Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

βœ… test(database): cover concurrency, lock, constraint and library guards with real tests (#21889)

Arvin Xu18cbc41b468a
diff --git a/packages/database/src/models/__tests__/_proxyTestDB.ts b/packages/database/src/models/__tests__/_proxyTestDB.ts
index 7d034eecc24..181f08c5dcf 100644
--- a/packages/database/src/models/__tests__/_proxyTestDB.ts
+++ b/packages/database/src/models/__tests__/_proxyTestDB.ts
@@ -1,5 +1,5 @@
import { drizzle as drizzleProxy } from 'drizzle-orm/pg-proxy';
-import { Pool } from 'pg';
+import { Client, Pool } from 'pg';
import * as schema from '../../schemas';
import type { LobeChatDatabase } from '../../type';
@@ -18,9 +18,13 @@ type RowRewriter = (query: string, result: ArrayQueryResult) => unknown[][];
* row mode differently: a query-config object versus a third options argument.
*/
const queryArrayRows = (db: LobeChatDatabase, text: string, values: unknown[]) => {
- const client = (db as unknown as { $client: unknown }).$client;
+ // A root database exposes its driver as `$client`; a transaction only through its session,
+ // which holds the checked-out node-postgres client or PGlite's transaction handle.
+ const client =
+ (db as unknown as { $client?: unknown }).$client ??
+ (db as unknown as { session: { client: unknown } }).session.client;
- return client instanceof Pool
+ return client instanceof Pool || client instanceof Client
? (client.query({ rowMode: 'array', text, values }) as Promise<ArrayQueryResult>)
: (client as { query: (...args: unknown[]) => Promise<ArrayQueryResult> }).query(text, values, {
rowMode: 'array',
@@ -31,12 +35,32 @@ const queryArrayRows = (db: LobeChatDatabase, text: string, values: unknown[]) =
* A database seam at the driver boundary: every query still runs against the real test
* database, but the rows come back through the driver's default type parsers (so timestamps
* arrive as `Date`) and can optionally be rewritten before drizzle maps them.
+ *
+ * pg-proxy has no transactions of its own, so `transaction()` opens one on the real driver and
+ * hands the callback a proxy bound to it: every statement inside still shares that connection,
+ * and nested calls become savepoints.
*/
-export const createProxyTestDB = (db: LobeChatDatabase, rewrite?: RowRewriter) =>
- drizzleProxy(
+export const createProxyTestDB = (
+ db: LobeChatDatabase,
+ rewrite?: RowRewriter,
+): LobeChatDatabase => {
+ const proxy = drizzleProxy(
async (query, params) => {
const result = await queryArrayRows(db, query, params);
return { rows: rewrite ? rewrite(query, result) : result.rows };
},
{ schema },
) as unknown as LobeChatDatabase;
+
+ return Object.assign(proxy, {
+ transaction: ((callback, config) =>
+ db.transaction(
+ (tx) => callback(createProxyTestDB(tx as unknown as LobeChatDatabase, rewrite) as any),
+ config,
+ )) as LobeChatDatabase['transaction'],
+ });
+};
+
+/** Index of a result column by its SQL name, for rewriters that patch one cell. */
+export const columnIndex = (result: ArrayQueryResult, name: string) =>
+ result.fields.findIndex((field) => field.name === name);
diff --git a/packages/database/src/models/agentIntervention/customExecution.guards.test.ts b/packages/database/src/models/agentIntervention/customExecution.guards.test.ts
new file mode 100644
index 00000000000..05c06897a48
--- /dev/null
+++ b/packages/database/src/models/agentIntervention/customExecution.guards.test.ts
@@ -0,0 +1,235 @@
+// @vitest-environment node
+import { randomUUID } from 'node:crypto';
+
+import { eq, inArray } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import {
+ agentInterventionResolutions,
+ agentInterventions,
+ agentOperations,
+ users,
+ workspaces,
+} from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { type ArrayQueryResult, columnIndex, createProxyTestDB } from '../__tests__/_proxyTestDB';
+import { AgentInterventionModel } from './index';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const ownerId = 'ce-guards-owner';
+const actorId = 'ce-guards-actor';
+const workspaceId = 'ce-guards-workspace';
+const operationId = 'ce-guards-operation';
+
+const model = new AgentInterventionModel(serverDB, ownerId, workspaceId);
+
+const inputHash = 'b'.repeat(64);
+const leaseDurationMs = 60_000;
+const now = new Date('2026-08-26T10:00:00.000Z');
+
+let sequence = 0;
+const nextHash = () => (++sequence).toString(16).padStart(64, 'a');
+
+/** A resolved `submit_custom` intervention whose private execution ledger starts out pending. */
+const createCustomResolution = async () => {
+ const [row] = await model.createBatch({
+ activityKey: `ce-guards-activity-${++sequence}`,
+ batchId: `ce-guards-batch-${sequence}`,
+ deadline: new Date(Date.now() + 10 * 60_000),
+ items: [
+ {
+ allowedActions: ['submit_custom'],
+ interactionKind: 'custom',
+ provider: 'claude-code',
+ requestRevisionHash: nextHash(),
+ reviewContext: { summary: 'Install it', title: 'Agent needs your input' },
+ reviewTokenHash: nextHash(),
+ sanitizedRequest: {
+ apiName: 'installMarketplaceItem',
+ fields: [{ id: 'confirm', label: 'Install', required: true, type: 'boolean' }],
+ },
+ surface: 'form',
+ toolCallId: `ce-guards-tool-${sequence}`,
+ },
+ ],
+ operationId,
+ provider: 'claude-code',
+ source: 'heterogeneous',
+ stepIndex: 0,
+ systemActionEligibility: 'review_only',
+ });
+ const claimed = await model.claimBatch({
+ action: {
+ expectedRevisionHash: row.requestRevisionHash,
+ result: { confirm: true },
+ type: 'submit_custom',
+ },
+ actorId,
+ batchId: row.batchId,
+ expectedItemCount: 1,
+ expectedRequestRevisionHashes: { [row.id]: row.requestRevisionHash },
+ expectedVersions: { [row.id]: row.version },
+ operationId: row.operationId,
+ resolutionRequestId: randomUUID(),
+ scope: 'single',
+ selectedInterventionIds: [row.id],
+ });
+ if (claimed.outcome !== 'applied') throw new Error('custom resolution claim failed');
+ return claimed.resolution;
+};
+
+const readLedger = async (resolutionRequestId: string) => {
+ const [row] = await serverDB
+ .select()
+ .from(agentInterventionResolutions)
+ .where(eq(agentInterventionResolutions.resolutionRequestId, resolutionRequestId));
+ return row;
+};
+
+/**
+ * A model whose locked read of the resolution row returns `patch` applied to the real row β€”
+ * the shape a relaxed CHECK constraint or a write between the read and the UPDATE would leave.
+ * Every statement, the UPDATE included, still runs against the real row; `writes` records the
+ * UPDATEs issued so a test can tell a guard after the write from an earlier return.
+ */
+const modelSeeing = (patch: Record<string, unknown>) => {
+ const writes: string[] = [];
+ const seeing = new AgentInterventionModel(
+ createProxyTestDB(serverDB, (query, result: ArrayQueryResult) => {
+ if (query.startsWith('update "agent_intervention_resolutions"')) writes.push(query);
+ if (!query.includes('from "agent_intervention_resolutions"') || !query.includes('for update'))
+ return result.rows;
+ return result.rows.map((row) => {
+ const next = [...row];
+ for (const [name, value] of Object.entries(patch)) next[columnIndex(result, name)] = value;
+ return next;
+ });
+ }),
+ ownerId,
+ workspaceId,
+ );
+ return { model: seeing, writes };
+};
+
+beforeEach(async () => {
+ await serverDB.insert(users).values([{ id: ownerId }, { id: actorId }]);
+ await serverDB.insert(workspaces).values({
+ id: workspaceId,
+ name: 'Custom execution guards',
+ primaryOwnerId: ownerId,
+ slug: 'ce-guards-workspace',
+ });
+ await serverDB
+ .insert(agentOperations)
+ .values({ id: operationId, status: 'running', userId: ownerId, workspaceId });
+});
+
+afterEach(async () => {
+ await serverDB.delete(agentInterventions).where(eq(agentInterventions.userId, ownerId));
+ await serverDB
+ .delete(agentInterventionResolutions)
+ .where(eq(agentInterventionResolutions.userId, ownerId));
+ await serverDB.delete(agentOperations).where(eq(agentOperations.id, operationId));
+ await serverDB.delete(workspaces).where(eq(workspaces.id, workspaceId));
+ await serverDB.delete(users).where(inArray(users.id, [ownerId, actorId]));
+});
+
+describe('claimCustomExecution guards', () => {
+ it('refuses an executing row that carries no lease token instead of reporting a live lease', async () => {
+ const resolution = await createCustomResolution();
+ const params = {
+ inputHash,
+ leaseDurationMs,
+ resolutionRequestId: resolution.resolutionRequestId,
+ };
+ expect(await model.claimCustomExecution(params, now)).toMatchObject({ outcome: 'applied' });
+ const before = await readLedger(resolution.resolutionRequestId);
+
+ // Without the token the lease cannot be fenced; the same read with the token is `in_progress`.
+ const seeing = modelSeeing({ custom_execution_lease_token: null });
+ const result = await seeing.model.claimCustomExecution(params, new Date(now.getTime() + 1000));
+
+ expect(result).toEqual({ outcome: 'conflict' });
+ expect(seeing.writes).toEqual([]);
+ expect(await readLedger(resolution.resolutionRequestId)).toEqual(before);
+ });
+
+ it('refuses a ledger state the CHECK constraint does not know instead of claiming it', async () => {
+ const resolution = await createCustomResolution();
+
+ const seeing = modelSeeing({ custom_execution_state: 'abandoned' });
+ const result = await seeing.model.claimCustomExecution(
+ { inputHash, leaseDurationMs, resolutionRequestId: resolution.resolutionRequestId },
+ now,
+ );
+
+ expect(result).toEqual({ outcome: 'conflict' });
+ // Refused before the claim UPDATE, which would otherwise mint a lease for an unknown state.
+ expect(seeing.writes).toEqual([]);
+ expect(await readLedger(resolution.resolutionRequestId)).toMatchObject({
+ customExecutionAttempt: 0,
+ customExecutionLeaseToken: null,
+ customExecutionState: 'pending',
+ });
+ });
+
+ it('reports a conflict, never a lease, when the resolving row is gone by the time of the UPDATE', async () => {
+ const resolution = await createCustomResolution();
+ expect((await model.rollbackResolution(resolution.resolutionRequestId)).outcome).toBe(
+ 'applied',
+ );
+
+ // The locked read still sees `resolving`; the UPDATE's own status filter sees the rollback.
+ const seeing = modelSeeing({ status: 'resolving' });
+ const result = await seeing.model.claimCustomExecution(
+ { inputHash, leaseDurationMs, resolutionRequestId: resolution.resolutionRequestId },
+ now,
+ );
+
+ expect(result).toEqual({ outcome: 'conflict' });
+ // The claim UPDATE was issued and matched nothing; the conflict comes from its empty result.
+ expect(seeing.writes).toHaveLength(1);
+ expect(result).not.toHaveProperty('leaseToken');
+ expect(await readLedger(resolution.resolutionRequestId)).toMatchObject({
+ customExecutionAttempt: 0,
+ customExecutionState: 'pending',
+ status: 'rolled_back',
+ });
+ });
+});
+
+describe('completeCustomExecution guards', () => {
+ it('reports a conflict when the lease was taken over between the locked read and the UPDATE', async () => {
+ const resolution = await createCustomResolution();
+ const claimed = await model.claimCustomExecution(
+ { inputHash, leaseDurationMs, resolutionRequestId: resolution.resolutionRequestId },
+ now,
+ );
+ if (claimed.outcome !== 'applied') throw new Error('execution lease claim failed');
+ const takeover = randomUUID();
+ await serverDB
+ .update(agentInterventionResolutions)
+ .set({ customExecutionLeaseToken: takeover })
+ .where(eq(agentInterventionResolutions.id, resolution.id));
+
+ // The locked read still shows the stale token; the UPDATE filters on the current one.
+ const seeing = modelSeeing({ custom_execution_lease_token: claimed.leaseToken });
+ const result = await seeing.model.completeCustomExecution({
+ inputHash,
+ leaseToken: claimed.leaseToken,
+ resolutionRequestId: resolution.resolutionRequestId,
+ result: { content: 'Installed', pluginState: { agentIds: ['agent-a'] } },
+ });
+
+ expect(result).toEqual({ outcome: 'conflict' });
+ // The completion UPDATE was issued and matched nothing; the conflict comes from its empty result.
+ expect(seeing.writes).toHaveLength(1);
+ expect(await readLedger(resolution.resolutionRequestId)).toMatchObject({
+ customExecutionLeaseToken: takeover,
+ customExecutionResult: null,
+ customExecutionState: 'executing',
+ });
+ });
+});
diff --git a/packages/database/src/models/agentIntervention/customExecution.ts b/packages/database/src/models/agentIntervention/customExecution.ts
index 82b97e227dd..913948319d3 100644
--- a/packages/database/src/models/agentIntervention/customExecution.ts
+++ b/packages/database/src/models/agentIntervention/customExecution.ts
@@ -71,7 +71,6 @@ export const claimCustomExecution = async (
}
if (resolution.customExecutionState === 'executing') {
- /* v8 ignore if -- unreachable: the custom_execution_state CHECK requires an executing row to carry a lease token, a lease expiry and an attempt > 0 */
if (
!resolution.customExecutionLeaseToken ||
!resolution.customExecutionLeaseExpiresAt ||
@@ -86,14 +85,12 @@ export const claimCustomExecution = async (
outcome: 'in_progress',
};
}
- /* v8 ignore start -- unreachable: the custom_execution_state CHECK only admits NULL, pending, executing and completed, and executing/completed are handled above */
} else if (
resolution.customExecutionState !== 'pending' &&
resolution.customExecutionState !== null
) {
return { outcome: 'conflict' };
}
- /* v8 ignore stop */
const attempt = (resolution.customExecutionAttempt ?? 0) + 1;
const leaseExpiresAt = new Date(now.getTime() + params.leaseDurationMs);
@@ -120,9 +117,7 @@ export const claimCustomExecution = async (
.returning({ id: agentInterventionResolutions.id });
return claimed
? { attempt, leaseExpiresAt, leaseToken, outcome: 'applied' }
- : /* v8 ignore next -- unreachable: the row was locked FOR UPDATE in this transaction with the same ownership and was just checked to be resolving, so the UPDATE by its id always returns it */ {
- outcome: 'conflict',
- };
+ : { outcome: 'conflict' };
});
};
@@ -194,8 +189,6 @@ export const completeCustomExecution = async (
.returning({ result: agentInterventionResolutions.customExecutionResult });
return completed?.result
? { outcome: 'completed', result: completed.result }
- : /* v8 ignore next -- unreachable: the row was locked FOR UPDATE in this transaction and just matched every filter of this UPDATE, which writes the validated non-null result */ {
- outcome: 'conflict',
- };
+ : { outcome: 'conflict' };
});
};
diff --git a/packages/database/src/models/agentShare.guards.test.ts b/packages/database/src/models/agentShare.guards.test.ts
new file mode 100644
index 00000000000..0ff8970035c
--- /dev/null
+++ b/packages/database/src/models/agentShare.guards.test.ts
@@ -0,0 +1,48 @@
+// @vitest-environment node
+import { eq, inArray } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../core/getTestDB';
+import { agents, agentShares, users } from '../schemas';
+import type { LobeChatDatabase } from '../type';
+import { createProxyTestDB } from './__tests__/_proxyTestDB';
+import { AgentShareModel } from './agentShare';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'agent-share-guards-user';
+const agentId = 'agent-share-guards-agent';
+
+beforeEach(async () => {
+ await serverDB.insert(users).values({ id: userId });
+ await serverDB.insert(agents).values({ id: agentId, slug: 'guarded-agent', userId });
+});
+
+afterEach(async () => {
+ await serverDB.delete(users).where(inArray(users.id, [userId]));
+});
+
+describe('AgentShareModel.create slug seed guard', () => {
+ it('keeps the freshly inserted share when the slug-seed UPDATE returns no row', async () => {
+ // The seed UPDATE reports no row back, the answer it would give if the row it just
+ // inserted had already gone; every other statement, the INSERT included, is untouched.
+ const model = new AgentShareModel(
+ createProxyTestDB(serverDB, (query, result) =>
+ query.startsWith('update "agent_shares" set "share_config"') ? [] : result.rows,
+ ),
+ userId,
+ );
+
+ const share = await model.create(agentId);
+
+ const [stored] = await serverDB
+ .select()
+ .from(agentShares)
+ .where(eq(agentShares.agentId, agentId));
+ // The seed UPDATE really ran (the stored row carries the slug); only its returned row was lost.
+ expect(stored.shareConfig?.slug).toBe('guarded-agent');
+ // Creation still succeeds with the inserted row, just without the seeded slug.
+ expect(share).toMatchObject({ agentId, id: stored.id, visibility: 'private' });
+ expect(share.shareConfig.slug).toBeUndefined();
+ });
+});
diff --git a/packages/database/src/models/agentShare.ts b/packages/database/src/models/agentShare.ts
index a9e7b0e8593..530c941303f 100644
--- a/packages/database/src/models/agentShare.ts
+++ b/packages/database/src/models/agentShare.ts
@@ -234,7 +234,6 @@ export class AgentShareModel {
.where(eq(agentShares.id, share.id))
.returning();
- /* v8 ignore next -- unreachable: `share` was inserted by this same open transaction (uncommitted, invisible to and undeletable by any other session), so the UPDATE by its id always returns the row */
return updated ?? share;
};
diff --git a/packages/database/src/models/favorite.guards.test.ts b/packages/database/src/models/favorite.guards.test.ts
new file mode 100644
index 00000000000..4989dabaaa1
--- /dev/null
+++ b/packages/database/src/models/favorite.guards.test.ts
@@ -0,0 +1,40 @@
+// @vitest-environment node
+import { inArray } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../core/getTestDB';
+import { users } from '../schemas';
+import type { LobeChatDatabase } from '../type';
+import { createProxyTestDB } from './__tests__/_proxyTestDB';
+import { FavoriteModel } from './favorite';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'favorite-guards-user';
+
+beforeEach(async () => {
+ await serverDB.insert(users).values({ id: userId });
+});
+
+afterEach(async () => {
+ await serverDB.delete(users).where(inArray(users.id, [userId]));
+});
+
+describe('FavoriteModel.reorder empty-sidebar guard', () => {
+ it('writes nothing when the sidebar has no favorites to order', async () => {
+ const statements: string[] = [];
+ const model = new FavoriteModel(
+ createProxyTestDB(serverDB, (query, result) => {
+ statements.push(query);
+ return result.rows;
+ }),
+ userId,
+ );
+
+ // Ids from another sidebar are ignored, which leaves nothing to position.
+ await expect(model.reorder(['fav-from-elsewhere'])).resolves.toBeUndefined();
+
+ expect(statements.filter((query) => query.startsWith('update'))).toEqual([]);
+ expect(await new FavoriteModel(serverDB, userId).query()).toEqual([]);
+ });
+});
diff --git a/packages/database/src/models/goalExploration.guards.test.ts b/packages/database/src/models/goalExploration.guards.test.ts
new file mode 100644
index 00000000000..41ce5992d1f
--- /dev/null
+++ b/packages/database/src/models/goalExploration.guards.test.ts
@@ -0,0 +1,155 @@
+// @vitest-environment node
+import { inArray } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { getTestDB } from '../core/getTestDB';
+import { users } from '../schemas';
+import type { LobeChatDatabase } from '../type';
+import { GoalModel } from './goal';
+import { GoalExplorationModel, goalExplorationSnapshot } from './goalExploration';
+import { GoalGraphModel } from './goalGraph';
+
+const db: LobeChatDatabase = await getTestDB();
+
+const userId = 'exploration-guards-owner';
+const graphModel = new GoalGraphModel(db, userId);
+const model = new GoalExplorationModel(db, userId);
+
+type NodeKind = Parameters<GoalGraphModel['createNode']>[1]['kind'];
+
+/**
+ * Makes the graph model each `apply` builds on its transaction answer `createNode` with
+ * `undefined` β€” its "this goal is no longer yours" result β€” for nodes of `lostKind`, the
+ * answer a goal that left the caller's ownership after `lock()` would produce. Other kinds
+ * are created for real on the same transaction.
+ */
+const loseCreateNodeFor = (lostKind: NodeKind) => {
+ const buildGraph = (GoalExplorationModel.prototype as any).graph as (
+ tx: LobeChatDatabase,
+ ) => GoalGraphModel;
+ vi.spyOn(GoalExplorationModel.prototype as any, 'graph').mockImplementation(function (
+ this: GoalExplorationModel,
+ tx: unknown,
+ ) {
+ const graph = buildGraph.call(this, tx as LobeChatDatabase);
+ const createNode = graph.createNode;
+ vi.spyOn(graph, 'createNode').mockImplementation(async (goalId, input) =>
+ input.kind === lostKind ? undefined : createNode(goalId, input),
+ );
+ return graph;
+ });
+};
+
+async function seed() {
+ const goal = await new GoalModel(db, userId).create({
+ config: { exploration: { instruction: 'Compare results', maxExperiments: 3 } },
+ status: 'running',
+ subjectType: 'standalone',
+ title: 'Explore candidates',
+ });
+ await graphModel.createNode(goal.id, { kind: 'problem', title: 'Find a candidate' });
+ const parent = await graphModel.createNode(goal.id, {
+ kind: 'task',
+ status: 'resolved',
+ title: 'Baseline',
+ });
+ return { goalId: goal.id, parent: parent! };
+}
+
+async function seedExperiment(goalId: string) {
+ const graph = (await graphModel.getGraph(goalId))!;
+ const experiment = await graphModel.createNode(goalId, {
+ kind: 'experiment',
+ questionId: graph.nodes.find((node) => node.kind === 'problem')!.id,
+ title: 'Three arms',
+ });
+ await graphModel.createNode(goalId, {
+ kind: 'task',
+ scopeId: experiment!.id,
+ status: 'resolved',
+ title: 'Three arms run 1',
+ });
+ return experiment!.id;
+}
+
+async function claim(goalId: string) {
+ return (await model.claim(goalId, goalExplorationSnapshot((await graphModel.getGraph(goalId))!)))!
+ .token;
+}
+
+const nodeIds = async (goalId: string) =>
+ (await graphModel.getGraph(goalId))!.nodes.map((node) => node.id).sort();
+
+const expand = (parentNodeId: string) => ({
+ action: 'expand' as const,
+ instruction: 'Change the baseline using its evidence',
+ parentNodeId,
+ reason: 'The first result is promising',
+ title: 'Alternative',
+});
+
+beforeEach(async () => {
+ await db.insert(users).values({ id: userId });
+});
+
+afterEach(async () => {
+ vi.restoreAllMocks();
+ await db.delete(users).where(inArray(users.id, [userId]));
+});
+
+describe('GoalExplorationModel.apply createNode guards', () => {
+ it('aborts a revision whose corrected protocol could not be persisted', async () => {
+ const { goalId } = await seed();
+ const experimentId = await seedExperiment(goalId);
+ const token = await claim(goalId);
+ const before = await nodeIds(goalId);
+ loseCreateNodeFor('task');
+
+ await expect(
+ model.apply(goalId, token, {
+ action: 'revise',
+ instruction: 'Emit a calibrated score, then report AUC',
+ parentNodeId: experimentId,
+ reason: 'The arms measured a hard verdict',
+ title: '',
+ }),
+ ).rejects.toThrow('Could not persist the revised protocol');
+
+ vi.restoreAllMocks();
+ const graph = (await graphModel.getGraph(goalId))!;
+ expect(graph.nodes.map((node) => node.id).sort()).toEqual(before);
+ expect(graph.edges.filter((edge) => edge.kind === 'revises')).toEqual([]);
+ });
+
+ it('aborts an expansion whose experiment container could not be created', async () => {
+ const { goalId, parent } = await seed();
+ const token = await claim(goalId);
+ const before = await nodeIds(goalId);
+ loseCreateNodeFor('experiment');
+
+ await expect(model.apply(goalId, token, expand(parent.id))).rejects.toThrow(
+ 'Could not create experiment',
+ );
+
+ vi.restoreAllMocks();
+ expect(await nodeIds(goalId)).toEqual(before);
+ });
+
+ it('rolls back the new experiment when its first protocol could not be persisted', async () => {
+ const { goalId, parent } = await seed();
+ const token = await claim(goalId);
+ const before = await nodeIds(goalId);
+ loseCreateNodeFor('task');
+
+ await expect(model.apply(goalId, token, expand(parent.id))).rejects.toThrow(
+ 'Could not persist exploration node',
+ );
+
+ vi.restoreAllMocks();
+ // The experiment was inserted on the same transaction; the throw takes it back out.
+ const graph = (await graphModel.getGraph(goalId))!;
+ expect(graph.nodes.map((node) => node.id).sort()).toEqual(before);
+ expect(graph.nodes.filter((node) => node.kind === 'experiment')).toEqual([]);
+ expect(graph.edges.filter((edge) => edge.kind === 'derived_from')).toEqual([]);
+ });
+});
diff --git a/packages/database/src/models/goalExploration.ts b/packages/database/src/models/goalExploration.ts
index 70814c59d15..820c9f62c42 100644
--- a/packages/database/src/models/goalExploration.ts
+++ b/packages/database/src/models/goalExploration.ts
@@ -210,7 +210,6 @@ export class GoalExplorationModel {
scopeId: container,
title: decision.title.trim() || target.title,
});
- /* v8 ignore next -- unreachable: this.lock() already holds the goal row FOR UPDATE in this transaction under the same ownership predicate createNode re-checks, so createNode never returns undefined */
if (!node) throw new Error('Could not persist the revised protocol');
await graphModel.createEdge(goalId, node.id, target.id, 'revises');
const members = experimentScope(graph, container);
@@ -263,7 +262,6 @@ export class GoalExplorationModel {
questionId,
scopeId: experimentOwner(graph, questionId),
});
- /* v8 ignore next -- unreachable: this.lock() already holds the goal row FOR UPDATE in this transaction under the same ownership predicate createNode re-checks, so createNode never returns undefined */
if (!experiment) throw new Error('Could not create experiment');
const node = await graphModel.createNode(goalId, {
scopeId: experiment.id,
@@ -271,7 +269,6 @@ export class GoalExplorationModel {
title: decision.title,
description: decision.instruction,
});
- /* v8 ignore next -- unreachable: this.lock() already holds the goal row FOR UPDATE in this transaction under the same ownership predicate createNode re-checks, so createNode never returns undefined */
if (!node) throw new Error('Could not persist exploration node');
await graphModel.createEdge(goalId, experiment.id, parent.id, 'derived_from');
const parentMembers = experimentScope(graph, parent.id);
diff --git a/packages/database/src/models/goalGraph.guards.test.ts b/packages/database/src/models/goalGraph.guards.test.ts
new file mode 100644
index 00000000000..1d50556b2d7
--- /dev/null
+++ b/packages/database/src/models/goalGraph.guards.test.ts
@@ -0,0 +1,130 @@
+// @vitest-environment node
+import { and, eq, inArray } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../core/getTestDB';
+import { goalEvents, goalNodeDecisions, goalNodes, users } from '../schemas';
+import type { LobeChatDatabase } from '../type';
+import { createProxyTestDB } from './__tests__/_proxyTestDB';
+import { GoalModel } from './goal';
+import { GoalGraphModel } from './goalGraph';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'goal-graph-guards-user';
+const graphModel = new GoalGraphModel(serverDB, userId);
+
+const options = [
+ { id: 'ship', label: 'Ship it' },
+ { id: 'hold', label: 'Hold' },
+];
+
+const pendingDecision = async () => {
+ const goal = await new GoalModel(serverDB, userId).create({
+ subjectType: 'standalone',
+ title: 'Decision guards',
+ });
+ const node = await graphModel.createNode(goal.id, { kind: 'decision', title: 'Ship?' });
+ const decision = await graphModel.createDecision(goal.id, node!.id, {
+ authority: 'user',
+ options,
+ question: 'Ship it?',
+ });
+ return { decision: decision!, goal, node: node! };
+};
+
+/**
+ * A graph model whose "is this decision still pending" read keeps returning `decisionId`
+ * after the row was settled β€” the view a writer that skipped the goal lock would leave
+ * between that read and the guarded UPDATE. The UPDATE itself runs against the real row;
+ * `writes` records it, so a test can tell the guard after it from an earlier return.
+ */
+const graphSeeingPending = (decisionId: string) => {
+ const writes: string[] = [];
+ const graph = new GoalGraphModel(
+ createProxyTestDB(serverDB, (query, result) => {
+ if (query.startsWith('update "goal_node_decisions"')) writes.push(query);
+ return query.startsWith('select "goal_node_decisions"."id" from "goal_node_decisions"')
+ ? [[decisionId]]
+ : result.rows;
+ }),
+ userId,
+ );
+ return { graph, writes };
+};
+
+const decisionEvents = async (goalId: string, decisionId: string) =>
+ serverDB
+ .select({ eventType: goalEvents.eventType })
+ .from(goalEvents)
+ .where(and(eq(goalEvents.goalId, goalId), eq(goalEvents.entityId, decisionId)));
+
+beforeEach(async () => {
+ await serverDB.insert(users).values({ id: userId });
+});
+
+afterEach(async () => {
+ await serverDB.delete(users).where(inArray(users.id, [userId]));
+});
+
+describe('GoalGraphModel decision guards', () => {
+ it('resolveDecision returns undefined and leaves the node alone when the decision settled under it', async () => {
+ const { decision, goal, node } = await pendingDecision();
+ // Settled by a writer that did not take the goal lock first.
+ await serverDB
+ .update(goalNodeDecisions)
+ .set({ resolvedAt: new Date(), resolvedOptionId: 'hold', status: 'resolved' })
+ .where(eq(goalNodeDecisions.id, decision.id));
+
+ const seeing = graphSeeingPending(decision.id);
+ const result = await seeing.graph.resolveDecision(goal.id, decision.id, 'ship', 'late answer');
+
+ expect(result).toBeUndefined();
+ // The guarded UPDATE was issued and matched nothing.
+ expect(seeing.writes).toHaveLength(1);
+ const [stored] = await serverDB
+ .select()
+ .from(goalNodeDecisions)
+ .where(eq(goalNodeDecisions.id, decision.id));
+ expect(stored).toMatchObject({
+ resolution: null,
+ resolvedOptionId: 'hold',
+ status: 'resolved',
+ });
+ const [storedNode] = await serverDB.select().from(goalNodes).where(eq(goalNodes.id, node.id));
+ expect(storedNode.status).toBe(node.status);
+ expect(storedNode.resolvedAt).toBeNull();
+ expect((await decisionEvents(goal.id, decision.id)).map((e) => e.eventType)).toEqual([
+ 'created',
+ ]);
+ });
+
+ it('cancelDecision returns undefined and does not retire the node when the decision settled under it', async () => {
+ const { decision, goal, node } = await pendingDecision();
+ await serverDB
+ .update(goalNodeDecisions)
+ .set({ resolvedAt: new Date(), resolvedOptionId: 'ship', status: 'resolved' })
+ .where(eq(goalNodeDecisions.id, decision.id));
+
+ const seeing = graphSeeingPending(decision.id);
+ const result = await seeing.graph.cancelDecision(goal.id, decision.id, 'question went away');
+
+ expect(result).toBeUndefined();
+ // The guarded UPDATE was issued and matched nothing.
+ expect(seeing.writes).toHaveLength(1);
+ const [stored] = await serverDB
+ .select()
+ .from(goalNodeDecisions)
+ .where(eq(goalNodeDecisions.id, decision.id));
+ expect(stored).toMatchObject({
+ canceledAt: null,
+ resolvedOptionId: 'ship',
+ status: 'resolved',
+ });
+ const [storedNode] = await serverDB.select().from(goalNodes).where(eq(goalNodes.id, node.id));
+ expect(storedNode.status).not.toBe('retired');
+ expect((await decisionEvents(goal.id, decision.id)).map((e) => e.eventType)).toEqual([
+ 'created',
+ ]);
+ });
+});
diff --git a/packages/database/src/models/goalGraph.ts b/packages/database/src/models/goalGraph.ts
index 42d0c79c1cb..4e784c3e896 100644
--- a/packages/database/src/models/goalGraph.ts
+++ b/packages/database/src/models/goalGraph.ts
@@ -984,7 +984,6 @@ export class GoalGraphModel {
and(eq(goalNodeDecisions.id, ownedDecision.id), eq(goalNodeDecisions.status, 'pending')),
)
.returning();
- /* v8 ignore next -- unreachable: ownedGoal() holds the goal row FOR UPDATE and every writer of a decision's status takes that lock first, so the pending row selected above is still pending */
if (!decision) return undefined;
await tx
.update(goalNodes)
@@ -1064,7 +1063,6 @@ export class GoalGraphModel {
and(eq(goalNodeDecisions.id, ownedDecision.id), eq(goalNodeDecisions.status, 'pending')),
)
.returning();
- /* v8 ignore next -- unreachable: ownedGoal() holds the goal row FOR UPDATE and every writer of a decision's status takes that lock first, so the pending row selected above is still pending */
if (!decision) return undefined;
await tx
.update(goalNodes)
diff --git a/packages/database/src/models/recent.guards.test.ts b/packages/database/src/models/recent.guards.test.ts
new file mode 100644
index 00000000000..aa8dfbbf21d
--- /dev/null
+++ b/packages/database/src/models/recent.guards.test.ts
@@ -0,0 +1,81 @@
+// @vitest-environment node
+import { eq, inArray } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { getTestDB } from '../core/getTestDB';
+import { agents, messages, topics, users } from '../schemas';
+import type { LobeChatDatabase } from '../type';
+import { RecentModel } from './recent';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'recent-guards-user';
+const agentId = 'recent-guards-agent';
+const topicId = 'recent-guards-topic';
+const recentModel = new RecentModel(serverDB, userId);
+
+const markdown = '## Done\n\n**Shipped** the [fix](https://example.com) ';
+
+beforeEach(async () => {
+ await serverDB.insert(users).values({ id: userId });
+ await serverDB.insert(agents).values({ id: agentId, slug: 'inbox', userId });
+ await serverDB.insert(topics).values({ agentId, id: topicId, userId });
+ await serverDB.insert(messages).values({
+ agentId,
+ content: markdown,
+ id: `${topicId}-message`,
+ role: 'assistant',
+ topicId,
+ userId,
+ });
+});
+
+afterEach(async () => {
+ vi.restoreAllMocks();
+ // Agents, topics and messages cascade with their owner.
+ await serverDB.delete(users).where(inArray(users.id, [userId]));
+});
+
+describe('RecentModel preview guard', () => {
+ it('falls back to the raw markdown when remove-markdown throws', async () => {
+ // remove-markdown strips horizontal rules before entering its own try/catch, so a
+ // `replace` that throws on this preview escapes the library. Every other string, the
+ // driver's and drizzle's included, goes through the real `replace`.
+ const replace = String.prototype.replace;
+ const failing = vi.spyOn(String.prototype, 'replace').mockImplementation(function (
+ this: string,
+ ...args: Parameters<typeof replace>
+ ) {
+ if (String(this) === markdown) throw new TypeError('remove-markdown: unexpected input');
+ return replace.apply(this, args);
+ });
+
+ const [row] = await recentModel.queryRecent(1, ['topic'], true);
+ const threw = failing.mock.results.some((result) => result.type === 'throw');
+ failing.mockRestore();
+
+ expect(threw).toBe(true);
+ // Untouched, trailing whitespace included: the fallback skips the plain-text pass entirely.
+ expect(row).toMatchObject({ id: topicId, lastAssistantMessage: markdown });
+ });
+});
+
+describe('RecentModel updatedAt guard', () => {
+ it('turns a non-Date updatedAt from the decoder back into a Date', async () => {
+ const [topic] = await serverDB.select().from(topics).where(eq(topics.id, topicId));
+ // The column decoder passes the driver's timestamptz text through undecoded, as a drizzle
+ // upgrade that stopped parsing it would (a Date from the driver is handed back as ISO text).
+ const decode = vi
+ .spyOn(topics.updatedAt, 'mapFromDriverValue')
+ .mockImplementation(
+ (value) => (value instanceof Date ? value.toISOString() : value) as unknown as Date,
+ );
+
+ const [row] = await recentModel.queryRecent(1, ['topic']);
+
+ expect(row.id).toBe(topicId);
+ expect(decode.mock.results.map((result) => typeof result.value)).toContain('string');
+ expect(row.updatedAt).toBeInstanceOf(Date);
+ expect(row.updatedAt.getTime()).toBe(topic.updatedAt.getTime());
+ });
+});
diff --git a/packages/database/src/models/recent.ts b/packages/database/src/models/recent.ts
index 3b6757fb78b..f003b3b9634 100644
--- a/packages/database/src/models/recent.ts
+++ b/packages/database/src/models/recent.ts
@@ -78,7 +78,6 @@ const toPlainTextPreview = (markdown: string): string => {
try {
return removeMarkdown(markdown).trimEnd();
} catch {
- /* v8 ignore next -- unreachable: remove-markdown swallows its own errors unless `throwError` is set, and the preview query only yields non-empty strings */
return markdown;
}
};
@@ -267,11 +266,8 @@ export class RecentModel {
status: row.status,
title: row.title,
type: row.type,
- // Unreachable fallback: drizzle's timestamp column maps every driver value to a Date.
- updatedAt:
- row.updatedAt instanceof Date
- ? row.updatedAt
- : /* v8 ignore next -- unreachable: see note */ new Date(row.updatedAt as any),
+ // Fallback for a driver or decoder that stops handing timestamps back as Date.
+ updatedAt: row.updatedAt instanceof Date ? row.updatedAt : new Date(row.updatedAt as any),
userId: row.userId,
};
});
diff --git a/packages/database/src/models/task/index.guards.test.ts b/packages/database/src/models/task/index.guards.test.ts
new file mode 100644
index 00000000000..fc0ab36be87
--- /dev/null
+++ b/packages/database/src/models/task/index.guards.test.ts
@@ -0,0 +1,69 @@
+// @vitest-environment node
+import { eq, inArray } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { taskActivities, users } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { columnIndex, createProxyTestDB } from '../__tests__/_proxyTestDB';
+import { TaskModel } from './index';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'task-index-guards-user';
+const model = new TaskModel(serverDB, userId);
+
+beforeEach(async () => {
+ await serverDB.insert(users).values({ id: userId });
+});
+
+afterEach(async () => {
+ vi.restoreAllMocks();
+ await serverDB.delete(users).where(inArray(users.id, [userId]));
+});
+
+describe('TaskModel.resolve ambiguity guard', () => {
+ it('refuses to pick one of two tasks that answer the same identifier', async () => {
+ const task = await model.create({ instruction: 'only task' });
+ // Two rows behind one identifier: what the lookup would see if the per-scope unique
+ // index (tasks_identifier_idx) were dropped or the scope predicate widened.
+ const duplicating = new TaskModel(
+ createProxyTestDB(serverDB, (query, result) => {
+ if (!query.startsWith('select') || !query.includes('from "tasks"')) return result.rows;
+ const id = columnIndex(result, 'id');
+ return result.rows.flatMap((row) => {
+ const twin = [...row];
+ twin[id] = `${row[id]}-twin`;
+ return [row, twin];
+ });
+ }),
+ userId,
+ );
+
+ await expect(duplicating.resolve(task.identifier)).rejects.toThrow(
+ `Ambiguous task reference: ${task.identifier}`,
+ );
+ // The same ref against the real rows resolves to the one task.
+ expect((await model.resolve(task.identifier))?.id).toBe(task.id);
+ });
+});
+
+describe('TaskModel.updateWithLog write guard', () => {
+ it('returns null and logs nothing when the locked write comes back empty', async () => {
+ const task = await model.create({ instruction: 'locked task', priority: 1 });
+ // The scoped write inside the transaction reports no row, as if the locked row had
+ // left the caller's scope between the lock and the write.
+ const write = vi.spyOn(TaskModel.prototype, 'update').mockResolvedValue(null);
+
+ const result = await model.updateWithLog(task.id, { priority: 3 }, { userId });
+
+ // The locked path ran: the write inside the transaction was attempted with the new value.
+ expect(write).toHaveBeenCalledWith(task.id, { priority: 3 });
+ expect(result).toBeNull();
+ vi.restoreAllMocks();
+ expect((await model.findById(task.id))?.priority).toBe(1);
+ expect(
+ await serverDB.select().from(taskActivities).where(eq(taskActivities.taskId, task.id)),
+ ).toEqual([]);
+ });
+});
diff --git a/packages/database/src/models/task/index.ts b/packages/database/src/models/task/index.ts
index 2cdf74e307d..4724a537578 100644
--- a/packages/database/src/models/task/index.ts
+++ b/packages/database/src/models/task/index.ts
@@ -133,7 +133,6 @@ export class TaskModel {
async resolve(ref: string): Promise<TaskItem | null> {
const result = await this.resolveRefs([ref]);
- /* v8 ignore next -- unreachable: one ref matches at most one row, ids are primary keys and identifiers are unique per scope (tasks_identifier_idx / tasks_identifier_workspace_id_unique) */
if (result.ambiguous.length) throw new Error(`Ambiguous task reference: ${ref}`);
return result.byRef.get(ref) ?? null;
}
@@ -675,7 +674,6 @@ export class TaskModel {
}
: data;
const updated = await scoped.update(id, writeData);
- /* v8 ignore next -- unreachable: the row was just locked FOR UPDATE in this transaction under the same ownership predicate, so the write always returns it */
if (!updated) return null;
const events: { payload: TaskActivityLogPayload; type: TaskActivityLogType }[] = [];
diff --git a/packages/database/src/models/topic/find.guards.test.ts b/packages/database/src/models/topic/find.guards.test.ts
new file mode 100644
index 00000000000..7ab13d547e3
--- /dev/null
+++ b/packages/database/src/models/topic/find.guards.test.ts
@@ -0,0 +1,49 @@
+// @vitest-environment node
+import { inArray } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { agents, topics, users } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { TopicModel } from './index';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'topic-find-guards-user';
+const agentId = 'topic-find-guards-agent';
+const topicId = 'topic-find-guards-topic';
+const updatedAt = new Date('2026-08-01T12:34:56.789Z');
+
+beforeEach(async () => {
+ await serverDB.insert(users).values({ id: userId });
+ await serverDB.insert(agents).values({ id: agentId, slug: 'inbox', userId });
+ await serverDB
+ .insert(topics)
+ .values({ agentId, id: topicId, title: 'Guarded', updatedAt, userId });
+});
+
+afterEach(async () => {
+ vi.restoreAllMocks();
+ // Agents and topics cascade with their owner.
+ await serverDB.delete(users).where(inArray(users.id, [userId]));
+});
+
+describe('queryRecent updatedAt guard', () => {
+ it('turns a non-Date activity time from the decoder back into a Date', async () => {
+ // `mapWith(topics.updatedAt)` decodes through the column; here the decoder passes the
+ // driver's timestamptz text through undecoded, as a drizzle upgrade that stopped parsing it
+ // would (a Date from the driver is handed back as its ISO text).
+ const decode = vi
+ .spyOn(topics.updatedAt, 'mapFromDriverValue')
+ .mockImplementation(
+ (value) => (value instanceof Date ? value.toISOString() : value) as unknown as Date,
+ );
+
+ const [item] = await new TopicModel(serverDB, userId).queryRecent();
+
+ expect(decode.mock.results.map((result) => typeof result.value)).toContain('string');
+ expect(item).toMatchObject({ id: topicId, title: 'Guarded', type: 'agent' });
+ expect(item.updatedAt).toBeInstanceOf(Date);
+ expect(item.updatedAt.getTime()).toBe(updatedAt.getTime());
+ });
+});
diff --git a/packages/database/src/models/topic/find.ts b/packages/database/src/models/topic/find.ts
index 2339fe85be9..454e6c646da 100644
--- a/packages/database/src/models/topic/find.ts
+++ b/packages/database/src/models/topic/find.ts
@@ -434,9 +434,7 @@ export const queryRecent = async (ctx: TopicModelContext, limit: number = 12) =>
return result.map((item) => ({
...item,
type: item.groupId ? ('group' as const) : ('agent' as const),
- /* v8 ignore start -- unreachable: the `new Date(…)` arm; `mapWith(topics.updatedAt)` decodes the timestamptz cell into a Date, whichever driver returns it */
updatedAt: item.updatedAt instanceof Date ? item.updatedAt : new Date(item.updatedAt),
- /* v8 ignore stop */
}));
};
diff --git a/packages/database/src/models/trash.guards.test.ts b/packages/database/src/models/trash.guards.test.ts
new file mode 100644
index 00000000000..dbb9341a32c
--- /dev/null
+++ b/packages/database/src/models/trash.guards.test.ts
@@ -0,0 +1,52 @@
+// @vitest-environment node
+import { inArray } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { getTestDB } from '../core/getTestDB';
+import { users } from '../schemas';
+import type { LobeChatDatabase } from '../type';
+import { TrashModel } from './trash';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'trash-guards-user';
+const model = new TrashModel(serverDB, userId);
+
+beforeEach(async () => {
+ await serverDB.insert(users).values({ id: userId });
+ for (let i = 0; i < 3; i++) {
+ await model.register({
+ deletedAt: new Date(`2026-08-0${i + 1}T00:00:00Z`),
+ root: { projectId: null, resourceId: `agt_${i}`, resourceType: 'agent', title: `a${i}` },
+ });
+ }
+});
+
+afterEach(async () => {
+ vi.restoreAllMocks();
+ await serverDB.delete(users).where(inArray(users.id, [userId]));
+});
+
+describe('TrashModel.list cursor guard', () => {
+ it('restarts from the first page when decoding the cursor throws', async () => {
+ const first = await model.list({ limit: 2 });
+ expect(first.items.map((item) => item.resourceId)).toEqual(['agt_2', 'agt_1']);
+ expect(first.nextCursor).toBeTruthy();
+
+ // Only the cursor decode passes 'base64url' to Buffer.from; the driver's own calls do not.
+ const from = Buffer.from;
+ const decode = vi.spyOn(Buffer, 'from').mockImplementation(((...args: unknown[]) => {
+ if (args[1] === 'base64url') throw new TypeError('Unknown encoding: base64url');
+ return (from as (...a: unknown[]) => Buffer)(...args);
+ }) as typeof Buffer.from);
+
+ const page = await model.list({ cursor: first.nextCursor, limit: 2 });
+ const threw = decode.mock.results.some((result) => result.type === 'throw');
+ decode.mockRestore();
+
+ expect(threw).toBe(true);
+ // An unreadable cursor is treated as no cursor, not as an error or an empty page.
+ expect(page.items.map((item) => item.resourceId)).toEqual(['agt_2', 'agt_1']);
+ expect(page.nextCursor).toBe(first.nextCursor);
+ });
+});
diff --git a/packages/database/src/models/trash.ts b/packages/database/src/models/trash.ts
index 0389c43f0f2..92c699d0e4a 100644
--- a/packages/database/src/models/trash.ts
+++ b/packages/database/src/models/trash.ts
@@ -599,7 +599,6 @@ const decodeCursor = (cursor?: string | null): { deletedAt: Date; id: string } |
if (!Number.isFinite(ms) || !id) return null;
return { deletedAt: new Date(ms), id };
} catch {
- /* v8 ignore next -- unreachable: Buffer.from(string, 'base64url') and Number() never throw */
return null;
}
};