Repository navigation
feat(sandbox-e2b): auto-prune old NATIVE_SNAPSHOT snapshots per sandbox - #2555
Conversation
Add configurable snapshotRetention (default 0 = disabled, <=0 disables)
that, after each NATIVE_SNAPSHOT persist, keeps the just-created snapshot
plus the newest retention-1 AgentScope-native snapshots for the sandbox and
deletes the rest via DELETE /templates/{snapshotId} (404 idempotent).
Native snapshots are named agentscope-<sandboxId>-<epochMillis> so the
embedded timestamp orders them deterministically even though GET /snapshots
returns no createdAt. Pruning is best-effort: failures are logged and never
block persistence. Legacy/foreign snapshots are never pruned.
|
Caution The consumer version of Gemini Code Assist on GitHub has been sunset. All code review activity has officially ceased. |
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
Verified against the live E2B API (snapshot listing exposes namespaced
snapshot IDs whose alias middle segment is the base32-style sandbox id,
not hex, and DELETE /templates/{id} requires the namespace slash to be
URL-encoded):
- widen SNAPSHOT_TIMESTAMP_PATTERN from hex [0-9a-f-]+ to the actual
lower-case alphanumeric sandbox id character set [a-z0-9-]+; the hex
restriction never matched real snapshots, so pruning silently no-oped
- build the delete URL with HttpUrl.addPathSegment so the namespace '/' in
a snapshot id (e.g. team/alias:tag) is encoded as %2F; unencoded it was
parsed as an extra path segment and E2B returned 404
- update prune tests to assert the encoded delete path
Replace E2B sandbox id with a locally-generated 8-hex-char short UUID as
the middle segment of the native snapshot alias
(agentscope-<shortId>-<epochMillis>). This guarantees uniqueness even
when two persists land in the same millisecond and makes the regex
(^agentscope-[0-9a-f]{8}-(\d{13})$) strict enough to never match
foreign or legacy snapshots.
…merge Match the call-level override semantics of the timeout and maxRetries fields: the per-call options always win, and a call-level 0 now disables pruning as documented. Document the override rule on the option field.
…te record Replace the team-wide GET /snapshots listing with a per-session record of previously created snapshot ids stored in E2bSandboxState. Pruning no longer depends on the source sandbox id (which changes when a session is resumed from an earlier snapshot) nor on a full listing. - E2bSandboxState gains snapshotIds (most recent last), persisted with the state; absent in older serialized states, defaulting to an empty list - E2bPlatformHttp.pruneSnapshots(keep, older, retention) keeps the keep snapshot plus the newest retention-1 older ones by embedded timestamp, deletes the rest (404 idempotent, failures logged), and returns the ids to keep so the caller updates its record - older ids with an unparseable timestamp are conservatively kept - E2bSandbox persists the record after pruning (SandboxManager saves the state on persist); listSnapshots remains as a diagnostic capability
No longer referenced since pruning is driven by the per-session state record; drop the method and its now-orphaned getJson helper together with the listing test.
… are saved SandboxLifecycleMiddleware.releaseForCall() called persistState before release(), serializing the state before stop() ran. State mutations made during stop — e.g. workspaceRootReady and the e2b per-session snapshot record updated in doPersistWorkspace — were therefore never captured by the persist. Release first, then persist the (post-stop) state.
…stored from E2B locks a snapshot template while a sandbox restored from it is alive and rejects deleting it with HTTP 400. Per-session pruning was picking that snapshot as an ordinary older entry and failing on the delete. - track the source snapshot id set in restoreSandboxFromSnapshotTemplate - pruneSnapshotsBestEffort excludes it from candidates (and keeps it in the record) so a persist never tries to delete the live sandbox's template - shutdown() deletes the source snapshot after killSandbox unlocks it and drops it from the record, converging back to retention per session
…on shutdown shutdown() unconditionally deleted the snapshot the sandbox was restored from, which for a session with only [source, keep] reduced the record to 1 snapshot regardless of snapshotRetention. Only drop the source once the session keeps >= retention snapshots after deletion, so retention=2 (and higher) is preserved for resumed sessions.
…p in one pass E2B locks a snapshot template while a sandbox restored from it is running and rejects deleting it with 400. Instead of tracking the source snapshot and excluding it during persist, defer all pruning to shutdown: persist only appends to the session record, and after killSandbox unlocks the templates, cleanupSnapshots() keeps the newest snapshotRetention ids by embedded timestamp and deletes the rest in one pass, correcting any residue regardless of earlier persists. - E2bPlatformHttp.cleanupSnapshots(ids, retention): one-shot correction - E2bSandbox: drop currentSandboxSourceSnapshotId/pruneSnapshotsBestEffort/ deleteSourceSnapshotBestEffort; persist appends, shutdown cleans up - snapshotTimestampMillis stays private to E2bPlatformHttp
oss-maintainer
left a comment
There was a problem hiding this comment.
Summary
This PR modifies 8 files with 697 lines of diff.
Observations
- Files changed: 8
- Test coverage: ✅ Tests included
- CLA: ✅ Signed
Suggestions
- Please ensure all public API changes are backward compatible
- Consider adding unit tests for new logic paths
Automated review by github-manager-bot
Keep the last N snapshots by insertion order (most recent last) instead of parsing alias timestamps. This makes retention work for any snapshotID format without needing alias sorting. Related to agentscope-ai#2547.
…etup Need to enqueue 2 DELETE responses for 2 deletions (snap-1, snap-2); single enqueue caused SocketTimeout/retries (4 requests, 360s) and assertion failure expected:<2> but was:<4>.
- remove dead snapshotTimestampMillis/StaleSnapshot/PATTERN (switched to insertion-order retention, 13 lines/9 instr always missed) - E2bPlatformHttpTest: add 14 cases covering null/blank older, size<=retention, exactly retention, invalid baseUrl/key, cleanup null/empty/retention<=0/ failure prepend, killSandbox 200/404/500, applySandboxFields, blank name - add E2bSandboxOptionsAndStateTest (14 tests): state/options null-defaults, filesystemSpec builder, client create/merge/resume/serialize, snapshotName format, shutdown skips/cleanup with mock server, persist NATIVE_SNAPSHOT success/missing-id Coverage e2b: 51.7% -> 72.5% instr; E2bPlatformHttp 78%->84%, State/Options 100%, Client 90%; 54 tests pass.
- agentscope-ai#2196: pass username query param in e2b filesystem REST calls (filesUrl helper plus URL assertions and workspace state setup) - agentscope-ai#2555: drop dead snapshot-timestamp helpers from E2bPlatformHttp, restore coverage tests plus InputStream close fix - agentscope-ai#2976: reliable e2b exec timeout with server-side kill (callTimeout plus readTimeout(0), Connect-Timeout-Ms header, interrupt-bit handling) plus its tests - E2bEnvdProcessClientTest: align three stale drain tests with the merged upstream agentscope-ai#2828 reject-without-exit-code behavior
oss-maintainer
left a comment
There was a problem hiding this comment.
Summary
Delta re-review of the 6 commits since cd4e07bc (my previous COMMENTED review): snapshot retention switched from embedded-timestamp ordering to insertion-order FIFO, the timestamp regex/parser was removed, and coverage was extended (FIFO snap-* ids, deletion-failure retention, fd-leak fix in the persist test). The new semantics are self-consistent and better aligned with how ids are persisted in E2bSandboxState — insertion order is authoritative, so opaque/foreign ids no longer escape pruning. Main follow-up is the stale never pruned javadoc in E2bSandbox; the rest is hygiene. CI on this head is green (build ubuntu/windows, license, module sync).
Automated review by github-manager-bot
| * AgentScope-native snapshot alias: {@code agentscope-<shortId>-<epochMillis>}, where the | ||
| * middle segment is an 8-hex-char short UUID generated locally. The trailing 13-digit epoch | ||
| * millis timestamp makes ordering deterministic; anything not matching this format is treated as | ||
| * a legacy/foreign snapshot and never pruned. |
There was a problem hiding this comment.
[Warning] Stale javadoc after the retention rework: it still says ids matching agentscope-<shortId>-<epochMillis> are ordered by embedded timestamp and that "anything not matching this format is treated as a legacy/foreign snapshot and never pruned". Since a12ed17 / 217ce04, both pruneSnapshots and cleanupSnapshots drop the timestamp parsing entirely and prune purely by insertion position, so foreign-shaped ids held in E2bSandboxState.getSnapshotIds() will now be deleted. Please reword this comment to describe position-based retention (the snapshotName() helper itself is still correct).
There was a problem hiding this comment.
Done in 257c614: rewrote the snapshotName() javadoc to describe position-based retention (insertion order, most recent last, any id format prunable; the epoch millis segment is human-readable only and never parsed), and fixed the same stale "embedded timestamp" wording in E2bSandbox.cleanupSnapshots().
| } | ||
|
|
||
| /** Retention keeps the last N snapshots by insertion order (most recent last). */ | ||
| List<String> pruneSnapshots( |
There was a problem hiding this comment.
[Info] pruneSnapshots now has no production caller — E2bSandbox.cleanupSnapshots() goes through cleanupSnapshots(snapshotIds, retention) (line ~158) instead, and only the tests exercise this method. If the persist-path hook was intentionally dropped in favour of the restore-time one-shot cleanup, consider removing pruneSnapshots (and folding its deletion-failure-kept tests onto cleanupSnapshots) so the two near-duplicate retention implementations can't drift apart.
There was a problem hiding this comment.
Done in 257c614: removed the uncalled pruneSnapshots() (+ append helper); cleanupSnapshots() is now the single retention path. Its retention tests were folded onto cleanupSnapshots (cleanupSnapshotsRetentionOneDeletesAllButNewest incl. namespaced-id encoding assertion, cleanupSnapshotsRetentionKeepsConfiguredCount, cleanupSnapshotsSkipsNullAndBlank); the delete-failure-kept case was already covered by cleanupSnapshotsFailurePrependsToKept. E2bPlatformHttp instr coverage 84% -> 96%.
| } | ||
|
|
||
| /** One-shot cleanup keeps the last {@code retention} ids by insertion order. */ | ||
| List<String> cleanupSnapshots(List<String> snapshotIds, int retention) { |
There was a problem hiding this comment.
[Info] Minor: neither retention helper de-duplicates its input list. If a persisted id appears twice in E2bSandboxState.getSnapshotIds() (e.g. partially-failed state save), positional retention counts it twice and can keep retention + duplicates - 1 snapshots. The old timestamp code had the same behaviour, so not a regression — a LinkedHashSet pass before slicing would make the "keep last N" contract exact.
There was a problem hiding this comment.
Done in 257c614: cleanupSnapshots() now dedupes its input via LinkedHashSet (first occurrence wins) and drops blank ids, so "keep last N" counts distinct snapshots. Covered by cleanupSnapshotsDeduplicatesIds and cleanupSnapshotsDuplicatesWithinRetentionNeedNoDelete.
- fix stale snapshotName()/cleanupSnapshots() javadoc: retention is purely insertion-order based (most recent last), any id format in the per-session record can be pruned; epoch millis in the alias is only human-readable, never parsed - remove now-uncalled pruneSnapshots() (+append helper) in favour of the single cleanupSnapshots() path used on shutdown; fold its retention tests onto cleanupSnapshots - dedupe cleanupSnapshots() input via LinkedHashSet (first occurrence wins) and drop blank ids, so "keep last N" counts distinct snapshots E2bPlatformHttp instr coverage 84% -> 96%; 49 e2b tests pass.
|
@Buktal The 3 review comments are addressed in 257c614 and pushed; the corresponding threads are replied. PTAL when convenient:
49 e2b tests pass locally, E2bPlatformHttp instr coverage 84% -> 96%. |
oss-maintainer
left a comment
There was a problem hiding this comment.
Summary
Delta re-review of the single commit since my previous pass: 257c614 addresses both open points — the stale never pruned javadoc on snapshotName() is rewritten to describe insertion-order retention (and links E2bPlatformHttp#cleanupSnapshots), the unused pruneSnapshots helper is deleted along with its duplicated test matrix, and cleanupSnapshots now de-duplicates its input (my earlier [Info]), so a re-persisted id counts once against the retention budget. Blank/null filtering moved into dedupe, which also makes the retention <= 0 / size <= retention early returns hand back a clean list instead of the caller's raw list — a small improvement for E2bSandbox#cleanupSnapshots, which writes that result straight into E2bSandboxState.
Findings
- [Info]
E2bPlatformHttp.java:147— first-occurrence-wins is documented and correct here; noting only that the ordering is now part of the retention contract.
CI on this head is green (ubuntu + windows build, license, module sync, codecov) and CLA is signed.
E2bSandbox.stop() removes ids recorded by the failed attempt, so the record always matches the archive and pruning can never delete the referenced snapshot, regardless of restarts or node switches. E2bSandboxClient.merge() only overrides snapshotRetention on positive per-call values so a call leaving it at default no longer resets the client default.
oss-maintainer
left a comment
There was a problem hiding this comment.
Summary
Re-review of 13d73380 ("roll back snapshot record on persist failure"). The failure mode being fixed is real: doPersistWorkspace() appends the new snapshot id before the archive is handed to the snapshot, so a persist() throw leaves the shared record pointing at an archive that was never written, and a later cleanupSnapshots() could then prune the snapshot the archive actually references. Catching it in stop() is the right place, close() still logs-and-proceeds so shutdown() is unaffected, and the two new MockWebServer tests pin both outcomes precisely (failed stop -> snapshot create + kill only, record unchanged; successful stop -> create + kill + one DELETE /templates/..., newest kept). CI is green on this head and CLA is signed.
What I want resolved before this is approved is narrower than the change itself: the rollback is positional rather than identity-based, and its stated justification depends on the corrected record actually reaching the store.
Findings
- [Warning]
E2bSandbox.java:85—subList(recordedBefore, size).clear()drops every id appended after the marker, including any written concurrently or by a shared-workspace counterpart, untracking snapshots that are still referenced. - [Warning]
E2bSandbox.java:77—stop()re-throws, so ifSandboxManager.releasedoes not still callpersistStateafter a stop failure, the rollback stays in memory and the restart/node-switch case the comment cites is not covered. - [Info]
E2bSandboxClient.java:155— primitiveintmakes0mean both "unset" and "disabled", so a call can no longer turn off a client-level retention; a nullable field would keepE2bFilesystemSpec.snapshotRetention(0)meaningful. - [Info]
E2bPlatformHttpTest.java:315— deleting the vacuous assertion also removes the only coverage of the blank-apiBaseUrl->trimSlashdefault.
Suggestions
Both warnings are small: record the id doPersistWorkspace() created and remove that single element on failure, and extend SandboxLifecycleMiddlewareReleaseOrderTest with the stop()-throws case asserting persistState still runs.
Automated review by github-manager-bot
The failed persist drops its own snapshot id from the record by identity rather than by position, so an id another session appended to the shared state while the archive persist was in flight survives the rollback. SandboxManager.release swallows the stop failure and the state is persisted after release, so the corrected record still reaches the store. Covered by stopFailureDropsOnlyTheIdItsOwnPersistRecorded (identity rollback), a failure-path case in SandboxLifecycleMiddlewareReleaseOrderTest (real release plus persist), and failedStopPersistsRolledBackRecordThroughSandboxManager (the rolled-back record visible in the persisted state). E2bPlatformHttp.trimSlash is now package-private and asserted directly, restoring the blank-base-url coverage lost with the removed vacuous test.
同步 upstream/main (3a6baf6, 21 个提交) 到 develop。唯一触及 e2b 模块的上游 提交是 agentscope-ai#2555 auto-prune old NATIVE_SNAPSHOT snapshots per sandbox。 冲突处理(8 个 e2b 文件): - snapshot 清理采用 upstream 实现: E2bSandboxState.snapshotIds 记录创建顺序 + E2bPlatformHttp.cleanupSnapshots/dedupe,删除本地已被取代的 pruneSnapshots/append 旧 API;per-call retention 仅在为正时覆盖 client 默认值 - 保留 develop 私有特性: E2B 持久化卷 (volumeMounts/workspaceOnVolume/ volumeTarExcludeArgs)、基于 E2B Filesystem REST API 的 tar 传输 - 测试以 upstream 版为底,workspace-root 断言改回本地统一 WorkspaceSpec API (spec.workspaceSpec().getRoot()) e2b 模块 103 个测试通过。
Closes #2547
Adds a configurable
snapshotRetentionto cap per-session cloud snapshot storage inNATIVE_SNAPSHOTmode.Changes
snapshotRetentionoption wired throughE2bSandboxClientOptionsand exposed onE2bFilesystemSpec; default0(disabled),<=0disables pruningE2bSandboxStategainssnapshotIds, a per-session record of the snapshots this session has created (most recent last), persisted with the sandbox state; older serialized states lacking the field default to an empty list (backwards compatible)retentionids by insertion order (most recent last) and deletes the rest viaDELETE /templates/{snapshotId}(404 idempotent). Insertion order equals creation time because the list is appended on each persist, so no alias timestamp parsing is needed and anysnapshotIDformat is supported.deleteSnapshotbuilds the URL withHttpUrl.addPathSegment, URL-encoding the namespace/in a snapshot id (team/alias:tag->%2F); an unencoded path was parsed as an extra segment and E2B returned 404Design notes (vs. proposal in #2547)
E2B locks a snapshot template while a sandbox restored from it is running and rejects deleting it with
HTTP 400. Pruning is therefore deferred toshutdown():persistonly appends to the per-session record, and afterkillSandboxunlocks the templatesE2bPlatformHttp.cleanupSnapshotskeeps the lastsnapshotRetentionids by insertion order and deletes the rest in one pass, correcting any residue from earlier persists.Fixes
SandboxLifecycleMiddleware.releaseForCall(): it now releases (stop/persist) the sandbox before persisting the state, so mutations made duringstop()— including the per-session snapshot record updated indoPersistWorkspace— are captured by the state persist.Issue proposed pruning per sandbox via
GET /snapshots?sandboxID=..., with a default of1. This approach was verified against the live API to be insufficient for sessions resumed from their own snapshots: the source sandbox id changes on every restore, so asandboxIDfilter never sees the session's older snapshots, and E2B's explicitkill()does not delete historic snapshots either.This PR therefore keeps a per-session record in
E2bSandboxStateinstead of queryingGET /snapshotsat all, making pruning independent of both the sandbox id and any team-wide listing. Default stays0to preserve historical behaviour (opt-in).Tests
14 e2b module tests pass, including 11
E2bPlatformHttpTestcases covering delete semantics (incl. URL encoding), FIFO retention by insertion order (snap-*andteam/alias:tag), and failure tolerance.