-
Notifications
You must be signed in to change notification settings - Fork 1
chore: improve dataset cache #226
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
Fedir-Yatsenko
wants to merge
3
commits into
development
Choose a base branch
from
chore/improve-dataset-cache
base: development
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| import asyncio | ||
| from collections.abc import Awaitable, Callable | ||
| from typing import Generic, TypeVar | ||
|
|
||
| T = TypeVar('T') | ||
|
|
||
|
|
||
| class AsyncLoadingCache(Generic[T]): | ||
| """A cache that loads values asynchronously on cache miss, | ||
| with optional validation of cached entries. | ||
|
|
||
| Concurrent requests for the same key are deduplicated: only one | ||
| load runs while other callers await its result. | ||
| """ | ||
|
|
||
| def __init__(self) -> None: | ||
| self._cache: dict[str, asyncio.Future[T]] = {} | ||
|
|
||
| async def get( | ||
| self, | ||
| key: str, | ||
| loader: Callable[[], Awaitable[T]], | ||
| validator: Callable[[T], bool] | None = None, | ||
| ) -> T: | ||
| if key in self._cache: | ||
| value = await self._cache[key] | ||
| if validator is None or validator(value): | ||
| return value | ||
| self._cache.pop(key, None) | ||
|
|
||
| self._cache[key] = asyncio.ensure_future(loader()) | ||
| try: | ||
| return await self._cache[key] | ||
| except BaseException: # includes CancelledError to avoid caching canceled futures | ||
| self._cache.pop(key, None) | ||
| raise | ||
|
|
||
| def remove(self, key: str) -> None: | ||
| self._cache.pop(key, None) | ||
|
|
||
| def clear(self) -> None: | ||
| self._cache.clear() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,115 @@ | ||
| """Unit tests for the AsyncLoadingCache utility class.""" | ||
|
|
||
| import asyncio | ||
| from unittest.mock import AsyncMock | ||
|
|
||
| import pytest | ||
|
|
||
| from statgpt.common.utils.async_loading_cache import AsyncLoadingCache | ||
|
|
||
|
|
||
| class TestAsyncLoadingCacheGet: | ||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_get_loads_on_miss(self) -> None: | ||
| cache: AsyncLoadingCache[str] = AsyncLoadingCache() | ||
| loader = AsyncMock(return_value="value") | ||
|
|
||
| result = await cache.get("k", loader) | ||
|
|
||
| assert result == "value" | ||
| loader.assert_awaited_once() | ||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_get_returns_cached_on_hit(self) -> None: | ||
| cache: AsyncLoadingCache[str] = AsyncLoadingCache() | ||
| loader = AsyncMock(return_value="value") | ||
|
|
||
| await cache.get("k", loader) | ||
| result = await cache.get("k", loader) | ||
|
|
||
| assert result == "value" | ||
| loader.assert_awaited_once() | ||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_get_reloads_when_validator_fails(self) -> None: | ||
| cache: AsyncLoadingCache[str] = AsyncLoadingCache() | ||
| loader = AsyncMock(side_effect=["old", "new"]) | ||
|
|
||
| await cache.get("k", loader) | ||
| result = await cache.get("k", loader, validator=lambda v: v == "new") | ||
|
|
||
| assert result == "new" | ||
| assert loader.await_count == 2 | ||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_get_without_validator_always_hits(self) -> None: | ||
| cache: AsyncLoadingCache[str] = AsyncLoadingCache() | ||
| loader = AsyncMock(return_value="value") | ||
|
|
||
| await cache.get("k", loader) | ||
| result = await cache.get("k", loader) | ||
|
|
||
| assert result == "value" | ||
| loader.assert_awaited_once() | ||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_concurrent_get_deduplicates(self) -> None: | ||
| cache: AsyncLoadingCache[str] = AsyncLoadingCache() | ||
| loader = AsyncMock(return_value="value") | ||
|
|
||
| results = await asyncio.gather( | ||
| cache.get("k", loader), | ||
| cache.get("k", loader), | ||
| ) | ||
|
|
||
| assert results == ["value", "value"] | ||
| loader.assert_awaited_once() | ||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_load_failure_not_cached(self) -> None: | ||
| cache: AsyncLoadingCache[str] = AsyncLoadingCache() | ||
| loader = AsyncMock(side_effect=[ValueError("fail"), "value"]) | ||
|
|
||
| with pytest.raises(ValueError, match="fail"): | ||
| await cache.get("k", loader) | ||
|
|
||
| result = await cache.get("k", loader) | ||
| assert result == "value" | ||
| assert loader.await_count == 2 | ||
|
|
||
|
|
||
| class TestAsyncLoadingCacheRemove: | ||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_remove_triggers_reload(self) -> None: | ||
| cache: AsyncLoadingCache[str] = AsyncLoadingCache() | ||
| loader = AsyncMock(side_effect=["first", "second"]) | ||
|
|
||
| await cache.get("k", loader) | ||
| cache.remove("k") | ||
| result = await cache.get("k", loader) | ||
|
|
||
| assert result == "second" | ||
| assert loader.await_count == 2 | ||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_remove_nonexistent_key(self) -> None: | ||
| cache: AsyncLoadingCache[str] = AsyncLoadingCache() | ||
| cache.remove("nonexistent") # should not raise | ||
|
|
||
|
|
||
| class TestAsyncLoadingCacheClear: | ||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_clear_removes_all(self) -> None: | ||
| cache: AsyncLoadingCache[str] = AsyncLoadingCache() | ||
| loader = AsyncMock(side_effect=["a1", "b1", "a2", "b2"]) | ||
|
|
||
| await cache.get("a", loader) | ||
| await cache.get("b", loader) | ||
| cache.clear() | ||
| await cache.get("a", loader) | ||
| await cache.get("b", loader) | ||
|
|
||
| assert loader.await_count == 4 |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This behavior is not correct. If
allow_offline=Trueand any problems occur,get_datasetshould return an OfflineDataset without caching itThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fixed. The loader now receives
allow_offline, so the server is only hit once. If loading fails andallow_offline=True, theSdmxOfflineDataSetis stored in cache but the validator rejects it on the next access — triggering a fresh load in case the upstream recovered.