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
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,13 @@ defaults or the output layout, often with no deprecation period. Pin an exact ve
`KeyboardInterrupt` arrives during the 30 s graceful `SIGTERM` wait.
- `multipart()` now sends one form field per item for `list` and `tuple` values in `data`
(restoring pre-0.3 `httpx` behaviour instead of serialising `str(value)`).
- `Timeouts.capped(math.inf)` and retry sends with `retry_budget_s=math.inf` no longer pass
`inf` to `aiohttp` (which raised `OverflowError` on the first retry when `read_timeout=None`
or `0`).
- `AdaptiveClient(read_timeout=None)` now raises `ValueError` asking for `retry_budget_s`
(matching `pump()`) instead of a bare `TypeError`.
- `ParquetSink.flush()` now commits the updated dynamic schema pin only after the part write
succeeds.

## [0.3.4] - 2026-11-30

Expand Down
13 changes: 8 additions & 5 deletions saturate/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -448,19 +448,22 @@ def __init__(
endpoint: str,
window: Fixed | Auto | None = None,
headers: dict | None = None,
read_timeout: float = 1800.0,
read_timeout: float | None = 1800.0,
signal_source: str = "auto",
on_tick: Callable[[Tick], None] | None = None,
retry_budget_s: float | None = None,
timeouts: dict[str, float] | None = None,
timeouts: dict[str, float | None] | None = None,
proxy: str | bool | None = None,
):
self.base = endpoint.rstrip("/")
# a row's attempts share one wall-clock budget; it must hold a retry of a long request,
# so by default it grows with the read timeout (300 s floor: 3600 s at the default 1800)
self.retry_budget_s = (
retry_budget_s if retry_budget_s is not None else max(transport.RETRY_BUDGET_S, 2 * read_timeout)
)
if retry_budget_s is not None:
self.retry_budget_s = retry_budget_s
elif read_timeout is None:
raise ValueError("AdaptiveClient requires retry_budget_s when read_timeout is None")
else:
self.retry_budget_s = max(transport.RETRY_BUDGET_S, 2 * read_timeout)
unknown = set(timeouts or {}) - {"connect", "write", "pool"}
if unknown:
raise ValueError(
Expand Down
6 changes: 5 additions & 1 deletion saturate/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import functools
import io
import json as jsonlib
import math
import os
import urllib.request
from collections.abc import Mapping
Expand Down Expand Up @@ -52,7 +53,10 @@ class Timeouts:
write: float | None = 30.0

def capped(self, cap: float) -> Timeouts:
"""Each phase limited to `cap` seconds, a phase without a limit included."""
"""Each phase limited to `cap` seconds, a phase without a limit included. An infinite
`cap` leaves every phase untouched (aiohttp raises OverflowError on `inf`)."""
if math.isinf(cap):
return self

def phase(limit: float | None) -> float:
return cap if limit is None or limit == 0 else min(limit, cap)
Expand Down
11 changes: 7 additions & 4 deletions saturate/sink.py
Original file line number Diff line number Diff line change
Expand Up @@ -435,6 +435,7 @@ def flush(self) -> None:
return
name = f"part-{int(time.time() * 1000)}-{self._seq:06d}-{uuid.uuid4().hex[:8]}.parquet"
self._seq += 1
pinned_schema: pa.Schema | None = None
if self._declared is not None: # declared mode: exact frame — missing fields null, extras raise
extra = set()
for r in self._buf:
Expand All @@ -455,10 +456,9 @@ def flush(self) -> None:
if pa.types.is_null(table.schema.field("error").type): # error is required: pin to string
i = table.schema.get_field_index("error")
table = table.set_column(i, pa.field("error", pa.string()), table["error"].cast(pa.string()))
# pin seen columns at first sight; pinned columns already conform, so the unify
# only ever appends new columns and new struct fields — a pinned type never moves,
# since retyping only the NEW part would break multi-part reads
schema = self._pin(
# compute the next pin without mutating self._schema yet: a failed write must not
# leave unlanded columns pinned on the sink
schema = without_untyped_schema(
table.schema if self._schema is None else pa.unify_schemas([self._schema, table.schema])
)
# every part carries the FULL pinned schema — absent or all-null columns become
Expand All @@ -469,6 +469,7 @@ def flush(self) -> None:
if f.name not in table.schema.names:
table = table.append_column(f, pa.nulls(len(table), type=f.type))
table = cast_columns(table.select(schema.names), schema).cast(schema)
pinned_schema = schema
target = self._hf_target()
if target is not None:
self._write_hf_flush(target, name, table)
Expand All @@ -479,6 +480,8 @@ def flush(self) -> None:
self._write(f"{self.root}/{MANIFEST_DIR}/ids-{name}", table.select(["id", "error"]))
except Exception as e:
log.warning(f"manifest write failed (non-fatal, part covered by scan fallback): {e}")
if pinned_schema is not None:
self._pin(pinned_schema)
self.rows_written += len(self._buf)
self._buf.clear()
self._buf_schema = None
Expand Down
2 changes: 1 addition & 1 deletion saturate/transport.py
Original file line number Diff line number Diff line change
Expand Up @@ -294,7 +294,7 @@ async def _send(client: HttpClient, url: str, req: Request, retry: bool, left: f
timeouts and wall-clock are capped to what is left of the row's budget; a first attempt
gets the client's full windows (long generations are legitimate)."""
form = multipart(req.data, req.files or {}) if req.kind == "multipart" else None
if retry and RETRY_ACTIVE:
if retry and RETRY_ACTIVE and not math.isinf(left):
capped = client.timeouts.capped(left)
return await asyncio.wait_for(client.post(url, json=req.json, form=form, timeouts=capped), left)
return await client.post(url, json=req.json, form=form)
Expand Down
36 changes: 36 additions & 0 deletions tests/test_pump_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,3 +102,39 @@ def test_a_phase_of_0_or_none_leaves_no_total_limit(phases):
timeouts = Timeouts(**phases)
assert timeouts.for_aiohttp().total is None
assert timeouts.capped(5.0).for_aiohttp().total == 15.0 # a capped retry still has a total
assert timeouts.capped(math.inf) == timeouts
assert timeouts.capped(math.inf).for_aiohttp().total is None


def test_infinite_retry_budget_with_no_read_timeout_retries_cleanly(tmp_path, monkeypatch):
"""pump(read_timeout=None, retry_budget_s=math.inf) must not hand inf to aiohttp on retry."""
import saturate.transport as transport

monkeypatch.setattr(transport, "BACKOFF_BASE_S", 0.01)
seen = 0

def fail_first(body):
nonlocal seen
seen += 1
return 503 if seen == 1 else 200

with StubServer(status_for=fail_first) as stub:
stats = call(
tmp_path / "out",
endpoint=stub.endpoint,
rows=2,
read_timeout=None,
retry_budget_s=math.inf,
)
assert (stats.rows_processed, stats.rows_failed, stats.retries) == (2, 0, 1)


def test_adaptive_client_requires_retry_budget_when_read_timeout_is_none():
"""AdaptiveClient matches pump(): read_timeout=None needs an explicit retry_budget_s
instead of crashing with TypeError on 2 * None."""
from saturate import AdaptiveClient

with pytest.raises(ValueError, match="retry_budget_s when read_timeout is None"):
AdaptiveClient("http://localhost:8000/v1", read_timeout=None)
client = AdaptiveClient("http://localhost:8000/v1", read_timeout=None, retry_budget_s=60.0)
assert client.retry_budget_s == 60.0
18 changes: 18 additions & 0 deletions tests/test_sinks.py
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,24 @@ def test_dynamic_type_change_becomes_error_row_at_flush(tmp_path):
assert pq.read_schema(part).field("score").type == pa.int64()


def test_failed_dynamic_flush_does_not_pin_unlanded_schema(tmp_path, monkeypatch):
"""If a dynamic ParquetSink flush fails to write, self._schema / self._pinned must stay
unchanged so an unlanded batch cannot poison later writes on the same sink."""
from saturate import ParquetSink

sink = ParquetSink(str(tmp_path), flush_every=10)
sink.append({"id": "a", "score": 1, "error": None})
assert sink._schema is None

def fail_write(*args, **kwargs):
raise OSError("disk full")

monkeypatch.setattr(sink, "_write", fail_write)
with pytest.raises(OSError, match="disk full"):
sink.flush()
assert sink._schema is None and sink._pinned == {} and sink.rows_written == 0


def test_dynamic_type_conflict_becomes_error_row_under_drain(tmp_path):
"""Under drain, a row whose type conflicts with the pinned dynamic schema becomes a
durable error row: probe() checks the pinned types before the row is buffered, not only
Expand Down