Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
6443b18
Add tombstone/deleting safety net for stream deletion (#1763)
prabhaks Aug 26, 2026
690410a
Nest tombstone markers under a per-stream directory so they're discov…
prabhaks Aug 26, 2026
4eafc27
Make stream deletion asynchronous, resumable across restarts (#1763)
prabhaks Aug 26, 2026
094389a
Address CodeRabbit review: preserve deleting flag, tighten tombstone …
prabhaks Aug 26, 2026
eeb367f
Merge branch 'fix/1763-stream-deletion-safety-net' into fix/1763-asyn…
prabhaks Aug 26, 2026
a3037b5
Flip the deleting flag before the tombstone write, not after
prabhaks Aug 26, 2026
e57e47d
Merge remote-tracking branch 'origin/main' into fix/1763-stream-delet…
prabhaks Sep 11, 2026
b2fa8f0
Merge branch 'fix/1763-stream-deletion-safety-net' into fix/1763-asyn…
prabhaks Sep 11, 2026
c7fc671
Merge remote-tracking branch 'origin/main' into fix/1763-async-stream…
prabhaks Sep 16, 2026
eba77ac
Address CodeRabbit review feedback on #1770, switch MinIO test image …
prabhaks Sep 16, 2026
b0b0f65
Fix stale is_deleting flag blocking recreation, serialize delete vs c…
prabhaks Sep 16, 2026
04fc9e7
fix: stale is_deleting self-heal didn't clear the "already exists" check
prabhaks Sep 16, 2026
4a719ce
Add missing is_deleting() guards and reconcile stuck tombstones
prabhaks Sep 17, 2026
2b5e081
Close remaining resurrection/race gaps found in review, fix stale com…
prabhaks Sep 17, 2026
8893e25
Address CodeRabbit findings: stats race, error swallowing, stale snap…
prabhaks Sep 17, 2026
c007bda
fix: don't swallow errors from live tombstone recheck in sync_all_str…
prabhaks Sep 17, 2026
186947c
refactor: split sync_all_streams reconciliation into helper functions
prabhaks Sep 18, 2026
4403a62
fix: close two self-review gaps in standalone delete and update self-…
prabhaks Sep 18, 2026
e502026
fix: prevent dataset resurrection and staging races during deletion
AadishJ Nov 9, 2026
0753207
Merge remote-tracking branch 'upstream/main' into fix/async-deletion-…
AadishJ Nov 11, 2026
1d5551b
fix: merge issues
AadishJ Nov 11, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 11 additions & 6 deletions src/event/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)?;
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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),
}
}
33 changes: 33 additions & 0 deletions src/handlers/http/ingest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(_)
Expand Down Expand Up @@ -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>;
Expand Down
57 changes: 32 additions & 25 deletions src/handlers/http/logstream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,35 +52,27 @@ 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(
req: HttpRequest,
logstream: Path<String>,
) -> Result<impl Responder, StreamError> {
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)
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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,
Expand All @@ -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((
Expand Down Expand Up @@ -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());
}
Comment on lines +770 to +775

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Hot-tier reads repeat a check

get_stream_hot_tier_internal already performs this exact deletion check immediately above. The added block repeats the stream lookup and metadata lock without protecting the later hot-tier read from concurrent deletion. Remove the repeated block so there is one guard to maintain.

Suggested change
if PARSEABLE
.get_stream(&stream_name, &tenant_id)
.is_ok_and(|stream| stream.is_deleting())
{
return Err(StreamNotFound(stream_name.to_owned()).into());
}
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/handlers/http/logstream.rs
Line: 770-775

Comment:
**Hot-tier reads repeat a check**

`get_stream_hot_tier_internal` already performs this exact deletion check immediately above. The added block repeats the stream lookup and metadata lock without protecting the later hot-tier read from concurrent deletion. Remove the repeated block so there is one guard to maintain.

```suggestion

```

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Fix in Codex Fix in Claude Code


let Some(hot_tier_manager) = GLOBAL_HOTTIER.get() else {
return Err(StreamError::HotTierNotEnabled(stream_name.to_owned()));
};
Expand Down
38 changes: 19 additions & 19 deletions src/handlers/http/modal/ingest/ingestor_logstream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@
*
*/

use std::fs;

use actix_web::http::StatusCode;
use actix_web::{
HttpRequest, Responder,
Expand All @@ -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,
Expand Down Expand Up @@ -82,33 +79,36 @@ pub async fn delete(
) -> Result<impl Responder, StreamError> {
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",
stream_name,
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,
Expand Down
67 changes: 30 additions & 37 deletions src/handlers/http/modal/query/querier_logstream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
*/

use core::str;
use std::{collections::HashMap, fs};
use std::collections::HashMap;

use actix_web::http::StatusCode;
use actix_web::{
Expand All @@ -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};
Expand Down Expand Up @@ -65,25 +67,14 @@ pub async fn delete(
) -> Result<impl Responder, StreamError> {
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)
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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!(
Expand All @@ -183,14 +174,17 @@ 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,
stream.data_path.to_string_lossy()
)
}

// 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
Expand All @@ -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((
Expand Down
Loading
Loading