Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
🪬 fix: Fence Agent Checkpoint Ownership and Cleanup Recovery (#15680)
Dustin Healycdc3339a785b
diff --git a/api/jest.config.js b/api/jest.config.jsindex f9f03da125..4ba0853094 100644--- a/api/jest.config.js+++ b/api/jest.config.js@@ -34,7 +34,10 @@ module.exports = {'\\.[jt]sx?$': ['babel-jest',{- presets: [['@babel/preset-env', { targets: { node: 'current' } }]],+ presets: [+ ['@babel/preset-env', { targets: { node: 'current' } }],+ '@babel/preset-typescript',+ ],},],},diff --git a/api/server/controllers/UserController.js b/api/server/controllers/UserController.jsindex 6a5199f844..607f7ce605 100644--- a/api/server/controllers/UserController.js+++ b/api/server/controllers/UserController.js@@ -8,7 +8,9 @@ const {normalizeHttpError,getWebSearchInstallEntries,getWebSearchUninstallFields,- deleteAgentCheckpoints,+ openCheckpointDeletion,+ isStopConfirmed,+ waitForGenerationPersistence,deleteAllSharedLinksWithCleanup,revokeUserCodeEnvironmentWorkers,} = require('@librechat/api');@@ -381,6 +383,7 @@ const updateUserPluginsController = async (req, res) => {const deleteUserController = async (req, res) => {const { user } = req;+ const tenantId = user.tenantId || undefined;let triggerDeletionFence;let scheduleSuspensionToken;let userDeleted = false;@@ -414,11 +417,11 @@ const deleteUserController = async (req, res) => {triggerDeletionFence = undefined;}if (triggerDeletionFence != null) {- await prepareAgentTriggerUserPurge(user.id, triggerDeletionFence, user.tenantId);+ await prepareAgentTriggerUserPurge(user.id, triggerDeletionFence, tenantId);}const deletionAppConfig = await getAppConfig({ baseOnly: true });await drainAgentTriggerDeliveriesForUser(user.id);- await subagentThreadTaskStore.cancelAndDrainForOwner(user.id, user.tenantId);+ await subagentThreadTaskStore.cancelAndDrainForOwner(user.id, tenantId);// Reversibly suspend the user's schedules under a per-attempt token BEFORE draining.// A later cascade step (or this drain) can still fail and cancel the deletion, and the// catch below restores exactly this attempt's rows — so a failed deletion never leaves@@ -427,40 +430,71 @@ const deleteUserController = async (req, res) => {if (!(await quiesceUserSchedules(user.id, scheduleSuspensionToken))) {throw new Error('Scheduled executions could not be confirmed stopped');}- const activeAgentRuns = await GenerationJobManager.getCleanupBlockingJobIdsForUser(+ const activeAgentRuns = await GenerationJobManager.getAccountCleanupJobIdsForUser(user.id,- user.tenantId,+ tenantId,);+ const activeAgentJobs = await Promise.all(+ activeAgentRuns.map(async (streamId) => ({+ streamId,+ job: await GenerationJobManager.getCleanupJob(streamId),+ })),+ );+ const ownedAgentJobs = activeAgentJobs.filter(+ ({ job }) =>+ job?.metadata?.userId === user.id &&+ (!job.metadata.tenantId || job.metadata.tenantId === tenantId),+ );+ const stopResults = await Promise.all(+ ownedAgentJobs.map(({ streamId, job }) =>+ GenerationJobManager.abortJob(streamId, {+ expectedCreatedAt: job.createdAt,+ awaitProviderDrain: true,+ }),+ ),+ );+ if (stopResults.some((result) => !isStopConfirmed(result))) {+ throw new Error('Agent generations could not be confirmed stopped');+ }await Promise.all(- activeAgentRuns.map((streamId) =>- GenerationJobManager.abortJob(streamId, { awaitProviderDrain: true }),+ ownedAgentJobs.map(({ streamId, job }) =>+ waitForGenerationPersistence(streamId, job.createdAt, (id) =>+ GenerationJobManager.getCleanupJob(id),+ ),),);+ const appConfig =+ req.config ??+ (await getAppConfig({+ role: user.role,+ userId: user.id,+ tenantId,+ }));+ const checkpointer = appConfig?.endpoints?.agents?.checkpointer;+ const checkpointDeletion = await openCheckpointDeletion(+ user.id,+ tenantId,+ undefined,+ checkpointer,+ );+ await db.deleteConvos(+ user.id,+ {},+ {+ allowEmpty: true,+ beforeDelete: (ids) => checkpointDeletion.remember(ids),+ },+ );+ await checkpointDeletion.cleanup();+ await checkpointDeletion.acknowledge();+await db.deleteMessages({ user: user.id });await db.deleteAllUserSessions({ userId: user.id });await db.deleteTransactions({ user: user.id });await db.deleteUserKey({ userId: user.id, all: true });await db.deleteBalances({ user: user._id });await db.deletePresets(user.id);- try {- const convoDeletion = await db.deleteConvos(user.id);- // HITL: prune the deleted conversations' durable checkpoints — a paused run's- // checkpoint would otherwise persist until the Mongo TTL. Never throws.- const appConfig =- req.config ??- (await getAppConfig({- role: req.user?.role,- userId: req.user?.id,- tenantId: req.user?.tenantId,- }));- await deleteAgentCheckpoints(- convoDeletion?.conversationIds,- appConfig?.endpoints?.agents?.checkpointer,- );- } catch (error) {- logger.error('[deleteUserController] Error deleting user convos, likely no convos', error);- }await deleteUserPluginAuth(user.id, null, true);await deleteAllSharedLinksWithCleanup(user.id);await deleteUserFiles(req);@@ -502,7 +536,7 @@ const deleteUserController = async (req, res) => {logger.error('[deleteUserController] Failed to delete code environments', error);}}- await invalidateCodeEnvironmentConfigCache(user.tenantId).catch((error) => {+ await invalidateCodeEnvironmentConfigCache(tenantId).catch((error) => {logger.error('[deleteUserController] code environment cache invalidation failed:', error);});await purgeAgentTriggerDeliveriesForUser(user.id);diff --git a/api/server/controllers/UserController.spec.js b/api/server/controllers/UserController.spec.jsindex 7d3fd9ff8e..aecc5bc218 100644--- a/api/server/controllers/UserController.spec.js+++ b/api/server/controllers/UserController.spec.js@@ -2,7 +2,16 @@ const mongoose = require('mongoose');const { MongoMemoryServer } = require('mongodb-memory-server');const mockGetActiveJobIdsForUser = jest.fn().mockResolvedValue([]);+const mockGetAgentJob = jest.fn().mockResolvedValue(null);const mockAbortJob = jest.fn().mockResolvedValue({ success: true });+const mockDeleteOwnedAgentCheckpoints = jest.fn().mockResolvedValue(undefined);+const mockDeleteAgentCheckpoints = jest.fn(async (threadIds = []) => {+ const filter = { thread_id: { $in: threadIds } };+ await Promise.all([+ mongoose.connection.db.collection('agent_checkpoints').deleteMany(filter),+ mongoose.connection.db.collection('agent_checkpoint_writes').deleteMany(filter),+ ]);+});const mockDrainAgentTriggerDeliveriesForUser = jest.fn().mockResolvedValue(undefined);const mockPrepareAgentTriggerUserPurge = jest.fn().mockResolvedValue(undefined);const mockCancelAgentTriggerUserPurge = jest.fn().mockResolvedValue(true);@@ -93,9 +102,18 @@ jest.mock('@librechat/api', () => ({getWebSearchInstallEntries: (...args) => mockGetWebSearchInstallEntries(...args),revokeUserCodeEnvironmentWorkers: (...args) => mockRevokeUserCodeEnvironmentWorkers(...args),GenerationJobManager: {- getCleanupBlockingJobIdsForUser: (...args) => mockGetActiveJobIdsForUser(...args),+ getAccountCleanupJobIdsForUser: (...args) => mockGetActiveJobIdsForUser(...args),+ getCleanupJob: (...args) => mockGetAgentJob(...args),abortJob: (...args) => mockAbortJob(...args),},+ deleteAgentCheckpoints: (...args) => mockDeleteAgentCheckpoints(...args),+ deleteOwnedAgentCheckpoints: (...args) => mockDeleteOwnedAgentCheckpoints(...args),+ openCheckpointDeletion: jest.fn(async (userId, tenantId, _root, cfg) => ({+ remember: jest.fn(async () => undefined),+ cleanup: async () => mockDeleteOwnedAgentCheckpoints(userId, tenantId, undefined, cfg),+ acknowledge: jest.fn(async () => undefined),+ conversationIds: () => [],+ })),}));jest.mock('~/server/services/Agents/triggers', () => ({@@ -270,6 +288,10 @@ describe('verifyEmailController', () => {beforeEach(() => {jest.clearAllMocks();mockQuiesceUserSchedules.mockResolvedValue(true);+ mockGetActiveJobIdsForUser.mockResolvedValue([]);+ mockGetAgentJob.mockResolvedValue(null);+ mockAbortJob.mockResolvedValue({ success: true });+ mockDeleteOwnedAgentCheckpoints.mockResolvedValue(undefined);});it('returns the generic verification error message from service failures', async () => {@@ -507,9 +529,29 @@ describe('deleteUserController', () => {expect(mockRestoreUserSchedules).not.toHaveBeenCalled();});+ it('does not erase checkpoint payload when conversation deletion fails', async () => {+ const userId = new mongoose.Types.ObjectId();+ deleteConvos.mockImplementationOnce(async (_userId, _filter, options) => {+ await options.beforeDelete(['conversation-1']);+ throw new Error('conversation deletion failed');+ });+ await deleteUserController(+ { user: { id: userId.toString(), _id: userId, email: '[email protected]' } },+ mockRes,+ );+ expect(mockRes.status).toHaveBeenCalledWith(500);+ expect(mockDeleteOwnedAgentCheckpoints).not.toHaveBeenCalled();+ expect(deleteMessages).not.toHaveBeenCalled();+ });+it('aborts generations admitted before the deletion fence before erasing messages', async () => {const userId = new mongoose.Types.ObjectId();mockGetActiveJobIdsForUser.mockResolvedValueOnce(['stream-1', 'stream-2']);+ mockGetAgentJob.mockImplementation(async (streamId) => ({+ metadata: { userId: userId.toString(), tenantId: 'tenant-1' },+ streamId,+ createdAt: 123,+ }));const req = {user: {id: userId.toString(),@@ -522,17 +564,247 @@ describe('deleteUserController', () => {await deleteUserController(req, mockRes);expect(mockGetActiveJobIdsForUser).toHaveBeenCalledWith(userId.toString(), 'tenant-1');- expect(mockAbortJob).toHaveBeenCalledWith('stream-1', { awaitProviderDrain: true });- expect(mockAbortJob).toHaveBeenCalledWith('stream-2', { awaitProviderDrain: true });+ expect(mockAbortJob).toHaveBeenCalledWith('stream-1', {+ expectedCreatedAt: 123,+ awaitProviderDrain: true,+ });+ expect(mockAbortJob).toHaveBeenCalledWith('stream-2', {+ expectedCreatedAt: 123,+ awaitProviderDrain: true,+ });expect(mockAbortJob.mock.invocationCallOrder[1]).toBeLessThan(deleteMessages.mock.invocationCallOrder[0],);});+ it.each(['terminalPersistencePending', 'terminalHostActionPending'])(+ 'waits for %s after an already-settled abort',+ async (marker) => {+ const userId = new mongoose.Types.ObjectId();+ const job = {+ createdAt: 123,+ status: 'complete',+ metadata: { userId: userId.toString(), [marker]: true },+ };+ mockGetActiveJobIdsForUser.mockResolvedValueOnce(['terminal']);+ mockGetAgentJob+ .mockResolvedValueOnce(job)+ .mockImplementationOnce(async () => {+ expect(deleteMessages).not.toHaveBeenCalled();+ expect(mockDeleteOwnedAgentCheckpoints).not.toHaveBeenCalled();+ return job;+ })+ .mockImplementationOnce(async () => {+ expect(deleteMessages).not.toHaveBeenCalled();+ return { ...job, metadata: { ...job.metadata, [marker]: false } };+ });+ mockAbortJob.mockResolvedValueOnce({ success: false, failureReason: 'already_settled' });+ await deleteUserController({ user: { id: userId.toString(), _id: userId } }, mockRes);+ expect(mockGetAgentJob).toHaveBeenCalledTimes(3);+ expect(deleteMessages).toHaveBeenCalled();+ },+ );++ it('retains account data when terminal persistence cannot be confirmed', async () => {+ const userId = new mongoose.Types.ObjectId();+ mockGetActiveJobIdsForUser.mockResolvedValueOnce(['terminal']);+ mockGetAgentJob+ .mockResolvedValueOnce({+ createdAt: 123,+ metadata: { userId: userId.toString(), terminalPersistencePending: true },+ })+ .mockRejectedValueOnce(new Error('terminal owner unavailable'));+ await deleteUserController({ user: { id: userId.toString(), _id: userId } }, mockRes);+ expect(mockRes.status).toHaveBeenCalledWith(500);+ expect(deleteMessages).not.toHaveBeenCalled();+ expect(mockDeleteOwnedAgentCheckpoints).not.toHaveBeenCalled();+ });++ it('normalizes an empty account tenant before checkpoint erasure', async () => {+ const userId = new mongoose.Types.ObjectId();+ const actual = jest.requireActual('@librechat/api');+ const owner = actual.checkpointOwnerNamespacePrefix(userId.toString());+ for (const name of ['agent_checkpoints', 'agent_checkpoint_writes']) {+ await mongoose.connection.db.collection(name).insertMany([+ { thread_id: 'thread', checkpoint_ns: owner + 'event-actor/new', lc_owner: owner },+ { thread_id: 'thread', checkpoint_ns: 'foreign', lc_owner: 'foreign' },+ ]);+ }+ mockDeleteOwnedAgentCheckpoints.mockImplementationOnce((...args) =>+ actual.deleteOwnedAgentCheckpoints(...args),+ );+ await deleteUserController(+ { user: { id: userId.toString(), _id: userId, tenantId: '' } },+ mockRes,+ );+ expect(mockDeleteOwnedAgentCheckpoints).toHaveBeenCalledWith(+ userId.toString(),+ undefined,+ undefined,+ undefined,+ );+ for (const name of ['agent_checkpoints', 'agent_checkpoint_writes']) {+ expect(+ (await mongoose.connection.db.collection(name).find().toArray()).map((row) => row.lc_owner),+ ).toEqual(['foreign']);+ }+ });++ it('prunes only account checkpoint receipts bound to the deleted user and tenant', async () => {+ const userId = new mongoose.Types.ObjectId();+ const userIdString = userId.toString();+ const ownedNamespace = `lcg:v2:${require('crypto')+ .createHash('sha256')+ .update(JSON.stringify(['tenant-1', userIdString]))+ .digest('hex')}:00000000-0000-4000-8000-000000000001`;+ const foreignUserNamespace = 'lcg:v1:00000000-0000-4000-8000-000000000002';+ const foreignTenantNamespace = 'lcg:v1:00000000-0000-4000-8000-000000000003';+ const missingTenantNamespace = 'lcg:v1:00000000-0000-4000-8000-000000000004';+ const checkpointDocuments = [+ ownedNamespace,+ `${ownedNamespace}|subgraph`,+ foreignUserNamespace,+ foreignTenantNamespace,+ missingTenantNamespace,+ '',+ ].map((checkpointNamespace) => ({+ thread_id: 'collision-id',+ checkpoint_ns: checkpointNamespace,+ }));+ await mongoose.connection.db.collection('agent_checkpoints').insertMany(checkpointDocuments);+ await mongoose.connection.db+ .collection('agent_checkpoint_writes')+ .insertMany(checkpointDocuments);+ mockDeleteOwnedAgentCheckpoints.mockImplementationOnce((...args) =>+ jest.requireActual('@librechat/api').deleteOwnedAgentCheckpoints(...args),+ );+ deleteConvos.mockResolvedValueOnce({ deletedCount: 1, conversationIds: ['collision-id'] });+ mockGetActiveJobIdsForUser.mockResolvedValueOnce([+ 'owned-run',+ 'foreign-user-run',+ 'foreign-tenant-run',+ 'legacy-tenant-run',+ 'legacy-run',+ ]);+ mockGetAgentJob.mockImplementation(async (streamId) => {+ const metadata = {+ 'owned-run': {+ userId: userIdString,+ tenantId: 'tenant-1',+ conversationId: 'collision-id',+ checkpointNamespace: ownedNamespace,+ generationProtocolVersion: 2,+ },+ 'foreign-user-run': {+ userId: 'foreign-user',+ tenantId: 'tenant-1',+ conversationId: 'collision-id',+ checkpointNamespace: foreignUserNamespace,+ generationProtocolVersion: 2,+ },+ 'foreign-tenant-run': {+ userId: userIdString,+ tenantId: 'foreign-tenant',+ conversationId: 'collision-id',+ checkpointNamespace: foreignTenantNamespace,+ generationProtocolVersion: 2,+ },+ 'legacy-run': {+ userId: userIdString,+ tenantId: 'tenant-1',+ conversationId: 'collision-id',+ checkpointNamespace: '',+ generationProtocolVersion: 1,+ },+ 'legacy-tenant-run': {+ userId: userIdString,+ conversationId: 'collision-id',+ checkpointNamespace: missingTenantNamespace,+ generationProtocolVersion: 2,+ },+ }[streamId];+ return { metadata, streamId, createdAt: 123 };+ });+ const req = {+ user: {+ id: userIdString,+ _id: userId,+ email: '[email protected]',+ tenantId: 'tenant-1',+ },+ config: {},+ };++ await deleteUserController(req, mockRes);++ expect(mockRes.status).toHaveBeenCalledWith(200);+ expect(+ await mongoose.connection.db+ .collection('agent_checkpoints')+ .find({ thread_id: 'collision-id' })+ .project({ _id: 0, checkpoint_ns: 1 })+ .sort({ checkpoint_ns: 1 })+ .toArray(),+ ).toEqual([+ { checkpoint_ns: '' },+ { checkpoint_ns: foreignUserNamespace },+ { checkpoint_ns: foreignTenantNamespace },+ { checkpoint_ns: missingTenantNamespace },+ ]);+ expect(mockAbortJob.mock.calls.map(([streamId]) => streamId)).toEqual([+ 'owned-run',+ 'legacy-tenant-run',+ 'legacy-run',+ ]);+ expect(mockDeleteOwnedAgentCheckpoints).toHaveBeenCalledWith(+ userIdString,+ 'tenant-1',+ undefined,+ undefined,+ );+ });++ it('fails closed when an account generation is replaced before abort', async () => {+ const userId = new mongoose.Types.ObjectId();+ const userIdString = userId.toString();+ mockGetActiveJobIdsForUser.mockResolvedValueOnce(['replaced-run']);+ mockGetAgentJob.mockResolvedValueOnce({+ metadata: { userId: userIdString, tenantId: 'tenant-1' },+ streamId: 'replaced-run',+ createdAt: 123,+ });+ mockAbortJob.mockResolvedValueOnce({ success: false, failureReason: 'generation_replaced' });++ await deleteUserController(+ {+ user: {+ id: userIdString,+ _id: userId,+ email: '[email protected]',+ tenantId: 'tenant-1',+ },+ },+ mockRes,+ );++ expect(mockAbortJob).toHaveBeenCalledWith('replaced-run', {+ expectedCreatedAt: 123,+ awaitProviderDrain: true,+ });+ expect(mockRes.status).toHaveBeenCalledWith(500);+ expect(deleteMessages).not.toHaveBeenCalled();+ expect(mockDeleteOwnedAgentCheckpoints).not.toHaveBeenCalled();+ });+it('fails closed and releases deletion fences when a provider cannot confirm drain', async () => {const userId = new mongoose.Types.ObjectId();const userIdString = userId.toString();mockGetActiveJobIdsForUser.mockResolvedValueOnce(['stream-still-writing']);+ mockGetAgentJob.mockResolvedValueOnce({+ metadata: { userId: userIdString, tenantId: 'tenant-1' },+ streamId: 'stream-still-writing',+ createdAt: 123,+ });mockAbortJob.mockRejectedValueOnce(new Error('provider drain timed out'));const req = {user: {@@ -671,15 +943,14 @@ describe('deleteUserController', () => {expect(group.memberIds).toEqual(['other']);});- it('should still succeed when deleteConvos throws', async () => {+ it('fails closed when conversation deletion fails', async () => {const userId = new mongoose.Types.ObjectId();deleteConvos.mockRejectedValueOnce(new Error('no convos'));const req = { user: { id: userId.toString(), _id: userId, email: '[email protected]' } };await deleteUserController(req, mockRes);- expect(mockRes.status).toHaveBeenCalledWith(200);- expect(mockRes.send).toHaveBeenCalledWith({ message: 'User deleted' });+ expect(mockRes.status).toHaveBeenCalledWith(500);});it('should return 500 when a critical operation fails', async () => {diff --git a/api/server/controllers/__tests__/deleteUser.spec.js b/api/server/controllers/__tests__/deleteUser.spec.jsindex aabf4a63c0..10a031bbbe 100644--- a/api/server/controllers/__tests__/deleteUser.spec.js+++ b/api/server/controllers/__tests__/deleteUser.spec.js@@ -22,6 +22,7 @@ const mockDeleteUserSkills = jest.fn();const mockDeleteUserCodeEnvironments = jest.fn();const mockInvalidateCodeEnvironmentConfigCache = jest.fn();const mockGetCleanupBlockingJobIdsForUser = jest.fn();+const mockGetAgentJob = jest.fn();const mockAbortJob = jest.fn();const mockDrainAgentTriggerDeliveriesForUser = jest.fn();const mockPrepareAgentTriggerUserPurge = jest.fn();@@ -56,9 +57,26 @@ jest.mock('@librechat/api', () => ({deleteAllSharedLinksWithCleanup: (...args) => mockDeleteAllSharedLinksWithCleanup(...args),revokeUserCodeEnvironmentWorkers: (...args) => mockRevokeUserCodeEnvironmentWorkers(...args),GenerationJobManager: {- getCleanupBlockingJobIdsForUser: (...args) => mockGetCleanupBlockingJobIdsForUser(...args),+ getAccountCleanupJobIdsForUser: (...args) => mockGetCleanupBlockingJobIdsForUser(...args),+ getCleanupJob: (...args) => mockGetAgentJob(...args),abortJob: (...args) => mockAbortJob(...args),},+ getOwnedAgentCheckpointScope: jest.fn(() => undefined),+ isStopConfirmed: jest.fn(+ (result) => result?.success === true || result?.failureReason === 'already_settled',+ ),+ deleteOwnedAgentCheckpoints: jest.fn(),+ waitForGenerationPersistence: jest.requireActual(+ '../../../../packages/api/src/stream/persistence.ts',+ ).waitForGenerationPersistence,+ openCheckpointDeletion: jest.fn(async (userId, tenantId, _root, cfg) => ({+ remember: jest.fn(),+ cleanup: () =>+ jest+ .requireMock('@librechat/api')+ .deleteOwnedAgentCheckpoints(userId, tenantId, undefined, cfg),+ acknowledge: jest.fn(),+ })),}));jest.mock('~/models', () => ({@@ -150,6 +168,7 @@ jest.mock('~/cache', () => ({}));const { deleteUserController } = require('~/server/controllers/UserController');+const { deleteOwnedAgentCheckpoints } = require('@librechat/api');function createRes() {const res = {};@@ -178,6 +197,7 @@ function stubDeletionMocks() {mockDeleteUserSkills.mockResolvedValue(0);mockInvalidateCodeEnvironmentConfigCache.mockResolvedValue(undefined);mockGetCleanupBlockingJobIdsForUser.mockResolvedValue([]);+ mockGetAgentJob.mockResolvedValue(null);mockAbortJob.mockResolvedValue({ success: true });mockDrainAgentTriggerDeliveriesForUser.mockResolvedValue();mockPrepareAgentTriggerUserPurge.mockResolvedValue();@@ -245,16 +265,43 @@ describe('deleteUserController - 2FA enforcement', () => {const res = createRes();mockGetUserById.mockResolvedValue({ _id: 'user1', twoFactorEnabled: false });mockGetCleanupBlockingJobIdsForUser.mockResolvedValueOnce(['stream-1']);+ mockGetAgentJob.mockResolvedValueOnce({+ metadata: { userId: 'user1', tenantId: 'tenant-1' },+ createdAt: 123,+ });+ mockAbortJob.mockResolvedValueOnce({ success: true });await deleteUserController(req, res);expect(mockGetCleanupBlockingJobIdsForUser).toHaveBeenCalledWith('user1', 'tenant-1');- expect(mockAbortJob).toHaveBeenCalledWith('stream-1', { awaitProviderDrain: true });+ expect(mockAbortJob).toHaveBeenCalledWith('stream-1', {+ expectedCreatedAt: 123,+ awaitProviderDrain: true,+ });expect(mockAbortJob.mock.invocationCallOrder[0]).toBeLessThan(mockDeleteMessages.mock.invocationCallOrder[0],);});+ it('deletes owner checkpoints before erasing the account after job records expire', async () => {+ const req = {+ user: { id: 'user1', _id: 'user1', email: '[email protected]', tenantId: 'tenant-1' },+ body: {},+ config: { endpoints: { agents: { checkpointer: { ttl: 60 } } } },+ };+ const res = createRes();+ mockGetUserById.mockResolvedValue({ _id: 'user1', twoFactorEnabled: false });++ await deleteUserController(req, res);++ expect(deleteOwnedAgentCheckpoints).toHaveBeenCalledWith('user1', 'tenant-1', undefined, {+ ttl: 60,+ });+ expect(deleteOwnedAgentCheckpoints.mock.invocationCallOrder[0]).toBeLessThan(+ mockDeleteUserById.mock.invocationCallOrder[0],+ );+ });+it('preserves code environment records when revocation marking fails after deletion', async () => {const req = { user: { id: 'user1', _id: 'user1', email: '[email protected]' }, body: {} };const res = createRes();diff --git a/api/server/controllers/agents/__tests__/askUserQuestion.e2e.spec.js b/api/server/controllers/agents/__tests__/askUserQuestion.e2e.spec.jsindex 3a331a791a..3733188e89 100644--- a/api/server/controllers/agents/__tests__/askUserQuestion.e2e.spec.js+++ b/api/server/controllers/agents/__tests__/askUserQuestion.e2e.spec.js@@ -231,7 +231,8 @@ describe('ask_user_question lifecycle (full wiring, approval policy disabled)',initialMetadata: { generationProtocolVersion: 2 },});const checkpointNamespace = job.metadata.checkpointNamespace;- expect(checkpointNamespace).toBe(String(job.createdAt));+ expect(checkpointNamespace).toEqual(expect.any(String));+ expect(checkpointNamespace).not.toBe(String(job.createdAt));// --- Turn 1: the model calls the ask tool → interrupt() from inside the tool body. ---const run = await buildAskRun({@@ -359,7 +360,8 @@ describe('ask_user_question lifecycle (full wiring, approval policy disabled)',initialMetadata: { generationProtocolVersion: 2 },});const checkpointNamespace = job.metadata.checkpointNamespace;- expect(checkpointNamespace).toBe(String(job.createdAt));+ expect(checkpointNamespace).toEqual(expect.any(String));+ expect(checkpointNamespace).not.toBe(String(job.createdAt));const run = await buildAskRunEventMode({saver,diff --git a/api/server/controllers/agents/__tests__/hitlCheckpoint.e2e.spec.js b/api/server/controllers/agents/__tests__/hitlCheckpoint.e2e.spec.jsindex 8015224398..b0c9c6fc2a 100644--- a/api/server/controllers/agents/__tests__/hitlCheckpoint.e2e.spec.js+++ b/api/server/controllers/agents/__tests__/hitlCheckpoint.e2e.spec.js@@ -215,7 +215,8 @@ describe('HITL checkpoint lifecycle (full wiring)', () => {initialMetadata: { generationProtocolVersion: 2 },});const checkpointNamespace = job.metadata.checkpointNamespace;- expect(checkpointNamespace).toBe(String(job.createdAt));+ expect(checkpointNamespace).toEqual(expect.any(String));+ expect(checkpointNamespace).not.toBe(String(job.createdAt));// --- Turn 1: the model calls the gated tool → PreToolUse 'ask' → interrupt. ---const run = await buildHitlRun({diff --git a/api/server/controllers/agents/__tests__/resume.spec.js b/api/server/controllers/agents/__tests__/resume.spec.jsindex b31d89b7f3..fdfe54ab97 100644--- a/api/server/controllers/agents/__tests__/resume.spec.js+++ b/api/server/controllers/agents/__tests__/resume.spec.js@@ -857,30 +857,41 @@ describe('ResumeAgentController (POST /agents/chat/resume)', () => {},);- it('fails closed when a versioned job marker no longer matches canonical suspension', async () => {- configureEventActorResume();- mockGenerationJobManager.getJob.mockResolvedValue(- makeToolApprovalJob({- metadata: {- agentEventSuspension: { version: 1, suspensionId: 'stale', attempt: 0 },- },- }),- );- mockGetAgentEventActorSnapshot.mockResolvedValue({- state: null,- epoch: 1,- legacyTurn: null,- reconciliations: [],- suspension: null,- });+ it.each([null, 'pending_owned', 'claimed_owned'])(+ 'does not consume approval for an unsupported raw suspension state: %s',+ async (status) => {+ configureEventActorResume();+ mockGenerationJobManager.getJob.mockResolvedValue(+ makeToolApprovalJob({+ metadata: {+ agentEventSuspension: { version: 1, suspensionId: 'stale', attempt: 0 },+ },+ }),+ );+ mockGetAgentEventActorSnapshot.mockResolvedValue({+ state: null,+ epoch: 1,+ legacyTurn: null,+ reconciliations: [],+ suspension:+ status == null+ ? null+ : {+ status,+ actionId: ACTION_ID,+ jobCreatedAt: 1000,+ suspension: { suspensionId: 'stale', attempt: 0 },+ },+ });- const res = await post(approveBody());+ const res = await post(approveBody());- expect(res.status).toBe(409);- expect(res.body).toMatchObject({ code: 'EVENT_ACTOR_SUSPENSION_STALE' });- expect(mockGenerationJobManager.approvals.resolve).not.toHaveBeenCalled();- expect(mockResumeAgentEventActor).not.toHaveBeenCalled();- });+ expect(res.status).toBe(409);+ expect(res.body).toMatchObject({ code: 'EVENT_ACTOR_SUSPENSION_STALE' });+ expect(mockGenerationJobManager.approvals.resolve).not.toHaveBeenCalled();+ expect(mockResumeAgentEventActor).not.toHaveBeenCalled();+ },+ );it('fails promptly when suspension validation rejects before the job claim callback', async () => {configureEventActorResume();@@ -1072,6 +1083,25 @@ describe('ResumeAgentController (POST /agents/chat/resume)', () => {},});+ it('persists the server namespace when a scheduled approval pauses again', async () => {+ mockGenerationJobManager.getJob.mockResolvedValue(makeScheduledJob());+ mockInitializeClient.mockResolvedValue({+ client: makeClient({ pendingApproval: { actionId: NEXT_ACTION_ID } }),+ userMCPAuthMap: {},+ });+ const res = await post(approveBody());+ expect(res.status).toBe(200);+ await settled;+ await flush();+ expect(mockRecordScheduleOutcome).toHaveBeenCalledWith(+ expect.objectContaining({+ scheduleId: 'schedule-1',+ status: 'requires_action',+ checkpointNamespace: '1000',+ }),+ );+ });+it('settles and prunes a scheduled occurrence terminalized by recovery validation', async () => {const scheduledJob = makeScheduledJob();mockGenerationJobManager.getJob.mockResolvedValueOnce(scheduledJob).mockResolvedValueOnce({diff --git a/api/server/controllers/agents/client.js b/api/server/controllers/agents/client.jsindex 9dada8692e..19308dbdf2 100644--- a/api/server/controllers/agents/client.js+++ b/api/server/controllers/agents/client.js@@ -67,6 +67,10 @@ const {deleteAgentCheckpoint,LIBRECHAT_CHECKPOINT_NAMESPACE_KEY,LIBRECHAT_EVENT_ACTOR_INVOCATION_KEY,+ LIBRECHAT_CHECKPOINT_OWNER_KEY,+ LIBRECHAT_CHECKPOINT_STORAGE_OWNER_KEY,+ LIBRECHAT_LEGACY_CHECKPOINT_KEY,+ checkpointOwnerNamespacePrefix,isAskUserQuestionAdminDisabled,attachAskUserQuestionArgs,hydrateResumeRunSteps,@@ -4453,6 +4457,13 @@ class AgentClient extends BaseClient {// into its physical namespace while tools keep the conversation id.checkpoint_ns: '',[LIBRECHAT_CHECKPOINT_NAMESPACE_KEY]: this.checkpointNamespace,+ [LIBRECHAT_CHECKPOINT_STORAGE_OWNER_KEY]:+ (this.user ?? this.options.req.user?.id)+ ? checkpointOwnerNamespacePrefix(+ this.user ?? this.options.req.user?.id,+ resolveRequestTenantId(this.options.req),+ )+ : undefined,...(this.eventActorCheckpointId == null? {}: { checkpoint_id: this.eventActorCheckpointId }),@@ -4460,6 +4471,13 @@ class AgentClient extends BaseClient {? {}: {[LIBRECHAT_EVENT_ACTOR_INVOCATION_KEY]: this.eventActorInvocationId,+ [LIBRECHAT_CHECKPOINT_OWNER_KEY]: checkpointOwnerNamespacePrefix(+ this.options.req.user.id,+ this.options.req._agentEventBindingTenantId,+ ),+ ...(this.eventActorCheckpointId == null+ ? {}+ : { [LIBRECHAT_LEGACY_CHECKPOINT_KEY]: this.eventActorCheckpointId }),event_actor_invocation_id: this.eventActorInvocationId,event_actor_depth: 1,}),@@ -5227,6 +5245,13 @@ class AgentClient extends BaseClient {thread_id: this.conversationId,checkpoint_ns: '',[LIBRECHAT_CHECKPOINT_NAMESPACE_KEY]: this.checkpointNamespace,+ [LIBRECHAT_CHECKPOINT_STORAGE_OWNER_KEY]:+ (this.user ?? this.options.req.user?.id)+ ? checkpointOwnerNamespacePrefix(+ this.user ?? this.options.req.user?.id,+ resolveRequestTenantId(this.options.req),+ )+ : undefined,last_agent_index: this.agentConfigs?.size ?? 0,user_id: this.user ?? this.options.req.user?.id,hide_sequential_outputs: this.options.agent.hide_sequential_outputs,diff --git a/api/server/controllers/agents/request.js b/api/server/controllers/agents/request.jsindex cfa0a383f2..274d5bed74 100644--- a/api/server/controllers/agents/request.js+++ b/api/server/controllers/agents/request.js@@ -1503,6 +1503,9 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTitjobCreatedAt,status,conversationId,+ ...(status === 'requires_action' && client?.checkpointNamespace != null+ ? { checkpointNamespace: client.checkpointNamespace }+ : {}),clearConversationId,error,});diff --git a/api/server/controllers/agents/resume.js b/api/server/controllers/agents/resume.jsindex 484ae01d7e..44101537da 100644--- a/api/server/controllers/agents/resume.js+++ b/api/server/controllers/agents/resume.js@@ -1977,6 +1977,7 @@ const ResumeAgentController = async (req, res, next, initializeClient, addTitle)jobCreatedAt: job.createdAt,status: 'requires_action',conversationId,+ checkpointNamespace: client.checkpointNamespace,});}} else {diff --git a/api/server/routes/__test-utils__/convos-route-mocks.js b/api/server/routes/__test-utils__/convos-route-mocks.jsindex 579e64656a..b4e9270f61 100644--- a/api/server/routes/__test-utils__/convos-route-mocks.js+++ b/api/server/routes/__test-utils__/convos-route-mocks.js@@ -1,6 +1,6 @@const archiveAllHandler = jest.fn();const generationJobManager = {- getJob: jest.fn().mockResolvedValue(null),+ getCleanupJob: jest.fn().mockResolvedValue(null),abortJob: jest.fn().mockResolvedValue({ success: true }),getCleanupBlockingJobIdsForUser: jest.fn().mockResolvedValue([]),getCleanupBlockingJobIdsForConversations: jest.fn().mockResolvedValue([]),@@ -13,15 +13,60 @@ const moderateText = jest.fn((req, _res, next) => {});const messageIpLimiter = jest.fn((_req, _res, next) => next());const messageUserLimiter = jest.fn((_req, _res, next) => next());+const checkpointRows = [];+const deleteAgentCheckpoints = jest.fn(async (threadIds = []) => {+ for (let index = checkpointRows.length - 1; index >= 0; index -= 1) {+ if (threadIds.includes(checkpointRows[index].threadId)) {+ checkpointRows.splice(index, 1);+ }+ }+});+const ownerPrefix = (userId, tenantId) =>+ `lcg:v2:${require('crypto')+ .createHash('sha256')+ .update(JSON.stringify([tenantId ?? null, userId]))+ .digest('hex')}:`;+const deleteOwnedAgentCheckpoints = jest.fn(async (userId, tenantId, threadIds) => {+ for (let index = checkpointRows.length - 1; index >= 0; index -= 1) {+ const row = checkpointRows[index];+ if (+ (threadIds == null || threadIds.includes(row.threadId)) &&+ row.checkpointNamespace.startsWith(ownerPrefix(userId, tenantId))+ ) {+ checkpointRows.splice(index, 1);+ }+ }+});+const deletionTargets = new Map();+const openCheckpointDeletion = jest.fn(async (userId, tenantId, root, cfg) => {+ const key = JSON.stringify([userId, tenantId, root]);+ const ids = deletionTargets.get(key) ?? new Set();+ deletionTargets.set(key, ids);+ return {+ conversationIds: () => [...ids],+ remember: async (targets) => targets.forEach((id) => ids.add(id)),+ cleanup: async () =>+ deleteOwnedAgentCheckpoints(userId, tenantId, root == null ? undefined : [...ids], cfg),+ acknowledge: async () => deletionTargets.delete(key),+ };+});++function resetCheckpointRows(rows = []) {+ checkpointRows.splice(0, checkpointRows.length, ...rows);+ deletionTargets.clear();+}module.exports = {archiveAllHandler,+ ownerPrefix,generationJobManager,subagentActivityHandlerInputs,moderateText,moderatedTexts,messageIpLimiter,messageUserLimiter,+ checkpointRows,+ resetCheckpointRows,agents: () => ({ sleep: jest.fn() }),@@ -96,6 +141,9 @@ module.exports = {() => (_req, res) => res.status(200).json({ threads: [] }),),GenerationJobManager: generationJobManager,+ waitForGenerationPersistence: jest.requireActual(+ '../../../../packages/api/src/stream/persistence.ts',+ ).waitForGenerationPersistence,isStopConfirmed: jest.fn((result) => result?.success === true || result?.failureReason === 'already_settled',),@@ -105,7 +153,9 @@ module.exports = {}),deleteConvoSharedLinksWithCleanup: jest.fn(),deleteAllSharedLinksWithCleanup: jest.fn(),- deleteAgentCheckpoints: jest.fn(),+ deleteAgentCheckpoints,+ deleteOwnedAgentCheckpoints,+ openCheckpointDeletion,isConversationImportError: jest.fn((error) => error?.name === 'ConversationImportError'),...overrides,}),diff --git a/api/server/routes/__tests__/convos.spec.js b/api/server/routes/__tests__/convos.spec.jsindex b17bf098dd..535e5cd440 100644--- a/api/server/routes/__tests__/convos.spec.js+++ b/api/server/routes/__tests__/convos.spec.js@@ -10,6 +10,8 @@ const {messageIpLimiter,messageUserLimiter,subagentActivityHandlerInputs,+ checkpointRows,+ resetCheckpointRows,} = require(MOCKS);const priorLimitMessageIp = process.env.LIMIT_MESSAGE_IP;@@ -17,6 +19,9 @@ const priorLimitMessageUser = process.env.LIMIT_MESSAGE_USER;process.env.LIMIT_MESSAGE_IP = 'true';process.env.LIMIT_MESSAGE_USER = 'true';+const checkpointNamespace = (id) =>+ `${require(MOCKS).ownerPrefix('test-user-123')}00000000-0000-4000-8000-${String(id).padStart(12, '0')}`;+jest.mock('@librechat/agents', () => require(MOCKS).agents());jest.mock('@librechat/api', () =>require(MOCKS).api({@@ -61,7 +66,7 @@ describe('Convos Routes', () => {saveConvo,} = require('~/models');const {- deleteAgentCheckpoints,+ deleteOwnedAgentCheckpoints,deleteAllSharedLinksWithCleanup,deleteConvoSharedLinksWithCleanup,} = require('@librechat/api');@@ -76,6 +81,10 @@ describe('Convos Routes', () => {/** Mock authenticated user */app.use((req, res, next) => {req.user = { id: 'test-user-123', role: 'USER' };+ const tenantId = req.get('x-test-tenant');+ if (tenantId) {+ req.user.tenantId = tenantId;+ }req.config = {messageFilter: {pii: {@@ -107,10 +116,11 @@ describe('Convos Routes', () => {beforeEach(() => {jest.clearAllMocks();moderatedTexts.length = 0;- generationJobManager.getJob.mockResolvedValue(null);+ generationJobManager.getCleanupJob.mockResolvedValue(null);generationJobManager.abortJob.mockResolvedValue({ success: true });generationJobManager.getCleanupBlockingJobIdsForUser.mockResolvedValue([]);generationJobManager.getCleanupBlockingJobIdsForConversations.mockResolvedValue([]);+ resetCheckpointRows();});it('binds the activity subscription adapter to the subagent task store', () => {@@ -456,18 +466,35 @@ describe('Convos Routes', () => {});describe('DELETE /all', () => {- it('prunes the deleted conversations’ agent checkpoints (bulk, ids from deleteConvos)', async () => {- // HITL: a paused conversation's durable checkpoint must not outlive the conversation.+ it('prunes the deleted conversations’ owned generation checkpoint scopes', async () => {+ // Generation-scoped checkpoints are removed eagerly after their ownership is proven.const conversationIds = ['conv-a', 'conv-b'];- deleteConvos.mockResolvedValue({ deletedCount: 2, conversationIds });+ deleteConvos.mockImplementation(async (_userId, _filter, options) => {+ await options.beforeDelete?.(conversationIds);+ return { deletedCount: 2, conversationIds };+ });deleteToolCalls.mockResolvedValue({ deletedCount: 0 });deleteAllSharedLinksWithCleanup.mockResolvedValue({ deletedCount: 0 });+ generationJobManager.getCleanupJob.mockImplementation(async (conversationId) => ({+ metadata: {+ userId: 'test-user-123',+ conversationId,+ checkpointNamespace: checkpointNamespace(conversationId === 'conv-a' ? 1 : 2),+ generationProtocolVersion: 2,+ },+ status: 'complete',+ createdAt: Date.now(),+ }));const response = await request(app).delete('/api/convos/all');expect(response.status).toBe(201);- expect(deleteAgentCheckpoints).toHaveBeenCalledTimes(1);- expect(deleteAgentCheckpoints.mock.calls[0][0]).toEqual(conversationIds);+ expect(deleteOwnedAgentCheckpoints).toHaveBeenCalledWith(+ 'test-user-123',+ undefined,+ undefined,+ undefined,+ );/** The deletion runs inside the owner admission fence, not around it. */expect(subagentThreadStore.withOwnerDeletionFence).toHaveBeenCalledTimes(1);const [fencedUserId, fencedTenantId] =@@ -486,7 +513,7 @@ describe('Convos Routes', () => {deletedCount: 1,conversationIds: ['paused-event-child'],});- generationJobManager.getJob.mockImplementation(async (conversationId) =>+ generationJobManager.getCleanupJob.mockImplementation(async (conversationId) =>conversationId === 'paused-event-child'? {metadata: { userId: 'test-user-123' },@@ -510,7 +537,7 @@ describe('Convos Routes', () => {generationJobManager.getCleanupBlockingJobIdsForUser.mockResolvedValue(['resp-new-conversation',]);- generationJobManager.getJob.mockImplementation(async (streamId) =>+ generationJobManager.getCleanupJob.mockImplementation(async (streamId) =>streamId === 'resp-new-conversation'? {conversationId: 'conversation-not-yet-persisted',@@ -546,9 +573,18 @@ describe('Convos Routes', () => {generationJobManager.getCleanupBlockingJobIdsForUser.mockResolvedValueOnce([]).mockResolvedValueOnce(['resp-gap']);- generationJobManager.getJob.mockImplementation(async (streamId) =>+ generationJobManager.getCleanupJob.mockImplementation(async (streamId) =>streamId === 'resp-gap'- ? { metadata: { userId: 'test-user-123' }, status: 'running', createdAt }+ ? {+ metadata: {+ userId: 'test-user-123',+ conversationId: 'gap-conversation',+ checkpointNamespace: checkpointNamespace(3),+ generationProtocolVersion: 2,+ },+ status: 'running',+ createdAt,+ }: null,);deleteConvos@@ -557,7 +593,7 @@ describe('Convos Routes', () => {expect(options).toEqual(expect.objectContaining({ allowEmpty: true, beforeDelete: expect.any(Function) }),);- await options.beforeDelete(['gap-conversation']);+ await options.beforeDelete?.(['gap-conversation']);return { deletedCount: 1, conversationIds: ['gap-conversation'] };});subagentThreadStore.withOwnerDeletionFence.mockImplementationOnce(@@ -575,12 +611,16 @@ describe('Convos Routes', () => {expectedCreatedAt: createdAt,awaitProviderDrain: true,});- expect(deleteConvos).toHaveBeenCalledTimes(2);+ expect(+ deleteConvos.mock.calls.filter(([, filter]) => Object.keys(filter).length === 0),+ ).toHaveLength(2);expect(deleteMessages).toHaveBeenCalledWith({ user: 'test-user-123' });- expect(deleteAgentCheckpoints.mock.calls.map((call) => call[0])).toEqual([- ['original'],- ['gap-conversation'],- ]);+ expect(deleteOwnedAgentCheckpoints).toHaveBeenCalledWith(+ 'test-user-123',+ undefined,+ undefined,+ undefined,+ );});it('retries owner message cleanup after conversations were already removed', async () => {@@ -596,14 +636,17 @@ describe('Convos Routes', () => {expect(first.status).toBe(500);expect(retry.status).toBe(201);- expect(deleteAgentCheckpoints.mock.calls[0][0]).toEqual(['original']);- expect(deleteConvos).toHaveBeenNthCalledWith(- 2,+ expect(deleteOwnedAgentCheckpoints).toHaveBeenCalledWith(+ 'test-user-123',+ undefined,+ undefined,+ undefined,+ );+ expect(deleteConvos).toHaveBeenCalledWith('test-user-123',{},expect.objectContaining({ allowEmpty: true }),);- expect(deleteMessages).toHaveBeenCalledTimes(2);expect(deleteMessages).toHaveBeenLastCalledWith({ user: 'test-user-123' });});@@ -623,7 +666,7 @@ describe('Convos Routes', () => {const response = await request(app).delete('/api/convos/all');expect(response.status).toBe(201);- expect(response.body).toEqual(mockDbResponse);+ expect(response.body).toMatchObject(mockDbResponse);/** Verify deleteConvos was called with correct userId */expect(deleteConvos).toHaveBeenCalledWith(@@ -685,7 +728,7 @@ describe('Convos Routes', () => {expect(response.status).toBe(500);expect(deleteConvos).not.toHaveBeenCalled();- expect(deleteAgentCheckpoints).not.toHaveBeenCalled();+ expect(deleteOwnedAgentCheckpoints).not.toHaveBeenCalled();expect(deleteToolCalls).not.toHaveBeenCalled();expect(deleteAllSharedLinksWithCleanup).not.toHaveBeenCalled();});@@ -822,7 +865,7 @@ describe('Convos Routes', () => {it('drains owner remote runs before the empty-filter deletion snapshot', async () => {const createdAt = Date.now();generationJobManager.getCleanupBlockingJobIdsForUser.mockResolvedValue(['resp-new']);- generationJobManager.getJob.mockImplementation(async (streamId) =>+ generationJobManager.getCleanupJob.mockImplementation(async (streamId) =>streamId === 'resp-new'? { metadata: { userId: 'test-user-123' }, status: 'running', createdAt }: null,@@ -852,7 +895,7 @@ describe('Convos Routes', () => {deletedCount: 1,conversationIds: ['paused-event-child'],});- generationJobManager.getJob.mockImplementation(async (conversationId) =>+ generationJobManager.getCleanupJob.mockImplementation(async (conversationId) =>conversationId === 'paused-event-child'? {metadata: { userId: 'test-user-123' },@@ -875,21 +918,23 @@ describe('Convos Routes', () => {it('fails closed before checkpoint pruning when generation lookup stays unavailable', async () => {deleteConvos.mockImplementation(async (_userId, _filter, options) => {- await options.beforeDelete(['paused-event-child']);+ await options.beforeDelete?.(['paused-event-child']);return {deletedCount: 1,conversationIds: ['paused-event-child'],};});- generationJobManager.getJob.mockRejectedValue(new Error('generation store unavailable'));+ generationJobManager.getCleanupJob.mockRejectedValue(+ new Error('generation store unavailable'),+ );const response = await request(app).delete('/api/convos').send({ arg: { thread_id: 'thread-abc' } });expect(response.status).toBe(500);- expect(generationJobManager.getJob).toHaveBeenCalledTimes(3);- expect(deleteAgentCheckpoints).not.toHaveBeenCalled();+ expect(generationJobManager.getCleanupJob).toHaveBeenCalledTimes(3);+ expect(deleteOwnedAgentCheckpoints).not.toHaveBeenCalled();});it('cancels root and descendant leases and cleans every cascaded conversation', async () => {@@ -939,7 +984,7 @@ describe('Convos Routes', () => {deletedCount: 2,conversationIds: ['parent-conversation', 'child-conversation'],});- generationJobManager.getJob.mockImplementation(async (conversationId) =>+ generationJobManager.getCleanupJob.mockImplementation(async (conversationId) =>conversationId === 'child-conversation'? { metadata: { userId: 'test-user-123' }, status: 'running', createdAt }: null,@@ -958,7 +1003,7 @@ describe('Convos Routes', () => {2,'test-user-123',{ conversationId: { $in: ['parent-conversation', 'child-conversation'] } },- { allowEmpty: true },+ expect.objectContaining({ allowEmpty: true }),);expect(deleteMessages).toHaveBeenCalledWith({user: 'test-user-123',@@ -971,13 +1016,13 @@ describe('Convos Routes', () => {generationJobManager.getCleanupBlockingJobIdsForConversations.mockResolvedValue(['resp_remote-run',]);- generationJobManager.getJob.mockImplementation(async (streamId) =>+ generationJobManager.getCleanupJob.mockImplementation(async (streamId) =>streamId === 'resp_remote-run'? { metadata: { userId: 'test-user-123' }, status: 'running', createdAt }: null,);deleteConvos.mockImplementationOnce(async (_userId, _filter, options) => {- await options.beforeDelete(['conversation-1']);+ await options.beforeDelete?.(['conversation-1']);return { deletedCount: 1, conversationIds: ['conversation-1'] };});@@ -997,12 +1042,279 @@ describe('Convos Routes', () => {});});+ it('preserves foreign and legacy checkpoints when conversation IDs collide', async () => {+ const conversationIds = ['conversation-1', 'child-conversation'];+ const jobs = {+ 'resp-owned': {+ metadata: {+ userId: 'test-user-123',+ conversationId: 'conversation-1',+ checkpointNamespace: checkpointNamespace(4),+ generationProtocolVersion: 2,+ },+ },+ 'task-owned-child': {+ metadata: {+ userId: 'test-user-123',+ conversationId: 'child-conversation',+ checkpointNamespace: checkpointNamespace(5),+ generationProtocolVersion: 2,+ },+ },+ 'resp-foreign-user': {+ metadata: {+ userId: 'foreign-user',+ conversationId: 'conversation-1',+ checkpointNamespace: 'foreign-user-generation',+ generationProtocolVersion: 2,+ },+ },+ 'resp-foreign-tenant': {+ metadata: {+ userId: 'test-user-123',+ tenantId: 'foreign-tenant',+ conversationId: 'conversation-1',+ checkpointNamespace: 'foreign-tenant-generation',+ generationProtocolVersion: 2,+ },+ },+ 'resp-legacy': {+ metadata: {+ userId: 'test-user-123',+ conversationId: 'conversation-1',+ checkpointNamespace: '',+ generationProtocolVersion: 1,+ },+ },+ };+ resetCheckpointRows([+ { threadId: 'conversation-1', checkpointNamespace: checkpointNamespace(4) },+ {+ threadId: 'conversation-1',+ checkpointNamespace: `${checkpointNamespace(4)}|subgraph`,+ },+ { threadId: 'child-conversation', checkpointNamespace: checkpointNamespace(5) },+ { threadId: 'conversation-1', checkpointNamespace: 'foreign-user-generation' },+ { threadId: 'conversation-1', checkpointNamespace: 'foreign-tenant-generation' },+ { threadId: 'conversation-1', checkpointNamespace: '' },+ ]);+ generationJobManager.getCleanupBlockingJobIdsForConversations.mockResolvedValue(+ Object.keys(jobs),+ );+ generationJobManager.getCleanupJob.mockImplementation(async (streamId) => {+ const job = jobs[streamId];+ return job == null ? null : { ...job, status: 'complete', createdAt: Date.now() };+ });+ deleteConvos.mockImplementationOnce(async (_userId, _filter, options) => {+ await options.beforeDelete?.(conversationIds);+ return { deletedCount: 2, conversationIds };+ });++ const response = await request(app)+ .delete('/api/convos')+ .send({ arg: { conversationId: 'conversation-1' } });++ expect(response.status).toBe(201);+ expect(checkpointRows).toEqual([+ { threadId: 'conversation-1', checkpointNamespace: 'foreign-user-generation' },+ { threadId: 'conversation-1', checkpointNamespace: 'foreign-tenant-generation' },+ { threadId: 'conversation-1', checkpointNamespace: '' },+ ]);+ expect(deleteOwnedAgentCheckpoints).toHaveBeenCalledWith(+ 'test-user-123',+ undefined,+ ['conversation-1', 'child-conversation'],+ undefined,+ );+ });++ it('deletes an owned checkpoint after its terminal job hash expires', async () => {+ const scope = {+ threadId: 'conversation-1',+ checkpointNamespace: checkpointNamespace(8),+ };+ resetCheckpointRows([scope]);+ deleteConvos.mockImplementationOnce(async (_userId, _filter, options) => {+ await options.beforeDelete?.(['conversation-1']);+ return { deletedCount: 1, conversationIds: ['conversation-1'] };+ });++ const response = await request(app)+ .delete('/api/convos')+ .send({ arg: { conversationId: 'conversation-1' } });++ expect(response.status).toBe(201);+ expect(checkpointRows).toEqual([]);+ expect(deleteOwnedAgentCheckpoints).toHaveBeenCalledWith(+ 'test-user-123',+ undefined,+ ['conversation-1'],+ undefined,+ );+ });++ it('retains checkpoint payload when conversation deletion fails after its snapshot', async () => {+ const scope = { threadId: 'conversation-1', checkpointNamespace: checkpointNamespace(8) };+ resetCheckpointRows([scope]);+ deleteConvos.mockImplementationOnce(async (_owner, _filter, options) => {+ await options.beforeDelete(['conversation-1']);+ throw new Error('conversation deletion failed');+ });+ const response = await request(app)+ .delete('/api/convos')+ .send({ arg: { conversationId: 'conversation-1' } });+ expect(response.status).toBe(500);+ expect(deleteOwnedAgentCheckpoints).not.toHaveBeenCalled();+ expect(checkpointRows).toEqual([scope]);+ });++ it('fails closed when saver deletion fails', async () => {+ deleteOwnedAgentCheckpoints.mockRejectedValueOnce(new Error('checkpoint store unavailable'));+ deleteConvos.mockImplementationOnce(async (_userId, _filter, options) => {+ await options.beforeDelete?.(['conversation-1']);+ return { deletedCount: 1, conversationIds: ['conversation-1'] };+ });++ const response = await request(app)+ .delete('/api/convos')+ .send({ arg: { conversationId: 'conversation-1' } });++ expect(response.status).toBe(500);+ });++ it('retries checkpoint cleanup for descendants after all conversation records are gone', async () => {+ deleteOwnedAgentCheckpoints.mockRejectedValueOnce(new Error('post-delete cleanup failed'));+ deleteConvos+ .mockImplementationOnce(async (_owner, _filter, options) => {+ await options.beforeDelete(['conversation-1', 'child-conversation']);+ return { deletedCount: 2, conversationIds: ['conversation-1', 'child-conversation'] };+ })+ .mockResolvedValue({ deletedCount: 0, conversationIds: [] });+ const first = await request(app)+ .delete('/api/convos')+ .send({ arg: { conversationId: 'conversation-1' } });+ expect(first.status).toBe(500);+ checkpointRows.push({+ threadId: 'child-conversation',+ checkpointNamespace: checkpointNamespace(13),+ });+ // Restore only a late checkpoint; the deletion intent must remain from the first request.+ const second = await request(app)+ .delete('/api/convos')+ .send({ arg: { conversationId: 'conversation-1' } });+ expect(second.status).toBe(201);+ expect(deleteOwnedAgentCheckpoints).toHaveBeenLastCalledWith(+ 'test-user-123',+ undefined,+ ['conversation-1', 'child-conversation'],+ undefined,+ );+ expect(checkpointRows).toEqual([]);+ });++ it('cleans checkpoints from every cascade wave', async () => {+ const jobs = {+ 'run-parent': {+ metadata: {+ userId: 'test-user-123',+ conversationId: 'parent-conversation',+ checkpointNamespace: checkpointNamespace(11),+ generationProtocolVersion: 2,+ },+ },+ 'run-child': {+ metadata: {+ userId: 'test-user-123',+ conversationId: 'child-conversation',+ checkpointNamespace: checkpointNamespace(12),+ generationProtocolVersion: 2,+ },+ },+ };+ generationJobManager.getCleanupBlockingJobIdsForConversations.mockImplementation(+ async (_userId, conversationIds) =>+ conversationIds.map((conversationId) =>+ conversationId === 'parent-conversation' ? 'run-parent' : 'run-child',+ ),+ );+ generationJobManager.getCleanupJob.mockImplementation(async (streamId) => {+ const job = jobs[streamId];+ return job == null ? null : { ...job, status: 'complete', createdAt: Date.now() };+ });+ deleteConvos+ .mockImplementationOnce(async (_userId, _filter, options) => {+ await options.beforeDelete?.(['parent-conversation']);+ await options.beforeDelete?.(['child-conversation']);+ return {+ deletedCount: 2,+ conversationIds: ['parent-conversation', 'child-conversation'],+ };+ })+ .mockResolvedValueOnce({ deletedCount: 0, conversationIds: [] });++ const response = await request(app)+ .delete('/api/convos')+ .send({ arg: { conversationId: 'parent-conversation' } });++ expect(response.status).toBe(201);+ expect(deleteOwnedAgentCheckpoints).toHaveBeenCalledWith(+ 'test-user-123',+ undefined,+ ['parent-conversation', 'child-conversation'],+ undefined,+ );+ });++ it('drains a tenant user legacy generation without pruning its ambiguous namespace', async () => {+ const createdAt = Date.now();+ generationJobManager.getCleanupBlockingJobIdsForConversations.mockResolvedValue([+ 'legacy-run',+ ]);+ generationJobManager.getCleanupJob.mockImplementation(async (streamId) =>+ streamId === 'legacy-run'+ ? {+ metadata: {+ userId: 'test-user-123',+ conversationId: 'conversation-1',+ checkpointNamespace: 'legacy-tenant-generation',+ generationProtocolVersion: 2,+ },+ status: 'running',+ createdAt,+ }+ : null,+ );+ deleteConvos+ .mockImplementationOnce(async (_userId, _filter, options) => {+ await options.beforeDelete?.(['conversation-1']);+ return { deletedCount: 1, conversationIds: ['conversation-1'] };+ })+ .mockResolvedValueOnce({ deletedCount: 0, conversationIds: [] });++ const response = await request(app)+ .delete('/api/convos')+ .set('x-test-tenant', 'tenant-1')+ .send({ arg: { conversationId: 'conversation-1' } });++ expect(response.status).toBe(201);+ expect(generationJobManager.abortJob).toHaveBeenCalledWith('legacy-run', {+ expectedCreatedAt: createdAt,+ awaitProviderDrain: true,+ });+ expect(deleteOwnedAgentCheckpoints).toHaveBeenCalledWith(+ 'test-user-123',+ 'tenant-1',+ ['conversation-1'],+ undefined,+ );+ });+it('waits for terminal response-id runs whose provider writes are undrained', async () => {const createdAt = Date.now();generationJobManager.getCleanupBlockingJobIdsForConversations.mockResolvedValue(['resp_terminal-run',]);- generationJobManager.getJob.mockImplementation(async (streamId) =>+ generationJobManager.getCleanupJob.mockImplementation(async (streamId) =>streamId === 'resp_terminal-run'? {metadata: { userId: 'test-user-123', providerDrained: false },@@ -1012,7 +1324,7 @@ describe('Convos Routes', () => {: null,);deleteConvos.mockImplementationOnce(async (_userId, _filter, options) => {- await options.beforeDelete(['conversation-1']);+ await options.beforeDelete?.(['conversation-1']);return { deletedCount: 1, conversationIds: ['conversation-1'] };});@@ -1033,13 +1345,13 @@ describe('Convos Routes', () => {generationJobManager.getCleanupBlockingJobIdsForConversations.mockImplementation(async () =>deletionCommitted ? ['resp_late-run'] : [],);- generationJobManager.getJob.mockImplementation(async (streamId) =>+ generationJobManager.getCleanupJob.mockImplementation(async (streamId) =>streamId === 'resp_late-run'? { metadata: { userId: 'test-user-123' }, status: 'running', createdAt }: null,);deleteConvos.mockImplementationOnce(async (_userId, _filter, options) => {- await options.beforeDelete(['conversation-1']);+ await options.beforeDelete?.(['conversation-1']);deletionCommitted = true;return { deletedCount: 1, conversationIds: ['conversation-1'] };});@@ -1061,7 +1373,7 @@ describe('Convos Routes', () => {it('removes persistence even when a racing response drains before post-delete discovery', async () => {deleteConvos.mockImplementationOnce(async (_userId, _filter, options) => {- await options.beforeDelete(['conversation-1']);+ await options.beforeDelete?.(['conversation-1']);return { deletedCount: 1, conversationIds: ['conversation-1'] };}).mockResolvedValueOnce({ deletedCount: 1, conversationIds: ['conversation-1'] });@@ -1077,7 +1389,7 @@ describe('Convos Routes', () => {2,'test-user-123',{ conversationId: { $in: ['conversation-1'] } },- { allowEmpty: true },+ expect.objectContaining({ allowEmpty: true }),);expect(deleteMessages).toHaveBeenCalledWith({user: 'test-user-123',@@ -1088,7 +1400,7 @@ describe('Convos Routes', () => {it('fails closed when the idempotent remnant sweep hits a storage failure', async () => {deleteConvos.mockImplementationOnce(async (_userId, _filter, options) => {- await options.beforeDelete(['conversation-1']);+ await options.beforeDelete?.(['conversation-1']);return { deletedCount: 1, conversationIds: ['conversation-1'] };}).mockRejectedValueOnce(new Error('remnant database unavailable'));@@ -1099,13 +1411,13 @@ describe('Convos Routes', () => {expect(response.status).toBe(500);expect(response.text).toBe('Error clearing conversations');- expect(deleteAgentCheckpoints).not.toHaveBeenCalled();+ expect(deleteOwnedAgentCheckpoints).not.toHaveBeenCalled();});it('fails closed when remnant message cleanup is unavailable', async () => {deleteConvos.mockImplementationOnce(async (_userId, _filter, options) => {- await options.beforeDelete(['conversation-1']);+ await options.beforeDelete?.(['conversation-1']);return { deletedCount: 1, conversationIds: ['conversation-1'] };}).mockResolvedValueOnce({ deletedCount: 0, conversationIds: [] });@@ -1117,21 +1429,21 @@ describe('Convos Routes', () => {expect(response.status).toBe(500);expect(response.text).toBe('Error clearing conversations');- expect(deleteAgentCheckpoints).not.toHaveBeenCalled();+ expect(deleteOwnedAgentCheckpoints).not.toHaveBeenCalled();});it('does not prune generation persistence when provider stop is unconfirmed', async () => {const createdAt = Date.now();let deletionCommitted = false;deleteConvos.mockImplementation(async (_userId, _filter, options) => {- await options.beforeDelete(['child-conversation']);+ await options.beforeDelete?.(['child-conversation']);deletionCommitted = true;return {deletedCount: 2,conversationIds: ['parent-conversation', 'child-conversation'],};});- generationJobManager.getJob.mockImplementation(async (conversationId) =>+ generationJobManager.getCleanupJob.mockImplementation(async (conversationId) =>conversationId === 'child-conversation'? { metadata: { userId: 'test-user-123' }, status: 'running', createdAt }: null,@@ -1151,55 +1463,60 @@ describe('Convos Routes', () => {expect(deleteMessages).not.toHaveBeenCalled();});- it('drains terminal persistence only for leases removed by this deletion', async () => {- const createdAt = Date.now();- deleteConvos.mockResolvedValue({- deletedCount: 2,- conversationIds: ['parent-conversation', 'child-conversation'],- });- subagentThreadStore.planCancellationForConversations.mockResolvedValueOnce({- userId: 'test-user-123',- conversationIds: ['parent-conversation'],- scopes: [],- leases: [- {- taskId: 'related-generation',- parentConversationId: 'parent-conversation',- conversationId: 'child-conversation',- },- {- taskId: 'unrelated-generation',- parentConversationId: 'other-parent',- conversationId: 'other-child',- },- ],- });- let relatedReads = 0;- generationJobManager.getJob.mockImplementation(async (conversationId) => {- if (conversationId !== 'related-generation') return null;- relatedReads += 1;- return {- status: 'complete',- createdAt,- metadata: {- userId: 'test-user-123',- terminalPersistencePending: relatedReads === 1,- },- };- });+ it.each(['terminalPersistencePending', 'terminalHostActionPending'])(+ 'drains %s only for leases removed by this deletion',+ async (marker) => {+ const createdAt = Date.now();+ deleteConvos.mockResolvedValue({+ deletedCount: 2,+ conversationIds: ['parent-conversation', 'child-conversation'],+ });+ subagentThreadStore.planCancellationForConversations.mockResolvedValueOnce({+ userId: 'test-user-123',+ conversationIds: ['parent-conversation'],+ scopes: [],+ leases: [+ {+ taskId: 'related-generation',+ parentConversationId: 'parent-conversation',+ conversationId: 'child-conversation',+ },+ {+ taskId: 'unrelated-generation',+ parentConversationId: 'other-parent',+ conversationId: 'other-child',+ },+ ],+ });+ let relatedReads = 0;+ generationJobManager.getCleanupJob.mockImplementation(async (conversationId) => {+ if (conversationId !== 'related-generation') return null;+ relatedReads += 1;+ return {+ status: 'complete',+ createdAt,+ metadata: {+ userId: 'test-user-123',+ providerDrained: true,+ [marker]: relatedReads <= 2,+ },+ };+ });- const response = await request(app)- .delete('/api/convos')- .send({ arg: { conversationId: 'parent-conversation' } });+ const response = await request(app)+ .delete('/api/convos')+ .send({ arg: { conversationId: 'parent-conversation' } });- expect(response.status).toBe(201);- expect(generationJobManager.abortJob).toHaveBeenCalledWith('related-generation', {- expectedCreatedAt: createdAt,- awaitProviderDrain: true,- });- expect(generationJobManager.getJob).not.toHaveBeenCalledWith('unrelated-generation');- expect(deleteConvos).toHaveBeenCalledTimes(2);- });+ expect(response.status).toBe(201);+ expect(generationJobManager.abortJob).toHaveBeenCalledWith('related-generation', {+ expectedCreatedAt: createdAt,+ awaitProviderDrain: true,+ });+ expect(relatedReads).toBeGreaterThanOrEqual(3);+ expect(generationJobManager.getCleanupJob).not.toHaveBeenCalledWith('unrelated-generation');+ expect(deleteConvos).toHaveBeenCalledTimes(2);+ },+ );it('should delete a single conversation, tool calls, and associated shared links', async () => {const mockConversationId = 'conv-123';@@ -1224,7 +1541,7 @@ describe('Convos Routes', () => {});expect(response.status).toBe(201);- expect(response.body).toEqual(mockDbResponse);+ expect(response.body).toMatchObject(mockDbResponse);/** Verify deleteConvos was called with correct parameters */expect(deleteConvos).toHaveBeenCalledWith(diff --git a/api/server/routes/convos.js b/api/server/routes/convos.jsindex 4bbd4f4adf..3183e26e3c 100644--- a/api/server/routes/convos.js+++ b/api/server/routes/convos.js@@ -4,7 +4,8 @@ const { sleep } = require('@librechat/agents');const {isEnabled,normalizeLimit,- deleteAgentCheckpoints,+ openCheckpointDeletion,+ waitForGenerationPersistence,createArchiveAllHandler,createSubagentActivityStreamHandler,createSubagentControlHandler,@@ -240,15 +241,13 @@ router.get('/gen_title/:conversationId', async (req, res) => {const POST_DELETE_CANCEL_ATTEMPTS = 3;const POST_DELETE_CANCEL_BACKOFF_MS = 250;-const GENERATION_PERSISTENCE_DRAIN_TIMEOUT_MS = 45_000;-const GENERATION_PERSISTENCE_DRAIN_POLL_MS = 100;const GENERATION_LOOKUP_ATTEMPTS = 3;async function readGenerationForDeletion(conversationId) {let lastError;for (let attempt = 1; attempt <= GENERATION_LOOKUP_ATTEMPTS; attempt += 1) {try {- return await GenerationJobManager.getJob(conversationId);+ return await GenerationJobManager.getCleanupJob(conversationId);} catch (error) {lastError = error;if (attempt < GENERATION_LOOKUP_ATTEMPTS) {@@ -284,7 +283,6 @@ async function confirmAgentGenerationsDrained(tenantId,ownerWide = false,) {- let foundActiveGeneration = false;const drainErrors = [];let conversationRunIds;try {@@ -307,20 +305,23 @@ async function confirmAgentGenerationsDrained(job = await readGenerationForDeletion(conversationId);} catch (error) {logger.warn('Deleted child generation lookup failed', error);- foundActiveGeneration = true;drainErrors.push(error);return;}if (job == null || job.metadata?.userId !== userId) {return;}+ const jobTenantId = job.metadata?.tenantId;+ if (jobTenantId != null && jobTenantId !== tenantId) {+ return;+ }const needsDrain =job.status === 'running' ||job.status === 'requires_action' ||job.metadata?.providerDrained === false ||- job.metadata?.terminalPersistencePending === true;+ job.metadata?.terminalPersistencePending === true ||+ job.metadata?.terminalHostActionPending === true;if (!needsDrain) return;- foundActiveGeneration = true;try {const abortResult = await GenerationJobManager.abortJob(conversationId, {expectedCreatedAt: job.createdAt,@@ -331,43 +332,44 @@ async function confirmAgentGenerationsDrained(`Could not confirm generation stop for ${conversationId}: ${abortResult?.failureReason ?? 'unknown'}`,);}- const deadline = Date.now() + GENERATION_PERSISTENCE_DRAIN_TIMEOUT_MS;- while (true) {- const current = await GenerationJobManager.getJob(conversationId);- if (- current == null ||- current.createdAt !== job.createdAt ||- current.metadata?.terminalPersistencePending !== true- ) {- break;- }- if (Date.now() >= deadline) {- throw new Error(`Timed out waiting for generation persistence: ${conversationId}`);- }- await new Promise((resolve) => setTimeout(resolve, GENERATION_PERSISTENCE_DRAIN_POLL_MS));- }+ await waitForGenerationPersistence(conversationId, job.createdAt, (id) =>+ GenerationJobManager.getCleanupJob(id),+ );} catch (error) {logger.warn('Deleted child generation drain failed', error);drainErrors.push(error);}}),);- if (!foundActiveGeneration) {- return false;- }if (drainErrors.length > 0) {throw new Error('One or more deleted child generations could not be confirmed drained.');}- return true;}/** Repeats generation discovery after the conversation wave is gone, then always* removes remnants for that immutable deletion set. A remote run may settle and* leave the cleanup index between persisting and this lookup; absence from the* index is therefore not evidence that the second persistence sweep is unnecessary. */-async function drainDeletedAgentGenerations(userId, conversationIds, leaseTaskIds = [], tenantId) {+async function drainDeletedAgentGenerations(+ userId,+ conversationIds,+ leaseTaskIds = [],+ tenantId,+ deletion,+) {await confirmAgentGenerationsDrained(userId, conversationIds, leaseTaskIds, tenantId);- await db.deleteConvos(userId, { conversationId: { $in: conversationIds } }, { allowEmpty: true });+ await db.deleteConvos(+ userId,+ { conversationId: { $in: conversationIds } },+ {+ allowEmpty: true,+ beforeDelete: async (ids) => {+ await deletion?.remember(ids);+ await confirmAgentGenerationsDrained(userId, ids, [], tenantId);+ await deletion?.remember(ids);+ },+ },+ );await db.deleteMessages({ user: userId, conversationId: { $in: conversationIds } });}@@ -396,24 +398,33 @@ async function withAgentOwnerDeletionFence(userId, tenantId, deletion, recoverPe}async function deleteOwnerConversationPersistence(userId, filter, tenantId, checkpointer) {+ const deletion = await openCheckpointDeletion(userId, tenantId, undefined, checkpointer);const result = await db.deleteConvos(userId, filter, {allowEmpty: true,- beforeDelete: (conversationIds) =>- confirmAgentGenerationsDrained(userId, conversationIds, [], tenantId),+ beforeDelete: async (conversationIds) => {+ await deletion.remember(conversationIds);+ await confirmAgentGenerationsDrained(userId, conversationIds, [], tenantId);+ await deletion.remember(conversationIds);+ },});- /** Consume the deletion receipt before the fallible message sweep. A retry after- * conversations are gone cannot reconstruct these checkpoint identities. */- await deleteAgentCheckpoints(result.conversationIds ?? [], checkpointer);- /** Always runs, including an empty conversation retry, so an interrupted writer- * that persisted messages first cannot make its cleanup permanently unreachable. */+ const targets = [...new Set([...deletion.conversationIds(), ...(result.conversationIds ?? [])])];+ if (targets.length > 0) {+ await drainDeletedAgentGenerations(userId, targets, [], tenantId, deletion);+ }+ await deletion.cleanup();await db.deleteMessages({ user: userId });- return result;+ await deletion.acknowledge();+ return { ...result, conversationIds: targets };}router.delete('/', configMiddleware, async (req, res) => {let filter = {};const { conversationId, source, thread_id, endpoint } = req.body?.arg ?? {};+ if (conversationId != null && typeof conversationId !== 'string') {+ return res.status(400).json({ error: 'Invalid conversationId' });+ }+// Prevent deletion of all conversationsif (!conversationId && !source && !thread_id && !endpoint) {return res.status(400).json({@@ -448,20 +459,29 @@ router.delete('/', configMiddleware, async (req, res) => {: undefined;const checkpointer = req.config?.endpoints?.[EModelEndpoint.agents]?.checkpointer;let cancellationPlan;+ let checkpointDeletion;let dbResponse;- let recoveryConversationIds = [];if (filter.conversationId) {- /** Resolve the targets while the conversations still exist: the second pass- * runs after their rows are gone and can only reach registered owners. */+ checkpointDeletion = await openCheckpointDeletion(+ req.user.id,+ tenantId,+ filter.conversationId,+ checkpointer,+ );+ await checkpointDeletion.remember([filter.conversationId]);cancellationPlan = await subagentThreadTaskStore.planCancellationForConversations(req.user.id,- [filter.conversationId],+ checkpointDeletion.conversationIds(),tenantId,);await subagentThreadTaskStore.cancelPlan(cancellationPlan);dbResponse = await db.deleteConvos(req.user.id, filter, {- beforeDelete: (conversationIds) =>- confirmAgentGenerationsDrained(req.user.id, conversationIds, [], tenantId),+ allowEmpty: true,+ beforeDelete: async (conversationIds) => {+ await checkpointDeletion.remember(conversationIds);+ await confirmAgentGenerationsDrained(req.user.id, conversationIds, [], tenantId);+ await checkpointDeletion.remember(conversationIds);+ },});} else {/** An empty filter deletes every conversation this owner has, so it runs behind@@ -472,22 +492,20 @@ router.delete('/', configMiddleware, async (req, res) => {() => deleteOwnerConversationPersistence(req.user.id, filter, tenantId, checkpointer),() => deleteOwnerConversationPersistence(req.user.id, filter, tenantId, checkpointer),);- dbResponse = fencedDeletion.result;- recoveryConversationIds = fencedDeletion.recoveryConversationIds;+ return res.status(201).json(fencedDeletion.result);}- const deletedConversationIds = [+ let deletedConversationIds = [...new Set([...(dbResponse.conversationIds ?? (filter.conversationId ? [filter.conversationId] : [])),- ...recoveryConversationIds,+ ...(checkpointDeletion?.conversationIds() ?? []),]),];/** Root deletion closes new child admission. Replay the plan to catch a task* admitted after the first pass but before that fence, extended with the cascade* this deletion reported. */if (cancellationPlan != null && deletedConversationIds.length > 0) {- /** The conversations are gone, so this pass is the only thing that can still- * stop a child admitted after the first one. It cannot fail the request — the- * deletion already committed — so it retries briefly before giving up. */+ /** Confirm late children stopped before payload cleanup. A failed retry leaves+ * durable deletion intent available even though conversation deletion committed. */await retryPostDeleteCancellation(cancellationPlan, deletedConversationIds);await drainDeletedAgentGenerations(req.user.id,@@ -500,18 +518,26 @@ router.delete('/', configMiddleware, async (req, res) => {).map((lease) => lease.taskId),tenantId,+ checkpointDeletion,);} else if (deletedConversationIds.length > 0) {/** Owner-wide deletion drains lease-backed tasks before the cascade, but a* requires_action event actor has intentionally released its lease. Its durable* generation is still addressable by the deleted conversation id and must be* terminalized before its checkpoint is pruned. */- await drainDeletedAgentGenerations(req.user.id, deletedConversationIds, [], tenantId);+ await drainDeletedAgentGenerations(+ req.user.id,+ deletedConversationIds,+ [],+ tenantId,+ checkpointDeletion,+ );}- // HITL: prune the deleted conversations' durable checkpoints — a paused run's- // checkpoint would otherwise persist until the Mongo TTL. Never throws.- if (filter.conversationId) {- await deleteAgentCheckpoints(deletedConversationIds, checkpointer);+ deletedConversationIds = [+ ...new Set([...deletedConversationIds, ...(checkpointDeletion?.conversationIds() ?? [])]),+ ];+ if (checkpointDeletion != null) {+ await checkpointDeletion.cleanup();}if (filter.conversationId) {await Promise.all(deletedConversationIds.map((id) => db.deleteToolCalls(req.user.id, id)));@@ -519,6 +545,7 @@ router.delete('/', configMiddleware, async (req, res) => {deletedConversationIds.map((id) => deleteConvoSharedLinksWithCleanup(req.user.id, id)),);}+ await checkpointDeletion?.acknowledge();res.status(201).json(dbResponse);} catch (error) {logger.error('Error clearing conversations', error);diff --git a/api/server/services/Agents/triggers.js b/api/server/services/Agents/triggers.jsindex 1548511269..66926c2991 100644--- a/api/server/services/Agents/triggers.js+++ b/api/server/services/Agents/triggers.js@@ -1,5 +1,6 @@const {createAgentTriggerService,+ createCheckpointDeletionReclaimer,createAgentContinuationResolver,createAgentEventContinueResolver,createSubagentCompletionWakeupResolver,@@ -44,6 +45,9 @@ const queuedTurnLifecycle = createAgentQueuedTurnLifecycle({service = createAgentTriggerService({methods,+ reclaimCheckpointDeletions: createCheckpointDeletionReclaimer((userId, tenantId) =>+ GenerationJobManager.getAccountCleanupJobIdsForUser(userId, tenantId),+ ),isPrincipalActive: methods.isAgentTriggerPrincipalActive,supportsDetachedActionCompletion: () => GenerationJobManager.supportsDetachedAgentEventActions,settleSourceBeforeDeadLetter: queuedTurnLifecycle.settleBeforeDeadLetter,diff --git a/api/server/services/Agents/triggers.spec.js b/api/server/services/Agents/triggers.spec.jsindex 230ae910cf..16965b5abe 100644--- a/api/server/services/Agents/triggers.spec.js+++ b/api/server/services/Agents/triggers.spec.js@@ -2,6 +2,7 @@ const mockCreateAgentTriggerService = jest.fn();const mockGenerationJobManager = {supportsDetachedAgentEventActions: true,getJob: jest.fn(),+ getAccountCleanupJobIdsForUser: jest.fn().mockResolvedValue([]),getGenerationAdmissionEvidence: jest.fn(),};const mockQueuedTurnLifecycle = {@@ -16,6 +17,7 @@ const mockQueuedTurnLifecycle = {};jest.mock('@librechat/api', () => ({+ createCheckpointDeletionReclaimer: jest.fn((getJobs) => () => getJobs('owner', 'tenant')),createAgentTriggerService: (...args) => mockCreateAgentTriggerService(...args),createAgentContinuationResolver: jest.fn(() => jest.fn()),createAgentEventContinueResolver: jest.fn(() => jest.fn()),@@ -53,6 +55,15 @@ describe('agent trigger service composition', () => {});});+ it('uses complete owner job discovery for checkpoint evidence reclamation', async () => {+ require('./triggers');+ await mockCreateAgentTriggerService.mock.calls[0][0].reclaimCheckpointDeletions(25);+ expect(mockGenerationJobManager.getAccountCleanupJobIdsForUser).toHaveBeenCalledWith(+ 'owner',+ 'tenant',+ );+ });+it('advertises detached completion capability for every compatible generation store', () => {require('./triggers');const supportsDetachedActionCompletion =diff --git a/packages/api/src/agents/checkpointer.integration.spec.ts b/packages/api/src/agents/checkpointer.integration.spec.tsindex 5a490a8a3e..c19fcc433e 100644--- a/packages/api/src/agents/checkpointer.integration.spec.ts+++ b/packages/api/src/agents/checkpointer.integration.spec.ts@@ -9,7 +9,7 @@ import {hasDurableAgentInterruptCheckpoint,captureAgentCheckpointGeneration,deleteAgentCheckpoint,- deleteAgentCheckpoints,+ deleteOwnedAgentCheckpoints,forkAgentEventCheckpoint,captureAgentEventCheckpoint,LazyMongoSaver,@@ -19,6 +19,7 @@ import {setupCheckpointIndexes,__resetCheckpointerForTests,} from './checkpointer';+import { createCheckpointNamespace } from '../stream/checkpoints';/*** Integration tests for the durable Mongo checkpointer seam, against a real@@ -477,6 +478,33 @@ describe('checkpointer (mongodb-memory-server integration)', () => {expect(await saver!.getTuple(readConfig(threadB))).toBeDefined();});+ it('scheduled namespace capture prunes root and nested writes while preserving a replacement', async () => {+ const db = mongoose.connection.db!;+ const threadId = 'scheduled-owned-run';+ const namespace = createCheckpointNamespace('owner', 'tenant');+ const replacement = createCheckpointNamespace('owner', 'tenant');+ const rows = [namespace, `${namespace}|child`, replacement, ''].map((checkpoint_ns) => ({+ thread_id: threadId,+ checkpoint_ns,+ checkpoint_id: 'same-checkpoint-id',+ }));+ for (const name of ['agent_checkpoints', 'agent_checkpoint_writes']) {+ await db.collection(name).insertMany(rows.map((row) => ({ ...row })));+ }+ const capture = await captureAgentCheckpointGeneration(threadId, MONGO_CFG, {+ checkpointNamespace: namespace,+ throwOnError: true,+ });+ expect(capture?.checkpointIds).toContain('same-checkpoint-id');+ await deleteAgentCheckpoint(threadId, MONGO_CFG, capture, { throwOnError: true });+ for (const name of ['agent_checkpoints', 'agent_checkpoint_writes']) {+ expect(await db.collection(name).distinct('checkpoint_ns', { thread_id: threadId })).toEqual(+ expect.arrayContaining([replacement, '']),+ );+ expect(await db.collection(name).countDocuments({ thread_id: threadId })).toBe(2);+ }+ });+it('generation-scoped cleanup preserves a replacement checkpoint on the same thread', async () => {const saver = await getAgentCheckpointer(MONGO_CFG);const threadId = `convo-${new mongoose.Types.ObjectId().toString()}`;@@ -510,6 +538,41 @@ describe('checkpointer (mongodb-memory-server integration)', () => {).toBe(0);});+ it('legacy capture and cleanup preserve ordinary owned payload even with matching checkpoint IDs', async () => {+ const saver = (await getAgentCheckpointer(MONGO_CFG))!;+ const threadId = 'legacy-owner-collision';+ const legacy = await seedInterruptCheckpoint(saver, threadId);+ const ownedNamespace = createCheckpointNamespace('other-owner', 'tenant');+ const db = mongoose.connection.db!;+ for (const name of ['agent_checkpoints', 'agent_checkpoint_writes']) {+ const row = await db.collection(name).findOne({ thread_id: threadId });+ const { _id, ...payload } = row!;+ await db.collection(name).insertOne({ ...payload, checkpoint_ns: ownedNamespace });+ await db+ .collection(name)+ .insertOne({ ...payload, checkpoint_id: 'only-owned', checkpoint_ns: ownedNamespace });+ }+ const captured = await captureAgentCheckpointGeneration(threadId, MONGO_CFG);+ expect(captured.checkpointIds).toEqual([legacy.id]);+ await deleteAgentCheckpoint(threadId, MONGO_CFG, captured, { throwOnError: true });+ await deleteAgentCheckpoint(threadId, MONGO_CFG, undefined, { throwOnError: true });+ for (const name of ['agent_checkpoints', 'agent_checkpoint_writes']) {+ const rows = await db.collection(name).find({ thread_id: threadId }).toArray();+ expect(rows).toHaveLength(2);+ expect(rows.every((row) => row.checkpoint_ns === ownedNamespace)).toBe(true);+ }+ await deleteAgentCheckpoint(threadId, MONGO_CFG, undefined, {+ checkpointNamespace: ownedNamespace,+ throwOnError: true,+ });+ expect(await db.collection('agent_checkpoints').countDocuments({ thread_id: threadId })).toBe(+ 0,+ );+ expect(+ await db.collection('agent_checkpoint_writes').countDocuments({ thread_id: threadId }),+ ).toBe(0);+ });+it('isolates a fresh generation from a predecessor checkpoint written after replacement', async () => {const saver = await getAgentCheckpointer(MONGO_CFG);const threadId = `convo-${new mongoose.Types.ObjectId().toString()}`;@@ -618,39 +681,46 @@ describe('checkpointer (mongodb-memory-server integration)', () => {await expect(deleteAgentCheckpoint(undefined, MONGO_CFG)).resolves.toBeUndefined();});- it('deleteAgentCheckpoints bulk-prunes exactly the given threads (checkpoints AND writes)', async () => {- // The bulk path behind conversation deletion / delete-all / account deletion:- // one $in deleteMany per collection instead of two round-trips per thread.+ it('bulk-deletes only an owned generation scope when thread IDs collide', async () => {const saver = await getAgentCheckpointer(MONGO_CFG);- const threadA = `convo-${new mongoose.Types.ObjectId().toString()}`;- const threadB = `convo-${new mongoose.Types.ObjectId().toString()}`;- const threadC = `convo-${new mongoose.Types.ObjectId().toString()}`;-- await seedInterruptCheckpoint(saver!, threadA);- await seedInterruptCheckpoint(saver!, threadB);- await seedInterruptCheckpoint(saver!, threadC);+ const threadId = `collision-${new mongoose.Types.ObjectId().toString()}`;+ const ownedNamespace = createCheckpointNamespace('owner', 'tenant');+ await seedInterruptCheckpoint(saver!, threadId, ownedNamespace);+ await seedInterruptCheckpoint(saver!, threadId, `${ownedNamespace}|subgraph`);+ await seedInterruptCheckpoint(saver!, threadId, 'foreign-generation');+ await seedInterruptCheckpoint(saver!, threadId, '');- // Falsy entries are skipped rather than widening the delete.- await deleteAgentCheckpoints([threadA, undefined, threadB, null], MONGO_CFG);-- expect(await saver!.getTuple(readConfig(threadA))).toBeUndefined();- expect(await saver!.getTuple(readConfig(threadB))).toBeUndefined();- expect(await saver!.getTuple(readConfig(threadC))).toBeDefined();+ await deleteOwnedAgentCheckpoints('owner', 'tenant', [threadId, threadId], MONGO_CFG);+ expect(await saver!.getTuple(readConfig(threadId, ownedNamespace))).toBeUndefined();+ expect(+ await saver!.getTuple(readConfig(threadId, `${ownedNamespace}|subgraph`)),+ ).toBeUndefined();+ expect(await saver!.getTuple(readConfig(threadId, 'foreign-generation'))).toBeDefined();+ expect(await saver!.getTuple(readConfig(threadId, ''))).toBeDefined();const db = mongoose.connection.db!;- const writesFilter = { thread_id: { $in: [threadA, threadB] } };- expect(await db.collection('agent_checkpoints').countDocuments(writesFilter)).toBe(0);- expect(await db.collection('agent_checkpoint_writes').countDocuments(writesFilter)).toBe(0);- // The untouched thread keeps its interrupt write row.expect(- await db.collection('agent_checkpoint_writes').countDocuments({ thread_id: threadC }),- ).toBe(1);+ await db.collection('agent_checkpoint_writes').countDocuments({+ thread_id: threadId,+ checkpoint_ns: { $in: [ownedNamespace, `${ownedNamespace}|subgraph`] },+ }),+ ).toBe(0);+ expect(+ await db.collection('agent_checkpoint_writes').countDocuments({ thread_id: threadId }),+ ).toBe(2);});- it('deleteAgentCheckpoints is a no-op for an empty or all-falsy list', async () => {- await expect(deleteAgentCheckpoints([], MONGO_CFG)).resolves.toBeUndefined();- await expect(deleteAgentCheckpoints([undefined, null], MONGO_CFG)).resolves.toBeUndefined();- await expect(deleteAgentCheckpoints(undefined, MONGO_CFG)).resolves.toBeUndefined();+ it('propagates a bulk checkpoint deletion failure for retry', async () => {+ const deletion = jest+ .spyOn(mongoose.mongo.Collection.prototype, 'deleteMany')+ .mockRejectedValueOnce(new Error('checkpoint deletion unavailable'));+ try {+ await expect(+ deleteOwnedAgentCheckpoints('owner', 'tenant', ['conversation-1'], MONGO_CFG),+ ).rejects.toThrow('checkpoint deletion unavailable');+ } finally {+ deletion.mockRestore();+ }});});diff --git a/packages/api/src/agents/checkpointer.spec.ts b/packages/api/src/agents/checkpointer.spec.tsindex 69ce7248c7..3f30614e46 100644--- a/packages/api/src/agents/checkpointer.spec.ts+++ b/packages/api/src/agents/checkpointer.spec.ts@@ -4,6 +4,7 @@ import {getAgentCheckpointer,captureAgentCheckpointGeneration,deleteAgentCheckpoint,+ deleteOwnedAgentCheckpoints,DEFAULT_CHECKPOINT_TTL_SECONDS,__resetCheckpointerForTests,} from './checkpointer';@@ -51,6 +52,22 @@ describe('getApprovalTtlMs', () => {});});+describe('owner checkpoint cleanup', () => {+ test('requires an authenticated owner', async () => {+ await expect(deleteOwnedAgentCheckpoints('', undefined, undefined)).rejects.toThrow('owner');+ });+ test('does not require a database in memory mode', async () => {+ await expect(+ deleteOwnedAgentCheckpoints('user-1', undefined, undefined, { type: 'memory' }),+ ).resolves.toBeUndefined();+ });+ test('fails closed when the durable database is unavailable', async () => {+ await expect(deleteOwnedAgentCheckpoints('user-1', undefined, undefined)).rejects.toThrow(+ 'unavailable',+ );+ });+});+describe('getAgentCheckpointer', () => {test('returns undefined for the in-memory type (SDK MemorySaver fallback)', async () => {await expect(getAgentCheckpointer({ type: 'memory' })).resolves.toBeUndefined();diff --git a/packages/api/src/agents/checkpointer.ts b/packages/api/src/agents/checkpointer.tsindex 055867eaf1..bb8c377b24 100644--- a/packages/api/src/agents/checkpointer.ts+++ b/packages/api/src/agents/checkpointer.ts@@ -13,6 +13,28 @@ import type { BaseMessage } from '@librechat/agents/langchain/messages';import type { TCheckpointerConfig } from 'librechat-data-provider';import type { IndexBuildOptions } from '@librechat/data-schemas';import type { RunnableConfig } from '@langchain/core/runnables';+import type { ResolvedCheckpointerConfig } from './checkpoints/config';+import {+ OwnedMongoSaver,+ LIBRECHAT_CHECKPOINT_OWNER_KEY,+ LIBRECHAT_LEGACY_CHECKPOINT_KEY,+} from './checkpoints/saver';+import { checkpointOwnerNamespacePrefix } from '../stream/checkpoints';+import { resolveCheckpointerConfig } from './checkpoints/config';++export {+ LIBRECHAT_CHECKPOINT_OWNER_KEY,+ LIBRECHAT_LEGACY_CHECKPOINT_KEY,+} from './checkpoints/saver';+export { checkpointOwnerNamespacePrefix } from '../stream/checkpoints';++export { resolveCheckpointerConfig } from './checkpoints/config';+export {+ checkpointStorageConfigs,+ LIBRECHAT_CHECKPOINT_STORAGE_OWNER_KEY,+} from './checkpoints/storage';+export type { ResolvedCheckpointerConfig } from './checkpoints/config';+export { DEFAULT_CHECKPOINT_TTL_SECONDS } from '../stream/checkpoints';/*** LangGraph reserves `checkpoint_ns` for nested graph namespaces and forcibly@@ -75,6 +97,15 @@ function fromStorageCheckpointConfig(...storedConfig,configurable: {...storedConfig.configurable,+ ...(requestedConfig.configurable?.[LIBRECHAT_CHECKPOINT_OWNER_KEY] && {+ [LIBRECHAT_CHECKPOINT_OWNER_KEY]:+ requestedConfig.configurable[LIBRECHAT_CHECKPOINT_OWNER_KEY],+ }),+ ...(requestedConfig.configurable?.[LIBRECHAT_LEGACY_CHECKPOINT_KEY] && {+ [LIBRECHAT_LEGACY_CHECKPOINT_KEY]:+ storedConfig.configurable?.[LIBRECHAT_LEGACY_CHECKPOINT_KEY] ??+ requestedConfig.configurable[LIBRECHAT_LEGACY_CHECKPOINT_KEY],+ }),thread_id: requestedConfig.configurable?.thread_id ?? storedConfig.configurable?.thread_id,checkpoint_ns: graphNamespace,[LIBRECHAT_CHECKPOINT_NAMESPACE_KEY]: generationNamespace,@@ -292,7 +323,7 @@ export type LazyMongoSaverOptions = ConstructorParameters<typeof MongoDBSaver>[0hardLimitBytes?: number;};-export class LazyMongoSaver extends MongoDBSaver {+export class LazyMongoSaver extends OwnedMongoSaver {/** checkpoint id → time the resumable `putWrites` anchoring it arrived; consumed by `put`. */private readonly writeAnchorIds = new Map<string, number>();/** checkpoint id → time its anchored `put` persisted it, so a bookkeeping batch that lands@@ -542,21 +573,6 @@ function sweepStale<T>(map: Map<string, T>, timeOf: (value: T) => number): void}}-/** Default approval window and checkpoint TTL: 24h. */-export const DEFAULT_CHECKPOINT_TTL_SECONDS = 86400;--const DEFAULT_CHECKPOINT_COLLECTION = 'agent_checkpoints';-const DEFAULT_CHECKPOINT_WRITES_COLLECTION = 'agent_checkpoint_writes';--/** Checkpointer settings with all defaults applied. */-export interface ResolvedCheckpointerConfig {- type: 'mongo' | 'memory';- /** Approval window / TTL in seconds. */- ttlSeconds: number;- checkpointCollectionName: string;- checkpointWritesCollectionName: string;-}-/*** Exact checkpoint ids present before a legacy, unscoped generation is claimed.*@@ -573,23 +589,6 @@ export interface AgentCheckpointGeneration {checkpointIds: string[];}-/**- * Apply defaults to the YAML `endpoints.agents.checkpointer` block. Mirrors- * {@link resolveRecursionLimit} — the schema stays descriptive, defaults live here.- */-export function resolveCheckpointerConfig(- cfg: TCheckpointerConfig | undefined,-): ResolvedCheckpointerConfig {- return {- type: cfg?.type ?? 'mongo',- ttlSeconds:- typeof cfg?.ttl === 'number' && cfg.ttl > 0 ? cfg.ttl : DEFAULT_CHECKPOINT_TTL_SECONDS,- checkpointCollectionName: cfg?.checkpointCollectionName ?? DEFAULT_CHECKPOINT_COLLECTION,- checkpointWritesCollectionName:- cfg?.checkpointWritesCollectionName ?? DEFAULT_CHECKPOINT_WRITES_COLLECTION,- };-}-/** Approval-window milliseconds from the resolved config; drives pending-action expiry. */export function getApprovalTtlMs(cfg: TCheckpointerConfig | undefined): number {return resolveCheckpointerConfig(cfg).ttlSeconds * 1000;@@ -743,6 +742,7 @@ function eventActorRunnableConfig(reference: Pick<AgentEventCheckpointReference, 'threadId' | 'checkpointNs'>,invocationId: string,checkpointId?: string,+ owner?: string,): RunnableConfig {return {configurable: {@@ -750,6 +750,12 @@ function eventActorRunnableConfig(checkpoint_ns: '',[LIBRECHAT_CHECKPOINT_NAMESPACE_KEY]: reference.checkpointNs,[LIBRECHAT_EVENT_ACTOR_INVOCATION_KEY]: invocationId,+ ...(owner == null+ ? {}+ : {+ [LIBRECHAT_CHECKPOINT_OWNER_KEY]: owner,+ ...(checkpointId == null ? {} : { [LIBRECHAT_LEGACY_CHECKPOINT_KEY]: checkpointId }),+ }),...(checkpointId == null ? {} : { checkpoint_id: checkpointId }),},};@@ -762,20 +768,21 @@ export async function forkAgentEventCheckpoint(invocationId: string,cfg?: TCheckpointerConfig,messageOverlay?: AgentEventCheckpointMessageOverlay,+ owner?: string,): Promise<AgentEventCheckpointReference | null> {const saver = await getAgentCheckpointer(cfg);if (!saver || checkpointNs.length === 0 || invocationId.length === 0) {return null;}const tuple = await saver.getTuple(- eventActorRunnableConfig(source, invocationId, source.checkpointId),+ eventActorRunnableConfig(source, invocationId, source.checkpointId, owner),);if (!tuple || tuple.metadata == null || (tuple.pendingWrites?.length ?? 0) > 0) {return null;}const target = { threadId: source.threadId, checkpointNs };const persisted = await saver.put(- eventActorRunnableConfig(target, invocationId),+ eventActorRunnableConfig(target, invocationId, undefined, owner),applyAgentEventCheckpointMessageOverlay(tuple.checkpoint, messageOverlay),tuple.metadata,);@@ -786,20 +793,83 @@ export async function forkAgentEventCheckpoint(return { ...target, checkpointId };}+/** Historical evidence authorizes only this exact ID, never the whole legacy namespace. */+export async function deleteAgentEventCheckpointReference(+ reference: AgentEventCheckpointReference,+ cfg?: TCheckpointerConfig,+ owner?: string,+): Promise<boolean> {+ const resolved = resolveCheckpointerConfig(cfg);+ if (resolved.type === 'memory') {+ return false;+ }+ const db = mongoose.connection.db;+ if (!db || mongoose.connection.readyState !== 1) {+ throw new Error('Mongo checkpoint storage is unavailable');+ }+ const exact = {+ thread_id: reference.threadId,+ checkpoint_ns: reference.checkpointNs,+ checkpoint_id: reference.checkpointId,+ ...(owner == null+ ? { lc_owner: { $exists: false } }+ : { $or: [{ lc_owner: owner }, { lc_owner: { $exists: false } }] }),+ };+ await db.collection(resolved.checkpointWritesCollectionName).deleteMany(exact);+ await db.collection(resolved.checkpointCollectionName).deleteOne(exact);+ return true;+}++/** Consume exact historical proofs in bounded batches, retaining intent on any failure. */+export async function deleteAgentEventCheckpointReferences(+ references: readonly AgentEventCheckpointReference[],+ owner: string,+ cfg?: TCheckpointerConfig,+): Promise<void> {+ const resolved = resolveCheckpointerConfig(cfg);+ if (resolved.type === 'memory' || references.length === 0) return;+ const db = mongoose.connection.db;+ if (!db || mongoose.connection.readyState !== 1)+ throw new Error('Checkpoint database is unavailable');+ for (let offset = 0; offset < references.length; offset += 256) {+ const exact = {+ $and: [+ { $or: [{ lc_owner: owner }, { lc_owner: { $exists: false } }] },+ {+ $or: references.slice(offset, offset + 256).map((reference) => ({+ thread_id: reference.threadId,+ checkpoint_ns: reference.checkpointNs,+ checkpoint_id: reference.checkpointId,+ })),+ },+ ],+ };+ await db.collection(resolved.checkpointWritesCollectionName).deleteMany(exact);+ await db.collection(resolved.checkpointCollectionName).deleteMany(exact);+ }+}+/** Reads the terminal checkpoint produced inside one invocation namespace. */export async function captureAgentEventCheckpoint(threadId: string,checkpointNs: string,invocationId: string,cfg?: TCheckpointerConfig,+ owner?: string,+ legacyCheckpointId?: string,): Promise<AgentEventCheckpointReference | null> {const saver = await getAgentCheckpointer(cfg);if (!saver) {return null;}- const tuple = await saver.getTuple(- eventActorRunnableConfig({ threadId, checkpointNs }, invocationId),+ let tuple = await saver.getTuple(+ eventActorRunnableConfig({ threadId, checkpointNs }, invocationId, undefined, owner),);+ if (legacyCheckpointId != null && (tuple == null || tuple.checkpoint.id < legacyCheckpointId)) {+ tuple = await saver.getTuple(+ eventActorRunnableConfig({ threadId, checkpointNs }, invocationId, legacyCheckpointId, owner),+ );+ }const checkpointId = tuple?.checkpoint.id;return typeof checkpointId === 'string' && checkpointId.length > 0? { threadId, checkpointId, checkpointNs }@@ -879,6 +949,35 @@ async function buildMongoSaver(errors,);}+ await Promise.all(+ [resolved.checkpointCollectionName, resolved.checkpointWritesCollectionName].map(+ async (name) => {+ try {+ await buildIndexWithRetry(+ () => mongoose.connection.db!.collection(name).createIndex({ checkpoint_ns: 1 }),+ `${name}.checkpoint_ns`,+ );+ } catch (error) {+ logger.warn('[checkpointer] Owner cleanup index unavailable:', error);+ }+ },+ ),+ );+ await Promise.all(+ [resolved.checkpointCollectionName, resolved.checkpointWritesCollectionName].map(+ async (name) => {+ try {+ await buildIndexWithRetry(+ () =>+ mongoose.connection.db!.collection(name).createIndex({ lc_owner: 1, thread_id: 1 }),+ `${name}.lc_owner`,+ );+ } catch (error) {+ logger.warn('[checkpointer] Payload ownership index unavailable:', error);+ }+ },+ ),+ );logger.info('[checkpointer] Durable Mongo checkpointer ready for agent continuation');return saver;} catch (err) {@@ -893,6 +992,10 @@ async function buildMongoSaver(}}+function legacyCheckpointStorageFilter() {+ return { checkpoint_ns: { $not: /^lcg:v2:/ }, lc_owner: { $exists: false } };+}+/*** Snapshot the durable checkpoint ids that belong to the generation about to* resume. Capture this before atomically claiming the paused job; a replacement@@ -933,9 +1036,9 @@ export async function captureAgentCheckpointGeneration(.find({thread_id: threadId,- ...(namespaceScoped && {- checkpoint_ns: generationNamespaceFilter(requestedNamespace),- }),+ ...(namespaceScoped+ ? { checkpoint_ns: generationNamespaceFilter(requestedNamespace) }+ : legacyCheckpointStorageFilter()),},{ projection: { _id: 0, checkpoint_id: 1 } },)@@ -967,7 +1070,7 @@ export async function captureAgentCheckpointGeneration(* @param threadId - the LangGraph `thread_id` (LibreChat's conversationId).* @param generation - when present, delete only the checkpoint ids captured for* this resumed generation; omitted by legacy callers that intentionally prune- * the entire thread.+ * the untagged legacy rows on the thread.*/export async function deleteAgentCheckpoint(threadId: string | undefined,@@ -1002,9 +1105,9 @@ export async function deleteAgentCheckpoint(const resolved = resolveCheckpointerConfig(cfg);const filter = {thread_id: threadId,- ...(Object.prototype.hasOwnProperty.call(generation, 'checkpointNamespace') && {- checkpoint_ns: generationNamespaceFilter(generation.checkpointNamespace ?? ''),- }),+ ...(Object.prototype.hasOwnProperty.call(generation, 'checkpointNamespace')+ ? { checkpoint_ns: generationNamespaceFilter(generation.checkpointNamespace ?? '') }+ : legacyCheckpointStorageFilter()),checkpoint_id: { $in: generation.checkpointIds },};await Promise.all([@@ -1041,7 +1144,14 @@ export async function deleteAgentCheckpoint(]);return;}- await saver.deleteThread(threadId);+ const db = mongoose.connection.db;+ if (!db) return;+ const resolved = resolveCheckpointerConfig(cfg);+ const filter = { thread_id: threadId, ...legacyCheckpointStorageFilter() };+ await Promise.all([+ db.collection(resolved.checkpointCollectionName).deleteMany(filter),+ db.collection(resolved.checkpointWritesCollectionName).deleteMany(filter),+ ]);} catch (err) {logger.warn(`[checkpointer] Failed to delete checkpoints for thread ${threadId}:`, err);if (options?.throwOnError) {@@ -1050,47 +1160,62 @@ export async function deleteAgentCheckpoint(}}-/**- * Bulk variant of {@link deleteAgentCheckpoint} for terminal transitions that cover MANY- * threads at once — deleting conversations, "delete all", account deletion. One indexed- * `deleteMany` per collection instead of two round-trips per thread. Deletes through the- * same live mongoose connection the saver is built on, using the same resolved collection- * names; like the single-thread variant it no-ops in memory mode or before Mongo is- * connected, and never throws (the conversations are already gone — the Mongo TTL remains- * the backstop for anything this misses).- *- * @param threadIds - LangGraph `thread_id`s (LibreChat conversationIds); falsy entries skipped.- */-export async function deleteAgentCheckpoints(- threadIds: Array<string | null | undefined> | undefined,+/** Erase only payload rows carrying this authenticated actor owner. */+export async function deleteOwnedActorCheckpointScope(+ threadId: string,+ checkpointNs: string,+ owner: string,cfg?: TCheckpointerConfig,): Promise<void> {- const ids = (threadIds ?? []).filter((id): id is string => Boolean(id));- if (ids.length === 0) {- return;+ const resolved = resolveCheckpointerConfig(cfg);+ if (resolved.type === 'memory') return;+ const db = mongoose.connection.db;+ if (!db || mongoose.connection.readyState !== 1)+ throw new Error('Checkpoint database is unavailable');+ const filter = {+ thread_id: `${owner}${threadId}`,+ checkpoint_ns: generationNamespaceFilter(`${owner}${checkpointNs}`),+ lc_owner: owner,+ };+ await Promise.all([+ db.collection(resolved.checkpointCollectionName).deleteMany(filter),+ db.collection(resolved.checkpointWritesCollectionName).deleteMany(filter),+ ]);+}++/** Delete durable rows by authenticated ownership, independently of job/receipt lifetimes. */+export async function deleteOwnedAgentCheckpoints(+ userId: string,+ tenantId: string | undefined,+ conversationIds: readonly string[] | undefined,+ cfg?: TCheckpointerConfig,+): Promise<void> {+ if (!userId) {+ throw new Error('Checkpoint cleanup requires an owner');}- // Reuse the saver gate: memory mode / no connection ⇒ nothing durable to delete.- const saver = await getAgentCheckpointer(cfg);- if (!saver) {+ const resolved = resolveCheckpointerConfig(cfg);+ if (resolved.type === 'memory' || conversationIds?.length === 0) {return;}- const resolved = resolveCheckpointerConfig(cfg);- try {- const db = mongoose.connection.db;- if (!db) {- return;- }- await Promise.all([- db.collection(resolved.checkpointCollectionName).deleteMany({ thread_id: { $in: ids } }),- db- .collection(resolved.checkpointWritesCollectionName)- .deleteMany({ thread_id: { $in: ids } }),- ]);- } catch (err) {- logger.warn(- `[checkpointer] Failed to bulk-delete checkpoints for ${ids.length} thread(s):`,- err,- );+ const db = mongoose.connection.db;+ if (!db || mongoose.connection.readyState !== 1) {+ throw new Error('Checkpoint database is unavailable');+ }+ const owner = checkpointOwnerNamespacePrefix(userId, tenantId);+ const ownership = { $or: [{ checkpoint_ns: { $regex: `^${owner}` } }, { lc_owner: owner }] };+ const ids = conversationIds == null ? undefined : [...new Set(conversationIds)];+ const batchSize = 128;+ for (let offset = 0; offset < (ids?.length ?? 1); offset += batchSize) {+ const filter = {+ ...ownership,+ ...(ids && {+ thread_id: {+ $in: ids.slice(offset, offset + batchSize).flatMap((id) => [id, `${owner}${id}`]),+ },+ }),+ };+ await db.collection(resolved.checkpointCollectionName).deleteMany(filter);+ await db.collection(resolved.checkpointWritesCollectionName).deleteMany(filter);}}diff --git a/packages/api/src/agents/checkpoints/actor.integration.spec.ts b/packages/api/src/agents/checkpoints/actor.integration.spec.tsnew file mode 100644index 0000000000..30e24d7d0a--- /dev/null+++ b/packages/api/src/agents/checkpoints/actor.integration.spec.ts@@ -0,0 +1,396 @@+import mongoose from 'mongoose';+import { MongoMemoryServer } from 'mongodb-memory-server';+import { MongoDBSaver } from '@langchain/langgraph-checkpoint-mongodb';+import { emptyCheckpoint, INTERRUPT } from '@langchain/langgraph-checkpoint';+import { Annotation, StateGraph, START, END, interrupt, Command } from '@langchain/langgraph';+import type { RunnableConfig } from '@langchain/core/runnables';+import {+ getAgentCheckpointer,+ deleteOwnedAgentCheckpoints,+ LIBRECHAT_CHECKPOINT_NAMESPACE_KEY,+ LIBRECHAT_CHECKPOINT_OWNER_KEY,+ LIBRECHAT_LEGACY_CHECKPOINT_KEY,+ LIBRECHAT_EVENT_ACTOR_INVOCATION_KEY,+ __resetCheckpointerForTests,+} from '../checkpointer';+import { checkpointOwnerNamespacePrefix } from '../../stream/checkpoints';+import { createOwnedActorCheckpoints } from './actor';+import { openCheckpointDeletion } from './deletion';++const cfg = { type: 'mongo' as const };+let server: MongoMemoryServer;+beforeAll(async () => {+ server = await MongoMemoryServer.create();+ await mongoose.connect(server.getUri());+}, 60000);+afterAll(async () => {+ await mongoose.disconnect();+ await server.stop();+});+afterEach(async () => {+ jest.restoreAllMocks();+ __resetCheckpointerForTests();+ await mongoose.connection.dropDatabase();+});++function config(+ namespace: string,+ owner?: string,+ checkpointId?: string,+ graphNamespace = '',+): RunnableConfig {+ return {+ configurable: {+ thread_id: 'actor-thread',+ checkpoint_ns: graphNamespace,+ [LIBRECHAT_CHECKPOINT_NAMESPACE_KEY]: namespace,+ [LIBRECHAT_EVENT_ACTOR_INVOCATION_KEY]: 'invocation',+ ...(owner == null+ ? {}+ : { [LIBRECHAT_CHECKPOINT_OWNER_KEY]: checkpointOwnerNamespacePrefix(owner) }),+ ...(checkpointId == null ? {} : { checkpoint_id: checkpointId }),+ },+ };+}++async function write(namespace: string, owner?: string, graphNamespace = '') {+ const saver = (await getAgentCheckpointer(cfg))!;+ const checkpoint = emptyCheckpoint();+ const input = config(namespace, owner, checkpoint.id, graphNamespace);+ await saver.put(input, checkpoint, { source: 'loop', step: 1, parents: {} });+ await saver.putWrites(input, [[INTERRUPT, { id: 'approval', value: 'approve' }]], 'task');+ return checkpoint.id;+}+const reference = (checkpointNs: string, checkpointId: string) => ({+ threadId: 'actor-thread',+ checkpointNs,+ checkpointId,+});++test('late legacy writes and another tagged owner survive owned scope deletion', async () => {+ const owner = createOwnedActorCheckpoints('owner');+ const ns = 'event-actor/collision';+ await write(ns, 'owner');+ await write(ns, 'owner', 'nested');+ const foreignId = await write(ns, 'foreign');+ const lateLegacyId = await write(ns);+ await owner.removeOwned({ threadId: 'actor-thread', checkpointNs: ns }, cfg);+ for (const name of ['agent_checkpoints', 'agent_checkpoint_writes']) {+ const rows = await mongoose.connection.db!.collection(name).find().toArray();+ expect(rows.map((row) => row.checkpoint_id).sort()).toEqual([foreignId, lateLegacyId].sort());+ }+ await deleteOwnedAgentCheckpoints('foreign', undefined, undefined, cfg);+ expect(+ (await mongoose.connection.db!.collection('agent_checkpoints').find().toArray()).map(+ (row) => row.checkpoint_id,+ ),+ ).toEqual([lateLegacyId]);+});++test('old raw readers cannot see isolated owner payloads', async () => {+ const id = await write('event-actor/head', 'owner');+ const tuple = await MongoDBSaver.prototype.getTuple.call((await getAgentCheckpointer(cfg))!, {+ configurable: {+ thread_id: 'actor-thread',+ checkpoint_ns: 'event-actor/head',+ checkpoint_id: id,+ },+ });+ expect(tuple).toBeUndefined();+ const saver = (await getAgentCheckpointer(cfg))!;+ expect(+ await MongoDBSaver.prototype.getTuple.call(saver, {+ configurable: { thread_id: 'actor-thread', checkpoint_ns: 'event-actor/head' },+ }),+ ).toBeUndefined();+ expect((await saver.getTuple(config('event-actor/head', 'owner')))?.checkpoint.id).toBe(id);+ for (const name of ['agent_checkpoints', 'agent_checkpoint_writes']) {+ const rows = await mongoose.connection.db!.collection(name).find().toArray();+ expect(rows.every((row) => row.lc_owner === checkpointOwnerNamespacePrefix('owner'))).toBe(+ true,+ );+ await mongoose.connection.db!.collection(name).dropIndexes();+ }+ await deleteOwnedAgentCheckpoints('owner', undefined, ['actor-thread'], cfg);+ expect(await mongoose.connection.db!.collection('agent_checkpoints').countDocuments()).toBe(0);+});++test('raw thread cleanup cannot remove isolated actor checkpoints or pending writes', async () => {+ const id = await write('event-actor/head', 'owner');+ await write('event-actor/head');+ const saver = (await getAgentCheckpointer(cfg))!;+ await MongoDBSaver.prototype.deleteThread.call(saver, 'actor-thread');+ const tuple = await saver.getTuple(config('event-actor/head', 'owner'));+ expect(tuple?.checkpoint.id).toBe(id);+ expect(tuple?.pendingWrites).toHaveLength(1);+ await createOwnedActorCheckpoints('owner').removeOwned(reference('event-actor/head', id), cfg);+ expect(await mongoose.connection.db!.collection('agent_checkpoints').countDocuments()).toBe(0);+ expect(await mongoose.connection.db!.collection('agent_checkpoint_writes').countDocuments()).toBe(+ 0,+ );+});++test.each([undefined, 'owner'])(+ 'follows exact legacy parents from a %s child',+ async (childOwner) => {+ const saver = (await getAgentCheckpointer(cfg))!;+ const namespace = 'event-actor/history';+ const parent = emptyCheckpoint();+ await saver.put(config(namespace), parent, { source: 'loop', step: 0, parents: {} });+ const child = emptyCheckpoint();+ await saver.put(config(namespace, childOwner, parent.id), child, {+ source: 'loop',+ step: 1,+ parents: {},+ });+ const input = config(namespace, 'owner', child.id);+ input.configurable![LIBRECHAT_LEGACY_CHECKPOINT_KEY] = child.id;+ const tuple = await saver.getTuple(input);+ expect(tuple?.parentConfig?.configurable).toMatchObject({+ thread_id: 'actor-thread',+ checkpoint_id: parent.id,+ [LIBRECHAT_LEGACY_CHECKPOINT_KEY]: parent.id,+ });+ expect((await saver.getTuple(tuple!.parentConfig!))?.checkpoint.id).toBe(parent.id);+ await mongoose.connection+ .db!.collection('agent_checkpoints')+ .updateOne(+ { thread_id: 'actor-thread', checkpoint_id: parent.id },+ { $set: { lc_owner: checkpointOwnerNamespacePrefix('foreign') } },+ );+ expect(await saver.getTuple(tuple!.parentConfig!)).toBeUndefined();+ },+);++test('capture and history never select another owner or fall back to latest legacy data', async () => {+ const owner = createOwnedActorCheckpoints('owner');+ const id = await write('event-actor/head', 'owner');+ const foreignId = await write('event-actor/head', 'foreign');+ await write('event-actor/head');+ expect(+ (await owner.capture('actor-thread', 'event-actor/head', 'invocation', cfg))?.checkpointId,+ ).toBe(id);+ expect(+ await owner.resolveNamespace(reference('event-actor/head', foreignId), cfg),+ ).toBeUndefined();+ await write('event-actor/legacy');+ expect(await owner.capture('actor-thread', 'event-actor/legacy', 'invocation', cfg)).toBeNull();+ const saver = (await getAgentCheckpointer(cfg))!;+ const listed = [];+ for await (const tuple of saver.list(config('event-actor/head', 'owner')))+ listed.push(tuple.checkpoint.id);+ expect(listed).toEqual([id]);+});++test('an exact legacy head forks into owner-tagged rows without changing SDK references', async () => {+ const saver = (await getAgentCheckpointer(cfg))!;+ const checkpoint = emptyCheckpoint();+ await saver.put(config('event-actor/legacy'), checkpoint, {+ source: 'loop',+ step: 1,+ parents: {},+ });+ const owner = createOwnedActorCheckpoints('owner');+ const fork = await owner.fork(+ reference('event-actor/legacy', checkpoint.id),+ 'event-actor/new',+ 'next',+ cfg,+ );+ expect(fork).toEqual(reference('event-actor/new', checkpoint.id));+ expect((await owner.capture('actor-thread', 'event-actor/new', 'next', cfg))?.checkpointId).toBe(+ checkpoint.id,+ );+ await owner.removeOwned({ threadId: 'actor-thread', checkpointNs: 'event-actor/new' }, cfg);+ expect(await owner.resolveNamespace(reference('event-actor/legacy', checkpoint.id), cfg)).toBe(+ 'event-actor/legacy',+ );+});++test('legacy pending writes preserve overwrite and insert-or-ignore behavior on new-replica resume', async () => {+ const id = await write('event-actor/legacy');+ const saver = (await getAgentCheckpointer(cfg))!;+ const legacy = config('event-actor/legacy', undefined, id);+ await saver.putWrites(legacy, [['messages', 'original']], 'regular');+ const resumed = config('event-actor/legacy', 'owner', id);+ resumed.configurable![LIBRECHAT_LEGACY_CHECKPOINT_KEY] = id;+ await saver.putWrites(resumed, [[INTERRUPT, { id: 'updated' }]], 'task');+ await saver.putWrites(resumed, [['messages', 'replacement']], 'regular');+ const tuple = await saver.getTuple(resumed);+ expect(tuple?.pendingWrites).toEqual(+ expect.arrayContaining([+ ['task', INTERRUPT, { id: 'updated' }],+ ['regular', 'messages', 'original'],+ ]),+ );+ expect(tuple?.pendingWrites).toHaveLength(2);+ const old = await saver.getTuple(legacy);+ expect(old?.pendingWrites).not.toEqual(tuple?.pendingWrites);+ expect(old?.pendingWrites).toContainEqual(['regular', 'messages', 'original']);+});++test('deletion intent survives topology loss and deletes only exact legacy IDs', async () => {+ const headId = await write('event-actor/legacy-head');+ const pauseId = await write('event-actor/legacy-closed');+ const foreignId = await write('event-actor/legacy-head');+ await mongoose.connection.db!.collection('conversations').insertOne({+ user: 'owner',+ conversationId: 'actor-thread',+ subagentThread: {},+ agentEventActor: { checkpoint: reference('event-actor/legacy-head', headId) },+ agentEventActorSuspension: {+ status: 'closed',+ suspension: { checkpoint: reference('event-actor/legacy-closed', pauseId) },+ },+ });+ const intent = await openCheckpointDeletion('owner', undefined, 'actor-thread', cfg);+ await intent.remember(['actor-thread']);+ await mongoose.connection.db!.collection('conversations').deleteOne({ user: 'owner' });+ const retry = await openCheckpointDeletion('owner', undefined, 'actor-thread', cfg);+ await retry.cleanup();+ await retry.acknowledge();+ for (const name of ['agent_checkpoints', 'agent_checkpoint_writes']) {+ expect(+ (await mongoose.connection.db!.collection(name).find().toArray()).map(+ (row) => row.checkpoint_id,+ ),+ ).toEqual([foreignId]);+ }+});++test('failed pruning keeps the outbox until exact legacy cleanup succeeds', async () => {+ const owner = createOwnedActorCheckpoints('owner');+ const id = await write('event-actor/prune');+ const nested = await write('event-actor/prune', undefined, 'nested');+ await mongoose.connection.db!.collection('conversations').insertOne({+ user: 'owner',+ conversationId: 'actor-thread',+ agentEventActorCleanup: [reference('event-actor/prune', id)],+ });+ jest+ .spyOn(mongoose.mongo.Collection.prototype, 'deleteOne')+ .mockRejectedValueOnce(new Error('interrupted cleanup'));+ await expect(owner.drain('actor-thread', cfg)).rejects.toThrow('interrupted cleanup');+ jest.restoreAllMocks();+ expect(+ (await mongoose.connection.db!.collection('conversations').findOne({ user: 'owner' }))+ ?.agentEventActorCleanup,+ ).toHaveLength(1);+ await owner.drain('actor-thread', cfg);+ expect(+ (await mongoose.connection.db!.collection('conversations').findOne({ user: 'owner' }))+ ?.agentEventActorCleanup,+ ).toEqual([]);+ expect(+ (await mongoose.connection.db!.collection('agent_checkpoints').find().toArray()).map(+ (row) => row.checkpoint_id,+ ),+ ).toEqual([nested]);+});++test('payload ownership survives missing conversations and partial deletion without a registry', async () => {+ await write('event-actor/head', 'owner');+ await write('event-actor/head', 'foreign');+ jest+ .spyOn(mongoose.mongo.Collection.prototype, 'deleteMany')+ .mockRejectedValueOnce(new Error('partial cleanup'));+ await expect(deleteOwnedAgentCheckpoints('owner', undefined, undefined, cfg)).rejects.toThrow(+ 'partial cleanup',+ );+ jest.restoreAllMocks();+ await deleteOwnedAgentCheckpoints('owner', undefined, undefined, cfg);+ for (const name of ['agent_checkpoints', 'agent_checkpoint_writes']) {+ expect(+ (await mongoose.connection.db!.collection(name).find().toArray()).map((row) => row.lc_owner),+ ).toEqual([checkpointOwnerNamespacePrefix('foreign')]);+ }+});++test('deletion intent retains both pre-drain and final historical references', async () => {+ const ns = 'event-actor/drain-snapshot';+ const first = await write(ns);+ await mongoose.connection.db!.collection('conversations').insertOne({+ user: 'owner',+ conversationId: 'actor-thread',+ subagentThread: {},+ agentEventActor: { checkpoint: reference(ns, first) },+ });+ const deletion = await openCheckpointDeletion('owner', undefined, 'actor-thread', cfg);+ await deletion.remember(['actor-thread']);+ const final = await write(ns);+ await mongoose.connection+ .db!.collection('conversations')+ .updateOne({ user: 'owner' }, { $set: { 'agentEventActor.checkpoint': reference(ns, final) } });+ await deletion.remember(['actor-thread']);+ const unrelated = await write(ns);+ await mongoose.connection.db!.collection('conversations').deleteOne({ user: 'owner' });+ const retry = await openCheckpointDeletion('owner', undefined, 'actor-thread', cfg);+ await retry.cleanup();+ await retry.acknowledge();+ expect(+ (await mongoose.connection.db!.collection('agent_checkpoints').find().toArray()).map(+ (row) => row.checkpoint_id,+ ),+ ).toEqual([unrelated]);+});++test('a legacy pause can re-pause and resume on upgraded replicas', async () => {+ const state = Annotation.Root({+ answers: Annotation<string[]>({ reducer: (_left, right) => right, default: () => [] }),+ });+ const saver = (await getAgentCheckpointer(cfg))!;+ const graph = new StateGraph(state)+ .addNode('ask', () => ({ answers: [interrupt('first'), interrupt('second')] }))+ .addEdge(START, 'ask')+ .addEdge('ask', END)+ .compile({ checkpointer: saver });+ const namespace = 'event-actor/upgrade';+ const oldReplica = config(namespace);+ await graph.invoke({ answers: [] }, { ...oldReplica, durability: 'exit' });+ const first = (await saver.getTuple(oldReplica))!;+ const resumed = config(namespace, 'owner', first.checkpoint.id);+ resumed.configurable![LIBRECHAT_LEGACY_CHECKPOINT_KEY] = first.checkpoint.id;+ await graph.invoke(new Command({ resume: 'one' }), { ...resumed, durability: 'exit' });+ const captured = await createOwnedActorCheckpoints('owner').capture(+ 'actor-thread',+ namespace,+ 'invocation',+ cfg,+ namespace,+ first.checkpoint.id,+ );+ expect(captured?.checkpointId).toBe(first.checkpoint.id);+ const result = await graph.invoke(new Command({ resume: 'two' }), {+ ...resumed,+ durability: 'exit',+ });+ expect(result.answers).toEqual(['one', 'two']);+ const head = await saver.getTuple(config(namespace, 'owner'));+ expect(head?.checkpoint.channel_values.answers).toEqual(['one', 'two']);+ expect((await saver.getTuple(head!.config))?.checkpoint.id).toBe(head?.checkpoint.id);+ expect((await saver.getTuple(oldReplica))?.checkpoint.id).toBe(first.checkpoint.id);+});++test('custom checkpoint collections carry owner authority without separate maintenance storage', async () => {+ const custom = {+ ...cfg,+ checkpointCollectionName: 'tenant_cp',+ checkpointWritesCollectionName: 'tenant_writes',+ };+ const saver = (await getAgentCheckpointer(custom))!;+ const cp = emptyCheckpoint();+ const input = config('event-actor/custom', 'owner', cp.id);+ await saver.put(input, cp, { source: 'loop', step: 1, parents: {} });+ await saver.putWrites(input, [[INTERRUPT, 'approval']], 'task');+ for (const name of ['tenant_cp', 'tenant_writes']) {+ const row = await mongoose.connection.db!.collection(name).findOne();+ expect(row?.lc_owner).toBe(checkpointOwnerNamespacePrefix('owner'));+ expect(row?.upserted_at).toBeInstanceOf(Date);+ }+ expect(+ await mongoose.connection.db!.listCollections({ name: /_actor_owners$/ }).toArray(),+ ).toHaveLength(0);+ await deleteOwnedAgentCheckpoints('owner', undefined, undefined, custom);+ expect(await mongoose.connection.db!.collection('tenant_cp').countDocuments()).toBe(0);+ expect(await mongoose.connection.db!.collection('tenant_writes').countDocuments()).toBe(0);+});diff --git a/packages/api/src/agents/checkpoints/actor.ts b/packages/api/src/agents/checkpoints/actor.tsnew file mode 100644index 0000000000..43765a6c77--- /dev/null+++ b/packages/api/src/agents/checkpoints/actor.ts@@ -0,0 +1,100 @@+import type { TCheckpointerConfig } from 'librechat-data-provider';+import type { AgentEventCheckpointReference } from '../checkpointer';+import {+ captureAgentEventCheckpoint,+ deleteOwnedActorCheckpointScope,+ deleteAgentEventCheckpointReference,+ forkAgentEventCheckpoint,+ getAgentCheckpointer,+ LIBRECHAT_CHECKPOINT_NAMESPACE_KEY,+ LIBRECHAT_CHECKPOINT_OWNER_KEY,+ LIBRECHAT_LEGACY_CHECKPOINT_KEY,+} from '../checkpointer';+import { checkpointOwnerNamespacePrefix } from '../../stream/checkpoints';+import { acknowledgeActorPruning, drainActorPruning } from './pruning';++type HistoricalReference = Omit<AgentEventCheckpointReference, 'checkpointId'> & {+ checkpointId?: string;+};++/** Preserve the SDK wire format; each new payload row carries authenticated ownership. */+export function createOwnedActorCheckpoints(user: string, tenantId?: string) {+ const owner = checkpointOwnerNamespacePrefix(user, tenantId);+ async function resolveNamespace(+ reference: HistoricalReference,+ cfg?: TCheckpointerConfig,+ ): Promise<string | undefined> {+ if (!reference.checkpointId)+ throw new Error('Historical actor checkpoint reference is missing its checkpoint id');+ const saver = await getAgentCheckpointer(cfg);+ if (!saver) throw new Error('Event actor checkpoints require a durable checkpointer');+ const tuple = await saver.getTuple({+ configurable: {+ thread_id: reference.threadId,+ checkpoint_ns: '',+ checkpoint_id: reference.checkpointId,+ [LIBRECHAT_CHECKPOINT_NAMESPACE_KEY]: reference.checkpointNs,+ [LIBRECHAT_CHECKPOINT_OWNER_KEY]: owner,+ [LIBRECHAT_LEGACY_CHECKPOINT_KEY]: reference.checkpointId,+ },+ });+ return tuple?.checkpoint.id === reference.checkpointId ? reference.checkpointNs : undefined;+ }++ const fork: typeof forkAgentEventCheckpoint = async (+ source,+ logical,+ invocationId,+ cfg,+ overlay,+ ) => forkAgentEventCheckpoint(source, logical, invocationId, cfg, overlay, owner);++ async function capture(+ threadId: string,+ logical: string,+ invocationId: string,+ cfg?: TCheckpointerConfig,+ storageNamespace?: string | null,+ legacyCheckpointId?: string,+ ): Promise<AgentEventCheckpointReference | null> {+ if (storageNamespace === null) return null;+ return captureAgentEventCheckpoint(+ threadId,+ storageNamespace ?? logical,+ invocationId,+ cfg,+ owner,+ legacyCheckpointId,+ );+ }++ async function removeOwned(+ reference: Pick<AgentEventCheckpointReference, 'threadId' | 'checkpointNs'>,+ cfg?: TCheckpointerConfig,+ ): Promise<void> {+ await deleteOwnedActorCheckpointScope(reference.threadId, reference.checkpointNs, owner, cfg);+ }++ async function remove(reference: HistoricalReference, cfg?: TCheckpointerConfig): Promise<void> {+ if (!reference.checkpointId)+ throw new Error('Historical actor checkpoint reference is missing its checkpoint id');+ await removeOwned(reference, cfg);+ await deleteAgentEventCheckpointReference(+ { ...reference, checkpointId: reference.checkpointId },+ cfg,+ owner,+ );+ }++ return {+ resolveNamespace,+ fork,+ capture,+ remove,+ removeOwned,+ drain: (threadId: string, cfg?: TCheckpointerConfig) =>+ drainActorPruning(user, tenantId, threadId, (reference) => remove(reference, cfg)),+ acknowledgePruning: (reference: AgentEventCheckpointReference) =>+ acknowledgeActorPruning(user, tenantId, reference.threadId, reference),+ };+}diff --git a/packages/api/src/agents/checkpoints/config.ts b/packages/api/src/agents/checkpoints/config.tsnew file mode 100644index 0000000000..9dea3996ff--- /dev/null+++ b/packages/api/src/agents/checkpoints/config.ts@@ -0,0 +1,31 @@+import type { TCheckpointerConfig } from 'librechat-data-provider';+import { DEFAULT_CHECKPOINT_TTL_SECONDS } from '../../stream/checkpoints';++const DEFAULT_CHECKPOINT_COLLECTION = 'agent_checkpoints';+const DEFAULT_CHECKPOINT_WRITES_COLLECTION = 'agent_checkpoint_writes';++/** Checkpointer settings with all defaults applied. */+export interface ResolvedCheckpointerConfig {+ type: 'mongo' | 'memory';+ /** Approval window / TTL in seconds. */+ ttlSeconds: number;+ checkpointCollectionName: string;+ checkpointWritesCollectionName: string;+}++/**+ * Apply defaults to the YAML `endpoints.agents.checkpointer` block. Mirrors+ * {@link resolveRecursionLimit} — the schema stays descriptive, defaults live here.+ */+export function resolveCheckpointerConfig(+ cfg: TCheckpointerConfig | undefined,+): ResolvedCheckpointerConfig {+ return {+ type: cfg?.type ?? 'mongo',+ ttlSeconds:+ typeof cfg?.ttl === 'number' && cfg.ttl > 0 ? cfg.ttl : DEFAULT_CHECKPOINT_TTL_SECONDS,+ checkpointCollectionName: cfg?.checkpointCollectionName ?? DEFAULT_CHECKPOINT_COLLECTION,+ checkpointWritesCollectionName:+ cfg?.checkpointWritesCollectionName ?? DEFAULT_CHECKPOINT_WRITES_COLLECTION,+ };+}diff --git a/packages/api/src/agents/checkpoints/deletion.integration.spec.ts b/packages/api/src/agents/checkpoints/deletion.integration.spec.tsnew file mode 100644index 0000000000..84d8b59eb9--- /dev/null+++ b/packages/api/src/agents/checkpoints/deletion.integration.spec.ts@@ -0,0 +1,389 @@+import mongoose from 'mongoose';+import { MongoMemoryServer } from 'mongodb-memory-server';+import { openCheckpointDeletion, createCheckpointDeletionReclaimer } from './deletion';+import { createCheckpointNamespace } from '../../stream/checkpoints';+import { deleteOwnedAgentCheckpoints } from '../checkpointer';++let server: MongoMemoryServer;+const cfg = {+ type: 'mongo' as const,+ checkpointCollectionName: 'cleanup_cp',+ checkpointWritesCollectionName: 'cleanup_writes',+};++beforeAll(async () => {+ server = await MongoMemoryServer.create();+ await mongoose.connect(server.getUri());+}, 60000);+afterAll(async () => {+ await mongoose.disconnect();+ await server.stop();+});+afterEach(async () => {+ jest.restoreAllMocks();+ await mongoose.connection.db!.dropDatabase();+});++test('cleanup identity survives absent jobs and missing TTL indexes', async () => {+ const ns = createCheckpointNamespace('owner', 'tenant');+ const other = createCheckpointNamespace('other', 'tenant');+ const otherTenant = createCheckpointNamespace('owner', 'other-tenant');+ const rows = [ns, `${ns}|child`, other, otherTenant, '', '1000'].map((checkpoint_ns) => ({+ thread_id: 'thread',+ checkpoint_ns,+ }));+ for (const name of ['cleanup_cp', 'cleanup_writes']) {+ await mongoose.connection.db!.collection(name).insertMany(rows.map((row) => ({ ...row })));+ }+ await deleteOwnedAgentCheckpoints('owner', 'tenant', ['thread'], cfg);+ await deleteOwnedAgentCheckpoints('owner', 'tenant', ['thread'], cfg);+ for (const name of ['cleanup_cp', 'cleanup_writes']) {+ const remaining = await mongoose.connection.db!.collection(name).find().toArray();+ expect(remaining.map((row) => row.checkpoint_ns).sort()).toEqual(+ [other, otherTenant, '', '1000'].sort(),+ );+ }+});++test('account cleanup remains retryable after one collection deletion fails', async () => {+ const checkpoint_ns = createCheckpointNamespace('owner');+ for (const name of ['cleanup_cp', 'cleanup_writes']) {+ await mongoose.connection.db!.collection(name).insertOne({ thread_id: 'gone', checkpoint_ns });+ }+ jest+ .spyOn(mongoose.mongo.Collection.prototype, 'deleteMany')+ .mockRejectedValueOnce(new Error('temporary failure'));+ await expect(deleteOwnedAgentCheckpoints('owner', undefined, undefined, cfg)).rejects.toThrow(+ 'temporary failure',+ );+ jest.restoreAllMocks();+ await deleteOwnedAgentCheckpoints('owner', undefined, undefined, cfg);+ expect(await mongoose.connection.db!.collection('cleanup_cp').countDocuments()).toBe(0);+ expect(await mongoose.connection.db!.collection('cleanup_writes').countDocuments()).toBe(0);+});++test('deletion intent retains every cascade wave across retries and scopes owners and roots', async () => {+ const first = await openCheckpointDeletion('owner', 'tenant', 'root', cfg);+ await first.remember(['root']);+ await first.remember(['child', 'grandchild']);+ const retry = await openCheckpointDeletion('owner', 'tenant', 'root', cfg);+ expect(retry.conversationIds().sort()).toEqual(['child', 'grandchild', 'root']);+ expect((await openCheckpointDeletion('other', 'tenant', 'root', cfg)).conversationIds()).toEqual(+ [],+ );+ expect((await openCheckpointDeletion('owner', 'other', 'root', cfg)).conversationIds()).toEqual(+ [],+ );+ expect(+ (await openCheckpointDeletion('owner', 'tenant', 'other-root', cfg)).conversationIds(),+ ).toEqual([]);+ await retry.acknowledge();+ expect((await openCheckpointDeletion('owner', 'tenant', 'root', cfg)).conversationIds()).toEqual(+ [],+ );+});++test('an earlier attempt cannot acknowledge a newer attempt’s intent', async () => {+ const first = await openCheckpointDeletion('owner', undefined, 'root', cfg);+ await first.remember(['child']);+ const second = await openCheckpointDeletion('owner', undefined, 'root', cfg);+ await second.remember(['child']);+ await first.acknowledge();+ expect((await openCheckpointDeletion('owner', undefined, 'root', cfg)).conversationIds()).toEqual(+ ['child'],+ );+ await second.acknowledge();+});++test('thousands of conversation targets use bounded cleanup commands', async () => {+ const ids = Array.from({ length: 1100 }, (_, i) => `thread-${i}`);+ const intent = await openCheckpointDeletion('owner', undefined, 'root', cfg);+ await intent.remember(ids);+ const ns = createCheckpointNamespace('owner');+ await mongoose.connection+ .db!.collection('cleanup_cp')+ .insertMany(ids.map((thread_id) => ({ thread_id, checkpoint_ns: ns })));+ const spy = jest.spyOn(mongoose.mongo.Collection.prototype, 'deleteMany');+ await deleteOwnedAgentCheckpoints('owner', undefined, ids, cfg);+ expect(spy.mock.calls.every(([filter]) => filter?.thread_id.$in.length <= 256)).toBe(true);+ expect(await mongoose.connection.db!.collection('cleanup_cp').countDocuments()).toBe(0);+ await intent.acknowledge();+ expect(+ (await openCheckpointDeletion('owner', undefined, undefined, cfg)).conversationIds(),+ ).toEqual([]);+});++test('snapshots legacy references without per-reference ownership lookups', async () => {+ const ids = Array.from({ length: 257 }, (_, i) => `thread-${i}`);+ await mongoose.connection.db!.collection('conversations').insertMany(+ ids.map((conversationId) => ({+ user: 'owner',+ conversationId,+ subagentThread: {},+ agentEventActorCleanup: Array.from({ length: 4 }, (_, i) => ({+ threadId: conversationId,+ checkpointNs: `event-actor/${i}`,+ checkpointId: `checkpoint-${i}`,+ })),+ })),+ );+ const deletion = await openCheckpointDeletion('owner', undefined, 'root', cfg);+ const find = jest.spyOn(mongoose.mongo.Collection.prototype, 'find');+ const findOne = jest.spyOn(mongoose.mongo.Collection.prototype, 'findOne');+ await deletion.remember(ids);+ const scopeReads = find.mock.calls.filter(+ (_, index) => find.mock.contexts[index].collectionName === 'cleanup_cp_actor_owners',+ );+ expect(scopeReads).toHaveLength(0);+ expect(+ findOne.mock.calls.filter(+ (_, index) => findOne.mock.contexts[index].collectionName === 'cleanup_cp_actor_owners',+ ),+ ).toHaveLength(0);+ expect(deletion.conversationIds()).toHaveLength(257);+ const deletionCommands = jest.spyOn(mongoose.mongo.Collection.prototype, 'deleteMany');+ await deletion.cleanup();+ const exactCommands = deletionCommands.mock.calls.filter(([filter]) => filter?.$and != null);+ expect(exactCommands).toHaveLength(10);+ expect(+ exactCommands.every(([filter]) => (filter?.$and?.[1]?.$or?.length ?? Infinity) <= 256),+ ).toBe(true);+ expect(+ await mongoose.connection.db!.collection('agent_checkpoint_deletions').countDocuments(),+ ).toBe(257 * 5);+});++test('memory checkpointer conversations can still record and acknowledge deletion intent', async () => {+ const memory = { ...cfg, type: 'memory' as const };+ const deletion = await openCheckpointDeletion('owner', undefined, 'thread', memory);+ await deletion.remember(['thread']);+ await deletion.cleanup();+ await deletion.acknowledge();+ expect(+ await mongoose.connection.db!.collection('agent_checkpoint_deletions').countDocuments(),+ ).toBe(0);+});++test('reclaims only empty recorded stores and discovers remaining work across configurations', async () => {+ const other = {+ ...cfg,+ checkpointCollectionName: 'custom_cp',+ checkpointWritesCollectionName: 'custom_writes',+ };+ for (const storage of [cfg, other]) {+ const deletion = await openCheckpointDeletion('owner', 'tenant', 'root', storage);+ await deletion.remember(['child']);+ }+ const db = mongoose.connection.db!;+ await db+ .collection('custom_writes')+ .insertOne({ thread_id: 'child', checkpoint_ns: createCheckpointNamespace('owner', 'tenant') });+ const getJobs = jest.fn().mockResolvedValue([]);+ const reclaim = createCheckpointDeletionReclaimer(getJobs);+ expect(await reclaim(25)).toBe(1);+ expect(getJobs).toHaveBeenCalledTimes(1);+ expect((await openCheckpointDeletion('owner', 'tenant', 'root', cfg)).conversationIds()).toEqual([+ 'child',+ ]);+ expect(+ (await openCheckpointDeletion('owner', 'tenant', 'root', other)).conversationIds(),+ ).toEqual(['child']);+ await db.collection('custom_writes').deleteMany({});+ expect(await reclaim(25)).toBe(1);+});++test.each(['conversations', 'messages', 'toolcalls', 'sharedlinks'])(+ 'retains cascade identity while %s work survives',+ async (name) => {+ const db = mongoose.connection.db!;+ const userId = new mongoose.Types.ObjectId().toString();+ const deletion = await openCheckpointDeletion(userId, undefined, 'root', cfg);+ await deletion.remember(['child']);+ await db.collection(name).insertOne({+ user: name === 'toolcalls' ? new mongoose.Types.ObjectId(userId) : userId,+ conversationId: 'child',+ });+ const reclaim = createCheckpointDeletionReclaimer(async () => []);+ expect(await reclaim(25)).toBe(0);+ await db.collection(name).deleteMany({});+ expect(await reclaim(25)).toBe(1);+ },+);++test('replays exact legacy proof without TTL indexes and rotates past retained work', async () => {+ const db = mongoose.connection.db!;+ const checkpoint = {+ threadId: 'child',+ checkpointNs: 'event-actor/legacy',+ checkpointId: 'exact',+ };+ await db.collection('conversations').insertOne({+ user: 'owner',+ conversationId: 'child',+ subagentThread: {},+ agentEventActorCleanup: [checkpoint],+ });+ const deletion = await openCheckpointDeletion('owner', undefined, 'root', cfg);+ await deletion.remember(['child', 'empty']);+ await db.collection('conversations').deleteMany({});+ await db.collection('cleanup_writes').insertOne({+ thread_id: 'child',+ checkpoint_ns: checkpoint.checkpointNs,+ checkpoint_id: checkpoint.checkpointId,+ });+ const reclaim = createCheckpointDeletionReclaimer(async () => []);+ for (let pass = 0; pass < 6; pass++) await reclaim(1);+ expect(await db.collection('cleanup_writes').countDocuments()).toBe(0);+ expect(await db.collection('agent_checkpoint_deletions').countDocuments()).toBe(0);+});++test('retains writer obligations, renewed revisions, and lookup failures', async () => {+ const deletion = await openCheckpointDeletion('owner', undefined, 'root', cfg);+ await deletion.remember(['child']);+ const getJobs = jest.fn().mockResolvedValue(['pending-host']);+ const reclaim = createCheckpointDeletionReclaimer(getJobs);+ expect(await reclaim(25)).toBe(0);+ getJobs.mockRejectedValueOnce(new Error('job store unavailable'));+ await expect(reclaim(25)).rejects.toThrow('reclamation failed');+ getJobs.mockImplementationOnce(async () => {+ const renewed = await openCheckpointDeletion('owner', undefined, 'root', cfg);+ await renewed.remember(['child']);+ return [];+ });+ expect(await reclaim(25)).toBe(0);+ expect((await openCheckpointDeletion('owner', undefined, 'root', cfg)).conversationIds()).toEqual(+ ['child'],+ );+ getJobs.mockResolvedValue([]);+ expect(await reclaim(25)).toBe(1);+});++test('current-tenant deletion recovers tenantless ownership and exact references without erasing another tenant', async () => {+ const db = mongoose.connection.db!;+ const current = createCheckpointNamespace('owner', 'tenant-a');+ const legacy = createCheckpointNamespace('owner');+ const foreign = createCheckpointNamespace('owner', 'tenant-b');+ const refs = [+ { thread_id: 'legacy-thread', checkpoint_ns: 'event-actor/legacy', checkpoint_id: 'proved' },+ { thread_id: 'legacy-thread', checkpoint_ns: 'event-actor/legacy', checkpoint_id: 'unproved' },+ ];+ for (const name of ['cleanup_cp', 'cleanup_writes']) {+ await db+ .collection(name)+ .insertMany([+ { thread_id: 'current-thread', checkpoint_ns: current },+ { thread_id: 'legacy-thread', checkpoint_ns: legacy },+ { thread_id: 'foreign-thread', checkpoint_ns: foreign },+ ...refs,+ ]);+ }+ await db.collection('conversations').insertOne({+ user: 'owner',+ conversationId: 'legacy-thread',+ subagentThread: {},+ agentEventActorCleanup: [+ { threadId: 'legacy-thread', checkpointNs: 'event-actor/legacy', checkpointId: 'proved' },+ ],+ });+ const deletion = await openCheckpointDeletion('owner', 'tenant-a', undefined, cfg);+ await deletion.remember(['current-thread', 'legacy-thread']);+ await db.collection('conversations').deleteMany({ user: 'owner' });+ const retry = await openCheckpointDeletion('owner', 'tenant-a', undefined, cfg);+ expect(retry.conversationIds().sort()).toEqual(['current-thread', 'legacy-thread']);+ await retry.cleanup();+ await retry.acknowledge();+ for (const name of ['cleanup_cp', 'cleanup_writes']) {+ const rows = await db.collection(name).find().toArray();+ expect(rows).toHaveLength(2);+ expect(rows.map((row) => row.checkpoint_ns)).toEqual([foreign, 'event-actor/legacy']);+ expect(rows.find((row) => row.checkpoint_id)?.checkpoint_id).toBe('unproved');+ }+ expect(await db.collection('agent_checkpoint_deletions').countDocuments()).toBe(0);+});++test.each(['mongo', 'memory'] as const)(+ 'replays a failed cascade against recorded stores after switching to %s',+ async (type) => {+ const db = mongoose.connection.db!;+ const next = {+ type,+ checkpointCollectionName: 'next_cp',+ checkpointWritesCollectionName: 'next_writes',+ };+ const ns = createCheckpointNamespace('owner', 'tenant');+ const foreign = createCheckpointNamespace('foreign', 'tenant');+ for (const name of ['cleanup_cp', 'cleanup_writes', 'next_cp', 'next_writes']) {+ await db.collection(name).insertMany([+ { thread_id: 'child', checkpoint_ns: ns },+ { thread_id: 'child', checkpoint_ns: foreign },+ { thread_id: 'unrelated', checkpoint_ns: ns },+ ]);+ }+ const original = await openCheckpointDeletion('owner', 'tenant', 'root', cfg);+ await original.remember(['child']);+ const attempt = await openCheckpointDeletion('owner', 'tenant', 'root', next);+ expect(attempt.conversationIds()).toEqual(['child']);+ await attempt.remember(attempt.conversationIds());+ const remove = mongoose.mongo.Collection.prototype.deleteMany;+ jest+ .spyOn(mongoose.mongo.Collection.prototype, 'deleteMany')+ .mockImplementationOnce(async () => {+ throw new Error('store unavailable');+ });+ await expect(attempt.cleanup()).rejects.toThrow('store unavailable');+ jest.restoreAllMocks();+ expect(remove).toBe(mongoose.mongo.Collection.prototype.deleteMany);+ expect(await db.collection('agent_checkpoint_deletions').countDocuments()).toBe(2);+ const retry = await openCheckpointDeletion('owner', 'tenant', 'root', next);+ await retry.cleanup();+ for (const name of [+ 'cleanup_cp',+ 'cleanup_writes',+ ...(type === 'mongo' ? ['next_cp', 'next_writes'] : []),+ ]) {+ expect(+ await db+ .collection(name)+ .find({}, { projection: { _id: 0 } })+ .toArray(),+ ).toEqual([+ { thread_id: 'child', checkpoint_ns: foreign },+ { thread_id: 'unrelated', checkpoint_ns: ns },+ ]);+ }+ await retry.acknowledge();+ expect(await db.collection('agent_checkpoint_deletions').countDocuments()).toBe(0);+ },+);++test('a failed owner deletion leaves no sibling delete running when the fence can reopen', async () => {+ const db = mongoose.connection.db!;+ const intent = await openCheckpointDeletion('owner', 'tenant', undefined, cfg);+ await intent.remember(['thread']);+ const remove = mongoose.mongo.Collection.prototype.deleteMany;+ const writesStarted = jest.fn();+ let releaseWrites!: () => void;+ const heldWrites = new Promise<void>((resolve) => {+ releaseWrites = resolve;+ });+ jest.spyOn(mongoose.mongo.Collection.prototype, 'deleteMany').mockImplementation(async function (+ this: InstanceType<typeof mongoose.mongo.Collection>,+ filter,+ options,+ ) {+ if (this.collectionName === 'cleanup_cp') throw new Error('checkpoint delete failed');+ writesStarted();+ await heldWrites;+ return remove.call(this, filter, options);+ });+ try {+ await expect(intent.cleanup()).rejects.toThrow('checkpoint delete failed');+ expect(writesStarted).not.toHaveBeenCalled();+ expect(await db.collection('agent_checkpoint_deletions').countDocuments()).toBe(1);+ } finally {+ releaseWrites();+ jest.restoreAllMocks();+ }+ await intent.cleanup();+ await intent.acknowledge();+});diff --git a/packages/api/src/agents/checkpoints/deletion.ts b/packages/api/src/agents/checkpoints/deletion.tsnew file mode 100644index 0000000000..074341dc2f--- /dev/null+++ b/packages/api/src/agents/checkpoints/deletion.ts@@ -0,0 +1,332 @@+import mongoose from 'mongoose';+import { createHash, randomUUID } from 'crypto';+import { logger } from '@librechat/data-schemas';+import type { TCheckpointerConfig } from 'librechat-data-provider';+import type { AgentEventCheckpointReference } from '../checkpointer';+import type { ResolvedCheckpointerConfig } from './config';+import type { CheckpointStorageRecord } from './storage';+import {+ checkpointStorageKey,+ checkpointStorageConfigs,+ ownedCheckpointReferences,+ CHECKPOINT_STORAGE_COLLECTION,+} from './storage';+import { deleteOwnedAgentCheckpoints, deleteAgentEventCheckpointReferences } from '../checkpointer';+import { checkpointOwnerNamespacePrefix } from '../../stream/checkpoints';+import { historicalActorReferences } from './pruning';++interface DeletionTarget {+ _id: string;+ version: string;+ threadId: string;+ checkpoint?: AgentEventCheckpointReference;+ userId: string;+ tenantId?: string;+ storage: ResolvedCheckpointerConfig;+}++const DELETION_COLLECTION = 'agent_checkpoint_deletions';++export interface CheckpointDeletion {+ conversationIds(): string[];+ remember(conversationIds: readonly string[]): Promise<void>;+ cleanup(): Promise<void>;+ acknowledge(): Promise<void>;+}++const hash = (value: string | null) =>+ createHash('sha256').update(JSON.stringify(value)).digest('hex');++/** Durable deletion intent preserves cascade identity after topology is removed.+ * These records contain no checkpoint payload and exist only during deletion,+ * not once per generation. They must survive until both drain and cleanup succeed. */+export async function openCheckpointDeletion(+ userId: string,+ tenantId: string | undefined,+ rootConversationId: string | undefined,+ cfg?: TCheckpointerConfig,+): Promise<CheckpointDeletion> {+ if (!userId) {+ throw new Error('Checkpoint deletion requires an owner');+ }+ const db = mongoose.connection.db;+ if (!db || mongoose.connection.readyState !== 1) {+ throw new Error('Checkpoint database is unavailable');+ }+ const collection = db.collection<DeletionTarget>(DELETION_COLLECTION);+ const storageKey = checkpointStorageKey;+ const ownerPrefix = checkpointOwnerNamespacePrefix(userId, tenantId);+ const tenants = tenantId ? [tenantId, undefined] : [undefined];+ const prefixes = tenants.map((tenant) => {+ const prefix = checkpointOwnerNamespacePrefix(userId, tenant);+ return rootConversationId == null+ ? prefix+ : `${prefix}[0-9a-f]{64}:${hash(rootConversationId)}:`;+ });+ const retained = await collection+ .find({ $or: prefixes.map((prefix) => ({ _id: { $regex: `^${prefix}` } })) })+ .toArray();+ const targets = new Map(retained.map((target) => [target._id, target]));+ const stores = new Map(retained.map((target) => [storageKey(target.storage), target.storage]));+ async function refreshStores() {+ for (const storage of await checkpointStorageConfigs(userId, tenantId, cfg)) {+ stores.set(storageKey(storage), storage);+ }+ }+ await refreshStores();+ const version = randomUUID();+ const batchSize = 256;++ async function persist(batch: DeletionTarget[]) {+ await collection.bulkWrite(+ batch.map((target) => ({+ updateOne: {+ filter: { _id: target._id },+ update: {+ $set: {+ version,+ threadId: target.threadId,+ userId,+ tenantId,+ storage: target.storage,+ ...(target.checkpoint && { checkpoint: target.checkpoint }),+ },+ },+ upsert: true,+ },+ })),+ );+ for (const target of batch) targets.set(target._id, target);+ }++ const conversationIds = () => [+ ...new Set([...targets.values()].map((target) => target.threadId)),+ ];+ async function captureOwned(ids: readonly string[] | undefined) {+ let batch: DeletionTarget[] = [];+ for (const [key, storage] of stores) {+ const rootPrefix = `${ownerPrefix}${key}:${hash(rootConversationId ?? null)}:`;+ for await (const { checkpoint, conversationId } of ownedCheckpointReferences(+ userId,+ tenantId,+ ids,+ storage,+ )) {+ batch.push({+ _id: `${rootPrefix}${hash(conversationId)}:${hash(JSON.stringify([checkpoint.threadId, checkpoint.checkpointNs, checkpoint.checkpointId]))}`,+ version,+ threadId: conversationId,+ userId,+ tenantId,+ storage,+ checkpoint,+ });+ if (batch.length === batchSize) {+ await persist(batch);+ batch = [];+ }+ }+ }+ if (batch.length > 0) await persist(batch);+ }+ return {+ conversationIds,+ async remember(ids: readonly string[]) {+ await refreshStores();+ for (let offset = 0; offset < ids.length; offset += batchSize) {+ const threads = ids.slice(offset, offset + batchSize);+ for (const [key, storage] of stores) {+ const rootPrefix = `${ownerPrefix}${key}:${hash(rootConversationId ?? null)}:`;+ await persist(+ threads.map((threadId) => ({+ _id: `${rootPrefix}${hash(threadId)}`,+ version,+ threadId,+ userId,+ tenantId,+ storage,+ })),+ );+ }+ await captureOwned(threads);+ let batch: DeletionTarget[] = [];+ for await (const checkpoint of historicalActorReferences(userId, tenantId, threads)) {+ for (const [key, storage] of stores) {+ const rootPrefix = `${ownerPrefix}${key}:${hash(rootConversationId ?? null)}:`;+ batch.push({+ _id: `${rootPrefix}${hash(checkpoint.threadId)}:${hash(JSON.stringify([checkpoint.checkpointNs, checkpoint.checkpointId]))}`,+ version,+ threadId: checkpoint.threadId,+ userId,+ tenantId,+ storage,+ checkpoint,+ });+ if (batch.length === batchSize) {+ await persist(batch);+ batch = [];+ }+ }+ }+ if (batch.length > 0) await persist(batch);+ }+ },+ async cleanup() {+ await refreshStores();+ await captureOwned(rootConversationId == null ? undefined : conversationIds());+ const groups = new Map([...stores.keys()].map((key) => [key, [] as DeletionTarget[]]));+ for (const target of targets.values()) groups.get(storageKey(target.storage))!.push(target);+ for (const [key, storage] of stores) {+ const group = groups.get(key)!;+ const storedConfig = { ...storage, ttl: storage.ttlSeconds };+ const ids =+ rootConversationId == null+ ? undefined+ : [...new Set(group.map((target) => target.threadId))];+ for (const tenant of tenants) {+ await deleteOwnedAgentCheckpoints(userId, tenant, ids, storedConfig);+ }+ await deleteAgentEventCheckpointReferences(+ group.flatMap((target) => target.checkpoint ?? []),+ ownerPrefix,+ storedConfig,+ );+ }+ },+ async acknowledge() {+ const receipts = [...targets.values()];+ for (let offset = 0; offset < receipts.length; offset += batchSize) {+ await collection.deleteMany({+ $or: receipts.slice(offset, offset + batchSize).map(({ _id, version: captured }) => ({+ _id,+ version: captured,+ })),+ });+ }+ if (rootConversationId != null) return;+ const pending = await collection.findOne(+ { $or: prefixes.map((prefix) => ({ _id: { $regex: `^${prefix}` } })) },+ { projection: { _id: 1 } },+ );+ if (pending != null) throw new Error('Checkpoint deletion intent is still pending');+ // Owner-wide callers retain their deletion fence through acknowledgement.+ const descriptors = [...stores.keys()].flatMap((key) =>+ tenants.map((tenant) => `${checkpointOwnerNamespacePrefix(userId, tenant)}${key}`),+ );+ for (let offset = 0; offset < descriptors.length; offset += batchSize) {+ await db.collection<CheckpointStorageRecord>(CHECKPOINT_STORAGE_COLLECTION).deleteMany({+ _id: { $in: descriptors.slice(offset, offset + batchSize) },+ });+ }+ },+ };+}++/** Replay captured identities after topology deletion; never sweep new generations. */+export function createCheckpointDeletionReclaimer(+ getOwnerJobs: (userId: string, tenantId?: string) => Promise<string[]>,+): (limit: number) => Promise<number> {+ let after: string | undefined;+ return async (limit) => {+ if (!Number.isSafeInteger(limit) || limit <= 0) throw new Error('Invalid reclamation limit');+ const db = mongoose.connection.db;+ if (!db || mongoose.connection.readyState !== 1)+ throw new Error('Checkpoint database is unavailable');+ const collection = db.collection<DeletionTarget>(DELETION_COLLECTION);+ const targets = await collection+ .find(after == null ? {} : { _id: { $gt: after } })+ .sort({ _id: 1 })+ .limit(limit)+ .toArray();+ after = targets.length === limit ? targets[targets.length - 1]._id : undefined;+ const jobsByOwner = new Map<string, Promise<string[]>>();++ const hasPersistence = async (target: DeletionTarget): Promise<boolean> => {+ const { userId, tenantId, threadId, checkpoint, storage } = target;+ const owners = (tenantId ? [tenantId, undefined] : [undefined]).map((tenant) =>+ checkpointOwnerNamespacePrefix(userId, tenant),+ );+ const user = mongoose.isValidObjectId(userId) ? new mongoose.Types.ObjectId(userId) : userId;+ const siblingCollections = [+ [mongoose.models.Conversation?.collection.name ?? 'conversations', userId],+ [mongoose.models.Message?.collection.name ?? 'messages', userId],+ [mongoose.models.ToolCall?.collection.name ?? 'toolcalls', user],+ [mongoose.models.SharedLink?.collection.name ?? 'sharedlinks', userId],+ ] as const;+ const siblings = siblingCollections.map(([name, owner]) =>+ db+ .collection(name)+ .findOne({ user: owner, conversationId: threadId }, { projection: { _id: 1 } }),+ );+ const payload =+ storage.type === 'memory'+ ? []+ : [storage.checkpointCollectionName, storage.checkpointWritesCollectionName].map((name) =>+ db.collection(name).findOne(+ {+ $or: [+ ...owners.map((owner) => ({+ thread_id: { $in: [threadId, `${owner}${threadId}`] },+ $or: [{ checkpoint_ns: { $regex: `^${owner}` } }, { lc_owner: owner }],+ })),+ ...(checkpoint == null+ ? []+ : [+ {+ thread_id: checkpoint.threadId,+ checkpoint_ns: checkpoint.checkpointNs,+ checkpoint_id: checkpoint.checkpointId,+ $or: [{ lc_owner: { $in: owners } }, { lc_owner: { $exists: false } }],+ },+ ]),+ ],+ },+ { projection: { _id: 1 } },+ ),+ );+ return (await Promise.all([...siblings, ...payload])).some((row) => row != null);+ };++ const results = await Promise.allSettled(+ targets.map(async (target) => {+ const owner = checkpointOwnerNamespacePrefix(target.userId, target.tenantId);+ let jobs = jobsByOwner.get(owner);+ if (jobs == null) {+ jobs = getOwnerJobs(target.userId, target.tenantId);+ jobsByOwner.set(owner, jobs);+ }+ if ((await jobs).length > 0) return 0;+ if (target.checkpoint != null) {+ const conversation = await db+ .collection(mongoose.models.Conversation?.collection.name ?? 'conversations')+ .findOne(+ { user: target.userId, conversationId: target.threadId },+ { projection: { _id: 1 } },+ );+ if (conversation == null) {+ for (const tenant of target.tenantId ? [target.tenantId, undefined] : [undefined]) {+ await deleteAgentEventCheckpointReferences(+ [target.checkpoint],+ checkpointOwnerNamespacePrefix(target.userId, tenant),+ { ...target.storage, ttl: target.storage.ttlSeconds },+ );+ }+ }+ }+ if (await hasPersistence(target)) return 0;+ return (await collection.deleteOne({ _id: target._id, version: target.version }))+ .deletedCount;+ }),+ );+ const failures = results.filter((result) => result.status === 'rejected');+ if (failures.length > 0) {+ for (const failure of failures)+ logger.error('[checkpoints] Deletion evidence reclamation failed:', failure.reason);+ throw new Error('Checkpoint evidence reclamation failed');+ }+ return results.reduce(+ (count, result) => count + (result.status === 'fulfilled' ? result.value : 0),+ 0,+ );+ };+}diff --git a/packages/api/src/agents/checkpoints/pruning.ts b/packages/api/src/agents/checkpoints/pruning.tsnew file mode 100644index 0000000000..18a1fddf9e--- /dev/null+++ b/packages/api/src/agents/checkpoints/pruning.ts@@ -0,0 +1,110 @@+import mongoose from 'mongoose';+import type { IConversation } from '@librechat/data-schemas';+import type { AgentEventCheckpointReference } from '../checkpointer';++function conversations() {+ const db = mongoose.connection.db;+ if (!db || mongoose.connection.readyState !== 1) {+ throw new Error('Actor checkpoint cleanup requires Mongo storage');+ }+ return db.collection<Omit<IConversation, 'tenantId'> & { tenantId?: string | null }>(+ mongoose.models.Conversation?.collection.name ?? 'conversations',+ );+}++export async function acknowledgeActorPruning(+ user: string,+ tenantId: string | undefined,+ conversationId: string,+ reference: AgentEventCheckpointReference,+): Promise<void> {+ await conversations().updateOne(+ { user, tenantId: tenantId ?? null, conversationId },+ { $pull: { agentEventActorCleanup: reference } },+ );+}++export async function drainActorPruning(+ user: string,+ tenantId: string | undefined,+ conversationId: string,+ remove: (reference: AgentEventCheckpointReference) => Promise<void>,+): Promise<void> {+ const conversation = await conversations().findOne(+ { user, tenantId: tenantId ?? null, conversationId },+ { projection: { agentEventActorCleanup: 1 } },+ );+ for (const reference of conversation?.agentEventActorCleanup ?? []) {+ await remove(reference);+ await acknowledgeActorPruning(user, tenantId, conversationId, reference);+ }+}++/** Read hidden historical evidence while the owner-filtered conversation still exists. */+export async function* historicalActorReferences(+ user: string,+ tenantId: string | undefined,+ conversationIds: readonly string[] | undefined,+): AsyncGenerator<AgentEventCheckpointReference> {+ const ids = conversationIds == null ? undefined : [...new Set(conversationIds)];+ for (let offset = 0; offset < (ids?.length ?? 1); offset += 256) {+ const cursor = conversations().find(+ {+ user,+ tenantId: tenantId ? { $in: [tenantId, null] } : null,+ subagentThread: { $exists: true },+ ...(ids && { conversationId: { $in: ids.slice(offset, offset + 256) } }),+ },+ {+ projection: {+ conversationId: 1,+ 'agentEventActor.checkpoint': 1,+ 'agentEventActor.previousCheckpoint': 1,+ 'agentEventActorSuspension.suspension.checkpoint': 1,+ 'agentEventActorSuspension.suspension.invocation.fork': 1,+ 'agentEventActorSuspension.suspension.invocation.base.checkpoint': 1,+ 'agentEventActorReconciliations.checkpoint': 1,+ agentEventActorCleanup: 1,+ },+ },+ );+ for await (const conversation of cursor) {+ const suspension = conversation.agentEventActorSuspension?.suspension;+ const candidates = [+ conversation.agentEventActor?.checkpoint,+ conversation.agentEventActor?.previousCheckpoint,+ suspension?.checkpoint,+ suspension?.invocation?.fork,+ suspension?.invocation?.base?.checkpoint,+ ...(conversation.agentEventActorReconciliations ?? []).map((entry) => entry.checkpoint),+ ...(conversation.agentEventActorCleanup ?? []),+ ];+ const seen = new Set<string>();+ for (const reference of candidates) {+ if (+ typeof reference?.checkpointId !== 'string' ||+ reference.checkpointId.length === 0 ||+ typeof reference.checkpointNs !== 'string' ||+ !reference.checkpointNs.startsWith('event-actor/') ||+ reference.threadId !== conversation.conversationId+ ) {+ continue;+ }+ const key = JSON.stringify([+ reference.threadId,+ reference.checkpointNs,+ reference.checkpointId,+ ]);+ if (seen.has(key)) {+ continue;+ }+ seen.add(key);+ yield {+ threadId: reference.threadId,+ checkpointNs: reference.checkpointNs,+ checkpointId: reference.checkpointId,+ };+ }+ }+ }+}diff --git a/packages/api/src/agents/checkpoints/saver.ts b/packages/api/src/agents/checkpoints/saver.tsnew file mode 100644index 0000000000..cc77509ba3--- /dev/null+++ b/packages/api/src/agents/checkpoints/saver.ts@@ -0,0 +1,329 @@+import { WRITES_IDX_MAP } from '@langchain/langgraph-checkpoint';+import { MongoDBSaver } from '@langchain/langgraph-checkpoint-mongodb';+import type {+ Checkpoint,+ CheckpointMetadata,+ CheckpointTuple,+ CheckpointListOptions,+ CheckpointPendingWrite,+ PendingWrite,+} from '@langchain/langgraph-checkpoint';+import type { RunnableConfig } from '@langchain/core/runnables';+import type { Binary } from 'mongodb';+import type { Filter } from 'mongodb';++import type { CheckpointStorageRecord } from './storage';+import {+ CHECKPOINT_STORAGE_COLLECTION,+ LIBRECHAT_CHECKPOINT_STORAGE_OWNER_KEY,+ checkpointStorageKey,+} from './storage';++export const LIBRECHAT_CHECKPOINT_OWNER_KEY = '__librechat_checkpoint_owner';+export const LIBRECHAT_LEGACY_CHECKPOINT_KEY = '__librechat_legacy_checkpoint_id';++interface CheckpointRow {+ thread_id: string;+ checkpoint_ns: string;+ checkpoint_id: string;+ parent_checkpoint_id?: string;+ lc_owner?: string;+ type: string;+ checkpoint: Binary;+ metadata: Binary;+ metadata_search: CheckpointMetadata;+}++interface WriteRow {+ thread_id: string;+ checkpoint_ns: string;+ checkpoint_id: string;+ task_id: string;+ idx: number;+ channel: string;+ type: string;+ value: Binary;+ lc_owner?: string;+}++function ownerOf(config: RunnableConfig): string | undefined {+ const owner = config.configurable?.[LIBRECHAT_CHECKPOINT_OWNER_KEY];+ return typeof owner === 'string' && owner.length > 0 ? owner : undefined;+}++function identity(config: RunnableConfig): {+ thread_id: string;+ checkpoint_ns: string;+ checkpoint_id?: string;+} {+ const thread_id = config.configurable?.thread_id;+ const checkpoint_ns = config.configurable?.checkpoint_ns ?? '';+ const checkpoint_id = config.configurable?.checkpoint_id;+ if (+ typeof thread_id !== 'string' ||+ typeof checkpoint_ns !== 'string' ||+ (checkpoint_id != null && typeof checkpoint_id !== 'string')+ ) {+ throw new Error('Invalid owned checkpoint identity');+ }+ return { thread_id, checkpoint_ns, ...(checkpoint_id == null ? {} : { checkpoint_id }) };+}++/** Isolate physical storage by owner while preserving logical SDK references. */+export class OwnedMongoSaver extends MongoDBSaver {+ private async recordStorage(config: RunnableConfig): Promise<void> {+ const namespace = config.configurable?.checkpoint_ns;+ const candidate =+ ownerOf(config) ??+ (typeof namespace === 'string' ? namespace.match(/^lcg:v2:[0-9a-f]{64}:/)?.[0] : undefined) ??+ config.configurable?.[LIBRECHAT_CHECKPOINT_STORAGE_OWNER_KEY];+ if (typeof candidate !== 'string' || !/^lcg:v2:[0-9a-f]{64}:$/.test(candidate)) return;+ const storage = {+ type: 'mongo' as const,+ checkpointCollectionName: this.checkpointCollectionName,+ checkpointWritesCollectionName: this.checkpointWritesCollectionName,+ };+ await this.db+ .collection<CheckpointStorageRecord>(CHECKPOINT_STORAGE_COLLECTION)+ .updateOne(+ { _id: `${candidate}${checkpointStorageKey(storage)}` },+ { $setOnInsert: { owner: candidate, storage } },+ { upsert: true },+ );+ }++ private async tuple(doc: CheckpointRow, owner: string, legacy = false): Promise<CheckpointTuple> {+ const namespace = doc.checkpoint_ns.startsWith(owner)+ ? doc.checkpoint_ns.slice(owner.length)+ : doc.checkpoint_ns;+ const key = {+ thread_id: doc.thread_id.startsWith(owner)+ ? doc.thread_id.slice(owner.length)+ : doc.thread_id,+ checkpoint_ns: namespace,+ checkpoint_id: doc.checkpoint_id,+ };+ const rows = await this.db+ .collection<WriteRow>(this.checkpointWritesCollectionName)+ .find({+ checkpoint_id: key.checkpoint_id,+ $or: [+ {+ thread_id: `${owner}${key.thread_id}`,+ checkpoint_ns: `${owner}${namespace}`,+ lc_owner: owner,+ },+ ...(legacy+ ? [{ thread_id: key.thread_id, checkpoint_ns: namespace, lc_owner: { $exists: false } }]+ : []),+ ],+ })+ .toArray();+ const slots = new Map<string, WriteRow>();+ for (const row of rows) {+ const slot = JSON.stringify([row.task_id, row.idx]);+ if (!slots.has(slot) || row.checkpoint_ns === `${owner}${namespace}`) slots.set(slot, row);+ }+ const pendingWrites: CheckpointPendingWrite[] = await Promise.all(+ [...slots.values()].map(+ async (row) =>+ [+ row.task_id,+ row.channel,+ await this.serde.loadsTyped(row.type, row.value.value()),+ ] as CheckpointPendingWrite,+ ),+ );+ return {+ config: {+ configurable: {+ ...key,+ [LIBRECHAT_CHECKPOINT_OWNER_KEY]: owner,+ ...(legacy ? { [LIBRECHAT_LEGACY_CHECKPOINT_KEY]: doc.checkpoint_id } : {}),+ },+ },+ checkpoint: (await this.serde.loadsTyped(doc.type, doc.checkpoint.value())) as Checkpoint,+ metadata: (await this.serde.loadsTyped(doc.type, doc.metadata.value())) as CheckpointMetadata,+ pendingWrites,+ ...(doc.parent_checkpoint_id == null+ ? {}+ : {+ parentConfig: {+ configurable: {+ ...key,+ checkpoint_id: doc.parent_checkpoint_id,+ [LIBRECHAT_CHECKPOINT_OWNER_KEY]: owner,+ [LIBRECHAT_LEGACY_CHECKPOINT_KEY]: doc.parent_checkpoint_id,+ },+ },+ }),+ };+ }++ override async getTuple(config: RunnableConfig): Promise<CheckpointTuple | undefined> {+ const owner = ownerOf(config);+ if (owner == null) return super.getTuple(config);+ const key = identity(config);+ const checkpoints = this.db.collection<CheckpointRow>(this.checkpointCollectionName);+ let doc = await checkpoints+ .find({+ ...key,+ thread_id: `${owner}${key.thread_id}`,+ checkpoint_ns: `${owner}${key.checkpoint_ns}`,+ lc_owner: owner,+ })+ .sort({ checkpoint_id: -1 })+ .limit(1)+ .next();+ if (+ doc == null &&+ key.checkpoint_id != null &&+ key.checkpoint_id === config.configurable?.[LIBRECHAT_LEGACY_CHECKPOINT_KEY]+ ) {+ doc = await checkpoints.findOne({ ...key, lc_owner: { $exists: false } });+ }+ return doc == null+ ? undefined+ : this.tuple(+ doc,+ owner,+ key.checkpoint_id != null &&+ key.checkpoint_id === config.configurable?.[LIBRECHAT_LEGACY_CHECKPOINT_KEY],+ );+ }++ override async *list(+ config: RunnableConfig,+ options?: CheckpointListOptions,+ ): AsyncGenerator<CheckpointTuple> {+ const owner = ownerOf(config);+ if (owner == null) {+ yield* super.list(config, options);+ return;+ }+ const key = identity(config);+ const query: Filter<CheckpointRow> = {+ thread_id: `${owner}${key.thread_id}`,+ checkpoint_ns: `${owner}${key.checkpoint_ns}`,+ lc_owner: owner,+ };+ for (const [name, value] of Object.entries(options?.filter ?? {})) {+ if (value !== null && typeof value === 'object')+ throw new Error('Checkpoint metadata filters must be primitive');+ query[`metadata_search.${name}`] = value;+ }+ const before = options?.before?.configurable?.checkpoint_id;+ if (before != null) {+ if (typeof before !== 'string') throw new Error('Invalid checkpoint list boundary');+ query.checkpoint_id = { $lt: before };+ }+ let cursor = this.db+ .collection<CheckpointRow>(this.checkpointCollectionName)+ .find(query)+ .sort({ checkpoint_id: -1 });+ if (options?.limit != null) cursor = cursor.limit(options.limit);+ for await (const doc of cursor) yield await this.tuple(doc, owner);+ }++ override async put(+ config: RunnableConfig,+ checkpoint: Checkpoint,+ metadata: CheckpointMetadata,+ ): Promise<RunnableConfig> {+ await this.recordStorage(config);+ const owner = ownerOf(config);+ if (owner == null) return super.put(config, checkpoint, metadata);+ const key = identity(config);+ const [[type, serializedCheckpoint], [metadataType, serializedMetadata]] = await Promise.all([+ this.serde.dumpsTyped(checkpoint),+ this.serde.dumpsTyped(metadata),+ ]);+ if (type !== metadataType) throw new Error('Mismatched checkpoint and metadata types');+ const stored = {+ thread_id: key.thread_id,+ checkpoint_ns: key.checkpoint_ns,+ checkpoint_id: checkpoint.id,+ };+ await this.db.collection(this.checkpointCollectionName).updateOne(+ {+ ...stored,+ thread_id: `${owner}${key.thread_id}`,+ checkpoint_ns: `${owner}${key.checkpoint_ns}`,+ lc_owner: owner,+ },+ {+ $set: {+ parent_checkpoint_id: key.checkpoint_id,+ type,+ checkpoint: serializedCheckpoint,+ metadata: serializedMetadata,+ metadata_search: metadata,+ },+ ...(this.enableTimestamps ? { $currentDate: { upserted_at: true as const } } : {}),+ },+ { upsert: true },+ );+ return { configurable: { ...stored, [LIBRECHAT_CHECKPOINT_OWNER_KEY]: owner } };+ }++ override async putWrites(+ config: RunnableConfig,+ writes: PendingWrite[],+ taskId: string,+ ): Promise<void> {+ await this.recordStorage(config);+ const owner = ownerOf(config);+ if (owner == null) return super.putWrites(config, writes, taskId);+ const key = identity(config);+ if (key.checkpoint_id == null) throw new Error('Owned writes require a checkpoint id');+ const allSpecial = writes.every(([channel]) => channel in WRITES_IDX_MAP);+ const legacy = key.checkpoint_id === config.configurable?.[LIBRECHAT_LEGACY_CHECKPOINT_KEY];+ const existing =+ !allSpecial && legacy+ ? await this.db+ .collection<WriteRow>(this.checkpointWritesCollectionName)+ .find(+ { ...key, task_id: taskId, lc_owner: { $exists: false } },+ { projection: { idx: 1 } },+ )+ .toArray()+ : [];+ const legacySlots = new Set(existing.map((row) => row.idx));+ const operations = await Promise.all(+ writes.map(async ([channel, value], idx) => {+ if (legacySlots.has(WRITES_IDX_MAP[channel] ?? idx)) return null;+ const [type, serializedValue] = await this.serde.dumpsTyped(value);+ const fields = { channel, type, value: serializedValue, lc_owner: owner };+ return {+ updateOne: {+ filter: {+ ...key,+ thread_id: `${owner}${key.thread_id}`,+ checkpoint_ns: `${owner}${key.checkpoint_ns}`,+ task_id: taskId,+ idx: WRITES_IDX_MAP[channel] ?? idx,+ lc_owner: owner,+ },+ update: allSpecial+ ? {+ $set: fields,+ ...(this.enableTimestamps+ ? { $currentDate: { upserted_at: true as const } }+ : {}),+ }+ : {+ $setOnInsert: {+ ...fields,+ ...(this.enableTimestamps ? { upserted_at: new Date() } : {}),+ },+ },+ upsert: true,+ },+ };+ }),+ );+ const pending = operations.filter((operation) => operation != null);+ if (pending.length > 0)+ await this.db.collection(this.checkpointWritesCollectionName).bulkWrite(pending);+ }+}diff --git a/packages/api/src/agents/checkpoints/storage.integration.spec.ts b/packages/api/src/agents/checkpoints/storage.integration.spec.tsnew file mode 100644index 0000000000..31c916f1fb--- /dev/null+++ b/packages/api/src/agents/checkpoints/storage.integration.spec.ts@@ -0,0 +1,413 @@+import mongoose from 'mongoose';+import { MongoMemoryServer } from 'mongodb-memory-server';+import { emptyCheckpoint, INTERRUPT } from '@langchain/langgraph-checkpoint';+import type { RunnableConfig } from '@langchain/core/runnables';+import type { Collection } from 'mongodb';+import {+ getAgentCheckpointer,+ __resetCheckpointerForTests,+ LIBRECHAT_CHECKPOINT_OWNER_KEY,+ LIBRECHAT_CHECKPOINT_STORAGE_OWNER_KEY,+} from '../checkpointer';+import {+ createCheckpointNamespace,+ checkpointOwnerNamespacePrefix,+} from '../../stream/checkpoints';+import { openCheckpointDeletion, createCheckpointDeletionReclaimer } from './deletion';+import { checkpointStorageConfigs, CHECKPOINT_STORAGE_COLLECTION } from './storage';++let server: MongoMemoryServer;+const cfg = {+ type: 'mongo' as const,+ checkpointCollectionName: 'old_cp',+ checkpointWritesCollectionName: 'old_writes',+};+beforeAll(async () => {+ server = await MongoMemoryServer.create();+ await mongoose.connect(server.getUri());+}, 60000);+afterAll(async () => {+ await mongoose.disconnect();+ await server.stop();+});+afterEach(async () => {+ jest.restoreAllMocks();+ __resetCheckpointerForTests();+ await mongoose.connection.db!.dropDatabase();+});++async function seed(config: RunnableConfig, storage = cfg) {+ const saver = (await getAgentCheckpointer(storage))!;+ const checkpoint = emptyCheckpoint();+ await saver.putWrites(+ { configurable: { ...config.configurable, checkpoint_id: checkpoint.id } },+ [[INTERRUPT, [{ value: 'approve', resumable: true }]]],+ 'task',+ );+ await saver.put(config, checkpoint, { source: 'input', step: -1, parents: {} });+ return { saver, checkpoint };+}++test.each(['mongo', 'memory'] as const)(+ 'the first deletion finds the original store after a switch to %s',+ async (type) => {+ const config = {+ configurable: {+ thread_id: 'thread',+ checkpoint_ns: createCheckpointNamespace('owner', 'tenant'),+ },+ };+ await seed(config);+ const intermediate = {+ ...cfg,+ checkpointCollectionName: 'intermediate_cp',+ checkpointWritesCollectionName: 'intermediate_writes',+ };+ await seed(config, intermediate);+ const changed = {+ type,+ checkpointCollectionName: 'new_cp',+ checkpointWritesCollectionName: 'new_writes',+ };+ const descriptors = await checkpointStorageConfigs('owner', 'tenant', changed);+ expect(descriptors).toEqual(+ expect.arrayContaining([+ expect.objectContaining(cfg),+ expect.objectContaining(intermediate),+ expect.objectContaining(changed),+ ]),+ );+ expect(await checkpointStorageConfigs('foreign', 'tenant', changed)).toEqual([+ expect.objectContaining(changed),+ ]);+ const deletion = await openCheckpointDeletion('owner', 'tenant', 'thread', changed);+ await deletion.remember(['thread']);+ await deletion.cleanup();+ await deletion.acknowledge();+ expect(await mongoose.connection.db!.collection('old_cp').countDocuments()).toBe(0);+ expect(await mongoose.connection.db!.collection('old_writes').countDocuments()).toBe(0);+ expect(await mongoose.connection.db!.collection('intermediate_cp').countDocuments()).toBe(0);+ expect(await mongoose.connection.db!.collection('intermediate_writes').countDocuments()).toBe(+ 0,+ );+ },+);++test('concurrent generations share one write-ahead store descriptor', async () => {+ await Promise.all(+ Array.from({ length: 8 }, (_, index) =>+ seed({+ configurable: {+ thread_id: `thread-${index}`,+ checkpoint_ns: createCheckpointNamespace('owner', 'tenant'),+ },+ }),+ ),+ );+ const db = mongoose.connection.db!;+ expect(await db.collection(CHECKPOINT_STORAGE_COLLECTION).countDocuments()).toBe(1);+ expect(await db.collection('old_cp').countDocuments()).toBe(8);+ expect(await db.collection('old_writes').countDocuments()).toBe(8);+});++test('catalog failure prevents payload writes, and a later write restores a missing descriptor', async () => {+ const saver = (await getAgentCheckpointer(cfg))!;+ const checkpoint = emptyCheckpoint();+ const config = {+ configurable: {+ thread_id: 'thread',+ checkpoint_ns: createCheckpointNamespace('owner'),+ checkpoint_id: checkpoint.id,+ },+ };+ jest+ .spyOn(mongoose.mongo.Collection.prototype, 'updateOne')+ .mockRejectedValueOnce(new Error('catalog unavailable'));+ await expect(saver.putWrites(config, [[INTERRUPT, []]], 'task')).rejects.toThrow(+ 'catalog unavailable',+ );+ expect(await mongoose.connection.db!.collection('old_writes').countDocuments()).toBe(0);+ jest.restoreAllMocks();+ await saver.putWrites(config, [[INTERRUPT, []]], 'task');+ await mongoose.connection.db!.collection(CHECKPOINT_STORAGE_COLLECTION).deleteMany({});+ await saver.putWrites(config, [[INTERRUPT, []]], 'task');+ expect(+ await mongoose.connection.db!.collection(CHECKPOINT_STORAGE_COLLECTION).countDocuments(),+ ).toBe(1);+});++test('upgraded legacy writes record storage without changing the legacy physical layout', async () => {+ await seed({+ configurable: {+ thread_id: 'legacy',+ checkpoint_ns: '',+ [LIBRECHAT_CHECKPOINT_STORAGE_OWNER_KEY]: checkpointOwnerNamespacePrefix('owner', 'tenant'),+ },+ });+ expect(+ await mongoose.connection+ .db!.collection('old_cp')+ .findOne({ thread_id: 'legacy', checkpoint_ns: '' }),+ ).not.toBeNull();+ expect(await checkpointStorageConfigs('owner', 'tenant', { type: 'memory' })).toEqual(+ expect.arrayContaining([expect.objectContaining(cfg)]),+ );+});++test.each([false, true])(+ 'background replay cleans failed deletion without client retry (actor=%s)',+ async (actor) => {+ const owner = checkpointOwnerNamespacePrefix('owner', 'tenant');+ const namespace = actor+ ? 'event-actor/invocation'+ : createCheckpointNamespace('owner', 'tenant');+ await seed({+ configurable: {+ thread_id: 'thread',+ checkpoint_ns: namespace,+ ...(actor ? { [LIBRECHAT_CHECKPOINT_OWNER_KEY]: owner } : {}),+ },+ });+ await mongoose.connection+ .db!.collection('conversations')+ .insertOne({ user: 'owner', conversationId: 'thread' });+ const deletion = await openCheckpointDeletion('owner', 'tenant', 'thread', { type: 'memory' });+ await deletion.remember(['thread']);+ await mongoose.connection.db!.collection('conversations').deleteMany({});+ jest+ .spyOn(mongoose.mongo.Collection.prototype, 'deleteMany')+ .mockRejectedValueOnce(new Error('delete unavailable'));+ await expect(deletion.cleanup()).rejects.toThrow('delete unavailable');+ jest.restoreAllMocks();+ const jobs = jest.fn().mockResolvedValue(['live-job']);+ const recover = createCheckpointDeletionReclaimer(jobs);+ expect(await recover(25)).toBe(0);+ expect(await mongoose.connection.db!.collection('old_writes').countDocuments()).toBeGreaterThan(+ 0,+ );+ jobs.mockResolvedValue([]);+ for (let i = 0; i < 3; i++) await recover(25);+ expect(await mongoose.connection.db!.collection('old_cp').countDocuments()).toBe(0);+ expect(await mongoose.connection.db!.collection('old_writes').countDocuments()).toBe(0);+ expect(+ await mongoose.connection.db!.collection('agent_checkpoint_deletions').countDocuments(),+ ).toBe(0);+ },+);++test('background replay preserves a recreated conversation and never captures a replacement namespace', async () => {+ const original = createCheckpointNamespace('owner');+ await seed({ configurable: { thread_id: 'thread', checkpoint_ns: original } });+ const deletion = await openCheckpointDeletion('owner', undefined, 'thread', cfg);+ await deletion.remember(['thread']);+ const replacement = createCheckpointNamespace('owner');+ await seed({ configurable: { thread_id: 'thread', checkpoint_ns: replacement } });+ const db = mongoose.connection.db!;+ await db.collection('conversations').insertOne({ user: 'owner', conversationId: 'thread' });+ const recover = createCheckpointDeletionReclaimer(async () => []);+ await recover(25);+ expect(await db.collection('old_cp').countDocuments()).toBe(2);+ await db.collection('conversations').deleteMany({});+ for (let i = 0; i < 3; i++) await recover(25);+ expect(await db.collection('old_cp').distinct('checkpoint_ns')).toEqual([replacement]);+ expect(await db.collection('old_writes').distinct('checkpoint_ns')).toEqual([replacement]);+});++test('captures nested pending writes without a checkpoint and retains them across replay failures', async () => {+ const saver = (await getAgentCheckpointer(cfg))!;+ const namespace = `${createCheckpointNamespace('owner', 'tenant')}|nested:task`;+ await saver.putWrites(+ {+ configurable: { thread_id: 'child', checkpoint_ns: namespace, checkpoint_id: 'pending-only' },+ },+ [[INTERRUPT, []]],+ 'task',+ );+ const db = mongoose.connection.db!;+ expect(await db.collection('old_cp').countDocuments()).toBe(0);+ const deletion = await openCheckpointDeletion('owner', 'tenant', 'root', { type: 'memory' });+ await deletion.remember(['child']);+ const recover = createCheckpointDeletionReclaimer(async () => []);+ const originalDelete = mongoose.mongo.Collection.prototype.deleteMany;+ jest.spyOn(mongoose.mongo.Collection.prototype, 'deleteMany').mockImplementation(function (+ this: Collection,+ ...args+ ) {+ if (this.collectionName === 'old_writes')+ return Promise.reject(new Error('payload unavailable'));+ return originalDelete.apply(this, args);+ });+ for (let pass = 0; pass < 2; pass++) {+ await expect(recover(25)).rejects.toThrow('reclamation failed');+ expect(await db.collection('old_writes').countDocuments()).toBe(1);+ expect(+ await db+ .collection('agent_checkpoint_deletions')+ .countDocuments({ checkpoint: { $exists: true } }),+ ).toBe(1);+ }+ jest.restoreAllMocks();+ for (let pass = 0; pass < 3; pass++) await recover(25);+ expect(await db.collection('old_writes').countDocuments()).toBe(0);+ expect(await db.collection('agent_checkpoint_deletions').countDocuments()).toBe(0);+});++test.each(['thread', undefined])(+ 'final cleanup discovers a store registered during drain (root=%s)',+ async (root) => {+ const deletion = await openCheckpointDeletion('owner', undefined, root, { type: 'memory' });+ await deletion.remember(['thread']);+ await seed({+ configurable: { thread_id: 'thread', checkpoint_ns: createCheckpointNamespace('owner') },+ });+ await deletion.cleanup();+ await deletion.acknowledge();+ const db = mongoose.connection.db!;+ expect(await db.collection('old_cp').countDocuments()).toBe(0);+ expect(await db.collection('old_writes').countDocuments()).toBe(0);+ expect(await db.collection(CHECKPOINT_STORAGE_COLLECTION).countDocuments()).toBe(+ root == null ? 0 : 1,+ );+ },+);++test('each post-drain topology capture refreshes the catalog before conversation removal', async () => {+ const deletion = await openCheckpointDeletion('owner', undefined, 'thread', { type: 'memory' });+ await deletion.remember(['thread']);+ await seed({+ configurable: { thread_id: 'thread', checkpoint_ns: createCheckpointNamespace('owner') },+ });+ await deletion.remember(['thread']);+ const db = mongoose.connection.db!;+ expect(+ await db.collection('agent_checkpoint_deletions').countDocuments({+ checkpoint: { $exists: true },+ 'storage.checkpointCollectionName': 'old_cp',+ }),+ ).toBe(1);+});++test.each([false, true])(+ 'owner-wide cleanup journals orphan payload before deletion fails (actor=%s)',+ async (actor) => {+ await seed({+ configurable: {+ thread_id: 'orphan',+ checkpoint_ns: actor ? 'event-actor/orphan' : createCheckpointNamespace('owner', 'tenant'),+ ...(actor+ ? { [LIBRECHAT_CHECKPOINT_OWNER_KEY]: checkpointOwnerNamespacePrefix('owner', 'tenant') }+ : {}),+ },+ });+ const deletion = await openCheckpointDeletion('owner', 'tenant', undefined, { type: 'memory' });+ const originalDelete = mongoose.mongo.Collection.prototype.deleteMany;+ jest.spyOn(mongoose.mongo.Collection.prototype, 'deleteMany').mockImplementation(function (+ this: Collection,+ ...args+ ) {+ if (this.collectionName === 'old_cp') return Promise.reject(new Error('payload unavailable'));+ return originalDelete.apply(this, args);+ });+ await expect(deletion.cleanup()).rejects.toThrow('payload unavailable');+ const db = mongoose.connection.db!;+ expect(+ await db+ .collection('agent_checkpoint_deletions')+ .countDocuments({ checkpoint: { $exists: true }, threadId: 'orphan' }),+ ).toBe(1);+ expect(await db.collection(CHECKPOINT_STORAGE_COLLECTION).countDocuments()).toBe(1);+ jest.restoreAllMocks();+ const recover = createCheckpointDeletionReclaimer(async () => []);+ for (let pass = 0; pass < 3; pass++) await recover(25);+ expect(await db.collection('old_cp').countDocuments()).toBe(0);+ expect(await db.collection('old_writes').countDocuments()).toBe(0);+ expect(await db.collection('agent_checkpoint_deletions').countDocuments()).toBe(0);+ expect(await db.collection(CHECKPOINT_STORAGE_COLLECTION).countDocuments()).toBe(1);+ },+);++test('owner-wide acknowledgement retires only its stores and later writes register again', async () => {+ for (const [user, tenant] of [+ ['owner', 'tenant'],+ ['owner', undefined],+ ['owner', 'other-tenant'],+ ['foreign', 'tenant'],+ ]) {+ await seed({+ configurable: {+ thread_id: 'thread',+ checkpoint_ns: createCheckpointNamespace(user!, tenant),+ },+ });+ }+ const deletion = await openCheckpointDeletion('owner', 'tenant', undefined, { type: 'memory' });+ await deletion.cleanup();+ const db = mongoose.connection.db!;+ expect(await db.collection(CHECKPOINT_STORAGE_COLLECTION).countDocuments()).toBe(4);+ await deletion.acknowledge();+ expect(await db.collection(CHECKPOINT_STORAGE_COLLECTION).countDocuments()).toBe(2);+ expect(await db.collection('old_cp').countDocuments()).toBe(2);+ await seed({+ configurable: {+ thread_id: 'new-thread',+ checkpoint_ns: createCheckpointNamespace('owner', 'tenant'),+ },+ });+ expect(await db.collection(CHECKPOINT_STORAGE_COLLECTION).countDocuments()).toBe(3);+ expect(await db.collection('old_cp').countDocuments()).toBe(3);+});++test('failed or renewed journal acknowledgement preserves catalog discovery', async () => {+ await seed({+ configurable: { thread_id: 'thread', checkpoint_ns: createCheckpointNamespace('owner') },+ });+ const first = await openCheckpointDeletion('owner', undefined, undefined, cfg);+ await first.remember(['thread']);+ await first.cleanup();+ const db = mongoose.connection.db!;+ const originalDelete = mongoose.mongo.Collection.prototype.deleteMany;+ jest.spyOn(mongoose.mongo.Collection.prototype, 'deleteMany').mockImplementation(function (+ this: Collection,+ ...args+ ) {+ if (this.collectionName === 'agent_checkpoint_deletions')+ return Promise.reject(new Error('journal unavailable'));+ return originalDelete.apply(this, args);+ });+ await expect(first.acknowledge()).rejects.toThrow('journal unavailable');+ expect(await db.collection(CHECKPOINT_STORAGE_COLLECTION).countDocuments()).toBe(1);+ jest.restoreAllMocks();+ const renewed = await openCheckpointDeletion('owner', undefined, undefined, cfg);+ await renewed.remember(['thread']);+ await expect(first.acknowledge()).rejects.toThrow('intent is still pending');+ expect(await db.collection(CHECKPOINT_STORAGE_COLLECTION).countDocuments()).toBe(1);+ await renewed.cleanup();+ await renewed.acknowledge();+ expect(await db.collection(CHECKPOINT_STORAGE_COLLECTION).countDocuments()).toBe(0);+});++test('catalog retirement can be retried after the journal has already been acknowledged', async () => {+ await seed({+ configurable: { thread_id: 'thread', checkpoint_ns: createCheckpointNamespace('owner') },+ });+ const deletion = await openCheckpointDeletion('owner', undefined, undefined, cfg);+ await deletion.cleanup();+ const originalDelete = mongoose.mongo.Collection.prototype.deleteMany;+ jest.spyOn(mongoose.mongo.Collection.prototype, 'deleteMany').mockImplementation(function (+ this: Collection,+ ...args+ ) {+ if (this.collectionName === CHECKPOINT_STORAGE_COLLECTION)+ return Promise.reject(new Error('catalog unavailable'));+ return originalDelete.apply(this, args);+ });+ await expect(deletion.acknowledge()).rejects.toThrow('catalog unavailable');+ const db = mongoose.connection.db!;+ expect(await db.collection('agent_checkpoint_deletions').countDocuments()).toBe(0);+ expect(await db.collection(CHECKPOINT_STORAGE_COLLECTION).countDocuments()).toBe(1);+ jest.restoreAllMocks();+ const retry = await openCheckpointDeletion('owner', undefined, undefined, { type: 'memory' });+ await retry.cleanup();+ await retry.acknowledge();+ expect(await db.collection(CHECKPOINT_STORAGE_COLLECTION).countDocuments()).toBe(0);+});diff --git a/packages/api/src/agents/checkpoints/storage.ts b/packages/api/src/agents/checkpoints/storage.tsnew file mode 100644index 0000000000..c17e9cbe00--- /dev/null+++ b/packages/api/src/agents/checkpoints/storage.ts@@ -0,0 +1,108 @@+import mongoose from 'mongoose';+import { createHash } from 'crypto';+import type { TCheckpointerConfig } from 'librechat-data-provider';+import type { ResolvedCheckpointerConfig } from './config';+import { checkpointOwnerNamespacePrefix } from '../../stream/checkpoints';+import { resolveCheckpointerConfig } from './config';++export const CHECKPOINT_STORAGE_COLLECTION = 'agent_checkpoint_stores';+export const LIBRECHAT_CHECKPOINT_STORAGE_OWNER_KEY = '__librechat_checkpoint_storage_owner';+export type CheckpointStorage = Omit<ResolvedCheckpointerConfig, 'ttlSeconds'>;+export interface CheckpointStorageRecord {+ _id: string;+ owner: string;+ storage: CheckpointStorage;+}++export function checkpointStorageKey(storage: CheckpointStorage): string {+ const value = JSON.stringify([+ storage.type,+ storage.checkpointCollectionName,+ storage.checkpointWritesCollectionName,+ ]);+ return createHash('sha256').update(JSON.stringify(value)).digest('hex');+}++/** Descriptors locate stores; caller ownership and captured identities authorize deletion. */+export async function checkpointStorageConfigs(+ userId: string,+ tenantId: string | undefined,+ cfg?: TCheckpointerConfig,+): Promise<ResolvedCheckpointerConfig[]> {+ const db = mongoose.connection.db;+ if (!db || mongoose.connection.readyState !== 1)+ throw new Error('Checkpoint database is unavailable');+ const owners = (tenantId ? [tenantId, undefined] : [undefined]).map((tenant) =>+ checkpointOwnerNamespacePrefix(userId, tenant),+ );+ const records = await db+ .collection<CheckpointStorageRecord>(CHECKPOINT_STORAGE_COLLECTION)+ .find({ $or: owners.map((owner) => ({ _id: { $regex: `^${owner}` } })) })+ .toArray();+ const configs = records.map(({ storage }) => resolveCheckpointerConfig(storage));+ configs.push(resolveCheckpointerConfig(cfg));+ return [...new Map(configs.map((storage) => [checkpointStorageKey(storage), storage])).values()];+}++/** Capture exact owner-qualified identities, including orphan payload during owner-wide deletion. */+export async function* ownedCheckpointReferences(+ userId: string,+ tenantId: string | undefined,+ conversationIds: readonly string[] | undefined,+ storage: CheckpointStorage,+): AsyncGenerator<{+ conversationId: string;+ checkpoint: { threadId: string; checkpointNs: string; checkpointId: string };+}> {+ if (storage.type === 'memory') return;+ const db = mongoose.connection.db;+ if (!db || mongoose.connection.readyState !== 1)+ throw new Error('Checkpoint database is unavailable');+ const owners = (tenantId ? [tenantId, undefined] : [undefined]).map((tenant) =>+ checkpointOwnerNamespacePrefix(userId, tenant),+ );+ for (let offset = 0; offset < (conversationIds?.length ?? 1); offset += 64) {+ const logicalIds = new Map<string, string>();+ for (const id of conversationIds?.slice(offset, offset + 64) ?? []) {+ logicalIds.set(id, id);+ for (const owner of owners) logicalIds.set(`${owner}${id}`, id);+ }+ for (const name of [storage.checkpointCollectionName, storage.checkpointWritesCollectionName]) {+ const cursor = db+ .collection<{+ thread_id: string;+ checkpoint_ns: string;+ checkpoint_id: string;+ lc_owner?: string;+ }>(name)+ .find(+ {+ ...(conversationIds == null ? {} : { thread_id: { $in: [...logicalIds.keys()] } }),+ $or: [+ ...owners.map((owner) => ({ checkpoint_ns: { $regex: `^${owner}` } })),+ { lc_owner: { $in: owners } },+ ],+ },+ { projection: { thread_id: 1, checkpoint_ns: 1, checkpoint_id: 1, lc_owner: 1 } },+ );+ for await (const row of cursor) {+ if (typeof row.checkpoint_id !== 'string' || typeof row.checkpoint_ns !== 'string')+ continue;+ const logicalThread =+ row.lc_owner != null &&+ owners.includes(row.lc_owner) &&+ row.thread_id.startsWith(row.lc_owner)+ ? row.thread_id.slice(row.lc_owner.length)+ : row.thread_id;+ yield {+ conversationId: logicalIds.get(row.thread_id) ?? logicalThread,+ checkpoint: {+ threadId: row.thread_id,+ checkpointNs: row.checkpoint_ns,+ checkpointId: row.checkpoint_id,+ },+ };+ }+ }+ }+}diff --git a/packages/api/src/agents/index.ts b/packages/api/src/agents/index.tsindex 205c758e91..9feddf69d0 100644--- a/packages/api/src/agents/index.ts+++ b/packages/api/src/agents/index.ts@@ -5,6 +5,7 @@ export * from './callerCapabilities';export * from './client';export * from './config';export * from './checkpointer';+export * from './checkpoints/deletion';export * from './compatibility';export * from './compaction';export * from './contact';diff --git a/packages/api/src/agents/remote/lifecycle.spec.ts b/packages/api/src/agents/remote/lifecycle.spec.tsindex d3dd68407a..ea8400d976 100644--- a/packages/api/src/agents/remote/lifecycle.spec.ts+++ b/packages/api/src/agents/remote/lifecycle.spec.ts@@ -274,6 +274,43 @@ describe('Agent execution enrollment', () => {).resolves.toEqual(expect.arrayContaining(['chatcmpl-a', 'chatcmpl-b']));});+ it('enumerates exact and legacy owner jobs for destructive account cleanup', async () => {+ const store = manager.getJobStore();+ const legacy = await store.createJob('legacy-owner-run', 'user-1', 'conversation-legacy');+ const exact = await store.createJob(+ 'tenant-owner-run',+ 'user-1',+ 'conversation-tenant',+ 'tenant-a',+ );+ await store.createJob('foreign-tenant-run', 'user-1', 'conversation-foreign', 'tenant-b');+ const cleanupBlocking = await manager.getCleanupBlockingJobIdsForUser('user-1', 'tenant-a');+ expect(cleanupBlocking).toEqual(+ expect.arrayContaining(['legacy-owner-run', 'tenant-owner-run']),+ );+ expect(cleanupBlocking).not.toContain('foreign-tenant-run');+ await store.transitionStatus('legacy-owner-run', {+ from: 'running',+ to: 'requires_action',+ expectCreatedAt: legacy.createdAt,+ });+ await store.transitionStatus('tenant-owner-run', {+ from: 'running',+ to: 'requires_action',+ expectCreatedAt: exact.createdAt,+ });++ await expect(manager.getCleanupBlockingJobIdsForUser('user-1', 'tenant-a')).resolves.toEqual(+ [],+ );+ await expect(manager.getAccountCleanupJobIdsForUser('user-1', 'tenant-a')).resolves.toEqual(+ expect.arrayContaining(['legacy-owner-run', 'tenant-owner-run']),+ );+ await expect(+ manager.getAccountCleanupJobIdsForUser('user-1', 'tenant-a'),+ ).resolves.not.toContain('foreign-tenant-run');+ });+it('waits for every trailing write before reporting the first failure', async () => {const failure = new Error('artifact failed');const remaining = deferred<void>();diff --git a/packages/api/src/agents/triggers/actor.spec.ts b/packages/api/src/agents/triggers/actor.spec.tsindex 3abef83f71..c2d5fade69 100644--- a/packages/api/src/agents/triggers/actor.spec.ts+++ b/packages/api/src/agents/triggers/actor.spec.ts@@ -6,24 +6,34 @@ import type {import type { EventActorInterrupt } from '@librechat/agents';import {captureAgentEventCheckpoint,- deleteAgentCheckpoint,+ deleteOwnedActorCheckpointScope,+ deleteAgentEventCheckpointReference,forkAgentEventCheckpoint,getAgentCheckpointer,} from '../checkpointer';import { cancelAgentEventActor, executeAgentEventActor, resumeAgentEventActor } from './actor';import { createAgentEventActionRecorder, findAgentEventAppliedAction } from './outcome';+import { checkpointOwnerNamespacePrefix } from '../../stream/checkpoints';import { createAgentContextFingerprint } from '../compatibility';+import { drainActorPruning } from '../checkpoints/pruning';++jest.mock('../checkpoints/pruning', () => ({+ drainActorPruning: jest.fn(async () => undefined),+ acknowledgeActorPruning: jest.fn(async () => undefined),+}));jest.mock('../checkpointer', () => ({...jest.requireActual('../checkpointer'),captureAgentEventCheckpoint: jest.fn(),- deleteAgentCheckpoint: jest.fn(),+ deleteOwnedActorCheckpointScope: jest.fn(),+ deleteAgentEventCheckpointReference: jest.fn(),forkAgentEventCheckpoint: jest.fn(),getAgentCheckpointer: jest.fn(),}));const mockedCapture = jest.mocked(captureAgentEventCheckpoint);-const mockedDelete = jest.mocked(deleteAgentCheckpoint);+const mockedDeleteReference = jest.mocked(deleteAgentEventCheckpointReference);+const mockedDelete = jest.mocked(deleteOwnedActorCheckpointScope);const mockedFork = jest.mocked(forkAgentEventCheckpoint);const mockedGetCheckpointer = jest.mocked(getAgentCheckpointer);@@ -42,7 +52,11 @@ describe('event actor host adapter', () => {legacyTurn = null;nextCheckpoint = 1;jest.clearAllMocks();- mockedGetCheckpointer.mockResolvedValue({} as never);+ mockedGetCheckpointer.mockResolvedValue({+ getTuple: jest.fn(async (config) => ({+ checkpoint: { id: config.configurable.checkpoint_id },+ })),+ } as never);mockedFork.mockImplementation(async (source, checkpointNs) => ({...source,checkpointNs,@@ -54,6 +68,8 @@ describe('event actor host adapter', () => {}));mockedDelete.mockReset();mockedDelete.mockResolvedValue();+ mockedDeleteReference.mockReset();+ mockedDeleteReference.mockResolvedValue(true);});afterAll(() => {@@ -124,6 +140,47 @@ describe('event actor host adapter', () => {hasActionAdmission: jest.fn(async () => false),});+ it.each([false, true])(+ 'starts the snapshot during pruning and gates execution (failure=%s)',+ async (fail) => {+ let finish!: () => void;+ const pruning = new Promise<void>((resolve) => {+ finish = resolve;+ });+ jest.mocked(drainActorPruning).mockImplementationOnce(async () => {+ await pruning;+ if (fail) throw new Error('pruning failed');+ });+ const dependencies = deps();+ const invoke = jest.fn(async () => 'response');+ const execution = executeAgentEventActor(+ {+ user: 'user-1',+ conversationId,+ invocationId: 'event-prune',+ event: { id: 'event-prune', type: 'turn' },+ signal: new AbortController().signal,+ invoke,+ readAppliedAction: () => ({ toolName: 'submit_move' }),+ },+ dependencies,+ );+ const observed = execution.then(+ (value) => value,+ (error: Error) => error,+ );+ await new Promise((resolve) => setImmediate(resolve));+ expect(dependencies.getSnapshot).toHaveBeenCalledTimes(1);+ expect(invoke).not.toHaveBeenCalled();+ finish();+ const result = await observed;+ if (fail) {+ expect(invoke).not.toHaveBeenCalled();+ expect(result).toBeDefined();+ } else expect(invoke).toHaveBeenCalledTimes(1);+ },+ );+it('publishes a signed durable suspension instead of discarding a paused fork', async () => {const dependencies = {...deps(),@@ -137,7 +194,10 @@ describe('event actor host adapter', () => {invocationId: 'event-paused',event: { id: 'event-paused', type: 'turn' },signal: new AbortController().signal,- invoke: async () => 'paused-response',+ invoke: async ({ checkpointNamespace }) => {+ expect(checkpointNamespace).toMatch(/^event-actor\//);+ return 'paused-response';+ },readAppliedAction: () => undefined,readSuspension: () => ({actionId: 'action-paused',@@ -158,7 +218,10 @@ describe('event actor host adapter', () => {version: 1,attempt: 0,invocation: { invocationId: 'event-paused' },- checkpoint: { checkpointId: 'checkpoint-1' },+ checkpoint: {+ checkpointId: 'checkpoint-1',+ checkpointNs: expect.stringMatching(/^event-actor\//),+ },interrupt: {id: 'interrupt-paused',payload: { type: 'ask_user_question', question: 'Continue?' },@@ -175,6 +238,7 @@ describe('event actor host adapter', () => {expect(dependencies.storeSuspension).toHaveBeenCalledTimes(1);expect(dependencies.commitState).not.toHaveBeenCalled();expect(mockedDelete).not.toHaveBeenCalled();+ expect(mockedDeleteReference).not.toHaveBeenCalled();});it('preserves a pause reached after the expected action in the same fresh segment', async () => {@@ -256,12 +320,9 @@ describe('event actor host adapter', () => {);expect(mockedDelete).toHaveBeenCalledWith(conversationId,+ paused.execution.suspension.checkpoint.checkpointNs,+ checkpointOwnerNamespacePrefix('user-1'),undefined,- undefined,- expect.objectContaining({- throwOnError: true,- checkpointNamespace: paused.execution.suspension.checkpoint.checkpointNs,- }),);});@@ -334,7 +395,8 @@ describe('event actor host adapter', () => {resumeAttemptId: 'resume-cross-executor',resumeValue: { approved: true },signal: new AbortController().signal,- resume: async () => {+ resume: async ({ checkpointNamespace }) => {+ expect(checkpointNamespace).toMatch(/^event-actor\//);action = { toolName: 'submit_move', toolCallId: 'call-resumed' };return 'resumed-response';},@@ -489,12 +551,9 @@ describe('event actor host adapter', () => {);expect(mockedDelete).toHaveBeenCalledWith(conversationId,+ repaused.execution.suspension.checkpoint.checkpointNs,+ checkpointOwnerNamespacePrefix('user-1'),undefined,- undefined,- expect.objectContaining({- throwOnError: true,- checkpointNamespace: repaused.execution.suspension.checkpoint.checkpointNs,- }),);expect(dependencies.commitState).not.toHaveBeenCalled();});@@ -646,6 +705,7 @@ describe('event actor host adapter', () => {'event-2',undefined,undefined,+ checkpointOwnerNamespacePrefix('user-1'),);expect(state).toMatchObject({ generation: 2, checkpoint: { checkpointId: 'checkpoint-2' } });});@@ -764,6 +824,7 @@ describe('event actor host adapter', () => {'event-skill-context',undefined,checkpointMessageOverlay,+ checkpointOwnerNamespacePrefix('user-1'),);});@@ -1030,12 +1091,9 @@ describe('event actor host adapter', () => {expect(dependencies.commitState).not.toHaveBeenCalled();expect(mockedDelete).toHaveBeenCalledWith(conversationId,+ expect.stringMatching(/^event-actor\//),+ checkpointOwnerNamespacePrefix('user-1'),undefined,- undefined,- expect.objectContaining({- throwOnError: true,- checkpointNamespace: expect.stringMatching(/^event-actor\//),- }),);expect(state.generation).toBe(1);});@@ -1071,6 +1129,7 @@ describe('event actor host adapter', () => {);expect(dependencies.resolveReconciliation).not.toHaveBeenCalled();expect(mockedDelete).not.toHaveBeenCalled();+ expect(mockedDeleteReference).not.toHaveBeenCalled();});it('retains an applied fork when its terminal checkpoint cannot be observed', async () => {@@ -1099,6 +1158,7 @@ describe('event actor host adapter', () => {}),);expect(mockedDelete).not.toHaveBeenCalled();+ expect(mockedDeleteReference).not.toHaveBeenCalled();});it('retains applied-action evidence when result context capture fails', async () => {@@ -1134,6 +1194,7 @@ describe('event actor host adapter', () => {);expect(mockedCapture).not.toHaveBeenCalled();expect(mockedDelete).not.toHaveBeenCalled();+ expect(mockedDeleteReference).not.toHaveBeenCalled();});it('recovers an indeterminate cleanup after the actor head was committed', async () => {@@ -1150,7 +1211,7 @@ describe('event actor host adapter', () => {checkpointNs: 'event-actor/old',},};- mockedDelete.mockRejectedValueOnce(new Error('checkpoint cleanup unavailable'));+ mockedDeleteReference.mockRejectedValueOnce(new Error('checkpoint cleanup unavailable'));const dependencies = deps();const result = await executeAgentEventActor({@@ -1223,6 +1284,7 @@ describe('event actor host adapter', () => {}),);expect(mockedDelete).not.toHaveBeenCalled();+ expect(mockedDeleteReference).not.toHaveBeenCalled();});it('still records reconciliation when an indeterminate commit cannot be read back', async () => {@@ -1275,6 +1337,7 @@ describe('event actor host adapter', () => {}),);expect(mockedDelete).not.toHaveBeenCalled();+ expect(mockedDeleteReference).not.toHaveBeenCalled();});it('does not clear a checkpoint marker before durable history is verified', async () => {diff --git a/packages/api/src/agents/triggers/actor.ts b/packages/api/src/agents/triggers/actor.tsindex a6f769eef8..13526677ba 100644--- a/packages/api/src/agents/triggers/actor.ts+++ b/packages/api/src/agents/triggers/actor.ts@@ -22,13 +22,8 @@ import type { AgentEventCheckpointMessageOverlay } from '../checkpointer';import type { AgentContextFingerprint } from '../compatibility';import type { AgentTriggerExpectedAction } from './envelope';import type { AgentEventAppliedAction } from './types';-import {- captureAgentEventCheckpoint,- deleteAgentCheckpoint,- forkAgentEventCheckpoint,- getAgentCheckpointer,- getApprovalTtlMs,-} from '../checkpointer';+import { getAgentCheckpointer, getApprovalTtlMs } from '../checkpointer';+import { createOwnedActorCheckpoints } from '../checkpoints/actor';import { agentContextFingerprintsMatch } from '../compatibility';interface EventActorResult extends Record<string, EventActorEvent> {@@ -232,6 +227,7 @@ export async function executeAgentEventActor<T>(input: ExecuteAgentEventActorInput<T>,deps: AgentEventActorDependencies,): Promise<ExecuteAgentEventActorResult<T>> {+ const checkpoints = createOwnedActorCheckpoints(input.user, input.tenantId);let value: T | undefined;let invocationError: unknown;let ownedActionAdmissionId: string | undefined;@@ -255,11 +251,14 @@ export async function executeAgentEventActor<T>(if (context.signal.aborted) {throw context.signal.reason;}- const snapshot = await deps.getSnapshot({- user: input.user,- conversationId: input.conversationId,- ...(input.tenantId == null ? {} : { tenantId: input.tenantId }),- });+ const [snapshot] = await Promise.all([+ deps.getSnapshot({+ user: input.user,+ conversationId: input.conversationId,+ ...(input.tenantId == null ? {} : { tenantId: input.tenantId }),+ }),+ checkpoints.drain(input.conversationId, input.checkpointer),+ ]);if (snapshot === undefined) {throw new Error('Event actor binding is no longer active');}@@ -392,7 +391,7 @@ export async function executeAgentEventActor<T>(return { status: 'checkpoint_unavailable', head };}}- const fork = await forkAgentEventCheckpoint(+ const fork = await checkpoints.fork(state.checkpoint,request.checkpointNs,request.invocationId,@@ -549,7 +548,7 @@ export async function executeAgentEventActor<T>(pendingSuspension = input.readSuspension?.();if (pendingSuspension != null) {actionAppliedBeforePause = input.readAppliedAction() != null;- const checkpoint = await captureAgentEventCheckpoint(+ const checkpoint = await checkpoints.capture(input.conversationId,invocation.fork.checkpointNs,invocation.invocationId,@@ -587,9 +586,9 @@ export async function executeAgentEventActor<T>(checkpoint: invocation.fork,};}- let checkpoint: Awaited<ReturnType<typeof captureAgentEventCheckpoint>>;+ let checkpoint: Awaited<ReturnType<typeof checkpoints.capture>>;try {- checkpoint = await captureAgentEventCheckpoint(+ checkpoint = await checkpoints.capture(input.conversationId,invocation.fork.checkpointNs,invocation.invocationId,@@ -667,6 +666,9 @@ export async function executeAgentEventActor<T>(? undefined: {generation: request.expectedHead.generation,+ ...(observedState.previousCheckpoint == null+ ? {}+ : { previousCheckpoint: observedState.previousCheckpoint }),checkpoint: {threadId: expectedHeadCheckpoint!.threadId,checkpointId: expectedCheckpointId!,@@ -733,15 +735,8 @@ export async function executeAgentEventActor<T>(};}if (committed.prunableCheckpoint != null) {- await deleteAgentCheckpoint(- committed.prunableCheckpoint.threadId,- input.checkpointer,- undefined,- {- throwOnError: true,- checkpointNamespace: committed.prunableCheckpoint.checkpointNs,- },- );+ await checkpoints.remove(committed.prunableCheckpoint, input.checkpointer);+ await checkpoints.acknowledgePruning(committed.prunableCheckpoint);}return { status: 'committed', head: toHead(input.conversationId, committed.state) };},@@ -773,10 +768,7 @@ export async function executeAgentEventActor<T>(}ownedActionAdmissionId = undefined;}- await deleteAgentCheckpoint(request.invocation.fork.threadId, input.checkpointer, undefined, {- throwOnError: true,- checkpointNamespace: request.invocation.fork.checkpointNs,- });+ await checkpoints.removeOwned(request.invocation.fork, input.checkpointer);const released = await deps.resolveReconciliation({user: input.user,conversationId: input.conversationId,@@ -914,6 +906,8 @@ export async function resumeAgentEventActor<T>(input: ResumeAgentEventActorInput<T>,deps: AgentEventActorDependencies,): Promise<ExecuteAgentEventActorResult<T>> {+ const checkpoints = createOwnedActorCheckpoints(input.user, input.tenantId);+ let checkpointStorageNamespace: string | null = null;let value: T | undefined;let invocationError: unknown;let observedState: IAgentEventActorState | null | undefined;@@ -950,7 +944,10 @@ export async function resumeAgentEventActor<T>(if (deps.claimSuspension == null) {throw new Error('Event actor suspension claim storage is unavailable');}- const snapshot = await deps.getSnapshot(owner);+ const [snapshot] = await Promise.all([+ deps.getSnapshot(owner),+ checkpoints.drain(input.conversationId, input.checkpointer),+ ]);const hostSuspension = snapshot?.suspension;if (snapshot == null ||@@ -990,8 +987,14 @@ export async function resumeAgentEventActor<T>(throw new Error('Event actor suspension claim could not be projected to its job');}try {+ checkpointStorageNamespace =+ (await checkpoints.resolveNamespace(request.suspension.checkpoint, input.checkpointer)) ??+ null;+ if (checkpointStorageNamespace == null) {+ throw new Error('Signed event actor checkpoint is no longer available');+ }value = await input.resume({- checkpointNamespace: request.suspension.checkpoint.checkpointNs,+ checkpointNamespace: checkpointStorageNamespace,...(request.suspension.checkpoint.checkpointId == null? {}: { checkpointId: request.suspension.checkpoint.checkpointId }),@@ -1017,11 +1020,13 @@ export async function resumeAgentEventActor<T>(hostSuspension.handlingGenerationCreatedAt ?? hostSuspension.jobCreatedAt,};actionAppliedBeforePause = observedAction != null;- const checkpoint = await captureAgentEventCheckpoint(+ const checkpoint = await checkpoints.capture(input.conversationId,request.suspension.checkpoint.checkpointNs,request.suspension.invocation.invocationId,input.checkpointer,+ checkpointStorageNamespace,+ request.suspension.checkpoint.checkpointId,);if (checkpoint?.checkpointId == null) {throw new Error('Re-paused event actor has no observable interrupt checkpoint');@@ -1062,13 +1067,15 @@ export async function resumeAgentEventActor<T>(},};}- let checkpoint: Awaited<ReturnType<typeof captureAgentEventCheckpoint>>;+ let checkpoint: Awaited<ReturnType<typeof checkpoints.capture>>;try {- checkpoint = await captureAgentEventCheckpoint(+ checkpoint = await checkpoints.capture(input.conversationId,request.suspension.checkpoint.checkpointNs,request.suspension.invocation.invocationId,input.checkpointer,+ checkpointStorageNamespace,+ request.suspension.checkpoint.checkpointId,);} catch (error) {return {@@ -1138,15 +1145,7 @@ export async function resumeAgentEventActor<T>(if (settled.status !== 'settled') {return settled;}- await deleteAgentCheckpoint(- input.suspension.checkpoint.threadId,- input.checkpointer,- undefined,- {- throwOnError: true,- checkpointNamespace: input.suspension.checkpoint.checkpointNs,- },- );+ await checkpoints.remove(input.suspension.checkpoint, input.checkpointer);return settled;},async commit(request) {@@ -1165,6 +1164,9 @@ export async function resumeAgentEventActor<T>(? undefined: {generation: observedState.generation,+ ...(observedState.previousCheckpoint == null+ ? {}+ : { previousCheckpoint: observedState.previousCheckpoint }),checkpoint: observedState.checkpoint,...(observedState.contextFingerprint == null? {}@@ -1220,15 +1222,8 @@ export async function resumeAgentEventActor<T>(};}if (committed.prunableCheckpoint != null) {- await deleteAgentCheckpoint(- committed.prunableCheckpoint.threadId,- input.checkpointer,- undefined,- {- throwOnError: true,- checkpointNamespace: committed.prunableCheckpoint.checkpointNs,- },- );+ await checkpoints.remove(committed.prunableCheckpoint, input.checkpointer);+ await checkpoints.acknowledgePruning(committed.prunableCheckpoint);}return { status: 'committed', head: toHead(input.conversationId, committed.state) };},@@ -1319,6 +1314,7 @@ export async function cancelAgentEventActor(input: CancelAgentEventActorInput,deps: Pick<AgentEventActorDependencies, 'cancelSuspension'>,): Promise<EventActorCancelSuspensionResult> {+ const checkpoints = createOwnedActorCheckpoints(input.user, input.tenantId);if (deps.cancelSuspension == null) {throw new Error('Event actor suspension cancellation storage is unavailable');}@@ -1348,15 +1344,7 @@ export async function cancelAgentEventActor(if (cancelled.status !== 'cancelled') {return cancelled;}- await deleteAgentCheckpoint(- request.suspension.checkpoint.threadId,- input.checkpointer,- undefined,- {- throwOnError: true,- checkpointNamespace: request.suspension.checkpoint.checkpointNs,- },- );+ await checkpoints.remove(request.suspension.checkpoint, input.checkpointer);return cancelled;},async commit() {diff --git a/packages/api/src/agents/triggers/service.delivery.spec.ts b/packages/api/src/agents/triggers/service.delivery.spec.tsindex c8e4bef770..bd3977598b 100644--- a/packages/api/src/agents/triggers/service.delivery.spec.ts+++ b/packages/api/src/agents/triggers/service.delivery.spec.ts@@ -386,6 +386,34 @@ describe('durable agent trigger service', () => {await service.stop();});+ it('runs checkpoint evidence maintenance in system context and waits on shutdown', async () => {+ let finish!: () => void;+ const pending = new Promise<number>((resolve) => {+ finish = () => resolve(1);+ });+ const reclaimCheckpointDeletions = jest.fn(() => {+ expect(getTenantId()).toBe(SYSTEM_TENANT_ID);+ return pending;+ });+ const service = createAgentTriggerService({+ methods: deliveryMethods(),+ reclaimCheckpointDeletions,+ purgeRecoveryLimit: 17,+ deliveryOptions: { concurrency: 1, tickMs: 60_000 },+ });+ await service.initialize({ address: { address: '127.0.0.1', family: 'IPv4', port: 3080 } });+ expect(reclaimCheckpointDeletions).toHaveBeenCalledWith(17);+ let stopped = false;+ const stop = service.stop().then(() => {+ stopped = true;+ });+ await new Promise((resolve) => setImmediate(resolve));+ expect(stopped).toBe(false);+ finish();+ await stop;+ expect(stopped).toBe(true);+ });+it('reclaims lanes even when another maintenance step rejects', async () => {/** A single broken cleanup (e.g. an engine-specific query rejection) used* to fail the whole Promise.all and skip the sequenced lane reclamation ondiff --git a/packages/api/src/agents/triggers/service.ts b/packages/api/src/agents/triggers/service.tsindex 57ec7270e7..029312caee 100644--- a/packages/api/src/agents/triggers/service.ts+++ b/packages/api/src/agents/triggers/service.ts@@ -55,6 +55,7 @@ export interface AgentTriggerServiceDeps {userDrainPollMs?: number;purgeRecoveryIntervalMs?: number;purgeRecoveryLimit?: number;+ reclaimCheckpointDeletions?: (limit: number) => Promise<number>;supportsDetachedActionCompletion?: () => boolean;settleSourceBeforeDeadLetter?: AgentTriggerDeliveryEngineDeps['settleSourceBeforeDeadLetter'];}@@ -365,29 +366,38 @@ export function createAgentTriggerService(deps: AgentTriggerServiceDeps = {}): Areturn 0;});const current = runAsSystem(async () => {- const [purgedUsers, publishedLanes, batchRecovery, expiredLegacyActorReceipts] =- await Promise.all([- isolated('user purges', () => methods.recoverAgentTriggerUserPurges(purgeRecoveryLimit)),- isolated('lane publications', () =>- methods.recoverAgentTriggerLanePublications(purgeRecoveryLimit),- ),- methods.recoverAgentTriggerBatchReceipts(purgeRecoveryLimit).then(- (count) => ({ succeeded: true as const, count }),- (error) => {- logger.error(- '[agent-triggers] durable delivery maintenance step failed (batch receipts):',- error,- );- return { succeeded: false as const, count: 0 };- },- ),- isolated(- 'legacy actor receipts',- () =>- methods.expireLegacyAgentEventActorReceipts?.(new Date(), purgeRecoveryLimit) ??- Promise.resolve(0),- ),- ]);+ const [+ purgedUsers,+ publishedLanes,+ batchRecovery,+ expiredLegacyActorReceipts,+ retiredCheckpointDeletions,+ ] = await Promise.all([+ isolated('user purges', () => methods.recoverAgentTriggerUserPurges(purgeRecoveryLimit)),+ isolated('lane publications', () =>+ methods.recoverAgentTriggerLanePublications(purgeRecoveryLimit),+ ),+ methods.recoverAgentTriggerBatchReceipts(purgeRecoveryLimit).then(+ (count) => ({ succeeded: true as const, count }),+ (error) => {+ logger.error(+ '[agent-triggers] durable delivery maintenance step failed (batch receipts):',+ error,+ );+ return { succeeded: false as const, count: 0 };+ },+ ),+ isolated(+ 'legacy actor receipts',+ () =>+ methods.expireLegacyAgentEventActorReceipts?.(new Date(), purgeRecoveryLimit) ??+ Promise.resolve(0),+ ),+ isolated(+ 'checkpoint deletion evidence',+ () => deps.reclaimCheckpointDeletions?.(purgeRecoveryLimit) ?? Promise.resolve(0),+ ),+ ]);const recoveredBatches = batchRecovery.count;const reclaimedLanes = batchRecovery.succeeded? await isolated('lane reclamation', () =>@@ -402,7 +412,8 @@ export function createAgentTriggerService(deps: AgentTriggerServiceDeps = {}): ApublishedLanes > 0 ||recoveredBatches > 0 ||reclaimedLanes > 0 ||- expiredLegacyActorReceipts > 0+ expiredLegacyActorReceipts > 0 ||+ retiredCheckpointDeletions > 0) {logger.info('[agent-triggers] recovered durable delivery maintenance', {purgedUsers,@@ -410,6 +421,7 @@ export function createAgentTriggerService(deps: AgentTriggerServiceDeps = {}): ArecoveredBatches,reclaimedLanes,expiredLegacyActorReceipts,+ retiredCheckpointDeletions,});}})diff --git a/packages/api/src/schedules/engine.ts b/packages/api/src/schedules/engine.tsindex c12d1486de..af2325d307 100644--- a/packages/api/src/schedules/engine.ts+++ b/packages/api/src/schedules/engine.ts@@ -97,6 +97,9 @@ export function startScheduleEngine(deps: ScheduleEngineDeps): ScheduleEngine {scheduleId: run.scheduleId,scheduledFor: run.scheduledFor,status,+ ...(status === 'requires_action' && jobState?.checkpointNamespace != null+ ? { checkpointNamespace: jobState.checkpointNamespace }+ : {}),// Pre-start aborts have a reserved id but no conversation was ever// created; projecting it gives the card a link to a missing chat.conversationId: opts?.omitConversationId ? undefined : run.conversationId,diff --git a/packages/api/src/schedules/service.spec.ts b/packages/api/src/schedules/service.spec.tsindex 52e24dc5f6..ae35656ab7 100644--- a/packages/api/src/schedules/service.spec.ts+++ b/packages/api/src/schedules/service.spec.ts@@ -7,6 +7,7 @@ import { createSchedulesService } from './service';let mockJobStore: { getJob: jest.Mock; deleteJob?: jest.Mock } | null = null;jest.mock('../agents/checkpointer', () => ({+ checkpointStorageConfigs: jest.fn(async (_user, _tenant, cfg) => [cfg]),deleteAgentCheckpoint: jest.fn(async () => undefined),// Non-empty by default so the scoped prune has something to delete in tests.captureAgentCheckpointGeneration: jest.fn(async (threadId: string) => ({@@ -15,6 +16,7 @@ jest.mock('../agents/checkpointer', () => ({})),}));const checkpointerModule = jest.requireMock('../agents/checkpointer') as {+ checkpointStorageConfigs: jest.Mock;deleteAgentCheckpoint: jest.Mock;captureAgentCheckpointGeneration: jest.Mock;};@@ -34,6 +36,7 @@ type ActiveRun = {scheduleId: string;scheduledFor: Date;conversationId?: string;+ checkpointNamespace?: string;status?: string;};@@ -374,6 +377,87 @@ describe('deleteScheduleForOwner', () => {return { service, methods };}+ it.each([undefined, 'lcg:v2:owner:generation'])(+ 'passes the matching paused job namespace (%s) through the raw projection to capture',+ async (checkpointNamespace) => {+ const scheduledFor = '2026-01-01T00:00:00.000Z';+ const { service } = makeDeleteHarness({+ scheduleId: 's1',+ scheduledFor: new Date(scheduledFor),+ conversationId: 'c1',+ status: 'requires_action',+ });+ mockJobStore = {+ getJob: jest.fn(async () => ({+ status: 'requires_action',+ createdAt: 1,+ scheduleId: 's1',+ scheduledFor,+ checkpointNamespace,+ })),+ } as unknown as typeof mockJobStore;+ const manager = jest.requireMock('../stream/GenerationJobManager').GenerationJobManager;+ manager.abortJob = jest.fn(async () => ({ success: true }));+ checkpointerModule.captureAgentCheckpointGeneration.mockClear();+ await expect(service.deleteScheduleForOwner('s1', 'user-1')).resolves.toBe('deleted');+ expect(checkpointerModule.captureAgentCheckpointGeneration).toHaveBeenCalledWith(+ 'c1',+ undefined,+ checkpointNamespace == null ? {} : { checkpointNamespace },+ );+ },+ );++ it('uses the durable paused namespace after job-store loss', async () => {+ const namespace = 'retained-owned-namespace';+ const { service } = makeDeleteHarness({+ scheduleId: 's1',+ scheduledFor: new Date('2026-01-01T00:00:00.000Z'),+ conversationId: 'c1',+ checkpointNamespace: namespace,+ status: 'requires_action',+ });+ mockJobStore = { getJob: jest.fn(async () => null) } as unknown as typeof mockJobStore;+ checkpointerModule.captureAgentCheckpointGeneration.mockClear();+ await expect(service.deleteScheduleForOwner('s1', 'user-1')).resolves.toBe('deleted');+ expect(checkpointerModule.captureAgentCheckpointGeneration).toHaveBeenCalledWith(+ 'c1',+ undefined,+ { checkpointNamespace: namespace },+ );+ });++ it('captures the retained namespace in every recorded store after job loss and a config change', async () => {+ const namespace = 'retained-owned-namespace';+ const stores = [+ { type: 'mongo', checkpointCollectionName: 'old-checkpoints' },+ { type: 'mongo', checkpointCollectionName: 'current-checkpoints' },+ ];+ checkpointerModule.checkpointStorageConfigs.mockResolvedValueOnce(stores);+ const { service } = makeDeleteHarness({+ scheduleId: 's1',+ scheduledFor: new Date('2026-01-01T00:00:00.000Z'),+ conversationId: 'c1',+ checkpointNamespace: namespace,+ status: 'requires_action',+ });+ mockJobStore = { getJob: jest.fn(async () => null) } as unknown as typeof mockJobStore;+ checkpointerModule.captureAgentCheckpointGeneration.mockClear();+ await expect(service.deleteScheduleForOwner('s1', 'user-1')).resolves.toBe('deleted');+ for (const storage of stores) {+ expect(checkpointerModule.captureAgentCheckpointGeneration).toHaveBeenCalledWith(+ 'c1',+ storage,+ { checkpointNamespace: namespace },+ );+ expect(checkpointerModule.deleteAgentCheckpoint).toHaveBeenCalledWith(+ 'c1',+ storage,+ expect.objectContaining({ checkpointIds: ['ck-1'] }),+ );+ }+ });+it('settles a pause hand-off after the exact provider drain is confirmed', async () => {const { service, methods } = makeDeleteHarness({scheduleId: 's1',diff --git a/packages/api/src/schedules/service.ts b/packages/api/src/schedules/service.tsindex 5d358662ad..b09dc3e0c0 100644--- a/packages/api/src/schedules/service.ts+++ b/packages/api/src/schedules/service.ts@@ -13,6 +13,7 @@ import type {JobIdentity,} from './types';import type { SerializableJobData } from '../stream/interfaces/IJobStore';+import type { AgentCheckpointGeneration } from '../agents/checkpointer';import type { BalanceUpdateFields } from '../types/balance';import type { GetAppConfigOptions } from '../app/service';import {@@ -22,7 +23,11 @@ import {hasResumeHandoffInFlight,hasAbortInFlight,} from './types';-import { deleteAgentCheckpoint, captureAgentCheckpointGeneration } from '../agents/checkpointer';+import {+ deleteAgentCheckpoint,+ captureAgentCheckpointGeneration,+ checkpointStorageConfigs,+} from '../agents/checkpointer';import { fireSchedule, BALANCE_SKIP_DISABLE_THRESHOLD } from './fire';import { GenerationJobManager } from '../stream/GenerationJobManager';import { isStopConfirmed } from '../stream/interfaces/IJobStore';@@ -92,6 +97,7 @@ export interface RecordScheduleOutcomeInput {jobCreatedAt?: number;status: ScheduleRunOutcomeStatus;conversationId?: string;+ checkpointNamespace?: string;/** Erase the row's reserved conversationId (pre-start abort: no conversation exists). */clearConversationId?: boolean;error?: string;@@ -544,6 +550,7 @@ export function createSchedulesService(return {status: job.status,createdAt: job.createdAt,+ checkpointNamespace: job.checkpointNamespace,scheduleId: job.scheduleId,scheduledFor: job.scheduledFor,createdEventEmitted: job.createdEventEmitted === true,@@ -837,6 +844,7 @@ export function createSchedulesService(jobCreatedAt,status,conversationId,+ checkpointNamespace,clearConversationId,error,}: RecordScheduleOutcomeInput): Promise<boolean> {@@ -891,6 +899,9 @@ export function createSchedulesService(status,clearConversationId,conversationId,+ ...(status === 'requires_action' && checkpointNamespace != null+ ? { checkpointNamespace }+ : {}),error,autoDisableAfterFailures: limits.autoDisableAfterFailures,balanceSkipDisableThreshold: BALANCE_SKIP_DISABLE_THRESHOLD,@@ -1331,6 +1342,15 @@ export function createSchedulesService(return undefined;}): undefined;+ const stores = hasPausedRun+ ? await checkpointStorageConfigs(userId, schedule.tenantId, checkpointer).catch((err) => {+ logger.warn(+ `[schedules] checkpoint storage lookup failed for delete ${scheduleId}:`,+ err,+ );+ return [checkpointer];+ })+ : [];let unconfirmed = 0;for (const run of active) {// UNKNOWN is not ABSENT — the same distinction the quiesce path draws. A lookup@@ -1351,10 +1371,29 @@ export function createSchedulesService(// Capture the paused run's checkpoint ids BEFORE any terminal transition below:// the prune afterwards is scoped to exactly this set, so checkpoints a// replacement turn writes after this point can never be swept up by it.- const checkpointGeneration =- run.status === 'requires_action' && run.conversationId- ? await captureAgentCheckpointGeneration(run.conversationId, checkpointer)+ const checkpointNamespace =+ isThisGeneration || live.job == null+ ? (live.job?.checkpointNamespace ?? run.checkpointNamespace): undefined;+ const captured: Array<{+ storage: TCheckpointerConfig | undefined;+ generation: AgentCheckpointGeneration;+ }> = [];+ if (+ run.status === 'requires_action' &&+ run.conversationId &&+ live.known &&+ (live.job == null || isThisGeneration)+ ) {+ for (const storage of stores) {+ const generation = await captureAgentCheckpointGeneration(+ run.conversationId,+ storage,+ checkpointNamespace == null ? {} : { checkpointNamespace },+ );+ if (generation != null) captured.push({ storage, generation });+ }+ }// Same abort-in-flight deferral as quiesce: post-abort job state (status `aborted`,// or absence once the abort deleted the job) appears before the owner has persisted// and settled, so it is not evidence that the generation is done.@@ -1437,8 +1476,7 @@ export function createSchedulesService(if (run.status === 'requires_action' &&run.conversationId &&- checkpointGeneration != null &&- checkpointGeneration.checkpointIds.length > 0+ captured.some(({ generation }) => generation.checkpointIds.length > 0)) {const fresh = await engineDeps.getJobStatus(run.conversationId).then((job) => ({ known: true, job }),@@ -1452,9 +1490,11 @@ export function createSchedulesService(});const ownsConversation = fresh.known && (fresh.job == null || freshIsThisGeneration);if (ownsConversation) {- await deleteAgentCheckpoint(run.conversationId, checkpointer, checkpointGeneration).catch(- () => undefined,- );+ for (const { storage, generation } of captured) {+ await deleteAgentCheckpoint(run.conversationId, storage, generation).catch(+ () => undefined,+ );+ }}}}diff --git a/packages/api/src/schedules/types.ts b/packages/api/src/schedules/types.tsindex 81e4a636ff..e7182a80c0 100644--- a/packages/api/src/schedules/types.ts+++ b/packages/api/src/schedules/types.ts@@ -275,6 +275,7 @@ export interface JobIdentity {/** Job-store state plus the job's scheduled identity (absent on a replacement turn). */export interface JobState {status: string;+ checkpointNamespace?: string;createdAt?: number;scheduleId?: string;scheduledFor?: string;diff --git a/packages/api/src/stream/GenerationJobManager.ts b/packages/api/src/stream/GenerationJobManager.tsindex 4322bb31b2..2b3eb57bd6 100644--- a/packages/api/src/stream/GenerationJobManager.ts+++ b/packages/api/src/stream/GenerationJobManager.ts@@ -2938,6 +2938,7 @@ class GenerationJobManagerClass {idempotencyClientRequestId: jobData.idempotencyClientRequestId,agentEventLegacyTurnToken: jobData.agentEventLegacyTurnToken,terminalPersistencePending: jobData.terminalPersistencePending,+ terminalHostActionPending: jobData.terminalHostActionPending,terminalPersistenceStartedAt: jobData.terminalPersistenceStartedAt,// Surface the pending review so status/resume routes built on the// facade can render the prompt for a `requires_action` job.@@ -3091,9 +3092,30 @@ class GenerationJobManagerClass {return runtime;}- /**- * Get a job by streamId.- */+ /** Durable deletion evidence does not depend on a replica's runtime attachment. */+ async getCleanupJob(+ streamId: string,+ ): Promise<Pick<t.GenerationJob, 'createdAt' | 'status' | 'metadata'> | undefined> {+ let job = await this.jobStore.getJob(streamId);+ if (job?.terminalPersistencePending === true) {+ await this.recoverStaleTerminalPersistence(job);+ job = await this.jobStore.getJob(streamId);+ }+ if (job == null) return undefined;+ return {+ createdAt: job.createdAt,+ status: job.status,+ metadata: {+ userId: job.userId,+ tenantId: job.tenantId,+ conversationId: job.conversationId,+ providerDrained: job.providerDrained,+ terminalPersistencePending: job.terminalPersistencePending,+ terminalHostActionPending: job.terminalHostActionPending,+ },+ };+ }+async getJob(streamId: string): Promise<t.GenerationJob | undefined> {let jobData = await this.jobStore.getJob(streamId);if (!jobData) {@@ -9286,7 +9308,40 @@ class GenerationJobManagerClass {/** Returns every generation whose provider can still mutate user-owned data,* including a terminal generation whose controller is finishing trailing writes. */async getCleanupBlockingJobIdsForUser(userId: string, tenantId?: string): Promise<string[]> {- return this.jobStore.getCleanupBlockingJobIdsByUser(userId, tenantId);+ const ownerQuery = this.jobStore.getCleanupJobIdsByUser;+ const readOwner = (tenant?: string) =>+ ownerQuery != null+ ? ownerQuery.call(this.jobStore, userId, tenant)+ : this.jobStore.getCleanupBlockingJobIdsByUser(userId, tenant);+ const [current, legacy, hostActions, detachedActions] = await Promise.all([+ readOwner(tenantId),+ tenantId == null ? [] : readOwner(),+ ownerQuery == null ? (this.jobStore.getTerminalHostActionJobs?.() ?? []) : [],+ ownerQuery == null+ ? (this.jobStore.getDetachedAgentEventTerminalHostActionJobs?.() ?? [])+ : [],+ ]);+ const pending = [...hostActions, ...detachedActions].filter(+ (job) =>+ job.userId === userId &&+ (!job.tenantId || job.tenantId === tenantId) &&+ job.terminalHostActionPending === true,+ );+ const streamIds = [...new Set([...current, ...legacy, ...pending.map((job) => job.streamId)])];+ const jobs = await Promise.all(streamIds.map((streamId) => this.jobStore.getJob(streamId)));+ return streamIds.filter((_, index) => {+ const job = jobs[index];+ return job?.userId === userId && (!job.tenantId || job.tenantId === tenantId);+ });+ }++ /** Also includes retained paused jobs whose checkpoints belong to this account. */+ async getAccountCleanupJobIdsForUser(userId: string, tenantId?: string): Promise<string[]> {+ const [retained, blocking] = await Promise.all([+ this.jobStore.getRetainedJobIdsByUser?.(userId, tenantId) ?? [],+ this.getCleanupBlockingJobIdsForUser(userId, tenantId),+ ]);+ return [...new Set([...retained, ...blocking])];}/** Resolves every cleanup-blocking run attached to any target conversation.@@ -9301,7 +9356,7 @@ class GenerationJobManagerClass {return [];}const targets = new Set(conversationIds);- const streamIds = await this.jobStore.getCleanupBlockingJobIdsByUser(userId, tenantId);+ const streamIds = await this.getCleanupBlockingJobIdsForUser(userId, tenantId);const jobs = await Promise.all(streamIds.map((streamId) => this.jobStore.getJob(streamId)));return streamIds.filter((_, index) => {const job = jobs[index];diff --git a/packages/api/src/stream/__tests__/RedisJobStore.spec.ts b/packages/api/src/stream/__tests__/RedisJobStore.spec.tsindex 6b3eab814f..316e9bf222 100644--- a/packages/api/src/stream/__tests__/RedisJobStore.spec.ts+++ b/packages/api/src/stream/__tests__/RedisJobStore.spec.ts@@ -40,9 +40,6 @@ function jobHashFromCreationCall(call: unknown[]): Record<string, string> {String(fields[index * 2 + 1]),]),);- if (hash.generationProtocolVersion === '2') {- hash.checkpointNamespace = hash.createdAt;- }return hash;}@@ -203,7 +200,7 @@ describe('RedisJobStore', () => {// ARGV[5] is the terminal job TTL. The persistence owner/recovery path// gets five minutes even when ordinary completed records are immediate.- expect(evalTransition.mock.calls[0][16]).toBe('300');+ expect(evalTransition.mock.calls.find((call) => call[1] === 10)?.[16]).toBe('300');});test('retains the generation epoch beyond the paused job TTL', async () => {@@ -220,7 +217,7 @@ describe('RedisJobStore', () => {expectCreatedAt: 123456,});- const transitionCall = evalTransition.mock.calls[0];+ const transitionCall = evalTransition.mock.calls.find((call) => call[1] === 10)!;expect(transitionCall[0]).toContain('redis.call("SET", KEYS[8], currentCreatedAt, "EX", ttl + generationEpochGraceTtl)',);@@ -397,7 +394,8 @@ describe('RedisJobStore', () => {expect(job.preemptCapable).toBe(true);expect(job.steerQuotesExecutionId).toBe('exec-1');expect(job.generationProtocolVersion).toBe(2);- expect(job.checkpointNamespace).toBe(String(job.createdAt));+ expect(job.checkpointNamespace).toEqual(expect.any(String));+ expect(job.checkpointNamespace).not.toBe(String(job.createdAt));expect(job.resolvedAskUserQuestions).toEqual([{request: { question: 'Deploy where?' },@@ -611,7 +609,7 @@ describe('RedisJobStore', () => {expect(script).toContain('if previousCreatedAt and previousCreatedAt >= createdAt then createdAt = previousCreatedAt + 1 end',);- expect(script).toContain('"checkpointNamespace", tostring(createdAt)');+ expect(script).not.toContain('"checkpointNamespace", tostring(createdAt)');expect(script).toContain('redis.call("DEL", KEYS[1], KEYS[2], KEYS[3], KEYS[4], KEYS[5])');expect(script).toContain('redis.call("SET", KEYS[7], tostring(createdAt), "EX", ttl + generationEpochGraceTtl)',@@ -750,21 +748,20 @@ describe('RedisJobStore', () => {]);});- test('parallelizes Redis Cluster membership bookkeeping with ordered user TTL', async () => {+ test('parallelizes Redis Cluster membership bookkeeping with atomic owner registration', async () => {const evalResult = createDeferred<number>();const runningMembership = createDeferred<number>();const requiresActionRemoval = createDeferred<number>();const terminalHostActionRemoval = createDeferred<number>();const detachedTerminalHostActionRemoval = createDeferred<number>();- const userMembership = createDeferred<number>();- const userExpiry = createDeferred<number>();+ const ownerRegistration = createDeferred<number>();const started: string[] = [];- const expire = jest.fn(() => {- started.push('user_expiry');- return userExpiry.promise;- });- const evalJobCreation = jest.fn(() => {+ const evalJobCreation = jest.fn((_script: string, keyCount: number) => {+ if (keyCount === 1) {+ started.push('owner');+ return ownerRegistration.promise;+ }started.push('job');return evalResult.promise;});@@ -776,8 +773,7 @@ describe('RedisJobStore', () => {started.push('running');return runningMembership.promise;}- started.push('user');- return userMembership.promise;+ throw new Error(`Unexpected SADD key: ${key}`);}),srem: jest.fn((key: string) => {if (key === 'stream:requires_action') {@@ -792,7 +788,6 @@ describe('RedisJobStore', () => {return terminalHostActionRemoval.promise;}),hgetall: jest.fn(() => jobHashFromCreationCall(evalJobCreation.mock.calls[0])),- expire,} as unknown as Cluster;const store = new RedisJobStore(redis, { userJobsSetTtl: 60 });@@ -812,27 +807,11 @@ describe('RedisJobStore', () => {'requires_action','terminal_host_action','detached_terminal_host_action',- 'user',+ 'owner',]);expect(settled).toBe(false);- expect(expire).not.toHaveBeenCalled();-- userMembership.resolve(1);- await waitFor(() => expire.mock.calls.length === 1);- expect(started).toEqual([- 'job',- 'running',- 'requires_action',- 'terminal_host_action',- 'detached_terminal_host_action',- 'user',- 'user_expiry',- ]);- expect(expire).toHaveBeenCalledWith('stream:user:{user-1}:jobs', 60);- expect(settled).toBe(false);-- userExpiry.resolve(1);+ ownerRegistration.resolve(1);await Promise.resolve();expect(settled).toBe(false);@@ -897,8 +876,13 @@ describe('RedisJobStore', () => {});const redis = {isCluster: true,- eval: jest.fn(async () => {- durableHash = { ...durableHash, status: 'requires_action' };+ eval: jest.fn(async (_script: string, keyCount: number, ...args: string[]) => {+ if (keyCount === 10) {+ durableHash = { ...durableHash, status: 'requires_action' };+ } else {+ const [ownerKey, streamId] = args;+ await sadd(ownerKey, streamId);+ }return 1;}),hgetall,@@ -1080,7 +1064,7 @@ describe('RedisJobStore', () => {expect(sadd.mock.invocationCallOrder[0]).toBeLessThan(evalTransition.mock.invocationCallOrder[0],);- const transitionCall = evalTransition.mock.calls[0];+ const transitionCall = evalTransition.mock.calls.find((call) => call[1] === 10)!;expect(transitionCall[16]).toBe('86400');expect(transitionCall[18]).toBe('86400');expect(transitionCall[19]).toBe('86400');@@ -1140,7 +1124,7 @@ describe('RedisJobStore', () => {'stream:terminal_host_action','["stream-detached-host-action",100]',]);- const transitionCall = evalTransition.mock.calls[0];+ const transitionCall = evalTransition.mock.calls.find((call) => call[1] === 10)!;expect(transitionCall).toContain('status');expect(transitionCall).toContain('detached_terminal_pending_v1');expect(transitionCall).toContain('detachedAgentEventTerminalStatus');@@ -1157,6 +1141,7 @@ describe('RedisJobStore', () => {const srem = jest.fn().mockResolvedValue(1);const redis = {isCluster: true,+ eval: jest.fn().mockResolvedValue(1),smembers: jest.fn().mockResolvedValue([member]),srem,sadd: jest.fn().mockResolvedValue(1),@@ -1205,6 +1190,7 @@ describe('RedisJobStore', () => {isCluster: true,eval: evalClear,srem,+ hgetall: jest.fn().mockResolvedValue({}),} as unknown as Cluster;const store = new RedisJobStore(redis, {completedTtl: 300,diff --git a/packages/api/src/stream/__tests__/RedisJobStore.stream_integration.spec.ts b/packages/api/src/stream/__tests__/RedisJobStore.stream_integration.spec.tsindex 4b5889fe97..df15322b64 100644--- a/packages/api/src/stream/__tests__/RedisJobStore.stream_integration.spec.ts+++ b/packages/api/src/stream/__tests__/RedisJobStore.stream_integration.spec.ts@@ -93,6 +93,66 @@ describe('RedisJobStore Integration Tests', () => {process.env = originalEnv;});+ test.each([false, true])(+ 'owner cleanup recovers legacy terminal membership once (detached=%s)',+ async (detached) => {+ expect(ioredisClient).not.toBeNull();+ const redis = ioredisClient!;+ const { RedisJobStore } = await import('../implementations/RedisJobStore');+ const old = new RedisJobStore(redis, { userJobsSetTtl: 1, requiresActionTtl: 120 });+ const id = 'owner-terminal-recovery';+ const job = await old.createJob(id, 'owner', id, 'tenant');+ if (detached)+ await old.updateJob(id, { agentEventInvocationKey: 'invocation' }, job.createdAt);+ await old.transitionStatus(id, {+ from: 'running',+ to: 'complete',+ expectCreatedAt: job.createdAt,+ patch: { completedAt: Date.now(), providerDrained: true, terminalHostActionPending: true },+ });+ const key = 'stream:user:{tenant:owner}:jobs';+ await redis.del(key);+ await old.destroy();+ const store = new RedisJobStore(redis, { userJobsSetTtl: 1, requiresActionTtl: 120 });+ try {+ const global = jest.spyOn(store, 'getTerminalHostActionJobs');+ const detachedGlobal = jest.spyOn(store, 'getDetachedAgentEventTerminalHostActionJobs');+ await store.initialize();+ expect(await store.getCleanupJobIdsByUser('owner', 'tenant')).toEqual([id]);+ expect(await redis.ttl(key)).toBeGreaterThan(60);+ expect(await store.getActiveJobIdsByUser('owner', 'tenant')).toEqual([]);+ expect(await store.getCleanupJobIdsByUser('owner', 'tenant')).toEqual([id]);+ expect(await store.getCleanupJobIdsByUser('foreign', 'tenant')).toEqual([]);+ expect(global).toHaveBeenCalledTimes(1);+ expect(detachedGlobal).toHaveBeenCalledTimes(1);+ await redis.persist(key);+ await store.getCleanupJobIdsByUser('owner', 'tenant');+ expect(await redis.ttl(key)).toBe(-1);+ await store.clearTerminalHostAction(id, job.createdAt);+ expect(await store.getCleanupJobIdsByUser('owner', 'tenant')).toEqual([]);+ expect(await redis.smembers(key)).toEqual([]);+ } finally {+ await store.destroy();+ }+ },+ );++ test('owner cleanup fails closed when startup recovery fails and retries it', async () => {+ expect(ioredisClient).not.toBeNull();+ const { RedisJobStore } = await import('../implementations/RedisJobStore');+ const store = new RedisJobStore(ioredisClient!);+ const read = jest+ .spyOn(store, 'getTerminalHostActionJobs')+ .mockRejectedValueOnce(new Error('index unavailable'));+ try {+ await expect(store.getCleanupJobIdsByUser('owner')).rejects.toThrow('index unavailable');+ await expect(store.getCleanupJobIdsByUser('owner')).resolves.toEqual([]);+ expect(read).toHaveBeenCalledTimes(2);+ } finally {+ await store.destroy();+ }+ });+describe('Job CRUD Operations', () => {test('should create and retrieve a job', async () => {if (!ioredisClient) {@@ -177,8 +237,8 @@ describe('RedisJobStore Integration Tests', () => {const replacement = await store.createJob(streamId, 'user-1', streamId);- expect(predecessor.checkpointNamespace).toBe(String(predecessor.createdAt));- expect(replacement.checkpointNamespace).toBe(String(replacement.createdAt));+ expect(predecessor.checkpointNamespace).toEqual(expect.any(String));+ expect(replacement.checkpointNamespace).toEqual(expect.any(String));expect(replacement.checkpointNamespace).not.toBe(predecessor.checkpointNamespace);expect(replacement.replacedJob).toEqual({createdAt: predecessor.createdAt,@@ -1622,6 +1682,84 @@ describe('RedisJobStore Integration Tests', () => {await store.destroy();});+ test('enumerates stale paused jobs from exact and legacy owner indexes', async () => {+ if (!ioredisClient) {+ return;+ }++ const { RedisJobStore } = await import('../implementations/RedisJobStore');+ const store = new RedisJobStore(ioredisClient);+ await store.initialize();++ const suffix = `${process.pid}-${Date.now()}`;+ const userId = `account-cleanup-user-${suffix}`;+ const legacyStreamId = `account-cleanup-legacy-${suffix}`;+ const tenantStreamId = `account-cleanup-tenant-${suffix}`;+ const foreignStreamId = `account-cleanup-foreign-${suffix}`;+ const legacy = await store.createJob(legacyStreamId, userId, legacyStreamId);+ const tenant = await store.createJob(tenantStreamId, userId, tenantStreamId, 'tenant-a');+ await store.createJob(foreignStreamId, userId, foreignStreamId, 'tenant-b');+ await store.transitionStatus(legacyStreamId, {+ from: 'running',+ to: 'requires_action',+ expectCreatedAt: legacy.createdAt,+ });+ await store.transitionStatus(tenantStreamId, {+ from: 'running',+ to: 'requires_action',+ expectCreatedAt: tenant.createdAt,+ });++ expect(await store.getCleanupBlockingJobIdsByUser(userId, 'tenant-a')).toEqual([]);+ const retained = await store.getRetainedJobIdsByUser(userId, 'tenant-a');+ expect(retained).toEqual(expect.arrayContaining([legacyStreamId, tenantStreamId]));+ expect(retained).not.toContain(foreignStreamId);++ await store.destroy();+ });++ test('does not shorten a shared owner index for a longer paused job', async () => {+ if (!ioredisClient) {+ return;+ }++ const { RedisJobStore } = await import('../implementations/RedisJobStore');+ const store = new RedisJobStore(ioredisClient, {+ userJobsSetTtl: 60,+ requiresActionTtl: 120,+ });+ await store.initialize();++ const suffix = `${process.pid}-${Date.now()}`;+ const userId = `mixed-ttl-user-${suffix}`;+ const tenantId = 'tenant-a';+ const pausedStreamId = `mixed-ttl-paused-${suffix}`;+ const paused = await store.createJob(pausedStreamId, userId, pausedStreamId, tenantId);+ const pendingAction = {+ ...buildPendingAction(pausedStreamId),+ expiresAt: Date.now() + 2 * 86400 * 1000,+ };+ await store.transitionStatus(pausedStreamId, {+ from: 'running',+ to: 'requires_action',+ expectCreatedAt: paused.createdAt,+ patch: { pendingAction },+ });+ const ownerKey = `stream:user:{${tenantId}:${userId}}:jobs`;+ const longTtl = await ioredisClient.ttl(ownerKey);++ await store.createJob(+ `mixed-ttl-ordinary-${suffix}`,+ userId,+ 'ordinary-conversation',+ tenantId,+ );++ expect(longTtl).toBeGreaterThan(86400);+ expect(await ioredisClient.ttl(ownerKey)).toBeGreaterThan(86400);+ await store.destroy();+ });+test('should prune expired requires_action IDs during cleanup', async () => {if (!ioredisClient) {return;diff --git a/packages/api/src/stream/__tests__/createJobOwnership.spec.ts b/packages/api/src/stream/__tests__/createJobOwnership.spec.tsindex 3c50889c7a..d3a99e5ba2 100644--- a/packages/api/src/stream/__tests__/createJobOwnership.spec.ts+++ b/packages/api/src/stream/__tests__/createJobOwnership.spec.ts@@ -117,7 +117,7 @@ describe('InMemoryJobStore createJob ownership integrity', () => {expect(second.createdAt).toBeGreaterThan(first.createdAt);expect(second.checkpointNamespace).not.toBe(first.checkpointNamespace);- expect(second.checkpointNamespace).toBe(String(second.createdAt));+ expect(second.checkpointNamespace).not.toBe(String(second.createdAt));} finally {now.mockRestore();}diff --git a/packages/api/src/stream/__tests__/protocolRollout.spec.ts b/packages/api/src/stream/__tests__/protocolRollout.spec.tsindex 5d53322c73..35ae28d84a 100644--- a/packages/api/src/stream/__tests__/protocolRollout.spec.ts+++ b/packages/api/src/stream/__tests__/protocolRollout.spec.ts@@ -29,11 +29,38 @@ describe('generation protocol rollout storage', () => {});expect(v2.generationProtocolVersion).toBe(2);- expect(v2.checkpointNamespace).toBe(String(v2.createdAt));+ expect(v2.checkpointNamespace).toEqual(expect.any(String));+ expect(v2.checkpointNamespace).not.toBe(String(v2.createdAt));expect(v1.generationProtocolVersion).toBe(1);expect(v1.checkpointNamespace).toBeUndefined();});+ test('jobs receive distinct globally unique checkpoint scopes under a frozen clock', async () => {+ const now = jest.spyOn(Date, 'now').mockReturnValue(1_000);+ try {+ const store = new InMemoryJobStore();+ const first = await store.createJob('stream-a', 'owner-a', 'shared-conversation', undefined, {+ providerExecutionId: 'shared-execution',+ });+ const second = await store.createJob(+ 'stream-b',+ 'owner-b',+ 'shared-conversation',+ undefined,+ {+ providerExecutionId: 'shared-execution',+ },+ );++ expect(second.createdAt).toBeGreaterThan(first.createdAt);+ expect(first.checkpointNamespace).not.toBe(second.checkpointNamespace);+ expect(first.checkpointNamespace).toMatch(/^lcg:v2:[0-9a-f]{64}:[0-9a-f-]{36}$/);+ expect(second.checkpointNamespace).toMatch(/^lcg:v2:[0-9a-f]{64}:[0-9a-f-]{36}$/);+ } finally {+ now.mockRestore();+ }+ });+test('v1 steering stays receiptless and uses the legacy destructive drain', async () => {const store = new InMemoryJobStore();const job = await store.createJob('protocol-v1-steer', 'user-1', undefined, undefined, {diff --git a/packages/api/src/stream/__tests__/protocolRollout.stream_integration.spec.ts b/packages/api/src/stream/__tests__/protocolRollout.stream_integration.spec.tsindex b3c04e34c7..94319d4dc4 100644--- a/packages/api/src/stream/__tests__/protocolRollout.stream_integration.spec.ts+++ b/packages/api/src/stream/__tests__/protocolRollout.stream_integration.spec.ts@@ -35,10 +35,38 @@ describe('Redis generation protocol rollout bridge', () => {expect(legacy.generationProtocolVersion).toBe(1);expect(legacy.checkpointNamespace).toBeUndefined();expect(current.generationProtocolVersion).toBe(2);- expect(current.checkpointNamespace).toBe(String(current.createdAt));+ expect(current.checkpointNamespace).toEqual(expect.any(String));+ expect(current.checkpointNamespace).not.toBe(String(current.createdAt));expect((await store.getJob(current.streamId))?.generationProtocolVersion).toBe(2);});+ test('same-millisecond cross-owner jobs receive distinct checkpoint scopes', async () => {+ const now = jest.spyOn(Date, 'now').mockReturnValue(1_000);+ try {+ const first = await store.createJob(+ 'redis-same-ms-a',+ 'owner-a',+ 'shared-conversation',+ 'tenant-a',+ { providerExecutionId: 'shared-execution' },+ );+ const second = await store.createJob(+ 'redis-same-ms-b',+ 'owner-b',+ 'shared-conversation',+ 'tenant-b',+ { providerExecutionId: 'shared-execution' },+ );++ expect(first.createdAt).toBe(second.createdAt);+ expect(first.checkpointNamespace).not.toBe(second.checkpointNamespace);+ expect(first.checkpointNamespace).toMatch(/^lcg:v2:[0-9a-f]{64}:[0-9a-f-]{36}$/);+ expect(second.checkpointNamespace).toMatch(/^lcg:v2:[0-9a-f]{64}:[0-9a-f-]{36}$/);+ } finally {+ now.mockRestore();+ }+ });+test('v1 receipt API falls back to a receiptless legacy queue and drain', async () => {const job = await store.createJob('redis-protocol-v1-steer', 'user-1', undefined, undefined, {generationProtocolVersion: 1,diff --git a/packages/api/src/stream/__tests__/startup.spec.ts b/packages/api/src/stream/__tests__/startup.spec.tsindex 1a388dd853..407ca4d9d3 100644--- a/packages/api/src/stream/__tests__/startup.spec.ts+++ b/packages/api/src/stream/__tests__/startup.spec.ts@@ -131,7 +131,7 @@ describe('GenerationJobManager startup telemetry', () => {expect(job.metadata).toMatchObject({userId: 'user-1',conversationId: 'conversation-1',- checkpointNamespace: String(job.createdAt),+ checkpointNamespace: expect.stringMatching(/^lcg:v2:[0-9a-f]{64}:[0-9a-f-]{36}$/),userMessage: {messageId: 'message-1',parentMessageId: 'parent-1',diff --git a/packages/api/src/stream/__tests__/terminalHostAction.spec.ts b/packages/api/src/stream/__tests__/terminalHostAction.spec.tsindex 2d68b2a8e1..80e0e5f91a 100644--- a/packages/api/src/stream/__tests__/terminalHostAction.spec.ts+++ b/packages/api/src/stream/__tests__/terminalHostAction.spec.ts@@ -27,6 +27,97 @@ describe('GenerationJobManager terminal host actions', () => {await manager.destroy();});+ it.each(['ordinary', 'detached'])(+ 'all deletion callers discover %s terminal host actions outside owner membership',+ async (lane) => {+ const job = await manager.createJob('pending-host', 'user-1', 'conversation');+ await store.transitionStatus('pending-host', {+ from: 'running',+ to: 'complete',+ expectCreatedAt: job.createdAt,+ patch: { completedAt: Date.now(), providerDrained: true, terminalHostActionPending: true },+ });+ Object.assign(store, { getCleanupJobIdsByUser: undefined });+ const terminal = (await store.getJob('pending-host'))!;+ jest.spyOn(store, 'getRetainedJobIdsByUser').mockResolvedValue([]);+ const rows = [+ terminal,+ { ...terminal, streamId: 'foreign-user', userId: 'user-2' },+ { ...terminal, streamId: 'foreign-tenant', tenantId: 'tenant-b' },+ ];+ jest+ .spyOn(store, 'getTerminalHostActionJobs')+ .mockResolvedValue(lane === 'ordinary' ? rows : []);+ Object.assign(store, {+ getDetachedAgentEventTerminalHostActionJobs: jest+ .fn()+ .mockResolvedValue(lane === 'detached' ? rows : []),+ });+ expect(await manager.getAccountCleanupJobIdsForUser('user-1', 'tenant-a')).toEqual([+ 'pending-host',+ ]);+ expect(await manager.getCleanupBlockingJobIdsForUser('user-1', 'tenant-a')).toEqual([+ 'pending-host',+ ]);+ expect(+ await manager.getCleanupBlockingJobIdsForConversations(+ 'user-1',+ ['conversation'],+ 'tenant-a',+ ),+ ).toEqual(['pending-host']);+ expect(+ await manager.getCleanupBlockingJobIdsForConversations('user-1', ['unrelated'], 'tenant-a'),+ ).toEqual([]);+ expect((await manager.getJob('pending-host'))?.metadata?.terminalHostActionPending).toBe(+ true,+ );+ },+ );++ it('owner queries retain terminal obligations through active polling without global scans', async () => {+ const job = await manager.createJob('owner-host', 'user-1', 'conversation');+ await store.transitionStatus('owner-host', {+ from: 'running',+ to: 'complete',+ expectCreatedAt: job.createdAt,+ patch: { completedAt: Date.now(), providerDrained: true, terminalHostActionPending: true },+ });+ const global = jest.spyOn(store, 'getTerminalHostActionJobs');+ expect(await manager.getActiveJobIdsForUser('user-1')).toEqual([]);+ expect(await manager.getCleanupBlockingJobIdsForUser('user-1')).toEqual(['owner-host']);+ expect(global).not.toHaveBeenCalled();+ await store.clearTerminalHostAction('owner-host', job.createdAt);+ expect(await manager.getCleanupBlockingJobIdsForUser('user-1')).toEqual([]);+ });++ it('durable cleanup preserves stale terminal-persistence recovery', async () => {+ const job = await manager.createJob('stale-persistence', 'user-1', 'conversation');+ await store.transitionStatus('stale-persistence', {+ from: 'running',+ to: 'complete',+ expectCreatedAt: job.createdAt,+ patch: { completedAt: 1, terminalPersistenceStartedAt: 1, terminalPersistencePending: true },+ });+ expect(await manager.getCleanupJob('stale-persistence')).toMatchObject({+ createdAt: job.createdAt,+ metadata: { terminalPersistencePending: false },+ });+ });++ it('durable cleanup still sees a replacement when runtime attachment loses its epoch', async () => {+ const first = await store.createJob('remote', 'user-1', 'conversation');+ const read = store.getJob.bind(store);+ const replacement = await store.createJob('remote', 'user-1', 'conversation');+ jest.spyOn(store, 'getJob').mockResolvedValueOnce(first).mockImplementation(read);+ expect(await manager.getJob('remote')).toBeUndefined();+ expect(await manager.getCleanupJob('remote')).toMatchObject({+ createdAt: replacement.createdAt,+ status: 'running',+ metadata: { userId: 'user-1' },+ });+ });+it('verifies detached terminal outbox persistence against the exact generation', async () => {const streamId = 'conversation-detached-outbox';const job = await manager.createJob(streamId, 'user-1', streamId);diff --git a/packages/api/src/stream/checkpoints.ts b/packages/api/src/stream/checkpoints.tsnew file mode 100644index 0000000000..f62e4ecaa3--- /dev/null+++ b/packages/api/src/stream/checkpoints.ts@@ -0,0 +1,41 @@+import { createHash, randomUUID } from 'crypto';++export const DEFAULT_CHECKPOINT_TTL_SECONDS: number = 24 * 60 * 60;++const CHECKPOINT_NAMESPACE_PREFIX = 'lcg:v2:';+const SHA256_PATTERN = '[0-9a-f]{64}';+const UUID_V4_PATTERN = '[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}';+const CHECKPOINT_NAMESPACE_PATTERN = new RegExp(+ `^${CHECKPOINT_NAMESPACE_PREFIX}${SHA256_PATTERN}:${UUID_V4_PATTERN}$`,+);++function checkpointOwnerHash(userId: string, tenantId?: string): string {+ return createHash('sha256')+ .update(JSON.stringify([tenantId || null, userId]))+ .digest('hex');+}++/** Stable prefix derived only from the authenticated owner identity. */+export function checkpointOwnerNamespacePrefix(userId: string, tenantId?: string): string {+ return `${CHECKPOINT_NAMESPACE_PREFIX}${checkpointOwnerHash(userId, tenantId)}:`;+}++/** Create an opaque, globally unique saver namespace bound to one exact owner. */+export function createCheckpointNamespace(userId: string, tenantId?: string): string {+ return `${checkpointOwnerNamespacePrefix(userId, tenantId)}${randomUUID()}`;+}++export function isCleanupSafeCheckpointNamespace(value: unknown): value is string {+ return typeof value === 'string' && CHECKPOINT_NAMESPACE_PATTERN.test(value);+}++export function checkpointNamespaceBelongsToOwner(+ value: unknown,+ userId: string,+ tenantId?: string,+): value is string {+ return (+ isCleanupSafeCheckpointNamespace(value) &&+ value.startsWith(checkpointOwnerNamespacePrefix(userId, tenantId))+ );+}diff --git a/packages/api/src/stream/implementations/InMemoryJobStore.ts b/packages/api/src/stream/implementations/InMemoryJobStore.tsindex 3d17d392a2..f711884b09 100644--- a/packages/api/src/stream/implementations/InMemoryJobStore.ts+++ b/packages/api/src/stream/implementations/InMemoryJobStore.ts@@ -43,6 +43,7 @@ import {recoveredSteerPayloadMatches,RecoveredSteerPayloadMismatchError,} from '~/stream/SteerRecovery';+import { createCheckpointNamespace } from '~/stream/checkpoints';import { toPendingSteer } from '~/stream/SteeringLifecycle';/** Recovery window for parked steers (mirrors Redis's completed-job TTL). */@@ -535,7 +536,7 @@ export class InMemoryJobStore implements IJobStoreV2 {createdAt,generationProtocolVersion: initialMetadata.generationProtocolVersion === 1 ? 1 : 2,...(initialMetadata.generationProtocolVersion !== 1 && {- checkpointNamespace: String(createdAt),+ checkpointNamespace: createCheckpointNamespace(userId, tenantId),}),...(conversationId !== undefined && { conversationId }),...(idempotencyClientRequestId !== undefined && {@@ -1367,6 +1368,19 @@ export class InMemoryJobStore implements IJobStoreV2 {return this.getJobIdsByUser(userId, tenantId, true);}+ async getCleanupJobIdsByUser(userId: string, tenantId?: string): Promise<string[]> {+ return this.getJobIdsByUser(userId, tenantId, true);+ }++ async getRetainedJobIdsByUser(userId: string, tenantId?: string): Promise<string[]> {+ const ownerKeys = tenantId ? [`${tenantId}:${userId}`, userId] : [userId];+ const streamIds = new Set(ownerKeys.flatMap((key) => [...(this.userJobMap.get(key) ?? [])]));+ return [...streamIds].filter((streamId) => {+ const job = this.jobs.get(streamId);+ return job?.userId === userId && (job.tenantId == null || job.tenantId === tenantId);+ });+ }+private getJobIdsByUser(userId: string,tenantId: string | undefined,@@ -1397,17 +1411,29 @@ export class InMemoryJobStore implements IJobStoreV2 {if (job.status === 'running' ||job.status === 'requires_action' ||- (includeUndrained && job.providerDrained === false)+ (includeUndrained &&+ (job.providerDrained === false ||+ job.terminalPersistencePending === true ||+ job.terminalHostActionPending === true))) {if (job.status === 'requires_action' &&isPendingActionStale(job) &&- !(includeUndrained && job.providerDrained === false)+ !(+ includeUndrained &&+ (job.providerDrained === false ||+ job.terminalPersistencePending === true ||+ job.terminalHostActionPending === true)+ )) {continue;}activeIds.push(streamId);- } else if (job.providerDrained !== false) {+ } else if (+ job.providerDrained !== false &&+ job.terminalPersistencePending !== true &&+ job.terminalHostActionPending !== true+ ) {// Self-healing: job completed/deleted but mapping wasn't cleaned - fix it nowtrackedIds.delete(streamId);}diff --git a/packages/api/src/stream/implementations/RedisJobStore.ts b/packages/api/src/stream/implementations/RedisJobStore.tsindex 86f5502a0b..1659f045f6 100644--- a/packages/api/src/stream/implementations/RedisJobStore.ts+++ b/packages/api/src/stream/implementations/RedisJobStore.ts@@ -48,6 +48,7 @@ import {} from '~/stream/internal/coalescing';import { instrumentIORedisClient, RedisUseCases } from '~/cache/redisTelemetry';import { RecoveredSteerPayloadMismatchError } from '~/stream/SteerRecovery';+import { createCheckpointNamespace } from '~/stream/checkpoints';const CLIENT_REQUEST_ID_PATTERN = /^[A-Za-z0-9:_-]{1,128}$/;@@ -572,8 +573,7 @@ const JOB_CREATE_LUA ='redis.call("HSET", KEYS[1], "__replacedCreatedAt", replacedCreatedAt, "__replacedStatus", replacedStatus) ' +'if replacedConversationId then redis.call("HSET", KEYS[1], "__replacedConversationId", replacedConversationId) end end ' +'if #replacementChain > 0 then redis.call("HSET", KEYS[1], "__replacedGenerations", cjson.encode(replacementChain)) end ' +- 'if ARGV[10] == "2" then redis.call("HSET", KEYS[1], "checkpointNamespace", tostring(createdAt)) ' +- 'else redis.call("HDEL", KEYS[1], "checkpointNamespace") end ' ++ 'if ARGV[10] ~= "2" then redis.call("HDEL", KEYS[1], "checkpointNamespace") end ' +'redis.call("EXPIRE", KEYS[1], ttl) ' +'redis.call("SET", KEYS[7], tostring(createdAt), "EX", ttl + generationEpochGraceTtl) ' +'if ARGV[8] ~= "" then local claimRaw = redis.call("GET", KEYS[10]) ' +@@ -618,6 +618,16 @@ const JOB_UPDATE_LUA ='end ' +'return 1';+/** Owner membership must outlive every paused job and must never shorten a peer's TTL. */+const OWNER_MEMBERSHIP_RECONCILE_LUA =+ 'local created = redis.call("EXISTS", KEYS[1]) == 0 ' ++ 'redis.call("SADD", KEYS[1], ARGV[1]) ' ++ 'local seconds = tonumber(ARGV[2]) ' ++ 'local current = redis.call("TTL", KEYS[1]) ' ++ 'if seconds > 0 and ((created and current == -1) or (current >= 0 and current < seconds)) then ' ++ 'redis.call("EXPIRE", KEYS[1], seconds) end ' ++ 'return 1';+/** Single-winner recovery outcome for one generation-scoped overflow. */const SETTLE_EARLY_BUFFER_RECOVERY_LUA ='if redis.call("HGET", KEYS[1], "createdAt") ~= ARGV[1] then return 0 end ' +@@ -1828,6 +1838,7 @@ export class RedisJobStore implements IJobStoreV2 {private redis: Redis | Cluster;private cleanupInterval: NodeJS.Timeout | null = null;+ private cleanupMembershipReady?: Promise<void>;private ttl: typeof DEFAULT_TTL;/** Coalescable chunk appends awaiting their window flush, per stream */private pendingAppends = new Map<string, PendingChunkAppendBatch>();@@ -1892,6 +1903,9 @@ export class RedisJobStore implements IJobStoreV2 {this.cleanupInterval.unref();}+ void this.ensureCleanupMembership().catch((err) => {+ logger.error('[RedisJobStore] Owner cleanup membership recovery failed:', err);+ });logger.info('[RedisJobStore] Initialized with cleanup interval');}@@ -2022,6 +2036,9 @@ export class RedisJobStore implements IJobStoreV2 {status: 'running',createdAt: Date.now(),generationProtocolVersion,+ ...(generationProtocolVersion === 2 && {+ checkpointNamespace: createCheckpointNamespace(userId, tenantId),+ }),...(conversationId !== undefined && { conversationId }),...(idempotencyClientRequestId !== undefined && {idempotencyClientRequestId,@@ -2136,11 +2153,6 @@ export class RedisJobStore implements IJobStoreV2 {? Number(previousOwner[2]): job.createdAt;job.createdAt = Number.isFinite(createdAt) ? createdAt : job.createdAt;- if (job.generationProtocolVersion === 2) {- job.checkpointNamespace = String(job.createdAt);- } else {- delete job.checkpointNamespace;- }const replacedCreatedAt =Array.isArray(previousOwner) &&(typeof previousOwner[4] === 'string' || typeof previousOwner[4] === 'number') &&@@ -2525,7 +2537,9 @@ export class RedisJobStore implements IJobStoreV2 {left.status === right.status &&left.userId === right.userId &&left.tenantId === right.tenantId &&- left.providerDrained === right.providerDrained+ left.providerDrained === right.providerDrained &&+ left.terminalPersistencePending === right.terminalPersistencePending &&+ left.terminalHostActionPending === right.terminalHostActionPending);}@@ -2535,6 +2549,47 @@ export class RedisJobStore implements IJobStoreV2 {}}+ private ownerMembershipTtl(job: SerializableJobData | null): number {+ if (this.ttl.userJobsSet <= 0) return this.ttl.userJobsSet;+ return Math.max(+ this.ttl.userJobsSet,+ job?.status === 'requires_action' ? this.pauseTtlSeconds(job.pendingAction) : 0,+ job?.terminalHostActionPending ? Math.max(this.ttl.completed, this.ttl.requiresAction) : 0,+ job?.terminalPersistencePending+ ? Math.max(this.ttl.completed, TERMINAL_PERSISTENCE_RETENTION_TTL_S)+ : 0,+ );+ }++ private async retainCleanupOwner(job: SerializableJobData): Promise<void> {+ await this.redis.eval(+ OWNER_MEMBERSHIP_RECONCILE_LUA,+ 1,+ KEYS.userJobs(job.userId, job.tenantId),+ job.streamId,+ String(this.ownerMembershipTtl(job)),+ );+ }++ /** Recover retained work from older stores once; owner requests await recovery. */+ private ensureCleanupMembership(): Promise<void> {+ if (this.cleanupMembershipReady == null) {+ this.cleanupMembershipReady = Promise.allSettled([+ this.getTerminalHostActionJobs(),+ this.getDetachedAgentEventTerminalHostActionJobs(),+ ])+ .then((results) => {+ const failure = results.find((result) => result.status === 'rejected');+ if (failure?.status === 'rejected') throw failure.reason;+ })+ .catch((err) => {+ this.cleanupMembershipReady = undefined;+ throw err;+ });+ }+ return this.cleanupMembershipReady;+ }+private async applyMembershipSnapshot(streamId: string,job: SerializableJobData | null,@@ -2542,9 +2597,14 @@ export class RedisJobStore implements IJobStoreV2 {): Promise<SerializableJobData | null> {const statusKey = job ? this.statusSetKey(job.status) : null;const activeUserKey =- job && (statusKey != null || job.providerDrained === false)+ job &&+ (statusKey != null ||+ job.providerDrained === false ||+ job.terminalPersistencePending === true ||+ job.terminalHostActionPending === true)? KEYS.userJobs(job.userId, job.tenantId): null;+ const ownerMembershipTtl = this.ownerMembershipTtl(job);const terminalMember = job == null ? null : terminalHostActionMember(streamId, job.createdAt);const terminalHostActionIndex =job != null && isDetachedAgentEventCompletionJob(job)@@ -2592,12 +2652,13 @@ export class RedisJobStore implements IJobStoreV2 {}if (activeUserKey) {operations.push(- (async () => {- await this.redis.sadd(activeUserKey, streamId);- if (this.ttl.userJobsSet > 0) {- await this.redis.expire(activeUserKey, this.ttl.userJobsSet);- }- })(),+ this.redis.eval(+ OWNER_MEMBERSHIP_RECONCILE_LUA,+ 1,+ activeUserKey,+ streamId,+ String(ownerMembershipTtl),+ ),);}await Promise.all(operations);@@ -2632,16 +2693,22 @@ export class RedisJobStore implements IJobStoreV2 {}}if (activeUserKey) {- pipeline.sadd(activeUserKey, streamId);- if (this.ttl.userJobsSet > 0) {- pipeline.expire(activeUserKey, this.ttl.userJobsSet);- }+ pipeline.eval(+ OWNER_MEMBERSHIP_RECONCILE_LUA,+ 1,+ activeUserKey,+ streamId,+ String(ownerMembershipTtl),+ );}// Keep the verification read in this network flush. Redis executes it// after the membership commands, preserving the guarded loop without an// extra round trip on the default single-node deployment.pipeline.hgetall(KEYS.job(streamId));const results = await pipeline.exec();+ if (results == null) throw new Error('Owner membership pipeline did not execute');+ const failed = results.find(([err]) => err != null);+ if (failed?.[0]) throw failed[0];const verification = results?.[results.length - 1];if (verification?.[0]) {throw verification[0];@@ -2836,6 +2903,13 @@ export class RedisJobStore implements IJobStoreV2 {);}+ if (+ terminalJob != null &&+ (patch?.terminalHostActionPending === true || patch?.terminalPersistencePending === true)+ ) {+ await this.retainCleanupOwner({ ...terminalJob, ...patch, status: to });+ }+// 1) Single-winner decision: an atomic CAS on the single-slot job hash.// Works identically on cluster and single-node, so two concurrent// resolves can never both win (and drive the run twice).@@ -3144,6 +3218,7 @@ export class RedisJobStore implements IJobStoreV2 {const rerouteToLegacy: string[] = [];const rerouteToDetached: string[] = [];const heldByGeneration = new Map<string, SerializableJobData>();+ const ownersToRetain: SerializableJobData[] = [];const readyByGeneration = new Map<string, SerializableJobData>();const providerLossCutoff = Date.now() - PROVIDER_DRAIN_TIMEOUT_MS;for (let i = 0; i < indexed.length; i++) {@@ -3154,6 +3229,7 @@ export class RedisJobStore implements IJobStoreV2 {job.terminalHostActionPending === true &&(indexedMember.createdAt == null || indexedMember.createdAt === job.createdAt)) {+ ownersToRetain.push(job);const jobIsDetachedCompletion = isDetachedAgentEventCompletionJob(job);if (jobIsDetachedCompletion !== detachedAgentEventCompletion) {const generationMember = terminalHostActionMember(job.streamId, job.createdAt);@@ -3211,6 +3287,7 @@ export class RedisJobStore implements IJobStoreV2 {stale.push(indexedMember.member);}}+ await Promise.all(ownersToRetain.map((job) => this.retainCleanupOwner(job)));// Repair a hint written by an earlier capable build before removing it// from the wrong lane. In particular, this drains detached completions out// of the legacy set without ever returning them to a capable claimant.@@ -3249,6 +3326,7 @@ export class RedisJobStore implements IJobStoreV2 {}async clearTerminalHostAction(streamId: string, expectedCreatedAt?: number): Promise<void> {+ const previousJob = await this.getJob(streamId);// Identity-fenced: only clear when the hash still holds this exact generation, so a// replacement at the same streamId is never cleared through its predecessor. The HDEL// and configured evidence-TTL reset happen atomically. The global retry@@ -3274,6 +3352,7 @@ export class RedisJobStore implements IJobStoreV2 {)) as number;if (cleared === 1 && expectedCreatedAt != null) {const member = terminalHostActionMember(streamId, expectedCreatedAt);+ await this.reconcileJobMembership(streamId, { previousJob });await Promise.all([this.redis.srem(KEYS.terminalHostActionJobs, member).catch(() => undefined),this.redis@@ -3552,6 +3631,24 @@ export class RedisJobStore implements IJobStoreV2 {return this.getJobIdsByUser(userId, tenantId, true);}+ async getCleanupJobIdsByUser(userId: string, tenantId?: string): Promise<string[]> {+ await this.ensureCleanupMembership();+ return this.getJobIdsByUser(userId, tenantId, true);+ }++ async getRetainedJobIdsByUser(userId: string, tenantId?: string): Promise<string[]> {+ const ownerKeys = tenantId+ ? [KEYS.userJobs(userId, tenantId), KEYS.userJobs(userId)]+ : [KEYS.userJobs(userId)];+ const tracked = await Promise.all(ownerKeys.map((key) => this.redis.smembers(key)));+ const streamIds = [...new Set(tracked.flat())];+ const jobs = await Promise.all(streamIds.map((streamId) => this.getJob(streamId)));+ return streamIds.filter((_, index) => {+ const job = jobs[index];+ return job?.userId === userId && (job.tenantId == null || job.tenantId === tenantId);+ });+ }+private async getJobIdsByUser(userId: string,tenantId: string | undefined,@@ -3581,12 +3678,20 @@ export class RedisJobStore implements IJobStoreV2 {job &&(job.status === 'running' ||job.status === 'requires_action' ||- (includeUndrained && job.providerDrained === false))+ (includeUndrained &&+ (job.providerDrained === false ||+ job.terminalPersistencePending === true ||+ job.terminalHostActionPending === true)))) {if (job.status === 'requires_action' &&isPendingActionStale(job) &&- !(includeUndrained && job.providerDrained === false)+ !(+ includeUndrained &&+ (job.providerDrained === false ||+ job.terminalPersistencePending === true ||+ job.terminalHostActionPending === true)+ )) {continue;}@@ -3599,6 +3704,8 @@ export class RedisJobStore implements IJobStoreV2 {previousJob: job,previousUserKeys: [userJobsKey],});+ if (includeUndrained && currentJob === undefined)+ throw new Error(`Cannot verify owner job membership: ${streamId}`);const currentBelongsToUser =currentJob?.userId === userId &&(currentJob.tenantId ?? undefined) === (tenantId ?? undefined);@@ -3607,11 +3714,19 @@ export class RedisJobStore implements IJobStoreV2 {currentJob &&(currentJob.status === 'running' ||currentJob.status === 'requires_action' ||- (includeUndrained && currentJob.providerDrained === false)) &&+ (includeUndrained &&+ (currentJob.providerDrained === false ||+ currentJob.terminalPersistencePending === true ||+ currentJob.terminalHostActionPending === true))) &&!(currentJob.status === 'requires_action' &&isPendingActionStale(currentJob) &&- !(includeUndrained && currentJob.providerDrained === false)+ !(+ includeUndrained &&+ (currentJob.providerDrained === false ||+ currentJob.terminalPersistencePending === true ||+ currentJob.terminalHostActionPending === true)+ ))) {activeIds.push(streamId);@@ -3628,6 +3743,8 @@ export class RedisJobStore implements IJobStoreV2 {}async destroy(): Promise<void> {+ await this.cleanupMembershipReady?.catch(() => undefined);+ this.cleanupMembershipReady = undefined;if (this.cleanupInterval) {clearInterval(this.cleanupInterval);this.cleanupInterval = null;diff --git a/packages/api/src/stream/index.ts b/packages/api/src/stream/index.tsindex 752c454148..bded1f628a 100644--- a/packages/api/src/stream/index.ts+++ b/packages/api/src/stream/index.ts@@ -70,3 +70,5 @@ export { InMemoryJobStore } from './implementations/InMemoryJobStore';export { InMemoryEventTransport } from './implementations/InMemoryEventTransport';export { RedisJobStore } from './implementations/RedisJobStore';export { RedisEventTransport } from './implementations/RedisEventTransport';++export { waitForGenerationPersistence } from './persistence';diff --git a/packages/api/src/stream/interfaces/IJobStore.ts b/packages/api/src/stream/interfaces/IJobStore.tsindex ff128e1bda..361ddccc28 100644--- a/packages/api/src/stream/interfaces/IJobStore.ts+++ b/packages/api/src/stream/interfaces/IJobStore.ts@@ -113,8 +113,8 @@ export interface SerializableJobData {status: JobStatus;createdAt: number;generationProtocolVersion?: GenerationProtocolVersion;- /** Saver-level checkpoint scope for this exact generation. New jobs use- * their final store-assigned epoch; LangGraph still sees an empty root+ /** Saver-level checkpoint scope for this exact generation. New jobs use a+ * globally unique opaque identity; LangGraph still sees an empty root* `checkpoint_ns`, which the saver adapter maps to this storage scope.* Legacy paused jobs omit it and use the historical unscoped storage. */checkpointNamespace?: string;@@ -953,6 +953,15 @@ export interface IJobStore {getJobCountByStatus(status: JobStatus): Promise<number>;destroy(): Promise<void>;getActiveJobIdsByUser(userId: string, tenantId?: string): Promise<string[]>;++ /** Complete owner cleanup query, including terminal host work and legacy-index recovery.+ * Managers retain the global-index fallback for older third-party stores. */+ getCleanupJobIdsByUser?(userId: string, tenantId?: string): Promise<string[]>;++ /** Enumerates every extant job in the owner's retained index, including a+ * stale paused generation that account deletion must erase before its worker+ * finalizes it. Optional custom stores fall back to cleanup-blocking jobs. */+ getRetainedJobIdsByUser?(userId: string, tenantId?: string): Promise<string[]>;setGraph(streamId: string, graph: StandardGraph, expectedCreatedAt?: number): void;setContentParts(streamId: string,diff --git a/packages/api/src/stream/persistence.spec.ts b/packages/api/src/stream/persistence.spec.tsnew file mode 100644index 0000000000..4eea9e6449--- /dev/null+++ b/packages/api/src/stream/persistence.spec.ts@@ -0,0 +1,42 @@+import { waitForGenerationPersistence } from './persistence';++test('waits for the captured terminal epoch to finish persistence', async () => {+ const read = jest+ .fn()+ .mockResolvedValueOnce({ createdAt: 1, metadata: { terminalPersistencePending: true } })+ .mockResolvedValueOnce({ createdAt: 1, metadata: { terminalPersistencePending: false } });+ await waitForGenerationPersistence('run', 1, read, { pollMs: 1 });+ expect(read).toHaveBeenCalledTimes(2);+});++test('fails closed on a replacement epoch', async () => {+ const read = jest+ .fn()+ .mockResolvedValue({ createdAt: 2, metadata: { terminalPersistencePending: true } });+ await expect(waitForGenerationPersistence('run', 1, read)).rejects.toThrow('Generation replaced');+ expect(read).toHaveBeenCalledTimes(1);+});++test.each(['terminalPersistencePending', 'terminalHostActionPending'])(+ 'fails closed on %s and lookup errors',+ async (marker) => {+ const read = jest.fn().mockResolvedValue({ createdAt: 1, metadata: { [marker]: true } });+ await expect(waitForGenerationPersistence('run', 1, read, { timeoutMs: 0 })).rejects.toThrow(+ 'Timed out',+ );+ read.mockRejectedValue(new Error('unavailable'));+ await expect(waitForGenerationPersistence('run', 1, read)).rejects.toThrow('unavailable');+ },+);++test('waits for terminal host actions after provider persistence has cleared', async () => {+ const read = jest+ .fn()+ .mockResolvedValueOnce({+ createdAt: 1,+ metadata: { terminalHostActionPending: true, terminalPersistencePending: false },+ })+ .mockResolvedValueOnce({ createdAt: 1, metadata: { terminalHostActionPending: false } });+ await waitForGenerationPersistence('run', 1, read, { pollMs: 1 });+ expect(read).toHaveBeenCalledTimes(2);+});diff --git a/packages/api/src/stream/persistence.ts b/packages/api/src/stream/persistence.tsnew file mode 100644index 0000000000..c85eddf965--- /dev/null+++ b/packages/api/src/stream/persistence.ts@@ -0,0 +1,29 @@+import type { GenerationJob } from '../types/stream';++/** A settled status can precede final persistence and terminal host actions. */+export async function waitForGenerationPersistence(+ streamId: string,+ createdAt: number,+ readJob: (+ id: string,+ ) => Promise<Pick<GenerationJob, 'createdAt' | 'metadata'> | null | undefined>,+ { timeoutMs = 45_000, pollMs = 100 }: { timeoutMs?: number; pollMs?: number } = {},+): Promise<void> {+ const deadline = Date.now() + timeoutMs;+ while (true) {+ const current = await readJob(streamId);+ if (current != null && current.createdAt !== createdAt) {+ throw new Error(`Generation replaced during deletion: ${streamId}`);+ }+ if (+ current == null ||+ (current.metadata?.terminalPersistencePending !== true &&+ current.metadata?.terminalHostActionPending !== true)+ )+ return;+ if (Date.now() >= deadline) {+ throw new Error(`Timed out waiting for generation persistence: ${streamId}`);+ }+ await new Promise((resolve) => setTimeout(resolve, pollMs));+ }+}diff --git a/packages/api/src/types/stream.ts b/packages/api/src/types/stream.tsindex c7571c557f..cac50e8fb5 100644--- a/packages/api/src/types/stream.ts+++ b/packages/api/src/types/stream.ts@@ -116,6 +116,7 @@ export interface GenerationJobMetadata {idempotencyClientRequestId?: string;/** Normal FINAL publication is waiting on required durable abort work. */terminalPersistencePending?: boolean;+ terminalHostActionPending?: boolean;terminalPersistenceStartedAt?: number;/** Set when the job is paused for human review (status === 'requires_action') */pendingAction?: Agents.PendingAction;diff --git a/packages/data-provider/src/config.spec.ts b/packages/data-provider/src/config.spec.tsindex cd18870865..320d1442c3 100644--- a/packages/data-provider/src/config.spec.ts+++ b/packages/data-provider/src/config.spec.ts@@ -27,6 +27,8 @@ describe('excludedKeys', () => {'conversationId','agentEventBinding','agentEventActor',+ 'agentEventActorCleanup',+ 'agentEventActorSuspension','agentEventActorReconciliations','__v',])('excludes system field "%s"', (field) => {diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.tsindex d7a50415a4..997f391016 100644--- a/packages/data-provider/src/config.ts+++ b/packages/data-provider/src/config.ts@@ -71,6 +71,8 @@ export const excludedKeys = new Set(['conversationId','agentEventBinding','agentEventActor',+ 'agentEventActorCleanup',+ 'agentEventActorSuspension','agentEventActorReconciliations','agentEventActorEpoch','agentEventActorLegacyTurn',diff --git a/packages/data-schemas/src/methods/conversation.spec.ts b/packages/data-schemas/src/methods/conversation.spec.tsindex 7a1f99af36..1997406cda 100644--- a/packages/data-schemas/src/methods/conversation.spec.ts+++ b/packages/data-schemas/src/methods/conversation.spec.ts@@ -174,6 +174,55 @@ describe('Conversation Operations', () => {expect(savedConvo?.title).toBe('Test Conversation');});+ it('rejects actor checkpoint ownership evidence through ordinary saves and imports', async () => {+ const forged = {+ agentEventActor: {+ generation: 1,+ checkpoint: {+ threadId: 'other',+ checkpointNs: 'event-actor/other',+ checkpointId: 'other',+ },+ },+ agentEventActorCleanup: [+ { threadId: 'other', checkpointNs: 'event-actor/other', checkpointId: 'other' },+ ],+ agentEventActorReconciliations: [+ {+ checkpoint: {+ threadId: 'other',+ checkpointNs: 'event-actor/other',+ checkpointId: 'other',+ },+ },+ ],+ agentEventActorSuspension: { status: 'closed' },+ 'agentEventActor.checkpoint': {+ threadId: 'other',+ checkpointNs: 'event-actor/other',+ checkpointId: 'other',+ },+ 'agentEventActorCleanup.0': {+ threadId: 'other',+ checkpointNs: 'event-actor/other',+ checkpointId: 'other',+ },+ };+ await saveConvo(mockCtx, { ...mockConversationData, ...forged });+ await methods.bulkSaveConvos([{ ...mockConversationData, user: mockCtx.userId, ...forged }]);+ const saved = await Conversation.findOne({+ conversationId: mockConversationData.conversationId,+ user: mockCtx.userId,+ })+ .select(+ '+agentEventActor +agentEventActorCleanup +agentEventActorReconciliations +agentEventActorSuspension',+ )+ .lean();+ for (const field of Object.keys(forged)) {+ expect(saved).not.toHaveProperty(field);+ }+ });+it('sets immutable agent attribution from server metadata only on insert', async () => {await saveConvo(mockCtx,@@ -2079,6 +2128,16 @@ describe('Conversation Operations', () => {);});+ it('allows a single-conversation cleanup retry after topology and messages are gone', async () => {+ const result = await deleteConvos(+ 'user123',+ { conversationId: 'already-absent' },+ { allowEmpty: true },+ );+ expect(result.deletedCount).toBe(0);+ expect(result.conversationIds).toEqual(['already-absent']);+ });+it('supports an idempotent empty recovery sweep without hiding storage failures', async () => {await expect(deleteConvos(@@ -4136,279 +4195,315 @@ describe('Conversation Operations', () => {);});- it('serializes suspension ownership through claim, re-pause, and resumed commit', async () => {- const conversationId = uuidv4();- const owner = {- user: 'suspended-actor-user',- tenantId: 'tenant-a',- conversationId,- };- await Conversation.create({- conversationId,- user: owner.user,- tenantId: owner.tenantId,- endpoint: EModelEndpoint.agents,- agent_id: 'agent-player',- agentEventBinding: {- bindingId: `evtbind_${'s'.repeat(48)}`,- sourceKeyId: 'key-a',- actorId: 'player-a',- },- subagentThread: {- rootConversationId: 'parent',- parentConversationId: 'parent',- parentMessageId: 'parent-message',- parentToolCallId: 'event-binding',- parentAgentId: 'agent-director',- subagentType: 'agent-player',- subagentKind: 'agent',- depth: 1,- },- });- const checkpoint = (suffix: string) => ({- threadId: conversationId,- checkpointId: `checkpoint-${suffix}`,- checkpointNs: `event-actor/${suffix}`,- });- const suspension = (suffix: string, attempt: number): IAgentEventActorSuspensionEvidence => ({- version: 1,- suspensionId: `suspension-${suffix}`,- attempt,- issuedAt: 1_000 + attempt,- expiresAt: 100_000 + attempt,- invocation: {- actorThreadId: conversationId,- invocationId: 'event-pause',- depth: 1,- continuation: 'cold',- base: { actorThreadId: conversationId, generation: 0 },- fork: { ...checkpoint('fork'), invocationId: 'event-pause' },- },- checkpoint: {- ...checkpoint('fork'),+ it.each(['owned', 'legacy'])(+ 'serializes %s suspension ownership through claim, re-pause, and resumed commit',+ async (storage) => {+ const conversationId = uuidv4();+ const owner = {+ user: 'suspended-actor-user',+ tenantId: 'tenant-a',+ conversationId,+ };+ await Conversation.create({+ conversationId,+ user: owner.user,+ tenantId: owner.tenantId,+ endpoint: EModelEndpoint.agents,+ agent_id: 'agent-player',+ agentEventBinding: {+ bindingId: `evtbind_${'s'.repeat(48)}`,+ sourceKeyId: 'key-a',+ actorId: 'player-a',+ },+ subagentThread: {+ rootConversationId: 'parent',+ parentConversationId: 'parent',+ parentMessageId: 'parent-message',+ parentToolCallId: 'event-binding',+ parentAgentId: 'agent-director',+ subagentType: 'agent-player',+ subagentKind: 'agent',+ depth: 1,+ },+ });+ const checkpoint = (suffix: string) => ({+ threadId: conversationId,checkpointId: `checkpoint-${suffix}`,- invocationId: 'event-pause',- },- interrupt: {- id: `interrupt-${suffix}`,- payload: { type: 'ask_user_question', actionId: `action-${suffix}` },- },- suspensionDigest: `digest-${suffix}`,- });-- await expect(- methods.recordAgentEventActorReconciliation({- ...owner,- reconciliation: {+ checkpointNs: `event-actor/${suffix}`,+ });+ const suspension = (+ suffix: string,+ attempt: number,+ ): IAgentEventActorSuspensionEvidence => ({+ version: 1,+ suspensionId: `suspension-${suffix}`,+ attempt,+ issuedAt: 1_000 + attempt,+ expiresAt: 100_000 + attempt,+ invocation: {+ actorThreadId: conversationId,invocationId: 'event-pause',- actionAdmitted: true,- status: 'invocation_pending',- checkpoint: checkpoint('fork'),- action: { toolName: 'submit_move' },- observedAt: new Date(),+ depth: 1,+ continuation: 'cold',+ base: { actorThreadId: conversationId, generation: 0 },+ fork: { ...checkpoint('fork'), invocationId: 'event-pause' },},- }),- ).resolves.toBe(true);- const first = suspension('first', 0);- await expect(- methods.storeAgentEventActorSuspension({- ...owner,- suspension: {- ...first,- interrupt: {- ...first.interrupt,- payload: { type: 'ask_user_question', question: 'x'.repeat(65 * 1_024) },- },+ checkpoint: {+ ...checkpoint('fork'),+ checkpointId: `checkpoint-${suffix}`,+ invocationId: 'event-pause',},- actionId: 'action-oversized',- jobCreatedAt: 123,- }),- ).rejects.toThrow('Event actor suspension exceeds maximum payload size');- await expect(- methods.storeAgentEventActorSuspension({- ...owner,- suspension: first,- actionId: 'action-first',- jobCreatedAt: 123,- }),- ).resolves.toEqual({ status: 'stored' });- await expect(methods.getAgentEventActorSnapshot(owner)).resolves.toMatchObject({- suspension: { kind: 'human_decision' },- });- await expect(- methods.storeAgentEventActorSuspension({- ...owner,- suspension: { ...first, suspensionId: 'competing-suspension' },- actionId: 'action-first',- jobCreatedAt: 123,- }),- ).resolves.toEqual({ status: 'stale' });+ interrupt: {+ id: `interrupt-${suffix}`,+ payload: { type: 'ask_user_question', actionId: `action-${suffix}` },+ },+ suspensionDigest: `digest-${suffix}`,+ });- const claim = {- ...owner,- suspensionId: first.suspensionId,- attempt: first.attempt,- actionId: 'action-first',- jobCreatedAt: 123,- resumeAttemptId: 'resume-one',- };- const claims = await Promise.all([- methods.claimAgentEventActorSuspension(claim),- methods.claimAgentEventActorSuspension({ ...claim, resumeAttemptId: 'resume-two' }),- ]);- expect(claims).toEqual(expect.arrayContaining([{ status: 'claimed' }, { status: 'stale' }]));- const winningResumeAttemptId = claims[0].status === 'claimed' ? 'resume-one' : 'resume-two';+ await expect(+ methods.recordAgentEventActorReconciliation({+ ...owner,+ reconciliation: {+ invocationId: 'event-pause',+ actionAdmitted: true,+ status: 'invocation_pending',+ checkpoint: checkpoint('fork'),+ action: { toolName: 'submit_move' },+ observedAt: new Date(),+ },+ }),+ ).resolves.toBe(true);+ const first = suspension('first', 0);+ await expect(+ methods.storeAgentEventActorSuspension({+ ...owner,+ suspension: {+ ...first,+ interrupt: {+ ...first.interrupt,+ payload: { type: 'ask_user_question', question: 'x'.repeat(65 * 1_024) },+ },+ },+ actionId: 'action-oversized',+ jobCreatedAt: 123,+ }),+ ).rejects.toThrow('Event actor suspension exceeds maximum payload size');+ await expect(+ methods.storeAgentEventActorSuspension({+ ...owner,+ suspension: first,+ actionId: 'action-first',+ jobCreatedAt: 123,+ }),+ ).resolves.toEqual({ status: 'stored' });+ await expect(methods.getAgentEventActorSnapshot(owner)).resolves.toMatchObject({+ suspension: { kind: 'human_decision' },+ });+ await expect(+ methods.storeAgentEventActorSuspension({+ ...owner,+ suspension: { ...first, suspensionId: 'competing-suspension' },+ actionId: 'action-first',+ jobCreatedAt: 123,+ }),+ ).resolves.toEqual({ status: 'stale' });- const second = suspension('second', 1);- await expect(- methods.storeAgentEventActorSuspension({+ expect(+ (await Conversation.collection.findOne({ conversationId }))?.agentEventActorSuspension+ .status,+ ).toBe('pending_owned');+ const oldClaim = await Conversation.collection.updateOne(+ { conversationId, user: owner.user, 'agentEventActorSuspension.status': 'pending' },+ { $set: { 'agentEventActorSuspension.status': 'claimed' } },+ );+ expect(oldClaim.matchedCount).toBe(0);+ if (storage === 'legacy') {+ await Conversation.collection.updateOne(+ { conversationId },+ { $set: { 'agentEventActorSuspension.status': 'pending' } },+ );+ }++ const claim = {...owner,- suspension: second,- kind: 'internal_completion',- actionId: 'action-second',+ suspensionId: first.suspensionId,+ attempt: first.attempt,+ actionId: 'action-first',jobCreatedAt: 123,- previous: {- suspensionId: first.suspensionId,- attempt: first.attempt,- resumeAttemptId: winningResumeAttemptId,+ resumeAttemptId: 'resume-one',+ };+ const claims = await Promise.all([+ methods.claimAgentEventActorSuspension(claim),+ methods.claimAgentEventActorSuspension({ ...claim, resumeAttemptId: 'resume-two' }),+ ]);+ expect(claims).toEqual(+ expect.arrayContaining([{ status: 'claimed' }, { status: 'stale' }]),+ );+ const winningResumeAttemptId = claims[0].status === 'claimed' ? 'resume-one' : 'resume-two';+ expect(+ (await Conversation.collection.findOne({ conversationId }))?.agentEventActorSuspension+ .status,+ ).toBe('claimed_owned');+ expect(+ (+ await Conversation.collection.updateOne(+ { conversationId, user: owner.user, 'agentEventActorSuspension.status': 'claimed' },+ { $set: { 'agentEventActorSuspension.status': 'closed' } },+ )+ ).matchedCount,+ ).toBe(0);++ const second = suspension('second', 1);+ await expect(+ methods.storeAgentEventActorSuspension({+ ...owner,+ suspension: second,+ kind: 'internal_completion',+ actionId: 'action-second',+ jobCreatedAt: 123,+ previous: {+ suspensionId: first.suspensionId,+ attempt: first.attempt,+ resumeAttemptId: winningResumeAttemptId,+ },+ }),+ ).resolves.toEqual({ status: 'stored' });+ await expect(methods.getAgentEventActorSnapshot(owner)).resolves.toMatchObject({+ suspension: {+ kind: 'internal_completion',+ suspension: { suspensionId: second.suspensionId },},- }),- ).resolves.toEqual({ status: 'stored' });- await expect(methods.getAgentEventActorSnapshot(owner)).resolves.toMatchObject({- suspension: {- kind: 'internal_completion',- suspension: { suspensionId: second.suspensionId },- },- });- await expect(- methods.claimAgentEventActorSuspension({- ...owner,- suspensionId: second.suspensionId,- attempt: second.attempt,- actionId: 'action-second',- jobCreatedAt: 123,- resumeAttemptId: 'resume-three',- }),- ).resolves.toEqual({ status: 'claimed' });-- await expect(- methods.commitAgentEventActorState({- ...owner,- invocationId: 'event-pause',- expectedEpoch: 0,- action: { toolName: 'submit_move' },- checkpoint: checkpoint('committed'),- settlementAuthority: {+ });+ await expect(+ methods.claimAgentEventActorSuspension({+ ...owner,suspensionId: second.suspensionId,attempt: second.attempt,+ actionId: 'action-second',+ jobCreatedAt: 123,resumeAttemptId: 'resume-three',- },- }),- ).resolves.toMatchObject({ status: 'committed' });- await expect(methods.getAgentEventActorSnapshot(owner)).resolves.toMatchObject({- suspension: {- status: 'closed',- outcome: 'committed',- resumeAttemptId: 'resume-three',- },- state: { generation: 1, checkpoint: checkpoint('committed') },- });- await expect(- methods.recordAgentEventActorReconciliation({- ...owner,- reconciliation: {+ }),+ ).resolves.toEqual({ status: 'claimed' });++ await expect(+ methods.commitAgentEventActorState({+ ...owner,invocationId: 'event-pause',- actionAdmitted: true,- status: 'history_persisted',- checkpoint: checkpoint('committed'),+ expectedEpoch: 0,action: { toolName: 'submit_move' },- observedAt: new Date(),+ checkpoint: checkpoint('committed'),+ settlementAuthority: {+ suspensionId: second.suspensionId,+ attempt: second.attempt,+ resumeAttemptId: 'resume-three',+ },+ }),+ ).resolves.toMatchObject({ status: 'committed' });+ await expect(methods.getAgentEventActorSnapshot(owner)).resolves.toMatchObject({+ suspension: {+ status: 'closed',+ outcome: 'committed',+ resumeAttemptId: 'resume-three',},- }),- ).resolves.toBe(true);- await expect(- methods.resolveAgentEventActorReconciliation({- ...owner,- invocationId: 'event-pause',- checkpoint: checkpoint('committed'),- resolution: 'checkpoint_verified',- }),- ).resolves.toBe(true);+ state: { generation: 1, checkpoint: checkpoint('committed') },+ });+ await expect(+ methods.recordAgentEventActorReconciliation({+ ...owner,+ reconciliation: {+ invocationId: 'event-pause',+ actionAdmitted: true,+ status: 'history_persisted',+ checkpoint: checkpoint('committed'),+ action: { toolName: 'submit_move' },+ observedAt: new Date(),+ },+ }),+ ).resolves.toBe(true);+ await expect(+ methods.resolveAgentEventActorReconciliation({+ ...owner,+ invocationId: 'event-pause',+ checkpoint: checkpoint('committed'),+ resolution: 'checkpoint_verified',+ }),+ ).resolves.toBe(true);- const cancellationCheckpoint = checkpoint('cancel');- const cancellationSuspension: IAgentEventActorSuspensionEvidence = {- ...suspension('cancel', 0),- invocation: {- ...suspension('cancel', 0).invocation,- invocationId: 'event-cancel',- fork: {- ...cancellationCheckpoint,+ const cancellationCheckpoint = checkpoint('cancel');+ const cancellationSuspension: IAgentEventActorSuspensionEvidence = {+ ...suspension('cancel', 0),+ invocation: {+ ...suspension('cancel', 0).invocation,invocationId: 'event-cancel',+ fork: {+ ...cancellationCheckpoint,+ invocationId: 'event-cancel',+ },},- },- checkpoint: {- ...cancellationCheckpoint,- invocationId: 'event-cancel',- },- };- await expect(- methods.recordAgentEventActorReconciliation({- ...owner,- reconciliation: {+ checkpoint: {+ ...cancellationCheckpoint,invocationId: 'event-cancel',- status: 'invocation_pending',- checkpoint: cancellationCheckpoint,- action: { toolName: 'submit_move' },- observedAt: new Date(),},- }),- ).resolves.toBe(true);- await expect(- methods.storeAgentEventActorSuspension({- ...owner,- suspension: cancellationSuspension,- actionId: 'action-cancel',- jobCreatedAt: 124,- }),- ).resolves.toEqual({ status: 'stored' });- const [resumeRace, cancelRace] = await Promise.all([- methods.claimAgentEventActorSuspension({- ...owner,- suspensionId: cancellationSuspension.suspensionId,- attempt: 0,- actionId: 'action-cancel',- jobCreatedAt: 124,- resumeAttemptId: 'resume-race',- }),- methods.cancelAgentEventActorSuspension({- ...owner,- suspensionId: cancellationSuspension.suspensionId,- attempt: 0,- invocationId: 'event-cancel',- checkpoint: cancellationCheckpoint,- }),- ]);- const raceStatuses = [resumeRace.status, cancelRace.status];- expect(raceStatuses.filter((status) => status === 'stale')).toHaveLength(1);- expect(raceStatuses).toEqual(- expect.arrayContaining([expect.stringMatching(/^(claimed|cancelled)$/), 'stale']),- );- if (resumeRace.status === 'claimed') {+ };+ await expect(+ methods.recordAgentEventActorReconciliation({+ ...owner,+ reconciliation: {+ invocationId: 'event-cancel',+ status: 'invocation_pending',+ checkpoint: cancellationCheckpoint,+ action: { toolName: 'submit_move' },+ observedAt: new Date(),+ },+ }),+ ).resolves.toBe(true);await expect(+ methods.storeAgentEventActorSuspension({+ ...owner,+ suspension: cancellationSuspension,+ actionId: 'action-cancel',+ jobCreatedAt: 124,+ }),+ ).resolves.toEqual({ status: 'stored' });+ const [resumeRace, cancelRace] = await Promise.all([+ methods.claimAgentEventActorSuspension({+ ...owner,+ suspensionId: cancellationSuspension.suspensionId,+ attempt: 0,+ actionId: 'action-cancel',+ jobCreatedAt: 124,+ resumeAttemptId: 'resume-race',+ }),methods.cancelAgentEventActorSuspension({...owner,suspensionId: cancellationSuspension.suspensionId,attempt: 0,invocationId: 'event-cancel',checkpoint: cancellationCheckpoint,- claimedResumeAttemptId: 'resume-race',}),- ).resolves.toEqual({ status: 'cancelled' });- }- await expect(methods.getAgentEventActorSnapshot(owner)).resolves.toMatchObject({- suspension: { status: 'closed', outcome: 'cancelled' },- });- });+ ]);+ const raceStatuses = [resumeRace.status, cancelRace.status];+ expect(raceStatuses.filter((status) => status === 'stale')).toHaveLength(1);+ expect(raceStatuses).toEqual(+ expect.arrayContaining([expect.stringMatching(/^(claimed|cancelled)$/), 'stale']),+ );+ if (resumeRace.status === 'claimed') {+ await expect(+ methods.cancelAgentEventActorSuspension({+ ...owner,+ suspensionId: cancellationSuspension.suspensionId,+ attempt: 0,+ invocationId: 'event-cancel',+ checkpoint: cancellationCheckpoint,+ claimedResumeAttemptId: 'resume-race',+ }),+ ).resolves.toEqual({ status: 'cancelled' });+ }+ await expect(methods.getAgentEventActorSnapshot(owner)).resolves.toMatchObject({+ suspension: { status: 'closed', outcome: 'cancelled' },+ });+ },+ );it('closes a resumed suspension when the actor-head commit is stale', async () => {const conversationId = uuidv4();@@ -4727,6 +4822,10 @@ describe('Conversation Operations', () => {},prunableCheckpoint: checkpoint('one'),});+ const pendingPruning = await Conversation.findOne({ conversationId })+ .select('+agentEventActorCleanup')+ .lean();+ expect(pendingPruning?.agentEventActorCleanup).toEqual([checkpoint('one')]);await expect(finishInvocation('three', checkpoint('three'))).resolves.toBe(true);await expect(methods.getAgentEventActorSnapshot({diff --git a/packages/data-schemas/src/methods/conversation.ts b/packages/data-schemas/src/methods/conversation.tsindex d7dc47c55c..5c526a2039 100644--- a/packages/data-schemas/src/methods/conversation.ts+++ b/packages/data-schemas/src/methods/conversation.ts@@ -50,6 +50,21 @@ import { isValidObjectIdString } from '~/utils/objectId';import { decrementTagCounts } from './conversationTag';import logger from '~/config/winston';+const ACTOR_CHECKPOINT_FIELDS = [+ 'agentEventActor',+ 'agentEventActorCleanup',+ 'agentEventActorReconciliations',+ 'agentEventActorSuspension',+] as const;++function stripActorCheckpointFields(record: Record<string, unknown>): void {+ for (const key of Object.keys(record)) {+ if (ACTOR_CHECKPOINT_FIELDS.some((field) => key === field || key.startsWith(`${field}.`))) {+ delete record[key];+ }+ }+}+const AGENT_EVENT_ACTOR_RECEIPT_RETENTION_MS = 90 * 24 * 60 * 60_000;const MAX_AGENT_EVENT_ACTOR_SUSPENSION_BYTES = 64 * 1_024;/** MeiliSearch's default `pagination.maxTotalHits` ceiling. */@@ -641,6 +656,15 @@ export function createConversationMethods(};}+ function readableActorSuspension(+ suspension: IConversation['agentEventActorSuspension'],+ ): IAgentEventActorSnapshot['suspension'] {+ if (suspension == null) return null;+ if (suspension.status === 'pending_owned') return { ...suspension, status: 'pending' };+ if (suspension.status === 'claimed_owned') return { ...suspension, status: 'claimed' };+ return suspension;+ }+/** Reads the private actor head and every fail-closed reconciliation marker. */async function getAgentEventActorSnapshot(input: {user: string;@@ -666,7 +690,7 @@ export function createConversationMethods(state: conversation.agentEventActor ?? null,reconciliations: conversation.agentEventActorReconciliations ?? [],legacyTurn: conversation.agentEventActorLegacyTurn ?? null,- suspension: conversation.agentEventActorSuspension ?? null,+ suspension: readableActorSuspension(conversation.agentEventActorSuspension),epoch: conversation.agentEventActorEpoch ?? 0,};}@@ -702,7 +726,7 @@ export function createConversationMethods(],}: {- 'agentEventActorSuspension.status': 'claimed',+ 'agentEventActorSuspension.status': { $in: ['claimed', 'claimed_owned'] },'agentEventActorSuspension.suspension.suspensionId': input.previous.suspensionId,'agentEventActorSuspension.suspension.attempt': input.previous.attempt,'agentEventActorSuspension.resumeAttemptId': input.previous.resumeAttemptId,@@ -729,7 +753,7 @@ export function createConversationMethods(handlingGenerationCreatedAt: input.handlingGenerationCreatedAt ?? input.jobCreatedAt,actionId: input.actionId,jobCreatedAt: input.jobCreatedAt,- status: 'pending' as const,+ status: 'pending_owned' as const,observedAt: new Date(),};const storeUpdate = {@@ -795,7 +819,7 @@ export function createConversationMethods(conversationId: input.conversationId,subagentThread: { $exists: true },agentEventBinding: { $exists: true },- 'agentEventActorSuspension.status': 'pending',+ 'agentEventActorSuspension.status': { $in: ['pending', 'pending_owned'] },'agentEventActorSuspension.suspension.suspensionId': input.suspensionId,'agentEventActorSuspension.suspension.attempt': input.attempt,'agentEventActorSuspension.actionId': input.actionId,@@ -805,7 +829,7 @@ export function createConversationMethods(},{$set: {- 'agentEventActorSuspension.status': 'claimed',+ 'agentEventActorSuspension.status': 'claimed_owned','agentEventActorSuspension.resumeAttemptId': input.resumeAttemptId,'agentEventActorSuspension.observedAt': new Date(),},@@ -837,7 +861,7 @@ export function createConversationMethods({user: input.user,conversationId: input.conversationId,- 'agentEventActorSuspension.status': 'claimed',+ 'agentEventActorSuspension.status': { $in: ['claimed', 'claimed_owned'] },'agentEventActorSuspension.suspension.suspensionId': input.suspensionId,'agentEventActorSuspension.suspension.attempt': input.attempt,'agentEventActorSuspension.resumeAttemptId': input.resumeAttemptId,@@ -904,9 +928,9 @@ export function createConversationMethods(const Conversation = mongoose.models.Conversation as Model<IConversation>;const suspensionOwner =input.claimedResumeAttemptId == null- ? { 'agentEventActorSuspension.status': 'pending' }+ ? { 'agentEventActorSuspension.status': { $in: ['pending', 'pending_owned'] } }: {- 'agentEventActorSuspension.status': 'claimed',+ 'agentEventActorSuspension.status': { $in: ['claimed', 'claimed_owned'] },'agentEventActorSuspension.resumeAttemptId': input.claimedResumeAttemptId,};const cancelled = await Conversation.findOneAndUpdate(@@ -1049,6 +1073,9 @@ export function createConversationMethods('agentEventActor.checkpoint.threadId': input.expected.checkpoint.threadId,'agentEventActor.checkpoint.checkpointId': input.expected.checkpoint.checkpointId,'agentEventActor.checkpoint.checkpointNs': input.expected.checkpoint.checkpointNs,+ 'agentEventActor.previousCheckpoint': input.expected.previousCheckpoint ?? {+ $exists: false,+ },...(input.expected.contextFingerprint == null? { 'agentEventActor.contextFingerprint': { $exists: false } }: {@@ -1084,7 +1111,7 @@ export function createConversationMethods(input.settlementAuthority == null? {}: {- 'agentEventActorSuspension.status': 'claimed',+ 'agentEventActorSuspension.status': { $in: ['claimed', 'claimed_owned'] },'agentEventActorSuspension.suspension.suspensionId':input.settlementAuthority.suspensionId,'agentEventActorSuspension.suspension.attempt': input.settlementAuthority.attempt,@@ -1138,6 +1165,11 @@ export function createConversationMethods('agentEventActorSuspension.observedAt': new Date(),}),},+ ...(input.expected?.previousCheckpoint == null+ ? {}+ : {+ $addToSet: { agentEventActorCleanup: input.expected.previousCheckpoint },+ }),$unset: { 'agentEventActorReconciliations.$.error': 1 },},{ new: false, timestamps: false },@@ -2141,6 +2173,7 @@ export function createConversationMethods(const appendMessageIds = metadata?.appendMessageIds;const update: Record<string, unknown> = { ...convo, user: userId };delete update.initial_agent_id;+ stripActorCheckpointFields(update);if (appendMessageIds == null) {update.messages = await getMessages({ conversationId, user: userId }, '_id');} else {@@ -2148,6 +2181,7 @@ export function createConversationMethods(}const unsetFields: Record<string, number> = { ...(metadata?.unsetFields ?? {}) };delete unsetFields.initial_agent_id;+ stripActorCheckpointFields(unsetFields);if (Object.prototype.hasOwnProperty.call(update, 'chatProjectId') && update.chatProjectId) {const chatProjectId = typeof update.chatProjectId === 'string' ? update.chatProjectId : '';@@ -2521,6 +2555,7 @@ export function createConversationMethods(const bulkOps = conversations.map((convo) => {const sanitized = { ...convo };delete sanitized.initial_agent_id;+ stripActorCheckpointFields(sanitized);if (typeof sanitized.user === 'string' && typeof sanitized.chatProjectId === 'string') {if (ownedProjects.has(`${sanitized.user}:${sanitized.chatProjectId}`)) {affectedProjectStats.set(`${sanitized.user}:${sanitized.chatProjectId}`, {@@ -2989,7 +3024,7 @@ export function createConversationMethods(),getMessages({ user, conversationId: filter.conversationId }, '_id', { limit: 1 }),]);- if (descendants.length === 0 && rootMessages.length === 0) {+ if (descendants.length === 0 && rootMessages.length === 0 && options?.allowEmpty !== true) {throw new Error('Conversation not found or already deleted.');}conversations = descendants;diff --git a/packages/data-schemas/src/methods/schedule.methods.spec.ts b/packages/data-schemas/src/methods/schedule.methods.spec.tsindex 665f362eda..8e46dc0db1 100644--- a/packages/data-schemas/src/methods/schedule.methods.spec.ts+++ b/packages/data-schemas/src/methods/schedule.methods.spec.ts@@ -463,6 +463,29 @@ describe('createScheduleWithSlot (atomic per-user cap)', () => {});describe('recordRunOutcome', () => {+ it('persists the paused namespace and preserves it when recovery has no namespace projection', async () => {+ const schedule = await Schedule.create(scheduleData());+ const row = await ScheduleRun.create(runData(schedule, { conversationId: 'paused-thread' }));+ const outcome = {+ scheduleId: schedule.id,+ scheduledFor: row.scheduledFor,+ status: 'requires_action' as const,+ conversationId: 'paused-thread',+ autoDisableAfterFailures: 3,+ };+ await methods.recordRunOutcome({ ...outcome, checkpointNamespace: 'owned-namespace' });+ await methods.recordRunOutcome(outcome);+ expect(await methods.getActiveRunsForSchedule(schedule.id)).toEqual([+ expect.objectContaining({+ status: 'requires_action',+ checkpointNamespace: 'owned-namespace',+ }),+ ]);+ expect(await ScheduleRun.findOne({ _id: row._id }).lean()).not.toHaveProperty(+ 'checkpointNamespace',+ );+ });+const scheduledFor = new Date('2026-07-20T12:00:00Z');it('success finalizes the run, increments runCount, and resets failure state', async () => {diff --git a/packages/data-schemas/src/methods/schedule.ts b/packages/data-schemas/src/methods/schedule.tsindex 487408662a..19499281a5 100644--- a/packages/data-schemas/src/methods/schedule.ts+++ b/packages/data-schemas/src/methods/schedule.ts@@ -120,6 +120,7 @@ export interface RecordRunOutcomeParams {'success' | 'error' | 'requires_action' | 'interrupted' | 'skipped_balance' | 'skipped_overlap'>;conversationId?: string;+ checkpointNamespace?: string;/** Erase the run row's RESERVED conversationId in the same terminal write: a* pre-start abort reserved an id but never created the conversation, and any* recovery replay that reads the row would otherwise project a dead link. */@@ -1414,6 +1415,9 @@ export function createScheduleMethods(mongoose: typeof import('mongoose')): Sche$set: {status: 'requires_action',...(params.conversationId ? { conversationId: params.conversationId } : {}),+ ...(params.checkpointNamespace != null+ ? { checkpointNamespace: params.checkpointNamespace }+ : {}),},// Leaving `started` frees the global capacity slot; the resume claims a// fresh one from the allocator rather than re-adopting a possibly-taken slot.@@ -1756,6 +1760,7 @@ export function createScheduleMethods(mongoose: typeof import('mongoose')): Scheasync function getActiveRunsForSchedule(scheduleId: string): Promise<IScheduleRun[]> {return ScheduleRun().find({ scheduleId, status: { $in: ACTIVE_RUN_STATUSES } })+ .select('+checkpointNamespace').lean<IScheduleRun[]>();}diff --git a/packages/data-schemas/src/schema/convo.ts b/packages/data-schemas/src/schema/convo.tsindex 0b291973c4..78ff9e6cea 100644--- a/packages/data-schemas/src/schema/convo.ts+++ b/packages/data-schemas/src/schema/convo.ts@@ -236,6 +236,18 @@ const convoSchema: Schema<IConversation> = new Schema(/** Fail-closed invocation proof. Active records block later turns through checkpoint,* history, and outcome settlement; settled receipts no longer block new IDs but keep* delayed owners from reacquiring an invocation that already applied its action. */+ agentEventActorCleanup: {+ type: [+ {+ threadId: { type: String, required: true },+ checkpointId: { type: String, required: true },+ checkpointNs: { type: String, required: true },+ _id: false,+ },+ ],+ default: undefined,+ select: false,+ },agentEventActorReconciliations: {type: [{@@ -324,7 +336,11 @@ const convoSchema: Schema<IConversation> = new Schema(handlingGenerationCreatedAt: { type: Number, min: 0, default: undefined },actionId: { type: String, required: true },jobCreatedAt: { type: Number, required: true },- status: { type: String, enum: ['pending', 'claimed', 'closed'], required: true },+ status: {+ type: String,+ enum: ['pending', 'claimed', 'pending_owned', 'claimed_owned', 'closed'],+ required: true,+ },resumeAttemptId: { type: String, default: undefined },outcome: {type: String,diff --git a/packages/data-schemas/src/schema/scheduleRun.ts b/packages/data-schemas/src/schema/scheduleRun.tsindex 4a1147db34..18ad668e7f 100644--- a/packages/data-schemas/src/schema/scheduleRun.ts+++ b/packages/data-schemas/src/schema/scheduleRun.ts@@ -29,6 +29,10 @@ const scheduleRunSchema: Schema<IScheduleRunDocument> = new Schema(conversationId: {type: String,},+ checkpointNamespace: {+ type: String,+ select: false,+ },/** Deterministic durable-trigger delivery key for this occurrence, stamped at* reservation before enqueue so reconciliation can read the delivery's live/dead* state rather than orphan-settling a deferred or dead-lettered run. */diff --git a/packages/data-schemas/src/types/convo.ts b/packages/data-schemas/src/types/convo.tsindex f149ce6b97..80b1199cb4 100644--- a/packages/data-schemas/src/types/convo.ts+++ b/packages/data-schemas/src/types/convo.ts@@ -188,7 +188,8 @@ export interface IAgentEventActorSuspension {handlingGenerationCreatedAt?: number;actionId: string;jobCreatedAt: number;- status: 'pending' | 'claimed' | 'closed';+ /** Owned states fence legacy replicas; snapshot readers expose pending/claimed. */+ status: 'pending' | 'claimed' | 'pending_owned' | 'claimed_owned' | 'closed';resumeAttemptId?: string;outcome?: 'committed' | 'stale' | 'settled' | 'cancelled';closedAt?: Date;@@ -274,6 +275,8 @@ export interface IConversation extends Document {agentEventBinding?: IAgentEventBinding;/** Internal event-actor checkpoint head. Excluded from ordinary conversation reads. */agentEventActor?: IAgentEventActorState;+ /** Prune work persisted atomically before the actor rotates its predecessor. */+ agentEventActorCleanup?: IAgentEventActorCheckpoint[];/** Private invocation proof: active lifecycle fences plus settled same-ID receipts. */agentEventActorReconciliations?: IAgentEventActorReconciliation[];/** Private invalidation epoch; see {@link IAgentEventActorSnapshot.epoch}. */diff --git a/packages/data-schemas/src/types/schedule.ts b/packages/data-schemas/src/types/schedule.tsindex 0c561e6b70..69c06a6173 100644--- a/packages/data-schemas/src/types/schedule.ts+++ b/packages/data-schemas/src/types/schedule.ts@@ -84,6 +84,7 @@ export interface IScheduleRun {scheduledFor: Date;firedAt?: Date;conversationId?: string;+ checkpointNamespace?: string;status: ScheduleRunStatus;error?: string;/** Deterministic durable-trigger delivery key for this occurrence, stamped at