Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
Enhance batch deletion process for project and environment secrets
Victor Hugo dos Santosce828dd9c149
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.mdindex 9e0689b11e..a28499985e 100644--- a/backend/CLAUDE.md+++ b/backend/CLAUDE.md@@ -334,7 +334,7 @@ Pattern:- **Chunk-deleting child rows: check inbound FKs first.** Reference implementation: `services/secret-v2-bridge/secret-tree-hard-delete-fns.ts` (project/env hard-delete workers).- `CASCADE` / `SET NULL` inbound FKs → safe to chunk.- `DEFERRABLE NO ACTION` → only if you delete the referencing rows in the **same transaction**; hard-delete paths only (never live deletes).- - Non-deferrable `NO ACTION` / `RESTRICT` → do not chunk; leave to the final cascade.+ - Non-deferrable `NO ACTION` / `RESTRICT` → neither path is safe: it breaks the final cascade too (next bullet). Migrate the FK to `DEFERRABLE INITIALLY DEFERRED` first.- Each batch: own transaction + `SET LOCAL statement_timeout`.- **A non-deferrable `NO ACTION`/`RESTRICT` inbound FK is unsafe under cascading deletes; make it `DEFERRABLE INITIALLY DEFERRED`.** It is checked at end of *statement*, so within one cascading `DELETE` a parent branch can be processed before a sibling branch deletes the referencer, raising "update or delete on X violates FK on Y". When a CASCADE child of the deleted root is itself referenced by `NO ACTION`/`RESTRICT` FKs, declare those FKs `.deferrable("deferred")` so the check runs at COMMIT after the cascade completes (a *direct* parent delete is still blocked while a referencer remains). Audit **all** inbound `NO ACTION`/`RESTRICT` FKs of such a parent, not just one.- **Index every FK referencing column that participates in a cascade.** Postgres does **not** auto-index FK columns. A cascade fires a **per-row** RI trigger on each child, so an unindexed child means one seq-scan *per deleted parent row*, which blows past `statement_timeout` on a chunked delete. Before chunk-deleting a large table, enumerate **every** inbound FK, including helper-generated ones: `createJunctionTable` (`src/db/utils.ts`) creates CASCADE FK columns with **no index** on either side, so every junction table needs explicit FK indexes. For a mostly-NULL nullable FK, a partial index `WHERE col IS NOT NULL` serves the cascade lookup at a fraction of the size/write cost.diff --git a/backend/src/services/project-env/project-env-dal.ts b/backend/src/services/project-env/project-env-dal.tsindex 480d676e0f..8fbf86f3fe 100644--- a/backend/src/services/project-env/project-env-dal.ts+++ b/backend/src/services/project-env/project-env-dal.ts@@ -244,58 +244,68 @@ export const projectEnvDALFactory = (db: TDbClient) => {}};- const pruneOpts = (batchSize: number, statementTimeoutMs: number, interBatchSleepMs: number) => ({+ const pruneOpts = (+ batchSize: number,+ statementTimeoutMs: number,+ interBatchSleepMs: number,+ onBatchCommitted?: (deleted: number) => void+ ) => ({batchSize,statementTimeoutMs,- interBatchSleepMs+ interBatchSleepMs,+ onBatchCommitted});const hardDeleteEnvironmentSecretVersionsInBatches = (envId: string,batchSize: number,statementTimeoutMs: number,- interBatchSleepMs: number+ interBatchSleepMs: number,+ onBatchCommitted?: (deleted: number) => void) =>hardDeleteSecretVersionsInBatches(db,envFolderIdsSubquery(envId),- pruneOpts(batchSize, statementTimeoutMs, interBatchSleepMs)+ pruneOpts(batchSize, statementTimeoutMs, interBatchSleepMs, onBatchCommitted));const hardDeleteEnvironmentSecretReferencesInBatches = (envId: string,batchSize: number,statementTimeoutMs: number,- interBatchSleepMs: number+ interBatchSleepMs: number,+ onBatchCommitted?: (deleted: number) => void) =>hardDeleteSecretReferencesInBatches(db,envFolderIdsSubquery(envId),- pruneOpts(batchSize, statementTimeoutMs, interBatchSleepMs)+ pruneOpts(batchSize, statementTimeoutMs, interBatchSleepMs, onBatchCommitted));const hardDeleteEnvironmentApprovalSecretLinksInBatches = (envId: string,batchSize: number,statementTimeoutMs: number,- interBatchSleepMs: number+ interBatchSleepMs: number,+ onBatchCommitted?: (deleted: number) => void) =>hardDeleteApprovalSecretLinksInBatches(db,envFolderIdsSubquery(envId),- pruneOpts(batchSize, statementTimeoutMs, interBatchSleepMs)+ pruneOpts(batchSize, statementTimeoutMs, interBatchSleepMs, onBatchCommitted));const hardDeleteEnvironmentSecretsInBatches = (envId: string,batchSize: number,statementTimeoutMs: number,- interBatchSleepMs: number+ interBatchSleepMs: number,+ onBatchCommitted?: (deleted: number) => void) =>hardDeleteSecretsInBatches(db,envFolderIdsSubquery(envId),- pruneOpts(batchSize, statementTimeoutMs, interBatchSleepMs)+ pruneOpts(batchSize, statementTimeoutMs, interBatchSleepMs, onBatchCommitted));return {diff --git a/backend/src/services/project-env/project-env-queue.ts b/backend/src/services/project-env/project-env-queue.tsindex 3c8ca820e3..f10bd49193 100644--- a/backend/src/services/project-env/project-env-queue.ts+++ b/backend/src/services/project-env/project-env-queue.ts@@ -74,7 +74,6 @@ export const projectEnvQueueFactory = ({});const processEnvHardDelete = async (envId: string, projectId: string) => {- // Declared outside the try so a failed run still reports how far the prune got.let deletedVersions = 0;let deletedReferences = 0;let nulledApprovalLinks = 0;@@ -105,30 +104,42 @@ export const projectEnvQueueFactory = ({// secret_versions_v2 has no FK back to the folder/env tree, so the cascade below would orphan it.// must be deleted first, while its folders still exist to identify the rows.- deletedVersions = await projectEnvDAL.hardDeleteEnvironmentSecretVersionsInBatches(+ await projectEnvDAL.hardDeleteEnvironmentSecretVersionsInBatches(envId,SECRET_VERSION_DELETE_BATCH,BATCH_STATEMENT_TIMEOUT_MS,- INTER_BATCH_SLEEP_MS+ INTER_BATCH_SLEEP_MS,+ (deleted) => {+ deletedVersions += deleted;+ });- deletedReferences = await projectEnvDAL.hardDeleteEnvironmentSecretReferencesInBatches(+ await projectEnvDAL.hardDeleteEnvironmentSecretReferencesInBatches(envId,SECRET_VERSION_DELETE_BATCH,BATCH_STATEMENT_TIMEOUT_MS,- INTER_BATCH_SLEEP_MS+ INTER_BATCH_SLEEP_MS,+ (deleted) => {+ deletedReferences += deleted;+ });- nulledApprovalLinks = await projectEnvDAL.hardDeleteEnvironmentApprovalSecretLinksInBatches(+ await projectEnvDAL.hardDeleteEnvironmentApprovalSecretLinksInBatches(envId,SECRET_VERSION_DELETE_BATCH,BATCH_STATEMENT_TIMEOUT_MS,- INTER_BATCH_SLEEP_MS+ INTER_BATCH_SLEEP_MS,+ (deleted) => {+ nulledApprovalLinks += deleted;+ });- deletedSecrets = await projectEnvDAL.hardDeleteEnvironmentSecretsInBatches(+ await projectEnvDAL.hardDeleteEnvironmentSecretsInBatches(envId,SECRET_VERSION_DELETE_BATCH,BATCH_STATEMENT_TIMEOUT_MS,- INTER_BATCH_SLEEP_MS+ INTER_BATCH_SLEEP_MS,+ (deleted) => {+ deletedSecrets += deleted;+ });const deleted = await projectEnvDAL.transaction(async (tx) => {diff --git a/backend/src/services/project/project-cleanup-queue.ts b/backend/src/services/project/project-cleanup-queue.tsindex c1b51e4837..c00298784b 100644--- a/backend/src/services/project/project-cleanup-queue.ts+++ b/backend/src/services/project/project-cleanup-queue.ts@@ -97,7 +97,6 @@ export const projectCleanupQueueFactory = ({});const processProjectHardDelete = async (projectId: string) => {- // Declared outside the try so a failed run still reports how far the prune got.let deletedVersions = 0;let deletedReferences = 0;let nulledApprovalLinks = 0;@@ -124,11 +123,14 @@ export const projectCleanupQueueFactory = ({// has no folderId/secretId FK and no other FK back to the project tree, so the project-delete// cascade would otherwise orphan all of these rows. Deleting by folderId is FK-safe and bounds the// final cascade's transaction size.- deletedVersions = await projectDAL.hardDeleteProjectSecretVersionsInBatches(+ await projectDAL.hardDeleteProjectSecretVersionsInBatches(projectId,SECRET_VERSION_DELETE_BATCH,BATCH_STATEMENT_TIMEOUT_MS,- INTER_BATCH_SLEEP_MS+ INTER_BATCH_SLEEP_MS,+ (deleted) => {+ deletedVersions += deleted;+ });// 2) Same treatment for the two statements that actually time out inside the final cascade on a@@ -136,23 +138,32 @@ export const projectCleanupQueueFactory = ({// secret_approval_requests_secrets_v2 SET NULL. Then the secrets themselves, so their remaining// per-secret CASCADE children run on a batch-sized statement instead of the whole project.// Order matters: deleting secrets first would just drag both cascades back into one statement.- deletedReferences = await projectDAL.hardDeleteProjectSecretReferencesInBatches(+ await projectDAL.hardDeleteProjectSecretReferencesInBatches(projectId,SECRET_VERSION_DELETE_BATCH,BATCH_STATEMENT_TIMEOUT_MS,- INTER_BATCH_SLEEP_MS+ INTER_BATCH_SLEEP_MS,+ (deleted) => {+ deletedReferences += deleted;+ });- nulledApprovalLinks = await projectDAL.hardDeleteProjectApprovalSecretLinksInBatches(+ await projectDAL.hardDeleteProjectApprovalSecretLinksInBatches(projectId,SECRET_VERSION_DELETE_BATCH,BATCH_STATEMENT_TIMEOUT_MS,- INTER_BATCH_SLEEP_MS+ INTER_BATCH_SLEEP_MS,+ (deleted) => {+ nulledApprovalLinks += deleted;+ });- deletedSecrets = await projectDAL.hardDeleteProjectSecretsInBatches(+ await projectDAL.hardDeleteProjectSecretsInBatches(projectId,SECRET_VERSION_DELETE_BATCH,BATCH_STATEMENT_TIMEOUT_MS,- INTER_BATCH_SLEEP_MS+ INTER_BATCH_SLEEP_MS,+ (deleted) => {+ deletedSecrets += deleted;+ });// 3) For big projects: mark envs for the env worker; the cron re-fires this job until drained.diff --git a/backend/src/services/project/project-dal.ts b/backend/src/services/project/project-dal.tsindex 815740d466..afa66fb53d 100644--- a/backend/src/services/project/project-dal.ts+++ b/backend/src/services/project/project-dal.ts@@ -145,58 +145,68 @@ export const projectDALFactory = (db: TDbClient) => {}};- const pruneOpts = (batchSize: number, statementTimeoutMs: number, interBatchSleepMs: number) => ({+ const pruneOpts = (+ batchSize: number,+ statementTimeoutMs: number,+ interBatchSleepMs: number,+ onBatchCommitted?: (deleted: number) => void+ ) => ({batchSize,statementTimeoutMs,- interBatchSleepMs+ interBatchSleepMs,+ onBatchCommitted});const hardDeleteProjectSecretVersionsInBatches = (projectId: string,batchSize: number,statementTimeoutMs: number,- interBatchSleepMs: number+ interBatchSleepMs: number,+ onBatchCommitted?: (deleted: number) => void) =>hardDeleteSecretVersionsInBatches(db,projectFolderIdsSubquery(projectId),- pruneOpts(batchSize, statementTimeoutMs, interBatchSleepMs)+ pruneOpts(batchSize, statementTimeoutMs, interBatchSleepMs, onBatchCommitted));const hardDeleteProjectSecretReferencesInBatches = (projectId: string,batchSize: number,statementTimeoutMs: number,- interBatchSleepMs: number+ interBatchSleepMs: number,+ onBatchCommitted?: (deleted: number) => void) =>hardDeleteSecretReferencesInBatches(db,projectFolderIdsSubquery(projectId),- pruneOpts(batchSize, statementTimeoutMs, interBatchSleepMs)+ pruneOpts(batchSize, statementTimeoutMs, interBatchSleepMs, onBatchCommitted));const hardDeleteProjectApprovalSecretLinksInBatches = (projectId: string,batchSize: number,statementTimeoutMs: number,- interBatchSleepMs: number+ interBatchSleepMs: number,+ onBatchCommitted?: (deleted: number) => void) =>hardDeleteApprovalSecretLinksInBatches(db,projectFolderIdsSubquery(projectId),- pruneOpts(batchSize, statementTimeoutMs, interBatchSleepMs)+ pruneOpts(batchSize, statementTimeoutMs, interBatchSleepMs, onBatchCommitted));const hardDeleteProjectSecretsInBatches = (projectId: string,batchSize: number,statementTimeoutMs: number,- interBatchSleepMs: number+ interBatchSleepMs: number,+ onBatchCommitted?: (deleted: number) => void) =>hardDeleteSecretsInBatches(db,projectFolderIdsSubquery(projectId),- pruneOpts(batchSize, statementTimeoutMs, interBatchSleepMs)+ pruneOpts(batchSize, statementTimeoutMs, interBatchSleepMs, onBatchCommitted));// Hands a project's envs to the paced env hard-delete worker: marks them deleteAfter = now,diff --git a/backend/src/services/secret-v2-bridge/secret-tree-hard-delete-fns.ts b/backend/src/services/secret-v2-bridge/secret-tree-hard-delete-fns.tsindex e5f956d491..76a168b874 100644--- a/backend/src/services/secret-v2-bridge/secret-tree-hard-delete-fns.ts+++ b/backend/src/services/secret-v2-bridge/secret-tree-hard-delete-fns.ts@@ -16,6 +16,10 @@ export type TSecretTreePruneOpts = {batchSize: number;statementTimeoutMs: number;interBatchSleepMs: number;+ // Called after each committed batch. Batches commit independently, so a later batch throwing must+ // not lose the count of what already went: the caller needs it to report progress on the failure+ // path, which is how an operator sees a stuck project converging across attempts.+ onBatchCommitted?: (deleted: number) => void;};export const projectFolderIdsSubquery =@@ -33,7 +37,7 @@ export const envFolderIdsSubquery =const runPruneBatches = async (db: Knex,- { batchSize, statementTimeoutMs, interBatchSleepMs }: TSecretTreePruneOpts,+ { batchSize, statementTimeoutMs, interBatchSleepMs, onBatchCommitted }: TSecretTreePruneOpts,runBatch: (tx: Knex) => Promise<number>) => {let totalAffected = 0;@@ -45,6 +49,7 @@ const runPruneBatches = async (return count;});totalAffected += affected;+ onBatchCommitted?.(affected);if (affected < batchSize) break;// eslint-disable-next-line no-await-in-loopawait new Promise((resolve) => {