Skip to content

Commit fdf98ba

Browse files
rustyconoverclaude
andcommitted
buffered_table: cursor-into-storage stream finalize; data lives in storage
Replaces the unary buffered_table_finalize RPC with a cursor-driven stream over the existing init machinery. Deletes the in-process _buffered_table_finalize_iters dict, _ChainIter, and the entire unary RPC handler. Also fixes the matching anti-pattern in streaming-shape TableInOutFinalizeState (which held _batches: Transient that silently truncated on HTTP). Both finalize shapes now converge on one ProducerState ``BufferedFinalizeState`` whose entire wire payload is: ``(execution_id, ns, key, cursor, attach_opaque_data)``. ``produce()`` cold-builds BoundedStorage per tick, scans the next page of the (ns, key) state_log past cursor, emits batches, advances the cursor. No per-tick user code; no batches in stream state ever. User contract changes: * Buffered fixtures (``Meta.buffered_table=True``) now declare which state_log to drain via a new ``finalize_log_key()`` classmethod. Default returns ``(b"buf", pack_int_key(state_id))`` — exactly where ``process()`` already writes via ``state_append``. * The ``finalize()`` override (yield-based) is GONE for buffered fixtures. Functions that needed sort or merge (BatchIndexBuffer, SumAllColumns, LargeState) now do that work in ``combine()`` and write the consolidated output as a NEW state_log under ``b"buf_sorted"``; ``finalize_log_key()`` points the framework at it. * CrashOnFinalizeFunction reframes: combine() drops a malformed payload into the log; the framework's source-phase _decode_ipc_batch raises (replaces the prior "user finalize raises" path). Streaming-shape TableInOut finalize (non-buffered): * ``finalize(params) -> list[batch]`` user API unchanged. * Worker init handler materializes the returned list into BoundedStorage via ``state_append(b"streaming_finalize", ...)`` at init time, then hands ``BufferedFinalizeState`` to vgi-rpc for the source-phase drain. * Removes the ``_batches: Transient list`` field that was breaking streaming finalize on HTTP transport. Storage primitive: * ``state_log_scan`` extends with ``after_id`` (default -1) and ``limit`` (default None) kwargs; return type widens from ``list[bytes]`` to ``list[tuple[int, bytes]]`` so callers can use the id as the next cursor. Existing callers updated; new tests cover paged drain with after_id+limit on all three backends. Wire/protocol: * New ``InitRequest.finalize_state_id: int | None`` field; required when ``phase=BUFFERED_TABLE_FINALIZE``. * New ``TableInOutFunctionInitPhase.BUFFERED_TABLE_FINALIZE`` enum value. * ``BufferedTableFinalizeRequest``/``BufferedTableFinalizeResponse`` + ``VgiProtocol.buffered_table_finalize`` method DELETED. * MetaWorker dispatcher entry deleted. Cursor helpers (``vgi.table_in_out_function``): * ``pack_int_cursor(int) -> bytes`` / ``unpack_int_cursor(bytes) -> int`` — canonical encoding for log-id cursors. Worker module-level helpers (vgi/worker.py): * ``_build_bound_storage_from_fields(execution_id, attach, ctx)`` — cold-build per tick, no func_cls dependency. * ``_decode_ipc_batch(value)`` — wraps ``pa.ipc.open_stream``. * ``_FINALIZE_PREFETCH = 8`` and ``_STREAMING_FINALIZE_KEY``. Tests: * All 27 buffered_table integration tests pass on the new path. * All Python storage tests pass (existing + new for after_id/limit). * mypy clean. ruff clean. * vgi-python suite: 30 failed / 1657 passed (baseline-equivalent; +5 net passes from new state_log_scan tests). C++ side wires up in the next commit (PerformInit kwarg + Source phase rewire + delete unary RPC). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
1 parent bf26357 commit fdf98ba

13 files changed

Lines changed: 539 additions & 326 deletions

‎tests/test_function_storage.py‎

Lines changed: 54 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -244,13 +244,18 @@ def test_facade_pack_int_key(self) -> None:
244244

245245
# --- state_append / state_log_scan (append-only log) ---
246246

247+
@staticmethod
248+
def _values(rows: list[tuple[int, bytes]]) -> list[bytes]:
249+
"""Strip ids from state_log_scan rows for value-only assertions."""
250+
return [v for _, v in rows]
251+
247252
def test_state_append_then_log_scan_single_key(self, storage: FunctionStorageSqlite) -> None:
248253
"""Appended values come back in append order via state_log_scan."""
249254
scope = b"exec-log"
250255
storage.state_append(scope, b"buf", b"k", b"a")
251256
storage.state_append(scope, b"buf", b"k", b"b")
252257
storage.state_append(scope, b"buf", b"k", b"c")
253-
assert storage.state_log_scan(scope, b"buf", b"k") == [b"a", b"b", b"c"]
258+
assert self._values(storage.state_log_scan(scope, b"buf", b"k")) == [b"a", b"b", b"c"]
254259

255260
def test_state_append_returns_monotone_ordinals_per_key(self, storage: FunctionStorageSqlite) -> None:
256261
"""Per-key ordinals strictly increase across appends."""
@@ -260,6 +265,41 @@ def test_state_append_returns_monotone_ordinals_per_key(self, storage: FunctionS
260265
ord3 = storage.state_append(scope, b"buf", b"k", b"c")
261266
assert ord1 < ord2 < ord3
262267

268+
def test_state_log_scan_returns_ids_matching_state_append(self, storage: FunctionStorageSqlite) -> None:
269+
"""The (id, value) pairs from state_log_scan match the ordinals state_append returned."""
270+
scope = b"exec-log"
271+
ord_a = storage.state_append(scope, b"buf", b"k", b"a")
272+
ord_b = storage.state_append(scope, b"buf", b"k", b"b")
273+
rows = storage.state_log_scan(scope, b"buf", b"k")
274+
assert rows == [(ord_a, b"a"), (ord_b, b"b")]
275+
276+
def test_state_log_scan_after_id_skips_consumed_rows(self, storage: FunctionStorageSqlite) -> None:
277+
"""after_id=N returns only rows with id > N — cursor-based scrolling."""
278+
scope = b"exec-log"
279+
ord_a = storage.state_append(scope, b"buf", b"k", b"a")
280+
ord_b = storage.state_append(scope, b"buf", b"k", b"b")
281+
ord_c = storage.state_append(scope, b"buf", b"k", b"c")
282+
# First page (everything).
283+
first = storage.state_log_scan(scope, b"buf", b"k")
284+
assert first == [(ord_a, b"a"), (ord_b, b"b"), (ord_c, b"c")]
285+
# Resume past the first row.
286+
rest = storage.state_log_scan(scope, b"buf", b"k", after_id=ord_a)
287+
assert rest == [(ord_b, b"b"), (ord_c, b"c")]
288+
# Resume past everything we've seen — empty.
289+
assert storage.state_log_scan(scope, b"buf", b"k", after_id=ord_c) == []
290+
291+
def test_state_log_scan_limit_caps_rows(self, storage: FunctionStorageSqlite) -> None:
292+
"""limit=N returns at most N rows (in id order)."""
293+
scope = b"exec-log"
294+
for letter in (b"a", b"b", b"c", b"d"):
295+
storage.state_append(scope, b"buf", b"k", letter)
296+
page1 = storage.state_log_scan(scope, b"buf", b"k", limit=2)
297+
assert self._values(page1) == [b"a", b"b"]
298+
page2 = storage.state_log_scan(scope, b"buf", b"k", after_id=page1[-1][0], limit=2)
299+
assert self._values(page2) == [b"c", b"d"]
300+
page3 = storage.state_log_scan(scope, b"buf", b"k", after_id=page2[-1][0], limit=2)
301+
assert page3 == []
302+
263303
def test_state_append_caller_retry_produces_duplicates(self, storage: FunctionStorageSqlite) -> None:
264304
"""Caller-level retry inserts a duplicate row (fresh internal attempt_id).
265305
@@ -273,31 +313,31 @@ def test_state_append_caller_retry_produces_duplicates(self, storage: FunctionSt
273313
scope = b"exec-log"
274314
storage.state_append(scope, b"buf", b"k", b"payload")
275315
storage.state_append(scope, b"buf", b"k", b"payload") # caller retry
276-
assert storage.state_log_scan(scope, b"buf", b"k") == [b"payload", b"payload"]
316+
assert self._values(storage.state_log_scan(scope, b"buf", b"k")) == [b"payload", b"payload"]
277317

278318
def test_state_log_scan_isolates_keys(self, storage: FunctionStorageSqlite) -> None:
279319
"""Logs for distinct keys in the same namespace stay separate."""
280320
scope = b"exec-log"
281321
storage.state_append(scope, b"buf", b"k1", b"a")
282322
storage.state_append(scope, b"buf", b"k2", b"x")
283323
storage.state_append(scope, b"buf", b"k1", b"b")
284-
assert storage.state_log_scan(scope, b"buf", b"k1") == [b"a", b"b"]
285-
assert storage.state_log_scan(scope, b"buf", b"k2") == [b"x"]
324+
assert self._values(storage.state_log_scan(scope, b"buf", b"k1")) == [b"a", b"b"]
325+
assert self._values(storage.state_log_scan(scope, b"buf", b"k2")) == [b"x"]
286326

287327
def test_state_log_scan_isolates_namespaces(self, storage: FunctionStorageSqlite) -> None:
288328
"""Logs for the same key in different namespaces stay separate."""
289329
scope = b"exec-log"
290330
storage.state_append(scope, b"ns-a", b"k", b"a1")
291331
storage.state_append(scope, b"ns-b", b"k", b"b1")
292-
assert storage.state_log_scan(scope, b"ns-a", b"k") == [b"a1"]
293-
assert storage.state_log_scan(scope, b"ns-b", b"k") == [b"b1"]
332+
assert self._values(storage.state_log_scan(scope, b"ns-a", b"k")) == [b"a1"]
333+
assert self._values(storage.state_log_scan(scope, b"ns-b", b"k")) == [b"b1"]
294334

295335
def test_state_log_scan_isolates_scopes(self, storage: FunctionStorageSqlite) -> None:
296336
"""Logs for the same key in different scopes stay separate."""
297337
storage.state_append(b"exec-A", b"buf", b"k", b"a")
298338
storage.state_append(b"exec-B", b"buf", b"k", b"b")
299-
assert storage.state_log_scan(b"exec-A", b"buf", b"k") == [b"a"]
300-
assert storage.state_log_scan(b"exec-B", b"buf", b"k") == [b"b"]
339+
assert self._values(storage.state_log_scan(b"exec-A", b"buf", b"k")) == [b"a"]
340+
assert self._values(storage.state_log_scan(b"exec-B", b"buf", b"k")) == [b"b"]
301341

302342
def test_state_log_scan_is_non_destructive(self, storage: FunctionStorageSqlite) -> None:
303343
"""Repeated scans return the same data."""
@@ -306,7 +346,8 @@ def test_state_log_scan_is_non_destructive(self, storage: FunctionStorageSqlite)
306346
storage.state_append(scope, b"buf", b"k", b"b")
307347
first = storage.state_log_scan(scope, b"buf", b"k")
308348
second = storage.state_log_scan(scope, b"buf", b"k")
309-
assert first == second == [b"a", b"b"]
349+
assert first == second
350+
assert self._values(first) == [b"a", b"b"]
310351

311352
def test_state_log_scan_empty_returns_empty(self, storage: FunctionStorageSqlite) -> None:
312353
"""Scan of a (scope, ns, key) that was never appended returns []."""
@@ -328,4 +369,7 @@ def test_facade_state_append_log_scan_roundtrip(self, storage: FunctionStorageSq
328369
ord1 = bs.state_append(b"buf", b"k", b"a")
329370
ord2 = bs.state_append(b"buf", b"k", b"b")
330371
assert ord1 < ord2
331-
assert bs.state_log_scan(b"buf", b"k") == [b"a", b"b"]
372+
rows = bs.state_log_scan(b"buf", b"k")
373+
assert rows == [(ord1, b"a"), (ord2, b"b")]
374+
# Cursor-based: after_id + limit also work through the facade.
375+
assert bs.state_log_scan(b"buf", b"k", after_id=ord1, limit=1) == [(ord2, b"b")]

‎tests/test_function_storage_azure_sql.py‎

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -418,12 +418,25 @@ def test_state_append_replay_returns_prior_ordinal(
418418
def test_state_log_scan_emits_select_in_id_order(
419419
self, storage: FunctionStorageAzureSql, mock_cursor: _MockCursor,
420420
) -> None:
421-
"""state_log_scan SELECTs values for (scope, ns, key) ORDER BY id."""
422-
mock_cursor.set_results([(b"a",), (b"b",), (b"c",)])
421+
"""state_log_scan SELECTs (id, value) for (scope, ns, key) ORDER BY id."""
422+
mock_cursor.set_results([(1, b"a"), (2, b"b"), (3, b"c")])
423423
result = storage.state_log_scan(b"exec1", b"buf", b"k")
424-
assert result == [b"a", b"b", b"c"]
424+
assert result == [(1, b"a"), (2, b"b"), (3, b"c")]
425425
sql, params = mock_cursor.executed[0]
426-
assert "SELECT value FROM function_state_log" in sql
426+
assert "SELECT id, value FROM function_state_log" in sql
427427
assert "ORDER BY id" in sql
428-
assert params == (b"exec1", b"buf", b"k")
428+
# Default after_id=-1 (before-first); no FETCH clause when limit is None.
429+
assert params == (b"exec1", b"buf", b"k", -1)
430+
assert "FETCH NEXT" not in sql
431+
432+
def test_state_log_scan_with_limit_emits_offset_fetch(
433+
self, storage: FunctionStorageAzureSql, mock_cursor: _MockCursor,
434+
) -> None:
435+
"""limit=N appends OFFSET/FETCH NEXT clause and threads N into params."""
436+
mock_cursor.set_results([(2, b"b")])
437+
result = storage.state_log_scan(b"exec1", b"buf", b"k", after_id=1, limit=1)
438+
assert result == [(2, b"b")]
439+
sql, params = mock_cursor.executed[0]
440+
assert "OFFSET 0 ROWS FETCH NEXT" in sql
441+
assert params == (b"exec1", b"buf", b"k", 1, 1)
429442

‎tests/test_function_storage_cf_do.py‎

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -312,15 +312,33 @@ def test_state_append_carries_attempt_id_returns_ordinal(
312312
assert body["item"] == _b64(b"payload")
313313
assert "attempt_id" in body
314314

315-
def test_state_log_scan_no_attempt_id_returns_values(
315+
def test_state_log_scan_no_attempt_id_returns_rows(
316316
self, storage: FunctionStorageCfDo, mock_transport: _MockTransport,
317317
) -> None:
318-
"""state_log_scan is read-only — no attempt_id; values returned in order."""
319-
mock_transport.queue_response(200, {"values": [_b64(b"a"), _b64(b"b"), _b64(b"c")]})
318+
"""state_log_scan is read-only — no attempt_id; (id, value) returned in order."""
319+
mock_transport.queue_response(200, {"rows": [
320+
{"id": 1, "value": _b64(b"a")},
321+
{"id": 2, "value": _b64(b"b")},
322+
{"id": 3, "value": _b64(b"c")},
323+
]})
320324
result = storage.state_log_scan(b"exec1", b"buf", b"k1")
321-
assert result == [b"a", b"b", b"c"]
325+
assert result == [(1, b"a"), (2, b"b"), (3, b"c")]
322326
body = _body(mock_transport.requests[0])
323327
assert body["scope_id"] == _b64(b"exec1")
324328
assert body["ns"] == _b64(b"buf")
325329
assert body["key"] == _b64(b"k1")
330+
# Default after_id=-1 (before-first); limit omitted means unbounded.
331+
assert body["after_id"] == -1
332+
assert "limit" not in body
326333
assert "attempt_id" not in body
334+
335+
def test_state_log_scan_with_after_id_and_limit(
336+
self, storage: FunctionStorageCfDo, mock_transport: _MockTransport,
337+
) -> None:
338+
"""after_id + limit are forwarded in the request body for cursor-based paging."""
339+
mock_transport.queue_response(200, {"rows": [{"id": 5, "value": _b64(b"e")}]})
340+
result = storage.state_log_scan(b"exec1", b"buf", b"k1", after_id=4, limit=1)
341+
assert result == [(5, b"e")]
342+
body = _body(mock_transport.requests[0])
343+
assert body["after_id"] == 4
344+
assert body["limit"] == 1

‎tests/test_protocol_classes.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,10 @@
1616
from tests.conftest import make_schema
1717
from vgi.arguments import Arg, Arguments, ArgumentValidationError
1818
from vgi.protocol import (
19+
BufferedFinalizeState,
1920
ProcessState,
2021
ScalarExchangeState,
2122
TableInOutExchangeState,
22-
TableInOutFinalizeState,
2323
TableProducerState,
2424
VgiProtocol,
2525
)
@@ -296,7 +296,7 @@ def test_init_declares_process_state_union(self) -> None:
296296
ScalarExchangeState,
297297
TableProducerState,
298298
TableInOutExchangeState,
299-
TableInOutFinalizeState,
299+
BufferedFinalizeState,
300300
}
301301
assert get_args(return_hint)[1].__name__ == "GlobalInitResponse"
302302
assert get_origin(return_hint) is Stream

0 commit comments

Comments
 (0)