Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 1 addition & 4 deletions sdks/python/apache_beam/runners/worker/sdk_worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = []
Expand Down
30 changes: 30 additions & 0 deletions sdks/python/apache_beam/runners/worker/statecache.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
import weakref
from typing import Any
from typing import Callable
from typing import Sequence
from typing import Union

import objsize
Expand Down Expand Up @@ -331,6 +332,35 @@ def put(self, key: Any, value: Any) -> None:
self._current_weight -= weighted_value.weight()
self._evict_count += 1

def extend(self, key: Any, elements: Sequence[Any]) -> None:
assert self.is_cache_enabled()
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 isinstance(cached_value, list):
raise TypeError(
'Cached value of type %s is not a list and cannot be extended' %
type(cached_value))
Comment thread
damccorm marked this conversation as resolved.
Resolved
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:
Expand Down
46 changes: 46 additions & 0 deletions sdks/python/apache_beam/runners/worker/statecache_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"""Tests for state caching."""
# pytype: skip-file

import collections
import logging
import re
import sys
Expand Down Expand Up @@ -412,6 +413,51 @@ 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_list_raises_type_error(self):
cache = StateCache(5 << 20)
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__':
logging.getLogger().setLevel(logging.INFO)
Expand Down
Loading