From 599faafba51c883868ef48774bedcbec9d992a74 Mon Sep 17 00:00:00 2001 From: AdaAibaby Date: Thu, 26 Nov 2026 14:07:21 +0800 Subject: [PATCH 1/2] =?UTF-8?q?fix(api):=20safe=20template-artifact=20dele?= =?UTF-8?q?tion=20=E2=80=94=20reachability=20guard=20+=20reconciliation=20?= =?UTF-8?q?metrics=20(bounded,=20panic-safe)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Delete GCS/S3 build artifacts on template deletion, guarded by a header-reachability closure that protects still-referenced ancestor bases (checkpoint/snapshot), with an online grace window, fail-closed source union, and reconciliation metrics. Rebuilt onto latest main (db layer moved to packages/api/internal/db). --- .../tests/builds/get_live_build_roots_test.go | 188 ++++++++++++ ...exclusive_builds_for_template_deletion.sql | 7 +- .../queries/builds/get_live_build_roots.sql | 45 +++ ...lusive_builds_for_template_deletion.sql.go | 15 +- .../db/queries/get_live_build_roots.sql.go | 85 ++++++ packages/api/internal/handlers/store.go | 9 + .../handlers/template_artifact_guard.go | 270 +++++++++++++++++ .../handlers/template_artifact_guard_test.go | 178 ++++++++++++ .../internal/handlers/template_artifacts.go | 274 ++++++++++++++++++ .../handlers/template_artifacts_test.go | 208 +++++++++++++ .../api/internal/handlers/template_delete.go | 5 + packages/shared/pkg/featureflags/flags.go | 8 + packages/shared/pkg/logger/fields.go | 6 + packages/shared/pkg/telemetry/meters.go | 21 ++ 14 files changed, 1315 insertions(+), 4 deletions(-) create mode 100644 packages/api/internal/db/pkg/tests/builds/get_live_build_roots_test.go create mode 100644 packages/api/internal/db/queries/builds/get_live_build_roots.sql create mode 100644 packages/api/internal/db/queries/get_live_build_roots.sql.go create mode 100644 packages/api/internal/handlers/template_artifact_guard.go create mode 100644 packages/api/internal/handlers/template_artifact_guard_test.go create mode 100644 packages/api/internal/handlers/template_artifacts.go create mode 100644 packages/api/internal/handlers/template_artifacts_test.go diff --git a/packages/api/internal/db/pkg/tests/builds/get_live_build_roots_test.go b/packages/api/internal/db/pkg/tests/builds/get_live_build_roots_test.go new file mode 100644 index 00000000000..ae027080c9c --- /dev/null +++ b/packages/api/internal/db/pkg/tests/builds/get_live_build_roots_test.go @@ -0,0 +1,188 @@ +package builds + +import ( + "testing" + + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/e2b-dev/infra/packages/api/internal/db/pkg/testutils" + "github.com/e2b-dev/infra/packages/api/internal/db/queries" +) + +// liveRootIDs runs the query and returns the build IDs as a set for assertions. +func liveRootIDs(t *testing.T, db *testutils.Database, teamID uuid.UUID, excludeTemplateID string) map[uuid.UUID]struct{} { + t.Helper() + + rows, err := db.SqlcClient.GetLiveBuildRootsForTeamExcludingTemplate(t.Context(), queries.GetLiveBuildRootsForTeamExcludingTemplateParams{ + TeamID: teamID, + TemplateID: excludeTemplateID, + }) + require.NoError(t, err) + + set := make(map[uuid.UUID]struct{}, len(rows)) + for _, id := range rows { + set[id] = struct{}{} + } + + return set +} + +// A build assigned to ANOTHER active template of the team is a live root; the +// doomed template's own exclusive build is excluded (source 1 of the UNION). +func TestGetLiveBuildRoots_OtherActiveTemplateIsRoot(t *testing.T) { + t.Parallel() + db := testutils.SetupDatabase(t) + ctx := t.Context() + + teamID := testutils.CreateTestTeam(t, db) + doomed := testutils.CreateTestTemplate(t, db, teamID) + other := testutils.CreateTestTemplate(t, db, teamID) + + doomedBuild := testutils.CreateTestBuild(t, ctx, db, doomed, "uploaded") + testutils.CreateTestBuildAssignment(t, ctx, db, doomed, doomedBuild, "default") + + otherBuild := testutils.CreateTestBuild(t, ctx, db, other, "uploaded") + testutils.CreateTestBuildAssignment(t, ctx, db, other, otherBuild, "default") + + roots := liveRootIDs(t, db, teamID, doomed) + + assert.Contains(t, roots, otherBuild, "a build of another active template is a live root") + assert.NotContains(t, roots, doomedBuild, "the doomed template's own assigned build is excluded") +} + +// The team's in-progress / pending builds are live roots even with NO +// assignment row yet (source 2 of the UNION). This is the gap the plain +// assignment-join query missed: a concurrent build reusing the doomed +// template's exclusive ancestor would otherwise be invisible to the guard. +func TestGetLiveBuildRoots_InProgressBuildWithoutAssignmentIsRoot(t *testing.T) { + t.Parallel() + db := testutils.SetupDatabase(t) + ctx := t.Context() + + teamID := testutils.CreateTestTeam(t, db) + doomed := testutils.CreateTestTemplate(t, db, teamID) + other := testutils.CreateTestTemplate(t, db, teamID) + + // 'building' -> status_group 'in_progress'; 'pending' -> 'pending'. + // Neither has an env_build_assignments row. + building := testutils.CreateTestBuild(t, ctx, db, other, "building") + pending := testutils.CreateTestBuild(t, ctx, db, other, "pending") + + roots := liveRootIDs(t, db, teamID, doomed) + + assert.Contains(t, roots, building, "an in_progress build with no assignment must still be a live root") + assert.Contains(t, roots, pending, "a pending build with no assignment must still be a live root") +} + +// A soft-deleted other template's build is NOT a live root (active_envs join), +// and a ready build with no assignment is NOT a root (not in-progress). +func TestGetLiveBuildRoots_SoftDeletedAndReadyUnassignedExcluded(t *testing.T) { + t.Parallel() + db := testutils.SetupDatabase(t) + ctx := t.Context() + + teamID := testutils.CreateTestTeam(t, db) + doomed := testutils.CreateTestTemplate(t, db, teamID) + gone := testutils.CreateTestTemplate(t, db, teamID) + + goneBuild := testutils.CreateTestBuild(t, ctx, db, gone, "uploaded") + testutils.CreateTestBuildAssignment(t, ctx, db, gone, goneBuild, "default") + // Soft-delete that template: its assigned build must drop out of live roots. + require.NoError(t, db.SqlcClient.TestsRawSQL(ctx, + `UPDATE public.envs SET deleted_at = NOW() WHERE id = $1`, gone)) + + // A terminal (ready) build with no assignment is not in-progress and has no + // assignment, so neither UNION source includes it. + readyUnassigned := testutils.CreateTestBuild(t, ctx, db, doomed, "uploaded") + + roots := liveRootIDs(t, db, teamID, doomed) + + assert.NotContains(t, roots, goneBuild, "a soft-deleted template's build is not a live root") + assert.NotContains(t, roots, readyUnassigned, "a ready build with no assignment is not a live root") +} + +// The query is team-scoped: another team's in-progress build is never a root. +func TestGetLiveBuildRoots_OtherTeamExcluded(t *testing.T) { + t.Parallel() + db := testutils.SetupDatabase(t) + ctx := t.Context() + + teamID := testutils.CreateTestTeam(t, db) + doomed := testutils.CreateTestTemplate(t, db, teamID) + + otherTeam := testutils.CreateTestTeam(t, db) + otherTeamTpl := testutils.CreateTestTemplate(t, db, otherTeam) + otherTeamBuild := testutils.CreateTestBuild(t, ctx, db, otherTeamTpl, "building") + + roots := liveRootIDs(t, db, teamID, doomed) + + assert.NotContains(t, roots, otherTeamBuild, "another team's build must never be a live root") +} + +// A snapshot (paused sandbox / checkpoint) build is a live root for the team +// even when the template being deleted is its BASE template (source 3 of the +// UNION). A snapshot is a COW diff on top of the base, so its header mapping +// references the base template's builds; it must protect them so deleting the +// base cannot orphan a still-referenced ancestor. This is the checkpoint +// corruption guard. +func TestGetLiveBuildRoots_SnapshotBuildIsRoot(t *testing.T) { + t.Parallel() + db := testutils.SetupDatabase(t) + ctx := t.Context() + + teamID := testutils.CreateTestTeam(t, db) + base := testutils.CreateTestTemplate(t, db, teamID) + + // A snapshot whose base_env_id = base, with its own env + build. The + // snapshot build is the COW layer that references base's builds. + snap := testutils.UpsertTestSnapshot(t, ctx, db, "", "sbx-snap-1", teamID, base) + + // Deleting the base template: the snapshot build must appear as a live root + // so base's ancestor builds are kept. + roots := liveRootIDs(t, db, teamID, base) + assert.Contains(t, roots, snap.BuildID, "a snapshot build on this base must be a live root when the base is deleted") +} + +// Source 3 is deliberately NOT gated on active_envs: a snapshot build still +// protects the base's ancestors even after the snapshot's OWN env is +// soft-deleted but its diff layer still lives in storage. This is exactly the +// window ExistsTemplateSnapshots (which joins active_envs) can let a base +// deletion through — without source 3 the base ancestor would fall out of the +// keep set and be deleted, corrupting the orphaned-but-present snapshot. +func TestGetLiveBuildRoots_SnapshotBuildIsRootEvenAfterSnapshotEnvSoftDeleted(t *testing.T) { + t.Parallel() + db := testutils.SetupDatabase(t) + ctx := t.Context() + + teamID := testutils.CreateTestTeam(t, db) + base := testutils.CreateTestTemplate(t, db, teamID) + snap := testutils.UpsertTestSnapshot(t, ctx, db, "", "sbx-snap-2", teamID, base) + + // Soft-delete the snapshot's OWN env (its diff layer is assumed still in + // storage). An active_envs-gated source would now miss it. + require.NoError(t, db.SqlcClient.TestsRawSQL(ctx, + `UPDATE public.envs SET deleted_at = NOW() WHERE id = $1`, snap.TemplateID)) + + roots := liveRootIDs(t, db, teamID, base) + assert.Contains(t, roots, snap.BuildID, + "a snapshot build must remain a live root for its base even after the snapshot's own env is soft-deleted") +} + +// A snapshot of ANOTHER team never protects this team's base (team-scoped). +func TestGetLiveBuildRoots_SnapshotOtherTeamExcluded(t *testing.T) { + t.Parallel() + db := testutils.SetupDatabase(t) + ctx := t.Context() + + teamID := testutils.CreateTestTeam(t, db) + base := testutils.CreateTestTemplate(t, db, teamID) + + otherTeam := testutils.CreateTestTeam(t, db) + otherBase := testutils.CreateTestTemplate(t, db, otherTeam) + otherSnap := testutils.UpsertTestSnapshot(t, ctx, db, "", "sbx-snap-other", otherTeam, otherBase) + + roots := liveRootIDs(t, db, teamID, base) + assert.NotContains(t, roots, otherSnap.BuildID, "another team's snapshot build must never be a live root here") +} diff --git a/packages/api/internal/db/queries/builds/get_exclusive_builds_for_template_deletion.sql b/packages/api/internal/db/queries/builds/get_exclusive_builds_for_template_deletion.sql index f990fc01ccf..a574d1736d6 100644 --- a/packages/api/internal/db/queries/builds/get_exclusive_builds_for_template_deletion.sql +++ b/packages/api/internal/db/queries/builds/get_exclusive_builds_for_template_deletion.sql @@ -2,12 +2,15 @@ -- Returns builds that are ONLY assigned to this template (safe to delete). -- Builds shared with other templates are excluded. -- DISTINCT needed because builds may have multiple tag assignments to the same template. -SELECT DISTINCT eb.id as build_id, eb.cluster_node_id +SELECT DISTINCT eb.id as build_id, eb.cluster_node_id, e.cluster_id, eb.created_at FROM "public"."env_build_assignments" eba JOIN "public"."env_builds" eb ON eb.id = eba.build_id +-- Join raw envs (not the active_envs view) so the query still resolves the +-- cluster after softDeleteTemplate has stamped the template's deleted_at. +JOIN "public"."envs" e ON e.id = eba.env_id WHERE eba.env_id = @template_id AND NOT EXISTS ( -- Exclude builds that have assignments to OTHER templates SELECT 1 FROM "public"."env_build_assignments" other_eba WHERE other_eba.build_id = eb.id AND other_eba.env_id != @template_id -); \ No newline at end of file +); diff --git a/packages/api/internal/db/queries/builds/get_live_build_roots.sql b/packages/api/internal/db/queries/builds/get_live_build_roots.sql new file mode 100644 index 00000000000..b623f921cb5 --- /dev/null +++ b/packages/api/internal/db/queries/builds/get_live_build_roots.sql @@ -0,0 +1,45 @@ +-- name: GetLiveBuildRootsForTeamExcludingTemplate :many +-- Returns the "live roots" of a team whose header mappings may still reference — +-- and therefore protect — a build that the deletion query considers exclusive to +-- the template being deleted. Cache sharing is team-scoped, so a cross-template +-- ancestor can only come from the same team; this bounds the set. +-- +-- The set is the UNION of three sources, because a build can protect an ancestor +-- without having an env_build_assignments row to an active template yet: +-- (1) builds assigned to a still-active (not soft-deleted) OTHER template, and +-- (2) the team's in-progress/pending builds, which are materialized (or being +-- materialized) on a node and reuse ancestor layers via cache hits, but +-- may not have an assignment row until they finish, and +-- (3) the team's snapshot builds (paused sandboxes / checkpoints). A snapshot +-- is a COW diff layer on top of a base template, so its header mapping +-- references the base template's builds; it must protect them even when +-- the snapshot's OWN env has been soft-deleted. Source (1) would miss this +-- because it joins active_envs on the assignment's env; (3) joins the +-- snapshots table directly and is deliberately NOT gated on active_envs, +-- so a base-template deletion cannot orphan a still-referenced ancestor of +-- a snapshot whose env row is already soft-deleted but whose diff layer +-- still lives in storage. This is the fix for the checkpoint corruption +-- vector: ExistsTemplateSnapshots (which joins active_envs) can let the +-- base delete through once the snapshot env is soft-deleted, and without +-- (3) the base ancestor would then fall out of the keep set. +-- +-- Residual (handled by the offline sweeper, not here): builds whose existence is +-- only known to the orchestrator/Redis before any DB row lands. +SELECT DISTINCT eb.id AS build_id +FROM "public"."env_build_assignments" eba +JOIN "public"."env_builds" eb ON eb.id = eba.build_id +JOIN "public"."active_envs" e ON e.id = eba.env_id +WHERE e.team_id = @team_id + AND eba.env_id != @template_id +UNION +SELECT DISTINCT eb.id AS build_id +FROM "public"."env_builds" eb +WHERE eb.team_id = @team_id + AND eb.status_group IN ('pending', 'in_progress') +UNION +SELECT DISTINCT eb.id AS build_id +FROM "public"."snapshots" s +JOIN "public"."env_build_assignments" eba ON eba.env_id = s.env_id +JOIN "public"."env_builds" eb ON eb.id = eba.build_id +WHERE s.team_id = @team_id + AND s.env_id != @template_id; diff --git a/packages/api/internal/db/queries/get_exclusive_builds_for_template_deletion.sql.go b/packages/api/internal/db/queries/get_exclusive_builds_for_template_deletion.sql.go index 600aba018a5..f9c54bb2bbb 100644 --- a/packages/api/internal/db/queries/get_exclusive_builds_for_template_deletion.sql.go +++ b/packages/api/internal/db/queries/get_exclusive_builds_for_template_deletion.sql.go @@ -7,14 +7,16 @@ package queries import ( "context" + "time" "github.com/google/uuid" ) const getExclusiveBuildsForTemplateDeletion = `-- name: GetExclusiveBuildsForTemplateDeletion :many -SELECT DISTINCT eb.id as build_id, eb.cluster_node_id +SELECT DISTINCT eb.id as build_id, eb.cluster_node_id, e.cluster_id, eb.created_at FROM "public"."env_build_assignments" eba JOIN "public"."env_builds" eb ON eb.id = eba.build_id +JOIN "public"."envs" e ON e.id = eba.env_id WHERE eba.env_id = $1 AND NOT EXISTS ( -- Exclude builds that have assignments to OTHER templates @@ -26,11 +28,15 @@ WHERE eba.env_id = $1 type GetExclusiveBuildsForTemplateDeletionRow struct { BuildID uuid.UUID ClusterNodeID *string + ClusterID *uuid.UUID + CreatedAt time.Time } // Returns builds that are ONLY assigned to this template (safe to delete). // Builds shared with other templates are excluded. // DISTINCT needed because builds may have multiple tag assignments to the same template. +// Join raw envs (not the active_envs view) so the query still resolves the +// cluster after softDeleteTemplate has stamped the template's deleted_at. func (q *Queries) GetExclusiveBuildsForTemplateDeletion(ctx context.Context, templateID string) ([]GetExclusiveBuildsForTemplateDeletionRow, error) { rows, err := q.db.Query(ctx, getExclusiveBuildsForTemplateDeletion, templateID) if err != nil { @@ -40,7 +46,12 @@ func (q *Queries) GetExclusiveBuildsForTemplateDeletion(ctx context.Context, tem var items []GetExclusiveBuildsForTemplateDeletionRow for rows.Next() { var i GetExclusiveBuildsForTemplateDeletionRow - if err := rows.Scan(&i.BuildID, &i.ClusterNodeID); err != nil { + if err := rows.Scan( + &i.BuildID, + &i.ClusterNodeID, + &i.ClusterID, + &i.CreatedAt, + ); err != nil { return nil, err } items = append(items, i) diff --git a/packages/api/internal/db/queries/get_live_build_roots.sql.go b/packages/api/internal/db/queries/get_live_build_roots.sql.go new file mode 100644 index 00000000000..a6940e8584f --- /dev/null +++ b/packages/api/internal/db/queries/get_live_build_roots.sql.go @@ -0,0 +1,85 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: get_live_build_roots.sql + +package queries + +import ( + "context" + + "github.com/google/uuid" +) + +const getLiveBuildRootsForTeamExcludingTemplate = `-- name: GetLiveBuildRootsForTeamExcludingTemplate :many +SELECT DISTINCT eb.id AS build_id +FROM "public"."env_build_assignments" eba +JOIN "public"."env_builds" eb ON eb.id = eba.build_id +JOIN "public"."active_envs" e ON e.id = eba.env_id +WHERE e.team_id = $1 + AND eba.env_id != $2 +UNION +SELECT DISTINCT eb.id AS build_id +FROM "public"."env_builds" eb +WHERE eb.team_id = $1 + AND eb.status_group IN ('pending', 'in_progress') +UNION +SELECT DISTINCT eb.id AS build_id +FROM "public"."snapshots" s +JOIN "public"."env_build_assignments" eba ON eba.env_id = s.env_id +JOIN "public"."env_builds" eb ON eb.id = eba.build_id +WHERE s.team_id = $1 + AND s.env_id != $2 +` + +type GetLiveBuildRootsForTeamExcludingTemplateParams struct { + TeamID uuid.UUID + TemplateID string +} + +// Returns the "live roots" of a team whose header mappings may still reference — +// and therefore protect — a build that the deletion query considers exclusive to +// the template being deleted. Cache sharing is team-scoped, so a cross-template +// ancestor can only come from the same team; this bounds the set. +// +// The set is the UNION of three sources, because a build can protect an ancestor +// without having an env_build_assignments row to an active template yet: +// +// (1) builds assigned to a still-active (not soft-deleted) OTHER template, and +// (2) the team's in-progress/pending builds, which are materialized (or being +// materialized) on a node and reuse ancestor layers via cache hits, but +// may not have an assignment row until they finish, and +// (3) the team's snapshot builds (paused sandboxes / checkpoints). A snapshot +// is a COW diff layer on top of a base template, so its header mapping +// references the base template's builds; it must protect them even when +// the snapshot's OWN env has been soft-deleted. Source (1) would miss this +// because it joins active_envs on the assignment's env; (3) joins the +// snapshots table directly and is deliberately NOT gated on active_envs, +// so a base-template deletion cannot orphan a still-referenced ancestor of +// a snapshot whose env row is already soft-deleted but whose diff layer +// still lives in storage. This is the fix for the checkpoint corruption +// vector: ExistsTemplateSnapshots (which joins active_envs) can let the +// base delete through once the snapshot env is soft-deleted, and without +// (3) the base ancestor would then fall out of the keep set. +// +// Residual (handled by the offline sweeper, not here): builds whose existence is +// only known to the orchestrator/Redis before any DB row lands. +func (q *Queries) GetLiveBuildRootsForTeamExcludingTemplate(ctx context.Context, arg GetLiveBuildRootsForTeamExcludingTemplateParams) ([]uuid.UUID, error) { + rows, err := q.db.Query(ctx, getLiveBuildRootsForTeamExcludingTemplate, arg.TeamID, arg.TemplateID) + if err != nil { + return nil, err + } + defer rows.Close() + var items []uuid.UUID + for rows.Next() { + var build_id uuid.UUID + if err := rows.Scan(&build_id); err != nil { + return nil, err + } + items = append(items, build_id) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} diff --git a/packages/api/internal/handlers/store.go b/packages/api/internal/handlers/store.go index 4c0fd0e524e..99459b73980 100644 --- a/packages/api/internal/handlers/store.go +++ b/packages/api/internal/handlers/store.go @@ -231,6 +231,14 @@ type APIStore struct { teamSandboxCounter teamRunningSandboxCounter sandboxLifecycles sandboxLifecycleReader templateManager *template_manager.TemplateManager + // buildAncestors resolves a build's header-mapping ancestor closure for + // the template-deletion reachability guard. Nil when template storage is + // not configured for the API, in which case artifact cleanup fails closed. + buildAncestors buildAncestorReader + // liveRootSources enumerates the build-ID roots the reachability guard + // expands to protect still-referenced ancestors. Nil in production (falls + // back to the DB source via liveRootSourcesOrDefault); tests inject stubs. + liveRootSources []liveRootSource sqlcDB *sqlcdb.Client sqlcReadDB *sqlcdb.Client authDB *authdb.Client @@ -506,6 +514,7 @@ func NewAPIStore(ctx context.Context, tel *telemetry.Client, redisClient redis.U teamSandboxCounter: sandboxcountscache.NewCountsCache(orch, redisClient), sandboxLifecycles: clickhouseStore, templateManager: templateManager, + buildAncestors: newTemplateBuildAncestorReader(ctx), sqlcDB: sqlcDB, sqlcReadDB: sqlcReadDB, authDB: authDB, diff --git a/packages/api/internal/handlers/template_artifact_guard.go b/packages/api/internal/handlers/template_artifact_guard.go new file mode 100644 index 00000000000..29fd3f853f5 --- /dev/null +++ b/packages/api/internal/handlers/template_artifact_guard.go @@ -0,0 +1,270 @@ +package handlers + +import ( + "context" + "errors" + "fmt" + "os" + "strings" + + "github.com/google/uuid" + + sqlcdb "github.com/e2b-dev/infra/packages/api/internal/db/client" + "github.com/e2b-dev/infra/packages/api/internal/db/queries" + "github.com/e2b-dev/infra/packages/shared/pkg/logger" + "github.com/e2b-dev/infra/packages/shared/pkg/storage" + "github.com/e2b-dev/infra/packages/shared/pkg/storage/header" +) + +// Fail-closed reasons. These are LOW-cardinality and safe to use as a metric +// attribute so the fail_closed counter is alertable by cause. team_id and +// build_id are deliberately NOT metric attributes (high cardinality); they stay +// on the log line / trace instead. +var ( + // errReaderUnconfigured: no template-storage access, so the header closure + // cannot be read at all. The deployment simply does not reclaim space. + errReaderUnconfigured = errors.New("build ancestor reader not configured") + // errLiveRootsQuery: the set of builds that could protect a candidate could + // not be enumerated from the DB. + errLiveRootsQuery = errors.New("live build roots query failed") + // errHeaderUnreadable: a live root's header could not be read/parsed, so its + // ancestor closure is unknown. + errHeaderUnreadable = errors.New("live root header unreadable") +) + +// failClosedReason maps a fail-closed error to a low-cardinality reason label. +func failClosedReason(err error) string { + switch { + case errors.Is(err, errReaderUnconfigured): + return "reader_unconfigured" + case errors.Is(err, errLiveRootsQuery): + return "live_roots_query" + case errors.Is(err, errHeaderUnreadable): + return "header_unreadable" + default: + return "unknown" + } +} + +// buildAncestorReader resolves the set of ancestor build IDs that a given build +// actually references through its header block mappings (memfile + rootfs). A +// template build stores only the bytes it changed relative to its ancestors; +// the full image is reconstructed by following the header's BuildMap into +// parent, grandparent, ... builds. Those ancestor builds are NOT recorded in +// the database (intermediate cache layers never get an env_build_assignments +// row), so the only source of truth for "which builds does this one depend on" +// is the header mapping itself. +type buildAncestorReader interface { + // AncestorBuilds returns every build ID referenced by buildID's memfile and + // rootfs header mappings, including buildID itself. An error means the + // dependency set could not be established and the caller must fail closed. + AncestorBuilds(ctx context.Context, buildID uuid.UUID) ([]uuid.UUID, error) +} + +// reachabilityKeepSet computes the set of builds that must NOT be deleted +// because a live root of the team still reaches them through its header +// closure. It fails closed (returns an error) when the reader is unavailable, +// the live-root set cannot be queried, or any live root's header cannot be +// read, so the caller deletes nothing rather than risk orphaning a shared +// ancestor. The returned error is classified by failClosedReason. +func (a *APIStore) reachabilityKeepSet(ctx context.Context, teamID uuid.UUID, templateID string, candidates []queries.GetExclusiveBuildsForTemplateDeletionRow) (map[uuid.UUID]struct{}, error) { + if len(candidates) == 0 { + return map[uuid.UUID]struct{}{}, nil + } + + if a.buildAncestors == nil { + return nil, errReaderUnconfigured + } + + liveRoots, err := collectLiveRoots(ctx, a.liveRootSourcesOrDefault(), teamID, templateID) + if err != nil { + return nil, err + } + + return reachableKeepSet(ctx, a.buildAncestors, liveRoots) +} + +// liveRootSource yields a set of build IDs that may protect a deletion candidate +// by referencing it through their header closure. The reachability guard unions +// every source's roots and expands each root's ancestor closure. A source that +// returns an error makes the whole guard fail closed (the caller deletes +// nothing), so a source must return an error — never a silently empty slice — +// when it cannot authoritatively enumerate its roots. +type liveRootSource interface { + // liveRoots returns the build IDs this source contributes as live roots for + // the team, excluding the template being deleted. An error means the set is + // unknown and the guard must fail closed. + liveRoots(ctx context.Context, teamID uuid.UUID, templateID string) ([]uuid.UUID, error) + // name is a short, low-cardinality label for logs/metrics. + name() string +} + +// dbLiveRootSource is the production live-root source. In one query it unions +// (1) other active templates' assigned builds, (2) the team's in-progress/ +// pending builds, and (3) the team's snapshot builds (paused sandboxes / +// checkpoints) regardless of whether the snapshot's own env is still active — +// see get_live_build_roots.sql. Source (3) is what keeps a base template's +// builds protected while a checkpoint-derived snapshot still references them +// through its COW header mapping, even after the snapshot's env is soft-deleted. +type dbLiveRootSource struct { + db *sqlcdb.Client +} + +func (s dbLiveRootSource) name() string { return "db" } + +func (s dbLiveRootSource) liveRoots(ctx context.Context, teamID uuid.UUID, templateID string) ([]uuid.UUID, error) { + return s.db.GetLiveBuildRootsForTeamExcludingTemplate(ctx, queries.GetLiveBuildRootsForTeamExcludingTemplateParams{ + TeamID: teamID, + TemplateID: templateID, + }) +} + +// collectLiveRoots unions the roots of every configured source. It fails closed +// on the FIRST source error: a partial root set is more dangerous than none, +// because a missing root means its ancestor closure is absent from the keep set +// and a still-referenced build could then be deleted. The error is wrapped as +// errLiveRootsQuery so the caller classifies it as a fail-closed reason. +func collectLiveRoots(ctx context.Context, sources []liveRootSource, teamID uuid.UUID, templateID string) ([]uuid.UUID, error) { + seen := make(map[uuid.UUID]struct{}) + var roots []uuid.UUID + for _, src := range sources { + ids, err := src.liveRoots(ctx, teamID, templateID) + if err != nil { + return nil, fmt.Errorf("%w: source %s: %w", errLiveRootsQuery, src.name(), err) + } + for _, id := range ids { + if _, ok := seen[id]; ok { + continue + } + seen[id] = struct{}{} + roots = append(roots, id) + } + } + + return roots, nil +} + +// liveRootSourcesOrDefault returns the injected sources, or the default DB +// source when none were set (production). Tests inject stubs. +func (a *APIStore) liveRootSourcesOrDefault() []liveRootSource { + if len(a.liveRootSources) > 0 { + return a.liveRootSources + } + + return []liveRootSource{dbLiveRootSource{db: a.sqlcDB}} +} + +// reachableKeepSet unions the ancestor closure of every live root build into a +// single "keep" set. Any build in this set is still referenced by a live build +// of the team and must never be deleted. A read failure for any root is +// returned as an error (wrapped as errHeaderUnreadable) so the caller fails +// closed (deletes nothing) rather than risk deleting a build whose reachability +// could not be proven. +func reachableKeepSet(ctx context.Context, reader buildAncestorReader, liveRoots []uuid.UUID) (map[uuid.UUID]struct{}, error) { + keep := make(map[uuid.UUID]struct{}) + + for _, root := range liveRoots { + ancestors, err := reader.AncestorBuilds(ctx, root) + if err != nil { + return nil, fmt.Errorf("%w: resolve ancestors of live root %s: %w", errHeaderUnreadable, root, err) + } + + for _, anc := range ancestors { + keep[anc] = struct{}{} + } + } + + return keep, nil +} + +// partitionDeletableBuilds splits candidate builds (those the DB considers +// exclusive to the doomed template) into the ones that are safe to physically +// delete and the ones that must be protected because a live root's header +// mapping still references them. A candidate is deletable only if it is NOT in +// the keep set. This is the guard against the silent, permanent "Input/output +// error" corruption that results from deleting a build whose blocks another +// live build still reconstructs from. +func partitionDeletableBuilds(candidates []uuid.UUID, keep map[uuid.UUID]struct{}) (deletable, protected []uuid.UUID) { + for _, b := range candidates { + if _, kept := keep[b]; kept { + protected = append(protected, b) + + continue + } + + deletable = append(deletable, b) + } + + return deletable, protected +} + +// storageBuildAncestorReader is the production buildAncestorReader. It reads the +// two header sidecar objects of a build from template storage and unions the +// build IDs their block mappings reference. +type storageBuildAncestorReader struct { + storage storage.StorageProvider +} + +func newStorageBuildAncestorReader(s storage.StorageProvider) *storageBuildAncestorReader { + return &storageBuildAncestorReader{storage: s} +} + +func (r *storageBuildAncestorReader) AncestorBuilds(ctx context.Context, buildID uuid.UUID) ([]uuid.UUID, error) { + paths := storage.Paths{BuildID: buildID.String()} + + seen := map[uuid.UUID]struct{}{buildID: {}} + + // Both the memfile and rootfs headers carry their own mapping; a build can + // share a parent on one and not the other, so both must be read. A missing + // or unparseable header means the dependency set is unknown -> error -> + // caller fails closed. + for _, hdrPath := range []string{paths.MemfileHeader(), paths.RootfsHeader()} { + h, _, err := header.LoadHeader(ctx, r.storage, hdrPath) + if err != nil { + return nil, fmt.Errorf("load header %s: %w", hdrPath, err) + } + + for _, b := range h.Mapping.Builds() { + seen[b] = struct{}{} + } + } + + out := make([]uuid.UUID, 0, len(seen)) + for b := range seen { + out = append(out, b) + } + + return out, nil +} + +// newTemplateBuildAncestorReader builds the production ancestor reader from the +// template storage destination in the environment (TEMPLATE_STORAGE_URL). It is +// best-effort: if the destination is unset or the provider cannot be built, it +// returns nil, and the deletion guard then fails closed (deletes nothing), +// which is no worse than leaving artifacts in place. Credentials are never +// echoed; only a build error (which may embed the bucket name, not secrets) is +// logged. +func newTemplateBuildAncestorReader(ctx context.Context) buildAncestorReader { + raw := strings.TrimSpace(os.Getenv("TEMPLATE_STORAGE_URL")) + if raw == "" { + logger.L().Warn(ctx, "TEMPLATE_STORAGE_URL unset; template artifact cleanup will fail closed") + + return nil + } + + spec, err := storage.ParseStorageURL(raw) + if err != nil { + logger.L().Warn(ctx, "could not parse TEMPLATE_STORAGE_URL; template artifact cleanup will fail closed", logger.WithError(err)) + + return nil + } + + provider, err := storage.NewProvider(ctx, spec) + if err != nil { + logger.L().Warn(ctx, "could not build template storage provider; template artifact cleanup will fail closed", logger.WithError(err)) + + return nil + } + + return newStorageBuildAncestorReader(provider) +} diff --git a/packages/api/internal/handlers/template_artifact_guard_test.go b/packages/api/internal/handlers/template_artifact_guard_test.go new file mode 100644 index 00000000000..67c3643cd4b --- /dev/null +++ b/packages/api/internal/handlers/template_artifact_guard_test.go @@ -0,0 +1,178 @@ +package handlers + +import ( + "context" + "errors" + "fmt" + "testing" + + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// stubAncestorReader is a test buildAncestorReader. AncestorBuilds returns the +// build itself plus any ancestors configured for it; a non-nil err makes every +// lookup fail (to exercise the fail-closed path). +type stubAncestorReader struct { + ancestors map[uuid.UUID][]uuid.UUID + err error +} + +func (s stubAncestorReader) AncestorBuilds(_ context.Context, buildID uuid.UUID) ([]uuid.UUID, error) { + if s.err != nil { + return nil, s.err + } + + out := []uuid.UUID{buildID} + out = append(out, s.ancestors[buildID]...) + + return out, nil +} + +// Reproduces the corruption scenario: a build that is DB-exclusive to the doomed +// template is nonetheless a header-mapping ancestor of another live build. +// Deleting it would orphan that ancestor and later surface as an unrecoverable +// I/O error. The guard must keep it (not delete it). +func TestReachabilityGuard_ProtectsReferencedAncestor(t *testing.T) { + t.Parallel() + + sharedAncestor := uuid.New() // DB-exclusive to the doomed template... + liveRoot := uuid.New() // ...but a live build references it. + + reader := stubAncestorReader{ + ancestors: map[uuid.UUID][]uuid.UUID{ + liveRoot: {sharedAncestor}, + }, + } + + keep, err := reachableKeepSet(context.Background(), reader, []uuid.UUID{liveRoot}) + require.NoError(t, err) + + deletable, protected := partitionDeletableBuilds([]uuid.UUID{sharedAncestor}, keep) + + assert.Empty(t, deletable, "a build referenced by a live root's header closure must not be deletable") + assert.Equal(t, []uuid.UUID{sharedAncestor}, protected) +} + +// A build that no live root references is deletable. +func TestReachabilityGuard_OrphanIsDeletable(t *testing.T) { + t.Parallel() + + orphan := uuid.New() + liveRoot := uuid.New() + unrelatedAncestor := uuid.New() + + reader := stubAncestorReader{ + ancestors: map[uuid.UUID][]uuid.UUID{ + liveRoot: {unrelatedAncestor}, + }, + } + + keep, err := reachableKeepSet(context.Background(), reader, []uuid.UUID{liveRoot}) + require.NoError(t, err) + + deletable, protected := partitionDeletableBuilds([]uuid.UUID{orphan}, keep) + + assert.Equal(t, []uuid.UUID{orphan}, deletable) + assert.Empty(t, protected, "an unreferenced build should not be protected") +} + +// If any live root's header cannot be read, keep-set resolution errors so the +// caller deletes nothing rather than risk deleting a build whose reachability is +// unknown. The error must classify as header_unreadable. +func TestReachabilityGuard_FailsClosedOnReadError(t *testing.T) { + t.Parallel() + + reader := stubAncestorReader{err: errors.New("header missing/corrupt")} + + _, err := reachableKeepSet(context.Background(), reader, []uuid.UUID{uuid.New()}) + + require.Error(t, err, "an unreadable live-root header must fail closed, not be treated as no-dependency") + assert.ErrorIs(t, err, errHeaderUnreadable) + assert.Equal(t, "header_unreadable", failClosedReason(err)) +} + +// The keep set is the union of every live root's ancestor closure. +func TestReachabilityGuard_UnionsMultipleRoots(t *testing.T) { + t.Parallel() + + a1, a2 := uuid.New(), uuid.New() + root1, root2 := uuid.New(), uuid.New() + + reader := stubAncestorReader{ + ancestors: map[uuid.UUID][]uuid.UUID{ + root1: {a1}, + root2: {a2}, + }, + } + + keep, err := reachableKeepSet(context.Background(), reader, []uuid.UUID{root1, root2}) + require.NoError(t, err) + + deletable, protected := partitionDeletableBuilds([]uuid.UUID{a1, a2, uuid.New()}, keep) + + assert.Len(t, protected, 2) + assert.Len(t, deletable, 1) + assert.Contains(t, keep, root1) + assert.Contains(t, keep, root2) + assert.Contains(t, keep, a1) + assert.Contains(t, keep, a2) +} + +// failClosedReason maps each sentinel to its low-cardinality label, and wrapped +// errors still classify correctly (so the fail_closed metric attribute is stable). +func TestFailClosedReason_Classification(t *testing.T) { + t.Parallel() + + assert.Equal(t, "reader_unconfigured", failClosedReason(errReaderUnconfigured)) + assert.Equal(t, "live_roots_query", failClosedReason(fmt.Errorf("%w: boom", errLiveRootsQuery))) + assert.Equal(t, "header_unreadable", failClosedReason(fmt.Errorf("%w: boom", errHeaderUnreadable))) + assert.Equal(t, "unknown", failClosedReason(errors.New("something else"))) +} + +// stubLiveRootSource is a test liveRootSource: returns configured roots, or err. +type stubLiveRootSource struct { + label string + roots []uuid.UUID + err error +} + +func (s stubLiveRootSource) name() string { return s.label } + +func (s stubLiveRootSource) liveRoots(_ context.Context, _ uuid.UUID, _ string) ([]uuid.UUID, error) { + return s.roots, s.err +} + +// collectLiveRoots unions roots across all sources and dedups. +func TestCollectLiveRoots_UnionsAndDedups(t *testing.T) { + t.Parallel() + + a, b, c := uuid.New(), uuid.New(), uuid.New() + sources := []liveRootSource{ + stubLiveRootSource{label: "db", roots: []uuid.UUID{a, b}}, + stubLiveRootSource{label: "snapshots", roots: []uuid.UUID{b, c}}, // b overlaps + } + + roots, err := collectLiveRoots(context.Background(), sources, uuid.New(), "tpl") + require.NoError(t, err) + assert.ElementsMatch(t, []uuid.UUID{a, b, c}, roots, "roots are the deduped union of all sources") +} + +// A single source error fails the whole collection closed (classified as +// live_roots_query), so the guard deletes nothing rather than expand an +// incomplete root set and risk deleting a still-referenced build. +func TestCollectLiveRoots_FailsClosedOnAnySourceError(t *testing.T) { + t.Parallel() + + good := uuid.New() + sources := []liveRootSource{ + stubLiveRootSource{label: "db", roots: []uuid.UUID{good}}, + stubLiveRootSource{label: "snapshots", err: errors.New("query boom")}, + } + + _, err := collectLiveRoots(context.Background(), sources, uuid.New(), "tpl") + require.Error(t, err, "an error from any source must fail closed") + assert.ErrorIs(t, err, errLiveRootsQuery) + assert.Equal(t, "live_roots_query", failClosedReason(err)) +} diff --git a/packages/api/internal/handlers/template_artifacts.go b/packages/api/internal/handlers/template_artifacts.go new file mode 100644 index 00000000000..b95198f5829 --- /dev/null +++ b/packages/api/internal/handlers/template_artifacts.go @@ -0,0 +1,274 @@ +package handlers + +import ( + "context" + "time" + + "github.com/google/uuid" + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/metric" + "golang.org/x/sync/errgroup" + + "github.com/e2b-dev/infra/packages/api/internal/db/queries" + "github.com/e2b-dev/infra/packages/shared/pkg/clusters" + "github.com/e2b-dev/infra/packages/shared/pkg/featureflags" + "github.com/e2b-dev/infra/packages/shared/pkg/logger" + "github.com/e2b-dev/infra/packages/shared/pkg/telemetry" +) + +const ( + // artifactCleanupTimeout bounds the whole background cleanup so a stuck + // DeleteBuild RPC cannot leak a goroutine forever. It is a deadline, not a + // cancellation of the request: the HTTP response has already been sent. + artifactCleanupTimeout = 2 * time.Minute + // artifactCleanupConcurrency caps concurrent DeleteBuild RPCs so deleting a + // template with many builds (or a burst of deletions) cannot fan out + // unboundedly against the cluster. + artifactCleanupConcurrency = 8 +) + +// deleteBuildFn deletes one build's storage artifacts on its cluster node. It +// matches TemplateManager.DeleteBuild; injectable so tests can observe calls. +type deleteBuildFn func(ctx context.Context, buildID uuid.UUID, templateID string, clusterID uuid.UUID, nodeID string) error + +// artifactCleanupCounters hold the reconciliation metrics. Any may be nil +// (metrics unavailable), in which case counting is skipped but cleanup still +// runs. The invariant that makes orphaned storage observable is: +// +// candidates == deleted + failed + skippedNilNode + guardKept + skippedTooNew (success path) +// candidates with failClosed > 0 (nothing deleted) +// +// so "how many artifacts did we fail to reclaim" is derivable, not guessed. +type artifactCleanupCounters struct { + candidates metric.Int64Counter // builds the DB considered exclusive (the denominator) + deleted metric.Int64Counter // artifacts actually deleted + failed metric.Int64Counter // delete attempted, RPC failed (potential orphan) + skippedNilNode metric.Int64Counter // build never materialized on a node; nothing to delete + guardKept metric.Int64Counter // reachability guard protected a still-referenced ancestor + skippedTooNew metric.Int64Counter // materialized but younger than the grace window; deferred to the offline sweeper + failClosed metric.Int64Counter // guard could not prove reachability; whole cleanup aborted +} + +// startTemplateArtifactCleanup runs deleteTemplateArtifacts in a detached, +// panic-safe, deadline-bounded goroutine. It is called AFTER the template's DB +// row is soft-deleted and the HTTP response is sent: storage-cleanup failures +// must never affect the already-committed deletion, so they are only logged and +// counted (not surfaced to the caller). ctx should be the request ctx; it is +// detached from cancellation here so the cleanup survives the response. +func (a *APIStore) startTemplateArtifactCleanup(ctx context.Context, teamID uuid.UUID, templateID string) { + // Detach from the request lifecycle but keep its trace/values, then bound it. + base := context.WithoutCancel(ctx) + + go func() { + defer func() { + if r := recover(); r != nil { + logger.L().Error(base, "panic in template artifact cleanup", + logger.WithTemplateID(templateID), + logger.WithTeamID(teamID.String()), + ) + } + }() + + cleanupCtx, cancel := context.WithTimeout(base, artifactCleanupTimeout) + defer cancel() + + a.deleteTemplateArtifacts(cleanupCtx, teamID, templateID, a.templateManager.DeleteBuild) + }() +} + +// deleteTemplateArtifacts queries the builds exclusively owned by templateID +// (the SQL guard excludes builds still shared with other templates), runs the +// reachability guard to drop any build still reachable from a live root's +// header closure, then hands the survivors to processExclusiveBuilds. deleteFn +// is injected for testing. +// +// Being DB-exclusive is NOT sufficient for deletion: intermediate cache layers +// are never written to the DB, so a build that is DB-exclusive to this template +// can still be a header-mapping ancestor of another live build. Deleting its +// storage prefix would orphan that ancestor and surface later as a silent, +// unrecoverable "Input/output error". The reachability guard is what prevents +// that; if reachability cannot be proven the whole cleanup fails closed. +func (a *APIStore) deleteTemplateArtifacts(ctx context.Context, teamID uuid.UUID, templateID string, deleteFn deleteBuildFn) { + counters := a.artifactCleanupCounters(ctx, templateID) + + builds, err := a.sqlcDB.GetExclusiveBuildsForTemplateDeletion(ctx, templateID) + if err != nil { + logger.L().Error(ctx, "failed to query exclusive builds for artifact cleanup", + logger.WithTemplateID(templateID), + logger.WithTeamID(teamID.String()), + logger.WithError(err), + ) + + return + } + + addCount(ctx, counters.candidates, int64(len(builds))) + + keep, err := a.reachabilityKeepSet(ctx, teamID, templateID, builds) + if err != nil { + reason := failClosedReason(err) + logger.L().Warn(ctx, "skipping template artifact cleanup: could not prove build reachability (failing closed, nothing deleted)", + logger.WithTemplateID(templateID), + logger.WithTeamID(teamID.String()), + logger.WithError(err), + ) + addCountAttrs(ctx, counters.failClosed, int64(len(builds)), attribute.String("reason", reason)) + + return + } + + // The online grace window defers very-new candidates to the offline sweeper + // (narrows the live-root-query -> DeleteBuild TOCTOU). Flag in seconds; + // <=0 disables the window. Fallback 24h. + minAge := time.Duration(a.featureFlags.IntFlag(ctx, featureflags.TemplateArtifactMinAgeSeconds)) * time.Second + + processExclusiveBuilds(ctx, templateID, builds, keep, deleteFn, counters, time.Now(), minAge) +} + +// artifactCleanupCounters resolves the reconciliation counters, logging (not +// failing) if the meter cannot provide any of them. +func (a *APIStore) artifactCleanupCounters(ctx context.Context, templateID string) artifactCleanupCounters { + meter := a.Telemetry.MeterProvider.Meter("github.com/e2b-dev/infra/packages/api/internal/handlers") + + candidates, e1 := telemetry.GetCounter(meter, telemetry.ApiTemplateArtifactsCandidates) + deleted, e2 := telemetry.GetCounter(meter, telemetry.ApiTemplateArtifactsDeleted) + failed, e3 := telemetry.GetCounter(meter, telemetry.ApiTemplateArtifactsDeleteFailed) + skipped, e4 := telemetry.GetCounter(meter, telemetry.ApiTemplateArtifactsSkippedNilNode) + kept, e5 := telemetry.GetCounter(meter, telemetry.ApiTemplateArtifactsGuardKept) + failClosed, e6 := telemetry.GetCounter(meter, telemetry.ApiTemplateArtifactsFailClosed) + tooNew, e7 := telemetry.GetCounter(meter, telemetry.ApiTemplateArtifactsSkippedTooNew) + + if err := firstErr(e1, e2, e3, e4, e5, e6, e7); err != nil { + logger.L().Error(ctx, "failed to create template artifact cleanup counters", + logger.WithTemplateID(templateID), + logger.WithError(err), + ) + } + + return artifactCleanupCounters{ + candidates: candidates, + deleted: deleted, + failed: failed, + skippedNilNode: skipped, + guardKept: kept, + skippedTooNew: tooNew, + failClosed: failClosed, + } +} + +// processExclusiveBuilds deletes each candidate build's artifacts best-effort. +// A candidate lands in EXACTLY ONE bucket so the counts reconcile: +// - protected by the reachability guard (still reachable from a live root) -> guardKept, skip +// - not yet materialized on a node (nil ClusterNodeID) -> skippedNilNode, skip +// - materialized but younger than minAge (grace window) -> skippedTooNew, skip +// - deleted -> deleted +// - delete attempted but failed -> failed (potential orphan) +// +// The bucket order encodes precedence: guardKept (correctness) first, then +// nil-node (nothing to delete regardless of age), then the grace window, then +// delete. Each delete is attempted independently with bounded concurrency; a +// failure on one never aborts the others. It takes no DB dependency so it is +// unit-testable directly: keep, now and minAge are passed in. A minAge of 0 +// disables the grace window. +func processExclusiveBuilds( + ctx context.Context, + templateID string, + builds []queries.GetExclusiveBuildsForTemplateDeletionRow, + keep map[uuid.UUID]struct{}, + deleteFn deleteBuildFn, + counters artifactCleanupCounters, + now time.Time, + minAge time.Duration, +) { + g, gctx := errgroup.WithContext(ctx) + g.SetLimit(artifactCleanupConcurrency) + + for _, b := range builds { + if _, protected := keep[b.BuildID]; protected { + // Still reachable from a live root's header closure; deleting it + // would orphan a shared ancestor. Keep it (space not reclaimed). + logger.L().Warn(gctx, "keeping build: still referenced by a live build's header closure", + logger.WithTemplateID(templateID), + logger.WithBuildID(b.BuildID.String()), + ) + addCount(gctx, counters.guardKept, 1) + + continue + } + + if b.ClusterNodeID == nil { + // Build was never materialized on a node; nothing to delete. Count + // it (not silent) so candidates still reconciles. + logger.L().Info(gctx, "skipping build with no cluster node (not materialized)", + logger.WithTemplateID(templateID), + logger.WithBuildID(b.BuildID.String()), + ) + addCount(gctx, counters.skippedNilNode, 1) + + continue + } + + if minAge > 0 && now.Sub(b.CreatedAt) < minAge { + // Materialized but younger than the grace window. A freshly created + // build may have just been reused as a cache-hit ancestor by a + // concurrent build whose protecting row/header has not landed yet; + // deleting it now risks orphaning that reuse. Defer to the offline + // sweeper, which re-derives liveness and age from ground truth. + logger.L().Info(gctx, "skipping build younger than the online grace window (deferred to offline sweep)", + logger.WithTemplateID(templateID), + logger.WithBuildID(b.BuildID.String()), + ) + addCount(gctx, counters.skippedTooNew, 1) + + continue + } + + g.Go(func() error { + clusterID := clusters.WithClusterFallback(b.ClusterID) + clusterAttr := attribute.String("cluster", clusterID.String()) + + if err := deleteFn(gctx, b.BuildID, templateID, clusterID, *b.ClusterNodeID); err != nil { + logger.L().Warn(gctx, "failed to delete build artifacts", + logger.WithTemplateID(templateID), + logger.WithBuildID(b.BuildID.String()), + logger.WithError(err), + ) + addCountAttrs(gctx, counters.failed, 1, clusterAttr) + + return nil // best-effort: never abort siblings + } + + logger.L().Info(gctx, "deleted build artifacts", + logger.WithTemplateID(templateID), + logger.WithBuildID(b.BuildID.String()), + ) + addCountAttrs(gctx, counters.deleted, 1, clusterAttr) + + return nil + }) + } + + _ = g.Wait() // goroutines never return a non-nil error +} + +func addCount(ctx context.Context, c metric.Int64Counter, n int64) { + if c != nil && n != 0 { + c.Add(ctx, n) + } +} + +func addCountAttrs(ctx context.Context, c metric.Int64Counter, n int64, attrs ...attribute.KeyValue) { + if c != nil && n != 0 { + c.Add(ctx, n, metric.WithAttributes(attrs...)) + } +} + +func firstErr(errs ...error) error { + for _, e := range errs { + if e != nil { + return e + } + } + + return nil +} diff --git a/packages/api/internal/handlers/template_artifacts_test.go b/packages/api/internal/handlers/template_artifacts_test.go new file mode 100644 index 00000000000..62fa99e8833 --- /dev/null +++ b/packages/api/internal/handlers/template_artifacts_test.go @@ -0,0 +1,208 @@ +package handlers + +import ( + "context" + "errors" + "sync" + "testing" + "time" + + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/e2b-dev/infra/packages/api/internal/db/queries" + "github.com/e2b-dev/infra/packages/shared/pkg/consts" +) + +// noKeep is an empty reachability keep set: nothing is protected. +func noKeep() map[uuid.UUID]struct{} { return map[uuid.UUID]struct{}{} } + +// rowWithNode builds a materialized build row (has a cluster node). +func rowWithNode(node string, cluster *uuid.UUID) queries.GetExclusiveBuildsForTemplateDeletionRow { + return queries.GetExclusiveBuildsForTemplateDeletionRow{ + BuildID: uuid.New(), + ClusterNodeID: &node, + ClusterID: cluster, + // Old enough that the grace window never applies unless a test sets it. + CreatedAt: time.Now().Add(-365 * 24 * time.Hour), + } +} + +// rowWithNodeAge builds a materialized build row with an explicit creation time, +// for exercising the online grace window. +func rowWithNodeAge(node string, created time.Time) queries.GetExclusiveBuildsForTemplateDeletionRow { + return queries.GetExclusiveBuildsForTemplateDeletionRow{ + BuildID: uuid.New(), + ClusterNodeID: &node, + CreatedAt: created, + } +} + +// rowNoNode builds a not-yet-materialized build row (nil cluster node). +func rowNoNode() queries.GetExclusiveBuildsForTemplateDeletionRow { + return queries.GetExclusiveBuildsForTemplateDeletionRow{BuildID: uuid.New()} +} + +// Builds with a node are deleted; builds without a node (not yet materialized) +// are skipped — never passed to the deleter. +func TestProcessExclusiveBuilds_SkipsNilNode(t *testing.T) { + t.Parallel() + + withNode := rowWithNode("node-a", nil) + nilNode := rowNoNode() + + var mu sync.Mutex + var called []uuid.UUID + deleteFn := func(_ context.Context, buildID uuid.UUID, _ string, _ uuid.UUID, _ string) error { + mu.Lock() + defer mu.Unlock() + called = append(called, buildID) + + return nil + } + + processExclusiveBuilds(t.Context(), "tpl", []queries.GetExclusiveBuildsForTemplateDeletionRow{withNode, nilNode}, noKeep(), deleteFn, artifactCleanupCounters{}, time.Now(), 0) + + assert.Equal(t, []uuid.UUID{withNode.BuildID}, called, "only the materialized build is deleted; nil-node build skipped") +} + +// A build protected by the reachability keep set must never be passed to the +// deleter, even when it is materialized on a node. This is the regression guard +// against deleting a header-mapping ancestor still reconstructed by a live build. +func TestProcessExclusiveBuilds_GuardKeptNotDeleted(t *testing.T) { + t.Parallel() + + protected := rowWithNode("node-a", nil) + deletable := rowWithNode("node-b", nil) + + keep := map[uuid.UUID]struct{}{protected.BuildID: {}} + + var mu sync.Mutex + var called []uuid.UUID + deleteFn := func(_ context.Context, buildID uuid.UUID, _ string, _ uuid.UUID, _ string) error { + mu.Lock() + defer mu.Unlock() + called = append(called, buildID) + + return nil + } + + processExclusiveBuilds(t.Context(), "tpl", []queries.GetExclusiveBuildsForTemplateDeletionRow{protected, deletable}, keep, deleteFn, artifactCleanupCounters{}, time.Now(), 0) + + assert.Equal(t, []uuid.UUID{deletable.BuildID}, called, "protected build must not be deleted; only the unreferenced build is") +} + +// A failure on one build must not stop the others (best-effort cleanup). +func TestProcessExclusiveBuilds_ErrorIsNonFatal(t *testing.T) { + t.Parallel() + + b1 := rowWithNode("node-a", nil) + b2 := rowWithNode("node-b", nil) + b3 := rowWithNode("node-c", nil) + + var mu sync.Mutex + attempted := map[uuid.UUID]bool{} + deleteFn := func(_ context.Context, buildID uuid.UUID, _ string, _ uuid.UUID, _ string) error { + mu.Lock() + defer mu.Unlock() + attempted[buildID] = true + if buildID == b2.BuildID { + return errors.New("storage unreachable") + } + + return nil + } + + processExclusiveBuilds(t.Context(), "tpl", []queries.GetExclusiveBuildsForTemplateDeletionRow{b1, b2, b3}, noKeep(), deleteFn, artifactCleanupCounters{}, time.Now(), 0) + + assert.True(t, attempted[b1.BuildID] && attempted[b2.BuildID] && attempted[b3.BuildID], + "all builds attempted even though one failed") +} + +// A nil ClusterID resolves to the local cluster fallback, not a panic. +func TestProcessExclusiveBuilds_NilClusterFallback(t *testing.T) { + t.Parallel() + + explicit := uuid.New() + withCluster := rowWithNode("node-a", &explicit) + nilCluster := rowWithNode("node-b", nil) + + var mu sync.Mutex + got := map[uuid.UUID]uuid.UUID{} + deleteFn := func(_ context.Context, buildID uuid.UUID, _ string, clusterID uuid.UUID, _ string) error { + mu.Lock() + defer mu.Unlock() + got[buildID] = clusterID + + return nil + } + + processExclusiveBuilds(t.Context(), "tpl", []queries.GetExclusiveBuildsForTemplateDeletionRow{withCluster, nilCluster}, noKeep(), deleteFn, artifactCleanupCounters{}, time.Now(), 0) + + assert.Equal(t, explicit, got[withCluster.BuildID], "explicit cluster id is passed through") + assert.Equal(t, consts.LocalClusterID, got[nilCluster.BuildID], "nil cluster id falls back to local cluster") +} + +// Empty input is a no-op and does not invoke the deleter. +func TestProcessExclusiveBuilds_Empty(t *testing.T) { + t.Parallel() + + calls := 0 + deleteFn := func(_ context.Context, _ uuid.UUID, _ string, _ uuid.UUID, _ string) error { + calls++ + + return nil + } + + processExclusiveBuilds(t.Context(), "tpl", nil, noKeep(), deleteFn, artifactCleanupCounters{}, time.Now(), 0) + require.Zero(t, calls) +} + +// A materialized build younger than the grace window is NOT deleted on the +// online path; an old one is. This is the TOCTOU-narrowing deferral to the +// offline sweeper. +func TestProcessExclusiveBuilds_SkipsTooNewWithinGrace(t *testing.T) { + t.Parallel() + + now := time.Now() + fresh := rowWithNodeAge("node-a", now.Add(-1*time.Hour)) // younger than 24h + old := rowWithNodeAge("node-b", now.Add(-48*time.Hour)) // older than 24h + + var mu sync.Mutex + var called []uuid.UUID + deleteFn := func(_ context.Context, buildID uuid.UUID, _ string, _ uuid.UUID, _ string) error { + mu.Lock() + defer mu.Unlock() + called = append(called, buildID) + + return nil + } + + processExclusiveBuilds(t.Context(), "tpl", []queries.GetExclusiveBuildsForTemplateDeletionRow{fresh, old}, noKeep(), deleteFn, artifactCleanupCounters{}, now, 24*time.Hour) + + assert.Equal(t, []uuid.UUID{old.BuildID}, called, "only the build older than the grace window is deleted; the fresh one is deferred") +} + +// With the grace window disabled (minAge=0), even a just-created build is +// deleted — the online path keeps its prior behavior when the window is off. +func TestProcessExclusiveBuilds_GraceDisabledDeletesFresh(t *testing.T) { + t.Parallel() + + now := time.Now() + fresh := rowWithNodeAge("node-a", now) + + var mu sync.Mutex + var called []uuid.UUID + deleteFn := func(_ context.Context, buildID uuid.UUID, _ string, _ uuid.UUID, _ string) error { + mu.Lock() + defer mu.Unlock() + called = append(called, buildID) + + return nil + } + + processExclusiveBuilds(t.Context(), "tpl", []queries.GetExclusiveBuildsForTemplateDeletionRow{fresh}, noKeep(), deleteFn, artifactCleanupCounters{}, now, 0) + + assert.Equal(t, []uuid.UUID{fresh.BuildID}, called, "grace window off: a fresh build is still deleted") +} diff --git a/packages/api/internal/handlers/template_delete.go b/packages/api/internal/handlers/template_delete.go index 678db2e3f63..687eba39236 100644 --- a/packages/api/internal/handlers/template_delete.go +++ b/packages/api/internal/handlers/template_delete.go @@ -129,6 +129,11 @@ func (a *APIStore) DeleteTemplatesTemplateID(c *gin.Context, aliasOrTemplateID a a.templateCache.InvalidateAllTags(context.WithoutCancel(ctx), templateID) a.templateCache.InvalidateAliasesByTemplateID(context.WithoutCancel(ctx), templateID, aliasKeys) + // Delete the storage artifacts (rootfs/kernel/snapshot) of builds now + // exclusively owned by this template. Runs in the background after the DB + // commit so storage errors never affect the delete response. + a.startTemplateArtifactCleanup(ctx, team.ID, templateID) + telemetry.ReportEvent(ctx, "deleted template from db") properties := a.posthog.GetPackageToPosthogProperties(&c.Request.Header) diff --git a/packages/shared/pkg/featureflags/flags.go b/packages/shared/pkg/featureflags/flags.go index 4650345bfab..8a57062f7d5 100644 --- a/packages/shared/pkg/featureflags/flags.go +++ b/packages/shared/pkg/featureflags/flags.go @@ -751,6 +751,14 @@ var ( // 0 probes the parent header's readiness without waiting; a positive value // waits up to that long before refusing retryably. PauseAdmissionGraceMs = NewIntFlag("pause-admission-grace-milliseconds", -1) + // TemplateArtifactMinAgeSeconds is the online template-artifact deletion + // grace window, in seconds. A DB-exclusive deletion candidate younger than + // this is NOT deleted on the online path; it is counted as skipped_too_new + // and left to the offline sweeper. This narrows the TOCTOU window between + // the live-root query and DeleteBuild (a fresh build may have just been + // reused as a cache-hit ancestor whose protecting row/header has not landed + // yet). Fallback 86400 (24h); 0 or negative disables the window. + TemplateArtifactMinAgeSeconds = NewIntFlag("template-artifact-min-age-seconds", 86400) // PauseEnvdHealthTimeoutMs gates the envd health probe every snapshot runs // before anything destructive, in milliseconds. 0 or less (default -1) // disables the probe: an HTTP request cannot complete inside a zero diff --git a/packages/shared/pkg/logger/fields.go b/packages/shared/pkg/logger/fields.go index f59e05243cb..bc548562c3a 100644 --- a/packages/shared/pkg/logger/fields.go +++ b/packages/shared/pkg/logger/fields.go @@ -27,6 +27,12 @@ func WithBuildID(buildID string) zap.Field { return zap.String("build.id", buildID) } +// WithError is the internal field helper for attaching an error to a log line, +// so callers use the logger package's API instead of importing zap directly. +func WithError(err error) zap.Field { + return zap.Error(err) +} + func WithExecutionID(executionID string) zap.Field { return zap.String("execution.id", executionID) } diff --git a/packages/shared/pkg/telemetry/meters.go b/packages/shared/pkg/telemetry/meters.go index a0f04bb4559..ddc75f093ca 100644 --- a/packages/shared/pkg/telemetry/meters.go +++ b/packages/shared/pkg/telemetry/meters.go @@ -30,6 +30,13 @@ const ( // back to any builder at that version. ApiTemplateBuildBuilderPinFallback CounterType = "api.template.build.builder_pin_fallback" ApiOrchestratorCreatedSandboxes CounterType = "api.orchestrator.created_sandboxes" + ApiTemplateArtifactsCandidates CounterType = "api.template.artifacts.candidates" + ApiTemplateArtifactsDeleted CounterType = "api.template.artifacts.deleted" + ApiTemplateArtifactsDeleteFailed CounterType = "api.template.artifacts.delete_failed" + ApiTemplateArtifactsSkippedNilNode CounterType = "api.template.artifacts.skipped_nil_node" + ApiTemplateArtifactsGuardKept CounterType = "api.template.artifacts.guard_kept" + ApiTemplateArtifactsSkippedTooNew CounterType = "api.template.artifacts.skipped_too_new" + ApiTemplateArtifactsFailClosed CounterType = "api.template.artifacts.fail_closed" ApiOrchestratorResumeOriginNodeRemap CounterType = "api.orchestrator.resume_origin_node_remapped" ApiOrchestratorSandboxFeatureUnsupported CounterType = "api.orchestrator.sandbox_feature_unsupported" // ApiOrchestratorPauseRefusalRestore counts what became of a pause the @@ -932,6 +939,13 @@ var counterDesc = map[CounterType]string{ ApiTemplateBuildBuilderPinFallback: "Template builder lookups that fell back to any builder because none with the pinned machine info is at the required version", SandboxCreateMeterName: "Number of currently waiting requests to create a new sandbox", ApiOrchestratorCreatedSandboxes: "Number of successfully created sandboxes", + ApiTemplateArtifactsCandidates: "Number of builds the DB considered exclusive to a deleted template (reconciliation denominator: candidates == deleted + delete_failed + skipped_nil_node + guard_kept, or fail_closed>0 when nothing was deleted)", + ApiTemplateArtifactsDeleted: "Number of template build artifacts (rootfs/kernel/snapshot) successfully deleted on template deletion, by cluster", + ApiTemplateArtifactsDeleteFailed: "Number of template build artifacts whose deletion failed on template deletion (potential orphaned storage), by cluster", + ApiTemplateArtifactsSkippedNilNode: "Number of exclusive builds skipped because they were never materialized on a node (nil cluster_node_id; nothing to delete)", + ApiTemplateArtifactsGuardKept: "Number of exclusive builds the reachability guard kept because a live build still references them through its header closure (space intentionally not reclaimed)", + ApiTemplateArtifactsSkippedTooNew: "Number of exclusive builds skipped on the online path because they were younger than the grace window (deferred to the offline sweeper; narrows the TOCTOU window against a concurrent cache-hit reuse)", + ApiTemplateArtifactsFailClosed: "Number of exclusive builds not deleted because the reachability guard could not be proven and the cleanup failed closed, by reason (reader_unconfigured|live_roots_query|header_unreadable). Alert on this: it means storage is not being reclaimed.", ApiEvictorFsOnlyAutoPause: "Timeout auto-pauses with a filesystem-only policy.", ApiEvictorAutoPauseDegraded: "Timeout auto-pauses the evictor answered with a degrade after a node refusal, by cause: filesystem-only for a busy node (admission_refused | overstay_budget), the memory pause retried without requiring a healthy guest agent, so the node takes it and records the miss (envd_grace), or that retry withheld for want of an execution id (envd_grace_withheld) or because the sweep asks for a filesystem-only capture, which needs the guest agent (envd_grace_fs_only).", ApiOrchestratorResumeOriginNodeRemap: "Number of resume snapshots repointed to the fallback node a previous resume timed out on", @@ -1043,6 +1057,13 @@ var counterUnits = map[CounterType]string{ ApiTemplateBuildBuilderPinFallback: "{lookup}", SandboxCreateMeterName: "{sandbox}", ApiOrchestratorCreatedSandboxes: "{sandbox}", + ApiTemplateArtifactsCandidates: "{build}", + ApiTemplateArtifactsDeleted: "{build}", + ApiTemplateArtifactsDeleteFailed: "{build}", + ApiTemplateArtifactsSkippedNilNode: "{build}", + ApiTemplateArtifactsGuardKept: "{build}", + ApiTemplateArtifactsSkippedTooNew: "{build}", + ApiTemplateArtifactsFailClosed: "{build}", ApiEvictorFsOnlyAutoPause: "{pause}", ApiEvictorAutoPauseDegraded: "{pause}", ApiOrchestratorResumeOriginNodeRemap: "{snapshot}", From 2536e80c9f1f963c6315a53c09630a6df386f7fe Mon Sep 17 00:00:00 2001 From: AdaAibaby Date: Thu, 26 Nov 2026 14:07:31 +0800 Subject: [PATCH 2/2] fix(api): delete snapshot build artifacts on sandbox snapshot deletion A snapshot is backed by its own template; on snapshot deletion, remove the build artifacts exclusively owned by that snapshot-template while protecting any base shared with a live template. Adds the exclusivity guard test (readmodel package, latest-main structure). Combines the two commits of #3798. --- .../snapshot_artifact_exclusivity_test.go | 123 ++++++++++++++++++ .../api/internal/handlers/sandbox_kill.go | 11 ++ 2 files changed, 134 insertions(+) create mode 100644 packages/api/internal/db/readmodel/snapshot_artifact_exclusivity_test.go diff --git a/packages/api/internal/db/readmodel/snapshot_artifact_exclusivity_test.go b/packages/api/internal/db/readmodel/snapshot_artifact_exclusivity_test.go new file mode 100644 index 00000000000..b8abad75a70 --- /dev/null +++ b/packages/api/internal/db/readmodel/snapshot_artifact_exclusivity_test.go @@ -0,0 +1,123 @@ +package readmodel + +import ( + "testing" + + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/e2b-dev/infra/packages/api/internal/db/pkg/testutils" + "github.com/e2b-dev/infra/packages/api/internal/db/queries" +) + +// buildIDs extracts the build IDs from exclusive-builds rows for assertions. +func buildIDs(rows []queries.GetExclusiveBuildsForTemplateDeletionRow) []uuid.UUID { + out := make([]uuid.UUID, 0, len(rows)) + for _, r := range rows { + out = append(out, r.BuildID) + } + + return out +} + +// Proves the artifact-cleanup exclusivity guard holds on the SNAPSHOT path: +// a snapshot is backed by its own template (deleteSnapshot soft-deletes it), so +// GetExclusiveBuildsForTemplateDeletion(snapshot.TemplateID) must return the +// builds exclusively owned by that snapshot-template — including after the +// template is soft-deleted — and must NOT return a build shared with another +// template. This is what gates which artifacts snapshot deletion removes. +func TestSnapshotArtifactExclusivity(t *testing.T) { + t.Parallel() + db := testutils.SetupDatabase(t) + ctx := t.Context() + + teamID := testutils.CreateTestTeam(t, db) + baseEnvID := testutils.CreateTestTemplate(t, db, teamID) + + // Snapshot backed by its own template; UpsertSnapshot creates one build. + _, snapTemplateID, snapshotBuildID := createTestSnapshot(t, db, teamID, baseEnvID) + + // An extra build exclusively owned by the snapshot's template. + exclusiveBuildID := createTestEnvBuild(t, db, snapTemplateID) + + // A build shared with ANOTHER template: assigned to both the snapshot's + // template and a second template -> must be excluded by the guard. + otherTemplateID := testutils.CreateTestTemplate(t, db, teamID) + sharedBuildID := uuid.New() + require.NoError(t, db.SqlcClient.TestsRawSQL(ctx, + `INSERT INTO public.env_builds + (id, status, vcpu, ram_mb, free_disk_size_mb, total_disk_size_mb, kernel_version, firecracker_version, envd_version, cluster_node_id, created_at, updated_at, version) + VALUES ($1,'ready',2,2048,512,1024,'6.1.0','1.4.0','v1.0.0','test-node',NOW(),NOW(),1)`, + sharedBuildID)) + require.NoError(t, db.SqlcClient.TestsRawSQL(ctx, + `INSERT INTO public.env_build_assignments (env_id, build_id, tag) VALUES ($1,$2,'default')`, + snapTemplateID, sharedBuildID)) + require.NoError(t, db.SqlcClient.TestsRawSQL(ctx, + `INSERT INTO public.env_build_assignments (env_id, build_id, tag) VALUES ($1,$2,'default')`, + otherTemplateID, sharedBuildID)) + + // Soft-delete the snapshot's template, exactly as deleteSnapshot does, to + // prove the query still resolves afterwards (it joins raw envs, not active). + require.NoError(t, db.SqlcClient.TestsRawSQL(ctx, + `UPDATE public.envs SET deleted_at = NOW() WHERE id = $1`, snapTemplateID)) + + rows, err := db.SqlcClient.GetExclusiveBuildsForTemplateDeletion(ctx, snapTemplateID) + require.NoError(t, err) + + got := buildIDs(rows) + assert.Contains(t, got, snapshotBuildID, "the snapshot's own build is exclusive -> returned") + assert.Contains(t, got, exclusiveBuildID, "the extra exclusive build is returned") + assert.NotContains(t, got, sharedBuildID, "a build shared with another template must NOT be returned") + + // Every returned build carries the node id needed to route DeleteBuild. + for _, r := range rows { + require.NotNil(t, r.ClusterNodeID, "exclusive build must carry cluster_node_id for routing") + } +} + +// The snapshot deletion path must never even consider the BASE template's build +// as a deletion candidate: the base build is assigned to the base template, not +// to the snapshot's template, so GetExclusiveBuildsForTemplateDeletion for the +// snapshot's template must exclude it. This is the complement of the live-root +// guard — together they ensure deleting a checkpoint-derived snapshot removes +// only the snapshot's own COW diff layer and never the base it stacks on. +func TestSnapshotArtifactExclusivity_BaseBuildNotCandidate(t *testing.T) { + t.Parallel() + db := testutils.SetupDatabase(t) + ctx := t.Context() + + teamID := testutils.CreateTestTeam(t, db) + baseEnvID := testutils.CreateTestTemplate(t, db, teamID) + + // The snapshot's source build lives on the BASE template; the snapshot gets + // its own diff build on its own template. + _, snapTemplateID, snapshotBuildID := createTestSnapshot(t, db, teamID, baseEnvID) + + // Deleting the snapshot => query exclusivity for the snapshot's template. + require.NoError(t, db.SqlcClient.TestsRawSQL(ctx, + `UPDATE public.envs SET deleted_at = NOW() WHERE id = $1`, snapTemplateID)) + + rows, err := db.SqlcClient.GetExclusiveBuildsForTemplateDeletion(ctx, snapTemplateID) + require.NoError(t, err) + got := buildIDs(rows) + + assert.Contains(t, got, snapshotBuildID, "the snapshot's own diff build is a deletion candidate") + + // Collect the base template's builds; none of them may appear as a candidate + // of the snapshot's template. + baseRows, err := db.SqlcClient.GetExclusiveBuildsForTemplateDeletion(ctx, baseEnvID) + require.NoError(t, err) + for _, br := range baseRows { + assert.NotContains(t, got, br.BuildID, "a base-template build must never be a deletion candidate of the snapshot template") + } + + // And the snapshot build protects the base on the base-delete direction: + // it is a live root for the team when the base template is deleted. + liveRoots, err := db.SqlcClient.GetLiveBuildRootsForTeamExcludingTemplate(ctx, queries.GetLiveBuildRootsForTeamExcludingTemplateParams{ + TeamID: teamID, + TemplateID: baseEnvID, + }) + require.NoError(t, err) + assert.Contains(t, liveRoots, snapshotBuildID, "the snapshot build must be a live root when its base template is deleted") +} diff --git a/packages/api/internal/handlers/sandbox_kill.go b/packages/api/internal/handlers/sandbox_kill.go index c9389a9a1a1..1bc9b6330ce 100644 --- a/packages/api/internal/handlers/sandbox_kill.go +++ b/packages/api/internal/handlers/sandbox_kill.go @@ -34,6 +34,17 @@ func (a *APIStore) deleteSnapshot(ctx context.Context, sandboxID string, teamID a.templateCache.InvalidateAliasesByTemplateID(context.WithoutCancel(ctx), snapshot.TemplateID, aliasKeys) a.snapshotCache.Invalidate(context.WithoutCancel(ctx), sandboxID) + // A snapshot is backed by its own template, so deleting it soft-deletes that + // template above. Clean up the storage artifacts of builds now exclusively + // owned by it, reusing the same reachability-guarded, best-effort cleanup as + // template deletion. The guard is what makes this safe in the base-deleted + // direction: the snapshot's build reaches its base template's layers through + // its header closure, so if some OTHER live build also reaches a base layer + // that is now DB-exclusive to this snapshot-template, the guard keeps it. + // Background + bounded: never affects the delete result. teamID scopes the + // live-root set the guard consults. + a.startTemplateArtifactCleanup(ctx, teamID, snapshot.TemplateID) + return nil }