Skip to content

Commit 4333d83

Browse files
rustyconoverclaude
andcommitted
cf-do storage: value envelope and blob-vendor externalization
The Durable Object refuses values over 1 MiB, so a buffered function storing large input failed the query with a 413. Every value the cloudflare-do client writes now carries a one-byte envelope: 0x00 || raw inline, or 0x01 || u64be(size) || sha256 || object_id pointing at a blob in the blob vendor (VGI_BLOB_VENDOR_URL, token VGI_BLOB_VENDOR_TOKEN falling back to VGI_CF_DO_TOKEN). With the vendor, values of VGI_CF_DO_EXTERNALIZE_BYTES (default 512 KiB) or more are uploaded before the DO request, idempotency key <attempt_id>.<index>, scope (shard, "q.<hex eid>" / "s.<hex scope>"); reads fetch and verify size and SHA-256. The FunctionStorage API is unchanged. The envelope is applied with or without the vendor so the stored format never depends on per-process configuration. Decoding is strict: an un-enveloped value raises StorageEnvelopeError. Without the vendor, an over-cap value fails client-side naming VGI_BLOB_VENDOR_URL. Sealed framework payloads are sealed in BoundStorage before reaching the client, so externalized ones stay AAD-authenticated. Clean-up is best-effort on a background thread: execution_clear and queue_clear delete their vendor scope, state_drain the blobs it drained, queue_pop the blob it claimed. Requires vgi-rpc 0.56.0 (vgi_rpc.vendor). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent db9de38 commit 4333d83

8 files changed

Lines changed: 1202 additions & 38 deletions

‎docs/shared-storage.md‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,33 @@ tables automatically on first request.
144144
| `VGI_CF_DO_URL` | Cloudflare Worker URL (required) |
145145
| `VGI_CF_DO_TOKEN` | Bearer token for authentication (optional) |
146146
| `VGI_CF_DO_DEBUG_LOG` | File path for debug/timing logs |
147+
| `VGI_BLOB_VENDOR_URL` | Blob vendor for values over the DO's 1 MiB cap (optional; see below) |
148+
| `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) |
150+
151+
### Large Values (Blob Vendor)
152+
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
155+
(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.
168+
169+
Blobs are scoped to the shard and execution. `execution_clear` and
170+
`queue_clear` delete their scope, `state_drain` the blobs it drained and
171+
`queue_pop` the blob it claimed. Clean-up is best-effort and runs on a
172+
background thread; the vendor's idle sweep and the bucket lifecycle rules
173+
are the backstop.
147174

148175
### Programmatic Usage
149176

‎pyproject.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ dependencies = [
4040
"pyarrow",
4141
"typer>=0.9",
4242
"platformdirs",
43-
"vgi-rpc>=0.55.0",
43+
"vgi-rpc>=0.56.0",
4444
"httpx2>=2.12.0",
4545
# vgi.query_execution seals execution handles with vgi_rpc.crypto, which
4646
# imports pycryptodome. vgi-rpc only pulls it in under its `http` extra, but

‎tests/_fake_cf_do.py‎

Lines changed: 195 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,195 @@
1+
# Copyright 2025, 2026 Query Farm LLC - https://query.farm
2+
3+
"""In-memory stand-in for the Cloudflare DO storage service, as an httpx2 transport.
4+
5+
Implements the endpoints `FunctionStorageCfDo` calls with the service's
6+
wire shapes (base64 keys and values, ``{rows, next_after}`` pages), its
7+
1 MiB per-value cap (413 ``payload_too_large``) and its ``attempt_id``
8+
replay for writes. One instance is one tenant; state is keyed by
9+
``shard_key`` so sharding bugs show up. Not a model of the DO's
10+
transactional details -- the live suite in
11+
``test_function_storage_cf_do_integration.py`` covers those.
12+
"""
13+
14+
from __future__ import annotations
15+
16+
import base64
17+
import json
18+
import threading
19+
from collections.abc import Callable
20+
from typing import Any
21+
22+
import httpx2
23+
24+
MAX_VALUE_BYTES = 1024 * 1024
25+
26+
27+
def _d(s: str) -> bytes:
28+
return base64.b64decode(s)
29+
30+
31+
def _e(b: bytes) -> str:
32+
return base64.b64encode(b).decode()
33+
34+
35+
class FakeCfDo:
36+
"""The fake service: in-memory tables plus request log and fault hooks."""
37+
38+
def __init__(self, *, page_rows: int = 2) -> None:
39+
"""Create an empty service whose scan/drain pages hold ``page_rows`` rows."""
40+
self.page_rows = page_rows
41+
self.queues: dict[tuple[str, bytes], list[bytes]] = {}
42+
self.state: dict[tuple[str, bytes, bytes, bytes], bytes] = {}
43+
self.logs: dict[tuple[str, bytes, bytes, bytes], list[tuple[int, bytes]]] = {}
44+
self.requests: list[tuple[str, dict[str, Any]]] = []
45+
self._replay: dict[str, dict[str, Any]] = {}
46+
self._drains: dict[str, list[tuple[bytes, bytes]]] = {}
47+
self._next_ordinal = 0
48+
self._lock = threading.Lock()
49+
#: Called with ``(endpoint, body)`` before handling; may return a status to fail with.
50+
self.fault: Callable[[str, dict[str, Any]], int | None] | None = None
51+
52+
def transport(self) -> httpx2.MockTransport:
53+
"""Return an httpx2 transport serving this fake."""
54+
return httpx2.MockTransport(self._handle)
55+
56+
def endpoint_counts(self) -> dict[str, int]:
57+
"""Return how many requests each endpoint received."""
58+
counts: dict[str, int] = {}
59+
for endpoint, _ in self.requests:
60+
counts[endpoint] = counts.get(endpoint, 0) + 1
61+
return counts
62+
63+
def stored_values(self) -> list[bytes]:
64+
"""Return every stored value as the DO holds it (envelopes)."""
65+
with self._lock:
66+
out = [v for q in self.queues.values() for v in q]
67+
out += list(self.state.values())
68+
out += [v for log in self.logs.values() for _, v in log]
69+
return out
70+
71+
def _handle(self, request: httpx2.Request) -> httpx2.Response:
72+
endpoint = request.url.path.lstrip("/")
73+
body: dict[str, Any] = json.loads(request.content)
74+
self.requests.append((endpoint, body))
75+
if self.fault is not None:
76+
status = self.fault(endpoint, body)
77+
if status is not None:
78+
return httpx2.Response(status, json={"error": "injected"})
79+
with self._lock:
80+
try:
81+
return httpx2.Response(200, json=self._dispatch(endpoint, body))
82+
except _TooLarge as exc:
83+
return httpx2.Response(413, json={"error": "payload_too_large", "message": str(exc)})
84+
85+
def _dispatch(self, endpoint: str, body: dict[str, Any]) -> dict[str, Any]:
86+
attempt = body.get("attempt_id")
87+
replay_key = f"{endpoint}:{attempt}" if attempt and endpoint not in ("state_drain",) else None
88+
if replay_key is not None and replay_key in self._replay:
89+
return self._replay[replay_key]
90+
result: dict[str, Any] = getattr(self, f"_op_{endpoint}")(body["shard_key"], body)
91+
if replay_key is not None:
92+
self._replay[replay_key] = result
93+
return result
94+
95+
@staticmethod
96+
def _check(value: bytes, what: str) -> bytes:
97+
if len(value) > MAX_VALUE_BYTES:
98+
raise _TooLarge(f"{what} exceeds {MAX_VALUE_BYTES} bytes (got {len(value)})")
99+
return value
100+
101+
# --- queue ---
102+
103+
def _op_queue_push(self, shard: str, body: dict[str, Any]) -> dict[str, Any]:
104+
items = [self._check(_d(i), "work item") for i in body["items"]]
105+
self.queues.setdefault((shard, _d(body["execution_id"])), []).extend(items)
106+
return {"count": len(items)}
107+
108+
def _op_queue_pop(self, shard: str, body: dict[str, Any]) -> dict[str, Any]:
109+
q = self.queues.get((shard, _d(body["execution_id"])), [])
110+
return {"item": _e(q.pop(0)) if q else None}
111+
112+
def _op_queue_clear(self, shard: str, body: dict[str, Any]) -> dict[str, Any]:
113+
q = self.queues.pop((shard, _d(body["execution_id"])), [])
114+
return {"cleared": len(q)}
115+
116+
# --- state ---
117+
118+
def _ns_rows(self, shard: str, scope: bytes, ns: bytes) -> list[tuple[bytes, bytes]]:
119+
return sorted((k[3], v) for k, v in self.state.items() if k[:3] == (shard, scope, ns))
120+
121+
def _op_state_get_many(self, shard: str, body: dict[str, Any]) -> dict[str, Any]:
122+
scope, ns = _d(body["scope_id"]), _d(body["ns"])
123+
rows = []
124+
for k in body["keys"]:
125+
v = self.state.get((shard, scope, ns, _d(k)))
126+
rows.append(None if v is None else {"value": _e(v)})
127+
return {"rows": rows}
128+
129+
def _op_state_put_many(self, shard: str, body: dict[str, Any]) -> dict[str, Any]:
130+
scope, ns = _d(body["scope_id"]), _d(body["ns"])
131+
for item in body["items"]:
132+
self.state[(shard, scope, ns, _d(item["key"]))] = self._check(_d(item["value"]), "value")
133+
return {}
134+
135+
def _page(self, rows: list[tuple[bytes, bytes]], after: str | None) -> dict[str, Any]:
136+
start = 0
137+
if after is not None:
138+
start = next((i + 1 for i, (k, _) in enumerate(rows) if _e(k) == after), len(rows))
139+
page = rows[start : start + self.page_rows]
140+
more = start + self.page_rows < len(rows)
141+
return {
142+
"rows": [{"key": _e(k), "value": _e(v)} for k, v in page],
143+
"next_after": _e(page[-1][0]) if more and page else None,
144+
}
145+
146+
def _op_state_scan(self, shard: str, body: dict[str, Any]) -> dict[str, Any]:
147+
rows = self._ns_rows(shard, _d(body["scope_id"]), _d(body["ns"]))
148+
return self._page(rows, body.get("after_key"))
149+
150+
def _op_state_drain(self, shard: str, body: dict[str, Any]) -> dict[str, Any]:
151+
scope, ns = _d(body["scope_id"]), _d(body["ns"])
152+
attempt = body["attempt_id"]
153+
if body.get("after_key") is None and attempt not in self._drains:
154+
self._drains[attempt] = self._ns_rows(shard, scope, ns)
155+
for k in [k for k in self.state if k[:3] == (shard, scope, ns)]:
156+
del self.state[k]
157+
return self._page(self._drains[attempt], body.get("after_key"))
158+
159+
def _op_state_delete(self, shard: str, body: dict[str, Any]) -> dict[str, Any]:
160+
scope, ns = _d(body["scope_id"]), _d(body["ns"])
161+
keys = [k for k in self.state if k[:3] == (shard, scope, ns)]
162+
if "keys" in body:
163+
wanted = {_d(k) for k in body["keys"]}
164+
keys = [k for k in keys if k[3] in wanted]
165+
for k in keys:
166+
del self.state[k]
167+
return {"deleted": len(keys)}
168+
169+
def _op_execution_clear(self, shard: str, body: dict[str, Any]) -> dict[str, Any]:
170+
scope = _d(body["scope_id"])
171+
keys = [k for k in self.state if k[:2] == (shard, scope)]
172+
logs = [k for k in self.logs if k[:2] == (shard, scope)]
173+
for k in keys:
174+
del self.state[k]
175+
for k in logs:
176+
del self.logs[k]
177+
return {"deleted": len(keys) + len(logs)}
178+
179+
def _op_state_append(self, shard: str, body: dict[str, Any]) -> dict[str, Any]:
180+
key = (shard, _d(body["scope_id"]), _d(body["ns"]), _d(body["key"]))
181+
item = self._check(_d(body["item"]), "log item")
182+
self._next_ordinal += 1
183+
self.logs.setdefault(key, []).append((self._next_ordinal, item))
184+
return {"ordinal": self._next_ordinal}
185+
186+
def _op_state_log_scan(self, shard: str, body: dict[str, Any]) -> dict[str, Any]:
187+
key = (shard, _d(body["scope_id"]), _d(body["ns"]), _d(body["key"]))
188+
rows = [(i, v) for i, v in self.logs.get(key, []) if i > body["after_id"]]
189+
if body.get("limit") is not None:
190+
rows = rows[: body["limit"]]
191+
return {"rows": [{"id": i, "value": _e(v)} for i, v in rows]}
192+
193+
194+
class _TooLarge(Exception):
195+
pass

‎tests/test_function_storage_cf_do.py‎

Lines changed: 19 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,11 @@ def storage(mock_transport: _MockTransport) -> FunctionStorageCfDo:
8282
return s
8383

8484

85+
def _env(data: bytes) -> str:
86+
"""Base64 of an inline value envelope (``0x00 || value``), as the DO stores it."""
87+
return base64.b64encode(b"\x00" + data).decode()
88+
89+
8590
def _b64(data: bytes) -> str:
8691
return base64.b64encode(data).decode()
8792

@@ -106,13 +111,13 @@ def test_queue_push_and_pop(self, storage: FunctionStorageCfDo, mock_transport:
106111

107112
body = _body(mock_transport.requests[0])
108113
assert len(body["items"]) == 3
109-
assert base64.b64decode(body["items"][0]) == b"item1"
114+
assert base64.b64decode(body["items"][0]) == b"\x00item1"
110115

111116
def test_queue_pop_returns_item(self, storage: FunctionStorageCfDo, mock_transport: _MockTransport) -> None:
112117
"""Test that queue_pop returns a decoded item."""
113118
execution_id = b"\x02" * 16
114119

115-
mock_transport.queue_response(200, {"item": _b64(b"item1")})
120+
mock_transport.queue_response(200, {"item": _env(b"item1")})
116121
result = storage.queue_pop(execution_id)
117122
assert result == b"item1"
118123

@@ -215,9 +220,9 @@ def test_state_get_many_emits_keys(
215220
200,
216221
{
217222
"rows": [
218-
{"value": _b64(b"v1")},
223+
{"value": _env(b"v1")},
219224
None,
220-
{"value": _b64(b"v3")},
225+
{"value": _env(b"v3")},
221226
]
222227
},
223228
)
@@ -251,8 +256,8 @@ def test_state_put_many_carries_attempt_id(
251256
assert body["scope_id"] == _b64(b"exec1")
252257
assert body["ns"] == _b64(b"agg")
253258
assert body["items"] == [
254-
{"key": _b64(b"k1"), "value": _b64(b"v1")},
255-
{"key": _b64(b"k2"), "value": _b64(b"v2")},
259+
{"key": _b64(b"k1"), "value": _env(b"v1")},
260+
{"key": _b64(b"k2"), "value": _env(b"v2")},
256261
]
257262
assert "attempt_id" in body
258263
assert len(body["attempt_id"]) == 32 # uuid.uuid4().hex
@@ -267,7 +272,7 @@ def test_state_scan_no_attempt_id(
267272
200,
268273
{
269274
"rows": [
270-
{"key": _b64(b"k"), "value": _b64(b"v")},
275+
{"key": _b64(b"k"), "value": _env(b"v")},
271276
]
272277
},
273278
)
@@ -286,8 +291,8 @@ def test_state_drain_carries_attempt_id_for_read_back_replay(
286291
200,
287292
{
288293
"rows": [
289-
{"key": _b64(b"k1"), "value": _b64(b"v1")},
290-
{"key": _b64(b"k2"), "value": _b64(b"v2")},
294+
{"key": _b64(b"k1"), "value": _env(b"v1")},
295+
{"key": _b64(b"k2"), "value": _env(b"v2")},
291296
]
292297
},
293298
)
@@ -345,7 +350,7 @@ def test_state_append_carries_attempt_id_returns_ordinal(
345350
assert body["scope_id"] == _b64(b"exec1")
346351
assert body["ns"] == _b64(b"buf")
347352
assert body["key"] == _b64(b"k1")
348-
assert body["item"] == _b64(b"payload")
353+
assert body["item"] == _env(b"payload")
349354
assert "attempt_id" in body
350355

351356
def test_state_log_scan_no_attempt_id_returns_rows(
@@ -358,9 +363,9 @@ def test_state_log_scan_no_attempt_id_returns_rows(
358363
200,
359364
{
360365
"rows": [
361-
{"id": 1, "value": _b64(b"a")},
362-
{"id": 2, "value": _b64(b"b")},
363-
{"id": 3, "value": _b64(b"c")},
366+
{"id": 1, "value": _env(b"a")},
367+
{"id": 2, "value": _env(b"b")},
368+
{"id": 3, "value": _env(b"c")},
364369
]
365370
},
366371
)
@@ -381,7 +386,7 @@ def test_state_log_scan_with_after_id_and_limit(
381386
mock_transport: _MockTransport,
382387
) -> None:
383388
"""after_id + limit are forwarded in the request body for cursor-based paging."""
384-
mock_transport.queue_response(200, {"rows": [{"id": 5, "value": _b64(b"e")}]})
389+
mock_transport.queue_response(200, {"rows": [{"id": 5, "value": _env(b"e")}]})
385390
result = storage.state_log_scan(b"exec1", b"buf", b"k1", after_id=4, limit=1)
386391
assert result == [(5, b"e")]
387392
body = _body(mock_transport.requests[0])

0 commit comments

Comments
 (0)