Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

chore: pipeline blob storage cleanup deletes and batch tombstone inserts (#14910)

Valery Meleshkin8532971d91f9
diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.ts
index c5a7fcc31c..cfa170c913 100644
--- a/packages/shared/src/env.ts
+++ b/packages/shared/src/env.ts
@@ -281,6 +281,13 @@ const EnvSchema = z.object({
LANGFUSE_ENABLE_BLOB_STORAGE_FILE_LOG: z
.enum(["true", "false"])
.default("true"),
+ // Max concurrent S3 deleteFiles requests the blob-storage cleanup consumer
+ // keeps in flight. Bounds memory and backpressures the ClickHouse ref stream.
+ LANGFUSE_BLOB_STORAGE_DELETE_S3_CONCURRENCY: z.coerce
+ .number()
+ .min(1)
+ .max(20)
+ .default(5),
// V4 write mode. Mirrors worker/src/env.ts so the web package can gate
// public API routes that rely on the legacy traces/observations tables.
diff --git a/packages/shared/src/server/data-deletion/ingestionFileDeletion.ts b/packages/shared/src/server/data-deletion/ingestionFileDeletion.ts
index 87faae86a3..8dd057810d 100644
--- a/packages/shared/src/server/data-deletion/ingestionFileDeletion.ts
+++ b/packages/shared/src/server/data-deletion/ingestionFileDeletion.ts
@@ -1,3 +1,4 @@
+import { Readable } from "stream";
import {
getBlobStorageByProjectId,
getBlobStorageByProjectIdAndEntityIds,
@@ -9,12 +10,39 @@ import { logger } from "../logger";
import { env } from "../../env";
import { clickhouseClient } from "../clickhouse/client";
import { buildClickHouseLogComment } from "../clickhouse/queryTags";
-import { getS3EventStorageClient } from "../s3";
+import { getS3EventStorageClient, S3_DELETE_OBJECTS_CHUNK_SIZE } from "../s3";
-export const deleteIngestionEventsFromS3AndClickhouseForScores = async (p: {
- projectId: string;
- scoreIds: string[];
-}) => {
+// Derive the default from the S3 DeleteObjects chunk size so a full chunk is
+// exactly one S3 API request (plus its internal retries) and the two can't
+// drift.
+const DEFAULT_S3_CHUNK_SIZE = S3_DELETE_OBJECTS_CHUNK_SIZE;
+// ClickHouse best practice batches inserts at 10k–100k rows; small tombstone
+// inserts create part-count pressure on blob_storage_file_log.
+const DEFAULT_TOMBSTONE_FLUSH_SIZE = 10_000;
+
+/**
+ * Tuning knobs for the blob-storage cleanup pipeline. All optional; defaults are
+ * production values. Tests inject tiny values to exercise chunking, batching, and
+ * the concurrency bound cheaply.
+ */
+type BlobCleanupPipelineOptions = {
+ // Refs per S3 deleteFiles call. Default matches the StorageService internal
+ // DeleteObjectsCommand chunk (900) so one dispatch is exactly one S3 request.
+ s3ChunkSize?: number;
+ // Max concurrent deleteFiles calls in flight; backpressures the ClickHouse ref
+ // stream and bounds resident memory. Defaults to the shared env knob.
+ s3Concurrency?: number;
+ // Refs buffered before a single tombstone insert. Larger batches mean fewer,
+ // bigger inserts (ClickHouse best practice; less part-count pressure).
+ tombstoneFlushSize?: number;
+};
+
+export const deleteIngestionEventsFromS3AndClickhouseForScores = async (
+ p: {
+ projectId: string;
+ scoreIds: string[];
+ } & BlobCleanupPipelineOptions,
+) => {
const stream = getBlobStorageByProjectIdAndEntityIds(
p.projectId,
"score",
@@ -24,15 +52,20 @@ export const deleteIngestionEventsFromS3AndClickhouseForScores = async (p: {
return removeIngestionEventsFromS3AndDeleteClickhouseRefs({
projectId: p.projectId,
stream,
+ s3ChunkSize: p.s3ChunkSize,
+ s3Concurrency: p.s3Concurrency,
+ tombstoneFlushSize: p.tombstoneFlushSize,
});
};
export const removeIngestionEventsFromS3AndDeleteClickhouseRefsForTraces =
- async (p: {
- projectId: string;
- traceIds: string[];
- includeEventsTable?: boolean;
- }) => {
+ async (
+ p: {
+ projectId: string;
+ traceIds: string[];
+ includeEventsTable?: boolean;
+ } & BlobCleanupPipelineOptions,
+ ) => {
const stream = getBlobStorageByProjectIdAndTraceIds(
p.projectId,
p.traceIds,
@@ -42,12 +75,16 @@ export const removeIngestionEventsFromS3AndDeleteClickhouseRefsForTraces =
return removeIngestionEventsFromS3AndDeleteClickhouseRefs({
projectId: p.projectId,
stream: stream,
+ s3ChunkSize: p.s3ChunkSize,
+ s3Concurrency: p.s3Concurrency,
+ tombstoneFlushSize: p.tombstoneFlushSize,
});
};
export const removeIngestionEventsFromS3AndDeleteClickhouseRefsForProject = (
projectId: string,
cutOffDate: Date | undefined,
+ options?: BlobCleanupPipelineOptions,
) => {
const stream = cutOffDate
? getBlobStorageByProjectIdBeforeDate(projectId, cutOffDate)
@@ -56,49 +93,114 @@ export const removeIngestionEventsFromS3AndDeleteClickhouseRefsForProject = (
return removeIngestionEventsFromS3AndDeleteClickhouseRefs({
projectId: projectId,
stream: stream,
+ s3ChunkSize: options?.s3ChunkSize,
+ s3Concurrency: options?.s3Concurrency,
+ tombstoneFlushSize: options?.tombstoneFlushSize,
});
};
-async function removeIngestionEventsFromS3AndDeleteClickhouseRefs(p: {
- projectId: string;
- stream: AsyncGenerator<BlobStorageFileRefRecordReadType>;
-}) {
- const { projectId, stream } = p;
+/**
+ * Groups `source` into arrays of at most `size` elements, in order. The final
+ * group may be smaller than `size`.
+ */
+async function* chunk<T>(
+ source: AsyncIterable<T>,
+ size: number,
+): AsyncGenerator<T[]> {
+ let batch: T[] = [];
+ for await (const item of source) {
+ batch.push(item);
+ if (batch.length >= size) {
+ yield batch;
+ batch = [];
+ }
+ }
+ if (batch.length > 0) yield batch;
+}
- let batch = 0;
+async function removeIngestionEventsFromS3AndDeleteClickhouseRefs(
+ p: {
+ projectId: string;
+ stream: AsyncGenerator<BlobStorageFileRefRecordReadType>;
+ } & BlobCleanupPipelineOptions,
+) {
+ const { projectId, stream } = p;
+ // Cap at the S3 DeleteObjects chunk size: deleteFiles re-chunks internally at
+ // that limit, so a larger value would turn one dispatch into several S3
+ // requests and inflate the real in-flight request count past s3Concurrency.
+ const s3ChunkSize = Math.min(
+ p.s3ChunkSize ?? DEFAULT_S3_CHUNK_SIZE,
+ S3_DELETE_OBJECTS_CHUNK_SIZE,
+ );
+ const s3Concurrency =
+ p.s3Concurrency ?? env.LANGFUSE_BLOB_STORAGE_DELETE_S3_CONCURRENCY;
+ const tombstoneFlushSize =
+ p.tombstoneFlushSize ?? DEFAULT_TOMBSTONE_FLUSH_SIZE;
- let blobStorageRefs: BlobStorageFileRefRecordReadType[] = [];
const eventStorageClient = getS3EventStorageClient(
env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET,
);
- for await (const eventLog of stream) {
- blobStorageRefs.push(eventLog);
- if (blobStorageRefs.length > 500) {
- // Delete the current batch and reset the list
- await eventStorageClient.deleteFiles(
- blobStorageRefs.map((r) => r.bucket_path),
- );
- // soft delete the blob storage references in clickhouse
- await softDeleteInClickhouse(blobStorageRefs, {
- projectId,
- });
- batch++;
+ let pendingTombstones: BlobStorageFileRefRecordReadType[] = [];
+ let dispatchedBatches = 0;
+ let flushes = 0;
+
+ const flushTombstones = async () => {
+ if (pendingTombstones.length === 0) {
+ return;
+ }
+ const toFlush = pendingTombstones;
+ pendingTombstones = [];
+ await softDeleteInClickhouse(toFlush, { projectId });
+ flushes++;
+ logger.info(
+ `Tombstoned ${toFlush.length} blob storage refs (flush ${flushes}) for project ${projectId}`,
+ );
+ };
+
+ // Cleanup is at-least-once: a ref reaches `pendingTombstones` only when the
+ // `.map` stage yields it, i.e. strictly after its chunk's `deleteFiles` call
+ // resolved -- so a ref can never be hidden from retry discovery while its S3
+ // object still exists (the one direction that would leak permanently).
+ // (`Readable.map`'s typings report `Readable`/`any` for the mapped async
+ // iterator; the cast only restores the loop variable's real type, it doesn't
+ // relax the function's signature.)
+ const mapped = Readable.from(chunk(stream, s3ChunkSize)).map(
+ async (refs: BlobStorageFileRefRecordReadType[]) => {
+ dispatchedBatches++;
logger.info(
- `Deleted batch ${batch} of size ${blobStorageRefs.length} for ${projectId} of deleting s3 refs`,
+ `Dispatched S3 delete batch ${dispatchedBatches} of ${refs.length} refs for project ${projectId}`,
);
- blobStorageRefs = [];
+ // deleteFiles already retries 3x internally; a rejection here is terminal.
+ await eventStorageClient.deleteFiles(refs.map((r) => r.bucket_path));
+ return refs;
+ },
+ { concurrency: s3Concurrency },
+ );
+
+ try {
+ for await (const deletedRefs of mapped as AsyncIterable<
+ BlobStorageFileRefRecordReadType[]
+ >) {
+ pendingTombstones.push(...deletedRefs);
+ if (pendingTombstones.length >= tombstoneFlushSize) {
+ await flushTombstones();
+ }
}
+ } finally {
+ // Tombstone whatever has been deleted but not yet flushed -- the final
+ // partial batch on success, or the already-succeeded chunks on error --
+ // so a retry resumes past them instead of redoing their deletes. Runs on
+ // both paths; flushTombstones() no-ops when the buffer is empty, so it
+ // never double-inserts. A throw here on the error path replaces the
+ // original error, which is acceptable: both outcomes just mean "retry",
+ // and every un-tombstoned ref stays FINAL-visible and idempotently
+ // re-deletable regardless.
+ await flushTombstones();
}
- // Delete any remaining files
- await eventStorageClient.deleteFiles(
- blobStorageRefs.map((r) => r.bucket_path),
- );
- await softDeleteInClickhouse(blobStorageRefs, {
- projectId,
- });
+
logger.info(
- `Deleted last batch ${batch} of size ${blobStorageRefs.length} for ${projectId} of deleting s3 refs`,
+ `Completed blob storage cleanup for project ${projectId}: ${dispatchedBatches} S3 delete batches, ${flushes} tombstone flushes`,
);
}
diff --git a/packages/shared/src/server/s3/index.ts b/packages/shared/src/server/s3/index.ts
index 7cc4ded6e1..6cdc47321c 100644
--- a/packages/shared/src/server/s3/index.ts
+++ b/packages/shared/src/server/s3/index.ts
@@ -4,6 +4,8 @@ import {
StorageServiceFactory,
} from "../services/StorageService";
+export { S3_DELETE_OBJECTS_CHUNK_SIZE } from "../services/StorageService";
+
let s3MediaStorageClient: StorageService;
let s3EventStorageClient: StorageService;
diff --git a/packages/shared/src/server/services/StorageService.ts b/packages/shared/src/server/services/StorageService.ts
index 96ee4b4758..ce237e6b3b 100644
--- a/packages/shared/src/server/services/StorageService.ts
+++ b/packages/shared/src/server/services/StorageService.ts
@@ -271,6 +271,11 @@ export interface StorageService {
deleteFiles(paths: string[]): Promise<void>;
}
+// Keys per S3 DeleteObjects request. The API hard limit is 1000; 900 leaves a
+// margin. Exported so callers that batch their own deletes can size a batch to
+// exactly one request instead of duplicating the number.
+export const S3_DELETE_OBJECTS_CHUNK_SIZE = 900;
+
export class StorageServiceFactory {
/**
* Get an instance of the StorageService
@@ -925,7 +930,7 @@ class S3StorageService implements StorageService {
}
async deleteFilesNonRetrying(paths: string[]): Promise<void> {
- const chunkSize = 900;
+ const chunkSize = S3_DELETE_OBJECTS_CHUNK_SIZE;
const chunks = [];
for (let i = 0; i < paths.length; i += chunkSize) {
diff --git a/worker/src/__tests__/ingestionFileDeletion.test.ts b/worker/src/__tests__/ingestionFileDeletion.test.ts
new file mode 100644
index 0000000000..2601f86c01
--- /dev/null
+++ b/worker/src/__tests__/ingestionFileDeletion.test.ts
@@ -0,0 +1,331 @@
+import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
+import waitForExpect from "wait-for-expect";
+import {
+ clickhouseClient,
+ createOrgProjectAndApiKey,
+ getBlobStorageByProjectId,
+ getS3EventStorageClient,
+ removeIngestionEventsFromS3AndDeleteClickhouseRefsForProject,
+ StorageService,
+ StorageServiceFactory,
+} from "@langfuse/shared/src/server";
+import { randomUUID } from "crypto";
+import { env } from "../env";
+
+type SeededRef = { entityId: string; bucketPath: string };
+
+describe("ingestion file deletion pipeline", () => {
+ let eventStorageService: StorageService;
+
+ beforeAll(() => {
+ eventStorageService = StorageServiceFactory.getInstance({
+ accessKeyId: env.LANGFUSE_S3_EVENT_UPLOAD_ACCESS_KEY_ID,
+ secretAccessKey: env.LANGFUSE_S3_EVENT_UPLOAD_SECRET_ACCESS_KEY,
+ bucketName: env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET,
+ endpoint: env.LANGFUSE_S3_EVENT_UPLOAD_ENDPOINT,
+ region: env.LANGFUSE_S3_EVENT_UPLOAD_REGION,
+ forcePathStyle: env.LANGFUSE_S3_EVENT_UPLOAD_FORCE_PATH_STYLE === "true",
+ });
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ /**
+ * Seeds `count` blob storage refs for a project: uploads a matching S3 object
+ * for each ref (so real deletes have something to remove) and inserts the log
+ * rows. Returns the refs so tests can reason about individual bucket paths.
+ */
+ const seedRefs = async (
+ projectId: string,
+ count: number,
+ opts?: { uploadFiles?: boolean },
+ ): Promise<SeededRef[]> => {
+ const refs: SeededRef[] = Array.from({ length: count }, () => {
+ const entityId = randomUUID();
+ return {
+ entityId,
+ bucketPath: `${projectId}/traces/${entityId}-trace.json`,
+ };
+ });
+
+ if (opts?.uploadFiles !== false) {
+ await Promise.all(
+ refs.map((r) =>
+ eventStorageService.uploadFile({
+ fileName: r.bucketPath,
+ fileType: "application/json",
+ data: JSON.stringify({ hello: "world" }),
+ }),
+ ),
+ );
+ }
+
+ await clickhouseClient().insert({
+ table: "blob_storage_file_log",
+ format: "JSONEachRow",
+ values: refs.map((r) => ({
+ id: randomUUID(),
+ project_id: projectId,
+ entity_type: "trace",
+ entity_id: r.entityId,
+ event_id: randomUUID(),
+ bucket_name: env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET,
+ bucket_path: r.bucketPath,
+ created_at: new Date().getTime(),
+ updated_at: new Date().getTime(),
+ })),
+ });
+
+ return refs;
+ };
+
+ /** Collects the bucket paths still visible under FINAL (i.e. not tombstoned). */
+ const visibleBucketPaths = async (projectId: string): Promise<string[]> => {
+ const paths: string[] = [];
+ for await (const ref of getBlobStorageByProjectId(projectId)) {
+ paths.push(ref.bucket_path);
+ }
+ return paths;
+ };
+
+ it("deletes every S3 object, tombstones every ref, and batches tombstone flushes independently of the S3 chunk size", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+ const refs = await seedRefs(projectId, 13);
+
+ const eventStorageClient = getS3EventStorageClient(
+ env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET,
+ );
+ const deleteFilesSpy = vi.spyOn(eventStorageClient, "deleteFiles");
+ // Count only the tombstone inserts issued by the consumer (seeding already
+ // happened above, before the spy was installed).
+ const insertSpy = vi.spyOn(clickhouseClient(), "insert");
+
+ // chunk 3 => ceil(13/3) = 5 S3 deletes; flush 5 with concurrency 1 (so
+ // completion order is deterministic) => flushes at buffer sizes 6, 6, 1 = 3
+ // tombstone inserts. The batching is driven by the flush threshold, NOT by
+ // the S3 chunk count (which would be 5 under the old one-insert-per-chunk
+ // shape).
+ await removeIngestionEventsFromS3AndDeleteClickhouseRefsForProject(
+ projectId,
+ undefined,
+ { s3ChunkSize: 3, s3Concurrency: 1, tombstoneFlushSize: 5 },
+ );
+
+ // Every ref tombstoned (invisible under FINAL).
+ expect(await visibleBucketPaths(projectId)).toHaveLength(0);
+
+ // Every S3 object removed.
+ const files = await eventStorageService.listFiles(projectId);
+ expect(files).toHaveLength(0);
+
+ // Exactly one S3 delete per chunk.
+ expect(deleteFilesSpy).toHaveBeenCalledTimes(5);
+ for (const call of deleteFilesSpy.mock.calls) {
+ expect((call[0] as string[]).length).toBeLessThanOrEqual(3);
+ }
+
+ // Tombstone inserts are batched by the flush threshold, not by S3 chunk.
+ expect(insertSpy).toHaveBeenCalledTimes(3);
+ expect(insertSpy.mock.calls.length).toBeLessThan(
+ deleteFilesSpy.mock.calls.length,
+ );
+
+ // Sanity: all seeded paths were passed to some delete call.
+ const deletedPaths = new Set(
+ deleteFilesSpy.mock.calls.flatMap((call) => call[0] as string[]),
+ );
+ for (const ref of refs) {
+ expect(deletedPaths.has(ref.bucketPath)).toBe(true);
+ }
+ });
+
+ it("rethrows on a failed chunk, tombstones only the chunks that succeeded, and leaves the failed chunk retry-able", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+ await seedRefs(projectId, 13);
+
+ const eventStorageClient = getS3EventStorageClient(
+ env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET,
+ );
+ const realDeleteFiles =
+ eventStorageClient.deleteFiles.bind(eventStorageClient);
+
+ let callIndex = 0;
+ const succeededPaths: string[] = [];
+ let failedPaths: string[] = [];
+ // Concurrency 1 => strictly sequential dispatch, so the 3rd chunk (index 2)
+ // fails only after chunks 0 and 1 fully resolved. Fail-fast then abandons
+ // the remaining chunks.
+ vi.spyOn(eventStorageClient, "deleteFiles").mockImplementation(
+ async (paths: string[]) => {
+ const idx = callIndex++;
+ if (idx === 2) {
+ failedPaths = [...paths];
+ throw new Error("Simulated S3 delete failure");
+ }
+ await realDeleteFiles(paths);
+ succeededPaths.push(...paths);
+ },
+ );
+
+ await expect(
+ removeIngestionEventsFromS3AndDeleteClickhouseRefsForProject(
+ projectId,
+ undefined,
+ { s3ChunkSize: 3, s3Concurrency: 1, tombstoneFlushSize: 5 },
+ ),
+ ).rejects.toThrow("Simulated S3 delete failure");
+
+ // Chunks 0 and 1 succeeded (6 refs); chunk 2 failed (3 refs); chunks 3 and 4
+ // were never dispatched (fail-fast) => 7 refs remain visible.
+ expect(succeededPaths).toHaveLength(6);
+ expect(failedPaths).toHaveLength(3);
+
+ const visible = new Set(await visibleBucketPaths(projectId));
+
+ // Succeeded chunks tombstoned so a retry does not redo their S3 work.
+ for (const path of succeededPaths) {
+ expect(visible.has(path)).toBe(false);
+ }
+ // Failed chunk stays visible for a retry (its refs were never tombstoned).
+ for (const path of failedPaths) {
+ expect(visible.has(path)).toBe(true);
+ }
+ // 13 total - 6 succeeded = 7 still visible (3 failed + 4 never dispatched).
+ expect(visible.size).toBe(7);
+ });
+
+ it("checkpoints already-deleted chunks on failure even when the flush threshold was never reached", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+ await seedRefs(projectId, 13);
+
+ const eventStorageClient = getS3EventStorageClient(
+ env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET,
+ );
+ const realDeleteFiles =
+ eventStorageClient.deleteFiles.bind(eventStorageClient);
+
+ let callIndex = 0;
+ const succeededPaths: string[] = [];
+ let failedPaths: string[] = [];
+ vi.spyOn(eventStorageClient, "deleteFiles").mockImplementation(
+ async (paths: string[]) => {
+ const idx = callIndex++;
+ if (idx === 2) {
+ failedPaths = [...paths];
+ throw new Error("Simulated S3 delete failure");
+ }
+ await realDeleteFiles(paths);
+ succeededPaths.push(...paths);
+ },
+ );
+
+ await expect(
+ removeIngestionEventsFromS3AndDeleteClickhouseRefsForProject(
+ projectId,
+ undefined,
+ // tombstoneFlushSize (100) far exceeds the 6 refs the succeeding chunks
+ // produce, so the in-loop flush never fires: the ONLY thing that can
+ // tombstone them before the error propagates is the finally-flush. This
+ // pins that fail-path checkpoint against regressing back to "no error
+ // handling", which would leave all 6 visible and redone on retry.
+ { s3ChunkSize: 3, s3Concurrency: 1, tombstoneFlushSize: 100 },
+ ),
+ ).rejects.toThrow("Simulated S3 delete failure");
+
+ expect(succeededPaths).toHaveLength(6);
+ expect(failedPaths).toHaveLength(3);
+
+ const visible = new Set(await visibleBucketPaths(projectId));
+
+ // The finally-flush checkpointed the succeeded chunks despite never hitting
+ // the flush threshold, so a retry does not redo their S3 deletes.
+ for (const path of succeededPaths) {
+ expect(visible.has(path)).toBe(false);
+ }
+ // The failed chunk was never tombstoned -- it stays retry-able.
+ for (const path of failedPaths) {
+ expect(visible.has(path)).toBe(true);
+ }
+ // 6 checkpointed => 7 still visible (3 failed + 4 never dispatched).
+ expect(visible.size).toBe(7);
+ });
+
+ it("never exceeds the configured concurrency while dispatching, and resumes as deletes settle", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+ // No S3 objects needed: deleteFiles is fully mocked with deferred promises.
+ await seedRefs(projectId, 5, { uploadFiles: false });
+
+ const eventStorageClient = getS3EventStorageClient(
+ env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET,
+ );
+
+ let activeDeletes = 0;
+ let maxActiveDeletes = 0;
+ const resolvers: Array<() => void> = [];
+ const deleteFilesSpy = vi
+ .spyOn(eventStorageClient, "deleteFiles")
+ .mockImplementation(() => {
+ activeDeletes++;
+ maxActiveDeletes = Math.max(maxActiveDeletes, activeDeletes);
+ return new Promise<void>((resolve) => {
+ resolvers.push(() => {
+ activeDeletes--;
+ resolve();
+ });
+ });
+ });
+
+ // chunk 1 => one delete per ref (5 chunks); concurrency 2; huge flush so no
+ // tombstone flush interferes mid-stream.
+ const runPromise =
+ removeIngestionEventsFromS3AndDeleteClickhouseRefsForProject(
+ projectId,
+ undefined,
+ { s3ChunkSize: 1, s3Concurrency: 2, tombstoneFlushSize: 100 },
+ );
+
+ // Pool saturates at exactly 2 and then blocks: no third dispatch yet.
+ await waitForExpect(() => {
+ expect(deleteFilesSpy).toHaveBeenCalledTimes(2);
+ });
+ expect(activeDeletes).toBe(2);
+ expect(maxActiveDeletes).toBe(2);
+ expect(deleteFilesSpy).toHaveBeenCalledTimes(2);
+
+ // Settle one delete => exactly one more dispatch proceeds, bound still holds.
+ resolvers[0]();
+ await waitForExpect(() => {
+ expect(deleteFilesSpy).toHaveBeenCalledTimes(3);
+ });
+ expect(maxActiveDeletes).toBe(2);
+
+ // Drain the rest so the pipeline completes; keep resolving new deferreds as
+ // they are dispatched (event-loop driven, no fixed delays).
+ let settled = false;
+ runPromise.then(
+ () => {
+ settled = true;
+ },
+ () => {
+ settled = true;
+ },
+ );
+ let nextResolverIndex = 1;
+ const pump = () => {
+ while (nextResolverIndex < resolvers.length) {
+ resolvers[nextResolverIndex++]();
+ }
+ if (!settled) setImmediate(pump);
+ };
+ pump();
+
+ await runPromise;
+
+ // The bound was never breached across the whole run, and every chunk ran.
+ expect(maxActiveDeletes).toBe(2);
+ expect(deleteFilesSpy).toHaveBeenCalledTimes(5);
+ expect(await visibleBucketPaths(projectId)).toHaveLength(0);
+ });
+});