← Back to Pull requests

Strip query strings and support download URLs in repo info parsing #5006

Closed
bodapatisaikrishna closed this pull request without merging on Sep 25, 2026 09:55 UTC
View on GitHub
bodapatisaikrishna bodapatisaikrishna commented on Sep 25, 2026 06:08 UTC
Author

What does this PR do?

Fixes #5002

This PR fixes two related bugs in URL parsing for error reporting in huggingface_hub.utils._http:
1. Query strings leaking into repo_id, bucket_id, and job_id:
_parse_repo_info_from_url, _parse_bucket_id_from_url, and _parse_job_id_from_url did not separate the path from query parameters before matching regexes. For example:
- https://huggingface.co/api/models/user/repo?blobs=true resulted in repo_id="user/repo?blobs=true".
- https://huggingface.co/api/buckets/my-bucket?prefix=foo resulted in bucket_id="my-bucket?prefix=foo".
Now, URLs are parsed with urlsplit(url).path before applying regex matches so query parameters are cleanly stripped.

2. Download / content URLs not parsed:
_parse_repo_info_from_url previously only matched /api/(models|datasets|spaces)/... endpoints. When downloading files directly from /resolve/..., /raw/..., or /blob/... (e.g., via hf download or direct HTTP requests):
- https://huggingface.co/openai-community/gpt2/resolve/main/config.json returned (None, None)
- https://huggingface.co/datasets/nyu-mll/glue/resolve/main/data.csv returned (None, None)
- https://huggingface.co/spaces/gradio/hello_world/resolve/main/app.py returned (None, None)
As a consequence, when a 404 or gated repo error occurred during a download, repo_id remained None in the raised HfHubHTTPError / RemoteEntryNotFoundError / GatedRepoError. For CLI commands such as hf download, this caused the error output to degrade to generic messages like "File not found in repository." without indicating which repository was being accessed.
We now support model, dataset, and space download URLs with /resolve/, /raw/, and /blob/ path segments, handling both namespaced and single-segment repo IDs.

3. HTTP scheme support:
Updated regex pattern from https:// to https?:// to ensure compatibility with local test servers or custom HTTP endpoints.

Tests added:


  • Unit tests in TestParseRepoInfoFromUrl:

  • - Query parameters on API URLs (/api/models/..., single-segment models, /api/datasets/...)
    - Download URLs (/resolve/..., /raw/..., /blob/...) across models, datasets, spaces, with and without query params
  • Unit tests in TestParseBucketIdFromUrl:

  • - Query parameters on bucket URLs (/api/buckets/...)

    <!-- CURSOR_SUMMARY -->
    ---

    [!NOTE]

    Low Risk

    Localized URL parsing for error messages in _http.py; behavior change improves correctness without altering request/auth flows.

    > Overview

    Fixes HTTP error enrichment in _http.py by parsing URLs on the path only (urlsplit) so query strings no longer pollute repo_id, bucket_id, and job_id.

    > _parse_repo_info_from_url now also recognizes model/dataset/space download paths (/resolve/, /raw/, /blob/) in addition to /api/..., so failures during direct downloads (e.g. hf download) can attach the correct repository to HfHubHTTPError and related exceptions. ID extraction regexes were narrowed to path segments; REPO_API_REGEX accepts http as well as https.

    > Broad unit tests cover query params, download URLs, and edge cases (reserved repo name segments).

    > <sup>Reviewed by Cursor Bugbot for commit 4073ca58716f0d175ea7b810072b1051b6141750. Bugbot is set up for automated code reviews on this repo. Configure here.</sup>

    <!-- /CURSOR_SUMMARY -->

    Diff: 150 lines (+131 / -19) across 2 files Reviewer: bodapatisaikrishna Review duration: 226m
    All Vouch review confidence checks passed
    Residual risk 0.08 = Change Risk (0.48) × (1 − Review Confidence (0.84)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.48 · 150 lines diff across 2 files
    0.48
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.72 · 3 substantive comment(s)
    0.72
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    83%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.300
    Self Review self_review
    0.140
    Real PR Conversation Timeline
    5 items
    cursor[bot] cursor[bot] commented on code on Sep 25, 2026 06:11 UTC
    Code Review
    src/huggingface_hub/utils/_http.py:1
    @@ -199,53 +199,85 @@ def _parse_retry_after(headers: Mapping[str, str]) -> int | None:
     
     # Regex to extract the job_id from a (scheduled) job API URL.
     # Matches /api/jobs/{namespace}/{job_id}[/...] and /api/scheduled-jobs/{namespace}/{job_id}[/...].
    -_JOB_ID_FROM_URL_REGEX = re.compile(r"^https?://[^/]+/api/(?:scheduled-jobs|jobs)/[^/]+/([^/?]+)")
    +_JOB_ID_FROM_URL_REGEX = re.compile(r"^/api/(?:scheduled-jobs|jobs)/[^/]+/([^/?]+)")
     
    -# Regex to extract repo_type and repo_id from API URLs.
    +# Regex to extract repo_type and repo_id from API URLs: /api/(models|datasets|spaces)/{repo_id}[/...]
     # Captures: group(1) = repo_type plural (models/datasets/spaces), group(2) = first path segment, group(3) = optional second segment.
    -_REPO_ID_FROM_URL_REGEX = re.compile(r"^https?://[^/]+/api/(models|datasets|spaces)/([^/]+)(?:/([^/]+))?")
    +_API_REPO_URL_REGEX = re.compile(r"^/api/(models|datasets|spaces)/([^/]+)(?:/([^/]+))?")
    +
    +# Regex to extract repo_type and repo_id from content/download URLs: [/(datasets|spaces)]/{repo_id}/(resolve|raw|blob)/...
    +_CONTENT_REPO_URL_REGEX = re.compile(r"^/(?:(datasets|spaces)/)?([^/]+)(?:/([^/]+))?/(?:resolve|raw|blob)/")
     
     # Regex to extract bucket_id (namespace/name) from bucket API URLs.
    -_BUCKET_ID_FROM_URL_REGEX = re.compile(r"^https?://[^/]+/api/buckets/([^/]+/[^/]+)")
    +_BUCKET_ID_FROM_URL_REGEX = re.compile(r"^/api/buckets/([^/]+/[^/]+)")
     
     # Sub-paths that follow a repo_id in API URLs (not part of the repo name).
     _REPO_URL_SUBPATHS = {"resolve", "tree", "blob", "raw", "refs", "commit", "discussions", "settings", "revision"}
     
     
     def _parse_repo_info_from_url(url: str) -> tuple[str | None, str | None]:
    -    """Extract (repo_type, repo_id) from an API URL.
    +    """Extract (repo_type, repo_id) from an API URL or download URL.
     
         Returns canonical repo_type values: "model", "dataset", "space" (or None).
     
         Examples:
             >>> _parse_repo_info_from_url("https://huggingface.co/api/models/user/repo")
             ("model", "user/repo")
    +        >>> _parse_repo_info_from_url("https://huggingface.co/api/models/user/repo?blobs=true")
    +        ("model", "user/repo")
             >>> _parse_repo_info_from_url("https://huggingface.co/api/datasets/user/repo/resolve/main/data.csv")
             ("dataset", "user/repo")
             >>> _parse_repo_info_from_url("https://huggingface.co/api/models/bert-base-cased/resolve/main/config.json")
             ("model", "bert-base-cased")
    +        >>> _parse_repo_info_from_url("https://huggingface.co/openai-community/gpt2/resolve/main/config.json")
    +        ("model", "openai-community/gpt2")
    +        >>> _parse_repo_info_from_url("https://huggingface.co/datasets/nyu-mll/glue/resolve/main/data.csv")
    +        ("dataset", "nyu-mll/glue")
         """
    -    match = _REPO_ID_FROM_URL_REGEX.search(url)
    -    if not match:
    -        return None, None
    -    repo_type = constants.REPO_TYPES_MAPPING.get(match.group(1))
    -    first, second = match.group(2), match.group(3)
    -    if second and second not in _REPO_URL_SUBPATHS:
    -        repo_id = f"{first}/{second}"
    -    else:
    -        repo_id = first
    -    return repo_type, repo_id
    +    path = urlsplit(url).path
    +
    +    # 1. API URLs: /api/(models|datasets|spaces)/{repo_id}[/...]
    +    match = _API_REPO_URL_REGEX.search(path)
    +    if match:
    +        repo_type = constants.REPO_TYPES_MAPPING.get(match.group(1))
    +        first, second = match.group(2), match.group(3)
    +        if second and second not in _REPO_URL_SUBPATHS:
    +            repo_id = f"{first}/{second}"
    +        else:
    +            repo_id = first
    +        return repo_type, repo_id
    +
    +    # 2. Content/download URLs: [/(datasets|spaces)]/{repo_id}/(resolve|raw|blob)/...
    +    match = _CONTENT_REPO_URL_REGEX.search(path)
    +    if match:
    +        type_prefix, first, second = match.group(1), match.group(2), match.group(3)
    +        if type_prefix == "datasets":
    +            repo_type = "dataset"
    +        elif type_prefix == "spaces":
    +            repo_type = "space"
    +        else:
    +            repo_type = "model"
    +
    +        if second and second not in _REPO_URL_SUBPATHS:
    +            repo_id = f"{first}/{second}"
    +        else:
    +            repo_id = first

    Content URLs drop reserved repo names

    Low Severity

    <!-- DESCRIPTION START -->
    The _REPO_URL_SUBPATHS filter is applied when building repo_id from content/download URLs, even though _CONTENT_REPO_URL_REGEX already requires resolve, raw, or blob after the repo segments. A namespaced repo whose name is a reserved word such as settings or tree is then reported as only the namespace on download errors.
    <!-- DESCRIPTION END -->

    <!-- BUGBOT_BUG_ID: fd1e08a4-d653-454f-b8d9-925756e46916 -->

    <!-- LOCATIONS START
    src/huggingface_hub/utils/_http.py#L260-L264
    src/huggingface_hub/utils/_http.py#L214-L215
    LOCATIONS END -->
    <details>
    <summary>Additional Locations (1)</summary>

  • src/huggingface_hub/utils/_http.py#L214-L215
  • </details>

    <div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjlkMmRkYjhmLTI0MjgtNGFhZi1hYWVmLTZhZTEzZmMzNTdiOCIsImVuY3J5cHRpb25LZXkiOiJiZkIxOUZCRVp3RzI5dGdOc0hFa3dnN01SVnltME1IMkkxOU9ySTRZOHdFIiwiYnJhbmNoIjoiZml4L2Vycm9yLXJlcG8taWQtcGFyc2luZyIsInJlcG9Pd25lciI6Imh1Z2dpbmdmYWNlIiwicmVwb05hbWUiOiJodWdnaW5nZmFjZV9odWIiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a>&nbsp;<a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjlkMmRkYjhmLTI0MjgtNGFhZi1hYWVmLTZhZTEzZmMzNTdiOCIsImVuY3J5cHRpb25LZXkiOiJiZkIxOUZCRVp3RzI5dGdOc0hFa3dnN01SVnltME1IMkkxOU9ySTRZOHdFIiwiYnJhbmNoIjoiZml4L2Vycm9yLXJlcG8taWQtcGFyc2luZyIsInJlcG9Pd25lciI6Imh1Z2dpbmdmYWNlIiwicmVwb05hbWUiOiJodWdnaW5nZmFjZV9odWIiLCJwck51bWJlciI6NTAwNiwiY29tbWl0U2hhIjoiZjJiZDExOGVhMzcyMDJmZWRmYjU4NTc0N2ZiYjE1ZjFlODBkYTdkNSIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div>

    <sup>Reviewed by Cursor Bugbot for commit f2bd118ea37202fedfb585747fbb15f1e80da7d5. Configure here.</sup>

    cursor[bot] cursor[bot] commented on Sep 25, 2026 06:11 UTC
    Reviewer

    <!-- BUGBOT_REVIEW -->
    Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

    <!-- BUGBOT_FIX_ALL -->
    <a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9BTExfSU5fQ1VSU09SIiwiZGF0YSI6eyJyZWRpc0tleSI6ImJ1Z2JvdC1tdWx0aToxMGRhNWU3ZC05ZGRkLTRmMmEtYTUzYy1jMTRhZjQzYjI3ZTAiLCJlbmNyeXB0aW9uS2V5IjoiakkwYjlYRGdoN0pZSTh4anFBWkJkZk9QTUtKSmNLRzdWYV9PZ3VPWGowQSIsImJyYW5jaCI6ImZpeC9lcnJvci1yZXBvLWlkLXBhcnNpbmciLCJyZXBvT3duZXIiOiJodWdnaW5nZmFjZSIsInJlcG9OYW1lIjoiaHVnZ2luZ2ZhY2VfaHViIiwicHJvdmlkZXIiOiJnaXRodWIifX0" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix All in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a>
    <!-- /BUGBOT_FIX_ALL -->

    <!-- BUGBOT_AUTOFIX_REVIEW_FOOTNOTE_BEGIN -->
    <sup>❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.</sup>
    <!-- BUGBOT_AUTOFIX_REVIEW_FOOTNOTE_END -->

    Want higher recall? High effort reviews run extra passes and find more bugs. A team admin can switch effort levels in the Cursor dashboard.

    <sup>Reviewed by Cursor Bugbot for commit f2bd118ea37202fedfb585747fbb15f1e80da7d5. Configure here.</sup>

    bodapatisaikrishna bodapatisaikrishna commented on code on Sep 25, 2026 06:28 UTC
    Code Review
    src/huggingface_hub/utils/_http.py:1
    @@ -199,53 +199,85 @@ def _parse_retry_after(headers: Mapping[str, str]) -> int | None:
     
     # Regex to extract the job_id from a (scheduled) job API URL.
     # Matches /api/jobs/{namespace}/{job_id}[/...] and /api/scheduled-jobs/{namespace}/{job_id}[/...].
    -_JOB_ID_FROM_URL_REGEX = re.compile(r"^https?://[^/]+/api/(?:scheduled-jobs|jobs)/[^/]+/([^/?]+)")
    +_JOB_ID_FROM_URL_REGEX = re.compile(r"^/api/(?:scheduled-jobs|jobs)/[^/]+/([^/?]+)")
     
    -# Regex to extract repo_type and repo_id from API URLs.
    +# Regex to extract repo_type and repo_id from API URLs: /api/(models|datasets|spaces)/{repo_id}[/...]
     # Captures: group(1) = repo_type plural (models/datasets/spaces), group(2) = first path segment, group(3) = optional second segment.
    -_REPO_ID_FROM_URL_REGEX = re.compile(r"^https?://[^/]+/api/(models|datasets|spaces)/([^/]+)(?:/([^/]+))?")
    +_API_REPO_URL_REGEX = re.compile(r"^/api/(models|datasets|spaces)/([^/]+)(?:/([^/]+))?")
    +
    +# Regex to extract repo_type and repo_id from content/download URLs: [/(datasets|spaces)]/{repo_id}/(resolve|raw|blob)/...
    +_CONTENT_REPO_URL_REGEX = re.compile(r"^/(?:(datasets|spaces)/)?([^/]+)(?:/([^/]+))?/(?:resolve|raw|blob)/")
     
     # Regex to extract bucket_id (namespace/name) from bucket API URLs.
    -_BUCKET_ID_FROM_URL_REGEX = re.compile(r"^https?://[^/]+/api/buckets/([^/]+/[^/]+)")
    +_BUCKET_ID_FROM_URL_REGEX = re.compile(r"^/api/buckets/([^/]+/[^/]+)")
     
     # Sub-paths that follow a repo_id in API URLs (not part of the repo name).
     _REPO_URL_SUBPATHS = {"resolve", "tree", "blob", "raw", "refs", "commit", "discussions", "settings", "revision"}
     
     
     def _parse_repo_info_from_url(url: str) -> tuple[str | None, str | None]:
    -    """Extract (repo_type, repo_id) from an API URL.
    +    """Extract (repo_type, repo_id) from an API URL or download URL.
     
         Returns canonical repo_type values: "model", "dataset", "space" (or None).
     
         Examples:
             >>> _parse_repo_info_from_url("https://huggingface.co/api/models/user/repo")
             ("model", "user/repo")
    +        >>> _parse_repo_info_from_url("https://huggingface.co/api/models/user/repo?blobs=true")
    +        ("model", "user/repo")
             >>> _parse_repo_info_from_url("https://huggingface.co/api/datasets/user/repo/resolve/main/data.csv")
             ("dataset", "user/repo")
             >>> _parse_repo_info_from_url("https://huggingface.co/api/models/bert-base-cased/resolve/main/config.json")
             ("model", "bert-base-cased")
    +        >>> _parse_repo_info_from_url("https://huggingface.co/openai-community/gpt2/resolve/main/config.json")
    +        ("model", "openai-community/gpt2")
    +        >>> _parse_repo_info_from_url("https://huggingface.co/datasets/nyu-mll/glue/resolve/main/data.csv")
    +        ("dataset", "nyu-mll/glue")
         """
    -    match = _REPO_ID_FROM_URL_REGEX.search(url)
    -    if not match:
    -        return None, None
    -    repo_type = constants.REPO_TYPES_MAPPING.get(match.group(1))
    -    first, second = match.group(2), match.group(3)
    -    if second and second not in _REPO_URL_SUBPATHS:
    -        repo_id = f"{first}/{second}"
    -    else:
    -        repo_id = first
    -    return repo_type, repo_id
    +    path = urlsplit(url).path
    +
    +    # 1. API URLs: /api/(models|datasets|spaces)/{repo_id}[/...]
    +    match = _API_REPO_URL_REGEX.search(path)
    +    if match:
    +        repo_type = constants.REPO_TYPES_MAPPING.get(match.group(1))
    +        first, second = match.group(2), match.group(3)
    +        if second and second not in _REPO_URL_SUBPATHS:
    +            repo_id = f"{first}/{second}"
    +        else:
    +            repo_id = first
    +        return repo_type, repo_id
    +
    +    # 2. Content/download URLs: [/(datasets|spaces)]/{repo_id}/(resolve|raw|blob)/...
    +    match = _CONTENT_REPO_URL_REGEX.search(path)
    +    if match:
    +        type_prefix, first, second = match.group(1), match.group(2), match.group(3)
    +        if type_prefix == "datasets":
    +            repo_type = "dataset"
    +        elif type_prefix == "spaces":
    +            repo_type = "space"
    +        else:
    +            repo_type = "model"
    +
    +        if second and second not in _REPO_URL_SUBPATHS:
    +            repo_id = f"{first}/{second}"
    +        else:
    +            repo_id = first

    Fixed in commit 4073ca5 - since content URLs explicitly require resolve/raw/blob immediately after the repo segments, any second segment is unambiguously part of the repository name (e.g. user/tree or user/settings). Added test coverage for this case as well.

    Wauplin Wauplin commented on Sep 25, 2026 09:55 UTC
    Contributor
    Assignees
    bodapatisaikrishna bodapatisaikrishna
    Labels
    risk: low confidence: 83.9% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 48.5% (MEDIUM) · Higher = larger blast radius
    48.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 83.9% · Lower = rushed or shallow review
    83.9%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 7.8% · Safe to merge
    7.8%