Repository navigation
fix(torrent): fix what the second field run of the torrent fixes found - #589
Merged
Merged
Conversation
…arts it Cancel and remove never wait for the queue, and the queue's start path checked for a cancel only once, before it saved the task as queued and before the coordinator saved and launched its execution outside its lock. A cancel landing in that window found nothing to stop and showed the task canceled, then the queue showed it queued again and the coordinator launched the download anyway: the task went from Canceled back to Queued or Downloading and kept downloading, as resuming a stopped torrent and canceling it right after did in the field. The coordinator now decides, saves and launches a start or resume under its lock, and cancel marks the task there until it shows it canceled. Either the cancel finds the execution and stops it, or the start comes second and refuses the task; the queue slot it took is freed as the cancel dequeues it. The queue's and a pause's saves keep a canceled record canceled, their state writes and the execution's progress reports never leave Canceled, and a cancel whose caller stops waiting still shows the task canceled.
Removing a task deleted its row from the store, but nothing stopped the task's record from being saved again afterwards: a download a racing start had launched failed on its deleted state and saved the task as failed, and a source saving its state or a caller still holding the task could do the same. The task was gone from the list, but the next start restored it from the store. Remove now deletes the row under the record's save lock and closes it, so any write after the removal saves nothing, and the task leaves the list right after.
A download that selected a file its source does not list, such as a hybrid torrent's padding file, was accepted and then failed as it started with "Unknown error occurred": the source's refusal was a plain IllegalArgumentException, which the coordinator wrapped as an unknown error. Clients could not tell what was wrong with their request. Ketch.download now refuses IDs the request's resolvedSource does not list at once, naming them, so REST callers get a 400 with the reason. A download without a resolution fails as it starts with a KetchError.SourceError whose detail names the IDs its resolution does not list, and any other refusal of the selection by its source, several variants of a single choice included, fails the same way with the source's reason.
POST /api/tasks answered a link no source handles with 400 bad_request, while the resolve routes answer the same link with 415 unsupported, so clients had to tell the two refusals apart by route. Such refusals were also logged as errors, and every failed download, a source's expected refusal such as pieces too large included, was logged as an error with a stack trace, which buried the failures that need one. Ketch.download's refusal of such a link is now caused by a NoDownloadSourceException, and the route answers it with 415 unsupported, "No download source handles this URL", as the resolve routes do; other invalid requests stay 400. An input no source takes is logged at debug, and a failed download is a warning with its cause chain unless it is unknown or a disk failure, which keep their stack trace.
…er looks stalled A download held by a low speed limit was reported stalled. Swarms added the time a payload chunk waited on the limits to their counter only once the wait ended, and a stall check counts at most the time since the check before, so it threw the rest away; a wait still running counted nothing. At 3 KiB/s a 16 KiB block waits over 5 s and was credited about 1 s, so 256 KiB pieces that take 85 s looked stalled after 64 s, and a single wait longer than 30 s looked like no payload at all. ThrottleClock now counts the time during which anything waits on the limits: waits that overlap count once, and a wait counts as it passes, so the signal never runs ahead of the clock nor lags a long wait. v1 peers and web seeds and v2 web seeds wait inside it, and the v2 loop counts as one wait while a peer's request waits for the limits, replacing the sum of its request delays.
… it restarts A source naming a peer we downloaded from again brings its next dial forward, at most once every five minutes, as the DHT names the same peers every minute. That limit was only lifted by time, so a peer that a bring-forward reconnected, which then sent data and restarted again within five minutes, was ignored when local discovery announced it back, and waited for its next scheduled dial or a stall's revive, a minute or more later. A connection that counts as the peer's first dial again, one that brought payload or lasted, now lifts the limit, in the v1 swarm and the v2 candidate book, so the limit only spans bring-forwards that never reconnected. The v1 redial test torrent gains a third piece, so a peer can send data over a bring-forward's connection without completing it.
…not up to 60 s A web seed request's idle watchdog compared a progress counter once per idle timeout, so data that arrived during one window only reset it at the window's end, and the request failed at the end of the next one: 30 to 60 s after the last byte. A mirror that sent its data at the start of a request and then hung held its pieces for a full minute. fetchRange now notes when the last chunk arrived and was handed over, and checks every tenth of the idle timeout (10 ms to 1 s) whether that long has passed with no chunk being handed over, so it fails within a second of 30 s after the last data. TorrentHttp takes the clock it follows, so tests run it on virtual time.
…eleting it keeps seeding In a v1 torrent a piece that holds the end of one file and the start of the next only verifies with all its bytes. A completed task stores every file in place, and removing a file from its selection left that file where it was without copying anything, so the pieces it shared with the files still selected lived only in it. Deleting the file afterwards broke those pieces: a seeder revoked them as peers asked and downloaded them again, and after a restart the seeder's check found the selection incomplete, reported the task as changed on disk and dropped its intent to seed for good. A deselected file kept in place now keeps an owned sidecar copy of each verified piece it shares with the selection, the mechanism partial selections already use: written as the selection shrinks, as such a piece is committed, and at each recheck (for a drop saved while no session ran), and never deleted as obsolete when the task completes. Once the file is deleted, a recheck and a seeder's reads take its span from the sidecar, so the task keeps seeding every piece of the files it kept.
…efore its pieces were kept A v1 file usually shares its first and last pieces with the files beside it. When the owner deleted such a file before removing it from a completed task, or before Ketch kept a copy of those pieces, its bytes were gone. The restored seeder's check then found the pieces it shares with the kept files unverifiable, called the whole task changed on disk, did not seed, and cleared the task's intent to seed for good, although every other piece of the kept files was intact. A seed-only session whose check misses only such pieces now sets them aside: each must hold bytes of a deselected file that is gone, cut short or never kept in place, with no sidecar that verifies, while the selected files it spans hold their part. Set-aside pieces are neither wanted, verified nor offered to peers, so the rest completes the selection and the session seeds it, keeps the intent, and logs a warning naming how many pieces it cannot serve. Trackers never hear `completed`, as a file is left out. The pieces are wanted again at the next check, or once the selection adds a file, whose download fetches them. Any other missing piece still stops the seeder as changed on disk.
`ketch <url>` printed "Download failed" on stdout and still exited 0 when the download failed, so a script could not tell a failed torrent from a finished one. A link no source handles was worse: Ketch.download's refusal escaped main as an uncaught exception with a JVM stack trace. The download now runs in downloadUntilDone, which returns the exit status: 0 once the download completes, 1 when it fails or Ketch refuses it (a link no source handles, a proxy or checksum it cannot use), with the reason on stderr and no stack trace, as --list-files already does.
`ketch --list-files gopher://...` said "Couldn't list the files: Operation not supported by server", the message every KetchError.Unsupported has, after an ERROR line from the source resolver. The server and MCP each had a helper that tells a link no source takes from one whose source lacks something, such as a usable proxy. That wording now lives in one place, KetchError.Unsupported.reason() (@InternalKetchApi in library:api), which the server's resolve routes, MCP's resolveUrl and --list-files use, so the CLI says "No download source handles this link". It keeps the server's rule of leaving out a cause that names a link, as links may hold credentials. The resolver logs an input no source takes at debug, since it is a link someone typed and the caller reports it.
Every `ketch add` or `ketch list --server` started with Ktor's INFO line naming the engine it picked among those on the classpath, as RemoteKetch builds its client without one, and every refused call printed a RemoteKetch WARN line ahead of the command's own error saying the same. The CLI's logback.xml keeps Ktor's engine-choice logger, named HttpClient, at WARN. RemoteKetch and RemoteDownloadTask log the HTTP errors they throw at debug, as their callers get the RemoteApiException with its status, code and message and report it; the event stream's own connection failures still warn.
Ktor's OkHttp engine gives each client a fresh okhttp3.Dispatcher and enqueues every call on it, so OkHttp's defaults applied to every HTTPS request Ketch makes on the JVM and Android: 64 requests at once and 5 per host. A call counts from its start until its response headers arrive (the body streams after the dispatcher lets it go), so a download's sixth segment request to a host waited for one of the first five to get its headers, and with a server slow to answer, or trackers that never do, later requests sat in OkHttp's queue, such as the stopped announces a torrent sends while it shuts down. Ketch's OkHttp clients now get a dispatcher of their own that lets 256 requests run at once, to one host too, as many as response bodies stream: Ketch already chooses how many connections a download opens and how many downloads share a host.
…it reschedules Rescheduling a running task pauses it and joins the stopping run, which can take seconds, and then saved the task as SCHEDULED, showed it Scheduled and launched a wait that enqueued it later, all without looking at whether a cancel or remove had landed meanwhile. A canceled task then showed Scheduled and downloaded again when its time came; a removed one ran a download that was in no list, could not be stopped and kept its queue slot until the next restart. The scheduler now leaves a CANCELED record and a Canceled state as they are, launches no wait for a canceled task, and checks again before a wait enqueues. Cancel and remove drop a wait a reschedule launched as they landed once the task shows canceled, so none lingers.
…ut of its slot When a cancel landed while the queue saved a task as QUEUED, markQueued kept it canceled, but enqueue still put it in the queue, promoted it and, for an URGENT task, preempted the running download with the lowest priority, only for the coordinator to refuse the canceled task. The pushed-out download stopped and started again, from zero for a server without ranges, or with a recheck for a torrent. enqueue now stops right after markQueued when the task shows canceled, before it takes a place, a slot or another task's slot.
… gets a slot back As the queue gave a preempted task its slot back, startTask read the state, saw Paused and then wrote Queued in a separate step. A cancel runs on the caller's thread without the queue's lock, so a Canceled written between the read and the write was replaced: the task showed Queued while its record said CANCELED, or, once the cancel had finished, started again and saved QUEUED over the CANCELED record. The write is now one atomic update that only turns Paused into Queued, so a Canceled state stays and the coordinator refuses to start the task.
A failed download is logged as a warning with its cause chain and no stack trace unless it is KetchError.Unknown or Disk. The torrent source reports any unexpected exception, such as an IndexOutOfBoundsException while it sets up a selection or storage, as a SourceError, so such a bug reached the log without a frame to debug it from. DownloadCoordinator.fail now also logs an error with the trace when the failure's root cause looks like a bug: an Error, or a RuntimeException other than an IllegalArgumentException (a refusal) or a cancellation (a timeout). Expected failures keep the one-line warning, also those that carry a cause: a source's refusal wrapping an IllegalArgumentException, an I/O error, or a stalled transfer's TransferStalledException.
…load later thrown away Stall checks count the time payload waits on speed limits as progress, as it passes, so a low limit never looks like a stall. That time is credited before anything shows whether the payload will be kept, and is never taken back: a web seed's bytes wait after they arrive and a v2 peer's requests before they are sent. A mirror that sends only corrupt pieces under a 3 KiB/s limit therefore shows a stall only once it is dropped after five failed runs, about seven and a half minutes in, though its first corrupt piece is known after about 85 seconds. Taking the waits back exactly is not possible with what the checks know: waits overlap one another, a peer's among them, and the times they moved have moved since for other reasons, so taking back too much would make a slow but healthy download look stalled again. The trade-off is now written down beside TorrentStallWatchdog.waited(), in docs/torrent.md and in AGENTS.md. New WebSeedLowLimitTest cases run a v1 swarm and a v2 session against a mirror serving another build of the file under a 3 KiB/s limit, and check that the stall shows by the time the seed is dropped, within half a minute of its five runs. The test clock limit moves to a shared ClockLimit helper, which also says whether a call is waiting so the clock can move faster while it does.
…talled, and one gone silent does The v2 session loop counts as one wait on the speed limits while a peer's request waits for them, which keeps stall checks from taking a low task limit for a stall. Nothing exercised that path: no v2 test ran a connected peer under a download limit while watching for stalls, so a toggle that never entered, or never left, the throttle clock would have passed every test. TorrentV2LowLimitTest downloads a 256 KiB piece from one seed over loopback TCP under a 3 KiB/s task limit on a test clock, so each 16 KiB request waits over five seconds and the piece takes 85 seconds, longer than a stall allows for a piece. When the seed answers everything, no stall shows before the piece verifies; without the loop entering the clock it stalls at 64 seconds. When the seed stops answering after four blocks, the loop still requests every block, and the stall shows within 30 seconds of the last request, once nothing waits; with a loop that never leaves the clock it never shows.
This reverts commit 56ccd2a45a56c3043a8fc0011cbefb389cd60c74. The copy it added did more harm than the case it covered. A recheck healed a shared piece from its sidecar into every file that stored it in place, deselected ones included, so a deselected file the user edited afterwards had the torrent's original bytes written over its start or end. The copy was only made while a v1 store was live as the selection shrank, or at that task's next check, so a completed task that was not seeding when a file was dropped kept nothing, although the docs promised that deleting the file later changed nothing. And each copy was a whole piece written under the store's mutex, holding up the session's reads and commits and the caller's selection change for as long as it took, and hashed again at every check. The later change that sets such pieces aside stays: a seed-only session whose check misses only pieces it shares with deselected files whose bytes are gone seeds the rest, keeps its intent and never announces completed. The docs now say a removed file keeps its part of those pieces, and deleting it sets them aside.
…he owner changed A v1 piece that holds the end of one file and the start of the next stores each span in its file. Once a file was deselected it stayed in place, and the store still wrote into it: a piece it shares with the selection was downloaded again into it, and a check healed such a piece from its sidecar into every file in place. A deselected file the owner edited afterwards, such as a tag editor rewriting a header, was overwritten with the torrent's bytes. A restored seeder that found such a piece unverifiable also called the whole task changed on disk and cleared its intent to seed, because the edited file was still there at its full size. The store now never writes a deselected file. A piece stored while one of its files is deselected keeps that file's span in the piece's sidecar, and reads take the span from there while the sidecar is owned; a check heals only selected files, and a sidecar a deselected file spans is kept when the task finishes. Choosing the file again copies those spans into it, as for a file that was never in place. A seed-only check now sets a missing piece aside whenever it spans a deselected file and the selected files hold their part, whether that file is gone, cut short or changed, so the task keeps seeding the rest and keeps its intent.
…oes while it seeds A restored seeder sets aside the pieces it shares with a deselected file that is gone or changed only as it checks its files. When the owner deleted or edited such a file while the seeder ran, a peer's request for one of those pieces found it unreadable, or no longer matching its hash, and the store wanted it again. The swarm then saw its selection incomplete and turned the seed-only session into a downloader: the task stopped showing Seeding, and as the user is often the only seed, it waited for a piece nobody had until Ketch restarted. A seed-only store whose selection is complete now sets such a piece aside right there, as the check would: it is neither wanted nor verified, so the selection stays complete and the session stays SEEDING. The revocation tells the swarm, whose scheduler forgets the piece rather than fetching it again, and new peers never see it in our bitfield. A piece whose selected files changed is handled as before, and sessions that download, lent seeders included, keep wanting revoked pieces.
…ay what is set aside The tests opened a restored seeder with the dropped file already left out, so the order the field report saw was never run end to end: the owner deletes a file, a check of every file creates it again empty and stops, and the next check is interrupted by the drop, which the session applies by stopping the check and starting it again. A source test now holds the engine's storage so that check waits, delivers the drop while it does, and checks that the seeder seeds and offers every piece but the two the dropped file shares, leaving that file empty. Another drops an owned file while the task does not seed, so no store sees the drop, deletes it and checks the same. The docs now say precisely what happens: a removed v1 file is never written again; deleting or changing it sets aside only the shared pieces that no longer verify, found as seeding checks its files or as a peer asks for one; the task keeps seeding the rest, while one still seeding right after its own download downloads such a piece again; and choosing that file, or any other, downloads them again.
…ystem proxy too OkHttp's call dispatcher, 64 requests at once and 5 per host by default, had its limits raised only in clients built by okHttpClient(route, ...). Android's unbound engine, which the app's downloads and the torrent source's trackers and web seeds use, sends requests under the system proxy through a client of its own, which still had the defaults: a download's sixth segment request to one host waited for an earlier one's headers, and announces queued behind those to trackers that never answer. Every OkHttp client the engine builds now comes from one okHttpClient() helper, which sets the raised call dispatcher, the HTTP threads, the connect timeout and no redirects, and Android's system proxy client is built by it. An Android host test sends 80 requests at once through that client to a server that holds back its answers, and CI now runs the ktor module's Android host tests.
… downloads A failed `ketch <url>` ended with `Download failed: <message>`, and a KetchError's own message is only a summary such as "Network error occurred" or "Operation not supported by server", so the line did not say why. The command also logged at info, so Ketch's records crowded the progress line, unlike --list-files, update and the commands that work on a running instance, which log only warnings unless -v or --debug asks for more. The summary now names the error's causes (describeCauses()), or what the source lacks for KetchError.Unsupported (reason()), and `ketch <url>` logs at the level the other commands use, now one quietLogLevel() for all of them. Tests fail a download with a host that does not resolve, logged as the command logs it, and with a source that lacks something; the README, the logging guide and AGENTS.md say which commands log only warnings.
… trace RealFtpClient logged a connection that failed, such as one the server refused or a host that cannot be reached, as an error with its stack trace. Such a failure is an expected network error that the download retries, so `ketch ftp://...` against a server that was down printed a stack trace on stderr for every attempt before saying why it failed. It is now one error line naming the cause chain, as KtorHttpEngine logs its network errors. A JVM test connects to a port nothing listens on and checks the record has no throwable.
…ent-field-round4 # Conflicts: # .github/workflows/tests.yml
…e selection test remoteSelection_liveExpandPauseShrinkAndReopen waited for a completed state with the reopened selection's size, but a completed task that gains files shows that size still completed while its selection saves, before the run that downloads the added file starts. On a slow CI runner the test read file 2 before it existed (NoSuchFileException: f2). It now waits for a completion newer than the one before the reopen.
…s cancelled The queue paused an urgent task's victim, joined its stop, and only then took it out of its slot and put it back in the queue. All of that ran in the caller's coroutine, which could be cancelled during the join: a scheduled urgent task's wait is cancelled when the task is canceled, and a REST resume is cancelled when its client leaves. The victim then stayed in the queue's active slots, shown paused for preemption, with no execution. Its resume did nothing, since the queue saw it active, and every other task waited for that slot until Ketch restarted. A start the queue made had the same gap: a caller cancelled while the coordinator was busy left the promoted task holding its slot, shown queued, with nothing running. From the victim's pause on, the preemption now runs under NonCancellable, and so does the coordinator call that starts or resumes a task taking a slot. A canceled urgent task gives the slot back to the task it pushed out, and a promoted task runs even when the caller gave up.
Rescheduling a running task pauses it first, and the run can complete just before the pause takes the coordinator's lock: the pause then keeps Completed, as it should. The scheduler only guarded a canceled task, though, so it went on to save the COMPLETED record as SCHEDULED, show the task Scheduled and launch a wait. When the wait ended the queue started the finished task again: it downloaded once more, beside its completed file, and the user saw a completed task go back to Scheduled and then Downloading. A reschedule now keeps every ended task as it is, completed and failed as well as canceled: its record and state stay, no wait is launched for it, and a wait that finds its task ended enqueues nothing.
…lost piece again The lent-seeder test changed the selection only while the task was listed as seeding, so the branch of changeSeedingSelection that reaches a seeder through its watcher while it downloads a piece it lost again decided nothing: reverting it left the suite green, though that is the path that keeps a deselected file from failing the seeder's storage once it is edited. The test now waits until the seeder downloads the piece again and is no longer listed as seeding, holding the scripted peer's HAVE and blocks back, drops a file then and checks the session takes it before the piece arrives. The edit of that file afterwards only revokes its piece. With the watcher branch reverted the session keeps the old selection and the test fails.
…er is asked again A v1 worker that asked a peer again for a piece it had refused a minute before told the scheduler at once that the peer no longer refused it, so the stall check counted the peer as a source again until it had rejected a whole piece's worth of blocks once more. With large pieces that takes many round trips, and every second check in between published another reason with no missing pieces, then missing pieces again: the stall notice and its Skip file flickered about once a minute, each change logged at info. A refusal that lapses now moves the piece to a probing set: the worker asks the peer for it again, while the scheduler keeps counting the peer as refusing it until the peer sends a block of it, announces it or unchokes us again. A peer that rejects it once more refuses it again without the scheduler hearing of any change.
…ied again are v1's The Fast extension section said, for every connection, that a refused piece is asked for again once the peer announces it or a minute passes, and that Ketch announces a piece it lost and verified again. Both hold for v1 torrents only: v2 and hybrid sessions announce each piece once and lift a peer's refusals only when it unchokes them again, and their stall check counts no refusal as missing. AGENTS.md now says so where it describes refusals and the HAVE log, and its stall reasons include the v1 refusal rule for missing pieces. The seedLatestSelection KDoc also still said a selection reaches a seeder only while it checks or seeds; it reaches one its watcher follows too, as it downloads a piece it lost again.
… heard it stop Since a torrent's `stopped` announces run detached in the engine, nothing ordered them before the next `started` of the same torrent: a task paused and resumed at once, or retried after a second, announced `started` while its `stopped` was still on its way. A tracker that applies announces out of order, as busy multi-worker ones may, applied the `stopped` last and dropped the peer, which other peers then could not find through it until its next regular announce, often half an hour later. The engine now keeps each goodbye by the topics it stops (KotlinTorrentEngine.sayGoodbye), and a v1 or v2 owner's tracker discovery, its own tiers, extra trackers and a private hybrid's tracker group alike, waits for those of its topics (awaitGoodbyes) before its first announce. They end within the 2 s stopped window, so a resume waits at most that long to announce; pausing, canceling and removing still return at once.
…ngine A tracker-only magnet lookup announced `stopped` inline, within its 2 s bound, before it ended. A v2 (btmh) lookup runs in the engine but its caller joins it, so pausing, canceling or removing such a task still waited up to 2 s on a tracker that never answers, unlike everything else a task stops. A v1 lookup that found its metadata held its caller the same way before handing it over, and nothing ordered a lookup's `stopped` before the next `started` for its hash, such as a lookup asked again at once. Both lookups now hand their `stopped` to the engine (sayGoodbye) under their topic, and each of their `started` announces first waits for the goodbyes of that topic (awaitGoodbyes), as torrents do. A lookup that is canceled or done returns at once, and the download that follows one announces `started` only once its trackers heard the lookup stop.
…seconds When the last task or preview waiting for a btih magnet's metadata lookup left, the lookup was canceled at once. A caller that came back a moment later started a new lookup and lost the DHT and tracker peers the first had found and any metadata it had partly received: a magnet task paused and resumed at once, or the download of a link the add sheet previewed, which reaches the lookup only after the sheet closes and gives the preview up. A lookup nothing waits for now goes on for ABANDONED_LOOKUP_GRACE (5 s) before TorrentMetadataCache cancels it, and a caller that joins it meanwhile carries on with it. It keeps its place among the 16 lookups the engine runs until it ends, so new lookups past the bound wait for its grace too. KotlinTorrentEngine takes the grace as a test hook.
TorrentV2Speed was tested on its own, but nothing checked that a v2 or hybrid task reports it: putting back the one-second sample, or the session's downloadSpeed (always 0 for v2), in TorrentDownloadSource.track kept every test passing. TorrentSourceSpeedTest runs a v2 download through the source against a seeding engine on loopback, under a 5 KiB/s task limit without a burst, so its 16 KiB blocks arrive 3.2 s apart, and samples the speed the task reports every 100 ms. From its first piece to the end, every reading is within a fifth of the limit; either old reading fails it, with 0 B/s a second after a block.
…val that keeps it The run that kept its partial file flushed it before closing it whatever stopped it, so Ketch.close() and shutdown() waited for an fsync of every engine-written file before the sources could stop: on a slow disk with gigabytes of dirty pages, shutdown's 5 s ran out before the torrent source saved its seeders' checkpoints and told trackers it stopped. A failure likewise waited for the fsync before the task showed Failed and gave up its queue slot. Neither flushed before the run took over the pause's flush. A pause, reschedule or preemption and remove(deleteFiles = false) now mark the execution (flushKeptFile), as a discarding cancel marks it with discardPartialFile, and the run flushes the file it keeps only when marked. A close or a failure closes it unflushed, as before.
…last flush The run marked its file flushed before its last flush ran. A pause landing while that flush still waited for a disk thread cancelled it before it ran, and the run then closed the file without flushing it in cleanup either, though the paused record's segments counted every byte; after a power loss, a resume would complete over bytes that never reached the disk. The run now counts the file flushed only once its last flush returns, or once that flush failed and its progress was discarded, so a pause that cancels the flush gets the file flushed as the run closes it.
…e its completion Nothing tested the half of the completion claim where a pause's claimStop wins: with the test dispatchers, the cancel always surfaced at the final flush or the checksum read first, so a run that completed anyway, or waited for a cancel while not cancellable, passed every test. A file accessor now pauses the task from inside the run's last flush, without suspending, so the run reaches claimCompletion already claimed. The test checks that the task ends Paused with the whole file under its partial name and none at the final name, and that a resume completes it without downloading it again.
… design The helper devices proposal still described DownloadCoordinator.pause flushing the file right after job.cancel(), in §9.7's durability order and in hazard 2 of its table, though the pause no longer touches the file: the run flushes the file a pause or remove(deleteFiles = false) keeps in cleanupAfterExecution, after its final save, and a failure or Ketch.close() closes it unflushed. Both now say so. The AGENTS.md selection paragraph had a line of 114 columns; it is rewrapped to 100.
`ketch <url>` and `ketch update` cleared their progress line with a carriage return and spaces before every log record and drew it again after it, whatever stdout was. Captured to a file or a pipe, as with `ketch -v <url> > debug.log`, the output keeps those characters: every record line began with the progress text, a carriage return and a run of spaces, which editors and issue trackers show as junk lines and `less` as `^M`, roughly doubling a verbose log. ProgressLine now writes over its line only when stdout is an interactive terminal: the JVM has a console, and from JDK 22, where a console may stand for redirected streams, Console.isTerminal says it is one. Elsewhere the progress goes on lines of its own, at most one every five seconds as updates come several times a second, and records and other lines are printed as they come. The line is also flushed when it ends, so an error that follows on stderr starts its own row whatever the stream buffers.
The lock that keeps progress updates and log records apart was only exercised from one thread: the integration test logs from the coroutine that also prints the progress, and the other ProgressLine tests are single-threaded, so dropping `synchronized` from show() or above() failed no test, although the defect it fixes is records from Ketch's worker threads meeting the monitor's updates. A test now writes 20,000 updates of varying length from one thread while four others log 500 records each through Logger.above, to stdout and stderr, and checks the rendered terminal: every row but the last is exactly one record, each record appears once, and the last row is one progress line. Without the lock in show() alone it fails on every run.
`ketch update` writes its download's progress over a ProgressLine, wraps the downloading engine's logger so records go above it, and ends the line in a finally block so the error `runUpdate` prints next starts its own row. None of that ran in a test: dropping the wrapper or the finally block would have put a retry's warning, or the reason the update failed, back on the end of the progress line unnoticed. The download step is now `downloadWithProgress`, which takes the line, the logger and the HTTP engine, and two tests run it over an engine that sends half the archive and waits for the progress to show: one drops the connection once, so Ketch warns that it retries, and checks that every record takes a row of its own above the progress line; the other sends content that does not match the checksum and checks that the error printed after the failure gets a row of its own.
The engine now logs transport failures, 5xx and 429 at debug level, since callers retry them and report the failure they give up on. But those reports name only the task and the error, such as `Http: HTTP error 503: Service Unavailable`, never where it happened: a download whose redirect led to a mirror that answered 503 on every attempt, or whose redirect target failed its TLS handshake, said at the default levels which status it got but not from which server, which only the engine's per-attempt errors had said. The engine's errors now carry the request that failed as a cause, a FailedRequest whose message is the method and the URL it went to after redirects, passed through redactUrl. The retries' warnings, the Coordinator's "Download failed" line and the one-line reason `ketch <url>` prints all describe the cause chain, so they now say where it failed, while each attempt is still logged at debug level only. An engine built with logRequests = false, as the torrent source's trackers use, adds nothing, as its URLs may hold a passkey. What an onData callback throws stays the direct cause of its KetchError.Network, which GitHubReleases looks for, marked on its way through the exchange so it is not mistaken for a failure of the request.
A v1 peer that rejected a piece block by block within its first minute kept it refused even when it then answered a request it still owed for that piece: only a piece whose refusal had lapsed into `probing` was lifted by a block. A Ketch uploader out of serve credit does exactly that, so the stall check went on calling the piece missing and offered Skip file for a piece the peer was sending, and the peer was not asked for its other blocks until the minute passed. A block of a piece now lifts it from `refused` as well as `probing`, as docs/torrent.md says. The refusal test drives its peer through actions, so it can hold requests back and lift a refusal at a chosen moment: it now checks that the stall stops naming the piece once the peer sends a block it still owed within the minute, and once the peer sends a block of, announces or unchokes the swarm again for a piece whose refusal lapsed, each of which fails without its lift.
remove(deleteFiles = false) marked its run to flush the partial file it keeps, so a removal waited for an fsync of everything the download had written, under NonCancellable, before the task showed Canceled and the queue freed its slot. On a slow disk with gigabytes of dirty pages a REST DELETE or an MCP removeDownload hung for tens of seconds, and the flush made nothing durable that anyone reads: cancel() saves the record without segments and Ketch.remove drops it, so nothing resumes from that file. Only a pause, which also covers reschedule and preemption, marks a run to flush its kept file now; a removal that keeps the file closes it unflushed, as a failure and Ketch.close() do. The KDocs, AGENTS.md and the durability section of the multi-instance design say so, and the coordinator test checks that such a removal closes the file without waiting for a disk that never finishes a flush.
A btih magnet lookup that nothing waits for goes on for its grace, so when Ketch shut down, a tracker-only lookup left by its task's pause was still running as the engine stopped. The engine completed its goodbyes job first and only then cancelled the lookup with the rest of its scope, so the `stopped` the lookup handed over on its way out was launched into a finished job and never sent: a private tracker kept listing us until it timed us out. A v2 lookup a preview still waited for lost its `stopped` the same way. The engine's stop now closes the metadata cache and cancels the v2 lookups beside its sessions, before the goodbyes stop taking new ones, so every lookup, one in its grace included, says `stopped` within the shared window. The cache runs its fetches under a job of their own, and its close cancels and waits for all of them, also one whose grace has just ended and that is still on its way out, rather than only those it still lists as pending.
…overs A btih lookup that nothing waits for goes on for a few seconds, and a caller arriving meanwhile carried on with it whatever its link named. The cache keyed lookups by hash and privacy alone, so the new caller's own lookup, with its trackers and explicit peers, was dropped: a link added again with a working tracker after one without any kept waiting on the old lookup, which never asked that tracker, until its two minutes ran out. Each pending lookup now records where it looks besides what every lookup of its hash asks (LookupSources: its link's usable trackers and, outside tracker-only lookups, its explicit peers). A caller arriving within the grace carries on with the lookup only when that lookup asks every source the caller's link names. Otherwise the cache cancels the left lookup at once and starts the caller's in its place, once the left one has ended, so its trackers hear the left lookup's `stopped` before the new one's `started`. A caller joining a lookup that others still wait for shares it as before. Web seeds stay out of the comparison: they find no metadata, and each caller's own are added to what was found.
… caller The torrent guide and AGENTS.md said a btih magnet's lookup goes on for 5 s once it is left, so a task resumed meanwhile keeps its peers. Only the lookup of the torrent's info does: a btmh magnet's lookup, and the lookup of the piece layers a btih magnet of a hybrid torrent needs next, run outside the shared cache and stop the moment their caller leaves, so a task paused and resumed starts them over with nothing they gathered. Both now say so.
FailedRequest, the cause through which the engine's errors say where they failed, held the whole URL after redirects, passed through redactUrl. That is more than a log needs, and it does not stay in logs: the updater words its failures with describeCauses, which the desktop and Android apps show in Settings › About and `ketch update` prints. A release file's redirect target is a signed link whose query runs to hundreds of characters and holds tokens redactUrl does not recognize, such as a `jwt`, so an update that failed there showed a live token in the app. FailedRequest now names the method and the scheme, host, port and path the request went to, never the URL's user information, query or fragment, which still says which server and file failed. The updater's tests now run a real KtorHttpEngine over a mock client, so they get its errors as they are.
AGENTS.md, docs/logging.md and the engine's KDoc said that its errors name the request that failed, excepting only engines that do not log requests and what an onData callback throws. Only the errors for HTTP error statuses and transport failures do. Those the engine raises itself on a response it refuses, such as another range than it asked for, a body shorter or longer than the range, one over the size limit or a redirect it will not follow, and after too many redirects, name none. Attaching the request to them is not a small change: KetchError.Unsupported.reason(), which the server's answers, `ketch <url>` and the apps show, reads the direct cause's message and leaves it out when it names a link, so a FailedRequest there would turn "Not supported: Server returned a different range" into "Not supported". The documents now name the errors that carry the request and those that do not.
…a terminal too ProgressLine writes over stdout's line only when stdoutIsTerminal says stdout is a terminal, which asks System.console(). The JVM has a console only while stdin and stdout are both terminals, and from JDK 22 Console.isTerminal checks both too, so a command run in a terminal with its input redirected, as `ketch <url> < /dev/null` or one in a `while read` loop over a file, prints a new progress line every 5 seconds instead of updating one. AGENTS.md said only a terminal is written over and that output captured to a file or pipe gets plain lines, which reads as if only stdout were checked. The KDoc of ProgressLine, ProgressLine.stdout and stdoutIsTerminal and the AGENTS.md CLI bullet now say that stdin must be a terminal too, and what happens when it is not.
The refusal tests moved the test clock in real-time steps and read the published stall at once. On the macOS CI runner the swarm had not checked itself at the new time yet, so refusedPiece_refusedAgainAMinuteLater_staysMissingThroughout began collecting while the stall was still null and failed on [null, MISSING_PIECES]. The stall assertions now wait up to 5 s of real time for the swarm to publish the stall they expect, and that test starts collecting once the piece reads missing, so it still fails if the reason ever leaves missing-pieces.
…piece 1 The scripted peer let the refusal tests start once the swarm had been quiet for 300 ms after a rejection of piece 0, which on the macOS CI runner could come before the swarm had asked for and received all of piece 1. Those blocks then arrived while the test moved its clock, counted as payload at a later time, and the 30 s no-payload stall was not there yet at the 35 s the test checks (Stall: null). The peer now reports the refusal only once it has also sent every block of piece 1, so all the payload arrives before the clock moves.
The swarm checks for a stall once per second of its clock and counts payload from the first check that sees it. The refusal tests moved the test clock 5 s every 150 ms, so on a slow runner the swarm checked only steps later and counted the payload it got at the start as arriving at 5 or 10 s: the 30 s no-payload stall was not there yet at 35 s (macOS CI, Stall: null). The clock now moves 1 s at a time, and the swarm first checks at 1 s before the clock moves on, so payload counts from when it came. The in-minute block case is checked at 75 s for more room.
… not within 1 s TorrentTaskStopTest asserted that cancel, pause and remove return within 1 s, to show they no longer wait for the 2 s `stopped` window; on the Windows runner a remove, which also deletes the task's files, took 1.14 s. The test now checks what it means: when the stop returns, the tracker's `stopped` announce is still waiting, which a stop that waited for its window could never see.
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 fixes what the second field run of #587's build found against real swarms and local scripted mirrors. That run covered selection changes on stopped tasks, stall timing with corrupt and slow mirrors, shutdown and resolve errors, and redial between two instances. Each fix went through adversarial review.
Cancel and remove stick
Ketch.downloadrefuses IDs its resolution does not list.POST /api/tasksanswers 415unsupportedfor a link no source handles, as the resolve routes do. No-source refusals log at debug. Expected typed failures log at warn without a stack trace.name (1).extbeside the finished file.Torrent timing
ThrottleClock). Before, only the last second of each finished wait counted, so a 3 KiB/s limit read as "no-peers" while payload arrived at the limit.v1 seeders and deleted files
completed. Before, it refused to seed and lost the intent, or a running seeder turned into a stalled download.CLI and HTTP
ketch <url>exits 1 when the download fails or is refused, and says why on stderr with no stack trace. While it downloads it logs only warnings unless-vis given. It no longer crashes on a link no source handles.ketch <url>shows why a torrent stalls on a line of its own when the reason changes. The progress line stays within 80 columns. A source error's reason is printed once, with the causes it does not already say.ketch --list-filessays when no download source handles a link, and why any other failure happened. That wording,KetchError.Unsupported.reason(), is now shared with the server and MCP.Found by the field run of this PR's build
That run checked:
Confirmed:
Fixed here:
sharing=true.unknown.stopped.Pausedflashes beforeCompletedwhen a pause lands as a download completes anyway.PUT /filesnames the unknown file IDs.Review follow-ups:
startedagain only after its trackers have heard it stop.Test plan
:library:api:checkKotlinAbiand the suites of api, torrent, torrent-api, core, server, ktor, hls, dash, ftp, webdav, metalink, remote, mcp, cli, updater and app:shared, on this branch over currentmain