Skip to content

fix: prevent stream resurrection and staging races during async deletion - #1857

Closed
AadishJ wants to merge 21 commits into
parseablehq:mainfrom
AadishJ:fix/async-deletion-race-conditions
Closed

AadishJ wants to merge 21 commits into
parseablehq:mainfrom
AadishJ:fix/async-deletion-race-conditions

Conversation

@AadishJ

@AadishJ AadishJ commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Addresses #1855.

Description

Follow-up to the asynchronous stream deletion introduced in #1770, now merged into main. This PR addresses remaining races between deletion, ingestion, local staging cleanup, and stream recreation.

Coordinates deletion and recreation through shared locks, drains participating ingestion and staging work before cleanup, and keeps old stream handles marked as deleting rather than reactivating them.

  • Serialize DELETE handling and local cleanup with stream creation/update, preventing delayed cleanup from affecting a recreated stream.
  • Recheck the durable tombstone before a background deletion job starts cleanup.
  • Coordinate staging cleanup with ingestion, schema writes, writer finalization, and local conversion to prevent deleted files from reappearing.
  • Clean stale staging and reset statistics before evicting deleting entries, so recreated streams do not inherit old data or counters.
  • Retain deletion state when staging cleanup fails, allowing background cleanup or reconciliation to retry.
  • Prevent ingestion and object-store sync from implicitly recreating missing stream entries.
  • Add deletion guards to hot-tier reads and tests for ingestion error responses (409 Conflict for deleting streams and 500 for staging failures).

This PR has:

  • been tested to ensure log ingestion and log query works.
  • added comments explaining the "why" and the intent of the code wherever would not be obvious for an unfamiliar reader.
  • added documentation for new or modified features or behaviors.

RetriggerView in GreptileConfidence Score: 4/5

The PR appears safe to merge, with non-blocking cleanup scheduling and duplicate-check improvements.

Fix All in CodexFindings

  1. P2 Deletion blocks an HTTP worker ▶
  2. P2 Hot-tier reads repeat a check ▶
Fix with agent prompt
### Issue 1
src/parseable/streams.rs:2323-2328
`remove_staging` waits on a blocking lock directly from async DELETE and reconciliation code. An active `flush_and_convert` holds shared access through the whole conversion. Deleting a stream with a large backlog can therefore block the HTTP worker until conversion finishes, delaying unrelated requests assigned to it.

Run cleanup on a blocking worker while keeping the creation lock held until cleanup finishes.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

### Issue 2
src/handlers/http/logstream.rs:770-775
`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.

Summary

This PR coordinates stream deletion with local ingestion, conversion, and recreation.

  • Stream deletion keeps recreation blocked until cleanup finishes.
  • Local cleanup waits for ingestion and conversion to finish.
  • Deleting streams reject ingestion and hot-tier reads.
  • Event processing and object-store sync require an existing stream.

Tests were not run during this review. AadishJ states that deletion-job lifecycle and multi-node recovery validation remain outstanding.

Diagram

sequenceDiagram
    participant Client
    participant Delete as DELETE handler
    participant Stream
    participant Job as Background deletion
    participant Store as Object storage
    Client->>Delete: Delete stream
    Delete->>Delete: Acquire creation lock
    Delete->>Stream: Mark deleting
    Delete->>Store: Write tombstone
    Delete->>Stream: Drain local work and remove staging
    Delete->>Job: Schedule deletion
    Delete-->>Client: 202 Accepted
    Job->>Job: Acquire creation lock
    Job->>Store: Recheck tombstone
    Job->>Stream: Retry staging cleanup
    Job->>Store: Delete stream data
    Job->>Stream: Evict deleting entry and clear stats
    Job->>Store: Remove tombstone
Loading

Reviews (1) · Last reviewed commit: "fix: merge issues" · Reviewed by Greptile

prabhaks and others added 21 commits August 25, 2026 22:18
Lays groundwork for background stream deletion: a durable tombstone
marker outside the deleted prefix, an in-memory `deleting` flag on
resident streams, and guards in the reload/query/info-endpoint code
paths that reject a stream once either is set. Purely additive, no
behavior change to the current delete handlers, since nothing yet
sets a tombstone or the flag. Prepares for the actual async-delete
rewrite in a follow-up PR.
…erable

list_dirs_relative only surfaces child directories on every backend
(S3/GCS/Azure via list-with-delimiter's common_prefixes, LocalFS via
read_dir + is_dir), never leaf objects. A tombstone stored as a bare
key named after the stream was therefore invisible to any future scan
that needs to discover tombstoned streams rather than check one known
name at a time. Move the marker one level deeper, under a directory
named after the stream, and add list_tombstoned_streams for that scan.
…lehq#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 parseablehq#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.
…discovery

set_metadata replaced the whole LogStreamMetadata wholesale, so a reload
racing a delete (e.g. a schema update landing after mark_deleting()) could
silently clear the deleting flag back to false despite it being documented
as monotonic. Now ORs it in instead of overwriting.

list_tombstoned_streams trusted list_dirs_relative's raw directory listing
as proof of a marker's existence, but a directory can exist under the
tombstone root without the marker itself (e.g. an interrupted write).
Each candidate is now re-verified with is_tombstoned before being reported.

list_old_streams (unused elsewhere in this codebase, but kept consistent
with list_streams) didn't exclude TOMBSTONE_ROOT_DIRECTORY, so dir_with_old_stream
would treat it as a corrupt stream directory the same way list_streams did
before the earlier fix.
check_or_load_stream's resident-stream fast path doesn't itself check
is_tombstoned (flagged in CodeRabbit's review of parseablehq#1768), so a concurrent
request on the same node could slip through in the window between the
tombstone becoming durable and mark_deleting() actually running. Moving
mark_deleting() before the tombstone write, with no await point in
between, closes that window entirely for the initiating node.

Cross-node propagation is still bounded by the existing fan-out push and
self-heal, not synchronous -- that's an accepted, already-documented
limitation of this design, not something this reorder attempts to fix.
…ion-safety-net

# Conflicts:
#	src/handlers/http/query.rs
…-deletion

# Conflicts:
#	src/storage/object_storage.rs
…test image to Quay

- clear_deleting() to roll back mark_deleting() when the tombstone
  write itself fails, so a transient storage error doesn't
  permanently strand a stream in "deleting" state
- reorder delete handlers (standalone + query node) so
  spawn_stream_deletion runs last, after local/hot-tier cleanup, and
  make ingestor fan-out and hot-tier cleanup best-effort instead of
  bailing the request
- reject create/update of a tombstoned-but-not-yet-purged stream even
  when it isn't resident in memory yet (create_update_stream)
- treat a repeated LocalFS delete_stream as success when the prefix
  is already gone, matching S3/Azure/GCS's empty-prefix behavior
- restrict the resident-entry reap in sync_all_streams's tombstone
  check to non-owner nodes, closing a race with the owner's own
  in-flight tombstone write
- fix stale comment on the dedup test module to reflect the real
  entry()-based atomic guard

Also switch the MinIO image in all four docker-compose test files
from minio/minio to quay.io/minio/minio (same pinned release tag) --
minio/minio has been pulled from Docker Hub, which was failing CI at
the image-pull step before tests even ran.
…reate/update

Root cause of the Quest distributed CI failure: a node that doesn't run
the background deletion job itself (an ingestor) never clears its
resident stream's is_deleting flag on its own -- it only self-heals on
the next sync_all_streams tick. Recreating a stream shortly after
deleting it (a pattern several Quest tests use) landed in the window
before that tick, so create_update_stream kept rejecting the recreate
with 409 even though the tombstone was already gone. It now re-checks
the durable tombstone before trusting the in-memory flag, and clears
the flag itself when the tombstone turns out to already be cleared.

Also addresses two new CodeRabbit findings on the delete/create race:
mark_deleting() plus the tombstone write could interleave with a
concurrent create_update_stream on the same node, since only the query
node's put_stream held CREATE_STREAM_LOCK and DELETE never did.
Standalone and ingestor put_stream/delete had no lock at all. All three
now hold the same lock across the is_deleting()-check-through-
tombstone-write window.
The stale-flag self-heal added in the previous commit cleared
is_deleting()/removed the flag but left stream_in_memory_dont_update
untouched, so create_update_stream still fell through to the
"Logstream already exists" 400 right after self-healing -- exactly the
Quest delete-then-recreate pattern that broke both the standalone and
distributed CI runs (TestSmokeIngestEventsToStream: expected 200, got
400).

Now the stale entry is dropped from the in-memory map (not just its
flag cleared) so get_or_create doesn't hand back the same stale
Arc<Stream>, and stream_in_memory_dont_update is corrected so the
"already exists" check no longer trips.

Also extracted the deletion/tombstone checks in create_update_stream
into reject_if_stream_deleting to bring its cyclomatic complexity back
down (DeepSource flagged RS-R1000 after the previous commit pushed it
to "very-high" risk).
Retention (get/put), hot tier (put/get/delete), and the distributed
get_stats handler could still act on a stream mid-deletion since they
never checked is_deleting() after resolving it. Add the same guard
used by the other stream endpoints to each of them.

Also extend sync_all_streams to periodically scan the tombstone
directory itself, not just resident streams: if a background deletion
finishes but the final tombstone-clear call fails, the stream is
already gone from memory and storage, so the existing per-stream
self-heal never sees it again. Retrying delete_stream against an
already-empty prefix is a cheap no-op, so this converges the tombstone
without waiting for a node restart.
…ments

- create_stream_if_not_exists (and the OTEL ingest path specifically,
  which never went through validate_stream_for_ingestion at all) could
  implicitly recreate a stream while its background deletion was still
  running, since neither checked the tombstone before falling through
  to create_stream().
- spawn_stream_deletion's finalization removed a stream from memory by
  name only, so a client recreating the same name right as the
  background job finished could have its brand-new stream evicted
  instead of the stale one. Streams::delete_if_still_deleting only
  removes an entry that's still actually flagged deleting.
- LocalFS list_streams could fail the entire listing if a stream's
  deletion (including its tombstone) finished in the narrow window
  between the directory snapshot and the per-entry check, misreading
  "already fully gone" as "corrupt".
- sync_all_streams' tombstone reconciliation only ever looked at
  streams already flagged deleting locally, so a node that missed the
  delete handler's fan-out push (e.g. a transient liveness-check
  failure) never self-healed at all, contrary to what its own comments
  claimed. It now also scans the tombstone directory for resident
  streams that were never flagged, on every node type.
- A retried DELETE against a query replica that hasn't resumed a
  tombstoned stream yet returned a plain 404, indistinguishable from
  the stream never having existed; it now reports the deletion as
  already in progress.
- Ingestor's delete endpoint returned 200 while the other two returned
  202 for the same "deletion started" response.

Added LocalFS-level tests for the snapshot race, a mixed
tombstoned/corrupt listing, and delete_stream's idempotent-retry
behavior.
…shot

- spawn_stream_deletion cleared the tombstone before removing the map
  entry and clearing stats. While the tombstone is still present, a
  recreate is rejected with 409, so nothing could race the map
  cleanup -- but clearing it first opened a window where a legitimate
  recreate's stats could be zeroed by the trailing delete_stats call.
  Reordered so tombstone clear is last.
- The new tombstone-check on a retried DELETE swallowed real storage
  errors as "not tombstoned", turning them into a misleading 404
  instead of surfacing the actual failure.
- sync_all_streams' tombstone-directory scan acted on a snapshot: if
  the original deletion finished and the name was legitimately
  recreated between the snapshot and this stream being processed, the
  fresh stream could be marked deleting with no tombstone left to ever
  clear it again. Added a live re-check of that one name immediately
  before flagging it.
…eams

is_tombstoned().unwrap_or(false) treated a real error the same as "not
tombstoned", silently leaving an actually-tombstoned stream unflagged
and open to ingestion for a cycle. Match on the result instead so a
failed check just retries next interval without masking the error.
DeepSource flagged sync_all_streams at cyclomatic complexity 27
(very-high risk) after the tombstone reconciliation logic was added.
Extract the two reconciliation passes into their own functions with no
behavior change, to bring the top-level function's complexity back
down.
…heal

Standalone/all-in-one delete() had no tombstone-aware fallback for the
narrow window where spawn_stream_deletion has already evicted the map
entry but hasn't cleared the tombstone yet, unlike the query node's
handler -- a retried DELETE landing there got a plain 404 instead of
202 "already in progress". Mirror the query node's check.

reject_if_stream_deleting only self-healed a stale is_deleting flag on
the create path; on the update path (e.g. a PUT reaching an ingestor
whose resident copy was flagged by a delete fan-out push, with the
tombstone since cleared elsewhere) the update would go through but the
flag stayed set, needlessly rejecting ingestion for up to another sync
interval. Clear it there too.

Also add unit tests for delete_if_still_deleting and clear_deleting,
which had no direct coverage despite delete_if_still_deleting being
the core compare-and-remove guard the whole background-deletion
cleanup order depends on.
- Use existing-stream lookups in ingestion and staging uploads
- Coordinate ingestion, schema writes, and local sync with cleanup
- Clean stale staging before eviction and recreation
- Recheck tombstones before background deletion
- Preserve deletion state on repeated DELETE requests
- Reset dataset stats during cleanup
- Return 409 for deletion-related ingestion errors
- Add HTTP error-mapping regression tests
Comment thread src/parseable/streams.rs
Comment on lines +2323 to +2328
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
)))
})?;

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 Deletion blocks an HTTP worker

remove_staging waits on a blocking lock directly from async DELETE and reconciliation code. An active flush_and_convert holds shared access through the whole conversion. Deleting a stream with a large backlog can therefore block the HTTP worker until conversion finishes, delaying unrelated requests assigned to it.

Run cleanup on a blocking worker while keeping the creation lock held until cleanup finishes.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/parseable/streams.rs
Line: 2323-2328

Comment:
**Deletion blocks an HTTP worker**

`remove_staging` waits on a blocking lock directly from async DELETE and reconciliation code. An active `flush_and_convert` holds shared access through the whole conversion. Deleting a stream with a large backlog can therefore block the HTTP worker until conversion finishes, delaying unrelated requests assigned to it.

Run cleanup on a blocking worker while keeping the creation lock held until cleanup finishes.

---

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

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Fix in Codex Fix in Claude Code

Comment on lines +770 to +775
if PARSEABLE
.get_stream(&stream_name, &tenant_id)
.is_ok_and(|stream| stream.is_deleting())
{
return Err(StreamNotFound(stream_name.to_owned()).into());
}

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

@AadishJ AadishJ closed this Nov 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants