Skip to content

The agent that grows with you

fix(pm): keep progress observers off range writer locks

ethernetc4baac2b0b72
diff --git a/pm/downloader.py b/pm/downloader.py
index 880d589c412..b93fe2e6a59 100644
--- a/pm/downloader.py
+++ b/pm/downloader.py
@@ -268,21 +268,18 @@ class Download:
totals[key] = remote.total
coverage[key] = covered
- progress_lock = threading.Lock()
-
def report(key: str, written: _Ranges, total: int, *, complete: bool = False) -> None:
- with progress_lock:
- totals[key] = total
- if total or complete:
- unknown.discard(key)
- else:
- unknown.add(key)
- # The last key identifies the source reporting this tick.
- coverage.pop(key, None)
- coverage[key] = list(written)
- if progress is not None:
- done = sum(b - a for rows in coverage.values() for a, b in rows)
- progress(done, 0 if unknown else sum(totals.values()), dict(coverage))
+ totals[key] = total
+ if total or complete:
+ unknown.discard(key)
+ else:
+ unknown.add(key)
+ # The last key identifies the source reporting this tick.
+ coverage.pop(key, None)
+ coverage[key] = list(written)
+ if progress is not None:
+ done = sum(b - a for rows in coverage.values() for a, b in rows)
+ progress(done, 0 if unknown else sum(totals.values()), dict(coverage))
for source in selected:
key = str(source.dest)
@@ -468,12 +465,16 @@ class Download:
lock = threading.Lock()
errors: list[Exception] = []
stop = threading.Event()
+ updated = threading.Event()
+ pending = len(ranges)
covered = list(covered)
+ reported = list(covered)
def worker(start: int, end: int) -> None:
- if self._paused.is_set() or stop.is_set():
- return
+ nonlocal pending
try:
+ if self._paused.is_set() or stop.is_set():
+ return
headers = {**_UA, "Range": f"bytes={start}-{end - 1}"}
if remote.etag:
headers["If-Range"] = remote.etag
@@ -494,7 +495,7 @@ class Download:
position += len(chunk)
with lock:
covered[:] = _coalesce(covered + [(start, position)])
- tick(list(covered))
+ updated.set()
if response.read(1):
raise _RangeError("range body exceeds its declared bounds")
except Exception as exc:
@@ -503,9 +504,36 @@ class Download:
with lock:
errors.append(exc)
stop.set()
+ finally:
+ with lock:
+ pending -= 1
+ updated.set()
with ThreadPoolExecutor(max_workers=connections, thread_name_prefix="hermes-download") as pool:
futures = [pool.submit(worker, start, end) for start, end in ranges]
+ observer_failed = False
+ finished = not ranges
+ while not finished:
+ updated.wait()
+ with lock:
+ snapshot = list(covered)
+ finished = pending == 0
+ updated.clear()
+ # Only the coordinator observes progress. Slow UI/worker IPC
+ # coalesces intermediate snapshots, never holds up range writes.
+ if not observer_failed and snapshot != reported:
+ try:
+ tick(snapshot)
+ except Exception as exc:
+ with lock:
+ errors.append(exc)
+ observer_failed = True
+ stop.set()
+ except BaseException:
+ stop.set()
+ raise
+ reported = snapshot
+
for future in futures:
future.result()
return covered, errors
diff --git a/tests/pm/test_worker_observers.py b/tests/pm/test_worker_observers.py
new file mode 100644
index 00000000000..1a86aea2a29
--- /dev/null
+++ b/tests/pm/test_worker_observers.py
@@ -0,0 +1,84 @@
+"""Progress observers cannot stall other range writers in the isolated worker."""
+from __future__ import annotations
+
+import json
+import threading
+import time
+
+import pytest
+
+from pm import paths
+from pm.lock import Facts
+from tests.pm._fixtures import client as client, isolated_python as isolated_python
+from tests.pm._range_server import dl_server as dl_server
+from tests.pm.test_worker import _node_archive
+
+
+def test_slow_worker_observer_does_not_hold_range_writers(client, dl_server):
+ # Every range contains several chunks: one write per range could otherwise
+ # appear to make progress even while all writers wait on the bitmap lock.
+ _node_archive(dl_server, b"#!/bin/sh\nexit 0\n#" + b"x" * (64 << 20))
+ snapshots = []
+ advanced = []
+
+ def observe(done, total, ranges):
+ snapshots.append((done, total, ranges))
+ if not done or advanced:
+ return
+ part, = paths.partials_root().glob("*.part")
+ # The eighth range's second chunk is untouched at the first callback
+ # on the old implementation. All writes are actual local HTTP bytes.
+ position = 7 * total // 8 + (1 << 20)
+ started = time.monotonic()
+ deadline = started + 3
+ while time.monotonic() < deadline:
+ with part.open("rb") as stream:
+ stream.seek(position)
+ if stream.read(1) == b"x":
+ advanced.append(True)
+ break
+ time.sleep(0.01)
+ else:
+ advanced.append(False)
+
+ client.ensure("node", explicit=True, download_progress=observe)
+ assert advanced == [True], "range writers stalled until the progress callback returned"
+ assert snapshots[-1][0] == snapshots[-1][1]
+ assert [done for done, _, _ in snapshots] == sorted(done for done, _, _ in snapshots)
+
+
[email protected]("action", ["pause", "error"])
+def test_worker_observer_failure_preserves_resumable_bytes(client, dl_server, action):
+ from pm.downloader import DownloadPaused
+
+ _node_archive(dl_server, b"#!/bin/sh\nexit 0\n#" + b"x" * (32 << 20))
+ pause = threading.Event()
+ failure = ValueError("observer failed")
+ seen = []
+
+ def observe(done, total, ranges):
+ seen.append((done, total, ranges))
+ if done:
+ if action == "pause":
+ pause.set()
+ else:
+ raise failure
+
+ with pytest.raises(DownloadPaused if action == "pause" else ValueError) as caught:
+ client.ensure("node", explicit=True, pause_event=pause, download_progress=observe)
+ if action == "error":
+ assert caught.value is failure
+ assert Facts(paths.facts_path()).get("node") is None
+ sidecar, = paths.partials_root().glob("*.ranges")
+ durable = sum(end - start for start, end in json.loads(sidecar.read_text())["ranges"])
+ assert durable >= seen[-1][0] and durable > 0
+ pause.clear()
+ resumed = []
+ client.ensure("node", explicit=True, pause_event=pause,
+ download_progress=lambda *args: resumed.append(args))
+ assert resumed[0][0] == durable
+ assert resumed[-1][0] == resumed[-1][1]
+ assert not list(paths.partials_root().glob("*.part"))
+ assert Facts(paths.facts_path()).get("node") is not None