chore: 初始化仓库,导入项目基线代码

Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、
Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。
今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
runny committed 2026-11-16 18:12:23 +08:00
commit 7ec21f35b0
5767 files changed
+1436788

No files matched your search

@@ -0,0 +1,340 @@
package sandboxalloc
import (
"context"
"errors"
"fmt"
"time"
"academy/internal/logger"
"academy/internal/sandbox"
"academy/internal/sandbox/allocation"
"academy/internal/types"
"academy/internal/types/interfaces"
)
// UserMachineOps is the slice of *sandbox.SessionBoundManager the cleaner and
// the GC drive.
type UserMachineOps interface {
DeleteSessionWorkspaces(ctx context.Context, machine allocation.UserMachine, sessionIDs []string) ([]string, error)
ReclaimUserMachine(ctx context.Context, machine allocation.UserMachine,
check func(context.Context) (bool, error)) (bool, error)
}
// cleanupBackoff is the wait before the next attempt. There is no attempt
// counter (C17): the delay grows with the time since the release, which
// roughly doubles it per attempt, from 1m up to 4h.
func cleanupBackoff(releasedAt *time.Time, now time.Time) time.Duration {
d := time.Minute
if releasedAt != nil {
d = now.Sub(*releasedAt)
}
return min(max(d, time.Minute), 4*time.Hour)
}
// WorkspaceCleaner gives a deleted user-mode session's directory back.
type WorkspaceCleaner struct {
svc *Service
resolver sandbox.TenantSandboxResolver
now func() time.Time
}
// NewWorkspaceCleaner wires the cleaner. resolver resolves managers without
// the workspace kill switch: teardown must work while scripts are disabled.
func NewWorkspaceCleaner(svc *Service, resolver sandbox.TenantSandboxResolver) *WorkspaceCleaner {
return &WorkspaceCleaner{svc: svc, resolver: resolver, now: svc.Now}
}
// sessionDirectoryDeleter is the only method directory cleanup needs.
// UserMachineOps also requires ReclaimUserMachine. Asserting that here would
// fail directory cleanup for a manager that can delete directories but not
// reclaim. The GC and delete-all assert ReclaimUserMachine on their own.
type sessionDirectoryDeleter interface {
DeleteSessionWorkspaces(ctx context.Context, machine allocation.UserMachine, sessionIDs []string) ([]string, error)
}
func (c *WorkspaceCleaner) machineOps(ctx context.Context, m allocation.UserMachine) (sessionDirectoryDeleter, error) {
if c.resolver == nil {
return nil, errors.New("sandboxalloc: no sandbox resolver")
}
mgr, err := c.resolver.Resolve(types.WithSandboxTenantID(ctx, m.OwnerTenantID), m.ConfigTenantID, m.ConfigID)
if err != nil {
return nil, err
}
ops, ok := mgr.(sessionDirectoryDeleter)
if !ok {
return nil, fmt.Errorf("sandboxalloc: config %d/%s does not serve user machines", m.ConfigTenantID, m.ConfigID)
}
return ops, nil
}
// userMachineReclaimer is asserted by the GC and by delete-all, separately
// from directory cleanup. machineOps stays the narrower assert so a manager
// that can delete directories still can, before it learns how to reclaim.
type userMachineReclaimer interface {
ReclaimUserMachine(
ctx context.Context, machine allocation.UserMachine, check func(context.Context) (bool, error),
) (bool, error)
}
func (c *WorkspaceCleaner) reclaimOps(ctx context.Context, m allocation.UserMachine) (userMachineReclaimer, error) {
ops, err := c.machineOps(ctx, m)
if err != nil {
return nil, err
}
reclaimer, ok := ops.(userMachineReclaimer)
if !ok {
return nil, fmt.Errorf("sandboxalloc: config %d/%s does not reclaim user machines",
m.ConfigTenantID, m.ConfigID)
}
return reclaimer, nil
}
// ReleaseSessions retires every session in sessionIDs in one transaction
// (C5): placement is closed for all of them, and each user-mode assignment
// is released with its cleanup task. handled names the sessions on a shared
// machine; the caller tears the others down as before. An error means
// nothing was retired; the caller must not delete the sessions.
func (c *WorkspaceCleaner) ReleaseSessions(ctx context.Context, sessionIDs []string) (map[string]bool, error) {
out, err := c.svc.Retire(ctx, sessionIDs)
if err != nil {
return nil, err
}
handled := make(map[string]bool, len(out))
for _, r := range out {
if r.Assignment != nil && r.Assignment.MachineDigest != "" {
handled[r.SessionID] = true
}
}
return handled, nil
}
// UserSessions classifies existing placements without retiring them. Retirement
// must commit with the session deletion, not with this pre-delete lookup.
func (c *WorkspaceCleaner) UserSessions(ctx context.Context, ids []string) (map[string]bool, error) {
handled := make(map[string]bool)
for _, id := range ids {
row, err := c.svc.repo.GetAssignment(ctx, id)
if err != nil {
return nil, err
}
if row != nil && row.MachineDigest != "" {
handled[id] = true
}
}
return handled, nil
}
// DeleteSessions atomically removes the authorized session rows and records
// retirement and cleanup intent. Only committed retirements may trigger cleanup.
func (c *WorkspaceCleaner) DeleteSessions(
ctx context.Context, tenantID uint64, idsByOwner map[string][]string,
) (map[string]bool, int, error) {
retired, err := c.svc.repo.DeleteSessionsRetiring(ctx, tenantID, idsByOwner, c.now())
if err != nil {
return nil, 0, err
}
handled := make(map[string]bool)
for _, r := range retired {
if r.Assignment != nil && r.Assignment.MachineDigest != "" {
handled[r.SessionID] = true
}
}
return handled, len(retired), nil
}
// RunCleanups runs the due cleanup of these sessions now, one command per
// machine. Anything not done stays due for RetryDue.
func (c *WorkspaceCleaner) RunCleanups(ctx context.Context, sessionIDs []string) {
rows := make([]*types.SessionSandboxAssignment, 0, len(sessionIDs))
for _, id := range sessionIDs {
row, err := c.svc.repo.GetAssignment(ctx, id)
if err != nil {
logger.Warnf(ctx, "[sandbox-alloc] load cleanup of %s: %v", id, err)
continue
}
if row != nil && row.CleanupDueAt != nil && row.MachineDigest != "" {
rows = append(rows, row)
}
}
c.execute(ctx, rows)
}
// RetryDue retries queued directory deletes whose backoff has elapsed.
func (c *WorkspaceCleaner) RetryDue(ctx context.Context, limit int) (int, int, error) {
rows, err := c.svc.repo.ListDueWorkspaceCleanups(ctx, c.now(), limit)
if err != nil {
return 0, 0, err
}
done, failed := c.execute(ctx, rows)
return done, failed, nil
}
func (c *WorkspaceCleaner) execute(ctx context.Context, rows []*types.SessionSandboxAssignment) (int, int) {
batches := map[string][]*types.SessionSandboxAssignment{}
for _, row := range rows {
batches[row.MachineDigest] = append(batches[row.MachineDigest], row)
}
done, failed := 0, 0
retry := func(row *types.SessionSandboxAssignment, reason string) {
failed++
logger.Warnf(ctx, "[sandbox-alloc] clean workspace of %s: %s", row.SessionID, reason)
_ = c.svc.repo.RetryWorkspaceCleanup(ctx, row.SessionID, c.now().Add(cleanupBackoff(row.ReleasedAt, c.now())))
}
for digest, rows := range batches {
// The machine's identity is its registry row. A reclaimed machine took
// the directory with it (C5).
reg, err := c.svc.repo.GetUserMachine(ctx, digest)
if err != nil {
for _, row := range rows {
retry(row, err.Error())
}
continue
}
if reg == nil {
for _, row := range rows {
_ = c.svc.repo.CompleteWorkspaceCleanup(ctx, row.SessionID)
done++
}
continue
}
b := struct {
machine allocation.UserMachine
rows []*types.SessionSandboxAssignment
}{machineOf(reg), rows}
ids := make([]string, 0, len(b.rows))
for _, row := range b.rows {
ids = append(ids, row.SessionID)
}
var deleted []string
ops, err := c.machineOps(ctx, b.machine)
if err == nil {
deleted, err = ops.DeleteSessionWorkspaces(ctx, b.machine, ids)
}
gone := make(map[string]bool, len(deleted))
for _, id := range deleted {
gone[id] = true
}
reason := "session operations still registered"
if err != nil {
reason = err.Error()
}
for _, row := range b.rows {
if gone[row.SessionID] {
_ = c.svc.repo.CompleteWorkspaceCleanup(ctx, row.SessionID)
done++
continue
}
retry(row, reason)
}
}
return done, failed
}
// ReleaseOwnerAssignments retires every session of a deleted account and
// releases their assignments (C5). It must succeed before the account is
// deleted: afterwards nothing could release them, and their machines would
// never become empty.
func (c *WorkspaceCleaner) ReleaseOwnerAssignments(ctx context.Context, ownerID string) error {
_, err := c.svc.repo.RetireOwnerSessions(ctx, ownerID, c.now())
return err
}
// ReclaimOwner gives back the deleted account's machines now; any it cannot
// reclaim yet are left to the GC's retention window.
func (c *WorkspaceCleaner) ReclaimOwner(ctx context.Context, ownerID string) {
machines, err := c.OwnerMachines(ctx, 0, ownerID)
if err != nil {
logger.Warnf(ctx, "[sandbox-alloc] list machines of %s: %v", ownerID, err)
return
}
c.ReclaimOwnerMachines(ctx, machines)
}
// OwnerMachines lists ownerID's machines in one tenant (0 = every tenant).
func (c *WorkspaceCleaner) OwnerMachines(
ctx context.Context, ownerTenantID uint64, ownerID string,
) ([]allocation.UserMachine, error) {
rows, err := c.svc.repo.ListUserMachinesByOwner(ctx, ownerTenantID, ownerID)
if err != nil {
return nil, err
}
out := make([]allocation.UserMachine, 0, len(rows))
for _, r := range rows {
out = append(out, machineOf(r))
}
return out, nil
}
// ReleaseMachine deletes m now, when an admin chose to. Registered work and
// a live session still block it (false, nil): the same locked check
// ReclaimOwnerMachines uses decides, so a terminal is never cut and there is
// no second destroy path. A cleared empty_since is a session that joined,
// not an empty machine. Sessions on a refused machine keep their assignments.
func (c *WorkspaceCleaner) ReleaseMachine(ctx context.Context, m allocation.UserMachine) (bool, error) {
return c.destroyIfEmpty(ctx, m)
}
// ReclaimOwnerMachines deletes machines whose sessions were all just deleted
// by "delete all" or a user deletion, without waiting for the retention
// window. A machine with a live session, a cleared empty clock, or registered
// work is left to the GC.
func (c *WorkspaceCleaner) ReclaimOwnerMachines(ctx context.Context, machines []allocation.UserMachine) {
for _, m := range machines {
if _, err := c.destroyIfEmpty(ctx, m); err != nil {
logger.Warnf(ctx, "[sandbox-alloc] release machine %s: %v", digestPrefix(c.svc.Digest(m)), err)
}
}
}
// destroyIfEmpty deletes the provider sandbox and the registry row while the
// machine row is locked. The lock is taken inside the manager's check, which
// runs after the lifecycle lock and the admission barrier and before the
// provider delete, and it is released only after the registry delete. A nil
// empty_since is not empty: joining a machine clears that clock.
func (c *WorkspaceCleaner) destroyIfEmpty(ctx context.Context, m allocation.UserMachine) (bool, error) {
ops, err := c.reclaimOps(ctx, m)
if err != nil {
return false, err
}
digest := c.svc.Digest(m)
var lock interfaces.MachineReclaimLock
ok, err := ops.ReclaimUserMachine(ctx, m, func(_ context.Context) (bool, error) {
var lockErr error
// The transaction outlives the manager's guarded provider context.
// Keep caller cancellation, but hold the row lock through CommitDelete.
lock, lockErr = c.svc.repo.LockEmptyMachine(ctx, digest)
if lockErr != nil || lock == nil {
return false, lockErr
}
return true, nil
})
if lock != nil {
defer lock.Abort()
}
if err != nil || !ok {
return false, err
}
if lock == nil {
// The manager reported the machine reclaimable without ever running
// the check that takes its row lock; nothing was provably deleted,
// so no registry row may be dropped.
return false, fmt.Errorf(
"sandboxalloc: manager of config %d/%s skipped the reclaim check",
m.ConfigTenantID, m.ConfigID)
}
deleted, delErr := lock.CommitDelete()
if delErr != nil {
logger.Warnf(ctx, "[sandbox-alloc] drop registry row %s: %v", digestPrefix(digest), delErr)
return false, delErr
}
return deleted, nil
}
// machineOf is the allocation identity stored on a registry row.
func machineOf(reg *types.SandboxUserMachine) allocation.UserMachine {
return allocation.UserMachine{
OwnerTenantID: reg.OwnerTenantID, OwnerID: reg.OwnerID,
ConfigTenantID: reg.ConfigTenantID, ConfigID: reg.ConfigID,
}
}
@@ -0,0 +1,265 @@
package sandboxalloc
import (
"context"
"errors"
"testing"
"time"
"github.com/google/uuid"
"github.com/stretchr/testify/require"
"academy/internal/sandbox"
"academy/internal/sandbox/allocation"
)
type fakeMachineOps struct {
sandbox.Manager
deleted [][]string
failNext error
busy map[string]bool
}
func (f *fakeMachineOps) DeleteSessionWorkspaces(
_ context.Context, _ allocation.UserMachine, ids []string,
) ([]string, error) {
if f.failNext != nil {
err := f.failNext
f.failNext = nil
return nil, err
}
var done []string
for _, id := range ids {
if !f.busy[id] {
done = append(done, id)
}
}
f.deleted = append(f.deleted, done)
return done, nil
}
func (f *fakeMachineOps) ReclaimUserMachine(
context.Context, allocation.UserMachine, func(context.Context) (bool, error),
) (bool, error) {
return true, nil
}
type fakeResolver struct{ mgr sandbox.Manager }
func (r fakeResolver) Resolve(context.Context, uint64, string) (sandbox.Manager, error) {
return r.mgr, nil
}
// pendingCleanups names the sessions in ids whose directory cleanup is still due.
func pendingCleanups(t *testing.T, e *testEnv, ids ...string) []string {
t.Helper()
var out []string
for _, id := range ids {
row, err := e.svc.repo.GetAssignment(context.Background(), id)
require.NoError(t, err)
if row != nil && row.CleanupDueAt != nil {
out = append(out, id)
}
}
return out
}
func TestReleaseSessionsPersistsIntentAndSkipsSessionMode(t *testing.T) {
enableUserMode(t)
a, b, legacy := uuid.NewString(), uuid.NewString(), uuid.NewString()
legacyRow := webSession(legacy)
legacyRow.SandboxConfigID, legacyRow.SandboxConfigTenantID = "cfg-a", 7
e := newEnv(t, fakeConfigs{"cfg-a": "user"}, webSession(a), webSession(b), legacyRow)
for _, id := range []string{a, b, legacy} {
e.place(t, id, "cfg-a")
}
ops := &fakeMachineOps{}
c := NewWorkspaceCleaner(e.svc, fakeResolver{mgr: ops})
handled, err := c.ReleaseSessions(context.Background(), []string{a, b, legacy})
require.NoError(t, err)
require.True(t, handled[a])
require.True(t, handled[b])
require.False(t, handled[legacy], "a per-session sandbox is torn down by the caller as before")
require.Empty(t, ops.deleted, "release only records intent; nothing runs on the machine yet")
require.ElementsMatch(t, []string{a, b}, pendingCleanups(t, e, a, b, legacy))
c.RunCleanups(context.Background(), []string{a, b})
require.Len(t, ops.deleted, 1, "one machine, one command")
require.ElementsMatch(t, []string{a, b}, ops.deleted[0])
require.Empty(t, pendingCleanups(t, e, a, b))
}
// deleteOnlyMachine is what *sandbox.SessionBoundManager can do today:
// DeleteSessionWorkspaces exists, ReclaimUserMachine does not until the
// empty-machine GC. Cleanup must not require the later method.
type deleteOnlyMachine struct {
sandbox.Manager
deleted [][]string
}
func (d *deleteOnlyMachine) DeleteSessionWorkspaces(
_ context.Context, _ allocation.UserMachine, ids []string,
) ([]string, error) {
copied := append([]string(nil), ids...)
d.deleted = append(d.deleted, copied)
return copied, nil
}
func TestRunCleanupsCompletesWhenTheManagerOnlyDeletesDirectories(t *testing.T) {
enableUserMode(t)
id := uuid.NewString()
e := newEnv(t, fakeConfigs{"cfg-a": "user"}, webSession(id))
e.place(t, id, "cfg-a")
ops := &deleteOnlyMachine{}
c := NewWorkspaceCleaner(e.svc, fakeResolver{mgr: ops})
_, err := c.ReleaseSessions(context.Background(), []string{id})
require.NoError(t, err)
c.RunCleanups(context.Background(), []string{id})
require.Empty(t, pendingCleanups(t, e, id), "the directory task is done, not retried")
require.Equal(t, [][]string{{id}}, ops.deleted)
}
func TestRunCleanupsKeepsBusyAndFailedTasksForRetry(t *testing.T) {
enableUserMode(t)
a, b := uuid.NewString(), uuid.NewString()
e := newEnv(t, fakeConfigs{"cfg-a": "user"}, webSession(a), webSession(b))
e.place(t, a, "cfg-a")
e.place(t, b, "cfg-a")
ops := &fakeMachineOps{busy: map[string]bool{b: true}}
c := NewWorkspaceCleaner(e.svc, fakeResolver{mgr: ops})
_, err := c.ReleaseSessions(context.Background(), []string{a, b})
require.NoError(t, err)
c.RunCleanups(context.Background(), []string{a, b})
require.Equal(t, []string{b}, pendingCleanups(t, e, a, b), "B still had work registered")
ops.busy = nil
ops.failNext = errors.New("connect: timeout")
c.now = func() time.Time { return time.Now().UTC().Add(time.Hour) }
done, failed, err := c.RetryDue(context.Background(), 10)
require.NoError(t, err)
require.Zero(t, done)
require.Equal(t, 1, failed)
c.now = func() time.Time { return time.Now().UTC().Add(24 * time.Hour) }
done, _, err = c.RetryDue(context.Background(), 10)
require.NoError(t, err)
require.Equal(t, 1, done)
}
func TestReleaseOwnerThenReclaim(t *testing.T) {
enableUserMode(t)
a := uuid.NewString()
e := newEnv(t, fakeConfigs{"cfg-a": "user"}, webSession(a))
e.place(t, a, "cfg-a")
ops := &reclaimRecorder{}
c := NewWorkspaceCleaner(e.svc, fakeResolver{mgr: ops})
require.NoError(t, c.ReleaseOwnerAssignments(context.Background(), "u-1"))
got, ok, err := e.svc.Lookup(context.Background(), a)
require.NoError(t, err)
require.True(t, ok)
require.NotNil(t, got.ReleasedAt)
c.ReclaimOwner(context.Background(), "u-1")
require.Equal(t, 1, ops.reclaims)
m, _ := e.svc.repo.GetUserMachine(context.Background(), e.digest(t, a))
require.Nil(t, m, "the registry row goes with the machine")
}
func TestReleaseMachineRefusesLiveSessions(t *testing.T) {
enableUserMode(t)
a := uuid.NewString()
e := newEnv(t, fakeConfigs{"cfg-a": "user"}, webSession(a))
e.place(t, a, "cfg-a")
ops := &reclaimRecorder{}
c := NewWorkspaceCleaner(e.svc, fakeResolver{mgr: ops})
machines, err := c.OwnerMachines(context.Background(), 7, "u-1")
require.NoError(t, err)
require.Len(t, machines, 1)
ok, err := c.ReleaseMachine(context.Background(), machines[0])
require.NoError(t, err)
require.False(t, ok, "a live session keeps the machine")
require.Zero(t, ops.reclaims, "the in-lock check must refuse before destroy")
m, err := e.svc.repo.GetUserMachine(context.Background(), e.digest(t, a))
require.NoError(t, err)
require.NotNil(t, m)
}
func TestReleaseMachineDoesNotTreatAClearedClockAsEmpty(t *testing.T) {
enableUserMode(t)
a := uuid.NewString()
e := newEnv(t, fakeConfigs{"cfg-a": "user"}, webSession(a))
e.place(t, a, "cfg-a")
ops := &reclaimRecorder{}
c := NewWorkspaceCleaner(e.svc, fakeResolver{mgr: ops})
require.NoError(t, c.ReleaseOwnerAssignments(context.Background(), "u-1"))
require.NoError(t, e.db.Exec(
"UPDATE sandbox_user_machines SET empty_since = NULL WHERE machine_digest = ?", e.digest(t, a),
).Error)
machines, err := c.OwnerMachines(context.Background(), 0, "u-1")
require.NoError(t, err)
ok, err := c.ReleaseMachine(context.Background(), machines[0])
require.NoError(t, err)
require.False(t, ok, "a cleared empty_since means a session joined; do not destroy")
require.Zero(t, ops.reclaims)
m, err := e.svc.repo.GetUserMachine(context.Background(), e.digest(t, a))
require.NoError(t, err)
require.NotNil(t, m)
}
func TestReleaseMachineReclaimsAnEmptyMachine(t *testing.T) {
enableUserMode(t)
a := uuid.NewString()
e := newEnv(t, fakeConfigs{"cfg-a": "user"}, webSession(a))
e.place(t, a, "cfg-a")
ops := &reclaimRecorder{}
c := NewWorkspaceCleaner(e.svc, fakeResolver{mgr: ops})
require.NoError(t, c.ReleaseOwnerAssignments(context.Background(), "u-1"))
machines, err := c.OwnerMachines(context.Background(), 0, "u-1")
require.NoError(t, err)
require.Len(t, machines, 1)
ok, err := c.ReleaseMachine(context.Background(), machines[0])
require.NoError(t, err)
require.True(t, ok)
require.Equal(t, 1, ops.reclaims)
m, err := e.svc.repo.GetUserMachine(context.Background(), e.digest(t, a))
require.NoError(t, err)
require.Nil(t, m, "an empty machine's registry row goes with it")
}
// busyReclaimer is what ReclaimUserMachine returns when work is still
// registered: false, and it never destroys. ReleaseMachine must not add a
// second path that deletes the machine anyway.
type busyReclaimer struct{ fakeMachineOps }
func (busyReclaimer) ReclaimUserMachine(
context.Context, allocation.UserMachine, func(context.Context) (bool, error),
) (bool, error) {
return false, nil
}
func TestReleaseMachineLeavesTheRowWhenTheManagerRefuses(t *testing.T) {
enableUserMode(t)
a := uuid.NewString()
e := newEnv(t, fakeConfigs{"cfg-a": "user"}, webSession(a))
e.place(t, a, "cfg-a")
c := NewWorkspaceCleaner(e.svc, fakeResolver{mgr: &busyReclaimer{}})
require.NoError(t, c.ReleaseOwnerAssignments(context.Background(), "u-1"))
machines, err := c.OwnerMachines(context.Background(), 0, "u-1")
require.NoError(t, err)
ok, err := c.ReleaseMachine(context.Background(), machines[0])
require.NoError(t, err)
require.False(t, ok)
m, err := e.svc.repo.GetUserMachine(context.Background(), e.digest(t, a))
require.NoError(t, err)
require.NotNil(t, m)
}
@@ -0,0 +1,40 @@
package sandboxalloc
import (
"academy/internal/sandbox/allocation"
"academy/internal/types"
)
// ToEntity converts an assignment into its row, and for a user-mode one the
// registry row of its machine (nil otherwise). digest names that machine.
func ToEntity(a allocation.Assignment, digest string) (*types.SessionSandboxAssignment, *types.SandboxUserMachine) {
row := &types.SessionSandboxAssignment{
SessionID: a.SessionID, ConfigTenantID: a.ConfigTenantID, ConfigID: a.ConfigID,
ReleasedAt: a.ReleasedAt,
}
m, ok := a.UserMachine()
if !ok {
return row, nil
}
row.MachineDigest = digest
return row, &types.SandboxUserMachine{
MachineDigest: digest, OwnerTenantID: m.OwnerTenantID, OwnerID: m.OwnerID,
ConfigTenantID: m.ConfigTenantID, ConfigID: m.ConfigID,
}
}
// FromEntity converts a row back. machine is the registry row its digest
// names; it is required for a user-mode row and ignored otherwise.
func FromEntity(e *types.SessionSandboxAssignment, machine *types.SandboxUserMachine) allocation.Assignment {
a := allocation.Assignment{
SessionID: e.SessionID, ConfigTenantID: e.ConfigTenantID, ConfigID: e.ConfigID,
ReleasedAt: e.ReleasedAt,
}
if e.MachineDigest != "" && machine != nil {
a.Machine = allocation.UserMachine{
OwnerTenantID: machine.OwnerTenantID, OwnerID: machine.OwnerID,
ConfigTenantID: machine.ConfigTenantID, ConfigID: machine.ConfigID,
}
}
return a
}
@@ -0,0 +1,269 @@
package sandboxalloc
import (
"context"
"encoding/json"
"fmt"
"time"
"github.com/redis/go-redis/v9"
"academy/internal/common/redislock"
"academy/internal/logger"
"academy/internal/sandbox/allocation"
"academy/internal/types"
"academy/internal/types/interfaces"
)
const (
// UserMachineGCLockKey makes one replica scan at a time.
UserMachineGCLockKey = "academy:sandbox:user-gc:lock"
// UserMachineGCInterval is how often the container runs the scan.
UserMachineGCInterval = time.Hour
// UserMachineGCCursorKey remembers where a scan stopped, so the next one
// continues instead of rereading the same oldest candidates.
UserMachineGCCursorKey = "academy:sandbox:user-gc:cursor"
gcLockLease = 5 * time.Minute
gcBatch = 200
gcMaxPerRun = 2000
)
// GCReport is one scan's outcome, logged as metrics.
type GCReport struct {
Scanned, Reclaimed, Busy, Failed int
CleanupsDone, CleanupsFailed int
Skipped bool
}
// UserMachineGC reclaims user machines that have had no live session for
// their config's retention window, and retries queued directory deletes.
type UserMachineGC struct {
svc *Service
cleaner *WorkspaceCleaner
configs ConfigReader
redis redis.UniversalClient
now func() time.Time
batch int // page size; tests shrink it
maxRun int
cursor interfaces.EmptyMachineCursor // used when there is no Redis
}
// NewUserMachineGC wires the GC. A nil redis client runs unlocked, which is
// only correct for a single process (user mode is never enabled without Redis).
func NewUserMachineGC(
svc *Service, cleaner *WorkspaceCleaner, configs ConfigReader, client redis.UniversalClient,
) *UserMachineGC {
return &UserMachineGC{
svc: svc, cleaner: cleaner, configs: configs, redis: client,
now: func() time.Time { return time.Now().UTC() }, batch: gcBatch, maxRun: gcMaxPerRun,
}
}
// RunOnce performs one scan unless another replica holds the lock. The lock
// is renewed for the scan's duration; a lost lock ends the scan.
func (g *UserMachineGC) RunOnce(ctx context.Context) (GCReport, error) {
if g.redis == nil {
return g.scan(ctx)
}
token, err := redislock.NewToken()
if err != nil {
return GCReport{}, err
}
ok, err := redislock.TryAcquire(ctx, g.redis, UserMachineGCLockKey, token, gcLockLease)
if err != nil {
return GCReport{}, err
}
if !ok {
return GCReport{Skipped: true}, nil
}
scanCtx, cancel := context.WithCancel(ctx)
defer cancel()
go func() {
t := time.NewTicker(gcLockLease / 3)
defer t.Stop()
for {
select {
case <-scanCtx.Done():
return
case <-t.C:
renewed, err := redislock.Renew(scanCtx, g.redis, UserMachineGCLockKey, token, gcLockLease)
if err != nil || !renewed {
cancel()
return
}
}
}
}()
defer func() {
relCtx, relCancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
defer relCancel()
_, _ = redislock.Release(relCtx, g.redis, UserMachineGCLockKey, token)
}()
return g.scan(scanCtx)
}
func (g *UserMachineGC) scan(ctx context.Context) (GCReport, error) {
var report GCReport
report.CleanupsDone, report.CleanupsFailed, _ = g.cleaner.RetryDue(ctx, gcBatch)
// Candidates only: the shortest window is one day, and every row is
// re-evaluated inside its machine's lock. Pages advance past every
// candidate, due or not, so none can hide the ones behind it.
cursor := g.loadCursor(ctx)
emptyBefore := g.now().Add(-24 * time.Hour)
for report.Scanned < g.maxRun {
rows, err := g.svc.repo.ListEmptyUserMachines(ctx, emptyBefore, cursor, g.batch)
if err != nil {
return report, err
}
if len(rows) == 0 {
cursor = interfaces.EmptyMachineCursor{} // reached the end: next run starts over
break
}
for _, row := range rows {
if ctx.Err() != nil {
g.saveCursor(ctx, cursor)
return report, ctx.Err()
}
if report.Scanned >= g.maxRun {
break
}
cursor = interfaces.EmptyMachineCursor{EmptySince: *row.EmptySince, Digest: row.MachineDigest}
g.reclaimCandidate(ctx, row, &report)
}
}
g.saveCursor(ctx, cursor)
logger.Infof(ctx, "[sandbox-gc] scanned=%d reclaimed=%d busy=%d failed=%d cleanups_done=%d cleanups_failed=%d",
report.Scanned, report.Reclaimed, report.Busy, report.Failed, report.CleanupsDone, report.CleanupsFailed)
return report, nil
}
func (g *UserMachineGC) reclaimCandidate(ctx context.Context, row *types.SandboxUserMachine, report *GCReport) {
report.Scanned++
m := machineOf(row)
digest := row.MachineDigest
ops, err := g.cleaner.reclaimOps(ctx, m)
if err != nil {
report.Failed++
logger.Warnf(ctx, "[sandbox-gc] resolve config %d/%s for machine %s: %v",
row.ConfigTenantID, row.ConfigID, digestPrefix(digest), err)
return
}
// Retention comes from the config table. Read it before the machine row
// lock: SQLite serves the whole process on one connection, so a config
// query while that transaction is open never returns. empty_since is
// still the value read under the lock, below.
days, err := g.retentionDays(ctx, row.ConfigTenantID, row.ConfigID)
if err != nil {
report.Failed++
logger.Warnf(ctx, "[sandbox-gc] retention for machine %s: %v", digestPrefix(digest), err)
return
}
var lock interfaces.MachineReclaimLock
ok, err := ops.ReclaimUserMachine(ctx, m, func(_ context.Context) (bool, error) {
var lockErr error
// The manager cancels its provider context before returning. The row
// lock must instead live until this scan commits or aborts the delete.
lock, lockErr = g.svc.repo.LockEmptyMachine(ctx, digest)
if lockErr != nil || lock == nil {
return false, lockErr
}
due := !g.now().Before(lock.Claim().EmptySince.Add(time.Duration(days) * 24 * time.Hour))
if !due {
lock.Abort()
lock = nil
return false, nil
}
return true, nil
})
if lock != nil {
defer lock.Abort()
}
switch {
case err != nil:
report.Failed++
logger.Warnf(ctx, "[sandbox-gc] reclaim machine %s: %v", digestPrefix(digest), err)
case !ok:
report.Busy++
case lock == nil:
// The manager reported the machine reclaimable without ever running
// the check that takes its row lock; nothing was provably deleted,
// so the registry row stays for the next scan.
report.Failed++
logger.Warnf(ctx, "[sandbox-gc] reclaim machine %s: manager skipped the reclaim check",
digestPrefix(digest))
default:
deleted, delErr := lock.CommitDelete()
if delErr != nil {
report.Failed++
logger.Warnf(ctx, "[sandbox-gc] drop registry row %s: %v", digestPrefix(digest), delErr)
return
}
if !deleted {
report.Busy++
return
}
report.Reclaimed++
}
}
type gcCursorJSON struct {
EmptySince time.Time `json:"empty_since"`
Digest string `json:"digest"`
}
func (g *UserMachineGC) loadCursor(ctx context.Context) interfaces.EmptyMachineCursor {
if g.redis == nil {
return g.cursor
}
raw, err := g.redis.Get(ctx, UserMachineGCCursorKey).Bytes()
if err != nil {
return interfaces.EmptyMachineCursor{}
}
var c gcCursorJSON
if json.Unmarshal(raw, &c) != nil {
return interfaces.EmptyMachineCursor{}
}
return interfaces.EmptyMachineCursor{EmptySince: c.EmptySince, Digest: c.Digest}
}
// saveCursor stores where this run stopped. A lost write only means the
// next run starts over; the scan stays correct, just slower.
func (g *UserMachineGC) saveCursor(ctx context.Context, c interfaces.EmptyMachineCursor) {
if g.redis == nil {
g.cursor = c
return
}
if c.EmptySince.IsZero() {
_ = g.redis.Del(context.WithoutCancel(ctx), UserMachineGCCursorKey).Err()
return
}
raw, _ := json.Marshal(gcCursorJSON{EmptySince: c.EmptySince, Digest: c.Digest})
_ = g.redis.Set(context.WithoutCancel(ctx), UserMachineGCCursorKey, raw, 2*UserMachineGCInterval).Err()
}
// retentionDays is the config's current empty-machine window, read before
// the row lock is taken.
func (g *UserMachineGC) retentionDays(ctx context.Context, tenantID uint64, configID string) (int, error) {
days := allocation.DefaultEmptyRetentionDays
if g.configs == nil {
return days, nil
}
entity, err := g.configs.GetByID(ctx, tenantID, configID)
if err != nil {
return 0, err
}
// GetByID returns (nil, nil) for a soft-deleted config. That is not
// the default window: config deletion reclaims the machine itself.
if entity == nil || entity.Config == nil {
return 0, fmt.Errorf("sandboxalloc: sandbox config %d/%s not found", tenantID, configID)
}
return allocation.EffectiveRetentionDays(entity.Config.UserSandboxEmptyRetentionDays), nil
}
func digestPrefix(digest string) string {
if len(digest) > 12 {
return digest[:12]
}
return digest
}
@@ -0,0 +1,232 @@
package sandboxalloc
import (
"context"
"fmt"
"testing"
"time"
"github.com/alicebob/miniredis/v2"
"github.com/google/uuid"
"github.com/redis/go-redis/v9"
"github.com/stretchr/testify/require"
"academy/internal/sandbox/allocation"
"academy/internal/types"
"academy/internal/types/interfaces"
)
// perConfigRetention answers each config's retention from a map.
type perConfigRetention map[string]int
func (p perConfigRetention) GetByID(
_ context.Context, tenantID uint64, id string,
) (*types.TenantSandboxConfigEntity, error) {
return &types.TenantSandboxConfigEntity{ID: id, TenantID: tenantID, Config: &types.TenantSandboxConfig{
AllocationMode: "user", UserSandboxEmptyRetentionDays: p[id],
}}, nil
}
type retentionConfigs struct{ days *int }
func (r retentionConfigs) GetByID(
_ context.Context, tenantID uint64, id string,
) (*types.TenantSandboxConfigEntity, error) {
days := 0
if r.days != nil {
days = *r.days
}
return &types.TenantSandboxConfigEntity{ID: id, TenantID: tenantID, Config: &types.TenantSandboxConfig{
AllocationMode: "user", UserSandboxEmptyRetentionDays: days,
}}, nil
}
// reclaimRecorder runs beforeCheck/afterCheck around the check the GC hands
// to the manager, standing in for things that happen while the lock is held.
type reclaimRecorder struct {
fakeMachineOps
beforeCheck, afterCheck func()
reclaims int
}
func (r *reclaimRecorder) ReclaimUserMachine(
ctx context.Context, _ allocation.UserMachine, check func(context.Context) (bool, error),
) (bool, error) {
if r.beforeCheck != nil {
r.beforeCheck()
}
ok, err := check(ctx)
if err != nil || !ok {
return false, err
}
if r.afterCheck != nil {
r.afterCheck()
}
r.reclaims++
return true, nil
}
func releasedMachine(t *testing.T) (*testEnv, string) {
t.Helper()
enableUserMode(t)
a := uuid.NewString()
e := newEnv(t, fakeConfigs{"cfg-a": "user"}, webSession(a))
e.place(t, a, "cfg-a")
_, err := e.svc.Release(context.Background(), a)
require.NoError(t, err)
return e, a
}
func TestGCReclaimsOnlyAfterRetention(t *testing.T) {
seven := 7
e, _ := releasedMachine(t)
ops := &reclaimRecorder{}
gc := NewUserMachineGC(e.svc, NewWorkspaceCleaner(e.svc, fakeResolver{mgr: ops}),
retentionConfigs{days: &seven}, nil)
gc.now = func() time.Time { return time.Now().UTC().Add(6 * 24 * time.Hour) }
report, err := gc.RunOnce(context.Background())
require.NoError(t, err)
require.Zero(t, report.Reclaimed)
gc.now = func() time.Time { return time.Now().UTC().Add(8 * 24 * time.Hour) }
report, err = gc.RunOnce(context.Background())
require.NoError(t, err)
require.Equal(t, 1, report.Reclaimed)
rows, _ := e.svc.repo.ListEmptyUserMachines(context.Background(),
time.Now().UTC().Add(30*24*time.Hour), interfaces.EmptyMachineCursor{}, 10)
require.Empty(t, rows, "the registry row goes with the machine")
}
func TestGCRecomputesInsideTheLock(t *testing.T) {
one := 1
e, _ := releasedMachine(t)
b := uuid.NewString()
e.addSession(t, webSession(b))
ops := &reclaimRecorder{beforeCheck: func() {
// Joined and left between the scan and the lock: empty_since moved.
e.svc.now = func() time.Time { return time.Now().UTC().Add(48 * time.Hour) }
e.place(t, b, "cfg-a")
_, err := e.svc.Release(context.Background(), b)
require.NoError(t, err)
}}
gc := NewUserMachineGC(e.svc, NewWorkspaceCleaner(e.svc, fakeResolver{mgr: ops}), retentionConfigs{days: &one}, nil)
gc.now = func() time.Time { return time.Now().UTC().Add(48 * time.Hour) }
report, err := gc.RunOnce(context.Background())
require.NoError(t, err)
require.Zero(t, ops.reclaims)
require.Equal(t, 1, report.Busy)
}
func TestGCKeepsTheRowWhenASessionJoinsBeforeTheLockedCheck(t *testing.T) {
one := 1
e, _ := releasedMachine(t)
b := uuid.NewString()
e.addSession(t, webSession(b))
ops := &reclaimRecorder{beforeCheck: func() {
// Joining clears empty_since. The locked check must see that and
// not destroy the machine this session now owns.
e.place(t, b, "cfg-a")
}}
gc := NewUserMachineGC(e.svc, NewWorkspaceCleaner(e.svc, fakeResolver{mgr: ops}), retentionConfigs{days: &one}, nil)
gc.now = func() time.Time { return time.Now().UTC().Add(48 * time.Hour) }
_, err := gc.RunOnce(context.Background())
require.NoError(t, err)
require.Zero(t, ops.reclaims, "a joined machine is not destroyed")
m, err := e.svc.repo.GetUserMachine(context.Background(), e.digest(t, b))
require.NoError(t, err)
require.NotNil(t, m, "B lives on this owner+config; its registry row must survive")
require.Nil(t, m.EmptySince)
}
func TestGCReadsRetentionFreshEachRun(t *testing.T) {
days := 30
e, _ := releasedMachine(t)
ops := &reclaimRecorder{}
gc := NewUserMachineGC(e.svc, NewWorkspaceCleaner(e.svc, fakeResolver{mgr: ops}),
retentionConfigs{days: &days}, nil)
gc.now = func() time.Time { return time.Now().UTC().Add(48 * time.Hour) }
_, _ = gc.RunOnce(context.Background())
require.Zero(t, ops.reclaims)
days = 1 // admin shortened the window
_, _ = gc.RunOnce(context.Background())
require.Equal(t, 1, ops.reclaims)
}
func TestGCIsNotStarvedByOldCandidatesThatAreNotDue(t *testing.T) {
enableUserMode(t)
// Two old machines on a 30-day config, one newer machine on a 1-day config.
thirty, one := uuid.NewString(), uuid.NewString()
old1, old2, due := uuid.NewString(), uuid.NewString(), uuid.NewString()
sess := func(id, owner string) *types.Session {
s := webSession(id)
s.UserID = owner
return s
}
e := newEnv(t, fakeConfigs{thirty: "user", one: "user"}, sess(old1, "u-1"), sess(old2, "u-2"), sess(due, "u-3"))
for _, id := range []string{old1, old2} {
e.place(t, id, thirty)
}
e.place(t, due, one)
for _, id := range []string{old1, old2, due} {
_, err := e.svc.Release(context.Background(), id)
require.NoError(t, err)
}
ops := &reclaimRecorder{}
days := map[string]int{thirty: 30, one: 1}
gc := NewUserMachineGC(e.svc, NewWorkspaceCleaner(e.svc, fakeResolver{mgr: ops}), perConfigRetention(days), nil)
gc.batch = 1 // one candidate per page: the two not-due ones come first
gc.now = func() time.Time { return time.Now().UTC().Add(48 * time.Hour) }
report, err := gc.RunOnce(context.Background())
require.NoError(t, err)
require.Equal(t, 3, report.Scanned)
require.Equal(t, 1, report.Reclaimed, "the due machine behind them is still reached")
}
func TestGCResumesFromItsCursorWhenARunIsCapped(t *testing.T) {
enableUserMode(t)
ids := []string{uuid.NewString(), uuid.NewString(), uuid.NewString()}
var rows []*types.Session
for i, id := range ids {
s := webSession(id)
s.UserID = fmt.Sprintf("u-%d", i)
rows = append(rows, s)
}
e := newEnv(t, fakeConfigs{"cfg-a": "user"}, rows...)
for _, id := range ids {
e.place(t, id, "cfg-a")
_, err := e.svc.Release(context.Background(), id)
require.NoError(t, err)
}
ops := &reclaimRecorder{}
thirty := 30
gc := NewUserMachineGC(e.svc, NewWorkspaceCleaner(e.svc, fakeResolver{mgr: ops}),
retentionConfigs{days: &thirty}, nil)
gc.batch, gc.maxRun = 1, 2
gc.now = func() time.Time { return time.Now().UTC().Add(48 * time.Hour) }
first, err := gc.RunOnce(context.Background())
require.NoError(t, err)
require.Equal(t, 2, first.Scanned)
second, err := gc.RunOnce(context.Background())
require.NoError(t, err)
require.Equal(t, 1, second.Scanned, "the second run continues where the first stopped")
third, err := gc.RunOnce(context.Background())
require.NoError(t, err)
require.Equal(t, 2, third.Scanned, "after the end the scan starts over")
}
func TestGCRunsOnOneReplicaAtATime(t *testing.T) {
mini := miniredis.RunT(t)
client := redis.NewClient(&redis.Options{Addr: mini.Addr()})
e := newEnv(t, fakeConfigs{})
gc := NewUserMachineGC(e.svc, NewWorkspaceCleaner(e.svc, fakeResolver{}), retentionConfigs{}, client)
require.NoError(t, mini.Set(UserMachineGCLockKey, "someone-else"))
report, err := gc.RunOnce(context.Background())
require.NoError(t, err)
require.True(t, report.Skipped)
}
@@ -0,0 +1,219 @@
package sandboxalloc
import (
"context"
"fmt"
"os"
"strings"
"sync"
"testing"
"time"
"github.com/google/uuid"
"github.com/redis/go-redis/v9"
"github.com/stretchr/testify/require"
"gorm.io/driver/postgres"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"academy/internal/application/repository"
"academy/internal/sandbox/allocation"
"academy/internal/types"
)
// integrationEnv returns an integration dependency's address. Missing, the
// test is skipped — unless ACADEMY_REQUIRE_INTEGRATION=1, which turns the
// skip into a failure so an enablement run cannot pass by skipping.
func integrationEnv(t *testing.T, name string) string {
t.Helper()
v := strings.TrimSpace(os.Getenv(name))
if v != "" {
return v
}
if os.Getenv("ACADEMY_REQUIRE_INTEGRATION") == "1" {
t.Fatalf("%s is required when ACADEMY_REQUIRE_INTEGRATION=1", name)
}
t.Skipf("set %s to run against a real dependency", name)
return ""
}
// gatingReclaim blocks inside ReclaimUserMachine until release is closed, so
// the replica that won the GC lock is still holding it when the other runs.
type gatingReclaim struct {
reclaimRecorder
entered chan struct{}
release chan struct{}
once sync.Once
}
func (g *gatingReclaim) ReclaimUserMachine(
ctx context.Context, m allocation.UserMachine, check func(context.Context) (bool, error),
) (bool, error) {
g.once.Do(func() { close(g.entered) })
select {
case <-g.release:
case <-ctx.Done():
return false, ctx.Err()
}
return g.reclaimRecorder.ReclaimUserMachine(ctx, m, check)
}
func TestMultiReplicaRealRedisGCRunsOnOneReplica(t *testing.T) {
addr := integrationEnv(t, "ACADEMY_TEST_REDIS_ADDR")
raw := redis.NewClient(&redis.Options{Addr: addr})
t.Cleanup(func() { _ = raw.Close() })
ctx := context.Background()
require.NoError(t, raw.Del(ctx, UserMachineGCLockKey, UserMachineGCCursorKey).Err())
t.Cleanup(func() {
c, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
_ = raw.Del(c, UserMachineGCLockKey, UserMachineGCCursorKey).Err()
})
one := 1
e, _ := releasedMachine(t)
ops := &gatingReclaim{entered: make(chan struct{}), release: make(chan struct{})}
cleaner := NewWorkspaceCleaner(e.svc, fakeResolver{mgr: ops})
configs := retentionConfigs{days: &one}
open := func() *redis.Client {
rc := redis.NewClient(&redis.Options{Addr: addr})
t.Cleanup(func() { _ = rc.Close() })
return rc
}
gc1 := NewUserMachineGC(e.svc, cleaner, configs, open())
gc2 := NewUserMachineGC(e.svc, cleaner, configs, open())
later := time.Now().UTC().Add(8 * 24 * time.Hour)
gc1.now = func() time.Time { return later }
gc2.now = func() time.Time { return later }
runCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
type outcome struct {
report GCReport
err error
}
ch := make(chan outcome, 2)
go func() {
report, err := gc1.RunOnce(runCtx)
ch <- outcome{report, err}
}()
go func() {
report, err := gc2.RunOnce(runCtx)
ch <- outcome{report, err}
}()
select {
case <-ops.entered:
case <-time.After(15 * time.Second):
t.Fatal("neither replica entered reclaim")
}
var skipped, winner outcome
select {
case skipped = <-ch:
case <-time.After(15 * time.Second):
t.Fatal("the replica that lost the lock did not return")
}
require.NoError(t, skipped.err)
require.True(t, skipped.report.Skipped, "one replica must observe the other's lock and skip")
close(ops.release)
select {
case winner = <-ch:
case <-time.After(15 * time.Second):
t.Fatal("the replica that held the lock did not finish")
}
require.NoError(t, winner.err)
require.False(t, winner.report.Skipped)
require.Equal(t, 1, winner.report.Reclaimed)
}
// placementDatabase is Postgres when ACADEMY_REPOSITORY_TEST_POSTGRES_DSN is
// set, and the shared-cache sqlite pool otherwise. The sqlite path is still a
// regression test; only ACADEMY_REQUIRE_INTEGRATION=1 demands Postgres.
func placementDatabase(t *testing.T) *gorm.DB {
t.Helper()
dsn := strings.TrimSpace(os.Getenv("ACADEMY_REPOSITORY_TEST_POSTGRES_DSN"))
if dsn == "" {
if os.Getenv("ACADEMY_REQUIRE_INTEGRATION") == "1" {
t.Fatal("ACADEMY_REPOSITORY_TEST_POSTGRES_DSN is required when ACADEMY_REQUIRE_INTEGRATION=1")
}
dsn = fmt.Sprintf("file:%s?mode=memory&cache=shared&_busy_timeout=5000", uuid.NewString())
db, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
require.NoError(t, err)
sqlDB, err := db.DB()
require.NoError(t, err)
sqlDB.SetMaxOpenConns(1)
require.NoError(t, db.AutoMigrate(
&types.Session{}, &types.SessionSandboxAssignment{}, &types.SandboxUserMachine{}, &types.Message{},
))
return db
}
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
require.NoError(t, err)
sqlDB, err := db.DB()
require.NoError(t, err)
t.Cleanup(func() { _ = sqlDB.Close() })
require.NoError(t, db.AutoMigrate(
&types.Session{}, &types.SessionSandboxAssignment{}, &types.SandboxUserMachine{}, &types.Message{},
))
return db
}
func TestMultiReplicaPlacementAgreesAcrossServices(t *testing.T) {
enableUserMode(t)
db := placementDatabase(t)
id := uuid.NewString()
require.NoError(t, db.Session(&gorm.Session{SkipHooks: true}).Create(webSession(id)).Error)
configs := fakeConfigs{"cfg-a": "user"}
repo := repository.NewSandboxAllocationRepository(db)
sessions := repository.NewSessionRepository(db)
s1 := New(repo, configs, sessions, "academy")
s2 := New(repo, configs, sessions, "academy")
services := []*Service{s1, s2}
type placed struct {
mode allocation.Mode
config string
tenant uint64
digest string
}
var wg sync.WaitGroup
results := make(chan placed, 16)
for i := 0; i < 16; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
a, err := services[i%2].Place(context.Background(), PlaceRequest{
SessionTenantID: 7, SessionID: id, ConfigTenantID: 7, ConfigID: "cfg-a",
})
require.NoError(t, err)
digest := ""
if m, ok := a.UserMachine(); ok {
digest = m.Digest(services[i%2].Namespace())
}
results <- placed{mode: a.Mode(), config: a.ConfigID, tenant: a.ConfigTenantID, digest: digest}
}(i)
}
wg.Wait()
close(results)
var first placed
n := 0
for got := range results {
if n == 0 {
first = got
}
require.Equal(t, first, got, "both services tell every caller the same placement")
n++
}
require.Equal(t, 16, n)
require.Equal(t, allocation.ModeUser, first.mode)
require.NotEmpty(t, first.digest)
var sess types.Session
require.NoError(t, db.Session(&gorm.Session{SkipHooks: true}).Where("id = ?", id).Take(&sess).Error)
require.Equal(t, first.config, sess.SandboxConfigID, "the pin is the agreed config")
require.Equal(t, first.tenant, sess.SandboxConfigTenantID)
}
@@ -0,0 +1,42 @@
package sandboxalloc
import (
"strings"
"academy/internal/sandbox/allocation"
"academy/internal/types"
)
// ownerFromSession maps the session's persisted owner onto allocation.Owner.
// Only the authentication source is stored; the kind follows from it, and is
// cross-checked against the owner id's shape so a row whose source disagrees
// with its owner can never look like a verified person.
func ownerFromSession(s *types.Session) allocation.Owner {
src := allocation.AuthSource(strings.TrimSpace(s.OwnerAuthSource))
if src == "" {
src = allocation.SourceUnknown
}
o := allocation.Owner{TenantID: s.TenantID, ID: s.UserID, Kind: allocation.KindUnknown, Source: src}
id := strings.TrimSpace(s.UserID)
switch src {
case allocation.SourceWeb:
if id != "" && !strings.Contains(id, ":") {
o.Kind = allocation.KindWebUser
}
case allocation.SourceAPIDirectHeader, allocation.SourceAPISignedToken:
if strings.HasPrefix(id, types.SessionOwnerAPIExternalUserPrefix) {
o.Kind = allocation.KindAPIExternalUser
}
case allocation.SourceAPITenantKey:
o.Kind = allocation.KindAPITenantKey
case allocation.SourceAPIPlatformKey:
o.Kind = allocation.KindAPIPlatformKey
case allocation.SourceMCPEndpoint:
o.Kind = allocation.KindMCPEndpoint
case allocation.SourceEmbed:
o.Kind = allocation.KindEmbed
case allocation.SourceIM:
o.Kind = allocation.KindIM
}
return o
}
@@ -0,0 +1,375 @@
// Package sandboxalloc decides and records how sessions are placed on remote
// sandboxes. It is the only writer of session_sandbox_assignments and, once
// wired, of the session's sandbox pin.
package sandboxalloc
import (
"context"
"errors"
"fmt"
"strings"
"time"
apperrors "academy/internal/errors"
"academy/internal/logger"
"academy/internal/sandbox"
"academy/internal/sandbox/allocation"
"academy/internal/types"
"academy/internal/types/interfaces"
"gorm.io/gorm"
)
// ConfigReader loads a sandbox config by its owning workspace.
type ConfigReader interface {
GetByID(ctx context.Context, tenantID uint64, id string) (*types.TenantSandboxConfigEntity, error)
}
// SessionReader loads a session row.
type SessionReader interface {
GetByID(ctx context.Context, tenantID uint64, id string) (*types.Session, error)
}
// Service is the allocation service.
type Service struct {
repo interfaces.SandboxAllocationRepository
configs ConfigReader
sessions SessionReader
namespace string
now func() time.Time
}
// ErrMachineUnregistered is returned when a user-mode assignment names a
// machine whose registry row is gone (its config was deleted). The session
// cannot run, and must never be mistaken for one with a machine of its own.
var ErrMachineUnregistered = errors.New("sandboxalloc: shared machine is not registered")
// New wires the service. namespace must be the Redis binding namespace.
func New(
repo interfaces.SandboxAllocationRepository, configs ConfigReader,
sessions SessionReader, namespace string,
) *Service {
return &Service{
repo: repo, configs: configs, sessions: sessions, namespace: namespace,
now: func() time.Time { return time.Now().UTC().Truncate(time.Microsecond) },
}
}
// Namespace is the deployment namespace machine digests use.
func (s *Service) Namespace() string { return s.namespace }
// Digest is the shared-machine digest of m in this deployment.
func (s *Service) Digest(m allocation.UserMachine) string { return m.Digest(s.namespace) }
// Repo is the allocation repository.
func (s *Service) Repo() interfaces.SandboxAllocationRepository { return s.repo }
// Now is the clock placements and releases use.
func (s *Service) Now() time.Time { return s.now() }
// PlaceRequest names the session and the config address the caller resolved
// as its candidate.
type PlaceRequest struct {
SessionTenantID uint64
SessionID string
ConfigTenantID uint64
ConfigID string
Purpose allocation.Purpose
}
const placeAttempts = 3
// Place returns the session's placement, recording it on first use together
// with the session's pin. The stored row always wins: neither the config
// switch, the candidate, nor the request identity can move a placed session.
func (s *Service) Place(ctx context.Context, req PlaceRequest) (allocation.Assignment, error) {
a, _, err := s.place(ctx, req)
return a, err
}
// place is Place that also reports why a placement it recorded differs from
// the config's mode. The reason is logged, not stored.
func (s *Service) place(
ctx context.Context, req PlaceRequest,
) (allocation.Assignment, allocation.FallbackReason, error) {
for attempt := 0; attempt < placeAttempts; attempt++ {
existing, ok, err := s.Lookup(ctx, req.SessionID)
if err != nil {
return allocation.Assignment{}, "", err
}
if ok && existing.Released() {
// Lookup keeps released rows for cleanup and inventory; nothing
// may run on them again.
return allocation.Assignment{}, "", fmt.Errorf("sandboxalloc: session %s is being deleted: %w",
req.SessionID, sandbox.ErrSandboxSessionDeleted)
}
if ok {
return existing, allocation.ReasonNone, nil
}
sess, err := s.sessions.GetByID(ctx, req.SessionTenantID, req.SessionID)
if err != nil {
return allocation.Assignment{}, "", fmt.Errorf("sandboxalloc: load session %s: %w", req.SessionID, err)
}
if sess == nil {
return allocation.Assignment{}, "", fmt.Errorf("sandboxalloc: session %s not found", req.SessionID)
}
pin := interfaces.PlacementPin{ConfigID: sess.SandboxConfigID, TenantID: sess.SandboxConfigTenantID}
a, reason, err := s.decide(ctx, req, sess, pin)
if err != nil {
return allocation.Assignment{}, "", err
}
row, machine := ToEntity(a, s.digestOf(a))
winner, err := s.repo.ClaimPlacement(ctx, row, machine, pin)
if errors.Is(err, interfaces.ErrPlacementConflict) {
continue
}
if errors.Is(err, interfaces.ErrSessionRetired) {
return allocation.Assignment{}, "", fmt.Errorf("sandboxalloc: session %s is being deleted: %w",
req.SessionID, sandbox.ErrSandboxSessionDeleted)
}
if err != nil {
return allocation.Assignment{}, "", fmt.Errorf("sandboxalloc: record placement: %w", err)
}
if winner.ConfigTenantID != row.ConfigTenantID || winner.ConfigID != row.ConfigID ||
winner.MachineDigest != row.MachineDigest || winner.ReleasedAt != nil {
// Someone else placed the session first; their row is the answer.
got, _, err := s.Lookup(ctx, req.SessionID)
return got, allocation.ReasonNone, err
}
logger.Infof(ctx, "[sandbox-alloc] session=%s mode=%s reason=%s config=%d/%s",
a.SessionID, a.Mode(), reason, a.ConfigTenantID, a.ConfigID)
return a, reason, nil
}
return allocation.Assignment{}, "", fmt.Errorf("sandboxalloc: placement of %s kept conflicting", req.SessionID)
}
// digestOf names a's shared machine, or "" for a machine of its own.
func (s *Service) digestOf(a allocation.Assignment) string {
m, ok := a.UserMachine()
if !ok {
return ""
}
return s.Digest(m)
}
// decide picks the mode and config for a session without a placement. A
// session that already used a per-session sandbox — it has a pin, an
// unopened snapshot fork, or a checkpoint — stays per-session on that config.
func (s *Service) decide(
ctx context.Context, req PlaceRequest, sess *types.Session, pin interfaces.PlacementPin,
) (allocation.Assignment, allocation.FallbackReason, error) {
purpose := req.Purpose
if purpose == "" {
purpose = allocation.PurposeChat
}
if types.IsSkillMaintenanceDescription(sess.Description) {
purpose = allocation.PurposeMaintenance
}
configID, configTenant := req.ConfigID, req.ConfigTenantID
if pin.ConfigID != "" {
configID = pin.ConfigID
if pin.TenantID != 0 {
configTenant = pin.TenantID
} else if req.ConfigID != pin.ConfigID {
configTenant = 0
}
}
if configTenant == 0 {
configTenant = sess.TenantID
}
configID = sandbox.NormalizeConfigID(configID)
owner := ownerFromSession(sess)
legacy := pin.ConfigID != "" || (sess.ForkBootstrap != nil && !sess.ForkBootstrap.Consumed())
if !legacy {
has, err := s.repo.HasSandboxCheckpoint(ctx, sess.ID)
if err != nil {
return allocation.Assignment{}, "", fmt.Errorf("sandboxalloc: check history of %s: %w", sess.ID, err)
}
legacy = has
}
decision := allocation.Decision{Mode: allocation.ModeSession, Reason: allocation.ReasonLegacySessionSandbox}
if !legacy {
mode, err := s.configMode(ctx, configTenant, configID)
if err != nil {
return allocation.Assignment{}, "", err
}
decision = allocation.Decide(allocation.DecideInput{
ConfigMode: mode,
Purpose: purpose,
Owner: owner,
SessionID: sess.ID,
UserModeAvailable: allocation.UserModeAvailable(),
})
}
a := allocation.Assignment{SessionID: sess.ID, ConfigTenantID: configTenant, ConfigID: configID}
if decision.Mode != allocation.ModeUser {
return a, decision.Reason, nil
}
a.Machine = allocation.UserMachine{
OwnerTenantID: sess.TenantID, OwnerID: sess.UserID,
ConfigTenantID: configTenant, ConfigID: configID,
}
if err := a.Machine.Validate(); err != nil {
return allocation.Assignment{}, "", fmt.Errorf("sandboxalloc: %w", err)
}
return a, decision.Reason, nil
}
// configMode reads the config's switch. A missing row or an unparsable value
// is session: a failure to load must never widen sharing. A transport error
// is not a decision — the caller retries instead of storing session mode.
func (s *Service) configMode(ctx context.Context, tenantID uint64, configID string) (allocation.Mode, error) {
if s.configs == nil || configID == "" || configID == types.SandboxConfigIDGlobalDefault {
return allocation.ModeSession, nil
}
entity, err := s.configs.GetByID(ctx, tenantID, configID)
if err != nil {
return "", fmt.Errorf("sandboxalloc: read config %d/%s: %w", tenantID, configID, err)
}
if entity == nil || entity.Config == nil {
return allocation.ModeSession, nil
}
mode, err := allocation.ParseMode(entity.Config.AllocationMode)
if err != nil {
return allocation.ModeSession, nil
}
return mode, nil
}
// Lookup returns the stored assignment without creating one. It always reads
// the database: callers use it to verify validity. A session retired before
// it was ever placed has no assignment.
func (s *Service) Lookup(ctx context.Context, sessionID string) (allocation.Assignment, bool, error) {
if strings.TrimSpace(sessionID) == "" {
return allocation.Assignment{}, false, nil
}
row, err := s.repo.GetAssignment(ctx, sessionID)
if err != nil {
return allocation.Assignment{}, false, fmt.Errorf("sandboxalloc: read assignment %s: %w", sessionID, err)
}
if row == nil || row.IsTombstone() {
return allocation.Assignment{}, false, nil
}
var machine *types.SandboxUserMachine
if row.MachineDigest != "" {
machine, err = s.repo.GetUserMachine(ctx, row.MachineDigest)
if err != nil {
return allocation.Assignment{}, false, fmt.Errorf("sandboxalloc: read machine of %s: %w", sessionID, err)
}
if machine == nil {
return allocation.Assignment{}, false, fmt.Errorf("%w: session %s", ErrMachineUnregistered, sessionID)
}
}
return FromEntity(row, machine), true, nil
}
// Retire is the first step of deleting sessions (C5): one transaction, under
// the lock first placement takes, releases each session's assignment and
// schedules its workspace cleanup. A session without an assignment gets a
// tombstone, so no placement can land after the deletion began.
func (s *Service) Retire(ctx context.Context, sessionIDs []string) ([]interfaces.RetiredSession, error) {
out, err := s.repo.RetireSessions(ctx, sessionIDs, s.now())
if err != nil {
return nil, fmt.Errorf("sandboxalloc: retire sessions: %w", err)
}
return out, nil
}
// Release retires one session.
func (s *Service) Release(ctx context.Context, sessionID string) (interfaces.RetiredSession, error) {
if strings.TrimSpace(sessionID) == "" {
return interfaces.RetiredSession{}, errors.New("sandboxalloc: release needs a session id")
}
out, err := s.Retire(ctx, []string{sessionID})
if err != nil {
return interfaces.RetiredSession{}, err
}
if len(out) != 1 {
return interfaces.RetiredSession{}, fmt.Errorf(
"sandboxalloc: retiring %s returned %d results", sessionID, len(out),
)
}
return out[0], nil
}
// SessionAllocation implements sandbox.AllocationDirectory.
func (s *Service) SessionAllocation(ctx context.Context, sessionID string) (allocation.Assignment, bool, error) {
return s.Lookup(ctx, sessionID)
}
// VerifySessionAllocation implements sandbox.AllocationDirectory (C4, C15,
// C17). The row must still be live and name the expected address. For a
// shared machine, the digest recomputed from the session's CURRENT owner must
// be the stored one — the digest binds the owner, so this is stricter than
// comparing a snapshot — and the session's current auth source must still
// qualify. A retired session's row is released (or a tombstone), so the
// release check covers retirement.
func (s *Service) VerifySessionAllocation(
ctx context.Context, sessionTenantID uint64, sessionID string, expected allocation.Assignment,
) error {
row, err := s.repo.GetAssignment(ctx, sessionID)
if err != nil {
return fmt.Errorf("sandboxalloc: read assignment %s: %w", sessionID, err)
}
if row == nil || row.ReleasedAt != nil {
return sandbox.ErrSandboxSessionDeleted
}
if row.ConfigTenantID != expected.ConfigTenantID ||
sandbox.NormalizeConfigID(row.ConfigID) != sandbox.NormalizeConfigID(expected.ConfigID) ||
row.MachineDigest != s.digestOf(expected) {
return fmt.Errorf("%w: session %s was re-addressed", sandbox.ErrUserAllocationRejected, sessionID)
}
sess, err := s.sessions.GetByID(ctx, sessionTenantID, sessionID)
if errors.Is(err, gorm.ErrRecordNotFound) || errors.Is(err, apperrors.ErrSessionNotFound) ||
(err == nil && sess == nil) {
return sandbox.ErrSandboxSessionDeleted
}
if err != nil {
return fmt.Errorf("sandboxalloc: read session %s: %w", sessionID, err)
}
if row.MachineDigest == "" {
return nil
}
current := allocation.UserMachine{
OwnerTenantID: sess.TenantID, OwnerID: sess.UserID,
ConfigTenantID: row.ConfigTenantID, ConfigID: row.ConfigID,
}
if s.Digest(current) != row.MachineDigest {
return fmt.Errorf("%w: session %s no longer belongs to the machine's owner",
sandbox.ErrUserAllocationRejected, sessionID)
}
owner := ownerFromSession(sess)
if !allocation.EligibleForUser(owner.Kind, owner.Source) {
return sandbox.ErrUserAllocationRejected
}
return nil
}
// UserMachinesByConfig implements sandbox.AllocationDirectory.
func (s *Service) UserMachinesByConfig(
ctx context.Context, configTenantID uint64, configID string,
) ([]allocation.UserMachine, error) {
rows, err := s.repo.ListUserMachinesByConfig(ctx, configTenantID, configID)
if err != nil {
return nil, err
}
out := make([]allocation.UserMachine, 0, len(rows))
for _, r := range rows {
out = append(out, allocation.UserMachine{
OwnerTenantID: r.OwnerTenantID, OwnerID: r.OwnerID,
ConfigTenantID: r.ConfigTenantID, ConfigID: r.ConfigID,
})
}
return out, nil
}
var _ sandbox.AllocationDirectory = (*Service)(nil)
// ForkAssignment is the child's assignment: same mode, machine and config,
// fresh session id. The caller persists it with the forked session.
func (s *Service) ForkAssignment(source allocation.Assignment, targetSessionID string) allocation.Assignment {
child := source
child.SessionID = targetSessionID
child.ReleasedAt = nil
return child
}
@@ -0,0 +1,348 @@
package sandboxalloc
import (
"context"
"errors"
"fmt"
"sync"
"testing"
"github.com/google/uuid"
"github.com/stretchr/testify/require"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"academy/internal/application/repository"
"academy/internal/sandbox"
"academy/internal/sandbox/allocation"
"academy/internal/types"
)
type fakeConfigs map[string]string // config id -> allocation_mode
func (f fakeConfigs) GetByID(_ context.Context, tenantID uint64, id string) (*types.TenantSandboxConfigEntity, error) {
return &types.TenantSandboxConfigEntity{
ID: id, TenantID: tenantID,
Config: &types.TenantSandboxConfig{AllocationMode: f[id]},
}, nil
}
type testEnv struct {
svc *Service
db *gorm.DB
}
func newEnv(t *testing.T, configs fakeConfigs, sessions ...*types.Session) *testEnv {
t.Helper()
// Same SQLite pool as the allocation repository tests: one connection and
// a busy timeout, so concurrent first-writers queue instead of failing
// with "database table is locked".
dsn := fmt.Sprintf("file:%s?mode=memory&cache=shared&_busy_timeout=5000", uuid.NewString())
db, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{
Logger: logger.Default.LogMode(logger.Silent),
})
require.NoError(t, err)
sqlDB, err := db.DB()
require.NoError(t, err)
sqlDB.SetMaxOpenConns(1)
require.NoError(t, db.AutoMigrate(&types.Session{}, &types.SessionSandboxAssignment{},
&types.SandboxUserMachine{}, &types.Message{}))
for _, s := range sessions {
require.NoError(t, db.Session(&gorm.Session{SkipHooks: true}).Create(s).Error)
}
svc := New(repository.NewSandboxAllocationRepository(db), configs, repository.NewSessionRepository(db), "academy")
return &testEnv{svc: svc, db: db}
}
func webSession(id string) *types.Session {
return &types.Session{ID: id, TenantID: 7, UserID: "u-1", OwnerAuthSource: types.AuthSourceWeb}
}
func (e *testEnv) place(t *testing.T, sessionID, configID string) allocation.Assignment {
t.Helper()
a, _ := e.placeWithReason(t, sessionID, configID)
return a
}
func (e *testEnv) placeWithReason(
t *testing.T, sessionID, configID string,
) (allocation.Assignment, allocation.FallbackReason) {
t.Helper()
a, reason, err := e.svc.place(context.Background(), PlaceRequest{
SessionTenantID: 7, SessionID: sessionID, ConfigTenantID: 7, ConfigID: configID,
})
require.NoError(t, err)
return a, reason
}
func (e *testEnv) reason(t *testing.T, sessionID, configID string) allocation.FallbackReason {
t.Helper()
_, r := e.placeWithReason(t, sessionID, configID)
return r
}
func (e *testEnv) addSession(t *testing.T, s *types.Session) {
t.Helper()
require.NoError(t, e.db.Session(&gorm.Session{SkipHooks: true}).Create(s).Error)
}
func (e *testEnv) digest(t *testing.T, sessionID string) string {
t.Helper()
row, err := e.svc.repo.GetAssignment(context.Background(), sessionID)
require.NoError(t, err)
require.NotNil(t, row)
return row.MachineDigest
}
func (e *testEnv) pin(t *testing.T, sessionID string) (string, uint64) {
t.Helper()
var s types.Session
require.NoError(t, e.db.Session(&gorm.Session{SkipHooks: true}).Where("id = ?", sessionID).Take(&s).Error)
return s.SandboxConfigID, s.SandboxConfigTenantID
}
func enableUserMode(t *testing.T) {
t.Helper()
allocation.SetUserModeAvailable(true)
t.Cleanup(func() { allocation.SetUserModeAvailable(false) })
}
type errConfigs struct{ err error }
func (e errConfigs) GetByID(context.Context, uint64, string) (*types.TenantSandboxConfigEntity, error) {
return nil, e.err
}
func TestPlaceDoesNotRecordAModeWhenTheConfigReadFails(t *testing.T) {
enableUserMode(t)
id := uuid.NewString()
e := newEnv(t, fakeConfigs{"cfg-a": "user"}, webSession(id))
e.svc.configs = errConfigs{err: errors.New("timeout")}
_, err := e.svc.Place(context.Background(), PlaceRequest{
SessionTenantID: 7, SessionID: id, ConfigTenantID: 7, ConfigID: "cfg-a",
})
require.Error(t, err)
row, err := e.svc.repo.GetAssignment(context.Background(), id)
require.NoError(t, err)
require.Nil(t, row, "a failed config read must be retried, not stored as session mode")
}
func TestPlacePutsAVerifiedWebUserOnASharedMachineAndPinsIt(t *testing.T) {
enableUserMode(t)
id := uuid.NewString()
e := newEnv(t, fakeConfigs{"cfg-a": "user"}, webSession(id))
a := e.place(t, id, "cfg-a")
require.Equal(t, allocation.ModeUser, a.Mode())
m, ok := a.UserMachine()
require.True(t, ok)
require.Equal(t, allocation.UserMachine{OwnerTenantID: 7, OwnerID: "u-1", ConfigTenantID: 7, ConfigID: "cfg-a"}, m)
cfg, tenant := e.pin(t, id)
require.Equal(t, "cfg-a", cfg)
require.EqualValues(t, 7, tenant)
// The stored row wins over a later request for another config, and reads
// back the same machine.
again := e.place(t, id, "cfg-b")
require.Equal(t, a, again)
}
// The owner's kind is derived from the stored source and the id's shape; a
// source that disagrees with the id never makes a verified person.
func TestPlaceDerivesTheOwnerKindFromItsSource(t *testing.T) {
enableUserMode(t)
ext, webWithColon, unknown := uuid.NewString(), uuid.NewString(), uuid.NewString()
e := newEnv(t, fakeConfigs{"cfg-a": "user"},
&types.Session{
ID: ext, TenantID: 7, UserID: "api_external_user:7:alice",
OwnerAuthSource: types.AuthSourceAPISignedToken,
},
&types.Session{
ID: webWithColon, TenantID: 7, UserID: "api_tenant_key:7:3",
OwnerAuthSource: types.AuthSourceWeb,
},
&types.Session{ID: unknown, TenantID: 7, UserID: "system-7"})
require.Equal(t, allocation.ModeUser, e.place(t, ext, "cfg-a").Mode())
require.Equal(t, allocation.ReasonOwnerIdentityUnverified, e.reason(t, webWithColon, "cfg-a"))
require.Equal(t, allocation.ReasonOwnerIdentityUnverified, e.reason(t, unknown, "cfg-a"),
"a row from before the column existed keeps a machine per session")
}
func TestLookupRefusesAUserAssignmentWithoutItsMachine(t *testing.T) {
enableUserMode(t)
id := uuid.NewString()
e := newEnv(t, fakeConfigs{"cfg-a": "user"}, webSession(id))
e.place(t, id, "cfg-a")
require.NoError(t, e.svc.Repo().DeleteUserMachinesByConfig(context.Background(), 7, "cfg-a"))
_, _, err := e.svc.Lookup(context.Background(), id)
require.ErrorIs(t, err, ErrMachineUnregistered, "never read back as a machine of its own")
}
func TestPlaceConcurrentCandidatesConvergeOnOneConfig(t *testing.T) {
enableUserMode(t)
id := uuid.NewString()
e := newEnv(t, fakeConfigs{"cfg-a": "user", "cfg-b": "session"}, webSession(id))
var wg sync.WaitGroup
got := make(chan string, 8)
for i := 0; i < 8; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
cfg := "cfg-a"
if i%2 == 1 {
cfg = "cfg-b"
}
got <- e.place(t, id, cfg).ConfigID
}(i)
}
wg.Wait()
close(got)
winner := ""
for c := range got {
if winner == "" {
winner = c
}
require.Equal(t, winner, c, "every caller is told the same config")
}
cfg, _ := e.pin(t, id)
require.Equal(t, winner, cfg, "the pin is the assignment's projection")
}
func TestPlaceFallbacks(t *testing.T) {
enableUserMode(t)
apiKey, legacy, maint, fork := uuid.NewString(), uuid.NewString(), uuid.NewString(), uuid.NewString()
legacyRow := webSession(legacy)
legacyRow.SandboxConfigID, legacyRow.SandboxConfigTenantID = "cfg-a", 7
maintRow := webSession(maint)
maintRow.Description = types.SkillMaintenanceSessionMarker + "install"
forkRow := webSession(fork)
forkRow.ForkBootstrap = &types.ForkBootstrap{SnapshotID: "snap"}
e := newEnv(t, fakeConfigs{"cfg-a": "user"},
&types.Session{
ID: apiKey, TenantID: 7, UserID: "api_tenant_key:7:3",
OwnerAuthSource: types.AuthSourceAPITenantKey,
},
legacyRow, maintRow, forkRow)
require.Equal(t, allocation.ReasonSharedAPIKey, e.reason(t, apiKey, "cfg-a"))
got, reason := e.placeWithReason(t, legacy, "cfg-a")
require.Equal(t, allocation.ModeSession, got.Mode(),
"a session that already has a pin keeps its per-session sandbox")
require.Equal(t, allocation.ReasonLegacySessionSandbox, reason)
require.Equal(t, allocation.ReasonMaintenanceDedicated, e.reason(t, maint, "cfg-a"))
require.Equal(t, allocation.ReasonLegacySessionSandbox, e.reason(t, fork, "cfg-a"),
"an unopened snapshot fork keeps its per-session bootstrap")
}
func TestPlaceWithTheGateOffFallsBack(t *testing.T) {
allocation.SetUserModeAvailable(false)
id := uuid.NewString()
e := newEnv(t, fakeConfigs{"cfg-a": "user"}, webSession(id))
a, reason := e.placeWithReason(t, id, "cfg-a")
require.Equal(t, allocation.ModeSession, a.Mode())
require.Equal(t, allocation.ReasonUserModeUnavailable, reason)
}
func TestReleaseAndForkAssignment(t *testing.T) {
enableUserMode(t)
id := uuid.NewString()
e := newEnv(t, fakeConfigs{"cfg-a": "user"}, webSession(id))
a := e.place(t, id, "cfg-a")
target := uuid.NewString()
child := e.svc.ForkAssignment(a, target)
require.Equal(t, target, child.SessionID)
require.Equal(t, a.Machine, child.Machine)
require.Equal(t, a.ConfigID, child.ConfigID)
require.Nil(t, child.ReleasedAt)
r, err := e.svc.Release(context.Background(), id)
require.NoError(t, err)
require.NotNil(t, r.Assignment)
require.True(t, r.MachineEmpty)
require.NotNil(t, r.Assignment.ReleasedAt)
require.NotNil(t, r.Assignment.CleanupDueAt)
released, ok, err := e.svc.Lookup(context.Background(), id)
require.NoError(t, err)
require.True(t, ok, "cleanup and inventory still find a released session's machine")
require.True(t, released.Released())
require.Equal(t, a.Machine, released.Machine)
}
func TestPlaceOnARetiredSessionIsRefused(t *testing.T) {
enableUserMode(t)
id := uuid.NewString()
e := newEnv(t, fakeConfigs{"cfg-a": "user"}, webSession(id))
out, err := e.svc.Retire(context.Background(), []string{id})
require.NoError(t, err)
require.Nil(t, out[0].Assignment, "retiring works before any placement")
_, err = e.svc.Place(types.WithSandboxTenantID(context.Background(), 7), PlaceRequest{
SessionTenantID: 7, SessionID: id, ConfigTenantID: 7, ConfigID: "cfg-a",
})
require.ErrorIs(t, err, sandbox.ErrSandboxSessionDeleted)
_, ok, err := e.svc.Lookup(context.Background(), id)
require.NoError(t, err)
require.False(t, ok)
}
// Lookup keeps a released row for cleanup; Place must refuse it, or a turn
// already in flight would rebuild the workspace of a deleted session.
func TestPlaceOnAReleasedAssignmentIsRefused(t *testing.T) {
enableUserMode(t)
id := uuid.NewString()
e := newEnv(t, fakeConfigs{"cfg-a": "user"}, webSession(id))
e.place(t, id, "cfg-a")
_, err := e.svc.Release(context.Background(), id)
require.NoError(t, err)
_, err = e.svc.Place(context.Background(), PlaceRequest{
SessionTenantID: 7, SessionID: id, ConfigTenantID: 7, ConfigID: "cfg-a",
})
require.ErrorIs(t, err, sandbox.ErrSandboxSessionDeleted)
}
func TestReleaseWithoutASessionIDIsAnError(t *testing.T) {
e := newEnv(t, fakeConfigs{})
_, err := e.svc.Release(context.Background(), " ")
require.Error(t, err)
}
func (e *testEnv) updateSession(t *testing.T, id string, cols map[string]any) {
t.Helper()
require.NoError(t, e.db.Session(&gorm.Session{SkipHooks: true}).
Model(&types.Session{}).Where("id = ?", id).Updates(cols).Error)
}
var _ sandbox.AllocationDirectory = (*Service)(nil)
func TestVerifySessionAllocationChecksTheCurrentOwnerAndRetirement(t *testing.T) {
enableUserMode(t)
id := uuid.NewString()
e := newEnv(t, fakeConfigs{"cfg-a": "user"}, webSession(id))
a := e.place(t, id, "cfg-a")
ctx := context.Background()
require.NoError(t, e.svc.VerifySessionAllocation(ctx, 7, id, a))
stale := a
stale.ConfigID = "cfg-b"
require.ErrorIs(t, e.svc.VerifySessionAllocation(ctx, 7, id, stale), sandbox.ErrUserAllocationRejected,
"a cached address that no longer matches the row is refused")
e.updateSession(t, id, map[string]any{"user_id": "u-2"})
require.ErrorIs(t, e.svc.VerifySessionAllocation(ctx, 7, id, a), sandbox.ErrUserAllocationRejected,
"the session changed hands; the old owner's machine is off limits (C15)")
e.updateSession(t, id, map[string]any{"user_id": "u-1", "owner_auth_source": "api_key"})
require.ErrorIs(t, e.svc.VerifySessionAllocation(ctx, 7, id, a), sandbox.ErrUserAllocationRejected)
e.updateSession(t, id, map[string]any{"owner_auth_source": "web"})
require.NoError(t, e.svc.VerifySessionAllocation(ctx, 7, id, a))
_, err := e.svc.Retire(ctx, []string{id})
require.NoError(t, err)
require.ErrorIs(t, e.svc.VerifySessionAllocation(ctx, 7, id, a), sandbox.ErrSandboxSessionDeleted)
}