Skip to content

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

fix(billing): clear a pending ClickHouse Billing scheduled change before setting a new one (#17811)

Steffen Reuther3d9973e36508
diff --git a/web/src/__tests__/server/unit/chbBillingService.servertest.ts b/web/src/__tests__/server/unit/chbBillingService.servertest.ts
index aa9302722e..d879ad4d3f 100644
--- a/web/src/__tests__/server/unit/chbBillingService.servertest.ts
+++ b/web/src/__tests__/server/unit/chbBillingService.servertest.ts
@@ -110,6 +110,9 @@ describe("chbBillingService", () => {
update.mockResolvedValue({});
// Default: the claim succeeds. Tests that exercise the race override it.
executeRaw.mockResolvedValue(1);
+ // Default: no pending scheduled change, so the schedule-setting paths have
+ // nothing to clear first. Tests that exercise the clear override it.
+ clientMock.getAttachedPlan.mockResolvedValue({ id: ATTACHED_PLAN_ID });
});
describe("getSubscriptionInfo", () => {
@@ -471,6 +474,45 @@ describe("chbBillingService", () => {
});
});
+ it("does not clear a schedule when none is pending", async () => {
+ withOrg(chbConfig({ planCode: "LANGFUSE_CORE" }));
+ // beforeEach stubs getAttachedPlan with no `scheduled` field.
+
+ await service().changePlan(ORG_ID, productIdFor("LANGFUSE_PRO_TEAMS"));
+
+ expect(clientMock.clearScheduledChange).not.toHaveBeenCalled();
+ expect(clientMock.setScheduledChange).toHaveBeenCalledTimes(1);
+ });
+
+ it("clears a pending scheduled change before setting the new one", async () => {
+ withOrg(chbConfig({ planCode: "LANGFUSE_CORE" }));
+ clientMock.getAttachedPlan.mockResolvedValue({
+ id: ATTACHED_PLAN_ID,
+ scheduled: {
+ type: "downgrade",
+ planCode: "LANGFUSE_CORE",
+ startDate: "2026-09-05T00:00:00Z",
+ },
+ });
+
+ await service().changePlan(
+ ORG_ID,
+ productIdFor("LANGFUSE_PRO_TEAMS"),
+ "op-1",
+ );
+
+ // CHB rejects a set while a change is pending, so the clear has to land
+ // first — assert both the call and the order.
+ expect(clientMock.clearScheduledChange).toHaveBeenCalledWith({
+ chOrganizationId: CH_ORG_ID,
+ idempotencyKey:
+ "chb.attachedplan.scheduled.clear:attachedPlanId=plan_1:phase=before-set:op=op-1",
+ });
+ expect(
+ clientMock.clearScheduledChange.mock.invocationCallOrder[0],
+ ).toBeLessThan(clientMock.setScheduledChange.mock.invocationCallOrder[0]);
+ });
+
it("defers a downgrade to the end of the billing cycle", async () => {
withOrg(chbConfig({ planCode: "LANGFUSE_PRO_TEAMS" }));
@@ -563,6 +605,21 @@ describe("chbBillingService", () => {
);
});
+ it("clears a pending plan switch before scheduling the cancellation", async () => {
+ withOrg(chbConfig());
+ clientMock.getAttachedPlan.mockResolvedValue({
+ id: ATTACHED_PLAN_ID,
+ scheduled: { type: "downgrade", planCode: "LANGFUSE_CORE" },
+ });
+
+ await service().cancel(ORG_ID, "op-3");
+
+ expect(clientMock.clearScheduledChange).toHaveBeenCalledTimes(1);
+ expect(
+ clientMock.clearScheduledChange.mock.invocationCallOrder[0],
+ ).toBeLessThan(clientMock.setScheduledChange.mock.invocationCallOrder[0]);
+ });
+
it.each([
["reactivate", (s: ChbBillingService) => s.reactivate(ORG_ID, "op-4")],
[
@@ -593,6 +650,23 @@ describe("chbBillingService", () => {
);
});
+ it("clears a pending change before cancelling immediately", async () => {
+ withOrg(chbConfig());
+ clientMock.getAttachedPlan.mockResolvedValue({
+ id: ATTACHED_PLAN_ID,
+ scheduled: { type: "cancel", endDate: "2026-09-01T00:00:00Z" },
+ });
+
+ await expect(
+ service().cancelImmediatelyAndInvoice(ORG_ID, "op-5"),
+ ).resolves.toEqual({ status: "success" });
+
+ expect(clientMock.clearScheduledChange).toHaveBeenCalledTimes(1);
+ expect(
+ clientMock.clearScheduledChange.mock.invocationCallOrder[0],
+ ).toBeLessThan(clientMock.setScheduledChange.mock.invocationCallOrder[0]);
+ });
+
it("no-ops the immediate cancellation for an org without an attached plan", async () => {
withOrg(null);
@@ -601,6 +675,9 @@ describe("chbBillingService", () => {
service().cancelImmediatelyAndInvoice(ORG_ID),
).resolves.toEqual({ status: "noop" });
expect(clientMock.setScheduledChange).not.toHaveBeenCalled();
+ // No attached plan → nothing read and nothing cleared either.
+ expect(clientMock.getAttachedPlan).not.toHaveBeenCalled();
+ expect(clientMock.clearScheduledChange).not.toHaveBeenCalled();
});
});
diff --git a/web/src/ee/features/billing/server/chb/chbBillingService.ts b/web/src/ee/features/billing/server/chb/chbBillingService.ts
index 824161f20a..ca537821f7 100644
--- a/web/src/ee/features/billing/server/chb/chbBillingService.ts
+++ b/web/src/ee/features/billing/server/chb/chbBillingService.ts
@@ -457,6 +457,14 @@ export class ChbBillingService {
});
try {
+ // CHB rejects a set while a change is already pending, so undo any
+ // pending one first — a user who scheduled a downgrade and then picks a
+ // different plan must not hit a conflict.
+ await this.clearExistingScheduledChangeIfAny(
+ chb.organizationId,
+ chb.attachedPlanId,
+ opId,
+ );
await this.client.setScheduledChange({
chOrganizationId: chb.organizationId,
change: {
@@ -529,6 +537,14 @@ export class ChbBillingService {
return { status: "noop" } as const;
}
+ // A pending downgrade or cancellation would make the immediate-cancel set
+ // conflict, so clear it first (org deletion reaches here).
+ await this.clearExistingScheduledChangeIfAny(
+ chb.organizationId,
+ chb.attachedPlanId,
+ opId,
+ );
+
await this.client.setScheduledChange({
chOrganizationId: chb.organizationId,
change: { type: "cancel", when: "immediate" },
@@ -642,6 +658,38 @@ export class ChbBillingService {
});
}
+ /**
+ * CHB rejects `PUT attachedplan/scheduled` while a scheduled change is
+ * already pending, so every set has to start from a clean slate.
+ */
+ private async clearExistingScheduledChangeIfAny(
+ chOrganizationId: string,
+ attachedPlanId: string,
+ opId?: string,
+ ) {
+ const attachedPlan = await this.client.getAttachedPlan({
+ chOrganizationId,
+ });
+ if (!attachedPlan.scheduled) return;
+
+ logger.info("chbBillingService.attachedplan.scheduled.clearBeforeSet", {
+ chOrganizationId,
+ attachedPlanId,
+ pendingType: attachedPlan.scheduled.type,
+ opId,
+ userId: this.ctx.session.user.id,
+ });
+
+ await this.client.clearScheduledChange({
+ chOrganizationId,
+ idempotencyKey: makeIdempotencyKey({
+ kind: IdempotencyKind.enum["chb.attachedplan.scheduled.clear"],
+ fields: { attachedPlanId, phase: "before-set" },
+ opId,
+ }),
+ });
+ }
+
private async setCancellation(
orgId: string,
when: "immediate" | "billing_cycle_end",
@@ -664,6 +712,14 @@ export class ChbBillingService {
userId: this.ctx.session.user.id,
});
+ // An existing pending change (e.g. a scheduled downgrade) would make this
+ // set conflict, so undo it before scheduling the cancellation.
+ await this.clearExistingScheduledChangeIfAny(
+ chb.organizationId,
+ chb.attachedPlanId,
+ opId,
+ );
+
await this.client.setScheduledChange({
chOrganizationId: chb.organizationId,
change: { type: "cancel", when },