Skip to content

refactor: simplify model credential handling and improve cache management - #8167

Merged
wxg0103 merged 1 commit into
v3from
pr@v3@refactor_model_cache
Nov 26, 2026
Merged

wxg0103 merged 1 commit into
v3from
pr@v3@refactor_model_cache

Conversation

@shaohuzhang1

Copy link
Copy Markdown
Contributor

refactor: simplify model credential handling and improve cache management


get_model_instance_by_model_workspace_id(str(model.id), workspace_id)

self.assertEqual(received_credentials, [old_credential, new_credential])

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 call get_provider?
  • If it calls a different function (e.g., provider_factory.get_provider or similar), your patch target is wrong.
  • Suggestion: Read the implementation of get_model_instance_by_model_workspace_id to 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 _UncachedModel is not properly recognized by the cache manager, this test may give false positives/negatives.
  • Suggestion: Consider adding a direct assertion on ModelManage.cache content after each call to verify invalidation behavior explicitly, rather than relying solely on side effects captured in received_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 ⚠️ Indirect Add explicit cache state assertions
Connection mocking ⚠️ Optional 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:

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. credential_cache (for decrypted RSA data).
  2. model_cache (for raw DB row data).
  3. Helper methods: get_decrypted_credential and set_model_row.
  4. Cache invalidation logic in delete_key for these removed caches.

Potential Issues & Observations

  1. Performance Regression (High Impact):

    • RSA Decryption Overhead: By removing credential_cache, the code no longer stores decrypted credentials. If rsa_long_decrypt was 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_cache likely forces frequent database queries for model existence or basic attributes if the consumer relies on this class for that lookup.
  2. 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 calling ModelManage.get_decrypted_credential have 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 with AttributeError.
  3. 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 MemCache usage for heavy objects was causing memory leaks or inconsistency issues.

Recommendations

  1. Verify Callers: Ensure no other module calls ModelManage.get_decrypted_credential or ModelManage.model_cache. Search the codebase for these references to prevent runtime errors.
  2. 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.
  3. 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, and cache are still correctly initialized.
  • delete_key is safely simplified because it only needs to clear one cache now.

ModelManage.set_model_row(_id, model)
return model


Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 the credential actually belongs to the model_id. The new code blindly decrypts the credential string passed in. If this function is called with a mismatched model_id and credential, it could lead to using credentials for the wrong model or exposing sensitive data if rsa_long_decrypt is not strictly bound to the specific key set associated with the model_id.
  • Error Handling: json.loads will throw an exception if the decrypted string is not valid JSON. Ensure rsa_long_decrypt always produces valid JSON or wrap this in a try-except block.
  • Recommendation: Revert to ModelManage.get_decrypted_credential unless you have explicitly moved the ownership validation logic elsewhere. If you must do it this way, ensure credential is already validated against model_id before 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 cached

and

    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 to get_model_by_id to 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. If get_authorized_model was 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 or get_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 via get_authorized_model. If get_authorized_model triggers another DB query, it might open a new connection or behave unexpectedly depending on Django's connection management. In modern Django (1.6+), manual connection.close() is rarely needed and can interfere with connection pooling/transactions.

Recommendation:

  1. 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_model only if it confirms access, or use an atomic cache read/write with permission checks.
  2. 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 model

Summary 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().

@wxg0103
wxg0103 merged commit 17b0e43 into v3 Nov 26, 2026
3 of 4 checks passed
@wxg0103
wxg0103 deleted the pr@v3@refactor_model_cache branch November 26, 2026 00:54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants