Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
Original file line number Diff line number Diff line change
Expand Up @@ -51,17 +51,22 @@ export const applyCustomerLicenseTransitions = ({
for (const customerLicenseTransition of customerLicenseTransitions) {
const planLicenseId =
customerLicenseTransition.incomingCustomerLicense.planLicense?.id;
if (planLicenseId) {
customerLicenseBillingContext.projectedPlanLicenseIds.add(planLicenseId);
if (
planLicenseId &&
!customerLicenseBillingContext.projectedPlanLicenseIds.includes(
planLicenseId,
)
) {
customerLicenseBillingContext.projectedPlanLicenseIds.push(planLicenseId);
}
customerLicenseBillingContext.licenseBillingPriceRows.push(
...transitionLicenseBillingPriceRows({
licenseBillingPriceRows: persistedRows,
customerLicenseTransition,
assignedSeatCount:
customerLicenseBillingContext.assignedSeatCountByCustomerLicenseId.get(
customerLicenseTransition.outgoingCustomerLicense.id,
) ?? 0,
customerLicenseBillingContext.assignedSeatCountByCustomerLicenseId[
customerLicenseTransition.outgoingCustomerLicense.id
] ?? 0,
}),
);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import {
getPatchCustomerProducts,
} from "@/internal/billing/v2/utils/billingPlan/customerProductPlanMutations";
import { orgDisableStripeWrites } from "@/internal/orgs/orgUtils/convertOrgUtils";
import { isStripeConnected } from "@/internal/orgs/orgUtils.js";
import { checkStripeProductExists } from "@/internal/products/productUtils";
import { applyStripeResourceReuseForProduct } from "@/internal/products/stripeResourceUtils/applyStripeResourceReuseForProduct";
import { applyStripeReuseFromVariantFamilies } from "@/internal/products/stripeResourceUtils/applyStripeReuseFromVariantFamilies";
Expand Down Expand Up @@ -51,6 +52,9 @@ export const initStripeResourcesForProducts = async ({

if (env === AppEnv.Live) return;
if (orgDisableStripeWrites({ ctx, includeSandbox: true })) return;
// No Stripe account (e.g. fresh sandbox sub-orgs) — resources are
// created lazily once one is connected.
if (!isStripeConnected({ org, env })) return;

const batchProductUpdates = [];
for (const product of products) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,7 @@ export const customerLicenseToStripeItemSpecs = ({
billingContext.customerLicenseBillingContext?.licenseBillingPriceRows ?? []
).filter((row) => row.source.customerLicenseId === customerLicense.id);
const projectedPlanLicenseIds =
billingContext.customerLicenseBillingContext?.projectedPlanLicenseIds ??
new Set<string>();
billingContext.customerLicenseBillingContext?.projectedPlanLicenseIds ?? [];

// Desired state prices seats through the pool's (possibly repointed)
// definition — the read-time twin of the seat repoint executor.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ export const setupCustomerLicenseBillingContext = async ({
if (customerLicenses.length === 0) {
return {
licenseBillingPriceRows: [],
assignedSeatCountByCustomerLicenseId: new Map(),
projectedPlanLicenseIds: new Set(),
assignedSeatCountByCustomerLicenseId: {},
projectedPlanLicenseIds: [],
};
}

Expand All @@ -37,7 +37,7 @@ export const setupCustomerLicenseBillingContext = async ({
),
}),
]);
const assignedSeatCountByCustomerLicenseId = new Map(
const assignedSeatCountByCustomerLicenseId = Object.fromEntries(
customerLicenses.map((customerLicense) => [
customerLicense.id,
assignedSeatCountByLinkId.get(customerLicense.link_id) ?? 0,
Expand All @@ -47,6 +47,6 @@ export const setupCustomerLicenseBillingContext = async ({
return {
licenseBillingPriceRows,
assignedSeatCountByCustomerLicenseId,
projectedPlanLicenseIds: new Set(),
projectedPlanLicenseIds: [],
};
};
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,7 @@ export const customerLicenseToLineItems = ({
billingContext.customerLicenseBillingContext?.licenseBillingPriceRows ?? []
).filter((row) => row.source.customerLicenseId === customerLicense.id);
const projectedPlanLicenseIds =
billingContext.customerLicenseBillingContext?.projectedPlanLicenseIds ??
new Set<string>();
billingContext.customerLicenseBillingContext?.projectedPlanLicenseIds ?? [];

// Seats bill through THIS side's definition: refunds get the outgoing
// pool's terms, charges the incoming — mirroring the repoint executor.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
import {
type FullPlanLicense,
type LicenseBillingPriceRow,
} from "@autumn/shared";
import type { FullPlanLicense, LicenseBillingPriceRow } from "@autumn/shared";

/** Selects projected rows for this definition, otherwise persisted rows. */
export const resolveLicenseBillingRowsThroughDefinition = ({
Expand All @@ -11,11 +8,11 @@ export const resolveLicenseBillingRowsThroughDefinition = ({
}: {
licenseBillingRows: LicenseBillingPriceRow[];
planLicense: FullPlanLicense;
projectedPlanLicenseIds: Set<string>;
projectedPlanLicenseIds: string[];
}): LicenseBillingPriceRow[] => {
const projectedRows = licenseBillingRows.filter(
(row) => row.source.planLicenseId === planLicense.id,
);
if (projectedPlanLicenseIds.has(planLicense.id)) return projectedRows;
if (projectedPlanLicenseIds.includes(planLicense.id)) return projectedRows;
return licenseBillingRows.filter((row) => !row.source.planLicenseId);
};
6 changes: 5 additions & 1 deletion server/src/internal/features/FeatureService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,13 +123,17 @@ export class FeatureService {
.returning();
}

// The row may have been deleted between read and update (e.g. async
// display generation racing an org/feature teardown).
if (updatedFeatures.length === 0) return null;

await clearOrgCache({
db,
orgId: updatedFeatures[0].org_id!,
env: updatedFeatures[0].env as AppEnv,
});

return updatedFeatures.length > 0 ? (updatedFeatures[0] as Feature) : null;
return updatedFeatures[0] as Feature;
}

static async insert({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -134,10 +134,13 @@ export const handleCopyProducts = async ({

await Promise.all(operations);

// inIds bypasses the products cache — the copy ops' invalidations land
// async, so a plain listFull can still see the pre-copy (empty) snapshot.
const copiedToProducts = await ProductService.listFull({
db,
orgId: toOrg.id,
env: toEnv,
inIds: fromProducts.map((product) => product.id),
});
await copyPlanLicenseLinks({
db,
Expand Down
17 changes: 10 additions & 7 deletions server/src/queue/createWorkerContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,18 @@ export const createWorkerContext = async ({
const { orgId, env, customerId, requestId } = payload;
if (!orgId || !env) return;

// Fetch org with features once for all items
const orgData = await OrgService.getWithFeatures({
db,
orgId,
env,
});
// Fetch org with features once for all items. A missing org means it was
// deleted after the job was queued (common in tests) — skip, don't fail.
let orgData: Awaited<ReturnType<typeof OrgService.getWithFeatures>> | null;
try {
orgData = await OrgService.getWithFeatures({ db, orgId, env });
} catch {
orgData = null;
}
Comment on lines +34 to +38

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 Bare catch swallows transient DB errors

The bare try/catch around OrgService.getWithFeatures treats every thrown exception — including database connection timeouts, network errors, or Drizzle query failures — identically to a deleted-org RecaseError. When a transient error fires, orgData is set to null, the job logs a warning, and returns silently. The queue never sees the error, so the job is not retried and the work is permanently dropped.

OrgService.getWithFeatures already has an allowNotFound: true option that returns null specifically for the not-found case while letting real errors propagate. Using that option keeps the intended graceful-skip behaviour for deleted orgs without silently discarding jobs on infrastructure failures.

Suggested change
try {
orgData = await OrgService.getWithFeatures({ db, orgId, env });
} catch {
orgData = null;
}
// Fetch org with features once for all items. A missing org means it was
// deleted after the job was queued (common in tests) — skip, don't fail.
const orgData = await OrgService.getWithFeatures({
db,
orgId,
env,
allowNotFound: true,
});
Prompt To Fix With AI
This is a comment left during a code review.
Path: server/src/queue/createWorkerContext.ts
Line: 34-38

Comment:
**Bare catch swallows transient DB errors**

The bare `try/catch` around `OrgService.getWithFeatures` treats every thrown exception — including database connection timeouts, network errors, or Drizzle query failures — identically to a deleted-org `RecaseError`. When a transient error fires, `orgData` is set to `null`, the job logs a warning, and returns silently. The queue never sees the error, so the job is not retried and the work is permanently dropped.

`OrgService.getWithFeatures` already has an `allowNotFound: true` option that returns `null` specifically for the not-found case while letting real errors propagate. Using that option keeps the intended graceful-skip behaviour for deleted orgs without silently discarding jobs on infrastructure failures.

```suggestion
	// Fetch org with features once for all items. A missing org means it was
	// deleted after the job was queued (common in tests) — skip, don't fail.
	const orgData = await OrgService.getWithFeatures({
		db,
		orgId,
		env,
		allowNotFound: true,
	});
```

How can I resolve this? If you propose a fix, please make it concise.


if (!orgData) {
throw new Error(`Organization not found: ${orgId}, env: ${env}`);
logger.warn(`Org ${orgId} (${env}) not found — skipping queued job`);
return;
}

const { org, features } = orgData;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import type {
TrackResponseV3,
} from "@autumn/shared";
import { ApiVersion, ErrCode, events, FeatureType } from "@autumn/shared";
import { eventsDb } from "@tests/integration/balances/utils/events/getCustomerEvents.js";
import { expectBalanceCorrect } from "@tests/integration/utils/expectBalanceCorrect.js";
import { TestFeature } from "@tests/setup/v2Features.js";
import { expectAutumnError } from "@tests/utils/expectUtils/expectErrUtils.js";
Expand All @@ -19,7 +20,6 @@ import { initScenario, s } from "@tests/utils/testInitUtils/initScenario.js";
import chalk from "chalk";
import { Decimal } from "decimal.js";
import { and, desc, eq } from "drizzle-orm";
import { db } from "@/db/initDrizzle.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { getModelCreditCost } from "@/internal/features/aiCreditSystemUtils.js";
import { getModelsDevPricing } from "@/internal/features/utils/getModelPricing.js";
Expand Down Expand Up @@ -205,7 +205,7 @@ test.concurrent(
const customer = (await autumnV2_2.customers.get(customerId, {
with_autumn_id: true,
})) as ApiCustomerV5 & { autumn_id?: string };
const eventRows = await db
const eventRows = await eventsDb()
.select({
created_at: events.created_at,
timestamp: events.timestamp,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
import { ApiVersion } from "@autumn/shared";
import { neonEventsDb } from "@server/db/initNeonEvents.js";
import { AutumnInt } from "@server/external/autumn/autumnCli.js";
import { EventService } from "@server/internal/api/events/EventService.js";
import ctx from "@tests/utils/testInitUtils/createTestContext.js";

/** Events land in the split Neon events DB when configured; mirror the
* writer's resolution so asserts read where the server wrote. */
export const eventsDb = () => neonEventsDb ?? ctx.db;

export const getCustomerEvents = async ({
customerId,
}: {
Expand All @@ -15,7 +20,7 @@ export const getCustomerEvents = async ({
});

const events = await EventService.getByCustomerId({
db: ctx.db,
db: eventsDb(),
orgId: ctx.org.id,
internalCustomerId: customer.autumn_id ?? "",
env: ctx.env,
Expand Down
Loading
Loading