You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@superset.apache.org by "dpgaspar (via GitHub)" <gi...@apache.org> on 2026/01/22 10:54:03 UTC
[PR] feat(cache): use configurable hash algorithm for flask-caching [superset]
dpgaspar opened a new pull request, #37361:
URL: https://github.com/apache/superset/pull/37361
<!---
Please write the PR title following the conventions at https://www.conventionalcommits.org/en/v1.0.0/
Example:
fix(dashboard): load charts correctly
-->
### SUMMARY
<!--- Describe the change below, including rationale and design decisions -->
### BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF
<!--- Skip this if not applicable -->
### TESTING INSTRUCTIONS
<!--- Required! What steps can be taken to manually verify the changes? -->
### ADDITIONAL INFORMATION
<!--- Check any relevant boxes with "x" -->
<!--- HINT: Include "Fixes #nnn" if you are fixing an existing issue -->
- [ ] Has associated issue:
- [ ] Required feature flags:
- [ ] Changes UI
- [ ] Includes DB Migration (follow approval process in [SIP-59](https://github.com/apache/superset/issues/13351))
- [ ] Migration is atomic, supports rollback & is backwards-compatible
- [ ] Confirm DB migration upgrade and downgrade tested
- [ ] Runtime estimates and downtime expectations provided
- [ ] Introduces new feature or API
- [ ] Removes existing feature or API
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(cache): use configurable hash algorithm for flask-caching [superset]
Posted by "dpgaspar (via GitHub)" <gi...@apache.org>.
dpgaspar commented on code in PR #37361:
URL: https://github.com/apache/superset/pull/37361#discussion_r2720524301
##########
superset/utils/cache_manager.py:
##########
@@ -27,8 +28,129 @@
CACHE_IMPORT_PATH = "superset.extensions.metastore_cache.SupersetMetastoreCache"
+# Hash function lookup table matching superset.utils.hashing
+_HASH_METHODS: dict[str, Callable[..., Any]] = {
+ "sha256": hashlib.sha256,
+ "md5": hashlib.md5,
+}
+
+
+class ConfigurableHashMethod:
+ """
+ A callable that defers hash algorithm selection to runtime.
+
+ Flask-caching's memoize decorator evaluates hash_method at decoration time
+ (module import), but we need to read HASH_ALGORITHM config at function call
+ time when the app context is available.
+
+ This class acts like a hashlib function but looks up the configured
+ algorithm when called.
+ """
+
+ def __call__(self, data: bytes = b"") -> Any:
+ """
+ Create a hash object using the configured algorithm.
+
+ Args:
+ data: Optional initial data to hash
+
+ Returns:
+ A hashlib hash object (e.g., sha256 or md5)
+ """
+ algorithm = current_app.config["HASH_ALGORITHM"]
+ hash_func = _HASH_METHODS[algorithm]
+ return hash_func(data)
+
+
+# Singleton instance to use as default hash_method
+configurable_hash_method = ConfigurableHashMethod()
+
+
+class SupersetCache(Cache):
+ """
+ Cache subclass that uses the configured HASH_ALGORITHM instead of MD5.
+
+ Flask-caching uses MD5 by default for cache key generation, which fails
+ in FIPS mode where MD5 is disabled. This class overrides the default
+ hash method to use the algorithm specified by HASH_ALGORITHM config.
+
+ Note: Switching hash algorithms will invalidate existing cache keys,
+ causing a one-time cache miss on upgrade.
+ """
+
+ def memoize(
+ self,
+ timeout: int | None = None,
+ make_name: Callable[..., Any] | None = None,
+ unless: Callable[..., bool] | None = None,
+ forced_update: Callable[..., bool] | None = None,
+ response_filter: Callable[..., Any] | None = None,
+ hash_method: Callable[..., Any] = configurable_hash_method,
+ cache_none: bool = False,
+ source_check: bool | None = None,
+ args_to_ignore: Any | None = None,
+ ) -> Callable[..., Any]:
+ return super().memoize(
+ timeout=timeout,
+ make_name=make_name,
+ unless=unless,
+ forced_update=forced_update,
+ response_filter=response_filter,
+ hash_method=hash_method,
+ cache_none=cache_none,
+ source_check=source_check,
+ args_to_ignore=args_to_ignore,
+ )
+
+ def cached(
+ self,
+ timeout: int | None = None,
+ key_prefix: str = "view/%s",
+ unless: Callable[..., bool] | None = None,
+ forced_update: Callable[..., bool] | None = None,
+ response_filter: Callable[..., Any] | None = None,
+ query_string: bool = False,
+ hash_method: Callable[..., Any] = configurable_hash_method,
+ cache_none: bool = False,
+ make_cache_key: Callable[..., Any] | None = None,
+ source_check: bool | None = None,
+ response_hit_indication: bool | None = False,
+ ) -> Callable[..., Any]:
+ return super().cached(
+ timeout=timeout,
+ key_prefix=key_prefix,
+ unless=unless,
+ forced_update=forced_update,
+ response_filter=response_filter,
+ query_string=query_string,
+ hash_method=hash_method,
+ cache_none=cache_none,
+ make_cache_key=make_cache_key,
+ source_check=source_check,
+ response_hit_indication=response_hit_indication,
+ )
+
+ # pylint: disable=protected-access
+ def _memoize_make_cache_key(
+ self,
+ make_name: Callable[..., Any] | None = None,
+ timeout: Callable[..., Any] | None = None,
Review Comment:
true it's weird, but this is actually a Callable upstream https://github.com/pallets-eco/flask-caching/blob/master/src/flask_caching/__init__.py#L608
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(cache): use configurable hash algorithm for flask-caching [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #37361:
URL: https://github.com/apache/superset/pull/37361#discussion_r2720819293
##########
superset/utils/cache_manager.py:
##########
@@ -27,8 +28,134 @@
CACHE_IMPORT_PATH = "superset.extensions.metastore_cache.SupersetMetastoreCache"
+# Hash function lookup table matching superset.utils.hashing
+_HASH_METHODS: dict[str, Callable[..., Any]] = {
+ "sha256": hashlib.sha256,
+ "md5": hashlib.md5,
+}
+
+
+class ConfigurableHashMethod:
+ """
+ A callable that defers hash algorithm selection to runtime.
+
+ Flask-caching's memoize decorator evaluates hash_method at decoration time
+ (module import), but we need to read HASH_ALGORITHM config at function call
+ time when the app context is available.
+
+ This class acts like a hashlib function but looks up the configured
+ algorithm when called.
+ """
+
+ def __call__(self, data: bytes = b"") -> Any:
+ """
+ Create a hash object using the configured algorithm.
+
+ Args:
+ data: Optional initial data to hash
+
+ Returns:
+ A hashlib hash object (e.g., sha256 or md5)
+
+ Raises:
+ ValueError: If HASH_ALGORITHM is set to an unsupported value
+ """
+ algorithm = current_app.config["HASH_ALGORITHM"]
+ hash_func = _HASH_METHODS.get(algorithm)
+ if hash_func is None:
+ raise ValueError(f"Unsupported hash algorithm: {algorithm}")
Review Comment:
<div>
<div id="suggestion">
<div id="issue"><b>Missing test coverage for error case</b></div>
<div id="fix">
The change adds error handling for unsupported hash algorithms, but tests should verify this behavior to prevent regressions. Consider adding a test case that sets an invalid algorithm and checks for ValueError.
</div>
</div>
<small><i>Code Review Run #3323b0</i></small>
</div>
---
Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
- [ ] Yes, avoid them
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(cache): use configurable hash algorithm for flask-caching [superset]
Posted by "Vitor-Avila (via GitHub)" <gi...@apache.org>.
Vitor-Avila commented on code in PR #37361:
URL: https://github.com/apache/superset/pull/37361#discussion_r2728012229
##########
superset/utils/cache_manager.py:
##########
@@ -27,8 +28,134 @@
CACHE_IMPORT_PATH = "superset.extensions.metastore_cache.SupersetMetastoreCache"
+# Hash function lookup table matching superset.utils.hashing
+_HASH_METHODS: dict[str, Callable[..., Any]] = {
+ "sha256": hashlib.sha256,
+ "md5": hashlib.md5,
+}
+
+
+class ConfigurableHashMethod:
+ """
+ A callable that defers hash algorithm selection to runtime.
+
+ Flask-caching's memoize decorator evaluates hash_method at decoration time
+ (module import), but we need to read HASH_ALGORITHM config at function call
+ time when the app context is available.
+
+ This class acts like a hashlib function but looks up the configured
+ algorithm when called.
+ """
+
+ def __call__(self, data: bytes = b"") -> Any:
+ """
+ Create a hash object using the configured algorithm.
+
+ Args:
+ data: Optional initial data to hash
+
+ Returns:
+ A hashlib hash object (e.g., sha256 or md5)
+
+ Raises:
+ ValueError: If HASH_ALGORITHM is set to an unsupported value
+ """
+ algorithm = current_app.config["HASH_ALGORITHM"]
Review Comment:
If I got this correctly, users need to have a `HASH_ALGORITHM` defined in `superset_config.py` or else this will raise, right?
I'm thinking we either need to add a mention to `UPDATING.md` that users need to define a value, or even better you could add `HASH_ALGORITHM` to the `config.py` with the default value set to `md5` (to make sure existing cache keys would still match). What do you think?
##########
superset/utils/cache_manager.py:
##########
@@ -27,8 +28,134 @@
CACHE_IMPORT_PATH = "superset.extensions.metastore_cache.SupersetMetastoreCache"
+# Hash function lookup table matching superset.utils.hashing
+_HASH_METHODS: dict[str, Callable[..., Any]] = {
+ "sha256": hashlib.sha256,
+ "md5": hashlib.md5,
+}
Review Comment:
If you think my other comment makes sense and you end up working on a new commit, might make sense to call this `_SUPPORTED_HASH_METHODS`, what do you think?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(cache): use configurable hash algorithm for flask-caching [superset]
Posted by "Vitor-Avila (via GitHub)" <gi...@apache.org>.
Vitor-Avila commented on code in PR #37361:
URL: https://github.com/apache/superset/pull/37361#discussion_r2728233600
##########
superset/utils/cache_manager.py:
##########
@@ -27,8 +28,134 @@
CACHE_IMPORT_PATH = "superset.extensions.metastore_cache.SupersetMetastoreCache"
+# Hash function lookup table matching superset.utils.hashing
+_HASH_METHODS: dict[str, Callable[..., Any]] = {
+ "sha256": hashlib.sha256,
+ "md5": hashlib.md5,
+}
+
+
+class ConfigurableHashMethod:
+ """
+ A callable that defers hash algorithm selection to runtime.
+
+ Flask-caching's memoize decorator evaluates hash_method at decoration time
+ (module import), but we need to read HASH_ALGORITHM config at function call
+ time when the app context is available.
+
+ This class acts like a hashlib function but looks up the configured
+ algorithm when called.
+ """
+
+ def __call__(self, data: bytes = b"") -> Any:
+ """
+ Create a hash object using the configured algorithm.
+
+ Args:
+ data: Optional initial data to hash
+
+ Returns:
+ A hashlib hash object (e.g., sha256 or md5)
+
+ Raises:
+ ValueError: If HASH_ALGORITHM is set to an unsupported value
+ """
+ algorithm = current_app.config["HASH_ALGORITHM"]
Review Comment:
ooof, should have checked the `config.py` file first. Sorry, my bad
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(cache): use configurable hash algorithm for flask-caching [superset]
Posted by "netlify[bot] (via GitHub)" <gi...@apache.org>.
netlify[bot] commented on PR #37361:
URL: https://github.com/apache/superset/pull/37361#issuecomment-3789465450
### <span aria-hidden="true">β
</span> Deploy Preview for *superset-docs-preview* ready!
| Name | Link |
|:-:|------------------------|
|<span aria-hidden="true">π¨</span> Latest commit | 1c208fd5c6dfc4091604184e48b02126d5ea6121 |
|<span aria-hidden="true">π</span> Latest deploy log | https://app.netlify.com/projects/superset-docs-preview/deploys/697346e89a0078000800719f |
|<span aria-hidden="true">π</span> Deploy Preview | [https://deploy-preview-37361--superset-docs-preview.netlify.app](https://deploy-preview-37361--superset-docs-preview.netlify.app) |
|<span aria-hidden="true">π±</span> Preview on mobile | <details><summary> Toggle QR Code... </summary><br /><br /><br /><br />_Use your smartphone camera to open QR code link._</details> |
---
<!-- [superset-docs-preview Preview](https://deploy-preview-37361--superset-docs-preview.netlify.app) -->
_To edit notification comments on pull requests, go to your [Netlify project configuration](https://app.netlify.com/projects/superset-docs-preview/configuration/notifications#deploy-notifications)._
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(cache): use configurable hash algorithm for flask-caching [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #37361:
URL: https://github.com/apache/superset/pull/37361#issuecomment-3788457111
<!-- Bito Reply -->
The suggestion replaces direct dictionary access with .get() and checks for None, raising a descriptive ValueError instead of a bare KeyError. Applying it improves error handling and matches the pattern in hashing.py, making the code more robust and user-friendly.
**superset/utils/cache_manager.py**
```
algorithm = current_app.config["HASH_ALGORITHM"]
hash_func = _HASH_METHODS.get(algorithm)
if hash_func is None:
raise ValueError(f"Unsupported hash algorithm: {algorithm}")
return hash_func(data)
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(cache): use configurable hash algorithm for flask-caching [superset]
Posted by "dpgaspar (via GitHub)" <gi...@apache.org>.
dpgaspar commented on code in PR #37361:
URL: https://github.com/apache/superset/pull/37361#discussion_r2720539640
##########
superset/utils/cache_manager.py:
##########
@@ -27,8 +28,129 @@
CACHE_IMPORT_PATH = "superset.extensions.metastore_cache.SupersetMetastoreCache"
+# Hash function lookup table matching superset.utils.hashing
+_HASH_METHODS: dict[str, Callable[..., Any]] = {
+ "sha256": hashlib.sha256,
+ "md5": hashlib.md5,
+}
+
+
+class ConfigurableHashMethod:
+ """
+ A callable that defers hash algorithm selection to runtime.
+
+ Flask-caching's memoize decorator evaluates hash_method at decoration time
+ (module import), but we need to read HASH_ALGORITHM config at function call
+ time when the app context is available.
+
+ This class acts like a hashlib function but looks up the configured
+ algorithm when called.
+ """
+
+ def __call__(self, data: bytes = b"") -> Any:
+ """
+ Create a hash object using the configured algorithm.
+
+ Args:
+ data: Optional initial data to hash
+
+ Returns:
+ A hashlib hash object (e.g., sha256 or md5)
+ """
+ algorithm = current_app.config["HASH_ALGORITHM"]
+ hash_func = _HASH_METHODS[algorithm]
+ return hash_func(data)
Review Comment:
Good point, updated
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(cache): use configurable hash algorithm for flask-caching [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #37361:
URL: https://github.com/apache/superset/pull/37361#discussion_r2719731138
##########
superset/utils/cache_manager.py:
##########
@@ -27,8 +28,129 @@
CACHE_IMPORT_PATH = "superset.extensions.metastore_cache.SupersetMetastoreCache"
+# Hash function lookup table matching superset.utils.hashing
+_HASH_METHODS: dict[str, Callable[..., Any]] = {
+ "sha256": hashlib.sha256,
+ "md5": hashlib.md5,
+}
+
+
+class ConfigurableHashMethod:
+ """
+ A callable that defers hash algorithm selection to runtime.
+
+ Flask-caching's memoize decorator evaluates hash_method at decoration time
+ (module import), but we need to read HASH_ALGORITHM config at function call
+ time when the app context is available.
+
+ This class acts like a hashlib function but looks up the configured
+ algorithm when called.
+ """
+
+ def __call__(self, data: bytes = b"") -> Any:
+ """
+ Create a hash object using the configured algorithm.
+
+ Args:
+ data: Optional initial data to hash
+
+ Returns:
+ A hashlib hash object (e.g., sha256 or md5)
+ """
+ algorithm = current_app.config["HASH_ALGORITHM"]
+ hash_func = _HASH_METHODS[algorithm]
+ return hash_func(data)
+
+
+# Singleton instance to use as default hash_method
+configurable_hash_method = ConfigurableHashMethod()
+
+
+class SupersetCache(Cache):
+ """
+ Cache subclass that uses the configured HASH_ALGORITHM instead of MD5.
+
+ Flask-caching uses MD5 by default for cache key generation, which fails
+ in FIPS mode where MD5 is disabled. This class overrides the default
+ hash method to use the algorithm specified by HASH_ALGORITHM config.
+
+ Note: Switching hash algorithms will invalidate existing cache keys,
+ causing a one-time cache miss on upgrade.
+ """
+
+ def memoize(
+ self,
+ timeout: int | None = None,
+ make_name: Callable[..., Any] | None = None,
+ unless: Callable[..., bool] | None = None,
+ forced_update: Callable[..., bool] | None = None,
+ response_filter: Callable[..., Any] | None = None,
+ hash_method: Callable[..., Any] = configurable_hash_method,
+ cache_none: bool = False,
+ source_check: bool | None = None,
+ args_to_ignore: Any | None = None,
+ ) -> Callable[..., Any]:
+ return super().memoize(
+ timeout=timeout,
+ make_name=make_name,
+ unless=unless,
+ forced_update=forced_update,
+ response_filter=response_filter,
+ hash_method=hash_method,
+ cache_none=cache_none,
+ source_check=source_check,
+ args_to_ignore=args_to_ignore,
+ )
+
+ def cached(
+ self,
+ timeout: int | None = None,
+ key_prefix: str = "view/%s",
+ unless: Callable[..., bool] | None = None,
+ forced_update: Callable[..., bool] | None = None,
+ response_filter: Callable[..., Any] | None = None,
+ query_string: bool = False,
+ hash_method: Callable[..., Any] = configurable_hash_method,
+ cache_none: bool = False,
+ make_cache_key: Callable[..., Any] | None = None,
+ source_check: bool | None = None,
+ response_hit_indication: bool | None = False,
+ ) -> Callable[..., Any]:
+ return super().cached(
+ timeout=timeout,
+ key_prefix=key_prefix,
+ unless=unless,
+ forced_update=forced_update,
+ response_filter=response_filter,
+ query_string=query_string,
+ hash_method=hash_method,
+ cache_none=cache_none,
+ make_cache_key=make_cache_key,
+ source_check=source_check,
+ response_hit_indication=response_hit_indication,
+ )
+
+ # pylint: disable=protected-access
+ def _memoize_make_cache_key(
+ self,
+ make_name: Callable[..., Any] | None = None,
+ timeout: Callable[..., Any] | None = None,
Review Comment:
Im probably wrong but does the type for timeout looks incorrect? β should this be int | None rather than Callable[..., Any] | None?
Same question for forced_update on the next line β in flask-caching's signature this is typically Callable[..., bool] | None, not bool. S
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(cache): use configurable hash algorithm for flask-caching [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #37361:
URL: https://github.com/apache/superset/pull/37361#discussion_r2719728689
##########
superset/utils/cache_manager.py:
##########
@@ -27,8 +28,129 @@
CACHE_IMPORT_PATH = "superset.extensions.metastore_cache.SupersetMetastoreCache"
+# Hash function lookup table matching superset.utils.hashing
+_HASH_METHODS: dict[str, Callable[..., Any]] = {
+ "sha256": hashlib.sha256,
+ "md5": hashlib.md5,
+}
+
+
+class ConfigurableHashMethod:
+ """
+ A callable that defers hash algorithm selection to runtime.
+
+ Flask-caching's memoize decorator evaluates hash_method at decoration time
+ (module import), but we need to read HASH_ALGORITHM config at function call
+ time when the app context is available.
+
+ This class acts like a hashlib function but looks up the configured
+ algorithm when called.
+ """
+
+ def __call__(self, data: bytes = b"") -> Any:
+ """
+ Create a hash object using the configured algorithm.
+
+ Args:
+ data: Optional initial data to hash
+
+ Returns:
+ A hashlib hash object (e.g., sha256 or md5)
+ """
+ algorithm = current_app.config["HASH_ALGORITHM"]
+ hash_func = _HASH_METHODS[algorithm]
+ return hash_func(data)
Review Comment:
This will raise a bare KeyError if HASH_ALGORITHM is set to an unsupported value. Consider matching the pattern in hashing.py which uses .get() and raises a ValueError with a descriptive message:
```
algorithm = current_app.config["HASH_ALGORITHM"]
hash_func = _HASH_METHODS.get(algorithm)
if hash_func is None:
raise ValueError(f"Unsupported hash algorithm: {algorithm}")
return hash_func(data)
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(cache): use configurable hash algorithm for flask-caching [superset]
Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #37361:
URL: https://github.com/apache/superset/pull/37361#discussion_r2720552237
##########
tests/unit_tests/utils/test_cache_manager.py:
##########
@@ -0,0 +1,171 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+import hashlib
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from superset.utils.cache_manager import (
+ configurable_hash_method,
+ ConfigurableHashMethod,
+ SupersetCache,
+)
+
+
+def test_configurable_hash_method_uses_sha256():
+ """Test ConfigurableHashMethod uses sha256 when configured."""
+ mock_app = MagicMock()
+ mock_app.config = {"HASH_ALGORITHM": "sha256"}
+
+ with patch("superset.utils.cache_manager.current_app", mock_app):
+ hash_obj = configurable_hash_method(b"test")
+ # Verify it returns a sha256 hash object
+ assert hash_obj.hexdigest() == hashlib.sha256(b"test").hexdigest()
+
+
+def test_configurable_hash_method_uses_md5():
+ """Test ConfigurableHashMethod uses md5 when configured."""
+ mock_app = MagicMock()
+ mock_app.config = {"HASH_ALGORITHM": "md5"}
+
+ with patch("superset.utils.cache_manager.current_app", mock_app):
+ hash_obj = configurable_hash_method(b"test")
+ # Verify it returns a md5 hash object
+ assert hash_obj.hexdigest() == hashlib.md5(b"test").hexdigest() # noqa: S324
+
+
+def test_configurable_hash_method_empty_data():
+ """Test ConfigurableHashMethod with empty data."""
+ mock_app = MagicMock()
+ mock_app.config = {"HASH_ALGORITHM": "sha256"}
+
+ with patch("superset.utils.cache_manager.current_app", mock_app):
+ hash_obj = configurable_hash_method()
+ assert hash_obj.hexdigest() == hashlib.sha256(b"").hexdigest()
+
+
+def test_configurable_hash_method_is_callable():
+ """Test that ConfigurableHashMethod instance is callable."""
+ method = ConfigurableHashMethod()
+ assert callable(method)
+
+
+def test_superset_cache_memoize_uses_configurable_hash():
+ """Test that SupersetCache.memoize uses configurable_hash_method by default."""
+ cache = SupersetCache()
+
+ with patch.object(
+ cache.__class__.__bases__[0], "memoize", return_value=lambda f: f
+ ) as mock_memoize:
+ cache.memoize(timeout=300)
+
+ mock_memoize.assert_called_once()
+ call_kwargs = mock_memoize.call_args[1]
+ assert call_kwargs["hash_method"] is configurable_hash_method
+
+
+def test_superset_cache_memoize_allows_explicit_hash_method():
+ """Test that SupersetCache.memoize allows explicit hash_method override."""
+ cache = SupersetCache()
+
+ with patch.object(
+ cache.__class__.__bases__[0], "memoize", return_value=lambda f: f
+ ) as mock_memoize:
+ cache.memoize(timeout=300, hash_method=hashlib.md5)
+
+ mock_memoize.assert_called_once()
+ call_kwargs = mock_memoize.call_args[1]
+ assert call_kwargs["hash_method"] == hashlib.md5
+
+
+def test_superset_cache_cached_uses_configurable_hash():
+ """Test that SupersetCache.cached uses configurable_hash_method by default."""
+ cache = SupersetCache()
+
+ with patch.object(
+ cache.__class__.__bases__[0], "cached", return_value=lambda f: f
+ ) as mock_cached:
+ cache.cached(timeout=300)
+
+ mock_cached.assert_called_once()
+ call_kwargs = mock_cached.call_args[1]
+ assert call_kwargs["hash_method"] is configurable_hash_method
+
+
+def test_superset_cache_cached_allows_explicit_hash_method():
+ """Test that SupersetCache.cached allows explicit hash_method override."""
+ cache = SupersetCache()
+
+ with patch.object(
+ cache.__class__.__bases__[0], "cached", return_value=lambda f: f
+ ) as mock_cached:
+ cache.cached(timeout=300, hash_method=hashlib.md5)
+
+ mock_cached.assert_called_once()
+ call_kwargs = mock_cached.call_args[1]
+ assert call_kwargs["hash_method"] == hashlib.md5
+
+
+def test_superset_cache_memoize_make_cache_key_uses_configurable_hash():
+ """Test _memoize_make_cache_key uses configurable_hash_method by default."""
+ cache = SupersetCache()
+
+ with patch.object(
+ cache.__class__.__bases__[0],
+ "_memoize_make_cache_key",
+ return_value=lambda *args, **kwargs: "cache_key",
+ ) as mock_make_key:
+ cache._memoize_make_cache_key(make_name=None, timeout=300)
+
+ mock_make_key.assert_called_once()
+ call_kwargs = mock_make_key.call_args[1]
+ assert call_kwargs["hash_method"] is configurable_hash_method
+
+
+def test_superset_cache_memoize_make_cache_key_allows_explicit_hash():
+ """Test _memoize_make_cache_key allows explicit hash_method override."""
+ cache = SupersetCache()
+
+ with patch.object(
+ cache.__class__.__bases__[0],
+ "_memoize_make_cache_key",
+ return_value=lambda *args, **kwargs: "cache_key",
+ ) as mock_make_key:
+ cache._memoize_make_cache_key(
+ make_name=None, timeout=300, hash_method=hashlib.md5
+ )
+
+ mock_make_key.assert_called_once()
+ call_kwargs = mock_make_key.call_args[1]
+ assert call_kwargs["hash_method"] == hashlib.md5
+
+
+@pytest.mark.parametrize(
+ "algorithm,expected_digest",
+ [
+ ("sha256", hashlib.sha256(b"test_data").hexdigest()),
+ ("md5", hashlib.md5(b"test_data").hexdigest()), # noqa: S324
+ ],
+)
+def test_configurable_hash_method_parametrized(algorithm, expected_digest):
+ """Parametrized test for ConfigurableHashMethod with different algorithms."""
+ mock_app = MagicMock()
+ mock_app.config = {"HASH_ALGORITHM": algorithm}
+
+ with patch("superset.utils.cache_manager.current_app", mock_app):
+ hash_obj = configurable_hash_method(b"test_data")
+ assert hash_obj.hexdigest() == expected_digest
Review Comment:
**Suggestion:** Parametrized test uses `hashlib.md5(...)` to compute an expected digest value, which also calls MD5 at runtime and will fail under FIPS. Change the parametrization to avoid calling MD5 (for example assert hexdigest length for MD5) and make the assertion based on digest length rather than computing MD5 directly. [possible bug]
<details>
<summary><b>Severity Level:</b> Critical π¨</summary>
```mdx
- β Test collection fails in FIPS-enabled environments.
- β οΈ CI pipeline test stage blocked by import error.
- β οΈ Prevents verification of cache HASH_ALGORITHM behavior.
```
</details>
```suggestion
"algorithm,expected_length",
[
("sha256", len(hashlib.sha256(b"test_data").hexdigest())),
("md5", 32), # md5 hexdigest length is 32; avoid constructing md5 in FIPS mode
],
)
def test_configurable_hash_method_parametrized(algorithm, expected_length):
"""Parametrized test for ConfigurableHashMethod with different algorithms."""
mock_app = MagicMock()
mock_app.config = {"HASH_ALGORITHM": algorithm}
with patch("superset.utils.cache_manager.current_app", mock_app):
hash_obj = configurable_hash_method(b"test_data")
assert isinstance(hash_obj.hexdigest(), str)
assert len(hash_obj.hexdigest()) == expected_length
```
<details>
<summary><b>Steps of Reproduction β
</b></summary>
```mdx
1. Run `pytest tests/unit_tests/utils/test_cache_manager.py -q`.
2. Pytest imports the test module; at import time it evaluates the
`@pytest.mark.parametrize(...)` decorator at lines 157-163.
3. Evaluation of the parametrization constructs `hashlib.md5(b"test_data").hexdigest()` at
line 161 during import.
4. In a FIPS-enabled environment constructing `hashlib.md5()` can raise an exception,
causing the test module import to fail before tests run.
5. Observed behavior: pytest fails quickly with an exception during test
collection/import, blocking the test run.
```
</details>
<details>
<summary><b>Prompt for AI Agent π€ </b></summary>
```mdx
This is a comment left during a code review.
**Path:** tests/unit_tests/utils/test_cache_manager.py
**Line:** 158:171
**Comment:**
*Possible Bug: Parametrized test uses `hashlib.md5(...)` to compute an expected digest value, which also calls MD5 at runtime and will fail under FIPS. Change the parametrization to avoid calling MD5 (for example assert hexdigest length for MD5) and make the assertion based on digest length rather than computing MD5 directly.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
```
</details>
##########
superset/utils/cache_manager.py:
##########
@@ -27,8 +28,134 @@
CACHE_IMPORT_PATH = "superset.extensions.metastore_cache.SupersetMetastoreCache"
+# Hash function lookup table matching superset.utils.hashing
+_HASH_METHODS: dict[str, Callable[..., Any]] = {
+ "sha256": hashlib.sha256,
+ "md5": hashlib.md5,
+}
+
+
+class ConfigurableHashMethod:
+ """
+ A callable that defers hash algorithm selection to runtime.
+
+ Flask-caching's memoize decorator evaluates hash_method at decoration time
+ (module import), but we need to read HASH_ALGORITHM config at function call
+ time when the app context is available.
+
+ This class acts like a hashlib function but looks up the configured
+ algorithm when called.
+ """
+
+ def __call__(self, data: bytes = b"") -> Any:
+ """
+ Create a hash object using the configured algorithm.
+
+ Args:
+ data: Optional initial data to hash
+
+ Returns:
+ A hashlib hash object (e.g., sha256 or md5)
+
+ Raises:
+ ValueError: If HASH_ALGORITHM is set to an unsupported value
+ """
+ algorithm = current_app.config["HASH_ALGORITHM"]
Review Comment:
**Suggestion:** Accessing `current_app.config["HASH_ALGORITHM"]` will raise a KeyError if the config key is missing and is case-sensitive; normalize and provide a safe default (e.g., "sha256") to avoid runtime KeyError and mismatches from different casings. [possible bug]
<details>
<summary><b>Severity Level:</b> Critical π¨</summary>
```mdx
- β Cache key generation raises KeyError on missing config.
- β οΈ Any memoize/cached decorator may error during requests.
- β οΈ Affects SupersetCache.memoize and .cached wrappers.
```
</details>
```suggestion
algorithm = current_app.config.get("HASH_ALGORITHM", "sha256")
algorithm = str(algorithm).lower()
```
<details>
<summary><b>Steps of Reproduction β
</b></summary>
```mdx
1. Start the Superset Flask app or run the cache manager unit tests (see PR testing
instructions). The CacheManager class constructs SupersetCache instances at
`superset/utils/cache_manager.py:179-186` and exposes them via properties.
2. Any code using the SupersetCache.memoize wrapper will default its hash_method to the
singleton `configurable_hash_method` defined in this file
(`superset/utils/cache_manager.py`); see `SupersetCache.memoize` signature at
`superset/utils/cache_manager.py:86-108` where `hash_method=configurable_hash_method`.
3. When a memoized function is invoked, Flask-Caching will call the provided hash_method
which dispatches to `ConfigurableHashMethod.__call__` implemented at
`superset/utils/cache_manager.py:63-67`. That method currently does direct indexing into
the Flask config with `current_app.config["HASH_ALGORITHM"]`.
4. If the running Flask app configuration does not include the "HASH_ALGORITHM" key (e.g.,
misconfiguration, minimal test app, or environment where the default isn't set), the
direct indexing at `superset/utils/cache_manager.py:63` raises a KeyError, causing the
request or memoized call to error out. The improved code uses `.get(..., "sha256")` and
normalizes casing to avoid this KeyError and mismatches.
```
</details>
<details>
<summary><b>Prompt for AI Agent π€ </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset/utils/cache_manager.py
**Line:** 63:63
**Comment:**
*Possible Bug: Accessing `current_app.config["HASH_ALGORITHM"]` will raise a KeyError if the config key is missing and is case-sensitive; normalize and provide a safe default (e.g., "sha256") to avoid runtime KeyError and mismatches from different casings.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
```
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(cache): use configurable hash algorithm for flask-caching [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe merged PR #37361:
URL: https://github.com/apache/superset/pull/37361
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(cache): use configurable hash algorithm for flask-caching [superset]
Posted by "dpgaspar (via GitHub)" <gi...@apache.org>.
dpgaspar commented on code in PR #37361:
URL: https://github.com/apache/superset/pull/37361#discussion_r2728109581
##########
superset/utils/cache_manager.py:
##########
@@ -27,8 +28,134 @@
CACHE_IMPORT_PATH = "superset.extensions.metastore_cache.SupersetMetastoreCache"
+# Hash function lookup table matching superset.utils.hashing
+_HASH_METHODS: dict[str, Callable[..., Any]] = {
+ "sha256": hashlib.sha256,
+ "md5": hashlib.md5,
+}
+
+
+class ConfigurableHashMethod:
+ """
+ A callable that defers hash algorithm selection to runtime.
+
+ Flask-caching's memoize decorator evaluates hash_method at decoration time
+ (module import), but we need to read HASH_ALGORITHM config at function call
+ time when the app context is available.
+
+ This class acts like a hashlib function but looks up the configured
+ algorithm when called.
+ """
+
+ def __call__(self, data: bytes = b"") -> Any:
+ """
+ Create a hash object using the configured algorithm.
+
+ Args:
+ data: Optional initial data to hash
+
+ Returns:
+ A hashlib hash object (e.g., sha256 or md5)
+
+ Raises:
+ ValueError: If HASH_ALGORITHM is set to an unsupported value
+ """
+ algorithm = current_app.config["HASH_ALGORITHM"]
Review Comment:
it's already there, was introduced on this PR: https://github.com/apache/superset/pull/35621
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(cache): use configurable hash algorithm for flask-caching [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #37361:
URL: https://github.com/apache/superset/pull/37361#issuecomment-3783764094
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(cache): use configurable hash algorithm for flask-caching [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #37361:
URL: https://github.com/apache/superset/pull/37361#discussion_r2719731138
##########
superset/utils/cache_manager.py:
##########
@@ -27,8 +28,129 @@
CACHE_IMPORT_PATH = "superset.extensions.metastore_cache.SupersetMetastoreCache"
+# Hash function lookup table matching superset.utils.hashing
+_HASH_METHODS: dict[str, Callable[..., Any]] = {
+ "sha256": hashlib.sha256,
+ "md5": hashlib.md5,
+}
+
+
+class ConfigurableHashMethod:
+ """
+ A callable that defers hash algorithm selection to runtime.
+
+ Flask-caching's memoize decorator evaluates hash_method at decoration time
+ (module import), but we need to read HASH_ALGORITHM config at function call
+ time when the app context is available.
+
+ This class acts like a hashlib function but looks up the configured
+ algorithm when called.
+ """
+
+ def __call__(self, data: bytes = b"") -> Any:
+ """
+ Create a hash object using the configured algorithm.
+
+ Args:
+ data: Optional initial data to hash
+
+ Returns:
+ A hashlib hash object (e.g., sha256 or md5)
+ """
+ algorithm = current_app.config["HASH_ALGORITHM"]
+ hash_func = _HASH_METHODS[algorithm]
+ return hash_func(data)
+
+
+# Singleton instance to use as default hash_method
+configurable_hash_method = ConfigurableHashMethod()
+
+
+class SupersetCache(Cache):
+ """
+ Cache subclass that uses the configured HASH_ALGORITHM instead of MD5.
+
+ Flask-caching uses MD5 by default for cache key generation, which fails
+ in FIPS mode where MD5 is disabled. This class overrides the default
+ hash method to use the algorithm specified by HASH_ALGORITHM config.
+
+ Note: Switching hash algorithms will invalidate existing cache keys,
+ causing a one-time cache miss on upgrade.
+ """
+
+ def memoize(
+ self,
+ timeout: int | None = None,
+ make_name: Callable[..., Any] | None = None,
+ unless: Callable[..., bool] | None = None,
+ forced_update: Callable[..., bool] | None = None,
+ response_filter: Callable[..., Any] | None = None,
+ hash_method: Callable[..., Any] = configurable_hash_method,
+ cache_none: bool = False,
+ source_check: bool | None = None,
+ args_to_ignore: Any | None = None,
+ ) -> Callable[..., Any]:
+ return super().memoize(
+ timeout=timeout,
+ make_name=make_name,
+ unless=unless,
+ forced_update=forced_update,
+ response_filter=response_filter,
+ hash_method=hash_method,
+ cache_none=cache_none,
+ source_check=source_check,
+ args_to_ignore=args_to_ignore,
+ )
+
+ def cached(
+ self,
+ timeout: int | None = None,
+ key_prefix: str = "view/%s",
+ unless: Callable[..., bool] | None = None,
+ forced_update: Callable[..., bool] | None = None,
+ response_filter: Callable[..., Any] | None = None,
+ query_string: bool = False,
+ hash_method: Callable[..., Any] = configurable_hash_method,
+ cache_none: bool = False,
+ make_cache_key: Callable[..., Any] | None = None,
+ source_check: bool | None = None,
+ response_hit_indication: bool | None = False,
+ ) -> Callable[..., Any]:
+ return super().cached(
+ timeout=timeout,
+ key_prefix=key_prefix,
+ unless=unless,
+ forced_update=forced_update,
+ response_filter=response_filter,
+ query_string=query_string,
+ hash_method=hash_method,
+ cache_none=cache_none,
+ make_cache_key=make_cache_key,
+ source_check=source_check,
+ response_hit_indication=response_hit_indication,
+ )
+
+ # pylint: disable=protected-access
+ def _memoize_make_cache_key(
+ self,
+ make_name: Callable[..., Any] | None = None,
+ timeout: Callable[..., Any] | None = None,
Review Comment:
The type for timeout looks incorrect β should this be int | None rather than Callable[..., Any] | None? Same question for forced_update on the next line β in flask-caching's signature this is typically Callable[..., bool] | None, not bool. Since these just delegate to super(), the signatures should match upstream exactly.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(cache): use configurable hash algorithm for flask-caching [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #37361:
URL: https://github.com/apache/superset/pull/37361#discussion_r2716978648
##########
tests/unit_tests/utils/test_cache_manager.py:
##########
@@ -0,0 +1,171 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+import hashlib
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from superset.utils.cache_manager import (
+ configurable_hash_method,
+ ConfigurableHashMethod,
+ SupersetCache,
+)
+
+
+def test_configurable_hash_method_uses_sha256():
+ """Test ConfigurableHashMethod uses sha256 when configured."""
+ mock_app = MagicMock()
+ mock_app.config = {"HASH_ALGORITHM": "sha256"}
+
+ with patch("superset.utils.cache_manager.current_app", mock_app):
+ hash_obj = configurable_hash_method(b"test")
+ # Verify it returns a sha256 hash object
+ assert hash_obj.hexdigest() == hashlib.sha256(b"test").hexdigest()
+
+
+def test_configurable_hash_method_uses_md5():
+ """Test ConfigurableHashMethod uses md5 when configured."""
+ mock_app = MagicMock()
+ mock_app.config = {"HASH_ALGORITHM": "md5"}
+
+ with patch("superset.utils.cache_manager.current_app", mock_app):
+ hash_obj = configurable_hash_method(b"test")
+ # Verify it returns a md5 hash object
+ assert hash_obj.hexdigest() == hashlib.md5(b"test").hexdigest() # noqa: S324
+
+
+def test_configurable_hash_method_empty_data():
+ """Test ConfigurableHashMethod with empty data."""
+ mock_app = MagicMock()
+ mock_app.config = {"HASH_ALGORITHM": "sha256"}
+
+ with patch("superset.utils.cache_manager.current_app", mock_app):
+ hash_obj = configurable_hash_method()
+ assert hash_obj.hexdigest() == hashlib.sha256(b"").hexdigest()
+
+
+def test_configurable_hash_method_is_callable():
+ """Test that ConfigurableHashMethod instance is callable."""
+ method = ConfigurableHashMethod()
+ assert callable(method)
+
+
+def test_superset_cache_memoize_uses_configurable_hash():
+ """Test that SupersetCache.memoize uses configurable_hash_method by default."""
+ cache = SupersetCache()
+
+ with patch.object(
+ cache.__class__.__bases__[0], "memoize", return_value=lambda f: f
+ ) as mock_memoize:
+ cache.memoize(timeout=300)
+
+ mock_memoize.assert_called_once()
+ call_kwargs = mock_memoize.call_args[1]
+ assert call_kwargs["hash_method"] is configurable_hash_method
+
+
+def test_superset_cache_memoize_allows_explicit_hash_method():
+ """Test that SupersetCache.memoize allows explicit hash_method override."""
+ cache = SupersetCache()
+
+ with patch.object(
+ cache.__class__.__bases__[0], "memoize", return_value=lambda f: f
+ ) as mock_memoize:
+ cache.memoize(timeout=300, hash_method=hashlib.md5)
+
+ mock_memoize.assert_called_once()
+ call_kwargs = mock_memoize.call_args[1]
+ assert call_kwargs["hash_method"] == hashlib.md5
+
+
+def test_superset_cache_cached_uses_configurable_hash():
+ """Test that SupersetCache.cached uses configurable_hash_method by default."""
+ cache = SupersetCache()
+
+ with patch.object(
+ cache.__class__.__bases__[0], "cached", return_value=lambda f: f
+ ) as mock_cached:
+ cache.cached(timeout=300)
+
+ mock_cached.assert_called_once()
+ call_kwargs = mock_cached.call_args[1]
+ assert call_kwargs["hash_method"] is configurable_hash_method
+
+
+def test_superset_cache_cached_allows_explicit_hash_method():
+ """Test that SupersetCache.cached allows explicit hash_method override."""
+ cache = SupersetCache()
+
+ with patch.object(
+ cache.__class__.__bases__[0], "cached", return_value=lambda f: f
+ ) as mock_cached:
+ cache.cached(timeout=300, hash_method=hashlib.md5)
+
+ mock_cached.assert_called_once()
+ call_kwargs = mock_cached.call_args[1]
+ assert call_kwargs["hash_method"] == hashlib.md5
+
+
+def test_superset_cache_memoize_make_cache_key_uses_configurable_hash():
+ """Test _memoize_make_cache_key uses configurable_hash_method by default."""
+ cache = SupersetCache()
+
+ with patch.object(
+ cache.__class__.__bases__[0],
+ "_memoize_make_cache_key",
+ return_value=lambda *args, **kwargs: "cache_key",
+ ) as mock_make_key:
+ cache._memoize_make_cache_key(make_name=None, timeout=300)
+
+ mock_make_key.assert_called_once()
+ call_kwargs = mock_make_key.call_args[1]
+ assert call_kwargs["hash_method"] is configurable_hash_method
+
+
+def test_superset_cache_memoize_make_cache_key_allows_explicit_hash():
+ """Test _memoize_make_cache_key allows explicit hash_method override."""
+ cache = SupersetCache()
+
+ with patch.object(
+ cache.__class__.__bases__[0],
+ "_memoize_make_cache_key",
+ return_value=lambda *args, **kwargs: "cache_key",
+ ) as mock_make_key:
+ cache._memoize_make_cache_key(
+ make_name=None, timeout=300, hash_method=hashlib.md5
+ )
+
+ mock_make_key.assert_called_once()
+ call_kwargs = mock_make_key.call_args[1]
+ assert call_kwargs["hash_method"] == hashlib.md5
+
+
+@pytest.mark.parametrize(
+ "algorithm,expected_digest",
Review Comment:
<div>
<div id="suggestion">
<div id="issue"><b>Wrong type for pytest parametrize</b></div>
<div id="fix">
Change the first argument of `pytest.mark.parametrize` from a string to a tuple: `("algorithm", "expected_digest")` instead of `"algorithm,expected_digest"`.
</div>
<details>
<summary>
<b>Code suggestion</b>
</summary>
<blockquote>Check the AI-generated fix before applying</blockquote>
<div id="code">
````suggestion
("algorithm", "expected_digest"),
````
</div>
</details>
</div>
<small><i>Code Review Run #3a5c30</i></small>
</div>
---
Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
- [ ] Yes, avoid them
##########
superset/utils/cache.py:
##########
@@ -273,7 +274,7 @@ def wrapper(*args: Any, **kwargs: Any) -> Response: # noqa: C901
wrapper.uncached = f # type: ignore
wrapper.cache_timeout = timeout # type: ignore
wrapper.make_cache_key = cache._memoize_make_cache_key( # type: ignore # pylint: disable=protected-access
Review Comment:
<div>
<div id="suggestion">
<div id="issue"><b>Private member access and blanket type ignore</b></div>
<div id="fix">
Line 276 accesses private method `_memoize_make_cache_key` (SLF001) and uses blanket `# type: ignore` (PGH003). Replace with `# type: ignore[attr-defined,misc]` and consider if private API access is necessary.
</div>
<details>
<summary>
<b>Code suggestion</b>
</summary>
<blockquote>Check the AI-generated fix before applying</blockquote>
<div id="code">
````suggestion
wrapper.make_cache_key = cache._memoize_make_cache_key( # type: ignore[attr-defined,misc] # pylint: disable=protected-access
````
</div>
</details>
</div>
<small><i>Code Review Run #3a5c30</i></small>
</div>
---
Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
- [ ] Yes, avoid them
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(cache): use configurable hash algorithm for flask-caching [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #37361:
URL: https://github.com/apache/superset/pull/37361#issuecomment-3789742415
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers a full AI review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(cache): use configurable hash algorithm for flask-caching [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #37361:
URL: https://github.com/apache/superset/pull/37361#issuecomment-3784450109
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers a full AI review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(cache): use configurable hash algorithm for flask-caching [superset]
Posted by "codecov[bot] (via GitHub)" <gi...@apache.org>.
codecov[bot] commented on PR #37361:
URL: https://github.com/apache/superset/pull/37361#issuecomment-3783870060
## [Codecov](https://app.codecov.io/gh/apache/superset/pull/37361?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
:x: Patch coverage is `95.65217%` with `1 line` in your changes missing coverage. Please review.
:white_check_mark: Project coverage is 66.19%. Comparing base ([`cc972ca`](https://app.codecov.io/gh/apache/superset/commit/cc972cad5ac19328d77662a4e377a10d5a8b2eac?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`f3a31bc`](https://app.codecov.io/gh/apache/superset/commit/f3a31bcff958c10671860f214c328b146faaf832?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
| [Files with missing lines](https://app.codecov.io/gh/apache/superset/pull/37361?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Patch % | Lines |
|---|---|---|
| [superset/utils/cache\_manager.py](https://app.codecov.io/gh/apache/superset/pull/37361?src=pr&el=tree&filepath=superset%2Futils%2Fcache_manager.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvdXRpbHMvY2FjaGVfbWFuYWdlci5weQ==) | 95.45% | [1 Missing :warning: ](https://app.codecov.io/gh/apache/superset/pull/37361?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
<details><summary>Additional details and impacted files</summary>
```diff
@@ Coverage Diff @@
## master #37361 +/- ##
===========================================
+ Coverage 0 66.19% +66.19%
===========================================
Files 0 642 +642
Lines 0 48968 +48968
Branches 0 5481 +5481
===========================================
+ Hits 0 32413 +32413
- Misses 0 15250 +15250
- Partials 0 1305 +1305
```
| [Flag](https://app.codecov.io/gh/apache/superset/pull/37361/flags?src=pr&el=flags&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage Ξ | |
|---|---|---|
| [hive](https://app.codecov.io/gh/apache/superset/pull/37361/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `41.95% <95.65%> (?)` | |
| [presto](https://app.codecov.io/gh/apache/superset/pull/37361/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `41.97% <95.65%> (?)` | |
| [python](https://app.codecov.io/gh/apache/superset/pull/37361/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `66.17% <95.65%> (?)` | |
| [sqlite](https://app.codecov.io/gh/apache/superset/pull/37361/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `64.48% <95.65%> (?)` | |
| [unit](https://app.codecov.io/gh/apache/superset/pull/37361/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `100.00% <ΓΈ> (?)` | |
Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#carryforward-flags-in-the-pull-request-comment) to find out more.
</details>
[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/apache/superset/pull/37361?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
<details><summary> :rocket: New features to boost your workflow: </summary>
- :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
- :package: [JS Bundle Analysis](https://docs.codecov.com/docs/javascript-bundle-analysis): Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(cache): use configurable hash algorithm for flask-caching [superset]
Posted by "dpgaspar (via GitHub)" <gi...@apache.org>.
dpgaspar commented on code in PR #37361:
URL: https://github.com/apache/superset/pull/37361#discussion_r2720524301
##########
superset/utils/cache_manager.py:
##########
@@ -27,8 +28,129 @@
CACHE_IMPORT_PATH = "superset.extensions.metastore_cache.SupersetMetastoreCache"
+# Hash function lookup table matching superset.utils.hashing
+_HASH_METHODS: dict[str, Callable[..., Any]] = {
+ "sha256": hashlib.sha256,
+ "md5": hashlib.md5,
+}
+
+
+class ConfigurableHashMethod:
+ """
+ A callable that defers hash algorithm selection to runtime.
+
+ Flask-caching's memoize decorator evaluates hash_method at decoration time
+ (module import), but we need to read HASH_ALGORITHM config at function call
+ time when the app context is available.
+
+ This class acts like a hashlib function but looks up the configured
+ algorithm when called.
+ """
+
+ def __call__(self, data: bytes = b"") -> Any:
+ """
+ Create a hash object using the configured algorithm.
+
+ Args:
+ data: Optional initial data to hash
+
+ Returns:
+ A hashlib hash object (e.g., sha256 or md5)
+ """
+ algorithm = current_app.config["HASH_ALGORITHM"]
+ hash_func = _HASH_METHODS[algorithm]
+ return hash_func(data)
+
+
+# Singleton instance to use as default hash_method
+configurable_hash_method = ConfigurableHashMethod()
+
+
+class SupersetCache(Cache):
+ """
+ Cache subclass that uses the configured HASH_ALGORITHM instead of MD5.
+
+ Flask-caching uses MD5 by default for cache key generation, which fails
+ in FIPS mode where MD5 is disabled. This class overrides the default
+ hash method to use the algorithm specified by HASH_ALGORITHM config.
+
+ Note: Switching hash algorithms will invalidate existing cache keys,
+ causing a one-time cache miss on upgrade.
+ """
+
+ def memoize(
+ self,
+ timeout: int | None = None,
+ make_name: Callable[..., Any] | None = None,
+ unless: Callable[..., bool] | None = None,
+ forced_update: Callable[..., bool] | None = None,
+ response_filter: Callable[..., Any] | None = None,
+ hash_method: Callable[..., Any] = configurable_hash_method,
+ cache_none: bool = False,
+ source_check: bool | None = None,
+ args_to_ignore: Any | None = None,
+ ) -> Callable[..., Any]:
+ return super().memoize(
+ timeout=timeout,
+ make_name=make_name,
+ unless=unless,
+ forced_update=forced_update,
+ response_filter=response_filter,
+ hash_method=hash_method,
+ cache_none=cache_none,
+ source_check=source_check,
+ args_to_ignore=args_to_ignore,
+ )
+
+ def cached(
+ self,
+ timeout: int | None = None,
+ key_prefix: str = "view/%s",
+ unless: Callable[..., bool] | None = None,
+ forced_update: Callable[..., bool] | None = None,
+ response_filter: Callable[..., Any] | None = None,
+ query_string: bool = False,
+ hash_method: Callable[..., Any] = configurable_hash_method,
+ cache_none: bool = False,
+ make_cache_key: Callable[..., Any] | None = None,
+ source_check: bool | None = None,
+ response_hit_indication: bool | None = False,
+ ) -> Callable[..., Any]:
+ return super().cached(
+ timeout=timeout,
+ key_prefix=key_prefix,
+ unless=unless,
+ forced_update=forced_update,
+ response_filter=response_filter,
+ query_string=query_string,
+ hash_method=hash_method,
+ cache_none=cache_none,
+ make_cache_key=make_cache_key,
+ source_check=source_check,
+ response_hit_indication=response_hit_indication,
+ )
+
+ # pylint: disable=protected-access
+ def _memoize_make_cache_key(
+ self,
+ make_name: Callable[..., Any] | None = None,
+ timeout: Callable[..., Any] | None = None,
Review Comment:
true it's weird, but this is actually a Callable upstream https://github.com/pallets-eco/flask-caching/blob/master/src/flask_caching/__init__.py#L608. So we must use Callable for compatibility
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org