Skip to content

Commit 60cf0b3

Browse files
rustyconoverclaude
andcommitted
aggregate: add window_prepare hook for per-partition derived state
Windowed aggregates with non-trivial window_init() state today have no clean way to memoise the deserialised form across the many window() calls the framework makes per partition: _WindowStatePlaceholder uses __slots__ without __weakref__, so neither attribute attachment nor WeakKeyDictionary works, and (execution_id, partition_id) — the framework's own cache key — isn't exposed to user code. Users end up with module-level dicts keyed by id(), with content-addressable identity verification to defend against id reuse after gc. That's a footgun: in our portfolio_ops worker we hit a silent correctness bug where 89,949 out of 99,844 cells diverged when an old partition's state was reused for a fresh one. window_prepare is a new optional classmethod on AggregateFunction that runs once per partition (in aggregate_window_init for fresh state, or lazily on the first dispatcher call for cold-reloaded state), with its return value passed to every subsequent window() call as window_state. The result lives on _CachedWindowPartition.prepared_state alongside the placeholder; it's dropped automatically when the partition is evicted from the LRU or its destructor fires — same lifecycle as the framework's existing partition cache, no user-side bookkeeping required. Default implementation returns window_state unchanged, so aggregates that don't define this hook see the placeholder exactly as before — fully backward compatible. For our N=100K cumulative-window benchmark, switching from the id()-keyed cache workaround to window_prepare drops portfolio_agg_numpy from 1.1s to 0.83s (parity with the equivalent native UNNEST + sum() OVER + map_from_entries SQL). The bigger win is in the user code: ~80 lines of cache + identity-check logic delete. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
1 parent d2fe246 commit 60cf0b3

2 files changed

Lines changed: 84 additions & 6 deletions

File tree

‎vgi/aggregate_function.py‎

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -413,6 +413,40 @@ def window_init(
413413
"""
414414
return None
415415

416+
@classmethod
417+
def window_prepare(
418+
cls,
419+
partition: WindowPartition,
420+
window_state: Any,
421+
params: ProcessParams[Any],
422+
) -> Any:
423+
"""Optional hook: derive per-partition state for the window() loop.
424+
425+
Called once per partition, after ``window_init`` (or after the state
426+
is rehydrated from storage on a cold reload), before any
427+
``window()`` call. The return value is passed as ``window_state``
428+
to every ``window()`` call against this partition, replacing the
429+
opaque ``_WindowStatePlaceholder`` user code would otherwise
430+
receive.
431+
432+
Use this hook for one-shot per-partition work that ``window()``
433+
would otherwise have to redo on every call: deserialise the
434+
``_WindowStatePlaceholder``, reshape NumPy buffers from
435+
``window_init``'s state, build symbol→index lookups, etc.
436+
Anything you would otherwise be tempted to memoise via a
437+
module-level dict.
438+
439+
The result lives in the framework's per-partition cache and is
440+
dropped automatically when the partition is evicted from the LRU
441+
or its destructor fires.
442+
443+
Default implementation returns ``window_state`` unchanged — for
444+
aggregates that don't define this hook, ``window()`` receives the
445+
placeholder (or ``None``) exactly as it did before. Backward
446+
compatible.
447+
"""
448+
return window_state
449+
416450
@classmethod
417451
def window(
418452
cls,
@@ -429,7 +463,10 @@ def window(
429463
subframes: Frame ranges ``[(begin, end), ...]`` — 1 for the default
430464
frame, 3 when ``EXCLUDE`` produces multiple subframes.
431465
partition: The cached partition data.
432-
window_state: Value returned by ``window_init()`` (may be ``None``).
466+
window_state: ``window_prepare()``'s return value if the function
467+
defines that hook; otherwise the value returned by
468+
``window_init()`` (may be ``None``), wrapped in a
469+
``_WindowStatePlaceholder`` on cold reload.
433470
params: Shared ``ProcessParams``.
434471
435472
Returns:

‎vgi/worker.py‎

Lines changed: 46 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -284,11 +284,21 @@ def format_scalar(scalar: Any) -> str:
284284

285285
@dataclass(slots=True)
286286
class _CachedWindowPartition:
287-
"""Fully-decoded partition ready to hand to the user's ``window()``."""
287+
"""Fully-decoded partition ready to hand to the user's ``window()``.
288+
289+
``prepared_state`` holds the result of ``AggregateFunction.window_prepare``
290+
if the user defines that hook — typically the deserialized
291+
``window_state`` plus any per-partition derived structures (NumPy views,
292+
dictionary lookups, etc.). It lives only in this in-memory cache and is
293+
regenerated whenever the partition is reloaded from FunctionStorage.
294+
Defaults to ``window_state`` when no hook is defined, so existing
295+
aggregates see the placeholder unchanged.
296+
"""
288297

289298
partition: Any # vgi.aggregate_function.WindowPartition (avoid import cycle)
290299
output_schema: pa.Schema
291300
window_state: Any # _WindowStatePlaceholder | None
301+
prepared_state: Any = None
292302

293303

294304
class _WindowPartitionCache:
@@ -1832,13 +1842,20 @@ def aggregate_window_init(
18321842
raw_bytes=window_state_bytes,
18331843
class_name=type(window_state).__name__,
18341844
)
1845+
# Hand the just-built window_state (the typed dataclass, not the
1846+
# placeholder) to the optional window_prepare hook. Result lives
1847+
# alongside the placeholder in the in-memory cache.
1848+
prepared_state = func_cls.window_prepare(
1849+
partition, window_state, params,
1850+
)
18351851
_window_partition_cache.put(
18361852
request.execution_id,
18371853
request.partition_id,
18381854
_CachedWindowPartition(
18391855
partition=partition,
18401856
output_schema=request.output_schema,
18411857
window_state=cache_window_state,
1858+
prepared_state=prepared_state,
18421859
),
18431860
)
18441861

@@ -1864,7 +1881,6 @@ def aggregate_window(
18641881
)
18651882
partition = cached.partition
18661883
output_schema = cached.output_schema
1867-
window_state = cached.window_state
18681884

18691885
const_args = self._load_aggregate_const_args(func_cls, storage)
18701886
params = ProcessParams(
@@ -1878,8 +1894,18 @@ def aggregate_window(
18781894
auth_context=ctx.auth,
18791895
)
18801896

1897+
# Lazily populate prepared_state on first access — covers cold reloads
1898+
# from FunctionStorage where _load_cached_window_partition can't yet
1899+
# call window_prepare (no params available there).
1900+
if cached.prepared_state is None:
1901+
cached.prepared_state = func_cls.window_prepare(
1902+
partition, cached.window_state, params,
1903+
)
1904+
18811905
subframes = list(zip(request.frame_starts, request.frame_ends, strict=True))
1882-
result_value = func_cls.window(request.rid, subframes, partition, window_state, params)
1906+
result_value = func_cls.window(
1907+
request.rid, subframes, partition, cached.prepared_state, params,
1908+
)
18831909

18841910
# Build a one-row result batch matching output_schema
18851911
result_batch = _build_scalar_result_batch(result_value, output_schema)
@@ -1901,6 +1927,11 @@ def _load_cached_window_partition(
19011927
Falls back to storage on a cache miss (multi-process HTTP, LRU
19021928
eviction, or worker restart). Raises IOError if the partition is
19031929
unknown — window_init never ran, or the destructor already fired.
1930+
1931+
``prepared_state`` is left as ``None`` on cold reload; the dispatcher
1932+
(aggregate_window or aggregate_window_batch) will lazily populate it
1933+
on first access via ``func_cls.window_prepare``. That keeps this
1934+
function params-free, matching its previous signature.
19041935
"""
19051936
from vgi.aggregate_function import WindowPartition
19061937

@@ -1938,6 +1969,7 @@ def _load_cached_window_partition(
19381969
partition=partition,
19391970
output_schema=output_schema,
19401971
window_state=window_state,
1972+
prepared_state=None, # populated lazily by the dispatcher
19411973
)
19421974
_window_partition_cache.put(execution_id, partition_id, cached)
19431975
return cached
@@ -1962,7 +1994,6 @@ def aggregate_window_batch(
19621994
)
19631995
partition = cached.partition
19641996
output_schema = cached.output_schema
1965-
window_state = cached.window_state
19661997

19671998
const_args = self._load_aggregate_const_args(func_cls, storage)
19681999
params = ProcessParams(
@@ -1976,6 +2007,14 @@ def aggregate_window_batch(
19762007
auth_context=ctx.auth,
19772008
)
19782009

2010+
# Lazily populate prepared_state on first batch — covers cold reloads
2011+
# from FunctionStorage where _load_cached_window_partition can't yet
2012+
# call window_prepare (no params available there).
2013+
if cached.prepared_state is None:
2014+
cached.prepared_state = func_cls.window_prepare(
2015+
partition, cached.window_state, params,
2016+
)
2017+
19792018
# Unflatten subframes: frame_starts/frame_ends are concatenated across
19802019
# all rows, frames_per_row[i] gives the slice length for row i.
19812020
starts = request.frame_starts
@@ -1993,7 +2032,9 @@ def aggregate_window_batch(
19932032
subframes = [(starts[offset + k], ends[offset + k]) for k in range(n)]
19942033
offset += n
19952034
rid = request.row_idx + i
1996-
results.append(func_cls.window(rid, subframes, partition, window_state, params))
2035+
results.append(
2036+
func_cls.window(rid, subframes, partition, cached.prepared_state, params)
2037+
)
19972038

19982039
result_batch = _build_batch_result(results, output_schema)
19992040
sink = pa.BufferOutputStream()

0 commit comments

Comments
 (0)