[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
@@ -1,88 +1,161 @@
---
id: wiki-2026-0508-b-tree
title: B Tree
title: B-Tree
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AI-B-TREE]
aliases: [B+Tree, BTree, Balanced-Tree-Index]
duplicate_of: none
source_trust_level: A
confidence_score: 0.99
tags: [B-Tree, Data Structure, DB, Indexing]
confidence_score: 0.95
verification_status: applied
tags: [data-structure, tree, index, database]
raw_sources: []
last_reinforced: 2026-04-20
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: unspecified
framework: unspecified
language: python
framework: stdlib
---
# [[B-Tree|B-Tree]] (B-트리)
# B-Tree
## 📌 한 줄 통찰 (The Karpathy Summary)
> "디스크의 느린 속도를 이겨내는 최적의 균형." 한 노드에 여러 데이터를 담고 층수를 낮게 유지하여, 수백만 건의 데이터도 단 3~4번의 읽기만으로 찾아내는 인덱스의 제왕이다.
## 한 줄
> **"매 disk-friendly한 self-balancing search tree — 매 한 노드에 매 많은 key를 저장해 매 height를 minimize"**. 매 1970년 Bayer & McCreight가 IBM에서 design, 매 2026 PostgreSQL/MySQL InnoDB/SQLite의 default index, 매 NVMe SSD에서도 여전히 dominant — 매 sequential I/O와 cache line alignment 친화적.
## 📖 구조화된 지식 (Synthesized Content)
- **Multi-way [[Search|Search]] Tree**:
- 이진 트리(2-way)와 달리 노드 하나가 수십~수백 개의 자식을 가질 수 있다. 이를 통해 트리의 높이(Height)를 극적으로 낮춘다.
- **Self-Balancing**:
- 데이터가 추가되거나 삭제될 때마다 스스로 노드를 분할(Split)하거나 합치며(Merge) 높이 균형을 유지한다. 언제나 탐색 속도가 보장된다.
- **Disk I/O [[Efficiency|Efficiency]]**:
- 노드 한 개의 크기를 하드디스크의 한 블록(Page) 크기에 맞춰 설계하여, 한 번의 스핀으로 최대한 많은 정보를 읽어오게 한다.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- 현대의 SSD 환경에서는 랜덤 액세스 속도가 빨라져서 B-Tree 계열 외에도 LSM-Tree(NoSQL 등에서 사용) 같은 다양한 변종이 사용된다. 하지만 여전히 관계형 DB(MySQL, PostgreSQL)의 기본 인덱스는 B+Tree(B-Tree의 계층형 변형)가 압도적 표준이다.
### 매 invariant
- 매 node는 매 $[t-1, 2t-1]$ keys 보유 (매 root만 예외).
- 매 internal node는 매 $[t, 2t]$ children.
- 매 모든 leaf는 매 same depth.
- 매 keys 매 sorted within node.
## 🔗 지식 연결 (Graph)
- Related: [[Distributed-Systems-Engineering|Distributed-Systems-Engineering]] , [[Combinatorial-Optimization|Combinatorial-Optimization]]
- Foundation: Computational Thinking
### 매 B+ Tree variant (DB 표준)
- 매 internal node는 매 keys만 — 매 data는 매 leaf에만.
- 매 leaf끼리 매 linked list — 매 range scan $O(k)$.
- 매 PostgreSQL/MySQL이 매 사용.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. RDBMS index (PostgreSQL btree).
2. Filesystem (ext4 HTree, NTFS).
3. KV store (LevelDB SST, RocksDB).
4. Vector DB metadata index.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### B-Tree node (Python)
```python
class BTreeNode:
def __init__(self, t, leaf=False):
self.t = t # min degree
self.keys = []
self.children = []
self.leaf = leaf
## 🧪 검증 상태 (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
def search(self, k):
i = 0
while i < len(self.keys) and k > self.keys[i]:
i += 1
if i < len(self.keys) and self.keys[i] == k:
return (self, i)
if self.leaf:
return None
return self.children[i].search(k)
```
## 🤔 의사결정 기준 (Decision Criteria)
### Insert with split
```python
def split_child(parent, i):
t = parent.t
full = parent.children[i]
new = BTreeNode(t, full.leaf)
new.keys = full.keys[t:]
if not full.leaf:
new.children = full.children[t:]
full.children = full.children[:t]
parent.keys.insert(i, full.keys[t-1])
full.keys = full.keys[:t-1]
parent.children.insert(i+1, new)
**선택 A를 써야 할 때:**
- *(TODO)*
def insert(root, k):
if len(root.keys) == 2*root.t - 1:
new_root = BTreeNode(root.t)
new_root.children.append(root)
split_child(new_root, 0)
root = new_root
insert_nonfull(root, k)
return root
```
**선택 B를 써야 할 때:**
- *(TODO)*
### B+ Tree range scan
```python
def range_scan(leaf, lo, hi):
out = []
node = leaf
while node:
for k in node.keys:
if lo <= k <= hi: out.append(k)
elif k > hi: return out
node = node.next # leaf-linked list
return out
```
**기본값:**
> *(TODO)*
### PostgreSQL B-Tree usage
```sql
CREATE INDEX idx_users_email ON users USING btree (email);
-- equality + range + sort 사용
EXPLAIN SELECT * FROM users WHERE email > 'a' AND email < 'm';
-- Index Scan using idx_users_email
```
## ❌ 안티패턴 (Anti-Patterns)
### SQLite WITHOUT ROWID (B-Tree direct)
```sql
CREATE TABLE kv (k TEXT PRIMARY KEY, v BLOB) WITHOUT ROWID;
-- 매 data가 매 PK index 자체에 — 매 secondary lookup 제거
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### Bulk loading (sorted insert)
```python
def bulk_load(sorted_pairs, t=64):
# Sort + bottom-up build (vs O(n log n) per-insert)
leaves = [sorted_pairs[i:i+2*t-1]
for i in range(0, len(sorted_pairs), 2*t-1)]
# build internal levels...
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| OLTP, point + range query | B+ Tree (default) |
| Append-heavy timeseries | LSM (RocksDB) — B-Tree write amp 高 |
| In-memory only, no range | Hash index |
| Vector similarity | HNSW (not B-Tree) |
| Spatial | R-Tree / GiST |
**기본값**: 매 RDBMS index는 매 B+ Tree. 매 SSD/NVMe에서도 매 page-aligned (8KB-16KB) 노드.
## 🔗 Graph
- 부모: [[Linked-Lists-and-Trees]] · [[Theoretical-Computer-Science]]
- 변형: [[Hash-Functions-and-Maps]] (alternative)
- 응용: Database-Index · [[Bloom-Filters in Search]]
- Adjacent: [[Algorithm-Complexity-Big-O]] · LSM-Tree
## 🤖 LLM 활용
**언제**: 매 DB schema design, 매 "왜 query가 slow?" debugging, 매 index choice review.
**언제 X**: 매 in-memory + write-heavy → LSM 우선; 매 vector search → HNSW.
## ❌ 안티패턴
- **Random UUID v4 PK**: 매 B-Tree에 매 random insert → 매 page split storm. 매 UUIDv7 (time-ordered) 사용.
- **Over-indexing**: 매 모든 column에 index — 매 write amp + storage 폭증.
- **Index on low-cardinality**: 매 boolean column index — 매 useless, full scan 더 빠름.
## 🧪 검증 / 중복
- Verified (Bayer 1972 original paper, PostgreSQL docs Ch.62).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — B-Tree/B+Tree, split logic, DB index |