|
| 1 | +# Copyright 2025, 2026 Query Farm LLC - https://query.farm |
| 2 | + |
| 3 | +"""The ``blob_test`` fixture catalog and the runnable fake blob vendor. |
| 4 | +
|
| 5 | +End to end through the subprocess fixture worker with |
| 6 | +``VGI_STORAGE_EXTERNALIZE=1`` over SQLite and the fake vendor: the hermetic |
| 7 | +setup the DuckDB extension's externalization lane uses. |
| 8 | +""" |
| 9 | + |
| 10 | +from __future__ import annotations |
| 11 | + |
| 12 | +import hashlib |
| 13 | +import json |
| 14 | +import subprocess |
| 15 | +import sys |
| 16 | +from collections.abc import Iterator |
| 17 | +from pathlib import Path |
| 18 | + |
| 19 | +import httpx2 |
| 20 | +import pyarrow as pa |
| 21 | +import pytest |
| 22 | +from vgi_rpc.conformance.fake_vendor import FakeVendorServer |
| 23 | +from vgi_rpc.vendor import VendorBlobClient |
| 24 | + |
| 25 | +from vgi._test_fixtures.fake_blob_vendor import serve_fake_blob_vendor |
| 26 | +from vgi.arguments import Arguments |
| 27 | +from vgi.client import Client |
| 28 | + |
| 29 | +pytest.importorskip("aiohttp", reason="blob downloads need vgi-rpc[external]") |
| 30 | + |
| 31 | +WORKER = "vgi-fixture-worker" |
| 32 | + |
| 33 | + |
| 34 | +@pytest.fixture |
| 35 | +def vendor() -> Iterator[FakeVendorServer]: |
| 36 | + """The fake vendor with its stats route.""" |
| 37 | + server = serve_fake_blob_vendor() |
| 38 | + try: |
| 39 | + yield server |
| 40 | + finally: |
| 41 | + server.close() |
| 42 | + |
| 43 | + |
| 44 | +def _stats(vendor: FakeVendorServer) -> dict[str, int]: |
| 45 | + resp = httpx2.get(vendor.url + "/__stats__", timeout=10.0) |
| 46 | + resp.raise_for_status() |
| 47 | + stats: dict[str, int] = json.loads(resp.content) |
| 48 | + return stats |
| 49 | + |
| 50 | + |
| 51 | +def test_stats_endpoint_counts_traffic(vendor: FakeVendorServer) -> None: |
| 52 | + """``/__stats__`` counts vendor calls, signed-URL traffic and live bytes.""" |
| 53 | + assert _stats(vendor)["puts"] == 0 |
| 54 | + client = VendorBlobClient(vendor.url, "test-token") |
| 55 | + ref = client.put_bytes(b"x" * 1000) |
| 56 | + assert client.get_bytes(ref) == b"x" * 1000 |
| 57 | + client.delete([ref]) |
| 58 | + client.close() |
| 59 | + stats = _stats(vendor) |
| 60 | + assert stats["puts"] == 1 and stats["gets"] == 1 and stats["deletes"] == 1 |
| 61 | + assert stats["storage_puts"] == 1 and stats["storage_gets"] >= 1 |
| 62 | + assert stats["bytes_uploaded"] == 1000 and stats["bytes_downloaded"] >= 1000 |
| 63 | + assert stats["objects"] == 0 and stats["bytes"] == 0 |
| 64 | + |
| 65 | + |
| 66 | +def test_launcher_cli_prints_port_and_url(tmp_path: Path) -> None: |
| 67 | + """``python -m vgi._test_fixtures.fake_blob_vendor`` prints PORT and URL, honours --token.""" |
| 68 | + proc = subprocess.Popen( |
| 69 | + [sys.executable, "-m", "vgi._test_fixtures.fake_blob_vendor", "--token", "T=ten"], |
| 70 | + stdout=subprocess.PIPE, |
| 71 | + text=True, |
| 72 | + ) |
| 73 | + try: |
| 74 | + assert proc.stdout is not None |
| 75 | + port = proc.stdout.readline().strip() |
| 76 | + url = proc.stdout.readline().strip() |
| 77 | + assert port.startswith("PORT:") and url == f"URL:http://127.0.0.1:{port[5:]}" |
| 78 | + base = url[4:] |
| 79 | + assert httpx2.get(base + "/__stats__", timeout=10.0).json()["puts"] == 0 |
| 80 | + assert VendorBlobClient(base, "T").put_bytes(b"hi").size == 2 |
| 81 | + finally: |
| 82 | + proc.terminate() |
| 83 | + proc.wait(timeout=10) |
| 84 | + |
| 85 | + |
| 86 | +@pytest.fixture |
| 87 | +def externalizing_env(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, vendor: FakeVendorServer) -> FakeVendorServer: |
| 88 | + """Fixture-worker environment: SQLite storage wrapped by the vendor, 4 KiB threshold.""" |
| 89 | + monkeypatch.setenv("VGI_WORKER_SHARED_STORAGE", "sqlite") |
| 90 | + monkeypatch.setenv("VGI_WORKER_SQLITE_PATH", str(tmp_path / "storage.db")) |
| 91 | + monkeypatch.setenv("VGI_STORAGE_EXTERNALIZE", "1") |
| 92 | + monkeypatch.setenv("VGI_STORAGE_EXTERNALIZE_BYTES", "4096") |
| 93 | + monkeypatch.setenv("VGI_BLOB_VENDOR_URL", vendor.url) |
| 94 | + monkeypatch.setenv("VGI_BLOB_VENDOR_TOKEN", "test-token") |
| 95 | + return vendor |
| 96 | + |
| 97 | + |
| 98 | +def _expected(values: list[str]) -> tuple[list[int], list[str]]: |
| 99 | + return [len(v.encode()) for v in values], [hashlib.sha256(v.encode()).hexdigest() for v in values] |
| 100 | + |
| 101 | + |
| 102 | +def _input(width: int, n: int) -> list[pa.RecordBatch]: |
| 103 | + return [ |
| 104 | + pa.RecordBatch.from_pydict( |
| 105 | + {"s": [chr(97 + (b * 2 + i) % 26) * width for i in range(2)], "k": [b * 2, b * 2 + 1]} |
| 106 | + ) |
| 107 | + for b in range(n) |
| 108 | + ] |
| 109 | + |
| 110 | + |
| 111 | +def test_blob_buffer_echo_externalizes_storage(externalizing_env: FakeVendorServer) -> None: |
| 112 | + """Each buffered batch goes to the vendor (over 4 KiB) and is replayed with checksums.""" |
| 113 | + batches = _input(50_000, 3) |
| 114 | + with Client(WORKER, pool=None) as client: |
| 115 | + out = list( |
| 116 | + client.table_buffering_function(function_name="blob_buffer_echo", schema_path=["main"], input=iter(batches)) |
| 117 | + ) |
| 118 | + rows = sorted(pa.Table.from_batches([b for b in out if b.num_rows]).to_pylist(), key=lambda r: str(r["s"])) |
| 119 | + values: list[str] = sorted(str(v) for b in batches for v in b.column(0).to_pylist()) |
| 120 | + lens, digests = _expected(values) |
| 121 | + assert [r["s"] for r in rows] == values |
| 122 | + assert [r["payload_len"] for r in rows] == lens |
| 123 | + assert [r["payload_sha256"] for r in rows] == digests |
| 124 | + stats = _stats(externalizing_env) |
| 125 | + assert stats["puts"] >= 3 and stats["gets"] >= 3 |
| 126 | + |
| 127 | + |
| 128 | +def test_blob_tio_externalizes_storage(externalizing_env: FakeVendorServer) -> None: |
| 129 | + """blob_tio round-trips every batch through externalized storage.""" |
| 130 | + batches = _input(20_000, 2) |
| 131 | + with Client(WORKER, pool=None) as client: |
| 132 | + out = list(client.table_in_out_function(function_name="blob_tio", schema_path=["main"], input=iter(batches))) |
| 133 | + rows = pa.Table.from_batches([b for b in out if b.num_rows]).to_pylist() |
| 134 | + values = sorted(str(v) for b in batches for v in b.column(0).to_pylist()) |
| 135 | + assert sorted(str(r["s"]) for r in rows) == values |
| 136 | + assert {r["payload_len"] for r in rows} == {20_000} |
| 137 | + stats = _stats(externalizing_env) |
| 138 | + assert stats["puts"] >= 2 and stats["gets"] >= 2 and stats["deletes"] == 0 |
| 139 | + |
| 140 | + |
| 141 | +def test_scalars_and_table_functions(externalizing_env: FakeVendorServer) -> None: |
| 142 | + """blob_repeat, blob_len, blob_rows, blob_param_echo and vgi_test_blob_stats.""" |
| 143 | + with Client(WORKER, pool=None) as client: |
| 144 | + rep = list( |
| 145 | + client.scalar_function( |
| 146 | + function_name="blob_repeat", |
| 147 | + schema_path=["main"], |
| 148 | + input=iter([pa.RecordBatch.from_pydict({"s": ["ab", None], "n": [3, 2]})]), |
| 149 | + ) |
| 150 | + ) |
| 151 | + assert rep[0].column(0).to_pylist() == ["ababab", None] |
| 152 | + lens = list( |
| 153 | + client.scalar_function( |
| 154 | + function_name="blob_len", |
| 155 | + schema_path=["main"], |
| 156 | + input=iter([pa.RecordBatch.from_pydict({"s": ["x" * 100_000, "é"]})]), |
| 157 | + ) |
| 158 | + ) |
| 159 | + assert lens[0].column(0).to_pylist() == [100_000, 2] |
| 160 | + rows = list( |
| 161 | + client.table_function( |
| 162 | + function_name="blob_rows", |
| 163 | + schema_path=["main"], |
| 164 | + arguments=Arguments(positional=(pa.scalar(3000), pa.scalar(5))), |
| 165 | + ) |
| 166 | + ) |
| 167 | + table = pa.Table.from_batches([b for b in rows if b.num_rows]) |
| 168 | + assert table.num_rows == 3000 |
| 169 | + assert table.column("payload")[27].as_py() == "bbbbb" |
| 170 | + payload = "p" * 300_000 |
| 171 | + echo = list( |
| 172 | + client.table_function( |
| 173 | + function_name="blob_param_echo", |
| 174 | + schema_path=["main"], |
| 175 | + arguments=Arguments(positional=(pa.scalar(payload),)), |
| 176 | + ) |
| 177 | + ) |
| 178 | + row = pa.Table.from_batches([b for b in echo if b.num_rows]).to_pylist() |
| 179 | + assert row == [{"payload_len": 300_000, "payload_sha256": hashlib.sha256(payload.encode()).hexdigest()}] |
| 180 | + stats = list(client.table_function(function_name="vgi_test_blob_stats", schema_path=["main"])) |
| 181 | + stats_row = pa.Table.from_batches([b for b in stats if b.num_rows]).to_pylist() |
| 182 | + assert len(stats_row) == 1 and set(stats_row[0]) >= {"puts", "gets", "bytes", "upload_urls", "deletes"} |
0 commit comments