From 2accf28062e46020148232fa221f8c198bf7273a Mon Sep 17 00:00:00 2001 From: Radek Stankiewicz Date: Fri, 13 Nov 2026 19:03:08 +0000 Subject: [PATCH 1/3] Incrementally update StateCache weight on extend --- .../apache_beam/runners/worker/sdk_worker.py | 5 +-- .../apache_beam/runners/worker/statecache.py | 37 +++++++++++++++++++ .../runners/worker/statecache_test.py | 29 +++++++++++++++ 3 files changed, 67 insertions(+), 4 deletions(-) diff --git a/sdks/python/apache_beam/runners/worker/sdk_worker.py b/sdks/python/apache_beam/runners/worker/sdk_worker.py index bc7e80c1edc2..5ad81927e090 100644 --- a/sdks/python/apache_beam/runners/worker/sdk_worker.py +++ b/sdks/python/apache_beam/runners/worker/sdk_worker.py @@ -1269,10 +1269,7 @@ def extend( # Materialize provided iterable to ensure reproducible iterations, # here and when writing to the state handler below. elements = list(elements) - cached_value.extend(elements) - # Re-insert into the cache the updated value so the updated size is - # reflected. - self._state_cache.put((cache_key, cache_token), cached_value) + self._state_cache.extend((cache_key, cache_token), elements) # Write to state handler futures = [] diff --git a/sdks/python/apache_beam/runners/worker/statecache.py b/sdks/python/apache_beam/runners/worker/statecache.py index 33e1c55deeff..95370f0ec05a 100644 --- a/sdks/python/apache_beam/runners/worker/statecache.py +++ b/sdks/python/apache_beam/runners/worker/statecache.py @@ -29,6 +29,7 @@ import weakref from typing import Any from typing import Callable +from typing import Iterable from typing import Union import objsize @@ -331,6 +332,42 @@ def put(self, key: Any, value: Any) -> None: self._current_weight -= weighted_value.weight() self._evict_count += 1 + def extend(self, key: Any, elements: Iterable[Any]) -> None: + assert self.is_cache_enabled() + with self._lock: + entry = self._cache.get(key, None) + if entry is None or _safe_isinstance(entry, _LoadingValue): + return + if not hasattr(entry.value(), 'extend'): + raise TypeError( + 'Cached value of type %s does not support extend' % + type(entry.value())) + + elements = list(elements) + added_weight = max(0, get_deep_size(*elements)) if elements else 0 + with self._lock: + entry = self._cache.get(key, None) + if entry is None or _safe_isinstance(entry, _LoadingValue): + return + cached_value = entry.value() + if not hasattr(cached_value, 'extend'): + raise TypeError( + 'Cached value of type %s does not support extend' % + type(cached_value)) + old_container_shallow = _size_func(cached_value) + cached_value.extend(elements) + new_container_shallow = _size_func(cached_value) + delta_weight = max( + 0, added_weight + (new_container_shallow - old_container_shallow)) + new_weight = max(_DEFAULT_WEIGHT, entry.weight() + delta_weight) + self._cache.pop(key, None) + self._cache[key] = WeightedValue(cached_value, new_weight) + self._current_weight += new_weight - entry.weight() + while self._current_weight > self._max_weight: + (_, weighted_value) = self._cache.popitem(last=False) + self._current_weight -= weighted_value.weight() + self._evict_count += 1 + def invalidate(self, key: Any) -> None: assert self.is_cache_enabled() with self._lock: diff --git a/sdks/python/apache_beam/runners/worker/statecache_test.py b/sdks/python/apache_beam/runners/worker/statecache_test.py index 7e02ff6a416a..2cee8066c1d1 100644 --- a/sdks/python/apache_beam/runners/worker/statecache_test.py +++ b/sdks/python/apache_beam/runners/worker/statecache_test.py @@ -412,6 +412,35 @@ def test_current_weight_between_get_and_put(self): self.assertEqual(get_cache._current_weight, put_cache._current_weight) + def test_extend_incremental_weight(self): + cache = StateCache(5 << 20) + initial = [{'k': i, 'v': 'x' * 50} for i in range(10)] + cache.put('key', list(initial)) + + sized_args = [] + orig_get_deep_size = objsize.get_deep_size + + def tracking_get_deep_size(*objs, **kwargs): + sized_args.append(objs) + return orig_get_deep_size(*objs, **kwargs) + + new_elements = [{'k': 10, 'v': 'y' * 50}, {'k': 11, 'v': 'z' * 50}] + with unittest.mock.patch.object(objsize, + 'get_deep_size', + side_effect=tracking_get_deep_size): + cache.extend('key', new_elements) + + self.assertEqual(len(sized_args), 1) + self.assertEqual(list(sized_args[0]), new_elements) + self.assertEqual(cache.peek('key'), initial + new_elements) + self.assertEqual(cache._current_weight, get_deep_size(cache.peek('key'))) + + def test_extend_non_extensible_raises_type_error(self): + cache = StateCache(5 << 20) + cache.put('key', (1, 2, 3)) + with self.assertRaises(TypeError): + cache.extend('key', [4, 5]) + if __name__ == '__main__': logging.getLogger().setLevel(logging.INFO) From cfe56c5da051f70f3c32cde7c5eb045348c693d7 Mon Sep 17 00:00:00 2001 From: Radek Stankiewicz Date: Tue, 24 Nov 2026 13:40:52 +0000 Subject: [PATCH 2/3] Simplify locking and enforce list type in StateCache.extend Drop the redundant pre-sizing lock check and duplicate list copy in StateCache.extend, and restrict cached values to list so sys.getsizeof tracks container growth accurately. Keep missing and loading entries as a no-op because another worker thread can evict or reload the key while elements are sized outside the lock. --- .../apache_beam/runners/worker/sdk_worker.py | 5 ++-- .../apache_beam/runners/worker/statecache.py | 21 ++++++---------- .../runners/worker/statecache_test.py | 25 ++++++++++++++++--- 3 files changed, 31 insertions(+), 20 deletions(-) diff --git a/sdks/python/apache_beam/runners/worker/sdk_worker.py b/sdks/python/apache_beam/runners/worker/sdk_worker.py index 5ad81927e090..b22ee3074b69 100644 --- a/sdks/python/apache_beam/runners/worker/sdk_worker.py +++ b/sdks/python/apache_beam/runners/worker/sdk_worker.py @@ -1268,8 +1268,9 @@ def extend( # Materialize provided iterable to ensure reproducible iterations, # here and when writing to the state handler below. - elements = list(elements) - self._state_cache.extend((cache_key, cache_token), elements) + materialized = list(elements) + elements = materialized + self._state_cache.extend((cache_key, cache_token), materialized) # Write to state handler futures = [] diff --git a/sdks/python/apache_beam/runners/worker/statecache.py b/sdks/python/apache_beam/runners/worker/statecache.py index 95370f0ec05a..5599e48b63ae 100644 --- a/sdks/python/apache_beam/runners/worker/statecache.py +++ b/sdks/python/apache_beam/runners/worker/statecache.py @@ -29,7 +29,7 @@ import weakref from typing import Any from typing import Callable -from typing import Iterable +from typing import Sequence from typing import Union import objsize @@ -332,27 +332,20 @@ def put(self, key: Any, value: Any) -> None: self._current_weight -= weighted_value.weight() self._evict_count += 1 - def extend(self, key: Any, elements: Iterable[Any]) -> None: + def extend(self, key: Any, elements: Sequence[Any]) -> None: assert self.is_cache_enabled() - with self._lock: - entry = self._cache.get(key, None) - if entry is None or _safe_isinstance(entry, _LoadingValue): - return - if not hasattr(entry.value(), 'extend'): - raise TypeError( - 'Cached value of type %s does not support extend' % - type(entry.value())) - - elements = list(elements) added_weight = max(0, get_deep_size(*elements)) if elements else 0 with self._lock: entry = self._cache.get(key, None) if entry is None or _safe_isinstance(entry, _LoadingValue): + # Entry may have been concurrently LRU-evicted, invalidated, or + # started reloading by another worker thread while sizing elements + # outside the lock. return cached_value = entry.value() - if not hasattr(cached_value, 'extend'): + if not isinstance(cached_value, list): raise TypeError( - 'Cached value of type %s does not support extend' % + 'Cached value of type %s is not a list and cannot be extended' % type(cached_value)) old_container_shallow = _size_func(cached_value) cached_value.extend(elements) diff --git a/sdks/python/apache_beam/runners/worker/statecache_test.py b/sdks/python/apache_beam/runners/worker/statecache_test.py index 2cee8066c1d1..8089c37ff95c 100644 --- a/sdks/python/apache_beam/runners/worker/statecache_test.py +++ b/sdks/python/apache_beam/runners/worker/statecache_test.py @@ -18,6 +18,7 @@ """Tests for state caching.""" # pytype: skip-file +import collections import logging import re import sys @@ -435,11 +436,27 @@ def tracking_get_deep_size(*objs, **kwargs): self.assertEqual(cache.peek('key'), initial + new_elements) self.assertEqual(cache._current_weight, get_deep_size(cache.peek('key'))) - def test_extend_non_extensible_raises_type_error(self): + def test_extend_non_list_raises_type_error(self): cache = StateCache(5 << 20) - cache.put('key', (1, 2, 3)) - with self.assertRaises(TypeError): - cache.extend('key', [4, 5]) + for non_list in ((1, 2, 3), collections.deque([1, 2, 3])): + cache.put('key', non_list) + with self.assertRaises(TypeError): + cache.extend('key', [4, 5]) + + def test_extend_missing_or_loading_entry_is_noop(self): + cache = StateCache(5 << 20) + cache.extend('evicted_key', [1, 2]) + self.assertIsNone(cache.peek('evicted_key')) + self.assertEqual(cache._current_weight, 0) + + loading = _LoadingValue() + with cache._lock: + cache._cache['loading_key'] = loading + cache._current_weight += loading.weight() + weight_before = cache._current_weight + cache.extend('loading_key', [1, 2]) + self.assertEqual(cache._current_weight, weight_before) + self.assertIs(cache._cache['loading_key'], loading) if __name__ == '__main__': From 021860de33f88f365d636c544b3f3f1cce15346b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Stankiewicz?= Date: Fri, 27 Nov 2026 18:57:58 +0100 Subject: [PATCH 3/3] Apply suggestion from @damccorm Co-authored-by: Danny McCormick --- sdks/python/apache_beam/runners/worker/sdk_worker.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/sdks/python/apache_beam/runners/worker/sdk_worker.py b/sdks/python/apache_beam/runners/worker/sdk_worker.py index b22ee3074b69..5ad81927e090 100644 --- a/sdks/python/apache_beam/runners/worker/sdk_worker.py +++ b/sdks/python/apache_beam/runners/worker/sdk_worker.py @@ -1268,9 +1268,8 @@ def extend( # Materialize provided iterable to ensure reproducible iterations, # here and when writing to the state handler below. - materialized = list(elements) - elements = materialized - self._state_cache.extend((cache_key, cache_token), materialized) + elements = list(elements) + self._state_cache.extend((cache_key, cache_token), elements) # Write to state handler futures = []