[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,109 +2,213 @@
id: wiki-2026-0508-execution-environment-sandbox
title: Execution Environment (Sandbox)
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: []
aliases: [sandbox, code execution sandbox, container, gVisor, Firecracker, WASM, code interpreter]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [uncategorized]
confidence_score: 0.94
verification_status: applied
tags: [security, sandbox, isolation, container, wasm, llm-tool, execution]
raw_sources: []
last_reinforced: 2026-05-08
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: Universal
framework: Docker / Firecracker / gVisor / WASM / E2B
---
# [[Execution Environment (Sandbox)|Execution Environment (Sandbox)]]
# Execution Environment (Sandbox)
## 📌 한 줄 통찰 (The Karpathy Summary)
Execution Environment(또는 Sandbox)는 에이전트가 생성한 코드를 실행하거나, 파일을 조작하고, 네트워크에 접근할 때 호스트 시스템으로부터 격리된 안전한 물리적/논리적 공간이다. 에이전트의 오작동이나 악의적인 공격(프롬프트 인젝션)으로 인한 호스트 시스템 오염, 데이터 유출, 자원 남용을 방지하기 위한 보안 방어선의 핵심이다.
## 한 줄
> **"매 untrusted code 의 isolated 의 run"**. 매 LLM 의 generate code → 매 host 의 보호. 매 levels: process → container → microVM → WASM. 매 modern: 매 Firecracker (AWS Lambda), gVisor (GKE), E2B (LLM agent), Code Interpreter.
## 📖 구조화된 지식 (Synthesized Content)
* **격리 기술 (Isolation Technologies)**:
* **Docker/Containers**: 프로세스 및 파일 시스템 수준의 격리 제공.
* **WASM (WebAssembly)**: 언어 수준의 초경량 격리 및 브라우저/서버 공통 실행 환경.
* **VM (Virtual Machines)**: 가장 강력한 격리 성능을 제공하나 리소스 소모가 큼.
* **Firecracker/gVisor**: 경량 VM 기술을 통해 컨테이너의 속도와 VM의 보안성을 결합.
* **자원 제어 (Resource Constraints)**: CPU 사용량, 메모리 할당량, 최대 실행 시간, 디스크 용량을 제한하여 DoS 공격이나 무한 루프를 방지한다.
* **네트워크 격리 (Network Air-gapping)**: 인터넷 접근을 완전히 차단하거나, 사전에 허용된 특정 도메인(Allowlist)에 대해서만 프록시를 통해 소통하게 제한한다.
* **가상 파일 시스템**: 에이전트가 호스트의 실제 파일에 직접 접근하지 못하게 하고, 하네스가 제공하는 가상 마운트 지점을 통해서만 파일을 읽고 쓰게 한다.
* **상태 휘발성 (Ephemeral Environment)**: 작업이 끝나면 샌드박스 전체를 삭제하여 잔류 데이터나 사이드 이펙트가 다음 작업에 영향을 미치지 않도록 한다.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
* **보안 vs 편의성**: 격리가 강화될수록 에이전트가 로컬 개발 환경의 도구나 라이브러리를 자유롭게 사용하는 데 제약이 발생한다.
* **성능 오버헤드**: 매번 새로운 샌드박스를 띄우고 라이브러리를 설치하는 과정에서 실행 지연(Latency)이 발생한다.
* **복잡한 상태 복구**: 샌드박스가 삭제될 때 중요한 작업 산출물이나 수정 사항을 안전하게 호스트로 옮기는 동기화 로직이 정교해야 한다.
### 매 isolation level
1. **Process** (chroot, seccomp): 매 weak.
2. **Container** (Docker): 매 namespace + cgroup.
3. **MicroVM** (Firecracker, gVisor): 매 hypervisor / user-space kernel.
4. **VM**: 매 strongest, 매 slow.
5. **WASM**: 매 capability-based, 매 portable.
## 🔗 지식 연결 (Graph)
### Related Concepts
* [[Agent Harness|Agent Harness]]
* 연결 이유: 샌드박스는 하네스가 명령을 내리는 물리적 실행 대상이다.
* [[Safety & Reliability|Safety & Reliability]]
* 연결 이유: 샌드박스는 시스템의 안정성을 보장하는 최후의 물리적 보루이다.
* [[E-component (Execution Loop)|E-component (Execution Loop)]]
* 연결 이유: 실행 루프에서 코드가 실행되는 실제 공간이다.
### 매 응용
1. **LLM code interpreter** (OpenAI, Claude, Anthropic).
2. **Serverless** (Lambda Firecracker).
3. **CI/CD** (GitHub Actions runner).
4. **Browser** (V8 isolate).
5. **Plugin sandbox** (Figma plugin = WASM).
6. **Agent tool** (E2B).
### Deeper Research Questions
* 에이전트가 샌드박스 내부에서 관리자 권한을 획득하여 호스트로 탈출(Escape)하려 할 때, 이를 커널 레벨에서 즉시 차단하는 감시 모델은 무엇인가?
* 초경량 WASM 샌드박스에서 Python의 복잡한 머신러닝 라이브러리(PyTorch 등)를 성능 저하 없이 실행하는 기술적 한계는 어디까지인가?
* 수천 명의 사용자가 동시에 에이전트를 사용할 때, 각 사용자별로 독립된 샌드박스를 수 밀리초(ms) 내에 생성하고 폐기하는 서버리스 아키텍처는 어떻게 설계하는가?
### 매 modern tool
- **Firecracker**: 매 microVM, 125ms startup.
- **gVisor**: 매 user-space kernel.
- **WASM**: 매 wasi, 매 capability.
- **E2B**: 매 LLM-targeted SDK.
- **Daytona**: 매 dev sandbox.
### Practical Application Contexts
* **Implementation:** Python의 `subprocess`나 Docker SDK를 사용하여 명령어를 실행하고 결과를 캡처하며, `resource` 모듈을 통해 메모리를 제한한다.
* **System Design:** 에이전틱 코딩 툴 구축 시, 사용자의 로컬 파일 시스템을 읽기 전용으로 마운트하고 쓰기 작업은 샌드박스 내의 임시 폴더에서만 수행하게 한다.
## 💻 패턴
---
*Last updated: 2026-05-01*
## 🤖 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
### Docker (basic)
```bash
docker run --rm \
--user 1000:1000 \
--read-only \
--tmpfs /tmp \
--network none \
--memory 256m --cpus 0.5 \
--cap-drop ALL \
--security-opt no-new-privileges \
python:3.12-slim python -c "$CODE"
```
## 🤔 의사결정 기준 (Decision Criteria)
### gVisor (runsc)
```bash
docker run --runtime=runsc python:3.12 python -c "$CODE"
```
**선택 A를 써야 할 때:**
- *(TODO)*
### Firecracker (programmatic)
```python
import requests
def boot_microvm(rootfs, kernel):
sock = '/tmp/firecracker.socket'
requests.put(f'http+unix://{sock}/boot-source', json={'kernel_image_path': kernel})
requests.put(f'http+unix://{sock}/drives/rootfs', json={'drive_id': 'rootfs', 'path_on_host': rootfs, 'is_root_device': True, 'is_read_only': False})
requests.put(f'http+unix://{sock}/actions', json={'action_type': 'InstanceStart'})
```
**선택 B를 써야 할 때:**
- *(TODO)*
### WASM (Wasmer / Wasmtime)
```rust
use wasmer::{Store, Module, Instance, imports};
let mut store = Store::default();
let module = Module::from_file(&store, "guest.wasm")?;
let imports = imports! {}; // 매 default = no host access
let instance = Instance::new(&mut store, &module, &imports)?;
let func = instance.exports.get_function("run")?;
func.call(&mut store, &[])?;
```
**기본값:**
> *(TODO)*
### WASI capability (file)
```rust
// 매 explicit 매 path 의 grant 만
let wasi = WasiState::new("agent")
.preopen_dir("/sandbox-fs")?
.build()?;
```
## ❌ 안티패턴 (Anti-Patterns)
### E2B (LLM-targeted)
```python
from e2b_code_interpreter import Sandbox
with Sandbox() as sb:
result = sb.run_code('import pandas; print(pandas.__version__)')
print(result.stdout)
sb.files.write('/data/output.csv', csv_content)
sb.files.read('/data/output.csv')
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### Resource limit (cgroups, Linux)
```bash
cgcreate -g cpu,memory:sandbox
cgset -r memory.max=256M sandbox
cgset -r cpu.max="50000 100000" sandbox # 매 50% of one core
cgexec -g cpu,memory:sandbox python untrusted.py
```
### Seccomp (syscall filter)
```python
import seccomp
filter = seccomp.SyscallFilter(seccomp.KILL)
for sc in ['read', 'write', 'open', 'close', 'mmap', 'brk', 'exit', 'exit_group']:
filter.add_rule(seccomp.ALLOW, sc)
filter.load()
```
### Time-out enforcement
```python
import resource, signal
def run_sandboxed(code, time_limit_s=30, mem_limit_mb=512):
def sandbox_init():
resource.setrlimit(resource.RLIMIT_AS, (mem_limit_mb * 1024 * 1024,) * 2)
resource.setrlimit(resource.RLIMIT_CPU, (time_limit_s,) * 2)
proc = subprocess.run(
['python', '-c', code],
preexec_fn=sandbox_init,
timeout=time_limit_s,
capture_output=True,
)
return proc.stdout
```
### Network egress block
```bash
docker run --network none ...
# 매 or specific allowlist
docker network create --internal sandboxed
docker run --network sandboxed ...
```
### Capability-based (Deno)
```bash
deno run --allow-read=/tmp --allow-write=/tmp --no-net script.ts
```
### LLM tool integration
```python
def llm_python_tool(code):
with Sandbox(timeout=60, mem_mb=512) as sb:
try:
result = sb.run_code(code)
return {'stdout': result.stdout, 'stderr': result.stderr}
except TimeoutError:
return {'error': 'execution timed out'}
```
### Snapshot for fast warmup
```python
# 매 Firecracker snapshot
def restore_microvm_from_snapshot(snapshot_path):
requests.put('/snapshot/load', json={'snapshot_path': snapshot_path})
# 매 < 100ms cold start
```
## 매 결정 기준
| 상황 | Sandbox |
|---|---|
| LLM code agent | E2B / Firecracker |
| Plugin (browser) | V8 Isolate / WASM |
| Serverless | Firecracker |
| CI runner | Container + ephemeral |
| Dev environment | Daytona / Codespaces |
| Strict isolation | MicroVM (Firecracker) |
| Lightweight | WASM |
**기본값**: 매 LLM agent = E2B 또는 Firecracker + 매 read-only fs + 매 no network + 매 cgroup limit + 매 timeout.
## 🔗 Graph
- 부모: [[Security]] · [[Isolation]]
- 변형: [[MicroVM]] · [[Container]] · [[WASM]]
- 응용: [[LLM-Code-Interpreter]] · [[Serverless]] · [[Plugin-System]]
- Adjacent: [[Excessive Agency]] · [[Capability-Security]] · [[gVisor]] · [[Firecracker]]
## 🤖 LLM 활용
**언제**: 매 code-executing agent. 매 user code. 매 plugin.
**언제 X**: 매 trusted internal-only.
## ❌ 안티패턴
- **chroot only**: 매 escape easy.
- **--privileged**: 매 isolation 의 lose.
- **Network on**: 매 exfil.
- **No timeout**: 매 fork bomb.
- **Shared volume**: 매 host file 의 leak.
## 🧪 검증 / 중복
- Verified (Firecracker paper, gVisor docs, WASM/WASI spec).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — sandbox + 매 Docker / Firecracker / WASM / E2B / cgroup code |