[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
+166 -66
View File
@@ -1,93 +1,193 @@
---
id: wiki-2026-0508-cache-miss-rates
title: Cache miss rates
title: Cache Miss Rates
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-E946BD]
aliases: [Cache Miss Rate, Cache Hit Rate, Cache Efficiency]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
verification_status: applied
tags: [performance, cache, profiling, cpu, memory]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - Cache miss rates"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: unspecified
framework: unspecified
language: agnostic
framework: agnostic
---
# [[Cache miss rates|Cache miss rates]]
# Cache Miss Rates
## 📌 한 줄 통찰 (The Karpathy Summary)
> 소스에 따르면, 캐시 미스 비율(Cache miss rates) 및 캐시 적중률(Cache hit rates)은 고해상도 타이머를 통해 관찰될 수 있는 메모리 접근 패턴의 지표입니다 [1, 2]. 공격자는 이를 분석하여 CPU 및 GPU의 물리적 메모리 구조를 파악하고, 스펙터([[Spectre|Spectre]]), 멜트다운(Meltdown), 로우해머(Rowhammer)와 같은 심각한 보안 취약점을 악용할 수 있습니다 [1, 2]. 결과적으로 브라우저 벤더들은 이러한 타이밍 기반의 부채널 공격([[Side-channel Attack|Side-channel Attack]])을 방지하기 위해 타임스탬프 쿼리의 정밀도를 의도적으로 제한하는 방어 기제를 채택하고 있습니다 [1, 3].
## 한 줄
> **"매 cache lookup 의 fail (data 의 cache 외 fetch) ratio"**. CPU L1/L2/L3 cache, browser HTTP cache, application-level memoization, CDN edge cache 의 universal metric — `miss / (hit + miss)`. 2026 perspective: Apple Silicon M4 의 huge L2 (16MB+), 매 Cloudflare/Fastly tiered cache, 매 LLM prompt-cache (Anthropic) 의 cost-driven optimization.
## 📖 구조화된 지식 (Synthesized Content)
- **보안 취약점 악용 매개체:** 보안 연구자들에 따르면, 고정밀 타이머(high-fidelity timing)를 사용해 캐시 미스 비율(또는 캐시 적중률)과 메모리 접근 패턴을 관찰할 수 있으며, 이는 스펙터와 멜트다운 같은 보안 취약점 악용을 용이하게 합니다 [1].
- **로우해머(Rowhammer) 공격과 GPU 캐시 미스:** [[WebGL|WebGL]] 환경에서 타임스탬프 쿼리를 이용해 고정밀 시간을 측정하면 공격자는 GPU의 캐시 미스 비율을 확인할 수 있습니다 [2]. 이를 통해 GPU 물리적 메모리의 레이아웃을 파악하고, 특정 메모리 비트를 변조(bit flip)시키는 로우해머 공격을 가하여 페이지 테이블을 속이는 등의 악의적인 행위가 가능합니다 [2].
- **타이밍 기반 정보 유출 (Timing-based information leak):** 스펙터(Spectre) 공격의 성공은 고정밀 타이밍 측정에 의존합니다 [4]. 데이터가 CPU의 L1 캐시에 존재할 때의 접근 지연 시간과 캐시 미스로 인해 메인 메모리에 접근해야 할 때의 지연 시간 차이를 측정함으로써, 공격자는 메모리 내부의 기밀 데이터를 유추해낼 수 있습니다 [4, 5].
- **브라우저의 방어 메커니즘 (타이머 정밀도 제한):** 캐시 미스에 따른 미세한 타이밍 차이(서브 마이크로초 단위)를 공격자가 관찰하지 못하도록, 브라우저 엔진들은 `performance.now()`의 정밀도를 1ms 단위로 낮추거나(reduce timer precision) 격리된 환경(Isolated Context)에서 [[WebGPU|WebGPU]] 타임스탬프 쿼리의 해상도를 100 마이크로초 등으로 제한([[Quantization|Quantization]])하는 보안 조치를 취하고 있습니다 [1, 3, 6, 7].
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
### 매 hierarchy (CPU)
- **L1**: 32-128KB / core, ~1-4 cycles.
- **L2**: 256KB-2MB / core, ~10-15 cycles.
- **L3**: 8-128MB shared, ~40 cycles.
- **DRAM**: >100ns, ~200-300 cycles. 매 miss 의 huge cost.
## 🔗 지식 연결 (Graph)
- **Related Topics:** [[Spectre|Spectre]], Meltdown, Rowhammer, [[Timestamp Queries|Timestamp Queries]]
- **Projects/Contexts:** WebGPU [[Timestamp Queries Quantization|Timestamp Queries Quantization]], [[WebKit Security Mitigations|WebKit Security Mitigations]]
- **Contradictions/Notes:** 소스에서는 캐시 미스 비율이 일반적인 시스템 성능 최적화 지표로 다루어지기보다는, 고해상도 타이머를 악용한 사이드 채널 보안 공격(side-channel attacks)을 가능하게 하는 위험 요소의 관점으로만 집중적으로 설명되어 있습니다 [1, 2, 4].
### 매 miss types (3C)
- **Compulsory** (cold): 매 first access.
- **Capacity**: 매 working set > cache size.
- **Conflict**: 매 set-associative collision.
- (+) **Coherence**: multi-core invalidation.
---
*Last updated: 2026-04-19*
### 매 measurement
- **CPU**: `perf stat -e cache-misses,cache-references` (Linux).
- **HTTP**: `cf-cache-status: HIT/MISS` headers.
- **App**: hit/miss counter on cache wrapper.
---
### 매 응용
1. 매 hot loop 의 data layout (SoA vs AoS) tuning.
2. 매 CDN cache key strategy.
3. 매 LLM prompt-cache 의 prefix stability.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 💻 패턴
**언제 이 지식을 쓰는가:**
- *(TODO)*
### Pattern 1 — 매 cache-friendly layout (SoA)
```ts
// 매 BAD (AoS) — 매 padding / strided access
const particles = [{ x: 0, y: 0, vx: 1, vy: 1 }, /* ... */];
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
// 매 GOOD (SoA) — 매 sequential, cache-line dense
const xs = new Float32Array(N), ys = new Float32Array(N);
const vxs = new Float32Array(N), vys = new Float32Array(N);
for (let i = 0; i < N; i++) {
xs[i] += vxs[i];
ys[i] += vys[i];
}
```
## 🤔 의사결정 기준 (Decision Criteria)
### Pattern 2 — 매 LRU cache (memoization)
```ts
class LRU<K, V> {
private map = new Map<K, V>();
constructor(private capacity: number) {}
**선택 A를 써야 할 때:**
- *(TODO)*
get(key: K): V | undefined {
if (!this.map.has(key)) return;
const v = this.map.get(key)!;
this.map.delete(key);
this.map.set(key, v); // refresh
return v;
}
set(key: K, val: V) {
if (this.map.has(key)) this.map.delete(key);
else if (this.map.size >= this.capacity) {
this.map.delete(this.map.keys().next().value!);
}
this.map.set(key, val);
}
}
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Pattern 3 — 매 hit rate metric
```ts
class CountingCache<K, V> {
private hits = 0;
private misses = 0;
constructor(private inner: Map<K, V>, private load: (k: K) => V) {}
**기본값:**
> *(TODO)*
get(k: K): V {
if (this.inner.has(k)) { this.hits++; return this.inner.get(k)!; }
this.misses++;
const v = this.load(k);
this.inner.set(k, v);
return v;
}
hitRate(): number { return this.hits / (this.hits + this.misses || 1); }
}
```
## ❌ 안티패턴 (Anti-Patterns)
### Pattern 4 — 매 HTTP cache header
```http
GET /api/posts/123
Cache-Control: public, max-age=300, stale-while-revalidate=86400
ETag: "abc123"
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
# CDN response
cf-cache-status: HIT
age: 42
```
### Pattern 5 — 매 stable key (CDN)
```ts
// 매 BAD — query order varies
fetch(`/api/list?b=2&a=1`);
fetch(`/api/list?a=1&b=2`); // 매 different cache key
// 매 GOOD — canonical
const params = new URLSearchParams();
[...Object.entries(args)].sort().forEach(([k, v]) => params.set(k, v));
fetch(`/api/list?${params}`);
```
### Pattern 6 — 매 LLM prompt cache (Anthropic)
```python
# 매 stable system prefix → cache hit (90% cost reduction)
client.messages.create(
model="claude-opus-4-7",
system=[
{"type": "text", "text": LARGE_STABLE_PREFIX,
"cache_control": {"type": "ephemeral"}},
],
messages=[{"role": "user", "content": query}],
)
```
### Pattern 7 — 매 CPU perf measure
```bash
perf stat -e cache-references,cache-misses,L1-dcache-load-misses ./app
# 매 miss rate = misses / references
```
### Pattern 8 — 매 prefetch hint
```ts
// 매 link prefetch (browser)
<link rel="prefetch" href="/next-page" as="document">
// 매 software prefetch (WASM/native via SIMD intrinsics)
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| 매 hot loop slow | profile cache-misses, switch to SoA. |
| 매 CDN low hit rate | normalize key, raise max-age. |
| 매 LLM cost high | prompt-cache stable prefix. |
| 매 working set > cache | partition (tiling), reduce. |
| 매 frequent-but-changing | LRU + TTL. |
**기본값**: 매 measure first (perf, CDN headers, app counter), 매 90%+ hit rate target on hot caches.
## 🔗 Graph
- 부모: [[Performance]] · [[Caching]]
- 변형: [[CPU Cache]] · [[HTTP Cache]] · [[CDN]] · [[Memoization]]
- 응용: [[Prompt Cache]] · [[Database Query Cache]]
- Adjacent: [[CPU Overhead]] · [[Buffer Allocation]] · [[Batching]]
## 🤖 LLM 활용
**언제**: 매 cache strategy design, hit rate target setting, prompt-cache prefix structuring.
**언제 X**: 매 hardware-specific cache line size assumption — vendor docs 의.
## ❌ 안티패턴
- **매 cache everything**: 매 cold data cache space waste.
- **매 unstable cache key**: 매 hit rate near zero.
- **매 no eviction**: unbounded memory.
- **매 measuring without baseline**: 매 hit rate alone meaningless — 매 latency / cost outcome 의.
- **매 caching mutable data without invalidation**: stale read bug.
## 🧪 검증 / 중복
- Reference (Hennessy & Patterson, Cloudflare cache docs, Anthropic prompt caching docs).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — cache hierarchy + LRU + HTTP + prompt-cache patterns |