[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
+151 -75
View File
@@ -1,99 +1,175 @@
---
id: wiki-2026-0508-long-tasks
title: Long Tasks
title: Long Tasks API
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-183DC1]
aliases: [Long Tasks, Long Animation Frame, LoAF, Main Thread Blocking]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
verification_status: applied
tags: [web-perf, performance-api, inp, main-thread, browser]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - Long Tasks"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: unspecified
framework: unspecified
last_reinforced: 2026-05-10
github_commit: pending
tech_stack: { language: JavaScript, framework: PerformanceObserver }
---
# [[Long Tasks|Long Tasks]]
# Long Tasks API
## 📌 한 줄 통찰 (The Karpathy Summary)
> 롱 태스크(Long Tasks)는 브라우저의 메인 스레드를 50ms 이상 장시간 차단하는 자바스크립트 연산 등의 CPU 처리 작업을 의미합니다 [1]. 이러한 작업은 짧은 여러 개의 작업보다 사용자 상호작용(Interaction)을 훨씬 더 지연시키며, 웹사이트를 느리게 느껴지게 만드는 주된 원인이 됩니다 [2].
## 한 줄
> **"매 long task = main thread 50ms+ 블록"**. INP/Responsiveness의 직접 원인. PerformanceObserver로 측정·attribute한다.
## 📖 구조화된 지식 (Synthesized Content)
- **정의 및 성능에 미치는 영향:**
롱 태스크는 브라우저의 메인 스레드를 50밀리초(ms) 이상 차단하는 자바스크립트 연산을 말합니다 [1]. 브라우저의 CPU 처리 작업 중 롱 태스크는 사용자 상호작용을 처리하는 것을 방해하여 응답성을 지연시킵니다 [2]. 이는 사용자 경험을 저하시키며, 구글의 [[Core Web Vitals|Core Web Vitals]] 지표 중 하나인 INP(Interaction to Next Paint) 점수를 악화시키는 주요 원인이 됩니다 [1, 3].
- **식별 및 모니터링 방법:**
개발자는 [[Chrome DevTools|Chrome DevTools]]의 Performance(성능) 패널을 통해 롱 태스크를 발견할 수 있습니다. 성능 프로파일링 시 긴 시간이 소요된 Task에는 빨간색 삼각형 경고가 표시되어 성능 병목 현상이 발생했음을 알립니다 [4, 5]. 또한 [[Long Animation Frames API|Long Animation Frames API]]를 활용하여 사용자 상호작용을 지연시키는 특정 스크립트를 식별하고 분석할 수도 있습니다 [6, 7].
- **최적화 및 해결 전략:**
상호작용 응답성을 개선하려면 롱 태스크를 쪼개어 브라우저가 렌더링 및 입력을 처리할 시간을 확보해야 합니다 [1]. 제공된 소스에서 권장하는 해결 방법은 다음과 같습니다.
- **작업 분할(Task Splitting):** 무거운 자바스크립트 함수를 더 작은 비동기 청크(async chunks)로 나눕니다 [1].
- **[[Scheduler API|Scheduler API]] 사용:** `scheduler.yield()`와 같은 메서드를 사용하여 작업 중간에 브라우저 스케줄러로 제어권을 넘겨(yield) 사용자 상호작용을 먼저 처리하게 한 뒤 남은 작업을 계속 진행합니다 [2].
- **메인 스레드 오프로딩:** Web Workers를 활용하여 무거운 로직을 메인 스레드에서 분리하여 실행합니다 [1, 8].
- **스케줄링 및 지연 로딩:** `requestIdleCallback`을 사용하여 중요도가 낮은 작업의 실행을 미루거나, 중요하지 않은 자바스크립트의 로딩을 지연(defer) 및 지연 로딩(lazy load) 처리합니다 [1, 9].
## 매 핵심
### 매 정의
- **Long Task**: 단일 task가 50ms 초과로 main thread 점유.
- 사용자 입력·rendering 지연 → INP 악화.
- W3C spec: `longtask` PerformanceEntry.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** AI 분야의 자동 자산화 수행.
### 매 후속 표준 (LoAF)
- **Long Animation Frame** (Long Animation Frames API): frame 단위, attribution 강화.
- entryType `long-animation-frame` — script source, style/layout 시간 포함.
- Long Tasks API보다 정확하고 디버깅 친화적 (2024+).
## 🔗 지식 연결 (Graph)
- **Related Topics:** [[Interaction to Next Paint (INP)|Interaction to Next Paint (INP)]], [[Main Thread|Main Thread]], [[Scheduler API|Scheduler API]], [[Chrome DevTools|Chrome DevTools]]
- **Projects/Contexts:** [[Core Web Vitals|Core Web Vitals]], [[Web Performance Optimization|Web Performance Optimization]]
- **Contradictions/Notes:** 소스 간의 모순된 내용은 발견되지 않았으며, 제공된 자료들은 공통적으로 웹 성능 향상을 위해 롱 태스크를 식별하고 분할하는 것의 중요성을 강조하고 있습니다.
### 매 측정 항목
- `duration`, `startTime`
- `attribution` (Long Tasks): TaskAttributionTiming, container 정도만 (cross-origin 익명화)
- `scripts[]` (LoAF): name, sourceURL, function, invoker, executionStart/forcedStyleAndLayoutDuration
---
*Last updated: 2026-04-19*
### 매 흔한 원인
1. 큰 JS 번들 parse/compile
2. 동기 layout/style (forced reflow)
3. 무거운 React render (큰 리스트, memo 부재)
4. JSON parse 큰 payload
5. 동기 third-party script
6. Hydration burst (Next.js, Nuxt)
---
### 매 완화
- Code split, dynamic import
- `requestIdleCallback`, `scheduler.postTask`, `scheduler.yield()`
- Web Worker로 오프로드
- Virtualization (큰 리스트)
- React: Suspense, useDeferredValue, transitions
- Defer non-critical scripts, async chunks
## 🤖 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
## 💻 패턴
### Long Tasks 관찰
```js
const obs = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
console.log("long task", entry.duration, entry.name, entry.attribution);
}
});
obs.observe({ type: "longtask", buffered: true });
```
## 🤔 의사결정 기준 (Decision Criteria)
### Long Animation Frame (현대)
```js
const obs = new PerformanceObserver((list) => {
for (const e of list.getEntries()) {
if (e.duration < 50) continue;
for (const s of e.scripts) {
console.log("LoAF script", s.name, s.sourceURL,
s.duration, "fwd-layout:", s.forcedStyleAndLayoutDuration);
}
}
});
obs.observe({ type: "long-animation-frame", buffered: true });
```
**선택 A를 써야 할 때:**
- *(TODO)*
### scheduler.yield (cooperative)
```js
async function processItems(items) {
for (const item of items) {
doWork(item);
if (navigator.scheduling?.isInputPending?.() || performance.now() - last > 5) {
await scheduler.yield(); // chunk 양보
last = performance.now();
}
}
}
```
**선택 B를 써야 할 때:**
- *(TODO)*
### requestIdleCallback fallback
```js
function chunked(items, fn) {
let i = 0;
function run(deadline) {
while (i < items.length && deadline.timeRemaining() > 0) fn(items[i++]);
if (i < items.length) requestIdleCallback(run);
}
requestIdleCallback(run);
}
```
**기본값:**
> *(TODO)*
### Web Worker로 오프로드
```js
// main
const w = new Worker("./parse.worker.js", { type: "module" });
w.postMessage(largePayload);
w.onmessage = (e) => render(e.data);
## ❌ 안티패턴 (Anti-Patterns)
// parse.worker.js
self.onmessage = (e) => {
const result = heavyParse(e.data);
self.postMessage(result);
};
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### React deferred / transition
```jsx
import { useDeferredValue, useTransition } from "react";
const deferred = useDeferredValue(query);
const [isPending, start] = useTransition();
start(() => setFilter(next)); // non-urgent → no long task on type
```
### web-vitals 통합
```js
import { onINP } from "web-vitals/attribution";
onINP((m) => {
// m.attribution.longAnimationFrameEntries → 원인 frame
beacon("inp", m);
}, { reportAllChanges: true });
```
## 매 결정 기준
| 상황 | 도구 |
|---|---|
| 측정 시작 | LoAF (지원) → Long Tasks fallback |
| 사용자 INP 추적 | web-vitals attribution |
| CPU-bound | Web Worker |
| 큰 리스트 처리 | scheduler.yield, chunking |
| Render bottleneck | useDeferredValue, virtualization |
| Third-party 무거움 | defer/async, Partytown |
**기본값**: web-vitals onINP + LoAF observer로 attribute → 가장 큰 script 우선 최적화.
## 🔗 Graph
- 부모: [[Web-Performance]], [[Performance-API]]
- 변형: [[Long-Animation-Frame]], [[Performance-Observer]]
- 응용: [[INP]], [[Core-Web-Vitals]], [[React-Performance]]
- Adjacent: [[Web-Workers]], [[Scheduler-API]], [[Code-Splitting]]
## 🤖 LLM 활용
**언제**: PerformanceObserver 코드, 원인 분류, 완화 전략 매핑.
**언제 X**: 실제 attribution은 production trace로 검증해야 정확.
## ❌ 안티패턴
- 50ms threshold만 보고 47ms task 무시 (LoAF가 누적 표시)
- requestAnimationFrame 안에 무거운 sync 작업
- Worker로 보내고 직렬화 cost > 작업 cost
- setTimeout(fn, 0)으로 yield (실제 양보 부족) → scheduler.yield
- Long task 발생만 알리고 attribution 안 봄 → 원인 파악 불가
- DevTools만 보고 production 측정 누락
## 🧪 검증 / 중복
- Verified (W3C Long Tasks, web.dev INP, Long Animation Frames API). 신뢰도 A.
- 중복: 없음.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — LoAF, scheduler.yield, web-vitals 통합 |