Skip to content

--resume holds the entire events.jsonl in native memory: grows ~3 KB/event, reaches 13 GB (synthetic repro included) #5654

Backlog

Description

@achicu

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 Small rather 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 -s showed 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. sample during load is dominated by malloc/free/memmove/realloc in runtime.node and 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:

  1. session.usage_checkpoint grows quadratically. Each checkpoint re-serializes the full cumulative accountingSnapshot, including codeChanges.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.
  2. session.binary_asset stores image bytes inline as base64, even though each event already carries a sha256 assetId. These are also the most expensive events to hold in memory (see the table).
  3. hook.start for postToolUse duplicates the full tool result. input.toolResult.textResultForLlm and sessionLog repeat what tool.execution_complete already stored, so every tool output is written at least twice.
  4. The stop_bash error lists every shell ever started in the session. Calling stop_bash on 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 to events.jsonl and 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

  1. Save the script below as make-large-copilot-session.mjs. It uses only the Node standard library and writes dummy data into its own COPILOT_HOME. It never touches ~/.copilot.
  2. Generate a session:
    node make-large-copilot-session.mjs --home ./copilot-home-repro --turns 150000 --images 1500
    It prints the session ID and the command to run.
  3. Resume it:
    COPILOT_HOME=$PWD/copilot-home-repro copilot --resume=<session-id>
    The isolated home isn't signed in, so the CLI shows Please use /login. That's expected and doesn't affect the result.
  4. In another terminal, watch memory:
    footprint $(pgrep -f "copilot --resume=<session-id>")   # macOS
    ps -o rss= -p <pid>
  5. Memory climbs to about 13 GB within about 30 s and stays there while idle. Without --images, --turns 150000 gives 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:

  1. 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.
  2. Rotate or segment events.jsonl at compaction, so resume starts at the last compaction boundary.
  3. Store usage_checkpoint as a delta, or keep only the latest one. filesModified could be a count or a separate set file.
  4. Move binary_asset bytes out of the event log into content-addressed blobs that load on demand.
  5. Don't embed toolResult in postToolUse hook.start. Reference it by toolCallId.
  6. Prune completed shells from the shell registry, and cap the size of the shell listing in stop_bash errors.
  7. Log resume duration, event count and resident memory at INFO, so these cases are easy to diagnose.

Additional context

Activity

  1. added
    area:sessions
    and removed on Dec 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:sessions

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions