diff --git a/docs/user-guide/basic-operations.md b/docs/user-guide/basic-operations.md index 94d372a..97436c7 100644 --- a/docs/user-guide/basic-operations.md +++ b/docs/user-guide/basic-operations.md @@ -283,7 +283,11 @@ A background service runs every 12 hours (by default) and issues `ALTER TABLE ## Deleting Data -HyperbyteDB supports `DELETE` statements that mark data with tombstones. Tombstoned data is excluded from query results at read time; physical row removal happens via retention enforcement or MergeTree background merges. +`DELETE` removes the matching rows from storage. The statement waits for points still in the WAL to be written first (up to 15 s), so a point written before the `DELETE` is removed and one written after it is kept. + +A node keeps the WAL entries behind its last flush for crash recovery and writes them again when it restarts. Each `DELETE` is recorded with the point the WAL had reached, and a restarted node applies it again at that point, so deleted rows stay deleted. + +In a cluster, a write that reaches a replica after the replica applied the `DELETE` (from the replication queue or hinted handoff) is not removed. Avoid deleting data that is still being written. ```sql -- Delete all data older than 30 days diff --git a/hyperbytedb/src/adapters/wal/batching_wal.rs b/hyperbytedb/src/adapters/wal/batching_wal.rs index c1c8949..3afe1d3 100644 --- a/hyperbytedb/src/adapters/wal/batching_wal.rs +++ b/hyperbytedb/src/adapters/wal/batching_wal.rs @@ -312,6 +312,17 @@ impl WalPort for BatchingWal { self.inner.flushed_margin_start(through, max_bytes) } + async fn record_delete( + &self, + marker: &crate::ports::wal::DeleteMarker, + ) -> Result<(), HyperbytedbError> { + self.inner.record_delete(marker).await + } + + fn delete_markers(&self) -> Result, HyperbytedbError> { + self.inner.delete_markers() + } + async fn flush_wal(&self) -> Result<(), HyperbytedbError> { self.inner.flush_wal().await } diff --git a/hyperbytedb/src/adapters/wal/rocksdb_wal.rs b/hyperbytedb/src/adapters/wal/rocksdb_wal.rs index e410a16..84cdc24 100644 --- a/hyperbytedb/src/adapters/wal/rocksdb_wal.rs +++ b/hyperbytedb/src/adapters/wal/rocksdb_wal.rs @@ -12,16 +12,57 @@ use crate::adapters::wal::wal_ipc; use crate::domain::point::Point; use crate::domain::prepared_wal::PreparedWalSlot; use crate::error::HyperbytedbError; -use crate::ports::wal::{WalAppendBundle, WalEntry, WalFormat, WalPort}; +use crate::ports::wal::{DeleteMarker, WalAppendBundle, WalEntry, WalFormat, WalPort}; const WAL_CF: &str = "wal"; const WAL_META_CF: &str = "wal_meta"; const LAST_SEQ_KEY: &[u8] = b"last_seq"; +/// `wal_meta` keys of delete markers: this prefix, the marker's +/// `flushed_through` and a unique suffix, both big-endian. +const DELETE_MARKER_PREFIX: &[u8] = b"delete_marker/"; /// Encoded bytes one `read_range` call may decode. Entries expand several-fold /// once decoded, so an entry-count limit alone let a restart's first flush /// decode thousands of large write batches at once and OOM the pod. const READ_MAX_BYTES: usize = 32 << 20; +/// A delete marker and its `wal_meta` key. +type DeleteMarkerEntry = (Box<[u8]>, DeleteMarker); + +/// The delete markers in `wal_meta` with their keys, lowest +/// `flushed_through` first (the key order). +fn read_delete_marker_entries(db: &DB) -> Result, HyperbytedbError> { + let wal_meta_cf = db + .cf_handle(WAL_META_CF) + .ok_or_else(|| HyperbytedbError::Wal("wal_meta column family not found".into()))?; + let mut out = Vec::new(); + let iter = db.iterator_cf( + &wal_meta_cf, + IteratorMode::From(DELETE_MARKER_PREFIX, rocksdb::Direction::Forward), + ); + for item in iter { + let (key, value) = + item.map_err(|e| HyperbytedbError::Wal(crate::error::ChainedError::from_error(e)))?; + if !key.starts_with(DELETE_MARKER_PREFIX) { + break; + } + let marker: DeleteMarker = serde_json::from_slice(&value).map_err(|e| { + HyperbytedbError::Wal(crate::error::ChainedError::with_context( + "decode delete marker", + e, + )) + })?; + out.push((key, marker)); + } + Ok(out) +} + +fn read_delete_markers(db: &DB) -> Result, HyperbytedbError> { + Ok(read_delete_marker_entries(db)? + .into_iter() + .map(|(_, m)| m) + .collect()) +} + fn u64_to_be_bytes(n: u64) -> [u8; 8] { n.to_be_bytes() } @@ -48,6 +89,14 @@ pub struct RocksDbWal { truncated_through: Arc, /// Range deletes written to the WAL CF since its memtable last flushed. range_deletes_unflushed: Arc, + /// Delete markers kept in `wal_meta`; truncation looks for ones to drop + /// only when there are some. + delete_markers: Arc, + /// Makes delete marker keys unique within one `flushed_through`. + delete_marker_nonce: AtomicU64, + /// The markers kept when the WAL was opened: deletes from before this + /// process, which a restart replays. + markers_at_open: Vec, /// `(seq, encoded bytes)` of entries written by this process and not yet /// truncated, oldest first: what a byte-bounded margin is measured in. sizes: Arc>>, @@ -240,6 +289,9 @@ impl RocksDbWal { } }; + let markers_at_open = read_delete_markers(&db)?; + let delete_markers = markers_at_open.len() as u64; + Ok(Self { db, seq: Arc::new(AtomicU64::new(seq)), @@ -248,6 +300,13 @@ impl RocksDbWal { flushed_through: AtomicU64::new(first.saturating_sub(1)), truncated_through: Arc::new(AtomicU64::new(first)), range_deletes_unflushed: Arc::new(AtomicU64::new(0)), + delete_markers: Arc::new(AtomicU64::new(delete_markers)), + markers_at_open, + delete_marker_nonce: AtomicU64::new( + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_nanos() as u64), + ), sizes: Arc::new(std::sync::Mutex::new(std::collections::VecDeque::new())), arrow_cache: Arc::new(WalArrowCache::new()), wal_format: options.wal_format, @@ -627,6 +686,7 @@ impl WalPort for RocksDbWal { let last_seq = self.seq.load(Ordering::Relaxed); let truncated_through = Arc::clone(&self.truncated_through); let range_deletes_unflushed = Arc::clone(&self.range_deletes_unflushed); + let delete_markers = Arc::clone(&self.delete_markers); tokio::task::spawn_blocking(move || { let wal_cf = db @@ -660,8 +720,22 @@ impl WalPort for RocksDbWal { } } batch.put_cf(&wal_meta_cf, LAST_SEQ_KEY, u64_to_be_bytes(last_seq)); + // A marker is needed while an entry up to its `flushed_through` + // is left to flush again. + let mut markers_dropped = 0u64; + if delete_markers.load(Ordering::Acquire) > 0 { + for (key, marker) in read_delete_marker_entries(&db)? { + if marker.flushed_through < sequence { + batch.delete_cf(&wal_meta_cf, key); + markers_dropped += 1; + } + } + } db.write(batch) .map_err(|e| HyperbytedbError::Wal(crate::error::ChainedError::from_error(e)))?; + if markers_dropped > 0 { + delete_markers.fetch_sub(markers_dropped, Ordering::AcqRel); + } truncated_through.fetch_max(sequence, Ordering::AcqRel); if ranged && range_deletes_unflushed.fetch_add(1, Ordering::AcqRel) + 1 @@ -695,6 +769,48 @@ impl WalPort for RocksDbWal { self.flushed_through.store(sequence, Ordering::Release); } + async fn record_delete(&self, marker: &DeleteMarker) -> Result<(), HyperbytedbError> { + let mut key = DELETE_MARKER_PREFIX.to_vec(); + key.extend_from_slice(&u64_to_be_bytes(marker.flushed_through)); + key.extend_from_slice(&u64_to_be_bytes( + self.delete_marker_nonce.fetch_add(1, Ordering::Relaxed), + )); + let value = serde_json::to_vec(marker).map_err(|e| { + HyperbytedbError::Wal(crate::error::ChainedError::with_context( + "encode delete marker", + e, + )) + })?; + let db = self.db.clone(); + tokio::task::spawn_blocking(move || { + let wal_meta_cf = db + .cf_handle(WAL_META_CF) + .ok_or_else(|| HyperbytedbError::Wal("wal_meta column family not found".into()))?; + db.put_cf(&wal_meta_cf, key, value) + .map_err(|e| HyperbytedbError::Wal(crate::error::ChainedError::from_error(e))) + }) + .await + .map_err(|e| { + HyperbytedbError::Wal(crate::error::ChainedError::with_context( + "WAL delete marker task panicked", + e, + )) + })??; + self.delete_markers.fetch_add(1, Ordering::AcqRel); + Ok(()) + } + + fn delete_markers(&self) -> Result, HyperbytedbError> { + // Truncated past: no entry up to it is left to flush again. + let truncated_through = self.truncated_through.load(Ordering::Acquire); + Ok(self + .markers_at_open + .iter() + .filter(|m| m.flushed_through >= truncated_through) + .cloned() + .collect()) + } + fn flushed_margin_start(&self, through: u64, max_bytes: u64) -> u64 { let Ok(sizes) = self.sizes.lock() else { return through; @@ -826,6 +942,57 @@ mod tests { assert_eq!(wal.flushed_through(), 5); } + fn delete_marker(flushed_through: u64) -> DeleteMarker { + DeleteMarker { + flushed_through, + database: "db".into(), + retention_policy: "autogen".into(), + measurement: "cpu".into(), + predicate: "`host` = 'a'".into(), + } + } + + /// A restart replays a delete while an entry up to its `flushed_through` + /// is left to flush again, and not after. + #[tokio::test] + async fn delete_markers_outlive_a_reopen_until_truncated_past() { + let dir = TempDir::new().unwrap(); + { + let wal = RocksDbWal::open(dir.path()).unwrap(); + for _ in 0..5 { + wal.append(cpu_entry(1)).await.unwrap(); + } + wal.record_delete(&delete_marker(4)).await.unwrap(); + wal.record_delete(&delete_marker(2)).await.unwrap(); + wal.record_delete(&delete_marker(2)).await.unwrap(); + } + let wal = RocksDbWal::open(dir.path()).unwrap(); + let kept: Vec = wal + .delete_markers() + .unwrap() + .iter() + .map(|m| m.flushed_through) + .collect(); + assert_eq!(kept, vec![2, 2, 4]); + assert_eq!(wal.delete_markers().unwrap()[0], delete_marker(2)); + + // Entry 2 is still there: both markers at 2 stay. + wal.truncate_before(2).await.unwrap(); + assert_eq!(wal.delete_markers().unwrap().len(), 3); + wal.truncate_before(3).await.unwrap(); + drop(wal); + let wal = RocksDbWal::open(dir.path()).unwrap(); + assert_eq!(wal.delete_markers().unwrap(), vec![delete_marker(4)]); + // One recorded since the open is not replayed by this process. + wal.record_delete(&delete_marker(5)).await.unwrap(); + assert_eq!(wal.delete_markers().unwrap(), vec![delete_marker(4)]); + wal.truncate_before(6).await.unwrap(); + assert!(wal.delete_markers().unwrap().is_empty()); + drop(wal); + let wal = RocksDbWal::open(dir.path()).unwrap(); + assert!(wal.delete_markers().unwrap().is_empty()); + } + fn memtable_counts(wal: &RocksDbWal) -> (u64, u64) { let cf = wal.db.cf_handle(WAL_CF).unwrap(); let get = |p: &str| wal.db.property_int_value_cf(&cf, p).unwrap().unwrap(); diff --git a/hyperbytedb/src/application/flush_service.rs b/hyperbytedb/src/application/flush_service.rs index 7790bd5..80f3f13 100644 --- a/hyperbytedb/src/application/flush_service.rs +++ b/hyperbytedb/src/application/flush_service.rs @@ -69,6 +69,11 @@ pub struct FlushServiceImpl { shard_map: Option>, /// Bytes of WAL kept behind the flush in a sharded cluster. sharded_wal_retention_bytes: u64, + /// Deletes that ran before this process opened the WAL + /// ([`WalPort::delete_markers`]), lowest `flushed_through` first. The + /// flush starts again from the oldest kept WAL entry, so each is applied + /// again once the entries up to its `flushed_through` are flushed again. + replay_deletes: std::sync::Mutex>, } struct FlushWork { @@ -103,6 +108,17 @@ impl FlushServiceImpl { "flush service batch size configured" ); + let replay_deletes = match wal.delete_markers() { + Ok(markers) => markers.into(), + Err(e) => { + tracing::error!( + error = %e, + "cannot read the WAL's delete markers; rows deleted before the restart may come back" + ); + std::collections::VecDeque::new() + } + }; + Self { wal, last_flushed: Arc::new(Mutex::new(0)), @@ -120,6 +136,73 @@ impl FlushServiceImpl { sharding_enabled: false, shard_map: None, sharded_wal_retention_bytes: SHARDED_WAL_RETENTION_BYTES, + replay_deletes: std::sync::Mutex::new(replay_deletes), + } + } + + /// The `flushed_through` of the next delete to replay, if any. + fn next_replay_delete(&self) -> Option { + self.replay_deletes + .lock() + .ok()? + .front() + .map(|m| m.flushed_through) + } + + /// Apply again the replayed deletes whose entries are flushed again, up + /// to `cursor`. A delete that fails stays first, for the next flush. + async fn replay_deletes_through(&self, cursor: u64) -> Result<(), HyperbytedbError> { + loop { + let marker = { + let Ok(mut queue) = self.replay_deletes.lock() else { + return Ok(()); + }; + if queue.front().is_none_or(|m| m.flushed_through > cursor) { + return Ok(()); + } + match queue.pop_front() { + Some(m) => m, + None => return Ok(()), + } + }; + if !self.sink.deletes_rows() { + continue; + } + match self + .sink + .delete_rows( + &marker.database, + &marker.retention_policy, + &marker.measurement, + &marker.predicate, + ) + .await + { + Ok(()) => tracing::info!( + db = %marker.database, + measurement = %marker.measurement, + flushed_through = marker.flushed_through, + "applied a delete again after flushing the WAL entries before it again" + ), + Err(e) + if crate::application::schema_mutation_apply::is_unknown_column( + &e.to_string(), + ) => + { + tracing::warn!( + db = %marker.database, + measurement = %marker.measurement, + error = %e, + "replayed delete names columns the table no longer has; skipped" + ); + } + Err(e) => { + if let Ok(mut queue) = self.replay_deletes.lock() { + queue.push_front(marker); + } + return Err(e); + } + } } } @@ -564,6 +647,7 @@ impl FlushServiceImpl { let mut total_entries_processed = 0u64; let start = std::time::Instant::now(); + self.replay_deletes_through(cursor).await?; let snapshot_seq = self.wal.last_sequence().await?; if snapshot_seq <= cursor { return Ok(()); @@ -574,7 +658,13 @@ impl FlushServiceImpl { // prepared path would `continue` past the snapshot and fall through to a // native `read_range` that always returns empty but still seeks RocksDB. while cursor < snapshot_seq { + self.replay_deletes_through(cursor).await?; let from_seq = cursor + 1; + // A chunk stops at the next delete to replay, which runs once + // the entries before it are flushed again. + let window_end = self + .next_replay_delete() + .map_or(snapshot_seq, |s| s.min(snapshot_seq)); let wal_read_start = std::time::Instant::now(); // Bound the native read so a gap in the prepared cache (an entry @@ -587,7 +677,7 @@ impl FlushServiceImpl { // writes that arrived mid-flush stay cached for the next flush. if let Some(prepared) = self .wal - .take_prepared_range(from_seq, snapshot_seq, WAL_READ_CHUNK) + .take_prepared_range(from_seq, window_end, WAL_READ_CHUNK) .await? { if !prepared.is_empty() { @@ -615,7 +705,18 @@ impl FlushServiceImpl { let wal_read_elapsed = wal_read_start.elapsed(); histogram!("hyperbytedb_flush_wal_read_seconds", "path" => "native") .record(wal_read_elapsed.as_secs_f64()); + let entries: Vec<_> = entries + .into_iter() + .filter(|(seq, _)| *seq <= window_end) + .collect(); if entries.is_empty() { + if window_end < snapshot_seq { + // No entry left up to the next replayed delete (the WAL + // was truncated past it): it applies now. + *self.last_flushed.lock().await = window_end; + cursor = window_end; + continue; + } break; } @@ -623,7 +724,6 @@ impl FlushServiceImpl { let mut taken_points = 0usize; let entries: Vec<_> = entries .into_iter() - .filter(|(seq, _)| *seq <= snapshot_seq) .take_while(|(_, e)| { // Always take one entry, then stop at the budget. let take = taken_points == 0 || taken_points < budget; @@ -805,6 +905,8 @@ impl FlushServiceImpl { } } + self.replay_deletes_through(cursor).await?; + if total_entries_processed > 0 { let elapsed = start.elapsed(); histogram!("hyperbytedb_flush_duration_seconds").record(elapsed.as_secs_f64()); diff --git a/hyperbytedb/src/application/predicate_sql.rs b/hyperbytedb/src/application/predicate_sql.rs index eaef164..30b4ffc 100644 --- a/hyperbytedb/src/application/predicate_sql.rs +++ b/hyperbytedb/src/application/predicate_sql.rs @@ -188,7 +188,41 @@ pub async fn delete_rows( if let Some(wal) = wal { wait_for_flush(wal).await?; } - sink.delete_rows(db, rp, measurement, predicate).await + delete_flushed_rows(wal, sink, db, rp, measurement, predicate).await +} + +/// [`delete_rows`] without the wait for the flush, for a caller that has +/// just waited. With a `wal`, a marker is kept so that a restart, which +/// flushes the kept WAL entries again, deletes the rows again. +/// +/// # Errors +/// A chDB error from the delete, or a WAL error keeping the marker. +pub async fn delete_flushed_rows( + wal: Option<&dyn crate::ports::wal::WalPort>, + sink: &dyn crate::ports::points_sink::PointsSinkPort, + db: &str, + rp: &str, + measurement: &str, + predicate: &str, +) -> Result<(), HyperbytedbError> { + if predicate.is_empty() || !sink.deletes_rows() { + return Ok(()); + } + // Read before the delete: every entry up to here is among the rows it + // removes. + let flushed_through = wal.map(|w| w.flushed_through()); + sink.delete_rows(db, rp, measurement, predicate).await?; + if let (Some(wal), Some(flushed_through)) = (wal, flushed_through) { + wal.record_delete(&crate::ports::wal::DeleteMarker { + flushed_through, + database: db.to_string(), + retention_policy: rp.to_string(), + measurement: measurement.to_string(), + predicate: predicate.to_string(), + }) + .await?; + } + Ok(()) } /// Longest wait for the flush service to write the WAL's current entries: diff --git a/hyperbytedb/src/application/schema_mutation_apply.rs b/hyperbytedb/src/application/schema_mutation_apply.rs index d255e85..d28e5cb 100644 --- a/hyperbytedb/src/application/schema_mutation_apply.rs +++ b/hyperbytedb/src/application/schema_mutation_apply.rs @@ -175,23 +175,24 @@ async fn delete_series_rows_everywhere( ) -> Result<(), HyperbytedbError> { // The first delete waits for the WAL to flush; that covers every // measurement, so the rest do not wait again inside the Raft apply. - let mut wal = wal; + let wal = wal.map(|w| w.as_ref()); + let mut waited = false; for meas in metadata.list_measurements(db).await? { let series = crate::domain::chdb_naming::quoted_series_table_name(db, rp, &meas); let predicate = format!( "`series_id` IN (SELECT `series_id` FROM {} WHERE {tag_condition})", series.as_str() ); - let result = crate::application::predicate_sql::delete_rows( - wal.map(|w| w.as_ref()), - sink, - db, - rp, - &meas, - &predicate, - ) - .await; - wal = None; + let result = if waited { + crate::application::predicate_sql::delete_flushed_rows( + wal, sink, db, rp, &meas, &predicate, + ) + .await + } else { + crate::application::predicate_sql::delete_rows(wal, sink, db, rp, &meas, &predicate) + .await + }; + waited = true; match result { Err(e) if is_unknown_column(&e.to_string()) => {} other => other?, diff --git a/hyperbytedb/src/domain/wal.rs b/hyperbytedb/src/domain/wal.rs index 664e30a..9e6b410 100644 --- a/hyperbytedb/src/domain/wal.rs +++ b/hyperbytedb/src/domain/wal.rs @@ -10,3 +10,18 @@ pub struct WalEntry { /// Node that originated this write. 0 means the local node. pub origin_node_id: u64, } + +/// A row delete that ran when the WAL was flushed through `flushed_through`. +/// +/// A restarted node flushes the WAL entries it still holds again, which puts +/// back rows a delete removed. Replaying the delete once the entries up to +/// `flushed_through` are flushed again removes them a second time, and the +/// entries after it, written after the delete, are flushed on top. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct DeleteMarker { + pub flushed_through: u64, + pub database: String, + pub retention_policy: String, + pub measurement: String, + pub predicate: String, +} diff --git a/hyperbytedb/src/ports/wal.rs b/hyperbytedb/src/ports/wal.rs index 2b81011..04cb615 100644 --- a/hyperbytedb/src/ports/wal.rs +++ b/hyperbytedb/src/ports/wal.rs @@ -3,7 +3,7 @@ use async_trait::async_trait; use crate::domain::prepared_wal::PreparedWalSlot; use crate::error::HyperbytedbError; -pub use crate::domain::wal::WalEntry; +pub use crate::domain::wal::{DeleteMarker, WalEntry}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub enum WalFormat { @@ -92,6 +92,21 @@ pub trait WalPort: Send + Sync { /// budget. fn flushed_margin_start(&self, through: u64, max_bytes: u64) -> u64; + /// Keep `marker` until the WAL is truncated past + /// `marker.flushed_through`, so a restart can replay the delete. + async fn record_delete(&self, marker: &DeleteMarker) -> Result<(), HyperbytedbError> { + let _ = marker; + Ok(()) + } + + /// The delete markers kept when the WAL was opened that it still keeps, + /// lowest `flushed_through` first: the deletes a restart replays. Ones + /// recorded since are not included, because the flush is already past + /// them. + fn delete_markers(&self) -> Result, HyperbytedbError> { + Ok(Vec::new()) + } + /// Remove all durable and in-memory WAL entries for `database`. async fn purge_database(&self, database: &str) -> Result<(), HyperbytedbError> { let _ = database; diff --git a/hyperbytedb/tests/compat/ddl_tests.rs b/hyperbytedb/tests/compat/ddl_tests.rs index 85e6207..4ddddd4 100644 --- a/hyperbytedb/tests/compat/ddl_tests.rs +++ b/hyperbytedb/tests/compat/ddl_tests.rs @@ -1869,3 +1869,99 @@ async fn measurement_written_again_after_drop_keeps_its_fields() { .unwrap(); assert_eq!(values(&ctx, "SELECT value FROM cpu").await, vec![2.0]); } + +/// A sharded flush service over `ctx`'s WAL. After [`TestContext::reopen_wal`] +/// it is what a restarted node runs: its cursor starts at 0, so it flushes +/// the WAL margin again. +fn sharded_flush(ctx: &TestContext) -> hyperbytedb::application::flush_service::FlushServiceImpl { + hyperbytedb::application::flush_service::FlushServiceImpl::new( + ctx.wal.clone(), + 0, + ctx.points_sink.clone(), + ) + .with_sharding(true, None, 1) +} + +async fn ingest(ctx: &TestContext, lines: &str) { + ctx.ingestion + .ingest( + "testdb", + None, + None, + lines.as_bytes(), + WritePayloadFormat::LineProtocol, + ) + .await + .unwrap(); +} + +#[tokio::test] +#[serial(chdb)] +async fn deleted_rows_stay_deleted_after_a_restart_reflushes_the_wal() { + let Some(mut ctx) = chdb_context() else { + return; + }; + ctx.metadata.create_database("testdb").await.unwrap(); + ingest( + &ctx, + "cpu,host=a value=1.0 1000000000\ncpu,host=b value=2.0 2000000000", + ) + .await; + sharded_flush(&ctx).flush().await.unwrap(); + assert_eq!(values(&ctx, "SELECT value FROM cpu").await.len(), 2); + + let resp = ctx + .query("testdb", "DELETE FROM cpu WHERE host = 'a'") + .await + .unwrap(); + assert!( + resp.results[0].error.is_none(), + "{:?}", + resp.results[0].error + ); + assert_eq!(values(&ctx, "SELECT value FROM cpu").await, vec![2.0]); + + ctx.reopen_wal().unwrap(); + sharded_flush(&ctx).flush().await.unwrap(); + assert_eq!( + values(&ctx, "SELECT value FROM cpu").await, + vec![2.0], + "deleted row came back after the restart re-flush" + ); +} + +#[tokio::test] +#[serial(chdb)] +async fn a_row_written_after_a_delete_survives_the_restart_reflush() { + let Some(mut ctx) = chdb_context() else { + return; + }; + ctx.metadata.create_database("testdb").await.unwrap(); + ingest( + &ctx, + "cpu,host=a value=1.0 1000000000\ncpu,host=b value=2.0 2000000000", + ) + .await; + let flush = sharded_flush(&ctx); + flush.flush().await.unwrap(); + + let resp = ctx + .query("testdb", "DELETE FROM cpu WHERE host = 'a'") + .await + .unwrap(); + assert!( + resp.results[0].error.is_none(), + "{:?}", + resp.results[0].error + ); + ingest(&ctx, "cpu,host=a value=3.0 3000000000").await; + flush.flush().await.unwrap(); + drop(flush); + assert_eq!(values(&ctx, "SELECT value FROM cpu").await, vec![2.0, 3.0]); + + // Restart: the replay re-applies the delete after the rows before it, + // and the row written after it is flushed again on top. + ctx.reopen_wal().unwrap(); + sharded_flush(&ctx).flush().await.unwrap(); + assert_eq!(values(&ctx, "SELECT value FROM cpu").await, vec![2.0, 3.0]); +} diff --git a/hyperbytedb/tests/compat/main.rs b/hyperbytedb/tests/compat/main.rs index 19b0830..4d2bcb6 100644 --- a/hyperbytedb/tests/compat/main.rs +++ b/hyperbytedb/tests/compat/main.rs @@ -94,6 +94,34 @@ pub struct TestContext { _tmpdir: tempfile::TempDir, } +impl TestContext { + /// What a restart does to the WAL: close it, open it again, and build + /// the services over it anew. The services first move to a scratch WAL, + /// so that nothing holds the old one open. + pub fn reopen_wal(&mut self) -> Result<(), HyperbytedbError> { + let path = self._tmpdir.path().join("wal"); + let scratch = self._tmpdir.path().join("wal-scratch"); + std::fs::create_dir_all(&scratch)?; + self.rebuild_over(Arc::new(RocksDbWal::open(scratch)?)); + self.rebuild_over(Arc::new(RocksDbWal::open(path)?)); + Ok(()) + } + + fn rebuild_over(&mut self, wal: Arc) { + self.wal = wal.clone(); + self.query_service = Arc::new(QueryServiceImpl::new( + self.query_port.clone(), + self.metadata.clone(), + wal.clone(), + 30, + self.points_sink.clone(), + )); + self.ingestion = + IngestionServiceImpl::new(wal.clone(), self.metadata.clone(), 100_000, 10_000, 0); + self.flush_service = Arc::new(FlushServiceImpl::new(wal, 0, self.points_sink.clone())); + } +} + impl TestContext { /// Create a TestContext that uses chDB for queries. /// Fails if chDB is not available.