Skip to content

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

remove unused index and unused columns

Thiago Araujo da Silva6eec185dbd7d
diff --git a/backend/src/db/migrations/20260522191822_audit-log-stream-outbox.ts b/backend/src/db/migrations/20260522191822_audit-log-stream-outbox.ts
index d578d6b4c7..b546f5c1a4 100644
--- a/backend/src/db/migrations/20260522191822_audit-log-stream-outbox.ts
+++ b/backend/src/db/migrations/20260522191822_audit-log-stream-outbox.ts
@@ -16,31 +16,26 @@ export async function up(knex: Knex): Promise<void> {
t.integer("attempts").notNullable().defaultTo(0);
t.timestamp("nextRetryAt", { useTz: true }).notNullable().defaultTo(knex.fn.now());
t.timestamp("lockedAt", { useTz: true });
- t.string("workerId");
- t.text("lastError");
t.timestamps(true, true, true);
t.foreign("streamId").references("id").inTable(TableName.AuditLogStream).onDelete("CASCADE");
t.foreign("orgId").references("id").inTable(TableName.Organization).onDelete("CASCADE");
- // Idempotency guard: the fanout insert targets this constraint with ON CONFLICT DO NOTHING.
+
t.unique(["streamId", "auditLogId"]);
});
- // Worker drain query: WHERE streamId = ? AND status IN ('pending','retry') AND nextRetryAt <= NOW() ORDER BY id LIMIT N FOR UPDATE SKIP LOCKED
await knex.schema.raw(`
CREATE INDEX IF NOT EXISTS "${TableName.AuditLogStreamOutbox}_drain_idx"
ON "${TableName.AuditLogStreamOutbox}" ("streamId", "nextRetryAt", "id")
WHERE status IN ('pending', 'retry')
`);
- // Stale lock recovery: surface rows stuck in 'processing' (worker crashed mid-batch).
await knex.schema.raw(`
CREATE INDEX IF NOT EXISTS "${TableName.AuditLogStreamOutbox}_processing_idx"
ON "${TableName.AuditLogStreamOutbox}" ("lockedAt")
WHERE status = 'processing'
`);
- // Cleanup cron: prune delivered rows past the retention window.
await knex.schema.raw(`
CREATE INDEX IF NOT EXISTS "${TableName.AuditLogStreamOutbox}_delivered_idx"
ON "${TableName.AuditLogStreamOutbox}" ("updatedAt")
@@ -64,9 +59,11 @@ export async function up(knex: Knex): Promise<void> {
t.foreign("streamId").references("id").inTable(TableName.AuditLogStream).onDelete("CASCADE");
t.foreign("orgId").references("id").inTable(TableName.Organization).onDelete("CASCADE");
- t.index(["streamId", "failedAt"]);
- t.index(["orgId", "failedAt"]);
- // Cleanup cron scans by failedAt only — the per-stream/per-org composites above don't help.
+
+ // FK referencing columns: Postgres does not auto-index these, so cascade
+ // deletes (stream/org removal) would otherwise seq-scan the DLQ.
+ t.index(["streamId"]);
+ t.index(["orgId"]);
t.index(["failedAt"]);
});
}
diff --git a/backend/src/db/schemas/audit-log-stream-outbox.ts b/backend/src/db/schemas/audit-log-stream-outbox.ts
index 1eddf94125..4dbe618cc5 100644
--- a/backend/src/db/schemas/audit-log-stream-outbox.ts
+++ b/backend/src/db/schemas/audit-log-stream-outbox.ts
@@ -17,8 +17,6 @@ export const AuditLogStreamOutboxSchema = z.object({
attempts: z.number().default(0),
nextRetryAt: z.date(),
lockedAt: z.date().nullable().optional(),
- workerId: z.string().nullable().optional(),
- lastError: z.string().nullable().optional(),
createdAt: z.date(),
updatedAt: z.date()
});
diff --git a/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-dal.ts b/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-dal.ts
index e46569d876..97cc0fbf3b 100644
--- a/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-dal.ts
+++ b/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-dal.ts
@@ -50,11 +50,7 @@ export const auditLogStreamOutboxDALFactory = (db: TDbClient) => {
// Atomically claim up to `limit` ready rows for `streamId`: lock them with
// FOR UPDATE SKIP LOCKED, mark them processing, and return them to the worker.
// Runs inside a single transaction so the lock and the status flip commit together.
- const claimBatchForStream = async (
- streamId: string,
- limit: number,
- workerId: string
- ): Promise<TAuditLogStreamOutboxRow[]> => {
+ const claimBatchForStream = async (streamId: string, limit: number): Promise<TAuditLogStreamOutboxRow[]> => {
try {
return await db.transaction(async (tx) => {
const lockedRows = await tx(TableName.AuditLogStreamOutbox)
@@ -74,8 +70,7 @@ export const auditLogStreamOutboxDALFactory = (db: TDbClient) => {
.whereIn("id", ids)
.update({
status: AuditLogStreamOutboxStatus.Processing,
- lockedAt: tx.fn.now(),
- workerId
+ lockedAt: tx.fn.now()
})
.returning("*");
@@ -91,9 +86,7 @@ export const auditLogStreamOutboxDALFactory = (db: TDbClient) => {
try {
await (tx || db)(TableName.AuditLogStreamOutbox).whereIn("id", ids).update({
status: AuditLogStreamOutboxStatus.Delivered,
- lockedAt: null,
- workerId: null,
- lastError: null
+ lockedAt: null
});
} catch (error) {
throw new DatabaseError({ error, name: "AuditLogStreamOutbox: markBatchAsDelivered" });
@@ -102,7 +95,7 @@ export const auditLogStreamOutboxDALFactory = (db: TDbClient) => {
// Release a claim by flipping rows back to 'retry' with an updated attempt count
// and a future nextRetryAt. Used when the provider call fails for the whole batch.
- const markBatchForRetry = async (ids: number[], nextRetryAt: Date, errorMessage: string, tx?: Knex) => {
+ const markBatchForRetry = async (ids: number[], nextRetryAt: Date, tx?: Knex) => {
if (ids.length === 0) return;
try {
await (tx || db)(TableName.AuditLogStreamOutbox)
@@ -111,9 +104,7 @@ export const auditLogStreamOutboxDALFactory = (db: TDbClient) => {
status: AuditLogStreamOutboxStatus.Retry,
attempts: db.raw('"attempts" + 1'),
nextRetryAt,
- lockedAt: null,
- workerId: null,
- lastError: errorMessage
+ lockedAt: null
});
} catch (error) {
throw new DatabaseError({ error, name: "AuditLogStreamOutbox: markBatchForRetry" });
@@ -161,12 +152,12 @@ export const auditLogStreamOutboxDALFactory = (db: TDbClient) => {
// around as the dedup guard against a re-fanout from a
// retried ingest tick; pruned later by the cleanup cron).
// - retriable: rows whose chunk failed but can still retry — flip to 'retry'
- // with attempt+1 and lastError = the chunk's error.
+ // with attempt+1.
// - exhausted: rows whose chunk failed and used up MAX_ATTEMPTS — move to DLQ.
// Failed rows arrive as TFailedStreamRow so each carries the errorMessage from
// its own chunk (different chunks of one claim can fail with different errors).
- // We group by errorMessage and issue one markBatchForRetry / moveToDlq per
- // group so each row's lastError reflects what actually broke for it.
+ // Exhausted rows are grouped by errorMessage and moved to the DLQ one group at
+ // a time so each DLQ row records what actually broke for it.
//
// Folding all three outcomes into a single transaction means a crash between
// the writes can't leave the claim half-applied (e.g. some rows flipped to
@@ -186,16 +177,11 @@ export const auditLogStreamOutboxDALFactory = (db: TDbClient) => {
await markBatchAsDelivered(input.successIds, tx);
}
if (input.retriable && retriableRows.length > 0) {
- const idsByError = new Map<string, number[]>();
- for (const { row, errorMessage } of retriableRows) {
- const existing = idsByError.get(errorMessage);
- if (existing) existing.push(row.id);
- else idsByError.set(errorMessage, [row.id]);
- }
- for (const [errorMessage, ids] of idsByError) {
- // eslint-disable-next-line no-await-in-loop
- await markBatchForRetry(ids, input.retriable.nextRetryAt, errorMessage, tx);
- }
+ await markBatchForRetry(
+ retriableRows.map(({ row }) => row.id),
+ input.retriable.nextRetryAt,
+ tx
+ );
}
if (input.exhausted.length > 0) {
const rowsByError = new Map<string, TAuditLogStreamOutboxRow[]>();
@@ -257,9 +243,7 @@ export const auditLogStreamOutboxDALFactory = (db: TDbClient) => {
status: AuditLogStreamOutboxStatus.Retry,
attempts: db.raw('"attempts" + 1'),
nextRetryAt: tx.fn.now(),
- lockedAt: null,
- workerId: null,
- lastError: errorMessage
+ lockedAt: null
});
}
diff --git a/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-service.test.ts b/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-service.test.ts
index 3212154277..45317e6782 100644
--- a/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-service.test.ts
+++ b/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-service.test.ts
@@ -55,8 +55,6 @@ const buildRow = (overrides: Partial<TAuditLogStreamOutboxRow> = {}): TAuditLogS
attempts: 0,
nextRetryAt: new Date(),
lockedAt: new Date(),
- workerId: "worker-1",
- lastError: null,
createdAt: new Date(),
updatedAt: new Date(),
...overrides
diff --git a/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-service.ts b/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-service.ts
index 0ef2c6707d..13ae7dfa13 100644
--- a/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-service.ts
+++ b/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-service.ts
@@ -1,5 +1,4 @@
import { isAxiosError } from "axios";
-import { randomUUID } from "crypto";
import { TAuditLogs } from "@app/db/schemas";
import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";
@@ -66,19 +65,6 @@ const computeBackoff = (attemptsAfterIncrement: number): Date => {
return new Date(Date.now() + base + jitter);
};
-const truncateError = (error: unknown): string => {
- let message: string;
- if (isAxiosError(error)) {
- message = `${error.message ?? "Request failed"} — ${JSON.stringify(error.response?.data ?? null)}`;
- } else {
- message = (error as Error)?.message ?? "Unknown error";
- }
- if (message.length > LAST_ERROR_MAX_LENGTH) {
- return `${message.slice(0, LAST_ERROR_MAX_LENGTH)}...`;
- }
- return message;
-};
-
const formatErrorMessage = (error: unknown): string => {
if (isAxiosError(error)) {
return `${error.message ?? "Request failed"} — ${JSON.stringify(error.response?.data ?? null)}`;
@@ -86,6 +72,11 @@ const formatErrorMessage = (error: unknown): string => {
return (error as Error)?.message ?? "Unknown error";
};
+const truncateError = (error: unknown): string => {
+ const message = formatErrorMessage(error);
+ return message.length > LAST_ERROR_MAX_LENGTH ? `${message.slice(0, LAST_ERROR_MAX_LENGTH)}...` : message;
+};
+
export type TAuditLogStreamOutboxServiceFactoryDep = {
auditLogStreamOutboxDAL: TAuditLogStreamOutboxDALFactory;
auditLogStreamDAL: Pick<TAuditLogStreamDALFactory, "find" | "findById">;
@@ -214,12 +205,11 @@ export const auditLogStreamOutboxServiceFactory = ({
kmsService
});
- const workerId = randomUUID();
const providerImpl = factory();
for (let batchIdx = 0; batchIdx < MAX_BATCHES_PER_JOB; batchIdx += 1) {
// eslint-disable-next-line no-await-in-loop
- const claimed = await auditLogStreamOutboxDAL.claimBatchForStream(streamId, BATCH_SIZE, workerId);
+ const claimed = await auditLogStreamOutboxDAL.claimBatchForStream(streamId, BATCH_SIZE);
if (claimed.length === 0) return;
const chunks = chunkAuditLogsByBatchLimit(claimed, providerImpl.getProviderBatchLimit());
@@ -231,12 +221,11 @@ export const auditLogStreamOutboxServiceFactory = ({
await providerImpl.batchStreamLog({ credentials, auditLogs: chunk.map((row) => row.payload) });
streamSuccess.push(...chunk);
} catch (error) {
- const logMessage = formatErrorMessage(error);
+ const errorMessage = truncateError(error);
logger.error(
error,
- `audit-log-stream-outbox: batch delivery failed [streamId=${streamId}] [orgId=${orgId}] [provider=${provider}] [chunkSize=${chunk.length}]: ${logMessage}`
+ `audit-log-stream-outbox: batch delivery failed [streamId=${streamId}] [orgId=${orgId}] [provider=${provider}] [chunkSize=${chunk.length}]: ${errorMessage}`
);
- const errorMessage = truncateError(error);
streamFail.push(...chunk.map((row) => ({ row, errorMessage })));
}
}
diff --git a/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-types.ts b/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-types.ts
index 30f2a14dde..0b4ac8e63d 100644
--- a/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-types.ts
+++ b/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-types.ts
@@ -19,8 +19,6 @@ export type TAuditLogStreamOutboxRow = {
attempts: number;
nextRetryAt: Date;
lockedAt: Date | null;
- workerId: string | null;
- lastError: string | null;
createdAt: Date;
updatedAt: Date;
};