🪢 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
fix(billing): align the CHB client with the attached-plan API (#16968)
Steffen Schmitz7b2e2eecad49
diff --git a/packages/shared/src/interfaces/billingProvider.test.ts b/packages/shared/src/interfaces/billingProvider.test.tsindex 924b0ad5ba..92a5157de7 100644--- a/packages/shared/src/interfaces/billingProvider.test.ts+++ b/packages/shared/src/interfaces/billingProvider.test.ts@@ -91,8 +91,8 @@ describe("hasPaidBillingState", () => {],["manual plan override", { plan: "Team" }, true],[- "CHB bundle",- { clickhouse: { organizationId: CHB_ORG_ID, bundleId: "bdl_123" } },+ "CHB attached plan",+ { clickhouse: { organizationId: CHB_ORG_ID, attachedPlanId: "ap_123" } },true,],[diff --git a/packages/shared/src/interfaces/billingProvider.ts b/packages/shared/src/interfaces/billingProvider.tsindex 31b69a41e1..c0ef1fec4b 100644--- a/packages/shared/src/interfaces/billingProvider.ts+++ b/packages/shared/src/interfaces/billingProvider.ts@@ -45,14 +45,14 @@ export function getBillingProvider(/*** True when the org holds paid billing state with any provider: an active- * Stripe subscription, a manual plan override, or a CHB bundle. Used as the- * paid gate for free-tier usage-threshold enforcement — a paying customer+ * Stripe subscription, a manual plan override, or a CHB attached plan. Used as+ * the paid gate for free-tier usage-threshold enforcement — a paying customer* must never be ingestion-blocked at the free-tier limit.*/export function hasPaidBillingState(org: OrgWithCloudConfig): boolean {return Boolean(org.cloudConfig?.stripe?.activeSubscriptionId ||org.cloudConfig?.plan ||- org.cloudConfig?.clickhouse?.bundleId,+ org.cloudConfig?.clickhouse?.attachedPlanId,);}diff --git a/packages/shared/src/interfaces/cloudConfigSchema.ts b/packages/shared/src/interfaces/cloudConfigSchema.tsindex 7d8f54725b..7cd5756a73 100644--- a/packages/shared/src/interfaces/cloudConfigSchema.ts+++ b/packages/shared/src/interfaces/cloudConfigSchema.ts@@ -36,7 +36,8 @@ export const CloudConfigSchema = z.object({// validate the uuid before persisting. Change the stored schema first,// writers second, if the id format ever loosens.organizationId: z.uuid(),- bundleId: z.string().nullish(),+ // CHB attached plan id (`data.id` on webhook events, `id` on GET /attachedplan)+ attachedPlanId: z.string().nullish(),// Validated against the shared plan-code enum so downstream resolution is// an exhaustive lookup. `.catch(null)` contains the damage if a code ever// drifts (CHB renames a tier, or ships one before we deploy support for@@ -49,7 +50,7 @@ export const CloudConfigSchema = z.object({paymentStatus: z.string().nullish(), // "active" | "failed" | ...nextPaymentDate: z.string().nullish(),// Stripe customer behind the CHB bundle (payment.provider.customerId on- // bundle.* events). Support tooling only — routing, plan resolution, and+ // attachedplan.* events). Support tooling only — routing, plan resolution, and// the worker jobs never read it.stripeCustomerId: z.string().nullish(),// Snapshot of a pending scheduled change (downgrade/cancel) for the UI.diff --git a/web/src/__tests__/server/unit/chbApiClient.servertest.ts b/web/src/__tests__/server/unit/chbApiClient.servertest.tsindex a48104512a..fc3f555856 100644--- a/web/src/__tests__/server/unit/chbApiClient.servertest.ts+++ b/web/src/__tests__/server/unit/chbApiClient.servertest.ts@@ -108,7 +108,7 @@ describe("chbApiClient", () => {describe("authentication", () => {it("presents the Auth0 access token and never follows a redirect", async () => {- onChb(jsonResponse(200, { url: "https://pay.example.com/s/1" }));+ onChb(jsonResponse(200, { portalUrl: "https://pay.example.com/s/1" }));await client().createPortalSession({chOrganizationId: CH_ORG_ID,@@ -123,13 +123,12 @@ describe("chbApiClient", () => {});it("reuses one token across requests", async () => {- onChb(jsonResponse(200, { id: "bundle_1" }), jsonResponse(200, {}));+ onChb(jsonResponse(200, { id: "plan_1" }), jsonResponse(200, {}));const chb = client();- await chb.getBundle({ chOrganizationId: CH_ORG_ID, bundleId: "b1" });+ await chb.getAttachedPlan({ chOrganizationId: CH_ORG_ID });await chb.clearScheduledChange({chOrganizationId: CH_ORG_ID,- bundleId: "b1",});expect(tokenCalls()).toHaveLength(1);@@ -144,9 +143,9 @@ describe("chbApiClient", () => {await client().setScheduledChange({chOrganizationId: CH_ORG_ID,- bundleId: "b1",change: { type: "cancel", when: "billing_cycle_end" },- idempotencyKey: "chb.bundle.scheduled.set:bundleId=b1:op=abc",+ idempotencyKey:+ "chb.attachedplan.scheduled.set:attachedPlanId=b1:op=abc",});expect(tokenCalls()).toHaveLength(2);@@ -159,7 +158,7 @@ describe("chbApiClient", () => {);// The replay must stay idempotent on CHB's side.expect(headersOf(second![1])["Idempotency-Key"]).toBe(- "chb.bundle.scheduled.set:bundleId=b1:op=abc",+ "chb.attachedplan.scheduled.set:attachedPlanId=b1:op=abc",);});@@ -167,7 +166,7 @@ describe("chbApiClient", () => {onChb(jsonResponse(401, {}), jsonResponse(401, {}));const error = await client()- .getBundle({ chOrganizationId: CH_ORG_ID, bundleId: "b1" })+ .getAttachedPlan({ chOrganizationId: CH_ORG_ID }).catch((e) => e);// One replay, not a loop.@@ -179,39 +178,68 @@ describe("chbApiClient", () => {describe("request wiring", () => {it("keeps the base url path prefix when joining the request path", async () => {- onChb(jsonResponse(200, { id: "bundle_1" }));+ onChb(jsonResponse(200, { id: "plan_1" }));- await client().getBundle({- chOrganizationId: CH_ORG_ID,- bundleId: "bundle_1",- });+ await client().getAttachedPlan({ chOrganizationId: CH_ORG_ID });expect(lastChbCall().url.toString()).toBe(- "https://chb.example.com/api/v1/bundles/bundle_1?fields=plan%2Cperiod%2Cpayment%2Cscheduled",+ "https://chb.example.com/api/v1/attachedplan?fields=plan%2Cperiod%2Cpayment%2Cscheduled",);});- it("url-encodes the bundle id into the path", async () => {- onChb(jsonResponse(202, {}));+ it("scopes the scheduled-change routes by header, with no id in the path", async () => {+ onChb(jsonResponse(200, {}));- await client().clearScheduledChange({- chOrganizationId: CH_ORG_ID,- bundleId: "../admin/bundles/other",- });+ await client().clearScheduledChange({ chOrganizationId: CH_ORG_ID });++ // CHB resolves the attached plan from the organization header, so the+ // path carries nothing caller-supplied.+ const { url, init } = lastChbCall();+ expect(url.pathname).toBe("/api/v1/attachedplan/scheduled");+ expect(headersOf(init)["CH-Organization-Id"]).toBe(CH_ORG_ID);+ });++ it("scopes the invoice list by an organizationId query parameter", async () => {+ onChb(jsonResponse(200, { invoices: [] }));++ await client().listInvoices({ chOrganizationId: CH_ORG_ID });++ const { url } = lastChbCall();+ expect(url.pathname).toBe("/api/v1/invoices");+ expect(url.searchParams.get("organizationId")).toBe(CH_ORG_ID);+ });++ it("always sends a checkout idempotency key, generating one when the caller has none", async () => {+ const session = {+ checkoutUrl: "https://pay.example.com/c/1",+ organizationId: CH_ORG_ID,+ };+ const checkout = (idempotencyKey?: string) =>+ client().createCheckoutSession({+ email: "[email protected]",+ planCode: "LANGFUSE_PRO",+ returnUrl: "https://cloud.langfuse.com/back",+ idempotencyKey,+ });- // Escaping matters: an unencoded id would let a caller-supplied value- // climb out of the bundles collection.- expect(lastChbCall().url.pathname).toBe(- "/api/v1/bundles/..%2Fadmin%2Fbundles%2Fother/scheduled",+ onChb(jsonResponse(200, session));+ await checkout("chb.checkout.create:orgId=org-1:op=abc");+ expect(JSON.parse(lastChbCall().init.body as string).idempotencyKey).toBe(+ "chb.checkout.create:orgId=org-1:op=abc",);++ // CHB rejects a checkout without a key; a generated one keeps the call+ // valid and merely gives up deduplication.+ onChb(jsonResponse(200, session));+ await checkout(undefined);+ const generated = JSON.parse(lastChbCall().init.body as string)+ .idempotencyKey as string;+ expect(generated).toMatch(/^[0-9a-f-]{36}$/);});it("scopes org endpoints with CH-Organization-Id and omits it elsewhere", async () => {- onChb(jsonResponse(200, { id: "bundle_1" }));- await client().getBundle({- chOrganizationId: CH_ORG_ID,- bundleId: "bundle_1",- });+ onChb(jsonResponse(200, { id: "plan_1" }));+ await client().getAttachedPlan({ chOrganizationId: CH_ORG_ID });expect(headersOf(lastChbCall().init)["CH-Organization-Id"]).toBe(CH_ORG_ID,);@@ -237,7 +265,6 @@ describe("chbApiClient", () => {onChb(jsonResponse(202, {}));await client().setScheduledChange({chOrganizationId: CH_ORG_ID,- bundleId: "bundle_1",change: {type: "downgrade",when: "billing_cycle_end",@@ -255,7 +282,6 @@ describe("chbApiClient", () => {onChb(jsonResponse(202, {}));await client().clearScheduledChange({chOrganizationId: CH_ORG_ID,- bundleId: "bundle_1",});const withoutBody = lastChbCall();expect(withoutBody.init.method).toBe("DELETE");@@ -267,18 +293,17 @@ describe("chbApiClient", () => {onChb(jsonResponse(202, {}));await client().setScheduledChange({chOrganizationId: CH_ORG_ID,- bundleId: "bundle_1",change: { type: "cancel", when: "billing_cycle_end" },- idempotencyKey: "chb.bundle.scheduled.set:bundleId=bundle_1:op=abc",+ idempotencyKey:+ "chb.attachedplan.scheduled.set:attachedPlanId=plan_1:op=abc",});expect(headersOf(lastChbCall().init)["Idempotency-Key"]).toBe(- "chb.bundle.scheduled.set:bundleId=bundle_1:op=abc",+ "chb.attachedplan.scheduled.set:attachedPlanId=plan_1:op=abc",);onChb(jsonResponse(202, {}));await client().setScheduledChange({chOrganizationId: CH_ORG_ID,- bundleId: "bundle_1",change: { type: "cancel", when: "billing_cycle_end" },});expect(headersOf(lastChbCall().init)["Idempotency-Key"]).toBeUndefined();@@ -292,7 +317,6 @@ describe("chbApiClient", () => {const error = await client().setScheduledChange({chOrganizationId: CH_ORG_ID,- bundleId: "bundle_1",change: {type: "upgrade",when: "immediate",@@ -315,7 +339,7 @@ describe("chbApiClient", () => {onChb(jsonResponse(503, { error: "unavailable" }));const error = await client()- .getBundle({ chOrganizationId: CH_ORG_ID, bundleId: "bundle_1" })+ .getAttachedPlan({ chOrganizationId: CH_ORG_ID }).catch((e) => e);expect(error).toBeInstanceOf(ChbApiError);@@ -334,7 +358,7 @@ describe("chbApiClient", () => {});const error = await client()- .getBundle({ chOrganizationId: CH_ORG_ID, bundleId: "bundle_1" })+ .getAttachedPlan({ chOrganizationId: CH_ORG_ID }).catch((e) => e);expect(error).toBeInstanceOf(ChbApiError);@@ -347,28 +371,43 @@ describe("chbApiClient", () => {it("ignores unknown fields so additive CHB changes cannot break us", async () => {onChb(jsonResponse(200, {- id: "bundle_1",+ id: "plan_1",plan: {- planCode: "LANGFUSE_PRO_TEAMS",- tierName: "Team",+ code: "LANGFUSE_PRO_TEAMS",+ amount: 199,+ currency: "USD",+ recurrence: "monthly",extra: true,},period: { startDate: "2026-08-01T00:00:00Z" },- payment: { status: "active", provider: { customerId: "cus_1" } },+ payment: {+ status: "active",+ provider: { name: "stripe", customerId: "cus_1" },+ },unknownTopLevel: { nested: 1 },}),);- const bundle = await client().getBundle({+ const attachedPlan = await client().getAttachedPlan({chOrganizationId: CH_ORG_ID,- bundleId: "bundle_1",});- expect(bundle.id).toBe("bundle_1");- expect(bundle.plan?.planCode).toBe("LANGFUSE_PRO_TEAMS");- expect(bundle.payment?.provider?.customerId).toBe("cus_1");- // Nothing required beyond `id`, so a sparse bundle still parses.- expect(bundle.scheduled).toBeUndefined();+ expect(attachedPlan.id).toBe("plan_1");+ expect(attachedPlan.plan?.code).toBe("LANGFUSE_PRO_TEAMS");+ expect(attachedPlan.payment?.provider?.customerId).toBe("cus_1");+ // Nothing required beyond `id`, so a sparse attached plan still parses.+ expect(attachedPlan.scheduled).toBeUndefined();+ });++ it("reads the portal URL from CHB's portalUrl field", async () => {+ onChb(jsonResponse(200, { portalUrl: "https://pay.example.com/s/1" }));++ await expect(+ client().createPortalSession({+ chOrganizationId: CH_ORG_ID,+ returnUrl: "https://cloud.langfuse.com/back",+ }),+ ).resolves.toBe("https://pay.example.com/s/1");});it("reads the checkout URL from CHB's checkoutUrl field", async () => {@@ -397,7 +436,6 @@ describe("chbApiClient", () => {await expect(client().listInvoices({chOrganizationId: CH_ORG_ID,- bundleId: "bundle_1",}),).resolves.toEqual([]);});@@ -475,8 +513,8 @@ describe("chbApiClient", () => {it("mints one token across calls made through the shared client", async () => {setAll();- onChb(jsonResponse(200, { url: "https://chb.example.com/portal" }));- onChb(jsonResponse(200, { url: "https://chb.example.com/portal" }));+ onChb(jsonResponse(200, { portalUrl: "https://chb.example.com/portal" }));+ onChb(jsonResponse(200, { portalUrl: "https://chb.example.com/portal" }));// Two separate resolutions, as two billing procedures in one page load.await getChbApiClient()!.createPortalSession({diff --git a/web/src/__tests__/server/unit/chbBillingService.servertest.ts b/web/src/__tests__/server/unit/chbBillingService.servertest.tsindex 5e9c793f8b..3683196042 100644--- a/web/src/__tests__/server/unit/chbBillingService.servertest.ts+++ b/web/src/__tests__/server/unit/chbBillingService.servertest.ts@@ -32,7 +32,7 @@ import { type OrgAuthedContext } from "@/src/server/api/trpc";const ORG_ID = "org-1";const CH_ORG_ID = "6dd6ab1d-9e8d-4c1a-8b4f-9a3d1e2c4b5a";-const BUNDLE_ID = "bundle_1";+const ATTACHED_PLAN_ID = "plan_1";// Resolved through the bridge rather than hardcoded: the catalogue swaps in// test-mode product ids, and this suite is about the mapping, not the literals.@@ -51,7 +51,7 @@ const executeRaw = vi.fn();const clientMock = {createCheckoutSession: vi.fn(),- getBundle: vi.fn(),+ getAttachedPlan: vi.fn(),setScheduledChange: vi.fn(),clearScheduledChange: vi.fn(),listInvoices: vi.fn(),@@ -90,7 +90,7 @@ const chbConfig = (): CloudConfigSchema => ({clickhouse: {organizationId: CH_ORG_ID,- bundleId: BUNDLE_ID,+ attachedPlanId: ATTACHED_PLAN_ID,planCode: "LANGFUSE_PRO",...overrides,},@@ -113,12 +113,12 @@ describe("chbBillingService", () => {});describe("getSubscriptionInfo", () => {- it("falls back to the cached billing cycle when the org has no bundle", async () => {+ it("falls back to the cached billing cycle when the org has no attached plan", async () => {withOrg({ clickhouse: { organizationId: CH_ORG_ID } });const info = await service().getSubscriptionInfo(ORG_ID);- expect(clientMock.getBundle).not.toHaveBeenCalled();+ expect(clientMock.getAttachedPlan).not.toHaveBeenCalled();expect(info.cancellation).toBeNull();expect(info.scheduledChange).toBeNull();expect(info.hasValidPaymentMethod).toBe(false);@@ -130,10 +130,10 @@ describe("chbBillingService", () => {);});- it("reports a healthy bundle's period and payment status", async () => {+ it("reports a healthy attached plan's period and payment status", async () => {withOrg(chbConfig());- clientMock.getBundle.mockResolvedValue({- id: BUNDLE_ID,+ clientMock.getAttachedPlan.mockResolvedValue({+ id: ATTACHED_PLAN_ID,period: {startDate: "2026-08-01T00:00:00Z",endDate: "2026-09-01T00:00:00Z",@@ -143,9 +143,8 @@ describe("chbBillingService", () => {const info = await service().getSubscriptionInfo(ORG_ID);- expect(clientMock.getBundle).toHaveBeenCalledWith({+ expect(clientMock.getAttachedPlan).toHaveBeenCalledWith({chOrganizationId: CH_ORG_ID,- bundleId: BUNDLE_ID,});expect(info.billingPeriod).toEqual({start: new Date("2026-08-01T00:00:00Z"),@@ -158,8 +157,8 @@ describe("chbBillingService", () => {it("treats any non-active payment status as no valid payment method", async () => {withOrg(chbConfig());- clientMock.getBundle.mockResolvedValue({- id: BUNDLE_ID,+ clientMock.getAttachedPlan.mockResolvedValue({+ id: ATTACHED_PLAN_ID,payment: { status: "failed" },});@@ -171,29 +170,29 @@ describe("chbBillingService", () => {it("maps a pending cancellation onto the cancellation field", async () => {withOrg(chbConfig());- clientMock.getBundle.mockResolvedValue({- id: BUNDLE_ID,+ clientMock.getAttachedPlan.mockResolvedValue({+ id: ATTACHED_PLAN_ID,period: { endDate: "2026-09-01T00:00:00Z" },- scheduled: { type: "cancel", when: "billing_cycle_end" },+ scheduled: { type: "cancel", endDate: "2026-09-03T00:00:00Z" },});const info = await service().getSubscriptionInfo(ORG_ID);- // Unix seconds, like the Stripe path the UI already renders.+ // Unix seconds, like the Stripe path the UI already renders. The plan's+ // own end date wins over the period end.expect(info.cancellation).toEqual({- cancelAt: Date.parse("2026-09-01T00:00:00Z") / 1000,+ cancelAt: Date.parse("2026-09-03T00:00:00Z") / 1000,});expect(info.scheduledChange).toBeNull();});it("maps a pending plan switch onto scheduledChange with a bridged product id", async () => {withOrg(chbConfig());- clientMock.getBundle.mockResolvedValue({- id: BUNDLE_ID,+ clientMock.getAttachedPlan.mockResolvedValue({+ id: ATTACHED_PLAN_ID,period: { endDate: "2026-09-01T00:00:00Z" },scheduled: {type: "downgrade",- when: "billing_cycle_end",planCode: "LANGFUSE_CORE",startDate: "2026-09-05T00:00:00Z",},@@ -203,7 +202,7 @@ describe("chbBillingService", () => {expect(info.cancellation).toBeNull();expect(info.scheduledChange).toEqual({- scheduleId: `chb:${BUNDLE_ID}`,+ scheduleId: `chb:${ATTACHED_PLAN_ID}`,// An explicit startDate wins over the period end.switchAt: Date.parse("2026-09-05T00:00:00Z") / 1000,newProductId: productIdFor("LANGFUSE_CORE"),@@ -213,9 +212,9 @@ describe("chbBillingService", () => {it("renders no pending state when the change has no resolvable date", async () => {withOrg(chbConfig());- clientMock.getBundle.mockResolvedValue({- id: BUNDLE_ID,- scheduled: { type: "cancel", when: "immediate" },+ clientMock.getAttachedPlan.mockResolvedValue({+ id: ATTACHED_PLAN_ID,+ scheduled: { type: "cancel" },});const info = await service().getSubscriptionInfo(ORG_ID);@@ -223,22 +222,21 @@ describe("chbBillingService", () => {expect(info.scheduledChange).toBeNull();});- it("renders no pending state for an immediate change on an active period", async () => {+ it("falls back to the period end for a cancellation without an end date", async () => {withOrg(chbConfig());- clientMock.getBundle.mockResolvedValue({- id: BUNDLE_ID,- // An immediate cancellation echoed back while the period is still- // populated: the date fallback would date it at the cycle end and- // render a change that has already applied as pending.+ clientMock.getAttachedPlan.mockResolvedValue({+ id: ATTACHED_PLAN_ID,period: {startDate: "2026-08-01T00:00:00Z",endDate: "2026-09-01T00:00:00Z",},- scheduled: { type: "cancel", when: "immediate" },+ scheduled: { type: "cancel" },});const info = await service().getSubscriptionInfo(ORG_ID);- expect(info.cancellation).toBeNull();+ expect(info.cancellation).toEqual({+ cancelAt: Date.parse("2026-09-01T00:00:00Z") / 1000,+ });expect(info.scheduledChange).toBeNull();});});@@ -341,7 +339,7 @@ describe("chbBillingService", () => {});// Sticky provider routing is broken; clobbering the stored id would point- // the org at a bundle it never bought.+ // the org at a plan it never bought.expect(await trpcCode(service().createCheckoutSession(@@ -463,14 +461,13 @@ describe("chbBillingService", () => {expect(clientMock.setScheduledChange).toHaveBeenCalledWith({chOrganizationId: CH_ORG_ID,- bundleId: BUNDLE_ID,change: {type: "upgrade",when: "immediate",planCode: "LANGFUSE_PRO_TEAMS",},idempotencyKey:- "chb.bundle.scheduled.set:bundleId=bundle_1:to=LANGFUSE_PRO_TEAMS:op=op-1",+ "chb.attachedplan.scheduled.set:attachedPlanId=plan_1:to=LANGFUSE_PRO_TEAMS:op=op-1",});});@@ -537,7 +534,7 @@ describe("chbBillingService", () => {it.each([["a manual plan override", { plan: "Team" } as CloudConfigSchema],["no CHB state at all", {} as CloudConfigSchema],- ["no bundle", { clickhouse: { organizationId: CH_ORG_ID } }],+ ["no attached plan", { clickhouse: { organizationId: CH_ORG_ID } }],])("refuses an org with %s", async (_label, cloudConfig) => {withOrg(cloudConfig);@@ -561,7 +558,7 @@ describe("chbBillingService", () => {expect.objectContaining({change: { type: "cancel", when: "billing_cycle_end" },idempotencyKey:- "chb.bundle.scheduled.set:bundleId=bundle_1:to=cancel-billing_cycle_end:op=op-3",+ "chb.attachedplan.scheduled.set:attachedPlanId=plan_1:to=cancel-billing_cycle_end:op=op-3",}),);});@@ -578,8 +575,8 @@ describe("chbBillingService", () => {await expect(call(service())).resolves.toEqual({ status: "success" });expect(clientMock.clearScheduledChange).toHaveBeenCalledWith({chOrganizationId: CH_ORG_ID,- bundleId: BUNDLE_ID,- idempotencyKey: "chb.bundle.scheduled.clear:bundleId=bundle_1:op=op-4",+ idempotencyKey:+ "chb.attachedplan.scheduled.clear:attachedPlanId=plan_1:op=op-4",});});@@ -596,7 +593,7 @@ describe("chbBillingService", () => {);});- it("no-ops the immediate cancellation for an org without a bundle", async () => {+ it("no-ops the immediate cancellation for an org without an attached plan", async () => {withOrg(null);// Org deletion must keep working for hobby orgs.@@ -610,7 +607,7 @@ describe("chbBillingService", () => {describe("getInvoices", () => {const pagination = { limit: 10 };- it("returns nothing for an org without a bundle", async () => {+ it("returns nothing for an org without an attached plan", async () => {withOrg(null);await expect(service().getInvoices(ORG_ID, pagination)).resolves.toEqual({@@ -630,8 +627,9 @@ describe("chbBillingService", () => {status: "paid",currency: "usd",createdAt: "2026-08-01T00:00:00Z",- totalCents: 19_900,- downloadUrl: "https://chb.example.com/inv_1.pdf",+ amount: 19_900,+ hostedUrl: "https://chb.example.com/inv_1",+ pdfUrl: "https://chb.example.com/inv_1.pdf",},]);@@ -645,7 +643,7 @@ describe("chbBillingService", () => {status: "paid",currency: "USD",created: Date.parse("2026-08-01T00:00:00Z"),- hostedInvoiceUrl: "https://chb.example.com/inv_1.pdf",+ hostedInvoiceUrl: "https://chb.example.com/inv_1",invoicePdfUrl: "https://chb.example.com/inv_1.pdf",breakdown: {subscriptionCents: 0,diff --git a/web/src/ee/features/billing/components/useBillingInformation.tsx b/web/src/ee/features/billing/components/useBillingInformation.tsxindex b365746366..24c2a94ec5 100644--- a/web/src/ee/features/billing/components/useBillingInformation.tsx+++ b/web/src/ee/features/billing/components/useBillingInformation.tsx@@ -126,7 +126,7 @@ export const useBillingInformation = (): UseBillingInformationResult => {),hasActiveSubscription: Boolean(organization?.cloudConfig?.stripe?.activeSubscriptionId ??- organization?.cloudConfig?.clickhouse?.bundleId,+ organization?.cloudConfig?.clickhouse?.attachedPlanId,),hasValidPaymentMethod: subscriptionInfo?.hasValidPaymentMethod ?? false,billingProvider,diff --git a/web/src/ee/features/billing/server/chb/chbApiClient.ts b/web/src/ee/features/billing/server/chb/chbApiClient.tsindex d58b64fb7a..047f569fbf 100644--- a/web/src/ee/features/billing/server/chb/chbApiClient.ts+++ b/web/src/ee/features/billing/server/chb/chbApiClient.ts@@ -1,3 +1,5 @@+import { randomUUID } from "crypto";+import { SpanKind, type Span } from "@opentelemetry/api";import { z } from "zod";@@ -25,7 +27,7 @@ export class ChbApiError extends Error {}/**- * CHB returns 409 Conflict on bundle mutations when the organization has no+ * CHB returns 409 Conflict on attached-plan mutations when the organization has no* active payment method. Callers translate this into the same "needs checkout"* UX path the billing dialog already handles.*/@@ -40,18 +42,21 @@ export class ChbPaymentRequiredError extends ChbApiError {}}-const ChbScheduledChangeSchema = z.object({+// A pending change on the attached plan, as GET /attachedplan reports it.+// Kept permissive (no discriminated union) because this is a read path that+// renders the billing page: an unknown type must degrade, not throw.+const ChbAttachedPlanScheduledSchema = z.object({type: z.string(), // "upgrade" | "downgrade" | "cancel"- when: z.string(), // "immediate" | "billing_cycle_end" | ISO date- planCode: z.string().nullish(),- startDate: z.string().nullish(),+ planCode: z.string().nullish(), // upgrade / downgrade target+ startDate: z.string().nullish(), // upgrade / downgrade effective date+ endDate: z.string().nullish(), // cancel: when the plan ends});-const ChbBundleSchema = z.object({+const ChbAttachedPlanSchema = z.object({id: z.string(),plan: z.object({- planCode: z.string().nullish(),+ code: z.string().nullish(),}).nullish(),period: z@@ -62,18 +67,18 @@ const ChbBundleSchema = z.object({.nullish(),payment: z.object({- status: z.string().nullish(),- nextPaymentDate: z.string().nullish(),+ status: z.string().nullish(), // "active" | "past-due" | "failed"provider: z.object({+ name: z.string().nullish(),customerId: z.string().nullish(),}).nullish(),}).nullish(),- scheduled: ChbScheduledChangeSchema.nullish(),+ scheduled: ChbAttachedPlanScheduledSchema.nullish(),});-export type ChbBundle = z.infer<typeof ChbBundleSchema>;+export type ChbAttachedPlan = z.infer<typeof ChbAttachedPlanSchema>;const ChbCheckoutSessionSchema = z.object({checkoutUrl: z.url(),@@ -86,13 +91,13 @@ export type ChbCheckoutSession = z.infer<typeof ChbCheckoutSessionSchema>;const ChbInvoiceSchema = z.object({id: z.string().nullish(),number: z.string().nullish(),- status: z.string().nullish(),+ status: z.string().nullish(), // "draft" | "open" | "paid" | "void" | "uncollectible"currency: z.string().nullish(),createdAt: z.string().nullish(),- totalCents: z.number().nullish(),- // Still an open question with CHB: a hosted download URL and draft/upcoming- // rows are requested but not confirmed in the invoice payload yet.- downloadUrl: z.string().nullish(),+ // Minor units (cents for USD)+ amount: z.number().nullish(),+ hostedUrl: z.string().nullish(),+ pdfUrl: z.string().nullish(),});export type ChbInvoice = z.infer<typeof ChbInvoiceSchema>;@@ -101,7 +106,7 @@ const ChbInvoiceListSchema = z.object({});const ChbPortalSessionSchema = z.object({- url: z.string(),+ portalUrl: z.string(),});const REQUEST_TIMEOUT_MS = 15_000;@@ -300,33 +305,36 @@ export class ChbApiClient {email: params.email,planCode: params.planCode,returnUrl: params.returnUrl,- ...(params.idempotencyKey- ? { idempotencyKey: params.idempotencyKey }- : {}),+ // Required by CHB. Without an opId there is nothing to dedupe against,+ // so a fresh key makes the call unique rather than rejected.+ idempotencyKey: params.idempotencyKey ?? randomUUID(),},idempotencyKey: params.idempotencyKey,});return ChbCheckoutSessionSchema.parse(body);}- async getBundle(params: {+ /**+ * The organization's current attached plan. CHB scopes the attached-plan+ * routes by the CH-Organization-Id header, there is no id in the path; a 404+ * means the organization has none.+ */+ async getAttachedPlan(params: {chOrganizationId: string;- bundleId: string;- }): Promise<ChbBundle> {+ }): Promise<ChbAttachedPlan> {const body = await this.request({- operation: "chb.bundle.get",+ operation: "chb.attachedplan.get",method: "GET",- path: `bundles/${encodeURIComponent(params.bundleId)}`,+ path: "attachedplan",chOrganizationId: params.chOrganizationId,searchParams: { fields: "plan,period,payment,scheduled" },});- return ChbBundleSchema.parse(body);+ return ChbAttachedPlanSchema.parse(body);}- /** Schedule an upgrade / downgrade / cancellation on a bundle (202). */+ /** Upgrade now, schedule a downgrade for the cycle end, or cancel the plan. */async setScheduledChange(params: {chOrganizationId: string;- bundleId: string;change: {type: "upgrade" | "downgrade" | "cancel";when: "immediate" | "billing_cycle_end";@@ -335,40 +343,42 @@ export class ChbApiClient {idempotencyKey?: string;}): Promise<void> {await this.request({- operation: "chb.bundle.scheduled.set",+ operation: "chb.attachedplan.scheduled.set",method: "PUT",- path: `bundles/${encodeURIComponent(params.bundleId)}/scheduled`,+ path: "attachedplan/scheduled",chOrganizationId: params.chOrganizationId,body: params.change,idempotencyKey: params.idempotencyKey,});}- /** Clear a pending scheduled change — reactivate / undo plan switch (202). */+ /** Clear a pending scheduled change — reactivate / undo plan switch. */async clearScheduledChange(params: {chOrganizationId: string;- bundleId: string;idempotencyKey?: string;}): Promise<void> {await this.request({- operation: "chb.bundle.scheduled.clear",+ operation: "chb.attachedplan.scheduled.clear",method: "DELETE",- path: `bundles/${encodeURIComponent(params.bundleId)}/scheduled`,+ path: "attachedplan/scheduled",chOrganizationId: params.chOrganizationId,idempotencyKey: params.idempotencyKey,});}+ /**+ * Issued invoices, most recent first. Unlike the attached-plan routes this+ * one is scoped by an `organizationId` query parameter.+ */async listInvoices(params: {chOrganizationId: string;- bundleId: string;}): Promise<ChbInvoice[]> {const body = await this.request({operation: "chb.invoices.list",method: "GET",path: "invoices",chOrganizationId: params.chOrganizationId,- searchParams: { bundleId: params.bundleId },+ searchParams: { organizationId: params.chOrganizationId },});return ChbInvoiceListSchema.parse(body).invoices;}@@ -384,7 +394,7 @@ export class ChbApiClient {chOrganizationId: params.chOrganizationId,body: { returnUrl: params.returnUrl },});- return ChbPortalSessionSchema.parse(body).url;+ return ChbPortalSessionSchema.parse(body).portalUrl;}}diff --git a/web/src/ee/features/billing/server/chb/chbBillingService.ts b/web/src/ee/features/billing/server/chb/chbBillingService.tsindex 76923a39ac..6b26c3ec33 100644--- a/web/src/ee/features/billing/server/chb/chbBillingService.ts+++ b/web/src/ee/features/billing/server/chb/chbBillingService.ts@@ -13,7 +13,7 @@ import {import { type BillingSubscriptionInfo } from "../stripe/stripeBillingService";import {type ChbApiClient,- type ChbBundle,+ type ChbAttachedPlan,ChbPaymentRequiredError,} from "./chbApiClient";import { backfillChbProjectEvents } from "./chbProjectEvents";@@ -83,44 +83,36 @@ export class ChbBillingService {}/**- * Map a bundle's pending scheduled change onto the Stripe-shaped- * cancellation / scheduledChange fields the billing UI renders.+ * Map the attached plan's pending scheduled change onto the Stripe-shaped+ * cancellation / scheduledChange fields the billing UI renders. CHB reports+ * a cancellation with the date the plan ends and an upgrade / downgrade with+ * the date the new plan starts; the current period end is the fallback while+ * CHB omits either date.*/- private mapScheduled(bundle: ChbBundle): {+ private mapScheduled(attachedPlan: ChbAttachedPlan): {cancellation: BillingSubscriptionInfo["cancellation"];scheduledChange: BillingSubscriptionInfo["scheduledChange"];} {- const scheduled = bundle.scheduled;+ const scheduled = attachedPlan.scheduled;if (!scheduled) return { cancellation: null, scheduledChange: null };- // An "immediate" change has already been applied, so there is no pending- // state to render. Checked explicitly rather than relying on the date- // fallback below: an immediate change echoed back on a bundle that still- // carries an active period would otherwise resolve to the period end and- // render as "switches at end of cycle".- if (scheduled.when === "immediate") {- return { cancellation: null, scheduledChange: null };- }-- // Date resolution: explicit startDate wins, else the period end.- const switchAt =- this.toUnixSeconds(scheduled.startDate) ??- this.toUnixSeconds(bundle.period?.endDate);- if (!switchAt) return { cancellation: null, scheduledChange: null };+ const periodEnd = this.toUnixSeconds(attachedPlan.period?.endDate);if (scheduled.type === "cancel") {- return {- cancellation: { cancelAt: switchAt },- scheduledChange: null,- };+ const cancelAt = this.toUnixSeconds(scheduled.endDate) ?? periodEnd;+ if (!cancelAt) return { cancellation: null, scheduledChange: null };+ return { cancellation: { cancelAt }, scheduledChange: null };}+ const switchAt = this.toUnixSeconds(scheduled.startDate) ?? periodEnd;+ if (!switchAt) return { cancellation: null, scheduledChange: null };+return {cancellation: null,scheduledChange: {// CHB has no schedule object of its own; synthesize a stable id for// the UI (only mutations by orgId exist, the id is display-only).- scheduleId: `chb:${bundle.id}`,+ scheduleId: `chb:${attachedPlan.id}`,switchAt,newProductId: scheduled.planCode? (mapChbPlanCodeToStripeProductId(scheduled.planCode) ?? undefined)@@ -134,8 +126,8 @@ export class ChbBillingService {const { org, parsedOrg } = await this.getParsedOrg(orgId);const chb = parsedOrg.cloudConfig?.clickhouse;- if (!chb?.bundleId) {- // No bundle yet (hobby / pre-checkout) → same cached-cycle fallback the+ if (!chb?.attachedPlanId) {+ // No attached plan yet (hobby / pre-checkout) → same cached-cycle fallback the// Stripe path uses for orgs without a subscription.const now = new Date();return {@@ -149,27 +141,26 @@ export class ChbBillingService {};}- const bundle = await this.client.getBundle({+ const attachedPlan = await this.client.getAttachedPlan({chOrganizationId: chb.organizationId,- bundleId: chb.bundleId,});- const periodStart = bundle.period?.startDate- ? new Date(bundle.period.startDate)+ const periodStart = attachedPlan.period?.startDate+ ? new Date(attachedPlan.period.startDate): null;- const periodEnd = bundle.period?.endDate- ? new Date(bundle.period.endDate)+ const periodEnd = attachedPlan.period?.endDate+ ? new Date(attachedPlan.period.endDate): null;return {- ...this.mapScheduled(bundle),+ ...this.mapScheduled(attachedPlan),billingPeriod:periodStart && periodEnd? { start: periodStart, end: periodEnd }: null,// No promotion-code API on the CHB path yetdiscounts: [],- hasValidPaymentMethod: bundle.payment?.status === "active",+ hasValidPaymentMethod: attachedPlan.payment?.status === "active",};}@@ -250,11 +241,11 @@ export class ChbBillingService {"Cannot initialize ClickHouse Billing checkout for a Stripe-billed organization",});}- if (parsedOrg.cloudConfig?.clickhouse?.bundleId) {+ if (parsedOrg.cloudConfig?.clickhouse?.attachedPlanId) {throw new TRPCError({code: "INTERNAL_SERVER_ERROR",message:- "Organization already has an active bundle; use changePlan instead of checkout",+ "Organization already has an active attached plan; use changePlan instead of checkout",});}@@ -428,7 +419,7 @@ export class ChbBillingService {}const chb = this.requireChbState(parsedOrg);- if (!chb.bundleId) {+ if (!chb.attachedPlanId) {throw new TRPCError({code: "INTERNAL_SERVER_ERROR",message: "Organization does not have an active subscription",@@ -449,14 +440,14 @@ export class ChbBillingService {: true;const idempotencyKey = makeIdempotencyKey({- kind: IdempotencyKind.enum["chb.bundle.scheduled.set"],- fields: { bundleId: chb.bundleId, to: newPlanCode },+ kind: IdempotencyKind.enum["chb.attachedplan.scheduled.set"],+ fields: { attachedPlanId: chb.attachedPlanId, to: newPlanCode },opId,});- logger.info("chbBillingService.bundle.scheduled.set", {+ logger.info("chbBillingService.attachedplan.scheduled.set", {orgId,- bundleId: chb.bundleId,+ attachedPlanId: chb.attachedPlanId,fromPlanCode: currentPlanCode,toPlanCode: newPlanCode,isUpgrade: upgrading,@@ -468,7 +459,6 @@ export class ChbBillingService {try {await this.client.setScheduledChange({chOrganizationId: chb.organizationId,- bundleId: chb.bundleId,change: {type: upgrading ? "upgrade" : "downgrade",// Same semantics as the Stripe path: upgrades apply immediately,@@ -526,14 +516,14 @@ export class ChbBillingService {/*** Immediate cancellation for destructive flows (org deletion). Per spec,* CHB closes the bill and invoices on the cancellation date; billing data- * only, the CH organization survives. No-op without a bundle so org+ * only, the CH organization survives. No-op without an attached plan so org* deletion keeps working for hobby orgs.*/async cancelImmediatelyAndInvoice(orgId: string, opId?: string) {const { parsedOrg } = await this.getParsedOrg(orgId);const chb = parsedOrg.cloudConfig?.clickhouse;- if (!chb?.bundleId) {- logger.info("chbBillingService.cancel.now:noop.noActiveBundle", {+ if (!chb?.attachedPlanId) {+ logger.info("chbBillingService.cancel.now:noop.noActiveAttachedPlan", {orgId,});return { status: "noop" } as const;@@ -541,11 +531,10 @@ export class ChbBillingService {await this.client.setScheduledChange({chOrganizationId: chb.organizationId,- bundleId: chb.bundleId,change: { type: "cancel", when: "immediate" },idempotencyKey: makeIdempotencyKey({- kind: IdempotencyKind.enum["chb.bundle.scheduled.set"],- fields: { bundleId: chb.bundleId, to: "cancel-immediate" },+ kind: IdempotencyKind.enum["chb.attachedplan.scheduled.set"],+ fields: { attachedPlanId: chb.attachedPlanId, to: "cancel-immediate" },opId,}),});@@ -583,19 +572,18 @@ export class ChbBillingService {) {const { parsedOrg } = await this.getParsedOrg(orgId);const chb = parsedOrg.cloudConfig?.clickhouse;- if (!chb?.bundleId) {+ if (!chb?.attachedPlanId) {return { invoices: [], hasMore: false, cursors: {} };}const invoices = await this.client.listInvoices({chOrganizationId: chb.organizationId,- bundleId: chb.bundleId,});return {- // Mapped into the existing invoice-table row shape. Breakdown parity- // (subscription vs usage split, draft/upcoming row) is still open with- // CHB, so this is total-only until they confirm the payload.+ // Mapped into the existing invoice-table row shape. CHB reports one+ // total per invoice, so the breakdown is total-only; the open period's+ // accrued usage is available as `preview` on the same route when needed.invoices: invoices.map((invoice) => ({id: invoice.id,number: invoice.number,@@ -604,14 +592,14 @@ export class ChbBillingService {// Milliseconds, like the Stripe path. Guarded: an unparsable CHB// timestamp must not reach the table as NaN.created: (this.toUnixSeconds(invoice.createdAt) ?? 0) * 1000,- hostedInvoiceUrl: invoice.downloadUrl ?? null,- invoicePdfUrl: invoice.downloadUrl ?? null,+ hostedInvoiceUrl: invoice.hostedUrl ?? null,+ invoicePdfUrl: invoice.pdfUrl ?? null,breakdown: {subscriptionCents: 0,usageCents: 0,discountCents: 0,taxCents: 0,- totalCents: invoice.totalCents ?? 0,+ totalCents: invoice.amount ?? 0,},})),// CHB invoice pagination is not part of the v1 contract; return the@@ -625,7 +613,7 @@ export class ChbBillingService {* v1 usage source of truth for CHB orgs is the existing non-Stripe* fallback: billing cycle from the org's anchor + the cached cycle usage* the hourly job maintains. Spend-in-USD can later come from- * `GET /bundles/{id}?fields=period`.+ * `GET /invoices?includePreview=true` (the open period's accrued usage).*/async getUsage(orgId: string) {const { org } = await this.getParsedOrg(orgId);@@ -661,16 +649,16 @@ export class ChbBillingService {) {const { parsedOrg } = await this.getParsedOrg(orgId);const chb = this.requireChbState(parsedOrg);- if (!chb.bundleId) {+ if (!chb.attachedPlanId) {throw new TRPCError({code: "INTERNAL_SERVER_ERROR",message: "No active subscription to cancel",});}- logger.info("chbBillingService.bundle.scheduled.cancel", {+ logger.info("chbBillingService.attachedplan.scheduled.cancel", {orgId,- bundleId: chb.bundleId,+ attachedPlanId: chb.attachedPlanId,when,opId,userId: this.ctx.session.user.id,@@ -678,11 +666,10 @@ export class ChbBillingService {await this.client.setScheduledChange({chOrganizationId: chb.organizationId,- bundleId: chb.bundleId,change: { type: "cancel", when },idempotencyKey: makeIdempotencyKey({- kind: IdempotencyKind.enum["chb.bundle.scheduled.set"],- fields: { bundleId: chb.bundleId, to: `cancel-${when}` },+ kind: IdempotencyKind.enum["chb.attachedplan.scheduled.set"],+ fields: { attachedPlanId: chb.attachedPlanId, to: `cancel-${when}` },opId,}),});@@ -701,16 +688,16 @@ export class ChbBillingService {private async clearScheduled(orgId: string, action: string, opId?: string) {const { parsedOrg } = await this.getParsedOrg(orgId);const chb = this.requireChbState(parsedOrg);- if (!chb.bundleId) {+ if (!chb.attachedPlanId) {throw new TRPCError({code: "INTERNAL_SERVER_ERROR",message: "No active subscription found",});}- logger.info("chbBillingService.bundle.scheduled.clear", {+ logger.info("chbBillingService.attachedplan.scheduled.clear", {orgId,- bundleId: chb.bundleId,+ attachedPlanId: chb.attachedPlanId,action,opId,userId: this.ctx.session.user.id,@@ -718,10 +705,9 @@ export class ChbBillingService {await this.client.clearScheduledChange({chOrganizationId: chb.organizationId,- bundleId: chb.bundleId,idempotencyKey: makeIdempotencyKey({- kind: IdempotencyKind.enum["chb.bundle.scheduled.clear"],- fields: { bundleId: chb.bundleId },+ kind: IdempotencyKind.enum["chb.attachedplan.scheduled.clear"],+ fields: { attachedPlanId: chb.attachedPlanId },opId,}),});diff --git a/web/src/ee/features/billing/utils/stripeIdempotencyKey.ts b/web/src/ee/features/billing/utils/stripeIdempotencyKey.tsindex 6553a6bd87..d021a4a765 100644--- a/web/src/ee/features/billing/utils/stripeIdempotencyKey.ts+++ b/web/src/ee/features/billing/utils/stripeIdempotencyKey.ts@@ -36,8 +36,8 @@ export const IdempotencyKind = z.enum([// lifetime, which is exactly the double-submit window, and drops it on// remount so a fresh visit gets a fresh session rather than an expired one."chb.checkout.create",- "chb.bundle.scheduled.set",- "chb.bundle.scheduled.clear",+ "chb.attachedplan.scheduled.set",+ "chb.attachedplan.scheduled.clear",]);export type IdempotencyKind = z.infer<typeof IdempotencyKind>;diff --git a/web/src/features/entitlements/server/getPlan.ts b/web/src/features/entitlements/server/getPlan.tsindex 8153a7209f..4932a4c6eb 100644--- a/web/src/features/entitlements/server/getPlan.ts+++ b/web/src/features/entitlements/server/getPlan.ts@@ -40,7 +40,8 @@ export function getOrganizationPlanServerSide(// CHB org can never fall through to stale Stripe state — the same// CHB-wins precedence getBillingProvider enforces. A missing plan code// (drifted, so dropped by cloudConfigSchema) fails open to the free tier,- // never to a paid one; the paid gate for usage thresholds reads bundleId+ // never to a paid one; the paid gate for usage thresholds reads+ // attachedPlanId// instead, so a drifted code does not get a paying org ingestion-blocked.if (cloudConfig.clickhouse?.organizationId) {const { planCode } = cloudConfig.clickhouse;diff --git a/worker/src/__tests__/thresholdProcessing.test.ts b/worker/src/__tests__/thresholdProcessing.test.tsindex b0bf5a694c..7a62875432 100644--- a/worker/src/__tests__/thresholdProcessing.test.ts+++ b/worker/src/__tests__/thresholdProcessing.test.ts@@ -610,13 +610,13 @@ describe("processThresholds", () => {});describe("CHB-billed orgs", () => {- it("skips enforcement for orgs with a CHB bundle (paid gate covers clickhouse.bundleId)", async () => {+ it("skips enforcement for orgs with a CHB attached plan (paid gate covers clickhouse.attachedPlanId)", async () => {const org = createMockOrg({cloudCurrentCycleUsage: 0,cloudConfig: {clickhouse: {organizationId: "0d5e6f7a-1b2c-4d3e-8f9a-0b1c2d3e4f5a",- bundleId: "bdl_123",+ attachedPlanId: "ap_123",planCode: "core",},},