Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

feat(sandbox): 共享机器的用户模式闭环(删除、回收、管理与桌面) (#4510)

nullptr-errora6cc635ab91f
diff --git a/.env.example b/.env.example
index 225fff977..41da4d3d9 100644
--- a/.env.example
+++ b/.env.example
@@ -647,6 +647,12 @@ SYSTEM_SIGNING_KEY=
# 「设置 → 系统设置 → 网络安全」打开(立即生效,无需重启)。
WEKNORA_SANDBOX_DOCKER_ENABLED=false
# 多实例仍应配置通用 REDIS_ADDR,以共享 session→sandbox binding。
+# 用户模式沙箱分配(同一合格用户的会话共用一台沙箱,目录按会话隔离)。
+# 设为 enabled 打开;还要求 REDIS_ADDR 已配置,多副本靠它协调同一台机器。
+# 升级顺序:所有实例都跑上新版本后,再在所有实例上设置,避免旧实例仍按
+# 每会话一台分配。未设置或 Redis 缺失时,沙箱配置里的「分配模式」不可
+# 保存为用户模式,已保存的用户模式配置在分配时回退为每会话一台。
+# WEKNORA_SANDBOX_USER_ALLOCATION=
# 智能体大模型调用默认超时(秒,默认 120;复杂推理调大如 300/600)。
# 注:全局默认;单个智能体在数据库配独立 llm_call_timeout 时以其为准。
diff --git a/frontend/src/api/system/index.ts b/frontend/src/api/system/index.ts
index 4770652be..6027e39e8 100644
--- a/frontend/src/api/system/index.ts
+++ b/frontend/src/api/system/index.ts
@@ -787,6 +787,8 @@ export interface SandboxConfig {
volume_mount?: SandboxVolumeMountConfig
skill_image?: SandboxSkillImage
skill_rollout?: 'next_turn' | 'new_session'
+ allocation_mode?: 'session' | 'user'
+ user_sandbox_empty_retention_days?: number
network?: SandboxNetworkPolicy
cube?: SandboxCubeConfig
e2b?: SandboxE2BConfig
@@ -925,6 +927,17 @@ export interface SandboxInventory {
session_ids?: string[]
agent_names?: string[]
unverifiable?: boolean
+ /** Shared user machines among sandbox_count, not sessions on those machines. */
+ user_sandbox_count?: number
+}
+
+export interface UserSandbox {
+ digest: string
+ owner_tenant_id: number
+ owner_id?: string
+ live_sessions: number
+ empty_since?: string
+ reclaim_after?: string
}
/** Sandbox backends managed as named workspace configurations. */
@@ -992,6 +1005,14 @@ export function getSandboxConfigInventory(id: string): Promise<{ data: SandboxIn
}>
}
+export function listUserSandboxes(configId: string) {
+ return get<{ success: boolean; data: UserSandbox[] }>(`/api/v1/sandbox-configs/${configId}/user-sandboxes`)
+}
+
+export function releaseUserSandbox(configId: string, digest: string) {
+ return post<{ success: boolean }>(`/api/v1/sandbox-configs/${configId}/user-sandboxes/${digest}/release`)
+}
+
/**
* Fetch templates using the connection currently entered in the drawer.
* `ensure_standard` starts a provider-side CLI build when that WeKnora
diff --git a/frontend/src/components/SandboxConfigEditorDrawer.allocation.test.ts b/frontend/src/components/SandboxConfigEditorDrawer.allocation.test.ts
new file mode 100644
index 000000000..62d0ce4aa
--- /dev/null
+++ b/frontend/src/components/SandboxConfigEditorDrawer.allocation.test.ts
@@ -0,0 +1,24 @@
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import test from 'node:test'
+
+const source = readFileSync(new URL('./SandboxConfigEditorDrawer.vue', import.meta.url), 'utf8')
+
+test('runtime step offers the allocation switch without the shared-root warning', () => {
+ const runtime = source.slice(source.lastIndexOf("currentStepKey === 'runtime'"))
+ for (const key of ['allocationModeRiskDelete', 'allocationModeRiskGit', 'allocationModeRiskResources', 'allocationModeRiskQuota', 'allocationModeSkillRolloutNote', 'allocationModeRiskTitle']) {
+ assert.equal(runtime.includes(key), false, `${key} must not be shown`)
+ }
+ assert.equal(runtime.includes("skillRollout === 'new_session'"), false)
+ assert.match(runtime, /:min="1" :max="90"/)
+})
+
+test('payload always sends allocation_mode so switching back to session is explicit', () => {
+ assert.match(source, /allocation_mode:\s*allocationMode\.value/)
+})
+
+test('choosing shared allocation scrolls the retention field into view', () => {
+ assert.match(source, /ref="userAllocationPanelRef"/)
+ assert.match(source, /scrollIntoView\(\{ behavior: 'smooth', block: 'end', inline: 'nearest' \}\)/)
+ assert.match(source, /if \(mode !== 'user' \|\| previous === 'user'\) return/)
+})
diff --git a/frontend/src/components/SandboxConfigEditorDrawer.vue b/frontend/src/components/SandboxConfigEditorDrawer.vue
index a8a3ed701..2a0a8f51b 100644
--- a/frontend/src/components/SandboxConfigEditorDrawer.vue
+++ b/frontend/src/components/SandboxConfigEditorDrawer.vue
@@ -728,6 +728,26 @@
<t-radio value="new_session">{{ $t('settings.sandbox.skillRolloutNewSession') }}</t-radio>
</t-radio-group>
</section>
+
+ <section v-if="currentStepKey === 'runtime'" class="setting-drawer__section">
+ <h4 class="setting-drawer__section-title">{{ $t('settings.sandbox.allocationMode') }}</h4>
+ <p class="section-help section-help--under-title">{{ $t('settings.sandbox.allocationModeHint') }}</p>
+ <t-radio-group v-model="allocationMode" class="allocation-mode-group">
+ <t-radio value="session">{{ $t('settings.sandbox.allocationModeSession') }}</t-radio>
+ <t-radio value="user" :disabled="!userAllocationSupported && allocationMode !== 'user'">
+ {{ $t('settings.sandbox.allocationModeUser') }}
+ </t-radio>
+ </t-radio-group>
+ <p v-if="!userAllocationSupported" class="section-help">{{ $t('settings.sandbox.allocationModeUnavailable') }}</p>
+ <template v-if="allocationMode === 'user'">
+ <div ref="userAllocationPanelRef">
+ <t-form-item :label="$t('settings.sandbox.userSandboxRetentionDays')">
+ <t-input-number v-model="userSandboxRetentionDays" :min="1" :max="90" :step="1" />
+ </t-form-item>
+ <p class="section-help">{{ $t('settings.sandbox.userSandboxRetentionHint') }}</p>
+ </div>
+ </template>
+ </section>
</t-form>
<div
@@ -805,6 +825,11 @@ const deploymentCapabilities = useDeploymentCapabilitiesStore()
const dockerBackendEnabled = computed(() =>
deploymentCapabilities.isSupported('settings.sandbox.docker'),
)
+// isSupported reads isDeploymentCapabilitySupported with the loaded map.
+// User allocation fails closed until the deployment reports it as supported.
+const userAllocationSupported = computed(() =>
+ deploymentCapabilities.isSupported('settings.sandbox.user_allocation'),
+)
// The backend echoes stored secrets as this placeholder. It never leaves the
// form as visible text: inputs stay empty and say "configured", and the
@@ -852,6 +877,20 @@ const docker = reactive<SandboxDockerConfig>({})
const storedSecrets = reactive({ cube: false, e2b: false })
const envRows = ref<{ key: string; value: string; stored?: boolean }[]>([])
const skillRollout = ref<'next_turn' | 'new_session'>('next_turn')
+const allocationMode = ref<'session' | 'user'>('session')
+const userAllocationPanelRef = ref<HTMLElement | null>(null)
+
+// The retention field is rendered below the fold. Selecting shared mode
+// grows the form; without a scroll the admin can save and never see it.
+watch(allocationMode, (mode, previous) => {
+ if (mode !== 'user' || previous === 'user') return
+ void nextTick(() => {
+ requestAnimationFrame(() => {
+ userAllocationPanelRef.value?.scrollIntoView({ behavior: 'smooth', block: 'end', inline: 'nearest' })
+ })
+ })
+})
+const userSandboxRetentionDays = ref<number>(7)
// Both defaults are the zero value on the server too: egress allowed, inbound
// requiring the per-sandbox credential. Inbound is not editable in this form.
const denyEgressByDefault = ref(false)
@@ -1173,6 +1212,10 @@ function reset() {
isMaskedSecret(value) ? { key, value: '', stored: true } : { key, value }
))
skillRollout.value = cfg.skill_rollout === 'new_session' ? 'new_session' : 'next_turn'
+ allocationMode.value = cfg.allocation_mode === 'user' ? 'user' : 'session'
+ // Stored 0 means "use the default". The merge treats 0 as omitted, so the
+ // editor shows and sends 7 when the admin wants that default.
+ userSandboxRetentionDays.value = cfg.user_sandbox_empty_retention_days || 7
const net = cfg.network || {}
denyEgressByDefault.value = net.deny_egress_by_default === true
allowOutRows.value = [...(net.allow_out || [])]
@@ -1548,6 +1591,9 @@ function collectPayload(): SandboxConfig {
desktop_enabled: collectedDesktopEnabled(),
env_vars: envVars,
skill_rollout: skillRollout.value,
+ allocation_mode: allocationMode.value,
+ user_sandbox_empty_retention_days:
+ allocationMode.value === 'user' ? (userSandboxRetentionDays.value || 7) : undefined,
network: collectNetworkPolicy(),
}
// Send only the selected backend's block so an unused one cannot fail
@@ -2422,7 +2468,8 @@ onUnmounted(stopTemplatePolling)
text-align: center;
}
-.skill-rollout-group {
+.skill-rollout-group,
+.allocation-mode-group {
display: flex;
flex-direction: column;
align-items: flex-start;
diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts
index c81fe8bb1..120fa7065 100755
--- a/frontend/src/i18n/locales/en-US.ts
+++ b/frontend/src/i18n/locales/en-US.ts
@@ -1998,6 +1998,23 @@ export default {
skillRolloutNextTurn: 'Rebuild open sessions on the next chat turn',
skillRolloutNewSession: 'Keep open sessions on their current sandbox; only new sessions use the new image',
skillRolloutSaveFailed: 'Failed to save the rollout setting',
+ allocationMode: 'Sandbox allocation',
+ allocationModeHint: 'Only affects sessions that have not used a sandbox yet; existing sessions keep their placement and files are never moved.',
+ allocationModeSession: 'One sandbox per session (default)',
+ allocationModeUser: "Share one sandbox across a user's sessions",
+ allocationModeUnavailable: 'Shared sandboxes are not enabled on this deployment (set WEKNORA_SANDBOX_USER_ALLOCATION=enabled on every replica; Redis is required).',
+ userSandboxRetentionDays: 'Keep an empty shared sandbox for (days)',
+ userSandboxRetentionHint: 'After every session on a shared sandbox is deleted, it is removed once it has been empty this long (1–90 days). This is not a minimum file retention: Docker idle cleanup or provider failures may remove it sooner.',
+ userSandboxesInInventory: "{count} of them are shared user sandboxes; each affects all of that user's sessions on this config.",
+ userSandboxesTitle: 'Shared user sandboxes',
+ userSandboxOwner: 'Owner',
+ userSandboxOwnerOtherWorkspace: 'A user from another workspace',
+ userSandboxLiveSessions: 'Sessions',
+ userSandboxEmptySince: 'Empty since',
+ userSandboxReclaimAfter: 'Reclaimed after',
+ userSandboxRelease: 'Release',
+ userSandboxReleaseConfirm: "Releasing deletes the files and installed packages of all of this user's sessions on this config; a new sandbox is created on next use. Release it?",
+ userSandboxBusy: 'A terminal, desktop or command is still running on this sandbox. Try again later.',
skillInstallGroup: 'Install a new skill',
skillInstalledGroup: 'Installed',
skillUploadClick: 'Click to upload a zip bundle',
diff --git a/frontend/src/i18n/locales/ja-JP.ts b/frontend/src/i18n/locales/ja-JP.ts
index 7f624f154..a9974cdfd 100644
--- a/frontend/src/i18n/locales/ja-JP.ts
+++ b/frontend/src/i18n/locales/ja-JP.ts
@@ -1998,6 +1998,23 @@ export default {
skillRolloutNextTurn: '開いているセッションは次のやり取りでサンドボックスを再構築する',
skillRolloutNewSession: '開いているセッションは現在のサンドボックスのままにし、新しいセッションのみ新しいイメージを使用する',
skillRolloutSaveFailed: '反映設定の保存に失敗しました',
+ allocationMode: 'Sandbox allocation',
+ allocationModeHint: 'Only affects sessions that have not used a sandbox yet; existing sessions keep their placement and files are never moved.',
+ allocationModeSession: 'One sandbox per session (default)',
+ allocationModeUser: "Share one sandbox across a user's sessions",
+ allocationModeUnavailable: 'Shared sandboxes are not enabled on this deployment (set WEKNORA_SANDBOX_USER_ALLOCATION=enabled on every replica; Redis is required).',
+ userSandboxRetentionDays: 'Keep an empty shared sandbox for (days)',
+ userSandboxRetentionHint: 'After every session on a shared sandbox is deleted, it is removed once it has been empty this long (1–90 days). This is not a minimum file retention: Docker idle cleanup or provider failures may remove it sooner.',
+ userSandboxesInInventory: "{count} of them are shared user sandboxes; each affects all of that user's sessions on this config.",
+ userSandboxesTitle: 'Shared user sandboxes',
+ userSandboxOwner: 'Owner',
+ userSandboxOwnerOtherWorkspace: 'A user from another workspace',
+ userSandboxLiveSessions: 'Sessions',
+ userSandboxEmptySince: 'Empty since',
+ userSandboxReclaimAfter: 'Reclaimed after',
+ userSandboxRelease: 'Release',
+ userSandboxReleaseConfirm: "Releasing deletes the files and installed packages of all of this user's sessions on this config; a new sandbox is created on next use. Release it?",
+ userSandboxBusy: 'A terminal, desktop or command is still running on this sandbox. Try again later.',
skillInstallGroup: '新しいスキルをインストール',
skillInstalledGroup: 'インストール済み',
skillUploadClick: 'クリックしてzipバンドルをアップロード',
diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts
index fcb6c9f29..e3d927491 100755
--- a/frontend/src/i18n/locales/ko-KR.ts
+++ b/frontend/src/i18n/locales/ko-KR.ts
@@ -6967,6 +6967,23 @@ export default {
skillRolloutNextTurn: '이미 열린 세션은 다음 대화 턴에서 샌드박스를 다시 만듭니다',
skillRolloutNewSession: '이미 열린 세션은 기존 샌드박스를 유지하고, 새 세션만 새 이미지를 사용합니다',
skillRolloutSaveFailed: '적용 방식 저장에 실패했습니다',
+ allocationMode: 'Sandbox allocation',
+ allocationModeHint: 'Only affects sessions that have not used a sandbox yet; existing sessions keep their placement and files are never moved.',
+ allocationModeSession: 'One sandbox per session (default)',
+ allocationModeUser: "Share one sandbox across a user's sessions",
+ allocationModeUnavailable: 'Shared sandboxes are not enabled on this deployment (set WEKNORA_SANDBOX_USER_ALLOCATION=enabled on every replica; Redis is required).',
+ userSandboxRetentionDays: 'Keep an empty shared sandbox for (days)',
+ userSandboxRetentionHint: 'After every session on a shared sandbox is deleted, it is removed once it has been empty this long (1–90 days). This is not a minimum file retention: Docker idle cleanup or provider failures may remove it sooner.',
+ userSandboxesInInventory: "{count} of them are shared user sandboxes; each affects all of that user's sessions on this config.",
+ userSandboxesTitle: 'Shared user sandboxes',
+ userSandboxOwner: 'Owner',
+ userSandboxOwnerOtherWorkspace: 'A user from another workspace',
+ userSandboxLiveSessions: 'Sessions',
+ userSandboxEmptySince: 'Empty since',
+ userSandboxReclaimAfter: 'Reclaimed after',
+ userSandboxRelease: 'Release',
+ userSandboxReleaseConfirm: "Releasing deletes the files and installed packages of all of this user's sessions on this config; a new sandbox is created on next use. Release it?",
+ userSandboxBusy: 'A terminal, desktop or command is still running on this sandbox. Try again later.',
skillInstallGroup: '새 스킬 설치',
skillInstalledGroup: '설치됨',
skillUploadClick: 'zip 파일을 클릭해 업로드',
diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts
index 90019aef0..e6c53ea5f 100755
--- a/frontend/src/i18n/locales/ru-RU.ts
+++ b/frontend/src/i18n/locales/ru-RU.ts
@@ -6967,6 +6967,23 @@ export default {
skillRolloutNextTurn: 'Пересоздать песочницу открытых сессий на следующем ходе диалога',
skillRolloutNewSession: 'Оставить открытые сессии на текущей песочнице; новый образ только у новых сессий',
skillRolloutSaveFailed: 'Не удалось сохранить способ применения',
+ allocationMode: 'Sandbox allocation',
+ allocationModeHint: 'Only affects sessions that have not used a sandbox yet; existing sessions keep their placement and files are never moved.',
+ allocationModeSession: 'One sandbox per session (default)',
+ allocationModeUser: "Share one sandbox across a user's sessions",
+ allocationModeUnavailable: 'Shared sandboxes are not enabled on this deployment (set WEKNORA_SANDBOX_USER_ALLOCATION=enabled on every replica; Redis is required).',
+ userSandboxRetentionDays: 'Keep an empty shared sandbox for (days)',
+ userSandboxRetentionHint: 'After every session on a shared sandbox is deleted, it is removed once it has been empty this long (1–90 days). This is not a minimum file retention: Docker idle cleanup or provider failures may remove it sooner.',
+ userSandboxesInInventory: "{count} of them are shared user sandboxes; each affects all of that user's sessions on this config.",
+ userSandboxesTitle: 'Shared user sandboxes',
+ userSandboxOwner: 'Owner',
+ userSandboxOwnerOtherWorkspace: 'A user from another workspace',
+ userSandboxLiveSessions: 'Sessions',
+ userSandboxEmptySince: 'Empty since',
+ userSandboxReclaimAfter: 'Reclaimed after',
+ userSandboxRelease: 'Release',
+ userSandboxReleaseConfirm: "Releasing deletes the files and installed packages of all of this user's sessions on this config; a new sandbox is created on next use. Release it?",
+ userSandboxBusy: 'A terminal, desktop or command is still running on this sandbox. Try again later.',
skillInstallGroup: 'Установить навык',
skillInstalledGroup: 'Установленные',
skillUploadClick: 'Нажмите, чтобы загрузить zip',
diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts
index b224e9ad5..2203260ae 100755
--- a/frontend/src/i18n/locales/zh-CN.ts
+++ b/frontend/src/i18n/locales/zh-CN.ts
@@ -6968,6 +6968,23 @@ export default {
skillRolloutNextTurn: '已有会话在下一轮提问时重建沙箱',
skillRolloutNewSession: '已有会话保持原沙箱,仅新会话使用新镜像',
skillRolloutSaveFailed: '保存生效方式失败',
+ allocationMode: '沙箱分配方式',
+ allocationModeHint: '只影响还没有用过沙箱的会话;已有会话保持原来的分配,不会搬迁文件。',
+ allocationModeSession: '每个会话一台沙箱(默认)',
+ allocationModeUser: '同一用户的会话共用一台沙箱',
+ allocationModeUnavailable: '当前部署未开启共用沙箱(需在所有实例设置 WEKNORA_SANDBOX_USER_ALLOCATION=enabled,并配置 Redis)。',
+ userSandboxRetentionDays: '空置沙箱保留天数',
+ userSandboxRetentionHint: '某台共用沙箱上的会话全部删除后,空置满这个天数会被自动删除(1–90 天)。这不是文件最少保留时间:Docker 空闲回收或服务商故障可能更早删除。',
+ userSandboxesInInventory: '其中 {count} 台是用户共用沙箱,影响该用户在此配置下的全部会话。',
+ userSandboxesTitle: '用户共用沙箱',
+ userSandboxOwner: '用户',
+ userSandboxOwnerOtherWorkspace: '其他空间的用户',
+ userSandboxLiveSessions: '会话数',
+ userSandboxEmptySince: '空置起点',
+ userSandboxReclaimAfter: '预计回收',
+ userSandboxRelease: '释放',
+ userSandboxReleaseConfirm: '释放后,该用户在此配置下全部会话的文件和已安装的包都会丢失,下次使用时会新建沙箱。确定释放?',
+ userSandboxBusy: '这台沙箱上还有终端、桌面或命令在运行,请稍后再试。',
skillInstallGroup: '安装新技能',
skillInstalledGroup: '已安装',
skillUploadClick: '点击上传 zip 压缩包',
diff --git a/frontend/src/i18n/locales/zh-TW.ts b/frontend/src/i18n/locales/zh-TW.ts
index e62fadb2f..7b769dd2d 100644
--- a/frontend/src/i18n/locales/zh-TW.ts
+++ b/frontend/src/i18n/locales/zh-TW.ts
@@ -6968,6 +6968,23 @@ export default {
skillRolloutNextTurn: '已有會話在下一輪提問時重建沙箱',
skillRolloutNewSession: '已有會話保持原沙箱,僅新會話使用新映像',
skillRolloutSaveFailed: '儲存生效方式失敗',
+ allocationMode: '沙箱分配方式',
+ allocationModeHint: '只影響還沒有用過沙箱的會話;已有會話保持原來的分配,不會搬遷檔案。',
+ allocationModeSession: '每個會話一台沙箱(預設)',
+ allocationModeUser: '同一使用者的會話共用一台沙箱',
+ allocationModeUnavailable: '目前部署未開啟共用沙箱(需在所有實例設定 WEKNORA_SANDBOX_USER_ALLOCATION=enabled,並設定 Redis)。',
+ userSandboxRetentionDays: '空置沙箱保留天數',
+ userSandboxRetentionHint: '某台共用沙箱上的會話全部刪除後,空置滿這個天數會被自動刪除(1–90 天)。這不是檔案最少保留時間:Docker 空閒回收或服務商故障可能更早刪除。',
+ userSandboxesInInventory: '其中 {count} 台是使用者共用沙箱,影響該使用者在此設定下的全部會話。',
+ userSandboxesTitle: '使用者共用沙箱',
+ userSandboxOwner: '使用者',
+ userSandboxOwnerOtherWorkspace: '其他空間的使用者',
+ userSandboxLiveSessions: '會話數',
+ userSandboxEmptySince: '空置起點',
+ userSandboxReclaimAfter: '預計回收',
+ userSandboxRelease: '釋放',
+ userSandboxReleaseConfirm: '釋放後,該使用者在此設定下全部會話的檔案和已安裝的套件都會遺失,下次使用時會新建沙箱。確定釋放?',
+ userSandboxBusy: '這台沙箱上還有終端、桌面或命令在執行,請稍後再試。',
skillInstallGroup: '安裝新技能',
skillInstalledGroup: '已安裝',
skillUploadClick: '點擊上傳 zip 壓縮包',
diff --git a/frontend/src/views/settings/SandboxSettings.vue b/frontend/src/views/settings/SandboxSettings.vue
index 36d74b9b1..336116b61 100644
--- a/frontend/src/views/settings/SandboxSettings.vue
+++ b/frontend/src/views/settings/SandboxSettings.vue
@@ -169,6 +169,9 @@
:message="$t('settings.sandbox.sandboxesStillLive', { count: inventory?.sandbox_count ?? 0 })">
<template #description>
<p>{{ $t('settings.sandbox.blockedHint') }}</p>
+ <p v-if="inventory?.user_sandbox_count" class="section-help">
+ {{ $t('settings.sandbox.userSandboxesInInventory', { count: inventory.user_sandbox_count }) }}
+ </p>
</template>
</t-alert>
</div>
@@ -198,6 +201,30 @@
<h4 class="setting-drawer__section-title">{{ $t('settings.sandbox.inventoryAgentsTitle') }}</h4>
<p class="inventory-agents">{{ inventoryAgents.join('、') }}</p>
</section>
+
+ <section v-if="showUserSandboxes" class="setting-drawer__section inventory-section">
+ <h4 class="setting-drawer__section-title">{{ $t('settings.sandbox.userSandboxesTitle') }}</h4>
+ <div class="user-sandbox-table">
+ <t-table
+ row-key="digest"
+ size="small"
+ :data="userSandboxes"
+ :columns="userSandboxColumns"
+ :loading="userSandboxesLoading"
+ >
+ <template #owner="{ row }">
+ {{ row.owner_id || $t('settings.sandbox.userSandboxOwnerOtherWorkspace') }}
+ </template>
+ <template #empty_since="{ row }">{{ formatSandboxTime(row.empty_since) }}</template>
+ <template #reclaim_after="{ row }">{{ formatSandboxTime(row.reclaim_after) }}</template>
+ <template #op="{ row }">
+ <t-button size="small" theme="danger" variant="text" @click="askRelease(row)">
+ {{ $t('settings.sandbox.userSandboxRelease') }}
+ </t-button>
+ </template>
+ </t-table>
+ </div>
+ </section>
</t-loading>
<!--
@@ -216,6 +243,20 @@
</t-popconfirm>
</template>
</SettingDrawer>
+
+ <t-dialog
+ v-model:visible="releaseDialogVisible"
+ :header="$t('settings.sandbox.userSandboxRelease')"
+ :confirm-btn="{
+ content: $t('settings.sandbox.userSandboxRelease'),
+ theme: 'danger',
+ loading: releasing,
+ }"
+ :cancel-btn="$t('common.cancel')"
+ @confirm="confirmRelease"
+ >
+ <p class="user-sandbox-release-confirm">{{ $t('settings.sandbox.userSandboxReleaseConfirm') }}</p>
+ </t-dialog>
</div>
</template>
@@ -230,6 +271,7 @@ import SettingDrawer from '@/components/settings/SettingDrawer.vue'
import { useConfirmDelete } from '@/components/settings/useConfirmDelete'
import { getSession } from '@/api/chat/index'
import { useDeploymentCapabilitiesStore } from '@/stores/deploymentCapabilities'
+import { formatStringDate } from '@/utils'
import { docsUrl } from '@/utils/docsUrl'
import { matchesResourceQuery } from '@/utils/resourceListSearch'
import {
@@ -237,11 +279,14 @@ import {
getSandboxConfigInventory,
isNamedSandboxBackend,
listSandboxConfigs,
+ listUserSandboxes,
NAMED_SANDBOX_BACKEND_TYPES,
parseSandboxConflict,
+ releaseUserSandbox,
setSandboxWorkspacePolicy,
type SandboxConfigRecord,
type SandboxInventory,
+ type UserSandbox,
} from '@/api/system'
const { t } = useI18n()
@@ -329,6 +374,81 @@ const inventorySubtitle = computed(() => {
const inventorySessions = computed(() => inventory.value?.session_ids || [])
const inventoryAgents = computed(() => inventory.value?.agent_names || [])
+const showUserSandboxes = computed(() => inventoryRecord.value?.config?.allocation_mode === 'user')
+const userSandboxes = ref<UserSandbox[]>([])
+const userSandboxesLoading = ref(false)
+const releaseTarget = ref<UserSandbox | null>(null)
+const releaseDialogVisible = ref(false)
+const releasing = ref(false)
+const userSandboxColumns = computed(() => [
+ { colKey: 'owner', title: t('settings.sandbox.userSandboxOwner'), ellipsis: true, minWidth: 120 },
+ { colKey: 'live_sessions', title: t('settings.sandbox.userSandboxLiveSessions'), width: 88 },
+ { colKey: 'empty_since', title: t('settings.sandbox.userSandboxEmptySince'), width: 160 },
+ { colKey: 'reclaim_after', title: t('settings.sandbox.userSandboxReclaimAfter'), width: 160 },
+ { colKey: 'op', title: t('settings.sandbox.userSandboxRelease'), width: 80 },
+])
+
+function formatSandboxTime(value?: string): string {
+ if (!value) return '—'
+ const date = new Date(value)
+ if (Number.isNaN(date.getTime())) return value
+ return formatStringDate(value)
+}
+
+function isUserSandboxBusy(err: unknown): boolean {
+ if (typeof err !== 'object' || err === null) return false
+ const body = err as { status?: number; error?: unknown; $httpStatus?: number }
+ return body.status === 409 || body.$httpStatus === 409 || body.error === 'USER_SANDBOX_BUSY'
+}
+
+async function loadUserSandboxes(configId: string) {
+ if (inventoryRecord.value?.config?.allocation_mode !== 'user') {
+ userSandboxes.value = []
+ return
+ }
+ userSandboxesLoading.value = true
+ try {
+ const res = await listUserSandboxes(configId)
+ userSandboxes.value = res?.data || []
+ } catch (e: any) {
+ userSandboxes.value = []
+ MessagePlugin.error(e?.message || t('settings.sandbox.inventoryFailed'))
+ } finally {
+ userSandboxesLoading.value = false
+ }
+}
+
+function askRelease(row: UserSandbox) {
+ releaseTarget.value = row
+ releaseDialogVisible.value = true
+}
+
+async function confirmRelease() {
+ const row = releaseTarget.value
+ const record = inventoryRecord.value
+ if (!row || !record) return
+ releasing.value = true
+ try {
+ await releaseUserSandbox(record.id, row.digest)
+ releaseDialogVisible.value = false
+ releaseTarget.value = null
+ try {
+ const res = await getSandboxConfigInventory(record.id)
+ inventory.value = res?.data || inventory.value
+ } catch {
+ // The shared-machine table is refreshed below either way.
+ }
+ await loadUserSandboxes(record.id)
+ } catch (e: any) {
+ if (isUserSandboxBusy(e)) {
+ MessagePlugin.warning(t('settings.sandbox.userSandboxBusy'))
+ return
+ }
+ MessagePlugin.error(e?.message || t('settings.sandbox.inventoryFailed'))
+ } finally {
+ releasing.value = false
+ }
+}
const sessionTitles = ref<Record<string, string>>({})
@@ -533,10 +653,16 @@ async function openInventory(record: SandboxConfigRecord) {
inventoryLoading.value = true
inventory.value = null
sessionTitles.value = {}
+ userSandboxes.value = []
+ releaseDialogVisible.value = false
+ releaseTarget.value = null
try {
const res = await getSandboxConfigInventory(record.id)
inventory.value = res?.data || null
- await loadSessionTitles(inventory.value?.session_ids || [])
+ await Promise.all([
+ loadSessionTitles(inventory.value?.session_ids || []),
+ loadUserSandboxes(record.id),
+ ])
} catch (e: any) {
MessagePlugin.error(e?.message || t('settings.sandbox.inventoryFailed'))
showInventory.value = false
@@ -580,7 +706,11 @@ function showRefusal(
inventory.value = inv || { sandbox_count: 0, unverifiable: notice === 'unverifiable' }
inventoryLoading.value = false
showInventory.value = true
+ userSandboxes.value = []
+ releaseDialogVisible.value = false
+ releaseTarget.value = null
void loadSessionTitles(inventory.value.session_ids || [])
+ void loadUserSandboxes(record.id)
}
async function forceRemove(record: SandboxConfigRecord) {
@@ -832,6 +962,22 @@ onMounted(async () => {
font-size: var(--app-text-md);
line-height: 1.5;
}
+
+.section-help {
+ margin: 8px 0 0;
+ color: var(--td-text-color-secondary);
+ font-size: var(--app-text-sm);
+ line-height: 1.5;
+}
+
+.user-sandbox-table {
+ overflow-x: auto;
+}
+
+.user-sandbox-release-confirm {
+ margin: 0;
+ line-height: 1.5;
+}
</style>
<style lang="less">
diff --git a/internal/application/repository/sandbox_allocation.go b/internal/application/repository/sandbox_allocation.go
index 7a2ec6e6e..e355b4d32 100644
--- a/internal/application/repository/sandbox_allocation.go
+++ b/internal/application/repository/sandbox_allocation.go
@@ -9,10 +9,20 @@ import (
"gorm.io/gorm"
"gorm.io/gorm/clause"
+ "github.com/Tencent/WeKnora/internal/sandbox/workspace"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
+// errWebUserDeleted means the canonical web user row is already soft-deleted.
+// Session create returns it as-is. ClaimPlacement maps it to ErrSessionRetired.
+var errWebUserDeleted = errors.New("repository: web user is deleted")
+
+// afterWebUserLock runs after lockLiveWebUser has locked a users row and
+// before it returns. Tests insert a session on that same transaction; they
+// clear the hook with t.Cleanup.
+var afterWebUserLock func(tx *gorm.DB)
+
type sandboxAllocationRepository struct{ db *gorm.DB }
// NewSandboxAllocationRepository builds the allocation repository.
@@ -89,23 +99,72 @@ func InsertSandboxAssignmentTx(
return true, err
}
+// lockLiveWebUser locks a canonical web user's row. Other owner ids are
+// not web accounts and must not touch the users table. No row means this
+// id is not a web account. A soft-deleted row returns errWebUserDeleted
+// while the lock is still held.
+func lockLiveWebUser(tx *gorm.DB, userID string) error {
+ if !workspace.IsCanonicalUUID(userID) {
+ return nil
+ }
+ var row struct {
+ ID string
+ DeletedAt gorm.DeletedAt
+ }
+ err := forUpdate(tx.Unscoped().Model(&types.User{})).
+ Select("id", "deleted_at").
+ Where("id = ?", userID).
+ Take(&row).Error
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ if afterWebUserLock != nil {
+ afterWebUserLock(tx)
+ }
+ if row.DeletedAt.Valid {
+ return errWebUserDeleted
+ }
+ return nil
+}
+
func (r *sandboxAllocationRepository) ClaimPlacement(
ctx context.Context, a *types.SessionSandboxAssignment, machine *types.SandboxUserMachine,
expected interfaces.PlacementPin,
) (*types.SessionSandboxAssignment, error) {
var out *types.SessionSandboxAssignment
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
+ // The owner row comes before the session row. Reading user_id without
+ // a lock is what makes that order possible: the session lock is next.
+ var owner struct {
+ UserID string `gorm:"column:user_id"`
+ }
+ res := tx.Model(&types.Session{}).
+ Select("user_id").
+ Where("id = ?", a.SessionID).
+ Take(&owner)
+ if res.Error != nil {
+ return res.Error // gorm.ErrRecordNotFound for a missing or soft-deleted session
+ }
+ if err := lockLiveWebUser(tx, owner.UserID); err != nil {
+ if errors.Is(err, errWebUserDeleted) {
+ return interfaces.ErrSessionRetired
+ }
+ return err
+ }
// Lock the session row: the pin lives on it, and an older replica's
// conditional pin update waits on this lock instead of interleaving.
var row struct {
SandboxConfigID *string
SandboxConfigTenantID uint64
}
- res := forUpdate(tx.Model(&types.Session{})).
+ res = forUpdate(tx.Model(&types.Session{})).
Select("sandbox_config_id", "sandbox_config_tenant_id").
Where("id = ?", a.SessionID).Take(&row)
if res.Error != nil {
- return res.Error // gorm.ErrRecordNotFound for a missing or soft-deleted session
+ return res.Error
}
current := interfaces.PlacementPin{TenantID: row.SandboxConfigTenantID}
if row.SandboxConfigID != nil {
@@ -190,11 +249,97 @@ func (r *sandboxAllocationRepository) RetireSessions(
return out, err
}
+// DeleteSessionsRetiring uses the same session-before-machine lock order as
+// placement. Ownership is checked under the session locks so a stale service
+// lookup cannot retire a session that has moved to another owner or tenant.
+func (r *sandboxAllocationRepository) DeleteSessionsRetiring(
+ ctx context.Context, tenantID uint64, idsByOwner map[string][]string, at time.Time,
+) ([]interfaces.RetiredSession, error) {
+ owners := make(map[string]string)
+ for owner, ids := range idsByOwner {
+ for _, id := range ids {
+ owners[id] = owner
+ }
+ }
+ ids := make([]string, 0, len(owners))
+ for id := range owners {
+ ids = append(ids, id)
+ }
+ sort.Strings(ids)
+ var retired []interfaces.RetiredSession
+ err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
+ live := make([]string, 0, len(ids))
+ for _, id := range ids {
+ var found []string
+ q := tx.Model(&types.Session{}).Where("tenant_id = ? AND id = ?", tenantID, id)
+ if owner := owners[id]; owner != "" {
+ q = q.Where("user_id = ?", owner)
+ } else {
+ q = q.Where("user_id IS NULL OR user_id = ''")
+ }
+ if err := forUpdate(q).Pluck("id", &found).Error; err != nil {
+ return err
+ }
+ live = append(live, found...)
+ }
+ if len(live) == 0 {
+ return nil
+ }
+ var err error
+ retired, err = RetireSessionsTx(tx, live, at)
+ if err != nil {
+ return err
+ }
+ return tx.Where("tenant_id = ? AND id IN ?", tenantID, live).Delete(&types.Session{}).Error
+ })
+ if err != nil {
+ return nil, err
+ }
+ return retired, nil
+}
+
+// RetireOwnerSessions retires every session of a deleted Web account and
+// releases their assignments in one transaction. The account's own sessions
+// (any source, including ones never placed) and any session whose live
+// assignment is on one of its machines are included: a session row may have
+// been reassigned onto a machine this account still owns.
+func (r *sandboxAllocationRepository) RetireOwnerSessions(
+ ctx context.Context, ownerID string, at time.Time,
+) ([]interfaces.RetiredSession, error) {
+ var out []interfaces.RetiredSession
+ err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
+ ids, err := ownerSessionIDs(tx, ownerID)
+ if err != nil {
+ return err
+ }
+ out, err = RetireSessionsTx(tx, ids, at)
+ return err
+ })
+ return out, err
+}
+
+// ownerSessionIDs is the account's own sessions, including ones never placed,
+// plus any session whose live assignment still sits on one of its machines.
+func ownerSessionIDs(tx *gorm.DB, ownerID string) ([]string, error) {
+ var ids []string
+ if err := tx.Unscoped().Model(&types.Session{}).
+ Where("user_id = ?", ownerID).Pluck("id", &ids).Error; err != nil {
+ return nil, err
+ }
+ var assigned []string
+ if err := tx.Table("session_sandbox_assignments AS a").
+ Joins("JOIN sandbox_user_machines AS m ON m.machine_digest = a.machine_digest").
+ Where("m.owner_id = ? AND a.released_at IS NULL", ownerID).
+ Pluck("a.session_id", &assigned).Error; err != nil {
+ return nil, err
+ }
+ return append(ids, assigned...), nil
+}
+
// RetireSessionsTx is RetireSessions inside the caller's transaction (T14
-// retires a deleted account's sessions with it). Locks are taken in a fixed
-// order — every session row by id, then every machine row by digest — which
-// is the order ClaimPlacement uses for one session, so the two cannot
-// deadlock.
+// retires a deleted account's sessions with it). Locks are session rows by
+// id, then machine rows by digest. A caller that also locks the user row
+// must do that first: user, then sessions, then machines.
func RetireSessionsTx(tx *gorm.DB, sessionIDs []string, at time.Time) ([]interfaces.RetiredSession, error) {
at = at.UTC().Truncate(time.Microsecond)
seen := make(map[string]bool, len(sessionIDs))
@@ -393,6 +538,124 @@ func (r *sandboxAllocationRepository) DeleteUserMachinesByConfig(
Delete(&types.SandboxUserMachine{}).Error
}
+// GormDB is the database this repository writes, so a caller can delete
+// machine rows and another table in one transaction.
+func (r *sandboxAllocationRepository) GormDB() *gorm.DB { return r.db }
+
+// LockEmptyMachine locks a machine that is actually empty. See the interface.
+func (r *sandboxAllocationRepository) LockEmptyMachine(
+ ctx context.Context, digest string,
+) (interfaces.MachineReclaimLock, error) {
+ tx := r.db.WithContext(ctx).Begin()
+ if tx.Error != nil {
+ return nil, tx.Error
+ }
+ fail := func(err error) (interfaces.MachineReclaimLock, error) {
+ tx.Rollback()
+ return nil, err
+ }
+ if err := lockMachineRow(tx, digest); err != nil {
+ return fail(err)
+ }
+ var row types.SandboxUserMachine
+ err := tx.Where("machine_digest = ?", digest).Take(&row).Error
+ if errors.Is(err, gorm.ErrRecordNotFound) || (err == nil && row.EmptySince == nil) {
+ tx.Rollback()
+ return nil, nil
+ }
+ if err != nil {
+ return fail(err)
+ }
+ live, err := countLive(tx, digest)
+ if err != nil {
+ return fail(err)
+ }
+ if live > 0 {
+ tx.Rollback()
+ return nil, nil
+ }
+ since := *row.EmptySince
+ return &machineReclaimLock{
+ tx: tx, digest: digest, emptySince: since,
+ configTenantID: row.ConfigTenantID, configID: row.ConfigID,
+ }, nil
+}
+
+// machineReclaimLock holds one registry row until the provider delete finishes.
+type machineReclaimLock struct {
+ tx *gorm.DB
+ digest string
+ emptySince time.Time
+ configTenantID uint64
+ configID string
+ done bool
+}
+
+func (l *machineReclaimLock) Claim() interfaces.EmptyMachineClaim {
+ return interfaces.EmptyMachineClaim{
+ EmptySince: l.emptySince, ConfigTenantID: l.configTenantID, ConfigID: l.configID,
+ }
+}
+
+func (l *machineReclaimLock) Abort() {
+ if l == nil || l.done {
+ return
+ }
+ l.done = true
+ l.tx.Rollback()
+}
+
+func (l *machineReclaimLock) CommitDelete() (bool, error) {
+ if l == nil || l.done {
+ return false, errors.New("sandbox allocation: reclaim lock is already closed")
+ }
+ l.done = true
+ live, err := countLive(l.tx, l.digest)
+ if err != nil {
+ l.tx.Rollback()
+ return false, err
+ }
+ if live > 0 {
+ l.tx.Rollback()
+ return false, nil
+ }
+ res := l.tx.Where("machine_digest = ? AND empty_since = ?", l.digest, l.emptySince).
+ Delete(&types.SandboxUserMachine{})
+ if res.Error != nil || res.RowsAffected == 0 {
+ l.tx.Rollback()
+ return false, res.Error
+ }
+ if err := l.tx.Commit().Error; err != nil {
+ l.tx.Rollback()
+ return false, err
+ }
+ return true, nil
+}
+
+// DeleteUserMachinesAndSandboxConfig removes the config's user-machine rows
+// and soft-deletes the config in one transaction. A missing config rolls
+// the machine delete back, so a failed config delete cannot leave sessions
+// pointing at a registry that cleanup treats as already gone.
+func DeleteUserMachinesAndSandboxConfig(
+ ctx context.Context, db *gorm.DB, tenantID uint64, configID string,
+) error {
+ return db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
+ if err := tx.Where("config_tenant_id = ? AND config_id = ?", tenantID, configID).
+ Delete(&types.SandboxUserMachine{}).Error; err != nil {
+ return err
+ }
+ res := tx.Where("tenant_id = ? AND id = ?", tenantID, configID).
+ Delete(&types.TenantSandboxConfigEntity{})
+ if res.Error != nil {
+ return res.Error
+ }
+ if res.RowsAffected == 0 {
+ return gorm.ErrRecordNotFound
+ }
+ return nil
+ })
+}
+
func (r *sandboxAllocationRepository) ListDueWorkspaceCleanups(
ctx context.Context, now time.Time, limit int,
) ([]*types.SessionSandboxAssignment, error) {
diff --git a/internal/application/repository/sandbox_allocation_test.go b/internal/application/repository/sandbox_allocation_test.go
index 68335fadb..d40aea214 100644
--- a/internal/application/repository/sandbox_allocation_test.go
+++ b/internal/application/repository/sandbox_allocation_test.go
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
+ "os"
"path/filepath"
"strings"
"sync"
@@ -12,6 +13,7 @@ import (
"github.com/google/uuid"
"github.com/stretchr/testify/require"
+ "gorm.io/driver/postgres"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
@@ -40,6 +42,45 @@ func newAllocationRepo(t *testing.T) (*sandboxAllocationRepository, *gorm.DB) {
return NewSandboxAllocationRepository(db).(*sandboxAllocationRepository), db
}
+// integrationEnv returns an integration dependency's address. Missing, the
+// test is skipped — unless WEKNORA_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("WEKNORA_REQUIRE_INTEGRATION") == "1" {
+ t.Fatalf("%s is required when WEKNORA_REQUIRE_INTEGRATION=1", name)
+ }
+ t.Skipf("set %s to run against a real dependency", name)
+ return ""
+}
+
+// allocationBackends runs fn on SQLite and, when a disposable Postgres is
+// configured, on Postgres. Session ids in fn must be unique: the Postgres
+// database is shared and is not cleaned between runs.
+func allocationBackends(t *testing.T, fn func(t *testing.T, repo *sandboxAllocationRepository, db *gorm.DB)) {
+ t.Helper()
+ t.Run("sqlite", func(t *testing.T) {
+ repo, db := newAllocationRepo(t)
+ fn(t, repo, db)
+ })
+ t.Run("postgres", func(t *testing.T) {
+ dsn := integrationEnv(t, "WEKNORA_REPOSITORY_TEST_POSTGRES_DSN")
+ 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{},
+ ))
+ fn(t, NewSandboxAllocationRepository(db).(*sandboxAllocationRepository), db)
+ })
+}
+
func seedSession(t *testing.T, db *gorm.DB, id string, pin interfaces.PlacementPin) {
t.Helper()
s := &types.Session{
@@ -49,6 +90,80 @@ func seedSession(t *testing.T, db *gorm.DB, id string, pin interfaces.PlacementP
require.NoError(t, db.Session(&gorm.Session{SkipHooks: true}).Create(s).Error)
}
+func TestDeleteSessionsRetiringChecksTenantAndOwner(t *testing.T) {
+ allocationBackends(t, func(t *testing.T, repo *sandboxAllocationRepository, db *gorm.DB) {
+ ctx := context.Background()
+ own, otherOwner, otherTenant, legacy := uuid.NewString(), uuid.NewString(), uuid.NewString(), uuid.NewString()
+ for _, row := range []*types.Session{
+ {ID: own, TenantID: 7, UserID: "u-1"},
+ {ID: otherOwner, TenantID: 7, UserID: "u-2"},
+ {ID: otherTenant, TenantID: 8, UserID: "u-1"},
+ {ID: legacy, TenantID: 7, UserID: ""},
+ } {
+ require.NoError(t, db.Session(&gorm.Session{SkipHooks: true}).Create(row).Error)
+ }
+ retired, err := repo.DeleteSessionsRetiring(ctx, 7, map[string][]string{
+ "u-1": {own, own, otherOwner, otherTenant, uuid.NewString()},
+ "": {legacy},
+ }, time.Now())
+ require.NoError(t, err)
+ require.Len(t, retired, 2)
+ for _, id := range []string{own, legacy} {
+ var row types.Session
+ require.ErrorIs(t, db.Where("id = ?", id).Take(&row).Error, gorm.ErrRecordNotFound)
+ a, err := repo.GetAssignment(ctx, id)
+ require.NoError(t, err)
+ require.True(t, a.IsTombstone())
+ }
+ for _, id := range []string{otherOwner, otherTenant} {
+ var row types.Session
+ require.NoError(t, db.Where("id = ?", id).Take(&row).Error)
+ a, err := repo.GetAssignment(ctx, id)
+ require.NoError(t, err)
+ require.Nil(t, a, "out-of-scope sessions must not even acquire retirement tombstones")
+ }
+ })
+}
+
+func TestDeleteSessionsRetiringRollsBackEveryOwnerOnDeleteFailure(t *testing.T) {
+ allocationBackends(t, func(t *testing.T, repo *sandboxAllocationRepository, db *gorm.DB) {
+ ctx := context.Background()
+ placed, unplaced, digest := uuid.NewString(), uuid.NewString(), uuid.NewString()
+ seedSession(t, db, placed, interfaces.PlacementPin{})
+ require.NoError(t, db.Session(&gorm.Session{SkipHooks: true}).Create(&types.Session{
+ ID: unplaced, TenantID: 7, UserID: "u-2",
+ }).Error)
+ _, err := claim(ctx, repo, userAssignment(placed, digest), interfaces.PlacementPin{})
+ require.NoError(t, err)
+ boom := errors.New("injected soft-delete failure")
+ require.NoError(t, db.Callback().Delete().Before("gorm:delete").Register(
+ "reject_session_delete", func(tx *gorm.DB) {
+ if tx.Statement.Table == "sessions" {
+ _ = tx.AddError(boom)
+ }
+ }))
+ retired, err := repo.DeleteSessionsRetiring(ctx, 7, map[string][]string{
+ "u-1": {placed}, "u-2": {unplaced},
+ }, time.Now())
+ require.ErrorIs(t, err, boom)
+ require.Nil(t, retired)
+ for _, id := range []string{placed, unplaced} {
+ var row types.Session
+ require.NoError(t, db.Where("id = ?", id).Take(&row).Error)
+ }
+ a, err := repo.GetAssignment(ctx, placed)
+ require.NoError(t, err)
+ require.Nil(t, a.ReleasedAt)
+ require.Nil(t, a.CleanupDueAt)
+ a, err = repo.GetAssignment(ctx, unplaced)
+ require.NoError(t, err)
+ require.Nil(t, a, "rollback must remove the new tombstone too")
+ m, err := repo.GetUserMachine(ctx, digest)
+ require.NoError(t, err)
+ require.Nil(t, m.EmptySince)
+ })
+}
+
func userAssignment(sessionID, digest string) *types.SessionSandboxAssignment {
return &types.SessionSandboxAssignment{
SessionID: sessionID, ConfigTenantID: 7, ConfigID: "cfg", MachineDigest: digest,
@@ -105,38 +220,41 @@ func TestClaimPlacementWritesAssignmentAndPinTogether(t *testing.T) {
}
func TestClaimPlacementFirstWriterWinsAndPinFollowsTheWinner(t *testing.T) {
- repo, db := newAllocationRepo(t)
- ctx := context.Background()
- seedSession(t, db, "s-1", interfaces.PlacementPin{})
- var wg sync.WaitGroup
- results := make(chan string, 8)
- for i := 0; i < 8; i++ {
- wg.Add(1)
- go func(i int) {
- defer wg.Done()
- a := userAssignment("s-1", "d-1")
- if i%2 == 1 {
- a.MachineDigest, a.ConfigID = "", "cfg-b"
- }
- w, err := claim(ctx, repo, a, interfaces.PlacementPin{})
- if errors.Is(err, interfaces.ErrPlacementConflict) {
- // The winner already pinned the row; a racer that re-reads adopts it.
- w, err = claim(ctx, repo, a, readPin(t, db, "s-1"))
+ allocationBackends(t, func(t *testing.T, repo *sandboxAllocationRepository, db *gorm.DB) {
+ ctx := context.Background()
+ id := uuid.NewString()
+ digest := "d-" + uuid.NewString()
+ seedSession(t, db, id, interfaces.PlacementPin{})
+ var wg sync.WaitGroup
+ results := make(chan string, 8)
+ for i := 0; i < 8; i++ {
+ wg.Add(1)
+ go func(i int) {
+ defer wg.Done()
+ a := userAssignment(id, digest)
+ if i%2 == 1 {
+ a.MachineDigest, a.ConfigID = "", "cfg-b"
+ }
+ w, err := claim(ctx, repo, a, interfaces.PlacementPin{})
+ if errors.Is(err, interfaces.ErrPlacementConflict) {
+ // The winner already pinned the row; a racer that re-reads adopts it.
+ w, err = claim(ctx, repo, a, readPin(t, db, id))
+ }
+ require.NoError(t, err)
+ results <- w.ConfigID
+ }(i)
+ }
+ wg.Wait()
+ close(results)
+ winner := ""
+ for c := range results {
+ if winner == "" {
+ winner = c
}
- require.NoError(t, err)
- results <- w.ConfigID
- }(i)
- }
- wg.Wait()
- close(results)
- winner := ""
- for c := range results {
- if winner == "" {
- winner = c
+ require.Equal(t, winner, c, "every racer ends on one persisted placement")
}
- require.Equal(t, winner, c, "every racer ends on one persisted placement")
- }
- require.Equal(t, winner, readPin(t, db, "s-1").ConfigID, "the pin is the winner's projection")
+ require.Equal(t, winner, readPin(t, db, id).ConfigID, "the pin is the winner's projection")
+ })
}
func TestClaimPlacementRefusesAStalePinRead(t *testing.T) {
@@ -191,27 +309,29 @@ func TestRetireWithoutAnAssignmentBlocksALaterPlacement(t *testing.T) {
}
func TestRetireAndPlacementInEitherOrderLeaveNothingLive(t *testing.T) {
- repo, db := newAllocationRepo(t)
- ctx := context.Background()
+ allocationBackends(t, func(t *testing.T, repo *sandboxAllocationRepository, db *gorm.DB) {
+ ctx := context.Background()
+ digest := "d-" + uuid.NewString()
- placedFirst := uuid.NewString()
- seedSession(t, db, placedFirst, interfaces.PlacementPin{})
- _, err := claim(ctx, repo, userAssignment(placedFirst, "d-race"), interfaces.PlacementPin{})
- require.NoError(t, err)
- out, err := repo.RetireSessions(ctx, []string{placedFirst}, time.Now().UTC())
- require.NoError(t, err)
- require.NotNil(t, out[0].Assignment.CleanupDueAt, "a placement that won is released with its cleanup")
+ placedFirst := uuid.NewString()
+ seedSession(t, db, placedFirst, interfaces.PlacementPin{})
+ _, err := claim(ctx, repo, userAssignment(placedFirst, digest), interfaces.PlacementPin{})
+ require.NoError(t, err)
+ out, err := repo.RetireSessions(ctx, []string{placedFirst}, time.Now().UTC())
+ require.NoError(t, err)
+ require.NotNil(t, out[0].Assignment.CleanupDueAt, "a placement that won is released with its cleanup")
- retiredFirst := uuid.NewString()
- seedSession(t, db, retiredFirst, interfaces.PlacementPin{})
- _, err = repo.RetireSessions(ctx, []string{retiredFirst}, time.Now().UTC())
- require.NoError(t, err)
- _, err = claim(ctx, repo, userAssignment(retiredFirst, "d-race"), interfaces.PlacementPin{})
- require.ErrorIs(t, err, interfaces.ErrSessionRetired, "a placement that lost never lands")
+ retiredFirst := uuid.NewString()
+ seedSession(t, db, retiredFirst, interfaces.PlacementPin{})
+ _, err = repo.RetireSessions(ctx, []string{retiredFirst}, time.Now().UTC())
+ require.NoError(t, err)
+ _, err = claim(ctx, repo, userAssignment(retiredFirst, digest), interfaces.PlacementPin{})
+ require.ErrorIs(t, err, interfaces.ErrSessionRetired, "a placement that lost never lands")
- live, err := repo.CountLiveAssignments(ctx, "d-race")
- require.NoError(t, err)
- require.Zero(t, live)
+ live, err := repo.CountLiveAssignments(ctx, digest)
+ require.NoError(t, err)
+ require.Zero(t, live)
+ })
}
func TestRetireSessionsDedupesAndKeepsOrder(t *testing.T) {
@@ -229,6 +349,68 @@ func TestRetireSessionsDedupesAndKeepsOrder(t *testing.T) {
require.True(t, out[1].MachineEmpty)
}
+func TestRetireOwnerSessionsEmptiesEveryMachineAndBlocksNewPlacements(t *testing.T) {
+ repo, db := newAllocationRepo(t)
+ ctx := context.Background()
+ seedSession(t, db, "s-1", interfaces.PlacementPin{})
+ seedSession(t, db, "s-2", interfaces.PlacementPin{})
+ seedSession(t, db, "s-3", interfaces.PlacementPin{}) // not placed yet
+ _, err := claim(ctx, repo, userAssignment("s-1", "d-1"), interfaces.PlacementPin{})
+ require.NoError(t, err)
+ other := userAssignment("s-2", "d-2")
+ other.ConfigID = "cfg-b"
+ _, err = claim(ctx, repo, other, interfaces.PlacementPin{})
+ require.NoError(t, err)
+
+ out, err := repo.RetireOwnerSessions(ctx, "u-1", time.Now().UTC())
+ require.NoError(t, err)
+ require.Len(t, out, 3)
+ _, err = claim(ctx, repo, userAssignment("s-3", "d-1"), interfaces.PlacementPin{})
+ require.ErrorIs(t, err, interfaces.ErrSessionRetired, "a request in flight cannot place after the account is gone")
+ for _, d := range []string{"d-1", "d-2"} {
+ m, _ := repo.GetUserMachine(ctx, d)
+ require.NotNil(t, m.EmptySince, d)
+ live, _ := repo.CountLiveAssignments(ctx, d)
+ require.Zero(t, live, d)
+ }
+}
+
+// A session row can leave the account while its live assignment stays on the
+// account's machine. Retiring the account must release that assignment too,
+// and a session of the account in another tenant is retired with the rest.
+func TestRetireOwnerSessionsReleasesStrandedAssignmentsAndOtherTenants(t *testing.T) {
+ repo, db := newAllocationRepo(t)
+ ctx := context.Background()
+ seedSession(t, db, "s-own", interfaces.PlacementPin{})
+ _, err := claim(ctx, repo, userAssignment("s-own", "d-1"), interfaces.PlacementPin{})
+ require.NoError(t, err)
+
+ stranded := &types.Session{ID: "s-stranded", TenantID: 8, UserID: "u-2"}
+ require.NoError(t, db.Session(&gorm.Session{SkipHooks: true}).Create(stranded).Error)
+ _, err = claim(ctx, repo, userAssignment("s-stranded", "d-1"), interfaces.PlacementPin{})
+ require.NoError(t, err)
+
+ otherTenant := &types.Session{ID: "s-other-tenant", TenantID: 9, UserID: "u-1"}
+ require.NoError(t, db.Session(&gorm.Session{SkipHooks: true}).Create(otherTenant).Error)
+
+ out, err := repo.RetireOwnerSessions(ctx, "u-1", time.Now().UTC())
+ require.NoError(t, err)
+ got := make([]string, 0, len(out))
+ for _, row := range out {
+ got = append(got, row.SessionID)
+ }
+ require.ElementsMatch(t, []string{"s-own", "s-stranded", "s-other-tenant"}, got)
+
+ _, err = claim(ctx, repo, userAssignment("s-other-tenant", "d-1"), interfaces.PlacementPin{})
+ require.ErrorIs(t, err, interfaces.ErrSessionRetired)
+ live, err := repo.CountLiveAssignments(ctx, "d-1")
+ require.NoError(t, err)
+ require.Zero(t, live)
+ m, err := repo.GetUserMachine(ctx, "d-1")
+ require.NoError(t, err)
+ require.NotNil(t, m.EmptySince)
+}
+
func TestListEmptyUserMachinesPagesPastSkippedCandidates(t *testing.T) {
repo, db := newAllocationRepo(t)
ctx := context.Background()
@@ -253,41 +435,47 @@ func TestListEmptyUserMachinesPagesPastSkippedCandidates(t *testing.T) {
}
func TestReleaseRecordsCleanupIntentAndEmptiesTheLastSession(t *testing.T) {
- repo, db := newAllocationRepo(t)
- ctx := context.Background()
- for _, id := range []string{"s-1", "s-2"} {
- seedSession(t, db, id, interfaces.PlacementPin{})
- _, err := claim(ctx, repo, userAssignment(id, "d-1"), interfaces.PlacementPin{})
- require.NoError(t, err)
- }
- now := time.Now().UTC().Truncate(time.Second)
-
- a, empty, err := retireOne(ctx, repo, "s-1", now)
- require.NoError(t, err)
- require.NotNil(t, a.ReleasedAt)
- require.False(t, empty)
- require.NotNil(t, a.CleanupDueAt, "the cleanup intent is written with the release")
+ allocationBackends(t, func(t *testing.T, repo *sandboxAllocationRepository, db *gorm.DB) {
+ ctx := context.Background()
+ firstID, secondID := uuid.NewString(), uuid.NewString()
+ digest := "d-" + uuid.NewString()
+ for _, id := range []string{firstID, secondID} {
+ seedSession(t, db, id, interfaces.PlacementPin{})
+ _, err := claim(ctx, repo, userAssignment(id, digest), interfaces.PlacementPin{})
+ require.NoError(t, err)
+ }
+ now := time.Now().UTC().Truncate(time.Second)
- _, empty, err = retireOne(ctx, repo, "s-2", now)
- require.NoError(t, err)
- require.True(t, empty)
- m, _ := repo.GetUserMachine(ctx, "d-1")
- require.NotNil(t, m.EmptySince)
+ a, empty, err := retireOne(ctx, repo, firstID, now)
+ require.NoError(t, err)
+ require.NotNil(t, a.ReleasedAt)
+ require.False(t, empty)
+ require.NotNil(t, a.CleanupDueAt, "the cleanup intent is written with the release")
- require.NoError(t, repo.CompleteWorkspaceCleanup(ctx, "s-2"))
- _, _, err = retireOne(ctx, repo, "s-2", now.Add(time.Hour))
- require.NoError(t, err)
- row, _ := repo.GetAssignment(ctx, "s-2")
- require.Nil(t, row.CleanupDueAt, "a second release records nothing new")
- require.True(t, row.ReleasedAt.Equal(now), "nor moves the release time")
- require.NoError(t, repo.RetryWorkspaceCleanup(ctx, "s-2", now))
- row, _ = repo.GetAssignment(ctx, "s-2")
- require.Nil(t, row.CleanupDueAt, "a completed cleanup is not revived by a late retry")
+ _, empty, err = retireOne(ctx, repo, secondID, now)
+ require.NoError(t, err)
+ require.True(t, empty)
+ m, _ := repo.GetUserMachine(ctx, digest)
+ require.NotNil(t, m.EmptySince)
- due, err := repo.ListDueWorkspaceCleanups(ctx, now.Add(time.Second), 10)
- require.NoError(t, err)
- require.Len(t, due, 1)
- require.Equal(t, "s-1", due[0].SessionID)
+ require.NoError(t, repo.CompleteWorkspaceCleanup(ctx, secondID))
+ _, _, err = retireOne(ctx, repo, secondID, now.Add(time.Hour))
+ require.NoError(t, err)
+ row, _ := repo.GetAssignment(ctx, secondID)
+ require.Nil(t, row.CleanupDueAt, "a second release records nothing new")
+ require.True(t, row.ReleasedAt.Equal(now), "nor moves the release time")
+ require.NoError(t, repo.RetryWorkspaceCleanup(ctx, secondID, now))
+ row, _ = repo.GetAssignment(ctx, secondID)
+ require.Nil(t, row.CleanupDueAt, "a completed cleanup is not revived by a late retry")
+
+ // Read this session back. A limited ListDueWorkspaceCleanups page is
+ // filled by older due rows left on a shared Postgres.
+ first, err := repo.GetAssignment(ctx, firstID)
+ require.NoError(t, err)
+ require.NotNil(t, first)
+ require.NotNil(t, first.CleanupDueAt)
+ require.False(t, first.CleanupDueAt.After(now.Add(time.Second)))
+ })
}
func TestReleaseOfASessionModeAssignmentHasNoCleanup(t *testing.T) {
@@ -305,27 +493,30 @@ func TestReleaseOfASessionModeAssignmentHasNoCleanup(t *testing.T) {
}
func TestDeleteUserMachineIfEmptySinceComparesTheClock(t *testing.T) {
- repo, db := newAllocationRepo(t)
- ctx := context.Background()
- seedSession(t, db, "s-1", interfaces.PlacementPin{})
- _, _ = claim(ctx, repo, userAssignment("s-1", "d-1"), interfaces.PlacementPin{})
- first := time.Now().UTC().Add(-10 * 24 * time.Hour).Truncate(time.Second)
- _, _, err := retireOne(ctx, repo, "s-1", first)
- require.NoError(t, err)
+ allocationBackends(t, func(t *testing.T, repo *sandboxAllocationRepository, db *gorm.DB) {
+ ctx := context.Background()
+ firstID, secondID := uuid.NewString(), uuid.NewString()
+ digest := "d-" + uuid.NewString()
+ seedSession(t, db, firstID, interfaces.PlacementPin{})
+ _, _ = claim(ctx, repo, userAssignment(firstID, digest), interfaces.PlacementPin{})
+ first := time.Now().UTC().Add(-10 * 24 * time.Hour).Truncate(time.Second)
+ _, _, err := retireOne(ctx, repo, firstID, first)
+ require.NoError(t, err)
- // Someone joined and left after the reclaimer read the row: a new clock.
- seedSession(t, db, "s-2", interfaces.PlacementPin{})
- _, _ = claim(ctx, repo, userAssignment("s-2", "d-1"), interfaces.PlacementPin{})
- second := time.Now().UTC().Truncate(time.Second)
- _, _, _ = retireOne(ctx, repo, "s-2", second)
+ // Someone joined and left after the reclaimer read the row: a new clock.
+ seedSession(t, db, secondID, interfaces.PlacementPin{})
+ _, _ = claim(ctx, repo, userAssignment(secondID, digest), interfaces.PlacementPin{})
+ second := time.Now().UTC().Truncate(time.Second)
+ _, _, _ = retireOne(ctx, repo, secondID, second)
- deleted, err := repo.DeleteUserMachineIfEmptySince(ctx, "d-1", first)
- require.NoError(t, err)
- require.False(t, deleted, "the verified clock is gone; the new empty period must run its full window")
+ deleted, err := repo.DeleteUserMachineIfEmptySince(ctx, digest, first)
+ require.NoError(t, err)
+ require.False(t, deleted, "the verified clock is gone; the new empty period must run its full window")
- deleted, err = repo.DeleteUserMachineIfEmptySince(ctx, "d-1", second)
- require.NoError(t, err)
- require.True(t, deleted)
+ deleted, err = repo.DeleteUserMachineIfEmptySince(ctx, digest, second)
+ require.NoError(t, err)
+ require.True(t, deleted)
+ })
}
func TestWorkspaceCleanupRetryAndComplete(t *testing.T) {
@@ -590,3 +781,93 @@ func TestSandboxAllocationOnTheMigratedSQLiteSchema(t *testing.T) {
require.NoError(t, err)
require.True(t, deleted)
}
+
+func TestPostgresRetireRacingFirstPlacementNeverLeavesALiveAssignment(t *testing.T) {
+ dsn := integrationEnv(t, "WEKNORA_REPOSITORY_TEST_POSTGRES_DSN")
+ 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{}))
+ repo := NewSandboxAllocationRepository(db).(*sandboxAllocationRepository)
+ ctx := context.Background()
+ digest := "d-" + uuid.NewString()
+ for i := 0; i < 50; i++ {
+ id := uuid.NewString()
+ seedSession(t, db, id, interfaces.PlacementPin{})
+ var wg sync.WaitGroup
+ wg.Add(2)
+ go func() {
+ defer wg.Done()
+ _, err := claim(ctx, repo, userAssignment(id, digest), interfaces.PlacementPin{})
+ if err != nil {
+ require.ErrorIs(t, err, interfaces.ErrSessionRetired)
+ }
+ }()
+ go func() {
+ defer wg.Done()
+ _, err := repo.RetireSessions(ctx, []string{id}, time.Now().UTC())
+ require.NoError(t, err)
+ }()
+ wg.Wait()
+ }
+ live, err := repo.CountLiveAssignments(ctx, digest)
+ require.NoError(t, err)
+ require.Zero(t, live, "whichever commits first, every session ends retired with nothing live")
+}
+
+func TestLockEmptyMachineRejectsAClearedClock(t *testing.T) {
+ repo, db := newAllocationRepo(t)
+ ctx := context.Background()
+ since := time.Now().UTC().Truncate(time.Microsecond)
+ row := &types.SandboxUserMachine{
+ MachineDigest: "d-cleared", OwnerTenantID: 7, OwnerID: "u-1",
+ ConfigTenantID: 7, ConfigID: "cfg-a", EmptySince: &since,
+ }
+ require.NoError(t, db.Create(row).Error)
+ require.NoError(t, db.Exec(
+ "UPDATE sandbox_user_machines SET empty_since = NULL WHERE machine_digest = ?", row.MachineDigest,
+ ).Error)
+
+ lock, err := repo.LockEmptyMachine(ctx, row.MachineDigest)
+ require.NoError(t, err)
+ if lock != nil {
+ lock.Abort()
+ }
+ require.Nil(t, lock)
+
+ var kept types.SandboxUserMachine
+ require.NoError(t, db.Where("machine_digest = ?", row.MachineDigest).Take(&kept).Error)
+ require.Nil(t, kept.EmptySince)
+}
+
+func TestDeleteUserMachinesAndSandboxConfigRollsBackWhenTheConfigIsGone(t *testing.T) {
+ _, db := newAllocationRepo(t)
+ require.NoError(t, db.AutoMigrate(&types.TenantSandboxConfigEntity{}))
+ ctx := context.Background()
+ require.NoError(t, db.Create(&types.SandboxUserMachine{
+ MachineDigest: "d-orphan", OwnerTenantID: 7, OwnerID: "u-1",
+ ConfigTenantID: 7, ConfigID: "missing",
+ }).Error)
+ require.NoError(t, db.Create(&types.TenantSandboxConfigEntity{
+ ID: "cfg-a", TenantID: 7, Name: "prod", SandboxType: "docker",
+ }).Error)
+ require.NoError(t, db.Create(&types.SandboxUserMachine{
+ MachineDigest: "d-cfg", OwnerTenantID: 7, OwnerID: "u-1",
+ ConfigTenantID: 7, ConfigID: "cfg-a",
+ }).Error)
+
+ err := DeleteUserMachinesAndSandboxConfig(ctx, db, 7, "missing")
+ require.ErrorIs(t, err, gorm.ErrRecordNotFound)
+ var orphan types.SandboxUserMachine
+ require.NoError(t, db.Where("machine_digest = ?", "d-orphan").Take(&orphan).Error)
+
+ require.NoError(t, DeleteUserMachinesAndSandboxConfig(ctx, db, 7, "cfg-a"))
+ var n int64
+ require.NoError(t, db.Model(&types.SandboxUserMachine{}).Where("config_id = ?", "cfg-a").Count(&n).Error)
+ require.Zero(t, n)
+ var cfg types.TenantSandboxConfigEntity
+ require.ErrorIs(t, db.Where("id = ?", "cfg-a").Take(&cfg).Error, gorm.ErrRecordNotFound)
+}
diff --git a/internal/application/repository/session.go b/internal/application/repository/session.go
index fc3c9a257..67e81ce91 100644
--- a/internal/application/repository/session.go
+++ b/internal/application/repository/session.go
@@ -3,6 +3,7 @@ package repository
import (
"context"
stderrors "errors"
+ "fmt"
"strings"
"time"
@@ -30,14 +31,20 @@ func NewSessionRepository(db *gorm.DB) interfaces.SessionRepository {
return &sessionRepository{db: db}
}
-// Create creates a new session
+// Create creates a new session. A canonical web owner is locked first so the
+// insert cannot land between account deletion's session list and the user
+// row's soft-delete. A deleted owner returns errWebUserDeleted.
func (r *sessionRepository) Create(ctx context.Context, session *types.Session) (*types.Session, error) {
session.CreatedAt = time.Now()
session.UpdatedAt = time.Now()
- if err := r.db.WithContext(ctx).Create(session).Error; err != nil {
+ if err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
+ if err := lockLiveWebUser(tx, session.UserID); err != nil {
+ return err
+ }
+ return tx.Create(session).Error
+ }); err != nil {
return nil, err
}
- // Return the session with generated ID
return session, nil
}
@@ -414,8 +421,26 @@ func (r *sessionRepository) DeleteAllByTenantID(ctx context.Context, tenantID ui
// empty conversation, so both halves must land together.
func (r *sessionRepository) CreateForked(
ctx context.Context, session *types.Session, messages []*types.Message,
+) error {
+ return r.CreateForkedWithAssignment(ctx, session, messages, nil, nil)
+}
+
+// CreateForkedWithAssignment additionally records the fork's inherited
+// sandbox assignment in the same transaction, so a user-mode branch can never
+// exist without its placement. A nil assignment is CreateForked.
+//
+// The canonical web user is locked before the session row, and the machine
+// row is locked inside InsertSandboxAssignmentTx after that insert. If this
+// session already has an assignment, the insert fails and this transaction's
+// session row is rolled back.
+func (r *sessionRepository) CreateForkedWithAssignment(
+ ctx context.Context, session *types.Session, messages []*types.Message,
+ assignment *types.SessionSandboxAssignment, machine *types.SandboxUserMachine,
) error {
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
+ if err := lockLiveWebUser(tx, session.UserID); err != nil {
+ return err
+ }
now := time.Now()
session.CreatedAt = now
session.UpdatedAt = now
@@ -425,14 +450,26 @@ func (r *sessionRepository) CreateForked(
if err := tx.Session(&gorm.Session{SkipHooks: true}).Create(session).Error; err != nil {
return err
}
- if len(messages) == 0 {
+ if len(messages) > 0 {
+ if err := tx.Session(&gorm.Session{SkipHooks: true}).
+ CreateInBatches(messages, 100).Error; err != nil {
+ return err
+ }
+ if err := insertMessageArtifacts(tx, messages); err != nil {
+ return err
+ }
+ }
+ if assignment == nil {
return nil
}
- if err := tx.Session(&gorm.Session{SkipHooks: true}).
- CreateInBatches(messages, 100).Error; err != nil {
+ created, err := InsertSandboxAssignmentTx(tx, assignment, machine)
+ if err != nil {
return err
}
- return insertMessageArtifacts(tx, messages)
+ if !created {
+ return fmt.Errorf("fork %s already has a sandbox assignment", session.ID)
+ }
+ return nil
})
}
diff --git a/internal/application/repository/session_fork_test.go b/internal/application/repository/session_fork_test.go
index 1acde9bd6..ae757e2bc 100644
--- a/internal/application/repository/session_fork_test.go
+++ b/internal/application/repository/session_fork_test.go
@@ -2,6 +2,7 @@ package repository
import (
"context"
+ "strings"
"testing"
"time"
@@ -67,6 +68,96 @@ func TestCreateForkedPersistsSessionAndCopiedMessages(t *testing.T) {
require.Equal(t, []string{"copy-1", "copy-2"}, messageIDs(stored))
}
+func TestCreateForkedWithAssignmentPersistsPlacementAndRollsBackARepeat(t *testing.T) {
+ repo, db := newSessionRepositoryForForkTest(t)
+ require.NoError(t, db.AutoMigrate(&types.SessionSandboxAssignment{}, &types.SandboxUserMachine{}))
+ ctx := context.Background()
+ digest := strings.Repeat("ab", 32)
+ const sessionID = "fork-user-1"
+ session := &types.Session{
+ ID: sessionID, TenantID: 1, UserID: "u1", Title: "branched",
+ SandboxConfigID: "cfg-1", ParentSessionID: "src",
+ }
+ messages := []*types.Message{
+ {ID: "copy-u", SessionID: sessionID, Role: "user", CreatedAt: time.Date(2026, 9, 10, 9, 0, 0, 0, time.UTC)},
+ }
+ assignment := &types.SessionSandboxAssignment{
+ SessionID: sessionID, ConfigTenantID: 1, ConfigID: "cfg-1", MachineDigest: digest,
+ }
+ machine := &types.SandboxUserMachine{
+ MachineDigest: digest, OwnerTenantID: 1, OwnerID: "u1",
+ ConfigTenantID: 1, ConfigID: "cfg-1",
+ }
+
+ require.NoError(t,
+ repo.(*sessionRepository).CreateForkedWithAssignment(ctx, session, messages, assignment, machine))
+
+ var row types.SessionSandboxAssignment
+ require.NoError(t, db.Where("session_id = ?", sessionID).Take(&row).Error)
+ require.Equal(t, digest, row.MachineDigest)
+ require.Equal(t, "cfg-1", row.ConfigID)
+ require.Nil(t, row.ReleasedAt)
+
+ var stored types.SandboxUserMachine
+ require.NoError(t, db.Where("machine_digest = ?", digest).Take(&stored).Error)
+ require.Nil(t, stored.EmptySince)
+ require.Equal(t, "u1", stored.OwnerID)
+
+ var sessions int64
+ require.NoError(t, db.Model(&types.Session{}).Where("id = ?", sessionID).Count(&sessions).Error)
+ require.Equal(t, int64(1), sessions)
+
+ again := &types.Session{ID: sessionID, TenantID: 1, UserID: "u1", Title: "again"}
+ err := repo.(*sessionRepository).CreateForkedWithAssignment(ctx, again, []*types.Message{
+ {ID: "copy-extra", SessionID: sessionID, Role: "user"},
+ }, assignment, machine)
+ require.Error(t, err)
+ require.NoError(t, db.Model(&types.Session{}).Where("id = ?", sessionID).Count(&sessions).Error)
+ require.Equal(t, int64(1), sessions, "the failed repeat rolls back and does not write a second session row")
+ var extras int64
+ require.NoError(t, db.Model(&types.Message{}).Where("id = ?", "copy-extra").Count(&extras).Error)
+ require.Zero(t, extras)
+}
+
+func TestCreateForkedWithAssignmentLocksWebUserBeforeSessionAndMachine(t *testing.T) {
+ repo, db := newSessionRepositoryForForkTest(t)
+ require.NoError(t, db.AutoMigrate(&types.SessionSandboxAssignment{}, &types.SandboxUserMachine{}))
+ migrateUsers(t, db)
+ ctx := context.Background()
+ owner := "11111111-1111-4111-8111-111111111111"
+ require.NoError(t, db.Create(&types.User{
+ ID: owner, Username: "fork-owner", Email: "[email protected]", PasswordHash: "x",
+ }).Error)
+ digest := strings.Repeat("cd", 32)
+ const sessionID = "fork-locked-1"
+ sawLock := false
+ sessionVisible := false
+ machineVisible := false
+ afterWebUserLock = func(tx *gorm.DB) {
+ sawLock = true
+ var n int64
+ require.NoError(t, tx.Model(&types.Session{}).Where("id = ?", sessionID).Count(&n).Error)
+ sessionVisible = n > 0
+ require.NoError(t, tx.Model(&types.SandboxUserMachine{}).Where("machine_digest = ?", digest).Count(&n).Error)
+ machineVisible = n > 0
+ }
+ t.Cleanup(func() { afterWebUserLock = nil })
+
+ err := repo.(*sessionRepository).CreateForkedWithAssignment(ctx, &types.Session{
+ ID: sessionID, TenantID: 1, UserID: owner, Title: "locked",
+ }, nil, &types.SessionSandboxAssignment{
+ SessionID: sessionID, ConfigTenantID: 1, ConfigID: "cfg-1", MachineDigest: digest,
+ }, &types.SandboxUserMachine{
+ MachineDigest: digest, OwnerTenantID: 1, OwnerID: owner,
+ ConfigTenantID: 1, ConfigID: "cfg-1",
+ })
+ afterWebUserLock = nil
+ require.NoError(t, err)
+ require.True(t, sawLock, "a canonical web owner is locked in the fork transaction")
+ require.False(t, sessionVisible, "the user row is locked before the session insert")
+ require.False(t, machineVisible, "the user row is locked before the machine row")
+}
+
func TestCreateForkedAllowsEmptyHistory(t *testing.T) {
repo, _ := newSessionRepositoryForForkTest(t)
ctx := context.Background()
diff --git a/internal/application/repository/tenant_sandbox_config.go b/internal/application/repository/tenant_sandbox_config.go
index ff5939df3..0436f295f 100644
--- a/internal/application/repository/tenant_sandbox_config.go
+++ b/internal/application/repository/tenant_sandbox_config.go
@@ -26,13 +26,32 @@ type TenantSandboxConfigRepository interface {
Update(ctx context.Context, e *types.TenantSandboxConfigEntity) error
SoftDelete(ctx context.Context, tenantID uint64, id string) error
SetCordon(ctx context.Context, tenantID uint64, id string, at time.Time) error
+ // RefreshCordon moves cordoned_at from previous to next only while the
+ // row still holds previous. Zero rows means another request owns the cordon.
+ RefreshCordon(ctx context.Context, tenantID uint64, id string, previous, next time.Time) error
ClearCordon(ctx context.Context, tenantID uint64, id string) error
+ // ClearCordonIf clears cordoned_at only when it still equals at. Zero
+ // rows is success: someone else owns the cordon.
+ ClearCordonIf(ctx context.Context, tenantID uint64, id string, at time.Time) error
}
type tenantSandboxConfigRepository struct {
db *gorm.DB
}
+// GormDB is the database this repository writes.
+func (r *tenantSandboxConfigRepository) GormDB() *gorm.DB { return r.db }
+
+// GormDB returns the database behind a repository that exposes one.
+func GormDB(repo any) *gorm.DB {
+ type holder interface{ GormDB() *gorm.DB }
+ h, ok := repo.(holder)
+ if !ok || h == nil {
+ return nil
+ }
+ return h.GormDB()
+}
+
// NewTenantSandboxConfigRepository returns a GORM-backed implementation.
func NewTenantSandboxConfigRepository(db *gorm.DB) TenantSandboxConfigRepository {
return &tenantSandboxConfigRepository{db: db}
@@ -142,6 +161,22 @@ func (r *tenantSandboxConfigRepository) SetCordon(
return nil
}
+func (r *tenantSandboxConfigRepository) RefreshCordon(
+ ctx context.Context, tenantID uint64, id string, previous, next time.Time,
+) error {
+ result := r.db.WithContext(ctx).
+ Model(&types.TenantSandboxConfigEntity{}).
+ Where("tenant_id = ? AND id = ? AND cordoned_at = ?", tenantID, id, previous).
+ Update("cordoned_at", next)
+ if result.Error != nil {
+ return result.Error
+ }
+ if result.RowsAffected == 0 {
+ return ErrSandboxConfigCordoned
+ }
+ return nil
+}
+
func (r *tenantSandboxConfigRepository) ClearCordon(
ctx context.Context, tenantID uint64, id string,
) error {
@@ -150,3 +185,12 @@ func (r *tenantSandboxConfigRepository) ClearCordon(
Where("tenant_id = ? AND id = ?", tenantID, id).
Update("cordoned_at", nil).Error
}
+
+func (r *tenantSandboxConfigRepository) ClearCordonIf(
+ ctx context.Context, tenantID uint64, id string, at time.Time,
+) error {
+ return r.db.WithContext(ctx).
+ Model(&types.TenantSandboxConfigEntity{}).
+ Where("tenant_id = ? AND id = ? AND cordoned_at = ?", tenantID, id, at).
+ Update("cordoned_at", nil).Error
+}
diff --git a/internal/application/repository/tenant_sandbox_config_test.go b/internal/application/repository/tenant_sandbox_config_test.go
index 00e89427c..18cb7b56a 100644
--- a/internal/application/repository/tenant_sandbox_config_test.go
+++ b/internal/application/repository/tenant_sandbox_config_test.go
@@ -116,3 +116,36 @@ func TestSandboxConfigRepoCordonRoundTrip(t *testing.T) {
require.NoError(t, err)
require.Nil(t, got.CordonedAt)
}
+
+func TestCordonRefreshAndClearMatchOnlyTheHeldStamp(t *testing.T) {
+ repo, _ := newSandboxConfigTestRepo(t)
+ ctx := context.Background()
+ require.NoError(t, repo.Create(ctx, &types.TenantSandboxConfigEntity{
+ ID: "cfg-a", TenantID: 1, Name: "prod", SandboxType: "e2b",
+ Config: &types.TenantSandboxConfig{SandboxType: "e2b"},
+ }))
+
+ held := time.Now().UTC().Truncate(time.Second)
+ require.NoError(t, repo.SetCordon(ctx, 1, "cfg-a", held))
+ newer := held.Add(time.Minute)
+ require.NoError(t, repo.RefreshCordon(ctx, 1, "cfg-a", held, newer))
+
+ got, err := repo.GetByID(ctx, 1, "cfg-a")
+ require.NoError(t, err)
+ require.NotNil(t, got.CordonedAt)
+ require.True(t, got.CordonedAt.Equal(newer))
+
+ err = repo.RefreshCordon(ctx, 1, "cfg-a", held, held.Add(2*time.Minute))
+ require.ErrorIs(t, err, ErrSandboxConfigCordoned)
+ require.NoError(t, repo.ClearCordonIf(ctx, 1, "cfg-a", held))
+
+ got, err = repo.GetByID(ctx, 1, "cfg-a")
+ require.NoError(t, err)
+ require.NotNil(t, got.CordonedAt)
+ require.True(t, got.CordonedAt.Equal(newer), "a newer stamp survives a stale refresh and a stale clear")
+
+ require.NoError(t, repo.ClearCordonIf(ctx, 1, "cfg-a", newer))
+ got, err = repo.GetByID(ctx, 1, "cfg-a")
+ require.NoError(t, err)
+ require.Nil(t, got.CordonedAt)
+}
diff --git a/internal/application/repository/user.go b/internal/application/repository/user.go
index f5ddc4877..6965245fe 100644
--- a/internal/application/repository/user.go
+++ b/internal/application/repository/user.go
@@ -146,6 +146,27 @@ func (r *userRepository) DeleteUser(ctx context.Context, id string) error {
return r.db.WithContext(ctx).Where("id = ?", id).Delete(&types.User{}).Error
}
+// DeleteUserRetiringSessions locks the web user, retires every session visible
+// under that lock, and soft-deletes the user in the same transaction. A user
+// row that is already soft-deleted is still held for the re-read; its sessions
+// are retired and the call returns nil.
+func (r *userRepository) DeleteUserRetiringSessions(ctx context.Context, id string, at time.Time) error {
+ return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
+ err := lockLiveWebUser(tx, id)
+ if err != nil && !errors.Is(err, errWebUserDeleted) {
+ return err
+ }
+ ids, err := ownerSessionIDs(tx, id)
+ if err != nil {
+ return err
+ }
+ if _, err := RetireSessionsTx(tx, ids, at); err != nil {
+ return err
+ }
+ return tx.Where("id = ?", id).Delete(&types.User{}).Error
+ })
+}
+
// ListUsers lists users with pagination
func (r *userRepository) ListUsers(ctx context.Context, offset, limit int) ([]*types.User, error) {
var users []*types.User
diff --git a/internal/application/repository/user_delete_retiring_test.go b/internal/application/repository/user_delete_retiring_test.go
new file mode 100644
index 000000000..fbd61483e
--- /dev/null
+++ b/internal/application/repository/user_delete_retiring_test.go
@@ -0,0 +1,140 @@
+package repository
+
+import (
+ "context"
+ "fmt"
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/stretchr/testify/require"
+ "gorm.io/driver/sqlite"
+ "gorm.io/gorm"
+ "gorm.io/gorm/logger"
+
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+)
+
+// openRetireDB is the allocation SQLite pool plus a users table, so account
+// deletion can lock the owner row. Allocation tests that never delete a web
+// user keep using newAllocationRepo and do not create users.
+func openRetireDB(t *testing.T) (*gorm.DB, *sandboxAllocationRepository, *userRepository, *sessionRepository) {
+ t.Helper()
+ 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{},
+ ))
+ migrateUsers(t, db)
+ return db,
+ NewSandboxAllocationRepository(db).(*sandboxAllocationRepository),
+ NewUserRepository(db).(*userRepository),
+ NewSessionRepository(db).(*sessionRepository)
+}
+
+// migrateUsers creates the columns soft-delete and the owner lock need.
+// AutoMigrate of types.User can fail on SQLite when the jsonb default is
+// rejected; the fallback is the same NOT NULL columns the model requires.
+func migrateUsers(t *testing.T, db *gorm.DB) {
+ t.Helper()
+ if err := db.AutoMigrate(&types.User{}); err == nil {
+ return
+ }
+ require.NoError(t, db.Exec(`
+ CREATE TABLE IF NOT EXISTS users (
+ id varchar(36) PRIMARY KEY,
+ username varchar(100) NOT NULL,
+ email varchar(255) NOT NULL,
+ password_hash varchar(255) NOT NULL,
+ avatar varchar(500),
+ tenant_id integer,
+ is_active numeric,
+ can_access_all_tenants numeric,
+ is_system_admin numeric,
+ preferences text NOT NULL DEFAULT '{}',
+ created_at datetime,
+ updated_at datetime,
+ deleted_at datetime
+ )
+ `).Error)
+}
+
+func TestDeleteUserRetiringSessionsRetiresASessionInsertedUnderTheLock(t *testing.T) {
+ db, alloc, users, sessions := openRetireDB(t)
+ ctx := context.Background()
+ owner := uuid.New().String()
+ require.NoError(t, db.Create(&types.User{
+ ID: owner, Username: "alice", Email: "[email protected]", PasswordHash: "x",
+ }).Error)
+ require.NoError(t, db.Session(&gorm.Session{SkipHooks: true}).Create(&types.Session{
+ ID: "s-1", TenantID: 7, UserID: owner,
+ }).Error)
+
+ afterWebUserLock = func(tx *gorm.DB) {
+ require.NoError(t, tx.Session(&gorm.Session{SkipHooks: true}).Create(&types.Session{
+ ID: "s-2", TenantID: 7, UserID: owner,
+ }).Error)
+ }
+ t.Cleanup(func() { afterWebUserLock = nil })
+
+ err := users.DeleteUserRetiringSessions(ctx, owner, time.Now().UTC())
+ afterWebUserLock = nil
+ require.NoError(t, err)
+
+ for _, id := range []string{"s-1", "s-2"} {
+ row, err := alloc.GetAssignment(ctx, id)
+ require.NoError(t, err)
+ require.NotNil(t, row, id)
+ require.NotNil(t, row.ReleasedAt, id)
+ }
+ var gone types.User
+ require.ErrorIs(t, db.Where("id = ?", owner).Take(&gone).Error, gorm.ErrRecordNotFound)
+ require.NoError(t, db.Unscoped().Where("id = ?", owner).Take(&gone).Error)
+ require.True(t, gone.DeletedAt.Valid)
+
+ require.NoError(t, db.Session(&gorm.Session{SkipHooks: true}).Create(&types.Session{
+ ID: "s-3", TenantID: 7, UserID: owner,
+ }).Error)
+ _, err = claim(ctx, alloc, userAssignment("s-3", "d-1"), interfaces.PlacementPin{})
+ require.ErrorIs(t, err, interfaces.ErrSessionRetired)
+ placed, err := alloc.GetAssignment(ctx, "s-3")
+ require.NoError(t, err)
+ require.Nil(t, placed, "a deleted owner never receives an assignment")
+
+ before := countSessions(t, db, owner)
+ _, err = sessions.Create(ctx, &types.Session{TenantID: 7, UserID: owner, Title: "late"})
+ require.ErrorIs(t, err, errWebUserDeleted)
+ require.Equal(t, before, countSessions(t, db, owner))
+}
+
+func TestSessionCreateAllowsANonCanonicalOwnerWithNoUsersRow(t *testing.T) {
+ // No users table at all: a non-UUID owner must not query it.
+ 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)
+ require.NoError(t, db.AutoMigrate(&types.Session{}))
+ sessions := NewSessionRepository(db)
+
+ created, err := sessions.Create(context.Background(), &types.Session{
+ TenantID: 7, UserID: "u-1", Title: "plain",
+ })
+ require.NoError(t, err)
+ require.NotEmpty(t, created.ID)
+ require.Equal(t, int64(1), countSessions(t, db, "u-1"))
+}
+
+func countSessions(t *testing.T, db *gorm.DB, userID string) int64 {
+ t.Helper()
+ var n int64
+ require.NoError(t, db.Model(&types.Session{}).Where("user_id = ?", userID).Count(&n).Error)
+ return n
+}
diff --git a/internal/application/service/pinned_session_sandbox.go b/internal/application/service/pinned_session_sandbox.go
index ae4f585e4..9edd2d2c7 100644
--- a/internal/application/service/pinned_session_sandbox.go
+++ b/internal/application/service/pinned_session_sandbox.go
@@ -129,17 +129,25 @@ func (a *PinnedSessionSandbox) HasActiveTurn(ctx context.Context, sessionID stri
return false, nil
}
-// TryLockRewind takes an exclusive rewind lock through the session's pinned
-// manager. Managers that do not expose the method succeed as a no-op.
-func (a *PinnedSessionSandbox) TryLockRewind(ctx context.Context, sessionID string) (func(), error) {
+// TryLockRewind locks rewind through the session's pinned manager. A manager
+// that can take the session exclusively returns the context to reset with;
+// one with only the rewind lock keeps ctx; others succeed as a no-op.
+func (a *PinnedSessionSandbox) TryLockRewind(ctx context.Context, sessionID string) (context.Context, func(), error) {
mgr := a.manager(ctx, sessionID)
+ type exclusiveLocker interface {
+ LockRewindSession(context.Context, string) (context.Context, func(), error)
+ }
+ if l, ok := mgr.(exclusiveLocker); ok {
+ return l.LockRewindSession(ctx, sessionID)
+ }
type locker interface {
TryLockRewind(context.Context, string) (func(), error)
}
if l, ok := mgr.(locker); ok {
- return l.TryLockRewind(ctx, sessionID)
+ unlock, err := l.TryLockRewind(ctx, sessionID)
+ return ctx, unlock, err
}
- return func() {}, nil
+ return ctx, func() {}, nil
}
// HasRewindLock reports whether rewind currently holds the session on the
@@ -155,6 +163,21 @@ func (a *PinnedSessionSandbox) HasRewindLock(ctx context.Context, sessionID stri
return false, nil
}
+// BeginWorkspaceFork opens a shared-machine fork through the session's
+// pinned manager. Backends without shared machines cannot.
+func (a *PinnedSessionSandbox) BeginWorkspaceFork(
+ ctx context.Context, sourceSessionID string,
+) (sandbox.WorkspaceFork, error) {
+ mgr := a.manager(ctx, sourceSessionID)
+ starter, ok := mgr.(interface {
+ BeginWorkspaceFork(context.Context, string) (sandbox.WorkspaceFork, error)
+ })
+ if !ok {
+ return nil, sandbox.ErrSharedSandbox
+ }
+ return starter.BeginWorkspaceFork(ctx, sourceSessionID)
+}
+
// CreateForkSnapshot snapshots the session's already-bound sandbox through the
// pinned manager. Managers that do not expose the method return an error so
// fork can degrade to SNAPSHOT_UNSUPPORTED.
@@ -235,5 +258,3 @@ var _ WorkspaceVersioning = (*PinnedSessionSandbox)(nil)
var _ sandbox.SessionWorkspaceLayoutProvider = (*PinnedSessionSandbox)(nil)
var _ SessionForkSandboxPort = (*sandbox.SessionBoundManager)(nil)
-
-var _ SessionRewindSandboxPort = (*sandbox.SessionBoundManager)(nil)
diff --git a/internal/application/service/sandbox_desktop_service.go b/internal/application/service/sandbox_desktop_service.go
index d86c5bb0d..bc0d0a104 100644
--- a/internal/application/service/sandbox_desktop_service.go
+++ b/internal/application/service/sandbox_desktop_service.go
@@ -73,31 +73,65 @@ func NewSandboxDesktopService(terminals *SandboxTerminalService) *SandboxDesktop
return &SandboxDesktopService{terminals: terminals}
}
-// EnsureSessionDesktop starts the desktop listeners and dials websockify.
-//
-// A zero provision pin is lookup-only: a running session sandbox is
-// attached (and XFCE is lazily started if needed), a paused one returns
-// sandbox.ErrSandboxPaused, and a missing one returns
-// sandbox.ErrNoLiveSessionSandbox. A non-zero pin is the confirmed-click
-// path and may create or resume, the same contract as EnsureSessionTerminal.
-func (s *SandboxDesktopService) EnsureSessionDesktop(
- ctx context.Context,
- sessionID string,
- provision SandboxPin,
-) (*SessionDesktop, error) {
+// DesktopTarget is a located desktop. The caller holds its operation, fixes
+// the machine, claims the machine's slot, then starts it.
+type DesktopTarget struct {
+ SessionID string
+ MachineID string
+ SandboxID string
+ mgr sandbox.Manager
+}
+
+// HoldOperation registers the desktop relay so a rebuild or reclaim of a
+// shared machine waits for it. The returned context ends if the hold is lost.
+// A no-op for per-session machines.
+func (t *DesktopTarget) HoldOperation(ctx context.Context) (context.Context, func(), error) {
+ if holder, ok := t.mgr.(interface {
+ HoldSessionOperation(context.Context, string, string) (context.Context, func(), error)
+ }); ok {
+ return holder.HoldSessionOperation(ctx, t.SessionID, "desktop")
+ }
+ return ctx, func() {}, nil
+}
+
+// FixMachine records which machine and sandbox this desktop is for. Managers
+// that cannot name the machine fall back to the session id (one machine per
+// session), with no sandbox pin.
+func (t *DesktopTarget) FixMachine(ctx context.Context) error {
+ t.MachineID = t.SessionID
+ namer, ok := t.mgr.(interface {
+ DesktopMachine(context.Context, string) (string, string, error)
+ })
+ if !ok {
+ return nil
+ }
+ machineID, sandboxID, err := namer.DesktopMachine(ctx, t.SessionID)
+ if err != nil {
+ return err
+ }
+ t.MachineID, t.SandboxID = machineID, sandboxID
+ return nil
+}
+
+// LocateSessionDesktop resolves (and, with a provision pin, creates or
+// resumes) the session's machine without starting anything on it.
+func (s *SandboxDesktopService) LocateSessionDesktop(
+ ctx context.Context, sessionID string, provision SandboxPin,
+) (*DesktopTarget, error) {
if s == nil || s.terminals == nil {
return nil, sandbox.ErrNoLiveSessionSandbox
}
-
- // 1. Resolve. Lookup-only skips create/resume; a confirmed config ID
- // provisions through the same path a chat turn uses. Either way the
- // inbound token is registered on THIS replica, which is what keeps
- // the gateway from answering 401.
mgr, err := s.resolveRunningManager(ctx, sessionID, provision)
if err != nil {
return nil, err
}
+ return &DesktopTarget{SessionID: sessionID, mgr: mgr}, nil
+}
+// StartSessionDesktop starts the desktop listeners and dials websockify on
+// t's fixed sandbox.
+func (s *SandboxDesktopService) StartSessionDesktop(ctx context.Context, t *DesktopTarget) (*SessionDesktop, error) {
+ mgr := t.mgr
provider, ok := mgr.(sandbox.SessionDesktopProvider)
if !ok {
return nil, ErrDesktopUnsupported
@@ -112,14 +146,14 @@ func (s *SandboxDesktopService) EnsureSessionDesktop(
return nil, ErrDesktopUnsupported
}
- secret, err := readDesktopSecret(ctx, exec, sessionID)
+ secret, err := readDesktopSecret(ctx, exec, t.SessionID, t.SandboxID)
if err != nil {
return nil, err
}
// Dial. The secret stays in memory for exactly one handshake and is
// never sent to the browser.
- dialed, err := desktops.OpenSessionDesktop(ctx, sessionID, sandbox.RemoteDesktopOptions{
+ dialed, err := desktops.OpenSessionDesktop(ctx, t.SessionID, sandbox.RemoteDesktopOptions{
BasicAuthUser: sandbox.DesktopBasicAuthUser,
BasicAuthPassword: secret,
})
@@ -129,6 +163,11 @@ func (s *SandboxDesktopService) EnsureSessionDesktop(
}
return nil, err
}
+ if t.SandboxID != "" && dialed.SandboxID != t.SandboxID {
+ _ = dialed.Conn.Close()
+ return nil, fmt.Errorf("%w: desktop dialed %s, expected %s",
+ sandbox.ErrNoLiveSessionSandbox, dialed.SandboxID, t.SandboxID)
+ }
return &SessionDesktop{
Conn: dialed.Conn,
Backend: mgr.GetType(),
@@ -138,6 +177,35 @@ func (s *SandboxDesktopService) EnsureSessionDesktop(
}, nil
}
+// EnsureSessionDesktop is the slot-less path: locate, hold, fix, start. The
+// hold is released when the call returns; the WebSocket handler keeps its
+// own for the relay's lifetime.
+//
+// A zero provision pin is lookup-only: a running session sandbox is
+// attached (and XFCE is lazily started if needed), a paused one returns
+// sandbox.ErrSandboxPaused, and a missing one returns
+// sandbox.ErrNoLiveSessionSandbox. A non-zero pin is the confirmed-click
+// path and may create or resume, the same contract as EnsureSessionTerminal.
+func (s *SandboxDesktopService) EnsureSessionDesktop(
+ ctx context.Context,
+ sessionID string,
+ provision SandboxPin,
+) (*SessionDesktop, error) {
+ t, err := s.LocateSessionDesktop(ctx, sessionID, provision)
+ if err != nil {
+ return nil, err
+ }
+ opCtx, release, err := t.HoldOperation(ctx)
+ if err != nil {
+ return nil, err
+ }
+ defer release()
+ if err := t.FixMachine(opCtx); err != nil {
+ return nil, err
+ }
+ return s.StartSessionDesktop(opCtx, t)
+}
+
// resolveRunningManager returns a manager whose session sandbox is live.
// With a zero provision pin it will not create or resume: a paused binding
// is ErrSandboxPaused so the overlay can ask first. DesktopEnabled is
@@ -206,16 +274,21 @@ type sessionShellOptionsExecutor interface {
) (*sandbox.ExecuteResult, error)
}
-func desktopSkipPrepOpts(timeout time.Duration) sandbox.ShellExecOptions {
- return sandbox.ShellExecOptions{Timeout: timeout, SkipWorkspacePrep: true}
+func desktopSkipPrepOpts(timeout time.Duration, expectedSandboxID string) sandbox.ShellExecOptions {
+ return sandbox.ShellExecOptions{
+ Timeout: timeout,
+ SkipWorkspacePrep: true,
+ ExpectedSandboxID: expectedSandboxID,
+ }
}
func readDesktopSecret(
ctx context.Context,
exec sessionShellOptionsExecutor,
sessionID string,
+ expectedSandboxID string,
) (string, error) {
- secret, err := runDesktopEnsure(ctx, exec, sessionID)
+ secret, err := runDesktopEnsure(ctx, exec, sessionID, expectedSandboxID)
if err == nil {
return secret, nil
}
@@ -224,20 +297,21 @@ func readDesktopSecret(
}
logger.Warnf(ctx, "[sandbox-desktop] ensure failed; resetting stack session=%s: %v",
sessionID, err)
- if _, resetErr := exec.ExecShellCommandWithOptions(ctx, sessionID,
- sandbox.DesktopResetListenersCmd(), desktopSkipPrepOpts(desktopProbeTimeout)); resetErr != nil {
+ if _, resetErr := exec.ExecShellCommandWithOptions(ctx, sessionID, sandbox.DesktopResetListenersCmd(),
+ desktopSkipPrepOpts(desktopProbeTimeout, expectedSandboxID)); resetErr != nil {
return "", fmt.Errorf("%w: reset desktop stack: %v", ErrDesktopStartFailed, resetErr)
}
- return runDesktopEnsure(ctx, exec, sessionID)
+ return runDesktopEnsure(ctx, exec, sessionID, expectedSandboxID)
}
func runDesktopEnsure(
ctx context.Context,
exec sessionShellOptionsExecutor,
sessionID string,
+ expectedSandboxID string,
) (string, error) {
result, err := exec.ExecShellCommandWithOptions(ctx, sessionID,
- sandbox.DesktopEnsureCmd(), desktopSkipPrepOpts(desktopStartTimeout))
+ sandbox.DesktopEnsureCmd(), desktopSkipPrepOpts(desktopStartTimeout, expectedSandboxID))
if err != nil {
return "", fmt.Errorf("%w: %v", ErrDesktopStartFailed, err)
}
diff --git a/internal/application/service/sandbox_desktop_service_test.go b/internal/application/service/sandbox_desktop_service_test.go
index a1fbf71b3..abe26c558 100644
--- a/internal/application/service/sandbox_desktop_service_test.go
+++ b/internal/application/service/sandbox_desktop_service_test.go
@@ -3,12 +3,20 @@ package service
import (
"context"
"errors"
+ "net/http"
+ "net/http/httptest"
"strings"
+ "sync"
"testing"
+ "time"
+ "github.com/gorilla/websocket"
"github.com/stretchr/testify/require"
+ "gorm.io/driver/sqlite"
+ "gorm.io/gorm"
"github.com/Tencent/WeKnora/internal/sandbox"
+ "github.com/Tencent/WeKnora/internal/types"
)
type fakeDesktopShell struct {
@@ -40,7 +48,7 @@ func TestReadDesktopSecretHappyPathSingleExec(t *testing.T) {
f := &fakeDesktopShell{results: []*sandbox.ExecuteResult{{
Stdout: "READY " + secret + "\n", ExitCode: 0,
}}}
- got, err := readDesktopSecret(context.Background(), f, "sess-1")
+ got, err := readDesktopSecret(context.Background(), f, "sess-1", "")
require.NoError(t, err)
require.Equal(t, secret, got)
require.Len(t, f.cmds, 1)
@@ -56,7 +64,7 @@ func TestReadDesktopSecretMissingScriptDoesNotReset(t *testing.T) {
ExitCode: sandbox.DesktopEnsureUnsupportedExit,
Stderr: sandbox.DesktopEnsureUnsupportedMarker + "\n",
}}}
- _, err := readDesktopSecret(context.Background(), f, "sess-1")
+ _, err := readDesktopSecret(context.Background(), f, "sess-1", "")
require.ErrorIs(t, err, ErrDesktopUnsupported)
require.Len(t, f.cmds, 1)
}
@@ -67,7 +75,7 @@ func TestReadDesktopSecretBareExit2IsStartFailed(t *testing.T) {
{ExitCode: 0},
{ExitCode: 2, Stderr: "Syntax error: end of file unexpected\n"},
}}
- _, err := readDesktopSecret(context.Background(), f, "sess-1")
+ _, err := readDesktopSecret(context.Background(), f, "sess-1", "")
require.ErrorIs(t, err, ErrDesktopStartFailed)
require.Equal(t, sandbox.DesktopResetListenersCmd(), f.cmds[1])
require.Len(t, f.cmds, 3)
@@ -82,7 +90,7 @@ func TestReadDesktopSecretTimeoutResetsThenRetries(t *testing.T) {
{Stdout: "READY " + secret + "\n", ExitCode: 0},
},
}
- got, err := readDesktopSecret(context.Background(), f, "sess-1")
+ got, err := readDesktopSecret(context.Background(), f, "sess-1", "")
require.NoError(t, err)
require.Equal(t, secret, got)
require.Equal(t, sandbox.DesktopEnsureCmd(), f.cmds[0])
@@ -99,7 +107,7 @@ func TestReadDesktopSecretResetExecError(t *testing.T) {
results: []*sandbox.ExecuteResult{{ExitCode: 1, Stderr: "boom"}},
errs: []error{nil, errors.New("reset failed")},
}
- _, err := readDesktopSecret(context.Background(), f, "sess-1")
+ _, err := readDesktopSecret(context.Background(), f, "sess-1", "")
require.ErrorIs(t, err, ErrDesktopStartFailed)
require.Len(t, f.cmds, 2)
}
@@ -141,7 +149,7 @@ func TestReadDesktopSecretRejectsUnparseableSuccess(t *testing.T) {
{ExitCode: 0},
{ExitCode: 0, Stdout: "started\n"},
}}
- _, err := readDesktopSecret(context.Background(), f, "sess-1")
+ _, err := readDesktopSecret(context.Background(), f, "sess-1", "")
require.ErrorIs(t, err, ErrDesktopStartFailed)
require.Equal(t, sandbox.DesktopResetListenersCmd(), f.cmds[1])
}
@@ -173,3 +181,194 @@ func TestRequireDesktopCapableRejectsWhenNotAdvertised(t *testing.T) {
func TestRequireDesktopCapableAcceptsAdvertisedManager(t *testing.T) {
require.NoError(t, requireDesktopCapable(stubDesktopProvider{advertised: true}))
}
+
+const desktopTestSecret = "abcdefghijklmnopqrstuvwxyz012345"
+
+func desktopReadyResult() *sandbox.ExecuteResult {
+ return &sandbox.ExecuteResult{Stdout: "READY " + desktopTestSecret + "\n", ExitCode: 0}
+}
+
+// orderDesktopManager records the Ensure path. HoldSessionOperation's release
+// is part of the order: it must run after the dial, not before the machine
+// is named.
+type orderDesktopManager struct {
+ mu sync.Mutex
+ order []string
+}
+
+func (m *orderDesktopManager) note(step string) {
+ m.mu.Lock()
+ m.order = append(m.order, step)
+ m.mu.Unlock()
+}
+
+func (m *orderDesktopManager) steps() []string {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ out := make([]string, len(m.order))
+ copy(out, m.order)
+ return out
+}
+
+func (m *orderDesktopManager) Execute(context.Context, *sandbox.ExecuteConfig) (*sandbox.ExecuteResult, error) {
+ return nil, nil
+}
+func (m *orderDesktopManager) Cleanup(context.Context) error { return nil }
+func (m *orderDesktopManager) GetSandbox() sandbox.Sandbox { return nil }
+func (m *orderDesktopManager) GetType() sandbox.SandboxType { return sandbox.SandboxTypeCube }
+
+func (m *orderDesktopManager) SessionDesktopManager() sandbox.SessionDesktopManager { return m }
+
+func (m *orderDesktopManager) HoldSessionOperation(ctx context.Context, _, _ string) (context.Context, func(), error) {
+ m.note("HoldSessionOperation")
+ return ctx, func() { m.note("release") }, nil
+}
+
+func (m *orderDesktopManager) DesktopMachine(context.Context, string) (string, string, error) {
+ m.note("DesktopMachine")
+ return "machine-1", "sb-1", nil
+}
+
+func (m *orderDesktopManager) ExecShellCommandWithOptions(
+ context.Context, string, string, sandbox.ShellExecOptions,
+) (*sandbox.ExecuteResult, error) {
+ m.note("ExecShellCommandWithOptions")
+ return desktopReadyResult(), nil
+}
+
+func (m *orderDesktopManager) OpenSessionDesktop(
+ context.Context, string, sandbox.RemoteDesktopOptions,
+) (*sandbox.SessionDesktopConn, error) {
+ m.note("OpenSessionDesktop")
+ return &sandbox.SessionDesktopConn{SandboxID: "sb-1"}, nil
+}
+
+type fixedDesktopResolver struct {
+ mgr sandbox.Manager
+}
+
+func (r *fixedDesktopResolver) Resolve(context.Context, uint64, string) (sandbox.Manager, error) {
+ return r.mgr, nil
+}
+
+func newEnsuredDesktopService(t *testing.T, mgr sandbox.Manager) *SandboxDesktopService {
+ t.Helper()
+ db, err := gorm.Open(sqlite.Open("file:"+t.Name()+"?mode=memory&cache=shared"), &gorm.Config{})
+ require.NoError(t, err)
+ require.NoError(t, db.AutoMigrate(&types.Session{}))
+ require.NoError(t, db.Model(&types.Session{}).Create(map[string]any{
+ "id": "sess-1", "tenant_id": uint64(42),
+ }).Error)
+ pinner := NewSessionSandboxPinner(db)
+ _, err = pinner.Pin(context.Background(), "sess-1", SandboxPin{ConfigID: "cfg-desk", TenantID: 42})
+ require.NoError(t, err)
+ return NewSandboxDesktopService(NewSandboxTerminalService(
+ pinner, &fixedDesktopResolver{mgr: mgr}, nil, nil, HostSandboxManager{},
+ ))
+}
+
+func TestEnsureSessionDesktopHoldsTheOperationBeforeReadingTheMachine(t *testing.T) {
+ mgr := &orderDesktopManager{}
+ svc := newEnsuredDesktopService(t, mgr)
+ _, err := svc.EnsureSessionDesktop(context.Background(), "sess-1", SandboxPin{})
+ require.NoError(t, err)
+ require.Equal(t, []string{
+ "HoldSessionOperation",
+ "DesktopMachine",
+ "ExecShellCommandWithOptions",
+ "OpenSessionDesktop",
+ "release",
+ }, mgr.steps())
+}
+
+// pinnedDesktopManager is a located target's manager. It records every shell
+// option and dials whatever sandbox the test names.
+type pinnedDesktopManager struct {
+ calls []sandbox.ShellExecOptions
+ dialSandboxID string
+ conn *websocket.Conn
+ results []*sandbox.ExecuteResult
+}
+
+func (m *pinnedDesktopManager) Execute(context.Context, *sandbox.ExecuteConfig) (*sandbox.ExecuteResult, error) {
+ return nil, nil
+}
+func (m *pinnedDesktopManager) Cleanup(context.Context) error { return nil }
+func (m *pinnedDesktopManager) GetSandbox() sandbox.Sandbox { return nil }
+func (m *pinnedDesktopManager) GetType() sandbox.SandboxType { return sandbox.SandboxTypeCube }
+func (m *pinnedDesktopManager) SessionDesktopManager() sandbox.SessionDesktopManager {
+ return m
+}
+
+func (m *pinnedDesktopManager) ExecShellCommandWithOptions(
+ _ context.Context, _ string, _ string, opts sandbox.ShellExecOptions,
+) (*sandbox.ExecuteResult, error) {
+ m.calls = append(m.calls, opts)
+ i := len(m.calls) - 1
+ if i < len(m.results) && m.results[i] != nil {
+ return m.results[i], nil
+ }
+ return desktopReadyResult(), nil
+}
+
+func (m *pinnedDesktopManager) OpenSessionDesktop(
+ context.Context, string, sandbox.RemoteDesktopOptions,
+) (*sandbox.SessionDesktopConn, error) {
+ return &sandbox.SessionDesktopConn{Conn: m.conn, SandboxID: m.dialSandboxID}, nil
+}
+
+func TestStartSessionDesktopPinsEveryStepToTheFixedSandbox(t *testing.T) {
+ mgr := &pinnedDesktopManager{
+ dialSandboxID: "sb-1",
+ results: []*sandbox.ExecuteResult{
+ {ExitCode: 1, Stderr: "x11vnc dead"},
+ {ExitCode: 0},
+ desktopReadyResult(),
+ },
+ }
+ svc := &SandboxDesktopService{}
+ _, err := svc.StartSessionDesktop(context.Background(), &DesktopTarget{
+ SessionID: "sess-1", SandboxID: "sb-1", mgr: mgr,
+ })
+ require.NoError(t, err)
+ require.NotEmpty(t, mgr.calls)
+ for _, opts := range mgr.calls {
+ require.Equal(t, "sb-1", opts.ExpectedSandboxID)
+ }
+}
+
+func TestStartSessionDesktopRejectsADialToAnotherSandbox(t *testing.T) {
+ client, server := desktopTestConn(t)
+ mgr := &pinnedDesktopManager{dialSandboxID: "sb-2", conn: server}
+ svc := &SandboxDesktopService{}
+ _, err := svc.StartSessionDesktop(context.Background(), &DesktopTarget{
+ SessionID: "sess-1", SandboxID: "sb-1", mgr: mgr,
+ })
+ require.ErrorIs(t, err, sandbox.ErrNoLiveSessionSandbox)
+ require.NoError(t, client.SetReadDeadline(time.Now().Add(time.Second)))
+ _, _, readErr := client.ReadMessage()
+ var netErr interface{ Timeout() bool }
+ require.False(t, errors.As(readErr, &netErr) && netErr.Timeout(),
+ "a dial to another sandbox must close the connection, not leave it open until the deadline")
+ require.Error(t, readErr, "a dial to another sandbox must close the connection")
+}
+
+func desktopTestConn(t *testing.T) (client, server *websocket.Conn) {
+ t.Helper()
+ accepted := make(chan *websocket.Conn, 1)
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ up := websocket.Upgrader{CheckOrigin: func(*http.Request) bool { return true }}
+ conn, err := up.Upgrade(w, r, nil)
+ if err != nil {
+ return
+ }
+ accepted <- conn
+ }))
+ t.Cleanup(srv.Close)
+ client, _, err := websocket.DefaultDialer.Dial("ws"+strings.TrimPrefix(srv.URL, "http"), nil)
+ require.NoError(t, err)
+ t.Cleanup(func() { _ = client.Close() })
+ server = <-accepted
+ t.Cleanup(func() { _ = server.Close() })
+ return client, server
+}
diff --git a/internal/application/service/sandboxalloc/cleanup.go b/internal/application/service/sandboxalloc/cleanup.go
new file mode 100644
index 000000000..ace72ddba
--- /dev/null
+++ b/internal/application/service/sandboxalloc/cleanup.go
@@ -0,0 +1,340 @@
+package sandboxalloc
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "time"
+
+ "github.com/Tencent/WeKnora/internal/logger"
+ "github.com/Tencent/WeKnora/internal/sandbox"
+ "github.com/Tencent/WeKnora/internal/sandbox/allocation"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/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,
+ }
+}
diff --git a/internal/application/service/sandboxalloc/cleanup_test.go b/internal/application/service/sandboxalloc/cleanup_test.go
new file mode 100644
index 000000000..d87f9e8eb
--- /dev/null
+++ b/internal/application/service/sandboxalloc/cleanup_test.go
@@ -0,0 +1,265 @@
+package sandboxalloc
+
+import (
+ "context"
+ "errors"
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/stretchr/testify/require"
+
+ "github.com/Tencent/WeKnora/internal/sandbox"
+ "github.com/Tencent/WeKnora/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)
+}
diff --git a/internal/application/service/sandboxalloc/gc.go b/internal/application/service/sandboxalloc/gc.go
new file mode 100644
index 000000000..a61ae5443
--- /dev/null
+++ b/internal/application/service/sandboxalloc/gc.go
@@ -0,0 +1,269 @@
+package sandboxalloc
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "time"
+
+ "github.com/redis/go-redis/v9"
+
+ "github.com/Tencent/WeKnora/internal/common/redislock"
+ "github.com/Tencent/WeKnora/internal/logger"
+ "github.com/Tencent/WeKnora/internal/sandbox/allocation"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+)
+
+const (
+ // UserMachineGCLockKey makes one replica scan at a time.
+ UserMachineGCLockKey = "weknora: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 = "weknora: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
+}
diff --git a/internal/application/service/sandboxalloc/gc_test.go b/internal/application/service/sandboxalloc/gc_test.go
new file mode 100644
index 000000000..f9ad84296
--- /dev/null
+++ b/internal/application/service/sandboxalloc/gc_test.go
@@ -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"
+
+ "github.com/Tencent/WeKnora/internal/sandbox/allocation"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/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)
+}
diff --git a/internal/application/service/sandboxalloc/multireplica_test.go b/internal/application/service/sandboxalloc/multireplica_test.go
new file mode 100644
index 000000000..a09372e6e
--- /dev/null
+++ b/internal/application/service/sandboxalloc/multireplica_test.go
@@ -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"
+
+ "github.com/Tencent/WeKnora/internal/application/repository"
+ "github.com/Tencent/WeKnora/internal/sandbox/allocation"
+ "github.com/Tencent/WeKnora/internal/types"
+)
+
+// integrationEnv returns an integration dependency's address. Missing, the
+// test is skipped — unless WEKNORA_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("WEKNORA_REQUIRE_INTEGRATION") == "1" {
+ t.Fatalf("%s is required when WEKNORA_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, "WEKNORA_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 WEKNORA_REPOSITORY_TEST_POSTGRES_DSN is
+// set, and the shared-cache sqlite pool otherwise. The sqlite path is still a
+// regression test; only WEKNORA_REQUIRE_INTEGRATION=1 demands Postgres.
+func placementDatabase(t *testing.T) *gorm.DB {
+ t.Helper()
+ dsn := strings.TrimSpace(os.Getenv("WEKNORA_REPOSITORY_TEST_POSTGRES_DSN"))
+ if dsn == "" {
+ if os.Getenv("WEKNORA_REQUIRE_INTEGRATION") == "1" {
+ t.Fatal("WEKNORA_REPOSITORY_TEST_POSTGRES_DSN is required when WEKNORA_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, "weknora")
+ s2 := New(repo, configs, sessions, "weknora")
+ 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)
+}
diff --git a/internal/application/service/sandboxalloc/service_test.go b/internal/application/service/sandboxalloc/service_test.go
index 3a07fd74f..279a074c6 100644
--- a/internal/application/service/sandboxalloc/service_test.go
+++ b/internal/application/service/sandboxalloc/service_test.go
@@ -82,6 +82,19 @@ func (e *testEnv) reason(t *testing.T, sessionID, configID string) allocation.Fa
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
diff --git a/internal/application/service/session.go b/internal/application/service/session.go
index 759d2a448..3dc384436 100644
--- a/internal/application/service/session.go
+++ b/internal/application/service/session.go
@@ -8,6 +8,7 @@ import (
"github.com/Tencent/WeKnora/internal/application/repository"
chatpipeline "github.com/Tencent/WeKnora/internal/application/service/chat_pipeline"
+ "github.com/Tencent/WeKnora/internal/application/service/sandboxalloc"
"github.com/Tencent/WeKnora/internal/config"
apperrors "github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/event"
@@ -176,6 +177,11 @@ type sessionService struct {
busyGate *SessionBusyGate
// deletedSessionsHook releases collaboration state of deleted conversations.
deletedSessionsHook func(context.Context, uint64, string, []string)
+ // workspaceCleaner retires sessions on delete and removes a user-mode
+ // session's directory from the shared machine. Nil (Lite, host, or no
+ // remote resolver) keeps the historical delete path and writes no
+ // allocation rows.
+ workspaceCleaner *sandboxalloc.WorkspaceCleaner
}
// NewSessionService creates a new session service instance with all required dependencies
@@ -543,6 +549,11 @@ func (s *sessionService) DeleteSession(ctx context.Context, id string) error {
return err
}
+ handled, err := s.userWorkspaceSessions(ctx, []string{id})
+ if err != nil {
+ return fmt.Errorf("read sandbox workspace: %w", err)
+ }
+
// Cleanup chat history knowledge entries for this session (async, best-effort).
// Use WithoutCancel so the goroutine survives after the HTTP request context is done.
bgCtx := context.WithoutCancel(ctx)
@@ -579,9 +590,19 @@ func (s *sessionService) DeleteSession(ctx context.Context, id string) error {
}
}
- s.destroyBoundSandbox(ctx, id)
+ if !handled[id] {
+ s.destroyBoundSandbox(ctx, id)
+ }
// Delete session from repository
- rows, err := s.sessionRepo.Delete(ctx, tenantID, session.UserID, id)
+ var rows int64
+ if s.workspaceCleaner != nil {
+ var count int
+ handled, count, err = s.workspaceCleaner.DeleteSessions(
+ ctx, tenantID, map[string][]string{session.UserID: {id}})
+ rows = int64(count)
+ } else {
+ rows, err = s.sessionRepo.Delete(ctx, tenantID, session.UserID, id)
+ }
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"session_id": id,
@@ -595,6 +616,7 @@ func (s *sessionService) DeleteSession(ctx context.Context, id string) error {
s.releaseForkSnapshot(ctx, session)
s.notifyDeletedSessions(ctx, tenantID, session.UserID, []string{id})
+ s.runUserWorkspaceCleanups(ctx, handled)
return nil
}
@@ -638,6 +660,11 @@ func (s *sessionService) BatchDeleteSessions(ctx context.Context, ids []string)
return apperrors.ErrSessionNotFound
}
+ handled, err := s.userWorkspaceSessions(ctx, visibleIDs)
+ if err != nil {
+ return fmt.Errorf("read sandbox workspace: %w", err)
+ }
+
// Cleanup associated resources for each session
bgCtx := context.WithoutCancel(ctx)
for _, id := range visibleIDs {
@@ -663,19 +690,19 @@ func (s *sessionService) BatchDeleteSessions(ctx context.Context, ids []string)
}
// Tear down sandboxes while session rows (and pins) are still readable.
+ // A session on a shared machine keeps that machine; only its directory
+ // is removed after the rows are gone.
for _, id := range visibleIDs {
+ if handled[id] {
+ continue
+ }
s.destroyBoundSandbox(ctx, id)
}
// Batch delete sessions from repository
- for ownerID, ownerIDs := range idsByOwner {
- if _, err := s.sessionRepo.BatchDelete(ctx, tenantID, ownerID, ownerIDs); err != nil {
- logger.ErrorWithFields(ctx, err, map[string]interface{}{
- "session_ids": ownerIDs,
- "tenant_id": tenantID,
- })
- return err
- }
+ handled, err = s.deleteSessionBatch(ctx, tenantID, idsByOwner)
+ if err != nil {
+ return err
}
if s.suggestionRepo != nil {
for _, id := range visibleIDs {
@@ -689,6 +716,7 @@ func (s *sessionService) BatchDeleteSessions(ctx context.Context, ids []string)
for ownerID, ownerIDs := range idsByOwner {
s.notifyDeletedSessions(ctx, tenantID, ownerID, ownerIDs)
}
+ s.runUserWorkspaceCleanups(ctx, handled)
return nil
}
@@ -700,47 +728,68 @@ func (s *sessionService) DeleteAllSessions(ctx context.Context) error {
sessions, err := s.sessionRepo.GetByTenantID(ctx, tenantID, userID)
if err != nil {
+ // A failed list is not an empty list; do not delete any rows.
logger.Warnf(ctx, "Failed to list sessions for cleanup: %v", err)
- } else {
- bgCtx := context.WithoutCancel(ctx)
- for _, session := range sessions {
- // Cleanup chat history knowledge entries (async, best-effort)
- go func(sessionID string) {
- knowledgeIDs, err := s.messageRepo.GetKnowledgeIDsBySessionID(bgCtx, sessionID)
- if err != nil {
- logger.Warnf(bgCtx, "Failed to get knowledge IDs for session %s: %v", sessionID, err)
- return
- }
- if len(knowledgeIDs) > 0 {
- if err := deleteReferencedKnowledge(bgCtx, s.knowledgeService, "", knowledgeIDs); err != nil {
- logger.Warnf(bgCtx, "Failed to delete chat history knowledge for session %s: %v", sessionID, err)
- }
+ return err
+ }
+ ids := make([]string, 0, len(sessions))
+ idsByOwner := make(map[string][]string)
+ for _, session := range sessions {
+ if session == nil || session.ID == "" {
+ continue
+ }
+ ids = append(ids, session.ID)
+ idsByOwner[session.UserID] = append(idsByOwner[session.UserID], session.ID)
+ }
+ handled, err := s.userWorkspaceSessions(ctx, ids)
+ if err != nil {
+ return fmt.Errorf("read sandbox workspace: %w", err)
+ }
+ bgCtx := context.WithoutCancel(ctx)
+ for _, session := range sessions {
+ if session == nil || session.ID == "" {
+ continue
+ }
+ // Cleanup chat history knowledge entries (async, best-effort)
+ go func(sessionID string) {
+ knowledgeIDs, err := s.messageRepo.GetKnowledgeIDsBySessionID(bgCtx, sessionID)
+ if err != nil {
+ logger.Warnf(bgCtx, "Failed to get knowledge IDs for session %s: %v", sessionID, err)
+ return
+ }
+ if len(knowledgeIDs) > 0 {
+ if err := deleteReferencedKnowledge(bgCtx, s.knowledgeService, "", knowledgeIDs); err != nil {
+ logger.Warnf(bgCtx, "Failed to delete chat history knowledge for session %s: %v", sessionID, err)
}
- }(session.ID)
-
- if err := s.webSearchStateRepo.DeleteWebSearchTempKBState(ctx, session.ID); err != nil {
- logger.Warnf(ctx, "Failed to cleanup temporary KB for session %s: %v", session.ID, err)
}
- // Artifact blobs are kept alongside soft-deleted messages — see
- // DeleteSession for the rationale.
+ }(session.ID)
+
+ if err := s.webSearchStateRepo.DeleteWebSearchTempKBState(ctx, session.ID); err != nil {
+ logger.Warnf(ctx, "Failed to cleanup temporary KB for session %s: %v", session.ID, err)
}
+ // Artifact blobs are kept alongside soft-deleted messages — see
+ // DeleteSession for the rationale.
}
// Tear down sandboxes while session rows (and pins) are still readable.
- if sessions != nil {
- for _, session := range sessions {
- s.destroyBoundSandbox(ctx, session.ID)
+ for _, session := range sessions {
+ if session == nil || session.ID == "" || handled[session.ID] {
+ continue
}
+ s.destroyBoundSandbox(ctx, session.ID)
}
- if _, err := s.sessionRepo.DeleteAllByTenantID(ctx, tenantID, userID); err != nil {
- logger.ErrorWithFields(ctx, err, map[string]interface{}{
- "tenant_id": tenantID,
- })
+ // Retire and delete only the listed ids. A session inserted after the list
+ // stays, instead of DeleteAllByTenantID removing every current row.
+ handled, err = s.deleteSessionBatch(ctx, tenantID, idsByOwner)
+ if err != nil {
return err
}
- if s.suggestionRepo != nil && sessions != nil {
+ if s.suggestionRepo != nil {
for _, session := range sessions {
+ if session == nil || session.ID == "" {
+ continue
+ }
if err := s.suggestionRepo.DeleteBySessionID(ctx, tenantID, session.ID); err != nil {
logger.Warnf(ctx, "Failed to delete suggestions for session %s: %v", session.ID, err)
}
@@ -748,17 +797,85 @@ func (s *sessionService) DeleteAllSessions(ctx context.Context) error {
}
s.releaseForkSnapshots(ctx, sessions)
- idsByOwner := make(map[string][]string)
- for _, session := range sessions {
- idsByOwner[session.UserID] = append(idsByOwner[session.UserID], session.ID)
- }
for ownerID, ownerIDs := range idsByOwner {
s.notifyDeletedSessions(ctx, tenantID, ownerID, ownerIDs)
}
+ // One detached goroutine: reclaim empty machines before directory cleanup.
+ // Cleanup holds a machine admission member, so starting it first makes
+ // reclaim see the machine as busy and leave it until retention.
+ // A machine another session still occupies fails the in-lock check and
+ // stays; its retired directories are cleaned afterwards. A reclaimed
+ // machine has no registry row, and execute completes those tasks.
+ if s.workspaceCleaner != nil && userID != "" {
+ ids := make([]string, 0, len(handled))
+ for id := range handled {
+ ids = append(ids, id)
+ }
+ bg := context.WithoutCancel(ctx)
+ go func() {
+ machines, err := s.workspaceCleaner.OwnerMachines(bg, tenantID, userID)
+ if err != nil {
+ logger.Warnf(bg, "Failed to list user sandboxes of %s: %v", userID, err)
+ } else {
+ s.workspaceCleaner.ReclaimOwnerMachines(bg, machines)
+ }
+ if len(ids) > 0 {
+ s.workspaceCleaner.RunCleanups(bg, ids)
+ }
+ }()
+ } else {
+ s.runUserWorkspaceCleanups(ctx, handled)
+ }
logger.Infof(ctx, "All sessions deleted for tenant %d", tenantID)
return nil
}
+// WithWorkspaceCleaner enables user-mode session teardown.
+func (s *sessionService) WithWorkspaceCleaner(c *sandboxalloc.WorkspaceCleaner) {
+ s.workspaceCleaner = c
+}
+
+// userWorkspaceSessions identifies shared machines before legacy teardown.
+// This lookup does not retire anything; retirement commits with row deletion.
+func (s *sessionService) userWorkspaceSessions(ctx context.Context, ids []string) (map[string]bool, error) {
+ if s.workspaceCleaner == nil || len(ids) == 0 {
+ return nil, nil
+ }
+ return s.workspaceCleaner.UserSessions(ctx, ids)
+}
+
+// deleteSessionBatch commits every listed owner's deletion and retirement
+// together. Lite/host retain their existing repository-only deletion path.
+func (s *sessionService) deleteSessionBatch(
+ ctx context.Context, tenantID uint64, idsByOwner map[string][]string,
+) (map[string]bool, error) {
+ if s.workspaceCleaner != nil {
+ handled, _, err := s.workspaceCleaner.DeleteSessions(ctx, tenantID, idsByOwner)
+ return handled, err
+ }
+ for ownerID, ids := range idsByOwner {
+ if _, err := s.sessionRepo.BatchDelete(ctx, tenantID, ownerID, ids); err != nil {
+ return nil, err
+ }
+ }
+ return nil, nil
+}
+
+// runUserWorkspaceCleanups deletes released directories after the rows are
+// gone. It waits for each session's operations to drain, so it runs detached
+// from the request; anything left is retried by the user machine GC (T13).
+func (s *sessionService) runUserWorkspaceCleanups(ctx context.Context, handled map[string]bool) {
+ if s.workspaceCleaner == nil || len(handled) == 0 {
+ return
+ }
+ ids := make([]string, 0, len(handled))
+ for id := range handled {
+ ids = append(ids, id)
+ }
+ bg := context.WithoutCancel(ctx)
+ go s.workspaceCleaner.RunCleanups(bg, ids)
+}
+
// destroyBoundSandbox tears down the sandbox MicroVM bound to sessionID, if
// the configured sandbox backend supports session-scoped instances.
//
diff --git a/internal/application/service/session_delete_user_mode_test.go b/internal/application/service/session_delete_user_mode_test.go
new file mode 100644
index 000000000..142142595
--- /dev/null
+++ b/internal/application/service/session_delete_user_mode_test.go
@@ -0,0 +1,497 @@
+package service
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/stretchr/testify/require"
+ "gorm.io/driver/sqlite"
+ "gorm.io/gorm"
+ "gorm.io/gorm/logger"
+
+ "github.com/Tencent/WeKnora/internal/application/repository"
+ "github.com/Tencent/WeKnora/internal/application/service/sandboxalloc"
+ "github.com/Tencent/WeKnora/internal/sandbox"
+ "github.com/Tencent/WeKnora/internal/sandbox/admission"
+ "github.com/Tencent/WeKnora/internal/sandbox/allocation"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+)
+
+// userDeleteSessionID is a canonical UUID. Place refuses user mode for any
+// other shape, so the brief's illustrative "s-1" cannot be placed on a shared
+// machine. Session-mode cases below keep "s-1".
+const userDeleteSessionID = "0f8fad5b-d9cb-469f-a165-70867728950e"
+
+type recordingUserMachine struct {
+ t *testing.T
+ mu sync.Mutex
+ deleted [][]string
+ destroyed []string
+ rejectDestroy bool
+ onReclaim func()
+ onDelete func()
+}
+
+func (m *recordingUserMachine) Execute(context.Context, *sandbox.ExecuteConfig) (*sandbox.ExecuteResult, error) {
+ return nil, nil
+}
+func (m *recordingUserMachine) Cleanup(context.Context) error { return nil }
+func (m *recordingUserMachine) GetSandbox() sandbox.Sandbox { return nil }
+func (m *recordingUserMachine) GetType() sandbox.SandboxType { return sandbox.SandboxTypeCube }
+
+func (m *recordingUserMachine) DestroySession(_ context.Context, id string) error {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ m.destroyed = append(m.destroyed, id)
+ if m.rejectDestroy {
+ m.t.Errorf("DestroySession(%s) called on a shared machine", id)
+ }
+ return nil
+}
+
+func (m *recordingUserMachine) DeleteSessionWorkspaces(
+ _ context.Context, _ allocation.UserMachine, ids []string,
+) ([]string, error) {
+ if m.onDelete != nil {
+ m.onDelete()
+ }
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ copied := append([]string(nil), ids...)
+ m.deleted = append(m.deleted, copied)
+ return copied, nil
+}
+
+func (m *recordingUserMachine) ReclaimUserMachine(
+ context.Context, allocation.UserMachine, func(context.Context) (bool, error),
+) (bool, error) {
+ if m.onReclaim != nil {
+ m.onReclaim()
+ }
+ return true, nil
+}
+
+func (m *recordingUserMachine) workspaceDeletes() [][]string {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ out := make([][]string, len(m.deleted))
+ for i := range m.deleted {
+ out[i] = append([]string(nil), m.deleted[i]...)
+ }
+ return out
+}
+
+func (m *recordingUserMachine) destroyedIDs() []string {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ return append([]string(nil), m.destroyed...)
+}
+
+type allocationModeConfig string
+
+func (m allocationModeConfig) GetByID(
+ _ context.Context, tenantID uint64, id string,
+) (*types.TenantSandboxConfigEntity, error) {
+ return &types.TenantSandboxConfigEntity{
+ ID: id, TenantID: tenantID,
+ Config: &types.TenantSandboxConfig{AllocationMode: string(m)},
+ }, nil
+}
+
+type retireErrorRepo struct {
+ interfaces.SandboxAllocationRepository
+ err error
+}
+
+func (r retireErrorRepo) RetireSessions(context.Context, []string, time.Time) ([]interfaces.RetiredSession, error) {
+ return nil, r.err
+}
+
+func (r retireErrorRepo) DeleteSessionsRetiring(
+ context.Context, uint64, map[string][]string, time.Time,
+) ([]interfaces.RetiredSession, error) {
+ return nil, r.err
+}
+
+type userDeleteFixture struct {
+ svc *sessionService
+ alloc *sandboxalloc.Service
+ ops *recordingUserMachine
+ db *gorm.DB
+}
+
+func newUserDeleteFixture(t *testing.T, mode string, retireErr error) *userDeleteFixture {
+ t.Helper()
+ allocation.SetUserModeAvailable(true)
+ t.Cleanup(func() { allocation.SetUserModeAvailable(false) })
+
+ 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{},
+ ))
+
+ repo := repository.NewSandboxAllocationRepository(db)
+ if retireErr != nil {
+ repo = retireErrorRepo{SandboxAllocationRepository: repo, err: retireErr}
+ }
+ alloc := sandboxalloc.New(repo, allocationModeConfig(mode), repository.NewSessionRepository(db), "weknora")
+ ops := &recordingUserMachine{t: t, rejectDestroy: mode == "user" && retireErr == nil}
+ resolver := stubSandboxResolver{mgr: ops}
+ svc := &sessionService{
+ sessionRepo: repository.NewSessionRepository(db),
+ messageRepo: deleteForkMessageRepo{},
+ webSearchStateRepo: deleteForkWebSearchState{},
+ sandboxPinner: NewSessionSandboxPinner(db),
+ sandboxResolver: resolver,
+ forkSnapshots: &fakeForkSessionSnapshotDeleter{},
+ workspaceCleaner: sandboxalloc.NewWorkspaceCleaner(alloc, resolver),
+ }
+ return &userDeleteFixture{svc: svc, alloc: alloc, ops: ops, db: db}
+}
+
+func (f *userDeleteFixture) place(t *testing.T, id string) {
+ t.Helper()
+ require.NoError(t, f.db.Session(&gorm.Session{SkipHooks: true}).Create(&types.Session{
+ ID: id, TenantID: 7, UserID: "u-1", Title: "chat", OwnerAuthSource: types.AuthSourceWeb,
+ }).Error)
+ _, err := f.alloc.Place(context.Background(), sandboxalloc.PlaceRequest{
+ SessionTenantID: 7, SessionID: id, ConfigTenantID: 7, ConfigID: "cfg-a",
+ })
+ require.NoError(t, err)
+}
+
+func (f *userDeleteFixture) assignment(t *testing.T, id string) *types.SessionSandboxAssignment {
+ t.Helper()
+ row, err := f.alloc.Repo().GetAssignment(context.Background(), id)
+ require.NoError(t, err)
+ return row
+}
+
+func TestDeleteSessionOnUserMachineReleasesThenCleansAndNeverDestroys(t *testing.T) {
+ f := newUserDeleteFixture(t, "user", nil)
+ f.place(t, userDeleteSessionID)
+ ctx := testSessionScopeContext(7, "u-1")
+
+ require.NoError(t, f.svc.DeleteSession(ctx, userDeleteSessionID))
+
+ row := f.assignment(t, userDeleteSessionID)
+ require.NotNil(t, row)
+ require.NotNil(t, row.ReleasedAt, "the assignment is released before the row goes")
+ require.Eventually(t, func() bool {
+ again := f.assignment(t, userDeleteSessionID)
+ return again != nil && again.CleanupDueAt == nil && len(f.ops.workspaceDeletes()) == 1
+ }, 2*time.Second, 10*time.Millisecond)
+ require.Equal(t, []string{userDeleteSessionID}, f.ops.workspaceDeletes()[0])
+ require.Empty(t, f.ops.destroyedIDs())
+}
+
+func TestDeleteSessionFailsWhenTheReleaseCannotBePersisted(t *testing.T) {
+ boom := errors.New("retire sessions: database is closed")
+ f := newUserDeleteFixture(t, "user", boom)
+ f.place(t, userDeleteSessionID)
+ ctx := testSessionScopeContext(7, "u-1")
+
+ err := f.svc.DeleteSession(ctx, userDeleteSessionID)
+ require.ErrorIs(t, err, boom)
+ got, err := f.svc.sessionRepo.GetByID(ctx, 7, userDeleteSessionID)
+ require.NoError(t, err)
+ require.Equal(t, userDeleteSessionID, got.ID)
+ require.Nil(t, f.assignment(t, userDeleteSessionID).ReleasedAt)
+ require.Empty(t, f.ops.destroyedIDs())
+ require.Empty(t, f.ops.workspaceDeletes())
+}
+
+func TestSessionDeleteFailureRollsBackRetirement(t *testing.T) {
+ for _, operation := range []string{"single", "batch", "all"} {
+ t.Run(operation, func(t *testing.T) {
+ f := newUserDeleteFixture(t, "user", nil)
+ f.place(t, userDeleteSessionID)
+ ids := []string{userDeleteSessionID}
+ if operation != "single" {
+ ids = append(ids, uuid.NewString())
+ f.place(t, ids[1])
+ }
+ // Fail the actual soft delete after retirement has written its rows.
+ require.NoError(t, f.db.Exec(`CREATE TRIGGER reject_session_delete
+BEFORE UPDATE OF deleted_at ON sessions
+BEGIN SELECT RAISE(ABORT, 'injected session delete failure'); END`).Error)
+ ctx := testSessionScopeContext(7, "u-1")
+ var err error
+ switch operation {
+ case "single":
+ err = f.svc.DeleteSession(ctx, ids[0])
+ case "batch":
+ err = f.svc.BatchDeleteSessions(ctx, ids)
+ case "all":
+ err = f.svc.DeleteAllSessions(ctx)
+ }
+ require.ErrorContains(t, err, "injected session delete failure")
+ for _, id := range ids {
+ _, err := f.svc.sessionRepo.GetByID(ctx, 7, id)
+ require.NoError(t, err, "the failed deletion must leave the session usable")
+ row := f.assignment(t, id)
+ require.Nil(t, row.ReleasedAt)
+ require.Nil(t, row.CleanupDueAt, "GC must not remove files of the surviving session")
+ machine, err := f.alloc.Repo().GetUserMachine(ctx, row.MachineDigest)
+ require.NoError(t, err)
+ require.Nil(t, machine.EmptySince)
+ a, found, err := f.alloc.Lookup(ctx, id)
+ require.NoError(t, err)
+ require.True(t, found)
+ require.NoError(t, f.alloc.VerifySessionAllocation(ctx, 7, id, a))
+ }
+ require.Empty(t, f.ops.workspaceDeletes())
+ require.Empty(t, f.ops.destroyedIDs())
+ })
+ }
+}
+
+type reclaimLifecycleClient struct {
+ sealRemoteClient
+ deleted []string
+}
+
+func (c *reclaimLifecycleClient) Delete(_ context.Context, id string) error {
+ c.deleted = append(c.deleted, id)
+ return nil
+}
+
+func TestUserMachineReclaimCommitsWithRealManagerAndRepository(t *testing.T) {
+ for _, operation := range []string{"release", "gc"} {
+ t.Run(operation, func(t *testing.T) {
+ f := newUserDeleteFixture(t, "user", nil)
+ f.place(t, userDeleteSessionID)
+ client := &reclaimLifecycleClient{}
+ cfg := sandbox.DefaultConfig()
+ cfg.Type = sandbox.SandboxTypeCube
+ cfg.CubeTemplate = "tpl-test"
+ mgr, err := sandbox.NewSessionBoundManager(sandbox.SessionBoundManagerConfig{
+ Config: cfg, Client: client, Store: sandbox.NewMemorySessionSandboxBindingStore(),
+ Checker: alwaysExistsChecker{}, SkipHealthProbe: true,
+ ConfigID: "cfg-a", ConfigTenantID: 7, Namespace: "weknora",
+ Allocations: f.alloc, Admission: admission.NewMemory(),
+ })
+ require.NoError(t, err)
+ ctx := types.WithSandboxTenantID(context.Background(), 7)
+ _, err = mgr.ExecShellCommand(ctx, userDeleteSessionID, "true", "", time.Second, nil)
+ require.NoError(t, err)
+ sandboxID, found := mgr.BoundSandboxID(ctx, userDeleteSessionID)
+ require.True(t, found)
+ a, found, err := f.alloc.Lookup(ctx, userDeleteSessionID)
+ require.NoError(t, err)
+ require.True(t, found)
+ machine, ok := a.UserMachine()
+ require.True(t, ok)
+ _, err = f.alloc.Retire(ctx, []string{userDeleteSessionID})
+ require.NoError(t, err)
+ digest := f.alloc.Digest(machine)
+ require.NoError(t, f.db.Model(&types.SandboxUserMachine{}).
+ Where("machine_digest = ?", digest).
+ Update("empty_since", time.Now().Add(-8*24*time.Hour)).Error)
+ cleaner := sandboxalloc.NewWorkspaceCleaner(f.alloc, stubSandboxResolver{mgr: mgr})
+ if operation == "release" {
+ deleted, err := cleaner.ReleaseMachine(ctx, machine)
+ require.NoError(t, err)
+ require.True(t, deleted)
+ } else {
+ gc := sandboxalloc.NewUserMachineGC(f.alloc, cleaner, allocationModeConfig("user"), nil)
+ report, err := gc.RunOnce(ctx)
+ require.NoError(t, err)
+ require.Zero(t, report.Failed)
+ require.Equal(t, 1, report.Reclaimed)
+ }
+ require.Equal(t, []string{sandboxID}, client.deleted)
+ row, err := f.alloc.Repo().GetUserMachine(ctx, digest)
+ require.NoError(t, err)
+ require.Nil(t, row, "provider deletion and registry deletion must both complete")
+ })
+ }
+}
+
+func TestDeleteSessionOnPerSessionSandboxStillDestroys(t *testing.T) {
+ f := newUserDeleteFixture(t, "session", nil)
+ f.place(t, "s-1")
+ ctx := testSessionScopeContext(7, "u-1")
+
+ require.NoError(t, f.svc.DeleteSession(ctx, "s-1"))
+
+ require.Equal(t, []string{"s-1"}, f.ops.destroyedIDs())
+ require.Empty(t, f.ops.workspaceDeletes())
+ row := f.assignment(t, "s-1")
+ require.NotNil(t, row.ReleasedAt, "session mode is retired too")
+ require.Nil(t, row.CleanupDueAt, "a per-session sandbox has no directory cleanup task")
+}
+
+func TestBatchDeleteSessionsReleasesUserModeAndStillDestroysSessionMode(t *testing.T) {
+ f := newUserDeleteFixture(t, "user", nil)
+ f.ops.rejectDestroy = false
+ f.place(t, userDeleteSessionID)
+ // Place the per-session row through a session-mode allocator that shares
+ // the repository. The cleaner keeps the user-mode service it was built with.
+ legacy := sandboxalloc.New(f.alloc.Repo(), allocationModeConfig("session"),
+ repository.NewSessionRepository(f.db), "weknora")
+ require.NoError(t, f.db.Session(&gorm.Session{SkipHooks: true}).Create(&types.Session{
+ ID: "s-1", TenantID: 7, UserID: "u-1", Title: "legacy", OwnerAuthSource: types.AuthSourceWeb,
+ }).Error)
+ _, err := legacy.Place(context.Background(), sandboxalloc.PlaceRequest{
+ SessionTenantID: 7, SessionID: "s-1", ConfigTenantID: 7, ConfigID: "cfg-a",
+ })
+ require.NoError(t, err)
+ ctx := testSessionScopeContext(7, "u-1")
+
+ require.NoError(t, f.svc.BatchDeleteSessions(ctx, []string{userDeleteSessionID, "s-1"}))
+
+ require.Eventually(t, func() bool {
+ return len(f.ops.workspaceDeletes()) == 1
+ }, 2*time.Second, 10*time.Millisecond)
+ require.ElementsMatch(t, []string{userDeleteSessionID}, f.ops.workspaceDeletes()[0])
+ require.Equal(t, []string{"s-1"}, f.ops.destroyedIDs())
+ require.NotNil(t, f.assignment(t, userDeleteSessionID).ReleasedAt)
+ require.NotNil(t, f.assignment(t, "s-1").ReleasedAt)
+ require.Nil(t, f.assignment(t, "s-1").CleanupDueAt)
+}
+
+func TestDeleteAllSessionsOnUserMachineReleasesThenCleans(t *testing.T) {
+ f := newUserDeleteFixture(t, "user", nil)
+ f.place(t, userDeleteSessionID)
+ ctx := testSessionScopeContext(7, "u-1")
+
+ require.NoError(t, f.svc.DeleteAllSessions(ctx))
+
+ _, err := f.svc.sessionRepo.GetByID(ctx, 7, userDeleteSessionID)
+ require.Error(t, err, "the listed session row is deleted")
+ require.Eventually(t, func() bool {
+ again := f.assignment(t, userDeleteSessionID)
+ return again != nil && again.CleanupDueAt == nil && len(f.ops.workspaceDeletes()) == 1
+ }, 2*time.Second, 10*time.Millisecond)
+ require.Equal(t, []string{userDeleteSessionID}, f.ops.workspaceDeletes()[0])
+ require.Empty(t, f.ops.destroyedIDs())
+ require.NotNil(t, f.assignment(t, userDeleteSessionID).ReleasedAt)
+}
+
+func TestDeleteAllSessionsReclaimsBeforeDirectoryCleanup(t *testing.T) {
+ f := newUserDeleteFixture(t, "user", nil)
+ f.place(t, userDeleteSessionID)
+
+ reclaimEntered := make(chan struct{})
+ releaseReclaim := make(chan struct{})
+ var releaseOnce sync.Once
+ release := func() { releaseOnce.Do(func() { close(releaseReclaim) }) }
+ t.Cleanup(release)
+ deleteStarted := make(chan struct{}, 1)
+ f.ops.onReclaim = func() {
+ close(reclaimEntered)
+ <-releaseReclaim
+ }
+ f.ops.onDelete = func() {
+ select {
+ case deleteStarted <- struct{}{}:
+ default:
+ }
+ }
+ ctx := testSessionScopeContext(7, "u-1")
+ require.NoError(t, f.svc.DeleteAllSessions(ctx))
+
+ select {
+ case <-reclaimEntered:
+ case <-time.After(2 * time.Second):
+ t.Fatal("reclaim was not called")
+ }
+ select {
+ case <-deleteStarted:
+ t.Fatal("directory delete started before reclaim returned")
+ case <-time.After(200 * time.Millisecond):
+ }
+ release()
+
+ require.Eventually(t, func() bool {
+ return len(f.ops.workspaceDeletes()) == 1
+ }, 2*time.Second, 10*time.Millisecond)
+}
+
+func TestDeleteAllSessionsLeavesRowsWhenTheListFails(t *testing.T) {
+ f := newUserDeleteFixture(t, "user", nil)
+ f.place(t, userDeleteSessionID)
+ boom := errors.New("list sessions: database is closed")
+ f.svc.sessionRepo = listFailSessionRepo{SessionRepository: f.svc.sessionRepo, err: boom}
+ ctx := testSessionScopeContext(7, "u-1")
+
+ err := f.svc.DeleteAllSessions(ctx)
+ require.ErrorIs(t, err, boom)
+ var row types.Session
+ require.NoError(t, f.db.Where("id = ?", userDeleteSessionID).Take(&row).Error)
+ require.Equal(t, userDeleteSessionID, row.ID)
+ require.Nil(t, f.assignment(t, userDeleteSessionID).ReleasedAt, "a failed list must not retire")
+}
+
+func TestDeleteAllSessionsLeavesASessionCreatedAfterTheList(t *testing.T) {
+ f := newUserDeleteFixture(t, "user", nil)
+ f.place(t, userDeleteSessionID)
+ const lateID = "s-late"
+ f.svc.sessionRepo = &insertAfterListRepo{SessionRepository: f.svc.sessionRepo, db: f.db, lateID: lateID}
+ ctx := testSessionScopeContext(7, "u-1")
+
+ require.NoError(t, f.svc.DeleteAllSessions(ctx))
+
+ _, err := f.svc.sessionRepo.GetByID(ctx, 7, userDeleteSessionID)
+ require.Error(t, err, "the session that was listed is deleted")
+ var late types.Session
+ require.NoError(t, f.db.Where("id = ?", lateID).Take(&late).Error, "a session created after the list stays")
+}
+
+func TestDeleteAllSessionsFailsWhenTheReleaseCannotBePersisted(t *testing.T) {
+ boom := errors.New("retire sessions: database is closed")
+ f := newUserDeleteFixture(t, "user", boom)
+ f.place(t, userDeleteSessionID)
+ ctx := testSessionScopeContext(7, "u-1")
+
+ err := f.svc.DeleteAllSessions(ctx)
+ require.ErrorIs(t, err, boom)
+ var row types.Session
+ require.NoError(t, f.db.Where("id = ?", userDeleteSessionID).Take(&row).Error)
+ require.Nil(t, f.assignment(t, userDeleteSessionID).ReleasedAt)
+}
+
+type listFailSessionRepo struct {
+ interfaces.SessionRepository
+ err error
+}
+
+func (r listFailSessionRepo) GetByTenantID(context.Context, uint64, string) ([]*types.Session, error) {
+ return nil, r.err
+}
+
+// insertAfterListRepo returns the sessions that existed at list time, then
+// inserts another row. Delete-all must not remove that later row.
+type insertAfterListRepo struct {
+ interfaces.SessionRepository
+ db *gorm.DB
+ lateID string
+}
+
+func (r *insertAfterListRepo) GetByTenantID(
+ ctx context.Context, tenantID uint64, userID string,
+) ([]*types.Session, error) {
+ listed, err := r.SessionRepository.GetByTenantID(ctx, tenantID, userID)
+ if err != nil {
+ return nil, err
+ }
+ err = r.db.Session(&gorm.Session{SkipHooks: true}).Create(&types.Session{
+ ID: r.lateID, TenantID: tenantID, UserID: userID, Title: "late", OwnerAuthSource: types.AuthSourceWeb,
+ }).Error
+ if err != nil {
+ return nil, err
+ }
+ return listed, nil
+}
diff --git a/internal/application/service/session_fork.go b/internal/application/service/session_fork.go
index ba1e8f520..678287a41 100644
--- a/internal/application/service/session_fork.go
+++ b/internal/application/service/session_fork.go
@@ -16,9 +16,12 @@ import (
"strings"
"time"
+ "github.com/Tencent/WeKnora/internal/application/service/sandboxalloc"
apperrors "github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/sandbox"
+ "github.com/Tencent/WeKnora/internal/sandbox/admission"
+ "github.com/Tencent/WeKnora/internal/sandbox/allocation"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/google/uuid"
@@ -49,6 +52,10 @@ const (
// ForkDegradeSnapshotUnsupported means snapshotting failed or the backend
// does not support it.
ForkDegradeSnapshotUnsupported ForkDegradeReason = "SNAPSHOT_UNSUPPORTED"
+
+ // ForkDegradeCopyFailed means the shared machine could not copy the source
+ // session's checkpoint into the new session's directory.
+ ForkDegradeCopyFailed ForkDegradeReason = "COPY_FAILED"
)
var (
@@ -141,11 +148,27 @@ type forkMessageStore interface {
) ([]*types.Message, error)
}
+type forkAllocations interface {
+ Lookup(ctx context.Context, sessionID string) (allocation.Assignment, bool, error)
+ ForkAssignment(source allocation.Assignment, targetSessionID string) allocation.Assignment
+ Digest(m allocation.UserMachine) string
+}
+
+type forkWorkspaceStarter interface {
+ BeginWorkspaceFork(ctx context.Context, sourceSessionID string) (sandbox.WorkspaceFork, error)
+}
+
+type forkWithAssignmentStore interface {
+ CreateForkedWithAssignment(ctx context.Context, session *types.Session, messages []*types.Message,
+ assignment *types.SessionSandboxAssignment, machine *types.SandboxUserMachine) error
+}
+
// SessionForkService implements the fork decision chain.
type SessionForkService struct {
- sessions forkSessionStore
- messages forkMessageStore
- sandbox SessionForkSandboxPort
+ sessions forkSessionStore
+ messages forkMessageStore
+ sandbox SessionForkSandboxPort
+ allocations forkAllocations
}
// NewSessionForkService wires the service. A nil sandbox port makes every fork
@@ -168,6 +191,12 @@ func NewSessionForkServiceFromRepos(
return NewSessionForkService(sessions, messages, sandboxPort)
}
+// WithAllocations enables user-mode forks.
+func (s *SessionForkService) WithAllocations(a forkAllocations) *SessionForkService {
+ s.allocations = a
+ return s
+}
+
// Fork branches sourceSessionID at messageID.
//
// Errors are reserved for conditions the user must act on: a bad request, a
@@ -231,16 +260,22 @@ func (s *SessionForkService) Fork(
}
}
- history, err := s.messages.ListMessagesBySessionUpTo(
- ctx, sourceSessionID, forkPoint.CreatedAt, forkPoint.ID,
- )
- if err != nil {
- return nil, fmt.Errorf("session fork: load history: %w", err)
- }
- history = historyThroughForkPoint(history, forkPoint)
-
workCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), forkSnapshotTimeout)
defer cancel()
+ if s.allocations != nil {
+ srcAssign, ok, err := s.allocations.Lookup(workCtx, source.ID)
+ if err != nil {
+ return nil, fmt.Errorf("session fork: read source allocation: %w", err)
+ }
+ if ok && srcAssign.IsUser() {
+ return s.forkOnSharedMachine(workCtx, source, forkPoint, title, srcAssign)
+ }
+ }
+
+ history, err := s.loadForkHistory(ctx, sourceSessionID, forkPoint)
+ if err != nil {
+ return nil, err
+ }
bootstrap, reason, createdSnapshot, prepErr := s.prepareBootstrap(workCtx, source, history)
if prepErr != nil {
@@ -295,6 +330,145 @@ func (s *SessionForkService) Fork(
}, nil
}
+// loadForkHistory lists the source's messages through the fork point.
+func (s *SessionForkService) loadForkHistory(
+ ctx context.Context, sourceSessionID string, forkPoint *types.Message,
+) ([]*types.Message, error) {
+ history, err := s.messages.ListMessagesBySessionUpTo(ctx, sourceSessionID, forkPoint.CreatedAt, forkPoint.ID)
+ if err != nil {
+ return nil, fmt.Errorf("session fork: load history: %w", err)
+ }
+ return historyThroughForkPoint(history, forkPoint), nil
+}
+
+// forkOnSharedMachine branches a user-mode session (C9). The workspace is
+// copied before the database commit, so nothing runs in the new directory
+// before the session exists; the fork handle keeps the source machine fixed
+// from the history read to the compensation.
+func (s *SessionForkService) forkOnSharedMachine(
+ ctx context.Context, source *types.Session, forkPoint *types.Message,
+ title string, srcAssign allocation.Assignment,
+) (*ForkResult, error) {
+ newID := uuid.New().String()
+ reason := ForkDegradeReason("")
+ var reachable map[string]bool
+ var fork sandbox.WorkspaceFork
+
+ starter, ok := s.sandbox.(forkWorkspaceStarter)
+ if !ok {
+ return nil, errors.New("session fork: this sandbox backend cannot fork a shared-machine session")
+ }
+ f, err := starter.BeginWorkspaceFork(ctx, source.ID)
+ switch {
+ case err == nil:
+ fork = f
+ defer fork.Release()
+ case errors.Is(err, sandbox.ErrSessionWorkspaceBusy), errors.Is(err, admission.ErrClosed):
+ return nil, ErrForkSourceBusy
+ case errors.Is(err, sandbox.ErrNoLiveSessionSandbox):
+ reason = ForkDegradeSandboxGone
+ default:
+ // Identity rejected, session deleted or retired, lease or infra
+ // failure: not a file-copy problem, so no branch is created (C9).
+ return nil, fmt.Errorf("session fork: open shared-machine fork: %w", err)
+ }
+ stepCtx := ctx
+ if fork != nil {
+ stepCtx = fork.Context()
+ busy, err := s.sandbox.HasActiveTurn(stepCtx, source.ID)
+ if err != nil {
+ return nil, fmt.Errorf("session fork: recheck source turn state: %w", err)
+ }
+ if busy {
+ return nil, ErrForkSourceBusy
+ }
+ }
+
+ history, err := s.loadForkHistory(stepCtx, source.ID, forkPoint)
+ if err != nil {
+ return nil, err
+ }
+ checkpoint := latestCheckpoint(history)
+ switch {
+ case checkpoint == nil && !hasAssistantMessage(history):
+ reason = ""
+ case checkpoint == nil:
+ reason = ForkDegradeNoCheckpoint
+ case fork == nil:
+ case checkpoint.SandboxID != fork.SandboxID():
+ reason = ForkDegradeSandboxReplaced
+ default:
+ candidates := make([]string, 0, len(history))
+ for _, m := range history {
+ if m.SandboxCheckpoint != nil {
+ candidates = append(candidates, m.SandboxCheckpoint.CommitSHA)
+ }
+ }
+ reachable, err = fork.Copy(newID, checkpoint.CommitSHA, candidates)
+ if err != nil {
+ if lost := forkLeaseLost(stepCtx, err); lost != nil {
+ return nil, fmt.Errorf("session fork: lost the source machine during copy: %w", lost)
+ }
+ logger.Warnf(ctx, "[SessionFork] copy workspace source=%s: %v", source.ID, err)
+ reason, reachable = ForkDegradeCopyFailed, nil
+ }
+ }
+
+ messages := copyMessagesInto(newID, history)
+ for _, m := range messages {
+ cp := m.SandboxCheckpoint
+ if cp != nil && (fork == nil || cp.SandboxID != fork.SandboxID() || !reachable[cp.CommitSHA]) {
+ m.SandboxCheckpoint = nil
+ }
+ }
+ newSession := &types.Session{
+ ID: newID, TenantID: source.TenantID, UserID: source.UserID,
+ OwnerAuthSource: source.OwnerAuthSource,
+ Title: forkTitle(title, source.Title), Description: source.Description,
+ LastRequestState: source.LastRequestState,
+ SandboxConfigID: source.SandboxConfigID, SandboxConfigTenantID: source.SandboxConfigTenantID,
+ ParentSessionID: source.ID, ForkedFromMessageID: forkPoint.ID,
+ }
+ child := s.allocations.ForkAssignment(srcAssign, newID)
+ machine, _ := child.UserMachine()
+ entity, machineRow := sandboxalloc.ToEntity(child, s.allocations.Digest(machine))
+
+ store, ok := s.sessions.(forkWithAssignmentStore)
+ if !ok {
+ return nil, errors.New("session fork: store cannot persist a user-mode fork")
+ }
+ if fork != nil {
+ if cause := context.Cause(stepCtx); cause != nil {
+ // Lost before the commit: the copy may already be gone with the
+ // machine, and the compensation could not run safely either.
+ return nil, fmt.Errorf("session fork: lost the source machine before commit: %w", cause)
+ }
+ }
+ if err := store.CreateForkedWithAssignment(stepCtx, newSession, messages, entity, machineRow); err != nil {
+ if reachable != nil {
+ if rmErr := fork.Remove(newID); rmErr != nil {
+ logger.Warnf(ctx, "[SessionFork] remove orphan workspace %s: %v", newID, rmErr)
+ }
+ }
+ return nil, fmt.Errorf("session fork: persist forked session: %w", err)
+ }
+ logger.Infof(ctx, "[SessionFork] shared-machine source=%s fork_point=%s new=%s degraded=%v reason=%s",
+ source.ID, forkPoint.ID, newID, reason != "", reason)
+ return &ForkResult{SessionID: newID, Degraded: reason != "", Reason: reason}, nil
+}
+
+// forkLeaseLost reports a lost admission hold. A copy that failed for any
+// other reason is a file problem and degrades; losing the lease is not.
+func forkLeaseLost(ctx context.Context, err error) error {
+ if cause := context.Cause(ctx); cause != nil {
+ return cause
+ }
+ if errors.Is(err, admission.ErrLeaseLost) {
+ return err
+ }
+ return nil
+}
+
// prepareBootstrap decides whether the fork can carry the source sandbox's
// workspace state. When every condition holds, it takes a snapshot.
//
diff --git a/internal/application/service/session_fork_test.go b/internal/application/service/session_fork_test.go
index e29c05076..d23cad5c7 100644
--- a/internal/application/service/session_fork_test.go
+++ b/internal/application/service/session_fork_test.go
@@ -8,6 +8,9 @@ import (
"testing"
"time"
+ "github.com/Tencent/WeKnora/internal/sandbox"
+ "github.com/Tencent/WeKnora/internal/sandbox/admission"
+ "github.com/Tencent/WeKnora/internal/sandbox/allocation"
"github.com/Tencent/WeKnora/internal/types"
"github.com/stretchr/testify/require"
)
@@ -27,14 +30,20 @@ type fakeForkSandboxPort struct {
snapshotCtxErr error
deleted []string
deleteErr error
+ beginErr error
+ beginCalls int
+ workspace *fakeWorkspaceFork
+ calls *[]string
+ hasActiveCtxs []context.Context
}
func (f *fakeForkSandboxPort) BoundSandboxID(context.Context, string) (string, bool) {
return f.boundID, f.bound
}
-func (f *fakeForkSandboxPort) HasActiveTurn(context.Context, string) (bool, error) {
+func (f *fakeForkSandboxPort) HasActiveTurn(ctx context.Context, _ string) (bool, error) {
f.hasActiveCalls++
+ f.hasActiveCtxs = append(f.hasActiveCtxs, ctx)
if f.activeTurnErr != nil {
return false, f.activeTurnErr
}
@@ -65,21 +74,109 @@ func (f *fakeForkSandboxPort) DeleteForkSnapshot(_ context.Context, _, snapshotI
return f.deleteErr
}
+func (f *fakeForkSandboxPort) BeginWorkspaceFork(context.Context, string) (sandbox.WorkspaceFork, error) {
+ noteForkCall(f.calls, "Begin")
+ f.beginCalls++
+ if f.beginErr != nil {
+ return nil, f.beginErr
+ }
+ if f.workspace == nil {
+ f.workspace = &fakeWorkspaceFork{id: f.boundID}
+ }
+ if f.workspace.id == "" {
+ f.workspace.id = f.boundID
+ }
+ f.workspace.calls = f.calls
+ return f.workspace, nil
+}
+
+// fakeWorkspaceFork is an open shared-machine fork the service drives.
+type fakeWorkspaceFork struct {
+ id string
+ ctx context.Context
+ cancel context.CancelCauseFunc
+ reachable map[string]bool
+ copyErr error
+ loseLeaseOnCopy bool
+ copied int
+ copyTarget string
+ copySHA string
+ copyCandidates []string
+ removed []string
+ released int
+ calls *[]string
+}
+
+func (f *fakeWorkspaceFork) SandboxID() string { return f.id }
+
+func (f *fakeWorkspaceFork) Context() context.Context {
+ if f.ctx == nil {
+ return context.Background()
+ }
+ return f.ctx
+}
+
+func (f *fakeWorkspaceFork) Copy(targetSessionID, sha string, candidates []string) (map[string]bool, error) {
+ noteForkCall(f.calls, "Copy")
+ f.copied++
+ f.copyTarget = targetSessionID
+ f.copySHA = sha
+ f.copyCandidates = append([]string(nil), candidates...)
+ if f.loseLeaseOnCopy && f.cancel != nil {
+ f.cancel(admission.ErrLeaseLost)
+ }
+ if f.copyErr != nil {
+ return nil, f.copyErr
+ }
+ if f.reachable == nil {
+ return map[string]bool{}, nil
+ }
+ out := make(map[string]bool, len(f.reachable))
+ for k, v := range f.reachable {
+ out[k] = v
+ }
+ return out, nil
+}
+
+func (f *fakeWorkspaceFork) Remove(targetSessionID string) error {
+ noteForkCall(f.calls, "Remove")
+ f.removed = append(f.removed, targetSessionID)
+ return nil
+}
+
+func (f *fakeWorkspaceFork) Release() {
+ noteForkCall(f.calls, "Release")
+ f.released++
+}
+
+func noteForkCall(calls *[]string, name string) {
+ if calls == nil {
+ return
+ }
+ *calls = append(*calls, name)
+}
+
// fakeSessionStore is the narrow session port SessionForkService needs.
type fakeSessionStore struct {
- source *types.Session
- created *types.Session
- copiedMessages []*types.Message
- copiedOrigIDs []string
- origIDsFrom *fakeMessageStore
- getErr error
- updatedBootstrap *types.ForkBootstrap
- bootstrapCleared bool
- clearErr error
- updateErr error
- unconsumed []*types.Session
- createErr error
- leases []*types.ForkSnapshotLease
+ source *types.Session
+ created *types.Session
+ copiedMessages []*types.Message
+ copiedOrigIDs []string
+ origIDsFrom *fakeMessageStore
+ getErr error
+ updatedBootstrap *types.ForkBootstrap
+ bootstrapCleared bool
+ clearErr error
+ updateErr error
+ unconsumed []*types.Session
+ createErr error
+ leases []*types.ForkSnapshotLease
+ calls *[]string
+ assignCalls int
+ assignCtx context.Context
+ assigned *types.SessionSandboxAssignment
+ assignedMachine *types.SandboxUserMachine
+ lastAssignSession string
}
func newFakeSessionStore(src *types.Session) *fakeSessionStore {
@@ -196,6 +293,38 @@ func (f *fakeSessionStore) ListStaleForkSnapshotLeases(
return out, nil
}
+func (f *fakeSessionStore) CreateForkedWithAssignment(
+ ctx context.Context, session *types.Session, messages []*types.Message,
+ assignment *types.SessionSandboxAssignment, machine *types.SandboxUserMachine,
+) error {
+ noteForkCall(f.calls, "CreateForkedWithAssignment")
+ f.assignCalls++
+ f.assignCtx = ctx
+ if session != nil {
+ f.lastAssignSession = session.ID
+ }
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ if f.createErr != nil {
+ return f.createErr
+ }
+ f.created = session
+ f.copiedMessages = append([]*types.Message(nil), messages...)
+ if assignment != nil {
+ copied := *assignment
+ f.assigned = &copied
+ }
+ if machine != nil {
+ copied := *machine
+ f.assignedMachine = &copied
+ }
+ if f.origIDsFrom != nil {
+ f.copiedOrigIDs = append([]string(nil), f.origIDsFrom.lastListedIDs...)
+ }
+ return nil
+}
+
func (f *fakeSessionStore) CreateForked(ctx context.Context, session *types.Session, messages []*types.Message) error {
if err := ctx.Err(); err != nil {
return err
@@ -228,6 +357,8 @@ type fakeMessageStore struct {
deleteFromFailTimes int
tombstoned []types.ArtifactRef
liveArtifacts []types.MessageArtifactRecord
+ calls *[]string
+ lastListCtx context.Context
}
func newFakeMessageStore(messages []*types.Message) *fakeMessageStore {
@@ -276,8 +407,10 @@ func (f *fakeMessageStore) GetMessagesBySession(
}
func (f *fakeMessageStore) ListMessagesBySessionUpTo(
- _ context.Context, sessionID string, boundary time.Time, boundaryID string,
+ ctx context.Context, sessionID string, boundary time.Time, boundaryID string,
) ([]*types.Message, error) {
+ noteForkCall(f.calls, "ListMessagesBySessionUpTo")
+ f.lastListCtx = ctx
var out []*types.Message
for _, m := range f.messages {
if m == nil || m.SessionID != sessionID {
@@ -1081,3 +1214,299 @@ func TestForkInheritsHostWorkspaceDir(t *testing.T) {
require.NotNil(t, sessions.created)
require.Equal(t, "/Users/dev/My Project", sessions.created.HostWorkspaceDir)
}
+
+type forkMarkerKey struct{}
+
+func userModeForkAssignment() allocation.Assignment {
+ return allocation.Assignment{
+ SessionID: "src", ConfigTenantID: 1, ConfigID: "cfg-1",
+ Machine: allocation.UserMachine{
+ OwnerTenantID: 1, OwnerID: "u1", ConfigTenantID: 1, ConfigID: "cfg-1",
+ },
+ }
+}
+
+type fakeForkAllocations struct {
+ assignment allocation.Assignment
+ found bool
+ err error
+}
+
+func (f *fakeForkAllocations) Lookup(context.Context, string) (allocation.Assignment, bool, error) {
+ if f.err != nil {
+ return allocation.Assignment{}, false, f.err
+ }
+ return f.assignment, f.found, nil
+}
+
+func (f *fakeForkAllocations) ForkAssignment(
+ source allocation.Assignment, targetSessionID string,
+) allocation.Assignment {
+ child := source
+ child.SessionID = targetSessionID
+ child.ReleasedAt = nil
+ return child
+}
+
+func (f *fakeForkAllocations) Digest(m allocation.UserMachine) string {
+ return m.Digest("weknora")
+}
+
+func newSharedMachineFork(
+ t *testing.T, port *fakeForkSandboxPort, messages []*types.Message,
+) (*SessionForkService, *fakeSessionStore, *fakeMessageStore, *[]string) {
+ t.Helper()
+ calls := []string{}
+ port.calls = &calls
+ if port.workspace != nil {
+ port.workspace.calls = &calls
+ }
+ svc, sessions, msgs := newForkFixture(t, port, messages)
+ sessions.calls = &calls
+ msgs.calls = &calls
+ sessions.source.OwnerAuthSource = "web"
+ svc.WithAllocations(&fakeForkAllocations{assignment: userModeForkAssignment(), found: true})
+ return svc, sessions, msgs, &calls
+}
+
+func userForkPoint() *types.Message {
+ return &types.Message{
+ ID: "u-msg-2", SessionID: "src", Role: "user", CreatedAt: forkBase.Add(10 * time.Second),
+ }
+}
+
+func TestForkOnSharedMachineCopiesAndInheritsAssignment(t *testing.T) {
+ turn := checkpointedTurn("u-msg-1", "a-msg-1", "sb-1", "sha1", 0)
+ port := &fakeForkSandboxPort{
+ boundID: "sb-1", bound: true, snapshotID: "snap-should-not-run",
+ workspace: &fakeWorkspaceFork{id: "sb-1", reachable: map[string]bool{"sha1": true}},
+ }
+ svc, sessions, _, calls := newSharedMachineFork(t, port, append(turn, userForkPoint()))
+
+ got, err := svc.Fork(context.Background(), 1, "u1", "src", "u-msg-2", "")
+
+ require.NoError(t, err)
+ require.False(t, got.Degraded)
+ require.Empty(t, got.Reason)
+ require.Zero(t, port.snapshotCalls)
+ require.NotNil(t, sessions.assigned)
+ require.Equal(t, got.SessionID, sessions.assigned.SessionID)
+ require.NotEqual(t, "src", sessions.assigned.SessionID)
+ machine, ok := userModeForkAssignment().UserMachine()
+ require.True(t, ok)
+ require.Equal(t, machine.Digest("weknora"), sessions.assigned.MachineDigest)
+ require.NotNil(t, sessions.assignedMachine)
+ require.Equal(t, sessions.assigned.MachineDigest, sessions.assignedMachine.MachineDigest)
+ require.Equal(t, "u1", sessions.assignedMachine.OwnerID)
+ require.Nil(t, sessions.assignedMachine.EmptySince)
+ require.Equal(t, "web", sessions.created.OwnerAuthSource)
+ require.Nil(t, sessions.created.ForkBootstrap)
+ require.Equal(t, []string{
+ "Begin", "ListMessagesBySessionUpTo", "Copy", "CreateForkedWithAssignment", "Release",
+ }, *calls)
+}
+
+func TestForkOnSharedMachineKeepsOnlyReachableMatchingCheckpoints(t *testing.T) {
+ history := []*types.Message{
+ {ID: "u1", SessionID: "src", Role: "user", CreatedAt: forkBase},
+ {
+ ID: "a1", SessionID: "src", Role: "assistant", CreatedAt: forkBase.Add(time.Second), IsCompleted: true,
+ SandboxCheckpoint: &types.SandboxCheckpoint{SandboxID: "sb-1", CommitSHA: "sha1"},
+ },
+ {ID: "u2", SessionID: "src", Role: "user", CreatedAt: forkBase.Add(2 * time.Second)},
+ {
+ ID: "a2", SessionID: "src", Role: "assistant", CreatedAt: forkBase.Add(3 * time.Second), IsCompleted: true,
+ SandboxCheckpoint: &types.SandboxCheckpoint{SandboxID: "sb-old", CommitSHA: "sha2"},
+ },
+ {ID: "u3", SessionID: "src", Role: "user", CreatedAt: forkBase.Add(4 * time.Second)},
+ {
+ ID: "a3", SessionID: "src", Role: "assistant", CreatedAt: forkBase.Add(5 * time.Second), IsCompleted: true,
+ SandboxCheckpoint: &types.SandboxCheckpoint{SandboxID: "sb-1", CommitSHA: "sha3"},
+ },
+ {ID: "u-fork", SessionID: "src", Role: "user", CreatedAt: forkBase.Add(6 * time.Second)},
+ }
+ port := &fakeForkSandboxPort{
+ workspace: &fakeWorkspaceFork{id: "sb-1", reachable: map[string]bool{"sha3": true, "sha1": true}},
+ }
+ svc, sessions, _, _ := newSharedMachineFork(t, port, history)
+
+ got, err := svc.Fork(context.Background(), 1, "u1", "src", "u-fork", "")
+
+ require.NoError(t, err)
+ require.False(t, got.Degraded)
+ require.Len(t, sessions.copiedMessages, 6)
+ require.Equal(t, "sha1", sessions.copiedMessages[1].SandboxCheckpoint.CommitSHA)
+ require.Equal(t, "sb-1", sessions.copiedMessages[1].SandboxCheckpoint.SandboxID)
+ require.Nil(t, sessions.copiedMessages[3].SandboxCheckpoint)
+ require.Equal(t, "sha3", sessions.copiedMessages[5].SandboxCheckpoint.CommitSHA)
+ require.Equal(t, []string{"sha1", "sha2", "sha3"}, port.workspace.copyCandidates)
+ require.Equal(t, "sha3", port.workspace.copySHA)
+}
+
+func TestForkOnSharedMachineReplacedSandboxDegrades(t *testing.T) {
+ turn := checkpointedTurn("u-msg-1", "a-msg-1", "sb-old", "sha-old", 0)
+ port := &fakeForkSandboxPort{
+ workspace: &fakeWorkspaceFork{id: "sb-1", reachable: map[string]bool{"sha-old": true}},
+ }
+ svc, sessions, _, calls := newSharedMachineFork(t, port, append(turn, userForkPoint()))
+
+ got, err := svc.Fork(context.Background(), 1, "u1", "src", "u-msg-2", "")
+
+ require.NoError(t, err)
+ require.True(t, got.Degraded)
+ require.Equal(t, ForkDegradeSandboxReplaced, got.Reason)
+ require.Zero(t, port.workspace.copied)
+ require.NotContains(t, *calls, "Copy")
+ require.Contains(t, *calls, "Release")
+ for _, m := range sessions.copiedMessages {
+ require.Nil(t, m.SandboxCheckpoint)
+ }
+}
+
+func TestForkOnSharedMachineCopyFailureDegrades(t *testing.T) {
+ turn := checkpointedTurn("u-msg-1", "a-msg-1", "sb-1", "sha1", 0)
+ port := &fakeForkSandboxPort{
+ workspace: &fakeWorkspaceFork{id: "sb-1", copyErr: errors.New("disk full")},
+ }
+ svc, sessions, _, calls := newSharedMachineFork(t, port, append(turn, userForkPoint()))
+
+ got, err := svc.Fork(context.Background(), 1, "u1", "src", "u-msg-2", "")
+
+ require.NoError(t, err)
+ require.True(t, got.Degraded)
+ require.Equal(t, ForkDegradeCopyFailed, got.Reason)
+ require.NotContains(t, *calls, "Remove")
+ require.Empty(t, port.workspace.removed)
+ for _, m := range sessions.copiedMessages {
+ require.Nil(t, m.SandboxCheckpoint)
+ }
+}
+
+func TestForkOnSharedMachineRemovesTheCopyWhenCommitFails(t *testing.T) {
+ turn := checkpointedTurn("u-msg-1", "a-msg-1", "sb-1", "sha1", 0)
+ port := &fakeForkSandboxPort{
+ workspace: &fakeWorkspaceFork{id: "sb-1", reachable: map[string]bool{"sha1": true}},
+ }
+ svc, sessions, _, calls := newSharedMachineFork(t, port, append(turn, userForkPoint()))
+ sessions.createErr = errors.New("db down")
+
+ got, err := svc.Fork(context.Background(), 1, "u1", "src", "u-msg-2", "")
+
+ require.Nil(t, got)
+ require.Error(t, err)
+ require.Equal(t, []string{sessions.lastAssignSession}, port.workspace.removed)
+ require.NotEmpty(t, sessions.lastAssignSession)
+ require.Equal(t, []string{"Remove", "Release"}, (*calls)[len(*calls)-2:])
+}
+
+func TestForkOnSharedMachineBusySourceIsRefused(t *testing.T) {
+ turn := checkpointedTurn("u-msg-1", "a-msg-1", "sb-1", "sha1", 0)
+ port := &fakeForkSandboxPort{beginErr: sandbox.ErrSessionWorkspaceBusy}
+ svc, sessions, _, _ := newSharedMachineFork(t, port, append(turn, userForkPoint()))
+
+ got, err := svc.Fork(context.Background(), 1, "u1", "src", "u-msg-2", "")
+
+ require.Nil(t, got)
+ require.ErrorIs(t, err, ErrForkSourceBusy)
+ require.Zero(t, sessions.assignCalls)
+}
+
+func TestForkOnSharedMachineRechecksTheTurnInsideTheWindow(t *testing.T) {
+ turn := checkpointedTurn("u-msg-1", "a-msg-1", "sb-1", "sha1", 0)
+ port := &fakeForkSandboxPort{
+ forceBusyAfter: 2,
+ workspace: &fakeWorkspaceFork{id: "sb-1"},
+ }
+ svc, sessions, _, calls := newSharedMachineFork(t, port, append(turn, userForkPoint()))
+
+ got, err := svc.Fork(context.Background(), 1, "u1", "src", "u-msg-2", "")
+
+ require.Nil(t, got)
+ require.ErrorIs(t, err, ErrForkSourceBusy)
+ require.Zero(t, port.workspace.copied)
+ require.NotContains(t, *calls, "Copy")
+ require.Zero(t, sessions.assignCalls)
+ require.NotContains(t, *calls, "CreateForkedWithAssignment")
+ require.Contains(t, *calls, "Release")
+ require.Equal(t, 1, port.workspace.released)
+}
+
+func TestForkOnSharedMachineRejectionIsAnErrorNotADegradedBranch(t *testing.T) {
+ turn := checkpointedTurn("u-msg-1", "a-msg-1", "sb-1", "sha1", 0)
+ messages := append(turn, userForkPoint())
+ for _, beginErr := range []error{
+ sandbox.ErrUserAllocationRejected, sandbox.ErrSandboxSessionDeleted, admission.ErrLeaseLost,
+ } {
+ beginErr := beginErr
+ t.Run(beginErr.Error(), func(t *testing.T) {
+ port := &fakeForkSandboxPort{beginErr: beginErr}
+ svc, sessions, _, _ := newSharedMachineFork(t, port, messages)
+ got, err := svc.Fork(context.Background(), 1, "u1", "src", "u-msg-2", "")
+ require.Nil(t, got)
+ require.ErrorIs(t, err, beginErr)
+ require.Zero(t, sessions.assignCalls)
+ require.Nil(t, sessions.created)
+ })
+ }
+}
+
+func TestForkOnSharedMachineLostLeaseBeforeCommitCreatesNothing(t *testing.T) {
+ turn := checkpointedTurn("u-msg-1", "a-msg-1", "sb-1", "sha1", 0)
+ forkCtx, cancel := context.WithCancelCause(context.Background())
+ t.Cleanup(func() { cancel(nil) })
+ port := &fakeForkSandboxPort{
+ workspace: &fakeWorkspaceFork{
+ id: "sb-1", ctx: forkCtx, cancel: cancel,
+ reachable: map[string]bool{"sha1": true}, loseLeaseOnCopy: true,
+ },
+ }
+ svc, sessions, _, _ := newSharedMachineFork(t, port, append(turn, userForkPoint()))
+
+ got, err := svc.Fork(context.Background(), 1, "u1", "src", "u-msg-2", "")
+
+ require.Nil(t, got)
+ require.ErrorIs(t, err, admission.ErrLeaseLost)
+ require.Zero(t, sessions.assignCalls)
+ require.Nil(t, sessions.created)
+}
+
+func TestForkOnSharedMachineReadsAndCommitsWithTheForkContext(t *testing.T) {
+ turn := checkpointedTurn("u-msg-1", "a-msg-1", "sb-1", "sha1", 0)
+ marked := context.WithValue(context.Background(), forkMarkerKey{}, "fork-window")
+ port := &fakeForkSandboxPort{
+ workspace: &fakeWorkspaceFork{
+ id: "sb-1", ctx: marked, reachable: map[string]bool{"sha1": true},
+ },
+ }
+ svc, sessions, msgs, _ := newSharedMachineFork(t, port, append(turn, userForkPoint()))
+
+ _, err := svc.Fork(context.Background(), 1, "u1", "src", "u-msg-2", "")
+
+ require.NoError(t, err)
+ require.Equal(t, "fork-window", msgs.lastListCtx.Value(forkMarkerKey{}))
+ require.Equal(t, "fork-window", sessions.assignCtx.Value(forkMarkerKey{}))
+ require.GreaterOrEqual(t, len(port.hasActiveCtxs), 2)
+ require.Equal(t, "fork-window", port.hasActiveCtxs[len(port.hasActiveCtxs)-1].Value(forkMarkerKey{}))
+}
+
+func TestForkOfSessionModeSourceStillSnapshots(t *testing.T) {
+ turn := checkpointedTurn("u-msg-1", "a-msg-1", "sbx-1", "sha1", 0)
+ port := &fakeForkSandboxPort{boundID: "sbx-1", bound: true, snapshotID: "snap-1"}
+ svc, sessions, _ := newForkFixture(t, port, append(turn, userForkPoint()))
+ svc.WithAllocations(&fakeForkAllocations{
+ found: true,
+ assignment: allocation.Assignment{
+ SessionID: "src", ConfigTenantID: 1, ConfigID: "cfg-1",
+ },
+ })
+
+ got, err := svc.Fork(context.Background(), 1, "u1", "src", "u-msg-2", "")
+
+ require.NoError(t, err)
+ require.False(t, got.Degraded)
+ require.Equal(t, 1, port.snapshotCalls)
+ require.Zero(t, port.beginCalls)
+ require.Zero(t, sessions.assignCalls)
+ require.NotNil(t, sessions.created.ForkBootstrap)
+ require.Equal(t, "snap-1", sessions.created.ForkBootstrap.SnapshotID)
+}
diff --git a/internal/application/service/session_rewind.go b/internal/application/service/session_rewind.go
index 2eaab1df4..a9db1d3c4 100644
--- a/internal/application/service/session_rewind.go
+++ b/internal/application/service/session_rewind.go
@@ -95,7 +95,10 @@ type RewindResult struct {
type SessionRewindSandboxPort interface {
BoundSandboxID(ctx context.Context, sessionID string) (string, bool)
HasActiveTurn(ctx context.Context, sessionID string) (bool, error)
- TryLockRewind(ctx context.Context, sessionID string) (unlock func(), err error)
+ // TryLockRewind locks the session for rewind. Run the workspace reset
+ // with the returned context: on a shared machine it carries the
+ // session's exclusive window.
+ TryLockRewind(ctx context.Context, sessionID string) (context.Context, func(), error)
SandboxShellRunner
}
@@ -286,14 +289,14 @@ func (s *SessionRewindService) Rewind(
// Once we are past the cheap busy reject, finish reset+truncate even if
// the HTTP request is gone.
persistCtx := context.WithoutCancel(ctx)
- unlock, err := s.lockRewind(persistCtx, sessionID)
+ workCtx, unlock, err := s.lockRewind(persistCtx, sessionID)
if err != nil {
return nil, err
}
defer unlock()
var abandonedBootstrap *types.ForkBootstrap
- workspaceReset, reason, resetErr := s.resetWorkspaceIfPossible(persistCtx, sessionID, history)
+ workspaceReset, reason, resetErr := s.resetWorkspaceIfPossible(workCtx, sessionID, history)
if resetErr != nil {
return nil, resetErr
}
@@ -393,9 +396,13 @@ func (s *SessionRewindService) resetWorkspaceIfPossible(
if err := s.rejectIfBusy(ctx, sessionID); err != nil {
return false, "", err
}
- workCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), workspaceResetTimeout)
+ workCtx, cancel := context.WithTimeout(ctx, workspaceResetTimeout)
defer cancel()
if err := resetWorkspaceToEmpty(workCtx, s.sandbox, sessionID, currentID); err != nil {
+ if errors.Is(err, errWorkspaceCommitMissing) {
+ // Checked before git touched any file: nothing changed.
+ return false, "", ErrRewindNoCheckpoint
+ }
return false, "", fmt.Errorf("session rewind: reset workspace: %w", err)
}
return true, "", nil
@@ -410,11 +417,15 @@ func (s *SessionRewindService) resetWorkspaceIfPossible(
return false, "", err
}
- workCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), workspaceResetTimeout)
+ workCtx, cancel := context.WithTimeout(ctx, workspaceResetTimeout)
defer cancel()
if err := resetWorkspaceToCommit(
workCtx, s.sandbox, sessionID, checkpoint.CommitSHA, checkpoint.SandboxID,
); err != nil {
+ if errors.Is(err, errWorkspaceCommitMissing) {
+ // Checked before git touched any file: nothing changed.
+ return false, "", ErrRewindNoCheckpoint
+ }
return false, "", fmt.Errorf("session rewind: reset workspace: %w", err)
}
return true, "", nil
@@ -451,28 +462,33 @@ func (s *SessionRewindService) deleteMessagesFrom(
return nil, lastErr
}
-func (s *SessionRewindService) lockRewind(ctx context.Context, sessionID string) (func(), error) {
+func (s *SessionRewindService) lockRewind(ctx context.Context, sessionID string) (context.Context, func(), error) {
unlockGate, err := s.busyGate.TryLockRewind(sessionID)
if err != nil {
- return nil, ErrRewindSourceBusy
+ return nil, nil, ErrRewindSourceBusy
}
+ workCtx := ctx
unlockPort := func() {}
if s.sandbox != nil {
- unlock, err := s.sandbox.TryLockRewind(ctx, sessionID)
+ locked, unlock, err := s.sandbox.TryLockRewind(ctx, sessionID)
if err != nil {
unlockGate()
if errors.Is(err, sandbox.ErrSessionRewindLocked) ||
errors.Is(err, sandbox.ErrSessionTurnActive) ||
+ errors.Is(err, sandbox.ErrSessionWorkspaceBusy) ||
errors.Is(err, ErrRewindSourceBusy) {
- return nil, ErrRewindSourceBusy
+ return nil, nil, ErrRewindSourceBusy
}
- return nil, fmt.Errorf("session rewind: lock session: %w", err)
+ return nil, nil, fmt.Errorf("session rewind: lock session: %w", err)
}
if unlock != nil {
unlockPort = unlock
}
+ if locked != nil {
+ workCtx = locked
+ }
}
- return func() {
+ return workCtx, func() {
unlockPort()
unlockGate()
}, nil
diff --git a/internal/application/service/session_rewind_test.go b/internal/application/service/session_rewind_test.go
index 0c9608818..0cae00f38 100644
--- a/internal/application/service/session_rewind_test.go
+++ b/internal/application/service/session_rewind_test.go
@@ -31,8 +31,12 @@ type fakeRewindSandboxPort struct {
execBlock func()
rewindMu sync.Mutex
rewindHeld bool
+ lockErr error
+ resetLockMarker any
}
+type rewindLockMarker struct{}
+
func newFakeRewindPort() *fakeRewindSandboxPort {
return &fakeRewindSandboxPort{
boundID: "sbx-1",
@@ -58,20 +62,32 @@ func (f *fakeRewindSandboxPort) HasActiveTurn(context.Context, string) (bool, er
return f.activeTurn, nil
}
-func (f *fakeRewindSandboxPort) TryLockRewind(context.Context, string) (func(), error) {
+func (f *fakeRewindSandboxPort) TryLockRewind(ctx context.Context, _ string) (context.Context, func(), error) {
+ if f.lockErr != nil {
+ return nil, nil, f.lockErr
+ }
f.rewindMu.Lock()
defer f.rewindMu.Unlock()
if f.rewindHeld {
- return nil, ErrRewindSourceBusy
+ return nil, nil, ErrRewindSourceBusy
}
f.rewindHeld = true
- return func() {
+ return context.WithValue(ctx, rewindLockMarker{}, true), func() {
f.rewindMu.Lock()
f.rewindHeld = false
f.rewindMu.Unlock()
}, nil
}
+func (f *fakeRewindSandboxPort) ExecShellCommandWithOptions(
+ ctx context.Context, sessionID, command string, opts sandbox.ShellExecOptions,
+) (*sandbox.ExecuteResult, error) {
+ if ctx != nil {
+ f.resetLockMarker = ctx.Value(rewindLockMarker{})
+ }
+ return f.ExecShellCommand(ctx, sessionID, command, opts.WorkDir, opts.Timeout, opts.Env)
+}
+
func (f *fakeRewindSandboxPort) ExecShellCommand(
ctx context.Context, sessionID, command, workDir string,
timeout time.Duration, env map[string]string,
@@ -860,6 +876,47 @@ func TestRewindUnopenedForkBootstrapClearFailureDoesNotDeleteMessages(t *testing
require.False(t, sessions.bootstrapCleared)
}
+func TestRewindRunsTheResetInsideTheLockWindow(t *testing.T) {
+ turn1 := rewindCompletedTurn("u-1", "a-1", "sbx-1", rewindSHA1, 0)
+ later := rewindCompletedTurn("u-2", "a-2", "sbx-1", rewindSHA2, 10*time.Second)
+ port := newFakeRewindPort()
+ svc, _ := newRewindFixture(t, port, append(turn1, later...))
+
+ got, err := svc.Rewind(context.Background(), 1, "u1", "src", "u-2")
+
+ require.NoError(t, err)
+ require.True(t, got.WorkspaceReset)
+ require.Equal(t, true, port.resetLockMarker)
+}
+
+func TestRewindReportsBusyWhenTheSessionCannotBeTakenExclusively(t *testing.T) {
+ turn1 := rewindCompletedTurn("u-1", "a-1", "sbx-1", rewindSHA1, 0)
+ later := rewindCompletedTurn("u-2", "a-2", "sbx-1", rewindSHA2, 10*time.Second)
+ port := newFakeRewindPort()
+ port.lockErr = sandbox.ErrSessionWorkspaceBusy
+ svc, msgs := newRewindFixture(t, port, append(turn1, later...))
+
+ got, err := svc.Rewind(context.Background(), 1, "u1", "src", "u-2")
+
+ require.ErrorIs(t, err, ErrRewindSourceBusy)
+ require.Nil(t, got)
+ require.Empty(t, port.runner.calls)
+ require.Equal(t, 0, msgs.deleteFromCalls)
+}
+
+func TestRewindRefusesACheckpointMissingFromTheSessionRepository(t *testing.T) {
+ turn := rewindCompletedTurn("u-1", "a-1", "sbx-1", rewindSHA1, 0)
+ port := newFakeRewindPort()
+ port.runner.result = &sandbox.ExecuteResult{ExitCode: 3}
+ svc, msgs := newRewindFixture(t, port, turn)
+
+ got, err := svc.Rewind(context.Background(), 1, "u1", "src", "a-1")
+
+ require.ErrorIs(t, err, ErrRewindNoCheckpoint)
+ require.Nil(t, got)
+ require.Equal(t, 0, msgs.deleteFromCalls)
+}
+
func messageIDs(messages []*types.Message) []string {
ids := make([]string, 0, len(messages))
for _, m := range messages {
diff --git a/internal/application/service/tenant_sandbox_config.go b/internal/application/service/tenant_sandbox_config.go
index 166e99961..7e2817543 100644
--- a/internal/application/service/tenant_sandbox_config.go
+++ b/internal/application/service/tenant_sandbox_config.go
@@ -40,6 +40,7 @@ import (
apperrors "github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/sandbox"
+ "github.com/Tencent/WeKnora/internal/sandbox/admission"
"github.com/Tencent/WeKnora/internal/sandbox/allocation"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
@@ -48,6 +49,8 @@ import (
const sandboxConfigCleanupTimeout = 20 * time.Second
+const configCreateDrainTimeout = 2 * time.Minute
+
// SandboxIdentityChanged reports whether sandboxes already created under oldCfg
// would stop being operable under newCfg. Names, templates, TTLs, HTTP timeouts
// and env vars deliberately do not count: they only shape FUTURE sandboxes.
@@ -197,6 +200,10 @@ var ErrSkillSnapshotBlocksTemplateChange = stderrors.New(
// row is recoverable; leaking a billable snapshot is not.
var ErrSkillSnapshotReleaseFailed = stderrors.New("failed to release skill snapshots")
+// ErrSandboxConfigCreatesInFlight is returned while a sandbox of this config
+// is still being created; retry the deletion once it finishes.
+var ErrSandboxConfigCreatesInFlight = stderrors.New("sandbox config still has sandboxes being created")
+
// SkillSnapshotReleaseFailedError names the snapshots that are still on the
// provider so the handler can show them and a retry can skip already-deleted
// ones.
@@ -252,6 +259,10 @@ type SandboxInventory struct {
SandboxCount int `json:"sandbox_count"`
SessionIDs []string `json:"session_ids,omitempty"`
AgentNames []string `json:"agent_names,omitempty"`
+ // UserSandboxCount is how many of SandboxCount are shared user machines.
+ // They carry no session id, so SessionIDs alone under-reports what a
+ // credential change would affect.
+ UserSandboxCount int `json:"user_sandbox_count,omitempty"`
// Unverifiable reports that SandboxCount is unknown rather than zero
// because the provider could not be reached. The management page must say
@@ -320,6 +331,11 @@ type TenantSandboxConfigService struct {
// build shows up in the provider's catalog, and a double-click on refresh
// is fast enough to slip in before that.
ensureTemplate singleflight.Group
+
+ allocations interfaces.SandboxAllocationRepository
+ admission admission.Registry
+ createDrainTimeout time.Duration
+ userMachines UserMachineReleaser
}
// NewTenantSandboxConfigService wires the config service.
@@ -331,18 +347,132 @@ func NewTenantSandboxConfigService(
files sandboxConfigBundleResolver,
) *TenantSandboxConfigService {
return &TenantSandboxConfigService{
- repo: repo,
- agents: agents,
- globalCfg: globalCfg,
- now: time.Now,
- skills: skills,
- files: files,
+ repo: repo,
+ agents: agents,
+ globalCfg: globalCfg,
+ now: time.Now,
+ skills: skills,
+ files: files,
+ createDrainTimeout: configCreateDrainTimeout,
newClient: func(cfg *sandbox.Config) (sandbox.ConfigSandboxClient, error) {
return sandbox.NewRemoteClientForCheck(cfg)
},
}
}
+// WithAllocationRepo lets config deletion drop the user machine registry.
+func (s *TenantSandboxConfigService) WithAllocationRepo(
+ repo interfaces.SandboxAllocationRepository,
+) *TenantSandboxConfigService {
+ s.allocations = repo
+ return s
+}
+
+// WithAdmission lets config deletion close and drain in-flight creates.
+func (s *TenantSandboxConfigService) WithAdmission(reg admission.Registry) *TenantSandboxConfigService {
+ s.admission = reg
+ return s
+}
+
+// ErrUserSandboxBusy is returned while a terminal, desktop or command is
+// still running on the machine; the admin is asked to retry once the user
+// has closed it.
+var ErrUserSandboxBusy = stderrors.New("user sandbox is busy")
+
+// UserMachineReleaser deletes one shared machine. It returns false when a
+// live session or registered work still holds the machine, and must not
+// destroy it in that case.
+type UserMachineReleaser interface {
+ ReleaseMachine(ctx context.Context, m allocation.UserMachine) (bool, error)
+}
+
+// WithUserMachineReleaser enables the admin release action.
+func (s *TenantSandboxConfigService) WithUserMachineReleaser(r UserMachineReleaser) *TenantSandboxConfigService {
+ s.userMachines = r
+ return s
+}
+
+// UserMachineView is one shared machine as the config admin sees it. Owners
+// from other workspaces (borrowers of a shared agent) are not named.
+type UserMachineView struct {
+ Digest string `json:"digest"`
+ OwnerTenantID uint64 `json:"owner_tenant_id"`
+ OwnerID string `json:"owner_id,omitempty"`
+ LiveSessions int64 `json:"live_sessions"`
+ EmptySince *time.Time `json:"empty_since,omitempty"`
+ ReclaimAfter *time.Time `json:"reclaim_after,omitempty"`
+}
+
+// ListUserMachines lists the config's shared machines with their retention clock.
+func (s *TenantSandboxConfigService) ListUserMachines(
+ ctx context.Context, tenantID uint64, configID string,
+) ([]UserMachineView, error) {
+ entity, err := s.repo.GetByID(ctx, tenantID, configID)
+ if err != nil || entity == nil {
+ return nil, err
+ }
+ if s.allocations == nil {
+ return nil, nil
+ }
+ rows, err := s.allocations.ListUserMachinesByConfig(ctx, tenantID, configID)
+ if err != nil {
+ return nil, err
+ }
+ days := allocation.DefaultEmptyRetentionDays
+ if entity.Config != nil {
+ days = allocation.EffectiveRetentionDays(entity.Config.UserSandboxEmptyRetentionDays)
+ }
+ out := make([]UserMachineView, 0, len(rows))
+ for _, r := range rows {
+ live, err := s.allocations.CountLiveAssignments(ctx, r.MachineDigest)
+ if err != nil {
+ return nil, err
+ }
+ v := UserMachineView{
+ Digest: r.MachineDigest, OwnerTenantID: r.OwnerTenantID,
+ LiveSessions: live, EmptySince: r.EmptySince,
+ }
+ if r.OwnerTenantID == tenantID {
+ v.OwnerID = r.OwnerID
+ }
+ if r.EmptySince != nil {
+ at := r.EmptySince.Add(time.Duration(days) * 24 * time.Hour)
+ v.ReclaimAfter = &at
+ }
+ out = append(out, v)
+ }
+ return out, nil
+}
+
+// ReleaseUserMachine deletes one shared machine now. Every session on it
+// keeps its assignment and gets a fresh machine on next use; its files and
+// installed packages are gone.
+func (s *TenantSandboxConfigService) ReleaseUserMachine(
+ ctx context.Context, tenantID uint64, configID, digest string,
+) error {
+ if s.allocations == nil || s.userMachines == nil {
+ return apperrors.NewBadRequestError("user sandboxes are not enabled")
+ }
+ row, err := s.allocations.GetUserMachine(ctx, digest)
+ if err != nil {
+ return err
+ }
+ if row == nil || row.ConfigTenantID != tenantID || row.ConfigID != configID {
+ return apperrors.NewNotFoundError("sandbox config not found")
+ }
+ ok, err := s.userMachines.ReleaseMachine(ctx, allocation.UserMachine{
+ OwnerTenantID: row.OwnerTenantID, OwnerID: row.OwnerID,
+ ConfigTenantID: row.ConfigTenantID, ConfigID: row.ConfigID,
+ })
+ if err != nil {
+ return err
+ }
+ if !ok {
+ return ErrUserSandboxBusy
+ }
+ return nil
+}
+
// SanitizeSandboxConfig resolves redacted secrets and validates the payload
// before it can be persisted.
func SanitizeSandboxConfig(
@@ -1149,10 +1279,11 @@ func (s *TenantSandboxConfigService) Update(
return s.writeConfig(ctx, entity, in, merged)
}
- if err := s.repo.SetCordon(ctx, tenantID, id, s.now()); err != nil {
+ cordonedAt := s.now()
+ if err := s.repo.SetCordon(ctx, tenantID, id, cordonedAt); err != nil {
return nil, err
}
- defer s.clearCordonAfterRequest(ctx, tenantID, id)
+ defer s.clearCordonAfterRequest(ctx, tenantID, id, cordonedAt)
// When old credentials no longer reach the provider we cannot enumerate
// sandboxes to refuse the edit — but blocking the save traps the admin on
@@ -1193,14 +1324,12 @@ func (s *TenantSandboxConfigService) Update(
// snapshots on its ledger cannot be destroyed. Agent references are permanent
// state and are surfaced as warnings by callers, not blockers.
//
-// force covers two cases we cannot complete from here: the provider could not
-// be reached to list sandboxes, and a skill snapshot could not be destroyed.
-// Without it a config whose endpoint's DNS record disappeared, or whose
-// snapshot API is down, could never be removed — unlike an edit, deletion has
-// no "create a second config" way out. It does NOT override sandboxes we can
-// actually see; those still have to be dealt with through their sessions,
-// otherwise the forced deletion would be precisely the permanent leak this
-// whole flow prevents.
+// force covers a skill snapshot that could not be destroyed. It does not
+// cover an inventory we could not list: an unreachable provider is not the
+// same as an empty one, and dropping the user-machine registry would make
+// directory cleanup treat those machines as already gone. Sandboxes we can
+// actually see, including user machines, still have to be dealt with through
+// their sessions.
func (s *TenantSandboxConfigService) Delete(
ctx context.Context, tenantID uint64, id string, force bool,
) error {
@@ -1216,25 +1345,168 @@ func (s *TenantSandboxConfigService) Delete(
if types.IsSandboxWorkspacePolicyRow(entity) {
return apperrors.NewBadRequestError("workspace policy cannot be deleted here")
}
+ lease := &cordonLease{at: s.now()}
+ if err := s.repo.SetCordon(ctx, tenantID, id, lease.at); err != nil {
+ return err
+ }
+ defer func() {
+ if lease.abandoned {
+ return
+ }
+ s.clearCordonAfterRequest(ctx, tenantID, id, lease.at)
+ }()
+ barrier, err := s.closeCreates(ctx, tenantID, id, lease)
+ if err != nil {
+ return err
+ }
+ // Release reopens creates. That is only correct when Delete fails and
+ // the config stays. A successful delete seals the scope instead.
+ var failed bool
+ if barrier != nil {
+ defer func() {
+ if failed {
+ barrier.Release()
+ }
+ }()
+ }
+ fail := func(err error) error {
+ failed = true
+ return err
+ }
+
+ if err := s.keepCordon(ctx, tenantID, id, lease); err != nil {
+ return fail(err)
+ }
summaries, listErr := s.listSandboxes(ctx, entity.Config, tenantID, id)
if listErr != nil {
- if !force {
- return fmt.Errorf("%w: %v", ErrSandboxInventoryUnverifiable, listErr)
- }
- logger.Warnf(ctx,
- "[sandbox] force-deleting config %s without verifying its sandboxes: %v",
- id, listErr)
+ return fail(fmt.Errorf("%w: %v", ErrSandboxInventoryUnverifiable, listErr))
}
if len(summaries) > 0 {
inv := s.inventoryFromSummaries(ctx, tenantID, id, summaries)
- return &SandboxesStillLiveError{Inventory: inv}
+ return fail(&SandboxesStillLiveError{Inventory: inv})
+ }
+ if err := s.keepCordon(ctx, tenantID, id, lease); err != nil {
+ return fail(err)
}
if err := s.releaseSkillSnapshots(ctx, entity, tenantID, id, force); err != nil {
- return err
+ return fail(err)
+ }
+ if barrier != nil {
+ if err := barrier.Check(); err != nil {
+ return fail(err) // a create may have been admitted after the inventory
+ }
+ }
+ if err := s.keepCordon(ctx, tenantID, id, lease); err != nil {
+ return fail(err)
+ }
+ if err := s.dropMachinesAndDelete(ctx, tenantID, id); err != nil {
+ return fail(err)
+ }
+ if barrier == nil && listErr == nil {
+ // No create registry injected: keep the previous post-delete sweep.
+ if client, err := s.clientFor(entity.Config); err == nil && client != nil {
+ s.sweepAfterWrite(ctx, client, tenantID, id)
+ }
+ }
+ if barrier != nil {
+ barrier.Seal()
+ }
+ return nil
+}
+
+// dropMachinesAndDelete removes the config's user-machine rows and
+// soft-deletes the config. When both repositories share a database this is
+// one transaction, so a failed config delete puts the registry rows back.
+// Fakes without a database keep the two calls in that order.
+func (s *TenantSandboxConfigService) dropMachinesAndDelete(
+ ctx context.Context, tenantID uint64, id string,
+) error {
+ if db := repository.GormDB(s.repo); db != nil {
+ if err := repository.DeleteUserMachinesAndSandboxConfig(ctx, db, tenantID, id); err != nil {
+ return fmt.Errorf("drop user machine registry of config %s: %w", id, err)
+ }
+ return nil
+ }
+ if s.allocations != nil {
+ if err := s.allocations.DeleteUserMachinesByConfig(ctx, tenantID, id); err != nil {
+ return fmt.Errorf("drop user machine registry of config %s: %w", id, err)
+ }
}
return s.repo.SoftDelete(ctx, tenantID, id)
}
+// cordonLease is the stamp this Delete wrote, moved forward while the call
+// runs so the lease cannot lapse underneath it.
+type cordonLease struct {
+ at time.Time
+ abandoned bool
+}
+
+// keepCordon moves the stamp once it is halfway through the lease. A compare
+// that matches nothing means another request owns the cordon: the caller must
+// not clear it.
+func (s *TenantSandboxConfigService) keepCordon(
+ ctx context.Context, tenantID uint64, id string, lease *cordonLease,
+) error {
+ if lease == nil || lease.abandoned {
+ return nil
+ }
+ now := s.now()
+ if now.Sub(lease.at) < types.SandboxCordonLease/2 {
+ return nil
+ }
+ if err := s.repo.RefreshCordon(ctx, tenantID, id, lease.at, now); err != nil {
+ if stderrors.Is(err, repository.ErrSandboxConfigCordoned) {
+ lease.abandoned = true
+ }
+ return err
+ }
+ lease.at = now
+ return nil
+}
+
+// closeCreates stops new creates of the config and waits for running ones.
+func (s *TenantSandboxConfigService) closeCreates(
+ ctx context.Context, tenantID uint64, id string, lease *cordonLease,
+) (admission.Barrier, error) {
+ if s.admission == nil {
+ return nil, nil
+ }
+ scope := admission.ConfigCreateScope(tenantID, id)
+ barrier, err := s.admission.Close(ctx, scope, admission.DefaultHoldTTL)
+ if stderrors.Is(err, admission.ErrClosed) {
+ return nil, ErrSandboxConfigCreatesInFlight // another deletion holds it
+ }
+ if err != nil {
+ return nil, err
+ }
+ deadline := time.Now().Add(s.createDrainTimeout)
+ for {
+ if err := s.keepCordon(ctx, tenantID, id, lease); err != nil {
+ barrier.Release()
+ return nil, err
+ }
+ n, err := s.admission.ActiveExcept(ctx, scope)
+ if err != nil {
+ barrier.Release()
+ return nil, err
+ }
+ if n == 0 {
+ return barrier, nil
+ }
+ if time.Now().After(deadline) {
+ barrier.Release()
+ return nil, ErrSandboxConfigCreatesInFlight
+ }
+ select {
+ case <-ctx.Done():
+ barrier.Release()
+ return nil, ctx.Err()
+ case <-time.After(250 * time.Millisecond):
+ }
+ }
+}
+
func snapshotReleaserFrom(client sandbox.ConfigSandboxClient) (sandboxSnapshotReleaser, bool) {
if client == nil {
return nil, false
@@ -1597,6 +1869,9 @@ func (s *TenantSandboxConfigService) inventoryFromSummaries(
if sessionID := summary.Metadata[sandbox.MetadataSessionIDKey()]; sessionID != "" {
inv.SessionIDs = append(inv.SessionIDs, sessionID)
}
+ if summary.Metadata[sandbox.MetadataAllocationKey()] == sandbox.MetadataAllocationUser {
+ inv.UserSandboxCount++
+ }
}
if s.agents == nil {
return inv
@@ -1614,11 +1889,12 @@ func (s *TenantSandboxConfigService) clearCordonAfterRequest(
ctx context.Context,
tenantID uint64,
id string,
+ at time.Time,
) {
cleanupCtx, cancel := context.WithTimeout(
context.WithoutCancel(ctx), sandboxConfigCleanupTimeout)
defer cancel()
- if err := s.repo.ClearCordon(cleanupCtx, tenantID, id); err != nil {
+ if err := s.repo.ClearCordonIf(cleanupCtx, tenantID, id, at); err != nil {
logger.Warnf(ctx, "[sandbox] clear cordon on config %s: %v", id, err)
}
}
diff --git a/internal/application/service/tenant_sandbox_config_test.go b/internal/application/service/tenant_sandbox_config_test.go
index 58a2c7a44..8ac277ea4 100644
--- a/internal/application/service/tenant_sandbox_config_test.go
+++ b/internal/application/service/tenant_sandbox_config_test.go
@@ -15,8 +15,10 @@ import (
"github.com/stretchr/testify/require"
+ "github.com/Tencent/WeKnora/internal/application/repository"
apperrors "github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/sandbox"
+ "github.com/Tencent/WeKnora/internal/sandbox/admission"
"github.com/Tencent/WeKnora/internal/sandbox/allocation"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
@@ -245,6 +247,7 @@ type fakeConfigRepo struct {
updateErr error
clearCordonCtxErr error
+ cordonedAt *time.Time
}
func (f *fakeConfigRepo) Create(_ context.Context, e *types.TenantSandboxConfigEntity) error {
@@ -304,20 +307,41 @@ func (f *fakeConfigRepo) SoftDelete(_ context.Context, _ uint64, id string) erro
return nil
}
-func (f *fakeConfigRepo) SetCordon(_ context.Context, _ uint64, _ string, _ time.Time) error {
+func (f *fakeConfigRepo) SetCordon(_ context.Context, _ uint64, _ string, at time.Time) error {
f.events = append(f.events, "cordon")
+ stamped := at
+ f.cordonedAt = &stamped
if f.onSetCordon != nil {
f.onSetCordon()
}
return nil
}
+func (f *fakeConfigRepo) RefreshCordon(
+ _ context.Context, _ uint64, _ string, previous, next time.Time,
+) error {
+ if f.cordonedAt == nil || !f.cordonedAt.Equal(previous) {
+ return repository.ErrSandboxConfigCordoned
+ }
+ stamped := next
+ f.cordonedAt = &stamped
+ return nil
+}
+
func (f *fakeConfigRepo) ClearCordon(ctx context.Context, _ uint64, _ string) error {
f.events = append(f.events, "uncordon")
+ f.cordonedAt = nil
f.clearCordonCtxErr = ctx.Err()
return nil
}
+func (f *fakeConfigRepo) ClearCordonIf(ctx context.Context, tenantID uint64, id string, at time.Time) error {
+ if f.cordonedAt == nil || !f.cordonedAt.Equal(at) {
+ return nil
+ }
+ return f.ClearCordon(ctx, tenantID, id)
+}
+
type stubAgentRepo struct {
names []string
err error
@@ -1302,7 +1326,7 @@ func TestDeleteRefusesWhileSandboxesLive(t *testing.T) {
require.Equal(t, []string{"s-1"}, liveErr.Inventory.SessionIDs)
require.Equal(t, []string{"analyst"}, liveErr.Inventory.AgentNames)
require.False(t, repo.deleted)
- require.Equal(t, []string{"get"}, repo.events)
+ require.Equal(t, []string{"get", "cordon", "uncordon"}, repo.events)
}
// "We cannot tell" must not read as "nothing there": refuse, and say which of
@@ -1324,20 +1348,25 @@ func TestDeleteRefusesWhenInventoryUnverifiable(t *testing.T) {
require.False(t, repo.deleted)
}
-// Deletion has no "create a second config" way out, so a config whose endpoint
-// vanished must remain removable once an admin takes responsibility.
-func TestDeleteForceRemovesConfigWithUnverifiableInventory(t *testing.T) {
+// An inventory failure does not mean the provider has no sandboxes. force
+// does not delete the config or its user-machine registry in that case:
+// cleanup treats a missing registry row as a machine that is already gone.
+func TestDeleteForceKeepsTheConfigWhenInventoryIsUnverifiable(t *testing.T) {
repo := &fakeConfigRepo{entity: &types.TenantSandboxConfigEntity{
ID: "cfg-a", TenantID: 7, Name: "prod", SandboxType: "e2b",
Config: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300),
}}
+ alloc := &recordingAlloc{}
svc := newTestConfigService(t, repo, nil, stubAgentRepo{})
+ svc.WithAllocationRepo(alloc)
svc.newClient = func(*sandbox.Config) (sandbox.ConfigSandboxClient, error) {
return nil, stderrors.New("dial tcp: no such host")
}
- require.NoError(t, svc.Delete(context.Background(), 7, "cfg-a", true))
- require.True(t, repo.deleted)
+ err := svc.Delete(context.Background(), 7, "cfg-a", true)
+ require.ErrorIs(t, err, ErrSandboxInventoryUnverifiable)
+ require.False(t, repo.deleted)
+ require.Zero(t, alloc.calls)
}
// force covers "cannot verify", never "verified live". Letting it through here
@@ -1418,7 +1447,7 @@ func TestDeleteSoftDeletesWhenEmpty(t *testing.T) {
require.NoError(t, err)
require.True(t, repo.deleted)
- require.Equal(t, []string{"get", "delete"}, repo.events)
+ require.Equal(t, []string{"get", "cordon", "delete", "uncordon"}, repo.events)
}
// Reporting success for a config that is not there would let the UI drop a card
@@ -2235,3 +2264,594 @@ var (
_ sandboxConfigSkillStore = (*deleteSkillStore)(nil)
_ sandboxConfigBundleResolver = (*deleteBundleResolver)(nil)
)
+
+func configA() *types.TenantSandboxConfigEntity {
+ return &types.TenantSandboxConfigEntity{
+ ID: "cfg-a", TenantID: 7, Name: "prod", SandboxType: "e2b",
+ Config: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300),
+ }
+}
+
+func userMachineOfConfigA(id string) sandbox.RemoteSandboxSummary {
+ return sandbox.RemoteSandboxSummary{
+ ID: id,
+ Metadata: map[string]string{
+ "weknora_tenant_id": "7",
+ "weknora_sandbox_config_id": "cfg-a",
+ sandbox.MetadataAllocationKey(): sandbox.MetadataAllocationUser,
+ },
+ }
+}
+
+// orderConfigRepo records cordon, delete, and uncordon beside the fake repo's
+// own event log, so a test can assert one timeline across the provider and
+// the admission registry.
+type orderConfigRepo struct {
+ repository.TenantSandboxConfigRepository
+ order *[]string
+}
+
+func (r orderConfigRepo) SetCordon(ctx context.Context, tenantID uint64, id string, at time.Time) error {
+ *r.order = append(*r.order, "SetCordon")
+ return r.TenantSandboxConfigRepository.SetCordon(ctx, tenantID, id, at)
+}
+
+func (r orderConfigRepo) ClearCordon(ctx context.Context, tenantID uint64, id string) error {
+ *r.order = append(*r.order, "ClearCordon")
+ return r.TenantSandboxConfigRepository.ClearCordon(ctx, tenantID, id)
+}
+
+func (r orderConfigRepo) ClearCordonIf(ctx context.Context, tenantID uint64, id string, at time.Time) error {
+ *r.order = append(*r.order, "ClearCordon")
+ return r.TenantSandboxConfigRepository.ClearCordonIf(ctx, tenantID, id, at)
+}
+
+func (r orderConfigRepo) SoftDelete(ctx context.Context, tenantID uint64, id string) error {
+ *r.order = append(*r.order, "SoftDelete")
+ return r.TenantSandboxConfigRepository.SoftDelete(ctx, tenantID, id)
+}
+
+// recordingAlloc records DeleteUserMachinesByConfig. Other methods are not
+// part of config deletion; calling one panics instead of pretending success.
+type recordingAlloc struct {
+ interfaces.SandboxAllocationRepository
+ order *[]string
+ err error
+ calls int
+}
+
+func (r *recordingAlloc) DeleteUserMachinesByConfig(_ context.Context, tenantID uint64, configID string) error {
+ r.calls++
+ if r.order != nil {
+ *r.order = append(*r.order, fmt.Sprintf("DeleteUserMachinesByConfig(%d,%q)", tenantID, configID))
+ }
+ return r.err
+}
+
+type recordingProvider struct {
+ summaries []sandbox.RemoteSandboxSummary
+ order *[]string
+ lists int
+ deleted []string
+}
+
+func (p *recordingProvider) List(context.Context, sandbox.RemoteListFilter) ([]sandbox.RemoteSandboxSummary, error) {
+ p.lists++
+ if p.order != nil {
+ *p.order = append(*p.order, "List")
+ }
+ return append([]sandbox.RemoteSandboxSummary(nil), p.summaries...), nil
+}
+
+func (p *recordingProvider) Delete(_ context.Context, sandboxID string) error {
+ p.deleted = append(p.deleted, sandboxID)
+ if p.order != nil {
+ *p.order = append(*p.order, "Delete")
+ }
+ return nil
+}
+
+type recordingAdmission struct {
+ admission.Registry
+ order *[]string
+}
+
+func (r recordingAdmission) Close(
+ ctx context.Context, scope admission.Scope, ttl time.Duration,
+) (admission.Barrier, error) {
+ *r.order = append(*r.order, "Close("+scope.Name+")")
+ b, err := r.Registry.Close(ctx, scope, ttl)
+ if err != nil || b == nil {
+ return b, err
+ }
+ return recordingBarrier{Barrier: b, order: r.order, name: scope.Name}, nil
+}
+
+type recordingBarrier struct {
+ admission.Barrier
+ order *[]string
+ name string
+}
+
+func (b recordingBarrier) Release() {
+ *b.order = append(*b.order, "release("+b.name+")")
+ b.Barrier.Release()
+}
+
+func (b recordingBarrier) Seal() {
+ *b.order = append(*b.order, "Seal("+b.name+")")
+ b.Barrier.Seal()
+}
+
+// gatedInventory lists nothing until released, then the sandbox the in-flight
+// create produced. early counts lists that ran before the release.
+type gatedInventory struct {
+ mu sync.Mutex
+ released bool
+ calls int
+ early int
+ deleted []string
+}
+
+func (g *gatedInventory) List(context.Context, sandbox.RemoteListFilter) ([]sandbox.RemoteSandboxSummary, error) {
+ g.mu.Lock()
+ defer g.mu.Unlock()
+ g.calls++
+ if !g.released {
+ g.early++
+ return nil, nil
+ }
+ return []sandbox.RemoteSandboxSummary{userMachineOfConfigA("sb-inflight")}, nil
+}
+
+func (g *gatedInventory) Delete(_ context.Context, sandboxID string) error {
+ g.mu.Lock()
+ defer g.mu.Unlock()
+ g.deleted = append(g.deleted, sandboxID)
+ return nil
+}
+
+func (g *gatedInventory) release() {
+ g.mu.Lock()
+ g.released = true
+ g.mu.Unlock()
+}
+
+func (g *gatedInventory) snapshot() (calls, early int) {
+ g.mu.Lock()
+ defer g.mu.Unlock()
+ return g.calls, g.early
+}
+
+func newConfigDeleteService(
+ repo repository.TenantSandboxConfigRepository,
+ client sandbox.ConfigSandboxClient,
+) *TenantSandboxConfigService {
+ svc := NewTenantSandboxConfigService(repo, stubAgentRepo{}, testGlobalSandboxConfig(), nil, nil)
+ svc.newClient = func(*sandbox.Config) (sandbox.ConfigSandboxClient, error) {
+ if client == nil {
+ return &stubProviderClient{}, nil
+ }
+ return client, nil
+ }
+ return svc
+}
+
+func TestDeleteConfigWaitsForInFlightCreatesBeforeTheInventory(t *testing.T) {
+ cordoned := make(chan struct{})
+ repo := &fakeConfigRepo{entity: configA(), onSetCordon: func() { close(cordoned) }}
+ reg := admission.NewMemory()
+ scope := admission.ConfigCreateScope(7, "cfg-a")
+ lease, err := reg.Hold(context.Background(), scope, "create:inflight", admission.DefaultHoldTTL)
+ require.NoError(t, err)
+ defer lease.Release()
+
+ inventory := &gatedInventory{}
+ svc := newConfigDeleteService(repo, inventory)
+ svc.WithAdmission(reg)
+
+ errCh := make(chan error, 1)
+ go func() {
+ errCh <- svc.Delete(context.Background(), 7, "cfg-a", false)
+ }()
+
+ select {
+ case <-cordoned:
+ case <-time.After(time.Second):
+ t.Fatal("Delete did not cordon while a create was still in flight")
+ }
+ time.Sleep(100 * time.Millisecond)
+ calls, _ := inventory.snapshot()
+ require.Zero(t, calls, "inventory must wait until the in-flight create is released")
+ inventory.release()
+ lease.Release()
+
+ select {
+ case err = <-errCh:
+ case <-time.After(5 * time.Second):
+ t.Fatal("Delete did not return after the in-flight create finished")
+ }
+ var live *SandboxesStillLiveError
+ require.ErrorAs(t, err, &live)
+ require.Equal(t, 1, live.Inventory.SandboxCount)
+ calls, early := inventory.snapshot()
+ require.Equal(t, 1, calls)
+ require.Zero(t, early, "List ran only after the release")
+ require.False(t, repo.deleted)
+ require.NotContains(t, repo.events, "delete")
+ require.Equal(t, []string{"get", "cordon", "uncordon"}, repo.events)
+}
+
+func TestDeleteConfigTimesOutWhileACreateIsStillRunning(t *testing.T) {
+ repo := &fakeConfigRepo{entity: configA()}
+ reg := admission.NewMemory()
+ scope := admission.ConfigCreateScope(7, "cfg-a")
+ lease, err := reg.Hold(context.Background(), scope, "create:stuck", admission.DefaultHoldTTL)
+ require.NoError(t, err)
+ defer lease.Release()
+
+ client := &stubProviderClient{}
+ svc := newConfigDeleteService(repo, client)
+ svc.WithAdmission(reg)
+ svc.createDrainTimeout = 100 * time.Millisecond
+
+ err = svc.Delete(context.Background(), 7, "cfg-a", false)
+
+ require.ErrorIs(t, err, ErrSandboxConfigCreatesInFlight)
+ require.Zero(t, client.listCalls)
+ require.False(t, repo.deleted)
+ require.Equal(t, []string{"get", "cordon", "uncordon"}, repo.events)
+}
+
+func TestDeleteConfigCordonsBeforeInventoryAndUncordonsWhenLive(t *testing.T) {
+ fake := &fakeConfigRepo{entity: configA()}
+ var order []string
+ repo := orderConfigRepo{TenantSandboxConfigRepository: fake, order: &order}
+ provider := &recordingProvider{
+ summaries: []sandbox.RemoteSandboxSummary{userMachineOfConfigA("sb-user")},
+ order: &order,
+ }
+ alloc := &recordingAlloc{}
+ svc := newConfigDeleteService(repo, provider)
+ svc.WithAllocationRepo(alloc)
+
+ err := svc.Delete(context.Background(), 7, "cfg-a", false)
+
+ var live *SandboxesStillLiveError
+ require.ErrorAs(t, err, &live)
+ require.Equal(t, []string{"SetCordon", "List", "ClearCordon"}, order)
+ require.False(t, fake.deleted)
+ require.Zero(t, alloc.calls)
+ require.Empty(t, provider.deleted)
+}
+
+func TestDeleteConfigKeepsTheConfigWhenTheRegistryCannotBeDropped(t *testing.T) {
+ fake := &fakeConfigRepo{entity: configA()}
+ dropErr := stderrors.New("registry down")
+ alloc := &recordingAlloc{err: dropErr}
+ svc := newConfigDeleteService(fake, &stubProviderClient{})
+ svc.WithAllocationRepo(alloc)
+
+ err := svc.Delete(context.Background(), 7, "cfg-a", false)
+
+ require.ErrorIs(t, err, dropErr)
+ require.Equal(t, 1, alloc.calls)
+ require.False(t, fake.deleted)
+ require.NotContains(t, fake.events, "delete")
+}
+
+func TestDeleteConfigDropsTheRegistryThenSoftDeletes(t *testing.T) {
+ fake := &fakeConfigRepo{entity: configA()}
+ var order []string
+ repo := orderConfigRepo{TenantSandboxConfigRepository: fake, order: &order}
+ provider := &recordingProvider{order: &order}
+ reg := recordingAdmission{Registry: admission.NewMemory(), order: &order}
+ alloc := &recordingAlloc{order: &order}
+ svc := newConfigDeleteService(repo, provider)
+ svc.WithAdmission(reg).WithAllocationRepo(alloc)
+
+ require.NoError(t, svc.Delete(context.Background(), 7, "cfg-a", false))
+ require.Equal(t, []string{
+ "SetCordon",
+ "Close(create)",
+ "List",
+ `DeleteUserMachinesByConfig(7,"cfg-a")`,
+ "SoftDelete",
+ "Seal(create)",
+ "ClearCordon",
+ }, order)
+ require.True(t, fake.deleted)
+ require.Equal(t, 1, provider.lists, "a drained delete does not sweep after the write")
+ require.Empty(t, provider.deleted)
+}
+
+func TestDeleteConfigSealsCreatesOnTheResolvedManager(t *testing.T) {
+ reg := admission.NewMemory()
+ client := &sealRemoteClient{}
+ cfg := sandbox.DefaultConfig()
+ cfg.Type = sandbox.SandboxTypeCube
+ cfg.CubeTemplate = "tpl-test"
+ mgr, err := sandbox.NewSessionBoundManager(sandbox.SessionBoundManagerConfig{
+ Config: cfg, Client: client, Store: sandbox.NewMemorySessionSandboxBindingStore(),
+ Checker: alwaysExistsChecker{}, SkipHealthProbe: true,
+ ConfigID: "cfg-a", ConfigTenantID: 7, Admission: reg,
+ })
+ require.NoError(t, err)
+ ctx := types.WithSandboxTenantID(context.Background(), 7)
+ _, err = mgr.ExecShellCommand(ctx, "sess-1", "echo hi", "", time.Second, nil)
+ require.NoError(t, err)
+ require.Equal(t, int32(1), client.creates.Load())
+
+ svc := newConfigDeleteService(&fakeConfigRepo{entity: configA()}, &stubProviderClient{})
+ svc.WithAdmission(reg)
+ require.NoError(t, svc.Delete(ctx, 7, "cfg-a", false))
+
+ _, err = mgr.ExecShellCommand(ctx, "sess-2", "echo hi", "", time.Second, nil)
+ require.ErrorIs(t, err, sandbox.ErrSandboxConfigCordoned)
+ require.Equal(t, int32(1), client.creates.Load(), "a sealed config must not reach the provider")
+}
+
+func TestDeleteConfigRefreshesCordonBeforeTheLeaseLapses(t *testing.T) {
+ start := time.Date(2026, 10, 16, 3, 4, 5, 0, time.UTC)
+ fake := &fakeConfigRepo{entity: configA()}
+ repo := &countingRefresh{fakeConfigRepo: fake}
+ svc := newConfigDeleteService(repo, &stubProviderClient{})
+ svc.WithAdmission(admission.NewMemory())
+ svc.now = cordonClock(start)
+
+ require.NoError(t, svc.Delete(context.Background(), 7, "cfg-a", false))
+ require.Equal(t, 1, repo.calls)
+ require.True(t, repo.prev.Equal(start))
+ require.True(t, repo.next.Equal(start.Add(types.SandboxCordonLease/2)))
+ require.True(t, fake.deleted)
+ require.Contains(t, fake.events, "uncordon")
+}
+
+func TestDeleteConfigLeavesACordonOwnedBySomeoneElse(t *testing.T) {
+ start := time.Date(2026, 10, 16, 3, 4, 5, 0, time.UTC)
+ fake := &fakeConfigRepo{entity: configA()}
+ svc := newConfigDeleteService(loseRefresh{fakeConfigRepo: fake}, &stubProviderClient{})
+ svc.WithAdmission(admission.NewMemory())
+ svc.now = cordonClock(start)
+
+ err := svc.Delete(context.Background(), 7, "cfg-a", false)
+ require.ErrorIs(t, err, repository.ErrSandboxConfigCordoned)
+ require.False(t, fake.deleted)
+ require.NotContains(t, fake.events, "uncordon")
+ require.NotContains(t, fake.events, "delete")
+}
+
+func cordonClock(start time.Time) func() time.Time {
+ var n atomic.Int32
+ advanced := start.Add(types.SandboxCordonLease / 2)
+ return func() time.Time {
+ if n.Add(1) == 1 {
+ return start
+ }
+ return advanced
+ }
+}
+
+type countingRefresh struct {
+ *fakeConfigRepo
+ calls int
+ prev, next time.Time
+}
+
+func (c *countingRefresh) RefreshCordon(
+ ctx context.Context, tenantID uint64, id string, previous, next time.Time,
+) error {
+ c.calls++
+ c.prev, c.next = previous, next
+ return c.fakeConfigRepo.RefreshCordon(ctx, tenantID, id, previous, next)
+}
+
+type loseRefresh struct {
+ *fakeConfigRepo
+}
+
+func (loseRefresh) RefreshCordon(context.Context, uint64, string, time.Time, time.Time) error {
+ return repository.ErrSandboxConfigCordoned
+}
+
+type alwaysExistsChecker struct{}
+
+func (alwaysExistsChecker) SessionExists(context.Context, sandbox.SessionSandboxKey) (bool, error) {
+ return true, nil
+}
+
+type sealRemoteClient struct {
+ creates atomic.Int32
+}
+
+func (c *sealRemoteClient) Provider() sandbox.RemoteProvider { return sandbox.SandboxTypeCube }
+func (c *sealRemoteClient) Capabilities() sandbox.RemoteSandboxCapabilities {
+ return sandbox.RemoteSandboxCapabilities{SupportsReconnect: true}
+}
+func (c *sealRemoteClient) Health(context.Context) error { return nil }
+func (c *sealRemoteClient) Create(context.Context, sandbox.RemoteCreateRequest) (sandbox.RemoteSandboxHandle, error) {
+ n := c.creates.Add(1)
+ return sealHandle{id: fmt.Sprintf("sb-%d", n)}, nil
+}
+
+func (c *sealRemoteClient) Connect(
+ _ context.Context, req sandbox.RemoteConnectRequest,
+) (sandbox.RemoteSandboxHandle, error) {
+ return sealHandle{id: req.SandboxID}, nil
+}
+
+func (c *sealRemoteClient) Get(context.Context, string) (*sandbox.RemoteSandboxSummary, error) {
+ return nil, nil
+}
+
+func (c *sealRemoteClient) List(context.Context, sandbox.RemoteListFilter) ([]sandbox.RemoteSandboxSummary, error) {
+ return nil, nil
+}
+func (c *sealRemoteClient) Delete(context.Context, string) error { return nil }
+func (c *sealRemoteClient) Exec(
+ context.Context, sandbox.RemoteSandboxHandle, sandbox.RemoteExecRequest,
+) (*sandbox.RemoteExecResult, error) {
+ return &sandbox.RemoteExecResult{}, nil
+}
+
+func (c *sealRemoteClient) WriteFile(context.Context, sandbox.RemoteSandboxHandle, string, []byte) error {
+ return nil
+}
+
+func (c *sealRemoteClient) ReadFile(context.Context, sandbox.RemoteSandboxHandle, string) ([]byte, error) {
+ return nil, nil
+}
+
+func (c *sealRemoteClient) ListDir(
+ context.Context, sandbox.RemoteSandboxHandle, string,
+) ([]sandbox.RemoteDirEntry, error) {
+ return nil, nil
+}
+
+func (c *sealRemoteClient) MakeDir(context.Context, sandbox.RemoteSandboxHandle, string) error {
+ return nil
+}
+
+func (c *sealRemoteClient) Remove(context.Context, sandbox.RemoteSandboxHandle, string) error {
+ return nil
+}
+
+func (c *sealRemoteClient) Stat(
+ context.Context, sandbox.RemoteSandboxHandle, string,
+) (*sandbox.RemoteStatEntry, error) {
+ return nil, nil
+}
+
+type sealHandle struct{ id string }
+
+func (h sealHandle) ID() string { return h.id }
+func (h sealHandle) Provider() sandbox.RemoteProvider { return sandbox.SandboxTypeCube }
+func (h sealHandle) Metadata() map[string]string { return nil }
+
+// recordingReleaser stands in for WorkspaceCleaner.ReleaseMachine. busy
+// reports a terminal, desktop or command still registered on the machine.
+type recordingReleaser struct {
+ released []allocation.UserMachine
+ busy bool
+}
+
+func (r *recordingReleaser) ReleaseMachine(_ context.Context, m allocation.UserMachine) (bool, error) {
+ if r.busy {
+ return false, nil
+ }
+ r.released = append(r.released, m)
+ return true, nil
+}
+
+// userMachineAllocRepo embeds the allocation repository and overrides only
+// the reads the admin list and release actions use.
+type userMachineAllocRepo struct {
+ interfaces.SandboxAllocationRepository
+ byDigest map[string]*types.SandboxUserMachine
+ byConfig []*types.SandboxUserMachine
+ live map[string]int64
+}
+
+func (r userMachineAllocRepo) GetUserMachine(_ context.Context, digest string) (*types.SandboxUserMachine, error) {
+ return r.byDigest[digest], nil
+}
+
+func (r userMachineAllocRepo) ListUserMachinesByConfig(
+ context.Context, uint64, string,
+) ([]*types.SandboxUserMachine, error) {
+ return r.byConfig, nil
+}
+
+func (r userMachineAllocRepo) CountLiveAssignments(_ context.Context, digest string) (int64, error) {
+ return r.live[digest], nil
+}
+
+func TestReleaseUserMachineChecksConfigOwnershipAndBusy(t *testing.T) {
+ repo := &fakeConfigRepo{entity: &types.TenantSandboxConfigEntity{ID: "cfg-a", TenantID: 7}}
+ allocRepo := userMachineAllocRepo{byDigest: map[string]*types.SandboxUserMachine{
+ "d-1": {MachineDigest: "d-1", ConfigTenantID: 7, ConfigID: "cfg-a", OwnerID: "u-1", OwnerTenantID: 7},
+ "d-x": {MachineDigest: "d-x", ConfigTenantID: 7, ConfigID: "cfg-b", OwnerID: "u-1", OwnerTenantID: 7},
+ }}
+ svc := newTestConfigService(t, repo, nil, stubAgentRepo{})
+ rel := &recordingReleaser{}
+ svc.WithAllocationRepo(allocRepo).WithUserMachineReleaser(rel)
+
+ require.NoError(t, svc.ReleaseUserMachine(context.Background(), 7, "cfg-a", "d-1"))
+ require.Equal(t, []allocation.UserMachine{{
+ OwnerTenantID: 7, OwnerID: "u-1", ConfigTenantID: 7, ConfigID: "cfg-a",
+ }}, rel.released)
+ // A digest that belongs to another config is the same answer as a missing
+ // config: this file reports absence as a not-found AppError, not a sentinel.
+ err := svc.ReleaseUserMachine(context.Background(), 7, "cfg-a", "d-x")
+ appErr, ok := apperrors.IsAppError(err)
+ require.True(t, ok)
+ require.Equal(t, http.StatusNotFound, appErr.HTTPCode)
+ require.Equal(t, "sandbox config not found", appErr.Message)
+ rel.busy = true
+ require.ErrorIs(t, svc.ReleaseUserMachine(context.Background(), 7, "cfg-a", "d-1"), ErrUserSandboxBusy)
+ require.Len(t, rel.released, 1, "a busy machine is not released")
+}
+
+func TestListUserMachinesHidesOtherWorkspacesAndClocksRetention(t *testing.T) {
+ empty := time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC)
+ repo := &fakeConfigRepo{entity: &types.TenantSandboxConfigEntity{
+ ID: "cfg-a", TenantID: 7,
+ Config: &types.TenantSandboxConfig{UserSandboxEmptyRetentionDays: 14},
+ }}
+ alloc := userMachineAllocRepo{
+ byConfig: []*types.SandboxUserMachine{
+ {
+ MachineDigest: "d-own", OwnerTenantID: 7, OwnerID: "u-1",
+ ConfigTenantID: 7, ConfigID: "cfg-a", EmptySince: &empty,
+ },
+ {
+ MachineDigest: "d-borrow", OwnerTenantID: 9, OwnerID: "secret-owner",
+ ConfigTenantID: 7, ConfigID: "cfg-a",
+ },
+ },
+ live: map[string]int64{"d-own": 2},
+ }
+ svc := newTestConfigService(t, repo, nil, stubAgentRepo{}).WithAllocationRepo(alloc)
+
+ got, err := svc.ListUserMachines(context.Background(), 7, "cfg-a")
+ require.NoError(t, err)
+ require.Len(t, got, 2)
+ require.Equal(t, "u-1", got[0].OwnerID)
+ require.EqualValues(t, 2, got[0].LiveSessions)
+ require.NotNil(t, got[0].ReclaimAfter)
+ require.True(t, got[0].ReclaimAfter.Equal(empty.Add(14*24*time.Hour)))
+ require.Empty(t, got[1].OwnerID, "a borrower from another workspace is not named")
+ require.Nil(t, got[1].EmptySince)
+ require.Nil(t, got[1].ReclaimAfter)
+}
+
+func TestListUserMachinesUsesDefaultRetentionWhenUnset(t *testing.T) {
+ empty := time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC)
+ repo := &fakeConfigRepo{entity: &types.TenantSandboxConfigEntity{
+ ID: "cfg-a", TenantID: 7,
+ Config: &types.TenantSandboxConfig{UserSandboxEmptyRetentionDays: 0},
+ }}
+ alloc := userMachineAllocRepo{byConfig: []*types.SandboxUserMachine{
+ {
+ MachineDigest: "d-1", OwnerTenantID: 7, OwnerID: "u-1",
+ ConfigTenantID: 7, ConfigID: "cfg-a", EmptySince: &empty,
+ },
+ }}
+ svc := newTestConfigService(t, repo, nil, stubAgentRepo{}).WithAllocationRepo(alloc)
+
+ got, err := svc.ListUserMachines(context.Background(), 7, "cfg-a")
+ require.NoError(t, err)
+ require.Len(t, got, 1)
+ require.True(t, got[0].ReclaimAfter.Equal(empty.Add(7*24*time.Hour)))
+}
+
+func TestInventoryCountsUserMachinesSeparately(t *testing.T) {
+ svc := &TenantSandboxConfigService{}
+ inv := svc.inventoryFromSummaries(context.Background(), 7, "cfg-a", []sandbox.RemoteSandboxSummary{
+ {ID: "sb-1", Metadata: map[string]string{sandbox.MetadataSessionIDKey(): "s-1"}},
+ {ID: "sb-2", Metadata: map[string]string{sandbox.MetadataAllocationKey(): sandbox.MetadataAllocationUser}},
+ })
+ require.Equal(t, 2, inv.SandboxCount)
+ require.Equal(t, []string{"s-1"}, inv.SessionIDs)
+ require.Equal(t, 1, inv.UserSandboxCount)
+}
diff --git a/internal/application/service/tenant_skill_install_test.go b/internal/application/service/tenant_skill_install_test.go
index c7736bccf..a5bd51db2 100644
--- a/internal/application/service/tenant_skill_install_test.go
+++ b/internal/application/service/tenant_skill_install_test.go
@@ -2318,6 +2318,13 @@ func (r *installConfigRepo) SetCordon(context.Context, uint64, string, time.Time
return nil
}
func (r *installConfigRepo) ClearCordon(context.Context, uint64, string) error { return nil }
+func (r *installConfigRepo) RefreshCordon(context.Context, uint64, string, time.Time, time.Time) error {
+ return nil
+}
+
+func (r *installConfigRepo) ClearCordonIf(context.Context, uint64, string, time.Time) error {
+ return nil
+}
type installSkillRepo struct {
mu sync.Mutex
@@ -3418,7 +3425,9 @@ func (s *installModelService) GetChatModel(_ context.Context, modelID string) (c
}
return installChat{id: modelID}, nil
}
+
func (s *installModelService) GetVLMModel(context.Context, string) (vlm.VLM, error) { return nil, nil }
+
func (s *installModelService) GetASRModel(context.Context, string) (asr.ASR, error) { return nil, nil }
type installChat struct{ id string }
diff --git a/internal/application/service/tenant_skill_reaper_test.go b/internal/application/service/tenant_skill_reaper_test.go
index 52634d380..fb0ce044e 100644
--- a/internal/application/service/tenant_skill_reaper_test.go
+++ b/internal/application/service/tenant_skill_reaper_test.go
@@ -1019,6 +1019,14 @@ func (r *reaperConfigStore) ClearCordon(context.Context, uint64, string) error {
panic("ClearCordon is outside the reaper surface")
}
+func (r *reaperConfigStore) RefreshCordon(context.Context, uint64, string, time.Time, time.Time) error {
+ panic("RefreshCordon is outside the reaper surface")
+}
+
+func (r *reaperConfigStore) ClearCordonIf(context.Context, uint64, string, time.Time) error {
+ panic("ClearCordonIf is outside the reaper surface")
+}
+
type reaperSandboxResolver struct {
provider *reaperSnapshotProvider
// resolves counts provider constructions. Resolving builds a client, so a
diff --git a/internal/application/service/user.go b/internal/application/service/user.go
index e60d803c3..61691dd7c 100644
--- a/internal/application/service/user.go
+++ b/internal/application/service/user.go
@@ -104,6 +104,7 @@ type userService struct {
memberService interfaces.TenantMemberService
config *config.Config
systemSettingSvc interfaces.SystemSettingService
+ sandboxReleaser SandboxOwnerReleaser
}
// NewUserService creates a new user service instance
@@ -717,9 +718,44 @@ func (s *userService) UpdateUserPreferences(
return merged, nil
}
-// DeleteUser deletes a user
+// SandboxOwnerReleaser frees a deleted account's user machines.
+type SandboxOwnerReleaser interface {
+ ReleaseOwnerAssignments(ctx context.Context, ownerID string) error
+ ReclaimOwner(ctx context.Context, ownerID string)
+}
+
+// WithSandboxReleaser wires user-machine release into DeleteUser.
+func (s *userService) WithSandboxReleaser(r SandboxOwnerReleaser) { s.sandboxReleaser = r }
+
+// DeleteUser deletes a user. When a releaser is wired onto the allocation
+// repository, one transaction locks the user, retires every session, and
+// soft-deletes the row. A repository without that method (in-memory doubles)
+// still releases assignments, then deletes, then reclaims. Reclaim after the
+// row is gone is best-effort.
func (s *userService) DeleteUser(ctx context.Context, id string) error {
- return s.userRepo.DeleteUser(ctx, id)
+ if s.sandboxReleaser != nil {
+ if retiring, ok := s.userRepo.(interface {
+ DeleteUserRetiringSessions(context.Context, string, time.Time) error
+ }); ok {
+ if err := retiring.DeleteUserRetiringSessions(ctx, id, time.Now()); err != nil {
+ return fmt.Errorf("release user sandboxes: %w", err)
+ }
+ bg := context.WithoutCancel(ctx)
+ go s.sandboxReleaser.ReclaimOwner(bg, id)
+ return nil
+ }
+ if err := s.sandboxReleaser.ReleaseOwnerAssignments(ctx, id); err != nil {
+ return fmt.Errorf("release user sandboxes: %w", err)
+ }
+ }
+ if err := s.userRepo.DeleteUser(ctx, id); err != nil {
+ return err
+ }
+ if s.sandboxReleaser != nil {
+ bg := context.WithoutCancel(ctx)
+ go s.sandboxReleaser.ReclaimOwner(bg, id)
+ }
+ return nil
}
// ChangePassword changes user password after verifying the current
diff --git a/internal/application/service/user_delete_sandbox_test.go b/internal/application/service/user_delete_sandbox_test.go
new file mode 100644
index 000000000..11ef06459
--- /dev/null
+++ b/internal/application/service/user_delete_sandbox_test.go
@@ -0,0 +1,103 @@
+package service
+
+import (
+ "context"
+ "errors"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+)
+
+// deleteOrder records the steps of an account deletion. The user repo and
+// the sandbox releaser share one log so the test can see which ran first.
+type deleteOrder struct {
+ mu sync.Mutex
+ steps []string
+}
+
+func (o *deleteOrder) note(step string) {
+ o.mu.Lock()
+ defer o.mu.Unlock()
+ o.steps = append(o.steps, step)
+}
+
+func (o *deleteOrder) snapshot() []string {
+ o.mu.Lock()
+ defer o.mu.Unlock()
+ out := make([]string, len(o.steps))
+ copy(out, o.steps)
+ return out
+}
+
+// memUserRepo is the in-memory user store these deletion tests drive.
+// DeleteUser removes the row, so a release failure can be told apart from
+// a deletion that went through.
+type memUserRepo struct {
+ interfaces.UserRepository
+ users map[string]*types.User
+ log *deleteOrder
+}
+
+func (r *memUserRepo) GetUserByID(_ context.Context, id string) (*types.User, error) {
+ u, ok := r.users[id]
+ if !ok {
+ return nil, errors.New("user not found")
+ }
+ cp := *u
+ return &cp, nil
+}
+
+func (r *memUserRepo) DeleteUser(_ context.Context, id string) error {
+ r.log.note("DeleteUser")
+ delete(r.users, id)
+ return nil
+}
+
+type fakeSandboxReleaser struct {
+ log *deleteOrder
+ releaseErr error
+}
+
+func (f *fakeSandboxReleaser) ReleaseOwnerAssignments(context.Context, string) error {
+ f.log.note("ReleaseOwnerAssignments")
+ return f.releaseErr
+}
+
+func (f *fakeSandboxReleaser) ReclaimOwner(context.Context, string) {
+ f.log.note("ReclaimOwner")
+}
+
+func TestDeleteUserAbortsWhenSandboxReleaseFails(t *testing.T) {
+ log := &deleteOrder{}
+ repo := &memUserRepo{users: map[string]*types.User{"u-1": {ID: "u-1"}}, log: log}
+ releaseErr := errors.New("sandbox release failed")
+ svc := &userService{userRepo: repo}
+ svc.WithSandboxReleaser(&fakeSandboxReleaser{log: log, releaseErr: releaseErr})
+
+ err := svc.DeleteUser(context.Background(), "u-1")
+ require.ErrorIs(t, err, releaseErr)
+ got, getErr := svc.GetUserByID(context.Background(), "u-1")
+ require.NoError(t, getErr)
+ require.Equal(t, "u-1", got.ID)
+ require.Equal(t, []string{"ReleaseOwnerAssignments"}, log.snapshot())
+}
+
+func TestDeleteUserReleasesBeforeDeletingAndReclaimsAfter(t *testing.T) {
+ log := &deleteOrder{}
+ repo := &memUserRepo{users: map[string]*types.User{"u-1": {ID: "u-1"}}, log: log}
+ svc := &userService{userRepo: repo}
+ svc.WithSandboxReleaser(&fakeSandboxReleaser{log: log})
+
+ require.NoError(t, svc.DeleteUser(context.Background(), "u-1"))
+ require.Eventually(t, func() bool {
+ return len(log.snapshot()) == 3
+ }, time.Second, 10*time.Millisecond)
+ require.Equal(t, []string{"ReleaseOwnerAssignments", "DeleteUser", "ReclaimOwner"}, log.snapshot())
+ _, err := svc.GetUserByID(context.Background(), "u-1")
+ require.Error(t, err)
+}
diff --git a/internal/application/service/user_env_test.go b/internal/application/service/user_env_test.go
index 93f7b9c53..1f1302d28 100644
--- a/internal/application/service/user_env_test.go
+++ b/internal/application/service/user_env_test.go
@@ -61,19 +61,31 @@ func (r *userEnvConfigRepo) ListByTenant(
func (r *userEnvConfigRepo) ListAll(context.Context) ([]*types.TenantSandboxConfigEntity, error) {
panic("ListAll is outside the user env surface")
}
+
func (r *userEnvConfigRepo) Update(context.Context, *types.TenantSandboxConfigEntity) error {
panic("Update is outside the user env surface")
}
+
func (r *userEnvConfigRepo) SoftDelete(context.Context, uint64, string) error {
panic("SoftDelete is outside the user env surface")
}
+
func (r *userEnvConfigRepo) SetCordon(context.Context, uint64, string, time.Time) error {
panic("SetCordon is outside the user env surface")
}
+
func (r *userEnvConfigRepo) ClearCordon(context.Context, uint64, string) error {
panic("ClearCordon is outside the user env surface")
}
+func (r *userEnvConfigRepo) RefreshCordon(context.Context, uint64, string, time.Time, time.Time) error {
+ panic("RefreshCordon is outside the user env surface")
+}
+
+func (r *userEnvConfigRepo) ClearCordonIf(context.Context, uint64, string, time.Time) error {
+ panic("ClearCordonIf is outside the user env surface")
+}
+
var _ repository.TenantSandboxConfigRepository = (*userEnvConfigRepo)(nil)
// newUserEnvFixture seeds one workspace whose skills cover every case the
diff --git a/internal/container/container.go b/internal/container/container.go
index fbb4c5fb4..6bfb7ea9e 100644
--- a/internal/container/container.go
+++ b/internal/container/container.go
@@ -97,6 +97,7 @@ import (
"github.com/Tencent/WeKnora/internal/models/utils/ollama"
"github.com/Tencent/WeKnora/internal/router"
"github.com/Tencent/WeKnora/internal/sandbox"
+ "github.com/Tencent/WeKnora/internal/sandbox/admission"
"github.com/Tencent/WeKnora/internal/storageallowlist"
"github.com/Tencent/WeKnora/internal/stream"
"github.com/Tencent/WeKnora/internal/tracing/langfuse"
@@ -234,6 +235,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
}
return b
}))
+ must(container.Provide(newAdmissionRegistry))
must(container.Provide(newTenantSandboxResolver))
// The resolver admits user-mode sessions, so the allocation service has to
// exist before the first Invoke that builds a TenantSandboxResolver
@@ -340,6 +342,15 @@ func BuildContainer(container *dig.Container) *dig.Container {
must(container.Provide(service.NewStorageBackendServiceWithResources))
must(container.Provide(func(s *service.StorageBackendService) interfaces.StorageBackendService { return s }))
must(container.Provide(func(s *service.StorageBackendService) interfaces.StorageBackendResolver { return s }))
+ // Config deletion drains in-flight creates on the same admission registry
+ // the resolver injects into managers, then drops that config's machines.
+ must(container.Invoke(func(
+ svc *service.TenantSandboxConfigService,
+ repo interfaces.SandboxAllocationRepository,
+ reg admission.Registry,
+ ) {
+ svc.WithAllocationRepo(repo).WithAdmission(reg)
+ }))
// Agent service layer (requires event bus, web search service)
// SessionService is passed as parameter to CreateAgentEngine method when creating AgentService
@@ -456,6 +467,9 @@ func BuildContainer(container *dig.Container) *dig.Container {
return pinned
}))
must(container.Provide(service.NewSessionForkServiceFromRepos))
+ must(container.Invoke(func(f *service.SessionForkService, a *sandboxalloc.Service) {
+ f.WithAllocations(a)
+ }))
must(container.Provide(func(
mgr sandbox.Manager,
pinned *service.PinnedSessionSandbox,
@@ -566,6 +580,53 @@ func BuildContainer(container *dig.Container) *dig.Container {
p.WithPlacer(a)
skills.WithPlacer(a)
}))
+ // Tombstones are allocation rows. Wire the cleaner only where a remote
+ // sandbox config can be resolved. Lite and host stay unwired, so a delete
+ // there does not write one.
+ must(container.Provide(sandboxalloc.NewWorkspaceCleaner))
+ must(container.Invoke(func(
+ s interfaces.SessionService,
+ c *sandboxalloc.WorkspaceCleaner,
+ resolver sandbox.TenantSandboxResolver,
+ ) {
+ if handler.Edition == "lite" || resolver == nil {
+ return
+ }
+ if svc, ok := s.(interface {
+ WithWorkspaceCleaner(*sandboxalloc.WorkspaceCleaner)
+ }); ok {
+ svc.WithWorkspaceCleaner(c)
+ }
+ }))
+ // Deleting a Web account retires that account's sessions before the user
+ // row goes. Lite and host stay unwired, same as session deletion, so a
+ // delete there does not write allocation rows.
+ must(container.Invoke(func(
+ u interfaces.UserService,
+ c *sandboxalloc.WorkspaceCleaner,
+ resolver sandbox.TenantSandboxResolver,
+ ) {
+ if handler.Edition == "lite" || resolver == nil {
+ return
+ }
+ if svc, ok := u.(interface {
+ WithSandboxReleaser(service.SandboxOwnerReleaser)
+ }); ok {
+ svc.WithSandboxReleaser(c)
+ }
+ }))
+ // Admin release uses the same cleaner. Lite and host stay unwired, so
+ // those editions do not gain a path that writes allocation rows.
+ must(container.Invoke(func(
+ cfgSvc *service.TenantSandboxConfigService,
+ cleaner *sandboxalloc.WorkspaceCleaner,
+ resolver sandbox.TenantSandboxResolver,
+ ) {
+ if handler.Edition == "lite" || resolver == nil {
+ return
+ }
+ cfgSvc.WithUserMachineReleaser(cleaner)
+ }))
must(container.Invoke(startTenantSkillReaper))
logger.Debugf(ctx, "[Container] Tenant skill reaper registered")
must(
@@ -591,6 +652,18 @@ func BuildContainer(container *dig.Container) *dig.Container {
}))
must(container.Invoke(startForkSnapshotReaper))
logger.Debugf(ctx, "[Container] Fork snapshot reaper registered")
+ must(container.Provide(func(
+ svc *sandboxalloc.Service, cleaner *sandboxalloc.WorkspaceCleaner,
+ configs repository.TenantSandboxConfigRepository, redisClient *redis.Client,
+ ) *sandboxalloc.UserMachineGC {
+ var client redis.UniversalClient
+ if redisClient != nil {
+ client = redisClient
+ }
+ return sandboxalloc.NewUserMachineGC(svc, cleaner, configs, client)
+ }))
+ must(container.Invoke(startUserMachineGC))
+ logger.Debugf(ctx, "[Container] User machine GC registered")
// HTTP handlers layer
logger.Debugf(ctx, "[Container] Registering HTTP handlers...")
@@ -2130,6 +2203,35 @@ func startAgentPromptReaper(runs *service.SuspendedRunService, cleaner interface
})
}
+// startUserMachineGC reclaims empty user machines hourly. Every replica runs
+// the ticker; the Redis lock inside RunOnce lets one of them scan.
+func startUserMachineGC(gc *sandboxalloc.UserMachineGC, cleaner interfaces.ResourceCleaner) {
+ if gc == nil || cleaner == nil {
+ logger.Warnf(context.Background(), "[Container] user machine GC unavailable")
+ return
+ }
+ stop := make(chan struct{})
+ go func() {
+ timer := time.NewTimer(2 * time.Minute)
+ defer timer.Stop()
+ for {
+ select {
+ case <-timer.C:
+ if _, err := gc.RunOnce(context.Background()); err != nil {
+ logger.Warnf(context.Background(), "[UserMachineGC] run failed: %v", err)
+ }
+ timer.Reset(sandboxalloc.UserMachineGCInterval)
+ case <-stop:
+ return
+ }
+ }
+ }()
+ cleaner.RegisterWithName("UserMachineGC", func() error {
+ close(stop)
+ return nil
+ })
+}
+
// startTemporaryDocumentCleanup removes expired session attachments and their
// extracted images. The durable expiry timestamp is the source of truth; the
// ticker only controls how quickly storage is reclaimed.
diff --git a/internal/container/sandbox.go b/internal/container/sandbox.go
index 25fd72803..b0c2080f9 100644
--- a/internal/container/sandbox.go
+++ b/internal/container/sandbox.go
@@ -40,14 +40,6 @@ func sandboxRedisNamespace() string {
return namespace
}
-// userModeRuntimeReady stays false until a deleted user-mode session is
-// retired, fork and rewind take the shared machine's exclusive window, and
-// the desktop slot is per machine (plan T12–T18). T10 can already place and
-// run those sessions, but opening the gate before the rest leaves a shared
-// machine that is never released, forked, or exclusively rewound. The gate
-// also needs Redis and the env opt-in; without those it stays closed.
-const userModeRuntimeReady = false
-
func selectSessionBindingStore(
redisClient *redis.Client,
requireRedis bool,
@@ -59,14 +51,10 @@ func selectSessionBindingStore(
if err != nil {
return nil, "", fmt.Errorf("build redis binding store: %w", err)
}
- allocation.SetUserModeAvailable(requested && userModeRuntimeReady)
- switch {
- case requested && !userModeRuntimeReady:
- logger.Warnf(context.Background(),
- "[sandbox] %s is set but this build cannot run user-mode sessions yet; "+
- "user-mode allocation stays disabled",
- allocation.UserModeEnvVar)
- case requested:
+ // User mode needs both the env opt-in and Redis; without Redis the
+ // leases that coordinate one machine across replicas do not exist.
+ allocation.SetUserModeAvailable(requested)
+ if requested {
logger.Infof(context.Background(), "[sandbox] user-mode allocation enabled (%s)", allocation.UserModeEnvVar)
}
return store, "redis", nil
@@ -149,6 +137,7 @@ func newTenantSandboxResolver(
sessionRepo interfaces.SessionRepository,
bootstrapper sandbox.SessionBootstrapper,
alloc *sandboxalloc.Service,
+ reg admission.Registry,
) sandbox.TenantSandboxResolver {
ctx := context.Background()
@@ -168,7 +157,7 @@ func newTenantSandboxResolver(
Checker: sessionExistenceCheckerFor(sessionRepo),
Bootstrapper: bootstrapper,
Allocations: alloc,
- Admission: newAdmissionRegistry(redisClient),
+ Admission: reg,
Namespace: sandboxRedisNamespace(),
SharedTransport: sandbox.NewGuardedTransport(),
})
diff --git a/internal/container/sandbox_test.go b/internal/container/sandbox_test.go
index da62b2f63..bb47f9f2a 100644
--- a/internal/container/sandbox_test.go
+++ b/internal/container/sandbox_test.go
@@ -54,8 +54,7 @@ func TestSelectSessionBindingStoreUserModeNeedsRedisAndEnv(t *testing.T) {
t.Cleanup(func() { _ = client.Close() })
_, _, err = selectSessionBindingStore(client, true)
require.NoError(t, err)
- require.Equal(t, userModeRuntimeReady, allocation.UserModeAvailable(),
- "env opt-in with Redis opens the gate only once the manager can run user-mode sessions")
+ require.True(t, allocation.UserModeAvailable(), "env opt-in with Redis opens the gate")
t.Setenv(allocation.UserModeEnvVar, "")
_, _, err = selectSessionBindingStore(client, true)
diff --git a/internal/handler/sandbox_config.go b/internal/handler/sandbox_config.go
index 0c0243443..54c4c6aa9 100644
--- a/internal/handler/sandbox_config.go
+++ b/internal/handler/sandbox_config.go
@@ -22,6 +22,8 @@ type sandboxConfigService interface {
Update(context.Context, uint64, string, service.UpdateSandboxConfigInput) (*types.TenantSandboxConfigEntity, error)
Delete(context.Context, uint64, string, bool) error
Inventory(context.Context, uint64, string) (service.SandboxInventory, error)
+ ListUserMachines(context.Context, uint64, string) ([]service.UserMachineView, error)
+ ReleaseUserMachine(context.Context, uint64, string, string) error
WorkspaceScriptsDisabled(context.Context, uint64) (bool, error)
SetWorkspaceScriptsDisabled(context.Context, uint64, bool) error
QueryTemplates(context.Context, uint64, service.SandboxTemplateQueryInput) (*service.SandboxTemplateCatalog, error)
@@ -215,7 +217,8 @@ func respondSandboxConfigRefusal(c *gin.Context, err error) bool {
respondSkillSnapshotBlocksTemplate(c)
return true
}
- if stderrors.Is(err, repository.ErrSandboxConfigCordoned) {
+ if stderrors.Is(err, repository.ErrSandboxConfigCordoned) ||
+ stderrors.Is(err, service.ErrSandboxConfigCreatesInFlight) {
respondSandboxConfigCordoned(c)
return true
}
@@ -455,3 +458,55 @@ func (h *SandboxConfigHandler) Inventory(c *gin.Context) {
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": inv})
}
+
+// ListUserSandboxes godoc
+// @Summary List shared user sandboxes
+// @Description List the config's shared user machines with live session counts and the empty-retention clock.
+// @Tags SandboxConfig
+// @Produce json
+// @Param id path string true "Sandbox config ID"
+// @Success 200 {object} map[string]interface{} "Shared user sandboxes"
+// @Failure 401 {object} map[string]interface{} "Unauthorized"
+// @Security Bearer
+// @Security ApiKeyAuth
+// @Router /sandbox-configs/{id}/user-sandboxes [get]
+func (h *SandboxConfigHandler) ListUserSandboxes(c *gin.Context) {
+ if h.liteHidden(c, false) {
+ return
+ }
+ rows, err := h.service.ListUserMachines(c.Request.Context(), sandboxConfigTenantID(c), c.Param("id"))
+ if err != nil {
+ _ = c.Error(err)
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"success": true, "data": rows})
+}
+
+// ReleaseUserSandbox godoc
+// @Summary Release a shared user sandbox
+// @Description Delete one shared user machine now; each session gets a fresh machine on next use. Refused while busy.
+// @Tags SandboxConfig
+// @Produce json
+// @Param id path string true "Sandbox config ID"
+// @Param digest path string true "User machine digest"
+// @Success 200 {object} map[string]interface{} "Released"
+// @Failure 401 {object} map[string]interface{} "Unauthorized"
+// @Failure 409 {object} map[string]interface{} "User sandbox is busy"
+// @Security Bearer
+// @Security ApiKeyAuth
+// @Router /sandbox-configs/{id}/user-sandboxes/{digest}/release [post]
+func (h *SandboxConfigHandler) ReleaseUserSandbox(c *gin.Context) {
+ if h.liteHidden(c, false) {
+ return
+ }
+ err := h.service.ReleaseUserMachine(c.Request.Context(), sandboxConfigTenantID(c), c.Param("id"), c.Param("digest"))
+ if stderrors.Is(err, service.ErrUserSandboxBusy) {
+ c.JSON(http.StatusConflict, gin.H{"success": false, "error": "USER_SANDBOX_BUSY"})
+ return
+ }
+ if err != nil {
+ _ = c.Error(err)
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"success": true})
+}
diff --git a/internal/handler/sandbox_config_test.go b/internal/handler/sandbox_config_test.go
index ae97280bc..fb11a2d46 100644
--- a/internal/handler/sandbox_config_test.go
+++ b/internal/handler/sandbox_config_test.go
@@ -14,6 +14,7 @@ import (
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
+ "github.com/Tencent/WeKnora/internal/application/repository"
"github.com/Tencent/WeKnora/internal/application/service"
apperrors "github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/middleware"
@@ -236,6 +237,13 @@ type fakeSandboxConfigService struct {
deleteTenantID uint64
deleteID string
deleteForce bool
+
+ machines []service.UserMachineView
+ listErr error
+ releaseErr error
+ releaseTenant uint64
+ releaseConfig string
+ releaseDigest string
}
func (s *fakeSandboxConfigService) Create(
@@ -290,6 +298,21 @@ func (s *fakeSandboxConfigService) Inventory(
return service.SandboxInventory{}, nil
}
+func (s *fakeSandboxConfigService) ListUserMachines(
+ context.Context, uint64, string,
+) ([]service.UserMachineView, error) {
+ return s.machines, s.listErr
+}
+
+func (s *fakeSandboxConfigService) ReleaseUserMachine(
+ _ context.Context, tenantID uint64, configID, digest string,
+) error {
+ s.releaseTenant = tenantID
+ s.releaseConfig = configID
+ s.releaseDigest = digest
+ return s.releaseErr
+}
+
func (s *fakeSandboxConfigService) WorkspaceScriptsDisabled(
context.Context,
uint64,
@@ -342,3 +365,64 @@ func TestSandboxConfigRoutesAreHiddenOnLiteDesktop(t *testing.T) {
r.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/sandbox-configs", strings.NewReader(`{"name":"x"}`)))
require.Equal(t, http.StatusNotFound, w.Code)
}
+
+func TestListAndReleaseUserSandboxes(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ svc := &fakeSandboxConfigService{machines: []service.UserMachineView{{
+ Digest: "d-1", OwnerTenantID: 7, OwnerID: "u-1", LiveSessions: 2,
+ }}}
+ h := &SandboxConfigHandler{service: svc}
+ r := gin.New()
+ r.Use(func(c *gin.Context) {
+ c.Set(types.TenantIDContextKey.String(), uint64(7))
+ c.Next()
+ })
+ r.GET("/sandbox-configs/:id/user-sandboxes", h.ListUserSandboxes)
+ r.POST("/sandbox-configs/:id/user-sandboxes/:digest/release", h.ReleaseUserSandbox)
+
+ w := httptest.NewRecorder()
+ r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/sandbox-configs/cfg-a/user-sandboxes", nil))
+ require.Equal(t, http.StatusOK, w.Code)
+ require.Contains(t, w.Body.String(), `"digest":"d-1"`)
+ require.Contains(t, w.Body.String(), `"owner_id":"u-1"`)
+
+ svc.releaseErr = service.ErrUserSandboxBusy
+ w = httptest.NewRecorder()
+ r.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/sandbox-configs/cfg-a/user-sandboxes/d-1/release", nil))
+ require.Equal(t, http.StatusConflict, w.Code)
+ require.JSONEq(t, `{"success":false,"error":"USER_SANDBOX_BUSY"}`, w.Body.String())
+ require.Equal(t, uint64(7), svc.releaseTenant)
+ require.Equal(t, "cfg-a", svc.releaseConfig)
+ require.Equal(t, "d-1", svc.releaseDigest)
+
+ svc.releaseErr = nil
+ w = httptest.NewRecorder()
+ r.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/sandbox-configs/cfg-a/user-sandboxes/d-1/release", nil))
+ require.Equal(t, http.StatusOK, w.Code)
+ require.JSONEq(t, `{"success":true}`, w.Body.String())
+}
+
+func TestCordonAndInFlightCreateMapToLocked(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ for _, err := range []error{
+ repository.ErrSandboxConfigCordoned,
+ service.ErrSandboxConfigCreatesInFlight,
+ } {
+ router := gin.New()
+ router.DELETE("/sandbox-configs/:id", func(c *gin.Context) {
+ if !respondSandboxConfigRefusal(c, err) {
+ t.Fatal("expected a locked refusal")
+ }
+ })
+ w := httptest.NewRecorder()
+ router.ServeHTTP(w, httptest.NewRequest(http.MethodDelete, "/sandbox-configs/cfg-a", nil))
+ require.Equal(t, http.StatusLocked, w.Code)
+ var payload struct {
+ Error struct {
+ Code string `json:"code"`
+ } `json:"error"`
+ }
+ require.NoError(t, json.Unmarshal(w.Body.Bytes(), &payload))
+ require.Equal(t, "sandbox_config_cordoned", payload.Error.Code)
+ }
+}
diff --git a/internal/handler/session/sandbox_desktop_ws.go b/internal/handler/session/sandbox_desktop_ws.go
index 72af0b005..490908dec 100644
--- a/internal/handler/session/sandbox_desktop_ws.go
+++ b/internal/handler/session/sandbox_desktop_ws.go
@@ -144,8 +144,9 @@ func (h *Handler) IssueSandboxDesktopTicket(c *gin.Context) {
// SandboxDesktopWS relays the browser's RFB stream to the session sandbox.
//
-// Ticket, auth, and the exclusive slot stay HTTP because those run before
-// Ensure. Overlay states from Ensure (SANDBOX_NOT_BOUND / SANDBOX_PAUSED /
+// Ticket and auth stay HTTP. Locate may provision but does not start the
+// desktop; the operation hold and the exclusive slots come next, then Start.
+// Overlay states from locate or start (SANDBOX_NOT_BOUND / SANDBOX_PAUSED /
// DESKTOP_UNSUPPORTED / DESKTOP_START_FAILED) must upgrade and then close
// with a reason: the JS WebSocket API never exposes a failed handshake's
// HTTP status, so a 409 here becomes a generic error overlay instead of
@@ -161,7 +162,7 @@ func (h *Handler) SandboxDesktopWS(c *gin.Context) {
// 1. One-shot ticket. Auth reads the incoming request; workspace identity
// is attached next. Do not capture c.Request.Context() before
// AttachAuthenticatedUser — that snapshot has no tenant, and
- // EnsureSessionDesktop then fails with "missing workspace context"
+ // LocateSessionDesktop then fails with "missing workspace context"
// (mapped to DESKTOP_UPSTREAM). SandboxTerminalWS binds ctx after attach
// for the same reason.
claims, err := h.desktopTickets.Consume(c.Request.Context(), c.Query("ticket"))
@@ -193,10 +194,52 @@ func (h *Handler) SandboxDesktopWS(c *gin.Context) {
}
ctx := c.Request.Context()
- // 2. One desktop per session, across replicas. Unlike the terminal's
- // 5-per-session in-process counter, this must be distributed: two
- // browsers on one desktop means two people fighting over one keyboard.
- releaseSlot, acquired, slotHold, err := h.acquireDesktopSlot(ctx, sessionID)
+ // 2. Locate. Lookup-only unless the user confirmed provision. A bare
+ // handshake — panel opened, tab restored, background reconnect —
+ // stays lookup-only: a running sandbox is attached, a paused one
+ // reports SANDBOX_PAUSED, and a missing one reports SANDBOX_NOT_BOUND.
+ // Only a confirmed click sets provision=1. This does not start the
+ // desktop; the request context cancels it if the browser gives up.
+ allowProvision := terminalFlagParam(c.Query("provision"))
+ provision := h.terminalProvisionPin(ctx, c, allowProvision)
+ target, err := h.desktopService.LocateSessionDesktop(ctx, sessionID, provision)
+ if err != nil {
+ h.closeDesktopWithError(c, sessionID, allowProvision, "locate", err)
+ return
+ }
+
+ // 3. Hold the operation first: from here the shared machine cannot be
+ // rebuilt or reclaimed, so the binding read next names the machine the
+ // relay will reach.
+ opCtx, releaseOp, err := target.HoldOperation(ctx)
+ if err != nil {
+ c.JSON(http.StatusConflict, gin.H{"error": desktopErrBusy})
+ return
+ }
+ defer releaseOp()
+ if err := target.FixMachine(opCtx); err != nil {
+ h.closeDesktopWithError(c, sessionID, allowProvision, "locate", err)
+ return
+ }
+
+ // 4. One controlling desktop per machine, across replicas. The legacy
+ // per-session slot is held too, so replicas still on the previous
+ // release stay mutually exclusive during a rolling upgrade (remove it
+ // in the following release). Unlike the terminal's 5-per-session
+ // in-process counter, this must be distributed: two browsers on one
+ // desktop means two people fighting over one keyboard.
+ releaseLegacy, gotLegacy, legacyHold, err := h.acquireDesktopSlot(ctx, desktopSlotKey(sessionID))
+ if err != nil {
+ logger.ErrorWithFields(ctx, err, map[string]interface{}{"session_id": sessionID})
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to reserve desktop"})
+ return
+ }
+ if !gotLegacy {
+ c.JSON(http.StatusConflict, gin.H{"error": desktopErrBusy})
+ return
+ }
+ defer releaseLegacy()
+ releaseSlot, acquired, machineHold, err := h.acquireDesktopSlot(ctx, desktopMachineSlotKey(target.MachineID))
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{"session_id": sessionID})
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to reserve desktop"})
@@ -207,16 +250,12 @@ func (h *Handler) SandboxDesktopWS(c *gin.Context) {
return
}
defer releaseSlot()
+ slotHold, stopSlotHold := mergeDesktopHolds(legacyHold, machineHold, opCtx)
+ defer stopSlotHold()
- // 3. Start, dial. Provisioning is opt-in per connect, because it creates
- // (or resumes and re-bills) a microVM and this is a GET. A bare
- // handshake — panel opened, tab restored, background reconnect —
- // stays lookup-only: a running sandbox is attached, a paused one
- // reports SANDBOX_PAUSED, and a missing one reports SANDBOX_NOT_BOUND.
- // Only a confirmed click sets provision=1. Use the request context so
- // a browser that gives up the handshake (and every DESKTOP_BUSY retry)
- // cancels this work and releases the slot. The relay context is
- // detached only after the browser socket is upgraded.
+ // Start, dial on the fixed sandbox. The relay context is detached only
+ // after the browser socket is upgraded. Losing either slot or the
+ // operation lease cancels this work.
ensureCtx := ctx
if slotHold != nil {
var cancelEnsure context.CancelFunc
@@ -225,9 +264,7 @@ func (h *Handler) SandboxDesktopWS(c *gin.Context) {
defer stopEnsureWatch()
defer cancelEnsure()
}
- allowProvision := terminalFlagParam(c.Query("provision"))
- provision := h.terminalProvisionPin(ensureCtx, c, allowProvision)
- desktop, err := h.desktopService.EnsureSessionDesktop(ensureCtx, sessionID, provision)
+ desktop, err := h.desktopService.StartSessionDesktop(ensureCtx, target)
if err != nil {
if slotHold != nil && slotHold.Err() != nil {
c.JSON(http.StatusConflict, gin.H{"error": desktopErrBusy})
@@ -257,9 +294,8 @@ func (h *Handler) SandboxDesktopWS(c *gin.Context) {
//
// A mute upstream is answered with 502 and nothing else. Tearing the
// stack down from here and redialling was tried and made it worse: the
- // browser waits out a second Ensure inside the same upgrade, and the
- // healing belongs in EnsureSessionDesktop, which runs before the slot
- // matters.
+ // browser waits out a second start inside the same upgrade, and the
+ // healing belongs in StartSessionDesktop, which already ran.
prelude, err := readDesktopServerHandshake(ctx, desktop.Conn)
if err != nil {
_ = desktop.Conn.Close()
@@ -417,8 +453,25 @@ func readDesktopServerHandshake(ctx context.Context, conn *websocket.Conn) ([]by
})
}
-// acquireDesktopSlot reserves the session's single desktop slot across all
-// replicas.
+// closeDesktopWithError upgrades and closes with the stable code for a
+// locate or machine-fix failure. The JS WebSocket API never exposes a failed
+// handshake's HTTP status, so overlay states have to ride a close reason.
+func (h *Handler) closeDesktopWithError(
+ c *gin.Context, sessionID string, allowProvision bool, stage string, err error,
+) {
+ ctx := c.Request.Context()
+ _, code := desktopErrorStatus(err)
+ logger.Warnf(ctx, "[sandbox-desktop] %s failed session=%s provision=%t code=%s: %v",
+ stage, sessionID, allowProvision, code, err)
+ browserConn, upErr := desktopUpgrader.Upgrade(c.Writer, c.Request, nil)
+ if upErr != nil {
+ return
+ }
+ writeDesktopProtocolClose(browserConn, code)
+}
+
+// acquireDesktopSlot reserves one desktop slot across all replicas. key is
+// the full Redis key (session or machine); callers build it.
//
// The terminal's per-session cap is a process-local counter, which is
// harmless there (a second shell is a cosmetic problem) and unacceptable here
@@ -429,13 +482,12 @@ func readDesktopServerHandshake(ctx context.Context, conn *websocket.Conn) ([]by
// Redis absent means Lite mode, which is one process, so the in-process
// limiter is the correct degradation there.
func (h *Handler) acquireDesktopSlot(
- ctx context.Context, sessionID string,
+ ctx context.Context, key string,
) (release func(), acquired bool, hold context.Context, err error) {
if h.redis == nil {
- release, ok := sessionDesktopLimiter.acquire(sessionID)
+ release, ok := sessionDesktopLimiter.acquire(key)
return release, ok, nil, nil
}
- key := desktopSlotKey(sessionID)
token, err := redislock.NewToken()
if err != nil {
return func() {}, false, nil, err
@@ -514,7 +566,34 @@ func desktopSlotKey(sessionID string) string {
return "weknora:desktop-slot:" + sessionID
}
-// desktopLimiter caps the session to one desktop within this process.
+func desktopMachineSlotKey(machineID string) string {
+ return "weknora:desktop-slot:machine:" + machineID
+}
+
+// mergeDesktopHolds ends as soon as any hold ends. Nil holds (no Redis) are
+// ignored; with none left it returns nil, as a single missing hold did. The
+// stop function ends the merged context; the caller defers it once the relay
+// is done, which also satisfies go vet's lostcancel check on cancel vars
+// whose only other use sits inside a loop body.
+func mergeDesktopHolds(holds ...context.Context) (context.Context, func()) {
+ var live []context.Context
+ for _, h := range holds {
+ if h != nil {
+ live = append(live, h)
+ }
+ }
+ if len(live) == 0 {
+ return nil, func() {}
+ }
+ merged, cancel := context.WithCancelCause(context.Background())
+ for _, h := range live {
+ context.AfterFunc(h, func() { cancel(context.Cause(h)) })
+ }
+ return merged, func() { cancel(context.Canceled) }
+}
+
+// desktopLimiter caps one key to one desktop within this process. The key is
+// the full slot key, so a machine and a session do not share an entry.
type desktopLimiter struct {
mu sync.Mutex
open map[string]bool
@@ -522,20 +601,20 @@ type desktopLimiter struct {
var sessionDesktopLimiter = &desktopLimiter{open: make(map[string]bool)}
-func (l *desktopLimiter) acquire(sessionID string) (func(), bool) {
+func (l *desktopLimiter) acquire(key string) (func(), bool) {
l.mu.Lock()
defer l.mu.Unlock()
- if l.open[sessionID] {
+ if l.open[key] {
return func() {}, false
}
- l.open[sessionID] = true
+ l.open[key] = true
released := false
return func() {
l.mu.Lock()
defer l.mu.Unlock()
if !released {
released = true
- delete(l.open, sessionID)
+ delete(l.open, key)
}
}, true
}
diff --git a/internal/handler/session/sandbox_desktop_ws_test.go b/internal/handler/session/sandbox_desktop_ws_test.go
index 92fa58d4d..530bfd095 100644
--- a/internal/handler/session/sandbox_desktop_ws_test.go
+++ b/internal/handler/session/sandbox_desktop_ws_test.go
@@ -93,6 +93,35 @@ func TestDesktopSlotIsExclusivePerSession(t *testing.T) {
third()
}
+func TestDesktopSlotIsExclusivePerMachineAcrossSessions(t *testing.T) {
+ h, _, _ := newDesktopSlotHandler(t)
+ ctx := context.Background()
+ key := desktopMachineSlotKey("machine-1")
+ release, got, _, err := h.acquireDesktopSlot(ctx, key)
+ require.NoError(t, err)
+ require.True(t, got)
+ _, got, _, err = h.acquireDesktopSlot(ctx, key)
+ require.NoError(t, err)
+ require.False(t, got, "a second session on the same machine gets DESKTOP_BUSY")
+ release()
+ _, got, _, err = h.acquireDesktopSlot(ctx, desktopMachineSlotKey("machine-2"))
+ require.NoError(t, err)
+ require.True(t, got)
+}
+
+func TestMergeDesktopHoldsEndsWithAnyHold(t *testing.T) {
+ a, cancelA := context.WithCancel(context.Background())
+ b, cancelB := context.WithCancel(context.Background())
+ defer cancelB()
+ merged, stopMerged := mergeDesktopHolds(a, nil, b)
+ defer stopMerged()
+ cancelA()
+ require.Eventually(t, func() bool { return merged.Err() != nil }, time.Second, 5*time.Millisecond)
+ none, stopNone := mergeDesktopHolds(nil, nil)
+ require.Nil(t, none)
+ stopNone()
+}
+
func TestDesktopSlotReleaseIsIdempotent(t *testing.T) {
release, ok := sessionDesktopLimiter.acquire("sess-idem")
require.True(t, ok)
@@ -125,7 +154,7 @@ func TestDesktopSlotRenewSurvivesTransientRedisError(t *testing.T) {
h, mini, client := newDesktopSlotHandler(t)
ctx := context.Background()
- release, got, hold, err := h.acquireDesktopSlot(ctx, "sess-blip")
+ release, got, hold, err := h.acquireDesktopSlot(ctx, desktopSlotKey("sess-blip"))
require.NoError(t, err)
require.True(t, got)
require.NotNil(t, hold)
@@ -146,7 +175,7 @@ func TestDesktopSlotRenewSurvivesTransientRedisError(t *testing.T) {
}
require.NotEmpty(t, client.Get(ctx, desktopSlotKey("sess-blip")).Val())
- _, got, _, err = h.acquireDesktopSlot(ctx, "sess-blip")
+ _, got, _, err = h.acquireDesktopSlot(ctx, desktopSlotKey("sess-blip"))
require.NoError(t, err)
require.False(t, got, "the original relay must still own the slot after a blip")
}
@@ -156,7 +185,7 @@ func TestDesktopSlotCancelsHoldWhenRedisStaysDownPastLease(t *testing.T) {
h, mini, _ := newDesktopSlotHandler(t)
ctx := context.Background()
- release, got, hold, err := h.acquireDesktopSlot(ctx, "sess-down")
+ release, got, hold, err := h.acquireDesktopSlot(ctx, desktopSlotKey("sess-down"))
require.NoError(t, err)
require.True(t, got)
defer release()
@@ -175,7 +204,7 @@ func TestDesktopSlotCancelsHoldWhenOwnershipIsStolen(t *testing.T) {
h, _, client := newDesktopSlotHandler(t)
ctx := context.Background()
- release, got, hold, err := h.acquireDesktopSlot(ctx, "sess-stolen")
+ release, got, hold, err := h.acquireDesktopSlot(ctx, desktopSlotKey("sess-stolen"))
require.NoError(t, err)
require.True(t, got)
defer release()
@@ -187,7 +216,7 @@ func TestDesktopSlotCancelsHoldWhenOwnershipIsStolen(t *testing.T) {
t.Fatal("losing the redis key must cancel the hold so the relay can drop")
}
- second, got, secondHold, err := h.acquireDesktopSlot(ctx, "sess-stolen")
+ second, got, secondHold, err := h.acquireDesktopSlot(ctx, desktopSlotKey("sess-stolen"))
require.NoError(t, err)
require.False(t, got, "the thief still owns the key; we must not overwrite it")
_ = second
@@ -199,7 +228,7 @@ func TestDesktopSlotCancelsHoldWhenKeyExpires(t *testing.T) {
h, _, client := newDesktopSlotHandler(t)
ctx := context.Background()
- release, got, hold, err := h.acquireDesktopSlot(ctx, "sess-expired")
+ release, got, hold, err := h.acquireDesktopSlot(ctx, desktopSlotKey("sess-expired"))
require.NoError(t, err)
require.True(t, got)
defer release()
@@ -211,7 +240,7 @@ func TestDesktopSlotCancelsHoldWhenKeyExpires(t *testing.T) {
t.Fatal("an expired slot must cancel the hold; otherwise a second client can join")
}
- second, got, secondHold, err := h.acquireDesktopSlot(ctx, "sess-expired")
+ second, got, secondHold, err := h.acquireDesktopSlot(ctx, desktopSlotKey("sess-expired"))
require.NoError(t, err)
require.True(t, got, "after the first hold is lost the session must accept one new desktop")
defer second()
@@ -259,7 +288,9 @@ func TestSandboxDesktopWSLookupIsOptInProvision(t *testing.T) {
require.NoError(t, err)
text := string(src)
require.Contains(t, text, `allowProvision := terminalFlagParam(c.Query("provision"))`)
- require.Contains(t, text, `h.terminalProvisionPin(ensureCtx, c, allowProvision)`)
+ // Locate runs before either slot exists, so the pin uses the request
+ // context. Start is what ensureCtx (the slot hold) cancels.
+ require.Contains(t, text, `h.terminalProvisionPin(ctx, c, allowProvision)`)
require.NotContains(t, text, `terminalProvisionPin(ctx, c, true)`)
// The JS WebSocket API never exposes a failed handshake's HTTP status.
// Overlay states (not bound / paused) have to ride a close reason after
diff --git a/internal/handler/session/stream.go b/internal/handler/session/stream.go
index 425a499b2..d30f9555e 100644
--- a/internal/handler/session/stream.go
+++ b/internal/handler/session/stream.go
@@ -355,6 +355,11 @@ func (h *Handler) handleAgentEventsForSSE(
lastOffset := 0
log := logger.GetLogger(ctx)
+ // Agent mode releases the sandbox turn lease, and therefore cancels ctx,
+ // before the completion event is published. Polling Redis with that
+ // context drops the terminal event and the client waits at the end of
+ // the answer. Client disconnect is still observed on the request below.
+ pollCtx := context.WithoutCancel(ctx)
log.Infof("Starting pull-based SSE streaming for session=%s, message=%s", sessionID, assistantMessageID)
@@ -374,7 +379,7 @@ func (h *Handler) handleAgentEventsForSSE(
c.Writer.Flush()
case <-ticker.C:
// Get new events from StreamManager using offset
- events, newOffset, err := h.streamManager.GetEvents(ctx, sessionID, assistantMessageID, lastOffset)
+ events, newOffset, err := h.streamManager.GetEvents(pollCtx, sessionID, assistantMessageID, lastOffset)
if err != nil {
log.Warnf("Failed to get events from stream: %v", err)
continue
diff --git a/internal/handler/session/stream_turn_context_test.go b/internal/handler/session/stream_turn_context_test.go
new file mode 100644
index 000000000..230c1ea98
--- /dev/null
+++ b/internal/handler/session/stream_turn_context_test.go
@@ -0,0 +1,70 @@
+package session
+
+import (
+ "context"
+ "fmt"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+)
+
+// cancelAfterFirstReadStream mimics Redis: a canceled context fails the read.
+// The first successful read cancels the caller's context, the way agent mode
+// releases the sandbox turn lease before the completion event is published.
+type cancelAfterFirstReadStream struct {
+ interfaces.StreamManager
+ events []interfaces.StreamEvent
+ cancel context.CancelFunc
+ reads int
+}
+
+func (s *cancelAfterFirstReadStream) GetEvents(
+ ctx context.Context, _, _ string, fromOffset int,
+) ([]interfaces.StreamEvent, int, error) {
+ if err := ctx.Err(); err != nil {
+ return nil, fromOffset, fmt.Errorf("failed to get events from Redis: %w", err)
+ }
+ s.reads++
+ if s.reads == 1 {
+ s.cancel()
+ return s.events[:1], 1, nil
+ }
+ if fromOffset >= len(s.events) {
+ return nil, len(s.events), nil
+ }
+ return s.events[fromOffset:], len(s.events), nil
+}
+
+func TestHandleAgentEventsForSSE_DrainsCompletionAfterTurnContextCanceled(t *testing.T) {
+ ctx, cancel := context.WithCancel(context.Background())
+ h := &Handler{streamManager: &cancelAfterFirstReadStream{
+ cancel: cancel,
+ events: []interfaces.StreamEvent{
+ {ID: "answer-1", Type: types.ResponseTypeAnswer, Content: "你好", Done: true},
+ {ID: "complete-1", Type: types.ResponseTypeComplete, Done: true},
+ },
+ }}
+ c, recorder := newTestGinContext(t, "")
+
+ done := make(chan struct{})
+ go func() {
+ h.handleAgentEventsForSSE(
+ ctx, c, "sess1", "msg1", "req-1", nil, false, publicStreamRewriter())
+ close(done)
+ }()
+
+ select {
+ case <-done:
+ case <-time.After(2 * time.Second):
+ t.Fatal("SSE poll kept using the cancelled turn context and never delivered completion")
+ }
+
+ body := recorder.Body.String()
+ require.Contains(t, body, "你好")
+ assert.Contains(t, body, `"response_type":"complete"`)
+}
diff --git a/internal/router/router_api_key_capabilities_test.go b/internal/router/router_api_key_capabilities_test.go
index 25d712385..b0223ae12 100644
--- a/internal/router/router_api_key_capabilities_test.go
+++ b/internal/router/router_api_key_capabilities_test.go
@@ -414,6 +414,8 @@ func TestSandboxConfigRoutesRequireFullAccessOnly(t *testing.T) {
{http.MethodPut, "/api/v1/sandbox-configs/:id"},
{http.MethodDelete, "/api/v1/sandbox-configs/:id"},
{http.MethodGet, "/api/v1/sandbox-configs/:id/sandboxes"},
+ {http.MethodGet, "/api/v1/sandbox-configs/:id/user-sandboxes"},
+ {http.MethodPost, "/api/v1/sandbox-configs/:id/user-sandboxes/:digest/release"},
{http.MethodGet, "/api/v1/sandbox-configs/:id/skills"},
{http.MethodPost, "/api/v1/sandbox-configs/:id/skills"},
{http.MethodGet, "/api/v1/sandbox-configs/:id/skills/:skillId"},
diff --git a/internal/router/routes_infra.go b/internal/router/routes_infra.go
index 90af757b3..39daae42b 100644
--- a/internal/router/routes_infra.go
+++ b/internal/router/routes_infra.go
@@ -67,6 +67,8 @@ func RegisterSandboxConfigRoutes(
configs.PUT("/:id", g.Admin(), h.Update)
configs.DELETE("/:id", g.Admin(), h.Delete)
configs.GET("/:id/sandboxes", g.Admin(), h.Inventory)
+ configs.GET("/:id/user-sandboxes", g.Admin(), h.ListUserSandboxes)
+ configs.POST("/:id/user-sandboxes/:digest/release", g.Admin(), h.ReleaseUserSandbox)
// Skills are Admin+ throughout, reads included: an upload drives a
// root shell whose output is baked into the image every session of
// this config boots, and the listing names what that image carries.
diff --git a/internal/sandbox/admission/admission.go b/internal/sandbox/admission/admission.go
index 7b3eda38c..f2e5123ae 100644
--- a/internal/sandbox/admission/admission.go
+++ b/internal/sandbox/admission/admission.go
@@ -12,6 +12,7 @@ package admission
import (
"context"
"errors"
+ "strconv"
"sync"
"time"
)
@@ -43,6 +44,13 @@ func SessionScope(digest, sessionID string) Scope {
return Scope{Tag: digest, Name: "session:" + sessionID}
}
+// ConfigCreateScope registers provider creates of one sandbox config, so a
+// config deletion can stop new creates and wait for running ones before it
+// takes inventory.
+func ConfigCreateScope(configTenantID uint64, configID string) Scope {
+ return Scope{Tag: "config:" + strconv.FormatUint(configTenantID, 10) + ":" + configID, Name: "create"}
+}
+
// SessionMember names one operation of sessionID: kind is "turn", "shell",
// "file", "exec", "pty", "desktop", "fork" or "cleanup". token is unique per
// hold — including turns, which may nest — so releasing one hold never
@@ -72,8 +80,13 @@ type Lease interface {
// Barrier is an exclusive close of a scope.
type Barrier interface {
Signal
- // Release reopens the scope. Idempotent.
+ // Release reopens the scope. Idempotent, and exclusive with Seal:
+ // whichever runs first wins.
Release()
+ // Seal stops renewal and leaves the scope closed. It does not remove
+ // the closed flag, so new creates of this scope stay refused. Idempotent,
+ // and exclusive with Release.
+ Seal()
}
// Bind returns a context cancelled with ErrLeaseLost as soon as any of
@@ -121,10 +134,13 @@ type Registry interface {
// signal is the shared Lost/deadline/Release bookkeeping of leases and
// barriers. A zero deadline (the memory registry) never expires on its own.
type signal struct {
- lost chan struct{}
- lostOnce sync.Once
- releaseOnce sync.Once
- release func()
+ lost chan struct{}
+ lostOnce sync.Once
+ finishOnce sync.Once
+ release func()
+ // seal stops renewal without reopening. Nil on a memory barrier: the
+ // scope stays in the barrier map.
+ seal func()
mu sync.Mutex
deadline time.Time
@@ -220,8 +236,14 @@ func (s *signal) currentDeadline() time.Time {
return s.deadline
}
-func (s *signal) Release() {
- s.releaseOnce.Do(func() {
+func (s *signal) Release() { s.finish(true) }
+
+// Seal stops the local deadline timer the same way Release does, so it
+// cannot mark the barrier lost, and runs the non-reopening callback.
+func (b *barrier) Seal() { b.finish(false) }
+
+func (s *signal) finish(reopen bool) {
+ s.finishOnce.Do(func() {
s.mu.Lock()
s.stopped = true
if s.timer != nil {
@@ -229,8 +251,14 @@ func (s *signal) Release() {
s.timer = nil
}
s.mu.Unlock()
- if s.release != nil {
- s.release()
+ if reopen {
+ if s.release != nil {
+ s.release()
+ }
+ return
+ }
+ if s.seal != nil {
+ s.seal()
}
})
}
@@ -241,6 +269,11 @@ func (s *signal) Check() error {
if s.lostClosed() {
return ErrLeaseLost
}
+ // Release and Seal both stop the deadline. A stopped signal is not a
+ // loss, even if the old deadline has since passed.
+ if s.stopped {
+ return nil
+ }
if d := s.deadline; !d.IsZero() && !time.Now().Before(d) {
s.closeLostLocked()
return ErrLeaseLost
diff --git a/internal/sandbox/admission/admission_test.go b/internal/sandbox/admission/admission_test.go
index abad82ccc..7f2b159a7 100644
--- a/internal/sandbox/admission/admission_test.go
+++ b/internal/sandbox/admission/admission_test.go
@@ -351,3 +351,46 @@ func TestRedisShortHoldNeverShortensALongerLease(t *testing.T) {
require.NoError(t, err)
require.Equal(t, 1, n, "the long lease is still registered")
}
+
+func TestSealKeepsTheScopeClosedWithoutReportingLoss(t *testing.T) {
+ ctx := context.Background()
+ scope := ConfigCreateScope(7, "cfg-a")
+
+ t.Run("memory", func(t *testing.T) {
+ reg := NewMemory()
+ barrier, err := reg.Close(ctx, scope, time.Minute)
+ require.NoError(t, err)
+ barrier.Seal()
+ barrier.Seal()
+ _, err = reg.Hold(ctx, scope, "create:again", time.Minute)
+ require.ErrorIs(t, err, ErrClosed)
+ _, err = reg.Close(ctx, scope, time.Minute)
+ require.ErrorIs(t, err, ErrClosed)
+ select {
+ case <-barrier.Lost():
+ t.Fatal("seal must not report the barrier lost")
+ default:
+ }
+ require.NoError(t, barrier.Check())
+ })
+
+ t.Run("redis", func(t *testing.T) {
+ reg, mini := newRedis(t)
+ barrier, err := reg.Close(ctx, scope, 300*time.Millisecond)
+ require.NoError(t, err)
+ barrier.Seal()
+ time.Sleep(400 * time.Millisecond)
+ mini.FastForward(time.Second)
+ key := prefix + "{config:7:cfg-a}:create:closed"
+ require.True(t, mini.Exists(key), "seal persists the closed flag past its TTL")
+ require.Equal(t, time.Duration(0), mini.TTL(key))
+ _, err = reg.Hold(ctx, scope, "create:again", time.Minute)
+ require.ErrorIs(t, err, ErrClosed)
+ select {
+ case <-barrier.Lost():
+ t.Fatal("seal must not report the barrier lost")
+ default:
+ }
+ require.NoError(t, barrier.Check())
+ })
+}
diff --git a/internal/sandbox/admission/redis.go b/internal/sandbox/admission/redis.go
index 05e544a12..97f6e572e 100644
--- a/internal/sandbox/admission/redis.go
+++ b/internal/sandbox/admission/redis.go
@@ -157,13 +157,9 @@ func (r *RedisRegistry) Close(ctx context.Context, scope Scope, ttl time.Duratio
b := &barrier{signal: newSignal()}
b.extend(sent, ttl)
renewCtx, stop := context.WithCancel(context.WithoutCancel(ctx))
- b.release = func() {
- stop()
- relCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
- defer cancel()
- _, _ = redislock.Release(relCtx, r.client, key, token)
- }
+ renewDone := make(chan struct{})
go func() {
+ defer close(renewDone)
ticker := time.NewTicker(renewInterval(ttl))
defer ticker.Stop()
for {
@@ -187,6 +183,21 @@ func (r *RedisRegistry) Close(ctx context.Context, scope Scope, ttl time.Duratio
}
}
}()
+ // Wait for the renewal goroutine to leave before touching the key, so a
+ // PEXPIRE cannot land after PERSIST and put the TTL back.
+ finishKey := func(persist bool) {
+ stop()
+ <-renewDone
+ relCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ if persist {
+ _ = r.client.Persist(relCtx, key).Err()
+ return
+ }
+ _, _ = redislock.Release(relCtx, r.client, key, token)
+ }
+ b.release = func() { finishKey(false) }
+ b.seal = func() { finishKey(true) }
return b, nil
}
diff --git a/internal/sandbox/admission/redis_integration_test.go b/internal/sandbox/admission/redis_integration_test.go
new file mode 100644
index 000000000..699edc8ae
--- /dev/null
+++ b/internal/sandbox/admission/redis_integration_test.go
@@ -0,0 +1,139 @@
+package admission_test
+
+import (
+ "os"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/redis/go-redis/v9"
+ "github.com/stretchr/testify/require"
+
+ "github.com/Tencent/WeKnora/internal/sandbox/admission"
+)
+
+// integrationEnv returns an integration dependency's address. Missing, the
+// test is skipped — unless WEKNORA_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("WEKNORA_REQUIRE_INTEGRATION") == "1" {
+ t.Fatalf("%s is required when WEKNORA_REQUIRE_INTEGRATION=1", name)
+ }
+ t.Skipf("set %s to run against a real dependency", name)
+ return ""
+}
+
+// realRedisPair dials WEKNORA_TEST_REDIS_ADDR twice. prefix isolates this run.
+func realRedisPair(t *testing.T) (c1, c2 *admission.RedisRegistry, raw *redis.Client, prefix string) {
+ t.Helper()
+ addr := integrationEnv(t, "WEKNORA_TEST_REDIS_ADDR")
+ prefix = "it-" + uuid.NewString() + ":"
+ open := func() *redis.Client {
+ rc := redis.NewClient(&redis.Options{Addr: addr})
+ t.Cleanup(func() { _ = rc.Close() })
+ return rc
+ }
+ left, right := open(), open()
+ raw = open()
+ return admission.NewRedis(left, prefix), admission.NewRedis(right, prefix), raw, prefix
+}
+
+// redisKey is RedisRegistry's key layout. The method is unexported; the
+// integration test builds the same string so it can inject faults.
+func redisKey(prefix string, scope admission.Scope, suffix string) string {
+ return prefix + "{" + scope.Tag + "}:" + scope.Name + ":" + suffix
+}
+
+func TestRedisRealTwoClientsShareAdmission(t *testing.T) {
+ c1, c2, _, _ := realRedisPair(t)
+ ctx := t.Context()
+ scope := admission.MachineScope("d-" + uuid.NewString())
+ member := "s:a:pty:1"
+
+ lease, err := c1.Hold(ctx, scope, member, time.Minute)
+ require.NoError(t, err)
+ defer lease.Release()
+
+ barrier, err := c2.Close(ctx, scope, time.Minute)
+ require.NoError(t, err)
+ defer barrier.Release()
+
+ n, err := c2.ActiveExcept(ctx, scope)
+ require.NoError(t, err)
+ require.Equal(t, 1, n)
+
+ lease.Release()
+ n, err = c2.ActiveExcept(ctx, scope)
+ require.NoError(t, err)
+ require.Zero(t, n)
+
+ _, err = c1.Hold(ctx, scope, "s:a:pty:2", time.Minute)
+ require.ErrorIs(t, err, admission.ErrClosed)
+
+ barrier.Release()
+ again, err := c1.Hold(ctx, scope, "s:a:pty:3", time.Minute)
+ require.NoError(t, err)
+ again.Release()
+}
+
+func TestRedisRealBarrierIsRenewedAndLossIsReported(t *testing.T) {
+ c1, c2, raw, prefix := realRedisPair(t)
+ ctx := t.Context()
+ scope := admission.MachineScope("d-" + uuid.NewString())
+ ttl := 2 * time.Second
+
+ barrier, err := c2.Close(ctx, scope, ttl)
+ require.NoError(t, err)
+ defer barrier.Release()
+
+ time.Sleep(3 * time.Second)
+ require.NoError(t, barrier.Check(), "a held barrier is renewed past its initial TTL")
+
+ closedKey := redisKey(prefix, scope, "closed")
+ require.NoError(t, raw.Del(ctx, closedKey).Err())
+
+ select {
+ case <-barrier.Lost():
+ require.ErrorIs(t, barrier.Check(), admission.ErrLeaseLost)
+ case <-time.After(ttl):
+ t.Fatal("the barrier kept reporting ownership after its key was deleted")
+ }
+
+ again, err := c1.Close(ctx, scope, time.Minute)
+ require.NoError(t, err, "a lost barrier does not keep the scope closed")
+ again.Release()
+}
+
+func TestRedisRealLostMemberIsNotResurrected(t *testing.T) {
+ c1, _, raw, prefix := realRedisPair(t)
+ ctx := t.Context()
+ scope := admission.MachineScope("d-" + uuid.NewString())
+ member := admission.SessionMember("s", "shell", "1")
+ ttl := 2 * time.Second
+
+ lease, err := c1.Hold(ctx, scope, member, ttl)
+ require.NoError(t, err)
+ defer lease.Release()
+
+ opsKey := redisKey(prefix, scope, "ops")
+ require.NoError(t, raw.ZRem(ctx, opsKey, member).Err())
+
+ // Renewal ticks every ttl/3. Wait past one tick, and past the ttl/6
+ // margin, so a loop that put the member back would be visible.
+ select {
+ case <-lease.Lost():
+ case <-time.After(ttl):
+ t.Fatal("a removed member was not reported lost")
+ }
+ time.Sleep(ttl/3 + 100*time.Millisecond)
+
+ _, err = raw.ZScore(ctx, opsKey, member).Result()
+ require.ErrorIs(t, err, redis.Nil, "renewal must not resurrect a removed member")
+ require.ErrorIs(t, lease.Check(), admission.ErrLeaseLost)
+}
diff --git a/internal/sandbox/cube_remote_client.go b/internal/sandbox/cube_remote_client.go
index e5ac26e7f..158bfc26a 100644
--- a/internal/sandbox/cube_remote_client.go
+++ b/internal/sandbox/cube_remote_client.go
@@ -1388,6 +1388,13 @@ func normalizeCubeError(op string, err error) error {
kind = RemoteErrorKindUnavailable
}
}
+ // Cube's file List wraps a missing path as a plain error ("path not
+ // found" / "no such file"), not NotFoundError. A new session on a shared
+ // machine has no directory yet; listing it must stay NotFound so callers
+ // can treat the tree as empty instead of failing the turn.
+ if kind == RemoteErrorKindInternal && op == "ListDir" && isSDKNotFound(err) {
+ kind = RemoteErrorKindNotFound
+ }
kind = snapshotDeleteKind(op, kind, err.Error())
remoteErr := NewRemoteError(SandboxTypeCube, op, kind, err.Error(), err)
remoteErr.StatusCode = status
diff --git a/internal/sandbox/cube_remote_client_test.go b/internal/sandbox/cube_remote_client_test.go
index 2f25af607..03f9ad524 100644
--- a/internal/sandbox/cube_remote_client_test.go
+++ b/internal/sandbox/cube_remote_client_test.go
@@ -642,6 +642,10 @@ func TestNormalizeCubeError(t *testing.T) {
{"template not found", "Create", cubesandbox.ErrTemplateNotFound, RemoteErrorKindInvalidRequest},
{"authentication", "Health", cubesandbox.ErrAuthentication, RemoteErrorKindAuthentication},
{"path not found", "Stat", &cubesandbox.NotFoundError{Path: "/x"}, RemoteErrorKindNotFound},
+ {"list missing session dir", "ListDir", errors.New(
+ "failed to list /workspace/sessions/f2e82fcb-abf8-4677-9567-5e20d6cbcb1f/input: " +
+ "path not found: lstat /workspace/sessions/f2e82fcb-abf8-4677-9567-5e20d6cbcb1f: " +
+ "no such file or directory"), RemoteErrorKindNotFound},
{"gone", "Get", &cubesandbox.APIError{StatusCode: http.StatusGone}, RemoteErrorKindTerminal},
{"conflict", "Connect", &cubesandbox.APIError{StatusCode: http.StatusConflict}, RemoteErrorKindConflict},
{"rate limited", "Create", &cubesandbox.APIError{StatusCode: http.StatusTooManyRequests}, RemoteErrorKindCapacity},
diff --git a/internal/sandbox/docker_integration_test.go b/internal/sandbox/docker_integration_test.go
index d968d125b..56f178b99 100644
--- a/internal/sandbox/docker_integration_test.go
+++ b/internal/sandbox/docker_integration_test.go
@@ -23,14 +23,20 @@ import (
"fmt"
"os"
"path"
+ "regexp"
"strings"
"sync"
"testing"
"time"
+ cerrdefs "github.com/containerd/errdefs"
+ "github.com/google/uuid"
"github.com/moby/moby/api/types/container"
"github.com/moby/moby/client"
+ "github.com/redis/go-redis/v9"
+ "github.com/Tencent/WeKnora/internal/sandbox/admission"
+ "github.com/Tencent/WeKnora/internal/sandbox/allocation"
"github.com/Tencent/WeKnora/internal/types"
)
@@ -38,10 +44,7 @@ const dockerIntegrationTenantID = 1
func dockerIntegrationConfig(t *testing.T) *Config {
t.Helper()
- image := strings.TrimSpace(os.Getenv("DOCKER_INTEGRATION_IMAGE"))
- if image == "" {
- t.Skip("DOCKER_INTEGRATION_IMAGE is required for the docker conformance suite")
- }
+ image := integrationEnv(t, "DOCKER_INTEGRATION_IMAGE")
cfg := DefaultConfig()
cfg.Type = SandboxTypeDocker
cfg.DockerImage = image
@@ -63,6 +66,9 @@ func newDockerIntegrationManager(t *testing.T, cfg *Config) *SessionBoundManager
probeCtx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
if err := client.Health(probeCtx); err != nil {
+ if os.Getenv("WEKNORA_REQUIRE_INTEGRATION") == "1" {
+ t.Fatalf("docker daemon unreachable: %v", err)
+ }
t.Skipf("docker daemon unreachable: %v", err)
}
manager, err := NewSessionBoundManager(SessionBoundManagerConfig{
@@ -586,6 +592,9 @@ func TestDockerSkillSnapshotIntegration(t *testing.T) {
probeCtx, cancelProbe := context.WithTimeout(context.Background(), 15*time.Second)
defer cancelProbe()
if err := client.Health(probeCtx); err != nil {
+ if os.Getenv("WEKNORA_REQUIRE_INTEGRATION") == "1" {
+ t.Fatalf("docker daemon unreachable: %v", err)
+ }
t.Skipf("docker daemon unreachable: %v", err)
}
if !client.Capabilities().SupportsSnapshots {
@@ -1050,3 +1059,285 @@ func terminalProbeJobAlive(
`n=0; for p in /proc/[0-9]*; do cmd=$(tr '\0' ' ' < "$p/cmdline" 2>/dev/null); case "$cmd" in "`+jobCmd+` "*) n=$((n+1));; esac; done; echo $n`)
return strings.TrimSpace(out) != "0"
}
+
+func dockerUserAssignment(sessionID string) allocation.Assignment {
+ return allocation.Assignment{
+ SessionID: sessionID, ConfigTenantID: dockerIntegrationTenantID, ConfigID: "docker-conformance",
+ Machine: allocation.UserMachine{
+ OwnerTenantID: dockerIntegrationTenantID, OwnerID: "docker-user",
+ ConfigTenantID: dockerIntegrationTenantID, ConfigID: "docker-conformance",
+ },
+ }
+}
+
+func dockerShellQuote(s string) string {
+ return "'" + strings.ReplaceAll(s, "'", `'"'"'`) + "'"
+}
+
+// dockerGitWorkspaceVars matches gitWorkspaceVars for a shared-machine layout.
+// checkpointScriptFor and workspaceResetScriptFor live in application/service,
+// which this package cannot import.
+func dockerGitWorkspaceVars(root, gitDir string) string {
+ return fmt.Sprintf(`WORK_TREE=%s
+GIT_DIR=%s
+git_ws() {
+ git -c safe.directory='*' --git-dir="$GIT_DIR" --work-tree="$WORK_TREE" "$@"
+}
+mkdir -p "$WORK_TREE"
+`, dockerShellQuote(root), dockerShellQuote(gitDir))
+}
+
+func dockerCheckpointScript(l WorkspaceLayout, messageID string) string {
+ return fmt.Sprintf(`set -e
+%s
+git_ws rev-parse --git-dir >/dev/null 2>&1 || {
+ mkdir -p "$(dirname "$GIT_DIR")"
+ git_ws init -q
+ git_ws config user.email [email protected]
+ git_ws config user.name 'WeKnora Agent'
+}
+git_ws add -A
+git_ws commit -q --allow-empty -m 'turn:%s'
+git_ws rev-parse HEAD`, dockerGitWorkspaceVars(l.Root, l.GitDir), messageID)
+}
+
+func dockerResetScript(l WorkspaceLayout, sha string) string {
+ return "set -e\n" + dockerGitWorkspaceVars(l.Root, l.GitDir) +
+ fmt.Sprintf("git_ws cat-file -e \"%s^{commit}\" 2>/dev/null || exit 3\n", sha) +
+ "git_ws reset --hard " + sha + "\n" +
+ `current=$(git_ws symbolic-ref -q HEAD || true)
+for ref in $(git_ws for-each-ref --format='%(refname)'); do
+ [ -z "$ref" ] && continue
+ [ "$ref" = "$current" ] && continue
+ git_ws update-ref -d "$ref"
+done
+rm -f "$GIT_DIR"/ORIG_HEAD "$GIT_DIR"/FETCH_HEAD
+git_ws reflog expire --expire=now --all
+git_ws gc --prune=now
+git_ws clean -fdx
+`
+}
+
+func dockerUserShell(t *testing.T, ctx context.Context, mgr *SessionBoundManager, sessionID, command string) *ExecuteResult {
+ t.Helper()
+ result, err := mgr.ExecShellCommand(ctx, sessionID, command, "", time.Minute, nil)
+ if err != nil {
+ t.Fatalf("ExecShellCommand %s: %v", sessionID, err)
+ }
+ if result == nil {
+ t.Fatalf("ExecShellCommand %s returned no result", sessionID)
+ }
+ return result
+}
+
+func dockerLastLine(stdout string) string {
+ lines := strings.Split(strings.TrimSpace(stdout), "\n")
+ if len(lines) == 0 {
+ return ""
+ }
+ return strings.TrimSpace(lines[len(lines)-1])
+}
+
+func requireDockerContainerGone(t *testing.T, ctx context.Context, id string) {
+ t.Helper()
+ api, err := sharedDockerEngineClients.get(dockerEndpoint{
+ Host: strings.TrimSpace(os.Getenv("DOCKER_INTEGRATION_HOST")),
+ Timeout: DefaultDockerHTTPTimeout,
+ })
+ if err != nil {
+ t.Fatalf("docker client: %v", err)
+ }
+ _, err = api.ContainerInspect(ctx, id, client.ContainerInspectOptions{})
+ if err == nil {
+ t.Fatalf("container %s still exists after reclaim", id)
+ }
+ if !cerrdefs.IsNotFound(err) {
+ t.Fatalf("docker inspect %s: %v", id, err)
+ }
+}
+
+func TestDockerUserMachineSharesContainerAndIsolatesDirectories(t *testing.T) {
+ cfg := dockerIntegrationConfig(t)
+ redisAddr := integrationEnv(t, "WEKNORA_TEST_REDIS_ADDR")
+ remote, err := NewDockerRemoteClient(cfg)
+ if err != nil {
+ t.Fatalf("build docker client: %v", err)
+ }
+ remote.sweeper = nil
+ probeCtx, cancelProbe := context.WithTimeout(context.Background(), 15*time.Second)
+ defer cancelProbe()
+ if err := remote.Health(probeCtx); err != nil {
+ if os.Getenv("WEKNORA_REQUIRE_INTEGRATION") == "1" {
+ t.Fatalf("docker daemon unreachable: %v", err)
+ }
+ t.Skipf("docker daemon unreachable: %v", err)
+ }
+
+ sessionA, sessionB, sessionC := uuid.NewString(), uuid.NewString(), uuid.NewString()
+ ns := "weknora-it-" + uuid.NewString()[:8]
+ rc := redis.NewClient(&redis.Options{Addr: redisAddr})
+ t.Cleanup(func() { _ = rc.Close() })
+ store, err := NewRedisSessionSandboxBindingStore(rc, ns)
+ if err != nil {
+ t.Fatalf("binding store: %v", err)
+ }
+ allocs := newFakeAllocations(
+ dockerUserAssignment(sessionA), dockerUserAssignment(sessionB), dockerUserAssignment(sessionC),
+ )
+ mgr, err := NewSessionBoundManager(SessionBoundManagerConfig{
+ Config: cfg, Client: remote, Store: store,
+ Checker: PermissiveSessionExistenceChecker{}, SkipHealthProbe: true,
+ ConfigID: "docker-conformance", ConfigTenantID: dockerIntegrationTenantID,
+ Allocations: allocs, Admission: admission.NewRedis(rc, "weknora:sandbox:user:"),
+ Namespace: ns,
+ })
+ if err != nil {
+ t.Fatalf("NewSessionBoundManager: %v", err)
+ }
+
+ ctx, cancel := context.WithTimeout(
+ types.WithSandboxTenantID(context.Background(), dockerIntegrationTenantID),
+ 8*time.Minute,
+ )
+ defer cancel()
+ machine, ok := dockerUserAssignment(sessionA).UserMachine()
+ if !ok {
+ t.Fatal("user assignment has no machine")
+ }
+ var releaseHold func()
+ t.Cleanup(func() {
+ if releaseHold != nil {
+ releaseHold()
+ }
+ cleanupCtx, cleanupCancel := context.WithTimeout(
+ types.WithSandboxTenantID(context.Background(), dockerIntegrationTenantID),
+ time.Minute,
+ )
+ defer cleanupCancel()
+ _, _ = mgr.ReclaimUserMachine(cleanupCtx, machine, func(context.Context) (bool, error) { return true, nil })
+ })
+
+ layoutA, err := UserWorkspaceLayout(sessionA)
+ if err != nil {
+ t.Fatal(err)
+ }
+ layoutB, err := UserWorkspaceLayout(sessionB)
+ if err != nil {
+ t.Fatal(err)
+ }
+ layoutC, err := UserWorkspaceLayout(sessionC)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ wrote := dockerUserShell(t, ctx, mgr, sessionA, "echo a > note.txt && cat note.txt")
+ if wrote.ExitCode != 0 || strings.TrimSpace(wrote.Stdout) != "a" {
+ t.Fatalf("seed A: %#v", wrote)
+ }
+ missing := dockerUserShell(t, ctx, mgr, sessionB, "cat note.txt || echo missing")
+ if missing.ExitCode != 0 || !strings.Contains(missing.Stdout, "missing") {
+ t.Fatalf("B should not see A's note: %#v", missing)
+ }
+ idA, okA := mgr.BoundSandboxID(ctx, sessionA)
+ idB, okB := mgr.BoundSandboxID(ctx, sessionB)
+ if !okA || !okB || idA == "" || idA != idB {
+ t.Fatalf("sessions do not share one sandbox: A=%q (%v) B=%q (%v)", idA, okA, idB, okB)
+ }
+ side := dockerUserShell(t, ctx, mgr, sessionB, "echo b-side > "+dockerShellQuote(layoutB.Root+"/keep.txt")+" && cat keep.txt")
+ if side.ExitCode != 0 || strings.TrimSpace(side.Stdout) != "b-side" {
+ t.Fatalf("seed B: %#v", side)
+ }
+
+ checkpoint := dockerUserShell(t, ctx, mgr, sessionA, dockerCheckpointScript(layoutA, "m1"))
+ sha := dockerLastLine(checkpoint.Stdout)
+ if checkpoint.ExitCode != 0 || !regexp.MustCompile(`^[0-9a-f]{40}$`).MatchString(sha) {
+ t.Fatalf("checkpoint: sha=%q %#v", sha, checkpoint)
+ }
+ more := dockerUserShell(t, ctx, mgr, sessionA, "echo more >> note.txt && cat note.txt")
+ if more.ExitCode != 0 || !strings.Contains(more.Stdout, "more") {
+ t.Fatalf("write after checkpoint: %#v", more)
+ }
+ reset := dockerUserShell(t, ctx, mgr, sessionA, dockerResetScript(layoutA, sha))
+ if reset.ExitCode != 0 {
+ t.Fatalf("reset to checkpoint: %#v", reset)
+ }
+ restored := dockerUserShell(t, ctx, mgr, sessionA, "cat note.txt")
+ if strings.TrimSpace(restored.Stdout) != "a" {
+ t.Fatalf("A was not restored: %#v", restored)
+ }
+ kept := dockerUserShell(t, ctx, mgr, sessionB, "cat "+dockerShellQuote(layoutB.Root+"/keep.txt"))
+ if strings.TrimSpace(kept.Stdout) != "b-side" {
+ t.Fatalf("B's files changed: %#v", kept)
+ }
+ missingSHA := strings.Repeat("f", 40)
+ if missingSHA == sha {
+ missingSHA = strings.Repeat("e", 40)
+ }
+ absent := dockerUserShell(t, ctx, mgr, sessionA, dockerResetScript(layoutA, missingSHA))
+ if absent.ExitCode != 3 {
+ t.Fatalf("missing commit exit=%d, want 3: %#v", absent.ExitCode, absent)
+ }
+ untouched := dockerUserShell(t, ctx, mgr, sessionA, "cat note.txt")
+ if strings.TrimSpace(untouched.Stdout) != "a" {
+ t.Fatalf("a missing commit changed A: %#v", untouched)
+ }
+
+ fork, err := mgr.BeginWorkspaceFork(ctx, sessionA)
+ if err != nil {
+ t.Fatalf("BeginWorkspaceFork: %v", err)
+ }
+ reachable, err := fork.Copy(sessionC, sha, []string{sha})
+ if err != nil {
+ fork.Release()
+ t.Fatalf("Copy: %v", err)
+ }
+ if !reachable[sha] {
+ fork.Release()
+ t.Fatalf("SHA not reachable: %#v", reachable)
+ }
+ fork.Release()
+ copied := dockerUserShell(t, ctx, mgr, sessionC, "cat note.txt")
+ if strings.TrimSpace(copied.Stdout) != "a" {
+ t.Fatalf("C did not receive note.txt: %#v", copied)
+ }
+ catFile := dockerUserShell(t, ctx, mgr, sessionC, fmt.Sprintf(
+ "git --git-dir=%s cat-file -e %s", dockerShellQuote(layoutC.GitDir), dockerShellQuote(sha+"^{commit}"),
+ ))
+ if catFile.ExitCode != 0 {
+ t.Fatalf("C.git does not contain the commit: %#v", catFile)
+ }
+
+ deleted, err := mgr.DeleteSessionWorkspaces(ctx, machine, []string{sessionA})
+ if err != nil {
+ t.Fatalf("DeleteSessionWorkspaces: %v", err)
+ }
+ if len(deleted) != 1 || deleted[0] != sessionA {
+ t.Fatalf("deleted %v, want [%s]", deleted, sessionA)
+ }
+ gone := dockerUserShell(t, ctx, mgr, sessionB, fmt.Sprintf(
+ "if [ -e %s ] || [ -e %s ]; then echo a-remains; else echo a-gone; fi; cat keep.txt",
+ dockerShellQuote(layoutA.Root), dockerShellQuote(layoutA.GitDir),
+ ))
+ if gone.ExitCode != 0 || !strings.Contains(gone.Stdout, "a-gone") || !strings.Contains(gone.Stdout, "b-side") {
+ t.Fatalf("A should be gone and B intact: %#v", gone)
+ }
+
+ _, releaseHold, err = mgr.HoldSessionOperation(ctx, sessionB, "pty")
+ if err != nil {
+ t.Fatalf("HoldSessionOperation: %v", err)
+ }
+ reclaimed, err := mgr.ReclaimUserMachine(ctx, machine, func(context.Context) (bool, error) { return true, nil })
+ if err != nil {
+ t.Fatalf("reclaim while held: %v", err)
+ }
+ if reclaimed {
+ t.Fatal("an open terminal must block reclaim")
+ }
+ releaseHold()
+ releaseHold = nil
+ reclaimed, err = mgr.ReclaimUserMachine(ctx, machine, func(context.Context) (bool, error) { return true, nil })
+ if err != nil || !reclaimed {
+ t.Fatalf("reclaim after release: ok=%v err=%v", reclaimed, err)
+ }
+ requireDockerContainerGone(t, ctx, idA)
+}
diff --git a/internal/sandbox/remote_fake_test.go b/internal/sandbox/remote_fake_test.go
index f0991ddbe..bf7989b9a 100644
--- a/internal/sandbox/remote_fake_test.go
+++ b/internal/sandbox/remote_fake_test.go
@@ -94,6 +94,7 @@ type fakeRemoteClient struct {
createHook func(context.Context, RemoteCreateRequest) error
afterCreate func(RemoteSandboxHandle)
deleteHook func(context.Context, string) error
+ execHook func(RemoteExecRequest) (*RemoteExecResult, error)
makeDirPaths []string
failMakeDirIfExists bool
@@ -107,6 +108,10 @@ type fakeRemoteClient struct {
// ptyClosed is set when a fake PTY opened on this client is closed.
ptyClosed atomic.Bool
+ // terminalOptions records OpenTerminal arguments so tests can see the
+ // options the manager actually passed through.
+ terminalOptions []RemoteTerminalOptions
+
// openTerminalHook, when set, runs instead of opening immediately. It
// sees the context the manager passed, so a test can block the dial
// until that context is cancelled.
@@ -335,6 +340,9 @@ func (c *fakeRemoteClient) Exec(
c.mu.Lock()
c.execRequests = append(c.execRequests, request)
c.mu.Unlock()
+ if c.execHook != nil {
+ return c.execHook(request)
+ }
return &RemoteExecResult{ExitCode: 0}, nil
}
@@ -458,6 +466,23 @@ func (c *fakeRemoteClient) addSandbox(
}
}
+// addSandboxWithMetadata registers a running sandbox that already carries
+// metadata, the way a failed create can leave a duplicate behind.
+func (c *fakeRemoteClient) addSandboxWithMetadata(metadata map[string]string) string {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ c.nextID++
+ id := fmt.Sprintf("%s-%d", c.provider, c.nextID)
+ c.sandboxes[id] = &fakeRemoteRecord{
+ id: id,
+ state: RemoteStateRunning,
+ rawState: string(RemoteStateRunning),
+ metadata: cloneStringMap(metadata),
+ startedAt: time.Now().UTC(),
+ }
+ return id
+}
+
func (c *fakeRemoteClient) counts() (creates, connects, gets, lists, deletes int) {
c.mu.Lock()
defer c.mu.Unlock()
@@ -465,16 +490,28 @@ func (c *fakeRemoteClient) counts() (creates, connects, gets, lists, deletes int
}
func (c *fakeRemoteClient) OpenTerminal(
- ctx context.Context, _ RemoteSandboxHandle, _ RemoteTerminalOptions,
+ ctx context.Context, _ RemoteSandboxHandle, opts RemoteTerminalOptions,
) (RemoteTerminalSession, error) {
if c.openTerminalHook != nil {
if err := c.openTerminalHook(ctx); err != nil {
return nil, err
}
}
+ c.mu.Lock()
+ c.terminalOptions = append(c.terminalOptions, opts)
+ c.mu.Unlock()
return &fakeRemoteTerminal{client: c}, nil
}
+func (c *fakeRemoteClient) lastTerminalOptions() RemoteTerminalOptions {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if len(c.terminalOptions) == 0 {
+ return RemoteTerminalOptions{}
+ }
+ return c.terminalOptions[len(c.terminalOptions)-1]
+}
+
func (c *fakeRemoteClient) terminalClosed() bool { return c.ptyClosed.Load() }
// fakeRemoteTerminal is the PTY the shared fake opens. Close records that
diff --git a/internal/sandbox/session_lifecycle.go b/internal/sandbox/session_lifecycle.go
index 020a5cd5c..09925ace4 100644
--- a/internal/sandbox/session_lifecycle.go
+++ b/internal/sandbox/session_lifecycle.go
@@ -10,6 +10,7 @@ import (
"strings"
"time"
+ "github.com/Tencent/WeKnora/internal/common/redislock"
"github.com/Tencent/WeKnora/internal/sandbox/admission"
"github.com/Tencent/WeKnora/internal/sandbox/allocation"
"github.com/Tencent/WeKnora/internal/types"
@@ -63,6 +64,11 @@ type remoteSessionLifecycle struct {
// shared user machines; user keys are refused without them.
namespace string
admission admission.Registry
+
+ // createGate registers every provider Create on the config (C13). Nil
+ // means creates are not registered.
+ createGate admission.Registry
+ configTenantID uint64
}
type lifecycleOption func(*remoteSessionLifecycle)
@@ -75,6 +81,14 @@ func withUserMachines(namespace string, reg admission.Registry) lifecycleOption
}
}
+// withConfigCreateGate makes every provider Create register with the
+// config first (C13). Without a registry creates are not registered.
+func withConfigCreateGate(reg admission.Registry, configTenantID uint64) lifecycleOption {
+ return func(l *remoteSessionLifecycle) {
+ l.createGate, l.configTenantID = reg, configTenantID
+ }
+}
+
func newRemoteSessionLifecycle(
client RemoteSandboxClient,
bindings SessionSandboxBindingStore,
@@ -410,6 +424,20 @@ func (l *remoteSessionLifecycle) missingRequiredInboundToken(handle RemoteSandbo
func (l *remoteSessionLifecycle) recoverOwnedSandbox(
ctx context.Context,
key SessionSandboxKey,
+) (RemoteSandboxHandle, bool, error) {
+ return l.recoverOwned(ctx, key, false)
+}
+
+// recoverOwned lists key's machine and binds it again. keepUnusable is the
+// directory-cleanup path: it returns a user machine even when the inbound
+// token is gone, so the cleanup command can run, and does not bind it.
+// A normal resolve of a tokenless user machine returns an error instead of
+// deleting it or creating another. A tokenless per-session sandbox is still
+// deleted, because that machine belongs to the one session.
+func (l *remoteSessionLifecycle) recoverOwned(
+ ctx context.Context,
+ key SessionSandboxKey,
+ keepUnusable bool,
) (RemoteSandboxHandle, bool, error) {
capabilities := l.client.Capabilities()
if !capabilities.SupportsMetadata || !capabilities.SupportsListSandboxes {
@@ -468,6 +496,21 @@ func (l *remoteSessionLifecycle) recoverOwnedSandbox(
// empty token there means "not applicable" rather than "lost" — and
// destroying a healthy container over it would cost /workspace on
// every binding loss.
+ if l.missingRequiredInboundToken(handle) && key.IsUserMachine() {
+ // Deleting a shared machine takes every sibling session's files,
+ // and binding the empty token wedges every later call: the
+ // provider issued it only at create time, and an authentication
+ // error is not replaceable. Directory cleanup still needs the
+ // handle for its one command. A normal resolve stops here so it
+ // neither deletes this machine nor starts another.
+ if keepUnusable {
+ return handle, true, nil
+ }
+ return nil, false, fmt.Errorf(
+ "adopt user machine %s: inbound traffic token missing under a closed-inbound policy",
+ summary.ID,
+ )
+ }
if l.missingRequiredInboundToken(handle) {
// Deleting rather than walking away is safe for the same reason
// cleanupOwnedDuplicates below is: this loop holds the lifecycle
@@ -524,10 +567,92 @@ func (l *remoteSessionLifecycle) recoverOwnedSandbox(
return nil, false, nil
}
+// recoverWithoutCreating finds key's machine after its binding was lost and
+// binds it again. (nil, false, nil) means the provider listed nothing with
+// key's identity: the machine is gone. A provider that cannot list by
+// metadata cannot prove that, so it returns ErrMachineAbsenceUnprovable.
+func (l *remoteSessionLifecycle) recoverWithoutCreating(
+ ctx context.Context, key SessionSandboxKey,
+) (RemoteSandboxHandle, bool, error) {
+ caps := l.client.Capabilities()
+ if !caps.SupportsMetadata || !caps.SupportsListSandboxes {
+ return nil, false, ErrMachineAbsenceUnprovable
+ }
+ var handle RemoteSandboxHandle
+ var found bool
+ err := l.bindings.WithLifecycleLock(ctx, key, func(lockCtx context.Context) error {
+ if binding, err := l.readBinding(lockCtx, key); err != nil || binding != nil {
+ if err != nil {
+ return err
+ }
+ // Bound meanwhile by another request: use that machine.
+ // connectKnownWinner takes the binding, not the key.
+ h, err := l.connectKnownWinner(lockCtx, *binding)
+ handle, found = h, err == nil && h != nil
+ return err
+ }
+ var err error
+ // Keep a tokenless machine: deleting it would take every other
+ // session's files. The cleanup command is the only call we make.
+ handle, found, err = l.recoverOwned(lockCtx, key, true)
+ return err
+ })
+ return handle, found, err
+}
+
+// ensureBinding records handle under key when the key is unbound. A cleanup
+// that re-adopted a machine without its inbound token calls this only after
+// the directory command succeeds, so a failed command does not leave a
+// binding that wedges every later call.
+func (l *remoteSessionLifecycle) ensureBinding(
+ ctx context.Context, key SessionSandboxKey, handle RemoteSandboxHandle,
+) error {
+ if handle == nil || handle.ID() == "" {
+ return errors.New("sandbox: cannot bind an empty recovered handle")
+ }
+ // A tokenless handle under a closed-inbound policy must stay unbound.
+ // The directory delete can still be reported complete; the next resolve
+ // refuses to delete the user machine or to create a second one.
+ if l.missingRequiredInboundToken(handle) {
+ return nil
+ }
+ return l.bindings.WithLifecycleLock(ctx, key, func(lockCtx context.Context) error {
+ existing, err := l.readBinding(lockCtx, key)
+ if err != nil || existing != nil {
+ return err
+ }
+ binding := l.newBinding(key, handle.ID(), l.createRequest.TemplateID, InboundTokenOf(handle), l.now())
+ _, err = l.bindings.Create(lockCtx, key, binding)
+ if err != nil {
+ return fmt.Errorf("bind recovered remote sandbox: %w", err)
+ }
+ return nil
+ })
+}
+
func (l *remoteSessionLifecycle) createAndBind(
ctx context.Context,
key SessionSandboxKey,
) (RemoteSandboxHandle, error) {
+ if l.createGate != nil {
+ token, err := redislock.NewToken()
+ if err != nil {
+ return nil, err
+ }
+ lease, err := l.createGate.Hold(ctx, admission.ConfigCreateScope(l.configTenantID, l.sandboxConfigID),
+ "create:"+token, admission.DefaultHoldTTL)
+ if errors.Is(err, admission.ErrClosed) {
+ return nil, fmt.Errorf("%w: %s", ErrSandboxConfigCordoned, l.sandboxConfigID)
+ }
+ if err != nil {
+ return nil, fmt.Errorf("register sandbox create: %w", err)
+ }
+ defer lease.Release()
+ var stop func()
+ ctx, stop = admission.Bind(ctx, lease)
+ defer stop()
+ }
+
// request is a VALUE copy of l.createRequest, and every mutation below
// must stay on the copy. l.createRequest is shared by every session this
// config serves, so writing the override onto it would make unrelated
@@ -781,6 +906,115 @@ func (l *remoteSessionLifecycle) destroyBindingLocked(
return errors.New("sandbox binding changed during destroy")
}
+// reclaimUserMachine deletes a shared machine. Under the lifecycle lock it
+// closes the machine scope, requires that nothing is registered, then runs
+// check, which must re-read everything that makes the machine reclaimable:
+// a session placed meanwhile either waits on the closed scope and gets a new
+// machine, or makes check false. The barrier is checked before each
+// destructive step. Busy or no-longer-eligible is (false, nil).
+//
+// Destroy goes through the binding id and a metadata sweep, not metadata
+// adoption. A missing inbound token must not skip that destroy: once check
+// says the machine is empty, sibling directories are already gone.
+func (l *remoteSessionLifecycle) reclaimUserMachine(
+ ctx context.Context, key SessionSandboxKey, check func(context.Context) (bool, error),
+) (bool, error) {
+ if !key.IsUserMachine() {
+ return false, errors.New("reclaim: not a user machine key")
+ }
+ if l.admission == nil {
+ return false, errors.New("reclaim: user machines require an admission registry")
+ }
+ reclaimed := false
+ err := l.bindings.WithLifecycleLock(ctx, key, func(lockCtx context.Context) error {
+ scope := admission.MachineScope(l.digest(key))
+ barrier, err := l.admission.Close(lockCtx, scope, redisLifecycleLockLease)
+ if errors.Is(err, admission.ErrClosed) {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ defer barrier.Release()
+ // C3: every provider call below stops if the barrier is lost.
+ guarded, stop := admission.Bind(lockCtx, barrier)
+ defer stop()
+ active, err := l.admission.ActiveExcept(guarded, scope)
+ if err != nil || active > 0 {
+ return err
+ }
+ ok, err := check(guarded)
+ if err != nil || !ok {
+ return err
+ }
+ binding, err := l.readBinding(guarded, key)
+ if err != nil {
+ return err
+ }
+ if binding != nil {
+ if err := barrier.Check(); err != nil {
+ return err
+ }
+ if err := l.destroyBindingLocked(guarded, key, *binding); err != nil {
+ return errors.Join(err, barrier.Check())
+ }
+ }
+ if err := l.deleteOwnedByMetadata(guarded, key, barrier); err != nil {
+ return err
+ }
+ reclaimed = true
+ return nil
+ })
+ return reclaimed, err
+}
+
+// deleteOwnedByMetadata removes every provider sandbox carrying key's
+// identity. A binding lost to a Redis flush leaves exactly such a machine.
+// guard is checked before each delete.
+func (l *remoteSessionLifecycle) deleteOwnedByMetadata(
+ ctx context.Context, key SessionSandboxKey, guard admission.Signal,
+) error {
+ caps := l.client.Capabilities()
+ if !caps.SupportsMetadata || !caps.SupportsListSandboxes {
+ return nil
+ }
+ if err := guard.Check(); err != nil {
+ return err
+ }
+ summaries, err := l.client.List(ctx, RemoteListFilter{Metadata: l.metadata(key)})
+ if err != nil {
+ return errors.Join(fmt.Errorf("list owned remote sandboxes: %w", err), guard.Check())
+ }
+ for _, s := range summaries {
+ if s.ID == "" || s.State == RemoteStateTerminal {
+ continue
+ }
+ if err := guard.Check(); err != nil {
+ return err
+ }
+ // Delete on the barrier-bound context, not the lifecycle-ownership
+ // context cleanupSandboxID uses. A lost barrier must cancel this Kill.
+ // Create-failure cleanup still goes through cleanupSandboxID.
+ if err := l.deleteListedSandbox(ctx, s.ID); err != nil {
+ return errors.Join(fmt.Errorf("delete owned remote sandbox %q: %w", s.ID, err), guard.Check())
+ }
+ }
+ return nil
+}
+
+// deleteListedSandbox kills one metadata-listed sandbox. ctx is the caller's
+// context (the barrier-bound one during reclaim), so a lost barrier cancels
+// the provider call. A missing sandbox is success, as in cleanupSandboxID.
+func (l *remoteSessionLifecycle) deleteListedSandbox(ctx context.Context, sandboxID string) error {
+ cleanupCtx, cancel := context.WithTimeout(ctx, l.cleanupTimeout)
+ defer cancel()
+ err := l.client.Delete(cleanupCtx, sandboxID)
+ if err != nil && !CanReplaceRemoteBinding(err) {
+ return err
+ }
+ return nil
+}
+
func (l *remoteSessionLifecycle) readBinding(
ctx context.Context,
key SessionSandboxKey,
diff --git a/internal/sandbox/session_lifecycle_test.go b/internal/sandbox/session_lifecycle_test.go
index 521bff6f9..8042c9583 100644
--- a/internal/sandbox/session_lifecycle_test.go
+++ b/internal/sandbox/session_lifecycle_test.go
@@ -1386,6 +1386,7 @@ func newUserLifecycleFixture(t *testing.T) *userLifecycleFixture {
}},
time.Minute, "cfg-1", nil,
withUserMachines("weknora", reg),
+ withConfigCreateGate(reg, 42),
)
require.NoError(t, err)
return &userLifecycleFixture{
@@ -1398,6 +1399,37 @@ func (f *userLifecycleFixture) sessionKey(sessionID string) SessionSandboxKey {
return SessionSandboxKey{TenantID: 42, SessionID: sessionID, User: f.machine}
}
+func TestCreateRegistersWithTheConfigAndIsRefusedOnceItIsClosed(t *testing.T) {
+ f := newUserLifecycleFixture(t)
+ ctx := context.Background()
+ scope := admission.ConfigCreateScope(42, "cfg-1")
+ var during int
+ f.client.createHook = func(context.Context, RemoteCreateRequest) error {
+ n, err := f.admission.ActiveExcept(ctx, scope)
+ require.NoError(t, err)
+ during = n
+ return nil
+ }
+ _, err := f.lifecycle.Resolve(ctx, f.sessionKey(userSessionA))
+ require.NoError(t, err)
+ require.Equal(t, 1, during, "the provider Create runs inside a config-level registration")
+ n, _ := f.admission.ActiveExcept(ctx, scope)
+ require.Zero(t, n, "released once the binding is written")
+
+ barrier, err := f.admission.Close(ctx, scope, time.Minute)
+ require.NoError(t, err)
+ defer barrier.Release()
+ creates, _, _, _, _ := f.client.counts()
+ // A second session of the same owner reuses the machine and never calls
+ // Create. Another owner is a new machine, so Resolve has to register again.
+ other := f.machine
+ other.OwnerID = "u-2"
+ _, err = f.lifecycle.Resolve(ctx, SessionSandboxKey{TenantID: 42, SessionID: userSessionB, User: other})
+ require.ErrorIs(t, err, ErrSandboxConfigCordoned)
+ after, _, _, _, _ := f.client.counts()
+ require.Equal(t, creates, after, "nothing reaches the provider after the close")
+}
+
func TestUserMachineIsSharedBySessions(t *testing.T) {
f := newUserLifecycleFixture(t)
ctx := context.Background()
@@ -1433,6 +1465,63 @@ func TestUserMachineSurvivesAMissingSession(t *testing.T) {
require.Zero(t, deletes)
}
+// A provider that issues the inbound token only at create time cannot hand it
+// back when the binding is gone. Session mode still deletes that sandbox and
+// starts another. A user machine must not: deleting it takes every sibling
+// session's files, and binding the empty token wedges every later call.
+func TestUserMachineTokenlessAdoptionKeepsTheMachineAndDoesNotBindAnEmptyToken(t *testing.T) {
+ closed := false
+
+ t.Run("resolve", func(t *testing.T) {
+ f := newUserLifecycleFixture(t)
+ f.lifecycle.createRequest.Network = RemoteNetworkPolicy{AllowPublicTraffic: &closed}
+ f.client.trafficAccessToken = "create-token"
+ ctx := context.Background()
+ first, err := f.lifecycle.Resolve(ctx, f.sessionKey(userSessionA))
+ require.NoError(t, err)
+ machineKey := f.sessionKey(userSessionA).Machine()
+ deleted, err := f.bindings.DeleteIfMatch(ctx, machineKey, f.client.Provider(), first.ID())
+ require.NoError(t, err)
+ require.True(t, deleted)
+
+ _, err = f.lifecycle.Resolve(ctx, f.sessionKey(userSessionB))
+ require.Error(t, err)
+ require.Contains(t, err.Error(), "inbound traffic token")
+ require.True(t, f.client.hasSandbox(first.ID()), "the shared machine stays")
+ creates, _, _, _, deletes := f.client.counts()
+ require.Equal(t, 1, creates, "resolve must not start a second machine")
+ require.Zero(t, deletes)
+ binding, err := f.bindings.Get(ctx, machineKey)
+ require.NoError(t, err)
+ require.Nil(t, binding, "an empty token must not be persisted")
+ })
+
+ t.Run("cleanup", func(t *testing.T) {
+ h := newUserManagerHarness(t, userAssignmentFor(userSessionA), userAssignmentFor(userSessionB))
+ h.mgr.lifecycle.createRequest.Network = RemoteNetworkPolicy{AllowPublicTraffic: &closed}
+ h.client.trafficAccessToken = "create-token"
+ ctx := ownerCtx()
+ _, err := h.mgr.ExecShellCommand(ctx, userSessionA, "true", "", time.Second, nil)
+ require.NoError(t, err)
+ m, _ := userAssignmentFor(userSessionA).UserMachine()
+ sandboxID, ok := h.mgr.BoundSandboxID(ctx, userSessionA)
+ require.True(t, ok)
+ _, err = h.mgr.bindings.DeleteIfMatch(ctx, h.mgr.UserMachineKey(m), h.client.Provider(), sandboxID)
+ require.NoError(t, err)
+
+ deleted, err := h.mgr.DeleteSessionWorkspaces(ctx, m, []string{userSessionA})
+ require.NoError(t, err)
+ require.Equal(t, []string{userSessionA}, deleted, "the directory command still completes")
+ require.True(t, h.client.hasSandbox(sandboxID), "the shared machine stays")
+ creates, _, _, _, deletes := h.client.counts()
+ require.Equal(t, 1, creates)
+ require.Zero(t, deletes)
+ binding, err := h.mgr.bindings.Get(ctx, h.mgr.UserMachineKey(m))
+ require.NoError(t, err)
+ require.Nil(t, binding, "a successful cleanup must not persist an empty token")
+ })
+}
+
func TestUserMachineRecoversFromLostBindingByDigest(t *testing.T) {
f := newUserLifecycleFixture(t)
ctx := context.Background()
@@ -1516,3 +1605,116 @@ func TestUserKeyWithoutAdmissionIsRefused(t *testing.T) {
})
require.ErrorContains(t, err, "admission")
}
+
+func TestReclaimUserMachineRespectsAdmissionAndTheCheck(t *testing.T) {
+ f := newUserLifecycleFixture(t)
+ ctx := context.Background()
+ h, err := f.lifecycle.Resolve(ctx, f.sessionKey(userSessionA))
+ require.NoError(t, err)
+ machine := f.sessionKey(userSessionA).Machine()
+ scope := admission.MachineScope(f.machine.Digest("weknora"))
+
+ pty, err := f.admission.Hold(ctx, scope, admission.SessionMember(userSessionB, "pty", "t"), time.Minute)
+ require.NoError(t, err)
+ ok, err := f.lifecycle.reclaimUserMachine(ctx, machine, func(context.Context) (bool, error) {
+ t.Fatal("the check must not run while an operation is registered")
+ return true, nil
+ })
+ require.NoError(t, err)
+ require.False(t, ok, "an attached terminal blocks reclaim")
+ pty.Release()
+
+ ok, err = f.lifecycle.reclaimUserMachine(ctx, machine, func(context.Context) (bool, error) { return false, nil })
+ require.NoError(t, err)
+ require.False(t, ok, "the in-lock recheck cancels reclaim")
+ require.True(t, f.client.hasSandbox(h.ID()))
+
+ ok, err = f.lifecycle.reclaimUserMachine(ctx, machine, func(context.Context) (bool, error) { return true, nil })
+ require.NoError(t, err)
+ require.True(t, ok)
+ require.False(t, f.client.hasSandbox(h.ID()))
+ got, err := f.bindings.Get(ctx, machine)
+ require.NoError(t, err)
+ require.Nil(t, got)
+}
+
+func TestReclaimUserMachineStopsWhenTheBarrierIsLost(t *testing.T) {
+ f := newUserLifecycleFixture(t)
+ ctx := context.Background()
+ _, err := f.lifecycle.Resolve(ctx, f.sessionKey(userSessionA))
+ require.NoError(t, err)
+ machine := f.sessionKey(userSessionA).Machine()
+ scope := admission.MachineScope(f.machine.Digest("weknora"))
+ f.client.deleteHook = func(context.Context, string) error {
+ f.admission.LoseBarrier(scope)
+ return nil
+ }
+ _, _, _, listsBefore, _ := f.client.counts()
+
+ ok, err := f.lifecycle.reclaimUserMachine(ctx, machine, func(context.Context) (bool, error) { return true, nil })
+ require.ErrorIs(t, err, admission.ErrLeaseLost)
+ require.False(t, ok)
+ _, _, _, listsAfter, _ := f.client.counts()
+ require.Equal(t, listsBefore, listsAfter, "no metadata sweep after the barrier is gone")
+}
+
+func TestReclaimUserMachineChecksTheBarrierBeforeEachMetadataDelete(t *testing.T) {
+ f := newUserLifecycleFixture(t)
+ ctx := context.Background()
+ first, err := f.lifecycle.Resolve(ctx, f.sessionKey(userSessionA))
+ require.NoError(t, err)
+ machine := f.sessionKey(userSessionA).Machine()
+ _, err = f.bindings.DeleteIfMatch(ctx, machine, SandboxTypeCube, first.ID())
+ require.NoError(t, err)
+ second := f.client.addSandboxWithMetadata(f.lifecycle.metadata(machine)) // a duplicate left by a failed create
+ scope := admission.MachineScope(f.machine.Digest("weknora"))
+ deletes := 0
+ f.client.deleteHook = func(context.Context, string) error {
+ deletes++
+ f.admission.LoseBarrier(scope) // lost after the first delete
+ return nil
+ }
+ _, err = f.lifecycle.reclaimUserMachine(ctx, machine, func(context.Context) (bool, error) { return true, nil })
+ require.ErrorIs(t, err, admission.ErrLeaseLost)
+ require.Equal(t, 1, deletes, "no further delete after the barrier is gone")
+ _ = second
+}
+
+func TestReclaimUserMachineMetadataDeleteStopsWhenTheBarrierIsLost(t *testing.T) {
+ f := newUserLifecycleFixture(t)
+ ctx := context.Background()
+ first, err := f.lifecycle.Resolve(ctx, f.sessionKey(userSessionA))
+ require.NoError(t, err)
+ machine := f.sessionKey(userSessionA).Machine()
+ _, err = f.bindings.DeleteIfMatch(ctx, machine, SandboxTypeCube, first.ID())
+ require.NoError(t, err)
+ scope := admission.MachineScope(f.machine.Digest("weknora"))
+
+ f.client.deleteHook = func(hookCtx context.Context, _ string) error {
+ f.admission.LoseBarrier(scope)
+ select {
+ case <-hookCtx.Done():
+ return nil
+ case <-time.After(time.Second):
+ t.Error("metadata delete kept running after the barrier was lost")
+ return context.DeadlineExceeded
+ }
+ }
+ _, err = f.lifecycle.reclaimUserMachine(ctx, machine, func(context.Context) (bool, error) { return true, nil })
+ require.ErrorIs(t, err, admission.ErrLeaseLost)
+}
+
+func TestReclaimUserMachineDeletesAnUnboundMachineByMetadata(t *testing.T) {
+ f := newUserLifecycleFixture(t)
+ ctx := context.Background()
+ h, err := f.lifecycle.Resolve(ctx, f.sessionKey(userSessionA))
+ require.NoError(t, err)
+ machine := f.sessionKey(userSessionA).Machine()
+ _, err = f.bindings.DeleteIfMatch(ctx, machine, SandboxTypeCube, h.ID()) // Redis lost it
+ require.NoError(t, err)
+
+ ok, err := f.lifecycle.reclaimUserMachine(ctx, machine, func(context.Context) (bool, error) { return true, nil })
+ require.NoError(t, err)
+ require.True(t, ok)
+ require.False(t, f.client.hasSandbox(h.ID()), "a paused machine with no binding must not bill forever")
+}
diff --git a/internal/sandbox/session_manager.go b/internal/sandbox/session_manager.go
index f11488b53..34cbf4112 100644
--- a/internal/sandbox/session_manager.go
+++ b/internal/sandbox/session_manager.go
@@ -24,11 +24,15 @@ package sandbox
import (
"context"
+ "crypto/sha256"
+ "encoding/hex"
"errors"
"fmt"
"log"
"os"
"path"
+ "regexp"
+ "strconv"
"strings"
"sync"
"time"
@@ -116,6 +120,11 @@ type SessionBoundManager struct {
// admissionWait bounds waiting for a closed scope (rebuild, exclusive).
admissionWait time.Duration
+ // rewindWait bounds the exclusive window rewind takes on a shared machine.
+ // It is shorter than admissionWait: an open terminal should fail rewind
+ // quickly instead of holding the HTTP request for a rebuild-length wait.
+ rewindWait time.Duration
+
// mu guards Cleanup's idempotency flag.
mu sync.RWMutex
closed bool
@@ -154,6 +163,10 @@ type SessionBoundManagerConfig struct {
// touching another that shares the same provider account.
ConfigID string
+ // ConfigTenantID is the workspace that owns ConfigID. The resolver fills
+ // it so provider creates register on that config's admission scope.
+ ConfigTenantID uint64
+
// SkipHealthProbe skips the construction-time Health() round-trip.
// Set by the per-tenant resolver, which builds a manager per request.
// See NewSessionBoundManager.
@@ -240,6 +253,7 @@ func NewSessionBoundManager(deps SessionBoundManagerConfig) (*SessionBoundManage
var lifecycleOpts []lifecycleOption
if deps.Admission != nil {
lifecycleOpts = append(lifecycleOpts, withUserMachines(deps.Namespace, deps.Admission))
+ lifecycleOpts = append(lifecycleOpts, withConfigCreateGate(deps.Admission, deps.ConfigTenantID))
}
lifecycle, err := newRemoteSessionLifecycle(
client,
@@ -269,6 +283,7 @@ func NewSessionBoundManager(deps SessionBoundManagerConfig) (*SessionBoundManage
admission: deps.Admission,
namespace: deps.Namespace,
admissionWait: 30 * time.Second,
+ rewindWait: rewindExclusiveWait,
}
// Per-tenant managers are rebuilt on every request, so probing here would
@@ -1294,6 +1309,18 @@ func (m *SessionBoundManager) OpenSessionTerminal(
}
return abandon(ErrNoLiveSessionSandbox)
}
+ // A shared machine already exists for the owner's other sessions. This
+ // session's directory is created by the first shell command, not by
+ // attaching a PTY, so opening the terminal first would start a shell in
+ // a directory that is not there yet.
+ if sc.user {
+ if err := m.prepareSessionDirs(
+ callCtx, handle, DefaultSandboxExecUser,
+ sc.layout.InputDir, sc.layout.OutputDir, opts.Cwd,
+ ); err != nil {
+ return abandon(err)
+ }
+ }
session, err := terminal.OpenTerminal(callCtx, handle, opts)
if err != nil {
return abandon(err)
@@ -1525,6 +1552,30 @@ func (m *SessionBoundManager) HasActiveTurn(ctx context.Context, sessionID strin
return active, err
}
+const rewindExclusiveWait = 5 * time.Second
+
+// LockRewindSession takes the session's rewind lock and, on a shared
+// machine, the session's exclusive window, so no other operation of the
+// session touches its work tree during the reset. Run the reset with the
+// returned context. On a per-session sandbox the context is ctx itself.
+func (m *SessionBoundManager) LockRewindSession(
+ ctx context.Context, sessionID string,
+) (context.Context, func(), error) {
+ unlockRewind, err := m.TryLockRewind(ctx, sessionID)
+ if err != nil {
+ return nil, nil, err
+ }
+ exCtx, release, err := m.acquireSessionExclusive(ctx, sessionID, m.rewindWait)
+ if err != nil {
+ unlockRewind()
+ return nil, nil, err
+ }
+ return exCtx, func() {
+ release()
+ unlockRewind()
+ }, nil
+}
+
// TryLockRewind takes an exclusive rewind lock for sessionID. Stores that do
// not implement rewind locking succeed as a no-op so local tests without a
// lease store still rewind.
@@ -2087,6 +2138,40 @@ func (m *SessionBoundManager) acquireSessionExclusive(
}, nil
}
+// DesktopMachine names the physical machine behind sessionID's desktop and
+// the sandbox it currently is. Sessions on one shared machine contend for one
+// control slot; a rebuilt machine, or a sandbox of another deployment,
+// provider or config, never shares a key. Call it while holding the session's
+// operation so the binding cannot change underneath the caller.
+func (m *SessionBoundManager) DesktopMachine(ctx context.Context, sessionID string) (string, string, error) {
+ sc, err := m.scope(ctx, sessionID)
+ if err != nil {
+ return "", "", err
+ }
+ if !sc.user {
+ // A per-session machine rebuilds a stale image on the next resolve.
+ // Pinning the current sandbox id would make the desktop's ensure
+ // command lookup-only and skip that rebuild.
+ return sessionID, "", nil
+ }
+ binding, err := m.bindings.Get(ctx, sc.machine())
+ if err != nil {
+ return "", "", err
+ }
+ if binding == nil || binding.SandboxID == "" || binding.Provider != m.client.Provider() {
+ return "", "", ErrNoLiveSessionSandbox
+ }
+ parts := []string{
+ m.namespace,
+ string(m.client.Provider()),
+ strconv.FormatUint(binding.ConfigTenantID, 10),
+ NormalizeConfigID(m.configID),
+ binding.SandboxID,
+ }
+ sum := sha256.Sum256([]byte(strings.Join(parts, "\x00")))
+ return hex.EncodeToString(sum[:]), binding.SandboxID, nil
+}
+
// HoldSessionOperation registers a long-lived operation (desktop relay) of
// sessionID; ctx is cancelled if the lease is lost. A no-op for per-session
// machines.
@@ -2115,6 +2200,151 @@ func (m *SessionBoundManager) UserMachineKey(machine allocation.UserMachine) Ses
return SessionSandboxKey{TenantID: machine.OwnerTenantID, User: machine}
}
+const sessionWorkspaceCleanupTimeout = 60 * time.Second
+
+// ErrMachineAbsenceUnprovable is returned when a user machine has no binding
+// and the provider cannot list by metadata, so it may still exist. Directory
+// cleanups keep their task instead of treating the machine as gone.
+var ErrMachineAbsenceUnprovable = errors.New("sandbox: cannot prove the user machine is gone")
+
+// DeleteSessionWorkspaces removes the work trees and checkpoint repositories
+// of retired sessions from their shared machine. It registers on the machine
+// first, then takes each session's scope exclusively so work admitted before
+// the retirement finishes before its directory goes; a session whose
+// operations do not leave in time is skipped and reported as not deleted.
+// Every hold is bound into the command's context, so a lost hold stops the
+// deletion (C3). A machine whose binding was lost is re-adopted by metadata,
+// never created; only a provider that lists nothing proves it is gone (C5).
+// Connect resumes a paused machine: a deleted session's files must not
+// linger on its disk.
+func (m *SessionBoundManager) DeleteSessionWorkspaces(
+ ctx context.Context, machine allocation.UserMachine, sessionIDs []string,
+) ([]string, error) {
+ if err := m.requireRemoteBackend(); err != nil {
+ return nil, err
+ }
+ if m.admission == nil {
+ return nil, errors.New("sandbox: user machines require the admission registry")
+ }
+ if len(sessionIDs) == 0 {
+ return nil, nil
+ }
+ for _, id := range sessionIDs {
+ if _, err := UserWorkspaceLayout(id); err != nil {
+ return nil, err
+ }
+ }
+ digest := machine.Digest(m.namespace)
+ token, err := redislock.NewToken()
+ if err != nil {
+ return nil, err
+ }
+ lease, err := m.holdWithWait(ctx, admission.MachineScope(digest),
+ admission.SessionMember(sessionIDs[0], "cleanup", token))
+ if err != nil {
+ return nil, err
+ }
+ defer lease.Release()
+
+ signals := []admission.Signal{lease}
+ var barriers []admission.Barrier
+ defer func() {
+ for _, b := range barriers {
+ b.Release()
+ }
+ }()
+ var ready []string
+ for _, id := range sessionIDs {
+ _, barrier, err := m.acquireExclusive(ctx, digest, id, m.admissionWait)
+ if errors.Is(err, ErrSessionWorkspaceBusy) {
+ continue
+ }
+ if err != nil {
+ return nil, err
+ }
+ barriers = append(barriers, barrier)
+ signals = append(signals, barrier)
+ ready = append(ready, id)
+ }
+ if len(ready) == 0 {
+ return nil, nil
+ }
+ guarded, stop := admission.Bind(ctx, signals...)
+ defer stop()
+ lost := func(err error) error {
+ if cause := context.Cause(guarded); errors.Is(cause, admission.ErrLeaseLost) {
+ return cause
+ }
+ return err
+ }
+
+ key := m.UserMachineKey(machine)
+ handle, found, err := m.lookupSessionHandleForKey(guarded, key, "")
+ if err != nil {
+ return nil, lost(err)
+ }
+ if !found {
+ handle, found, err = m.lifecycle.recoverWithoutCreating(guarded, key)
+ if err != nil {
+ return nil, lost(err)
+ }
+ if !found {
+ return ready, nil
+ }
+ }
+ var targets []string
+ for _, id := range ready {
+ l, _ := UserWorkspaceLayout(id)
+ targets = append(targets, ShellQuote(l.Root), ShellQuote(l.GitDir))
+ }
+ // Refuse a symlinked parent instead of following it: an agent on this
+ // machine runs as root and may have replaced one.
+ script := `set -eu
+for p in /workspace /workspace/sessions /var/lib/weknora /var/lib/weknora/sessions; do
+ if [ -L "$p" ]; then echo "refusing to clean through symlinked $p" >&2; exit 4; fi
+done
+for t in ` + strings.Join(targets, " ") + `; do
+ if [ -L "$t" ]; then rm -f -- "$t"; else rm -rf -- "$t"; fi
+done`
+ result, err := m.client.Exec(guarded, handle, RemoteExecRequest{
+ Shell: true, Command: script, User: "root", Timeout: sessionWorkspaceCleanupTimeout,
+ })
+ if err != nil {
+ return nil, lost(fmt.Errorf("sandbox: delete session workspaces: %w", err))
+ }
+ if result == nil || result.ExitCode != 0 || result.Killed {
+ detail := "no result"
+ if result != nil {
+ detail = fmt.Sprintf("exit=%d stderr=%s", result.ExitCode, strings.TrimSpace(result.Stderr))
+ }
+ return nil, fmt.Errorf("sandbox: delete session workspaces: %s", detail)
+ }
+ if err := lost(nil); err != nil {
+ return nil, err
+ }
+ // A re-adopted machine whose token could not be recovered is bound only
+ // once the directories are actually gone. ensureBinding is a no-op when
+ // the binding was already there.
+ if err := m.lifecycle.ensureBinding(guarded, key, handle); err != nil {
+ return nil, lost(err)
+ }
+ if err := lost(nil); err != nil {
+ return nil, err
+ }
+ return ready, nil
+}
+
+// ReclaimUserMachine deletes a shared user machine; see
+// remoteSessionLifecycle.reclaimUserMachine for the safety rules.
+func (m *SessionBoundManager) ReclaimUserMachine(
+ ctx context.Context, machine allocation.UserMachine, check func(context.Context) (bool, error),
+) (bool, error) {
+ if err := m.requireRemoteBackend(); err != nil {
+ return false, err
+ }
+ return m.lifecycle.reclaimUserMachine(ctx, m.UserMachineKey(machine), check)
+}
+
// withSessionEnv overlays the session's input/output paths. On a shared
// machine they are reserved: no config or caller value may redirect them.
func withSessionEnv(env map[string]string, layout WorkspaceLayout) map[string]string {
@@ -2316,6 +2546,190 @@ func effectiveHTTPTimeout(provider RemoteProvider, cfg *Config) time.Duration {
}
}
+var forkCommitPattern = regexp.MustCompile(`^[0-9a-f]{40}$`)
+
+const (
+ forkCopyTimeout = 5 * time.Minute
+ forkMaxCandidates = 2000
+)
+
+// WorkspaceFork is an open fork of a session on a shared machine. It holds
+// the machine's and the source session's admission until Release, so the
+// machine named by SandboxID is the one every step runs on. Its steps fail
+// with admission.ErrLeaseLost once that hold is lost.
+type WorkspaceFork interface {
+ SandboxID() string
+ // Context is cancelled with admission.ErrLeaseLost once the hold is
+ // lost. Run every step of the fork with it, database steps included.
+ Context() context.Context
+ // Copy materializes sha of the source's checkpoint repository as
+ // targetSessionID's workspace and reports which of candidates are sha
+ // or its ancestors, i.e. which checkpoints exist in the new repository.
+ Copy(targetSessionID, sha string, candidates []string) (map[string]bool, error)
+ // Remove deletes targetSessionID's work tree and repository.
+ Remove(targetSessionID string) error
+ Release()
+}
+
+type workspaceFork struct {
+ m *SessionBoundManager
+ ctx context.Context
+ source WorkspaceLayout
+ handle RemoteSandboxHandle
+ member string
+ release func()
+}
+
+// BeginWorkspaceFork opens a fork of sourceSessionID on its shared machine.
+// It never creates the machine: a source without one has nothing to copy.
+func (m *SessionBoundManager) BeginWorkspaceFork(ctx context.Context, sourceSessionID string) (WorkspaceFork, error) {
+ if err := m.requireRemoteBackend(); err != nil {
+ return nil, err
+ }
+ sc, err := m.scope(ctx, sourceSessionID)
+ if err != nil {
+ return nil, err
+ }
+ if !sc.user {
+ return nil, ErrSharedSandbox
+ }
+ opCtx, release, err := m.admitUser(ctx, sc, "fork")
+ if err != nil {
+ // admitUser releases anything it acquired and returns a nil func.
+ if release != nil {
+ release()
+ }
+ return nil, err
+ }
+ handle, found, err := m.lookupSessionHandleForKey(opCtx, sc.machine(), "")
+ if err != nil {
+ release()
+ return nil, err
+ }
+ if !found {
+ release()
+ return nil, ErrNoLiveSessionSandbox
+ }
+ exempt := admissionExemptFrom(opCtx)
+ return &workspaceFork{
+ m: m, ctx: opCtx, source: sc.layout, handle: handle,
+ member: exempt[len(exempt)-1], release: release,
+ }, nil
+}
+
+func (f *workspaceFork) SandboxID() string { return f.handle.ID() }
+func (f *workspaceFork) Context() context.Context { return f.ctx }
+func (f *workspaceFork) Member() string { return f.member }
+func (f *workspaceFork) Release() { f.release() }
+
+func (f *workspaceFork) alive() error {
+ if err := context.Cause(f.ctx); err != nil {
+ return err
+ }
+ return nil
+}
+
+func (f *workspaceFork) run(script string) (*RemoteExecResult, error) {
+ if err := f.alive(); err != nil {
+ return nil, err
+ }
+ result, err := f.m.client.Exec(f.ctx, f.handle, RemoteExecRequest{
+ Shell: true, Command: script, User: "root", Timeout: forkCopyTimeout,
+ })
+ if cause := f.alive(); cause != nil {
+ return nil, cause
+ }
+ if err != nil {
+ return nil, err
+ }
+ if result == nil || result.ExitCode != 0 || result.Killed {
+ detail := "no result"
+ if result != nil {
+ detail = fmt.Sprintf("exit=%d stderr=%s", result.ExitCode, strings.TrimSpace(result.Stderr))
+ }
+ return nil, errors.New(detail)
+ }
+ return result, nil
+}
+
+func (f *workspaceFork) Copy(targetSessionID, sha string, candidates []string) (map[string]bool, error) {
+ if !forkCommitPattern.MatchString(sha) {
+ return nil, fmt.Errorf("sandbox: invalid fork commit %q", sha)
+ }
+ target, err := UserWorkspaceLayout(targetSessionID)
+ if err != nil {
+ return nil, err
+ }
+ seen := map[string]bool{}
+ var quoted []string
+ for _, c := range candidates {
+ if forkCommitPattern.MatchString(c) && !seen[c] && len(quoted) < forkMaxCandidates {
+ seen[c] = true
+ quoted = append(quoted, ShellQuote(c))
+ }
+ }
+ script := fmt.Sprintf(`set -eu
+SRC_GIT=%s
+DST_TREE=%s
+DST_GIT=%s
+SHA=%s
+for p in /workspace /workspace/sessions /var/lib/weknora /var/lib/weknora/sessions; do
+ if [ -L "$p" ]; then echo "refusing symlinked $p" >&2; exit 4; fi
+done
+if [ -e "$DST_TREE" ] || [ -e "$DST_GIT" ]; then echo "fork target exists" >&2; exit 5; fi
+mkdir -p /var/lib/weknora/sessions /workspace/sessions
+tmp=$(mktemp -d /var/lib/weknora/sessions/.fork.XXXXXX)
+trap 'rm -rf -- "$tmp"' EXIT
+g() { git -c safe.directory='*' -c core.hooksPath=/dev/null "$@"; }
+g --git-dir="$SRC_GIT" cat-file -e "$SHA^{commit}"
+if g --git-dir="$SRC_GIT" ls-tree -r "$SHA" | awk '$1=="160000"{f=1} END{exit !f}'; then
+ echo "checkpoint contains a gitlink" >&2; exit 6
+fi
+g init -q --bare "$tmp/repo.git"
+g -c uploadpack.allowAnySHA1InWant=true --git-dir="$tmp/repo.git" fetch -q --no-tags "$SRC_GIT" "$SHA:refs/heads/main"
+g --git-dir="$tmp/repo.git" symbolic-ref HEAD refs/heads/main
+g --git-dir="$tmp/repo.git" config core.bare false
+g --git-dir="$tmp/repo.git" config user.email [email protected]
+g --git-dir="$tmp/repo.git" config user.name 'WeKnora Agent'
+mkdir -p "$tmp/tree"
+g --git-dir="$tmp/repo.git" --work-tree="$tmp/tree" checkout -q -f main
+mkdir -p "$tmp/tree/input" "$tmp/tree/output"
+mv -- "$tmp/repo.git" "$DST_GIT"
+mv -- "$tmp/tree" "$DST_TREE"
+for c in %s; do
+ if g --git-dir="$DST_GIT" merge-base --is-ancestor "$c" "$SHA" 2>/dev/null; then echo "R $c"; fi
+done
+`, ShellQuote(f.source.GitDir), ShellQuote(target.Root), ShellQuote(target.GitDir), ShellQuote(sha),
+ strings.Join(quoted, " "))
+ result, err := f.run(script)
+ if err != nil {
+ return nil, fmt.Errorf("sandbox: copy session workspace: %w", err)
+ }
+ reachable := map[string]bool{}
+ for _, line := range strings.Split(result.Stdout, "\n") {
+ if c, ok := strings.CutPrefix(strings.TrimSpace(line), "R "); ok && seen[c] {
+ reachable[c] = true
+ }
+ }
+ return reachable, nil
+}
+
+func (f *workspaceFork) Remove(targetSessionID string) error {
+ target, err := UserWorkspaceLayout(targetSessionID)
+ if err != nil {
+ return err
+ }
+ _, err = f.run(fmt.Sprintf(`set -eu
+for p in /workspace /workspace/sessions /var/lib/weknora /var/lib/weknora/sessions; do
+ if [ -L "$p" ]; then echo "refusing symlinked $p" >&2; exit 4; fi
+done
+rm -rf -- %s %s`, ShellQuote(target.Root), ShellQuote(target.GitDir)))
+ if err != nil {
+ return fmt.Errorf("sandbox: remove forked workspace: %w", err)
+ }
+ return nil
+}
+
var (
_ SessionCapabilityProvider = (*SessionBoundManager)(nil)
_ SessionShellExecutor = (*SessionBoundManager)(nil)
diff --git a/internal/sandbox/session_manager_desktop_test.go b/internal/sandbox/session_manager_desktop_test.go
index f9cd670ed..bf173a504 100644
--- a/internal/sandbox/session_manager_desktop_test.go
+++ b/internal/sandbox/session_manager_desktop_test.go
@@ -30,6 +30,19 @@ func newSessionManagerDesktopHarness(t *testing.T, desktopEnabled bool) (*Sessio
return mgr, client
}
+func TestDesktopMachineDoesNotPinASessionOwnedSandbox(t *testing.T) {
+ ctx := terminalTestContext()
+ mgr, _ := newSessionManagerDesktopTestHarness(t)
+ _, err := mgr.ExecShellCommand(ctx, "sess-live", "true", "", time.Second, nil)
+ require.NoError(t, err)
+
+ machineID, sandboxID, err := mgr.DesktopMachine(ctx, "sess-live")
+ require.NoError(t, err)
+ require.Equal(t, "sess-live", machineID)
+ require.Empty(t, sandboxID,
+ "session mode must resolve, including a stale rebuild, instead of pinning the current id")
+}
+
func TestOpenSessionDesktopNoLiveSandbox(t *testing.T) {
ctx := terminalTestContext()
mgr, inner := newSessionManagerDesktopTestHarness(t)
@@ -133,3 +146,44 @@ func TestOpenSessionDesktopDisabledDoesNotDial(t *testing.T) {
require.ErrorIs(t, err, ErrDesktopUnsupported)
require.False(t, inner.dialed, "must not dial websockify when the config is not a desktop image")
}
+
+func TestDesktopMachineIsSharedByTheMachinesSessionsAndNamesTheSandbox(t *testing.T) {
+ h := newUserManagerHarness(t, userAssignmentFor(userSessionA), userAssignmentFor(userSessionB))
+ ctx := ownerCtx()
+ _, err := h.mgr.ExecShellCommand(ctx, userSessionA, "true", "", time.Second, nil)
+ require.NoError(t, err)
+ a, sandboxA, err := h.mgr.DesktopMachine(ctx, userSessionA)
+ require.NoError(t, err)
+ b, sandboxB, err := h.mgr.DesktopMachine(ctx, userSessionB)
+ require.NoError(t, err)
+ require.Equal(t, a, b)
+ require.Equal(t, sandboxA, sandboxB)
+ require.Len(t, a, 64)
+}
+
+func TestDesktopMachineChangesWithTheSandbox(t *testing.T) {
+ h := newUserManagerHarness(t, userAssignmentFor(userSessionA))
+ ctx := ownerCtx()
+ _, err := h.mgr.ExecShellCommand(ctx, userSessionA, "true", "", time.Second, nil)
+ require.NoError(t, err)
+ before, sandboxBefore, err := h.mgr.DesktopMachine(ctx, userSessionA)
+ require.NoError(t, err)
+ m, _ := userAssignmentFor(userSessionA).UserMachine()
+ _, err = h.mgr.bindings.DeleteIfMatch(ctx, h.mgr.UserMachineKey(m), h.client.provider, sandboxBefore)
+ require.NoError(t, err)
+ // Closed inbound refuses to adopt the leftover machine and will not start
+ // a second one while it still exists. Removing it is what lets the next
+ // exec create the replacement the slot key must change with.
+ require.NoError(t, h.client.Delete(ctx, sandboxBefore))
+ _, err = h.mgr.ExecShellCommand(ctx, userSessionA, "true", "", time.Second, nil)
+ require.NoError(t, err)
+ after, _, err := h.mgr.DesktopMachine(ctx, userSessionA)
+ require.NoError(t, err)
+ require.NotEqual(t, before, after, "a rebuilt machine gets a new slot key")
+}
+
+func TestDesktopMachineWithoutABindingIsNoLiveSandbox(t *testing.T) {
+ h := newUserManagerHarness(t, userAssignmentFor(userSessionA))
+ _, _, err := h.mgr.DesktopMachine(ownerCtx(), userSessionA)
+ require.ErrorIs(t, err, ErrNoLiveSessionSandbox)
+}
diff --git a/internal/sandbox/session_manager_test.go b/internal/sandbox/session_manager_test.go
index fda70b7a1..858f5dd8e 100644
--- a/internal/sandbox/session_manager_test.go
+++ b/internal/sandbox/session_manager_test.go
@@ -11,6 +11,7 @@ import (
"time"
"github.com/alicebob/miniredis/v2"
+ "github.com/google/uuid"
"github.com/redis/go-redis/v9"
"github.com/stretchr/testify/require"
@@ -1066,21 +1067,36 @@ func newUserManagerHarness(t *testing.T, assignments ...allocation.Assignment) *
admission.NewMemory(), assignments...)
}
+func newFakeAllocations(assignments ...allocation.Assignment) *fakeAllocations {
+ allocs := &fakeAllocations{byID: map[string]allocation.Assignment{}}
+ for _, a := range assignments {
+ allocs.byID[a.SessionID] = a
+ }
+ return allocs
+}
+
func newUserManagerHarnessWith(
t *testing.T, client *fakeRemoteClient, store SessionSandboxBindingStore, reg admission.Registry,
assignments ...allocation.Assignment,
+) *userHarness {
+ t.Helper()
+ return newUserManagerHarnessWithDirectory(t, client, store, reg, newFakeAllocations(assignments...), "weknora")
+}
+
+// newUserManagerHarnessWithDirectory is newUserManagerHarnessWith with the
+// allocation directory and Redis namespace passed in, so two replicas can
+// share one directory the way production replicas share one database.
+func newUserManagerHarnessWithDirectory(
+ t *testing.T, client *fakeRemoteClient, store SessionSandboxBindingStore, reg admission.Registry,
+ allocs *fakeAllocations, namespace string,
) *userHarness {
t.Helper()
cfg := DefaultConfig()
cfg.CubeTemplate = "tpl-test"
- allocs := &fakeAllocations{byID: map[string]allocation.Assignment{}}
- for _, a := range assignments {
- allocs.byID[a.SessionID] = a
- }
mgr, err := NewSessionBoundManager(SessionBoundManagerConfig{
Config: cfg, Client: client, Store: store,
Checker: &fakeSessionExistenceChecker{exists: true}, SkipHealthProbe: true,
- ConfigID: "cfg-1", Allocations: allocs, Admission: reg, Namespace: "weknora",
+ ConfigID: "cfg-1", Allocations: allocs, Admission: reg, Namespace: namespace,
})
require.NoError(t, err)
mgr.admissionWait = 200 * time.Millisecond
@@ -1088,6 +1104,49 @@ func newUserManagerHarnessWith(
return &userHarness{mgr: mgr, client: client, allocs: allocs, admission: mem}
}
+// integrationEnv returns an integration dependency's address. Missing, the
+// test is skipped — unless WEKNORA_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("WEKNORA_REQUIRE_INTEGRATION") == "1" {
+ t.Fatalf("%s is required when WEKNORA_REQUIRE_INTEGRATION=1", name)
+ }
+ t.Skipf("set %s to run against a real dependency", name)
+ return ""
+}
+
+// multiReplicaPair builds two managers that share one provider and one
+// allocation directory. An empty redisAddr starts miniredis; otherwise both
+// replicas dial that address. Each run uses its own namespace so a shared
+// Redis needs no cleanup.
+func multiReplicaPair(
+ t *testing.T, redisAddr string, assignments ...allocation.Assignment,
+) (*userHarness, *userHarness, *redis.Client) {
+ t.Helper()
+ if redisAddr == "" {
+ redisAddr = miniredis.RunT(t).Addr()
+ }
+ ns := "weknora-it-" + uuid.NewString()[:8]
+ client := newFakeRemoteClient(SandboxTypeCube)
+ allocs := newFakeAllocations(assignments...)
+ replica := func() *userHarness {
+ rc := redis.NewClient(&redis.Options{Addr: redisAddr})
+ t.Cleanup(func() { _ = rc.Close() })
+ store, err := NewRedisSessionSandboxBindingStore(rc, ns)
+ require.NoError(t, err)
+ return newUserManagerHarnessWithDirectory(t, client, store,
+ admission.NewRedis(rc, ns+":sandbox:user:"), allocs, ns)
+ }
+ raw := redis.NewClient(&redis.Options{Addr: redisAddr})
+ t.Cleanup(func() { _ = raw.Close() })
+ return replica(), replica(), raw
+}
+
func ownerCtx() context.Context {
return types.WithSandboxTenantID(context.Background(), 42)
}
@@ -1363,6 +1422,48 @@ func TestExclusiveWindowIsAMachineMemberAndBlocksRebuild(t *testing.T) {
require.Zero(t, n, "ending the window releases the machine member")
}
+func TestLockRewindSessionIsExclusiveForTheSessionOnly(t *testing.T) {
+ h := newUserManagerHarness(t, userAssignmentFor(userSessionA), userAssignmentFor(userSessionB))
+ ctx := ownerCtx()
+ h.mgr.admissionWait = 50 * time.Millisecond
+ h.mgr.rewindWait = 50 * time.Millisecond
+
+ _, closePTY, err := h.mgr.HoldSessionOperation(ctx, userSessionA, "pty")
+ require.NoError(t, err)
+ _, _, err = h.mgr.LockRewindSession(ctx, userSessionA)
+ require.ErrorIs(t, err, ErrSessionWorkspaceBusy, "A's open terminal blocks A's rewind")
+ locked, err := h.mgr.HasRewindLock(ctx, userSessionA)
+ require.NoError(t, err)
+ require.False(t, locked, "a failed exclusive window releases the rewind lock too")
+ closePTY()
+
+ exCtx, unlock, err := h.mgr.LockRewindSession(ctx, userSessionA)
+ require.NoError(t, err)
+ _, err = h.mgr.ExecShellCommand(exCtx, userSessionA, "true", "", time.Second, nil)
+ require.NoError(t, err, "the rewind's own reset runs inside its window")
+ _, err = h.mgr.ExecShellCommand(ctx, userSessionA, "true", "", time.Second, nil)
+ require.ErrorIs(t, err, ErrSessionWorkspaceBusy, "anything else of A waits for the rewind")
+ _, err = h.mgr.ExecShellCommand(ctx, userSessionB, "true", "", time.Second, nil)
+ require.NoError(t, err, "B on the same machine is unaffected")
+ unlock()
+
+ _, err = h.mgr.ExecShellCommand(ctx, userSessionA, "true", "", time.Second, nil)
+ require.NoError(t, err)
+}
+
+func TestLockRewindSessionOnAPerSessionSandboxKeepsTheContext(t *testing.T) {
+ mgr, _ := newSessionManagerExecTestHarness(t)
+ // sessionKey refuses a context with no tenant; the marker still has to
+ // come back on the same context session mode returns unchanged.
+ ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(10000))
+ ctx = context.WithValue(ctx, struct{ k string }{"marker"}, 1)
+ got, unlock, err := mgr.LockRewindSession(ctx, "sess-1")
+ require.NoError(t, err)
+ defer unlock()
+ require.Equal(t, ctx, got)
+ require.Equal(t, 1, got.Value(struct{ k string }{"marker"}))
+}
+
func TestUploadedScriptsStayInTheSessionDirectory(t *testing.T) {
h := newUserManagerHarness(t, userAssignmentFor(userSessionA))
script := filepath.Join(t.TempDir(), "run.py")
@@ -1377,17 +1478,8 @@ func TestUploadedScriptsStayInTheSessionDirectory(t *testing.T) {
}
func TestMultiReplicaAdmissionBlocksRebuildAcrossManagers(t *testing.T) {
- mini := miniredis.RunT(t)
- client := newFakeRemoteClient(SandboxTypeCube) // one provider shared by both replicas
- replica := func() *userHarness {
- rc := redis.NewClient(&redis.Options{Addr: mini.Addr()})
- t.Cleanup(func() { _ = rc.Close() })
- store, err := NewRedisSessionSandboxBindingStore(rc, "weknora")
- require.NoError(t, err)
- return newUserManagerHarnessWith(t, client, store, admission.NewRedis(rc, "weknora:sandbox:user:"),
- userAssignmentFor(userSessionA), userAssignmentFor(userSessionB))
- }
- r1, r2 := replica(), replica()
+ r1, r2, _ := multiReplicaPair(t, "",
+ userAssignmentFor(userSessionA), userAssignmentFor(userSessionB))
ctx := ownerCtx()
_, err := r1.mgr.ExecShellCommand(ctx, userSessionA, "true", "", time.Second, nil)
@@ -1411,3 +1503,303 @@ func TestMultiReplicaAdmissionBlocksRebuildAcrossManagers(t *testing.T) {
rebuilt, _ := r1.mgr.BoundSandboxID(ctx, userSessionA)
require.NotEqual(t, first, rebuilt)
}
+
+func TestDeleteSessionWorkspacesWaitsForTheSessionAndRemovesOnlyIt(t *testing.T) {
+ h := newUserManagerHarness(t, userAssignmentFor(userSessionA), userAssignmentFor(userSessionB))
+ ctx := ownerCtx()
+ _, err := h.mgr.ExecShellCommand(ctx, userSessionA, "true", "", time.Second, nil)
+ require.NoError(t, err)
+ _, connectsBefore, _, _, _ := h.client.counts()
+ m, _ := userAssignmentFor(userSessionA).UserMachine()
+
+ _, releasePTY, err := h.mgr.HoldSessionOperation(ctx, userSessionA, "pty")
+ require.NoError(t, err)
+ deleted, err := h.mgr.DeleteSessionWorkspaces(ctx, m, []string{userSessionA})
+ require.NoError(t, err)
+ require.Empty(t, deleted, "an attached terminal of A keeps A's directory until it leaves")
+ releasePTY()
+
+ deleted, err = h.mgr.DeleteSessionWorkspaces(ctx, m, []string{userSessionA})
+ require.NoError(t, err)
+ require.Equal(t, []string{userSessionA}, deleted)
+ _, connectsAfter, _, _, deletes := h.client.counts()
+ require.Greater(t, connectsAfter, connectsBefore, "deleting a session connects (and resumes) the machine")
+ require.Zero(t, deletes, "the shared machine itself stays")
+ cmd := lastExecRequest(t, h.client).Command
+ require.Contains(t, cmd, "/workspace/sessions/"+userSessionA)
+ require.Contains(t, cmd, "/var/lib/weknora/sessions/"+userSessionA+".git")
+ require.NotContains(t, cmd, userSessionB)
+ require.Contains(t, cmd, "-L", "symlinked parents are refused, not followed")
+}
+
+func TestDeleteSessionWorkspacesCompletesOnlyWhenTheMachineIsProvablyGone(t *testing.T) {
+ h := newUserManagerHarness(t)
+ m, _ := userAssignmentFor(userSessionA).UserMachine()
+ deleted, err := h.mgr.DeleteSessionWorkspaces(ownerCtx(), m, []string{userSessionA})
+ require.NoError(t, err)
+ require.Equal(t, []string{userSessionA}, deleted, "the provider lists nothing with this identity")
+}
+
+func TestDeleteSessionWorkspacesReadoptsAMachineWhoseBindingWasLost(t *testing.T) {
+ h := newUserManagerHarness(t, userAssignmentFor(userSessionA), userAssignmentFor(userSessionB))
+ // DefaultConfig closes inbound. This case is the provider that does not
+ // require a token, so re-adoption restores the same sandbox. A closed
+ // inbound policy must not bind the empty token; that is covered separately.
+ h.mgr.lifecycle.createRequest.Network.AllowPublicTraffic = nil
+ ctx := ownerCtx()
+ _, err := h.mgr.ExecShellCommand(ctx, userSessionA, "true", "", time.Second, nil)
+ require.NoError(t, err)
+ m, _ := userAssignmentFor(userSessionA).UserMachine()
+ sandboxID, _ := h.mgr.BoundSandboxID(ctx, userSessionA)
+ _, err = h.mgr.bindings.DeleteIfMatch(ctx, h.mgr.UserMachineKey(m), h.client.provider, sandboxID) // Redis lost it
+ require.NoError(t, err)
+
+ deleted, err := h.mgr.DeleteSessionWorkspaces(ctx, m, []string{userSessionA})
+ require.NoError(t, err)
+ require.Equal(t, []string{userSessionA}, deleted)
+ require.Contains(t, lastExecRequest(t, h.client).Command, "/workspace/sessions/"+userSessionA,
+ "the files are really deleted on the machine B will keep using")
+ rebound, _ := h.mgr.BoundSandboxID(ctx, userSessionB)
+ require.Equal(t, sandboxID, rebound, "re-adopted, not recreated")
+}
+
+func TestDeleteSessionWorkspacesKeepsTheTaskWhenAbsenceCannotBeProven(t *testing.T) {
+ h := newUserManagerHarness(t)
+ h.client.capabilities.SupportsListSandboxes = false
+ m, _ := userAssignmentFor(userSessionA).UserMachine()
+ deleted, err := h.mgr.DeleteSessionWorkspaces(ownerCtx(), m, []string{userSessionA})
+ require.ErrorIs(t, err, ErrMachineAbsenceUnprovable)
+ require.Empty(t, deleted)
+}
+
+func TestDeleteSessionWorkspacesStopsTheCommandWhenALeaseIsLost(t *testing.T) {
+ h := newUserManagerHarness(t, userAssignmentFor(userSessionA))
+ ctx := ownerCtx()
+ _, err := h.mgr.ExecShellCommand(ctx, userSessionA, "true", "", time.Second, nil)
+ require.NoError(t, err)
+ m, _ := userAssignmentFor(userSessionA).UserMachine()
+ h.client.execHook = func(req RemoteExecRequest) (*RemoteExecResult, error) {
+ if strings.Contains(req.Command, "rm -rf") {
+ h.admission.LoseBarrier(admission.SessionScope(m.Digest("weknora"), userSessionA))
+ time.Sleep(50 * time.Millisecond) // the cancellation reaches the call
+ return nil, context.Canceled
+ }
+ return &RemoteExecResult{}, nil
+ }
+ deleted, err := h.mgr.DeleteSessionWorkspaces(ctx, m, []string{userSessionA})
+ require.ErrorIs(t, err, admission.ErrLeaseLost)
+ require.Empty(t, deleted, "a deletion that may not have run is retried, not completed")
+}
+
+func TestInvalidateConfigSandboxesMarksUserMachines(t *testing.T) {
+ h := newUserManagerHarness(t, userAssignmentFor(userSessionA))
+ ctx := ownerCtx()
+ _, err := h.mgr.ExecShellCommand(ctx, userSessionA, "true", "", time.Second, nil)
+ require.NoError(t, err)
+ m, _ := userAssignmentFor(userSessionA).UserMachine()
+ h.allocs.machines = []allocation.UserMachine{m}
+
+ n, err := h.mgr.InvalidateConfigSandboxes(ctx, 42, "cfg-1")
+ require.NoError(t, err)
+ require.Equal(t, 1, n)
+ b, err := h.mgr.bindings.Get(ctx, h.mgr.UserMachineKey(m))
+ require.NoError(t, err)
+ require.NotNil(t, b.StaleAt)
+}
+
+func TestWorkspaceForkHoldsLeasesAndCopiesWithOneGuardedScript(t *testing.T) {
+ h := newUserManagerHarness(t, userAssignmentFor(userSessionA))
+ ctx := ownerCtx()
+ _, err := h.mgr.ExecShellCommand(ctx, userSessionA, "true", "", time.Second, nil)
+ require.NoError(t, err)
+ sha, older, foreign := strings.Repeat("c", 40), strings.Repeat("b", 40), strings.Repeat("e", 40)
+ h.client.execHook = func(req RemoteExecRequest) (*RemoteExecResult, error) {
+ if strings.Contains(req.Command, "uploadpack.allowAnySHA1InWant") {
+ return &RemoteExecResult{Stdout: "R " + sha + "\nR " + older + "\n"}, nil
+ }
+ return &RemoteExecResult{}, nil
+ }
+
+ fork, err := h.mgr.BeginWorkspaceFork(ctx, userSessionA)
+ require.NoError(t, err)
+ require.NotEmpty(t, fork.SandboxID())
+ machine, _ := userAssignmentFor(userSessionA).UserMachine()
+ active, err := h.admission.ActiveExcept(ctx, admission.MachineScope(machine.Digest("weknora")))
+ require.NoError(t, err)
+ require.Equal(t, 1, active, "the fork holds the machine until Release")
+
+ reachable, err := fork.Copy(userSessionB, sha, []string{sha, older, foreign})
+ require.NoError(t, err)
+ require.Equal(t, map[string]bool{sha: true, older: true}, reachable)
+ req := lastExecRequest(t, h.client)
+ require.Equal(t, "root", req.User)
+ require.Contains(t, req.Command, "/var/lib/weknora/sessions/"+userSessionA+".git")
+ require.Contains(t, req.Command, "/workspace/sessions/"+userSessionB)
+ require.Contains(t, req.Command, "core.hooksPath=/dev/null")
+ require.Contains(t, req.Command, `"160000"`, "gitlinks are refused")
+ require.Contains(t, req.Command, "merge-base --is-ancestor")
+
+ _, err = fork.Copy("not-a-uuid", sha, nil)
+ require.Error(t, err)
+ _, err = fork.Copy(userSessionB, "abc", nil)
+ require.Error(t, err)
+
+ require.NoError(t, fork.Remove(userSessionB))
+ require.Contains(t, lastExecRequest(t, h.client).Command, "/workspace/sessions/"+userSessionB)
+ fork.Release()
+ active, _ = h.admission.ActiveExcept(ctx, admission.MachineScope(machine.Digest("weknora")))
+ require.Zero(t, active)
+}
+
+func TestWorkspaceForkStopsAfterTheLeaseIsLost(t *testing.T) {
+ h := newUserManagerHarness(t, userAssignmentFor(userSessionA))
+ ctx := ownerCtx()
+ _, err := h.mgr.ExecShellCommand(ctx, userSessionA, "true", "", time.Second, nil)
+ require.NoError(t, err)
+ fork, err := h.mgr.BeginWorkspaceFork(ctx, userSessionA)
+ require.NoError(t, err)
+ defer fork.Release()
+ machine, _ := userAssignmentFor(userSessionA).UserMachine()
+ h.admission.ExpireMember(admission.MachineScope(machine.Digest("weknora")),
+ fork.(interface{ Member() string }).Member())
+
+ require.Eventually(t, func() bool {
+ _, err := fork.Copy(userSessionB, strings.Repeat("c", 40), nil)
+ return errors.Is(err, admission.ErrLeaseLost)
+ }, time.Second, 10*time.Millisecond)
+}
+
+func TestWorkspaceForkWithoutAMachineReportsNoLiveSandbox(t *testing.T) {
+ h := newUserManagerHarness(t, userAssignmentFor(userSessionA))
+ _, err := h.mgr.BeginWorkspaceFork(ownerCtx(), userSessionA)
+ require.ErrorIs(t, err, ErrNoLiveSessionSandbox, "fork never creates the source's machine")
+}
+
+func TestUserModeTerminalCreatesTheSessionDirectoryFirst(t *testing.T) {
+ h := newUserManagerHarness(t, userAssignmentFor(userSessionA), userAssignmentFor(userSessionB))
+ ctx := ownerCtx()
+ _, err := h.mgr.ExecShellCommand(ctx, userSessionA, "true", "", time.Second, nil)
+ require.NoError(t, err)
+
+ term, err := h.mgr.OpenSessionTerminal(ctx, userSessionB, RemoteTerminalOptions{})
+ require.NoError(t, err)
+ defer func() { _ = term.Close() }()
+
+ cmd := lastExecRequest(t, h.client).Command
+ require.Contains(t, cmd, "mkdir -p")
+ require.Contains(t, cmd, "/workspace/sessions/"+userSessionB)
+ require.Equal(t, "/workspace/sessions/"+userSessionB, h.client.lastTerminalOptions().Cwd)
+}
+
+func TestUserModeTerminalNeverReattachesAClientPID(t *testing.T) {
+ h := newUserManagerHarness(t, userAssignmentFor(userSessionA))
+ ctx := ownerCtx()
+ _, err := h.mgr.ExecShellCommand(ctx, userSessionA, "true", "", time.Second, nil)
+ require.NoError(t, err)
+ term, err := h.mgr.OpenSessionTerminal(ctx, userSessionA, RemoteTerminalOptions{AttachPID: 4242})
+ require.NoError(t, err)
+ defer func() { _ = term.Close() }()
+ opts := h.client.lastTerminalOptions()
+ require.Zero(t, opts.AttachPID, "a PID on a shared machine may belong to another session")
+ require.Equal(t, "/workspace/sessions/"+userSessionA, opts.Cwd)
+}
+
+func TestMultiReplicaRealRedisFirstAllocationCreatesOneMachine(t *testing.T) {
+ r1, r2, _ := multiReplicaPair(t, integrationEnv(t, "WEKNORA_TEST_REDIS_ADDR"),
+ userAssignmentFor(userSessionA), userAssignmentFor(userSessionB))
+ ctx := ownerCtx()
+ var wg sync.WaitGroup
+ errs := make(chan error, 8)
+ for i := 0; i < 8; i++ {
+ wg.Add(1)
+ go func(i int) {
+ defer wg.Done()
+ h, sid := r1, userSessionA
+ if i%2 == 1 {
+ h, sid = r2, userSessionB
+ }
+ _, err := h.mgr.ExecShellCommand(ctx, sid, "true", "", time.Second, nil)
+ errs <- err
+ }(i)
+ }
+ wg.Wait()
+ close(errs)
+ for err := range errs {
+ require.NoError(t, err)
+ }
+ creates, _, _, _, _ := r1.client.counts()
+ require.Equal(t, 1, creates, "two replicas racing the first exec create one shared machine")
+ a, okA := r1.mgr.BoundSandboxID(ctx, userSessionA)
+ b, okB := r2.mgr.BoundSandboxID(ctx, userSessionB)
+ require.True(t, okA)
+ require.True(t, okB)
+ require.NotEmpty(t, a)
+ require.Equal(t, a, b)
+}
+
+func TestMultiReplicaRealRedisLeaseBlocksRebuildAndReclaim(t *testing.T) {
+ r1, r2, _ := multiReplicaPair(t, integrationEnv(t, "WEKNORA_TEST_REDIS_ADDR"),
+ userAssignmentFor(userSessionA), userAssignmentFor(userSessionB))
+ ctx := ownerCtx()
+ _, err := r1.mgr.ExecShellCommand(ctx, userSessionA, "true", "", time.Second, nil)
+ require.NoError(t, err)
+ first, _ := r1.mgr.BoundSandboxID(ctx, userSessionA)
+ m, _ := userAssignmentFor(userSessionA).UserMachine()
+
+ _, closePTY, err := r2.mgr.HoldSessionOperation(ctx, userSessionB, "pty")
+ require.NoError(t, err)
+
+ _, err = r1.mgr.InvalidateConfigSandboxesForMachines(ctx, "cfg-1", []allocation.UserMachine{m})
+ require.NoError(t, err)
+ _, err = r1.mgr.ExecShellCommand(ctx, userSessionA, "true", "", time.Second, nil)
+ require.NoError(t, err)
+ kept, _ := r1.mgr.BoundSandboxID(ctx, userSessionA)
+ require.Equal(t, first, kept, "replica 2's terminal blocks replica 1's rebuild")
+
+ ok, err := r1.mgr.ReclaimUserMachine(ctx, m, func(context.Context) (bool, error) { return true, nil })
+ require.NoError(t, err)
+ require.False(t, ok, "and blocks reclaim")
+
+ closePTY()
+ _, err = r1.mgr.ExecShellCommand(ctx, userSessionA, "true", "", time.Second, nil)
+ require.NoError(t, err)
+ rebuilt, _ := r1.mgr.BoundSandboxID(ctx, userSessionA)
+ require.NotEqual(t, first, rebuilt)
+}
+
+func TestMultiReplicaRealRedisLostLeaseStopsTheHolderAndFreesTheMachine(t *testing.T) {
+ r1, r2, raw := multiReplicaPair(t, integrationEnv(t, "WEKNORA_TEST_REDIS_ADDR"),
+ userAssignmentFor(userSessionA), userAssignmentFor(userSessionB))
+ ctx := ownerCtx()
+ _, err := r1.mgr.ExecShellCommand(ctx, userSessionA, "true", "", time.Second, nil)
+ require.NoError(t, err)
+ m, _ := userAssignmentFor(userSessionA).UserMachine()
+
+ opCtx, release, err := r2.mgr.HoldSessionOperation(ctx, userSessionB, "desktop")
+ require.NoError(t, err)
+ defer release()
+
+ // Fault injection: the admission keys vanish (failover to a replica that
+ // had not received them, or an operator FLUSHDB).
+ keys, err := raw.Keys(ctx, "*"+m.Digest(r1.mgr.Namespace())+"*:ops").Result()
+ require.NoError(t, err)
+ require.NotEmpty(t, keys)
+ require.NoError(t, raw.Del(ctx, keys...).Err())
+
+ // HoldSessionOperation uses admission.DefaultHoldTTL. Renewal is ttl/3 and
+ // is not configurable from the test, so the wait is bounded by that TTL:
+ // a failed confirmation inside the margin reports the lease lost.
+ select {
+ case <-opCtx.Done():
+ require.ErrorIs(t, context.Cause(opCtx), admission.ErrLeaseLost)
+ case <-time.After(admission.DefaultHoldTTL):
+ t.Fatal("the holder kept running after its lease was gone")
+ }
+ n, err := raw.Exists(ctx, keys...).Result()
+ require.NoError(t, err)
+ require.Zero(t, n, "renewal must not resurrect a lost member")
+
+ ok, err := r1.mgr.ReclaimUserMachine(ctx, m, func(context.Context) (bool, error) { return true, nil })
+ require.NoError(t, err)
+ require.True(t, ok, "with the holder gone the machine can be reclaimed")
+}
diff --git a/internal/sandbox/tenant_resolver.go b/internal/sandbox/tenant_resolver.go
index 21b6a1948..f931a92e5 100644
--- a/internal/sandbox/tenant_resolver.go
+++ b/internal/sandbox/tenant_resolver.go
@@ -200,6 +200,7 @@ func (r *tenantSandboxResolver) Resolve(
Checker: r.deps.Checker,
SkipHealthProbe: true,
ConfigID: configID,
+ ConfigTenantID: tenantID,
Bootstrapper: r.deps.Bootstrapper,
Allocations: r.deps.Allocations,
Admission: r.deps.Admission,
diff --git a/internal/types/interfaces/sandbox_allocation.go b/internal/types/interfaces/sandbox_allocation.go
index 15d46e696..7cf28aaa6 100644
--- a/internal/types/interfaces/sandbox_allocation.go
+++ b/internal/types/interfaces/sandbox_allocation.go
@@ -32,6 +32,23 @@ type EmptyMachineCursor struct {
Digest string
}
+// EmptyMachineClaim is the identity a reclaimer verified under the row lock.
+type EmptyMachineClaim struct {
+ EmptySince time.Time
+ ConfigTenantID uint64
+ ConfigID string
+}
+
+// MachineReclaimLock is the open row lock from LockEmptyMachine.
+type MachineReclaimLock interface {
+ Claim() EmptyMachineClaim
+ // Abort releases the lock without deleting the row.
+ Abort()
+ // CommitDelete drops the row only if it is still empty at the same
+ // empty_since, then releases the lock. False means the row stayed.
+ CommitDelete() (bool, error)
+}
+
// PlacementPin is the (sandbox_config_id, sandbox_config_tenant_id) pair on
// the sessions row. A zero ConfigID means the session has no pin.
type PlacementPin struct {
@@ -61,6 +78,19 @@ type SandboxAllocationRepository interface {
// placement racing the deletion cannot land after it. Idempotent; results
// are in sessionIDs order.
RetireSessions(ctx context.Context, sessionIDs []string, at time.Time) ([]RetiredSession, error)
+ // DeleteSessionsRetiring soft-deletes the listed owner-scoped sessions and
+ // retires their assignments in one transaction. Missing rows are skipped.
+ // An error rolls back the entire batch, including queued workspace cleanup.
+ DeleteSessionsRetiring(ctx context.Context, tenantID uint64, idsByOwner map[string][]string,
+ at time.Time) ([]RetiredSession, error)
+ // RetireOwnerSessions retires every session of a Web account in one
+ // transaction: the account's own sessions in every tenant (including
+ // sessions that were never placed) and any session whose live assignment
+ // is on one of that account's machines. It releases those assignments,
+ // writes the cleanup task of a user-mode one, and sets empty_since on a
+ // machine this leaves empty. A later ClaimPlacement returns
+ // ErrSessionRetired.
+ RetireOwnerSessions(ctx context.Context, ownerID string, at time.Time) ([]RetiredSession, error)
HasSandboxCheckpoint(ctx context.Context, sessionID string) (bool, error)
ListUserMachinesByConfig(
@@ -82,6 +112,13 @@ type SandboxAllocationRepository interface {
// emptySince — the value the reclaimer verified — so a machine that was
// joined and emptied again meanwhile keeps its row and its new clock.
DeleteUserMachineIfEmptySince(ctx context.Context, digest string, emptySince time.Time) (bool, error)
+ // LockEmptyMachine locks the registry row when the machine has no live
+ // assignment and a non-nil empty_since. A nil lock means it is not
+ // reclaimable (missing row, a live session, or a cleared clock — a join
+ // clears the clock). The lock is held until Abort or CommitDelete, and
+ // that span must cover the provider delete: a placement takes the same
+ // row lock before its assignment exists.
+ LockEmptyMachine(ctx context.Context, digest string) (MachineReclaimLock, error)
DeleteUserMachinesByConfig(ctx context.Context, configTenantID uint64, configID string) error
// ListDueWorkspaceCleanups returns released assignments whose directory
diff --git a/website-docs/01-getting-started/04-configuration.md b/website-docs/01-getting-started/04-configuration.md
index 8fa548281..40cab4b84 100644
--- a/website-docs/01-getting-started/04-configuration.md
+++ b/website-docs/01-getting-started/04-configuration.md
@@ -174,6 +174,7 @@ flowchart LR
| `REDIS_ADDR` / `REDIS_USERNAME` / `REDIS_PASSWORD` / `REDIS_DB` / `REDIS_PREFIX` | redis:6379 / … | Redis 连接 |
| `REDIS_USE_TLS` | false | **启用 TLS 的总开关**,托管 Redis(如 AWS ElastiCache)需要打开;`REDIS_TLS_SERVER_NAME` 指定校验与 SNI 用的服务器名(地址是 IP 时有用),`REDIS_TLS_INSECURE_SKIP_VERIFY` 跳过证书校验(不安全,仅自签证书的开发环境用) |
| `WEKNORA_REDIS_NAMESPACE` | 空 | 多部署共用 Redis 时的频道命名空间后缀 |
+| `WEKNORA_SANDBOX_USER_ALLOCATION` | 空 | 设为 `enabled` 后,沙箱配置可选择「同一用户的会话共用一台沙箱」。必须在所有实例升级完成后再在所有实例上设置,且需要 Redis;未满足时该选项不可保存,已保存的配置在分配时回退为每会话一台。 |
| `WEKNORA_ASYNQ_CORE_CONCURRENCY` 等 | 8 / 2 / 12 / 4 / 6 | Asynq 各队列并发(core/postprocess/enrichment/maintenance/shared),另有 `WEKNORA_WIKI_ASYNQ_CONCURRENCY=8`、`WEKNORA_MODEL_MAX_CONCURRENCY=32` |
### 检索引擎与向量库
diff --git a/website-docs/03-features/22-skills-sandbox.md b/website-docs/03-features/22-skills-sandbox.md
index ed8f2a535..b6d4a5bb8 100644
--- a/website-docs/03-features/22-skills-sandbox.md
+++ b/website-docs/03-features/22-skills-sandbox.md
@@ -145,6 +145,45 @@ macOS 桌面版可在「工具箱 → 技能管理」将技能安装到「本机
caption="沙箱可视化面板:在对话旁查看产物、使用终端和桌面"
hint="展示一个使用 Cube 或 E2B 沙箱的对话,右侧「沙箱可视化」面板切换到「终端」标签,终端内有带颜色的 user@host 提示符和一条命令输出;面板顶部可见「产物 / 终端 / 桌面」三个标签。" />
+## 沙箱分配方式
+
+远程沙箱(Docker、CubeSandbox、E2B)有两种分配方式。Lite 的本机沙箱不受影响。
+
+| 方式 | 何时使用 | 会话看到什么 |
+| --- | --- | --- |
+| 每会话一台(默认) | 配置保持会话模式,或下面任一条件不满足 | 该会话独占一台沙箱,工作目录仍是 `/workspace` |
+| 同一用户共用一台 | 环境变量已开启,配置选了共用,且会话属于可共用的身份 | 同一位所有者、同一份配置上的会话共用一台沙箱。每个会话的目录是 `/workspace/sessions/<会话 ID>`,检查点仓库在 `/var/lib/weknora/sessions/<会话 ID>.git` |
+
+切换只影响还没有用过沙箱的会话。已经钉住沙箱配置、已经有检查点,或分叉后还没完成首次准备的会话,继续用自己原来的那一台。
+
+能进共用机器的只有两类身份:Web 登录账号,以及带外部用户标识的 API 调用。同一把 API Key、但不带外部用户的两个会话各用一台沙箱,分配行的 `machine_digest` 为空,分配日志的原因是 `SHARED_API_KEY`。
+
+共用一台时,设计上的风险(设计文档 §5.2.1)是:
+
+- 沙箱里的命令以 root 运行,同一台机器上的会话之间没有操作系统级的隔离。
+- 磁盘是共享的。工具会把读写限制在本会话目录里,但 root 命令不受这层限制。
+- 进程互相可见。
+- 一台机器上没有会话数量上限。
+
+空置保留天数写在沙箱配置上。`0` 表示用默认的 7 天,也可以填 1 到 90。它从「这台机器上已经没有存活会话」开始算,到点后回收任务可以删掉这台机器。它不是机器的最短寿命,也不是会话至少保留这么久:还有会话在用时不会按这个天数拆机,未到天数也不会因为空置就提前删。
+
+删除一个共用会话会先把暂停的沙箱唤醒,再删掉这个会话的目录和检查点仓库。同一台机器上其他会话的目录还在。
+
+共用机器上的终端不会按客户端传来的进程号重连旧 shell:那个进程可能属于另一个会话。本会话的终端还开着时,把本会话 rewind 到旧检查点会返回忙;同一台机器上其他会话不受影响。
+
+滚动升级按这个顺序做:
+
+1. 把新版本部署到所有实例,先不要设置 `WEKNORA_SANDBOX_USER_ALLOCATION`。新实例会给会话写下 `machine_digest` 为空的分配记录;还没升级的实例不读这张表,行为与升级前一致。
+2. 确认每个实例都是新版本之后,在所有实例上设置 `WEKNORA_SANDBOX_USER_ALLOCATION=enabled` 并滚动重启。需要 Redis。
+3. 再由管理员把某一份沙箱配置改成共用。
+4. 回退到旧版本之前,先确认没有仍在使用的共用机器。分配表没有 `mode` 列,共用与否看 `machine_digest` 是否为空:
+
+```sql
+SELECT count(*) FROM session_sandbox_assignments WHERE machine_digest <> '' AND released_at IS NULL;
+```
+
+结果为 0 才能无损回退。否则先把配置改回每会话一台,并按设计文档处理还在的用户机器。
+
## 部署与排障
Docker socket/TLS、模板版本、远端网关、多副本 Redis、技能快照磁盘占用、终端与桌面中继以及 Lite 本机沙箱的构建要求见[沙箱部署与排障](../06-development/04-sandbox-deployment.md)。