Skip to content

perf(torrent): share v1 pieces between peers and pipeline requests by rate - #567

Merged
linroid merged 3 commits into
perf/torrent-v1-interestfrom
perf/torrent-v1-block-pipeline
Oct 16, 2026
Merged

linroid merged 3 commits into
perf/torrent-v1-interestfrom
perf/torrent-v1-block-pipeline

Conversation

@linroid

@linroid linroid commented Oct 16, 2026 •

Copy link
Copy Markdown
Owner

Third of three stacked PRs for v1 torrent throughput, based on #566 (and #565) (review items 8 and 9).

The limits

  • Each v1 peer claimed a whole piece and reserved all of it from the engine-wide transfer budget (maxBufferedBytes, 32 MiB). That left room for about eight 4 MiB pieces in flight across the whole engine, or a single 16 MiB one. A slow peer could hold its buffer for up to 90 s.
  • Requests were capped at 16 blocks of that one piece, about 256 KiB per round trip. The queue drained at every piece end, and with 16 KiB pieces only one request was ever outstanding.
  • A choke threw the partial piece away, and the request loop copied the pending set once per block (O(blocks²) allocation per piece).

Design: shared in-memory pieces, not write-through

Writing blocks through to disk and hashing incrementally was the other option. Against TorrentPieceStore it would mean:

  • unverified peer bytes in the user's files, including files adopted in place on reselection and pieces still waiting for verifyExisting;
  • a per-piece layout generation, because changeSelection and dropIfVanished move spans between the file and its sidecar;
  • a reorder buffer or a read-back to hash;
  • a validated-handle cache, so each 16 KiB write does not repeat the secure path walk.

That is a storage redesign, so this PR keeps store.commit(index, bytes) (a whole, hashed piece) and changes how pieces are shared.

  • Open pieces. Peers request 16 KiB blocks of open pieces: one buffer per piece being assembled, reserved whole when the piece opens and shared by every peer that has it. A piece opens, rarest first, when a peer has nothing left to fetch in the open ones. The budget now bounds pieces in assembly rather than peers transferring, and the commit, sidecar and selection rules are untouched.
  • Adaptive pipeline. Each peer keeps about 3 s of its measured rate outstanding: 4 to 500 requests, within its BEP 10 reqq (250 when it names none). It starts at 16 with a slow start of one more request per block received until the first rate sample. Requests run across piece ends and go out in batches (PeerWire.sendAll). We advertise reqq 500; the upload queue became a LinkedHashSet.
  • Chokes keep data. A choke, reject, cancel or disconnect frees only the blocks still owed; received blocks stay with their piece. A partial piece nobody fetches gives its buffer up after 10 s idle when another piece needs it, after 60 s anyway, and at once when no connected peer has it. The scheduler's close() returns everything when the swarm stops.
  • Corrupt pieces. A failed hash check blames a peer only when it sent every block (CorruptPieceException, as before). Otherwise one peer fetches the piece alone next, so a repeat offender ends up identified.
  • Endgame. Once every wanted piece is open, idle peers ask for blocks one other peer owes, and the first copy to arrive cancels the other.
  • Smaller fixes on the hot path. HAVEs come from an append-only verified log with a cursor per peer, instead of a bitmap copy and scan per peer per verified piece. PeerProtocolState.pendingCount replaces the copying requests.size. Workers read completion lock-free (completedNow()), so a commit holding the store lock no longer stalls every peer. A peer is admitted while everything the engine-wide budget holds except this swarm's own pieces (other torrents' peers and pieces, uploads) leaves room for one more piece; the swarm's own open pieces, which its peers share and finish, no longer keep peers out. A peer waiting for a buffer is not dropped as useless. Web seeds keep their whole-piece runs.

Results

Median MB/s (3 runs), CPU s/GiB and GiB allocated per GiB downloaded:

Piece RTT main platform digests this PR CPU main → this PR Allocated main → this PR
16 KiB 0 69.4 65.3 80.9 (79.4–85.8) 34.09 → 19.72 55.41 → 7.03
256 KiB 0 491.6 569.0 889.0 (768.6–946.8) 5.94 → 4.20 5.10 → 4.44
4 MiB 0 572.1 961.1 1,093.8 (1,047.8–1,174.1) 6.49 → 2.84 11.45 → 4.31
16 MiB 0 135.9 170.4 666.5 (620.6–685.6) 8.84 → 1.84 31.51 → 4.21
16 KiB 50 ms 1.2 1.2 69.6 (67.0–72.6) 81.90 → 17.60 19.07 → 7.33
256 KiB 50 ms 18.2 18.1 166.9 (164.7–168.2) 12.54 → 4.96 4.96 → 4.44
4 MiB 50 ms 18.9 19.0 162.7 (159.5–166.2) 11.26 → 3.52 11.58 → 4.53
16 MiB 50 ms 4.8 4.8 99.5 (97.8–100.1) 17.39 → 3.67 31.54 → 4.61

The 64 MiB rows with a round trip include the slow start. With 512 MiB at 50 ms (this PR only, 3 runs), the rates are: 16 KiB 77.4, 256 KiB 406.1, 4 MiB 379.0, 16 MiB 129.4 MB/s.

Limits left

  • 16 MiB pieces. With the default 32 MiB budget, only one 16 MiB piece fits next to the peers' wire overhead. Every peer fills that one piece, but nothing downloads while it commits and the next one opens, which costs one round trip per piece (129 MB/s at 50 ms). A larger default maxBufferedBytes, or write-through, would remove this; that is a memory-policy decision for a separate change.
  • 16 KiB pieces. These are now bound by per-piece storage cost: every commit reopens its file through the secure path walk (JNA calls and lstat per component), plus socket syscalls per message. A profile shows the download path itself no longer dominates. The review's validated-handle cache is the fix.
  • Not addressed here. Peer banning, duplicate-connection detection and the PEX directory are separate items in the review.

Tests

New regression tests, each checked against the previous code:

Test Previous code
TorrentSwarmPipelineTest.requestsRunAcrossPieceEnds: 6 requests over at least 3 two-block pieces before any reply times out
TorrentSwarmPipelineTest.peersShareOnePiecesBuffer: a budget of one 32-block piece, and both peers are asked for blocks of it before either answers times out
TorrentSwarmPipelineTest.chokeKeepsTheBlocksAlreadyReceived: after a non-Fast choke at half a piece, the other peer is asked only for the missing 4 blocks asks for all 8
TorrentSwarmPipelineTest.fastPeerThatChokesAfterServingLeavesTheRestToOthers: a Fast peer serves its 16 requests after choking and never unchokes; a seed found later finishes well within the 90 s deadline times out
TorrentSwarmPipelineTest.stoppedSwarmReturnsEveryBuffer: a stopped swarm returns its partial pieces' buffers passes (guards the new path)

TorrentPieceSchedulerTest was rewritten for the block API (17 tests). It covers:

  • buffer accounting: one budget charge per shared piece, starved, finish and close freeing it;
  • requests across piece ends, and rarest first;
  • choke and reject release;
  • endgame duplicates and their cancels;
  • corrupt-piece attribution, and abandoned commits;
  • stale and abandoned piece eviction;
  • interest and both-seeds via poll;
  • the HAVE log, retarget closing unwanted pieces, revoke;
  • web-seed runs alongside open pieces.

TorrentSwarmPipelineTest.peerWaitsWhileOtherTorrentsLeaveNoRoomForAPiece checks that admission (added after review; it fails on the swarm-only rule). :library:torrent:jvmTest passes in full (1,305 tests). v1 and crypto tests also pass on the Android host, and the module compiles for iOS.

How this was measured

V1ThroughputTest (opt-in, added in the first PR of the stack): a KotlinTorrentEngine with the default buffer limits (maxBufferedBytes 32 MiB) downloads a v1 torrent from 4 in-process LoopbackSeeders, memory-backed seeds on plain threads that answer each request after an optional delay, which the engine sees as the round trip. Uploads, DHT, uTP, encryption, local discovery and port mapping are off; the seeders' threads are subtracted from CPU time and allocation; one warm-up download runs first. 256 MiB payload without a round trip, 64 MiB with 50 ms, 3 runs per row (median and range). CPU is process CPU, JIT and GC included.

Apple M4 Pro (14 cores), 48 GiB, macOS 27, APFS SSD, OpenJDK 21.0.11 (Homebrew), otherwise idle.

KETCH_TORRENT_THROUGHPUT=1 KETCH_THROUGHPUT_LABEL="$(git rev-parse --short HEAD)" \
  ./gradlew :library:torrent:jvmTest --tests '*V1ThroughputTest'

… rate

Each v1 peer claimed a whole piece and reserved all of it from the
engine-wide transfer budget, so the default 32 MiB let about eight 4 MiB
pieces, or one 16 MiB piece, be in flight across the engine. Requests
stopped at 16 blocks of that one piece, the queue drained at every piece
end, and a choke threw the partial piece away.

Peers now request 16 KiB blocks of open pieces: one buffer per piece being
assembled, opened rarest first when a peer has nothing left to fetch in the
open ones, and shared by every peer that has the piece. The budget bounds
pieces in assembly rather than peers transferring, and store.commit still
takes a whole, hashed piece, so the commit, sidecar and selection rules are
unchanged.

- Each peer keeps about 3 s of its measured rate outstanding (4 to 500
  requests, within its reqq or 250), with a slow start from 16, across
  piece ends; we advertise reqq 500.
- A choke, reject, cancel or disconnect frees only the blocks still owed.
  Partial pieces give their buffers up after 10 s idle when another piece
  needs one, after 60 s anyway, and at once when no connected peer has them.
- A failed hash check blames a peer only when it sent every block;
  otherwise one peer fetches the piece alone next.
- Once every wanted piece is open, idle peers duplicate outstanding blocks
  and the first copy cancels the other.
- HAVEs come from an append-only log, the pending count no longer copies
  the request set, peers read completion without the store lock, and a
  peer waiting for a buffer is not dropped as useless.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-16T13:21:24.704324Z ec2b788 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ec2b7889a1

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@linroid
linroid added this pull request to stack #568 October 16, 2026 13:24
Every torrent's peers and pieces, and uploads, share one transfer budget.
Counting only the swarm's own peers let several swarms admit peers until no
piece fit anywhere, and peers waiting for a buffer are no longer dropped,
so every download could stall. A peer is admitted again only while all of
the budget but the swarm's own pieces, which its peers share and finish,
leaves room for one more piece.
@github-actions

Copy link
Copy Markdown
Contributor

Test Results

 1 954 files  + 5   1 982 suites  +5   24m 9s ⏱️ +47s
13 146 tests +51  12 899 ✅ +51  247 💤 ±0  0 ❌ ±0 
15 849 runs  +85  15 602 ✅ +85  247 💤 ±0  0 ❌ ±0 

Results for commit 743fd67. ± Comparison against base commit cf0fc4f.

@linroid
linroid merged commit 21cc4ac into main Oct 16, 2026
14 checks passed
@linroid
linroid deleted the perf/torrent-v1-block-pipeline branch October 16, 2026 14:38
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.

1 participant