Skip to content

fix(core): stop downloads and sources before closing the HTTP engine - #573

Merged
linroid merged 2 commits into
mainfrom
fix/awaited-shutdown
Oct 17, 2026
Merged

linroid merged 2 commits into
mainfrom
fix/awaited-shutdown

Conversation

@linroid

@linroid linroid commented Oct 17, 2026

Copy link
Copy Markdown
Owner

Why

Field tests of #570 restarted ketch server with SIGTERM and found that Ketch.close() waited for nothing:

  • DownloadCoordinator.close() cancelled the executions and returned their job without joining it.
  • TorrentDownloadSource.close() only asked KotlinTorrentEngine to shut down, asynchronously.
  • Ketch then closed the shared HttpEngine straight away.

As a result, torrent sessions' stopped announces failed with "HTTP engine is closed" within milliseconds of "Closing Ketch". The CLI's shutdown hook also returned before the cancelled executions' NonCancellable cleanup ran (the final pause, the store() checkpoint and the record writes). v1 receivedPayloadBytes went back about 8 MB across a graceful restart.

What changes

  • Ketch.close() still pauses running tasks for Shutdown straight away, so their records stay DOWNLOADING. It then releases everything else in the background (from Dispatchers.Default), in this order:
    1. joins the cancelled executions, so their final checkpoints and record writes land;
    2. awaits each source's new DownloadSource.stop() (default: no-op). Sources stop side by side through SourceResolver.stop();
    3. closes the sources and the HttpEngine;
    4. closes the dispatchers it was given once every cancelled coroutine has finished. As before, this never happens under running coroutines and never touches KetchDispatchers.Default.
  • KetchApi.shutdown(timeout = 5.seconds): new; its default just calls close(). Ketch's version closes and then waits until the sources and the HttpEngine are released, at most timeout. The timeout is wall-clock time, also under runTest. Whatever hasn't finished by then carries on in the background.
  • TorrentDownloadSource.stop() refuses new engines, cancels the seed watchers as close() did, and awaits KotlinTorrentEngine.stop(). That's when seeding sessions close and announce stopped. close() afterwards only closes what is left.
  • Callers: ketch server and ketch mcp --standalone shutdown hooks and ketch <url> call shutdown(). So does the desktop app's quit, through a new InstanceManager.shutdown() that closes remote devices and awaits the embedded one.
  • AGENTS.md (the close() semantics), docs/api.md, docs/architecture.md, docs/developers.md and docs/torrent.md are updated. The library:api ABI dump is updated too.

Torrent downloads already announce stopped from their execution's cleanup (removeTorrent). Joining the executions before the HTTP engine closes is what lets those announces through. stop() covers sessions that outlived their download, such as seeders.

Tests

  • KetchCloseTest.shutdown_whileDownloading_savesTheFinalStateBeforeSourcesStopAndTheEngineCloses: a source that takes a while to stop saves a later checkpoint while it stops. shutdown() returns with that state saved, and the order is: checkpoint with HTTP open → stop() with HTTP open → close() → engine closed.
  • KetchCloseTest.shutdown_returnsAfterItsTimeout_andTheRestStopsLater.
  • TorrentSourceStopTest: stop() returns only once the engine's stop does, and no engine starts after it. Ketch.shutdown() lets the engine's stopped announce through a live HttpEngine.
  • InstanceManagerShutdownTest: the embedded device is awaited and remote ones are closed.
  • ConfigurableNetworkHttpEngineTest now uses shutdown(), because the engine is released after close() returns rather than inside it.
  • With the old close order restored, the three end-to-end tests fail: wrong event order, and no announce.

Run locally, all passing: :library:core:jvmTest, :library:torrent:jvmTest, :app:shared:jvmTest, :cli:test, :app:desktop:test, :library:server:test, :hooks:test, :library:mcp:test, :library:remote:jvmTest, :updater:test, :library:api:checkKotlinAbi and :library:core:compileTestKotlinIosSimulatorArm64. Core's close tests also pass on jsNodeTest. On wasmWasiNodeTest, the tests that write to the temp folder crash inside okio, including the existing close_whileDownloading test. CI doesn't run that target.

Built on main; independent of #570, which touches none of these lines.

Ketch.close() cancelled the executions, asked the torrent engine to stop and closed the shared
HttpEngine at once, without waiting for any of it. Torrent sessions' `stopped` announces failed
against the closed engine, and `ketch server`'s shutdown hook returned before the executions'
final pause, store() checkpoint and record writes ran, so a graceful restart lost progress.

close() now releases the engine in order, in the background: it joins the cancelled executions,
awaits each source's new DownloadSource.stop() (the torrent source awaits its engine's stop),
then closes the sources, the HttpEngine and the dispatchers it was given. KetchApi.shutdown(timeout)
does the same and waits for it, at most 5 s by default. `ketch server`, `ketch mcp --standalone`,
`ketch <url>` and the desktop app's quit (InstanceManager.shutdown) call it.
@chatgpt-codex-connector

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

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-17T11:12:30.154289Z a5215b4 PR opened
ℹ️ About Codex in GitHub

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

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

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

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a5215b4674

ℹ️ About Codex in GitHub

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

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

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

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

@github-actions

github-actions Bot commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

Test Results

 1 969 files  + 7   1 997 suites  +7   22m 24s ⏱️ +36s
13 209 tests +19  12 948 ✅ +19  261 💤 ±0  0 ❌ ±0 
15 918 runs  +25  15 657 ✅ +25  261 💤 ±0  0 ❌ ±0 

Results for commit c1a36b3. ± Comparison against base commit f168285.

♻️ This comment has been updated with latest results.

A torrent engine that was still starting when stop() came was only closed asynchronously, so
stop() could return while it still held its listener and port mappings: startEngine() now stops
it under the mutex stop() waits for. ReleaseDownloader awaits Ketch.shutdown(), so its HTTP
engine is closed once download() returns, as before.
@linroid
linroid merged commit 5554fa4 into main Oct 17, 2026
14 checks passed
@linroid
linroid deleted the fix/awaited-shutdown branch October 17, 2026 12:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant