Repository navigation
refactor: simplify model credential handling and improve cache management - #8167
Conversation
|
|
||
| get_model_instance_by_model_workspace_id(str(model.id), workspace_id) | ||
|
|
||
| self.assertEqual(received_credentials, [old_credential, new_credential]) |
There was a problem hiding this comment.
Here is an analysis of the provided code, highlighting irregularities, potential issues, and optimization suggestions.
1. Critical Issue: Mocking get_provider incorrectly
Issue: You are patching models_provider.tools.get_provider, but the function name you are importing and calling is get_model_instance_by_model_workspace_id. It is highly unlikely that get_model_instance_by_model_workspace_id calls a function named get_provider directly if it’s not imported or defined in that scope.
- Check the source of
get_model_instance_by_model_workspace_id. Does it actually callget_provider? - If it calls a different function (e.g.,
provider_factory.get_provideror similar), your patch target is wrong. - Suggestion: Read the implementation of
get_model_instance_by_model_workspace_idto confirm the exact function being called inside it. Patch that specific function instead.
2. Potential Issue: Cache Invalidation Logic Not Explicitly Tested
Issue: The test relies on the fact that ModelManage.cache does not cache _UncachedModel instances (because is_cache_model() returns False). However, it's unclear how get_model_instance_by_model_workspace_id interacts with ModelManage.cache.
- Does it check the cache and then decide whether to fetch from DB/provider?
- Does it store results back in the cache?
- Risk: If the caching logic changes or if
_UncachedModelis not properly recognized by the cache manager, this test may give false positives/negatives. - Suggestion: Consider adding a direct assertion on
ModelManage.cachecontent after each call to verify invalidation behavior explicitly, rather than relying solely on side effects captured inreceived_credentials.
3. Code Quality: Unnecessary Mock() Instance
Irregularity: You create a provider = Mock() and set its get_model.side_effect, but you never directly interact with provider besides patching get_provider to return it. This is acceptable, but make sure that the patched path (models_provider.tools.get_provider) is correct (see Point #1).
4. Best Practice: Avoid Patching Internal Connections
Irregularity: patch("models_provider.tools.connection.close") is used to prevent actual database connection closures during tests. While this prevents errors, it’s often better to use Django’s TransactionTestCase or ensure proper transaction rollback in TestCase. Since you're already using TestCase, Django handles DB isolation well. This patch might be unnecessary or indicate deeper coupling issues.
- Suggestion: Test if removing this patch causes failures. If not, remove it for simplicity.
5. Security/Encryption Dependency
Observation: The test uses rsa_long_encrypt for storing credentials. While necessary for realistic testing, ensure that:
- RSA keys are mocked or configured safely in test environments.
- No real private key is used in CI pipelines.
- Use environment variables or test settings to control the RSA configuration.
6. Test Coverage Gaps
- Positive Caching Case: No test verifies that a cached model instance is reused when appropriate.
- Concurrency/Race Condition: The test name says “saved by another process”, but there’s no simulation of concurrent processes. Consider using threading or multiprocessing if true cross-process cache invalidation needs to be verified (though complex in unit tests).
✅ Suggested Improved Structure
def test_runtime_uses_credential_saved_by_another_process(self):
workspace_id = "credential-refresh"
old_creds = {"auth_value": "before-rotation"}
new_creds = {"auth_value": "after-rotation"}
# Create model with encrypted credentials
model = Model.objects.create(
workspace_id=workspace_id,
name="Qwen VL",
model_type="LLM",
model_name="qwen-vl-max",
provider="aliyun_bai_lian_model_provider",
credential=rsa_long_encrypt(json.dumps(old_creds)),
)
seen_credentials = []
# Use a class-based mock for clarity if needed
def dummy_create_model(_type, _name, credential, **kwargs):
seen_credentials.append(credential)
return _UncachedModel()
# ⚠️ CRITICAL: Verify this correct function path exists in get_model_instance_by_model_workspace_id
with (
patch("models_provider.tools.get_provider") as mock_get_provider,
patch("models_provider.tools.connection.close"),
):
mock_provider = Mock()
mock_provider.get_model.side_effect = dummy_create_model
mock_get_provider.return_value = mock_provider
# First call – should load old credential
get_model_instance_by_model_workspace_id(str(model.id), workspace_id)
# Simulate external update (e.g., another API/process)
Model.objects.filter(id=model.id).update(
credential=rsa_long_encrypt(json.dumps(new_creds))
)
# Second call – should detect change and reload
get_model_instance_by_model_workspace_id(str(model.id), workspace_id)
# Assert that both old and new credentials were passed to provider
self.assertEqual(seen_credentials, [old_creds, new_creds])Summary Checklist:
| Item | Status | Action |
|---|---|---|
| Patch target correctness | ❌ Likely Wrong | Audit get_model_instance_by_model_workspace_id internals |
| Cache invalidation verification | Add explicit cache state assertions | |
| Connection mocking | Try removing; use Django test isolation | |
| Test realism | ✅ Good | Ensure RSA config doesn’t break in CI |
| Side-effect capture | ✅ Clear | Keep received_credentials list approach |
Let me know if you want help tracing the actual internal flow of get_model_instance_by_model_workspace_id.
| ModelManage.cache.delete(_id) | ||
|
|
||
|
|
||
| class VectorStore: |
There was a problem hiding this comment.
Based on the provided diff, here is an analysis of the changes:
Summary of Changes
The patch reverts specific caching optimizations for model credentials and rows. It removes:
credential_cache(for decrypted RSA data).model_cache(for raw DB row data).- Helper methods:
get_decrypted_credentialandset_model_row. - Cache invalidation logic in
delete_keyfor these removed caches.
Potential Issues & Observations
-
Performance Regression (High Impact):
- RSA Decryption Overhead: By removing
credential_cache, the code no longer stores decrypted credentials. Ifrsa_long_decryptwas previously being called inside the removed helper or implicitly elsewhere due to missing cache logic, every request requiring a credential will now incur high CPU costs for RSA decryption. - DB Hits: Removing
model_cachelikely forces frequent database queries for model existence or basic attributes if the consumer relies on this class for that lookup.
- RSA Decryption Overhead: By removing
-
Logic Gap / Broken Dependency:
- The removal of imports (
json,rsa_long_decrypt) implies these are no longer used in this file. However, verify that all call sites callingModelManage.get_decrypted_credentialhave been updated to handle decryption themselves or use a different service layer. If any other part of the system expects this method to exist, the application will crash withAttributeError.
- The removal of imports (
-
Simplification vs. Optimization:
- This change simplifies the concurrency and memory management logic (fewer locks/cache invalidations needed). This is acceptable if:
- RSA decryption has been moved to a lower-level middleware or gateway.
- The
MemCacheusage for heavy objects was causing memory leaks or inconsistency issues.
- This change simplifies the concurrency and memory management logic (fewer locks/cache invalidations needed). This is acceptable if:
Recommendations
- Verify Callers: Ensure no other module calls
ModelManage.get_decrypted_credentialorModelManage.model_cache. Search the codebase for these references to prevent runtime errors. - Confirm Decryption Location: Confirm where RSA decryption is now happening. Ensure it is not being done redundantly per-request at a higher layer without appropriate caching elsewhere.
- Monitor Latency/Load: Since this is a revert of optimization, monitor API latency and CPU utilization immediately after deployment to ensure the loss of local caching doesn't degrade performance unacceptably.
Code Cleanliness Post-Patch
- The remaining code appears clean.
_lock,locks, andcacheare still correctly initialized. delete_keyis safely simplified because it only needs to clear one cache now.
| ModelManage.set_model_row(_id, model) | ||
| return model | ||
|
|
||
|
|
There was a problem hiding this comment.
Here is an analysis of the code changes, focusing on security, logic, and optimization.
1. Security & Logic Issue: Credential Decryption Change
Change:
- ModelManage.get_decrypted_credential(model_id, credential),
+ json.loads(rsa_long_decrypt(credential)),Analysis:
- Loss of Contextual Validation: The original call
ModelManage.get_decrypted_credential(model_id, credential)likely included logic to verify that thecredentialactually belongs to themodel_id. The new code blindly decrypts thecredentialstring passed in. If this function is called with a mismatchedmodel_idandcredential, it could lead to using credentials for the wrong model or exposing sensitive data ifrsa_long_decryptis not strictly bound to the specific key set associated with themodel_id. - Error Handling:
json.loadswill throw an exception if the decrypted string is not valid JSON. Ensurersa_long_decryptalways produces valid JSON or wrap this in a try-except block. - Recommendation: Revert to
ModelManage.get_decrypted_credentialunless you have explicitly moved the ownership validation logic elsewhere. If you must do it this way, ensurecredentialis already validated againstmodel_idbefore calling this.
2. Performance Regression: Removal of Caching
Change:
cached = ModelManage.get_model_row(_id)
if cached is not None and cached.workspace_id == workspace_id:
return cachedand
if not authorized:
ModelManage.set_model_row(_id, model)Analysis:
- Increased DB Load: Removing the cache check and the cache population (
set_model_row) forces every call toget_model_by_idto hit the database (QuerySet...filter...first()). The comment explicitly stated this was a "high-frequency path." Removing this cache will likely cause a significant performance degradation under load. - Potential Bug Fix vs. Performance Trade-off: The original code had a potential security flaw:
cached.workspace_id == workspace_id. Ifget_authorized_modelwas used previously, or if the cache was poisoned, this check might be bypassed or insufficient. However, the new approach is safer (always checks via DB orget_authorized_model) but slower. - Connection Leak Risk: The line
connection.close()is called after fetching from the DB but before checking if the model needs to be fetched viaget_authorized_model. Ifget_authorized_modeltriggers another DB query, it might open a new connection or behave unexpectedly depending on Django's connection management. In modern Django (1.6+), manualconnection.close()is rarely needed and can interfere with connection pooling/transactions.
Recommendation:
- Re-introduce caching safely: If you must remove the old cache due to security concerns, introduce a secure cache layer. For example, cache the result of
get_authorized_modelonly if it confirms access, or use an atomic cache read/write with permission checks. - Remove
connection.close(): This is generally unnecessary in Django ORM usage and can cause issues. Let Django handle connection pooling.
3. Code Structure & Readability
Suggested Refactored Code:
import json
def get_model_(provider, model_type, model_name, credential, model_id, use_local,
streaming=True): # Assuming other args exist
model = get_provider(provider).get_model(
model_type,
model_name,
# Ensure credential decryption is secure and tied to model_id
ModelManage.get_decrypted_credential(model_id, credential),
model_id=model_id,
use_local=use_local,
streaming=streaming,
)
return model
def get_model_by_id(_id, workspace_id):
"""
Retrieve model by ID.
Security Note: Always verify ownership via DB or authorized queryset.
Optimization: Use Redis/Memcached for high-frequency reads if necessary,
but ensure keys are scoped by user/workspace permissions.
"""
# Option A: Secure DB Fetch (Current change, safe but slow)
model = QuerySet(Model).filter(id=_id).first()
if model is None or model.workspace_id != workspace_id:
# Fallback to authorized access pattern if cross-workspace sharing is allowed
model = get_authorized_model(QuerySet(Model).filter(id=_id), workspace_id).first()
if model is None:
raise Exception(_("Model does not exist"))
# Optional: Add safe caching here if needed
# e.g., RedisCache.set(f"model:{_id}:ws:{workspace_id}", model.id, ttl=60)
return modelSummary of Issues
| Issue | Severity | Description |
|---|---|---|
| Credential Decryption | High | Bypasses implicit validation of model_id vs credential. Risk of using wrong credentials. |
| Removed DB Cache | Medium | Performance regression on a "high-frequency path". Consider re-adding secure caching. |
Manual connection.close() |
Low | Unnecessary and potentially harmful in Django ORM standard usage. |
Final Recommendation:
Restore ModelManage.get_decrypted_credential for security. Evaluate whether the security reason for removing the cache in get_model_by_id can be addressed without sacrificing all performance (e.g., by caching only after successful authorization verification). Remove connection.close().
refactor: simplify model credential handling and improve cache management