Version AI cache entries by permission and model context
An AI response cache can leak data if it keys only on user text. The same query may be answered under a different tenant, permission set, model version, prompt template or retrieval corpus. Every input that changes permissible evidence or output semantics belongs in cache identity.
The exercise hashes a canonical request envelope and normalizes the set-like scope list. It does not store responses or secrets. Permission revocation needs an invalidation or short-lived authorization boundary even with scoped keys. A correct cache key cannot compensate for evidence that was already retrieved without authorization.
import json
one={"tenant":"a","query":"hello"}
two={"tenant":"b","query":"hello"}
print(json.dumps(one,sort_keys=True)!=json.dumps(two,sort_keys=True))Review the design
A cache identity must include the context that governs reuse. It is not access control or encryption, and cached outputs still require permission checks and an invalidation policy when source permissions change.
Your task
Implement ai_cache_key(tenant,scopes,model,prompt_version,corpus_version,query). Hash compact sorted UTF-8 JSON of those named fields with scopes sorted and deduplicated. Query whitespace is significant.
The explanation opens here once every check passes.