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
2 changes: 2 additions & 0 deletions docs/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -495,6 +495,8 @@ Base exception class for all PSR Lakehouse errors.
* Missing required parameters (e.g., ``group_by`` without ``aggregation_method``)
* API connection errors
* Authentication failures
* A query the server cancelled for running too long (``HTTP 504``). It is not
retried: the message says how to narrow the query

**Example:**

Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "psr-lakehouse"
version = "0.6.2"
version = "0.6.3"
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
Expand Down
16 changes: 13 additions & 3 deletions src/psr/lakehouse/connector.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,19 @@ def _create_session() -> requests.Session:
# 503 is retried because the usual cause is transient. A 503 that
# persists past the backoff is a server-side misconfiguration and
# is reported as such rather than as a bad token. 401 and 403 are
# deliberately absent: a bad token must fail fast.
status_forcelist=[502, 503, 504],
# deliberately absent: a bad token must fail fast. So is 504: it
# is the server cancelling the query at its statement timeout, so
# a retry only runs the same query again to fail the same way.
status_forcelist=[502, 503],
allowed_methods=["GET", "POST"],
# Without this, urllib3 also retries any 429 that carries a
# Retry-After, and sleeps for it: a spent weekly row quota
# answers with days, so the call hangs instead of raising.
respect_retry_after_header=False,
# Once the retries run out, hand back the last response rather
# than raise "too many 503 error responses": raise_for_status()
# then reports its status and the server's detail.
raise_on_status=False,
)
)
session.mount("https://", adapter)
Expand Down Expand Up @@ -133,6 +139,8 @@ def initialize(
headers={"X-PSR-Lakehouse-Version": installed},
timeout=10,
)
# An error answer is JSON too, and truthy.
response.raise_for_status()
if not response.json():
raise LakehouseError("Health check failed: API returned a non-truthy response.")
except requests.exceptions.RequestException as e:
Expand Down Expand Up @@ -256,7 +264,9 @@ def get(self, endpoint: str, params: dict | None = None, _skip_init_check: bool
response = self._session.get(
url,
params=params,
timeout=60,
# Longer than the server's 60 s statement timeout, so its 504
# arrives before the read timeout, which is retried.
timeout=90,
)
response.raise_for_status()
return response.json()
Expand Down
65 changes: 64 additions & 1 deletion tests/unit/test_connector.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,9 +112,28 @@ def test_initialize_creates_session_with_retries(self):
retries = connector._session.get_adapter("https://api.example.com").max_retries
assert retries.total == 3
assert retries.backoff_factor == 1
assert set(retries.status_forcelist) == {502, 503, 504}
assert set(retries.status_forcelist) == {502, 503}
assert set(retries.allowed_methods) == {"GET", "POST"}
assert retries.respect_retry_after_header is False
assert retries.raise_on_status is False

@responses.activate
def test_initialize_health_check_failure_error_status(self):
"""An error body is JSON too, and truthy: the status is what says the API is down."""
connector = Connector.__new__(Connector)
connector._is_initialized = False

responses.add(
responses.GET,
"https://api.example.com/health-check",
json={"detail": "Service unavailable."},
status=503,
)

with pytest.raises(LakehouseError, match="Health check failed"):
connector.initialize(base_url="https://api.example.com")

assert connector._is_initialized is False

@responses.activate
def test_initialize_health_check_failure_non_truthy(self):
Expand Down Expand Up @@ -283,6 +302,50 @@ def test_get_request_http_error(self):
with pytest.raises(LakehouseError, match="HTTP"):
connector.get("/query/schema/InvalidModel")

@pytest.mark.parametrize("method", ["POST", "GET"])
@responses.activate
def test_a_504_is_raised_once_with_the_server_detail(self, method):
"""A 504 is the server cancelling the query at its statement timeout:
the same query fails the same way, and the detail says how to narrow it."""
from psr.lakehouse.connector import connector

responses.add(
method,
"https://test-api.example.com/query/",
json={"detail": "The query took longer than 60 seconds and was cancelled."},
status=504,
)

with pytest.raises(LakehouseError, match="HTTP 504 .* took longer than 60 seconds and was cancelled"):
connector.post("/query/", {}) if method == "POST" else connector.get("/query/")

assert len(responses.calls) == 1

@pytest.mark.parametrize("status", [502, 503])
@responses.activate
def test_a_502_or_503_is_still_retried(self, status):
from psr.lakehouse.connector import connector

responses.add(responses.POST, "https://test-api.example.com/query/", status=status)
responses.add(responses.POST, "https://test-api.example.com/query/", json={"data": []}, status=200)

assert connector.post("/query/", {}) == {"data": []}
assert len(responses.calls) == 2

@pytest.mark.parametrize("status", [502, 503])
@responses.activate
def test_a_502_or_503_that_persists_carries_the_server_detail(self, status):
from psr.lakehouse.connector import connector

responses.add(
responses.POST, "https://test-api.example.com/query/", json={"detail": "Warming up."}, status=status
)

with pytest.raises(LakehouseError, match=f"HTTP {status} .* Warming up"):
connector.post("/query/", {})

assert len(responses.calls) == 4 # the first attempt and three retries

@responses.activate
def test_auto_initialize_on_post(self, monkeypatch):
"""Test that connector auto-initializes on first POST request."""
Expand Down
Loading