[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
+148 -73
View File
@@ -2,98 +2,173 @@
id: wiki-2026-0508-timestamp-queries
title: Timestamp Queries
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-77D993]
aliases: [GPU Timestamp Queries, WebGPU Timestamp]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
verification_status: applied
tags: [webgpu, profiling, gpu, performance]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - Timestamp Queries"
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: javascript
framework: webgpu
---
# [[Timestamp Queries|Timestamp Queries]]
# Timestamp Queries
## 📌 한 줄 통찰 (The Karpathy Summary)
> Timestamp Queries(타임스탬프 쿼리)는 [[WebGL|WebGL]] 및 WebGPU와 같은 웹 그래픽 파이프라인에서 GPU 명령 세트의 경과 시간을 나노초 단위까지 정밀하게 측정할 수 있게 해주는 기능입니다 [1-3]. 렌더링 파이프라인을 지연시키지 않으면서 GPU 작업 부하의 성능과 동작에 대한 깊은 통찰력을 제공하는 데 필수적입니다 [3, 4]. 그러나 고정밀 타이머가 사이드 채널 공격(예: Spectre 및 Meltdown)에 악용될 수 있다는 보안 취약점 때문에, 최신 브라우저 환경에서는 타이머의 정밀도를 의도적으로 낮추는 양자화([[Quantization|Quantization]]) 기법이 적용됩니다 [2, 5, 6].
## 한 줄
> **"매 nanosecond-precision GPU timing"**. WebGPU `timestamp-query` feature 의 GPU command buffer 안 의 timestamp 의 record 의 pass-level / draw-level latency 의 measure. 매 CPU `performance.now()` 의 GPU work 의 invisible 의 problem 의 solve, 매 2026 production profiling 의 standard.
## 📖 구조화된 지식 (Synthesized Content)
* **WebGL에서의 타이머 쿼리 한계:**
기존 WebGL은 `EXT_disjoint_timer_query` 확장을 통해 렌더링 파이프라인의 중단 없이 GL 명령의 지속 시간을 측정할 수 있었습니다 [1, 4]. 하지만 이 고정밀 타이밍 기능이 캐시 적중률을 관찰하여 Spectre 및 Meltdown과 같은 사이드 채널 공격에 악용될 수 있음이 밝혀지면서, 대부분의 브라우저 공급업체는 이 확장을 비활성화하거나 타이머 값에 엄격한 양자화 및 클램핑을 적용했습니다 [2].
* **WebGPU 타임스탬프 쿼리 도입:**
WebGPU는 `timestamp-query` 기능과 `GPUQuerySet`을 통해 렌더링 및 컴퓨트 패스의 시작과 끝에서 매우 정밀한(나노초 단위) 측정을 지원합니다 [2, 3]. 이 기능은 텐서플로우(Tensorflow.js)와 같은 복잡한 GPU 작업 부하의 동작을 파악하고 최적화하는 데 널리 활용됩니다 [7].
* **보안을 위한 양자화(Quantization) 및 거칠기(Coarsening) 적용:**
고정밀 타이머를 통한 지문 수집(Fingerprinting) 및 타이밍 공격을 방지하기 위해 WebGPU는 타임스탬프 값을 양자화합니다 [2, 5]. WebGPU 제안 초기에는 사이트 격리(Site isolation) 여부에 따라 격리된 컨텍스트에서는 100 마이크로초(µs) 해상도로, 격리되지 않은 컨텍스트에서는 쿼리 자체를 노출하지 않는 방식을 고려했습니다 [5, 8].
* **교차 출처(Cross-origin) 및 하드웨어 특성을 반영한 정책 변경:**
이후 논의 과정에서 GPU 타임스탬프는 고립된 컨텍스트 간에도 공유될 수 있으며 GPU 캐시를 통한 타이밍 공격 위험이 여전히 존재함이 확인되었습니다 [6]. 상호 운용성(Interop)을 높이고 보안을 유지하기 위해, 사이트의 교차 출처 격리(cross-origin isolated) 상태와 무관하게 항상 고해상도 시간 사양(HR-time)에 맞추어 100 마이크로초(µs)로 해상도를 거칠게 만드는(coarsening) 것으로 최종 정책이 합의되었습니다 [6, 9].
* **개발자를 위한 예외 처리:**
성능 프로파일링을 위해 실제 나노초 단위의 정밀한 측정값이 필요한 개발자는 로컬 환경에서 "WebGPU Developer Features" 또는 "Unsafe WebGPU [[Support|Support]]" 같은 특정 브라우저 플래그를 활성화하여 이러한 양자화 제한을 일시적으로 우회할 수 있습니다 [8, 10].
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Graphics & Performance 분야의 자동 자산화 수행.
### 매 동작 원리
- `timestamp` query type 의 query set 의 allocate.
- `pass.writeTimestamp(querySet, index)` 의 command buffer 의 inject.
- `commandEncoder.resolveQuerySet()` 의 GPU buffer 의 result 의 write.
- `mapAsync(GPUMapMode.READ)` 의 CPU 의 read — 매 BigInt64Array 의 nanosecond.
## 🔗 지식 연결 (Graph)
- **Related Topics:** WebGL Timer Queries, [[Spectre and Meltdown|Spectre and Meltdown]], WebGPU, [[Timestamp Quantization|Timestamp Quantization]]
- **Projects/Contexts:** EXT_disjoint_timer_query, High Re[[Solution|Solution]] Time Spec
- **Contradictions/Notes:** 초기 WebGPU 구현 제안에서는 사이트 격리 상태에 따라 타임스탬프 쿼리의 노출 여부와 해상도를 다르게 적용하려고 했으나(격리 시 100µs, 비격리 시 미노출) [5], 브라우저 간의 상호 운용성 부족 및 GPU의 격리 한계를 이유로 격리 상태와 관계없이 모든 GPU 작업에 대해 일괄적으로 100µs 해상도를 적용하도록 사양이 수정되었습니다 [6, 9].
### 매 caveat
- 매 feature flag 의 `requiredFeatures: ['timestamp-query']` 의 device 의 request 의 require.
- 매 timestamp resolution 의 driver-dependent — 매 Chrome 의 100ns granularity 의 quantize (privacy).
- 매 GPU clock 의 CPU clock 의 unsynced — 매 absolute time 의 X.
- 매 query result 의 readback 의 1+ frame 의 lag — 매 real-time 의 X 의 best-effort.
---
*Last updated: 2026-04-19*
### 매 응용
1. Render pass / compute pass 의 cost breakdown.
2. Shader optimization 의 before/after 의 measure.
3. Adaptive quality (timestamp 의 budget exceed 의 case 의 LOD drop).
4. Production telemetry 의 GPU bottleneck 의 detect.
---
## 💻 패턴
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(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
### Request feature
```javascript
const adapter = await navigator.gpu.requestAdapter();
if (!adapter.features.has('timestamp-query')) {
throw new Error('timestamp-query unsupported');
}
const device = await adapter.requestDevice({
requiredFeatures: ['timestamp-query'],
});
```
## 🤔 의사결정 기준 (Decision Criteria)
### Create query set + buffer
```javascript
const querySet = device.createQuerySet({ type: 'timestamp', count: 2 });
const queryBuffer = device.createBuffer({
size: 16, // 2 × u64
usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC,
});
const readBuffer = device.createBuffer({
size: 16,
usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST,
});
```
**선택 A를 써야 할 때:**
- *(TODO)*
### Inject into render pass
```javascript
const pass = encoder.beginRenderPass({
colorAttachments: [...],
timestampWrites: {
querySet,
beginningOfPassWriteIndex: 0,
endOfPassWriteIndex: 1,
},
});
pass.setPipeline(...);
pass.draw(...);
pass.end();
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Resolve + readback
```javascript
encoder.resolveQuerySet(querySet, 0, 2, queryBuffer, 0);
encoder.copyBufferToBuffer(queryBuffer, 0, readBuffer, 0, 16);
device.queue.submit([encoder.finish()]);
**기본값:**
> *(TODO)*
await readBuffer.mapAsync(GPUMapMode.READ);
const times = new BigInt64Array(readBuffer.getMappedRange());
const deltaNs = Number(times[1] - times[0]);
console.log(`Pass: ${(deltaNs / 1e6).toFixed(2)} ms`);
readBuffer.unmap();
```
## ❌ 안티패턴 (Anti-Patterns)
### Three.js helper (r170+)
```javascript
const renderer = new THREE.WebGPURenderer({ trackTimestamp: true });
await renderer.init();
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
await renderer.renderAsync(scene, camera);
const renderTime = await renderer.resolveTimestampsAsync(THREE.TimestampQuery.RENDER);
console.log(`Render GPU: ${renderTime} ms`);
```
### Multiple pass labels
```javascript
const querySet = device.createQuerySet({ type: 'timestamp', count: 6 });
// pass A: index 0, 1
// pass B: index 2, 3
// pass C: index 4, 5
// 매 single resolve 의 batch
```
### Ring buffer 의 frame-over-frame
```javascript
class GpuProfiler {
constructor(device, frames = 4) {
this.queries = Array.from({ length: frames }, () => ({
set: device.createQuerySet({ type: 'timestamp', count: 2 }),
buf: device.createBuffer({ size: 16, usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST }),
pending: false,
}));
this.frame = 0;
}
acquire() {
const slot = this.queries[this.frame % this.queries.length];
this.frame++;
return slot;
}
}
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Coarse CPU+GPU 의 frame time | `performance.now()` + `requestAnimationFrame` |
| Per-pass GPU breakdown | timestamp-query |
| Shader instruction-level | Chrome WebGPU Inspector / RenderDoc |
| Production telemetry | timestamp-query + sampling (1% session) |
| WebGL fallback | EXT_disjoint_timer_query (degraded, deprecated) |
**기본값**: 매 WebGPU app 의 production 의 ring-buffered timestamp-query — 매 1-frame lag 의 accept.
## 🔗 Graph
- 부모: [[WebGPU]] · [[GPU Profiling]]
- 변형: [[Pipeline Statistics Query]] · [[Occlusion Query]]
- 응용: [[Adaptive Quality Rendering]] · [[Performance Telemetry]]
- Adjacent: [[performance.now]] · [[RenderDoc]]
## 🤖 LLM 활용
**언제**: 매 GPU bottleneck 의 suspect, 매 pass-level cost 의 attribute 의 want.
**언제 X**: 매 CPU-bound problem (e.g. JS hot loop) — 매 DevTools profiler 의 use.
## ❌ 안티패턴
- **Sync `mapAsync` await 의 매 frame**: 매 pipeline stall — 매 ring buffer 의 use.
- **Single timestamp 의 absolute time 의 interpret**: 매 GPU clock 의 CPU 의 unsync.
- **100ns 의 below 의 reliance**: 매 browser 의 quantize — 매 noise.
- **Feature 의 unrequest 의 use**: 매 `device.createQuerySet` 의 throw.
- **Profiler 의 production 의 always-on**: 매 overhead minor 의 X 의 budget — 매 sample.
## 🧪 검증 / 중복
- Verified (W3C WebGPU spec §22 Queries, Chrome WebGPU release notes).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — query set, ring buffer, Three.js integration |