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
respect each provider batch boundaries
Thiago Araujo da Silva6223555238cd
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.tsindex 281a98b5b4..76bdded6c7 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@@ -5,7 +5,11 @@ import { TableName, TAuditLogs } from "@app/db/schemas";import { DatabaseError } from "@app/lib/errors";import { chunkArray } from "@app/lib/fn";-import { AuditLogStreamOutboxStatus, TAuditLogStreamOutboxRow } from "./audit-log-stream-outbox-types";+import {+ AuditLogStreamOutboxStatus,+ TAuditLogStreamOutboxRow,+ TFailedStreamRow+} from "./audit-log-stream-outbox-types";export type TAuditLogStreamOutboxDALFactory = ReturnType<typeof auditLogStreamOutboxDALFactory>;@@ -146,24 +150,61 @@ export const auditLogStreamOutboxDALFactory = (db: TDbClient) => {}};- const applyBatchFailure = async (input: {- retriable: { ids: number[]; nextRetryAt: Date } | null;- exhausted: TAuditLogStreamOutboxRow[];- errorMessage: string;+ // Commit the outcome of a chunked delivery for a single claimed batch in one+ // transaction:+ // - successIds: rows that reached the provider — delete them.+ // - retriable: rows whose chunk failed but can still retry — flip to 'retry'+ // with attempt+1 and lastError = the chunk's error.+ // - 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.+ //+ // Folding all three outcomes into a single transaction means a crash between+ // the delete and the retry/DLQ writes can't leave the claim half-applied+ // (e.g. delivered rows deleted but retriable rows still 'processing'); either+ // every write commits or none do, and the stale-claim sweeper picks up an+ // un-applied claim on the next pass.+ const commitDeliveryResult = async (input: {+ successIds: number[];+ retriable: { rows: TFailedStreamRow[]; nextRetryAt: Date } | null;+ exhausted: TFailedStreamRow[];}) => {- const retriableIds = input.retriable?.ids ?? [];- if (retriableIds.length === 0 && input.exhausted.length === 0) return;+ const retriableRows = input.retriable?.rows ?? [];+ if (input.successIds.length === 0 && retriableRows.length === 0 && input.exhausted.length === 0) return;try {await db.transaction(async (tx) => {- if (input.retriable && retriableIds.length > 0) {- await markBatchForRetry(input.retriable.ids, input.retriable.nextRetryAt, input.errorMessage, tx);+ if (input.successIds.length > 0) {+ await deleteByIds(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);+ }}if (input.exhausted.length > 0) {- await moveToDlq(input.exhausted, input.errorMessage, tx);+ const rowsByError = new Map<string, TAuditLogStreamOutboxRow[]>();+ for (const { row, errorMessage } of input.exhausted) {+ const existing = rowsByError.get(errorMessage);+ if (existing) existing.push(row);+ else rowsByError.set(errorMessage, [row]);+ }+ for (const [errorMessage, rows] of rowsByError) {+ // eslint-disable-next-line no-await-in-loop+ await moveToDlq(rows, errorMessage, tx);+ }}});} catch (error) {- throw new DatabaseError({ error, name: "AuditLogStreamOutbox: applyBatchFailure" });+ throw new DatabaseError({ error, name: "AuditLogStreamOutbox: commitDeliveryResult" });}};@@ -229,8 +270,7 @@ export const auditLogStreamOutboxDALFactory = (db: TDbClient) => {return {batchInsert,claimBatchForStream,- deleteByIds,- applyBatchFailure,+ commitDeliveryResult,recoverStaleClaims};};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 498dfbe009..1f1369b0ab 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@@ -2,7 +2,11 @@ import { beforeEach, describe, expect, test, vi } from "vitest";import { LogProvider } from "../audit-log-stream/audit-log-stream-enums";import { auditLogStreamOutboxServiceFactory } from "./audit-log-stream-outbox-service";-import { AuditLogStreamOutboxStatus, TAuditLogStreamOutboxRow } from "./audit-log-stream-outbox-types";+import {+ AuditLogStreamOutboxStatus,+ TAuditLogStreamOutboxRow,+ TFailedStreamRow+} from "./audit-log-stream-outbox-types";const STREAM_ID = "stream-1";const ORG_ID = "org-1";@@ -11,6 +15,12 @@ const PROVIDER = LogProvider.Datadog;const FAILURE_MESSAGE = "upstream failure";const batchStreamLog = vi.fn<(input: unknown) => Promise<void>>();+// Configurable per-test so we can force chunking (e.g. maxLogs: 1) to drive the+// partial-chunk-failure path without rewiring the factory mock for each case.+const getProviderBatchLimit = vi.fn<() => { maxLogs: number; maxBytes: number }>(() => ({+ maxLogs: 1_000,+ maxBytes: 4 * 1024 * 1024+}));vi.mock("@app/lib/logger", () => ({logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() }@@ -28,7 +38,8 @@ vi.mock("../audit-log-stream/audit-log-stream-factory", () => ({{get: () => () => ({batchStreamLog,- validateCredentials: async ({ credentials }: { credentials: unknown }) => credentials+ validateCredentials: async ({ credentials }: { credentials: unknown }) => credentials,+ getProviderBatchLimit})})@@ -57,8 +68,7 @@ const createService = () => {const auditLogStreamOutboxDAL = {batchInsert: vi.fn(async () => undefined),claimBatchForStream: vi.fn<(...args: unknown[]) => Promise<TAuditLogStreamOutboxRow[]>>(async () => []),- deleteByIds: vi.fn(async () => undefined),- applyBatchFailure: vi.fn(async () => undefined),+ commitDeliveryResult: vi.fn<(input: unknown) => Promise<void>>(async () => undefined),recoverStaleClaims: vi.fn(async () => ({ retried: 0, movedToDlq: 0 }))};@@ -87,6 +97,8 @@ const createService = () => {describe("audit-log-stream-outbox-service drainStream failure wiring", () => {beforeEach(() => {vi.clearAllMocks();+ // Reset to the generous default; tests that need chunking override per-call.+ getProviderBatchLimit.mockReturnValue({ maxLogs: 1_000, maxBytes: 4 * 1024 * 1024 });});test("invokes onStreamFailure with the truncated error message when the provider rejects", async () => {@@ -105,12 +117,16 @@ describe("audit-log-stream-outbox-service drainStream failure wiring", () => {// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- asymmetric matcher is typed `any`errorMessage: expect.stringContaining(FAILURE_MESSAGE)});- expect(auditLogStreamOutboxDAL.applyBatchFailure).toHaveBeenCalledTimes(1);- expect(auditLogStreamOutboxDAL.applyBatchFailure.mock.calls[0][0]).toMatchObject({- retriable: { ids: [1] },- exhausted: []- });- expect(auditLogStreamOutboxDAL.deleteByIds).not.toHaveBeenCalled();+ expect(auditLogStreamOutboxDAL.commitDeliveryResult).toHaveBeenCalledTimes(1);+ const call = auditLogStreamOutboxDAL.commitDeliveryResult.mock.calls[0][0] as {+ successIds: number[];+ retriable: { rows: TFailedStreamRow[]; nextRetryAt: Date } | null;+ exhausted: TFailedStreamRow[];+ };+ expect(call.successIds).toEqual([]);+ expect(call.retriable?.rows.map(({ row }) => row.id)).toEqual([1]);+ expect(call.retriable?.rows[0].errorMessage).toEqual(expect.stringContaining(FAILURE_MESSAGE));+ expect(call.exhausted).toEqual([]);});test("routes rows that hit MAX_ATTEMPTS to DLQ instead of retry", async () => {@@ -125,13 +141,16 @@ describe("audit-log-stream-outbox-service drainStream failure wiring", () => {await service.drainStream({ streamId: STREAM_ID, orgId: ORG_ID, provider: PROVIDER });expect(onStreamFailure).toHaveBeenCalledTimes(1);- expect(auditLogStreamOutboxDAL.applyBatchFailure).toHaveBeenCalledTimes(1);- const call = auditLogStreamOutboxDAL.applyBatchFailure.mock.calls[0][0] as {- retriable: unknown;- exhausted: TAuditLogStreamOutboxRow[];+ expect(auditLogStreamOutboxDAL.commitDeliveryResult).toHaveBeenCalledTimes(1);+ const call = auditLogStreamOutboxDAL.commitDeliveryResult.mock.calls[0][0] as {+ successIds: number[];+ retriable: { rows: TFailedStreamRow[]; nextRetryAt: Date } | null;+ exhausted: TFailedStreamRow[];};+ expect(call.successIds).toEqual([]);expect(call.retriable).toBeNull();expect(call.exhausted).toHaveLength(1);+ expect(call.exhausted[0].errorMessage).toEqual(expect.stringContaining(FAILURE_MESSAGE));});test("does not invoke onStreamFailure on the success path", async () => {@@ -143,8 +162,15 @@ describe("audit-log-stream-outbox-service drainStream failure wiring", () => {await service.drainStream({ streamId: STREAM_ID, orgId: ORG_ID, provider: PROVIDER });expect(onStreamFailure).not.toHaveBeenCalled();- expect(auditLogStreamOutboxDAL.deleteByIds).toHaveBeenCalledTimes(1);- expect(auditLogStreamOutboxDAL.applyBatchFailure).not.toHaveBeenCalled();+ expect(auditLogStreamOutboxDAL.commitDeliveryResult).toHaveBeenCalledTimes(1);+ const call = auditLogStreamOutboxDAL.commitDeliveryResult.mock.calls[0][0] as {+ successIds: number[];+ retriable: { rows: TFailedStreamRow[]; nextRetryAt: Date } | null;+ exhausted: TFailedStreamRow[];+ };+ expect(call.successIds).toEqual([1]);+ expect(call.retriable).toBeNull();+ expect(call.exhausted).toEqual([]);});test("stops draining after the first failed batch — does not claim another batch", async () => {@@ -157,6 +183,31 @@ describe("audit-log-stream-outbox-service drainStream failure wiring", () => {expect(auditLogStreamOutboxDAL.claimBatchForStream).toHaveBeenCalledTimes(1);});++ test("partial-chunk failure: commits delivered rows + retries failed ones in one call", async () => {+ const { service, auditLogStreamOutboxDAL } = createService();++ // maxLogs=1 → claim of 2 rows splits into 2 chunks. First send resolves,+ // second rejects: row 1 lands in successIds, row 2 in retriable. Both flow+ // through a single commitDeliveryResult so they share a transaction.+ getProviderBatchLimit.mockReturnValue({ maxLogs: 1, maxBytes: 4 * 1024 * 1024 });+ auditLogStreamOutboxDAL.claimBatchForStream+ .mockResolvedValueOnce([buildRow({ id: 1, auditLogId: "log-1" }), buildRow({ id: 2, auditLogId: "log-2" })])+ .mockResolvedValueOnce([]);+ batchStreamLog.mockResolvedValueOnce(undefined).mockRejectedValueOnce(new Error(FAILURE_MESSAGE));++ await service.drainStream({ streamId: STREAM_ID, orgId: ORG_ID, provider: PROVIDER });++ expect(auditLogStreamOutboxDAL.commitDeliveryResult).toHaveBeenCalledTimes(1);+ const call = auditLogStreamOutboxDAL.commitDeliveryResult.mock.calls[0][0] as {+ successIds: number[];+ retriable: { rows: TFailedStreamRow[]; nextRetryAt: Date } | null;+ exhausted: TFailedStreamRow[];+ };+ expect(call.successIds).toEqual([1]);+ expect(call.retriable?.rows.map(({ row }) => row.id)).toEqual([2]);+ expect(call.exhausted).toEqual([]);+ });});describe("audit-log-stream-outbox-service enqueueForLogs batch fanout", () => {@@ -164,8 +215,7 @@ describe("audit-log-stream-outbox-service enqueueForLogs batch fanout", () => {const auditLogStreamOutboxDAL = {batchInsert: vi.fn<(rows: unknown[]) => Promise<void>>(async () => undefined),claimBatchForStream: vi.fn(async () => []),- deleteByIds: vi.fn(async () => undefined),- applyBatchFailure: vi.fn(async () => undefined),+ commitDeliveryResult: vi.fn(async () => undefined),recoverStaleClaims: vi.fn(async () => ({ retried: 0, movedToDlq: 0 }))};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 bb6df87858..dd67765ec0 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@@ -7,12 +7,17 @@ import { logger } from "@app/lib/logger";import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";import { TKmsServiceFactory } from "@app/services/kms/kms-service";+import { chunkAuditLogsByBatchLimit } from "../audit-log-stream/audit-log-stream-batching";import { TAuditLogStreamDALFactory } from "../audit-log-stream/audit-log-stream-dal";import { LogProvider } from "../audit-log-stream/audit-log-stream-enums";import { LOG_STREAM_FACTORY_MAP } from "../audit-log-stream/audit-log-stream-factory";import { decryptLogStreamCredentials } from "../audit-log-stream/audit-log-stream-fns";import { TAuditLogStreamOutboxDALFactory } from "./audit-log-stream-outbox-dal";-import { TAuditLogStreamFlushJobData, TAuditLogStreamOutboxRow } from "./audit-log-stream-outbox-types";+import {+ TAuditLogStreamFlushJobData,+ TAuditLogStreamOutboxRow,+ TFailedStreamRow+} from "./audit-log-stream-outbox-types";// Debounce window: first writer for a stream enqueues a flush job delayed by this many ms.// Subsequent writers within the window are absorbed by the same job (SETNX is a no-op for them).@@ -203,50 +208,61 @@ export const auditLogStreamOutboxServiceFactory = ({const claimed = await auditLogStreamOutboxDAL.claimBatchForStream(streamId, BATCH_SIZE, workerId);if (claimed.length === 0) return;- const auditLogs = claimed.map((row) => row.payload);- try {- // eslint-disable-next-line no-await-in-loop- await providerImpl.batchStreamLog({ credentials, auditLogs });- // eslint-disable-next-line no-await-in-loop- await auditLogStreamOutboxDAL.deleteByIds(claimed.map((row) => row.id));- } catch (error) {- const errorMessage = truncateError(error);- const logMessage = formatErrorMessage(error);- logger.error(- error,- `audit-log-stream-outbox: batch delivery failed [streamId=${streamId}] [orgId=${orgId}] [provider=${provider}] [batchSize=${claimed.length}]: ${logMessage}`- );-- const exhausted: TAuditLogStreamOutboxRow[] = [];- const retriable: TAuditLogStreamOutboxRow[] = [];- for (const row of claimed) {- if (row.attempts + 1 >= MAX_ATTEMPTS) {- exhausted.push(row);- } else {- retriable.push(row);- }+ const chunks = chunkAuditLogsByBatchLimit(claimed, providerImpl.getProviderBatchLimit());+ const streamSuccess: TAuditLogStreamOutboxRow[] = [];+ const streamFail: TFailedStreamRow[] = [];+ for (const chunk of chunks) {+ try {+ // eslint-disable-next-line no-await-in-loop+ await providerImpl.batchStreamLog({ credentials, auditLogs: chunk.map((row) => row.payload) });+ streamSuccess.push(...chunk);+ } catch (error) {+ const logMessage = formatErrorMessage(error);+ logger.error(+ error,+ `audit-log-stream-outbox: batch delivery failed [streamId=${streamId}] [orgId=${orgId}] [provider=${provider}] [chunkSize=${chunk.length}]: ${logMessage}`+ );+ const errorMessage = truncateError(error);+ streamFail.push(...chunk.map((row) => ({ row, errorMessage })));}+ }- const retriableInput = retriable.length- ? {- ids: retriable.map((row) => row.id),- nextRetryAt: computeBackoff(Math.max(...retriable.map((row) => row.attempts + 1)))- }- : null;- // eslint-disable-next-line no-await-in-loop- await auditLogStreamOutboxDAL.applyBatchFailure({- retriable: retriableInput,- exhausted,- errorMessage- });+ const exhausted: TFailedStreamRow[] = [];+ const retriable: TFailedStreamRow[] = [];+ for (const failed of streamFail) {+ if (failed.row.attempts + 1 >= MAX_ATTEMPTS) {+ exhausted.push(failed);+ } else {+ retriable.push(failed);+ }+ }++ const retriableInput = retriable.length+ ? {+ rows: retriable,+ nextRetryAt: computeBackoff(Math.max(...retriable.map(({ row }) => row.attempts + 1)))+ }+ : null;++ // eslint-disable-next-line no-await-in-loop+ await auditLogStreamOutboxDAL.commitDeliveryResult({+ successIds: streamSuccess.map((row) => row.id),+ retriable: retriableInput,+ exhausted+ });+ if (streamFail.length > 0) {if (onStreamFailure) {+ const representativeError = streamFail.at(-1)?.errorMessage ?? "Unknown error";// eslint-disable-next-line no-await-in-loop- await Promise.resolve(onStreamFailure({ orgId, streamId, provider, errorMessage }));+ await Promise.resolve(onStreamFailure({ orgId, streamId, provider, errorMessage: representativeError }));}- // Stop draining on the first failure — let backoff govern the retry cadence- // instead of hammering a failing endpoint with the next batch.+ // Bail when this claim saw any failure. The inner loop already attempted+ // every chunk independently (so partial-success rows are committed+ // above), but hopping straight to the next claim risks compounding load+ // on a degraded endpoint — let backoff on the retriable rows govern+ // when we come back.return;}}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.tsindex 0fa4eed040..d10968ad23 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@@ -29,3 +29,11 @@ export type TAuditLogStreamFlushJobData = {orgId: string;provider: LogProvider;};++// Pairs an outbox row with the error its chunk hit during delivery. Different+// chunks of one claim can fail with different errors, so the worker collects+// these and the DAL groups by message when writing back to retry / DLQ.+export type TFailedStreamRow = {+ row: TAuditLogStreamOutboxRow;+ errorMessage: string;+};diff --git a/backend/src/ee/services/audit-log-stream/audit-log-stream-batching.test.ts b/backend/src/ee/services/audit-log-stream/audit-log-stream-batching.test.tsnew file mode 100644index 0000000000..81f79b2ea0--- /dev/null+++ b/backend/src/ee/services/audit-log-stream/audit-log-stream-batching.test.ts@@ -0,0 +1,105 @@+import { describe, expect, test } from "vitest";++import { TAuditLogs } from "@app/db/schemas";++import { TAuditLogStreamOutboxRow } from "../audit-log-stream-outbox/audit-log-stream-outbox-types";+import { chunkAuditLogsByBatchLimit } from "./audit-log-stream-batching";+import { TLogStreamFactoryProviderBatchLimit } from "./audit-log-stream-types";++// The chunker only reads `.payload` from each row, so test fixtures use a+// minimal row stub. `padBytes` lets us drive the byte-cap branch deterministically.+const buildRow = (idx: number, padBytes = 0): TAuditLogStreamOutboxRow =>+ ({+ id: idx,+ payload: {+ id: `log-${idx.toString().padStart(6, "0")}`,+ eventMetadata: { pad: "x".repeat(padBytes) }+ } as unknown as TAuditLogs+ }) as TAuditLogStreamOutboxRow;++// A roomy limit used when we want chunks driven purely by count.+const COUNT_BOUND_LIMIT: TLogStreamFactoryProviderBatchLimit = { maxLogs: 4, maxBytes: 10 * 1024 * 1024 };+// A small byte cap that forces splits regardless of count.+const BYTE_BOUND_LIMIT: TLogStreamFactoryProviderBatchLimit = { maxLogs: 10_000, maxBytes: 1_024 };++describe("chunkAuditLogsByBatchLimit", () => {+ test("returns no chunks for an empty input", () => {+ expect(chunkAuditLogsByBatchLimit([], COUNT_BOUND_LIMIT)).toEqual([]);+ });++ test("returns a single chunk when both caps fit", () => {+ const rows = [buildRow(1), buildRow(2), buildRow(3)];+ const chunks = chunkAuditLogsByBatchLimit(rows, COUNT_BOUND_LIMIT);+ expect(chunks).toHaveLength(1);+ expect(chunks[0]).toEqual(rows);+ });++ test("respects the count cap", () => {+ const rows = Array.from({ length: COUNT_BOUND_LIMIT.maxLogs + 1 }, (_, i) => buildRow(i));++ const chunks = chunkAuditLogsByBatchLimit(rows, COUNT_BOUND_LIMIT);++ expect(chunks).toHaveLength(2);+ expect(chunks[0]).toHaveLength(COUNT_BOUND_LIMIT.maxLogs);+ expect(chunks[1]).toHaveLength(1);+ });++ test("respects the byte cap", () => {+ // Two rows each just over half the byte cap → one chunk apiece.+ const padBytes = Math.floor(BYTE_BOUND_LIMIT.maxBytes / 2);+ const rows = [buildRow(1, padBytes), buildRow(2, padBytes)];++ const chunks = chunkAuditLogsByBatchLimit(rows, BYTE_BOUND_LIMIT);++ expect(chunks).toHaveLength(2);+ expect(chunks[0]).toHaveLength(1);+ expect(chunks[1]).toHaveLength(1);+ for (const chunk of chunks) {+ const bytes = Buffer.byteLength(JSON.stringify(chunk[0].payload), "utf8");+ expect(bytes).toBeLessThanOrEqual(BYTE_BOUND_LIMIT.maxBytes);+ }+ });++ test("emits an oversized single row as its own singleton chunk", () => {+ const small = buildRow(1);+ const oversized = buildRow(2, BYTE_BOUND_LIMIT.maxBytes + 100);+ const trailing = buildRow(3);++ const chunks = chunkAuditLogsByBatchLimit([small, oversized, trailing], BYTE_BOUND_LIMIT);++ expect(chunks).toHaveLength(3);+ expect(chunks[0]).toEqual([small]);+ expect(chunks[1]).toEqual([oversized]);+ expect(chunks[2]).toEqual([trailing]);+ });++ test("packs greedily — fills each chunk before opening the next", () => {+ const rows = Array.from({ length: COUNT_BOUND_LIMIT.maxLogs * 2 + 1 }, (_, i) => buildRow(i));++ const chunks = chunkAuditLogsByBatchLimit(rows, COUNT_BOUND_LIMIT);++ expect(chunks).toHaveLength(3);+ expect(chunks[0]).toHaveLength(COUNT_BOUND_LIMIT.maxLogs);+ expect(chunks[1]).toHaveLength(COUNT_BOUND_LIMIT.maxLogs);+ expect(chunks[2]).toHaveLength(1);+ // No row dropped or duplicated.+ expect(chunks.flat()).toEqual(rows);+ });++ test("handles a mix of count- and byte-bounded packing", () => {+ // maxLogs=4 / maxBytes=1KB: a few medium-sized payloads partition by bytes+ // well before the count cap is reached.+ const limit: TLogStreamFactoryProviderBatchLimit = { maxLogs: 4, maxBytes: 1_024 };+ const padBytes = Math.floor(limit.maxBytes / 3);+ const rows = [buildRow(1, padBytes), buildRow(2, padBytes), buildRow(3, padBytes), buildRow(4, padBytes)];++ const chunks = chunkAuditLogsByBatchLimit(rows, limit);++ expect(chunks.flat()).toHaveLength(4);+ expect(chunks.length).toBeGreaterThanOrEqual(2);+ for (const chunk of chunks) {+ const bytes = chunk.reduce((s, r) => s + Buffer.byteLength(JSON.stringify(r.payload), "utf8"), 0);+ expect(bytes).toBeLessThanOrEqual(limit.maxBytes);+ }+ });+});diff --git a/backend/src/ee/services/audit-log-stream/audit-log-stream-batching.ts b/backend/src/ee/services/audit-log-stream/audit-log-stream-batching.tsnew file mode 100644index 0000000000..69b24c5b5b--- /dev/null+++ b/backend/src/ee/services/audit-log-stream/audit-log-stream-batching.ts@@ -0,0 +1,44 @@+import { TAuditLogs } from "@app/db/schemas";++import { TAuditLogStreamOutboxRow } from "../audit-log-stream-outbox/audit-log-stream-outbox-types";+import { TLogStreamFactoryProviderBatchLimit } from "./audit-log-stream-types";++const sizeOf = (log: TAuditLogs): number => Buffer.byteLength(JSON.stringify(log), "utf8");++export const chunkAuditLogsByBatchLimit = (+ auditLogs: TAuditLogStreamOutboxRow[],+ limit: TLogStreamFactoryProviderBatchLimit+): TAuditLogStreamOutboxRow[][] => {+ if (auditLogs.length === 0) return [];++ const chunks: TAuditLogStreamOutboxRow[][] = [];+ let current: TAuditLogStreamOutboxRow[] = [];+ let currentBytes = 0;++ for (const log of auditLogs) {+ const logBytes = sizeOf(log.payload);++ if (logBytes > limit.maxBytes) {+ if (current.length > 0) {+ chunks.push(current);+ current = [];+ currentBytes = 0;+ }+ chunks.push([log]);+ } else {+ const wouldExceedCount = current.length + 1 > limit.maxLogs;+ const wouldExceedBytes = currentBytes + logBytes > limit.maxBytes;+ if (wouldExceedCount || wouldExceedBytes) {+ chunks.push(current);+ current = [log];+ currentBytes = logBytes;+ } else {+ current.push(log);+ currentBytes += logBytes;+ }+ }+ }++ if (current.length > 0) chunks.push(current);+ return chunks;+};diff --git a/backend/src/ee/services/audit-log-stream/audit-log-stream-types.ts b/backend/src/ee/services/audit-log-stream/audit-log-stream-types.tsindex c1e8ac85aa..bfa29cd614 100644--- a/backend/src/ee/services/audit-log-stream/audit-log-stream-types.ts+++ b/backend/src/ee/services/audit-log-stream/audit-log-stream-types.ts@@ -36,7 +36,15 @@ export type TLogStreamFactoryBatchStreamLog<C extends TAuditLogStreamCredentialsauditLogs: TAuditLogs[];}) => Promise<void>;+export type TLogStreamFactoryProviderBatchLimit = {+ maxLogs: number;+ maxBytes: number;+};++export type TLogStreamFactoryGetProviderBatchLimit = () => TLogStreamFactoryProviderBatchLimit;+export type TLogStreamFactory<C extends TAuditLogStreamCredentials> = () => {validateCredentials: TLogStreamFactoryValidateCredentials<C>;batchStreamLog: TLogStreamFactoryBatchStreamLog<C>;+ getProviderBatchLimit: TLogStreamFactoryGetProviderBatchLimit;};diff --git a/backend/src/ee/services/audit-log-stream/azure/azure-provider-factory.ts b/backend/src/ee/services/audit-log-stream/azure/azure-provider-factory.tsindex 43778a9902..df8a0dee53 100644--- a/backend/src/ee/services/audit-log-stream/azure/azure-provider-factory.ts+++ b/backend/src/ee/services/audit-log-stream/azure/azure-provider-factory.ts@@ -5,7 +5,11 @@ import { BadRequestError } from "@app/lib/errors";import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";import { AUDIT_LOG_STREAM_BATCH_TIMEOUT, AUDIT_LOG_STREAM_TIMEOUT } from "../../audit-log/audit-log-queue";-import { TLogStreamFactoryBatchStreamLog, TLogStreamFactoryValidateCredentials } from "../audit-log-stream-types";+import {+ TLogStreamFactoryBatchStreamLog,+ TLogStreamFactoryGetProviderBatchLimit,+ TLogStreamFactoryValidateCredentials+} from "../audit-log-stream-types";import { TAzureProviderCredentials } from "./azure-provider-types";function buildAzureEvent(event: { createdAt?: Date | string } & Record<string, unknown>) {@@ -97,8 +101,14 @@ export const AzureProviderFactory = () => {);};+ const getProviderBatchLimit: TLogStreamFactoryGetProviderBatchLimit = () => ({+ maxLogs: 400,+ maxBytes: 900 * 1024+ });+return {validateCredentials,- batchStreamLog+ batchStreamLog,+ getProviderBatchLimit};};diff --git a/backend/src/ee/services/audit-log-stream/cribl/cribl-provider-factory.ts b/backend/src/ee/services/audit-log-stream/cribl/cribl-provider-factory.tsindex 5ed85a199a..aff688699d 100644--- a/backend/src/ee/services/audit-log-stream/cribl/cribl-provider-factory.ts+++ b/backend/src/ee/services/audit-log-stream/cribl/cribl-provider-factory.ts@@ -5,7 +5,11 @@ import { BadRequestError } from "@app/lib/errors";import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";import { AUDIT_LOG_STREAM_BATCH_TIMEOUT, AUDIT_LOG_STREAM_TIMEOUT } from "../../audit-log/audit-log-queue";-import { TLogStreamFactoryBatchStreamLog, TLogStreamFactoryValidateCredentials } from "../audit-log-stream-types";+import {+ TLogStreamFactoryBatchStreamLog,+ TLogStreamFactoryGetProviderBatchLimit,+ TLogStreamFactoryValidateCredentials+} from "../audit-log-stream-types";import { TCriblProviderCredentials } from "./cribl-provider-types";export const CriblProviderFactory = () => {@@ -57,8 +61,14 @@ export const CriblProviderFactory = () => {});};+ const getProviderBatchLimit: TLogStreamFactoryGetProviderBatchLimit = () => ({+ maxLogs: 900,+ maxBytes: 4 * 1024 * 1024+ });+return {validateCredentials,- batchStreamLog+ batchStreamLog,+ getProviderBatchLimit};};diff --git a/backend/src/ee/services/audit-log-stream/custom/custom-provider-factory.ts b/backend/src/ee/services/audit-log-stream/custom/custom-provider-factory.tsindex 95899526d0..f495405ad2 100644--- a/backend/src/ee/services/audit-log-stream/custom/custom-provider-factory.ts+++ b/backend/src/ee/services/audit-log-stream/custom/custom-provider-factory.ts@@ -5,7 +5,11 @@ import { BadRequestError } from "@app/lib/errors";import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";import { AUDIT_LOG_STREAM_BATCH_TIMEOUT, AUDIT_LOG_STREAM_TIMEOUT } from "../../audit-log/audit-log-queue";-import { TLogStreamFactoryBatchStreamLog, TLogStreamFactoryValidateCredentials } from "../audit-log-stream-types";+import {+ TLogStreamFactoryBatchStreamLog,+ TLogStreamFactoryGetProviderBatchLimit,+ TLogStreamFactoryValidateCredentials+} from "../audit-log-stream-types";import { TCustomProviderCredentials } from "./custom-provider-types";export const CustomProviderFactory = () => {@@ -65,8 +69,14 @@ export const CustomProviderFactory = () => {});};+ const getProviderBatchLimit: TLogStreamFactoryGetProviderBatchLimit = () => ({+ maxLogs: 400,+ maxBytes: 800 * 1024+ });+return {validateCredentials,- batchStreamLog+ batchStreamLog,+ getProviderBatchLimit};};diff --git a/backend/src/ee/services/audit-log-stream/datadog/datadog-provider-factory.ts b/backend/src/ee/services/audit-log-stream/datadog/datadog-provider-factory.tsindex 8e5bafe44b..52c943a439 100644--- a/backend/src/ee/services/audit-log-stream/datadog/datadog-provider-factory.ts+++ b/backend/src/ee/services/audit-log-stream/datadog/datadog-provider-factory.ts@@ -6,7 +6,11 @@ import { BadRequestError } from "@app/lib/errors";import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";import { AUDIT_LOG_STREAM_BATCH_TIMEOUT, AUDIT_LOG_STREAM_TIMEOUT } from "../../audit-log/audit-log-queue";-import { TLogStreamFactoryBatchStreamLog, TLogStreamFactoryValidateCredentials } from "../audit-log-stream-types";+import {+ TLogStreamFactoryBatchStreamLog,+ TLogStreamFactoryGetProviderBatchLimit,+ TLogStreamFactoryValidateCredentials+} from "../audit-log-stream-types";import { TDatadogProviderCredentials } from "./datadog-provider-types";function createPayload(event: Record<string, unknown>) {@@ -64,8 +68,14 @@ export const DatadogProviderFactory = () => {});};+ const getProviderBatchLimit: TLogStreamFactoryGetProviderBatchLimit = () => ({+ maxLogs: 900,+ maxBytes: 4 * 1024 * 1024+ });+return {validateCredentials,- batchStreamLog+ batchStreamLog,+ getProviderBatchLimit};};diff --git a/backend/src/ee/services/audit-log-stream/splunk/splunk-provider-factory.ts b/backend/src/ee/services/audit-log-stream/splunk/splunk-provider-factory.tsindex 40fe4f8879..122b01960d 100644--- a/backend/src/ee/services/audit-log-stream/splunk/splunk-provider-factory.ts+++ b/backend/src/ee/services/audit-log-stream/splunk/splunk-provider-factory.ts@@ -6,7 +6,11 @@ import { BadRequestError } from "@app/lib/errors";import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";import { AUDIT_LOG_STREAM_BATCH_TIMEOUT, AUDIT_LOG_STREAM_TIMEOUT } from "../../audit-log/audit-log-queue";-import { TLogStreamFactoryBatchStreamLog, TLogStreamFactoryValidateCredentials } from "../audit-log-stream-types";+import {+ TLogStreamFactoryBatchStreamLog,+ TLogStreamFactoryGetProviderBatchLimit,+ TLogStreamFactoryValidateCredentials+} from "../audit-log-stream-types";import { TSplunkProviderCredentials } from "./splunk-provider-types";function createPayload(event: Record<string, unknown>) {@@ -83,8 +87,14 @@ export const SplunkProviderFactory = () => {});};+ const getProviderBatchLimit: TLogStreamFactoryGetProviderBatchLimit = () => ({+ maxLogs: 400,+ maxBytes: 800 * 1024+ });+return {validateCredentials,- batchStreamLog+ batchStreamLog,+ getProviderBatchLimit};};diff --git a/backend/src/ee/services/audit-log/audit-log-dal.ts b/backend/src/ee/services/audit-log/audit-log-dal.tsindex a5a8981125..88e901265b 100644--- a/backend/src/ee/services/audit-log/audit-log-dal.ts+++ b/backend/src/ee/services/audit-log/audit-log-dal.ts@@ -6,12 +6,12 @@ import { TDbClient } from "@app/db";import { TableName, TAuditLogs, TAuditLogsInsert } from "@app/db/schemas";import { getConfig } from "@app/lib/config/env";import { DatabaseError, GatewayTimeoutError } from "@app/lib/errors";+import { chunkArray } from "@app/lib/fn";import { ormify, selectAllTableCols, TOrmify } from "@app/lib/knex";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;