Skip to content

Commit c790416

Browse files
rustyconoverclaude
andcommitted
function_storage_cf_do: implement transaction_state_* + worker_scan
The Cloudflare DO backend stubbed out transaction_state_get/put/clear with NotImplementedError, which crashed kafka_consume's _topic_snapshot the moment a SQL transaction tried to pin watermarks. worker_scan was also missing from the Worker switch — silently turned into a 500 that the EXPLAIN aggregator swallowed without surfacing the gap. * Add a transaction_state SQLite table to the DO and route transaction_state_get/put/clear through it (parallel-result get to match FunctionStorageSqlite, single-row put with INSERT OR REPLACE, delete-by-transaction_id clear). TTL sweep extended to drop stale transaction rows alongside worker_state and work_queue. * Add a worker_scan route mirroring the existing worker_collect path but non-destructive — required for table-function dynamic_to_string hooks to read all per-pid payloads without poisoning workers that haven't run yet. * Replace the three transaction_state_* NotImplementedError stubs in FunctionStorageCfDo with real _post calls; add 8 unit tests covering put/get round-trips, miss → None semantics, empty-input short circuits, clear, and worker_scan tuple shape. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
1 parent 54627ed commit c790416

3 files changed

Lines changed: 232 additions & 9 deletions

File tree

‎cloudflare/vgi-storage/src/index.ts‎

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,13 @@ export class VgiStorageDO implements DurableObject {
7979
execution_id BLOB PRIMARY KEY,
8080
created_at REAL DEFAULT (julianday('now'))
8181
);
82+
CREATE TABLE IF NOT EXISTS transaction_state (
83+
transaction_id BLOB NOT NULL,
84+
key BLOB NOT NULL,
85+
value BLOB NOT NULL,
86+
created_at REAL DEFAULT (julianday('now')),
87+
PRIMARY KEY (transaction_id, key)
88+
);
8289
`);
8390
this.initialized = true;
8491
}
@@ -102,6 +109,10 @@ export class VgiStorageDO implements DurableObject {
102109
`DELETE FROM invocation_registry WHERE julianday('now') - created_at > ?`,
103110
threshold,
104111
);
112+
this.sql.exec(
113+
`DELETE FROM transaction_state WHERE julianday('now') - created_at > ?`,
114+
threshold,
115+
);
105116
// Re-arm the alarm
106117
this.scheduleCleanup();
107118
}
@@ -125,12 +136,20 @@ export class VgiStorageDO implements DurableObject {
125136
return this.workerPut(body);
126137
case "worker_collect":
127138
return this.workerCollect(body);
139+
case "worker_scan":
140+
return this.workerScan(body);
128141
case "queue_push":
129142
return this.queuePush(body);
130143
case "queue_pop":
131144
return this.queuePop(body);
132145
case "queue_clear":
133146
return this.queueClear(body);
147+
case "transaction_state_get":
148+
return this.transactionStateGet(body);
149+
case "transaction_state_put":
150+
return this.transactionStatePut(body);
151+
case "transaction_state_clear":
152+
return this.transactionStateClear(body);
134153
default:
135154
return Response.json({ error: "not_found" }, { status: 404 });
136155
}
@@ -256,4 +275,75 @@ export class VgiStorageDO implements DurableObject {
256275

257276
return Response.json({ cleared: deleted.length });
258277
}
278+
279+
// --- Worker State (non-destructive) ---
280+
281+
private workerScan(body: Record<string, unknown>): Response {
282+
const eid = this.b64ToBytes(body.execution_id as string);
283+
const rows = this.sql
284+
.exec(
285+
`SELECT process_id, state_data FROM worker_state WHERE execution_id = ?`,
286+
eid,
287+
)
288+
.toArray();
289+
const out = rows.map((row) => ({
290+
worker_id: row.process_id as number,
291+
state: this.bytesToB64(row.state_data as ArrayBuffer),
292+
}));
293+
return Response.json({ rows: out });
294+
}
295+
296+
// --- Transaction State ---
297+
298+
private transactionStateGet(body: Record<string, unknown>): Response {
299+
const txnId = this.b64ToBytes(body.transaction_id as string);
300+
const keysB64 = body.keys as string[];
301+
// Lookup is per-key so the response can return null for misses in
302+
// the same order the client sent — mirrors FunctionStorageSqlite's
303+
// contract where the result list is parallel to ``keys``.
304+
const values: (string | null)[] = [];
305+
for (const keyB64 of keysB64) {
306+
const key = this.b64ToBytes(keyB64);
307+
const rows = this.sql
308+
.exec(
309+
`SELECT value FROM transaction_state WHERE transaction_id = ? AND key = ?`,
310+
txnId,
311+
key,
312+
)
313+
.toArray();
314+
values.push(
315+
rows.length === 0
316+
? null
317+
: this.bytesToB64(rows[0].value as ArrayBuffer),
318+
);
319+
}
320+
return Response.json({ values });
321+
}
322+
323+
private transactionStatePut(body: Record<string, unknown>): Response {
324+
const txnId = this.b64ToBytes(body.transaction_id as string);
325+
const items = body.items as Array<{ key: string; value: string }>;
326+
for (const item of items) {
327+
this.sql.exec(
328+
`INSERT OR REPLACE INTO transaction_state
329+
(transaction_id, key, value, created_at)
330+
VALUES (?, ?, ?, julianday('now'))`,
331+
txnId,
332+
this.b64ToBytes(item.key),
333+
this.b64ToBytes(item.value),
334+
);
335+
}
336+
return Response.json({});
337+
}
338+
339+
private transactionStateClear(body: Record<string, unknown>): Response {
340+
const txnId = this.b64ToBytes(body.transaction_id as string);
341+
const deleted = this.sql
342+
.exec(
343+
`DELETE FROM transaction_state WHERE transaction_id = ? RETURNING key`,
344+
txnId,
345+
)
346+
.toArray();
347+
return Response.json({ cleared: deleted.length });
348+
}
259349
}

‎tests/test_function_storage_cf_do.py‎

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,92 @@ def test_queue_clear_empty_queue(self, storage: FunctionStorageCfDo, mock_conn:
189189
cleared = storage.queue_clear(b"\x02" * 16)
190190
assert cleared == 0
191191

192+
# --- Transaction State Tests ---
193+
194+
def test_transaction_state_put_and_get(
195+
self, storage: FunctionStorageCfDo, mock_conn: _MockConnection
196+
) -> None:
197+
"""Round-trip: put two keys, get them back."""
198+
txn_id = b"\xaa" * 16
199+
200+
mock_conn.queue_response(200, {})
201+
storage.transaction_state_put(txn_id, [(b"k1", b"v1"), (b"k2", b"v2")])
202+
203+
# Wire format: items is a list of {key, value} objects, both base64.
204+
body = json.loads(mock_conn.requests[0][2])
205+
assert base64.b64decode(body["transaction_id"]) == txn_id
206+
items = body["items"]
207+
assert len(items) == 2
208+
assert {(base64.b64decode(it["key"]), base64.b64decode(it["value"])) for it in items} == {
209+
(b"k1", b"v1"),
210+
(b"k2", b"v2"),
211+
}
212+
213+
mock_conn.queue_response(
214+
200,
215+
{"values": [_b64(b"v1"), _b64(b"v2")]},
216+
)
217+
result = storage.transaction_state_get(txn_id, [b"k1", b"k2"])
218+
assert result == [b"v1", b"v2"]
219+
220+
def test_transaction_state_get_misses_return_none(
221+
self, storage: FunctionStorageCfDo, mock_conn: _MockConnection
222+
) -> None:
223+
"""Misses surface as None in the parallel result list."""
224+
mock_conn.queue_response(200, {"values": [_b64(b"hit"), None, _b64(b"hit2")]})
225+
result = storage.transaction_state_get(b"\xaa" * 16, [b"a", b"missing", b"c"])
226+
assert result == [b"hit", None, b"hit2"]
227+
228+
def test_transaction_state_get_empty_keys_short_circuits(
229+
self, storage: FunctionStorageCfDo, mock_conn: _MockConnection
230+
) -> None:
231+
"""No request should be issued for an empty key list."""
232+
result = storage.transaction_state_get(b"\xaa" * 16, [])
233+
assert result == []
234+
assert len(mock_conn.requests) == 0
235+
236+
def test_transaction_state_put_empty_short_circuits(
237+
self, storage: FunctionStorageCfDo, mock_conn: _MockConnection
238+
) -> None:
239+
"""No request should be issued for an empty item list."""
240+
storage.transaction_state_put(b"\xaa" * 16, [])
241+
assert len(mock_conn.requests) == 0
242+
243+
def test_transaction_state_clear(
244+
self, storage: FunctionStorageCfDo, mock_conn: _MockConnection
245+
) -> None:
246+
"""Clear sends transaction_id and ignores response body."""
247+
mock_conn.queue_response(200, {"cleared": 5})
248+
storage.transaction_state_clear(b"\xbb" * 16)
249+
assert len(mock_conn.requests) == 1
250+
body = json.loads(mock_conn.requests[0][2])
251+
assert base64.b64decode(body["transaction_id"]) == b"\xbb" * 16
252+
253+
# --- Worker Scan Tests ---
254+
255+
def test_worker_scan_returns_pairs(
256+
self, storage: FunctionStorageCfDo, mock_conn: _MockConnection
257+
) -> None:
258+
"""Non-destructive scan returns (worker_id, state) tuples."""
259+
mock_conn.queue_response(
260+
200,
261+
{
262+
"rows": [
263+
{"worker_id": 11, "state": _b64(b"alpha")},
264+
{"worker_id": 22, "state": _b64(b"beta")},
265+
],
266+
},
267+
)
268+
rows = storage.worker_scan(b"\x01" * 16)
269+
assert rows == [(11, b"alpha"), (22, b"beta")]
270+
271+
def test_worker_scan_empty(
272+
self, storage: FunctionStorageCfDo, mock_conn: _MockConnection
273+
) -> None:
274+
"""Empty scan returns an empty list, not None."""
275+
mock_conn.queue_response(200, {"rows": []})
276+
assert storage.worker_scan(b"\x01" * 16) == []
277+
192278
# --- Auth Tests ---
193279

194280
def test_auth_header_sent(self, storage: FunctionStorageCfDo, mock_conn: _MockConnection) -> None:

‎vgi/function_storage_cf_do.py‎

Lines changed: 56 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -280,21 +280,68 @@ def aggregate_state_clear(self, execution_id: bytes) -> None:
280280
# --- Transaction State ---
281281

282282
def transaction_state_get(self, transaction_id: bytes, keys: list[bytes]) -> list[bytes | None]:
283-
"""Not yet supported on Cloudflare DO."""
284-
raise NotImplementedError(
285-
"Transaction state is not yet supported with the Cloudflare Durable Object storage backend."
283+
"""Load transaction-scoped values for the given keys."""
284+
if not keys:
285+
return []
286+
t0 = time.monotonic()
287+
data = self._post(
288+
"transaction_state_get",
289+
{
290+
"transaction_id": base64.b64encode(transaction_id).decode(),
291+
"keys": [base64.b64encode(k).decode() for k in keys],
292+
},
293+
)
294+
# ``values`` is parallel to ``keys`` — null for misses, b64 for hits.
295+
result: list[bytes | None] = [
296+
base64.b64decode(v) if v is not None else None for v in data["values"]
297+
]
298+
_logger.debug(
299+
"transaction_state_get txn=%s keys=%d hits=%d elapsed_ms=%.1f",
300+
transaction_id.hex()[:8],
301+
len(keys),
302+
sum(1 for v in result if v is not None),
303+
(time.monotonic() - t0) * 1000,
286304
)
305+
return result
287306

288307
def transaction_state_put(self, transaction_id: bytes, items: list[tuple[bytes, bytes]]) -> None:
289-
"""Not yet supported on Cloudflare DO."""
290-
raise NotImplementedError(
291-
"Transaction state is not yet supported with the Cloudflare Durable Object storage backend."
308+
"""Write transaction-scoped values."""
309+
if not items:
310+
return
311+
t0 = time.monotonic()
312+
self._post(
313+
"transaction_state_put",
314+
{
315+
"transaction_id": base64.b64encode(transaction_id).decode(),
316+
"items": [
317+
{
318+
"key": base64.b64encode(k).decode(),
319+
"value": base64.b64encode(v).decode(),
320+
}
321+
for k, v in items
322+
],
323+
},
324+
)
325+
_logger.debug(
326+
"transaction_state_put txn=%s items=%d elapsed_ms=%.1f",
327+
transaction_id.hex()[:8],
328+
len(items),
329+
(time.monotonic() - t0) * 1000,
292330
)
293331

294332
def transaction_state_clear(self, transaction_id: bytes) -> None:
295-
"""Not yet supported on Cloudflare DO."""
296-
raise NotImplementedError(
297-
"Transaction state is not yet supported with the Cloudflare Durable Object storage backend."
333+
"""Drop all state for a transaction."""
334+
t0 = time.monotonic()
335+
self._post(
336+
"transaction_state_clear",
337+
{
338+
"transaction_id": base64.b64encode(transaction_id).decode(),
339+
},
340+
)
341+
_logger.debug(
342+
"transaction_state_clear txn=%s elapsed_ms=%.1f",
343+
transaction_id.hex()[:8],
344+
(time.monotonic() - t0) * 1000,
298345
)
299346

300347
def aggregate_window_partition_put(self, execution_id: bytes, partition_id: int, data: bytes) -> None:

0 commit comments

Comments
 (0)