Repository navigation
Description
Describe the bug
copilot --resume=<id> on a long-running session uses many GB of native memory, and it doesn't release it while idle. The cost grows linearly with the number of events in the session's events.jsonl. With 1 M events it uses about 4.4 GB, and with images in the history it reaches 13 GB.
The log keeps the full history, and compaction doesn't trim it. On resume, every event appears to be loaded and kept as an in-memory object. That costs about 3 KB of native memory per event, even when the event is tiny. The memory is almost entirely native malloc (Malloc Small in footprint), not the V8 heap (App-Specific Tag 16 stays at about 0.2–0.4 GB). So it comes from the Rust runtime (runtime.node), not from JavaScript.
I first saw this on a real long-running autopilot session (multi-GB events.jsonl, 8–11 GB on resume). Below is a fully synthetic reproduction: a Node script that writes a dummy session with the same event structure.
Results (synthetic sessions, macOS arm64, CLI 1.0.119)
Each row is one generated session, resumed in an isolated COPILOT_HOME and measured for 60 s with ps and footprint <pid>. Every turn writes 7 events: assistant.turn_start, assistant.message, tool.execution_start, tool.execution_complete, hook.start (postToolUse), hook.end and assistant.turn_end. There is also a user.message every 50 turns.
| generator args | events | events.jsonl |
peak RSS | idle footprint | Malloc Small | Malloc Large |
|---|---|---|---|---|---|---|
--turns 100 |
703 | 0.8 MiB | 291 MB | 144 MB | 41 MB | 14 MB |
--turns 15000 |
105 K | 126 MiB | 822 MB | 686 MB | 445 MB | 21 MB |
--turns 50000 |
351 K | 421 MiB | 1.8 GB | 1.6 GB | 1.35 GB | 64 MB |
--turns 150000 |
1.05 M | 1,264 MiB | 4.5 GB | 4.4 GB | 4.0 GB | 210 MB |
--turns 150000 --tool-output-bytes 64 |
1.05 M | 403 MiB | 3.2 GB | 3.1 GB | 2.6 GB | 210 MB |
--turns 150000 --checkpoint-every 150 |
1.05 M | 1,591 MiB | 4.9 GB | 4.7 GB | 4.3 GB | 210 MB |
--turns 150000 --images 1500 |
1.05 M | 4,126 MiB | 13.1 GB | 13 GB | 12 GB | 217 MB |
--turns 150000 --images 1500 --checkpoint-every 150 |
1.06 M | 4,471 MiB | 8.0 GB* | 13 GB | 13 GB | 209 MB |
* RSS is lower than the footprint because macOS compressed part of the memory; the footprint is the real cost.
What the table shows:
- Memory is linear in the number of events. 105 K → 351 K → 1.05 M events cost 0.69 → 1.65 → 4.4 GB.
- There is a large fixed cost per event. With 1.05 M events, cutting the file from 1,264 MiB to 403 MiB (64-byte tool outputs) only reduces memory from 4.4 to 3.1 GB, which leaves about 3 KB per event.
- Inline images cost about 3× their size. 1,500 images add about 2.9 GB of base64 to the file and about 8.6 GB of native memory, mostly as
Malloc Smallrather than one large allocation per image. - The process is idle (0% CPU) once loaded and keeps all of that memory.
- On a real session,
heap -sshowed tens of millions of live small blocks. There was about one 768 B, one 320 B and one 80 B block per event, plus millions of 16–48 B blocks. That looks like one record plus a generic JSON value tree kept for every event in history.sampleduring load is dominated bymalloc/free/memmove/reallocinruntime.nodeand N-API string marshalling (napi_get_value_string_utf16). - On a real session, a missing required field late in the file made resume fail with
Session file is corrupted (line N: missing field …), but only after RSS had already reached about 10 GB. The whole prefix is materialized before validation finishes.
Write-side problems that make events.jsonl grow faster than needed
These make the log, and therefore the resume cost, grow much faster in long sessions:
session.usage_checkpointgrows quadratically. Each checkpoint re-serializes the full cumulativeaccountingSnapshot, includingcodeChanges.filesModified, which only grows. Checkpoint N is O(N) in size, so the total is O(N²). On long sessions individual checkpoints reach about 1 MB each.session.binary_assetstores image bytes inline as base64, even though each event already carries asha256assetId. These are also the most expensive events to hold in memory (see the table).hook.startforpostToolUseduplicates the full tool result.input.toolResult.textResultForLlmandsessionLogrepeat whattool.execution_completealready stored, so every tool output is written at least twice.- The
stop_basherror lists every shell ever started in the session. Callingstop_bashon an already-stopped shell returns"shellId: X was already stopped via stop_bash.\n\nActive shell sessions:\n ...". That list includes completed shells with their full command text, because completed shells are never pruned from the registry. In a long session this one tool result can reach tens of MB. It's written toevents.jsonland also sent back to the model as the tool result.
Affected version
GitHub Copilot CLI 1.0.119 (Node v24.22.3)
Steps to reproduce the behavior
- Save the script below as
make-large-copilot-session.mjs. It uses only the Node standard library and writes dummy data into its ownCOPILOT_HOME. It never touches~/.copilot. - Generate a session:
It prints the session ID and the command to run.
node make-large-copilot-session.mjs --home ./copilot-home-repro --turns 150000 --images 1500
- Resume it:
The isolated home isn't signed in, so the CLI shows
COPILOT_HOME=$PWD/copilot-home-repro copilot --resume=<session-id>
Please use /login. That's expected and doesn't affect the result. - In another terminal, watch memory:
footprint $(pgrep -f "copilot --resume=<session-id>") # macOS ps -o rss= -p <pid>
- Memory climbs to about 13 GB within about 30 s and stays there while idle. Without
--images,--turns 150000gives about 4.4 GB.
make-large-copilot-session.mjs
#!/usr/bin/env node
// Generates a synthetic GitHub Copilot CLI session whose events.jsonl has the shape of a
// long-running agent session (many turns, each with a tool call), so that
// `copilot --resume=<id>` can be used to observe resume memory usage.
//
// All content is dummy filler; no real data is used.
//
// Usage:
// node make-large-copilot-session.mjs [--home DIR] [--turns N] [--tool-output-bytes N]
// [--images N] [--image-bytes N]
// [--checkpoint-every N] [--files-per-checkpoint N]
//
// Then:
// COPILOT_HOME=<DIR> copilot --resume=<printed session id>
//
// COPILOT_HOME isolates the synthetic session from your real ~/.copilot. The isolated home
// is not signed in (the CLI shows "Please use /login"); that doesn't matter here, because
// the memory growth happens while the session loads, before any request is made.
import fs from "node:fs";
import path from "node:path";
import crypto from "node:crypto";
const args = Object.fromEntries(
process.argv.slice(2).reduce((acc, a, i, all) => {
if (a.startsWith("--")) acc.push([a.slice(2), all[i + 1]]);
return acc;
}, []),
);
const num = (k, d) => (args[k] !== undefined ? Number(args[k]) : d);
const home = path.resolve(args.home ?? "copilot-home-repro");
const turns = num("turns", 150_000);
const toolOutputBytes = num("tool-output-bytes", 2048);
const images = num("images", 0);
const imageBytes = num("image-bytes", 1_500_000);
const checkpointEvery = num("checkpoint-every", 0);
const filesPerCheckpoint = num("files-per-checkpoint", 5);
const model = args.model ?? "claude-sonnet-4.5";
const sessionId = crypto.randomUUID();
const cwd = path.join(home, "workdir");
const sessionDir = path.join(home, "session-state", sessionId);
fs.mkdirSync(sessionDir, { recursive: true });
fs.mkdirSync(cwd, { recursive: true });
const uuid = () => crypto.randomUUID();
const filler = (n, seed) => {
const line = `dummy output line ${seed} lorem ipsum dolor sit amet consectetur adipiscing elit\n`;
return line.repeat(Math.ceil(n / line.length)).slice(0, n);
};
let t = Date.UTC(2026, 0, 1);
const startIso = new Date(t).toISOString();
let parentId = null;
let eventCount = 0;
let buf = [];
let bufBytes = 0;
const fd = fs.openSync(path.join(sessionDir, "events.jsonl"), "w");
function emit(type, data, extra = {}) {
t += 50;
const id = uuid();
const line = JSON.stringify({ type, data, ...extra, id, timestamp: new Date(t).toISOString(), parentId }) + "\n";
parentId = id;
eventCount++;
buf.push(line);
bufBytes += line.length;
if (bufBytes > 4 << 20) flush();
}
function flush() {
fs.writeSync(fd, buf.join(""));
buf = [];
bufBytes = 0;
}
emit("session.start", {
sessionId,
version: 1,
producer: "copilot-agent",
copilotVersion: "1.0.119",
startTime: startIso,
selectedModel: model,
reasoningEffort: "high",
context: { cwd },
alreadyInUse: false,
remoteSteerable: false,
});
const imageEvery = images > 0 ? Math.max(1, Math.floor(turns / images)) : 0;
const filesModified = [];
let interactionId = uuid();
for (let turn = 0; turn < turns; turn++) {
if (turn % 50 === 0) {
interactionId = uuid();
emit("user.message", {
content: `dummy prompt ${turn}`,
attachments: [],
agentMode: "autopilot",
messageId: uuid(),
turnId: String(turn),
interactionId,
});
}
const turnId = String(turn);
const toolCallId = `toolu_${crypto.randomBytes(12).toString("hex")}`;
const command = `echo dummy-command-${turn}`;
const output = filler(toolOutputBytes, turn);
emit("assistant.turn_start", { turnId, interactionId, agentMode: "autopilot" });
emit("assistant.message", {
messageId: uuid(),
content: `Running dummy step ${turn}.`,
toolRequests: [{ toolCallId, name: "bash", arguments: { command, description: "dummy" } }],
});
emit("tool.execution_start", { toolCallId, toolName: "bash", arguments: { command, description: "dummy" } });
emit("tool.execution_complete", {
toolCallId,
model,
interactionId,
turnId,
shellExecution: { exitCode: 0 },
success: true,
result: { content: output, structuredContent: { shellId: String(turn) } },
toolTelemetry: { properties: { executionMode: "sync" }, metrics: {} },
});
const hookInvocationId = uuid();
emit("hook.start", {
hookInvocationId,
hookType: "postToolUse",
input: {
sessionId,
timestamp: t,
cwd,
toolCallId,
toolName: "bash",
toolArgs: { command, description: "dummy" },
toolResult: { textResultForLlm: output, resultType: "success", sessionLog: output, toolTelemetry: {} },
},
});
emit("hook.end", { hookInvocationId, hookType: "postToolUse", success: true });
if (imageEvery && turn % imageEvery === 0) {
const bytes = crypto.randomBytes(imageBytes);
emit("session.binary_asset", {
assetId: "sha256:" + crypto.createHash("sha256").update(bytes).digest("hex"),
type: "image",
mimeType: "image/png",
byteLength: bytes.length,
data: bytes.toString("base64"),
});
}
if (checkpointEvery && turn % checkpointEvery === checkpointEvery - 1) {
for (let i = 0; i < filesPerCheckpoint; i++) {
filesModified.push(`${cwd}/src/dummy/module_${filesModified.length}/file_${filesModified.length}.ts`);
}
emit("session.usage_checkpoint", {
totalNanoAiu: 0,
totalPremiumRequests: turn,
accountingSnapshot: {
totalPremiumRequestCost: turn,
totalUserRequests: Math.floor(turn / 50),
totalNanoAiu: 0,
aiCreditsStatus: "complete",
tokenDetails: {
input: { tokenCount: 0 },
cache_read: { tokenCount: 0 },
cache_write: { tokenCount: 0 },
output: { tokenCount: 0 },
},
totalApiDurationMs: turn * 1000,
sessionStartTime: startIso,
codeChanges: {
linesAdded: turn * 10,
linesRemoved: turn,
filesModifiedCount: filesModified.length,
filesModified,
},
modelMetrics: {},
agentMetrics: {},
providerModelMetrics: [],
currentModel: model,
lastCallInputTokens: 1000,
lastCallOutputTokens: 100,
},
providerModelMetrics: [],
usageAccountingWatermarks: { [sessionId]: turn },
});
}
emit("assistant.turn_end", { turnId });
}
flush();
fs.closeSync(fd);
const now = new Date(t).toISOString();
fs.writeFileSync(
path.join(sessionDir, "workspace.yaml"),
[
`id: ${sessionId}`,
`cwd: ${cwd}`,
`client_name: github/cli`,
`last_client_name: github/cli`,
`name: Synthetic large session`,
`user_named: true`,
`summary_count: 0`,
`fork_count: 0`,
`created_at: ${startIso}`,
`updated_at: ${now}`,
"",
].join("\n"),
);
const size = fs.statSync(path.join(sessionDir, "events.jsonl")).size;
// Pre-trust the dummy working folder in the isolated COPILOT_HOME so no trust prompt appears.
const configPath = path.join(home, "config.json");
const config = fs.existsSync(configPath) ? JSON.parse(fs.readFileSync(configPath, "utf8").replace(/^\s*\/\/.*$/gm, "")) : {};
config.trustedFolders = [...new Set([...(config.trustedFolders ?? []), cwd])];
fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
console.log(`session id: ${sessionId}`);
console.log(`events: ${eventCount.toLocaleString()}`);
console.log(`events.jsonl: ${(size / 1048576).toFixed(1)} MiB`);
console.log(`\nReproduce with:\n COPILOT_HOME=${home} copilot --resume=${sessionId}`);Expected behavior
- Resume memory should be bounded by what the live session needs: the post-compaction conversation plus metadata. It shouldn't grow with the full lifetime of
events.jsonl. - An idle resumed session shouldn't hold GBs of memory.
- The event log shouldn't grow quadratically or store duplicate or binary payloads inline.
Suggested fixes:
- Stream the log on resume. Replay into current state from the last compaction boundary and drop processed events. Load history, rewind and timeline views lazily from file offsets or an index (
session.db), instead of keeping every event as a live JSON value. - Rotate or segment
events.jsonlat compaction, so resume starts at the last compaction boundary. - Store
usage_checkpointas a delta, or keep only the latest one.filesModifiedcould be a count or a separate set file. - Move
binary_assetbytes out of the event log into content-addressed blobs that load on demand. - Don't embed
toolResultinpostToolUsehook.start. Reference it bytoolCallId. - Prune completed shells from the shell registry, and cap the size of the shell listing in
stop_basherrors. - Log resume duration, event count and resident memory at
INFO, so these cases are easy to diagnose.
Additional context
- macOS 27.0.1, Apple Silicon (arm64), 64 GB RAM; zsh in a pty.
- Measured with
ps -o rss=,footprint <pid>,heap -s <pid>andsample <pid>. - Possibly related: Session compaction OOMs and never completes, leaving the session permanently unresumable (heap exhaustion at default ~4.3 GB cap) #4780, Repeated out-of-memory crash during a long interactive session in 1.0.109 #5435, v1.0.80: event-storage exhaustion retry storm drives long-running session into GC/compaction loop and Node OOM #4639, Windows: multi-GiB native runtime memory bursts in desktop-hosted CLI 1.0.87-0, followed by same-process release #4928.
Activity