Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

fix: add missing snapshot index and chunk deletion in cleanup

Scott Wilson913ab4aa2adb
diff --git a/backend/src/db/migrations/20260513182201_add-folder-id-indexes-for-snapshot-prune.ts b/backend/src/db/migrations/20260513182201_add-folder-id-indexes-for-snapshot-prune.ts
new file mode 100644
index 0000000000..c89781a524
--- /dev/null
+++ b/backend/src/db/migrations/20260513182201_add-folder-id-indexes-for-snapshot-prune.ts
@@ -0,0 +1,49 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+
+const MIGRATION_TIMEOUT = 60 * 60 * 1000; // 60 minutes
+const MIGRATION_LOCK_TIMEOUT = 30 * 1000; // 30 seconds
+
+export async function up(knex: Knex): Promise<void> {
+ const stmtResult = await knex.raw("SHOW statement_timeout");
+ const originalStatementTimeout = stmtResult.rows[0].statement_timeout;
+ const lockResult = await knex.raw("SHOW lock_timeout");
+ const originalLockTimeout = lockResult.rows[0].lock_timeout;
+
+ try {
+ await knex.raw(`SET statement_timeout = ${MIGRATION_TIMEOUT}`);
+ await knex.raw(`SET lock_timeout = ${MIGRATION_LOCK_TIMEOUT}`);
+
+ if (
+ (await knex.schema.hasTable(TableName.Snapshot)) &&
+ (await knex.schema.hasColumn(TableName.Snapshot, "folderId"))
+ ) {
+ await knex.raw(`
+ CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_secret_snapshots_folder_id
+ ON ${TableName.Snapshot} ("folderId")
+ `);
+ }
+
+ if (
+ (await knex.schema.hasTable(TableName.SecretFolderVersion)) &&
+ (await knex.schema.hasColumn(TableName.SecretFolderVersion, "folderId"))
+ ) {
+ await knex.raw(`
+ CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_secret_folder_versions_folder_id
+ ON ${TableName.SecretFolderVersion} ("folderId")
+ `);
+ }
+ } finally {
+ await knex.raw(`SET statement_timeout = '${originalStatementTimeout}'`);
+ await knex.raw(`SET lock_timeout = '${originalLockTimeout}'`);
+ }
+}
+
+export async function down(knex: Knex): Promise<void> {
+ await knex.raw(`DROP INDEX IF EXISTS idx_secret_snapshots_folder_id`);
+ await knex.raw(`DROP INDEX IF EXISTS idx_secret_folder_versions_folder_id`);
+}
+
+const config = { transaction: false };
+export { config };
diff --git a/backend/src/ee/services/secret-snapshot/snapshot-dal.ts b/backend/src/ee/services/secret-snapshot/snapshot-dal.ts
index 391113eea8..11824195c8 100644
--- a/backend/src/ee/services/secret-snapshot/snapshot-dal.ts
+++ b/backend/src/ee/services/secret-snapshot/snapshot-dal.ts
@@ -619,6 +619,9 @@ export const snapshotDALFactory = (db: TDbClient) => {
*/
const pruneExcessSnapshots = async () => {
const PRUNE_FOLDER_BATCH_SIZE = 10000;
+ const ORPHAN_PRUNE_BATCH_SIZE = 10000;
+ const ORPHAN_QUERY_TIMEOUT_MS = 10 * 60 * 1000; // 10 minutes
+ const ORPHAN_MAX_RETRY_ON_FAILURE = 3;
logger.info(`daily-resource-cleanup: pruning secret snapshots started`);
try {
@@ -724,15 +727,71 @@ export const snapshotDALFactory = (db: TDbClient) => {
}
}
- // cleanup orphaned snapshots (those that don't belong to an existing folder and folder version)
- await db(TableName.Snapshot)
- .whereNotIn("folderId", (qb) => {
- void qb
- .select("folderId")
- .from(TableName.SecretFolderVersion)
- .union((qb1) => void qb1.select("id").from(TableName.SecretFolder));
- })
- .delete();
+ // cleanup orphaned snapshots (those that don't belong to an existing folder and folder version).
+ let orphanCursor = "00000000-0000-0000-0000-000000000000";
+ let orphanRetryCount = 0;
+ let orphanBatchHadRows = true;
+ logger.info(`daily-resource-cleanup: pruning orphaned secret snapshots started`);
+ while (orphanBatchHadRows) {
+ // Bind to a const so the transaction closure doesn't capture the mutable
+ // `orphanCursor` from the loop scope (no-loop-func).
+ const cursor = orphanCursor;
+ try {
+ const result = await db.transaction(async (trx) => {
+ // SET LOCAL: scope the timeout to this transaction so it auto-reverts on commit/rollback
+ // and doesn't leak back to the connection pool.
+ await trx.raw(`SET LOCAL statement_timeout = ${ORPHAN_QUERY_TIMEOUT_MS}`);
+
+ const batch = await trx(TableName.Snapshot)
+ .where("id", ">", cursor)
+ .orderBy("id", "asc")
+ .limit(ORPHAN_PRUNE_BATCH_SIZE)
+ .select("id");
+
+ if (batch.length === 0) {
+ return { nextCursor: cursor, scanned: 0, deleted: 0 };
+ }
+
+ const batchIds = batch.map((row) => row.id);
+ const lastId = batchIds[batchIds.length - 1];
+
+ const deleted = await trx(TableName.Snapshot)
+ .whereIn("id", batchIds)
+ .whereNotExists(
+ (qb) =>
+ void qb
+ .select(trx.raw("1"))
+ .from(TableName.SecretFolder)
+ .whereRaw(`"${TableName.SecretFolder}"."id" = "${TableName.Snapshot}"."folderId"`)
+ )
+ .whereNotExists(
+ (qb) =>
+ void qb
+ .select(trx.raw("1"))
+ .from(TableName.SecretFolderVersion)
+ .whereRaw(`"${TableName.SecretFolderVersion}"."folderId" = "${TableName.Snapshot}"."folderId"`)
+ )
+ .delete();
+
+ return { nextCursor: lastId, scanned: batch.length, deleted };
+ });
+
+ orphanCursor = result.nextCursor;
+ orphanBatchHadRows = result.scanned > 0;
+ orphanRetryCount = 0;
+ } catch (err) {
+ orphanRetryCount += 1;
+ logger.error(err, `Failed to prune orphaned snapshots starting after id=${cursor}`);
+ if (orphanRetryCount >= ORPHAN_MAX_RETRY_ON_FAILURE) {
+ logger.error(`Giving up on orphaned snapshot prune after ${ORPHAN_MAX_RETRY_ON_FAILURE} retries`);
+ break;
+ }
+ } finally {
+ await new Promise((resolve) => {
+ setTimeout(resolve, 10); // breathing room for the db between batches
+ });
+ }
+ }
} catch (error) {
throw new DatabaseError({ error, name: "SnapshotPrune" });
}