Skip to content

Commit 85c5999

Browse files
rustyconoverclaude
andcommitted
blob_test: SDK-neutral contract; storage-blob error messages; envelope vectors
- Storage blob read failures raise StorageBlobIntegrityError / StorageBlobMissingError / StorageBlobError with messages that start 'storage blob <id>' and name 'sha256 mismatch', 'size mismatch' or 'is missing: not found' (the vgi extension's SDK-neutral regexes). - blob_test: drop vgi_test_blob_stats and the fake_blob_vendor wrapper; vgi-rpc's vgi-rpc-fake-vendor --test-routes serves /__stats__ itself. Add blob_store_values (one storage value of exactly each input value's size) for threshold-boundary, empty and NULL tests. - Storage envelope test vectors (vgi/_test_fixtures/storage_envelope_v1.json, scripts/gen_storage_envelope_vectors.py), checked against this implementation and the vgi extension's copy. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent e2af552 commit 85c5999

9 files changed

Lines changed: 683 additions & 317 deletions

‎CLAUDE.md‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -328,7 +328,6 @@ vgi-client --input data.parquet --function sum_all_columns --worker vgi-fixture-
328328
| `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` |
329329
| `VGI_STORAGE_EXTERNALIZE` | `1` wraps any storage backend (e.g. SQLite) in `ExternalizingStorage`; needs `VGI_BLOB_VENDOR_URL`. cloudflare-do is always wrapped |
330330
| `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` |
331-
| `VGI_TEST_BLOB_STATS_URL` | Fixture only: where `vgi_test_blob_stats()` reads counters (default `$VGI_BLOB_VENDOR_URL/__stats__`) |
332331
| `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 |
333332
| `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 |
334333

Lines changed: 160 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,160 @@
1+
# Copyright 2025, 2026 Query Farm LLC - https://query.farm
2+
3+
"""Regenerate ``vgi/_test_fixtures/storage_envelope_v1.json``.
4+
5+
Language-neutral test vectors for the function-storage value envelope and the
6+
blob-vendor scope names (`vgi.function_storage_blobs`), so another SDK can be
7+
byte-compatible. Every input is fixed, so the output is byte-identical on
8+
every run; ``tests/test_storage_envelope_vectors.py`` fails if the file drifts
9+
from what this script produces. The vgi extension carries a verbatim copy at
10+
``test/vectors/storage_envelope_v1.json``. Run::
11+
12+
uv run python scripts/gen_storage_envelope_vectors.py
13+
"""
14+
15+
from __future__ import annotations
16+
17+
import hashlib
18+
import json
19+
from pathlib import Path
20+
from typing import Any
21+
22+
from vgi_rpc.vendor import BlobRef
23+
24+
from vgi.function_storage_blobs import (
25+
_OBJECT_ID_RE,
26+
_POINTER_FIXED,
27+
_SHARD_RE,
28+
DEFAULT_EXTERNALIZE_BYTES,
29+
TAG_INLINE,
30+
TAG_POINTER,
31+
_blob_execution_id,
32+
_blob_shard,
33+
encode_inline,
34+
encode_pointer,
35+
)
36+
37+
OUT = Path(__file__).resolve().parent.parent / "vgi" / "_test_fixtures" / "storage_envelope_v1.json"
38+
39+
_INLINE: list[tuple[str, bytes]] = [
40+
("empty value", b""),
41+
("ascii text", b"hello"),
42+
("value starting with the pointer tag byte", b"\x01\x02\x03"),
43+
("value starting with the inline tag byte", b"\x00\x00"),
44+
("all byte values", bytes(range(256))),
45+
]
46+
47+
_POINTERS: list[tuple[str, str, bytes]] = [
48+
("32-hex object id (the vendor's)", "0123456789abcdef0123456789abcdef", b"x" * 4096),
49+
("object id using every allowed punctuation", "A-z_0.9:obj", b"payload"),
50+
("one-character object id, empty blob", "a", b""),
51+
("128-character object id (the maximum)", "o" * 128, b"y" * 1_000_000),
52+
]
53+
54+
55+
def _pointer_case(name: str, object_id: str, blob: bytes) -> dict[str, Any]:
56+
ref = BlobRef(object_id=object_id, size=len(blob), sha256=hashlib.sha256(blob).hexdigest())
57+
return {
58+
"name": name,
59+
"object_id": object_id,
60+
"size": ref.size,
61+
"sha256": ref.sha256,
62+
"envelope_hex": encode_pointer(ref).hex(),
63+
}
64+
65+
66+
def _malformed() -> list[dict[str, str]]:
67+
good = encode_pointer(BlobRef(object_id="abc", size=5, sha256="00" * 32))
68+
fixed = good[:_POINTER_FIXED]
69+
return [
70+
{"name": "empty stored value", "envelope_hex": "", "error": "empty"},
71+
{"name": "unknown tag 0x02", "envelope_hex": "02616263", "error": "unknown_tag"},
72+
{"name": "unknown tag 0xff", "envelope_hex": "ff", "error": "unknown_tag"},
73+
{"name": "pointer tag only", "envelope_hex": "01", "error": "malformed_pointer"},
74+
{"name": "pointer truncated inside the sha256", "envelope_hex": good[:20].hex(), "error": "malformed_pointer"},
75+
{"name": "pointer with an empty object id", "envelope_hex": fixed.hex(), "error": "malformed_pointer"},
76+
{
77+
"name": "pointer object id with a disallowed character (/)",
78+
"envelope_hex": (fixed + b"a/b").hex(),
79+
"error": "malformed_pointer",
80+
},
81+
{
82+
"name": "pointer object id with a space",
83+
"envelope_hex": (fixed + b"a b").hex(),
84+
"error": "malformed_pointer",
85+
},
86+
{
87+
"name": "pointer object id of 129 characters",
88+
"envelope_hex": (fixed + b"o" * 129).hex(),
89+
"error": "malformed_pointer",
90+
},
91+
]
92+
93+
94+
def _scopes() -> list[dict[str, str]]:
95+
cases = [
96+
("q", b"\x00" * 16),
97+
("s", bytes(range(16))),
98+
("s", b""),
99+
("q", b"\xab" * 63), # 2 + 126 hex chars = 128: kept
100+
("s", b"\xab" * 64), # 2 + 128 hex chars = 130: hashed
101+
]
102+
return [{"kind": k, "ident_hex": ident.hex(), "execution_id": _blob_execution_id(k, ident)} for k, ident in cases]
103+
104+
105+
def _shards() -> list[dict[str, str]]:
106+
keys = ["att-" + "ab" * 16, "", "loc-anon", "has space", "a/b", "x" * 128, "x" * 129, "colon:not-allowed"]
107+
return [{"shard_key": key, "shard": _blob_shard(key)} for key in keys]
108+
109+
110+
def build() -> dict[str, Any]:
111+
"""Return the vectors document."""
112+
return {
113+
"format": "vgi.storage_envelope.v1",
114+
"description": (
115+
"Function-storage value envelope: every stored value is 0x00||raw (inline) or "
116+
"0x01||u64be(size)||sha256(32 bytes)||object_id (pointer to a blob-vendor object, purpose fs). "
117+
"Hex strings are lowercase. See docs/testing/blob-test-catalog.md in the vgi extension."
118+
),
119+
"tag_inline": TAG_INLINE,
120+
"tag_pointer": TAG_POINTER,
121+
"pointer_fixed_bytes": _POINTER_FIXED,
122+
"object_id_regex": _OBJECT_ID_RE.pattern.decode(),
123+
"default_externalize_bytes": DEFAULT_EXTERNALIZE_BYTES,
124+
"externalize_rule": "with a vendor, a value of len >= VGI_STORAGE_EXTERNALIZE_BYTES is a pointer, else inline",
125+
"inline": [
126+
{"name": name, "value_hex": raw.hex(), "envelope_hex": encode_inline(raw).hex()} for name, raw in _INLINE
127+
],
128+
"pointers": [_pointer_case(*case) for case in _POINTERS],
129+
"malformed": _malformed(),
130+
"scope_execution_ids": {
131+
"rule": (
132+
"'<kind>.<hex ident>' where kind is q (queue, ident = execution id) or s (state/log, "
133+
"ident = scope id); if longer than 128 characters, '<kind>.h<sha256(ident) hex>'"
134+
),
135+
"cases": _scopes(),
136+
},
137+
"scope_shards": {
138+
"rule": (
139+
"the storage shard key; empty becomes 'loc-anon'; a key not matching "
140+
f"{_SHARD_RE.pattern} becomes 'h-<sha256(utf8 key) hex>'"
141+
),
142+
"regex": _SHARD_RE.pattern,
143+
"cases": _shards(),
144+
},
145+
}
146+
147+
148+
def render() -> str:
149+
"""Return the vectors as the exact file contents."""
150+
return json.dumps(build(), indent=2) + "\n"
151+
152+
153+
def main() -> None:
154+
"""Write the vectors file."""
155+
OUT.write_text(render())
156+
print(f"wrote {OUT}")
157+
158+
159+
if __name__ == "__main__":
160+
main()

‎tests/test_blob_fixtures.py‎

Lines changed: 66 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -1,86 +1,65 @@
11
# Copyright 2025, 2026 Query Farm LLC - https://query.farm
22

3-
"""The ``blob_test`` fixture catalog and the runnable fake blob vendor.
3+
"""The ``blob_test`` fixture catalog.
44
55
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.
6+
``VGI_STORAGE_EXTERNALIZE=1`` over SQLite and vgi-rpc's fake vendor: the
7+
hermetic setup the DuckDB extension's externalization lane uses (there the
8+
fake runs as ``vgi-rpc-fake-vendor --test-routes`` and SQL reads its
9+
``/__stats__``; here the same counters come from the in-process fake).
810
"""
911

1012
from __future__ import annotations
1113

1214
import hashlib
13-
import json
14-
import subprocess
15-
import sys
1615
from collections.abc import Iterator
1716
from pathlib import Path
1817

19-
import httpx2
2018
import pyarrow as pa
2119
import pytest
22-
from vgi_rpc.conformance.fake_vendor import FakeVendorServer
23-
from vgi_rpc.vendor import VendorBlobClient
20+
from vgi_rpc.conformance.fake_vendor import FakeVendorServer, serve_fake_vendor
2421

25-
from vgi._test_fixtures.fake_blob_vendor import serve_fake_blob_vendor
22+
from vgi._test_fixtures.blob_catalog import CATALOG_NAME, BlobTestWorker
2623
from vgi.arguments import Arguments
2724
from vgi.client import Client
2825

2926
pytest.importorskip("aiohttp", reason="blob downloads need vgi-rpc[external]")
3027

3128
WORKER = "vgi-fixture-worker"
29+
THRESHOLD = 4096
3230

3331

3432
@pytest.fixture
3533
def vendor() -> Iterator[FakeVendorServer]:
36-
"""The fake vendor with its stats route."""
37-
server = serve_fake_blob_vendor()
38-
try:
34+
"""Run the fake vendor on a background thread."""
35+
with serve_fake_vendor({"test-token": "tenant-a"}) as server:
3936
yield server
40-
finally:
41-
server.close()
4237

4338

4439
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)
40+
"""Vendor API call counts (the ``/__stats__`` keys that tests here use)."""
41+
hits = vendor.vendor.stats()
42+
return {
43+
"puts": hits.get("/v1/blobs/put", 0),
44+
"gets": hits.get("/v1/blobs/get", 0),
45+
"deletes": hits.get("/v1/blobs/delete", 0),
46+
}
47+
48+
49+
def test_catalog_functions_match_the_contract() -> None:
50+
"""The catalog serves exactly the functions docs/testing/blob-test-catalog.md documents."""
51+
assert CATALOG_NAME == "blob_test"
52+
(schema,) = BlobTestWorker.catalog.schemas
53+
names = sorted(f.Meta.name for f in schema.functions) # type: ignore[attr-defined]
54+
assert names == [
55+
"blob_buffer_echo",
56+
"blob_len",
57+
"blob_param_echo",
58+
"blob_repeat",
59+
"blob_rows",
60+
"blob_store_values",
61+
"blob_tio",
62+
]
8463

8564

8665
@pytest.fixture
@@ -89,14 +68,14 @@ def externalizing_env(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, vendor: F
8968
monkeypatch.setenv("VGI_WORKER_SHARED_STORAGE", "sqlite")
9069
monkeypatch.setenv("VGI_WORKER_SQLITE_PATH", str(tmp_path / "storage.db"))
9170
monkeypatch.setenv("VGI_STORAGE_EXTERNALIZE", "1")
92-
monkeypatch.setenv("VGI_STORAGE_EXTERNALIZE_BYTES", "4096")
71+
monkeypatch.setenv("VGI_STORAGE_EXTERNALIZE_BYTES", str(THRESHOLD))
9372
monkeypatch.setenv("VGI_BLOB_VENDOR_URL", vendor.url)
9473
monkeypatch.setenv("VGI_BLOB_VENDOR_TOKEN", "test-token")
9574
return vendor
9675

9776

9877
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]
78+
return [len(v.encode()) for v in values], [hashlib.sha256(str(v).encode()).hexdigest() for v in values]
10079

10180

10281
def _input(width: int, n: int) -> list[pa.RecordBatch]:
@@ -139,7 +118,7 @@ def test_blob_tio_externalizes_storage(externalizing_env: FakeVendorServer) -> N
139118

140119

141120
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."""
121+
"""blob_repeat, blob_len, blob_rows and blob_param_echo."""
143122
with Client(WORKER, pool=None) as client:
144123
rep = list(
145124
client.scalar_function(
@@ -177,6 +156,33 @@ def test_scalars_and_table_functions(externalizing_env: FakeVendorServer) -> Non
177156
)
178157
row = pa.Table.from_batches([b for b in echo if b.num_rows]).to_pylist()
179158
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"}
159+
160+
161+
def _store_values(values: list[str | None]) -> list[dict[str, object]]:
162+
batch = pa.RecordBatch.from_pydict({"s": pa.array(values, pa.string()), "id": list(range(len(values)))})
163+
with Client(WORKER, pool=None) as client:
164+
out = list(
165+
client.table_in_out_function(function_name="blob_store_values", schema_path=["main"], input=iter([batch]))
166+
)
167+
return sorted(pa.Table.from_batches([b for b in out if b.num_rows]).to_pylist(), key=lambda r: int(r["id"]))
168+
169+
170+
def test_blob_store_values_threshold_boundary(externalizing_env: FakeVendorServer) -> None:
171+
"""Values one below, at and one above the threshold round-trip; only the last two are vendored."""
172+
values: list[str | None] = ["a" * (THRESHOLD - 1), "b" * THRESHOLD, "c" * (THRESHOLD + 1)]
173+
rows = _store_values(values)
174+
assert list(rows[0]) == ["id", "payload_len", "payload_sha256"]
175+
assert [r["payload_len"] for r in rows] == [len(str(v)) for v in values]
176+
assert [r["payload_sha256"] for r in rows] == [hashlib.sha256(str(v).encode()).hexdigest() for v in values]
177+
assert _stats(externalizing_env)["puts"] == 2
178+
179+
180+
def test_blob_store_values_empty_and_null(externalizing_env: FakeVendorServer) -> None:
181+
"""An empty value round-trips as empty; NULL stores nothing and reports NULLs."""
182+
rows = _store_values(["", None, "é"])
183+
assert [(r["payload_len"], r["payload_sha256"]) for r in rows] == [
184+
(0, hashlib.sha256(b"").hexdigest()),
185+
(None, None),
186+
(2, hashlib.sha256("é".encode()).hexdigest()),
187+
]
188+
assert _stats(externalizing_env)["puts"] == 0

0 commit comments

Comments
 (0)