Repository navigation
fix(torrent): fix what the next round of field tests found - #587
Merged
Merged
Conversation
Checking or unchecking files of a torrent that was checking its files briefly showed the old selection's progress and size again before the new one came back. Ketch shows the new selection as soon as it saves it, but the run kept following the old files until the session returned from changeSelection, which stops the check, changes the files and starts it again, about a quarter of a second. Each progress pass in that window republished the old files' progress over Ketch's. A live session had the same window, as it reports its old files until its swarm takes the change. The run now follows the new files before it hands them to the session, and shows the progress it holds for them until the session has taken the change; a report the session made while a selection arrived is dropped.
Changing the files of a running torrent could make its downloaded bytes drop for a moment, even when a file was only added. Ketch planned the new selection from the segments in the task record, which a running download saves only every save interval (5 s by default), so the plan fitted progress up to five seconds old. Ketch then showed the plan's progress and saved its stale segments into the record. A running task's selection is now planned from the download's live segments, which the execution's context shares with the task, so the plan, the record and the progress shown all start from where the download is. Tasks that are not running still plan from the record.
After a file selection on a running task, clients of the event stream got a task.state event that carried the new selection with the old selection's progress and size, corrected by a task.progress event in the same millisecond. Ketch saved the selection first, which publishes the task's new request, and only updated the progress once it had delivered the selection; the stream sends a request change with the state it sees at that moment. A running, downloading task now shows the plan's progress and size before the save publishes the new request, and again once the selection is delivered, as a transfer may have reported the old files in between. A save that fails shows the old progress again. Holding the task's control lock keeps the execution from finishing meanwhile.
A stalled download whose web seed was backing off from a failing mirror, or had just been started again, reported its stall as "unknown" for minutes: the watchdog counted every running seed as a source, so a download with no peer could be neither "no-peers" nor "choked", and with nothing missing it fell through to "unknown". Field tests saw it on archive.org torrents for over 100 seconds at a time, in v1 and v2 swarms alike. A stall means nothing from the web seeds was stored either, whatever they are doing, so they no longer decide the reason: with no peer connected and nothing missing a stall is "no-peers", and with peers that all choke us it is "choked". Web seeds still matter through the pieces they cannot serve. Starting dropped seeds again made the reason flip for a moment too: a seed that rejoins offers every piece until it refuses the bad ones again, so "missing-pieces" briefly read as something else. The pieces missing when seeds start again now stay missing for 10 seconds while they ask once more, as they already do when the last source leaves.
A download with two web seeds reported "missing-pieces" for files that only the running seed lacked, while the other seed, dropped after network errors, had never refused them; once the running seed was dropped as well, the same stall turned into "no-peers" without anything changing at the mirrors. Field tests saw it name three files for about 35 seconds. The check counted a piece as missing whenever no connected peer or running seed had it, and only asked the stopped seeds once nothing at all was connected. Both v1 and v2 swarms now apply one rule: a wanted piece is missing when no connected peer or running web seed has it and every web seed that stopped found it could not serve it, as one started again may still serve the rest. With nothing connected and no web seed, nothing is known to be missing and the download waits for peers, as before.
A v1 torrent that finished downloading from web seeds and went on seeding kept every web seed worker alive for the whole seeding session: each one found nothing to claim, waited 250 ms and asked the piece scheduler again, taking its lock each time, and the swarm summary still listed the seeds as running (webSeeds=1/1 long after completion). It sent no requests, so the cost was CPU and lock contention for as long as the torrent seeded. The swarm now stops its web seeds when it completes, and starts them again, as a swarm that begins as a seeder already does, once a selection wants pieces. Started again, a seed asks once more for what it could not serve before. V2 and hybrid transfers are unaffected: their idle seeds wait for a run without polling.
Once every wanted piece of a v1 torrent was open, a peer with room in its pipeline asked for any block another peer owed, up to its whole pipeline of as many as 500 blocks, starting with the oldest open piece. Those are the blocks their owners send next, so both copies arrived and one was thrown away. A torrent that fits the transfer budget, such as a small one, opens every piece at once, so its endgame covered the whole download: field tests received 56% more than an 11.6 MB torrent from three peers, and 14.5% more on a larger one with many. In the endgame a peer now copies blocks on time only once it owes none of its own, at most 16 at once, and those due last first: an owner sends its requests in order, so a copy of a block far back in its queue arrives first and cancels the owner's before it is sent. Blocks an owner is late with are still copied as the pipeline allows. Against local seeders at 2 MB/s each, a 45-piece torrent from three of them received 19% more than its size before and under 0.5% now, and finished in 2.0 s instead of 2.4 s; against seeders that ignore cancels, 52% more before and at most 3% now.
… window Stopping the engine paused and closed its torrents one at a time, and each gave its trackers up to 2 seconds to hear `stopped` before the next began; the router's port mappings were removed after all of them, which can take 2 seconds more. Three or four torrents with slow trackers took 6 to 8 seconds, past the 5 seconds Ketch.shutdown waits, so `ketch server` exited while later torrents had not announced `stopped`, the router still forwarded the port and the DHT never closed. The engine now closes its torrents side by side while the port mapper removes the mappings, and every `stopped` announce made while it stops ends within one 2-second window that starts when the stop does, however long a torrent took to pause. Announces still name the port the trackers knew, as stopping the mapper leaves it. Three torrents whose trackers never answer `stopped` now stop in about 2 seconds instead of 6.
… announces on each LAN On a Mac running a TUN proxy, local peer discovery joined the IPv4 group on the tunnel too, as only the IPv6 side left out point-to-point interfaces. Every announce then reached other clients through the tunnel with the tunnel's own address, so each LAN peer was 172.19.0.1 and every dial was reset by the proxy. The tunnel also took the announces themselves: on macOS the interface option of the dual-stack socket steers only IPv6 multicast, so every IPv4 announce left on the interface holding the multicast route, whichever interface the transport meant. With the tunnel left out, nothing would have reached the LAN. Point-to-point interfaces are now left out for both families, and IPv4 announces go through an IPv4 DatagramChannel whose IP_MULTICAST_IF is set for each joined interface, so they leave on the LAN and loop back to other clients on the device with its LAN address.
…hen they are added The v1 parser refuses pieces over 16 MiB, so a v1 torrent with them fails its preview. A v2 or hybrid .torrent, or a v2 magnet's metadata, passed resolve and add, as only session admission checked the piece length: the task then failed the moment it started. The limit is now one constant in the metainfo package, checked by the v1 parser, by v2 and hybrid resolution of new inputs, and by the v2 metadata exchange as soon as a magnet's info arrives, so the lookup ends before any piece layers are fetched. A task saved before this still reads, for its file list and removal, and admission still refuses it when it starts.
…s pass A task resumed with a source state read its saved metainfo through resolveMetainfo, the entry point for metainfo a caller hands in, which applies the checks of new inputs: a private or tracker-only torrent left without a usable tracker, and v2 pieces over 16 MiB. A task saved before those checks existed then failed on resume with a reason it was never given when it was added, although the checks were meant for new inputs only and the docs said saved metainfo skips them. Only a start without a state, which reads the saved resolution with newInput = false, behaved as documented. The resume path now parses the saved metainfo with newInput = false, as the file table and fresh starts already do, so a saved task runs as it was accepted. Session admission still refuses v2 pieces no session can assemble, now for resumed tasks too.
…es, not when added The docs said a torrent with pieces over 16 MiB is refused when it is added. Only a preview resolves before a task exists: Ketch.download saves the task and returns, and a link added directly, through the API, the CLI, MCP or the browser extension, is resolved by the task's first run, which then fails. The torrent guide and AGENTS.md now say these torrents are refused when resolved or previewed, and that a link added directly fails as it starts.
…nnot join ipv4_sendsOutOfTheInterfaceItJoined probes loopback multicast with plain IPv4 channels, then opens two JvmLsdTransports, which join through their dual-stack MulticastSocket. Where that socket refuses the IPv4 group on loopback but the probe's channel took it, open throws and the test errored instead of skipping, as its siblings do when the system refuses multicast. That could turn the Windows job of the torrent desktop tests red. Both opens now skip the test when they throw, closing the first transport if only the second fails.
…nnel exclusion Leaving point-to-point links out of local peer discovery was tested only against the host's own interfaces: no CI runner has a multicast tunnel with a private address, so the test passed with the exclusion removed, and only a developer Mac with a VPN up exercised it. The choice now reads each interface's facts once (up, loopback, point-to-point, multicast, addresses) into LsdInterfaceFacts, whose joinsIpv4Group and joinsIpv6Group decide from those alone; lsdInterfaces and lsdIpv6Interfaces apply them to the system's interfaces. A unit test puts a utun holding 172.19.0.1 beside en0 and checks that only en0 joins either group, while the same addresses on a LAN interface would.
…s leave The torrent guide promised that VPN tunnels are left out of local peer discovery everywhere. The check is NetworkInterface.isPointToPoint, which holds for tunnels on macOS, Linux and Android, but Windows has no such flag: Wintun and TAP adapters may count as LAN interfaces there. The guide now says so, without filtering adapters by name. The developer section still tied the tunnel exclusion to IPv6 alone and said everything went through the one shared socket on 6771, and the JvmLsdTransport KDoc said that socket sends on every interface. Both families leave out point-to-point links, and IPv4 announces leave through a separate IPv4 socket from an ephemeral port, out of each joined interface in turn, which matters to firewall rules and captures on udp port 6771. The section, the KDoc and AGENTS.md now say so.
A selection made while its task waited in the queue could be lost when the queue started the task during the planning. Ketch read whether the task ran before planning, which for a torrent decodes the source state and the metainfo and may stat files on disk, and handed the selection to the execution only if it ran then. The queue does not take the task's control lock, so it could start the task in that window, building the execution's selection from the request it had then. Ketch saved the new selection without delivering it, the source started with the old files and acknowledged them, and the task completed at the new size without the files that were added, which later selections saw as unchanged. Ketch now delivers a saved selection to whatever execution runs once the save is done, as the coordinator answers NOT_RUNNING when none does. An execution also takes the saved selection again under the control lock before it builds its context, so a run never starts with a selection older than the one saved.
…saved A running task could still publish its new file selection with the old selection's progress and size. Ketch showed the plan's progress, then saved the selection, which publishes the new request once the store returns. The transfer kept reporting meanwhile, and as it only learns of the selection when Ketch delivers it after the save, a report in that window (a torrent reports every 200 ms) put the old selection's progress back just before the new request went out, so event stream clients saw a task.state event pairing them. A slow store, or a periodic save holding the record, widened the window. The task's running execution now holds back its progress reports from just before the plan is shown until the selection is delivered, or the save fails. A report already on its way when the hold begins cannot replace the plan, as the plan is shown with a compare-and-set loop and the reports check the hold on every attempt. With nothing reported in between, the second show after the delivery is gone. A source reports the files of a delivered revision from then on, which the selection's KDoc now says.
…earlier one A torrent's file selection could show an older selection's progress and size again when two selections came close together. The run followed the selection its collector was applying, and the collector takes one selection at a time: a second one delivered while the session was still taking the first, which can last seconds when a v2 store checks a newly selected file, waited until the first returned. Ketch showed the second selection at once, but every 200 ms pass held the first one's files and reported its size, until the collector reached the second. The run now follows the latest selection Ketch delivered whenever its revision is newer than the files it follows, so the held progress always describes what Ketch shows. A session report is used only once the session took that latest revision, so the first selection's report is not published in the moment between its apply returning and the collector taking the next one.
… in a selection save While a selection was saved, Ketch dropped the running execution's progress reports rather than holding them back, which the docs claimed. A source that reports often loses nothing by that, but one that reports once and then waits does: a torrent waiting for one of the engine's slots reports once, and that report is what takes a started task from Queued to Downloading. When it fell inside the save, the task kept showing Queued while it held a Ketch download slot, until a torrent slot freed, as nothing showed the plan on a task that was not downloading yet. The execution now keeps its last report, written before it reads the hold, and when the hold ends a task that still shows Queued shows that report as Downloading: as the plan, with its size and segment progress, once the selection is delivered, and as it was when the save failed. The KDoc and AGENTS.md now say the reports are dropped.
Ketch delivers a file selection to the task's running execution after it saves it, through the coordinator, whose lock every task shares: another task's pause holds it while it saves and flushes, and starts and cancels take it too. A caller cancelled while it waited there, such as a REST request the client dropped or an app scope that ended, skipped the delivery. The new request was published and the plan shown, but the execution kept the old selection: it downloaded the old files and completed at their size under the new request, and selecting the same files again changed nothing, so the added files were never downloaded. Once the selection is saved, the command's afterSave and the delivery now run without cancellation, so a saved selection always reaches the execution that runs.
…cancelled Once a file selection is saved, Ketch delivered it to a running execution without cancellation, but the step that puts it to work when no execution runs still ran cancellably after it: queueing a completed task that gains files or a task waiting for its files, and telling a completed task's seeding session about a smaller selection. Queueing waits for the queue's lock and the store, which every task shares, as when another task's start joins its stopping execution. A caller cancelled there, such as a REST request the client dropped, left the record saved as QUEUED with the new files while nothing queued the task: a completed task kept showing its old size and never downloaded the added files, and a task waiting for its files stayed paused. Selecting the same files again found nothing to change, so only a restart or deselecting and selecting the files again recovered it. That step now runs without cancellation too, so a saved selection is always delivered, queued or shared.
…iece may come back A stalled download counted every wanted piece as obtainable while any web seed that had stopped had not refused it. A seed is only told a piece is unservable by a lasting answer (404, 410, 416, a wrong range or a corrupt copy); one dropped for failures that may pass, such as a host that does not resolve, refused connections, timeouts, 403, 5xx or TLS errors, refuses nothing. Such a dead mirror therefore stood for every piece: v1 intersected its empty set with the others' and found nothing missing, and v2's "any stopped seed that did not refuse it" was true for every piece. Missing pieces and the inspector's Skip file disappeared for good whenever one url-list mirror was down, even with peers connected that lacked those pieces; the stall read choked or no-peers instead. A stopped seed now counts only once it refused something. v1 leaves seeds with an empty refused set out of the intersection, so with none left a peer or running seed decides alone, and with nothing connected nothing is reported missing. v2 asks the same of TorrentV2WebSeeds.refusesAny, and with nothing connected and no refusing seed reports nothing missing, as v1 does. A torrent whose running seed lacks a file while another mirror is down now reads missing-pieces both before and after the refusing seed stops. New v1 and v2 tests connect a peer lacking a piece beside a dropped dead mirror and expect missing-pieces. The tests that dropped a dead mirror beside one lacking the file (pieceOneDroppedSeedLacked, pieceTheRunningSeedLacks) expected no-peers with nothing missing; they now expect the file missing, and check again past the relaunch's grace.
…r missing pieces When a stall starts dropped web seeds again, the watchdog keeps reporting the pieces that were missing for 10 seconds, as the relaunched seeds offer every piece until they refuse those pieces once more. The grace replaced whatever the swarm reported, so a peer that connected meanwhile with every missing piece could not clear the reason: for up to 10 seconds the stall still read missing-pieces and the inspector offered to skip the file that peer was about to deliver. The watchdog now remembers how many peers were connected at the relaunch and keeps the earlier missing pieces only while no more are connected; once another peer joins, what the swarm reports stands at once.
…that they deliver nothing The public KDoc of TorrentStallReason.NO_PEERS said web seeds deliver nothing. A stall is also declared when no piece verifies within four pieces' worth of time, so no-peers is reported while a slow mirror still streams payload, as the tests that feed a corrupt piece a part a second show. It now says no peer is connected and web seeds, if any, have stored no piece meanwhile, as docs/torrent.md already did.
Since a v1 swarm stops its web seeds once it has every piece, its periodic summary keyed the web seed section on the running workers and left the whole section out while it seeded: the pieces, payload, waste and failures the seeds accounted for vanished from field logs, while a v2 swarm in the same state still printed them. The section now follows the torrent's configured web seeds, so a seeding v1 swarm prints webSeeds=0/n with its totals, and a swarm that has not started its seeds yet shows them as not running. docs/logging.md says so.
PeerTopic was imported after TorrentV2DiscoverySink; it now comes first, as the IDE's Optimize Imports orders them.
…s across a relaunch 526becd counted a stopped web seed that refused nothing as a possible source of every piece, so a mirror that is only down for a while (maintenance, 503 or 429, timeouts) never made the apps offer Skip file for a file it serves once started again. 2fe91ff02 reversed that to stop a dead mirror from hiding missing pieces for good: it took only seeds that had refused pieces as evidence. That brought the false Skip file back: with one mirror lacking a file and another down for a few minutes, the stall read missing-pieces about 40 seconds in, although the second mirror would serve the file after the relaunch two minutes into the stall. Both goals now hold with a bounded rule. A stopped seed counts again by what it refused, as 526becd had it, unless it was dropped, started again and dropped again without verifying or refusing a piece in between. WebSeedWorker records that as downAcrossRelaunch, set on such a second drop before the swarm can see the seed stop and cleared as soon as the seed verifies a piece or refuses one (after the refusal is visible to the swarm). The v1 stall check leaves such seeds out of the intersection of refused pieces, and the v2 check out of the stopped seeds that may still bring a piece, through TorrentV2WebSeeds.downAcrossRelaunch, which replaces refusesAny. A mirror down for a while therefore keeps the reason at no-peers or choked until its first restart fails too, and a dead one stops hiding missing pieces from then on. The tests 2fe91ff02 renamed go back to main's expectations (pieceOneSeedLacked_isMissingOnlyOnceEverySeedLacksIt and pieceTheRunningSeedLacks_isMissingOnlyOnceTheStoppedSeedLacksItToo, v1 and v2: no-peers while the second mirror is down, missing once it is back and lacks the file). New v1 and v2 tests keep that mirror down across the relaunch and expect no-peers, then missing-pieces once it was dropped again; and a peer lacking a file beside a dead mirror now reads choked with nothing missing until the mirror fails across a relaunch, then missing-pieces naming the file. docs/torrent.md says how long a down mirror counts.
…et to answer When a stall starts dropped web seeds again, each seed offers every piece until it verifies or refuses one, so the swarm counts nothing missing meanwhile. The watchdog kept the pieces missing at the relaunch for a fixed 10 seconds only. A mirror that answers slowly, or not at all, takes far longer: a blackholed one fails five requests of up to 30 seconds each with backoffs between, about three minutes before it is dropped again. For all that time after the first 10 seconds the stall read choked or no-peers, Skip file disappeared and the reason flipped back once the seed was dropped, at every relaunch. WebSeedWorker now reports whether it was dropped and has neither verified nor refused a piece since (unproven), and the v1 swarm and v2 session loop count the running seeds that are, as StallSignals.unprovenWebSeeds. The watchdog keeps the missing pieces of the relaunch while that count is above zero, at least the old 10 seconds and at most RELAUNCH_MS, when seeds would start again anyway. A dead mirror thus keeps the earlier pieces missing until it is dropped again, a mirror that now has the file verifies a piece and ends the stall, and one that refuses again shows the pieces through the swarm. Since the grace may now last minutes, progressed() ends it: once a piece verifies or the selection changes (as when the user skips the file), what was missing at the relaunch is stale. Watchdog tests cover a seed unproven for three minutes (missing until it answers), the 10 second floor, the cap at RELAUNCH_MS and a selection change ending the grace. New v1 and v2 swarm tests hold a relaunched seed's request: the file stays missing well past 10 seconds, and the download finishes once the mirror answers with it.
… another leaves After a relaunch the watchdog keeps the pieces that were missing until the restarted web seeds answer, but a peer that connected since may hold them, so it should have its say at once. 90e5adfab compared the number of peers connected now with the number at the relaunch, so a peer that connected while another left did not count: with two peers lacking a file at the relaunch, one leaving and one holding the whole file arriving, the stall still read missing-pieces and offered Skip file for a file a connected peer had. The swarms now report how many peers ever completed their handshake, as StallSignals.joinedPeers: v1 counts a peer the first time its contact is added to connected, v2 when a peer becomes ready and joins the loop's peers. The watchdog records that count at the relaunch and keeps the earlier missing pieces only while it is unchanged, so any arrival ends the grace whatever left meanwhile. A watchdog test relaunches with two peers, then reports two peers of which one is new and nothing missing, and expects choked. New v1 and v2 swarm tests connect a peer lacking the file before the relaunch, hold the restarted seed's request, let that peer leave and one holding the file connect, and expect choked with nothing missing; all three read missing-pieces before this change.
POST /api/resolve let every failure reach the status pages' catch-all, so a source's refusal, such as a torrent with pieces larger than Ketch supports, came back as 500 internal_error, and RemoteKetch threw a RemoteApiException: the apps showed a server failure instead of the reason, and a URL no source handles was a 500 too, not the KetchError.Unsupported KetchApi.resolve promises. POST /api/resolve/content already answered both properly. Both routes now share respondResolved: an input no source takes answers 415 unsupported, a source's refusal 422 with the KetchError itself, its detail saying why. RemoteKetch decodes both for URLs as it did for content (resolveRefusal), so remote clients get the typed SourceError and its message; older servers still answer 500, which stays a RemoteApiException. Server tests resolve a URL a source refuses and one no source handles; remote tests decode each answer.
…at shutdown Shutting down `ketch server` with a torrent downloading and others seeding took 4.5 to 5 seconds when trackers were slow, right at the 5 s shutdown budget. Ketch paused the downloads first, and each paused torrent gave its trackers a full 2 seconds to hear `stopped`; only once the downloads had stopped did the torrent source stop its engine, which opened a second 2-second window for the seeders. Ketch now tells every source that it is closing before it cancels the downloads, through a new non-suspending DownloadSource.stopping() that does nothing by default. The torrent source opens its engine's stopped-announce window there and stops its seeders right away, each after saving its checkpoint, so their announces run alongside the downloads' within the same 2 seconds. stop() waits for them, stops any session that began seeding since, and then stops the engine, which keeps a window that is already open rather than starting another. With trackers that never answer, shutdown now takes about 2 seconds.
…lection saves A completed task gaining files, or a task waiting for its files, showed Queued before the record save that publishes its new selection. When that save failed, or its caller was cancelled while it waited for the store, the old Completed or Paused state came back. Followers that act on transitions took it for a new one: hooks ran their completed command or webhook again, and the apps announced the finished download, or the files it needed, once more. While Queued, the completed task also accepted cancel and pause, which it ignores while completed: a cancel during the save was undone when the selection queued the task right after. The task now shows a state of the kind it has before the save: a completed one its new size and a waiting one its new size as a paused task, and the queue shows it queued only once it takes it after the save. Taking it back after a failed save no longer changes its kind, and a completed task ignores cancel and pause until its selection is saved, as it did before.
A completed task whose seeder was being restored kept checking every file it had when the restore read the task, although the user dropped one meanwhile: Ketch handed the smaller selection to the source, but the source only changed a seeder once it was marked seeding, after the check. The check still needed the dropped files, often dropped because they were deleted or changed, so the restore ended without seeding: a v1 check found the pieces missing, which clears the task's intent to seed, and a v2 session refused the checkpoint's claim on a deleted file as it opened. A large torrent's check of files it no longer shares also takes minutes. The restore now opens the seeder with the task's latest selection when it only drops files, a selection saved while the seeder checks reaches it, which checks again with it, and one saved as it opened is read before the check. Once it seeds, the state its checkpoint saves into takes the selection it seeds, and the selection is read once more for one saved as it was marked.
…er one The selection a restored seeder reads once it seeds was read and then applied with no lock and no second look. A newer, smaller selection that Ketch applied while that call waited for the session landed first, and the older one then replaced it: the seeder shared a file the user had dropped, and the state its checkpoint saves into disagreed with the task, until the next selection change. The seeder now reads the selection again after each change it applies and applies it once more when it differs, until it holds, so the last selection saved is the one it seeds.
… once The docs said a file chosen again on a paused, queued, scheduled or failed task shows the verified pieces it kept at once. Only a paused task shows progress before it starts, and the saved checkpoint knows a deselected file's pieces only until the next run starts: its recheck drops their bits, v1 and v2 alike, so a file deselected before that run shows nothing until the task starts and checks its files again. The docs now say that a paused task shows at once the pieces its last run verified of a file deselected after that run started, and that other files show theirs once the task starts.
The stall watchdog took all payload a check found thrown away as having arrived before that check: it settled the waste against earlier checks first, and only what those did not cover came out of the check's own bytes. A fast web seed can send a whole corrupt piece and fail it within one check. When another seed's bytes were still waiting to be stored then, the take-back removed that seed's checks instead, and the corrupt bytes counted as payload that had just arrived. Once the waiting bytes were thrown away too, the take-back stopped inside the check that had replaced them, so the stall showed 20 s late: at 55 s instead of 35 s in the reviewed two-seed case. The same rule also took innocent payload: waste from before a verified piece, whose checks were cleared, came out of whatever else arrived in the check that found it, showing the stall early. Web seeds now say when what they throw away arrived. A stall check reads what was thrown away and marks itself in one atomic step (WebSeedStats.checked), and each run notes how much it had received by the latest check before its last bytes. A failed run's thrown-away bytes are taken as the last it received, so the part that arrived since that check is recent (StallSignals.recentWastedBytes). The watchdog counts none of it as the check's payload, and only the rest takes back earlier checks, newest first, as far as those whose payload may still be thrown away reach; nothing comes out of the check's other payload. Any payload thrown away still keeps the payload waiting to be kept from giving a piece its time again, as the settled count no longer says which of it is settled. The v1 swarm and the v2 loop read the counters the same way. Watchdog tests: the two-seed case (a stalled seed's pending bytes, a kept peer byte, whole corrupt pieces arriving and failing within one check, then the stalled seed's bytes wasted) stalls 30 s after the peer's payload, at 35 s; waste from before a verified piece takes none of a peer's later payload (the stall shows 30 s after it, not 11 s early); and a piece thrown away on arrival after a gap gives the payload still waiting to be kept no time again. Worker tests check the recent part of a corrupt piece's bytes across a check and after a verified piece. The field-pattern tests pass with the recent bytes their patterns imply.
AGENTS.md and the torrent guide said payload thrown away settles against the checks before and that what arrives with it, such as the next piece's first bytes, is never taken for it, as if the attribution were exact. They now say what the watchdog does: a web seed's thrown-away bytes are taken as the last it received, those that arrived since the check before never count, and the rest takes back as much of the payload earlier checks counted that could still be thrown away.
… stopped window Since seeders stop as Ketch begins to close, the torrent source's stop() waits for their stopped announces before it stops the engine, and only the engine's stop began removing the router's port mappings, with its own 2 seconds. With port mapping on, as it is by default, a router that never answers the removal (or a network going away at quit) kept shutdown at about 4 seconds with a download running, and doubled a seeder-only shutdown from about 2 to about 4, where the removal used to run beside the seeders' announces. The engine now starts removing the mappings for good when its stopped window opens, which the source does as Ketch begins to close, so the router forgets the port while the torrents say goodbye; stopping the engine waits for that removal instead of starting it, and no mapper starts once it began. Announces still name the mapped port, which the removal leaves as it was. A test hook hands the engine scripted gateways (portMapGateways), so the shutdown tests now run with port mapping on against a NAT-PMP router that maps the port but never answers its removal, with a download and a seeder and with a seeder alone; both stay near the one window. The NAT-PMP gateway fixture moved out of PortMappingTest so both tests share it.
As Ketch began to close, each seeder saved its checkpoint and only then paused, which sends its stopped announce. The save could take up to 5 seconds, writing the sidecar checkpoint and the task record while Ketch also flushes the paused downloads, but the announce window is 2 seconds from the start of the shutdown: a seeder whose save outlasted what was left of it found no time left and sent no stopped announce at all, so its trackers, private ones too, kept listing it as seeding. A seeder now pauses first, as a download run does before its last store, so it says goodbye within the window, and saves afterwards, which also records the counters it ended with. A test whose seeder takes 2.5 seconds to save checks that its tracker still hears stopped within the window and that the state is still saved.
…d when the engine stops Stopping the engine removed the router's port mappings without a word: a removal that worked, one a router never answered and one that timed out looked the same in the log, so a field test could not tell whether the router still forwarded the port after shutdown. The mapper's stop now logs once, at info like the line reporting the mapping, how many NAT layers confirmed the removal, naming only the port and the layer counts. A gateway confirms by answering (NAT-PMP, PCP) or by not faulting (UPnP); a UPnP fault 714, no such entry, counts as removed, as the router no longer holds the mapping. For the layers that did not confirm, or when the removal timed out, the line says they forward the port until their lease ends, or, where UPnP leased it permanently after fault 725, until the router drops it, as a lease of 0 never ends. Nothing is logged when nothing was mapped. The mappings a timed-out removal did not reach stay noted, as before. The tests cover a confirmed removal, logged once, a silent gateway, a timeout, a permanent UPnP lease the router will not remove and a router answering 714; the scripted UPnP gateway can now refuse leases other than permanent ones and fault on DeletePortMapping.
POST /api/resolve now answers a source's refusal with 422 and the KetchError itself, but released RemoteKetch clients only read error bodies as an ErrorResponse, which needs an error code. The bare KetchError has none, so they lost the reason they used to get from the 500's message and showed "HTTP 422: Unprocessable Entity" instead, as would the MCP tool and anything else reading the API that way. Both resolve routes now send the KetchError's JSON plus "error": "source_error": released clients read its message as an ErrorResponse's, and new ones decode the KetchError, ignoring the extra key. RemoteKetch reads a 422 as a KetchError only when its body is a JSON object with a type, and otherwise reports it as a RemoteApiException, as for a proxy's error page. A server test decodes the 422 body both ways; remote tests decode the new body and fall back for an HTML page and a body without a type.
Both resolve routes answered every KetchError.Unsupported with 415 "No download source handles this URL". Sources that take a URL raise Unsupported too: the HTTP engine for a server that answers its probe with the wrong range, for a custom client asked for a proxy, or for an https_proxy variable that names neither an HTTP nor a SOCKS5 proxy. Callers were told the link type is unsupported when the real cause was the server or the proxy setting. RemoteKetch also read any 415 as KetchError.Unsupported, including the unsupported_media_type the server answers for a body that is not JSON. SourceResolver now gives the Unsupported it throws when no source takes an input a NoDownloadSourceException cause, and the routes use the no-source wording only for that one. A source's own Unsupported answers 415 unsupported with "Not supported" and its cause's reason, leaving the reason out when it quotes a URL. RemoteKetch maps a 415 to KetchError.Unsupported only when its code is unsupported, and to a RemoteApiException otherwise. Tests cover the cause in SourceResolver, both messages on the server, and the other 415 bodies on the client.
…ter its handshake A source naming a v2 or hybrid peer that brought payload while it is being dialed brings its next dial forward once that dial fails without connecting, as v1 does. The candidate book applied it whenever the entry left DIALING through retry(), including closed(): the session loop closes a dialed peer it refuses after the handshake, with no room left or for another torrent, while the entry is still DIALING. The peer was reachable, so the naming said nothing new, yet its retry came 30 s after the dial and spent the five-minute allowance for bringing dials forward. closed() now clears the flag before retrying, so only a failed dial applies it. A candidate book test names a peer during a dial that the session then refuses, and checks it waits its usual two minutes and that a naming a minute later still brings the dial forward.
… dial as it was The v1 swarm applies a source's naming of a peer that brought payload, made while a connection to it ran, only when that attempt never reached the connected stage. No test named a peer while it was connected, so dropping that guard went unnoticed: a long-connected peer the DHT named would be dialed again at once when it dropped, as 30 s after its last dial lies in the past, and its five-minute allowance for bringing dials forward would be spent. A swarm test now names a peer that brought payload while it is connected, drops it five minutes later and checks it is dialed again 5 s later, not at once, and that a naming a minute after the drop still brings its next dial forward. Without the guard it is dialed again at once.
…that counted it The stall watchdog still guessed which checks had counted the web seed payload it found thrown away. It took a failed run's waste as the last bytes the run received, and took back the part from before the latest check from the newest checks still at risk. It kept checks by count: once the payload received, less what might still be thrown away, reached a check's total. That count treated thrown-away payload as settled, and peers' payload too. With two corrupt mirrors, a fast mirror's piece wasted within one check settled, by count, the checks that still held a slow mirror's pending bytes. Once those bytes were thrown away, nothing was left to take back, so the stall showed at 49 s instead of 30 s. Any waste also cancelled every pending restart of the piece clock, whichever source it came from. Web seeds now tell each check exactly what it counted. WebSeedStats.arrive tags each chunk with the number of checks before it, atomically with adding it to the next check's payload. Each response part tallies its bytes by those tags (WebSeedArrivals). A stored piece reports its tallies as kept. A piece that a failed run leaves unstored reports them as thrown away. WebSeedStats.checked hands the stall check one WebSeedLedger: the bytes that arrived since the last check, and the kept and wasted bytes by tag. The watchdog keeps one credit per check whose bytes are still at risk. Waste is taken back only from the check that counted it. A check's payload is kept as soon as some of its bytes are stored. Payload that comes back after a gap restarts the piece clock at that point, and only its own bytes decide that. Peers' payload now arrives separately (peerPayloadBytes) and is kept at once. The v1 swarm no longer adds web seed bytes to its peer counter, and the v2 loop counts its peers' payload itself. Both take the web seed share from the ledger, so each byte is counted in the check its tag names. Chunks are copied and tallied before the throttle wait, so a run stopped while it waits throws away all it tallied. WebSeedStats.unsettled is gone. So are the min() in fetch and the clamp in throwAway that guarded the old guess: a tally cannot report more than arrived. Credits merge only past 600 checks, the longest a piece may take, instead of 64. The watchdog tests now run pieces through a real WebSeedStats. The earlier field-pattern and two-seed scenarios keep their expected stalls. New cases cover: - the two corrupt mirrors, now stalled at 30 s; - a restart that another seed's waste does not cancel, and that does not wait for the check's other bytes; - a peer's payload that no longer settles another seed's pending bytes. v1 and v2 swarm tests deliver a corrupt piece within one check after a verified one, where only the no-payload clock can show the stall. They fail when a call site passes web seed payload without its tags, passes none, or drops the kept and wasted reports.
…from the checks that counted them AGENTS.md and docs/torrent.md still described the old heuristic. They said a web seed's thrown-away bytes were taken as the last it received, with the rest taken back from earlier checks, newest first. They also said payload back after a gap restarts the piece clock once none of it can still be thrown away. They now say that each web seed byte is tallied by the check that counted it, and that thrown-away bytes come back from those checks and never from another source's payload. Payload back after a gap gives the next piece its time again once some of it is kept: a peer's at once, a web seed's once its piece is stored.
…dbye Shutting down paused each seeder before saving it, so its `stopped` announces kept the window, but the record save began only once the pause returned: after the whole 2 s window when a tracker hangs on `stopped`, and for a v1 seeder after a second checkpoint write, as its pause writes the sidecar and saveResumeData wrote it again. On a slow disk the record landed past the 5 s KetchApi.shutdown waits before `ketch server`, `ketch mcp --standalone` and the desktop app exit, so the seeder's last minute of counters was lost. Each seeder now saves while it pauses: first its state as it is, read through the new TorrentSession.currentResumeData, which a v1 session encodes from its store without writing the sidecar or taking the lifecycle lock its pause holds (v2 already reads its store in memory), then, once paused, the state the pause left, when that differs, read the same way rather than written again. Both stay within SHUTDOWN_SAVE_MS. The slow-save shutdown test now waits as hosts do, the default 5 s, with saves of 3.5 s each, and checks that the record was saved before the shutdown returned while the tracker still heard `stopped`. A unit test checks that the save goes out while a gated pause is still under way and that the state the pause left follows it, and a session test that the v1 read neither waits for a pause nor writes the sidecar.
The removal log added in the previous round only looked at the layers of `current`, while stop() removes every mapping in `requested`, as #579 made it do: also those of a first pass, or of a newly found outer layer, whose request went out but whose pass never finished. With `current` empty nothing was logged, however the removals went, and with an inner layer mapped a confirmed inner removal was logged as "Removed the mapping ... through 1 NAT layer(s)" while the outer gateway's removal went unconfirmed. Those are the mappings a router most likely keeps forwarding, since nothing ever confirmed them either way. The log now covers what stop() removes: the requests, grouped by the layer they were asked of, a layer counting as confirmed only when every one of its removals was, and it is written whenever anything was asked for. Whether a mapping may outlive its lease comes from the request: one asked for with UPnP's lease 0, the 725 fallback included, is marked permanent before the request goes out, so a lease granted without a reply is named too. As an unconfirmed removal may also be one the gateway carried out, the lines now say the others "may still forward the port". A PortMappingTest stops a mapper during its first pass against a NAT-PMP gateway that grants and removes without replying, and a NatLayersTest stops one while the NAT outside the router maps silently after the router confirmed its layer; both logged nothing before and now say the port may still be forwarded, the second through 1 of 2 layers.
RemoteKetch.resolve turned every 415 `unsupported` into a bare KetchError.Unsupported. That dropped the reason the server now gives when the source that takes a URL lacks something it needs, such as a usable proxy, and with it the difference from an input no source takes. Apps on a remote device and the web app could not tell a proxy misconfiguration from an unsupported kind of link, and a server over a RemoteKetch (the desktop app's while `ketch server` runs the downloads) answered "Not supported" for a URL no source takes, where it used to pass on the server's wording. NoDownloadSourceException moves from library:core to library:api, its constructor reserved with @InternalKetchApi, so RemoteKetch, the server and the apps' common code, which the web app shares and which has no core, all read the same marker. RemoteKetch causes the Unsupported with it for the servers' "No download source" wordings, and otherwise with an IllegalStateException carrying the reason after "Not supported: ", or none when the server gave none. A server over a RemoteKetch then answers both cases as the first server did. KetchApi.resolve's KDoc, AGENTS.md and docs/api.md say what the cause means.
The add sheet called every KetchError.Unsupported a kind of link Ketch can't download, listing the schemes it supports, also when the source that takes an https link lacks something it needs, such as a usable proxy, on this device or a remote one. The user saw "it supports http(s)" for an https link and never the reason. It now says so only when no source takes the link: the Unsupported is caused by a NoDownloadSourceException, or by nothing. Any other cause shows the check-failed problem with the cause's reason and Retry, and a magnet or .torrent whose source lacks something no longer reads as a device without torrents. The app reuses the existing strings.
… saves Cancel and remove never wait for a task's control lock, so either could land while a task waiting for its files, or a completed task gaining files, saved its new selection. Once saved, the selection queued the task anyway: the queue showed it queued again and started it, undoing the cancel, and a removed task went on downloading outside the task list while its record came back. A cancel saved before the selection also had its record turned back to queued, which a restart would start. The queue now refuses a canceled task, as cancel and remove both show the task canceled before they stop it, and the selection's save keeps a canceled record canceled.
…r from seeding The docs said a dropped file, deleted maybe, never stops a restored seeder. That holds when the drop is saved before the restore opens the seeder or while it checks its files. A v2 or hybrid seeder missing a selected file fails as it opens, before any check, as its checkpoint's ownership no longer holds; it keeps its intent, and a drop saved after that failure takes effect the next time seeding is restored.
…dger has them WebSeedStats.throwAway raised the wasted total before it added the bytes to the stall ledger, in two atomic steps. A stall check made between them, once the total grew, missed the waste, which then went to the next check; the ledger tests, which wait for the total and then read the ledger, could fail now and then. The ledger now takes the bytes first.
The resolveUrl tool failed with an Unsupported error's own message, "Operation not supported by server", whatever the reason, so an agent could not tell a link no source takes from one whose source lacks something, such as a usable proxy. It now says "No download source handles this URL" for the first and "Not supported: " with the cause for the second. FTPS on a platform without TLS threw Unsupported without a cause, which the apps read as no source taking the link; it now says FTPS is not available on this platform.
…eads the selection A restored seeder reads the task's selection as it starts, not as it opens, so a drop saved between that read and the check does not reach a v2 or hybrid seeder that fails to open.
This was referenced Oct 18, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
This PR fixes what the next round of BitTorrent field tests found against real public swarms, after #570. That round covered rechecks and restarts, live file selection, web seeds and stalls, peer redial, local discovery, and shutdown. Each fix went through adversarial review, and the review findings are fixed in later commits.
Live file selection
restart-progress, v1 and hybrid, REST and/api/stream.downloadedBytesdropped for a moment. It now plans from the download's live segments.task.stateno longer pairs the new selection with the old progress.Stall reasons and web seeds
v1 endgame
Shutdown
stoppedannounces share one 2 s window, soketch serverstops within Ketch's 5 s shutdown. Before, it took 6 to 8 s with several torrents. Downloads paused before the engine stops still get their own window; the docs say so.Local discovery and limits
172.19.0.1.Found by the field re-run of this branch
The first build was field-tested again in four scenarios: selection progress, web seed stalls, endgame/shutdown/limits, and LSD between two instances. Confirmed:
What it found is fixed here:
stoppedwithin one 2 s window that starts when Ketch begins closing..torrentcontent keeps it.POST /api/resolveanswers 422 with the source's error, and older clients can still read it. It answers 415 only when no source handles the URL.resolveUrltool say which case it is.Test plan
:library:api:checkKotlinAbi,:library:api:jvmTest,:library:torrent:jvmTest,:library:torrent-api:jvmTest,:library:core:jvmTest,:library:server:test,:library:ktor:jvmTest,:library:hls:jvmTest,:library:dash:jvmTest,:library:ftp:jvmTest,:library:remote:jvmTest,:library:mcp:test,:cli:test,:app:shared:jvmTest:library:torrent:compileTestKotlinIosSimulatorArm64,:library:core:compileTestKotlinIosSimulatorArm64,:library:remote:compileTestKotlinIosSimulatorArm64