Skip to content

Commit de3cb06

Browse files
rustyconoverclaude
andcommitted
buffered_table: relocate init metadata to BoundStorage; remove process global (review §2)
Previously vgi/worker.py held a module-level dict ``_buffered_table_exec_cache: dict[execution_id, (func_cls, params)]`` populated at init (phase=BUFFERED_TABLE) and read by the three buffered_table_{process,combine,finalize} handlers. The dict was never popped — permanent memory leak per query for the worker's lifetime — and forced the C++ Sink+Source operator to pin one worker per execution because RPCs landing on a worker that didn't run init would raise "execution not initialized." This commit moves the bind/init metadata to FunctionStorage: * At init (phase=BUFFERED_TABLE), persist the (InitRequest, GlobalInitResponse) byte envelopes under namespace b"buf_init", key pack_int_key(_BUFFERED_TABLE_INIT_KEY). * Add ``_load_buffered_table_params`` helper that on every RPC resolves the function class by name (registry-driven, available on every worker), reads the persisted envelopes from FunctionStorage, and rebuilds ProcessParams via the same construction the init handler performs (args parsed via _parse_arguments, settings via _batch_to_scalar_dict, secrets via SecretsAccessor). * Drop ``_buffered_table_exec_cache`` entirely. Workers are now stateless w.r.t. buffered_table executions. Any pool worker can serve any RPC for any execution_id; the C++ side's sticky- worker requirement is no longer load-bearing on the worker-side cache. Cost: one extra ``state_get(b"buf_init", ...)`` per RPC. Negligible on subprocess transport (SQLite via WAL is microseconds). On CfDo this is one HTTP RTT per RPC — bench shows +10-15% on the heavy 100k×1024B cells. If that surfaces as a real bottleneck in HTTP deployments, the mitigation is to thread the metadata bytes through the request envelope from C++ (out of scope here). Tests: all 14 buffered_table integration tests pass. vgi-python suite: 31 failed / 1651 passed — baseline failure count unchanged. The ``_buffered_table_finalize_iters`` dict is intentionally NOT relocated: it holds generator stack frames, which are intrinsically process-local. The destructor RPC (next commit) will pop orphaned entries; steady-state finalize sequences self-clean on StopIteration. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
1 parent 81c27ca commit de3cb06

1 file changed

Lines changed: 105 additions & 59 deletions

File tree

‎vgi/worker.py‎

Lines changed: 105 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -434,17 +434,20 @@ def clear_execution(self, shard_key: str, execution_id: bytes) -> None:
434434
_aggregate_const_args_cache = _AggregateConstArgsCache()
435435

436436

437-
# Process-local cache for the buffered-table-function path. Keyed by
438-
# execution_id (raw bytes). Maps to (func_cls, ProcessParams). The init
439-
# handler populates this on phase=BUFFERED_TABLE; the
440-
# buffered_table_{process,combine,finalize} handlers read it instead of
441-
# re-shipping the bind context on every RPC.
437+
# Buffered-table init metadata is persisted to FunctionStorage at init
438+
# time (namespace b"buf_init", key = pack_int_key(_BUFFERED_TABLE_INIT_KEY))
439+
# and cold-loaded by every subsequent buffered_table_{process,combine,
440+
# finalize} RPC. There is intentionally NO in-process cache here — workers
441+
# are stateless w.r.t. buffered_table executions, so any pool worker can
442+
# serve any RPC for any execution_id. The C++ Sink+Source operator no
443+
# longer has to pin one worker per query.
442444
#
443-
# Lifetime: until the C++ side tears down the execution. We could plumb a
444-
# destructor RPC to evict eagerly; for now the entry survives until the
445-
# worker process exits. The map is process-local, so each worker instance
446-
# only sees its own executions (primary or per-thread secondary).
447-
_buffered_table_exec_cache: dict[bytes, tuple[type, Any]] = {}
445+
# Cost: one extra storage round-trip per RPC. Negligible on subprocess
446+
# (SQLite is microseconds). One HTTP RTT on CfDo deployments — if that
447+
# surfaces as a hot-path bottleneck, the mitigation is to thread the
448+
# init metadata bytes through the request envelope from C++ instead.
449+
_BUFFERED_TABLE_INIT_KEY = -1
450+
448451

449452
# Process-local cache for in-flight finalize generators. Keyed by
450453
# (execution_id, finalize_state_id). Each entry is the iterator returned
@@ -533,6 +536,32 @@ def _decode_streaming_session(payload: bytes, func_cls: type[AggregateFunction[A
533536
)
534537

535538

539+
# --- Buffered-table init metadata persistence ----------------------------
540+
#
541+
# Persists just the two ArrowSerializableDataclass envelopes (the init
542+
# request that the C++ side originally shipped, and the GlobalInitResponse
543+
# the worker built from it). On cold-load, deserializing these is enough
544+
# to rebuild the full ProcessParams via the same code path the init
545+
# handler runs. func_cls is NOT persisted — re-resolved by name from the
546+
# function registry on every load, both to avoid pickle-loading arbitrary
547+
# classes and to handle version skew if the function definition changes.
548+
549+
550+
def _encode_buffered_table_init(init_call: InitRequest, init_response: GlobalInitResponse) -> bytes:
551+
return pickle.dumps({
552+
"init_call_bytes": init_call.serialize_to_bytes(),
553+
"init_response_bytes": init_response.serialize_to_bytes(),
554+
})
555+
556+
557+
def _decode_buffered_table_init(payload: bytes) -> tuple[InitRequest, GlobalInitResponse]:
558+
d = pickle.loads(payload)
559+
return (
560+
InitRequest.deserialize_from_bytes(d["init_call_bytes"]),
561+
GlobalInitResponse.deserialize_from_bytes(d["init_response_bytes"]),
562+
)
563+
564+
536565
class _StreamingSessionCache:
537566
"""Process-local map ``execution_id -> _StreamingSession``."""
538567

@@ -2394,6 +2423,54 @@ def aggregate_destructor(
23942423

23952424
# ========== Buffered Table Function Methods (Sink+Source path) ==========
23962425

2426+
def _load_buffered_table_params(
2427+
self, request: Any, ctx: CallContext,
2428+
) -> tuple[type[TableInOutGenerator[Any, Any]], ProcessParams[Any]]:
2429+
"""Cold-load buffered_table init metadata from FunctionStorage.
2430+
2431+
Always reads from storage — no in-process cache. Costs one
2432+
round-trip per RPC; trade-off explained next to the
2433+
``_BUFFERED_TABLE_INIT_KEY`` constant. Raises ``OSError`` if the
2434+
execution_id is unknown (init never ran on this catalog, or the
2435+
destructor has already fired).
2436+
2437+
Returns ``(func_cls, base_params)``. Callers further specialize
2438+
``base_params`` per RPC via ``_dataclass_replace`` to inject the
2439+
request-scoped ``storage`` / ``auth_context`` / ``batch_index`` /
2440+
``state_id`` fields.
2441+
"""
2442+
func_cls = self._resolve_function_by_name(
2443+
request.function_name,
2444+
self._unwrap_attach(request.attach_opaque_data),
2445+
function_type=TableInOutGenerator,
2446+
)
2447+
cold_storage = BoundStorage(
2448+
func_cls.storage, request.execution_id, request=request, auth=ctx.auth,
2449+
)
2450+
payload = cold_storage.state_get(
2451+
b"buf_init", BoundStorage.pack_int_key(_BUFFERED_TABLE_INIT_KEY),
2452+
)
2453+
if payload is None:
2454+
raise OSError(
2455+
f"buffered_table: unknown execution_id {request.execution_id.hex()} "
2456+
f"(init never ran or destructor already fired)"
2457+
)
2458+
init_call, init_response = _decode_buffered_table_init(payload)
2459+
# Rebuild ProcessParams from the persisted init request — same
2460+
# construction the init handler performs (worker.py search:
2461+
# "Table-in-out function: separate INPUT and FINALIZE phases").
2462+
base_params = ProcessParams(
2463+
args=func_cls._parse_arguments(func_cls.FunctionArguments, init_call.bind_call.arguments),
2464+
init_call=init_call,
2465+
init_response=init_response,
2466+
output_schema=init_call.output_schema,
2467+
settings=_batch_to_scalar_dict(init_call.bind_call.settings),
2468+
secrets=SecretsAccessor(init_call.bind_call.secrets).to_dict(),
2469+
storage=cold_storage,
2470+
auth_context=ctx.auth,
2471+
)
2472+
return func_cls, base_params
2473+
23972474
def buffered_table_process(
23982475
self,
23992476
request: Any, # BufferedTableProcessRequest — lazy import below
@@ -2410,24 +2487,14 @@ def buffered_table_process(
24102487
"""
24112488
from vgi.protocol import BufferedTableProcessResponse
24122489

2413-
cached = _buffered_table_exec_cache.get(request.execution_id)
2414-
if cached is None:
2415-
raise RuntimeError(
2416-
f"buffered_table_process: execution {request.execution_id.hex()} "
2417-
f"not initialized — was init phase=BUFFERED_TABLE called first?"
2418-
)
2419-
func_cls, params = cached
2420-
# Rebuild storage with this request's auth context so the storage
2421-
# layer's request-scoped fields stay consistent. Forward the
2422-
# per-call batch_index (only set when Meta.requires_input_batch_index
2423-
# = True; otherwise None). ProcessParams is otherwise immutable
2424-
# across process() calls within one execution.
2490+
func_cls, params = self._load_buffered_table_params(request, ctx)
2491+
# Inject per-RPC fields. ``storage`` is already bound to the right
2492+
# execution_id by the loader; we still call _dataclass_replace
2493+
# to forward batch_index / state_id (set only on the process
2494+
# path). Per-RPC fields rebuilt as today; ProcessParams is
2495+
# otherwise immutable across process() calls within one execution.
24252496
params = _dataclass_replace(
24262497
params,
2427-
storage=BoundStorage(
2428-
func_cls.storage, request.execution_id, request=request, auth=ctx.auth
2429-
),
2430-
auth_context=ctx.auth,
24312498
batch_index=request.batch_index,
24322499
state_id=request.state_id,
24332500
)
@@ -2495,20 +2562,7 @@ def buffered_table_combine(
24952562
the partition keys the source phase will iterate over."""
24962563
from vgi.protocol import BufferedTableCombineResponse
24972564

2498-
cached = _buffered_table_exec_cache.get(request.execution_id)
2499-
if cached is None:
2500-
raise RuntimeError(
2501-
f"buffered_table_combine: execution {request.execution_id.hex()} "
2502-
f"not initialized"
2503-
)
2504-
func_cls, params = cached
2505-
params = _dataclass_replace(
2506-
params,
2507-
storage=BoundStorage(
2508-
func_cls.storage, request.execution_id, request=request, auth=ctx.auth
2509-
),
2510-
auth_context=ctx.auth,
2511-
)
2565+
func_cls, params = self._load_buffered_table_params(request, ctx)
25122566
finalize_state_ids = list(func_cls.combine(list(request.state_ids), params))
25132567
return BufferedTableCombineResponse(finalize_state_ids=finalize_state_ids)
25142568

@@ -2526,20 +2580,7 @@ def buffered_table_finalize(
25262580
"""
25272581
from vgi.protocol import BufferedTableFinalizeResponse
25282582

2529-
cached = _buffered_table_exec_cache.get(request.execution_id)
2530-
if cached is None:
2531-
raise RuntimeError(
2532-
f"buffered_table_finalize: execution {request.execution_id.hex()} "
2533-
f"not initialized"
2534-
)
2535-
func_cls, params = cached
2536-
params = _dataclass_replace(
2537-
params,
2538-
storage=BoundStorage(
2539-
func_cls.storage, request.execution_id, request=request, auth=ctx.auth
2540-
),
2541-
auth_context=ctx.auth,
2542-
)
2583+
func_cls, params = self._load_buffered_table_params(request, ctx)
25432584

25442585
key = (request.execution_id, request.finalize_state_id)
25452586
iter_ = _buffered_table_finalize_iters.get(key)
@@ -3221,11 +3262,16 @@ def init(self, request: InitRequest, ctx: CallContext) -> Stream[ProcessState, G
32213262
elif request.phase == TableInOutFunctionInitPhase.BUFFERED_TABLE:
32223263
# Sink+Source path. The init RPC itself carries no data
32233264
# exchange — all subsequent traffic uses the dedicated
3224-
# buffered_table_{process,combine,finalize} RPCs. We just
3225-
# cache the function class + params keyed by execution_id
3226-
# so those handlers can rebuild ProcessParams without
3227-
# re-shipping the bind context on every call.
3228-
_buffered_table_exec_cache[init_response.execution_id] = (type(instance), params)
3265+
# buffered_table_{process,combine,finalize} RPCs. Persist
3266+
# the init request + response into FunctionStorage so any
3267+
# pool worker can cold-load and serve subsequent RPCs.
3268+
# No in-process cache: workers are stateless w.r.t.
3269+
# buffered_table executions.
3270+
params.storage.state_put(
3271+
b"buf_init",
3272+
BoundStorage.pack_int_key(_BUFFERED_TABLE_INIT_KEY),
3273+
_encode_buffered_table_init(request, init_response),
3274+
)
32293275
# An empty-batches TableInOutFinalizeState produces nothing
32303276
# and immediately calls out.finish() — exactly the right
32313277
# behavior for a stream we won't use.

0 commit comments

Comments
 (0)