62 / CACHING / PRODUCTION FABRIC
62 / PRODUCTION / REUSE · LATENCY · COST · INVALIDATION

CACHING.

Caching — механизм повторного использования ранее вычисленного, загруженного или сгенерированного результата, если новый запрос считается достаточно эквивалентным старому и сохранённый результат всё ещё допустим по freshness, permissions, policy и version constraints.

Главный принцип: cache — это ускоритель, а не source of truth. Удаление cache entry должно ухудшить скорость/стоимость, но не сломать корректность системы. Самая важная часть caching — не storage, а правильный cache key + invalidation/freshness contract.
00. ARCHITECTURAL STATUS

КЭШ НУЖЕН ПОСЛЕ ПОЯВЛЕНИЯ ПОВТОРЯЮЩЕЙСЯ ДОРОГОЙ РАБОТЫ

В прототипе сначала добейтесь correctness. Затем измерьте repeated calls / repeated retrieval / repeated embeddings / repeated document processing. Cache включается там, где есть реальная повторяемость и понятная invalidation semantics.
TYPEPRODUCTIONPerformance / cost optimization layer.
DEFAULTCONDITIONALНе кэшировать всё автоматически.
ENABLE WHENREPEATABLE WORKHigh latency/cost + stable equivalence.
SEPARATE COMPONENTYESLogical cache service/policy.
LIVES INPRODUCTION FABRICCross-cutting acceleration.
COMPLEXITYLOW → HIGHExact cache first; semantic later.
IMPLEMENT: AFTER MEASUREMENT
Минимум 80% ценности: deterministic key, namespace/version, TTL, tenant/security scope, hit/miss metrics, explicit stale behavior, max object size, bounded capacity, invalidation hooks и bypass switch. Для AI сначала кэшировать deterministic/expensive stages: embeddings, parsed artifacts, retrieval results under stable corpus version, model outputs only where equivalence/freshness are well-defined.
01A. ARCHITECTURE BOUNDARIES & OPERATIONS

EXPLICIT SYSTEM CONTRACT

A. BOUNDARY WITH NEIGHBORS

№60 Artifact Store хранит durable objects, которые нельзя просто выбросить; №62 хранит disposable acceleration copies/results. №07 Memory сохраняет knowledge/experience для будущего reasoning; cache сохраняет result ради reuse и не является learned memory. №08 RAG определяет retrieval pipeline; cache может ускорять query/result/embedding stages, но не владеет retrieval semantics. №61 Provenance говорит, какая source/version produced result; cache использует эти версии для safe key/invalidation. №63 Retry/Fallbacks отвечает за resilience при failure; cache может быть fallback only if policy explicitly allows stale result.

B. PREREQUISITES / CROSS-REFERENCES

Prerequisites: №08 RAG, №46 Observability, №50 Contracts, №51 Permissions, №60 Artifact Store, №61 Provenance. Forward references: №63 Retry/Circuit Breakers, №64 Quotas/Budgets, №65 Model Gateway, №66 Vector DB & Embeddings, №76 Data Governance.

C. PLANE PLACEMENT

REQUEST-TIME: YES — lookup/set on hot paths. CONTROL PLANE: TTLs, capacity, namespaces, versions, stale policy, bypass rules. DATA PLANE: cached values/refs and metadata. OFFLINE: warming, invalidation, capacity analysis, cache-key regression tests.

D. FAILURE & OPERATIONS CONTRACT

Success: hit returns a result equivalent enough for current request under current policy/version/access context. Failure: cache unavailable should usually degrade to miss, not break correctness. Idempotency: set/refresh safe to repeat. Persist: key, namespace, version, created_at, expires_at, source/version refs, tenant/security scope, value/ref. Trace: HIT/MISS/STALE/BYPASS/REFRESH reason. Security: never share result across principals/tenants unless equivalence and access are proven.

E. WHAT THIS TOPIC DOES NOT OWN

№62 не владеет durable storage, model memory, source-of-truth data, retrieval ranking, retry strategy or state. Она владеет DISPOSABLE REUSE OF PREVIOUSLY COMPUTED OR FETCHED RESULTS UNDER EXPLICIT EQUIVALENCE AND FRESHNESS RULES.

01. CACHE INVARIANT

MISS ДОЛЖЕН БЫТЬ МЕДЛЕННЕЕ, НО КОРРЕКТНЕЕ НЕ ДОЛЖЕН СТАНОВИТЬСЯ

CACHE HIT

Reuse compatible result.

Lower latency / lower cost.

CACHE MISS

Compute authoritative path normally.

Then optionally populate cache.

SAME LOGICAL CONTRACT

Both paths must satisfy the same output/security/quality requirements.

Если cache miss приводит к «невозможно восстановить данные», это storage. Если cache hit обходится без current permission/policy check, это security bug.
02. WHAT TO CACHE

КЭШИРОВАТЬ СТАБИЛЬНЫЕ ДОРОГИЕ ПРЕОБРАЗОВАНИЯ С ПОНЯТНЫМ INPUT

EMBEDDINGS

Excellent candidate

Key = content hash + embedding model/version + preprocessing version.

PARSING

Excellent candidate

Key = raw artifact hash + parser profile/version.

TOOL / API READ

Conditional

Use TTL if source changes over time and stale window is acceptable.

RAG RETRIEVAL

Conditional

Key must include corpus/index version, filters, tenant, query normalization.

LLM RESPONSE

Risky but useful

Exact prompt/context/model/version or carefully bounded semantic cache.

STATIC CONFIG / METADATA

Easy

Short TTL or version key for schemas, model metadata, source descriptors.

03. WHAT NOT TO CACHE BLINDLY

HIGH-VOLATILITY И HIGH-RISK CURRENT STATE

PERMISSIONS

Current authority

Dangerous to reuse too long; stale ACL can leak access.

BALANCE / INVENTORY

Transactional state

Financial/current inventory should usually read authoritative state or very short TTL.

APPROVAL

Expiring decisions

Approval token tied to exact action and expiry; don't cache broad ALLOW.

HIGH-RISK OUTPUT

Context sensitive

Cached response may be wrong if policy/source versions changed.

Чем выше риск и volatility, тем больше cache key должен включать current state — в какой-то момент проще и безопаснее сделать live read.
04. CACHE KEY

КЛЮЧ — ЭТО ФОРМАЛИЗОВАННОЕ «ЭТИ ДВА ЗАПРОСА ЭКВИВАЛЕНТНЫ»

cache_key = hash({
  "namespace": "embedding",
  "input_hash": "sha256:...",
  "model": "embed-v3",
  "preprocess": "norm-v2",
  "tenant_scope": "tenant_A",
  "policy_version": "p17"
})

safe hit requires:
  same namespace
  same relevant inputs
  same transformation version
  same security scope
  not expired
  not invalidated
KEY DESIGN RULE

Include every variable that changes meaning

В key/version context часто входят:

  • normalized input/content hash;
  • model/prompt/parser/tool version;
  • tenant/principal/access scope;
  • locale/language;
  • retrieval corpus/index version;
  • policy/config version;
  • output schema;
  • temperature/seed only if they matter to equivalence.
05. NAMESPACE & VERSION

НЕ УДАЛЯТЬ МИЛЛИОН КЛЮЧЕЙ, ЕСЛИ МОЖНО СМЕНИТЬ VERSION PREFIX

NAMESPACE

Separate purpose

parse:, embed:, retrieve:, llm:, toolread:.

VERSION

Invalidate by generation

embed:v3: makes old v2 cache unreachable without deleting immediately.

TENANT / SCOPE

Isolation

Separate tenant/security namespaces or include scope in key deterministically.

Versioned namespaces — один из самых дешёвых способов избежать subtle stale-cache bugs после prompt/model/parser/index changes.
06. FRESHNESS MODELS

TTL — ТОЛЬКО ОДИН ИЗ СПОСОБОВ

MODEL
INVALIDATION
STALENESS
COMPLEXITY
USE
EXAMPLE
TTL
time expiry
bounded by TTL
LOW
volatile reads
API metadata 5 min
VERSION KEY
new version = miss
LOW
LOW
deterministic transforms
parser v3
EVENT INVALIDATE
source event
small
MEDIUM
mutable objects
document updated
VALIDATE-ON-READ
cheap version check
LOW
MEDIUM
critical cached object
ETag / version
Лучший cache часто комбинирует approaches: long TTL + source version in key + event invalidation for fast convergence.
07. CACHE-ASIDE

САМЫЙ ПРОСТОЙ И ПОНЯТНЫЙ PATTERN

function get_or_compute(key):

    value = cache.get(key)

    if value exists and is_valid(value):
        return value   # HIT

    result = authoritative_compute()

    cache.set(
        key,
        result,
        ttl=...
    )

    return result      # MISS → FILL
Cache-aside хорош тем, что authoritative path остаётся явным. Cache service outage можно обработать как miss.
08. READ-THROUGH / WRITE-THROUGH / WRITE-BEHIND

НЕ ВСЕ CACHE PATTERNS ОДИНАКОВО БЕЗОПАСНЫ ДЛЯ AI

PatternMeaningAI system note
CACHE-ASIDEApplication loads on miss and fills cache.Best default: explicit and simple.
READ-THROUGHCache layer itself loads source on miss.Useful if abstraction stable.
WRITE-THROUGHWrites go authoritative store + cache together.For current projections, but cache isn't source of truth.
WRITE-BEHINDCache accepts write, authoritative store updated later.High risk for critical state; avoid unless carefully designed.
Для AI pipelines чаще всего нужны cache-aside и immutable version-key caching, а не сложные write-behind semantics.
09. STALE-WHILE-REVALIDATE

ИНогда ЧУТЬ УСТАРЕВШИЙ RESULT ЛУЧШЕ, ЧЕМ WAIT

FRESH

Return cached value immediately.

STALE BUT ALLOWED

Return stale value with age/freshness flag; asynchronously refresh.

TOO STALE / HIGH RISK

Block stale response and perform live compute/read.

Stale-while-revalidate должен быть policy by data class. Для weather/news metadata — может быть допустим. Для permission/payment/current approval — обычно нет.
10. CACHE STAMPede / THUNDERING HERD

ОДИН EXPIRED KEY НЕ ДОЛЖЕН ЗАПУСТИТЬ 500 ОДИНАКОВЫХ LLM CALLS

SINGLEFLIGHT

One compute per key

Первый caller computes; остальные ждут/shared result.

LOCK / LEASE

Short-lived ownership

Refresh key has bounded lock/lease so crash can recover.

JITTER

Spread expiry

Randomized TTL prevents thousands of keys expiring at same second.

STALE SERVE

If allowed

Serve acceptable stale value while one worker refreshes.

Stampede protection особенно важна для expensive models, embeddings, remote APIs и large retrieval aggregations.
11. NEGATIVE CACHING

«НЕ НАЙДЕНО» ТОЖЕ МОЖНО КЭШИРОВАТЬ — ОСТОРОЖНО

404 / NOT FOUND

Short TTL

Reduce repeated expensive lookups when absence is likely stable for a short window.

PERMISSION DENY

Very careful

Access can change; deny cache must be principal-scoped and often short-lived.

TRANSIENT ERROR

Don't cache as truth

Timeout/5xx is not «not found». Resilience belongs to №63.

Negative cache must preserve reason class. NOT_FOUND, DENIED and ERROR are not interchangeable.
12. EMBEDDING CACHE

ОДИН ИЗ САМЫХ БЕЗОПАСНЫХ AI CACHE USE CASES

key = hash({
  "content_hash": sha256(normalized_text),
  "embedding_model": "embed-v3",
  "normalizer": "norm-v2",
  "dimensions": 1536
})

hit:
  return vector

miss:
  vector = embed(text)
  cache.set(key, vector)
  return vector
WHY SAFE

Deterministic-ish transform

Если exact input и exact embedding configuration одинаковы, повторный результат практически не несёт новой ценности.

Лучше сохранять embedding как durable derived data/index, если он является частью corpus. Cache полезен для transient/repeated calls до durable persistence.

13. PARSING / TRANSFORMATION CACHE

HASH INPUT + PIPELINE VERSION

INPUT HASH

Exact bytes

Raw artifact hash identifies exact source bytes.

PROFILE

Parser config

Parser/OCR/layout profile/version included in key.

RESULT REF

Reuse artifact

Cache can return existing derived artifact_ref instead of duplicating bytes.

Здесь cache и Artifact Store взаимодействуют: cache entry может быть маленьким mapping key → durable artifact_ref.
14. RAG RETRIEVAL CACHE

QUERY ALONE НЕ ДОСТАТОЧНА ДЛЯ SAFE KEY

retrieval_key = hash({
  "query_normalized": "...",
  "tenant_id": "tenant_A",
  "filters": {...},
  "index_version": "knowledge-v17",
  "retriever": "hybrid-v4",
  "top_k": 12,
  "reranker": "rerank-v2",
  "policy_scope": "..."
})
RAG RISKS

Corpus changes invalidate meaning

  • new/deleted documents;
  • ACL changes;
  • embedding/index rebuild;
  • filter changes;
  • query rewriting changes;
  • reranker version changes.

Index/corpus version in key is often safer than trying to invalidate every possible query.

15. LLM EXACT CACHE

СНАЧАЛА EXACT MATCH, ПОТОМ SEMANTIC

EXACT PROMPT HASH

Lowest risk

Same assembled messages/context/model/config → reuse exact prior output if freshness/security allow.

STRUCTURED INPUT KEY

Better than raw text

Hash task contract + evidence refs + prompt/skill/model versions.

SEMANTIC CACHE

Higher risk

Use only when «similar question» truly permits same answer and source freshness is bounded.

Для open-ended writing, personalization, current news or high-risk decisions semantic cache часто unsafe or low-value. Exact cache намного проще проверить.
16. SEMANTIC CACHE

«ПОХОЖИЙ ЗАПРОС» НЕ ВСЕГДА ОЗНАЧАЕТ «ТОТ ЖЕ ОТВЕТ»

CASE
SIMILAR TEXT
SAME INTENT
SAME ANSWER?
RISK
DECISION
FAQ
often
often
usually
LOW
GOOD
CURRENT PRICE
yes
yes
time-dependent
HIGH
LIVE / SHORT TTL
LEGAL ANALYSIS
maybe
context differs
dangerous reuse
HIGH
AVOID
STATIC HOW-TO
yes
yes
often
MEDIUM
BOUNDED
Semantic cache должен иметь threshold evals: false-hit rate важнее raw hit rate. Один неверный semantic hit может быть дороже сотни missed opportunities.
17. PERSONALIZATION & TENANCY

САМАЯ ОПАСНАЯ ОШИБКА — CROSS-USER CACHE HIT

USER CONTEXT

Preferences matter

Если output зависит от user profile/history, key должен отражать relevant personalization version.

TENANT

Hard isolation

Never share private RAG/tool/model outputs across tenants by query text alone.

PUBLIC DATA

Shareable only if proven

Global cache allowed only for explicitly public, context-independent results.

SCOPE TAG

Explicit cache scope

GLOBAL_PUBLIC, TENANT, USER, RUN.

Cache scope должен быть first-class field, а не implied by key string conventions.
18. SECURITY / POLICY VERSIONING

КЭШИРОВАННЫЙ RESULT МОЖЕТ СТАТЬ НЕДОПУСТИМЫМ ПОСЛЕ ИЗМЕНЕНИЯ POLICY

POLICY VERSION

Key or metadata

Material policy changes create miss/invalidation for affected cache classes.

RELEASE CHECK

Re-evaluate on output

Even cached generation can pass current output/release guardrail before exposure.

ACL VERSION

Current access

Prefer live/current authorization check even when data payload is cached.

Cache may reuse content, but should not reuse stale permission to reveal that content.
19. CACHE INVALIDATION

«ДВЕ СЛОЖНЫЕ ВЕЩИ» — НО ЗДЕСЬ НУЖНА ДИСЦИПЛИНА, А НЕ МАГИЯ

SOURCE / CONFIG CHANGEDocument/model/prompt/policy/index changes.
IDENTIFY CACHE DOMAINWhich namespace/version depends on it?
BUMP VERSION / INVALIDATEPrefer coarse safe invalidation.
OPTIONAL WARMPrecompute hot keys.
OBSERVEMiss spike / latency / correctness.
Version bump часто безопаснее fine-grained invalidation. Старые entries можно удалять lazy/TTL, пока новый namespace уже используется.
20. PROVENANCE-DRIVEN INVALIDATION

№61 ПОМОГАЕТ ПОНЯТЬ, ЧТО ИМЕННО СТАЛО STALE

SOURCE RETRACTED

source://doc42/v7 invalid.

LINEAGE QUERY

Find chunks, embeddings, retrieval caches, reports depending on v7.

INVALIDATE / REBUILD

Delete cache keys or bump affected generations; queue rebuild.

Без lineage приходится either under-invalidate (stale bugs) или flush everything (latency/cost spike).
21. EVICTION

CAPACITY BOUNDED: ЧТО УДАЛЯТЬ ПЕРВЫМ

LRU

Least recently used

Хороший общий default для memory caches.

LFU

Least frequently used

Useful when hot set stable and recency alone insufficient.

TTL

Expiry driven

Entries naturally disappear based on freshness policy.

COST-AWARE

Keep expensive hits

Prioritize entries with high recomputation cost × reuse probability.

Самая большая entry не обязательно самая дорогая для recompute. Для AI полезна cost-aware cache policy, но LRU + TTL достаточно для MVP.
22. CACHE WARMING

ПРЕДВАРИТЕЛЬНО ЗАПОЛНЯТЬ ТОЛЬКО ПРЕДСКАЗУЕМО ГОРЯЧИЕ KEYS

KNOWN HOT

Warm intentionally

Popular static FAQ, common embeddings, high-traffic metadata.

AFTER DEPLOY

Avoid cold-start spike

Warm a small top set after version change if miss storm is expensive.

DON'T PRECOMPUTE EVERYTHING

Waste

Most possible prompts/queries may never be requested.

Warming should be measured by warm-hit benefit vs cost and invalidation frequency.
23. TWO-LEVEL CACHE

L1 PROCESS MEMORY + L2 SHARED CACHE

L1 LOCAL

Fastest

In-process memory, small hot objects, very low latency. Lost on restart; per-process inconsistency tolerated only for cacheable data.

L2 SHARED

Cross-worker reuse

Redis/DB/object mapping shared by multiple processes. Higher latency but better hit rate.

Не добавлять L1+L2 до измерений. Каждый уровень увеличивает invalidation complexity.
24. CACHE BACKEND CHOICES

BACKEND — ВТОРИЧЕН ПО СРАВНЕНИЮ С CORRECTNESS CONTRACT

BackendGood forNotes
IN-PROCESS MEMORYTiny local hot cache.No shared state, disappears on restart.
POSTGRESLow/medium throughput shared cache, version mappings.Often enough initially; not ideal for very high QPS hot cache.
REDIS-LIKEFast shared TTL/LRU cache.Great when performance justifies extra service.
ARTIFACT STORE + INDEXLarge cached outputs.Cache key maps to artifact_ref; don't put giant blobs in Redis.
Для локальной AI-системы Postgres table or in-process LRU may be enough before adding Redis.
25. FAILURE BEHAVIOR

CACHE DOWN = MISS, ЕСЛИ CORRECTNESS НЕ ЗАВИСИТ ОТ CACHE

CACHE TIMEOUT

Fail around it

Short timeout, treat as miss if authoritative path healthy.

SET FAILURE

Return result anyway

Usually do not fail user request because cache write failed.

STALE DATA

Policy decision

Serve only if stale policy allows; otherwise live path.

CORRUPT ENTRY

Discard

Validation/hash/schema mismatch → delete/bypass and recompute.

Cache should have a global bypass/disable switch for incidents. Hidden dependence on cache availability is a smell.
26. OBSERVABILITY

HIT RATE БЕЗ COST И CORRECTNESS — ПОЛОВИНА КАРТИНЫ

HIT

Hit rate

By namespace/key class/tenant/workload.

MISS

Miss reasons

not found / expired / version mismatch / bypass / access mismatch.

SAVE

Latency saved

Estimated compute/tool/model time avoided.

COST

Spend saved

Tokens/API/GPU calls avoided minus cache infra cost.

STALE

Stale served

Count/age by policy class.

EVICT

Evictions

Pressure/capacity by namespace.

STAMP

Stampede

Concurrent computes for same key / singleflight waits.

WRONG

False hit incidents

Cache hit returned semantically/security-invalid result. Target: zero.

27. EVALS

КЭШ НУЖНО ПРОВЕРЯТЬ НА FALSE HIT И INVALIDATION

EXACT

Key determinism

Equivalent exact inputs yield same key; meaningful differences change key.

VERSION

Upgrade miss

Prompt/model/parser/index change invalidates expected entries.

ACL

Isolation

Same query across tenants/users cannot leak cached private result.

SEMANTIC

False hit set

Near-phrases with different intent must not reuse answer.

STALE

Freshness

Source change/misfire invalidates or ages result according to policy.

DOWN

Cache outage

System falls back to authoritative path.

STAMP

Concurrency

100 simultaneous misses create bounded recomputations.

ROI

Net value

Latency/cost reduction exceeds operational complexity.

Semantic-cache eval needs a curated boundary set: superficially similar prompts whose correct answers differ. Это ключевой anti-false-hit test.
28. FAILURE MODES

КАК CACHE ЛОМАЕТ КОРРЕКТНОСТЬ

QUERY-ONLY KEY
Игнорируются tenant, corpus, model, filters, policy.
FULL SEMANTIC KEY
CACHE = SOURCE OF TRUTH
Eviction/outage destroys required data.
DISPOSABLE BY DESIGN
TTL ONLY
Model/parser/source changed but old result remains valid until clock expires.
VERSION + TTL
NO TENANT SCOPE
Private result leaks through shared cache hit.
EXPLICIT CACHE SCOPE
SEMANTIC TOO EARLY
Similar wording reuses wrong answer.
EXACT FIRST
NO STAMPEDE GUARD
One expiry triggers hundreds of duplicate LLM/API calls.
SINGLEFLIGHT
CACHE ERRORS FAIL REQUEST
Performance layer becomes availability dependency.
MISS ON FAILURE
CACHE PERMISSION RESULT
Stale authorization grants/rejects incorrectly.
CURRENT AUTH CHECK
OPTIMIZE HIT RATE ONLY
System keeps large low-value entries and increases false-hit risk.
ROI + CORRECTNESS
29. METRICS

ЧТО ИЗМЕРЯТЬ

HR

Hit Rate

Hits / lookups by namespace and workload class.

P95↓

Latency Saved

p95 request/stage reduction due to cache hits.

$↓

Cost Saved

Model/API/GPU/tool cost avoided minus cache cost.

FH

False Hit Rate

Semantically/security-invalid hits. Target: effectively zero.

STA

Stale Serve Rate

How often stale results are served and average age.

MIS

Version Miss

Misses caused by model/prompt/source/index generation changes.

EV

Eviction Rate

Capacity pressure and churn.

SF

Singleflight Savings

Duplicate recomputations prevented per hot key.

30. MVP IMPLEMENTATION

IN-PROCESS LRU ИЛИ POSTGRES CACHE TABLE УЖЕ МОГУТ ДАТЬ 80%

cache/
├── keys.py
├── service.py
├── policy.py
├── invalidation.py
├── singleflight.py
└── tests/

cache_entries(
  namespace       text,
  cache_key       text,
  tenant_scope    text,
  value_json      jsonb,
  artifact_ref    text,
  created_at      timestamptz,
  expires_at      timestamptz,
  source_version  text,
  config_version  text,
  metadata_json   jsonb,
  primary key(namespace, cache_key)
)

get(key, context):
  if BYPASS: miss
  entry = load
  if absent: miss
  if expired: miss/stale-policy
  if access/version invalid: miss
  return hit

set:
  bounded size
  ttl
  namespace/version
  scope metadata
80% VALUE MVP

Exact cache first

  • Cache only 2–4 proven expensive stages.
  • Exact deterministic keys.
  • Versioned namespace.
  • Tenant/user/global-public scope.
  • TTL only where time freshness matters.
  • Singleflight for expensive misses.
  • Bypass switch.
  • Hit/miss/latency/cost metrics.
  • Version bump invalidation.
  • Cache outage = miss.

Добавлять Redis или semantic cache только после измеренного bottleneck/ROI.

31. PRACTICAL DECISION

СТОИТ ЛИ ДЕЛАТЬ ОТДЕЛЬНЫЙ КОМПОНЕНТ?

ВопросОтвет
Стоит ли реализовывать?Да, после появления повторяемой дорогой работы и измеренного benefit. Не обязательный первый компонент.
Separate Component?YES логически. Физически сначала может быть library + local/Postgres cache.
Минимум 80% ценности?Exact key, namespace/version, TTL/freshness, tenant scope, singleflight, invalidation, hit/miss/cost metrics, bypass.
Когда overkill?Semantic cache, distributed Redis cluster и multi-level invalidation для системы с низким повторением запросов.
Trigger?Repeated identical/equivalent expensive transformations or reads create material latency/cost load.
Как измерить uplift?Hit rate, latency/cost saved, false-hit incidents, stale response rate, cache infra cost, duplicate work prevented.
Можно ли rule/tool/code вместо LLM-agent?Да, и нужно. Exact caching is deterministic infrastructure. LLM/embeddings can participate only in optional semantic similarity layer.
32. DESIGN RULES

ПРАВИЛА ДЛЯ РЕАЛЬНОЙ СИСТЕМЫ

RULE 01

Correct without cache

Cache miss/outage must preserve correctness.

RULE 02

Key defines equivalence

Every meaning-changing input/version belongs in key/context.

RULE 03

Exact before semantic

Start with deterministic reuse; semantic matching needs eval proof.

RULE 04

Version aggressively

Model/prompt/parser/index changes should make old results unreachable.

RULE 05

Scope security explicitly

GLOBAL_PUBLIC / TENANT / USER / RUN.

RULE 06

TTL is not enough

Use source/config versions and events where meaning changes.

RULE 07

Prevent stampedes

Singleflight/lease/jitter for hot expensive keys.

RULE 08

Measure false hits

Hit rate without correctness can reward dangerous behavior.

RULE 09

Optimize by ROI

Cache where saved latency/cost exceeds invalidation/infra complexity.

33. FINAL MAP

REUSE ONLY WHEN THE OLD RESULT IS STILL THE RIGHT RESULT

REQUEST / PIPELINE STAGE
        ↓
BUILD CACHE CONTEXT
  namespace
  normalized input
  tenant/user scope
  model/prompt/tool/parser version
  corpus/index version
  policy version
        ↓
HASH → CACHE KEY
        ↓
LOOKUP
        ├─ MISS
        │    ↓
        │  AUTHORITATIVE COMPUTE
        │    ↓
        │  VALIDATE RESULT
        │    ↓
        │  CACHE SET
        │    ↓
        │  RETURN
        │
        ├─ HIT
        │    ↓
        │  CHECK:
        │    not expired
        │    current access allowed
        │    versions compatible
        │    source freshness acceptable
        │    schema valid
        │    ↓
        │  RETURN
        │
        └─ STALE
             ↓
           policy:
             serve + refresh
             OR miss + recompute

INVALIDATION:
  source changed
  parser changed
  model changed
  prompt changed
  index rebuilt
  policy changed
        ↓
  bump namespace/version
  OR targeted invalidation
        ↓
  optional warm

SAFE FIRST CANDIDATES:
  content_hash + parser_version
  content_hash + embedding_version
  stable API read + short TTL
  retrieval + exact corpus/index version
  exact model request + exact context/config

HIGH-RISK:
  permissions
  current financial state
  approvals
  volatile external facts
  semantic reuse without evals

CORE PRINCIPLE:

CACHE IS A
DISPOSABLE ACCELERATOR.

THE HARD QUESTION IS NOT
"WHERE DO WE STORE IT?"

THE HARD QUESTION IS:

"WHEN ARE TWO REQUESTS
REALLY EQUIVALENT,
AND FOR HOW LONG
IS THE OLD RESULT
STILL SAFE TO REUSE?"

IF THAT CANNOT BE ANSWERED
PRECISELY—

DO NOT CACHE THE RESULT.

ECC RETROFIT / PRACTICAL HARNESS INTEGRATION

A. Related ECC ideas. Context-as-cache, scoped memory, lifecycle hooks, selective capabilities, feature flags, deterministic enforcement, provider-neutral adapters and eval-gated learning are applied only where relevant to №62 Caching.

B–E. Existing boundary and placement. The existing conceptual boundary, class PRODUCTION, default CONDITIONAL and owner Production Fabric remain authoritative. Runtime/control/data/offline placement is unchanged; durable state stays outside model context.

F–H. Hooks and contracts. Use bounded PRE_MODEL/POST_MODEL, PRE_TOOL/POST_TOOL, CHECKPOINT and TASK_COMPLETED events as applicable. Illustrative fields and canonical contracts are defined in NEW_CONTRACTS_SPEC.md; no universal schema is implied.

I–J. Security and evaluation. Host-side schema, permission, secret, budget, idempotency and audit checks take precedence over LLM output. Optional mechanisms require a feature flag and WITH/WITHOUT ablation; measure quality, acceptance, correction, latency, cost, escalations and severe errors.

K–L. Task profiles and cross-references. A TaskProfile selects the relevant skill, tool/context slice, memory scope and enforcement profile independently from FAST/STANDARD/DEEP. See cross-reference map, hook spec and ablation plan. Provider adapters remain outside the core.