Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions apps/api/src/routes/organization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -433,6 +433,11 @@ organization.openapi(updateOrganization, async (c) => {
}
if (autoTopUpEnabled !== undefined) {
updateData.autoTopUpEnabled = autoTopUpEnabled;
if (autoTopUpEnabled && !userOrganization.organization?.autoTopUpEnabled) {
updateData.paymentFailureCount = 0;
updateData.lastPaymentFailureAt = null;
updateData.paymentFailureStartedAt = null;
}
}
if (autoTopUpThreshold !== undefined) {
updateData.autoTopUpThreshold = autoTopUpThreshold.toString();
Expand Down
4 changes: 4 additions & 0 deletions apps/api/src/stripe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -568,6 +568,7 @@ async function recordCreditTopUp({
credits: sql`${tables.organization.credits} + ${finalCreditAmount}`,
paymentFailureCount: 0,
lastPaymentFailureAt: null,
paymentFailureStartedAt: null,
})
.where(eq(tables.organization.id, organizationId));

Expand Down Expand Up @@ -810,6 +811,7 @@ async function handlePaymentIntentSucceeded(
credits: sql`${tables.organization.credits} + ${finalCreditAmount}`,
paymentFailureCount: 0,
lastPaymentFailureAt: null,
paymentFailureStartedAt: null,
})
.where(eq(tables.organization.id, organizationId));

Expand Down Expand Up @@ -1027,6 +1029,7 @@ async function handlePaymentIntentFailed(
// Calculate new failure count and check if we should send an email
const previousFailureCount = organization.paymentFailureCount ?? 0;
const previousFailureAt = organization.lastPaymentFailureAt;
const failureStartedAt = organization.paymentFailureStartedAt ?? new Date();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Scope failure streak to auto top-up intents

paymentFailureStartedAt is initialized for every payment_intent.payment_failed event, including non-auto-top-up failures (e.g., manual top-ups or subscription-related payment intents resolved via customer lookup). With this commit’s worker logic (apps/worker/src/worker.ts) disabling auto top-up after 7 days based on this field, unrelated payment failures can now shut off auto top-up for an organization even when auto top-up itself hasn’t been failing. Restrict setting this streak start (and the associated counters used for disablement) to verified auto top-up failures only (such as events carrying the auto top-up transaction metadata).

Useful? React with 👍 / 👎.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Restrict failure streak updates to auto top-up intents

This assignment updates the 7-day disable timer for every payment_intent.payment_failed event that resolves an organization, not just failed auto top-ups. Fresh evidence in this commit: the transactionId-missing path explicitly handles manual/non-auto payments ("for manual top-ups or payments without transactionId") and still flows into this unconditional paymentFailureStartedAt update, while processAutoTopUp now disables auto top-up once that timestamp is 7 days old. A failed non-auto payment can therefore disable auto top-up even when auto top-up itself was healthy.

Useful? React with 👍 / 👎.

const newFailureCount = previousFailureCount + 1;

// Update organization with new failure count and timestamp
Expand All @@ -1035,6 +1038,7 @@ async function handlePaymentIntentFailed(
.set({
paymentFailureCount: newFailureCount,
lastPaymentFailureAt: new Date(),
paymentFailureStartedAt: failureStartedAt,
})
Comment on lines 1032 to 1042

Copilot AI Mar 28, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

failureStartedAt currently falls back to new Date() when paymentFailureStartedAt is null. For existing rows (new column) that already have paymentFailureCount > 0/lastPaymentFailureAt populated, this effectively “restarts” the streak on the next failure and can delay auto top-up disabling. Consider falling back to organization.lastPaymentFailureAt (if present) before new Date() so the streak start is preserved as best as possible for pre-existing data.

Copilot uses AI. Check for mistakes.
.where(eq(tables.organization.id, organizationId));

Expand Down
6 changes: 6 additions & 0 deletions apps/gateway/src/lib/rate-limit.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ describe("Rate Limiting", () => {
referralEarnings: "0",
paymentFailureCount: 0,
lastPaymentFailureAt: null,
paymentFailureStartedAt: null,
isPersonal: false,
devPlan: "none" as const,
devPlanCreditsUsed: "0",
Expand Down Expand Up @@ -156,6 +157,7 @@ describe("Rate Limiting", () => {
referralEarnings: "0",
paymentFailureCount: 0,
lastPaymentFailureAt: null,
paymentFailureStartedAt: null,
isPersonal: false,
devPlan: "none" as const,
devPlanCreditsUsed: "0",
Expand Down Expand Up @@ -214,6 +216,7 @@ describe("Rate Limiting", () => {
referralEarnings: "0",
paymentFailureCount: 0,
lastPaymentFailureAt: null,
paymentFailureStartedAt: null,
isPersonal: false,
devPlan: "none" as const,
devPlanCreditsUsed: "0",
Expand Down Expand Up @@ -266,6 +269,7 @@ describe("Rate Limiting", () => {
referralEarnings: "0",
paymentFailureCount: 0,
lastPaymentFailureAt: null,
paymentFailureStartedAt: null,
isPersonal: false,
devPlan: "none" as const,
devPlanCreditsUsed: "0",
Expand Down Expand Up @@ -326,6 +330,7 @@ describe("Rate Limiting", () => {
referralEarnings: "0",
paymentFailureCount: 0,
lastPaymentFailureAt: null,
paymentFailureStartedAt: null,
isPersonal: false,
devPlan: "none" as const,
devPlanCreditsUsed: "0",
Expand Down Expand Up @@ -386,6 +391,7 @@ describe("Rate Limiting", () => {
referralEarnings: "0",
paymentFailureCount: 0,
lastPaymentFailureAt: null,
paymentFailureStartedAt: null,
isPersonal: false,
devPlan: "none" as const,
devPlanCreditsUsed: "0",
Expand Down
84 changes: 81 additions & 3 deletions apps/worker/src/worker.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,20 @@ import { afterAll, beforeEach, describe, expect, test } from "vitest";

import { db, tables } from "@llmgateway/db";

import { acquireLock } from "./worker.js";
import { acquireLock, processAutoTopUp } from "./worker.js";

describe("worker", () => {
beforeEach(async () => {
// Clean up lock table before each test
await db.delete(tables.transaction);
await db.delete(tables.paymentMethod);
await db.delete(tables.organization);
await db.delete(tables.lock);
});

afterAll(async () => {
// Clean up after all tests
await db.delete(tables.transaction);
await db.delete(tables.paymentMethod);
await db.delete(tables.organization);
await db.delete(tables.lock);
});

Expand Down Expand Up @@ -108,4 +112,78 @@ describe("worker", () => {
expect(lockKeys).toEqual([lockKey1, lockKey2].sort());
});
});

describe("processAutoTopUp", () => {
test("should disable auto top-up after 7 days of payment failures", async () => {
const eightDaysMs = 8 * 24 * 60 * 60 * 1000;

await db.insert(tables.organization).values({
id: "org-disable-auto-topup",
name: "Disable Auto Top-up",
billingEmail: "billing@example.com",
credits: "0",
autoTopUpEnabled: true,
autoTopUpThreshold: "10",
autoTopUpAmount: "10",
paymentFailureCount: 8,
lastPaymentFailureAt: new Date(),
paymentFailureStartedAt: new Date(Date.now() - eightDaysMs),
});

await processAutoTopUp();

const organization = await db.query.organization.findFirst({
where: {
id: {
eq: "org-disable-auto-topup",
},
},
});

expect(organization?.autoTopUpEnabled).toBe(false);
expect(organization?.paymentFailureCount).toBe(0);
expect(organization?.lastPaymentFailureAt).toBeNull();
expect(organization?.paymentFailureStartedAt).toBeNull();

const transactions = await db.query.transaction.findMany({
where: {
organizationId: {
eq: "org-disable-auto-topup",
},
},
});
expect(transactions).toHaveLength(0);
});

test("should keep auto top-up enabled when failures are newer than 7 days", async () => {
const sixDaysMs = 6 * 24 * 60 * 60 * 1000;

await db.insert(tables.organization).values({
id: "org-keep-auto-topup",
name: "Keep Auto Top-up",
billingEmail: "billing@example.com",
credits: "0",
autoTopUpEnabled: true,
autoTopUpThreshold: "10",
autoTopUpAmount: "10",
paymentFailureCount: 3,
lastPaymentFailureAt: new Date(),
paymentFailureStartedAt: new Date(Date.now() - sixDaysMs),
});

await processAutoTopUp();

const organization = await db.query.organization.findFirst({
where: {
id: {
eq: "org-keep-auto-topup",
},
},
});

expect(organization?.autoTopUpEnabled).toBe(true);
expect(organization?.paymentFailureCount).toBe(3);
expect(organization?.paymentFailureStartedAt).not.toBeNull();
});
});
});
26 changes: 25 additions & 1 deletion apps/worker/src/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,9 @@ const AUTO_TOPUP_LOCK_KEY = "auto_topup_check";
const CREDIT_PROCESSING_LOCK_KEY = "credit_processing";
const DATA_RETENTION_LOCK_KEY = "data_retention_cleanup";
const LOCK_DURATION_MINUTES = 5;
const AUTO_TOPUP_DISABLE_AFTER_DAYS = 7;
const AUTO_TOPUP_DISABLE_AFTER_MS =
AUTO_TOPUP_DISABLE_AFTER_DAYS * 24 * 60 * 60 * 1000;

// Configuration for batch processing
const BATCH_SIZE = Number(process.env.CREDIT_BATCH_SIZE) || 100;
Expand Down Expand Up @@ -161,7 +164,7 @@ async function releaseLock(key: string): Promise<void> {
await db.delete(tables.lock).where(eq(tables.lock.key, key));
}

async function processAutoTopUp(): Promise<void> {
export async function processAutoTopUp(): Promise<void> {
const lockAcquired = await acquireLock(AUTO_TOPUP_LOCK_KEY);
if (!lockAcquired) {
return;
Expand Down Expand Up @@ -215,6 +218,27 @@ async function processAutoTopUp(): Promise<void> {
}
}

if (
org.paymentFailureStartedAt &&
Date.now() - org.paymentFailureStartedAt.getTime() >=
Comment on lines +221 to +223

Copilot AI Mar 28, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The disable-after-7-days check relies solely on org.paymentFailureStartedAt. For existing organizations that already have paymentFailureCount > 0/lastPaymentFailureAt set (from before this column existed), paymentFailureStartedAt will be null and auto top-up will never be disabled until another failure occurs. Consider initializing/backfilling paymentFailureStartedAt (e.g., from lastPaymentFailureAt) when it’s missing but failures are present, or ensure the migration backfills it.

Suggested change
if (
org.paymentFailureStartedAt &&
Date.now() - org.paymentFailureStartedAt.getTime() >=
// Backfill paymentFailureStartedAt for legacy organizations if needed
let paymentFailureStartedAt = org.paymentFailureStartedAt;
if (
!paymentFailureStartedAt &&
org.paymentFailureCount > 0 &&
org.lastPaymentFailureAt
) {
await db
.update(tables.organization)
.set({
paymentFailureStartedAt: org.lastPaymentFailureAt,
})
.where(eq(tables.organization.id, org.id));
paymentFailureStartedAt = org.lastPaymentFailureAt;
}
if (
paymentFailureStartedAt &&
Date.now() - paymentFailureStartedAt.getTime() >=

Copilot uses AI. Check for mistakes.
AUTO_TOPUP_DISABLE_AFTER_MS
) {
await db
.update(tables.organization)
.set({
autoTopUpEnabled: false,
paymentFailureCount: 0,
lastPaymentFailureAt: null,
paymentFailureStartedAt: null,
})
.where(eq(tables.organization.id, org.id));

logger.warn(
`Disabled auto top-up for organization ${org.id} after ${AUTO_TOPUP_DISABLE_AFTER_DAYS} days of payment failures`,
);
continue;
}

// Check for exponential backoff based on payment failure count
// Backoff intervals: 1h, 2h, 4h, 8h, 16h, 24h (capped)
if (org.lastPaymentFailureAt && (org.paymentFailureCount ?? 0) > 0) {
Expand Down
1 change: 1 addition & 0 deletions packages/db/migrations/1774728743_solid_randall.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
ALTER TABLE "organization" ADD COLUMN "payment_failure_started_at" timestamp;
Loading
Loading