Skip to content

Claim a distinct listen port per concurrently-running torrent - #17

Merged
pratts merged 7 commits into
mainfrom
fix/port-pool-per-torrent-listen-ports
Sep 7, 2026
Merged

pratts merged 7 commits into
mainfrom
fix/port-pool-per-torrent-listen-ports

Conversation

@pratts

@pratts pratts commented Sep 7, 2026

Copy link
Copy Markdown
Owner

The bug

tocli's process-per-torrent architecture means every running torrent is a separate OS process, and every one of them previously tried to bind the same configured port (PortRangeStart) for inbound peer connections. Only the first process to bind won; every other concurrently-running torrent silently fell back to outbound-only -- it could still find and connect out to peers via DHT/trackers/PEX, but nothing could connect in to it. This degraded seeding/upload contribution and defeated any router port-forwarding the user had set up, with no visible symptom anywhere in list or logs. port_range_end in config.toml did nothing at all.

What changed

Five layered commits (each independently buildable -- verified by checking out and building every one in sequence):

  1. Validate the configured port range at load time -- Config.Validate() rejects port_range_start > port_range_end, or one set without the other, at Load() time instead of leaving it undefined.
  2. Add AcquireLockBlocking alongside the existing non-blocking AcquireLock -- shared flock logic factored out; the new blocking variant fits the port registry's contention (wait a moment) differently from the existing per-torrent spawn lock's (give up immediately).
  3. Add store.PortRegistry -- ~/.tocli/ports.json (which port is claimed by which torrent id) plus ~/.tocli/ports.lock guarding it, following this package's existing convention of owning all on-disk state/serialization.
  4. Add internal/portpool -- Claim(id, cfg) assigns the lowest available port in [PortRangeStart, PortRangeEnd]; Release(id) frees it. No range configured short-circuits before touching the registry; exhaustion returns ephemeral=true (not an error) so the caller can fall back rather than fail to start.
  5. Claim a distinct listen port per torrent instead of pinning them all to one -- wires portpool.Claim/Release into internal/engine.Run, replacing the old pin-to-PortRangeStart block, released via the same paths that already release the per-torrent lock (completion, SIGTERM/pause, and any earlier failure via defer).

Plus two follow-up commits from review of this PR's own scope, done before opening it:

  1. Expand Config's doc comment -- the struct comment wasn't wrong, just silent on the new per-torrent behavior; it's the only place in the repo documenting these two fields, so it's worth actually saying what they do now. (Searched the rest of the repo -- README, CONTRIBUTING.md, .github/workflows/*.yml, other doc comments -- for anything describing the old single-port-pinning behavior or claiming port_range_end is unused: nothing else needed changing. Both workflow files' only port-adjacent text is the unrelated Windows/build-matrix comment.)
  2. Surface the ephemeral-port fallback in list/dashboard, not just log.txt -- the exhaustion warning was originally logged only to log.txt, which nobody looks at unless they already suspect something's wrong -- the exact "no visible symptom" problem this whole PR exists to fix, just moved one layer down. store.TorrentConfig gets a new PortEphemeral field (set/cleared alongside the existing PID/status bookkeeping), surfaced in list/list --json (port_ephemeral), list --plain (STATUS column: running (ephemeral port)), and the dashboard (STATUS column widened 12→20 to fit running (ephemeral)).

Verification

  • go build ./..., go vet ./..., gofmt -l ., go mod tidy (no diff), go test ./... -race, govulncheck ./... -- all clean.
  • Real-subprocess tests (genuine separate tocli __run processes, not goroutines, matching the existing lock_concurrency_test.go pattern): concurrent torrents land on distinct ports with no collision (verified via the shared registry), a freed port is reclaimed by the next spawn rather than staying marked claimed, and range exhaustion falls back to an ephemeral port with the expected warning logged and persisted (PortEphemeral=true) while still reaching running.
  • Unit tests for internal/portpool (sequential/lowest-available assignment, exhaustion, release-then-reclaim) and internal/config (range validation).
  • Manually verified end-to-end against the real compiled binary: three concurrent tocli __run processes against a configured [49500-49502] range, confirmed via lsof that each bound a distinct TCP+UDP port matching the port registry exactly.

Out of scope (tracked separately)

No limit on concurrent torrents, no queueing when the range is exhausted -- it still starts immediately on an ephemeral port either way. See the pool/queue GitHub issue for that.

port_range_start > port_range_end (or one set without the other) was
previously undefined behavior -- nothing checked it. Config.Validate
rejects it clearly at config load time instead, ahead of
internal/portpool depending on the range actually being well-formed.
Refactors the shared flock/open/release logic out of AcquireLock into
a private acquireLock(path, flags) so the two variants share it rather
than duplicating it.

AcquireLock's non-blocking semantics fit its existing use (the
per-torrent spawn lock: contention there means another process already
owns this one, give up). A different, upcoming use -- coordinating
access to a shared port registry file (internal/portpool) -- needs the
opposite: brief, expected contention where waiting a moment is the
right response, not failing immediately. Unused until that lands.
~/.tocli/ports.json records which port in the configured range is
currently claimed and by which torrent id; ~/.tocli/ports.lock guards
read-check-claim-write access to it. Root-level, not per-torrent,
since it's shared across every torrent rather than scoped to one --
contrast store.LockPath.

Pure storage, following this package's existing convention (it owns
all of ~/.tocli's on-disk state and serialization); the claim/release
decision logic that will use this lands separately in
internal/portpool. Unused until that lands.
…cesses

Claim assigns a torrent id the lowest available port in
[PortRangeStart, PortRangeEnd], recording it in store.PortRegistry
under process.AcquireLockBlocking so two concurrently-starting
torrents can never claim the same one. Assignment is always
lowest-available, not an arbitrary free port, so a range a user has
forwarded on their router gets used predictably from the bottom up.

No range configured (PortRangeStart <= 0) short-circuits before
touching the registry at all, matching existing behavior exactly.
Range exhaustion returns (0, ephemeral=true, nil) rather than an
error, so the caller can fall back to an OS-assigned port instead of
failing to start.

Release frees a claimed port so a later torrent can reclaim it; safe
to call for an id that never held one.

Covered by unit tests in isolation (sequential assignment, exhaustion,
release-then-reclaim, the no-range-configured short circuit); not yet
wired into anything that calls it.
…to one

Every internal/engine.Run process previously pinned its BitTorrent
listen port to config.PortRangeStart unconditionally, so only the
first concurrently-running torrent could ever actually bind it --
every one after it silently fell back to outbound-only (no inbound
peer connections), with no visible symptom in list/logs, and
defeating any router port-forwarding the user had set up for the
range. port_range_end was pure dead config as a result.

Run now claims a port via internal/portpool.Claim before creating the
torrent.Client, using it as the listener port when one was actually
claimed, and logging a clear warning when the configured range is
exhausted and it falls back to an OS-assigned port instead (still
starts normally -- exhaustion is not a failure to start). The claimed
port is released via internal/portpool.Release as part of the same
paths that already release the per-torrent lock: normal completion,
the SIGTERM/pause handler, and (via defer) any early failure in
between. Nothing is deferred at all for a torrent that never actually
claimed a port (no range configured, or the ephemeral fallback), so
the registry/lock file is never touched in that case.

Tests spawn real, separate "tocli __run" processes (not goroutines)
against a small configured range: concurrent torrents land on
distinct ports with no collision, a freed port (previous holder exits
via SIGTERM) is reclaimed by the next spawn rather than staying
marked claimed, and range exhaustion falls back to an ephemeral port
with the expected warning rather than failing to start.

Manually verified end-to-end against the real binary: three concurrent
"tocli __run" processes against a configured [49500-49502] range,
confirmed via lsof to each be listening (TCP+UDP) on a distinct port
matching the port registry exactly.

Out of scope, tracked separately (see the pool/queue GitHub issue):
no limit on concurrent torrents, no queueing when the range is
exhausted -- it still starts immediately on an ephemeral port.
…avior

Not stale (it never described the old single-port-pinning bug), just
silent on what a configured port range actually does now that
internal/portpool exists. This is the only place in the repo that
documents these two fields, so it's worth it actually saying so.
The exhaustion warning portpool.Claim's caller logs was only ever
reaching log.txt -- invisible during normal use unless someone already
suspects something's wrong and goes looking. That undercuts the whole
point of this fix: the original bug's defining symptom was "no visible
symptom anywhere in list or logs".

store.TorrentConfig gets a new PortEphemeral field, set by Run
alongside the existing PID/status bookkeeping whenever it falls back
to an OS-assigned port, and cleared once the torrent stops actively
running (paused/completed) since the claim -- or lack of one -- no
longer applies once released.

Surfaced in both places a user actually looks: `list`/`list --json`
(a new port_ephemeral field, and "(ephemeral port)" appended to the
STATUS column in `list --plain`) and the dashboard's STATUS column
(widened from 12 to 20 to fit "running (ephemeral)" without
truncating).

Tests: the existing real-subprocess exhaustion test now also confirms
the persisted config actually records PortEphemeral=true, and a new
`list --plain` test confirms it renders visibly.
@pratts
pratts merged commit 102bf94 into main Sep 7, 2026
4 checks passed
@pratts
pratts deleted the fix/port-pool-per-torrent-listen-ports branch October 25, 2026 14:17
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