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
merge with batch insertion work
Thiago Araujo da Silva27ed18e64d7c
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.tsindex da20292009..6b135f8e0e 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@@ -102,6 +102,7 @@ describe("audit-log-stream-outbox-service drainStream failure wiring", () => {orgId: ORG_ID,streamId: STREAM_ID,provider: PROVIDER,+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- asymmetric matcher is typed `any`errorMessage: expect.stringContaining(FAILURE_MESSAGE)});expect(auditLogStreamOutboxDAL.markBatchForRetry).toHaveBeenCalledTimes(1);@@ -150,3 +151,91 @@ describe("audit-log-stream-outbox-service drainStream failure wiring", () => {expect(auditLogStreamOutboxDAL.claimBatchForStream).toHaveBeenCalledTimes(1);});});++describe("audit-log-stream-outbox-service enqueueForLogs batch fanout", () => {+ const buildService = () => {+ const auditLogStreamOutboxDAL = {+ batchInsert: vi.fn<(rows: unknown[]) => Promise<void>>(async () => undefined),+ claimBatchForStream: vi.fn(async () => []),+ deleteByIds: vi.fn(async () => undefined),+ markBatchForRetry: vi.fn(async () => undefined),+ moveToDlq: vi.fn(async () => undefined),+ recoverStaleClaims: vi.fn(async () => ({ retried: 0, movedToDlq: 0 }))+ };++ const auditLogStreamDAL = {+ find: vi.fn<(arg: { orgId: string }) => Promise<{ id: string; provider: LogProvider }[]>>(async () => []),+ findById: vi.fn()+ };++ // Win the debounce SETNX so the flush job is always enqueued in these tests.+ const keyStore = { setItemWithExpiryNX: vi.fn(async () => true) };+ const queueService = { queue: vi.fn(async () => undefined) };++ const service = auditLogStreamOutboxServiceFactory({+ auditLogStreamOutboxDAL: auditLogStreamOutboxDAL as never,+ auditLogStreamDAL: auditLogStreamDAL as never,+ kmsService: {} as never,+ keyStore: keyStore as never,+ queueService: queueService as never+ });++ return { service, auditLogStreamOutboxDAL, auditLogStreamDAL, keyStore, queueService };+ };++ const log = (id: string, orgId?: string) => ({ id, orgId }) as TAuditLogStreamOutboxRow["payload"];++ beforeEach(() => {+ vi.clearAllMocks();+ });++ test("empty input does nothing", async () => {+ const { service, auditLogStreamDAL, auditLogStreamOutboxDAL } = buildService();++ await service.enqueueForLogs([]);++ expect(auditLogStreamDAL.find).not.toHaveBeenCalled();+ expect(auditLogStreamOutboxDAL.batchInsert).not.toHaveBeenCalled();+ });++ test("groups by org: one find per distinct org, one batchInsert, one debounce per stream", async () => {+ const { service, auditLogStreamDAL, auditLogStreamOutboxDAL, keyStore, queueService } = buildService();++ auditLogStreamDAL.find.mockImplementation(async ({ orgId }) => {+ if (orgId === "orgA") return [{ id: "sA", provider: PROVIDER }];+ if (orgId === "orgB") return [{ id: "sB", provider: PROVIDER }];+ return [];+ });++ await service.enqueueForLogs([log("1", "orgA"), log("2", "orgA"), log("3", "orgB")]);++ // one lookup per distinct org+ expect(auditLogStreamDAL.find).toHaveBeenCalledTimes(2);+ // single batch insert: sA × 2 logs + sB × 1 log = 3 rows+ expect(auditLogStreamOutboxDAL.batchInsert).toHaveBeenCalledTimes(1);+ expect(auditLogStreamOutboxDAL.batchInsert.mock.calls[0][0]).toHaveLength(3);+ // debounce/wake once per distinct stream+ expect(keyStore.setItemWithExpiryNX).toHaveBeenCalledTimes(2);+ expect(queueService.queue).toHaveBeenCalledTimes(2);+ });++ test("skips logs without an orgId", async () => {+ const { service, auditLogStreamDAL, auditLogStreamOutboxDAL } = buildService();++ await service.enqueueForLogs([log("1")]);++ expect(auditLogStreamDAL.find).not.toHaveBeenCalled();+ expect(auditLogStreamOutboxDAL.batchInsert).not.toHaveBeenCalled();+ });++ test("no active streams for the org → no insert, no debounce", async () => {+ const { service, auditLogStreamDAL, auditLogStreamOutboxDAL, keyStore } = buildService();+ auditLogStreamDAL.find.mockResolvedValue([]);++ await service.enqueueForLogs([log("1", "orgA")]);++ expect(auditLogStreamDAL.find).toHaveBeenCalledTimes(1);+ expect(auditLogStreamOutboxDAL.batchInsert).not.toHaveBeenCalled();+ expect(keyStore.setItemWithExpiryNX).not.toHaveBeenCalled();+ });+});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.tsindex 40b6b0ffab..d4273ee6fb 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@@ -84,7 +84,7 @@ export type TAuditLogStreamOutboxServiceFactoryDep = {};export type TAuditLogStreamOutboxServiceFactory = {- enqueueForOrg: (orgId: string, auditLog: TAuditLogs) => Promise<void>;+ enqueueForLogs: (auditLogs: TAuditLogs[]) => Promise<void>;drainStream: (data: TAuditLogStreamFlushJobData) => Promise<void>;sweepStaleClaims: () => Promise<void>;};@@ -128,22 +128,47 @@ export const auditLogStreamOutboxServiceFactory = ({return true;};- // Per-audit-log fanout:- // 1. Look up active streams for the org.- // 2. Insert one outbox row per stream (payload is self-contained).- // 3. For each stream, try to win the 5s debounce SETNX. The winner enqueues- // the flush job (delayed by FLUSH_DEBOUNCE_MS) on the provider queue;- // losers do nothing because their event is already covered by the winner's job.- const enqueueForOrg = async (orgId: string, auditLog: TAuditLogs) => {- const streams = await auditLogStreamDAL.find({ orgId });- if (streams.length === 0) return;-- await auditLogStreamOutboxDAL.batchInsert(- streams.map((stream) => ({ streamId: stream.id, orgId, payload: auditLog }))- );+ // Batch fanout for a drained set of audit logs:+ // 1. Group logs by org so active streams are looked up once per org (not per log).+ // 2. Insert one outbox row per (stream, log) in a single batch insert.+ // 3. For each stream that received rows, try to win the 5s debounce SETNX once.+ // The winner enqueues the flush job (delayed by FLUSH_DEBOUNCE_MS) on the+ // provider queue; losers do nothing because their events are already covered.+ const enqueueForLogs = async (auditLogs: TAuditLogs[]) => {+ if (auditLogs.length === 0) return;++ const logsByOrg = new Map<string, TAuditLogs[]>();+ for (const log of auditLogs) {+ if (log.orgId) {+ const existing = logsByOrg.get(log.orgId);+ if (existing) existing.push(log);+ else logsByOrg.set(log.orgId, [log]);+ }+ }++ const outboxRows: { streamId: string; orgId: string; payload: TAuditLogs }[] = [];+ // Dedup streams touched this batch so each is debounced/woken exactly once.+ const streamsToFlush = new Map<string, { orgId: string; provider: LogProvider }>();++ for (const [orgId, logs] of logsByOrg) {+ // eslint-disable-next-line no-await-in-loop+ const streams = await auditLogStreamDAL.find({ orgId });+ for (const stream of streams) {+ for (const log of logs) {+ outboxRows.push({ streamId: stream.id, orgId, payload: log });+ }+ streamsToFlush.set(stream.id, { orgId, provider: stream.provider as LogProvider });+ }+ }++ if (outboxRows.length === 0) return;++ await auditLogStreamOutboxDAL.batchInsert(outboxRows);await Promise.allSettled(- streams.map((stream) => debounceAndEnqueueFlush(stream.id, orgId, stream.provider as LogProvider))+ Array.from(streamsToFlush.entries()).map(([streamId, { orgId, provider }]) =>+ debounceAndEnqueueFlush(streamId, orgId, provider)+ ));};@@ -250,7 +275,7 @@ export const auditLogStreamOutboxServiceFactory = ({};return {- enqueueForOrg,+ enqueueForLogs,drainStream,sweepStaleClaims};diff --git a/backend/src/ee/services/audit-log/audit-log-dal.ts b/backend/src/ee/services/audit-log/audit-log-dal.tsindex 2d258d5e2d..a5a8981125 100644--- a/backend/src/ee/services/audit-log/audit-log-dal.ts+++ b/backend/src/ee/services/audit-log/audit-log-dal.ts@@ -3,7 +3,7 @@ import knex from "knex";import { v4 as uuidv4 } from "uuid";import { TDbClient } from "@app/db";-import { TableName, TAuditLogs } from "@app/db/schemas";+import { TableName, TAuditLogs, TAuditLogsInsert } from "@app/db/schemas";import { getConfig } from "@app/lib/config/env";import { DatabaseError, GatewayTimeoutError } from "@app/lib/errors";import { ormify, selectAllTableCols, TOrmify } from "@app/lib/knex";@@ -11,6 +11,7 @@ import { logger } from "@app/lib/logger";import { ActorType } from "@app/services/auth/auth-type";import { ACTOR_TYPE_TO_METADATA_ID_KEY, EventType, filterableSecretEvents } from "./audit-log-types";+import { chunkArray } from "@app/lib/fn";type TAggregateQuery = {orgId: string;@@ -23,6 +24,7 @@ type TAggregateQuery = {export interface TAuditLogDALFactory extends Omit<TOrmify<TableName.AuditLog>, "find"> {pruneAuditLog: () => Promise<void>;getApproximateRowCount: () => Promise<number>;+ batchCreate: (logs: TAuditLogsInsert[]) => Promise<void>;find: (arg: Omit<TFindQuery, "actor" | "eventType"> & {actorId?: string | undefined;@@ -61,6 +63,7 @@ type TFindQuery = {const QUERY_TIMEOUT_MS = 10 * 60 * 1000; // 10 minutesconst AUDIT_LOG_PRUNE_BATCH_SIZE = 10000;const MAX_RETRY_ON_FAILURE = 3;+const AUDIT_LOG_BATCH_INSERT_CHUNK_SIZE = 1000;export const auditLogDALFactory = (db: TDbClient) => {const auditLogOrm = ormify(db, TableName.AuditLog);@@ -264,6 +267,22 @@ export const auditLogDALFactory = (db: TDbClient) => {return auditLogOrm.create(tx);};+ const batchCreate: TAuditLogDALFactory["batchCreate"] = async (logs) => {+ if (logs.length === 0) return;+ if (getConfig().DISABLE_POSTGRES_AUDIT_LOG_STORAGE) return;++ try {+ await db.transaction(async (tx) => {+ for (const chunk of chunkArray(logs, AUDIT_LOG_BATCH_INSERT_CHUNK_SIZE)) {+ // eslint-disable-next-line no-await-in-loop+ await tx(TableName.AuditLog).insert(chunk).onConflict().ignore();+ }+ });+ } catch (error) {+ throw new DatabaseError({ error, name: "auditLogBulkInsert" });+ }+ };+const countByDateAndActor = async ({orgId,@@ -364,6 +383,7 @@ export const auditLogDALFactory = (db: TDbClient) => {return {...auditLogOrm,create,+ batchCreate,pruneAuditLog,getApproximateRowCount,find,diff --git a/backend/src/ee/services/audit-log/audit-log-queue.test.ts b/backend/src/ee/services/audit-log/audit-log-queue.test.tsnew file mode 100644index 0000000000..3dabee860f--- /dev/null+++ b/backend/src/ee/services/audit-log/audit-log-queue.test.ts@@ -0,0 +1,316 @@+import { beforeEach, describe, expect, test, vi } from "vitest";++import { QueueName } from "@app/queue";++import { auditLogQueueServiceFactory } from "./audit-log-queue";++// Mutable config the mocked getConfig() returns. CLICKHOUSE_AUDIT_LOG_ENABLED is read once at+// factory construction; AUDIT_LOG_STREAMS_ENABLED is read per consumer run.+const mockConfig = {+ CLICKHOUSE_AUDIT_LOG_ENABLED: false,+ CLICKHOUSE_AUDIT_LOG_TABLE_NAME: "audit_logs",+ CLICKHOUSE_AUDIT_LOG_INSERT_SETTINGS: {},+ AUDIT_LOG_STREAMS_ENABLED: false,+ DISABLE_POSTGRES_AUDIT_LOG_STORAGE: false+};++vi.mock("@app/lib/config/env", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@app/lib/config/env")>()),+ getConfig: () => mockConfig+}));++vi.mock("@app/lib/logger", () => ({+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() }+}));++const STREAM_KEY = "audit-log-stream";++const streamEntry = (overrides: Record<string, unknown> = {}) => ({+ id: "log-1",+ createdAt: new Date("2026-05-27T00:00:00.000Z").toISOString(),+ event: { type: "test-event", metadata: { k: "v" } },+ actor: { type: "platform", metadata: {} },+ orgId: "org-1",+ ...overrides+});++// streamCollect returns [entryId, ["data", json]] tuples; the consumer parses fields[1].+const collectResult = (payloads: Record<string, unknown>[], lastId = "9-0") => ({+ entries: payloads.map((p, i) => [`${i + 1}-0`, ["data", JSON.stringify(p)]] as [string, string[]]),+ lastId+});++const createHarness = async ({ clickhouse = false, streamsEnabled = false } = {}) => {+ mockConfig.CLICKHOUSE_AUDIT_LOG_ENABLED = clickhouse;+ mockConfig.AUDIT_LOG_STREAMS_ENABLED = streamsEnabled;++ const startHandlers = new Map<string, (job?: unknown) => Promise<void>>();+ const queueService = {+ start: vi.fn((name: string, fn: (job?: unknown) => Promise<void>) => {+ startHandlers.set(name, fn);+ }),+ queue: vi.fn(async () => undefined),+ upsertJobScheduler: vi.fn(async () => undefined)+ };++ const keyStore = {+ streamAdd: vi.fn<+ (key: string, id: string, fieldValue: { data: string }, maxLen?: number) => Promise<string | null>+ >(async () => "1-0"),+ streamCollect: vi.fn<() => Promise<{ entries: [string, string[]][]; lastId: string | null }>>(async () => ({+ entries: [],+ lastId: null+ })),+ streamTrim: vi.fn<(key: string, minId: string, inclusive?: boolean) => Promise<number>>(async () => 0)+ };++ const auditLogDAL = { batchCreate: vi.fn<(logs: Record<string, unknown>[]) => Promise<void>>(async () => undefined) };+ const projectDAL = {+ findById: vi.fn<(id: string) => Promise<Record<string, unknown> | undefined>>(async () => undefined)+ };+ const licenseService = {+ getPlan: vi.fn<(orgId: string) => Promise<{ auditLogsRetentionDays: number }>>(async () => ({+ auditLogsRetentionDays: 30+ }))+ };+ const auditLogStreamOutboxService = {+ enqueueForLogs: vi.fn<(logs: unknown[]) => Promise<void>>(async () => undefined)+ };+ const clickhouseClient = clickhouse+ ? {+ insert: vi.fn<(opts: { table: string; values: Record<string, unknown>[] }) => Promise<unknown>>(+ async () => undefined+ )+ }+ : null;++ const service = await auditLogQueueServiceFactory({+ auditLogDAL: auditLogDAL as never,+ queueService: queueService as never,+ projectDAL: projectDAL as never,+ licenseService: licenseService as never,+ auditLogStreamOutboxService: auditLogStreamOutboxService as never,+ clickhouseClient: clickhouseClient as never,+ keyStore: keyStore as never+ });++ return {+ service,+ queueService,+ keyStore,+ auditLogDAL,+ projectDAL,+ licenseService,+ auditLogStreamOutboxService,+ clickhouseClient,+ consumer: startHandlers.get(QueueName.AuditLogClickHouseBatch)!,+ shim: startHandlers.get(QueueName.AuditLog)!+ };+};++beforeEach(() => {+ vi.clearAllMocks();+});++describe("audit-log-queue pushToLog", () => {+ test("appends a stream entry with a pinned id and an ISO createdAt", async () => {+ const { service, keyStore } = await createHarness();++ await service.pushToLog({+ event: { type: "e", metadata: {} },+ actor: { type: "platform", metadata: {} },+ orgId: "org-1"+ } as never);++ expect(keyStore.streamAdd).toHaveBeenCalledTimes(1);+ const [key, id, fields] = keyStore.streamAdd.mock.calls[0];+ expect(key).toBe(STREAM_KEY);+ expect(id).toBe("*");+ const parsed = JSON.parse(fields.data) as { id: string; createdAt: string };+ expect(typeof parsed.id).toBe("string");+ expect(parsed.id).toHaveLength(36);+ expect(new Date(parsed.createdAt).toISOString()).toBe(parsed.createdAt);+ });++ test("never throws when streamAdd fails", async () => {+ const { service, keyStore } = await createHarness();+ keyStore.streamAdd.mockRejectedValueOnce(new Error("redis down"));++ await expect(+ service.pushToLog({+ event: { type: "e", metadata: {} },+ actor: { type: "platform", metadata: {} },+ orgId: "o"+ } as never)+ ).resolves.toBeUndefined();+ });++ test("compatibility shim re-routes legacy jobs into the stream", async () => {+ const { shim, keyStore } = await createHarness();++ await shim({ data: { event: { type: "e", metadata: {} }, actor: { type: "platform", metadata: {} }, orgId: "o" } });++ expect(keyStore.streamAdd).toHaveBeenCalledTimes(1);+ });+});++describe("audit-log-queue unified consumer", () => {+ test("does nothing on an empty stream", async () => {+ const { consumer, auditLogDAL, keyStore } = await createHarness();+ keyStore.streamCollect.mockResolvedValueOnce({ entries: [], lastId: null });++ await consumer();++ expect(auditLogDAL.batchCreate).not.toHaveBeenCalled();+ expect(keyStore.streamTrim).not.toHaveBeenCalled();+ });++ test("postgres branch batch-inserts with null-normalized empties + projectName, then trims", async () => {+ const { consumer, auditLogDAL, projectDAL, keyStore } = await createHarness();+ projectDAL.findById.mockResolvedValue({ orgId: "org-1", name: "proj", auditLogsRetentionDays: null });+ keyStore.streamCollect.mockResolvedValueOnce(+ collectResult([streamEntry({ orgId: undefined, projectId: "p1", ipAddress: undefined })])+ );++ await consumer();++ expect(auditLogDAL.batchCreate).toHaveBeenCalledTimes(1);+ const rows = auditLogDAL.batchCreate.mock.calls[0][0];+ expect(rows).toHaveLength(1);+ expect(rows[0].ipAddress).toBeNull();+ expect(rows[0].projectName).toBe("proj");+ expect(rows[0].orgId).toBe("org-1");+ expect(keyStore.streamTrim).toHaveBeenCalledWith(STREAM_KEY, "9-0", true);+ });++ test("clickhouse branch inserts with empty-string empties and no projectName", async () => {+ const { consumer, clickhouseClient, keyStore } = await createHarness({ clickhouse: true });+ keyStore.streamCollect.mockResolvedValueOnce(collectResult([streamEntry({ ipAddress: undefined })]));++ await consumer();++ expect(clickhouseClient!.insert).toHaveBeenCalledTimes(1);+ const args = clickhouseClient!.insert.mock.calls[0][0];+ expect(args.values).toHaveLength(1);+ expect(args.values[0].ipAddress).toBe("");+ expect(args.values[0]).not.toHaveProperty("projectName");+ });++ test("drops entries failing skip rules and inserts only survivors", async () => {+ const { consumer, auditLogDAL, projectDAL, licenseService, keyStore } = await createHarness();+ projectDAL.findById.mockImplementation(async (id: string) =>+ id === "pD" ? { orgId: "orgD", name: "d" } : undefined+ );+ licenseService.getPlan.mockImplementation(async (orgId: string) => ({+ auditLogsRetentionDays: orgId === "orgZero" ? 0 : 30+ }));+ keyStore.streamCollect.mockResolvedValueOnce(+ collectResult([+ streamEntry({ id: "A", orgId: undefined, projectId: undefined }), // neither → drop+ streamEntry({ id: "B", orgId: undefined, projectId: "pB" }), // project deleted → drop+ streamEntry({ id: "C", orgId: "orgZero" }), // retention 0 → drop+ streamEntry({ id: "D", orgId: undefined, projectId: "pD" }) // valid+ ])+ );++ await consumer();++ const rows = auditLogDAL.batchCreate.mock.calls[0][0];+ expect(rows).toHaveLength(1);+ expect(rows[0].id).toBe("D");+ expect(keyStore.streamTrim).toHaveBeenCalledTimes(1);+ });++ test("dedups project and plan lookups across the batch", async () => {+ const { consumer, projectDAL, licenseService, keyStore } = await createHarness();+ projectDAL.findById.mockImplementation(async (id: string) => ({ orgId: id === "p1" ? "orgA" : "orgB", name: id }));+ keyStore.streamCollect.mockResolvedValueOnce(+ collectResult([+ streamEntry({ id: "1", orgId: undefined, projectId: "p1" }),+ streamEntry({ id: "2", orgId: undefined, projectId: "p1" }),+ streamEntry({ id: "3", orgId: undefined, projectId: "p2" }),+ streamEntry({ id: "4", orgId: "orgA" })+ ])+ );++ await consumer();++ expect(projectDAL.findById).toHaveBeenCalledTimes(2); // p1, p2+ expect(licenseService.getPlan).toHaveBeenCalledTimes(2); // orgA, orgB+ });++ test("insert failure skips both the outbox and the trim", async () => {+ const { consumer, auditLogDAL, auditLogStreamOutboxService, keyStore } = await createHarness({+ streamsEnabled: true+ });+ auditLogDAL.batchCreate.mockRejectedValueOnce(new Error("db down"));+ keyStore.streamCollect.mockResolvedValueOnce(collectResult([streamEntry()]));++ await consumer();++ expect(keyStore.streamTrim).not.toHaveBeenCalled();+ expect(auditLogStreamOutboxService.enqueueForLogs).not.toHaveBeenCalled();+ });++ test("on success runs insert → outbox → trim in order", async () => {+ const { consumer, auditLogDAL, auditLogStreamOutboxService, keyStore } = await createHarness({+ streamsEnabled: true+ });+ keyStore.streamCollect.mockResolvedValueOnce(collectResult([streamEntry()]));++ await consumer();++ const insertOrder = auditLogDAL.batchCreate.mock.invocationCallOrder[0];+ const outboxOrder = auditLogStreamOutboxService.enqueueForLogs.mock.invocationCallOrder[0];+ const trimOrder = keyStore.streamTrim.mock.invocationCallOrder[0];+ expect(insertOrder).toBeLessThan(outboxOrder);+ expect(outboxOrder).toBeLessThan(trimOrder);+ });++ test("outbox failure after a successful insert still trims", async () => {+ const { consumer, auditLogStreamOutboxService, keyStore } = await createHarness({ streamsEnabled: true });+ auditLogStreamOutboxService.enqueueForLogs.mockRejectedValueOnce(new Error("outbox down"));+ keyStore.streamCollect.mockResolvedValueOnce(collectResult([streamEntry()]));++ await consumer();++ expect(keyStore.streamTrim).toHaveBeenCalledTimes(1);+ });++ test("does not fan out to the outbox when AUDIT_LOG_STREAMS_ENABLED is false", async () => {+ const { consumer, auditLogStreamOutboxService, keyStore } = await createHarness({ streamsEnabled: false });+ keyStore.streamCollect.mockResolvedValueOnce(collectResult([streamEntry()]));++ await consumer();++ expect(auditLogStreamOutboxService.enqueueForLogs).not.toHaveBeenCalled();+ });++ test("an all-dropped batch still trims without inserting", async () => {+ const { consumer, auditLogDAL, licenseService, keyStore } = await createHarness();+ licenseService.getPlan.mockResolvedValue({ auditLogsRetentionDays: 0 });+ keyStore.streamCollect.mockResolvedValueOnce(collectResult([streamEntry(), streamEntry({ id: "log-2" })]));++ await consumer();++ expect(auditLogDAL.batchCreate).not.toHaveBeenCalled();+ expect(keyStore.streamTrim).toHaveBeenCalledTimes(1);+ });++ test("skips unparseable entries and processes the rest", async () => {+ const { consumer, auditLogDAL, keyStore } = await createHarness();+ keyStore.streamCollect.mockResolvedValueOnce({+ entries: [+ ["1-0", ["data", "not-json{"]],+ ["2-0", ["data", JSON.stringify(streamEntry({ id: "ok" }))]]+ ],+ lastId: "2-0"+ });++ await consumer();++ const rows = auditLogDAL.batchCreate.mock.calls[0][0];+ expect(rows).toHaveLength(1);+ expect(rows[0].id).toBe("ok");+ });+});diff --git a/backend/src/ee/services/audit-log/audit-log-queue.ts b/backend/src/ee/services/audit-log/audit-log-queue.tsindex 887929e964..1cb4425e31 100644--- a/backend/src/ee/services/audit-log/audit-log-queue.ts+++ b/backend/src/ee/services/audit-log/audit-log-queue.ts@@ -2,26 +2,21 @@ import type { ClickHouseClient } from "@clickhouse/client";import { randomUUID } from "crypto";import { v7 as uuidv7 } from "uuid";-import type { TProjects } from "@app/db/schemas";+import type { TAuditLogs, TProjects } from "@app/db/schemas";import { TAuditLogStreamOutboxServiceFactory } from "@app/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-service";import { TKeyStoreFactory } from "@app/keystore/keystore";import { getConfig } from "@app/lib/config/env";import { logger } from "@app/lib/logger";-import {- auditLogDroppedCounter,- auditLogEnqueuedCounter,- auditLogPersistDurationHistogram-} from "@app/lib/telemetry/metrics";import { JOB_SCHEDULER_PREFIX, QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";import { TProjectDALFactory } from "@app/services/project/project-dal";import { TLicenseServiceFactory } from "../license/license-service";import { TAuditLogDALFactory } from "./audit-log-dal";-import { TCreateAuditLogDTO } from "./audit-log-types";+import { TAuditLogStreamEntry, TCreateAuditLogDTO } from "./audit-log-types";type TAuditLogQueueServiceFactoryDep = {auditLogDAL: TAuditLogDALFactory;- auditLogStreamOutboxService: Pick<TAuditLogStreamOutboxServiceFactory, "enqueueForOrg">;+ auditLogStreamOutboxService: Pick<TAuditLogStreamOutboxServiceFactory, "enqueueForLogs">;queueService: TQueueServiceFactory;projectDAL: Pick<TProjectDALFactory, "findById">;licenseService: Pick<TLicenseServiceFactory, "getPlan">;@@ -59,9 +54,13 @@ export const AUDIT_LOG_STREAM_TIMEOUT = 5 * 1000;// give them more headroom than the single-event ping timeout above.export const AUDIT_LOG_STREAM_BATCH_TIMEOUT = 30 * 1000;const MS_IN_DAY = 24 * 60 * 60 * 1000;-const AUDIT_LOG_CLICKHOUSE_STREAM_KEY = "audit-log-stream";-const AUDIT_LOG_CLICKHOUSE_BATCH_SIZE = 10_000;-const AUDIT_LOG_CLICKHOUSE_MAX_ENTRIES = 50_000;++// Redis ingest stream shared by both storage backends. `pushToLog` appends raw-ish entries+// here; a single scheduled consumer drains, enriches, batch-inserts, fans out to the outbox,+// and trims. Keep the key literal stable so a rolling deploy doesn't strand in-flight entries.+const AUDIT_LOG_STREAM_KEY = "audit-log-stream";+const AUDIT_LOG_STREAM_BATCH_SIZE = 10_000;+const AUDIT_LOG_STREAM_MAX_ENTRIES = 50_000;export const auditLogQueueServiceFactory = async ({auditLogDAL,@@ -77,180 +76,204 @@ export const auditLogQueueServiceFactory = async ({const isClickHouseBatchEnabled = Boolean(clickhouseClient && CLICKHOUSE_AUDIT_LOG_ENABLED);+ // Append the log to the Redis ingest stream. We pin `id` and `createdAt` here so a consumer+ // retry (reprocessing the same batch after a failed insert) re-inserts byte-identical rows+ // instead of regenerating ids. UUIDv7 embeds the timestamp for ClickHouse's time-sorted id;+ // UUIDv4 keeps the existing Postgres schema expectation.const pushToLog = async (data: TCreateAuditLogDTO) => {- await queueService.queue<QueueName.AuditLog>(QueueName.AuditLog, QueueJobs.AuditLog, data, {- removeOnFail: {- count: 3- },- removeOnComplete: true,- jobId: randomUUID()- });- auditLogEnqueuedCounter.add(1, {- "audit_log.event_type": data.event?.type ?? "unknown",- "audit_log.actor_type": data.actor?.type ?? "unknown",- ...(data.orgId ? { "infisical.organization.id": data.orgId } : {})- });+ try {+ const createdAt = new Date();+ const id = isClickHouseBatchEnabled ? uuidv7({ msecs: createdAt.getTime() }) : randomUUID();+ const entry: TAuditLogStreamEntry = { ...data, id, createdAt: createdAt.toISOString() };+ await keyStore.streamAdd(AUDIT_LOG_STREAM_KEY, "*", { data: JSON.stringify(entry) });+ } catch (error) {+ logger.error(+ error,+ `audit-log-queue: Failed to push audit log to ingest stream [event=${data.event?.type}] [orgId=${data.orgId}] [projectId=${data.projectId}]`+ );+ }};+ // Compatibility shim: legacy per-log AuditLog jobs enqueued by old pods (before the+ // stream rollout) get re-routed into the unified stream so a rolling deploy doesn't+ // strand them with no consumer.+ // TODO: remove next release once the legacy QueueName.AuditLog queue has drained.queueService.start(QueueName.AuditLog, async (job) => {- try {- if (!job.data) {- logger.error({ jobId: job.id }, "audit-log-queue: Received job with empty data, skipping");- return;+ if (!job.data) return;+ await pushToLog(job.data);+ });++ const insertBatch = async (logs: TAuditLogs[]) => {+ if (isClickHouseBatchEnabled) {+ await clickhouseClient!.insert({+ table: CLICKHOUSE_AUDIT_LOG_TABLE_NAME,+ clickhouse_settings: CLICKHOUSE_AUDIT_LOG_INSERT_SETTINGS,+ values: logs,+ format: "JSONEachRow"+ });+ } else {+ await auditLogDAL.batchCreate(logs);+ }+ };++ // Unified consumer: drain a batch from the ingest stream, enrich each entry, batch-insert+ // into the active backend, fan out to the stream outbox, and trim. Trim happens only after a+ // successful insert so a failed batch is retried on the next tick (re-inserts are idempotent:+ // ClickHouse ReplacingMergeTree dedups on id, Postgres uses ON CONFLICT (id) DO NOTHING).+ const consumeAuditLogStream = async () => {+ const { entries, lastId } = await keyStore.streamCollect(+ AUDIT_LOG_STREAM_KEY,+ AUDIT_LOG_STREAM_BATCH_SIZE,+ AUDIT_LOG_STREAM_MAX_ENTRIES+ );++ if (entries.length === 0 || !lastId) return;++ // Parse — a single corrupt entry is skipped, not allowed to abort the whole batch.+ const parsed: TAuditLogStreamEntry[] = [];+ for (const [, fields] of entries) {+ try {+ parsed.push(JSON.parse(fields[1]) as TAuditLogStreamEntry);+ } catch (error) {+ logger.error(error, "audit-log-queue: Skipping unparseable audit log stream entry");}+ }++ // Resolve projects for entries that arrived without an orgId (deduped by projectId). A+ // lookup that returns nothing means the project was deleted → drop that entry; a lookup+ // that throws bubbles up to fail the tick (no trim → retry) so a transient DB error+ // doesn't silently lose logs.+ const projectCache = new Map<string, TProjects | undefined>();+ const distinctProjectIds = [+ ...new Set(parsed.filter((entry) => !entry.orgId && entry.projectId).map((entry) => entry.projectId as string))+ ];+ for (const projectId of distinctProjectIds) {+ // eslint-disable-next-line no-await-in-loop+ projectCache.set(projectId, await projectDAL.findById(projectId));+ }- const { actor, event, ipAddress, projectId, userAgent, userAgentType } = job.data;- let { orgId } = job.data;- let project: TProjects | undefined;+ const resolveOrgId = (entry: TAuditLogStreamEntry): string | undefined =>+ entry.orgId ?? (entry.projectId ? projectCache.get(entry.projectId)?.orgId : undefined);- if (!orgId && !projectId) {+ // Resolve license plans (deduped by orgId) — drives the audit-log retention check + TTL.+ const planCache = new Map<string, Awaited<ReturnType<typeof licenseService.getPlan>>>();+ const distinctOrgIds = new Set<string>();+ for (const entry of parsed) {+ const orgId = resolveOrgId(entry);+ if (orgId) distinctOrgIds.add(orgId);+ }+ for (const orgId of distinctOrgIds) {+ // eslint-disable-next-line no-await-in-loop+ planCache.set(orgId, await licenseService.getPlan(orgId));+ }++ // Enrich one entry into a persistable audit log, or return null to drop it (skip rules+ // mirror the prior per-log worker). Only org-less (project-scoped) entries carry project+ // context — a directly-supplied orgId skips the project lookup entirely, as before.+ const enrichEntry = (entry: TAuditLogStreamEntry): TAuditLogs | null => {+ const { projectId } = entry;++ if (!entry.orgId && !projectId) {+ logger.error(`audit-log-queue: Skipping entry with neither orgId nor projectId [event=${entry.event?.type}]`);+ return null;+ }++ const project = !entry.orgId && projectId ? projectCache.get(projectId) : undefined;+ if (!entry.orgId && projectId && !project) {logger.error(- `audit-log-queue: Received job with neither orgId nor projectId, skipping [jobId=${job.id}] [event=${job.data.event?.type}]`+ `audit-log-queue: Skipping entry, project was deleted [projectId=${projectId}] [event=${entry.event?.type}]`);- return;+ return null;}- if (!orgId) {- // TODO(akhilmhdh): use caching here in dal to avoid db calls- project = await projectDAL.findById(projectId!);- if (!project) {- logger.error(- `audit-log-queue: projecet was deleted, skipping [jobId=${job.id}] [projectId=${projectId}] [event=${job.data.event?.type}]`- );- return;- }- orgId = project.orgId;+ const orgId = entry.orgId ?? project?.orgId;+ if (!orgId) return null;++ const plan = planCache.get(orgId);+ // Skip inserting if audit log retention is 0/unset, meaning it's not supported.+ if (!plan?.auditLogsRetentionDays) return null;++ // For project actions, cap TTL at the project-level retention so the plan's retention+ // days cannot be bypassed upward.+ const ttlInDays =+ project?.auditLogsRetentionDays && project.auditLogsRetentionDays < plan.auditLogsRetentionDays+ ? project.auditLogsRetentionDays+ : plan.auditLogsRetentionDays;+ const ttl = ttlInDays * MS_IN_DAY;++ const createdAt = new Date(entry.createdAt);+ return {+ id: entry.id,+ actor: entry.actor.type,+ actorMetadata: normalizeJsonPayload(entry.actor.metadata),+ ipAddress: normalizeEmptyValue(entry.ipAddress, isClickHouseBatchEnabled),+ eventType: entry.event.type,+ eventMetadata: normalizeJsonPayload(entry.event.metadata),+ userAgent: normalizeEmptyValue(entry.userAgent, isClickHouseBatchEnabled),+ userAgentType: normalizeEmptyValue(entry.userAgentType, isClickHouseBatchEnabled),+ projectId: normalizeEmptyValue(projectId, isClickHouseBatchEnabled),+ orgId,+ expiresAt: new Date(createdAt.getTime() + ttl),+ createdAt,+ updatedAt: createdAt,+ // project name is only stored for non-ClickHouse insertion+ ...(!isClickHouseBatchEnabled ? { projectName: project?.name } : {})+ };+ };++ const enriched = parsed.map(enrichEntry).filter((log): log is TAuditLogs => log !== null);++ if (enriched.length > 0) {+ try {+ await insertBatch(enriched);+ } catch (error) {+ logger.error(+ error,+ `audit-log-queue: Failed to batch insert ${enriched.length} audit logs [backend=${+ isClickHouseBatchEnabled ? "clickhouse" : "postgres"+ }]`+ );+ // Do not trim — the same entries are reprocessed next tick (re-insert is idempotent).+ return;}- const plan = await licenseService.getPlan(orgId);-- // skip inserting if audit log retention is 0 meaning its not supported- if (plan.auditLogsRetentionDays) {- // For project actions, set TTL to project-level audit log retention config- // This condition ensures that the plan's audit log retention days cannot be bypassed- const ttlInDays =- project?.auditLogsRetentionDays && project.auditLogsRetentionDays < plan.auditLogsRetentionDays- ? project.auditLogsRetentionDays- : plan.auditLogsRetentionDays;-- const ttl = ttlInDays * MS_IN_DAY;-- const createdAt = new Date(job.timestamp);- const eventMetadata = normalizeJsonPayload(event.metadata);- const actorMetadata = normalizeJsonPayload(actor.metadata);-- // UUIDv7 embeds job.timestamp so the id's time matches createdAt- // UUIDv4 for Postgres (existing schema expectation)- const id = isClickHouseBatchEnabled ? uuidv7({ msecs: createdAt.getTime() }) : randomUUID();- const auditLog = {- id,- actor: actor.type,- actorMetadata,- ipAddress: normalizeEmptyValue(ipAddress, isClickHouseBatchEnabled),- eventType: event.type,- eventMetadata,- userAgent: normalizeEmptyValue(userAgent, isClickHouseBatchEnabled),- userAgentType: normalizeEmptyValue(userAgentType, isClickHouseBatchEnabled),- projectId: normalizeEmptyValue(projectId, isClickHouseBatchEnabled),- orgId,- expiresAt: new Date(createdAt.getTime() + ttl),- createdAt,- updatedAt: createdAt,- // project name is only used for non-ClickHouse insertion- ...(!isClickHouseBatchEnabled ? { projectName: project?.name } : {})- };-- // Push to Redis stream for ClickHouse batch processing- const persistStart = Date.now();- const backend = isClickHouseBatchEnabled ? "clickhouse" : "postgres";- let persistOutcome: "success" | "failure" = "success";- if (isClickHouseBatchEnabled) {- try {- await keyStore.streamAdd(AUDIT_LOG_CLICKHOUSE_STREAM_KEY, "*", {- data: JSON.stringify(auditLog)- });- } catch (error) {- persistOutcome = "failure";- logger.error(- error,- `audit-log-queue: Failed to push audit log to Redis stream for ClickHouse batch [jobId=${job.id}] [event=${job.data.event?.type}] [orgId=${job.data.orgId}] [projectId=${job.data.projectId}]`- );- }- } else {- await auditLogDAL.create(auditLog);- }- auditLogPersistDurationHistogram.record((Date.now() - persistStart) / 1000, {- "audit_log.backend": backend,- "audit_log.event_type": event.type,- "infisical.organization.id": orgId,- outcome: persistOutcome- });-- if (getConfig().AUDIT_LOG_STREAMS_ENABLED) {- // Hand off to the outbox: fan out one row per active stream and let- // per-provider workers batch-drain in the background.- await auditLogStreamOutboxService.enqueueForOrg(orgId, auditLog);+ if (getConfig().AUDIT_LOG_STREAMS_ENABLED) {+ // Fan out to the outbox and wake provider drainers. A failure here must not block the+ // trim: the logs are already in the system of record, and the outbox/drain machinery+ // retries delivery independently. Holding the trim hostage would wedge ingestion.+ try {+ await auditLogStreamOutboxService.enqueueForLogs(enriched);+ } catch (error) {+ logger.error(error, "audit-log-queue: Failed to enqueue audit logs to stream outbox; continuing to trim");}}- } catch (error) {- logger.error(- error,- `audit-log-queue: Failed to process audit log job [jobId=${job.id}] [event=${job.data.event?.type}] [orgId=${job.data.orgId}] [projectId=${job.data.projectId}]`- );- throw error;- }- });- // Track audit log events that were ultimately dropped after exhausting BullMQ's retry budget.- queueService.listen(QueueName.AuditLog, "failed", (job) => {- if (!job) return;- const attemptsRemaining = (job.opts.attempts ?? 1) - (job.attemptsMade ?? 0);- if (attemptsRemaining > 0) return;- auditLogDroppedCounter.add(1, {- "audit_log.event_type": job.data?.event?.type ?? "unknown",- "audit_log.drop_reason": "max_retries",- ...(job.data?.orgId ? { "infisical.organization.id": job.data.orgId } : {})- });- });-- // Batch consumer: reads from Redis stream and inserts into ClickHouse every 5 seconds- if (isClickHouseBatchEnabled) {- queueService.start(QueueName.AuditLogClickHouseBatch, async () => {- const { entries, lastId } = await keyStore.streamCollect(- AUDIT_LOG_CLICKHOUSE_STREAM_KEY,- AUDIT_LOG_CLICKHOUSE_BATCH_SIZE,- AUDIT_LOG_CLICKHOUSE_MAX_ENTRIES+ logger.info(+ {+ inserted: enriched.length,+ dropped: parsed.length - enriched.length,+ backend: isClickHouseBatchEnabled ? "clickhouse" : "postgres"+ },+ "audit-log-queue: Batch processed audit logs");+ }- if (entries.length === 0 || !lastId) return;-- const values = entries.map(([, fields]) => JSON.parse(fields[1]) as Record<string, unknown>);-- try {- await clickhouseClient!.insert({- table: CLICKHOUSE_AUDIT_LOG_TABLE_NAME,- clickhouse_settings: CLICKHOUSE_AUDIT_LOG_INSERT_SETTINGS,- values,- format: "JSONEachRow"- });+ // Trim whenever the insert step did not throw — including the all-dropped case — so skipped+ // and handled entries don't accumulate in the stream forever.+ await keyStore.streamTrim(AUDIT_LOG_STREAM_KEY, lastId, true);+ };- // Only trim after successful insert- await keyStore.streamTrim(AUDIT_LOG_CLICKHOUSE_STREAM_KEY, lastId, true);+ // Single scheduled consumer for both backends, every 5 seconds. Registered unconditionally+ // now that Postgres also batches through the stream. The scheduler id is kept as the historical+ // "audit-log-clickhouse-batch" so the existing Redis scheduler key isn't orphaned on upgrade.+ queueService.start(QueueName.AuditLogClickHouseBatch, consumeAuditLogStream);- logger.info({ count: values.length }, "audit-log-queue: Batch inserted audit logs into ClickHouse");- } catch (error) {- logger.error(error, `audit-log-queue: Failed to batch insert ${values.length} audit logs into ClickHouse`);- }- });-- // Schedule repeatable job every 5 seconds- await queueService.upsertJobScheduler(- QueueName.AuditLogClickHouseBatch,- `${JOB_SCHEDULER_PREFIX}:audit-log-clickhouse-batch`,- { every: 5000 },- { name: QueueJobs.AuditLogClickHouseBatch }- );- }+ await queueService.upsertJobScheduler(+ QueueName.AuditLogClickHouseBatch,+ `${JOB_SCHEDULER_PREFIX}:audit-log-clickhouse-batch`,+ { every: 5000 },+ { name: QueueJobs.AuditLogClickHouseBatch }+ );return {pushToLogdiff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex 9f05e80459..6615b60e04 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -101,6 +101,15 @@ export type TCreateAuditLogDTO = {export type AuditLogInfo = Pick<TCreateAuditLogDTO, "userAgent" | "userAgentType" | "ipAddress" | "actor">;+// What `pushToLog` writes to the Redis ingest stream. We pin `id` and `createdAt` at+// push time so a consumer retry (reprocessing the same batch after a failed insert)+// re-inserts byte-identical rows instead of regenerating ids and creating duplicates.+// `createdAt` is an ISO string for JSON round-tripping through the stream.+export type TAuditLogStreamEntry = TCreateAuditLogDTO & {+ id: string;+ createdAt: string;+};+export type TAuditLogServiceFactory = {createAuditLog: (data: TCreateAuditLogDTO) => Promise<void>;listAuditLogs: (arg: TListProjectAuditLogDTO) => Promise<