diff --git a/docs/sandbox-docker-backend.md b/docs/sandbox-docker-backend.md index 37f1b7f4..5a03b2ef 100644 --- a/docs/sandbox-docker-backend.md +++ b/docs/sandbox-docker-backend.md @@ -168,6 +168,32 @@ WeKnora 自己跑在容器里时,要把 **实际的** docker socket 挂进 app 两个要注意的约束:镜像层上限 127,长期增量要定期压平;快照是本机资产,多机部署必须推到 registry。 压平和跨 daemon 分发还不在这条路径里。 +磁盘占用的实际形态和 Cube / E2B 不一样,值得单独说清楚: + +- 第 N+1 代是从第 N 代起的容器 commit 出来的,**N 的层完整包含在 N+1 里**。所以两代镜像并存 + 时,旧的那个 tag 不额外占盘;反过来说,`PruneSupersededSnapshots` 到期删掉旧 tag 也几乎 + 回收不了空间。真正回收发生在整条链的 tag 全部退役之后,因此 `DeleteSnapshot` 必须带 + `PruneChildren`(即 `noprune=0`),否则无 tag 的祖先层会永久留下。 +- **卸载一个 skill 会让镜像变大**:`rm -rf` 在 overlay 上是新增一层 whiteout,被删的文件仍 + 留在父层。也就是说装和卸都只增不减,Cube / E2B 是每代一张独立模板、到期真删,只有 Docker + 是单调累积。要把空间还回来,只能从基础模板重建整条链——`SkillSnapshotTriggerRebuild` 为此 + 预留了,但重建流程尚未实现。 +- 快照的 owner fingerprint 只在 host 是**显式配置**时才把 host 计入。留空的配置一律记成 + `local-daemon`,不能采用 `DetectLocalDockerHost()` 的结果:那个值来自 `DOCKER_HOST` 或当前 + docker context,切一次 Colima / Docker Desktop / OrbStack 就会变,而它一变就等价于「凭据 + 轮换」——会话静默退回基础模板(skill 全部消失)、安装被拒、快照清理被永久跳过。本机 daemon + 换个 host 字符串通常还是同一块盘上的同一批镜像,跨账号那套推理在这里不成立。 + +回收路径依赖 ledger 能给每张快照命名,而 `snapshot_id` 只有在 provider 应答之后才写得下来。 +进程死在 commit 与那次写入之间,就会留下一张谁都叫不出名字的快照:`PruneSupersededSnapshots` +因为状态是 `building` 而跳过它,`ReconcileSnapshots` 只告警不删,配置删除时空 `snapshot_id` +被当成「无需释放」。因此 `planned_name` 在 commit **之前**就落库(迁移 000088),之后靠 +provider 的 `ListSnapshots` 按名字认领:Cube / E2B 会把请求的名字回显在 `Names` 里,Docker 的 +ID 本身就是这个名字加上 `weknora-skill/` 前缀。两条路径会用它——周期清理里的 +`reapAbandonedBuilds`,以及配置删除时的 `resolveAbandonedBuildIDs`(配置一删,周期清理就再也 +遍历不到这张快照,那是最后一次机会)。只有**认领成功**才会删;名字对不上时不动,因为无法区分 +「commit 从未发生」和「该 provider 不回显名字」,猜错就等于丢掉一张仍然存在的快照的唯一记录。 + ## 测试 单元测试用一个内存版 Engine API 驱动适配器,不需要 daemon: diff --git a/internal/application/service/tenant_sandbox_config.go b/internal/application/service/tenant_sandbox_config.go index 6abb559f..3db67371 100644 --- a/internal/application/service/tenant_sandbox_config.go +++ b/internal/application/service/tenant_sandbox_config.go @@ -789,15 +789,64 @@ func snapshotReleaserFrom(client sandbox.ConfigSandboxClient) (sandboxSnapshotRe return releaser, ok } -func pendingHaveProviderIDs(rows []*types.TenantSkillSnapshotEntity) bool { +// pendingNeedProvider reports whether releasing these rows has to talk to the +// provider at all. A planned name counts: it is how an abandoned build — one +// whose commit outlived the process that started it — is still addressable. +func pendingNeedProvider(rows []*types.TenantSkillSnapshotEntity) bool { for _, row := range rows { - if row != nil && strings.TrimSpace(row.SnapshotID) != "" { + if row == nil { + continue + } + if strings.TrimSpace(row.SnapshotID) != "" || + strings.TrimSpace(row.PlannedName) != "" { return true } } return false } +// resolveAbandonedBuildIDs fills in the provider ID of a build that died +// between its commit and the ledger write. +// +// This is the last chance to reclaim one: PruneSupersededSnapshots walks live +// configs, so once this config's row is gone the snapshot is unreachable by +// anything. A name that resolves to nothing is left alone — the usual reason +// is that the commit never happened, and there is no resource to release. +func resolveAbandonedBuildIDs( + ctx context.Context, + client sandbox.ConfigSandboxClient, + pending []*types.TenantSkillSnapshotEntity, +) { + unresolved := make([]*types.TenantSkillSnapshotEntity, 0, len(pending)) + for _, row := range pending { + if row != nil && strings.TrimSpace(row.SnapshotID) == "" && + strings.TrimSpace(row.PlannedName) != "" { + unresolved = append(unresolved, row) + } + } + if len(unresolved) == 0 { + return + } + lister, ok := client.(skillSnapshotLister) + if !ok { + return + } + listed, err := lister.ListSnapshots(ctx, "") + if err != nil { + logger.Warnf(ctx, "[sandbox] list snapshots to release abandoned builds failed: %v", err) + return + } + for _, row := range unresolved { + id := matchSnapshotByName(listed, row.PlannedName) + if id == "" { + continue + } + logger.Infof(ctx, "[sandbox] abandoned build %s resolved to snapshot %s for release", + row.PlannedName, id) + row.SnapshotID = id + } +} + func pendingSkillSnapshots(rows []*types.TenantSkillSnapshotEntity) []*types.TenantSkillSnapshotEntity { var out []*types.TenantSkillSnapshotEntity for _, row := range rows { @@ -865,8 +914,15 @@ func (s *TenantSandboxConfigService) destroyPendingSnapshots( } releaser := sandboxSnapshotReleaser(nil) - if pendingHaveProviderIDs(pending) { - releaser = s.snapshotReleaserFor(ctx, entity) + if pendingNeedProvider(pending) { + client := s.snapshotClientFor(ctx, entity) + resolveAbandonedBuildIDs(ctx, client, pending) + if found, ok := snapshotReleaserFrom(client); ok { + releaser = found + } else if client != nil { + logger.Warnf(ctx, "[sandbox] config %s provider does not support snapshot delete", + entityID(entity)) + } } var remaining []string for _, row := range pending { @@ -884,9 +940,13 @@ func (s *TenantSandboxConfigService) destroyPendingSnapshots( return remaining } -func (s *TenantSandboxConfigService) snapshotReleaserFor( +// snapshotClientFor builds the provider client config deletion needs to +// release this config's snapshots. It returns the client rather than just the +// delete capability because an abandoned build has to be looked up by name +// first, which is a different capability on the same client. +func (s *TenantSandboxConfigService) snapshotClientFor( ctx context.Context, entity *types.TenantSandboxConfigEntity, -) sandboxSnapshotReleaser { +) sandbox.ConfigSandboxClient { cfg := (*types.TenantSandboxConfig)(nil) if entity != nil { cfg = entity.Config @@ -897,13 +957,7 @@ func (s *TenantSandboxConfigService) snapshotReleaserFor( entityID(entity), err) return nil } - releaser, ok := snapshotReleaserFrom(client) - if !ok { - logger.Warnf(ctx, "[sandbox] config %s provider does not support snapshot delete", - entityID(entity)) - return nil - } - return releaser + return client } func entityID(entity *types.TenantSandboxConfigEntity) string { diff --git a/internal/application/service/tenant_sandbox_config_test.go b/internal/application/service/tenant_sandbox_config_test.go index 6d970d51..1ff3db1c 100644 --- a/internal/application/service/tenant_sandbox_config_test.go +++ b/internal/application/service/tenant_sandbox_config_test.go @@ -1109,6 +1109,70 @@ func TestDeleteMarksBuildingSnapshotsWhenProviderHasNoSnapshotClient(t *testing. require.Contains(t, skills.marks, "row-build:"+types.SkillSnapshotStateDeleted) } +// Deleting the config is the last chance to reclaim a build that died between +// its commit and the ledger write: PruneSupersededSnapshots walks live configs, +// so once this row is gone nothing can reach that snapshot again. +func TestDeleteReleasesAnAbandonedBuildByPlannedName(t *testing.T) { + repo := &fakeConfigRepo{entity: &types.TenantSandboxConfigEntity{ + ID: "cfg-a", TenantID: 7, Name: "prod", SandboxType: "e2b", + Config: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300), + }} + skills := &deleteSkillStore{ + snapshots: []*types.TenantSkillSnapshotEntity{{ + ID: "row-build", TenantID: 7, SandboxConfigID: "cfg-a", + PlannedName: "weknora-sk-cfga-g3", State: types.SkillSnapshotStateBuilding, + }}, + } + var events []string + client := &snapshotReleaseClient{ + events: &events, + listed: []sandbox.RemoteSnapshotRef{ + {ID: "snap-orphan", Names: []string{"weknora-sk-cfga-g3"}}, + }, + } + svc := newTestConfigService(t, repo, &client.stubProviderClient, stubAgentRepo{}) + svc.skills = skills + svc.newClient = func(*sandbox.Config) (sandbox.ConfigSandboxClient, error) { + return client, nil + } + + require.NoError(t, svc.Delete(context.Background(), 7, "cfg-a", false)) + + require.Equal(t, []string{"list-snapshots", "snap-orphan"}, events, + "the name has to be resolved to a provider ID before it can be released") + require.Contains(t, skills.marks, "row-build:"+types.SkillSnapshotStateDeleted) + require.True(t, repo.deleted) +} + +// A planned name that resolves to nothing is the ordinary case: the commit +// never happened, so there is no provider resource to release. +func TestDeleteAcceptsAnAbandonedBuildThatNeverCommitted(t *testing.T) { + repo := &fakeConfigRepo{entity: &types.TenantSandboxConfigEntity{ + ID: "cfg-a", TenantID: 7, Name: "prod", SandboxType: "e2b", + Config: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300), + }} + skills := &deleteSkillStore{ + snapshots: []*types.TenantSkillSnapshotEntity{{ + ID: "row-build", TenantID: 7, SandboxConfigID: "cfg-a", + PlannedName: "weknora-sk-cfga-g3", State: types.SkillSnapshotStateBuilding, + }}, + } + var events []string + client := &snapshotReleaseClient{events: &events} + svc := newTestConfigService(t, repo, &client.stubProviderClient, stubAgentRepo{}) + svc.skills = skills + svc.newClient = func(*sandbox.Config) (sandbox.ConfigSandboxClient, error) { + return client, nil + } + + require.NoError(t, svc.Delete(context.Background(), 7, "cfg-a", false)) + + require.Equal(t, []string{"list-snapshots"}, events, + "nothing carries that name, so there is nothing to delete") + require.Contains(t, skills.marks, "row-build:"+types.SkillSnapshotStateDeleted) + require.True(t, repo.deleted) +} + // snapshotReleaseFixture drives Delete through a provider that also implements // snapshot deletion, which is the production Cube/E2B split. type snapshotReleaseFixture struct { @@ -1177,6 +1241,17 @@ type snapshotReleaseClient struct { stubProviderClient events *[]string failDelete map[string]error + listed []sandbox.RemoteSnapshotRef +} + +func (c *snapshotReleaseClient) ListSnapshots( + ctx context.Context, sandboxID string, +) ([]sandbox.RemoteSnapshotRef, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + *c.events = append(*c.events, "list-snapshots") + return c.listed, nil } func (c *snapshotReleaseClient) List( diff --git a/internal/application/service/tenant_skill_install.go b/internal/application/service/tenant_skill_install.go index 14fe1757..6c1c3b42 100644 --- a/internal/application/service/tenant_skill_install.go +++ b/internal/application/service/tenant_skill_install.go @@ -361,14 +361,19 @@ func (s *TenantSkillService) runInstall( // cordon, which this lock says nothing about — hence the re-read there. generation := currentGeneration(cfgEntity) + 1 installRowID := uuid.NewString() + // The name is recorded with the row rather than derived at the call below, + // so a run that dies during the commit still leaves the ledger able to + // name what it was building. Without it the snapshot would be a provider + // resource nothing could ever address, let alone reclaim. + snapshotName := skillSnapshotBuildName(configID, generation) if err := s.skills.CreateSnapshotRow(ctx, &types.TenantSkillSnapshotEntity{ ID: installRowID, TenantID: tenantID, SandboxConfigID: configID, SkillID: skillID, ParentSnapshotID: currentSnapshotID(cfgEntity), Generation: generation, Trigger: types.SkillSnapshotTriggerInstall, State: types.SkillSnapshotStateBuilding, + PlannedName: snapshotName, }); err != nil { return err } - snapshotName := fmt.Sprintf("weknora-sk-%s-g%d", shortID(configID), generation) ref, err := s.createSnapshot(ctx, mgr, sess.ID, snapshotName) if err != nil { return err @@ -1324,6 +1329,14 @@ func currentSnapshotID(cfgEntity *types.TenantSandboxConfigEntity) string { return cfgEntity.Config.SkillImage.SnapshotID } +// skillSnapshotBuildName is the name every generation of a config's image +// chain is committed under. It is deterministic so the abandoned-build sweep +// can match a provider listing against a ledger row that never learned its +// snapshot ID. +func skillSnapshotBuildName(configID string, generation int) string { + return fmt.Sprintf("weknora-sk-%s-g%d", shortID(configID), generation) +} + func shortID(id string) string { trimmed := strings.ReplaceAll(strings.TrimSpace(id), "-", "") if len(trimmed) > 8 { diff --git a/internal/application/service/tenant_skill_reaper.go b/internal/application/service/tenant_skill_reaper.go index 882351bb..67b8b20a 100644 --- a/internal/application/service/tenant_skill_reaper.go +++ b/internal/application/service/tenant_skill_reaper.go @@ -404,6 +404,12 @@ func configuredSandboxTTL(cfg *types.TenantSandboxConfig) time.Duration { if cfg.E2B != nil && cfg.E2B.E2BSandboxTTLSeconds > seconds { seconds = cfg.E2B.E2BSandboxTTLSeconds } + // Docker's equivalent is the idle TTL: the daemon has none of its own, so + // that is how long a container created from the previous image may still + // be sitting there unused. + if cfg.Docker != nil && cfg.Docker.IdleTTLSeconds > seconds { + seconds = cfg.Docker.IdleTTLSeconds + } if seconds <= 0 { return 0 } @@ -501,7 +507,145 @@ func (s *TenantSkillService) pruneConfigSnapshots( } pruned++ } - return pruned, nil + return pruned + s.reapAbandonedBuilds(ctx, cfg, rows), nil +} + +// reapAbandonedBuilds deletes the provider snapshot of a build that never +// reached the ledger. It is the only path that can. +// +// A row is written as building, the provider commit runs, and only then is the +// snapshot's ID recorded. A process that dies in that window leaves a real, +// billed snapshot whose ID exists nowhere: PruneSupersededSnapshots skips the +// row because building is not a prunable state and its SnapshotID is empty, +// ReconcileSnapshots reports it as an extra but deliberately never deletes, and +// the config-delete path reads an empty SnapshotID as nothing to release. +// PlannedName is what closes that, because it is written before the commit. +// +// Only a positive match is acted on. A listing that names nothing we recognise +// cannot tell "the commit never happened" from "this provider does not echo +// names back", and marking the row deleted on that guess would throw away the +// last record of a snapshot that is still there. +func (s *TenantSkillService) reapAbandonedBuilds( + ctx context.Context, cfg *types.TenantSandboxConfigEntity, + rows []*types.TenantSkillSnapshotEntity, +) int { + cutoff := s.clock()().Add(-skillInstallStuckTTL) + pending := make([]*types.TenantSkillSnapshotEntity, 0, len(rows)) + for _, row := range rows { + if abandonedBuild(row, cutoff) && !s.buildStillRunning(ctx, row) { + pending = append(pending, row) + } + } + if len(pending) == 0 { + return 0 + } + + lister := snapshotListerFrom(ctx, s.sandboxes, cfg.TenantID, cfg.ID) + deleter := snapshotDeleterFrom(ctx, s.sandboxes, cfg.TenantID, cfg.ID) + if lister == nil || deleter == nil { + return 0 + } + listed, err := lister.ListSnapshots(ctx, "") + if err != nil { + logger.Warnf(ctx, "[skill] list snapshots to reap abandoned builds of config %s failed: %v", + cfg.ID, err) + return 0 + } + + live := strings.TrimSpace(currentSnapshotID(cfg)) + reaped := 0 + for _, row := range pending { + found := matchSnapshotByName(listed, row.PlannedName) + // Unreachable by construction — the pointer moves after the ID is + // recorded, so a building row cannot be live — but the delete is + // irreversible, so the guard stays. + if found == "" || found == live { + continue + } + if err := deleter.DeleteSnapshot(ctx, found); err != nil && !sandbox.IsRemoteNotFound(err) { + logger.Warnf(ctx, "[skill] delete abandoned build %s of config %s failed: %v", + found, cfg.ID, err) + continue + } + if err := s.skills.MarkSnapshotState( + ctx, cfg.TenantID, row.ID, types.SkillSnapshotStateDeleted, found, + ); err != nil { + logger.Warnf(ctx, "[skill] mark abandoned build %s deleted failed: %v", row.ID, err) + continue + } + logger.Infof(ctx, "[skill] reclaimed abandoned build %s of config %s", found, cfg.ID) + reaped++ + } + return reaped +} + +// abandonedBuild reports a building row old enough that the commit it was +// waiting on cannot still be running. The row is written immediately before the +// provider call and marked active immediately after, so the window is one +// commit wide; skillInstallStuckTTL is the same silence budget ReapStuckRuns +// gives a whole install. +func abandonedBuild(row *types.TenantSkillSnapshotEntity, cutoff time.Time) bool { + if row == nil || row.State != types.SkillSnapshotStateBuilding { + return false + } + if strings.TrimSpace(row.PlannedName) == "" { + // Written before PlannedName existed. Nothing can name its snapshot. + return false + } + return row.CreatedAt.Before(cutoff) +} + +// buildStillRunning reports whether the run that opened this row is alive. +// +// The age check alone would be enough for any commit that finishes in the +// minutes it normally takes, but a huge image on a slow remote daemon could +// exceed it — and deleting the snapshot of a commit that then succeeds would +// switch the config's pointer to an image that no longer exists. The install +// keeps stamping InstallingSince, so that is what says "still working". +func (s *TenantSkillService) buildStillRunning( + ctx context.Context, row *types.TenantSkillSnapshotEntity, +) bool { + skill, err := s.skills.GetSkill(ctx, row.TenantID, row.SandboxConfigID, row.SkillID) + if err != nil { + // Cannot tell; refuse to guess before an irreversible delete. + return true + } + if skill == nil || skill.InstallingSince == nil { + return false + } + switch skill.Status { + case types.SkillStatusInstalling, types.SkillStatusRemoving: + return skill.InstallingSince.After(s.clock()().Add(-skillInstallStuckTTL)) + } + return false +} + +// matchSnapshotByName finds the provider snapshot a planned name refers to. +// +// Cube and E2B mint their own ID and echo the requested name in Names. Docker's +// ID *is* the name, prefixed with the local repository it commits into, which +// is why a trailing path segment counts as a match. +func matchSnapshotByName(listed []sandbox.RemoteSnapshotRef, plannedName string) string { + want := strings.TrimSpace(plannedName) + if want == "" { + return "" + } + for _, ref := range listed { + candidates := append([]string{ref.ID}, ref.Names...) + for _, candidate := range candidates { + candidate = strings.TrimSpace(candidate) + if candidate == "" { + continue + } + if candidate == want || strings.HasSuffix(candidate, "/"+want) { + if id := strings.TrimSpace(ref.ID); id != "" { + return id + } + return candidate + } + } + } + return "" } // snapshotEligibleForPrune is the ledger-side gate. The provider delete is diff --git a/internal/application/service/tenant_skill_reaper_test.go b/internal/application/service/tenant_skill_reaper_test.go index 49cb6c42..7522e4af 100644 --- a/internal/application/service/tenant_skill_reaper_test.go +++ b/internal/application/service/tenant_skill_reaper_test.go @@ -429,6 +429,130 @@ func TestPruneSupersededSnapshotsHonoursALongerConfiguredSandboxTTL(t *testing.T "a config whose sandbox TTL exceeds the floor must keep templates that young") } +// A process that dies between the commit and the ledger write leaves a real, +// billed snapshot whose ID exists nowhere. PlannedName is written before the +// provider call precisely so this sweep can still name it. +func TestPruneReclaimsAnAbandonedBuildByPlannedName(t *testing.T) { + fx := newReaperFixture(t) + fx.live("snap-live") + fx.installed("sk-1", "snap-live", "") + fx.building("sk-2", "weknora-sk-cfg1-g2", fx.now.Add(-skillInstallStuckTTL-time.Minute)) + fx.provider.listed = []sandbox.RemoteSnapshotRef{ + {ID: "snap-live"}, + {ID: "snap-orphan", Names: []string{"weknora-sk-cfg1-g2"}}, + } + + n, err := fx.svc.PruneSupersededSnapshots(context.Background()) + + require.NoError(t, err) + require.Equal(t, 1, n) + require.Equal(t, []string{"snap-orphan"}, fx.provider.deleted, + "the snapshot is addressed by the provider ID the listing matched, not by the name") + require.Equal(t, types.SkillSnapshotStateDeleted, + fx.snapshotState(t, "row-weknora-sk-cfg1-g2")) +} + +// Docker's snapshot ID *is* the planned name, prefixed with the local +// repository it commits into. +func TestPruneReclaimsAnAbandonedBuildThroughARepositoryPrefix(t *testing.T) { + fx := newReaperFixture(t) + fx.building("sk-2", "weknora-sk-cfg1-g2", fx.now.Add(-skillInstallStuckTTL-time.Minute)) + fx.provider.listed = []sandbox.RemoteSnapshotRef{ + {ID: "weknora-skill/weknora-sk-cfg1-g2", Names: []string{"weknora-skill/weknora-sk-cfg1-g2"}}, + } + + n, err := fx.svc.PruneSupersededSnapshots(context.Background()) + + require.NoError(t, err) + require.Equal(t, 1, n) + require.Equal(t, []string{"weknora-skill/weknora-sk-cfg1-g2"}, fx.provider.deleted) +} + +// A listing that names nothing we recognise cannot distinguish "the commit +// never happened" from "this provider does not echo names back". Guessing +// would discard the last record of a snapshot that is still there. +func TestPruneLeavesAnUnmatchedAbandonedBuildOnTheLedger(t *testing.T) { + fx := newReaperFixture(t) + fx.building("sk-2", "weknora-sk-cfg1-g2", fx.now.Add(-skillInstallStuckTTL-time.Minute)) + fx.provider.listed = []sandbox.RemoteSnapshotRef{{ID: "snap-unrelated"}} + + n, err := fx.svc.PruneSupersededSnapshots(context.Background()) + + require.NoError(t, err) + require.Zero(t, n) + require.Empty(t, fx.provider.deleted) + require.Equal(t, types.SkillSnapshotStateBuilding, + fx.snapshotState(t, "row-weknora-sk-cfg1-g2")) +} + +// A huge image on a slow daemon can commit for longer than the age cutoff, and +// deleting the snapshot of a commit that then succeeds would point the config +// at an image that no longer exists. +func TestPruneLeavesABuildWhoseInstallIsStillBeating(t *testing.T) { + fx := newReaperFixture(t) + alive := fx.now.Add(-time.Minute) + fx.skills.put(&types.TenantSkillEntity{ + ID: "sk-2", TenantID: 7, SandboxConfigID: "cfg-1", + Name: "pdf", Status: types.SkillStatusInstalling, InstallingSince: &alive, + }) + fx.building("sk-2", "weknora-sk-cfg1-g2", fx.now.Add(-skillInstallStuckTTL-time.Minute)) + fx.provider.listed = []sandbox.RemoteSnapshotRef{ + {ID: "snap-orphan", Names: []string{"weknora-sk-cfg1-g2"}}, + } + + n, err := fx.svc.PruneSupersededSnapshots(context.Background()) + + require.NoError(t, err) + require.Zero(t, n) + require.Empty(t, fx.provider.deleted) + require.Zero(t, fx.resolver.resolves, + "a live install must not even cost a provider client") +} + +func TestPruneLeavesARecentBuildAlone(t *testing.T) { + fx := newReaperFixture(t) + fx.building("sk-2", "weknora-sk-cfg1-g2", fx.now.Add(-time.Minute)) + fx.provider.listed = []sandbox.RemoteSnapshotRef{ + {ID: "snap-orphan", Names: []string{"weknora-sk-cfg1-g2"}}, + } + + n, err := fx.svc.PruneSupersededSnapshots(context.Background()) + + require.NoError(t, err) + require.Zero(t, n) + require.Empty(t, fx.provider.deleted, "the commit may still be running") +} + +// Rows written before planned_name existed name nothing, so there is no safe +// way to tell which provider snapshot was theirs. +func TestPruneLeavesALegacyBuildWithNoPlannedName(t *testing.T) { + fx := newReaperFixture(t) + fx.building("sk-2", "", fx.now.Add(-skillInstallStuckTTL-time.Minute)) + fx.provider.listed = []sandbox.RemoteSnapshotRef{{ID: "snap-orphan"}} + + n, err := fx.svc.PruneSupersededSnapshots(context.Background()) + + require.NoError(t, err) + require.Zero(t, n) + require.Empty(t, fx.provider.deleted) +} + +// The docker daemon has no TTL of its own, so a container created from the +// previous image sits there until the idle sweep reclaims it. That window is +// what the snapshot has to outlive, exactly as the Cube and E2B TTLs are. +func TestConfiguredSandboxTTLCoversTheDockerIdleWindow(t *testing.T) { + require.Equal(t, 48*time.Hour, configuredSandboxTTL(&types.TenantSandboxConfig{ + SandboxType: "docker", + Docker: &types.DockerSandboxConfig{ + IdleTTLSeconds: int((48 * time.Hour).Seconds()), + }, + })) + require.Zero(t, configuredSandboxTTL(&types.TenantSandboxConfig{ + SandboxType: "docker", + Docker: &types.DockerSandboxConfig{}, + }), "an unset idle TTL leaves the retention floor in charge") +} + func TestTenantSkillServiceStartIsIdempotent(t *testing.T) { svc := NewTenantSkillService(nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) @@ -512,6 +636,31 @@ func (f *reaperFixture) superseded(skillID, snapshotID, parentSnapshotID string, }) } +// building writes the row an install leaves behind between CreateSnapshotRow +// and the ledger learning the snapshot's ID: named, but with no provider ID. +func (f *reaperFixture) building(skillID, plannedName string, createdAt time.Time) { + f.skills.snapshots = append(f.skills.snapshots, &types.TenantSkillSnapshotEntity{ + ID: "row-" + plannedName, TenantID: 7, SandboxConfigID: "cfg-1", SkillID: skillID, + PlannedName: plannedName, Generation: 2, + Trigger: types.SkillSnapshotTriggerInstall, + State: types.SkillSnapshotStateBuilding, + CreatedAt: createdAt, UpdatedAt: createdAt, + }) +} + +func (f *reaperFixture) snapshotState(t *testing.T, rowID string) string { + t.Helper() + rows, err := f.skills.ListSnapshotsByConfig(context.Background(), 7, "cfg-1") + require.NoError(t, err) + for _, row := range rows { + if row.ID == rowID { + return row.State + } + } + t.Fatalf("snapshot row %s not found", rowID) + return "" +} + // live points the config at a snapshot, the way an install's pointer switch // does. func (f *reaperFixture) live(snapshotID string) { diff --git a/internal/application/service/tenant_skill_remove.go b/internal/application/service/tenant_skill_remove.go index f65c4cb3..a2db2527 100644 --- a/internal/application/service/tenant_skill_remove.go +++ b/internal/application/service/tenant_skill_remove.go @@ -227,14 +227,15 @@ func (s *TenantSkillService) runRemove( // The ledger row is written before the snapshot: a snapshot with no ledger // entry is a provider resource nobody knows exists. removeRowID := uuid.NewString() + snapshotName := skillSnapshotBuildName(configID, generation) if err := s.skills.CreateSnapshotRow(ctx, &types.TenantSkillSnapshotEntity{ ID: removeRowID, TenantID: tenantID, SandboxConfigID: configID, SkillID: skillID, ParentSnapshotID: currentSnapshotID(cfgEntity), Generation: generation, Trigger: types.SkillSnapshotTriggerRemove, State: types.SkillSnapshotStateBuilding, + PlannedName: snapshotName, }); err != nil { return err } - snapshotName := fmt.Sprintf("weknora-sk-%s-g%d", shortID(configID), generation) ref, err := s.createSnapshot(ctx, mgr, sess.ID, snapshotName) if err != nil { return err diff --git a/internal/sandbox/docker_remote_client_test.go b/internal/sandbox/docker_remote_client_test.go index 04de68ec..8c2265d2 100644 --- a/internal/sandbox/docker_remote_client_test.go +++ b/internal/sandbox/docker_remote_client_test.go @@ -66,11 +66,13 @@ type fakeDockerEngine struct { imagePresent map[string]bool pulled []string - committed []client.ContainerCommitOptions - commitID string - commitErr error - removedImages []string - removeImageErr error + committed []client.ContainerCommitOptions + commitID string + commitErr error + removedImages []string + removeImageOptions []client.ImageRemoveOptions + removeImageErr error + listImagesErr error } func newFakeDockerEngine() *fakeDockerEngine { @@ -247,13 +249,17 @@ func (f *fakeDockerEngine) ImagePull( func (f *fakeDockerEngine) ImageList( _ context.Context, _ client.ImageListOptions, ) (client.ImageListResult, error) { + if f.listImagesErr != nil { + return client.ImageListResult{}, f.listImagesErr + } return client.ImageListResult{Items: f.images}, nil } func (f *fakeDockerEngine) ImageRemove( - _ context.Context, imageID string, _ client.ImageRemoveOptions, + _ context.Context, imageID string, options client.ImageRemoveOptions, ) (client.ImageRemoveResult, error) { f.removedImages = append(f.removedImages, imageID) + f.removeImageOptions = append(f.removeImageOptions, options) if f.removeImageErr != nil { return client.ImageRemoveResult{}, f.removeImageErr } diff --git a/internal/sandbox/docker_snapshot.go b/internal/sandbox/docker_snapshot.go index 4d4bfffe..548c752c 100644 --- a/internal/sandbox/docker_snapshot.go +++ b/internal/sandbox/docker_snapshot.go @@ -62,12 +62,24 @@ func (c *DockerRemoteClient) CreateSnapshot( // DeleteSnapshot removes a committed skill image. A missing image is success: // the reaper and the install-compensation path both retry deletes. +// +// PruneChildren is what makes the delete reclaim anything. Each generation is +// committed from a container started off the previous one, so generation N+1 +// holds generation N's layers as ancestors. Untagging N alone therefore frees +// nothing while N+1 exists — which is correct and unavoidable — but the layers +// of a chain whose every tag has been retired would stay on disk forever +// without this, because the Go client defaults to noprune. Layers a live image +// still references are refcounted by the daemon, so cascading here cannot take +// the current image's storage out from under it. func (c *DockerRemoteClient) DeleteSnapshot(ctx context.Context, snapshotID string) error { id := strings.TrimSpace(snapshotID) if id == "" { return dockerInvalidRequest("DeleteSnapshot", "snapshot ID is required") } - _, err := c.api.ImageRemove(ctx, id, client.ImageRemoveOptions{Force: true}) + _, err := c.api.ImageRemove(ctx, id, client.ImageRemoveOptions{ + Force: true, + PruneChildren: true, + }) if err != nil { normalized := dockerError("DeleteSnapshot", err) if IsRemoteNotFound(normalized) { @@ -75,9 +87,48 @@ func (c *DockerRemoteClient) DeleteSnapshot(ctx context.Context, snapshotID stri } return normalized } + c.pruneDanglingSkillImages(ctx) return nil } +// pruneDanglingSkillImages drops skill-snapshot images that no longer carry a +// tag. Nothing can boot one: the ledger addresses snapshots by the tag minted +// in CreateSnapshot and never by digest, so an untagged one is unreachable by +// construction. They are left behind by a commit whose ledger write or pointer +// switch failed, and by every delete that ran before PruneChildren was set. +// +// Best effort by nature — reclaiming storage must never turn a successful +// delete into a failed one. An image a container still holds comes back as a +// conflict and is skipped; the next pass retries once that container is gone. +func (c *DockerRemoteClient) pruneDanglingSkillImages(ctx context.Context) { + listed, err := c.api.ImageList(ctx, client.ImageListOptions{ + All: true, + Filters: client.Filters{}.Add("label", dockerSkillSnapshotLabel+"=true"), + }) + if err != nil { + return + } + for _, item := range listed.Items { + if !dockerImageIsSkillSnapshot(item) || dockerImageHasTag(item) { + continue + } + id := strings.TrimSpace(item.ID) + if id == "" { + continue + } + _, _ = c.api.ImageRemove(ctx, id, client.ImageRemoveOptions{PruneChildren: true}) + } +} + +func dockerImageHasTag(item image.Summary) bool { + for _, tag := range item.RepoTags { + if strings.TrimSpace(tag) != "" && tag != ":" { + return true + } + } + return false +} + // ListSnapshots returns skill-snapshot images on this daemon. An empty // sandboxID lists every skill snapshot; a non-empty one keeps those committed // from that container. diff --git a/internal/sandbox/docker_snapshot_test.go b/internal/sandbox/docker_snapshot_test.go index df0ce141..989430ce 100644 --- a/internal/sandbox/docker_snapshot_test.go +++ b/internal/sandbox/docker_snapshot_test.go @@ -2,6 +2,7 @@ package sandbox import ( "context" + "errors" "testing" "github.com/moby/moby/api/types/image" @@ -74,6 +75,77 @@ func TestDockerSnapshotRoundTripAndListFilter(t *testing.T) { require.Equal(t, second.ID, fromA[0].ID) } +// Each generation is committed from a container started off the previous one, +// so untagging one alone frees nothing while its descendant lives. Without +// noprune=0 the layers of a fully retired chain would stay on disk forever. +func TestDockerDeleteSnapshotPrunesUntaggedAncestors(t *testing.T) { + engine := newFakeDockerEngine() + docker := newTestDockerClient(t, engine) + + ref, err := docker.CreateSnapshot(context.Background(), "container-a", "weknora-sk-a-g1") + require.NoError(t, err) + require.NoError(t, docker.DeleteSnapshot(context.Background(), ref.ID)) + + require.True(t, engine.removeImageOptions[0].PruneChildren, + "a delete that keeps untagged parents can never reclaim a retired chain") + require.True(t, engine.removeImageOptions[0].Force) +} + +// A skill snapshot the ledger cannot name is unreachable: snapshots are always +// addressed by the tag CreateSnapshot mints, never by digest. +func TestDockerDeleteSnapshotSweepsUntaggedSkillImages(t *testing.T) { + engine := newFakeDockerEngine() + engine.images = []image.Summary{ + { + ID: "sha256:retired", + RepoTags: []string{"weknora-skill/weknora-sk-a-g1:latest"}, + Labels: map[string]string{dockerSkillSnapshotLabel: "true"}, + }, + { + ID: "sha256:orphan", + RepoTags: []string{":"}, + Labels: map[string]string{dockerSkillSnapshotLabel: "true"}, + }, + { + ID: "sha256:live", + RepoTags: []string{"weknora-skill/weknora-sk-a-g2:latest"}, + Labels: map[string]string{dockerSkillSnapshotLabel: "true"}, + }, + { + ID: "sha256:base", + RepoTags: []string{"weknora/sandbox:test"}, + Labels: map[string]string{dockerTemplateLabel: "true"}, + }, + } + docker := newTestDockerClient(t, engine) + + require.NoError(t, docker.DeleteSnapshot( + context.Background(), "weknora-skill/weknora-sk-a-g1")) + + require.Equal(t, + []string{"weknora-skill/weknora-sk-a-g1", "sha256:orphan"}, + engine.removedImages, + "the sweep must take the untagged snapshot and nothing that is still named") +} + +func TestDockerDeleteSnapshotSweepFailureIsNotAnError(t *testing.T) { + engine := newFakeDockerEngine() + engine.images = []image.Summary{ + { + ID: "sha256:orphan", + RepoTags: []string{":"}, + Labels: map[string]string{dockerSkillSnapshotLabel: "true"}, + }, + } + engine.imagePresent["weknora-skill/weknora-sk-a-g1"] = true + engine.listImagesErr = errors.New("daemon busy") + docker := newTestDockerClient(t, engine) + + require.NoError(t, docker.DeleteSnapshot( + context.Background(), "weknora-skill/weknora-sk-a-g1"), + "reclaiming storage must not turn a completed delete into a failure") +} + func TestDockerListTemplatesHidesSkillSnapshots(t *testing.T) { engine := newFakeDockerEngine() engine.images = []image.Summary{ diff --git a/internal/sandbox/skill_image.go b/internal/sandbox/skill_image.go index aefd87e5..5f1c1e92 100644 --- a/internal/sandbox/skill_image.go +++ b/internal/sandbox/skill_image.go @@ -63,13 +63,7 @@ func SkillImageActive(tenantCfg *types.TenantSandboxConfig) bool { tenantCfg.SkillImage, "e2b", tenantCfg.E2B.APIKey, tenantCfg.E2B.APIURL, ) != "" case SandboxTypeDocker: - if tenantCfg.Docker == nil { - return false - } - host, tls := dockerSkillOwnerIdentity(tenantCfg.Docker) - return skillImageTemplateOverride( - tenantCfg.SkillImage, "docker", tls, host, - ) != "" + return DockerSkillImageOverride(tenantCfg) != "" } return false } @@ -96,21 +90,50 @@ func SkillOwnerFingerprint(tenantCfg *types.TenantSandboxConfig) string { return "" } -// dockerSkillOwnerIdentity is the daemon this config will actually dial. -// A blank host follows the local docker CLI, which is also how -// ResolveEffectiveConfig fills DockerHost, so the fingerprint computed here -// matches the override computed there. +// dockerLocalDaemonIdentity stands in for a blank host in the fingerprint. +// +// It must not be the host DetectLocalDockerHost resolves to. That value comes +// from DOCKER_HOST or the current docker context, so it changes when an +// operator switches between Colima, Docker Desktop and OrbStack, or when the +// app is redeployed with a different environment. Feeding it into the +// fingerprint made all three of those look like a credential rotation: the +// session layer would drop the snapshot and boot the base template with no +// skills, installs would be refused, and PruneSupersededSnapshots would skip +// the config forever, so nothing ever reclaimed the images either. +// +// The account-rotation reasoning that fingerprint exists for does not carry +// over to a local daemon anyway. A rotated Cube/E2B key addresses a different +// account where our snapshot IDs genuinely do not exist; a re-detected local +// host is almost always the same daemon holding the same images on the same +// disk. An explicitly configured host is still part of the identity, because +// that one only changes when an admin edits the config. +const dockerLocalDaemonIdentity = "local-daemon" + +// dockerSkillOwnerIdentity is the daemon identity a skill snapshot is stamped +// with. It reads the STORED config rather than a resolved one so that every +// caller — the install path, SkillImageActive and ResolveEffectiveConfig — +// computes the fingerprint from the same inputs. func dockerSkillOwnerIdentity(docker *types.DockerSandboxConfig) (host, tls string) { if docker == nil { return "", "" } host = strings.TrimSpace(docker.Host) if host == "" { - host = DetectLocalDockerHost() + host = dockerLocalDaemonIdentity } return host, strings.TrimSpace(docker.TLSCertPath) } +// DockerSkillImageOverride returns the committed skill image the docker backend +// should boot instead of the config's base image, or "" to keep the base. +func DockerSkillImageOverride(tenantCfg *types.TenantSandboxConfig) string { + if tenantCfg == nil || tenantCfg.Docker == nil { + return "" + } + host, tls := dockerSkillOwnerIdentity(tenantCfg.Docker) + return skillImageTemplateOverride(tenantCfg.SkillImage, "docker", tls, host) +} + func dockerSkillOwnerFingerprint(docker *types.DockerSandboxConfig) string { if docker == nil { return "" diff --git a/internal/sandbox/tenant_config.go b/internal/sandbox/tenant_config.go index 41c392ae..39730ef5 100644 --- a/internal/sandbox/tenant_config.go +++ b/internal/sandbox/tenant_config.go @@ -138,9 +138,11 @@ func ResolveEffectiveConfig( effective.E2BTemplate = snapshot } case SandboxTypeDocker: - if snapshot := skillImageTemplateOverride( - tenantCfg.SkillImage, "docker", effective.DockerTLSCertPath, effective.DockerHost, - ); snapshot != "" { + // Deliberately computed from the STORED docker block, not from + // effective.DockerHost: a blank host is resolved from the environment + // by applyDockerRuntimeDefaults, and that resolved value must never + // reach the fingerprint (see dockerLocalDaemonIdentity). + if snapshot := DockerSkillImageOverride(tenantCfg); snapshot != "" { effective.DockerImage = snapshot } } diff --git a/internal/sandbox/tenant_config_test.go b/internal/sandbox/tenant_config_test.go index 2496d8b8..c78282e7 100644 --- a/internal/sandbox/tenant_config_test.go +++ b/internal/sandbox/tenant_config_test.go @@ -410,22 +410,58 @@ func TestResolveEffectiveConfigUsesSkillSnapshotAsDockerImage(t *testing.T) { "a snapshot from another daemon is invisible; the session must still boot") }) - t.Run("blank host fingerprints as the resolved daemon", func(t *testing.T) { - t.Setenv("DOCKER_HOST", "unix:///tmp/weknora-skill-docker.sock") - cfg := &types.TenantSandboxConfig{ - SandboxType: "docker", - Docker: &types.DockerSandboxConfig{Image: "weknora/sandbox:base"}, - SkillImage: &types.SkillImageConfig{ - SnapshotID: "weknora-skill/weknora-sk-cfg1-g1", - OwnerFingerprint: SkillImageFingerprint("docker", "", DetectLocalDockerHost()), - }, + // A blank host follows the environment, so binding the fingerprint to the + // resolved daemon would make "switch docker context" indistinguishable + // from "rotate the credentials": sessions would silently lose every + // skill, installs would be refused, and the snapshot prune would skip the + // config forever. The images are on the same disk either way. + t.Run("blank host survives a change of local daemon", func(t *testing.T) { + newConfig := func() *types.TenantSandboxConfig { + return &types.TenantSandboxConfig{ + SandboxType: "docker", + Docker: &types.DockerSandboxConfig{Image: "weknora/sandbox:base"}, + SkillImage: &types.SkillImageConfig{ + SnapshotID: "weknora-skill/weknora-sk-cfg1-g1", + OwnerFingerprint: SkillOwnerFingerprint(&types.TenantSandboxConfig{ + SandboxType: "docker", + Docker: &types.DockerSandboxConfig{Image: "weknora/sandbox:base"}, + }), + }, + } } - eff, err := ResolveEffectiveConfig(cfg, global) + for _, host := range []string{ + "unix:///tmp/colima.sock", + "unix:///tmp/orbstack.sock", + } { + t.Setenv("DOCKER_HOST", host) + cfg := newConfig() + + eff, err := ResolveEffectiveConfig(cfg, global) + + require.NoError(t, err) + require.Equal(t, "weknora-skill/weknora-sk-cfg1-g1", eff.DockerImage, + "DOCKER_HOST=%s must not retire the config's skill image", host) + require.True(t, SkillImageActive(cfg)) + } + }) + + // An explicit host is still part of the identity: only an admin editing + // the config can change it, and it may well be another machine. + t.Run("an explicit host change retires the image", func(t *testing.T) { + cfg := *base + cfg.Docker = &types.DockerSandboxConfig{ + Image: "weknora/sandbox:base", Host: "tcp://198.51.100.10:2376", + TLSCertPath: "/certs", + } + cfg.SkillImage = &types.SkillImageConfig{ + SnapshotID: "weknora-skill/weknora-sk-cfg1-g1", OwnerFingerprint: fp, + } + + eff, err := ResolveEffectiveConfig(&cfg, global) require.NoError(t, err) - require.Equal(t, "weknora-skill/weknora-sk-cfg1-g1", eff.DockerImage) - require.True(t, SkillImageActive(cfg)) + require.Equal(t, "weknora/sandbox:base", eff.DockerImage) }) } diff --git a/internal/types/tenant_skill.go b/internal/types/tenant_skill.go index fad685f9..6eebf27f 100644 --- a/internal/types/tenant_skill.go +++ b/internal/types/tenant_skill.go @@ -107,6 +107,15 @@ type TenantSkillSnapshotEntity struct { ParentSnapshotID string `gorm:"type:varchar(255)"` Generation int + // PlannedName is the name handed to CreateSnapshot. It is written before + // the provider call, which is what makes an abandoned build identifiable: + // SnapshotID can only be recorded once the provider has answered, so a + // process that died in between left a snapshot the ledger could not name + // and therefore could never reclaim. Matching is by name because only + // Docker's ID is derivable from it; Cube and E2B mint their own and echo + // the name back in the listing. + PlannedName string `gorm:"type:varchar(255)"` + Trigger string `gorm:"type:varchar(16)"` State string `gorm:"type:varchar(16);index"` diff --git a/migrations/versioned/000088_skill_snapshot_planned_name.down.sql b/migrations/versioned/000088_skill_snapshot_planned_name.down.sql new file mode 100644 index 00000000..38d39d1d --- /dev/null +++ b/migrations/versioned/000088_skill_snapshot_planned_name.down.sql @@ -0,0 +1,3 @@ +DO $$ BEGIN RAISE NOTICE '[Migration 000088] Dropping planned_name from tenant_skill_snapshots'; END $$; + +ALTER TABLE tenant_skill_snapshots DROP COLUMN IF EXISTS planned_name; diff --git a/migrations/versioned/000088_skill_snapshot_planned_name.up.sql b/migrations/versioned/000088_skill_snapshot_planned_name.up.sql new file mode 100644 index 00000000..7d1fc843 --- /dev/null +++ b/migrations/versioned/000088_skill_snapshot_planned_name.up.sql @@ -0,0 +1,9 @@ +-- Description: The name a snapshot was going to be committed under, recorded +-- before the provider call. snapshot_id can only be filled in afterwards, so a +-- process that died between the commit and that write left a real provider +-- snapshot the ledger could not name — and therefore could never reclaim. +DO $$ BEGIN RAISE NOTICE '[Migration 000088] Adding planned_name to tenant_skill_snapshots'; END $$; + +ALTER TABLE tenant_skill_snapshots ADD COLUMN IF NOT EXISTS planned_name VARCHAR(255); + +COMMENT ON COLUMN tenant_skill_snapshots.planned_name IS 'Name passed to CreateSnapshot, written before the provider call so an abandoned build stays identifiable';