Skip to content

Commit b77ce27

Browse files
rustyconoverclaude
andcommitted
aggregate: persist state by tracking explicit user writes
Replace the byte-equality optimisation in `aggregate_update` that skipped persisting "new groups whose state didn't change" with an explicit tracking dict. The old heuristic conflated two cases: 1. update() saw rows but chose not to mutate state (e.g. SumFunction skipping all-NULL value_sum) -> finalize should return NULL. 2. update() saw rows and assigned a state byte-equal to the initial state (e.g. SumState(total=0) after summing zeros) -> finalize should return that state. The conflation meant `vgi_sum(0)` returned NULL where built-in `sum(0)` returns 0 — observable both as `SELECT vgi_sum(0) FROM range(5)` and `SELECT vgi_sum(i) OVER (ORDER BY i ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) FROM range(5)`. Same trap applied to any aggregate whose post-update state happened to match its initial state for some input. The fix introduces `_UpdateTrackingDict`, a dict subclass that records every gid the user explicitly reassigns. After update() runs, the framework persists (a) every gid that already had storage from a prior batch and (b) every gid the user wrote during this batch. Pre-existing entries from prior batches are also persisted so multi-batch state survives. The all-NULL guarantee is preserved because SumFunction's `if val is not None` guard never executes `states[gid] = ...`, leaving the gid out of `states.written`. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
1 parent ac1caf4 commit b77ce27

1 file changed

Lines changed: 51 additions & 16 deletions

File tree

‎vgi/worker.py‎

Lines changed: 51 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -289,6 +289,30 @@ def format_scalar(scalar: Any) -> str:
289289
_WINDOW_PARTITION_CACHE_MAX = 256
290290

291291

292+
class _UpdateTrackingDict[K, V](dict[K, V]):
293+
"""A dict that records explicit ``__setitem__`` writes.
294+
295+
Used by ``aggregate_update`` to tell apart "user's update() reassigned
296+
state for this group" from "we pre-populated the entry with initial
297+
state and the user's update() chose not to touch it (e.g. saw only
298+
NULL inputs)". The framework then persists only entries the user
299+
actually wrote, so a no-op update on a freshly-seeded group does not
300+
overwrite the absence of stored state — preserving SQL-standard
301+
NULL semantics for ``SUM`` of all NULLs.
302+
"""
303+
304+
def __init__(self) -> None:
305+
super().__init__()
306+
self.written: set[K] = set()
307+
308+
def __setitem__(self, key: K, value: V) -> None:
309+
super().__setitem__(key, value)
310+
self.written.add(key)
311+
312+
def clear_writes(self) -> None:
313+
self.written.clear()
314+
315+
292316
@dataclass(slots=True)
293317
class _CachedWindowPartition:
294318
"""Fully-decoded partition ready to hand to the user's ``window()``.
@@ -1686,19 +1710,34 @@ def aggregate_update(
16861710
storage=storage,
16871711
auth_context=ctx.auth,
16881712
)
1689-
states: dict[int, Any] = {}
1690-
new_gids: set[int] = set() # Track groups created in this batch
1691-
initial_bytes: dict[int, bytes] = {} # Snapshot initial state for new groups
1713+
# ``states`` is a tracking dict that records every gid the user's
1714+
# ``update()`` reassigns. Earlier this method used a plain dict and
1715+
# then heuristically skipped persisting "new groups whose serialized
1716+
# state didn't change". That heuristic conflated two cases:
1717+
#
1718+
# 1. ``update()`` saw rows but chose not to mutate state (e.g.
1719+
# SumFunction skipping all-NULL value_sum) → finalize should
1720+
# return NULL because the group effectively had no rows.
1721+
# 2. ``update()`` saw rows and assigned a state that happens to be
1722+
# byte-equal to the initial state (e.g. ``SumState(total=0)``
1723+
# after summing zeros) → finalize should return that state.
1724+
#
1725+
# The fix: persist a state iff the user explicitly wrote it during
1726+
# this batch's ``update()``. Pre-existing entries from prior batches
1727+
# are also persisted so multi-batch state survives.
1728+
existing_gids: set[int] = set()
1729+
states: _UpdateTrackingDict[int, Any] = _UpdateTrackingDict()
16921730
stored = storage.aggregate_get(unique_gids)
16931731
for i, gid in enumerate(unique_gids):
16941732
result = stored[i]
16951733
if result is not None:
16961734
states[gid] = func_cls.state_class.deserialize_from_bytes(result[1])
1735+
existing_gids.add(gid)
16971736
else:
1698-
state = func_cls.initial_state(params)
1699-
states[gid] = state
1700-
new_gids.add(gid)
1701-
initial_bytes[gid] = state.serialize_to_bytes()
1737+
states[gid] = func_cls.initial_state(params)
1738+
# Snapshot the writes made during seeding so we don't count them as
1739+
# user-initiated mutations.
1740+
states.clear_writes()
17021741

17031742
# Call user's update() with column arrays and const scalars as kwargs
17041743
kwargs: dict[str, Any] = {"states": states, "group_ids": group_ids}
@@ -1731,15 +1770,11 @@ def aggregate_update(
17311770
kwargs["params"] = params
17321771
func_cls.update(**kwargs)
17331772

1734-
# Save updated states. Skip new groups whose state wasn't modified —
1735-
# this ensures groups that received only NULL values (NullHandling.DEFAULT
1736-
# skips them) don't get stored, so finalize() sees None → returns NULL.
1737-
state_data: list[tuple[int, bytes]] = []
1738-
for gid in states:
1739-
serialized = states[gid].serialize_to_bytes()
1740-
if gid in new_gids and serialized == initial_bytes[gid]:
1741-
continue # New group, not modified by update() — don't persist
1742-
state_data.append((gid, serialized))
1773+
# Persist (a) every gid that already had storage from a prior batch
1774+
# (its state may have been mutated by the user) and (b) every gid the
1775+
# user's ``update()`` explicitly wrote during this batch.
1776+
gids_to_persist = existing_gids | states.written
1777+
state_data: list[tuple[int, bytes]] = [(gid, states[gid].serialize_to_bytes()) for gid in gids_to_persist]
17431778
if state_data:
17441779
storage.aggregate_put(state_data)
17451780

0 commit comments

Comments
 (0)