Skip to content

fix(torrent): fix what field tests against real swarms found - #570

Merged
linroid merged 55 commits into
mainfrom
fix/torrent-field-test
Oct 17, 2026
Merged

linroid merged 55 commits into
mainfrom
fix/torrent-field-test

Conversation

@linroid

@linroid linroid commented Oct 16, 2026 •

Copy link
Copy Markdown
Owner

Summary

Fixes from field-testing BitTorrent in the desktop app against real public swarms:

  • v1, v2 and hybrid torrents, from .torrent links and from magnets;
  • web seeds, uploads and seeding.

Each run downloaded, read the logs, fixed what went wrong, and ran again. A review of the whole branch then found more, fixed in the last commits.

Downloads that got stuck

  • Late blocks, v1 and v2 ("stuck at 99%"). A block whose peer is late, by twice its queue's time at its rate (4 to 30 s), is also asked of another peer. In the endgame, any outstanding block can be. The first copy cancels the other.
  • Slow v2 peers stay connected. A v2 peer that keeps answering is no longer disconnected for being slow.
  • Stall watchdog, v1 and v2. A download stalls once it gets no payload for 30 s, or verifies no piece for four pieces' worth of time. Speed limits don't count.
    • It reports why in TorrentSnapshot.stall: missing pieces (naming their files), no peers, all choking, or slow peers.
    • It recovers: it reannounces with backoff, re-dials peers it gave up on, and restarts dropped web seeds.
    • The inspector shows the reason at the top of Overview, and offers Skip file when no source has a file's pieces.
  • Web seeds go on past files they can't serve. A seed answering 404, 410, 416 or the wrong range for a file, or sending a piece corrupt twice, now skips just those, not the whole mirror. It is dropped only once nothing it can serve is left. A run's files are fetched side by side.
  • Fair piece buffers between v1 torrents. A share always holds at least one piece, so a torrent with large pieces isn't starved. Peer wire buffers are kept apart from piece buffers.

Magnets and discovery

  • Large and partly seeded v2/hybrid magnets now resolve.
    • A peer has 30 s for each part it sends, and 3 minutes in all.
    • A lookup runs past its 2 minutes while a peer is still sending.
    • Piece layers are requested 8 at a time. Those each peer sends are kept, so the next peer is asked only for the rest.
    • Dual-topic magnets look for peers under both hashes.
  • The download starts with the peers that sent the metadata, instead of waiting for trackers and the DHT to find them again.
  • Swarms never dial our own public address. Trackers kept handing back our old listen ports.
  • Stall reannounces reach UDP trackers. Without a minimum interval from the tracker, a manual announce now waits 5 minutes, not the full interval.
  • Lenient tracker, DHT and peer parsing: keys out of order, CRLF, peers6 as a list, a missing interval.

Other fixes

  • Torrent failures say what went wrong.
  • A removed task's sidecar and creation log are deleted when its files are kept.
  • A v2 file check no longer fails when other torrents fill the transfer buffer.
  • Ketch.download refuses a link no source handles.
  • Peer addresses stay out of debug logs.
  • v2 speed is measured over a second, not 200 ms.
  • Peer state memory stays bounded.
  • The v1 endgame check no longer rescans every piece as pieces open.
  • HTTPS on the JVM goes through OkHttp (the JVM's TLS), up to 256 bodies at once. CIO's TLS failed on some trackers and mirrors.

From a second field round (six parallel scenarios on isolated ketch server instances)

  • Download tracking:
    • A per-task speed limit applies again after a finished torrent reopens to download added files. A torrent kept seeding after its run pays only Ketch's global limit, through the new DownloadContext.globalThrottle.
    • Progress no longer drops to 0% while a resumed or restarted torrent rechecks its files. It follows a selection changed mid-check or while the task waits for an engine slot.
  • Web seeds and stalls:
    • A mirror missing a file is skipped for that whole file.
    • A web seed is dropped only once nothing it can serve is left, and it sends fewer requests at once after transient errors.
    • A stall started again by recovery asks a relaunched seed once more for what it refused. With nothing connected, a piece counts as missing only when every seed refused it.
    • Thrown-away payload never ends a stall.
  • Peers:
    • A peer that drops is dialed again until it comes back: about half an hour for one that sent data, and every minute during a stall with no peers. Peers named only once stay known.
    • One peer reached at two local addresses keeps one connection.

Snapshots

The inspector of a downloading torrent. Before, as on main, a torrent that stopped moving said nothing:

Before After: missing pieces After: no peers

Verified in the field

  • NRCS, a 1.24 GB hybrid with 16 KiB pieces and one reachable seeder:
    • its magnet now resolves (3 min);
    • the v2 watchdog flagged and recovered its no-peers stall;
    • all 75,728 pieces verify against the .torrent.
  • A 104-file hybrid whose qBittorrent leechers each hold only some piece layers: it never resolved before, and now resolves in about 2 minutes, with all 323 pieces verified.
  • A dual-topic hybrid and a btih-only hybrid magnet: each resolves in about 4 s and starts downloading with peers at once. The btih-only one's 1154 pieces verify.
  • A slow v1 download finished without a stall at the end.
  • Speed limits: a speed-limited download is never reported stalled.
  • Uploads and seeding work for v1, v2 and hybrid.

Not addressed

  • Follow-ups in their own PRs: shutdown waiting for downloads to stop, persisted seeding counters and discarded-payload counts, connection rates and speed-limit fairness.
  • UDP trackers were unreachable on the test network (a proxy that doesn't relay UDP), so swarms there leaned on the DHT and HTTP trackers.
  • A stalled torrent still holds its download slot.
  • Our own IPv6 address can still be dialed; those dials fail at once.

Test plan

  • ./gradlew :library:torrent:jvmTest
  • ./gradlew :library:torrent:compileTestKotlinIosSimulatorArm64 :app:shared:compileTestKotlinIosSimulatorArm64
  • core, ktor, remote, server, mcp, torrent-api, endpoints, cli and app:shared tests
  • ./gradlew :app:shared:jvmTest -Psnapshots --tests '*InspectorSnapshots.inspector_stalledTorrent_saysWhy*'

… peer wire buffers apart

Every v1 torrent's peers and pieces reserved from one engine-wide 32 MiB
budget. A busy torrent's peers took each buffer the moment it freed, so a
second torrent, a web-seeded one above all, sat idle until the first one
finished. Each peer also reserved about 140 KiB of wire room from it, so a
torrent with 100 peers held over 13 MiB before opening a piece.

Each v1 session now reserves from a fair share of the budget: it may always
grow to its part, and past it only while no other torrent is held back
below its own. Connected peers' wire buffers come from a partition of their
own, as v2 peers' state already does.
Direct requests on the JVM used Ktor CIO, whose own TLS speaks only TLS 1.2
and lost some servers' handshakes with "Not enough data available". In a
real torrent test, several HTTPS trackers failed this way on many
announces, so torrents got fewer peers; the same servers answered every
request through the JDK's TLS. HTTPS now always goes through OkHttp
(HTTP/1.1), as proxied requests already did; plain HTTP keeps CIO.
Several public trackers answer announces with dictionary keys in insertion
order, which Ketch refused as "Unsorted or duplicate bencode key" while
other clients read them, so those trackers never gave Ketch peers. What
trackers, DHT nodes and peers send is now parsed leniently, keeping the
first of a repeated key; metainfo and Ketch's own files stay canonical.
Integers are checked without compiling a regex for each one.
The uTP report logged every busy connection's address at debug every 10 s,
over a thousand lines in a short test, and magnet metadata lookups logged
each peer's address at debug, though only verbose per-peer lines may name
peers. The uTP report is now per-peer verbose detail, named by connection
ID; per-peer lookup failures log at verbose.
A v2 or hybrid task checks its files as it starts, through a scratch
buffer it reserved from the transfer budget every torrent shares. Started
while v1 torrents were downloading, it found the budget full and failed at
once with "Recheck budget exhausted", which is not retried. The scratch,
at most 64 KiB like v1's, is now allocated outside the budget.
Every torrent source error read "The torrent stopped: no reachable peers
or trackers", though a torrent without peers waits rather than fails: what
fails it are limits, unusable metadata and the like. The source now puts
the failure's message, without URLs, in the error's detail, which remote
devices receive too, and limits name their numbers ("The torrent's pieces
are 64 MiB, larger than the 16 MiB Ketch supports"). The apps show that
reason on the row and in the add sheet.
…fetch a run's files side by side

Archive.org items regenerate files such as __ia_thumb.jpg after their
torrent is made. A mirror then answered that one file with a different
length, every web seed retried the same run until it was dropped after
five failures, and a download that needed only that piece stalled near 90%
with every mirror gone. A seed now gives up only the pieces it cannot
serve: those of a file it answers 404, 410, 416 or with another range, and
a piece it sends corrupt twice. It goes on with the rest and is dropped
only after five failed runs without a verified piece, or once it has
nothing left it can serve before it ever served one, as a dead mirror.

A run spanning many small files also asked for them one at a time, each
behind a redirect on archive.org, so three mirrors gave 0.8 MB/s where one
stream reached 2.5 MB/s. Once the first request of a run is answered, the
others now go out four at a time.
…ts files are kept

Removing a torrent task without deleting its files left its hidden
.ketch-<hash>-<task> sidecar (checkpoint, ownership journal, pieces of
skipped files) or v2 creation log in the download folder for good, and so
did every `ketch <magnet>` download, whose task ends with the process. A
removal that keeps the files now deletes only that bookkeeping, checked
against the identities it recorded, and the CLI removes its task once the
download ends.
In real announces, one public tracker ended its reply with CRLF and another
sent peers6 as an empty list; Ketch refused both replies and lost their
peers. Replies are now read like other clients read them: trailing
whitespace is ignored, peers and peers6 may be compact or a list of
{ip, port} dictionaries with malformed entries skipped, and a reply that
names no interval is announced again after 30 minutes.
`ketch add wt-big-buck-bunny` was queued, then failed when it started with
"Operation not supported by server", and REST clients got a 500. A link no
source handles is now refused as the download is added, like other invalid
requests, so the CLI and MCP say why at once and the server answers 400.
A v1 block stayed with the peer first asked for it: until that peer
delivered it, rejected it, choked us or went away, nobody else could ask,
so one slow peer held its pieces' buffers and stalled the download at any
stage, most visibly at 99%. The endgame, which duplicates requests, also
waited for every wanted piece to open, so a piece no connected peer had
kept it from ever starting.

Each block now gets a due time when it is requested: twice the time the
peer's queue takes at its rate, 4 to 30 s. A peer with room asks for
blocks others are late with, at most one duplicate each, and the first copy
cancels the other. The endgame starts once every unopened piece is one no
connected peer or web seed has. A request we cancel is now remembered for a
minute rather than for a count of later blocks, so a peer that had already
queued it is not taken for sending unsolicited data.
A download that stopped making progress said nothing about it: the J-Horror
torrent sat at 99% forever while its web seeds could not serve one changed
file, and a swarm of peers that all choked us looked the same as one about
to finish. Each v1 swarm now checks itself every second. It stalls once no
payload arrived for 30 s, or no piece verified for four pieces' worth of
time (one to ten minutes); time spent waiting on speed limits never counts.
It says why: wanted pieces no connected peer or web seed has (and the files
they belong to, which can be skipped), no peers, peers that all choke us,
or slow peers. After a minute it announces to its trackers again (every 5,
then 10 minutes, up to 30), dials peers it gave up on, and after two
minutes starts dropped web seeds again.

The stall reaches TorrentSnapshot.stall, and through it REST, the event
stream and remote clients; an unknown reason decodes as unknown. The swarm
summary and an info line on each change log it.
…r has

A torrent that stopped making progress showed only a frozen bar, often at
99%. The inspector now says why, from the stall the device's torrent
controls report: no peer or web seed has some pieces it needs, no peers
for a while, peers that all choke it, or slow peers. When pieces are
missing it offers Skip file, which keeps every chosen file but the ones
those pieces belong to, so the rest can finish.
A v2 or hybrid download asked each block of one peer only: until that
peer delivered it, nobody else could ask, so the last piece finished at
the pace of the slowest peer holding part of it, and pieces a web seed
fetched waited for that mirror however slowly it served them. A peer
that was 30 s late with any request, as one slower than about 17 KiB/s
with a full pipeline always is, was disconnected, again and again.

Each request now gets a due time from its peer's rate: twice the time
its queue takes, 4 to 30 s. Once a request is late, or in the endgame
(every wanted piece left is being fetched or has no source), a peer with
room asks for the same block, at most one duplicate per block, eight per
peer and 64 in all, and none while the transfer budget runs low. The
first copy is stored, the other peer is sent a CANCEL, and a copy that
still arrives is discarded instead of failing the piece. A canceled
request is forgotten once the CANCEL is written, so a late block or
reject for it is ignored rather than taken for a protocol violation. In
the endgame peers may also begin pieces a web seed is fetching, and
whichever verifies first stores them; a run handed to a web seed just as
it stopped goes back to the peers.

A peer that keeps answering is no longer closed for being slow: its
requests time out only once it answered none of them for 60 s, or one of
them has waited four minutes.
V2 and hybrid downloads said nothing when they stopped making progress:
a mirror that lost a file left the download at 99% with no reason given,
while v1 swarms already report their stalls. The v2 session loop now
checks a stall watchdog every second while it downloads, with the
signals a v1 swarm gives it: peers connected and unchoking us, wanted
pieces no connected peer or running web seed has and the files they
belong to, late requests, running and dropped web seeds, payload
received and time spent waiting on speed limits. With nothing connected
at all, the stall is for want of peers rather than missing pieces.

The session publishes the stall, so torrent snapshots, REST, the event
stream and remote clients carry it for v2 tasks as for v1, and it clears
when the transfer stops. The swarm summary ends with it, and each change
of reason logs at info. The recoveries are v1's: the torrent's own
trackers are announced to again as soon as their minimum interval
allows (a private hybrid's shared tracker and the extra trackers keep
their schedule), peers given up on or backing off are dialed again, and
web seeds that were dropped start again with every piece, as their
mirror may have the missing files by now.
Trackers and the DHT keep handing back our own earlier listen ports at
our public address. They were filtered out only as they arrived, so the
peers named in the seconds before the engine learned that address (the
DHT's vote, as behind a second NAT the router's address is private)
stayed queued: every swarm dialed itself on a dozen ports, waited out
each dial and asked relays to punch through to it. v1 swarms and v2
candidate books now check each peer as they dial it and give up on
ours.
A v2 or hybrid magnet's metadata is the info dictionary and every file's
piece layer. Each peer had 30 s for all of it, the layers asked one
request at a time: a torrent of hundreds of files took a round trip
each, and one with a 1.5 MB info dictionary never arrived from its only
seeder, which was cut off at 30 s every time, or when its 2-minute
lookup ended. qBittorrent leechers hold only the layers of the files
they reached, and rejecting one request failed the whole peer, so such
swarms never resolved either.

A peer now has 30 s for each part it sends (an info block or a layer
response) and three minutes in all, and a lookup goes on past its time
while one arrives. Layers are asked eight requests at a time, and those
a peer sends are kept, so the next peer is asked only for the rest. A
magnet naming both a v1 and a v2 hash looks for peers under each, as a
hybrid's peers may announce only one.
A v2 or hybrid task's speed was the payload received since the progress
loop's last pass, 200 ms before. Blocks arrive in bursts, so a download
at 80 KB/s showed 0, then 313 KB/s, then 80 KB/s, and its time left
jumped with it. It is now measured over a second or more, as v1
sessions measure theirs.
…metadata

Once a magnet's lookup found the metadata, the download that followed
started from nothing: its swarm waited for trackers and the DHT to name
peers again, and in a small swarm, where the DHT took six minutes to
find the one seeder that had just sent the metadata, it sat stalled
with no peers. The peers that sent any of it are now kept, by swarm,
and dialed first when its download starts.
Three cases the stall watchdog got wrong:
- A v1 swarm with no peer connected and no web seed counted every
  piece left as one no source has, so it reported missing pieces, and
  the app offered to skip files, rather than no peers. Like v2, it now
  reports no missing pieces until something is connected.
- Every peer waiting on a speed limit added its own wait, and the
  watchdog credited them all: twenty throttled peers pushed its clocks
  twenty seconds ahead each second, so once the limit was lifted and
  the peers left it saw no stall for hours. A check now credits at most
  the time that passed.
- Reviving peers during a stall dialed again those that broke the
  protocol or sent a corrupt piece, which are never retried otherwise.
…n minutes

A manual announce, as a stalled download's recovery makes, waited for
the tracker's minimum interval, or without one, as UDP trackers never
name one, for the regular interval, often half an hour. The stall's
reannounces, minutes apart, never reached those trackers. Without a
minimum from the tracker, a manual announce now waits five minutes, or
the regular interval when that is shorter.
A web seed that refused a file before serving anything was dropped the
first time a claim came back empty, taken for a mirror without the
torrent. An empty claim may only mean that the buffers are full or that
peers took every free piece, so a mirror missing one file was dropped
though it had the rest, and started again only if the download stalled.
It is now dropped only when no wanted piece it may serve is left.
…iece

The fair split of piece buffers between v1 torrents only held others
back for a torrent asking within its part. With three torrents in the
default 32 MiB, a torrent of 16 MiB pieces never was: the others grew
past their parts and took each buffer as it freed, and it starved. A
part now holds at least one of its torrent's pieces. maxBufferedBytes
and maxExchangeBytes also say that v1 peers' wire buffers sit beside
them.
A peer connection remembered every block it delivered for a minute, up
to 8192 of them, so a fast peer held hundreds of kilobytes no budget
counted; only canceled requests need that long, and delivered ones are
again the last few, as before. The v1 endgame check also counted the
pieces no source has again each time a piece opened, a full scan per
piece in a large torrent; opening one never changes that count, so it
is counted once a second.
Every HTTPS request on the JVM now goes through OkHttp, which reads each
response body on a thread of its own, at most 64 at once. Several
downloads of up to 32 segments each stream more than that, and the
bodies past it waited for a thread until their transfer watchdog failed
them. The cap is now 256; the threads start only as bodies stream and
end once idle for 30 seconds.
@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-16T17:17:36.135281Z 6c0d2af 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.

@github-actions

github-actions Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Test Results

 2 042 files  + 69   2 070 suites  +69   31m 23s ⏱️ + 10m 45s
13 644 tests +383  13 382 ✅ +382  262 💤 +1  0 ❌ ±0 
16 597 runs  +627  16 335 ✅ +626  262 💤 +1  0 ❌ ±0 

Results for commit 7c3aad8. ± Comparison against base commit 22cfd50.

This pull request removes 5 and adds 388 tests. Note that renamed tests count towards both.
com.linroid.ketch.engine.JvmTransportsTest ‑ direct_usesCioOnlyWhenTheSelectorWouldToo[jvm]
com.linroid.ketch.torrent.storage.TorrentV2RecheckCancellationTest ‑ canceledRecheckRetainsReservationsAndDoesNotPublishTheBlockedPiece[jvm]
com.linroid.ketch.torrent.tracker.TrackerDiscoveryTest ‑ missingMinimumUsesRegularIntervalForManualAnnounces
com.linroid.ketch.torrent.tracker.TrackerDiscoveryTest ‑ missingMinimumUsesRegularIntervalForManualAnnounces[jvm]
iosSimulatorArm64Test.com.linroid.ketch.torrent.tracker.TrackerDiscoveryTest ‑ missingMinimumUsesRegularIntervalForManualAnnounces[iosSimulatorArm64]
com.linroid.ketch.app.snapshot.InspectorSnapshots ‑ inspector_stalledTorrent_saysWhy[jvm]
com.linroid.ketch.app.ui.inspector.StallNoticeTest ‑ message_saysWhy[jvm]
com.linroid.ketch.app.ui.inspector.StallNoticeTest ‑ skip_isOfferedOnlyWhenItLeavesSomethingAndRemovesSomething[jvm]
com.linroid.ketch.app.ui.inspector.StallNoticeTest ‑ skip_leavesOutTheFilesNoSourceHas[jvm]
com.linroid.ketch.app.util.ErrorCopyTest ‑ toCopy_torrentErrorWithDetail_saysWhyRatherThanBlamingPeers[jvm]
com.linroid.ketch.engine.GlobalThrottleTest ‑ globalThrottle_afterTheRun_paysTheGlobalLimitWithoutTheTasks
com.linroid.ketch.engine.GlobalThrottleTest ‑ globalThrottle_afterTheRun_paysTheGlobalLimitWithoutTheTasks[jvm]
com.linroid.ketch.engine.JvmTransportsTest ‑ direct_usesCioOnlyForPlainHttpWhenTheSelectorWouldToo[jvm]
com.linroid.ketch.engine.KetchSubmissionTest ‑ download_linkNoSourceHandles_isRefusedUpFront
com.linroid.ketch.engine.KetchSubmissionTest ‑ download_linkNoSourceHandles_isRefusedUpFront[jvm]
…

♻️ This comment has been updated with latest results.

@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: 6c0d2af529

ℹ️ 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".

Refusing links no source handles checked the request's URL even when it
carried a resolution, which starts with the source of its type and never
asks a source to handle that URL. A source that takes only uploaded
content resolves to a link it need not handle, so its every download was
refused. A resolved request is now checked by its source type, as it is
started.
A run that lends its finished torrent to seeding cleared the session's task throttle, so no
finished execution's per-task limiter would be called. That throttle was the run's
DownloadContext.throttle, which pays the task's limit and also Ketch's global one, and torrents
meet the global limit only through it. A lent v1 seeder still downloads now and then: a piece
that spans a deselected file whose bytes changed is revoked when a peer asks for it, and the
seeder fetches it again. That payload paid no limit at all.

DownloadContext now has a globalThrottle, Ketch's global limit alone, which holds only the
shared limiter and nothing of the run. A run that lends its session to seeding sets it as the
session's task throttle, and a run that takes the seeder over still sets its own.
…ollows

While its session checks the files, or has not yet taken a seeder's new selection, a run shows
the segments Ketch restored or planned, against the size of the files the run started with. It
never fitted either to a selection taken later. A file unchecked during a check restarts the
check, and for its whole length the task went back to reporting the old selection's bytes and
size, overriding the size Ketch had just shown. A pause meanwhile showed more downloaded than
the new total and saved those segments, which a restart then showed again. A run that Ketch
repeats with the same context, for a selection that came as the last run finished, started out
the same way, with segments that still described that run's files.

The run now keeps each file's progress, as Ketch restored or planned it or as the session last
reported it, and shows it over the files it follows now, as planSelection fits saved progress
to a selection. It does so as it starts, as it applies each selection and on every pass that
does not publish the session's own view, so the segments and the total change with the
selection, and a file checked again shows the progress it had.
An earlier change resets a lent seeder's task throttle so that it no longer pays a finished
run's limits. The engine still kept that run's throttle reachable. The v1 session's discovery
lambda captured the whole TorrentTaskSpec, and the v2 owner's captured the whole
TorrentV2TaskSpec, to read a few fields. Each spec holds the throttle of the run that opened
the session, and that throttle reaches the run's DownloadExecution, with its task handle and
flows. A torrent that seeded for days therefore kept its first run's execution alive through
every later takeover. The v1 spec's resume data stayed in memory as well.

Discovery now captures only what it reads: the metadata, privacy and magnet link for v1, and
the tracker tiers, magnet link and privacy for v2. Once the session's task throttle is
replaced, nothing of the opening run is left.
… slot

A task waiting for one of the engine's active torrent slots reported the
segments it was started with against the size of the files it follows.
When Ketch ran it again for a selection that came as the last run ended,
those segments still described the old files, so the waiting task showed,
and a pause saved, more downloaded than its size. The wait now fits the
progress to the files the task follows, as the run does once it starts.
The docs also no longer say that seeders Ketch starts again after a
restart pay its global limit: only one its own run lent does.
…s it again

A stalled download starts its dropped web seeds again every ten minutes, and each restarted
seed joined with every piece, as a fresh worker that had forgotten which pieces it had sent
corrupt. A file whose copy at the mirror is no longer the torrent's was therefore fetched twice
more per seed at every relaunch (one archive.org piece 16 times in a field test), and until it
failed again the scheduler saw it as available, so the stall read "unknown" instead of
"missing pieces".

Each seed now keeps one worker for the whole transfer, which remembers the pieces it sent
corrupt once, and its pieces object keeps the pieces it sent corrupt twice. Started again, the
seed joins without them and is never asked for them again during the transfer; files it lacked
(404, 410, 416, a range it would not serve) are still asked for once more, as a mirror may have
restored them. A seed left with nothing but corrupt pieces is not started again, and the
watchdog counts only the stopped seeds that could still fetch something.
…stall

A download whose only wanted file is stale at its web seeds, with no peer connected, reported
its stall as "no peers" with no missing pieces or files, because the stall check only looked
for missing pieces while something was connected, and a dropped seed took what it had found
unservable with it. The apps therefore never offered Skip file for the case the docs describe,
and TorrentStall.missingPieces was always 0 in such a stall. A single peer reconnecting also
flipped a missing-pieces stall to no-peers and back within seconds.

With nothing connected, the v1 swarm and the v2 loop now count as missing the wanted pieces a
web seed, running or dropped, found it could not serve, and name their files; the rest still
wait for peers. The watchdog keeps what was missing while something was connected for ten
seconds after the last source leaves, so a peer that reconnects at once no longer changes the
reason. The TorrentStall KDoc says what missingPieces counts.
The stall watchdog took any payload as progress, including web seed bytes of a piece that then
failed its hash check, so a stale mirror sending its copy again cleared a no-payload stall and
logged "makes progress again" while nothing was verified. In the other direction, once peers
came back after a long stall and payload flowed again, the stall stayed until a piece verified,
because the piece timer still counted the minutes without payload, and the reason read
"unknown". A swarm that completed while stalled also logged "makes progress again".

Web seed workers now count the bytes they throw away (pieces that fail their hash check or that
a failed request cuts off) in WebSeedStats.wasted, shown as webSeedWasted in the swarm summary,
and both swarms pass it to the watchdog, which takes back the checks that counted those bytes,
newest first, restoring its clocks as they were. Payload that comes back after 30 seconds
without any starts the time for a piece again, while the stall's length still counts from the
last verified piece. The v1 swarm no longer logs progress when the stall ends because it
completed.
A web seed was dropped after five failed runs in a row without a verified piece, whatever had
failed. With backoffs of 2 to 16 seconds, half a minute of reset connections was enough, even
for a seed that had served most of the torrent, and a dropped seed only came back after a
two-minute stall. In a field test a proxy refused parallel connections to archive.org: each
seed sent up to four requests at once, three seeds to one origin, and every one of them was
dropped while it still worked one request at a time.

A failure that may pass (a reset connection, a timeout, a busy server) now first halves how
many requests the seed sends at once, down to one, and only failures that cannot lower it any
further, or that come from corrupt or missing pieces, count toward dropping the seed. Each run
that works allows one more request again. A seed so survives about two minutes of transient
failures, backing off up to the one-minute cap, before it is dropped.
A torrent restored to seed, or one that kept seeding after it finished, logged "downloading
from N web seed(s) too" although it had nothing to fetch, and a v1 swarm kept one worker per
web seed polling four times a second for the whole seeding session.

The v1 swarm now starts its web seeds the first time it wants pieces, joining them all before
any claims a run as before, so a session that only seeds never starts them, and one whose
selection grows starts them then. The v2 hub, whose idle workers already wait without polling,
logs the line when it hands out its first run instead of when the transfer starts.
The stall watchdog restarted the time a piece may take whenever payload came back after 30 s
without any, deciding the gap from the clock that thrown-away payload moves back. Two ways let
discarded web seed bytes clear a real stall. While a corrupt or cut-off run was still arriving,
each check took its bytes as payload back after a gap, so a stall that had outlasted the piece
time cleared and "makes progress again" was logged until the run failed. And once a failed run was
taken back, the clock it rewound made the next byte from any peer look like payload back after a
gap, so a trickle that never verified a piece ended a piece-timer stall the discarded bytes never
caused.

Whether payload came back after a gap is now decided from when any payload last arrived, a clock
nothing moves back. The restart it earns waits on the check that took the payload until nothing
can throw that payload away any more: web seeds count the bytes of pieces not stored yet
(WebSeedStats.unsettled, StallSignals.unsettledBytes), counted before they are payload and
settled after they are counted wasted, so swarms that read them in that order never see a byte
kept early. Payload thrown away meanwhile cancels the waiting restarts, as which bytes it was is
not known. Peers' payload is never at risk and restarts the time at once, as before. Checks that
may still be taken back merge once there are 64 instead of being forgotten.

The watchdog tests now cover a long stall while unsettled payload arrives and a trickle after a
large wasted run; the v1 and v2 swarm tests let the corrupt piece arrive a part at a time across
several checks instead of all at once.
Payload back after 30 s without any restarted the time a piece may take every time it happened.
Payload that comes and goes without ever completing a piece, such as peers that mostly choke us
and unchoke for a few seconds every minute or two, therefore never tripped the piece rule: each
burst cleared the stall and logged "makes progress again", and 30 s after it the stall and its
log line came back, for as long as the download ran. Before payload back after a gap restarted
the timer, such a stall stayed once no piece had verified for the piece time.

The restart now happens only the first time payload comes back after a gap until the next piece
verifies, which is what it is for: peers back after a long outage get a piece's time before the
stall shows again. Later bursts leave the time counting from that first return, so once it is up
the stall stays until a piece verifies.

A watchdog test sends 10 s of payload every 100 s for ten minutes with no piece verifying and
expects the stall to stay once the first piece time after the first burst is up.
…rupt

A piece a web seed sent corrupt twice was left out of its claims for the rest of the transfer, and
a seed left with only such pieces was never started again. That removed the recovery a stalled
download had before: starting dropped seeds again two minutes into the stall, then every ten
minutes, asks a mirror once more for what it could not serve, as it may have fixed it by then.
A torrent whose only source is a web seed that served an old copy of a file for a while, during
a redeploy or until a stale cache expired, stayed at missing pieces after the mirror was fixed
until the user paused and resumed it or skipped the file.

A seed started again now joins with every piece again, those it could not serve included, as it
did before the seed kept what it learned. Its worker still remembers the pieces it sent corrupt
once, so a piece it sent corrupt before is given up again after one more corrupt copy instead of
two: one request per relaunch for a mirror that is still stale. Every stopped seed counts as
dropped again, so the relaunch runs. What a seed could not serve, whether it lacked the file or
sent it corrupt, is still kept for the transfer (SwarmWebSeedPieces.unservable,
TorrentV2WebSeeds.refuses) for the stall to report while every seed is stopped; v2 keeps it apart
from the pieces a running seed is not asked for, which a relaunch clears. The stale flag of
WebSeedPieces.unavailable and the schedulers' wantsOutside and needsOutside go, as nothing tells
corrupt and missing pieces apart any more.

New v1 and v2 tests fix the mirror after its seed was dropped and expect the relaunch to ask once
more and finish the download; the relaunch tests now expect one more request for the stale file.
Saying that payload back after a gap gives a piece its time again only once left one line of the
watchdog's KDoc past the 100-column limit. The paragraph is wrapped again; its words are unchanged.
…eb seed refused it

With no peer connected and no web seed running, a stall counted a wanted piece as missing as soon
as any one web seed had found it could not serve it: the union of the seeds' refused pieces in v1,
and in v2 any seed refusing it. A torrent with two seeds, one lacking a file and the other merely
down, therefore read missing pieces naming that file, and the apps offered Skip file, although
the second seed would serve it once started again. Missing pieces also took the place of no peers
when other wanted pieces had no source at all.

Only the pieces every web seed refused count now. A running seed counts as serving every piece,
and a stopped one by what it found it could not serve, kept for the transfer; v1 intersects the
stopped seeds' sets, and v2 counts a piece as served while any seed runs or one that stopped never
refused it. With a single seed nothing changes.

New v1 and v2 tests drop two seeds, one lacking the only wanted file and the other down, and
expect no peers; once both start again and neither has the file, they expect missing pieces
naming it.
A web seed's refusals were kept for the whole transfer, even after a
stall started it again and it served the file it once refused. With
nothing connected, the stall then still counted that file's pieces as
missing and offered to skip it, though its seed serves it and was only
down. A seed now forgets its refusals when it starts again, and records
anew what it still cannot serve. The docs also say that a seed still
serving other files is asked again for a refused one only on resume.
A peer that dropped was dialed again only twice, one and two seconds later
in v1 (three times over 50 s in v2), then left alone for five minutes: a
tracker, the DHT or peer exchange naming it again was ignored until then,
and a stalled swarm revived peers at most every five minutes. A download
whose only peer restarted for two minutes waited up to five more.

Both swarms now share one redial policy (PeerRedial): an endpoint is dialed
again after 5, 15 and 30 s, then 1, 2 and 5 minutes, and every 5 minutes
on. One that never brought payload is still given up after three retries,
as most endpoints trackers and the DHT name are long gone. One that brought
payload is never given up while the swarm downloads, its count starts over
with each connection that brings payload, and a source naming it again has
it dialed 30 s after its last dial. A revive keeps each endpoint's count,
and a stall without a single peer revives every minute instead of every
five, as nothing is lost by dialing more then.
…esses

A v1 swarm kept every connection whose handshake succeeded, so a peer it
reached at two addresses, such as loopback from a magnet's x.pe and its LAN
address from local discovery, held two connections for the whole transfer:
the seeder spent two of its four upload slots on one downloader. v2 told
peers apart by their claimed ID on the host they came from, so it missed the
same case.

Both swarms now key peers by PeerIdentity: the claimed peer ID and the host,
where loopback, private, link-local and unique local hosts count as one, as
one client there is reached at several addresses. A public host claiming
another's ID is still another peer. Of two connections of one direction the
first stays; of opposite directions both ends keep the one the side with the
lower listen port dialed (keepsOutgoing, moved out of the v2 loop), and a v1
worker it replaces ends at its next pass. The endpoint of the connection
closed is given up until found again five minutes later, rather than redialed
and closed over and over.
Both ends of a duplicate connection keep the socket keepsOutgoing picks,
comparing their own listen port with the port they dialed. Ours was
advertisedPort.current(), the router's external port while a port
mapping exists, but a peer on this machine or our LAN dials the listen
port, which local discovery announces and a magnet's x.pe names. With D
listening on 40000 behind a mapping to 60000 and S on 50000, D compared
60000 with 50000 and kept S's dial, while S compared 50000 with 40000
and kept D's: both connections closed, exactly in the local-peer case
the duplicate check was added for.

TorrentAdvertisedPort.portFor gives the port a peer reaches us on: the
listen port for a peer at a local address (localTorrentAddress), else
the mapped one. Both swarms use it for keepsOutgoing and for the BEP 10
`p` they send, so a local peer is also told a port it can dial.
A peer that sent payload was never given up while the swarm downloaded,
so nothing bounded such endpoints: on a long download every peer that
sent data and left stayed in the book for good, dialed every five
minutes and holding a dial slot for up to 17 s each time. The DHT names
the same peers every minute, and each lookup brought a waiting peer's
dial forward to 30 s after its last one, so a dead peer the DHT still
listed was dialed about once a minute. In v1 an endpoint waiting to be
dialed again counted twice against the 4096-endpoint limit, among the
endpoints known and among those queued, so 2048 waiting endpoints
refused every new one, and each revive did the same. A revive's dial
also renewed when an endpoint was given up, so a stall without peers,
which revives every minute, kept every endpoint it gave up from ever
being forgotten.

A peer that sent data is now dialed again ten times
(PeerRedial.DELIVERED_RETRIES), about half an hour, then given up like
any other endpoint. A source naming it again brings its dial forward at
most once every five minutes. The v1 swarm keeps every endpoint it
knows, queued or not, in one book where each counts once. A revive's
dial of an endpoint given up on leaves when that was (PeerRedial.spent),
in both swarms, so the endpoint is forgotten five minutes later all the
same.
…pened

Only an endpoint we dialed got credit for the payload its connection
brought. A peer that dialed us and served us, as peers often do after we
announce or through local discovery, was queued where it listens as a
new endpoint once it dropped: dialed 0, 5, 20 and 50 s later, then given
up, so a peer that restarted for two minutes waited for the next revive,
up to five minutes in a stall with other peers connected. A peer whose
connection to us replaced ours as a duplicate fared no better: in v1 our
dial ended with DuplicatePeerException and stayed known as tried, and
when the kept connection closed nothing queued that endpoint again; v2
queued it without the payload the replaced connection had brought.

When an incoming connection that brought payload closes, the endpoint
the peer listens on (BEP 10 `p`) is now dialed again as a dialed one
that brought payload is, known already or not (v1 redial, v2
incomingClosed with delivered). A connection that replaces another to
the same peer inherits what that one brought, and a v1 incoming
connection kept over our dial remembers where we dialed the peer
(alias), so the peer is dialed there once it closes. A peer that broke
the protocol gets no credit.
…dial

Once the window-based reset left TorrentV2Candidates.next(), a v2
endpoint's count of dials kept rising across connections that came up
and stayed up for hours, until one of them brought payload. A peer we
only upload to, which has nothing we need yet, was given up for five
minutes after its fourth connection in all, however long each lasted;
the old window had reset the count every five minutes. The v1 swarm
counted dials the same way.

A connection that stays up five minutes (PeerRedial.LASTING_MS) now
counts as its endpoint's first dial when it closes, as one that brings
payload does, in both swarms. Only failed dials, and connections that
drop soon after they come up, add to the count.
When a peer's connection to us replaced ours as a duplicate, the v1
swarm gave our dial's endpoint up until forgotten, which happens five
minutes after its last dial. A dial kept for an hour before it was
displaced was forgotten on the loop's next pass, so the next tracker or
DHT answer queued it again, and the new connection was closed as a
duplicate in turn, every five or six minutes for as long as the kept
connection lasted. v2 already counted from the close.

The endpoint of a dial closed as a duplicate now counts as dialed when
it closes, so it stays given up for five minutes from then, unless the
kept connection closed first and queued it again.
The swarm tests built their swarms without a stall flow, so the lonely
revive that bounds how soon a returning peer is reached ran in neither
swarm, and v2's redial of a peer that sent payload was tested only on
its candidate book: TorrentV2SessionLoop.forget could have stopped
passing what the peer delivered, or the swarms stopped reviving peers,
without any test failing.

TorrentV2SwarmRig takes a stall flow. A v1 and a v2 test now run a
stalled download whose only peer drops and comes back between its own
redials, and must reach it within a minute of its return, and a v2 loop
test checks that a peer that sent payload is dialed a fifth time.
A v1 swarm forgot an endpoint five minutes after it gave the endpoint
up. Now that a stall's revives no longer postpone that, a peer named
once only, by a magnet's x.pe or as one that sent the metadata, was
forgotten about seven minutes after its dials ran out, and no source
named it again, so the stalled swarm never reached it when it came
back. Given-up endpoints are now kept: a source naming one again five
minutes after its last dial starts it over, as forgetting it did, and
the longest known one makes room when the swarm knows 4096.

A v2 peer that dialed us over uTP from the socket it listens on has the
same source and listen endpoint, which the v2 book took for an
ephemeral port, so it never dialed such a peer back after it sent data
and dropped. Its listen endpoint now counts like any other.
@linroid
linroid added this pull request to stack #575 October 17, 2026 12:42
@linroid
linroid merged commit 2c70589 into main Oct 17, 2026
14 checks passed
@linroid
linroid deleted the fix/torrent-field-test branch October 17, 2026 14:54
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