feat(session): fork conversations from a historical user message (#3304)

* feat(session): add fork schema and history queries

为会话分叉增加数据模型与迁移,并提供截至分叉点的消息查询以及会话内的 request_id 配对。

* feat(sandbox): add git, fork snapshots, and bootstrap hook

沙箱镜像安装 git,Docker 快照使用独立的 fork 命名空间,并在首次创建会话沙箱时接入可选 bootstrap。

* feat(session): checkpoint workspace at the end of each turn

每轮结束后对沙箱 /workspace 打 git checkpoint,并避免 fork 后因 mtime 刷新重复挂上产物、以及附件仍绑在父会话而无法还原。

* feat(session): fork conversations and reap orphan snapshots

支持从历史 user 消息分叉会话、首次打开时从快照 bootstrap,并在失败或删除未打开的分叉时回收孤儿快照。

* feat(chat): add session fork entry, prefill, and badges

在用户消息上提供分叉入口,进入新会话时预填原问题,并展示降级提示与来源角标。

* style: add missing newline so session_fork_delete_test.go is gofmt-clean

* fix(session): prune later git history when rolling a fork workspace back

reset --hard 只还原工作区,分叉点之后的 commit 仍可被 checkout。校验 SHA 后丢掉其他 ref 并 gc,避免错误基线。

* style(session): clear golangci-lint findings on the session-fork diff

Pre-push lints the whole PR against main; wrap long lines, check c.Error,
and fix gofumpt/revive/staticcheck so the merge can be pushed.

* fix(chat): show the fork button on hover without shifting the thread

Overlay the action so revealing it no longer expands the user bubble and janks the messages below.

* fix(chat): drop the fork landing banners

Keep the original question prefilled; do not explain sandbox snapshot vs checkpoint on the new thread.

* fix(agent): dedupe artifacts by content hash, not size

Same-path same-size rewrites were skipped as restores. Keep path+mtime as the cheap skip, hash bytes when mtime moves, and stamp the restored mtime onto this session only.

* feat(session): allow forking from an assistant answer

User forks still copy history before the question and prefill it. Assistant forks copy through that reply and reuse its checkpoint, with a degrade tooltip when none exists.

* fix(session): resolve parent attachments from a forked chat

Fork copies attachment IDs onto the new messages but leaves temporary_documents on the parent. Preview and Get now look up those IDs on the fork's copied history instead of a scoped miss.

* fix(agent): rewrite sandbox refs after a content-hash skip

Fork restores change mtime on unchanged files, so Collect returns empty
and named citations were left as sandbox: paths. Resolve those names
against session artifacts, notify only real uploads, and stamp restored
mtime only on the matching content hash.

* fix(session): drop a dead fork snapshot and retry checkpoint rewrite

Create from a missing template now abandons bootstrap so the next
Resolve uses a normal sandbox. A failed checkpoint rewrite no longer
marks the bootstrap consumed, which previously made nested forks
SANDBOX_REPLACED.

* fix(session): load forked parent attachments into the prompt

ResolveForPrompt used session-scoped lookup, so copied parent attachment
IDs passed Get but never reached the model. Use the same resolveInSession
path as preview.

* fix(chat): keep the user-message fork button visible

The control was hover-only, which hid it on touch. Always show it, and
drop the unused degrade tooltip.

---------

Co-authored-by: hailongzhao <hailongzhao@tencent.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
main
nullptr-error 2026-09-17 14:20:18 +08:00 committed by GitHub
parent c9d5987a5d
commit 42e6163981
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
90 changed files with 8271 additions and 266 deletions

View File

@ -56,7 +56,8 @@ RUN npm install -g pnpm
# image). `file` is not in slim; models reach for it after a script-type error.
# curl is not optional: the sandbox connectivity check probes egress with it,
# and skills that fetch a URL expect it to be there. The compression tools are
# here because skill bundles and their assets arrive archived.
# here because skill bundles and their assets arrive archived. git backs the
# per-turn /workspace checkpoints that session fork rolls back to.
RUN apt-get update && apt-get install -y --no-install-recommends \
jq \
curl \
@ -67,6 +68,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
bzip2 \
xz-utils \
zstd \
git \
&& rm -rf /var/lib/apt/lists/* /var/cache/apt/*
# Add packages here when installed skills actually need them:

View File

@ -30,6 +30,13 @@ export async function updateSession(session_id: string, data: { title: string; d
return put(`/api/v1/sessions/${session_id}`, data);
}
export async function forkSession(
session_id: string,
data: { message_id: string; title?: string },
) {
return post(`/api/v1/sessions/${session_id}/fork`, data, { timeout: 180000 });
}
export async function knowledgeChat(data: { session_id: string; query: string; }) {
return postChat(`/api/v1/knowledge-chat/${data.session_id}`, { query: data.query, channel: "web" });
}

View File

@ -2614,6 +2614,14 @@ defineExpose({
if (!text.trim()) return;
query.value = text;
nextTick(() => createSession(text));
},
/**
* Puts text in the composer WITHOUT sending it. Session fork uses this so
* the user lands on the branch with the original question ready to edit —
* the whole point of branching at a user message.
*/
prefill(text: string) {
query.value = text;
}
});

View File

@ -14,6 +14,9 @@
</form>
<span v-else class="submenu_title" :class="batchMode ? 'submenu_title--batch' : ''" :title="item.title">
<t-icon v-if="item.is_pinned" name="pin" class="submenu_pin_icon" />
<t-tooltip v-if="item.parent_session_id" content="由其他会话分叉而来">
<t-icon name="git-branch" class="submenu_fork_icon" />
</t-tooltip>
<span class="submenu_title-text">{{ item.title }}</span>
<span v-if="apiOwnerTag" class="session-owner-tag" :class="`session-owner-tag--${apiOwnerTag.kind}`"
:title="apiOwnerTag.full">{{ apiOwnerTag.label }}</span>
@ -77,7 +80,7 @@ interface SessionMenuOption {
type MenuMode = 'menu' | 'clear' | 'delete'
const props = defineProps<{
item: { id: string; path: string; title: string; is_pinned?: boolean; user_id?: string }
item: { id: string; path: string; title: string; is_pinned?: boolean; user_id?: string; parent_session_id?: string }
batchMode: boolean
activePath: string
selectedIds: string[]

View File

@ -699,6 +699,7 @@ const mapSessionRow = (item: any) => ({
im_platform: item.im_platform || '',
description: item.description || '',
user_id: item.user_id || '',
parent_session_id: item.parent_session_id || '',
});
const syncMenuStoreFromBuckets = () => {
@ -720,6 +721,7 @@ const menuChildToSessionRow = (item: Record<string, unknown>): SessionForGroupin
im_platform: typeof item.im_platform === 'string' ? item.im_platform : '',
description: typeof item.description === 'string' ? item.description : '',
user_id: typeof item.user_id === 'string' ? item.user_id : '',
parent_session_id: typeof item.parent_session_id === 'string' ? item.parent_session_id : '',
};
};
@ -1501,6 +1503,14 @@ const onDragHandleMouseDown = (e: MouseEvent) => {
flex-shrink: 0;
}
:deep(.submenu_fork_icon) {
color: inherit;
font-size: 12px;
margin-right: 4px;
vertical-align: middle;
flex-shrink: 0;
}
.submenu_source_icon {
width: 14px;
height: 14px;

View File

@ -23,6 +23,7 @@ export interface SessionForGrouping {
im_platform?: string
description?: string
user_id?: string
parent_session_id?: string
originalIndex?: number
}

View File

@ -384,6 +384,11 @@
</div>
<div v-if="answerFullyRendered && event.done && event.content && event.content.trim() && !embeddedMode"
class="answer-toolbar">
<t-tooltip v-if="canFork" :content="forkTooltip">
<t-button size="small" variant="outline" shape="round" @click.stop="emitFork">
<t-icon name="git-branch" />
</t-button>
</t-tooltip>
<t-button size="small" variant="outline" shape="round" @click.stop="handleCopyAnswer(event)"
:title="$t('agent.copy')">
<t-icon name="copy" />
@ -961,12 +966,21 @@ const props = defineProps<{
embedVisitorId?: string;
ragMode?: boolean;
followUpLoading?: boolean;
canFork?: boolean;
}>();
const emit = defineEmits<{
(event: 'render-complete-change', ready: boolean): void;
(event: 'fork', messageId: string): void;
}>();
const canFork = computed(() => props.canFork === true && !props.embeddedMode)
const forkTooltip = '从这条回答继续分叉'
const emitFork = () => {
const messageId = persistedAssistantId(props.session) || String(props.session?.id || '')
if (messageId) emit('fork', messageId)
}
const embedAuthProps = computed(() => ({
embeddedMode: props.embeddedMode,
embedChannelId: props.embedChannelId,

View File

@ -18,6 +18,9 @@
<RagPipelineProgress :session="session" :embedded-mode="embeddedMode" />
<AgentStreamDisplay v-if="session.isAgentMode" :session="session" :session-id="sessionId"
:user-query="userQuery" :rag-mode="true" :follow-up-loading="followUpLoading"
:embedded-mode="embeddedMode"
:can-fork="canFork"
@fork="emit('fork', $event)"
@render-complete-change="emit('render-complete-change', $event)" />
</div>
<template v-else>
@ -30,6 +33,9 @@
<docInfo v-if="session.knowledge_references?.length" :session="session"></docInfo>
<AgentStreamDisplay :session="session" :session-id="sessionId" :user-query="userQuery"
v-if="session.isAgentMode" :follow-up-loading="followUpLoading"
:embedded-mode="embeddedMode"
:can-fork="canFork"
@fork="emit('fork', $event)"
@render-complete-change="emit('render-complete-change', $event)" />
</template>
<deepThink :deepSession="session" v-if="session.showThink && !session.isAgentMode"></deepThink>
@ -44,6 +50,11 @@
</div>
<!-- 复制和添加到知识库按钮 - 非 Agent 模式下显示 -->
<div v-if="answerFullyRendered && (content || session.content)" class="answer-toolbar">
<t-tooltip v-if="canFork" :content="forkTooltip">
<t-button size="small" variant="outline" shape="round" @click.stop="emitFork">
<t-icon name="git-branch" />
</t-button>
</t-tooltip>
<t-button size="small" variant="outline" shape="round" @click.stop="handleCopyAnswer"
:title="$t('agent.copy')">
<t-icon name="copy" />
@ -161,7 +172,7 @@ const mentionTagIcon = (item) => {
return 'file';
};
const emit = defineEmits(['scroll-bottom', 'render-complete-change'])
const emit = defineEmits(['scroll-bottom', 'render-complete-change', 'fork'])
const { t } = useI18n()
const uiStore = useUIStore();
let parentMd = ref()
@ -202,9 +213,20 @@ const props = defineProps({
followUpLoading: {
type: Boolean,
default: false
},
canFork: {
type: Boolean,
default: false
}
});
const canFork = computed(() => props.canFork === true && !props.embeddedMode)
const forkTooltip = '从这条回答继续分叉'
const emitFork = () => {
const messageId = persistedAssistantId(props.session) || props.session?.id
if (messageId) emit('fork', messageId)
}
const showRequestInfo = computed(() => !!(props.session?.request_id || props.session?.id));
// -----------------------------------------------------------------------------

View File

@ -43,6 +43,18 @@
<div class="user_msg">
{{ content }}
</div>
<div v-if="canFork" class="user_msg_actions">
<t-tooltip :content="forkTooltip">
<t-button
variant="text"
size="small"
class="user_msg_action"
@click="emit('fork', messageId)"
>
<t-icon name="git-branch" />
</t-button>
</t-tooltip>
</div>
<div v-if="steerFailed" class="steer-failure" role="status">
<span>{{ t('input.messages.steerFailed') }}</span>
<t-tooltip :content="t('input.steerRetry')"><button type="button" :aria-label="t('input.steerRetry')" @click="emit('retry-steer')"><t-icon name="refresh" /></button></t-tooltip>
@ -59,7 +71,7 @@ import { useI18n } from 'vue-i18n';
import { useChatAttachmentPreviewDrawer } from '@/composables/useChatAttachmentPreviewDrawer';
import { isPreviewableAttachment, resolveAttachmentFileType } from '@/utils/attachmentPreview';
import { SKILL_ICON } from '@/types/mention';
const emit = defineEmits(['retry-steer', 'remove-steer']);
const emit = defineEmits(['retry-steer', 'remove-steer', 'fork']);
const { t } = useI18n();
@ -108,9 +120,20 @@ const props = defineProps({
sessionId: {
type: String,
default: ''
},
messageId: {
type: String,
default: ''
},
canFork: {
type: Boolean,
default: false
}
});
const canFork = computed(() => props.canFork === true && !props.embeddedMode);
const forkTooltip = '从这里分叉出新会话';
const attachmentPreviewDrawer = useChatAttachmentPreviewDrawer();
const channelLabelMap = {
@ -195,6 +218,7 @@ const closePreImg = () => {
@import '../../../components/css/chat-resource-chips.less';
.user_msg_container {
position: relative;
display: flex;
flex-direction: column;
align-items: flex-end;
@ -370,4 +394,10 @@ html[theme-mode="dark"] {
.steer-failure { margin-top: 6px; color: var(--td-error-color); }
.steer-failure button { display: inline-flex; align-items: center; justify-content: center; width: 26px; height: 26px; border: 0; border-radius: 6px; background: transparent; color: inherit; cursor: pointer; }
.steer-failure button:hover { background: var(--td-bg-color-secondarycontainer); }
.user_msg_actions {
display: flex;
justify-content: flex-end;
padding-top: 2px;
}
</style>

View File

@ -0,0 +1,51 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { resolveForkAffordance } from './forkPoint'
test('第一条 user 消息可以分叉', () => {
const messages = [
{ id: 'u1', role: 'user' },
{ id: 'a1', role: 'assistant' },
]
assert.deepEqual(resolveForkAffordance(messages, 'u1'), { canFork: true })
})
test('前置 assistant 无论有没有 checkpoint 都可以分叉', () => {
const messages = [
{ id: 'u1', role: 'user' },
{ id: 'a1', role: 'assistant' },
{ id: 'u2', role: 'user' },
]
assert.deepEqual(resolveForkAffordance(messages, 'u2'), { canFork: true })
})
test('assistant 消息可以分叉', () => {
const messages = [
{ id: 'u1', role: 'user' },
{ id: 'a1', role: 'assistant', is_completed: true },
]
assert.deepEqual(resolveForkAffordance(messages, 'a1'), { canFork: true })
})
test('未知角色不能作为分叉点', () => {
const messages = [
{ id: 'u1', role: 'user' },
{ id: 's1', role: 'system' },
]
assert.deepEqual(resolveForkAffordance(messages, 's1'), { canFork: false })
})
test('未知消息 ID 不能分叉', () => {
assert.deepEqual(
resolveForkAffordance([{ id: 'u1', role: 'user' }], 'nope'),
{ canFork: false },
)
})
test('未完成的 assistant 消息意味着本轮还在跑,不给分叉', () => {
const messages = [
{ id: 'u1', role: 'user' },
{ id: 'a1', role: 'assistant', is_completed: false },
]
assert.deepEqual(resolveForkAffordance(messages, 'u1'), { canFork: false })
})

View File

@ -0,0 +1,45 @@
/**
* Fork affordance rules, kept as a pure function so they can be tested without
* mounting the chat view.
*
* The backend re-derives all of this; this is purely so the UI can show the
* right button state without an extra round trip.
*
* User messages fork *at* the question (history excludes it, composer prefills
* it). Assistant messages fork *after* the answer (history includes it).
*/
export interface ForkCandidateMessage {
id?: unknown
role?: unknown
is_completed?: unknown
}
export interface ForkAffordance {
/** Whether the fork button should be offered on this message at all. */
canFork: boolean
}
const REFUSED: ForkAffordance = { canFork: false }
export function resolveForkAffordance(
messages: ForkCandidateMessage[],
messageId: string,
): ForkAffordance {
const index = messages.findIndex((m) => m.id === messageId)
if (index < 0) {
return REFUSED
}
// A turn still streaming means the source session holds an active sandbox
// lease. The backend would answer 409, so do not offer the button.
if (messages.some((m) => m.role === 'assistant' && m.is_completed === false)) {
return REFUSED
}
const target = messages[index]
if (target.role === 'assistant' || target.role === 'user') {
return { canFork: true }
}
return REFUSED
}

View File

@ -109,9 +109,12 @@
<usermsg :content="session.content" :mentioned_items="session.mentioned_items"
:images="session.images" :attachments="session.attachments" :embeddedMode="embeddedMode"
:session-id="session_id"
:message-id="session.id"
:can-fork="!embeddedMode && forkAffordanceOf(session.id).canFork"
:steer-failed="Boolean(session._steerFailed)"
@retry-steer="handleRetrySteer(session.steer_id)"
@remove-steer="handleRemoveSteer(session.steer_id)">
@remove-steer="handleRemoveSteer(session.steer_id)"
@fork="handleFork">
</usermsg>
</div>
<div v-if="session.role == 'assistant' && shouldRenderAssistantMessage(session)"
@ -120,6 +123,8 @@
:user-query="getUserQuery(index)" @scroll-bottom="scrollToBottom"
:isFirstEnter="isFirstEnter" :embeddedMode="embeddedMode"
:follow-up-loading="Boolean(session.suggestionLoading && !session.suggestionSet?.questions?.length)"
:can-fork="!embeddedMode && forkAffordanceOf(session.id).canFork"
@fork="handleFork"
@render-complete-change="(ready) => handleAnswerRenderComplete(session, ready)">
</botmsg>
<FollowUpSuggestions v-if="session.answerFullyRendered && !session.steerForked && !session.suggestionsDismissed"
@ -176,11 +181,12 @@
import { makeSteerClientId } from '@/utils/steerId';
import { storeToRefs } from 'pinia';
import { ref, onMounted, onBeforeMount, onUnmounted, nextTick, watch, reactive, computed } from 'vue';
import { useRoute, onBeforeRouteLeave, onBeforeRouteUpdate } from 'vue-router';
import { useRoute, useRouter, onBeforeRouteLeave, onBeforeRouteUpdate } from 'vue-router';
import InputField from '../../components/Input-field.vue';
import botmsg from './components/botmsg.vue';
import usermsg from './components/usermsg.vue';
import { getMessageList, getSession } from "@/api/chat/index";
import { getMessageList, getSession, forkSession } from "@/api/chat/index";
import { resolveForkAffordance } from './forkPoint';
import { getSuggestedQuestions } from "@/api/agent/index";
import { deleteTemporaryAttachment, uploadTemporaryAttachment } from '@/api/chat/temporary-attachments';
import { useStream } from '../../api/chat/streame'
@ -277,6 +283,7 @@ const attachStreamDebugToMessage = (message) => {
message.debugRequest = payload;
};
const route = useRoute();
const router = useRouter();
const session_id = ref(props.session_id || route.params.chatid);
const currentSession = ref(null);
@ -303,6 +310,102 @@ const inputFieldRef = ref();
const created_at = ref('');
const limit = ref(20);
const messagesList = reactive([]);
function forkAffordanceOf(messageId) {
if (!messageId) return { canFork: false }
return resolveForkAffordance(messagesList, messageId)
}
const FORK_PREFILL_KEY = 'weknora:fork-prefill'
let forkInFlight = false
function stashForkLanding(sessionId, text) {
const payload = JSON.stringify({ sessionId, text })
try {
sessionStorage.setItem(FORK_PREFILL_KEY, payload)
} catch {
// sessionStorage can throw in private mode; landing still navigates.
}
}
function readForkLanding() {
try {
const raw = sessionStorage.getItem(FORK_PREFILL_KEY)
if (!raw) return null
const parsed = JSON.parse(raw)
if (!parsed || typeof parsed !== 'object') return null
return {
sessionId: String(parsed.sessionId || ''),
text: String(parsed.text || ''),
}
} catch {
return null
}
}
function clearForkLanding() {
try {
sessionStorage.removeItem(FORK_PREFILL_KEY)
} catch {
// ignore
}
}
function applyForkLanding() {
const landed = readForkLanding()
if (!landed || landed.sessionId !== String(session_id.value || '')) {
return false
}
clearForkLanding()
inputFieldRef.value?.prefill(landed.text)
return true
}
async function handleFork(messageId) {
if (props.embeddedMode) return
if (forkInFlight) return
if (!messageId || !session_id.value) return
const source = messagesList.find((m) => m.id === messageId)
if (!source) return
const sourceSessionId = session_id.value
forkInFlight = true
try {
const res = await forkSession(sourceSessionId, { message_id: messageId })
const data = res?.data
if (!data?.session_id) return
// Carry the question across navigation in sessionStorage: the chat view
// is reused across chat/:chatid, and history reload / composer reset
// would clobber an in-memory prefill if we applied it too early.
const prefill = source.role === 'user' ? String(source.content ?? '') : ''
stashForkLanding(data.session_id, prefill)
const now = new Date().toISOString()
const sourceTitle = currentSession.value?.title || t('menu.newSession')
usemenuStore.updataMenuChildren({
id: data.session_id,
path: `chat/${data.session_id}`,
title: `${sourceTitle}(分支)`,
parent_session_id: sourceSessionId,
isMore: false,
isNoTitle: false,
created_at: now,
updated_at: now,
})
await router.push(`/platform/chat/${data.session_id}`)
} catch (err) {
if (err?.status === 409 || err?.$httpStatus === 409) {
MessagePlugin.warning('请等本轮回答结束后再分叉')
return
}
MessagePlugin.error('分叉失败,请重试')
} finally {
forkInFlight = false
}
}
const sessionArtifacts = computed(() => collectSessionArtifacts(messagesList));
const sessionArtifactsCollecting = computed(() =>
messagesList.some((message) => isCollectingSkillArtifacts(message)),
@ -332,6 +435,14 @@ watch([activitySessionId, isReplying, isStreaming, isImRecovering, currentAssist
const historyLoading = ref(true);
const historyLoadingMore = ref(false);
const hasMoreHistory = ref(true);
// Prefill after THIS session's history load settles. A messagesList watch
// would fire on the splice-to-empty that starts a session switch and then
// get clobbered by composer reset / history mount.
watch(historyLoading, (loading) => {
if (loading) return
applyForkLanding()
}, { flush: 'post' })
let fullContent = ref('')
const scrollContainer = ref(null)
const userHasScrolledUp = ref(false)

View File

@ -139,6 +139,10 @@ export default defineConfig({
// 沙箱终端等 WebSocket 升级请求也走 /api,必须开启 WS 转发,
// 否则浏览器侧握手失败、前端表现为"一直正在连接"。
ws: true,
// Cube fork snapshots pause a live MicroVM; 30s axios/proxy defaults
// abort the POST and the backend then 500s on a canceled persist.
timeout: 180_000,
proxyTimeout: 180_000,
},
'/files': {
target: DEV_PROXY_TARGET,
@ -159,6 +163,8 @@ export default defineConfig({
changeOrigin: true,
secure: false,
ws: true,
timeout: 180_000,
proxyTimeout: 180_000,
},
'/files': {
target: DEV_PROXY_TARGET,

View File

@ -46,12 +46,18 @@ func (r *messageRepository) GetMessage(
return &message, nil
}
// GetMessagesBySession retrieves all messages for a session with pagination
// GetMessagesBySession retrieves all messages for a session with pagination.
//
// The secondary sort on id is not cosmetic: messages created in the same
// millisecond would otherwise come back in an order the database is free to
// vary between calls, which makes a fork boundary drawn at one of them
// irreproducible.
func (r *messageRepository) GetMessagesBySession(
ctx context.Context, sessionID string, page int, pageSize int,
) ([]*types.Message, error) {
var messages []*types.Message
if err := r.db.WithContext(ctx).Where("session_id = ?", sessionID).Order("created_at ASC").
if err := r.db.WithContext(ctx).Where("session_id = ?", sessionID).
Order("created_at ASC, id ASC").
Offset((page - 1) * pageSize).Limit(pageSize).Find(&messages).Error; err != nil {
return nil, err
}
@ -135,6 +141,27 @@ func (r *messageRepository) ListMessagesBySessionAfterCursor(ctx context.Context
return messages, err
}
// ListMessagesBySessionUpTo returns every message of a session that sorts
// strictly before the (boundary, boundaryID) cursor, oldest first.
//
// The cursor is composite rather than a bare timestamp because a fork boundary
// must be reproducible: two messages written in the same millisecond are
// ordered by ID, and the caller's boundary message must be excluded regardless
// of how many peers share its timestamp.
func (r *messageRepository) ListMessagesBySessionUpTo(
ctx context.Context, sessionID string, boundary time.Time, boundaryID string,
) ([]*types.Message, error) {
var messages []*types.Message
if err := r.db.WithContext(ctx).
Where("session_id = ?", sessionID).
Where("created_at < ? OR (created_at = ? AND id < ?)", boundary, boundary, boundaryID).
Order("created_at ASC, id ASC").
Find(&messages).Error; err != nil {
return nil, err
}
return messages, nil
}
// UpdateMessage updates an existing message.
func (r *messageRepository) UpdateMessage(ctx context.Context, message *types.Message) error {
return r.db.WithContext(ctx).Model(&types.Message{}).Where(
@ -275,11 +302,12 @@ func (r *messageRepository) GetMessagesByKnowledgeIDs(
return results, nil
}
// GetMessagesByRequestIDs retrieves messages by their request IDs (used to fetch Q&A pair partners)
// GetMessagesByRequestIDs retrieves messages by request ID inside one session
// (used to fetch Q&A pair partners). Empty sessionID is treated as no match.
func (r *messageRepository) GetMessagesByRequestIDs(
ctx context.Context, requestIDs []string,
ctx context.Context, sessionID string, requestIDs []string,
) ([]*types.MessageWithSession, error) {
if len(requestIDs) == 0 {
if sessionID == "" || len(requestIDs) == 0 {
return nil, nil
}
var results []*types.MessageWithSession
@ -288,6 +316,7 @@ func (r *messageRepository) GetMessagesByRequestIDs(
Select("messages.*, sessions.title as session_title").
Joins("INNER JOIN sessions ON sessions.id = messages.session_id AND sessions.deleted_at IS NULL").
Where("messages.deleted_at IS NULL").
Where("messages.session_id = ?", sessionID).
Where("messages.request_id IN ?", requestIDs).
Find(&results).Error; err != nil {
return nil, err
@ -379,6 +408,73 @@ func (r *messageRepository) GetSessionArtifacts(
return result, nil
}
// RewriteSandboxCheckpoints retargets copied checkpoints onto the forked
// session's live sandbox. CommitSHA / CommittedAt are left untouched: the git
// objects are in the snapshot, only the sandbox identity changed.
func (r *messageRepository) RewriteSandboxCheckpoints(
ctx context.Context, sessionID, oldSandboxID, newSandboxID string,
) error {
if sessionID == "" || oldSandboxID == "" || newSandboxID == "" || oldSandboxID == newSandboxID {
return nil
}
var messages []*types.Message
if err := r.db.WithContext(ctx).
Where("session_id = ?", sessionID).
Find(&messages).Error; err != nil {
return err
}
for _, message := range messages {
if message == nil || message.SandboxCheckpoint == nil {
continue
}
if message.SandboxCheckpoint.SandboxID != oldSandboxID {
continue
}
updated := *message.SandboxCheckpoint
updated.SandboxID = newSandboxID
if err := r.db.WithContext(ctx).
Model(&types.Message{}).
Where("id = ? AND session_id = ?", message.ID, sessionID).
Update("sandbox_checkpoint", updated).Error; err != nil {
return err
}
}
return nil
}
// RecordRestoredArtifactMtime updates ModTime (and ContentHash) on artifacts
// in this session whose source path matches a same-content sandbox restore.
func (r *messageRepository) RecordRestoredArtifactMtime(
ctx context.Context, sessionID, sourcePath string, mod time.Time, hash string,
) error {
if sessionID == "" || sourcePath == "" {
return nil
}
var messages []*types.Message
if err := r.db.WithContext(ctx).
Select("id", "session_id", "artifacts").
Where("session_id = ?", sessionID).
Find(&messages).Error; err != nil {
return err
}
for _, message := range messages {
if message == nil {
continue
}
updated, changed := message.Artifacts.WithRestoredMtime(sourcePath, mod, hash)
if !changed {
continue
}
if err := r.db.WithContext(ctx).
Model(&types.Message{}).
Where("id = ? AND session_id = ?", message.ID, sessionID).
Update("artifacts", updated).Error; err != nil {
return err
}
}
return nil
}
// GetSessionAttachments returns every user-uploaded attachment in creation
// order while projecting only the attachments JSON column.
func (r *messageRepository) GetSessionAttachments(

View File

@ -0,0 +1,133 @@
package repository
import (
"context"
"testing"
"time"
"github.com/Tencent/WeKnora/internal/types"
"github.com/stretchr/testify/require"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
func newMessageRepositoryForForkTest(t *testing.T) (*messageRepository, *gorm.DB) {
t.Helper()
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
require.NoError(t, err)
require.NoError(t, db.AutoMigrate(&types.Message{}))
return &messageRepository{db: db}, db
}
func seedMessage(t *testing.T, db *gorm.DB, id, sessionID, role string, at time.Time) {
t.Helper()
// Message.BeforeCreate always assigns a fresh UUID, which would discard
// the IDs these tests use as both expected results and the composite
// cursor. Skip hooks so the seeded identity is the one the queries see.
require.NoError(t, db.Session(&gorm.Session{SkipHooks: true}).Create(&types.Message{
ID: id,
SessionID: sessionID,
Role: role,
CreatedAt: at,
}).Error)
}
// Same-millisecond messages must come back in a deterministic order, otherwise
// a fork boundary drawn at one of them is not reproducible.
func TestGetMessagesBySessionBreaksTimestampTiesById(t *testing.T) {
repo, db := newMessageRepositoryForForkTest(t)
ctx := context.Background()
at := time.Date(2026, 9, 10, 9, 0, 0, 0, time.UTC)
seedMessage(t, db, "m-c", "s1", "assistant", at)
seedMessage(t, db, "m-a", "s1", "user", at)
seedMessage(t, db, "m-b", "s1", "assistant", at)
got, err := repo.GetMessagesBySession(ctx, "s1", 1, 10)
require.NoError(t, err)
require.Equal(t, []string{"m-a", "m-b", "m-c"}, messageIDs(got))
}
func TestListMessagesBySessionUpToExcludesBoundaryAndLater(t *testing.T) {
repo, db := newMessageRepositoryForForkTest(t)
ctx := context.Background()
base := time.Date(2026, 9, 10, 9, 0, 0, 0, time.UTC)
seedMessage(t, db, "m1", "s1", "user", base)
seedMessage(t, db, "m2", "s1", "assistant", base.Add(time.Second))
seedMessage(t, db, "m3", "s1", "user", base.Add(2*time.Second))
seedMessage(t, db, "m4", "s1", "assistant", base.Add(3*time.Second))
seedMessage(t, db, "other", "s2", "user", base)
got, err := repo.ListMessagesBySessionUpTo(ctx, "s1", base.Add(2*time.Second), "m3")
require.NoError(t, err)
require.Equal(t, []string{"m1", "m2"}, messageIDs(got))
}
// The boundary is a composite (created_at, id) cursor, so a message sharing the
// boundary's timestamp is included only when its ID sorts before the boundary's.
func TestListMessagesBySessionUpToUsesCompositeCursor(t *testing.T) {
repo, db := newMessageRepositoryForForkTest(t)
ctx := context.Background()
at := time.Date(2026, 9, 10, 9, 0, 0, 0, time.UTC)
seedMessage(t, db, "m-a", "s1", "user", at)
seedMessage(t, db, "m-b", "s1", "assistant", at)
seedMessage(t, db, "m-c", "s1", "user", at)
got, err := repo.ListMessagesBySessionUpTo(ctx, "s1", at, "m-c")
require.NoError(t, err)
require.Equal(t, []string{"m-a", "m-b"}, messageIDs(got))
}
func TestListMessagesBySessionUpToSkipsSoftDeleted(t *testing.T) {
repo, db := newMessageRepositoryForForkTest(t)
ctx := context.Background()
base := time.Date(2026, 9, 10, 9, 0, 0, 0, time.UTC)
seedMessage(t, db, "m1", "s1", "user", base)
seedMessage(t, db, "m2", "s1", "assistant", base.Add(time.Second))
seedMessage(t, db, "boundary", "s1", "user", base.Add(2*time.Second))
require.NoError(t, db.Delete(&types.Message{}, "id = ?", "m2").Error)
got, err := repo.ListMessagesBySessionUpTo(ctx, "s1", base.Add(2*time.Second), "boundary")
require.NoError(t, err)
require.Equal(t, []string{"m1"}, messageIDs(got))
}
func TestRecordRestoredArtifactMtimeOnlyTouchesThisSession(t *testing.T) {
repo, db := newMessageRepositoryForForkTest(t)
ctx := context.Background()
at := time.Date(2026, 9, 10, 9, 0, 0, 0, time.UTC)
oldMod := at
newMod := at.Add(time.Minute)
hash := "abc"
art := types.MessageArtifacts{{
SourcePath: "/workspace/output/report.pptx", FileName: "report.pptx",
ModTime: oldMod, FileSize: 4, ContentHash: hash,
}}
require.NoError(t, db.Session(&gorm.Session{SkipHooks: true}).Create(&types.Message{
ID: "parent-msg", SessionID: "parent", Role: "assistant", CreatedAt: at, Artifacts: art,
}).Error)
require.NoError(t, db.Session(&gorm.Session{SkipHooks: true}).Create(&types.Message{
ID: "fork-msg", SessionID: "fork-1", Role: "assistant", CreatedAt: at, Artifacts: art,
}).Error)
require.NoError(t, repo.RecordRestoredArtifactMtime(ctx, "fork-1", "/workspace/output/report.pptx", newMod, hash))
var parent, child types.Message
require.NoError(t, db.Where("id = ?", "parent-msg").First(&parent).Error)
require.NoError(t, db.Where("id = ?", "fork-msg").First(&child).Error)
require.True(t, parent.Artifacts[0].ModTime.Equal(oldMod), "parent artifact mtime must stay put")
require.True(t, child.Artifacts[0].ModTime.Equal(newMod), "fork artifact mtime should follow the restored sandbox")
}
func messageIDs(messages []*types.Message) []string {
ids := make([]string, 0, len(messages))
for _, m := range messages {
ids = append(ids, m.ID)
}
return ids
}

View File

@ -0,0 +1,52 @@
package repository
import (
"context"
"testing"
"time"
"github.com/Tencent/WeKnora/internal/types"
"github.com/stretchr/testify/require"
"gorm.io/gorm"
)
func TestGetMessagesByRequestIDsStaysInsideSession(t *testing.T) {
repo, db := newMessageRepositoryForForkTest(t)
require.NoError(t, db.AutoMigrate(&types.Session{}))
ctx := context.Background()
at := time.Date(2026, 9, 10, 9, 0, 0, 0, time.UTC)
require.NoError(t, db.Session(&gorm.Session{SkipHooks: true}).
Create(&types.Session{ID: "parent", TenantID: 1}).Error)
require.NoError(t, db.Session(&gorm.Session{SkipHooks: true}).Create(&types.Session{ID: "fork", TenantID: 1}).Error)
require.NoError(t, db.Session(&gorm.Session{SkipHooks: true}).Create(&types.Message{
ID: "p-u", SessionID: "parent", RequestID: "req", Role: "user", CreatedAt: at,
}).Error)
require.NoError(t, db.Session(&gorm.Session{SkipHooks: true}).Create(&types.Message{
ID: "p-a", SessionID: "parent", RequestID: "req", Role: "assistant", CreatedAt: at.Add(time.Second),
}).Error)
require.NoError(t, db.Session(&gorm.Session{SkipHooks: true}).Create(&types.Message{
ID: "f-u", SessionID: "fork", RequestID: "req", Role: "user", CreatedAt: at,
}).Error)
require.NoError(t, db.Session(&gorm.Session{SkipHooks: true}).Create(&types.Message{
ID: "f-a", SessionID: "fork", RequestID: "req", Role: "assistant", CreatedAt: at.Add(time.Second),
}).Error)
got, err := repo.GetMessagesByRequestIDs(ctx, "fork", []string{"req"})
require.NoError(t, err)
require.Equal(t, []string{"f-u", "f-a"}, messageIDsFromWithSession(got))
empty, err := repo.GetMessagesByRequestIDs(ctx, "", []string{"req"})
require.NoError(t, err)
require.Empty(t, empty)
}
func messageIDsFromWithSession(messages []*types.MessageWithSession) []string {
ids := make([]string, 0, len(messages))
for _, m := range messages {
if m != nil {
ids = append(ids, m.ID)
}
}
return ids
}

View File

@ -391,3 +391,175 @@ func (r *sessionRepository) DeleteAllByTenantID(ctx context.Context, tenantID ui
).Delete(&types.Session{})
return res.RowsAffected, res.Error
}
// CreateForked persists a forked session and its copied history atomically.
// A partially written fork would show up in the sidebar with a truncated or
// empty conversation, so both halves must land together.
func (r *sessionRepository) CreateForked(
ctx context.Context, session *types.Session, messages []*types.Message,
) error {
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
now := time.Now()
session.CreatedAt = now
session.UpdatedAt = now
// Session.BeforeCreate would overwrite the ID the fork service already
// assigned (the copied messages point at it), so write the row with
// the hook skipped.
if err := tx.Session(&gorm.Session{SkipHooks: true}).Create(session).Error; err != nil {
return err
}
if len(messages) == 0 {
return nil
}
return tx.Session(&gorm.Session{SkipHooks: true}).
CreateInBatches(messages, 100).Error
})
}
// UpdateForkBootstrap overwrites a session's fork bootstrap. Passing nil clears
// it, which is how a failed or abandoned bootstrap is retired.
func (r *sessionRepository) UpdateForkBootstrap(
ctx context.Context, sessionID string, b *types.ForkBootstrap,
) error {
return r.db.WithContext(ctx).Unscoped().Model(&types.Session{}).
Where("id = ?", sessionID).
Update("fork_bootstrap", b).Error
}
// ListUnconsumedForks returns fork bootstraps the snapshot reaper should
// try to retire: unopened forks older than olderThan, plus consumed forks
// that still name a snapshot (Cube keeps runtime refs until both sandboxes
// exit, so AfterCreate often cannot delete immediately).
//
// Soft-deleted sessions are included: deleting an unopened fork hides the
// row from the default GORM scope, and this listing is the reaper's fallback
// when delete-path snapshot cleanup did not run.
func (r *sessionRepository) ListUnconsumedForks(
ctx context.Context, olderThan time.Time,
) ([]*types.Session, error) {
var sessions []*types.Session
// Only the columns the reaper needs. The full session row includes large
// JSONB (last_request_state) that this listing never reads.
if err := r.db.WithContext(ctx).Unscoped().
Model(&types.Session{}).
Select("id", "tenant_id", "sandbox_config_id", "fork_bootstrap", "deleted_at").
Where("fork_bootstrap IS NOT NULL").
Find(&sessions).Error; err != nil {
return nil, err
}
pending := make([]*types.Session, 0, len(sessions))
for _, s := range sessions {
if s == nil || s.ForkBootstrap == nil {
continue
}
if strings.TrimSpace(s.ForkBootstrap.SnapshotID) == "" {
continue
}
if s.ForkBootstrap.Consumed() {
pending = append(pending, s)
continue
}
if s.ForkBootstrap.CreatedAt.After(olderThan) {
continue
}
pending = append(pending, s)
}
return pending, nil
}
func forkBootstrapJSONText(db *gorm.DB, key string) string {
if db.Name() == "postgres" {
return "fork_bootstrap ->> '" + key + "'"
}
return "json_extract(fork_bootstrap, '$." + key + "')"
}
func (r *sessionRepository) unconsumedForkSnapshotQuery(ctx context.Context, snapshotID string) *gorm.DB {
snapExpr := forkBootstrapJSONText(r.db, "snapshot_id")
consumedExpr := forkBootstrapJSONText(r.db, "consumed_at")
// Matches idx_sessions_unconsumed_fork on Postgres: snapshot_id equality
// under (fork_bootstrap IS NOT NULL AND consumed_at IS NULL).
return r.db.WithContext(ctx).
Model(&types.Session{}).
Where("fork_bootstrap IS NOT NULL").
Where(snapExpr+" = ?", snapshotID).
Where(consumedExpr + " IS NULL")
}
func (r *sessionRepository) unconsumedForkSnapshotHolders(
ctx context.Context, snapshotID string,
) ([]string, error) {
snapshotID = strings.TrimSpace(snapshotID)
if snapshotID == "" {
return nil, nil
}
var ids []string
if err := r.unconsumedForkSnapshotQuery(ctx, snapshotID).
Pluck("id", &ids).Error; err != nil {
return nil, err
}
return ids, nil
}
// HasOtherUnconsumedForkSnapshot reports whether another session still needs
// snapshotID to provision. Nested unused forks share one snapshot; deleting it
// when the first sibling boots would strand the rest.
func (r *sessionRepository) HasOtherUnconsumedForkSnapshot(
ctx context.Context, snapshotID, excludeSessionID string,
) (bool, error) {
snapshotID = strings.TrimSpace(snapshotID)
if snapshotID == "" {
return false, nil
}
q := r.unconsumedForkSnapshotQuery(ctx, snapshotID)
if excludeSessionID != "" {
q = q.Where("id <> ?", excludeSessionID)
}
var ids []string
if err := q.Limit(1).Pluck("id", &ids).Error; err != nil {
return false, err
}
return len(ids) > 0, nil
}
// UnconsumedForkSnapshotHolders returns session IDs that still need snapshotID
// to boot.
func (r *sessionRepository) UnconsumedForkSnapshotHolders(
ctx context.Context, snapshotID string,
) ([]string, error) {
return r.unconsumedForkSnapshotHolders(ctx, snapshotID)
}
func (r *sessionRepository) CreateForkSnapshotLease(
ctx context.Context, lease *types.ForkSnapshotLease,
) error {
if lease == nil || strings.TrimSpace(lease.SnapshotID) == "" {
return nil
}
if lease.CreatedAt.IsZero() {
lease.CreatedAt = time.Now().UTC()
}
return r.db.WithContext(ctx).Create(lease).Error
}
func (r *sessionRepository) DeleteForkSnapshotLease(ctx context.Context, snapshotID string) error {
snapshotID = strings.TrimSpace(snapshotID)
if snapshotID == "" {
return nil
}
return r.db.WithContext(ctx).
Where("snapshot_id = ?", snapshotID).
Delete(&types.ForkSnapshotLease{}).Error
}
func (r *sessionRepository) ListStaleForkSnapshotLeases(
ctx context.Context, olderThan time.Time,
) ([]*types.ForkSnapshotLease, error) {
var leases []*types.ForkSnapshotLease
if err := r.db.WithContext(ctx).
Where("created_at <= ?", olderThan).
Find(&leases).Error; err != nil {
return nil, err
}
return leases, nil
}

View File

@ -0,0 +1,295 @@
package repository
import (
"context"
"testing"
"time"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/stretchr/testify/require"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
func newSessionRepositoryForForkTest(t *testing.T) (interfaces.SessionRepository, *gorm.DB) {
t.Helper()
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
require.NoError(t, err)
require.NoError(t, db.AutoMigrate(&types.Session{}, &types.Message{}, &types.ForkSnapshotLease{}))
return NewSessionRepository(db), db
}
func TestCreateForkedPersistsSessionAndCopiedMessages(t *testing.T) {
repo, db := newSessionRepositoryForForkTest(t)
ctx := context.Background()
createdAt := time.Date(2026, 9, 10, 9, 0, 0, 0, time.UTC)
session := &types.Session{
ID: "fork-1",
TenantID: 1,
UserID: "u1",
Title: "原会话(分支)",
SandboxConfigID: "cfg-1",
ParentSessionID: "src",
ForkedFromMessageID: "u-msg-2",
ForkBootstrap: &types.ForkBootstrap{
SnapshotID: "snap-1",
CommitSHA: "sha1",
SourceSandboxID: "sbx-1",
CreatedAt: createdAt,
},
}
messages := []*types.Message{
{ID: "copy-1", SessionID: "fork-1", Role: "user", CreatedAt: createdAt, KnowledgeID: ""},
{ID: "copy-2", SessionID: "fork-1", Role: "assistant", CreatedAt: createdAt.Add(time.Second)},
}
require.NoError(t, repo.CreateForked(ctx, session, messages))
got, err := repo.GetByID(ctx, 1, "fork-1")
require.NoError(t, err)
require.Equal(t, "fork-1", got.ID, "SkipHooks must keep the ID the service already assigned")
require.Equal(t, "src", got.ParentSessionID)
require.Equal(t, "u-msg-2", got.ForkedFromMessageID)
require.Equal(t, "cfg-1", got.SandboxConfigID)
require.NotNil(t, got.ForkBootstrap)
require.Equal(t, "snap-1", got.ForkBootstrap.SnapshotID)
require.Equal(t, "sha1", got.ForkBootstrap.CommitSHA)
require.False(t, got.ForkBootstrap.Consumed())
var stored []*types.Message
require.NoError(t, db.Where("session_id = ?", "fork-1").Order("created_at ASC, id ASC").Find(&stored).Error)
require.Equal(t, []string{"copy-1", "copy-2"}, messageIDs(stored))
}
func TestCreateForkedAllowsEmptyHistory(t *testing.T) {
repo, _ := newSessionRepositoryForForkTest(t)
ctx := context.Background()
session := &types.Session{ID: "fork-empty", TenantID: 1, UserID: "u1", Title: "first"}
require.NoError(t, repo.CreateForked(ctx, session, nil))
got, err := repo.GetByID(ctx, 1, "fork-empty")
require.NoError(t, err)
require.Equal(t, "fork-empty", got.ID)
}
func TestUpdateForkBootstrapSetsAndClears(t *testing.T) {
repo, _ := newSessionRepositoryForForkTest(t)
ctx := context.Background()
session := &types.Session{ID: "s1", TenantID: 1, UserID: "u1", Title: "s"}
require.NoError(t, repo.CreateForked(ctx, session, nil))
bootstrap := &types.ForkBootstrap{
SnapshotID: "snap-1",
CommitSHA: "sha1",
SourceSandboxID: "sbx-1",
CreatedAt: time.Date(2026, 9, 10, 8, 0, 0, 0, time.UTC),
}
require.NoError(t, repo.UpdateForkBootstrap(ctx, "s1", bootstrap))
got, err := repo.GetByID(ctx, 1, "s1")
require.NoError(t, err)
require.NotNil(t, got.ForkBootstrap)
require.Equal(t, "snap-1", got.ForkBootstrap.SnapshotID)
require.NoError(t, repo.UpdateForkBootstrap(ctx, "s1", nil))
got, err = repo.GetByID(ctx, 1, "s1")
require.NoError(t, err)
require.Nil(t, got.ForkBootstrap)
}
func TestListUnconsumedForksFiltersConsumedAndTooNew(t *testing.T) {
repo, _ := newSessionRepositoryForForkTest(t)
ctx := context.Background()
cutoff := time.Date(2026, 9, 10, 10, 0, 0, 0, time.UTC)
consumedAt := cutoff.Add(-time.Hour)
stale := &types.Session{
ID: "stale", TenantID: 1, UserID: "u1", Title: "stale",
ForkBootstrap: &types.ForkBootstrap{
SnapshotID: "snap-stale", CommitSHA: "sha", SourceSandboxID: "sbx",
CreatedAt: cutoff.Add(-time.Hour),
},
}
fresh := &types.Session{
ID: "fresh", TenantID: 1, UserID: "u1", Title: "fresh",
ForkBootstrap: &types.ForkBootstrap{
SnapshotID: "snap-fresh", CommitSHA: "sha", SourceSandboxID: "sbx",
CreatedAt: cutoff.Add(time.Minute),
},
}
consumed := &types.Session{
ID: "consumed", TenantID: 1, UserID: "u1", Title: "consumed",
ForkBootstrap: &types.ForkBootstrap{
SnapshotID: "snap-consumed", CommitSHA: "sha", SourceSandboxID: "sbx",
CreatedAt: cutoff.Add(-2 * time.Hour),
ConsumedAt: &consumedAt,
},
}
plain := &types.Session{ID: "plain", TenantID: 1, UserID: "u1", Title: "plain"}
require.NoError(t, repo.CreateForked(ctx, stale, nil))
require.NoError(t, repo.CreateForked(ctx, fresh, nil))
require.NoError(t, repo.CreateForked(ctx, consumed, nil))
require.NoError(t, repo.CreateForked(ctx, plain, nil))
got, err := repo.ListUnconsumedForks(ctx, cutoff)
require.NoError(t, err)
ids := make([]string, 0, len(got))
for _, s := range got {
ids = append(ids, s.ID)
}
require.ElementsMatch(t, []string{"stale", "consumed"}, ids)
}
func TestListUnconsumedForksIncludesSoftDeletedUnopenedFork(t *testing.T) {
repo, _ := newSessionRepositoryForForkTest(t)
ctx := context.Background()
cutoff := time.Date(2026, 9, 10, 10, 0, 0, 0, time.UTC)
stale := &types.Session{
ID: "deleted-fork", TenantID: 1, UserID: "u1", Title: "gone",
ForkBootstrap: &types.ForkBootstrap{
SnapshotID: "snap-deleted", CommitSHA: "sha", SourceSandboxID: "sbx",
CreatedAt: cutoff.Add(-time.Hour),
},
}
require.NoError(t, repo.CreateForked(ctx, stale, nil))
n, err := repo.Delete(ctx, 1, "u1", "deleted-fork")
require.NoError(t, err)
require.Equal(t, int64(1), n)
got, err := repo.ListUnconsumedForks(ctx, cutoff)
require.NoError(t, err)
require.Len(t, got, 1)
require.Equal(t, "deleted-fork", got[0].ID)
require.Equal(t, "snap-deleted", got[0].ForkBootstrap.SnapshotID)
}
func TestHasOtherUnconsumedForkSnapshotIgnoresSelfAndConsumed(t *testing.T) {
repo, _ := newSessionRepositoryForForkTest(t)
ctx := context.Background()
consumedAt := time.Now().UTC()
self := &types.Session{
ID: "self", TenantID: 1, UserID: "u1", Title: "self",
ForkBootstrap: &types.ForkBootstrap{
SnapshotID: "snap-shared", CommitSHA: "sha", SourceSandboxID: "sbx",
CreatedAt: time.Now().UTC(),
},
}
sibling := &types.Session{
ID: "sibling", TenantID: 1, UserID: "u1", Title: "sibling",
ForkBootstrap: &types.ForkBootstrap{
SnapshotID: "snap-shared", CommitSHA: "sha-early", SourceSandboxID: "sbx",
CreatedAt: time.Now().UTC(),
},
}
otherSnap := &types.Session{
ID: "other-snap", TenantID: 1, UserID: "u1", Title: "other",
ForkBootstrap: &types.ForkBootstrap{
SnapshotID: "snap-other", CommitSHA: "sha", SourceSandboxID: "sbx",
CreatedAt: time.Now().UTC(),
},
}
consumed := &types.Session{
ID: "consumed", TenantID: 1, UserID: "u1", Title: "consumed",
ForkBootstrap: &types.ForkBootstrap{
SnapshotID: "snap-shared", CommitSHA: "sha", SourceSandboxID: "sbx",
CreatedAt: time.Now().UTC().Add(-time.Hour),
ConsumedAt: &consumedAt,
},
}
require.NoError(t, repo.CreateForked(ctx, self, nil))
require.NoError(t, repo.CreateForked(ctx, sibling, nil))
require.NoError(t, repo.CreateForked(ctx, otherSnap, nil))
require.NoError(t, repo.CreateForked(ctx, consumed, nil))
got, err := repo.HasOtherUnconsumedForkSnapshot(ctx, "snap-shared", "self")
require.NoError(t, err)
require.True(t, got)
got, err = repo.HasOtherUnconsumedForkSnapshot(ctx, "snap-shared", "sibling")
require.NoError(t, err)
require.True(t, got, "self is still unconsumed")
got, err = repo.HasOtherUnconsumedForkSnapshot(ctx, "snap-other", "other-snap")
require.NoError(t, err)
require.False(t, got, "only this session names snap-other")
got, err = repo.HasOtherUnconsumedForkSnapshot(ctx, "snap-shared", "missing")
require.NoError(t, err)
require.True(t, got)
got, err = repo.HasOtherUnconsumedForkSnapshot(ctx, "", "self")
require.NoError(t, err)
require.False(t, got)
holders, err := repo.UnconsumedForkSnapshotHolders(ctx, "snap-shared")
require.NoError(t, err)
require.ElementsMatch(t, []string{"self", "sibling"}, holders)
}
func TestHasOtherUnconsumedForkSnapshotIgnoresSoftDeletedSibling(t *testing.T) {
repo, _ := newSessionRepositoryForForkTest(t)
ctx := context.Background()
self := &types.Session{
ID: "self", TenantID: 1, UserID: "u1", Title: "self",
ForkBootstrap: &types.ForkBootstrap{
SnapshotID: "snap-shared", CommitSHA: "sha", SourceSandboxID: "sbx",
CreatedAt: time.Now().UTC(),
},
}
sibling := &types.Session{
ID: "sibling", TenantID: 1, UserID: "u1", Title: "sibling",
ForkBootstrap: &types.ForkBootstrap{
SnapshotID: "snap-shared", CommitSHA: "sha", SourceSandboxID: "sbx",
CreatedAt: time.Now().UTC(),
},
}
require.NoError(t, repo.CreateForked(ctx, self, nil))
require.NoError(t, repo.CreateForked(ctx, sibling, nil))
n, err := repo.Delete(ctx, 1, "u1", "sibling")
require.NoError(t, err)
require.Equal(t, int64(1), n)
got, err := repo.HasOtherUnconsumedForkSnapshot(ctx, "snap-shared", "self")
require.NoError(t, err)
require.False(t, got, "a soft-deleted sibling no longer needs the snapshot")
}
func TestForkSnapshotLeaseRoundTripAndStaleListing(t *testing.T) {
repo, _ := newSessionRepositoryForForkTest(t)
ctx := context.Background()
stale := time.Now().UTC().Add(-20 * time.Minute)
fresh := time.Now().UTC()
require.NoError(t, repo.CreateForkSnapshotLease(ctx, &types.ForkSnapshotLease{
SnapshotID: "snap-stale",
TenantID: 9,
SandboxConfigID: "cfg-1",
CreatedAt: stale,
}))
require.NoError(t, repo.CreateForkSnapshotLease(ctx, &types.ForkSnapshotLease{
SnapshotID: "snap-fresh",
CreatedAt: fresh,
}))
got, err := repo.ListStaleForkSnapshotLeases(ctx, time.Now().UTC().Add(-15*time.Minute))
require.NoError(t, err)
require.Len(t, got, 1)
require.Equal(t, "snap-stale", got[0].SnapshotID)
require.Equal(t, uint64(9), got[0].TenantID)
require.Equal(t, "cfg-1", got[0].SandboxConfigID)
require.NoError(t, repo.DeleteForkSnapshotLease(ctx, "snap-stale"))
got, err = repo.ListStaleForkSnapshotLeases(ctx, time.Now().UTC().Add(-15*time.Minute))
require.NoError(t, err)
require.Empty(t, got)
}

View File

@ -14,12 +14,16 @@
// sandbox and returns an empty slice when none exists.
// - Best-effort: individual errors are logged and skipped, never returned,
// so a stray unreadable file cannot block the assistant reply.
// - De-duplication by (SourcePath, ModTime): if a prior message in the
// same session already recorded the same (path, mtime), skip it.
// - De-duplication by (SourcePath, ModTime), with a content-hash check
// when mtime changed: git checkout refreshes mtime on unchanged bytes
// and must not re-attach; a same-size in-place rewrite must.
package service
import (
"context"
"crypto/sha256"
"encoding/hex"
"io"
"path/filepath"
"strings"
"time"
@ -45,10 +49,14 @@ type SandboxArtifactSource interface {
// backed by the message repository; in tests it is stubbed with an in-memory
// map so the collector can be exercised without a database.
type SessionArtifactStore interface {
// KnownArtifacts returns every (SourcePath, ModTime) pair already
// attached to any prior message of the session. The returned set is
// unordered and safe to mutate by the caller.
// KnownArtifacts returns every artifact already attached to any prior
// message of the session. The collector uses SourcePath + ModTime as the
// cheap identity and ContentHash (or the stored blob) when mtime moved.
KnownArtifacts(ctx context.Context, sessionID string) ([]types.MessageArtifact, error)
// RecordRestoredMtime writes the sandbox mtime observed after a same-content
// restore onto this session's copied artifacts so the next collect can skip
// by path+mtime. It must not touch any other session. Best-effort.
RecordRestoredMtime(ctx context.Context, sessionID, sourcePath string, mod time.Time, hash string) error
}
// ArtifactCollectorConfig bounds the collector's I/O and storage footprint.
@ -233,11 +241,11 @@ func (c *ArtifactCollector) Collect(
return c.collect(ctx, sessionID, messageID, tenantID, outputDir, nil)
}
// CollectWithNotify is Collect plus a progress hook fired after the sandbox
// listing is filtered, before any file is read or uploaded. The frontend uses
// this to show a toolbar placeholder while object-storage uploads (often a
// few seconds for HTML charts) finish. notify is skipped when nothing will
// be persisted, so ordinary sandbox turns without new files stay quiet.
// CollectWithNotify is Collect plus a progress hook fired after files have
// been hashed and we know they will be uploaded. The frontend uses this to
// show a toolbar placeholder while object-storage uploads (often a few
// seconds for HTML charts) finish. notify is skipped when nothing will be
// persisted, so a fork restore that only refreshes mtime stays quiet.
func (c *ArtifactCollector) CollectWithNotify(
ctx context.Context,
sessionID string,
@ -319,42 +327,46 @@ func (c *ArtifactCollector) collect(
// file when several turns share the sandbox. Errors here degrade to an
// empty set: attaching duplicates is a soft failure, aborting is not.
known := c.loadKnownSet(ctx, sessionID)
if len(known) > 0 {
logger.Infof(ctx, "[ArtifactCollector] known set size=%d (session=%s)", len(known), sessionID)
if known.len() > 0 {
logger.Infof(ctx, "[ArtifactCollector] known set size=%d (session=%s)", known.len(), sessionID)
}
pending := 0
// pending uploads are files that passed the hash check. Counting
// acceptEntry (mtime miss) before the read would treat a git restore as
// "about to persist" and spin the toolbar on an empty attach.
var uploads []pendingArtifactUpload
for _, entry := range entries {
if c.acceptEntry(entry, known) {
pending++
data, hash, ok := c.readNewContent(ctx, source, sessionID, entry, known)
if !ok {
continue
}
uploads = append(uploads, pendingArtifactUpload{entry: entry, data: data, hash: hash})
known.remember(types.MessageArtifact{
SourcePath: entry.Path, ModTime: entry.ModTime, ContentHash: hash, FileSize: int64(len(data)),
})
}
if pending > 0 && notify != nil {
notify(pending)
if len(uploads) > 0 && notify != nil {
notify(len(uploads))
}
artifacts = make(types.MessageArtifacts, 0, pending)
for _, entry := range entries {
art, ok := c.maybePersist(ctx, source, sessionID, messageID, tenantID, entry, known)
artifacts = make(types.MessageArtifacts, 0, len(uploads))
for _, item := range uploads {
art, ok := c.persistBytes(ctx, sessionID, messageID, tenantID, item.entry, item.data, item.hash)
if !ok {
continue
}
artifacts = append(artifacts, art)
// Adding to the known set inside the loop protects us against the
// pathological case where ListSessionFiles returns the same path
// twice (envd hasn't been observed to do so, but future-proofing
// the loop is cheap).
known[artifactKey(art.SourcePath, art.ModTime)] = struct{}{}
known.remember(art)
}
logger.Infof(ctx, "[ArtifactCollector] done session=%s listed=%d attached=%d",
sessionID, len(entries), len(artifacts))
return artifacts, nil
}
// loadKnownSet returns the (source_path, mod_time) tuples already recorded
// against the session. Empty on error so the caller can proceed.
func (c *ArtifactCollector) loadKnownSet(ctx context.Context, sessionID string) map[string]struct{} {
set := map[string]struct{}{}
// loadKnownSet returns the artifacts already recorded against the session.
// Empty on error so the caller can proceed.
func (c *ArtifactCollector) loadKnownSet(ctx context.Context, sessionID string) *artifactKnownSet {
set := newArtifactKnownSet()
if c.store == nil {
return set
}
@ -365,12 +377,12 @@ func (c *ArtifactCollector) loadKnownSet(ctx context.Context, sessionID string)
return set
}
for _, p := range prev {
set[artifactKey(p.SourcePath, p.ModTime)] = struct{}{}
set.remember(p)
}
return set
}
func (c *ArtifactCollector) acceptEntry(entry sandbox.RemoteDirEntry, known map[string]struct{}) bool {
func (c *ArtifactCollector) acceptEntry(entry sandbox.RemoteDirEntry, known *artifactKnownSet) bool {
if entry.Type != sandbox.RemoteEntryFile {
return false
}
@ -380,51 +392,69 @@ func (c *ArtifactCollector) acceptEntry(entry sandbox.RemoteDirEntry, known map[
if entry.Size > c.config.MaxFileBytes {
return false
}
if _, seen := known[artifactKey(entry.Path, entry.ModTime)]; seen {
return false
}
return true
return !known.seenMtime(entry.Path, entry.ModTime)
}
// maybePersist runs the per-file pipeline (filter → download → upload →
// build metadata). Returns ok=false when the entry was skipped for any
// reason (already known, too large, upload failed). All skip reasons are
// logged so operators can diagnose empty artifact panels.
func (c *ArtifactCollector) maybePersist(
type pendingArtifactUpload struct {
entry sandbox.RemoteDirEntry
data []byte
hash string
}
// readNewContent downloads an accepted file and returns its bytes when the
// content is new. Same-content restores update this session's mtime and
// return ok=false so they are not counted as pending uploads.
func (c *ArtifactCollector) readNewContent(
ctx context.Context,
source SandboxArtifactSource,
sessionID string,
messageID string,
tenantID uint64,
entry sandbox.RemoteDirEntry,
known map[string]struct{},
) (types.MessageArtifact, bool) {
known *artifactKnownSet,
) ([]byte, string, bool) {
if !c.acceptEntry(entry, known) {
if entry.Type == sandbox.RemoteEntryFile && entry.Size > c.config.MaxFileBytes {
logger.Warnf(ctx, "[ArtifactCollector] skip oversize artifact: session=%s path=%s size=%d limit=%d",
sessionID, entry.Path, entry.Size, c.config.MaxFileBytes)
}
return types.MessageArtifact{}, false
return nil, "", false
}
data, err := source.ReadSessionFile(ctx, sessionID, entry.Path)
if err != nil {
logger.Warnf(ctx, "[ArtifactCollector] read artifact failed: session=%s path=%s err=%v",
sessionID, entry.Path, err)
return types.MessageArtifact{}, false
return nil, "", false
}
hash := artifactContentHash(data)
if c.knownSameContent(ctx, known, entry.Path, hash) {
known.remember(types.MessageArtifact{
SourcePath: entry.Path, ModTime: entry.ModTime, ContentHash: hash, FileSize: int64(len(data)),
})
if c.store != nil {
if err := c.store.RecordRestoredMtime(ctx, sessionID, entry.Path, entry.ModTime, hash); err != nil {
logger.Warnf(ctx, "[ArtifactCollector] persist restored mtime failed: session=%s path=%s err=%v",
sessionID, entry.Path, err)
}
}
return nil, "", false
}
// A second guard: envd may report a stale size while the file is being
// re-written; enforce the cap against the actual byte count too.
if int64(len(data)) > c.config.MaxFileBytes {
logger.Warnf(ctx, "[ArtifactCollector] skip oversize artifact after read: session=%s path=%s size=%d limit=%d",
sessionID, entry.Path, len(data), c.config.MaxFileBytes)
return types.MessageArtifact{}, false
return nil, "", false
}
return data, hash, true
}
// Give each blob a UUID-namespaced storage name so concurrent turns
// cannot collide, and so the storage key itself is unguessable from
// the outside (defence-in-depth on top of the /artifacts/:index
// endpoint's ownership check).
func (c *ArtifactCollector) persistBytes(
ctx context.Context,
sessionID string,
messageID string,
tenantID uint64,
entry sandbox.RemoteDirEntry,
data []byte,
hash string,
) (types.MessageArtifact, bool) {
storageName := "artifact_" + uuid.NewString() + "_" + safeFileName(entry.Name)
storagePath, err := c.fileService.SaveBytes(ctx, data, tenantID, storageName, false)
if err != nil {
@ -436,16 +466,58 @@ func (c *ArtifactCollector) maybePersist(
c.bindArtifactResource(ctx, storagePath, messageID)
return types.MessageArtifact{
URL: storagePath,
FileName: entry.Name,
FileType: strings.ToLower(filepath.Ext(entry.Name)),
FileSize: int64(len(data)),
SourcePath: entry.Path,
ModTime: entry.ModTime,
CreatedAt: time.Now().UTC(),
URL: storagePath,
FileName: entry.Name,
FileType: strings.ToLower(filepath.Ext(entry.Name)),
FileSize: int64(len(data)),
ContentHash: hash,
SourcePath: entry.Path,
ModTime: entry.ModTime,
CreatedAt: time.Now().UTC(),
}, true
}
func (c *ArtifactCollector) knownSameContent(ctx context.Context, known *artifactKnownSet, path, hash string) bool {
if known == nil || hash == "" {
return false
}
if known.seenHash(path, hash) {
return true
}
for _, art := range known.byPath[path] {
if art.ContentHash == hash {
return true
}
if art.ContentHash != "" {
continue
}
stored := c.hashStoredArtifact(ctx, art)
if stored != "" {
known.keys[artifactHashKey(path, stored)] = struct{}{}
if stored == hash {
return true
}
}
}
return false
}
func (c *ArtifactCollector) hashStoredArtifact(ctx context.Context, art types.MessageArtifact) string {
if c == nil || c.fileService == nil || strings.TrimSpace(art.URL) == "" {
return ""
}
file, err := c.fileService.GetFile(ctx, art.URL)
if err != nil || file == nil {
return ""
}
defer file.Close()
data, err := io.ReadAll(file)
if err != nil {
return ""
}
return artifactContentHash(data)
}
// bindArtifactResource records that the freshly-persisted artifact resource
// is owned by its assistant message. Best-effort: a binding failure never
// discards the artifact, because the file is already stored and remains
@ -469,34 +541,41 @@ func (c *ArtifactCollector) bindArtifactResource(ctx context.Context, ref, messa
}
}
// ReferencedHistory returns only artifacts from this session explicitly named
// in the answer. Bind these immutable versions to the new message as well, so
// deleting their original message cannot invalidate a later reference.
func (c *ArtifactCollector) ReferencedHistory(ctx context.Context, sessionID, messageID, content string) types.MessageArtifacts {
if c == nil || c.store == nil {
return nil
}
refs := make(map[string]bool)
for _, ref := range types.ScanResourceReferences(content) {
refs[ref] = true
}
if len(refs) == 0 {
// SessionArtifacts returns every artifact already recorded against the session.
// Empty on error, so the caller degrades to "nothing to resolve" rather than
// dropping the turn.
//
// Callers need this to resolve an answer's file references: a turn can name a
// file it did not (re)generate — the first turn after a session fork points the
// sandbox back at an earlier commit, so every unchanged file is de-duplicated
// out of that turn's own artifact list — and the reference still has to be bound
// to that file's stable handle.
func (c *ArtifactCollector) SessionArtifacts(ctx context.Context, sessionID string) types.MessageArtifacts {
if c == nil || c.store == nil || sessionID == "" {
return nil
}
previous, err := c.store.KnownArtifacts(ctx, sessionID)
if err != nil {
logger.Warnf(ctx, "Read referenced artifact history failed: %v", err)
logger.Warnf(ctx, "Read session artifacts failed: %v", err)
return nil
}
var result types.MessageArtifacts
for _, artifact := range previous {
if refs[artifact.URL] {
result = append(result, artifact)
c.bindArtifactResource(ctx, artifact.URL, messageID)
delete(refs, artifact.URL)
}
return previous
}
// BindArtifactsToMessage makes messageID an owner of each artifact's resource
// handle as well. Deleting the message that originally produced the file then
// cannot invalidate a reference made from a later one. Best-effort: a binding
// failure never discards the artifact, which is already stored and downloadable
// through the /artifacts endpoint.
func (c *ArtifactCollector) BindArtifactsToMessage(
ctx context.Context, messageID string, artifacts types.MessageArtifacts,
) {
if c == nil || c.catalog == nil || messageID == "" {
return
}
for _, artifact := range artifacts {
c.bindArtifactResource(ctx, artifact.URL, messageID)
}
return result
}
// artifactKey is the string form of the (source_path, mtime) tuple used to
@ -510,6 +589,72 @@ func artifactKey(path string, mod time.Time) string {
return path + "\x00" + mod.UTC().Format(time.RFC3339Nano)
}
func artifactHashKey(path, hash string) string {
return path + "\x00h" + hash
}
func artifactContentHash(data []byte) string {
sum := sha256.Sum256(data)
return hex.EncodeToString(sum[:])
}
// artifactKnownSet is the per-collect de-dupe index. path+mtime is the cheap
// skip for an untouched file; path+hash catches a restore that only changed
// mtime. Size is never an identity key.
type artifactKnownSet struct {
keys map[string]struct{}
byPath map[string][]types.MessageArtifact
}
func newArtifactKnownSet() *artifactKnownSet {
return &artifactKnownSet{
keys: map[string]struct{}{},
byPath: map[string][]types.MessageArtifact{},
}
}
func (k *artifactKnownSet) len() int {
if k == nil {
return 0
}
return len(k.keys)
}
func (k *artifactKnownSet) remember(art types.MessageArtifact) {
if k == nil {
return
}
if k.keys == nil {
k.keys = map[string]struct{}{}
}
if k.byPath == nil {
k.byPath = map[string][]types.MessageArtifact{}
}
k.keys[artifactKey(art.SourcePath, art.ModTime)] = struct{}{}
if art.ContentHash != "" {
k.keys[artifactHashKey(art.SourcePath, art.ContentHash)] = struct{}{}
}
if art.SourcePath != "" {
k.byPath[art.SourcePath] = append(k.byPath[art.SourcePath], art)
}
}
func (k *artifactKnownSet) seenMtime(path string, mod time.Time) bool {
if k == nil {
return false
}
_, ok := k.keys[artifactKey(path, mod)]
return ok
}
func (k *artifactKnownSet) seenHash(path, hash string) bool {
if k == nil || hash == "" {
return false
}
_, ok := k.keys[artifactHashKey(path, hash)]
return ok
}
// safeFileName strips slashes and backslashes from the original name before
// concatenating it into the storage key. The FileService may or may not
// sanitise on its own; belt-and-suspenders here avoids provider-specific

View File

@ -2,6 +2,7 @@ package service
import (
"context"
"time"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
@ -34,3 +35,53 @@ func (s *messageRepoArtifactStore) KnownArtifacts(
}
return arts, nil
}
// RecordRestoredMtime stamps checkout mtimes onto this session's copied
// artifacts only. The parent session is a different session_id and is not
// loaded here.
func (s *messageRepoArtifactStore) RecordRestoredMtime(
ctx context.Context, sessionID, sourcePath string, mod time.Time, hash string,
) error {
if s == nil || s.repo == nil || sessionID == "" || sourcePath == "" {
return nil
}
if rewriter, ok := s.repo.(restoredArtifactMtimeRewriter); ok {
return rewriter.RecordRestoredArtifactMtime(ctx, sessionID, sourcePath, mod, hash)
}
return s.recordRestoredMtimeViaMessages(ctx, sessionID, sourcePath, mod, hash)
}
type restoredArtifactMtimeRewriter interface {
RecordRestoredArtifactMtime(ctx context.Context, sessionID, sourcePath string, mod time.Time, hash string) error
}
func (s *messageRepoArtifactStore) recordRestoredMtimeViaMessages(
ctx context.Context, sessionID, sourcePath string, mod time.Time, hash string,
) error {
const pageSize = 200
for page := 1; ; page++ {
messages, err := s.repo.GetMessagesBySession(ctx, sessionID, page, pageSize)
if err != nil {
return err
}
if len(messages) == 0 {
return nil
}
for _, message := range messages {
if message == nil {
continue
}
updated, changed := message.Artifacts.WithRestoredMtime(sourcePath, mod, hash)
if !changed {
continue
}
message.Artifacts = updated
if err := s.repo.UpdateMessage(ctx, message); err != nil {
return err
}
}
if len(messages) < pageSize {
return nil
}
}
}

View File

@ -63,6 +63,14 @@ func (s *fakeStore) KnownArtifacts(_ context.Context, _ string) ([]types.Message
return s.prev, s.err
}
func (s *fakeStore) RecordRestoredMtime(_ context.Context, _, sourcePath string, mod time.Time, hash string) error {
updated, changed := types.MessageArtifacts(s.prev).WithRestoredMtime(sourcePath, mod, hash)
if changed {
s.prev = updated
}
return nil
}
// fakeFileService captures uploads and returns a deterministic provider URL.
// Only SaveBytes is exercised by the collector; the other methods are
// implemented to satisfy interfaces.FileService but panic on use so a
@ -94,8 +102,11 @@ func (f *fakeFileService) SaveBytes(_ context.Context, data []byte, tenantID uin
return key, nil
}
func (f *fakeFileService) GetFile(_ context.Context, _ string) (io.ReadCloser, error) {
panic("GetFile should not be called by ArtifactCollector")
func (f *fakeFileService) GetFile(_ context.Context, filePath string) (io.ReadCloser, error) {
if data, ok := f.saved[filePath]; ok {
return io.NopCloser(strings.NewReader(string(data))), nil
}
return nil, stderrors.New("fake file service: not found: " + filePath)
}
func (f *fakeFileService) GetFileURL(_ context.Context, _ string) (string, error) {
@ -150,12 +161,15 @@ type fakeCatalog struct {
func (c *fakeCatalog) Register(context.Context, uint64, string, interfaces.ResourceRegistration) (string, error) {
return "", nil
}
func (c *fakeCatalog) Resolve(context.Context, string) (*types.StoredResource, error) {
return nil, nil
}
func (c *fakeCatalog) ResolvePath(_ context.Context, v string) (string, *types.StoredResource, error) {
return v, nil, nil
}
func (c *fakeCatalog) Bind(_ context.Context, ref, ownerType, ownerID, relation string) error {
c.binds = append(c.binds, bindCall{ref, ownerType, ownerID, relation})
return c.bindErr
@ -172,9 +186,11 @@ func (c *fakeCatalog) Release(_ context.Context, ref, ownerType, ownerID string)
}
return -1, nil
}
func (c *fakeCatalog) CreateAccessGrant(context.Context, string, time.Duration) (string, error) {
return "", nil
}
func (c *fakeCatalog) ResolveAccessGrant(context.Context, string) (*types.StoredResource, error) {
return nil, nil
}
@ -257,12 +273,16 @@ func TestArtifactCollector_NotifyFiresBeforeUpload(t *testing.T) {
"/workspace/output/b.csv": []byte("x,"),
},
}
c := newTestCollector(src, &fakeStore{}, &fakeFileService{}, 1<<20)
fs := &fakeFileService{}
c := newTestCollector(src, &fakeStore{}, fs, 1<<20)
var notified int
got, err := c.CollectWithNotify(ctx, "sess-1", "msg-1", 42, "/workspace/output", func(n int) {
if src.readCalls != nil {
t.Fatalf("notify ran after ReadSessionFile: %v", src.readCalls)
if len(fs.saved) != 0 {
t.Fatalf("notify ran after SaveBytes: saved=%v", fs.saved)
}
if len(src.readCalls) == 0 {
t.Fatalf("notify should run after hash reads")
}
notified = n
})
@ -277,6 +297,44 @@ func TestArtifactCollector_NotifyFiresBeforeUpload(t *testing.T) {
}
}
func TestArtifactCollector_NotifySkipsHashMatchedRestores(t *testing.T) {
ctx := context.Background()
oldMod, _ := time.Parse(time.RFC3339, "2026-07-10T10:20:33Z")
src := &fakeSandboxSource{
entries: map[string][]sandbox.RemoteDirEntry{
"sess-1": {
{Name: "report.pptx", Path: "/workspace/output/report.pptx", Type: sandbox.RemoteEntryFile, Size: 4, ModTime: mustParseTime("2026-07-10T10:21:00Z")},
},
},
contents: map[string][]byte{
"/workspace/output/report.pptx": []byte("PPTX"),
},
}
store := &fakeStore{prev: []types.MessageArtifact{
{
SourcePath: "/workspace/output/report.pptx",
ModTime: oldMod,
FileSize: 4,
ContentHash: artifactContentHash([]byte("PPTX")),
},
}}
c := newTestCollector(src, store, &fakeFileService{}, 1<<20)
notified := 0
got, err := c.CollectWithNotify(ctx, "sess-1", "msg-1", 42, "/workspace/output", func(n int) {
notified = n
})
if err != nil {
t.Fatalf("CollectWithNotify() error = %v", err)
}
if notified != 0 {
t.Fatalf("notify count = %d, want 0 (restored files must not look pending)", notified)
}
if len(got) != 0 {
t.Fatalf("CollectWithNotify() len = %d, want 0", len(got))
}
}
func TestArtifactCollector_SkipsAlreadyKnown(t *testing.T) {
ctx := context.Background()
mod, _ := time.Parse(time.RFC3339, "2026-07-10T10:20:33Z")
@ -311,13 +369,15 @@ func TestArtifactCollector_SkipsAlreadyKnown(t *testing.T) {
}
}
func TestArtifactCollector_ReattachesOnMtimeChange(t *testing.T) {
func TestArtifactCollector_SkipsRestoredFileSamePathSameSize(t *testing.T) {
ctx := context.Background()
oldMod, _ := time.Parse(time.RFC3339, "2026-07-10T10:20:33Z")
src := &fakeSandboxSource{
entries: map[string][]sandbox.RemoteDirEntry{
"sess-1": {
// Same path as the known set, but a *newer* mtime — must be re-attached.
// git checkout rewrites the file with a fresh mtime but the
// same bytes. That must not attach a duplicate to the next
// assistant message.
{Name: "report.pptx", Path: "/workspace/output/report.pptx", Type: sandbox.RemoteEntryFile, Size: 4, ModTime: mustParseTime("2026-07-10T10:21:00Z")},
},
},
@ -326,7 +386,130 @@ func TestArtifactCollector_ReattachesOnMtimeChange(t *testing.T) {
},
}
store := &fakeStore{prev: []types.MessageArtifact{
{SourcePath: "/workspace/output/report.pptx", ModTime: oldMod},
{
SourcePath: "/workspace/output/report.pptx",
ModTime: oldMod,
FileSize: 4,
ContentHash: artifactContentHash([]byte("PPTX")),
},
}}
fs := &fakeFileService{}
c := newTestCollector(src, store, fs, 1<<20)
got, err := c.Collect(ctx, "sess-1", "msg-1", 42, "/workspace/output")
if err != nil {
t.Fatalf("Collect() error = %v", err)
}
if len(got) != 0 {
t.Fatalf("Collect() len = %d, want 0 (same bytes after restore must not re-attach)", len(got))
}
if len(fs.saved) != 0 {
t.Fatalf("SaveBytes should not have been called; saved=%v", fs.saved)
}
}
func TestArtifactCollector_SkipsRestoredFileUsingStoredBlob(t *testing.T) {
ctx := context.Background()
oldMod, _ := time.Parse(time.RFC3339, "2026-07-10T10:20:33Z")
src := &fakeSandboxSource{
entries: map[string][]sandbox.RemoteDirEntry{
"sess-1": {
{Name: "report.pptx", Path: "/workspace/output/report.pptx", Type: sandbox.RemoteEntryFile, Size: 4, ModTime: mustParseTime("2026-07-10T10:21:00Z")},
},
},
contents: map[string][]byte{
"/workspace/output/report.pptx": []byte("PPTX"),
},
}
fs := &fakeFileService{saved: map[string][]byte{"fake://prev": []byte("PPTX")}}
store := &fakeStore{prev: []types.MessageArtifact{
{SourcePath: "/workspace/output/report.pptx", ModTime: oldMod, FileSize: 4, URL: "fake://prev"},
}}
c := newTestCollector(src, store, fs, 1<<20)
got, err := c.Collect(ctx, "sess-1", "msg-1", 42, "/workspace/output")
if err != nil {
t.Fatalf("Collect() error = %v", err)
}
if len(got) != 0 {
t.Fatalf("Collect() len = %d, want 0 (same stored blob after restore must not re-attach)", len(got))
}
}
func TestArtifactCollector_PersistsRestoredMtimeSoNextTurnDoesNotReread(t *testing.T) {
ctx := context.Background()
oldMod, _ := time.Parse(time.RFC3339, "2026-07-10T10:20:33Z")
newMod := mustParseTime("2026-07-10T10:21:00Z")
src := &fakeSandboxSource{
entries: map[string][]sandbox.RemoteDirEntry{
"fork-1": {
{Name: "report.pptx", Path: "/workspace/output/report.pptx", Type: sandbox.RemoteEntryFile, Size: 4, ModTime: newMod},
},
},
contents: map[string][]byte{
"/workspace/output/report.pptx": []byte("PPTX"),
},
}
store := &fakeStore{prev: []types.MessageArtifact{
{
SourcePath: "/workspace/output/report.pptx",
ModTime: oldMod,
FileSize: 4,
ContentHash: artifactContentHash([]byte("PPTX")),
},
}}
c := newTestCollector(src, store, &fakeFileService{}, 1<<20)
got, err := c.Collect(ctx, "fork-1", "msg-1", 42, "/workspace/output")
if err != nil {
t.Fatalf("first Collect() error = %v", err)
}
if len(got) != 0 {
t.Fatalf("first Collect() len = %d, want 0", len(got))
}
if len(src.readCalls) != 1 {
t.Fatalf("first Collect() reads = %d, want 1 (hash restore)", len(src.readCalls))
}
if !store.prev[0].ModTime.Equal(newMod) {
t.Fatalf("restored mtime not written back: got %v want %v", store.prev[0].ModTime, newMod)
}
src.readCalls = nil
got, err = c.Collect(ctx, "fork-1", "msg-2", 42, "/workspace/output")
if err != nil {
t.Fatalf("second Collect() error = %v", err)
}
if len(got) != 0 {
t.Fatalf("second Collect() len = %d, want 0", len(got))
}
if len(src.readCalls) != 0 {
t.Fatalf("second Collect() should hit path+mtime and skip the read; readCalls=%v", src.readCalls)
}
}
func TestArtifactCollector_ReattachesOnMtimeChange(t *testing.T) {
ctx := context.Background()
oldMod, _ := time.Parse(time.RFC3339, "2026-07-10T10:20:33Z")
src := &fakeSandboxSource{
entries: map[string][]sandbox.RemoteDirEntry{
"sess-1": {
// Same path, newer mtime *and* a different size — the skill
// actually rewrote the file this turn.
{
Name: "report.pptx",
Path: "/workspace/output/report.pptx",
Type: sandbox.RemoteEntryFile,
Size: 8,
ModTime: mustParseTime("2026-07-10T10:21:00Z"),
},
},
},
contents: map[string][]byte{
"/workspace/output/report.pptx": []byte("PPTX-NEW"),
},
}
store := &fakeStore{prev: []types.MessageArtifact{
{SourcePath: "/workspace/output/report.pptx", ModTime: oldMod, FileSize: 4},
}}
fs := &fakeFileService{}
c := newTestCollector(src, store, fs, 1<<20)
@ -336,7 +519,43 @@ func TestArtifactCollector_ReattachesOnMtimeChange(t *testing.T) {
t.Fatalf("Collect() error = %v", err)
}
if len(got) != 1 {
t.Fatalf("Collect() len = %d, want 1 (mtime-change should re-attach)", len(got))
t.Fatalf("Collect() len = %d, want 1 (rewritten file should re-attach)", len(got))
}
if len(fs.saved) != 1 {
t.Fatalf("SaveBytes calls = %d, want 1", len(fs.saved))
}
}
func TestArtifactCollector_ReattachesSameSizeDifferentContent(t *testing.T) {
ctx := context.Background()
oldMod, _ := time.Parse(time.RFC3339, "2026-07-10T10:20:33Z")
oldBytes := []byte("PPTX")
newBytes := []byte("PPT!")
if len(oldBytes) != len(newBytes) {
t.Fatal("fixture must keep size identical so a size-key skip would hide the rewrite")
}
src := &fakeSandboxSource{
entries: map[string][]sandbox.RemoteDirEntry{
"sess-1": {
{Name: "report.pptx", Path: "/workspace/output/report.pptx", Type: sandbox.RemoteEntryFile, Size: int64(len(newBytes)), ModTime: mustParseTime("2026-07-10T10:21:00Z")},
},
},
contents: map[string][]byte{
"/workspace/output/report.pptx": newBytes,
},
}
store := &fakeStore{prev: []types.MessageArtifact{
{SourcePath: "/workspace/output/report.pptx", ModTime: oldMod, FileSize: int64(len(oldBytes)), ContentHash: artifactContentHash(oldBytes)},
}}
fs := &fakeFileService{}
c := newTestCollector(src, store, fs, 1<<20)
got, err := c.Collect(ctx, "sess-1", "msg-1", 42, "/workspace/output")
if err != nil {
t.Fatalf("Collect() error = %v", err)
}
if len(got) != 1 {
t.Fatalf("Collect() len = %d, want 1 (same-size rewrite must still attach)", len(got))
}
if len(fs.saved) != 1 {
t.Fatalf("SaveBytes calls = %d, want 1", len(fs.saved))

View File

@ -0,0 +1,372 @@
// Package service - forked-session sandbox bootstrap.
//
// ForkBootstrapper implements sandbox.SessionBootstrapper for forked sessions:
// it points the first create at the fork snapshot, then rolls /workspace back
// to the fork point with git. Git tracks the full tree, including input/ and
// output/; object storage is not rewritten into the sandbox.
//
// The provider snapshot is the live sandbox at fork *time*, so reset must
// also drop later-turn git objects. Otherwise `git checkout` of a post-fork
// commit would restore files the working tree just rolled back. Packages and
// other paths outside /workspace stay at the fork moment; that is intentional.
//
// It is all-or-nothing for the filesystem: handing back a sandbox that sits
// at the fork MOMENT rather than the fork POINT would look normal while
// silently working from the wrong baseline. Snapshot deletion is not part of
// that contract — Cube refuses to delete a snapshot while the source and
// child sandboxes still hold runtime refs, and failing the bootstrap for that
// would destroy a correctly rolled-back sandbox.
package service
import (
"context"
"errors"
"fmt"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// ForkSnapshotDeleter retires a consumed or abandoned fork snapshot.
type ForkSnapshotDeleter interface {
DeleteSnapshot(ctx context.Context, snapshotID string) error
}
type forkBootstrapSessionStore interface {
GetByID(ctx context.Context, tenantID uint64, id string) (*types.Session, error)
UpdateForkBootstrap(ctx context.Context, sessionID string, b *types.ForkBootstrap) error
HasOtherUnconsumedForkSnapshot(ctx context.Context, snapshotID, excludeSessionID string) (bool, error)
}
type forkBootstrapMessageStore interface {
RewriteSandboxCheckpoints(ctx context.Context, sessionID, oldSandboxID, newSandboxID string) error
}
// forkResetTimeout bounds the git rollback. clean -fdx may delete a large
// untracked tree, and gc --prune=now walks leftover objects from later turns,
// so this is more generous than the per-turn checkpoint.
const forkResetTimeout = 90 * time.Second
// ForkBootstrapper provisions forked sessions' first sandbox.
type ForkBootstrapper struct {
sessions forkBootstrapSessionStore
messages forkBootstrapMessageStore
runner SandboxShellRunner
snapshots ForkSnapshotDeleter
client sandbox.RemoteSandboxClient
}
// NewForkBootstrapper wires the bootstrapper.
func NewForkBootstrapper(
sessions forkBootstrapSessionStore,
messages forkBootstrapMessageStore,
runner SandboxShellRunner,
snapshots ForkSnapshotDeleter,
) *ForkBootstrapper {
return &ForkBootstrapper{
sessions: sessions,
messages: messages,
runner: runner,
snapshots: snapshots,
}
}
// NewForkBootstrapperFromRepos is the exported DI constructor. The sandbox
// client is bound later via WithClient.
func NewForkBootstrapperFromRepos(
sessions interfaces.SessionRepository,
messages interfaces.MessageRepository,
) *ForkBootstrapper {
return NewForkBootstrapper(sessions, messages, nil, nil)
}
// WithClient returns a copy that executes AfterCreate against the client
// that created the handle. AfterCreate runs under the session lifecycle
// lock and must not call Resolve.
func (b *ForkBootstrapper) WithClient(client sandbox.RemoteSandboxClient) sandbox.SessionBootstrapper {
if b == nil {
return nil
}
cp := *b
cp.client = client
return &cp
}
// TemplateOverride returns the fork snapshot for a session whose bootstrap is
// still pending.
func (b *ForkBootstrapper) TemplateOverride(
ctx context.Context, key sandbox.SessionSandboxKey,
) (string, error) {
pending, err := b.pendingBootstrap(ctx, key)
if err != nil {
return "", err
}
if pending == nil {
return "", nil
}
return pending.SnapshotID, nil
}
// OnCreateFailed retires a fork snapshot that Create could not boot.
//
// AfterCreate never runs on this path, so git-reset abandon cannot fire.
// NotFound / invalid template mean the snapshot will not start next time
// either; leave transient errors (timeout, capacity, outage) on the row so
// a later Resolve can retry the same snapshot.
func (b *ForkBootstrapper) OnCreateFailed(
ctx context.Context, key sandbox.SessionSandboxKey, createErr error,
) {
if b == nil || !forkSnapshotUnusable(createErr) {
return
}
pending, err := b.pendingBootstrap(ctx, key)
if err != nil {
logger.Warnf(ctx, "[ForkBootstrap] load bootstrap after create failure: %v", err)
return
}
if pending == nil {
return
}
logger.Warnf(ctx, "[ForkBootstrap] create from snapshot %s failed; abandoning bootstrap: %v",
pending.SnapshotID, createErr)
b.abandon(ctx, key.SessionID, pending)
}
func forkSnapshotUnusable(err error) bool {
return sandbox.IsRemoteNotFound(err) || sandbox.IsRemoteInvalidRequest(err)
}
// AfterCreate rolls the new sandbox back to the fork point.
func (b *ForkBootstrapper) AfterCreate(
ctx context.Context, key sandbox.SessionSandboxKey, handle sandbox.RemoteSandboxHandle,
) error {
pending, err := b.pendingBootstrap(ctx, key)
if err != nil {
return err
}
if pending == nil {
return nil
}
if err := b.resetWorkspace(ctx, key.SessionID, pending.CommitSHA, handle); err != nil {
// Retire the bootstrap so the next resolve provisions an ordinary
// sandbox instead of retrying a rollback that just failed.
b.abandon(ctx, key.SessionID, pending)
return err
}
if err := b.rewriteCopiedCheckpoints(ctx, key.SessionID, pending.SourceSandboxID, handle); err != nil {
// Git reset succeeded, so the snapshot is still the right disk.
// Leave bootstrap unconsumed: lifecycle destroys this sandbox and
// the next Resolve retries from the same snapshot instead of
// marking consumed with the parent's sandbox ID (SANDBOX_REPLACED
// on a nested fork).
return err
}
now := time.Now().UTC()
consumed := *pending
consumed.ConsumedAt = &now
if err := b.sessions.UpdateForkBootstrap(ctx, key.SessionID, &consumed); err != nil {
return fmt.Errorf("mark fork bootstrap consumed: %w", err)
}
// Cube (and sometimes Docker/E2B) refuses to delete a snapshot while the
// source sandbox and the sandbox just created from it still hold runtime
// refs. Failing here would make lifecycle destroy a correctly rolled-back
// sandbox, then the next Resolve would boot from the same snapshot and
// hit the same delete — a create/destroy loop. Snapshot GC is best-effort;
// the reaper retries leftover IDs after the refs drop.
if keep, err := b.snapshotStillShared(ctx, key.SessionID, pending.SnapshotID); err != nil {
logger.Warnf(ctx, "[ForkBootstrap] lookup shared snapshot %s failed; leaving it: %v",
pending.SnapshotID, err)
} else if keep {
logger.Infof(ctx, "[ForkBootstrap] snapshot %s still referenced by another unopened fork; deferring delete",
pending.SnapshotID)
} else if err := b.deleteSnapshot(ctx, pending.SnapshotID); err != nil {
logger.Warnf(ctx, "[ForkBootstrap] delete snapshot %s failed after reset; sandbox kept: %v",
pending.SnapshotID, err)
}
return nil
}
func (b *ForkBootstrapper) pendingBootstrap(
ctx context.Context, key sandbox.SessionSandboxKey,
) (*types.ForkBootstrap, error) {
if b == nil || b.sessions == nil {
return nil, nil
}
session, err := b.sessions.GetByID(ctx, key.TenantID, key.SessionID)
if err != nil {
return nil, fmt.Errorf("load session for fork bootstrap: %w", err)
}
if session == nil || session.ForkBootstrap == nil {
return nil, nil
}
if session.ForkBootstrap.Consumed() {
return nil, nil
}
if strings.TrimSpace(session.ForkBootstrap.SnapshotID) == "" {
return nil, nil
}
return session.ForkBootstrap, nil
}
func (b *ForkBootstrapper) snapshotStillShared(ctx context.Context, sessionID, snapshotID string) (bool, error) {
if b == nil || b.sessions == nil {
return false, nil
}
return b.sessions.HasOtherUnconsumedForkSnapshot(ctx, snapshotID, sessionID)
}
func forkResetScript(workspace, sha string) (string, error) {
if !gitSHAPattern.MatchString(sha) {
return "", fmt.Errorf("fork bootstrap: invalid commit sha %q", truncateForLog(sha))
}
ws := shellSingleQuote(workspace)
return fmt.Sprintf(`set -e
git config --global safe.directory %[1]s
git -C %[1]s reset --hard %[2]s
current=$(git -C %[1]s symbolic-ref -q HEAD || true)
for ref in $(git -C %[1]s for-each-ref --format='%%(refname)'); do
[ -z "$ref" ] && continue
[ "$ref" = "$current" ] && continue
git -C %[1]s update-ref -d "$ref"
done
rm -f %[1]s/.git/ORIG_HEAD %[1]s/.git/FETCH_HEAD
git -C %[1]s reflog expire --expire=now --all
git -C %[1]s gc --prune=now
git -C %[1]s clean -fdx`, ws, sha), nil
}
func shellSingleQuote(s string) string {
return "'" + strings.ReplaceAll(s, `'`, `'"'"'`) + "'"
}
func gitResetFailure(sha, stderr string) error {
return fmt.Errorf("fork bootstrap: git reset to %s failed: %s", sha, stderr)
}
// resetWorkspace rolls /workspace back to sha.
//
// reset --hard restores tracked files (including input/ and output/). Other
// refs, ORIG_HEAD, and reflogs still name later-turn commits from the live
// snapshot, so those are deleted and gc'd before clean -fdx; otherwise the
// working tree would look right while `git checkout` could resurrect later
// files. -x then drops leftover untracked files that are not in that commit.
func (b *ForkBootstrapper) resetWorkspace(
ctx context.Context, sessionID, sha string, handle sandbox.RemoteSandboxHandle,
) error {
script, err := forkResetScript(sandbox.SessionWorkspaceRoot, strings.TrimSpace(sha))
if err != nil {
return err
}
if b.client != nil && handle != nil {
result, err := b.client.Exec(ctx, handle, sandbox.RemoteExecRequest{
Command: script,
Shell: true,
WorkDir: sandbox.SessionWorkspaceRoot,
Timeout: forkResetTimeout,
User: sandbox.DefaultSandboxExecUser,
})
if err != nil {
return fmt.Errorf("fork bootstrap: git reset exec: %w", err)
}
if result == nil || result.ExitCode != 0 {
stderr := ""
if result != nil {
stderr = result.Stderr
}
return gitResetFailure(sha, stderr)
}
return nil
}
if b.runner == nil {
return errors.New("fork bootstrap: no shell runner wired")
}
result, err := b.runner.ExecShellCommand(
ctx, sessionID, script, sandbox.SessionWorkspaceRoot, forkResetTimeout, nil,
)
if err != nil {
return fmt.Errorf("fork bootstrap: git reset exec: %w", err)
}
if result == nil || result.ExitCode != 0 {
stderr := ""
if result != nil {
stderr = result.Stderr
}
return gitResetFailure(sha, stderr)
}
return nil
}
func (b *ForkBootstrapper) rewriteCopiedCheckpoints(
ctx context.Context, sessionID, oldSandboxID string, handle sandbox.RemoteSandboxHandle,
) error {
if b.messages == nil || handle == nil {
return nil
}
newID := strings.TrimSpace(handle.ID())
oldID := strings.TrimSpace(oldSandboxID)
if newID == "" || oldID == "" || newID == oldID {
return nil
}
if err := b.messages.RewriteSandboxCheckpoints(ctx, sessionID, oldID, newID); err != nil {
return fmt.Errorf("fork bootstrap: rewrite sandbox checkpoints: %w", err)
}
return nil
}
// abandon retires a bootstrap that could not be applied.
//
// Clear the bootstrap pointer first. Deleting the snapshot while the row still
// names it is the leak-safe order the reaper uses in reverse: if clear fails,
// the snapshot ID remains so a later pass can retry.
func (b *ForkBootstrapper) abandon(ctx context.Context, sessionID string, pending *types.ForkBootstrap) {
cleanupCtx := context.WithoutCancel(ctx)
if err := b.sessions.UpdateForkBootstrap(cleanupCtx, sessionID, nil); err != nil {
logger.Warnf(cleanupCtx, "[ForkBootstrap] clear bootstrap of %s failed: %v", sessionID, err)
return
}
if pending != nil {
if keep, err := b.snapshotStillShared(cleanupCtx, sessionID, pending.SnapshotID); err != nil {
logger.Warnf(cleanupCtx, "[ForkBootstrap] lookup shared snapshot %s failed; leaving it: %v",
pending.SnapshotID, err)
} else if keep {
logger.Infof(cleanupCtx,
"[ForkBootstrap] snapshot %s still referenced by another unopened fork; deferring delete",
pending.SnapshotID)
} else if err := b.deleteSnapshot(cleanupCtx, pending.SnapshotID); err != nil {
logger.Warnf(cleanupCtx, "[ForkBootstrap] delete snapshot %s failed: %v", pending.SnapshotID, err)
}
}
}
func (b *ForkBootstrapper) deleteSnapshot(ctx context.Context, snapshotID string) error {
if strings.TrimSpace(snapshotID) == "" {
return nil
}
var err error
if b.snapshots != nil {
err = b.snapshots.DeleteSnapshot(ctx, snapshotID)
} else if b.client != nil {
if mgr, ok := sandbox.SnapshotManagerFrom(b.client); ok {
err = mgr.DeleteSnapshot(ctx, snapshotID)
}
}
if err == nil || sandbox.IsRemoteNotFound(err) {
return nil
}
return err
}
var _ sandbox.SessionBootstrapper = (*ForkBootstrapper)(nil)
var _ sandbox.SessionBootstrapperWithClient = (*ForkBootstrapper)(nil)
var _ sandbox.SessionCreateFailureHandler = (*ForkBootstrapper)(nil)

View File

@ -0,0 +1,504 @@
package service
import (
"context"
"errors"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/Tencent/WeKnora/internal/types"
"github.com/stretchr/testify/require"
)
func forkTestCommitSHA() string {
return strings.Repeat("a", 40)
}
type fakeSnapshotDeleter struct {
deleted []string
err error
}
func (f *fakeSnapshotDeleter) DeleteSnapshot(_ context.Context, id string) error {
f.deleted = append(f.deleted, id)
return f.err
}
type fakeHandle struct {
id string
}
func (h fakeHandle) ID() string { return h.id }
func (h fakeHandle) Provider() sandbox.RemoteProvider { return sandbox.SandboxTypeCube }
func (h fakeHandle) Metadata() map[string]string { return nil }
func pendingForkSession() *types.Session {
return &types.Session{
ID: "fork-1", TenantID: 1,
ForkBootstrap: &types.ForkBootstrap{
SnapshotID: "snap-1", CommitSHA: forkTestCommitSHA(),
SourceSandboxID: "sbx-1", CreatedAt: time.Now().UTC(),
},
}
}
func forkKey() sandbox.SessionSandboxKey {
return sandbox.SessionSandboxKey{TenantID: 1, SessionID: "fork-1"}
}
func TestTemplateOverrideReturnsSnapshotForPendingFork(t *testing.T) {
sessions := newFakeSessionStore(pendingForkSession())
b := NewForkBootstrapper(sessions, nil, nil, nil)
got, err := b.TemplateOverride(context.Background(), forkKey())
require.NoError(t, err)
require.Equal(t, "snap-1", got)
}
func TestTemplateOverrideIsEmptyForOrdinarySession(t *testing.T) {
sessions := newFakeSessionStore(&types.Session{ID: "fork-1", TenantID: 1})
b := NewForkBootstrapper(sessions, nil, nil, nil)
got, err := b.TemplateOverride(context.Background(), forkKey())
require.NoError(t, err)
require.Empty(t, got)
}
func TestTemplateOverrideIsEmptyForConsumedFork(t *testing.T) {
s := pendingForkSession()
at := time.Now().UTC()
s.ForkBootstrap.ConsumedAt = &at
sessions := newFakeSessionStore(s)
b := NewForkBootstrapper(sessions, nil, nil, nil)
got, err := b.TemplateOverride(context.Background(), forkKey())
require.NoError(t, err)
require.Empty(t, got)
}
func TestTemplateOverridePropagatesLookupError(t *testing.T) {
sessions := newFakeSessionStore(nil)
sessions.getErr = errors.New("db down")
b := NewForkBootstrapper(sessions, nil, nil, nil)
_, err := b.TemplateOverride(context.Background(), forkKey())
require.Error(t, err)
}
func TestAfterCreateResetsWorkspaceThenConsumesAndDeletesSnapshot(t *testing.T) {
sessions := newFakeSessionStore(pendingForkSession())
runner := &fakeShellRunner{result: &sandbox.ExecuteResult{ExitCode: 0}}
snapshots := &fakeSnapshotDeleter{}
b := NewForkBootstrapper(sessions, newFakeMessageStore(nil), runner, snapshots)
require.NoError(t, b.AfterCreate(context.Background(), forkKey(), fakeHandle{id: "sbx-2"}))
require.Len(t, runner.calls, 1)
script := runner.calls[0]
require.Contains(t, script, "reset --hard "+forkTestCommitSHA())
require.Contains(t, script, "reflog expire --expire=now --all")
require.Contains(t, script, "gc --prune=now")
require.Contains(t, script, "clean -fdx")
require.Contains(t, script, "ORIG_HEAD")
require.Equal(t, []string{"snap-1"}, snapshots.deleted)
require.NotNil(t, sessions.updatedBootstrap)
require.True(t, sessions.updatedBootstrap.Consumed())
}
func TestAfterCreateConsumesWhenSnapshotDeleteFailsAfterReset(t *testing.T) {
sessions := newFakeSessionStore(pendingForkSession())
runner := &fakeShellRunner{result: &sandbox.ExecuteResult{ExitCode: 0}}
snapshots := &fakeSnapshotDeleter{err: sandbox.NewRemoteError(
sandbox.SandboxTypeCube, "DeleteSnapshot", sandbox.RemoteErrorKindConflict,
"CubeMaster returned error code 130409: template attempt is already in progress: "+
"snapshot snap-1 still has 2 active runtime ref(s): src@host, fork@host (HTTP 500)",
nil,
)}
b := NewForkBootstrapper(sessions, newFakeMessageStore(nil), runner, snapshots)
err := b.AfterCreate(context.Background(), forkKey(), fakeHandle{id: "sbx-2"})
require.NoError(t, err, "git reset succeeded; an in-use Cube snapshot must not destroy the sandbox")
require.Equal(t, []string{"snap-1"}, snapshots.deleted)
require.False(t, sessions.bootstrapCleared)
require.True(t, sessions.updatedBootstrap.Consumed())
require.Equal(t, "snap-1", sessions.updatedBootstrap.SnapshotID)
got, overrideErr := b.TemplateOverride(context.Background(), forkKey())
require.NoError(t, overrideErr)
require.Empty(t, got, "retry must not boot another sandbox from the same snapshot")
}
func TestAfterCreateSkipsDeleteWhenSiblingStillNeedsSnapshot(t *testing.T) {
sessions := newFakeSessionStore(pendingForkSession())
sessions.unconsumed = []*types.Session{{
ID: "fork-2", TenantID: 1,
ForkBootstrap: &types.ForkBootstrap{
SnapshotID: "snap-1", CreatedAt: time.Now().UTC(),
},
}}
runner := &fakeShellRunner{result: &sandbox.ExecuteResult{ExitCode: 0}}
snapshots := &fakeSnapshotDeleter{}
b := NewForkBootstrapper(sessions, newFakeMessageStore(nil), runner, snapshots)
require.NoError(t, b.AfterCreate(context.Background(), forkKey(), fakeHandle{id: "sbx-2"}))
require.Empty(t, snapshots.deleted, "a sibling still boots from this snapshot")
require.True(t, sessions.updatedBootstrap.Consumed())
require.Equal(t, "snap-1", sessions.updatedBootstrap.SnapshotID)
}
func TestAfterCreateResetFailKeepsSnapshotWhenClearFails(t *testing.T) {
sessions := newFakeSessionStore(pendingForkSession())
sessions.clearErr = errors.New("db down")
runner := &fakeShellRunner{result: &sandbox.ExecuteResult{
ExitCode: 128, Stderr: "fatal: bad object " + forkTestCommitSHA(),
}}
snapshots := &fakeSnapshotDeleter{}
b := NewForkBootstrapper(sessions, newFakeMessageStore(nil), runner, snapshots)
err := b.AfterCreate(context.Background(), forkKey(), fakeHandle{id: "sbx-2"})
require.Error(t, err)
require.False(t, sessions.bootstrapCleared)
require.Empty(t, snapshots.deleted)
require.NotNil(t, sessions.source.ForkBootstrap)
}
func TestAfterCreateRewritesCopiedCheckpointsToNewSandboxID(t *testing.T) {
sessions := newFakeSessionStore(pendingForkSession())
runner := &fakeShellRunner{result: &sandbox.ExecuteResult{ExitCode: 0}}
committedAt := time.Date(2026, 9, 10, 9, 0, 1, 0, time.UTC)
messages := newFakeMessageStore([]*types.Message{{
ID: "a1", SessionID: "fork-1", Role: "assistant",
SandboxCheckpoint: &types.SandboxCheckpoint{
SandboxID: "sbx-1", CommitSHA: forkTestCommitSHA(), CommittedAt: committedAt,
},
}})
b := NewForkBootstrapper(sessions, messages, runner, &fakeSnapshotDeleter{})
require.NoError(t, b.AfterCreate(context.Background(), forkKey(), fakeHandle{id: "sbx-2"}))
require.Equal(t, "sbx-2", messages.messages[0].SandboxCheckpoint.SandboxID)
require.Equal(t, forkTestCommitSHA(), messages.messages[0].SandboxCheckpoint.CommitSHA)
require.Equal(t, committedAt, messages.messages[0].SandboxCheckpoint.CommittedAt)
require.True(t, sessions.updatedBootstrap.Consumed())
}
func TestAfterCreateRewriteFailureDoesNotConsumeBootstrap(t *testing.T) {
sessions := newFakeSessionStore(pendingForkSession())
runner := &fakeShellRunner{result: &sandbox.ExecuteResult{ExitCode: 0}}
snapshots := &fakeSnapshotDeleter{}
messages := newFakeMessageStore([]*types.Message{{
ID: "a1", SessionID: "fork-1", Role: "assistant",
SandboxCheckpoint: &types.SandboxCheckpoint{
SandboxID: "sbx-1", CommitSHA: "abc123",
},
}})
messages.rewriteErr = errors.New("db down")
b := NewForkBootstrapper(sessions, messages, runner, snapshots)
err := b.AfterCreate(context.Background(), forkKey(), fakeHandle{id: "sbx-2"})
require.Error(t, err)
require.False(t, sessions.bootstrapCleared)
require.Nil(t, sessions.updatedBootstrap)
require.False(t, sessions.source.ForkBootstrap.Consumed())
require.Empty(t, snapshots.deleted)
require.Equal(t, "sbx-1", messages.messages[0].SandboxCheckpoint.SandboxID)
got, overrideErr := b.TemplateOverride(context.Background(), forkKey())
require.NoError(t, overrideErr)
require.Equal(t, "snap-1", got, "retry must boot from the same snapshot")
}
func TestAfterCreateIsNoOpForOrdinarySession(t *testing.T) {
sessions := newFakeSessionStore(&types.Session{ID: "fork-1", TenantID: 1})
runner := &fakeShellRunner{result: &sandbox.ExecuteResult{ExitCode: 0}}
b := NewForkBootstrapper(sessions, newFakeMessageStore(nil), runner, &fakeSnapshotDeleter{})
require.NoError(t, b.AfterCreate(context.Background(), forkKey(), fakeHandle{id: "sbx-2"}))
require.Empty(t, runner.calls)
}
// 全有或全无:reset 失败必须返回 error,让 lifecycle 销毁这个沙箱。
func TestAfterCreateFailsWhenResetFails(t *testing.T) {
sessions := newFakeSessionStore(pendingForkSession())
runner := &fakeShellRunner{result: &sandbox.ExecuteResult{
ExitCode: 128, Stderr: "fatal: bad object " + forkTestCommitSHA(),
}}
snapshots := &fakeSnapshotDeleter{}
b := NewForkBootstrapper(sessions, newFakeMessageStore(nil), runner, snapshots)
err := b.AfterCreate(context.Background(), forkKey(), fakeHandle{id: "sbx-2"})
require.Error(t, err)
// 引导失败时清空 bootstrap 并回收快照:下次 resolve 走全新沙箱路径。
require.Equal(t, []string{"snap-1"}, snapshots.deleted)
require.True(t, sessions.bootstrapCleared)
}
func TestAfterCreateRejectsInvalidCommitSHAWithoutExec(t *testing.T) {
sessions := newFakeSessionStore(pendingForkSession())
sessions.source.ForkBootstrap.CommitSHA = "HEAD; echo pwned"
runner := &fakeShellRunner{result: &sandbox.ExecuteResult{ExitCode: 0}}
snapshots := &fakeSnapshotDeleter{}
b := NewForkBootstrapper(sessions, newFakeMessageStore(nil), runner, snapshots)
err := b.AfterCreate(context.Background(), forkKey(), fakeHandle{id: "sbx-2"})
require.Error(t, err)
require.Empty(t, runner.calls)
require.Contains(t, err.Error(), "invalid commit sha")
}
func TestForkResetScriptRejectsNonHexSHA(t *testing.T) {
_, err := forkResetScript(sandbox.SessionWorkspaceRoot, "abc123")
require.Error(t, err)
_, err = forkResetScript(sandbox.SessionWorkspaceRoot, "")
require.Error(t, err)
_, err = forkResetScript(sandbox.SessionWorkspaceRoot, forkTestCommitSHA()+";rm")
require.Error(t, err)
}
func TestForkResetScriptPrunesLaterCommits(t *testing.T) {
if _, err := exec.LookPath("git"); err != nil {
t.Skip("git not available")
}
dir := t.TempDir()
env := isolatedGitEnv(t)
runGit := func(args ...string) string {
t.Helper()
cmd := exec.Command("git", append([]string{"-C", dir}, args...)...)
cmd.Env = env
out, err := cmd.CombinedOutput()
require.NoError(t, err, string(out))
return strings.TrimSpace(string(out))
}
runGit("init")
runGit("config", "user.email", "agent@weknora.local")
runGit("config", "user.name", "WeKnora Agent")
require.NoError(t, os.WriteFile(filepath.Join(dir, "keep.txt"), []byte("early"), 0o644))
runGit("add", "-A")
runGit("commit", "-m", "early")
early := runGit("rev-parse", "HEAD")
if !gitSHAPattern.MatchString(early) {
t.Skip("host git is not using SHA-1 object names")
}
require.NoError(t, os.WriteFile(filepath.Join(dir, "secret.txt"), []byte("later-secret"), 0o644))
runGit("add", "-A")
runGit("commit", "-m", "later")
later := runGit("rev-parse", "HEAD")
require.NotEqual(t, early, later)
script, err := forkResetScript(dir, early)
require.NoError(t, err)
cmd := exec.Command("bash", "-c", script)
cmd.Env = env
out, err := cmd.CombinedOutput()
require.NoError(t, err, string(out))
cat := exec.Command("git", "-C", dir, "cat-file", "-t", later)
cat.Env = env
require.Error(t, cat.Run(), "later-turn commit must be unreachable after prune")
_, err = os.Stat(filepath.Join(dir, "secret.txt"))
require.True(t, os.IsNotExist(err))
body, err := os.ReadFile(filepath.Join(dir, "keep.txt"))
require.NoError(t, err)
require.Equal(t, "early", string(body))
}
func isolatedGitEnv(t *testing.T) []string {
t.Helper()
return append(os.Environ(),
"GIT_CONFIG_GLOBAL="+filepath.Join(t.TempDir(), "gitconfig"),
"GIT_CONFIG_NOSYSTEM=1",
"GIT_AUTHOR_NAME=WeKnora Agent",
"GIT_AUTHOR_EMAIL=agent@weknora.local",
"GIT_COMMITTER_NAME=WeKnora Agent",
"GIT_COMMITTER_EMAIL=agent@weknora.local",
)
}
func TestWithClientNilReceiver(t *testing.T) {
var b *ForkBootstrapper
require.Nil(t, b.WithClient(&recordingRemoteClient{}))
}
func TestOnCreateFailedAbandonsWhenSnapshotIsGone(t *testing.T) {
sessions := newFakeSessionStore(pendingForkSession())
snapshots := &fakeSnapshotDeleter{}
b := NewForkBootstrapper(sessions, nil, nil, snapshots)
b.OnCreateFailed(context.Background(), forkKey(), sandbox.NewRemoteError(
sandbox.SandboxTypeCube, "Create", sandbox.RemoteErrorKindNotFound, "template gone", nil,
))
require.True(t, sessions.bootstrapCleared)
require.Equal(t, []string{"snap-1"}, snapshots.deleted)
got, err := b.TemplateOverride(context.Background(), forkKey())
require.NoError(t, err)
require.Empty(t, got, "retry must boot an ordinary sandbox, not the dead snapshot")
}
func TestOnCreateFailedAbandonsWhenTemplateIsInvalid(t *testing.T) {
sessions := newFakeSessionStore(pendingForkSession())
snapshots := &fakeSnapshotDeleter{}
b := NewForkBootstrapper(sessions, nil, nil, snapshots)
// Create HTTP 404 is classified as invalid_request, not not_found.
b.OnCreateFailed(context.Background(), forkKey(), sandbox.NewRemoteError(
sandbox.SandboxTypeCube, "Create", sandbox.RemoteErrorKindInvalidRequest, "unknown template", nil,
))
require.True(t, sessions.bootstrapCleared)
require.Equal(t, []string{"snap-1"}, snapshots.deleted)
}
func TestOnCreateFailedKeepsBootstrapOnTransientError(t *testing.T) {
sessions := newFakeSessionStore(pendingForkSession())
snapshots := &fakeSnapshotDeleter{}
b := NewForkBootstrapper(sessions, nil, nil, snapshots)
b.OnCreateFailed(context.Background(), forkKey(), sandbox.NewRemoteError(
sandbox.SandboxTypeCube, "Create", sandbox.RemoteErrorKindUnavailable, "provider down", nil,
))
require.False(t, sessions.bootstrapCleared)
require.Empty(t, snapshots.deleted)
got, err := b.TemplateOverride(context.Background(), forkKey())
require.NoError(t, err)
require.Equal(t, "snap-1", got)
}
func TestOnCreateFailedIsNoOpWithoutPendingBootstrap(t *testing.T) {
sessions := newFakeSessionStore(&types.Session{ID: "fork-1", TenantID: 1})
snapshots := &fakeSnapshotDeleter{}
b := NewForkBootstrapper(sessions, nil, nil, snapshots)
b.OnCreateFailed(context.Background(), forkKey(), sandbox.NewRemoteError(
sandbox.SandboxTypeCube, "Create", sandbox.RemoteErrorKindNotFound, "template gone", nil,
))
require.False(t, sessions.bootstrapCleared)
require.Empty(t, snapshots.deleted)
}
func TestAfterCreateWithClientUsesHandleNotRunner(t *testing.T) {
sessions := newFakeSessionStore(pendingForkSession())
runner := &fakeShellRunner{result: &sandbox.ExecuteResult{ExitCode: 0}}
client := &recordingRemoteClient{execResult: &sandbox.RemoteExecResult{ExitCode: 0}}
snapshots := &fakeSnapshotDeleter{}
b := NewForkBootstrapper(sessions, newFakeMessageStore(nil), runner, snapshots)
bound, ok := b.WithClient(client).(*ForkBootstrapper)
require.True(t, ok)
require.Same(t, client, bound.client)
require.NoError(t, bound.AfterCreate(context.Background(), forkKey(), fakeHandle{id: "sbx-2"}))
require.Empty(t, runner.calls, "AfterCreate must not Resolve via the session runner")
require.Len(t, client.execs, 1)
require.True(t, client.execs[0].Shell)
require.Equal(t, sandbox.SessionWorkspaceRoot, client.execs[0].WorkDir)
require.Equal(t, sandbox.DefaultSandboxExecUser, client.execs[0].User)
require.Equal(t, forkResetTimeout, client.execs[0].Timeout)
require.Contains(t, client.execs[0].Command, "reset --hard "+forkTestCommitSHA())
require.Contains(t, client.execs[0].Command, "gc --prune=now")
require.Equal(t, []string{"snap-1"}, snapshots.deleted)
require.True(t, sessions.updatedBootstrap.Consumed())
}
type recordingRemoteClient struct {
execs []sandbox.RemoteExecRequest
execResult *sandbox.RemoteExecResult
execErr error
}
func (c *recordingRemoteClient) Provider() sandbox.RemoteProvider { return sandbox.SandboxTypeCube }
func (c *recordingRemoteClient) Capabilities() sandbox.RemoteSandboxCapabilities {
return sandbox.RemoteSandboxCapabilities{}
}
func (c *recordingRemoteClient) Health(context.Context) error { return nil }
func (c *recordingRemoteClient) Create(
context.Context, sandbox.RemoteCreateRequest,
) (sandbox.RemoteSandboxHandle, error) {
panic("Create should not be called from AfterCreate")
}
func (c *recordingRemoteClient) Connect(
context.Context, sandbox.RemoteConnectRequest,
) (sandbox.RemoteSandboxHandle, error) {
panic("Connect should not be called from AfterCreate")
}
func (c *recordingRemoteClient) Get(context.Context, string) (*sandbox.RemoteSandboxSummary, error) {
panic("Get should not be called from AfterCreate")
}
func (c *recordingRemoteClient) List(
context.Context, sandbox.RemoteListFilter,
) ([]sandbox.RemoteSandboxSummary, error) {
panic("List should not be called from AfterCreate")
}
func (c *recordingRemoteClient) Delete(context.Context, string) error {
panic("Delete should not be called from AfterCreate")
}
func (c *recordingRemoteClient) Exec(
_ context.Context, _ sandbox.RemoteSandboxHandle, req sandbox.RemoteExecRequest,
) (*sandbox.RemoteExecResult, error) {
c.execs = append(c.execs, req)
if c.execErr != nil {
return nil, c.execErr
}
if c.execResult != nil {
return c.execResult, nil
}
return &sandbox.RemoteExecResult{ExitCode: 0}, nil
}
func (c *recordingRemoteClient) WriteFile(context.Context, sandbox.RemoteSandboxHandle, string, []byte) error {
panic("WriteFile should not be called from AfterCreate")
}
func (c *recordingRemoteClient) ReadFile(context.Context, sandbox.RemoteSandboxHandle, string) ([]byte, error) {
panic("ReadFile should not be called from AfterCreate")
}
func (c *recordingRemoteClient) ListDir(
context.Context, sandbox.RemoteSandboxHandle, string,
) ([]sandbox.RemoteDirEntry, error) {
panic("ListDir should not be called from AfterCreate")
}
func (c *recordingRemoteClient) MakeDir(context.Context, sandbox.RemoteSandboxHandle, string) error {
panic("MakeDir should not be called from AfterCreate")
}
func (c *recordingRemoteClient) Remove(context.Context, sandbox.RemoteSandboxHandle, string) error {
panic("Remove should not be called from AfterCreate")
}
func (c *recordingRemoteClient) Stat(
context.Context, sandbox.RemoteSandboxHandle, string,
) (*sandbox.RemoteStatEntry, error) {
panic("Stat should not be called from AfterCreate")
}
var _ sandbox.RemoteSandboxClient = (*recordingRemoteClient)(nil)

View File

@ -0,0 +1,356 @@
// Package service - orphan fork snapshot collection.
//
// A fork takes a provider snapshot immediately but provisions the sandbox
// lazily. A branch the user never opens therefore leaves a snapshot behind
// forever. Persist can also fail after the snapshot already exists, or the
// process can crash before the session row is committed; those IDs live in
// fork_snapshot_leases so this reaper can still find them.
//
// The happy path tries to delete at consume time. Cube often refuses while
// the source and child sandboxes still hold runtime refs, so this reaper
// retries leftover snapshot IDs after those refs drop, and still collects
// forks that were never opened.
package service
import (
"context"
"errors"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// DefaultForkSnapshotRetention is how long an unopened fork keeps its
// snapshot. A week is long enough that "I'll get back to that branch on
// Monday" works, and short enough that abandoned forks do not accumulate.
const DefaultForkSnapshotRetention = 7 * 24 * time.Hour
// DefaultForkSnapshotLeaseGrace is how long a snapshot lease lives before the
// reaper treats it as abandoned. It must outlast CreateForked (milliseconds)
// and a brief process restart, but not a week — there is no session for the
// user to come back to.
const DefaultForkSnapshotLeaseGrace = 15 * time.Minute
type reaperSessionStore interface {
ListUnconsumedForks(ctx context.Context, olderThan time.Time) ([]*types.Session, error)
UpdateForkBootstrap(ctx context.Context, sessionID string, b *types.ForkBootstrap) error
UnconsumedForkSnapshotHolders(ctx context.Context, snapshotID string) ([]string, error)
ListStaleForkSnapshotLeases(ctx context.Context, olderThan time.Time) ([]*types.ForkSnapshotLease, error)
DeleteForkSnapshotLease(ctx context.Context, snapshotID string) error
}
type forkSnapshotReleaseStore interface {
HasOtherUnconsumedForkSnapshot(ctx context.Context, snapshotID, excludeSessionID string) (bool, error)
CreateForkSnapshotLease(ctx context.Context, lease *types.ForkSnapshotLease) error
}
// ForkSnapshotReaper deletes snapshots of forks that were never opened.
type ForkSnapshotReaper struct {
sessions reaperSessionStore
snapshots ForkSnapshotDeleter
retention time.Duration
}
// NewForkSnapshotReaper wires the reaper.
func NewForkSnapshotReaper(
sessions reaperSessionStore, snapshots ForkSnapshotDeleter, retention time.Duration,
) *ForkSnapshotReaper {
if retention <= 0 {
retention = DefaultForkSnapshotRetention
}
return &ForkSnapshotReaper{sessions: sessions, snapshots: snapshots, retention: retention}
}
// NewForkSnapshotReaperFromRepos is the exported DI constructor. It uses the
// default retention; tests inject a shorter window through NewForkSnapshotReaper.
func NewForkSnapshotReaperFromRepos(
sessions interfaces.SessionRepository, snapshots ForkSnapshotDeleter,
) *ForkSnapshotReaper {
return NewForkSnapshotReaper(sessions, snapshots, DefaultForkSnapshotRetention)
}
type forkSessionSnapshotDeleter interface {
DeleteForkSnapshot(ctx context.Context, tenantID uint64, sandboxConfigID, snapshotID string) error
}
// ReapOnce runs a single collection pass and reports how many snapshots it
// retired.
//
// A per-snapshot delete failure is logged and skipped rather than returned:
// one unreachable snapshot must not stop the pass, and the next run retries it.
func (r *ForkSnapshotReaper) ReapOnce(ctx context.Context) (int, error) {
if r == nil || r.sessions == nil || r.snapshots == nil {
return 0, nil
}
cutoff := time.Now().UTC().Add(-r.retention)
stale, err := r.sessions.ListUnconsumedForks(ctx, cutoff)
if err != nil {
return 0, err
}
staleIDs := make(map[string]struct{}, len(stale))
for _, session := range stale {
if session != nil {
staleIDs[session.ID] = struct{}{}
}
}
deleted := make(map[string]bool)
skipped := make(map[string]bool)
reaped := 0
for _, session := range stale {
if session == nil || session.ForkBootstrap == nil {
continue
}
snapshotID := session.ForkBootstrap.SnapshotID
if strings.TrimSpace(snapshotID) == "" {
continue
}
if skipped[snapshotID] {
continue
}
if deleted[snapshotID] {
if err := r.sessions.UpdateForkBootstrap(ctx, session.ID, nil); err != nil {
logger.Warnf(ctx, "[ForkSnapshotReaper] clear bootstrap of %s failed: %v",
session.ID, err)
continue
}
reaped++
continue
}
holders, shareErr := r.sessions.UnconsumedForkSnapshotHolders(ctx, snapshotID)
if shareErr != nil {
logger.Warnf(ctx, "[ForkSnapshotReaper] lookup snapshot holders %s failed; leaving it: %v",
snapshotID, shareErr)
continue
}
if snapshotHeldOutsideBatch(holders, staleIDs) {
skipped[snapshotID] = true
continue
}
if err := r.deleteSnapshot(ctx, session, snapshotID); err != nil {
// Clearing the bootstrap now would drop the only record of this
// snapshot's ID and leak it permanently. Leave it for next time.
logger.Warnf(ctx, "[ForkSnapshotReaper] delete %s (session=%s) failed: %v",
snapshotID, session.ID, err)
continue
}
if err := r.sessions.UpdateForkBootstrap(ctx, session.ID, nil); err != nil {
logger.Warnf(ctx, "[ForkSnapshotReaper] clear bootstrap of %s failed: %v",
session.ID, err)
continue
}
deleted[snapshotID] = true
reaped++
}
leased, err := r.reapSnapshotLeases(ctx, deleted, skipped)
if err != nil {
return reaped, err
}
reaped += leased
if reaped > 0 {
logger.Infof(ctx, "[ForkSnapshotReaper] reaped %d orphan fork snapshot(s)", reaped)
}
return reaped, nil
}
// releaseForkSnapshotOnDelete retires a fork snapshot that no remaining live
// session needs. Call it after the session row is gone so a sibling that still
// lists the same snapshot is not stranded. Delete failure writes a lease so
// the reaper can retry; lookup failure does the same rather than risk deleting
// a snapshot another fork still needs.
func releaseForkSnapshotOnDelete(
ctx context.Context,
sessions forkSnapshotReleaseStore,
snapshots ForkSnapshotDeleter,
session *types.Session,
) {
if session == nil || session.ForkBootstrap == nil {
return
}
snapshotID := strings.TrimSpace(session.ForkBootstrap.SnapshotID)
if snapshotID == "" {
return
}
if sessions != nil {
keep, err := sessions.HasOtherUnconsumedForkSnapshot(ctx, snapshotID, session.ID)
if err != nil {
logger.Warnf(ctx, "[SessionFork] lookup snapshot holders %s failed; leasing it: %v",
snapshotID, err)
leaseForkSnapshotOnDelete(ctx, sessions, session, snapshotID)
return
}
if keep {
return
}
}
if err := deleteForkSnapshot(ctx, snapshots, session, snapshotID); err != nil {
logger.Warnf(ctx, "[SessionFork] delete snapshot %s on session delete failed: %v",
snapshotID, err)
leaseForkSnapshotOnDelete(ctx, sessions, session, snapshotID)
}
}
func leaseForkSnapshotOnDelete(
ctx context.Context,
sessions forkSnapshotReleaseStore,
session *types.Session,
snapshotID string,
) {
if sessions == nil || session == nil || strings.TrimSpace(snapshotID) == "" {
return
}
lease := &types.ForkSnapshotLease{
SnapshotID: snapshotID,
TenantID: session.TenantID,
SandboxConfigID: session.SandboxConfigID,
CreatedAt: time.Now().UTC(),
}
if err := sessions.CreateForkSnapshotLease(ctx, lease); err != nil {
logger.Warnf(ctx, "[SessionFork] record snapshot lease %s failed: %v", snapshotID, err)
}
}
func (r *ForkSnapshotReaper) reapSnapshotLeases(
ctx context.Context, deleted, skipped map[string]bool,
) (int, error) {
cutoff := time.Now().UTC().Add(-DefaultForkSnapshotLeaseGrace)
leases, err := r.sessions.ListStaleForkSnapshotLeases(ctx, cutoff)
if err != nil {
return 0, err
}
reaped := 0
for _, lease := range leases {
if lease == nil || strings.TrimSpace(lease.SnapshotID) == "" {
continue
}
snapshotID := lease.SnapshotID
if skipped[snapshotID] {
continue
}
holders, shareErr := r.sessions.UnconsumedForkSnapshotHolders(ctx, snapshotID)
if shareErr != nil {
logger.Warnf(ctx, "[ForkSnapshotReaper] lookup snapshot holders %s failed; leaving lease: %v",
snapshotID, shareErr)
continue
}
if len(holders) > 0 {
if err := r.sessions.DeleteForkSnapshotLease(ctx, snapshotID); err != nil {
logger.Warnf(ctx, "[ForkSnapshotReaper] clear lease %s failed: %v", snapshotID, err)
}
continue
}
if deleted[snapshotID] {
if err := r.sessions.DeleteForkSnapshotLease(ctx, snapshotID); err != nil {
logger.Warnf(ctx, "[ForkSnapshotReaper] clear lease %s failed: %v", snapshotID, err)
continue
}
reaped++
continue
}
placeholder := &types.Session{
TenantID: lease.TenantID,
SandboxConfigID: lease.SandboxConfigID,
}
if err := r.deleteSnapshot(ctx, placeholder, snapshotID); err != nil {
logger.Warnf(ctx, "[ForkSnapshotReaper] delete leased snapshot %s failed: %v",
snapshotID, err)
continue
}
if err := r.sessions.DeleteForkSnapshotLease(ctx, snapshotID); err != nil {
logger.Warnf(ctx, "[ForkSnapshotReaper] clear lease %s failed: %v", snapshotID, err)
continue
}
deleted[snapshotID] = true
reaped++
}
return reaped, nil
}
func snapshotHeldOutsideBatch(holders []string, staleIDs map[string]struct{}) bool {
for _, id := range holders {
if _, inBatch := staleIDs[id]; !inBatch {
return true
}
}
return false
}
func (r *ForkSnapshotReaper) deleteSnapshot(
ctx context.Context, session *types.Session, snapshotID string,
) error {
return deleteForkSnapshot(ctx, r.snapshots, session, snapshotID)
}
func deleteForkSnapshot(
ctx context.Context, snapshots ForkSnapshotDeleter, session *types.Session, snapshotID string,
) error {
if snapshots == nil {
return errors.New("fork snapshot deleter is nil")
}
var err error
if session != nil {
if scoped, ok := snapshots.(forkSessionSnapshotDeleter); ok {
err = scoped.DeleteForkSnapshot(ctx, session.TenantID, session.SandboxConfigID, snapshotID)
} else {
err = snapshots.DeleteSnapshot(ctx, snapshotID)
}
} else {
err = snapshots.DeleteSnapshot(ctx, snapshotID)
}
if err == nil || sandbox.IsRemoteNotFound(err) {
return nil
}
return err
}
type resolverForkSnapshotDeleter struct {
resolver sandbox.TenantSandboxResolver
fallback sandbox.Manager
}
// NewResolverForkSnapshotDeleter deletes fork snapshots through the tenant's
// sandbox manager. Cube and E2B credentials are per-tenant, so an ID-only
// delete cannot reach them.
func NewResolverForkSnapshotDeleter(
resolver sandbox.TenantSandboxResolver, fallback sandbox.Manager,
) ForkSnapshotDeleter {
return &resolverForkSnapshotDeleter{resolver: resolver, fallback: fallback}
}
func (d *resolverForkSnapshotDeleter) DeleteSnapshot(context.Context, string) error {
return errors.New("fork snapshot delete requires tenant and sandbox config")
}
type managerSnapshotDeleter interface {
DeleteSnapshot(ctx context.Context, snapshotID string) error
}
func (d *resolverForkSnapshotDeleter) DeleteForkSnapshot(
ctx context.Context, tenantID uint64, sandboxConfigID, snapshotID string,
) error {
if d == nil {
return errors.New("fork snapshot deleter is nil")
}
ctx = context.WithValue(ctx, types.TenantIDContextKey, tenantID)
mgr, err := resolveTenantSandboxForConfig(ctx, d.resolver, d.fallback, tenantID, sandboxConfigID, nil)
if err != nil {
return err
}
deleter, ok := mgr.(managerSnapshotDeleter)
if !ok || deleter == nil {
return errors.New("sandbox: resolved manager does not support snapshot delete")
}
return deleter.DeleteSnapshot(ctx, snapshotID)
}
var (
_ ForkSnapshotDeleter = (*resolverForkSnapshotDeleter)(nil)
_ forkSessionSnapshotDeleter = (*resolverForkSnapshotDeleter)(nil)
)

View File

@ -0,0 +1,343 @@
package service
import (
"context"
"errors"
"testing"
"time"
"github.com/Tencent/WeKnora/internal/types"
"github.com/stretchr/testify/require"
)
func agedFork(id string, age time.Duration) *types.Session {
return &types.Session{
ID: id, TenantID: 1,
ForkBootstrap: &types.ForkBootstrap{
SnapshotID: "snap-" + id,
CreatedAt: time.Now().UTC().Add(-age),
},
}
}
func TestReapDeletesSnapshotAndClearsBootstrap(t *testing.T) {
sessions := newFakeSessionStore(nil)
sessions.unconsumed = []*types.Session{agedFork("f1", 8*24*time.Hour)}
snapshots := &fakeSnapshotDeleter{}
reaper := NewForkSnapshotReaper(sessions, snapshots, 7*24*time.Hour)
n, err := reaper.ReapOnce(context.Background())
require.NoError(t, err)
require.Equal(t, 1, n)
require.Equal(t, []string{"snap-f1"}, snapshots.deleted)
require.True(t, sessions.bootstrapCleared)
}
func TestReapReportsZeroWhenNothingIsOldEnough(t *testing.T) {
sessions := newFakeSessionStore(nil)
sessions.unconsumed = nil // 仓储层已按 retention 过滤
reaper := NewForkSnapshotReaper(sessions, &fakeSnapshotDeleter{}, 7*24*time.Hour)
n, err := reaper.ReapOnce(context.Background())
require.NoError(t, err)
require.Zero(t, n)
}
// 一个删不掉的快照不该挡住后面的。
func TestReapContinuesAfterOneDeleteFails(t *testing.T) {
sessions := newFakeSessionStore(nil)
sessions.unconsumed = []*types.Session{
agedFork("f1", 8*24*time.Hour),
agedFork("f2", 9*24*time.Hour),
}
snapshots := &fakeSnapshotDeleter{err: errors.New("provider timeout")}
reaper := NewForkSnapshotReaper(sessions, snapshots, 7*24*time.Hour)
_, err := reaper.ReapOnce(context.Background())
require.NoError(t, err, "单个删除失败不该让整轮回收报错")
require.Len(t, snapshots.deleted, 2, "两个都要尝试")
}
// 删不掉时绝不能清空 bootstrap,否则快照 ID 丢失,快照永久泄漏。
func TestReapKeepsBootstrapWhenDeleteFails(t *testing.T) {
sessions := newFakeSessionStore(nil)
sessions.unconsumed = []*types.Session{agedFork("f1", 8*24*time.Hour)}
snapshots := &fakeSnapshotDeleter{err: errors.New("provider timeout")}
reaper := NewForkSnapshotReaper(sessions, snapshots, 7*24*time.Hour)
_, err := reaper.ReapOnce(context.Background())
require.NoError(t, err)
require.False(t, sessions.bootstrapCleared)
}
func TestReapDeletesStaleLeaseWithNoSessionHolder(t *testing.T) {
sessions := newFakeSessionStore(nil)
sessions.leases = []*types.ForkSnapshotLease{{
SnapshotID: "snap-orphan",
TenantID: 9,
SandboxConfigID: "cfg-1",
CreatedAt: time.Now().UTC().Add(-20 * time.Minute),
}}
snapshots := &fakeForkSessionSnapshotDeleter{}
reaper := NewForkSnapshotReaper(sessions, snapshots, 7*24*time.Hour)
n, err := reaper.ReapOnce(context.Background())
require.NoError(t, err)
require.Equal(t, 1, n)
require.Equal(t, []string{"snap-orphan"}, snapshots.forkDeleted)
require.Empty(t, sessions.leases)
}
func TestReapSkipsFreshLease(t *testing.T) {
sessions := newFakeSessionStore(nil)
sessions.leases = []*types.ForkSnapshotLease{{
SnapshotID: "snap-fresh",
CreatedAt: time.Now().UTC(),
}}
snapshots := &fakeSnapshotDeleter{}
reaper := NewForkSnapshotReaper(sessions, snapshots, 7*24*time.Hour)
n, err := reaper.ReapOnce(context.Background())
require.NoError(t, err)
require.Zero(t, n)
require.Empty(t, snapshots.deleted)
require.Len(t, sessions.leases, 1)
}
func TestReapDropsLeaseWhenSessionHoldsSnapshot(t *testing.T) {
holder := agedFork("f1", time.Hour)
holder.ForkBootstrap.SnapshotID = "snap-held"
sessions := newFakeSessionStore(holder)
sessions.leases = []*types.ForkSnapshotLease{{
SnapshotID: "snap-held",
CreatedAt: time.Now().UTC().Add(-20 * time.Minute),
}}
snapshots := &fakeSnapshotDeleter{}
reaper := NewForkSnapshotReaper(sessions, snapshots, 7*24*time.Hour)
n, err := reaper.ReapOnce(context.Background())
require.NoError(t, err)
require.Zero(t, n)
require.Empty(t, snapshots.deleted, "session still needs this snapshot")
require.Empty(t, sessions.leases, "redundant lease is just bookkeeping")
}
type fakeForkSessionSnapshotDeleter struct {
fakeSnapshotDeleter
forkDeleted []string
forkErr error
lastTenant uint64
lastConfig string
}
func (f *fakeForkSessionSnapshotDeleter) DeleteForkSnapshot(
_ context.Context, tenantID uint64, sandboxConfigID, snapshotID string,
) error {
f.lastTenant = tenantID
f.lastConfig = sandboxConfigID
f.forkDeleted = append(f.forkDeleted, snapshotID)
return f.forkErr
}
func TestReapPrefersTenantScopedForkDelete(t *testing.T) {
sessions := newFakeSessionStore(nil)
sess := agedFork("f1", 8*24*time.Hour)
sess.SandboxConfigID = "cfg-1"
sessions.unconsumed = []*types.Session{sess}
snapshots := &fakeForkSessionSnapshotDeleter{}
reaper := NewForkSnapshotReaper(sessions, snapshots, 7*24*time.Hour)
n, err := reaper.ReapOnce(context.Background())
require.NoError(t, err)
require.Equal(t, 1, n)
require.Equal(t, []string{"snap-f1"}, snapshots.forkDeleted)
require.Equal(t, uint64(1), snapshots.lastTenant)
require.Equal(t, "cfg-1", snapshots.lastConfig)
require.Empty(t, snapshots.deleted, "ID-only DeleteSnapshot must not run when tenant-scoped delete exists")
require.True(t, sessions.bootstrapCleared)
}
func TestReapSkipsSnapshotStillNeededByUnopenedSibling(t *testing.T) {
sessions := newFakeSessionStore(&types.Session{
ID: "unopened", TenantID: 1,
ForkBootstrap: &types.ForkBootstrap{
SnapshotID: "snap-shared",
CreatedAt: time.Now().UTC(),
},
})
consumedAt := time.Now().UTC()
sessions.unconsumed = []*types.Session{{
ID: "opened", TenantID: 1,
ForkBootstrap: &types.ForkBootstrap{
SnapshotID: "snap-shared",
CreatedAt: consumedAt.Add(-time.Minute),
ConsumedAt: &consumedAt,
},
}}
snapshots := &fakeSnapshotDeleter{}
reaper := NewForkSnapshotReaper(sessions, snapshots, 7*24*time.Hour)
n, err := reaper.ReapOnce(context.Background())
require.NoError(t, err)
require.Zero(t, n)
require.Empty(t, snapshots.deleted)
require.False(t, sessions.bootstrapCleared)
}
func TestReapDeletesSharedSnapshotOnceBothHoldersAreStale(t *testing.T) {
sessions := newFakeSessionStore(nil)
sessions.unconsumed = []*types.Session{
agedFork("f1", 8*24*time.Hour),
{
ID: "f2", TenantID: 1,
ForkBootstrap: &types.ForkBootstrap{
SnapshotID: "snap-f1",
CreatedAt: time.Now().UTC().Add(-9 * 24 * time.Hour),
},
},
}
snapshots := &fakeSnapshotDeleter{}
reaper := NewForkSnapshotReaper(sessions, snapshots, 7*24*time.Hour)
n, err := reaper.ReapOnce(context.Background())
require.NoError(t, err)
require.Equal(t, 2, n)
require.Equal(t, []string{"snap-f1"}, snapshots.deleted)
}
func TestReapRetriesConsumedLeftoverSnapshot(t *testing.T) {
sessions := newFakeSessionStore(nil)
consumedAt := time.Now().UTC()
sessions.unconsumed = []*types.Session{{
ID: "fork-1", TenantID: 1,
ForkBootstrap: &types.ForkBootstrap{
SnapshotID: "snap-fork-1",
CreatedAt: consumedAt.Add(-time.Minute),
ConsumedAt: &consumedAt,
},
}}
snapshots := &fakeSnapshotDeleter{}
reaper := NewForkSnapshotReaper(sessions, snapshots, 7*24*time.Hour)
n, err := reaper.ReapOnce(context.Background())
require.NoError(t, err)
require.Equal(t, 1, n)
require.Equal(t, []string{"snap-fork-1"}, snapshots.deleted)
require.True(t, sessions.bootstrapCleared)
}
func TestReapKeepsBootstrapWhenForkDeleteFails(t *testing.T) {
sessions := newFakeSessionStore(nil)
sessions.unconsumed = []*types.Session{agedFork("f1", 8*24*time.Hour)}
snapshots := &fakeForkSessionSnapshotDeleter{forkErr: errors.New("cube timeout")}
reaper := NewForkSnapshotReaper(sessions, snapshots, 7*24*time.Hour)
_, err := reaper.ReapOnce(context.Background())
require.NoError(t, err)
require.False(t, sessions.bootstrapCleared)
}
type stubSnapshotDeletingManager struct {
stubPinnedManager
deleted []string
err error
}
func (m *stubSnapshotDeletingManager) DeleteSnapshot(_ context.Context, snapshotID string) error {
m.deleted = append(m.deleted, snapshotID)
return m.err
}
func TestResolverForkSnapshotDeleterDeletesViaResolvedManager(t *testing.T) {
mgr := &stubSnapshotDeletingManager{}
resolver := &stubTenantSandboxResolver{mgr: mgr}
deleter := NewResolverForkSnapshotDeleter(resolver, nil)
scoped, ok := deleter.(forkSessionSnapshotDeleter)
require.True(t, ok)
err := scoped.DeleteForkSnapshot(context.Background(), 9, "cfg-1", "snap-1")
require.NoError(t, err)
require.Equal(t, []string{"snap-1"}, mgr.deleted)
require.Equal(t, 1, resolver.calls)
require.Equal(t, "cfg-1", resolver.lastCfg)
}
func TestResolverForkSnapshotDeleterKeepsIDOnlyDeleteUnsupported(t *testing.T) {
err := NewResolverForkSnapshotDeleter(nil, nil).DeleteSnapshot(context.Background(), "snap-1")
require.Error(t, err)
}
func TestReleaseForkSnapshotOnDeleteRemovesUnusedSnapshot(t *testing.T) {
session := &types.Session{
ID: "fork-1", TenantID: 9, UserID: "u1", SandboxConfigID: "cfg-1",
ForkBootstrap: &types.ForkBootstrap{SnapshotID: "snap-1", CreatedAt: time.Now().UTC()},
}
sessions := newFakeSessionStore(session)
snapshots := &fakeForkSessionSnapshotDeleter{}
releaseForkSnapshotOnDelete(context.Background(), sessions, snapshots, session)
require.Equal(t, []string{"snap-1"}, snapshots.forkDeleted)
require.Equal(t, uint64(9), snapshots.lastTenant)
require.Equal(t, "cfg-1", snapshots.lastConfig)
require.Empty(t, sessions.leases)
}
func TestReleaseForkSnapshotOnDeleteKeepsSharedSnapshot(t *testing.T) {
session := &types.Session{
ID: "fork-1", TenantID: 1, UserID: "u1",
ForkBootstrap: &types.ForkBootstrap{SnapshotID: "snap-shared", CreatedAt: time.Now().UTC()},
}
sessions := newFakeSessionStore(session)
sessions.unconsumed = []*types.Session{{
ID: "sibling", TenantID: 1,
ForkBootstrap: &types.ForkBootstrap{SnapshotID: "snap-shared", CreatedAt: time.Now().UTC()},
}}
snapshots := &fakeForkSessionSnapshotDeleter{}
releaseForkSnapshotOnDelete(context.Background(), sessions, snapshots, session)
require.Empty(t, snapshots.forkDeleted)
require.Empty(t, sessions.leases)
}
func TestReleaseForkSnapshotOnDeleteLeasesWhenDeleteFails(t *testing.T) {
session := &types.Session{
ID: "fork-1", TenantID: 9, UserID: "u1", SandboxConfigID: "cfg-1",
ForkBootstrap: &types.ForkBootstrap{SnapshotID: "snap-1", CreatedAt: time.Now().UTC()},
}
sessions := newFakeSessionStore(session)
snapshots := &fakeForkSessionSnapshotDeleter{forkErr: errors.New("cube timeout")}
releaseForkSnapshotOnDelete(context.Background(), sessions, snapshots, session)
require.Equal(t, []string{"snap-1"}, snapshots.forkDeleted)
require.Len(t, sessions.leases, 1)
require.Equal(t, "snap-1", sessions.leases[0].SnapshotID)
require.Equal(t, uint64(9), sessions.leases[0].TenantID)
require.Equal(t, "cfg-1", sessions.leases[0].SandboxConfigID)
}
func TestReleaseForkSnapshotOnDeleteSkipsSessionsWithoutBootstrap(t *testing.T) {
session := &types.Session{ID: "plain", TenantID: 1, UserID: "u1"}
sessions := newFakeSessionStore(session)
snapshots := &fakeForkSessionSnapshotDeleter{}
releaseForkSnapshotOnDelete(context.Background(), sessions, snapshots, session)
require.Empty(t, snapshots.forkDeleted)
require.Empty(t, sessions.leases)
}

View File

@ -855,14 +855,14 @@ func (s *messageService) fetchPartnerMessages(ctx context.Context, items []*type
existingIDs := make(map[string]bool)
for _, item := range items {
existingIDs[item.ID] = true
rid := item.RequestID
if rid == "" {
if item.RequestID == "" || item.SessionID == "" {
continue
}
rs, ok := seen[rid]
key := searchPairKey(item.SessionID, item.RequestID)
rs, ok := seen[key]
if !ok {
rs = &roleSet{}
seen[rid] = rs
seen[key] = rs
}
if item.Role == "user" {
rs.hasUser = true
@ -871,35 +871,38 @@ func (s *messageService) fetchPartnerMessages(ctx context.Context, items []*type
}
}
// Find request_ids that need partner lookup
var needFetch []string
for rid, rs := range seen {
if !rs.hasUser || !rs.hasAssistant {
needFetch = append(needFetch, rid)
}
}
if len(needFetch) == 0 {
return items
}
// Fetch partner messages
partners, err := s.messageRepo.GetMessagesByRequestIDs(ctx, needFetch)
if err != nil {
logger.Warnf(ctx, "Failed to fetch partner messages: %v", err)
return items
}
// Append only messages not already in results
for _, p := range partners {
if existingIDs[p.ID] {
needBySession := make(map[string][]string)
for key, rs := range seen {
if rs.hasUser && rs.hasAssistant {
continue
}
existingIDs[p.ID] = true
items = append(items, &types.MessageSearchResultItem{
MessageWithSession: *p,
Score: 0, // partner is not directly matched
MatchType: "",
})
sessionID, rid, ok := strings.Cut(key, "\x00")
if !ok || sessionID == "" || rid == "" {
continue
}
needBySession[sessionID] = append(needBySession[sessionID], rid)
}
if len(needBySession) == 0 {
return items
}
for sessionID, rids := range needBySession {
partners, err := s.messageRepo.GetMessagesByRequestIDs(ctx, sessionID, rids)
if err != nil {
logger.Warnf(ctx, "Failed to fetch partner messages: %v", err)
return items
}
for _, p := range partners {
if existingIDs[p.ID] {
continue
}
existingIDs[p.ID] = true
items = append(items, &types.MessageSearchResultItem{
MessageWithSession: *p,
Score: 0, // partner is not directly matched
MatchType: "",
})
}
}
return items
@ -916,10 +919,9 @@ func groupByRequestID(items []*types.MessageSearchResultItem) []*types.MessageSe
nextOrder := 0
for _, item := range items {
key := item.RequestID
if key == "" {
// No request_id — treat as standalone
key = item.ID
key := item.ID
if item.RequestID != "" {
key = searchPairKey(item.SessionID, item.RequestID)
}
g, exists := groups[key]
@ -976,3 +978,7 @@ func groupByRequestID(items []*types.MessageSearchResultItem) []*types.MessageSe
return result
}
func searchPairKey(sessionID, requestID string) string {
return sessionID + "\x00" + requestID
}

View File

@ -2,6 +2,7 @@ package service
import (
"context"
stderrors "errors"
"testing"
"github.com/Tencent/WeKnora/internal/types"
@ -37,10 +38,16 @@ func TestHistoricalVersionClarificationAcrossPagination(t *testing.T) {
require.Equal(t, 1, repo.calls, "matching current references need no session-wide lookup")
}
func TestReferencedArtifactHistoryDoesNotGuessByName(t *testing.T) {
func TestSessionArtifactsReadsEveryRecordedArtifact(t *testing.T) {
old := types.MessageArtifact{URL: "resource://dHZ_fFslfs0GgJGaJZGjGA", FileName: "deck.pptx"}
c := &ArtifactCollector{store: &fakeStore{prev: []types.MessageArtifact{old, old}}}
got := c.ReferencedHistory(context.Background(), "session", "message", "![deck]("+old.URL+")")
require.Equal(t, types.MessageArtifacts{old}, got)
require.Empty(t, c.ReferencedHistory(context.Background(), "session", "message", "![deck](resource://4N1nAo-FZZoDEExDQz2yoA)"))
c := &ArtifactCollector{store: &fakeStore{prev: []types.MessageArtifact{old}}}
require.Equal(t, types.MessageArtifacts{old}, c.SessionArtifacts(context.Background(), "session"))
// A missing store, an empty session, and a lookup failure all degrade to
// "nothing to resolve" rather than failing the turn.
require.Nil(t, (&ArtifactCollector{}).SessionArtifacts(context.Background(), "session"))
require.Nil(t, c.SessionArtifacts(context.Background(), ""))
require.Nil(t, (&ArtifactCollector{
store: &fakeStore{err: stderrors.New("boom")},
}).SessionArtifacts(context.Background(), "session"))
}

View File

@ -0,0 +1,73 @@
package service
import (
"context"
"testing"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/stretchr/testify/require"
)
func TestGroupByRequestIDKeepsSessionsApart(t *testing.T) {
items := []*types.MessageSearchResultItem{
{MessageWithSession: types.MessageWithSession{Message: types.Message{
ID: "p-u", SessionID: "parent", RequestID: "req", Role: "user", Content: "q-parent",
}}},
{MessageWithSession: types.MessageWithSession{Message: types.Message{
ID: "f-u", SessionID: "fork", RequestID: "req", Role: "user", Content: "q-fork",
}}},
}
got := groupByRequestID(items)
require.Len(t, got, 2)
bySession := map[string]string{}
for _, g := range got {
bySession[g.SessionID] = g.QueryContent
}
require.Equal(t, "q-parent", bySession["parent"])
require.Equal(t, "q-fork", bySession["fork"])
}
type partnerLookupRepo struct {
interfaces.MessageRepository
calls []partnerLookupCall
}
type partnerLookupCall struct {
sessionID string
requestIDs []string
}
func (r *partnerLookupRepo) GetMessagesByRequestIDs(
_ context.Context, sessionID string, requestIDs []string,
) ([]*types.MessageWithSession, error) {
copied := append([]string(nil), requestIDs...)
r.calls = append(r.calls, partnerLookupCall{sessionID: sessionID, requestIDs: copied})
return nil, nil
}
func TestFetchPartnerMessagesQueriesEachSessionSeparately(t *testing.T) {
repo := &partnerLookupRepo{}
svc := &messageService{messageRepo: repo}
items := []*types.MessageSearchResultItem{
{MessageWithSession: types.MessageWithSession{Message: types.Message{
ID: "p-u", SessionID: "parent", RequestID: "req", Role: "user",
}}},
{MessageWithSession: types.MessageWithSession{Message: types.Message{
ID: "f-u", SessionID: "fork", RequestID: "req", Role: "user",
}}},
}
got := svc.fetchPartnerMessages(context.Background(), items)
require.Equal(t, items, got)
require.Len(t, repo.calls, 2)
bySession := map[string][]string{}
for _, call := range repo.calls {
bySession[call.sessionID] = call.requestIDs
}
require.Equal(t, []string{"req"}, bySession["parent"])
require.Equal(t, []string{"req"}, bySession["fork"])
}

View File

@ -0,0 +1,150 @@
package service
import (
"context"
"errors"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/Tencent/WeKnora/internal/types"
)
// sessionSandboxPinReader is the pin lookup used to choose the manager that
// owns a session's binding. *SessionSandboxPinner is the production
// implementation; tests use a stub so this does not need a database.
type sessionSandboxPinReader interface {
Read(ctx context.Context, sessionID string) (string, error)
}
// PinnedSessionSandbox resolves the session's pinned sandbox manager at
// request time. The process-wide sandbox.Manager is DisabledManager, so
// checkpoint and BoundSandboxID must go through the same pin + tenant
// resolver path ArtifactCollector and SandboxTerminalService already use.
type PinnedSessionSandbox struct {
pinner sessionSandboxPinReader
resolver sandbox.TenantSandboxResolver
fallback sandbox.Manager
}
// NewPinnedSessionSandbox wires request-time sandbox access. Any dependency
// may be nil; BoundSandboxID then reports ok=false and ExecShellCommand
// fails, which WorkspaceCheckpointer treats as "no checkpoint".
func NewPinnedSessionSandbox(
pinner sessionSandboxPinReader,
resolver sandbox.TenantSandboxResolver,
fallback sandbox.Manager,
) *PinnedSessionSandbox {
return &PinnedSessionSandbox{
pinner: pinner,
resolver: resolver,
fallback: fallback,
}
}
func (a *PinnedSessionSandbox) manager(ctx context.Context, sessionID string) sandbox.Manager {
if a == nil || strings.TrimSpace(sessionID) == "" {
return nil
}
if a.pinner == nil {
return nil
}
configID, err := a.pinner.Read(ctx, sessionID)
if err != nil || strings.TrimSpace(configID) == "" {
return nil
}
tenantID, _ := types.TenantIDFromContext(ctx)
mgr, err := resolveTenantSandboxForConfig(
ctx, a.resolver, a.fallback, tenantID, configID, nil,
)
if err != nil {
return nil
}
return mgr
}
// BoundSandboxID reports the sandbox currently bound to sessionID without
// provisioning one. A session with no pin or no live binding reports
// ok=false.
func (a *PinnedSessionSandbox) BoundSandboxID(ctx context.Context, sessionID string) (string, bool) {
mgr := a.manager(ctx, sessionID)
type lookup interface {
BoundSandboxID(context.Context, string) (string, bool)
}
if l, ok := mgr.(lookup); ok {
return l.BoundSandboxID(ctx, sessionID)
}
return "", false
}
// ExecShellCommand runs a command on the session's pinned sandbox manager.
func (a *PinnedSessionSandbox) ExecShellCommand(
ctx context.Context,
sessionID, command, workDir string,
timeout time.Duration,
env map[string]string,
) (*sandbox.ExecuteResult, error) {
mgr := a.manager(ctx, sessionID)
runner, ok := mgr.(SandboxShellRunner)
if !ok || runner == nil {
return nil, errors.New("sandbox: no shell runner for session")
}
return runner.ExecShellCommand(ctx, sessionID, command, workDir, timeout, env)
}
// HasActiveTurn reports whether the session's pinned manager currently holds a
// turn lease. Managers that do not expose the method are treated as not busy.
func (a *PinnedSessionSandbox) HasActiveTurn(ctx context.Context, sessionID string) (bool, error) {
mgr := a.manager(ctx, sessionID)
type turnChecker interface {
HasActiveTurn(context.Context, string) (bool, error)
}
if checker, ok := mgr.(turnChecker); ok {
return checker.HasActiveTurn(ctx, sessionID)
}
return false, nil
}
// 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.
func (a *PinnedSessionSandbox) CreateForkSnapshot(
ctx context.Context, sessionID, name string,
) (string, error) {
mgr := a.manager(ctx, sessionID)
type snapshotter interface {
CreateForkSnapshot(context.Context, string, string) (string, error)
}
if s, ok := mgr.(snapshotter); ok {
return s.CreateForkSnapshot(ctx, sessionID, name)
}
return "", errors.New("sandbox: fork snapshot is not supported")
}
// DeleteForkSnapshot removes a fork snapshot through the session's pinned
// manager. Managers that do not expose the method return an error so the
// caller can keep the lease for the reaper.
func (a *PinnedSessionSandbox) DeleteForkSnapshot(
ctx context.Context, sessionID, snapshotID string,
) error {
mgr := a.manager(ctx, sessionID)
type deleter interface {
DeleteForkSnapshot(context.Context, string, string) error
}
if d, ok := mgr.(deleter); ok {
return d.DeleteForkSnapshot(ctx, sessionID, snapshotID)
}
type snapshotDeleter interface {
DeleteSnapshot(context.Context, string) error
}
if d, ok := mgr.(snapshotDeleter); ok {
return d.DeleteSnapshot(ctx, snapshotID)
}
return errors.New("sandbox: fork snapshot delete is not supported")
}
var _ SandboxShellRunner = (*PinnedSessionSandbox)(nil)
var _ SessionForkSandboxPort = (*PinnedSessionSandbox)(nil)
var _ SessionForkSandboxPort = (*sandbox.SessionBoundManager)(nil)

View File

@ -0,0 +1,163 @@
package service
import (
"context"
"testing"
"time"
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/Tencent/WeKnora/internal/types"
"github.com/stretchr/testify/require"
)
type stubPinReader struct {
configID string
err error
}
func (s stubPinReader) Read(context.Context, string) (string, error) {
return s.configID, s.err
}
type stubTenantSandboxResolver struct {
mgr sandbox.Manager
err error
calls int
lastCfg string
}
func (s *stubTenantSandboxResolver) Resolve(_ context.Context, _ uint64, configID string) (sandbox.Manager, error) {
s.calls++
s.lastCfg = configID
return s.mgr, s.err
}
type stubPinnedManager struct {
id string
ok bool
execs int
execErr error
execOut *sandbox.ExecuteResult
}
func (m *stubPinnedManager) Execute(context.Context, *sandbox.ExecuteConfig) (*sandbox.ExecuteResult, error) {
return nil, nil
}
func (m *stubPinnedManager) Cleanup(context.Context) error { return nil }
func (m *stubPinnedManager) GetSandbox() sandbox.Sandbox { return nil }
func (m *stubPinnedManager) GetType() sandbox.SandboxType { return sandbox.SandboxTypeCube }
func (m *stubPinnedManager) BoundSandboxID(context.Context, string) (string, bool) {
return m.id, m.ok
}
func (m *stubPinnedManager) ExecShellCommand(
_ context.Context, _ string, _, _ string, _ time.Duration, _ map[string]string,
) (*sandbox.ExecuteResult, error) {
m.execs++
if m.execErr != nil {
return nil, m.execErr
}
return m.execOut, nil
}
func TestPinnedSessionSandboxBoundSandboxIDUsesPinnedManager(t *testing.T) {
mgr := &stubPinnedManager{id: "sbx-1", ok: true}
resolver := &stubTenantSandboxResolver{mgr: mgr}
access := NewPinnedSessionSandbox(stubPinReader{configID: "cfg-1"}, resolver, nil)
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(9))
id, ok := access.BoundSandboxID(ctx, "sess-1")
require.True(t, ok)
require.Equal(t, "sbx-1", id)
require.Equal(t, 1, resolver.calls)
require.Equal(t, "cfg-1", resolver.lastCfg)
require.Zero(t, mgr.execs)
}
func TestPinnedSessionSandboxBoundSandboxIDSkipsWhenUnpinned(t *testing.T) {
resolver := &stubTenantSandboxResolver{mgr: &stubPinnedManager{id: "sbx-1", ok: true}}
access := NewPinnedSessionSandbox(stubPinReader{}, resolver, nil)
id, ok := access.BoundSandboxID(context.Background(), "sess-1")
require.False(t, ok)
require.Empty(t, id)
require.Zero(t, resolver.calls)
}
type stubForkPinnedManager struct {
stubPinnedManager
busy bool
busyErr error
snapshotID string
snapErr error
snapCalls int
snapName string
}
func (m *stubForkPinnedManager) HasActiveTurn(context.Context, string) (bool, error) {
return m.busy, m.busyErr
}
func (m *stubForkPinnedManager) CreateForkSnapshot(_ context.Context, _, name string) (string, error) {
m.snapCalls++
m.snapName = name
return m.snapshotID, m.snapErr
}
func TestPinnedSessionSandboxHasActiveTurnDelegates(t *testing.T) {
mgr := &stubForkPinnedManager{busy: true}
access := NewPinnedSessionSandbox(
stubPinReader{configID: "cfg-1"},
&stubTenantSandboxResolver{mgr: mgr},
nil,
)
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(9))
busy, err := access.HasActiveTurn(ctx, "sess-1")
require.NoError(t, err)
require.True(t, busy)
}
func TestPinnedSessionSandboxHasActiveTurnWhenManagerLacksMethod(t *testing.T) {
access := NewPinnedSessionSandbox(
stubPinReader{configID: "cfg-1"},
&stubTenantSandboxResolver{mgr: &stubPinnedManager{id: "sbx-1", ok: true}},
nil,
)
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(9))
busy, err := access.HasActiveTurn(ctx, "sess-1")
require.NoError(t, err)
require.False(t, busy)
}
func TestPinnedSessionSandboxCreateForkSnapshotDelegates(t *testing.T) {
mgr := &stubForkPinnedManager{snapshotID: "snap-9"}
access := NewPinnedSessionSandbox(
stubPinReader{configID: "cfg-1"},
&stubTenantSandboxResolver{mgr: mgr},
nil,
)
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(9))
id, err := access.CreateForkSnapshot(ctx, "sess-1", "fork-name")
require.NoError(t, err)
require.Equal(t, "snap-9", id)
require.Equal(t, 1, mgr.snapCalls)
require.Equal(t, "fork-name", mgr.snapName)
}
func TestPinnedSessionSandboxCreateForkSnapshotErrorsWhenUnsupported(t *testing.T) {
access := NewPinnedSessionSandbox(
stubPinReader{configID: "cfg-1"},
&stubTenantSandboxResolver{mgr: &stubPinnedManager{id: "sbx-1", ok: true}},
nil,
)
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(9))
_, err := access.CreateForkSnapshot(ctx, "sess-1", "fork-name")
require.Error(t, err)
}

View File

@ -134,6 +134,10 @@ type sessionService struct {
// TenantSkillService because that service depends on this one.
sandboxConfigRepo repository.TenantSandboxConfigRepository
tenantSkillRepo repository.TenantSkillRepository
// forkSnapshots retires provider snapshots when a forked session is deleted
// before its sandbox is provisioned. Nil uses NewResolverForkSnapshotDeleter
// from sandboxResolver/sandboxMgr.
forkSnapshots ForkSnapshotDeleter
}
// NewSessionService creates a new session service instance with all required dependencies
@ -480,7 +484,8 @@ func (s *sessionService) DeleteSession(ctx context.Context, id string) error {
tenantID := types.MustTenantIDFromContext(ctx)
userID := sessionUserIDFromContext(ctx)
if _, err := s.sessionRepo.Get(ctx, tenantID, userID, id); err != nil {
session, err := s.sessionRepo.Get(ctx, tenantID, userID, id)
if err != nil {
return err
}
@ -534,6 +539,7 @@ func (s *sessionService) DeleteSession(ctx context.Context, id string) error {
return apperrors.ErrSessionNotFound
}
s.releaseForkSnapshot(ctx, session)
return nil
}
@ -548,9 +554,12 @@ func (s *sessionService) BatchDeleteSessions(ctx context.Context, ids []string)
tenantID := types.MustTenantIDFromContext(ctx)
userID := sessionUserIDFromContext(ctx)
visible := make([]*types.Session, 0, len(ids))
visibleIDs := make([]string, 0, len(ids))
for _, id := range ids {
if _, err := s.sessionRepo.Get(ctx, tenantID, userID, id); err == nil {
session, err := s.sessionRepo.Get(ctx, tenantID, userID, id)
if err == nil {
visible = append(visible, session)
visibleIDs = append(visibleIDs, id)
} else if !stderrors.Is(err, apperrors.ErrSessionNotFound) {
return err
@ -605,6 +614,7 @@ func (s *sessionService) BatchDeleteSessions(ctx context.Context, ids []string)
}
}
s.releaseForkSnapshots(ctx, visible)
return nil
}
@ -663,6 +673,7 @@ func (s *sessionService) DeleteAllSessions(ctx context.Context) error {
}
}
s.releaseForkSnapshots(ctx, sessions)
logger.Infof(ctx, "All sessions deleted for tenant %d", tenantID)
return nil
}
@ -724,6 +735,35 @@ func (s *sessionService) destroyBoundSandbox(ctx context.Context, sessionID stri
}
}
func (s *sessionService) releaseForkSnapshot(ctx context.Context, session *types.Session) {
if s == nil || session == nil {
return
}
snapshots := s.forkSnapshots
if snapshots == nil {
snapshots = NewResolverForkSnapshotDeleter(s.sandboxResolver, s.sandboxMgr)
}
releaseForkSnapshotOnDelete(ctx, s.sessionRepo, snapshots, session)
}
func (s *sessionService) releaseForkSnapshots(ctx context.Context, sessions []*types.Session) {
seen := make(map[string]struct{}, len(sessions))
for _, session := range sessions {
if session == nil || session.ForkBootstrap == nil {
continue
}
snapshotID := strings.TrimSpace(session.ForkBootstrap.SnapshotID)
if snapshotID == "" {
continue
}
if _, ok := seen[snapshotID]; ok {
continue
}
seen[snapshotID] = struct{}{}
s.releaseForkSnapshot(ctx, session)
}
}
// maxSessionTitleRunes bounds the auto-generated session title. sessions.title
// is VARCHAR(255) in every shipped migration, so an over-long model response
// would be rejected by the database; 100 runes stays well clear of that limit

View File

@ -192,12 +192,14 @@ func (s *agentService) stageSessionAttachments(
// deliberately excluded from DB serialization (json:"-") so a cross-session
// downloadable reference cannot leak; the temporary-document row keyed by
// attachment.ID is the authoritative source of the storage reference.
// Lookup is tenant+id (not session-scoped) so a forked session can still
// stage attachments whose temporary_documents row remains on the parent.
// Attachments that already carry a URL, or that have no temporary-document ID,
// pass through unchanged so callers with other attachment sources keep working.
func (s *agentService) resolveSessionAttachmentURLs(
ctx context.Context,
tenantID uint64,
sessionID string,
_ string,
attachments types.MessageAttachments,
) (types.MessageAttachments, error) {
if len(attachments) == 0 || s == nil || s.db == nil {
@ -210,7 +212,7 @@ func (s *agentService) resolveSessionAttachmentURLs(
out = append(out, attachment)
continue
}
document, err := repo.GetScoped(ctx, tenantID, sessionID, attachment.ID)
document, err := repo.GetByID(ctx, tenantID, attachment.ID)
if err != nil {
return nil, fmt.Errorf("resolve attachment %q storage reference: %w", attachment.FileName, err)
}

View File

@ -257,6 +257,59 @@ func TestStageSessionAttachmentsResolvesURLFromTemporaryDocument(t *testing.T) {
assert.Equal(t, 1, fileService.getCalls[resourceRef])
}
func TestStageSessionAttachmentsResolvesURLFromParentSessionDocument(t *testing.T) {
db := stagingTempDocDB(t)
docID := "doc-1"
resourceRef := "local://tenant/attachment-1"
require.NoError(t, db.Create(&types.TemporaryDocument{
ID: docID,
TenantID: 7,
SessionID: "parent-session",
ResourceRef: resourceRef,
FileName: "report.pdf",
FileType: ".pdf",
FileSize: 7,
Status: types.TemporaryDocumentStatusReady,
ExpiresAt: time.Now().Add(time.Hour),
}).Error)
attachment := types.MessageAttachment{
ID: docID,
FileName: "report.pdf",
FileType: ".pdf",
FileSize: 7,
}
remotePath, err := sandboxAttachmentPath(types.MessageAttachment{
URL: resourceRef, FileName: "report.pdf",
})
require.NoError(t, err)
manager := &stagingSandboxManager{sandboxType: sandbox.SandboxTypeCube}
fileService := &stagingFileService{
files: map[string][]byte{resourceRef: []byte("content")},
}
service := &agentService{
db: db,
sandboxMgr: manager,
fileService: fileService,
sandboxResolver: stubSandboxResolver{mgr: manager},
}
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(7))
staged, err := service.stageSessionAttachments(
ctx,
"forked-session",
"cfg-remote",
7,
types.MessageAttachments{attachment},
)
require.NoError(t, err)
require.Len(t, staged, 1)
assert.Equal(t, remotePath, staged[0].Path)
assert.Equal(t, []string{remotePath}, manager.writes)
}
func TestStageSessionAttachmentsSkipsMissingTemporaryDocument(t *testing.T) {
db := stagingTempDocDB(t)
manager := &stagingSandboxManager{sandboxType: sandbox.SandboxTypeCube}

View File

@ -0,0 +1,509 @@
// Package service - session fork.
//
// Fork copies a session's history through a chosen user or assistant message
// into a brand new session, and arranges for that new session's first sandbox
// to boot from a snapshot of the source sandbox rolled back to the fork point.
//
// The whole operation is cheap and synchronous: it writes the database and
// takes one provider snapshot. No sandbox is created here — provisioning stays
// lazy, exactly as it is for ordinary sessions.
package service
import (
"context"
"errors"
"fmt"
"strings"
"time"
apperrors "github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/google/uuid"
"gorm.io/gorm"
)
// ForkDegradeReason explains why a fork could not carry the source sandbox's
// state over. A degraded fork still succeeds — it just starts from a brand new
// sandbox — because the alternative (refusing) would block the common cases:
// Docker kills idle containers outright, and plain chat sessions never had a
// sandbox to begin with.
type ForkDegradeReason string
const (
// ForkDegradeNoCheckpoint means the turn preceding the fork point never
// produced a git checkpoint (commit failed, or it ran without a sandbox).
ForkDegradeNoCheckpoint ForkDegradeReason = "NO_CHECKPOINT"
// ForkDegradeSandboxReplaced means the checkpoint belongs to a sandbox the
// session no longer uses. In-sandbox git history restarts from zero on
// every rebuild, so that SHA is unreachable from the current sandbox.
ForkDegradeSandboxReplaced ForkDegradeReason = "SANDBOX_REPLACED"
// ForkDegradeSandboxGone means the source session has no live sandbox to
// snapshot.
ForkDegradeSandboxGone ForkDegradeReason = "SANDBOX_GONE"
// ForkDegradeSnapshotUnsupported means snapshotting failed or the backend
// does not support it.
ForkDegradeSnapshotUnsupported ForkDegradeReason = "SNAPSHOT_UNSUPPORTED"
)
var (
// ErrForkSourceBusy reports that the source session has an agent turn in
// flight. Snapshotting pauses the source sandbox on every backend, which
// would interrupt a tool mid-execution, so the fork is refused rather than
// queued. HTTP 409.
ErrForkSourceBusy = errors.New("session fork: source session has an active turn")
// ErrForkSessionNotFound covers a missing session and a session the caller
// does not own. Both map to HTTP 404 so ownership is not enumerable.
ErrForkSessionNotFound = errors.New("session fork: source session not found")
// ErrForkMessageNotFound covers a missing message and a message that
// belongs to a different session. HTTP 404.
ErrForkMessageNotFound = errors.New("session fork: fork point message not found")
// ErrForkMessageNotUser is returned when the fork point exists but is
// neither a user nor an assistant message. HTTP 400.
ErrForkMessageNotUser = errors.New("session fork: fork point must be a user or assistant message")
)
// forkSnapshotTimeout bounds the provider snapshot plus the persist that
// follows it. Cube pauses a live MicroVM and copies its disk; that routinely
// exceeds the 30s HTTP-client timeout and the browser's default axios budget.
// The work is detached from the incoming request cancel so a client abort
// mid-snapshot cannot leave a 500 after the snapshot already ran.
const forkSnapshotTimeout = 2 * time.Minute
func isForkNotFound(err error) bool {
return errors.Is(err, apperrors.ErrSessionNotFound) || errors.Is(err, gorm.ErrRecordNotFound)
}
// ForkResult is what the HTTP layer renders.
type ForkResult struct {
SessionID string `json:"session_id"`
Degraded bool `json:"degraded"`
Reason ForkDegradeReason `json:"reason,omitempty"`
}
// SessionForkSandboxPort is the narrow sandbox surface fork needs. It is an
// interface so the fork logic is testable without a provider.
type SessionForkSandboxPort interface {
// BoundSandboxID returns the session's currently bound sandbox without
// provisioning one.
BoundSandboxID(ctx context.Context, sessionID string) (string, bool)
// HasActiveTurn reports whether an agent turn currently holds the
// session's sandbox lease.
HasActiveTurn(ctx context.Context, sessionID string) (bool, error)
// CreateForkSnapshot snapshots the session's live sandbox and returns a
// snapshot ID usable as a create-time template.
CreateForkSnapshot(ctx context.Context, sessionID, name string) (string, error)
// DeleteForkSnapshot removes a snapshot created for sessionID. Used when
// fork persist fails after the snapshot already exists.
DeleteForkSnapshot(ctx context.Context, sessionID, snapshotID string) error
}
type forkSessionStore interface {
GetByID(ctx context.Context, tenantID uint64, id string) (*types.Session, error)
// CreateForked persists the new session and the copied messages in one
// transaction. Copied messages arrive with fresh IDs already assigned and
// SessionID pointing at the new session.
CreateForked(ctx context.Context, session *types.Session, messages []*types.Message) error
CreateForkSnapshotLease(ctx context.Context, lease *types.ForkSnapshotLease) error
DeleteForkSnapshotLease(ctx context.Context, snapshotID string) error
}
type forkMessageStore interface {
GetMessage(ctx context.Context, sessionID, messageID string) (*types.Message, error)
ListMessagesBySessionUpTo(
ctx context.Context, sessionID string, boundary time.Time, boundaryID string,
) ([]*types.Message, error)
}
// SessionForkService implements the fork decision chain.
type SessionForkService struct {
sessions forkSessionStore
messages forkMessageStore
sandbox SessionForkSandboxPort
}
// NewSessionForkService wires the service. A nil sandbox port makes every fork
// degrade, which is the correct behaviour for a deployment without sandboxes.
func NewSessionForkService(
sessions forkSessionStore,
messages forkMessageStore,
sandboxPort SessionForkSandboxPort,
) *SessionForkService {
return &SessionForkService{sessions: sessions, messages: messages, sandbox: sandboxPort}
}
// NewSessionForkServiceFromRepos is the DI-friendly constructor. The
// repository interfaces satisfy the narrow ports structurally.
func NewSessionForkServiceFromRepos(
sessions interfaces.SessionRepository,
messages interfaces.MessageRepository,
sandboxPort SessionForkSandboxPort,
) *SessionForkService {
return NewSessionForkService(sessions, messages, sandboxPort)
}
// Fork branches sourceSessionID at messageID.
//
// Errors are reserved for conditions the user must act on: a bad request, a
// session they do not own, or a source that is busy. Everything about the
// sandbox degrades instead, and is reported through ForkResult.
func (s *SessionForkService) Fork(
ctx context.Context,
tenantID uint64,
userID string,
sourceSessionID string,
messageID string,
title string,
) (*ForkResult, error) {
source, err := s.sessions.GetByID(ctx, tenantID, sourceSessionID)
if err != nil {
if isForkNotFound(err) {
return nil, ErrForkSessionNotFound
}
return nil, fmt.Errorf("session fork: load source session: %w", err)
}
if source == nil {
return nil, ErrForkSessionNotFound
}
// Fork is a write. Empty user_id rows are tenant-level channel/legacy
// sessions: list/read scope still surfaces them, but copying history into
// a new session requires an exact owner match. Skipping that when UserID
// is empty would let any same-tenant caller fork the row.
if userID == "" || source.UserID != userID {
return nil, ErrForkSessionNotFound
}
forkPoint, err := s.messages.GetMessage(ctx, sourceSessionID, messageID)
if err != nil {
if isForkNotFound(err) {
return nil, ErrForkMessageNotFound
}
return nil, fmt.Errorf("session fork: load fork point: %w", err)
}
if forkPoint == nil {
return nil, ErrForkMessageNotFound
}
if forkPoint.Role != "user" && forkPoint.Role != "assistant" {
return nil, ErrForkMessageNotUser
}
// An unfinished assistant answer is still the live turn. Snapshotting
// would pause the sandbox under it; treat it like a busy source.
if forkPoint.Role == "assistant" && !forkPoint.IsCompleted {
return nil, ErrForkSourceBusy
}
// Refuse before doing anything observable: snapshotting pauses the source
// sandbox, and interrupting a running tool is worse than making the user
// wait for the turn to finish.
if s.sandbox != nil {
busy, turnErr := s.sandbox.HasActiveTurn(ctx, sourceSessionID)
if turnErr != nil {
return nil, fmt.Errorf("session fork: check source turn state: %w", turnErr)
}
if busy {
return nil, ErrForkSourceBusy
}
}
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()
bootstrap, reason, createdSnapshot, prepErr := s.prepareBootstrap(workCtx, source, history)
if prepErr != nil {
return nil, prepErr
}
if createdSnapshot {
if err := s.recordSnapshotLease(workCtx, source, bootstrap); err != nil {
s.abandonCreatedSnapshot(workCtx, source.ID, bootstrap.SnapshotID)
return nil, err
}
}
newSession := &types.Session{
ID: uuid.New().String(),
TenantID: source.TenantID,
UserID: source.UserID,
Title: forkTitle(title, source.Title),
Description: source.Description,
LastRequestState: source.LastRequestState,
SandboxConfigID: source.SandboxConfigID,
ParentSessionID: source.ID,
ForkedFromMessageID: forkPoint.ID,
ForkBootstrap: bootstrap,
}
copied := copyMessagesInto(newSession.ID, history)
if err := s.sessions.CreateForked(workCtx, newSession, copied); err != nil {
if createdSnapshot {
s.abandonCreatedSnapshot(workCtx, source.ID, bootstrap.SnapshotID)
}
return nil, fmt.Errorf("session fork: persist forked session: %w", err)
}
if createdSnapshot {
s.clearSnapshotLease(workCtx, bootstrap.SnapshotID)
}
logger.Infof(ctx,
"[SessionFork] source=%s fork_point=%s new=%s messages=%d degraded=%v reason=%s",
sourceSessionID, forkPoint.ID, newSession.ID, len(copied), reason != "", reason)
return &ForkResult{
SessionID: newSession.ID,
Degraded: reason != "",
Reason: reason,
}, nil
}
// prepareBootstrap runs the decision chain from the design doc §4.2 and, when
// every condition holds, takes the snapshot.
//
// A nil bootstrap with an empty reason means "no sandbox state was needed":
// forking at the very first user message has no prior output to carry, so a
// brand new sandbox is the correct result rather than a degradation.
func (s *SessionForkService) prepareBootstrap(
ctx context.Context, source *types.Session, history []*types.Message,
) (*types.ForkBootstrap, ForkDegradeReason, bool, error) {
checkpoint := latestCheckpoint(history)
if checkpoint == nil {
if !hasAssistantMessage(history) {
// Forking at the first user message.
return nil, "", false, nil
}
return nil, ForkDegradeNoCheckpoint, false, nil
}
if inherited := inheritUnconsumedForkSnapshot(source, checkpoint); inherited != nil {
if currentID, ok := s.boundSandboxID(ctx, source.ID); !ok || currentID == "" {
logger.Infof(ctx, "[SessionFork] inherit unused snapshot %s from source=%s sha=%s",
inherited.SnapshotID, source.ID, inherited.CommitSHA)
return inherited, "", false, nil
}
}
if s.sandbox == nil {
return nil, ForkDegradeSandboxGone, false, nil
}
currentID, ok := s.sandbox.BoundSandboxID(ctx, source.ID)
if !ok || currentID == "" {
return nil, ForkDegradeSandboxGone, false, nil
}
if currentID != checkpoint.SandboxID {
// The session swapped sandboxes after this checkpoint was written, so
// the SHA does not exist in the current sandbox's repository.
return nil, ForkDegradeSandboxReplaced, false, nil
}
// Re-check immediately before pausing the sandbox. The earlier check in
// Fork is a cheap reject; this closes the window after checkpoint lookup.
busy, turnErr := s.sandbox.HasActiveTurn(ctx, source.ID)
if turnErr != nil {
return nil, "", false, fmt.Errorf("session fork: check source turn state: %w", turnErr)
}
if busy {
return nil, "", false, ErrForkSourceBusy
}
snapshotID, err := s.sandbox.CreateForkSnapshot(
ctx, source.ID, forkSnapshotName(source.ID),
)
if err != nil {
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return nil, "", false, fmt.Errorf("session fork: snapshot source sandbox: %w", err)
}
logger.Warnf(ctx, "[SessionFork] snapshot failed source=%s: %v", source.ID, err)
return nil, ForkDegradeSnapshotUnsupported, false, nil
}
if snapshotID == "" {
logger.Warnf(ctx, "[SessionFork] snapshot failed source=%s: empty snapshot id", source.ID)
return nil, ForkDegradeSnapshotUnsupported, false, nil
}
return &types.ForkBootstrap{
SnapshotID: snapshotID,
CommitSHA: checkpoint.CommitSHA,
SourceSandboxID: checkpoint.SandboxID,
CreatedAt: time.Now().UTC(),
}, "", true, nil
}
func (s *SessionForkService) recordSnapshotLease(
ctx context.Context, source *types.Session, bootstrap *types.ForkBootstrap,
) error {
if s.sessions == nil || source == nil || bootstrap == nil || strings.TrimSpace(bootstrap.SnapshotID) == "" {
return nil
}
lease := &types.ForkSnapshotLease{
SnapshotID: bootstrap.SnapshotID,
TenantID: source.TenantID,
SandboxConfigID: source.SandboxConfigID,
CreatedAt: time.Now().UTC(),
}
if err := s.sessions.CreateForkSnapshotLease(ctx, lease); err != nil {
return fmt.Errorf("session fork: record snapshot lease: %w", err)
}
return nil
}
func (s *SessionForkService) clearSnapshotLease(ctx context.Context, snapshotID string) {
if s.sessions == nil || strings.TrimSpace(snapshotID) == "" {
return
}
if err := s.sessions.DeleteForkSnapshotLease(ctx, snapshotID); err != nil {
logger.Warnf(ctx, "[SessionFork] clear snapshot lease %s failed: %v", snapshotID, err)
}
}
// abandonCreatedSnapshot deletes a snapshot this fork just created. On success
// it also drops the lease. On delete failure the lease stays so the reaper
// can retry — there is no session row to hang the ID on.
func (s *SessionForkService) abandonCreatedSnapshot(ctx context.Context, sourceSessionID, snapshotID string) {
snapshotID = strings.TrimSpace(snapshotID)
if snapshotID == "" || s.sandbox == nil {
return
}
cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
defer cancel()
if err := s.sandbox.DeleteForkSnapshot(cleanupCtx, sourceSessionID, snapshotID); err != nil {
if !sandbox.IsRemoteNotFound(err) {
logger.Warnf(cleanupCtx, "[SessionFork] delete orphan snapshot %s failed; lease kept for reaper: %v",
snapshotID, err)
return
}
}
s.clearSnapshotLease(cleanupCtx, snapshotID)
}
func (s *SessionForkService) boundSandboxID(ctx context.Context, sessionID string) (string, bool) {
if s == nil || s.sandbox == nil {
return "", false
}
return s.sandbox.BoundSandboxID(ctx, sessionID)
}
// inheritUnconsumedForkSnapshot reuses a parent branch's unused snapshot when
// that branch has never provisioned a sandbox. Treating "no binding" as
// SANDBOX_GONE would drop state that still exists on the provider.
func inheritUnconsumedForkSnapshot(source *types.Session, checkpoint *types.SandboxCheckpoint) *types.ForkBootstrap {
if source == nil || source.ForkBootstrap == nil || source.ForkBootstrap.Consumed() || checkpoint == nil {
return nil
}
snapshotID := strings.TrimSpace(source.ForkBootstrap.SnapshotID)
sha := strings.TrimSpace(checkpoint.CommitSHA)
if snapshotID == "" || sha == "" {
return nil
}
parentSandbox := strings.TrimSpace(source.ForkBootstrap.SourceSandboxID)
checkpointSandbox := strings.TrimSpace(checkpoint.SandboxID)
if parentSandbox != "" && checkpointSandbox != "" && parentSandbox != checkpointSandbox {
return nil
}
sourceSandbox := checkpointSandbox
if sourceSandbox == "" {
sourceSandbox = parentSandbox
}
return &types.ForkBootstrap{
SnapshotID: snapshotID,
CommitSHA: sha,
SourceSandboxID: sourceSandbox,
CreatedAt: time.Now().UTC(),
}
}
// latestCheckpoint returns the checkpoint of the last assistant message in
// history, or nil when that message has none.
func latestCheckpoint(history []*types.Message) *types.SandboxCheckpoint {
for i := len(history) - 1; i >= 0; i-- {
if history[i].Role != "assistant" {
continue
}
return history[i].SandboxCheckpoint
}
return nil
}
func hasAssistantMessage(history []*types.Message) bool {
for _, m := range history {
if m.Role == "assistant" {
return true
}
}
return false
}
// historyThroughForkPoint is exclusive of a user fork point (the client
// prefills that question) and inclusive of an assistant fork point (the
// branch continues after that answer).
func historyThroughForkPoint(listed []*types.Message, forkPoint *types.Message) []*types.Message {
if forkPoint == nil || forkPoint.Role != "assistant" {
return listed
}
out := make([]*types.Message, 0, len(listed)+1)
out = append(out, listed...)
return append(out, forkPoint)
}
// copyMessagesInto clones history into the new session.
//
// Every copy gets a fresh primary key but keeps its original CreatedAt so the
// branch reads with the same timeline as its parent. RequestIDs are remapped
// per original value so a user/assistant pair stays paired inside the fork
// without colliding with the parent in search partner lookups.
//
// Copies deliberately keep their Artifacts and Attachments. Artifact URLs are
// persisted on the message row, so the forked session's 产物 tab can list and
// download the same files. Attachment storage handles live in
// temporary_documents (still scoped to the parent session) and are resolved
// by ID at preview and staging time when the copied messages reference them.
func copyMessagesInto(newSessionID string, history []*types.Message) []*types.Message {
copies := make([]*types.Message, 0, len(history))
requestIDs := make(map[string]string, len(history))
for _, src := range history {
clone := *src
clone.ID = uuid.New().String()
clone.SessionID = newSessionID
// The parent already indexed these into the chat-history knowledge
// base. Clearing the link stops the copy from being re-indexed, which
// would both duplicate retrieval hits and burn embedding quota.
clone.KnowledgeID = ""
if src.RequestID != "" {
mapped, ok := requestIDs[src.RequestID]
if !ok {
mapped = uuid.New().String()
requestIDs[src.RequestID] = mapped
}
clone.RequestID = mapped
}
copies = append(copies, &clone)
}
return copies
}
func forkTitle(requested, sourceTitle string) string {
if requested != "" {
return requested
}
return sourceTitle + "(分支)"
}
func forkSnapshotName(sourceSessionID string) string {
return fmt.Sprintf("fork-%s-%d", sourceSessionID, time.Now().UnixMilli())
}

View File

@ -0,0 +1,106 @@
package service
import (
"context"
"testing"
"time"
"github.com/Tencent/WeKnora/internal/application/repository"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/stretchr/testify/require"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
type deleteForkMessageRepo struct {
interfaces.MessageRepository
}
func (deleteForkMessageRepo) GetKnowledgeIDsBySessionID(context.Context, string) ([]string, error) {
return nil, nil
}
type deleteForkWebSearchState struct {
interfaces.WebSearchStateService
}
func (deleteForkWebSearchState) DeleteWebSearchTempKBState(context.Context, string) error {
return nil
}
func newSessionServiceForForkDeleteTest(t *testing.T) (*sessionService, *gorm.DB, *fakeForkSessionSnapshotDeleter) {
t.Helper()
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
require.NoError(t, err)
require.NoError(t, db.AutoMigrate(&types.Session{}, &types.ForkSnapshotLease{}))
snapshots := &fakeForkSessionSnapshotDeleter{}
svc := &sessionService{
sessionRepo: repository.NewSessionRepository(db),
messageRepo: deleteForkMessageRepo{},
webSearchStateRepo: deleteForkWebSearchState{},
forkSnapshots: snapshots,
}
return svc, db, snapshots
}
func TestDeleteSessionReleasesUnopenedForkSnapshot(t *testing.T) {
svc, db, snapshots := newSessionServiceForForkDeleteTest(t)
ctx := testSessionScopeContext(1, "u1")
row := &types.Session{
ID: "fork-1", TenantID: 1, UserID: "u1", Title: "branch", SandboxConfigID: "cfg-1",
ForkBootstrap: &types.ForkBootstrap{
SnapshotID: "snap-1", CommitSHA: "sha", SourceSandboxID: "sbx",
CreatedAt: time.Now().UTC(),
},
}
require.NoError(t, db.Session(&gorm.Session{SkipHooks: true}).Create(row).Error)
require.NoError(t, svc.DeleteSession(ctx, "fork-1"))
require.Equal(t, []string{"snap-1"}, snapshots.forkDeleted)
var n int64
require.NoError(t, db.Model(&types.Session{}).Count(&n).Error)
require.Zero(t, n)
}
func TestDeleteSessionKeepsSnapshotStillNeededBySibling(t *testing.T) {
svc, db, snapshots := newSessionServiceForForkDeleteTest(t)
ctx := testSessionScopeContext(1, "u1")
bootstrap := &types.ForkBootstrap{
SnapshotID: "snap-shared", CommitSHA: "sha", SourceSandboxID: "sbx",
CreatedAt: time.Now().UTC(),
}
require.NoError(t, db.Session(&gorm.Session{SkipHooks: true}).Create(&types.Session{
ID: "fork-1", TenantID: 1, UserID: "u1", Title: "branch",
ForkBootstrap: bootstrap,
}).Error)
require.NoError(t, db.Session(&gorm.Session{SkipHooks: true}).Create(&types.Session{
ID: "fork-2", TenantID: 1, UserID: "u1", Title: "sibling",
ForkBootstrap: bootstrap,
}).Error)
require.NoError(t, svc.DeleteSession(ctx, "fork-1"))
require.Empty(t, snapshots.forkDeleted)
}
func TestBatchDeleteSessionsReleasesUnopenedForkSnapshotsAfterAllRowsAreGone(t *testing.T) {
svc, db, snapshots := newSessionServiceForForkDeleteTest(t)
ctx := testSessionScopeContext(1, "u1")
bootstrap := &types.ForkBootstrap{
SnapshotID: "snap-shared", CommitSHA: "sha", SourceSandboxID: "sbx",
CreatedAt: time.Now().UTC(),
}
require.NoError(t, db.Session(&gorm.Session{SkipHooks: true}).Create(&types.Session{
ID: "fork-1", TenantID: 1, UserID: "u1", Title: "a", ForkBootstrap: bootstrap,
}).Error)
require.NoError(t, db.Session(&gorm.Session{SkipHooks: true}).Create(&types.Session{
ID: "fork-2", TenantID: 1, UserID: "u1", Title: "b", ForkBootstrap: bootstrap,
}).Error)
require.NoError(t, svc.BatchDeleteSessions(ctx, []string{"fork-1", "fork-2"}))
require.Equal(t, []string{"snap-shared"}, snapshots.forkDeleted,
"shared snapshot must be deleted once, after both rows are gone")
}

View File

@ -0,0 +1,897 @@
package service
import (
"context"
"errors"
"sort"
"strings"
"testing"
"time"
"github.com/Tencent/WeKnora/internal/types"
"github.com/stretchr/testify/require"
)
type fakeForkSandboxPort struct {
boundID string
bound bool
activeTurn bool
activeTurnErr error
forceBusyAfter int
hasActiveCalls int
snapshotID string
snapshotErr error
snapshotCalls int
snapshotNameIn string
cancelParent context.CancelFunc
snapshotCtxErr error
deleted []string
deleteErr error
}
func (f *fakeForkSandboxPort) BoundSandboxID(context.Context, string) (string, bool) {
return f.boundID, f.bound
}
func (f *fakeForkSandboxPort) HasActiveTurn(context.Context, string) (bool, error) {
f.hasActiveCalls++
if f.activeTurnErr != nil {
return false, f.activeTurnErr
}
if f.forceBusyAfter > 0 && f.hasActiveCalls >= f.forceBusyAfter {
return true, nil
}
return f.activeTurn, nil
}
func (f *fakeForkSandboxPort) CreateForkSnapshot(ctx context.Context, _, name string) (string, error) {
f.snapshotCalls++
f.snapshotNameIn = name
if f.cancelParent != nil {
f.cancelParent()
}
f.snapshotCtxErr = ctx.Err()
if f.snapshotErr != nil {
return "", f.snapshotErr
}
if err := ctx.Err(); err != nil {
return "", err
}
return f.snapshotID, nil
}
func (f *fakeForkSandboxPort) DeleteForkSnapshot(_ context.Context, _, snapshotID string) error {
f.deleted = append(f.deleted, snapshotID)
return f.deleteErr
}
// 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
unconsumed []*types.Session
createErr error
leases []*types.ForkSnapshotLease
}
func newFakeSessionStore(src *types.Session) *fakeSessionStore {
return &fakeSessionStore{source: src}
}
func (f *fakeSessionStore) GetByID(_ context.Context, tenantID uint64, id string) (*types.Session, error) {
if f.getErr != nil {
return nil, f.getErr
}
if f.source == nil || f.source.ID != id || f.source.TenantID != tenantID {
return nil, nil
}
return f.source, nil
}
func (f *fakeSessionStore) UpdateForkBootstrap(_ context.Context, _ string, b *types.ForkBootstrap) error {
if b == nil {
if f.clearErr != nil {
return f.clearErr
}
f.bootstrapCleared = true
f.updatedBootstrap = nil
if f.source != nil {
f.source.ForkBootstrap = nil
}
return nil
}
copied := *b
f.updatedBootstrap = &copied
if f.source != nil {
f.source.ForkBootstrap = &copied
}
return nil
}
func (f *fakeSessionStore) ListUnconsumedForks(_ context.Context, _ time.Time) ([]*types.Session, error) {
return f.unconsumed, nil
}
func (f *fakeSessionStore) UnconsumedForkSnapshotHolders(_ context.Context, snapshotID string) ([]string, error) {
snapshotID = strings.TrimSpace(snapshotID)
if snapshotID == "" {
return nil, nil
}
seen := map[string]struct{}{}
var ids []string
candidates := []*types.Session{f.source, f.created}
candidates = append(candidates, f.unconsumed...)
for _, s := range candidates {
if s == nil || s.ForkBootstrap == nil || s.ForkBootstrap.Consumed() {
continue
}
if s.ForkBootstrap.SnapshotID != snapshotID {
continue
}
if _, ok := seen[s.ID]; ok {
continue
}
seen[s.ID] = struct{}{}
ids = append(ids, s.ID)
}
return ids, nil
}
func (f *fakeSessionStore) HasOtherUnconsumedForkSnapshot(
ctx context.Context, snapshotID, excludeSessionID string,
) (bool, error) {
holders, err := f.UnconsumedForkSnapshotHolders(ctx, snapshotID)
if err != nil {
return false, err
}
for _, id := range holders {
if id != excludeSessionID {
return true, nil
}
}
return false, nil
}
func (f *fakeSessionStore) CreateForkSnapshotLease(_ context.Context, lease *types.ForkSnapshotLease) error {
if lease == nil {
return nil
}
copied := *lease
f.leases = append(f.leases, &copied)
return nil
}
func (f *fakeSessionStore) DeleteForkSnapshotLease(_ context.Context, snapshotID string) error {
out := f.leases[:0]
for _, lease := range f.leases {
if lease != nil && lease.SnapshotID != snapshotID {
out = append(out, lease)
}
}
f.leases = out
return nil
}
func (f *fakeSessionStore) ListStaleForkSnapshotLeases(
_ context.Context, olderThan time.Time,
) ([]*types.ForkSnapshotLease, error) {
var out []*types.ForkSnapshotLease
for _, lease := range f.leases {
if lease == nil || lease.CreatedAt.After(olderThan) {
continue
}
out = append(out, lease)
}
return out, nil
}
func (f *fakeSessionStore) CreateForked(ctx context.Context, session *types.Session, messages []*types.Message) error {
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...)
// Copies already have fresh IDs; original IDs come from the listing the
// service used as the copy source.
if f.origIDsFrom != nil {
f.copiedOrigIDs = append([]string(nil), f.origIDsFrom.lastListedIDs...)
}
return nil
}
func (f *fakeSessionStore) copiedFromIDs() []string {
return f.copiedOrigIDs
}
// fakeMessageStore is the narrow message port SessionForkService needs.
type fakeMessageStore struct {
messages []*types.Message
lastListedIDs []string
rewriteErr error
}
func newFakeMessageStore(messages []*types.Message) *fakeMessageStore {
return &fakeMessageStore{messages: messages}
}
func (f *fakeMessageStore) GetMessage(_ context.Context, sessionID, messageID string) (*types.Message, error) {
for _, m := range f.messages {
if m != nil && m.SessionID == sessionID && m.ID == messageID {
return m, nil
}
}
return nil, nil
}
func (f *fakeMessageStore) GetMessagesBySession(
_ context.Context, sessionID string, page, pageSize int,
) ([]*types.Message, error) {
var out []*types.Message
for _, m := range f.messages {
if m != nil && m.SessionID == sessionID {
out = append(out, m)
}
}
sort.Slice(out, func(i, j int) bool {
if !out[i].CreatedAt.Equal(out[j].CreatedAt) {
return out[i].CreatedAt.Before(out[j].CreatedAt)
}
return out[i].ID < out[j].ID
})
if page < 1 {
page = 1
}
if pageSize <= 0 {
return out, nil
}
start := (page - 1) * pageSize
if start >= len(out) {
return []*types.Message{}, nil
}
end := start + pageSize
if end > len(out) {
end = len(out)
}
return out[start:end], nil
}
func (f *fakeMessageStore) ListMessagesBySessionUpTo(
_ context.Context, sessionID string, boundary time.Time, boundaryID string,
) ([]*types.Message, error) {
var out []*types.Message
for _, m := range f.messages {
if m == nil || m.SessionID != sessionID {
continue
}
if m.CreatedAt.Before(boundary) || (m.CreatedAt.Equal(boundary) && m.ID < boundaryID) {
out = append(out, m)
}
}
sort.Slice(out, func(i, j int) bool {
if !out[i].CreatedAt.Equal(out[j].CreatedAt) {
return out[i].CreatedAt.Before(out[j].CreatedAt)
}
return out[i].ID < out[j].ID
})
f.lastListedIDs = make([]string, 0, len(out))
for _, m := range out {
f.lastListedIDs = append(f.lastListedIDs, m.ID)
}
return out, nil
}
func (f *fakeMessageStore) GetSessionArtifacts(ctx context.Context, sessionID string) (types.MessageArtifacts, error) {
messages, err := f.GetMessagesBySession(ctx, sessionID, 1, 0)
if err != nil {
return nil, err
}
var out types.MessageArtifacts
for _, m := range messages {
if m == nil || len(m.Artifacts) == 0 {
continue
}
out = append(out, m.Artifacts...)
}
if out == nil {
out = types.MessageArtifacts{}
}
return out, nil
}
func (f *fakeMessageStore) RewriteSandboxCheckpoints(_ context.Context, sessionID, oldID, newID string) error {
if f.rewriteErr != nil {
return f.rewriteErr
}
if sessionID == "" || oldID == "" || newID == "" || oldID == newID {
return nil
}
for _, m := range f.messages {
if m == nil || m.SessionID != sessionID || m.SandboxCheckpoint == nil {
continue
}
if m.SandboxCheckpoint.SandboxID != oldID {
continue
}
cp := *m.SandboxCheckpoint
cp.SandboxID = newID
m.SandboxCheckpoint = &cp
}
return nil
}
var (
_ forkSessionStore = (*fakeSessionStore)(nil)
_ forkBootstrapSessionStore = (*fakeSessionStore)(nil)
_ reaperSessionStore = (*fakeSessionStore)(nil)
_ forkMessageStore = (*fakeMessageStore)(nil)
_ forkBootstrapMessageStore = (*fakeMessageStore)(nil)
_ SessionForkSandboxPort = (*fakeForkSandboxPort)(nil)
)
// --- fixture helpers -------------------------------------------------------
var forkBase = time.Date(2026, 9, 10, 9, 0, 0, 0, time.UTC)
func checkpointedTurn(userID, assistantID, sandboxID, sha string, offset time.Duration) []*types.Message {
return []*types.Message{
{ID: userID, SessionID: "src", Role: "user", CreatedAt: forkBase.Add(offset)},
{
ID: assistantID, SessionID: "src", Role: "assistant",
CreatedAt: forkBase.Add(offset + time.Second),
SandboxCheckpoint: &types.SandboxCheckpoint{
SandboxID: sandboxID, CommitSHA: sha, CommittedAt: forkBase.Add(offset + time.Second),
},
},
}
}
func newForkFixture(t *testing.T, port *fakeForkSandboxPort, messages []*types.Message) (
*SessionForkService, *fakeSessionStore, *fakeMessageStore,
) {
t.Helper()
sessions := newFakeSessionStore(&types.Session{
ID: "src", TenantID: 1, UserID: "u1", Title: "原会话", SandboxConfigID: "cfg-1",
})
msgs := newFakeMessageStore(messages)
sessions.origIDsFrom = msgs
return NewSessionForkService(sessions, msgs, port), sessions, msgs
}
// --- tests -----------------------------------------------------------------
func TestForkHappyPathTakesSnapshotAndCopiesHistory(t *testing.T) {
turn := checkpointedTurn("u-msg-1", "a-msg-1", "sbx-1", "sha1", 0)
forkPoint := &types.Message{
ID: "u-msg-2", SessionID: "src", Role: "user", CreatedAt: forkBase.Add(10 * time.Second),
}
port := &fakeForkSandboxPort{boundID: "sbx-1", bound: true, snapshotID: "snap-1"}
svc, sessions, _ := newForkFixture(t, port, append(turn, forkPoint))
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.Equal(t, 1, port.snapshotCalls)
created := sessions.created
require.NotNil(t, created)
require.Equal(t, "src", created.ParentSessionID)
require.Equal(t, "u-msg-2", created.ForkedFromMessageID)
require.Equal(t, "cfg-1", created.SandboxConfigID, "必须继承 sandbox_config_id,否则可能落到别的 backend")
require.Equal(t, "原会话(分支)", created.Title)
require.NotNil(t, created.ForkBootstrap)
require.Equal(t, "snap-1", created.ForkBootstrap.SnapshotID)
require.Equal(t, "sha1", created.ForkBootstrap.CommitSHA)
require.Equal(t, "sbx-1", created.ForkBootstrap.SourceSandboxID)
require.False(t, created.ForkBootstrap.Consumed())
// 只复制分叉点之前的消息,且都换了新 ID
require.Equal(t, []string{"u-msg-1", "a-msg-1"}, sessions.copiedFromIDs())
for _, m := range sessions.copiedMessages {
require.NotEmpty(t, m.ID)
require.Equal(t, created.ID, m.SessionID)
}
}
func TestCopyMessagesIntoRemapsRequestIDsPerTurn(t *testing.T) {
history := []*types.Message{
{ID: "u1", SessionID: "src", Role: "user", RequestID: "req-a", Content: "q1"},
{ID: "a1", SessionID: "src", Role: "assistant", RequestID: "req-a", Content: "a1"},
{ID: "u2", SessionID: "src", Role: "user", RequestID: "req-b", Content: "q2"},
{ID: "a2", SessionID: "src", Role: "assistant", RequestID: "req-b", Content: "a2"},
{ID: "u3", SessionID: "src", Role: "user", Content: "no-request-id"},
}
copies := copyMessagesInto("fork-1", history)
require.Len(t, copies, 5)
require.NotEqual(t, "req-a", copies[0].RequestID)
require.Equal(t, copies[0].RequestID, copies[1].RequestID, "same turn must still pair")
require.NotEqual(t, copies[0].RequestID, copies[2].RequestID, "distinct turns must not share an ID")
require.Equal(t, copies[2].RequestID, copies[3].RequestID)
require.Empty(t, copies[4].RequestID)
require.Equal(t, "fork-1", copies[0].SessionID)
require.NotEqual(t, "u1", copies[0].ID)
}
func TestForkCopiesArtifactsAndAttachmentsOntoNewSession(t *testing.T) {
turn := checkpointedTurn("u-msg-1", "a-msg-1", "sbx-1", "sha1", 0)
turn[0].Attachments = types.MessageAttachments{{
ID: "doc-1", FileName: "brief.pdf", FileType: ".pdf", FileSize: 12,
}}
turn[1].Artifacts = types.MessageArtifacts{{
URL: "local://tenant/deck",
FileName: "deck.pptx",
FileType: ".pptx",
FileSize: 32,
SourcePath: "/workspace/output/deck.pptx",
}}
forkPoint := &types.Message{
ID: "u-msg-2", SessionID: "src", Role: "user", CreatedAt: forkBase.Add(10 * time.Second),
}
port := &fakeForkSandboxPort{boundID: "sbx-1", bound: true, snapshotID: "snap-1"}
svc, sessions, _ := newForkFixture(t, port, append(turn, forkPoint))
_, err := svc.Fork(context.Background(), 1, "u1", "src", "u-msg-2", "")
require.NoError(t, err)
var copiedUser, copiedAssistant *types.Message
for _, m := range sessions.copiedMessages {
switch m.Role {
case "user":
copiedUser = m
case "assistant":
copiedAssistant = m
}
}
require.NotNil(t, copiedUser)
require.Equal(t, turn[0].Attachments, copiedUser.Attachments)
require.NotNil(t, copiedAssistant)
require.Equal(t, turn[1].Artifacts, copiedAssistant.Artifacts)
}
func TestForkUsesProvidedTitle(t *testing.T) {
turn := checkpointedTurn("u-msg-1", "a-msg-1", "sbx-1", "sha1", 0)
forkPoint := &types.Message{
ID: "u-msg-2", SessionID: "src", Role: "user", CreatedAt: forkBase.Add(10 * time.Second),
}
port := &fakeForkSandboxPort{boundID: "sbx-1", bound: true, snapshotID: "snap-1"}
svc, sessions, _ := newForkFixture(t, port, append(turn, forkPoint))
_, err := svc.Fork(context.Background(), 1, "u1", "src", "u-msg-2", "我的分支")
require.NoError(t, err)
require.Equal(t, "我的分支", sessions.created.Title)
}
// 分叉点是第一条 user 消息:前面本就无产物,全新沙箱才是正确结果,不算降级。
func TestForkAtFirstUserMessageIsNotDegraded(t *testing.T) {
first := &types.Message{ID: "u-msg-1", SessionID: "src", Role: "user", CreatedAt: forkBase}
port := &fakeForkSandboxPort{boundID: "sbx-1", bound: true, snapshotID: "snap-1"}
svc, sessions, _ := newForkFixture(t, port, []*types.Message{first})
got, err := svc.Fork(context.Background(), 1, "u1", "src", "u-msg-1", "")
require.NoError(t, err)
require.False(t, got.Degraded)
require.Empty(t, got.Reason)
require.Zero(t, port.snapshotCalls, "没有前置产物就不该浪费一个快照")
require.Nil(t, sessions.created.ForkBootstrap)
require.Empty(t, sessions.copiedFromIDs())
}
func TestForkDegradesWhenPrecedingTurnHasNoCheckpoint(t *testing.T) {
messages := []*types.Message{
{ID: "u-msg-1", SessionID: "src", Role: "user", CreatedAt: forkBase},
{ID: "a-msg-1", SessionID: "src", Role: "assistant", CreatedAt: forkBase.Add(time.Second)},
{ID: "u-msg-2", SessionID: "src", Role: "user", CreatedAt: forkBase.Add(10 * time.Second)},
}
port := &fakeForkSandboxPort{boundID: "sbx-1", bound: true, snapshotID: "snap-1"}
svc, sessions, _ := newForkFixture(t, port, messages)
got, err := svc.Fork(context.Background(), 1, "u1", "src", "u-msg-2", "")
require.NoError(t, err)
require.True(t, got.Degraded)
require.Equal(t, ForkDegradeNoCheckpoint, got.Reason)
require.Zero(t, port.snapshotCalls)
require.Nil(t, sessions.created.ForkBootstrap)
require.Equal(t, []string{"u-msg-1", "a-msg-1"}, sessions.copiedFromIDs(), "降级也要复制消息")
}
// 会话中途换过沙箱:旧 sha 在新沙箱的仓库里根本不存在。
func TestForkDegradesWhenSandboxWasReplaced(t *testing.T) {
turn := checkpointedTurn("u-msg-1", "a-msg-1", "sbx-OLD", "sha1", 0)
forkPoint := &types.Message{
ID: "u-msg-2", SessionID: "src", Role: "user", CreatedAt: forkBase.Add(10 * time.Second),
}
port := &fakeForkSandboxPort{boundID: "sbx-NEW", bound: true, snapshotID: "snap-1"}
svc, _, _ := newForkFixture(t, port, append(turn, forkPoint))
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.snapshotCalls)
}
func TestForkDegradesWhenSandboxGone(t *testing.T) {
turn := checkpointedTurn("u-msg-1", "a-msg-1", "sbx-1", "sha1", 0)
forkPoint := &types.Message{
ID: "u-msg-2", SessionID: "src", Role: "user", CreatedAt: forkBase.Add(10 * time.Second),
}
port := &fakeForkSandboxPort{bound: false}
svc, _, _ := newForkFixture(t, port, append(turn, forkPoint))
got, err := svc.Fork(context.Background(), 1, "u1", "src", "u-msg-2", "")
require.NoError(t, err)
require.True(t, got.Degraded)
require.Equal(t, ForkDegradeSandboxGone, got.Reason)
}
func TestForkInheritsUnconsumedBootstrapWhenSourceHasNoSandbox(t *testing.T) {
turn := checkpointedTurn("u-msg-1", "a-msg-1", "sbx-1", "sha-early", 0)
forkPoint := &types.Message{
ID: "u-msg-2", SessionID: "src", Role: "user", CreatedAt: forkBase.Add(10 * time.Second),
}
port := &fakeForkSandboxPort{bound: false, snapshotID: "must-not-create"}
svc, sessions, _ := newForkFixture(t, port, append(turn, forkPoint))
sessions.source.ForkBootstrap = &types.ForkBootstrap{
SnapshotID: "snap-shared",
CommitSHA: "sha-later",
SourceSandboxID: "sbx-1",
CreatedAt: forkBase,
}
got, err := svc.Fork(context.Background(), 1, "u1", "src", "u-msg-2", "")
require.NoError(t, err)
require.False(t, got.Degraded)
require.Zero(t, port.snapshotCalls, "unused fork has no live sandbox to snapshot")
require.NotNil(t, sessions.created.ForkBootstrap)
require.Equal(t, "snap-shared", sessions.created.ForkBootstrap.SnapshotID)
require.Equal(t, "sha-early", sessions.created.ForkBootstrap.CommitSHA)
require.Equal(t, "sbx-1", sessions.created.ForkBootstrap.SourceSandboxID)
require.False(t, sessions.created.ForkBootstrap.Consumed())
}
func TestForkDoesNotInheritConsumedBootstrapWhenSandboxGone(t *testing.T) {
turn := checkpointedTurn("u-msg-1", "a-msg-1", "sbx-1", "sha1", 0)
forkPoint := &types.Message{
ID: "u-msg-2", SessionID: "src", Role: "user", CreatedAt: forkBase.Add(10 * time.Second),
}
consumedAt := forkBase.Add(time.Minute)
port := &fakeForkSandboxPort{bound: false}
svc, sessions, _ := newForkFixture(t, port, append(turn, forkPoint))
sessions.source.ForkBootstrap = &types.ForkBootstrap{
SnapshotID: "snap-old",
CommitSHA: "sha1",
SourceSandboxID: "sbx-1",
CreatedAt: forkBase,
ConsumedAt: &consumedAt,
}
got, err := svc.Fork(context.Background(), 1, "u1", "src", "u-msg-2", "")
require.NoError(t, err)
require.True(t, got.Degraded)
require.Equal(t, ForkDegradeSandboxGone, got.Reason)
require.Zero(t, port.snapshotCalls)
}
func TestForkDegradesWhenSnapshotFails(t *testing.T) {
turn := checkpointedTurn("u-msg-1", "a-msg-1", "sbx-1", "sha1", 0)
forkPoint := &types.Message{
ID: "u-msg-2", SessionID: "src", Role: "user", CreatedAt: forkBase.Add(10 * time.Second),
}
port := &fakeForkSandboxPort{
boundID: "sbx-1", bound: true, snapshotErr: errors.New("provider does not support snapshots"),
}
svc, sessions, _ := newForkFixture(t, port, append(turn, forkPoint))
got, err := svc.Fork(context.Background(), 1, "u1", "src", "u-msg-2", "")
require.NoError(t, err, "快照失败是降级,不是报错")
require.True(t, got.Degraded)
require.Equal(t, ForkDegradeSnapshotUnsupported, got.Reason)
require.Nil(t, sessions.created.ForkBootstrap)
}
func TestForkDoesNotDegradeWhenSnapshotIsCanceled(t *testing.T) {
turn := checkpointedTurn("u-msg-1", "a-msg-1", "sbx-1", "sha1", 0)
forkPoint := &types.Message{
ID: "u-msg-2", SessionID: "src", Role: "user", CreatedAt: forkBase.Add(10 * time.Second),
}
port := &fakeForkSandboxPort{
boundID: "sbx-1", bound: true, snapshotErr: context.Canceled,
}
svc, sessions, _ := newForkFixture(t, port, append(turn, forkPoint))
_, err := svc.Fork(context.Background(), 1, "u1", "src", "u-msg-2", "")
require.ErrorIs(t, err, context.Canceled)
require.Nil(t, sessions.created, "canceled snapshot must not persist a degraded fork")
}
func TestForkFinishesSnapshotAfterCallerCancels(t *testing.T) {
turn := checkpointedTurn("u-msg-1", "a-msg-1", "sbx-1", "sha1", 0)
forkPoint := &types.Message{
ID: "u-msg-2", SessionID: "src", Role: "user", CreatedAt: forkBase.Add(10 * time.Second),
}
ctx, cancel := context.WithCancel(context.Background())
port := &fakeForkSandboxPort{
boundID: "sbx-1", bound: true, snapshotID: "snap-1", cancelParent: cancel,
}
svc, sessions, _ := newForkFixture(t, port, append(turn, forkPoint))
got, err := svc.Fork(ctx, 1, "u1", "src", "u-msg-2", "")
require.NoError(t, err)
require.NoError(t, port.snapshotCtxErr, "snapshot must not inherit the canceled HTTP request")
require.False(t, got.Degraded)
require.Equal(t, "snap-1", sessions.created.ForkBootstrap.SnapshotID)
}
// 源沙箱正在跑 agent 时打快照会暂停它、打断执行中的工具。
func TestForkRefusesWhileSourceTurnIsActive(t *testing.T) {
turn := checkpointedTurn("u-msg-1", "a-msg-1", "sbx-1", "sha1", 0)
forkPoint := &types.Message{
ID: "u-msg-2", SessionID: "src", Role: "user", CreatedAt: forkBase.Add(10 * time.Second),
}
port := &fakeForkSandboxPort{boundID: "sbx-1", bound: true, activeTurn: true, snapshotID: "snap-1"}
svc, sessions, _ := newForkFixture(t, port, append(turn, forkPoint))
_, err := svc.Fork(context.Background(), 1, "u1", "src", "u-msg-2", "")
require.ErrorIs(t, err, ErrForkSourceBusy)
require.Zero(t, port.snapshotCalls)
require.Nil(t, sessions.created, "拒绝时不得留下半个会话")
}
func TestForkAtAssistantCopiesTurnAndUsesItsCheckpoint(t *testing.T) {
turn := checkpointedTurn("u-msg-1", "a-msg-1", "sbx-1", "sha1", 0)
turn[1].IsCompleted = true
later := &types.Message{
ID: "u-msg-2", SessionID: "src", Role: "user", CreatedAt: forkBase.Add(10 * time.Second),
}
port := &fakeForkSandboxPort{boundID: "sbx-1", bound: true, snapshotID: "snap-1"}
svc, sessions, _ := newForkFixture(t, port, append(turn, later))
got, err := svc.Fork(context.Background(), 1, "u1", "src", "a-msg-1", "")
require.NoError(t, err)
require.False(t, got.Degraded)
require.Equal(t, 1, port.snapshotCalls)
require.Equal(t, "a-msg-1", sessions.created.ForkedFromMessageID)
require.Len(t, sessions.copiedMessages, 2, "assistant fork must include the clicked answer, not stop before it")
require.Equal(t, "user", sessions.copiedMessages[0].Role)
require.Equal(t, "assistant", sessions.copiedMessages[1].Role)
require.Equal(t, "sha1", sessions.copiedMessages[1].SandboxCheckpoint.CommitSHA)
require.Equal(t, "sbx-1", sessions.created.ForkBootstrap.SourceSandboxID)
}
func TestForkAtAssistantUsesThisTurnsCheckpointNotAnEarlierOne(t *testing.T) {
first := checkpointedTurn("u-msg-1", "a-msg-1", "sbx-1", "sha-old", 0)
first[1].IsCompleted = true
second := checkpointedTurn("u-msg-2", "a-msg-2", "sbx-1", "sha-new", 10*time.Second)
second[1].IsCompleted = true
port := &fakeForkSandboxPort{boundID: "sbx-1", bound: true, snapshotID: "snap-2"}
svc, sessions, _ := newForkFixture(t, port, append(first, second...))
_, err := svc.Fork(context.Background(), 1, "u1", "src", "a-msg-2", "")
require.NoError(t, err)
require.Len(t, sessions.copiedMessages, 4)
require.Equal(t, "assistant", sessions.copiedMessages[3].Role)
require.Equal(t, "sha-new", sessions.copiedMessages[3].SandboxCheckpoint.CommitSHA)
}
func TestForkAtAssistantWithoutCheckpointDegrades(t *testing.T) {
turn := []*types.Message{
{ID: "u-msg-1", SessionID: "src", Role: "user", CreatedAt: forkBase},
{ID: "a-msg-1", SessionID: "src", Role: "assistant", CreatedAt: forkBase.Add(time.Second), IsCompleted: true},
}
port := &fakeForkSandboxPort{boundID: "sbx-1", bound: true, snapshotID: "snap-1"}
svc, sessions, _ := newForkFixture(t, port, turn)
got, err := svc.Fork(context.Background(), 1, "u1", "src", "a-msg-1", "")
require.NoError(t, err)
require.True(t, got.Degraded)
require.Equal(t, ForkDegradeNoCheckpoint, got.Reason)
require.Zero(t, port.snapshotCalls)
require.Len(t, sessions.copiedMessages, 2)
require.Equal(t, "assistant", sessions.copiedMessages[1].Role)
require.Nil(t, sessions.created.ForkBootstrap)
}
func TestForkRejectsIncompleteAssistantAsForkPoint(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, turn)
_, err := svc.Fork(context.Background(), 1, "u1", "src", "a-msg-1", "")
require.ErrorIs(t, err, ErrForkSourceBusy)
require.Zero(t, port.snapshotCalls)
require.Nil(t, sessions.created)
}
func TestForkRejectsNonUserNonAssistantForkPoint(t *testing.T) {
turn := checkpointedTurn("u-msg-1", "a-msg-1", "sbx-1", "sha1", 0)
turn = append(turn, &types.Message{
ID: "sys-1", SessionID: "src", Role: "system", CreatedAt: forkBase.Add(2 * time.Second),
})
port := &fakeForkSandboxPort{boundID: "sbx-1", bound: true, snapshotID: "snap-1"}
svc, _, _ := newForkFixture(t, port, turn)
_, err := svc.Fork(context.Background(), 1, "u1", "src", "sys-1", "")
require.ErrorIs(t, err, ErrForkMessageNotUser)
require.Zero(t, port.snapshotCalls)
}
func TestForkRejectsForeignSession(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, _, _ := newForkFixture(t, port, turn)
_, err := svc.Fork(context.Background(), 1, "someone-else", "src", "u-msg-1", "")
require.ErrorIs(t, err, ErrForkSessionNotFound)
require.Zero(t, port.snapshotCalls)
}
func TestForkRejectsEmptyOwnerSession(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, turn)
sessions.source.UserID = ""
_, err := svc.Fork(context.Background(), 1, "u1", "src", "u-msg-1", "")
require.ErrorIs(t, err, ErrForkSessionNotFound)
require.Zero(t, port.snapshotCalls)
require.Nil(t, sessions.created)
}
func TestForkRejectsEmptyCaller(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, turn)
sessions.source.UserID = ""
_, err := svc.Fork(context.Background(), 1, "", "src", "u-msg-1", "")
require.ErrorIs(t, err, ErrForkSessionNotFound)
require.Zero(t, port.snapshotCalls)
require.Nil(t, sessions.created)
}
func TestForkRejectsMissingSession(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, _, _ := newForkFixture(t, port, turn)
_, err := svc.Fork(context.Background(), 1, "u1", "missing", "u-msg-1", "")
require.ErrorIs(t, err, ErrForkSessionNotFound)
}
func TestForkRejectsMissingMessage(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, _, _ := newForkFixture(t, port, turn)
_, err := svc.Fork(context.Background(), 1, "u1", "src", "no-such-msg", "")
require.ErrorIs(t, err, ErrForkMessageNotFound)
}
func TestForkRefusesWhenSourceBecomesBusyBeforeSnapshot(t *testing.T) {
turn := checkpointedTurn("u-msg-1", "a-msg-1", "sbx-1", "sha1", 0)
forkPoint := &types.Message{
ID: "u-msg-2", SessionID: "src", Role: "user", CreatedAt: forkBase.Add(10 * time.Second),
}
port := &fakeForkSandboxPort{
boundID: "sbx-1", bound: true, snapshotID: "snap-1", forceBusyAfter: 2,
}
svc, sessions, _ := newForkFixture(t, port, append(turn, forkPoint))
_, err := svc.Fork(context.Background(), 1, "u1", "src", "u-msg-2", "")
require.ErrorIs(t, err, ErrForkSourceBusy)
require.GreaterOrEqual(t, port.hasActiveCalls, 2)
require.Zero(t, port.snapshotCalls)
require.Nil(t, sessions.created)
}
func TestForkDeletesCreatedSnapshotWhenPersistFails(t *testing.T) {
turn := checkpointedTurn("u-msg-1", "a-msg-1", "sbx-1", "sha1", 0)
forkPoint := &types.Message{
ID: "u-msg-2", SessionID: "src", Role: "user", CreatedAt: forkBase.Add(10 * time.Second),
}
port := &fakeForkSandboxPort{boundID: "sbx-1", bound: true, snapshotID: "snap-1"}
svc, sessions, _ := newForkFixture(t, port, append(turn, forkPoint))
sessions.createErr = errors.New("db down")
_, err := svc.Fork(context.Background(), 1, "u1", "src", "u-msg-2", "")
require.Error(t, err)
require.Nil(t, sessions.created)
require.Equal(t, 1, port.snapshotCalls)
require.Equal(t, []string{"snap-1"}, port.deleted)
require.Empty(t, sessions.leases, "deleted snapshot must not leave a lease behind")
}
func TestForkKeepsLeaseWhenPersistAndDeleteBothFail(t *testing.T) {
turn := checkpointedTurn("u-msg-1", "a-msg-1", "sbx-1", "sha1", 0)
forkPoint := &types.Message{
ID: "u-msg-2", SessionID: "src", Role: "user", CreatedAt: forkBase.Add(10 * time.Second),
}
port := &fakeForkSandboxPort{
boundID: "sbx-1", bound: true, snapshotID: "snap-1", deleteErr: errors.New("provider timeout"),
}
svc, sessions, _ := newForkFixture(t, port, append(turn, forkPoint))
sessions.createErr = errors.New("db down")
_, err := svc.Fork(context.Background(), 1, "u1", "src", "u-msg-2", "")
require.Error(t, err)
require.Equal(t, []string{"snap-1"}, port.deleted)
require.Len(t, sessions.leases, 1)
require.Equal(t, "snap-1", sessions.leases[0].SnapshotID)
require.Equal(t, uint64(1), sessions.leases[0].TenantID)
require.Equal(t, "cfg-1", sessions.leases[0].SandboxConfigID)
}
func TestForkDoesNotDeleteInheritedSnapshotWhenPersistFails(t *testing.T) {
turn := checkpointedTurn("u-msg-1", "a-msg-1", "sbx-1", "sha-early", 0)
forkPoint := &types.Message{
ID: "u-msg-2", SessionID: "src", Role: "user", CreatedAt: forkBase.Add(10 * time.Second),
}
port := &fakeForkSandboxPort{bound: false, snapshotID: "must-not-create"}
svc, sessions, _ := newForkFixture(t, port, append(turn, forkPoint))
sessions.source.ForkBootstrap = &types.ForkBootstrap{
SnapshotID: "snap-shared",
CommitSHA: "sha-later",
SourceSandboxID: "sbx-1",
CreatedAt: forkBase,
}
sessions.createErr = errors.New("db down")
_, err := svc.Fork(context.Background(), 1, "u1", "src", "u-msg-2", "")
require.Error(t, err)
require.Zero(t, port.snapshotCalls)
require.Empty(t, port.deleted, "parent still needs the inherited snapshot")
require.Empty(t, sessions.leases)
}
func TestForkClearsLeaseAfterPersistSucceeds(t *testing.T) {
turn := checkpointedTurn("u-msg-1", "a-msg-1", "sbx-1", "sha1", 0)
forkPoint := &types.Message{
ID: "u-msg-2", SessionID: "src", Role: "user", CreatedAt: forkBase.Add(10 * time.Second),
}
port := &fakeForkSandboxPort{boundID: "sbx-1", bound: true, snapshotID: "snap-1"}
svc, sessions, _ := newForkFixture(t, port, append(turn, forkPoint))
_, err := svc.Fork(context.Background(), 1, "u1", "src", "u-msg-2", "")
require.NoError(t, err)
require.Empty(t, port.deleted)
require.Empty(t, sessions.leases, "session.fork_bootstrap now owns the snapshot")
}

View File

@ -93,15 +93,24 @@ var temporaryTextExtensions = map[string]struct{}{
".md": {}, ".markdown": {}, ".txt": {}, ".csv": {}, ".json": {}, ".xml": {}, ".yaml": {}, ".yml": {}, ".log": {},
}
// sessionAttachmentLookup is the message-store surface Get/OpenFile need to
// authorize a parent-session temporary document after a fork. Fork copies
// attachment IDs onto the new messages but leaves the temporary_documents
// row on the parent; preview still has to work from the fork session id.
type sessionAttachmentLookup interface {
GetSessionAttachments(ctx context.Context, sessionID string) (types.MessageAttachments, error)
}
type temporaryDocumentService struct {
repo interfaces.TemporaryDocumentRepository
fileService interfaces.FileService
resourceCatalog interfaces.ResourceCatalog
documentReader interfaces.DocumentReader
imageResolver *docparser.ImageResolver
modelService interfaces.ModelService
tenantService interfaces.TenantService
taskEnqueuer interfaces.TaskEnqueuer
repo interfaces.TemporaryDocumentRepository
fileService interfaces.FileService
resourceCatalog interfaces.ResourceCatalog
documentReader interfaces.DocumentReader
imageResolver *docparser.ImageResolver
modelService interfaces.ModelService
tenantService interfaces.TenantService
taskEnqueuer interfaces.TaskEnqueuer
sessionAttachments sessionAttachmentLookup
}
func NewTemporaryDocumentService(
@ -113,11 +122,13 @@ func NewTemporaryDocumentService(
modelService interfaces.ModelService,
tenantService interfaces.TenantService,
taskEnqueuer interfaces.TaskEnqueuer,
messages interfaces.MessageRepository,
) interfaces.TemporaryDocumentService {
return &temporaryDocumentService{
repo: repo, fileService: fileService, resourceCatalog: resourceCatalog,
documentReader: documentReader, imageResolver: imageResolver,
modelService: modelService, tenantService: tenantService, taskEnqueuer: taskEnqueuer,
sessionAttachments: messages,
}
}
@ -242,11 +253,11 @@ func (s *temporaryDocumentService) supportsExtension(ctx context.Context, tenant
}
func (s *temporaryDocumentService) Get(ctx context.Context, tenantID uint64, sessionID, documentID string) (*types.TemporaryDocument, error) {
return s.repo.GetScoped(ctx, tenantID, sessionID, documentID)
return s.resolveInSession(ctx, tenantID, sessionID, documentID)
}
func (s *temporaryDocumentService) OpenFile(ctx context.Context, tenantID uint64, sessionID, documentID string) (io.ReadCloser, string, error) {
document, err := s.repo.GetScoped(ctx, tenantID, sessionID, documentID)
document, err := s.resolveInSession(ctx, tenantID, sessionID, documentID)
if err != nil {
return nil, "", err
}
@ -260,6 +271,52 @@ func (s *temporaryDocumentService) OpenFile(ctx context.Context, tenantID uint64
return file, document.FileName, nil
}
// resolveInSession finds a temporary document the caller may read from this
// session. Composer uploads live on temporary_documents.session_id; forked
// history keeps the parent's document id on copied messages, so a scoped miss
// falls back to tenant+id when that id appears on this session's messages.
func (s *temporaryDocumentService) resolveInSession(
ctx context.Context, tenantID uint64, sessionID, documentID string,
) (*types.TemporaryDocument, error) {
document, err := s.repo.GetScoped(ctx, tenantID, sessionID, documentID)
if err != nil || document != nil {
return document, err
}
document, err = s.repo.GetByID(ctx, tenantID, documentID)
if err != nil || document == nil {
return document, err
}
if document.SessionID == sessionID {
return document, nil
}
ok, authErr := s.sessionReferencesAttachment(ctx, sessionID, documentID)
if authErr != nil {
return nil, authErr
}
if !ok {
return nil, nil
}
return document, nil
}
func (s *temporaryDocumentService) sessionReferencesAttachment(
ctx context.Context, sessionID, documentID string,
) (bool, error) {
if s == nil || s.sessionAttachments == nil || sessionID == "" || documentID == "" {
return false, nil
}
attachments, err := s.sessionAttachments.GetSessionAttachments(ctx, sessionID)
if err != nil {
return false, fmt.Errorf("authorize forked attachment: %w", err)
}
for _, attachment := range attachments {
if attachment.ID == documentID {
return true, nil
}
}
return false, nil
}
func (s *temporaryDocumentService) List(ctx context.Context, tenantID uint64, sessionID string) ([]*types.TemporaryDocument, error) {
return s.repo.ListScoped(ctx, tenantID, sessionID)
}
@ -609,7 +666,7 @@ func (s *temporaryDocumentService) ResolveForPrompt(ctx context.Context, tenantI
continue
}
seen[documentID] = struct{}{}
document, err := s.repo.GetScoped(ctx, tenantID, sessionID, documentID)
document, err := s.resolveInSession(ctx, tenantID, sessionID, documentID)
if err != nil {
return nil, err
}

View File

@ -0,0 +1,186 @@
package service
import (
"bytes"
"context"
"io"
"testing"
"time"
"github.com/Tencent/WeKnora/internal/types"
"github.com/stretchr/testify/require"
)
// Fork copies message attachment IDs onto the new session but leaves the
// temporary_documents row on the parent. Preview/Get are session-scoped, so
// they must still resolve a parent-owned document when this session's copied
// messages reference it — and must not leak a document that is not on the
// fork's history.
type forkAccessDocRepo struct {
docs []*types.TemporaryDocument
}
func (r *forkAccessDocRepo) Create(context.Context, *types.TemporaryDocument) error {
panic("unexpected Create")
}
func (r *forkAccessDocRepo) MarkProcessing(context.Context, uint64, string, time.Time) error {
panic("unexpected MarkProcessing")
}
func (r *forkAccessDocRepo) MarkReady(context.Context, uint64, string, string, types.JSON, types.JSON, types.JSON, int, int, time.Time) error {
panic("unexpected MarkReady")
}
func (r *forkAccessDocRepo) MarkFailed(context.Context, uint64, string, string) error {
panic("unexpected MarkFailed")
}
func (r *forkAccessDocRepo) DeleteScoped(context.Context, uint64, string, string) error {
panic("unexpected DeleteScoped")
}
func (r *forkAccessDocRepo) ListExpired(context.Context, time.Time, int) ([]*types.TemporaryDocument, error) {
panic("unexpected ListExpired")
}
func (r *forkAccessDocRepo) ListScoped(context.Context, uint64, string) ([]*types.TemporaryDocument, error) {
panic("unexpected ListScoped")
}
func (r *forkAccessDocRepo) GetByID(_ context.Context, tenantID uint64, documentID string) (*types.TemporaryDocument, error) {
for _, doc := range r.docs {
if doc.TenantID == tenantID && doc.ID == documentID {
return doc, nil
}
}
return nil, nil
}
func (r *forkAccessDocRepo) GetScoped(_ context.Context, tenantID uint64, sessionID, documentID string) (*types.TemporaryDocument, error) {
for _, doc := range r.docs {
if doc.TenantID == tenantID && doc.SessionID == sessionID && doc.ID == documentID {
return doc, nil
}
}
return nil, nil
}
type forkAccessAttachments struct {
bySession map[string]types.MessageAttachments
}
func (s *forkAccessAttachments) GetSessionAttachments(_ context.Context, sessionID string) (types.MessageAttachments, error) {
return s.bySession[sessionID], nil
}
func parentOwnedBrief(t *testing.T) *types.TemporaryDocument {
t.Helper()
return &types.TemporaryDocument{
ID: "doc-1",
TenantID: 7,
SessionID: "parent",
ResourceRef: "local://tenant/brief.pdf",
FileName: "brief.pdf",
FileType: ".pdf",
FileSize: 12,
Status: types.TemporaryDocumentStatusReady,
ExpiresAt: time.Now().Add(time.Hour),
}
}
func TestGetUsesOwningSessionScopeWithoutMessageLookup(t *testing.T) {
doc := parentOwnedBrief(t)
doc.SessionID = "session-1"
svc := &temporaryDocumentService{
repo: &forkAccessDocRepo{docs: []*types.TemporaryDocument{doc}},
}
got, err := svc.Get(context.Background(), 7, "session-1", "doc-1")
require.NoError(t, err)
require.NotNil(t, got)
require.Equal(t, "session-1", got.SessionID)
}
func TestGetResolvesParentAttachmentReferencedByForkedSession(t *testing.T) {
doc := parentOwnedBrief(t)
svc := &temporaryDocumentService{
repo: &forkAccessDocRepo{docs: []*types.TemporaryDocument{doc}},
sessionAttachments: &forkAccessAttachments{bySession: map[string]types.MessageAttachments{
"fork": {{ID: "doc-1", FileName: "brief.pdf"}},
}},
}
got, err := svc.Get(context.Background(), 7, "fork", "doc-1")
require.NoError(t, err)
require.NotNil(t, got)
require.Equal(t, "doc-1", got.ID)
require.Equal(t, "parent", got.SessionID)
}
func TestGetHidesParentAttachmentNotOnForkedHistory(t *testing.T) {
doc := parentOwnedBrief(t)
svc := &temporaryDocumentService{
repo: &forkAccessDocRepo{docs: []*types.TemporaryDocument{doc}},
sessionAttachments: &forkAccessAttachments{bySession: map[string]types.MessageAttachments{
"fork": {{ID: "other-doc", FileName: "later.pdf"}},
}},
}
got, err := svc.Get(context.Background(), 7, "fork", "doc-1")
require.NoError(t, err)
require.Nil(t, got, "a fork must not preview attachments that were not copied into its history")
}
func TestOpenFileResolvesParentAttachmentReferencedByForkedSession(t *testing.T) {
doc := parentOwnedBrief(t)
files := &stagingFileService{files: map[string][]byte{doc.ResourceRef: []byte("%PDF-fake")}}
svc := &temporaryDocumentService{
repo: &forkAccessDocRepo{docs: []*types.TemporaryDocument{doc}},
fileService: files,
sessionAttachments: &forkAccessAttachments{bySession: map[string]types.MessageAttachments{
"fork": {{ID: "doc-1", FileName: "brief.pdf"}},
}},
}
reader, name, err := svc.OpenFile(context.Background(), 7, "fork", "doc-1")
require.NoError(t, err)
require.Equal(t, "brief.pdf", name)
body, err := io.ReadAll(reader)
require.NoError(t, err)
require.NoError(t, reader.Close())
require.True(t, bytes.Equal(body, []byte("%PDF-fake")))
}
func TestResolveForPromptUsesParentAttachmentReferencedByFork(t *testing.T) {
doc := parentOwnedBrief(t)
doc.Content = "parent brief body"
svc := &temporaryDocumentService{
repo: &forkAccessDocRepo{docs: []*types.TemporaryDocument{doc}},
sessionAttachments: &forkAccessAttachments{bySession: map[string]types.MessageAttachments{
"fork": {{ID: "doc-1", FileName: "brief.pdf"}},
}},
}
got, err := svc.ResolveForPrompt(context.Background(), 7, "fork", []string{"doc-1"}, "summarize")
require.NoError(t, err)
require.Len(t, got.Attachments, 1)
require.Equal(t, "doc-1", got.Attachments[0].ID)
require.Equal(t, "parent brief body", got.Attachments[0].Content)
}
func TestResolveForPromptHidesParentAttachmentNotOnForkedHistory(t *testing.T) {
doc := parentOwnedBrief(t)
doc.Content = "secret"
svc := &temporaryDocumentService{
repo: &forkAccessDocRepo{docs: []*types.TemporaryDocument{doc}},
sessionAttachments: &forkAccessAttachments{bySession: map[string]types.MessageAttachments{
"fork": {{ID: "other-doc", FileName: "later.pdf"}},
}},
}
_, err := svc.ResolveForPrompt(context.Background(), 7, "fork", []string{"doc-1"}, "summarize")
require.Error(t, err)
require.Contains(t, err.Error(), "not found")
}

View File

@ -0,0 +1,166 @@
// Package service - per-turn /workspace git checkpoints.
//
// WorkspaceCheckpointer commits the session sandbox's /workspace at the end of
// every agent turn so session fork can later roll a forked sandbox back to a
// specific turn. It mirrors ArtifactCollector's shape deliberately: a narrow
// injectable interface for the sandbox side, and strict best-effort semantics
// so an auxiliary feature can never break a reply.
//
// Contract:
// - Never returns an error. A failed checkpoint yields nil, the message
// simply carries no checkpoint, and that fork point degrades.
// - Never lazy-creates a sandbox: an empty sandboxID short-circuits.
// - Idempotent inside the sandbox: the script initialises the repository
// only when absent, so pause/resume and sandbox rebuilds self-heal.
package service
import (
"context"
"fmt"
"regexp"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/Tencent/WeKnora/internal/types"
)
// SandboxShellRunner is the narrow subset of sandbox behaviour the
// checkpointer needs. *sandbox.SessionBoundManager satisfies it in production;
// tests use a fake to assert on the emitted script without a real sandbox.
type SandboxShellRunner interface {
ExecShellCommand(
ctx context.Context,
sessionID, command, workDir string,
timeout time.Duration,
env map[string]string,
) (*sandbox.ExecuteResult, error)
}
// workspaceCheckpointTimeout bounds the git round-trip. `git add -A` walks the
// whole working tree, so this is generous relative to a normal commit but
// still short enough that a wedged sandbox cannot stall the completion path.
const workspaceCheckpointTimeout = 30 * time.Second
// gitSHAPattern matches a full 40-character hex object name. The script's last
// stdout line must look like one; anything else means git printed a warning or
// the script diverged, and we refuse to record a checkpoint we cannot trust.
var gitSHAPattern = regexp.MustCompile(`^[0-9a-f]{40}$`)
// WorkspaceCheckpointer commits /workspace after each agent turn.
type WorkspaceCheckpointer struct {
runner SandboxShellRunner
}
// NewWorkspaceCheckpointer wires a checkpointer. A nil runner yields a
// checkpointer that degrades to "no checkpoint", matching the graceful
// degradation contract used by ArtifactCollector.
func NewWorkspaceCheckpointer(runner SandboxShellRunner) *WorkspaceCheckpointer {
return &WorkspaceCheckpointer{runner: runner}
}
// checkpointScript renders the idempotent init-and-commit script.
//
// Ordering matters in two places:
//
// - `safe.directory` comes first. /workspace is owned by uid 1000 while
// shell_exec runs as root by default, and git refuses to touch a
// dubiously-owned repository — including from the rev-parse probe below.
// Plain assignment rather than `--add`: safe.directory is a multi-valued
// key, so --add would append one duplicate line to ~/.gitconfig per turn.
//
// - `--allow-empty` is mandatory. A turn that only answered a question
// without touching a file would otherwise produce no commit, leaving that
// message with no checkpoint and making it unusable as a fork point. With
// it, every turn has exactly one checkpoint and fork boundaries are always
// resolvable.
func checkpointScript(workspace, messageID string) string {
return fmt.Sprintf(`set -e
git config --global safe.directory %[1]s
git -C %[1]s rev-parse --git-dir >/dev/null 2>&1 || {
git init -q %[1]s
git -C %[1]s config user.email agent@weknora.local
git -C %[1]s config user.name 'WeKnora Agent'
}
git -C %[1]s add -A
git -C %[1]s commit -q --allow-empty -m 'turn:%[2]s'
git -C %[1]s rev-parse HEAD`, workspace, messageID)
}
// Checkpoint commits /workspace and returns the resulting checkpoint, or nil
// when anything at all went wrong. It never returns an error by design: the
// caller runs on the turn-completion path and must not be blocked here.
func (c *WorkspaceCheckpointer) Checkpoint(
ctx context.Context, sessionID, sandboxID, messageID string,
) *types.SandboxCheckpoint {
if c == nil || c.runner == nil {
return nil
}
if strings.TrimSpace(sessionID) == "" || strings.TrimSpace(messageID) == "" {
return nil
}
// No bound sandbox means there is nothing to snapshot, and a checkpoint
// without a sandbox ID could never be validated at fork time anyway.
if strings.TrimSpace(sandboxID) == "" {
return nil
}
result, err := c.runner.ExecShellCommand(
ctx,
sessionID,
checkpointScript(sandbox.SessionWorkspaceRoot, messageID),
sandbox.SessionWorkspaceRoot,
workspaceCheckpointTimeout,
nil,
)
if err != nil {
logger.Warnf(ctx, "[WorkspaceCheckpointer] exec failed session=%s message=%s: %v",
sessionID, messageID, err)
return nil
}
if result == nil {
logger.Warnf(ctx, "[WorkspaceCheckpointer] nil result session=%s message=%s",
sessionID, messageID)
return nil
}
if result.ExitCode != 0 {
logger.Warnf(ctx,
"[WorkspaceCheckpointer] git exited %d session=%s message=%s stderr=%s",
result.ExitCode, sessionID, messageID, truncateForLog(result.Stderr))
return nil
}
sha := lastNonEmptyLine(result.Stdout)
if !gitSHAPattern.MatchString(sha) {
logger.Warnf(ctx,
"[WorkspaceCheckpointer] unexpected stdout tail session=%s message=%s tail=%q",
sessionID, messageID, truncateForLog(sha))
return nil
}
return &types.SandboxCheckpoint{
SandboxID: sandboxID,
CommitSHA: sha,
CommittedAt: time.Now().UTC(),
}
}
func lastNonEmptyLine(s string) string {
lines := strings.Split(strings.TrimRight(s, "\n"), "\n")
for i := len(lines) - 1; i >= 0; i-- {
if line := strings.TrimSpace(lines[i]); line != "" {
return line
}
}
return ""
}
func truncateForLog(s string) string {
const limit = 256
s = strings.TrimSpace(s)
if len(s) <= limit {
return s
}
return s[:limit] + "…"
}

View File

@ -0,0 +1,118 @@
package service
import (
"context"
"errors"
"strings"
"testing"
"time"
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/stretchr/testify/require"
)
type fakeShellRunner struct {
calls []string
result *sandbox.ExecuteResult
err error
timeout time.Duration
workDir string
}
func (f *fakeShellRunner) ExecShellCommand(
_ context.Context, _ string, command, workDir string,
timeout time.Duration, _ map[string]string,
) (*sandbox.ExecuteResult, error) {
f.calls = append(f.calls, command)
f.timeout = timeout
f.workDir = workDir
return f.result, f.err
}
func TestCheckpointReturnsShaFromLastStdoutLine(t *testing.T) {
runner := &fakeShellRunner{result: &sandbox.ExecuteResult{
ExitCode: 0,
Stdout: "Initialized empty Git repository\n1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b\n",
}}
cp := NewWorkspaceCheckpointer(runner)
got := cp.Checkpoint(context.Background(), "s1", "sbx-1", "msg-1")
require.NotNil(t, got)
require.Equal(t, "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b", got.CommitSHA)
require.Equal(t, "sbx-1", got.SandboxID)
require.False(t, got.CommittedAt.IsZero())
}
func TestCheckpointScriptShape(t *testing.T) {
runner := &fakeShellRunner{result: &sandbox.ExecuteResult{
ExitCode: 0, Stdout: strings.Repeat("a", 40) + "\n",
}}
cp := NewWorkspaceCheckpointer(runner)
cp.Checkpoint(context.Background(), "s1", "sbx-1", "msg-42")
require.Len(t, runner.calls, 1)
script := runner.calls[0]
// safe.directory must precede the rev-parse probe: the probe itself is
// what dubious-ownership blocks.
require.Less(t,
strings.Index(script, "safe.directory"),
strings.Index(script, "rev-parse --git-dir"),
)
// Plain assignment, not --add: safe.directory is multi-valued and --add
// would append a duplicate line to ~/.gitconfig on every single turn.
require.NotContains(t, script, "--add safe.directory")
require.Contains(t, script, "--allow-empty")
require.Contains(t, script, "turn:msg-42")
require.NotContains(t, script, ".gitignore")
require.NotContains(t, script, "printf 'input/\\noutput/\\n'")
require.Equal(t, workspaceCheckpointTimeout, runner.timeout)
require.Equal(t, sandbox.SessionWorkspaceRoot, runner.workDir)
}
func TestCheckpointReturnsNilWhenExecFails(t *testing.T) {
runner := &fakeShellRunner{err: errors.New("sandbox unreachable")}
cp := NewWorkspaceCheckpointer(runner)
require.Nil(t, cp.Checkpoint(context.Background(), "s1", "sbx-1", "msg-1"))
}
func TestCheckpointReturnsNilOnNonZeroExit(t *testing.T) {
runner := &fakeShellRunner{result: &sandbox.ExecuteResult{
ExitCode: 128, Stderr: "fatal: not a git repository",
}}
cp := NewWorkspaceCheckpointer(runner)
require.Nil(t, cp.Checkpoint(context.Background(), "s1", "sbx-1", "msg-1"))
}
func TestCheckpointReturnsNilWhenStdoutIsNotASha(t *testing.T) {
runner := &fakeShellRunner{result: &sandbox.ExecuteResult{
ExitCode: 0, Stdout: "warning: something odd\n",
}}
cp := NewWorkspaceCheckpointer(runner)
require.Nil(t, cp.Checkpoint(context.Background(), "s1", "sbx-1", "msg-1"))
}
func TestCheckpointReturnsNilWhenRunnerMissing(t *testing.T) {
require.Nil(t, NewWorkspaceCheckpointer(nil).Checkpoint(
context.Background(), "s1", "sbx-1", "msg-1"))
var nilCheckpointer *WorkspaceCheckpointer
require.Nil(t, nilCheckpointer.Checkpoint(context.Background(), "s1", "sbx-1", "msg-1"))
}
func TestCheckpointReturnsNilWithoutSandboxID(t *testing.T) {
runner := &fakeShellRunner{result: &sandbox.ExecuteResult{
ExitCode: 0, Stdout: strings.Repeat("a", 40) + "\n",
}}
cp := NewWorkspaceCheckpointer(runner)
// No bound sandbox means there is nothing to check point, and a checkpoint
// without a sandbox ID could never be validated at fork time.
require.Nil(t, cp.Checkpoint(context.Background(), "s1", "", "msg-1"))
require.Empty(t, runner.calls)
}

View File

@ -88,6 +88,7 @@ import (
"github.com/Tencent/WeKnora/internal/models/limiter"
"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/storageallowlist"
"github.com/Tencent/WeKnora/internal/stream"
"github.com/Tencent/WeKnora/internal/tracing/langfuse"
@ -197,6 +198,13 @@ func BuildContainer(container *dig.Container) *dig.Container {
// from the tenant's own configuration, falling back to the singleton above
// for tenants that configured nothing.
must(container.Provide(service.NewTenantSandboxConfigLoader))
must(container.Provide(service.NewForkBootstrapperFromRepos))
must(container.Provide(func(b *service.ForkBootstrapper) sandbox.SessionBootstrapper {
if b == nil {
return nil
}
return b
}))
must(container.Provide(newTenantSandboxResolver))
// Business service layer
@ -322,6 +330,54 @@ func BuildContainer(container *dig.Container) *dig.Container {
// per-session file inspection; downstream code guards on nil.
must(container.Provide(service.NewArtifactCollectorFromSandboxManager))
// WorkspaceCheckpointer commits the sandbox /workspace after each agent
// turn so session fork can roll a forked sandbox back to a given message.
// The process-wide Manager is DisabledManager, so the runner and ID lookup
// go through the session pin + per-tenant resolver — the same path
// ArtifactCollector already uses. Direct Manager type-asserts still win
// when a deployment injects a SessionBoundManager as the process default.
must(container.Provide(func(
mgr sandbox.Manager,
resolver sandbox.TenantSandboxResolver,
pinner *service.SessionSandboxPinner,
) *service.PinnedSessionSandbox {
return service.NewPinnedSessionSandbox(pinner, resolver, mgr)
}))
must(container.Provide(func(
mgr sandbox.Manager,
pinned *service.PinnedSessionSandbox,
) *service.WorkspaceCheckpointer {
if runner, ok := mgr.(service.SandboxShellRunner); ok {
return service.NewWorkspaceCheckpointer(runner)
}
return service.NewWorkspaceCheckpointer(pinned)
}))
must(container.Provide(func(
mgr sandbox.Manager,
pinned *service.PinnedSessionSandbox,
) session.SandboxIDLookup {
if lookup, ok := mgr.(session.SandboxIDLookup); ok {
return lookup
}
if pinned == nil {
return nil
}
return pinned
}))
must(container.Provide(func(
mgr sandbox.Manager,
pinned *service.PinnedSessionSandbox,
) service.SessionForkSandboxPort {
if port, ok := mgr.(service.SessionForkSandboxPort); ok {
return port
}
if pinned == nil {
return nil
}
return pinned
}))
must(container.Provide(service.NewSessionForkServiceFromRepos))
// SandboxTerminalService opens interactive PTYs on session sandboxes for
// the frontend terminal panel. First-use provisioning takes a sandbox
// config ID already resolved by the WebSocket handler (own or shared agent).
@ -411,6 +467,17 @@ func BuildContainer(container *dig.Container) *dig.Container {
// block above — starting the reaper any earlier panics.
must(container.Invoke(startTenantSkillReaper))
logger.Debugf(ctx, "[Container] Tenant skill reaper registered")
must(container.Provide(func(
sessions interfaces.SessionRepository,
resolver sandbox.TenantSandboxResolver,
mgr sandbox.Manager,
) *service.ForkSnapshotReaper {
return service.NewForkSnapshotReaperFromRepos(
sessions, service.NewResolverForkSnapshotDeleter(resolver, mgr),
)
}))
must(container.Invoke(startForkSnapshotReaper))
logger.Debugf(ctx, "[Container] Fork snapshot reaper registered")
// HTTP handlers layer
logger.Debugf(ctx, "[Container] Registering HTTP handlers...")
@ -1782,6 +1849,38 @@ func startTenantSkillReaper(svc *service.TenantSkillService, cleaner interfaces.
})
}
// startForkSnapshotReaper collects snapshots of forks that were never opened.
// Best-effort: a wiring gap is logged but does NOT abort the container.
func startForkSnapshotReaper(reaper *service.ForkSnapshotReaper, cleaner interfaces.ResourceCleaner) {
if reaper == nil {
logger.Warnf(context.Background(), "[Container] fork snapshot reaper unavailable")
return
}
if cleaner == nil {
logger.Warnf(context.Background(), "[Container] fork snapshot reaper start failed: resource cleaner missing")
return
}
stop := make(chan struct{})
go func() {
ticker := time.NewTicker(6 * time.Hour)
defer ticker.Stop()
for {
select {
case <-ticker.C:
if _, err := reaper.ReapOnce(context.Background()); err != nil {
logger.Warnf(context.Background(), "[ForkSnapshotReaper] reap failed: %v", err)
}
case <-stop:
return
}
}
}()
cleaner.RegisterWithName("ForkSnapshotReaper", 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.

View File

@ -112,6 +112,7 @@ func newTenantSandboxResolver(
loader sandbox.TenantSandboxConfigLoader,
redisClient *redis.Client,
sessionRepo interfaces.SessionRepository,
bootstrapper sandbox.SessionBootstrapper,
) sandbox.TenantSandboxResolver {
ctx := context.Background()
@ -129,6 +130,7 @@ func newTenantSandboxResolver(
Loader: loader,
Store: store,
Checker: sessionExistenceCheckerFor(sessionRepo),
Bootstrapper: bootstrapper,
SharedTransport: sandbox.NewGuardedTransport(),
})
if err != nil {

View File

@ -2,8 +2,10 @@ package database
import (
"database/sql"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"github.com/stretchr/testify/require"
@ -23,24 +25,26 @@ var versionedSQLiteTables = []string{
"browser_devices",
"browser_pairings",
"browser_task_interruptions",
"fork_snapshot_leases",
}
// versionedSQLiteColumns maps each existing table to the columns that the
// versioned migrations add and the SQLite baseline was missing.
var versionedSQLiteColumns = map[string][]string{
"memory_subjects": {"extraction_state"}, // 000094
"memory_items": {"replaces_id"}, // 000094
"tenants": {"api_principal_config"}, // 000064
"users": {"is_system_admin"}, // 000053
"knowledges": {"pending_subtasks_count"}, // 000056
"messages": {"attachments", "usage"}, // 000034, 000085
"tenant_invitations": {"token", "accepted_count"}, // 000054
"embed_channels": {"allow_memory"}, // 000060
"mcp_oauth_tokens": {"principal_type", "principal_id"}, // 000064
"mcp_tool_approvals": {"enabled"}, // 000091
"memory_subjects": {"extraction_state"}, // 000094
"memory_items": {"replaces_id"}, // 000094
"tenants": {"api_principal_config"}, // 000064
"users": {"is_system_admin"}, // 000053
"knowledges": {"pending_subtasks_count"}, // 000056
"messages": {"attachments", "usage", "sandbox_checkpoint"}, // 000034, 000085, 000097
"sessions": {"parent_session_id", "forked_from_message_id", "fork_bootstrap"}, // 000097
"tenant_invitations": {"token", "accepted_count"}, // 000054
"embed_channels": {"allow_memory"}, // 000060
"mcp_oauth_tokens": {"principal_type", "principal_id"}, // 000064
"mcp_tool_approvals": {"enabled"}, // 000091
}
const expectedSQLiteMigrationVersion = 17
const expectedSQLiteMigrationVersion = 19
func TestSQLiteMigrationsCreateVersionedSchema(t *testing.T) {
repoRoot := sqliteRepoRoot(t)
@ -137,6 +141,42 @@ func TestSQLiteMigrationsUpgradeV4PreservesData(t *testing.T) {
require.False(t, sqliteColumnExists(t, db, "knowledges", "tag_id"))
}
func TestSQLiteMigrationsUpgradeV16AddsSessionForkColumns(t *testing.T) {
repoRoot := sqliteRepoRoot(t)
legacyRoot := copySQLiteMigrationsThrough(t, repoRoot, 16)
chdirAndRestore(t, legacyRoot)
dbPath := filepath.Join(t.TempDir(), "upgrade-v16.db")
require.NoError(t, RunMigrationsWithOptions("sqlite3://unused", MigrationOptions{SQLiteDBPath: dbPath}))
db := openSQLiteDB(t, dbPath)
versionBefore, dirtyBefore := sqliteMigrationState(t, db)
require.Equal(t, 16, versionBefore)
require.False(t, dirtyBefore)
require.False(t, sqliteColumnExists(t, db, "sessions", "parent_session_id"))
require.False(t, sqliteColumnExists(t, db, "sessions", "forked_from_message_id"))
require.False(t, sqliteColumnExists(t, db, "sessions", "fork_bootstrap"))
require.False(t, sqliteColumnExists(t, db, "messages", "sandbox_checkpoint"))
chdirAndRestore(t, repoRoot)
require.NoError(t, RunMigrationsWithOptions("sqlite3://unused", MigrationOptions{SQLiteDBPath: dbPath}))
db = openSQLiteDB(t, dbPath)
versionAfter, dirtyAfter := sqliteMigrationState(t, db)
require.Equal(t, expectedSQLiteMigrationVersion, versionAfter)
require.False(t, dirtyAfter)
for _, column := range versionedSQLiteColumns["sessions"] {
require.Truef(
t,
sqliteColumnExists(t, db, "sessions", column),
"upgraded SQLite DB must have column sessions.%s",
column,
)
}
require.True(t, sqliteColumnExists(t, db, "messages", "sandbox_checkpoint"))
}
func sqliteRepoRoot(t *testing.T) string {
t.Helper()
repoRoot, err := filepath.Abs(filepath.Join("..", ".."))
@ -248,23 +288,36 @@ func assertSQLiteMCPOAuthPrincipalUpsertWorks(t *testing.T, db *sql.DB) {
}
func copySQLiteMigrationsV4(t *testing.T, repoRoot string) string {
t.Helper()
return copySQLiteMigrationsThrough(t, repoRoot, 4)
}
func copySQLiteMigrationsThrough(t *testing.T, repoRoot string, maxVersion int) string {
t.Helper()
dest := t.TempDir()
srcDir := filepath.Join(repoRoot, "migrations", "sqlite")
destDir := filepath.Join(dest, "migrations", "sqlite")
require.NoError(t, os.MkdirAll(destDir, 0o755))
legacy := []string{
"000000_init.up.sql",
"000001_remove_wiki_log.up.sql",
"000002_knowledge_folder_path.up.sql",
"000003_knowledge_base_auto_tag_config.up.sql",
"000004_memory.up.sql",
}
for _, name := range legacy {
data, err := os.ReadFile(filepath.Join(srcDir, name))
require.NoError(t, err)
entries, err := os.ReadDir(srcDir)
require.NoError(t, err)
copied := 0
for _, entry := range entries {
name := entry.Name()
if entry.IsDir() || !strings.HasSuffix(name, ".up.sql") {
continue
}
var version int
_, scanErr := fmt.Sscanf(name, "%d_", &version)
require.NoError(t, scanErr, "sqlite migration filename %s", name)
if version > maxVersion {
continue
}
data, readErr := os.ReadFile(filepath.Join(srcDir, name))
require.NoError(t, readErr)
require.NoError(t, os.WriteFile(filepath.Join(destDir, name), data, 0o600))
copied++
}
require.Greater(t, copied, 0)
return dest
}

View File

@ -13,10 +13,22 @@ import (
"github.com/Tencent/WeKnora/internal/application/service"
"github.com/Tencent/WeKnora/internal/event"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// SandboxIDLookup reports the sandbox currently bound to a session without
// provisioning one. A session with no live sandbox reports ok=false, which the
// completion path treats as "nothing to check point".
type SandboxIDLookup interface {
BoundSandboxID(ctx context.Context, sessionID string) (string, bool)
}
var _ SandboxIDLookup = (*sandbox.SessionBoundManager)(nil)
var _ SandboxIDLookup = (*service.PinnedSessionSandbox)(nil)
// AgentStreamHandler handles agent events for SSE streaming
// It uses a dedicated EventBus per request to avoid SessionID filtering
// Events are appended to StreamManager without accumulation
@ -38,6 +50,16 @@ type AgentStreamHandler struct {
// doesn't support artifact collection or WeKnora was built without it.
artifactCollector *service.ArtifactCollector
// checkpointer commits the sandbox's /workspace at the end of the turn so
// session fork can roll a forked sandbox back to this exact message. Nil
// when the deployment has no sandbox backend; handleComplete checks.
checkpointer *service.WorkspaceCheckpointer
// sandboxIDLookup resolves the session's currently bound sandbox ID. The
// ID is stored next to the commit SHA because a SHA is only meaningful
// within one sandbox's git repository.
sandboxIDLookup SandboxIDLookup
// State tracking
knowledgeRefs []*types.SearchResult
finalAnswer string
@ -90,6 +112,8 @@ func NewAgentStreamHandler(
streamManager interfaces.StreamManager,
eventBus *event.EventBus,
artifactCollector *service.ArtifactCollector,
checkpointer *service.WorkspaceCheckpointer,
sandboxIDLookup SandboxIDLookup,
) *AgentStreamHandler {
return &AgentStreamHandler{
ctx: ctx,
@ -102,6 +126,8 @@ func NewAgentStreamHandler(
streamManager: streamManager,
eventBus: eventBus,
artifactCollector: artifactCollector,
checkpointer: checkpointer,
sandboxIDLookup: sandboxIDLookup,
knowledgeRefs: make([]*types.SearchResult, 0),
eventStartTimes: make(map[string]time.Time),
}
@ -717,6 +743,26 @@ func (h *AgentStreamHandler) handleComplete(ctx context.Context, evt event.Event
h.assistantMessage.Usage = usage
}
// Check point /workspace before draining artifacts. Every tool has
// finished, and the turn's sandbox lease is still held, so the sandbox
// is guaranteed to still be here.
//
// This runs on every exit path, including cancelled and errored turns.
// Skipping unsuccessful turns would fold their file changes into the
// NEXT turn's commit, so forking at that next turn would silently pick
// up the cancelled turn's edits.
//
// Best-effort throughout: a nil checkpoint just means this message
// cannot serve as a fork point.
if h.checkpointer != nil && h.sandboxIDLookup != nil {
checkpointCtx := context.WithoutCancel(h.ctx)
if sandboxID, ok := h.sandboxIDLookup.BoundSandboxID(checkpointCtx, h.sessionID); ok {
h.assistantMessage.SandboxCheckpoint = h.checkpointer.Checkpoint(
checkpointCtx, h.sessionID, sandboxID, h.assistantMessageID,
)
}
}
// Drain skill-generated files from the sandbox into persistent
// storage. Best-effort: any failure is logged and the turn is
// persisted without artifacts. Collect is a no-op when either the
@ -738,22 +784,46 @@ func (h *AgentStreamHandler) handleComplete(ctx context.Context, evt event.Event
"artifact collect failed session=%s message=%s: %v",
h.sessionID, h.assistantMessageID, err,
)
} else if len(artifacts) > 0 {
h.assistantMessage.Artifacts = artifacts
}
// Resolve the files the answer names against this turn's artifacts
// AND the ones already recorded for the session.
//
// A turn can legitimately reference a file it did not regenerate.
// The first turn after a session fork is restored to the fork point,
// so every unchanged file is de-duplicated out of `artifacts` — yet
// the model still writes `sandbox:<name>` for it. Gating the
// rewrite on `artifacts` alone would leave those references
// unnormalized, and the client resolves names only against the
// message's own artifact list, so they would render as missing
// files.
// KnownArtifacts is oldest-first. Name matching is first-wins, so
// this turn shadows a regenerated file, then the latest known
// version (the fork-point file) beats earlier ones of the same name.
known := h.artifactCollector.SessionArtifacts(collectCtx, h.sessionID)
referenced := referencedArtifacts(
h.assistantMessage.Content,
mergeArtifactLists(artifacts, artifactsNewestFirst(known)),
)
previous = historyOnlyArtifacts(referenced, artifacts)
if attached := mergeArtifactLists(h.assistantMessage.Artifacts, artifacts, referenced); len(attached) > 0 {
h.assistantMessage.Artifacts = attached
// The answer text names generated files the way the model saw
// them in the sandbox. Bind those names to artifact indices now
// that the index space is final, so a reloaded conversation
// renders them instead of showing a broken link.
h.assistantMessage.Content = rewriteArtifactReferences(
h.assistantMessage.Content, artifacts,
h.assistantMessage.Content, attached,
)
logger.GetLogger(h.ctx).Infof(
"artifact collect attached %d file(s) to message=%s session=%s",
len(artifacts), h.assistantMessageID, h.sessionID,
len(attached), h.assistantMessageID, h.sessionID,
)
}
previous = h.artifactCollector.ReferencedHistory(collectCtx, h.sessionID,
h.assistantMessageID, h.assistantMessage.Content)
// A reused reference is owned by this message too, so deleting the
// message that first produced the file cannot invalidate it.
h.artifactCollector.BindArtifactsToMessage(collectCtx, h.assistantMessageID, previous)
}
h.assistantMessage.Content = types.ClarifyArtifactVersions(h.assistantMessage.Content,
h.assistantMessage.Artifacts, previous, types.LanguageFromContextOrDefault(h.ctx))

View File

@ -2,7 +2,9 @@ package session
import (
"context"
"strings"
"testing"
"time"
"github.com/Tencent/WeKnora/internal/application/service"
"github.com/Tencent/WeKnora/internal/event"
@ -27,14 +29,24 @@ func (s completionHistory) KnownArtifacts(context.Context, string) ([]types.Mess
return s.previous, nil
}
func (s completionHistory) RecordRestoredMtime(context.Context, string, string, time.Time, string) error {
return nil
}
func TestCompletionPublishesReconciledArtifactContent(t *testing.T) {
old := types.MessageArtifact{URL: "resource://dHZ_fFslfs0GgJGaJZGjGA", FileName: "deck.pptx", SourcePath: "/workspace/output/deck.pptx"}
next := old
next.URL = "resource://4N1nAo-FZZoDEExDQz2yoA"
stream := &completionEventRecorder{}
message := &types.Message{ID: "m", Content: "![deck](" + old.URL + ")", Artifacts: types.MessageArtifacts{next}}
handler := NewAgentStreamHandler(context.Background(), "s", "m", "req", 1, next.CreatedAt,
message, stream, nil, service.NewArtifactCollector(nil, nil, completionHistory{[]types.MessageArtifact{old}}, nil, service.ArtifactCollectorConfig{}))
handler := NewAgentStreamHandler(
context.Background(), "s", "m", "req", 1, next.CreatedAt,
message, stream, nil,
service.NewArtifactCollector(
nil, nil, completionHistory{[]types.MessageArtifact{old}}, nil, service.ArtifactCollectorConfig{},
),
nil, nil,
)
err := handler.handleComplete(context.Background(), event.Event{Data: event.AgentCompleteData{MessageID: "m"}})
require.NoError(t, err)
last := stream.events[len(stream.events)-1]
@ -45,3 +57,68 @@ func TestCompletionPublishesReconciledArtifactContent(t *testing.T) {
response := buildStreamResponse(last, "req")
require.Equal(t, message.Content, response.Data["final_content"])
}
// A turn that re-references a file it did not regenerate must still resolve the
// name. ArtifactCollector de-duplicates identical content, so this turn's
// `artifacts` is empty — and the rewrite used to be gated on it, leaving the
// body's `sandbox:<name>` unnormalized and rendering as a missing file.
//
// The first turn after a session fork is exactly this: the sandbox is rolled
// back to the fork point, so every file carried over from before the fork is
// skipped as unchanged.
func TestCompletionResolvesReferencesWhenNothingWasPersisted(t *testing.T) {
existing := types.MessageArtifact{
URL: types.BuildResourcePath(strings.Repeat("a", types.ResourceHandleLength)),
FileName: "report.pptx",
SourcePath: "/workspace/output/report.pptx",
}
stream := &completionEventRecorder{}
message := &types.Message{ID: "m", Content: "已生成 ![报告](sandbox:report.pptx)"}
handler := NewAgentStreamHandler(context.Background(), "s", "m", "req", 1, time.Time{},
message, stream, nil,
service.NewArtifactCollector(nil, nil, completionHistory{[]types.MessageArtifact{existing}}, nil, service.ArtifactCollectorConfig{}),
nil, nil)
err := handler.handleComplete(context.Background(), event.Event{Data: event.AgentCompleteData{MessageID: "m"}})
require.NoError(t, err)
require.Len(t, message.Artifacts, 1, "the referenced file must be attached to this message")
require.Equal(t, existing.URL, message.Artifacts[0].URL)
require.Contains(t, message.Content, existing.URL)
require.NotContains(t, message.Content, "sandbox:")
last := stream.events[len(stream.events)-1]
require.Equal(t, types.ResponseTypeComplete, last.Type)
require.Equal(t, message.Content, last.Data["final_content"])
}
// KnownArtifacts is creation order (oldest first). A name with several
// versions must resolve to the latest recorded file — the one sitting in
// the sandbox at the fork point — not the first time that name appeared.
func TestCompletionResolvesNameToLatestKnownVersion(t *testing.T) {
old := types.MessageArtifact{
URL: types.BuildResourcePath(strings.Repeat("a", types.ResourceHandleLength)),
FileName: "report.pptx",
SourcePath: "/workspace/output/report.pptx",
}
latest := types.MessageArtifact{
URL: types.BuildResourcePath(strings.Repeat("b", types.ResourceHandleLength)),
FileName: "report.pptx",
SourcePath: "/workspace/output/report.pptx",
}
stream := &completionEventRecorder{}
message := &types.Message{ID: "m", Content: "已生成 ![报告](sandbox:report.pptx)"}
handler := NewAgentStreamHandler(context.Background(), "s", "m", "req", 1, time.Time{},
message, stream, nil,
service.NewArtifactCollector(nil, nil, completionHistory{[]types.MessageArtifact{old, latest}}, nil, service.ArtifactCollectorConfig{}),
nil, nil)
err := handler.handleComplete(context.Background(), event.Event{Data: event.AgentCompleteData{MessageID: "m"}})
require.NoError(t, err)
require.Len(t, message.Artifacts, 1)
require.Equal(t, latest.URL, message.Artifacts[0].URL)
require.Contains(t, message.Content, latest.URL)
require.NotContains(t, message.Content, old.URL)
require.NotContains(t, message.Content, "sandbox:")
}

View File

@ -190,6 +190,19 @@ func looksLikeSandboxOutputPath(candidate string) bool {
// lookupArtifactRef resolves one Markdown destination to an artifact reference.
func lookupArtifactRef(destination string, byName map[string]string, image bool) (string, bool) {
name, ok := artifactDestinationName(destination, image)
if !ok {
return "", false
}
ref, ok := byName[name]
return ref, ok
}
// artifactDestinationName normalizes one Markdown link/image destination down to
// the sandbox-output file name it names. ok is false when the destination is not
// a sandbox-local file name at all — a real URL, a resource:// handle, a bare
// name in an ordinary link, or incidental prose punctuation.
func artifactDestinationName(destination string, image bool) (string, bool) {
candidate := strings.TrimSpace(destination)
if candidate == "" {
return "", false
@ -231,9 +244,101 @@ func lookupArtifactRef(destination string, byName map[string]string, image bool)
if candidate == "" || candidate == "." || candidate == "/" {
return "", false
}
return candidate, true
}
ref, ok := byName[candidate]
return ref, ok
// forEachArtifactDestination calls fn with the normalized file name of every
// link/image destination in content. Destinations inside code spans or fences
// are skipped, mirroring rewriteArtifactReferences.
func forEachArtifactDestination(content string, fn func(name string)) {
if content == "" || !strings.Contains(content, "](") {
return
}
// Split returns only the non-code segments (Go does not interleave the
// matched fences the way a capturing-group Python split would). Walk
// every part; skipping odd indexes would drop citations after the first
// fence, which rewriteArtifactReferences still rewrites.
for _, part := range fencedOrInlineCodeRE.Split(content, -1) {
walkSegmentDestinations(part, fn)
}
}
func walkSegmentDestinations(segment string, fn func(name string)) {
cursor := 0
for cursor < len(segment) {
relative := strings.Index(segment[cursor:], "](")
if relative < 0 {
return
}
closeBracket := cursor + relative
open := closeBracket + 1
inner, end, ok := scanLinkDestination(segment, open)
if !ok || !hasLinkLabelBefore(segment, closeBracket) {
cursor = open + 1
continue
}
destination, _ := splitDestinationTitle(inner)
if name, ok := artifactDestinationName(destination, markdownImageBefore(segment, closeBracket)); ok {
fn(name)
}
cursor = end + 1
}
}
// referencedArtifacts returns the candidates the answer body names, in
// candidate order.
//
// A candidate is named when the body carries its resource:// handle, or when a
// link/image destination resolves to its file name — the same spellings
// rewriteArtifactReferences accepts. Matching goes through the Markdown
// destination rules rather than a substring search, so a file that merely
// appears in prose is not treated as a reference.
//
// Candidates are matched in the order given: listing this turn's artifacts
// first lets a regenerated file shadow the older version of itself, so only an
// explicit handle reference still pulls the old version in.
func referencedArtifacts(content string, candidates types.MessageArtifacts) types.MessageArtifacts {
if content == "" || len(candidates) == 0 {
return nil
}
matched := make([]bool, len(candidates))
for _, handle := range types.ScanResourceReferences(content) {
for i := range candidates {
if candidates[i].URL == handle {
matched[i] = true
break
}
}
}
nameToIndex := make(map[string]int, len(candidates))
for i := range candidates {
name := strings.TrimSpace(candidates[i].FileName)
if name == "" {
continue
}
if _, exists := nameToIndex[name]; exists {
continue
}
nameToIndex[name] = i
}
if len(nameToIndex) > 0 {
forEachArtifactDestination(content, func(name string) {
if i, ok := nameToIndex[name]; ok {
matched[i] = true
}
})
}
var out types.MessageArtifacts
for i := range candidates {
if matched[i] {
out = append(out, candidates[i])
}
}
return out
}
// artifactRefByName maps each artifact's file name to the reference that
@ -268,3 +373,67 @@ func artifactReference(artifact types.MessageArtifact) string {
}
return "sandbox:" + strings.TrimSpace(artifact.FileName)
}
// artifactsNewestFirst returns a copy of artifacts in reverse order so the
// latest recorded version of a name is first. KnownArtifacts is creation
// order (oldest first); a hash-skipped citation must bind the fork-point
// file, not the first time that name appeared. A copy is required: reversing
// in place would mutate the store's backing slice.
func artifactsNewestFirst(artifacts types.MessageArtifacts) types.MessageArtifacts {
n := len(artifacts)
if n < 2 {
return artifacts
}
out := make(types.MessageArtifacts, n)
for i, artifact := range artifacts {
out[n-1-i] = artifact
}
return out
}
// mergeArtifactLists concatenates artifact lists in order, keeping the first
// occurrence of each storage URL. Order is preserved because a reference
// resolves to an index into the resulting list, so the caller's ordering
// decides which version a name points at: putting this turn's artifacts first
// makes a regenerated file shadow the older one.
func mergeArtifactLists(lists ...types.MessageArtifacts) types.MessageArtifacts {
var out types.MessageArtifacts
var seen map[string]struct{}
for _, list := range lists {
for _, artifact := range list {
key := strings.TrimSpace(artifact.URL)
if key != "" {
if _, exists := seen[key]; exists {
continue
}
if seen == nil {
seen = make(map[string]struct{})
}
seen[key] = struct{}{}
}
out = append(out, artifact)
}
}
return out
}
// historyOnlyArtifacts returns the entries of referenced that this turn did not
// produce. Those are the ones whose ownership has to be extended to the new
// message; the collector already bound the ones it persisted itself.
func historyOnlyArtifacts(referenced, current types.MessageArtifacts) types.MessageArtifacts {
if len(referenced) == 0 {
return nil
}
produced := make(map[string]struct{}, len(current))
for _, artifact := range current {
produced[strings.TrimSpace(artifact.URL)] = struct{}{}
}
var out types.MessageArtifacts
for _, artifact := range referenced {
if _, isCurrent := produced[strings.TrimSpace(artifact.URL)]; isCurrent {
continue
}
out = append(out, artifact)
}
return out
}

View File

@ -6,6 +6,7 @@ import (
"testing"
"github.com/Tencent/WeKnora/internal/types"
"github.com/stretchr/testify/require"
)
// handleFor builds a syntactically valid 22-character resource handle for
@ -206,3 +207,110 @@ func TestArtifactRefByNameKeepsFirstDuplicate(t *testing.T) {
t.Fatalf("b.html resolved to %q, want %q", byName["b.html"], refFor(2))
}
}
func TestReferencedArtifactsMatchesNamesAndHandles(t *testing.T) {
artifacts := artifactsFixture("report.pptx", "chart.html", "data.csv")
cases := []struct {
name string
content string
want types.MessageArtifacts
}{
{
name: "sandbox-prefixed name",
content: "已生成 ![报告](sandbox:report.pptx)",
want: types.MessageArtifacts{artifacts[0]},
},
{
name: "bare name in an image",
content: "![图表](chart.html)",
want: types.MessageArtifacts{artifacts[1]},
},
{
name: "output path in an ordinary link",
content: "[数据](./output/data.csv)",
want: types.MessageArtifacts{artifacts[2]},
},
{
name: "canonical handle",
content: "![报告](" + refFor(0) + ")",
want: types.MessageArtifacts{artifacts[0]},
},
{
name: "prose mention is not a reference",
content: "生成了 report.pptx 和 chart.html 两个文件。",
want: nil,
},
{
name: "bare name in an ordinary link is not a reference",
content: "见 [说明](report.pptx)",
want: nil,
},
{
name: "unknown name",
content: "![别的](missing.pptx)",
want: nil,
},
{
name: "code sample is not a reference",
content: "```\n![报告](sandbox:report.pptx)\n```",
want: nil,
},
{
// Go regexp.Split does not interleave the matched fences, so
// walking parts with i+=2 would skip the segment after the first
// fence and miss a real citation that rewrite still rewrites.
name: "reference after a code fence",
content: "![报告](sandbox:report.pptx)\n\n```\n![忽略](sandbox:chart.html)\n```\n\n![图表](sandbox:chart.html)",
want: types.MessageArtifacts{artifacts[0], artifacts[1]},
},
{
name: "multiple references keep candidate order",
content: "![数据](data.csv)\n\n![报告](sandbox:report.pptx)",
want: types.MessageArtifacts{artifacts[0], artifacts[2]},
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
require.Equal(t, tc.want, referencedArtifacts(tc.content, artifacts))
})
}
}
// A regenerated file shadows the older version of itself: the name resolves to
// the first candidate, while an explicit handle still reaches the old one.
func TestReferencedArtifactsPrefersTheFirstCandidate(t *testing.T) {
old := types.MessageArtifact{FileName: "deck.pptx", URL: refFor(0)}
fresh := types.MessageArtifact{FileName: "deck.pptx", URL: refFor(1)}
candidates := types.MessageArtifacts{fresh, old}
require.Equal(t, types.MessageArtifacts{fresh},
referencedArtifacts("![deck](sandbox:deck.pptx)", candidates))
require.Equal(t, types.MessageArtifacts{old},
referencedArtifacts("![deck]("+old.URL+")", candidates))
}
// KnownArtifacts is oldest-first. Reverse it before merging so a hash-skipped
// name binds the latest file; this turn still shadows that latest file.
func TestMergeArtifactListsPrefersThisTurnThenLatestKnown(t *testing.T) {
old := types.MessageArtifact{FileName: "deck.pptx", URL: refFor(0)}
latest := types.MessageArtifact{FileName: "deck.pptx", URL: refFor(1)}
fresh := types.MessageArtifact{FileName: "deck.pptx", URL: refFor(2)}
known := types.MessageArtifacts{old, latest}
require.Equal(t, types.MessageArtifacts{latest},
referencedArtifacts("![deck](sandbox:deck.pptx)",
mergeArtifactLists(nil, artifactsNewestFirst(known))))
require.Equal(t, types.MessageArtifacts{fresh},
referencedArtifacts("![deck](sandbox:deck.pptx)",
mergeArtifactLists(types.MessageArtifacts{fresh}, artifactsNewestFirst(known))))
}
func TestArtifactsNewestFirstDoesNotMutateInput(t *testing.T) {
in := artifactsFixture("a.html", "b.html")
got := artifactsNewestFirst(in)
require.Equal(t, "b.html", got[0].FileName)
require.Equal(t, "a.html", got[1].FileName)
require.Equal(t, "a.html", in[0].FileName)
}

View File

@ -15,7 +15,9 @@ func TestCommandOutputReachesChatStreamWithoutCompletingTool(t *testing.T) {
bus := event.NewEventBus()
streams := &completionEventRecorder{}
message := &types.Message{ID: "message"}
h := NewAgentStreamHandler(ctx, "session", "message", "request", 1, time.Now(), message, streams, bus, nil)
h := NewAgentStreamHandler(
ctx, "session", "message", "request", 1, time.Now(), message, streams, bus, nil, nil, nil,
)
h.Subscribe()
for _, done := range []bool{false, true} {
require.NoError(t, bus.Emit(ctx, event.Event{

View File

@ -0,0 +1,115 @@
package session
import (
"context"
stderrors "errors"
"net/http"
"strings"
"github.com/Tencent/WeKnora/internal/application/service"
"github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/gin-gonic/gin"
)
// sessionForker is the fork surface the handler needs. Declaring it here
// rather than depending on *service.SessionForkService keeps the handler
// testable with a stub.
type sessionForker interface {
Fork(
ctx context.Context,
tenantID uint64,
userID, sourceSessionID, messageID, title string,
) (*service.ForkResult, error)
}
// ForkSessionRequest is the fork endpoint's body.
type ForkSessionRequest struct {
// MessageID is the message to branch at. A user message copies history
// strictly before it (the client prefills that question). An assistant
// message copies history through that answer so the branch continues after it.
MessageID string `json:"message_id" binding:"required"`
// Title is optional. Empty falls back to the source title plus a suffix.
Title string `json:"title"`
}
// ForkSession godoc
// @Summary 分叉会话
// @Description 从指定的用户或助手消息处分叉出一个新会话。用户消息:复制其之前的历史并预填该问题;助手消息:复制含该回答在内的历史,从该轮沙箱状态继续。
// @Tags 会话
// @Accept json
// @Produce json
// @Param session_id path string true "源会话 ID"
// @Param request body ForkSessionRequest true "分叉请求"
// @Success 200 {object} map[string]interface{} "新会话"
// @Failure 400 {object} errors.AppError "请求参数错误 / 分叉点角色不支持"
// @Failure 404 {object} errors.AppError "会话或消息不存在"
// @Failure 409 {object} errors.AppError "源会话正在生成中"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /sessions/{session_id}/fork [post]
func (h *Handler) ForkSession(c *gin.Context) {
ctx := c.Request.Context()
sessionID := strings.TrimSpace(c.Param("session_id"))
if sessionID == "" {
sessionID = strings.TrimSpace(c.Param("id"))
}
if sessionID == "" {
_ = c.Error(errors.NewBadRequestError("session ID is required"))
return
}
var req ForkSessionRequest
if err := c.ShouldBindJSON(&req); err != nil {
_ = c.Error(errors.NewBadRequestError("message_id is required"))
return
}
if strings.TrimSpace(req.MessageID) == "" {
_ = c.Error(errors.NewBadRequestError("message_id is required"))
return
}
if h.forkService == nil {
_ = c.Error(errors.NewBadRequestError("session fork is not available"))
return
}
tenantID, _ := types.TenantIDFromContext(ctx)
userID := types.SessionOwnerIDFromContext(ctx)
result, err := h.forkService.Fork(
ctx, tenantID, userID, sessionID,
strings.TrimSpace(req.MessageID), strings.TrimSpace(req.Title),
)
if err != nil {
// A busy source is a retryable, user-actionable state, not a fault:
// snapshotting would pause the sandbox and interrupt the running turn.
if stderrors.Is(err, service.ErrForkSourceBusy) {
c.JSON(http.StatusConflict, gin.H{
"success": false,
"error": "source session has an active turn",
"code": "FORK_SOURCE_BUSY",
})
return
}
if stderrors.Is(err, service.ErrForkSessionNotFound) {
_ = c.Error(errors.NewNotFoundError("session not found"))
return
}
if stderrors.Is(err, service.ErrForkMessageNotFound) {
_ = c.Error(errors.NewNotFoundError("message not found"))
return
}
if stderrors.Is(err, service.ErrForkMessageNotUser) {
_ = c.Error(errors.NewBadRequestError("fork point must be a user or assistant message"))
return
}
logger.Errorf(ctx, "fork session %s failed: %v", sessionID, err)
_ = c.Error(errors.NewInternalServerError("fork session failed"))
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": result})
}

View File

@ -0,0 +1,135 @@
package session
import (
"bytes"
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"testing"
"github.com/Tencent/WeKnora/internal/application/service"
"github.com/Tencent/WeKnora/internal/middleware"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
type stubForker struct {
result *service.ForkResult
err error
gotMsg string
gotTit string
}
func (s *stubForker) Fork(
_ context.Context, _ uint64, _, _, messageID, title string,
) (*service.ForkResult, error) {
s.gotMsg = messageID
s.gotTit = title
return s.result, s.err
}
func performFork(t *testing.T, forker sessionForker, body string) *httptest.ResponseRecorder {
t.Helper()
gin.SetMode(gin.TestMode)
h := &Handler{forkService: forker}
w := httptest.NewRecorder()
r := gin.New()
r.Use(middleware.ErrorHandler())
r.POST("/sessions/:session_id/fork", h.ForkSession)
req := httptest.NewRequest(http.MethodPost, "/sessions/src/fork", bytes.NewBufferString(body))
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(w, req)
return w
}
func TestForkSessionReturnsNewSessionID(t *testing.T) {
forker := &stubForker{result: &service.ForkResult{SessionID: "new-1"}}
w := performFork(t, forker, `{"message_id":"u-2"}`)
require.Equal(t, http.StatusOK, w.Code)
require.Equal(t, "u-2", forker.gotMsg)
var body map[string]any
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body))
data := body["data"].(map[string]any)
require.Equal(t, "new-1", data["session_id"])
require.Equal(t, false, data["degraded"])
}
func TestForkSessionSurfacesDegradeReason(t *testing.T) {
forker := &stubForker{result: &service.ForkResult{
SessionID: "new-1", Degraded: true, Reason: service.ForkDegradeSandboxGone,
}}
w := performFork(t, forker, `{"message_id":"u-2"}`)
require.Equal(t, http.StatusOK, w.Code)
var body map[string]any
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body))
data := body["data"].(map[string]any)
require.Equal(t, true, data["degraded"])
require.Equal(t, "SANDBOX_GONE", data["reason"])
}
func TestForkSessionMapsBusySourceTo409(t *testing.T) {
forker := &stubForker{err: service.ErrForkSourceBusy}
w := performFork(t, forker, `{"message_id":"u-2"}`)
require.Equal(t, http.StatusConflict, w.Code)
var body map[string]any
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body))
require.Equal(t, "FORK_SOURCE_BUSY", body["code"])
}
func TestForkSessionMapsMissingSessionTo404(t *testing.T) {
forker := &stubForker{err: service.ErrForkSessionNotFound}
w := performFork(t, forker, `{"message_id":"u-2"}`)
require.Equal(t, http.StatusNotFound, w.Code)
}
func TestForkSessionMapsMissingMessageTo404(t *testing.T) {
forker := &stubForker{err: service.ErrForkMessageNotFound}
w := performFork(t, forker, `{"message_id":"u-2"}`)
require.Equal(t, http.StatusNotFound, w.Code)
}
func TestForkSessionMapsNonUserForkPointTo400(t *testing.T) {
forker := &stubForker{err: service.ErrForkMessageNotUser}
w := performFork(t, forker, `{"message_id":"a-1"}`)
require.Equal(t, http.StatusBadRequest, w.Code)
}
func TestForkSessionRejectsMissingMessageID(t *testing.T) {
forker := &stubForker{result: &service.ForkResult{SessionID: "new-1"}}
w := performFork(t, forker, `{}`)
require.Equal(t, http.StatusBadRequest, w.Code)
}
func TestForkSessionMapsUnknownErrorTo500(t *testing.T) {
forker := &stubForker{err: errors.New("boom")}
w := performFork(t, forker, `{"message_id":"u-2"}`)
require.Equal(t, http.StatusInternalServerError, w.Code)
}
func TestForkSessionPassesTitleThrough(t *testing.T) {
forker := &stubForker{result: &service.ForkResult{SessionID: "new-1"}}
performFork(t, forker, `{"message_id":"u-2","title":"我的分支"}`)
require.Equal(t, "我的分支", forker.gotTit)
}

View File

@ -40,7 +40,13 @@ type Handler struct {
// after an agent turn completes. May be nil when the sandbox backend does
// not support artifact collection; handlers must check before using.
artifactCollector *service.ArtifactCollector
memoryService interfaces.MemoryService // Service for cross-session long-term memory
// workspaceCheckpointer commits the sandbox /workspace at the end of each
// agent turn so session fork can roll back to a specific message. May be
// nil when the deployment has no sandbox backend.
workspaceCheckpointer *service.WorkspaceCheckpointer
// sandboxIDLookup resolves a session's bound sandbox without provisioning.
sandboxIDLookup SandboxIDLookup
memoryService interfaces.MemoryService // Service for cross-session long-term memory
// userService / memberService back the sandbox terminal's self-contained
// handshake (browser WebSocket upgrades cannot send Authorization).
userService interfaces.UserService
@ -56,6 +62,9 @@ type Handler struct {
// redis backs the distributed desktop slot. Nil in Lite mode, where the
// in-process limiter is the correct degradation.
redis *redis.Client
// forkService branches a session at a chosen user message. May be nil in
// deployments where fork is not wired; ForkSession checks.
forkService sessionForker
}
// NewHandler creates a new instance of Handler with all necessary dependencies
@ -78,6 +87,8 @@ func NewHandler(
imageResolver *docparser.ImageResolver,
temporaryDocuments interfaces.TemporaryDocumentService,
artifactCollector *service.ArtifactCollector,
workspaceCheckpointer *service.WorkspaceCheckpointer,
sandboxIDLookup SandboxIDLookup,
memoryService interfaces.MemoryService,
userService interfaces.UserService,
memberService interfaces.TenantMemberService,
@ -87,33 +98,36 @@ func NewHandler(
desktopTickets service.SandboxDesktopTicketStore,
desktopLast service.SandboxDesktopLastStore,
rdb *redis.Client,
forkService *service.SessionForkService,
) *Handler {
return &Handler{
browserSkill: browserSkill,
sessionService: sessionService,
messageService: messageService,
suggestionService: suggestionService,
streamManager: streamManager,
config: config,
knowledgebaseService: knowledgebaseService,
customAgentService: customAgentService,
tenantService: tenantService,
agentShareService: agentShareService,
kbShareService: kbShareService,
fileService: fileService,
resourceCatalog: resourceCatalog,
storageResolver: storageResolver,
modelService: modelService,
temporaryDocuments: temporaryDocuments,
artifactCollector: artifactCollector,
memoryService: memoryService,
userService: userService,
memberService: memberService,
terminalService: terminalService,
desktopService: desktopService,
desktopTickets: desktopTickets,
desktopLast: desktopLast,
redis: rdb,
h := &Handler{
browserSkill: browserSkill,
sessionService: sessionService,
messageService: messageService,
suggestionService: suggestionService,
streamManager: streamManager,
config: config,
knowledgebaseService: knowledgebaseService,
customAgentService: customAgentService,
tenantService: tenantService,
agentShareService: agentShareService,
kbShareService: kbShareService,
fileService: fileService,
resourceCatalog: resourceCatalog,
storageResolver: storageResolver,
modelService: modelService,
temporaryDocuments: temporaryDocuments,
artifactCollector: artifactCollector,
workspaceCheckpointer: workspaceCheckpointer,
sandboxIDLookup: sandboxIDLookup,
memoryService: memoryService,
userService: userService,
memberService: memberService,
terminalService: terminalService,
desktopService: desktopService,
desktopTickets: desktopTickets,
desktopLast: desktopLast,
redis: rdb,
attachmentProcessor: NewAttachmentProcessor(
fileService,
documentReader,
@ -121,6 +135,10 @@ func NewHandler(
modelService,
),
}
if forkService != nil {
h.forkService = forkService
}
return h
}
// CreateSession godoc

View File

@ -309,6 +309,7 @@ func (h *Handler) setupStreamHandler(
streamHandler := NewAgentStreamHandler(
ctx, sessionID, assistantMessageID, requestID, tenantID, receivedAt,
assistantMessage, h.streamManager, eventBus, h.artifactCollector,
h.workspaceCheckpointer, h.sandboxIDLookup,
)
streamHandler.Subscribe()
return streamHandler

View File

@ -1194,12 +1194,7 @@ func (h *Handler) executeQA(reqCtx *qaRequestContext, mode qaMode, generateTitle
logger.Infof(streamCtx.asyncCtx, "Knowledge QA service completed for session: %s", sessionID)
updateCtx := context.WithValue(streamCtx.asyncCtx, types.TenantIDContextKey, reqCtx.session.TenantID)
h.completeAssistantMessage(updateCtx, streamCtx.assistantMessage, reqCtx.query, reqCtx.userMessageID)
streamCtx.eventBus.Emit(streamCtx.asyncCtx, event.Event{
Type: event.EventAgentComplete,
SessionID: sessionID,
Data: event.AgentCompleteData{FinalAnswer: streamCtx.assistantMessage.Content},
})
h.completeQuickAnswerTurn(updateCtx, streamCtx, reqCtx.query, reqCtx.userMessageID)
}
return nil
})
@ -1674,6 +1669,31 @@ func appendQuickAnswerReasoning(msg *types.Message, content string) {
ensureQuickAnswerStep(msg).ReasoningContent += content
}
// completeQuickAnswerTurn finishes a KnowledgeQA (fast-answer) turn.
// EventAgentComplete must run before the GORM write: handleComplete attaches
// SandboxCheckpoint (and artifacts) to the in-memory message, and
// completeAssistantMessage is the only persist on this path.
func (h *Handler) completeQuickAnswerTurn(
ctx context.Context, streamCtx *sseStreamContext, query, userMessageID string,
) {
if streamCtx == nil || streamCtx.assistantMessage == nil {
return
}
if streamCtx.eventBus != nil {
// MessageID is what handleComplete keys on. Leave FinalAnswer empty:
// KnowledgeQA already accumulated the answer on the message, and
// handleComplete would append FinalAnswer a second time.
_ = streamCtx.eventBus.Emit(ctx, event.Event{
Type: event.EventAgentComplete,
SessionID: streamCtx.assistantMessage.SessionID,
Data: event.AgentCompleteData{
MessageID: streamCtx.assistantMessage.ID,
},
})
}
h.completeAssistantMessage(ctx, streamCtx.assistantMessage, query, userMessageID)
}
// completeAssistantMessage marks an assistant message as complete, updates it,
// and asynchronously indexes the Q&A pair into the chat history knowledge base.
func (h *Handler) completeAssistantMessage(

View File

@ -0,0 +1,151 @@
package session
import (
"context"
"errors"
"strings"
"testing"
"time"
"github.com/Tencent/WeKnora/internal/application/service"
"github.com/Tencent/WeKnora/internal/event"
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/stretchr/testify/require"
)
type stubShellRunner struct {
stdout string
exitCode int
err error
calls int
}
func (s *stubShellRunner) ExecShellCommand(
_ context.Context, _ string, _, _ string, _ time.Duration, _ map[string]string,
) (*sandbox.ExecuteResult, error) {
s.calls++
if s.err != nil {
return nil, s.err
}
return &sandbox.ExecuteResult{ExitCode: s.exitCode, Stdout: s.stdout}, nil
}
type stubSandboxIDLookup struct {
id string
ok bool
}
func (s stubSandboxIDLookup) BoundSandboxID(context.Context, string) (string, bool) {
return s.id, s.ok
}
func newCheckpointHandler(
t *testing.T, runner service.SandboxShellRunner, lookup SandboxIDLookup,
) (*AgentStreamHandler, *types.Message) {
t.Helper()
message := &types.Message{ID: "m1", SessionID: "s1", Role: "assistant"}
h := NewAgentStreamHandler(
context.Background(), "s1", "m1", "req1", 1, time.Now(),
message, &completionEventRecorder{}, event.NewEventBus(), nil,
service.NewWorkspaceCheckpointer(runner), lookup,
)
return h, message
}
func completeEvent() event.Event {
return event.Event{Data: event.AgentCompleteData{MessageID: "m1", FinalAnswer: "done"}}
}
func TestHandleCompleteRecordsCheckpoint(t *testing.T) {
runner := &stubShellRunner{stdout: strings.Repeat("a", 40) + "\n"}
h, message := newCheckpointHandler(t, runner, stubSandboxIDLookup{id: "sbx-1", ok: true})
require.NoError(t, h.handleComplete(context.Background(), completeEvent()))
require.Equal(t, 1, runner.calls)
require.NotNil(t, message.SandboxCheckpoint)
require.Equal(t, "sbx-1", message.SandboxCheckpoint.SandboxID)
require.Equal(t, strings.Repeat("a", 40), message.SandboxCheckpoint.CommitSHA)
}
// A failed checkpoint must never disturb the reply: the message still
// completes, it just carries no checkpoint and cannot serve as a fork point.
func TestHandleCompleteSurvivesCheckpointFailure(t *testing.T) {
runner := &stubShellRunner{err: errors.New("sandbox unreachable")}
h, message := newCheckpointHandler(t, runner, stubSandboxIDLookup{id: "sbx-1", ok: true})
require.NoError(t, h.handleComplete(context.Background(), completeEvent()))
require.Nil(t, message.SandboxCheckpoint)
require.True(t, message.IsCompleted)
}
func TestHandleCompleteSkipsCheckpointWithoutBoundSandbox(t *testing.T) {
runner := &stubShellRunner{stdout: strings.Repeat("a", 40) + "\n"}
h, message := newCheckpointHandler(t, runner, stubSandboxIDLookup{ok: false})
require.NoError(t, h.handleComplete(context.Background(), completeEvent()))
require.Zero(t, runner.calls)
require.Nil(t, message.SandboxCheckpoint)
}
func TestHandleCompleteWorksWithoutCheckpointerWired(t *testing.T) {
message := &types.Message{ID: "m1", SessionID: "s1", Role: "assistant"}
h := NewAgentStreamHandler(
context.Background(), "s1", "m1", "req1", 1, time.Now(),
message, &completionEventRecorder{}, event.NewEventBus(), nil, nil, nil,
)
require.NoError(t, h.handleComplete(context.Background(), completeEvent()))
require.Nil(t, message.SandboxCheckpoint)
}
type capturingMessageService struct {
interfaces.MessageService
content string
checkpoint *types.SandboxCheckpoint
}
func (s *capturingMessageService) UpdateMessage(_ context.Context, message *types.Message) error {
if message == nil {
return nil
}
s.content = message.Content
if message.SandboxCheckpoint != nil {
cp := *message.SandboxCheckpoint
s.checkpoint = &cp
}
return nil
}
func (s *capturingMessageService) IndexMessageToKB(context.Context, string, string, string, string) {}
func TestQuickAnswerCompletionPersistsSandboxCheckpoint(t *testing.T) {
runner := &stubShellRunner{stdout: strings.Repeat("a", 40) + "\n"}
bus := event.NewEventBus()
message := &types.Message{
ID: "m1", SessionID: "s1", Role: "assistant", Content: "hello from quick answer",
}
streamHandler := NewAgentStreamHandler(
context.Background(), "s1", "m1", "req1", 1, time.Now(),
message, &completionEventRecorder{}, bus,
nil, service.NewWorkspaceCheckpointer(runner), stubSandboxIDLookup{id: "sbx-1", ok: true},
)
streamHandler.Subscribe()
stub := &capturingMessageService{}
h := &Handler{messageService: stub}
h.completeQuickAnswerTurn(context.Background(), &sseStreamContext{
eventBus: bus,
assistantMessage: message,
}, "", "")
require.Equal(t, 1, runner.calls, "quick-answer complete must checkpoint before persist")
require.NotNil(t, stub.checkpoint, "UpdateMessage must see SandboxCheckpoint")
require.Equal(t, "sbx-1", stub.checkpoint.SandboxID)
require.Equal(t, strings.Repeat("a", 40), stub.checkpoint.CommitSHA)
require.Equal(t, "hello from quick answer", stub.content, "complete event must not re-append the answer")
}

View File

@ -64,6 +64,7 @@ func RegisterSessionRoutes(
sessions.GET("/:id/attachments/:attachment_id/preview", handler.PreviewTemporaryDocument)
sessions.DELETE("/:id/attachments/:attachment_id", handler.DeleteTemporaryDocument)
sessions.POST("/:session_id/stop", handler.StopSession)
sessions.POST("/:session_id/fork", handler.ForkSession)
sessions.POST("/:session_id/sandbox/terminal-ticket", handler.IssueSandboxTerminalTicket)
sessions.POST("/:session_id/sandbox/desktop-ticket", handler.IssueSandboxDesktopTicket)
sessions.POST("/:session_id/sandbox/desktop/activity", handler.ReportSandboxDesktopActivity)

View File

@ -652,6 +652,11 @@ func TestNormalizeCubeError(t *testing.T) {
StatusCode: http.StatusBadRequest,
Message: "cannot delete template x because there are paused sandboxes using it",
}, RemoteErrorKindConflict},
{"delete snapshot runtime refs", "DeleteSnapshot", &cubesandbox.APIError{
StatusCode: http.StatusInternalServerError,
Message: "CubeMaster returned error code 130409: template attempt is already in progress: " +
"snapshot snap-x still has 2 active runtime ref(s): a@host, b@host",
}, RemoteErrorKindConflict},
{"delete snapshot bad id", "DeleteSnapshot", &cubesandbox.APIError{
StatusCode: http.StatusBadRequest,
Message: "invalid snapshot id",

View File

@ -14,7 +14,7 @@
// Get/List → GET /containers/json?filters=label=…
// Delete → DELETE /containers/{id}?force=1
// Exec → POST /containers/{id}/exec → /exec/{id}/start (hijack)
// Snapshot → POST /commit (skill images under weknora-skill/)
// Snapshot → POST /commit (skill images under weknora-skill/, fork images under weknora-fork/)
//
// Every file operation uses exec with an explicit account (root by default),
// timeout and activity tracking. Archive endpoints bypass those exec settings.
@ -1183,8 +1183,12 @@ func (c *DockerRemoteClient) ensureImage(ctx context.Context, image string) erro
// Skill snapshots are daemon-local commits, not registry tags. Pulling
// one would hit Docker Hub for a name we minted and never pushed, and a
// miss here means "this daemon does not have the image", not "fetch it".
if dockerIsSkillSnapshotRef(image) {
return dockerInvalidRequest("Create", "skill snapshot image "+image+" is not on this daemon")
if dockerIsLocalSnapshotRef(image) {
kind := "skill"
if dockerIsForkSnapshotRef(image) {
kind = "fork"
}
return dockerInvalidRequest("Create", kind+" snapshot image "+image+" is not on this daemon")
}
pullCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), dockerImagePullBudget)
defer cancel()

View File

@ -18,6 +18,16 @@ const (
dockerSkillSnapshotLabel = "com.weknora.sandbox.skill-snapshot"
dockerSkillSnapshotSourceLabel = "com.weknora.sandbox.skill-snapshot-source"
// DockerForkSnapshotRepo is the local image namespace for session-fork
// snapshots. It is deliberately separate from dockerSkillSnapshotRepo: the
// skill reaper prunes by the skill namespace and labels, and letting fork
// snapshots share them would have each reaper collecting the other's
// images.
DockerForkSnapshotRepo = "weknora-fork"
dockerForkSnapshotLabel = "com.weknora.sandbox.fork-snapshot"
dockerForkSnapshotSourceLabel = "com.weknora.sandbox.fork-snapshot-source"
)
// CreateSnapshot commits the container's filesystem into a tagged local image.
@ -34,25 +44,58 @@ func (c *DockerRemoteClient) CreateSnapshot(
if id == "" {
return RemoteSnapshotRef{}, dockerInvalidRequest("CreateSnapshot", "sandbox ID is required")
}
reference, err := dockerSkillSnapshotReference(name, id)
return c.commitSnapshot(
ctx, id, name,
dockerSkillSnapshotRepo,
"weknora skill snapshot",
dockerSkillSnapshotLabel,
dockerSkillSnapshotSourceLabel,
"CreateSnapshot",
)
}
// CreateForkSnapshot commits the container into the fork image namespace.
// Same shape as CreateSnapshot; a different repo and labels keep the skill
// reaper from collecting (or being collected by) session-fork images.
func (c *DockerRemoteClient) CreateForkSnapshot(
ctx context.Context, sandboxID string, name string,
) (RemoteSnapshotRef, error) {
id := strings.TrimSpace(sandboxID)
if id == "" {
return RemoteSnapshotRef{}, dockerInvalidRequest("CreateForkSnapshot", "sandbox ID is required")
}
return c.commitSnapshot(
ctx, id, name,
DockerForkSnapshotRepo,
"weknora fork snapshot",
dockerForkSnapshotLabel,
dockerForkSnapshotSourceLabel,
"CreateForkSnapshot",
)
}
func (c *DockerRemoteClient) commitSnapshot(
ctx context.Context,
sandboxID, name, repo, comment, label, sourceLabel, op string,
) (RemoteSnapshotRef, error) {
reference, err := dockerSnapshotReference(repo, name, sandboxID, op)
if err != nil {
return RemoteSnapshotRef{}, err
}
committed, err := c.api.ContainerCommit(ctx, id, client.ContainerCommitOptions{
committed, err := c.api.ContainerCommit(ctx, sandboxID, client.ContainerCommitOptions{
Reference: reference,
Comment: "weknora skill snapshot",
Comment: comment,
Changes: []string{
"LABEL " + dockerSkillSnapshotLabel + "=true",
"LABEL " + dockerSkillSnapshotSourceLabel + "=" + id,
"LABEL " + label + "=true",
"LABEL " + sourceLabel + "=" + sandboxID,
},
})
if err != nil {
return RemoteSnapshotRef{}, dockerError("CreateSnapshot", err)
return RemoteSnapshotRef{}, dockerError(op, err)
}
if strings.TrimSpace(committed.ID) == "" {
return RemoteSnapshotRef{}, dockerInvalidRequest(
"CreateSnapshot", "provider returned an empty snapshot ID")
return RemoteSnapshotRef{}, dockerInvalidRequest(op, "provider returned an empty snapshot ID")
}
return RemoteSnapshotRef{
ID: dockerCanonicalSnapshotID(reference),
@ -86,7 +129,11 @@ func (c *DockerRemoteClient) DeleteSnapshot(ctx context.Context, snapshotID stri
}
return normalized
}
c.pruneDanglingSkillImages(ctx)
if dockerIsForkSnapshotRef(id) {
c.pruneDanglingForkImages(ctx)
} else {
c.pruneDanglingSkillImages(ctx)
}
return nil
}
@ -119,6 +166,29 @@ func (c *DockerRemoteClient) pruneDanglingSkillImages(ctx context.Context) {
}
}
// pruneDanglingForkImages drops untagged fork-snapshot images. Same rationale
// as pruneDanglingSkillImages; the filter is the fork label so a skill delete
// cannot sweep a live fork image and vice versa.
func (c *DockerRemoteClient) pruneDanglingForkImages(ctx context.Context) {
listed, err := c.api.ImageList(ctx, client.ImageListOptions{
All: true,
Filters: client.Filters{}.Add("label", dockerForkSnapshotLabel+"=true"),
})
if err != nil {
return
}
for _, item := range listed.Items {
if !dockerImageIsForkSnapshot(item) || dockerImageHasTag(item) {
continue
}
id := strings.TrimSpace(item.ID)
if id == "" {
continue
}
_, _ = c.api.ImageRemove(ctx, id, client.ImageRemoveOptions{PruneChildren: true})
}
}
func dockerImageHasTag(item image.Summary) bool {
for _, tag := range item.RepoTags {
if strings.TrimSpace(tag) != "" && tag != "<none>:<none>" {
@ -169,9 +239,33 @@ func dockerImageIsSkillSnapshot(item image.Summary) bool {
return false
}
func dockerImageIsForkSnapshot(item image.Summary) bool {
if item.Labels[dockerForkSnapshotLabel] == "true" {
return true
}
for _, tag := range item.RepoTags {
if dockerIsForkSnapshotRef(tag) {
return true
}
}
return false
}
func dockerIsSkillSnapshotRef(ref string) bool {
return dockerIsRepoSnapshotRef(ref, dockerSkillSnapshotRepo)
}
func dockerIsForkSnapshotRef(ref string) bool {
return dockerIsRepoSnapshotRef(ref, DockerForkSnapshotRepo)
}
func dockerIsLocalSnapshotRef(ref string) bool {
return dockerIsSkillSnapshotRef(ref) || dockerIsForkSnapshotRef(ref)
}
func dockerIsRepoSnapshotRef(ref, repo string) bool {
trimmed := strings.TrimSpace(ref)
prefix := dockerSkillSnapshotRepo + "/"
prefix := repo + "/"
if strings.HasPrefix(trimmed, prefix) {
return true
}
@ -204,15 +298,15 @@ func dockerCanonicalSnapshotID(ref string) string {
return strings.TrimSuffix(trimmed, ":latest")
}
func dockerSkillSnapshotReference(name, sandboxID string) (string, error) {
func dockerSnapshotReference(repo, name, sandboxID, op string) (string, error) {
base := dockerSanitizeImageName(name)
if base == "" {
base = dockerSanitizeImageName(sandboxID)
}
if base == "" {
return "", dockerInvalidRequest("CreateSnapshot", "snapshot name is required")
return "", dockerInvalidRequest(op, "snapshot name is required")
}
return dockerSkillSnapshotRepo + "/" + base, nil
return repo + "/" + base, nil
}
// dockerSanitizeImageName maps an install-generated snapshot name onto a
@ -240,3 +334,5 @@ func dockerSanitizeImageName(raw string) string {
}
return out
}
var _ forkSnapshotCreator = (*DockerRemoteClient)(nil)

View File

@ -129,6 +129,41 @@ func TestDockerDeleteSnapshotSweepsUntaggedSkillImages(t *testing.T) {
"the sweep must take the untagged snapshot and nothing that is still named")
}
func TestDockerDeleteSnapshotSweepsUntaggedForkImages(t *testing.T) {
engine := newFakeDockerEngine()
engine.images = []image.Summary{
{
ID: "sha256:retired-fork",
RepoTags: []string{DockerForkSnapshotRepo + "/fork-a:latest"},
Labels: map[string]string{dockerForkSnapshotLabel: "true"},
},
{
ID: "sha256:orphan-fork",
RepoTags: []string{"<none>:<none>"},
Labels: map[string]string{dockerForkSnapshotLabel: "true"},
},
{
ID: "sha256:orphan-skill",
RepoTags: []string{"<none>:<none>"},
Labels: map[string]string{dockerSkillSnapshotLabel: "true"},
},
{
ID: "sha256:live-fork",
RepoTags: []string{DockerForkSnapshotRepo + "/fork-b:latest"},
Labels: map[string]string{dockerForkSnapshotLabel: "true"},
},
}
docker := newTestDockerClient(t, engine)
require.NoError(t, docker.DeleteSnapshot(
context.Background(), DockerForkSnapshotRepo+"/fork-a"))
require.Equal(t,
[]string{DockerForkSnapshotRepo + "/fork-a", "sha256:orphan-fork"},
engine.removedImages,
"a fork delete must not sweep skill images")
}
func TestDockerDeleteSnapshotSweepFailureIsNotAnError(t *testing.T) {
engine := newFakeDockerEngine()
engine.images = []image.Summary{
@ -181,6 +216,77 @@ func TestDockerCreateDoesNotPullAMissingSkillSnapshot(t *testing.T) {
"a local commit must not be fetched from a registry")
}
func TestDockerCreateForkSnapshotTagsAForkImage(t *testing.T) {
engine := newFakeDockerEngine()
docker := newTestDockerClient(t, engine)
ref, err := docker.CreateForkSnapshot(context.Background(), "container-1", "fork-session-a-1")
require.NoError(t, err)
require.Equal(t, DockerForkSnapshotRepo+"/fork-session-a-1", ref.ID)
require.Len(t, engine.committed, 1)
require.Equal(t, DockerForkSnapshotRepo+"/fork-session-a-1", engine.committed[0].Reference)
require.Equal(t, "weknora fork snapshot", engine.committed[0].Comment)
require.False(t, engine.committed[0].NoPause,
"the Engine must pause the container for the duration of the commit")
require.Contains(t, engine.committed[0].Changes, "LABEL "+dockerForkSnapshotLabel+"=true")
require.Contains(t, engine.committed[0].Changes,
"LABEL "+dockerForkSnapshotSourceLabel+"=container-1")
}
func TestDockerListTemplatesHidesForkSnapshots(t *testing.T) {
engine := newFakeDockerEngine()
engine.images = []image.Summary{
{
ID: "sha256:base",
RepoTags: []string{"weknora/sandbox:test"},
Labels: map[string]string{dockerTemplateLabel: "true"},
},
{
ID: "sha256:fork",
RepoTags: []string{DockerForkSnapshotRepo + "/fork-session-a-1:latest"},
Labels: map[string]string{dockerForkSnapshotLabel: "true"},
},
{
ID: "sha256:fork-tag-only",
RepoTags: []string{DockerForkSnapshotRepo + "/untagged-label:latest"},
},
}
docker := newTestDockerClient(t, engine)
templates, err := docker.ListTemplates(context.Background())
require.NoError(t, err)
require.Len(t, templates, 1)
require.Equal(t, "weknora/sandbox:test", templates[0].ID)
}
func TestDockerListSnapshotsExcludesForkImages(t *testing.T) {
engine := newFakeDockerEngine()
docker := newTestDockerClient(t, engine)
ctx := context.Background()
_, err := docker.CreateSnapshot(ctx, "container-1", "weknora-sk-cfg1-g1")
require.NoError(t, err)
_, err = docker.CreateForkSnapshot(ctx, "container-1", "fork-session-a-1")
require.NoError(t, err)
listed, err := docker.ListSnapshots(ctx, "")
require.NoError(t, err)
require.Len(t, listed, 1)
require.Equal(t, "weknora-skill/weknora-sk-cfg1-g1", listed[0].ID)
}
func TestDockerCreateDoesNotPullAMissingForkSnapshot(t *testing.T) {
engine := newFakeDockerEngine()
docker := newTestDockerClient(t, engine)
_, err := docker.Create(context.Background(), RemoteCreateRequest{
TemplateID: DockerForkSnapshotRepo + "/fork-session-a-1",
})
require.True(t, IsRemoteInvalidRequest(err), err)
require.Empty(t, engine.pulled,
"a local fork commit must not be fetched from a registry")
}
func TestDockerSanitizeImageName(t *testing.T) {
require.Equal(t, "weknora-sk-cfg1-g1", dockerSanitizeImageName("weknora-sk-cfg1-g1"))
require.Equal(t, "abc-def", dockerSanitizeImageName("ABC_DEF"))

View File

@ -11,8 +11,9 @@
// nothing to do with sandboxes. Listing all of them would bury the one the
// admin needs, so the catalog only reports images that are recognisably
// sandbox templates.
// - Skill snapshots live in the same image store (weknora-skill/…), so they
// are subtracted the way Cube hides snap- IDs from GET /templates.
// - Skill and fork snapshots live in the same image store (weknora-skill/…
// and weknora-fork/…), so they are subtracted the way Cube hides snap- IDs
// from GET /templates.
// - Making the standard template exist means pulling, which can take minutes
// on a cold host. The pull therefore runs in the background and the
// template reports "building" until it lands, mirroring how the other
@ -58,14 +59,15 @@ func (c *DockerRemoteClient) ListTemplates(ctx context.Context) ([]RemoteTemplat
configured := strings.TrimSpace(c.settings.Image)
configuredPresent := false
for _, image := range listed.Items {
snapshot := dockerImageIsSkillSnapshot(image)
snapshot := dockerImageIsSkillSnapshot(image) || dockerImageIsForkSnapshot(image)
for _, tag := range image.RepoTags {
if tag == "" || tag == "<none>:<none>" {
continue
}
// Skill snapshots are images, so they would otherwise appear in
// the "pick a base template" list the way Cube's snap- IDs used
// to. Hide them unless this config's stored image is that tag.
// Skill and fork snapshots are images, so they would otherwise
// appear in the "pick a base template" list the way Cube's snap-
// IDs used to. Hide them unless this config's stored image is
// that tag.
if snapshot && tag != configured {
continue
}

View File

@ -251,6 +251,7 @@ func newE2BIntegrationLifecycle(
createRequest,
time.Minute,
"",
nil,
)
if err != nil {
t.Fatalf("newRemoteSessionLifecycle: %v", err)

View File

@ -67,7 +67,22 @@ func rpcUsesCallerDeadline(path string) bool {
if strings.HasPrefix(path, "/process.Process/") {
return true
}
return isFilesystemContentRPC(path)
if isFilesystemContentRPC(path) {
return true
}
return isCubeSandboxSnapshotRPC(path)
}
// isCubeSandboxSnapshotRPC reports POST /sandboxes/{id}/snapshots. Cube pauses
// the live MicroVM and copies its disk; that exceeds CubeHTTPTimeout (30s).
func isCubeSandboxSnapshotRPC(path string) bool {
const prefix = "/sandboxes/"
const suffix = "/snapshots"
if !strings.HasPrefix(path, prefix) || !strings.HasSuffix(path, suffix) {
return false
}
id := strings.TrimSuffix(strings.TrimPrefix(path, prefix), suffix)
return id != "" && !strings.Contains(id, "/")
}
func isFilesystemContentRPC(path string) bool {

View File

@ -106,6 +106,7 @@ func TestFileTransferSkipsShortHTTPTimeout(t *testing.T) {
assertBudget(t, cube, "/filesystem.Filesystem/WriteFile", false)
assertBudget(t, cube, "/filesystem.Filesystem/MakeDir", true)
assertBudget(t, cube, "/process.Process/Start", false)
assertBudget(t, cube, "/sandboxes/sbx-1/snapshots", false)
assertBudget(t, e2b, "/files", false)
assertBudget(t, e2b, "/filesystem.Filesystem/Read", false)
assertBudget(t, e2b, "/filesystem.Filesystem/MakeDir", true)

View File

@ -17,7 +17,8 @@ const sandboxSpanPreviewRunes = 256
// the caller has no parent trace.
//
// Snapshot capability is forwarded: wrapping must not hide RemoteSnapshotManager
// from SnapshotManagerFrom.
// from SnapshotManagerFrom, and CreateForkSnapshot must still reach Docker's
// fork namespace.
func wrapLangfuseRemoteClient(inner RemoteSandboxClient) RemoteSandboxClient {
if inner == nil {
return nil
@ -208,6 +209,29 @@ func (c *langfuseSnapshotClient) CreateSnapshot(
return ref, err
}
func (c *langfuseSnapshotClient) CreateForkSnapshot(
ctx context.Context, sandboxID string, name string,
) (RemoteSnapshotRef, error) {
if creator, ok := c.inner.(forkSnapshotCreator); ok {
ctx, span := startSandboxSpan(ctx, "sandbox.create_fork_snapshot", map[string]interface{}{
"sandbox_id": sandboxID,
"name": name,
}, nil)
ref, err := creator.CreateForkSnapshot(ctx, sandboxID, name)
span.Finish(map[string]interface{}{"snapshot_id": ref.ID}, nil, err)
return ref, err
}
inner, ok := c.inner.(RemoteSnapshotManager)
if !ok {
return RemoteSnapshotRef{}, &RemoteError{
Kind: RemoteErrorKindUnsupported,
Op: "CreateForkSnapshot",
Message: "inner client has no snapshot manager",
}
}
return inner.CreateSnapshot(ctx, sandboxID, name)
}
func (c *langfuseSnapshotClient) DeleteSnapshot(ctx context.Context, snapshotID string) error {
inner, ok := c.inner.(RemoteSnapshotManager)
if !ok {
@ -347,6 +371,7 @@ func (c *langfuseRemoteClient) StartDesktopTTLRefresh(ctx context.Context, handl
var (
_ RemoteSandboxClient = (*langfuseRemoteClient)(nil)
_ RemoteSnapshotManager = (*langfuseSnapshotClient)(nil)
_ forkSnapshotCreator = (*langfuseSnapshotClient)(nil)
_ RemoteTerminalManager = (*langfuseRemoteClient)(nil)
_ RemoteDesktopManager = (*langfuseRemoteClient)(nil)
_ RemoteDesktopTTLRefresher = (*langfuseRemoteClient)(nil)

View File

@ -23,6 +23,21 @@ func TestWrapLangfuseRemoteClientPreservesSnapshotCapability(t *testing.T) {
require.NotEmpty(t, ref.ID)
}
func TestWrapLangfuseRemoteClientPreservesForkSnapshotCapability(t *testing.T) {
inner := newFakeRemoteClient(SandboxTypeCube)
inner.capabilities.SupportsSnapshots = true
client := &recordingForkSnapshotClient{fakeRemoteClient: inner}
wrapped := wrapLangfuseRemoteClient(client)
creator, ok := wrapped.(forkSnapshotCreator)
require.True(t, ok, "wrapping must not hide CreateForkSnapshot")
ref, err := creator.CreateForkSnapshot(context.Background(), "sb-1", "fork-1")
require.NoError(t, err)
require.Equal(t, "fork-sb-1", ref.ID)
require.Equal(t, 1, client.forkCalls)
}
func TestWrapLangfuseRemoteClientDoesNotInventSnapshotSupport(t *testing.T) {
inner := &noSnapshotClient{}
wrapped := wrapLangfuseRemoteClient(inner)

View File

@ -212,7 +212,14 @@ func snapshotInUseBySandboxes(message string) bool {
if strings.Contains(msg, "sandboxes using") {
return true
}
return strings.Contains(msg, "cannot delete template") && strings.Contains(msg, "using it")
if strings.Contains(msg, "cannot delete template") && strings.Contains(msg, "using it") {
return true
}
// Cube CoW: HTTP 500 / 130409 while source + child sandboxes still reference the snapshot.
if strings.Contains(msg, "runtime ref") {
return true
}
return strings.Contains(msg, "130409")
}
// IsRemoteDirAlreadyExists reports whether MakeDir failed because the

View File

@ -230,6 +230,14 @@ func TestSnapshotDeleteKindPromotesInUseToConflict(t *testing.T) {
msg: "cannot delete template x because there are sandboxes using it",
want: RemoteErrorKindConflict,
},
{
name: "cube 130409 runtime refs as 500",
op: "DeleteSnapshot",
kind: RemoteErrorKindInternal,
msg: "unavailable: CubeMaster returned error code 130409: template attempt is already in progress: " +
"snapshot snap-6a6707d7b51246c68ad643ee still has 2 active runtime ref(s): a@host, b@host (HTTP 500)",
want: RemoteErrorKindConflict,
},
{
name: "already conflict stays conflict",
op: "DeleteSnapshot",

View File

@ -61,12 +61,14 @@ type fakeRemoteClient struct {
nextID int
sandboxes map[string]*fakeRemoteRecord
createCount int
connectIDs []string
connects []RemoteConnectRequest
getIDs []string
deleteIDs []string
listCount int
createCount int
connectIDs []string
connects []RemoteConnectRequest
getIDs []string
deleteIDs []string
listCount int
lastCreateRequest RemoteCreateRequest
lastCreatedID string
trafficAccessToken string
@ -181,6 +183,8 @@ func (c *fakeRemoteClient) Create(
c.mu.Lock()
c.nextID++
id := fmt.Sprintf("%s-%d", c.provider, c.nextID)
c.lastCreateRequest = req
c.lastCreatedID = id
record := &fakeRemoteRecord{
id: id,
templateID: req.TemplateID,

View File

@ -0,0 +1,53 @@
package sandbox
import "context"
// SessionBootstrapper customises how ONE session's first sandbox is created.
// It exists for session fork: a forked session boots from a snapshot of its
// parent's sandbox and then rolls /workspace back to the fork point.
//
// It is optional. A nil bootstrapper leaves the lifecycle's behaviour
// unchanged, which is what every ordinary session gets.
//
// The lifecycle calls both methods inside the per-session lifecycle lock, so
// implementations need no locking of their own and cannot race with a
// concurrent resolve of the same session.
type SessionBootstrapper interface {
// TemplateOverride returns a template ID to create this session's sandbox
// from instead of the config's. An empty string means "no override".
//
// An error aborts the create: an implementation that cannot tell whether
// an override applies must not be silently treated as "no override",
// because that would boot a plain sandbox for a session the user expects
// to carry forked state.
TemplateOverride(ctx context.Context, key SessionSandboxKey) (string, error)
// AfterCreate runs once, immediately after the binding is written.
//
// Returning an error makes the lifecycle destroy the sandbox and delete
// the binding. That severity is deliberate: a half-bootstrapped fork looks
// completely normal but has the wrong baseline, and that silent wrongness
// is far worse than an honest failure the next resolve can retry from a
// clean slate.
AfterCreate(ctx context.Context, key SessionSandboxKey, handle RemoteSandboxHandle) error
}
// SessionCreateFailureHandler is an optional SessionBootstrapper extension.
//
// AfterCreate only runs when Create succeeded. A fork snapshot that the
// provider will never boot (deleted, unknown template) would otherwise stay
// on the session forever: every Resolve retries the same dead ID. The
// lifecycle calls this when Create used a TemplateOverride and still failed,
// so the bootstrapper can retire that snapshot and let the next Resolve use
// the ordinary template.
type SessionCreateFailureHandler interface {
OnCreateFailed(ctx context.Context, key SessionSandboxKey, createErr error)
}
// SessionBootstrapperWithClient rebinds a bootstrapper to the client that
// created the sandbox handle. AfterCreate runs under the session lifecycle
// lock, which is not reentrant, so implementations must talk to `client`
// (and the handle) directly instead of calling Resolve.
type SessionBootstrapperWithClient interface {
WithClient(client RemoteSandboxClient) SessionBootstrapper
}

View File

@ -0,0 +1,188 @@
package sandbox
import (
"context"
"errors"
"testing"
"github.com/stretchr/testify/require"
)
var testSessionKey = SessionSandboxKey{TenantID: 1, SessionID: "session-bootstrap"}
type recordingBootstrapper struct {
override string
overrideErr error
afterErr error
afterCalls int
afterHandleID string
}
func (b *recordingBootstrapper) TemplateOverride(
context.Context, SessionSandboxKey,
) (string, error) {
return b.override, b.overrideErr
}
func (b *recordingBootstrapper) AfterCreate(
_ context.Context, _ SessionSandboxKey, handle RemoteSandboxHandle,
) error {
b.afterCalls++
if handle != nil {
b.afterHandleID = handle.ID()
}
return b.afterErr
}
func newLifecycleForTest(t *testing.T) (*remoteSessionLifecycle, *fakeRemoteClient, SessionSandboxBindingStore) {
t.Helper()
client := newFakeRemoteClient(SandboxTypeCube)
store := NewMemorySessionSandboxBindingStore()
lc := newTestRemoteSessionLifecycle(
t, client, store, &fakeSessionExistenceChecker{exists: true},
)
return lc, client, store
}
func TestCreateAndBindUsesTemplateOverride(t *testing.T) {
lc, client, _ := newLifecycleForTest(t)
lc.bootstrapper = &recordingBootstrapper{override: "snap-1"}
_, err := lc.Resolve(context.Background(), testSessionKey)
require.NoError(t, err)
require.Equal(t, "snap-1", client.lastCreateRequest.TemplateID)
}
func TestCreateAndBindKeepsConfigTemplateWithoutOverride(t *testing.T) {
lc, client, _ := newLifecycleForTest(t)
lc.bootstrapper = &recordingBootstrapper{override: ""}
_, err := lc.Resolve(context.Background(), testSessionKey)
require.NoError(t, err)
require.Equal(t, lc.createRequest.TemplateID, client.lastCreateRequest.TemplateID)
}
// 最重要的一条:override 绝不能污染跨 session 复用的 l.createRequest。
func TestTemplateOverrideDoesNotMutateSharedCreateRequest(t *testing.T) {
lc, _, _ := newLifecycleForTest(t)
baseTemplate := lc.createRequest.TemplateID
lc.bootstrapper = &recordingBootstrapper{override: "snap-1"}
_, err := lc.Resolve(context.Background(), testSessionKey)
require.NoError(t, err)
require.Equal(t, baseTemplate, lc.createRequest.TemplateID,
"共享的 createRequest 被改了,同 config 下其他会话会从别人的快照启动")
}
func TestAfterCreateRunsWithTheNewHandle(t *testing.T) {
lc, _, _ := newLifecycleForTest(t)
b := &recordingBootstrapper{override: "snap-1"}
lc.bootstrapper = b
handle, err := lc.Resolve(context.Background(), testSessionKey)
require.NoError(t, err)
require.Equal(t, 1, b.afterCalls)
require.Equal(t, handle.ID(), b.afterHandleID)
}
// 全有或全无:引导失败必须销毁沙箱并删掉 binding,否则用户会在一个
// 「文件系统停在分叉时刻而不是分叉点」的沙箱里干活。
func TestAfterCreateFailureDestroysSandboxAndBinding(t *testing.T) {
lc, client, store := newLifecycleForTest(t)
lc.bootstrapper = &recordingBootstrapper{override: "snap-1", afterErr: errors.New("git reset failed")}
_, err := lc.Resolve(context.Background(), testSessionKey)
require.Error(t, err)
require.Contains(t, client.deleteIDs, client.lastCreatedID)
binding, getErr := store.Get(context.Background(), testSessionKey)
require.NoError(t, getErr)
require.Nil(t, binding, "引导失败后不得留下 binding")
}
func TestTemplateOverrideErrorAbortsCreate(t *testing.T) {
lc, client, _ := newLifecycleForTest(t)
lc.bootstrapper = &recordingBootstrapper{overrideErr: errors.New("db down")}
_, err := lc.Resolve(context.Background(), testSessionKey)
require.Error(t, err)
require.Empty(t, client.lastCreatedID, "读不到 override 就不该建沙箱")
}
type recordingCreateFailureHandler struct {
recordingBootstrapper
failedCalls int
lastFailErr error
}
func (b *recordingCreateFailureHandler) OnCreateFailed(_ context.Context, _ SessionSandboxKey, err error) {
b.failedCalls++
b.lastFailErr = err
}
func TestNilBootstrapperIsANoOp(t *testing.T) {
lc, client, _ := newLifecycleForTest(t)
lc.bootstrapper = nil
_, err := lc.Resolve(context.Background(), testSessionKey)
require.NoError(t, err)
require.Equal(t, lc.createRequest.TemplateID, client.lastCreateRequest.TemplateID)
}
// A missing fork snapshot must not be retried forever. Create using the
// override failed, so the bootstrapper has to be told — AfterCreate never
// runs, and abandon on git-reset-failure cannot fire.
func TestCreateFailureWithOverrideNotifiesBootstrapper(t *testing.T) {
lc, client, _ := newLifecycleForTest(t)
handler := &recordingCreateFailureHandler{
recordingBootstrapper: recordingBootstrapper{override: "snap-1"},
}
lc.bootstrapper = handler
client.createErr = NewRemoteError(
SandboxTypeCube, "Create", RemoteErrorKindNotFound, "template gone", nil,
)
_, err := lc.Resolve(context.Background(), testSessionKey)
require.Error(t, err)
require.Equal(t, 1, handler.failedCalls)
require.True(t, IsRemoteNotFound(handler.lastFailErr))
require.Empty(t, client.lastCreatedID)
}
func TestCreateFailureWithoutOverrideDoesNotNotifyBootstrapper(t *testing.T) {
lc, client, _ := newLifecycleForTest(t)
handler := &recordingCreateFailureHandler{}
lc.bootstrapper = handler
client.createErr = NewRemoteError(
SandboxTypeCube, "Create", RemoteErrorKindNotFound, "template gone", nil,
)
_, err := lc.Resolve(context.Background(), testSessionKey)
require.Error(t, err)
require.Zero(t, handler.failedCalls)
}
func TestTransientCreateFailureWithOverrideStillNotifiesBootstrapper(t *testing.T) {
lc, client, _ := newLifecycleForTest(t)
handler := &recordingCreateFailureHandler{
recordingBootstrapper: recordingBootstrapper{override: "snap-1"},
}
lc.bootstrapper = handler
client.createErr = NewRemoteError(
SandboxTypeCube, "Create", RemoteErrorKindUnavailable, "provider down", nil,
)
_, err := lc.Resolve(context.Background(), testSessionKey)
require.Error(t, err)
require.Equal(t, 1, handler.failedCalls)
}

View File

@ -44,6 +44,10 @@ type remoteSessionLifecycle struct {
cleanupTimeout time.Duration
sandboxConfigID string
now func() time.Time
// bootstrapper customises the first create of individual sessions
// (session fork). Optional; nil keeps the default behaviour.
bootstrapper SessionBootstrapper
}
func newRemoteSessionLifecycle(
@ -53,6 +57,7 @@ func newRemoteSessionLifecycle(
createRequest RemoteCreateRequest,
cleanupTimeout time.Duration,
sandboxConfigID string,
bootstrapper SessionBootstrapper,
) (*remoteSessionLifecycle, error) {
if client == nil {
return nil, errors.New("remote sandbox client is required")
@ -88,6 +93,7 @@ func newRemoteSessionLifecycle(
cleanupTimeout: cleanupTimeout,
sandboxConfigID: sandboxConfigID,
now: time.Now,
bootstrapper: bootstrapper,
}, nil
}
@ -437,6 +443,11 @@ func (l *remoteSessionLifecycle) createAndBind(
ctx context.Context,
key SessionSandboxKey,
) (RemoteSandboxHandle, error) {
// 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
// sessions boot from another session's fork snapshot — a failure that
// reproduces only under specific interleavings and is brutal to diagnose.
request := l.createRequest
request.Metadata = nil
if l.client.Capabilities().SupportsMetadata {
@ -450,8 +461,23 @@ func (l *remoteSessionLifecycle) createAndBind(
}
request.EnvVars = cloneMetadata(l.createRequest.EnvVars)
usedOverride := false
if l.bootstrapper != nil {
override, err := l.bootstrapper.TemplateOverride(ctx, key)
if err != nil {
return nil, fmt.Errorf("resolve session template override: %w", err)
}
if strings.TrimSpace(override) != "" {
request.TemplateID = override
usedOverride = true
}
}
handle, err := l.client.Create(ctx, request)
if err != nil {
if usedOverride {
l.notifyCreateFailed(ctx, key, err)
}
return nil, fmt.Errorf("create remote sandbox: %w", err)
}
if err := l.validateHandle(handle, ""); err != nil {
@ -497,6 +523,9 @@ func (l *remoteSessionLifecycle) createAndBind(
)
}
if created {
if err := l.runBootstrap(ctx, key, handle); err != nil {
return nil, err
}
return handle, nil
}
@ -520,6 +549,43 @@ func (l *remoteSessionLifecycle) createAndBind(
return l.connectKnownWinner(ctx, *winner)
}
// runBootstrap applies the session bootstrapper to a freshly bound sandbox.
//
// Failure is all-or-nothing: the sandbox is destroyed and the binding deleted
// so the next resolve starts from a clean slate. Leaving a half-bootstrapped
// sandbox in place would hand the user an environment that looks right and is
// not.
func (l *remoteSessionLifecycle) runBootstrap(
ctx context.Context, key SessionSandboxKey, handle RemoteSandboxHandle,
) error {
if l.bootstrapper == nil {
return nil
}
bootstrapErr := l.bootstrapper.AfterCreate(ctx, key, handle)
if bootstrapErr == nil {
return nil
}
// Use a cancellation-immune context: the caller may already be gone, and
// abandoning the rollback would leak both a sandbox and a wrong binding.
cleanupCtx := context.WithoutCancel(ctx)
if _, delErr := l.bindings.DeleteIfMatch(
cleanupCtx, key, l.client.Provider(), handle.ID(),
); delErr != nil {
return errors.Join(bootstrapErr, fmt.Errorf("delete binding after failed bootstrap: %w", delErr))
}
return errors.Join(bootstrapErr, l.cleanupCreated(cleanupCtx, handle))
}
func (l *remoteSessionLifecycle) notifyCreateFailed(
ctx context.Context, key SessionSandboxKey, createErr error,
) {
handler, ok := l.bootstrapper.(SessionCreateFailureHandler)
if !ok {
return
}
handler.OnCreateFailed(context.WithoutCancel(ctx), key, createErr)
}
func (l *remoteSessionLifecycle) connectWinner(
ctx context.Context,
key SessionSandboxKey,

View File

@ -177,6 +177,7 @@ func newTestRemoteSessionLifecycle(
},
time.Second,
"",
nil,
)
require.NoError(t, err)
return lifecycle
@ -542,6 +543,7 @@ func newTestRemoteSessionLifecycleWithPolicy(
},
time.Second,
"",
nil,
)
require.NoError(t, err)
return lifecycle
@ -1181,6 +1183,7 @@ func newLifecycleFixture(t *testing.T) *lifecycleFixture {
RemoteCreateRequest{TemplateID: "template-a"},
time.Minute,
"cfg-1",
nil,
)
require.NoError(t, err)
return &lifecycleFixture{
@ -1348,6 +1351,7 @@ func newTestLifecycleWithConfigID(t *testing.T, configID string) *remoteSessionL
RemoteCreateRequest{TemplateID: "template-a"},
time.Minute,
configID,
nil,
)
require.NoError(t, err)
return lifecycle

View File

@ -109,6 +109,10 @@ type SessionBoundManagerConfig struct {
// Set by the per-tenant resolver, which builds a manager per request.
// See NewSessionBoundManager.
SkipHealthProbe bool
// Bootstrapper customises the first sandbox create of individual sessions
// (session fork). Optional: nil is the ordinary path.
Bootstrapper SessionBootstrapper
}
// NewSessionBoundManager wires the manager with an explicit RemoteSandboxClient
@ -173,6 +177,11 @@ func NewSessionBoundManager(deps SessionBoundManagerConfig) (*SessionBoundManage
client := wrapLangfuseRemoteClient(deps.Client)
bootstrapper := deps.Bootstrapper
if withClient, ok := bootstrapper.(SessionBootstrapperWithClient); ok {
bootstrapper = withClient.WithClient(client)
}
lifecycle, err := newRemoteSessionLifecycle(
client,
deps.Store,
@ -180,6 +189,7 @@ func NewSessionBoundManager(deps SessionBoundManagerConfig) (*SessionBoundManage
createRequest,
sessionLifecycleCleanupTimeout,
deps.ConfigID,
bootstrapper,
)
if err != nil {
return nil, fmt.Errorf("session bound manager: %w", err)
@ -445,6 +455,14 @@ func (m *SessionBoundManager) DeleteSnapshot(ctx context.Context, snapshotID str
return snapshots.DeleteSnapshot(ctx, snapshotID)
}
// DeleteForkSnapshot removes a fork snapshot. sessionID is accepted so the
// method matches SessionForkSandboxPort; deletion is by snapshot ID.
func (m *SessionBoundManager) DeleteForkSnapshot(
ctx context.Context, _ /* sessionID */, snapshotID string,
) error {
return m.DeleteSnapshot(ctx, snapshotID)
}
// ListSnapshots forwards provider snapshot listing for audit and later cleanup
// tasks.
func (m *SessionBoundManager) ListSnapshots(
@ -1021,6 +1039,72 @@ func (m *SessionBoundManager) EndSessionTurn(ctx context.Context, sessionID stri
return leaser.EndTurn(context.WithoutCancel(ctx), key)
}
// HasActiveTurn reports whether an agent turn currently holds the session's
// sandbox lease. A store without turn-lease support is treated as not busy
// so fork can proceed.
func (m *SessionBoundManager) HasActiveTurn(ctx context.Context, sessionID string) (bool, error) {
if m == nil {
return false, nil
}
leaser, ok := m.bindings.(sessionTurnLeaseStore)
if !ok {
return false, nil
}
key, err := m.sessionKey(ctx, sessionID)
if err != nil {
return false, err
}
active, _, err := leaser.TurnState(ctx, key)
return active, err
}
// CreateForkSnapshot snapshots the session's already-bound sandbox. It never
// provisions: an unbound session or a backend without snapshots returns an
// error so fork can degrade.
func (m *SessionBoundManager) CreateForkSnapshot(
ctx context.Context, sessionID, name string,
) (string, error) {
if err := m.requireRemoteBackend(); err != nil {
return "", err
}
snapshots, ok := SnapshotManagerFrom(m.client)
if !ok || !m.client.Capabilities().SupportsSnapshots {
return "", errors.New("sandbox: remote provider does not support snapshots")
}
sandboxID, bound := m.BoundSandboxID(ctx, sessionID)
if !bound || sandboxID == "" {
return "", errors.New("sandbox: session has no bound sandbox")
}
ref, err := createForkOrProviderSnapshot(ctx, m.client, snapshots, sandboxID, name)
if err != nil {
return "", err
}
id := strings.TrimSpace(ref.ID)
if id == "" {
return "", errors.New("sandbox: snapshot returned empty id")
}
return id, nil
}
type forkSnapshotCreator interface {
CreateForkSnapshot(ctx context.Context, sandboxID, name string) (RemoteSnapshotRef, error)
}
// createForkOrProviderSnapshot uses a fork-specific commit when the client
// has one (Docker's weknora-fork/ namespace). Cube and E2B have no extra
// namespace, so they keep using CreateSnapshot.
func createForkOrProviderSnapshot(
ctx context.Context,
client RemoteSandboxClient,
snapshots RemoteSnapshotManager,
sandboxID, name string,
) (RemoteSnapshotRef, error) {
if creator, ok := client.(forkSnapshotCreator); ok {
return creator.CreateForkSnapshot(ctx, sandboxID, name)
}
return snapshots.CreateSnapshot(ctx, sandboxID, name)
}
var _ SessionTurnHolder = (*SessionBoundManager)(nil)
// resolveSession resolves (or lazily creates) the remote sandbox bound to
@ -1084,6 +1168,33 @@ func (m *SessionBoundManager) peekBoundSandboxState(
return RemoteStateUnknown, true, nil
}
// BoundSandboxID returns the ID of the sandbox currently bound to sessionID.
// It never provisions and never Connects: a session with no live binding
// reports ok=false, which callers treat as "nothing to check point".
func (m *SessionBoundManager) BoundSandboxID(
ctx context.Context, sessionID string,
) (string, bool) {
if m.remoteDisabled() || strings.TrimSpace(sessionID) == "" {
return "", false
}
key, err := m.sessionKey(ctx, sessionID)
if err != nil {
return "", false
}
binding, err := m.bindings.Get(ctx, key)
if err != nil {
return "", false
}
if binding == nil || binding.Provider != m.client.Provider() {
return "", false
}
sandboxID := strings.TrimSpace(binding.SandboxID)
if sandboxID == "" {
return "", false
}
return sandboxID, true
}
// lookupSessionHandle reads the authoritative binding and, when one exists
// with the current provider, connects to the remote sandbox without
// allocating. Used by artifact / staging paths that must never provision.

View File

@ -2,6 +2,7 @@ package sandbox
import (
"context"
"errors"
"strings"
"testing"
"time"
@ -548,3 +549,323 @@ func TestOpenSessionDesktopUnsupportedBackend(t *testing.T) {
_, err := mgr.OpenSessionDesktop(context.Background(), "sess-1", RemoteDesktopOptions{})
require.ErrorIs(t, err, ErrDesktopUnsupported)
}
func TestBoundSandboxIDReadsBindingWithoutConnect(t *testing.T) {
client := newFakeRemoteClient(SandboxTypeCube)
store := NewMemorySessionSandboxBindingStore()
cfg := DefaultConfig()
cfg.CubeTemplate = "tpl-test"
mgr, err := NewSessionBoundManager(SessionBoundManagerConfig{
Config: cfg,
Client: client,
Store: store,
Checker: &fakeSessionExistenceChecker{exists: true},
SkipHealthProbe: true,
})
require.NoError(t, err)
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(10000))
key := SessionSandboxKey{TenantID: 10000, SessionID: "session-a"}
created, err := store.Create(ctx, key, validSessionSandboxBinding(key, "sbx-existing"))
require.NoError(t, err)
require.True(t, created)
id, ok := mgr.BoundSandboxID(ctx, "session-a")
require.True(t, ok)
require.Equal(t, "sbx-existing", id)
client.mu.Lock()
connects := append([]string(nil), client.connectIDs...)
client.mu.Unlock()
require.Empty(t, connects, "BoundSandboxID must not Connect")
}
func TestBoundSandboxIDReportsUnbound(t *testing.T) {
mgr, client := newSessionManagerExecTestHarness(t)
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(10000))
id, ok := mgr.BoundSandboxID(ctx, "session-a")
require.False(t, ok)
require.Empty(t, id)
client.mu.Lock()
connects := append([]string(nil), client.connectIDs...)
client.mu.Unlock()
require.Empty(t, connects)
}
func TestHasActiveTurnReportsLeaseState(t *testing.T) {
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(10000))
store := NewMemorySessionSandboxBindingStore()
cfg := DefaultConfig()
cfg.CubeTemplate = "tpl-test"
mgr, err := NewSessionBoundManager(SessionBoundManagerConfig{
Config: cfg,
Client: newFakeRemoteClient(SandboxTypeCube),
Store: store,
Checker: &fakeSessionExistenceChecker{exists: true},
SkipHealthProbe: true,
})
require.NoError(t, err)
busy, err := mgr.HasActiveTurn(ctx, "sess-1")
require.NoError(t, err)
require.False(t, busy)
require.NoError(t, mgr.BeginSessionTurn(ctx, "sess-1"))
busy, err = mgr.HasActiveTurn(ctx, "sess-1")
require.NoError(t, err)
require.True(t, busy)
}
func TestHasActiveTurnWithoutLeaseStoreIsNotBusy(t *testing.T) {
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(10000))
store := leaseFreeBindingStore{SessionSandboxBindingStore: NewMemorySessionSandboxBindingStore()}
cfg := DefaultConfig()
cfg.CubeTemplate = "tpl-test"
mgr, err := NewSessionBoundManager(SessionBoundManagerConfig{
Config: cfg,
Client: newFakeRemoteClient(SandboxTypeCube),
Store: store,
Checker: &fakeSessionExistenceChecker{exists: true},
SkipHealthProbe: true,
})
require.NoError(t, err)
busy, err := mgr.HasActiveTurn(ctx, "sess-1")
require.NoError(t, err)
require.False(t, busy)
}
func TestCreateForkSnapshotSnapshotsBoundSandboxWithoutProvisioning(t *testing.T) {
client := newFakeRemoteClient(SandboxTypeCube)
client.capabilities.SupportsSnapshots = true
store := NewMemorySessionSandboxBindingStore()
cfg := DefaultConfig()
cfg.CubeTemplate = "tpl-test"
mgr, err := NewSessionBoundManager(SessionBoundManagerConfig{
Config: cfg,
Client: client,
Store: store,
Checker: &fakeSessionExistenceChecker{exists: true},
SkipHealthProbe: true,
})
require.NoError(t, err)
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(10000))
key := SessionSandboxKey{TenantID: 10000, SessionID: "session-a"}
created, err := store.Create(ctx, key, validSessionSandboxBinding(key, "sbx-existing"))
require.NoError(t, err)
require.True(t, created)
id, err := mgr.CreateForkSnapshot(ctx, "session-a", "fork-session-a-1")
require.NoError(t, err)
require.Equal(t, "snap-1", id)
creates, connects, _, _, _ := client.counts()
require.Zero(t, creates, "CreateForkSnapshot must not provision")
require.Zero(t, connects, "CreateForkSnapshot must not Connect")
client.mu.Lock()
src := client.snapshots[id]
client.mu.Unlock()
require.Equal(t, "sbx-existing", src)
}
func TestCreateForkSnapshotErrorsWhenUnbound(t *testing.T) {
client := newFakeRemoteClient(SandboxTypeCube)
client.capabilities.SupportsSnapshots = true
cfg := DefaultConfig()
cfg.CubeTemplate = "tpl-test"
mgr, err := NewSessionBoundManager(SessionBoundManagerConfig{
Config: cfg,
Client: client,
Store: NewMemorySessionSandboxBindingStore(),
Checker: &fakeSessionExistenceChecker{exists: true},
SkipHealthProbe: true,
})
require.NoError(t, err)
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(10000))
_, err = mgr.CreateForkSnapshot(ctx, "session-a", "fork-session-a-1")
require.Error(t, err)
creates, connects, _, _, _ := client.counts()
require.Zero(t, creates)
require.Zero(t, connects)
}
func TestCreateForkSnapshotErrorsWhenUnsupported(t *testing.T) {
client := newFakeRemoteClient(SandboxTypeCube)
store := NewMemorySessionSandboxBindingStore()
cfg := DefaultConfig()
cfg.CubeTemplate = "tpl-test"
mgr, err := NewSessionBoundManager(SessionBoundManagerConfig{
Config: cfg,
Client: client,
Store: store,
Checker: &fakeSessionExistenceChecker{exists: true},
SkipHealthProbe: true,
})
require.NoError(t, err)
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(10000))
key := SessionSandboxKey{TenantID: 10000, SessionID: "session-a"}
created, err := store.Create(ctx, key, validSessionSandboxBinding(key, "sbx-existing"))
require.NoError(t, err)
require.True(t, created)
_, err = mgr.CreateForkSnapshot(ctx, "session-a", "fork-session-a-1")
require.Error(t, err)
creates, connects, _, _, _ := client.counts()
require.Zero(t, creates)
require.Zero(t, connects)
}
type recordingForkSnapshotClient struct {
*fakeRemoteClient
forkCalls int
forkName string
forkSrc string
}
func (c *recordingForkSnapshotClient) CreateForkSnapshot(
_ context.Context, sandboxID, name string,
) (RemoteSnapshotRef, error) {
c.forkCalls++
c.forkName = name
c.forkSrc = sandboxID
return RemoteSnapshotRef{ID: "fork-" + sandboxID, Names: []string{name}}, nil
}
func TestCreateForkSnapshotPrefersClientCreateForkSnapshot(t *testing.T) {
inner := newFakeRemoteClient(SandboxTypeCube)
inner.capabilities.SupportsSnapshots = true
client := &recordingForkSnapshotClient{fakeRemoteClient: inner}
store := NewMemorySessionSandboxBindingStore()
cfg := DefaultConfig()
cfg.CubeTemplate = "tpl-test"
mgr, err := NewSessionBoundManager(SessionBoundManagerConfig{
Config: cfg,
Client: client,
Store: store,
Checker: &fakeSessionExistenceChecker{exists: true},
SkipHealthProbe: true,
})
require.NoError(t, err)
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(10000))
key := SessionSandboxKey{TenantID: 10000, SessionID: "session-a"}
created, err := store.Create(ctx, key, validSessionSandboxBinding(key, "sbx-existing"))
require.NoError(t, err)
require.True(t, created)
id, err := mgr.CreateForkSnapshot(ctx, "session-a", "fork-session-a-1")
require.NoError(t, err)
require.Equal(t, "fork-sbx-existing", id)
require.Equal(t, 1, client.forkCalls)
require.Equal(t, "fork-session-a-1", client.forkName)
require.Equal(t, "sbx-existing", client.forkSrc)
creates, connects, _, _, _ := inner.counts()
require.Zero(t, creates, "CreateForkSnapshot must not provision")
require.Zero(t, connects, "CreateForkSnapshot must not Connect")
inner.mu.Lock()
_, usedCreateSnapshot := inner.snapshots["snap-1"]
inner.mu.Unlock()
require.False(t, usedCreateSnapshot, "Docker must not fall back to skill CreateSnapshot")
}
type clientBoundRecordingState struct {
withClientCalls int
afterExecs int
}
type clientBoundRecordingBootstrapper struct {
state *clientBoundRecordingState
client RemoteSandboxClient
}
func (b *clientBoundRecordingBootstrapper) WithClient(client RemoteSandboxClient) SessionBootstrapper {
b.state.withClientCalls++
cp := *b
cp.client = client
return &cp
}
func (b *clientBoundRecordingBootstrapper) TemplateOverride(
context.Context, SessionSandboxKey,
) (string, error) {
return "", nil
}
func (b *clientBoundRecordingBootstrapper) AfterCreate(
ctx context.Context, _ SessionSandboxKey, handle RemoteSandboxHandle,
) error {
if b.client == nil || handle == nil {
return errors.New("AfterCreate must use the bound remote client")
}
_, err := b.client.Exec(ctx, handle, RemoteExecRequest{
Command: "echo weknora-fork-after-create",
Shell: true,
WorkDir: SessionWorkspaceRoot,
Timeout: time.Second,
User: DefaultSandboxExecUser,
})
if err != nil {
return err
}
b.state.afterExecs++
return nil
}
var _ SessionBootstrapper = (*clientBoundRecordingBootstrapper)(nil)
var _ SessionBootstrapperWithClient = (*clientBoundRecordingBootstrapper)(nil)
func TestNewSessionBoundManagerBindsBootstrapperToClient(t *testing.T) {
client := newFakeRemoteClient(SandboxTypeCube)
state := &clientBoundRecordingState{}
boot := &clientBoundRecordingBootstrapper{state: state}
cfg := DefaultConfig()
cfg.CubeTemplate = "tpl-test"
mgr, err := NewSessionBoundManager(SessionBoundManagerConfig{
Config: cfg,
Client: client,
Store: NewMemorySessionSandboxBindingStore(),
Checker: &fakeSessionExistenceChecker{exists: true},
SkipHealthProbe: true,
Bootstrapper: boot,
})
require.NoError(t, err)
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(10000))
_, err = mgr.Execute(ctx, &ExecuteConfig{
SessionID: "session-fork-boot",
SkipValidation: true,
ScriptContent: "print('ok')\n",
Script: "hello.py",
})
require.NoError(t, err)
require.Equal(t, 1, state.withClientCalls)
require.Equal(t, 1, state.afterExecs)
found := false
client.mu.Lock()
for _, req := range client.execRequests {
if strings.Contains(req.Command, "weknora-fork-after-create") {
found = true
require.True(t, req.Shell)
require.Equal(t, SessionWorkspaceRoot, req.WorkDir)
require.Equal(t, DefaultSandboxExecUser, req.User)
}
}
client.mu.Unlock()
require.True(t, found, "AfterCreate must Exec on the handle's client")
}
// leaseFreeBindingStore implements only SessionSandboxBindingStore so the
// optional turn-lease type assert fails.
type leaseFreeBindingStore struct {
SessionSandboxBindingStore
}

View File

@ -85,6 +85,10 @@ type TenantSandboxResolverDeps struct {
Store SessionSandboxBindingStore
Checker SessionExistenceChecker
// Bootstrapper customises the first sandbox create of individual sessions
// (session fork). Optional: nil is the ordinary path.
Bootstrapper SessionBootstrapper
// SharedTransport is reused by every tenant's HTTP client. Optional; a
// guarded transport is installed when nil.
SharedTransport *http.Transport
@ -194,6 +198,7 @@ func (r *tenantSandboxResolver) Resolve(
Checker: r.deps.Checker,
SkipHealthProbe: true,
ConfigID: configID,
Bootstrapper: r.deps.Bootstrapper,
})
default:
return NewDisabledManager(), nil

View File

@ -89,6 +89,12 @@ type MessageRepository interface {
) ([]*types.Message, error)
// ListMessagesBySessionAfterCursor uses (created_at, id) for lossless paging.
ListMessagesBySessionAfterCursor(ctx context.Context, sessionID string, cursor types.MemoryMessageCursor, limit int) ([]*types.Message, error)
// ListMessagesBySessionUpTo returns every message sorting strictly before
// the (boundary, boundaryID) composite cursor, oldest first. Used by
// session fork to copy the history preceding a fork point.
ListMessagesBySessionUpTo(
ctx context.Context, sessionID string, boundary time.Time, boundaryID string,
) ([]*types.Message, error)
// UpdateMessage updates a message
UpdateMessage(ctx context.Context, message *types.Message) error
// UpdateMessageImages updates only the images JSONB column for a message
@ -107,8 +113,11 @@ type MessageRepository interface {
SearchMessagesByKeyword(ctx context.Context, tenantID uint64, ownerID, keyword string, sessionIDs []string, limit int) ([]*types.MessageWithSession, error)
// GetMessagesByKnowledgeIDs retrieves messages by their associated Knowledge IDs
GetMessagesByKnowledgeIDs(ctx context.Context, knowledgeIDs []string) ([]*types.MessageWithSession, error)
// GetMessagesByRequestIDs retrieves messages by their request IDs (used to fetch Q&A pair partners)
GetMessagesByRequestIDs(ctx context.Context, requestIDs []string) ([]*types.MessageWithSession, error)
// GetMessagesByRequestIDs retrieves messages by request ID inside one session
// (used to fetch Q&A pair partners). Empty sessionID returns no rows.
GetMessagesByRequestIDs(
ctx context.Context, sessionID string, requestIDs []string,
) ([]*types.MessageWithSession, error)
// GetKnowledgeIDsBySessionID retrieves all knowledge IDs for messages in a session
GetKnowledgeIDsBySessionID(ctx context.Context, sessionID string) ([]string, error)
// UpdateMessageKnowledgeID updates the knowledge_id field for a message
@ -122,4 +131,9 @@ type MessageRepository interface {
// GetSessionAttachments returns every user-uploaded attachment recorded in
// the session. Implementations should project only the attachments column.
GetSessionAttachments(ctx context.Context, sessionID string) (types.MessageAttachments, error)
// RewriteSandboxCheckpoints replaces SandboxID on every copied checkpoint
// in the session that still points at oldSandboxID, keeping CommitSHA and
// CommittedAt. Used after a forked sandbox boots so a later fork-of-fork
// compares against the live handle rather than the parent's sandbox.
RewriteSandboxCheckpoints(ctx context.Context, sessionID, oldSandboxID, newSandboxID string) error
}

View File

@ -2,6 +2,7 @@ package interfaces
import (
"context"
"time"
"github.com/Tencent/WeKnora/internal/event"
"github.com/Tencent/WeKnora/internal/types"
@ -106,4 +107,29 @@ type SessionRepository interface {
BatchDelete(ctx context.Context, tenantID uint64, userID string, ids []string) (int64, error)
// DeleteAllByTenantID deletes all sessions visible to the tenant/user scope.
DeleteAllByTenantID(ctx context.Context, tenantID uint64, userID string) (int64, error)
// CreateForked persists a forked session and its copied history atomically.
CreateForked(ctx context.Context, session *types.Session, messages []*types.Message) error
// UpdateForkBootstrap overwrites a session's fork bootstrap. Passing nil clears it.
UpdateForkBootstrap(ctx context.Context, sessionID string, b *types.ForkBootstrap) error
// ListUnconsumedForks returns fork bootstraps the snapshot reaper should
// try to retire: unopened forks older than olderThan, plus consumed forks
// that still name a snapshot.
ListUnconsumedForks(ctx context.Context, olderThan time.Time) ([]*types.Session, error)
// HasOtherUnconsumedForkSnapshot reports whether another session still
// needs snapshotID to boot. excludeSessionID is the row currently being
// consumed or reaped.
HasOtherUnconsumedForkSnapshot(ctx context.Context, snapshotID, excludeSessionID string) (bool, error)
// UnconsumedForkSnapshotHolders returns session IDs that still need
// snapshotID to provision. The reaper uses this to avoid deleting a
// snapshot while a fork within retention still depends on it.
UnconsumedForkSnapshotHolders(ctx context.Context, snapshotID string) ([]string, error)
// CreateForkSnapshotLease records a provider snapshot ID before the forked
// session row exists, so a crash or CreateForked failure cannot hide it
// from the reaper.
CreateForkSnapshotLease(ctx context.Context, lease *types.ForkSnapshotLease) error
// DeleteForkSnapshotLease drops a lease after the session owns the
// snapshot, or after the snapshot itself has been deleted.
DeleteForkSnapshotLease(ctx context.Context, snapshotID string) error
// ListStaleForkSnapshotLeases returns leases older than olderThan.
ListStaleForkSnapshotLeases(ctx context.Context, olderThan time.Time) ([]*types.ForkSnapshotLease, error)
}

View File

@ -228,18 +228,18 @@ func (m *MessageAttachments) Scan(value interface{}) error {
// behalf and that WeKnora has persisted to its file service so the user can
// download them after the sandbox is reaped.
//
// URL is the provider-scoped storage path (e.g. "local://tenant/..."), never
// exposed directly to the client. SourcePath + ModTime form the sandbox-side
// identity used by ArtifactCollector to de-duplicate files across multi-turn
// runs (see docs/superpowers/specs/2026-07-10-skill-artifact-download-design.md).
// SourcePath + ModTime is the cheap identity for an unchanged sandbox file.
// When mtime moves, ArtifactCollector compares content hashes so a git
// checkout cannot duplicate a blob and a same-size rewrite still attaches.
type MessageArtifact struct {
URL string `json:"url"` // Storage URL (provider://path); persisted, not sent to client
FileName string `json:"file_name"` // Original filename inside the sandbox
FileType string `json:"file_type"` // File extension (e.g., ".pptx", ".pdf")
FileSize int64 `json:"file_size"` // File size in bytes
SourcePath string `json:"source_path"` // Absolute path inside the sandbox (used for diff)
ModTime time.Time `json:"mod_time"` // Sandbox-side modification time (used for diff)
CreatedAt time.Time `json:"created_at"` // When WeKnora persisted the blob
URL string `json:"url"` // Storage URL (provider://path); persisted, not sent to client
FileName string `json:"file_name"` // Original filename inside the sandbox
FileType string `json:"file_type"` // File extension (e.g., ".pptx", ".pdf")
FileSize int64 `json:"file_size"` // File size in bytes
ContentHash string `json:"content_hash,omitempty"` // SHA-256 of the persisted bytes
SourcePath string `json:"source_path"` // Absolute path inside the sandbox (used for diff)
ModTime time.Time `json:"mod_time"` // Sandbox-side modification time (used for diff)
CreatedAt time.Time `json:"created_at"` // When WeKnora persisted the blob
}
// MessageArtifacts is a slice of MessageArtifact for database storage.
@ -272,6 +272,37 @@ func (m *MessageArtifacts) Scan(value interface{}) error {
return json.Unmarshal(b, m)
}
// WithRestoredMtime stamps sandbox mtime onto the artifact at sourcePath
// whose ContentHash already matches. Used after a fork checkout so later
// collects can skip by path+mtime. Other versions at the same path —
// including empty-hash legacy rows — are left alone. The returned slice is a
// copy.
func (m MessageArtifacts) WithRestoredMtime(sourcePath string, mod time.Time, hash string) (MessageArtifacts, bool) {
if len(m) == 0 || sourcePath == "" || hash == "" {
return m, false
}
out := make(MessageArtifacts, len(m))
copy(out, m)
changed := false
for i := range out {
if out[i].SourcePath != sourcePath {
continue
}
// Empty hashes are not a match: a restore must not stamp every
// historical version at this path. Only the row whose content
// already hashed to `hash` gets the new mtime.
if out[i].ContentHash != hash {
continue
}
if out[i].ModTime.Equal(mod) {
continue
}
out[i].ModTime = mod
changed = true
}
return out, changed
}
// MentionedItems is a slice of MentionedItem for database storage
type MentionedItems []MentionedItem
@ -369,6 +400,12 @@ type Message struct {
// spot. Persisted rather than only streamed so reopening a conversation
// still explains what the answer saw.
UsedMemories UsedMemories `json:"used_memories,omitempty" gorm:"type:jsonb;column:used_memories"`
// SandboxCheckpoint is the git commit this assistant turn produced in the
// session sandbox's /workspace. Nil for user messages, for turns that ran
// without a sandbox, and for turns whose commit failed (best-effort — a
// failed checkpoint must never block the reply). A message without a
// checkpoint cannot serve as a fork point with sandbox state.
SandboxCheckpoint *SandboxCheckpoint `json:"sandbox_checkpoint,omitempty" gorm:"type:jsonb"`
// Message creation timestamp
CreatedAt time.Time `json:"created_at"`
// Last update timestamp

View File

@ -120,6 +120,31 @@ func TestMessageArtifacts_ScanUnknownType(t *testing.T) {
}
}
func TestWithRestoredMtimeLeavesEmptyHashOlderVersionAlone(t *testing.T) {
path := "/workspace/output/deck.pptx"
oldMod := time.Date(2026, 7, 10, 10, 20, 30, 0, time.UTC)
newMod := time.Date(2026, 7, 10, 10, 21, 0, 0, time.UTC)
arts := MessageArtifacts{
{URL: "resource://old", FileName: "deck.pptx", SourcePath: path, ModTime: oldMod},
{URL: "resource://new", FileName: "deck.pptx", SourcePath: path, ContentHash: "abc", ModTime: oldMod},
}
got, changed := arts.WithRestoredMtime(path, newMod, "abc")
if !changed {
t.Fatal("matching hashed version should be stamped")
}
if got[0].ContentHash != "" || !got[0].ModTime.Equal(oldMod) {
t.Fatalf("empty-hash older version was rewritten: %+v", got[0])
}
if got[1].ContentHash != "abc" || !got[1].ModTime.Equal(newMod) {
t.Fatalf("matching version not stamped: %+v", got[1])
}
if arts[1].ModTime.Equal(newMod) {
t.Fatal("WithRestoredMtime must not mutate the input slice")
}
}
// TestMessageArtifacts_ValueNil pins the "nil slice → JSON empty array" path
// so a fresh Message without artifacts serialises as `[]` rather than `null`.
func TestMessageArtifacts_ValueNil(t *testing.T) {

View File

@ -107,6 +107,23 @@ type Session struct {
// permanent would make "no session references this config" never true.
SandboxConfigID string `json:"sandbox_config_id,omitempty" gorm:"type:varchar(36)"`
// ParentSessionID names the session this one was forked from. Empty for
// ordinary sessions. Deliberately not a foreign key: the parent may be
// deleted while the branch lives on, and a branch must not cascade away
// with it. A dangling value simply renders as an ordinary session.
ParentSessionID string `json:"parent_session_id,omitempty" gorm:"type:varchar(36);index"`
// ForkedFromMessageID is the user or assistant message, IN THE PARENT
// SESSION, that the fork branched at. For a user point, messages strictly
// before it were copied here. For an assistant point, that answer is
// included so the branch continues after it.
ForkedFromMessageID string `json:"forked_from_message_id,omitempty" gorm:"type:varchar(36)"`
// ForkBootstrap holds the one-shot sandbox provisioning instructions for a
// forked session. Nil for ordinary sessions and for forks that have
// already provisioned. See types.ForkBootstrap.
ForkBootstrap *ForkBootstrap `json:"-" gorm:"type:jsonb;column:fork_bootstrap"`
// // Strategy configuration
// KnowledgeBaseID string `json:"knowledge_base_id"` // 关联的知识库ID
// MaxRounds int `json:"max_rounds"` // 多轮保持轮数

View File

@ -0,0 +1,115 @@
package types
import (
"database/sql/driver"
"encoding/json"
"errors"
"time"
)
// SandboxCheckpoint records the git commit an agent turn produced inside the
// session sandbox's /workspace. It is written on assistant messages only.
//
// SandboxID is stored alongside CommitSHA because commit hashes are only
// meaningful within one sandbox's repository. When a session's sandbox is
// reaped and rebuilt mid-conversation the in-sandbox git history restarts from
// zero, so every checkpoint written before the rebuild becomes unreachable.
// Comparing SandboxID against the session's current binding detects that
// purely from the database, without probing the sandbox.
type SandboxCheckpoint struct {
SandboxID string `json:"sandbox_id"`
CommitSHA string `json:"commit_sha"`
CommittedAt time.Time `json:"committed_at"`
}
// Value implements the driver.Valuer interface for database serialization.
func (c SandboxCheckpoint) Value() (driver.Value, error) {
return json.Marshal(c)
}
// Scan implements the sql.Scanner interface for database deserialization.
func (c *SandboxCheckpoint) Scan(value any) error {
if value == nil {
*c = SandboxCheckpoint{}
return nil
}
var b []byte
switch v := value.(type) {
case []byte:
b = v
case string:
b = []byte(v)
default:
return errors.New("types: cannot scan sandbox checkpoint from unsupported type")
}
if len(b) == 0 {
*c = SandboxCheckpoint{}
return nil
}
return json.Unmarshal(b, c)
}
// ForkBootstrap carries the one-shot instructions a forked session needs the
// first time it provisions a sandbox: boot from SnapshotID instead of the
// config's template, then roll /workspace back to CommitSHA.
//
// It is consumed exactly once. After ConsumedAt is set the forked session is
// indistinguishable from an ordinary session — matching the durability
// semantics every session already has, where a reaped sandbox loses
// /workspace.
type ForkBootstrap struct {
SnapshotID string `json:"snapshot_id"`
CommitSHA string `json:"commit_sha"`
SourceSandboxID string `json:"source_sandbox_id"`
CreatedAt time.Time `json:"created_at"`
ConsumedAt *time.Time `json:"consumed_at,omitempty"`
}
// Consumed reports whether the bootstrap has already been applied.
func (f ForkBootstrap) Consumed() bool {
return f.ConsumedAt != nil
}
// Value implements the driver.Valuer interface for database serialization.
func (f ForkBootstrap) Value() (driver.Value, error) {
return json.Marshal(f)
}
// Scan implements the sql.Scanner interface for database deserialization.
func (f *ForkBootstrap) Scan(value any) error {
if value == nil {
*f = ForkBootstrap{}
return nil
}
var b []byte
switch v := value.(type) {
case []byte:
b = v
case string:
b = []byte(v)
default:
return errors.New("types: cannot scan fork bootstrap from unsupported type")
}
if len(b) == 0 {
*f = ForkBootstrap{}
return nil
}
return json.Unmarshal(b, f)
}
// ForkSnapshotLease is the durable record of a provider snapshot taken before
// the forked session row exists. CreateForked can fail or the process can
// crash in that window; the reaper scans these rows so a snapshot without a
// session is still collectable.
type ForkSnapshotLease struct {
SnapshotID string `json:"snapshot_id" gorm:"column:snapshot_id;primaryKey;type:varchar(128)"`
TenantID uint64 `json:"tenant_id" gorm:"column:tenant_id"`
SandboxConfigID string `json:"sandbox_config_id" gorm:"column:sandbox_config_id;type:varchar(36)"`
CreatedAt time.Time `json:"created_at" gorm:"column:created_at"`
}
// TableName is the lease table. It is separate from sessions: a rolled-back
// CreateForked must not erase the only copy of the snapshot ID.
func (ForkSnapshotLease) TableName() string {
return "fork_snapshot_leases"
}

View File

@ -0,0 +1,62 @@
package types
import (
"testing"
"time"
"github.com/stretchr/testify/require"
)
func TestSandboxCheckpointRoundTrips(t *testing.T) {
at := time.Date(2026, 9, 10, 9, 59, 0, 0, time.UTC)
original := SandboxCheckpoint{SandboxID: "sbx-1", CommitSHA: "abc123", CommittedAt: at}
raw, err := original.Value()
require.NoError(t, err)
var decoded SandboxCheckpoint
require.NoError(t, decoded.Scan(raw))
require.Equal(t, original.SandboxID, decoded.SandboxID)
require.Equal(t, original.CommitSHA, decoded.CommitSHA)
require.True(t, original.CommittedAt.Equal(decoded.CommittedAt))
}
func TestSandboxCheckpointScanNilYieldsZeroValue(t *testing.T) {
var decoded SandboxCheckpoint
require.NoError(t, decoded.Scan(nil))
require.Equal(t, SandboxCheckpoint{}, decoded)
}
func TestSandboxCheckpointScanRejectsGarbage(t *testing.T) {
var decoded SandboxCheckpoint
require.Error(t, decoded.Scan([]byte("not json")))
}
func TestForkBootstrapConsumedReportsState(t *testing.T) {
pending := ForkBootstrap{SnapshotID: "snap-1", CommitSHA: "abc123"}
require.False(t, pending.Consumed())
at := time.Now().UTC()
done := ForkBootstrap{SnapshotID: "snap-1", CommitSHA: "abc123", ConsumedAt: &at}
require.True(t, done.Consumed())
}
func TestForkBootstrapRoundTripsConsumedAt(t *testing.T) {
at := time.Date(2026, 9, 10, 10, 0, 0, 0, time.UTC)
original := ForkBootstrap{
SnapshotID: "snap-1",
CommitSHA: "abc123",
SourceSandboxID: "sbx-1",
CreatedAt: at,
ConsumedAt: &at,
}
raw, err := original.Value()
require.NoError(t, err)
var decoded ForkBootstrap
require.NoError(t, decoded.Scan(raw))
require.Equal(t, original.SnapshotID, decoded.SnapshotID)
require.NotNil(t, decoded.ConsumedAt)
require.True(t, at.Equal(*decoded.ConsumedAt))
}

View File

@ -0,0 +1,7 @@
DROP INDEX IF EXISTS idx_sessions_parent_session_id;
ALTER TABLE sessions DROP COLUMN fork_bootstrap;
ALTER TABLE sessions DROP COLUMN forked_from_message_id;
ALTER TABLE sessions DROP COLUMN parent_session_id;
ALTER TABLE messages DROP COLUMN sandbox_checkpoint;

View File

@ -0,0 +1,13 @@
-- Mirrors versioned migration 000097_session_fork:
-- session lineage plus the per-turn sandbox checkpoint used as a fork point.
-- Existing Lite databases are already at version 13 and never replay 000000_init,
-- so these columns must be added here.
ALTER TABLE sessions ADD COLUMN parent_session_id TEXT;
ALTER TABLE sessions ADD COLUMN forked_from_message_id TEXT;
ALTER TABLE sessions ADD COLUMN fork_bootstrap TEXT;
CREATE INDEX IF NOT EXISTS idx_sessions_parent_session_id
ON sessions (parent_session_id);
ALTER TABLE messages ADD COLUMN sandbox_checkpoint TEXT;

View File

@ -0,0 +1,2 @@
DROP INDEX IF EXISTS idx_fork_snapshot_leases_created_at;
DROP TABLE IF EXISTS fork_snapshot_leases;

View File

@ -0,0 +1,12 @@
-- Mirrors versioned migration 000098_fork_snapshot_lease:
-- durable snapshot IDs taken before the forked session row is committed.
CREATE TABLE IF NOT EXISTS fork_snapshot_leases (
snapshot_id TEXT PRIMARY KEY,
tenant_id INTEGER NOT NULL DEFAULT 0,
sandbox_config_id TEXT NOT NULL DEFAULT '',
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_fork_snapshot_leases_created_at
ON fork_snapshot_leases (created_at);

View File

@ -0,0 +1,8 @@
DROP INDEX IF EXISTS idx_sessions_unconsumed_fork;
DROP INDEX IF EXISTS idx_sessions_parent_session_id;
ALTER TABLE sessions DROP COLUMN IF EXISTS fork_bootstrap;
ALTER TABLE sessions DROP COLUMN IF EXISTS forked_from_message_id;
ALTER TABLE sessions DROP COLUMN IF EXISTS parent_session_id;
ALTER TABLE messages DROP COLUMN IF EXISTS sandbox_checkpoint;

View File

@ -0,0 +1,17 @@
ALTER TABLE sessions ADD COLUMN IF NOT EXISTS parent_session_id VARCHAR(36);
ALTER TABLE sessions ADD COLUMN IF NOT EXISTS forked_from_message_id VARCHAR(36);
ALTER TABLE sessions ADD COLUMN IF NOT EXISTS fork_bootstrap JSONB;
CREATE INDEX IF NOT EXISTS idx_sessions_parent_session_id
ON sessions (parent_session_id)
WHERE parent_session_id IS NOT NULL;
-- Drives the orphan-snapshot reaper, which scans for forks whose bootstrap was
-- never consumed. Partial so the index stays tiny: the overwhelming majority of
-- sessions have no bootstrap at all.
CREATE INDEX IF NOT EXISTS idx_sessions_unconsumed_fork
ON sessions ((fork_bootstrap ->> 'snapshot_id'))
WHERE fork_bootstrap IS NOT NULL
AND fork_bootstrap ->> 'consumed_at' IS NULL;
ALTER TABLE messages ADD COLUMN IF NOT EXISTS sandbox_checkpoint JSONB;

View File

@ -0,0 +1,2 @@
DROP INDEX IF EXISTS idx_fork_snapshot_leases_created_at;
DROP TABLE IF EXISTS fork_snapshot_leases;

View File

@ -0,0 +1,9 @@
CREATE TABLE IF NOT EXISTS fork_snapshot_leases (
snapshot_id VARCHAR(128) PRIMARY KEY,
tenant_id BIGINT NOT NULL DEFAULT 0,
sandbox_config_id VARCHAR(36) NOT NULL DEFAULT '',
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_fork_snapshot_leases_created_at
ON fork_snapshot_leases (created_at);