---
id: wiki-2026-0508-incremental-computation
title: Incremental Computation
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [Incremental Build, Memoization, Salsa, Adapton]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
verification_status: applied
tags: [incremental, memoization, build-systems, reactive]
raw_sources: []
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
  language: rust
  framework: salsa
---

# Incremental Computation

## 매 한 줄
> **"매 unchanged 매 recompute X"**. Incremental computation 매 prior result 의 reuse — 매 input change 만 propagate. 매 2026 rust-analyzer (Salsa), Bazel, Buck2, Turbopack 매 standard. 매 trade-off: 매 memory vs recompute time.

## 매 핵심

### 매 mechanism 분류
- **Memoization**: 매 (input → output) cache. 매 pure function 필수.
- **Demand-Driven**: 매 query-based; pull 시 dependency graph 추적 (Salsa, Adapton).
- **Change-Driven**: 매 push; input change → invalidate downstream (React reactivity).
- **Self-Adjusting Computation**: 매 Acar — formal foundation, dynamic dependency graph.

### 매 invalidation strategy
- **Hash-based**: 매 input fingerprint compare (Bazel digest).
- **Timestamp**: 매 mtime check (make).
- **Reference equality**: 매 pointer compare (React).
- **Structural diff**: 매 deep equal (immer, Redux).

### 매 응용
1. 매 build systems (Bazel, Buck2).
2. 매 IDE backends (rust-analyzer, TypeScript LSP).
3. 매 reactive UI (React, SolidJS signals).
4. 매 dataflow / spreadsheets.

## 💻 패턴

### 1. Salsa Query (Rust)
```rust
#[salsa::query_group(CompilerStorage)]
pub trait Compiler: salsa::Database {
    #[salsa::input]
    fn source_text(&self, file: FileId) -> Arc<String>;

    fn parse(&self, file: FileId) -> Arc<Ast>;
    fn type_check(&self, file: FileId) -> Arc<TypeMap>;
}

fn parse(db: &dyn Compiler, file: FileId) -> Arc<Ast> {
    let text = db.source_text(file);  // 매 dependency tracked
    Arc::new(parse_text(&text))
}
// 매 source_text unchanged → parse skipped automatically
```

### 2. Memoization with LRU
```python
from functools import lru_cache

@lru_cache(maxsize=10_000)
def expensive(x: int, y: int) -> int:
    return slow_compute(x, y)

# 매 hash(args) → cached result; LRU evict oldest
```

### 3. React useMemo (Reference Equality)
```jsx
const expensive = useMemo(() => {
  return items.filter(i => i.active).sort();
}, [items]);  // 매 items reference unchanged → skip
```

### 4. Bazel Action Cache
```python
# WORKSPACE — 매 each action keyed by:
# hash(inputs) + hash(command) + hash(env)
# Output stored in CAS (content-addressable storage)
# Remote cache — 매 distributed reuse across team
```

### 5. Self-Adjusting Computation (OCaml-style)
```ocaml
let m = Mod.create ()
let a = Var.create m 1
let b = Var.create m 2
let sum = Mod.bind m (fun () -> Var.read a + Var.read b)
Var.write a 10  (* sum auto-recomputes only its branch *)
```

### 6. Incremental Diff (Patch Generation)
```typescript
function diff<T>(old: T[], new_: T[]): Patch[] {
  // 매 Myers diff — O(ND) — minimal edit script
  // 매 used by git, react reconciler, immer
}
```

### 7. Signal-Based Reactivity (SolidJS)
```javascript
const [count, setCount] = createSignal(0);
const doubled = createMemo(() => count() * 2);
// 매 fine-grained — only doubled recomputes when count changes
// 매 NO virtual DOM diff
```

## 매 결정 기준
| 상황 | Approach |
|---|---|
| Pure function repeat | `lru_cache` / memoize |
| Compiler / IDE | Salsa, Adapton |
| UI reactivity | Signals (Solid) > Virtual DOM (React) |
| Build system | Bazel / Buck2 / Turbo |
| Stream pipeline | Materialize, ksqlDB |

**기본값**: 매 pure function memoize, 매 large pipeline 매 Salsa pattern.

## 🔗 Graph
- 부모: [[Theoretical-Computer-Science]] · [[Algorithm-Complexity-Big-O]]
- 변형: [[Memoization]]
- Adjacent: [[Dynamic-Programming]]

## 🤖 LLM 활용
**언제**: 매 build pipeline design, 매 query system architecture, 매 cache invalidation logic.
**언제 X**: 매 input always changes (no reuse benefit), 매 memory-constrained embedded.

## ❌ 안티패턴
- **Cache invalidation bug**: 매 stale result return. 매 dependency graph correctness 매 critical.
- **Unbounded memo**: 매 OOM. 매 LRU/TTL bound 필수.
- **Impure function memo**: 매 random()/now() 매 cache 시 incorrect.
- **Over-fine-grained**: 매 cache overhead > recompute cost.

## 🧪 검증 / 중복
- Verified (Acar, *Self-Adjusting Computation*; Salsa docs; Bazel design).
- 신뢰도 A.

## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Salsa/Bazel/SolidJS patterns + decision matrix |
