Skip to content

Commit 00c8c25

Browse files
rustyconoverclaude
andcommitted
vgi-serve: externalize results and vend upload URLs via the blob vendor
When VGI_BLOB_VENDOR_URL is set, create_app (and so both the waitress and granian paths) passes vgi-rpc's external_config_from_env() as the RpcServer's external_location -- large results go to the vendor and inbound pointers are pinned to its storage hosts -- and the VendorStorage as upload_url_provider, with VGI_RPC_MAX_UPLOAD_BYTES advertised. VGI_RPC_MAX_REQUEST_BYTES is read whenever set (advertised, enforced, and sizing waitress's buffers); the DuckDB extension only takes the upload-URL path for requests over it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 4333d83 commit 00c8c25

3 files changed

Lines changed: 245 additions & 2 deletions

File tree

‎CLAUDE.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -324,6 +324,10 @@ vgi-client --input data.parquet --function sum_all_columns --worker vgi-fixture-
324324
| `VGI_CF_DO_URL` | Cloudflare Worker URL (required when `cloudflare-do`) |
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 |
327+
| `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 |
330+
| `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 |
327331

328332
### Worker Debug Mode
329333

‎tests/test_serve_blob_vendor.py‎

Lines changed: 157 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,157 @@
1+
# Copyright 2025, 2026 Query Farm LLC - https://query.farm
2+
3+
"""``vgi-serve`` wiring of the blob vendor (``VGI_BLOB_VENDOR_URL``).
4+
5+
With the vendor configured, the HTTP worker externalizes large results to it
6+
(pointers carry vendor download URLs), vends client upload URLs, and pins
7+
inbound pointer URLs to the vendor's storage hosts.
8+
"""
9+
10+
from __future__ import annotations
11+
12+
import os
13+
import subprocess
14+
import sys
15+
from collections.abc import Iterator
16+
from urllib.parse import urlsplit
17+
18+
import pyarrow as pa
19+
import pytest
20+
from vgi_rpc.conformance.fake_vendor import FakeVendorServer, serve_fake_vendor
21+
from vgi_rpc.vendor import VendorStorage
22+
23+
from vgi.serve import resolve_blob_vendor_http_config
24+
25+
pytest.importorskip("aiohttp", reason="external location resolution needs vgi-rpc[external]")
26+
27+
28+
@pytest.fixture
29+
def vendor() -> Iterator[FakeVendorServer]:
30+
"""A fake blob vendor on a background thread."""
31+
with serve_fake_vendor() as server:
32+
yield server
33+
34+
35+
def test_nothing_configured() -> None:
36+
"""No vendor and no request cap: everything off, as before."""
37+
cfg = resolve_blob_vendor_http_config({})
38+
assert (cfg.external_location, cfg.upload_url_provider, cfg.max_upload_bytes, cfg.max_request_bytes) == (
39+
None,
40+
None,
41+
None,
42+
None,
43+
)
44+
45+
46+
def test_request_cap_without_vendor() -> None:
47+
"""VGI_RPC_MAX_REQUEST_BYTES is honoured on its own (an explicit operator setting)."""
48+
cfg = resolve_blob_vendor_http_config({"VGI_RPC_MAX_REQUEST_BYTES": "1048576"})
49+
assert cfg.max_request_bytes == 1048576
50+
assert cfg.external_location is None and cfg.upload_url_provider is None
51+
52+
53+
@pytest.mark.parametrize("bad", ["0", "-1", "big"])
54+
def test_malformed_request_cap(bad: str) -> None:
55+
"""A malformed cap stops startup."""
56+
with pytest.raises(ValueError, match="VGI_RPC_MAX_REQUEST_BYTES"):
57+
resolve_blob_vendor_http_config({"VGI_RPC_MAX_REQUEST_BYTES": bad})
58+
59+
60+
def test_vendor_configured(vendor: FakeVendorServer) -> None:
61+
"""The vendor supplies the external config, the upload URL provider and the advertised upload size."""
62+
cfg = resolve_blob_vendor_http_config(
63+
{
64+
"VGI_BLOB_VENDOR_URL": vendor.url,
65+
"VGI_CF_DO_TOKEN": "test-token",
66+
"VGI_RPC_EXTERNALIZE_THRESHOLD_BYTES": "2048",
67+
"VGI_RPC_MAX_UPLOAD_BYTES": "1073741824",
68+
"VGI_RPC_MAX_REQUEST_BYTES": "65536",
69+
}
70+
)
71+
assert cfg.external_location is not None
72+
assert isinstance(cfg.upload_url_provider, VendorStorage)
73+
assert cfg.external_location.storage is cfg.upload_url_provider
74+
assert cfg.external_location.externalize_threshold_bytes == 2048
75+
assert cfg.max_upload_bytes == 1073741824
76+
assert cfg.max_request_bytes == 65536
77+
78+
79+
def test_vendor_without_token(vendor: FakeVendorServer) -> None:
80+
"""A vendor URL with no token stops startup."""
81+
with pytest.raises(ValueError, match="VGI_BLOB_VENDOR_TOKEN"):
82+
resolve_blob_vendor_http_config({"VGI_BLOB_VENDOR_URL": vendor.url})
83+
84+
85+
def test_vgi_serve_externalizes_results_and_vends_upload_urls(vendor: FakeVendorServer) -> None:
86+
"""End to end: a large scalar result comes back as a vendor pointer and resolves."""
87+
from vgi_rpc import ExternalLocationConfig
88+
from vgi_rpc.http import http_capabilities, http_connect
89+
from vgi_rpc.metadata import LOCATION_SOURCE_KEY
90+
from vgi_rpc.rpc import AnnotatedBatch
91+
from vgi_rpc.vendor import pinned_hosts_validator
92+
93+
from vgi.arguments import Arguments
94+
from vgi.invocation import FunctionType
95+
from vgi.protocol import BindRequest, InitRequest, VgiProtocol
96+
97+
env = {
98+
**os.environ,
99+
"VGI_BLOB_VENDOR_URL": vendor.url,
100+
"VGI_BLOB_VENDOR_TOKEN": "test-token",
101+
"VGI_RPC_EXTERNALIZE_THRESHOLD_BYTES": "16384",
102+
"VGI_RPC_MAX_REQUEST_BYTES": "262144",
103+
"VGI_RPC_MAX_UPLOAD_BYTES": "1073741824",
104+
"PYTHONUNBUFFERED": "1",
105+
}
106+
proc = subprocess.Popen(
107+
[sys.executable, "-m", "vgi.serve", "vgi._test_fixtures.worker:ExampleWorker", "--http"]
108+
+ ["--host", "127.0.0.1", "--port", "0"],
109+
env=env,
110+
stdout=subprocess.PIPE,
111+
stderr=subprocess.DEVNULL,
112+
text=True,
113+
)
114+
try:
115+
assert proc.stdout is not None
116+
line = proc.stdout.readline()
117+
assert line.startswith("PORT:"), line
118+
base_url = f"http://127.0.0.1:{line.strip().split(':', 1)[1]}"
119+
120+
caps = http_capabilities(base_url=base_url)
121+
assert caps.upload_url_support is True
122+
assert caps.max_request_bytes == 262144
123+
assert caps.max_upload_bytes == 1073741824
124+
125+
payload_bytes = 64 * 1024
126+
validator = pinned_hosts_validator([vendor.vendor.host], allow_http=True)
127+
with http_connect(
128+
VgiProtocol, # type: ignore[type-abstract]
129+
base_url=base_url,
130+
external_location=ExternalLocationConfig(url_validator=validator),
131+
) as proxy:
132+
schema = pa.schema([("dummy", pa.int64())])
133+
bind = BindRequest(
134+
function_name="random_bytes",
135+
arguments=Arguments(positional=(pa.scalar(7), pa.scalar(payload_bytes))),
136+
function_type=FunctionType.SCALAR,
137+
input_schema=schema,
138+
)
139+
bound = proxy.bind(request=bind)
140+
stream = proxy.init(
141+
request=InitRequest(
142+
bind_call=bind, output_schema=bound.output_schema, bind_opaque_data=bound.opaque_data
143+
)
144+
)
145+
try:
146+
out = stream.exchange(AnnotatedBatch(batch=pa.RecordBatch.from_pydict({"dummy": [1]}, schema=schema)))
147+
finally:
148+
stream.close()
149+
assert len(out.batch.column("result")[0].as_py()) == payload_bytes
150+
assert out.custom_metadata is not None
151+
source = out.custom_metadata.get(LOCATION_SOURCE_KEY)
152+
assert isinstance(source, bytes)
153+
assert urlsplit(source.decode()).netloc == vendor.vendor.host
154+
assert vendor.vendor.stats().get("/v1/blobs/put", 0) >= 1
155+
finally:
156+
proc.terminate()
157+
proc.wait(timeout=10)

‎vgi/serve.py‎

Lines changed: 84 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,8 @@
3232
import os
3333
import secrets
3434
import sys
35-
from collections.abc import Callable, Iterable, Sequence
35+
from collections.abc import Callable, Iterable, Mapping, Sequence
36+
from dataclasses import dataclass
3637
from types import ModuleType
3738
from typing import TYPE_CHECKING, Any, Literal
3839

@@ -198,6 +199,81 @@ def on_get(self, req: falcon.Request, resp: falcon.Response) -> None:
198199
return _FrontendRedirectResource()
199200

200201

202+
@dataclass(frozen=True)
203+
class BlobVendorHttpConfig:
204+
"""HTTP server settings derived from the blob-vendor environment.
205+
206+
Attributes:
207+
external_location: Server external-location config (large results
208+
are uploaded to the vendor and replaced by a pointer; inbound
209+
pointers are fetched only from the vendor's storage hosts), or
210+
``None`` when ``VGI_BLOB_VENDOR_URL`` is unset.
211+
upload_url_provider: The vendor, vending pre-signed upload URLs so
212+
clients can send requests over ``max_request_bytes``; ``None``
213+
without the vendor.
214+
max_upload_bytes: ``VGI_RPC_MAX_UPLOAD_BYTES`` (advertised only).
215+
max_request_bytes: ``VGI_RPC_MAX_REQUEST_BYTES`` -- advertised and
216+
enforced. Clients (the DuckDB extension) only take the upload-URL
217+
path for a request larger than this, so set it with the vendor.
218+
219+
"""
220+
221+
external_location: Any = None
222+
upload_url_provider: Any = None
223+
max_upload_bytes: int | None = None
224+
max_request_bytes: int | None = None
225+
226+
227+
def resolve_blob_vendor_http_config(env: Mapping[str, str] | None = None) -> BlobVendorHttpConfig:
228+
"""Read the blob-vendor HTTP settings from the environment.
229+
230+
``VGI_BLOB_VENDOR_URL`` (with ``VGI_BLOB_VENDOR_TOKEN``, falling back to
231+
``VGI_CF_DO_TOKEN``) turns on result externalization
232+
(``VGI_RPC_EXTERNALIZE_THRESHOLD_BYTES``, default 1 MiB;
233+
``VGI_RPC_EXTERNAL_COMPRESSION``) and client upload URLs
234+
(``VGI_RPC_MAX_UPLOAD_BYTES``). ``VGI_RPC_MAX_REQUEST_BYTES`` is read
235+
either way: it is an explicit operator setting.
236+
237+
Args:
238+
env: Environment mapping (defaults to ``os.environ``).
239+
240+
Returns:
241+
The settings; all ``None`` when nothing is configured.
242+
243+
Raises:
244+
ValueError: A variable is set but malformed, or the vendor URL is set
245+
without a token.
246+
247+
"""
248+
environ = os.environ if env is None else env
249+
max_request_bytes = _positive_int_env(environ, "VGI_RPC_MAX_REQUEST_BYTES")
250+
if not environ.get("VGI_BLOB_VENDOR_URL", "").strip():
251+
return BlobVendorHttpConfig(max_request_bytes=max_request_bytes)
252+
from vgi_rpc.vendor import external_config_from_env, max_upload_bytes_from_env
253+
254+
external = external_config_from_env(environ)
255+
assert external is not None
256+
return BlobVendorHttpConfig(
257+
external_location=external,
258+
upload_url_provider=external.storage,
259+
max_upload_bytes=max_upload_bytes_from_env(environ),
260+
max_request_bytes=max_request_bytes,
261+
)
262+
263+
264+
def _positive_int_env(env: Mapping[str, str], name: str) -> int | None:
265+
raw = env.get(name, "").strip()
266+
if not raw:
267+
return None
268+
try:
269+
value = int(raw)
270+
except ValueError:
271+
raise ValueError(f"{name} must be an integer, got {raw!r}") from None
272+
if value <= 0:
273+
raise ValueError(f"{name} must be positive, got {value}")
274+
return value
275+
276+
201277
def create_app(
202278
worker_cls: type[Worker],
203279
*,
@@ -355,12 +431,15 @@ def create_app(
355431
worker._vgi_tracer = VgiTracer.create(otel_config)
356432
worker._signing_key = signing_key
357433

434+
blob_http = resolve_blob_vendor_http_config()
435+
358436
server = build_rpc_server(
359437
worker,
360438
transport="http",
361439
describe=describe,
362440
introspect_principals=introspect_principals,
363441
grant_keys=grant_keys if grant_keys is not None else resolve_grant_keys(),
442+
external_location=blob_http.external_location,
364443
signing_key_configured=signing_key_configured,
365444
)
366445
authenticate, identity_bearer = _compose_identity_bearer(server, authenticate)
@@ -399,6 +478,9 @@ def create_app(
399478
otel_config=otel_config,
400479
max_stream_response_bytes=max_stream_response_bytes,
401480
max_externalized_response_bytes=max_externalized_response_bytes,
481+
max_request_bytes=blob_http.max_request_bytes,
482+
upload_url_provider=blob_http.upload_url_provider,
483+
max_upload_bytes=blob_http.max_upload_bytes,
402484
enable_landing_page=False,
403485
identity_bearer=identity_bearer,
404486
strict_auth=hosted,
@@ -1585,7 +1667,7 @@ def _serve_http(
15851667

15861668
_tame_queue_depth_logger()
15871669
serve_kwargs: dict[str, Any] = {"host": host, "port": port, "_quiet": True}
1588-
serve_kwargs.update(waitress_arrow_tuning())
1670+
serve_kwargs.update(waitress_arrow_tuning(resolve_blob_vendor_http_config().max_request_bytes))
15891671
if http_threads is not None:
15901672
serve_kwargs["threads"] = http_threads
15911673
waitress.serve(wsgi_app, **serve_kwargs)

0 commit comments

Comments
 (0)