Skip to content

armgit / Soup

Public Imported from GitHub
0

Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.

fix(cli): read the auth phrasing out of the whole exception chain (#1361) (#1366)

dymuxf0bb65061caa
diff --git a/changelog.d/0.75.1/1366.fixed.md b/changelog.d/0.75.1/1366.fixed.md
new file mode 100644
index 00000000..71f39126
--- /dev/null
+++ b/changelog.d/0.75.1/1366.fixed.md
@@ -0,0 +1 @@
+- **The friendly error reads a 401/403 out of the whole exception chain, not just the outer message (#1361 by @putramkti in #1366).** The status-phrase check (`401 Client Error`, `HTTP Error 403`, ...) searched only the outermost message, so a wrapper that says nothing about status, such as `RuntimeError("Failed to load adapter")` around a text-only `401 Client Error: Unauthorized`, printed the wrapper's message instead of `Authentication failed.` It now reads every exception in the `__cause__`/`__context__` chain, outermost first, so a 403 wrapper of a text-only 401 still reads as the 403 it says. An exception whose own `__str__` raises no longer turns the friendly error into a second traceback either.
diff --git a/src/soup_cli/utils/errors.py b/src/soup_cli/utils/errors.py
index afb1f882..ce69fe93 100644
--- a/src/soup_cli/utils/errors.py
+++ b/src/soup_cli/utils/errors.py
@@ -275,6 +275,19 @@ def _exception_chain(exc: Exception):
current = current.__cause__ or current.__context__
+def _safe_str(exc: BaseException) -> str:
+ """`str(exc)`, or an empty string when the exception's own `__str__` raises.
+
+ The text fallback below runs over every exception in the chain, so one class
+ with a broken `__str__` would otherwise turn the friendly error into a second
+ traceback. Same guard CPython's `traceback` module applies.
+ """
+ try:
+ return str(exc)
+ except Exception:
+ return ""
+
+
def _auth_status(exc: Exception) -> int | None:
"""Return 401/403 when the exception is genuinely an auth failure.
@@ -285,6 +298,13 @@ def _auth_status(exc: Exception) -> int | None:
401/403 status does the HTTP-phrasing text fallback apply; an object
carrying some other status (a 404, say) still falls through to the text
check.
+
+ The fallback walks the chain the same way, exception-major: the outermost
+ exception that carries a status phrase decides, so a wrapper that says
+ nothing about status does not hide the failure it wraps, and a 403 wrapper
+ of a 401 is still read as the 403 it says. Pattern-major (every pattern
+ across the chain before the next pattern) would let the 401 entries, which
+ come first in `_AUTH_STATUS_TEXT`, beat an outer 403.
"""
chain = list(_exception_chain(exc))
if any(type(e).__name__ in _STATUS_DECLINE_TYPES for e in chain):
@@ -297,9 +317,10 @@ def _auth_status(exc: Exception) -> int | None:
status = getattr(e, attr, None)
if isinstance(status, int) and status in _AUTH_HINTS:
return status
- for pattern, status in _AUTH_STATUS_TEXT:
- if pattern.search(str(exc)):
- return status
+ for e in chain:
+ for pattern, status in _AUTH_STATUS_TEXT:
+ if pattern.search(_safe_str(e)):
+ return status
return None
diff --git a/tests/test_issue1267_auth_status_classification.py b/tests/test_issue1267_auth_status_classification.py
index cad96718..90fc412d 100644
--- a/tests/test_issue1267_auth_status_classification.py
+++ b/tests/test_issue1267_auth_status_classification.py
@@ -218,8 +218,9 @@ def test_implicitly_chained_status_is_used():
def test_wrapped_urllib_error_uses_its_code():
- # The text fallback reads only the top message, so a wrapped urllib error is
- # recognised by its `.code` alone.
+ # urllib's HTTPError also says "HTTP Error 403" in its text, which the text
+ # fallback now reads anywhere in the chain (#1361); the phrase-free variant in
+ # test_issue1361_auth_status_text_chain.py pins the `.code` probe on its own.
cause = urllib.error.HTTPError("https://x/y", 403, "Forbidden", None, None)
try:
raise RuntimeError("download failed") from cause
diff --git a/tests/test_issue1361_auth_status_text_chain.py b/tests/test_issue1361_auth_status_text_chain.py
new file mode 100644
index 00000000..748837bc
--- /dev/null
+++ b/tests/test_issue1361_auth_status_text_chain.py
@@ -0,0 +1,115 @@
+"""Tests for #1361: the auth phrasing check must read the whole exception chain.
+
+`_auth_status` (#1268) reads a 401/403 from the exception object by walking
+`__cause__`/`__context__`, but its text fallback searches only `str(exc)`, the
+outermost message. A wrapper that says nothing about status, such as
+`RuntimeError("Failed to load adapter")` around a text-only
+`401 Client Error: Unauthorized`, therefore printed the wrapper's message:
+
+ RuntimeError("Failed to load adapter") <- __cause__
+ Exception("401 Client Error: Unauthorized for url: ...")
+
+The fallback now walks the chain too, exception-major, so the outermost
+exception that carries a status phrase decides, and a 403 wrapper of a text-only
+401 still reads as the 403 it says.
+"""
+
+import urllib.error
+from io import StringIO
+from unittest.mock import patch
+
+from rich.console import Console
+
+from soup_cli.utils.errors import format_friendly_error
+
+_401_TEXT = "401 Client Error: Unauthorized for url: https://huggingface.co/org/model"
+_403_TEXT = "Client error '403 Forbidden' for url 'https://huggingface.co/org/model'"
+
+
+def _render(exc: Exception) -> str:
+ buf = StringIO()
+ console = Console(file=buf, stderr=False)
+ with patch("soup_cli.utils.errors.console", console):
+ format_friendly_error(exc, verbose=False)
+ return buf.getvalue()
+
+
+def test_a_wrapped_text_only_401_cause_prints_authentication_failed():
+ exc = RuntimeError("Failed to load adapter")
+ exc.__cause__ = Exception(_401_TEXT)
+ out = _render(exc)
+ assert "Authentication failed." in out
+ assert "Failed to load adapter" not in out
+
+
+def test_a_wrapped_text_only_403_cause_prints_access_denied():
+ exc = RuntimeError("Failed to load adapter")
+ exc.__cause__ = Exception("403 Client Error: Forbidden for url: https://huggingface.co/x")
+ out = _render(exc)
+ assert "Access denied." in out
+ assert "Failed to load adapter" not in out
+
+
+def test_an_implicitly_chained_text_only_401_prints_authentication_failed():
+ """`raise ... from` sets `__cause__`; a `raise` inside an `except` sets `__context__`."""
+ try:
+ try:
+ raise Exception(_401_TEXT)
+ except Exception:
+ raise RuntimeError("Failed to load adapter")
+ except RuntimeError as exc:
+ out = _render(exc)
+ assert "Authentication failed." in out
+ assert "Failed to load adapter" not in out
+
+
+def test_the_outer_phrasing_decides_when_a_403_wraps_a_401():
+ """Exception-major, not pattern-major: the 401 pattern comes first in the table, so a
+ pattern-major walk would let the inner 401 phrase beat the outer 403 message."""
+ exc = RuntimeError(_403_TEXT)
+ exc.__cause__ = Exception(_401_TEXT)
+ out = _render(exc)
+ assert "Access denied." in out
+ assert "Authentication failed." not in out
+
+
+def test_the_inner_phrasing_still_decides_when_the_outer_has_none():
+ exc = RuntimeError("Failed to load adapter")
+ inner = ValueError("the checkpoint is gone")
+ inner.__cause__ = Exception(_403_TEXT)
+ exc.__cause__ = inner
+ out = _render(exc)
+ assert "Access denied." in out
+
+
+class _QuietHTTPError(urllib.error.HTTPError):
+ """A urllib error whose message states no status, so only `.code` can classify it."""
+
+ def __str__(self) -> str:
+ return "download refused"
+
+
+def test_a_wrapped_code_only_error_is_still_read_from_its_code():
+ # urllib's own HTTPError always renders "HTTP Error 403: ...", which the text
+ # fallback now reads anywhere in the chain, so a plain wrapped HTTPError no
+ # longer shows whether the `.code` probe works. This one says nothing in text.
+ cause = _QuietHTTPError("https://x/y", 403, "Forbidden", None, None)
+ try:
+ raise RuntimeError("download failed") from cause
+ except RuntimeError as exc:
+ out = _render(exc)
+ assert "Access denied." in out
+
+
+class _UnprintableError(Exception):
+ def __str__(self) -> str:
+ raise RuntimeError("__str__ failed")
+
+
+def test_an_unprintable_wrapped_exception_does_not_break_the_formatter():
+ # The text fallback now calls str() on every wrapped exception; one whose own
+ # __str__ raises must not turn the friendly error into a second traceback.
+ exc = RuntimeError("Failed to load adapter")
+ exc.__cause__ = _UnprintableError()
+ out = _render(exc)
+ assert "Failed to load adapter" in out