diff --git a/src/event/mod.rs b/src/event/mod.rs index 4baa8f8c7..1d04a0802 100644 --- a/src/event/mod.rs +++ b/src/event/mod.rs @@ -85,8 +85,9 @@ impl Event { key.push_str(&format!("&{k}={v}")); } } - - let stream = PARSEABLE.get_or_create_stream(&self.stream_name, &self.tenant_id); + + let stream = PARSEABLE.get_stream(&self.stream_name, &self.tenant_id)?; + let _ingestion_guard = stream.ingestion_guard()?; if self.is_first_event { commit_schema(&self.stream_name, self.rb.schema(), &self.tenant_id)?; @@ -132,7 +133,7 @@ impl Event { let key = get_schema_key(&self.rb.schema().fields); PARSEABLE - .get_or_create_stream(&self.stream_name, &self.tenant_id) + .get_stream(&self.stream_name, &self.tenant_id)? .push( &key, &self.rb, @@ -180,14 +181,18 @@ pub fn commit_schema( } pub mod error { - - use crate::{parseable::StagingError, storage::ObjectStorageError}; - + use crate::{ + parseable::{StagingError, StreamNotFound}, + storage::ObjectStorageError, + }; #[derive(Debug, thiserror::Error)] + pub enum EventError { #[error("Staging Failed: {0}")] Staging(#[from] StagingError), #[error("ObjectStorage Error: {0}")] ObjectStorage(#[from] ObjectStorageError), + #[error(transparent)] + StreamNotFound(#[from] StreamNotFound), } } diff --git a/src/handlers/http/ingest.rs b/src/handlers/http/ingest.rs index 18f496dd0..ef96e5fb8 100644 --- a/src/handlers/http/ingest.rs +++ b/src/handlers/http/ingest.rs @@ -572,6 +572,10 @@ impl actix_web::ResponseError for PostError { | CreateStream(CreateStreamError::StreamNameValidation(_)) | OtelNotSupported(_) => StatusCode::BAD_REQUEST, + Event(EventError::Staging(crate::parseable::StagingError::StreamDeleting(_))) => { + StatusCode::CONFLICT + } + Event(_) | CreateStream(_) | CustomError(_) @@ -619,6 +623,35 @@ mod tests { metadata::SchemaVersion, }; + #[test] + fn event_staging_deleting_returns_conflict() { + use actix_web::{ResponseError, http::StatusCode}; + + let error = super::PostError::Event(crate::event::error::EventError::Staging( + crate::parseable::StagingError::StreamDeleting("teststream".to_owned()), + )); + + assert_eq!(error.status_code(), StatusCode::CONFLICT); + assert_eq!(error.error_response().status(), StatusCode::CONFLICT); + } + + #[test] + fn event_staging_io_failure_returns_internal_server_error() { + use actix_web::{ResponseError, http::StatusCode}; + + let error = super::PostError::Event(crate::event::error::EventError::Staging( + crate::parseable::StagingError::ObjectStorage(std::io::Error::other( + "staging write failed", + )), + )); + + assert_eq!(error.status_code(), StatusCode::INTERNAL_SERVER_ERROR); + assert_eq!( + error.error_response().status(), + StatusCode::INTERNAL_SERVER_ERROR + ); + } + trait TestExt { fn as_int64_arr(&self) -> Option<&Int64Array>; fn as_float64_arr(&self) -> Option<&Float64Array>; diff --git a/src/handlers/http/logstream.rs b/src/handlers/http/logstream.rs index 70c8ab8cc..207db2cde 100644 --- a/src/handlers/http/logstream.rs +++ b/src/handlers/http/logstream.rs @@ -52,16 +52,13 @@ use chrono::Utc; use itertools::Itertools; use serde::Deserialize; use serde_json::{Value, json}; -use std::fs; use std::sync::Arc; use tokio::sync::Mutex; use tracing::{Instrument, warn}; -// Shared between put_stream and delete: without it, a concurrent create/ -// update could read is_deleting()=false right before delete() flips it and -// writes the tombstone, then go on to write fresh stream data that the -// background deletion job -- already committed to running by that point -- -// would sweep up from underneath it. +// Serializes dataset creation/update and deletion cleanup on this process. +// Background deletion and reconciliation also acquire this lock before local +// cleanup, preventing old cleanup from removing a recreated dataset's files. pub static CREATE_STREAM_LOCK: Mutex<()> = Mutex::const_new(()); pub async fn delete( @@ -69,18 +66,13 @@ pub async fn delete( logstream: Path, ) -> Result { let stream_name = logstream.into_inner(); - // Error out if stream doesn't exist in memory, or in the case of query node, in storage as well let tenant_id = get_tenant_id_from_request(&req); - // Fetched once, up front: every step below this point is either - // infallible or best-effort, so nothing after this line can bail out - // with "stream not found" partway through an already-durably-started - // deletion. + // Hold through local and hot-tier cleanup, not just the tombstone write. + // A job started by reconciliation must wait here too, so it cannot finish + // deletion and permit recreation while this handler still has cleanup left. + let _creation_guard = CREATE_STREAM_LOCK.lock().await; let stream = { - // Scoped to just this check-through-tombstone-write window: - // everything after is already guarded by is_deleting()/ - // is_tombstoned() checks on the read/write paths. - let _guard = CREATE_STREAM_LOCK.lock().await; if !PARSEABLE .check_or_load_stream(&stream_name, &tenant_id) @@ -109,10 +101,17 @@ pub async fn delete( let stream = PARSEABLE.get_stream(&stream_name, &tenant_id)?; - // Flip the in-memory guard before any `.await` point: check_or_load_stream's - // resident-stream fast path doesn't itself consult is_tombstoned, so a - // concurrent request on this node could otherwise slip through in the - // window between the tombstone becoming durable and this flag being set. + // Do not rewrite an existing deletion's tombstone: a failed rewrite + // would otherwise reach clear_deleting() and re-enable ingestion. + if stream.is_deleting() { + return Ok(( + format!("log stream {stream_name} deletion already in progress"), + StatusCode::ACCEPTED, + )); + } + + // Reject new local ingestion before awaiting the durable tombstone. + // Existing operations are drained by remove_staging() below. stream.mark_deleting(); let objectstore = PARSEABLE.storage.get_object_store(); @@ -152,8 +151,10 @@ pub async fn delete( ); } - // Delete from staging - if let Err(err) = fs::remove_dir_all(&stream.data_path) { + // Wait for participating ingestion/sync, finalize disk writers, then remove + // staging and reset stats under the stream's cleanup locks. The background + // job retries local cleanup before deleting object storage if this fails. + if let Err(err) = stream.remove_staging(&tenant_id) { warn!( "failed to delete local data for stream {} with error {err}. Clean {} manually", stream_name, @@ -173,10 +174,9 @@ pub async fn delete( warn!("failed to delete hot tier for stream {stream_name}: {e}"); } - // Scheduled only once every other cleanup step above has run, so the - // background job (which clears the tombstone on completion) can't race - // ahead of them and let a stream recreated under this name get swept up - // by leftover local/hot-tier cleanup that's still in flight. + // Schedule bulk deletion without waiting for it. The job acquires the same + // creation lock, so even one already scheduled by reconciliation cannot + // begin its protected cleanup until this handler releases the guard. spawn_stream_deletion(stream_name.clone(), tenant_id.clone()); Ok(( @@ -767,6 +767,13 @@ pub async fn get_stream_hot_tier_internal( return Err(StreamNotFound(stream_name.to_owned()).into()); } + if PARSEABLE + .get_stream(&stream_name, &tenant_id) + .is_ok_and(|stream| stream.is_deleting()) + { + return Err(StreamNotFound(stream_name.to_owned()).into()); + } + let Some(hot_tier_manager) = GLOBAL_HOTTIER.get() else { return Err(StreamError::HotTierNotEnabled(stream_name.to_owned())); }; diff --git a/src/handlers/http/modal/ingest/ingestor_logstream.rs b/src/handlers/http/modal/ingest/ingestor_logstream.rs index b11f5c50c..f76fa281f 100644 --- a/src/handlers/http/modal/ingest/ingestor_logstream.rs +++ b/src/handlers/http/modal/ingest/ingestor_logstream.rs @@ -16,8 +16,6 @@ * */ -use std::fs; - use actix_web::http::StatusCode; use actix_web::{ HttpRequest, Responder, @@ -35,11 +33,10 @@ use crate::{ utils::get_tenant_id_from_request, }; -// Shared between put_stream and delete: without it, a concurrent create/ -// update could read is_deleting()=false right before delete() flips it, -// then go on to write fresh stream data into a directory delete() is about -// to (or just did) remove. -static CREATE_STREAM_LOCK: Mutex<()> = Mutex::const_new(()); +// Serializes creation/update and local deletion cleanup on this ingestor. +// Reconciliation uses the same lock so old cleanup cannot remove files from +// a dataset recreated under the same name. +pub(crate) static CREATE_STREAM_LOCK: Mutex<()> = Mutex::const_new(()); pub async fn retention_cleanup( req: HttpRequest, @@ -82,19 +79,22 @@ pub async fn delete( ) -> Result { let stream_name = stream_name.into_inner(); let tenant_id = get_tenant_id_from_request(&req); + // The querier owns the tombstone and object-storage deletion. This handler + // handles its notification locally, holding off recreation through cleanup. + let _creation_guard = CREATE_STREAM_LOCK.lock().await; let stream_dir = { - let _guard = CREATE_STREAM_LOCK.lock().await; - // Delete from staging + // Reject new ingestion before waiting for active local operations. let stream_dir = PARSEABLE.get_stream(&stream_name, &tenant_id)?; stream_dir.mark_deleting(); stream_dir }; - // delete staging only for ingest server or standalone server - // else skip + // On ingest/standalone nodes, wait for participating ingestion and local + // sync, finalize writers, then remove staging and reset stats. Cleanup is + // synchronous here; reconciliation retries it before evicting a stale entry. if (PARSEABLE.options.mode == Mode::Ingest || PARSEABLE.options.mode == Mode::All) - && let Err(err) = fs::remove_dir_all(&stream_dir.data_path) + && let Err(err) = stream_dir.remove_staging(&tenant_id) { warn!( "failed to delete local data for stream {} with error {err}. Clean {} manually", @@ -102,13 +102,13 @@ pub async fn delete( stream_dir.data_path.to_string_lossy() ) } - - // Not removed from memory here: this node doesn't run the background - // deletion job, so it doesn't know when the underlying prefix is - // actually gone. The entry is reaped once `sync_all_streams` notices - // the tombstone has cleared (see its is_deleting()/is_tombstoned() - // self-heal check) -- until then, `is_deleting()` keeps rejecting - // ingestion for this stream with a clear "being deleted" error. + if let Err(err) = crate::stats::delete_stats(&stream_name, "json", &tenant_id) { + warn!("failed to clear stats for deleted stream {stream_name}: {err}"); + } + // Keep the old entry marked deleting until the querier finishes deleting + // object storage. Once the tombstone is gone, reconciliation or recreation + // self-healing cleans any remaining staging and evicts the entry. Evicting + // here would let requests lose the local guard while deletion is ongoing. Ok(( format!("log stream {stream_name} deletion started"), StatusCode::ACCEPTED, diff --git a/src/handlers/http/modal/query/querier_logstream.rs b/src/handlers/http/modal/query/querier_logstream.rs index 34fc1919e..a7853c5cd 100644 --- a/src/handlers/http/modal/query/querier_logstream.rs +++ b/src/handlers/http/modal/query/querier_logstream.rs @@ -17,7 +17,7 @@ */ use core::str; -use std::{collections::HashMap, fs}; +use std::collections::HashMap; use actix_web::http::StatusCode; use actix_web::{ @@ -29,6 +29,8 @@ use chrono::Utc; use tokio::sync::Mutex; use tracing::{error, warn}; +// Serializes creation/update and deletion cleanup on this querier. Background +// deletion and reconciliation use the same lock before local cleanup. pub static CREATE_STREAM_LOCK: Mutex<()> = Mutex::const_new(()); use crate::handlers::http::middleware::{CLUSTER_SECRET, CLUSTER_SECRET_HEADER}; @@ -65,25 +67,14 @@ pub async fn delete( ) -> Result { let stream_name = stream_name.into_inner(); let tenant_id = get_tenant_id_from_request(&req); + // Hold through ingestor notification and local/hot-tier cleanup. A background + // job must wait for this guard, so it cannot finish deletion and permit + // recreation while this handler still has cleanup left to perform. + let _creation_guard = CREATE_STREAM_LOCK.lock().await; - // Fetched once, up front: every step below this point is either - // infallible or best-effort, so nothing after this line can bail out - // with "stream not found" partway through an already-durably-started - // deletion. let stream = { - // Shared with put_stream: without it, a concurrent create/update on - // this node could read is_deleting()=false right before this - // handler flips it and writes the tombstone, then go on to write - // fresh stream data that the background deletion job -- already - // committed to running by that point -- would sweep up from - // underneath it. Scoped to just this check-through-tombstone-write - // window: everything after is already guarded by is_deleting()/ - // is_tombstoned() checks on the read/write paths. - let _guard = CREATE_STREAM_LOCK.lock().await; - - // if the stream not found in memory map, - //check if it exists in the storage - //create stream and schema from storage + // A querier may not have this dataset resident; try loading its metadata + // from object storage before treating it as missing. if !PARSEABLE.streams.contains(&stream_name, &tenant_id) && !PARSEABLE .create_stream_and_schema_from_storage(&stream_name, &tenant_id) @@ -115,10 +106,16 @@ pub async fn delete( let stream = PARSEABLE.get_stream(&stream_name, &tenant_id)?; - // Flip the in-memory guard before any `.await` point: check_or_load_stream's - // resident-stream fast path doesn't itself consult is_tombstoned, so a - // concurrent request on this node could otherwise slip through in the - // window between the tombstone becoming durable and this flag being set. + // Do not rewrite an existing deletion's tombstone: failure would reach + // clear_deleting() and incorrectly roll back another request's deletion. + if stream.is_deleting() { + return Ok(( + format!("log stream {stream_name} deletion already in progress"), + StatusCode::ACCEPTED, + )); + } + // Block new local operations before awaiting the durable tombstone. + // Ingestors receive their own local guard via the notification below. stream.mark_deleting(); let objectstore = PARSEABLE.storage.get_object_store(); @@ -158,16 +155,10 @@ pub async fn delete( ); } - // Best-effort: the tombstone is already durable and the stream is - // already flagged, so a fan-out failure must not turn an - // already-accepted deletion into an error response. An ingestor that - // misses this push doesn't self-heal on its own next sync tick (its - // local is_deleting() stays false, which is exactly what the resident- - // stream self-heal check keys off) -- recovery instead comes from - // sync_all_streams' separate tombstone-directory scan, which lists - // tombstones directly rather than depending on the flag already being - // set locally, at the cost of taking up to one sync interval rather - // than being immediate. + // Notify live ingestors to stop local ingestion and clean their staging. + // Failure is best-effort because deletion is already durable. An ingestor + // that misses notification can discover the marker through sync's tombstone + // directory scan while the tombstone remains present. let fanout_stream_name = stream_name.clone(); if let Err(e) = cluster::for_each_live_node(&tenant_id, move |node| { let url = format!( @@ -183,7 +174,9 @@ pub async fn delete( warn!("failed to notify all ingestors of deletion of {stream_name}: {e}"); } - if let Err(err) = fs::remove_dir_all(&stream.data_path) { + // Drain participating local work and finalize writers before removing this + // querier's staging. The background job retries local cleanup if it fails. + if let Err(err) = stream.remove_staging(&tenant_id) { warn!( "failed to delete local data for stream {} with error {err}. Clean {} manually", stream_name, @@ -191,6 +184,7 @@ pub async fn delete( ) } + // Hot-tier cleanup is best-effort; failure does not undo a durable deletion. if let Some(hot_tier_manager) = GLOBAL_HOTTIER.get() && hot_tier_manager.check_stream_hot_tier_exists(&stream_name, &tenant_id) && let Err(e) = hot_tier_manager @@ -200,10 +194,9 @@ pub async fn delete( warn!("failed to delete hot tier for stream {stream_name}: {e}"); } - // Scheduled only once every other cleanup step above has run, so the - // background job (which clears the tombstone on completion) can't race - // ahead of them and let a stream recreated under this name get swept up - // by leftover fan-out/local/hot-tier cleanup that's still in flight. + // Schedule bulk object-storage deletion without waiting for completion. + // Jobs also acquire the creation lock, including those already scheduled by + // reconciliation, so their protected cleanup waits until this handler exits. spawn_stream_deletion(stream_name.clone(), tenant_id.clone()); Ok(( diff --git a/src/parseable/mod.rs b/src/parseable/mod.rs index fff616a1e..fe2ebc14b 100644 --- a/src/parseable/mod.rs +++ b/src/parseable/mod.rs @@ -687,34 +687,24 @@ impl Parseable { Ok(()) } - /// Rejects a create/update call blocked by an in-progress or stale - /// deletion, self-healing a stale `is_deleting()` flag once its - /// tombstone is confirmed gone. Returns the (possibly corrected) value - /// of `stream_in_memory_dont_update` for the caller's subsequent - /// "already exists" check. + /// Rejects creation/update while a deletion tombstone exists. Once it is + /// gone, cleans staging and evicts a stale deleting entry before proceeding. + /// Returns the corrected value for the caller's "already exists" check. + /// Callers must hold their mode's creation lock through cleanup and creation. async fn reject_if_stream_deleting( &self, stream_name: &str, tenant_id: &Option, stream_in_memory_dont_update: bool, ) -> Result { - // A stream still resident with is_deleting()=true is functionally - // gone (reads/writes are already rejected elsewhere), but its entry - // isn't removed from memory until the background deletion job - // finishes -- surface that distinctly rather than telling the - // caller it "already exists", which reads as if nothing were wrong. + // A resident entry may outlive deletion elsewhere, especially on an + // ingestor. Distinguish an active deletion from an entry awaiting eviction. if stream_in_memory_dont_update && let Ok(stream) = self.get_stream(stream_name, tenant_id) && stream.is_deleting() { - // The flag can be stale on a node that never runs the - // background deletion job itself (e.g. an ingestor: see its - // `delete()` handler) -- it only self-heals once - // `sync_all_streams` next notices the tombstone is gone, which - // can lag well behind a client recreating the stream right - // away. Re-check the durable tombstone before trusting the - // in-memory flag, and clear it here instead of blocking - // creation for up to a full sync interval. + // Recheck the durable marker instead of waiting for the next sync + // tick to evict an old entry. A present tombstone still blocks reuse. if is_tombstoned( self.storage.get_object_store().as_ref(), stream_name, @@ -727,29 +717,22 @@ impl Parseable { status: StatusCode::CONFLICT, }); } - stream.clear_deleting(); - - // The stale entry itself (data path, schema, old metadata) must - // go too, not just the flag -- otherwise the "already exists" - // check just below still trips on it, and get_or_create's - // resident-entry short-circuit would hand back this same stale - // Arc instead of actually recreating it. Dropping it - // here makes this indistinguishable from a stream that was - // never resident in the first place. + // Keep the old object marked deleting while draining local work and + // removing staging. On failure, retain the entry and reject recreation + // so a replacement cannot inherit old schema/data files. + stream.remove_staging(tenant_id).map_err(|err| StreamError::Custom { + msg: format!("Failed to clean staging for deleting logstream {stream_name}: {err}"), + status: StatusCode::INTERNAL_SERVER_ERROR, + })?; + // Evict rather than clear the flag: outstanding Arc handles + // must remain unable to ingest. Returning false lets creation build + // a fresh entry instead of reusing the old schema and metadata. self.streams.delete(stream_name, tenant_id); return Ok(false); } - // A tombstoned-but-not-yet-purged stream must be rejected the same - // way even when it isn't resident in memory on this node yet (e.g. a - // query node before restart-recovery has resumed it, or a node that - // never loaded it in the first place). create_stream_and_schema_from_storage - // below already checks this internally and returns Ok(false) for a - // tombstoned stream, but that's indistinguishable from "doesn't - // exist" to its caller -- without this explicit check, the client - // could recreate the name while the background deletion job is - // still sweeping its prefix, and that job would delete the freshly - // created data too. + // Check the tombstone even without an "already exists" result. Missing + // local metadata does not authorize reuse while object deletion is active. if !stream_in_memory_dont_update { if is_tombstoned( self.storage.get_object_store().as_ref(), @@ -764,16 +747,18 @@ impl Parseable { }); } - // Self-heal a stale is_deleting flag on this path too (e.g. an - // ingestor's resident copy, flagged by the delete handler's - // fan-out push, whose tombstone has since cleared without - // sync_all_streams having noticed yet) -- otherwise this update - // succeeds but ingestion keeps being rejected here for up to - // another sync interval regardless. + // The update path can also encounter a resident deleting entry. + // Apply the same cleanup-before-eviction rule; never reactivate the + // old object or allow leftover staging to reach its replacement. if let Ok(stream) = self.get_stream(stream_name, tenant_id) && stream.is_deleting() { - stream.clear_deleting(); + stream.remove_staging(tenant_id).map_err(|err| StreamError::Custom { + msg: format!( + "Failed to clean staging for deleting logstream {stream_name}: {err}" + ), + status: StatusCode::INTERNAL_SERVER_ERROR, + })?; self.streams.delete(stream_name, tenant_id); } } diff --git a/src/parseable/staging/mod.rs b/src/parseable/staging/mod.rs index 823f95c45..fc5a266ac 100644 --- a/src/parseable/staging/mod.rs +++ b/src/parseable/staging/mod.rs @@ -40,6 +40,8 @@ pub enum StagingError { TenantNotFound(#[from] TenantNotFound), #[error("{0}")] PoisonError(#[from] PoisonError), + #[error("Dataset {0} is being deleted")] + StreamDeleting(String), #[error("JSON Error {0}")] Json(#[from] serde_json::Error), } diff --git a/src/parseable/streams.rs b/src/parseable/streams.rs index b19075d15..2b1306a25 100644 --- a/src/parseable/streams.rs +++ b/src/parseable/streams.rs @@ -381,6 +381,9 @@ pub struct Stream { pub writer: Mutex, schema_writer: Mutex<()>, pub ingestor_id: Option, + // Ingestion/local sync hold read access; staging cleanup holds write access. + // Acquire before schema_writer or writer when an operation needs both. + staging_activity: RwLock<()>, } /// Startup conversion owns this immutable processing-file snapshot. Periodic @@ -655,6 +658,20 @@ impl ArrowFileConversionOutcome { impl StartupSyncPlan { pub(crate) fn execute(self) -> Result<(), StagingError> { + // Preparation and execution are separate: reacquire activity access and + // recheck deletion before using the captured files. Hold through schema + // finalization so cleanup cannot remove staging during conversion. + let _staging_activity = self.stream.staging_activity.read().map_err(|err| { + StagingError::PoisonError(PoisonError::new(format!( + "Staging activity lock poisoned during startup conversion for {} - {}", + self.stream.stream_name, err + ))) + })?; + + if self.stream.is_deleting() { + return Ok(()); + } + let time_partition = self.stream.get_time_partition(); let custom_partition = self.stream.get_custom_partition(); let outcome = self.stream.convert_arrow_file_groups_to_parquet( @@ -687,6 +704,7 @@ impl Stream { writer: Mutex::new(Writer::default()), schema_writer: Mutex::new(()), ingestor_id, + staging_activity: RwLock::new(()), }) } @@ -724,6 +742,11 @@ impl Stream { } } }; + // Recheck after waiting for the writer lock: an earlier validation may + // predate deletion. Cleanup takes this same lock before removing files. + if self.is_deleting() { + return Err(StagingError::StreamDeleting(self.stream_name.clone())); + } if self.options.mode != Mode::Query || stream_type == StreamType::Internal { let filename = self.filename_by_partition(schema_key, parsed_timestamp, custom_partition_values); @@ -1101,7 +1124,12 @@ impl Stream { ))) })?; - // schema is dynamic, read from staging and merge if present + if self.is_deleting() { + return Err(StagingError::StreamDeleting(self.stream_name.clone())); + } + + // The deletion check above runs under the schema lock shared with + // cleanup, preventing a late schema write from recreating staging. fs::create_dir_all(&self.data_path)?; // need to add something before .schema to make the file have an extension of type `schema` @@ -1167,24 +1195,22 @@ impl Stream { #[cfg_attr(feature = "hotpath", hotpath::measure)] pub fn flush(&self, forced: bool) -> Result<(), StagingError> { let _span = info_span!("flush", stream_name = %self.stream_name, forced).entered(); - // Swap out stale writers under the lock, drop them after releasing it. - // DiskWriter::Drop does I/O (IPC finish + file rename) so dropping - // outside the lock avoids blocking concurrent push() calls. - let stale_writers = { - let mut writer = self.writer.lock().map_err(|poisoned| { - StagingError::PoisonError(PoisonError::new(format!( - "Writer lock poisoned while flushing data for stream {} - {}", - self.stream_name, poisoned - ))) - })?; - if let Some(mem) = writer.mem.as_mut() { - mem.clear(); - } - writer.take_flushable_disk(forced) - }; - // DiskWriter::Drop I/O happens here, outside the lock - drop(stale_writers); + let mut writer = self.writer.lock().map_err(|poisoned| { + StagingError::PoisonError(PoisonError::new(format!( + "Writer lock poisoned while flushing data for stream {} - {}", + self.stream_name, poisoned + ))) + })?; + + if let Some(mem) = writer.mem.as_mut() { + mem.clear(); + } + + // Finalize and rename files while holding the writer lock so staging + // deletion cannot remove them before DiskWriter::drop completes. + drop(writer.take_flushable_disk(forced)); + Ok(()) } @@ -2287,6 +2313,52 @@ impl Stream { self.cleanup_arrow_files_and_dir(arrow_files, tenant_id); } + /// Drains participating local work, finalizes disk writers, and removes + /// staging and dataset stats. The stream must already be marked deleting; + /// callers must prevent recreation while cleaning and evicting this entry. + /// Does not delete object storage or evict the entry itself. + pub fn remove_staging(&self, tenant_id: &Option) -> Result<(), StagingError> { + // Keep the order activity -> schema -> writer. Exclusive activity access + // waits for ingestion (including stats updates) and local conversion. + let _staging_activity = self.staging_activity.write().map_err(|err| { + StagingError::PoisonError(PoisonError::new(format!( + "Staging activity lock poisoned while deleting stream {} - {}", + self.stream_name, err + ))) + })?; + let _schema_writer = self.schema_writer.lock().map_err(|poisoned| { + StagingError::PoisonError(PoisonError::new(format!( + "Schema writer lock poisoned while deleting stream {} - {}", + self.stream_name, poisoned + ))) + })?; + let mut writer = self.writer.lock().map_err(|poisoned| { + StagingError::PoisonError(PoisonError::new(format!( + "Writer lock poisoned while deleting stream {} - {}", + self.stream_name, poisoned + ))) + })?; + // Disk writers finish and rename their files when dropped. + drop(writer.take_flushable_disk(true)); + + match fs::remove_dir_all(&self.data_path) { + Ok(()) => {} + Err(err) if err.kind() == std::io::ErrorKind::NotFound => {} + Err(err) => return Err(err.into()), + } + + // Reset under exclusive activity access so an old Event::process cannot + // update counters after cleanup has reset them. + if let Err(err) = crate::stats::delete_stats(&self.stream_name, "json", tenant_id) { + warn!( + "failed to clear stats for deleted stream {}: {err}", + self.stream_name + ); + } + + Ok(()) + } + pub fn updated_schema(&self, current_schema: Schema) -> Schema { let staging_files = self.arrow_files(); let record_reader = MergedReverseRecordReader::try_new(&staging_files); @@ -2439,20 +2511,34 @@ impl Stream { self.metadata.read().expect(LOCK_EXPECT).hot_tier_enabled } - /// Marks this stream as being deleted. Once set, this flag is never - /// cleared for this in-memory entry — a deletion in progress runs to - /// completion (or is resumed on restart), it is never cancelled. + /// Blocks new ingestion on this object. After a durable deletion starts, + /// keep the flag set even after eviction so outstanding handles stay blocked. + /// Only roll it back if persisting the deletion tombstone fails. pub fn mark_deleting(&self) { self.metadata.write().expect(LOCK_EXPECT).deleting = true; } + /// Holds shared activity access through an event's writes and stats updates. + /// Check deletion after acquiring access; do not reacquire this activity lock + /// in nested calls, as a waiting cleanup writer can make that deadlock. + pub(crate) fn ingestion_guard( + &self, + ) -> Result, StagingError> { + let guard = self.staging_activity.read().map_err(|err| { + StagingError::PoisonError(PoisonError::new(format!( + "Staging activity lock poisoned during ingestion for {} - {}", + self.stream_name, err + ))) + })?; + + if self.is_deleting() { + return Err(StagingError::StreamDeleting(self.stream_name.clone())); + } - /// Undoes a `mark_deleting()` call, in one of two cases: the tombstone - /// write that would have made it durable just failed, or the caller has - /// independently confirmed (via `is_tombstoned()`) that the tombstone is - /// already gone and this flag is just a stale leftover on a node that - /// doesn't run the background deletion job itself. Unlike - /// `mark_deleting()`, this is not part of the monotonic contract, and - /// must never be called while the tombstone still exists in storage. + Ok(guard) + } + /// Rolls back this request's deletion flag when its tombstone write fails. + /// Do not use to reactivate an old entry after completed deletion: clean and + /// evict it instead. Never clear another request's ongoing deletion flag. pub fn clear_deleting(&self) { self.metadata.write().expect(LOCK_EXPECT).deleting = false; } @@ -2692,6 +2778,21 @@ impl Stream { self: &Arc, tenant_id: Option, ) -> Result { + // Protect recovery, flushing, and the file snapshot from staging cleanup. + // The returned plan reacquires access when executed; no guard spans tasks. + let _staging_activity = self.staging_activity.read().map_err(|err| { + StagingError::PoisonError(PoisonError::new(format!( + "Staging activity lock poisoned for stream {} - {}", + self.stream_name, err + ))) + })?; + if self.is_deleting() { + return Ok(StartupSyncPlan { + stream: Arc::clone(self), + tenant_id, + staging_files: Vec::new(), + }); + } self.recover_orphan_part_files(); let start_flush = Instant::now(); @@ -2731,6 +2832,17 @@ impl Stream { shutdown_signal: bool, tenant_id: &Option, ) -> Result<(), StagingError> { + // Cover the entire local sync, not just flush: conversion and schema + // finalization also touch staging after the writer mutex is released. + let _staging_activity = self.staging_activity.read().map_err(|err| { + StagingError::PoisonError(PoisonError::new(format!( + "Staging activity lock poisoned for stream {} - {}", + self.stream_name, err + ))) + })?; + if self.is_deleting() { + return Ok(()); + } // On init, recover any orphaned .part files from previous interrupted runs if init_signal { self.recover_orphan_part_files(); diff --git a/src/storage/object_storage.rs b/src/storage/object_storage.rs index f60695c6e..b1456c56a 100644 --- a/src/storage/object_storage.rs +++ b/src/storage/object_storage.rs @@ -42,7 +42,8 @@ use arrow_schema::Schema; use async_trait::async_trait; use bytes::Bytes; use chrono::{DateTime, Utc}; -use dashmap::{DashMap, DashSet, mapref::entry::Entry}; +use dashmap::{DashMap, DashSet}; +use dashmap::mapref::entry::Entry; use datafusion::{datasource::listing::ListingTableUrl, execution::runtime_env::RuntimeEnvBuilder}; use itertools::Itertools; use object_store::ListResult; @@ -1071,7 +1072,7 @@ pub trait ObjectStorage: Debug + Send + Sync + 'static { info!("Starting object_store_sync for stream- {stream_name}"); - let stream = PARSEABLE.get_or_create_stream(stream_name, &tenant_id); + let stream = PARSEABLE.get_stream(stream_name, &tenant_id)?; let upload_context = UploadContext::new(stream); // Process parquet files concurrently and collect results @@ -1426,6 +1427,51 @@ pub fn spawn_stream_deletion(stream_name: String, tenant_id: Option) { let _guard = StreamDeletionGuard(Some(key.clone())); let (tenant_id, stream_name) = &key; let storage = PARSEABLE.storage.get_object_store(); + { + let creation_lock = if PARSEABLE.options.mode == Mode::Query { + &crate::handlers::http::modal::query::querier_logstream::CREATE_STREAM_LOCK + } else { + &crate::handlers::http::logstream::CREATE_STREAM_LOCK + }; + let _creation_guard = creation_lock.lock().await; + + match is_tombstoned(storage.as_ref(), stream_name, tenant_id).await { + Ok(true) => {} + Ok(false) => return, + Err(err) => { + warn!("failed to check deletion tombstone for {stream_name}: {err}"); + return; + } + } + + let cleanup: Result<(), crate::parseable::StagingError> = + match PARSEABLE.get_stream(stream_name, tenant_id) { + Ok(stream) => { + stream.mark_deleting(); + stream.remove_staging(tenant_id) + } + Err(_) => { + // Recovery may have no resident Stream to clean through. + let path = PARSEABLE + .options + .local_stream_data_path(stream_name, tenant_id); + + match std::fs::remove_dir_all(path) { + Ok(()) => Ok(()), + Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(err) => Err(err.into()), + } + } + }; + + if let Err(err) = cleanup { + warn!( + "failed to clean staging for deleting stream {stream_name}: \ + {err}; retaining tombstone for retry" + ); + return; + } + } match storage.delete_stream(stream_name, tenant_id).await { Ok(()) => { // Clear the map entry and stats *before* the tombstone, not @@ -1496,15 +1542,31 @@ fn spawn_deleting_stream_reconciliation( } } Ok(false) if !is_deletion_owner => { - // Deletion already finished elsewhere and the tombstone - // is gone, but this node's resident entry was never - // dropped -- e.g. an ingestor, which doesn't run the - // background deletion job itself. Reap it so a stream - // recreated under the same name doesn't inherit a stuck - // deleting=true state. - PARSEABLE - .streams - .delete_if_still_deleting(&stream_name, &tenant_id); + let _creation_guard = + crate::handlers::http::modal::ingest::ingestor_logstream::CREATE_STREAM_LOCK + .lock() + .await; + + if let Ok(stream) = PARSEABLE.get_stream(&stream_name, &tenant_id) + && stream.is_deleting() + { + match stream.remove_staging(&tenant_id) { + Ok(()) => { + if let Err(err) = stats::delete_stats(&stream_name, "json", &tenant_id) { + warn!("failed to clear stats for deleted stream {stream_name}: {err}"); + } + PARSEABLE + .streams + .delete_if_still_deleting(&stream_name, &tenant_id); + } + Err(err) => { + warn!( + "failed to clean staging for deleting stream \ + {stream_name}, retrying next sync interval: {err}" + ); + } + } + } } Ok(false) => { // On the owning node, an absent tombstone can also just @@ -1578,6 +1640,15 @@ async fn reconcile_one_tombstoned_stream( stream_name: String, is_deletion_owner: bool, ) { + let creation_lock = match PARSEABLE.options.mode { + Mode::Ingest => { + &crate::handlers::http::modal::ingest::ingestor_logstream::CREATE_STREAM_LOCK + } + Mode::Query => &crate::handlers::http::modal::query::querier_logstream::CREATE_STREAM_LOCK, + _ => &crate::handlers::http::logstream::CREATE_STREAM_LOCK, + }; + + let _creation_guard = creation_lock.lock().await; match PARSEABLE.get_stream(&stream_name, tenant_id) { Ok(stream) if !stream.is_deleting() => { // list_tombstoned_streams is a snapshot -- by the time we get @@ -1588,7 +1659,16 @@ async fn reconcile_one_tombstoned_stream( // stream can't be flagged deleting based on stale snapshot data // with no tombstone left to ever clear it again. match is_tombstoned(object_store, &stream_name, tenant_id).await { - Ok(true) => stream.mark_deleting(), + Ok(true) => { + stream.mark_deleting(); + + if let Err(err) = stream.remove_staging(tenant_id) { + warn!( + "failed to remove local staging for deleting stream \ + {stream_name}: {err}" + ); + } + } Ok(false) => {} // A real error here (as opposed to "no tombstone") is not // evidence the tombstone is gone -- folding it into Ok(false)