Skip to content

Add timeout to streaming shard snapshot writer - #9239

Merged
timvisee merged 2 commits into
devfrom
snapshot-stream-timeout
Jun 2, 2026
Merged

timvisee merged 2 commits into
devfrom
snapshot-stream-timeout

Conversation

@generall

Copy link
Copy Markdown
Member

Problem

When a node streams a shard snapshot (GET /collections/{c}/shards/{id}/snapshot), the producer writes the tar into a small in-memory tokio::io::duplex while holding the shard's SegmentHolder upgradable-read lock and occupying a blocking thread. If the consumer stops draining without tearing down the connection — a crashed/partitioned receiver, or any path where no FIN/RST comes back — the blocking write parks forever. With no teardown to observe, the snapshot never fails, so the lock is held indefinitely, optimizers stall, and retried transfers pile up parked tasks until the blocking pool is exhausted and the shard wedges.

Manual testing confirmed the asymmetry: rst / fin (clean teardown) are already handled via the OS → broken-pipe path; only the blackhole / offline case (no packets at all) wedges the sender — and nothing on the sender bounds it.

Fix

TimeoutWriter (lib/collection/src/common/timeout_writer.rs): an AsyncWrite adapter that aborts a write that makes no progress for an idle timeout. It wraps the duplex write half (SNAPSHOT_STREAM_WRITE_IDLE_TIMEOUT = 30s). On a stalled consumer the write resolves TimedOut, which unwinds the snapshot, releases the SegmentHolder lock, and frees the blocking thread. The timer measures idle time only and resets on every byte/flush, so a slow-but-progressing consumer is not affected.

Test tooling (this PR adds)

  • tests/manual/slow_snapshot_download.py — slowly / partially download a streaming snapshot from a URL to exercise sender backpressure against a remote node. --then hold|rst|fin|blackhole simulates a stalled, kill -9'd, or offline (firewall blackhole) consumer. Stdlib only, read-only against the target.
  • tests/consensus_tests/test_streaming_snapshot_receiver_kill.py — throttled receiver killed mid-flight + a second receiver, to observe whether the sender releases the lock and recovers.

Notes / follow-ups

  • A 30s idle timeout implies a minimum sustained-throughput floor of roughly downstream_buffer / timeout (sender SO_SNDBUF + BDP + client SO_RCVBUF). With default autotuned buffers that can be a few hundred KiB/s, so consider bounding SO_SNDBUF on the connection to make the floor a small, deterministic constant.
  • This addresses the deadlock (lock released within the timeout). It does not cap how many concurrent/retried snapshot streams can stack up — a per-shard concurrency limit is still worth adding so a retry storm can't pile parked tasks up to the blocking-pool limit in the first place.

🤖 Generated with Claude Code

timvisee and others added 2 commits May 29, 2026 16:56
- tests/manual/slow_snapshot_download.py: slowly / partially download a
  streaming shard snapshot from a URL to exercise sender-side backpressure.
  Supports hold / rst / fin / blackhole termination to simulate a stalled,
  killed, or offline (network-partitioned) consumer against a remote node.
  Stdlib only; read-only against the target.
- tests/consensus_tests/test_streaming_snapshot_receiver_kill.py: throttled
  receiver killed mid-flight + a second receiver, to observe whether the
  sender releases the SegmentHolder lock and recovers.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (1)
tests/consensus_tests/test_streaming_snapshot_receiver_kill.py (1)

169-174: ⚡ Quick win

Poll responsiveness during recovery instead of checking only once at the end.

_wait_for_file(done2, timeout=RECOVER_TIMEOUT_SECS) can sit there for the full two minutes, and Line 174 probes _responsive() only after that wait completes. A long stall that clears just before the final probe still passes, even though this test documents that the node stayed responsive “the whole time.”

Possible refactor
-    recovered = _wait_for_file(done2, timeout=RECOVER_TIMEOUT_SECS)
+    deadline = time.time() + RECOVER_TIMEOUT_SECS
+    recovered = False
+    while time.time() < deadline:
+        assert _responsive(peer_url), "node became unresponsive during recovery"
+        if done2.exists():
+            recovered = True
+            break
+        time.sleep(0.5)
     recv2.join(timeout=5)
 
-    # The node must stay responsive the whole time (blast-radius containment).
-    assert _responsive(peer_url), "node became unresponsive after receiver kill"
+    assert _responsive(peer_url), "node became unresponsive after receiver kill"
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/consensus_tests/test_streaming_snapshot_receiver_kill.py` around lines
169 - 174, The test currently waits for _wait_for_file(done2,
timeout=RECOVER_TIMEOUT_SECS) and only calls _responsive(peer_url) once after
that, so transient unresponsiveness during the recovery window is not detected;
change the flow in the section around _wait_for_file, recv2.join and the final
assert to poll _responsive(peer_url) repeatedly (e.g., every 0.5–1s) until
either the done2 file appears or RECOVER_TIMEOUT_SECS elapses, asserting
responsiveness on each poll to ensure the node stayed responsive the whole time;
keep the existing recv2.join(timeout=5) after recovery finishes.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@tests/consensus_tests/test_streaming_snapshot_receiver_kill.py`:
- Around line 76-81: In throttled_receiver(), delay writing the ready marker
(ready_path.write_text("streaming")) until the receiver has actually started
receiving body bytes by moving that call inside the for chunk in
r.iter_content(...) loop and writing it after the first non-empty chunk is seen;
additionally, during the kill→recovery window in the test add periodic polling
calls to _responsive() (e.g., a small sleep loop that calls _responsive()
repeatedly until receiver `#2` recovers or a timeout) so responsiveness is checked
throughout recovery rather than only before kill and after recovery.

In `@tests/manual/slow_snapshot_download.py`:
- Around line 334-342: The test spawns daemon threads in main() which can exit
on KeyboardInterrupt before download()’s finally block runs and _blackhole()’s
cleanup executes, so add a guard in main(): if args.then == "blackhole" and
args.concurrency != 1, print an error and exit (reject this combination); locate
the validation near the main() argument handling where threads are created
(reference main(), download(), _blackhole()) and enforce that --then blackhole
is only allowed when concurrency == 1 to ensure the cleanup callback runs
reliably.

---

Nitpick comments:
In `@tests/consensus_tests/test_streaming_snapshot_receiver_kill.py`:
- Around line 169-174: The test currently waits for _wait_for_file(done2,
timeout=RECOVER_TIMEOUT_SECS) and only calls _responsive(peer_url) once after
that, so transient unresponsiveness during the recovery window is not detected;
change the flow in the section around _wait_for_file, recv2.join and the final
assert to poll _responsive(peer_url) repeatedly (e.g., every 0.5–1s) until
either the done2 file appears or RECOVER_TIMEOUT_SECS elapses, asserting
responsiveness on each poll to ensure the node stayed responsive the whole time;
keep the existing recv2.join(timeout=5) after recovery finishes.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI (base), Organization UI (inherited)

Review profile: CHILL

Plan: Pro

Run ID: f31246f6-c70a-4db1-9efa-5f5d6f7591fa

📥 Commits

Reviewing files that changed from the base of the PR and between 74071c4 and 06c9f17.

📒 Files selected for processing (5)
  • lib/collection/src/common/mod.rs
  • lib/collection/src/common/timeout_writer.rs
  • lib/collection/src/shards/shard_holder/mod.rs
  • tests/consensus_tests/test_streaming_snapshot_receiver_kill.py
  • tests/manual/slow_snapshot_download.py

Comment on lines +76 to +81
# Signal that the stream actually started (sender is now producing/parked).
pathlib.Path(ready_path).write_text("streaming")
total = 0
for chunk in r.iter_content(chunk_size=THROTTLE_CHUNK):
total += len(chunk)
time.sleep(THROTTLE_SLEEP)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail
FILE="tests/consensus_tests/test_streaming_snapshot_receiver_kill.py"
echo "== $FILE =="
nl -ba "$FILE" | sed -n '1,220p' | sed -n '60,110p'

Repository: qdrant/qdrant

Length of output: 187


🏁 Script executed:

#!/bin/bash
set -euo pipefail
FILE="tests/consensus_tests/test_streaming_snapshot_receiver_kill.py"
echo "== $FILE (lines 60-100) =="
sed -n '60,105p' "$FILE" | cat -n

Repository: qdrant/qdrant

Length of output: 2351


🏁 Script executed:

#!/bin/bash
set -euo pipefail
FILE="tests/consensus_tests/test_streaming_snapshot_receiver_kill.py"
echo "== $FILE (lines 100-190) =="
sed -n '100,210p' "$FILE" | cat -n

Repository: qdrant/qdrant

Length of output: 5347


🏁 Script executed:

#!/bin/bash
set -euo pipefail
FILE=".github/review-rules.md"
echo "== $FILE (head) =="
sed -n '1,200p' "$FILE" | cat -n

Repository: qdrant/qdrant

Length of output: 2840


Delay ready1 signaling until body bytes are read; poll responsiveness during recovery

  • In throttled_receiver(), ready_path is written immediately after requests.get(...).status_code == 200 and before any iter_content() chunks are consumed, so receiver #1 can be killed while the request is only header-complete. Move the marker into the iter_content() loop (e.g., after the first non-empty chunk).
  • The test claims the node stays responsive “the whole time”, but it only calls _responsive() once before the kill and once after receiver #2 finishes/recover times out; add periodic _responsive() polling during the kill→recovery window.
Proposed fix
-        # Signal that the stream actually started (sender is now producing/parked).
-        pathlib.Path(ready_path).write_text("streaming")
         total = 0
         for chunk in r.iter_content(chunk_size=THROTTLE_CHUNK):
+            if total == 0 and chunk:
+                # First body bytes observed.
+                pathlib.Path(ready_path).write_text("streaming")
             total += len(chunk)
             time.sleep(THROTTLE_SLEEP)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/consensus_tests/test_streaming_snapshot_receiver_kill.py` around lines
76 - 81, In throttled_receiver(), delay writing the ready marker
(ready_path.write_text("streaming")) until the receiver has actually started
receiving body bytes by moving that call inside the for chunk in
r.iter_content(...) loop and writing it after the first non-empty chunk is seen;
additionally, during the kill→recovery window in the test add periodic polling
calls to _responsive() (e.g., a small sleep loop that calls _responsive()
repeatedly until receiver `#2` recovers or a timeout) so responsiveness is checked
throughout recovery rather than only before kill and after recovery.

Comment on lines +334 to +342
threads = [threading.Thread(target=download, args=(i, args), daemon=True)
for i in range(args.concurrency)]
for t in threads:
t.start()
try:
while any(t.is_alive() for t in threads):
time.sleep(0.5)
except KeyboardInterrupt:
print("interrupted, exiting (daemon downloads will be torn down)")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# 1) Read review rules (per instructions)
echo "=== .github/review-rules.md ==="
sed -n '1,200p' .github/review-rules.md || true

# 2) Locate and inspect the target Python file + relevant line ranges
echo
echo "=== tests/manual/slow_snapshot_download.py (around 300-380) ==="
python - <<'PY'
from pathlib import Path
p = Path("tests/manual/slow_snapshot_download.py")
lines = p.read_text().splitlines()
start, end = 300, 390  # includes 334-342 plus nearby context
for i in range(start, min(end, len(lines))):
    print(f"{i+1:4d}: {lines[i]}")
PY

# 3) Inspect blackhole implementation and any cleanup wiring
echo
echo "=== tests/manual/slow_snapshot_download.py: definitions for _blackhole and where cleanup is used ==="
rg -n "_blackhole|then ==|args\.then|iptables|ip6tables|cleanup" tests/manual/slow_snapshot_download.py

# Print larger relevant sections for context
python - <<'PY'
from pathlib import Path
p = Path("tests/manual/slow_snapshot_download.py")
lines = p.read_text().splitlines()
def dump(a,b):
    for i in range(a-1,b):
        if 0 <= i < len(lines):
            print(f"{i+1:4d}: {lines[i]}")
print("\n=== near _blackhole ===")
# best-effort find around first occurrence
txt = "\n".join(lines)
idx = txt.find("_blackhole")
if idx != -1:
    # compute line number
    line_no = txt[:idx].count("\n")+1
    dump(max(1, line_no-30), line_no+80)

print("\n=== near concurrency / main then blackhole dispatch ===")
# find where "def main" and "concurrency"
for pat in ["def main", "concurrency", "args.then", "--then", "blackhole"]:
    if pat in txt:
        # print around first hit of each pattern (dedup later manually if too much)
        i0 = txt.find(pat)
        line_no = txt[:i0].count("\n")+1
        dump(max(1, line_no-40), line_no+80)
PY

Repository: qdrant/qdrant

Length of output: 34878


Avoid daemon worker threads for --then blackhole (iptables cleanup can be skipped on Ctrl-C).

main() starts concurrent downloads as daemon=True threads and exits immediately on KeyboardInterrupt; daemon threads may not run the finally block in the blackhole path, so _blackhole()’s iptables/ip6tables cleanup callback (the -D rules) may never be executed.

Minimal guard
     if args.concurrency == 1:
         download(0, args)
         return
+
+    if args.then == "blackhole":
+        raise SystemExit(
+            "--then blackhole requires --concurrency 1 so cleanup can reliably remove iptables rules"
+        )
 
     threads = [threading.Thread(target=download, args=(i, args), daemon=True)
                for i in range(args.concurrency)]
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/manual/slow_snapshot_download.py` around lines 334 - 342, The test
spawns daemon threads in main() which can exit on KeyboardInterrupt before
download()’s finally block runs and _blackhole()’s cleanup executes, so add a
guard in main(): if args.then == "blackhole" and args.concurrency != 1, print an
error and exit (reject this combination); locate the validation near the main()
argument handling where threads are created (reference main(), download(),
_blackhole()) and enforce that --then blackhole is only allowed when concurrency
== 1 to ensure the cleanup callback runs reliably.

@timvisee
timvisee self-requested a review June 1, 2026 08:49
@qdrant qdrant deleted a comment from coderabbitai Bot Jun 2, 2026
@timvisee
timvisee merged commit c4a22aa into dev Jun 2, 2026
20 of 21 checks passed
@timvisee
timvisee deleted the snapshot-stream-timeout branch June 2, 2026 12:24
timvisee added a commit that referenced this pull request Jun 3, 2026
* Add block level timeout to snapshot stream writer

* Add tooling to exercise streaming snapshot stalls

- tests/manual/slow_snapshot_download.py: slowly / partially download a
  streaming shard snapshot from a URL to exercise sender-side backpressure.
  Supports hold / rst / fin / blackhole termination to simulate a stalled,
  killed, or offline (network-partitioned) consumer against a remote node.
  Stdlib only; read-only against the target.
- tests/consensus_tests/test_streaming_snapshot_receiver_kill.py: throttled
  receiver killed mid-flight + a second receiver, to observe whether the
  sender releases the SegmentHolder lock and recovers.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

---------

Co-authored-by: timvisee <[email protected]>
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
@timvisee timvisee mentioned this pull request Jun 3, 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