Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1105,6 +1105,7 @@ Token is persisted locally after `ms-hub login` and auto-loaded in subsequent se
| `MODELSCOPE_DOWNLOAD_FILE_LOCK` | `true` | File lock for multiprocess download safety |
| `MODELSCOPE_DOWNLOAD_INTRA_CLOUD` | `true` | Alibaba cloud intra-cloud acceleration |
| `MODELSCOPE_DOWNLOAD_INTRA_CLOUD_REGION` | (auto) | Override intra-cloud region ID |
| `MODELSCOPE_DOWNLOAD_REGION_PROBE_TIMEOUT_SECONDS` | `1` | Per-hop timeout for the intra-cloud region probe (seconds) |
| `MODELSCOPE_DOWNLOAD_INTER_CLOUD_REGIONS` | | Comma-separated peer regions for cross-region internal acceleration (e.g. `cn-hangzhou,cn-zhangjiakou`) |

**Upload:**
Expand Down
55 changes: 38 additions & 17 deletions src/modelscope_hub/_download.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@
DOWNLOAD_PARALLEL_THRESHOLD,
DOWNLOAD_PARALLELS,
DOWNLOAD_PART_SIZE,
DOWNLOAD_REGION_PROBE_TIMEOUT_SECONDS,
DOWNLOAD_RETRY_MAX_DELAY_SECONDS,
DOWNLOAD_RETRY_TIMES,
DOWNLOAD_TIMEOUT,
Expand Down Expand Up @@ -653,6 +654,7 @@ def __init__(
# None defers to MODELSCOPE_DOWNLOAD_TOTAL_TIMEOUT; 0 or less means no limit.
self._total_timeout = total_timeout
self._cached_region: str | None = None
self._region_probe_failures = 0
self._region_lock = threading.Lock()
# Cache only confirmed OSS-internal resolutions. A repository can contain
# Git metadata and LFS objects behind different download routes, so cache
Expand All @@ -672,17 +674,34 @@ def _build_user_agent(self, user_agent: dict | str | None = None) -> str:

return append_user_agent(self._user_agent, user_agent)

# A probe that never reached the endpoint says nothing about the machine's
# location, so the result is not cached and a later call probes again. The
# budget keeps a broken route from costing a probe timeout on every file.
_REGION_PROBE_MAX_ATTEMPTS = 2

def _detect_region(self) -> str:
"""Probe the region only once per DownloadManager instance."""
"""Probe the region once per DownloadManager instance.

An inconclusive probe (the endpoint never answered) is retried on a
later call rather than cached: caching it would silently drop
intra-cloud acceleration for every remaining download of this instance.
"""
with self._region_lock:
if self._cached_region is None:
if self._cached_region is not None:
return self._cached_region
region = self._detect_region_uncached()
if region is not None:
self._cached_region = region
return region
self._region_probe_failures += 1
if self._region_probe_failures >= self._REGION_PROBE_MAX_ATTEMPTS:
self._cached_region = ""
self._cached_region = self._detect_region_uncached()
return self._cached_region
return ""

def _detect_region_uncached(self) -> str:
def _detect_region_uncached(self) -> str | None:
endpoint = self._client.endpoint
internal_url = f"{endpoint}/api/v1/repos/internalAccelerationInfo"
timeout = DOWNLOAD_REGION_PROBE_TIMEOUT_SECONDS

def _get(url: str, timeout: float):
try:
Expand All @@ -699,18 +718,20 @@ def _get(url: str, timeout: float):
return None

region_id = ""
resp = _get(internal_url, 0.2)
if resp is not None:
data = resp.json()
query_addr = ""
if "Data" in data:
query_addr = data["Data"].get("InternalRegionQueryAddress", "")
if query_addr:
domain_resp = _get(query_addr, 0.2)
if domain_resp is not None:
region_id = domain_resp.text.strip()

self._cached_region = region_id
resp = _get(internal_url, timeout)
if resp is None:
# Unreachable endpoint: no conclusion about this machine may be
# cached, so the caller can probe again on a later call.
return None
data = resp.json()
query_addr = ""
if "Data" in data:
query_addr = data["Data"].get("InternalRegionQueryAddress", "")
if query_addr:
domain_resp = _get(query_addr, timeout)
if domain_resp is not None:
region_id = domain_resp.text.strip()

return region_id

# OSS internal endpoint hostname pattern:
Expand Down
10 changes: 10 additions & 0 deletions src/modelscope_hub/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -927,6 +927,15 @@ def _env_register(
"Download",
allow_zero=True,
)

"""Budget for one hop of the intra-cloud region probe."""
DOWNLOAD_REGION_PROBE_TIMEOUT_SECONDS: int = _env_int(
"MODELSCOPE_DOWNLOAD_REGION_PROBE_TIMEOUT_SECONDS",
1,
"Per-hop timeout for the intra-cloud region probe (seconds)",
"Download",
)

DOWNLOAD_MIN_BYTES_PER_SECOND: int = _env_int(
"MODELSCOPE_DOWNLOAD_MIN_BYTES_PER_SECOND",
1024,
Expand Down Expand Up @@ -1579,6 +1588,7 @@ def get_upload_ignore_file_pattern() -> str | None:
"DOWNLOAD_MIN_BYTES_PER_SECOND",
"DOWNLOAD_LOW_SPEED_WINDOW_SECONDS",
"DOWNLOAD_RETRY_MAX_DELAY_SECONDS",
"DOWNLOAD_REGION_PROBE_TIMEOUT_SECONDS",
"DOWNLOAD_FILE_LOCK_TIMEOUT_SECONDS",
"REPO_TREE_PAGE_TIMEOUT_SECONDS",
"REPO_TREE_LIST_TIMEOUT_SECONDS",
Expand Down
49 changes: 49 additions & 0 deletions tests/test_download_integrity.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
from urllib.parse import parse_qs, quote, unquote, urlparse

import pytest
import requests

from modelscope_hub import _download
from modelscope_hub.api import HubApi
Expand Down Expand Up @@ -787,6 +788,53 @@ def probe():
assert list(pool.map(lambda _: api.downloader._detect_region(), range(16))) == ["cn-test"] * 16
assert calls == [1]

def test_region_probe_uses_the_configured_timeout(self, api, monkeypatch):
seen = []

class _Recorder:
def get(self, url, **kwargs):
seen.append(kwargs["timeout"])
raise requests.exceptions.ConnectTimeout("probe")

monkeypatch.setattr(_download, "DOWNLOAD_REGION_PROBE_TIMEOUT_SECONDS", 2)
monkeypatch.setattr(api.downloader._client, "_read_session", _Recorder())

assert api.downloader._detect_region_uncached() is None
assert seen == [2]

def test_unreachable_endpoint_is_not_cached_as_no_region(self, api, monkeypatch):
results = iter([None, "cn-test"])
monkeypatch.setattr(api.downloader, "_detect_region_uncached", lambda: next(results))

assert api.downloader._detect_region() == ""
assert api.downloader._detect_region() == "cn-test"
assert api.downloader._detect_region() == "cn-test"

def test_region_probe_failures_stop_after_the_attempt_budget(self, api, monkeypatch):
calls = []

def probe():
calls.append(1)
return None

monkeypatch.setattr(api.downloader, "_detect_region_uncached", probe)

for _ in range(5):
assert api.downloader._detect_region() == ""
assert len(calls) == api.downloader._REGION_PROBE_MAX_ATTEMPTS

def test_confirmed_no_region_is_cached_at_once(self, api, monkeypatch):
calls = []

def probe():
calls.append(1)
return ""

monkeypatch.setattr(api.downloader, "_detect_region_uncached", probe)

assert [api.downloader._detect_region() for _ in range(3)] == [""] * 3
assert len(calls) == 1


class TestDownloadConfiguration:
def test_defaults_exports_registry_and_readme_are_aligned(self):
Expand All @@ -800,6 +848,7 @@ def test_defaults_exports_registry_and_readme_are_aligned(self):
"DOWNLOAD_FILE_LOCK_TIMEOUT_SECONDS": 600,
"REPO_TREE_PAGE_TIMEOUT_SECONDS": 15,
"REPO_TREE_LIST_TIMEOUT_SECONDS": 3600,
"DOWNLOAD_REGION_PROBE_TIMEOUT_SECONDS": 1,
}
registry = {entry.name: entry.default for entry in constants.ENV_REGISTRY}
readme = (Path(__file__).parents[1] / "README.md").read_text()
Expand Down
Loading