πͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(blobstorage): disable export on deterministic customer-config faults (#14628)
Niklas Semmler780a583f7e09
diff --git a/packages/shared/src/server/services/email/blobStorageExportFailed/BlobStorageExportFailedEmailTemplate.tsx b/packages/shared/src/server/services/email/blobStorageExportFailed/BlobStorageExportFailedEmailTemplate.tsxindex cfa43af04b..f60766e8dd 100644--- a/packages/shared/src/server/services/email/blobStorageExportFailed/BlobStorageExportFailedEmailTemplate.tsx+++ b/packages/shared/src/server/services/email/blobStorageExportFailed/BlobStorageExportFailedEmailTemplate.tsx@@ -17,18 +17,23 @@ import {type BlobStorageExportFailedEmailTemplateProps = {projectName: string;settingsUrl: string;+ // When true, the export was turned off after repeated failures and the+ // customer must fix their config and re-enable it β not a transient failure.+ disabled?: boolean;};export const BlobStorageExportFailedEmailTemplate = ({projectName,settingsUrl,+ disabled = false,}: BlobStorageExportFailedEmailTemplateProps) => {+ const preview = disabled+ ? `Blob storage export disabled for project "${projectName}"`+ : `Blob storage export failed for project "${projectName}"`;return (<Html><Head />- <Preview>- Blob storage export failed for project "{projectName}"- </Preview>+ <Preview>{preview}</Preview><Tailwind><Body className="bg-background my-auto mx-auto font-sans"><Container className="mx-auto my-10 w-[465px] rounded border border-solid border-[#eaeaea] p-5">@@ -44,12 +49,29 @@ export const BlobStorageExportFailedEmailTemplate = ({<Section><Heading className="mx-0 my-[30px] p-0 text-center text-2xl font-normal text-black">- Blob Storage Export Failed+ {disabled+ ? "Blob Storage Export Disabled"+ : "Blob Storage Export Failed"}</Heading><Text className="text-gray-700 text-sm leading-6">- The scheduled blob storage export for project "- {projectName}" has failed. Review the integration settings- to see the error details and resolve the issue.+ {disabled ? (+ <>+ The blob storage export for project "{projectName}+ " has been disabled after repeated failures. This+ usually means the destination configuration or credentials+ are no longer valid. Once you have updated them, simply+ re-enable the export in the integration settings and it will+ pick up right where it left off.+ </>+ ) : (+ <>+ The scheduled blob storage export for project "+ {projectName}" has failed after multiple attempts. It+ will be retried automatically at the next scheduled export.+ If the issue persists, review the integration settings to+ see the error details.+ </>+ )}</Text></Section>@@ -66,8 +88,9 @@ export const BlobStorageExportFailedEmailTemplate = ({<Section><Text className="text-[#666666] text-[12px] leading-[24px]">- This notification was sent to project admins regarding a failed- blob storage export for project "{projectName}".+ This notification was sent to project admins regarding a{" "}+ {disabled ? "disabled" : "failed"} blob storage export for+ project "{projectName}".</Text></Section></Container>diff --git a/packages/shared/src/server/services/email/blobStorageExportFailed/sendBlobStorageExportFailedEmail.ts b/packages/shared/src/server/services/email/blobStorageExportFailed/sendBlobStorageExportFailedEmail.tsindex dcccca6d13..06eef9d958 100644--- a/packages/shared/src/server/services/email/blobStorageExportFailed/sendBlobStorageExportFailedEmail.ts+++ b/packages/shared/src/server/services/email/blobStorageExportFailed/sendBlobStorageExportFailedEmail.ts@@ -18,6 +18,9 @@ export type SendBlobStorageExportFailedEmailParams = {projectName: string;settingsUrl: string;receiverEmails: string[];+ // When true, the export was disabled after repeated failures (needs the+ // customer to fix config and re-enable) rather than a transient failure.+ disabled?: boolean;};export const sendBlobStorageExportFailedEmail = async ({@@ -25,6 +28,7 @@ export const sendBlobStorageExportFailedEmail = async ({projectName,settingsUrl,receiverEmails,+ disabled = false,}: SendBlobStorageExportFailedEmailParams) => {if (!env.EMAIL_FROM_ADDRESS || !env.SMTP_CONNECTION_URL) {logger.error(@@ -40,11 +44,14 @@ export const sendBlobStorageExportFailedEmail = async ({try {const mailer = createMailTransport(env.SMTP_CONNECTION_URL);const safeProjectName = sanitizeEmailSubject(projectName);- const subject = `Blob storage export failed for "${safeProjectName}" β action required`;+ const subject = disabled+ ? `Blob storage export disabled for "${safeProjectName}" β action required`+ : `Blob storage export failed for "${safeProjectName}"`;const html = await render(BlobStorageExportFailedEmailTemplate({projectName: safeProjectName,settingsUrl,+ disabled,}),);diff --git a/web/src/features/blobstorage-integration/README.md b/web/src/features/blobstorage-integration/README.mdindex a6a186a896..afdfcf0fb8 100644--- a/web/src/features/blobstorage-integration/README.md+++ b/web/src/features/blobstorage-integration/README.md@@ -8,16 +8,18 @@ computed at read time by `deriveSyncStatus.ts`.| Field | Type | Written by ||---|---|---|-| `enabled` | boolean | Web (save) |+| `enabled` | boolean | Web (save), Worker (catch β disables on a final-attempt customer-fault) || `lastError` | string \| null | Worker (catch / success) || `lastSyncAt` | Date \| null | Worker (success) || `nextSyncAt` | Date \| null | Worker (success / empty-window), Web (save) || `runStartedAt` | Date \| null | Worker (start / end), Web (save clears it) |+| `lastFailureNotificationSentAt` | Date \| null | Worker (cooldown claim before the "failed" email), Web (save with enabled clears it) |## Derived states (precedence top-to-bottom)```-disabled β enabled = false+disabled β enabled = false (set by user save, or by the worker after a+ final-attempt customer-config/credential failure)error β lastError != nullrunning β runStartedAt != null AND age < 2hqueued β nextSyncAt <= now@@ -62,6 +64,11 @@ up_to_date β fallthroughβββββββββββββ ββββββββββ up_to_dateβ β error ββββββββββββββ βββββββββ+ β final-attempt customer-fault β enabled = false+ βΌ+ ββββββββββββ+ β disabled β+ ββββββββββββ```## Transition detail@@ -78,7 +85,9 @@ up_to_date β fallthrough| **running** | Worker: empty time window | `runStartedAt=null`, `nextSyncAt=now+frequency`, `lastError=null` | **up_to_date** (or **idle** if never synced) || **running** | Worker: export succeeds, caught up | `lastSyncAt=max`, `nextSyncAt=max+freq`, `lastError=null`, `runStartedAt=null` | **up_to_date** || **running** | Worker: export succeeds, not caught up | `lastSyncAt=max`, `nextSyncAt=now`, `lastError=null`, `runStartedAt=null` + re-enqueues job | **queued** (immediately) |-| **running** | Worker: export fails | `lastError=msg`, `lastErrorAt=now`, `runStartedAt=null` | **error** |+| **running** | Worker: export fails (retries left) | `lastError=msg`, `lastErrorAt=now`, `runStartedAt=null` (no email β a later retry may succeed) | **error** |+| **running** | Worker: export fails, retries exhausted | `lastError=msg`, `lastErrorAt=now`, `runStartedAt=null` (+ cooldown-gated "failed" email) | **error** |+| **running** | Worker: retries exhausted on a customer-config/credential failure | `lastError=msg`, `lastErrorAt=now`, `runStartedAt=null`, `enabled=false` (+ one-time "disabled" email, no cooldown) | **disabled** || **error** | User saves (enabled, same mode) | `runStartedAt=null`, `nextSyncAt=now` | stays **error** (`lastError` preserved; scheduler re-enqueues via `nextSyncAt`) || **error** | User clicks Run Now | Enqueues manual job (no DB write) | stays **error** until worker clears `lastError` (success or empty-window) || **running** | Stale `runStartedAt` > 2h | (no write β derived only) | falls through to **queued**, **idle**, or **up_to_date** |diff --git a/web/src/features/blobstorage-integration/service.ts b/web/src/features/blobstorage-integration/service.tsindex 96e242629f..41d8965be2 100644--- a/web/src/features/blobstorage-integration/service.ts+++ b/web/src/features/blobstorage-integration/service.ts@@ -179,6 +179,9 @@ export async function upsertBlobStorageIntegration(params: {// start-date logic takes effect instead of continuing from the// previous mode's lastSyncAt....(modeChanged ? { lastSyncAt: null, nextSyncAt: new Date() } : {}),+ // Saving enabled resets the failure-notification cooldown: the+ // customer just acted, so a fresh failure should email promptly.+ ...(data.enabled ? { lastFailureNotificationSentAt: null } : {}),runStartedAt: null,},});diff --git a/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts b/worker/src/__tests__/blobStorageIntegrationProcessing.test.tsindex 4bd9ff5fc9..d2740fc66e 100644--- a/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts+++ b/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts@@ -19,13 +19,22 @@ const originalCloudRegion = vi.hoisted(() => {// per-stage timing metrics are assertable.const mockRecordIncrement = vi.hoisted(() => vi.fn());const mockRecordHistogram = vi.hoisted(() => vi.fn());+// Stubbable endpoint preflight β the customer-fault tests reject it to drive an+// in-try failure without infra. Defaults to the real impl for other tests.+const mockValidateBlobStorageEndpoint = vi.hoisted(() => vi.fn());vi.mock("@langfuse/shared/src/server", async (importOriginal) => {const actual =await importOriginal<typeof import("@langfuse/shared/src/server")>();+ if (mockValidateBlobStorageEndpoint.getMockImplementation() === undefined) {+ mockValidateBlobStorageEndpoint.mockImplementation(+ actual.validateBlobStorageEndpoint,+ );+ }return {...actual,recordIncrement: mockRecordIncrement,recordHistogram: mockRecordHistogram,+ validateBlobStorageEndpoint: mockValidateBlobStorageEndpoint,};});@@ -176,6 +185,175 @@ describe("BlobStorageIntegrationProcessingJob", () => {});});+ // After BullMQ exhausts its retries, a customer-fault error disables the+ // integration; everything else keeps retrying as before.+ describe("customer-fault disable", () => {+ const originalV4Preview = env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN;++ afterEach(() => {+ (env as any).LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN =+ originalV4Preview;+ });++ // Minimal AWS SDK v3 S3 AccessDenied shape (high-confidence customer fault).+ const accessDeniedError = (): Error => {+ const err = new Error("Access Denied");+ err.name = "AccessDenied";+ Object.assign(err, {+ Code: "AccessDenied",+ $metadata: { httpStatusCode: 403 },+ });+ return err;+ };++ // endpoint must be non-null so the handler runs the preflight we stub.+ const createIntegration = async (projectId: string) => {+ await prisma.blobStorageIntegration.create({+ data: {+ projectId,+ type: BlobStorageIntegrationType.S3,+ bucketName,+ prefix: projectId,+ accessKeyId,+ secretAccessKey: encrypt(secretAccessKey),+ region: region ? region : "auto",+ endpoint: "https://customer-bucket.s3.example.com",+ forcePathStyle:+ env.LANGFUSE_S3_EVENT_UPLOAD_FORCE_PATH_STYLE === "true",+ enabled: true,+ exportFrequency: "daily",+ exportSource: "TRACES_OBSERVATIONS",+ lastSyncAt: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000),+ },+ });+ };++ const runAttempt = (projectId: string, attemptsMade: number) =>+ handleBlobStorageIntegrationProjectJob({+ data: { payload: { projectId } },+ attemptsMade,+ opts: { attempts: 5 },+ } as Job);++ // The notification runs fire-and-forget after the handler rejects; give+ // it time to land (or prove it never fires) before negative assertions.+ const settleBackgroundTasks = () =>+ new Promise((resolve) => setTimeout(resolve, 200));++ it("keeps the integration enabled and does not notify on a non-final customer-fault attempt", async () => {+ const { projectId } = await createOrgProjectAndApiKey();+ s3Prefix = projectId;+ await createIntegration(projectId);+ mockValidateBlobStorageEndpoint.mockRejectedValueOnce(+ accessDeniedError(),+ );++ await expect(runAttempt(projectId, 0)).rejects.toThrow(/access denied/i);+ await settleBackgroundTasks();++ const row = await prisma.blobStorageIntegration.findUniqueOrThrow({+ where: { projectId },+ });+ // BullMQ still has retries left, so we let it retry β no disable yet,+ // and no email either: a later retry may still succeed.+ expect(row.enabled).toBe(true);+ expect(row.lastError).toMatch(/access denied/i);+ expect(row.lastFailureNotificationSentAt).toBeNull();+ });++ it("disables the integration on the final exhausted customer-fault attempt", async () => {+ const { projectId } = await createOrgProjectAndApiKey();+ s3Prefix = projectId;+ await createIntegration(projectId);+ mockValidateBlobStorageEndpoint.mockRejectedValueOnce(+ accessDeniedError(),+ );++ await expect(runAttempt(projectId, 4)).rejects.toThrow(/access denied/i);+ await settleBackgroundTasks();++ const row = await prisma.blobStorageIntegration.findUniqueOrThrow({+ where: { projectId },+ });+ expect(row.enabled).toBe(false);+ expect(row.lastError).toMatch(/access denied/i);+ expect(row.lastErrorAt).not.toBeNull();+ // The "disabled" email bypasses the cooldown, so it must not claim it.+ expect(row.lastFailureNotificationSentAt).toBeNull();+ });++ it("does not disable on the final attempt of a non-customer-fault ('other') error", async () => {+ // Enriched source + V4 preview off => the guard throws a plain Error,+ // which the classifier treats as "other".+ (env as any).LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN = "false";+ const { projectId } = await createOrgProjectAndApiKey();+ s3Prefix = projectId;++ await prisma.blobStorageIntegration.create({+ data: {+ projectId,+ type: BlobStorageIntegrationType.S3,+ bucketName,+ prefix: s3Prefix,+ accessKeyId,+ secretAccessKey: encrypt(secretAccessKey),+ region: region ? region : "auto",+ endpoint: endpoint ? endpoint : null,+ forcePathStyle:+ env.LANGFUSE_S3_EVENT_UPLOAD_FORCE_PATH_STYLE === "true",+ enabled: true,+ exportFrequency: "daily",+ exportSource: "EVENTS",+ lastSyncAt: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000),+ },+ });++ await expect(runAttempt(projectId, 4)).rejects.toThrow(/enriched/i);++ const row = await prisma.blobStorageIntegration.findUniqueOrThrow({+ where: { projectId },+ });+ // "other" errors stay enabled and keep retrying on the next scheduled+ // run β but the run is exhausted, so the cooldown-gated informational+ // notification fires (observable via its atomic cooldown claim).+ expect(row.enabled).toBe(true);+ await vi.waitFor(async () => {+ const notified = await prisma.blobStorageIntegration.findUniqueOrThrow({+ where: { projectId },+ });+ expect(notified.lastFailureNotificationSentAt).not.toBeNull();+ });+ });++ it("suppresses the informational email when the integration was disabled mid-run", async () => {+ const { projectId } = await createOrgProjectAndApiKey();+ s3Prefix = projectId;+ await createIntegration(projectId);+ // Simulate a concurrent worker's customer-fault disable (or a user+ // toggle) landing mid-run, followed by a non-customer-fault failure:+ // "will retry at the next scheduled export" would be false.+ mockValidateBlobStorageEndpoint.mockImplementationOnce(async () => {+ await prisma.blobStorageIntegration.updateMany({+ where: { projectId },+ data: { enabled: false },+ });+ throw new Error("connection refused");+ });++ await expect(runAttempt(projectId, 4)).rejects.toThrow(+ /connection refused/i,+ );+ await settleBackgroundTasks();++ const row = await prisma.blobStorageIntegration.findUniqueOrThrow({+ where: { projectId },+ });+ expect(row.enabled).toBe(false);+ expect(row.lastError).toMatch(/connection refused/i);+ expect(row.lastFailureNotificationSentAt).toBeNull();+ });+ });+it("should not process when blob storage integration is disabled", async () => {const { projectId } = await createOrgProjectAndApiKey();s3Prefix = projectId;diff --git a/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts b/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.tsindex 3316c17f54..f14b4456a8 100644--- a/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts+++ b/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts@@ -47,6 +47,7 @@ import {} from "./abortClassification";import { isSigtermReceived } from "../health";import { TimedGzip, ZLIB_DEFAULT_LEVEL, type GzipStats } from "./gzipStream";+import { isCustomerFaultError } from "./isCustomerFaultError";import { ByteCounter, TimedByteCounter } from "./byteCounters";import { WORKER_HOST_ID } from "../../utils/hostId";import {@@ -1340,8 +1341,26 @@ export const handleBlobStorageIntegrationProjectJob = async (} catch (error) {const errorMessage = extractStorageErrorMessage(error);+ // A deterministic customer-config/credential fault can't succeed until the+ // customer fixes it. Once BullMQ exhausts its retries, disable the+ // integration so it stops re-scheduling and spamming. attemptsMade is+ // 0-based, so the final attempt is attempts - 1.+ const isFinalAttempt =+ (job.attemptsMade ?? 0) >= (job.opts?.attempts ?? 1) - 1;+ const disableForCustomerFault =+ isFinalAttempt && isCustomerFaultError(error);++ // True only for the worker that actually flips enabled trueβfalse, so the+ // "disabled" email (which bypasses the cooldown) is sent exactly once and+ // never claims a state we failed to write. The atomic claim also dedups+ // concurrent terminal failures β e.g. a scheduled run racing a manual Run+ // Now across pods, which have distinct jobIds and so aren't queue-deduped.+ let persistedDisable = false;+ let disableClaimRan = false;+ // Assume enabled when the read-back fails; worst case is today's email.+ let enabledAfterPersist = true;try {- await prisma.blobStorageIntegration.update({+ const updated = await prisma.blobStorageIntegration.update({where: { projectId },data: {lastError: errorMessage,@@ -1349,6 +1368,20 @@ export const handleBlobStorageIntegrationProjectJob = async (runStartedAt: null,},});+ enabledAfterPersist = updated.enabled;+ if (disableForCustomerFault) {+ const { count } = await prisma.blobStorageIntegration.updateMany({+ where: { projectId, enabled: true },+ data: { enabled: false },+ });+ disableClaimRan = true;+ persistedDisable = count === 1;+ if (persistedDisable) {+ logger.warn(+ `[BLOB INTEGRATION] Disabled blob storage integration for project ${projectId} after a customer-config/credential failure: ${errorMessage}`,+ );+ }+ }} catch (persistError) {logger.error(`[BLOB INTEGRATION] Failed to persist blob storage error for project ${projectId}`,@@ -1356,7 +1389,26 @@ export const handleBlobStorageIntegrationProjectJob = async ();}- notifyBlobStorageExportFailedInBackground(projectId);+ // Notify only after BullMQ exhausts its retries β an email on an earlier+ // attempt fires even when a later retry succeeds, and would double up+ // with the "disabled" email on customer faults. Skip only when a+ // concurrent terminal failure won the disable claim (the winner already+ // notified); if the claim never ran because persistence threw, fall back+ // to the informational email so the failure isn't silent.+ const lostDisableRaceToConcurrentRun =+ disableForCustomerFault && disableClaimRan && !persistedDisable;+ // The informational email promises a retry at the next scheduled run,+ // which is false once the integration is disabled (a concurrent run's+ // customer-fault disable or a user toggle mid-run) β skip it then.+ const disabledOutFromUnderUs =+ !disableForCustomerFault && !enabledAfterPersist;+ if (+ isFinalAttempt &&+ !lostDisableRaceToConcurrentRun &&+ !disabledOutFromUnderUs+ ) {+ notifyBlobStorageExportFailedInBackground(projectId, persistedDisable);+ }const chain = errorChainText(error);logger.error(@@ -1373,38 +1425,49 @@ export const handleBlobStorageIntegrationProjectJob = async (}};-function notifyBlobStorageExportFailedInBackground(projectId: string): void {+function notifyBlobStorageExportFailedInBackground(+ projectId: string,+ disabled = false,+): void {(async () => {try {- const cooldownMs =- env.LANGFUSE_BLOB_STORAGE_FAILURE_NOTIFICATION_COOLDOWN_HOURS *- 60 *- 60 *- 1000;-- // Atomic claim: set timestamp before sending to prevent duplicate emails on concurrent retries.- // If the email send subsequently fails, the cooldown still applies β the next failure- // after cooldown expiry will retry the notification.- const claimed = await prisma.blobStorageIntegration.updateMany({- where: {- projectId,- OR: [- { lastFailureNotificationSentAt: null },- {- lastFailureNotificationSentAt: {- lt: new Date(Date.now() - cooldownMs),+ // Called once per exhausted run. The cooldown gates across scheduled+ // runs (the scheduler re-enqueues every frequency period, and each+ // failing run would otherwise email again). The disable notification+ // bypasses it: it is a one-time, terminal event β the integration+ // won't run again until the customer re-enables it β and a cooldown+ // claim could silently drop the one email that says it was turned off.+ if (!disabled) {+ const cooldownMs =+ env.LANGFUSE_BLOB_STORAGE_FAILURE_NOTIFICATION_COOLDOWN_HOURS *+ 60 *+ 60 *+ 1000;++ // Atomic claim: set timestamp before sending to prevent duplicate emails on concurrent retries.+ // If the email send subsequently fails, the cooldown still applies β the next failure+ // after cooldown expiry will retry the notification.+ const claimed = await prisma.blobStorageIntegration.updateMany({+ where: {+ projectId,+ OR: [+ { lastFailureNotificationSentAt: null },+ {+ lastFailureNotificationSentAt: {+ lt: new Date(Date.now() - cooldownMs),+ },},- },- ],- },- data: { lastFailureNotificationSentAt: new Date() },- });+ ],+ },+ data: { lastFailureNotificationSentAt: new Date() },+ });- if (claimed.count === 0) {- logger.info(- `[BLOB INTEGRATION] Skipping failure notification for project ${projectId}, cooldown still active`,- );- return;+ if (claimed.count === 0) {+ logger.info(+ `[BLOB INTEGRATION] Skipping failure notification for project ${projectId}, cooldown still active`,+ );+ return;+ }}const emailEnv = {@@ -1442,6 +1505,7 @@ function notifyBlobStorageExportFailedInBackground(projectId: string): void {projectName,settingsUrl,receiverEmails: adminEmails,+ disabled,});} catch (error) {logger.error(diff --git a/worker/src/features/blobstorage/isCustomerFaultError.test.ts b/worker/src/features/blobstorage/isCustomerFaultError.test.tsnew file mode 100644index 0000000000..3f1922b145--- /dev/null+++ b/worker/src/features/blobstorage/isCustomerFaultError.test.ts@@ -0,0 +1,169 @@+import { describe, it, expect } from "vitest";+import { isCustomerFaultError } from "./isCustomerFaultError";++// Builds the wrapper the handler actually sees: StorageService.handleStorageError+// rethrows SDK errors as `new Error("Failed to ...", { cause: sdkError })`.+const wrapped = (sdkError: unknown): Error =>+ new Error("Failed to upload file to S3", { cause: sdkError });++// Minimal AWS SDK v3 S3ServiceException shape: `.name`/`.Code` carry the error+// code, `$metadata.httpStatusCode` carries the HTTP status.+const s3Error = (name: string, httpStatusCode: number): Error => {+ const err = new Error(`${name} error`);+ err.name = name;+ Object.assign(err, { Code: name, $metadata: { httpStatusCode } });+ return err;+};++// Minimal Azure @azure/storage-blob RestError shape: `.code` + `.statusCode`.+const azureError = (code: string, statusCode: number): Error => {+ const err = new Error(`${code} error`);+ err.name = "RestError";+ Object.assign(err, { code, statusCode });+ return err;+};++// Minimal GCS JSON-API error shape.+const gcsError = (+ code: number,+ reason: string,+): Error & { code: number; errors: { reason: string }[] } => {+ const err = new Error(`GCS ${reason}`) as Error & {+ code: number;+ errors: { reason: string }[];+ };+ Object.assign(err, { code, errors: [{ reason }] });+ return err;+};++describe("isCustomerFaultError", () => {+ describe("customer_fault β S3 / S3-compatible", () => {+ it.each([+ ["InvalidAccessKeyId", 403],+ ["SignatureDoesNotMatch", 403],+ ["AccessDenied", 403],+ ["AllAccessDisabled", 403],+ ["AccountProblem", 403],+ ["AuthorizationHeaderMalformed", 400],+ ["NoSuchBucket", 404],+ ["InvalidBucketName", 400],+ ])("classifies %s as customer_fault", (code, status) => {+ expect(isCustomerFaultError(wrapped(s3Error(code, status)))).toBe(true);+ });++ it("classifies a raw (unwrapped) S3 error too", () => {+ expect(isCustomerFaultError(s3Error("AccessDenied", 403))).toBe(true);+ });+ });++ describe("customer_fault β Azure", () => {+ it.each([+ ["AuthenticationFailed", 403],+ ["AuthorizationFailure", 403],+ ["AuthorizationPermissionMismatch", 403],+ ["InvalidAuthenticationInfo", 400],+ ["AccountIsDisabled", 403],+ ["InsufficientAccountPermissions", 403],+ ["ContainerNotFound", 404],+ ["InvalidResourceName", 400],+ ])("classifies %s as customer_fault", (code, status) => {+ expect(isCustomerFaultError(wrapped(azureError(code, status)))).toBe(+ true,+ );+ });+ });++ describe("customer_fault β GCS JSON API", () => {+ it("classifies 403 forbidden as customer_fault", () => {+ expect(isCustomerFaultError(wrapped(gcsError(403, "forbidden")))).toBe(+ true,+ );+ });+ });++ describe("customer_fault β bare HTTP status", () => {+ it("classifies a 401 with no recognized code as customer_fault", () => {+ const err = new Error("Unauthorized");+ Object.assign(err, { $metadata: { httpStatusCode: 401 } });+ expect(isCustomerFaultError(wrapped(err))).toBe(true);+ });+ });++ describe("other β transient / infra / unknown (bias toward investigation)", () => {+ it.each(["ETIMEDOUT", "ECONNRESET", "EAI_AGAIN", "ECONNREFUSED", "EPIPE"])(+ "classifies network error %s as other",+ (code) => {+ const err = new Error(`network ${code}`);+ Object.assign(err, { code });+ expect(isCustomerFaultError(wrapped(err))).toBe(false);+ },+ );++ it("classifies a 503 ServiceUnavailable as other", () => {+ expect(+ isCustomerFaultError(wrapped(s3Error("ServiceUnavailable", 503))),+ ).toBe(false);+ });++ it("classifies a 500 InternalError as other", () => {+ expect(isCustomerFaultError(wrapped(s3Error("InternalError", 500)))).toBe(+ false,+ );+ });++ it("classifies S3 SlowDown / throttling as other", () => {+ expect(isCustomerFaultError(wrapped(s3Error("SlowDown", 503)))).toBe(+ false,+ );+ });++ it("classifies a bare 403 with no recognized code as other (e.g. clock skew)", () => {+ expect(+ isCustomerFaultError(wrapped(s3Error("RequestTimeTooSkewed", 403))),+ ).toBe(false);+ });++ it("classifies a RequestTimeout as other", () => {+ expect(+ isCustomerFaultError(wrapped(s3Error("RequestTimeout", 400))),+ ).toBe(false);+ });++ it("classifies a plain application error as other", () => {+ expect(+ isCustomerFaultError(+ new Error("The configured export source includes enriched ..."),+ ),+ ).toBe(false);+ });++ it("classifies a GCS object-level notFound as other", () => {+ expect(isCustomerFaultError(wrapped(gcsError(404, "notFound")))).toBe(+ false,+ );+ });++ it("classifies null/undefined/non-error inputs as other", () => {+ expect(isCustomerFaultError(null)).toBe(false);+ expect(isCustomerFaultError(undefined)).toBe(false);+ expect(isCustomerFaultError("AccessDenied")).toBe(false);+ expect(isCustomerFaultError(403)).toBe(false);+ });+ });++ describe("cause-chain traversal", () => {+ it("finds a customer fault nested several causes deep", () => {+ const root = s3Error("InvalidAccessKeyId", 403);+ const mid = new Error("mid", { cause: root });+ const top = new Error("top", { cause: mid });+ expect(isCustomerFaultError(top)).toBe(true);+ });++ it("does not infinite-loop on a cyclic cause chain", () => {+ const a = new Error("a");+ const b = new Error("b", { cause: a });+ Object.assign(a, { cause: b });+ expect(isCustomerFaultError(a)).toBe(false);+ });+ });+});diff --git a/worker/src/features/blobstorage/isCustomerFaultError.ts b/worker/src/features/blobstorage/isCustomerFaultError.tsnew file mode 100644index 0000000000..c40753570b--- /dev/null+++ b/worker/src/features/blobstorage/isCustomerFaultError.ts@@ -0,0 +1,108 @@+// True when a caught blob-export error is a deterministic customer-config /+// credential fault. The handler uses this (after BullMQ exhausts retries) to+// disable the integration.+//+// Conservative allowlist of stable provider error codes, biased toward false:+// a false positive disables a working integration, a false negative only keeps+// retrying. Errors arrive wrapped via `new Error(..., { cause })`+// (StorageService.handleStorageError), so we walk the cause chain.++// AWS SDK v3 sets `.name`/`.Code`; Azure RestError sets `.code`. S3-compatible+// providers (incl. GCS S3-interop) surface the S3 codes.+const CUSTOMER_FAULT_ERROR_CODES = new Set<string>([+ // S3 β auth & credentials+ "InvalidAccessKeyId",+ "SignatureDoesNotMatch",+ "AccessDenied",+ "AllAccessDisabled",+ "AccountProblem",+ "AuthorizationHeaderMalformed",+ // S3 β bucket & path+ "NoSuchBucket",+ "InvalidBucketName",+ // Azure β auth & credentials+ "AuthenticationFailed",+ "AuthorizationFailure",+ "AuthorizationPermissionMismatch",+ "InvalidAuthenticationInfo",+ "AccountIsDisabled",+ "InsufficientAccountPermissions",+ // Azure β container & path+ "ContainerNotFound",+ "InvalidResourceName",+]);++// GCS JSON-API reasons (only reachable via a GCS-native client; S3-interop uses+// the S3 codes above). Narrow on purpose: object-level notFound stays `other`.+const CUSTOMER_FAULT_GCS_REASONS = new Set<string>(["forbidden"]);++const MAX_CAUSE_DEPTH = 10; // guard against cyclic `cause`++function* errorCauseChain(error: unknown): Generator<object> {+ let current: unknown = error;+ for (let depth = 0; depth < MAX_CAUSE_DEPTH; depth++) {+ if (!current || typeof current !== "object") return;+ yield current;+ current = (current as { cause?: unknown }).cause;+ }+}++// `.code` is overloaded by type: a number is a GCS HTTP status (here), a string+// is an Azure error code (extractErrorCodes). Split the reads if a future+// provider ever reports a numeric `code: 401` that isn't a credential failure.+function extractHttpStatus(err: object): number | undefined {+ const metaStatus = (err as { $metadata?: { httpStatusCode?: unknown } })+ .$metadata?.httpStatusCode;+ if (typeof metaStatus === "number") return metaStatus;++ const statusCode = (err as { statusCode?: unknown }).statusCode;+ if (typeof statusCode === "number") return statusCode;++ const numericCode = (err as { code?: unknown }).code;+ if (typeof numericCode === "number") return numericCode;++ return undefined;+}++function extractErrorCodes(err: object): string[] {+ const candidates = [+ (err as { name?: unknown }).name,+ (err as { Code?: unknown }).Code,+ (err as { code?: unknown }).code,+ ];+ return candidates.filter((c): c is string => typeof c === "string");+}++function extractGcsReasons(err: object): string[] {+ const errors = (err as { errors?: unknown }).errors;+ if (!Array.isArray(errors)) return [];+ return errors+ .map((e) =>+ e &&+ typeof e === "object" &&+ typeof (e as { reason?: unknown }).reason === "string"+ ? (e as { reason: string }).reason+ : undefined,+ )+ .filter((r): r is string => typeof r === "string");+}++function isCustomerFaultLink(err: object): boolean {+ if (extractErrorCodes(err).some((c) => CUSTOMER_FAULT_ERROR_CODES.has(c))) {+ return true;+ }+ // 401 = credentials rejected: unambiguous, so it trips without a code. A bare+ // 403/404 does not (e.g. clock-skew RequestTimeTooSkewed is a 403).+ if (extractHttpStatus(err) === 401) return true;+ if (extractGcsReasons(err).some((r) => CUSTOMER_FAULT_GCS_REASONS.has(r))) {+ return true;+ }+ return false;+}++export function isCustomerFaultError(error: unknown): boolean {+ for (const link of errorCauseChain(error)) {+ if (isCustomerFaultLink(link)) return true;+ }+ return false;+}