Running a lot of agent sessions ends up being CPU, memory and disk space intensive
especially for opencode, a lot of .so files end up filling disk space
OpenCode .so File Leak & CPU Investigation
OpenCode: 1.3.17 (embeds Bun v1.3.11) | System: Linux x86-64, 12 cores, 22GB RAM
AO (Agent Orchestrator): @composio/ao | Related: anomalyco/opencode#21427
Summary
Every opencode process extracts identical copies of libopentui.so (4.3MB) to /tmp with random filenames and never deletes them. AO compounds this by spawning opencode session list processes from 7 independent call sites — up to 23 concurrent processes observed. Result: ~3,000 leaked files/hour (~13 GB/hour), disk full in ~36 hours, sustained CPU overload.
1. What leaks: libopentui.so extracted to /tmp, never cleaned up
All leaked .so files are byte-for-byte identical — only 2 unique hashes across 1,300+ files (libopentui.so + librust_pty.so):
$ find /tmp -maxdepth 1 -name '.fcbcf*-00000000.so' | head -5 | xargs md5sum
b937f51f51f919d80cdbb94e5486f51f /tmp/.fcbcf6cf9beaddad-00000000.so
b937f51f51f919d80cdbb94e5486f51f /tmp/.fcbcf7178bbcfc8d-00000000.so
b937f51f51f919d80cdbb94e5486f51f /tmp/.fcbcf6571fbdfcff-00000000.so
b937f51f51f919d80cdbb94e5486f51f /tmp/.fcbcf66f3ef8c78d-00000000.so
b937f51f51f919d80cdbb94e5486f51f /tmp/.fcbcf6f7bbbad4cd-00000000.so
$ ls -la /tmp/.fcbcf*-00000000.so | head -3
-rw-r--r-- 1 user user 4467856 Apr 9 19:53 /tmp/.fcbcf6571fbdfcff-00000000.so
-rw-r--r-- 1 user user 4467856 Apr 9 19:55 /tmp/.fcbcf66f3ef8c78d-00000000.so
-rw-r--r-- 1 user user 4467856 Apr 9 20:02 /tmp/.fcbcf6cf9beaddad-00000000.so
The file comes from @opentui/[email protected] embedded inside the opencode binary:
$ strings ~/.opencode/bin/opencode | grep -i 'opentui.*core\|bunfs.*\.so'
// ../../node_modules/.bun/@[email protected]/node_modules/@opentui/core-linux-x64/libopentui.so
module2.exports = "/$bunfs/root/libopentui-ayp6xrpn.so";
Bun's /$bunfs/root/ virtual filesystem extracts this to /tmp at startup. The file is dlopen()'d and memory-mapped — confirmed via /proc/PID/map_files/:
$ ls -la /proc/<opencode_pid>/map_files/ | grep '/tmp/'
lr-------- 1 user user 64 Apr 9 20:11 7c5601600000-7c560164b000 -> /tmp/.fcbcf7f77eeddeef-00000000.so
lr-------- 1 user user 64 Apr 9 20:11 7c560164b000-7c56016cb000 -> /tmp/.fcbcf7f77eeddeef-00000000.so
On exit, unlink() is never called. This is loaded eagerly even in headless modes like opencode session list --format json where no TUI rendering occurs. Known Bun bug (oven-sh/bun#19550), fix may have regressed.
2. Each opencode invocation leaks 2–7 new files
Controlled test — 3 manual opencode session list runs:
before_run_1: .so_count=1364
after_run_1: .so_count=1369 (delta=+5)
after_run_2: .so_count=1376 (delta=+7)
after_run_3: .so_count=1378 (delta=+2)
total_new_so_from_3_invocations: 14
3. AO spawns opencode session list from 7 call sites — producing 23+ concurrent processes
Source: fetchOpenCodeSessionList() spawns a new process every call
// @composio/ao-core/dist/session-manager.js:65
const { stdout } = await execFileAsync("opencode", ["session", "list", "--format", "json"], {
timeout: timeoutMs, // OPENCODE_DISCOVERY_TIMEOUT_MS = 2000
});
All 7 call sites (traced from source)
| # | Trigger | Source | Processes |
|---|---|---|---|
| 1 | Lifecycle poll (every 30s) | lifecycle-manager.js:663 → sessionManager.list() |
1 per poll |
| 2 | Per-session enrichment in list() |
session-manager.js:1198 ??= fetchOpenCodeSessionList() |
1 (shared within one list() call) |
| 3 | getOpenCodeSessionUpdatedAt() in enrichment |
session-manager.js:1507 via waitForInteractiveReadiness() |
1 per session (NOT shared) |
| 4 | ao send delivery confirmation |
session-manager.js:1631+1639 |
Up to 7 per message |
| 5 | ao status CLI |
ao-cli/commands/status.js:161 → sm.list() |
1 |
| 6 | ao session ls CLI |
ao-cli/commands/session.js:23 → sm.list() |
1 |
| 7 | ao spawn CLI |
ao-cli/commands/spawn.js:264 + plugin lines 184,220 |
Up to 3 |
The critical amplifier: ao send confirmation loop
// session-manager.js:153-154
const SEND_CONFIRMATION_ATTEMPTS = 6;
const SEND_CONFIRMATION_POLL_MS = 500;
// line 1631: baseline
const baselineUpdatedAt = await getOpenCodeSessionUpdatedAt(); // ← 1 process spawned
// line 1633-1639: retry loop
for (let attempt = 1; attempt <= SEND_CONFIRMATION_ATTEMPTS; attempt++) {
await sleep(SEND_CONFIRMATION_POLL_MS);
const updatedAt = await getOpenCodeSessionUpdatedAt(); // ← 1 process each
Each getOpenCodeSessionUpdatedAt() calls fetchOpenCodeSessionList() → spawns a fresh opencode process. One ao send = up to 7 processes over ~3 seconds.
The feedback loop: orchestrator agent runs ao commands from its shell
The orchestrator is an opencode TUI running in tmux. Its system prompt references ao status/ao session/ao send 30 times, instructing it to monitor workers frequently:
// @composio/ao-core/dist/orchestrator-prompt.js
"Inspect with read-only commands such as `ao status`, `ao session ls`..."
"Check `ao status` for sessions in 'stuck' or 'needs_input' state"
Each ao CLI command internally calls fetchOpenCodeSessionList():
orchestrator (opencode TUI in tmux)
└── runs: `ao status`
└── calls: sm.list() → spawns: `opencode session list --format json`
How they pile up (example 30s window)
[t=0s] pollAll() → 1 + 2 enrichment = 3 processes
[t=2s] orchestrator: ao status → 1 + 2 enrichment = 6
[t=5s] orchestrator: ao send → 1 + 6 retries = 13
[t=10s] orchestrator: ao status → 1 + 2 enrichment = 16
[t=15s] orchestrator: ao send → 7 = 23
(previous processes still alive — each takes ~2-3s)
4. Observed impact
Real-time .so growth (1-second resolution, 2 opencode sessions active)
20:10:34 | .so_count=1364 | session_list_procs=3
20:10:37 | .so_count=1364 | session_list_procs=9
20:10:38 | .so_count=1366 | session_list_procs=10
20:10:39 | .so_count=1369 | session_list_procs=8
20:10:44 | .so_count=1372 | session_list_procs=8
20:10:46 | .so_count=1376 | session_list_procs=5
20:10:52 | .so_count=1379 | session_list_procs=3
20:10:55 | .so_count=1383 | session_list_procs=1
20:10:59 | .so_count=1386 | session_list_procs=2
+22 files in 26 seconds. Up to 10 concurrent opencode session list processes.
CPU snapshot (23 concurrent processes observed)
$ ps aux --sort=-%cpu | head -8
USER PID %CPU %MEM VSZ RSS COMMAND
user 544234 64.8 1.1 74167808 268320 opencode session list --format json
user 544236 60.8 1.1 74166840 269496 opencode session list --format json
user 544129 52.3 1.2 74166784 290024 opencode session list --format json
user 544094 51.8 1.1 74166816 268984 opencode session list --format json
user 544275 51.2 0.8 73863168 191880 opencode session list --format json
user 544232 51.2 0.9 74170896 219636 opencode session list --format json
...16 more identical processes (23 total, system load: 48.04 on 12 cores)
Memory
$ free -h
Swap: 2.0Gi 2.0Gi 384Ki ← 100% full
Each opencode session list process: ~300MB RSS, ~74GB VSZ.
Before/after AO start
| Metric | Before AO | After 22 min |
|---|---|---|
.so files |
335 | 1,310 |
/tmp size |
1.5 GB | 5.6 GB |
| System load | 1.05 | 4.44 |
Projected impact
| Metric | Value |
|---|---|
.so growth |
~3,000 files/hour |
| Disk growth | ~13 GB/hour |
| Time to fill 468GB disk | ~36 hours |
Avg CPU burned by session list |
~2.9 cores (172 process-seconds in 60s) |
| Peak concurrent processes | 23 |
| Peak system load | 48.04 (12-core machine) |
Workarounds
# 1. Redirect temp files + periodic cleanup
export BUN_TMPDIR=~/.opencode/tmp
mkdir -p ~/.opencode/tmp
# crontab: */15 * * * * find ~/.opencode/tmp -name '*.so' -mmin +5 -delete
# 2. Use `opencode run` instead of TUI mode in AO worker sessions
# Still leaks .so files but avoids TUI overhead
Permanent fixes:
- Opencode: upgrade embedded Bun to a version that auto-cleans temp files on exit
- Opencode: lazy-load
@opentui/coreonly when TUI rendering is actually needed - Opencode: extract to a deterministic path (e.g., content-hash filename) so all processes share one
.sofile instead of each creating a random-named copy - AO: cache
fetchOpenCodeSessionList()with a short TTL — currently every call spawns a fresh process. A 5-second cache would collapse most concurrent calls into one. The??=pattern inlist()only deduplicates within a singlelist()invocation — separate triggers (poll, CLI, send) each spawn independently - AO:
ao sendconfirmation should not spawn processes —getOpenCodeSessionUpdatedAt()spawns up to 7opencode session listprocesses just to check a timestamp. It could instead read the tmux pane output or check session JSONL files on disk — both already available locally
Appendix: Run It Yourself — Evidence Commands
Copy-paste these commands to verify each finding on your own machine. All are read-only (except the cleanup commands at the end).
1. See how many leaked .so files exist right now
# Count them
find /tmp -maxdepth 1 -name '.*-00000000.so' 2>/dev/null | wc -l
# Total disk usage
find /tmp -maxdepth 1 -name '.*-00000000.so' -exec du -ch {} + 2>/dev/null | tail -1
# List the 10 newest (shows they keep appearing)
find /tmp -maxdepth 1 -name '.*-00000000.so' -printf '%T+ %s %f\n' 2>/dev/null | sort -r | head -10
2. Prove all .so files are identical
# Pick any 5 random files and md5sum them — all hashes will match
find /tmp -maxdepth 1 -name '.*-00000000.so' 2>/dev/null | shuf | head -5 | xargs md5sum
3. Prove the file is libopentui.so from @opentui/core
# Pick any leaked .so file and run strings on it — look for opentui markers
SAMPLE=$(find /tmp -maxdepth 1 -name '.*-00000000.so' 2>/dev/null | head -1)
strings "$SAMPLE" | grep -i 'opentui'
# Also look for Zig/Ghostty markers (opentui wraps libghostty)
strings "$SAMPLE" | grep -i 'ghostty' | head -5
strings "$SAMPLE" | grep -i 'text_buffer\|rope\|terminal' | head -10
4. Prove opencode processes have the files open
# Show which processes have .so files open in /tmp
lsof +D /tmp 2>/dev/null | grep '\.so$' | head -20
# Or more targeted:
lsof /tmp/.*-00000000.so 2>/dev/null | head -20
5. Prove the .so is memory-mapped (not just opened)
# Get any running opencode PID
OC_PID=$(pgrep -f 'opencode' | head -1)
# Show its memory-mapped files from /tmp
ls -la /proc/$OC_PID/map_files/ 2>/dev/null | grep '/tmp/'
# Or via /proc/PID/maps
grep '/tmp/.*\.so' /proc/$OC_PID/maps 2>/dev/null | head -5
6. Watch .so files appear in real time (run with AO active)
# Count every second for 60 seconds — watch the number climb
for i in $(seq 1 60); do
COUNT=$(find /tmp -maxdepth 1 -name '.*-00000000.so' 2>/dev/null | wc -l)
echo "$(date +%H:%M:%S) — $COUNT .so files"
sleep 1
done
7. Prove a single opencode session list creates new files
# Snapshot before
BEFORE=$(find /tmp -maxdepth 1 -name '.*-00000000.so' 2>/dev/null | wc -l)
# Run the command
opencode session list --format json >/dev/null 2>&1
# Snapshot after
AFTER=$(find /tmp -maxdepth 1 -name '.*-00000000.so' 2>/dev/null | wc -l)
echo "Before: $BEFORE — After: $AFTER — New files: $((AFTER - BEFORE))"
8. See the mass process spawning (CPU cause)
# How many opencode processes right now?
pgrep -afc 'opencode'
# Full details with CPU/MEM
ps aux | grep '[o]pencode' | head -20
# System load vs core count
echo "Load: $(cat /proc/loadavg) — Cores: $(nproc)"
9. See memory/swap pressure
free -h
# Top swap consumers
for pid in $(ls /proc/ | grep '^[0-9]'); do
if [ -f /proc/$pid/smaps_rollup ] 2>/dev/null; then
SWAP=$(awk '/^Swap:/{print $2}' /proc/$pid/smaps_rollup 2>/dev/null)
if [ "$SWAP" -gt 50000 ] 2>/dev/null; then
CMD=$(cat /proc/$pid/cmdline 2>/dev/null | tr '\0' ' ' | cut -c1-60)
echo "${SWAP}kB PID=$pid $CMD"
fi
fi
done 2>/dev/null | sort -rn | head -10
10. Find the AO polling source code yourself
# The 30-second polling interval
grep -n 'setInterval.*pollAll\|intervalMs.*30' \
~/.nvm/versions/node/*/lib/node_modules/@composio/ao/node_modules/@composio/ao-core/dist/lifecycle-manager.js
# The opencode process spawn
grep -n 'execFileAsync.*opencode\|session.*list.*json' \
~/.nvm/versions/node/*/lib/node_modules/@composio/ao/node_modules/@composio/ao-core/dist/session-manager.js
11. Prove opencode embeds Bun v1.3.11
strings ~/.opencode/bin/opencode | grep -oP 'bun-v\d+\.\d+\.\d+' | sort -u
strings ~/.opencode/bin/opencode | grep '@opentui/core' | head -3
12. Check disk usage before and after cleanup
# Current disk state
df -h /
# Count + size of leaked files
echo "Files: $(find /tmp -maxdepth 1 -name '.*-00000000.so' 2>/dev/null | wc -l)"
find /tmp -maxdepth 1 -name '.*-00000000.so' -exec du -ch {} + 2>/dev/null | tail -1
13. Cleanup commands (⚠️ these DELETE files)
# Delete all leaked .so files
find /tmp -maxdepth 1 -name '.*-00000000.so' -delete
# Also delete the .node files (same leak, different extension)
find /tmp -maxdepth 1 -name '.*-00000001.node' -delete
# Verify
df -h /
Tip: Run commands 6 and 7 side-by-side to see the leak happening live. Command 6 in one terminal, command 7 in another — you'll see the count jump each time.
New Report — RAM-specific investigation
Reported by: @Ashish in Discord
Date: 2026-04-21
Analyzed against: 59f66f4d (origin/main)
Root Cause Analysis
Deep code trace across lifecycle-manager, session-manager, SSE stream, observability, and terminal modules. No single dramatic leak — it's cumulative pressure from multiple sources:
1. SSE polling amplification (primary suspect)
Each connected SSE client (/api/events/route.ts) creates its own 2-second polling interval calling sessionManager.list(). That list() call reads all session metadata from disk, creates full Session objects, enriches them via execFile for runtime state, and serializes them. With N browser tabs, list() runs N times independently every 2 seconds — no deduplication.
2. Observability snapshot write amplification
observability.ts — every recordOperation() does a synchronous file read + mutate + atomic write + append to the snapshot JSON. The lifecycle manager records multiple operations per poll cycle, and SSE records per-client. This blocks the event loop, preventing timely GC.
3. processedIssues set (unbounded growth)
services.ts line 172 — processedIssues is a Set<string> at module scope. Every projectId:issueId pair is added but never evicted. Grows monotonically for process lifetime.
4. snapshot.metrics keys (no eviction)
observability.ts — snapshot.metrics uses composite keys projectId::metricName. Keys are never evicted when projects are removed, so stale entries accumulate indefinitely.
Well-managed areas (not leaking)
- Lifecycle manager maps (
states,reactionTrackers,prEnrichmentCache) — pruned every poll cycle against active sessions ✅ - Terminal/PTY streams — proper cleanup on disconnect, ring buffer capped at 50KB ✅
- Session cache — TTL of 35 seconds, invalidated on mutations ✅
- Traces/sessions snapshots — bounded (80/200 entries) ✅
Suggested Fixes
- SSE deduplication — share a single polling interval across all SSE clients, broadcast one
list()result to all connected streams - Increase SSE poll interval — 2s is aggressive; 5–10s or change-detection would reduce allocation pressure
- Batch observability writes — coalesce multiple
recordOperation()calls per poll cycle into one snapshot write - Add
processedIssueseviction — cap set size or clear entries older than N hours - Add metrics key eviction — prune stale
projectId::metricNameentries periodically
Solved, closed by #1478