[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
@@ -2,63 +2,174 @@
id: wiki-2026-0508-directed-acyclic-graph-dependenc
title: Directed Acyclic Graph Dependency Management
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [DAG-001]
aliases: [DAG, Build Graph, Task Dependency, Topological Sort]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [computer-science, Graph-Theory, data-structures, workflow]
confidence_score: 0.94
verification_status: applied
tags: [DAG, dependency, build-system, scheduler, topological-sort]
raw_sources: []
last_reinforced: 2026-04-26
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: python
framework: networkx/airflow
---
# Directed Acyclic Graph (DAG, 유향 비순환 그래프)
# Directed Acyclic Graph Dependency Management
## 📌 한 줄 통찰 (The Karpathy Summary)
> "순환하지 않는 방향성 — 작업의 순서와 의존성을 정의하는 가장 완벽한 수학적 모델."
## 한 줄
> **"매 DAG = nodes (tasks) + directed edges (must-run-before) + 매 cycle 금지"**. 매 1960s Make 의 build graph 부터 매 2026 Airflow/Dagster pipelines, Bazel/Turborepo monorepo, Spark physical plan, Git commit history, React fiber tree 까지 — 매 dependency resolution 의 universal data structure.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** 노드 간의 방향은 존재하되, 어떤 노드에서 출발해도 다시 자기 자신으로 돌아오는 경로(Cycle)가 없는 구조를 통해 순차적 실행과 계층 관계를 보장하는 패턴.
- **세부 내용:**
- **Topo[[Logic|Logic]]al Sort:** DAG의 노드들을 의존성에 따라 일렬로 정렬하는 알고리즘 (빌드 시스템, 태스크 스케줄링의 핵심).
- **Dependency [[Management|Management]]:** 특정 작업이 완료되어야 다음 작업이 시작될 수 있는 인과 관계를 명확히 표현.
- **Data Pipelines:** Spark, Airflow 등 현대 데이터 엔지니어링 도구에서 데이터의 흐름을 정의하는 표준 모델.
- **Version Control:** Git의 커밋 히스토리는 부모-자식 관계를 가진 거대한 DAG 구조임.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 단순 트리(Tree) 구조보다 복잡한 관계를 표현할 수 있으면서도, 순환 구조(Graph)가 주는 무한 루프 위험을 제거한 실용적 타협점.
- **정책 변화:** Antigravity 프로젝트의 '지식 연결 그래프'는 기본적으로 순환을 허용하나, '실행 워크플로우'는 엄격한 DAG 규칙을 따름.
### 매 핵심 연산
- **Topological Sort**: 매 valid execution order. Kahn's O(V+E) or DFS.
- **Cycle Detection**: 매 DAG validity check.
- **Transitive Reduction**: 매 minimal edge set with same reachability.
- **Critical Path**: 매 longest path = makespan lower bound.
- **Incremental Recompute**: 매 dirty subgraph 만 재실행.
## 🔗 지식 연결 (Graph)
- **Parent:** 10_Wiki/💡 Topics/AI
- **Related:** Topological-Sort, [[Graph-Theory|Graph-Theory]], Workflow-Automation
- **Raw Source:** 10_Wiki/Topics/AI/Directed-Acyclic-Graph-Dependency-Management.md
### 매 응용
1. **Build systems**: Make, Bazel, Buck, Turborepo, Nx.
2. **Workflow orchestration**: Airflow, Dagster, Prefect, Argo Workflows.
3. **ML training pipelines**: Kubeflow, MLflow, ZenML.
4. **Spreadsheet recalc**: Excel, Google Sheets formula engine.
5. **VCS**: Git commit DAG, Mercurial.
6. **React/Solid reactivity**: 매 signal dependency graph.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 schedule strategies
- **List scheduling**: 매 ready tasks → workers (greedy).
- **HEFT**: 매 heterogeneous earliest finish time (cloud).
- **Critical Path Method (CPM)**: 매 longest path 기반 prioritization.
- **Work-stealing**: 매 dynamic load balancing (Tokio, Rayon).
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### Topological Sort (Kahn's Algorithm)
```python
from collections import deque, defaultdict
## 🧪 검증 상태 (Validation)
def topo_sort(nodes, edges):
indegree = defaultdict(int)
graph = defaultdict(list)
for u, v in edges:
graph[u].append(v); indegree[v] += 1
queue = deque([n for n in nodes if indegree[n] == 0])
order = []
while queue:
u = queue.popleft(); order.append(u)
for v in graph[u]:
indegree[v] -= 1
if indegree[v] == 0: queue.append(v)
if len(order) != len(nodes): raise ValueError("Cycle detected")
return order
```
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
### Parallel DAG Executor (asyncio)
```python
import asyncio
async def run_dag(tasks, deps):
"""tasks: {name: async_fn}, deps: {name: [prereqs]}."""
completed = {}; pending = dict(deps)
async def run(name):
await asyncio.gather(*(completed[d] for d in deps.get(name, [])))
return await tasks[name]()
completed = {n: asyncio.create_task(run(n)) for n in tasks}
return await asyncio.gather(*completed.values())
```
## 🧬 중복 검사 (Duplicate Check)
### Incremental Build (Content-Hash)
```python
def needs_rebuild(node, hashes, prev_hashes):
own_hash = hash_inputs(node.sources, [hashes[d] for d in node.deps])
if prev_hashes.get(node.name) != own_hash:
hashes[node.name] = own_hash
return True
hashes[node.name] = own_hash
return False
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### Critical Path
```python
def critical_path(graph, durations):
order = topo_sort(graph.nodes, graph.edges)
earliest = {n: durations[n] for n in graph.nodes}
for u in order:
for v in graph.successors(u):
earliest[v] = max(earliest[v], earliest[u] + durations[v])
return max(earliest.values()), earliest
```
## 🕓 변경 이력 (Changelog)
### Cycle Detection (DFS)
```python
WHITE, GRAY, BLACK = 0, 1, 2
def has_cycle(graph):
color = {n: WHITE for n in graph}
def dfs(u):
color[u] = GRAY
for v in graph[u]:
if color[v] == GRAY: return True
if color[v] == WHITE and dfs(v): return True
color[u] = BLACK
return False
return any(dfs(n) for n in graph if color[n] == WHITE)
```
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
### Airflow DAG (Practical)
```python
from airflow.decorators import dag, task
from datetime import datetime
@dag(start_date=datetime(2026,1,1), schedule="@daily", catchup=False)
def etl():
@task
def extract(): return fetch()
@task
def transform(data): return clean(data)
@task
def load(clean): warehouse.write(clean)
load(transform(extract()))
etl()
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Build deterministic, hermetic | Bazel / Buck (content-hash) |
| Data pipeline, scheduled | Airflow / Dagster |
| Monorepo JS/TS | Turborepo / Nx |
| ML experiment tracking | Kubeflow / MLflow / ZenML |
| In-process reactive UI | Signals (Solid/Vue/Svelte) |
| Real-time stream graph | Flink / Spark Structured Streaming |
**기본값**: 매 explicit DAG (declarative) > 매 implicit ordering — 매 visualization + audit + parallel scheduling 가능.
## 🔗 Graph
- 부모: [[Graph Theory]] · [[Topological Sort]]
- 변형: [[Build Graph]] · [[Reactive Signal Graph]] · [[Workflow DAG]]
- 응용: [[Bazel]] · [[Airflow]] · [[Turborepo 환경 구성]] · [[Spark]]
- Adjacent: [[Critical-Path-Method]] · [[Job Scheduling]] · [[Incremental-Computation]]
## 🤖 LLM 활용
**언제**: 매 multi-step agent plan 의 dependency 표현, 매 RAG indexing pipeline orchestration.
**언제 X**: 매 cyclic feedback loop 가 본질적 (RL, gradient descent) — 매 DAG 외 unrolled iteration.
## ❌ 안티패턴
- **Hidden side effects**: 매 task 가 state 직접 mutate → 매 incremental build 깨짐.
- **Ignoring transitive dependencies**: 매 missing edge → race condition.
- **Single-task megasinks**: 매 fan-in bottleneck — 매 break into shards.
- **Cycle by feature flag**: 매 conditional dependencies 가 implicit cycle 만들 수 있음.
- **Over-fine granularity**: 매 nano-tasks → scheduler overhead > work.
## 🧪 검증 / 중복
- Verified (Kahn 1962; Bazel docs 2026; Airflow 3.x docs; CLRS Ch.22).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — full content with topo, parallel exec, incremental, Airflow |