Skip to content

Commit c3128d6

Browse files
rustyconoverclaude
andcommitted
Generic ExternalizingStorage wrapper; blob_test fixtures and a fake vendor
Storage externalization moves out of the cloudflare-do client into vgi.function_storage_blobs.ExternalizingStorage, which wraps any backend with the same per-value envelope (0x00 || raw, 0x01 || size || sha256 || object_id) and blob-vendor upload/fetch/clean-up. _resolve_storage always wraps cloudflare-do (1 MiB cap, vendor optional) and wraps any other backend only with VGI_STORAGE_EXTERNALIZE=1, which requires VGI_BLOB_VENDOR_URL; SQLite's on-disk format is unchanged by default. Threshold: VGI_STORAGE_EXTERNALIZE_BYTES (alias VGI_CF_DO_EXTERNALIZE_BYTES). FunctionStorageCfDo is the raw transport again. state_drain still calls the backend eagerly, so an unconsumed drain of SQLite drains as before. For the DuckDB extension's externalization lane: - vgi._test_fixtures.fake_blob_vendor: runnable fake vendor (PORT:/URL: on stdout, --token, --port-file) with an unauthenticated GET /__stats__; - the blob_test catalog (both fixture entry points): blob_repeat, blob_len, blob_rows, blob_param_echo, blob_buffer_echo, blob_tio and vgi_test_blob_stats(), in their own catalog so example counts hold; - vgi-fixture-http takes the vendor from the environment like vgi-serve. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 00c8c25 commit c3128d6

13 files changed

Lines changed: 1796 additions & 475 deletions

‎CLAUDE.md‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -325,8 +325,10 @@ vgi-client --input data.parquet --function sum_all_columns --worker vgi-fixture-
325325
| `VGI_CF_DO_TOKEN` | Bearer token for Cloudflare Worker auth (optional) |
326326
| `VGI_CF_DO_DEBUG_LOG` | File path for Cloudflare DO storage debug/timing logs |
327327
| `VGI_BLOB_VENDOR_URL` | Blob vendor (region-pinned pre-signed R2 URLs). Enables cf-do value externalization and, under `vgi-serve --http`, result externalization + client upload URLs. Token: `VGI_BLOB_VENDOR_TOKEN`, falling back to `VGI_CF_DO_TOKEN` |
328-
| `VGI_CF_DO_EXTERNALIZE_BYTES` | cf-do values at or over this size go to the blob vendor (default 524288, max 1048576) |
329-
| `VGI_RPC_MAX_REQUEST_BYTES` | `vgi-serve --http`: advertised and enforced request cap; clients upload larger requests via the vendor's upload URLs |
328+
| `VGI_STORAGE_EXTERNALIZE` | `1` wraps any storage backend (e.g. SQLite) in `ExternalizingStorage`; needs `VGI_BLOB_VENDOR_URL`. cloudflare-do is always wrapped |
329+
| `VGI_STORAGE_EXTERNALIZE_BYTES` | Storage values at or over this size go to the blob vendor (default 524288; max 1048576 on cloudflare-do). Alias: `VGI_CF_DO_EXTERNALIZE_BYTES` |
330+
| `VGI_TEST_BLOB_STATS_URL` | Fixture only: where `vgi_test_blob_stats()` reads counters (default `$VGI_BLOB_VENDOR_URL/__stats__`) |
331+
| `VGI_RPC_MAX_REQUEST_BYTES` | `vgi-serve --http` (and `vgi-fixture-http` with the vendor): advertised and enforced request cap; clients upload larger requests via the vendor's upload URLs |
330332
| `VGI_RPC_EXTERNALIZE_THRESHOLD_BYTES` / `VGI_RPC_EXTERNAL_COMPRESSION` / `VGI_RPC_MAX_UPLOAD_BYTES` | With the vendor: result externalization threshold (default 1 MiB), its compression, and the advertised upload size |
331333

332334
### Worker Debug Mode

‎docs/shared-storage.md‎

Lines changed: 20 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -146,25 +146,30 @@ tables automatically on first request.
146146
| `VGI_CF_DO_DEBUG_LOG` | File path for debug/timing logs |
147147
| `VGI_BLOB_VENDOR_URL` | Blob vendor for values over the DO's 1 MiB cap (optional; see below) |
148148
| `VGI_BLOB_VENDOR_TOKEN` | Vendor bearer token (defaults to `VGI_CF_DO_TOKEN`) |
149-
| `VGI_CF_DO_EXTERNALIZE_BYTES` | With the vendor, values of at least this size are stored as blobs (default 524288, at most 1048576) |
149+
| `VGI_STORAGE_EXTERNALIZE_BYTES` | With the vendor, values of at least this size are stored as blobs (default 524288; at most 1048576 on cloudflare-do). `VGI_CF_DO_EXTERNALIZE_BYTES` is an alias |
150150

151151
### Large Values (Blob Vendor)
152152

153-
The Durable Object refuses any stored value over 1 MiB. With
154-
`VGI_BLOB_VENDOR_URL` set, a value of `VGI_CF_DO_EXTERNALIZE_BYTES` or more
153+
`vgi.function_storage_blobs.ExternalizingStorage` wraps any backend. With
154+
`VGI_BLOB_VENDOR_URL` set, a value of `VGI_STORAGE_EXTERNALIZE_BYTES` or more
155155
(work-queue item, `state_*` value or log item) is uploaded to the blob vendor
156-
before the DO request, and the DO stores a ~73-byte pointer. Reads fetch the
157-
blob back and check its size and SHA-256. The `FunctionStorage` API does not
158-
change. Without the vendor, a value over 1 MiB fails client-side with an
159-
error naming `VGI_BLOB_VENDOR_URL`. Installing the vendor client needs
160-
`vgi[external]`.
161-
162-
Every value the client writes carries a one-byte envelope tag, whether or not
163-
the vendor is configured: `0x00 || value` inline, `0x01 || size || sha256 ||
164-
object_id` for a blob. A value without a valid tag (for example one written by
165-
an older release) fails to read with `StorageEnvelopeError`. Executions are
166-
short-lived, so nothing needs migrating, but old and new clients cannot share
167-
one running query.
156+
before the backend call, and the backend stores a ~73-byte pointer. Reads
157+
fetch the blob back and check its size and SHA-256. The `FunctionStorage` API
158+
does not change. Installing the vendor client needs `vgi[external]`.
159+
160+
The cloudflare-do backend is always wrapped, vendor or not, because the
161+
Durable Object refuses values over 1 MiB: without the vendor, a larger value
162+
fails client-side with an error naming `VGI_BLOB_VENDOR_URL`. Any other
163+
backend is wrapped only with `VGI_STORAGE_EXTERNALIZE=1` (which then requires
164+
the vendor), so SQLite's on-disk format is unchanged by default; the
165+
extension's externalization tests use SQLite plus a fake vendor this way.
166+
167+
Every value the wrapper writes carries a one-byte envelope tag:
168+
`0x00 || value` inline, `0x01 || size || sha256 || object_id` for a blob. A
169+
value without a valid tag (for example one written without the wrapper) fails
170+
to read with `StorageEnvelopeError`. Executions are short-lived, so nothing
171+
needs migrating, but wrapped and unwrapped clients cannot share one running
172+
query.
168173

169174
Blobs are scoped to the shard and execution. `execution_clear` and
170175
`queue_clear` delete their scope, `state_drain` the blobs it drained and

‎tests/test_blob_fixtures.py‎

Lines changed: 182 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,182 @@
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

Comments
 (0)