diff --git a/src/backfill/worker/task.rs b/src/backfill/worker/task.rs index b84cfb7..10ced9e 100644 --- a/src/backfill/worker/task.rs +++ b/src/backfill/worker/task.rs @@ -867,6 +867,47 @@ mod tests { }) } + /// [`Self::live_commit`] for `c`, followed by an op whose rkey doesn't parse, so applying + /// it fails halfway + fn half_bad_commit( + &self, + car: &BuiltCar, + c: &[u8], + ) -> miette::Result> { + let mut commit = self.live_commit(car, "c", c)?; + let mut bad = commit.ops[0].clone(); + bad.path = CowStr::Owned(format!("{COLLECTION}/bad rkey").into()); + commit.ops.push(bad); + Ok(commit) + } + + /// hands `commit`, whose blocks are `car`, to a shard as a live event and waits for it + async fn apply_live( + &self, + car: &BuiltCar, + commit: StreamCommit<'static>, + ) -> miette::Result<()> { + let event = IndexerEvent { + seq: 1, + firehose: Url::parse("wss://relay.example").into_diagnostic()?, + advances_cursor: false, + data: IndexerEventData::Commit(IndexerCommitData { + commit, + chain_break: false, + parsed_blocks: crate::car::parse_commit_car(car.bytes.clone(), false)?, + }), + }; + let (tx, shard) = FirehoseWorker::spawn_one_shard(self.state.clone()); + tx.send(IndexerMessage::Event(Box::new(event))) + .await + .map_err(|_| miette::miette!("the shard is gone"))?; + drop(tx); + tokio::task::spawn_blocking(move || shard.join()) + .await + .into_diagnostic()? + .map_err(|_| miette::miette!("indexer shard panicked")) + } + /// [`Self::live_commit`], buffered the way the shard does while the repo is queued fn buffer(&self, car: &BuiltCar, rkey: &str, body: &[u8]) -> miette::Result<()> { let commit = self.live_commit(car, rkey, body)?; @@ -1778,31 +1819,59 @@ mod tests { .insert(keys::repo_key(&fixture.did), db::ser_repo_state(&row)?) .into_diagnostic()?; - let event = IndexerEvent { - seq: 1, - firehose: Url::parse("wss://relay.example").into_diagnostic()?, - advances_cursor: false, - data: IndexerEventData::Commit(IndexerCommitData { - commit: fixture.live_commit(&live, "b", &b)?, - chain_break: false, - parsed_blocks: crate::car::parse_commit_car(live.bytes.clone(), false)?, - }), - }; - let (tx, shard) = FirehoseWorker::spawn_one_shard(fixture.state.clone()); - tx.send(IndexerMessage::Event(Box::new(event))) - .await - .map_err(|_| miette::miette!("the shard is gone"))?; - drop(tx); - tokio::task::spawn_blocking(move || shard.join()) - .await - .into_diagnostic()? - .map_err(|_| miette::miette!("indexer shard panicked"))?; + fixture + .apply_live(&live, fixture.live_commit(&live, "b", &b)?) + .await?; assert_eq!(fixture.record_rkeys()?, ["a", "b"]); assert_eq!(fixture.repo()?.root, rooted("3jzfcijpj2z2d")?.root); Ok(()) } + #[tokio::test] + async fn a_buffered_commit_failing_halfway_writes_none_of_its_records() -> miette::Result<()> { + let fixture = Fixture::new().await?; + fixture.fetch_with_a_buffered_commit().await?; + let c = post("c"); + let bad = build_car("3jzfcijpj2z2d", &[("c", c.as_slice())]).await?; + let commit = fixture.half_bad_commit(&bad, &c)?; + let mut txn = DbTxn::new(&fixture.state.db); + crate::ops::persist_to_resync_buffer(&mut txn, &fixture.state.db, &fixture.did, &commit)?; + txn.commit()?; + + let result = fixture.run(keys::pending_key(7)).await; + assert!( + matches!(result, Err(BackfillError::Generic(_))), + "{result:?}" + ); + assert_eq!(fixture.record_rkeys()?, ["a", "b"]); + assert_eq!(fixture.state.db.get_count_sync("records"), 2); + Ok(()) + } + + #[tokio::test] + async fn a_live_commit_failing_halfway_writes_none_of_its_records() -> miette::Result<()> { + let fixture = Fixture::new().await?; + fixture.seed(&rooted("3jzfcijpj2z2a")?, 7, &[])?; + let a = post("a"); + let c = post("c"); + let fetched = build_car("3jzfcijpj2z2b", &[("a", a.as_slice())]).await?; + fixture.pds.serve_car(fetched.bytes).await; + assert_eq!( + fixture.run(keys::pending_key(7)).await?, + TaskDisposition::Finished + ); + let live = build_car("3jzfcijpj2z2c", &[("a", a.as_slice()), ("c", c.as_slice())]).await?; + + fixture + .apply_live(&live, fixture.half_bad_commit(&live, &c)?) + .await?; + + assert_eq!(fixture.record_rkeys()?, ["a"]); + assert_eq!(fixture.state.db.get_count_sync("records"), 1); + Ok(()) + } + #[tokio::test] async fn a_buffered_commit_that_cant_apply_costs_one_refetch() -> miette::Result<()> { let fixture = Fixture::new().await?; diff --git a/src/car.rs b/src/car.rs index 0620d63..dc6152d 100644 --- a/src/car.rs +++ b/src/car.rs @@ -128,6 +128,15 @@ impl CarBlock { &self.cid } + /// the same block, hashed now if the parse didn't, so verifying it later costs nothing + pub(crate) fn checked(self) -> Result { + self.verify()?; + Ok(Self { + cid_checked: true, + ..self + }) + } + pub(crate) fn verify(&self) -> Result> { if !self.cid_checked { validate_block_cid(&self.cid, &self.bytes)?; @@ -695,6 +704,18 @@ mod tests { assert_eq!(verified.bytes().as_ref(), b"forged"); } + #[test] + fn checking_a_block_hashes_it_once() { + let block = forged(cid(1)).block(&cid(1)).unwrap(); + let err = block.checked().unwrap_err(); + assert!(err.to_string().contains("CAR block CID mismatch")); + + let real = jacquard_repo::mst::util::compute_cid(b"forged").unwrap(); + let checked = forged(real).block(&real).unwrap().checked().unwrap(); + assert!(checked.cid_checked); + assert_eq!(checked.verify().unwrap().bytes().as_ref(), b"forged"); + } + #[tokio::test] async fn blocks_from_a_non_verifying_parse_are_hashed_when_verified() { let car = car_with_blocks(&[(cid(1), b"forged")]).await; diff --git a/src/ops.rs b/src/ops.rs index b8eed7a..73ec84d 100644 --- a/src/ops.rs +++ b/src/ops.rs @@ -248,8 +248,9 @@ pub fn apply_commit<'s>( } repo_state.touch(); - let mut record_txn = txn.records(state, &DbTid::from(&commit.rev), did)?; - + // the shard commits its batch even when this fails, and the counts only land in finish, so + // everything the commit itself can get wrong is checked before the first write + let mut writes = Vec::with_capacity(commit.ops.len()); for op in &commit.ops { let (collection, rkey) = parse_path(&op.path)?; @@ -260,7 +261,7 @@ pub fn apply_commit<'s>( let rkey = DbRkey::new(rkey); let action = DbAction::try_from(op.action.as_str())?; - match action { + let block = match action { DbAction::Create | DbAction::Update => { let Some(cid) = &op.cid else { continue; @@ -274,11 +275,21 @@ pub fn apply_commit<'s>( "block {cid} not found in CAR for record {did}/{collection}/{rkey}" )); }; - record_txn.put_record(collection, &rkey, &block, action)?; - } - DbAction::Delete => { - record_txn.delete_record(collection, &rkey)?; + let block = block + .checked() + .map_err(|e| miette::miette!("record {did}/{collection}/{rkey}: {e}"))?; + Some(block) } + DbAction::Delete => None, + }; + writes.push((collection, rkey, action, block)); + } + + let mut record_txn = txn.records(state, &DbTid::from(&commit.rev), did)?; + for (collection, rkey, action, block) in &writes { + match block { + Some(block) => record_txn.put_record(collection, rkey, block, *action)?, + None => record_txn.delete_record(collection, rkey)?, } } diff --git a/tests/representation_inventory.tsv b/tests/representation_inventory.tsv index 1c38524..5c6fe67 100644 --- a/tests/representation_inventory.tsv +++ b/tests/representation_inventory.tsv @@ -86,6 +86,7 @@ car-codec:src/car.rs::Blocks::default rust:src/car.rs::an_empty_default_keeps_me car-codec:src/car.rs::Blocks::extend rust:src/car.rs::merged_blocks_stay_checked_only_if_both_sides_were car-codec:src/car.rs::Blocks::get rust:src/car.rs::every_parse_keeps_the_last_duplicate_copy car-codec:src/car.rs::Blocks::map rust:src/car.rs::stream_cut_short_is_truncated +car-codec:src/car.rs::CarBlock::checked rust:src/car.rs::checking_a_block_hashes_it_once car-codec:src/car.rs::CarBlock::cid rust:src/car.rs::an_empty_default_keeps_merged_blocks_checked car-codec:src/car.rs::CarBlock::verify rust:src/car.rs::blocks_from_a_non_verifying_parse_are_hashed_when_verified car-codec:src/car.rs::CarStream::finish_with rust:src/car.rs::stream_cut_short_is_truncated