E2B icon indicating copy to clipboard operation
E2B copied to clipboard

Paused sandbox is not persisting the file changes / addition after second time resumed and onward

Open byrizki opened this issue 1 year ago • 14 comments

Describe the bug When a sandbox environment is paused and resumed multiple times, file changes or additions are not persisted after resuming. On the first resume, changes are retained as expected, but after subsequent resumes, file modifications and new files are lost.

To Reproduce Steps to reproduce the behavior:

  1. Go to the sandbox environment.
  2. Create or edit a file (e.g., add test.txt or modify existing code).
  3. Pause the sandbox.
  4. Resume the sandbox → changes persist (works correctly).
  5. Do some edit, or add file
  6. Pause the sandbox again.
  7. Resume the sandbox → file changes/additions are gone (bug occurs).

Expected behavior File changes and additions should persist after every resume, not just the first one.

Additional context

  • resuming
Sandbox.connect(currentRunningSandbox?.sandboxId || currentPausedSandbox?.sandboxId, { timeoutMs: sandboxTimeout })
  • creation
Sandbox.betaCreate(template, {
      metadata: {
        template,
        userID: userId,
        roomID: roomId,
        createdAt: new Date().toISOString(),
      },
      timeoutMs: sandboxTimeout,
      autoPause: true,
    })

byrizki avatar Aug 29 '25 22:08 byrizki

I have the same use case. Is this bug fixed already?

debajyoti-truefoundry avatar Dec 09 '25 05:12 debajyoti-truefoundry

@dobrac any updates on this?

maciej-trebacz avatar Mar 05 '26 15:03 maciej-trebacz

Hi, Could you please give me an example of a recent sandbox ID on which you experienced this behavior? I might have an idea of what could be happening.

This is definitely not something that should happen, nor is it something that I get reported often.

beran-t avatar Mar 05 '26 16:03 beran-t

Hi @beran-t , I just experienced this issue again on sandbox iev7qmc9ht4nmmvhlif3k

Cycle Event File State
(n)th pause (22:49) Agent idle after research → sandbox pauses Edit was on disk
(n)th resume (22:55) User accesses preview → auto-resume Changes persist (as expected)
(n+1)th pause (23:04) Agent idle again → sandbox pauses Edit still on disk
(n+1)th resume (23:04) "check lot-pr" chat → auto-resume Changes GONE (bug!)

jiaming-jx avatar Mar 16 '26 00:03 jiaming-jx

@beran-t another one i2rg2gaslcgsu7cw0a5d9

jiaming-jx avatar Mar 16 '26 23:03 jiaming-jx

@beran-t just happened again on ijczuzv4tcp823tmhbq2t

all 3 sandboxes has lifecycle: { onTimeout: 'pause' as const, autoResume: true }

jiaming-jx avatar Mar 17 '26 04:03 jiaming-jx

Thank you for the examples, taking a look at it.

beran-t avatar Mar 18 '26 13:03 beran-t

Would you be able to provide a similar report with times for iev7qmc9ht4nmmvhlif3k? I wanted to check, but the sandbox was already deleted iev7qmc9ht4nmmvhlif3k. I checked the lifecycle of the reported sandboxes, but didn't find any errors that could explain this so far.

beran-t avatar Mar 18 '26 14:03 beran-t

@beran-t here it is

Sandbox ID: ijczuzv4tcp823tmhbq2t Date: Tuesday March 17, 2026 All times UTC

Activity windows:

  • Window 1: 00:36 – 00:51 (15 min active), then 6 min idle
  • Window 2: 00:57 – 01:23 (26 min active), then 137 min pause (2h 17m)
  • Window 3: 03:40 – 04:24 (44 min active), then 6 min idle
  • Window 4: 04:30 – 04:42 (12 min active) — I noticed the change the agent made on Window 3 was lost

The data loss scenario: All changes made during Window 3 (03:40–04:24) were lost, but changes made in Window 2 are still there.

jiaming-jx avatar Mar 19 '26 20:03 jiaming-jx

We have identified a race condition and are working on a fix. Thanks @LASkuma

beran-t avatar Mar 23 '26 22:03 beran-t

This is a critical persistence bug for any agent workflow that relies on sandbox state across pause/resume cycles.

From building persistent sandbox environments for agents:

The likely root cause: The first resume restores from a full snapshot (taken at pause time). The second pause takes a new snapshot — but if the filesystem changes from the first resumed session weren't properly flushed to the snapshot layer before the second pause, they're lost. It's a write-back cache coherence issue.

The general pattern for sandbox persistence:

  1. Write-ahead log (WAL): Every filesystem write goes to a WAL first, then to the snapshot layer. On resume, replay the WAL on top of the last snapshot. This guarantees no writes are lost regardless of how many pause/resume cycles occur.

  2. Checkpoint on pause, not snapshot: Instead of a full filesystem snapshot (which can miss unflushed writes), take a checkpoint that includes: the last snapshot + accumulated WAL entries. On resume, apply the checkpoint. The WAL is truncated only after a successful checkpoint.

  3. Verification step: After each resume, verify filesystem integrity by comparing a hash of critical files against the expected state from the checkpoint. If there's a mismatch, the checkpoint/resume process has a bug.

The agent impact: Agents that rely on sandbox state across sessions (accumulated data, intermediate results, installed packages) will silently lose work. The agent continues executing as if the state exists, producing wrong results. This is particularly dangerous for long-running research or coding agents.

Workaround: Until fixed, agents should persist critical state to an external store (object storage, database) before signaling readiness for pause, and restore from the external store after resume — treating the sandbox as ephemeral.

Related architecture on persistent agent state: https://blog.kinthai.ai/why-character-ai-forgets-you-persistent-memory-architecture

kinthaiofficial avatar Apr 28 '26 17:04 kinthaiofficial

Closing this thread as the issue has been resolved.

beran-t avatar May 15 '26 15:05 beran-t

Summary

We are seeing the exact symptom described in the (now-closed) issue #884 — a sandbox created with on_timeout: "pause" and auto_resume: true came back from a Sandbox.connect() call with partial filesystem state: the project root that previously contained a full Next.js scaffold (app/, package.json, AGENTS.md, lockfile, etc.) was replaced by a directory containing only src/ plus some heavy artefacts (node_modules/, .git/, .next/).

Because #884 was closed five hours before this incident occurred, I'm filing a fresh report with full sandbox IDs, timestamps, and a reproduction-grade timeline so the team can verify whether the fix is fully deployed in the orchestrator and whether the SDK side needs any release.

This is reproducibly destructive for any agent product that relies on E2B as its persistent workspace: when the agent observes a half-empty project on resume it (correctly!) assumes its own previous tool calls were lost, and then tries to recreate the project — at which point even the partial state that was preserved gets rm -rf'd by the agent.

Environment

  • Python SDK: e2b==2.21.0 (latest at the time of incident; 2.21.1 is current and the changelog shows no orchestrator/persistence fix between them)
  • Region: default
  • Template: 4osdm12o84cpvhilxcbb (custom team template based on Next.js dev image)
  • Lifecycle config used at create:
    AsyncSandbox.create(
        template=E2B_SANDBOX_TEMPLATE,
        api_key=...,
        timeout=3600,            # 1h
        envs={...},
        lifecycle={"on_timeout": "pause", "auto_resume": True},
    )
    
  • Reconnect path: AsyncSandbox.connect(sandbox_id=..., api_key=...) (no manual pause/resume calls anywhere in our code — pause is only ever triggered by E2B's idle timeout)
  • We never call sandbox.pause() ourselves; we never call sandbox.resume() ourselves; pause/resume is entirely E2B-managed via the lifecycle config above.

Affected sandboxes

Both sandboxes are in the same E2B account (team account, single API key) and represent the same logical chat session in our product.

sandbox_id role started_at (UTC) end_at (UTC) current state filesystem on direct connect today
i7d6wvs07uub958wpse89 initial sandbox the agent worked in 2026-05-16 02:56:08.642572 2026-05-16 03:56:07.699594 (idle-timeout pause exactly +1h) PAUSED (still on the account, listable via API) complete project root: app/, src/, .next/, .git/, package.json, AGENTS.md, bun.lock, node_modules/, etc. — files are timestamped 02:56–02:58 (matches when the agent wrote them)
indjvz9ra6ymwd10ojsbm sandbox returned by connect() after worker restart 2026-05-16 02:56:08.723076 2026-05-16 04:51:22.977991 PAUSED (still listable) partial root: only src/, .next/, .git/, node_modules/ survive; app/, package.json, AGENTS.md, lockfile, etc. are missing. All surviving non-template files are timestamped 03:44 (i.e. after our agent re-issued writes on the half-empty filesystem)

I directly verified both states by listing them via AsyncSandbox.list(query=SandboxQuery(state=[PAUSED])) and by AsyncSandbox.connect()-ing into each and running ls -la /home/user/evergreen-mental-training/. Both sandboxes resumed successfully on direct connect; the file content above is what each one actually contains right now.

Timeline (all UTC, 2026-05-16)

  1. 02:56:07 — worker A creates sandbox i7d6wvs0... via AsyncSandbox.create(...) with the lifecycle config above, git clones our Next.js template, runs bun install. ls /home/user/evergreen-mental-training/ would show the full project (verified: I ran exactly this against the still-paused sandbox today and got the full listing).
  2. 02:56–02:58 — agent does ~15 tool calls (file_write, shell_run), agent commits and pushes 9 times to GitHub successfully. No pause / resume is triggered yet.
  3. 03:00:24 — worker A K8s pod is terminated (graceful pod restart from our side). We do not call sandbox.pause() in any teardown hook. The sandbox itself is still RUNNING on E2B at this point — its idle timeout has not elapsed.
  4. 03:43:42 — worker B (same code, same lifecycle config) starts handling the same chat, looks up the stored sandbox_id = i7d6wvs0..., and calls AsyncSandbox.connect(sandbox_id="i7d6wvs0...", api_key=...).
  5. The connect returns a sandbox object whose sandbox_id is indjvz9ra6ymwd10ojsbm — i.e. a different id from the one we asked for. (This is consistent with the auto-resume docs note that resume can produce a new sandbox_id, so we treat that as expected and persist the new id.) The new sandbox is on the same E2B account, same template.
  6. 03:43:55 — agent's first tool call on the newly-connected sandbox does file_write /home/user/evergreen-mental-training/src/app/page.tsx. It succeeds.
  7. 03:43:58 — agent calls preview_open (which internally runs next dev); the dev server fails to start because the root is missing package.json etc.
  8. 03:44:01 — ls /home/user returns just evergreen-mental-training.
  9. 03:44:05 — ls /home/user/evergreen-mental-training/ returns just src (one line; the agent doesn't pass -a so dotfiles are hidden, but package.json, app/, bun.lock, node_modules/, AGENTS.md are all absent from a non--a listing as well — they really aren't there).
  10. 03:44:11–03:44:30 — agent (correctly!) concludes "files were lost", calls rm -rf and tries to re-run create_nextjs_app. The subsequent recreate succeeds. Everything in the sandbox after this point is freshly created by the agent, which is why the surviving files in indjvz9... are timestamped 03:44.
  11. 03:56:07 — i7d6wvs0... reaches its 1h idle timeout and is PAUSED with end_at = 03:56:07. All the original files are still there — confirmed by directly resuming and lsing the sandbox today.
  12. 04:51:22 — indjvz9... itself is later paused. Confirmed listable today.

Why I do not believe this is on the SDK / consumer side

  • We never call sandbox.pause() / sandbox.resume() directly — all pause/resume is E2B-driven via lifecycle config.
  • The lifecycle config matches the official auto-resume docs verbatim.
  • Both sandboxes are still alive on the E2B side and observable; one of them clearly has the full project, the other clearly has a half-mutated root with non-template directories missing. There is no way for our worker to have produced this asymmetry, because between t=02:58 (last agent write to i7d6wvs0...) and t=03:43:42 (connect call) we made zero API calls of any kind to E2B.
  • The pod restart at 03:00:24 cannot itself drop files — at that moment i7d6wvs0... was still RUNNING on the orchestrator, and that sandbox today still has every file the agent wrote.
  • connect() returned a new sandbox_id (indjvz9...), which is the documented auto-resume behaviour. So the question is: when the orchestrator allocates indjvz9... to back the resume of i7d6wvs0..., why does its filesystem differ from i7d6wvs0...'s last-known state, with app/ and package.json missing while src/, .git/, .next/, node_modules/ survive?

Suspected behaviour

It looks like the same write-back / snapshot-flush race that #884 was tracking, but reachable via a slightly different path: client disconnect → orchestrator-side resume bound to a fresh sandbox_id, rather than #884's "multiple manual pause/resume cycles within one client". The selective survival pattern matches what #884 commenters described — older / template-layer content (node_modules, .git) survives while later-written application files (app/, package.json) don't.

Reproduction recipe (best effort)

I don't have a deterministic local reproducer because the trigger seems to be the orchestrator's resume scheduling, not anything on the SDK side. But the pattern that hit us was:

  1. Create a sandbox with lifecycle={"on_timeout": "pause", "auto_resume": True} and a non-trivial idle timeout (we use 1h).
  2. From the worker, do enough writes to materially change the filesystem (clone a repo, install deps, write app code).
  3. Kill the worker (do not call sandbox.pause(); let the sandbox remain RUNNING on the orchestrator).
  4. Wait long enough for activity-tracking to mark the sandbox idle, but before the idle timeout elapses (we hit the bug ~43 min after the last write, with idle timeout = 1h).
  5. From a new worker, call AsyncSandbox.connect(sandbox_id, api_key) → orchestrator returns a new sandbox_id and you get a half-populated /home/user/....

I am happy to provide more sandbox IDs if you can repro on these or want me to capture a fresh case. Both i7d6wvs07uub958wpse89 and indjvz9ra6ymwd10ojsbm are still alive on our team account (e2b_07e4cc9cfd953d6a99879b6b, "Eazo Team") as of the time I'm filing this — I will leave them paused and untouched for at least the next 7 days so your team can inspect them server-side. Please ping me before you destroy them; I'd like to extract the surviving project content first.

Concrete questions for the E2B team

  1. Is the orchestrator-side fix that closed #884 expected to cover the client-disconnect → reconnect-with-different-sandbox_id path described above, or only the "multiple pause() / resume() calls from the same client" path?
  2. Is there an SDK release planned that requires consumers to upgrade to pick up the fix? e2b==2.21.1 is the current latest on PyPI and its changelog has no entry referencing #884.
  3. Given two sandbox_ids (i7d6wvs07uub958wpse89 source / indjvz9ra6ymwd10ojsbm post-resume) where the post-resume one has demonstrably wrong filesystem state, can you cross-check the orchestrator logs for the resume event and tell us whether a fresh snapshot was taken or an older snapshot was applied?
  4. Until this is fully resolved on the orchestrator side, what's the recommended client-side mitigation for the worker-restart use case (where pause is involuntary and not driven by client lifecycle)? E.g. should we be calling Sandbox.create(...) from a known good template snapshot ID and re-applying our project state ourselves, rather than relying on connect/auto-resume across worker restarts?

Thanks — happy to provide more logs, the full agent tool-call trace, or shell access to repro hosts on request.

codevoyager1984 avatar May 16 '26 12:05 codevoyager1984