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
16 changes: 16 additions & 0 deletions docs/user-guide/datasets.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,22 @@ for ds in list_datasets():
print(ds.name, ds.task, ds.n_features, ds.n_classes)
```

### Downloads and certificates

`concrete` and `beijing_pm25` are downloaded on first use and then read from the
cache. eigenkit checks the certificate of the server against the CA certificates
of your system and against those of certifi, which the `datasets` extra installs.
So the download also works on the python.org build of Python for macOS, which has
no CA certificates until you run `Install Certificates.command` in its folder in
Applications.

scikit-learn downloads `california_housing` itself, and it uses only the CA
certificates of Python. On the python.org build of Python for macOS, run
`Install Certificates.command` before you load it.

Behind a proxy that inspects TLS traffic, set the `SSL_CERT_FILE` environment
variable to a CA bundle that holds the certificate of the proxy.

## Synthetic generators

To choose the size and the seed of a synthetic dataset, call its generator function
Expand Down
3 changes: 3 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,9 @@ router = [
# Synthetic + real datasets and the sklearn baselines used by them.
datasets = [
"scikit-learn>=1.3,<2",
# CA certificates for the downloaded datasets, which the python.org build of
# Python for macOS lacks. 2024.7.4 drops the distrusted GLOBALTRUST roots.
"certifi>=2024.7.4",
]
benchmark = [
"matplotlib>=3.7",
Expand Down
50 changes: 44 additions & 6 deletions src/eigenkit/datasets/_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@

import hashlib
import os
import ssl
import tempfile
import urllib.error
import urllib.request
from pathlib import Path

Expand Down Expand Up @@ -35,6 +37,23 @@ def _file_hash(filepath: Path) -> str:
return h.hexdigest()


def _ssl_context() -> ssl.SSLContext:
"""The system's CA certificates, plus certifi's when it is installed.

The python.org build of Python for macOS has no CA certificates until its
`Install Certificates.command` runs, so the default context alone fails to
verify any server there. certifi's roots are added, not substituted, so a CA
trusted through the system or `SSL_CERT_FILE` still verifies.
"""
context = ssl.create_default_context()
try:
import certifi
except ImportError:
return context
context.load_verify_locations(certifi.where())
return context


def cached_download(
url: str,
filename: str,
Expand Down Expand Up @@ -73,17 +92,36 @@ def cached_download(
else:
return filepath

# Download beside the target and rename into place. `urlretrieve` writes
# directly to its destination, so an interrupted download -- a dropped
# connection, a Ctrl-C -- would leave a truncated file at the cache path
# that every later call would return as valid, forever, unless the registry
# entry carries a hash to check it against.
# Download beside the target and rename into place, so an interrupted
# download -- a dropped connection, a Ctrl-C -- never leaves a truncated file
# at the cache path that every later call would return as valid, forever,
# unless the registry entry carries a hash to check it against.
with tempfile.NamedTemporaryFile(
dir=cache_dir, prefix=f".{filename}.", suffix=".part", delete=False
) as handle:
partial = Path(handle.name)
try:
urllib.request.urlretrieve(url, partial) # noqa: S310
try:
with urllib.request.urlopen(url, context=_ssl_context()) as response: # noqa: S310
# One unbounded read(): unlike read(n) in a loop, it raises
# IncompleteRead when the body is shorter than its Content-Length.
# The registry's datasets are a few MB, so they fit in memory.
partial.write_bytes(response.read())
except urllib.error.URLError as exc:
if isinstance(exc.reason, ssl.SSLCertVerificationError):
# With an errno beside it, the message prints as text, not as
# the repr of a one-element tuple.
raise ssl.SSLCertVerificationError(
exc.reason.errno,
f"Could not verify the TLS certificate of {url}: {exc.reason}. "
"Python has no CA certificate that signs it. On the python.org "
"build of Python for macOS, run 'Install Certificates.command' "
"in the Python folder of Applications, or install certifi "
"(pip install certifi). Behind a proxy that inspects TLS, set "
"the SSL_CERT_FILE environment variable to a CA bundle that "
"holds the proxy's certificate.",
) from exc
raise
if expected_hash is not None:
actual = _file_hash(partial)
if actual != expected_hash:
Expand Down
58 changes: 48 additions & 10 deletions tests/datasets/test_cache.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
"""Tests for the dataset cache system (_cache.py)."""

import hashlib
import io
import os
import ssl
import urllib.error
from pathlib import Path
from unittest.mock import patch

import pytest

from eigenkit.datasets._cache import (
DEFAULT_CACHE_DIR,
cached_download,
Expand Down Expand Up @@ -34,11 +39,11 @@ def test_cached_download_creates_file(tmp_path):
url = "http://example.com/data.csv"
filename = "data.csv"

def fake_urlretrieve(url, dest):
Path(dest).write_bytes(content)
def fake_urlopen(url, context):
return io.BytesIO(content)

with patch.dict(os.environ, {"EIGENKIT_DATA_DIR": str(tmp_path)}):
with patch("urllib.request.urlretrieve", side_effect=fake_urlretrieve) as mock_dl:
with patch("urllib.request.urlopen", side_effect=fake_urlopen) as mock_dl:
path = cached_download(url, filename)
assert path.exists()
assert path.read_bytes() == content
Expand All @@ -55,7 +60,7 @@ def test_cached_download_uses_cache(tmp_path):
cached_file.write_bytes(content)

with patch.dict(os.environ, {"EIGENKIT_DATA_DIR": str(tmp_path)}):
with patch("urllib.request.urlretrieve") as mock_dl:
with patch("urllib.request.urlopen") as mock_dl:
path = cached_download(url, filename)
mock_dl.assert_not_called()
assert path == cached_file
Expand All @@ -74,11 +79,11 @@ def test_cached_download_rehashes_corrupt(tmp_path):
cached_file = tmp_path / filename
cached_file.write_bytes(corrupt)

def fake_urlretrieve(url, dest):
Path(dest).write_bytes(content)
def fake_urlopen(url, context):
return io.BytesIO(content)

with patch.dict(os.environ, {"EIGENKIT_DATA_DIR": str(tmp_path)}):
with patch("urllib.request.urlretrieve", side_effect=fake_urlretrieve) as mock_dl:
with patch("urllib.request.urlopen", side_effect=fake_urlopen) as mock_dl:
path = cached_download(url, filename, expected_hash=expected_hash)
mock_dl.assert_called_once()
assert path.read_bytes() == content
Expand All @@ -90,10 +95,43 @@ def test_cached_download_hash_verified(tmp_path):
filename = "good.csv"
expected_hash = hashlib.sha256(content).hexdigest()

def fake_urlretrieve(url, dest):
Path(dest).write_bytes(content)
def fake_urlopen(url, context):
return io.BytesIO(content)

with patch.dict(os.environ, {"EIGENKIT_DATA_DIR": str(tmp_path)}):
with patch("urllib.request.urlretrieve", side_effect=fake_urlretrieve):
with patch("urllib.request.urlopen", side_effect=fake_urlopen):
path = cached_download(url, filename, expected_hash=expected_hash)
assert path.exists()


def test_certifi_roots_are_trusted_when_python_ships_none(tmp_path, monkeypatch):
"""The python.org build of Python for macOS has no CA certificates until
`Install Certificates.command` runs, so OpenSSL's default paths are empty and
every HTTPS download fails verification."""
pytest.importorskip("certifi")
monkeypatch.setenv("EIGENKIT_DATA_DIR", str(tmp_path))
monkeypatch.setenv("SSL_CERT_FILE", str(tmp_path / "missing.pem"))
monkeypatch.setenv("SSL_CERT_DIR", str(tmp_path / "missing"))
contexts = []

def fake_urlopen(url, context):
contexts.append(context)
return io.BytesIO(b"a,b\n1,2\n")

monkeypatch.setattr("urllib.request.urlopen", fake_urlopen)
cached_download("https://example.com/data.csv", "data.csv")
assert contexts[0].cert_store_stats()["x509_ca"] > 0


def test_a_certificate_error_says_how_to_fix_it(tmp_path, monkeypatch):
monkeypatch.setenv("EIGENKIT_DATA_DIR", str(tmp_path))

def fake_urlopen(url, context):
raise urllib.error.URLError(ssl.SSLCertVerificationError("verify failed"))

monkeypatch.setattr("urllib.request.urlopen", fake_urlopen)
with pytest.raises(ssl.SSLCertVerificationError, match="Install Certificates") as e:
cached_download("https://example.com/data.csv", "data.csv")
assert str(e.value).startswith("Could not verify"), "printed as a tuple"
assert "SSL_CERT_FILE" in str(e.value)
assert list(tmp_path.iterdir()) == [], "a partial download was left cached"
10 changes: 5 additions & 5 deletions tests/datasets/test_cache_and_labels.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@

from __future__ import annotations

from pathlib import Path
import io
from urllib.error import URLError

import numpy as np
Expand Down Expand Up @@ -45,13 +45,13 @@ def test_a_failed_download_caches_nothing(self, cache):
def test_a_completed_download_is_cached_and_reused(self, cache, monkeypatch):
calls = []

def fake_urlretrieve(url, path):
def fake_urlopen(url, context):
calls.append(url)
Path(path).write_text("a,b\n1,2\n")
return io.BytesIO(b"a,b\n1,2\n")

monkeypatch.setattr(
"eigenkit.datasets._cache.urllib.request.urlretrieve",
fake_urlretrieve,
"eigenkit.datasets._cache.urllib.request.urlopen",
fake_urlopen,
)
first = cached_download("http://example/x.csv", "x.csv")
second = cached_download("http://example/x.csv", "x.csv")
Expand Down
31 changes: 15 additions & 16 deletions tests/datasets/test_loaders.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

import io
import os
from pathlib import Path
from unittest.mock import patch

import numpy as np
Expand Down Expand Up @@ -117,11 +116,11 @@ def _make_concrete_csv(n_rows: int = 50) -> bytes:
def test_concrete_dataset_shapes(tmp_path):
csv_bytes = _make_concrete_csv(50)

def fake_urlretrieve(url, dest):
Path(dest).write_bytes(csv_bytes)
def fake_urlopen(url, context):
return io.BytesIO(csv_bytes)

with patch.dict(os.environ, {"EIGENKIT_DATA_DIR": str(tmp_path)}):
with patch("urllib.request.urlretrieve", side_effect=fake_urlretrieve):
with patch("urllib.request.urlopen", side_effect=fake_urlopen):
data = load_dataset("concrete", random_state=42)

assert {"X_train", "y_train", "X_test", "y_test", "metadata"} <= data.keys()
Expand All @@ -133,11 +132,11 @@ def fake_urlretrieve(url, dest):
def test_concrete_dataset_y_is_float(tmp_path):
csv_bytes = _make_concrete_csv(50)

def fake_urlretrieve(url, dest):
Path(dest).write_bytes(csv_bytes)
def fake_urlopen(url, context):
return io.BytesIO(csv_bytes)

with patch.dict(os.environ, {"EIGENKIT_DATA_DIR": str(tmp_path)}):
with patch("urllib.request.urlretrieve", side_effect=fake_urlretrieve):
with patch("urllib.request.urlopen", side_effect=fake_urlopen):
data = load_dataset("concrete", random_state=42)

assert data["y_train"].dtype == np.float32
Expand All @@ -158,11 +157,11 @@ def _make_beijing_csv(n_rows: int = 100) -> bytes:
def test_beijing_pm25_dataset_shapes(tmp_path):
csv_bytes = _make_beijing_csv(100)

def fake_urlretrieve(url, dest):
Path(dest).write_bytes(csv_bytes)
def fake_urlopen(url, context):
return io.BytesIO(csv_bytes)

with patch.dict(os.environ, {"EIGENKIT_DATA_DIR": str(tmp_path)}):
with patch("urllib.request.urlretrieve", side_effect=fake_urlretrieve):
with patch("urllib.request.urlopen", side_effect=fake_urlopen):
data = load_dataset("beijing_pm25", random_state=42)

assert {"X_train", "y_train", "X_test", "y_test", "metadata"} <= data.keys()
Expand All @@ -174,11 +173,11 @@ def fake_urlretrieve(url, dest):
def test_beijing_pm25_chronological_split(tmp_path):
csv_bytes = _make_beijing_csv(100)

def fake_urlretrieve(url, dest):
Path(dest).write_bytes(csv_bytes)
def fake_urlopen(url, context):
return io.BytesIO(csv_bytes)

with patch.dict(os.environ, {"EIGENKIT_DATA_DIR": str(tmp_path)}):
with patch("urllib.request.urlretrieve", side_effect=fake_urlretrieve):
with patch("urllib.request.urlopen", side_effect=fake_urlopen):
data = load_dataset("beijing_pm25", test_size=0.2, random_state=42)

raw = np.loadtxt(io.BytesIO(csv_bytes), delimiter=",", skiprows=1)
Expand All @@ -193,11 +192,11 @@ def fake_urlretrieve(url, dest):
def test_beijing_pm25_no_split(tmp_path):
csv_bytes = _make_beijing_csv(100)

def fake_urlretrieve(url, dest):
Path(dest).write_bytes(csv_bytes)
def fake_urlopen(url, context):
return io.BytesIO(csv_bytes)

with patch.dict(os.environ, {"EIGENKIT_DATA_DIR": str(tmp_path)}):
with patch("urllib.request.urlretrieve", side_effect=fake_urlretrieve):
with patch("urllib.request.urlopen", side_effect=fake_urlopen):
data = load_dataset("beijing_pm25", split=False)

assert {"X", "y", "metadata"} <= data.keys()
Expand Down
3 changes: 3 additions & 0 deletions uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading