Skip to content

Commit 4eafc27

Browse files
committed
Make stream deletion asynchronous, resumable across restarts (#1763)
DELETE /logstream/{stream} now writes a tombstone, notifies ingestors, and returns 202 Accepted immediately instead of blocking on the full recursive object-store delete. The actual deletion runs in a deduplicated background task, resumes automatically if the node crashes or restarts mid-delete (via the tombstone left by PR #1768's safety net), and self-heals nodes that missed the live notification. Only the node that receives the original DELETE request ever runs the physical delete; ingestors flag the stream as deleting and wait for the tombstone to clear, so a large deletion doesn't get redundantly re-run by every node in the cluster. list_streams() on the local filesystem backend is also fixed to treat a stream mid-deletion as absent rather than erroring out the whole listing.
1 parent 690410a commit 4eafc27

7 files changed

Lines changed: 417 additions & 62 deletions

File tree

‎src/handlers/http/logstream.rs‎

Lines changed: 47 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,10 @@ use crate::rbac::Users;
2828
use crate::rbac::role::Action;
2929
use crate::stats::{Stats, event_labels_date, storage_size_labels_date};
3030
use crate::storage::retention::Retention;
31-
use crate::storage::{ObjectStoreFormat, StreamInfo, StreamType};
31+
use crate::storage::{
32+
ObjectStoreFormat, StreamInfo, StreamType,
33+
object_storage::{spawn_stream_deletion, stream_json_path, to_bytes, tombstone_path},
34+
};
3235
use crate::tenants::TenantNotFound;
3336
use crate::utils::actix::extract_session_key_from_req;
3437
use crate::utils::get_tenant_id_from_request;
@@ -63,17 +66,51 @@ pub async fn delete(
6366
return Err(StreamNotFound(stream_name).into());
6467
}
6568

69+
// Fetched once, up front: every step below this point is either
70+
// infallible or best-effort, so nothing after this line can bail out
71+
// with "stream not found" partway through an already-durably-started
72+
// deletion.
73+
let stream = PARSEABLE.get_stream(&stream_name, &tenant_id)?;
74+
6675
let objectstore = PARSEABLE.storage.get_object_store();
6776

68-
// Delete from storage
69-
objectstore.delete_stream(&stream_name, &tenant_id).await?;
77+
// Durable marker first: if the process crashes anywhere after this
78+
// point, restart-recovery resumes the deletion instead of silently
79+
// leaving the stream half-deleted with no record of it.
80+
objectstore
81+
.put_object(
82+
&tombstone_path(&stream_name, &tenant_id),
83+
to_bytes(&()),
84+
&tenant_id,
85+
)
86+
.await?;
87+
88+
// Best-effort: makes the stream vanish from listings almost
89+
// immediately. Not fatal if it fails -- is_deleting()/is_tombstoned()
90+
// checks already block reads and writes regardless of whether this file
91+
// is gone yet.
92+
if let Err(e) = objectstore
93+
.delete_object(&stream_json_path(&stream_name, &tenant_id), &tenant_id)
94+
.await
95+
{
96+
warn!(
97+
"failed to eagerly delete stream.json for {stream_name}, will be removed with the rest of the prefix: {e}"
98+
);
99+
}
100+
101+
stream.mark_deleting();
102+
// Scheduled immediately once the stream is durably tombstoned and
103+
// flagged locally, before any of the remaining best-effort steps --
104+
// none of them are allowed to leave the deletion itself unscheduled if
105+
// they fail.
106+
spawn_stream_deletion(stream_name.clone(), tenant_id.clone());
107+
70108
// Delete from staging
71-
let stream_dir = PARSEABLE.get_or_create_stream(&stream_name, &tenant_id);
72-
if let Err(err) = fs::remove_dir_all(&stream_dir.data_path) {
109+
if let Err(err) = fs::remove_dir_all(&stream.data_path) {
73110
warn!(
74111
"failed to delete local data for stream {} with error {err}. Clean {} manually",
75112
stream_name,
76-
stream_dir.data_path.to_string_lossy()
113+
stream.data_path.to_string_lossy()
77114
)
78115
}
79116

@@ -85,12 +122,10 @@ pub async fn delete(
85122
.await?;
86123
}
87124

88-
// Delete from memory
89-
PARSEABLE.streams.delete(&stream_name, &tenant_id);
90-
stats::delete_stats(&stream_name, "json", &tenant_id)
91-
.unwrap_or_else(|e| warn!("failed to delete stats for stream {}: {:?}", stream_name, e));
92-
93-
Ok((format!("log stream {stream_name} deleted"), StatusCode::OK))
125+
Ok((
126+
format!("log stream {stream_name} deletion started"),
127+
StatusCode::ACCEPTED,
128+
))
94129
}
95130

96131
pub async fn list(req: HttpRequest) -> Result<impl Responder, StreamError> {

‎src/handlers/http/modal/ingest/ingestor_logstream.rs‎

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,6 @@ use crate::{
3131
catalog::remove_manifest_from_snapshot,
3232
handlers::http::logstream::error::StreamError,
3333
parseable::{PARSEABLE, StreamNotFound},
34-
stats,
3534
utils::get_tenant_id_from_request,
3635
};
3736

@@ -78,6 +77,7 @@ pub async fn delete(
7877
let tenant_id = get_tenant_id_from_request(&req);
7978
// Delete from staging
8079
let stream_dir = PARSEABLE.get_stream(&stream_name, &tenant_id)?;
80+
stream_dir.mark_deleting();
8181

8282
// delete staging only for ingest server or standalone server
8383
// else skip
@@ -91,12 +91,16 @@ pub async fn delete(
9191
)
9292
}
9393

94-
// Delete from memory
95-
PARSEABLE.streams.delete(&stream_name, &tenant_id);
96-
stats::delete_stats(&stream_name, "json", &tenant_id)
97-
.unwrap_or_else(|e| warn!("failed to delete stats for stream {}: {:?}", stream_name, e));
98-
99-
Ok((format!("log stream {stream_name} deleted"), StatusCode::OK))
94+
// Not removed from memory here: this node doesn't run the background
95+
// deletion job, so it doesn't know when the underlying prefix is
96+
// actually gone. The entry is reaped once `sync_all_streams` notices
97+
// the tombstone has cleared (see its is_deleting()/is_tombstoned()
98+
// self-heal check) -- until then, `is_deleting()` keeps rejecting
99+
// ingestion for this stream with a clear "being deleted" error.
100+
Ok((
101+
format!("log stream {stream_name} deletion started"),
102+
StatusCode::OK,
103+
))
100104
}
101105

102106
pub async fn put_stream(

‎src/handlers/http/modal/query/querier_logstream.rs‎

Lines changed: 60 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -45,12 +45,14 @@ use crate::{
4545
utils::{IngestionStats, QueriedStats, StorageStats, merge_queried_stats},
4646
},
4747
logstream::error::StreamError,
48-
modal::{NodeMetadata, NodeType},
4948
},
5049
},
5150
parseable::{PARSEABLE, StreamNotFound},
5251
stats,
53-
storage::{ObjectStoreFormat, StreamType},
52+
storage::{
53+
ObjectStoreFormat, StreamType,
54+
object_storage::{spawn_stream_deletion, stream_json_path, to_bytes, tombstone_path},
55+
},
5456
utils::get_tenant_id_from_request,
5557
};
5658
const STATS_DATE_QUERY_PARAM: &str = "date";
@@ -73,52 +75,77 @@ pub async fn delete(
7375
return Err(StreamNotFound(stream_name.clone()).into());
7476
}
7577

78+
// Fetched once, up front: every step below this point is either
79+
// infallible or best-effort, so nothing after this line can bail out
80+
// with "stream not found" partway through an already-durably-started
81+
// deletion.
82+
let stream = PARSEABLE.get_stream(&stream_name, &tenant_id)?;
83+
7684
let objectstore = PARSEABLE.storage.get_object_store();
77-
// Delete from storage
78-
objectstore.delete_stream(&stream_name, &tenant_id).await?;
79-
let stream_dir = PARSEABLE.get_or_create_stream(&stream_name, &tenant_id);
80-
if let Err(err) = fs::remove_dir_all(&stream_dir.data_path) {
81-
warn!(
82-
"failed to delete local data for stream {} with error {err}. Clean {} manually",
83-
stream_name,
84-
stream_dir.data_path.to_string_lossy()
85+
86+
// Durable marker first: if the process crashes anywhere after this
87+
// point, restart-recovery resumes the deletion instead of silently
88+
// leaving the stream half-deleted with no record of it.
89+
objectstore
90+
.put_object(
91+
&tombstone_path(&stream_name, &tenant_id),
92+
to_bytes(&()),
93+
&tenant_id,
8594
)
86-
}
95+
.await?;
8796

88-
if let Some(hot_tier_manager) = GLOBAL_HOTTIER.get()
89-
&& hot_tier_manager.check_stream_hot_tier_exists(&stream_name, &tenant_id)
97+
// Best-effort: makes the stream vanish from listings almost
98+
// immediately, without touching every listing endpoint individually.
99+
// Not fatal if it fails -- is_deleting()/is_tombstoned() checks already
100+
// block reads and writes regardless of whether this file is gone yet.
101+
if let Err(e) = objectstore
102+
.delete_object(&stream_json_path(&stream_name, &tenant_id), &tenant_id)
103+
.await
90104
{
91-
hot_tier_manager
92-
.delete_hot_tier(&stream_name, &tenant_id)
93-
.await?;
105+
warn!(
106+
"failed to eagerly delete stream.json for {stream_name}, will be removed with the rest of the prefix: {e}"
107+
);
94108
}
95109

96-
let ingestor_metadata: Vec<NodeMetadata> =
97-
cluster::get_node_info(NodeType::Ingestor, &tenant_id)
98-
.await
99-
.map_err(|err| {
100-
error!("Fatal: failed to get ingestor info: {:?}", err);
101-
err
102-
})?;
110+
stream.mark_deleting();
111+
// Scheduled immediately once the stream is durably tombstoned and
112+
// flagged locally, before any of the remaining best-effort steps --
113+
// none of them are allowed to leave the deletion itself unscheduled if
114+
// they fail.
115+
spawn_stream_deletion(stream_name.clone(), tenant_id.clone());
103116

104-
for ingestor in ingestor_metadata {
117+
let fanout_stream_name = stream_name.clone();
118+
cluster::for_each_live_node(&tenant_id, move |node| {
105119
let url = format!(
106120
"{}{}/logstream/{}/sync",
107-
ingestor.domain_name,
121+
node.domain_name,
108122
base_path_without_preceding_slash(),
109-
stream_name
123+
fanout_stream_name
110124
);
125+
async move { cluster::send_stream_delete_request(&url, node).await }
126+
})
127+
.await?;
111128

112-
// delete the stream
113-
cluster::send_stream_delete_request(&url, ingestor.clone()).await?;
129+
if let Err(err) = fs::remove_dir_all(&stream.data_path) {
130+
warn!(
131+
"failed to delete local data for stream {} with error {err}. Clean {} manually",
132+
stream_name,
133+
stream.data_path.to_string_lossy()
134+
)
114135
}
115136

116-
// Delete from memory
117-
PARSEABLE.streams.delete(&stream_name, &tenant_id);
118-
stats::delete_stats(&stream_name, "json", &tenant_id)
119-
.unwrap_or_else(|e| warn!("failed to delete stats for stream {}: {:?}", stream_name, e));
137+
if let Some(hot_tier_manager) = GLOBAL_HOTTIER.get()
138+
&& hot_tier_manager.check_stream_hot_tier_exists(&stream_name, &tenant_id)
139+
{
140+
hot_tier_manager
141+
.delete_hot_tier(&stream_name, &tenant_id)
142+
.await?;
143+
}
120144

121-
Ok((format!("log stream {stream_name} deleted"), StatusCode::OK))
145+
Ok((
146+
format!("log stream {stream_name} deletion started"),
147+
StatusCode::ACCEPTED,
148+
))
122149
}
123150

124151
pub async fn put_stream(

‎src/migration/mod.rs‎

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,10 @@ use crate::{
3535
metrics::fetch_stats_from_storage,
3636
option::Mode,
3737
parseable::{DEFAULT_TENANT, PARSEABLE, Parseable},
38-
storage::{ObjectStorage, ObjectStoreFormat, PARSEABLE_METADATA_FILE_NAME, StorageMetadata},
38+
storage::{
39+
ObjectStorage, ObjectStoreFormat, PARSEABLE_METADATA_FILE_NAME, StorageMetadata,
40+
object_storage::{is_tombstoned, list_tombstoned_streams, spawn_stream_deletion},
41+
},
3942
};
4043

4144
fn get_version(metadata: &serde_json::Value) -> Option<&str> {
@@ -213,8 +216,12 @@ pub async fn run_migration(config: &Parseable) -> anyhow::Result<()> {
213216
let mut futures = Vec::new();
214217

215218
for tenant_id in tenants {
216-
// Get all stream names
217-
let stream_names = PARSEABLE.metastore.list_streams(&tenant_id).await?;
219+
// Get all stream names, plus any stream whose `.stream.json` is
220+
// already gone because it's mid-deletion -- `list_streams` alone
221+
// would miss it, and `migration_stream` needs the chance to resume
222+
// that deletion below if the process crashed before finishing it.
223+
let mut stream_names = PARSEABLE.metastore.list_streams(&tenant_id).await?;
224+
stream_names.extend(list_tombstoned_streams(storage.as_ref(), &tenant_id).await?);
218225

219226
// Create futures for each stream migration
220227
let f = stream_names.into_iter().map(|stream_name| {
@@ -267,6 +274,23 @@ async fn migration_stream(
267274
storage: &dyn ObjectStorage,
268275
tenant_id: &Option<String>,
269276
) -> anyhow::Result<Option<LogStreamMetadata>> {
277+
if is_tombstoned(storage, stream, tenant_id).await? {
278+
// Left mid-deletion by a node that crashed or restarted before the
279+
// background job finished. Resume it here rather than treating the
280+
// stream as a normal (possibly schema-less) migration candidate --
281+
// `create_schema_from_metastore` below can itself error out on a
282+
// partially-swept schema file, which would otherwise turn "resume
283+
// deletion" into "abort node startup". Only a query/standalone node
284+
// ever owns this job (mirrors the same guard in
285+
// `object_storage::sync_all_streams`'s self-heal check) -- an
286+
// ingestor just skips the stream here and waits for the tombstone to
287+
// clear.
288+
if PARSEABLE.options.mode != Mode::Ingest {
289+
spawn_stream_deletion(stream.to_string(), tenant_id.clone());
290+
}
291+
return Ok(None);
292+
}
293+
270294
let mut arrow_schema: Schema = Schema::empty();
271295

272296
let schema = storage

‎src/parseable/mod.rs‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -789,6 +789,21 @@ impl Parseable {
789789
let stream_in_memory_dont_update =
790790
self.streams.contains(stream_name, tenant_id) && !update_stream_flag;
791791

792+
// A stream still resident with is_deleting()=true is functionally
793+
// gone (reads/writes are already rejected elsewhere), but its entry
794+
// isn't removed from memory until the background deletion job
795+
// finishes -- surface that distinctly rather than telling the
796+
// caller it "already exists", which reads as if nothing were wrong.
797+
if stream_in_memory_dont_update
798+
&& let Ok(stream) = self.get_stream(stream_name, tenant_id)
799+
&& stream.is_deleting()
800+
{
801+
return Err(StreamError::Custom {
802+
msg: format!("Logstream {stream_name} is being deleted, please retry shortly"),
803+
status: StatusCode::CONFLICT,
804+
});
805+
}
806+
792807
// check if stream in storage only if not in memory
793808
// for Parseable OSS, create_update_stream is called only from query node
794809
// for Parseable Enterprise, create_update_stream is called from prism node

0 commit comments

Comments
 (0)