LLM cache keys can return cross-model responses
[x] I checked the documentation and current issues/PRs and did not find this collision reported.
Describe the bug
Cached LLM methods can return one model's response for a different model when both wrappers share a cache backend. _generate_cache_key() includes the function qualified name plus call arguments, but not the bound wrapper's model/provider configuration. Ragas binds the cache decorator to LLM methods at construction time, while the actual output also depends on instance state such as provider, model, model arguments, system prompt, and endpoint configuration.
This is especially risky with DiskCacheBackend or a shared backend across requests/workers: the second model can receive a plausible cached answer and never execute.
Ragas version: current main at 298b68274234c060deacab3cf5fb52aa3a20e885
Python version: 3.12
Code to reproduce
This no-network reproduction loads only the current cache module and mirrors the cached bound-method construction used by the LLM wrappers:
import importlib.util
from pathlib import Path
spec = importlib.util.spec_from_file_location("ragas_cache", Path("src/ragas/cache.py"))
cache_module = importlib.util.module_from_spec(spec)
assert spec.loader is not None
spec.loader.exec_module(cache_module)
class MemoryCache:
def __init__(self):
self.data = {}
def get(self, key):
return self.data[key]
def set(self, key, value):
self.data[key] = value
def has_key(self, key):
return key in self.data
class FakeLLM:
def __init__(self, name, cache):
self.name = name
self.calls = 0
self.generate_text = cache_module.cacher(cache_backend=cache)(self.generate_text)
def generate_text(self, prompt):
self.calls += 1
return f"{self.name}:{prompt}"
backend = MemoryCache()
model_a = FakeLLM("model-a", backend)
model_b = FakeLLM("model-b", backend)
print(model_a.generate_text("same prompt"))
print(model_b.generate_text("same prompt"))
print({"calls": (model_a.calls, model_b.calls), "entries": len(backend.data)})
Actual:
model-a:same prompt
model-a:same prompt
{'calls': (1, 0), 'entries': 1}
Expected: the second result is model-b:same prompt, both models are called once, and the two configurations do not share an entry.
Contract question
I do not think globally hashing self is safe or compatible. tests/unit/test_cache.py deliberately expects equal keys for the same bound method across different objects, and arbitrary client representations can be unstable or contain credentials.
Would the intended fix be an explicit, hashed LLM cache identity/namespace supplied by the wrappers? A useful identity appears to need at least the wrapper class, provider, model, generation arguments, and system prompt. The unresolved part is how endpoint/deployment identity should be normalized across OpenAI-compatible clients without incorporating API keys, userinfo, or raw client representations.
Once that identity contract is confirmed, I can add regressions for different-model misses, same-config cross-instance hits, provider/argument/system-prompt misses, and secret exclusion, then implement the narrow wrapper-level change.
Hey @YusefSyed, i wanted to fix it . Reproduced it on my end too, same broken output.
I took a shot at implementing it but wanted to check the approach with you or the maintainers first, since you raised the identity contract question and I didn't want to just guess and open a PR blind.
What I did: first check a few known attributes that ragas's own LLM/embedding wrappers actually use (model, provider, system_prompt, model_args, etc). But that alone doesn't cover everything, your own FakeLLM repro doesn't have any of those attrs, so I added a fallback that just looks at whatever other plain attributes the object has (strings, numbers, bools, that kind of thing) and pulls those in too, as long as the value isn't some client object or other messy stuff. Also made sure anything with "key", "secret", "token", "password" etc in the name gets skipped no matter what, so credentials can't sneak into the hash.
Had to touch the existing test_cache.py too. The old test literally asserted "keys should match no matter what the instance state is," which is basically the bug written down as a passing test. I split it into two tests instead: same config means same key, different config means different key.
Ran your exact repro script against it. Before the fix:
model-a:same prompt
model-a:same prompt
{'calls': (1, 0), 'entries': 1}
After:
model-a:same prompt
model-b:same prompt
{'calls': (1, 1), 'entries': 2}
model_b actually gets its own response now, two separate cache entries. Tried it against a real DiskCacheBackend too, not just the toy one, and double checked no api keys or client objects leak into the hash anywhere.
Still haven't touched the endpoint/deployment normalization part you mentioned. Figured that one's more of a "what should this even mean" decision for you all rather than something I should just guess at.
Let me know if this direction seems reasonable and I'll open a PR. Happy to adjust if you had something else in mind.
@mohitrai810 The different-model miss is the right regression, but I would avoid the arbitrary-attribute fallback. In the current test_generate_cache_key_bound_method, the varying attribute is named irrelevant, and the method returns only a + b. That test protects a valid generic-cache contract; I would keep it and add wrapper-specific identity tests separately.
Plain attributes can include mutable counters such as FakeLLM.calls, which could change the key after every execution and prevent repeat hits. Filtering attribute names for credential words also cannot guarantee exclusion: a credential can live in a URL, nested generation configuration, or a differently named field. Conversely, max_tokens is output-relevant configuration that a broad token-name filter could discard.
My preference is an explicit wrapper-supplied identity/namespace using deliberately selected configuration, with the generic decorator's default behavior preserved. The fake should supply that identity too. Useful tests include a repeat call on the same instance, equal-config cross-instance hits, and different-model misses. Endpoint/deployment and credential-partition semantics still need a maintainer decision. I have not reviewed your patch, so this is feedback on the described approach rather than approval of its implementation.