diff --git a/.sqlx/query-0533b4daa4f55ce7361a045bda6915aed1e9e0ba5692f577a09a6fd1425fd39d.json b/.sqlx/query-0533b4daa4f55ce7361a045bda6915aed1e9e0ba5692f577a09a6fd1425fd39d.json new file mode 100644 index 0000000..ebf5895 --- /dev/null +++ b/.sqlx/query-0533b4daa4f55ce7361a045bda6915aed1e9e0ba5692f577a09a6fd1425fd39d.json @@ -0,0 +1,21 @@ +{ + "db_name": "PostgreSQL", + "query": "\n with incoming as (\n select * from unnest(\n $1::text[], $2::bigint[], $3::text[], $4::text[],\n $5::timestamptz[], $6::timestamptz[], $7::numeric[], $8::boolean[]\n ) as t(chain, height, hash, miner, authored_at, observed_at, difficulty, at_tip)\n ),\n displaced as (\n insert into block_displacement (\n chain, height, hash, miner, authored_at, observed_at,\n difficulty, at_tip, displaced_at\n )\n select b.chain, b.height, b.hash, b.miner, b.authored_at, b.observed_at,\n b.difficulty, b.at_tip, now()\n from block b\n join incoming i on i.chain = b.chain and i.height = b.height\n -- `is distinct from`, not `<>`: a null on either side of `<>`\n -- yields null, which is not true, so a nulled hash would slip\n -- through unrecorded. Neither column is nullable today; the\n -- operator costs nothing and does not depend on that staying so.\n where b.hash is distinct from i.hash\n on conflict (chain, height, hash) do update\n set displaced_at = now()\n )\n insert into block (\n chain, height, hash, miner, authored_at, observed_at, difficulty, at_tip\n )\n select chain, height, hash, miner, authored_at, observed_at, difficulty, at_tip\n from incoming\n on conflict (chain, height) do update set\n hash = excluded.hash,\n miner = excluded.miner,\n authored_at = excluded.authored_at,\n observed_at = excluded.observed_at,\n -- coalesce: a reorg replacement re-observed from history has no\n -- difficulty to offer, and dropping the one already recorded for\n -- that height would put a hole in the series for no gain.\n difficulty = coalesce(excluded.difficulty, block.difficulty),\n at_tip = excluded.at_tip\n ", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "TextArray", + "Int8Array", + "TextArray", + "TextArray", + "TimestamptzArray", + "TimestamptzArray", + "NumericArray", + "BoolArray" + ] + }, + "nullable": [] + }, + "hash": "0533b4daa4f55ce7361a045bda6915aed1e9e0ba5692f577a09a6fd1425fd39d" +} diff --git a/.sqlx/query-18154cee1213de1b275c87babe63bd46b4191a20a9cf7b764ac9b197a594f7da.json b/.sqlx/query-18154cee1213de1b275c87babe63bd46b4191a20a9cf7b764ac9b197a594f7da.json deleted file mode 100644 index 4eb4d1f..0000000 --- a/.sqlx/query-18154cee1213de1b275c87babe63bd46b4191a20a9cf7b764ac9b197a594f7da.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n insert into block (\n chain, height, hash, miner, authored_at, observed_at, difficulty, at_tip\n )\n select * from unnest(\n $1::text[], $2::bigint[], $3::text[], $4::text[],\n $5::timestamptz[], $6::timestamptz[], $7::numeric[], $8::boolean[]\n )\n on conflict (chain, height) do update set\n hash = excluded.hash,\n miner = excluded.miner,\n authored_at = excluded.authored_at,\n observed_at = excluded.observed_at,\n -- coalesce: a reorg replacement re-observed from history has no\n -- difficulty to offer, and dropping the one already recorded for\n -- that height would put a hole in the series for no gain.\n difficulty = coalesce(excluded.difficulty, block.difficulty),\n at_tip = excluded.at_tip\n ", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "TextArray", - "Int8Array", - "TextArray", - "TextArray", - "TimestamptzArray", - "TimestamptzArray", - "NumericArray", - "BoolArray" - ] - }, - "nullable": [] - }, - "hash": "18154cee1213de1b275c87babe63bd46b4191a20a9cf7b764ac9b197a594f7da" -} diff --git a/CLAUDE.md b/CLAUDE.md index 8468571..d2ea4b3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -60,6 +60,16 @@ would quietly under-count exactly the miners who won blocks during a burst. upsert is what makes a replacement overwrite rather than accumulate. A schema keyed on the hash would inflate the losing fork's author forever. +**A reorg copies the old row into `block_displacement` first** (`0003`), in the +same statement as the upsert. That is not optional bookkeeping: the node cannot +be asked for the block later. `blocks-pruning` defaults to `archive-canonical`, +so non-canonical bodies go once finality passes them — about a hundred blocks +behind the tip on Planck — and difficulty is a state read against a 256-block +default. Whatever `record_blocks` captures is all there will ever be. The two +halves are one statement because every data-modifying CTE sees the same +snapshot, so the copy reads the pre-update row; splitting them would need an +explicit transaction to be equivalent. + ## Facts established by measurement Taken from the live Planck chain, 2026-09-04. Don't re-derive or contradict diff --git a/crates/blackbeard-data/migrations/0003_block_displacement.sql b/crates/blackbeard-data/migrations/0003_block_displacement.sql new file mode 100644 index 0000000..548b0f7 --- /dev/null +++ b/crates/blackbeard-data/migrations/0003_block_displacement.sql @@ -0,0 +1,46 @@ +-- What a reorg overwrote. +-- +-- `block` is keyed on (chain, height) precisely so a replacement overwrites +-- rather than accumulates — a schema keyed on the hash would inflate the losing +-- fork's author forever. The cost of that choice is that the losing block is +-- gone without a trace, and with it the only record that the height was ever +-- contested. This table is that trace: one row per displacement, holding +-- exactly what was about to be overwritten. +-- +-- It is not an attempt to keep the orphan itself. The node will not serve one +-- for long — `blocks-pruning` defaults to `archive-canonical`, which discards +-- non-canonical bodies once finality passes them, and Planck finalises about a +-- hundred blocks behind the tip. Difficulty is worse: it is a state read, and +-- state defaults to 256 blocks. So a few minutes after the reorg the chain +-- itself can no longer answer for the block, and what is written here is all +-- there will ever be. +-- +-- Which is why it holds the whole displaced row rather than just its hash. The +-- author is the interesting field — it says who lost the race — and it costs +-- eight columns of a table that gains a row only when the chain forks. +create table block_displacement ( + chain text not null references chain (id) on delete cascade, + height bigint not null, + -- The displaced block's hash. Addressable: a block route keyed on the hash + -- can serve this even though `block` no longer mentions it. + hash text not null, + miner text not null, + authored_at timestamptz, + observed_at timestamptz not null, + difficulty numeric, + at_tip boolean not null, + -- When the replacement arrived. On the same hash being displaced twice — + -- a chain that reorgs back and forth across the same pair — this is the + -- most recent time, and every other column is immutable for a given hash. + displaced_at timestamptz not null default now(), + primary key (chain, height, hash) +); + +-- "What else has held this height?", for the block page's replaced-by banner. +create index block_displacement_chain_height_idx + on block_displacement (chain, height desc); + +-- "Is this hash a block we once recorded?" — the lookup a hash-addressed route +-- makes, which the primary key cannot serve without knowing the height first. +create index block_displacement_chain_hash_idx + on block_displacement (chain, hash); diff --git a/crates/blackbeard-data/src/store.rs b/crates/blackbeard-data/src/store.rs index f4d1649..1359556 100644 --- a/crates/blackbeard-data/src/store.rs +++ b/crates/blackbeard-data/src/store.rs @@ -219,7 +219,17 @@ impl Store { /// One statement with array parameters rather than a loop: a startup /// backfill inserts tens of thousands of rows, and a round trip each would /// take minutes. The `on conflict` is what makes a reorg correct — a block - /// replacing another at the same height overwrites it. + /// replacing another at the same height overwrites it — and the CTE ahead of + /// it copies whatever is about to be overwritten into `block_displacement` + /// first, so the losing block leaves a trace even though the standings do + /// not count it. + /// + /// Both halves are one statement deliberately. Every data-modifying CTE + /// sees the same snapshot, so the copy reads the *old* row even though the + /// insert below it is replacing that row in the same breath — and a failure + /// anywhere rolls back both, which two statements without a transaction + /// would not. The alternative, a trigger, would do this invisibly to anyone + /// reading the query. pub async fn record_blocks(&self, blocks: &[BlockRecord]) -> Result { if blocks.is_empty() { return Ok(0); @@ -238,13 +248,34 @@ impl Store { let result = sqlx::query!( r#" + with incoming as ( + select * from unnest( + $1::text[], $2::bigint[], $3::text[], $4::text[], + $5::timestamptz[], $6::timestamptz[], $7::numeric[], $8::boolean[] + ) as t(chain, height, hash, miner, authored_at, observed_at, difficulty, at_tip) + ), + displaced as ( + insert into block_displacement ( + chain, height, hash, miner, authored_at, observed_at, + difficulty, at_tip, displaced_at + ) + select b.chain, b.height, b.hash, b.miner, b.authored_at, b.observed_at, + b.difficulty, b.at_tip, now() + from block b + join incoming i on i.chain = b.chain and i.height = b.height + -- `is distinct from`, not `<>`: a null on either side of `<>` + -- yields null, which is not true, so a nulled hash would slip + -- through unrecorded. Neither column is nullable today; the + -- operator costs nothing and does not depend on that staying so. + where b.hash is distinct from i.hash + on conflict (chain, height, hash) do update + set displaced_at = now() + ) insert into block ( chain, height, hash, miner, authored_at, observed_at, difficulty, at_tip ) - select * from unnest( - $1::text[], $2::bigint[], $3::text[], $4::text[], - $5::timestamptz[], $6::timestamptz[], $7::numeric[], $8::boolean[] - ) + select chain, height, hash, miner, authored_at, observed_at, difficulty, at_tip + from incoming on conflict (chain, height) do update set hash = excluded.hash, miner = excluded.miner, diff --git a/crates/blackbeard-data/tests/store.rs b/crates/blackbeard-data/tests/store.rs index f80827a..fb16837 100644 --- a/crates/blackbeard-data/tests/store.rs +++ b/crates/blackbeard-data/tests/store.rs @@ -474,3 +474,153 @@ async fn re_recording_a_block_without_a_difficulty_keeps_the_one_already_known() f.cleanup().await; } + +/// The displacement table, read back raw — there is no store method for it yet. +/// The read shape belongs with the route that will use it; what these tests +/// hold is that the write happens and captures the right side of the swap. +async fn displacements(pool: &sqlx::PgPool, height: i64) -> Vec<(String, String, Option)> { + sqlx::query_as::<_, (String, String, Option)>( + "select hash, miner, difficulty::text from block_displacement + where chain = $1 and height = $2 order by hash", + ) + .bind(chain().as_str()) + .bind(height) + .fetch_all(pool) + .await + .unwrap() +} + +#[tokio::test] +async fn a_reorg_records_what_it_displaced() { + // The losing block is overwritten in `block` by design. Without this it + // would vanish entirely — and the node cannot be asked for it later, since + // non-canonical bodies are discarded once finality passes them. What is + // captured here is all there will ever be, so it has to be the *old* row: + // the author who lost the race, not the one who won it. + let f = fixture!("displacement"); + seed_chain(&f.store).await; + + f.store + .record_blocks(&[block(100, 1, 600, "1000")]) + .await + .unwrap(); + + let mut replacement = block(100, 2, 601, "2000"); + replacement.hash = "0xreplacement".into(); + f.store.record_blocks(&[replacement]).await.unwrap(); + + // The canonical row is the winner. + let rows = f.store.recent_blocks(&chain(), 10).await.unwrap(); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].miner, miner(2)); + + // The trace is the loser, with everything we knew about it. + let gone = displacements(&f.pool, 100).await; + assert_eq!(gone.len(), 1); + assert_eq!(gone[0].0, format!("0x{:064x}", 100), "the displaced hash"); + assert_eq!(gone[0].1, miner(1).0, "the author who lost the race"); + assert_eq!( + gone[0].2.as_deref(), + Some("1000"), + "the difficulty as recorded then, not the replacement's" + ); + + f.cleanup().await; +} + +#[tokio::test] +async fn re_recording_the_same_block_displaces_nothing() { + // Every head is written again by the gap fill that spans it, and the + // startup backfill rewrites whatever it overlaps. If an identical rewrite + // counted as a displacement, the table would fill with reorgs that never + // happened and the block page would claim every height had been contested. + let f = fixture!("displacement_noop"); + seed_chain(&f.store).await; + + for _ in 0..3 { + f.store + .record_blocks(&[block(100, 1, 600, "1000")]) + .await + .unwrap(); + } + + assert!(displacements(&f.pool, 100).await.is_empty()); + + f.cleanup().await; +} + +#[tokio::test] +async fn a_batch_records_only_the_heights_that_actually_changed() { + // The capture joins the whole incoming batch against `block`, so a gap fill + // of a thousand blocks that replaces one of them must record one row. + let f = fixture!("displacement_batch"); + seed_chain(&f.store).await; + + let first: Vec<_> = (1..=10) + .map(|h| block(h, 1, h as i64 * 6, "1000")) + .collect(); + f.store.record_blocks(&first).await.unwrap(); + + let mut second = first.clone(); + second[4].hash = "0xforked".into(); + second[4].miner = miner(9); + assert_eq!(f.store.record_blocks(&second).await.unwrap(), 10); + + assert!(displacements(&f.pool, 4).await.is_empty()); + let gone = displacements(&f.pool, 5).await; + assert_eq!(gone.len(), 1); + assert_eq!(gone[0].1, miner(1).0); + assert!(displacements(&f.pool, 6).await.is_empty()); + + f.cleanup().await; +} + +#[tokio::test] +async fn a_chain_that_reorgs_back_and_forth_keeps_both_sides() { + // A displaces nothing, B displaces A, A displaces B, B displaces A again. + // The last step is a hash that has been displaced before: it must update + // rather than collide, and the table must not grow a third row for a fork + // with only two sides. + let f = fixture!("displacement_flapping"); + seed_chain(&f.store).await; + + let side = |tag: &str, m: u8| { + let mut b = block(100, m, 600, "1000"); + b.hash = format!("0x{tag}"); + b + }; + + f.store.record_blocks(&[side("aaa", 1)]).await.unwrap(); + f.store.record_blocks(&[side("bbb", 2)]).await.unwrap(); + f.store.record_blocks(&[side("aaa", 1)]).await.unwrap(); + + let before_last: DateTime = sqlx::query_scalar("select now()") + .fetch_one(&f.pool) + .await + .unwrap(); + f.store.record_blocks(&[side("bbb", 2)]).await.unwrap(); + + let gone = displacements(&f.pool, 100).await; + assert_eq!( + gone.iter().map(|g| g.0.as_str()).collect::>(), + vec!["0xaaa", "0xbbb"], + "two sides of the fork, one row each" + ); + + // The repeat displacement of 0xaaa moved its timestamp rather than being + // dropped, so the table answers "when was this last replaced". + let latest: DateTime = sqlx::query_scalar( + "select displaced_at from block_displacement + where chain = $1 and height = 100 and hash = '0xaaa'", + ) + .bind(chain().as_str()) + .fetch_one(&f.pool) + .await + .unwrap(); + assert!( + latest >= before_last, + "displaced_at {latest} did not advance past {before_last}" + ); + + f.cleanup().await; +} diff --git a/readme.md b/readme.md index 1f1c27a..9d22c9d 100644 --- a/readme.md +++ b/readme.md @@ -143,6 +143,14 @@ is a proof-of-work chain and it reorgs. An upsert on that key means a block replacing another at the same height overwrites it, so the standings reflect the canonical chain rather than the union of every fork the observer witnessed. +What that overwrites is copied into `block_displacement` on the way past, so a +contested height leaves a trace of who lost it. The node will not answer for the +losing block for long — it keeps only canonical bodies once finality passes +them, and difficulty is a state read behind a 256-block window — so the row +written at the moment of the reorg is the only record there will be. It is not +an orphan store: the block itself is gone, and only what the observer had +already seen of it survives. + The database is what lets the site keep promises a rolling window cannot: "how did I do last week", a hashrate line older than the process, and a leaderboard that survives a deploy. On start the daemon replays the window and the held