Skip to content

Commit 3d56cf3

Browse files
rustyconoverclaude
andcommitted
storage: migrate aggregate / window / per-pid / txn callers to state_* (Turn 3)
Every Python caller of the legacy storage API families now uses the unified state_* shape. The legacy method families themselves are NOT removed yet — that's Turn 5, after Azure SQL + CfDo client + DO server catch up in Turn 4. Migrations in this turn: worker.py — aggregate + window-aggregate + streaming-aggregate handlers: - aggregate_bind / _load_aggregate_const_args: state_get/put under namespace b"agg", synthetic group_id=-2 packed via pack_int_key. - aggregate_update: state_get_many/state_put_many for batched group state. - aggregate_combine: same shape as aggregate_update. - aggregate_finalize: state_get_many to load groups. - aggregate_destructor: ONE call to storage.execution_clear() now sweeps every namespace (b"agg", b"win", b"buf") for the execution. Replaces the previous aggregate_clear + aggregate_window_partition_clear pair. - aggregate_window_partition_*: state_put/state_get/state_delete under namespace b"win" with pack_int_key(partition_id). - Streaming-aggregate session storage (_STREAMING_SESSION_STORAGE_KEY) same b"win" namespace. TransactionBoundStorage facade: now backed by state_* with scope_id=transaction_opaque_data, ns=b"txn". Public API surface (get / get_one / put / put_one / clear) unchanged so user code in _test_fixtures/table/transaction_storage.py works without modification. vgi/_test_fixtures/worker.py: catalog_transaction_commit / _rollback now call execution_clear(transaction_opaque_data) instead of the legacy transaction_state_clear. vgi/_test_fixtures/table/profiling_example.py: ProfilingDemoFunction's storage.put / storage.collect (which used worker_state per-pid keying) now uses state_put / state_drain under namespace b"profile" with pack_int_key(os.getpid()) — explicit about the per-pid model. tests/test_table_function_dynamic_to_string.py: updated the test_bind_params_carries_execution_scoped_storage test to match the new fixture contract (state_scan(b"profile") instead of worker_scan). Verification: - 36 vgi-python unit tests pass (storage + dynamic_to_string) - 152 vgi C++ subprocess integration tests pass - 81 HTTP test cases pass (aggregate, window, buffered_table all green) - All buffered_table semantics preserved - All aggregate semantics preserved Note: HTTP tests against the CfDo backend will continue to use the legacy methods until Turn 4 lands the state_* methods on the cloud backends + DO server. The current cohabitation lets every backend serve every fixture during the migration window. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
1 parent 7da9e2d commit 3d56cf3

5 files changed

Lines changed: 106 additions & 54 deletions

File tree

‎tests/test_table_function_dynamic_to_string.py‎

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -144,8 +144,9 @@ def test_bind_params_carries_execution_scoped_storage(self) -> None:
144144
"""Dispatcher populates BindParams.storage keyed by global_execution_id.
145145
146146
Lets dynamic_to_string read whatever process() persisted via
147-
worker_put without manually reconstructing BoundStorage.
147+
the unified state_* API without manually reconstructing BoundStorage.
148148
"""
149+
from vgi.function_storage import BoundStorage
149150

150151
@init_single_worker
151152
@bind_fixed_schema
@@ -158,8 +159,11 @@ class Meta:
158159
@classmethod
159160
def dynamic_to_string(cls, params: BindParams[_Args], execution_id: bytes) -> Mapping[str, str]:
160161
assert params.storage is not None
161-
pairs = params.storage.worker_scan()
162-
return {f"pid_{wid}": state.decode() for wid, state in sorted(pairs)}
162+
pairs = params.storage.state_scan(b"profile")
163+
return {
164+
f"pid_{int.from_bytes(k, 'little', signed=True)}": v.decode()
165+
for k, v in sorted(pairs)
166+
}
163167

164168
@classmethod
165169
def process(cls, params, state, out) -> None: # type: ignore[no-untyped-def]
@@ -170,8 +174,11 @@ class _MyWorker(Worker):
170174

171175
worker = _MyWorker()
172176
execution_id = b"\x01\x02\x03\x04\x05\x06\x07\x08"
173-
_StorageFunc.storage.worker_put(execution_id, worker_id=10, state=b"hello")
174-
_StorageFunc.storage.worker_put(execution_id, worker_id=20, state=b"world")
177+
_StorageFunc.storage.state_put_many(
178+
execution_id, b"profile",
179+
[(BoundStorage.pack_int_key(10), b"hello"),
180+
(BoundStorage.pack_int_key(20), b"world")],
181+
)
175182

176183
result = worker.table_function_dynamic_to_string(_request("with_storage"), _ctx())
177184
assert dict(zip(result.keys, result.values, strict=True)) == {

‎vgi/_test_fixtures/table/profiling_example.py‎

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -124,9 +124,15 @@ def process(
124124
) -> None:
125125
if state.remaining <= 0:
126126
# Final write so dynamic_to_string sees the totals even after
127-
# the stream finishes.
127+
# the stream finishes. One row per OS pid via state_put under
128+
# namespace b"profile" — dynamic_to_string drains them all.
128129
elapsed_us = (time.monotonic_ns() - state.started_at_ns) // 1000
129-
params.storage.put(_pack_snapshot(state.rows_emitted, state.batches_emitted, elapsed_us))
130+
import os as _os
131+
params.storage.state_put(
132+
b"profile",
133+
BoundStorage.pack_int_key(_os.getpid()),
134+
_pack_snapshot(state.rows_emitted, state.batches_emitted, elapsed_us),
135+
)
130136
out.finish()
131137
return
132138
batch_size = params.args.batch_size
@@ -145,9 +151,14 @@ def process(
145151
state.batches_emitted += 1
146152

147153
# Per-tick snapshot — overwrites this worker's slot. The dispatcher's
148-
# collect() on dynamic_to_string sums one snapshot per worker pid.
154+
# state_drain on dynamic_to_string sums one snapshot per worker pid.
149155
elapsed_us = (time.monotonic_ns() - state.started_at_ns) // 1000
150-
params.storage.put(_pack_snapshot(state.rows_emitted, state.batches_emitted, elapsed_us))
156+
import os as _os
157+
params.storage.state_put(
158+
b"profile",
159+
BoundStorage.pack_int_key(_os.getpid()),
160+
_pack_snapshot(state.rows_emitted, state.batches_emitted, elapsed_us),
161+
)
151162

152163
@classmethod
153164
def dynamic_to_string(
@@ -159,7 +170,8 @@ def dynamic_to_string(
159170
# time). Construct one with the execution_id we received.
160171
storage = BoundStorage(cls.storage, execution_id, request=params.bind_call, auth=params.auth_context)
161172
try:
162-
snapshots = storage.collect()
173+
# state_drain returns (key, value) pairs; we only want the values.
174+
snapshots = [v for _, v in storage.state_drain(b"profile")]
163175
except Exception:
164176
return {}
165177
if not snapshots:

‎vgi/_test_fixtures/worker.py‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -983,14 +983,16 @@ def catalog_transaction_commit(
983983
) -> None:
984984
"""Clear per-transaction storage on commit (best-effort hygiene)."""
985985
del attach_opaque_data
986-
TxCachedValueFunction.storage.transaction_state_clear(bytes(transaction_opaque_data))
986+
# transaction_opaque_data plays the role of scope_id in the unified
987+
# state_* API; execution_clear wipes every namespace for that scope.
988+
TxCachedValueFunction.storage.execution_clear(bytes(transaction_opaque_data))
987989

988990
def catalog_transaction_rollback(
989991
self, *, attach_opaque_data: AttachOpaqueData, transaction_opaque_data: TransactionOpaqueData
990992
) -> None:
991993
"""Mirror of commit — same cleanup path."""
992994
del attach_opaque_data
993-
TxCachedValueFunction.storage.transaction_state_clear(bytes(transaction_opaque_data))
995+
TxCachedValueFunction.storage.execution_clear(bytes(transaction_opaque_data))
994996

995997

996998
class ExampleWorker(Worker):

‎vgi/function_storage.py‎

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -656,10 +656,20 @@ def __init__(
656656
shard_key = _derive_shard_key(attach_opaque_data=attach_opaque_data, auth=auth, _origin=origin)
657657
self._shard_key = shard_key
658658

659+
# Backed by the unified state_* API: scope_id = transaction_opaque_data,
660+
# ns = b"txn". Caller-supplied keys are user-chosen bytes (typically
661+
# short ASCII like b"watermark:topic-A"); the storage doesn't interpret
662+
# them. This class is preserved as a convenience wrapper so callers
663+
# don't have to thread the (transaction_opaque_data, b"txn") pair on
664+
# every call — the surface stays clean.
665+
666+
_NS = b"txn"
667+
659668
def get(self, keys: list[bytes]) -> list[bytes | None]:
660669
"""Load values for a list of keys; parallel return list."""
661-
return self._base.transaction_state_get(
670+
return self._base.state_get_many(
662671
self._transaction_opaque_data,
672+
self._NS,
663673
keys,
664674
shard_key=self._shard_key,
665675
)
@@ -670,8 +680,9 @@ def get_one(self, key: bytes) -> bytes | None:
670680

671681
def put(self, items: list[tuple[bytes, bytes]]) -> None:
672682
"""Write a batch of (key, value) pairs."""
673-
self._base.transaction_state_put(
683+
self._base.state_put_many(
674684
self._transaction_opaque_data,
685+
self._NS,
675686
items,
676687
shard_key=self._shard_key,
677688
)
@@ -681,8 +692,11 @@ def put_one(self, key: bytes, value: bytes) -> None:
681692
self.put([(key, value)])
682693

683694
def clear(self) -> None:
684-
"""Drop every value for this transaction."""
685-
self._base.transaction_state_clear(
695+
"""Drop every value for this transaction (every namespace)."""
696+
# execution_clear sweeps all namespaces — same effect as the old
697+
# transaction_state_clear since the only namespace under txn scope
698+
# is b"txn".
699+
self._base.execution_clear(
686700
self._transaction_opaque_data,
687701
shard_key=self._shard_key,
688702
)

‎vgi/worker.py‎

Lines changed: 55 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -2043,14 +2043,18 @@ def _load_aggregate_const_args(
20432043
if cached is not None:
20442044
return cast(Arguments, cached)
20452045

2046-
result = storage.aggregate_get([-2])
2047-
if result[0] is None:
2046+
# Const args live at the synthetic group_id -2 in namespace b"agg" —
2047+
# same row-keyspace as the rest of aggregate_state, no separate table
2048+
# needed. The negative key avoids collision with caller-supplied
2049+
# group_ids (which are non-negative).
2050+
result = storage.state_get(b"agg", BoundStorage.pack_int_key(-2))
2051+
if result is None:
20482052
# Most aggregates have no const params; cache the negative result
20492053
# so we don't re-hit storage on every aggregate_window /
20502054
# aggregate_update / etc.
20512055
_aggregate_const_args_cache.put(shard_key, execution_id, _ABSENT_SENTINEL)
20522056
return None
2053-
parsed = Arguments.deserialize_from_bytes(result[0][1])
2057+
parsed = Arguments.deserialize_from_bytes(result)
20542058
_aggregate_const_args_cache.put(shard_key, execution_id, parsed)
20552059
return parsed
20562060

@@ -2105,10 +2109,12 @@ def aggregate_bind(
21052109
"which is not yet supported for aggregate functions."
21062110
)
21072111

2108-
# Store const arguments in FunctionStorage for later callbacks (group_id=-2).
2112+
# Store const arguments in FunctionStorage for later callbacks
2113+
# (synthetic group_id=-2 in namespace b"agg").
21092114
if request.arguments and request.arguments.positional:
21102115
storage = BoundStorage(func_cls.storage, execution_id, request=request, auth=ctx.auth)
2111-
storage.aggregate_put([(-2, request.arguments.serialize_to_bytes())])
2116+
storage.state_put(b"agg", BoundStorage.pack_int_key(-2),
2117+
request.arguments.serialize_to_bytes())
21122118

21132119
return AggregateBindResponse(
21142120
output_schema=result.output_schema,
@@ -2171,11 +2177,12 @@ def aggregate_update(
21712177
# are also persisted so multi-batch state survives.
21722178
existing_gids: set[int] = set()
21732179
states: _UpdateTrackingDict[int, Any] = _UpdateTrackingDict()
2174-
stored = storage.aggregate_get(unique_gids)
2180+
gid_keys = [BoundStorage.pack_int_key(g) for g in unique_gids]
2181+
stored = storage.state_get_many(b"agg", gid_keys)
21752182
for i, gid in enumerate(unique_gids):
2176-
result = stored[i]
2177-
if result is not None:
2178-
states[gid] = func_cls.state_class.deserialize_from_bytes(result[1])
2183+
value = stored[i]
2184+
if value is not None:
2185+
states[gid] = func_cls.state_class.deserialize_from_bytes(value)
21792186
existing_gids.add(gid)
21802187
else:
21812188
states[gid] = func_cls.initial_state(params)
@@ -2218,9 +2225,12 @@ def aggregate_update(
22182225
# (its state may have been mutated by the user) and (b) every gid the
22192226
# user's ``update()`` explicitly wrote during this batch.
22202227
gids_to_persist = existing_gids | states.written
2221-
state_data: list[tuple[int, bytes]] = [(gid, states[gid].serialize_to_bytes()) for gid in gids_to_persist]
2222-
if state_data:
2223-
storage.aggregate_put(state_data)
2228+
items: list[tuple[bytes, bytes]] = [
2229+
(BoundStorage.pack_int_key(gid), states[gid].serialize_to_bytes())
2230+
for gid in gids_to_persist
2231+
]
2232+
if items:
2233+
storage.state_put_many(b"agg", items)
22242234

22252235
return AggregateUpdateResponse()
22262236

@@ -2262,11 +2272,12 @@ def aggregate_combine(
22622272
auth_context=ctx.auth,
22632273
)
22642274
states: dict[int, Any] = {}
2265-
stored = storage.aggregate_get(all_gids)
2275+
all_keys = [BoundStorage.pack_int_key(g) for g in all_gids]
2276+
stored = storage.state_get_many(b"agg", all_keys)
22662277
for i, gid in enumerate(all_gids):
2267-
result = stored[i]
2268-
if result is not None:
2269-
states[gid] = func_cls.state_class.deserialize_from_bytes(result[1])
2278+
value = stored[i]
2279+
if value is not None:
2280+
states[gid] = func_cls.state_class.deserialize_from_bytes(value)
22702281
# else: group was never updated — leave absent from states dict
22712282

22722283
# Apply merges. Skip pairs where both source and target were never
@@ -2285,9 +2296,13 @@ def aggregate_combine(
22852296

22862297
# Save updated targets back to storage.
22872298
updated_targets = set(target_ids)
2288-
state_data = [(gid, states[gid].serialize_to_bytes()) for gid in updated_targets if gid in states]
2289-
if state_data:
2290-
storage.aggregate_put(state_data)
2299+
items = [
2300+
(BoundStorage.pack_int_key(gid), states[gid].serialize_to_bytes())
2301+
for gid in updated_targets
2302+
if gid in states
2303+
]
2304+
if items:
2305+
storage.state_put_many(b"agg", items)
22912306

22922307
return AggregateCombineResponse()
22932308

@@ -2324,11 +2339,12 @@ def aggregate_finalize(
23242339
auth_context=ctx.auth,
23252340
)
23262341
states: dict[int, Any] = {}
2327-
stored = storage.aggregate_get(gid_list)
2342+
gid_keys = [BoundStorage.pack_int_key(g) for g in gid_list]
2343+
stored = storage.state_get_many(b"agg", gid_keys)
23282344
for i, gid in enumerate(gid_list):
2329-
result = stored[i]
2330-
if result is not None:
2331-
states[gid] = func_cls.state_class.deserialize_from_bytes(result[1])
2345+
value = stored[i]
2346+
if value is not None:
2347+
states[gid] = func_cls.state_class.deserialize_from_bytes(value)
23322348
else:
23332349
# Group was never updated — no entry in FunctionStorage.
23342350
# Pass None so finalize() can return NULL (SQL standard for
@@ -2365,12 +2381,12 @@ def aggregate_destructor(
23652381
raise TypeError(f"Function '{request.function_name}' is not an AggregateFunction (got {func_cls.__name__})")
23662382

23672383
# Called once when all states have been destroyed (C++ tracks with
2368-
# destroy_counter == group_id_counter). Clear all FunctionStorage state.
2384+
# destroy_counter == group_id_counter). Clear all FunctionStorage
2385+
# state. execution_clear() sweeps every namespace (b"agg", b"win",
2386+
# b"buf", anything else) for this execution_id in one call —
2387+
# subsumes the per-family clears we used to need.
23692388
storage = BoundStorage(func_cls.storage, request.execution_id, request=request, auth=ctx.auth)
2370-
storage.aggregate_clear()
2371-
# Safety sweep for windowed aggregates — in case a window_destructor
2372-
# RPC was dropped mid-query.
2373-
storage.aggregate_window_partition_clear()
2389+
storage.execution_clear()
23742390
_window_partition_cache.clear_execution(request.execution_id)
23752391
_aggregate_const_args_cache.clear_execution(storage._shard_key, request.execution_id)
23762392

@@ -2617,7 +2633,7 @@ def aggregate_window_init(
26172633
window_state_bytes=window_state_bytes,
26182634
window_state_class_name=type(window_state).__name__ if window_state is not None else "",
26192635
)
2620-
storage.aggregate_window_partition_put(request.partition_id, payload)
2636+
storage.state_put(b"win", BoundStorage.pack_int_key(request.partition_id), payload)
26212637

26222638
# Populate the in-process cache with the already-decoded partition
26232639
# so aggregate_window() can skip the storage read + deserialize.
@@ -2732,7 +2748,7 @@ def _load_cached_window_partition(
27322748
if cached is not None:
27332749
return cached
27342750

2735-
payload = storage.aggregate_window_partition_get(partition_id)
2751+
payload = storage.state_get(b"win", BoundStorage.pack_int_key(partition_id))
27362752
if payload is None:
27372753
raise OSError(
27382754
f"aggregate_window called for unknown partition_id={partition_id} "
@@ -2860,7 +2876,7 @@ def aggregate_window_destructor(
28602876
raise TypeError(f"Function '{request.function_name}' is not an AggregateFunction (got {func_cls.__name__})")
28612877

28622878
storage = BoundStorage(func_cls.storage, request.execution_id, request=request, auth=ctx.auth)
2863-
storage.aggregate_window_partition_delete(request.partition_id)
2879+
storage.state_delete(b"win", [BoundStorage.pack_int_key(request.partition_id)])
28642880
_window_partition_cache.delete(request.execution_id, request.partition_id)
28652881
return AggregateWindowDestructorResponse()
28662882

@@ -2885,7 +2901,8 @@ def aggregate_streaming_open(
28852901
# declares const params.
28862902
if request.arguments and request.arguments.positional:
28872903
storage = BoundStorage(func_cls.storage, execution_id, request=request, auth=ctx.auth)
2888-
storage.aggregate_put([(-2, request.arguments.serialize_to_bytes())])
2904+
storage.state_put(b"agg", BoundStorage.pack_int_key(-2),
2905+
request.arguments.serialize_to_bytes())
28892906

28902907
storage = BoundStorage(func_cls.storage, execution_id, request=request, auth=ctx.auth)
28912908
const_args = self._load_aggregate_const_args(func_cls, storage)
@@ -2912,7 +2929,7 @@ def aggregate_streaming_open(
29122929
_streaming_session_cache.put(execution_id, session)
29132930
# Also persist to FunctionStorage so a chunk RPC landing on a
29142931
# different pool worker can reload the session.
2915-
storage.aggregate_window_partition_put(_STREAMING_SESSION_STORAGE_KEY, _encode_streaming_session(session))
2932+
storage.state_put(b"win", BoundStorage.pack_int_key(_STREAMING_SESSION_STORAGE_KEY), _encode_streaming_session(session))
29162933
return AggregateStreamingOpenResponse(execution_id=execution_id)
29172934

29182935
def aggregate_streaming_chunk(
@@ -2938,7 +2955,7 @@ def aggregate_streaming_chunk(
29382955
import time as _t
29392956

29402957
t_get_start = _t.perf_counter()
2941-
payload = cold_storage.aggregate_window_partition_get(_STREAMING_SESSION_STORAGE_KEY)
2958+
payload = cold_storage.state_get(b"win", BoundStorage.pack_int_key(_STREAMING_SESSION_STORAGE_KEY))
29422959
t_get = _t.perf_counter() - t_get_start
29432960
with _streaming_persist_lock:
29442961
_streaming_persist_stats["storage_get_seconds"] += t_get
@@ -2996,7 +3013,7 @@ def aggregate_streaming_chunk(
29963013
payload = _encode_streaming_session(session)
29973014
t_enc = _t.perf_counter() - t_enc_start
29983015
t_put_start = _t.perf_counter()
2999-
storage.aggregate_window_partition_put(_STREAMING_SESSION_STORAGE_KEY, payload)
3016+
storage.state_put(b"win", BoundStorage.pack_int_key(_STREAMING_SESSION_STORAGE_KEY), payload)
30003017
t_put = _t.perf_counter() - t_put_start
30013018
_record_persist_timing(t_enc, t_put, len(payload))
30023019
with _streaming_persist_lock:
@@ -3027,10 +3044,10 @@ def aggregate_streaming_close(
30273044
func_cls = None
30283045
if func_cls is not None and issubclass(func_cls, AggregateFunction):
30293046
cold_storage = BoundStorage(func_cls.storage, request.execution_id, request=request, auth=ctx.auth)
3030-
payload = cold_storage.aggregate_window_partition_get(_STREAMING_SESSION_STORAGE_KEY)
3047+
payload = cold_storage.state_get(b"win", BoundStorage.pack_int_key(_STREAMING_SESSION_STORAGE_KEY))
30313048
if payload is not None:
30323049
session = _decode_streaming_session(payload, func_cls)
3033-
cold_storage.aggregate_window_partition_delete(_STREAMING_SESSION_STORAGE_KEY)
3050+
cold_storage.state_delete(b"win", [BoundStorage.pack_int_key(_STREAMING_SESSION_STORAGE_KEY)])
30343051
if session is None:
30353052
# Idempotent: nothing to clean up.
30363053
return AggregateStreamingCloseResponse()
@@ -3053,7 +3070,7 @@ def aggregate_streaming_close(
30533070
_logger.exception("streaming_close raised; session dropped anyway")
30543071

30553072
# Drop the persisted state.
3056-
storage.aggregate_window_partition_delete(_STREAMING_SESSION_STORAGE_KEY)
3073+
storage.state_delete(b"win", [BoundStorage.pack_int_key(_STREAMING_SESSION_STORAGE_KEY)])
30573074

30583075
# Dump worker-side persist stats accumulated for this session.
30593076
with _streaming_persist_lock:

0 commit comments

Comments
 (0)