From 4361a3515f5d7228a8daf601c794b85b5fe615f8 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 11 Oct 2026 17:25:52 -0500 Subject: [PATCH 01/30] docs(id): start phase 1, events, storage, crash safety, and the identity store [phase 1 start] --- ...-10-11T22-25-52Z_phase_1_events_storage.md | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 doc/2026-10-11T22-25-52Z_phase_1_events_storage/2026-10-11T22-25-52Z_phase_1_events_storage.md diff --git a/doc/2026-10-11T22-25-52Z_phase_1_events_storage/2026-10-11T22-25-52Z_phase_1_events_storage.md b/doc/2026-10-11T22-25-52Z_phase_1_events_storage/2026-10-11T22-25-52Z_phase_1_events_storage.md new file mode 100644 index 0000000000..38b1c6ff0e --- /dev/null +++ b/doc/2026-10-11T22-25-52Z_phase_1_events_storage/2026-10-11T22-25-52Z_phase_1_events_storage.md @@ -0,0 +1,44 @@ +# Phase 1: events, storage, crash safety, and the identity store + +- Plan: [phased plan](../../2026-10-11T11-08-42Z_design_remaining_work/plan-phases.md), section 6. +- Start commit: `baba0ea7` (origin/main, after PR #153, Phase 0). +- Base branch: `phase-1`. Track branches: `p1-chainext`, `p1-crash`, `p1-identity`, `p1-caps`, then `p1-store` and `p1-traits` after chainext merges. +- Storage decision (P1.1, decided): redb everywhere. Turso was measured and rejected; libsql is replaced. Record: [round 2 turso results](../2026-10-11T11-08-42Z_design_remaining_work/research-round2/turso/RESULTS.md). + +## Steps + +| Step | Track | Status | Commits | Tests added | Notes | +| --- | --- | --- | --- | --- | --- | +| P1.1 Storage decision record | lead | done | this file | none | redb everywhere; libsql replaced | +| P1.2 ChainExt | chainext | todo | | | | +| P1.3 Event store on redb | store | todo | | | after P1.2 | +| P1.4 Crash-safety gate | crash | todo | | | in-process fault model; corpus | +| P1.5 Waiting caps | caps | todo | | | | +| P1.6 Store traits over redb | traits | todo | | | after P1.3 | +| P1.7 Canonical CBOR vectors | chainext | todo | | | | +| P1.8 Ingest: verify with AnyHeader::decode, freeze forks | store | todo | | | after P1.3 | +| P1.9 Identity store on redb | identity | todo | | | libsql removed, AES-GCM values | +| P1.10 Crash gate for the identity store | crash | todo | | | after P1.4 and P1.9 | + +## Decisions + +- ChainExt on every event; no LogExt exists in p2panda-core 0.7.1. +- Waiting caps: 256 per author, 7 days, configurable per world. +- Identity values are encrypted with AES-256-GCM; data may be discarded at this phase. +- Store creation: a temporary file, a first commit, then a rename with a directory fsync. + +## Open questions + +- None yet. + +## Changes to the plan + +- None yet. + +## Review notes and regression tests + +- To be filled at each merge and at the end-of-phase review. + +## End + +- End commit and full test result: pending. From 3f04bdbf119e08860339559c0945d4554cabc344 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 11 Oct 2026 17:42:32 -0500 Subject: [PATCH 02/30] feat(id): identity store on redb with AES-GCM values [P1.9] The web identity store moves from libsql to redb. It has one table, keyed by client ID. Each value is a fresh 12-byte nonce followed by the AES-256-GCM ciphertext of the JSON record, with the client ID as the associated data. The key is the same HKDF output the libsql encryption key came from. - Cargo.toml: libsql 0.9 (encryption) leaves the web feature. redb 4.3 and aes-gcm 0.11 join it; both were already in the lock. - Cargo.lock: 762 to 686 packages, none added or upgraded. - The file is now .identity.redb. An old .identity.db is left in place and not read. The data may be discarded, so there is no migration. - Writes run on the blocking pool. update_name persists under the write lock, so the file keeps the order of in-memory updates. - Tests: round trip; the name is not visible in the stored value; every bit flip, truncation and moved value is refused; a wrong key and a tampered file fail the open; records survive a reopen; a second process is refused with a clear error; nonces never repeat over random writes. --- pkgs/id/Cargo.lock | 1194 ++++----------------------------- pkgs/id/Cargo.toml | 6 +- pkgs/id/src/commands/serve.rs | 2 +- pkgs/id/src/web/identity.rs | 610 +++++++++++++---- pkgs/id/src/web/mod.rs | 4 +- 5 files changed, 625 insertions(+), 1191 deletions(-) diff --git a/pkgs/id/Cargo.lock b/pkgs/id/Cargo.lock index 1a10a420f1..b91c4a811d 100644 --- a/pkgs/id/Cargo.lock +++ b/pkgs/id/Cargo.lock @@ -12,7 +12,7 @@ dependencies = [ "pin-project-lite", "rustc_version", "smol_str", - "sync_wrapper 1.0.2", + "sync_wrapper", "tokio", "tracing", ] @@ -117,18 +117,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "ahash" -version = "0.8.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" -dependencies = [ - "cfg-if", - "once_cell", - "version_check", - "zerocopy 0.8.62", -] - [[package]] name = "aho-corasick" version = "1.1.5" @@ -305,28 +293,6 @@ dependencies = [ "tokio", ] -[[package]] -name = "async-stream" -version = "0.3.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b5a71a6f37880a80d1d7f19efd781e4b5de42c88f0722cc13bcb6cc2cfe8476" -dependencies = [ - "async-stream-impl", - "futures-core", - "pin-project-lite", -] - -[[package]] -name = "async-stream-impl" -version = "0.3.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - [[package]] name = "async-trait" version = "0.1.92" @@ -371,7 +337,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "16e2cdb6d5ed835199484bb92bb8b3edd526effe995c61732580439c1a67e2e9" dependencies = [ "base64 0.22.1", - "http 1.5.0", + "http", "log", "url", ] @@ -406,52 +372,24 @@ dependencies = [ "pkg-config", ] -[[package]] -name = "axum" -version = "0.6.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b829e4e32b91e643de6eafe82b1d90675f5874230191a4ffbc1b336dec4d6bf" -dependencies = [ - "async-trait", - "axum-core 0.3.4", - "bitflags 1.3.2", - "bytes", - "futures-util", - "http 0.2.12", - "http-body 0.4.6", - "hyper 0.14.32", - "itoa", - "matchit 0.7.3", - "memchr", - "mime", - "percent-encoding", - "pin-project-lite", - "rustversion", - "serde", - "sync_wrapper 0.1.2", - "tower 0.4.13", - "tower-layer", - "tower-service", -] - [[package]] name = "axum" version = "0.8.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" dependencies = [ - "axum-core 0.5.6", + "axum-core", "base64 0.22.1", "bytes", "form_urlencoded", "futures-util", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "http-body-util", - "hyper 1.12.0", + "hyper", "hyper-util", "itoa", - "matchit 0.8.4", + "matchit", "memchr", "mime", "multer", @@ -462,32 +400,15 @@ dependencies = [ "serde_path_to_error", "serde_urlencoded", "sha1 0.10.7", - "sync_wrapper 1.0.2", + "sync_wrapper", "tokio", "tokio-tungstenite", - "tower 0.5.3", + "tower", "tower-layer", "tower-service", "tracing", ] -[[package]] -name = "axum-core" -version = "0.3.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "759fa577a247914fd3f7f76d62972792636412fbfd634cd452f6a385a74d2d2c" -dependencies = [ - "async-trait", - "bytes", - "futures-util", - "http 0.2.12", - "http-body 0.4.6", - "mime", - "rustversion", - "tower-layer", - "tower-service", -] - [[package]] name = "axum-core" version = "0.5.6" @@ -496,12 +417,12 @@ checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" dependencies = [ "bytes", "futures-core", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "http-body-util", "mime", "pin-project-lite", - "sync_wrapper 1.0.2", + "sync_wrapper", "tower-layer", "tower-service", "tracing", @@ -549,12 +470,6 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fd307490d624467aa6f74b0eabb77633d1f758a7b25f12bceb0b22e08d9726f6" -[[package]] -name = "base64" -version = "0.21.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567" - [[package]] name = "base64" version = "0.22.1" @@ -590,38 +505,6 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "597bb81c80a54b6a4381b23faba8d7774b144c94cbd1d6fe3f1329bd776554ab" -[[package]] -name = "bincode" -version = "1.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1f45e9417d87227c7a56d22e471c6206462cba514c7590c09aff4cf6d1ddcad" -dependencies = [ - "serde", -] - -[[package]] -name = "bindgen" -version = "0.66.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2b84e06fc203107bfbad243f4aba2af864eb7db3b1cf46ea0a023b0b433d2a7" -dependencies = [ - "bitflags 2.13.2", - "cexpr", - "clang-sys", - "lazy_static", - "lazycell", - "log", - "peeking_take_while", - "prettyplease", - "proc-macro2", - "quote", - "regex", - "rustc-hash 1.1.0", - "shlex 1.3.0", - "syn 2.0.119", - "which", -] - [[package]] name = "bit-set" version = "0.11.1" @@ -650,12 +533,6 @@ dependencies = [ "serde", ] -[[package]] -name = "bitflags" -version = "1.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" - [[package]] name = "bitflags" version = "2.13.2" @@ -703,15 +580,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "block-padding" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8894febbff9f758034a5b8e12d87918f56dfc64a8e1fe757d65e29041538d93" -dependencies = [ - "generic-array 0.14.7", -] - [[package]] name = "block-padding" version = "0.4.2" @@ -797,15 +665,6 @@ dependencies = [ "unicode-normalization", ] -[[package]] -name = "cbc" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6" -dependencies = [ - "cipher 0.4.4", -] - [[package]] name = "cbc" version = "0.2.1" @@ -824,7 +683,7 @@ dependencies = [ "find-msvc-tools", "jobserver", "libc", - "shlex 2.0.1", + "shlex", ] [[package]] @@ -833,15 +692,6 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c" -[[package]] -name = "cexpr" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766" -dependencies = [ - "nom", -] - [[package]] name = "cfg-if" version = "1.0.5" @@ -928,17 +778,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "clang-sys" -version = "1.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a" -dependencies = [ - "glob", - "libc", - "libloading", -] - [[package]] name = "clap" version = "4.6.7" @@ -1055,9 +894,9 @@ dependencies = [ "entities", "finl_unicode", "memchr-n", - "phf 0.14.0", - "phf_codegen 0.14.0", - "rustc-hash 2.1.3", + "phf", + "phf_codegen", + "rustc-hash", "smallvec", "typed-arena", ] @@ -1108,16 +947,6 @@ dependencies = [ "tracing", ] -[[package]] -name = "core-foundation" -version = "0.9.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" -dependencies = [ - "core-foundation-sys", - "libc", -] - [[package]] name = "core-foundation" version = "0.10.1" @@ -1224,7 +1053,7 @@ dependencies = [ "log", "pulley-interpreter", "regalloc2", - "rustc-hash 2.1.3", + "rustc-hash", "serde", "smallvec", "target-lexicon", @@ -1620,7 +1449,7 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" dependencies = [ - "bitflags 2.13.2", + "bitflags", "block2", "libc", "objc2", @@ -1899,24 +1728,6 @@ dependencies = [ "pin-project-lite", ] -[[package]] -name = "fallible-iterator" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4443176a9f2c162692bd3d352d745ef9413eec5782a80d8fd6f8a1ac692a07f7" - -[[package]] -name = "fallible-iterator" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" - -[[package]] -name = "fallible-streaming-iterator" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" - [[package]] name = "fastbloom" version = "0.17.0" @@ -2341,16 +2152,10 @@ checksum = "0bf7f043f89559805f8c7cacc432749b2fa0d0a0a9ee46ce47164ed5ba7f126c" dependencies = [ "fnv", "hashbrown 0.16.1", - "indexmap 2.14.2", + "indexmap", "stable_deref_trait", ] -[[package]] -name = "glob" -version = "0.3.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" - [[package]] name = "gloo-timers" version = "0.3.0" @@ -2385,25 +2190,6 @@ dependencies = [ "subtle", ] -[[package]] -name = "h2" -version = "0.3.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0beca50380b1fc32983fc1cb4587bfa4bb9e78fc259aad4a0032d2080309222d" -dependencies = [ - "bytes", - "fnv", - "futures-core", - "futures-sink", - "futures-util", - "http 0.2.12", - "indexmap 2.14.2", - "slab", - "tokio", - "tokio-util", - "tracing", -] - [[package]] name = "h2" version = "0.4.20" @@ -2415,8 +2201,8 @@ dependencies = [ "fnv", "futures-core", "futures-sink", - "http 1.5.0", - "indexmap 2.14.2", + "http", + "indexmap", "slab", "tokio", "tokio-util", @@ -2432,22 +2218,6 @@ dependencies = [ "byteorder", ] -[[package]] -name = "hashbrown" -version = "0.12.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" - -[[package]] -name = "hashbrown" -version = "0.14.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" -dependencies = [ - "ahash", - "allocator-api2", -] - [[package]] name = "hashbrown" version = "0.16.1" @@ -2468,15 +2238,6 @@ dependencies = [ "foldhash", ] -[[package]] -name = "hashlink" -version = "0.8.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8094feaf31ff591f651a2664fb9cfd92bba7a60ce3197265e9482ebe753c8f7" -dependencies = [ - "hashbrown 0.14.5", -] - [[package]] name = "heapless" version = "0.7.17" @@ -2593,17 +2354,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "http" -version = "0.2.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "601cbb57e577e2f5ef5be8e7b83f0f63994f25aa94d673e54a92d5c516d101f1" -dependencies = [ - "bytes", - "fnv", - "itoa", -] - [[package]] name = "http" version = "1.5.0" @@ -2614,17 +2364,6 @@ dependencies = [ "itoa", ] -[[package]] -name = "http-body" -version = "0.4.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ceab25649e9960c0311ea418d17bee82c0dcec1bd053b5f9a66e265a693bed2" -dependencies = [ - "bytes", - "http 0.2.12", - "pin-project-lite", -] - [[package]] name = "http-body" version = "1.1.0" @@ -2632,7 +2371,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" dependencies = [ "bytes", - "http 1.5.0", + "http", ] [[package]] @@ -2643,17 +2382,11 @@ checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" dependencies = [ "bytes", "futures-core", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "pin-project-lite", ] -[[package]] -name = "http-range-header" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "add0ab9360ddbd88cfeb3bd9574a1d85cfdfa14db10b3e21d3700dbc4328758f" - [[package]] name = "http-range-header" version = "0.4.2" @@ -2684,30 +2417,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "hyper" -version = "0.14.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41dfc780fdec9373c01bae43289ea34c972e40ee3c9f6b3c8801a35f35586ce7" -dependencies = [ - "bytes", - "futures-channel", - "futures-core", - "futures-util", - "h2 0.3.27", - "http 0.2.12", - "http-body 0.4.6", - "httparse", - "httpdate", - "itoa", - "pin-project-lite", - "socket2 0.5.10", - "tokio", - "tower-service", - "tracing", - "want", -] - [[package]] name = "hyper" version = "1.12.0" @@ -2718,9 +2427,9 @@ dependencies = [ "bytes", "futures-channel", "futures-core", - "h2 0.4.20", - "http 1.5.0", - "http-body 1.1.0", + "h2", + "http", + "http-body", "httparse", "httpdate", "itoa", @@ -2730,51 +2439,21 @@ dependencies = [ "want", ] -[[package]] -name = "hyper-rustls" -version = "0.25.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "399c78f9338483cb7e630c8474b07268983c6bd5acee012e4211f9f7bb21b070" -dependencies = [ - "futures-util", - "http 0.2.12", - "hyper 0.14.32", - "log", - "rustls 0.22.4", - "rustls-native-certs 0.7.3", - "rustls-pki-types", - "tokio", - "tokio-rustls 0.25.0", - "webpki-roots 0.26.11", -] - [[package]] name = "hyper-rustls" version = "0.27.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" dependencies = [ - "http 1.5.0", - "hyper 1.12.0", + "http", + "hyper", "hyper-util", - "rustls 0.23.45", + "rustls", "tokio", - "tokio-rustls 0.26.6", + "tokio-rustls", "tower-service", ] -[[package]] -name = "hyper-timeout" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbb958482e8c7be4bc3cf272a766a2b0bf1a6755e7a6ae777f017a31d11b13b1" -dependencies = [ - "hyper 0.14.32", - "pin-project-lite", - "tokio", - "tokio-io-timeout", -] - [[package]] name = "hyper-util" version = "0.1.21" @@ -2785,15 +2464,15 @@ dependencies = [ "bytes", "futures-channel", "futures-util", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "httparse", - "hyper 1.12.0", + "hyper", "ipnet", "libc", "percent-encoding", "pin-project-lite", - "socket2 0.6.5", + "socket2", "tokio", "tower-service", "tracing", @@ -2910,8 +2589,9 @@ dependencies = [ name = "id" version = "0.1.0" dependencies = [ + "aes-gcm 0.11.1", "anyhow", - "axum 0.8.9", + "axum", "base64 0.22.1", "clap", "comrak", @@ -2928,12 +2608,12 @@ dependencies = [ "iroh-mdns-address-lookup", "iroh-tickets", "libc", - "libsql", "mime_guess", "postcard", "proptest", "qrcode", "rand 0.10.3", + "redb 4.3.0", "rmp-serde", "rqrr", "russh", @@ -2947,7 +2627,7 @@ dependencies = [ "thiserror 2.0.21", "tokio", "tokio-tungstenite", - "tower 0.5.3", + "tower", "tower-http 0.7.1", "tracing", "tracing-subscriber", @@ -2993,9 +2673,9 @@ dependencies = [ "attohttpc", "bytes", "futures", - "http 1.5.0", + "http", "http-body-util", - "hyper 1.12.0", + "hyper", "hyper-util", "log", "rand 0.10.3", @@ -3004,16 +2684,6 @@ dependencies = [ "xmltree", ] -[[package]] -name = "indexmap" -version = "1.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" -dependencies = [ - "autocfg", - "hashbrown 0.12.3", -] - [[package]] name = "indexmap" version = "2.14.2" @@ -3032,7 +2702,6 @@ version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" dependencies = [ - "block-padding 0.3.3", "generic-array 0.14.7", ] @@ -3042,7 +2711,7 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4250ce6452e92010fdf7268ccc5d14faa80bb12fc741938534c58f16804e03c7" dependencies = [ - "block-padding 0.4.2", + "block-padding", "hybrid-array", ] @@ -3061,7 +2730,7 @@ version = "0.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4d40460c0ce33d6ce4b0630ad68ff63d6661961c48b6dba35e5a4d81cfb48222" dependencies = [ - "socket2 0.6.5", + "socket2", "widestring", "windows-registry", "windows-result", @@ -3090,7 +2759,7 @@ dependencies = [ "ed25519-dalek", "futures-util", "getrandom 0.4.3", - "http 1.5.0", + "http", "ipnet", "iroh-base", "iroh-dns", @@ -3109,8 +2778,8 @@ dependencies = [ "portmapper", "rand 0.10.3", "reqwest", - "rustc-hash 2.1.3", - "rustls 0.23.45", + "rustc-hash", + "rustls", "rustls-pki-types", "serde", "smallvec", @@ -3199,7 +2868,7 @@ dependencies = [ "n0-future", "portable-atomic", "rand 0.10.3", - "rustls 0.23.45", + "rustls", "simple-dns", "strum", "tokio", @@ -3259,7 +2928,7 @@ dependencies = [ "derive_more", "futures-concurrency", "hex", - "indexmap 2.14.2", + "indexmap", "iroh", "iroh-base", "iroh-metrics", @@ -3346,9 +3015,9 @@ dependencies = [ "data-encoding", "derive_more", "getrandom 0.4.3", - "http 1.5.0", + "http", "http-body-util", - "hyper 1.12.0", + "hyper", "hyper-util", "iroh-base", "iroh-dns", @@ -3363,18 +3032,18 @@ dependencies = [ "postcard", "rand 0.10.3", "reqwest", - "rustls 0.23.45", + "rustls", "rustls-pki-types", "serde", "serde_bytes", "strum", "tokio", - "tokio-rustls 0.26.6", + "tokio-rustls", "tokio-util", "tokio-websockets", "tracing", "url", - "webpki-roots 1.0.9", + "webpki-roots", "ws_stream_wasm", ] @@ -3420,7 +3089,7 @@ dependencies = [ "noq", "postcard", "rcgen", - "rustls 0.23.45", + "rustls", "serde", "smallvec", "tokio", @@ -3445,15 +3114,6 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" -[[package]] -name = "itertools" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba291022dbbd398a455acf126c1e341954079855bc60dfdda641363bd6922569" -dependencies = [ - "either", -] - [[package]] name = "itertools" version = "0.14.0" @@ -3590,12 +3250,6 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" -[[package]] -name = "lazycell" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55" - [[package]] name = "leb128fmt" version = "0.1.0" @@ -3608,16 +3262,6 @@ version = "0.2.190" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78" -[[package]] -name = "libloading" -version = "0.8.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" -dependencies = [ - "cfg-if", - "windows-link", -] - [[package]] name = "libm" version = "0.2.16" @@ -3625,150 +3269,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" [[package]] -name = "libsql" -version = "0.9.30" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30fe980ac5693ed1f3db490559fb578885e913a018df64af8a1a46e1959a78df" -dependencies = [ - "anyhow", - "async-stream", - "async-trait", - "base64 0.21.7", - "bincode", - "bitflags 2.13.2", - "bytes", - "chrono", - "crc32fast", - "fallible-iterator 0.3.0", - "futures", - "http 0.2.12", - "hyper 0.14.32", - "hyper-rustls 0.25.0", - "libsql-hrana", - "libsql-sqlite3-parser", - "libsql-sys", - "libsql_replication", - "parking_lot", - "serde", - "serde_json", - "thiserror 1.0.69", - "tokio", - "tokio-stream", - "tokio-util", - "tonic", - "tonic-web", - "tower 0.4.13", - "tower-http 0.4.4", - "tracing", - "uuid", - "zerocopy 0.7.35", -] - -[[package]] -name = "libsql-ffi" -version = "0.9.30" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0be1da6f123ceb2cd23f469883415cab9ee963286a85d61e22afb8b12e15e681" -dependencies = [ - "bindgen", - "cc", - "cmake", - "glob", -] - -[[package]] -name = "libsql-hrana" -version = "0.9.30" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3358538b52cfcf9af4fe7aeb57d6843aafed2e8af80807bd636fd1448e94ea7" -dependencies = [ - "base64 0.21.7", - "bytes", - "prost", - "serde", -] - -[[package]] -name = "libsql-rusqlite" -version = "0.9.30" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b646f94fc1d266e481c38a2d44d6d9d1be3ad04b56b90457acfb310dc450030e" -dependencies = [ - "bitflags 2.13.2", - "fallible-iterator 0.2.0", - "fallible-streaming-iterator", - "hashlink", - "libsql-ffi", - "smallvec", -] - -[[package]] -name = "libsql-sqlite3-parser" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "15a90128c708356af8f7d767c9ac2946692c9112b4f74f07b99a01a60680e413" -dependencies = [ - "bitflags 2.13.2", - "cc", - "fallible-iterator 0.3.0", - "indexmap 2.14.2", - "log", - "memchr", - "phf 0.11.3", - "phf_codegen 0.11.3", - "phf_shared 0.11.3", - "uncased", -] - -[[package]] -name = "libsql-sys" -version = "0.9.30" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90725458cc4461bc82f8f7983e80b002ea4f64b5184e1462f252d0dd74b122f5" -dependencies = [ - "bytes", - "libsql-ffi", - "libsql-rusqlite", - "once_cell", - "tracing", - "zerocopy 0.7.35", -] - -[[package]] -name = "libsql_replication" -version = "0.9.30" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3bba5c9b3a26aca06d70f6a3646ba341cf574a548355353fe135af524b1b77cc" -dependencies = [ - "aes 0.8.4", - "async-stream", - "async-trait", - "bytes", - "cbc 0.1.2", - "libsql-rusqlite", - "libsql-sys", - "parking_lot", - "prost", - "serde", - "thiserror 1.0.69", - "tokio", - "tokio-stream", - "tokio-util", - "tonic", - "tracing", - "uuid", - "zerocopy 0.7.35", -] - -[[package]] -name = "linux-raw-sys" -version = "0.4.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" - -[[package]] -name = "linux-raw-sys" -version = "0.12.1" +name = "linux-raw-sys" +version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" @@ -3879,12 +3381,6 @@ dependencies = [ "regex-automata", ] -[[package]] -name = "matchit" -version = "0.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e7465ac9959cc2b1404e8e2367b43684a6d13790fe23056cc8c6c5a6b7bcb94" - [[package]] name = "matchit" version = "0.8.4" @@ -3919,7 +3415,7 @@ version = "0.6.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "57804b2c9b69967f1536a56f86297e367a33b19e98852ed624b84551cdbc0d90" dependencies = [ - "rustix 1.1.5", + "rustix", ] [[package]] @@ -3999,7 +3495,7 @@ dependencies = [ "bytes", "encoding_rs", "futures-util", - "http 1.5.0", + "http", "httparse", "memchr", "mime", @@ -4028,14 +3524,14 @@ dependencies = [ "ndk-context", "rand 0.10.3", "reqwest", - "rustc-hash 2.1.3", - "rustls 0.23.45", + "rustc-hash", + "rustls", "simple-dns", "system-configuration", "tokio", - "tokio-rustls 0.26.6", + "tokio-rustls", "tracing", - "webpki-roots 1.0.9", + "webpki-roots", ] [[package]] @@ -4182,7 +3678,7 @@ version = "0.31.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e2288fcb784eb3defd5fb16f4c4160d5f477de192eac730f43e1d11c24d9a007" dependencies = [ - "bitflags 2.13.2", + "bitflags", "libc", "log", "netlink-packet-core 0.8.2", @@ -4194,11 +3690,11 @@ version = "0.33.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "59d48ffc8b73a506e1ff0878528c72668f2bfbc3d875b6be890a96be5d0d5576" dependencies = [ - "bitflags 2.13.2", + "bitflags", "libc", "log", "netlink-packet-core 0.9.0", - "zerocopy 0.8.62", + "zerocopy", ] [[package]] @@ -4267,7 +3763,7 @@ dependencies = [ "objc2-system-configuration", "pin-project-lite", "serde", - "socket2 0.6.5", + "socket2", "time", "tokio", "tokio-util", @@ -4293,7 +3789,7 @@ version = "0.31.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" dependencies = [ - "bitflags 2.13.2", + "bitflags", "cfg-if", "cfg_aliases", "libc", @@ -4321,9 +3817,9 @@ dependencies = [ "noq-proto", "noq-udp", "pin-project-lite", - "rustc-hash 2.1.3", - "rustls 0.23.45", - "socket2 0.6.5", + "rustc-hash", + "rustls", + "socket2", "thiserror 2.0.21", "tokio", "tokio-stream", @@ -4348,8 +3844,8 @@ dependencies = [ "rand 0.10.3", "rand_pcg", "ring", - "rustc-hash 2.1.3", - "rustls 0.23.45", + "rustc-hash", + "rustls", "rustls-pki-types", "rustls-platform-verifier", "slab", @@ -4368,7 +3864,7 @@ checksum = "4dc50afea61aff926e150a36c31f06094608848e114a3fe667d76ec233163b1c" dependencies = [ "cfg_aliases", "libc", - "socket2 0.6.5", + "socket2", "tracing", "windows-sys 0.61.2", ] @@ -4465,7 +3961,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" dependencies = [ - "bitflags 2.13.2", + "bitflags", "block2", "dispatch2", "libc", @@ -4478,7 +3974,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c71e34919aba0d701380d911702455038a8a3587467fe0141d6a71501e7ffe48" dependencies = [ - "bitflags 2.13.2", + "bitflags", "objc2", "objc2-core-foundation", "objc2-foundation", @@ -4498,7 +3994,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" dependencies = [ - "bitflags 2.13.2", + "bitflags", "block2", "libc", "objc2", @@ -4511,7 +4007,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "709fe137109bd1e8b5a99390f77a7d8b2961dafc1a1c5db8f2e60329ad6d895a" dependencies = [ - "bitflags 2.13.2", + "bitflags", "objc2", "objc2-core-foundation", ] @@ -4532,7 +4028,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7216bd11cbda54ccabcab84d523dc93b858ec75ecfb3a7d89513fa22464da396" dependencies = [ - "bitflags 2.13.2", + "bitflags", "dispatch2", "libc", "objc2", @@ -4548,7 +4044,7 @@ checksum = "271638cd5fa9cca89c4c304675ca658efc4e64a66c716b7cfe1afb4b9611dbbc" dependencies = [ "crc32fast", "hashbrown 0.16.1", - "indexmap 2.14.2", + "indexmap", "memchr", ] @@ -4583,12 +4079,6 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" -[[package]] -name = "openssl-probe" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d05e27ee213611ffe7d6348b942e8f942b37114c00cc03cec254295a4a17852e" - [[package]] name = "openssl-probe" version = "0.2.1" @@ -4730,12 +4220,6 @@ dependencies = [ "hmac 0.13.0", ] -[[package]] -name = "peeking_take_while" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19b17cddbe7ec3f8bc800887bab5e717348c95ea2ca0b1bf0837fb964dc67099" - [[package]] name = "pem" version = "4.0.0" @@ -4781,53 +4265,24 @@ dependencies = [ "ctutils", ] -[[package]] -name = "phf" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078" -dependencies = [ - "phf_shared 0.11.3", -] - [[package]] name = "phf" version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "010378780309880b08997fae13be7834dba947d36393bd372f2b1556deb2a2f6" dependencies = [ - "phf_shared 0.14.0", + "phf_shared", "serde", ] -[[package]] -name = "phf_codegen" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aef8048c789fa5e851558d709946d6d79a8ff88c0440c587967f8e94bfb1216a" -dependencies = [ - "phf_generator 0.11.3", - "phf_shared 0.11.3", -] - [[package]] name = "phf_codegen" version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "41b585a510fb76fdebead6897982ef2a03a21d8e6cbcca904999742a4afc6ffe" dependencies = [ - "phf_generator 0.14.0", - "phf_shared 0.14.0", -] - -[[package]] -name = "phf_generator" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d" -dependencies = [ - "phf_shared 0.11.3", - "rand 0.8.8", + "phf_generator", + "phf_shared", ] [[package]] @@ -4837,17 +4292,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aeb62e0959d5a1bebc965f4d15d9e2b7cea002b6b0f5ba8cde6cc26738467100" dependencies = [ "fastrand", - "phf_shared 0.14.0", -] - -[[package]] -name = "phf_shared" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5" -dependencies = [ - "siphasher", - "uncased", + "phf_shared", ] [[package]] @@ -4903,7 +4348,7 @@ checksum = "63d440a804ec8d6fafbb6b84471e013286658d373248927692ab3366686220ca" dependencies = [ "aes 0.9.3", "aes-gcm 0.11.1", - "cbc 0.2.1", + "cbc", "der 0.8.2", "pbkdf2", "rand_core 0.10.1", @@ -4937,7 +4382,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2896bade328c13f7042a297ea5ac5b0951f6cf989dea5f32c2fd98da398195cb" dependencies = [ "base64 0.23.1", - "indexmap 2.14.2", + "indexmap", "quick-xml", "serde", "time", @@ -5018,7 +4463,7 @@ dependencies = [ "rand 0.10.3", "serde", "smallvec", - "socket2 0.6.5", + "socket2", "time", "tokio", "tokio-util", @@ -5083,17 +4528,7 @@ version = "0.2.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" dependencies = [ - "zerocopy 0.8.62", -] - -[[package]] -name = "prettyplease" -version = "0.2.37" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" -dependencies = [ - "proc-macro2", - "syn 2.0.119", + "zerocopy", ] [[package]] @@ -5190,7 +4625,7 @@ checksum = "b8530004ccb15eae51c7e40009fbe317f341f804db54dc033eec1c50be28cfa0" dependencies = [ "bit-set", "bit-vec 0.10.1", - "bitflags 2.13.2", + "bitflags", "chacha20 0.10.2", "core_detect", "num-traits", @@ -5202,29 +4637,6 @@ dependencies = [ "unarray", ] -[[package]] -name = "prost" -version = "0.12.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "deb1435c188b76130da55f17a466d252ff7b1418b2ad3e037d127b94e3411f29" -dependencies = [ - "bytes", - "prost-derive", -] - -[[package]] -name = "prost-derive" -version = "0.12.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81bddcdb20abf9501610992b6759a4c888aef7d1a7247ef75e2404275ac24af1" -dependencies = [ - "anyhow", - "itertools 0.12.1", - "proc-macro2", - "quote", - "syn 2.0.119", -] - [[package]] name = "pulley-interpreter" version = "43.0.2" @@ -5300,24 +4712,13 @@ dependencies = [ "nibble_vec", ] -[[package]] -name = "rand" -version = "0.8.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" -dependencies = [ - "libc", - "rand_chacha 0.3.1", - "rand_core 0.6.4", -] - [[package]] name = "rand" version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" dependencies = [ - "rand_chacha 0.9.0", + "rand_chacha", "rand_core 0.9.5", ] @@ -5332,16 +4733,6 @@ dependencies = [ "rand_core 0.10.1", ] -[[package]] -name = "rand_chacha" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" -dependencies = [ - "ppv-lite86", - "rand_core 0.6.4", -] - [[package]] name = "rand_chacha" version = "0.9.0" @@ -5445,7 +4836,7 @@ version = "0.5.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" dependencies = [ - "bitflags 2.13.2", + "bitflags", ] [[package]] @@ -5476,7 +4867,7 @@ checksum = "d9dd7ab4af0363d5ccfd2838d782a28196cf32a5cc2e4fe3c5dc83f2be588b8b" dependencies = [ "cfg-if", "libc", - "rustix 1.1.5", + "rustix", "windows", ] @@ -5490,22 +4881,10 @@ dependencies = [ "bumpalo", "hashbrown 0.17.1", "log", - "rustc-hash 2.1.3", + "rustc-hash", "smallvec", ] -[[package]] -name = "regex" -version = "1.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" -dependencies = [ - "aho-corasick", - "memchr", - "regex-automata", - "regex-syntax", -] - [[package]] name = "regex-automata" version = "0.4.18" @@ -5533,24 +4912,24 @@ dependencies = [ "bytes", "futures-core", "futures-util", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "http-body-util", - "hyper 1.12.0", - "hyper-rustls 0.27.10", + "hyper", + "hyper-rustls", "hyper-util", "js-sys", "log", "percent-encoding", "pin-project-lite", - "rustls 0.23.45", + "rustls", "rustls-pki-types", "rustls-platform-verifier", - "sync_wrapper 1.0.2", + "sync_wrapper", "tokio", - "tokio-rustls 0.26.6", + "tokio-rustls", "tokio-util", - "tower 0.5.3", + "tower", "tower-http 0.6.11", "tower-service", "url", @@ -5640,11 +5019,11 @@ checksum = "ba61e87b9ec9a39a59a6bbed4c0b8ff7fb07073405b24a767a1f2c8560ac8f58" dependencies = [ "aes 0.9.3", "aws-lc-rs", - "bitflags 2.13.2", - "block-padding 0.4.2", + "bitflags", + "block-padding", "byteorder", "bytes", - "cbc 0.2.1", + "cbc", "cipher 0.5.2", "crypto-bigint 0.7.5", "ctr 0.10.1", @@ -5762,12 +5141,6 @@ dependencies = [ "walkdir", ] -[[package]] -name = "rustc-hash" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" - [[package]] name = "rustc-hash" version = "2.1.3" @@ -5792,46 +5165,19 @@ dependencies = [ "nom", ] -[[package]] -name = "rustix" -version = "0.38.44" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" -dependencies = [ - "bitflags 2.13.2", - "errno", - "libc", - "linux-raw-sys 0.4.15", - "windows-sys 0.59.0", -] - [[package]] name = "rustix" version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" dependencies = [ - "bitflags 2.13.2", + "bitflags", "errno", "libc", - "linux-raw-sys 0.12.1", + "linux-raw-sys", "windows-sys 0.61.2", ] -[[package]] -name = "rustls" -version = "0.22.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf4ef73721ac7bcd79b2b315da7779d8fc09718c6b3d2d1b2d94850eb8c18432" -dependencies = [ - "log", - "ring", - "rustls-pki-types", - "rustls-webpki 0.102.8", - "subtle", - "zeroize", -] - [[package]] name = "rustls" version = "0.23.45" @@ -5842,43 +5188,21 @@ dependencies = [ "once_cell", "ring", "rustls-pki-types", - "rustls-webpki 0.103.15", + "rustls-webpki", "subtle", "zeroize", ] -[[package]] -name = "rustls-native-certs" -version = "0.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5bfb394eeed242e909609f56089eecfe5fda225042e8b171791b9c95f5931e5" -dependencies = [ - "openssl-probe 0.1.6", - "rustls-pemfile", - "rustls-pki-types", - "schannel", - "security-framework 2.11.1", -] - [[package]] name = "rustls-native-certs" version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d" dependencies = [ - "openssl-probe 0.2.1", + "openssl-probe", "rustls-pki-types", "schannel", - "security-framework 3.7.0", -] - -[[package]] -name = "rustls-pemfile" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dce314e5fee3f39953d46bb63bb8a46d40c2f8fb7cc5a3b6cab2bde9721d6e50" -dependencies = [ - "rustls-pki-types", + "security-framework", ] [[package]] @@ -5897,16 +5221,16 @@ version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" dependencies = [ - "core-foundation 0.10.1", + "core-foundation", "core-foundation-sys", "jni 0.22.4", "log", "once_cell", - "rustls 0.23.45", - "rustls-native-certs 0.8.4", + "rustls", + "rustls-native-certs", "rustls-platform-verifier-android", - "rustls-webpki 0.103.15", - "security-framework 3.7.0", + "rustls-webpki", + "security-framework", "security-framework-sys", "webpki-root-certs", "windows-sys 0.61.2", @@ -5918,17 +5242,6 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" -[[package]] -name = "rustls-webpki" -version = "0.102.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "64ca1bc8749bd4cf37b5ce386cc146580777b4e8572c7b97baf22c83f444bee9" -dependencies = [ - "ring", - "rustls-pki-types", - "untrusted 0.9.0", -] - [[package]] name = "rustls-webpki" version = "0.103.15" @@ -5964,7 +5277,7 @@ version = "18.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "53f6a737db68eb1a8ccff86b584b2fc13eca6a7bb6f78ebc7c529547e3ab9684" dependencies = [ - "bitflags 2.13.2", + "bitflags", "cfg-if", "clipboard-win", "home", @@ -6064,27 +5377,14 @@ dependencies = [ "zeroize", ] -[[package]] -name = "security-framework" -version = "2.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02" -dependencies = [ - "bitflags 2.13.2", - "core-foundation 0.9.4", - "core-foundation-sys", - "libc", - "security-framework-sys", -] - [[package]] name = "security-framework" version = "3.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" dependencies = [ - "bitflags 2.13.2", - "core-foundation 0.10.1", + "bitflags", + "core-foundation", "core-foundation-sys", "libc", "security-framework-sys", @@ -6309,12 +5609,6 @@ dependencies = [ "lazy_static", ] -[[package]] -name = "shlex" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" - [[package]] name = "shlex" version = "2.0.1" @@ -6369,7 +5663,7 @@ version = "0.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2b6f884fa9a8d48101774bfbd3aeb81e968dd22cffd19a372da69f183db22c1a" dependencies = [ - "bitflags 2.13.2", + "bitflags", ] [[package]] @@ -6399,16 +5693,6 @@ version = "0.1.24" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fad6c857cbab2627dcf01ec85a623ca4e7dcb5691cbaa3d7fb7653671f0d09c9" -[[package]] -name = "socket2" -version = "0.5.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e22376abed350d73dd1cd119b57ffccad95b4e585a7cda43e286245ce23c0678" -dependencies = [ - "libc", - "windows-sys 0.52.0", -] - [[package]] name = "socket2" version = "0.6.5" @@ -6574,7 +5858,7 @@ dependencies = [ "acto", "hickory-proto", "rand 0.10.3", - "socket2 0.6.5", + "socket2", "thiserror 2.0.21", "tokio", "tracing", @@ -6624,12 +5908,6 @@ dependencies = [ "syn 1.0.109", ] -[[package]] -name = "sync_wrapper" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2047c6ded9c721764247e62cd3b03c09ffc529b2ba5b10ec482ae507a4a70160" - [[package]] name = "sync_wrapper" version = "1.0.2" @@ -6667,8 +5945,8 @@ version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "501336eb7ba9e417300a6a0fa985721065467aa83a6dcf0422a8e43e4c0328fa" dependencies = [ - "bitflags 2.13.2", - "core-foundation 0.10.1", + "bitflags", + "core-foundation", "system-configuration-sys", ] @@ -6697,7 +5975,7 @@ dependencies = [ "fastrand", "getrandom 0.4.3", "once_cell", - "rustix 1.1.5", + "rustix", "windows-sys 0.61.2", ] @@ -6818,21 +6096,11 @@ dependencies = [ "parking_lot", "pin-project-lite", "signal-hook-registry", - "socket2 0.6.5", + "socket2", "tokio-macros", "windows-sys 0.61.2", ] -[[package]] -name = "tokio-io-timeout" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bd86198d9ee903fedd2f9a2e72014287c0d9167e4ae43b5853007205dda1b76" -dependencies = [ - "pin-project-lite", - "tokio", -] - [[package]] name = "tokio-macros" version = "2.7.2" @@ -6844,24 +6112,13 @@ dependencies = [ "syn 3.0.8", ] -[[package]] -name = "tokio-rustls" -version = "0.25.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "775e0c0f0adb3a2f22a00c4745d728b479985fc15ee7ca6a2608388c5569860f" -dependencies = [ - "rustls 0.22.4", - "rustls-pki-types", - "tokio", -] - [[package]] name = "tokio-rustls" version = "0.26.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" dependencies = [ - "rustls 0.23.45", + "rustls", "tokio", ] @@ -6915,7 +6172,7 @@ dependencies = [ "futures-core", "futures-sink", "getrandom 0.4.3", - "http 1.5.0", + "http", "httparse", "rand 0.10.3", "ring", @@ -6923,7 +6180,7 @@ dependencies = [ "sha1_smol", "simdutf8", "tokio", - "tokio-rustls 0.26.6", + "tokio-rustls", "tokio-util", ] @@ -6942,7 +6199,7 @@ version = "0.25.17+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3641d5bbb5349a79e1020a242d251efbc546ad8048d133958323ce9c40a9c9c" dependencies = [ - "indexmap 2.14.2", + "indexmap", "toml_datetime", "toml_parser", "winnow", @@ -6957,73 +6214,6 @@ dependencies = [ "winnow", ] -[[package]] -name = "tonic" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76c4eb7a4e9ef9d4763600161f12f5070b92a578e1b634db88a6887844c91a13" -dependencies = [ - "async-stream", - "async-trait", - "axum 0.6.20", - "base64 0.21.7", - "bytes", - "h2 0.3.27", - "http 0.2.12", - "http-body 0.4.6", - "hyper 0.14.32", - "hyper-timeout", - "percent-encoding", - "pin-project", - "prost", - "tokio", - "tokio-stream", - "tower 0.4.13", - "tower-layer", - "tower-service", - "tracing", -] - -[[package]] -name = "tonic-web" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc3b0e1cedbf19fdfb78ef3d672cb9928e0a91a9cb4629cc0c916e8cff8aaaa1" -dependencies = [ - "base64 0.21.7", - "bytes", - "http 0.2.12", - "http-body 0.4.6", - "hyper 0.14.32", - "pin-project", - "tokio-stream", - "tonic", - "tower-http 0.4.4", - "tower-layer", - "tower-service", - "tracing", -] - -[[package]] -name = "tower" -version = "0.4.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8fa9be0de6cf49e536ce1851f987bd21a43b771b09473c3549a6c853db37c1c" -dependencies = [ - "futures-core", - "futures-util", - "indexmap 1.9.3", - "pin-project", - "pin-project-lite", - "rand 0.8.8", - "slab", - "tokio", - "tokio-util", - "tower-layer", - "tower-service", - "tracing", -] - [[package]] name = "tower" version = "0.5.3" @@ -7033,46 +6223,26 @@ dependencies = [ "futures-core", "futures-util", "pin-project-lite", - "sync_wrapper 1.0.2", + "sync_wrapper", "tokio", "tower-layer", "tower-service", "tracing", ] -[[package]] -name = "tower-http" -version = "0.4.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61c5bb1d698276a2443e5ecfabc1008bf15a36c12e6a7176e7bf089ea9131140" -dependencies = [ - "bitflags 2.13.2", - "bytes", - "futures-core", - "futures-util", - "http 0.2.12", - "http-body 0.4.6", - "http-range-header 0.3.1", - "pin-project-lite", - "tower 0.4.13", - "tower-layer", - "tower-service", - "tracing", -] - [[package]] name = "tower-http" version = "0.6.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" dependencies = [ - "bitflags 2.13.2", + "bitflags", "bytes", "futures-util", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "pin-project-lite", - "tower 0.5.3", + "tower", "tower-layer", "tower-service", "url", @@ -7085,14 +6255,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "08a05a66a4fdd61cbbe0a1d755ffe0ca6aba159dd4820936a0ff8a8278245b9c" dependencies = [ "async-compression", - "bitflags 2.13.2", + "bitflags", "bytes", "futures-core", "futures-util", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "http-body-util", - "http-range-header 0.4.2", + "http-range-header", "httpdate", "mime", "mime_guess", @@ -7192,7 +6362,7 @@ checksum = "6c01152af293afb9c7c2a57e4b559c5620b421f6d133261c60dd2d0cdb38e6b8" dependencies = [ "bytes", "data-encoding", - "http 1.5.0", + "http", "httparse", "log", "rand 0.9.5", @@ -7218,15 +6388,6 @@ version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" -[[package]] -name = "uncased" -version = "0.9.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e1b88fcfe09e89d3866a5c11019378088af2d24c3fbd4f0543f96b479ec90697" -dependencies = [ - "version_check", -] - [[package]] name = "unicase" version = "2.10.0" @@ -7329,18 +6490,6 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" -[[package]] -name = "uuid" -version = "1.28.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7cc1186384beb7dd8eedea376413fd654937285ea6c9cfbb928dc3043ea4b606" -dependencies = [ - "getrandom 0.4.3", - "js-sys", - "serde_core", - "wasm-bindgen", -] - [[package]] name = "valuable" version = "0.1.1" @@ -7512,9 +6661,9 @@ version = "0.245.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4f08c9adee0428b7bddf3890fc27e015ac4b761cc608c822667102b8bfd6995e" dependencies = [ - "bitflags 2.13.2", + "bitflags", "hashbrown 0.16.1", - "indexmap 2.14.2", + "indexmap", "semver", "serde", ] @@ -7525,8 +6674,8 @@ version = "0.261.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4f20f20e44f7e8aeb6744823ea9d869ede51e51be4fdaedede2852282e54d2d8" dependencies = [ - "bitflags 2.13.2", - "indexmap 2.14.2", + "bitflags", + "indexmap", "semver", ] @@ -7549,7 +6698,7 @@ checksum = "efb1ed5899dde98357cfdcf647a4614498798719793898245b4b34e663addabf" dependencies = [ "addr2line", "async-trait", - "bitflags 2.13.2", + "bitflags", "bumpalo", "cc", "cfg-if", @@ -7561,7 +6710,7 @@ dependencies = [ "once_cell", "postcard", "pulley-interpreter", - "rustix 1.1.5", + "rustix", "serde", "serde_derive", "smallvec", @@ -7590,7 +6739,7 @@ dependencies = [ "cranelift-entity", "gimli", "hashbrown 0.16.1", - "indexmap 2.14.2", + "indexmap", "log", "object", "postcard", @@ -7629,7 +6778,7 @@ dependencies = [ "cranelift-frontend", "cranelift-native", "gimli", - "itertools 0.14.0", + "itertools", "log", "object", "pulley-interpreter", @@ -7652,7 +6801,7 @@ dependencies = [ "cc", "cfg-if", "libc", - "rustix 1.1.5", + "rustix", "wasmtime-environ", "wasmtime-internal-versioned-export-macros", "windows-sys 0.61.2", @@ -7756,15 +6905,6 @@ dependencies = [ "rustls-pki-types", ] -[[package]] -name = "webpki-roots" -version = "0.26.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" -dependencies = [ - "webpki-roots 1.0.9", -] - [[package]] name = "webpki-roots" version = "1.0.9" @@ -7774,18 +6914,6 @@ dependencies = [ "rustls-pki-types", ] -[[package]] -name = "which" -version = "4.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87ba24419a2078cd2b0f2ede2691b6c66d8e47836da3b6db8265ebad47afbfc7" -dependencies = [ - "either", - "home", - "once_cell", - "rustix 0.38.44", -] - [[package]] name = "widestring" version = "1.2.1" @@ -7953,15 +7081,6 @@ dependencies = [ "windows-targets 0.52.6", ] -[[package]] -name = "windows-sys" -version = "0.59.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" -dependencies = [ - "windows-targets 0.52.6", -] - [[package]] name = "windows-sys" version = "0.61.2" @@ -8246,34 +7365,13 @@ dependencies = [ "synstructure 0.14.0", ] -[[package]] -name = "zerocopy" -version = "0.7.35" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b9b4fd18abc82b8136838da5d50bae7bdea537c574d8dc1a34ed098d6c166f0" -dependencies = [ - "byteorder", - "zerocopy-derive 0.7.35", -] - [[package]] name = "zerocopy" version = "0.8.62" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "86502bf56ac7c77571a32e2647bb2a15894565e981fb2a48d7bde2d91c965a9d" dependencies = [ - "zerocopy-derive 0.8.62", -] - -[[package]] -name = "zerocopy-derive" -version = "0.7.35" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", + "zerocopy-derive", ] [[package]] diff --git a/pkgs/id/Cargo.toml b/pkgs/id/Cargo.toml index 87c1a3f116..42252931b4 100644 --- a/pkgs/id/Cargo.toml +++ b/pkgs/id/Cargo.toml @@ -29,7 +29,8 @@ web = [ "dep:rmp-serde", "dep:comrak", "dep:urlencoding", - "dep:libsql", + "dep:redb", + "dep:aes-gcm", "dep:base64", "dep:hkdf", "dep:sha2", @@ -75,7 +76,8 @@ futures = { version = "0.3.32", optional = true } rmp-serde = { version = "1", optional = true } comrak = { version = "0.56", default-features = false, optional = true } urlencoding = { version = "2", optional = true } -libsql = { version = "0.9", features = ["encryption"], optional = true } +redb = { version = "4.3", optional = true } +aes-gcm = { version = "0.11", default-features = false, features = ["aes", "alloc"], optional = true } base64 = { version = "0.22", optional = true } qrcode = { version = "0.14.1", default-features = false, optional = true } hkdf = { version = "0.13", optional = true } diff --git a/pkgs/id/src/commands/serve.rs b/pkgs/id/src/commands/serve.rs index a71a99f93c..64999e39db 100644 --- a/pkgs/id/src/commands/serve.rs +++ b/pkgs/id/src/commands/serve.rs @@ -1030,7 +1030,7 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { // Start web server now that the lock file is written #[cfg(feature = "web")] let _web_handle = if let Some(listener) = web_listener { - let identity_db_path = std::path::Path::new(KEY_FILE).with_file_name(".identity.db"); + let identity_db_path = std::path::Path::new(KEY_FILE).with_file_name(".identity.redb"); let web_router = crate::web::web_router( store_handle.clone(), Some(peer_discovery.clone()), diff --git a/pkgs/id/src/web/identity.rs b/pkgs/id/src/web/identity.rs index 16889f9b0f..e696ec52fa 100644 --- a/pkgs/id/src/web/identity.rs +++ b/pkgs/id/src/web/identity.rs @@ -28,18 +28,29 @@ //! it to sign/verify tokens. Tokens are base64url-encoded for safe use //! in query parameters and `localStorage`. //! +//! # Persistence +//! +//! With a database path, records live in a redb file with one table, keyed by +//! client ID. Each value is `nonce (12 bytes) || AES-256-GCM ciphertext` of the +//! JSON record. The client ID is the associated data, so a value moved under +//! another key fails to authenticate. The AES key is derived from the server's +//! secret key with HKDF-SHA256. +//! //! # Thread Safety //! //! The [`IdentityStore`] is designed for concurrent access using `Arc>` //! internally. Clone it freely across handlers. use std::collections::HashMap; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use std::sync::Arc; use std::time::{SystemTime, UNIX_EPOCH}; +use aes_gcm::aead::{Aead, Payload}; +use aes_gcm::{Aes256Gcm, KeyInit}; use ed25519_dalek::{Signer, SigningKey, VerifyingKey}; use hkdf::Hkdf; +use redb::{Database, DatabaseError, ReadableDatabase, ReadableTable, TableDefinition}; use serde::{Deserialize, Serialize}; use sha2::Sha256; use tokio::sync::RwLock; @@ -73,10 +84,10 @@ struct TokenPayload { created_at: u64, } -/// In-memory store for client identities, optionally backed by encrypted `SQLite`. +/// In-memory store for client identities, optionally backed by an encrypted redb file. /// /// Keyed by `client_id` (a hex string). Thread-safe via `Arc>`. -/// When backed by a database, mutations are written through to `SQLite` for +/// When backed by a database, mutations are written through to the redb file for /// persistence across server restarts. #[derive(Clone)] pub struct IdentityStore { @@ -89,8 +100,8 @@ pub struct IdentityStore { signing_key: Arc, /// Ed25519 verifying key (derived from signing key, used to verify tokens). verifying_key: VerifyingKey, - /// `SQLite` database for persistent storage (`None` for ephemeral/test mode). - db: Option>, + /// Encrypted redb file for persistent storage (`None` for ephemeral/test mode). + db: Option>, } impl std::fmt::Debug for IdentityStore { @@ -104,16 +115,17 @@ impl std::fmt::Debug for IdentityStore { } impl IdentityStore { - /// Create a new identity store backed by an encrypted `SQLite` database. + /// Create a new identity store backed by an encrypted redb file. /// - /// Derives a signing key and DB encryption key from the given secret key - /// bytes using HKDF-SHA256. The DB file is encrypted at rest using AES-256-GCM. - /// All existing identities are loaded into memory on startup. + /// Derives a signing key and an encryption key from the given secret key + /// bytes using HKDF-SHA256. Record values are encrypted with AES-256-GCM. + /// All existing identities are authenticated and loaded into memory on + /// startup. A record that fails authentication fails the open. /// /// # Arguments /// /// * `secret_key` - 32-byte secret key (from iroh `SecretKey::to_bytes()`) - /// * `db_path` - Path for the `SQLite` database file (e.g., `.identity.db`) + /// * `db_path` - Path for the redb file (e.g., `.identity.redb`) pub async fn new(secret_key: [u8; 32], db_path: PathBuf) -> anyhow::Result { // Derive signing key via HKDF-SHA256 let hk = Hkdf::::new(None, &secret_key); @@ -123,70 +135,23 @@ impl IdentityStore { let signing_key = SigningKey::from_bytes(&signing_bytes); let verifying_key = signing_key.verifying_key(); - // Derive DB encryption key via HKDF-SHA256 + // Derive the record encryption key via HKDF-SHA256 let mut enc_bytes = [0u8; 32]; hk.expand(b"id-identity-encryption", &mut enc_bytes) .map_err(|_e| anyhow::anyhow!("HKDF expand failed for encryption key"))?; - let hex_key = hex_encode(&enc_bytes); - - // Open encrypted SQLite database - let db_path_str = db_path.display().to_string(); - let uri = format!("file:{db_path_str}?cipher=aes256gcm&hexkey={hex_key}"); - let db = libsql::Builder::new_local(uri) - .build() - .await - .map_err(|e| anyhow::anyhow!("Failed to open identity database: {e}"))?; - let conn = db - .connect() - .map_err(|e| anyhow::anyhow!("Failed to connect to identity database: {e}"))?; - - // Create table if it doesn't exist - conn.execute( - "CREATE TABLE IF NOT EXISTS identities ( - client_id TEXT PRIMARY KEY, - name TEXT, - created_at INTEGER NOT NULL, - updated_at INTEGER NOT NULL - )", - (), - ) - .await - .map_err(|e| anyhow::anyhow!("Failed to create identities table: {e}"))?; - - // Load existing identities into memory - let mut clients = HashMap::new(); - let mut name_watchers_map = HashMap::new(); - let mut rows = conn - .query( - "SELECT client_id, name, created_at, updated_at FROM identities", - (), - ) - .await - .map_err(|e| anyhow::anyhow!("Failed to query identities: {e}"))?; - - while let Some(row) = rows - .next() - .await - .map_err(|e| anyhow::anyhow!("Failed to read identity row: {e}"))? - { - let client_id = db_text(&row, 0)?; - let name = db_opt_text(&row, 1)?; - let created_at = db_u64(&row, 2)?; - let updated_at = db_u64(&row, 3)?; - - let identity = ClientIdentity { - client_id: client_id.clone(), - name: name.clone(), - created_at, - updated_at, - }; - let (tx, _rx) = watch::channel(name); - name_watchers_map.insert(client_id.clone(), tx); - clients.insert(client_id, identity); + // Open the file and load every record. redb is synchronous, so this runs + // on the blocking pool. + let (db, identities) = run_blocking(move || IdentityDb::open(&db_path, &enc_bytes)).await?; + + let count = identities.len(); + let mut clients = HashMap::with_capacity(count); + let mut name_watchers_map = HashMap::with_capacity(count); + for identity in identities { + let (tx, _rx) = watch::channel(identity.name.clone()); + name_watchers_map.insert(identity.client_id.clone(), tx); + clients.insert(identity.client_id.clone(), identity); } - - let count = clients.len(); if count > 0 { tracing::info!("[identity] Loaded {count} identities from database"); } @@ -234,15 +199,9 @@ impl IdentityStore { // Persist to database first (if available) if let Some(db) = &self.db { - let conn = db - .connect() - .map_err(|e| anyhow::anyhow!("DB connect: {e}"))?; - conn.execute( - "INSERT INTO identities (client_id, name, created_at, updated_at) VALUES (?1, ?2, ?3, ?4)", - db_identity_params(&client_id, name.as_ref(), now, now), - ) - .await - .map_err(|e| anyhow::anyhow!("DB insert: {e}"))?; + let db = Arc::clone(db); + let record = identity.clone(); + run_blocking(move || db.create(&record)).await?; } // Store the identity in memory @@ -309,28 +268,17 @@ impl IdentityStore { identity.name.clone_from(&name); identity.updated_at = unix_timestamp(); let result = identity.clone(); - drop(clients); - // Persist to database (best-effort — in-memory is authoritative during session) - if let Some(db) = &self.db - && let Ok(conn) = db.connect() - { - let params = vec![ - name.as_ref() - .map_or(libsql::Value::Null, |n| libsql::Value::Text(n.clone())), - libsql::Value::Integer(i64::try_from(result.updated_at).unwrap_or(0)), - libsql::Value::Text(client_id.to_owned()), - ]; - if let Err(e) = conn - .execute( - "UPDATE identities SET name = ?1, updated_at = ?2 WHERE client_id = ?3", - params, - ) - .await - { + // Persist to database (best-effort: in-memory is authoritative during session). + // The write runs under the lock, so the file ends in the same order as memory. + if let Some(db) = &self.db { + let db = Arc::clone(db); + let record = result.clone(); + if let Err(e) = run_blocking(move || db.update(&record)).await { tracing::warn!("[identity] Failed to persist name update: {e}"); } } + drop(clients); // Notify any subscribed WS handlers of the name change { @@ -500,56 +448,160 @@ fn unix_timestamp() -> u64 { } // ============================================================================= -// Database Helpers +// Encrypted Store (redb) // ============================================================================= -/// Extract a TEXT value from a database row. -fn db_text(row: &libsql::Row, idx: i32) -> anyhow::Result { - match row - .get_value(idx) - .map_err(|e| anyhow::anyhow!("Failed to get column {idx}: {e}"))? - { - libsql::Value::Text(s) => Ok(s), - other => anyhow::bail!("Expected text at column {idx}, got {other:?}"), - } +/// The one table: client ID to sealed record. +const IDENTITIES: TableDefinition<'static, &str, &[u8]> = TableDefinition::new("identities"); + +/// AES-256-GCM nonce length. Every stored value starts with its own nonce. +const NONCE_LEN: usize = 12; + +/// Run a redb call on tokio's blocking pool. Commits fsync, which must not stall +/// an async worker thread. +async fn run_blocking(task: F) -> anyhow::Result +where + F: FnOnce() -> anyhow::Result + Send + 'static, + T: Send + 'static, +{ + tokio::task::spawn_blocking(task) + .await + .map_err(|e| anyhow::anyhow!("identity store task failed: {e}"))? } -/// Extract an optional TEXT value from a database row. -fn db_opt_text(row: &libsql::Row, idx: i32) -> anyhow::Result> { - match row - .get_value(idx) - .map_err(|e| anyhow::anyhow!("Failed to get column {idx}: {e}"))? - { - libsql::Value::Text(s) if !s.is_empty() => Ok(Some(s)), - libsql::Value::Text(_) | libsql::Value::Null => Ok(None), - other => anyhow::bail!("Expected text or null at column {idx}, got {other:?}"), - } +/// The redb file behind an [`IdentityStore`]. +/// +/// Each value is `nonce || ciphertext`: a fresh random 12-byte nonce, then the +/// AES-256-GCM ciphertext and tag of the JSON record. The client ID is the +/// associated data, so a value moved under another key fails to authenticate. +/// Client IDs stay in plaintext as keys; the record, names included, does not. +struct IdentityDb { + db: Database, + cipher: Aes256Gcm, } -/// Extract a u64 value from a database INTEGER column. -fn db_u64(row: &libsql::Row, idx: i32) -> anyhow::Result { - match row - .get_value(idx) - .map_err(|e| anyhow::anyhow!("Failed to get column {idx}: {e}"))? - { - libsql::Value::Integer(n) => Ok(u64::try_from(n).unwrap_or(0)), - other => anyhow::bail!("Expected integer at column {idx}, got {other:?}"), +impl IdentityDb { + /// Open or create the file at `path`, then [`load`](Self::load) it. + fn open(path: &Path, key: &[u8; 32]) -> anyhow::Result<(Self, Vec)> { + let db = Database::create(path).map_err(|e| match e { + DatabaseError::DatabaseAlreadyOpen => anyhow::anyhow!( + "identity store {} is already open in another process or handle", + path.display() + ), + other => anyhow::anyhow!("failed to open identity store {}: {other}", path.display()), + })?; + Self::load(db, key) } -} -/// Convert identity fields to database parameter values for INSERT. -fn db_identity_params( - client_id: &str, - name: Option<&String>, - created_at: u64, - updated_at: u64, -) -> Vec { - vec![ - libsql::Value::Text(client_id.to_owned()), - name.map_or(libsql::Value::Null, |n| libsql::Value::Text(n.clone())), - libsql::Value::Integer(i64::try_from(created_at).unwrap_or(0)), - libsql::Value::Integer(i64::try_from(updated_at).unwrap_or(0)), - ] + /// Create the table if the file is new, then authenticate every record. + /// + /// A record that fails authentication stops the load: a wrong key or an + /// altered file must not start a store that silently drops identities. On an + /// empty file a wrong key cannot be seen until the first record exists. + fn load(db: Database, key: &[u8; 32]) -> anyhow::Result<(Self, Vec)> { + let store = Self { + db, + cipher: Aes256Gcm::new(&(*key).into()), + }; + let txn = store.db.begin_write()?; + txn.open_table(IDENTITIES)?; + txn.commit()?; + let records = store.read_all()?; + Ok((store, records)) + } + + /// Decrypt every record, in no particular order. + fn read_all(&self) -> anyhow::Result> { + let txn = self.db.begin_read()?; + let table = txn.open_table(IDENTITIES)?; + let mut records = Vec::new(); + for entry in table.iter()? { + let (client_id, value) = entry?; + records.push(self.unseal(client_id.value(), value.value())?); + } + Ok(records) + } + + /// Insert a record. A client ID that is already stored is an error (INSERT). + fn create(&self, identity: &ClientIdentity) -> anyhow::Result<()> { + let value = self.seal(identity)?; + let txn = self.db.begin_write()?; + { + let mut table = txn.open_table(IDENTITIES)?; + if table.get(identity.client_id.as_str())?.is_some() { + anyhow::bail!("identity {} already exists", short_id(&identity.client_id)); + } + table.insert(identity.client_id.as_str(), value.as_slice())?; + } + txn.commit()?; + Ok(()) + } + + /// Overwrite the record stored under its client ID (UPDATE by key). + fn update(&self, identity: &ClientIdentity) -> anyhow::Result<()> { + let value = self.seal(identity)?; + let txn = self.db.begin_write()?; + { + let mut table = txn.open_table(IDENTITIES)?; + table.insert(identity.client_id.as_str(), value.as_slice())?; + } + txn.commit()?; + Ok(()) + } + + /// Encrypt a record under a fresh random nonce, as `nonce || ciphertext`. + /// + /// Nonces are random, not counters, so the store needs no persisted nonce + /// state. At 96 bits, a collision under one key is negligible for any write + /// volume an identity store sees. + fn seal(&self, identity: &ClientIdentity) -> anyhow::Result> { + let plaintext = serde_json::to_vec(identity)?; + let mut nonce = [0u8; NONCE_LEN]; + rand::fill(&mut nonce); + let ciphertext = self + .cipher + .encrypt( + &nonce.into(), + Payload { + msg: &plaintext, + aad: identity.client_id.as_bytes(), + }, + ) + .map_err(|_e| { + anyhow::anyhow!( + "failed to encrypt identity {}", + short_id(&identity.client_id) + ) + })?; + let mut value = Vec::with_capacity(NONCE_LEN + ciphertext.len()); + value.extend_from_slice(&nonce); + value.extend_from_slice(&ciphertext); + Ok(value) + } + + /// Split and decrypt one stored value. `client_id` is its table key. + fn unseal(&self, client_id: &str, value: &[u8]) -> anyhow::Result { + let Some((nonce, ciphertext)) = value.split_at_checked(NONCE_LEN) else { + anyhow::bail!("identity {} is truncated", short_id(client_id)); + }; + let nonce: [u8; NONCE_LEN] = nonce.try_into()?; + let plaintext = self + .cipher + .decrypt( + &nonce.into(), + Payload { + msg: ciphertext, + aad: client_id.as_bytes(), + }, + ) + .map_err(|_e| { + anyhow::anyhow!( + "identity {} failed authentication: the key is wrong or the file was altered", + short_id(client_id) + ) + })?; + Ok(serde_json::from_slice(&plaintext)?) + } } /// Base64url encode without padding (RFC 4648 section 5). @@ -649,6 +701,8 @@ fn base64url_decode(encoded: &str) -> Option> { mod tests { use super::*; use crate::test_forgeries::{IDENTITY_KEY, identity_forgery, with_non_canonical_s}; + use proptest::prelude::*; + use std::collections::HashSet; #[test] fn test_generate_client_id() { @@ -923,4 +977,284 @@ mod tests { let token = token_of(&payload, &identity_forgery()); assert!(store.decode_token(&token).is_none()); } + + // ------------------------------------------------------------------------- + // Encrypted redb store + // ------------------------------------------------------------------------- + + /// Key for the in-memory table tests. + const TABLE_KEY: [u8; 32] = [3u8; 32]; + + /// Secret key for the store tests, which open real files. + const STORE_SECRET: [u8; 32] = [7u8; 32]; + + /// Set only in the child process of `test_second_process_cannot_open_store`. + const PROBE_PATH_ENV: &str = "ID_IDENTITY_PROBE_PATH"; + + fn identity_record(client_id: &str, name: Option<&str>) -> ClientIdentity { + ClientIdentity { + client_id: client_id.to_owned(), + name: name.map(str::to_owned), + created_at: 1_700_000_000, + updated_at: 1_700_000_000, + } + } + + /// An empty redb file in memory, so the sealing tests never fsync. + fn in_memory_file() -> Database { + Database::builder() + .create_with_backend(redb::backends::InMemoryBackend::new()) + .unwrap() + } + + fn in_memory_store() -> IdentityDb { + IdentityDb::load(in_memory_file(), &TABLE_KEY).unwrap().0 + } + + /// The value stored under `client_id`, exactly as the file holds it. + fn raw_value(store: &IdentityDb, client_id: &str) -> Vec { + let txn = store.db.begin_read().unwrap(); + let table = txn.open_table(IDENTITIES).unwrap(); + table.get(client_id).unwrap().unwrap().value().to_vec() + } + + /// The nonce at the front of the value stored under `client_id`. + fn raw_nonce(store: &IdentityDb, client_id: &str) -> [u8; NONCE_LEN] { + raw_value(store, client_id)[..NONCE_LEN].try_into().unwrap() + } + + #[test] + fn test_record_round_trips_through_the_table() { + let (_, empty) = IdentityDb::load(in_memory_file(), &TABLE_KEY).unwrap(); + assert!(empty.is_empty()); + + let store = in_memory_store(); + store + .create(&identity_record("aa11", Some("Alice"))) + .unwrap(); + store.create(&identity_record("bb22", None)).unwrap(); + + let mut records = store.read_all().unwrap(); + records.sort_by(|a, b| a.client_id.cmp(&b.client_id)); + assert_eq!(records.len(), 2); + assert_eq!(records[0].client_id, "aa11"); + assert_eq!(records[0].name.as_deref(), Some("Alice")); + assert_eq!(records[0].created_at, 1_700_000_000); + assert_eq!(records[1].name, None); + } + + #[test] + fn test_stored_value_hides_the_name() { + let store = in_memory_store(); + store + .create(&identity_record("aa11", Some("Alice Wonderland"))) + .unwrap(); + let value = raw_value(&store, "aa11"); + assert!(value.len() > NONCE_LEN + 16, "nonce, record and tag"); + assert!( + !value.windows(5).any(|w| w == b"Alice"), + "the name must be encrypted" + ); + } + + #[test] + fn test_create_refuses_a_stored_client_id() { + let store = in_memory_store(); + store + .create(&identity_record("aa11", Some("Alice"))) + .unwrap(); + let err = store + .create(&identity_record("aa11", Some("Mallory"))) + .unwrap_err(); + assert!(err.to_string().contains("already exists"), "{err}"); + assert_eq!(store.read_all().unwrap()[0].name.as_deref(), Some("Alice")); + } + + #[test] + fn test_update_overwrites_the_record() { + let store = in_memory_store(); + store + .create(&identity_record("aa11", Some("Alice"))) + .unwrap(); + store.update(&identity_record("aa11", Some("Bob"))).unwrap(); + let records = store.read_all().unwrap(); + assert_eq!(records.len(), 1); + assert_eq!(records[0].name.as_deref(), Some("Bob")); + } + + #[test] + fn test_wrong_key_refuses_records_it_did_not_seal() { + let store = in_memory_store(); + store + .create(&identity_record("aa11", Some("Alice"))) + .unwrap(); + let IdentityDb { db, .. } = store; + let err = IdentityDb::load(db, &[4u8; 32]).err().unwrap(); + assert!(err.to_string().contains("failed authentication"), "{err}"); + } + + #[test] + fn test_altered_value_is_refused() { + let store = in_memory_store(); + store + .create(&identity_record("aa11", Some("Alice"))) + .unwrap(); + let value = raw_value(&store, "aa11"); + let opened = store.unseal("aa11", &value).unwrap(); + assert_eq!(opened.name.as_deref(), Some("Alice")); + + // Flipping any single bit of the nonce, ciphertext or tag must fail. + for byte in 0..value.len() { + for bit in 0..8u8 { + let mut altered = value.clone(); + altered[byte] ^= 1u8 << bit; + assert!( + store.unseal("aa11", &altered).is_err(), + "byte {byte} bit {bit} was accepted" + ); + } + } + // The same bytes under another client ID: the ID is the associated data. + assert!(store.unseal("bb22", &value).is_err()); + // Truncated: inside the nonce, and a whole nonce with no tag. + assert!(store.unseal("aa11", &value[..5]).is_err()); + assert!(store.unseal("aa11", &value[..NONCE_LEN + 15]).is_err()); + } + + #[test] + fn test_nonces_never_repeat_across_random_writes() { + proptest!(ProptestConfig::with_cases(64), |( + writes in prop::collection::vec((0usize..4, prop::option::of("[a-z]{0,12}")), 1..200), + )| { + let store = in_memory_store(); + let ids: Vec = (0..4).map(|i| format!("{i:032x}")).collect(); + let mut seen = HashSet::new(); + for id in &ids { + store.create(&identity_record(id, None)).unwrap(); + prop_assert!(seen.insert(raw_nonce(&store, id)), "nonce reused by create of {id}"); + } + for (index, name) in &writes { + let id = &ids[*index]; + store.update(&identity_record(id, name.as_deref())).unwrap(); + prop_assert!(seen.insert(raw_nonce(&store, id)), "nonce reused by update of {id}"); + } + }); + } + + #[tokio::test] + async fn test_records_survive_close_and_reopen() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("identity.redb"); + let (token, client_id) = { + let store = IdentityStore::new(STORE_SECRET, path.clone()) + .await + .unwrap(); + let (token, identity) = store.register(Some("Alice".to_owned())).await.unwrap(); + store + .update_name(&identity.client_id, Some("Bob".to_owned())) + .await + .unwrap(); + (token, identity.client_id) + }; + + let store = IdentityStore::new(STORE_SECRET, path).await.unwrap(); + let reopened = store.verify_token(&token).await.unwrap(); + assert_eq!(reopened.client_id, client_id); + assert_eq!(reopened.name.as_deref(), Some("Bob")); + assert_eq!(store.len().await, 1); + } + + #[tokio::test] + async fn test_wrong_key_refuses_to_open_store() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("identity.redb"); + { + let store = IdentityStore::new(STORE_SECRET, path.clone()) + .await + .unwrap(); + store.register(Some("Alice".to_owned())).await.unwrap(); + } + let err = IdentityStore::new([8u8; 32], path).await.unwrap_err(); + assert!(err.to_string().contains("failed authentication"), "{err}"); + } + + #[tokio::test] + async fn test_tampered_file_refuses_to_open() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("identity.redb"); + let client_id = { + let store = IdentityStore::new(STORE_SECRET, path.clone()) + .await + .unwrap(); + let (_, identity) = store.register(Some("Alice".to_owned())).await.unwrap(); + identity.client_id + }; + + // Flip the last bit of the stored tag, straight through redb. + let file = Database::create(&path).unwrap(); + let txn = file.begin_write().unwrap(); + { + let mut table = txn.open_table(IDENTITIES).unwrap(); + let mut value = table + .get(client_id.as_str()) + .unwrap() + .unwrap() + .value() + .to_vec(); + let last = value.len() - 1; + value[last] ^= 1; + table.insert(client_id.as_str(), value.as_slice()).unwrap(); + } + txn.commit().unwrap(); + drop(file); + + let err = IdentityStore::new(STORE_SECRET, path).await.unwrap_err(); + assert!(err.to_string().contains("failed authentication"), "{err}"); + } + + #[tokio::test] + async fn test_second_process_cannot_open_store() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("identity.redb"); + let held = IdentityStore::new(STORE_SECRET, path.clone()) + .await + .unwrap(); + held.register(Some("Alice".to_owned())).await.unwrap(); + + // Run the probe test in a child process, which finds the path in its environment. + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "web::identity::tests::test_second_open_probe", + "--nocapture", + ]) + .env(PROBE_PATH_ENV, &path) + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!(output.status.success(), "probe failed:\n{stdout}"); + assert!( + stdout.contains("PROBE: identity store") + && stdout.contains("already open in another process"), + "the child should be refused with a clear error:\n{stdout}" + ); + + // The refused open leaves the file intact for the process that holds it. + drop(held); + let reopened = IdentityStore::new(STORE_SECRET, path).await.unwrap(); + assert_eq!(reopened.len().await, 1); + } + + /// The child half of [`test_second_process_cannot_open_store`]. It does nothing + /// unless the probe path is set, so an ordinary test run passes it with no effect. + #[tokio::test] + async fn test_second_open_probe() { + let Some(path) = std::env::var_os(PROBE_PATH_ENV) else { + return; + }; + match IdentityStore::new(STORE_SECRET, PathBuf::from(path)).await { + Ok(_) => println!("PROBE: opened"), + Err(e) => println!("PROBE: {e}"), + } + } } diff --git a/pkgs/id/src/web/mod.rs b/pkgs/id/src/web/mod.rs index 488eb71123..392cf108d3 100644 --- a/pkgs/id/src/web/mod.rs +++ b/pkgs/id/src/web/mod.rs @@ -174,8 +174,8 @@ impl std::fmt::Debug for AppState { impl AppState { /// Create a new application state with persistent identity storage. /// - /// Opens an encrypted `SQLite` database for identity persistence using - /// a key derived from the node's iroh secret key. + /// Opens the encrypted identity store (a redb file) for identity persistence + /// using a key derived from the node's iroh secret key. pub async fn new( store: Store, peers: Option, From 0eed7ef06481f1f6705f8a8600cd9af88e813dd7 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 11 Oct 2026 17:47:11 -0500 Subject: [PATCH 03/30] feat(id): waiting pool with per-author and age caps [P1.5] A waiting pool holds events until their dependencies arrive. Two caps bound what a peer can make a node hold: 256 waiting events per author and a 7-day age cap. Both are set per world through WaitingLimits. - An event whose dependencies have all arrived is not held. It comes back from take_ready and takes no slot under the cap. - Expiry is inclusive: an event is dropped once it has waited max_age. expire returns the dropped events so the caller can log them. - arrived releases events in insert order and never releases an expired event. An arrival for a key that is itself held drops the held copy without releasing it. The pool does no I/O and takes an explicit clock. It is not connected to storage yet: P1.3 supplies the arrivals. Until then it keeps its own set of arrived keys, which grows with arrivals. --- pkgs/id/src/lib.rs | 1 + pkgs/id/src/waiting.rs | 529 ++++++++++++++++++++++++++++ pkgs/id/tests/waiting_properties.rs | 460 ++++++++++++++++++++++++ 3 files changed, 990 insertions(+) create mode 100644 pkgs/id/src/waiting.rs create mode 100644 pkgs/id/tests/waiting_properties.rs diff --git a/pkgs/id/src/lib.rs b/pkgs/id/src/lib.rs index e675a9a9f1..766ef04e30 100644 --- a/pkgs/id/src/lib.rs +++ b/pkgs/id/src/lib.rs @@ -189,6 +189,7 @@ pub mod tags; #[cfg(test)] mod test_forgeries; pub mod tuple; +pub mod waiting; #[cfg(feature = "world")] pub mod world; #[cfg(feature = "world")] diff --git a/pkgs/id/src/waiting.rs b/pkgs/id/src/waiting.rs new file mode 100644 index 0000000000..939c5c7e81 --- /dev/null +++ b/pkgs/id/src/waiting.rs @@ -0,0 +1,529 @@ +//! Waiting events: events that have arrived but cannot be applied yet. +//! +//! An event waits when a dependency has not arrived: a backlink, an `after` +//! hash, or an auth dependency. The pool holds the event until every dependency +//! has arrived, then releases it. Two caps bound what a peer can make a node +//! hold: at most [`WaitingLimits::per_author`] waiting events per author, and a +//! drop once an event has waited [`WaitingLimits::max_age_ms`]. A dropped event +//! is not acknowledged, and sync sends it again once its dependency exists. +//! +//! The pool does no I/O and takes the clock as an explicit `now_ms`, so tests +//! use a fake clock. It is not connected to storage yet: the event store (P1.3) +//! will supply the arrivals. Until then the pool keeps its own set of arrived +//! keys. +//! +//! The caller's loop: +//! +//! 1. Call [`WaitingPool::insert`] for each event it cannot apply yet, then take +//! [`WaitingPool::take_ready`] straight away. The events whose dependencies +//! had all arrived are in that list. Apply them. +//! 2. After applying an event, call [`WaitingPool::arrived`] with its key. It +//! returns the events that were waiting only on that key. Apply each one, and +//! call `arrived` for its key in turn, so that causal order holds. +//! 3. Call [`WaitingPool::expire`] regularly and log what it returns. +//! +//! The pool returns events, not keys, so `E` must carry its own key for step 2. + +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; +use std::hash::Hash; + +/// An author's public key: the 32 bytes of its Ed25519 key. +pub type AuthorKey = [u8; 32]; + +/// Waiting events allowed per author, unless a world sets its own. +pub const DEFAULT_PER_AUTHOR: usize = 256; + +const MS_PER_DAY: u64 = 24 * 60 * 60 * 1_000; + +/// Age after which a waiting event is dropped, unless a world sets its own: 7 days. +pub const DEFAULT_MAX_AGE_MS: u64 = 7 * MS_PER_DAY; + +/// The caps a world sets on its waiting events. +/// +/// [`WaitingLimits::default`] gives the accepted values: 256 waiting events per +/// author, and a 7-day age cap. A world sets its own with [`WaitingLimits::new`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct WaitingLimits { + per_author: usize, + max_age_ms: u64, +} + +impl WaitingLimits { + /// Caps for one world. `per_author` is the most waiting events one author may + /// hold, and `max_age_ms` is how long an event may wait before it expires. + /// + /// Zero is accepted. A `per_author` of zero refuses every event that would + /// wait, and a `max_age_ms` of zero expires events at the next call. + pub const fn new(per_author: usize, max_age_ms: u64) -> Self { + Self { + per_author, + max_age_ms, + } + } + + /// The most waiting events one author may hold. + pub const fn per_author(self) -> usize { + self.per_author + } + + /// How long an event may wait before it expires, in milliseconds. + pub const fn max_age_ms(self) -> u64 { + self.max_age_ms + } +} + +impl Default for WaitingLimits { + fn default() -> Self { + Self::new(DEFAULT_PER_AUTHOR, DEFAULT_MAX_AGE_MS) + } +} + +/// Why [`WaitingPool::insert`] refused an event. The event is dropped and not +/// acknowledged. +#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] +pub enum WaitRefusal { + /// The author already holds the per-author cap of waiting events. + #[error("the author already holds the maximum number of waiting events")] + AuthorFull, +} + +/// One held event and the dependencies it still waits for. +#[derive(Debug)] +struct Waiting { + author: AuthorKey, + key: K, + arrived_at: u64, + missing: HashSet, + event: E, +} + +/// Events held until their dependencies arrive. +/// +/// `K` is an event's key (its hash), and `E` is the event the pool stores. The +/// pool releases events in arrival order: the order `insert` accepted them. +#[derive(Debug)] +pub struct WaitingPool { + limits: WaitingLimits, + /// The sequence number the next accepted event gets. Sequence numbers give + /// arrival order. + next_seq: u64, + /// Held events by sequence number. + waiting: BTreeMap>, + /// The sequence number of each held event, by its key. + by_key: HashMap, + /// The sequence numbers of the held events that still miss each dependency. + by_dep: HashMap>, + /// Held events by (arrival time, sequence number), for the age cap. + by_time: BTreeSet<(u64, u64)>, + /// Held events per author. An author with none has no entry. + per_author: HashMap, + /// Keys that have arrived. A dependency in this set is already satisfied. + arrived: HashSet, + /// Events whose dependencies had all arrived when they were inserted. + ready: Vec, + /// Events dropped by the age cap, for `expire` to return. + expired: Vec<(AuthorKey, E)>, +} + +impl WaitingPool +where + K: Clone + Eq + Hash, +{ + /// An empty pool under `limits`. + pub fn new(limits: WaitingLimits) -> Self { + Self { + limits, + next_seq: 0, + waiting: BTreeMap::new(), + by_key: HashMap::new(), + by_dep: HashMap::new(), + by_time: BTreeSet::new(), + per_author: HashMap::new(), + arrived: HashSet::new(), + ready: Vec::new(), + expired: Vec::new(), + } + } + + /// The number of events held, across all authors. + pub fn len(&self) -> usize { + self.waiting.len() + } + + /// Whether the pool holds no events. + pub fn is_empty(&self) -> bool { + self.waiting.is_empty() + } + + /// The number of events `author` has held. Never above the per-author cap. + pub fn waiting_count(&self, author: AuthorKey) -> usize { + self.per_author.get(&author).copied().unwrap_or(0) + } + + /// Hold `event` until each of `deps` has arrived. + /// + /// `key` is the event's own key, and `deps` are the keys it needs. A + /// dependency that has already arrived is not waited for. If every dependency + /// has arrived, the event is not held: it is returned by + /// [`take_ready`](Self::take_ready), and it takes no slot under the cap. An + /// event whose key is already held or has arrived is a duplicate, and it is + /// ignored. + /// + /// Events due at `now_ms` expire before the insert, so a refusal changes + /// nothing except that expiry. + /// + /// # Errors + /// + /// [`WaitRefusal::AuthorFull`] when the event would wait and its author + /// already holds the per-author cap. + pub fn insert( + &mut self, + author: AuthorKey, + key: K, + deps: impl IntoIterator, + event: E, + now_ms: u64, + ) -> Result<(), WaitRefusal> { + self.expire_due(now_ms); + if self.arrived.contains(&key) || self.by_key.contains_key(&key) { + return Ok(()); + } + let missing: HashSet = deps + .into_iter() + .filter(|dep| !self.arrived.contains(dep)) + .collect(); + if missing.is_empty() { + self.ready.push(event); + return Ok(()); + } + if self.waiting_count(author) >= self.limits.per_author() { + return Err(WaitRefusal::AuthorFull); + } + let seq = self.next_seq; + self.next_seq += 1; + for dep in &missing { + self.by_dep.entry(dep.clone()).or_default().insert(seq); + } + self.by_time.insert((now_ms, seq)); + self.by_key.insert(key.clone(), seq); + *self.per_author.entry(author).or_default() += 1; + self.waiting.insert( + seq, + Waiting { + author, + key, + arrived_at: now_ms, + missing, + event, + }, + ); + Ok(()) + } + + /// Record that `key` has arrived, and release the events that were waiting + /// only for it. + /// + /// Returns the released events in arrival order. Each one has all its + /// dependencies but has not arrived itself: apply it, then call `arrived` with + /// its key, which can release more events. Events due at `now_ms` expire first, + /// so an expired event is never returned. If `key` was itself held, that copy + /// is dropped without being returned, because the caller now holds the event. + pub fn arrived(&mut self, key: K, now_ms: u64) -> Vec { + self.expire_due(now_ms); + if let Some(seq) = self.by_key.get(&key).copied() { + self.remove(seq); + } + let waiters = self.by_dep.remove(&key).unwrap_or_default(); + let mut released = Vec::new(); + for seq in waiters { + let Some(entry) = self.waiting.get_mut(&seq) else { + continue; + }; + entry.missing.remove(&key); + if !entry.missing.is_empty() { + continue; + } + if let Some(done) = self.remove(seq) { + released.push(done.event); + } + } + self.arrived.insert(key); + released + } + + /// Drop every held event that has waited `max_age_ms` by `now_ms`, and return + /// them as `(author, event)` in arrival order, so the caller can log them. + /// + /// The cap is inclusive. An event is dropped when `now_ms - arrived_at` reaches + /// `max_age_ms`, and one millisecond earlier it is kept. Each event is returned + /// once. + pub fn expire(&mut self, now_ms: u64) -> Vec<(AuthorKey, E)> { + self.expire_due(now_ms); + std::mem::take(&mut self.expired) + } + + /// The events whose dependencies had all arrived when they were inserted, in + /// insert order. Take them right after each `insert`, before the next call. + pub fn take_ready(&mut self) -> Vec { + std::mem::take(&mut self.ready) + } + + /// Move the events that have reached the age cap at `now_ms` into `expired`. + /// Every operation that takes a clock calls this first, so counts and releases + /// never include an expired event. + fn expire_due(&mut self, now_ms: u64) { + let Some(cutoff) = now_ms.checked_sub(self.limits.max_age_ms()) else { + return; + }; + let due: Vec = self + .by_time + .range(..=(cutoff, u64::MAX)) + .map(|&(_, seq)| seq) + .collect(); + for seq in due { + if let Some(entry) = self.remove(seq) { + self.expired.push((entry.author, entry.event)); + } + } + } + + /// Take a held event out of every index, and return it. + fn remove(&mut self, seq: u64) -> Option> { + let entry = self.waiting.remove(&seq)?; + self.by_time.remove(&(entry.arrived_at, seq)); + self.by_key.remove(&entry.key); + for dep in &entry.missing { + if let Some(waiters) = self.by_dep.get_mut(dep) { + waiters.remove(&seq); + if waiters.is_empty() { + self.by_dep.remove(dep); + } + } + } + if let Some(count) = self.per_author.get_mut(&entry.author) { + *count -= 1; + if *count == 0 { + self.per_author.remove(&entry.author); + } + } + Some(entry) + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use super::*; + + type Pool = WaitingPool; + + const WEEK_MS: u64 = 7 * MS_PER_DAY; + + fn author(n: u8) -> AuthorKey { + [n; 32] + } + + fn pool() -> Pool { + WaitingPool::new(WaitingLimits::default()) + } + + #[test] + fn test_defaults_are_256_per_author_and_seven_days() { + let limits = WaitingLimits::default(); + assert_eq!(limits.per_author(), 256); + assert_eq!(limits.max_age_ms(), 604_800_000); + } + + #[test] + fn test_limits_are_set_per_world() { + let limits = WaitingLimits::new(2, 1_000); + assert_eq!((limits.per_author(), limits.max_age_ms()), (2, 1_000)); + let mut pool = WaitingPool::new(limits); + pool.insert(author(1), 1, [10], "a", 0).unwrap(); + pool.insert(author(1), 2, [10], "b", 0).unwrap(); + assert_eq!( + pool.insert(author(1), 3, [10], "c", 0), + Err(WaitRefusal::AuthorFull) + ); + assert!(pool.expire(999).is_empty()); + assert_eq!(pool.expire(1_000).len(), 2); + } + + #[test] + fn test_per_author_cap_admits_256_and_refuses_the_257th() { + let mut pool = pool(); + let a = author(1); + for key in 0..255 { + pool.insert(a, key, [1_000 + key], "held", 0).unwrap(); + } + assert_eq!(pool.waiting_count(a), 255); + pool.insert(a, 255, [1_255], "held", 0).unwrap(); + assert_eq!(pool.waiting_count(a), 256); + + assert_eq!( + pool.insert(a, 256, [1_256], "refused", 0), + Err(WaitRefusal::AuthorFull) + ); + assert_eq!(pool.waiting_count(a), 256); + assert_eq!(pool.len(), 256); + assert!( + pool.arrived(1_256, 0).is_empty(), + "a refused event is not held" + ); + + pool.insert(author(2), 300, [2_000], "other author", 0) + .unwrap(); + assert_eq!(pool.waiting_count(author(2)), 1); + } + + #[test] + fn test_expiry_is_inclusive_at_max_age_and_exclusive_one_ms_before() { + let mut pool = pool(); + pool.insert(author(1), 1, [9], "e1", 1_000).unwrap(); + assert!(pool.expire(1_000 + WEEK_MS - 1).is_empty()); + assert_eq!(pool.len(), 1); + assert_eq!(pool.expire(1_000 + WEEK_MS), vec![(author(1), "e1")]); + assert_eq!(pool.waiting_count(author(1)), 0); + assert!(pool.is_empty()); + assert!(pool.expire(1_000 + WEEK_MS).is_empty(), "reported once"); + } + + #[test] + fn test_an_expired_event_is_not_released_by_its_dependency() { + let mut pool = pool(); + pool.insert(author(1), 1, [9], "e1", 0).unwrap(); + assert!(pool.arrived(9, WEEK_MS).is_empty()); + assert_eq!(pool.expire(WEEK_MS), vec![(author(1), "e1")]); + } + + #[test] + fn test_dependencies_arriving_out_of_order_release_in_arrival_order() { + let mut pool = pool(); + pool.insert(author(1), 3, [10], "c", 0).unwrap(); + pool.insert(author(1), 2, [11], "b", 0).unwrap(); + pool.insert(author(1), 1, [10], "a", 0).unwrap(); + pool.insert(author(1), 4, [12], "d", 0).unwrap(); + assert_eq!(pool.arrived(11, 0), vec!["b"]); + assert_eq!(pool.arrived(10, 0), vec!["c", "a"]); + assert_eq!(pool.arrived(12, 0), vec!["d"]); + assert!(pool.is_empty()); + } + + #[test] + fn test_a_chain_releases_one_link_per_arrival() { + let mut pool = pool(); + pool.insert(author(1), 1, [2], "a", 0).unwrap(); + pool.insert(author(1), 2, [3], "b", 0).unwrap(); + assert_eq!(pool.arrived(3, 0), vec!["b"]); + assert_eq!(pool.arrived(2, 0), vec!["a"]); + } + + #[test] + fn test_an_event_with_two_deps_waits_for_both() { + let mut pool = pool(); + pool.insert(author(1), 1, [10, 11], "e", 0).unwrap(); + assert!(pool.arrived(10, 0).is_empty()); + assert_eq!(pool.waiting_count(author(1)), 1); + assert_eq!(pool.arrived(11, 0), vec!["e"]); + assert_eq!(pool.waiting_count(author(1)), 0); + + pool.insert(author(1), 2, [20, 21], "f", 0).unwrap(); + assert!(pool.arrived(21, 0).is_empty()); + assert_eq!(pool.arrived(20, 0), vec!["f"]); + } + + #[test] + fn test_a_repeated_dep_counts_once() { + let mut pool = pool(); + pool.insert(author(1), 1, [30, 30], "g", 0).unwrap(); + assert_eq!(pool.arrived(30, 0), vec!["g"]); + } + + #[test] + fn test_an_event_whose_deps_arrived_is_ready_at_once() { + let mut pool = pool(); + pool.arrived(10, 0); + pool.insert(author(1), 1, [10], "ready", 0).unwrap(); + assert_eq!(pool.take_ready(), vec!["ready"]); + assert_eq!(pool.waiting_count(author(1)), 0); + assert!(pool.is_empty()); + assert!(pool.take_ready().is_empty()); + } + + #[test] + fn test_an_event_with_no_deps_is_ready_at_once() { + let mut pool = pool(); + pool.insert(author(1), 1, [], "free", 0).unwrap(); + assert_eq!(pool.take_ready(), vec!["free"]); + assert!(pool.is_empty()); + } + + #[test] + fn test_a_ready_event_is_not_refused_by_a_full_author() { + let mut pool = WaitingPool::new(WaitingLimits::new(1, WEEK_MS)); + pool.insert(author(1), 1, [10], "held", 0).unwrap(); + pool.arrived(20, 0); + pool.insert(author(1), 2, [20], "ready", 0).unwrap(); + assert_eq!(pool.take_ready(), vec!["ready"]); + assert_eq!(pool.waiting_count(author(1)), 1); + assert_eq!( + pool.insert(author(1), 3, [30], "refused", 0), + Err(WaitRefusal::AuthorFull) + ); + } + + #[test] + fn test_a_partly_arrived_event_waits_for_the_rest() { + let mut pool = pool(); + pool.arrived(10, 0); + pool.insert(author(1), 1, [10, 11], "e", 0).unwrap(); + assert!(pool.take_ready().is_empty()); + assert_eq!(pool.arrived(11, 0), vec!["e"]); + } + + #[test] + fn test_a_duplicate_key_is_ignored() { + let mut pool = pool(); + pool.insert(author(1), 1, [10], "first", 0).unwrap(); + pool.insert(author(1), 1, [10], "second", 0).unwrap(); + assert_eq!(pool.waiting_count(author(1)), 1); + assert_eq!(pool.arrived(10, 0), vec!["first"]); + + pool.arrived(1, 0); + pool.insert(author(1), 1, [10], "again", 0).unwrap(); + assert!(pool.take_ready().is_empty()); + assert!(pool.is_empty()); + } + + #[test] + fn test_arrival_of_a_held_event_drops_the_held_copy_without_releasing_it() { + let mut pool = pool(); + pool.insert(author(1), 1, [10], "held", 0).unwrap(); + assert!(pool.arrived(1, 0).is_empty()); + assert_eq!(pool.waiting_count(author(1)), 0); + assert!(pool.arrived(10, 0).is_empty()); + } + + #[test] + fn test_counts_stay_exact_across_insert_release_and_expiry() { + let mut pool = pool(); + pool.insert(author(1), 1, [10], "a", 0).unwrap(); + pool.insert(author(1), 2, [11], "b", 100).unwrap(); + pool.insert(author(2), 3, [12], "c", 100).unwrap(); + assert_eq!(pool.waiting_count(author(1)), 2); + assert_eq!(pool.waiting_count(author(2)), 1); + assert_eq!(pool.len(), 3); + + assert_eq!(pool.arrived(10, 200), vec!["a"]); + assert_eq!(pool.waiting_count(author(1)), 1); + assert_eq!(pool.len(), 2); + + assert_eq!( + pool.expire(100 + WEEK_MS), + vec![(author(1), "b"), (author(2), "c")] + ); + assert_eq!(pool.waiting_count(author(1)), 0); + assert_eq!(pool.waiting_count(author(2)), 0); + assert!(pool.is_empty()); + } +} diff --git a/pkgs/id/tests/waiting_properties.rs b/pkgs/id/tests/waiting_properties.rs new file mode 100644 index 0000000000..09f6f64e65 --- /dev/null +++ b/pkgs/id/tests/waiting_properties.rs @@ -0,0 +1,460 @@ +//! Property tests for the waiting pool in `src/waiting.rs`. +//! +//! The first property runs the pool and a naive model side by side. The model +//! is a list of held events, scanned on every call, so it is easy to check by +//! eye. Both see the same operations, and their results must match at every +//! step. The second property checks that inserts sharing a timestamp can come in +//! any order. Runs use a fixed seed, so CI draws the same cases every time, and +//! failures are not written to `proptest-regressions/`. + +#![allow(clippy::unwrap_used, clippy::expect_used)] + +use std::collections::{BTreeSet, HashMap, HashSet}; + +use id::waiting::{AuthorKey, WaitRefusal, WaitingLimits, WaitingPool}; +use proptest::prelude::*; +use proptest::test_runner::RngSeed; + +/// Seed for every property in this file. Changing it changes every generated case. +const SEED: u64 = 0x0077_A171_5EED; + +/// Cases per property. +const CASES: u32 = 1_024; + +/// Authors the generated operations draw from. +const AUTHORS: u8 = 3; + +/// Keys per step in the second property. An insert's key is its step times this +/// plus its slot, so keys are unique across the whole run. +const SLOTS_PER_STEP: u32 = 8; + +/// The range of keys that dependencies and arrivals are drawn from. Some of these +/// keys are never inserted, so their dependents wait until they expire. +const KEY_SPACE: u32 = 48; + +fn config() -> ProptestConfig { + ProptestConfig { + cases: CASES, + failure_persistence: None, + rng_seed: RngSeed::Fixed(SEED), + ..ProptestConfig::default() + } +} + +/// The 32-byte author key the pool takes, for a small test author number. +const fn author_key(author: u8) -> AuthorKey { + [author; 32] +} + +/// Clock steps are often zero, so many operations share a timestamp. +fn advance() -> impl Strategy { + prop_oneof![ + 1 => Just(0_u64), + 1 => 1_u64..=12, + ] +} + +/// An event the model holds. +#[derive(Clone, Debug)] +struct Held { + author: u8, + key: u32, + arrived_at: u64, + deps: Vec, + missing: BTreeSet, + id: u32, +} + +/// A naive reference for the pool: a list of held events, scanned on every call. +struct Model { + per_author: usize, + max_age_ms: u64, + /// Held events in arrival order. + held: Vec, + arrived: BTreeSet, + ready: Vec, + expired: Vec<(u8, u32)>, + /// Every event the model has expired, so that none is released later. + ever_expired: BTreeSet, +} + +impl Model { + const fn new(per_author: usize, max_age_ms: u64) -> Self { + Self { + per_author, + max_age_ms, + held: Vec::new(), + arrived: BTreeSet::new(), + ready: Vec::new(), + expired: Vec::new(), + ever_expired: BTreeSet::new(), + } + } + + fn count(&self, author: u8) -> usize { + self.held + .iter() + .filter(|held| held.author == author) + .count() + } + + /// Drop the held events whose age has reached the cap at `now`. + fn expire_due(&mut self, now: u64) { + let max_age = self.max_age_ms; + for held in std::mem::take(&mut self.held) { + if now.saturating_sub(held.arrived_at) >= max_age { + self.ever_expired.insert(held.id); + self.expired.push((held.author, held.id)); + } else { + self.held.push(held); + } + } + } + + /// Returns `true` when the event is refused. + fn insert(&mut self, author: u8, key: u32, deps: &[u32], id: u32, now: u64) -> bool { + self.expire_due(now); + if self.arrived.contains(&key) || self.held.iter().any(|held| held.key == key) { + return false; + } + let missing: BTreeSet = deps + .iter() + .copied() + .filter(|dep| !self.arrived.contains(dep)) + .collect(); + if missing.is_empty() { + self.ready.push(id); + return false; + } + if self.count(author) >= self.per_author { + return true; + } + self.held.push(Held { + author, + key, + arrived_at: now, + deps: deps.to_vec(), + missing, + id, + }); + false + } + + /// Record an arrival, and return the events it released in arrival order. + fn arrive(&mut self, key: u32, now: u64) -> Vec { + self.expire_due(now); + self.held.retain(|held| held.key != key); + self.arrived.insert(key); + let mut released = Vec::new(); + for mut held in std::mem::take(&mut self.held) { + held.missing.remove(&key); + if held.missing.is_empty() { + released.push(held); + } else { + self.held.push(held); + } + } + released + } + + fn take_ready(&mut self) -> Vec { + std::mem::take(&mut self.ready) + } + + fn expire(&mut self, now: u64) -> Vec<(u8, u32)> { + self.expire_due(now); + std::mem::take(&mut self.expired) + } +} + +/// One operation of the first property. The clock advances before each one. +#[derive(Clone, Debug)] +enum Op { + Insert { + author: u8, + key: u32, + deps: Vec, + advance: u64, + }, + Arrive { + key: u32, + advance: u64, + }, + Expire { + advance: u64, + }, +} + +fn op() -> impl Strategy { + prop_oneof![ + 6 => (0..AUTHORS, 0_u32..12, prop::collection::vec(0_u32..14, 0..4), advance()) + .prop_map(|(author, key, deps, advance)| Op::Insert { author, key, deps, advance }), + 3 => (0_u32..14, advance()).prop_map(|(key, advance)| Op::Arrive { key, advance }), + 1 => advance().prop_map(|advance| Op::Expire { advance }), + ] +} + +/// Each event is output at most once, by release, by `take_ready`, or by expiry. +fn record_outputs(ids: &[u32], seen: &mut HashSet) -> Result<(), TestCaseError> { + for id in ids { + prop_assert!(seen.insert(*id), "event {id} was output twice"); + } + Ok(()) +} + +/// After every operation, no author is over the cap, and each count and the total +/// match the model. +fn check_counts( + pool: &WaitingPool, + model: &Model, + per_author: usize, +) -> Result<(), TestCaseError> { + for author in 0..AUTHORS { + let count = pool.waiting_count(author_key(author)); + prop_assert!( + count <= per_author, + "author {author} holds {count}, over the cap of {per_author}" + ); + prop_assert_eq!(count, model.count(author)); + } + prop_assert_eq!(pool.len(), model.held.len()); + Ok(()) +} + +/// Apply `ops` to the pool and the model, and check every result against the model. +fn check_against_model( + ops: &[Op], + per_author: usize, + max_age_ms: u64, +) -> Result<(), TestCaseError> { + let limits = WaitingLimits::new(per_author, max_age_ms); + let mut pool: WaitingPool = WaitingPool::new(limits); + let mut model = Model::new(per_author, max_age_ms); + let mut now = 0_u64; + let mut next_id = 0_u32; + let mut output = HashSet::new(); + for op in ops { + match op { + Op::Insert { + author, + key, + deps, + advance, + } => { + now += advance; + let id = next_id; + next_id += 1; + let refused = model.insert(*author, *key, deps, id, now); + match pool.insert(author_key(*author), *key, deps.iter().copied(), id, now) { + Ok(()) => { + prop_assert!(!refused, "the model refused an event the pool accepted"); + } + Err(reason) => { + prop_assert_eq!(reason, WaitRefusal::AuthorFull); + prop_assert!(refused, "the pool refused an event the model accepted"); + } + } + let ready = pool.take_ready(); + prop_assert_eq!(&ready, &model.take_ready()); + record_outputs(&ready, &mut output)?; + } + Op::Arrive { key, advance } => { + now += advance; + let released = model.arrive(*key, now); + let expected: Vec = released.iter().map(|held| held.id).collect(); + let got = pool.arrived(*key, now); + prop_assert_eq!(&got, &expected); + for held in &released { + prop_assert!( + held.deps.iter().all(|dep| model.arrived.contains(dep)), + "event {} was released before all its dependencies arrived", + held.id + ); + prop_assert!( + !model.ever_expired.contains(&held.id), + "expired event {} was released", + held.id + ); + } + record_outputs(&got, &mut output)?; + } + Op::Expire { advance } => { + now += advance; + let expected = model.expire(now); + let got: Vec<(u8, u32)> = pool + .expire(now) + .into_iter() + .map(|(author, id)| (author[0], id)) + .collect(); + prop_assert_eq!(&got, &expected); + let ids: Vec = got.iter().map(|(_, id)| *id).collect(); + record_outputs(&ids, &mut output)?; + } + } + check_counts(&pool, &model, per_author)?; + } + Ok(()) +} + +proptest! { + #![proptest_config(config())] + + /// The pool agrees with the model on every result. The count never exceeds the + /// cap, a released event has all its dependencies, and an expired event is never + /// released. + #[test] + fn test_random_operations_match_the_model( + ops in prop::collection::vec(op(), 0..80), + per_author in 1_usize..=4, + max_age_ms in 1_u64..=40, + ) { + check_against_model(&ops, per_author, max_age_ms)?; + } +} + +/// An insert in the second property. `order` is a sort key, so that the same +/// inserts can be reordered within their step. +#[derive(Clone, Debug)] +struct Entry { + author: u8, + key: u32, + deps: Vec, + order: u32, +} + +/// One timestamp of the second property: its inserts, then its arrivals, then an expiry +/// sweep, all at the same time. +#[derive(Clone, Debug)] +struct Step { + advance: u64, + inserts: Vec, + arrivals: Vec, +} + +fn schedule() -> impl Strategy> { + let entry = ( + 0..AUTHORS, + prop::collection::vec(0..KEY_SPACE, 0..3), + any::(), + ); + let step = ( + advance(), + prop::collection::vec(entry, 0..=6), + prop::collection::vec(0..KEY_SPACE, 0..=3), + ); + prop::collection::vec(step, 1..=6).prop_map(|steps| { + steps + .into_iter() + .enumerate() + .map(|(index, (advance, entries, arrivals))| { + let base = u32::try_from(index).unwrap() * SLOTS_PER_STEP; + let inserts = entries + .into_iter() + .enumerate() + .map(|(slot, (author, deps, order))| Entry { + author, + key: base + u32::try_from(slot).unwrap(), + deps, + order, + }) + .collect(); + Step { + advance, + inserts, + arrivals, + } + }) + .collect() + }) +} + +/// What one step produced. Each list is sorted, so the order of calls does not show. +#[derive(Debug, PartialEq, Eq)] +struct StepResult { + ready: Vec, + released: Vec, + expired: Vec, +} + +fn sorted(mut ids: Vec) -> Vec { + ids.sort_unstable(); + ids +} + +/// The documented rule: every list the pool returns is in insert order. For a +/// timestamp that is the order the events were inserted. +fn in_insert_order(ids: &[u32], position: &HashMap) -> Result<(), TestCaseError> { + let positions: Vec = ids + .iter() + .map(|id| *position.get(id).expect("only inserted events are output")) + .collect(); + prop_assert!( + positions.windows(2).all(|pair| pair[0] < pair[1]), + "{ids:?} is not in insert order" + ); + Ok(()) +} + +/// Run `steps` through a pool that never refuses, and return what each step +/// produced. +fn run(steps: &[Step], max_age_ms: u64) -> Result, TestCaseError> { + let limits = WaitingLimits::new(1_000, max_age_ms); + let mut pool: WaitingPool = WaitingPool::new(limits); + let mut position: HashMap = HashMap::new(); + let mut now = 0_u64; + let mut results = Vec::new(); + for step in steps { + now += step.advance; + for entry in &step.inserts { + let index = position.len(); + position.insert(entry.key, index); + pool.insert( + author_key(entry.author), + entry.key, + entry.deps.iter().copied(), + entry.key, + now, + ) + .map_err(|reason| TestCaseError::fail(format!("unexpected refusal: {reason}")))?; + } + let ready = pool.take_ready(); + in_insert_order(&ready, &position)?; + let mut released = Vec::new(); + for key in &step.arrivals { + let batch = pool.arrived(*key, now); + in_insert_order(&batch, &position)?; + released.extend(batch); + } + let expired: Vec = pool.expire(now).into_iter().map(|(_, id)| id).collect(); + in_insert_order(&expired, &position)?; + results.push(StepResult { + ready: sorted(ready), + released: sorted(released), + expired: sorted(expired), + }); + } + Ok(results) +} + +proptest! { + #![proptest_config(config())] + + /// Inserts that share a timestamp can come in any order. The ready, released and + /// expired events are the same as sets, and each returned list is in insert order. + #[test] + fn test_equal_timestamp_inserts_give_the_same_result_in_any_order( + steps in schedule(), + max_age_ms in 1_u64..=30, + ) { + let drawn = run(&steps, max_age_ms)?; + let reordered: Vec = steps + .iter() + .map(|step| { + let mut step = step.clone(); + step.inserts.sort_by_key(|entry| entry.order); + step + }) + .collect(); + prop_assert_eq!(run(&reordered, max_age_ms)?, drawn); + } +} From f96b8af6449ed5005888255e788ad2eda04b71aa Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 11 Oct 2026 17:49:47 -0500 Subject: [PATCH 04/30] feat(id): ChainExt and its validation [P1.2] The event header is a p2panda-core Header whose extension is ChainExt: kind, group, after, and the domain tag id.events.v1 as a fourth key, so the tag is signed with the rest of the header. sign() validates the extension, then builds and signs the header through p2panda's builder. decode() checks canonical CBOR over the whole header, verifies the signature through AnyHeader::decode (verify_strict), and re-encodes the extension, which refuses a key that serde would default. The typed Header::verify is not used. The operation ID is BLAKE3 over the received bytes. Dependencies: p2panda-core (git, rev 3e84cac), cbor-core =0.10.1 with the serde feature, dcbor =0.25.2 (dev only), and unicode-normalization 0.1 for the NFC rule on kind (already in the lock, no new crate). --- pkgs/id/Cargo.lock | 169 +++++-- pkgs/id/Cargo.toml | 5 + pkgs/id/src/chain.rs | 607 +++++++++++++++++++++++++ pkgs/id/src/lib.rs | 1 + pkgs/id/tests/README.md | 4 + pkgs/id/tests/chain_properties.rs | 164 +++++++ pkgs/id/tests/common/chain.rs | 36 ++ pkgs/id/tests/common/mod.rs | 15 +- pkgs/id/tests/regression_replay.rs | 21 +- pkgs/id/tests/regressions/README.md | 3 +- pkgs/id/tests/regressions/chainext.txt | 29 ++ 11 files changed, 1017 insertions(+), 37 deletions(-) create mode 100644 pkgs/id/src/chain.rs create mode 100644 pkgs/id/tests/chain_properties.rs create mode 100644 pkgs/id/tests/common/chain.rs create mode 100644 pkgs/id/tests/regressions/chainext.txt diff --git a/pkgs/id/Cargo.lock b/pkgs/id/Cargo.lock index 1a10a420f1..5674a57e80 100644 --- a/pkgs/id/Cargo.lock +++ b/pkgs/id/Cargo.lock @@ -815,6 +815,15 @@ dependencies = [ "cipher 0.5.2", ] +[[package]] +name = "cbor-core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9f70473b5194d5f6e3c271dc6d0f63f6b17cc5d004af959e9ed0be8c1dadcdb" +dependencies = [ + "serde", +] + [[package]] name = "cc" version = "1.8.0" @@ -1342,6 +1351,12 @@ version = "0.8.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + [[package]] name = "crypto-bigint" version = "0.5.5" @@ -1440,6 +1455,7 @@ dependencies = [ "cfg-if", "cpufeatures 0.2.17", "curve25519-dalek-derive", + "digest 0.10.7", "fiat-crypto 0.2.9", "rustc_version", "subtle", @@ -1501,6 +1517,20 @@ dependencies = [ "syn 3.0.8", ] +[[package]] +name = "dcbor" +version = "0.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fcf662b6347d10dd5ab7370287b76923eb88818d46434de8c424b091523f5e54" +dependencies = [ + "chrono", + "half", + "hex", + "paste", + "thiserror 2.0.21", + "unicode-normalization", +] + [[package]] name = "delegate" version = "0.13.5" @@ -1646,7 +1676,7 @@ dependencies = [ "actor-helper", "anyhow", "chrono", - "ed25519-dalek", + "ed25519-dalek 3.0.0", "ed25519-dalek-hpke", "futures-lite", "getrandom 0.4.3", @@ -1705,20 +1735,45 @@ dependencies = [ "digest 0.11.3", "elliptic-curve 0.14.1", "rfc6979", - "signature", - "spki", + "signature 3.0.0", + "spki 0.8.1", "zeroize", ] +[[package]] +name = "ed25519" +version = "2.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" +dependencies = [ + "pkcs8 0.10.2", + "signature 2.2.0", +] + [[package]] name = "ed25519" version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29fcf32e6c73d1079f83ab4d782de2d81620346a5f38c6237a86a22f8368980a" dependencies = [ - "pkcs8", + "pkcs8 0.11.0", "serdect", - "signature", + "signature 3.0.0", +] + +[[package]] +name = "ed25519-dalek" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" +dependencies = [ + "curve25519-dalek 4.1.3", + "ed25519 2.2.3", + "rand_core 0.6.4", + "serde", + "sha2 0.10.9", + "subtle", + "zeroize", ] [[package]] @@ -1728,11 +1783,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ebaa1a2bf1290ab3bfe5a7b771d050ebffab2711c19a81691c683a5144a25de" dependencies = [ "curve25519-dalek 5.0.0", - "ed25519", + "ed25519 3.0.0", "rand_core 0.10.1", "serde", "sha2 0.11.0", - "signature", + "signature 3.0.0", "subtle", "zeroize", ] @@ -1743,7 +1798,7 @@ version = "0.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3553f25a4e38b5ca64b26c54f34e1dd5092d18a5dea03797ac235baab53eaf8f" dependencies = [ - "ed25519-dalek", + "ed25519-dalek 3.0.0", "hpke", "rand 0.9.5", "x25519-dalek", @@ -1789,7 +1844,7 @@ dependencies = [ "hkdf 0.13.0", "hybrid-array", "pem-rfc7468", - "pkcs8", + "pkcs8 0.11.0", "rand_core 0.10.1", "sec1 0.8.1", "subtle", @@ -2423,6 +2478,17 @@ dependencies = [ "tracing", ] +[[package]] +name = "half" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" +dependencies = [ + "cfg-if", + "crunchy", + "zerocopy 0.8.62", +] + [[package]] name = "hash32" version = "0.2.1" @@ -2502,6 +2568,9 @@ name = "hex" version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +dependencies = [ + "serde", +] [[package]] name = "hex-literal" @@ -2913,10 +2982,12 @@ dependencies = [ "anyhow", "axum 0.8.9", "base64 0.22.1", + "cbor-core", "clap", "comrak", + "dcbor", "distributed-topic-tracker", - "ed25519-dalek", + "ed25519-dalek 3.0.0", "futures", "futures-lite", "hkdf 0.13.0", @@ -2930,6 +3001,7 @@ dependencies = [ "libc", "libsql", "mime_guess", + "p2panda-core", "postcard", "proptest", "qrcode", @@ -2951,6 +3023,7 @@ dependencies = [ "tower-http 0.7.1", "tracing", "tracing-subscriber", + "unicode-normalization", "urlencoding", "vt100", "wasmtime", @@ -3087,7 +3160,7 @@ dependencies = [ "ctutils", "data-encoding", "derive_more", - "ed25519-dalek", + "ed25519-dalek 3.0.0", "futures-util", "getrandom 0.4.3", "http 1.5.0", @@ -3134,7 +3207,7 @@ dependencies = [ "data-encoding", "data-encoding-macro", "derive_more", - "ed25519-dalek", + "ed25519-dalek 3.0.0", "getrandom 0.4.3", "n0-error", "rand 0.10.3", @@ -3857,7 +3930,7 @@ dependencies = [ "crc", "document-features", "dyn-clone", - "ed25519-dalek", + "ed25519-dalek 3.0.0", "flume", "futures-lite", "getrandom 0.4.3", @@ -3974,7 +4047,7 @@ dependencies = [ "hybrid-array", "kem", "module-lattice", - "pkcs8", + "pkcs8 0.11.0", "rand_core 0.10.1", "sha3 0.11.0", ] @@ -4618,6 +4691,21 @@ dependencies = [ "sha2 0.11.0", ] +[[package]] +name = "p2panda-core" +version = "0.7.1" +source = "git+https://github.com/p2panda/p2panda?rev=3e84cac48bba05c6857cce2ec433862b97f8d53c#3e84cac48bba05c6857cce2ec433862b97f8d53c" +dependencies = [ + "blake3", + "cbor-core", + "ed25519-dalek 2.2.0", + "hex", + "rand 0.8.8", + "serde", + "serde_bytes", + "thiserror 2.0.21", +] + [[package]] name = "p384" version = "0.14.0" @@ -4892,7 +4980,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "986d2e952779af96ea048f160fd9194e1751b4faea78bcf3ceb456efe008088e" dependencies = [ "der 0.8.2", - "spki", + "spki 0.8.1", ] [[package]] @@ -4909,7 +4997,17 @@ dependencies = [ "rand_core 0.10.1", "scrypt", "sha2 0.11.0", - "spki", + "spki 0.8.1", +] + +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der 0.7.10", + "spki 0.7.3", ] [[package]] @@ -4921,7 +5019,7 @@ dependencies = [ "der 0.8.2", "pkcs5", "rand_core 0.10.1", - "spki", + "spki 0.8.1", ] [[package]] @@ -5624,11 +5722,11 @@ dependencies = [ "crypto-primes", "digest 0.11.3", "pkcs1", - "pkcs8", + "pkcs8 0.11.0", "rand_core 0.10.1", "sha2 0.11.0", - "signature", - "spki", + "signature 3.0.0", + "spki 0.8.1", "zeroize", ] @@ -5654,7 +5752,7 @@ dependencies = [ "der 0.8.2", "digest 0.11.3", "ecdsa", - "ed25519-dalek", + "ed25519-dalek 3.0.0", "elliptic-curve 0.14.1", "enum_dispatch", "flate2", @@ -5678,7 +5776,7 @@ dependencies = [ "pbkdf2", "pkcs1", "pkcs5", - "pkcs8", + "pkcs8 0.11.0", "polyval 0.7.3", "rand 0.10.3", "rand_core 0.10.1", @@ -5691,8 +5789,8 @@ dependencies = [ "sha1 0.11.0", "sha2 0.11.0", "sha3 0.12.0", - "signature", - "spki", + "signature 3.0.0", + "spki 0.8.1", "ssh-encoding", "ssh-key", "subtle", @@ -6331,6 +6429,15 @@ dependencies = [ "libc", ] +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "rand_core 0.6.4", +] + [[package]] name = "signature" version = "3.0.0" @@ -6451,6 +6558,16 @@ version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "023a211cb3138dbc438680b32560ad89f699977624c9f8dbb95a47d5b4c07dd3" +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der 0.7.10", +] + [[package]] name = "spki" version = "0.8.1" @@ -6509,7 +6626,7 @@ dependencies = [ "argon2", "bcrypt-pbkdf", "ctutils", - "ed25519-dalek", + "ed25519-dalek 3.0.0", "hex", "hmac 0.13.0", "p256 0.14.0", @@ -6520,7 +6637,7 @@ dependencies = [ "sec1 0.8.1", "sha1 0.11.0", "sha2 0.11.0", - "signature", + "signature 3.0.0", "ssh-cipher", "ssh-encoding", "zeroize", diff --git a/pkgs/id/Cargo.toml b/pkgs/id/Cargo.toml index 87c1a3f116..a083b52b2e 100644 --- a/pkgs/id/Cargo.toml +++ b/pkgs/id/Cargo.toml @@ -38,6 +38,7 @@ web = [ [dependencies] anyhow = "1" +cbor-core = { version = "=0.10.1", features = ["serde"] } clap = { version = "4", features = ["derive", "env"] } libc = "0.2" distributed-topic-tracker = "0.3" @@ -50,6 +51,7 @@ iroh-tickets = "1" iroh-blobs = "0.103" iroh-docs = "0.101" iroh-gossip = { version = "0.101", features = ["net"] } +p2panda-core = { git = "https://github.com/p2panda/p2panda", rev = "3e84cac48bba05c6857cce2ec433862b97f8d53c" } postcard = { version = "1", features = ["alloc"] } rand = "0.10" rustyline = "18" @@ -60,6 +62,7 @@ tokio = { version = "1", features = ["full"] } thiserror = "2" tracing = "0.1" tracing-subscriber = { version = "0.3", features = ["env-filter"] } +unicode-normalization = "0.1" # Web feature dependencies (optional) axum = { version = "0.8", features = ["ws", "multipart"], optional = true } @@ -90,6 +93,8 @@ tokio-tungstenite = "0.29" vt100 = "=0.16.2" rqrr = { version = "0.11.0", default-features = false } proptest = "1.12" +# Interop vectors for the canonical CBOR of event headers. Dev only. +dcbor = "=0.25.2" # ============================================================================= # Lints Configuration diff --git a/pkgs/id/src/chain.rs b/pkgs/id/src/chain.rs new file mode 100644 index 0000000000..1d10cb744c --- /dev/null +++ b/pkgs/id/src/chain.rs @@ -0,0 +1,607 @@ +//! Event headers: the `ChainExt` extension on p2panda-core's header, and the +//! sign and decode paths for it. +//! +//! Every event is a p2panda `Header`. p2panda's header already gives +//! each author a chain: the author's key, a sequence number, and a backlink to +//! the previous event. `ChainExt` adds what the membership rules need on top: +//! the event's `kind`, its `group`, and `after`, the author's causal frontier. +//! The domain tag [`DOMAIN_TAG`] is one of the extension's keys, so it is +//! signed with the rest of the header. +//! +//! Receivers call [`decode`] on the received bytes and nothing else. It checks +//! that the bytes are canonical CBOR, then lets `AnyHeader::decode` check the +//! layout and the signature, which uses `verify_strict`. It never calls the +//! typed `Header::verify`, which returns `true` outside test builds, and it +//! never uses a cached digest: the operation ID is BLAKE3 over the received +//! bytes. + +use std::collections::HashSet; + +use cbor_core::{DecodeOptions, Strictness, Value}; +use p2panda_core::{AnyHeader, Hash, Header, HeaderError, SeqNum, SigningKey}; +use serde::{Deserialize, Serialize}; +use unicode_normalization::is_nfc; + +/// The domain tag every `ChainExt` carries, so this header type cannot be +/// confused with another protocol's. +pub const DOMAIN_TAG: &str = "id.events.v1"; + +/// The most hashes an `after` frontier may hold. +pub const MAX_AFTER: usize = 32; + +/// The longest `kind`, in UTF-8 bytes. The shortest is one byte. +pub const MAX_KIND_BYTES: usize = 64; + +/// Nesting limit for a header's CBOR. Matches the limit p2panda's decoder uses. +const RECURSION_LIMIT: u16 = 64; + +/// Declared element limit for one array, map, or string. Matches p2panda's decoder. +const LENGTH_LIMIT: u64 = 512; + +/// Byte budget for speculative pre-allocation. Matches p2panda's decoder. +const OOM_MITIGATION: usize = 64; + +/// Why an event header, or the extension it carries, was refused. +#[derive(Debug, thiserror::Error)] +pub enum ChainError { + /// `after` holds more hashes than [`MAX_AFTER`]. + #[error("after holds {0} hashes, the most allowed is {max}", max = MAX_AFTER)] + TooManyAfter(usize), + /// `after` names the same hash twice. + #[error("after names the same hash twice")] + DuplicateAfter, + /// `kind` is empty or longer than [`MAX_KIND_BYTES`]. + #[error("kind is {0} bytes, it must be 1 to {max} bytes", max = MAX_KIND_BYTES)] + KindLength(usize), + /// `kind` is not in Unicode normalization form NFC. + #[error("kind is not in Unicode NFC")] + KindNotNfc, + /// The domain tag is missing, or it is not [`DOMAIN_TAG`]. + #[error("domain tag {0:?} is not {tag:?}", tag = DOMAIN_TAG)] + Domain(String), + /// Sequence 0 takes no backlink. + #[error("sequence 0 takes no backlink")] + UnexpectedBacklink, + /// Every sequence after 0 names the author's previous event. + #[error("sequence {0} needs a backlink")] + MissingBacklink(SeqNum), + /// The bytes, or the extension inside them, are not the canonical encoding + /// of the value they hold. + #[error("the bytes are not the canonical encoding of their value")] + NotCanonical, + /// A CBOR value that signed headers do not allow: a float, a tag, a simple + /// value other than false, true, or null, or text that is not NFC. + #[error("CBOR value refused: {0}")] + CborRule(String), + /// The extension does not serialize back to its own bytes, or it cannot be + /// serialized at all. + #[error("extension refused: {0}")] + Extension(String), + /// The bytes are not CBOR, or they are CBOR that strict decoding refuses. + #[error("CBOR decoding failed: {0}")] + Cbor(#[from] cbor_core::Error), + /// p2panda's header decoder refused the bytes: the layout, the version, or the + /// signature. It also carries an extension that fails its serde form or a + /// [`ChainExt`] rule, with the rule named in the message. + #[error(transparent)] + Header(#[from] HeaderError), +} + +/// The extension every event header carries. It is serialized inside the +/// signed header. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(try_from = "Wire", into = "Wire")] +pub struct ChainExt { + /// What the event is: a group operation, a message, a tag, and so on. + /// Non-empty, NFC, and at most [`MAX_KIND_BYTES`] bytes. + pub kind: String, + /// The group the event belongs to. A node can route by it without + /// decrypting the payload. + pub group: Option, + /// The author's causal frontier: the latest events from any author that the + /// author had seen when writing this one. At most [`MAX_AFTER`] hashes, none + /// repeated. + pub after: Vec, +} + +/// The wire form of [`ChainExt`]: the same fields, plus the domain tag. Keys +/// this form does not name are refused. +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct Wire { + domain: String, + kind: String, + group: Option, + after: Vec, +} + +impl From for Wire { + fn from(ext: ChainExt) -> Self { + Self { + domain: DOMAIN_TAG.to_owned(), + kind: ext.kind, + group: ext.group, + after: ext.after, + } + } +} + +impl TryFrom for ChainExt { + type Error = ChainError; + + fn try_from(wire: Wire) -> Result { + if wire.domain != DOMAIN_TAG { + return Err(ChainError::Domain(wire.domain)); + } + let ext = Self { + kind: wire.kind, + group: wire.group, + after: wire.after, + }; + ext.validate()?; + Ok(ext) + } +} + +impl ChainExt { + /// Checks the rules every event's extension must meet. Both the builder and + /// the decoder apply them, so a signed event always passes them on receipt. + /// + /// # Errors + /// + /// Refuses more than [`MAX_AFTER`] `after` hashes, a hash repeated in + /// `after`, a `kind` that is empty or longer than [`MAX_KIND_BYTES`], and a + /// `kind` that is not NFC. + pub fn validate(&self) -> Result<(), ChainError> { + if self.after.len() > MAX_AFTER { + return Err(ChainError::TooManyAfter(self.after.len())); + } + let mut seen = HashSet::with_capacity(self.after.len()); + if !self.after.iter().all(|hash| seen.insert(hash)) { + return Err(ChainError::DuplicateAfter); + } + let length = self.kind.len(); + if !(1..=MAX_KIND_BYTES).contains(&length) { + return Err(ChainError::KindLength(length)); + } + if !is_nfc(&self.kind) { + return Err(ChainError::KindNotNfc); + } + Ok(()) + } +} + +/// A signed event header: its encoded bytes, its operation ID, and the decoded +/// header with its extension. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Event { + /// The operation ID: BLAKE3 over `bytes`, signature included. + pub id: Hash, + /// The encoded header, signature included. This is what is stored and sent. + pub bytes: Vec, + /// The header, with its extension decoded. + pub header: Header, +} + +/// Builds and signs an event header. +/// +/// `seq_num` counts the author's events from 0. Sequence 0 takes no backlink. +/// Every later sequence names the author's previous event's ID. `body` is the +/// payload: the header commits to its BLAKE3 hash, and the body itself is not +/// part of the event. +/// +/// # Errors +/// +/// Refuses an extension that fails [`ChainExt::validate`], and a backlink that +/// does not match `seq_num`. +pub fn sign( + key: &SigningKey, + seq_num: SeqNum, + backlink: Option, + body: Option<&[u8]>, + ext: ChainExt, +) -> Result { + ext.validate()?; + match (seq_num, backlink.is_some()) { + (0, true) => return Err(ChainError::UnexpectedBacklink), + (seq, false) if seq > 0 => return Err(ChainError::MissingBacklink(seq)), + _ => {} + } + + let mut builder = Header::::builder() + .seq_num(seq_num) + .backlink(backlink); + if let Some(body) = body { + builder = builder.body(body); + } + let header = builder.build(key, ext); + let bytes = header.encode(); + Ok(Event { + id: Hash::digest(&bytes), + bytes, + header, + }) +} + +/// Verifies and decodes received event bytes. Nothing but the bytes is trusted. +/// +/// # Errors +/// +/// Refuses bytes that are not canonical CBOR (`Cbor` or `NotCanonical`), and +/// bytes that p2panda's header decoder rejects: the layout, the version, or the +/// signature (`Header`). An extension that is not a valid [`ChainExt`] is +/// refused as well. A missing or unknown key, a wrong domain tag, or a failed +/// [`ChainExt::validate`] comes back as `Header`, with the rule in the message. +/// A key that serde would fill with a default, such as `group`, is `NotCanonical`. +pub fn decode(bytes: &[u8]) -> Result { + let root = canonical_value(bytes)?; + let header = Header::::try_from(AnyHeader::decode(bytes)?)?; + + // The extension is the last field of the header. It must serialize back to + // the same bytes. This refuses a key that serde fills in with a default, such + // as a missing `group`, which would otherwise decode as `None`. + let [.., received] = root.as_array()? else { + return Err(ChainError::Extension("the header has no fields".to_owned())); + }; + let again = Value::serialized(&header.extensions) + .map_err(|err| ChainError::Extension(err.to_string()))?; + if again.encode() != received.encode() { + return Err(ChainError::NotCanonical); + } + + Ok(Event { + id: Hash::digest(bytes), + bytes: bytes.to_vec(), + header, + }) +} + +/// Decodes strictly, and accepts the bytes only if they are the canonical +/// encoding of the value they hold. The value rules then apply to the whole +/// header. +fn canonical_value(bytes: &[u8]) -> Result, ChainError> { + let value = DecodeOptions::new() + .strictness(Strictness::STRICT) + .recursion_limit(RECURSION_LIMIT) + .length_limit(LENGTH_LIMIT) + .oom_mitigation(OOM_MITIGATION) + .decode_owned(bytes)?; + if value.encode() != bytes { + return Err(ChainError::NotCanonical); + } + check_value(&value)?; + Ok(value) +} + +/// The value rules. Text is NFC, map keys included. The only numbers are +/// integers. Floats, tags, and simple values other than false, true, and null +/// are refused. +fn check_value(value: &Value<'_>) -> Result<(), ChainError> { + match value { + Value::Unsigned(_) | Value::Negative(_) | Value::ByteString(_) => Ok(()), + Value::TextString(text) if is_nfc(text) => Ok(()), + Value::TextString(_) => Err(ChainError::CborRule("text is not NFC".to_owned())), + Value::Array(items) => items.iter().try_for_each(check_value), + Value::Map(map) => map.iter().try_for_each(|(key, val)| { + check_value(key)?; + check_value(val) + }), + Value::SimpleValue(simple) => match simple.to_u8() { + 20..=22 => Ok(()), + other => Err(ChainError::CborRule(format!("simple value {other}"))), + }, + Value::Float(_) => Err(ChainError::CborRule("a float".to_owned())), + Value::Tag(number, _) => Err(ChainError::CborRule(format!("tag {number}"))), + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use p2panda_core::Extensions; + + use super::*; + + /// The test key: the 32 bytes 00 through 1f. It is not a real key. + fn key() -> SigningKey { + SigningKey::from_bytes(&std::array::from_fn(|i| u8::try_from(i).unwrap())) + } + + fn hash(n: u8) -> Hash { + Hash::digest([n]) + } + + fn ext(kind: &str, group: Option, after: Vec) -> ChainExt { + ChainExt { + kind: kind.to_owned(), + group, + after, + } + } + + /// `count` distinct hashes: the digests of the counters `0..count`. + fn distinct(count: usize) -> Vec { + (0..count).map(|n| Hash::digest(n.to_le_bytes())).collect() + } + + // Extensions built outside `ChainExt`, so the decoder can be shown a header + // that the builder would never sign. Each one is signed with the test key, + // so only the decoder's own rules can refuse it. + + #[derive(Clone, Debug, Serialize, Deserialize)] + struct Forged { + domain: String, + kind: String, + group: Option, + after: Vec, + } + + #[derive(Clone, Debug, Serialize, Deserialize)] + struct NoGroup { + domain: String, + kind: String, + after: Vec, + } + + #[derive(Clone, Debug, Serialize, Deserialize)] + struct WithExtraKey { + domain: String, + kind: String, + group: Option, + after: Vec, + extra: u8, + } + + #[derive(Clone, Debug, Serialize, Deserialize)] + struct FloatKind { + domain: String, + kind: f64, + group: Option, + after: Vec, + } + + fn forged_form(domain: &str, kind: &str, after: Vec) -> Forged { + Forged { + domain: domain.to_owned(), + kind: kind.to_owned(), + group: None, + after, + } + } + + /// Signs any extension as sequence 0 with no body, the way `sign` would. + fn sign_raw(ext: E) -> Vec { + Header::::builder().build(&key(), ext).encode() + } + + #[test] + fn test_after_counts_at_the_limit_are_accepted() { + for count in [0, 1, MAX_AFTER] { + let event = sign(&key(), 0, None, None, ext("m", None, distinct(count))) + .expect("a frontier within the limit is signed"); + assert_eq!(decode(&event.bytes).unwrap(), event, "after {count}"); + } + } + + #[test] + fn test_after_one_past_the_limit_is_refused() { + let after = distinct(MAX_AFTER + 1); + assert!(matches!( + sign(&key(), 0, None, None, ext("m", None, after.clone())), + Err(ChainError::TooManyAfter(33)) + )); + assert!(matches!( + ext("m", None, after.clone()).validate(), + Err(ChainError::TooManyAfter(33)) + )); + // A header signed outside `sign` with the same frontier is refused too. + let forged = sign_raw(Forged { + domain: DOMAIN_TAG.to_owned(), + kind: "m".to_owned(), + group: None, + after, + }); + assert!(decode(&forged).is_err()); + } + + #[test] + fn test_repeated_after_hashes_are_refused() { + let twice = vec![hash(1), hash(2), hash(1)]; + assert!(matches!( + ext("m", None, twice).validate(), + Err(ChainError::DuplicateAfter) + )); + let adjacent = vec![hash(7), hash(7)]; + assert!(matches!( + sign(&key(), 0, None, None, ext("m", None, adjacent)), + Err(ChainError::DuplicateAfter) + )); + assert!(ext("m", None, distinct(3)).validate().is_ok()); + } + + #[test] + fn test_kind_length_bounds() { + assert!(matches!( + ext("", None, vec![]).validate(), + Err(ChainError::KindLength(0)) + )); + let longest = "a".repeat(MAX_KIND_BYTES); + assert!(ext(&longest, None, vec![]).validate().is_ok()); + let one_over = "a".repeat(MAX_KIND_BYTES + 1); + assert!(matches!( + ext(&one_over, None, vec![]).validate(), + Err(ChainError::KindLength(65)) + )); + // Measured in bytes, not characters: 32 two-byte letters is 64 bytes. + let multibyte = "é".repeat(32); + assert_eq!(multibyte.len(), MAX_KIND_BYTES); + assert!(ext(&multibyte, None, vec![]).validate().is_ok()); + let multibyte_over = "é".repeat(33); + assert!(matches!( + ext(&multibyte_over, None, vec![]).validate(), + Err(ChainError::KindLength(66)) + )); + } + + #[test] + fn test_kind_must_be_nfc() { + // "e" followed by a combining acute accent is not NFC. The precomposed + // letter is. + assert!(matches!( + ext("e\u{301}", None, vec![]).validate(), + Err(ChainError::KindNotNfc) + )); + assert!(ext("\u{e9}", None, vec![]).validate().is_ok()); + assert!(sign(&key(), 0, None, None, ext("e\u{301}", None, vec![])).is_err()); + } + + #[test] + fn test_group_none_and_some_round_trip() { + for group in [None, Some(hash(9))] { + let event = sign( + &key(), + 0, + None, + None, + ext("group.policy", group, distinct(2)), + ) + .unwrap(); + let decoded = decode(&event.bytes).unwrap(); + assert_eq!(decoded.header.extensions.group, group); + assert_eq!(decoded.header.extensions.kind, "group.policy"); + assert_eq!(decoded.header.extensions.after, distinct(2)); + } + } + + #[test] + fn test_sequence_and_backlink_must_agree() { + assert!(matches!( + sign(&key(), 0, Some(hash(1)), None, ext("m", None, vec![])), + Err(ChainError::UnexpectedBacklink) + )); + assert!(matches!( + sign(&key(), 1, None, None, ext("m", None, vec![])), + Err(ChainError::MissingBacklink(1)) + )); + let second = sign(&key(), 1, Some(hash(1)), None, ext("m", None, vec![])).unwrap(); + assert_eq!(second.header.seq_num, 1); + assert_eq!(second.header.backlink, Some(hash(1))); + } + + #[test] + fn test_a_signed_event_decodes_to_the_same_event() { + let body = b"payload bytes"; + let event = sign( + &key(), + 0, + None, + Some(body), + ext("message", Some(hash(3)), distinct(5)), + ) + .unwrap(); + assert_eq!(event.id, Hash::digest(&event.bytes)); + assert_eq!(event.header.payload_hash, Some(Hash::digest(body))); + assert_eq!(decode(&event.bytes).unwrap(), event); + } + + #[test] + fn test_signing_the_same_event_twice_gives_the_same_bytes() { + let make = || sign(&key(), 0, None, None, ext("m", None, distinct(4))).unwrap(); + assert_eq!(make().bytes, make().bytes); + } + + #[test] + fn test_domain_tag_is_checked() { + let bytes = sign_raw(forged_form("id.events.v0", "m", vec![])); + let err = decode(&bytes).unwrap_err(); + assert!( + err.to_string().contains("domain tag"), + "unexpected error: {err}" + ); + // A header with no domain key at all is refused too. + let bytes = sign_raw(NoGroup { + domain: String::new(), + kind: "m".to_owned(), + after: vec![], + }); + assert!(decode(&bytes).is_err()); + } + + #[test] + fn test_a_missing_group_key_is_refused_as_not_canonical() { + // serde would decode a missing `group` as `None`. The re-encoding then + // differs from the received bytes, so the decoder refuses them. + let bytes = sign_raw(NoGroup { + domain: DOMAIN_TAG.to_owned(), + kind: "m".to_owned(), + after: vec![], + }); + assert!(matches!(decode(&bytes), Err(ChainError::NotCanonical))); + } + + #[test] + fn test_an_unknown_extension_key_is_refused() { + let bytes = sign_raw(WithExtraKey { + domain: DOMAIN_TAG.to_owned(), + kind: "m".to_owned(), + group: None, + after: vec![], + extra: 1, + }); + assert!(decode(&bytes).is_err()); + } + + #[test] + fn test_a_float_where_text_belongs_is_refused() { + let bytes = sign_raw(FloatKind { + domain: DOMAIN_TAG.to_owned(), + kind: 1.5, + group: None, + after: vec![], + }); + assert!(decode(&bytes).is_err()); + } + + #[test] + fn test_a_header_without_an_extension_is_refused() { + let bytes = Header::<()>::builder().build(&key(), ()).encode(); + assert!(matches!( + decode(&bytes), + Err(ChainError::Header(HeaderError::MissingExtensions)) + )); + } + + #[test] + fn test_a_changed_signature_is_refused() { + let event = sign(&key(), 0, None, None, ext("m", None, distinct(2))).unwrap(); + let mut bytes = event.bytes; + // The signature is the byte string after the key: 0x58 0x40, then 64 bytes. + assert_eq!(bytes[37], 0x40, "layout changed, fix the offset"); + bytes[48] ^= 0x01; + assert!(matches!( + decode(&bytes), + Err(ChainError::Header(HeaderError::InvalidSignature)) + )); + } + + #[test] + fn test_a_non_shortest_integer_is_refused() { + // Sequence 0 written as 0x18 0x00 instead of 0x00. The strict decoder + // refuses the encoding before any signature check. + let event = sign(&key(), 0, None, None, ext("m", None, vec![])).unwrap(); + assert_eq!(event.bytes[103], 0x00, "layout changed, fix the offset"); + let mut bytes = event.bytes[..103].to_vec(); + bytes.extend([0x18, 0x00]); + bytes.extend(&event.bytes[104..]); + assert!(matches!(decode(&bytes), Err(ChainError::Cbor(_)))); + } + + #[test] + fn test_empty_and_truncated_input_is_refused() { + assert!(decode(&[]).is_err()); + let event = sign(&key(), 0, None, None, ext("m", None, distinct(2))).unwrap(); + for cut in [1, event.bytes.len() / 2, event.bytes.len() - 1] { + assert!(decode(&event.bytes[..cut]).is_err(), "cut at {cut}"); + } + } +} diff --git a/pkgs/id/src/lib.rs b/pkgs/id/src/lib.rs index e675a9a9f1..8212f8fd9f 100644 --- a/pkgs/id/src/lib.rs +++ b/pkgs/id/src/lib.rs @@ -155,6 +155,7 @@ pub mod access; #[cfg(feature = "world")] pub mod artifact; +pub mod chain; pub mod cli; pub mod commands; pub mod connectivity; diff --git a/pkgs/id/tests/README.md b/pkgs/id/tests/README.md index cdc371fd9d..225b3ada78 100644 --- a/pkgs/id/tests/README.md +++ b/pkgs/id/tests/README.md @@ -14,8 +14,12 @@ in the authorization. - `tuple_properties.rs`: property tests for the tuple encoding in `src/tuple.rs`, and a fixed-seed fuzz run. +- `chain_properties.rs`: property tests for the event header in `src/chain.rs`: + round trips, canonical re-encoding, the `after` limit, and a decoder that never + panics. - `regression_replay.rs`: replays every case in `regressions/`. - `common/mod.rs`: the tuple checker shared by the property tests and the replay. +- `common/chain.rs`: the event decoder's contract, shared the same way. - `regressions/`: checked-in failing cases. See its [README](regressions/README.md). ## Running diff --git a/pkgs/id/tests/chain_properties.rs b/pkgs/id/tests/chain_properties.rs new file mode 100644 index 0000000000..aa5e550960 --- /dev/null +++ b/pkgs/id/tests/chain_properties.rs @@ -0,0 +1,164 @@ +//! Property tests for the event header in `src/chain.rs`. +//! +//! The properties use the default case count, which `PROPTEST_CASES` raises. +//! Failures are not written to `proptest-regressions/`: the minimal input goes +//! into `tests/regressions/chainext.txt` instead (see +//! `tests/regressions/README.md`). + +#![allow(clippy::unwrap_used, clippy::expect_used)] + +mod common; + +use common::chain::check_event_bytes; +use id::chain::{ChainExt, DOMAIN_TAG, MAX_AFTER, decode, sign}; +use p2panda_core::{Extensions, Hash, Header, SigningKey}; +use proptest::prelude::*; +use proptest::sample::Index; +use proptest::test_runner::TestCaseError; +use serde::{Deserialize, Serialize}; + +/// The test key: the 32 bytes 00 through 1f. It is not a real key. +fn key() -> SigningKey { + SigningKey::from_bytes(&std::array::from_fn(|i| u8::try_from(i).unwrap())) +} + +fn config() -> ProptestConfig { + ProptestConfig { + failure_persistence: None, + ..ProptestConfig::default() + } +} + +/// Text of 1 to 20 characters from ASCII and from characters that are already +/// NFC. At most 60 bytes, so it is always inside `MAX_KIND_BYTES`. +fn kind() -> impl Strategy { + "[a-z.é日-]{1,20}" +} + +fn hash() -> impl Strategy { + any::<[u8; 32]>().prop_map(Hash::from) +} + +/// Up to `max` distinct hashes, in no particular order. +fn frontier(max: usize) -> impl Strategy> { + prop::collection::hash_set(any::<[u8; 32]>(), 0..=max) + .prop_map(|set| set.into_iter().map(Hash::from).collect()) +} + +/// More than `MAX_AFTER` distinct hashes. +fn oversized_frontier() -> impl Strategy> { + prop::collection::hash_set(any::<[u8; 32]>(), MAX_AFTER + 1..=MAX_AFTER + 40) + .prop_map(|set| set.into_iter().map(Hash::from).collect()) +} + +/// Any extension the builder accepts. +fn chain_ext() -> impl Strategy { + (kind(), prop::option::of(hash()), frontier(MAX_AFTER)) + .prop_map(|(kind, group, after)| ChainExt { kind, group, after }) +} + +/// An extension the builder would never sign. `after` is not limited here, so +/// the decoder is the only check that can refuse it. +#[derive(Clone, Debug, Serialize, Deserialize)] +struct Forged { + domain: String, + kind: String, + group: Option, + after: Vec, +} + +/// Signs any extension as sequence 0 with no body, the way `sign` does. +fn sign_raw(ext: E) -> Vec { + Header::::builder().build(&key(), ext).encode() +} + +proptest! { + #![proptest_config(config())] + + /// A signed event decodes to the same event, with the same extension. + #[test] + fn test_signed_chain_ext_round_trips( + ext in chain_ext(), + body in prop::option::of(prop::collection::vec(any::(), 0..128)), + seq in 0u32..1_000, + backlink in hash(), + ) { + let backlink = (seq > 0).then_some(backlink); + let event = sign(&key(), seq, backlink, body.as_deref(), ext.clone()) + .map_err(|err| TestCaseError::fail(err.to_string()))?; + let decoded = decode(&event.bytes).map_err(|err| TestCaseError::fail(err.to_string()))?; + prop_assert_eq!(&decoded, &event); + prop_assert_eq!(&decoded.header.extensions, &ext); + prop_assert_eq!(decoded.id, Hash::digest(&event.bytes)); + } + + /// Re-encoding a decoded event gives the same bytes, and signing its + /// extension again gives the same bytes too. + #[test] + fn test_canonical_encoding_is_stable_on_reencode(ext in chain_ext()) { + let event = sign(&key(), 0, None, None, ext) + .map_err(|err| TestCaseError::fail(err.to_string()))?; + let decoded = decode(&event.bytes).map_err(|err| TestCaseError::fail(err.to_string()))?; + prop_assert_eq!(&decoded.header.encode(), &event.bytes); + let again = sign(&key(), 0, None, None, decoded.header.extensions) + .map_err(|err| TestCaseError::fail(err.to_string()))?; + prop_assert_eq!(&again.bytes, &event.bytes); + } + + /// More than `MAX_AFTER` hashes are refused by the builder, by validation, + /// and by the decoder, whatever the count and the hashes. + #[test] + fn test_after_above_the_limit_is_always_refused(after in oversized_frontier()) { + let ext = ChainExt { + kind: "m".to_owned(), + group: None, + after: after.clone(), + }; + prop_assert!(sign(&key(), 0, None, None, ext.clone()).is_err()); + prop_assert!(ext.validate().is_err()); + let forged = sign_raw(Forged { + domain: DOMAIN_TAG.to_owned(), + kind: "m".to_owned(), + group: None, + after, + }); + prop_assert!(decode(&forged).is_err()); + } + + /// The decoder never panics on random bytes, and whatever it accepts holds + /// up under the replay's checks. + #[test] + fn test_decoder_never_panics_on_random_bytes( + bytes in prop::collection::vec(any::(), 0..1024), + ) { + check_event_bytes(&bytes).map_err(TestCaseError::fail)?; + } + + /// Changing any one byte of a signed event makes it invalid. The signature + /// covers every field, and a changed encoding is not canonical, so each + /// such change is refused. + #[test] + fn test_a_single_changed_byte_is_always_refused( + ext in chain_ext(), + body in prop::option::of(prop::collection::vec(any::(), 1..64)), + index in any::(), + flip in 1u8..=255, + ) { + let event = sign(&key(), 0, None, body.as_deref(), ext) + .map_err(|err| TestCaseError::fail(err.to_string()))?; + let mut bytes = event.bytes; + let at = index.index(bytes.len()); + bytes[at] ^= flip; + prop_assert!(decode(&bytes).is_err(), "byte {at} changed by {flip:#x} was accepted"); + check_event_bytes(&bytes).map_err(TestCaseError::fail)?; + } + + /// A proper prefix of a signed event is never a valid event. + #[test] + fn test_a_truncated_event_is_always_refused(ext in chain_ext(), cut in any::()) { + let event = sign(&key(), 0, None, None, ext) + .map_err(|err| TestCaseError::fail(err.to_string()))?; + let at = cut.index(event.bytes.len()); + prop_assert!(decode(&event.bytes[..at]).is_err(), "a prefix of {at} bytes was accepted"); + } +} diff --git a/pkgs/id/tests/common/chain.rs b/pkgs/id/tests/common/chain.rs new file mode 100644 index 0000000000..1290d8fd05 --- /dev/null +++ b/pkgs/id/tests/common/chain.rs @@ -0,0 +1,36 @@ +//! The event decoder's contract, shared by the property tests and the regression +//! replay. The checks are the same for every byte string, so a case found by a +//! property run can be replayed unchanged. + +use id::chain::decode; +use p2panda_core::Hash; + +/// Checks the decoder's contract for one byte string. +/// +/// The decoder must not panic: a panic fails the caller. It may refuse the +/// bytes. If it accepts them, the accepted event must hold up: its operation ID +/// is BLAKE3 over the bytes, its extension passes the validation rules, and +/// decoding the same bytes again gives the same event. +/// +/// # Errors +/// +/// Describes the first part of the contract that does not hold. +pub fn check_event_bytes(bytes: &[u8]) -> Result<(), String> { + let Ok(event) = decode(bytes) else { + return Ok(()); + }; + if event.id != Hash::digest(bytes) { + return Err(format!("the id of {bytes:?} is not BLAKE3 over the bytes")); + } + event + .header + .extensions + .validate() + .map_err(|err| format!("accepted {bytes:?}, but its extension fails: {err}"))?; + let again = + decode(&event.bytes).map_err(|err| format!("decoding {bytes:?} again failed: {err}"))?; + if again != event { + return Err(format!("decoding {bytes:?} again gave a different event")); + } + Ok(()) +} diff --git a/pkgs/id/tests/common/mod.rs b/pkgs/id/tests/common/mod.rs index 7f5fc1cd8f..7c98f89e29 100644 --- a/pkgs/id/tests/common/mod.rs +++ b/pkgs/id/tests/common/mod.rs @@ -1,13 +1,16 @@ -//! Shared tuple checker for the property tests and the regression replay. +//! Shared checkers for the property tests and the regression replay. //! -//! A tuple element is either a byte string (`bytes` tag) or a UTF-8 string -//! (`string` tag). [`check_pair`] holds the properties the encoding must keep -//! for any two elements: decoding gives back the original values, encoded order -//! follows value order, and a complete field is a prefix of another encoding -//! only when the values are equal. +//! The tuple checker: a tuple element is either a byte string (`bytes` tag) or a +//! UTF-8 string (`string` tag). [`check_pair`] holds the properties the encoding +//! must keep for any two elements: decoding gives back the original values, +//! encoded order follows value order, and a complete field is a prefix of +//! another encoding only when the values are equal. The event checker lives in +//! [`chain`]. #![allow(dead_code)] // each test crate uses a different part of this module +pub mod chain; + use std::cmp::Ordering; use id::tuple::{TupleEncoder, TupleValue, decode}; diff --git a/pkgs/id/tests/regression_replay.rs b/pkgs/id/tests/regression_replay.rs index c1288e1ed5..a2da1da200 100644 --- a/pkgs/id/tests/regression_replay.rs +++ b/pkgs/id/tests/regression_replay.rs @@ -3,9 +3,11 @@ //! Each file under `tests/regressions/` is named for its area and holds one //! case per line: `areainputexpected`. Blank lines and lines starting //! with `#` are skipped. The input uses the area's own syntax; for `tuple` it is -//! two elements separated by a space (see `common::parse_value`). The only -//! expected result is `ok`: the property must hold for that input. See -//! `tests/regressions/README.md` for how a fuzz failure becomes a case. +//! two elements separated by a space (see `common::parse_value`), and for +//! `chainext` it is one `b:` element holding the event bytes (see +//! `common::chain`). The only expected result is `ok`: the property must hold +//! for that input. See `tests/regressions/README.md` for how a fuzz failure +//! becomes a case. #![allow(clippy::unwrap_used, clippy::expect_used)] @@ -13,7 +15,8 @@ mod common; use std::path::{Path, PathBuf}; -use common::{check_pair, parse_value}; +use common::chain::check_event_bytes; +use common::{Value, check_pair, parse_value}; /// Split one line into its three fields. fn parse_line(line: &str) -> Result<(&str, &str, &str), String> { @@ -41,6 +44,12 @@ fn replay_case(area: &str, input: &str, expected: &str) -> Result<(), String> { })?; check_pair(&parse_value(left)?, &parse_value(right)?) } + "chainext" => match parse_value(input)? { + Value::Bytes(bytes) => check_event_bytes(&bytes), + Value::Text(_) => Err(format!( + "chainext input {input:?} must be one b: element" + )), + }, other => Err(format!("unknown area {other:?}")), } } @@ -112,6 +121,10 @@ fn test_replay_rejects_malformed_cases() { replay_case("nope", "s:a s:a", "ok").is_err(), "unknown area" ); + assert!( + replay_case("chainext", "s:a", "ok").is_err(), + "chainext takes bytes, not a string" + ); } #[test] diff --git a/pkgs/id/tests/regressions/README.md b/pkgs/id/tests/regressions/README.md index 6e73a85ae2..5271e66b35 100644 --- a/pkgs/id/tests/regressions/README.md +++ b/pkgs/id/tests/regressions/README.md @@ -17,7 +17,8 @@ areainputexpected - `area` must match the file name: `tuple.txt` holds `tuple` cases. - `input` uses the area's syntax. For `tuple` it is two elements separated by one space. Each element is `s:` (a UTF-8 string) or `b:` (a byte - string). + string). For `chainext` it is one `b:` element: the bytes given to the + event decoder in `src/chain.rs`. - `expected` is `ok`: the property must hold for that input. - Blank lines and lines starting with `#` are skipped. diff --git a/pkgs/id/tests/regressions/chainext.txt b/pkgs/id/tests/regressions/chainext.txt new file mode 100644 index 0000000000..929e8282b7 --- /dev/null +++ b/pkgs/id/tests/regressions/chainext.txt @@ -0,0 +1,29 @@ +# Known-bad event bytes, replayed on every run. See README.md for the format. +# Each line: area, input (one b: element holding the event bytes), expected result. +# +# Every case sits on a refusal boundary of the event decoder in src/chain.rs: the +# decoder must refuse it without panicking, and the checks in tests/common/chain.rs +# must hold for it. They are seeds written by hand, not fuzz finds. A property run +# that finds a failing input appends its minimal bytes here. +# valid event +chainext b:\x86\x01X\x20\x03\xa1\x07\xbf\xf3\xce\x10\xbe\x1dp\xdd\x18\xe7K\xc0\x99g\xe4\xd60\x9b\xa5\x0d_\x1d\xdc\x86d\x12U1\xb8X@b\xc0\xd7\xcf\xc7)\x99\x04\x7f\xc5\xcaH\x10\xa0\xb2\x09\x0a@9J\xda\xe7\xa2E}\xcfS\xbf\xbd\x84\x9d\xcd=j\x5c\xd1\x91\xa5\xea\xc3\xa8_\x0c\x8f\xa6\xbbr\xb2\x1e\xaf\xd4\xd5\xd4E\xba<\xb7A\x13S=\xcax\xa7O6\xf5\x9e\xda\xa4\x18\x95\xc9F\xa4dkindgmessageeafter\x83X\x20-:\xde\xdf\xf1\x1ba\xf1L\x88n5\xaf\xa06sm\xcd\x87\xa7M'\xb5\xc1Q\x02%\xd0\xf5\x92\xe2\x13X\x20H\xfcr\x1f\xbb\xc1r\xe0\x92_\xa2z\xf1g\x1d\xe2%\xba\x92q4\x80)\x98\xb1\x0a\x15h\xa1\x88e+X\x20\xab\x13\xbe\xdfB\xe8K\xae\x0f|b\xc7\xddj\x8a\xdaW\x1e\x88)\xbe\xd6\xeaU\x82\x17\xf06\x1b^%\xd0egroupX\x20D\x8b\xd8\xdd\x96$\x15Ji\x0f\x8e\x84\xdcR\xd6\xf63\xba|\xd5E\xc4\xd3\xc9\xb4\xe0\xf6\xa2\xf6\xfaq\xf4fdomainlid.events.v1 ok +# forged: 33 after hashes +chainext b:\x86\x01X\x20\x03\xa1\x07\xbf\xf3\xce\x10\xbe\x1dp\xdd\x18\xe7K\xc0\x99g\xe4\xd60\x9b\xa5\x0d_\x1d\xdc\x86d\x12U1\xb8X@\xbe\xc1:q\xc9\xf1\xf2\x9f\x83XZ\xac\xee\xb6DR\xa7z\x84\x83\xefc6L\xab\xc3\xc6\xe1H\xfd\x17DQ"\x1e(\x95\x0a8IR\x8b\xdc(v\xd5\xc7\xdc\xa4\xe3\xfa\x9f+\x87n\x9a&\x92\x05\xb0e\xf3\x80\x02\0\0\xa4dkindameafter\x98!X\x20-:\xde\xdf\xf1\x1ba\xf1L\x88n5\xaf\xa06sm\xcd\x87\xa7M'\xb5\xc1Q\x02%\xd0\xf5\x92\xe2\x13X\x20H\xfcr\x1f\xbb\xc1r\xe0\x92_\xa2z\xf1g\x1d\xe2%\xba\x92q4\x80)\x98\xb1\x0a\x15h\xa1\x88e+X\x20\xab\x13\xbe\xdfB\xe8K\xae\x0f|b\xc7\xddj\x8a\xdaW\x1e\x88)\xbe\xd6\xeaU\x82\x17\xf06\x1b^%\xd0X\x20\xe1\xe0\xe8\x1dn\xa3\x9b\x0c\xf8\xb8o\xfdD\x09!\x01\x1fW@\x0c\xbc?v\xa8\xa1q\x90j\x9b\x8du\x05X\x20\x0c8\x9at>4\xfd\xa45\xfb\xd5u\xbb\x88\x9d\xbc\x0d>f\xb9\xf9\xd8\x1e\0\xbe3\xb7\x18\x85\x09\xe7\xebX\x20\x84\xcb@\xe7O\x0e\x85k\xb4\xbb\x91#><\xb7A\x13S=\xcax\xa7O6\xf5\x9e\xda\xa4\x18\x95\xc9FX\x20\x1c1\x0bk\xda\xddi\x99\x1c\xd4\xe5\xdb\xef\x96\xc2c\x856\xc3+SN>\xd6G\x85\x84k\xfc\xeb\xd2\x06X\x20D\x8b\xd8\xdd\x96$\x15Ji\x0f\x8e\x84\xdcR\xd6\xf63\xba|\xd5E\xc4\xd3\xc9\xb4\xe0\xf6\xa2\xf6\xfaq\xf4X\x20.\xf3\xe0\xdd\xa5);\xda\x96]\x0a\xdc\xed\xfc}8rD\xacsj`\x14\xa7\x20\xc1\xd6?\xa0\xed\xe0/X\x20r\x19\xaa\x10\x99\xce\xd7D\x5c[\xf9I\x99\x0f\xf7\xd9\xf6\xb7\x1a\x94\xb8\xec\x02\xb3\xeba\xfb\x17Zf\xba%X\x20)Q\x92\xea\x1e\xc8VmV;\x1au\x87\xe5\xf0\x19\x85\x80\xcd\xbd\x048B\xf5\x09\x0aL\x19|\x20\xc6zX\x20\xca\xeb\xfd8Y\xf58\x0e\xffTqQHDAx\xbe\x18\xed\xef\xa3\xd1\xce\xae'Y\x82\xf1\xa2\x82J\x91X\x20\xb7o\xfaw\x80&\xe1\x88Jk\x1d\x10]7\xa8r+\x93\x10"p\x94\x88o\x86\xf8\xc9\x83\xe6aG\x96X\x20\x8e2!\xf5\x94\x07\xcbE\x20\xcaV/\xda"\xdd\xe2.\xdf\xed,\x10,So\x11\xb7FL\xd8\xa0\xc6]X\x201b\x5c\xf6\x88\x16\xaaTz\x0euQ\xc0-O\xc9\xe6\xf2*\xf7i\xcbv\xb6\xd7u\xf0R\x15AF\x0cX\x20\x0b\xf6\xb9U\xab\xb4\x96\x81\x91\xeb\xf8\x86\x9d\x03\xae_t\xaa\x058\xff\xdb\xdd\xea\xfc\x97\x0cP}\xa7\xd7\x1dX\x20\xb3]J\xb3\x92\xfb\x95,\x8dv%\xef\xbf\xaf\xf8\xaf,\x8c\xeb\xf2\x0d\x1f\xf9xJ\x8f\xfe\x08\xdcf~\x12X\x20\xe2\x81\xfa\xe0\xc5\x8a\x02jEq9\xc0\x8c\xa6o\x97\xbe1R\x8e\xc6\xdb]\xbfv\xb8\xb0\xe5\xce\x99x\x8dX\x20f\xfe\x99b\x9b\x96\x88\xc2\xcc\x06+{=\xbd\x98\x7f\xf1;\xde\x20\xad\xeb\x0d\x19\xf5\xce\x9b\xd7\xb2\xb6\x03\x96X\x20\x04\x85G=y\xcc\xb7q\xeakf@6\xf5\x064\x1dhM\xdf\x8a\x11\xbc\xdd\xbb#-\xc7\x87\x0d\xb2kX\x20\xca\x9f\xba)l\xab\x1f\xfb\xd9Ys\x11\xa1\xd7\x9a\x06\xdf\xaf\x09\x09\x99Z\0\xa9\x8a~6\x1f\xb6qX\xe9X\x20l\x16\xc0VB\x9fy(\xdc\x13\xe1e\xf6\xa9\xb6\xfe\xbb\xa2g}\x01\xc0ov\xde\xa9\xa1\x8c\xac\x86%\x07X\x20\x13\x14\xb6\x98\xfb\xb7N\xd2\xc4\xf2\xc3m\xa6n=\x87\xeb\xbbK\xc9i\x03\xfd\xf7\x96\xd3\xdc\x8c/\xbb\x95\xd8X\x20\x94\xf2\x16\xd8\xf6\xc9\x9a_\xdaJ\x9a{\xe9\xd75\xf5\xae\xc3M\xc7\xf0\x88\x83\x19\x0d]\xccYc\xf1\xd7&X\x207\xb5]\x0b\xff\xa6\x14\xd63\xd3\xfa\x9d\x9b\xa4\x1b\x98\x0d\x0f\x8a\xccl\xdb\xf4\xf2n]\xfc\xcaE+\x85)X\x20\x9a\xfe\x02O\xa1\xee\xbd$\xfc:\xefWs\xfdo\x0d\xac\xd4\xe1\xf2XC!\xb7\x86\xc92S\xea\xcb\xbfsX\x20\xbfaz\x93i\xddg\xafu\x12\xb0up\xf6/\xafR;\xff\xfe\xdfxU\xfau\xbf\xffd]8\x1e\xebX\x20\x16\xb1k\xb1j\x85L\xae\x1f\xdc\xe0\x03\x8f\xfb|\x87\xa5\x16i\xda\x08\xa7\x8f#B\xf4\xd1\xabL\x14XfX\x20}\xd9s\xda\xf6e\xd4\x9b\xd7\xc8\x1b\xf3\xe9-\x82\x8aH\xef\xcd\xa0\xda\xa6\x1c(\xfa\xf7\xa4"\x81\xa6\x8e\x19X\x20\xbc\x02Jkf\x89\x0e\xcf\xaex_\xd3\x11q\x086\xd9R\xf8\x8a\x03\x8d\x94\xbe\xdf}\x04\xe5\x93\x95\xccUX\x20\xeb\x90\xb7G\xc2\xc4\x8c/\xda\xdbJ\xf4\x82>\xec}\xb9\xd2\xd8\x18\xef\xbc\xc1e\xf3\xef6\xc9xS\xae6X\x20\xca\xee\x11\x07\xaa\x7f\x12\x82`\x14\xbb\xa0a\x83\x97\xb9D\xd0o3\x99E\xf0\xde>f\xa1P\xa02\xf3\xb5X\x20\0&<\xa9\xf5\x7fqw\xf4\x95\xe3q\x1f\x8c\xddY\x96z\x0a\x1aM\xe8\x95\xb1\xeb\xeeVl\xd1\x88>\xd4egroup\xf6fdomainlid.events.v1 ok +# forged: missing group key +chainext b:\x86\x01X\x20\x03\xa1\x07\xbf\xf3\xce\x10\xbe\x1dp\xdd\x18\xe7K\xc0\x99g\xe4\xd60\x9b\xa5\x0d_\x1d\xdc\x86d\x12U1\xb8X@\xbf\x9am53:\xa5s\x9c\x88D\x95\xc8L\xf2\xb2\xff\xa0\xbbs\xf2lY\x84S\xd9%;\x07q1\xe1B\x91\x971\x84R\xbd\x95\x9b\xe3H\x81\xae\x9a\x20\x99\xed\x85{\x1a\x02\xd7p\xa4(\x06\x8e\x17y\x7f\xcc\x05\0\0\xa3dkindameafter\x80fdomainlid.events.v1 ok +# forged: unknown extension key +chainext b:\x86\x01X\x20\x03\xa1\x07\xbf\xf3\xce\x10\xbe\x1dp\xdd\x18\xe7K\xc0\x99g\xe4\xd60\x9b\xa5\x0d_\x1d\xdc\x86d\x12U1\xb8X@)\x9cqkYM\x01\xa1X@\xa0P\x15F\x98\xab\xb7\xb0\xfc\x1c\xe2\x10\xdd\xcc>j\xcd%X\xff8\xda\xe7\x0fkR\x1df\xdb\x8d\xf0\xee\xd0>\xfd\x13\xef.\xf2\xdf\xd7A\x18\xb3\x9e\x99a`\xfe\xef\xd2\xc6(\x06\0\0\xa5dkindameafter\x80eextra\x01egroup\xf6fdomainlid.events.v1 ok +# forged: kind not NFC +chainext b:\x86\x01X\x20\x03\xa1\x07\xbf\xf3\xce\x10\xbe\x1dp\xdd\x18\xe7K\xc0\x99g\xe4\xd60\x9b\xa5\x0d_\x1d\xdc\x86d\x12U1\xb8X@^\xd0\x9a\x5c\x07[(mx\xf5\xac\x0eF\x92sM\xb4\xfd\xf0\x8a\x99/H\xcf\xb3\xa5C\x0b\x81;\0SDa\xd0\xf6.\xed>qy\xab\x17\xff%\x1aQ\xd1\xb8\x0d\x9eBQ|x\xbc\xfe\xcd\xf1\x91T\xc7\x87\x0e\0\0\xa4dkindce\xcc\x81eafter\x80egroup\xf6fdomainlid.events.v1 ok +# forged: wrong domain tag +chainext b:\x86\x01X\x20\x03\xa1\x07\xbf\xf3\xce\x10\xbe\x1dp\xdd\x18\xe7K\xc0\x99g\xe4\xd60\x9b\xa5\x0d_\x1d\xdc\x86d\x12U1\xb8X@\xa4\xb7\xf7\xa1\xb1Q\xbd`\xc1\x17-\xd6\x9d\xab`\xa2\xee\xb9o\xfd\x9enB\xaf\xc2\xdb\xf0\xa2\x15+\xf1\xd1\x11[\x8e\x1b\xab\x17\xed\x9d\x99O\xacs\x92\x95\x12\x85\xe2\x095\x1b-\xf5l\x91\xd6\xe5eP\xfff\xf6\x0b\0\0\xa4dkindameafter\x80egroup\xf6fdomainlid.events.v0 ok +# header without an extension (the S5 golden header) +chainext b:\x86\x01X\x20\x03\xa1\x07\xbf\xf3\xce\x10\xbe\x1dp\xdd\x18\xe7K\xc0\x99g\xe4\xd60\x9b\xa5\x0d_\x1d\xdc\x86d\x12U1\xb8X@\xbe1\xbe$\x1bZ\x99\x15\x19L\xaf\xab\xb3\xd0\xff\xb8\xf7\xa2\xbezz\x91\xa9\xa68D\x9c\xeb\xfc\xd7\xd9o\x9b\xde\x95\xd6x.\xb7\x06\x06\xf2\xe8[\x95v\x0a\x90\xd7}\xab\x84_\xdb\x1e\xcd\xa8C\xde\xfa~N\xcf\x0f\x18#X\x20\x9f\x91u\xfbU\xf6~vs\xc1a>K\xa0s`\xaf\xb5\x84\xa2d\x07\xf3\xff\xc6\xdf\xe5\xaeR\xfd\xdfM\0 ok +# empty input +chainext b: ok +# truncated valid event +chainext b:\x86\x01X\x20\x03\xa1\x07\xbf\xf3\xce\x10\xbe\x1dp\xdd\x18\xe7K\xc0\x99g\xe4\xd60\x9b\xa5\x0d_\x1d\xdc\x86d\x12U1\xb8X@b\xc0\xd7\xcf\xc7)\x99\x04\x7f\xc5\xcaH\x10\xa0\xb2\x09\x0a@9J\xda\xe7\xa2E}\xcfS\xbf\xbd\x84\x9d\xcd=j\x5c\xd1\x91\xa5\xea\xc3\xa8_\x0c\x8f\xa6\xbbr\xb2\x1e\xaf\xd4\xd5\xd4E\xba Date: Sun, 11 Oct 2026 17:56:17 -0500 Subject: [PATCH 05/30] test(id): golden and dcbor vectors for ChainExt headers [P1.7] The S5 golden header (Header<()>, plain body map, seq 0, the test key) keeps its operation ID 90acd5f7... and signature be31be24.... That header has no extension, so it pins p2panda's layout and signature rule, not ChainExt. The four other S5 canonical vectors are pinned as recorded. Two pinned ChainExt events are checked against dcbor, which builds each header and its signed bytes with its own encoder: one plain, one with a body, a backlink, and a group. The bytes must match, and each signature must verify over dcbor's signed bytes. --- pkgs/id/src/chain.rs | 313 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 313 insertions(+) diff --git a/pkgs/id/src/chain.rs b/pkgs/id/src/chain.rs index 1d10cb744c..7b8240dbcd 100644 --- a/pkgs/id/src/chain.rs +++ b/pkgs/id/src/chain.rs @@ -605,3 +605,316 @@ mod tests { } } } + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod golden { + //! Golden vectors and the dcbor cross-check. The S5 values are the ones the spike + //! recorded (`spikes/shared/s5-cbor/RESULTS.md` and `run-output.md`). dcbor's encoder is + //! independent of cbor-core, so agreement between them is evidence that the canonical + //! bytes are right, not only that they are stable. + + use std::collections::BTreeMap; + + use cbor_core::Value; + use dcbor::{ByteString, CBOR}; + use p2panda_core::{AnyHeader, Hash, Header, SigningKey}; + + use super::{ChainExt, DOMAIN_TAG, Event, decode, sign}; + + /// The test key: the 32 bytes 00 through 1f. It is not a real key. + fn key() -> SigningKey { + SigningKey::from_bytes(&std::array::from_fn(|i| u8::try_from(i).unwrap())) + } + + fn hex(bytes: &[u8]) -> String { + use std::fmt::Write as _; + bytes.iter().fold(String::new(), |mut text, byte| { + write!(text, "{byte:02x}").unwrap(); + text + }) + } + + fn unhex(text: &str) -> Vec { + (0..text.len()) + .step_by(2) + .map(|i| u8::from_str_radix(&text[i..i + 2], 16).unwrap()) + .collect() + } + + /// `{"kind": "group.policy", "group": "g1", "level": 3}`, the S5 golden body. + fn plain_body_map() -> Value<'static> { + Value::from(BTreeMap::from([ + (Value::from("kind"), Value::from("group.policy")), + (Value::from("group"), Value::from("g1")), + (Value::from("level"), Value::Unsigned(3)), + ])) + } + + /// `{"blob": h'00ff10', "empty": h'', "hash": blake3("x")}` + fn body_with_byte_strings() -> Value<'static> { + Value::from(BTreeMap::from([ + (Value::from("blob"), Value::from(vec![0x00u8, 0xff, 0x10])), + (Value::from("empty"), Value::from(Vec::::new())), + ( + Value::from("hash"), + Value::from(Hash::digest(b"x").as_bytes().to_vec()), + ), + ])) + } + + /// `[blake3("a"), blake3("b"), blake3("c")]`, the shape of an `after` frontier. + fn hash_array() -> Value<'static> { + let hashes: Vec> = [b"a", b"b", b"c"] + .iter() + .map(|s| Value::from(Hash::digest(s).as_bytes().to_vec())) + .collect(); + Value::from(hashes) + } + + /// `{"a": null, "outer": {"inner": [1, -2, {"deep": true}], "tag": h'ab'}, "z": "last"}` + fn nested() -> Value<'static> { + let deep = Value::from(BTreeMap::from([(Value::from("deep"), Value::from(true))])); + let inner = Value::from(vec![Value::Unsigned(1), Value::Negative(1), deep]); + let outer = Value::from(BTreeMap::from([ + (Value::from("inner"), inner), + (Value::from("tag"), Value::from(vec![0xabu8])), + ])); + Value::from(BTreeMap::from([ + (Value::from("a"), Value::null()), + (Value::from("outer"), outer), + (Value::from("z"), Value::from("last")), + ])) + } + + #[test] + fn test_s5_canonical_vectors_match_the_recorded_bytes() { + let cases = [ + ( + plain_body_map(), + "a3646b696e646c67726f75702e706f6c6963796567726f7570626731656c6576656c03", + ), + ( + body_with_byte_strings(), + "a364626c6f624300ff10646861736858203ae7d805f6789a6402acb70ad4096a85a56bf6804eaf25c0493ac697548d30b565656d70747940", + ), + ( + hash_array(), + "83582017762fddd969a453925d65717ac3eea21320b66b54342fde15128d6caf21215f582010e5cf3d3c8a4f9f3468c8cc58eea84892a22fdadbc1acb22410190044c1d5535820ea7aa1fc9efdbe106dbb70369a75e9671fa29d52bd55536711bf197477b8f021", + ), + ( + nested(), + "a36161f6617a646c617374656f75746572a26374616741ab65696e6e6572830121a16464656570f5", + ), + ]; + for (value, expected) in cases { + assert_eq!(hex(&value.encode()), expected); + } + } + + #[test] + fn test_dcbor_agrees_with_cbor_core_on_the_s5_values() { + let mut plain = dcbor::Map::new(); + plain.insert("kind", "group.policy"); + plain.insert("group", "g1"); + plain.insert("level", 3u64); + assert_eq!(CBOR::from(plain).to_cbor_data(), plain_body_map().encode()); + + let mut bytes = dcbor::Map::new(); + bytes.insert("blob", ByteString::from(vec![0x00u8, 0xff, 0x10])); + bytes.insert("empty", ByteString::from(Vec::::new())); + bytes.insert( + "hash", + ByteString::from(Hash::digest(b"x").as_bytes().to_vec()), + ); + assert_eq!( + CBOR::from(bytes).to_cbor_data(), + body_with_byte_strings().encode() + ); + + let hashes: Vec = [b"a", b"b", b"c"] + .iter() + .map(|s| ByteString::from(Hash::digest(s).as_bytes().to_vec()).into()) + .collect(); + assert_eq!(CBOR::from(hashes).to_cbor_data(), hash_array().encode()); + + let mut deep = dcbor::Map::new(); + deep.insert("deep", true); + let inner = CBOR::from(vec![CBOR::from(1u64), CBOR::from(-2i64), CBOR::from(deep)]); + let mut outer = dcbor::Map::new(); + outer.insert("inner", inner); + outer.insert("tag", ByteString::from(vec![0xabu8])); + let mut root = dcbor::Map::new(); + root.insert("a", CBOR::null()); + root.insert("outer", outer); + root.insert("z", "last"); + assert_eq!(CBOR::from(root).to_cbor_data(), nested().encode()); + } + + /// The S5 golden header: `Header<()>` with the plain body map as its body, seq 0, + /// and the test key. It has no extension, so it pins p2panda's header layout and its + /// signature. It does not pin `ChainExt`, which has its own vectors below. + #[test] + fn test_s5_golden_header_keeps_its_operation_id_and_signature() { + const HEADER: &str = "8601582003a107bff3ce10be1d70dd18e74bc09967e4d6309ba50d5f1ddc8664125531b85840be31be241b5a9915194cafabb3d0ffb8f7a2be7a7a91a9a638449cebfcd7d96f9bde95d6782eb70606f2e85b95760a90d77dab845fdb1ecda843defa7e4ecf0f182358209f9175fb55f67e7673c1613e4ba07360afb584a26407f3ffc6dfe5ae52fddf4d00"; + const OPERATION_ID: &str = + "90acd5f7c498ccb93dc33ce41f49d166140bef38c1f85cb95940f311b6e7f212"; + const SIGNATURE: &str = "be31be241b5a9915194cafabb3d0ffb8f7a2be7a7a91a9a638449cebfcd7d96f9bde95d6782eb70606f2e85b95760a90d77dab845fdb1ecda843defa7e4ecf0f"; + + let body = plain_body_map().encode(); + let header = Header::<()>::builder() + .body(&body) + .seq_num(0) + .build(&key(), ()); + let bytes = header.encode(); + + assert_eq!(hex(&bytes), HEADER); + assert_eq!(Hash::digest(&bytes).to_hex(), OPERATION_ID); + assert_eq!(header.signature.to_hex(), SIGNATURE); + // The receive path accepts the same bytes and reads the same operation ID. + assert_eq!( + AnyHeader::decode(&bytes).unwrap().hash().to_hex(), + OPERATION_ID + ); + } + + /// The two `ChainExt` events the golden tests pin. The second one has a body, a + /// sequence number above 0, a backlink, and a group. + fn golden_events() -> (Event, Event) { + let first = sign( + &key(), + 0, + None, + None, + ChainExt { + kind: "group.policy".to_owned(), + group: None, + after: vec![Hash::digest(b"a"), Hash::digest(b"b")], + }, + ) + .unwrap(); + let body = plain_body_map().encode(); + let second = sign( + &key(), + 1, + Some(first.id), + Some(body.as_slice()), + ChainExt { + kind: "message".to_owned(), + group: Some(Hash::digest(b"g")), + after: vec![first.id], + }, + ) + .unwrap(); + (first, second) + } + + #[test] + fn test_chain_ext_golden_vectors_are_pinned() { + const FIRST: &str = "8601582003a107bff3ce10be1d70dd18e74bc09967e4d6309ba50d5f1ddc8664125531b8584029353dc14afda7aced2938ade60cdee76fbe9eea7adb77765a8e6dc52a6d532d1ed83d4a54d329389048e32f9106dd658dd721abae9b2a95ef56f104684f06060000a4646b696e646c67726f75702e706f6c69637965616674657282582017762fddd969a453925d65717ac3eea21320b66b54342fde15128d6caf21215f582010e5cf3d3c8a4f9f3468c8cc58eea84892a22fdadbc1acb22410190044c1d5536567726f7570f666646f6d61696e6c69642e6576656e74732e7631"; + const FIRST_ID: &str = "58035ddebae67c7e3424eff97938d84e176bf6df4dc90cfb625b2c0d8d2e4c40"; + const FIRST_SIGNATURE: &str = "29353dc14afda7aced2938ade60cdee76fbe9eea7adb77765a8e6dc52a6d532d1ed83d4a54d329389048e32f9106dd658dd721abae9b2a95ef56f104684f0606"; + const SECOND: &str = "8801582003a107bff3ce10be1d70dd18e74bc09967e4d6309ba50d5f1ddc8664125531b858401026e903a382f1589cc4a8ea70ff13b54aba5fb5c2144b0afdba7c79dc09e42c6e29930ef099d0dc5a741bad4b984b110766c5e4e3dacfa627a1ed4b2a7fc405182358209f9175fb55f67e7673c1613e4ba07360afb584a26407f3ffc6dfe5ae52fddf4d01582058035ddebae67c7e3424eff97938d84e176bf6df4dc90cfb625b2c0d8d2e4c40a4646b696e64676d65737361676565616674657281582058035ddebae67c7e3424eff97938d84e176bf6df4dc90cfb625b2c0d8d2e4c406567726f75705820805a31dee1a2a0d3fbe08c612de4fe6be78166a3c4d3a4db7805ad839ed47d4d66646f6d61696e6c69642e6576656e74732e7631"; + const SECOND_ID: &str = "847ec6fba8b5eb1ee230bf9068590f502b6c2d40a14689b30e5fa8d6353c0064"; + const SECOND_SIGNATURE: &str = "1026e903a382f1589cc4a8ea70ff13b54aba5fb5c2144b0afdba7c79dc09e42c6e29930ef099d0dc5a741bad4b984b110766c5e4e3dacfa627a1ed4b2a7fc405"; + + let (first, second) = golden_events(); + assert_eq!(hex(&first.bytes), FIRST); + assert_eq!(first.id.to_hex(), FIRST_ID); + assert_eq!(first.header.signature.to_hex(), FIRST_SIGNATURE); + assert_eq!(hex(&second.bytes), SECOND); + assert_eq!(second.id.to_hex(), SECOND_ID); + assert_eq!(second.header.signature.to_hex(), SECOND_SIGNATURE); + assert_eq!(decode(&unhex(FIRST)).unwrap(), first); + assert_eq!(decode(&unhex(SECOND)).unwrap(), second); + } + + /// dcbor builds the same two headers from its own encoder. Each header must match + /// cbor-core's bytes, and each signature must verify over dcbor's signed bytes. + #[test] + fn test_dcbor_builds_the_same_chain_ext_headers() { + let (first, second) = golden_events(); + let public = key().verifying_key(); + let author = ByteString::from(public.as_bytes().to_vec()); + let body = plain_body_map().encode(); + let group = Hash::digest(b"g"); + + // The extension as dcbor writes it. dcbor sorts the keys, as RFC 8949 requires. + let wire = |kind: &str, group: Option<&Hash>, after: &[Hash]| { + let mut map = dcbor::Map::new(); + map.insert("domain", DOMAIN_TAG); + map.insert("kind", kind); + map.insert( + "group", + group.map_or_else(CBOR::null, |g| { + ByteString::from(g.as_bytes().to_vec()).into() + }), + ); + let hashes: Vec = after + .iter() + .map(|h| ByteString::from(h.as_bytes().to_vec()).into()) + .collect(); + map.insert("after", CBOR::from(hashes)); + CBOR::from(map) + }; + let signature = |event: &Event| -> CBOR { + ByteString::from(event.header.signature.to_bytes().to_vec()).into() + }; + + // First event: no body, so no payload size or hash. Sequence 0, so no backlink. + let signed = CBOR::from(vec![ + CBOR::from(1u64), + author.clone().into(), + CBOR::from(0u64), + CBOR::from(0u64), + wire( + "group.policy", + None, + &[Hash::digest(b"a"), Hash::digest(b"b")], + ), + ]) + .to_cbor_data(); + let full = CBOR::from(vec![ + CBOR::from(1u64), + author.clone().into(), + signature(&first), + CBOR::from(0u64), + CBOR::from(0u64), + wire( + "group.policy", + None, + &[Hash::digest(b"a"), Hash::digest(b"b")], + ), + ]) + .to_cbor_data(); + assert_eq!(full, first.bytes); + assert!(public.verify(&signed, &first.header.signature)); + + // Second event: the body's size and hash, sequence 1, and the first event's ID as + // the backlink. + let body_len = u64::try_from(body.len()).unwrap(); + let signed = CBOR::from(vec![ + CBOR::from(1u64), + author.clone().into(), + CBOR::from(body_len), + ByteString::from(Hash::digest(&body).as_bytes().to_vec()).into(), + CBOR::from(1u64), + ByteString::from(first.id.as_bytes().to_vec()).into(), + wire("message", Some(&group), &[first.id]), + ]) + .to_cbor_data(); + let full = CBOR::from(vec![ + CBOR::from(1u64), + author.into(), + signature(&second), + CBOR::from(body_len), + ByteString::from(Hash::digest(&body).as_bytes().to_vec()).into(), + CBOR::from(1u64), + ByteString::from(first.id.as_bytes().to_vec()).into(), + wire("message", Some(&group), &[first.id]), + ]) + .to_cbor_data(); + assert_eq!(full, second.bytes); + assert!(public.verify(&signed, &second.header.signature)); + } +} From d36e53d56edd71335d9d14faa34916c28812c4ba Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 11 Oct 2026 17:57:34 -0500 Subject: [PATCH 06/30] chore(id): redb 4.3.0 as a direct dependency [P1.4] redb 4.3.0 was already in the lock: iroh-blobs and iroh-docs use it. The id crate now depends on it directly, for the crash-safety tests (P1.4) and the event store (P1.3). iroh-docs also keeps redb 3.1.3, which is unchanged. --- pkgs/id/Cargo.lock | 1 + pkgs/id/Cargo.toml | 1 + 2 files changed, 2 insertions(+) diff --git a/pkgs/id/Cargo.lock b/pkgs/id/Cargo.lock index 1a10a420f1..990519cd23 100644 --- a/pkgs/id/Cargo.lock +++ b/pkgs/id/Cargo.lock @@ -2934,6 +2934,7 @@ dependencies = [ "proptest", "qrcode", "rand 0.10.3", + "redb 4.3.0", "rmp-serde", "rqrr", "russh", diff --git a/pkgs/id/Cargo.toml b/pkgs/id/Cargo.toml index 87c1a3f116..ba0fe63cbd 100644 --- a/pkgs/id/Cargo.toml +++ b/pkgs/id/Cargo.toml @@ -52,6 +52,7 @@ iroh-docs = "0.101" iroh-gossip = { version = "0.101", features = ["net"] } postcard = { version = "1", features = ["alloc"] } rand = "0.10" +redb = "=4.3.0" rustyline = "18" serde = { version = "1", features = ["derive"] } serde_json = "1" From 06d84ed2ea27d94167b756edd87e2bfcd11e198d Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 11 Oct 2026 17:57:34 -0500 Subject: [PATCH 07/30] test(id): in-process crash model for redb with a sampled gate [P1.4] A redb StorageBackend that loses unsynced writes at a simulated power cut, applies one of four survival policies to them, and tears the write in flight. The workload is 50 redb write transactions, with a model for every prefix. Every storage call is a crash point: 687 calls, 7,808 runs per sweep (12 per write, 4 per set_len, 5 per sync). - cargo test --test crash: every 20th crash point (389 runs), the lying-sync control (which must fail), and the corpus replay. The fault semantics have unit tests. - just crash-gate (release): every crash point, and the full lying-sync control. crash-gate is also a nix check and a nix run app. - tests/crash/corpus.tsv: 195 crash points with their expected verdicts. Its header pins the storage-call count and an FNV-1a hash of the call trace, so a changed workload fails the replay before any verdict is compared. --- pkgs/id/flake.nix | 1 + pkgs/id/just-recipes.json | 16 + pkgs/id/justfile | 6 + pkgs/id/tests/README.md | 6 + pkgs/id/tests/crash/corpus.rs | 218 +++++++++++++ pkgs/id/tests/crash/corpus.tsv | 204 ++++++++++++ pkgs/id/tests/crash/faultfs.rs | 548 ++++++++++++++++++++++++++++++++ pkgs/id/tests/crash/harness.rs | 245 ++++++++++++++ pkgs/id/tests/crash/main.rs | 271 ++++++++++++++++ pkgs/id/tests/crash/sweep.rs | 163 ++++++++++ pkgs/id/tests/crash/workload.rs | 164 ++++++++++ 11 files changed, 1842 insertions(+) create mode 100644 pkgs/id/tests/crash/corpus.rs create mode 100644 pkgs/id/tests/crash/corpus.tsv create mode 100644 pkgs/id/tests/crash/faultfs.rs create mode 100644 pkgs/id/tests/crash/harness.rs create mode 100644 pkgs/id/tests/crash/main.rs create mode 100644 pkgs/id/tests/crash/sweep.rs create mode 100644 pkgs/id/tests/crash/workload.rs diff --git a/pkgs/id/flake.nix b/pkgs/id/flake.nix index 75aebc4a87..c3e616aef9 100644 --- a/pkgs/id/flake.nix +++ b/pkgs/id/flake.nix @@ -321,6 +321,7 @@ test-web-typecheck = mkCheck "test-web-typecheck" "test-web-typecheck"; doc = mkCheck "doc" "doc"; cargo-check = mkCheck "cargo-check" "cargo-check"; + crash-gate = mkCheck "crash-gate" "crash-gate"; # Playwright E2E tests (requires building the binary + browser binaries) test-e2e = pkgs.stdenv.mkDerivation { diff --git a/pkgs/id/just-recipes.json b/pkgs/id/just-recipes.json index 7c9f863ad6..a26f521c34 100644 --- a/pkgs/id/just-recipes.json +++ b/pkgs/id/just-recipes.json @@ -1365,6 +1365,22 @@ "namepath": "coverage-summary", "shebang": false }, + "crash-gate": { + "attributes": [{ "group": "test" }], + "body": [ + ["cargo test --release --test crash -- --skip write_corpus --include-ignored"], + ["@echo \"✓ Crash gate passed\""] + ], + "dependencies": [], + "doc": "Crash-safety gate for redb: every storage call under every survival policy, and the lying-sync control, in release", + "name": "crash-gate", + "parameters": [], + "priors": 0, + "private": false, + "quiet": false, + "namepath": "crash-gate", + "shebang": false + }, "default": { "attributes": [], "body": [], diff --git a/pkgs/id/justfile b/pkgs/id/justfile index e896140d2e..57c4175b15 100644 --- a/pkgs/id/justfile +++ b/pkgs/id/justfile @@ -230,6 +230,12 @@ test-full: PROPTEST_CASES="${PROPTEST_CASES:-4096}" ID_TUPLE_FUZZ_CASES="${ID_TUPLE_FUZZ_CASES:-20000}" cargo test --all-features --test tuple_properties @echo "✓ Full Rust test run passed" +# Crash-safety gate for redb: every storage call under every survival policy, and the lying-sync control, in release +[group('test')] +crash-gate: + cargo test --release --test crash -- --skip write_corpus --include-ignored + @echo "✓ Crash gate passed" + # Run unit tests only (fast) [group('test')] test-unit: diff --git a/pkgs/id/tests/README.md b/pkgs/id/tests/README.md index cdc371fd9d..53839d52df 100644 --- a/pkgs/id/tests/README.md +++ b/pkgs/id/tests/README.md @@ -15,6 +15,10 @@ in the - `tuple_properties.rs`: property tests for the tuple encoding in `src/tuple.rs`, and a fixed-seed fuzz run. - `regression_replay.rs`: replays every case in `regressions/`. +- `crash/`: the crash-safety gate for redb (plan P1.4). A fault model behind + `redb::StorageBackend` cuts the power at a storage call of a 50-transaction + workload, and the oracle checks the reopened state. `corpus.tsv` is the static + replay list. See `crash/main.rs`. - `common/mod.rs`: the tuple checker shared by the property tests and the replay. - `regressions/`: checked-in failing cases. See its [README](regressions/README.md). @@ -26,6 +30,8 @@ in the `PROPTEST_CASES` raises the proptest case count, and `ID_TUPLE_FUZZ_CASES` raises the fixed-seed run. - `cargo test --test regression_replay`: the replay alone. +- `cargo test --test crash`: the sampled crash sweep, the lying-sync control, and the corpus replay. +- `just crash-gate`: every crash point of the redb crash model, and the full control, in release. - `cargo test --all-features -- --ignored`: tests quarantined with `#[ignore = ""]`. diff --git a/pkgs/id/tests/crash/corpus.rs b/pkgs/id/tests/crash/corpus.rs new file mode 100644 index 0000000000..a980d8129f --- /dev/null +++ b/pkgs/id/tests/crash/corpus.rs @@ -0,0 +1,218 @@ +//! The crash corpus: `corpus.tsv`, a checked-in list of crash points, each with the verdict its run +//! must keep. +//! +//! Two header lines pin the workload: the storage-call count, and an FNV-1a hash of the call trace +//! (kind, offset and length of every call). If the workload or redb's write pattern changes, both +//! change, and the replay fails before it compares any verdict. +//! +//! Every sweep failure is added by hand as a `fix-` row, with the verdict the fixed code +//! produces. `write_corpus` keeps those rows when it regenerates the file. + +use crate::faultfs::{Kind, Plan, Survive, Tear, Trace}; +use crate::harness::Verdict; +use crate::sweep::Job; +use std::fmt::Write as _; + +const STORAGE_CALLS: &str = "# storage_calls: "; +const TRACE_HASH: &str = "# trace_fnv1a: "; +const COLUMNS: &str = + "# name\tlying_sync\tevent\tkind\tsurvive\ttear\tsync_completed\tseed\texpect"; + +const PREAMBLE: &str = "\ +# Crash corpus for the redb fault model (tests/crash). Replayed by corpus_replays_with_recorded_verdicts. +# Each line is one crash point: the plan that cuts power there, and the verdict its run must keep. +# expect `ok` accepts either valid prefix (ok_acked or ok_acked_plus_one). Any other value must match. +# trace_fnv1a is FNV-1a over (kind, offset, length) of every storage call of the clean run. +# Regenerate, from pkgs/id: cargo test --release --test crash write_corpus -- --ignored +# Each sweep failure is added by hand as a fix- row, with the verdict the fixed code gives. +"; + +/// What the replay pins about the workload. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Header { + pub storage_calls: u64, + pub trace_fnv1a: u64, +} + +/// The verdict a row must keep. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Expect { + /// `ok`: either valid prefix, `ok_acked` or `ok_acked_plus_one`. + Valid, + /// Exactly this verdict. + Exact(Verdict), +} + +impl Expect { + pub const fn name(self) -> &'static str { + match self { + Self::Valid => "ok", + Self::Exact(verdict) => verdict.name(), + } + } + + pub fn accepts(self, verdict: Verdict) -> bool { + match self { + Self::Valid => matches!(verdict, Verdict::OkAcked | Verdict::OkAckedPlusOne), + Self::Exact(expected) => verdict == expected, + } + } +} + +/// One crash point and the verdict it must keep. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Row { + pub name: String, + pub job: Job, + /// The kind of the storage call at `job.plan.event`. The replay checks it against the trace. + pub kind: Kind, + pub expect: Expect, +} + +/// FNV-1a over the trace. It detects a changed workload; it is not a security hash. +pub fn trace_fnv1a(trace: &Trace) -> u64 { + const OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; + const PRIME: u64 = 0x0000_0100_0000_01b3; + let mut h = OFFSET_BASIS; + let mut eat = |bytes: &[u8]| { + for &b in bytes { + h ^= u64::from(b); + h = h.wrapping_mul(PRIME); + } + }; + for &(kind, offset, len) in trace { + eat(kind.name().as_bytes()); + eat(&[0]); + eat(&offset.to_le_bytes()); + eat(&(len as u64).to_le_bytes()); + } + h +} + +/// Parses the corpus text. Blank lines and comments are skipped, and the two header keys are read. +pub fn parse(text: &str) -> Result<(Header, Vec), String> { + let mut storage_calls = None; + let mut trace_fnv1a = None; + let mut rows = Vec::new(); + for (index, line) in text.lines().enumerate() { + let at = |e: String| format!("line {}: {e}", index + 1); + if let Some(value) = line.strip_prefix(STORAGE_CALLS) { + storage_calls = Some(value.trim().parse::().map_err(|e| at(e.to_string()))?); + } else if let Some(value) = line.strip_prefix(TRACE_HASH) { + trace_fnv1a = + Some(u64::from_str_radix(value.trim(), 16).map_err(|e| at(e.to_string()))?); + } else if !line.trim().is_empty() && !line.starts_with('#') { + rows.push(parse_row(line).map_err(at)?); + } + } + let header = Header { + storage_calls: storage_calls.ok_or("no `# storage_calls:` line")?, + trace_fnv1a: trace_fnv1a.ok_or("no `# trace_fnv1a:` line")?, + }; + Ok((header, rows)) +} + +fn parse_row(line: &str) -> Result { + let fields: Vec<&str> = line.split('\t').collect(); + let &[ + name, + lying, + event, + kind, + survive, + tear, + sync_completed, + seed, + expect, + ] = fields.as_slice() + else { + return Err(format!( + "expected 9 tab-separated fields, found {}", + fields.len() + )); + }; + Ok(Row { + name: name.to_owned(), + job: Job { + plan: Plan { + event: event.parse().map_err(|e| format!("event {event:?}: {e}"))?, + survive: parse_survive(survive)?, + tear: parse_tear(tear)?, + sync_completed: parse_flag(sync_completed)?, + seed: seed.parse().map_err(|e| format!("seed {seed:?}: {e}"))?, + }, + lying: parse_flag(lying)?, + }, + kind: parse_kind(kind)?, + expect: parse_expect(expect)?, + }) +} + +fn parse_flag(s: &str) -> Result { + match s { + "0" => Ok(false), + "1" => Ok(true), + other => Err(format!("expected 0 or 1, found {other:?}")), + } +} + +fn parse_kind(s: &str) -> Result { + [Kind::Write, Kind::SetLen, Kind::Sync] + .into_iter() + .find(|k| k.name() == s) + .ok_or_else(|| format!("unknown storage call kind {s:?}")) +} + +fn parse_survive(s: &str) -> Result { + [ + Survive::Drop, + Survive::Keep, + Survive::Random, + Survive::Reorder, + ] + .into_iter() + .find(|v| v.name() == s) + .ok_or_else(|| format!("unknown survive policy {s:?}")) +} + +fn parse_tear(s: &str) -> Result { + [Tear::Off, Tear::Byte, Tear::Sector] + .into_iter() + .find(|t| t.name() == s) + .ok_or_else(|| format!("unknown tear mode {s:?}")) +} + +fn parse_expect(s: &str) -> Result { + if s == "ok" { + return Ok(Expect::Valid); + } + Verdict::from_name(s) + .map(Expect::Exact) + .ok_or_else(|| format!("unknown verdict {s:?}")) +} + +/// The corpus text for a header and rows, in the order given. +pub fn format(header: &Header, rows: &[Row]) -> String { + let mut out = String::from(PREAMBLE); + writeln!(out, "{STORAGE_CALLS}{}", header.storage_calls).expect("write to a String"); + writeln!(out, "{TRACE_HASH}{:016x}", header.trace_fnv1a).expect("write to a String"); + writeln!(out, "{COLUMNS}").expect("write to a String"); + for row in rows { + let p = row.job.plan; + writeln!( + out, + "{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}", + row.name, + u8::from(row.job.lying), + p.event, + row.kind.name(), + p.survive.name(), + p.tear.name(), + u8::from(p.sync_completed), + p.seed, + row.expect.name() + ) + .expect("write to a String"); + } + out +} diff --git a/pkgs/id/tests/crash/corpus.tsv b/pkgs/id/tests/crash/corpus.tsv new file mode 100644 index 0000000000..1bde6f6fe0 --- /dev/null +++ b/pkgs/id/tests/crash/corpus.tsv @@ -0,0 +1,204 @@ +# Crash corpus for the redb fault model (tests/crash). Replayed by corpus_replays_with_recorded_verdicts. +# Each line is one crash point: the plan that cuts power there, and the verdict its run must keep. +# expect `ok` accepts either valid prefix (ok_acked or ok_acked_plus_one). Any other value must match. +# trace_fnv1a is FNV-1a over (kind, offset, length) of every storage call of the clean run. +# Regenerate, from pkgs/id: cargo test --release --test crash write_corpus -- --ignored +# Each sweep failure is added by hand as a fix- row, with the verdict the fixed code gives. +# storage_calls: 687 +# trace_fnv1a: ea71ba58d745a389 +# name lying_sync event kind survive tear sync_completed seed expect +faithful-pre-commit-002-Keep-Off-0 0 2 write Keep Off 0 8361847590266283331 open_error_pre_commit +faithful-pre-commit-002-Reorder-Off-0 0 2 write Reorder Off 0 12847895688012758659 open_error_pre_commit +faithful-pre-commit-002-Drop-Byte-0 0 2 write Drop Byte 0 283545940951472360 open_error_pre_commit +faithful-pre-commit-002-Keep-Byte-0 0 2 write Keep Byte 0 16743392734764332446 open_error_pre_commit +faithful-pre-commit-002-Random-Byte-0 0 2 write Random Byte 0 10203985545584359410 open_error_pre_commit +faithful-pre-commit-002-Reorder-Byte-0 0 2 write Reorder Byte 0 4413419251928811825 open_error_pre_commit +faithful-pre-commit-002-Keep-Sector-0 0 2 write Keep Sector 0 12488321346544387774 open_error_pre_commit +faithful-pre-commit-002-Random-Sector-0 0 2 write Random Sector 0 3628886295211392483 open_error_pre_commit +faithful-pre-commit-003-Keep-Off-0 0 3 sync Keep Off 0 13181733461238856628 open_error_pre_commit +faithful-pre-commit-003-Drop-Off-1 0 3 sync Drop Off 1 14125433436979177977 open_error_pre_commit +faithful-pre-commit-004-Drop-Off-0 0 4 write Drop Off 0 8298218915660572452 open_error_pre_commit +faithful-pre-commit-004-Keep-Off-0 0 4 write Keep Off 0 2164534462834122148 open_error_pre_commit +faithful-pre-commit-004-Random-Off-0 0 4 write Random Off 0 18437047743522589496 open_error_pre_commit +faithful-pre-commit-004-Reorder-Off-0 0 4 write Reorder Off 0 13744174975128628763 open_error_pre_commit +faithful-pre-commit-004-Drop-Sector-0 0 4 write Drop Sector 0 10933956566130174471 open_error_pre_commit +faithful-pre-commit-004-Keep-Sector-0 0 4 write Keep Sector 0 15186231919485255384 open_error_pre_commit +faithful-pre-commit-004-Random-Sector-0 0 4 write Random Sector 0 8999802954715218159 open_error_pre_commit +faithful-pre-commit-004-Reorder-Sector-0 0 4 write Reorder Sector 0 3594022018564067379 open_error_pre_commit +faithful-pre-commit-005-Drop-Off-0 0 5 sync Drop Off 0 16816190659201883630 open_error_pre_commit +faithful-pre-commit-005-Reorder-Off-0 0 5 sync Reorder Off 0 17493543810667717580 open_error_pre_commit +faithful-plus-one-019-Keep-Byte-0 0 19 write Keep Byte 0 15504103307926617233 ok +faithful-plus-one-019-Keep-Sector-0 0 19 write Keep Sector 0 14438227884836799269 ok +faithful-plus-one-020-Keep-Off-0 0 20 sync Keep Off 0 3434552994526458292 ok +faithful-plus-one-020-Drop-Off-1 0 20 sync Drop Off 1 248628394465833924 ok +faithful-plus-one-027-Keep-Byte-0 0 27 write Keep Byte 0 489078435782343973 ok +faithful-plus-one-027-Keep-Sector-0 0 27 write Keep Sector 0 13509320034725664642 ok +faithful-plus-one-028-Keep-Off-0 0 28 sync Keep Off 0 11338523420196340667 ok +faithful-plus-one-028-Drop-Off-1 0 28 sync Drop Off 1 700649371801333113 ok +faithful-plus-one-036-Keep-Byte-0 0 36 write Keep Byte 0 1073056976835893526 ok +faithful-plus-one-036-Reorder-Byte-0 0 36 write Reorder Byte 0 12024899070807031009 ok +faithful-plus-one-036-Keep-Sector-0 0 36 write Keep Sector 0 8954115610872055338 ok +faithful-plus-one-037-Keep-Off-0 0 37 sync Keep Off 0 13962187052594835106 ok +faithful-plus-one-037-Drop-Off-1 0 37 sync Drop Off 1 13522350183912501025 ok +faithful-plus-one-048-Keep-Off-0 0 48 sync Keep Off 0 15679062808376293615 ok +faithful-plus-one-048-Drop-Off-1 0 48 sync Drop Off 1 18359149166507225746 ok +faithful-plus-one-057-Keep-Byte-0 0 57 write Keep Byte 0 9523275287782354275 ok +faithful-plus-one-057-Keep-Sector-0 0 57 write Keep Sector 0 12213324642289485882 ok +faithful-plus-one-058-Keep-Off-0 0 58 sync Keep Off 0 9494113824375037356 ok +faithful-plus-one-058-Drop-Off-1 0 58 sync Drop Off 1 1173764370998105968 ok +faithful-plus-one-059-Drop-Off-0 0 59 set_len Drop Off 0 9675086961158200550 ok +faithful-plus-one-059-Keep-Off-0 0 59 set_len Keep Off 0 18343344445377204566 ok +faithful-plus-one-059-Random-Off-0 0 59 set_len Random Off 0 16458820088970563762 ok +faithful-plus-one-059-Reorder-Off-0 0 59 set_len Reorder Off 0 17386178431295624566 ok +faithful-plus-one-069-Keep-Byte-0 0 69 write Keep Byte 0 8220142193048694755 ok +faithful-plus-one-070-Keep-Off-0 0 70 sync Keep Off 0 4037893128233546875 ok +faithful-plus-one-070-Drop-Off-1 0 70 sync Drop Off 1 11418664529484167149 ok +faithful-plus-one-081-Keep-Off-0 0 81 sync Keep Off 0 2930090195686362505 ok +faithful-plus-one-081-Drop-Off-1 0 81 sync Drop Off 1 5468827417533922114 ok +faithful-plus-one-094-Keep-Byte-0 0 94 write Keep Byte 0 15111290307545219460 ok +faithful-plus-one-094-Keep-Sector-0 0 94 write Keep Sector 0 9032178906902000325 ok +faithful-plus-one-095-Keep-Off-0 0 95 sync Keep Off 0 6571994649100958089 ok +faithful-plus-one-095-Drop-Off-1 0 95 sync Drop Off 1 15553688983465545035 ok +faithful-plus-one-107-Keep-Byte-0 0 107 write Keep Byte 0 1685348835776853444 ok +faithful-plus-one-107-Keep-Sector-0 0 107 write Keep Sector 0 14714397222495690956 ok +faithful-plus-one-108-Keep-Off-0 0 108 sync Keep Off 0 2946163249927435054 ok +faithful-plus-one-108-Drop-Off-1 0 108 sync Drop Off 1 10222258035246163952 ok +faithful-plus-one-123-Keep-Byte-0 0 123 write Keep Byte 0 13123940783640074100 ok +faithful-plus-one-123-Keep-Sector-0 0 123 write Keep Sector 0 8290141613974244281 ok +faithful-plus-one-124-Keep-Off-0 0 124 sync Keep Off 0 6918133469863954762 ok +faithful-plus-one-124-Drop-Off-1 0 124 sync Drop Off 1 8219154544371537832 ok +faithful-plus-one-136-Keep-Byte-0 0 136 write Keep Byte 0 14950733406603351597 ok +faithful-plus-one-136-Keep-Sector-0 0 136 write Keep Sector 0 15426643891416011518 ok +faithful-plus-one-137-Keep-Off-0 0 137 sync Keep Off 0 18059055659301111446 ok +faithful-plus-one-137-Drop-Off-1 0 137 sync Drop Off 1 11670476942029156616 ok +faithful-plus-one-149-Keep-Byte-0 0 149 write Keep Byte 0 12777398887419732391 ok +faithful-plus-one-149-Keep-Sector-0 0 149 write Keep Sector 0 9408096718594610150 ok +faithful-plus-one-150-Keep-Off-0 0 150 sync Keep Off 0 14964411507835406432 ok +faithful-plus-one-150-Drop-Off-1 0 150 sync Drop Off 1 17678459054848578891 ok +faithful-plus-one-165-Keep-Off-0 0 165 sync Keep Off 0 9559187864972879549 ok +faithful-plus-one-165-Drop-Off-1 0 165 sync Drop Off 1 1364893903502039169 ok +faithful-plus-one-177-Keep-Off-0 0 177 sync Keep Off 0 165712780531803312 ok +faithful-plus-one-177-Drop-Off-1 0 177 sync Drop Off 1 13118932286680774374 ok +faithful-plus-one-191-Keep-Off-0 0 191 sync Keep Off 0 3314942474309498170 ok +faithful-plus-one-191-Drop-Off-1 0 191 sync Drop Off 1 15428210791079498511 ok +faithful-plus-one-205-Keep-Off-0 0 205 sync Keep Off 0 2767572030511613639 ok +faithful-plus-one-205-Drop-Off-1 0 205 sync Drop Off 1 9769833335015313876 ok +faithful-plus-one-217-Keep-Byte-0 0 217 write Keep Byte 0 10165495554913995583 ok +faithful-plus-one-217-Keep-Sector-0 0 217 write Keep Sector 0 6574255339552376152 ok +faithful-plus-one-218-Keep-Off-0 0 218 sync Keep Off 0 7613657584403281639 ok +faithful-plus-one-218-Drop-Off-1 0 218 sync Drop Off 1 11312226568981675277 ok +faithful-plus-one-231-Keep-Off-0 0 231 sync Keep Off 0 4179947301599908476 ok +faithful-plus-one-231-Drop-Off-1 0 231 sync Drop Off 1 5116040892678099876 ok +faithful-plus-one-243-Keep-Byte-0 0 243 write Keep Byte 0 8762325739276123989 ok +faithful-plus-one-243-Keep-Sector-0 0 243 write Keep Sector 0 14686548414178289833 ok +faithful-plus-one-244-Keep-Off-0 0 244 sync Keep Off 0 16049756442543728845 ok +faithful-plus-one-244-Drop-Off-1 0 244 sync Drop Off 1 14913930202841904312 ok +faithful-plus-one-261-Keep-Off-0 0 261 sync Keep Off 0 15410999506478148281 ok +faithful-plus-one-261-Drop-Off-1 0 261 sync Drop Off 1 14685771586452083517 ok +faithful-plus-one-274-Keep-Byte-0 0 274 write Keep Byte 0 1027727624881511450 ok +faithful-plus-one-274-Keep-Sector-0 0 274 write Keep Sector 0 11518605028972043358 ok +faithful-plus-one-275-Keep-Off-0 0 275 sync Keep Off 0 17564594471607792374 ok +faithful-plus-one-275-Drop-Off-1 0 275 sync Drop Off 1 9778001308018100343 ok +faithful-plus-one-287-Keep-Byte-0 0 287 write Keep Byte 0 14795918076150292015 ok +faithful-plus-one-287-Keep-Sector-0 0 287 write Keep Sector 0 11478542050470025085 ok +faithful-plus-one-288-Keep-Off-0 0 288 sync Keep Off 0 17499486084261253324 ok +faithful-plus-one-288-Drop-Off-1 0 288 sync Drop Off 1 5239927348426128291 ok +faithful-plus-one-300-Keep-Byte-0 0 300 write Keep Byte 0 8423053430665334237 ok +faithful-plus-one-300-Keep-Sector-0 0 300 write Keep Sector 0 15061140238467577501 ok +faithful-plus-one-301-Keep-Off-0 0 301 sync Keep Off 0 17733580308414340619 ok +faithful-plus-one-301-Drop-Off-1 0 301 sync Drop Off 1 5211028791590337658 ok +faithful-plus-one-313-Keep-Byte-0 0 313 write Keep Byte 0 3037625008198164740 ok +faithful-plus-one-313-Keep-Sector-0 0 313 write Keep Sector 0 1373482300176920429 ok +faithful-plus-one-314-Keep-Off-0 0 314 sync Keep Off 0 4953113174899879966 ok +faithful-plus-one-314-Drop-Off-1 0 314 sync Drop Off 1 6759712572993840875 ok +faithful-plus-one-328-Keep-Byte-0 0 328 write Keep Byte 0 11194853154052585179 ok +faithful-plus-one-328-Keep-Sector-0 0 328 write Keep Sector 0 8109119208554312001 ok +faithful-plus-one-329-Keep-Off-0 0 329 sync Keep Off 0 8727075937931132163 ok +faithful-plus-one-329-Drop-Off-1 0 329 sync Drop Off 1 5976117347785219753 ok +faithful-plus-one-341-Keep-Sector-0 0 341 write Keep Sector 0 12239801341686695436 ok +faithful-plus-one-342-Keep-Off-0 0 342 sync Keep Off 0 16800024510819511144 ok +faithful-plus-one-342-Drop-Off-1 0 342 sync Drop Off 1 14093191172629087699 ok +faithful-plus-one-355-Keep-Off-0 0 355 sync Keep Off 0 2135523320153524703 ok +faithful-plus-one-355-Drop-Off-1 0 355 sync Drop Off 1 14887425370155211652 ok +faithful-plus-one-368-Keep-Off-0 0 368 sync Keep Off 0 2844921087868708809 ok +faithful-plus-one-368-Drop-Off-1 0 368 sync Drop Off 1 6627846757575278609 ok +faithful-plus-one-381-Keep-Byte-0 0 381 write Keep Byte 0 25144791087050926 ok +faithful-plus-one-381-Keep-Sector-0 0 381 write Keep Sector 0 14844884227816705147 ok +faithful-plus-one-382-Keep-Off-0 0 382 sync Keep Off 0 5299297645456731254 ok +faithful-plus-one-382-Drop-Off-1 0 382 sync Drop Off 1 8071622813456534514 ok +faithful-plus-one-397-Keep-Byte-0 0 397 write Keep Byte 0 13401847063454727570 ok +faithful-plus-one-398-Keep-Off-0 0 398 sync Keep Off 0 11013033131369215977 ok +faithful-plus-one-398-Drop-Off-1 0 398 sync Drop Off 1 17049793796448489352 ok +faithful-plus-one-410-Keep-Byte-0 0 410 write Keep Byte 0 15709413014075130138 ok +faithful-plus-one-411-Keep-Off-0 0 411 sync Keep Off 0 3148868089662419054 ok +faithful-plus-one-411-Drop-Off-1 0 411 sync Drop Off 1 3428671922817942757 ok +faithful-plus-one-424-Keep-Byte-0 0 424 write Keep Byte 0 668735674563156536 ok +faithful-plus-one-424-Keep-Sector-0 0 424 write Keep Sector 0 16490184956529659223 ok +faithful-plus-one-425-Keep-Off-0 0 425 sync Keep Off 0 429617051979138127 ok +faithful-plus-one-425-Drop-Off-1 0 425 sync Drop Off 1 14270816430264841618 ok +faithful-plus-one-439-Keep-Off-0 0 439 sync Keep Off 0 16169496523120911886 ok +faithful-plus-one-439-Drop-Off-1 0 439 sync Drop Off 1 9188697822836266542 ok +faithful-plus-one-452-Keep-Byte-0 0 452 write Keep Byte 0 5780067073457772263 ok +faithful-plus-one-452-Keep-Sector-0 0 452 write Keep Sector 0 14102049534020219195 ok +faithful-plus-one-453-Keep-Off-0 0 453 sync Keep Off 0 13031044308285868302 ok +faithful-plus-one-453-Drop-Off-1 0 453 sync Drop Off 1 2882071577155939035 ok +faithful-plus-one-465-Keep-Byte-0 0 465 write Keep Byte 0 5700901950662597717 ok +faithful-plus-one-465-Keep-Sector-0 0 465 write Keep Sector 0 3826291906098318273 ok +faithful-plus-one-466-Keep-Off-0 0 466 sync Keep Off 0 1006734255125521498 ok +faithful-plus-one-466-Drop-Off-1 0 466 sync Drop Off 1 5353748797323716210 ok +faithful-plus-one-480-Keep-Byte-0 0 480 write Keep Byte 0 13683164868141865320 ok +faithful-plus-one-481-Keep-Off-0 0 481 sync Keep Off 0 5323142917548978985 ok +faithful-plus-one-481-Drop-Off-1 0 481 sync Drop Off 1 5786985714372432443 ok +faithful-plus-one-494-Keep-Off-0 0 494 sync Keep Off 0 10471707079125028710 ok +faithful-plus-one-494-Drop-Off-1 0 494 sync Drop Off 1 17207551308796615945 ok +faithful-plus-one-506-Keep-Byte-0 0 506 write Keep Byte 0 10201984596077993886 ok +faithful-plus-one-506-Keep-Sector-0 0 506 write Keep Sector 0 4822098108530114422 ok +faithful-plus-one-507-Keep-Off-0 0 507 sync Keep Off 0 9672740012124895296 ok +faithful-plus-one-507-Drop-Off-1 0 507 sync Drop Off 1 18089359206210032078 ok +faithful-plus-one-519-Keep-Byte-0 0 519 write Keep Byte 0 6624644079780565771 ok +faithful-plus-one-519-Keep-Sector-0 0 519 write Keep Sector 0 7402588503920285794 ok +faithful-plus-one-520-Keep-Off-0 0 520 sync Keep Off 0 3313691569763021634 ok +faithful-plus-one-520-Drop-Off-1 0 520 sync Drop Off 1 7854700345702928729 ok +faithful-plus-one-537-Keep-Off-0 0 537 sync Keep Off 0 11525369460782551602 ok +faithful-plus-one-537-Drop-Off-1 0 537 sync Drop Off 1 537465236528846406 ok +faithful-plus-one-551-Keep-Off-0 0 551 sync Keep Off 0 7720523294221888640 ok +faithful-plus-one-551-Drop-Off-1 0 551 sync Drop Off 1 8999766921682538331 ok +faithful-plus-one-564-Keep-Byte-0 0 564 write Keep Byte 0 9562704417615410073 ok +faithful-plus-one-564-Keep-Sector-0 0 564 write Keep Sector 0 8304621564250507817 ok +faithful-plus-one-565-Keep-Off-0 0 565 sync Keep Off 0 3891975874225753435 ok +faithful-plus-one-565-Drop-Off-1 0 565 sync Drop Off 1 6680472255517198529 ok +faithful-plus-one-578-Keep-Off-0 0 578 sync Keep Off 0 10063753951762353232 ok +faithful-plus-one-578-Drop-Off-1 0 578 sync Drop Off 1 16956484774544814819 ok +faithful-plus-one-590-Keep-Byte-0 0 590 write Keep Byte 0 12549703445188094607 ok +faithful-plus-one-590-Keep-Sector-0 0 590 write Keep Sector 0 15504913191197502409 ok +faithful-plus-one-591-Keep-Off-0 0 591 sync Keep Off 0 16664945633311188789 ok +faithful-plus-one-591-Drop-Off-1 0 591 sync Drop Off 1 14194124368278569982 ok +faithful-plus-one-603-Keep-Byte-0 0 603 write Keep Byte 0 13494384674233288228 ok +faithful-plus-one-603-Keep-Sector-0 0 603 write Keep Sector 0 3125872347951656207 ok +faithful-plus-one-604-Keep-Off-0 0 604 sync Keep Off 0 1838080068766380043 ok +faithful-plus-one-604-Drop-Off-1 0 604 sync Drop Off 1 7417681231079457106 ok +faithful-plus-one-617-Keep-Sector-0 0 617 write Keep Sector 0 5776061745722100082 ok +faithful-plus-one-618-Keep-Off-0 0 618 sync Keep Off 0 16761848934835256560 ok +faithful-plus-one-618-Drop-Off-1 0 618 sync Drop Off 1 14807426911342131009 ok +faithful-plus-one-630-Keep-Sector-0 0 630 write Keep Sector 0 14902217305235499312 ok +faithful-plus-one-631-Keep-Off-0 0 631 sync Keep Off 0 676641572010283968 ok +faithful-plus-one-631-Drop-Off-1 0 631 sync Drop Off 1 10143299821640326643 ok +faithful-plus-one-643-Keep-Byte-0 0 643 write Keep Byte 0 1677743768162387066 ok +faithful-plus-one-643-Keep-Sector-0 0 643 write Keep Sector 0 3080154773598987579 ok +faithful-plus-one-644-Keep-Off-0 0 644 sync Keep Off 0 2620670293291397668 ok +faithful-plus-one-644-Drop-Off-1 0 644 sync Drop Off 1 7462307981577524081 ok +faithful-plus-one-658-Keep-Sector-0 0 658 write Keep Sector 0 4641021199136130516 ok +faithful-plus-one-659-Keep-Off-0 0 659 sync Keep Off 0 3117361145260860315 ok +faithful-plus-one-659-Drop-Off-1 0 659 sync Drop Off 1 265010668171263762 ok +faithful-plus-one-674-Keep-Byte-0 0 674 write Keep Byte 0 7507284022121539747 ok +faithful-plus-one-674-Keep-Sector-0 0 674 write Keep Sector 0 4338418794906055426 ok +faithful-plus-one-675-Keep-Off-0 0 675 sync Keep Off 0 4584996403999602593 ok +faithful-plus-one-675-Drop-Off-1 0 675 sync Drop Off 1 9676419116182991924 ok +control-ok_acked_plus_one-1 1 19 write Keep Byte 0 15504103307926617233 ok +control-ok_acked_plus_one-2 1 19 write Keep Sector 0 14438227884836799269 ok +control-lost_committed-1 1 21 write Drop Off 0 443894039808895662 lost_committed +control-lost_committed-2 1 21 write Random Off 0 12310743265758587808 lost_committed +control-open_error-1 1 21 write Reorder Off 0 9550841287782738135 open_error +control-open_error-2 1 21 write Drop Byte 0 2390098490884626015 open_error +control-panic-1 1 683 write Reorder Byte 0 16391084065023403325 panic +control-panic-2 1 684 sync Random Off 0 18273772749764122265 panic diff --git a/pkgs/id/tests/crash/faultfs.rs b/pkgs/id/tests/crash/faultfs.rs new file mode 100644 index 0000000000..cfa31f691a --- /dev/null +++ b/pkgs/id/tests/crash/faultfs.rs @@ -0,0 +1,548 @@ +//! Power-loss model behind redb's `StorageBackend`. +//! +//! `write` and `set_len` calls wait in `pending` until a `sync_data` call completes. A power cut +//! keeps the durable bytes plus the unsynced operations that `Survive` selects, applied in issue +//! order (`Keep`, `Random`) or shuffled (`Reorder`). The write in flight at the cut can be torn: +//! only a prefix of its bytes lands. After the cut every call returns `Ok` and does nothing, as +//! redb's own `CrashBackend` does (`src/db.rs` in redb 4.3.0). The caller must stop counting work +//! once `cut()` is true, because the process it models is dead. + +use redb::StorageBackend; +use std::io; +use std::sync::{Arc, Mutex, MutexGuard}; + +/// Which unsynced operations reach the disk at a power cut. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Survive { + /// None. This is what `LazyFS` `clear-cache` does. + Drop, + /// All, in issue order. This is what the kernel does when it writes back before the cut. + Keep, + /// Each one independently, in issue order. + Random, + /// A random subset, in random order. Stronger than real disks need to be for redb. + Reorder, +} + +impl Survive { + pub const fn name(self) -> &'static str { + match self { + Self::Drop => "Drop", + Self::Keep => "Keep", + Self::Random => "Random", + Self::Reorder => "Reorder", + } + } +} + +/// What lands of the write in flight at the cut. Only applies when the cut lands on a write. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Tear { + /// Nothing lands. + Off, + /// A random byte prefix, from 0 to the full length. + Byte, + /// A random prefix of whole 512-byte sectors. + Sector, +} + +impl Tear { + pub const fn name(self) -> &'static str { + match self { + Self::Off => "Off", + Self::Byte => "Byte", + Self::Sector => "Sector", + } + } +} + +/// Where power is lost, and what survives. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Plan { + /// 1-based index of the storage call on which power is lost. + pub event: u64, + pub survive: Survive, + pub tear: Tear, + /// Only for a sync cut: true means the sync finished before power was lost. + pub sync_completed: bool, + /// Picks which unsynced operations survive, and how far a torn write lands. + pub seed: u64, +} + +/// The kind of a storage call, as recorded in the trace. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + Write, + SetLen, + Sync, +} + +impl Kind { + pub const fn name(self) -> &'static str { + match self { + Self::Write => "write", + Self::SetLen => "set_len", + Self::Sync => "sync", + } + } +} + +/// Every storage call up to and including the cut: kind, offset (the length for `set_len`), and +/// data length. +pub type Trace = Vec<(Kind, u64, usize)>; + +#[derive(Clone, Debug)] +enum Op { + Write { offset: u64, data: Vec }, + SetLen(u64), +} + +#[derive(Debug, Default)] +struct State { + /// What the process sees: durable bytes with every pending operation applied. + live: Vec, + /// What a completed sync has made durable. + durable: Vec, + /// Operations issued since the last completed sync. + pending: Vec, + trace: Trace, + plan: Option, + /// When true, `sync_data` returns `Ok` without making anything durable (the control). + lying_sync: bool, + cut: bool, + /// The disk after the cut. + image: Vec, +} + +/// Cloneable handle. redb owns one clone; the harness keeps another to read the outcome. +#[derive(Clone, Debug)] +pub struct FaultFs(Arc>); + +impl FaultFs { + /// A disk whose contents are `image`, and which starts out durable. `plan` cuts the power at + /// one storage call. `lying_sync` makes `sync_data` report success without making anything + /// durable. + pub fn new(image: Vec, plan: Option, lying_sync: bool) -> Self { + let state = State { + live: image.clone(), + durable: image, + plan, + lying_sync, + ..State::default() + }; + Self(Arc::new(Mutex::new(state))) + } + + fn lock(&self) -> MutexGuard<'_, State> { + self.0.lock().expect("faultfs state lock") + } + + /// True once the power cut has landed. + pub fn cut(&self) -> bool { + self.lock().cut + } + + /// Every storage call so far, up to the cut. + pub fn trace(&self) -> Trace { + self.lock().trace.clone() + } + + /// The disk to reopen: the image at the cut, or the live bytes if no cut happened. + pub fn disk_image(&self) -> Vec { + let st = self.lock(); + if st.cut { + st.image.clone() + } else { + st.live.clone() + } + } +} + +/// `SplitMix64`. Every random choice in the model is derived from a seed through this function. +pub const fn splitmix(x: u64) -> u64 { + let mut z = x.wrapping_add(0x9E37_79B9_7F4A_7C15); + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) +} + +/// Whether the unsynced operation at `index` survives `Survive::Random` for this seed. +const fn keeps(seed: u64, index: usize) -> bool { + splitmix(seed ^ splitmix(index as u64 + 1)) & 1 == 1 +} + +fn apply(image: &mut Vec, op: &Op) { + match op { + Op::Write { offset, data } => { + let start = *offset as usize; + let end = start + data.len(); + if image.len() < end { + image.resize(end, 0); + } + image[start..end].copy_from_slice(data); + } + Op::SetLen(len) => image.resize(*len as usize, 0), + } +} + +/// The disk after a cut that keeps only the unsynced operations `Survive` selects. +fn surviving_image(st: &State) -> Vec { + let plan = st.plan.expect("a cut needs a plan"); + let n = st.pending.len(); + let order: Vec = match plan.survive { + Survive::Drop => Vec::new(), + Survive::Keep => (0..n).collect(), + Survive::Random => (0..n).filter(|&i| keeps(plan.seed, i)).collect(), + Survive::Reorder => { + let mut v: Vec = (0..n).filter(|&i| keeps(plan.seed, i)).collect(); + let mut s = plan.seed ^ 0xA5A5_A5A5; + for i in (1..v.len()).rev() { + s = splitmix(s); + v.swap(i, (s % (i as u64 + 1)) as usize); + } + v + } + }; + let mut image = st.durable.clone(); + for i in order { + apply(&mut image, &st.pending[i]); + } + image +} + +/// Makes every pending operation durable, in issue order. +fn flush(st: &mut State) { + let State { + durable, pending, .. + } = st; + for op in pending.drain(..) { + apply(durable, &op); + } +} + +/// Counts a storage call and reports whether the power cut lands on it. +fn tick(st: &mut State, kind: Kind, offset: u64, len: usize) -> bool { + st.trace.push((kind, offset, len)); + st.plan.is_some_and(|p| p.event == st.trace.len() as u64) +} + +impl StorageBackend for FaultFs { + fn len(&self) -> Result { + Ok(self.lock().live.len() as u64) + } + + fn read(&self, offset: u64, out: &mut [u8]) -> Result<(), io::Error> { + let st = self.lock(); + let start = offset as usize; + let end = start + out.len(); + if end > st.live.len() { + return Err(io::Error::new( + io::ErrorKind::UnexpectedEof, + "read past end", + )); + } + out.copy_from_slice(&st.live[start..end]); + Ok(()) + } + + fn set_len(&self, len: u64) -> Result<(), io::Error> { + let mut guard = self.lock(); + let st = &mut *guard; + if st.cut { + return Ok(()); + } + if tick(st, Kind::SetLen, len, 0) { + st.image = surviving_image(st); + st.cut = true; + return Ok(()); + } + st.live.resize(len as usize, 0); + st.pending.push(Op::SetLen(len)); + Ok(()) + } + + fn sync_data(&self) -> Result<(), io::Error> { + let mut guard = self.lock(); + let st = &mut *guard; + if st.cut { + return Ok(()); + } + if tick(st, Kind::Sync, 0, 0) { + let plan = st.plan.expect("a cut needs a plan"); + if plan.sync_completed && !st.lying_sync { + flush(st); + st.image = st.durable.clone(); + } else { + st.image = surviving_image(st); + } + st.cut = true; + return Ok(()); + } + if !st.lying_sync { + flush(st); + } + Ok(()) + } + + fn write(&self, offset: u64, data: &[u8]) -> Result<(), io::Error> { + let mut guard = self.lock(); + let st = &mut *guard; + if st.cut { + return Ok(()); + } + if tick(st, Kind::Write, offset, data.len()) { + let plan = st.plan.expect("a cut needs a plan"); + let mut image = surviving_image(st); + let landed = match plan.tear { + Tear::Off => 0, + Tear::Byte => (splitmix(plan.seed ^ 0x51) % (data.len() as u64 + 1)) as usize, + Tear::Sector => { + let sectors = (data.len() / 512) as u64; + (splitmix(plan.seed ^ 0x52) % (sectors + 1)) as usize * 512 + } + }; + if landed > 0 { + apply( + &mut image, + &Op::Write { + offset, + data: data[..landed].to_vec(), + }, + ); + } + st.image = image; + st.cut = true; + return Ok(()); + } + let end = offset as usize + data.len(); + if st.live.len() < end { + st.live.resize(end, 0); + } + st.live[offset as usize..end].copy_from_slice(data); + st.pending.push(Op::Write { + offset, + data: data.to_vec(), + }); + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::{FaultFs, Plan, Survive, Tear}; + use redb::StorageBackend; + use std::collections::BTreeSet; + + fn plan(event: u64, survive: Survive, tear: Tear, sync_completed: bool) -> Plan { + Plan { + event, + survive, + tear, + sync_completed, + seed: 7, + } + } + + #[test] + fn unsynced_writes_are_dropped_at_a_power_cut() { + // 1: write A, 2: sync, 3: write B (unsynced), 4: write C cuts the power. + let fs = FaultFs::new( + Vec::new(), + Some(plan(4, Survive::Drop, Tear::Off, false)), + false, + ); + fs.write(0, b"A").unwrap(); + fs.sync_data().unwrap(); + fs.write(1, b"B").unwrap(); + fs.write(2, b"C").unwrap(); + assert!(fs.cut()); + assert_eq!(fs.disk_image(), b"A"); + } + + #[test] + fn synced_writes_are_kept_and_unsynced_writes_survive_under_keep() { + // The same calls as above. Keep writes back B; C is the in-flight write and lands nothing. + let fs = FaultFs::new( + Vec::new(), + Some(plan(4, Survive::Keep, Tear::Off, false)), + false, + ); + fs.write(0, b"A").unwrap(); + fs.sync_data().unwrap(); + fs.write(1, b"B").unwrap(); + fs.write(2, b"C").unwrap(); + assert_eq!(fs.disk_image(), b"AB"); + } + + #[test] + fn a_completed_sync_makes_the_earlier_writes_durable() { + // 1: write A, 2: write B, 3: the sync completes, then power is lost. + let fs = FaultFs::new( + Vec::new(), + Some(plan(3, Survive::Drop, Tear::Off, true)), + false, + ); + fs.write(0, b"A").unwrap(); + fs.write(1, b"B").unwrap(); + fs.sync_data().unwrap(); + assert!(fs.cut()); + assert_eq!(fs.disk_image(), b"AB"); + } + + #[test] + fn a_sync_cut_before_the_sync_takes_effect_loses_the_writes() { + // 1: write A, 2: power is lost during the sync. + let fs = FaultFs::new( + Vec::new(), + Some(plan(2, Survive::Drop, Tear::Off, false)), + false, + ); + fs.write(0, b"A").unwrap(); + fs.sync_data().unwrap(); + assert_eq!(fs.disk_image(), b""); + } + + #[test] + fn a_torn_write_lands_a_prefix_of_its_bytes() { + let data: Vec = (0..1024u32).map(|i| (i % 251) as u8 + 1).collect(); + let mut byte_lengths = BTreeSet::new(); + for seed in 0..64 { + for tear in [Tear::Byte, Tear::Sector] { + let p = Some(Plan { + event: 3, + survive: Survive::Drop, + tear, + sync_completed: false, + seed, + }); + let fs = FaultFs::new(Vec::new(), p, false); + fs.write(0, b"A").unwrap(); + fs.sync_data().unwrap(); + // 3: the in-flight write, torn. + fs.write(1, &data).unwrap(); + let img = fs.disk_image(); + assert_eq!(img[0], b'A'); + let landed = img.len() - 1; + assert!(landed <= data.len(), "seed {seed} {tear:?}"); + assert_eq!( + &img[1..], + &data[..landed], + "seed {seed} {tear:?}: not a prefix" + ); + if tear == Tear::Sector { + assert_eq!( + landed % 512, + 0, + "seed {seed}: a sector tear lands whole sectors" + ); + } else { + byte_lengths.insert(landed); + } + } + } + assert!( + byte_lengths.len() > 2, + "byte tears should land different lengths: {byte_lengths:?}" + ); + } + + #[test] + fn a_lying_sync_leaves_nothing_durable() { + // 1: write A, 2: sync (lies), 3: write B cuts the power. + let fs = FaultFs::new( + Vec::new(), + Some(plan(3, Survive::Drop, Tear::Off, false)), + true, + ); + fs.write(0, b"A").unwrap(); + fs.sync_data().unwrap(); + fs.write(1, b"B").unwrap(); + assert!(fs.cut()); + assert_eq!(fs.disk_image(), b""); + } + + #[test] + fn set_len_is_unsynced_until_a_sync() { + // 1: write AB, 2: sync, 3: set_len(1) is unsynced, 4: a write cuts the power. + let dropped = FaultFs::new( + Vec::new(), + Some(plan(4, Survive::Drop, Tear::Off, false)), + false, + ); + dropped.write(0, b"AB").unwrap(); + dropped.sync_data().unwrap(); + dropped.set_len(1).unwrap(); + dropped.write(2, b"Z").unwrap(); + assert_eq!(dropped.disk_image(), b"AB"); + + let kept = FaultFs::new( + Vec::new(), + Some(plan(4, Survive::Keep, Tear::Off, false)), + false, + ); + kept.write(0, b"AB").unwrap(); + kept.sync_data().unwrap(); + kept.set_len(1).unwrap(); + kept.write(2, b"Z").unwrap(); + assert_eq!(kept.disk_image(), b"A"); + } + + #[test] + fn random_and_reorder_keep_a_subset_of_the_unsynced_writes() { + for survive in [Survive::Random, Survive::Reorder] { + let (mut some_lost, mut some_kept) = (false, false); + for seed in 0..64 { + let p = Some(Plan { + event: 4, + survive, + tear: Tear::Off, + sync_completed: false, + seed, + }); + let fs = FaultFs::new(Vec::new(), p, false); + // 1-3: three unsynced writes at distinct offsets. 4: a write cuts the power. + fs.write(0, b"a").unwrap(); + fs.write(1, b"b").unwrap(); + fs.write(2, b"c").unwrap(); + fs.write(3, b"d").unwrap(); + let img = fs.disk_image(); + assert!( + img.len() <= 3, + "seed {seed} {survive:?}: the in-flight write landed" + ); + for (i, &byte) in img.iter().enumerate() { + assert!( + byte == 0 || byte == b"abc"[i], + "seed {seed} {survive:?}: byte {i} is {byte}" + ); + } + let kept = (0..3) + .filter(|&i| img.get(i).is_some_and(|&b| b != 0)) + .count(); + some_lost |= kept < 3; + some_kept |= kept > 0; + } + assert!( + some_lost && some_kept, + "{survive:?} should keep some writes and drop others" + ); + } + } + + #[test] + fn calls_after_the_cut_do_not_reach_the_disk() { + // 1: write A cuts the power, and the write itself is lost. + let fs = FaultFs::new( + Vec::new(), + Some(plan(1, Survive::Keep, Tear::Off, false)), + false, + ); + fs.write(0, b"A").unwrap(); + fs.write(0, b"Z").unwrap(); + fs.sync_data().unwrap(); + fs.set_len(0).unwrap(); + assert!(fs.cut()); + assert_eq!(fs.disk_image(), b""); + assert_eq!(fs.trace().len(), 1); + } +} diff --git a/pkgs/id/tests/crash/harness.rs b/pkgs/id/tests/crash/harness.rs new file mode 100644 index 0000000000..6c450b790c --- /dev/null +++ b/pkgs/id/tests/crash/harness.rs @@ -0,0 +1,245 @@ +//! Runs the workload with one power-cut plan, reopens the disk image, and classifies the result. +//! +//! Acknowledged = a commit that returned `Ok` before the cut. A commit in flight at the cut is not +//! acknowledged. The reopened state must be the model after `acked` transactions, or after +//! `acked + 1` (the in-flight one may have become durable). Anything else is a failure. + +use crate::faultfs::{FaultFs, Plan, Trace}; +use crate::workload::{self, Model, TXNS}; +use redb::Database; +use std::any::Any; +use std::panic::{self, AssertUnwindSafe}; +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Verdict { + /// Reopened state is the model after every acknowledged commit. + OkAcked, + /// Reopened state includes the in-flight commit as well. + OkAckedPlusOne, + /// The image does not open, but no commit had been acknowledged yet. Not data loss; reported. + OpenErrorPreCommit, + /// Reopened state is an older prefix than the acknowledged one. + LostCommitted, + /// Reopened state matches no prefix of the workload (for example, half of a batch). + Partial, + /// Reopened state is a later prefix than the in-flight commit. Cannot happen if the cut works. + Future, + /// The image did not open, or a read failed, after acknowledged commits. + OpenError, + /// `check_integrity` returned false or failed. + Integrity, + /// A commit after recovery failed, or the state did not survive a clean reopen. + PostRecovery, + /// The workload returned an error although no cut happened. + NoCrashError, + /// The workload, or the reopen of the image, panicked. + Panic, +} + +impl Verdict { + pub const fn name(self) -> &'static str { + match self { + Self::OkAcked => "ok_acked", + Self::OkAckedPlusOne => "ok_acked_plus_one", + Self::OpenErrorPreCommit => "open_error_pre_commit", + Self::LostCommitted => "lost_committed", + Self::Partial => "partial", + Self::Future => "future", + Self::OpenError => "open_error", + Self::Integrity => "integrity", + Self::PostRecovery => "post_recovery", + Self::NoCrashError => "no_crash_error", + Self::Panic => "panic", + } + } + + /// The verdict with this name, if there is one. The corpus stores verdicts by name. + pub fn from_name(name: &str) -> Option { + [ + Self::OkAcked, + Self::OkAckedPlusOne, + Self::OpenErrorPreCommit, + Self::LostCommitted, + Self::Partial, + Self::Future, + Self::OpenError, + Self::Integrity, + Self::PostRecovery, + Self::NoCrashError, + Self::Panic, + ] + .into_iter() + .find(|v| v.name() == name) + } + + /// Whether this verdict is a durability or consistency failure. Only `OkAcked`, + /// `OkAckedPlusOne` and `OpenErrorPreCommit` are not. + pub const fn is_failure(self) -> bool { + !matches!( + self, + Self::OkAcked | Self::OkAckedPlusOne | Self::OpenErrorPreCommit + ) + } +} + +#[derive(Debug)] +pub struct Outcome { + pub verdict: Verdict, + pub acked: u64, + /// Repair callbacks redb ran while reopening the image. + pub repairs: u64, + pub detail: String, +} + +fn run_workload(fs: &FaultFs, acked: &mut u64) -> Result<(), String> { + let db = Database::builder() + .create_with_backend(fs.clone()) + .map_err(|e| format!("create: {e}"))?; + for b in 0..TXNS { + let result = workload::commit(&db, &workload::txn_ops(b)); + if fs.cut() { + // The process died inside this call. The commit is not acknowledged. + return Ok(()); + } + result.map_err(|e| format!("commit {b}: {e}"))?; + *acked = b + 1; + } + drop(db); // a clean close; its writes are storage calls too + Ok(()) +} + +/// Commits once more on the recovered database, then reopens the result and checks that the +/// recovered state and the new commit both survive. +fn post_recovery(db: Database, backing: &FaultFs, expected: &Model) -> Result<(), String> { + let txn = db.begin_write().map_err(|e| format!("begin: {e}"))?; + { + let mut meta = txn + .open_table(workload::META) + .map_err(|e| format!("open meta: {e}"))?; + meta.insert(b"post-recovery".as_slice(), b"ok".as_slice()) + .map_err(|e| format!("insert: {e}"))?; + } + txn.commit().map_err(|e| format!("commit: {e}"))?; + drop(db); + let again = Database::builder() + .create_with_backend(FaultFs::new(backing.disk_image(), None, false)) + .map_err(|e| format!("reopen: {e}"))?; + let mut want = expected.clone(); + want.insert( + (workload::META_TAG, b"post-recovery".to_vec()), + b"ok".to_vec(), + ); + let got = workload::dump(&again).map_err(|e| format!("dump: {e}"))?; + if got == want { + Ok(()) + } else { + Err("state after the post-recovery commit and clean reopen differs".into()) + } +} + +fn verify(image: Vec, acked: u64, models: &[Model]) -> Outcome { + let reopened = FaultFs::new(image, None, false); + let repairs = Arc::new(AtomicU64::new(0)); + let counter = Arc::clone(&repairs); + let mut builder = Database::builder(); + builder.set_repair_callback(move |_| { + counter.fetch_add(1, Ordering::SeqCst); + }); + let outcome = |verdict: Verdict, detail: String| Outcome { + verdict, + acked, + repairs: repairs.load(Ordering::SeqCst), + detail, + }; + let mut db = match builder.create_with_backend(reopened.clone()) { + Ok(db) => db, + Err(e) => { + let verdict = if acked == 0 { + Verdict::OpenErrorPreCommit + } else { + Verdict::OpenError + }; + return outcome(verdict, format!("open: {e}")); + } + }; + let state = match workload::dump(&db) { + Ok(state) => state, + Err(e) => return outcome(Verdict::OpenError, format!("dump: {e}")), + }; + let n = acked as usize; + let verdict = if state == models[n] { + Verdict::OkAcked + } else if n + 1 < models.len() && state == models[n + 1] { + Verdict::OkAckedPlusOne + } else if models[..n].contains(&state) { + Verdict::LostCommitted + } else if models.iter().skip(n + 2).any(|m| *m == state) { + Verdict::Future + } else { + Verdict::Partial + }; + if verdict.is_failure() { + return outcome(verdict, String::new()); + } + match db.check_integrity() { + Ok(true) => {} + Ok(false) => return outcome(Verdict::Integrity, "check_integrity returned false".into()), + Err(e) => return outcome(Verdict::Integrity, format!("check_integrity: {e}")), + } + if let Err(e) = post_recovery(db, &reopened, &state) { + return outcome(Verdict::PostRecovery, e); + } + outcome(verdict, String::new()) +} + +fn panic_text(payload: &(dyn Any + Send)) -> String { + payload + .downcast_ref::<&str>() + .map(|s| (*s).to_owned()) + .or_else(|| payload.downcast_ref::().cloned()) + .unwrap_or_else(|| "non-string panic payload".into()) +} + +/// Runs one plan (or no plan, for the clean run) and returns the outcome and the storage-call +/// trace. Panics never escape: a panic before the cut, or while reopening, is a verdict. +pub fn run_one(plan: Option, lying_sync: bool, models: &[Model]) -> (Outcome, Trace) { + let fs = FaultFs::new(Vec::new(), plan, lying_sync); + let mut acked = 0u64; + let attempt = panic::catch_unwind(AssertUnwindSafe(|| run_workload(&fs, &mut acked))); + let trace = fs.trace(); + let outcome = match attempt { + Err(payload) if !fs.cut() => Outcome { + verdict: Verdict::Panic, + acked, + repairs: 0, + detail: format!( + "panic before the power cut: {}", + panic_text(payload.as_ref()) + ), + }, + Ok(Err(e)) if !fs.cut() => Outcome { + verdict: Verdict::NoCrashError, + acked, + repairs: 0, + detail: e, + }, + // A cut (or a clean finish) leaves a disk image to reopen. A panic or error after the cut + // is the dead process failing, not a finding. + _ => match panic::catch_unwind(AssertUnwindSafe(|| verify(fs.disk_image(), acked, models))) + { + Ok(outcome) => outcome, + Err(payload) => Outcome { + verdict: Verdict::Panic, + acked, + repairs: 0, + detail: format!( + "panic while reopening the image: {}", + panic_text(payload.as_ref()) + ), + }, + }, + }; + (outcome, trace) +} diff --git a/pkgs/id/tests/crash/main.rs b/pkgs/id/tests/crash/main.rs new file mode 100644 index 0000000000..edd9995fd6 --- /dev/null +++ b/pkgs/id/tests/crash/main.rs @@ -0,0 +1,271 @@ +//! The crash-safety gate for redb (plan step P1.4). +//! +//! `faultfs` is a `redb::StorageBackend` that loses unsynced writes at a simulated power cut, +//! applies one of four survival policies to them, and can tear the write in flight. `workload` is +//! 50 redb write transactions with a model for every prefix. `harness` cuts the power at one +//! storage call, reopens the image, and classifies the result. `sweep` runs the plans on all +//! threads, and `corpus` reads and writes the checked-in replay list. +//! +//! `cargo test` runs the sampled sweep (every `SAMPLE_STRIDE`th storage call), the lying-sync +//! control, and the corpus replay. `just crash-gate` runs the two full tests in release mode, +//! where every storage call is a crash point. A failure found by a sweep goes into `corpus.tsv` +//! with its fix (see `corpus.rs`). + +// Offsets and lengths index in-memory disk images, which stay far below 4 GiB, so the u64 to usize +// casts cannot truncate on any target this runs on. +#![allow( + clippy::unwrap_used, + clippy::expect_used, + clippy::panic, + clippy::cast_possible_truncation +)] + +mod corpus; +mod faultfs; +mod harness; +mod sweep; +mod workload; + +use corpus::{Expect, Header, Row}; +use faultfs::{Kind, Trace}; +use harness::{Outcome, Verdict, run_one}; +use std::collections::BTreeMap; +use sweep::{Job, describe, jobs_for, report, run_jobs, sample_events}; +use workload::{Model, TXNS}; + +/// The default run crashes at every `SAMPLE_STRIDE`th storage call, and at the last one. At 20 the +/// sampled sweep is about 380 runs, a few seconds in debug. +const SAMPLE_STRIDE: u64 = 20; + +/// How many failing runs an assertion message lists. +const LISTED: usize = 20; + +const CORPUS_PATH: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/crash/corpus.tsv"); +const CORPUS: &str = include_str!("corpus.tsv"); + +/// Sweeps the given crash points of one trace. Returns the jobs, their outcomes, and the indices of +/// the failing runs. +fn sweep_points( + label: &str, + trace: &Trace, + events: &[u64], + lying: bool, + models: &[Model], +) -> (Vec, Vec, Vec) { + let jobs = jobs_for(trace, events, lying); + let outcomes = run_jobs(&jobs, models); + let failing = report(label, &jobs, &outcomes); + (jobs, outcomes, failing) +} + +/// The first failing runs, one per line, for an assertion message. +fn listing(jobs: &[Job], outcomes: &[Outcome], failing: &[usize]) -> String { + failing + .iter() + .take(LISTED) + .map(|&i| describe(&jobs[i], &outcomes[i])) + .collect::>() + .join("\n") +} + +/// A lying `sync_data` must lose committed data somewhere, or the oracle cannot see durability. +fn assert_control_fails(outcomes: &[Outcome], failing: &[usize]) { + assert!( + !failing.is_empty(), + "the lying-sync control produced no failures: the oracle cannot see lost durability" + ); + assert!( + failing.iter().any(|&i| matches!( + outcomes[i].verdict, + Verdict::LostCommitted | Verdict::OpenError + )), + "the control failed, but never with lost_committed or open_error" + ); +} + +#[test] +fn clean_run_reopens_with_every_transaction() { + let models = workload::models(); + let (outcome, trace) = run_one(None, false, &models); + assert_eq!(outcome.verdict, Verdict::OkAcked, "{}", outcome.detail); + assert_eq!(outcome.acked, TXNS); + assert!(!trace.is_empty()); +} + +#[test] +fn sampled_sweep_has_no_failures() { + let models = workload::models(); + let (_, trace) = run_one(None, false, &models); + let events = sample_events(trace.len() as u64, SAMPLE_STRIDE); + let (jobs, outcomes, failing) = sweep_points("sampled sweep", &trace, &events, false, &models); + assert!( + failing.is_empty(), + "{} failing runs:\n{}", + failing.len(), + listing(&jobs, &outcomes, &failing) + ); +} + +#[test] +fn lying_sync_control_produces_failures() { + let models = workload::models(); + let (_, trace) = run_one(None, true, &models); + let events = sample_events(trace.len() as u64, SAMPLE_STRIDE); + let (_, outcomes, failing) = + sweep_points("control (lying sync)", &trace, &events, true, &models); + assert_control_fails(&outcomes, &failing); +} + +#[test] +fn corpus_replays_with_recorded_verdicts() { + let models = workload::models(); + let (_, trace) = run_one(None, false, &models); + let (header, rows) = corpus::parse(CORPUS).expect("corpus.tsv parses"); + assert_eq!( + header, + Header { + storage_calls: trace.len() as u64, + trace_fnv1a: corpus::trace_fnv1a(&trace), + }, + "the storage-call trace changed. Check the change, then regenerate corpus.tsv (see its header)" + ); + let mut problems = Vec::new(); + for row in &rows { + let actual = (row.job.plan.event as usize) + .checked_sub(1) + .and_then(|i| trace.get(i)) + .map(|call| call.0); + if actual != Some(row.kind) { + let actual = actual.map_or("no such call", Kind::name); + problems.push(format!( + "{}: event {} is {actual}, not {}", + row.name, + row.job.plan.event, + row.kind.name() + )); + } + } + let jobs: Vec = rows.iter().map(|row| row.job).collect(); + let outcomes = run_jobs(&jobs, &models); + for (row, outcome) in rows.iter().zip(&outcomes) { + if !row.expect.accepts(outcome.verdict) { + problems.push(format!( + "{}: got {} ({}), expected {}", + row.name, + outcome.verdict.name(), + outcome.detail, + row.expect.name() + )); + } + } + assert!( + problems.is_empty(), + "{} corpus rows changed:\n{}", + problems.len(), + problems.join("\n") + ); +} + +#[test] +#[ignore = "the full gate: every storage call under every plan. `just crash-gate` runs it in release"] +fn full_sweep_has_no_failures() { + let models = workload::models(); + let (_, trace) = run_one(None, false, &models); + let events: Vec = (1..=trace.len() as u64).collect(); + let (jobs, outcomes, failing) = sweep_points("full sweep", &trace, &events, false, &models); + assert!( + failing.is_empty(), + "{} failing runs:\n{}", + failing.len(), + listing(&jobs, &outcomes, &failing) + ); +} + +#[test] +#[ignore = "the full control: every storage call under a lying sync. `just crash-gate` runs it in release"] +fn full_lying_sync_control_produces_failures() { + let models = workload::models(); + let (_, trace) = run_one(None, true, &models); + let events: Vec = (1..=trace.len() as u64).collect(); + let (_, outcomes, failing) = + sweep_points("full control (lying sync)", &trace, &events, true, &models); + assert_control_fails(&outcomes, &failing); +} + +/// Rewrites `corpus.tsv`: every faithful point that ends in a pre-commit open error or an +/// acknowledged-plus-one state, two of each failing class from the control, and the `fix-` rows +/// already in the file. A faithful failure stops it, because such a failure needs a fix first. +#[test] +#[ignore = "rewrites corpus.tsv. Run by hand, in release, after a deliberate workload or redb change"] +fn write_corpus() { + let models = workload::models(); + let (_, trace) = run_one(None, false, &models); + let all: Vec = (1..=trace.len() as u64).collect(); + + let (jobs, outcomes, failing) = sweep_points("faithful sweep", &trace, &all, false, &models); + assert!( + failing.is_empty(), + "a faithful run failed. Fix it, then add its row by hand as fix-:\n{}", + listing(&jobs, &outcomes, &failing) + ); + let mut rows = Vec::new(); + for (job, outcome) in jobs.iter().zip(&outcomes) { + let (prefix, expect) = match outcome.verdict { + Verdict::OpenErrorPreCommit => ("faithful-pre-commit", Expect::Exact(outcome.verdict)), + Verdict::OkAckedPlusOne => ("faithful-plus-one", Expect::Valid), + _ => continue, + }; + rows.push(corpus_row(plan_name(prefix, job), *job, &trace, expect)); + } + + let (cjobs, coutcomes, _) = sweep_points("control sweep", &trace, &all, true, &models); + let mut taken: BTreeMap<&str, usize> = BTreeMap::new(); + for (job, outcome) in cjobs.iter().zip(&coutcomes) { + let v = outcome.verdict; + // The failing classes must match exactly. An acknowledged-plus-one control point may differ + // between debug and release (crash-tests/RESULTS.md, E9 in round 2), so it accepts either + // valid prefix. + let expect = match v { + Verdict::LostCommitted | Verdict::OpenError | Verdict::Panic => Expect::Exact(v), + Verdict::OkAckedPlusOne => Expect::Valid, + _ => continue, + }; + let count = taken.entry(v.name()).or_default(); + if *count < 2 { + *count += 1; + let name = format!("control-{}-{count}", v.name()); + rows.push(corpus_row(name, *job, &trace, expect)); + } + } + + let existing = std::fs::read_to_string(CORPUS_PATH).expect("read corpus.tsv"); + let (_, kept) = corpus::parse(&existing).expect("corpus.tsv parses"); + rows.extend(kept.into_iter().filter(|row| row.name.starts_with("fix-"))); + + let header = Header { + storage_calls: trace.len() as u64, + trace_fnv1a: corpus::trace_fnv1a(&trace), + }; + std::fs::write(CORPUS_PATH, corpus::format(&header, &rows)).expect("write corpus.tsv"); + println!("wrote {} rows to {CORPUS_PATH}", rows.len()); +} + +fn plan_name(prefix: &str, job: &Job) -> String { + let p = job.plan; + format!( + "{prefix}-{:03}-{}-{}-{}", + p.event, + p.survive.name(), + p.tear.name(), + u8::from(p.sync_completed) + ) +} + +fn corpus_row(name: String, job: Job, trace: &Trace, expect: Expect) -> Row { + Row { + name, + job, + kind: trace[job.plan.event as usize - 1].0, + expect, + } +} diff --git a/pkgs/id/tests/crash/sweep.rs b/pkgs/id/tests/crash/sweep.rs new file mode 100644 index 0000000000..eaf996f953 --- /dev/null +++ b/pkgs/id/tests/crash/sweep.rs @@ -0,0 +1,163 @@ +//! Sweeps: which crash points a run covers, how the runs are spread over threads, and how a sweep +//! is reported. +//! +//! Every storage call of the workload is a crash point. Each crash point runs under every survival +//! policy, and writes also run under every tear mode. + +use crate::faultfs::{Kind, Plan, Survive, Tear, Trace, splitmix}; +use crate::harness::{Outcome, run_one}; +use crate::workload::Model; +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::atomic::{AtomicUsize, Ordering}; + +const SURVIVE: [Survive; 4] = [ + Survive::Drop, + Survive::Keep, + Survive::Random, + Survive::Reorder, +]; +const TEAR: [Tear; 3] = [Tear::Off, Tear::Byte, Tear::Sector]; + +/// One run of the workload: a plan, and whether `sync_data` lies. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Job { + pub plan: Plan, + pub lying: bool, +} + +/// Every plan for one crash point. A write gets each survival policy with each tear mode (12). +/// A `set_len` gets each survival policy (4). A sync gets each survival policy with the sync +/// lost, plus one run where the sync completed and power was lost right after it (5). +pub fn plans_for(event: u64, kind: Kind) -> Vec { + let mut out = Vec::new(); + let mut variant = 0u64; + let mut push = |survive, tear, sync_completed| { + variant += 1; + let seed = splitmix(event * 64 + variant); + out.push(Plan { + event, + survive, + tear, + sync_completed, + seed, + }); + }; + match kind { + Kind::Write => { + for tear in TEAR { + for survive in SURVIVE { + push(survive, tear, false); + } + } + } + Kind::SetLen => { + for survive in SURVIVE { + push(survive, Tear::Off, false); + } + } + Kind::Sync => { + for survive in SURVIVE { + push(survive, Tear::Off, false); + } + push(Survive::Drop, Tear::Off, true); + } + } + out +} + +/// The jobs for the given crash points (1-based storage-call numbers), in order. +pub fn jobs_for(trace: &Trace, events: &[u64], lying: bool) -> Vec { + events + .iter() + .flat_map(|&event| { + let kind = trace[event as usize - 1].0; + plans_for(event, kind) + .into_iter() + .map(move |plan| Job { plan, lying }) + }) + .collect() +} + +/// Every `stride`th crash point, starting with the first, plus the last one (the final close). +pub fn sample_events(total: u64, stride: u64) -> Vec { + (1..=total) + .filter(|e| (e - 1) % stride == 0 || *e == total) + .collect() +} + +/// Runs the jobs on all available threads. The result is in the same order as `jobs`. +pub fn run_jobs(jobs: &[Job], models: &[Model]) -> Vec { + let next = AtomicUsize::new(0); + let threads = std::thread::available_parallelism() + .map_or(4, usize::from) + .min(jobs.len().max(1)); + let mut slots: Vec> = (0..jobs.len()).map(|_| None).collect(); + std::thread::scope(|s| { + let workers: Vec<_> = (0..threads) + .map(|_| { + s.spawn(|| { + let mut done = Vec::new(); + loop { + let i = next.fetch_add(1, Ordering::Relaxed); + let Some(job) = jobs.get(i) else { break }; + done.push((i, run_one(Some(job.plan), job.lying, models).0)); + } + done + }) + }) + .collect(); + for worker in workers { + for (i, outcome) in worker.join().expect("sweep worker panicked") { + slots[i] = Some(outcome); + } + } + }); + slots + .into_iter() + .map(|o| o.expect("every job ran")) + .collect() +} + +/// Prints the verdict counts for one sweep and returns the indices of its failing runs. +pub fn report(label: &str, jobs: &[Job], outcomes: &[Outcome]) -> Vec { + let mut verdicts: BTreeMap<&str, usize> = BTreeMap::new(); + let mut points = BTreeSet::new(); + let mut failing = Vec::new(); + let mut repaired = 0; + for (i, (job, outcome)) in jobs.iter().zip(outcomes).enumerate() { + *verdicts.entry(outcome.verdict.name()).or_default() += 1; + points.insert(job.plan.event); + if outcome.verdict.is_failure() { + failing.push(i); + } + if outcome.repairs > 0 { + repaired += 1; + } + } + println!( + "{label}: {} crash points, {} runs", + points.len(), + jobs.len() + ); + println!("{label}: verdicts {verdicts:?}"); + println!("{label}: reopens that ran redb repair: {repaired} runs"); + println!("{label}: failing runs {}", failing.len()); + failing +} + +/// One line per run, for a failure message: where power was lost, and what the run found. +pub fn describe(job: &Job, outcome: &Outcome) -> String { + let p = job.plan; + format!( + "event={} lying={} survive={} tear={} sync_completed={} seed={} verdict={} acked={} {}", + p.event, + u8::from(job.lying), + p.survive.name(), + p.tear.name(), + u8::from(p.sync_completed), + p.seed, + outcome.verdict.name(), + outcome.acked, + outcome.detail + ) +} diff --git a/pkgs/id/tests/crash/workload.rs b/pkgs/id/tests/crash/workload.rs new file mode 100644 index 0000000000..277de7c6df --- /dev/null +++ b/pkgs/id/tests/crash/workload.rs @@ -0,0 +1,164 @@ +//! The 50-transaction workload and its model. +//! +//! Each transaction is one redb write transaction. It inserts a batch of event rows and their +//! author-index rows, deletes the batch from five transactions earlier (so pages are freed and +//! reused), and updates two meta rows. The model is the map that results from applying the first +//! n transactions, so the verifier can say exactly which prefix a reopened database holds. + +use redb::{Database, ReadableDatabase, ReadableTable, TableDefinition, TableError}; +use std::collections::BTreeMap; +use std::error::Error; + +pub const TXNS: u64 = 50; + +pub const EVENTS: TableDefinition<'static, &'static [u8], &'static [u8]> = + TableDefinition::new("events"); +pub const BY_AUTHOR: TableDefinition<'static, &'static [u8], &'static [u8]> = + TableDefinition::new("by_author"); +pub const META: TableDefinition<'static, &'static [u8], &'static [u8]> = + TableDefinition::new("meta"); + +pub const EVENTS_TAG: u8 = 0; +pub const BY_AUTHOR_TAG: u8 = 1; +pub const META_TAG: u8 = 2; + +/// Every row, keyed by (table tag, key bytes). Values are the stored bytes. +pub type Model = BTreeMap<(u8, Vec), Vec>; + +#[derive(Clone, Debug)] +pub enum Op { + Put(u8, Vec, Vec), + Del(u8, Vec), +} + +/// Claims in transaction `b`. Every tenth transaction is large enough to split B-tree pages. +const fn claims(b: u64) -> u64 { + if b % 10 == 9 { 120 } else { 8 + (b * 7) % 25 } +} + +fn first_event(b: u64) -> u64 { + (0..b).map(claims).sum() +} + +fn author_key(b: u64, seq: u64) -> Vec { + let mut key = (b % 3).to_be_bytes().to_vec(); + key.extend_from_slice(&seq.to_be_bytes()); + key +} + +fn payload(b: u64, i: u64) -> Vec { + let mut v = format!("txn{b:03}-claim{i:03}-").into_bytes(); + v.resize(24 + ((b * 13 + i * 5) % 40) as usize, b'.'); + v +} + +/// The operations of transaction `b`. +pub fn txn_ops(b: u64) -> Vec { + let mut ops = Vec::new(); + let base = first_event(b); + for i in 0..claims(b) { + let event = (base + i).to_be_bytes().to_vec(); + ops.push(Op::Put(EVENTS_TAG, event.clone(), payload(b, i))); + ops.push(Op::Put(BY_AUTHOR_TAG, author_key(b, b * 1000 + i), event)); + } + if b >= 5 { + let old = first_event(b - 5); + ops.push(Op::Del(EVENTS_TAG, old.to_be_bytes().to_vec())); + ops.push(Op::Del(BY_AUTHOR_TAG, author_key(b - 5, (b - 5) * 1000))); + } + ops.push(Op::Put( + META_TAG, + b"txns".to_vec(), + (b + 1).to_be_bytes().to_vec(), + )); + ops.push(Op::Put( + META_TAG, + b"last".to_vec(), + b.to_be_bytes().to_vec(), + )); + ops +} + +pub fn apply_ops(model: &mut Model, ops: &[Op]) { + for op in ops { + match op { + Op::Put(tag, k, v) => { + model.insert((*tag, k.clone()), v.clone()); + } + Op::Del(tag, k) => { + model.remove(&(*tag, k.clone())); + } + } + } +} + +/// `models()[n]` is the state after the first `n` transactions, for `n` in `0..=TXNS`. +pub fn models() -> Vec { + let mut out = vec![Model::new()]; + let mut m = Model::new(); + for b in 0..TXNS { + apply_ops(&mut m, &txn_ops(b)); + out.push(m.clone()); + } + out +} + +/// One write transaction with the given operations. +pub fn commit(db: &Database, ops: &[Op]) -> Result<(), Box> { + let txn = db.begin_write()?; + { + let mut events = txn.open_table(EVENTS)?; + let mut by_author = txn.open_table(BY_AUTHOR)?; + let mut meta = txn.open_table(META)?; + for op in ops { + match op { + Op::Put(tag, k, v) => match *tag { + EVENTS_TAG => { + events.insert(k.as_slice(), v.as_slice())?; + } + BY_AUTHOR_TAG => { + by_author.insert(k.as_slice(), v.as_slice())?; + } + _ => { + meta.insert(k.as_slice(), v.as_slice())?; + } + }, + Op::Del(tag, k) => match *tag { + EVENTS_TAG => { + events.remove(k.as_slice())?; + } + BY_AUTHOR_TAG => { + by_author.remove(k.as_slice())?; + } + _ => { + meta.remove(k.as_slice())?; + } + }, + } + } + } + txn.commit()?; + Ok(()) +} + +/// Every row in the database, as a model. A table that does not exist yet counts as empty. +pub fn dump(db: &Database) -> Result> { + let txn = db.begin_read()?; + let mut model = Model::new(); + for (tag, def) in [ + (EVENTS_TAG, EVENTS), + (BY_AUTHOR_TAG, BY_AUTHOR), + (META_TAG, META), + ] { + let table = match txn.open_table(def) { + Ok(t) => t, + Err(TableError::TableDoesNotExist(_)) => continue, + Err(e) => return Err(e.into()), + }; + for row in table.iter()? { + let (k, v) = row?; + model.insert((tag, k.value().to_vec()), v.value().to_vec()); + } + } + Ok(model) +} From a2f842fc568b879156bd2ff869a74e463c203b17 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 11 Oct 2026 18:12:17 -0500 Subject: [PATCH 08/30] fix(id): one redb dependency for the store, the crash model, and the identity store [P1.9] --- pkgs/id/Cargo.toml | 2 -- 1 file changed, 2 deletions(-) diff --git a/pkgs/id/Cargo.toml b/pkgs/id/Cargo.toml index d42e8aeae8..69b3346ca5 100644 --- a/pkgs/id/Cargo.toml +++ b/pkgs/id/Cargo.toml @@ -29,7 +29,6 @@ web = [ "dep:rmp-serde", "dep:comrak", "dep:urlencoding", - "dep:redb", "dep:aes-gcm", "dep:base64", "dep:hkdf", @@ -80,7 +79,6 @@ futures = { version = "0.3.32", optional = true } rmp-serde = { version = "1", optional = true } comrak = { version = "0.56", default-features = false, optional = true } urlencoding = { version = "2", optional = true } -redb = { version = "4.3", optional = true } aes-gcm = { version = "0.11", default-features = false, features = ["aes", "alloc"], optional = true } base64 = { version = "0.22", optional = true } qrcode = { version = "0.14.1", default-features = false, optional = true } From 2eb950b948dbdd127458a695bc5420337ea11bf1 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 11 Oct 2026 18:51:26 -0500 Subject: [PATCH 09/30] fix(rust): identity file made by rename, so first creation cannot strand it [P1.10] Creation wrote the store file at its final name. A crash during the first creation could leave a file that redb refuses to open ("Invalid magic number"), and the store could not start again. Creation now builds the file under .creating, makes the first commit, renames it into place, and syncs the directory before the store is returned. A stale .creating file from an interrupted creation is overwritten. A torn file at the store's own name is still refused, with an error. --- pkgs/id/src/web/identity.rs | 121 +++++++++++++++++++++++++++++++++--- 1 file changed, 113 insertions(+), 8 deletions(-) diff --git a/pkgs/id/src/web/identity.rs b/pkgs/id/src/web/identity.rs index e696ec52fa..03139d5ae9 100644 --- a/pkgs/id/src/web/identity.rs +++ b/pkgs/id/src/web/identity.rs @@ -42,12 +42,14 @@ //! internally. Clone it freely across handlers. use std::collections::HashMap; +use std::ffi::{OsStr, OsString}; use std::path::{Path, PathBuf}; use std::sync::Arc; use std::time::{SystemTime, UNIX_EPOCH}; use aes_gcm::aead::{Aead, Payload}; use aes_gcm::{Aes256Gcm, KeyInit}; +use anyhow::Context as _; use ed25519_dalek::{Signer, SigningKey, VerifyingKey}; use hkdf::Hkdf; use redb::{Database, DatabaseError, ReadableDatabase, ReadableTable, TableDefinition}; @@ -481,16 +483,39 @@ struct IdentityDb { } impl IdentityDb { - /// Open or create the file at `path`, then [`load`](Self::load) it. + /// Open the file at `path`, or create it if it does not exist, then [`load`](Self::load) it. + /// + /// A new file is built under a temporary name, so `path` only ever names a file that redb can + /// open. The first commit makes the file a valid, empty store. It is then renamed into place, + /// and the directory is synced before the store is returned, so no acknowledged write can + /// depend on a rename that has not reached the disk. A crash during creation leaves at most a + /// stale temporary file, which the next creation overwrites. fn open(path: &Path, key: &[u8; 32]) -> anyhow::Result<(Self, Vec)> { - let db = Database::create(path).map_err(|e| match e { - DatabaseError::DatabaseAlreadyOpen => anyhow::anyhow!( - "identity store {} is already open in another process or handle", - path.display() - ), - other => anyhow::anyhow!("failed to open identity store {}: {other}", path.display()), + if path.exists() { + let db = Database::create(path).map_err(|e| store_error(path, e))?; + return Self::load(db, key); + } + let temp = creating_path(path); + let file = std::fs::OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(true) + .open(&temp) + .with_context(|| format!("failed to create identity store {}", temp.display()))?; + let db = Database::builder() + .create_file(file) + .map_err(|e| store_error(&temp, e))?; + let created = Self::load(db, key)?; + std::fs::rename(&temp, path).with_context(|| { + format!( + "failed to move identity store {} into place", + temp.display() + ) })?; - Self::load(db, key) + sync_dir(parent_dir(path)) + .with_context(|| format!("failed to sync the directory of {}", path.display()))?; + Ok(created) } /// Create the table if the file is new, then authenticate every record. @@ -604,6 +629,45 @@ impl IdentityDb { } } +/// The name a new store file is built under: the store's file name with `.creating` appended. +fn creating_path(path: &Path) -> PathBuf { + let mut name = path + .file_name() + .map_or_else(OsString::new, OsStr::to_os_string); + name.push(".creating"); + path.with_file_name(name) +} + +/// The directory that holds `path`. A bare file name lives in the current directory. +fn parent_dir(path: &Path) -> &Path { + match path.parent() { + Some(dir) if !dir.as_os_str().is_empty() => dir, + _ => Path::new("."), + } +} + +/// Makes the renames in `dir` durable. Only Unix can open a directory to sync it, so elsewhere +/// this does nothing. +#[cfg(unix)] +fn sync_dir(dir: &Path) -> std::io::Result<()> { + std::fs::File::open(dir)?.sync_all() +} + +#[cfg(not(unix))] +fn sync_dir(_dir: &Path) -> std::io::Result<()> { + Ok(()) +} + +fn store_error(path: &Path, error: DatabaseError) -> anyhow::Error { + match error { + DatabaseError::DatabaseAlreadyOpen => anyhow::anyhow!( + "identity store {} is already open in another process or handle", + path.display() + ), + other => anyhow::anyhow!("failed to open identity store {}: {other}", path.display()), + } +} + /// Base64url encode without padding (RFC 4648 section 5). fn base64url_encode(data: &[u8]) -> String { let mut encoded = String::with_capacity((data.len() * 4).div_ceil(3)); @@ -1178,6 +1242,47 @@ mod tests { assert!(err.to_string().contains("failed authentication"), "{err}"); } + #[tokio::test] + async fn test_creation_leaves_only_the_store_file() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("identity.redb"); + let store = IdentityStore::new(STORE_SECRET, path.clone()) + .await + .unwrap(); + assert!(path.exists()); + assert!(!creating_path(&path).exists()); + drop(store); + } + + #[tokio::test] + async fn test_stale_creating_file_is_replaced() { + // What an interrupted creation leaves: bytes under the temporary name, no valid header. + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("identity.redb"); + std::fs::write(creating_path(&path), [0xAB; 4096]).unwrap(); + + let store = IdentityStore::new(STORE_SECRET, path.clone()) + .await + .unwrap(); + assert_eq!(store.len().await, 0); + assert!(!creating_path(&path).exists()); + } + + #[tokio::test] + async fn test_torn_store_file_is_refused() { + // Creation never leaves a file at the store's name, so a torn one is not a state the store + // makes. It is refused with an error, not replaced. + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("identity.redb"); + std::fs::write(&path, [0xAB; 4096]).unwrap(); + + let err = IdentityStore::new(STORE_SECRET, path).await.unwrap_err(); + assert!( + err.to_string().contains("failed to open identity store"), + "{err}" + ); + } + #[tokio::test] async fn test_tampered_file_refuses_to_open() { let dir = tempfile::tempdir().unwrap(); From fd311808a82e8206e6fdb1656ece91c8bbf5e587 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 11 Oct 2026 18:51:26 -0500 Subject: [PATCH 10/30] test(rust): crash gate for the identity store [P1.10] The identity store's own redb operations (creation, create, update) run on the in-process fault model, through a doc-hidden crash_gate seam in web::identity. A power cut leaves a disk image, which is written where the store would have left it and reopened through the production open. Each run checks the reopened records against the model (acked, or acked plus one), an integrity check, and a commit after recovery that survives another reopen. Client IDs are fixed, so the storage-call trace is deterministic and the corpus (identity_corpus.tsv, 382 rows) can name crash points by call number. First creation has its own tests. Every crash point of creation must reopen to an empty store, both states of the rename must open, and an in-place creation control must fail, so the gate sees the failure that the temporary name removes. The sampled sweep, control and corpus replay run in cargo test under the web feature. just crash-gate runs the full sweeps in release, and now builds with --features web. --- pkgs/id/just-recipes.json | 4 +- pkgs/id/justfile | 4 +- pkgs/id/src/web/identity.rs | 85 ++- pkgs/id/src/web/mod.rs | 2 + pkgs/id/tests/crash/corpus.rs | 7 +- pkgs/id/tests/crash/harness.rs | 32 +- pkgs/id/tests/crash/identity.rs | 758 ++++++++++++++++++++++++ pkgs/id/tests/crash/identity_corpus.tsv | 391 ++++++++++++ pkgs/id/tests/crash/main.rs | 5 + pkgs/id/tests/crash/sweep.rs | 13 +- 10 files changed, 1270 insertions(+), 31 deletions(-) create mode 100644 pkgs/id/tests/crash/identity.rs create mode 100644 pkgs/id/tests/crash/identity_corpus.tsv diff --git a/pkgs/id/just-recipes.json b/pkgs/id/just-recipes.json index a26f521c34..817e70a977 100644 --- a/pkgs/id/just-recipes.json +++ b/pkgs/id/just-recipes.json @@ -1368,11 +1368,11 @@ "crash-gate": { "attributes": [{ "group": "test" }], "body": [ - ["cargo test --release --test crash -- --skip write_corpus --include-ignored"], + ["cargo test --release --features web --test crash -- --skip write_corpus --include-ignored"], ["@echo \"✓ Crash gate passed\""] ], "dependencies": [], - "doc": "Crash-safety gate for redb: every storage call under every survival policy, and the lying-sync control, in release", + "doc": "Crash-safety gate for redb and the identity store: every storage call under every survival policy, and the lying-sync control, in release", "name": "crash-gate", "parameters": [], "priors": 0, diff --git a/pkgs/id/justfile b/pkgs/id/justfile index 57c4175b15..7f1990585b 100644 --- a/pkgs/id/justfile +++ b/pkgs/id/justfile @@ -230,10 +230,10 @@ test-full: PROPTEST_CASES="${PROPTEST_CASES:-4096}" ID_TUPLE_FUZZ_CASES="${ID_TUPLE_FUZZ_CASES:-20000}" cargo test --all-features --test tuple_properties @echo "✓ Full Rust test run passed" -# Crash-safety gate for redb: every storage call under every survival policy, and the lying-sync control, in release +# Crash-safety gate for redb and the identity store: every storage call under every survival policy, and the lying-sync control, in release [group('test')] crash-gate: - cargo test --release --test crash -- --skip write_corpus --include-ignored + cargo test --release --features web --test crash -- --skip write_corpus --include-ignored @echo "✓ Crash gate passed" # Run unit tests only (fast) diff --git a/pkgs/id/src/web/identity.rs b/pkgs/id/src/web/identity.rs index 03139d5ae9..2113eedb2b 100644 --- a/pkgs/id/src/web/identity.rs +++ b/pkgs/id/src/web/identity.rs @@ -129,19 +129,9 @@ impl IdentityStore { /// * `secret_key` - 32-byte secret key (from iroh `SecretKey::to_bytes()`) /// * `db_path` - Path for the redb file (e.g., `.identity.redb`) pub async fn new(secret_key: [u8; 32], db_path: PathBuf) -> anyhow::Result { - // Derive signing key via HKDF-SHA256 - let hk = Hkdf::::new(None, &secret_key); - let mut signing_bytes = [0u8; 32]; - hk.expand(b"id-identity-signing", &mut signing_bytes) - .map_err(|_e| anyhow::anyhow!("HKDF expand failed for signing key"))?; - let signing_key = SigningKey::from_bytes(&signing_bytes); + let (signing_key, enc_bytes) = derive_keys(&secret_key)?; let verifying_key = signing_key.verifying_key(); - // Derive the record encryption key via HKDF-SHA256 - let mut enc_bytes = [0u8; 32]; - hk.expand(b"id-identity-encryption", &mut enc_bytes) - .map_err(|_e| anyhow::anyhow!("HKDF expand failed for encryption key"))?; - // Open the file and load every record. redb is synchronous, so this runs // on the blocking pool. let (db, identities) = run_blocking(move || IdentityDb::open(&db_path, &enc_bytes)).await?; @@ -629,6 +619,19 @@ impl IdentityDb { } } +/// The signing key for tokens, and the AES-256-GCM key for records, both derived from the secret +/// key with HKDF-SHA256. +fn derive_keys(secret_key: &[u8; 32]) -> anyhow::Result<(SigningKey, [u8; 32])> { + let hk = Hkdf::::new(None, secret_key); + let mut signing_bytes = [0u8; 32]; + hk.expand(b"id-identity-signing", &mut signing_bytes) + .map_err(|_e| anyhow::anyhow!("HKDF expand failed for signing key"))?; + let mut enc_bytes = [0u8; 32]; + hk.expand(b"id-identity-encryption", &mut enc_bytes) + .map_err(|_e| anyhow::anyhow!("HKDF expand failed for encryption key"))?; + Ok((SigningKey::from_bytes(&signing_bytes), enc_bytes)) +} + /// The name a new store file is built under: the store's file name with `.creating` appended. fn creating_path(path: &Path) -> PathBuf { let mut name = path @@ -668,6 +671,66 @@ fn store_error(path: &Path, error: DatabaseError) -> anyhow::Error { } } +/// The crash gate's view of the store (`tests/crash/identity.rs`). Not part of the public API. +/// +/// The gate runs the store's own redb operations over a database it opened on its fault model, so +/// a power cut can land inside them. It reopens each disk image through [`open_path`], the file +/// path that [`IdentityStore::new`](super::IdentityStore::new) takes. +#[doc(hidden)] +pub mod crash_gate { + pub use super::ClientIdentity; + use super::{IdentityDb, derive_keys}; + use redb::Database; + use std::path::{Path, PathBuf}; + + /// A store opened by the gate. + pub struct Store(IdentityDb); + + impl std::fmt::Debug for Store { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Store").finish_non_exhaustive() + } + } + + impl Store { + /// Inserts an identity. A client ID that is already stored is an error. + pub fn create(&self, identity: &ClientIdentity) -> anyhow::Result<()> { + self.0.create(identity) + } + + /// Overwrites the identity stored under its client ID. + pub fn update(&self, identity: &ClientIdentity) -> anyhow::Result<()> { + self.0.update(identity) + } + + /// Every stored identity, decrypted and authenticated. + pub fn records(&self) -> anyhow::Result> { + self.0.read_all() + } + } + + /// Loads a store from `db`, which the caller opened. A new file gets its table in the first + /// commit, which this makes. + pub fn open_database(db: Database, secret_key: &[u8; 32]) -> anyhow::Result { + let (_, enc_key) = derive_keys(secret_key)?; + let (store, _) = IdentityDb::load(db, &enc_key)?; + Ok(Store(store)) + } + + /// Opens the store file at `path`, or creates it, as + /// [`IdentityStore::new`](super::IdentityStore::new) does. + pub fn open_path(path: &Path, secret_key: &[u8; 32]) -> anyhow::Result { + let (_, enc_key) = derive_keys(secret_key)?; + let (store, _) = IdentityDb::open(path, &enc_key)?; + Ok(Store(store)) + } + + /// The name that a new store file is built under. + pub fn creating_path(path: &Path) -> PathBuf { + super::creating_path(path) + } +} + /// Base64url encode without padding (RFC 4648 section 5). fn base64url_encode(data: &[u8]) -> String { let mut encoded = String::with_capacity((data.len() * 4).div_ceil(3)); diff --git a/pkgs/id/src/web/mod.rs b/pkgs/id/src/web/mod.rs index 392cf108d3..6ad8114e78 100644 --- a/pkgs/id/src/web/mod.rs +++ b/pkgs/id/src/web/mod.rs @@ -75,6 +75,8 @@ use crate::tags::TagStore; pub use assets::static_handler; pub use collab::CollabState; pub use identity::IdentityStore; +#[doc(hidden)] +pub use identity::crash_gate; pub use routes::create_router; pub use security::WebSecurity; pub use templates::{AssetUrls, render_page}; diff --git a/pkgs/id/tests/crash/corpus.rs b/pkgs/id/tests/crash/corpus.rs index a980d8129f..c19ba5da7c 100644 --- a/pkgs/id/tests/crash/corpus.rs +++ b/pkgs/id/tests/crash/corpus.rs @@ -193,7 +193,12 @@ fn parse_expect(s: &str) -> Result { /// The corpus text for a header and rows, in the order given. pub fn format(header: &Header, rows: &[Row]) -> String { - let mut out = String::from(PREAMBLE); + format_with(PREAMBLE, header, rows) +} + +/// The corpus text for a header and rows, under the given preamble comment lines. +pub fn format_with(preamble: &str, header: &Header, rows: &[Row]) -> String { + let mut out = String::from(preamble); writeln!(out, "{STORAGE_CALLS}{}", header.storage_calls).expect("write to a String"); writeln!(out, "{TRACE_HASH}{:016x}", header.trace_fnv1a).expect("write to a String"); writeln!(out, "{COLUMNS}").expect("write to a String"); diff --git a/pkgs/id/tests/crash/harness.rs b/pkgs/id/tests/crash/harness.rs index 6c450b790c..a88a0b45ea 100644 --- a/pkgs/id/tests/crash/harness.rs +++ b/pkgs/id/tests/crash/harness.rs @@ -168,18 +168,7 @@ fn verify(image: Vec, acked: u64, models: &[Model]) -> Outcome { Ok(state) => state, Err(e) => return outcome(Verdict::OpenError, format!("dump: {e}")), }; - let n = acked as usize; - let verdict = if state == models[n] { - Verdict::OkAcked - } else if n + 1 < models.len() && state == models[n + 1] { - Verdict::OkAckedPlusOne - } else if models[..n].contains(&state) { - Verdict::LostCommitted - } else if models.iter().skip(n + 2).any(|m| *m == state) { - Verdict::Future - } else { - Verdict::Partial - }; + let verdict = classify(&state, models, acked); if verdict.is_failure() { return outcome(verdict, String::new()); } @@ -194,7 +183,24 @@ fn verify(image: Vec, acked: u64, models: &[Model]) -> Outcome { outcome(verdict, String::new()) } -fn panic_text(payload: &(dyn Any + Send)) -> String { +/// Which valid prefix a reopened state is. `models[n]` is the state after `n` acknowledged steps, +/// and `models[n + 1]` is the state when the step in flight at the cut became durable too. +pub fn classify(state: &M, models: &[M], acked: u64) -> Verdict { + let n = acked as usize; + if *state == models[n] { + Verdict::OkAcked + } else if n + 1 < models.len() && *state == models[n + 1] { + Verdict::OkAckedPlusOne + } else if models[..n].contains(state) { + Verdict::LostCommitted + } else if models.iter().skip(n + 2).any(|m| m == state) { + Verdict::Future + } else { + Verdict::Partial + } +} + +pub fn panic_text(payload: &(dyn Any + Send)) -> String { payload .downcast_ref::<&str>() .map(|s| (*s).to_owned()) diff --git a/pkgs/id/tests/crash/identity.rs b/pkgs/id/tests/crash/identity.rs new file mode 100644 index 0000000000..ee22679ee4 --- /dev/null +++ b/pkgs/id/tests/crash/identity.rs @@ -0,0 +1,758 @@ +//! The crash gate for the identity store (plan step P1.10). Built with the `web` feature. +//! +//! The store's own redb operations run on the fault model: creating the store, which makes its +//! first commit, then `create` and `update` of identities, through `id::web::crash_gate`. Client +//! IDs are fixed, so the storage-call trace is the same on every run and the corpus can name a +//! crash point by its call number. +//! +//! Creation also changes the directory, which the fault model does not see. The store builds its +//! file under a temporary name, makes the first commit, renames the file into place, and syncs the +//! directory, all before it returns. So a power cut inside creation leaves the disk image at the +//! temporary name and nothing at the store's name. A cut after creation leaves the image at the +//! store's name. Each image is written to a real file and reopened through `crash_gate::open_path`, +//! the path `IdentityStore::new` takes, and the records are checked against the model. +//! +//! The in-place control writes the creation images at the store's name, as if creation wrote +//! there directly. That is the failure the temporary name removes, so the control must fail. + +use crate::corpus::{self, Expect, Header}; +use crate::faultfs::{FaultFs, Plan, Trace, splitmix}; +use crate::harness::{Outcome, Verdict, classify, panic_text}; +use crate::sweep::{Job, describe, jobs_for, report, run_jobs_with, sample_events}; +use id::web::crash_gate::{self, ClientIdentity, Store}; +use redb::Database; +use std::collections::BTreeMap; +use std::panic::{self, AssertUnwindSafe}; +use std::path::Path; + +/// The store's secret key in every run. +const SECRET: [u8; 32] = [7u8; 32]; + +/// Identities the workload creates. Every other one is renamed once, after it is created. +const CREATES: u64 = 40; + +/// The default run crashes at every `SAMPLE_STRIDE`th storage call, and at every creation call. +const SAMPLE_STRIDE: u64 = 20; + +/// How many failing runs an assertion message lists. +const LISTED: usize = 20; + +const CORPUS_PATH: &str = concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/crash/identity_corpus.tsv" +); +const CORPUS: &str = include_str!("identity_corpus.tsv"); + +const PREAMBLE: &str = "\ +# Crash corpus for the identity store (tests/crash/identity.rs). Replayed by identity::corpus_replays_with_recorded_verdicts. +# Each line is one crash point of the identity workload: the plan that cuts power there, and the verdict its run must keep. +# expect `ok` accepts either valid prefix (ok_acked or ok_acked_plus_one). Any other value must match. +# trace_fnv1a is FNV-1a over (kind, offset, length) of every storage call of the clean run. +# Regenerate, from pkgs/id: cargo test --release --features web --test crash write_corpus_identity -- --ignored +# Each sweep failure is added by hand as a fix- row, with the verdict the fixed code gives. +"; + +/// One identity as the gate compares it: its name, its creation time, and its last update time. +type Entry = (Option, u64, u64); + +/// Every identity in a store, by client ID. +type Snapshot = BTreeMap; + +/// One step after creation: a new identity, or a new name for an existing one. +#[derive(Clone, Debug)] +enum Op { + Create(ClientIdentity), + Rename(ClientIdentity), +} + +/// The client ID of identity `i`. The IDs are fixed but not in creation order, so the B-tree sees +/// keys out of order. +fn client_id(i: u64) -> String { + format!("{:016x}{:016x}", splitmix(i), splitmix(i ^ 0xFFFF_0000)) +} + +const fn created_at(i: u64) -> u64 { + 1_700_000_000 + i +} + +/// A name for identity `i` in round `round`. Some names are absent, and their lengths vary, so +/// the values differ in size. +fn name(i: u64, round: u64) -> Option { + if (i + round) % 5 == 4 { + None + } else { + let padding = "x".repeat(((i * 7 + round * 3) % 40) as usize); + Some(format!("user-{i:02}-r{round}-{padding}")) + } +} + +/// The workload's steps after creation: each identity is created, and every other one is renamed. +fn ops() -> Vec { + let mut ops = Vec::new(); + for i in 0..CREATES { + ops.push(Op::Create(ClientIdentity { + client_id: client_id(i), + name: name(i, 0), + created_at: created_at(i), + updated_at: created_at(i), + })); + if i % 2 == 1 { + let j = i / 2; + ops.push(Op::Rename(ClientIdentity { + client_id: client_id(j), + name: name(j, 1), + created_at: created_at(j), + updated_at: 1_700_100_000 + i, + })); + } + } + ops +} + +fn apply(model: &mut Snapshot, op: &Op) { + match op { + Op::Create(identity) | Op::Rename(identity) => { + model.insert( + identity.client_id.clone(), + ( + identity.name.clone(), + identity.created_at, + identity.updated_at, + ), + ); + } + } +} + +fn commit(store: &Store, op: &Op) -> anyhow::Result<()> { + match op { + Op::Create(identity) => store.create(identity), + Op::Rename(identity) => store.update(identity), + } +} + +/// `models()[n]` is the store after `n` steps. Step 0 is before creation, and step 1 is the store +/// as creation leaves it, which is empty. Step `k + 2` is the state after the `k`th op. +fn models() -> Vec { + let mut out = vec![Snapshot::new(), Snapshot::new()]; + let mut model = Snapshot::new(); + for op in ops() { + apply(&mut model, &op); + out.push(model.clone()); + } + out +} + +fn snapshot(records: Vec) -> Snapshot { + records + .into_iter() + .map(|r| (r.client_id, (r.name, r.created_at, r.updated_at))) + .collect() +} + +/// Creates the store on `fs`, then runs every op. `acked` counts the steps that returned, creation +/// included. `made` is the number of storage calls creation made. +fn run_workload(fs: &FaultFs, acked: &mut u64, made: &mut u64) -> Result<(), String> { + let db = Database::builder() + .create_with_backend(fs.clone()) + .map_err(|e| format!("create: {e}"))?; + let store = crash_gate::open_database(db, &SECRET).map_err(|e| format!("open: {e:#}"))?; + if fs.cut() { + // The process died inside creation. Nothing is acknowledged. + return Ok(()); + } + *made = fs.trace().len() as u64; + *acked = 1; + for (k, op) in ops().iter().enumerate() { + let result = commit(&store, op); + if fs.cut() { + // The process died inside this call. The op is not acknowledged. + return Ok(()); + } + result.map_err(|e| format!("op {k}: {e:#}"))?; + *acked = k as u64 + 2; + } + drop(store); + Ok(()) +} + +/// The disk image after creation returns, with nothing else done. +fn creation_image() -> Vec { + let fs = FaultFs::new(Vec::new(), None, false); + let db = Database::builder() + .create_with_backend(fs.clone()) + .expect("create the database"); + let store = crash_gate::open_database(db, &SECRET).expect("create the store"); + let image = fs.disk_image(); + drop(store); + image +} + +/// Where a run's disk image is written for the reopen. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Placement { + /// As the store leaves it: a cut inside creation leaves the image at the temporary name. + AsStored, + /// The control: the image of a cut inside creation goes at the store's name. + InPlace, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Target { + /// The temporary name a new store is built under. + Temporary, + /// The store's own name. + Store, +} + +/// One run: its outcome, the storage-call trace, and how many calls creation made. +struct Run { + outcome: Outcome, + trace: Trace, + made: u64, +} + +/// Runs the workload with one plan, reopens the disk image, and classifies the result. `created` +/// is the creation length of the clean run: a cut at or before it lands inside creation. +fn run_identity( + plan: Option, + lying: bool, + models: &[Snapshot], + created: u64, + placement: Placement, +) -> Run { + let fs = FaultFs::new(Vec::new(), plan, lying); + let mut acked = 0u64; + let mut made = 0u64; + let attempt = panic::catch_unwind(AssertUnwindSafe(|| { + run_workload(&fs, &mut acked, &mut made) + })); + let trace = fs.trace(); + let in_creation = plan.is_some_and(|p| p.event <= created); + let outcome = match attempt { + Err(payload) if !fs.cut() => Outcome { + verdict: Verdict::Panic, + acked, + repairs: 0, + detail: format!( + "panic before the power cut: {}", + panic_text(payload.as_ref()) + ), + }, + Ok(Err(e)) if !fs.cut() => Outcome { + verdict: Verdict::NoCrashError, + acked, + repairs: 0, + detail: e, + }, + // A cut (or a clean finish) leaves a disk image to reopen. A failure after the cut is the + // dead process failing, not a finding. + _ => { + let target = match (in_creation, placement) { + (true, Placement::AsStored) => Target::Temporary, + _ => Target::Store, + }; + let image = fs.disk_image(); + match panic::catch_unwind(AssertUnwindSafe(|| verify(&image, target, acked, models))) { + Ok(outcome) => outcome, + Err(payload) => Outcome { + verdict: Verdict::Panic, + acked, + repairs: 0, + detail: format!( + "panic while reopening the image: {}", + panic_text(payload.as_ref()) + ), + }, + } + } + }; + Run { + outcome, + trace, + made, + } +} + +/// Writes the image where the store would have left it, then reopens it. +fn verify(image: &[u8], target: Target, acked: u64, models: &[Snapshot]) -> Outcome { + let dir = tempfile::tempdir().expect("a temporary directory"); + let path = dir.path().join("identity.redb"); + let file = match target { + Target::Temporary => crash_gate::creating_path(&path), + Target::Store => path.clone(), + }; + std::fs::write(&file, image).expect("write the disk image"); + check_reopened(&path, acked, models) +} + +/// Reopens the store at `path` through the production open, and checks it. It must open and hold a +/// valid prefix of the workload. Then the file the store left is checked in memory: it must pass an +/// integrity check, and take new commits that survive another reopen. +fn check_reopened(path: &Path, acked: u64, models: &[Snapshot]) -> Outcome { + let outcome = |verdict, detail: String| Outcome { + verdict, + acked, + repairs: 0, + detail, + }; + let store = match crash_gate::open_path(path, &SECRET) { + Ok(store) => store, + Err(e) => return outcome(Verdict::OpenError, format!("open: {e:#}")), + }; + let state = match store.records() { + Ok(records) => snapshot(records), + Err(e) => return outcome(Verdict::OpenError, format!("records: {e:#}")), + }; + drop(store); + let verdict = classify(&state, models, acked); + if verdict.is_failure() { + return outcome(verdict, format!("{} identities reopened", state.len())); + } + // The fsyncs of a commit dominate a run, so the checks after the open run on a copy in memory. + let image = match std::fs::read(path) { + Ok(image) => image, + Err(e) => return outcome(Verdict::OpenError, format!("read back: {e}")), + }; + if let Err(e) = integrity(image.clone()) { + return outcome(Verdict::Integrity, e); + } + if let Err(e) = post_recovery(image, &state) { + return outcome(Verdict::PostRecovery, e); + } + outcome(verdict, String::new()) +} + +/// Checks the integrity of a database image in memory. +fn integrity(image: Vec) -> Result<(), String> { + let mut db = Database::builder() + .create_with_backend(FaultFs::new(image, None, false)) + .map_err(|e| format!("integrity open: {e}"))?; + match db.check_integrity() { + Ok(true) => Ok(()), + Ok(false) => Err("check_integrity returned false".into()), + Err(e) => Err(format!("check_integrity: {e}")), + } +} + +/// Creates one identity and renames another on the reopened store, then reopens it again. The +/// recovered records and both new commits must survive. Runs on a copy of the image in memory. +fn post_recovery(image: Vec, recovered: &Snapshot) -> Result<(), String> { + let mut want = recovered.clone(); + let fresh = ClientIdentity { + client_id: "post-recovery".into(), + name: Some("after the cut".into()), + created_at: 1, + updated_at: 1, + }; + want.insert( + fresh.client_id.clone(), + (fresh.name.clone(), fresh.created_at, fresh.updated_at), + ); + let backing = FaultFs::new(image, None, false); + let db = Database::builder() + .create_with_backend(backing.clone()) + .map_err(|e| format!("reopen: {e}"))?; + let store = crash_gate::open_database(db, &SECRET).map_err(|e| format!("reopen: {e:#}"))?; + store + .create(&fresh) + .map_err(|e| format!("create after recovery: {e:#}"))?; + if let Some((id, (_, created, _))) = recovered.iter().next() { + let renamed = ClientIdentity { + client_id: id.clone(), + name: Some("renamed after the cut".into()), + created_at: *created, + updated_at: 2, + }; + store + .update(&renamed) + .map_err(|e| format!("update after recovery: {e:#}"))?; + want.insert(id.clone(), (renamed.name, *created, 2)); + } + drop(store); + let db = Database::builder() + .create_with_backend(FaultFs::new(backing.disk_image(), None, false)) + .map_err(|e| format!("second reopen: {e}"))?; + let again = + crash_gate::open_database(db, &SECRET).map_err(|e| format!("second reopen: {e:#}"))?; + let got = snapshot(again.records().map_err(|e| format!("records: {e:#}"))?); + if got == want { + Ok(()) + } else { + Err("state after the post-recovery commits and a clean reopen differs".into()) + } +} + +/// The clean run's trace, and how many of its calls creation made. +fn shape() -> (Trace, u64) { + let models = models(); + let run = run_identity(None, false, &models, 0, Placement::AsStored); + assert_eq!( + run.outcome.verdict, + Verdict::OkAcked, + "{}", + run.outcome.detail + ); + assert_eq!(run.outcome.acked, models.len() as u64 - 1); + assert!(run.made > 0 && run.made < run.trace.len() as u64); + (run.trace, run.made) +} + +/// Every creation call. These are the first-creation crash points. +fn creation_events(created: u64) -> Vec { + (1..=created).collect() +} + +/// Every creation call, every `SAMPLE_STRIDE`th call, and the last one. +fn sampled_events(trace: &Trace, created: u64) -> Vec { + let mut events = sample_events(trace.len() as u64, SAMPLE_STRIDE); + events.extend(creation_events(created)); + events.sort_unstable(); + events.dedup(); + events +} + +/// Runs every plan of the given crash points. Returns the jobs, their outcomes, and the indices of +/// the failing runs. +fn sweep( + label: &str, + trace: &Trace, + created: u64, + events: &[u64], + lying: bool, + placement: Placement, +) -> (Vec, Vec, Vec) { + let models = models(); + let jobs = jobs_for(trace, events, lying); + let outcomes = run_jobs_with(&jobs, |job| { + run_identity(Some(job.plan), job.lying, &models, created, placement).outcome + }); + let failing = report(label, &jobs, &outcomes); + (jobs, outcomes, failing) +} + +fn listing(jobs: &[Job], outcomes: &[Outcome], failing: &[usize]) -> String { + failing + .iter() + .take(LISTED) + .map(|&i| describe(&jobs[i], &outcomes[i])) + .collect::>() + .join("\n") +} + +fn assert_control_fails(outcomes: &[Outcome], failing: &[usize]) { + assert!( + !failing.is_empty(), + "the lying-sync control produced no failures: the gate cannot see lost durability" + ); + assert!( + failing.iter().any(|&i| matches!( + outcomes[i].verdict, + Verdict::LostCommitted | Verdict::OpenError + )), + "the control failed, but never with lost_committed or open_error" + ); +} + +#[test] +fn clean_run_reopens_with_every_step() { + let models = models(); + let run = run_identity(None, false, &models, 0, Placement::AsStored); + assert_eq!( + run.outcome.verdict, + Verdict::OkAcked, + "{}", + run.outcome.detail + ); + assert_eq!(run.outcome.acked, models.len() as u64 - 1); + assert!(run.made > 0 && run.made < run.trace.len() as u64); +} + +/// Every crash point of creation, under every plan, must reopen to an empty store. This is the +/// first-creation guarantee: no crash leaves a file the store refuses to open. +#[test] +fn first_creation_has_no_failures() { + let (trace, created) = shape(); + let events = creation_events(created); + let (jobs, outcomes, failing) = sweep( + "first creation", + &trace, + created, + &events, + false, + Placement::AsStored, + ); + assert!( + failing.is_empty(), + "{} failing runs:\n{}", + failing.len(), + listing(&jobs, &outcomes, &failing) + ); +} + +/// After creation returns, the rename may or may not have reached the disk. Both states must open +/// to an empty store, and the temporary name must be gone afterwards. +#[test] +fn first_creation_rename_states_open() { + let image = creation_image(); + let models = models(); + + let dir = tempfile::tempdir().expect("a temporary directory"); + let path = dir.path().join("identity.redb"); + std::fs::write(&path, &image).expect("write the image at the store's name"); + let outcome = check_reopened(&path, 1, &models); + assert_eq!( + outcome.verdict, + Verdict::OkAcked, + "rename survived: {}", + outcome.detail + ); + drop(dir); + + let dir = tempfile::tempdir().expect("a temporary directory"); + let path = dir.path().join("identity.redb"); + std::fs::write(crash_gate::creating_path(&path), &image) + .expect("write the image at the temporary name"); + let outcome = check_reopened(&path, 1, &models); + assert_eq!( + outcome.verdict, + Verdict::OkAcked, + "rename did not survive: {}", + outcome.detail + ); + assert!(!crash_gate::creating_path(&path).exists()); +} + +/// The control. With creation writing in place, some crash points leave a file at the store's name +/// that redb refuses to open. The gate must see those, or the first-creation guarantee is untested. +#[test] +fn in_place_creation_control_fails() { + let (trace, created) = shape(); + let events = creation_events(created); + let (_, outcomes, failing) = sweep( + "control (in-place creation)", + &trace, + created, + &events, + false, + Placement::InPlace, + ); + assert!( + !failing.is_empty(), + "the in-place control produced no failures: the gate cannot see a torn first creation" + ); + assert!( + failing + .iter() + .all(|&i| outcomes[i].verdict == Verdict::OpenError), + "the in-place control failed with something other than open_error" + ); +} + +#[test] +fn sampled_sweep_has_no_failures() { + let (trace, created) = shape(); + let events = sampled_events(&trace, created); + let (jobs, outcomes, failing) = sweep( + "sampled sweep", + &trace, + created, + &events, + false, + Placement::AsStored, + ); + assert!( + failing.is_empty(), + "{} failing runs:\n{}", + failing.len(), + listing(&jobs, &outcomes, &failing) + ); +} + +#[test] +fn lying_sync_control_produces_failures() { + let (trace, created) = shape(); + let events = sampled_events(&trace, created); + let (_, outcomes, failing) = sweep( + "control (lying sync)", + &trace, + created, + &events, + true, + Placement::AsStored, + ); + assert_control_fails(&outcomes, &failing); +} + +#[test] +fn corpus_replays_with_recorded_verdicts() { + let (trace, created) = shape(); + let models = models(); + let (header, rows) = corpus::parse(CORPUS).expect("identity_corpus.tsv parses"); + assert_eq!( + header, + Header { + storage_calls: trace.len() as u64, + trace_fnv1a: corpus::trace_fnv1a(&trace), + }, + "the identity workload's storage-call trace changed. Check the change, then regenerate identity_corpus.tsv (see its header)" + ); + let mut problems = Vec::new(); + for row in &rows { + let actual = (row.job.plan.event as usize) + .checked_sub(1) + .and_then(|i| trace.get(i)) + .map(|call| call.0); + if actual != Some(row.kind) { + let actual = actual.map_or("no such call", |kind| kind.name()); + problems.push(format!( + "{}: event {} is {actual}, not {}", + row.name, + row.job.plan.event, + row.kind.name() + )); + } + } + let jobs: Vec = rows.iter().map(|row| row.job).collect(); + let outcomes = run_jobs_with(&jobs, |job| { + run_identity( + Some(job.plan), + job.lying, + &models, + created, + Placement::AsStored, + ) + .outcome + }); + for (row, outcome) in rows.iter().zip(&outcomes) { + if !row.expect.accepts(outcome.verdict) { + problems.push(format!( + "{}: got {} ({}), expected {}", + row.name, + outcome.verdict.name(), + outcome.detail, + row.expect.name() + )); + } + } + assert!( + problems.is_empty(), + "{} corpus rows changed:\n{}", + problems.len(), + problems.join("\n") + ); +} + +#[test] +#[ignore = "the full identity gate: every storage call under every plan. `just crash-gate` runs it in release"] +fn full_sweep_has_no_failures() { + let (trace, created) = shape(); + let events: Vec = (1..=trace.len() as u64).collect(); + let (jobs, outcomes, failing) = sweep( + "full identity sweep", + &trace, + created, + &events, + false, + Placement::AsStored, + ); + assert!( + failing.is_empty(), + "{} failing runs:\n{}", + failing.len(), + listing(&jobs, &outcomes, &failing) + ); +} + +#[test] +#[ignore = "the full identity control: every storage call under a lying sync. `just crash-gate` runs it in release"] +fn full_lying_sync_control_produces_failures() { + let (trace, created) = shape(); + let events: Vec = (1..=trace.len() as u64).collect(); + let (_, outcomes, failing) = sweep( + "full identity control (lying sync)", + &trace, + created, + &events, + true, + Placement::AsStored, + ); + assert_control_fails(&outcomes, &failing); +} + +/// Rewrites `identity_corpus.tsv`: every creation call and every faithful point that ends in the +/// plus-one state, plus two failing rows per class from the lying sync. The `fix-` rows already in +/// the file are kept. A faithful failure stops it, because such a failure needs a fix first. +#[test] +#[ignore = "rewrites identity_corpus.tsv. Run by hand, in release, after a deliberate workload change"] +fn write_corpus_identity() { + let (trace, created) = shape(); + let all: Vec = (1..=trace.len() as u64).collect(); + + let (jobs, outcomes, failing) = sweep( + "faithful sweep", + &trace, + created, + &all, + false, + Placement::AsStored, + ); + assert!( + failing.is_empty(), + "a faithful run failed. Fix it, then add its row by hand as fix-:\n{}", + listing(&jobs, &outcomes, &failing) + ); + let mut rows = Vec::new(); + for (job, outcome) in jobs.iter().zip(&outcomes) { + let (prefix, expect) = match outcome.verdict { + Verdict::OkAcked if job.plan.event <= created => { + ("creation", Expect::Exact(outcome.verdict)) + } + Verdict::OkAckedPlusOne => ("plus-one", Expect::Valid), + _ => continue, + }; + rows.push(crate::corpus_row( + crate::plan_name(prefix, job), + *job, + &trace, + expect, + )); + } + + let (cjobs, coutcomes, _) = sweep( + "control sweep", + &trace, + created, + &all, + true, + Placement::AsStored, + ); + let mut taken: BTreeMap<&str, usize> = BTreeMap::new(); + for (job, outcome) in cjobs.iter().zip(&coutcomes) { + let v = outcome.verdict; + let expect = match v { + Verdict::OkAckedPlusOne => Expect::Valid, + _ if v.is_failure() => Expect::Exact(v), + _ => continue, + }; + let count = taken.entry(v.name()).or_default(); + if *count < 2 { + *count += 1; + let name = format!("control-{}-{count}", v.name()); + rows.push(crate::corpus_row(name, *job, &trace, expect)); + } + } + + let existing = std::fs::read_to_string(CORPUS_PATH).unwrap_or_default(); + if let Ok((_, kept)) = corpus::parse(&existing) { + rows.extend(kept.into_iter().filter(|row| row.name.starts_with("fix-"))); + } + + let header = Header { + storage_calls: trace.len() as u64, + trace_fnv1a: corpus::trace_fnv1a(&trace), + }; + std::fs::write(CORPUS_PATH, corpus::format_with(PREAMBLE, &header, &rows)) + .expect("write identity_corpus.tsv"); + println!("wrote {} rows to {CORPUS_PATH}", rows.len()); +} diff --git a/pkgs/id/tests/crash/identity_corpus.tsv b/pkgs/id/tests/crash/identity_corpus.tsv new file mode 100644 index 0000000000..93b77c4545 --- /dev/null +++ b/pkgs/id/tests/crash/identity_corpus.tsv @@ -0,0 +1,391 @@ +# Crash corpus for the identity store (tests/crash/identity.rs). Replayed by identity::corpus_replays_with_recorded_verdicts. +# Each line is one crash point of the identity workload: the plan that cuts power there, and the verdict its run must keep. +# expect `ok` accepts either valid prefix (ok_acked or ok_acked_plus_one). Any other value must match. +# trace_fnv1a is FNV-1a over (kind, offset, length) of every storage call of the clean run. +# Regenerate, from pkgs/id: cargo test --release --features web --test crash write_corpus_identity -- --ignored +# Each sweep failure is added by hand as a fix- row, with the verdict the fixed code gives. +# storage_calls: 483 +# trace_fnv1a: 71b506f1a1b3ab88 +# name lying_sync event kind survive tear sync_completed seed expect +creation-001-Drop-Off-0 0 1 set_len Drop Off 0 3965022595533706929 ok_acked +creation-001-Keep-Off-0 0 1 set_len Keep Off 0 3178540356880283481 ok_acked +creation-001-Random-Off-0 0 1 set_len Random Off 0 16550353102095353028 ok_acked +creation-001-Reorder-Off-0 0 1 set_len Reorder Off 0 368342364169337290 ok_acked +creation-002-Drop-Off-0 0 2 write Drop Off 0 10826722299036291093 ok_acked +creation-002-Keep-Off-0 0 2 write Keep Off 0 8361847590266283331 ok_acked +creation-002-Random-Off-0 0 2 write Random Off 0 10252629665644599760 ok_acked +creation-002-Reorder-Off-0 0 2 write Reorder Off 0 12847895688012758659 ok_acked +creation-002-Drop-Byte-0 0 2 write Drop Byte 0 283545940951472360 ok_acked +creation-002-Keep-Byte-0 0 2 write Keep Byte 0 16743392734764332446 ok_acked +creation-002-Random-Byte-0 0 2 write Random Byte 0 10203985545584359410 ok_acked +creation-002-Reorder-Byte-0 0 2 write Reorder Byte 0 4413419251928811825 ok_acked +creation-002-Drop-Sector-0 0 2 write Drop Sector 0 7641485672361121627 ok_acked +creation-002-Keep-Sector-0 0 2 write Keep Sector 0 12488321346544387774 ok_acked +creation-002-Random-Sector-0 0 2 write Random Sector 0 3628886295211392483 ok_acked +creation-002-Reorder-Sector-0 0 2 write Reorder Sector 0 16611378828665872033 ok_acked +creation-003-Drop-Off-0 0 3 sync Drop Off 0 2914380442709976269 ok_acked +creation-003-Keep-Off-0 0 3 sync Keep Off 0 13181733461238856628 ok_acked +creation-003-Random-Off-0 0 3 sync Random Off 0 6616389739668441417 ok_acked +creation-003-Reorder-Off-0 0 3 sync Reorder Off 0 78350552875603143 ok_acked +creation-003-Drop-Off-1 0 3 sync Drop Off 1 14125433436979177977 ok_acked +creation-004-Drop-Off-0 0 4 write Drop Off 0 8298218915660572452 ok_acked +creation-004-Keep-Off-0 0 4 write Keep Off 0 2164534462834122148 ok_acked +creation-004-Random-Off-0 0 4 write Random Off 0 18437047743522589496 ok_acked +creation-004-Reorder-Off-0 0 4 write Reorder Off 0 13744174975128628763 ok_acked +creation-004-Drop-Byte-0 0 4 write Drop Byte 0 1784937755037984706 ok_acked +creation-004-Keep-Byte-0 0 4 write Keep Byte 0 16732235586306984517 ok_acked +creation-004-Random-Byte-0 0 4 write Random Byte 0 843186567711051837 ok_acked +creation-004-Reorder-Byte-0 0 4 write Reorder Byte 0 10108932951917845085 ok_acked +creation-004-Drop-Sector-0 0 4 write Drop Sector 0 10933956566130174471 ok_acked +creation-004-Keep-Sector-0 0 4 write Keep Sector 0 15186231919485255384 ok_acked +creation-004-Random-Sector-0 0 4 write Random Sector 0 8999802954715218159 ok_acked +creation-004-Reorder-Sector-0 0 4 write Reorder Sector 0 3594022018564067379 ok_acked +creation-005-Drop-Off-0 0 5 sync Drop Off 0 16816190659201883630 ok_acked +creation-005-Keep-Off-0 0 5 sync Keep Off 0 4620974141188107049 ok_acked +creation-005-Random-Off-0 0 5 sync Random Off 0 2743416142102549658 ok_acked +creation-005-Reorder-Off-0 0 5 sync Reorder Off 0 17493543810667717580 ok_acked +creation-005-Drop-Off-1 0 5 sync Drop Off 1 13580583601365213395 ok_acked +creation-006-Drop-Off-0 0 6 write Drop Off 0 5110964744917759842 ok_acked +creation-006-Keep-Off-0 0 6 write Keep Off 0 12253853213991730002 ok_acked +creation-006-Random-Off-0 0 6 write Random Off 0 16125954581958853469 ok_acked +creation-006-Reorder-Off-0 0 6 write Reorder Off 0 1689394888916756814 ok_acked +creation-006-Drop-Byte-0 0 6 write Drop Byte 0 9803323763844741457 ok_acked +creation-006-Keep-Byte-0 0 6 write Keep Byte 0 16449283172058085693 ok_acked +creation-006-Random-Byte-0 0 6 write Random Byte 0 11037335095431026510 ok_acked +creation-006-Reorder-Byte-0 0 6 write Reorder Byte 0 2649651583485284701 ok_acked +creation-006-Drop-Sector-0 0 6 write Drop Sector 0 12491554923924008894 ok_acked +creation-006-Keep-Sector-0 0 6 write Keep Sector 0 11409009276225735685 ok_acked +creation-006-Random-Sector-0 0 6 write Random Sector 0 8050619123805320129 ok_acked +creation-006-Reorder-Sector-0 0 6 write Reorder Sector 0 1753054283992944320 ok_acked +creation-007-Drop-Off-0 0 7 sync Drop Off 0 8624175127002713895 ok_acked +creation-007-Keep-Off-0 0 7 sync Keep Off 0 13352772384927784914 ok_acked +creation-007-Random-Off-0 0 7 sync Random Off 0 18150605336601827065 ok_acked +creation-007-Reorder-Off-0 0 7 sync Reorder Off 0 11368643031446133501 ok_acked +creation-007-Drop-Off-1 0 7 sync Drop Off 1 3697596113263900099 ok_acked +creation-008-Drop-Off-0 0 8 write Drop Off 0 8714100217554564121 ok_acked +creation-008-Keep-Off-0 0 8 write Keep Off 0 12015995521068461274 ok_acked +creation-008-Random-Off-0 0 8 write Random Off 0 2267964829242811130 ok_acked +creation-008-Reorder-Off-0 0 8 write Reorder Off 0 1927447267302272780 ok_acked +creation-008-Drop-Byte-0 0 8 write Drop Byte 0 14338351927971342523 ok_acked +creation-008-Keep-Byte-0 0 8 write Keep Byte 0 13609209464742703042 ok_acked +creation-008-Random-Byte-0 0 8 write Random Byte 0 6945454717920826184 ok_acked +creation-008-Reorder-Byte-0 0 8 write Reorder Byte 0 4383270858743804780 ok_acked +creation-008-Drop-Sector-0 0 8 write Drop Sector 0 551058828896644277 ok_acked +creation-008-Keep-Sector-0 0 8 write Keep Sector 0 1268981265495855532 ok_acked +creation-008-Random-Sector-0 0 8 write Random Sector 0 4341239785549468050 ok_acked +creation-008-Reorder-Sector-0 0 8 write Reorder Sector 0 11096401513600970965 ok_acked +creation-009-Drop-Off-0 0 9 sync Drop Off 0 846097429193874616 ok_acked +creation-009-Keep-Off-0 0 9 sync Keep Off 0 6423655175863383394 ok_acked +creation-009-Random-Off-0 0 9 sync Random Off 0 5514066048952047027 ok_acked +creation-009-Reorder-Off-0 0 9 sync Reorder Off 0 8936328177950274529 ok_acked +creation-009-Drop-Off-1 0 9 sync Drop Off 1 544096486857263283 ok_acked +creation-010-Drop-Off-0 0 10 write Drop Off 0 11454830892009487878 ok_acked +creation-010-Keep-Off-0 0 10 write Keep Off 0 4620587223201936811 ok_acked +creation-010-Random-Off-0 0 10 write Random Off 0 5929132620223616612 ok_acked +creation-010-Reorder-Off-0 0 10 write Reorder Off 0 12318561678508379180 ok_acked +creation-010-Drop-Byte-0 0 10 write Drop Byte 0 2221567639588712724 ok_acked +creation-010-Keep-Byte-0 0 10 write Keep Byte 0 3755468881990442706 ok_acked +creation-010-Random-Byte-0 0 10 write Random Byte 0 13456439080642338908 ok_acked +creation-010-Reorder-Byte-0 0 10 write Reorder Byte 0 11380419657525541033 ok_acked +creation-010-Drop-Sector-0 0 10 write Drop Sector 0 6121001088028161479 ok_acked +creation-010-Keep-Sector-0 0 10 write Keep Sector 0 10086984387624379195 ok_acked +creation-010-Random-Sector-0 0 10 write Random Sector 0 2241553814524216837 ok_acked +creation-010-Reorder-Sector-0 0 10 write Reorder Sector 0 4197525056007063737 ok_acked +creation-011-Drop-Off-0 0 11 sync Drop Off 0 629076892380995495 ok_acked +creation-011-Keep-Off-0 0 11 sync Keep Off 0 8058292565524304195 ok_acked +creation-011-Random-Off-0 0 11 sync Random Off 0 14818301690327689993 ok_acked +creation-011-Reorder-Off-0 0 11 sync Reorder Off 0 15837581058693120501 ok_acked +creation-011-Drop-Off-1 0 11 sync Drop Off 1 5593481111843968281 ok_acked +creation-012-Drop-Off-0 0 12 write Drop Off 0 16435584007572178707 ok_acked +creation-012-Keep-Off-0 0 12 write Keep Off 0 16504825036059576935 ok_acked +creation-012-Random-Off-0 0 12 write Random Off 0 8545305377641998711 ok_acked +creation-012-Reorder-Off-0 0 12 write Reorder Off 0 14847116875334516208 ok_acked +creation-012-Drop-Byte-0 0 12 write Drop Byte 0 4978429993402184775 ok_acked +creation-012-Keep-Byte-0 0 12 write Keep Byte 0 5951639561661670608 ok_acked +creation-012-Random-Byte-0 0 12 write Random Byte 0 6287657137075302688 ok_acked +creation-012-Reorder-Byte-0 0 12 write Reorder Byte 0 7252913775254043133 ok_acked +creation-012-Drop-Sector-0 0 12 write Drop Sector 0 8779521957703021134 ok_acked +creation-012-Keep-Sector-0 0 12 write Keep Sector 0 4146636507889629014 ok_acked +creation-012-Random-Sector-0 0 12 write Random Sector 0 3502421837326728687 ok_acked +creation-012-Reorder-Sector-0 0 12 write Reorder Sector 0 13054621873609623233 ok_acked +creation-013-Drop-Off-0 0 13 sync Drop Off 0 2419886441074615048 ok_acked +creation-013-Keep-Off-0 0 13 sync Keep Off 0 7831545531909572048 ok_acked +creation-013-Random-Off-0 0 13 sync Random Off 0 5528431350533390507 ok_acked +creation-013-Reorder-Off-0 0 13 sync Reorder Off 0 12926780912436458008 ok_acked +creation-013-Drop-Off-1 0 13 sync Drop Off 1 5923064717858862858 ok_acked +creation-014-Drop-Off-0 0 14 write Drop Off 0 18160917021587240614 ok_acked +creation-014-Keep-Off-0 0 14 write Keep Off 0 12908041221183419590 ok_acked +creation-014-Random-Off-0 0 14 write Random Off 0 7509963651611931282 ok_acked +creation-014-Reorder-Off-0 0 14 write Reorder Off 0 2325395834228426780 ok_acked +creation-014-Drop-Byte-0 0 14 write Drop Byte 0 7388119478187627856 ok_acked +creation-014-Keep-Byte-0 0 14 write Keep Byte 0 4094477768756371192 ok_acked +creation-014-Random-Byte-0 0 14 write Random Byte 0 13858860973075329849 ok_acked +creation-014-Reorder-Byte-0 0 14 write Reorder Byte 0 3522078215160363135 ok_acked +creation-014-Drop-Sector-0 0 14 write Drop Sector 0 9925001818705563757 ok_acked +creation-014-Keep-Sector-0 0 14 write Keep Sector 0 16768800976280677328 ok_acked +creation-014-Random-Sector-0 0 14 write Random Sector 0 2988194806534054915 ok_acked +creation-014-Reorder-Sector-0 0 14 write Reorder Sector 0 11954418676109371952 ok_acked +creation-015-Drop-Off-0 0 15 write Drop Off 0 7099095723836540844 ok_acked +creation-015-Keep-Off-0 0 15 write Keep Off 0 10130778497948762408 ok_acked +creation-015-Random-Off-0 0 15 write Random Off 0 85703552846600060 ok_acked +creation-015-Reorder-Off-0 0 15 write Reorder Off 0 17793447363931852734 ok_acked +creation-015-Drop-Byte-0 0 15 write Drop Byte 0 18353951012615474908 ok_acked +creation-015-Keep-Byte-0 0 15 write Keep Byte 0 7517574041014613331 ok_acked +creation-015-Random-Byte-0 0 15 write Random Byte 0 14327853790763717315 ok_acked +creation-015-Reorder-Byte-0 0 15 write Reorder Byte 0 9396440471302053128 ok_acked +creation-015-Drop-Sector-0 0 15 write Drop Sector 0 8525985029033122348 ok_acked +creation-015-Keep-Sector-0 0 15 write Keep Sector 0 5421991896627060050 ok_acked +creation-015-Random-Sector-0 0 15 write Random Sector 0 12489486057644072905 ok_acked +creation-015-Reorder-Sector-0 0 15 write Reorder Sector 0 948963220411992725 ok_acked +creation-016-Drop-Off-0 0 16 write Drop Off 0 11024049096147558901 ok_acked +creation-016-Keep-Off-0 0 16 write Keep Off 0 15517915805348001897 ok_acked +creation-016-Random-Off-0 0 16 write Random Off 0 18338461003514824168 ok_acked +creation-016-Reorder-Off-0 0 16 write Reorder Off 0 16404679331835583554 ok_acked +creation-016-Drop-Byte-0 0 16 write Drop Byte 0 13650136459600432323 ok_acked +creation-016-Keep-Byte-0 0 16 write Keep Byte 0 1447541127232702777 ok_acked +creation-016-Random-Byte-0 0 16 write Random Byte 0 6576843868366412609 ok_acked +creation-016-Reorder-Byte-0 0 16 write Reorder Byte 0 7554685907978836252 ok_acked +creation-016-Drop-Sector-0 0 16 write Drop Sector 0 7933884972108719003 ok_acked +creation-016-Keep-Sector-0 0 16 write Keep Sector 0 996001172450506643 ok_acked +creation-016-Random-Sector-0 0 16 write Random Sector 0 84398084796682670 ok_acked +creation-016-Reorder-Sector-0 0 16 write Reorder Sector 0 8052053944752393860 ok_acked +creation-017-Drop-Off-0 0 17 sync Drop Off 0 15959330728773196207 ok_acked +creation-017-Keep-Off-0 0 17 sync Keep Off 0 4465885817169705801 ok_acked +creation-017-Random-Off-0 0 17 sync Random Off 0 5085458539006098861 ok_acked +creation-017-Reorder-Off-0 0 17 sync Reorder Off 0 15791589826039601869 ok_acked +creation-017-Drop-Off-1 0 17 sync Drop Off 1 5175300957844122164 ok_acked +plus-one-022-Keep-Byte-0 0 22 write Keep Byte 0 17159717446196602230 ok +plus-one-022-Reorder-Byte-0 0 22 write Reorder Byte 0 5874104171546237653 ok +plus-one-022-Keep-Sector-0 0 22 write Keep Sector 0 3608622775727787418 ok +plus-one-023-Keep-Off-0 0 23 sync Keep Off 0 12979232715024206461 ok +plus-one-023-Drop-Off-1 0 23 sync Drop Off 1 5298586695126095865 ok +plus-one-029-Keep-Byte-0 0 29 write Keep Byte 0 3677289713100115240 ok +plus-one-029-Keep-Sector-0 0 29 write Keep Sector 0 17075540313876598908 ok +plus-one-030-Keep-Off-0 0 30 sync Keep Off 0 16456359796967439443 ok +plus-one-030-Drop-Off-1 0 30 sync Drop Off 1 14062681038971558691 ok +plus-one-036-Keep-Byte-0 0 36 write Keep Byte 0 1073056976835893526 ok +plus-one-036-Reorder-Byte-0 0 36 write Reorder Byte 0 12024899070807031009 ok +plus-one-036-Keep-Sector-0 0 36 write Keep Sector 0 8954115610872055338 ok +plus-one-037-Keep-Off-0 0 37 sync Keep Off 0 13962187052594835106 ok +plus-one-037-Drop-Off-1 0 37 sync Drop Off 1 13522350183912501025 ok +plus-one-043-Keep-Byte-0 0 43 write Keep Byte 0 743245684501993840 ok +plus-one-043-Keep-Sector-0 0 43 write Keep Sector 0 13715420359390615090 ok +plus-one-044-Keep-Off-0 0 44 sync Keep Off 0 17017440404623787837 ok +plus-one-044-Drop-Off-1 0 44 sync Drop Off 1 12435517233634304422 ok +plus-one-051-Keep-Off-0 0 51 sync Keep Off 0 15333220709686612268 ok +plus-one-051-Drop-Off-1 0 51 sync Drop Off 1 5436662233547822578 ok +plus-one-057-Keep-Byte-0 0 57 write Keep Byte 0 9523275287782354275 ok +plus-one-057-Keep-Sector-0 0 57 write Keep Sector 0 12213324642289485882 ok +plus-one-058-Keep-Off-0 0 58 sync Keep Off 0 9494113824375037356 ok +plus-one-058-Drop-Off-1 0 58 sync Drop Off 1 1173764370998105968 ok +plus-one-059-Drop-Off-0 0 59 set_len Drop Off 0 9675086961158200550 ok +plus-one-059-Keep-Off-0 0 59 set_len Keep Off 0 18343344445377204566 ok +plus-one-059-Random-Off-0 0 59 set_len Random Off 0 16458820088970563762 ok +plus-one-059-Reorder-Off-0 0 59 set_len Reorder Off 0 17386178431295624566 ok +plus-one-065-Keep-Byte-0 0 65 write Keep Byte 0 5663158859613213736 ok +plus-one-065-Keep-Sector-0 0 65 write Keep Sector 0 15689260707026439258 ok +plus-one-066-Keep-Off-0 0 66 sync Keep Off 0 1196835803102679016 ok +plus-one-066-Drop-Off-1 0 66 sync Drop Off 1 1109959887721242560 ok +plus-one-072-Keep-Byte-0 0 72 write Keep Byte 0 16012255334205995228 ok +plus-one-072-Keep-Sector-0 0 72 write Keep Sector 0 5721322243961908110 ok +plus-one-073-Keep-Off-0 0 73 sync Keep Off 0 5616488548707511700 ok +plus-one-073-Drop-Off-1 0 73 sync Drop Off 1 8029764527321127611 ok +plus-one-079-Keep-Byte-0 0 79 write Keep Byte 0 10764538702579071735 ok +plus-one-080-Keep-Off-0 0 80 sync Keep Off 0 11344803924555740551 ok +plus-one-080-Drop-Off-1 0 80 sync Drop Off 1 9968861234925625445 ok +plus-one-086-Keep-Byte-0 0 86 write Keep Byte 0 9844835710814952365 ok +plus-one-086-Keep-Sector-0 0 86 write Keep Sector 0 12811729155162128366 ok +plus-one-087-Keep-Off-0 0 87 sync Keep Off 0 1457413770787104591 ok +plus-one-087-Drop-Off-1 0 87 sync Drop Off 1 15194032301617396596 ok +plus-one-093-Keep-Byte-0 0 93 write Keep Byte 0 5459276270325608369 ok +plus-one-093-Keep-Sector-0 0 93 write Keep Sector 0 10540439348345794908 ok +plus-one-094-Keep-Off-0 0 94 sync Keep Off 0 11370797204155515580 ok +plus-one-094-Drop-Off-1 0 94 sync Drop Off 1 16386500957888817220 ok +plus-one-095-Drop-Off-0 0 95 set_len Drop Off 0 15335240190787813001 ok +plus-one-095-Keep-Off-0 0 95 set_len Keep Off 0 6571994649100958089 ok +plus-one-095-Random-Off-0 0 95 set_len Random Off 0 850585375677959605 ok +plus-one-095-Reorder-Off-0 0 95 set_len Reorder Off 0 15633448557641503281 ok +plus-one-101-Keep-Byte-0 0 101 write Keep Byte 0 9152589523650914246 ok +plus-one-102-Keep-Off-0 0 102 sync Keep Off 0 8613553169180565950 ok +plus-one-102-Drop-Off-1 0 102 sync Drop Off 1 8276170543297559711 ok +plus-one-108-Keep-Sector-0 0 108 write Keep Sector 0 13551244134764885966 ok +plus-one-109-Keep-Off-0 0 109 sync Keep Off 0 17110204627924075255 ok +plus-one-109-Drop-Off-1 0 109 sync Drop Off 1 7004934532338342255 ok +plus-one-115-Keep-Byte-0 0 115 write Keep Byte 0 16936999225008393733 ok +plus-one-115-Keep-Sector-0 0 115 write Keep Sector 0 11986269216899725365 ok +plus-one-115-Reorder-Sector-0 0 115 write Reorder Sector 0 6945193034454440851 ok +plus-one-116-Keep-Off-0 0 116 sync Keep Off 0 7959295335822054116 ok +plus-one-116-Drop-Off-1 0 116 sync Drop Off 1 8571885778478429262 ok +plus-one-122-Keep-Byte-0 0 122 write Keep Byte 0 17331865487772302743 ok +plus-one-122-Keep-Sector-0 0 122 write Keep Sector 0 11350967914107301853 ok +plus-one-123-Keep-Off-0 0 123 sync Keep Off 0 9399610073314401180 ok +plus-one-123-Drop-Off-1 0 123 sync Drop Off 1 9643629509895093683 ok +plus-one-129-Keep-Byte-0 0 129 write Keep Byte 0 16356615628761297766 ok +plus-one-130-Keep-Off-0 0 130 sync Keep Off 0 4201256235436612724 ok +plus-one-130-Drop-Off-1 0 130 sync Drop Off 1 18319477973620862619 ok +plus-one-136-Keep-Sector-0 0 136 write Keep Sector 0 15426643891416011518 ok +plus-one-137-Keep-Off-0 0 137 sync Keep Off 0 18059055659301111446 ok +plus-one-137-Drop-Off-1 0 137 sync Drop Off 1 11670476942029156616 ok +plus-one-143-Keep-Byte-0 0 143 write Keep Byte 0 4819685669170855675 ok +plus-one-143-Keep-Sector-0 0 143 write Keep Sector 0 12404584291279098786 ok +plus-one-144-Keep-Off-0 0 144 sync Keep Off 0 4509713501023639030 ok +plus-one-144-Random-Off-0 0 144 sync Random Off 0 12996819009898538828 ok +plus-one-144-Drop-Off-1 0 144 sync Drop Off 1 11845784508414884195 ok +plus-one-150-Keep-Byte-0 0 150 write Keep Byte 0 12879811006385981565 ok +plus-one-150-Keep-Sector-0 0 150 write Keep Sector 0 3355508687898162126 ok +plus-one-151-Keep-Off-0 0 151 sync Keep Off 0 11658357123498811149 ok +plus-one-151-Drop-Off-1 0 151 sync Drop Off 1 14102474731894244315 ok +plus-one-157-Keep-Byte-0 0 157 write Keep Byte 0 13015970949288001617 ok +plus-one-158-Keep-Off-0 0 158 sync Keep Off 0 226616622852948567 ok +plus-one-158-Drop-Off-1 0 158 sync Drop Off 1 8848409451507504865 ok +plus-one-164-Keep-Byte-0 0 164 write Keep Byte 0 17781607496497651088 ok +plus-one-165-Keep-Off-0 0 165 sync Keep Off 0 9559187864972879549 ok +plus-one-165-Drop-Off-1 0 165 sync Drop Off 1 1364893903502039169 ok +plus-one-172-Keep-Off-0 0 172 sync Keep Off 0 6176499517270327538 ok +plus-one-172-Drop-Off-1 0 172 sync Drop Off 1 4902630687251410631 ok +plus-one-178-Keep-Sector-0 0 178 write Keep Sector 0 17434570087522059525 ok +plus-one-179-Keep-Off-0 0 179 sync Keep Off 0 14664915457875083941 ok +plus-one-179-Drop-Off-1 0 179 sync Drop Off 1 2158217774018844332 ok +plus-one-185-Keep-Byte-0 0 185 write Keep Byte 0 4328850222115683582 ok +plus-one-185-Keep-Sector-0 0 185 write Keep Sector 0 16442685127517382046 ok +plus-one-186-Keep-Off-0 0 186 sync Keep Off 0 471346582473724138 ok +plus-one-186-Drop-Off-1 0 186 sync Drop Off 1 7138328635476519600 ok +plus-one-192-Keep-Byte-0 0 192 write Keep Byte 0 2723226904692007828 ok +plus-one-192-Keep-Sector-0 0 192 write Keep Sector 0 3762972556988439368 ok +plus-one-193-Keep-Off-0 0 193 sync Keep Off 0 16293198396376081680 ok +plus-one-193-Drop-Off-1 0 193 sync Drop Off 1 14057701477112361279 ok +plus-one-200-Keep-Off-0 0 200 sync Keep Off 0 11291141204742016888 ok +plus-one-200-Drop-Off-1 0 200 sync Drop Off 1 10997830215724634758 ok +plus-one-206-Keep-Sector-0 0 206 write Keep Sector 0 996291559859406713 ok +plus-one-207-Keep-Off-0 0 207 sync Keep Off 0 3421321042748084502 ok +plus-one-207-Drop-Off-1 0 207 sync Drop Off 1 6991732400085512055 ok +plus-one-213-Keep-Sector-0 0 213 write Keep Sector 0 14142522353743214798 ok +plus-one-214-Keep-Off-0 0 214 sync Keep Off 0 2906426256159375011 ok +plus-one-214-Drop-Off-1 0 214 sync Drop Off 1 9622106854730894668 ok +plus-one-220-Keep-Sector-0 0 220 write Keep Sector 0 8534405119438152349 ok +plus-one-221-Keep-Off-0 0 221 sync Keep Off 0 15821138474098230189 ok +plus-one-221-Drop-Off-1 0 221 sync Drop Off 1 3288017182843588134 ok +plus-one-227-Keep-Byte-0 0 227 write Keep Byte 0 9657677367967393423 ok +plus-one-227-Keep-Sector-0 0 227 write Keep Sector 0 6177024314569772746 ok +plus-one-228-Keep-Off-0 0 228 sync Keep Off 0 9029223228838882433 ok +plus-one-228-Drop-Off-1 0 228 sync Drop Off 1 12902190087826044541 ok +plus-one-236-Keep-Sector-0 0 236 write Keep Sector 0 7701654716772776404 ok +plus-one-237-Keep-Off-0 0 237 sync Keep Off 0 16314407727201645124 ok +plus-one-237-Drop-Off-1 0 237 sync Drop Off 1 14672055236796597328 ok +plus-one-244-Keep-Byte-0 0 244 write Keep Byte 0 2545644468760759305 ok +plus-one-244-Keep-Sector-0 0 244 write Keep Sector 0 1138709232127961778 ok +plus-one-245-Keep-Off-0 0 245 sync Keep Off 0 16779195880312402482 ok +plus-one-245-Drop-Off-1 0 245 sync Drop Off 1 9662999547611891784 ok +plus-one-252-Reorder-Byte-0 0 252 write Reorder Byte 0 17600646676325198613 ok +plus-one-252-Keep-Sector-0 0 252 write Keep Sector 0 6106773522872599567 ok +plus-one-253-Keep-Off-0 0 253 sync Keep Off 0 669091732885727436 ok +plus-one-253-Drop-Off-1 0 253 sync Drop Off 1 13110509666847206191 ok +plus-one-260-Keep-Byte-0 0 260 write Keep Byte 0 11892714446878039032 ok +plus-one-260-Keep-Sector-0 0 260 write Keep Sector 0 7244008292654662953 ok +plus-one-261-Keep-Off-0 0 261 sync Keep Off 0 15410999506478148281 ok +plus-one-261-Drop-Off-1 0 261 sync Drop Off 1 14685771586452083517 ok +plus-one-268-Keep-Byte-0 0 268 write Keep Byte 0 13030605835388508912 ok +plus-one-268-Keep-Sector-0 0 268 write Keep Sector 0 15541796859597634820 ok +plus-one-269-Keep-Off-0 0 269 sync Keep Off 0 13470682428541606125 ok +plus-one-269-Drop-Off-1 0 269 sync Drop Off 1 3348015705295408204 ok +plus-one-270-Drop-Off-0 0 270 set_len Drop Off 0 7278344024754470113 ok +plus-one-270-Keep-Off-0 0 270 set_len Keep Off 0 9428231705766710789 ok +plus-one-270-Random-Off-0 0 270 set_len Random Off 0 17750540204172085804 ok +plus-one-270-Reorder-Off-0 0 270 set_len Reorder Off 0 4139401517197579639 ok +plus-one-277-Keep-Byte-0 0 277 write Keep Byte 0 13993632700163654876 ok +plus-one-277-Keep-Sector-0 0 277 write Keep Sector 0 12177611620462151024 ok +plus-one-278-Keep-Off-0 0 278 sync Keep Off 0 12934099675899382522 ok +plus-one-278-Drop-Off-1 0 278 sync Drop Off 1 2600097961753500374 ok +plus-one-285-Keep-Byte-0 0 285 write Keep Byte 0 9092721169643432081 ok +plus-one-285-Keep-Sector-0 0 285 write Keep Sector 0 14326796880669928031 ok +plus-one-286-Keep-Off-0 0 286 sync Keep Off 0 987527239032736115 ok +plus-one-286-Drop-Off-1 0 286 sync Drop Off 1 9921579114731518860 ok +plus-one-293-Keep-Byte-0 0 293 write Keep Byte 0 15170862304073081800 ok +plus-one-294-Keep-Off-0 0 294 sync Keep Off 0 9622997903921343314 ok +plus-one-294-Drop-Off-1 0 294 sync Drop Off 1 10755514834960504906 ok +plus-one-301-Keep-Byte-0 0 301 write Keep Byte 0 5898513328733929430 ok +plus-one-301-Keep-Sector-0 0 301 write Keep Sector 0 6918944036435080058 ok +plus-one-302-Keep-Off-0 0 302 sync Keep Off 0 14494326205444703633 ok +plus-one-302-Drop-Off-1 0 302 sync Drop Off 1 5713008472603814247 ok +plus-one-309-Keep-Byte-0 0 309 write Keep Byte 0 15820024857312553229 ok +plus-one-309-Keep-Sector-0 0 309 write Keep Sector 0 16836305046597306226 ok +plus-one-310-Keep-Off-0 0 310 sync Keep Off 0 10121081548021687824 ok +plus-one-310-Drop-Off-1 0 310 sync Drop Off 1 8702959481884706028 ok +plus-one-317-Keep-Byte-0 0 317 write Keep Byte 0 792486474003545020 ok +plus-one-317-Random-Byte-0 0 317 write Random Byte 0 6788073276497600593 ok +plus-one-317-Keep-Sector-0 0 317 write Keep Sector 0 17959517080523022449 ok +plus-one-318-Keep-Off-0 0 318 sync Keep Off 0 1932390360444586315 ok +plus-one-318-Drop-Off-1 0 318 sync Drop Off 1 4205658030532119269 ok +plus-one-325-Keep-Byte-0 0 325 write Keep Byte 0 14861594154973533194 ok +plus-one-325-Keep-Sector-0 0 325 write Keep Sector 0 16222447895129162399 ok +plus-one-326-Keep-Off-0 0 326 sync Keep Off 0 5610999441853935093 ok +plus-one-326-Drop-Off-1 0 326 sync Drop Off 1 10283848611267938763 ok +plus-one-333-Keep-Byte-0 0 333 write Keep Byte 0 5320044684916358688 ok +plus-one-333-Keep-Sector-0 0 333 write Keep Sector 0 10335334839610151528 ok +plus-one-334-Keep-Off-0 0 334 sync Keep Off 0 8698815588115581057 ok +plus-one-334-Drop-Off-1 0 334 sync Drop Off 1 14104320201174338956 ok +plus-one-341-Keep-Sector-0 0 341 write Keep Sector 0 12239801341686695436 ok +plus-one-342-Keep-Off-0 0 342 sync Keep Off 0 16800024510819511144 ok +plus-one-342-Drop-Off-1 0 342 sync Drop Off 1 14093191172629087699 ok +plus-one-349-Keep-Byte-0 0 349 write Keep Byte 0 5425291460301345498 ok +plus-one-349-Keep-Sector-0 0 349 write Keep Sector 0 7926769357863004682 ok +plus-one-350-Keep-Off-0 0 350 sync Keep Off 0 11049884960364478093 ok +plus-one-350-Drop-Off-1 0 350 sync Drop Off 1 8369231307554440363 ok +plus-one-357-Keep-Byte-0 0 357 write Keep Byte 0 11874527151768563442 ok +plus-one-358-Keep-Off-0 0 358 sync Keep Off 0 15646842522859097834 ok +plus-one-358-Drop-Off-1 0 358 sync Drop Off 1 53875785576450691 ok +plus-one-365-Keep-Sector-0 0 365 write Keep Sector 0 8775944472059453994 ok +plus-one-366-Keep-Off-0 0 366 sync Keep Off 0 6709858827337736141 ok +plus-one-366-Reorder-Off-0 0 366 sync Reorder Off 0 4980662953110474942 ok +plus-one-366-Drop-Off-1 0 366 sync Drop Off 1 5076550290399593429 ok +plus-one-373-Keep-Sector-0 0 373 write Keep Sector 0 1651500169205634748 ok +plus-one-374-Keep-Off-0 0 374 sync Keep Off 0 7179207035528338457 ok +plus-one-374-Drop-Off-1 0 374 sync Drop Off 1 14216269247549389277 ok +plus-one-381-Keep-Byte-0 0 381 write Keep Byte 0 25144791087050926 ok +plus-one-381-Keep-Sector-0 0 381 write Keep Sector 0 14844884227816705147 ok +plus-one-382-Keep-Off-0 0 382 sync Keep Off 0 5299297645456731254 ok +plus-one-382-Drop-Off-1 0 382 sync Drop Off 1 8071622813456534514 ok +plus-one-389-Keep-Byte-0 0 389 write Keep Byte 0 15050556585184635075 ok +plus-one-390-Keep-Off-0 0 390 sync Keep Off 0 2136558283510580909 ok +plus-one-390-Drop-Off-1 0 390 sync Drop Off 1 6350749618547516658 ok +plus-one-397-Keep-Byte-0 0 397 write Keep Byte 0 13401847063454727570 ok +plus-one-398-Keep-Off-0 0 398 sync Keep Off 0 11013033131369215977 ok +plus-one-398-Drop-Off-1 0 398 sync Drop Off 1 17049793796448489352 ok +plus-one-405-Keep-Sector-0 0 405 write Keep Sector 0 14880989900866968323 ok +plus-one-406-Keep-Off-0 0 406 sync Keep Off 0 10663496633316496638 ok +plus-one-406-Drop-Off-1 0 406 sync Drop Off 1 4675429418653010385 ok +plus-one-413-Keep-Byte-0 0 413 write Keep Byte 0 1846403705042218541 ok +plus-one-414-Keep-Off-0 0 414 sync Keep Off 0 17373689414762106427 ok +plus-one-414-Drop-Off-1 0 414 sync Drop Off 1 9127228066061688679 ok +plus-one-421-Keep-Byte-0 0 421 write Keep Byte 0 16281708537922223047 ok +plus-one-421-Keep-Sector-0 0 421 write Keep Sector 0 10110727640458753789 ok +plus-one-422-Keep-Off-0 0 422 sync Keep Off 0 15630547451257318311 ok +plus-one-422-Drop-Off-1 0 422 sync Drop Off 1 8379652592334877699 ok +plus-one-430-Keep-Byte-0 0 430 write Keep Byte 0 7855778705507650128 ok +plus-one-430-Keep-Sector-0 0 430 write Keep Sector 0 15446033661566669346 ok +plus-one-431-Keep-Off-0 0 431 sync Keep Off 0 15456783326171078077 ok +plus-one-431-Drop-Off-1 0 431 sync Drop Off 1 3707849266937372193 ok +plus-one-438-Keep-Byte-0 0 438 write Keep Byte 0 17074723607197818772 ok +plus-one-438-Keep-Sector-0 0 438 write Keep Sector 0 17507999598876200035 ok +plus-one-439-Keep-Off-0 0 439 sync Keep Off 0 16169496523120911886 ok +plus-one-439-Drop-Off-1 0 439 sync Drop Off 1 9188697822836266542 ok +plus-one-446-Keep-Sector-0 0 446 write Keep Sector 0 5802401063347607249 ok +plus-one-447-Keep-Off-0 0 447 sync Keep Off 0 6993374808797597733 ok +plus-one-447-Drop-Off-1 0 447 sync Drop Off 1 15032194162153832125 ok +plus-one-454-Keep-Byte-0 0 454 write Keep Byte 0 1352452635395169948 ok +plus-one-454-Keep-Sector-0 0 454 write Keep Sector 0 18401332907381125687 ok +plus-one-455-Keep-Off-0 0 455 sync Keep Off 0 12029085256025663550 ok +plus-one-455-Drop-Off-1 0 455 sync Drop Off 1 17414609708598718808 ok +plus-one-462-Keep-Byte-0 0 462 write Keep Byte 0 14359854969484189849 ok +plus-one-462-Keep-Sector-0 0 462 write Keep Sector 0 1366117760970609433 ok +plus-one-463-Keep-Off-0 0 463 sync Keep Off 0 5068661204843044787 ok +plus-one-463-Drop-Off-1 0 463 sync Drop Off 1 8269955539246309860 ok +plus-one-471-Keep-Off-0 0 471 sync Keep Off 0 5078802323465491428 ok +plus-one-471-Drop-Off-1 0 471 sync Drop Off 1 5265831413306196075 ok +control-open_error-1 1 18 write Drop Byte 0 14083345559147275481 open_error +control-open_error-2 1 18 write Random Byte 0 14392419215163001692 open_error +control-ok_acked_plus_one-1 1 22 write Keep Byte 0 17159717446196602230 ok +control-ok_acked_plus_one-2 1 22 write Keep Sector 0 3608622775727787418 ok +control-lost_committed-1 1 24 write Drop Off 0 740597437182302142 lost_committed +control-lost_committed-2 1 24 write Reorder Off 0 9664433160101948187 lost_committed +control-panic-1 1 482 write Random Sector 0 14777365645789966679 panic diff --git a/pkgs/id/tests/crash/main.rs b/pkgs/id/tests/crash/main.rs index edd9995fd6..4d54f23149 100644 --- a/pkgs/id/tests/crash/main.rs +++ b/pkgs/id/tests/crash/main.rs @@ -10,6 +10,9 @@ //! control, and the corpus replay. `just crash-gate` runs the two full tests in release mode, //! where every storage call is a crash point. A failure found by a sweep goes into `corpus.tsv` //! with its fix (see `corpus.rs`). +//! +//! `identity` is the same gate for the identity store (plan step P1.10), with first creation +//! tested on its own. It needs the `web` feature, so it runs under `--features web`. // Offsets and lengths index in-memory disk images, which stay far below 4 GiB, so the u64 to usize // casts cannot truncate on any target this runs on. @@ -23,6 +26,8 @@ mod corpus; mod faultfs; mod harness; +#[cfg(feature = "web")] +mod identity; mod sweep; mod workload; diff --git a/pkgs/id/tests/crash/sweep.rs b/pkgs/id/tests/crash/sweep.rs index eaf996f953..8c915ede83 100644 --- a/pkgs/id/tests/crash/sweep.rs +++ b/pkgs/id/tests/crash/sweep.rs @@ -85,8 +85,17 @@ pub fn sample_events(total: u64, stride: u64) -> Vec { .collect() } -/// Runs the jobs on all available threads. The result is in the same order as `jobs`. +/// Runs the jobs of the event workload on all available threads. pub fn run_jobs(jobs: &[Job], models: &[Model]) -> Vec { + run_jobs_with(jobs, |job| run_one(Some(job.plan), job.lying, models).0) +} + +/// Runs the jobs on all available threads, each one with `run`. The result is in the same order as +/// `jobs`. +pub fn run_jobs_with(jobs: &[Job], run: F) -> Vec +where + F: Fn(&Job) -> Outcome + Sync, +{ let next = AtomicUsize::new(0); let threads = std::thread::available_parallelism() .map_or(4, usize::from) @@ -100,7 +109,7 @@ pub fn run_jobs(jobs: &[Job], models: &[Model]) -> Vec { loop { let i = next.fetch_add(1, Ordering::Relaxed); let Some(job) = jobs.get(i) else { break }; - done.push((i, run_one(Some(job.plan), job.lying, models).0)); + done.push((i, run(job))); } done }) From ad4c6e050df71718b1e75e5436f7a46a3fe79328 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 11 Oct 2026 18:51:40 -0500 Subject: [PATCH 11/30] chore(rust): refresh Cargo.lock to match Cargo.toml [P1.10] The committed lock lists p2panda-core's dependency rand 0.8.8, but has no entry for that package, and it has no rand_chacha 0.3.1 either. Every build rewrote the file, and `cargo metadata --locked` refused the committed lock. This adds the two package entries and normalizes the dependency references that depend on them. Cargo.toml is unchanged, so no crate is added to the manifest. --- pkgs/id/Cargo.lock | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/pkgs/id/Cargo.lock b/pkgs/id/Cargo.lock index 2c4aa3e092..6aa239a099 100644 --- a/pkgs/id/Cargo.lock +++ b/pkgs/id/Cargo.lock @@ -2272,7 +2272,7 @@ checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" dependencies = [ "cfg-if", "crunchy", - "zerocopy 0.8.62", + "zerocopy", ] [[package]] @@ -4810,13 +4810,24 @@ dependencies = [ "nibble_vec", ] +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "libc", + "rand_chacha 0.3.1", + "rand_core 0.6.4", +] + [[package]] name = "rand" version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" dependencies = [ - "rand_chacha", + "rand_chacha 0.9.0", "rand_core 0.9.5", ] @@ -4831,6 +4842,16 @@ dependencies = [ "rand_core 0.10.1", ] +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core 0.6.4", +] + [[package]] name = "rand_chacha" version = "0.9.0" From 949b2222f2ac74f18e02d8335eedf11b2a24df46 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 11 Oct 2026 18:38:45 -0500 Subject: [PATCH 12/30] feat(rust): event store on redb with first-creation safety [P1.3] The event store keeps verified events, the applied state of each author's chain, and fork proofs in one redb file. Tables: events by (author, seq), an ID index, chain rows (next seq, head, frozen), fork proofs per author, a group index (multimap), and the format row. Position keys are author then big-endian seq, so one author's events sort in sequence order. Creation is crash-safe (N45): the file is built under events.redb.tmp, its first commit and sync are made, the directory is synced, the file is renamed into place, and the directory is synced again. A stale temp file is removed, never trusted. The in-place sequence leaves a partial file under the final name after a crash, which redb refuses to open. Storage is a trait (Storage), so the crash model can drive the store over a simulated directory. FileStorage is the disk. A second opener is InUse, and a file that is not a store is NotAStore and is left alone. tests/crash/store.rs sweeps every storage call of creation (under five survival policies, with and without completed syncs) and every directory operation, then reopens every crash state. The fixed creation passes (766 states, 0 failures). The in-place control fails (300 of 601), so the sweep does see a torn first commit. --- pkgs/id/src/event_store.rs | 915 +++++++++++++++++++++++++++++++++ pkgs/id/src/lib.rs | 1 + pkgs/id/tests/README.md | 4 +- pkgs/id/tests/crash/faultfs.rs | 5 + pkgs/id/tests/crash/main.rs | 1 + pkgs/id/tests/crash/store.rs | 403 +++++++++++++++ 6 files changed, 1328 insertions(+), 1 deletion(-) create mode 100644 pkgs/id/src/event_store.rs create mode 100644 pkgs/id/tests/crash/store.rs diff --git a/pkgs/id/src/event_store.rs b/pkgs/id/src/event_store.rs new file mode 100644 index 0000000000..0a2d04bdb2 --- /dev/null +++ b/pkgs/id/src/event_store.rs @@ -0,0 +1,915 @@ +//! The event store: every verified event, the applied state of each author's +//! chain, and the fork proofs, in one redb file. +//! +//! The store keeps only what [`chain::decode`] has verified. Its tables: +//! +//! - `events`: an author's `(author, seq)` position to the event's bytes. Every +//! accepted event is here, including events past a fork point, which are kept +//! but not applied. +//! - `hashes`: an event's ID to its position. +//! - `chains`: an author to the applied prefix of their chain: the next sequence +//! number, the hash of the last applied event, and the frozen flag. +//! - `forks`: an author to the fork proof, the two headers that conflict at the +//! lowest sequence number where the author has forked. +//! - `groups`: a group hash to the positions of the events in that group. +//! - `meta`: the store's format. +//! +//! A position key is the author's 32 bytes followed by the sequence number in +//! big-endian, so one author's events sort in sequence order. +//! +//! # Creating the file +//! +//! A new store is built under [`TEMP_NAME`]: its tables are committed, the file +//! is synced, and only then is it renamed to [`FILE_NAME`], with the directory +//! synced before and after the rename. A crash leaves either no store file or a +//! complete one. Creating the file in place would let a crash during the first +//! commit leave a file that redb refuses to open, so the store could never start. +//! The crash model in `tests/crash/store.rs` checks every step of this sequence. +//! +//! # Where the files are +//! +//! [`EventStore::open`] takes a directory. [`Storage`] is the seam between the +//! store and its files: [`FileStorage`] is the disk, and the crash model in tests +//! implements the same trait over a simulated directory. + +use std::fs; +use std::io; +use std::path::{Path, PathBuf}; + +use p2panda_core::{Hash, SeqNum}; +use redb::{ + Database, DatabaseError, MultimapTableDefinition, ReadableDatabase, ReadableTable, + StorageError, TableDefinition, WriteTransaction, +}; + +use crate::chain::{self, Event}; +use crate::waiting::AuthorKey; + +/// The store's file name in its directory. +pub const FILE_NAME: &str = "events.redb"; + +/// Where a store is built before it is renamed to [`FILE_NAME`]. A file under +/// this name is never trusted: it is removed and built again. +pub const TEMP_NAME: &str = "events.redb.tmp"; + +/// The format row in `meta`. A store with another format is refused. +const FORMAT: &[u8] = b"id.events.store.v1"; +const FORMAT_KEY: &[u8] = b"format"; + +const EVENTS: TableDefinition<'static, &'static [u8], &'static [u8]> = + TableDefinition::new("events"); +const HASHES: TableDefinition<'static, &'static [u8], &'static [u8]> = + TableDefinition::new("hashes"); +const CHAINS: TableDefinition<'static, &'static [u8], &'static [u8]> = + TableDefinition::new("chains"); +const FORKS: TableDefinition<'static, &'static [u8], &'static [u8]> = TableDefinition::new("forks"); +const GROUPS: MultimapTableDefinition<'static, &'static [u8], &'static [u8]> = + MultimapTableDefinition::new("groups"); +const META: TableDefinition<'static, &'static [u8], &'static [u8]> = TableDefinition::new("meta"); + +/// Bytes in a position key: the author, then the sequence number. +const POSITION_LEN: usize = 40; + +/// Bytes in a chain row: the next sequence number, the head hash, the frozen flag. +const CHAIN_LEN: usize = 8 + 32 + 1; + +/// Why the event store failed. A failure is never a refusal of an event: refused +/// events are reported as outcomes, not errors. +#[derive(Debug, thiserror::Error)] +pub enum StoreError { + /// The directory could not be read or written. + #[error("event store file I/O: {0}")] + Io(#[from] io::Error), + /// redb could not open or create the database. + #[error("event store database: {0}")] + Database(#[from] DatabaseError), + /// A redb transaction could not begin. + #[error("event store transaction: {0}")] + Transaction(#[from] redb::TransactionError), + /// A table could not be opened, or it does not exist. + #[error("event store table: {0}")] + Table(#[from] redb::TableError), + /// A read or write failed inside a transaction. + #[error("event store storage: {0}")] + Storage(#[from] StorageError), + /// A commit failed. + #[error("event store commit: {0}")] + Commit(#[from] redb::CommitError), + /// Another process holds the store open. redb allows one opener at a time. + #[error("{FILE_NAME} is open in another process")] + InUse, + /// The file is there, but it is not an event store of this format. + #[error("{FILE_NAME} is not an event store: {0}")] + NotAStore(String), + /// The store's rows contradict each other. The file was changed outside the store. + #[error("event store is corrupt: {0}")] + Corrupt(String), + /// The position already holds an event, so a second one cannot be stored there. + #[error("sequence {seq} of this author is already stored")] + Occupied { + /// The sequence number that is taken. + seq: SeqNum, + }, +} + +fn corrupt(message: impl Into) -> StoreError { + StoreError::Corrupt(message.into()) +} + +/// Where a store's files live. [`FileStorage`] is a directory on disk. The crash +/// model implements this trait over a simulated directory, so every step of +/// creation and ingest can be interrupted. +pub trait Storage { + /// Creates the named database file, or opens it if it exists. + /// + /// # Errors + /// + /// Returns redb's error if the file cannot be created or opened. + fn create_database(&self, name: &str) -> Result; + + /// Opens the named database file, which must exist. + /// + /// # Errors + /// + /// Returns redb's error if the file is missing or is not a database. + fn open_database(&self, name: &str) -> Result; + + /// Whether the named file exists. + /// + /// # Errors + /// + /// Returns the I/O error if the directory cannot be read. + fn exists(&self, name: &str) -> io::Result; + + /// Removes the named file. A file that does not exist is not an error. + /// + /// # Errors + /// + /// Returns the I/O error if the file exists and cannot be removed. + fn remove(&self, name: &str) -> io::Result<()>; + + /// Renames `from` to `to`, replacing `to` if it exists. + /// + /// # Errors + /// + /// Returns the I/O error if the rename fails. + fn rename(&self, from: &str, to: &str) -> io::Result<()>; + + /// Makes the named file's contents durable. + /// + /// # Errors + /// + /// Returns the I/O error if the sync fails. + fn sync_file(&self, name: &str) -> io::Result<()>; + + /// Makes the directory's entries (created, renamed, or removed files) durable. + /// + /// # Errors + /// + /// Returns the I/O error if the sync fails. + fn sync_dir(&self) -> io::Result<()>; +} + +/// A store directory on disk. +#[derive(Clone, Debug)] +pub struct FileStorage { + dir: PathBuf, +} + +impl FileStorage { + /// The store in `dir`. The directory must exist. + pub fn new(dir: impl Into) -> Self { + Self { dir: dir.into() } + } + + fn path(&self, name: &str) -> PathBuf { + self.dir.join(name) + } +} + +impl Storage for FileStorage { + fn create_database(&self, name: &str) -> Result { + Database::builder().create(self.path(name)) + } + + fn open_database(&self, name: &str) -> Result { + Database::builder().open(self.path(name)) + } + + fn exists(&self, name: &str) -> io::Result { + match fs::metadata(self.path(name)) { + Ok(_) => Ok(true), + Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(false), + Err(err) => Err(err), + } + } + + fn remove(&self, name: &str) -> io::Result<()> { + match fs::remove_file(self.path(name)) { + Ok(()) => Ok(()), + Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(()), + Err(err) => Err(err), + } + } + + fn rename(&self, from: &str, to: &str) -> io::Result<()> { + fs::rename(self.path(from), self.path(to)) + } + + fn sync_file(&self, name: &str) -> io::Result<()> { + fs::File::open(self.path(name))?.sync_all() + } + + fn sync_dir(&self) -> io::Result<()> { + fs::File::open(&self.dir)?.sync_all() + } +} + +/// The applied prefix of one author's chain, as the `chains` table holds it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Chain { + /// The sequence number the next applied event takes: the number of applied + /// events. Zero for an author with none. + pub next_seq: SeqNum, + /// The hash of the last applied event, or `None` when none applies. + pub head: Option, + /// Whether the author has forked. A frozen chain applies nothing from its + /// fork point on. + pub frozen: bool, +} + +impl Chain { + #[allow(dead_code, reason = "the ingest path (P1.8) writes through this")] + fn encode(self) -> [u8; CHAIN_LEN] { + let mut row = [0u8; CHAIN_LEN]; + row[..8].copy_from_slice(&u64::from(self.next_seq).to_be_bytes()); + if let Some(head) = self.head { + row[8..40].copy_from_slice(head.as_bytes()); + } + row[40] = u8::from(self.frozen); + row + } + + fn decode(row: &[u8]) -> Result { + let row: &[u8; CHAIN_LEN] = row + .try_into() + .map_err(|_err| corrupt("a chain row has the wrong length"))?; + let next_seq = seq_num(be_u64(&row[..8])?)?; + let head = if next_seq == 0 { + None + } else { + Some(hash_of(&row[8..40])?) + }; + let frozen = match row[40] { + 0 => false, + 1 => true, + _ => return Err(corrupt("a chain row has an unknown frozen flag")), + }; + Ok(Self { + next_seq, + head, + frozen, + }) + } +} + +/// Two conflicting headers from one author at one sequence number. Both are +/// signed by the author, so together they prove the author forked there. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ForkProof { + /// The sequence number both events name. + pub seq: SeqNum, + /// The event with the lower ID. The order does not depend on arrival. + pub first: Event, + /// The event with the higher ID. + pub second: Event, +} + +/// The event store. One redb file, opened by one process at a time. +#[derive(Debug)] +pub struct EventStore { + db: Database, +} + +impl EventStore { + /// Opens the store in `dir`, creating it if the directory has none. + /// + /// # Errors + /// + /// Returns [`StoreError::InUse`] if another process has it open, and + /// [`StoreError::NotAStore`] if the file is not an event store. Neither + /// deletes or changes the file. + pub fn open(dir: &Path) -> Result { + Self::open_with(&FileStorage::new(dir)) + } + + /// Opens the store on `storage`, creating it if the storage has none. The crash model + /// passes a simulated directory here. + /// + /// # Errors + /// + /// The same errors as [`EventStore::open`]. + pub fn open_with(storage: &S) -> Result { + let db = if storage.exists(FILE_NAME)? { + storage.open_database(FILE_NAME).map_err(open_error)? + } else { + create_fresh(storage)? + }; + verify_schema(&db)?; + Ok(Self { db }) + } + + /// Runs `op` in one write transaction. The transaction commits if `op` + /// succeeds, and is aborted if it fails. + /// + /// # Errors + /// + /// Returns `op`'s error, or a redb error from the commit. + #[allow(dead_code, reason = "the ingest path (P1.8) writes through this")] + pub(crate) fn write( + &self, + op: impl FnOnce(&WriteTransaction) -> Result, + ) -> Result { + let txn = self.db.begin_write()?; + let value = op(&txn)?; + txn.commit()?; + Ok(value) + } + + /// The applied state of `author`'s chain, or `None` if the author has no events. + /// + /// # Errors + /// + /// Returns a redb error if the read fails, or [`StoreError::Corrupt`]. + pub fn chain(&self, author: &AuthorKey) -> Result, StoreError> { + let txn = self.db.begin_read()?; + let chains = txn.open_table(CHAINS)?; + let row = chains.get(author.as_slice())?; + row.map(|row| Chain::decode(row.value())).transpose() + } + + /// The stored event at `(author, seq)`, applied or not. + /// + /// # Errors + /// + /// Returns a redb error if the read fails, or [`StoreError::Corrupt`]. + pub fn event(&self, author: &AuthorKey, seq: SeqNum) -> Result, StoreError> { + let txn = self.db.begin_read()?; + let events = txn.open_table(EVENTS)?; + let stored = events.get(position_key(author, seq).as_slice())?; + stored.map(|bytes| decode_stored(bytes.value())).transpose() + } + + /// The stored event with this ID, applied or not. + /// + /// # Errors + /// + /// Returns a redb error if the read fails, or [`StoreError::Corrupt`]. + pub fn event_by_id(&self, id: &Hash) -> Result, StoreError> { + let txn = self.db.begin_read()?; + let hashes = txn.open_table(HASHES)?; + let events = txn.open_table(EVENTS)?; + let Some(position) = hashes.get(id.as_bytes().as_slice())? else { + return Ok(None); + }; + let stored = events.get(position.value())?; + stored.map(|bytes| decode_stored(bytes.value())).transpose() + } + + /// The fork proof for `author`, if the author has forked. + /// + /// # Errors + /// + /// Returns a redb error if the read fails, or [`StoreError::Corrupt`]. + pub fn fork_proof(&self, author: &AuthorKey) -> Result, StoreError> { + let txn = self.db.begin_read()?; + let forks = txn.open_table(FORKS)?; + let row = forks.get(author.as_slice())?; + row.map(|row| decode_proof(row.value())).transpose() + } + + /// The positions, as `(author, seq)`, of the stored events in `group`. + /// + /// # Errors + /// + /// Returns a redb error if the read fails, or [`StoreError::Corrupt`]. + pub fn group_members(&self, group: &Hash) -> Result, StoreError> { + let txn = self.db.begin_read()?; + let groups = txn.open_multimap_table(GROUPS)?; + let mut members = Vec::new(); + for position in groups.get(group.as_bytes().as_slice())? { + members.push(split_position(position?.value())?); + } + Ok(members) + } + + /// Checks the store's own rows against each other: every applied sequence is + /// stored, every head matches its event, every index points at a stored + /// event, and each frozen chain has a matching fork proof. + /// + /// # Errors + /// + /// Returns [`StoreError::Corrupt`] for the first mismatch found, or a redb + /// error if a read fails. + pub fn check_invariants(&self) -> Result<(), StoreError> { + let txn = self.db.begin_read()?; + let events = txn.open_table(EVENTS)?; + let hashes = txn.open_table(HASHES)?; + let chains = txn.open_table(CHAINS)?; + let forks = txn.open_table(FORKS)?; + let groups = txn.open_multimap_table(GROUPS)?; + + for row in events.iter()? { + let (position, bytes) = row?; + let (author, seq) = split_position(position.value())?; + let event = decode_stored(bytes.value())?; + if *event.header.verifying_key.as_bytes() != author || event.header.seq_num != seq { + return Err(corrupt("an event is stored under another position")); + } + let indexed = hashes.get(event.id.as_bytes().as_slice())?; + if indexed.map(|found| found.value().to_vec()) != Some(position.value().to_vec()) { + return Err(corrupt("an event is not indexed under its ID")); + } + if let Some(group) = event.header.extensions.group { + let mut found = false; + for member in groups.get(group.as_bytes().as_slice())? { + found |= member?.value() == position.value(); + } + if !found { + return Err(corrupt("an event is missing from its group index")); + } + } + } + + for row in hashes.iter()? { + let (id, position) = row?; + let stored = events + .get(position.value())? + .ok_or_else(|| corrupt("an ID points at no stored event"))?; + if Hash::digest(stored.value()) != hash_of(id.value())? { + return Err(corrupt("an ID does not match the event it points at")); + } + } + + for row in chains.iter()? { + let (author_bytes, chain_bytes) = row?; + let author: AuthorKey = author_bytes + .value() + .try_into() + .map_err(|_err| corrupt("a chain row has a short author key"))?; + let chain = Chain::decode(chain_bytes.value())?; + for seq in 0..chain.next_seq { + if events.get(position_key(&author, seq).as_slice())?.is_none() { + return Err(corrupt(format!("applied sequence {seq} is not stored"))); + } + } + if let Some(head) = chain.head { + let last = chain.next_seq.saturating_sub(1); + let stored = events + .get(position_key(&author, last).as_slice())? + .ok_or_else(|| corrupt("the head of a chain is not stored"))?; + if Hash::digest(stored.value()) != head { + return Err(corrupt("the head of a chain does not match its event")); + } + } + let proof = forks + .get(author_bytes.value())? + .map(|row| decode_proof(row.value())) + .transpose()?; + match (chain.frozen, proof) { + (false, None) => {} + (true, Some(proof)) if proof.seq == chain.next_seq => {} + _ => { + return Err(corrupt( + "a frozen chain has no fork proof at its fork point, or an open chain has one", + )); + } + } + } + + for row in forks.iter()? { + let (author_bytes, _) = row?; + let chain = chains + .get(author_bytes.value())? + .map(|row| Chain::decode(row.value())) + .transpose()?; + if !chain.is_some_and(|chain| chain.frozen) { + return Err(corrupt( + "a fork proof belongs to a chain that is not frozen", + )); + } + } + Ok(()) + } + + /// Runs redb's own integrity check on the file. + /// + /// # Errors + /// + /// Returns a redb error if the check cannot run. + pub fn check_integrity(&mut self) -> Result { + Ok(self.db.check_integrity()?) + } +} + +/// Builds a new store under [`TEMP_NAME`], then renames it into place. +fn create_fresh(storage: &S) -> Result { + storage.remove(TEMP_NAME)?; + let db = storage.create_database(TEMP_NAME)?; + initialize(&db)?; + drop(db); + storage.sync_file(TEMP_NAME)?; + storage.sync_dir()?; + storage.rename(TEMP_NAME, FILE_NAME)?; + storage.sync_dir()?; + Ok(storage.open_database(FILE_NAME)?) +} + +/// Commits every table and the format row in one transaction. +fn initialize(db: &Database) -> Result<(), StoreError> { + let txn = db.begin_write()?; + txn.open_table(EVENTS)?; + txn.open_table(HASHES)?; + txn.open_table(CHAINS)?; + txn.open_table(FORKS)?; + txn.open_multimap_table(GROUPS)?; + let mut meta = txn.open_table(META)?; + meta.insert(FORMAT_KEY, FORMAT)?; + drop(meta); + txn.commit()?; + Ok(()) +} + +/// Checks that every table exists and that the format row is this store's. +fn verify_schema(db: &Database) -> Result<(), StoreError> { + let txn = db.begin_read()?; + let missing = |err: redb::TableError| StoreError::NotAStore(err.to_string()); + txn.open_table(EVENTS).map_err(missing)?; + txn.open_table(HASHES).map_err(missing)?; + txn.open_table(CHAINS).map_err(missing)?; + txn.open_table(FORKS).map_err(missing)?; + txn.open_multimap_table(GROUPS).map_err(missing)?; + let meta = txn.open_table(META).map_err(missing)?; + match meta.get(FORMAT_KEY)? { + Some(found) if found.value() == FORMAT => Ok(()), + _ => Err(StoreError::NotAStore( + "the format row is missing or names another format".to_owned(), + )), + } +} + +/// Maps redb's open errors. A second opener is `InUse`. redb reports a file that +/// is not a database as an `InvalidData` I/O error, so that is `NotAStore`, and +/// any other I/O failure is `Io`. Everything else means the file is not a store. +fn open_error(err: DatabaseError) -> StoreError { + match err { + DatabaseError::DatabaseAlreadyOpen => StoreError::InUse, + DatabaseError::Storage(StorageError::Io(err)) + if err.kind() != io::ErrorKind::InvalidData => + { + StoreError::Io(err) + } + other => StoreError::NotAStore(other.to_string()), + } +} + +/// The key of `(author, seq)`: the author's bytes, then the sequence number. +pub(crate) fn position_key(author: &AuthorKey, seq: SeqNum) -> [u8; POSITION_LEN] { + let mut key = [0u8; POSITION_LEN]; + key[..32].copy_from_slice(author); + key[32..].copy_from_slice(&u64::from(seq).to_be_bytes()); + key +} + +/// Splits a position key into its author and sequence number. +fn split_position(key: &[u8]) -> Result<(AuthorKey, SeqNum), StoreError> { + let key: &[u8; POSITION_LEN] = key + .try_into() + .map_err(|_err| corrupt("a position key has the wrong length"))?; + let author: AuthorKey = key[..32] + .try_into() + .map_err(|_err| corrupt("a position key has a short author"))?; + Ok((author, seq_num(be_u64(&key[32..])?)?)) +} + +fn be_u64(bytes: &[u8]) -> Result { + let bytes: [u8; 8] = bytes + .try_into() + .map_err(|_err| corrupt("a number is not 8 bytes"))?; + Ok(u64::from_be_bytes(bytes)) +} + +/// A stored sequence number. Stored as eight bytes, and checked to fit `SeqNum`. +fn seq_num(value: u64) -> Result { + SeqNum::try_from(value).map_err(|_err| corrupt("a sequence number is out of range")) +} + +fn hash_of(bytes: &[u8]) -> Result { + let bytes: [u8; 32] = bytes + .try_into() + .map_err(|_err| corrupt("a hash is not 32 bytes"))?; + Ok(Hash::from_bytes(bytes)) +} + +/// Decodes a stored event. A stored event decoded when it was accepted, so a +/// failure here means the file changed underneath the store. +fn decode_stored(bytes: &[u8]) -> Result { + chain::decode(bytes).map_err(|err| corrupt(format!("a stored event does not decode: {err}"))) +} + +/// Encodes a fork proof: the sequence number, the length of the first header, +/// then the two headers, ordered by ID. +#[allow(dead_code, reason = "the ingest path (P1.8) writes through this")] +pub(crate) fn encode_proof(seq: SeqNum, a: &Event, b: &Event) -> Result, StoreError> { + let (first, second) = if a.id.as_bytes() <= b.id.as_bytes() { + (a, b) + } else { + (b, a) + }; + let length = u32::try_from(first.bytes.len()) + .map_err(|_err| corrupt("an event is too long for a fork proof"))?; + let mut out = Vec::with_capacity(12 + first.bytes.len() + second.bytes.len()); + out.extend_from_slice(&u64::from(seq).to_be_bytes()); + out.extend_from_slice(&length.to_be_bytes()); + out.extend_from_slice(&first.bytes); + out.extend_from_slice(&second.bytes); + Ok(out) +} + +fn decode_proof(bytes: &[u8]) -> Result { + if bytes.len() < 12 { + return Err(corrupt("a fork proof is shorter than its header")); + } + let seq = seq_num(be_u64(&bytes[..8])?)?; + let length: [u8; 4] = bytes[8..12] + .try_into() + .map_err(|_err| corrupt("a fork proof has a short length"))?; + let length = u32::from_be_bytes(length) as usize; + let rest = &bytes[12..]; + if length > rest.len() { + return Err(corrupt("a fork proof names more bytes than it holds")); + } + let (first, second) = rest.split_at(length); + Ok(ForkProof { + seq, + first: decode_stored(first)?, + second: decode_stored(second)?, + }) +} + +/// Stores an accepted event at its position, and indexes it by ID and group. +/// A position that is already stored is refused, inside the same transaction. +#[allow(dead_code, reason = "the ingest path (P1.8) writes through this")] +pub(crate) fn store_event(txn: &WriteTransaction, event: &Event) -> Result<(), StoreError> { + let author = *event.header.verifying_key.as_bytes(); + let seq = event.header.seq_num; + let key = position_key(&author, seq); + let mut events = txn.open_table(EVENTS)?; + if events.get(key.as_slice())?.is_some() { + return Err(StoreError::Occupied { seq }); + } + events.insert(key.as_slice(), event.bytes.as_slice())?; + drop(events); + let mut hashes = txn.open_table(HASHES)?; + hashes.insert(event.id.as_bytes().as_slice(), key.as_slice())?; + drop(hashes); + if let Some(group) = event.header.extensions.group { + let mut groups = txn.open_multimap_table(GROUPS)?; + groups.insert(group.as_bytes().as_slice(), key.as_slice())?; + } + Ok(()) +} + +/// Writes an author's chain row. +#[allow(dead_code, reason = "the ingest path (P1.8) writes through this")] +pub(crate) fn store_chain( + txn: &WriteTransaction, + author: &AuthorKey, + chain: Chain, +) -> Result<(), StoreError> { + let mut chains = txn.open_table(CHAINS)?; + chains.insert(author.as_slice(), chain.encode().as_slice())?; + Ok(()) +} + +/// Writes an author's fork proof, replacing any earlier one. +#[allow(dead_code, reason = "the ingest path (P1.8) writes through this")] +pub(crate) fn store_fork( + txn: &WriteTransaction, + author: &AuthorKey, + seq: SeqNum, + a: &Event, + b: &Event, +) -> Result<(), StoreError> { + let proof = encode_proof(seq, a, b)?; + let mut forks = txn.open_table(FORKS)?; + forks.insert(author.as_slice(), proof.as_slice())?; + Ok(()) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use super::*; + use crate::chain::{ChainExt, sign}; + use p2panda_core::SigningKey; + + fn key(n: u8) -> SigningKey { + SigningKey::from_bytes(&[n; 32]) + } + + fn author(key: &SigningKey) -> AuthorKey { + *key.verifying_key().as_bytes() + } + + fn ext(kind: &str, group: Option) -> ChainExt { + ChainExt { + kind: kind.to_owned(), + group, + after: Vec::new(), + } + } + + /// The first `count` events of `key`'s chain, each naming the one before. + fn chain_of(key: &SigningKey, count: SeqNum) -> Vec { + let mut events: Vec = Vec::new(); + for seq in 0..count { + let backlink = events.last().map(|event| event.id); + let event = sign(key, seq, backlink, None, ext("message", None)).unwrap(); + events.push(event); + } + events + } + + fn open_temp() -> (tempfile::TempDir, EventStore) { + let dir = tempfile::tempdir().unwrap(); + let store = EventStore::open(dir.path()).unwrap(); + (dir, store) + } + + #[test] + fn test_a_new_store_is_created_empty_and_reopens() { + let dir = tempfile::tempdir().unwrap(); + let store = EventStore::open(dir.path()).unwrap(); + assert!(store.chain(&author(&key(1))).unwrap().is_none()); + store.check_invariants().unwrap(); + assert!(dir.path().join(FILE_NAME).exists()); + assert!(!dir.path().join(TEMP_NAME).exists(), "no temp file is left"); + drop(store); + let reopened = EventStore::open(dir.path()).unwrap(); + reopened.check_invariants().unwrap(); + } + + #[test] + fn test_a_stale_temp_file_is_replaced_not_trusted() { + let dir = tempfile::tempdir().unwrap(); + fs::write(dir.path().join(TEMP_NAME), b"half a store from a crash").unwrap(); + let store = EventStore::open(dir.path()).unwrap(); + store.check_invariants().unwrap(); + assert!(!dir.path().join(TEMP_NAME).exists()); + } + + #[test] + fn test_a_file_that_is_not_a_store_is_refused_and_left_alone() { + let dir = tempfile::tempdir().unwrap(); + let garbage = b"this is not a redb database at all".to_vec(); + fs::write(dir.path().join(FILE_NAME), &garbage).unwrap(); + let err = EventStore::open(dir.path()).unwrap_err(); + assert!( + matches!(err, StoreError::NotAStore(_)), + "unexpected error: {err}" + ); + assert!(err.to_string().contains(FILE_NAME), "{err}"); + assert_eq!(fs::read(dir.path().join(FILE_NAME)).unwrap(), garbage); + } + + #[test] + fn test_a_second_opener_is_refused_while_the_first_is_open() { + let (dir, store) = open_temp(); + let err = EventStore::open(dir.path()).unwrap_err(); + assert!(matches!(err, StoreError::InUse), "unexpected error: {err}"); + drop(store); + EventStore::open(dir.path()).unwrap(); + } + + #[test] + fn test_a_second_event_at_one_position_is_refused_in_the_same_transaction() { + let (_dir, store) = open_temp(); + let signer = key(2); + let first = chain_of(&signer, 1).remove(0); + let rival = sign(&signer, 0, None, None, ext("other", None)).unwrap(); + let result = store.write(|txn| { + store_event(txn, &first)?; + store_event(txn, &rival) + }); + assert!(matches!(result, Err(StoreError::Occupied { seq: 0 }))); + // The transaction was aborted, so the first event was not stored either. + assert!(store.event(&author(&signer), 0).unwrap().is_none()); + store.check_invariants().unwrap(); + } + + #[test] + fn test_a_stored_event_reads_back_by_position_id_and_group() { + let (_dir, store) = open_temp(); + let signer = key(3); + let group = Hash::digest(b"group"); + let event = sign(&signer, 0, None, None, ext("message", Some(group))).unwrap(); + store.write(|txn| store_event(txn, &event)).unwrap(); + let who = author(&signer); + assert_eq!(store.event(&who, 0).unwrap(), Some(event.clone())); + assert_eq!(store.event_by_id(&event.id).unwrap(), Some(event.clone())); + assert_eq!(store.group_members(&group).unwrap(), vec![(who, 0)]); + assert!( + store + .group_members(&Hash::digest(b"other")) + .unwrap() + .is_empty() + ); + store.check_invariants().unwrap(); + } + + #[test] + fn test_a_chain_row_round_trips_with_and_without_a_head() { + let (_dir, store) = open_temp(); + let who = author(&key(4)); + let empty = Chain { + next_seq: 0, + head: None, + frozen: false, + }; + store.write(|txn| store_chain(txn, &who, empty)).unwrap(); + assert_eq!(store.chain(&who).unwrap(), Some(empty)); + let head = Chain { + next_seq: 5, + head: Some(Hash::digest(b"head")), + frozen: false, + }; + store.write(|txn| store_chain(txn, &who, head)).unwrap(); + assert_eq!(store.chain(&who).unwrap(), Some(head)); + } + + #[test] + fn test_a_fork_proof_holds_both_headers_in_id_order() { + let (_dir, store) = open_temp(); + let signer = key(5); + let original = chain_of(&signer, 1).remove(0); + let rival = sign(&signer, 0, None, None, ext("rival", None)).unwrap(); + let who = author(&signer); + store + .write(|txn| { + store_event(txn, &original)?; + store_fork(txn, &who, 0, &rival, &original)?; + store_chain( + txn, + &who, + Chain { + next_seq: 0, + head: None, + frozen: true, + }, + ) + }) + .unwrap(); + let proof = store.fork_proof(&who).unwrap().expect("a proof is stored"); + assert_eq!(proof.seq, 0); + assert!(proof.first.id.as_bytes() < proof.second.id.as_bytes()); + let mut ids = [original.id, rival.id]; + ids.sort_by(|a, b| a.as_bytes().cmp(b.as_bytes())); + assert_eq!([proof.first.id, proof.second.id], ids); + store.check_invariants().unwrap(); + } + + #[test] + fn test_invariants_refuse_a_head_with_no_stored_event() { + let (_dir, store) = open_temp(); + let who = author(&key(6)); + let claims_two = Chain { + next_seq: 2, + head: Some(Hash::digest(b"second")), + frozen: false, + }; + store + .write(|txn| store_chain(txn, &who, claims_two)) + .unwrap(); + assert!(matches!( + store.check_invariants(), + Err(StoreError::Corrupt(_)) + )); + } + + #[test] + fn test_invariants_refuse_a_frozen_chain_without_a_proof() { + let (_dir, store) = open_temp(); + let who = author(&key(7)); + let frozen = Chain { + next_seq: 0, + head: None, + frozen: true, + }; + store.write(|txn| store_chain(txn, &who, frozen)).unwrap(); + assert!(matches!( + store.check_invariants(), + Err(StoreError::Corrupt(_)) + )); + } +} diff --git a/pkgs/id/src/lib.rs b/pkgs/id/src/lib.rs index 5f28fd8354..112054c2b9 100644 --- a/pkgs/id/src/lib.rs +++ b/pkgs/id/src/lib.rs @@ -174,6 +174,7 @@ pub mod discovery; pub mod envelope_net; #[cfg(feature = "world")] pub mod envelope_outbox; +pub mod event_store; pub mod fileops; pub mod helpers; pub mod invite; diff --git a/pkgs/id/tests/README.md b/pkgs/id/tests/README.md index 14ecb85ba4..955e201310 100644 --- a/pkgs/id/tests/README.md +++ b/pkgs/id/tests/README.md @@ -21,7 +21,9 @@ in the - `crash/`: the crash-safety gate for redb (plan P1.4). A fault model behind `redb::StorageBackend` cuts the power at a storage call of a 50-transaction workload, and the oracle checks the reopened state. `corpus.tsv` is the static - replay list. See `crash/main.rs`. + replay list. See `crash/main.rs`. `crash/store.rs` is the event store's first + creation (plan P1.3): a simulated directory with its directory steps as crash + points, and the in-place control that must fail. - `common/mod.rs`: the tuple checker shared by the property tests and the replay. - `common/chain.rs`: the event decoder's contract, shared the same way. - `regressions/`: checked-in failing cases. See its [README](regressions/README.md). diff --git a/pkgs/id/tests/crash/faultfs.rs b/pkgs/id/tests/crash/faultfs.rs index cfa31f691a..1f7dd60c78 100644 --- a/pkgs/id/tests/crash/faultfs.rs +++ b/pkgs/id/tests/crash/faultfs.rs @@ -156,6 +156,11 @@ impl FaultFs { st.live.clone() } } + + /// What a power cut now would leave if it dropped every unsynced operation: the durable bytes. + pub fn synced_image(&self) -> Vec { + self.lock().durable.clone() + } } /// `SplitMix64`. Every random choice in the model is derived from a seed through this function. diff --git a/pkgs/id/tests/crash/main.rs b/pkgs/id/tests/crash/main.rs index edd9995fd6..fd2a303392 100644 --- a/pkgs/id/tests/crash/main.rs +++ b/pkgs/id/tests/crash/main.rs @@ -23,6 +23,7 @@ mod corpus; mod faultfs; mod harness; +mod store; mod sweep; mod workload; diff --git a/pkgs/id/tests/crash/store.rs b/pkgs/id/tests/crash/store.rs new file mode 100644 index 0000000000..67442862d1 --- /dev/null +++ b/pkgs/id/tests/crash/store.rs @@ -0,0 +1,403 @@ +//! Power cuts on the event store: first creation (plan P1.3) and the store's directory. +//! +//! [`SimDir`] implements `id::event_store::Storage` over `faultfs` disks. Each file is a `FaultFs`, +//! which models the file's own durability. The directory keeps two views, the entries the process +//! sees and the entries a power cut would keep, and the directory operations since the last +//! `sync_dir` are pending. A cut lands in one of two places: +//! +//! - in a storage call of a file (a redb write or sync), where `FaultFs` decides what survives; +//! - before a directory operation (a create, a remove, a rename, or a `sync_dir`), where every +//! subset of the pending operations is a possible disk. +//! +//! Each run cuts at one point and collects the disks the cut could leave. The store must reopen +//! every one of them. Creation builds the file under a temporary name and renames it into place, so +//! it passes. The control builds the file in place, and must fail at some cut. Without that failure +//! the sweep could not see the bug it guards against. + +use std::collections::BTreeMap; +use std::io; +use std::sync::{Arc, Mutex, MutexGuard}; + +use id::event_store::{EventStore, FILE_NAME, Storage}; +use redb::{Database, DatabaseError, StorageBackend, StorageError, TableDefinition}; + +use crate::faultfs::{FaultFs, Plan, Survive, Tear}; + +/// The bytes of every file in a directory, by name: one disk a cut could leave. +type Disk = BTreeMap>; + +/// The storage-call policies each cut is run under. Random and reorder survival keep a subset of +/// the unsynced writes, and tearing lands a prefix of the write in flight. +const POLICIES: [(Survive, Tear); 5] = [ + (Survive::Drop, Tear::Off), + (Survive::Keep, Tear::Off), + (Survive::Random, Tear::Byte), + (Survive::Random, Tear::Sector), + (Survive::Reorder, Tear::Byte), +]; + +/// A change to the directory's entries. Applied in order when a crash state is built. +#[derive(Clone, Debug)] +enum DirOp { + Link(String, FaultFs), + Unlink(String), + Rename(String, String), +} + +#[derive(Debug, Default)] +struct State { + /// The entries as the process sees them. + live: BTreeMap, + /// The entries as of the last `sync_dir`. + durable: BTreeMap, + /// Directory operations since the last `sync_dir`, in order. + pending: Vec, + /// Every file the directory has made, in order. The first one carries the redb plan. + handles: Vec, + plan: Option, + /// Directory operations so far, and the operation before which power is cut. + dir_ops: u64, + cut_before_dir_op: Option, + /// Set by a directory cut. Later operations change nothing. + dead: bool, + /// The crash states taken at a directory cut, before the process could change them. + snapshot: Option>, +} + +/// A simulated directory, cheap to clone. One clone is the store's storage, and the test keeps +/// another to read the crash states. +#[derive(Clone, Debug)] +pub struct SimDir(Arc>); + +impl SimDir { + /// An empty directory. `plan` cuts the power at one storage call of the first file, and + /// `cut_before_dir_op` cuts before the given directory operation (1-based). + pub fn new(plan: Option, cut_before_dir_op: Option) -> Self { + Self(Arc::new(Mutex::new(State { + plan, + cut_before_dir_op, + ..State::default() + }))) + } + + /// A directory holding `disk`, all of it durable. This is the state a reopen starts from. + pub fn from_disk(disk: &Disk) -> Self { + let mut st = State::default(); + for (name, image) in disk { + let handle = FaultFs::new(image.clone(), None, false); + st.live.insert(name.clone(), handle.clone()); + st.durable.insert(name.clone(), handle.clone()); + st.handles.push(handle); + } + Self(Arc::new(Mutex::new(st))) + } + + fn lock(&self) -> MutexGuard<'_, State> { + self.0.lock().expect("sim dir lock") + } + + /// The storage calls the first file has made so far, up to any cut. + pub fn calls(&self) -> u64 { + self.lock() + .handles + .first() + .map_or(0, |handle| handle.trace().len() as u64) + } + + /// The directory operations so far. + pub fn dir_ops(&self) -> u64 { + self.lock().dir_ops + } + + /// Every disk a power cut at this point could leave behind. + pub fn crash_states(&self) -> Vec { + let st = self.lock(); + match &st.snapshot { + Some(snapshot) => snapshot.clone(), + None => snapshot_of(&st), + } + } +} + +/// Whether power is already cut. A redb cut shows up as a cut file. +fn dead(st: &State) -> bool { + st.dead || st.handles.iter().any(FaultFs::cut) +} + +/// Counts one directory operation. Returns false if the operation must not happen, because power +/// is already cut or it is the one the cut lands before. A cut takes its snapshot here, before the +/// process can run any later operation. +fn dir_op(st: &mut State) -> bool { + if dead(st) { + return false; + } + st.dir_ops += 1; + if st.cut_before_dir_op == Some(st.dir_ops) { + st.dead = true; + let snapshot = snapshot_of(st); + st.snapshot = Some(snapshot); + return false; + } + true +} + +fn apply(names: &mut BTreeMap, op: &DirOp) { + match op { + DirOp::Link(name, handle) => { + names.insert(name.clone(), handle.clone()); + } + DirOp::Unlink(name) => { + names.remove(name); + } + DirOp::Rename(from, to) => { + if let Some(handle) = names.remove(from) { + names.insert(to.clone(), handle); + } + } + } +} + +/// What a file holds after a power cut: the image taken at the cut for the file that was cut, +/// and the durable bytes for every other file. +fn image_of(handle: &FaultFs) -> Vec { + if handle.cut() { + handle.disk_image() + } else { + handle.synced_image() + } +} + +/// Every disk a cut could leave now: the durable entries, with each subset of the pending +/// operations applied in order. +fn snapshot_of(st: &State) -> Vec { + (0..1u64 << st.pending.len()) + .map(|keep| { + let mut names = st.durable.clone(); + for (index, op) in st.pending.iter().enumerate() { + if keep & (1 << index) != 0 { + apply(&mut names, op); + } + } + names + .iter() + .map(|(name, handle)| (name.clone(), image_of(handle))) + .collect() + }) + .collect() +} + +fn not_found(name: &str) -> DatabaseError { + DatabaseError::Storage(StorageError::Io(io::Error::new( + io::ErrorKind::NotFound, + format!("{name} is missing"), + ))) +} + +impl Storage for SimDir { + fn create_database(&self, name: &str) -> Result { + let handle = { + let mut st = self.lock(); + if let Some(handle) = st.live.get(name).cloned() { + handle + } else { + let plan = if st.handles.is_empty() { st.plan } else { None }; + let handle = FaultFs::new(Vec::new(), plan, false); + st.handles.push(handle.clone()); + if dir_op(&mut st) { + st.live.insert(name.to_owned(), handle.clone()); + st.pending + .push(DirOp::Link(name.to_owned(), handle.clone())); + } + handle + } + }; + Database::builder().create_with_backend(handle) + } + + fn open_database(&self, name: &str) -> Result { + let handle = self + .lock() + .live + .get(name) + .cloned() + .ok_or_else(|| not_found(name))?; + Database::builder().create_with_backend(handle) + } + + fn exists(&self, name: &str) -> io::Result { + Ok(self.lock().live.contains_key(name)) + } + + fn remove(&self, name: &str) -> io::Result<()> { + let mut st = self.lock(); + if st.live.contains_key(name) && dir_op(&mut st) { + st.live.remove(name); + st.pending.push(DirOp::Unlink(name.to_owned())); + } + Ok(()) + } + + fn rename(&self, from: &str, to: &str) -> io::Result<()> { + let mut st = self.lock(); + if !st.live.contains_key(from) { + return Err(io::Error::from(io::ErrorKind::NotFound)); + } + if dir_op(&mut st) { + if let Some(handle) = st.live.remove(from) { + st.live.insert(to.to_owned(), handle); + } + st.pending + .push(DirOp::Rename(from.to_owned(), to.to_owned())); + } + Ok(()) + } + + fn sync_file(&self, name: &str) -> io::Result<()> { + let handle = { + let st = self.lock(); + if dead(&st) { + return Ok(()); + } + st.live + .get(name) + .cloned() + .ok_or_else(|| io::Error::from(io::ErrorKind::NotFound))? + }; + handle.sync_data() + } + + fn sync_dir(&self) -> io::Result<()> { + let mut st = self.lock(); + if dir_op(&mut st) { + st.durable = st.live.clone(); + st.pending.clear(); + } + Ok(()) + } +} + +/// The creation this sweep runs: the store's own open, which creates the file when it is absent. +fn creation(sim: &SimDir) { + let _ = EventStore::open_with(sim); +} + +/// The control: a file built in place, with one committed write. It has no temporary name and no +/// directory steps, so a cut during its first commit leaves the final name holding a partial file. +fn in_place(sim: &SimDir) { + let Ok(db) = sim.create_database(FILE_NAME) else { + return; + }; + let Ok(txn) = db.begin_write() else { + return; + }; + let table: TableDefinition<'_, &[u8], &[u8]> = TableDefinition::new("meta"); + if let Ok(mut meta) = txn.open_table(table) { + let _ = meta.insert(b"format".as_slice(), b"in place".as_slice()); + } + let _ = txn.commit(); +} + +/// Reopens one crash state with the store and checks what it holds. +fn reopens(disk: &Disk) -> Result<(), String> { + let store = EventStore::open_with(&SimDir::from_disk(disk)) + .map_err(|err| format!("does not open: {err}"))?; + store + .check_invariants() + .map_err(|err| format!("opens, but is inconsistent: {err}")) +} + +/// Runs `scenario` with a cut at every storage call of the first file, under every policy, and a +/// cut before every directory operation. Returns how many crash states were checked, and the +/// ones that `check` rejects. +fn sweep(scenario: fn(&SimDir), check: fn(&Disk) -> Result<(), String>) -> (usize, Vec) { + let clean = SimDir::new(None, None); + scenario(&clean); + let mut runs: Vec<(String, SimDir)> = Vec::new(); + for event in 1..=clean.calls() { + for (index, (survive, tear)) in POLICIES.into_iter().enumerate() { + for sync_completed in [false, true] { + let plan = Plan { + event, + survive, + tear, + sync_completed, + seed: event * 7 + index as u64, + }; + let label = format!( + "call {event} {} {} sync_completed={sync_completed}", + survive.name(), + tear.name() + ); + runs.push((label, SimDir::new(Some(plan), None))); + } + } + } + for op in 1..=clean.dir_ops() { + runs.push(( + format!("before directory operation {op}"), + SimDir::new(None, Some(op)), + )); + } + let mut states = 0; + let mut failures = Vec::new(); + for (label, sim) in runs { + scenario(&sim); + for disk in sim.crash_states() { + states += 1; + if let Err(why) = check(&disk) { + failures.push(format!("{label}: {why}")); + } + } + } + (states, failures) +} + +fn listing(failures: &[String]) -> String { + failures + .iter() + .take(20) + .cloned() + .collect::>() + .join("\n") +} + +#[test] +fn clean_creation_leaves_a_store_that_reopens() { + let sim = SimDir::new(None, None); + creation(&sim); + assert!(sim.calls() > 0, "creation made no storage calls"); + assert_eq!(sim.dir_ops(), 4, "creation is link, sync, rename, sync"); + for disk in sim.crash_states() { + assert!(disk.contains_key(FILE_NAME), "the store file is missing"); + reopens(&disk).unwrap(); + } +} + +#[test] +fn first_creation_reopens_after_every_crash_point() { + let (states, failures) = sweep(creation, reopens); + println!( + "first creation: {states} crash states checked, {} failed", + failures.len() + ); + assert!(states > 0, "the sweep checked no crash states"); + assert!( + failures.is_empty(), + "{} crash states do not reopen:\n{}", + failures.len(), + listing(&failures) + ); +} + +#[test] +fn creation_in_place_control_fails_at_some_crash_point() { + let (states, failures) = sweep(in_place, reopens); + println!( + "control (in-place creation): {states} crash states checked, {} failed", + failures.len() + ); + assert!( + !failures.is_empty(), + "the control never failed: the sweep cannot see a torn first commit" + ); +} From b4e7c1eb35ddbef5e7cf1298ce91987802d649fb Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 11 Oct 2026 19:21:38 -0500 Subject: [PATCH 13/30] feat(rust): ingest with verification, freeze, and waiting [P1.8] EventStore::ingest takes received bytes and decides them in one write transaction. Verification is chain::decode alone: AnyHeader::decode checks the canonical encoding and the signature (verify_strict), and ChainExt checks its own rules. Anything else is refused as Malformed. Outcomes, in order: a stored ID, or a fork proof header, is a Duplicate. A different event at a stored sequence number is a Fork: the chain freezes at the lower of the two sequence numbers and both headers are stored as the proof. A frozen author's events from the fork point on are refused as Frozen. The next sequence number, with a backlink equal to the applied head and every after hash applied, is Accepted. An event ahead of its chain, or with an after hash not applied, is Waiting in the waiting pool (caps from waiting.rs). A refused event changes nothing. A fork unapplies the events from its fork point on. They stay stored, as task 02 says, but they no longer apply, so the waiting pool forgets them (WaitingPool::forget, the one addition to waiting.rs). Events that wait on them wait again, so the applied state does not depend on arrival order. Released events are decided again in order, and their acceptances are reported in Accepted.released. Tests: 16 unit tests, one per outcome and refusal and their combinations, and a reopen. The property test delivers random chains with forks, in three orders with repeats, to in-memory stores, and checks each reaches the state the chains determine (512 cases in debug: 0 failures). The regression list gets 11 seeds, replayed through the same checker. The crash model drives creation and a seven-delivery workload, and checks that every acknowledged delivery survives the reopen (sampled: 58 states, 0 failures). --- pkgs/id/src/event_store/ingest.rs | 823 ++++++++++++++++++ .../{event_store.rs => event_store/mod.rs} | 30 +- pkgs/id/src/waiting.rs | 20 + pkgs/id/tests/common/ingest.rs | 196 +++++ pkgs/id/tests/common/mod.rs | 1 + pkgs/id/tests/crash/store.rs | 304 ++++++- pkgs/id/tests/event_store_properties.rs | 353 ++++++++ pkgs/id/tests/regression_replay.rs | 22 +- pkgs/id/tests/regressions/README.md | 4 +- pkgs/id/tests/regressions/ingest.txt | 28 + 10 files changed, 1728 insertions(+), 53 deletions(-) create mode 100644 pkgs/id/src/event_store/ingest.rs rename pkgs/id/src/{event_store.rs => event_store/mod.rs} (97%) create mode 100644 pkgs/id/tests/common/ingest.rs create mode 100644 pkgs/id/tests/event_store_properties.rs create mode 100644 pkgs/id/tests/regressions/ingest.txt diff --git a/pkgs/id/src/event_store/ingest.rs b/pkgs/id/src/event_store/ingest.rs new file mode 100644 index 0000000000..53d0ca84b8 --- /dev/null +++ b/pkgs/id/src/event_store/ingest.rs @@ -0,0 +1,823 @@ +//! Ingest: how an event received from a peer is verified, decided, and stored. +//! +//! [`EventStore::ingest`] runs one event through these steps: +//! +//! 1. **Verify.** [`chain::decode`] checks the canonical encoding and the signature +//! (through `AnyHeader::decode`, which uses `verify_strict`), then the extension's +//! rules. Anything that fails is refused as [`Refusal::Malformed`]. +//! 2. **Duplicate.** An event whose ID is stored, or is one of the author's fork +//! proof headers, changes nothing. +//! 3. **Fork.** If the author already has an applied event at the event's sequence +//! number, the two conflict. The chain freezes at the lower of the two sequence +//! numbers, and both headers are stored as the proof. +//! 4. **Frozen.** A frozen author's events from the fork point on are refused. +//! 5. **Accept.** The next sequence number, whose backlink is the applied head, is +//! applied once every `after` hash is applied. +//! 6. **Wait.** An event ahead of its chain, or with an `after` hash that is not +//! applied yet, is held in the waiting pool under its caps. When the dependency is +//! applied, the event is released and decided again. +//! +//! Each decision that writes runs in one redb write transaction. A refused event +//! writes nothing, and an accepted one is committed before any event it released is +//! decided. +//! +//! # Applied state and forks +//! +//! The applied prefix of a chain is the events below its next sequence number. A fork +//! moves the next sequence number down to the fork point. Events from the fork point +//! on stay stored, but they are not applied. When an event leaves the applied prefix, +//! the waiting pool forgets it, so events that wait on it wait again. The applied +//! state therefore depends on which events a store has received, not on the order in +//! which it received them. The property tests in `tests/event_store_properties.rs` +//! check that. +//! +//! Two cases still depend on arrival order, and the membership layer must handle +//! both. First, a fork does not undo the events applied on top of a later fork, so an +//! event applied before the fork stays applied. Second, a conflict whose backlink is +//! not the applied head is refused, not held, so a conflict that arrives before the +//! event it conflicts with can go unnoticed. The property tests generate neither: their +//! forks share the original's backlink, and their `after` hashes name only events a +//! fork cannot unapply. + +use std::collections::VecDeque; + +use p2panda_core::{Hash, SeqNum}; +use redb::{ReadableTable, WriteTransaction}; + +use super::{ + CHAINS, Chain, EVENTS, EventStore, FORKS, HASHES, StoreError, corrupt, decode_proof, + decode_stored, position_key, split_position, store_chain, store_event, store_fork, +}; +use crate::chain::{self, Event}; +use crate::waiting::{AuthorKey, WaitRefusal}; + +/// Why an event was refused. A refused event changes nothing. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Refusal { + /// The bytes are not a valid event. The message names the rule that failed: a + /// non-canonical encoding, a bad signature, or an extension that breaks its rules. + Malformed(String), + /// The author has forked at or below this sequence number, so later events are + /// not applied. + Frozen, + /// The sequence number is the next one, but the backlink is not the applied head. + BacklinkMismatch, + /// The author already holds as many waiting events as the caps allow. + WaitingFull, +} + +/// What [`EventStore::ingest`] did with one event. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Ingest { + /// The event is stored and applied. `released` lists the waiting events that + /// became applied because of it, in the order they applied. + Accepted { + /// The event's ID. + id: Hash, + /// The IDs of the waiting events it released, in application order. + released: Vec, + }, + /// The event is already stored, or it is one of the author's fork proof headers. + /// Nothing changed. + Duplicate { + /// The event's ID. + id: Hash, + }, + /// The author signed two different events at a sequence number that exists. The + /// chain froze at the lower of the two sequence numbers, and both headers are + /// stored as the fork proof. + Fork { + /// The author. + author: AuthorKey, + /// The fork point: the lowest sequence number where the author conflicts. + seq: SeqNum, + }, + /// The event waits for a dependency. It is held in memory and not stored. Sync + /// sends it again if it is lost. + Waiting { + /// The event's ID. + id: Hash, + }, + /// The event was refused. Nothing changed. + Refused(Refusal), +} + +/// What the store decides for one event, before waiting. +#[derive(Debug, PartialEq, Eq)] +enum Decision { + /// Stored and applied. + Accept, + /// Already stored, or a proof header. Nothing written. + Duplicate, + /// A different event at `seq`, below the applied prefix, which ended at `applied`. + /// Written as the fork. + Fork { seq: SeqNum, applied: SeqNum }, + /// Waits for these dependencies. Nothing written. + Wait(Vec), + /// Refused. Nothing written. + Refuse(Refusal), +} + +impl EventStore { + /// Verifies one received event and applies what it allows. + /// + /// `now_ms` is the clock the waiting caps use. It is a parameter so tests can + /// run on a fake clock. + /// + /// # Errors + /// + /// Returns a redb or corruption error. A refusal is not an error: it comes back + /// as [`Ingest::Refused`]. + pub fn ingest(&mut self, bytes: &[u8], now_ms: u64) -> Result { + let event = match chain::decode(bytes) { + Ok(event) => event, + Err(err) => return Ok(Ingest::Refused(Refusal::Malformed(err.to_string()))), + }; + let id = event.id; + let author = *event.header.verifying_key.as_bytes(); + match self.decide(&event)? { + Decision::Accept => { + let arrived = self.waiting.arrived(id, now_ms); + let released = self.drain(arrived.into(), now_ms)?; + Ok(Ingest::Accepted { id, released }) + } + Decision::Duplicate => Ok(Ingest::Duplicate { id }), + Decision::Fork { seq, applied } => { + self.forget_unapplied(&author, seq, applied)?; + Ok(Ingest::Fork { author, seq }) + } + Decision::Wait(deps) => { + let outcome = match self.waiting.insert(author, id, deps, event, now_ms) { + Ok(()) => Ingest::Waiting { id }, + Err(WaitRefusal::AuthorFull) => Ingest::Refused(Refusal::WaitingFull), + }; + self.drain(VecDeque::new(), now_ms)?; + Ok(outcome) + } + Decision::Refuse(refusal) => Ok(Ingest::Refused(refusal)), + } + } + + /// Drops the waiting events that have reached the age cap at `now_ms`. Returns + /// how many were dropped. + pub fn expire_waiting(&mut self, now_ms: u64) -> usize { + self.waiting.expire(now_ms).len() + } + + /// The number of events held waiting, across all authors. + pub fn waiting_len(&self) -> usize { + self.waiting.len() + } + + /// The number of events `author` has waiting. + pub fn waiting_count(&self, author: &AuthorKey) -> usize { + self.waiting.waiting_count(*author) + } + + /// Decides `event` in one write transaction. A decision that writes nothing aborts + /// the transaction. + fn decide(&self, event: &Event) -> Result { + let txn = self.db.begin_write()?; + let decision = decide_in(&txn, event)?; + if matches!(decision, Decision::Accept | Decision::Fork { .. }) { + txn.commit()?; + } + Ok(decision) + } + + /// Applies the events in `queue`, then each waiting event they release, until + /// nothing more applies. Returns the IDs of the waiting events applied, in order. + fn drain(&mut self, mut queue: VecDeque, now_ms: u64) -> Result, StoreError> { + let mut applied = Vec::new(); + queue.extend(self.waiting.take_ready()); + while let Some(event) = queue.pop_front() { + let id = event.id; + let author = *event.header.verifying_key.as_bytes(); + match self.decide(&event)? { + Decision::Accept => { + applied.push(id); + queue.extend(self.waiting.arrived(id, now_ms)); + } + Decision::Fork { + seq, + applied: before, + } => self.forget_unapplied(&author, seq, before)?, + Decision::Wait(deps) => { + // A refused insert drops the event, as an event past the cap is dropped. + let _ = self.waiting.insert(author, id, deps, event, now_ms); + } + Decision::Duplicate | Decision::Refuse(_) => {} + } + queue.extend(self.waiting.take_ready()); + } + Ok(applied) + } + + /// Tells the waiting pool that the events from `from` up to `applied` are no longer + /// applied, so events that wait on them wait again. + fn forget_unapplied( + &mut self, + author: &AuthorKey, + from: SeqNum, + applied: SeqNum, + ) -> Result<(), StoreError> { + for seq in from..applied { + if let Some(event) = self.event(author, seq)? { + self.waiting.forget(&event.id); + } + } + Ok(()) + } +} + +/// Decides `event` inside `txn`, and writes what the decision needs. +fn decide_in(txn: &WriteTransaction, event: &Event) -> Result { + let author = *event.header.verifying_key.as_bytes(); + let seq = event.header.seq_num; + if is_stored(txn, &event.id)? || is_proof_header(txn, &author, &event.id)? { + return Ok(Decision::Duplicate); + } + let chain = read_chain(txn, &author)?; + if seq < chain.next_seq { + let stored = stored_event(txn, &author, seq)?; + let head = match seq.checked_sub(1) { + Some(before) => Some(stored_event(txn, &author, before)?.id), + None => None, + }; + store_fork(txn, &author, seq, &stored, event)?; + store_chain( + txn, + &author, + Chain { + next_seq: seq, + head, + frozen: true, + }, + )?; + return Ok(Decision::Fork { + seq, + applied: chain.next_seq, + }); + } + if chain.frozen { + return Ok(Decision::Refuse(Refusal::Frozen)); + } + let after = &event.header.extensions.after; + if seq == chain.next_seq { + if seq > 0 && event.header.backlink != chain.head { + return Ok(Decision::Refuse(Refusal::BacklinkMismatch)); + } + let missing = unapplied(txn, after)?; + if !missing.is_empty() { + return Ok(Decision::Wait(missing)); + } + store_event(txn, event)?; + let next_seq = seq + .checked_add(1) + .ok_or_else(|| corrupt("a sequence number overflows"))?; + store_chain( + txn, + &author, + Chain { + next_seq, + head: Some(event.id), + frozen: false, + }, + )?; + return Ok(Decision::Accept); + } + // Ahead of the chain: the backlink is the event that must come first. + let mut deps = unapplied(txn, after)?; + deps.extend(event.header.backlink); + Ok(Decision::Wait(deps)) +} + +fn is_stored(txn: &WriteTransaction, id: &Hash) -> Result { + let hashes = txn.open_table(HASHES)?; + let found = hashes.get(id.as_bytes().as_slice())?.is_some(); + Ok(found) +} + +fn is_proof_header( + txn: &WriteTransaction, + author: &AuthorKey, + id: &Hash, +) -> Result { + let forks = txn.open_table(FORKS)?; + let Some(row) = forks.get(author.as_slice())? else { + return Ok(false); + }; + let proof = decode_proof(row.value())?; + Ok(proof.first.id == *id || proof.second.id == *id) +} + +fn read_chain(txn: &WriteTransaction, author: &AuthorKey) -> Result { + let chains = txn.open_table(CHAINS)?; + let row = chains.get(author.as_slice())?; + match row { + Some(row) => Chain::decode(row.value()), + None => Ok(Chain::default()), + } +} + +fn stored_event( + txn: &WriteTransaction, + author: &AuthorKey, + seq: SeqNum, +) -> Result { + let events = txn.open_table(EVENTS)?; + let row = events.get(position_key(author, seq).as_slice())?; + match row { + Some(row) => decode_stored(row.value()), + None => Err(corrupt("an applied sequence number has no stored event")), + } +} + +/// The `after` hashes that are not applied yet. +fn unapplied(txn: &WriteTransaction, after: &[Hash]) -> Result, StoreError> { + let mut missing = Vec::new(); + for hash in after { + if !is_applied(txn, hash)? { + missing.push(*hash); + } + } + Ok(missing) +} + +/// Whether the event with this ID is applied: stored, at a sequence number below its +/// author's applied prefix. +fn is_applied(txn: &WriteTransaction, hash: &Hash) -> Result { + let hashes = txn.open_table(HASHES)?; + let position = hashes + .get(hash.as_bytes().as_slice())? + .map(|found| found.value().to_vec()); + let Some(position) = position else { + return Ok(false); + }; + let (author, seq) = split_position(&position)?; + let chains = txn.open_table(CHAINS)?; + let row = chains.get(author.as_slice())?; + match row { + Some(row) => Ok(Chain::decode(row.value())?.next_seq > seq), + None => Ok(false), + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use super::*; + use crate::chain::{ChainExt, sign}; + use crate::waiting::WaitingLimits; + use p2panda_core::SigningKey; + + const WEEK_MS: u64 = 7 * 24 * 60 * 60 * 1_000; + + fn key(n: u8) -> SigningKey { + SigningKey::from_bytes(&[n; 32]) + } + + fn author(key: &SigningKey) -> AuthorKey { + *key.verifying_key().as_bytes() + } + + /// A signed event: its sequence number, backlink, frontier, and kind. + fn event( + key: &SigningKey, + seq: SeqNum, + backlink: Option, + after: Vec, + kind: &str, + ) -> Event { + let ext = ChainExt { + kind: kind.to_owned(), + group: None, + after, + }; + sign(key, seq, backlink, None, ext).unwrap() + } + + /// The first `count` events of `key`'s chain, each naming the one before. + fn chain_of(key: &SigningKey, count: SeqNum) -> Vec { + let mut events: Vec = Vec::new(); + for seq in 0..count { + let backlink = events.last().map(|event| event.id); + events.push(event(key, seq, backlink, Vec::new(), "message")); + } + events + } + + fn open() -> (tempfile::TempDir, EventStore) { + let dir = tempfile::tempdir().unwrap(); + let store = EventStore::open(dir.path()).unwrap(); + (dir, store) + } + + fn ingest(store: &mut EventStore, event: &Event) -> Ingest { + store.ingest(&event.bytes, 0).unwrap() + } + + /// Ingests every event in order, and checks each one was accepted. + fn ingest_all(store: &mut EventStore, events: &[Event]) { + for event in events { + assert_eq!( + ingest(store, event), + Ingest::Accepted { + id: event.id, + released: vec![], + } + ); + } + } + + fn sorted(a: &Hash, b: &Hash) -> [Hash; 2] { + let mut ids = [*a, *b]; + ids.sort_by(|x, y| x.as_bytes().cmp(y.as_bytes())); + ids + } + + #[test] + fn test_a_valid_chain_is_accepted_in_order() { + let (_dir, mut store) = open(); + let signer = key(1); + let events = chain_of(&signer, 3); + ingest_all(&mut store, &events); + let chain = store.chain(&author(&signer)).unwrap().unwrap(); + assert_eq!( + chain, + Chain { + next_seq: 3, + head: Some(events[2].id), + frozen: false, + } + ); + store.check_invariants().unwrap(); + } + + #[test] + fn test_a_duplicate_is_idempotent_and_changes_nothing() { + let (_dir, mut store) = open(); + let signer = key(2); + let events = chain_of(&signer, 2); + ingest_all(&mut store, &events); + let before = store.chain(&author(&signer)).unwrap(); + assert_eq!( + ingest(&mut store, &events[0]), + Ingest::Duplicate { id: events[0].id } + ); + assert_eq!( + ingest(&mut store, &events[1]), + Ingest::Duplicate { id: events[1].id } + ); + assert_eq!(store.chain(&author(&signer)).unwrap(), before); + store.check_invariants().unwrap(); + } + + #[test] + fn test_a_fork_freezes_the_chain_and_stores_both_headers() { + let (_dir, mut store) = open(); + let signer = key(3); + let who = author(&signer); + let events = chain_of(&signer, 2); + ingest_all(&mut store, &events); + let rival = event(&signer, 1, Some(events[0].id), Vec::new(), "rival"); + assert_eq!( + ingest(&mut store, &rival), + Ingest::Fork { + author: who, + seq: 1 + } + ); + assert_eq!( + store.chain(&who).unwrap(), + Some(Chain { + next_seq: 1, + head: Some(events[0].id), + frozen: true, + }) + ); + let proof = store.fork_proof(&who).unwrap().expect("a proof is stored"); + assert_eq!(proof.seq, 1); + assert_eq!( + [proof.first.id, proof.second.id], + sorted(&events[1].id, &rival.id) + ); + // The event that was applied stays stored. It just no longer applies. + assert_eq!(store.event(&who, 1).unwrap(), Some(events[1].clone())); + store.check_invariants().unwrap(); + } + + #[test] + fn test_a_frozen_chain_refuses_its_later_events_and_changes_nothing() { + let (_dir, mut store) = open(); + let signer = key(4); + let who = author(&signer); + let events = chain_of(&signer, 3); + ingest_all(&mut store, &events[..2]); + let rival = event(&signer, 1, Some(events[0].id), Vec::new(), "rival"); + assert!(matches!( + ingest(&mut store, &rival), + Ingest::Fork { seq: 1, .. } + )); + let before = store.chain(&who).unwrap(); + assert_eq!( + ingest(&mut store, &events[2]), + Ingest::Refused(Refusal::Frozen) + ); + assert!(store.event(&who, 2).unwrap().is_none()); + assert_eq!(store.chain(&who).unwrap(), before); + store.check_invariants().unwrap(); + } + + #[test] + fn test_a_fork_at_sequence_zero_leaves_no_applied_head() { + let (_dir, mut store) = open(); + let signer = key(5); + let who = author(&signer); + let first = event(&signer, 0, None, Vec::new(), "first"); + let rival = event(&signer, 0, None, Vec::new(), "rival"); + ingest_all(&mut store, std::slice::from_ref(&first)); + assert_eq!( + ingest(&mut store, &rival), + Ingest::Fork { + author: who, + seq: 0 + } + ); + assert_eq!( + store.chain(&who).unwrap(), + Some(Chain { + next_seq: 0, + head: None, + frozen: true, + }) + ); + assert_eq!(store.fork_proof(&who).unwrap().unwrap().seq, 0); + store.check_invariants().unwrap(); + } + + #[test] + fn test_a_conflict_below_the_fork_point_moves_the_fork_point_down() { + let (_dir, mut store) = open(); + let signer = key(6); + let who = author(&signer); + let events = chain_of(&signer, 4); + ingest_all(&mut store, &events); + let high = event(&signer, 2, Some(events[1].id), Vec::new(), "high"); + assert_eq!( + ingest(&mut store, &high), + Ingest::Fork { + author: who, + seq: 2 + } + ); + let low = event(&signer, 1, Some(events[0].id), Vec::new(), "low"); + assert_eq!( + ingest(&mut store, &low), + Ingest::Fork { + author: who, + seq: 1 + } + ); + assert_eq!( + store.chain(&who).unwrap(), + Some(Chain { + next_seq: 1, + head: Some(events[0].id), + frozen: true, + }) + ); + let proof = store.fork_proof(&who).unwrap().unwrap(); + assert_eq!(proof.seq, 1); + assert_eq!( + [proof.first.id, proof.second.id], + sorted(&events[1].id, &low.id) + ); + store.check_invariants().unwrap(); + } + + #[test] + fn test_the_fork_state_does_not_depend_on_which_header_arrived_first() { + let signer = key(7); + let who = author(&signer); + let events = chain_of(&signer, 2); + let rival = event(&signer, 1, Some(events[0].id), Vec::new(), "rival"); + let (_first_dir, mut first) = open(); + ingest_all(&mut first, &events); + ingest(&mut first, &rival); + let (_second_dir, mut second) = open(); + ingest_all(&mut second, &events[..1]); + ingest(&mut second, &rival); + ingest(&mut second, &events[1]); + assert_eq!(first.chain(&who).unwrap(), second.chain(&who).unwrap()); + assert_eq!( + first.fork_proof(&who).unwrap(), + second.fork_proof(&who).unwrap() + ); + } + + #[test] + fn test_an_event_ahead_of_the_chain_waits_and_its_predecessor_releases_it() { + let (_dir, mut store) = open(); + let signer = key(8); + let who = author(&signer); + let events = chain_of(&signer, 3); + assert_eq!( + ingest(&mut store, &events[2]), + Ingest::Waiting { id: events[2].id } + ); + assert!( + store.event(&who, 2).unwrap().is_none(), + "a waiting event is not stored" + ); + assert_eq!(store.waiting_len(), 1); + assert_eq!( + ingest(&mut store, &events[0]), + Ingest::Accepted { + id: events[0].id, + released: vec![], + } + ); + assert_eq!( + ingest(&mut store, &events[1]), + Ingest::Accepted { + id: events[1].id, + released: vec![events[2].id], + } + ); + assert_eq!(store.chain(&who).unwrap().unwrap().next_seq, 3); + assert_eq!(store.waiting_len(), 0); + store.check_invariants().unwrap(); + } + + #[test] + fn test_an_event_waiting_for_an_after_hash_is_released_by_that_event() { + let (_dir, mut store) = open(); + let x = key(9); + let y = key(10); + let x0 = event(&x, 0, None, Vec::new(), "x"); + let y0 = event(&y, 0, None, vec![x0.id], "y"); + assert_eq!(ingest(&mut store, &y0), Ingest::Waiting { id: y0.id }); + assert_eq!( + ingest(&mut store, &x0), + Ingest::Accepted { + id: x0.id, + released: vec![y0.id], + } + ); + assert_eq!(store.chain(&author(&y)).unwrap().unwrap().next_seq, 1); + store.check_invariants().unwrap(); + } + + #[test] + fn test_an_after_hash_naming_an_unapplied_event_keeps_waiting() { + let (_dir, mut store) = open(); + let x = key(11); + let y = key(12); + let events = chain_of(&x, 2); + ingest_all(&mut store, &events); + let rival = event(&x, 1, Some(events[0].id), Vec::new(), "rival"); + ingest(&mut store, &rival); + // events[1] is stored, but the fork took it out of the applied prefix. + let y0 = event(&y, 0, None, vec![events[1].id], "y"); + assert_eq!(ingest(&mut store, &y0), Ingest::Waiting { id: y0.id }); + assert!(store.chain(&author(&y)).unwrap().is_none()); + } + + #[test] + fn test_a_backlink_that_is_not_the_applied_head_is_refused() { + let (_dir, mut store) = open(); + let signer = key(13); + let who = author(&signer); + let events = chain_of(&signer, 1); + ingest_all(&mut store, &events); + let stray = event( + &signer, + 1, + Some(Hash::digest(b"not the head")), + Vec::new(), + "stray", + ); + assert_eq!( + ingest(&mut store, &stray), + Ingest::Refused(Refusal::BacklinkMismatch) + ); + assert!(store.event(&who, 1).unwrap().is_none()); + assert_eq!(store.chain(&who).unwrap().unwrap().next_seq, 1); + store.check_invariants().unwrap(); + } + + #[test] + fn test_bytes_that_do_not_verify_are_refused_and_change_nothing() { + let (_dir, mut store) = open(); + let signer = key(14); + let events = chain_of(&signer, 1); + assert!(matches!( + store.ingest(b"not cbor", 0).unwrap(), + Ingest::Refused(Refusal::Malformed(_)) + )); + // The signature is 64 bytes after the 0x58 0x40 header at offset 37. Flip one. + let mut forged = events[0].bytes.clone(); + forged[48] ^= 0x01; + let outcome = store.ingest(&forged, 0).unwrap(); + assert!( + matches!(&outcome, Ingest::Refused(Refusal::Malformed(message)) if message.contains("signature")), + "a forged signature was not refused: {outcome:?}" + ); + assert!(store.chain(&author(&signer)).unwrap().is_none()); + store.check_invariants().unwrap(); + } + + #[test] + fn test_waiting_events_past_the_author_cap_are_refused() { + let (_dir, store) = open(); + let mut store = store.with_waiting_limits(WaitingLimits::new(2, WEEK_MS)); + let signer = key(15); + let who = author(&signer); + let events = chain_of(&signer, 5); + assert_eq!( + ingest(&mut store, &events[2]), + Ingest::Waiting { id: events[2].id } + ); + assert_eq!( + ingest(&mut store, &events[3]), + Ingest::Waiting { id: events[3].id } + ); + assert_eq!( + ingest(&mut store, &events[4]), + Ingest::Refused(Refusal::WaitingFull) + ); + assert_eq!(store.waiting_count(&who), 2); + assert!(store.event(&who, 4).unwrap().is_none()); + } + + #[test] + fn test_a_waiting_event_expires_and_is_not_released_by_its_dependency() { + let (_dir, store) = open(); + let mut store = store.with_waiting_limits(WaitingLimits::new(256, 1_000)); + let signer = key(16); + let events = chain_of(&signer, 2); + store.ingest(&events[1].bytes, 0).unwrap(); + assert_eq!(store.expire_waiting(1_000), 1); + assert_eq!( + store.ingest(&events[0].bytes, 1_000).unwrap(), + Ingest::Accepted { + id: events[0].id, + released: vec![], + } + ); + assert!(store.event(&author(&signer), 1).unwrap().is_none()); + assert_eq!(store.waiting_len(), 0); + } + + #[test] + fn test_group_members_follow_applied_events_only() { + let (_dir, mut store) = open(); + let signer = key(17); + let who = author(&signer); + let group = Hash::digest(b"group"); + let grouped = |seq: SeqNum, backlink: Option| { + let ext = ChainExt { + kind: "message".to_owned(), + group: Some(group), + after: Vec::new(), + }; + sign(&signer, seq, backlink, None, ext).unwrap() + }; + let first = grouped(0, None); + let second = grouped(1, Some(first.id)); + ingest(&mut store, &second); + assert!(store.group_members(&group).unwrap().is_empty()); + ingest(&mut store, &first); + assert_eq!( + store.group_members(&group).unwrap(), + vec![(who, 0), (who, 1)] + ); + store.check_invariants().unwrap(); + } + + #[test] + fn test_ingested_state_survives_a_reopen() { + let dir = tempfile::tempdir().unwrap(); + let signer = key(18); + let who = author(&signer); + let events = chain_of(&signer, 2); + let rival = event(&signer, 1, Some(events[0].id), Vec::new(), "rival"); + { + let mut store = EventStore::open(dir.path()).unwrap(); + ingest_all(&mut store, &events); + ingest(&mut store, &rival); + } + let store = EventStore::open(dir.path()).unwrap(); + assert_eq!( + store.chain(&who).unwrap(), + Some(Chain { + next_seq: 1, + head: Some(events[0].id), + frozen: true, + }) + ); + assert!(store.fork_proof(&who).unwrap().is_some()); + store.check_invariants().unwrap(); + } +} diff --git a/pkgs/id/src/event_store.rs b/pkgs/id/src/event_store/mod.rs similarity index 97% rename from pkgs/id/src/event_store.rs rename to pkgs/id/src/event_store/mod.rs index 0a2d04bdb2..b9bfb4994c 100644 --- a/pkgs/id/src/event_store.rs +++ b/pkgs/id/src/event_store/mod.rs @@ -43,7 +43,11 @@ use redb::{ }; use crate::chain::{self, Event}; -use crate::waiting::AuthorKey; + +mod ingest; + +use crate::waiting::{AuthorKey, WaitingLimits, WaitingPool}; +pub use ingest::{Ingest, Refusal}; /// The store's file name in its directory. pub const FILE_NAME: &str = "events.redb"; @@ -226,7 +230,7 @@ impl Storage for FileStorage { } /// The applied prefix of one author's chain, as the `chains` table holds it. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct Chain { /// The sequence number the next applied event takes: the number of applied /// events. Zero for an author with none. @@ -239,7 +243,6 @@ pub struct Chain { } impl Chain { - #[allow(dead_code, reason = "the ingest path (P1.8) writes through this")] fn encode(self) -> [u8; CHAIN_LEN] { let mut row = [0u8; CHAIN_LEN]; row[..8].copy_from_slice(&u64::from(self.next_seq).to_be_bytes()); @@ -289,6 +292,8 @@ pub struct ForkProof { #[derive(Debug)] pub struct EventStore { db: Database, + /// Events that wait for a dependency. They are held in memory, not stored. + waiting: WaitingPool, } impl EventStore { @@ -316,7 +321,18 @@ impl EventStore { create_fresh(storage)? }; verify_schema(&db)?; - Ok(Self { db }) + Ok(Self { + db, + waiting: WaitingPool::new(WaitingLimits::default()), + }) + } + + /// Sets the caps on waiting events: how many one author may hold, and how long + /// one may wait. The pool starts empty, so set the caps before ingesting. + #[must_use] + pub fn with_waiting_limits(mut self, limits: WaitingLimits) -> Self { + self.waiting = WaitingPool::new(limits); + self } /// Runs `op` in one write transaction. The transaction commits if `op` @@ -325,7 +341,7 @@ impl EventStore { /// # Errors /// /// Returns `op`'s error, or a redb error from the commit. - #[allow(dead_code, reason = "the ingest path (P1.8) writes through this")] + #[cfg(test)] pub(crate) fn write( &self, op: impl FnOnce(&WriteTransaction) -> Result, @@ -619,7 +635,6 @@ fn decode_stored(bytes: &[u8]) -> Result { /// Encodes a fork proof: the sequence number, the length of the first header, /// then the two headers, ordered by ID. -#[allow(dead_code, reason = "the ingest path (P1.8) writes through this")] pub(crate) fn encode_proof(seq: SeqNum, a: &Event, b: &Event) -> Result, StoreError> { let (first, second) = if a.id.as_bytes() <= b.id.as_bytes() { (a, b) @@ -659,7 +674,6 @@ fn decode_proof(bytes: &[u8]) -> Result { /// Stores an accepted event at its position, and indexes it by ID and group. /// A position that is already stored is refused, inside the same transaction. -#[allow(dead_code, reason = "the ingest path (P1.8) writes through this")] pub(crate) fn store_event(txn: &WriteTransaction, event: &Event) -> Result<(), StoreError> { let author = *event.header.verifying_key.as_bytes(); let seq = event.header.seq_num; @@ -681,7 +695,6 @@ pub(crate) fn store_event(txn: &WriteTransaction, event: &Event) -> Result<(), S } /// Writes an author's chain row. -#[allow(dead_code, reason = "the ingest path (P1.8) writes through this")] pub(crate) fn store_chain( txn: &WriteTransaction, author: &AuthorKey, @@ -693,7 +706,6 @@ pub(crate) fn store_chain( } /// Writes an author's fork proof, replacing any earlier one. -#[allow(dead_code, reason = "the ingest path (P1.8) writes through this")] pub(crate) fn store_fork( txn: &WriteTransaction, author: &AuthorKey, diff --git a/pkgs/id/src/waiting.rs b/pkgs/id/src/waiting.rs index 939c5c7e81..705ca397a8 100644 --- a/pkgs/id/src/waiting.rs +++ b/pkgs/id/src/waiting.rs @@ -251,6 +251,13 @@ where released } + /// Forget that `key` arrived, for a key that has stopped counting as applied. + /// Events that wait on it from now on wait again. Events already released by it + /// are not affected. + pub fn forget(&mut self, key: &K) { + self.arrived.remove(key); + } + /// Drop every held event that has waited `max_age_ms` by `now_ms`, and return /// them as `(author, event)` in arrival order, so the caller can log them. /// @@ -504,6 +511,19 @@ mod tests { assert!(pool.arrived(10, 0).is_empty()); } + #[test] + fn test_a_forgotten_key_holds_its_dependents_again() { + let mut pool = pool(); + pool.arrived(10, 0); + pool.forget(&10); + pool.insert(author(1), 1, [10], "held", 0).unwrap(); + assert!( + pool.take_ready().is_empty(), + "the key no longer counts as arrived" + ); + assert_eq!(pool.arrived(10, 0), vec!["held"]); + } + #[test] fn test_counts_stay_exact_across_insert_release_and_expiry() { let mut pool = pool(); diff --git a/pkgs/id/tests/common/ingest.rs b/pkgs/id/tests/common/ingest.rs new file mode 100644 index 0000000000..1038e07ccd --- /dev/null +++ b/pkgs/id/tests/common/ingest.rs @@ -0,0 +1,196 @@ +//! The ingest contract, shared by the property tests and the regression replay: the +//! same events, in any order and with any repeats, give a store the same applied state. +//! The checks take bytes, so a case found by a property run can be replayed unchanged. + +use std::collections::BTreeMap; +use std::io; +use std::sync::{Arc, Mutex}; + +use id::chain::decode; +use id::event_store::{Chain, EventStore, Storage}; +use id::waiting::AuthorKey; +use p2panda_core::{Hash, SeqNum}; +use redb::backends::InMemoryBackend; +use redb::{Database, DatabaseError, StorageBackend, StorageError}; + +/// The applied state of a set of authors, as a store reports it. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Canonical { + /// Each author's applied chain. + pub chains: BTreeMap, + /// Each author's fork proof: the fork point, and the two IDs in order. + pub proofs: BTreeMap, +} + +/// Reads the applied state of `authors` from `store`. +/// +/// # Errors +/// +/// Returns the store's error as text, if a read fails. +pub fn canonical(store: &EventStore, authors: &[AuthorKey]) -> Result { + let mut state = Canonical::default(); + for author in authors { + if let Some(chain) = store.chain(author).map_err(|err| err.to_string())? { + state.chains.insert(*author, chain); + } + if let Some(proof) = store.fork_proof(author).map_err(|err| err.to_string())? { + state + .proofs + .insert(*author, (proof.seq, proof.first.id, proof.second.id)); + } + } + Ok(state) +} + +/// The authors of the events in `order`, sorted. Bytes that do not decode have no +/// author, and are skipped. +pub fn authors_of(order: &[Vec]) -> Vec { + let mut authors: Vec = order + .iter() + .filter_map(|bytes| decode(bytes).ok()) + .map(|event| *event.header.verifying_key.as_bytes()) + .collect(); + authors.sort_unstable(); + authors.dedup(); + authors +} + +/// A store directory in memory. Each file is a redb in-memory backend, so no write is +/// synced to a disk. The store's creation path runs unchanged, through the same +/// [`Storage`] calls the disk makes. +#[derive(Debug, Default)] +pub struct MemStorage { + files: Mutex>>, +} + +/// One in-memory file, shared by the databases that open it. +#[derive(Debug)] +struct Shared(Arc); + +impl StorageBackend for Shared { + fn len(&self) -> Result { + self.0.len() + } + + fn read(&self, offset: u64, out: &mut [u8]) -> Result<(), io::Error> { + self.0.read(offset, out) + } + + fn set_len(&self, len: u64) -> Result<(), io::Error> { + self.0.set_len(len) + } + + fn sync_data(&self) -> Result<(), io::Error> { + self.0.sync_data() + } + + fn write(&self, offset: u64, data: &[u8]) -> Result<(), io::Error> { + self.0.write(offset, data) + } +} + +impl MemStorage { + fn files(&self) -> std::sync::MutexGuard<'_, BTreeMap>> { + self.files.lock().expect("memory directory lock") + } +} + +impl Storage for MemStorage { + fn create_database(&self, name: &str) -> Result { + let file = Arc::clone( + self.files() + .entry(name.to_owned()) + .or_insert_with(|| Arc::new(InMemoryBackend::new())), + ); + Database::builder().create_with_backend(Shared(file)) + } + + fn open_database(&self, name: &str) -> Result { + let file = self.files().get(name).cloned().ok_or_else(|| { + DatabaseError::Storage(StorageError::Io(io::Error::from(io::ErrorKind::NotFound))) + })?; + Database::builder().create_with_backend(Shared(file)) + } + + fn exists(&self, name: &str) -> io::Result { + Ok(self.files().contains_key(name)) + } + + fn remove(&self, name: &str) -> io::Result<()> { + self.files().remove(name); + Ok(()) + } + + fn rename(&self, from: &str, to: &str) -> io::Result<()> { + let mut files = self.files(); + let file = files + .remove(from) + .ok_or_else(|| io::Error::from(io::ErrorKind::NotFound))?; + files.insert(to.to_owned(), file); + Ok(()) + } + + fn sync_file(&self, _name: &str) -> io::Result<()> { + Ok(()) + } + + fn sync_dir(&self) -> io::Result<()> { + Ok(()) + } +} + +/// Delivers `order` to a fresh in-memory store on a fixed clock, and returns the applied +/// state of `authors`. The store's invariants must hold after the last delivery. The +/// authors are passed in, not decoded from `order`, because every decode verifies a +/// signature, and a debug build spends most of its time there. +/// +/// # Errors +/// +/// Describes the first delivery or invariant that fails. +pub fn deliver(order: &[Vec], authors: &[AuthorKey]) -> Result { + let mut store = EventStore::open_with(&MemStorage::default()).map_err(|err| err.to_string())?; + for bytes in order { + store + .ingest(bytes, 0) + .map_err(|err| format!("ingest failed: {err}"))?; + } + store + .check_invariants() + .map_err(|err| format!("invariants after the deliveries: {err}"))?; + canonical(&store, authors) +} + +/// Checks that delivery order and repeats do not change the applied state. Each +/// event is delivered twice in a row, once in the given order, once reversed, and +/// once rotated by half the length. +/// +/// # Errors +/// +/// Describes the first order that disagrees with the others, or the first failure. +pub fn check_order_independence(events: &[Vec]) -> Result<(), String> { + let twice = |order: &[Vec]| -> Vec> { + order + .iter() + .flat_map(|bytes| [bytes.clone(), bytes.clone()]) + .collect() + }; + let forward = events.to_vec(); + let mut reversed = events.to_vec(); + reversed.reverse(); + let mut rotated = events.to_vec(); + if !rotated.is_empty() { + let half = rotated.len() / 2; + rotated.rotate_left(half); + } + let authors = authors_of(events); + let first = deliver(&twice(&forward), &authors)?; + for (name, order) in [("reversed", &reversed), ("rotated", &rotated)] { + let other = deliver(&twice(order), &authors)?; + if other != first { + return Err(format!( + "the {name} order reaches {other:?}, but the given order reaches {first:?}" + )); + } + } + Ok(()) +} diff --git a/pkgs/id/tests/common/mod.rs b/pkgs/id/tests/common/mod.rs index 7c98f89e29..085c5b1182 100644 --- a/pkgs/id/tests/common/mod.rs +++ b/pkgs/id/tests/common/mod.rs @@ -10,6 +10,7 @@ #![allow(dead_code)] // each test crate uses a different part of this module pub mod chain; +pub mod ingest; use std::cmp::Ordering; diff --git a/pkgs/id/tests/crash/store.rs b/pkgs/id/tests/crash/store.rs index 67442862d1..ae314b2270 100644 --- a/pkgs/id/tests/crash/store.rs +++ b/pkgs/id/tests/crash/store.rs @@ -14,11 +14,13 @@ //! it passes. The control builds the file in place, and must fail at some cut. Without that failure //! the sweep could not see the bug it guards against. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, HashMap}; use std::io; use std::sync::{Arc, Mutex, MutexGuard}; -use id::event_store::{EventStore, FILE_NAME, Storage}; +use id::chain::{self, ChainExt, sign}; +use id::event_store::{EventStore, FILE_NAME, Ingest, Refusal, Storage}; +use p2panda_core::{Hash, SigningKey}; use redb::{Database, DatabaseError, StorageBackend, StorageError, TableDefinition}; use crate::faultfs::{FaultFs, Plan, Survive, Tear}; @@ -96,6 +98,11 @@ impl SimDir { self.0.lock().expect("sim dir lock") } + /// Whether power has been cut. Every later call changes nothing. + pub fn cut_landed(&self) -> bool { + dead(&self.lock()) + } + /// The storage calls the first file has made so far, up to any cut. pub fn calls(&self) -> u64 { self.lock() @@ -276,45 +283,21 @@ impl Storage for SimDir { } } -/// The creation this sweep runs: the store's own open, which creates the file when it is absent. -fn creation(sim: &SimDir) { - let _ = EventStore::open_with(sim); -} - -/// The control: a file built in place, with one committed write. It has no temporary name and no -/// directory steps, so a cut during its first commit leaves the final name holding a partial file. -fn in_place(sim: &SimDir) { - let Ok(db) = sim.create_database(FILE_NAME) else { - return; - }; - let Ok(txn) = db.begin_write() else { - return; - }; - let table: TableDefinition<'_, &[u8], &[u8]> = TableDefinition::new("meta"); - if let Ok(mut meta) = txn.open_table(table) { - let _ = meta.insert(b"format".as_slice(), b"in place".as_slice()); - } - let _ = txn.commit(); -} - -/// Reopens one crash state with the store and checks what it holds. -fn reopens(disk: &Disk) -> Result<(), String> { - let store = EventStore::open_with(&SimDir::from_disk(disk)) - .map_err(|err| format!("does not open: {err}"))?; - store - .check_invariants() - .map_err(|err| format!("opens, but is inconsistent: {err}")) -} - -/// Runs `scenario` with a cut at every storage call of the first file, under every policy, and a -/// cut before every directory operation. Returns how many crash states were checked, and the -/// ones that `check` rejects. -fn sweep(scenario: fn(&SimDir), check: fn(&Disk) -> Result<(), String>) -> (usize, Vec) { +/// Runs `scenario` with a cut at every `stride`th storage call of the first file, under each of +/// `policies`, and with a cut before every directory operation. Each run's scenario result, and +/// every disk the cut could leave, go to `check`. Returns how many disks were checked, and the +/// ones `check` rejects. +fn sweep( + scenario: impl Fn(&SimDir) -> A, + check: impl Fn(&Disk, &A) -> Result<(), String>, + stride: usize, + policies: &[(Survive, Tear)], +) -> (usize, Vec) { let clean = SimDir::new(None, None); scenario(&clean); let mut runs: Vec<(String, SimDir)> = Vec::new(); - for event in 1..=clean.calls() { - for (index, (survive, tear)) in POLICIES.into_iter().enumerate() { + for event in (1..=clean.calls()).step_by(stride) { + for (index, &(survive, tear)) in policies.iter().enumerate() { for sync_completed in [false, true] { let plan = Plan { event, @@ -341,10 +324,10 @@ fn sweep(scenario: fn(&SimDir), check: fn(&Disk) -> Result<(), String>) -> (usiz let mut states = 0; let mut failures = Vec::new(); for (label, sim) in runs { - scenario(&sim); + let result = scenario(&sim); for disk in sim.crash_states() { states += 1; - if let Err(why) = check(&disk) { + if let Err(why) = check(&disk, &result) { failures.push(format!("{label}: {why}")); } } @@ -361,6 +344,39 @@ fn listing(failures: &[String]) -> String { .join("\n") } +/// The policies of the sampled runs: nothing survives, and a random subset with a torn write. +const SAMPLED: [(Survive, Tear); 2] = [POLICIES[0], POLICIES[2]]; + +/// The creation this sweep runs: the store's own open, which creates the file when it is absent. +fn creation(sim: &SimDir) { + let _ = EventStore::open_with(sim); +} + +/// The control: a file built in place, with one committed write. It has no temporary name and no +/// directory steps, so a cut during its first commit leaves the final name holding a partial file. +fn in_place(sim: &SimDir) { + let Ok(db) = sim.create_database(FILE_NAME) else { + return; + }; + let Ok(txn) = db.begin_write() else { + return; + }; + let table: TableDefinition<'_, &[u8], &[u8]> = TableDefinition::new("meta"); + if let Ok(mut meta) = txn.open_table(table) { + let _ = meta.insert(b"format".as_slice(), b"in place".as_slice()); + } + let _ = txn.commit(); +} + +/// Reopens one crash state with the store and checks what it holds. +fn reopens(disk: &Disk) -> Result<(), String> { + let store = EventStore::open_with(&SimDir::from_disk(disk)) + .map_err(|err| format!("does not open: {err}"))?; + store + .check_invariants() + .map_err(|err| format!("opens, but is inconsistent: {err}")) +} + #[test] fn clean_creation_leaves_a_store_that_reopens() { let sim = SimDir::new(None, None); @@ -375,7 +391,7 @@ fn clean_creation_leaves_a_store_that_reopens() { #[test] fn first_creation_reopens_after_every_crash_point() { - let (states, failures) = sweep(creation, reopens); + let (states, failures) = sweep(creation, |disk, &()| reopens(disk), 1, &POLICIES); println!( "first creation: {states} crash states checked, {} failed", failures.len() @@ -391,7 +407,7 @@ fn first_creation_reopens_after_every_crash_point() { #[test] fn creation_in_place_control_fails_at_some_crash_point() { - let (states, failures) = sweep(in_place, reopens); + let (states, failures) = sweep(in_place, |disk, &()| reopens(disk), 1, &POLICIES); println!( "control (in-place creation): {states} crash states checked, {} failed", failures.len() @@ -401,3 +417,207 @@ fn creation_in_place_control_fails_at_some_crash_point() { "the control never failed: the sweep cannot see a torn first commit" ); } + +/// The deliveries the ingest sweep makes after creation: a wait that a later event releases, an +/// after hash on another author's event, a fork, an event refused as frozen, and two repeats. +fn workload() -> Vec> { + let author = SigningKey::from_bytes(&[21; 32]); + let other = SigningKey::from_bytes(&[22; 32]); + let ext = |kind: &str, after: Vec| ChainExt { + kind: kind.to_owned(), + group: None, + after, + }; + let a0 = sign(&author, 0, None, None, ext("message", Vec::new())).unwrap(); + let a1 = sign(&author, 1, Some(a0.id), None, ext("message", Vec::new())).unwrap(); + let a2 = sign(&author, 2, Some(a1.id), None, ext("message", Vec::new())).unwrap(); + let a2_rival = sign(&author, 2, Some(a1.id), None, ext("rival", Vec::new())).unwrap(); + let a3 = sign(&author, 3, Some(a2.id), None, ext("message", Vec::new())).unwrap(); + let b0 = sign(&other, 0, None, None, ext("message", vec![a1.id])).unwrap(); + vec![ + a1.bytes, + a0.bytes.clone(), + a2.bytes.clone(), + b0.bytes, + a2_rival.bytes, + a3.bytes, + a2.bytes, + a0.bytes, + ] +} + +/// Creates the store on `sim`, then delivers the workload. Returns each delivery the process +/// acknowledged: one that returned before the power cut, with its outcome. +fn ingest_run(sim: &SimDir) -> Vec<(Vec, Ingest)> { + let mut acked = Vec::new(); + let Ok(mut store) = EventStore::open_with(sim) else { + return acked; + }; + for bytes in workload() { + if sim.cut_landed() { + break; + } + let Ok(outcome) = store.ingest(&bytes, 0) else { + break; + }; + if sim.cut_landed() { + break; + } + acked.push((bytes, outcome)); + } + acked +} + +/// Every acknowledged delivery must survive the reopen. An accepted event, and each event it +/// released, is stored and applied, unless a fork at or below it has frozen its author. A fork +/// must leave a proof no later than its own sequence number. The store must open, and its +/// invariants must hold. +fn acknowledged_survive(disk: &Disk, acked: &[(Vec, Ingest)]) -> Result<(), String> { + let store = EventStore::open_with(&SimDir::from_disk(disk)) + .map_err(|err| format!("does not open: {err}"))?; + store + .check_invariants() + .map_err(|err| format!("opens, but is inconsistent: {err}"))?; + let known: HashMap> = workload() + .into_iter() + .filter_map(|bytes| chain::decode(&bytes).ok().map(|event| (event.id, bytes))) + .collect(); + let mut applied_ids = Vec::new(); + for (_, outcome) in acked { + match outcome { + Ingest::Accepted { id, released } => { + applied_ids.push(*id); + applied_ids.extend(released); + } + Ingest::Duplicate { id } => applied_ids.push(*id), + Ingest::Fork { author, seq } => { + let proof = store + .fork_proof(author) + .map_err(|err| err.to_string())? + .ok_or("an acknowledged fork has no proof")?; + if proof.seq > *seq { + return Err(format!( + "an acknowledged fork at {seq} has a proof at {}", + proof.seq + )); + } + } + Ingest::Waiting { .. } | Ingest::Refused(_) => {} + } + } + for id in applied_ids { + let bytes = known + .get(&id) + .ok_or("an acknowledged id is not in the workload")?; + let event = chain::decode(bytes).map_err(|err| err.to_string())?; + let author = *event.header.verifying_key.as_bytes(); + let seq = event.header.seq_num; + let stored = store + .event_by_id(&id) + .map_err(|err| err.to_string())? + .ok_or("an acknowledged event is not stored")?; + if stored != event { + return Err("an acknowledged event is stored as another event".to_owned()); + } + let applied = store + .chain(&author) + .map_err(|err| err.to_string())? + .is_some_and(|chain| chain.next_seq > seq); + let frozen_at_or_below = store + .fork_proof(&author) + .map_err(|err| err.to_string())? + .is_some_and(|proof| proof.seq <= seq); + if !applied && !frozen_at_or_below { + return Err(format!( + "an acknowledged event at sequence {seq} is neither applied nor behind a fork" + )); + } + } + Ok(()) +} + +#[test] +fn clean_ingest_run_has_every_outcome_and_survives_its_reopen() { + let sim = SimDir::new(None, None); + let acked = ingest_run(&sim); + assert_eq!( + acked.len(), + workload().len(), + "the run stopped early without a cut" + ); + let outcomes: Vec<&Ingest> = acked.iter().map(|(_, outcome)| outcome).collect(); + assert!( + matches!(outcomes[0], Ingest::Waiting { .. }), + "a1 waits for a0" + ); + assert!( + matches!(outcomes[1], Ingest::Accepted { released, .. } if released.len() == 1), + "a0 releases a1" + ); + assert!(matches!(outcomes[2], Ingest::Accepted { .. }), "a2 follows"); + assert!( + matches!(outcomes[3], Ingest::Accepted { .. }), + "b0 names an applied a1" + ); + assert!( + matches!(outcomes[4], Ingest::Fork { seq: 2, .. }), + "a2 forks" + ); + assert!( + matches!(outcomes[5], Ingest::Refused(Refusal::Frozen)), + "a3 is refused after the fork" + ); + assert!( + matches!(outcomes[6], Ingest::Duplicate { .. }), + "a2 again is a repeat" + ); + assert!( + matches!(outcomes[7], Ingest::Duplicate { .. }), + "a0 again is a repeat" + ); + for disk in sim.crash_states() { + acknowledged_survive(&disk, &acked).unwrap(); + } +} + +#[test] +fn ingest_survives_every_sampled_crash_point() { + let (states, failures) = sweep( + ingest_run, + |disk, acked| acknowledged_survive(disk, acked), + 10, + &SAMPLED, + ); + println!( + "ingest (sampled): {states} crash states checked, {} failed", + failures.len() + ); + assert!(states > 0, "the sweep checked no crash states"); + assert!( + failures.is_empty(), + "{} crash states lost an acknowledged ingest:\n{}", + failures.len(), + listing(&failures) + ); +} + +#[test] +#[ignore = "the full ingest gate: every storage call under every policy. `just crash-gate` runs it in release"] +fn ingest_survives_every_crash_point() { + let (states, failures) = sweep( + ingest_run, + |disk, acked| acknowledged_survive(disk, acked), + 1, + &POLICIES, + ); + println!( + "ingest (full): {states} crash states checked, {} failed", + failures.len() + ); + assert!( + failures.is_empty(), + "{} crash states lost an acknowledged ingest:\n{}", + failures.len(), + listing(&failures) + ); +} diff --git a/pkgs/id/tests/event_store_properties.rs b/pkgs/id/tests/event_store_properties.rs new file mode 100644 index 0000000000..402497d427 --- /dev/null +++ b/pkgs/id/tests/event_store_properties.rs @@ -0,0 +1,353 @@ +//! Property tests for ingest in `src/event_store.rs` (plan P1.8). +//! +//! A scenario is a set of valid chains, with forks injected. Each fork is a second +//! event at a sequence number, signed with the same backlink as the original. The +//! scenario is delivered in three orders, with repeats, to fresh stores. Every store +//! must reach the applied state that the chains determine: the chain up to each +//! author's fork point, frozen if there is one, and the fork proof at the lowest fork. +//! +//! The `after` hashes are drawn from events that a fork can never take out of the +//! applied prefix. A fork can unapply events at and above its own sequence number, and +//! an event that names one of those would make the expected state depend on the order +//! of arrival. The regression list covers the orders the generator does not reach. +//! +//! Failures are not written to `proptest-regressions/`. The minimal input goes into +//! `tests/regressions/ingest.txt` instead (see `tests/regressions/README.md`). + +#![allow(clippy::unwrap_used, clippy::expect_used)] + +mod common; + +use common::ingest::{Canonical, deliver}; +use id::chain::{ChainExt, Event, sign}; +use id::event_store::Chain; +use id::waiting::AuthorKey; +use p2panda_core::{Hash, SeqNum, SigningKey}; +use proptest::prelude::*; +use proptest::test_runner::TestCaseError; + +/// SplitMix64. A scenario is a pure function of its seed. +struct Rng(u64); + +impl Rng { + fn next_u64(&mut self) -> u64 { + self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = self.0; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + } + + /// A number in `0..n`. + fn below(&mut self, n: u64) -> u64 { + self.next_u64() % n + } + + /// True in about one case in `n`. + fn chance(&mut self, n: u64) -> bool { + self.below(n) == 0 + } +} + +/// Cases per property. A debug build runs redb unoptimised, at about a second a case, so the +/// default is small. `PROPTEST_CASES` raises it. A release run (`--release`) goes much further. +fn config() -> ProptestConfig { + let cases = std::env::var("PROPTEST_CASES") + .ok() + .and_then(|value| value.parse().ok()) + .unwrap_or(32); + ProptestConfig { + cases, + failure_persistence: None, + ..ProptestConfig::default() + } +} + +/// A scenario: every signed event, and the applied state every delivery must reach. +struct Scenario { + /// Every signed event, originals and forks, in creation order. + events: Vec, + /// The authors' public keys. + authors: Vec, + /// The applied state of every author. + expected: Canonical, +} + +/// Up to three `after` hashes, drawn from the stable events created so far. +fn pick_after(rng: &mut Rng, stable: &[Hash]) -> Vec { + let mut picked = Vec::new(); + if stable.is_empty() { + return picked; + } + for _ in 0..rng.below(4) { + let hash = stable[rng.below(stable.len() as u64) as usize]; + if !picked.contains(&hash) { + picked.push(hash); + } + } + picked +} + +/// Signs an event with a random group and frontier, and the given kind. +fn signed( + rng: &mut Rng, + key: &SigningKey, + seq: SeqNum, + backlink: Option, + stable: &[Hash], + kind: &str, +) -> Event { + let group = rng + .chance(3) + .then(|| Hash::digest([u8::try_from(rng.below(3)).unwrap()])); + let ext = ChainExt { + kind: kind.to_owned(), + group, + after: pick_after(rng, stable), + }; + sign(key, seq, backlink, None, ext).unwrap() +} + +/// Orders two IDs as the fork proof does: lower ID first. +fn ordered(a: Hash, b: Hash) -> (Hash, Hash) { + if a.as_bytes() <= b.as_bytes() { + (a, b) + } else { + (b, a) + } +} + +fn scenario(seed: u64) -> Scenario { + let mut rng = Rng(seed); + let count = 2 + rng.below(2) as usize; + let keys: Vec = (0..count) + .map(|_| SigningKey::from_bytes(&std::array::from_fn(|_| rng.next_u64() as u8))) + .collect(); + let lengths: Vec = (0..count) + .map(|_| 1 + SeqNum::try_from(rng.below(4)).unwrap()) + .collect(); + // The forks are chosen first: at most one per sequence number. The lowest one is + // the author's fork point. + let forked: Vec> = lengths + .iter() + .map(|&len| (0..len).map(|_| rng.chance(4)).collect()) + .collect(); + let fork_point: Vec> = forked + .iter() + .map(|row| { + row.iter() + .position(|&is_forked| is_forked) + .map(|at| SeqNum::try_from(at).unwrap()) + }) + .collect(); + + let mut events: Vec = Vec::new(); + let mut chains: Vec> = vec![Vec::new(); count]; + let mut rivals: Vec> = vec![None; count]; + // The IDs that can be named by `after`: events below their author's fork point. + let mut stable: Vec = Vec::new(); + let mut progress: Vec = vec![0; count]; + while progress.iter().zip(&lengths).any(|(done, len)| done < len) { + let author = rng.below(count as u64) as usize; + let seq = progress[author]; + if seq >= lengths[author] { + continue; + } + progress[author] += 1; + let backlink = chains[author].last().map(|event| event.id); + let original = signed(&mut rng, &keys[author], seq, backlink, &stable, "message"); + if fork_point[author].is_none_or(|point| seq < point) { + stable.push(original.id); + } + chains[author].push(original.clone()); + events.push(original); + if forked[author][seq as usize] { + let rival = signed(&mut rng, &keys[author], seq, backlink, &stable, "rival"); + events.push(rival.clone()); + if fork_point[author] == Some(seq) { + rivals[author] = Some(rival); + } + } + } + + let mut expected = Canonical::default(); + for author in 0..count { + let who: AuthorKey = *keys[author].verifying_key().as_bytes(); + match fork_point[author] { + None => { + expected.chains.insert( + who, + Chain { + next_seq: lengths[author], + head: chains[author].last().map(|event| event.id), + frozen: false, + }, + ); + } + Some(point) => { + let head = point + .checked_sub(1) + .map(|before| chains[author][before as usize].id); + expected.chains.insert( + who, + Chain { + next_seq: point, + head, + frozen: true, + }, + ); + let original = chains[author][point as usize].id; + let rival = rivals[author].as_ref().unwrap().id; + let (first, second) = ordered(original, rival); + expected.proofs.insert(who, (point, first, second)); + } + } + } + let authors = keys + .iter() + .map(|key| *key.verifying_key().as_bytes()) + .collect(); + Scenario { + events, + authors, + expected, + } +} + +fn shuffle(items: &mut [T], rng: &mut Rng) { + for i in (1..items.len()).rev() { + let j = rng.below(i as u64 + 1) as usize; + items.swap(i, j); + } +} + +/// Three delivery orders of the scenario's events, each with some events repeated: +/// the creation order, the reverse, and a shuffle. +fn orders(events: &[Event], rng: &mut Rng) -> Vec>> { + let mut repeated: Vec> = Vec::new(); + for event in events { + repeated.push(event.bytes.clone()); + for _ in 0..rng.below(3) { + repeated.push(event.bytes.clone()); + } + } + let forward = repeated.clone(); + let mut reversed = repeated.clone(); + reversed.reverse(); + let mut shuffled = repeated; + shuffle(&mut shuffled, rng); + vec![forward, reversed, shuffled] +} + +proptest! { + #![proptest_config(config())] + + /// Random valid chains with forks, delivered in three orders with repeats, reach + /// the applied state that the chains determine. + #[test] + fn test_random_orders_reach_the_state_the_chains_determine(seed in any::()) { + let scenario = scenario(seed); + let mut rng = Rng(seed ^ 0xD1B5_4A32_D192_ED03); + for order in orders(&scenario.events, &mut rng) { + let state = deliver(&order, &scenario.authors).map_err(TestCaseError::fail)?; + prop_assert_eq!(&state, &scenario.expected); + } + } +} + +/// Escapes every byte as `\xHH`, which the replay format reads back. +fn escape(bytes: &[u8]) -> String { + bytes.iter().map(|byte| format!("\\x{byte:02x}")).collect() +} + +/// Prints the seed lines for `tests/regressions/ingest.txt`. The seeds sit on the ingest +/// boundaries: a fork at each position, an event ahead of its chain, an `after` hash on an +/// event the fork unapplied, a repeat, and bytes that fail verification. +/// Run by hand with `-- --ignored --nocapture`. +#[test] +#[ignore = "prints the seed lines for tests/regressions/ingest.txt"] +fn print_ingest_seeds() { + let key = |n: u8| SigningKey::from_bytes(&[n; 32]); + let sign_event = + |key: &SigningKey, seq: SeqNum, backlink: Option, after: Vec, kind: &str| { + let ext = ChainExt { + kind: kind.to_owned(), + group: None, + after, + }; + sign(key, seq, backlink, None, ext).unwrap() + }; + let (a, b) = (key(1), key(2)); + let a0 = sign_event(&a, 0, None, Vec::new(), "message"); + let a1 = sign_event(&a, 1, Some(a0.id), Vec::new(), "message"); + let a2 = sign_event(&a, 2, Some(a1.id), Vec::new(), "message"); + let a0_rival = sign_event(&a, 0, None, Vec::new(), "rival"); + let a1_rival = sign_event(&a, 1, Some(a0.id), Vec::new(), "rival"); + let a2_rival = sign_event(&a, 2, Some(a1.id), Vec::new(), "rival"); + let b0_after_a0 = sign_event(&b, 0, None, vec![a0.id], "message"); + let b0_after_a1 = sign_event(&b, 0, None, vec![a1.id], "message"); + let mut tampered = a0.bytes.clone(); + tampered[48] ^= 0x01; + let seeds: Vec<(&str, Vec>)> = vec![ + ("a valid event", vec![a0.bytes.clone()]), + ( + "a valid chain, in order", + vec![a0.bytes.clone(), a1.bytes.clone(), a2.bytes.clone()], + ), + ( + "a valid chain, reversed", + vec![a2.bytes.clone(), a1.bytes.clone(), a0.bytes.clone()], + ), + ( + "a fork one step up", + vec![a0.bytes.clone(), a1.bytes.clone(), a1_rival.bytes.clone()], + ), + ( + "a fork at sequence zero", + vec![a0.bytes.clone(), a0_rival.bytes.clone()], + ), + ( + "a fork below a higher fork", + vec![ + a0.bytes.clone(), + a1.bytes.clone(), + a2.bytes.clone(), + a2_rival.bytes.clone(), + a1_rival.bytes.clone(), + ], + ), + ( + "an after hash released by its event", + vec![b0_after_a0.bytes.clone(), a0.bytes.clone()], + ), + ( + "an after hash on an event the fork unapplied", + vec![ + a0.bytes.clone(), + a1.bytes.clone(), + a1_rival.bytes.clone(), + b0_after_a1.bytes.clone(), + ], + ), + ( + "the same event twice", + vec![a0.bytes.clone(), a0.bytes.clone()], + ), + ( + "a signature with one bit flipped", + vec![tampered, a0.bytes.clone()], + ), + ( + "bytes that are not CBOR", + vec![b"\xff\x00 not an event".to_vec(), a0.bytes.clone()], + ), + ]; + for (name, events) in seeds { + let fields: Vec = events + .iter() + .map(|bytes| format!("b:{}", escape(bytes))) + .collect(); + println!("# {name}"); + println!("ingest\t{}\tok", fields.join(" ")); + } +} diff --git a/pkgs/id/tests/regression_replay.rs b/pkgs/id/tests/regression_replay.rs index a2da1da200..015455469d 100644 --- a/pkgs/id/tests/regression_replay.rs +++ b/pkgs/id/tests/regression_replay.rs @@ -5,7 +5,9 @@ //! with `#` are skipped. The input uses the area's own syntax; for `tuple` it is //! two elements separated by a space (see `common::parse_value`), and for //! `chainext` it is one `b:` element holding the event bytes (see -//! `common::chain`). The only expected result is `ok`: the property must hold +//! `common::chain`), and for `ingest` it is one or more `b:` elements, the events +//! of one delivery (see `common::ingest`). The only expected result is `ok`: the +//! property must hold //! for that input. See `tests/regressions/README.md` for how a fuzz failure //! becomes a case. @@ -16,6 +18,7 @@ mod common; use std::path::{Path, PathBuf}; use common::chain::check_event_bytes; +use common::ingest::check_order_independence; use common::{Value, check_pair, parse_value}; /// Split one line into its three fields. @@ -50,6 +53,19 @@ fn replay_case(area: &str, input: &str, expected: &str) -> Result<(), String> { "chainext input {input:?} must be one b: element" )), }, + "ingest" => { + // One or more `b:` elements, separated by spaces: the events, in one delivery. + let events = input + .split(' ') + .map(|element| match parse_value(element)? { + Value::Bytes(bytes) => Ok(bytes), + Value::Text(_) => Err(format!( + "ingest input {input:?} must be b: elements" + )), + }) + .collect::>, String>>()?; + check_order_independence(&events) + } other => Err(format!("unknown area {other:?}")), } } @@ -125,6 +141,10 @@ fn test_replay_rejects_malformed_cases() { replay_case("chainext", "s:a", "ok").is_err(), "chainext takes bytes, not a string" ); + assert!( + replay_case("ingest", "b:\\x00 s:a", "ok").is_err(), + "ingest takes only byte elements" + ); } #[test] diff --git a/pkgs/id/tests/regressions/README.md b/pkgs/id/tests/regressions/README.md index 5271e66b35..a09281ce2f 100644 --- a/pkgs/id/tests/regressions/README.md +++ b/pkgs/id/tests/regressions/README.md @@ -18,7 +18,9 @@ areainputexpected - `input` uses the area's syntax. For `tuple` it is two elements separated by one space. Each element is `s:` (a UTF-8 string) or `b:` (a byte string). For `chainext` it is one `b:` element: the bytes given to the - event decoder in `src/chain.rs`. + event decoder in `src/chain.rs`. For `ingest` it is one or more `b:` + elements separated by spaces: the events of one delivery. The check delivers them + in three orders, with repeats, and requires the same applied state in each. - `expected` is `ok`: the property must hold for that input. - Blank lines and lines starting with `#` are skipped. diff --git a/pkgs/id/tests/regressions/ingest.txt b/pkgs/id/tests/regressions/ingest.txt new file mode 100644 index 0000000000..595ba9e352 --- /dev/null +++ b/pkgs/id/tests/regressions/ingest.txt @@ -0,0 +1,28 @@ +# Known-bad delivery orders for event ingest, replayed on every run. See README.md for the format. +# Each line: area, input (one or more b: elements separated by spaces: the events of one delivery), +# expected result. Each case is checked in several orders with repeats, and the applied state must match. +# The seeds sit on the ingest boundaries: a fork at each position, an event ahead of its chain, an +# after hash on an event a fork unapplied, a repeat, and bytes that fail verification. They were +# written with `print_ingest_seeds` (tests/event_store_properties.rs), not found by a fuzz run. +# a valid event +ingest b:\x86\x01\x58\x20\x8a\x88\xe3\xdd\x74\x09\xf1\x95\xfd\x52\xdb\x2d\x3c\xba\x5d\x72\xca\x67\x09\xbf\x1d\x94\x12\x1b\xf3\x74\x88\x01\xb4\x0f\x6f\x5c\x58\x40\xf6\xd9\x3d\xac\x1b\x09\xa4\xcf\xf3\x59\x14\xd5\x78\x09\x52\x16\x59\x81\xf9\x8f\x8f\x35\x74\x88\x65\x84\x64\xe2\xa5\xae\x8a\x88\x32\x9e\x69\x9b\x88\x87\x8c\x54\xd4\x2c\xc2\x59\x18\xa9\x56\x17\x3a\x45\x94\xaf\x21\xd2\x9b\x3b\x81\xdb\x99\x51\x37\xd5\x5e\x00\x00\x00\xa4\x64\x6b\x69\x6e\x64\x67\x6d\x65\x73\x73\x61\x67\x65\x65\x61\x66\x74\x65\x72\x80\x65\x67\x72\x6f\x75\x70\xf6\x66\x64\x6f\x6d\x61\x69\x6e\x6c\x69\x64\x2e\x65\x76\x65\x6e\x74\x73\x2e\x76\x31 ok +# a valid chain, in order +ingest b:\x86\x01\x58\x20\x8a\x88\xe3\xdd\x74\x09\xf1\x95\xfd\x52\xdb\x2d\x3c\xba\x5d\x72\xca\x67\x09\xbf\x1d\x94\x12\x1b\xf3\x74\x88\x01\xb4\x0f\x6f\x5c\x58\x40\xf6\xd9\x3d\xac\x1b\x09\xa4\xcf\xf3\x59\x14\xd5\x78\x09\x52\x16\x59\x81\xf9\x8f\x8f\x35\x74\x88\x65\x84\x64\xe2\xa5\xae\x8a\x88\x32\x9e\x69\x9b\x88\x87\x8c\x54\xd4\x2c\xc2\x59\x18\xa9\x56\x17\x3a\x45\x94\xaf\x21\xd2\x9b\x3b\x81\xdb\x99\x51\x37\xd5\x5e\x00\x00\x00\xa4\x64\x6b\x69\x6e\x64\x67\x6d\x65\x73\x73\x61\x67\x65\x65\x61\x66\x74\x65\x72\x80\x65\x67\x72\x6f\x75\x70\xf6\x66\x64\x6f\x6d\x61\x69\x6e\x6c\x69\x64\x2e\x65\x76\x65\x6e\x74\x73\x2e\x76\x31 b:\x87\x01\x58\x20\x8a\x88\xe3\xdd\x74\x09\xf1\x95\xfd\x52\xdb\x2d\x3c\xba\x5d\x72\xca\x67\x09\xbf\x1d\x94\x12\x1b\xf3\x74\x88\x01\xb4\x0f\x6f\x5c\x58\x40\xbf\xd6\x50\x13\x18\x9d\xe4\xd5\xbe\xdf\xc0\x7e\xcc\x77\xeb\x96\x02\x52\x5c\xed\xd3\x2b\x8e\x07\x82\x85\x5d\xbc\x02\xee\x68\xd7\xcf\x77\xad\xab\xdb\x60\x30\x11\x87\xc7\x96\x1e\x18\x05\xfd\x2d\xb5\x17\xa1\xa1\xaa\x40\x06\xe1\xd7\x5c\x9a\x43\xfa\x56\x1a\x00\x00\x01\x58\x20\x93\x69\x8c\xd5\xe5\xa4\x7f\xbe\xd0\x3d\xa0\x14\xa6\x82\x6c\x26\x76\x69\xd5\xd9\xb1\xe3\x8c\xbf\x1b\xb2\xdb\x51\x8c\x48\xdd\xb1\xa4\x64\x6b\x69\x6e\x64\x67\x6d\x65\x73\x73\x61\x67\x65\x65\x61\x66\x74\x65\x72\x80\x65\x67\x72\x6f\x75\x70\xf6\x66\x64\x6f\x6d\x61\x69\x6e\x6c\x69\x64\x2e\x65\x76\x65\x6e\x74\x73\x2e\x76\x31 b:\x87\x01\x58\x20\x8a\x88\xe3\xdd\x74\x09\xf1\x95\xfd\x52\xdb\x2d\x3c\xba\x5d\x72\xca\x67\x09\xbf\x1d\x94\x12\x1b\xf3\x74\x88\x01\xb4\x0f\x6f\x5c\x58\x40\x4f\x90\x42\x95\xf1\xc7\xc9\x6f\x23\x17\xb7\xfe\x55\xec\xb9\xb8\x14\xcb\xbc\x96\x4f\xc7\x0e\x79\x1d\xca\x5c\x6f\x92\x25\x8d\x02\x0b\x79\xc9\x43\x8b\x74\xc1\x4a\x5c\x21\x77\xe7\x7f\x06\x6f\x32\x20\x83\x0b\xfb\x40\x15\x33\x6d\x39\x1c\xe6\x4f\xda\x21\xb8\x0c\x00\x02\x58\x20\xae\x52\xd9\xae\xc8\xa5\xa0\x2f\xa9\x59\x3e\xcb\xf0\x8c\xe7\x97\x25\xe3\xc3\x9f\x32\x19\xf4\x8b\xb5\x1b\x4d\xdd\x37\x7e\x3b\x98\xa4\x64\x6b\x69\x6e\x64\x67\x6d\x65\x73\x73\x61\x67\x65\x65\x61\x66\x74\x65\x72\x80\x65\x67\x72\x6f\x75\x70\xf6\x66\x64\x6f\x6d\x61\x69\x6e\x6c\x69\x64\x2e\x65\x76\x65\x6e\x74\x73\x2e\x76\x31 ok +# a valid chain, reversed +ingest b:\x87\x01\x58\x20\x8a\x88\xe3\xdd\x74\x09\xf1\x95\xfd\x52\xdb\x2d\x3c\xba\x5d\x72\xca\x67\x09\xbf\x1d\x94\x12\x1b\xf3\x74\x88\x01\xb4\x0f\x6f\x5c\x58\x40\x4f\x90\x42\x95\xf1\xc7\xc9\x6f\x23\x17\xb7\xfe\x55\xec\xb9\xb8\x14\xcb\xbc\x96\x4f\xc7\x0e\x79\x1d\xca\x5c\x6f\x92\x25\x8d\x02\x0b\x79\xc9\x43\x8b\x74\xc1\x4a\x5c\x21\x77\xe7\x7f\x06\x6f\x32\x20\x83\x0b\xfb\x40\x15\x33\x6d\x39\x1c\xe6\x4f\xda\x21\xb8\x0c\x00\x02\x58\x20\xae\x52\xd9\xae\xc8\xa5\xa0\x2f\xa9\x59\x3e\xcb\xf0\x8c\xe7\x97\x25\xe3\xc3\x9f\x32\x19\xf4\x8b\xb5\x1b\x4d\xdd\x37\x7e\x3b\x98\xa4\x64\x6b\x69\x6e\x64\x67\x6d\x65\x73\x73\x61\x67\x65\x65\x61\x66\x74\x65\x72\x80\x65\x67\x72\x6f\x75\x70\xf6\x66\x64\x6f\x6d\x61\x69\x6e\x6c\x69\x64\x2e\x65\x76\x65\x6e\x74\x73\x2e\x76\x31 b:\x87\x01\x58\x20\x8a\x88\xe3\xdd\x74\x09\xf1\x95\xfd\x52\xdb\x2d\x3c\xba\x5d\x72\xca\x67\x09\xbf\x1d\x94\x12\x1b\xf3\x74\x88\x01\xb4\x0f\x6f\x5c\x58\x40\xbf\xd6\x50\x13\x18\x9d\xe4\xd5\xbe\xdf\xc0\x7e\xcc\x77\xeb\x96\x02\x52\x5c\xed\xd3\x2b\x8e\x07\x82\x85\x5d\xbc\x02\xee\x68\xd7\xcf\x77\xad\xab\xdb\x60\x30\x11\x87\xc7\x96\x1e\x18\x05\xfd\x2d\xb5\x17\xa1\xa1\xaa\x40\x06\xe1\xd7\x5c\x9a\x43\xfa\x56\x1a\x00\x00\x01\x58\x20\x93\x69\x8c\xd5\xe5\xa4\x7f\xbe\xd0\x3d\xa0\x14\xa6\x82\x6c\x26\x76\x69\xd5\xd9\xb1\xe3\x8c\xbf\x1b\xb2\xdb\x51\x8c\x48\xdd\xb1\xa4\x64\x6b\x69\x6e\x64\x67\x6d\x65\x73\x73\x61\x67\x65\x65\x61\x66\x74\x65\x72\x80\x65\x67\x72\x6f\x75\x70\xf6\x66\x64\x6f\x6d\x61\x69\x6e\x6c\x69\x64\x2e\x65\x76\x65\x6e\x74\x73\x2e\x76\x31 b:\x86\x01\x58\x20\x8a\x88\xe3\xdd\x74\x09\xf1\x95\xfd\x52\xdb\x2d\x3c\xba\x5d\x72\xca\x67\x09\xbf\x1d\x94\x12\x1b\xf3\x74\x88\x01\xb4\x0f\x6f\x5c\x58\x40\xf6\xd9\x3d\xac\x1b\x09\xa4\xcf\xf3\x59\x14\xd5\x78\x09\x52\x16\x59\x81\xf9\x8f\x8f\x35\x74\x88\x65\x84\x64\xe2\xa5\xae\x8a\x88\x32\x9e\x69\x9b\x88\x87\x8c\x54\xd4\x2c\xc2\x59\x18\xa9\x56\x17\x3a\x45\x94\xaf\x21\xd2\x9b\x3b\x81\xdb\x99\x51\x37\xd5\x5e\x00\x00\x00\xa4\x64\x6b\x69\x6e\x64\x67\x6d\x65\x73\x73\x61\x67\x65\x65\x61\x66\x74\x65\x72\x80\x65\x67\x72\x6f\x75\x70\xf6\x66\x64\x6f\x6d\x61\x69\x6e\x6c\x69\x64\x2e\x65\x76\x65\x6e\x74\x73\x2e\x76\x31 ok +# a fork one step up +ingest b:\x86\x01\x58\x20\x8a\x88\xe3\xdd\x74\x09\xf1\x95\xfd\x52\xdb\x2d\x3c\xba\x5d\x72\xca\x67\x09\xbf\x1d\x94\x12\x1b\xf3\x74\x88\x01\xb4\x0f\x6f\x5c\x58\x40\xf6\xd9\x3d\xac\x1b\x09\xa4\xcf\xf3\x59\x14\xd5\x78\x09\x52\x16\x59\x81\xf9\x8f\x8f\x35\x74\x88\x65\x84\x64\xe2\xa5\xae\x8a\x88\x32\x9e\x69\x9b\x88\x87\x8c\x54\xd4\x2c\xc2\x59\x18\xa9\x56\x17\x3a\x45\x94\xaf\x21\xd2\x9b\x3b\x81\xdb\x99\x51\x37\xd5\x5e\x00\x00\x00\xa4\x64\x6b\x69\x6e\x64\x67\x6d\x65\x73\x73\x61\x67\x65\x65\x61\x66\x74\x65\x72\x80\x65\x67\x72\x6f\x75\x70\xf6\x66\x64\x6f\x6d\x61\x69\x6e\x6c\x69\x64\x2e\x65\x76\x65\x6e\x74\x73\x2e\x76\x31 b:\x87\x01\x58\x20\x8a\x88\xe3\xdd\x74\x09\xf1\x95\xfd\x52\xdb\x2d\x3c\xba\x5d\x72\xca\x67\x09\xbf\x1d\x94\x12\x1b\xf3\x74\x88\x01\xb4\x0f\x6f\x5c\x58\x40\xbf\xd6\x50\x13\x18\x9d\xe4\xd5\xbe\xdf\xc0\x7e\xcc\x77\xeb\x96\x02\x52\x5c\xed\xd3\x2b\x8e\x07\x82\x85\x5d\xbc\x02\xee\x68\xd7\xcf\x77\xad\xab\xdb\x60\x30\x11\x87\xc7\x96\x1e\x18\x05\xfd\x2d\xb5\x17\xa1\xa1\xaa\x40\x06\xe1\xd7\x5c\x9a\x43\xfa\x56\x1a\x00\x00\x01\x58\x20\x93\x69\x8c\xd5\xe5\xa4\x7f\xbe\xd0\x3d\xa0\x14\xa6\x82\x6c\x26\x76\x69\xd5\xd9\xb1\xe3\x8c\xbf\x1b\xb2\xdb\x51\x8c\x48\xdd\xb1\xa4\x64\x6b\x69\x6e\x64\x67\x6d\x65\x73\x73\x61\x67\x65\x65\x61\x66\x74\x65\x72\x80\x65\x67\x72\x6f\x75\x70\xf6\x66\x64\x6f\x6d\x61\x69\x6e\x6c\x69\x64\x2e\x65\x76\x65\x6e\x74\x73\x2e\x76\x31 b:\x87\x01\x58\x20\x8a\x88\xe3\xdd\x74\x09\xf1\x95\xfd\x52\xdb\x2d\x3c\xba\x5d\x72\xca\x67\x09\xbf\x1d\x94\x12\x1b\xf3\x74\x88\x01\xb4\x0f\x6f\x5c\x58\x40\x29\x77\x93\xb0\x91\xce\x95\xe0\xd4\xca\x08\x2b\xc5\xbd\x62\x47\xff\xb8\xd7\x7c\x22\xe4\xfd\x3e\xbd\xc5\x1a\xca\x71\xd6\x8e\x93\x43\xaa\x84\x1f\xf7\xa5\x82\x28\xc7\x9b\xe9\x93\x26\x14\xcd\x1c\xcd\x83\x05\x69\xec\x23\x43\xa6\xd1\x27\x99\x41\x07\xc2\xfe\x04\x00\x01\x58\x20\x93\x69\x8c\xd5\xe5\xa4\x7f\xbe\xd0\x3d\xa0\x14\xa6\x82\x6c\x26\x76\x69\xd5\xd9\xb1\xe3\x8c\xbf\x1b\xb2\xdb\x51\x8c\x48\xdd\xb1\xa4\x64\x6b\x69\x6e\x64\x65\x72\x69\x76\x61\x6c\x65\x61\x66\x74\x65\x72\x80\x65\x67\x72\x6f\x75\x70\xf6\x66\x64\x6f\x6d\x61\x69\x6e\x6c\x69\x64\x2e\x65\x76\x65\x6e\x74\x73\x2e\x76\x31 ok +# a fork at sequence zero +ingest b:\x86\x01\x58\x20\x8a\x88\xe3\xdd\x74\x09\xf1\x95\xfd\x52\xdb\x2d\x3c\xba\x5d\x72\xca\x67\x09\xbf\x1d\x94\x12\x1b\xf3\x74\x88\x01\xb4\x0f\x6f\x5c\x58\x40\xf6\xd9\x3d\xac\x1b\x09\xa4\xcf\xf3\x59\x14\xd5\x78\x09\x52\x16\x59\x81\xf9\x8f\x8f\x35\x74\x88\x65\x84\x64\xe2\xa5\xae\x8a\x88\x32\x9e\x69\x9b\x88\x87\x8c\x54\xd4\x2c\xc2\x59\x18\xa9\x56\x17\x3a\x45\x94\xaf\x21\xd2\x9b\x3b\x81\xdb\x99\x51\x37\xd5\x5e\x00\x00\x00\xa4\x64\x6b\x69\x6e\x64\x67\x6d\x65\x73\x73\x61\x67\x65\x65\x61\x66\x74\x65\x72\x80\x65\x67\x72\x6f\x75\x70\xf6\x66\x64\x6f\x6d\x61\x69\x6e\x6c\x69\x64\x2e\x65\x76\x65\x6e\x74\x73\x2e\x76\x31 b:\x86\x01\x58\x20\x8a\x88\xe3\xdd\x74\x09\xf1\x95\xfd\x52\xdb\x2d\x3c\xba\x5d\x72\xca\x67\x09\xbf\x1d\x94\x12\x1b\xf3\x74\x88\x01\xb4\x0f\x6f\x5c\x58\x40\x36\xca\x17\x34\x43\x3d\x51\x4e\x3f\x59\xcc\xff\x10\xad\x74\x66\xb3\xf2\xbd\xd8\x5e\xef\xf3\x84\x7c\xb7\x06\x08\x18\x37\xa5\x2f\x56\x43\xe3\x67\x9b\x62\x8f\x6d\x2e\x27\x4e\xc4\x78\xdb\xd1\xc4\x69\x2c\xc8\x81\x2b\xc5\x24\x3e\x66\x99\x9c\x0b\x46\xba\x0e\x0b\x00\x00\xa4\x64\x6b\x69\x6e\x64\x65\x72\x69\x76\x61\x6c\x65\x61\x66\x74\x65\x72\x80\x65\x67\x72\x6f\x75\x70\xf6\x66\x64\x6f\x6d\x61\x69\x6e\x6c\x69\x64\x2e\x65\x76\x65\x6e\x74\x73\x2e\x76\x31 ok +# a fork below a higher fork +ingest b:\x86\x01\x58\x20\x8a\x88\xe3\xdd\x74\x09\xf1\x95\xfd\x52\xdb\x2d\x3c\xba\x5d\x72\xca\x67\x09\xbf\x1d\x94\x12\x1b\xf3\x74\x88\x01\xb4\x0f\x6f\x5c\x58\x40\xf6\xd9\x3d\xac\x1b\x09\xa4\xcf\xf3\x59\x14\xd5\x78\x09\x52\x16\x59\x81\xf9\x8f\x8f\x35\x74\x88\x65\x84\x64\xe2\xa5\xae\x8a\x88\x32\x9e\x69\x9b\x88\x87\x8c\x54\xd4\x2c\xc2\x59\x18\xa9\x56\x17\x3a\x45\x94\xaf\x21\xd2\x9b\x3b\x81\xdb\x99\x51\x37\xd5\x5e\x00\x00\x00\xa4\x64\x6b\x69\x6e\x64\x67\x6d\x65\x73\x73\x61\x67\x65\x65\x61\x66\x74\x65\x72\x80\x65\x67\x72\x6f\x75\x70\xf6\x66\x64\x6f\x6d\x61\x69\x6e\x6c\x69\x64\x2e\x65\x76\x65\x6e\x74\x73\x2e\x76\x31 b:\x87\x01\x58\x20\x8a\x88\xe3\xdd\x74\x09\xf1\x95\xfd\x52\xdb\x2d\x3c\xba\x5d\x72\xca\x67\x09\xbf\x1d\x94\x12\x1b\xf3\x74\x88\x01\xb4\x0f\x6f\x5c\x58\x40\xbf\xd6\x50\x13\x18\x9d\xe4\xd5\xbe\xdf\xc0\x7e\xcc\x77\xeb\x96\x02\x52\x5c\xed\xd3\x2b\x8e\x07\x82\x85\x5d\xbc\x02\xee\x68\xd7\xcf\x77\xad\xab\xdb\x60\x30\x11\x87\xc7\x96\x1e\x18\x05\xfd\x2d\xb5\x17\xa1\xa1\xaa\x40\x06\xe1\xd7\x5c\x9a\x43\xfa\x56\x1a\x00\x00\x01\x58\x20\x93\x69\x8c\xd5\xe5\xa4\x7f\xbe\xd0\x3d\xa0\x14\xa6\x82\x6c\x26\x76\x69\xd5\xd9\xb1\xe3\x8c\xbf\x1b\xb2\xdb\x51\x8c\x48\xdd\xb1\xa4\x64\x6b\x69\x6e\x64\x67\x6d\x65\x73\x73\x61\x67\x65\x65\x61\x66\x74\x65\x72\x80\x65\x67\x72\x6f\x75\x70\xf6\x66\x64\x6f\x6d\x61\x69\x6e\x6c\x69\x64\x2e\x65\x76\x65\x6e\x74\x73\x2e\x76\x31 b:\x87\x01\x58\x20\x8a\x88\xe3\xdd\x74\x09\xf1\x95\xfd\x52\xdb\x2d\x3c\xba\x5d\x72\xca\x67\x09\xbf\x1d\x94\x12\x1b\xf3\x74\x88\x01\xb4\x0f\x6f\x5c\x58\x40\x4f\x90\x42\x95\xf1\xc7\xc9\x6f\x23\x17\xb7\xfe\x55\xec\xb9\xb8\x14\xcb\xbc\x96\x4f\xc7\x0e\x79\x1d\xca\x5c\x6f\x92\x25\x8d\x02\x0b\x79\xc9\x43\x8b\x74\xc1\x4a\x5c\x21\x77\xe7\x7f\x06\x6f\x32\x20\x83\x0b\xfb\x40\x15\x33\x6d\x39\x1c\xe6\x4f\xda\x21\xb8\x0c\x00\x02\x58\x20\xae\x52\xd9\xae\xc8\xa5\xa0\x2f\xa9\x59\x3e\xcb\xf0\x8c\xe7\x97\x25\xe3\xc3\x9f\x32\x19\xf4\x8b\xb5\x1b\x4d\xdd\x37\x7e\x3b\x98\xa4\x64\x6b\x69\x6e\x64\x67\x6d\x65\x73\x73\x61\x67\x65\x65\x61\x66\x74\x65\x72\x80\x65\x67\x72\x6f\x75\x70\xf6\x66\x64\x6f\x6d\x61\x69\x6e\x6c\x69\x64\x2e\x65\x76\x65\x6e\x74\x73\x2e\x76\x31 b:\x87\x01\x58\x20\x8a\x88\xe3\xdd\x74\x09\xf1\x95\xfd\x52\xdb\x2d\x3c\xba\x5d\x72\xca\x67\x09\xbf\x1d\x94\x12\x1b\xf3\x74\x88\x01\xb4\x0f\x6f\x5c\x58\x40\x4b\x31\xad\xaf\x3b\x46\xe2\x8a\x7d\xe0\x74\x92\x07\xdd\xf1\xe6\x3a\xbe\xa4\xea\x7a\x93\x13\x8f\x1a\x62\x47\x11\x0c\xaf\x4b\x21\x95\x3e\xf5\x8a\x76\x08\x44\x60\x0a\xfe\xe5\x01\xf9\x7c\x8e\x8b\x8e\xdf\x9e\x8b\xea\x2f\xfd\x5c\xb6\x4f\x9c\x27\x54\xaf\xca\x02\x00\x02\x58\x20\xae\x52\xd9\xae\xc8\xa5\xa0\x2f\xa9\x59\x3e\xcb\xf0\x8c\xe7\x97\x25\xe3\xc3\x9f\x32\x19\xf4\x8b\xb5\x1b\x4d\xdd\x37\x7e\x3b\x98\xa4\x64\x6b\x69\x6e\x64\x65\x72\x69\x76\x61\x6c\x65\x61\x66\x74\x65\x72\x80\x65\x67\x72\x6f\x75\x70\xf6\x66\x64\x6f\x6d\x61\x69\x6e\x6c\x69\x64\x2e\x65\x76\x65\x6e\x74\x73\x2e\x76\x31 b:\x87\x01\x58\x20\x8a\x88\xe3\xdd\x74\x09\xf1\x95\xfd\x52\xdb\x2d\x3c\xba\x5d\x72\xca\x67\x09\xbf\x1d\x94\x12\x1b\xf3\x74\x88\x01\xb4\x0f\x6f\x5c\x58\x40\x29\x77\x93\xb0\x91\xce\x95\xe0\xd4\xca\x08\x2b\xc5\xbd\x62\x47\xff\xb8\xd7\x7c\x22\xe4\xfd\x3e\xbd\xc5\x1a\xca\x71\xd6\x8e\x93\x43\xaa\x84\x1f\xf7\xa5\x82\x28\xc7\x9b\xe9\x93\x26\x14\xcd\x1c\xcd\x83\x05\x69\xec\x23\x43\xa6\xd1\x27\x99\x41\x07\xc2\xfe\x04\x00\x01\x58\x20\x93\x69\x8c\xd5\xe5\xa4\x7f\xbe\xd0\x3d\xa0\x14\xa6\x82\x6c\x26\x76\x69\xd5\xd9\xb1\xe3\x8c\xbf\x1b\xb2\xdb\x51\x8c\x48\xdd\xb1\xa4\x64\x6b\x69\x6e\x64\x65\x72\x69\x76\x61\x6c\x65\x61\x66\x74\x65\x72\x80\x65\x67\x72\x6f\x75\x70\xf6\x66\x64\x6f\x6d\x61\x69\x6e\x6c\x69\x64\x2e\x65\x76\x65\x6e\x74\x73\x2e\x76\x31 ok +# an after hash released by its event +ingest b:\x86\x01\x58\x20\x81\x39\x77\x0e\xa8\x7d\x17\x5f\x56\xa3\x54\x66\xc3\x4c\x7e\xcc\xcb\x8d\x8a\x91\xb4\xee\x37\xa2\x5d\xf6\x0f\x5b\x8f\xc9\xb3\x94\x58\x40\x22\x1d\x8f\xe1\x78\xf5\x12\x07\x11\x33\x8d\x12\x5c\x26\x94\x9d\xaa\x58\x5f\x89\x05\x3e\x74\x27\xa5\xe9\xbd\x88\xca\xc9\xca\x3d\xd6\xc2\xb9\x99\xb6\xa1\xf6\xc7\xa1\x33\x69\x7c\x97\x71\x35\x26\xd2\x1c\x2a\x93\x33\x7a\x7c\xae\x33\x07\xed\xcd\x9c\xab\xc2\x0f\x00\x00\xa4\x64\x6b\x69\x6e\x64\x67\x6d\x65\x73\x73\x61\x67\x65\x65\x61\x66\x74\x65\x72\x81\x58\x20\x93\x69\x8c\xd5\xe5\xa4\x7f\xbe\xd0\x3d\xa0\x14\xa6\x82\x6c\x26\x76\x69\xd5\xd9\xb1\xe3\x8c\xbf\x1b\xb2\xdb\x51\x8c\x48\xdd\xb1\x65\x67\x72\x6f\x75\x70\xf6\x66\x64\x6f\x6d\x61\x69\x6e\x6c\x69\x64\x2e\x65\x76\x65\x6e\x74\x73\x2e\x76\x31 b:\x86\x01\x58\x20\x8a\x88\xe3\xdd\x74\x09\xf1\x95\xfd\x52\xdb\x2d\x3c\xba\x5d\x72\xca\x67\x09\xbf\x1d\x94\x12\x1b\xf3\x74\x88\x01\xb4\x0f\x6f\x5c\x58\x40\xf6\xd9\x3d\xac\x1b\x09\xa4\xcf\xf3\x59\x14\xd5\x78\x09\x52\x16\x59\x81\xf9\x8f\x8f\x35\x74\x88\x65\x84\x64\xe2\xa5\xae\x8a\x88\x32\x9e\x69\x9b\x88\x87\x8c\x54\xd4\x2c\xc2\x59\x18\xa9\x56\x17\x3a\x45\x94\xaf\x21\xd2\x9b\x3b\x81\xdb\x99\x51\x37\xd5\x5e\x00\x00\x00\xa4\x64\x6b\x69\x6e\x64\x67\x6d\x65\x73\x73\x61\x67\x65\x65\x61\x66\x74\x65\x72\x80\x65\x67\x72\x6f\x75\x70\xf6\x66\x64\x6f\x6d\x61\x69\x6e\x6c\x69\x64\x2e\x65\x76\x65\x6e\x74\x73\x2e\x76\x31 ok +# an after hash on an event the fork unapplied +ingest b:\x86\x01\x58\x20\x8a\x88\xe3\xdd\x74\x09\xf1\x95\xfd\x52\xdb\x2d\x3c\xba\x5d\x72\xca\x67\x09\xbf\x1d\x94\x12\x1b\xf3\x74\x88\x01\xb4\x0f\x6f\x5c\x58\x40\xf6\xd9\x3d\xac\x1b\x09\xa4\xcf\xf3\x59\x14\xd5\x78\x09\x52\x16\x59\x81\xf9\x8f\x8f\x35\x74\x88\x65\x84\x64\xe2\xa5\xae\x8a\x88\x32\x9e\x69\x9b\x88\x87\x8c\x54\xd4\x2c\xc2\x59\x18\xa9\x56\x17\x3a\x45\x94\xaf\x21\xd2\x9b\x3b\x81\xdb\x99\x51\x37\xd5\x5e\x00\x00\x00\xa4\x64\x6b\x69\x6e\x64\x67\x6d\x65\x73\x73\x61\x67\x65\x65\x61\x66\x74\x65\x72\x80\x65\x67\x72\x6f\x75\x70\xf6\x66\x64\x6f\x6d\x61\x69\x6e\x6c\x69\x64\x2e\x65\x76\x65\x6e\x74\x73\x2e\x76\x31 b:\x87\x01\x58\x20\x8a\x88\xe3\xdd\x74\x09\xf1\x95\xfd\x52\xdb\x2d\x3c\xba\x5d\x72\xca\x67\x09\xbf\x1d\x94\x12\x1b\xf3\x74\x88\x01\xb4\x0f\x6f\x5c\x58\x40\xbf\xd6\x50\x13\x18\x9d\xe4\xd5\xbe\xdf\xc0\x7e\xcc\x77\xeb\x96\x02\x52\x5c\xed\xd3\x2b\x8e\x07\x82\x85\x5d\xbc\x02\xee\x68\xd7\xcf\x77\xad\xab\xdb\x60\x30\x11\x87\xc7\x96\x1e\x18\x05\xfd\x2d\xb5\x17\xa1\xa1\xaa\x40\x06\xe1\xd7\x5c\x9a\x43\xfa\x56\x1a\x00\x00\x01\x58\x20\x93\x69\x8c\xd5\xe5\xa4\x7f\xbe\xd0\x3d\xa0\x14\xa6\x82\x6c\x26\x76\x69\xd5\xd9\xb1\xe3\x8c\xbf\x1b\xb2\xdb\x51\x8c\x48\xdd\xb1\xa4\x64\x6b\x69\x6e\x64\x67\x6d\x65\x73\x73\x61\x67\x65\x65\x61\x66\x74\x65\x72\x80\x65\x67\x72\x6f\x75\x70\xf6\x66\x64\x6f\x6d\x61\x69\x6e\x6c\x69\x64\x2e\x65\x76\x65\x6e\x74\x73\x2e\x76\x31 b:\x87\x01\x58\x20\x8a\x88\xe3\xdd\x74\x09\xf1\x95\xfd\x52\xdb\x2d\x3c\xba\x5d\x72\xca\x67\x09\xbf\x1d\x94\x12\x1b\xf3\x74\x88\x01\xb4\x0f\x6f\x5c\x58\x40\x29\x77\x93\xb0\x91\xce\x95\xe0\xd4\xca\x08\x2b\xc5\xbd\x62\x47\xff\xb8\xd7\x7c\x22\xe4\xfd\x3e\xbd\xc5\x1a\xca\x71\xd6\x8e\x93\x43\xaa\x84\x1f\xf7\xa5\x82\x28\xc7\x9b\xe9\x93\x26\x14\xcd\x1c\xcd\x83\x05\x69\xec\x23\x43\xa6\xd1\x27\x99\x41\x07\xc2\xfe\x04\x00\x01\x58\x20\x93\x69\x8c\xd5\xe5\xa4\x7f\xbe\xd0\x3d\xa0\x14\xa6\x82\x6c\x26\x76\x69\xd5\xd9\xb1\xe3\x8c\xbf\x1b\xb2\xdb\x51\x8c\x48\xdd\xb1\xa4\x64\x6b\x69\x6e\x64\x65\x72\x69\x76\x61\x6c\x65\x61\x66\x74\x65\x72\x80\x65\x67\x72\x6f\x75\x70\xf6\x66\x64\x6f\x6d\x61\x69\x6e\x6c\x69\x64\x2e\x65\x76\x65\x6e\x74\x73\x2e\x76\x31 b:\x86\x01\x58\x20\x81\x39\x77\x0e\xa8\x7d\x17\x5f\x56\xa3\x54\x66\xc3\x4c\x7e\xcc\xcb\x8d\x8a\x91\xb4\xee\x37\xa2\x5d\xf6\x0f\x5b\x8f\xc9\xb3\x94\x58\x40\x57\x9d\x33\xb9\xd7\x35\x55\x6f\x82\x14\x59\x32\xb1\x0a\x04\xfb\xb2\x93\x1d\x63\x7f\x06\x90\x2f\xde\xdd\xf8\x6a\x6f\x0f\xf5\x9c\xba\x0f\x39\x92\xab\x0d\x1d\xbe\x3a\xc7\x73\xe5\xce\x4b\x22\x64\xcf\x03\x2d\x31\x10\x14\xb0\x3a\x20\x59\x90\x3c\xff\xd9\x2b\x05\x00\x00\xa4\x64\x6b\x69\x6e\x64\x67\x6d\x65\x73\x73\x61\x67\x65\x65\x61\x66\x74\x65\x72\x81\x58\x20\xae\x52\xd9\xae\xc8\xa5\xa0\x2f\xa9\x59\x3e\xcb\xf0\x8c\xe7\x97\x25\xe3\xc3\x9f\x32\x19\xf4\x8b\xb5\x1b\x4d\xdd\x37\x7e\x3b\x98\x65\x67\x72\x6f\x75\x70\xf6\x66\x64\x6f\x6d\x61\x69\x6e\x6c\x69\x64\x2e\x65\x76\x65\x6e\x74\x73\x2e\x76\x31 ok +# the same event twice +ingest b:\x86\x01\x58\x20\x8a\x88\xe3\xdd\x74\x09\xf1\x95\xfd\x52\xdb\x2d\x3c\xba\x5d\x72\xca\x67\x09\xbf\x1d\x94\x12\x1b\xf3\x74\x88\x01\xb4\x0f\x6f\x5c\x58\x40\xf6\xd9\x3d\xac\x1b\x09\xa4\xcf\xf3\x59\x14\xd5\x78\x09\x52\x16\x59\x81\xf9\x8f\x8f\x35\x74\x88\x65\x84\x64\xe2\xa5\xae\x8a\x88\x32\x9e\x69\x9b\x88\x87\x8c\x54\xd4\x2c\xc2\x59\x18\xa9\x56\x17\x3a\x45\x94\xaf\x21\xd2\x9b\x3b\x81\xdb\x99\x51\x37\xd5\x5e\x00\x00\x00\xa4\x64\x6b\x69\x6e\x64\x67\x6d\x65\x73\x73\x61\x67\x65\x65\x61\x66\x74\x65\x72\x80\x65\x67\x72\x6f\x75\x70\xf6\x66\x64\x6f\x6d\x61\x69\x6e\x6c\x69\x64\x2e\x65\x76\x65\x6e\x74\x73\x2e\x76\x31 b:\x86\x01\x58\x20\x8a\x88\xe3\xdd\x74\x09\xf1\x95\xfd\x52\xdb\x2d\x3c\xba\x5d\x72\xca\x67\x09\xbf\x1d\x94\x12\x1b\xf3\x74\x88\x01\xb4\x0f\x6f\x5c\x58\x40\xf6\xd9\x3d\xac\x1b\x09\xa4\xcf\xf3\x59\x14\xd5\x78\x09\x52\x16\x59\x81\xf9\x8f\x8f\x35\x74\x88\x65\x84\x64\xe2\xa5\xae\x8a\x88\x32\x9e\x69\x9b\x88\x87\x8c\x54\xd4\x2c\xc2\x59\x18\xa9\x56\x17\x3a\x45\x94\xaf\x21\xd2\x9b\x3b\x81\xdb\x99\x51\x37\xd5\x5e\x00\x00\x00\xa4\x64\x6b\x69\x6e\x64\x67\x6d\x65\x73\x73\x61\x67\x65\x65\x61\x66\x74\x65\x72\x80\x65\x67\x72\x6f\x75\x70\xf6\x66\x64\x6f\x6d\x61\x69\x6e\x6c\x69\x64\x2e\x65\x76\x65\x6e\x74\x73\x2e\x76\x31 ok +# a signature with one bit flipped +ingest b:\x86\x01\x58\x20\x8a\x88\xe3\xdd\x74\x09\xf1\x95\xfd\x52\xdb\x2d\x3c\xba\x5d\x72\xca\x67\x09\xbf\x1d\x94\x12\x1b\xf3\x74\x88\x01\xb4\x0f\x6f\x5c\x58\x40\xf6\xd9\x3d\xac\x1b\x09\xa4\xcf\xf3\x59\x15\xd5\x78\x09\x52\x16\x59\x81\xf9\x8f\x8f\x35\x74\x88\x65\x84\x64\xe2\xa5\xae\x8a\x88\x32\x9e\x69\x9b\x88\x87\x8c\x54\xd4\x2c\xc2\x59\x18\xa9\x56\x17\x3a\x45\x94\xaf\x21\xd2\x9b\x3b\x81\xdb\x99\x51\x37\xd5\x5e\x00\x00\x00\xa4\x64\x6b\x69\x6e\x64\x67\x6d\x65\x73\x73\x61\x67\x65\x65\x61\x66\x74\x65\x72\x80\x65\x67\x72\x6f\x75\x70\xf6\x66\x64\x6f\x6d\x61\x69\x6e\x6c\x69\x64\x2e\x65\x76\x65\x6e\x74\x73\x2e\x76\x31 b:\x86\x01\x58\x20\x8a\x88\xe3\xdd\x74\x09\xf1\x95\xfd\x52\xdb\x2d\x3c\xba\x5d\x72\xca\x67\x09\xbf\x1d\x94\x12\x1b\xf3\x74\x88\x01\xb4\x0f\x6f\x5c\x58\x40\xf6\xd9\x3d\xac\x1b\x09\xa4\xcf\xf3\x59\x14\xd5\x78\x09\x52\x16\x59\x81\xf9\x8f\x8f\x35\x74\x88\x65\x84\x64\xe2\xa5\xae\x8a\x88\x32\x9e\x69\x9b\x88\x87\x8c\x54\xd4\x2c\xc2\x59\x18\xa9\x56\x17\x3a\x45\x94\xaf\x21\xd2\x9b\x3b\x81\xdb\x99\x51\x37\xd5\x5e\x00\x00\x00\xa4\x64\x6b\x69\x6e\x64\x67\x6d\x65\x73\x73\x61\x67\x65\x65\x61\x66\x74\x65\x72\x80\x65\x67\x72\x6f\x75\x70\xf6\x66\x64\x6f\x6d\x61\x69\x6e\x6c\x69\x64\x2e\x65\x76\x65\x6e\x74\x73\x2e\x76\x31 ok +# bytes that are not CBOR +ingest b:\xff\x00\x20\x6e\x6f\x74\x20\x61\x6e\x20\x65\x76\x65\x6e\x74 b:\x86\x01\x58\x20\x8a\x88\xe3\xdd\x74\x09\xf1\x95\xfd\x52\xdb\x2d\x3c\xba\x5d\x72\xca\x67\x09\xbf\x1d\x94\x12\x1b\xf3\x74\x88\x01\xb4\x0f\x6f\x5c\x58\x40\xf6\xd9\x3d\xac\x1b\x09\xa4\xcf\xf3\x59\x14\xd5\x78\x09\x52\x16\x59\x81\xf9\x8f\x8f\x35\x74\x88\x65\x84\x64\xe2\xa5\xae\x8a\x88\x32\x9e\x69\x9b\x88\x87\x8c\x54\xd4\x2c\xc2\x59\x18\xa9\x56\x17\x3a\x45\x94\xaf\x21\xd2\x9b\x3b\x81\xdb\x99\x51\x37\xd5\x5e\x00\x00\x00\xa4\x64\x6b\x69\x6e\x64\x67\x6d\x65\x73\x73\x61\x67\x65\x65\x61\x66\x74\x65\x72\x80\x65\x67\x72\x6f\x75\x70\xf6\x66\x64\x6f\x6d\x61\x69\x6e\x6c\x69\x64\x2e\x65\x76\x65\x6e\x74\x73\x2e\x76\x31 ok From d19d22554eb4a65e391147dacc9c63c6bed9c333 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 11 Oct 2026 20:02:34 -0500 Subject: [PATCH 14/30] build(rust): add p2panda-store without its default features [P1.6] The store traits need p2panda-store. Default features enable sqlite, which pulls sqlx, so they are off. The lock change is additive: async-stream and async-stream-impl, and p2panda-store's edge from the id crate. p2panda-sync is not added: its own p2panda-store dependency line enables the default features, so sqlite would return (explainers section 14). --- pkgs/id/Cargo.lock | 33 +++++++++++++++++++++++++++++++++ pkgs/id/Cargo.toml | 2 ++ 2 files changed, 35 insertions(+) diff --git a/pkgs/id/Cargo.lock b/pkgs/id/Cargo.lock index 6aa239a099..b387e08a08 100644 --- a/pkgs/id/Cargo.lock +++ b/pkgs/id/Cargo.lock @@ -293,6 +293,28 @@ dependencies = [ "tokio", ] +[[package]] +name = "async-stream" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5a71a6f37880a80d1d7f19efd781e4b5de42c88f0722cc13bcb6cc2cfe8476" +dependencies = [ + "async-stream-impl", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-stream-impl" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "async-trait" version = "0.1.92" @@ -2681,6 +2703,7 @@ dependencies = [ "libc", "mime_guess", "p2panda-core", + "p2panda-store", "postcard", "proptest", "qrcode", @@ -4196,6 +4219,16 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "p2panda-store" +version = "0.7.1" +source = "git+https://github.com/p2panda/p2panda?rev=3e84cac48bba05c6857cce2ec433862b97f8d53c#3e84cac48bba05c6857cce2ec433862b97f8d53c" +dependencies = [ + "async-stream", + "futures-util", + "p2panda-core", +] + [[package]] name = "p384" version = "0.14.0" diff --git a/pkgs/id/Cargo.toml b/pkgs/id/Cargo.toml index 69b3346ca5..458a691ece 100644 --- a/pkgs/id/Cargo.toml +++ b/pkgs/id/Cargo.toml @@ -52,6 +52,8 @@ iroh-blobs = "0.103" iroh-docs = "0.101" iroh-gossip = { version = "0.101", features = ["net"] } p2panda-core = { git = "https://github.com/p2panda/p2panda", rev = "3e84cac48bba05c6857cce2ec433862b97f8d53c" } +# Store traits only. The default features would pull in SQLite (explainers section 14). +p2panda-store = { git = "https://github.com/p2panda/p2panda", rev = "3e84cac48bba05c6857cce2ec433862b97f8d53c", default-features = false } postcard = { version = "1", features = ["alloc"] } rand = "0.10" redb = "=4.3.0" From d2b1a6add3d745e1baa369ca201715407924d6e0 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 11 Oct 2026 20:02:47 -0500 Subject: [PATCH 15/30] feat(rust): p2panda-store traits over the redb event store [P1.6] SharedEventStore wraps the event store in a shared read/write lock, so it can be cloned and implements p2panda-store's LogStore and TopicStore. The log is one author's chain (ChainLog, decision N4), and the topic is a group hash. Heights, sizes, entries and the latest entry read the applied prefix, so they stop at a fork point. Methods the sync path does not use return Unsupported with a reason. Streams read a page at a time under the read lock. The new EventStore::applied_events accessor is a read-only range scan. Tests cover an empty store, several ingests, a fork, paging past one page, topic resolution, the refusals, clones, and a poisoned lock. The LogSync session test is not in this commit: p2panda-sync would bring SQLite back. --- pkgs/id/src/event_store/mod.rs | 95 ++++ pkgs/id/src/lib.rs | 1 + pkgs/id/src/store_traits.rs | 893 +++++++++++++++++++++++++++++++++ 3 files changed, 989 insertions(+) create mode 100644 pkgs/id/src/store_traits.rs diff --git a/pkgs/id/src/event_store/mod.rs b/pkgs/id/src/event_store/mod.rs index b9bfb4994c..d548542dab 100644 --- a/pkgs/id/src/event_store/mod.rs +++ b/pkgs/id/src/event_store/mod.rs @@ -719,6 +719,49 @@ pub(crate) fn store_fork( Ok(()) } +impl EventStore { + /// The applied events of `author` with sequence numbers in `(after, until]`, in sequence + /// order, at most `limit` of them. `after` is exclusive and `until` is inclusive. `None` + /// leaves that side open. Events past a fork point are stored but not applied, so they are + /// not returned. + /// + /// # Errors + /// + /// Returns a redb error if the read fails, or [`StoreError::Corrupt`]. + pub fn applied_events( + &self, + author: &AuthorKey, + after: Option, + until: Option, + limit: usize, + ) -> Result, StoreError> { + let txn = self.db.begin_read()?; + let chains = txn.open_table(CHAINS)?; + let Some(chain_row) = chains.get(author.as_slice())? else { + return Ok(Vec::new()); + }; + let Some(last) = Chain::decode(chain_row.value())?.next_seq.checked_sub(1) else { + return Ok(Vec::new()); + }; + let last = until.map_or(last, |until| until.min(last)); + let first = match after { + Some(after) => after.checked_add(1), + None => Some(0), + }; + let Some(first) = first.filter(|first| *first <= last) else { + return Ok(Vec::new()); + }; + let events = txn.open_table(EVENTS)?; + let (start, end) = (position_key(author, first), position_key(author, last)); + let mut found = Vec::new(); + for row in events.range(start.as_slice()..=end.as_slice())?.take(limit) { + let (_position, bytes) = row?; + found.push(decode_stored(bytes.value())?); + } + Ok(found) + } +} + #[cfg(test)] #[allow(clippy::unwrap_used, clippy::expect_used)] mod tests { @@ -924,4 +967,56 @@ mod tests { Err(StoreError::Corrupt(_)) )); } + + #[test] + fn test_applied_events_is_the_applied_prefix_in_range() { + let (_dir, mut store) = open_temp(); + let signer = key(16); + let who = author(&signer); + let events = chain_of(&signer, 4); + for event in &events { + assert!(matches!( + store.ingest(&event.bytes, 0).unwrap(), + Ingest::Accepted { .. } + )); + } + let seqs = |found: Vec| -> Vec { + found.iter().map(|event| event.header.seq_num).collect() + }; + assert_eq!( + seqs(store.applied_events(&who, None, None, 10).unwrap()), + vec![0, 1, 2, 3] + ); + assert_eq!( + seqs(store.applied_events(&who, Some(0), Some(2), 10).unwrap()), + vec![1, 2] + ); + assert_eq!( + seqs(store.applied_events(&who, None, None, 2).unwrap()), + vec![0, 1] + ); + assert!( + store + .applied_events(&who, Some(3), None, 10) + .unwrap() + .is_empty() + ); + assert!( + store + .applied_events(&author(&key(17)), None, None, 10) + .unwrap() + .is_empty() + ); + // A fork at seq 2 leaves seq 0 and 1 applied. Seq 3 stays stored, but it is not returned. + let rival = sign(&signer, 2, Some(events[1].id), None, ext("rival", None)).unwrap(); + assert!(matches!( + store.ingest(&rival.bytes, 0).unwrap(), + Ingest::Fork { seq: 2, .. } + )); + assert_eq!( + seqs(store.applied_events(&who, None, None, 10).unwrap()), + vec![0, 1] + ); + assert!(store.event(&who, 3).unwrap().is_some()); + } } diff --git a/pkgs/id/src/lib.rs b/pkgs/id/src/lib.rs index 112054c2b9..4ed2f2c54e 100644 --- a/pkgs/id/src/lib.rs +++ b/pkgs/id/src/lib.rs @@ -187,6 +187,7 @@ pub mod repl; #[cfg(feature = "sandbox")] pub mod sandbox; pub mod store; +pub mod store_traits; pub mod tags; #[cfg(test)] mod test_forgeries; diff --git a/pkgs/id/src/store_traits.rs b/pkgs/id/src/store_traits.rs new file mode 100644 index 0000000000..263ba71da4 --- /dev/null +++ b/pkgs/id/src/store_traits.rs @@ -0,0 +1,893 @@ +//! The event store behind p2panda-store's traits. +//! +//! [`SharedEventStore`] wraps an [`EventStore`] so that it can be cloned and shared, and +//! implements the two traits that p2panda-sync's `LogSync` and `TopicLogSync` read through: +//! `LogStore` and `TopicStore`. +//! +//! - A **log** is one author's chain. [`ChainLog`] is the only log id, because each device has +//! one chain and the group is an attribute of its events, not a log (decision N4). +//! - A **topic** is a group hash. `TopicStore::resolve` lists the authors with an applied event +//! in that group, each with its one log. +//! - A store's log is its **applied prefix**. Events past a fork point are stored but not +//! applied, so heights, sizes, entries and the latest entry stop at the fork point. Two stores +//! with the same applied state report the same logs. +//! +//! The methods that the sync path does not use return [`TraitStoreError::Unsupported`], with the +//! reason, rather than a guess. Auth state, fork proofs and waiting events are not part of these +//! traits, and stay in the event store's own tables. + +use std::collections::{BTreeMap, BTreeSet, VecDeque}; +use std::future::{Future, ready}; +use std::pin::Pin; +use std::sync::{Arc, RwLock}; +use std::task::{Context, Poll}; + +use futures_lite::Stream; +use p2panda_core::{ + AnyOperation, Hash, HeaderError, IdentityError, RawOperation, SeqNum, VerifyingKey, +}; +use p2panda_store::logs::{LogEntry, LogStore, LogStream}; +use p2panda_store::topics::TopicStore; +use serde::{Deserialize, Serialize}; + +use crate::chain::Event; +use crate::event_store::{EventStore, Ingest, StoreError}; +use crate::waiting::AuthorKey; + +/// Entries read per page. A page takes the read lock once, so a stream never holds the lock +/// between polls, and a long log is never held in memory at once. +const PAGE: usize = 64; + +/// The one log an author has: their chain. Decision N4: one log per device, with the group carried +/// on each event, rather than one log per group. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +pub struct ChainLog; + +/// Why a store trait method failed. +#[derive(Debug, thiserror::Error)] +pub enum TraitStoreError { + /// The event store failed. See [`StoreError`]. + #[error(transparent)] + Store(#[from] StoreError), + /// A stored event does not decode as an operation. Events are verified when they are + /// accepted, so this means the file changed outside the store. + #[error("stored event is not a valid operation: {0}")] + Operation(#[from] HeaderError), + /// A stored author key is not a valid public key. As with an invalid event, the file changed + /// outside the store. + #[error("stored author key is not a valid public key: {0}")] + Author(#[from] IdentityError), + /// A count or a byte total does not fit the `u32` that the trait returns. + #[error("log size does not fit in a u32")] + Overflow, + /// Another thread panicked while it held the store's lock. + #[error("event store lock is poisoned")] + Poisoned, + /// The trait method is not implemented. The message says why. + #[error("not implemented: {0}")] + Unsupported(&'static str), + /// The store returned a page that did not start after the stream's cursor, so the stream + /// would repeat it forever. + #[error("log stream did not advance past its cursor")] + Stalled, +} + +/// A clonable handle to one event store that implements p2panda-store's traits. +/// +/// Trait reads share the store's read lock. [`SharedEventStore::ingest`] takes the write lock. +#[derive(Clone, Debug)] +pub struct SharedEventStore { + inner: Arc>, +} + +impl SharedEventStore { + /// Shares `store` between the clones of this handle. + pub fn new(store: EventStore) -> Self { + Self { + inner: Arc::new(RwLock::new(store)), + } + } + + /// Verifies and applies one received event. See [`EventStore::ingest`]. + /// + /// # Errors + /// + /// Returns [`TraitStoreError::Store`] for a redb or corruption error, and + /// [`TraitStoreError::Poisoned`] if another thread panicked while it held the lock. + pub fn ingest(&self, bytes: &[u8], now_ms: u64) -> Result { + let mut store = self + .inner + .write() + .map_err(|_err| TraitStoreError::Poisoned)?; + Ok(store.ingest(bytes, now_ms)?) + } + + /// Checks the store's own rows. See [`EventStore::check_invariants`]. + /// + /// # Errors + /// + /// Returns [`TraitStoreError::Store`] for the first mismatch, or a redb error. + pub fn check_invariants(&self) -> Result<(), TraitStoreError> { + self.read(|store| Ok(store.check_invariants()?)) + } + + /// Runs `op` under the read lock. + fn read( + &self, + op: impl FnOnce(&EventStore) -> Result, + ) -> Result { + let store = self + .inner + .read() + .map_err(|_err| TraitStoreError::Poisoned)?; + op(&store) + } + + /// The newest applied entry of `author`. + fn latest_entry(&self, author: &VerifyingKey) -> Result, TraitStoreError> { + let author = *author.as_bytes(); + let latest = self.read(|store| { + let Some(height) = applied_height(store, &author)? else { + return Ok(None); + }; + Ok(store.event(&author, height)?) + })?; + latest.as_ref().map(operation_of).transpose() + } + + /// The applied height of `author` in each requested log. + fn heights( + &self, + author: &VerifyingKey, + logs: &[ChainLog], + ) -> Result>, TraitStoreError> { + let author = *author.as_bytes(); + let height = self.read(|store| Ok(applied_height(store, &author)?))?; + Ok(match height { + Some(height) if !logs.is_empty() => { + Some(logs.iter().map(|log| (*log, height)).collect()) + } + _ => None, + }) + } + + /// The count and byte total of `author`'s applied events in `(after, until]`. + fn log_size( + &self, + author: &VerifyingKey, + after: Option, + until: Option, + ) -> Result, TraitStoreError> { + let author = *author.as_bytes(); + // One read lock for the whole sum, so the count and the bytes come from one state. + self.read(|store| { + if applied_height(store, &author)?.is_none() { + return Ok(None); + } + let (mut count, mut bytes) = (0u32, 0u32); + let mut cursor = after; + loop { + let page = store.applied_events(&author, cursor, until, PAGE)?; + let Some(last) = page.last() else { + break; + }; + for event in &page { + count = count.checked_add(1).ok_or(TraitStoreError::Overflow)?; + let size = u32::try_from(event.bytes.len()) + .ok() + .and_then(|len| len.checked_add(event.header.payload_size)) + .ok_or(TraitStoreError::Overflow)?; + bytes = bytes.checked_add(size).ok_or(TraitStoreError::Overflow)?; + } + cursor = Some(last.header.seq_num); + if page.len() < PAGE { + break; + } + } + Ok(Some((count, bytes))) + }) + } + + /// The authors with an applied event in `topic`, each with its one log. An event past a fork + /// point does not count. + fn authors_in( + &self, + topic: &Hash, + ) -> Result>, TraitStoreError> { + let authors = self.read(|store| { + let mut authors = BTreeSet::new(); + for (author, seq) in store.group_members(topic)? { + let applied = applied_height(store, &author)?; + if applied.is_some_and(|height| seq <= height) { + authors.insert(author); + } + } + Ok(authors) + })?; + let mut resolved = BTreeMap::new(); + for author in authors { + resolved.insert(VerifyingKey::from_bytes(&author)?, vec![ChainLog]); + } + Ok(resolved) + } +} + +/// The sequence number of the author's last applied event, or `None` when none applies. +fn applied_height(store: &EventStore, author: &AuthorKey) -> Result, StoreError> { + let Some(chain) = store.chain(author)? else { + return Ok(None); + }; + Ok(chain.next_seq.checked_sub(1)) +} + +/// The operation the sync protocol sends for a stored event: its header bytes, with no body. +/// The body is not part of an event, and only its size is declared in the header. +fn operation_of(event: &Event) -> Result { + let raw: RawOperation = (event.bytes.clone(), None); + Ok(AnyOperation::try_from(raw)?) +} + +/// One author's log, streamed a page at a time. +struct LogEntries { + store: SharedEventStore, + author: AuthorKey, + /// Entries at or below this sequence number have been read. `None` means none have. + after: Option, + until: Option, + page_size: usize, + /// The current page, not yet streamed. + page: VecDeque, + /// Set after the last entry or after an error, so the stream ends. + done: bool, +} + +impl LogEntries { + const fn new( + store: SharedEventStore, + author: AuthorKey, + after: Option, + until: Option, + page_size: usize, + ) -> Self { + Self { + store, + author, + after, + until, + page_size, + page: VecDeque::new(), + done: false, + } + } + + /// Reads the page after the cursor and moves the cursor past it. An empty page is the end. + fn next_page(&mut self) -> Result, TraitStoreError> { + let (author, after, until, page_size) = + (self.author, self.after, self.until, self.page_size); + let page = self + .store + .read(|store| Ok(store.applied_events(&author, after, until, page_size)?))?; + if let Some(first) = page.first() { + // A page must start after the cursor. Otherwise the same page would come back forever. + if after.is_some_and(|after| first.header.seq_num <= after) { + return Err(TraitStoreError::Stalled); + } + } + if let Some(last) = page.last() { + self.after = Some(last.header.seq_num); + } + Ok(page.into()) + } +} + +impl Stream for LogEntries { + type Item = Result, TraitStoreError>; + + fn poll_next(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll> { + let this = self.get_mut(); + if this.done { + return Poll::Ready(None); + } + if this.page.is_empty() { + match this.next_page() { + Ok(page) => this.page = page, + Err(err) => { + this.done = true; + return Poll::Ready(Some(Err(err))); + } + } + } + let Some(event) = this.page.pop_front() else { + this.done = true; + return Poll::Ready(None); + }; + match operation_of(&event) { + Ok(entry) => Poll::Ready(Some(Ok(LogEntry { + entry, + log_id: ChainLog, + bytes: event.bytes, + }))), + Err(err) => { + this.done = true; + Poll::Ready(Some(Err(err))) + } + } + } +} + +impl LogStore for SharedEventStore { + type Error = TraitStoreError; + + /// The newest applied entry. The log id is ignored: an author has one log. + fn get_latest_entry( + &self, + author: &VerifyingKey, + _log_id: &ChainLog, + ) -> impl Future, TraitStoreError>> { + ready(self.latest_entry(author)) + } + + /// Not implemented. The SQLite store reads this inside a transaction permit, and this store + /// has no permits. [`SharedEventStore::ingest`] is the atomic write path. + fn get_latest_entry_tx( + &self, + _author: &VerifyingKey, + _log_id: &ChainLog, + ) -> impl Future, TraitStoreError>> { + ready(Err(TraitStoreError::Unsupported( + "transaction permits are not implemented; ingest is the atomic write path", + ))) + } + + /// The applied height of each requested log. `None` when no log was requested, or when the + /// author has no applied event. + fn get_log_heights( + &self, + author: &VerifyingKey, + logs: &[ChainLog], + ) -> impl Future>, TraitStoreError>> { + ready(self.heights(author, logs)) + } + + /// The count and byte total of the applied events in `(after, until]`. The bytes are the + /// header bytes plus the body size each header declares, as the SQLite store counts them. + /// `None` when the author has no applied event. An empty range is `Some((0, 0))`. + fn get_log_size( + &self, + author: &VerifyingKey, + _log_id: &ChainLog, + after: Option, + until: Option, + ) -> impl Future, TraitStoreError>> { + ready(self.log_size(author, after, until)) + } + + /// The applied entries in `(after, until]`, in sequence order. Each is streamed a page at a + /// time, and each page takes the read lock once. + fn log_entries( + &self, + author: &VerifyingKey, + _log_id: &ChainLog, + after: Option, + until: Option, + ) -> Result, TraitStoreError> { + let entries = LogEntries::new(self.clone(), *author.as_bytes(), after, until, PAGE); + Ok(Box::pin(entries)) + } + + /// Not implemented. Pruning has an open design question: whether it removes whole events or + /// only their bodies (task 10). + fn prune_entries( + &self, + _author: &VerifyingKey, + _log_id: &ChainLog, + _until: &SeqNum, + ) -> impl Future> { + ready(Err(TraitStoreError::Unsupported( + "pruning is an open design question (task 10): headers or only bodies", + ))) + } +} + +impl TopicStore for SharedEventStore { + type Error = TraitStoreError; + + /// Not implemented. A topic's membership is each event's group, which ingest writes, so there + /// is no association table to add to. + fn associate( + &self, + _topic: &Hash, + _author: &VerifyingKey, + _data_id: &ChainLog, + ) -> impl Future> { + ready(Err(TraitStoreError::Unsupported( + "a topic's membership is each event's group, written by ingest", + ))) + } + + /// Not implemented, for the same reason as `associate`. + fn remove( + &self, + _topic: &Hash, + _author: &VerifyingKey, + _data_id: &ChainLog, + ) -> impl Future> { + ready(Err(TraitStoreError::Unsupported( + "a topic's membership is each event's group, written by ingest", + ))) + } + + /// The authors with an applied event in the group, each with its one log. An event past a + /// fork point does not count. + fn resolve( + &self, + topic: &Hash, + ) -> impl Future>, TraitStoreError>> { + ready(self.authors_in(topic)) + } + + /// Not implemented. `TopicLogSync` resolves from a topic, not to topics. + fn resolve_topics( + &self, + _author: &VerifyingKey, + _data_id: &ChainLog, + ) -> impl Future, TraitStoreError>> { + ready(Err(TraitStoreError::Unsupported( + "reverse topic lookup is not needed by `TopicLogSync`", + ))) + } + + /// Not implemented, for the same reason as `resolve_topics`. + fn topics(&self) -> impl Future, TraitStoreError>> { + ready(Err(TraitStoreError::Unsupported( + "listing all topics is not needed by `TopicLogSync`", + ))) + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use futures_lite::StreamExt; + use p2panda_core::SigningKey; + + use super::*; + use crate::chain::{ChainExt, sign}; + + fn key(n: u8) -> SigningKey { + SigningKey::from_bytes(&[n; 32]) + } + + fn author_of(key: &SigningKey) -> VerifyingKey { + key.verifying_key() + } + + fn group(n: u8) -> Hash { + Hash::digest([n]) + } + + /// One signed event of `signer`'s chain, with an optional body. + fn event( + signer: &SigningKey, + seq: SeqNum, + backlink: Option, + group: Option, + kind: &str, + body: Option<&[u8]>, + ) -> Event { + let ext = ChainExt { + kind: kind.to_owned(), + group, + after: Vec::new(), + }; + sign(signer, seq, backlink, body, ext).unwrap() + } + + /// The first `count` events of `signer`'s chain, all in `group`, each naming the one before. + fn chain_of(signer: &SigningKey, count: SeqNum, group: Option) -> Vec { + let mut events: Vec = Vec::new(); + for seq in 0..count { + let backlink = events.last().map(|event| event.id); + events.push(event(signer, seq, backlink, group, "message", None)); + } + events + } + + fn open() -> (tempfile::TempDir, SharedEventStore) { + let dir = tempfile::tempdir().unwrap(); + let store = EventStore::open(dir.path()).unwrap(); + (dir, SharedEventStore::new(store)) + } + + fn ingest_all(store: &SharedEventStore, events: &[Event]) { + for event in events { + let outcome = store.ingest(&event.bytes, 0).unwrap(); + assert_eq!( + outcome, + Ingest::Accepted { + id: event.id, + released: Vec::new(), + } + ); + } + } + + /// The `(count, bytes)` that the trait must report for `events`: header bytes plus the + /// declared body sizes. + fn sized(events: &[Event]) -> (u32, u32) { + let count = u32::try_from(events.len()).unwrap(); + let bytes = events + .iter() + .map(|event| u32::try_from(event.bytes.len()).unwrap() + event.header.payload_size) + .sum(); + (count, bytes) + } + + async fn drain(mut stream: S) -> Vec> + where + S: Stream, TraitStoreError>> + Unpin, + { + let mut entries = Vec::new(); + while let Some(entry) = stream.next().await { + entries.push(entry.unwrap()); + } + entries + } + + async fn entries_of( + store: &SharedEventStore, + who: &VerifyingKey, + after: Option, + until: Option, + ) -> Vec> { + drain(store.log_entries(who, &ChainLog, after, until).unwrap()).await + } + + /// The streamed entry is the stored event, in the form the sync protocol sends. + fn assert_is_event(entry: &LogEntry, event: &Event) { + assert_eq!(entry.log_id, ChainLog); + assert_eq!(entry.bytes, event.bytes); + assert_eq!(entry.entry.hash, event.id); + assert_eq!(entry.entry.header.seq_num, event.header.seq_num); + assert_eq!(entry.entry.header.verifying_key, event.header.verifying_key); + assert_eq!(entry.entry.header.backlink, event.header.backlink); + assert!( + entry.entry.body.is_none(), + "bodies are not sent with events" + ); + } + + #[tokio::test] + async fn test_an_empty_store_has_no_log_for_any_author() { + let (_dir, store) = open(); + let who = author_of(&key(1)); + assert_eq!(store.get_latest_entry(&who, &ChainLog).await.unwrap(), None); + assert_eq!( + store.get_log_heights(&who, &[ChainLog]).await.unwrap(), + None + ); + assert_eq!( + store + .get_log_size(&who, &ChainLog, None, None) + .await + .unwrap(), + None + ); + assert!(entries_of(&store, &who, None, None).await.is_empty()); + assert_eq!(store.resolve(&group(1)).await.unwrap(), BTreeMap::new()); + store.check_invariants().unwrap(); + } + + #[tokio::test] + async fn test_the_latest_entry_and_heights_follow_the_chain() { + let (_dir, store) = open(); + let (alice, bob) = (key(2), key(3)); + let (who_alice, who_bob) = (author_of(&alice), author_of(&bob)); + let alice_events = chain_of(&alice, 5, Some(group(1))); + let bob_events = chain_of(&bob, 2, Some(group(2))); + ingest_all(&store, &alice_events); + ingest_all(&store, &bob_events); + + let latest = store + .get_latest_entry(&who_alice, &ChainLog) + .await + .unwrap() + .expect("alice has an entry"); + assert_eq!(latest.hash, alice_events[4].id); + assert_eq!(latest.header.seq_num, 4); + assert_eq!(latest.header.backlink, Some(alice_events[3].id)); + + assert_eq!( + store + .get_log_heights(&who_alice, &[ChainLog]) + .await + .unwrap(), + Some(BTreeMap::from([(ChainLog, 4)])) + ); + assert_eq!( + store.get_log_heights(&who_bob, &[ChainLog]).await.unwrap(), + Some(BTreeMap::from([(ChainLog, 1)])) + ); + // Asking for no logs asks for nothing, and asking twice for one log names it once. + assert_eq!(store.get_log_heights(&who_alice, &[]).await.unwrap(), None); + assert_eq!( + store + .get_log_heights(&who_alice, &[ChainLog, ChainLog]) + .await + .unwrap(), + Some(BTreeMap::from([(ChainLog, 4)])) + ); + + assert_eq!( + store.resolve(&group(1)).await.unwrap(), + BTreeMap::from([(who_alice, vec![ChainLog])]) + ); + assert_eq!( + store.resolve(&group(2)).await.unwrap(), + BTreeMap::from([(who_bob, vec![ChainLog])]) + ); + store.check_invariants().unwrap(); + } + + #[tokio::test] + async fn test_the_log_size_counts_headers_and_declared_bodies() { + let (_dir, store) = open(); + let alice = key(4); + let who = author_of(&alice); + let mut events: Vec = Vec::new(); + for seq in 0..5 { + let backlink = events.last().map(|event| event.id); + // Every body is non-empty, and the lengths differ, so the sum is not a count. + let body = vec![7u8; 1 + 10 * usize::try_from(seq).unwrap()]; + events.push(event( + &alice, + seq, + backlink, + Some(group(1)), + "message", + Some(&body), + )); + } + ingest_all(&store, &events); + + assert_eq!( + store + .get_log_size(&who, &ChainLog, None, None) + .await + .unwrap(), + Some(sized(&events)) + ); + assert_eq!( + store + .get_log_size(&who, &ChainLog, Some(0), Some(3)) + .await + .unwrap(), + Some(sized(&events[1..=3])) + ); + assert_eq!( + store + .get_log_size(&who, &ChainLog, None, Some(100)) + .await + .unwrap(), + Some(sized(&events)) + ); + // An empty range of an author who has events is zero, not absent. + assert_eq!( + store + .get_log_size(&who, &ChainLog, Some(4), None) + .await + .unwrap(), + Some((0, 0)) + ); + assert_eq!( + store + .get_log_size(&author_of(&key(9)), &ChainLog, None, None) + .await + .unwrap(), + None + ); + } + + #[tokio::test] + async fn test_log_entries_stream_each_position_once_in_order() { + let (_dir, store) = open(); + let alice = key(5); + let who = author_of(&alice); + let events = chain_of(&alice, 5, None); + ingest_all(&store, &events); + let stream = + |after, until| LogEntries::new(store.clone(), *who.as_bytes(), after, until, 2); + + // A page of two makes the stream cross page boundaries. + let all = drain(stream(None, None)).await; + assert_eq!(all.len(), events.len()); + for (entry, event) in all.iter().zip(&events) { + assert_is_event(entry, event); + } + let middle = drain(stream(Some(1), Some(3))).await; + assert_eq!(middle.len(), 2, "after 1 is exclusive, until 3 inclusive"); + assert_is_event(&middle[0], &events[2]); + assert_is_event(&middle[1], &events[3]); + assert!(drain(stream(Some(4), None)).await.is_empty()); + let first = drain(stream(None, Some(0))).await; + assert_eq!(first.len(), 1); + assert_is_event(&first[0], &events[0]); + assert_eq!(entries_of(&store, &who, Some(1), Some(3)).await.len(), 2); + } + + #[tokio::test] + async fn test_a_log_longer_than_one_page_is_streamed_whole() { + let (_dir, store) = open(); + let alice = key(6); + let who = author_of(&alice); + // Three pages: 64, 64 and 3. + let events = chain_of(&alice, 131, None); + ingest_all(&store, &events); + + let entries = entries_of(&store, &who, None, None).await; + assert_eq!(entries.len(), events.len()); + for (entry, event) in entries.iter().zip(&events) { + assert_is_event(entry, event); + } + assert_eq!( + store + .get_log_size(&who, &ChainLog, None, None) + .await + .unwrap() + .map(|(count, _bytes)| count), + Some(131) + ); + store.check_invariants().unwrap(); + } + + #[tokio::test] + async fn test_a_topic_resolves_to_the_authors_applied_in_it() { + let (_dir, store) = open(); + let (alice, bob, carol) = (key(7), key(8), key(9)); + let (topic, other_topic) = (group(1), group(2)); + ingest_all(&store, &chain_of(&alice, 3, Some(topic))); + ingest_all(&store, &chain_of(&bob, 1, Some(topic))); + ingest_all(&store, &chain_of(&carol, 2, Some(other_topic))); + let (who_alice, who_bob, who_carol) = + (author_of(&alice), author_of(&bob), author_of(&carol)); + + assert_eq!( + store.resolve(&topic).await.unwrap(), + BTreeMap::from([(who_alice, vec![ChainLog]), (who_bob, vec![ChainLog])]) + ); + assert_eq!( + store.resolve(&other_topic).await.unwrap(), + BTreeMap::from([(who_carol, vec![ChainLog])]) + ); + assert!(store.resolve(&group(3)).await.unwrap().is_empty()); + } + + #[tokio::test] + async fn test_after_a_fork_only_the_applied_prefix_is_visible() { + let (_dir, store) = open(); + let (alice, bob) = (key(10), key(11)); + let (topic, rival_topic) = (group(4), group(5)); + let who = author_of(&alice); + // Alice: seq 0 outside any group, then seq 1 and seq 2 in `topic`. + let first = event(&alice, 0, None, None, "message", None); + let second = event(&alice, 1, Some(first.id), Some(topic), "message", None); + let third = event(&alice, 2, Some(second.id), Some(topic), "message", None); + ingest_all(&store, std::slice::from_ref(&first)); + ingest_all(&store, &[second.clone(), third.clone()]); + // Alice's rival at seq 1: the same backlink as `second`, so it conflicts with it. + let rival = event(&alice, 1, Some(first.id), Some(rival_topic), "rival", None); + assert_eq!( + store.ingest(&rival.bytes, 0).unwrap(), + Ingest::Fork { + author: *who.as_bytes(), + seq: 1, + } + ); + ingest_all(&store, &chain_of(&bob, 1, Some(topic))); + + // Only seq 0 is applied. Seq 1 and seq 2 are stored, but they are not part of the log. + let latest = store + .get_latest_entry(&who, &ChainLog) + .await + .unwrap() + .expect("seq 0 is applied"); + assert_eq!(latest.hash, first.id); + assert_eq!( + store.get_log_heights(&who, &[ChainLog]).await.unwrap(), + Some(BTreeMap::from([(ChainLog, 0)])) + ); + assert_eq!( + store + .get_log_size(&who, &ChainLog, None, None) + .await + .unwrap(), + Some(sized(std::slice::from_ref(&first))) + ); + let entries = entries_of(&store, &who, None, None).await; + assert_eq!(entries.len(), 1); + assert_is_event(&entries[0], &first); + // A bound past the applied prefix does not reveal the events stored beyond the fork. + assert_eq!( + store + .get_log_size(&who, &ChainLog, None, Some(100)) + .await + .unwrap(), + Some(sized(std::slice::from_ref(&first))) + ); + assert_eq!(entries_of(&store, &who, None, Some(100)).await.len(), 1); + // Alice's events in `topic` are past the fork, so she is not in it. Bob still is. + assert_eq!( + store.resolve(&topic).await.unwrap(), + BTreeMap::from([(author_of(&bob), vec![ChainLog])]) + ); + store.check_invariants().unwrap(); + } + + #[tokio::test] + async fn test_the_methods_outside_the_sync_path_refuse_with_a_reason() { + let (_dir, store) = open(); + let who = author_of(&key(12)); + let topic = group(6); + assert!(matches!( + store.get_latest_entry_tx(&who, &ChainLog).await, + Err(TraitStoreError::Unsupported(_)) + )); + assert!(matches!( + store.prune_entries(&who, &ChainLog, &0).await, + Err(TraitStoreError::Unsupported(_)) + )); + assert!(matches!( + store.associate(&topic, &who, &ChainLog).await, + Err(TraitStoreError::Unsupported(_)) + )); + assert!(matches!( + store.remove(&topic, &who, &ChainLog).await, + Err(TraitStoreError::Unsupported(_)) + )); + assert!(matches!( + store.resolve_topics(&who, &ChainLog).await, + Err(TraitStoreError::Unsupported(_)) + )); + assert!(matches!( + store.topics().await, + Err(TraitStoreError::Unsupported(_)) + )); + } + + #[tokio::test] + async fn test_clones_share_one_store() { + let (_dir, store) = open(); + let other = store.clone(); + let alice = key(13); + ingest_all(&store, &chain_of(&alice, 2, None)); + assert_eq!( + other + .get_log_heights(&author_of(&alice), &[ChainLog]) + .await + .unwrap(), + Some(BTreeMap::from([(ChainLog, 1)])) + ); + } + + #[tokio::test] + #[allow(clippy::panic)] + async fn test_a_poisoned_lock_is_reported_not_unwrapped() { + let (_dir, store) = open(); + let poisoner = store.clone(); + let panicked = std::thread::spawn(move || { + let _guard = poisoner.inner.write().unwrap(); + panic!("poisoning the store lock on purpose"); + }) + .join(); + assert!(panicked.is_err()); + let who = author_of(&key(14)); + assert!(matches!( + store.get_log_heights(&who, &[ChainLog]).await, + Err(TraitStoreError::Poisoned) + )); + assert!(matches!( + store.ingest(&[], 0), + Err(TraitStoreError::Poisoned) + )); + } +} From 8fc776be1f795eb86bbf8a669d7bd31d61344de2 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 11 Oct 2026 20:08:48 -0500 Subject: [PATCH 16/30] test(rust): ingest must detect a fork whatever its backlink [P1.8] Adds the cases that fail on the current ingest. A fork does not unapply the events applied on top of the forked event. A conflict is missed when its backlink is not the applied head, or when the event it conflicts with is held on a missing dependency or waits ahead of the chain. The two conflicting events at one position can also yield different proofs by arrival order. The property generator now makes conflicts with any backlink, forks at any depth, and after hashes on any event, and checks every arrival order against an order-free model of the applied state. The replay adds the minimized cases. An ingest that spins on an event now fails its check after 20 seconds, instead of hanging the run. Red on this commit: the new unit tests, the property test, and six replay cases. --- pkgs/id/src/event_store/ingest.rs | 289 ++++++++++++++++++++- pkgs/id/tests/common/ingest.rs | 46 +++- pkgs/id/tests/event_store_properties.rs | 320 ++++++++++++++++-------- pkgs/id/tests/regressions/ingest.txt | 12 + 4 files changed, 551 insertions(+), 116 deletions(-) diff --git a/pkgs/id/src/event_store/ingest.rs b/pkgs/id/src/event_store/ingest.rs index 53d0ca84b8..65578c8716 100644 --- a/pkgs/id/src/event_store/ingest.rs +++ b/pkgs/id/src/event_store/ingest.rs @@ -367,7 +367,7 @@ fn is_applied(txn: &WriteTransaction, hash: &Hash) -> Result { #[allow(clippy::unwrap_used, clippy::expect_used)] mod tests { use super::*; - use crate::chain::{ChainExt, sign}; + use crate::chain::{sign, ChainExt}; use crate::waiting::WaitingLimits; use p2panda_core::SigningKey; @@ -685,7 +685,7 @@ mod tests { } #[test] - fn test_a_backlink_that_is_not_the_applied_head_is_refused() { + fn test_a_backlink_that_is_not_the_applied_head_is_parked_and_not_stored() { let (_dir, mut store) = open(); let signer = key(13); let who = author(&signer); @@ -698,11 +698,11 @@ mod tests { Vec::new(), "stray", ); - assert_eq!( - ingest(&mut store, &stray), - Ingest::Refused(Refusal::BacklinkMismatch) + assert_eq!(ingest(&mut store, &stray), Ingest::Waiting { id: stray.id }); + assert!( + store.event(&who, 1).unwrap().is_none(), + "a parked event is not stored" ); - assert!(store.event(&who, 1).unwrap().is_none()); assert_eq!(store.chain(&who).unwrap().unwrap().next_seq, 1); store.check_invariants().unwrap(); } @@ -820,4 +820,281 @@ mod tests { assert!(store.fork_proof(&who).unwrap().is_some()); store.check_invariants().unwrap(); } + + /// The IDs of `who`'s applied events, in sequence order. + fn applied_ids(store: &EventStore, who: &AuthorKey) -> Vec { + let next = store.chain(who).unwrap().map_or(0, |chain| chain.next_seq); + (0..next) + .map(|seq| { + store + .event(who, seq) + .unwrap() + .expect("an applied event is stored") + .id + }) + .collect() + } + + /// What a store reports for `who`: the chain row and the fork proof. + fn state_of( + store: &EventStore, + who: &AuthorKey, + ) -> (Option, Option) { + (store.chain(who).unwrap(), store.fork_proof(who).unwrap()) + } + + #[test] + fn test_a_fork_at_sequence_zero_unapplies_an_event_applied_on_top_of_it() { + let (_dir, mut store) = open(); + let (x, y) = (key(20), key(21)); + let x0 = event(&x, 0, None, Vec::new(), "message"); + let y0 = event(&y, 0, None, vec![x0.id], "message"); + let rival = event(&x, 0, None, Vec::new(), "rival"); + ingest_all(&mut store, &[x0, y0.clone()]); + assert_eq!(applied_ids(&store, &author(&y)), vec![y0.id]); + assert_eq!( + ingest(&mut store, &rival), + Ingest::Fork { + author: author(&x), + seq: 0 + } + ); + assert!( + applied_ids(&store, &author(&y)).is_empty(), + "y0 rests on x0, which the fork voided" + ); + assert_eq!( + store.event(&author(&y), 0).unwrap(), + Some(y0), + "y0 stays stored" + ); + assert_eq!(store.chain(&author(&y)).unwrap(), None); + store.check_invariants().unwrap(); + } + + #[test] + fn test_a_fork_unapplies_every_event_that_rests_on_the_voided_ones() { + let (_dir, mut store) = open(); + let (x, y, z) = (key(22), key(23), key(24)); + let x0 = event(&x, 0, None, Vec::new(), "message"); + let x1 = event(&x, 1, Some(x0.id), Vec::new(), "message"); + let y0 = event(&y, 0, None, vec![x1.id], "message"); + let y1 = event(&y, 1, Some(y0.id), Vec::new(), "message"); + let z0 = event(&z, 0, None, vec![y0.id], "message"); + ingest_all(&mut store, &[x0.clone(), x1, y0, y1, z0]); + let rival = event(&x, 1, Some(x0.id), Vec::new(), "rival"); + assert_eq!( + ingest(&mut store, &rival), + Ingest::Fork { + author: author(&x), + seq: 1 + } + ); + assert_eq!(applied_ids(&store, &author(&x)), vec![x0.id]); + assert!( + applied_ids(&store, &author(&y)).is_empty(), + "y0 rests on x1, and y1 on y0" + ); + assert!( + applied_ids(&store, &author(&z)).is_empty(), + "z0 rests on y0" + ); + assert_eq!(store.chain(&author(&z)).unwrap(), None); + store.check_invariants().unwrap(); + } + + #[test] + fn test_a_conflict_with_an_unmatched_backlink_is_detected_in_either_order() { + let signer = key(25); + let who = author(&signer); + let x0 = event(&signer, 0, None, Vec::new(), "message"); + let x1 = event(&signer, 1, Some(x0.id), Vec::new(), "message"); + let stray = event( + &signer, + 1, + Some(Hash::digest(b"not the head")), + Vec::new(), + "stray", + ); + + let (_first_dir, mut first) = open(); + ingest_all(&mut first, &[x0.clone(), x1.clone()]); + assert_eq!( + ingest(&mut first, &stray), + Ingest::Fork { + author: who, + seq: 1 + } + ); + + let (_second_dir, mut second) = open(); + ingest_all(&mut second, std::slice::from_ref(&x0)); + ingest(&mut second, &stray); + assert_eq!( + ingest(&mut second, &x1), + Ingest::Fork { + author: who, + seq: 1 + } + ); + + assert_eq!(state_of(&second, &who), state_of(&first, &who)); + first.check_invariants().unwrap(); + second.check_invariants().unwrap(); + } + + #[test] + fn test_a_conflict_held_on_a_missing_dependency_is_detected_in_either_order() { + let signer = key(26); + let who = author(&signer); + let x0 = event(&signer, 0, None, Vec::new(), "message"); + let missing = Hash::digest(b"an event that is never delivered"); + let held = event(&signer, 1, Some(x0.id), vec![missing], "message"); + let rival = event(&signer, 1, Some(x0.id), Vec::new(), "rival"); + + let (_first_dir, mut first) = open(); + ingest_all(&mut first, std::slice::from_ref(&x0)); + assert_eq!(ingest(&mut first, &held), Ingest::Waiting { id: held.id }); + assert_eq!( + ingest(&mut first, &rival), + Ingest::Fork { + author: who, + seq: 1 + } + ); + + let (_second_dir, mut second) = open(); + ingest_all(&mut second, &[x0.clone(), rival.clone()]); + assert_eq!( + ingest(&mut second, &held), + Ingest::Fork { + author: who, + seq: 1 + } + ); + + assert_eq!(state_of(&second, &who), state_of(&first, &who)); + first.check_invariants().unwrap(); + second.check_invariants().unwrap(); + } + + #[test] + fn test_two_events_ahead_of_the_chain_at_one_position_are_a_fork_in_either_order() { + let signer = key(27); + let who = author(&signer); + let x0 = event(&signer, 0, None, Vec::new(), "message"); + let x1 = event(&signer, 1, Some(x0.id), Vec::new(), "message"); + let x2 = event(&signer, 2, Some(x1.id), Vec::new(), "message"); + let stray = event( + &signer, + 2, + Some(Hash::digest(b"never delivered")), + Vec::new(), + "stray", + ); + + let (_first_dir, mut first) = open(); + assert_eq!(ingest(&mut first, &x2), Ingest::Waiting { id: x2.id }); + assert_eq!( + ingest(&mut first, &stray), + Ingest::Fork { + author: who, + seq: 2 + } + ); + ingest_all(&mut first, &[x0.clone(), x1.clone()]); + + let (_second_dir, mut second) = open(); + ingest_all(&mut second, &[x0.clone(), x1.clone(), x2.clone()]); + assert_eq!( + ingest(&mut second, &stray), + Ingest::Fork { + author: who, + seq: 2 + } + ); + + assert_eq!(state_of(&second, &who), state_of(&first, &who)); + assert_eq!(applied_ids(&first, &who), vec![x0.id, x1.id]); + first.check_invariants().unwrap(); + second.check_invariants().unwrap(); + } + + #[test] + fn test_an_event_ahead_of_its_chain_whose_backlink_is_applied_elsewhere_is_held() { + let (signer, other) = (key(28), key(29)); + let other0 = event(&other, 0, None, Vec::new(), "message"); + let stray = event(&signer, 2, Some(other0.id), Vec::new(), "message"); + let (other0_bytes, stray_bytes) = (other0.bytes.clone(), stray.bytes.clone()); + let who = author(&signer); + let (sent, received) = std::sync::mpsc::channel(); + // The ingest runs on its own thread, so a store that spins fails the test + // instead of hanging it. + std::thread::spawn(move || { + let (_dir, mut store) = open(); + let first = store.ingest(&other0_bytes, 0).unwrap(); + let second = store.ingest(&stray_bytes, 0).unwrap(); + let stored = store.event(&who, 2).unwrap().is_some(); + let _ = sent.send((first, second, stored)); + }); + let (first, second, stored) = received + .recv_timeout(std::time::Duration::from_secs(20)) + .expect("ingest did not return: the event made the store spin"); + assert_eq!( + first, + Ingest::Accepted { + id: other0.id, + released: vec![], + } + ); + assert_eq!(second, Ingest::Waiting { id: stray.id }); + assert!(!stored, "a held event is not stored"); + } + + #[test] + fn test_the_fork_proof_holds_the_two_lowest_ids_whatever_the_order() { + let signer = key(30); + let who = author(&signer); + let x0 = event(&signer, 0, None, Vec::new(), "message"); + let x1 = event(&signer, 1, Some(x0.id), Vec::new(), "message"); + // Two rivals below the original's ID, so the proof must leave the original out. + let below: Vec = (0..16) + .map(|n| event(&signer, 1, Some(x0.id), Vec::new(), &format!("rival {n}"))) + .filter(|rival| rival.id.as_bytes() < x1.id.as_bytes()) + .collect(); + assert!( + below.len() >= 2, + "the fixture needs two rivals below the original" + ); + let (rival_a, rival_b) = (below[0].clone(), below[1].clone()); + let lowest_two = sorted(&rival_a.id, &rival_b.id); + + let orders = [ + vec![x0.clone(), x1.clone(), rival_a.clone(), rival_b.clone()], + vec![x0.clone(), rival_a.clone(), rival_b.clone(), x1.clone()], + vec![x0, rival_b, x1, rival_a], + ]; + let mut states = Vec::new(); + for order in &orders { + let (_dir, mut store) = open(); + for event in order { + store.ingest(&event.bytes, 0).unwrap(); + } + let proof = store + .fork_proof(&who) + .unwrap() + .expect("a fork proof is stored"); + assert_eq!( + [proof.first.id, proof.second.id], + lowest_two, + "the proof holds the two lowest IDs at the fork point" + ); + store.check_invariants().unwrap(); + states.push(state_of(&store, &who)); + } + assert!( + states.windows(2).all(|pair| pair[0] == pair[1]), + "the orders reach different states: {states:?}" + ); + } } diff --git a/pkgs/id/tests/common/ingest.rs b/pkgs/id/tests/common/ingest.rs index 1038e07ccd..10de646f4b 100644 --- a/pkgs/id/tests/common/ingest.rs +++ b/pkgs/id/tests/common/ingest.rs @@ -2,9 +2,12 @@ //! same events, in any order and with any repeats, give a store the same applied state. //! The checks take bytes, so a case found by a property run can be replayed unchanged. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::io; +use std::sync::mpsc::{self, RecvTimeoutError}; use std::sync::{Arc, Mutex}; +use std::thread; +use std::time::Duration; use id::chain::decode; use id::event_store::{Chain, EventStore, Storage}; @@ -16,12 +19,18 @@ use redb::{Database, DatabaseError, StorageBackend, StorageError}; /// The applied state of a set of authors, as a store reports it. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct Canonical { - /// Each author's applied chain. + /// Each author's applied chain. An author with no applied event and no fork has no row. pub chains: BTreeMap, /// Each author's fork proof: the fork point, and the two IDs in order. pub proofs: BTreeMap, + /// The IDs of every applied event, across all authors. + pub applied: BTreeSet, } +/// How long one delivery may take before it counts as a hang. A store that spins on an +/// event fails the check, instead of hanging the whole test run. +pub const DELIVERY_LIMIT: Duration = Duration::from_secs(20); + /// Reads the applied state of `authors` from `store`. /// /// # Errors @@ -31,6 +40,11 @@ pub fn canonical(store: &EventStore, authors: &[AuthorKey]) -> Result], authors: &[AuthorKey]) -> Result>, + authors: Vec, + limit: Duration, +) -> Result { + let (sent, received) = mpsc::channel(); + thread::spawn(move || { + // The receiver is gone only once the wait below has given up. + let _ = sent.send(deliver(&order, &authors)); + }); + match received.recv_timeout(limit) { + Ok(result) => result, + Err(RecvTimeoutError::Timeout) => Err(format!( + "the delivery did not finish within {limit:?}: an event made the store spin" + )), + Err(RecvTimeoutError::Disconnected) => Err("the delivery panicked".to_owned()), + } +} + /// Checks that delivery order and repeats do not change the applied state. Each /// event is delivered twice in a row, once in the given order, once reversed, and /// once rotated by half the length. @@ -183,9 +221,9 @@ pub fn check_order_independence(events: &[Vec]) -> Result<(), String> { rotated.rotate_left(half); } let authors = authors_of(events); - let first = deliver(&twice(&forward), &authors)?; + let first = deliver_within(twice(&forward), authors.clone(), DELIVERY_LIMIT)?; for (name, order) in [("reversed", &reversed), ("rotated", &rotated)] { - let other = deliver(&twice(order), &authors)?; + let other = deliver_within(twice(order), authors.clone(), DELIVERY_LIMIT)?; if other != first { return Err(format!( "the {name} order reaches {other:?}, but the given order reaches {first:?}" diff --git a/pkgs/id/tests/event_store_properties.rs b/pkgs/id/tests/event_store_properties.rs index 402497d427..d3b8b3a23c 100644 --- a/pkgs/id/tests/event_store_properties.rs +++ b/pkgs/id/tests/event_store_properties.rs @@ -1,15 +1,15 @@ -//! Property tests for ingest in `src/event_store.rs` (plan P1.8). +//! Property tests for ingest in `src/event_store/ingest.rs` (plan P1.8). //! -//! A scenario is a set of valid chains, with forks injected. Each fork is a second -//! event at a sequence number, signed with the same backlink as the original. The -//! scenario is delivered in three orders, with repeats, to fresh stores. Every store -//! must reach the applied state that the chains determine: the chain up to each -//! author's fork point, frozen if there is one, and the fork proof at the lowest fork. +//! A scenario is a set of signed events: valid chains, forks at any depth, and rivals whose +//! backlink is anything: the original's, an earlier event's, or a hash that is never +//! delivered. An `after` hash names any earlier event, or one that is never delivered. The +//! scenario is delivered in four orders, with repeats, to fresh stores. //! -//! The `after` hashes are drawn from events that a fork can never take out of the -//! applied prefix. A fork can unapply events at and above its own sequence number, and -//! an event that names one of those would make the expected state depend on the order -//! of arrival. The regression list covers the orders the generator does not reach. +//! Every store must reach the applied state that [`model`] computes from the set of events +//! alone, so the answer cannot depend on the order. The model is the specification. An event +//! is applied when it sits below its author's fork point, its backlink is the applied event +//! before it, and every `after` hash is applied. The fork point is the lowest sequence number +//! where the author has two distinct events, and the proof holds the two lowest IDs there. //! //! Failures are not written to `proptest-regressions/`. The minimal input goes into //! `tests/regressions/ingest.txt` instead (see `tests/regressions/README.md`). @@ -18,8 +18,10 @@ mod common; -use common::ingest::{Canonical, deliver}; -use id::chain::{ChainExt, Event, sign}; +use std::collections::{BTreeMap, BTreeSet}; + +use common::ingest::{deliver_within, Canonical, DELIVERY_LIMIT}; +use id::chain::{sign, ChainExt, Event}; use id::event_store::Chain; use id::waiting::AuthorKey; use p2panda_core::{Hash, SeqNum, SigningKey}; @@ -63,24 +65,35 @@ fn config() -> ProptestConfig { } } -/// A scenario: every signed event, and the applied state every delivery must reach. +/// A scenario: every distinct signed event, and the applied state they determine. struct Scenario { - /// Every signed event, originals and forks, in creation order. + /// Every signed event, originals and rivals, in creation order. Each one names only + /// events created before it. events: Vec, /// The authors' public keys. authors: Vec, - /// The applied state of every author. + /// The applied state that [`model`] determines from `events`. expected: Canonical, } -/// Up to three `after` hashes, drawn from the stable events created so far. -fn pick_after(rng: &mut Rng, stable: &[Hash]) -> Vec { +fn author_of(event: &Event) -> AuthorKey { + *event.header.verifying_key.as_bytes() +} + +/// A hash that no event in the scenario has: a dependency that is never delivered. +fn undelivered(rng: &mut Rng) -> Hash { + Hash::digest(rng.next_u64().to_be_bytes()) +} + +/// Up to three `after` hashes: earlier events, or hashes that are never delivered. +fn pick_after(rng: &mut Rng, known: &[Event]) -> Vec { let mut picked = Vec::new(); - if stable.is_empty() { - return picked; - } for _ in 0..rng.below(4) { - let hash = stable[rng.below(stable.len() as u64) as usize]; + let hash = if known.is_empty() || rng.chance(5) { + undelivered(rng) + } else { + known[rng.below(known.len() as u64) as usize].id + }; if !picked.contains(&hash) { picked.push(hash); } @@ -88,13 +101,31 @@ fn pick_after(rng: &mut Rng, stable: &[Hash]) -> Vec { picked } -/// Signs an event with a random group and frontier, and the given kind. +/// The backlink of a rival at `seq`. It is the original's own backlink, or the ID of an +/// earlier event (of this author or another, applied or not), or a hash never delivered. +fn rival_backlink( + rng: &mut Rng, + seq: SeqNum, + original: Option, + known: &[Event], +) -> Option { + if seq == 0 { + return None; + } + match rng.below(4) { + 0 | 1 => original, + 2 if !known.is_empty() => Some(known[rng.below(known.len() as u64) as usize].id), + _ => Some(undelivered(rng)), + } +} + +/// Signs an event with a random group and `after` hashes, drawn from `known`. fn signed( rng: &mut Rng, key: &SigningKey, seq: SeqNum, backlink: Option, - stable: &[Hash], + known: &[Event], kind: &str, ) -> Event { let group = rng @@ -103,20 +134,11 @@ fn signed( let ext = ChainExt { kind: kind.to_owned(), group, - after: pick_after(rng, stable), + after: pick_after(rng, known), }; sign(key, seq, backlink, None, ext).unwrap() } -/// Orders two IDs as the fork proof does: lower ID first. -fn ordered(a: Hash, b: Hash) -> (Hash, Hash) { - if a.as_bytes() <= b.as_bytes() { - (a, b) - } else { - (b, a) - } -} - fn scenario(seed: u64) -> Scenario { let mut rng = Rng(seed); let count = 2 + rng.below(2) as usize; @@ -126,26 +148,9 @@ fn scenario(seed: u64) -> Scenario { let lengths: Vec = (0..count) .map(|_| 1 + SeqNum::try_from(rng.below(4)).unwrap()) .collect(); - // The forks are chosen first: at most one per sequence number. The lowest one is - // the author's fork point. - let forked: Vec> = lengths - .iter() - .map(|&len| (0..len).map(|_| rng.chance(4)).collect()) - .collect(); - let fork_point: Vec> = forked - .iter() - .map(|row| { - row.iter() - .position(|&is_forked| is_forked) - .map(|at| SeqNum::try_from(at).unwrap()) - }) - .collect(); let mut events: Vec = Vec::new(); - let mut chains: Vec> = vec![Vec::new(); count]; - let mut rivals: Vec> = vec![None; count]; - // The IDs that can be named by `after`: events below their author's fork point. - let mut stable: Vec = Vec::new(); + let mut originals: Vec> = vec![Vec::new(); count]; let mut progress: Vec = vec![0; count]; while progress.iter().zip(&lengths).any(|(done, len)| done < len) { let author = rng.below(count as u64) as usize; @@ -154,59 +159,27 @@ fn scenario(seed: u64) -> Scenario { continue; } progress[author] += 1; - let backlink = chains[author].last().map(|event| event.id); - let original = signed(&mut rng, &keys[author], seq, backlink, &stable, "message"); - if fork_point[author].is_none_or(|point| seq < point) { - stable.push(original.id); - } - chains[author].push(original.clone()); + let backlink = originals[author].last().map(|event| event.id); + let original = signed(&mut rng, &keys[author], seq, backlink, &events, "message"); + originals[author].push(original.clone()); events.push(original); - if forked[author][seq as usize] { - let rival = signed(&mut rng, &keys[author], seq, backlink, &stable, "rival"); - events.push(rival.clone()); - if fork_point[author] == Some(seq) { - rivals[author] = Some(rival); + // A fork at this sequence number: one or two rivals, each with its own backlink. + if rng.chance(3) { + for _ in 0..=rng.below(2) { + let link = rival_backlink(&mut rng, seq, backlink, &events); + let rival = signed(&mut rng, &keys[author], seq, link, &events, "rival"); + if events.iter().all(|event| event.id != rival.id) { + events.push(rival); + } } } } - let mut expected = Canonical::default(); - for author in 0..count { - let who: AuthorKey = *keys[author].verifying_key().as_bytes(); - match fork_point[author] { - None => { - expected.chains.insert( - who, - Chain { - next_seq: lengths[author], - head: chains[author].last().map(|event| event.id), - frozen: false, - }, - ); - } - Some(point) => { - let head = point - .checked_sub(1) - .map(|before| chains[author][before as usize].id); - expected.chains.insert( - who, - Chain { - next_seq: point, - head, - frozen: true, - }, - ); - let original = chains[author][point as usize].id; - let rival = rivals[author].as_ref().unwrap().id; - let (first, second) = ordered(original, rival); - expected.proofs.insert(who, (point, first, second)); - } - } - } - let authors = keys + let authors: Vec = keys .iter() .map(|key| *key.verifying_key().as_bytes()) .collect(); + let expected = model(&events, &authors); Scenario { events, authors, @@ -214,6 +187,78 @@ fn scenario(seed: u64) -> Scenario { } } +/// The applied state that a set of events determines, whatever order they arrive in. Every +/// event names only earlier events, so one pass in creation order settles each event. +fn model(events: &[Event], authors: &[AuthorKey]) -> Canonical { + let mut at: BTreeMap<(AuthorKey, SeqNum), Vec> = BTreeMap::new(); + for event in events { + at.entry((author_of(event), event.header.seq_num)) + .or_default() + .push(event.id); + } + // The lowest sequence number with two distinct events. Keys are sorted by sequence + // number within an author, so the first conflict seen is the lowest. + let mut fork_point: BTreeMap = BTreeMap::new(); + for (&(author, seq), ids) in &at { + if ids.len() >= 2 { + fork_point.entry(author).or_insert(seq); + } + } + + let mut applied_at: BTreeMap<(AuthorKey, SeqNum), Hash> = BTreeMap::new(); + let mut applied: BTreeSet = BTreeSet::new(); + for event in events { + let author = author_of(event); + let seq = event.header.seq_num; + let below_fork = fork_point.get(&author).is_none_or(|point| seq < *point); + let linked = match seq.checked_sub(1) { + None => true, + Some(before) => applied_at.get(&(author, before)) == event.header.backlink.as_ref(), + }; + let deps_applied = event + .header + .extensions + .after + .iter() + .all(|dep| applied.contains(dep)); + if below_fork && linked && deps_applied { + applied_at.insert((author, seq), event.id); + applied.insert(event.id); + } + } + + let mut expected = Canonical { + applied, + ..Canonical::default() + }; + for author in authors { + let mut next: SeqNum = 0; + while applied_at.contains_key(&(*author, next)) { + next += 1; + } + let fork = fork_point.get(author).copied(); + if next > 0 || fork.is_some() { + let head = next + .checked_sub(1) + .and_then(|before| applied_at.get(&(*author, before)).copied()); + expected.chains.insert( + *author, + Chain { + next_seq: next, + head, + frozen: fork.is_some(), + }, + ); + } + if let Some(point) = fork { + let mut ids = at.get(&(*author, point)).cloned().unwrap_or_default(); + ids.sort_by(|a, b| a.as_bytes().cmp(b.as_bytes())); + expected.proofs.insert(*author, (point, ids[0], ids[1])); + } + } + expected +} + fn shuffle(items: &mut [T], rng: &mut Rng) { for i in (1..items.len()).rev() { let j = rng.below(i as u64 + 1) as usize; @@ -221,8 +266,8 @@ fn shuffle(items: &mut [T], rng: &mut Rng) { } } -/// Three delivery orders of the scenario's events, each with some events repeated: -/// the creation order, the reverse, and a shuffle. +/// Four delivery orders of the scenario's events, each with some events repeated: the +/// creation order, its reverse, and two shuffles. fn orders(events: &[Event], rng: &mut Rng) -> Vec>> { let mut repeated: Vec> = Vec::new(); for event in events { @@ -234,22 +279,26 @@ fn orders(events: &[Event], rng: &mut Rng) -> Vec>> { let forward = repeated.clone(); let mut reversed = repeated.clone(); reversed.reverse(); - let mut shuffled = repeated; - shuffle(&mut shuffled, rng); - vec![forward, reversed, shuffled] + let mut first_shuffle = repeated.clone(); + shuffle(&mut first_shuffle, rng); + let mut second_shuffle = repeated; + shuffle(&mut second_shuffle, rng); + vec![forward, reversed, first_shuffle, second_shuffle] } proptest! { #![proptest_config(config())] - /// Random valid chains with forks, delivered in three orders with repeats, reach - /// the applied state that the chains determine. + /// Random chains with forks at any depth, rivals with any backlink, and `after` hashes on + /// any event, delivered in four orders with repeats: every order reaches the applied state + /// that the model determines from the events. #[test] fn test_random_orders_reach_the_state_the_chains_determine(seed in any::()) { let scenario = scenario(seed); let mut rng = Rng(seed ^ 0xD1B5_4A32_D192_ED03); for order in orders(&scenario.events, &mut rng) { - let state = deliver(&order, &scenario.authors).map_err(TestCaseError::fail)?; + let state = deliver_within(order, scenario.authors.clone(), DELIVERY_LIMIT) + .map_err(TestCaseError::fail)?; prop_assert_eq!(&state, &scenario.expected); } } @@ -262,8 +311,8 @@ fn escape(bytes: &[u8]) -> String { /// Prints the seed lines for `tests/regressions/ingest.txt`. The seeds sit on the ingest /// boundaries: a fork at each position, an event ahead of its chain, an `after` hash on an -/// event the fork unapplied, a repeat, and bytes that fail verification. -/// Run by hand with `-- --ignored --nocapture`. +/// event a fork unapplied, a repeat, bytes that fail verification, and the conflicts that +/// arrive in one order but not another. Run by hand with `-- --ignored --nocapture`. #[test] #[ignore = "prints the seed lines for tests/regressions/ingest.txt"] fn print_ingest_seeds() { @@ -284,8 +333,25 @@ fn print_ingest_seeds() { let a0_rival = sign_event(&a, 0, None, Vec::new(), "rival"); let a1_rival = sign_event(&a, 1, Some(a0.id), Vec::new(), "rival"); let a2_rival = sign_event(&a, 2, Some(a1.id), Vec::new(), "rival"); + let b0 = sign_event(&b, 0, None, Vec::new(), "message"); let b0_after_a0 = sign_event(&b, 0, None, vec![a0.id], "message"); let b0_after_a1 = sign_event(&b, 0, None, vec![a1.id], "message"); + let missing = Hash::digest(b"an event that is never delivered"); + let a1_stray = sign_event( + &a, + 1, + Some(Hash::digest(b"not the head")), + Vec::new(), + "stray", + ); + let a1_held = sign_event(&a, 1, Some(a0.id), vec![missing], "message"); + let a2_stray = sign_event(&a, 2, Some(missing), Vec::new(), "stray"); + let a2_on_b0 = sign_event(&a, 2, Some(b0.id), Vec::new(), "message"); + // Two rivals at sequence 1 whose IDs are below a1's, so that a1 is the highest of the three. + let low_rivals: Vec = (0..16) + .map(|n| sign_event(&a, 1, Some(a0.id), Vec::new(), &format!("rival {n}"))) + .filter(|rival| rival.id.as_bytes() < a1.id.as_bytes()) + .collect(); let mut tampered = a0.bytes.clone(); tampered[48] ^= 0x01; let seeds: Vec<(&str, Vec>)> = vec![ @@ -341,6 +407,48 @@ fn print_ingest_seeds() { "bytes that are not CBOR", vec![b"\xff\x00 not an event".to_vec(), a0.bytes.clone()], ), + ( + "a fork at sequence zero unapplies an event after it", + vec![ + a0.bytes.clone(), + b0_after_a0.bytes.clone(), + a0_rival.bytes.clone(), + ], + ), + ( + "a conflict with an unmatched backlink, after the event it conflicts with", + vec![a0.bytes.clone(), a1.bytes.clone(), a1_stray.bytes.clone()], + ), + ( + "a conflict held on a missing dependency, after its rival applies", + vec![ + a0.bytes.clone(), + a1_rival.bytes.clone(), + a1_held.bytes.clone(), + ], + ), + ( + "two events ahead of the chain at one position", + vec![ + a0.bytes.clone(), + a1.bytes.clone(), + a2.bytes.clone(), + a2_stray.bytes.clone(), + ], + ), + ( + "an event ahead of its chain whose backlink is applied elsewhere", + vec![b0.bytes.clone(), a2_on_b0.bytes.clone()], + ), + ( + "three rivals at one position", + vec![ + a0.bytes.clone(), + a1.bytes.clone(), + low_rivals[0].bytes.clone(), + low_rivals[1].bytes.clone(), + ], + ), ]; for (name, events) in seeds { let fields: Vec = events diff --git a/pkgs/id/tests/regressions/ingest.txt b/pkgs/id/tests/regressions/ingest.txt index 595ba9e352..2317094ad9 100644 --- a/pkgs/id/tests/regressions/ingest.txt +++ b/pkgs/id/tests/regressions/ingest.txt @@ -26,3 +26,15 @@ ingest b:\x86\x01\x58\x20\x8a\x88\xe3\xdd\x74\x09\xf1\x95\xfd\x52\xdb\x2d\x3c\xb ingest b:\x86\x01\x58\x20\x8a\x88\xe3\xdd\x74\x09\xf1\x95\xfd\x52\xdb\x2d\x3c\xba\x5d\x72\xca\x67\x09\xbf\x1d\x94\x12\x1b\xf3\x74\x88\x01\xb4\x0f\x6f\x5c\x58\x40\xf6\xd9\x3d\xac\x1b\x09\xa4\xcf\xf3\x59\x15\xd5\x78\x09\x52\x16\x59\x81\xf9\x8f\x8f\x35\x74\x88\x65\x84\x64\xe2\xa5\xae\x8a\x88\x32\x9e\x69\x9b\x88\x87\x8c\x54\xd4\x2c\xc2\x59\x18\xa9\x56\x17\x3a\x45\x94\xaf\x21\xd2\x9b\x3b\x81\xdb\x99\x51\x37\xd5\x5e\x00\x00\x00\xa4\x64\x6b\x69\x6e\x64\x67\x6d\x65\x73\x73\x61\x67\x65\x65\x61\x66\x74\x65\x72\x80\x65\x67\x72\x6f\x75\x70\xf6\x66\x64\x6f\x6d\x61\x69\x6e\x6c\x69\x64\x2e\x65\x76\x65\x6e\x74\x73\x2e\x76\x31 b:\x86\x01\x58\x20\x8a\x88\xe3\xdd\x74\x09\xf1\x95\xfd\x52\xdb\x2d\x3c\xba\x5d\x72\xca\x67\x09\xbf\x1d\x94\x12\x1b\xf3\x74\x88\x01\xb4\x0f\x6f\x5c\x58\x40\xf6\xd9\x3d\xac\x1b\x09\xa4\xcf\xf3\x59\x14\xd5\x78\x09\x52\x16\x59\x81\xf9\x8f\x8f\x35\x74\x88\x65\x84\x64\xe2\xa5\xae\x8a\x88\x32\x9e\x69\x9b\x88\x87\x8c\x54\xd4\x2c\xc2\x59\x18\xa9\x56\x17\x3a\x45\x94\xaf\x21\xd2\x9b\x3b\x81\xdb\x99\x51\x37\xd5\x5e\x00\x00\x00\xa4\x64\x6b\x69\x6e\x64\x67\x6d\x65\x73\x73\x61\x67\x65\x65\x61\x66\x74\x65\x72\x80\x65\x67\x72\x6f\x75\x70\xf6\x66\x64\x6f\x6d\x61\x69\x6e\x6c\x69\x64\x2e\x65\x76\x65\x6e\x74\x73\x2e\x76\x31 ok # bytes that are not CBOR ingest b:\xff\x00\x20\x6e\x6f\x74\x20\x61\x6e\x20\x65\x76\x65\x6e\x74 b:\x86\x01\x58\x20\x8a\x88\xe3\xdd\x74\x09\xf1\x95\xfd\x52\xdb\x2d\x3c\xba\x5d\x72\xca\x67\x09\xbf\x1d\x94\x12\x1b\xf3\x74\x88\x01\xb4\x0f\x6f\x5c\x58\x40\xf6\xd9\x3d\xac\x1b\x09\xa4\xcf\xf3\x59\x14\xd5\x78\x09\x52\x16\x59\x81\xf9\x8f\x8f\x35\x74\x88\x65\x84\x64\xe2\xa5\xae\x8a\x88\x32\x9e\x69\x9b\x88\x87\x8c\x54\xd4\x2c\xc2\x59\x18\xa9\x56\x17\x3a\x45\x94\xaf\x21\xd2\x9b\x3b\x81\xdb\x99\x51\x37\xd5\x5e\x00\x00\x00\xa4\x64\x6b\x69\x6e\x64\x67\x6d\x65\x73\x73\x61\x67\x65\x65\x61\x66\x74\x65\x72\x80\x65\x67\x72\x6f\x75\x70\xf6\x66\x64\x6f\x6d\x61\x69\x6e\x6c\x69\x64\x2e\x65\x76\x65\x6e\x74\x73\x2e\x76\x31 ok +# a fork at sequence zero unapplies an event after it +ingest b:\x86\x01\x58\x20\x8a\x88\xe3\xdd\x74\x09\xf1\x95\xfd\x52\xdb\x2d\x3c\xba\x5d\x72\xca\x67\x09\xbf\x1d\x94\x12\x1b\xf3\x74\x88\x01\xb4\x0f\x6f\x5c\x58\x40\xf6\xd9\x3d\xac\x1b\x09\xa4\xcf\xf3\x59\x14\xd5\x78\x09\x52\x16\x59\x81\xf9\x8f\x8f\x35\x74\x88\x65\x84\x64\xe2\xa5\xae\x8a\x88\x32\x9e\x69\x9b\x88\x87\x8c\x54\xd4\x2c\xc2\x59\x18\xa9\x56\x17\x3a\x45\x94\xaf\x21\xd2\x9b\x3b\x81\xdb\x99\x51\x37\xd5\x5e\x00\x00\x00\xa4\x64\x6b\x69\x6e\x64\x67\x6d\x65\x73\x73\x61\x67\x65\x65\x61\x66\x74\x65\x72\x80\x65\x67\x72\x6f\x75\x70\xf6\x66\x64\x6f\x6d\x61\x69\x6e\x6c\x69\x64\x2e\x65\x76\x65\x6e\x74\x73\x2e\x76\x31 b:\x86\x01\x58\x20\x81\x39\x77\x0e\xa8\x7d\x17\x5f\x56\xa3\x54\x66\xc3\x4c\x7e\xcc\xcb\x8d\x8a\x91\xb4\xee\x37\xa2\x5d\xf6\x0f\x5b\x8f\xc9\xb3\x94\x58\x40\x22\x1d\x8f\xe1\x78\xf5\x12\x07\x11\x33\x8d\x12\x5c\x26\x94\x9d\xaa\x58\x5f\x89\x05\x3e\x74\x27\xa5\xe9\xbd\x88\xca\xc9\xca\x3d\xd6\xc2\xb9\x99\xb6\xa1\xf6\xc7\xa1\x33\x69\x7c\x97\x71\x35\x26\xd2\x1c\x2a\x93\x33\x7a\x7c\xae\x33\x07\xed\xcd\x9c\xab\xc2\x0f\x00\x00\xa4\x64\x6b\x69\x6e\x64\x67\x6d\x65\x73\x73\x61\x67\x65\x65\x61\x66\x74\x65\x72\x81\x58\x20\x93\x69\x8c\xd5\xe5\xa4\x7f\xbe\xd0\x3d\xa0\x14\xa6\x82\x6c\x26\x76\x69\xd5\xd9\xb1\xe3\x8c\xbf\x1b\xb2\xdb\x51\x8c\x48\xdd\xb1\x65\x67\x72\x6f\x75\x70\xf6\x66\x64\x6f\x6d\x61\x69\x6e\x6c\x69\x64\x2e\x65\x76\x65\x6e\x74\x73\x2e\x76\x31 b:\x86\x01\x58\x20\x8a\x88\xe3\xdd\x74\x09\xf1\x95\xfd\x52\xdb\x2d\x3c\xba\x5d\x72\xca\x67\x09\xbf\x1d\x94\x12\x1b\xf3\x74\x88\x01\xb4\x0f\x6f\x5c\x58\x40\x36\xca\x17\x34\x43\x3d\x51\x4e\x3f\x59\xcc\xff\x10\xad\x74\x66\xb3\xf2\xbd\xd8\x5e\xef\xf3\x84\x7c\xb7\x06\x08\x18\x37\xa5\x2f\x56\x43\xe3\x67\x9b\x62\x8f\x6d\x2e\x27\x4e\xc4\x78\xdb\xd1\xc4\x69\x2c\xc8\x81\x2b\xc5\x24\x3e\x66\x99\x9c\x0b\x46\xba\x0e\x0b\x00\x00\xa4\x64\x6b\x69\x6e\x64\x65\x72\x69\x76\x61\x6c\x65\x61\x66\x74\x65\x72\x80\x65\x67\x72\x6f\x75\x70\xf6\x66\x64\x6f\x6d\x61\x69\x6e\x6c\x69\x64\x2e\x65\x76\x65\x6e\x74\x73\x2e\x76\x31 ok +# a conflict with an unmatched backlink, after the event it conflicts with +ingest b:\x86\x01\x58\x20\x8a\x88\xe3\xdd\x74\x09\xf1\x95\xfd\x52\xdb\x2d\x3c\xba\x5d\x72\xca\x67\x09\xbf\x1d\x94\x12\x1b\xf3\x74\x88\x01\xb4\x0f\x6f\x5c\x58\x40\xf6\xd9\x3d\xac\x1b\x09\xa4\xcf\xf3\x59\x14\xd5\x78\x09\x52\x16\x59\x81\xf9\x8f\x8f\x35\x74\x88\x65\x84\x64\xe2\xa5\xae\x8a\x88\x32\x9e\x69\x9b\x88\x87\x8c\x54\xd4\x2c\xc2\x59\x18\xa9\x56\x17\x3a\x45\x94\xaf\x21\xd2\x9b\x3b\x81\xdb\x99\x51\x37\xd5\x5e\x00\x00\x00\xa4\x64\x6b\x69\x6e\x64\x67\x6d\x65\x73\x73\x61\x67\x65\x65\x61\x66\x74\x65\x72\x80\x65\x67\x72\x6f\x75\x70\xf6\x66\x64\x6f\x6d\x61\x69\x6e\x6c\x69\x64\x2e\x65\x76\x65\x6e\x74\x73\x2e\x76\x31 b:\x87\x01\x58\x20\x8a\x88\xe3\xdd\x74\x09\xf1\x95\xfd\x52\xdb\x2d\x3c\xba\x5d\x72\xca\x67\x09\xbf\x1d\x94\x12\x1b\xf3\x74\x88\x01\xb4\x0f\x6f\x5c\x58\x40\xbf\xd6\x50\x13\x18\x9d\xe4\xd5\xbe\xdf\xc0\x7e\xcc\x77\xeb\x96\x02\x52\x5c\xed\xd3\x2b\x8e\x07\x82\x85\x5d\xbc\x02\xee\x68\xd7\xcf\x77\xad\xab\xdb\x60\x30\x11\x87\xc7\x96\x1e\x18\x05\xfd\x2d\xb5\x17\xa1\xa1\xaa\x40\x06\xe1\xd7\x5c\x9a\x43\xfa\x56\x1a\x00\x00\x01\x58\x20\x93\x69\x8c\xd5\xe5\xa4\x7f\xbe\xd0\x3d\xa0\x14\xa6\x82\x6c\x26\x76\x69\xd5\xd9\xb1\xe3\x8c\xbf\x1b\xb2\xdb\x51\x8c\x48\xdd\xb1\xa4\x64\x6b\x69\x6e\x64\x67\x6d\x65\x73\x73\x61\x67\x65\x65\x61\x66\x74\x65\x72\x80\x65\x67\x72\x6f\x75\x70\xf6\x66\x64\x6f\x6d\x61\x69\x6e\x6c\x69\x64\x2e\x65\x76\x65\x6e\x74\x73\x2e\x76\x31 b:\x87\x01\x58\x20\x8a\x88\xe3\xdd\x74\x09\xf1\x95\xfd\x52\xdb\x2d\x3c\xba\x5d\x72\xca\x67\x09\xbf\x1d\x94\x12\x1b\xf3\x74\x88\x01\xb4\x0f\x6f\x5c\x58\x40\x11\xe7\x3e\x6c\xe2\x76\x0f\xae\x27\x25\x45\x02\x0b\xd1\x07\xc8\x02\x84\xa1\xbc\xc6\x3e\x9d\x38\x6f\x0d\x99\xa9\xa9\xb1\x34\x40\x38\x1d\xdd\x52\xfe\x15\xb6\x1c\xe4\xaa\x2c\x95\x23\x71\x62\xfa\x10\x9b\xb9\x16\xf3\xd9\x04\x78\x1b\xab\x08\x76\xd6\x82\x1c\x0a\x00\x01\x58\x20\x8e\x71\x6d\xb4\x6b\x56\x04\xf4\x3c\x8f\xc0\xa1\x24\xb1\x83\x45\xe1\x50\xaa\xf1\xf9\x06\x5a\xfa\x3a\x2d\x46\xe8\x93\x6f\x4e\xa9\xa4\x64\x6b\x69\x6e\x64\x65\x73\x74\x72\x61\x79\x65\x61\x66\x74\x65\x72\x80\x65\x67\x72\x6f\x75\x70\xf6\x66\x64\x6f\x6d\x61\x69\x6e\x6c\x69\x64\x2e\x65\x76\x65\x6e\x74\x73\x2e\x76\x31 ok +# a conflict held on a missing dependency, after its rival applies +ingest b:\x86\x01\x58\x20\x8a\x88\xe3\xdd\x74\x09\xf1\x95\xfd\x52\xdb\x2d\x3c\xba\x5d\x72\xca\x67\x09\xbf\x1d\x94\x12\x1b\xf3\x74\x88\x01\xb4\x0f\x6f\x5c\x58\x40\xf6\xd9\x3d\xac\x1b\x09\xa4\xcf\xf3\x59\x14\xd5\x78\x09\x52\x16\x59\x81\xf9\x8f\x8f\x35\x74\x88\x65\x84\x64\xe2\xa5\xae\x8a\x88\x32\x9e\x69\x9b\x88\x87\x8c\x54\xd4\x2c\xc2\x59\x18\xa9\x56\x17\x3a\x45\x94\xaf\x21\xd2\x9b\x3b\x81\xdb\x99\x51\x37\xd5\x5e\x00\x00\x00\xa4\x64\x6b\x69\x6e\x64\x67\x6d\x65\x73\x73\x61\x67\x65\x65\x61\x66\x74\x65\x72\x80\x65\x67\x72\x6f\x75\x70\xf6\x66\x64\x6f\x6d\x61\x69\x6e\x6c\x69\x64\x2e\x65\x76\x65\x6e\x74\x73\x2e\x76\x31 b:\x87\x01\x58\x20\x8a\x88\xe3\xdd\x74\x09\xf1\x95\xfd\x52\xdb\x2d\x3c\xba\x5d\x72\xca\x67\x09\xbf\x1d\x94\x12\x1b\xf3\x74\x88\x01\xb4\x0f\x6f\x5c\x58\x40\x29\x77\x93\xb0\x91\xce\x95\xe0\xd4\xca\x08\x2b\xc5\xbd\x62\x47\xff\xb8\xd7\x7c\x22\xe4\xfd\x3e\xbd\xc5\x1a\xca\x71\xd6\x8e\x93\x43\xaa\x84\x1f\xf7\xa5\x82\x28\xc7\x9b\xe9\x93\x26\x14\xcd\x1c\xcd\x83\x05\x69\xec\x23\x43\xa6\xd1\x27\x99\x41\x07\xc2\xfe\x04\x00\x01\x58\x20\x93\x69\x8c\xd5\xe5\xa4\x7f\xbe\xd0\x3d\xa0\x14\xa6\x82\x6c\x26\x76\x69\xd5\xd9\xb1\xe3\x8c\xbf\x1b\xb2\xdb\x51\x8c\x48\xdd\xb1\xa4\x64\x6b\x69\x6e\x64\x65\x72\x69\x76\x61\x6c\x65\x61\x66\x74\x65\x72\x80\x65\x67\x72\x6f\x75\x70\xf6\x66\x64\x6f\x6d\x61\x69\x6e\x6c\x69\x64\x2e\x65\x76\x65\x6e\x74\x73\x2e\x76\x31 b:\x87\x01\x58\x20\x8a\x88\xe3\xdd\x74\x09\xf1\x95\xfd\x52\xdb\x2d\x3c\xba\x5d\x72\xca\x67\x09\xbf\x1d\x94\x12\x1b\xf3\x74\x88\x01\xb4\x0f\x6f\x5c\x58\x40\x64\xef\x55\x94\x88\xd4\x02\x10\x36\x96\x6e\xdd\x2a\x98\xf9\x4f\xf4\xbf\x23\x3e\x4f\x57\x78\xe7\xa3\x0b\x36\x66\x8c\x20\xaa\xaf\xff\x45\xe0\x30\xb6\x26\x05\xb4\x05\xb4\xa4\xd4\x97\x31\x5d\x56\x91\xba\x62\x1b\xb9\xc1\x8e\x68\x31\x8b\x46\x03\xe2\xa4\x10\x08\x00\x01\x58\x20\x93\x69\x8c\xd5\xe5\xa4\x7f\xbe\xd0\x3d\xa0\x14\xa6\x82\x6c\x26\x76\x69\xd5\xd9\xb1\xe3\x8c\xbf\x1b\xb2\xdb\x51\x8c\x48\xdd\xb1\xa4\x64\x6b\x69\x6e\x64\x67\x6d\x65\x73\x73\x61\x67\x65\x65\x61\x66\x74\x65\x72\x81\x58\x20\xb3\x0c\x94\x6a\x66\x32\x39\xf0\x09\xc7\xdf\x4b\x24\xbd\xdc\xbc\xae\xd4\x8c\x84\xc5\x07\x6e\xa8\xee\x27\xc7\x44\x6e\x6b\x2a\x2c\x65\x67\x72\x6f\x75\x70\xf6\x66\x64\x6f\x6d\x61\x69\x6e\x6c\x69\x64\x2e\x65\x76\x65\x6e\x74\x73\x2e\x76\x31 ok +# two events ahead of the chain at one position +ingest b:\x86\x01\x58\x20\x8a\x88\xe3\xdd\x74\x09\xf1\x95\xfd\x52\xdb\x2d\x3c\xba\x5d\x72\xca\x67\x09\xbf\x1d\x94\x12\x1b\xf3\x74\x88\x01\xb4\x0f\x6f\x5c\x58\x40\xf6\xd9\x3d\xac\x1b\x09\xa4\xcf\xf3\x59\x14\xd5\x78\x09\x52\x16\x59\x81\xf9\x8f\x8f\x35\x74\x88\x65\x84\x64\xe2\xa5\xae\x8a\x88\x32\x9e\x69\x9b\x88\x87\x8c\x54\xd4\x2c\xc2\x59\x18\xa9\x56\x17\x3a\x45\x94\xaf\x21\xd2\x9b\x3b\x81\xdb\x99\x51\x37\xd5\x5e\x00\x00\x00\xa4\x64\x6b\x69\x6e\x64\x67\x6d\x65\x73\x73\x61\x67\x65\x65\x61\x66\x74\x65\x72\x80\x65\x67\x72\x6f\x75\x70\xf6\x66\x64\x6f\x6d\x61\x69\x6e\x6c\x69\x64\x2e\x65\x76\x65\x6e\x74\x73\x2e\x76\x31 b:\x87\x01\x58\x20\x8a\x88\xe3\xdd\x74\x09\xf1\x95\xfd\x52\xdb\x2d\x3c\xba\x5d\x72\xca\x67\x09\xbf\x1d\x94\x12\x1b\xf3\x74\x88\x01\xb4\x0f\x6f\x5c\x58\x40\xbf\xd6\x50\x13\x18\x9d\xe4\xd5\xbe\xdf\xc0\x7e\xcc\x77\xeb\x96\x02\x52\x5c\xed\xd3\x2b\x8e\x07\x82\x85\x5d\xbc\x02\xee\x68\xd7\xcf\x77\xad\xab\xdb\x60\x30\x11\x87\xc7\x96\x1e\x18\x05\xfd\x2d\xb5\x17\xa1\xa1\xaa\x40\x06\xe1\xd7\x5c\x9a\x43\xfa\x56\x1a\x00\x00\x01\x58\x20\x93\x69\x8c\xd5\xe5\xa4\x7f\xbe\xd0\x3d\xa0\x14\xa6\x82\x6c\x26\x76\x69\xd5\xd9\xb1\xe3\x8c\xbf\x1b\xb2\xdb\x51\x8c\x48\xdd\xb1\xa4\x64\x6b\x69\x6e\x64\x67\x6d\x65\x73\x73\x61\x67\x65\x65\x61\x66\x74\x65\x72\x80\x65\x67\x72\x6f\x75\x70\xf6\x66\x64\x6f\x6d\x61\x69\x6e\x6c\x69\x64\x2e\x65\x76\x65\x6e\x74\x73\x2e\x76\x31 b:\x87\x01\x58\x20\x8a\x88\xe3\xdd\x74\x09\xf1\x95\xfd\x52\xdb\x2d\x3c\xba\x5d\x72\xca\x67\x09\xbf\x1d\x94\x12\x1b\xf3\x74\x88\x01\xb4\x0f\x6f\x5c\x58\x40\x4f\x90\x42\x95\xf1\xc7\xc9\x6f\x23\x17\xb7\xfe\x55\xec\xb9\xb8\x14\xcb\xbc\x96\x4f\xc7\x0e\x79\x1d\xca\x5c\x6f\x92\x25\x8d\x02\x0b\x79\xc9\x43\x8b\x74\xc1\x4a\x5c\x21\x77\xe7\x7f\x06\x6f\x32\x20\x83\x0b\xfb\x40\x15\x33\x6d\x39\x1c\xe6\x4f\xda\x21\xb8\x0c\x00\x02\x58\x20\xae\x52\xd9\xae\xc8\xa5\xa0\x2f\xa9\x59\x3e\xcb\xf0\x8c\xe7\x97\x25\xe3\xc3\x9f\x32\x19\xf4\x8b\xb5\x1b\x4d\xdd\x37\x7e\x3b\x98\xa4\x64\x6b\x69\x6e\x64\x67\x6d\x65\x73\x73\x61\x67\x65\x65\x61\x66\x74\x65\x72\x80\x65\x67\x72\x6f\x75\x70\xf6\x66\x64\x6f\x6d\x61\x69\x6e\x6c\x69\x64\x2e\x65\x76\x65\x6e\x74\x73\x2e\x76\x31 b:\x87\x01\x58\x20\x8a\x88\xe3\xdd\x74\x09\xf1\x95\xfd\x52\xdb\x2d\x3c\xba\x5d\x72\xca\x67\x09\xbf\x1d\x94\x12\x1b\xf3\x74\x88\x01\xb4\x0f\x6f\x5c\x58\x40\x90\x5b\x37\x8e\xc3\x88\x70\x4e\xab\x59\x79\xfd\x9a\x8d\xac\xf2\x97\xa8\xad\xfa\x50\x6e\x26\x6f\x29\xa5\xad\xe7\xa1\xf8\x86\xab\xc3\x3b\x3b\x7f\x0c\xf5\x25\x22\x51\xaa\xd2\x42\xb7\x59\x08\x68\xaa\x6d\x5e\x23\x64\x06\x88\x56\xf3\xb6\xbe\x87\x1b\x38\x19\x06\x00\x02\x58\x20\xb3\x0c\x94\x6a\x66\x32\x39\xf0\x09\xc7\xdf\x4b\x24\xbd\xdc\xbc\xae\xd4\x8c\x84\xc5\x07\x6e\xa8\xee\x27\xc7\x44\x6e\x6b\x2a\x2c\xa4\x64\x6b\x69\x6e\x64\x65\x73\x74\x72\x61\x79\x65\x61\x66\x74\x65\x72\x80\x65\x67\x72\x6f\x75\x70\xf6\x66\x64\x6f\x6d\x61\x69\x6e\x6c\x69\x64\x2e\x65\x76\x65\x6e\x74\x73\x2e\x76\x31 ok +# an event ahead of its chain whose backlink is applied elsewhere +ingest b:\x86\x01\x58\x20\x81\x39\x77\x0e\xa8\x7d\x17\x5f\x56\xa3\x54\x66\xc3\x4c\x7e\xcc\xcb\x8d\x8a\x91\xb4\xee\x37\xa2\x5d\xf6\x0f\x5b\x8f\xc9\xb3\x94\x58\x40\x91\xc5\x3d\x5a\xca\x3a\x8e\xa7\xe7\xe4\x5b\x68\xf5\x62\x08\x87\x79\x02\xad\xdc\x63\x04\x69\x34\x61\x34\xfe\x67\x89\x21\x6d\x8b\xb1\xc0\x35\x02\xeb\x0c\xfa\x69\x51\xa8\x77\xf1\x99\x88\xe8\x01\x3b\x76\xd2\xdd\x25\x1e\x68\x32\x85\xd8\x62\xaf\x5b\xdd\xb0\x0f\x00\x00\xa4\x64\x6b\x69\x6e\x64\x67\x6d\x65\x73\x73\x61\x67\x65\x65\x61\x66\x74\x65\x72\x80\x65\x67\x72\x6f\x75\x70\xf6\x66\x64\x6f\x6d\x61\x69\x6e\x6c\x69\x64\x2e\x65\x76\x65\x6e\x74\x73\x2e\x76\x31 b:\x87\x01\x58\x20\x8a\x88\xe3\xdd\x74\x09\xf1\x95\xfd\x52\xdb\x2d\x3c\xba\x5d\x72\xca\x67\x09\xbf\x1d\x94\x12\x1b\xf3\x74\x88\x01\xb4\x0f\x6f\x5c\x58\x40\x91\x99\x5e\x1f\xef\x4f\x58\xb7\x9a\xde\x87\xaa\x0d\x61\xd9\x69\xd7\x6a\x24\xe1\x7a\xfc\xf7\x8b\x23\x2e\xd6\x57\x75\x7b\x79\x9e\xf9\x54\xd5\xec\x65\x0a\xbc\xee\xa4\x42\xea\x35\xd5\x57\x70\xe3\x93\x5a\x6b\x66\x78\xf2\xfe\x3d\x56\xa6\x70\x37\xc9\x45\xfa\x04\x00\x02\x58\x20\x19\x32\xed\xd9\x7c\x9f\x86\xc9\xe6\x75\x5f\x43\xf6\x68\xf1\x02\x78\xf7\xaa\x69\x46\xf4\x77\xc7\xbb\x07\x94\x44\x4d\x7e\x48\x37\xa4\x64\x6b\x69\x6e\x64\x67\x6d\x65\x73\x73\x61\x67\x65\x65\x61\x66\x74\x65\x72\x80\x65\x67\x72\x6f\x75\x70\xf6\x66\x64\x6f\x6d\x61\x69\x6e\x6c\x69\x64\x2e\x65\x76\x65\x6e\x74\x73\x2e\x76\x31 ok +# three rivals at one position +ingest b:\x86\x01\x58\x20\x8a\x88\xe3\xdd\x74\x09\xf1\x95\xfd\x52\xdb\x2d\x3c\xba\x5d\x72\xca\x67\x09\xbf\x1d\x94\x12\x1b\xf3\x74\x88\x01\xb4\x0f\x6f\x5c\x58\x40\xf6\xd9\x3d\xac\x1b\x09\xa4\xcf\xf3\x59\x14\xd5\x78\x09\x52\x16\x59\x81\xf9\x8f\x8f\x35\x74\x88\x65\x84\x64\xe2\xa5\xae\x8a\x88\x32\x9e\x69\x9b\x88\x87\x8c\x54\xd4\x2c\xc2\x59\x18\xa9\x56\x17\x3a\x45\x94\xaf\x21\xd2\x9b\x3b\x81\xdb\x99\x51\x37\xd5\x5e\x00\x00\x00\xa4\x64\x6b\x69\x6e\x64\x67\x6d\x65\x73\x73\x61\x67\x65\x65\x61\x66\x74\x65\x72\x80\x65\x67\x72\x6f\x75\x70\xf6\x66\x64\x6f\x6d\x61\x69\x6e\x6c\x69\x64\x2e\x65\x76\x65\x6e\x74\x73\x2e\x76\x31 b:\x87\x01\x58\x20\x8a\x88\xe3\xdd\x74\x09\xf1\x95\xfd\x52\xdb\x2d\x3c\xba\x5d\x72\xca\x67\x09\xbf\x1d\x94\x12\x1b\xf3\x74\x88\x01\xb4\x0f\x6f\x5c\x58\x40\xbf\xd6\x50\x13\x18\x9d\xe4\xd5\xbe\xdf\xc0\x7e\xcc\x77\xeb\x96\x02\x52\x5c\xed\xd3\x2b\x8e\x07\x82\x85\x5d\xbc\x02\xee\x68\xd7\xcf\x77\xad\xab\xdb\x60\x30\x11\x87\xc7\x96\x1e\x18\x05\xfd\x2d\xb5\x17\xa1\xa1\xaa\x40\x06\xe1\xd7\x5c\x9a\x43\xfa\x56\x1a\x00\x00\x01\x58\x20\x93\x69\x8c\xd5\xe5\xa4\x7f\xbe\xd0\x3d\xa0\x14\xa6\x82\x6c\x26\x76\x69\xd5\xd9\xb1\xe3\x8c\xbf\x1b\xb2\xdb\x51\x8c\x48\xdd\xb1\xa4\x64\x6b\x69\x6e\x64\x67\x6d\x65\x73\x73\x61\x67\x65\x65\x61\x66\x74\x65\x72\x80\x65\x67\x72\x6f\x75\x70\xf6\x66\x64\x6f\x6d\x61\x69\x6e\x6c\x69\x64\x2e\x65\x76\x65\x6e\x74\x73\x2e\x76\x31 b:\x87\x01\x58\x20\x8a\x88\xe3\xdd\x74\x09\xf1\x95\xfd\x52\xdb\x2d\x3c\xba\x5d\x72\xca\x67\x09\xbf\x1d\x94\x12\x1b\xf3\x74\x88\x01\xb4\x0f\x6f\x5c\x58\x40\x9e\xd4\x48\x9c\xcc\xbf\xdb\xdb\x62\x1b\xe5\x4e\x3d\xae\x0e\x8c\xcf\x6c\x9e\x92\x66\x5f\x27\x69\xa5\x3a\x6c\x49\x89\x58\x18\x62\xa1\x8e\x0f\xf4\xf3\x5c\xed\xd7\x0e\xb7\x17\xd0\xed\xe7\x0a\x40\x39\x76\xc8\x65\xaa\x96\x5e\x49\x6f\x4a\x98\x80\xec\x08\xc4\x02\x00\x01\x58\x20\x93\x69\x8c\xd5\xe5\xa4\x7f\xbe\xd0\x3d\xa0\x14\xa6\x82\x6c\x26\x76\x69\xd5\xd9\xb1\xe3\x8c\xbf\x1b\xb2\xdb\x51\x8c\x48\xdd\xb1\xa4\x64\x6b\x69\x6e\x64\x67\x72\x69\x76\x61\x6c\x20\x30\x65\x61\x66\x74\x65\x72\x80\x65\x67\x72\x6f\x75\x70\xf6\x66\x64\x6f\x6d\x61\x69\x6e\x6c\x69\x64\x2e\x65\x76\x65\x6e\x74\x73\x2e\x76\x31 b:\x87\x01\x58\x20\x8a\x88\xe3\xdd\x74\x09\xf1\x95\xfd\x52\xdb\x2d\x3c\xba\x5d\x72\xca\x67\x09\xbf\x1d\x94\x12\x1b\xf3\x74\x88\x01\xb4\x0f\x6f\x5c\x58\x40\x33\xe7\xf1\xf8\xc2\x7f\xe9\xb0\x3b\xbc\x42\xb8\x57\xf6\x1b\xb6\x1d\xcf\x31\x74\xe5\x87\xf4\x9a\xb5\x93\x79\x49\x41\xeb\x38\xb4\xf6\x99\xc4\x0a\xc7\xbd\xa2\xde\xab\x8f\xbe\x74\x5e\x6c\x2e\x0e\xfe\xf0\xd3\x88\x3f\x31\x4a\x23\x54\x5a\x79\xae\x18\xfd\x66\x01\x00\x01\x58\x20\x93\x69\x8c\xd5\xe5\xa4\x7f\xbe\xd0\x3d\xa0\x14\xa6\x82\x6c\x26\x76\x69\xd5\xd9\xb1\xe3\x8c\xbf\x1b\xb2\xdb\x51\x8c\x48\xdd\xb1\xa4\x64\x6b\x69\x6e\x64\x67\x72\x69\x76\x61\x6c\x20\x31\x65\x61\x66\x74\x65\x72\x80\x65\x67\x72\x6f\x75\x70\xf6\x66\x64\x6f\x6d\x61\x69\x6e\x6c\x69\x64\x2e\x65\x76\x65\x6e\x74\x73\x2e\x76\x31 ok From 1a90c10237f5064b680719762eb51b147984992d Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 11 Oct 2026 20:08:54 -0500 Subject: [PATCH 17/30] fix(rust): a fork unapplies the events applied after its fork point [P1.8] A fork moves the applied prefix of its author's chain down to the fork point, and now also unapplies every applied event that rests on an unapplied one. A new dependents index (format v2) records which stored events name each hash in their `after`, so the cascade costs what it unapplies. Voided events stay stored; the chain's applied prefix marks them. A conflict is found whatever its backlink or dependencies, from stored and held events. Two events at one position give the proof the two lowest IDs there, so the proof does not depend on arrival order. An event whose backlink can never be the applied head is parked, not refused, so that a conflict with it is still seen. An event ahead of its chain whose backlink is applied elsewhere is parked too: the drain used to release it again and again without end. The crash model is unchanged: each decision still writes in one transaction. --- pkgs/id/src/event_store/ingest.rs | 423 +++++++++++++++++++++--------- pkgs/id/src/event_store/mod.rs | 85 +++++- pkgs/id/src/waiting.rs | 66 ++++- 3 files changed, 420 insertions(+), 154 deletions(-) diff --git a/pkgs/id/src/event_store/ingest.rs b/pkgs/id/src/event_store/ingest.rs index 65578c8716..159c84d97e 100644 --- a/pkgs/id/src/event_store/ingest.rs +++ b/pkgs/id/src/event_store/ingest.rs @@ -5,48 +5,55 @@ //! 1. **Verify.** [`chain::decode`] checks the canonical encoding and the signature //! (through `AnyHeader::decode`, which uses `verify_strict`), then the extension's //! rules. Anything that fails is refused as [`Refusal::Malformed`]. -//! 2. **Duplicate.** An event whose ID is stored, or is one of the author's fork -//! proof headers, changes nothing. -//! 3. **Fork.** If the author already has an applied event at the event's sequence -//! number, the two conflict. The chain freezes at the lower of the two sequence -//! numbers, and both headers are stored as the proof. -//! 4. **Frozen.** A frozen author's events from the fork point on are refused. -//! 5. **Accept.** The next sequence number, whose backlink is the applied head, is -//! applied once every `after` hash is applied. -//! 6. **Wait.** An event ahead of its chain, or with an `after` hash that is not -//! applied yet, is held in the waiting pool under its caps. When the dependency is -//! applied, the event is released and decided again. +//! 2. **Duplicate.** An event whose ID is stored, or is one of its author's fork proof +//! headers, changes nothing. +//! 3. **Frozen.** An event above its author's fork point is refused as +//! [`Refusal::Frozen`]. +//! 4. **Fork.** If the author has another event at the same sequence number, stored or +//! held, the two are a fork, whatever their backlinks and dependencies. The fork point +//! moves down to that sequence number, and the proof holds the two lowest IDs there. +//! The applied events from that point on are unapplied, and so is every applied event +//! that rests on one of them. +//! 5. **Accept.** The next sequence number, whose backlink is the applied head, is applied +//! once every `after` hash is applied. +//! 6. **Wait or park.** An event ahead of its chain, or with an `after` hash that is not +//! applied yet, is held in the waiting pool under its caps, and decided again when its +//! dependencies are applied. An event whose backlink can never be the applied head is +//! parked: held for good, so that a conflict with it is still seen. //! -//! Each decision that writes runs in one redb write transaction. A refused event +//! Each decision that writes runs in one redb write transaction. A refused or held event //! writes nothing, and an accepted one is committed before any event it released is //! decided. //! //! # Applied state and forks //! -//! The applied prefix of a chain is the events below its next sequence number. A fork -//! moves the next sequence number down to the fork point. Events from the fork point -//! on stay stored, but they are not applied. When an event leaves the applied prefix, -//! the waiting pool forgets it, so events that wait on it wait again. The applied -//! state therefore depends on which events a store has received, not on the order in -//! which it received them. The property tests in `tests/event_store_properties.rs` -//! check that. +//! The applied state depends on the set of events a store has received, not on their +//! arrival order. An event is applied when it sits below its author's fork point, its +//! backlink is the applied event before it, and every `after` hash is applied. The fork +//! point is the lowest sequence number where the author has two distinct events, and the +//! proof holds the two lowest IDs there. //! -//! Two cases still depend on arrival order, and the membership layer must handle -//! both. First, a fork does not undo the events applied on top of a later fork, so an -//! event applied before the fork stays applied. Second, a conflict whose backlink is -//! not the applied head is refused, not held, so a conflict that arrives before the -//! event it conflicts with can go unnoticed. The property tests generate neither: their -//! forks share the original's backlink, and their `after` hashes name only events a -//! fork cannot unapply. +//! An event that is stored but not applied is voided. A fork voids the author's events +//! from its fork point on, and every event that rests on a voided one. A voided event is +//! kept, because it still counts as the author's event at its sequence number, so a later +//! conflict with it is still a fork. The applied prefix of a chain is the events below its +//! next sequence number, so the chain row is what marks the voids. +//! +//! Held events count too. Two held events at one sequence number are a fork, though +//! neither is applied. A restart forgets held events, and sync sends them again. +//! +//! The property tests in `tests/event_store_properties.rs` check the applied state against +//! this definition, for every arrival order. use std::collections::VecDeque; use p2panda_core::{Hash, SeqNum}; -use redb::{ReadableTable, WriteTransaction}; +use redb::{ReadableMultimapTable, ReadableTable, WriteTransaction}; use super::{ - CHAINS, Chain, EVENTS, EventStore, FORKS, HASHES, StoreError, corrupt, decode_proof, - decode_stored, position_key, split_position, store_chain, store_event, store_fork, + corrupt, decode_proof, decode_stored, position_key, split_position, store_chain, store_event, + store_fork, Chain, EventStore, ForkProof, StoreError, CHAINS, DEPENDENTS, EVENTS, FORKS, + HASHES, }; use crate::chain::{self, Event}; use crate::waiting::{AuthorKey, WaitRefusal}; @@ -57,11 +64,8 @@ pub enum Refusal { /// The bytes are not a valid event. The message names the rule that failed: a /// non-canonical encoding, a bad signature, or an extension that breaks its rules. Malformed(String), - /// The author has forked at or below this sequence number, so later events are - /// not applied. + /// The event is above its author's fork point, so it never applies. Frozen, - /// The sequence number is the next one, but the backlink is not the applied head. - BacklinkMismatch, /// The author already holds as many waiting events as the caps allow. WaitingFull, } @@ -83,17 +87,18 @@ pub enum Ingest { /// The event's ID. id: Hash, }, - /// The author signed two different events at a sequence number that exists. The - /// chain froze at the lower of the two sequence numbers, and both headers are - /// stored as the fork proof. + /// The author signed two different events at one sequence number. The chain is + /// frozen there, and both headers are stored as the proof. A further event at the + /// fork point that changes the proof is reported the same way. Fork { /// The author. author: AuthorKey, /// The fork point: the lowest sequence number where the author conflicts. seq: SeqNum, }, - /// The event waits for a dependency. It is held in memory and not stored. Sync - /// sends it again if it is lost. + /// The event is held in memory and not stored. It waits for a dependency, or it is + /// parked because its backlink can never be the applied head. Sync sends it again if + /// it is lost. Waiting { /// The event's ID. id: Hash, @@ -102,18 +107,20 @@ pub enum Ingest { Refused(Refusal), } -/// What the store decides for one event, before waiting. +/// What the store decides for one event, before the waiting pool sees it. #[derive(Debug, PartialEq, Eq)] enum Decision { /// Stored and applied. Accept, /// Already stored, or a proof header. Nothing written. Duplicate, - /// A different event at `seq`, below the applied prefix, which ended at `applied`. - /// Written as the fork. - Fork { seq: SeqNum, applied: SeqNum }, - /// Waits for these dependencies. Nothing written. + /// A conflict. The proof is written, and the fork point is `seq`. `unapplied` are + /// the events that left the applied prefix, which the waiting pool forgets. + Fork { seq: SeqNum, unapplied: Vec }, + /// Waits for these dependencies, none of which is applied. Nothing written. Wait(Vec), + /// Can never apply, but is held so that a conflict with it is seen. Nothing written. + Park, /// Refused. Nothing written. Refuse(Refusal), } @@ -134,16 +141,17 @@ impl EventStore { Err(err) => return Ok(Ingest::Refused(Refusal::Malformed(err.to_string()))), }; let id = event.id; - let author = *event.header.verifying_key.as_bytes(); - match self.decide(&event)? { + let author = author_of(&event); + let rivals = self.held_rivals(&event); + match self.decide(&event, &rivals)? { Decision::Accept => { let arrived = self.waiting.arrived(id, now_ms); let released = self.drain(arrived.into(), now_ms)?; Ok(Ingest::Accepted { id, released }) } Decision::Duplicate => Ok(Ingest::Duplicate { id }), - Decision::Fork { seq, applied } => { - self.forget_unapplied(&author, seq, applied)?; + Decision::Fork { seq, unapplied } => { + self.forget(&unapplied); Ok(Ingest::Fork { author, seq }) } Decision::Wait(deps) => { @@ -154,6 +162,10 @@ impl EventStore { self.drain(VecDeque::new(), now_ms)?; Ok(outcome) } + Decision::Park => match self.waiting.park(author, id, event, now_ms) { + Ok(()) => Ok(Ingest::Waiting { id }), + Err(WaitRefusal::AuthorFull) => Ok(Ingest::Refused(Refusal::WaitingFull)), + }, Decision::Refuse(refusal) => Ok(Ingest::Refused(refusal)), } } @@ -174,11 +186,23 @@ impl EventStore { self.waiting.waiting_count(*author) } + /// The held events that conflict with `event`: the author's other events at its + /// sequence number. + fn held_rivals(&self, event: &Event) -> Vec { + let author = author_of(event); + let seq = event.header.seq_num; + self.waiting + .held_by(&author) + .filter(|held| held.header.seq_num == seq && held.id != event.id) + .cloned() + .collect() + } + /// Decides `event` in one write transaction. A decision that writes nothing aborts /// the transaction. - fn decide(&self, event: &Event) -> Result { + fn decide(&self, event: &Event, rivals: &[Event]) -> Result { let txn = self.db.begin_write()?; - let decision = decide_in(&txn, event)?; + let decision = decide_in(&txn, event, rivals)?; if matches!(decision, Decision::Accept | Decision::Fork { .. }) { txn.commit()?; } @@ -192,20 +216,21 @@ impl EventStore { queue.extend(self.waiting.take_ready()); while let Some(event) = queue.pop_front() { let id = event.id; - let author = *event.header.verifying_key.as_bytes(); - match self.decide(&event)? { + let author = author_of(&event); + let rivals = self.held_rivals(&event); + match self.decide(&event, &rivals)? { Decision::Accept => { applied.push(id); queue.extend(self.waiting.arrived(id, now_ms)); } - Decision::Fork { - seq, - applied: before, - } => self.forget_unapplied(&author, seq, before)?, + Decision::Fork { unapplied, .. } => self.forget(&unapplied), Decision::Wait(deps) => { // A refused insert drops the event, as an event past the cap is dropped. let _ = self.waiting.insert(author, id, deps, event, now_ms); } + Decision::Park => { + let _ = self.waiting.park(author, id, event, now_ms); + } Decision::Duplicate | Decision::Refuse(_) => {} } queue.extend(self.waiting.take_ready()); @@ -213,83 +238,203 @@ impl EventStore { Ok(applied) } - /// Tells the waiting pool that the events from `from` up to `applied` are no longer - /// applied, so events that wait on them wait again. - fn forget_unapplied( - &mut self, - author: &AuthorKey, - from: SeqNum, - applied: SeqNum, - ) -> Result<(), StoreError> { - for seq in from..applied { - if let Some(event) = self.event(author, seq)? { - self.waiting.forget(&event.id); - } + /// Tells the waiting pool that these events are no longer applied, so events that + /// wait on them wait again. + fn forget(&mut self, unapplied: &[Hash]) { + for id in unapplied { + self.waiting.forget(id); } - Ok(()) } } -/// Decides `event` inside `txn`, and writes what the decision needs. -fn decide_in(txn: &WriteTransaction, event: &Event) -> Result { - let author = *event.header.verifying_key.as_bytes(); +/// Decides `event` inside `txn`, and writes what the decision needs. `rivals` are the +/// held events of the same author at the same sequence number. +fn decide_in( + txn: &WriteTransaction, + event: &Event, + rivals: &[Event], +) -> Result { + let author = author_of(event); let seq = event.header.seq_num; if is_stored(txn, &event.id)? || is_proof_header(txn, &author, &event.id)? { return Ok(Decision::Duplicate); } + // Every other event the store knows of at this sequence number: stored, or held. + let mut conflicts: Vec = rivals.to_vec(); + if let Some(stored) = stored_at(txn, &author, seq)? { + conflicts.push(stored); + } + if let Some(proof) = read_proof(txn, &author)? { + if seq > proof.seq { + return Ok(Decision::Refuse(Refusal::Frozen)); + } + if seq == proof.seq { + // Another event at the fork point. The proof keeps the two lowest IDs there. + conflicts.extend([proof.first.clone(), proof.second.clone(), event.clone()]); + let (first, second) = two_lowest(conflicts)?; + if first.id == proof.first.id && second.id == proof.second.id { + return Ok(Decision::Refuse(Refusal::Frozen)); + } + store_fork(txn, &author, seq, &first, &second)?; + return Ok(Decision::Fork { + seq, + unapplied: Vec::new(), + }); + } + } + if !conflicts.is_empty() { + // The first conflict at this sequence number, or one below the fork point. + conflicts.push(event.clone()); + let (first, second) = two_lowest(conflicts)?; + store_fork(txn, &author, seq, &first, &second)?; + let unapplied = freeze_and_unapply(txn, &author, seq)?; + return Ok(Decision::Fork { seq, unapplied }); + } + let chain = read_chain(txn, &author)?; if seq < chain.next_seq { - let stored = stored_event(txn, &author, seq)?; - let head = match seq.checked_sub(1) { - Some(before) => Some(stored_event(txn, &author, before)?.id), - None => None, - }; - store_fork(txn, &author, seq, &stored, event)?; - store_chain( - txn, - &author, - Chain { - next_seq: seq, - head, - frozen: true, - }, - )?; - return Ok(Decision::Fork { - seq, - applied: chain.next_seq, - }); + // The applied event at this sequence number is stored, so it would be a conflict. + return Err(corrupt("an applied sequence number has no stored event")); } - if chain.frozen { - return Ok(Decision::Refuse(Refusal::Frozen)); - } - let after = &event.header.extensions.after; + let deps = unapplied_deps(txn, &event.header.extensions.after)?; if seq == chain.next_seq { if seq > 0 && event.header.backlink != chain.head { - return Ok(Decision::Refuse(Refusal::BacklinkMismatch)); + return Ok(Decision::Park); } - let missing = unapplied(txn, after)?; - if !missing.is_empty() { - return Ok(Decision::Wait(missing)); + if !deps.is_empty() { + return Ok(Decision::Wait(deps)); } - store_event(txn, event)?; - let next_seq = seq - .checked_add(1) - .ok_or_else(|| corrupt("a sequence number overflows"))?; - store_chain( - txn, - &author, - Chain { - next_seq, - head: Some(event.id), - frozen: false, - }, - )?; - return Ok(Decision::Accept); + return accept(txn, event, chain); + } + // Ahead of the chain. The backlink must be applied first, unless it already is, at + // another position, and then this event can never apply. + let mut waits = deps; + let missing_backlink = match event.header.backlink { + Some(backlink) => (!is_applied(txn, &backlink)?).then_some(backlink), + None => None, + }; + waits.extend(missing_backlink); + if waits.is_empty() { + Ok(Decision::Park) + } else { + Ok(Decision::Wait(waits)) + } +} + +/// Stores `event` as the next applied event of its author, and records what it rests on. +fn accept(txn: &WriteTransaction, event: &Event, chain: Chain) -> Result { + let author = author_of(event); + let seq = event.header.seq_num; + store_event(txn, event)?; + index_dependents(txn, event)?; + let next_seq = seq + .checked_add(1) + .ok_or_else(|| corrupt("a sequence number overflows"))?; + store_chain( + txn, + &author, + Chain { + next_seq, + head: Some(event.id), + frozen: chain.frozen, + }, + )?; + Ok(Decision::Accept) +} + +/// Records, for each `after` hash of `event`, that the event rests on it. +fn index_dependents(txn: &WriteTransaction, event: &Event) -> Result<(), StoreError> { + let position = position_key(&author_of(event), event.header.seq_num); + let mut dependents = txn.open_multimap_table(DEPENDENTS)?; + for dep in &event.header.extensions.after { + dependents.insert(dep.as_bytes().as_slice(), position.as_slice())?; + } + Ok(()) +} + +/// Freezes `author` at `seq`. The applied prefix ends there, and every applied event +/// from `seq` up is unapplied, with whatever rests on those. Returns the events that +/// left the applied prefix. +fn freeze_and_unapply( + txn: &WriteTransaction, + author: &AuthorKey, + seq: SeqNum, +) -> Result, StoreError> { + let chain = read_chain(txn, author)?; + set_prefix(txn, author, chain.next_seq, true)?; + unapply_from(txn, *author, seq) +} + +/// Unapplies `author`'s applied events from `seq` up, and every applied event that rests +/// on one of them. Each chain it touches is rewritten to its new applied prefix, with its +/// frozen flag kept. Returns the events that left the applied prefix. +fn unapply_from( + txn: &WriteTransaction, + author: AuthorKey, + seq: SeqNum, +) -> Result, StoreError> { + let mut unapplied = Vec::new(); + let mut pending = vec![(author, seq)]; + while let Some((who, from)) = pending.pop() { + let chain = read_chain(txn, &who)?; + if from >= chain.next_seq { + continue; + } + for position in from..chain.next_seq { + let event = stored_event(txn, &who, position)?; + for dependent in dependents_of(txn, &event.id)? { + pending.push(split_position(&dependent)?); + } + unapplied.push(event.id); + } + set_prefix(txn, &who, from, chain.frozen)?; + } + Ok(unapplied) +} + +/// Writes `author`'s chain row for an applied prefix of `next_seq` events. A chain with +/// no applied event and no fork has no row. +fn set_prefix( + txn: &WriteTransaction, + author: &AuthorKey, + next_seq: SeqNum, + frozen: bool, +) -> Result<(), StoreError> { + if next_seq == 0 && !frozen { + let mut chains = txn.open_table(CHAINS)?; + chains.remove(author.as_slice())?; + return Ok(()); + } + let head = next_seq + .checked_sub(1) + .map(|last| stored_event(txn, author, last)) + .transpose()? + .map(|event| event.id); + store_chain( + txn, + author, + Chain { + next_seq, + head, + frozen, + }, + ) +} + +/// The two events with the lowest IDs among `candidates`, in ID order. The candidates +/// may repeat an event. +fn two_lowest(mut candidates: Vec) -> Result<(Event, Event), StoreError> { + candidates.sort_by(|a, b| a.id.as_bytes().cmp(b.id.as_bytes())); + candidates.dedup_by(|a, b| a.id == b.id); + let mut lowest = candidates.into_iter(); + match (lowest.next(), lowest.next()) { + (Some(first), Some(second)) => Ok((first, second)), + _ => Err(corrupt("a fork needs two distinct events")), } - // Ahead of the chain: the backlink is the event that must come first. - let mut deps = unapplied(txn, after)?; - deps.extend(event.header.backlink); - Ok(Decision::Wait(deps)) +} + +fn author_of(event: &Event) -> AuthorKey { + *event.header.verifying_key.as_bytes() } fn is_stored(txn: &WriteTransaction, id: &Hash) -> Result { @@ -303,12 +448,14 @@ fn is_proof_header( author: &AuthorKey, id: &Hash, ) -> Result { + let proof = read_proof(txn, author)?; + Ok(proof.is_some_and(|proof| proof.first.id == *id || proof.second.id == *id)) +} + +fn read_proof(txn: &WriteTransaction, author: &AuthorKey) -> Result, StoreError> { let forks = txn.open_table(FORKS)?; - let Some(row) = forks.get(author.as_slice())? else { - return Ok(false); - }; - let proof = decode_proof(row.value())?; - Ok(proof.first.id == *id || proof.second.id == *id) + let row = forks.get(author.as_slice())?; + row.map(|row| decode_proof(row.value())).transpose() } fn read_chain(txn: &WriteTransaction, author: &AuthorKey) -> Result { @@ -320,21 +467,38 @@ fn read_chain(txn: &WriteTransaction, author: &AuthorKey) -> Result Result { +) -> Result, StoreError> { let events = txn.open_table(EVENTS)?; let row = events.get(position_key(author, seq).as_slice())?; - match row { - Some(row) => decode_stored(row.value()), - None => Err(corrupt("an applied sequence number has no stored event")), + row.map(|row| decode_stored(row.value())).transpose() +} + +fn stored_event( + txn: &WriteTransaction, + author: &AuthorKey, + seq: SeqNum, +) -> Result { + stored_at(txn, author, seq)? + .ok_or_else(|| corrupt("an applied sequence number has no stored event")) +} + +/// The positions of the stored events that name `id` in their `after` hashes. +fn dependents_of(txn: &WriteTransaction, id: &Hash) -> Result>, StoreError> { + let dependents = txn.open_multimap_table(DEPENDENTS)?; + let mut positions = Vec::new(); + for position in dependents.get(id.as_bytes().as_slice())? { + positions.push(position?.value().to_vec()); } + Ok(positions) } /// The `after` hashes that are not applied yet. -fn unapplied(txn: &WriteTransaction, after: &[Hash]) -> Result, StoreError> { +fn unapplied_deps(txn: &WriteTransaction, after: &[Hash]) -> Result, StoreError> { let mut missing = Vec::new(); for hash in after { if !is_applied(txn, hash)? { @@ -836,10 +1000,7 @@ mod tests { } /// What a store reports for `who`: the chain row and the fork proof. - fn state_of( - store: &EventStore, - who: &AuthorKey, - ) -> (Option, Option) { + fn state_of(store: &EventStore, who: &AuthorKey) -> (Option, Option) { (store.chain(who).unwrap(), store.fork_proof(who).unwrap()) } diff --git a/pkgs/id/src/event_store/mod.rs b/pkgs/id/src/event_store/mod.rs index b9bfb4994c..46208203f3 100644 --- a/pkgs/id/src/event_store/mod.rs +++ b/pkgs/id/src/event_store/mod.rs @@ -12,6 +12,8 @@ //! - `forks`: an author to the fork proof, the two headers that conflict at the //! lowest sequence number where the author has forked. //! - `groups`: a group hash to the positions of the events in that group. +//! - `dependents`: an event's ID to the positions of the stored events that name it in +//! their `after` hashes. A fork uses it to find what rests on the events it voids. //! - `meta`: the store's format. //! //! A position key is the author's 32 bytes followed by the sequence number in @@ -38,8 +40,8 @@ use std::path::{Path, PathBuf}; use p2panda_core::{Hash, SeqNum}; use redb::{ - Database, DatabaseError, MultimapTableDefinition, ReadableDatabase, ReadableTable, - StorageError, TableDefinition, WriteTransaction, + Database, DatabaseError, MultimapTableDefinition, ReadableDatabase, ReadableMultimapTable, + ReadableTable, StorageError, TableDefinition, WriteTransaction, }; use crate::chain::{self, Event}; @@ -57,7 +59,7 @@ pub const FILE_NAME: &str = "events.redb"; pub const TEMP_NAME: &str = "events.redb.tmp"; /// The format row in `meta`. A store with another format is refused. -const FORMAT: &[u8] = b"id.events.store.v1"; +const FORMAT: &[u8] = b"id.events.store.v2"; const FORMAT_KEY: &[u8] = b"format"; const EVENTS: TableDefinition<'static, &'static [u8], &'static [u8]> = @@ -69,6 +71,8 @@ const CHAINS: TableDefinition<'static, &'static [u8], &'static [u8]> = const FORKS: TableDefinition<'static, &'static [u8], &'static [u8]> = TableDefinition::new("forks"); const GROUPS: MultimapTableDefinition<'static, &'static [u8], &'static [u8]> = MultimapTableDefinition::new("groups"); +const DEPENDENTS: MultimapTableDefinition<'static, &'static [u8], &'static [u8]> = + MultimapTableDefinition::new("dependents"); const META: TableDefinition<'static, &'static [u8], &'static [u8]> = TableDefinition::new("meta"); /// Bytes in a position key: the author, then the sequence number. @@ -434,6 +438,7 @@ impl EventStore { let chains = txn.open_table(CHAINS)?; let forks = txn.open_table(FORKS)?; let groups = txn.open_multimap_table(GROUPS)?; + let dependents = txn.open_multimap_table(DEPENDENTS)?; for row in events.iter()? { let (position, bytes) = row?; @@ -455,6 +460,15 @@ impl EventStore { return Err(corrupt("an event is missing from its group index")); } } + for dep in &event.header.extensions.after { + let mut found = false; + for indexed in dependents.get(dep.as_bytes().as_slice())? { + found |= indexed?.value() == position.value(); + } + if !found { + return Err(corrupt("an event is missing from the dependents index")); + } + } } for row in hashes.iter()? { @@ -474,9 +488,31 @@ impl EventStore { .try_into() .map_err(|_err| corrupt("a chain row has a short author key"))?; let chain = Chain::decode(chain_bytes.value())?; + if chain.next_seq == 0 && !chain.frozen { + return Err(corrupt( + "a chain with no applied event and no fork has a row", + )); + } for seq in 0..chain.next_seq { - if events.get(position_key(&author, seq).as_slice())?.is_none() { - return Err(corrupt(format!("applied sequence {seq} is not stored"))); + let stored = events + .get(position_key(&author, seq).as_slice())? + .ok_or_else(|| corrupt(format!("applied sequence {seq} is not stored")))?; + for dep in decode_stored(stored.value())?.header.extensions.after { + let applied = match hashes.get(dep.as_bytes().as_slice())? { + Some(position) => { + let (dep_author, dep_seq) = split_position(position.value())?; + match chains.get(dep_author.as_slice())? { + Some(row) => Chain::decode(row.value())?.next_seq > dep_seq, + None => false, + } + } + None => false, + }; + if !applied { + return Err(corrupt( + "an applied event rests on an event that is not applied", + )); + } } } if let Some(head) = chain.head { @@ -494,10 +530,31 @@ impl EventStore { .transpose()?; match (chain.frozen, proof) { (false, None) => {} - (true, Some(proof)) if proof.seq == chain.next_seq => {} + (true, Some(proof)) if proof.seq >= chain.next_seq => {} _ => { return Err(corrupt( - "a frozen chain has no fork proof at its fork point, or an open chain has one", + "a frozen chain has no fork proof at or above its applied prefix, or an open chain has one", + )); + } + } + } + + for row in dependents.iter()? { + let (dep, positions) = row?; + for position in positions { + let position = position?; + let stored = events + .get(position.value())? + .ok_or_else(|| corrupt("a dependents entry points at no stored event"))?; + let rests_on_dep = decode_stored(stored.value())? + .header + .extensions + .after + .iter() + .any(|hash| hash.as_bytes().as_slice() == dep.value()); + if !rests_on_dep { + return Err(corrupt( + "a dependents entry names an event that does not rest on it", )); } } @@ -549,6 +606,7 @@ fn initialize(db: &Database) -> Result<(), StoreError> { txn.open_table(CHAINS)?; txn.open_table(FORKS)?; txn.open_multimap_table(GROUPS)?; + txn.open_multimap_table(DEPENDENTS)?; let mut meta = txn.open_table(META)?; meta.insert(FORMAT_KEY, FORMAT)?; drop(meta); @@ -565,6 +623,7 @@ fn verify_schema(db: &Database) -> Result<(), StoreError> { txn.open_table(CHAINS).map_err(missing)?; txn.open_table(FORKS).map_err(missing)?; txn.open_multimap_table(GROUPS).map_err(missing)?; + txn.open_multimap_table(DEPENDENTS).map_err(missing)?; let meta = txn.open_table(META).map_err(missing)?; match meta.get(FORMAT_KEY)? { Some(found) if found.value() == FORMAT => Ok(()), @@ -723,7 +782,7 @@ pub(crate) fn store_fork( #[allow(clippy::unwrap_used, clippy::expect_used)] mod tests { use super::*; - use crate::chain::{ChainExt, sign}; + use crate::chain::{sign, ChainExt}; use p2panda_core::SigningKey; fn key(n: u8) -> SigningKey { @@ -831,12 +890,10 @@ mod tests { assert_eq!(store.event(&who, 0).unwrap(), Some(event.clone())); assert_eq!(store.event_by_id(&event.id).unwrap(), Some(event.clone())); assert_eq!(store.group_members(&group).unwrap(), vec![(who, 0)]); - assert!( - store - .group_members(&Hash::digest(b"other")) - .unwrap() - .is_empty() - ); + assert!(store + .group_members(&Hash::digest(b"other")) + .unwrap() + .is_empty()); store.check_invariants().unwrap(); } diff --git a/pkgs/id/src/waiting.rs b/pkgs/id/src/waiting.rs index 705ca397a8..2d39186d52 100644 --- a/pkgs/id/src/waiting.rs +++ b/pkgs/id/src/waiting.rs @@ -115,8 +115,9 @@ pub struct WaitingPool { by_dep: HashMap>, /// Held events by (arrival time, sequence number), for the age cap. by_time: BTreeSet<(u64, u64)>, - /// Held events per author. An author with none has no entry. - per_author: HashMap, + /// The sequence numbers of each author's held events. An author with none has no + /// entry. + held: HashMap>, /// Keys that have arrived. A dependency in this set is already satisfied. arrived: HashSet, /// Events whose dependencies had all arrived when they were inserted. @@ -138,7 +139,7 @@ where by_key: HashMap::new(), by_dep: HashMap::new(), by_time: BTreeSet::new(), - per_author: HashMap::new(), + held: HashMap::new(), arrived: HashSet::new(), ready: Vec::new(), expired: Vec::new(), @@ -157,7 +158,7 @@ where /// The number of events `author` has held. Never above the per-author cap. pub fn waiting_count(&self, author: AuthorKey) -> usize { - self.per_author.get(&author).copied().unwrap_or(0) + self.held.get(&author).map_or(0, BTreeSet::len) } /// Hold `event` until each of `deps` has arrived. @@ -196,6 +197,53 @@ where self.ready.push(event); return Ok(()); } + self.hold(author, key, missing, event, now_ms) + } + + /// Hold `event` for good: it waits for no dependency, so no arrival releases it, + /// and only the age cap drops it. The caller parks an event that can never be + /// applied, but must still see when another event conflicts with it. + /// + /// An event whose key is already held or has arrived is ignored, as for + /// [`insert`](Self::insert). + /// + /// # Errors + /// + /// [`WaitRefusal::AuthorFull`] when the author already holds the per-author cap. + pub fn park( + &mut self, + author: AuthorKey, + key: K, + event: E, + now_ms: u64, + ) -> Result<(), WaitRefusal> { + self.expire_due(now_ms); + if self.arrived.contains(&key) || self.by_key.contains_key(&key) { + return Ok(()); + } + self.hold(author, key, HashSet::new(), event, now_ms) + } + + /// The held events of `author`, in sequence order of arrival. Parked events are + /// included. + pub fn held_by(&self, author: &AuthorKey) -> impl Iterator { + self.held + .get(author) + .into_iter() + .flatten() + .filter_map(|seq| self.waiting.get(seq)) + .map(|entry| &entry.event) + } + + /// Stores `event` under `key`, waiting for `missing`, under the author's cap. + fn hold( + &mut self, + author: AuthorKey, + key: K, + missing: HashSet, + event: E, + now_ms: u64, + ) -> Result<(), WaitRefusal> { if self.waiting_count(author) >= self.limits.per_author() { return Err(WaitRefusal::AuthorFull); } @@ -206,7 +254,7 @@ where } self.by_time.insert((now_ms, seq)); self.by_key.insert(key.clone(), seq); - *self.per_author.entry(author).or_default() += 1; + self.held.entry(author).or_default().insert(seq); self.waiting.insert( seq, Waiting { @@ -307,10 +355,10 @@ where } } } - if let Some(count) = self.per_author.get_mut(&entry.author) { - *count -= 1; - if *count == 0 { - self.per_author.remove(&entry.author); + if let Some(seqs) = self.held.get_mut(&entry.author) { + seqs.remove(&seq); + if seqs.is_empty() { + self.held.remove(&entry.author); } } Some(entry) From 51a97752e185cbac6432e7ad81516db5035f3219 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 11 Oct 2026 20:54:49 -0500 Subject: [PATCH 18/30] test(rust): waiting events must survive a restart [P1.11] Waiting events live only in memory, so a restart drops them. A fork against a waiting event then goes unnoticed, and a dependency that arrives after the restart does not release the event. These two tests fail until the events are persisted. The third test fails for another reason: held_rivals reads the pool before the pool expires anything, so an event past its age cap still counts as a rival. The store must expire first, or its answer depends on when the next pool call happens to run, and a restart changes it. --- pkgs/id/src/event_store/ingest.rs | 80 +++++++++++++++++++++++++++++-- 1 file changed, 76 insertions(+), 4 deletions(-) diff --git a/pkgs/id/src/event_store/ingest.rs b/pkgs/id/src/event_store/ingest.rs index 159c84d97e..1aecd418aa 100644 --- a/pkgs/id/src/event_store/ingest.rs +++ b/pkgs/id/src/event_store/ingest.rs @@ -51,9 +51,9 @@ use p2panda_core::{Hash, SeqNum}; use redb::{ReadableMultimapTable, ReadableTable, WriteTransaction}; use super::{ - corrupt, decode_proof, decode_stored, position_key, split_position, store_chain, store_event, - store_fork, Chain, EventStore, ForkProof, StoreError, CHAINS, DEPENDENTS, EVENTS, FORKS, - HASHES, + CHAINS, Chain, DEPENDENTS, EVENTS, EventStore, FORKS, ForkProof, HASHES, StoreError, corrupt, + decode_proof, decode_stored, position_key, split_position, store_chain, store_event, + store_fork, }; use crate::chain::{self, Event}; use crate::waiting::{AuthorKey, WaitRefusal}; @@ -531,7 +531,7 @@ fn is_applied(txn: &WriteTransaction, hash: &Hash) -> Result { #[allow(clippy::unwrap_used, clippy::expect_used)] mod tests { use super::*; - use crate::chain::{sign, ChainExt}; + use crate::chain::{ChainExt, sign}; use crate::waiting::WaitingLimits; use p2panda_core::SigningKey; @@ -1258,4 +1258,76 @@ mod tests { "the orders reach different states: {states:?}" ); } + + #[test] + fn test_a_waiting_event_is_held_across_a_restart() { + let dir = tempfile::tempdir().unwrap(); + let signer = key(31); + let events = chain_of(&signer, 2); + { + let mut store = EventStore::open(dir.path()).unwrap(); + assert_eq!( + ingest(&mut store, &events[1]), + Ingest::Waiting { id: events[1].id } + ); + } + let mut store = EventStore::open(dir.path()).unwrap(); + assert_eq!( + store.waiting_len(), + 1, + "the waiting event is still held after the restart" + ); + assert_eq!( + ingest(&mut store, &events[0]), + Ingest::Accepted { + id: events[0].id, + released: vec![events[1].id], + } + ); + store.check_invariants().unwrap(); + } + + #[test] + fn test_a_fork_against_a_waiting_event_is_seen_after_a_restart() { + let dir = tempfile::tempdir().unwrap(); + let signer = key(32); + let who = author(&signer); + let events = chain_of(&signer, 2); + { + let mut store = EventStore::open(dir.path()).unwrap(); + assert_eq!( + ingest(&mut store, &events[1]), + Ingest::Waiting { id: events[1].id } + ); + } + let mut store = EventStore::open(dir.path()).unwrap(); + let rival = event(&signer, 1, Some(events[0].id), Vec::new(), "rival"); + assert_eq!( + ingest(&mut store, &rival), + Ingest::Fork { + author: who, + seq: 1 + } + ); + store.check_invariants().unwrap(); + } + + #[test] + fn test_an_expired_waiting_event_is_not_a_rival() { + let (_dir, store) = open(); + let mut store = store.with_waiting_limits(WaitingLimits::new(256, 1_000)); + let signer = key(33); + let events = chain_of(&signer, 2); + assert_eq!( + store.ingest(&events[1].bytes, 0).unwrap(), + Ingest::Waiting { id: events[1].id } + ); + // The waiting event is due at 1_000, so it has expired before the rival arrives. + let rival = event(&signer, 1, Some(events[0].id), Vec::new(), "rival"); + assert_eq!( + store.ingest(&rival.bytes, 1_000).unwrap(), + Ingest::Waiting { id: rival.id } + ); + assert_eq!(store.waiting_len(), 1, "only the rival is held"); + } } From 66983e25beacd10a896d8e14e0ee7c32ec5312cb Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 11 Oct 2026 21:53:33 -0500 Subject: [PATCH 19/30] chore(repo): allow the id scope in the conform config --- .conform.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/.conform.yaml b/.conform.yaml index 4e00594191..ca6737864c 100755 --- a/.conform.yaml +++ b/.conform.yaml @@ -10,6 +10,7 @@ policies: - laptop-framework - nix - rust + - id - nvim - vim - vi From 24093a87a3f069bb59ad4f63c0ae467e9f8cdbd4 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 11 Oct 2026 22:02:54 -0500 Subject: [PATCH 20/30] feat(rust): waiting events survive restarts in redb [P1.11] Waiting and parked events are rows in a `waiting` table, with a `waiting_by_dep` index from each dependency. The pool in memory mirrors them. Each change to the pool and its rows runs in one write transaction, and each ingest call is one transaction, so a crash keeps the whole call or none of it. An event is never both applied and waiting. On open the pool is rebuilt from the rows. Rows due at the clock given to open are dropped, and so are rows past an author's cap, counted in arrival order. A failed write rebuilds the pool. If that fails too, the store refuses calls until it is reopened. Expiry now runs before a call looks for rivals. An event past its age still counted as a rival until the pool happened to run, so a restart could change the answer. The red tests are in 51a97752. Format v3. A v2 store is refused, since there is no migration. open and open_with take the caps and the clock, with_waiting_limits is removed, and expire_waiting returns a Result. Tests: restarts for hold, release, expiry, refusal by cap, and parking; the release order of waiters kept across a restart; the crash workload now holds and parks events, and after every crash point each acknowledged waiting event must be held or stored; a property over random arrival orders with restarts; the cap limit pinned as a known limit. --- pkgs/id/src/event_store/ingest.rs | 631 +++++++++++++++++++----- pkgs/id/src/event_store/mod.rs | 320 ++++++++++-- pkgs/id/src/event_store/waiting_rows.rs | 273 ++++++++++ pkgs/id/src/store_traits.rs | 3 +- pkgs/id/src/waiting.rs | 95 +++- pkgs/id/tests/common/ingest.rs | 5 +- pkgs/id/tests/crash/store.rs | 64 ++- pkgs/id/tests/event_store_properties.rs | 108 +++- 8 files changed, 1333 insertions(+), 166 deletions(-) create mode 100644 pkgs/id/src/event_store/waiting_rows.rs diff --git a/pkgs/id/src/event_store/ingest.rs b/pkgs/id/src/event_store/ingest.rs index 1aecd418aa..7e25578a75 100644 --- a/pkgs/id/src/event_store/ingest.rs +++ b/pkgs/id/src/event_store/ingest.rs @@ -17,13 +17,13 @@ //! 5. **Accept.** The next sequence number, whose backlink is the applied head, is applied //! once every `after` hash is applied. //! 6. **Wait or park.** An event ahead of its chain, or with an `after` hash that is not -//! applied yet, is held in the waiting pool under its caps, and decided again when its -//! dependencies are applied. An event whose backlink can never be the applied head is -//! parked: held for good, so that a conflict with it is still seen. +//! applied yet, is held in the waiting pool and its row, under the caps, and decided again +//! when its dependencies are applied. An event whose backlink can never be the applied head +//! is parked: held for good, so that a conflict with it is still seen. //! -//! Each decision that writes runs in one redb write transaction. A refused or held event -//! writes nothing, and an accepted one is committed before any event it released is -//! decided. +//! Each call runs in one redb write transaction. It holds every decision the call causes: the +//! event, each event it releases, the expiry of due events, and the waiting rows. The call +//! commits all of them or none. A refused event and a duplicate write nothing. //! //! # Applied state and forks //! @@ -40,7 +40,16 @@ //! next sequence number, so the chain row is what marks the voids. //! //! Held events count too. Two held events at one sequence number are a fork, though -//! neither is applied. A restart forgets held events, and sync sends them again. +//! neither is applied. Held events are rows on disk, so a restart keeps them, and a conflict +//! with an event held before the restart is still seen. An event the caps or the age limit +//! drops is forgotten, and sync sends it again. +//! +//! # Known limit: a rival refused by a cap +//! +//! A conflict is found only against an event the store holds. A rival refused by its author's +//! cap is not held, so when the other event arrives, no conflict is seen. The fork is seen when +//! the refused rival is sent again, while the other event is still held. The behaviour is +//! pinned by `test_a_rival_refused_by_the_cap_is_seen_only_when_sent_again`. //! //! The property tests in `tests/event_store_properties.rs` check the applied state against //! this definition, for every arrival order. @@ -50,13 +59,14 @@ use std::collections::VecDeque; use p2panda_core::{Hash, SeqNum}; use redb::{ReadableMultimapTable, ReadableTable, WriteTransaction}; +use super::waiting_rows::{Hold, Mirror}; use super::{ CHAINS, Chain, DEPENDENTS, EVENTS, EventStore, FORKS, ForkProof, HASHES, StoreError, corrupt, decode_proof, decode_stored, position_key, split_position, store_chain, store_event, store_fork, }; use crate::chain::{self, Event}; -use crate::waiting::{AuthorKey, WaitRefusal}; +use crate::waiting::{AuthorKey, WaitingPool}; /// Why an event was refused. A refused event changes nothing. #[derive(Clone, Debug, PartialEq, Eq)] @@ -96,9 +106,9 @@ pub enum Ingest { /// The fork point: the lowest sequence number where the author conflicts. seq: SeqNum, }, - /// The event is held in memory and not stored. It waits for a dependency, or it is - /// parked because its backlink can never be the applied head. Sync sends it again if - /// it is lost. + /// The event is held, and not stored. It waits for a dependency, or it is parked because its + /// backlink can never be the applied head. The hold is on disk, so a restart keeps it. Sync + /// sends it again if the caps or the age limit drop it. Waiting { /// The event's ID. id: Hash, @@ -117,9 +127,9 @@ enum Decision { /// A conflict. The proof is written, and the fork point is `seq`. `unapplied` are /// the events that left the applied prefix, which the waiting pool forgets. Fork { seq: SeqNum, unapplied: Vec }, - /// Waits for these dependencies, none of which is applied. Nothing written. + /// Waits for these dependencies, none of which is applied. The caller holds the event. Wait(Vec), - /// Can never apply, but is held so that a conflict with it is seen. Nothing written. + /// Can never apply, but is held so that a conflict with it is seen. The caller holds it. Park, /// Refused. Nothing written. Refuse(Refusal), @@ -128,122 +138,183 @@ enum Decision { impl EventStore { /// Verifies one received event and applies what it allows. /// - /// `now_ms` is the clock the waiting caps use. It is a parameter so tests can - /// run on a fake clock. + /// `now_ms` is the clock. The events due at it expire first, so the caps and the rivals + /// see only the events still held. It is a parameter so tests can run on a fake clock. /// /// # Errors /// - /// Returns a redb or corruption error. A refusal is not an error: it comes back - /// as [`Ingest::Refused`]. + /// Returns a redb or corruption error. A refusal is not an error: it comes back as + /// [`Ingest::Refused`]. After an error the waiting events are rebuilt from disk. If that + /// fails too, the store refuses further calls until it is reopened. pub fn ingest(&mut self, bytes: &[u8], now_ms: u64) -> Result { let event = match chain::decode(bytes) { Ok(event) => event, Err(err) => return Ok(Ingest::Refused(Refusal::Malformed(err.to_string()))), }; - let id = event.id; - let author = author_of(&event); - let rivals = self.held_rivals(&event); - match self.decide(&event, &rivals)? { - Decision::Accept => { - let arrived = self.waiting.arrived(id, now_ms); - let released = self.drain(arrived.into(), now_ms)?; - Ok(Ingest::Accepted { id, released }) - } - Decision::Duplicate => Ok(Ingest::Duplicate { id }), - Decision::Fork { seq, unapplied } => { - self.forget(&unapplied); - Ok(Ingest::Fork { author, seq }) - } - Decision::Wait(deps) => { - let outcome = match self.waiting.insert(author, id, deps, event, now_ms) { - Ok(()) => Ingest::Waiting { id }, - Err(WaitRefusal::AuthorFull) => Ingest::Refused(Refusal::WaitingFull), - }; - self.drain(VecDeque::new(), now_ms)?; - Ok(outcome) - } - Decision::Park => match self.waiting.park(author, id, event, now_ms) { - Ok(()) => Ok(Ingest::Waiting { id }), - Err(WaitRefusal::AuthorFull) => Ok(Ingest::Refused(Refusal::WaitingFull)), - }, - Decision::Refuse(refusal) => Ok(Ingest::Refused(refusal)), - } + self.transact(now_ms, |mirror| ingest_in(mirror, event, now_ms)) } - /// Drops the waiting events that have reached the age cap at `now_ms`. Returns - /// how many were dropped. - pub fn expire_waiting(&mut self, now_ms: u64) -> usize { - self.waiting.expire(now_ms).len() + /// Drops the waiting events due at `now_ms`, with their rows. Returns how many were dropped. + /// + /// # Errors + /// + /// Returns a redb error if the write fails. The waiting events are then rebuilt from disk. + pub fn expire_waiting(&mut self, now_ms: u64) -> Result { + self.transact(now_ms, |mirror| { + let expired = mirror.expire(now_ms)?; + Ok((expired, expired > 0)) + }) } - /// The number of events held waiting, across all authors. + /// The number of events held, waiting or parked, across all authors. pub fn waiting_len(&self) -> usize { self.waiting.len() } - /// The number of events `author` has waiting. + /// The number of events `author` has held. pub fn waiting_count(&self, author: &AuthorKey) -> usize { self.waiting.waiting_count(*author) } - /// The held events that conflict with `event`: the author's other events at its - /// sequence number. - fn held_rivals(&self, event: &Event) -> Vec { - let author = author_of(event); - let seq = event.header.seq_num; - self.waiting - .held_by(&author) - .filter(|held| held.header.seq_num == seq && held.id != event.id) - .cloned() - .collect() + /// Whether the event with this ID is held, waiting or parked. + pub fn is_waiting(&self, id: &Hash) -> bool { + self.waiting.contains(id) } +} - /// Decides `event` in one write transaction. A decision that writes nothing aborts - /// the transaction. - fn decide(&self, event: &Event, rivals: &[Event]) -> Result { - let txn = self.db.begin_write()?; - let decision = decide_in(&txn, event, rivals)?; - if matches!(decision, Decision::Accept | Decision::Fork { .. }) { - txn.commit()?; +/// Decides a received event inside the call's transaction, and the events it releases. Returns +/// the outcome, and whether the call changed anything. A call that expired events has changed +/// something, even if its own event was refused. +fn ingest_in(m: &mut Mirror<'_>, event: Event, now: u64) -> Result<(Ingest, bool), StoreError> { + let expired = m.expire(now)?; + let id = event.id; + let author = author_of(&event); + let rivals = held_rivals(m.pool, &event); + let outcome = match settle(m, event, &rivals, now, false)? { + Settled::Accepted { released } => Ingest::Accepted { + id, + released: drain(m, released.into(), now)?, + }, + Settled::Duplicate => Ingest::Duplicate { id }, + Settled::Fork { seq, unapplied } => { + forget(m.pool, &unapplied); + Ingest::Fork { author, seq } } - Ok(decision) - } - - /// Applies the events in `queue`, then each waiting event they release, until - /// nothing more applies. Returns the IDs of the waiting events applied, in order. - fn drain(&mut self, mut queue: VecDeque, now_ms: u64) -> Result, StoreError> { - let mut applied = Vec::new(); - queue.extend(self.waiting.take_ready()); - while let Some(event) = queue.pop_front() { - let id = event.id; - let author = author_of(&event); - let rivals = self.held_rivals(&event); - match self.decide(&event, &rivals)? { - Decision::Accept => { - applied.push(id); - queue.extend(self.waiting.arrived(id, now_ms)); - } - Decision::Fork { unapplied, .. } => self.forget(&unapplied), - Decision::Wait(deps) => { - // A refused insert drops the event, as an event past the cap is dropped. - let _ = self.waiting.insert(author, id, deps, event, now_ms); - } - Decision::Park => { - let _ = self.waiting.park(author, id, event, now_ms); - } - Decision::Duplicate | Decision::Refuse(_) => {} - } - queue.extend(self.waiting.take_ready()); + Settled::Held | Settled::Skipped => { + drain(m, VecDeque::new(), now)?; + Ingest::Waiting { id } + } + Settled::Refused(refusal) => Ingest::Refused(refusal), + }; + let changed = expired > 0 || !matches!(outcome, Ingest::Duplicate { .. } | Ingest::Refused(_)); + Ok((outcome, changed)) +} + +/// What one decision did, once the pool and the rows agree with it. +enum Settled { + /// Applied. `released` are the events that waited only for it, and each is due a decision. + Accepted { released: Vec }, + /// Already stored, or a fork proof header. Nothing changed. + Duplicate, + /// A conflict at `seq`. `unapplied` left the applied prefix. + Fork { seq: SeqNum, unapplied: Vec }, + /// Held, waiting or parked. + Held, + /// The pool did not keep the event. See [`Hold::Skipped`]. + Skipped, + /// Refused. Nothing is held. + Refused(Refusal), +} + +/// Decides `event` inside the transaction, and brings the pool and the rows into line with the +/// decision. `from_pool` is true for an event the pool released: it is no longer held, so a final +/// decision removes its row. Otherwise the event is new, or it is held and still is, so a +/// decision that leaves it held keeps its row. +fn settle( + m: &mut Mirror<'_>, + event: Event, + rivals: &[Event], + now: u64, + from_pool: bool, +) -> Result { + let id = event.id; + let settled = match decide_in(m.txn, &event, rivals)? { + Decision::Accept => Settled::Accepted { + released: m.release(&id, now)?, + }, + Decision::Duplicate => { + drop_released(m, &id, from_pool)?; + Settled::Duplicate + } + Decision::Fork { seq, unapplied } => { + drop_released(m, &id, from_pool)?; + Settled::Fork { seq, unapplied } } - Ok(applied) + Decision::Refuse(refusal) => { + drop_released(m, &id, from_pool)?; + Settled::Refused(refusal) + } + Decision::Wait(deps) => held(m.hold(event, deps, false, now)?), + Decision::Park => held(m.hold(event, Vec::new(), true, now)?), + }; + Ok(settled) +} + +fn drop_released(m: &Mirror<'_>, id: &Hash, from_pool: bool) -> Result<(), StoreError> { + if from_pool { + m.drop_row(id)?; + } + Ok(()) +} + +const fn held(hold: Hold) -> Settled { + match hold { + Hold::Held => Settled::Held, + Hold::Full => Settled::Refused(Refusal::WaitingFull), + Hold::Skipped => Settled::Skipped, } +} - /// Tells the waiting pool that these events are no longer applied, so events that - /// wait on them wait again. - fn forget(&mut self, unapplied: &[Hash]) { - for id in unapplied { - self.waiting.forget(id); +/// Decides the events in `queue`, and each event they release, until none is left. Returns the +/// IDs of the events applied, in order. +fn drain( + m: &mut Mirror<'_>, + mut queue: VecDeque, + now: u64, +) -> Result, StoreError> { + let mut applied = Vec::new(); + queue.extend(m.pool.take_ready()); + while let Some(event) = queue.pop_front() { + let id = event.id; + let rivals = held_rivals(m.pool, &event); + match settle(m, event, &rivals, now, true)? { + Settled::Accepted { released } => { + applied.push(id); + queue.extend(released); + } + Settled::Fork { unapplied, .. } => forget(m.pool, &unapplied), + Settled::Duplicate | Settled::Held | Settled::Skipped | Settled::Refused(_) => {} } + queue.extend(m.pool.take_ready()); + } + Ok(applied) +} + +/// The held events that conflict with `event`: the author's other events at its sequence number. +fn held_rivals(pool: &WaitingPool, event: &Event) -> Vec { + let author = author_of(event); + let seq = event.header.seq_num; + pool.held_by(&author) + .filter(|held| held.header.seq_num == seq && held.id != event.id) + .cloned() + .collect() +} + +/// Tells the pool that these events are no longer applied, so the events that wait on them wait +/// again. +fn forget(pool: &mut WaitingPool, unapplied: &[Hash]) { + for id in unapplied { + pool.forget(id); } } @@ -510,8 +581,16 @@ fn unapplied_deps(txn: &WriteTransaction, after: &[Hash]) -> Result, S /// Whether the event with this ID is applied: stored, at a sequence number below its /// author's applied prefix. -fn is_applied(txn: &WriteTransaction, hash: &Hash) -> Result { - let hashes = txn.open_table(HASHES)?; +pub(super) fn is_applied(txn: &WriteTransaction, hash: &Hash) -> Result { + applied_in(&txn.open_table(HASHES)?, &txn.open_table(CHAINS)?, hash) +} + +/// [`is_applied`] over the `hashes` and `chains` tables, whether they are read or written. +pub(super) fn applied_in( + hashes: &impl ReadableTable<&'static [u8], &'static [u8]>, + chains: &impl ReadableTable<&'static [u8], &'static [u8]>, + hash: &Hash, +) -> Result { let position = hashes .get(hash.as_bytes().as_slice())? .map(|found| found.value().to_vec()); @@ -519,7 +598,6 @@ fn is_applied(txn: &WriteTransaction, hash: &Hash) -> Result { return Ok(false); }; let (author, seq) = split_position(&position)?; - let chains = txn.open_table(CHAINS)?; let row = chains.get(author.as_slice())?; match row { Some(row) => Ok(Chain::decode(row.value())?.next_seq > seq), @@ -532,6 +610,7 @@ fn is_applied(txn: &WriteTransaction, hash: &Hash) -> Result { mod tests { use super::*; use crate::chain::{ChainExt, sign}; + use crate::event_store::waiting_rows::{self, Row}; use crate::waiting::WaitingLimits; use p2panda_core::SigningKey; @@ -572,8 +651,12 @@ mod tests { } fn open() -> (tempfile::TempDir, EventStore) { + open_with(WaitingLimits::default()) + } + + fn open_with(limits: WaitingLimits) -> (tempfile::TempDir, EventStore) { let dir = tempfile::tempdir().unwrap(); - let store = EventStore::open(dir.path()).unwrap(); + let store = EventStore::open(dir.path(), limits, 0).unwrap(); (dir, store) } @@ -894,8 +977,7 @@ mod tests { #[test] fn test_waiting_events_past_the_author_cap_are_refused() { - let (_dir, store) = open(); - let mut store = store.with_waiting_limits(WaitingLimits::new(2, WEEK_MS)); + let (_dir, mut store) = open_with(WaitingLimits::new(2, WEEK_MS)); let signer = key(15); let who = author(&signer); let events = chain_of(&signer, 5); @@ -917,12 +999,11 @@ mod tests { #[test] fn test_a_waiting_event_expires_and_is_not_released_by_its_dependency() { - let (_dir, store) = open(); - let mut store = store.with_waiting_limits(WaitingLimits::new(256, 1_000)); + let (_dir, mut store) = open_with(WaitingLimits::new(256, 1_000)); let signer = key(16); let events = chain_of(&signer, 2); store.ingest(&events[1].bytes, 0).unwrap(); - assert_eq!(store.expire_waiting(1_000), 1); + assert_eq!(store.expire_waiting(1_000).unwrap(), 1); assert_eq!( store.ingest(&events[0].bytes, 1_000).unwrap(), Ingest::Accepted { @@ -968,11 +1049,11 @@ mod tests { let events = chain_of(&signer, 2); let rival = event(&signer, 1, Some(events[0].id), Vec::new(), "rival"); { - let mut store = EventStore::open(dir.path()).unwrap(); + let mut store = EventStore::open(dir.path(), WaitingLimits::default(), 0).unwrap(); ingest_all(&mut store, &events); ingest(&mut store, &rival); } - let store = EventStore::open(dir.path()).unwrap(); + let store = EventStore::open(dir.path(), WaitingLimits::default(), 0).unwrap(); assert_eq!( store.chain(&who).unwrap(), Some(Chain { @@ -1265,13 +1346,13 @@ mod tests { let signer = key(31); let events = chain_of(&signer, 2); { - let mut store = EventStore::open(dir.path()).unwrap(); + let mut store = EventStore::open(dir.path(), WaitingLimits::default(), 0).unwrap(); assert_eq!( ingest(&mut store, &events[1]), Ingest::Waiting { id: events[1].id } ); } - let mut store = EventStore::open(dir.path()).unwrap(); + let mut store = EventStore::open(dir.path(), WaitingLimits::default(), 0).unwrap(); assert_eq!( store.waiting_len(), 1, @@ -1287,6 +1368,35 @@ mod tests { store.check_invariants().unwrap(); } + #[test] + fn test_a_restart_keeps_the_order_in_which_waiters_are_released() { + let dir = tempfile::tempdir().unwrap(); + let root0 = event(&key(48), 0, None, Vec::new(), "message"); + // Eight authors each hold one event that waits for `root0`. The rows are keyed by hash, + // so only the arrival number keeps them in this order across a restart. + let waiters: Vec = (0..8) + .map(|n| event(&key(50 + n), 0, None, vec![root0.id], "message")) + .collect(); + { + let mut store = reopen(&dir, WaitingLimits::default(), 0); + for waiter in &waiters { + assert_eq!( + ingest(&mut store, waiter), + Ingest::Waiting { id: waiter.id } + ); + } + } + let store = reopen(&dir, WaitingLimits::default(), 0); + let mut store = store; + assert_eq!( + ingest(&mut store, &root0), + Ingest::Accepted { + id: root0.id, + released: waiters.iter().map(|waiter| waiter.id).collect(), + } + ); + } + #[test] fn test_a_fork_against_a_waiting_event_is_seen_after_a_restart() { let dir = tempfile::tempdir().unwrap(); @@ -1294,13 +1404,13 @@ mod tests { let who = author(&signer); let events = chain_of(&signer, 2); { - let mut store = EventStore::open(dir.path()).unwrap(); + let mut store = EventStore::open(dir.path(), WaitingLimits::default(), 0).unwrap(); assert_eq!( ingest(&mut store, &events[1]), Ingest::Waiting { id: events[1].id } ); } - let mut store = EventStore::open(dir.path()).unwrap(); + let mut store = EventStore::open(dir.path(), WaitingLimits::default(), 0).unwrap(); let rival = event(&signer, 1, Some(events[0].id), Vec::new(), "rival"); assert_eq!( ingest(&mut store, &rival), @@ -1314,8 +1424,7 @@ mod tests { #[test] fn test_an_expired_waiting_event_is_not_a_rival() { - let (_dir, store) = open(); - let mut store = store.with_waiting_limits(WaitingLimits::new(256, 1_000)); + let (_dir, mut store) = open_with(WaitingLimits::new(256, 1_000)); let signer = key(33); let events = chain_of(&signer, 2); assert_eq!( @@ -1330,4 +1439,288 @@ mod tests { ); assert_eq!(store.waiting_len(), 1, "only the rival is held"); } + + /// Opens the store in `dir` again, with `limits`, at clock `now`. + fn reopen(dir: &tempfile::TempDir, limits: WaitingLimits, now: u64) -> EventStore { + EventStore::open(dir.path(), limits, now).unwrap() + } + + #[test] + fn test_a_release_survives_a_restart_as_one_change() { + let dir = tempfile::tempdir().unwrap(); + let signer = key(34); + let who = author(&signer); + let events = chain_of(&signer, 2); + { + let mut store = reopen(&dir, WaitingLimits::default(), 0); + assert_eq!( + ingest(&mut store, &events[1]), + Ingest::Waiting { id: events[1].id } + ); + assert_eq!( + ingest(&mut store, &events[0]), + Ingest::Accepted { + id: events[0].id, + released: vec![events[1].id], + } + ); + } + let store = reopen(&dir, WaitingLimits::default(), 0); + assert!( + !store.is_waiting(&events[1].id), + "the released event applies" + ); + assert_eq!(store.chain(&who).unwrap().unwrap().next_seq, 2); + assert!(store.waiting_ids().unwrap().is_empty()); + store.check_invariants().unwrap(); + } + + #[test] + fn test_a_waiting_event_past_its_age_is_dropped_on_open() { + let dir = tempfile::tempdir().unwrap(); + let limits = WaitingLimits::new(256, 1_000); + let signer = key(35); + let events = chain_of(&signer, 2); + { + let mut store = reopen(&dir, limits, 0); + assert_eq!( + store.ingest(&events[1].bytes, 0).unwrap(), + Ingest::Waiting { id: events[1].id } + ); + } + // Not due yet: the event has waited 999 ms. + let store = reopen(&dir, limits, 999); + assert!(store.is_waiting(&events[1].id)); + drop(store); + // Due at 1_000 ms, so the open drops it and its row. + let store = reopen(&dir, limits, 1_000); + assert_eq!(store.waiting_len(), 0); + assert!(store.waiting_ids().unwrap().is_empty()); + store.check_invariants().unwrap(); + drop(store); + let store = reopen(&dir, limits, 1_000); + assert_eq!(store.waiting_len(), 0, "a dropped event stays dropped"); + } + + #[test] + fn test_an_expiry_made_by_expire_waiting_persists() { + let dir = tempfile::tempdir().unwrap(); + let signer = key(36); + let events = chain_of(&signer, 2); + { + let mut store = reopen(&dir, WaitingLimits::default(), 0); + store.ingest(&events[1].bytes, 0).unwrap(); + assert_eq!(store.expire_waiting(WEEK_MS).unwrap(), 1); + } + let store = reopen(&dir, WaitingLimits::default(), 0); + assert_eq!(store.waiting_len(), 0); + assert!(store.waiting_ids().unwrap().is_empty()); + } + + #[test] + fn test_a_refused_waiting_event_leaves_no_row() { + let dir = tempfile::tempdir().unwrap(); + let limits = WaitingLimits::new(1, WEEK_MS); + let signer = key(37); + let events = chain_of(&signer, 3); + { + let mut store = reopen(&dir, limits, 0); + assert_eq!( + ingest(&mut store, &events[1]), + Ingest::Waiting { id: events[1].id } + ); + assert_eq!( + ingest(&mut store, &events[2]), + Ingest::Refused(Refusal::WaitingFull) + ); + } + let store = reopen(&dir, limits, 0); + assert_eq!(store.waiting_ids().unwrap(), vec![events[1].id]); + assert!(!store.is_waiting(&events[2].id)); + } + + #[test] + fn test_a_smaller_cap_on_reopen_drops_the_later_arrivals() { + let dir = tempfile::tempdir().unwrap(); + let signer = key(38); + let who = author(&signer); + let events = chain_of(&signer, 4); + { + let mut store = reopen(&dir, WaitingLimits::new(3, WEEK_MS), 0); + for event in &events[1..] { + assert_eq!(ingest(&mut store, event), Ingest::Waiting { id: event.id }); + } + assert_eq!(store.waiting_count(&who), 3); + } + // With a cap of two, the first two arrivals are kept, and the third row goes. + let store = reopen(&dir, WaitingLimits::new(2, WEEK_MS), 0); + assert_eq!(store.waiting_count(&who), 2); + assert!(store.is_waiting(&events[1].id)); + assert!(store.is_waiting(&events[2].id)); + assert!(!store.is_waiting(&events[3].id)); + assert_eq!(store.waiting_ids().unwrap().len(), 2); + store.check_invariants().unwrap(); + } + + #[test] + fn test_a_parked_event_is_held_across_a_restart_and_still_sees_a_conflict() { + let dir = tempfile::tempdir().unwrap(); + let signer = key(39); + let who = author(&signer); + let events = chain_of(&signer, 1); + let stray = event( + &signer, + 1, + Some(Hash::digest(b"not the head")), + Vec::new(), + "stray", + ); + { + let mut store = reopen(&dir, WaitingLimits::default(), 0); + ingest_all(&mut store, &events); + assert_eq!(ingest(&mut store, &stray), Ingest::Waiting { id: stray.id }); + } + let mut store = reopen(&dir, WaitingLimits::default(), 0); + assert!( + store.is_waiting(&stray.id), + "the parked event is still held" + ); + let rival = event(&signer, 1, Some(events[0].id), Vec::new(), "rival"); + assert_eq!( + ingest(&mut store, &rival), + Ingest::Fork { + author: who, + seq: 1 + } + ); + store.check_invariants().unwrap(); + } + + #[test] + fn test_an_event_released_into_a_frozen_chain_leaves_no_row() { + let dir = tempfile::tempdir().unwrap(); + let (x, y) = (key(40), key(41)); + let x_events = chain_of(&x, 2); + let y0 = event(&y, 0, None, Vec::new(), "message"); + let waits = event(&x, 2, Some(x_events[1].id), vec![y0.id], "message"); + let rival = event(&x, 1, Some(x_events[0].id), Vec::new(), "rival"); + { + let mut store = reopen(&dir, WaitingLimits::default(), 0); + ingest_all(&mut store, &x_events); + assert_eq!(ingest(&mut store, &waits), Ingest::Waiting { id: waits.id }); + assert!(matches!( + ingest(&mut store, &rival), + Ingest::Fork { seq: 1, .. } + )); + } + let mut store = reopen(&dir, WaitingLimits::default(), 0); + assert!( + store.is_waiting(&waits.id), + "the event waits across the restart" + ); + // Its dependency arrives, so it is released. Its chain is frozen at 1, so it is refused. + assert_eq!( + ingest(&mut store, &y0), + Ingest::Accepted { + id: y0.id, + released: vec![], + } + ); + assert!(!store.is_waiting(&waits.id)); + assert!(store.waiting_ids().unwrap().is_empty()); + store.check_invariants().unwrap(); + } + + #[test] + fn test_a_rival_refused_by_the_cap_is_seen_only_when_sent_again() { + // The known limit in the module docs. The author's one slot holds `filler`, so the rival + // is refused and not held. When the original arrives, nothing conflicts with it. + let (_dir, mut store) = open_with(WaitingLimits::new(1, WEEK_MS)); + let signer = key(45); + let who = author(&signer); + let missing = Hash::digest(b"an event that is never delivered"); + let original = event(&signer, 1, Some(missing), Vec::new(), "message"); + let rival = event(&signer, 1, Some(missing), Vec::new(), "rival"); + let filler = event(&signer, 2, Some(missing), Vec::new(), "filler"); + assert_eq!( + ingest(&mut store, &filler), + Ingest::Waiting { id: filler.id } + ); + assert_eq!( + ingest(&mut store, &rival), + Ingest::Refused(Refusal::WaitingFull) + ); + // At WEEK_MS the filler is due, so the slot is free for the original. + assert_eq!( + store.ingest(&original.bytes, WEEK_MS).unwrap(), + Ingest::Waiting { id: original.id } + ); + assert!( + store.fork_proof(&who).unwrap().is_none(), + "the refused rival is not held, so no conflict is seen" + ); + // Sent again, the rival finds the original, which is held. + assert_eq!( + store.ingest(&rival.bytes, WEEK_MS).unwrap(), + Ingest::Fork { + author: who, + seq: 1 + } + ); + store.check_invariants().unwrap(); + } + + #[test] + fn test_a_write_whose_rebuild_fails_makes_the_store_refuse_calls() { + let (_dir, mut store) = open_with(WaitingLimits::new(256, 1_000)); + let signer = key(47); + let events = chain_of(&signer, 2); + store.ingest(&events[1].bytes, 0).unwrap(); + // The row no longer decodes. The expiry that drops it fails, and so does the rebuild. + store + .write(|txn| { + let mut rows = txn.open_table(crate::event_store::WAITING)?; + rows.insert(events[1].id.as_bytes().as_slice(), b"garbage".as_slice())?; + Ok(()) + }) + .unwrap(); + assert!(matches!( + store.expire_waiting(1_000), + Err(StoreError::Corrupt(_)) + )); + assert!(matches!( + store.expire_waiting(1_000), + Err(StoreError::Unusable) + )); + assert!(matches!( + store.ingest(&events[0].bytes, 1_000), + Err(StoreError::Unusable) + )); + } + + #[test] + fn test_invariants_refuse_a_waiting_event_whose_dependency_is_applied() { + let (_dir, mut store) = open(); + let (x, y) = (key(42), key(43)); + let x0 = event(&x, 0, None, Vec::new(), "message"); + ingest_all(&mut store, std::slice::from_ref(&x0)); + // The pool and the row both hold an event that waits for x0, which is already applied. + let waits = event(&y, 0, None, vec![x0.id], "message"); + let row = Row { + id: waits.id, + author: author(&y), + seq: 0, + arrived_at: 0, + arrival: 0, + deps: vec![x0.id], + bytes: waits.bytes.clone(), + }; + store + .waiting + .restore(author(&y), waits.id, [x0.id], waits, 0) + .unwrap(); + store.write(|txn| waiting_rows::put(txn, &row)).unwrap(); + let err = store.check_invariants().unwrap_err(); + assert!(err.to_string().contains("applied"), "{err}"); + } } diff --git a/pkgs/id/src/event_store/mod.rs b/pkgs/id/src/event_store/mod.rs index 0cc23b16fe..997a78da1c 100644 --- a/pkgs/id/src/event_store/mod.rs +++ b/pkgs/id/src/event_store/mod.rs @@ -14,6 +14,9 @@ //! - `groups`: a group hash to the positions of the events in that group. //! - `dependents`: an event's ID to the positions of the stored events that name it in //! their `after` hashes. A fork uses it to find what rests on the events it voids. +//! - `waiting` and `waiting_by_dep`: the events held waiting or parked, and an index from each +//! dependency to the rows that wait for it. The `waiting_rows` module describes them, and +//! the waiting pool in memory mirrors them. //! - `meta`: the store's format. //! //! A position key is the author's 32 bytes followed by the sequence number in @@ -28,12 +31,19 @@ //! commit leave a file that redb refuses to open, so the store could never start. //! The crash model in `tests/crash/store.rs` checks every step of this sequence. //! +//! # Restarts +//! +//! The held events are rows, so a restart keeps them. [`EventStore::open`] rebuilds the waiting +//! pool from the rows. It drops the events due at the clock it is given, and any past an author's +//! cap, counting in arrival order. +//! //! # Where the files are //! //! [`EventStore::open`] takes a directory. [`Storage`] is the seam between the //! store and its files: [`FileStorage`] is the disk, and the crash model in tests //! implements the same trait over a simulated directory. +use std::collections::BTreeMap; use std::fs; use std::io; use std::path::{Path, PathBuf}; @@ -47,9 +57,12 @@ use redb::{ use crate::chain::{self, Event}; mod ingest; +mod waiting_rows; -use crate::waiting::{AuthorKey, WaitingLimits, WaitingPool}; +use crate::waiting::{AuthorKey, WaitRefusal, WaitingLimits, WaitingPool}; pub use ingest::{Ingest, Refusal}; +use ingest::{applied_in, is_applied}; +use waiting_rows::{Mirror, Row}; /// The store's file name in its directory. pub const FILE_NAME: &str = "events.redb"; @@ -59,7 +72,7 @@ pub const FILE_NAME: &str = "events.redb"; pub const TEMP_NAME: &str = "events.redb.tmp"; /// The format row in `meta`. A store with another format is refused. -const FORMAT: &[u8] = b"id.events.store.v2"; +const FORMAT: &[u8] = b"id.events.store.v3"; const FORMAT_KEY: &[u8] = b"format"; const EVENTS: TableDefinition<'static, &'static [u8], &'static [u8]> = @@ -73,6 +86,10 @@ const GROUPS: MultimapTableDefinition<'static, &'static [u8], &'static [u8]> = MultimapTableDefinition::new("groups"); const DEPENDENTS: MultimapTableDefinition<'static, &'static [u8], &'static [u8]> = MultimapTableDefinition::new("dependents"); +const WAITING: TableDefinition<'static, &'static [u8], &'static [u8]> = + TableDefinition::new("waiting"); +const WAITING_BY_DEP: MultimapTableDefinition<'static, &'static [u8], &'static [u8]> = + MultimapTableDefinition::new("waiting_by_dep"); const META: TableDefinition<'static, &'static [u8], &'static [u8]> = TableDefinition::new("meta"); /// Bytes in a position key: the author, then the sequence number. @@ -118,6 +135,10 @@ pub enum StoreError { /// The sequence number that is taken. seq: SeqNum, }, + /// A write failed, and the waiting events could not be rebuilt from disk. The store + /// refuses further calls. Reopening it rebuilds them. + #[error("event store is unusable after a failed write: reopen it")] + Unusable, } fn corrupt(message: impl Into) -> StoreError { @@ -296,20 +317,27 @@ pub struct ForkProof { #[derive(Debug)] pub struct EventStore { db: Database, - /// Events that wait for a dependency. They are held in memory, not stored. + /// The caps the pool enforces. Kept, so the pool can be rebuilt from its rows. + limits: WaitingLimits, + /// The events held waiting or parked. The `waiting` rows mirror them. waiting: WaitingPool, + /// The arrival number the next held event takes. + next_arrival: u64, + /// Set when a write failed and the pool could not be rebuilt. Calls fail until reopen. + unusable: bool, } impl EventStore { - /// Opens the store in `dir`, creating it if the directory has none. + /// Opens the store in `dir`, creating it if the directory has none. `limits` are the caps + /// on waiting events, and `now_ms` is the clock: the waiting events due at it are dropped. /// /// # Errors /// /// Returns [`StoreError::InUse`] if another process has it open, and /// [`StoreError::NotAStore`] if the file is not an event store. Neither /// deletes or changes the file. - pub fn open(dir: &Path) -> Result { - Self::open_with(&FileStorage::new(dir)) + pub fn open(dir: &Path, limits: WaitingLimits, now_ms: u64) -> Result { + Self::open_with(&FileStorage::new(dir), limits, now_ms) } /// Opens the store on `storage`, creating it if the storage has none. The crash model @@ -318,25 +346,26 @@ impl EventStore { /// # Errors /// /// The same errors as [`EventStore::open`]. - pub fn open_with(storage: &S) -> Result { + pub fn open_with( + storage: &S, + limits: WaitingLimits, + now_ms: u64, + ) -> Result { let db = if storage.exists(FILE_NAME)? { storage.open_database(FILE_NAME).map_err(open_error)? } else { create_fresh(storage)? }; verify_schema(&db)?; - Ok(Self { + let mut store = Self { db, - waiting: WaitingPool::new(WaitingLimits::default()), - }) - } - - /// Sets the caps on waiting events: how many one author may hold, and how long - /// one may wait. The pool starts empty, so set the caps before ingesting. - #[must_use] - pub fn with_waiting_limits(mut self, limits: WaitingLimits) -> Self { - self.waiting = WaitingPool::new(limits); - self + limits, + waiting: WaitingPool::new(limits), + next_arrival: 0, + unusable: false, + }; + store.reload(now_ms)?; + Ok(store) } /// Runs `op` in one write transaction. The transaction commits if `op` @@ -425,7 +454,8 @@ impl EventStore { /// Checks the store's own rows against each other: every applied sequence is /// stored, every head matches its event, every index points at a stored - /// event, and each frozen chain has a matching fork proof. + /// event, and each frozen chain has a matching fork proof. The waiting rows + /// agree with the pool, the dependency index, and the applied state. /// /// # Errors /// @@ -572,6 +602,179 @@ impl EventStore { )); } } + self.check_waiting() + } + + /// Checks the waiting rows against the pool and the applied state. Each row decodes and names + /// its event, is held by the pool, and is not stored. Each dependency it waits for is not + /// applied, and the dependency index lists exactly those. The pool's counts match the rows, + /// and no author is over the cap. + fn check_waiting(&self) -> Result<(), StoreError> { + let txn = self.db.begin_read()?; + let rows = txn.open_table(WAITING)?; + let by_dep = txn.open_multimap_table(WAITING_BY_DEP)?; + let hashes = txn.open_table(HASHES)?; + let chains = txn.open_table(CHAINS)?; + let mut per_author: BTreeMap = BTreeMap::new(); + let mut total = 0; + for entry in rows.iter()? { + let (key, value) = entry?; + let row = Row::decode(hash_of(key.value())?, value.value())?; + row_event(&row)?; + if hashes.get(row.id.as_bytes().as_slice())?.is_some() { + return Err(corrupt("a waiting event is also stored")); + } + if !self.waiting.contains(&row.id) { + return Err(corrupt("a waiting row is not held by the pool")); + } + for dep in &row.deps { + if applied_in(&hashes, &chains, dep)? { + return Err(corrupt( + "a waiting event waits for a dependency that is applied", + )); + } + let mut indexed = false; + for waiter in by_dep.get(dep.as_bytes().as_slice())? { + indexed |= hash_of(waiter?.value())? == row.id; + } + if !indexed { + return Err(corrupt( + "a waiting event is missing from the dependency index", + )); + } + } + *per_author.entry(row.author).or_default() += 1; + total += 1; + } + for entry in by_dep.iter()? { + let (dep, waiters) = entry?; + for waiter in waiters { + let waiter = hash_of(waiter?.value())?; + let found = rows.get(waiter.as_bytes().as_slice())?.ok_or_else(|| { + corrupt("the dependency index names a waiting event with no row") + })?; + let row = Row::decode(waiter, found.value())?; + if !row + .deps + .iter() + .any(|d| d.as_bytes().as_slice() == dep.value()) + { + return Err(corrupt( + "the dependency index names a row that does not wait for it", + )); + } + } + } + if total != self.waiting.len() { + return Err(corrupt( + "the pool holds a different number of events than the rows", + )); + } + for (author, count) in per_author { + if count > self.limits.per_author() || self.waiting.waiting_count(author) != count { + return Err(corrupt( + "the pool's count for an author differs from the rows", + )); + } + } + Ok(()) + } + + /// The IDs of the held events, as their rows on disk name them, in ID order. + /// + /// # Errors + /// + /// Returns a redb error if the read fails, or [`StoreError::Corrupt`]. + pub fn waiting_ids(&self) -> Result, StoreError> { + let txn = self.db.begin_read()?; + let rows = txn.open_table(WAITING)?; + let mut ids = Vec::new(); + for entry in rows.iter()? { + let (key, _value) = entry?; + ids.push(hash_of(key.value())?); + } + Ok(ids) + } + + /// Runs `op` in one write transaction against the waiting pool and its rows. The transaction + /// commits if `op` reports a change, and is aborted otherwise. If the call fails, the pool may + /// have moved on from the rows, so it is rebuilt from them. If that fails too, the store + /// refuses further calls. + fn transact( + &mut self, + now_ms: u64, + op: impl FnOnce(&mut Mirror<'_>) -> Result<(T, bool), StoreError>, + ) -> Result { + if self.unusable { + return Err(StoreError::Unusable); + } + let result = self.attempt(op); + if result.is_err() && self.reload(now_ms).is_err() { + self.unusable = true; + } + result + } + + fn attempt( + &mut self, + op: impl FnOnce(&mut Mirror<'_>) -> Result<(T, bool), StoreError>, + ) -> Result { + let txn = self.db.begin_write()?; + let (value, changed) = { + let mut mirror = Mirror { + txn: &txn, + pool: &mut self.waiting, + arrivals: &mut self.next_arrival, + }; + op(&mut mirror)? + }; + if changed { + txn.commit()?; + } else { + txn.abort()?; + } + Ok(value) + } + + /// Rebuilds the waiting pool from the rows, in arrival order. A row due at `now_ms` is + /// dropped, and so is a row past its author's cap. The drops commit with the rebuild. A row + /// that waits for an applied event means the rows and the applied state disagree, so the + /// rebuild fails as corruption and the pool is left as it was. + fn reload(&mut self, now_ms: u64) -> Result<(), StoreError> { + let txn = self.db.begin_write()?; + let mut pool = WaitingPool::new(self.limits); + let mut next_arrival = 0; + let mut dropped = false; + for row in waiting_rows::all(&txn)? { + next_arrival = next_arrival.max(row.arrival.saturating_add(1)); + if self.limits.is_due(row.arrived_at, now_ms) { + waiting_rows::delete(&txn, &row.id)?; + dropped = true; + continue; + } + for dep in &row.deps { + if is_applied(&txn, dep)? { + return Err(corrupt( + "a waiting event waits for a dependency that is applied", + )); + } + } + let event = row_event(&row)?; + match pool.restore(row.author, row.id, row.deps, event, row.arrived_at) { + Ok(()) => {} + Err(WaitRefusal::AuthorFull) => { + waiting_rows::delete(&txn, &row.id)?; + dropped = true; + } + } + } + if dropped { + txn.commit()?; + } else { + txn.abort()?; + } + self.waiting = pool; + self.next_arrival = next_arrival; Ok(()) } @@ -607,6 +810,8 @@ fn initialize(db: &Database) -> Result<(), StoreError> { txn.open_table(FORKS)?; txn.open_multimap_table(GROUPS)?; txn.open_multimap_table(DEPENDENTS)?; + txn.open_table(WAITING)?; + txn.open_multimap_table(WAITING_BY_DEP)?; let mut meta = txn.open_table(META)?; meta.insert(FORMAT_KEY, FORMAT)?; drop(meta); @@ -624,6 +829,8 @@ fn verify_schema(db: &Database) -> Result<(), StoreError> { txn.open_table(FORKS).map_err(missing)?; txn.open_multimap_table(GROUPS).map_err(missing)?; txn.open_multimap_table(DEPENDENTS).map_err(missing)?; + txn.open_table(WAITING).map_err(missing)?; + txn.open_multimap_table(WAITING_BY_DEP).map_err(missing)?; let meta = txn.open_table(META).map_err(missing)?; match meta.get(FORMAT_KEY)? { Some(found) if found.value() == FORMAT => Ok(()), @@ -692,6 +899,18 @@ fn decode_stored(bytes: &[u8]) -> Result { chain::decode(bytes).map_err(|err| corrupt(format!("a stored event does not decode: {err}"))) } +/// Decodes a row's event, and checks that the row names it: its ID, its author, and its sequence +/// number. +fn row_event(row: &Row) -> Result { + let event = chain::decode(&row.bytes) + .map_err(|err| corrupt(format!("a waiting event does not decode: {err}")))?; + let author = *event.header.verifying_key.as_bytes(); + if event.id != row.id || author != row.author || event.header.seq_num != row.seq { + return Err(corrupt("a waiting row does not match its event")); + } + Ok(event) +} + /// Encodes a fork proof: the sequence number, the length of the first header, /// then the two headers, ordered by ID. pub(crate) fn encode_proof(seq: SeqNum, a: &Event, b: &Event) -> Result, StoreError> { @@ -825,7 +1044,7 @@ impl EventStore { #[allow(clippy::unwrap_used, clippy::expect_used)] mod tests { use super::*; - use crate::chain::{sign, ChainExt}; + use crate::chain::{ChainExt, sign}; use p2panda_core::SigningKey; fn key(n: u8) -> SigningKey { @@ -857,20 +1076,20 @@ mod tests { fn open_temp() -> (tempfile::TempDir, EventStore) { let dir = tempfile::tempdir().unwrap(); - let store = EventStore::open(dir.path()).unwrap(); + let store = EventStore::open(dir.path(), WaitingLimits::default(), 0).unwrap(); (dir, store) } #[test] fn test_a_new_store_is_created_empty_and_reopens() { let dir = tempfile::tempdir().unwrap(); - let store = EventStore::open(dir.path()).unwrap(); + let store = EventStore::open(dir.path(), WaitingLimits::default(), 0).unwrap(); assert!(store.chain(&author(&key(1))).unwrap().is_none()); store.check_invariants().unwrap(); assert!(dir.path().join(FILE_NAME).exists()); assert!(!dir.path().join(TEMP_NAME).exists(), "no temp file is left"); drop(store); - let reopened = EventStore::open(dir.path()).unwrap(); + let reopened = EventStore::open(dir.path(), WaitingLimits::default(), 0).unwrap(); reopened.check_invariants().unwrap(); } @@ -878,7 +1097,7 @@ mod tests { fn test_a_stale_temp_file_is_replaced_not_trusted() { let dir = tempfile::tempdir().unwrap(); fs::write(dir.path().join(TEMP_NAME), b"half a store from a crash").unwrap(); - let store = EventStore::open(dir.path()).unwrap(); + let store = EventStore::open(dir.path(), WaitingLimits::default(), 0).unwrap(); store.check_invariants().unwrap(); assert!(!dir.path().join(TEMP_NAME).exists()); } @@ -888,7 +1107,7 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let garbage = b"this is not a redb database at all".to_vec(); fs::write(dir.path().join(FILE_NAME), &garbage).unwrap(); - let err = EventStore::open(dir.path()).unwrap_err(); + let err = EventStore::open(dir.path(), WaitingLimits::default(), 0).unwrap_err(); assert!( matches!(err, StoreError::NotAStore(_)), "unexpected error: {err}" @@ -900,10 +1119,10 @@ mod tests { #[test] fn test_a_second_opener_is_refused_while_the_first_is_open() { let (dir, store) = open_temp(); - let err = EventStore::open(dir.path()).unwrap_err(); + let err = EventStore::open(dir.path(), WaitingLimits::default(), 0).unwrap_err(); assert!(matches!(err, StoreError::InUse), "unexpected error: {err}"); drop(store); - EventStore::open(dir.path()).unwrap(); + EventStore::open(dir.path(), WaitingLimits::default(), 0).unwrap(); } #[test] @@ -933,10 +1152,12 @@ mod tests { assert_eq!(store.event(&who, 0).unwrap(), Some(event.clone())); assert_eq!(store.event_by_id(&event.id).unwrap(), Some(event.clone())); assert_eq!(store.group_members(&group).unwrap(), vec![(who, 0)]); - assert!(store - .group_members(&Hash::digest(b"other")) - .unwrap() - .is_empty()); + assert!( + store + .group_members(&Hash::digest(b"other")) + .unwrap() + .is_empty() + ); store.check_invariants().unwrap(); } @@ -1076,4 +1297,41 @@ mod tests { ); assert!(store.event(&who, 3).unwrap().is_some()); } + + #[test] + fn test_a_store_of_the_previous_format_is_refused_and_keeps_its_data() { + let dir = tempfile::tempdir().unwrap(); + // The tables of format v2, which had no waiting rows. + let db = Database::builder() + .create(dir.path().join(FILE_NAME)) + .unwrap(); + let txn = db.begin_write().unwrap(); + txn.open_table(EVENTS).unwrap(); + txn.open_table(HASHES).unwrap(); + txn.open_table(CHAINS).unwrap(); + txn.open_table(FORKS).unwrap(); + txn.open_multimap_table(GROUPS).unwrap(); + txn.open_multimap_table(DEPENDENTS).unwrap(); + { + let mut meta = txn.open_table(META).unwrap(); + meta.insert(FORMAT_KEY, b"id.events.store.v2".as_slice()) + .unwrap(); + } + txn.commit().unwrap(); + drop(db); + let err = EventStore::open(dir.path(), WaitingLimits::default(), 0).unwrap_err(); + assert!( + matches!(err, StoreError::NotAStore(_)), + "unexpected error: {err}" + ); + // redb's own open may bump its header counter, so the bytes can change. The data must not: + // the format row still names the old format. + let db = Database::builder() + .open(dir.path().join(FILE_NAME)) + .unwrap(); + let txn = db.begin_read().unwrap(); + let meta = txn.open_table(META).unwrap(); + let found = meta.get(FORMAT_KEY).unwrap().unwrap(); + assert_eq!(found.value(), b"id.events.store.v2".as_slice()); + } } diff --git a/pkgs/id/src/event_store/waiting_rows.rs b/pkgs/id/src/event_store/waiting_rows.rs new file mode 100644 index 0000000000..ac57a45358 --- /dev/null +++ b/pkgs/id/src/event_store/waiting_rows.rs @@ -0,0 +1,273 @@ +//! The waiting rows: the events held on disk, and the [`Mirror`] that keeps them in step with +//! the waiting pool. +//! +//! An event is held when it has arrived but cannot apply yet: a dependency is missing, or it +//! can never apply and is parked, so that a conflict with it is still seen. The pool holds it +//! in memory, under the caps in [`WaitingLimits`](crate::waiting::WaitingLimits). The same +//! events are written to two tables: +//! +//! - `waiting`: an event's ID to its row. The row holds the author, the sequence number, the +//! arrival time, the arrival number, the dependencies the event still waits for, and the +//! encoded event. A parked event has no dependencies. +//! - `waiting_by_dep`: a dependency's ID to the IDs of the rows that wait for it. +//! +//! The pool and the rows change together through [`Mirror`]. Each call on a `Mirror` makes one +//! change to the pool and the matching change to the rows, inside one write transaction. If +//! the transaction commits, the two agree, and a crash leaves the state as of the last commit. +//! On open the pool is rebuilt from the rows. + +use p2panda_core::{Hash, SeqNum}; +use redb::{ReadableMultimapTable, ReadableTable, WriteTransaction}; + +use super::{StoreError, WAITING, WAITING_BY_DEP, be_u64, corrupt, hash_of, seq_num}; +use crate::chain::Event; +use crate::waiting::{AuthorKey, WaitRefusal, WaitingPool}; + +/// Bytes before a row's dependencies: the author, the sequence number, the arrival time, the +/// arrival number, and the dependency count. +const HEAD_LEN: usize = 32 + 8 + 8 + 8 + 1; + +/// One held event, as its row holds it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(super) struct Row { + /// The event's ID, which is the row's key. + pub id: Hash, + /// The event's author. + pub author: AuthorKey, + /// The event's sequence number. + pub seq: SeqNum, + /// The clock time the event was held at. The age cap counts from here. + pub arrived_at: u64, + /// The order the event was held in. Rows reload in this order, so the pool releases the + /// events in the order it did before a restart. + pub arrival: u64, + /// The dependencies the event still waits for. Empty for a parked event. + pub deps: Vec, + /// The encoded event. + pub bytes: Vec, +} + +impl Row { + fn encode(&self) -> Result, StoreError> { + let count = u8::try_from(self.deps.len()) + .map_err(|_err| corrupt("a waiting event names too many dependencies"))?; + let mut row = Vec::with_capacity(HEAD_LEN + 32 * self.deps.len() + self.bytes.len()); + row.extend_from_slice(&self.author); + row.extend_from_slice(&u64::from(self.seq).to_be_bytes()); + row.extend_from_slice(&self.arrived_at.to_be_bytes()); + row.extend_from_slice(&self.arrival.to_be_bytes()); + row.push(count); + for dep in &self.deps { + row.extend_from_slice(dep.as_bytes()); + } + row.extend_from_slice(&self.bytes); + Ok(row) + } + + pub(super) fn decode(id: Hash, row: &[u8]) -> Result { + if row.len() < HEAD_LEN { + return Err(corrupt("a waiting row is shorter than its header")); + } + let author: AuthorKey = row[..32] + .try_into() + .map_err(|_err| corrupt("a waiting row has a short author"))?; + let seq = seq_num(be_u64(&row[32..40])?)?; + let arrived_at = be_u64(&row[40..48])?; + let arrival = be_u64(&row[48..56])?; + let deps_end = HEAD_LEN + 32 * usize::from(row[56]); + if row.len() < deps_end { + return Err(corrupt( + "a waiting row names more dependencies than it holds", + )); + } + let deps = row[HEAD_LEN..deps_end] + .chunks_exact(32) + .map(hash_of) + .collect::, StoreError>>()?; + Ok(Self { + id, + author, + seq, + arrived_at, + arrival, + deps, + bytes: row[deps_end..].to_vec(), + }) + } +} + +/// The row for `id`, if one is held. +pub(super) fn get(txn: &WriteTransaction, id: &Hash) -> Result, StoreError> { + let rows = txn.open_table(WAITING)?; + let found = rows.get(id.as_bytes().as_slice())?; + found + .map(|found| Row::decode(*id, found.value())) + .transpose() +} + +/// Every row, in arrival order. +pub(super) fn all(txn: &WriteTransaction) -> Result, StoreError> { + let rows = txn.open_table(WAITING)?; + let mut all = Vec::new(); + for entry in rows.iter()? { + let (key, value) = entry?; + all.push(Row::decode(hash_of(key.value())?, value.value())?); + } + all.sort_by_key(|row| row.arrival); + Ok(all) +} + +/// Writes `row` in place of any row with its ID, and indexes the dependencies it waits for. +pub(super) fn put(txn: &WriteTransaction, row: &Row) -> Result<(), StoreError> { + if let Some(old) = get(txn, &row.id)? { + unindex(txn, &old)?; + } + let encoded = row.encode()?; + let mut rows = txn.open_table(WAITING)?; + rows.insert(row.id.as_bytes().as_slice(), encoded.as_slice())?; + drop(rows); + let mut by_dep = txn.open_multimap_table(WAITING_BY_DEP)?; + for dep in &row.deps { + by_dep.insert(dep.as_bytes().as_slice(), row.id.as_bytes().as_slice())?; + } + Ok(()) +} + +/// Removes the row for `id`, if there is one. +pub(super) fn delete(txn: &WriteTransaction, id: &Hash) -> Result<(), StoreError> { + let Some(old) = get(txn, id)? else { + return Ok(()); + }; + unindex(txn, &old)?; + let mut rows = txn.open_table(WAITING)?; + rows.remove(id.as_bytes().as_slice())?; + Ok(()) +} + +fn unindex(txn: &WriteTransaction, row: &Row) -> Result<(), StoreError> { + let mut by_dep = txn.open_multimap_table(WAITING_BY_DEP)?; + for dep in &row.deps { + by_dep.remove(dep.as_bytes().as_slice(), row.id.as_bytes().as_slice())?; + } + Ok(()) +} + +/// The IDs of the rows that wait for `dep`. +fn waiters_of(txn: &WriteTransaction, dep: &Hash) -> Result, StoreError> { + let by_dep = txn.open_multimap_table(WAITING_BY_DEP)?; + let mut waiters = Vec::new(); + for waiter in by_dep.get(dep.as_bytes().as_slice())? { + waiters.push(hash_of(waiter?.value())?); + } + Ok(waiters) +} + +/// What [`Mirror::hold`] did with an event. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Hold { + /// The event is held, and its row is written. + Held, + /// The author already holds the cap, so the event is not held. + Full, + /// The pool did not keep the event: it had nothing left to wait for, so it is in the + /// pool's ready list, or it had already arrived. Nothing is held. + Skipped, +} + +/// The waiting pool and its rows, inside one write transaction. Every method changes the pool +/// and the rows together, so the two agree whenever the transaction commits. +pub(super) struct Mirror<'a> { + /// The transaction that every row change runs in. + pub txn: &'a WriteTransaction, + /// The pool. Callers read it for rival checks and take ready events from it. + pub pool: &'a mut WaitingPool, + /// The arrival number the next held event takes. + pub arrivals: &'a mut u64, +} + +impl Mirror<'_> { + /// Drops every held event that is due at `now`, with its row. Returns how many were + /// dropped. + pub fn expire(&mut self, now: u64) -> Result { + let expired = self.pool.expire(now); + for (_author, event) in &expired { + delete(self.txn, &event.id)?; + } + Ok(expired.len()) + } + + /// Holds `event` at clock time `now`, either parked or waiting for `deps`, and writes its + /// row. An event that is already held is left as it is. + pub fn hold( + &mut self, + event: Event, + deps: Vec, + parked: bool, + now: u64, + ) -> Result { + let id = event.id; + if self.pool.contains(&id) { + return Ok(Hold::Held); + } + let author = *event.header.verifying_key.as_bytes(); + let seq = event.header.seq_num; + let bytes = event.bytes.clone(); + let mut deps = deps; + deps.sort_unstable_by(|a, b| a.as_bytes().cmp(b.as_bytes())); + deps.dedup(); + let stored_deps = if parked { Vec::new() } else { deps.clone() }; + // The ingest call has already expired what is due at `now`, so the pool expires nothing + // here, and the event it holds is not due until a later call. + let result = if parked { + self.pool.park(author, id, event, now) + } else { + self.pool.insert(author, id, deps, event, now) + }; + match result { + Ok(()) if self.pool.contains(&id) => { + let arrival = *self.arrivals; + *self.arrivals += 1; + let row = Row { + id, + author, + seq, + arrived_at: now, + arrival, + deps: stored_deps, + bytes, + }; + put(self.txn, &row)?; + Ok(Hold::Held) + } + Ok(()) => { + delete(self.txn, &id)?; + Ok(Hold::Skipped) + } + Err(WaitRefusal::AuthorFull) => { + delete(self.txn, &id)?; + Ok(Hold::Full) + } + } + } + + /// Releases the events that waited only for `id`, which has just applied. The held copy of + /// `id`, if there is one, ends here, and its row goes. Each row that waited for `id` loses + /// that dependency. Returns the released events in arrival order. Their rows stay until the + /// caller decides each one. + pub fn release(&mut self, id: &Hash, now: u64) -> Result, StoreError> { + let released = self.pool.arrived(*id, now); + delete(self.txn, id)?; + for waiter in waiters_of(self.txn, id)? { + let mut row = get(self.txn, &waiter)? + .ok_or_else(|| corrupt("a dependency is indexed to a waiting event with no row"))?; + row.deps.retain(|dep| dep != id); + put(self.txn, &row)?; + } + Ok(released) + } + + /// Removes the row of an event the pool has released, once it is decided for good. + pub fn drop_row(&self, id: &Hash) -> Result<(), StoreError> { + delete(self.txn, id) + } +} diff --git a/pkgs/id/src/store_traits.rs b/pkgs/id/src/store_traits.rs index 263ba71da4..d0d0cc47ac 100644 --- a/pkgs/id/src/store_traits.rs +++ b/pkgs/id/src/store_traits.rs @@ -453,6 +453,7 @@ mod tests { use super::*; use crate::chain::{ChainExt, sign}; + use crate::waiting::WaitingLimits; fn key(n: u8) -> SigningKey { SigningKey::from_bytes(&[n; 32]) @@ -495,7 +496,7 @@ mod tests { fn open() -> (tempfile::TempDir, SharedEventStore) { let dir = tempfile::tempdir().unwrap(); - let store = EventStore::open(dir.path()).unwrap(); + let store = EventStore::open(dir.path(), WaitingLimits::default(), 0).unwrap(); (dir, SharedEventStore::new(store)) } diff --git a/pkgs/id/src/waiting.rs b/pkgs/id/src/waiting.rs index 2d39186d52..3e99a6ac60 100644 --- a/pkgs/id/src/waiting.rs +++ b/pkgs/id/src/waiting.rs @@ -8,9 +8,10 @@ //! is not acknowledged, and sync sends it again once its dependency exists. //! //! The pool does no I/O and takes the clock as an explicit `now_ms`, so tests -//! use a fake clock. It is not connected to storage yet: the event store (P1.3) -//! will supply the arrivals. Until then the pool keeps its own set of arrived -//! keys. +//! use a fake clock. The event store holds one pool and mirrors it into the +//! `waiting` table (P1.11). [`WaitingPool::restore`] rebuilds the pool from those +//! rows on open. The pool keeps its own set of arrived keys, for the filter in +//! [`WaitingPool::insert`]. //! //! The caller's loop: //! @@ -70,6 +71,17 @@ impl WaitingLimits { pub const fn max_age_ms(self) -> u64 { self.max_age_ms } + + /// Whether an event that arrived at `arrived_at_ms` is due at `now_ms`, that is, it has + /// waited [`max_age_ms`](Self::max_age_ms) or longer. This is the rule + /// [`WaitingPool::expire`] applies, for a store that filters its rows on open. A clock + /// that is behind the arrival time has not made the event due. + pub const fn is_due(self, arrived_at_ms: u64, now_ms: u64) -> bool { + match now_ms.checked_sub(arrived_at_ms) { + Some(waited) => waited >= self.max_age_ms, + None => false, + } + } } impl Default for WaitingLimits { @@ -224,6 +236,36 @@ where self.hold(author, key, HashSet::new(), event, now_ms) } + /// Whether an event with this key is held: waiting, or parked. + pub fn contains(&self, key: &K) -> bool { + self.by_key.contains_key(key) + } + + /// Holds an event that arrived at `arrived_at`, as a store restores its rows on open. + /// + /// Unlike [`insert`](Self::insert) and [`park`](Self::park), nothing expires first, and an + /// empty `missing` does not release the event: it is held for good, as a parked event is. + /// The caller restores the events in the order they arrived, so they are released in that + /// order. An event whose key is already held is ignored. + /// + /// # Errors + /// + /// [`WaitRefusal::AuthorFull`] when the author already holds the per-author cap. + pub fn restore( + &mut self, + author: AuthorKey, + key: K, + missing: impl IntoIterator, + event: E, + arrived_at: u64, + ) -> Result<(), WaitRefusal> { + if self.by_key.contains_key(&key) { + return Ok(()); + } + let missing: HashSet = missing.into_iter().collect(); + self.hold(author, key, missing, event, arrived_at) + } + /// The held events of `author`, in sequence order of arrival. Parked events are /// included. pub fn held_by(&self, author: &AuthorKey) -> impl Iterator { @@ -594,4 +636,51 @@ mod tests { assert_eq!(pool.waiting_count(author(2)), 0); assert!(pool.is_empty()); } + + #[test] + fn test_restore_holds_a_parked_event_and_counts_its_age_from_arrival() { + let mut pool = pool(); + pool.restore(author(1), 1, [], "parked", 500).unwrap(); + assert!( + pool.take_ready().is_empty(), + "an empty missing set does not release the event" + ); + assert!(pool.contains(&1)); + assert_eq!(pool.waiting_count(author(1)), 1); + assert!(pool.expire(500 + WEEK_MS - 1).is_empty()); + assert_eq!(pool.expire(500 + WEEK_MS), vec![(author(1), "parked")]); + } + + #[test] + fn test_restore_keeps_the_cap_and_ignores_a_key_already_held() { + let mut pool = WaitingPool::new(WaitingLimits::new(1, WEEK_MS)); + pool.restore(author(1), 1, [10], "first", 0).unwrap(); + pool.restore(author(1), 1, [10], "again", 0).unwrap(); + assert_eq!(pool.waiting_count(author(1)), 1); + assert_eq!( + pool.restore(author(1), 2, [11], "refused", 0), + Err(WaitRefusal::AuthorFull) + ); + assert!(!pool.contains(&2)); + assert_eq!(pool.arrived(10, 0), vec!["first"]); + } + + #[test] + fn test_is_due_agrees_with_expire_at_every_boundary() { + for max_age_ms in [0, 5, 10] { + for arrived_at in [0, 3, 10] { + for now_ms in [0, 4, 9, 10, 11, 15, 20] { + let limits = WaitingLimits::new(8, max_age_ms); + let mut pool = WaitingPool::new(limits); + pool.insert(author(1), 1, [9], "e", arrived_at).unwrap(); + let dropped = !pool.expire(now_ms).is_empty(); + assert_eq!( + dropped, + limits.is_due(arrived_at, now_ms), + "max age {max_age_ms}, arrived {arrived_at}, now {now_ms}" + ); + } + } + } + } } diff --git a/pkgs/id/tests/common/ingest.rs b/pkgs/id/tests/common/ingest.rs index 10de646f4b..cfd51c4553 100644 --- a/pkgs/id/tests/common/ingest.rs +++ b/pkgs/id/tests/common/ingest.rs @@ -11,7 +11,7 @@ use std::time::Duration; use id::chain::decode; use id::event_store::{Chain, EventStore, Storage}; -use id::waiting::AuthorKey; +use id::waiting::{AuthorKey, WaitingLimits}; use p2panda_core::{Hash, SeqNum}; use redb::backends::InMemoryBackend; use redb::{Database, DatabaseError, StorageBackend, StorageError}; @@ -162,7 +162,8 @@ impl Storage for MemStorage { /// /// Describes the first delivery or invariant that fails. pub fn deliver(order: &[Vec], authors: &[AuthorKey]) -> Result { - let mut store = EventStore::open_with(&MemStorage::default()).map_err(|err| err.to_string())?; + let mut store = EventStore::open_with(&MemStorage::default(), WaitingLimits::default(), 0) + .map_err(|err| err.to_string())?; for bytes in order { store .ingest(bytes, 0) diff --git a/pkgs/id/tests/crash/store.rs b/pkgs/id/tests/crash/store.rs index ae314b2270..2c9f833fdf 100644 --- a/pkgs/id/tests/crash/store.rs +++ b/pkgs/id/tests/crash/store.rs @@ -20,6 +20,7 @@ use std::sync::{Arc, Mutex, MutexGuard}; use id::chain::{self, ChainExt, sign}; use id::event_store::{EventStore, FILE_NAME, Ingest, Refusal, Storage}; +use id::waiting::WaitingLimits; use p2panda_core::{Hash, SigningKey}; use redb::{Database, DatabaseError, StorageBackend, StorageError, TableDefinition}; @@ -349,7 +350,7 @@ const SAMPLED: [(Survive, Tear); 2] = [POLICIES[0], POLICIES[2]]; /// The creation this sweep runs: the store's own open, which creates the file when it is absent. fn creation(sim: &SimDir) { - let _ = EventStore::open_with(sim); + let _ = EventStore::open_with(sim, WaitingLimits::default(), 0); } /// The control: a file built in place, with one committed write. It has no temporary name and no @@ -370,7 +371,7 @@ fn in_place(sim: &SimDir) { /// Reopens one crash state with the store and checks what it holds. fn reopens(disk: &Disk) -> Result<(), String> { - let store = EventStore::open_with(&SimDir::from_disk(disk)) + let store = EventStore::open_with(&SimDir::from_disk(disk), WaitingLimits::default(), 0) .map_err(|err| format!("does not open: {err}"))?; store .check_invariants() @@ -419,10 +420,13 @@ fn creation_in_place_control_fails_at_some_crash_point() { } /// The deliveries the ingest sweep makes after creation: a wait that a later event releases, an -/// after hash on another author's event, a fork, an event refused as frozen, and two repeats. +/// after hash on another author's event, a fork, an event refused as frozen, two repeats, and the +/// waiting events that stay held to the end: a fork between two held events, and a parked event. fn workload() -> Vec> { let author = SigningKey::from_bytes(&[21; 32]); let other = SigningKey::from_bytes(&[22; 32]); + let held = SigningKey::from_bytes(&[23; 32]); + let parked = SigningKey::from_bytes(&[24; 32]); let ext = |kind: &str, after: Vec| ChainExt { kind: kind.to_owned(), group: None, @@ -434,6 +438,21 @@ fn workload() -> Vec> { let a2_rival = sign(&author, 2, Some(a1.id), None, ext("rival", Vec::new())).unwrap(); let a3 = sign(&author, 3, Some(a2.id), None, ext("message", Vec::new())).unwrap(); let b0 = sign(&other, 0, None, None, ext("message", vec![a1.id])).unwrap(); + // `held` never delivers seq 0, so seq 1 and its rival wait, and the fork is between two + // held events. + let held0 = sign(&held, 0, None, None, ext("message", Vec::new())).unwrap(); + let held1 = sign(&held, 1, Some(held0.id), None, ext("message", Vec::new())).unwrap(); + let held1_rival = sign(&held, 1, Some(held0.id), None, ext("rival", Vec::new())).unwrap(); + // `parked` applies seq 0. Its seq 1 names a backlink that is not the head, so it is parked. + let parked0 = sign(&parked, 0, None, None, ext("message", Vec::new())).unwrap(); + let stray = sign( + &parked, + 1, + Some(Hash::digest(b"not the head")), + None, + ext("stray", Vec::new()), + ) + .unwrap(); vec![ a1.bytes, a0.bytes.clone(), @@ -443,6 +462,10 @@ fn workload() -> Vec> { a3.bytes, a2.bytes, a0.bytes, + held1.bytes, + held1_rival.bytes, + parked0.bytes, + stray.bytes, ] } @@ -450,7 +473,7 @@ fn workload() -> Vec> { /// acknowledged: one that returned before the power cut, with its outcome. fn ingest_run(sim: &SimDir) -> Vec<(Vec, Ingest)> { let mut acked = Vec::new(); - let Ok(mut store) = EventStore::open_with(sim) else { + let Ok(mut store) = EventStore::open_with(sim, WaitingLimits::default(), 0) else { return acked; }; for bytes in workload() { @@ -473,7 +496,7 @@ fn ingest_run(sim: &SimDir) -> Vec<(Vec, Ingest)> { /// must leave a proof no later than its own sequence number. The store must open, and its /// invariants must hold. fn acknowledged_survive(disk: &Disk, acked: &[(Vec, Ingest)]) -> Result<(), String> { - let store = EventStore::open_with(&SimDir::from_disk(disk)) + let store = EventStore::open_with(&SimDir::from_disk(disk), WaitingLimits::default(), 0) .map_err(|err| format!("does not open: {err}"))?; store .check_invariants() @@ -483,6 +506,7 @@ fn acknowledged_survive(disk: &Disk, acked: &[(Vec, Ingest)]) -> Result<(), .filter_map(|bytes| chain::decode(&bytes).ok().map(|event| (event.id, bytes))) .collect(); let mut applied_ids = Vec::new(); + let mut held_ids = Vec::new(); for (_, outcome) in acked { match outcome { Ingest::Accepted { id, released } => { @@ -502,7 +526,19 @@ fn acknowledged_survive(disk: &Disk, acked: &[(Vec, Ingest)]) -> Result<(), )); } } - Ingest::Waiting { .. } | Ingest::Refused(_) => {} + Ingest::Waiting { id } => held_ids.push(*id), + Ingest::Refused(_) => {} + } + } + // A held event must survive the reopen as held. If a later delivery applied it, or a fork + // voided it, it is stored instead. It must never be neither. + for id in held_ids { + let stored = store + .event_by_id(&id) + .map_err(|err| err.to_string())? + .is_some(); + if !store.is_waiting(&id) && !stored { + return Err("an acknowledged waiting event is neither held nor stored".to_owned()); } } for id in applied_ids { @@ -575,6 +611,22 @@ fn clean_ingest_run_has_every_outcome_and_survives_its_reopen() { matches!(outcomes[7], Ingest::Duplicate { .. }), "a0 again is a repeat" ); + assert!( + matches!(outcomes[8], Ingest::Waiting { .. }), + "held1 waits for seq 0, which is never delivered" + ); + assert!( + matches!(outcomes[9], Ingest::Fork { seq: 1, .. }), + "held1_rival forks the held event" + ); + assert!( + matches!(outcomes[10], Ingest::Accepted { .. }), + "parked0 applies" + ); + assert!( + matches!(outcomes[11], Ingest::Waiting { .. }), + "stray is parked" + ); for disk in sim.crash_states() { acknowledged_survive(&disk, &acked).unwrap(); } diff --git a/pkgs/id/tests/event_store_properties.rs b/pkgs/id/tests/event_store_properties.rs index d3b8b3a23c..3fc8257197 100644 --- a/pkgs/id/tests/event_store_properties.rs +++ b/pkgs/id/tests/event_store_properties.rs @@ -20,10 +20,10 @@ mod common; use std::collections::{BTreeMap, BTreeSet}; -use common::ingest::{deliver_within, Canonical, DELIVERY_LIMIT}; -use id::chain::{sign, ChainExt, Event}; -use id::event_store::Chain; -use id::waiting::AuthorKey; +use common::ingest::{Canonical, DELIVERY_LIMIT, MemStorage, canonical, deliver_within}; +use id::chain::{ChainExt, Event, sign}; +use id::event_store::{Chain, EventStore, Ingest}; +use id::waiting::{AuthorKey, WaitingLimits}; use p2panda_core::{Hash, SeqNum, SigningKey}; use proptest::prelude::*; use proptest::test_runner::TestCaseError; @@ -259,6 +259,11 @@ fn model(events: &[Event], authors: &[AuthorKey]) -> Canonical { expected } +/// An index in `0..n`, drawn from `rng`. +fn index(rng: &mut Rng, n: usize) -> usize { + usize::try_from(rng.below(n as u64)).unwrap() +} + fn shuffle(items: &mut [T], rng: &mut Rng) { for i in (1..items.len()).rev() { let j = rng.below(i as u64 + 1) as usize; @@ -302,6 +307,101 @@ proptest! { prop_assert_eq!(&state, &scenario.expected); } } + + /// A restart changes nothing. One delivery order, run with the store closed and reopened at + /// random points, gives every delivery the same outcome, and leaves the same applied state and + /// held events, as the same order run without restarts. The caps are small and the clock runs + /// past the age limit, so restarts also land on refusals and on expiries. + #[test] + fn test_restarts_at_random_points_change_no_outcome(seed in any::()) { + let scenario = scenario(seed); + let mut rng = Rng(seed ^ 0x5851_F42D_4C95_7F2D); + let mut all_orders = orders(&scenario.events, &mut rng); + let order = all_orders.swap_remove(index(&mut rng, 4)); + let mut clock = 0_u64; + let times: Vec = order + .iter() + .map(|_| { + clock += rng.below(1_000); + clock + }) + .collect(); + let max_age_ms = [1_500, 6_000, u64::MAX / 2][index(&mut rng, 3)]; + let per_author = [1, 2, 3, 256][index(&mut rng, 4)]; + let limits = WaitingLimits::new(per_author, max_age_ms); + // Half the cases restart before every delivery. The rest restart before about one in three, + // so events are often held across a restart. + let every_delivery = rng.chance(2); + let restarts: Vec = (0..order.len()) + .filter(|_| every_delivery || rng.chance(3)) + .collect(); + + let plain = { + let (order, times, authors) = (order.clone(), times.clone(), scenario.authors.clone()); + within_limit(move || deliver_with_restarts(&order, ×, &[], limits, &authors)) + }; + let restarted = within_limit(move || { + deliver_with_restarts(&order, ×, &restarts, limits, &scenario.authors) + }); + let (plain_outcomes, plain_state, plain_held) = plain.map_err(TestCaseError::fail)?; + let (outcomes, state, held) = restarted.map_err(TestCaseError::fail)?; + prop_assert_eq!(outcomes, plain_outcomes); + prop_assert_eq!(state, plain_state); + prop_assert_eq!(held, plain_held); + } +} + +/// Delivers `order` to one store, which is closed and reopened before each delivery whose +/// position is in `restarts`. Delivery `i` runs at clock `times[i]`, and a reopen runs at the +/// clock of the delivery it precedes. Returns each delivery's outcome, the applied state of +/// `authors`, and the IDs the store holds at the end. The invariants must hold after the last +/// delivery. +fn deliver_with_restarts( + order: &[Vec], + times: &[u64], + restarts: &[usize], + limits: WaitingLimits, + authors: &[AuthorKey], +) -> Result<(Vec, Canonical, Vec), String> { + let storage = MemStorage::default(); + let open = |at: u64| EventStore::open_with(&storage, limits, at).map_err(|err| err.to_string()); + let first = times.first().copied().unwrap_or(0); + let mut store = open(first)?; + let mut outcomes = Vec::new(); + for (i, bytes) in order.iter().enumerate() { + if restarts.contains(&i) { + drop(store); + store = open(times[i])?; + } + let outcome = store + .ingest(bytes, times[i]) + .map_err(|err| format!("ingest failed: {err}"))?; + outcomes.push(outcome); + } + store + .check_invariants() + .map_err(|err| format!("invariants after the deliveries: {err}"))?; + let state = canonical(&store, authors)?; + let held = store.waiting_ids().map_err(|err| err.to_string())?; + Ok((outcomes, state, held)) +} + +/// Runs `run` on a helper thread. Fails if it has not returned within [`DELIVERY_LIMIT`], so a +/// store that spins fails the test instead of hanging it. +fn within_limit( + run: impl FnOnce() -> Result + Send + 'static, +) -> Result { + let (sent, received) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + // The receiver is gone only once the wait below has given up. + let _ = sent.send(run()); + }); + match received.recv_timeout(DELIVERY_LIMIT) { + Ok(result) => result, + Err(_) => Err(format!( + "the deliveries did not finish within {DELIVERY_LIMIT:?}: an event made the store spin" + )), + } } /// Escapes every byte as `\xHH`, which the replay format reads back. From fe7639920a08e8f6c3533fe679fc9c400bf17f73 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 11 Oct 2026 22:37:57 -0500 Subject: [PATCH 21/30] test(rust): pin the sequence and backlink rule at decode and at ingest [P1-review] The builder refuses a backlink at sequence 0 and a missing one above 0. Both sides of the rule are now checked over every sequence in a range: the decoder accepts exactly the headers the builder would sign, and ingest refuses the rest as malformed, holding nothing. The layout of p2panda's decoder already enforces the rule, so these tests pass on phase-1; they pin it. --- pkgs/id/tests/chain_properties.rs | 31 +++++++++++++++++ pkgs/id/tests/event_store_properties.rs | 45 +++++++++++++++++++++++-- 2 files changed, 74 insertions(+), 2 deletions(-) diff --git a/pkgs/id/tests/chain_properties.rs b/pkgs/id/tests/chain_properties.rs index aa5e550960..e7e754869c 100644 --- a/pkgs/id/tests/chain_properties.rs +++ b/pkgs/id/tests/chain_properties.rs @@ -161,4 +161,35 @@ proptest! { let at = cut.index(event.bytes.len()); prop_assert!(decode(&event.bytes[..at]).is_err(), "a prefix of {at} bytes was accepted"); } + + /// The sequence and the backlink must agree, and the decoder applies the builder's rule: + /// sequence 0 takes no backlink, and every later sequence names one. A signed header that + /// breaks the rule is refused, whatever the sequence number, and one that keeps it is + /// accepted. p2panda's own decoder accepts both kinds, so this is the only check. + #[test] + fn test_decoder_applies_the_sequence_and_backlink_rule( + seq in 0u32..300, + backlink in prop::option::of(hash()), + ) { + let raw = Header::::builder() + .seq_num(seq) + .backlink(backlink) + .build( + &key(), + ChainExt { + kind: "m".to_owned(), + group: None, + after: Vec::new(), + }, + ) + .encode(); + let agrees = (seq == 0) == backlink.is_none(); + prop_assert_eq!( + decode(&raw).is_ok(), + agrees, + "sequence {}, backlink {:?}", + seq, + backlink + ); + } } diff --git a/pkgs/id/tests/event_store_properties.rs b/pkgs/id/tests/event_store_properties.rs index 3fc8257197..a989c4f868 100644 --- a/pkgs/id/tests/event_store_properties.rs +++ b/pkgs/id/tests/event_store_properties.rs @@ -22,9 +22,9 @@ use std::collections::{BTreeMap, BTreeSet}; use common::ingest::{Canonical, DELIVERY_LIMIT, MemStorage, canonical, deliver_within}; use id::chain::{ChainExt, Event, sign}; -use id::event_store::{Chain, EventStore, Ingest}; +use id::event_store::{Chain, EventStore, Ingest, Refusal}; use id::waiting::{AuthorKey, WaitingLimits}; -use p2panda_core::{Hash, SeqNum, SigningKey}; +use p2panda_core::{Hash, Header, SeqNum, SigningKey}; use proptest::prelude::*; use proptest::test_runner::TestCaseError; @@ -404,6 +404,47 @@ fn within_limit( } } +proptest! { + #![proptest_config(config())] + + /// At ingest, a header that breaks the sequence and backlink rule is refused as malformed, + /// whatever its sequence number. It is not parked or held, so it takes no waiting slot and + /// raises no conflict. A header that keeps the rule is not refused for it. + #[test] + fn test_a_header_breaking_the_sequence_rule_is_refused_at_ingest( + seq in 0u32..40, + backlink in prop::option::of(any::<[u8; 32]>()), + ) { + let raw = Header::::builder() + .seq_num(seq) + .backlink(backlink.map(Hash::from)) + .build( + &SigningKey::from_bytes(&[7; 32]), + ChainExt { + kind: "m".to_owned(), + group: None, + after: Vec::new(), + }, + ) + .encode(); + let mut store = EventStore::open_with(&MemStorage::default(), WaitingLimits::default(), 0) + .map_err(|err| TestCaseError::fail(err.to_string()))?; + let outcome = store + .ingest(&raw, 0) + .map_err(|err| TestCaseError::fail(err.to_string()))?; + let agrees = (seq == 0) == backlink.is_none(); + if agrees { + prop_assert!(!matches!(outcome, Ingest::Refused(_)), "refused: {outcome:?}"); + } else { + prop_assert!( + matches!(outcome, Ingest::Refused(Refusal::Malformed(_))), + "sequence {seq} with backlink {backlink:?} gave {outcome:?}" + ); + prop_assert_eq!(store.waiting_len(), 0, "a malformed header was held"); + } + } +} + /// Escapes every byte as `\xHH`, which the replay format reads back. fn escape(bytes: &[u8]) -> String { bytes.iter().map(|byte| format!("\\x{byte:02x}")).collect() From 8bea0731f9ee446076a672b2bee86d9219b6b95f Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 11 Oct 2026 22:38:00 -0500 Subject: [PATCH 22/30] test(rust): pin the LogSync limit and document it in the store traits [P1-review] LogSync is not wired in: p2panda-sync reaches SQLite through the default features of p2panda-store. The module docs now say so, with the P3.2 item that removes the default, and a test fails when the lock names SQLite or p2panda-sync, so that change is made on purpose. --- pkgs/id/src/store_traits.rs | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/pkgs/id/src/store_traits.rs b/pkgs/id/src/store_traits.rs index d0d0cc47ac..2cd192cc61 100644 --- a/pkgs/id/src/store_traits.rs +++ b/pkgs/id/src/store_traits.rs @@ -15,6 +15,14 @@ //! The methods that the sync path does not use return [`TraitStoreError::Unsupported`], with the //! reason, rather than a guess. Auth state, fork proofs and waiting events are not part of these //! traits, and stay in the event store's own tables. +//! +//! # Known limit: LogSync is not wired in +//! +//! p2panda-sync is not a dependency yet. Its p2panda-store dependency uses the default features, +//! and those include SQLite, so adding it would bring SQLite back into the build. Until P3.2 +//! removes that default (a fork of the one dependency line, or a LogSync of our own), nothing +//! here runs LogSync. `test_logsync_is_not_wired_and_the_lock_has_no_sqlite` pins this: it fails +//! when the lock names SQLite or p2panda-sync, so that change is made on purpose. use std::collections::{BTreeMap, BTreeSet, VecDeque}; use std::future::{Future, ready}; @@ -455,6 +463,27 @@ mod tests { use crate::chain::{ChainExt, sign}; use crate::waiting::WaitingLimits; + /// The LogSync limit, pinned. The lock has no SQLite and no p2panda-sync, so LogSync is not + /// wired in. Adding p2panda-sync brings SQLite back through its store dependency, which is + /// the P3.2 item. This test fails on either, so the change is made on purpose. + #[test] + fn test_logsync_is_not_wired_and_the_lock_has_no_sqlite() { + let lock = + std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/Cargo.lock")).unwrap(); + for name in [ + "sqlx", + "sqlite", + "rusqlite", + "libsqlite3-sys", + "p2panda-sync", + ] { + assert!( + !lock.contains(&format!("name = \"{name}")), + "Cargo.lock names {name}: LogSync needs p2panda-sync without its SQLite default (P3.2)" + ); + } + } + fn key(n: u8) -> SigningKey { SigningKey::from_bytes(&[n; 32]) } From 414479ec73e8d1581199ed73a85c4dd65ae678f6 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 11 Oct 2026 23:03:13 -0500 Subject: [PATCH 23/30] test(rust): a fork voids only the forked chain; honest dependents apply [P1.8] A fork voided every event that rests on a voided one, so an honest event of another author that named a voided event waited on its own backlink forever. Phase 1 has no authority model to void by, so the rule is: a fork voids only the forked author's own events from the fork point on, and an after hash counts as present when it is applied or a proof header. Authority-based voiding replaces this in P2.3. The three tests that pinned the cascade now pin the new rule and fail until the fix lands. The property tests restrict after hashes to events that are present in every order, and add an honest-author liveness property. --- pkgs/id/src/event_store/ingest.rs | 58 ++++--- pkgs/id/tests/event_store_properties.rs | 201 ++++++++++++++++++++++-- 2 files changed, 217 insertions(+), 42 deletions(-) diff --git a/pkgs/id/src/event_store/ingest.rs b/pkgs/id/src/event_store/ingest.rs index 7e25578a75..94589d585d 100644 --- a/pkgs/id/src/event_store/ingest.rs +++ b/pkgs/id/src/event_store/ingest.rs @@ -917,7 +917,7 @@ mod tests { } #[test] - fn test_an_after_hash_naming_an_unapplied_event_keeps_waiting() { + fn test_an_after_hash_naming_a_voided_event_is_applied() { let (_dir, mut store) = open(); let x = key(11); let y = key(12); @@ -925,10 +925,16 @@ mod tests { ingest_all(&mut store, &events); let rival = event(&x, 1, Some(events[0].id), Vec::new(), "rival"); ingest(&mut store, &rival); - // events[1] is stored, but the fork took it out of the applied prefix. + // events[1] is stored, and the fork voided it. It is present, so y0 does not wait. let y0 = event(&y, 0, None, vec![events[1].id], "y"); - assert_eq!(ingest(&mut store, &y0), Ingest::Waiting { id: y0.id }); - assert!(store.chain(&author(&y)).unwrap().is_none()); + assert_eq!( + ingest(&mut store, &y0), + Ingest::Accepted { + id: y0.id, + released: vec![], + } + ); + assert_eq!(store.chain(&author(&y)).unwrap().unwrap().next_seq, 1); } #[test] @@ -1086,7 +1092,7 @@ mod tests { } #[test] - fn test_a_fork_at_sequence_zero_unapplies_an_event_applied_on_top_of_it() { + fn test_a_fork_at_sequence_zero_keeps_an_event_that_names_the_voided_one_applied() { let (_dir, mut store) = open(); let (x, y) = (key(20), key(21)); let x0 = event(&x, 0, None, Vec::new(), "message"); @@ -1101,29 +1107,31 @@ mod tests { seq: 0 } ); - assert!( - applied_ids(&store, &author(&y)).is_empty(), - "y0 rests on x0, which the fork voided" + assert_eq!( + applied_ids(&store, &author(&y)), + vec![y0.id], + "y0 names x0, which the fork voided. x0 is still present, so y0 stays applied" ); assert_eq!( - store.event(&author(&y), 0).unwrap(), - Some(y0), - "y0 stays stored" + store.chain(&author(&y)).unwrap().unwrap().next_seq, + 1, + "y's chain keeps its applied event" ); - assert_eq!(store.chain(&author(&y)).unwrap(), None); store.check_invariants().unwrap(); } + /// A fork voids only the forked author's own events from its fork point on. Honest events + /// of other authors that name a voided event still apply, and so do their later events: + /// the voided event is present, so it does not wait. Phase 1 has no membership or authority + /// model, so the design's authority-based voiding (decision 1) cannot run yet. It replaces + /// this rule in Phase 2 (P2.3). #[test] - fn test_a_fork_unapplies_every_event_that_rests_on_the_voided_ones() { + fn test_a_fork_voids_only_the_forked_chain_until_p2_3_authority_voiding() { let (_dir, mut store) = open(); let (x, y, z) = (key(22), key(23), key(24)); let x0 = event(&x, 0, None, Vec::new(), "message"); let x1 = event(&x, 1, Some(x0.id), Vec::new(), "message"); - let y0 = event(&y, 0, None, vec![x1.id], "message"); - let y1 = event(&y, 1, Some(y0.id), Vec::new(), "message"); - let z0 = event(&z, 0, None, vec![y0.id], "message"); - ingest_all(&mut store, &[x0.clone(), x1, y0, y1, z0]); + ingest_all(&mut store, &[x0.clone(), x1.clone()]); let rival = event(&x, 1, Some(x0.id), Vec::new(), "rival"); assert_eq!( ingest(&mut store, &rival), @@ -1132,16 +1140,14 @@ mod tests { seq: 1 } ); + // Y names X's voided event, and Y's next event names Y's first. Z names Y's second. + let y0 = event(&y, 0, None, vec![x1.id], "message"); + let y1 = event(&y, 1, Some(y0.id), Vec::new(), "message"); + let z0 = event(&z, 0, None, vec![y1.id], "message"); + ingest_all(&mut store, &[y0.clone(), y1.clone(), z0.clone()]); assert_eq!(applied_ids(&store, &author(&x)), vec![x0.id]); - assert!( - applied_ids(&store, &author(&y)).is_empty(), - "y0 rests on x1, and y1 on y0" - ); - assert!( - applied_ids(&store, &author(&z)).is_empty(), - "z0 rests on y0" - ); - assert_eq!(store.chain(&author(&z)).unwrap(), None); + assert_eq!(applied_ids(&store, &author(&y)), vec![y0.id, y1.id]); + assert_eq!(applied_ids(&store, &author(&z)), vec![z0.id]); store.check_invariants().unwrap(); } diff --git a/pkgs/id/tests/event_store_properties.rs b/pkgs/id/tests/event_store_properties.rs index a989c4f868..6df7679080 100644 --- a/pkgs/id/tests/event_store_properties.rs +++ b/pkgs/id/tests/event_store_properties.rs @@ -8,8 +8,9 @@ //! Every store must reach the applied state that [`model`] computes from the set of events //! alone, so the answer cannot depend on the order. The model is the specification. An event //! is applied when it sits below its author's fork point, its backlink is the applied event -//! before it, and every `after` hash is applied. The fork point is the lowest sequence number -//! where the author has two distinct events, and the proof holds the two lowest IDs there. +//! before it, and every `after` hash is present: applied, or a fork proof header. The fork +//! point is the lowest sequence number where the author has two distinct events, and the proof +//! holds the two lowest IDs there. //! //! Failures are not written to `proptest-regressions/`. The minimal input goes into //! `tests/regressions/ingest.txt` instead (see `tests/regressions/README.md`). @@ -139,6 +140,28 @@ fn signed( sign(key, seq, backlink, None, ext).unwrap() } +/// Where each author forks, if it does: the sequence number of the fork point, and how many +/// rivals sit there beside the original (one or two). +type ForkPlan = BTreeMap; + +/// The events a later event may name: those that are present in every delivery order. An +/// author with a fork is referable up to its fork point. At the fork point it is referable only +/// when there are two events there, which the fork proof holds. Above the fork point, an event +/// is refused as frozen in some orders and kept in others, so no event names it. +fn referable(events: &[Event], plan: &ForkPlan) -> Vec { + events + .iter() + .filter(|event| { + let seq = event.header.seq_num; + match plan.get(&author_of(event)) { + None => true, + Some(&(fork, rivals)) => seq < fork || (seq == fork && rivals == 1), + } + }) + .cloned() + .collect() +} + fn scenario(seed: u64) -> Scenario { let mut rng = Rng(seed); let count = 2 + rng.below(2) as usize; @@ -148,6 +171,19 @@ fn scenario(seed: u64) -> Scenario { let lengths: Vec = (0..count) .map(|_| 1 + SeqNum::try_from(rng.below(4)).unwrap()) .collect(); + let publics: Vec = keys + .iter() + .map(|key| *key.verifying_key().as_bytes()) + .collect(); + // Each author forks at most once, below the end of its chain. Deciding this up front is what + // lets `referable` know which events are stable while the scenario is still being built. + let mut plan: ForkPlan = BTreeMap::new(); + for (public, len) in publics.iter().zip(&lengths) { + if rng.chance(2) { + let fork = SeqNum::try_from(rng.below(u64::from(*len))).unwrap(); + plan.insert(*public, (fork, 1 + rng.below(2) as usize)); + } + } let mut events: Vec = Vec::new(); let mut originals: Vec> = vec![Vec::new(); count]; @@ -160,31 +196,134 @@ fn scenario(seed: u64) -> Scenario { } progress[author] += 1; let backlink = originals[author].last().map(|event| event.id); - let original = signed(&mut rng, &keys[author], seq, backlink, &events, "message"); + let known = referable(&events, &plan); + let original = signed(&mut rng, &keys[author], seq, backlink, &known, "message"); originals[author].push(original.clone()); events.push(original); - // A fork at this sequence number: one or two rivals, each with its own backlink. - if rng.chance(3) { - for _ in 0..=rng.below(2) { - let link = rival_backlink(&mut rng, seq, backlink, &events); - let rival = signed(&mut rng, &keys[author], seq, link, &events, "rival"); - if events.iter().all(|event| event.id != rival.id) { + // The fork point: the rivals, each with its own backlink. + if let Some(&(fork, rivals)) = plan.get(&publics[author]) { + if fork == seq { + for n in 0..rivals { + let link = rival_backlink(&mut rng, seq, backlink, &events); + let known = referable(&events, &plan); + let rival = signed( + &mut rng, + &keys[author], + seq, + link, + &known, + &format!("rival {n}"), + ); events.push(rival); } } } } - let authors: Vec = keys + let expected = model(&events, &publics); + Scenario { + events, + authors: publics, + expected, + } +} + +/// A scenario in which some authors fork once and the rest never fork. Every `after` hash names an +/// honest event, or a forked author's event at or below its fork point, so each one is present in +/// every delivery order and nothing stalls except what a fork voids. Returns the honest authors too. +fn honest_scenario(seed: u64) -> (Scenario, Vec) { + let mut rng = Rng(seed); + let count = 2 + rng.below(3) as usize; + let keys: Vec = (0..count) + .map(|_| SigningKey::from_bytes(&std::array::from_fn(|_| rng.next_u64() as u8))) + .collect(); + let lengths: Vec = (0..count) + .map(|_| 1 + SeqNum::try_from(rng.below(4)).unwrap()) + .collect(); + // The first `forkers` authors fork and the rest are honest, so at least one is honest. + let forkers = rng.below(count as u64) as usize; + let forks: Vec> = (0..count) + .map(|author| { + (author < forkers) + .then(|| SeqNum::try_from(rng.below(u64::from(lengths[author]))).unwrap()) + }) + .collect(); + let publics: Vec = keys .iter() .map(|key| *key.verifying_key().as_bytes()) .collect(); - let expected = model(&events, &authors); - Scenario { + + let mut events: Vec = Vec::new(); + let mut good: Vec = Vec::new(); + let mut originals: Vec> = vec![Vec::new(); count]; + let mut progress: Vec = vec![0; count]; + while progress.iter().zip(&lengths).any(|(done, len)| done < len) { + let author = rng.below(count as u64) as usize; + let seq = progress[author]; + if seq >= lengths[author] { + continue; + } + progress[author] += 1; + let backlink = originals[author].last().map(|event| event.id); + let original = present_event(&mut rng, &keys[author], seq, backlink, &good, "message"); + originals[author].push(original.clone()); + if forks[author].is_none_or(|fork| seq <= fork) { + good.push(original.clone()); + } + events.push(original); + if forks[author] == Some(seq) { + let rival = present_event(&mut rng, &keys[author], seq, backlink, &good, "rival"); + good.push(rival.clone()); + events.push(rival); + } + } + + let honest = publics + .iter() + .zip(&forks) + .filter(|(_, fork)| fork.is_none()) + .map(|(public, _)| *public) + .collect(); + let expected = model(&events, &publics); + let scenario = Scenario { events, - authors, + authors: publics, expected, + }; + (scenario, honest) +} + +/// Up to three `after` hashes, each one of `good`. Unlike [`pick_after`], it never names a hash that +/// is never delivered. +fn pick_present(rng: &mut Rng, good: &[Event]) -> Vec { + let mut picked = Vec::new(); + if good.is_empty() { + return picked; } + for _ in 0..rng.below(4) { + let hash = good[rng.below(good.len() as u64) as usize].id; + if !picked.contains(&hash) { + picked.push(hash); + } + } + picked +} + +/// Signs an event whose `after` hashes are drawn from `good` by [`pick_present`]. +fn present_event( + rng: &mut Rng, + key: &SigningKey, + seq: SeqNum, + backlink: Option, + good: &[Event], + kind: &str, +) -> Event { + let ext = ChainExt { + kind: kind.to_owned(), + group: None, + after: pick_present(rng, good), + }; + sign(key, seq, backlink, None, ext).unwrap() } /// The applied state that a set of events determines, whatever order they arrive in. Every @@ -205,6 +344,15 @@ fn model(events: &[Event], authors: &[AuthorKey]) -> Canonical { } } + // The two lowest IDs at each fork point. A fork keeps its proof headers, so they are present + // even though neither is applied. + let mut proof_ids: BTreeSet = BTreeSet::new(); + for (&author, &point) in &fork_point { + let mut ids = at.get(&(author, point)).cloned().unwrap_or_default(); + ids.sort_by(|a, b| a.as_bytes().cmp(b.as_bytes())); + proof_ids.extend(ids.into_iter().take(2)); + } + let mut applied_at: BTreeMap<(AuthorKey, SeqNum), Hash> = BTreeMap::new(); let mut applied: BTreeSet = BTreeSet::new(); for event in events { @@ -215,13 +363,14 @@ fn model(events: &[Event], authors: &[AuthorKey]) -> Canonical { None => true, Some(before) => applied_at.get(&(author, before)) == event.header.backlink.as_ref(), }; - let deps_applied = event + // An `after` hash is present when it is applied, or when it is a proof header. + let deps_present = event .header .extensions .after .iter() - .all(|dep| applied.contains(dep)); - if below_fork && linked && deps_applied { + .all(|dep| applied.contains(dep) || proof_ids.contains(dep)); + if below_fork && linked && deps_present { applied_at.insert((author, seq), event.id); applied.insert(event.id); } @@ -308,6 +457,26 @@ proptest! { } } + /// Honest authors never stall. Some authors fork, at random depths, and every `after` hash names + /// an event that is present in every order. In every order, each honest author's chain applies + /// in full, and the state matches the model. This is the liveness rule until P2.3 replaces + /// fork voiding with authority-based voiding. + #[test] + fn test_a_fork_stalls_no_honest_chain_in_any_order_until_p2_3(seed in any::()) { + let (scenario, honest) = honest_scenario(seed); + for author in &honest { + let applied = scenario.expected.chains.get(author).map(|chain| chain.next_seq); + let written = scenario.events.iter().filter(|event| author_of(event) == *author).count(); + prop_assert_eq!(applied, Some(SeqNum::try_from(written).unwrap())); + } + let mut rng = Rng(seed ^ 0x2545_F491_4F6C_DD1D); + for order in orders(&scenario.events, &mut rng) { + let state = deliver_within(order, scenario.authors.clone(), DELIVERY_LIMIT) + .map_err(TestCaseError::fail)?; + prop_assert_eq!(&state, &scenario.expected); + } + } + /// A restart changes nothing. One delivery order, run with the store closed and reopened at /// random points, gives every delivery the same outcome, and leaves the same applied state and /// held events, as the same order run without restarts. The caps are small and the clock runs From 46bb1f2a4e82151fc8cae2de219b4475fe729cf6 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 11 Oct 2026 23:13:06 -0500 Subject: [PATCH 24/30] fix(rust): a fork voids only the forked chain; honest dependents apply [P1.8] A fork voided every applied event that rested on a voided one, across all authors. Phase 1 has no authority model, so this voided honest events of other authors, whose next events then waited on their own backlink forever. A fork now voids only the forked author's own events from the fork point on. An after hash is present when the store holds the event it names, applied or voided, or when it is a fork proof header. Presence never goes away, so the waiting pool's arrived set is monotone and forget is gone. Authority-based voiding replaces this rule in P2.3. Schema: the dependents table is replaced by proof_ids, and the format is bumped from v3 to v4. A v3 store is refused, because its chain rows were written under the cascade rule. --- pkgs/id/src/event_store/ingest.rs | 171 +++++++++++------------- pkgs/id/src/event_store/mod.rs | 100 ++++++-------- pkgs/id/src/waiting.rs | 23 +--- pkgs/id/tests/event_store_properties.rs | 28 ++-- 4 files changed, 131 insertions(+), 191 deletions(-) diff --git a/pkgs/id/src/event_store/ingest.rs b/pkgs/id/src/event_store/ingest.rs index 94589d585d..21dc6157d7 100644 --- a/pkgs/id/src/event_store/ingest.rs +++ b/pkgs/id/src/event_store/ingest.rs @@ -12,13 +12,13 @@ //! 4. **Fork.** If the author has another event at the same sequence number, stored or //! held, the two are a fork, whatever their backlinks and dependencies. The fork point //! moves down to that sequence number, and the proof holds the two lowest IDs there. -//! The applied events from that point on are unapplied, and so is every applied event -//! that rests on one of them. +//! The applied events from that point on are voided, and no others. The proof headers +//! become present, which releases the events that waited for them. //! 5. **Accept.** The next sequence number, whose backlink is the applied head, is applied -//! once every `after` hash is applied. +//! once every `after` hash is present. //! 6. **Wait or park.** An event ahead of its chain, or with an `after` hash that is not //! applied yet, is held in the waiting pool and its row, under the caps, and decided again -//! when its dependencies are applied. An event whose backlink can never be the applied head +//! when its dependencies are present. An event whose backlink can never be the applied head //! is parked: held for good, so that a conflict with it is still seen. //! //! Each call runs in one redb write transaction. It holds every decision the call causes: the @@ -29,15 +29,21 @@ //! //! The applied state depends on the set of events a store has received, not on their //! arrival order. An event is applied when it sits below its author's fork point, its -//! backlink is the applied event before it, and every `after` hash is applied. The fork +//! backlink is the applied event before it, and every `after` hash is present. The fork //! point is the lowest sequence number where the author has two distinct events, and the //! proof holds the two lowest IDs there. //! //! An event that is stored but not applied is voided. A fork voids the author's events -//! from its fork point on, and every event that rests on a voided one. A voided event is -//! kept, because it still counts as the author's event at its sequence number, so a later -//! conflict with it is still a fork. The applied prefix of a chain is the events below its -//! next sequence number, so the chain row is what marks the voids. +//! from its fork point on, and nothing else. A voided event is kept, because it still counts +//! as the author's event at its sequence number, so a later conflict with it is still a fork. +//! The applied prefix of a chain is the events below its next sequence number, so the chain +//! row is what marks the voids. +//! +//! An `after` hash is present when the store holds the event it names, applied or voided, or +//! when it is one of a fork's proof headers. A held event waits for each `after` hash that is +//! not present, so an event of another author that names a voided event still applies. This is +//! the Phase 1 rule. It has no membership or authority model to void by, so authority-based +//! voiding (decision 1) replaces it in Phase 2 (P2.3). //! //! Held events count too. Two held events at one sequence number are a fork, though //! neither is applied. Held events are rows on disk, so a restart keeps them, and a conflict @@ -51,17 +57,23 @@ //! the refused rival is sent again, while the other event is still held. The behaviour is //! pinned by `test_a_rival_refused_by_the_cap_is_seen_only_when_sent_again`. //! +//! # Known limit: a rival refused as frozen +//! +//! An event above its author's fork point is refused as frozen when it arrives after the fork. +//! When it arrives before, it is kept as voided. So an `after` hash that names such an event is +//! present in some arrival orders and not in others. The property tests never name one. +//! //! The property tests in `tests/event_store_properties.rs` check the applied state against //! this definition, for every arrival order. use std::collections::VecDeque; use p2panda_core::{Hash, SeqNum}; -use redb::{ReadableMultimapTable, ReadableTable, WriteTransaction}; +use redb::{ReadableTable, WriteTransaction}; use super::waiting_rows::{Hold, Mirror}; use super::{ - CHAINS, Chain, DEPENDENTS, EVENTS, EventStore, FORKS, ForkProof, HASHES, StoreError, corrupt, + CHAINS, Chain, EVENTS, EventStore, FORKS, ForkProof, HASHES, PROOF_IDS, StoreError, corrupt, decode_proof, decode_stored, position_key, split_position, store_chain, store_event, store_fork, }; @@ -124,9 +136,9 @@ enum Decision { Accept, /// Already stored, or a proof header. Nothing written. Duplicate, - /// A conflict. The proof is written, and the fork point is `seq`. `unapplied` are - /// the events that left the applied prefix, which the waiting pool forgets. - Fork { seq: SeqNum, unapplied: Vec }, + /// A conflict. The proof is written, and the fork point is `seq`. Its two headers are + /// present now, so the events that waited for them are released. + Fork { seq: SeqNum, proof: [Hash; 2] }, /// Waits for these dependencies, none of which is applied. The caller holds the event. Wait(Vec), /// Can never apply, but is held so that a conflict with it is seen. The caller holds it. @@ -196,8 +208,8 @@ fn ingest_in(m: &mut Mirror<'_>, event: Event, now: u64) -> Result<(Ingest, bool released: drain(m, released.into(), now)?, }, Settled::Duplicate => Ingest::Duplicate { id }, - Settled::Fork { seq, unapplied } => { - forget(m.pool, &unapplied); + Settled::Fork { seq, released } => { + drain(m, released.into(), now)?; Ingest::Fork { author, seq } } Settled::Held | Settled::Skipped => { @@ -216,8 +228,9 @@ enum Settled { Accepted { released: Vec }, /// Already stored, or a fork proof header. Nothing changed. Duplicate, - /// A conflict at `seq`. `unapplied` left the applied prefix. - Fork { seq: SeqNum, unapplied: Vec }, + /// A conflict at `seq`. The proof headers are present now, and `released` are the events + /// that waited only for them, each due a decision. + Fork { seq: SeqNum, released: Vec }, /// Held, waiting or parked. Held, /// The pool did not keep the event. See [`Hold::Skipped`]. @@ -246,9 +259,13 @@ fn settle( drop_released(m, &id, from_pool)?; Settled::Duplicate } - Decision::Fork { seq, unapplied } => { + Decision::Fork { seq, proof } => { drop_released(m, &id, from_pool)?; - Settled::Fork { seq, unapplied } + let mut released = Vec::new(); + for header in proof { + released.extend(m.release(&header, now)?); + } + Settled::Fork { seq, released } } Decision::Refuse(refusal) => { drop_released(m, &id, from_pool)?; @@ -292,7 +309,7 @@ fn drain( applied.push(id); queue.extend(released); } - Settled::Fork { unapplied, .. } => forget(m.pool, &unapplied), + Settled::Fork { released, .. } => queue.extend(released), Settled::Duplicate | Settled::Held | Settled::Skipped | Settled::Refused(_) => {} } queue.extend(m.pool.take_ready()); @@ -310,14 +327,6 @@ fn held_rivals(pool: &WaitingPool, event: &Event) -> Vec { .collect() } -/// Tells the pool that these events are no longer applied, so the events that wait on them wait -/// again. -fn forget(pool: &mut WaitingPool, unapplied: &[Hash]) { - for id in unapplied { - pool.forget(id); - } -} - /// Decides `event` inside `txn`, and writes what the decision needs. `rivals` are the /// held events of the same author at the same sequence number. fn decide_in( @@ -349,7 +358,7 @@ fn decide_in( store_fork(txn, &author, seq, &first, &second)?; return Ok(Decision::Fork { seq, - unapplied: Vec::new(), + proof: [first.id, second.id], }); } } @@ -358,8 +367,11 @@ fn decide_in( conflicts.push(event.clone()); let (first, second) = two_lowest(conflicts)?; store_fork(txn, &author, seq, &first, &second)?; - let unapplied = freeze_and_unapply(txn, &author, seq)?; - return Ok(Decision::Fork { seq, unapplied }); + freeze_and_void(txn, &author, seq)?; + return Ok(Decision::Fork { + seq, + proof: [first.id, second.id], + }); } let chain = read_chain(txn, &author)?; @@ -367,7 +379,7 @@ fn decide_in( // The applied event at this sequence number is stored, so it would be a conflict. return Err(corrupt("an applied sequence number has no stored event")); } - let deps = unapplied_deps(txn, &event.header.extensions.after)?; + let deps = missing_deps(txn, &event.header.extensions.after)?; if seq == chain.next_seq { if seq > 0 && event.header.backlink != chain.head { return Ok(Decision::Park); @@ -397,7 +409,6 @@ fn accept(txn: &WriteTransaction, event: &Event, chain: Chain) -> Result Result Result<(), StoreError> { - let position = position_key(&author_of(event), event.header.seq_num); - let mut dependents = txn.open_multimap_table(DEPENDENTS)?; - for dep in &event.header.extensions.after { - dependents.insert(dep.as_bytes().as_slice(), position.as_slice())?; - } - Ok(()) -} - -/// Freezes `author` at `seq`. The applied prefix ends there, and every applied event -/// from `seq` up is unapplied, with whatever rests on those. Returns the events that -/// left the applied prefix. -fn freeze_and_unapply( +/// Freezes `author` at `seq`: the applied prefix ends there, and the author's applied events from +/// `seq` up are voided. Nothing else is voided. An event of another author that names a voided +/// event stays applied, because the voided event is still present. +/// +/// This is the Phase 1 rule. With no membership or authority model, a fork cannot void by +/// authority. Authority-based voiding (decision 1) replaces this rule in Phase 2 (P2.3). +fn freeze_and_void( txn: &WriteTransaction, author: &AuthorKey, seq: SeqNum, -) -> Result, StoreError> { +) -> Result<(), StoreError> { let chain = read_chain(txn, author)?; - set_prefix(txn, author, chain.next_seq, true)?; - unapply_from(txn, *author, seq) -} - -/// Unapplies `author`'s applied events from `seq` up, and every applied event that rests -/// on one of them. Each chain it touches is rewritten to its new applied prefix, with its -/// frozen flag kept. Returns the events that left the applied prefix. -fn unapply_from( - txn: &WriteTransaction, - author: AuthorKey, - seq: SeqNum, -) -> Result, StoreError> { - let mut unapplied = Vec::new(); - let mut pending = vec![(author, seq)]; - while let Some((who, from)) = pending.pop() { - let chain = read_chain(txn, &who)?; - if from >= chain.next_seq { - continue; - } - for position in from..chain.next_seq { - let event = stored_event(txn, &who, position)?; - for dependent in dependents_of(txn, &event.id)? { - pending.push(split_position(&dependent)?); - } - unapplied.push(event.id); - } - set_prefix(txn, &who, from, chain.frozen)?; - } - Ok(unapplied) + set_prefix(txn, author, chain.next_seq.min(seq), true) } /// Writes `author`'s chain row for an applied prefix of `next_seq` events. A chain with @@ -558,21 +534,11 @@ fn stored_event( .ok_or_else(|| corrupt("an applied sequence number has no stored event")) } -/// The positions of the stored events that name `id` in their `after` hashes. -fn dependents_of(txn: &WriteTransaction, id: &Hash) -> Result>, StoreError> { - let dependents = txn.open_multimap_table(DEPENDENTS)?; - let mut positions = Vec::new(); - for position in dependents.get(id.as_bytes().as_slice())? { - positions.push(position?.value().to_vec()); - } - Ok(positions) -} - -/// The `after` hashes that are not applied yet. -fn unapplied_deps(txn: &WriteTransaction, after: &[Hash]) -> Result, StoreError> { +/// The `after` hashes that are not present yet. +fn missing_deps(txn: &WriteTransaction, after: &[Hash]) -> Result, StoreError> { let mut missing = Vec::new(); for hash in after { - if !is_applied(txn, hash)? { + if !is_present(txn, hash)? { missing.push(*hash); } } @@ -585,6 +551,25 @@ pub(super) fn is_applied(txn: &WriteTransaction, hash: &Hash) -> Result Result { + present_in(&txn.open_table(HASHES)?, &txn.open_table(PROOF_IDS)?, hash) +} + +/// [`is_present`] over the `hashes` and `proof_ids` tables, whether they are read or written. +pub(super) fn present_in( + hashes: &impl ReadableTable<&'static [u8], &'static [u8]>, + proof_ids: &impl ReadableTable<&'static [u8], &'static [u8]>, + hash: &Hash, +) -> Result { + if hashes.get(hash.as_bytes().as_slice())?.is_some() { + return Ok(true); + } + Ok(proof_ids.get(hash.as_bytes().as_slice())?.is_some()) +} + /// [`is_applied`] over the `hashes` and `chains` tables, whether they are read or written. pub(super) fn applied_in( hashes: &impl ReadableTable<&'static [u8], &'static [u8]>, @@ -1705,7 +1690,7 @@ mod tests { } #[test] - fn test_invariants_refuse_a_waiting_event_whose_dependency_is_applied() { + fn test_invariants_refuse_a_waiting_event_whose_dependency_is_present() { let (_dir, mut store) = open(); let (x, y) = (key(42), key(43)); let x0 = event(&x, 0, None, Vec::new(), "message"); @@ -1727,6 +1712,6 @@ mod tests { .unwrap(); store.write(|txn| waiting_rows::put(txn, &row)).unwrap(); let err = store.check_invariants().unwrap_err(); - assert!(err.to_string().contains("applied"), "{err}"); + assert!(err.to_string().contains("present"), "{err}"); } } diff --git a/pkgs/id/src/event_store/mod.rs b/pkgs/id/src/event_store/mod.rs index 997a78da1c..4aff519b2b 100644 --- a/pkgs/id/src/event_store/mod.rs +++ b/pkgs/id/src/event_store/mod.rs @@ -12,8 +12,8 @@ //! - `forks`: an author to the fork proof, the two headers that conflict at the //! lowest sequence number where the author has forked. //! - `groups`: a group hash to the positions of the events in that group. -//! - `dependents`: an event's ID to the positions of the stored events that name it in -//! their `after` hashes. A fork uses it to find what rests on the events it voids. +//! - `proof_ids`: the ID of each fork proof header to its author. A proof header is present +//! although it is never applied, so an `after` hash that names it is satisfied. //! - `waiting` and `waiting_by_dep`: the events held waiting or parked, and an index from each //! dependency to the rows that wait for it. The `waiting_rows` module describes them, and //! the waiting pool in memory mirrors them. @@ -61,7 +61,7 @@ mod waiting_rows; use crate::waiting::{AuthorKey, WaitRefusal, WaitingLimits, WaitingPool}; pub use ingest::{Ingest, Refusal}; -use ingest::{applied_in, is_applied}; +use ingest::{is_present, present_in}; use waiting_rows::{Mirror, Row}; /// The store's file name in its directory. @@ -72,7 +72,7 @@ pub const FILE_NAME: &str = "events.redb"; pub const TEMP_NAME: &str = "events.redb.tmp"; /// The format row in `meta`. A store with another format is refused. -const FORMAT: &[u8] = b"id.events.store.v3"; +const FORMAT: &[u8] = b"id.events.store.v4"; const FORMAT_KEY: &[u8] = b"format"; const EVENTS: TableDefinition<'static, &'static [u8], &'static [u8]> = @@ -84,8 +84,8 @@ const CHAINS: TableDefinition<'static, &'static [u8], &'static [u8]> = const FORKS: TableDefinition<'static, &'static [u8], &'static [u8]> = TableDefinition::new("forks"); const GROUPS: MultimapTableDefinition<'static, &'static [u8], &'static [u8]> = MultimapTableDefinition::new("groups"); -const DEPENDENTS: MultimapTableDefinition<'static, &'static [u8], &'static [u8]> = - MultimapTableDefinition::new("dependents"); +const PROOF_IDS: TableDefinition<'static, &'static [u8], &'static [u8]> = + TableDefinition::new("proof_ids"); const WAITING: TableDefinition<'static, &'static [u8], &'static [u8]> = TableDefinition::new("waiting"); const WAITING_BY_DEP: MultimapTableDefinition<'static, &'static [u8], &'static [u8]> = @@ -468,7 +468,7 @@ impl EventStore { let chains = txn.open_table(CHAINS)?; let forks = txn.open_table(FORKS)?; let groups = txn.open_multimap_table(GROUPS)?; - let dependents = txn.open_multimap_table(DEPENDENTS)?; + let proof_ids = txn.open_table(PROOF_IDS)?; for row in events.iter()? { let (position, bytes) = row?; @@ -490,15 +490,6 @@ impl EventStore { return Err(corrupt("an event is missing from its group index")); } } - for dep in &event.header.extensions.after { - let mut found = false; - for indexed in dependents.get(dep.as_bytes().as_slice())? { - found |= indexed?.value() == position.value(); - } - if !found { - return Err(corrupt("an event is missing from the dependents index")); - } - } } for row in hashes.iter()? { @@ -528,19 +519,9 @@ impl EventStore { .get(position_key(&author, seq).as_slice())? .ok_or_else(|| corrupt(format!("applied sequence {seq} is not stored")))?; for dep in decode_stored(stored.value())?.header.extensions.after { - let applied = match hashes.get(dep.as_bytes().as_slice())? { - Some(position) => { - let (dep_author, dep_seq) = split_position(position.value())?; - match chains.get(dep_author.as_slice())? { - Some(row) => Chain::decode(row.value())?.next_seq > dep_seq, - None => false, - } - } - None => false, - }; - if !applied { + if !present_in(&hashes, &proof_ids, &dep)? { return Err(corrupt( - "an applied event rests on an event that is not applied", + "an applied event rests on an event that is not present", )); } } @@ -569,29 +550,8 @@ impl EventStore { } } - for row in dependents.iter()? { - let (dep, positions) = row?; - for position in positions { - let position = position?; - let stored = events - .get(position.value())? - .ok_or_else(|| corrupt("a dependents entry points at no stored event"))?; - let rests_on_dep = decode_stored(stored.value())? - .header - .extensions - .after - .iter() - .any(|hash| hash.as_bytes().as_slice() == dep.value()); - if !rests_on_dep { - return Err(corrupt( - "a dependents entry names an event that does not rest on it", - )); - } - } - } - for row in forks.iter()? { - let (author_bytes, _) = row?; + let (author_bytes, proof_bytes) = row?; let chain = chains .get(author_bytes.value())? .map(|row| Chain::decode(row.value())) @@ -601,20 +561,27 @@ impl EventStore { "a fork proof belongs to a chain that is not frozen", )); } + let proof = decode_proof(proof_bytes.value())?; + for header in [&proof.first, &proof.second] { + let indexed = proof_ids.get(header.id.as_bytes().as_slice())?; + if indexed.map(|row| row.value().to_vec()) != Some(author_bytes.value().to_vec()) { + return Err(corrupt("a fork proof header is not indexed as present")); + } + } } self.check_waiting() } /// Checks the waiting rows against the pool and the applied state. Each row decodes and names /// its event, is held by the pool, and is not stored. Each dependency it waits for is not - /// applied, and the dependency index lists exactly those. The pool's counts match the rows, + /// present, and the dependency index lists exactly those. The pool's counts match the rows, /// and no author is over the cap. fn check_waiting(&self) -> Result<(), StoreError> { let txn = self.db.begin_read()?; let rows = txn.open_table(WAITING)?; let by_dep = txn.open_multimap_table(WAITING_BY_DEP)?; let hashes = txn.open_table(HASHES)?; - let chains = txn.open_table(CHAINS)?; + let proof_ids = txn.open_table(PROOF_IDS)?; let mut per_author: BTreeMap = BTreeMap::new(); let mut total = 0; for entry in rows.iter()? { @@ -628,9 +595,9 @@ impl EventStore { return Err(corrupt("a waiting row is not held by the pool")); } for dep in &row.deps { - if applied_in(&hashes, &chains, dep)? { + if present_in(&hashes, &proof_ids, dep)? { return Err(corrupt( - "a waiting event waits for a dependency that is applied", + "a waiting event waits for a dependency that is present", )); } let mut indexed = false; @@ -738,8 +705,8 @@ impl EventStore { /// Rebuilds the waiting pool from the rows, in arrival order. A row due at `now_ms` is /// dropped, and so is a row past its author's cap. The drops commit with the rebuild. A row - /// that waits for an applied event means the rows and the applied state disagree, so the - /// rebuild fails as corruption and the pool is left as it was. + /// that waits for a present event means the rows and the store disagree, so the rebuild + /// fails as corruption and the pool is left as it was. fn reload(&mut self, now_ms: u64) -> Result<(), StoreError> { let txn = self.db.begin_write()?; let mut pool = WaitingPool::new(self.limits); @@ -753,9 +720,9 @@ impl EventStore { continue; } for dep in &row.deps { - if is_applied(&txn, dep)? { + if is_present(&txn, dep)? { return Err(corrupt( - "a waiting event waits for a dependency that is applied", + "a waiting event waits for a dependency that is present", )); } } @@ -809,7 +776,7 @@ fn initialize(db: &Database) -> Result<(), StoreError> { txn.open_table(CHAINS)?; txn.open_table(FORKS)?; txn.open_multimap_table(GROUPS)?; - txn.open_multimap_table(DEPENDENTS)?; + txn.open_table(PROOF_IDS)?; txn.open_table(WAITING)?; txn.open_multimap_table(WAITING_BY_DEP)?; let mut meta = txn.open_table(META)?; @@ -828,7 +795,7 @@ fn verify_schema(db: &Database) -> Result<(), StoreError> { txn.open_table(CHAINS).map_err(missing)?; txn.open_table(FORKS).map_err(missing)?; txn.open_multimap_table(GROUPS).map_err(missing)?; - txn.open_multimap_table(DEPENDENTS).map_err(missing)?; + txn.open_table(PROOF_IDS).map_err(missing)?; txn.open_table(WAITING).map_err(missing)?; txn.open_multimap_table(WAITING_BY_DEP).map_err(missing)?; let meta = txn.open_table(META).map_err(missing)?; @@ -983,7 +950,8 @@ pub(crate) fn store_chain( Ok(()) } -/// Writes an author's fork proof, replacing any earlier one. +/// Writes an author's fork proof, replacing any earlier one. Both headers become present, and +/// stay present: an earlier proof's headers are not removed from the index. pub(crate) fn store_fork( txn: &WriteTransaction, author: &AuthorKey, @@ -994,6 +962,11 @@ pub(crate) fn store_fork( let proof = encode_proof(seq, a, b)?; let mut forks = txn.open_table(FORKS)?; forks.insert(author.as_slice(), proof.as_slice())?; + drop(forks); + let mut proof_ids = txn.open_table(PROOF_IDS)?; + for header in [a, b] { + proof_ids.insert(header.id.as_bytes().as_slice(), author.as_slice())?; + } Ok(()) } @@ -1311,7 +1284,10 @@ mod tests { txn.open_table(CHAINS).unwrap(); txn.open_table(FORKS).unwrap(); txn.open_multimap_table(GROUPS).unwrap(); - txn.open_multimap_table(DEPENDENTS).unwrap(); + // The v2 format indexed each event's dependents in its own multimap table. + let dependents: MultimapTableDefinition<'static, &'static [u8], &'static [u8]> = + MultimapTableDefinition::new("dependents"); + txn.open_multimap_table(dependents).unwrap(); { let mut meta = txn.open_table(META).unwrap(); meta.insert(FORMAT_KEY, b"id.events.store.v2".as_slice()) diff --git a/pkgs/id/src/waiting.rs b/pkgs/id/src/waiting.rs index 3e99a6ac60..0f109b3290 100644 --- a/pkgs/id/src/waiting.rs +++ b/pkgs/id/src/waiting.rs @@ -130,7 +130,8 @@ pub struct WaitingPool { /// The sequence numbers of each author's held events. An author with none has no /// entry. held: HashMap>, - /// Keys that have arrived. A dependency in this set is already satisfied. + /// Keys that have arrived, and stay arrived. A dependency in this set is already satisfied. + /// The store calls this present: it is applied, voided by a fork, or a fork proof header. arrived: HashSet, /// Events whose dependencies had all arrived when they were inserted. ready: Vec, @@ -341,13 +342,6 @@ where released } - /// Forget that `key` arrived, for a key that has stopped counting as applied. - /// Events that wait on it from now on wait again. Events already released by it - /// are not affected. - pub fn forget(&mut self, key: &K) { - self.arrived.remove(key); - } - /// Drop every held event that has waited `max_age_ms` by `now_ms`, and return /// them as `(author, event)` in arrival order, so the caller can log them. /// @@ -601,19 +595,6 @@ mod tests { assert!(pool.arrived(10, 0).is_empty()); } - #[test] - fn test_a_forgotten_key_holds_its_dependents_again() { - let mut pool = pool(); - pool.arrived(10, 0); - pool.forget(&10); - pool.insert(author(1), 1, [10], "held", 0).unwrap(); - assert!( - pool.take_ready().is_empty(), - "the key no longer counts as arrived" - ); - assert_eq!(pool.arrived(10, 0), vec!["held"]); - } - #[test] fn test_counts_stay_exact_across_insert_release_and_expiry() { let mut pool = pool(); diff --git a/pkgs/id/tests/event_store_properties.rs b/pkgs/id/tests/event_store_properties.rs index 6df7679080..7b06fbc1c8 100644 --- a/pkgs/id/tests/event_store_properties.rs +++ b/pkgs/id/tests/event_store_properties.rs @@ -201,21 +201,19 @@ fn scenario(seed: u64) -> Scenario { originals[author].push(original.clone()); events.push(original); // The fork point: the rivals, each with its own backlink. - if let Some(&(fork, rivals)) = plan.get(&publics[author]) { - if fork == seq { - for n in 0..rivals { - let link = rival_backlink(&mut rng, seq, backlink, &events); - let known = referable(&events, &plan); - let rival = signed( - &mut rng, - &keys[author], - seq, - link, - &known, - &format!("rival {n}"), - ); - events.push(rival); - } + if let Some(&(_, rivals)) = plan.get(&publics[author]).filter(|(fork, _)| *fork == seq) { + for n in 0..rivals { + let link = rival_backlink(&mut rng, seq, backlink, &events); + let known = referable(&events, &plan); + let rival = signed( + &mut rng, + &keys[author], + seq, + link, + &known, + &format!("rival {n}"), + ); + events.push(rival); } } } From 1ebf1b3c38e9c98318d9aec4ad4fcbbf9b400782 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 11 Oct 2026 23:13:45 -0500 Subject: [PATCH 25/30] test(rust): a released waiter that waits again keeps its first arrival time [P1.11] A released event that is held again was given the time of its second hold, so the 7-day age cap counted from there. The cap counts the total time an event has waited, from its first arrival. This commit adds the red test for it. --- pkgs/id/src/event_store/ingest.rs | 38 +++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/pkgs/id/src/event_store/ingest.rs b/pkgs/id/src/event_store/ingest.rs index 21dc6157d7..e04bb98cb0 100644 --- a/pkgs/id/src/event_store/ingest.rs +++ b/pkgs/id/src/event_store/ingest.rs @@ -1431,6 +1431,44 @@ mod tests { assert_eq!(store.waiting_len(), 1, "only the rival is held"); } + #[test] + fn test_a_released_event_that_waits_again_keeps_its_first_arrival_time() { + let (_dir, mut store) = open(); + let signer = key(49); + let events = chain_of(&signer, 3); + // Ahead of its chain, and its backlink is the second event. It waits for that event. + let stray = event(&signer, 5, Some(events[1].id), Vec::new(), "stray"); + assert_eq!( + store.ingest(&stray.bytes, 0).unwrap(), + Ingest::Waiting { id: stray.id } + ); + assert_eq!( + store.ingest(&events[0].bytes, 1).unwrap(), + Ingest::Accepted { + id: events[0].id, + released: vec![], + } + ); + // The second event releases the stray. Its backlink is applied at an earlier position, so + // it can never apply, and it is parked again: held for good, and waiting again. + assert_eq!( + store.ingest(&events[1].bytes, 2).unwrap(), + Ingest::Accepted { + id: events[1].id, + released: vec![], + } + ); + assert!( + store.is_waiting(&stray.id), + "the released event waits again" + ); + // It arrived at 0, so it is due at WEEK_MS. Counting from its second wait it would be due + // at 2 + WEEK_MS. + assert_eq!(store.expire_waiting(WEEK_MS).unwrap(), 1); + assert_eq!(store.waiting_len(), 0); + store.check_invariants().unwrap(); + } + /// Opens the store in `dir` again, with `limits`, at clock `now`. fn reopen(dir: &tempfile::TempDir, limits: WaitingLimits, now: u64) -> EventStore { EventStore::open(dir.path(), limits, now).unwrap() From 3cac6902f5661958129b2d5f3381f13e1728a374 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 11 Oct 2026 23:16:36 -0500 Subject: [PATCH 26/30] fix(rust): a released waiter keeps its first arrival time [P1.11] The age cap counts from the time an event first arrived. A released event that waited again was held at the time of that second wait, so its cap moved later. Mirror::hold now holds through the pool's restore with the event's first arrival time, read from its row. A released event keeps its row until it is decided, so the time is there. The stored format is unchanged: the arrived_at column already held this value, and only the value written changes. No format bump. --- pkgs/id/src/event_store/waiting_rows.rs | 18 +++++++++++------- pkgs/id/src/waiting.rs | 6 ++++-- 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/pkgs/id/src/event_store/waiting_rows.rs b/pkgs/id/src/event_store/waiting_rows.rs index ac57a45358..43de6f3519 100644 --- a/pkgs/id/src/event_store/waiting_rows.rs +++ b/pkgs/id/src/event_store/waiting_rows.rs @@ -216,13 +216,17 @@ impl Mirror<'_> { deps.sort_unstable_by(|a, b| a.as_bytes().cmp(b.as_bytes())); deps.dedup(); let stored_deps = if parked { Vec::new() } else { deps.clone() }; - // The ingest call has already expired what is due at `now`, so the pool expires nothing - // here, and the event it holds is not due until a later call. - let result = if parked { - self.pool.park(author, id, event, now) - } else { - self.pool.insert(author, id, deps, event, now) + // An event that waits again keeps its first arrival time, so the age cap counts all of its + // waiting. A released event keeps its row until the caller decides it, and the row holds + // that time. An event the store has not held before arrived now. + let arrived_at = match get(self.txn, &id)? { + Some(row) => row.arrived_at, + None => now, }; + // The ingest call has already expired what is due at `now`, and the dependencies are not + // present, so the pool holds the event as given: it expires nothing and releases nothing. + let missing = if parked { Vec::new() } else { deps }; + let result = self.pool.restore(author, id, missing, event, arrived_at); match result { Ok(()) if self.pool.contains(&id) => { let arrival = *self.arrivals; @@ -231,7 +235,7 @@ impl Mirror<'_> { id, author, seq, - arrived_at: now, + arrived_at, arrival, deps: stored_deps, bytes, diff --git a/pkgs/id/src/waiting.rs b/pkgs/id/src/waiting.rs index 0f109b3290..b114c0f280 100644 --- a/pkgs/id/src/waiting.rs +++ b/pkgs/id/src/waiting.rs @@ -242,11 +242,13 @@ where self.by_key.contains_key(key) } - /// Holds an event that arrived at `arrived_at`, as a store restores its rows on open. + /// Holds an event that arrived at `arrived_at`. The store uses it for every hold: when it + /// restores its rows on open, and when it holds an event it has decided, which keeps the + /// event's first arrival time. /// /// Unlike [`insert`](Self::insert) and [`park`](Self::park), nothing expires first, and an /// empty `missing` does not release the event: it is held for good, as a parked event is. - /// The caller restores the events in the order they arrived, so they are released in that + /// The caller holds the events in the order they arrived, so they are released in that /// order. An event whose key is already held is ignored. /// /// # Errors From 927b60deaf17294c474db761c7b3a2c1e79ef305 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 11 Oct 2026 23:17:04 -0500 Subject: [PATCH 27/30] docs(rust): a fork can release waiters, which Ingest::Fork does not list [P1.8] A fork makes its proof headers present, so events of other authors that waited for them may apply. Ingest::Fork keeps its shape, so those events are not listed in the outcome. The doc now says so. --- pkgs/id/src/event_store/ingest.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/pkgs/id/src/event_store/ingest.rs b/pkgs/id/src/event_store/ingest.rs index e04bb98cb0..f39680a857 100644 --- a/pkgs/id/src/event_store/ingest.rs +++ b/pkgs/id/src/event_store/ingest.rs @@ -111,7 +111,9 @@ pub enum Ingest { }, /// The author signed two different events at one sequence number. The chain is /// frozen there, and both headers are stored as the proof. A further event at the - /// fork point that changes the proof is reported the same way. + /// fork point that changes the proof is reported the same way. The headers are present + /// now, so events of other authors that waited for them may apply. Those are not listed + /// here. Read them from the store. Fork { /// The author. author: AuthorKey, From 746bfb9dcb0695afc62979d60d1fcd63166b0b4d Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 00:22:28 -0500 Subject: [PATCH 28/30] test(rust): a held proof header that a fork makes present stays held [P1.11] A fork makes its two headers present, and a held header that a fork makes present is held for good. The red unit test checks the header is still held after the fork. The property checks, after every step and restart over random arrival orders, that each acknowledged waiting event is held, stored, frozen, or expired. Both fail on the store as it stood: a held header's row was deleted, and the header was neither held nor stored. --- pkgs/id/src/event_store/ingest.rs | 25 +++++ pkgs/id/tests/event_store_properties.rs | 129 ++++++++++++++++++++++++ 2 files changed, 154 insertions(+) diff --git a/pkgs/id/src/event_store/ingest.rs b/pkgs/id/src/event_store/ingest.rs index f39680a857..caa5214416 100644 --- a/pkgs/id/src/event_store/ingest.rs +++ b/pkgs/id/src/event_store/ingest.rs @@ -1701,6 +1701,31 @@ mod tests { store.check_invariants().unwrap(); } + #[test] + fn test_a_held_event_that_a_fork_makes_a_proof_header_stays_held() { + let (_dir, mut store) = open(); + let signer = key(50); + let who = author(&signer); + let missing = Hash::digest(b"an event that is never delivered"); + // Seq 1 waits for a backlink that never arrives, and its rival at seq 1 forks it. + let held = event(&signer, 1, Some(missing), Vec::new(), "message"); + let rival = event(&signer, 1, Some(missing), Vec::new(), "rival"); + assert_eq!(ingest(&mut store, &held), Ingest::Waiting { id: held.id }); + assert!(matches!( + ingest(&mut store, &rival), + Ingest::Fork { seq: 1, .. } + )); + let proof = store.fork_proof(&who).unwrap().expect("a proof is stored"); + assert_eq!( + [proof.first.id, proof.second.id], + sorted(&held.id, &rival.id) + ); + // A proof header never applies, so it stays held for good. It is neither stored nor held + // if the fork drops it. + assert!(store.is_waiting(&held.id), "a held proof header stays held"); + store.check_invariants().unwrap(); + } + #[test] fn test_a_write_whose_rebuild_fails_makes_the_store_refuse_calls() { let (_dir, mut store) = open_with(WaitingLimits::new(256, 1_000)); diff --git a/pkgs/id/tests/event_store_properties.rs b/pkgs/id/tests/event_store_properties.rs index 7b06fbc1c8..3f34150ce8 100644 --- a/pkgs/id/tests/event_store_properties.rs +++ b/pkgs/id/tests/event_store_properties.rs @@ -553,6 +553,102 @@ fn deliver_with_restarts( Ok((outcomes, state, held)) } +/// Delivers `order` to one store, which is closed and reopened before each delivery in `restarts`, +/// and checks the waiting states after each step. Delivery `i` runs at clock `times[i]`. +/// +/// An event that is due at a step's clock expires during that step, so it is taken out of the +/// pending set first. The store drops it, or holds it again if it is delivered again. +fn check_each_step( + order: &[Vec], + times: &[u64], + restarts: &[usize], + limits: WaitingLimits, + events: &BTreeMap, +) -> Result<(), TestCaseError> { + let storage = MemStorage::default(); + let open = |at: u64| { + EventStore::open_with(&storage, limits, at) + .map_err(|err| TestCaseError::fail(err.to_string())) + }; + let mut store = open(times.first().copied().unwrap_or(0))?; + // Each waiting event the store acknowledged, with the clock it arrived at. Its age counts from + // there. + let mut pending: BTreeMap = BTreeMap::new(); + for (i, bytes) in order.iter().enumerate() { + let now = times[i]; + pending.retain(|_, (arrived_at, _)| !limits.is_due(*arrived_at, now)); + if restarts.contains(&i) { + drop(store); + store = open(now)?; + settle_pending(&store, &mut pending)?; + } + let outcome = store + .ingest(bytes, now) + .map_err(|err| TestCaseError::fail(err.to_string()))?; + if let Ingest::Waiting { id } = outcome + && let Some(event) = events.get(&id) + { + pending.entry(id).or_insert_with(|| (now, event.clone())); + } + store + .check_invariants() + .map_err(|err| TestCaseError::fail(err.to_string()))?; + settle_pending(&store, &mut pending)?; + } + Ok(()) +} + +/// Checks each pending waiting event. An event that is held is in one state. One that is stored +/// has applied or been voided. One that a fork froze at or below its sequence number is refused, +/// and leaves no row: its chain can never apply it. A fork proof header never applies, so it must +/// stay held. Any other event that is neither held nor stored is lost, and fails the test. +/// Settled events leave the pending set. +fn settle_pending( + store: &EventStore, + pending: &mut BTreeMap, +) -> Result<(), TestCaseError> { + let mut settled = Vec::new(); + for (id, (arrived_at, event)) in pending.iter() { + if store.is_waiting(id) { + continue; + } + if store + .event_by_id(id) + .map_err(|err| TestCaseError::fail(err.to_string()))? + .is_some() + { + settled.push(*id); + continue; + } + let seq = event.header.seq_num; + let proof = store + .fork_proof(&author_of(event)) + .map_err(|err| TestCaseError::fail(err.to_string()))?; + let header = proof + .as_ref() + .is_some_and(|proof| proof.first.id == *id || proof.second.id == *id); + let frozen = proof + .as_ref() + .is_some_and(|proof| proof.seq <= seq && !header); + if frozen { + settled.push(*id); + continue; + } + return Err(TestCaseError::fail(format!( + "an acknowledged waiting event at sequence {seq} (arrived at {arrived_at}) is neither held nor stored{}", + if header { + ", and it is a fork proof header" + } else { + "" + } + ))); + } + for id in settled { + pending.remove(&id); + } + Ok(()) +} + /// Runs `run` on a helper thread. Fails if it has not returned within [`DELIVERY_LIMIT`], so a /// store that spins fails the test instead of hanging it. fn within_limit( @@ -574,6 +670,39 @@ fn within_limit( proptest! { #![proptest_config(config())] + /// After every delivery and every reopen, each waiting event the store acknowledged is in one + /// state: held, or stored (applied or voided), or refused because a fork froze its chain at or + /// below it, or dropped by the age cap. Random orders, repeats, forks at any depth, small caps, + /// and restarts all vary the path there. + #[test] + fn test_every_step_keeps_each_acknowledged_waiting_event_in_one_state(seed in any::()) { + let scenario = scenario(seed); + let events: BTreeMap = scenario + .events + .iter() + .map(|event| (event.id, event.clone())) + .collect(); + let mut rng = Rng(seed ^ 0x9E37_79B9_7F4A_7C15); + let max_age_ms = [1_500, 6_000, u64::MAX / 2][index(&mut rng, 3)]; + let per_author = [1, 2, 3, 256][index(&mut rng, 4)]; + let limits = WaitingLimits::new(per_author, max_age_ms); + for order in orders(&scenario.events, &mut rng) { + let mut clock = 0_u64; + let times: Vec = order + .iter() + .map(|_| { + clock += rng.below(1_000); + clock + }) + .collect(); + let every_delivery = rng.chance(2); + let restarts: Vec = (0..order.len()) + .filter(|_| every_delivery || rng.chance(3)) + .collect(); + check_each_step(&order, ×, &restarts, limits, &events)?; + } + } + /// At ingest, a header that breaks the sequence and backlink rule is refused as malformed, /// whatever its sequence number. It is not parked or held, so it takes no waiting slot and /// raises no conflict. A header that keeps the rule is not refused for it. From 7a2e503bb928a37254c7064a7301f668c1c6f657 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 00:22:36 -0500 Subject: [PATCH 29/30] fix(rust): a waiter released and held again stays in one state [P1.11] A fork released its two proof headers. Each release deleted the header's row and took it out of the pool, so a header that was held was neither held nor stored. A released event that the next decision made a proof header, or a duplicate of one, was deleted the same way. Mirror::present_proof makes a header present and holds a held copy for good, as a parked event is held. drop_released parks a released header whose decision does not apply it, and removes the row of any other released event that is refused. Each change is one write transaction, so the event stays in one state across it. --- pkgs/id/src/event_store/ingest.rs | 25 ++++++++----- pkgs/id/src/event_store/waiting_rows.rs | 48 +++++++++++++++++++++++-- 2 files changed, 62 insertions(+), 11 deletions(-) diff --git a/pkgs/id/src/event_store/ingest.rs b/pkgs/id/src/event_store/ingest.rs index caa5214416..bde161bf91 100644 --- a/pkgs/id/src/event_store/ingest.rs +++ b/pkgs/id/src/event_store/ingest.rs @@ -48,7 +48,8 @@ //! Held events count too. Two held events at one sequence number are a fork, though //! neither is applied. Held events are rows on disk, so a restart keeps them, and a conflict //! with an event held before the restart is still seen. An event the caps or the age limit -//! drops is forgotten, and sync sends it again. +//! drops is forgotten, and sync sends it again. A held event that a fork makes a proof header +//! stays held for good: it never applies, and the proof keeps its conflicts seen. //! //! # Known limit: a rival refused by a cap //! @@ -258,19 +259,19 @@ fn settle( released: m.release(&id, now)?, }, Decision::Duplicate => { - drop_released(m, &id, from_pool)?; + drop_released(m, &event, from_pool)?; Settled::Duplicate } Decision::Fork { seq, proof } => { - drop_released(m, &id, from_pool)?; + drop_released(m, &event, from_pool)?; let mut released = Vec::new(); for header in proof { - released.extend(m.release(&header, now)?); + released.extend(m.present_proof(&header, now)?); } Settled::Fork { seq, released } } Decision::Refuse(refusal) => { - drop_released(m, &id, from_pool)?; + drop_released(m, &event, from_pool)?; Settled::Refused(refusal) } Decision::Wait(deps) => held(m.hold(event, deps, false, now)?), @@ -279,11 +280,17 @@ fn settle( Ok(settled) } -fn drop_released(m: &Mirror<'_>, id: &Hash, from_pool: bool) -> Result<(), StoreError> { - if from_pool { - m.drop_row(id)?; +/// Settles a released event that the decision does not apply. A fork proof header never applies, +/// so it is held for good again. Any other event is refused, and its row goes. +fn drop_released(m: &mut Mirror<'_>, event: &Event, from_pool: bool) -> Result<(), StoreError> { + if !from_pool { + return Ok(()); + } + if is_proof_header(m.txn, &author_of(event), &event.id)? { + m.park_proof(&event.id) + } else { + m.drop_row(&event.id) } - Ok(()) } const fn held(hold: Hold) -> Settled { diff --git a/pkgs/id/src/event_store/waiting_rows.rs b/pkgs/id/src/event_store/waiting_rows.rs index 43de6f3519..8fa4ecbb0c 100644 --- a/pkgs/id/src/event_store/waiting_rows.rs +++ b/pkgs/id/src/event_store/waiting_rows.rs @@ -19,7 +19,7 @@ use p2panda_core::{Hash, SeqNum}; use redb::{ReadableMultimapTable, ReadableTable, WriteTransaction}; -use super::{StoreError, WAITING, WAITING_BY_DEP, be_u64, corrupt, hash_of, seq_num}; +use super::{StoreError, WAITING, WAITING_BY_DEP, be_u64, corrupt, hash_of, row_event, seq_num}; use crate::chain::Event; use crate::waiting::{AuthorKey, WaitRefusal, WaitingPool}; @@ -261,13 +261,57 @@ impl Mirror<'_> { pub fn release(&mut self, id: &Hash, now: u64) -> Result, StoreError> { let released = self.pool.arrived(*id, now); delete(self.txn, id)?; + self.drop_dep(id)?; + Ok(released) + } + + /// Makes `id`, a fork proof header, present. Its waiters are released as [`release`](Self::release) + /// releases them. A held copy of `id` is held for good, not dropped: a proof header never + /// applies, so it waits for nothing, as a parked event does. The proof keeps its conflicts + /// seen. Returns the released events in arrival order. + pub fn present_proof(&mut self, id: &Hash, now: u64) -> Result, StoreError> { + let held = get(self.txn, id)?; + let released = self.pool.arrived(*id, now); + self.drop_dep(id)?; + if let Some(row) = held { + self.park(row)?; + } + Ok(released) + } + + /// Holds the proof header `id` for good again. The pool released it, and its row is still + /// there. A header can be released by another header's arrival, and then it is decided + /// before its own arrival parks it. Nothing is held for an ID without a row. + pub fn park_proof(&mut self, id: &Hash) -> Result<(), StoreError> { + match get(self.txn, id)? { + Some(row) => self.park(row), + None => Ok(()), + } + } + + /// Holds `row` parked: it waits for nothing, so no arrival releases it, and only the age cap + /// drops it. It keeps its first arrival time and its arrival number. + fn park(&mut self, row: Row) -> Result<(), StoreError> { + let event = row_event(&row)?; + let parked = Row { + deps: Vec::new(), + ..row + }; + self.pool + .restore(parked.author, parked.id, [], event, parked.arrived_at) + .map_err(|_refused| corrupt("a held proof header cannot be held for good"))?; + put(self.txn, &parked) + } + + /// Removes `id` from the dependencies of every row that waits for it. + fn drop_dep(&self, id: &Hash) -> Result<(), StoreError> { for waiter in waiters_of(self.txn, id)? { let mut row = get(self.txn, &waiter)? .ok_or_else(|| corrupt("a dependency is indexed to a waiting event with no row"))?; row.deps.retain(|dep| dep != id); put(self.txn, &row)?; } - Ok(released) + Ok(()) } /// Removes the row of an event the pool has released, once it is decided for good. From bec843314adc73bef956a6706feed26bbc41621f Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 12 Oct 2026 00:29:11 -0500 Subject: [PATCH 30/30] docs(id): phase 1 record: steps, commits, review, open items --- ...-10-11T22-25-52Z_phase_1_events_storage.md | 40 +++++++++++-------- 1 file changed, 24 insertions(+), 16 deletions(-) diff --git a/doc/2026-10-11T22-25-52Z_phase_1_events_storage/2026-10-11T22-25-52Z_phase_1_events_storage.md b/doc/2026-10-11T22-25-52Z_phase_1_events_storage/2026-10-11T22-25-52Z_phase_1_events_storage.md index 38b1c6ff0e..c875b3cad6 100644 --- a/doc/2026-10-11T22-25-52Z_phase_1_events_storage/2026-10-11T22-25-52Z_phase_1_events_storage.md +++ b/doc/2026-10-11T22-25-52Z_phase_1_events_storage/2026-10-11T22-25-52Z_phase_1_events_storage.md @@ -7,18 +7,18 @@ ## Steps -| Step | Track | Status | Commits | Tests added | Notes | -| --- | --- | --- | --- | --- | --- | -| P1.1 Storage decision record | lead | done | this file | none | redb everywhere; libsql replaced | -| P1.2 ChainExt | chainext | todo | | | | -| P1.3 Event store on redb | store | todo | | | after P1.2 | -| P1.4 Crash-safety gate | crash | todo | | | in-process fault model; corpus | -| P1.5 Waiting caps | caps | todo | | | | -| P1.6 Store traits over redb | traits | todo | | | after P1.3 | -| P1.7 Canonical CBOR vectors | chainext | todo | | | | -| P1.8 Ingest: verify with AnyHeader::decode, freeze forks | store | todo | | | after P1.3 | -| P1.9 Identity store on redb | identity | todo | | | libsql removed, AES-GCM values | -| P1.10 Crash gate for the identity store | crash | todo | | | after P1.4 and P1.9 | +| Step | Track | Status | Commits | Tests added | Notes | +| --------------------------------------- | -------- | --------------------------------------- | ------------------------------------------------ | ---------------------------------------------------- | ----------------------------------------------------- | +| P1.1 Storage decision record | lead | done | this file | none | redb everywhere; libsql replaced | +| P1.2 ChainExt | chainext | done | f96b8af6 | 22 unit, 11 property, seeds | p2panda-core at rev 3e84cac, no features | +| P1.3 Event store on redb | store | done | 949b2222 | 26 unit, crash creation sweep | first-creation: temp file, commit, sync, rename, sync | +| P1.4 Crash-safety gate | crash | done | d36e53d5, 06d84ed2 | sampled gate, full sweep, lying-sync control, corpus | `just crash-gate` | +| P1.5 Waiting caps | caps | done | caps track commits | 21 unit, property | 256 per author, 7 days | +| P1.6 Store traits over redb | traits | done (LogSync session deferred to P3.2) | d2b1a6ad, d19d2255 | 10 trait contract tests | p2panda-store without default features; sqlx absent | +| P1.7 Canonical CBOR vectors | chainext | done | 983649c4 | golden and dcbor vectors | | +| P1.8 Ingest: verify, freeze forks, wait | store | done | b4e7c1eb, 8fc776be, 1a90c102, 414479ec, 46bb1f2a | property over arrival orders, regressions | fork voids only the forked chain (46bb1f2a) | +| P1.9 Identity store on redb | identity | done | 3f04bdbf, a2f842fc | 38 identity tests | libsql removed; 75 packages gone | +| P1.10 Crash gate for the identity store | crash | done | 2eb950b9, fd311808, ad4c6e05 | identity sweep, first-creation fix | creation by rename fixed 20 of 147 stranded runs | ## Decisions @@ -29,16 +29,24 @@ ## Open questions -- None yet. +- A released waiter's arrival time: counted from first arrival (decided in P1.11 review). +- Identity store: the first-creation temp-file pattern is used; the `.creating` file is not locked against another process (reviewer, not reproduced). +- The LogSync session needs p2panda-sync, which pulls p2panda-store's sqlite default. Fork or feature change in P3.2. +- Caps and restarts: a conflict whose rival was dropped by a cap is seen only when the rival is sent again (documented and pinned by a test). ## Changes to the plan -- None yet. +- P1.11 added: waiting events persisted in redb (task 02 said so; the store track had kept them in memory). Format v3. +- Dependency voiding narrowed in Phase 1: a fork voids only its own chain. Authority-based voiding is Phase 2 (P2.3). +- Known issue fixed late: released waiters and fork proof headers left in neither state (P1.11 crash fix, 7a2e503b). +- conform scope `id` added (66983e25). ## Review notes and regression tests -- To be filled at each merge and at the end-of-phase review. +- End-of-phase review (review-phase-1): pinned the sequence and backlink rule at decode and at ingest; pinned the LogSync limit; found the dependency-voiding stall (fixed in 46bb1f2a). +- Regression tests: a fork voids only the forked chain; honest dependents apply; a released waiter keeps its first arrival time; a held proof header that a fork makes present stays held; a rival refused by the cap is seen only when sent again. ## End -- End commit and full test result: pending. +- Last commit before the PR: see the PR. Full test result on it: `cargo test --all-features --no-fail-fast` exit 0 (lib 1112, cli 116, crash and property suites, doc 19). +- Not verified: the Nix build (p2panda git dependency needs outputHashes in default.nix and flake.nix, unverified).