Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

fix(jobs): per-tenant cron isolation + auto-disable dead accounting OAuth grants (#1653)

Sidfd910410c6cd
diff --git a/.ai/lessons.md b/.ai/lessons.md
index c2da31130c..80e7643f9d 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -1580,3 +1580,13 @@ full-screen ERP route.
**Rule:** Never discard a supabase-js write result — bind it and check `.error`, even for a fire-and-forget link write. Treat `as any` on a `.from(...).insert(...)` as a defect in review: the cast exists precisely because the row object does not satisfy the generated type, which is the compiler telling you a required column is missing. When a "seeded" side table is mysteriously empty, check the writer's error handling before suspecting the read.
**Applies to:** every `.from(...).insert(...)` / `.update(...)` whose result is not bound, especially in post-commit "also link X" tails; fixed for both writers in PR #1612 by moving them into a Kysely transaction under `lockIssueDispositions`.
+
+## A cron that walks every tenant must isolate each tenant
+
+**Context:** `accounting-pull-sweep` looped `for (target of targets) await step.run(...)` over every active accounting integration; `mrp` ran every company inside ONE `step.run`. One Xero tenant's refresh token died (`invalid_grant` "Refresh token not found"); one MRP run outgrew Vercel's function timeout.
+
+**Problem:** An Inngest step that exhausts its retries throws into the function and fails the run, so the dead-token company silently skipped every company after it on every sweep — for weeks, with no notification. The single-step MRP was one Vercel invocation for all tenants, timed out, and every retry restarted from company #1. In both cases the run's status said what happened to the run, not to the tenants.
+
+**Rule:** One `step.run` per tenant, wrapped in `try/catch` that records `{ error }` and continues; return the per-tenant outcomes so the run output says who failed. Classify terminal failures (a refused OAuth grant is `AccountingAuthError`) and return them from the step instead of throwing — retries cannot fix them and only delay the next tenant. Pair the per-tenant step with a `maxDuration` on the serve route: a step's ceiling is that function's ceiling.
+
+**Applies to:** `packages/jobs/src/inngest/functions/**` — every cron with a per-company loop (`accounting-*-sweep`, `accounting-reconciliation`, `accounting-consolidation`, `scheduled/mrp.ts`); use `runIsolatedCompanyStep` (`integrations/accounting-auth-failure.ts`) for the accounting ones.
diff --git a/.claude/rules/accounting-sync-handlers.md b/.claude/rules/accounting-sync-handlers.md
index aa6f62b5e2..74ecbcbeee 100644
--- a/.claude/rules/accounting-sync-handlers.md
+++ b/.claude/rules/accounting-sync-handlers.md
@@ -43,6 +43,12 @@ These live in `packages/jobs/src/inngest/functions/integrations/` (+ `events/syn
| `accounting-reconciliation` | — | `accounting-reconciliation.ts` | cron `0 3 * * 1` (Mondays 03:00 UTC) — presence drift check + `accountingSyncTieOut` writer; see the tie-out section below |
| `event-handler-sync` | `carbon/event-sync` | `events/sync.ts` | the SYNC event-system handler (see event-system.md) — DB writes -> push to the provider |
+### Per-tenant isolation and dead OAuth grants
+
+The four crons (`pull-sweep`, `outbound-sweep`, `reconciliation`, `consolidation`) walk every active integration with one `step.run` per company, through `runIsolatedCompanyStep` (`accounting-auth-failure.ts`). Two invariants: a tenant that exhausts its step retries returns `{ error }` and the loop continues — it never fails the run for every tenant after it (it used to: one company with a dead token skipped every later company on every sweep); and an `AccountingAuthError` (the provider's token endpoint answered 400/401 — `invalid_grant` "Refresh token not found", revoked, rotated-and-lost) is NOT retried, because nothing retries a dead grant back to life. It returns `{ authFailed }`, `recordIntegrationAuthFailure` increments a redis counter (`integrations:<companyId>:<providerId>:auth-failures`, cleared by any successful pass), notifies the configurer (`integration.updatedBy`, `NotificationEvent.IntegrationSync`, deduped to one per day), and at `AUTH_FAILURE_DISABLE_THRESHOLD` (12 consecutive ≈ 3 h across both sweeps — `drainSyncOperations` rethrows `AccountingAuthError` like `RatelimitError` instead of parking it as Failed rows, so drain-path auth failures count too) sets `companyIntegration.active = false`, clears the integration cache keys, and notifies "disabled — reconnect". The OAuth callback routes upsert `active: true`, so reconnecting is the whole recovery. Note a deactivated accounting integration makes the period-close "External GL sync complete" blocker auto-pass (it only checks ACTIVE integrations) — that is the trade-off the user chose over an integration that sits active and silently syncs nothing.
+
+Why tokens die: Xero and QBO rotate refresh tokens, and Carbon refreshes reactively on a 401 (`providers/*/provider.ts`). Several runners (both sweeps, webhooks, event sync, reconciliation) build their own provider from the vault and can refresh with the same token. `createOAuthClient.refresh()` therefore calls `beforeRefresh` first (`core/service.ts` re-reads the vault): a stored refresh token that differs from the in-memory one means another runner already rotated — adopt it, skip the token endpoint. And `onTokenRefresh` now THROWS when `persistIntegrationSecrets` fails: the provider has already rotated, so a lost write is a dead credential; failing the run right there beats "Refresh token not found" thirty minutes later with no trail. Pinned by `core/oauth-refresh.test.ts`.
+
### The operation ledger — enqueue, cooldown, truthful close
Every entry point routes through the durable **`accountingSyncOperation`** ledger (`accounting-sync-operations.ts` in jobs + `core/operations.ts` in ee) between enqueue and `SyncFactory.getSyncer(...).pushBatch/pullBatch`:
diff --git a/.claude/rules/mrp-system.md b/.claude/rules/mrp-system.md
index d1872674a9..b1e1f6311f 100644
--- a/.claude/rules/mrp-system.md
+++ b/.claude/rules/mrp-system.md
@@ -23,11 +23,20 @@ Phase-7 write) and throws on failure.
1. **Scheduled job** — `packages/jobs/src/inngest/functions/scheduled/mrp.ts`.
`inngest.createFunction({ id: "mrp", retries: 2 }, { cron: "0 */3 * * *" }, …)`
- — every 3 hours. Fans out **per company**: selects all rows from `company`
- and, for each, calls `runMrp(serviceRole, getJobDatabaseClient(), { type:
- "company", id, companyId, userId: "system" })` **in-process** (`runMrp` throws
- on failure; the loop try/catches per company). There is no location-scoped
- cron — only company-wide.
+ — every 3 hours. A `find-companies` step selects all rows from `company`,
+ then **one `step.run` per company** (`mrp-<companyId>`) calls
+ `runMrp(serviceRole, getJobDatabaseClient(), { type: "company", id,
+ companyId, userId: "system" })` **in-process** (`runMrp` throws on failure;
+ the loop try/catches per step and returns `{ companies, failed }`). Every
+ Inngest step is one HTTP request to `/api/inngest`, so a step's ceiling is
+ that Vercel function's max duration — set project-wide in the Vercel
+ dashboard (Settings → Functions), NOT via a route `config` export: a
+ `maxDuration` in the route config splits a second server bundle in the
+ @vercel/react-router preset and the Vite 8 css-post plugin fails the build
+ ("Unable to get file name for unknown file"). All companies in ONE step was one invocation, hit
+ `FUNCTION_INVOCATION_TIMEOUT` as the tenant count grew after the
+ `company`-enumeration change below, and every retry restarted from company
+ #1. There is no location-scoped cron — only company-wide.
It enumerated `companyPlan` until 2026-08-26. MRP is not in `FEATURE_PLANS`,
so that was never a billing gate — just a convenient list of companies — but
diff --git a/.claude/rules/testing-no-mock-theater.md b/.claude/rules/testing-no-mock-theater.md
new file mode 100644
index 0000000000..5be1572d45
--- /dev/null
+++ b/.claude/rules/testing-no-mock-theater.md
@@ -0,0 +1,50 @@
+---
+paths:
+ - "**/*.test.ts"
+ - "**/*.test.tsx"
+---
+
+# Tests: no mock theater
+
+A test that fakes every collaborator and then asserts call counts against the
+fakes proves the mocks work, not the code. One such file was deleted from a PR
+on sight (`accounting-auth-failure.test.ts`, 2026-09-17: hand-rolled redis +
+supabase + Inngest step fakes, assertions like "redis.del was called with these
+keys"). Do not write tests like that.
+
+## The rule
+
+Stub only the **real external boundary** — the thing the code genuinely cannot
+reach in a test process:
+
+- an HTTP endpoint → stub global `fetch` (see `core/oauth-refresh.test.ts`:
+ four tests, one stub, pins real branching in `refresh()`)
+- the wall clock → fake timers
+- the filesystem → a temp dir
+
+Everything between the test and that boundary runs real. If the unit under
+test touches redis, the database, AND a runtime harness, and you would have to
+fake all three to test it, **don't write the test** — either extract the pure
+decision into its own function and test that (the codebase's established
+pattern: `reconcile.ts`, `mrp-companies.ts`, `posting-policy` are all pure
+cores with real tests), or leave it untested and let an integration path cover
+it.
+
+## Smells that mean delete-and-rethink, not refactor-the-test
+
+- A hand-rolled in-memory fake of redis/supabase/Kysely inside a test file.
+- `expect(mock).toHaveBeenCalledWith(...)` as the primary assertion — you are
+ pinning the implementation's call shape, not its behavior.
+- The fake needs its own logic (NX semantics, builder chains) to make the test
+ pass — the fake is now a second implementation that can drift from the real
+ one.
+- A loop driving the code N times purely to trip a threshold inside mocks.
+
+## What a test must earn
+
+A test exists to fail when the LOGIC breaks. Before keeping one, ask: "which
+real bug flips this red?" If the only answer is "someone renamed the mock's
+method", it has earned nothing. A branch worth testing is worth testing
+through real values at a real boundary; a glue function that just wires
+collaborators together is verified by typecheck + the integration that uses
+it, not by a puppet show.
diff --git a/packages/ee/src/accounting/core/oauth-refresh.test.ts b/packages/ee/src/accounting/core/oauth-refresh.test.ts
new file mode 100644
index 0000000000..176d77fe6c
--- /dev/null
+++ b/packages/ee/src/accounting/core/oauth-refresh.test.ts
@@ -0,0 +1,112 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { AccountingAuthError, createOAuthClient } from "./utils";
+
+const jsonResponse = (status: number, body: unknown) =>
+ new Response(JSON.stringify(body), {
+ status,
+ headers: { "content-type": "application/json" }
+ });
+
+function makeClient(
+ overrides: Partial<Parameters<typeof createOAuthClient>[0]> = {}
+) {
+ return createOAuthClient({
+ clientId: "id",
+ clientSecret: "secret",
+ tokenUrl: "https://identity.example.com/connect/token",
+ accessToken: "at-old",
+ refreshToken: "rt-old",
+ getAuthUrl: () => "",
+ ...overrides
+ });
+}
+
+describe("createOAuthClient.refresh", () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it("throws AccountingAuthError when the token endpoint refuses the grant", async () => {
+ const fetchMock = vi.fn(async () =>
+ jsonResponse(400, {
+ error: "invalid_grant",
+ error_description: "Refresh token not found"
+ })
+ );
+ vi.stubGlobal("fetch", fetchMock);
+
+ const client = makeClient();
+ const error = await client.refresh().catch((e) => e);
+
+ expect(error).toBeInstanceOf(AccountingAuthError);
+ expect(error.code).toBe(400);
+ expect(error.provider).toBe("identity.example.com");
+ expect(error.message).toContain("Refresh token not found");
+ });
+
+ it("keeps other failures as plain errors", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () => jsonResponse(503, { error: "temporarily_unavailable" }))
+ );
+
+ const error = await makeClient()
+ .refresh()
+ .catch((e) => e);
+
+ expect(error).toBeInstanceOf(Error);
+ expect(error).not.toBeInstanceOf(AccountingAuthError);
+ });
+
+ it("adopts a pair another runner already rotated instead of refreshing", async () => {
+ const fetchMock = vi.fn();
+ vi.stubGlobal("fetch", fetchMock);
+ const onTokenRefresh = vi.fn();
+
+ const client = makeClient({
+ beforeRefresh: async () => ({
+ accessToken: "at-new",
+ refreshToken: "rt-new"
+ }),
+ onTokenRefresh
+ });
+
+ const creds = await client.refresh();
+
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(onTokenRefresh).not.toHaveBeenCalled();
+ expect(creds).toMatchObject({
+ accessToken: "at-new",
+ refreshToken: "rt-new"
+ });
+ expect(client.getCredentials()).toMatchObject({ refreshToken: "rt-new" });
+ });
+
+ it("refreshes normally when the stored pair is the one it holds", async () => {
+ const fetchMock = vi.fn(async () =>
+ jsonResponse(200, {
+ access_token: "at-fresh",
+ refresh_token: "rt-fresh",
+ expires_in: 1800
+ })
+ );
+ vi.stubGlobal("fetch", fetchMock);
+ const onTokenRefresh = vi.fn();
+
+ const client = makeClient({
+ beforeRefresh: async () => ({
+ accessToken: "at-old",
+ refreshToken: "rt-old"
+ }),
+ onTokenRefresh
+ });
+
+ const creds = await client.refresh();
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(creds).toMatchObject({ refreshToken: "rt-fresh" });
+ expect(onTokenRefresh).toHaveBeenCalledWith(
+ expect.objectContaining({ refreshToken: "rt-fresh" })
+ );
+ });
+});
diff --git a/packages/ee/src/accounting/core/service.ts b/packages/ee/src/accounting/core/service.ts
index fc6fb869a4..886d07aceb 100644
--- a/packages/ee/src/accounting/core/service.ts
+++ b/packages/ee/src/accounting/core/service.ts
@@ -242,6 +242,42 @@ export function getProviderIntegration(
provider,
error
});
+ // The provider has already rotated the pair; losing the write means the
+ // stored refresh token is dead and the next runner reads "Refresh token
+ // not found" with no trail back to here. Fail now, loudly.
+ throw new Error(
+ `Failed to persist refreshed ${provider} tokens: ${
+ error instanceof Error ? error.message : String(error)
+ }`
+ );
+ }
+ };
+
+ // Re-read the vault right before refreshing: if another runner already
+ // rotated the pair, adopt it instead of burning the token a second time.
+ // Any failure here just falls through to a normal refresh.
+ const beforeRefresh = async () => {
+ try {
+ const latest = await getAccountingIntegration(
+ client,
+ companyId,
+ provider
+ );
+ const stored = latest.metadata.credentials
+ ? parseStoredCredentials(latest.metadata.credentials)
+ : undefined;
+ if (stored?.type !== "oauth2" || !stored.refreshToken) return null;
+ return {
+ accessToken: stored.accessToken,
+ refreshToken: stored.refreshToken,
+ expiresAt: stored.expiresAt
+ };
+ } catch (error) {
+ logger.warning("Could not re-read stored credentials before refresh", {
+ provider,
+ error
+ });
+ return null;
}
};
@@ -271,7 +307,8 @@ export function getProviderIntegration(
clientSecret: process.env.QUICKBOOKS_CLIENT_SECRET!,
redirectUri: process.env.QUICKBOOKS_REDIRECT_URI,
syncConfig,
- onTokenRefresh
+ onTokenRefresh,
+ beforeRefresh
});
}
case "xero": {
@@ -285,7 +322,8 @@ export function getProviderIntegration(
clientSecret: process.env.XERO_CLIENT_SECRET!,
redirectUri: process.env.XERO_REDIRECT_URI,
syncConfig,
- onTokenRefresh
+ onTokenRefresh,
+ beforeRefresh
});
}
// Add other providers as needed
diff --git a/packages/ee/src/accounting/core/types.ts b/packages/ee/src/accounting/core/types.ts
index f9d08b3648..50e75c3043 100644
--- a/packages/ee/src/accounting/core/types.ts
+++ b/packages/ee/src/accounting/core/types.ts
@@ -55,6 +55,18 @@ export interface OAuthClientOptions {
redirectUri?: string;
getAuthUrl: (scopes: string[], redirectUri: string) => string;
onTokenRefresh?: (creds: ProviderCredentials) => Promise<void>;
+ /**
+ * Re-read the stored credentials right before a refresh. Several runners
+ * (pull/outbound sweeps, webhooks, event sync) hold the same pair and the
+ * providers rotate refresh tokens, so whoever refreshes second burns a token
+ * that is already dead. Returning a pair whose refreshToken differs from the
+ * in-memory one means another runner already rotated: adopt it, skip the call.
+ */
+ beforeRefresh?: () => Promise<{
+ accessToken: string;
+ refreshToken: string;
+ expiresAt?: string;
+ } | null>;
}
export interface AuthProvider {
@@ -69,6 +81,7 @@ export type ProviderConfig<T = unknown> = {
companyId: string;
syncConfig: GlobalSyncConfig;
onTokenRefresh?: OAuthClientOptions["onTokenRefresh"];
+ beforeRefresh?: OAuthClientOptions["beforeRefresh"];
} & T;
/**
diff --git a/packages/ee/src/accounting/core/utils.ts b/packages/ee/src/accounting/core/utils.ts
index 083bfe4edb..cd59832cf1 100644
--- a/packages/ee/src/accounting/core/utils.ts
+++ b/packages/ee/src/accounting/core/utils.ts
@@ -158,6 +158,23 @@ export interface RateLimitInfo {
details?: Record<string, unknown>;
}
+/**
+ * The provider's token endpoint rejected the stored grant (invalid_grant /
+ * invalid_client): the refresh token was revoked, expired, or rotated away by
+ * another runner and lost. Not transient — retrying cannot mint a new pair;
+ * only reconnecting the integration can.
+ */
+export class AccountingAuthError extends Error {
+ constructor(
+ public readonly provider: string,
+ public readonly code: number,
+ detail: string
+ ) {
+ super(`[${provider}] authentication failed (HTTP ${code}): ${detail}`);
+ this.name = "AccountingAuthError";
+ }
+}
+
export class RatelimitError extends Error {
public rateLimitInfo: RateLimitInfo;
@@ -488,6 +505,15 @@ export function createOAuthClient({
throw new Error("No refresh token available");
}
+ // ponytail: read-then-write CAS; add a pg advisory lock RPC if two
+ // runners still collide inside the same second.
+ const stored = options.beforeRefresh && (await options.beforeRefresh());
+ if (stored && stored.refreshToken !== creds.refreshToken) {
+ logger.info("Adopting tokens rotated by another runner");
+ creds = { ...creds, ...stored };
+ return creds;
+ }
+
const response = await http.request<{
access_token: string;
refresh_token: string;
@@ -509,14 +535,21 @@ export function createOAuthClient({
message: response.message,
data: response.data
});
- // Surface the provider's actual rejection (e.g. invalid_grant /
- // invalid_client) instead of the useless boolean "true".
+ const detail =
+ typeof response.data === "string"
+ ? response.data
+ : JSON.stringify(response.data);
+ // 400/401 from the token endpoint is the grant itself being refused
+ // (invalid_grant / invalid_client) — terminal, see AccountingAuthError.
+ if (response.code === 400 || response.code === 401) {
+ throw new AccountingAuthError(
+ new URL(options.tokenUrl).hostname,
+ response.code,
+ detail
+ );
+ }
throw new Error(
- `Token refresh failed (HTTP ${response.code}): ${
- typeof response.data === "string"
- ? response.data
- : JSON.stringify(response.data)
- }`
+ `Token refresh failed (HTTP ${response.code}): ${detail}`
);
}
diff --git a/packages/ee/src/accounting/providers/quickbooks-online/provider.ts b/packages/ee/src/accounting/providers/quickbooks-online/provider.ts
index 4fc8b323ef..2ae4bd9882 100644
--- a/packages/ee/src/accounting/providers/quickbooks-online/provider.ts
+++ b/packages/ee/src/accounting/providers/quickbooks-online/provider.ts
@@ -391,6 +391,7 @@ export class QboProvider extends BaseProvider {
redirectUri: config.redirectUri,
tokenUrl: QBO_TOKEN_URL,
onTokenRefresh: config.onTokenRefresh,
+ beforeRefresh: config.beforeRefresh,
getAuthUrl(scopes: string[], redirectURL: string): string {
const params = new URLSearchParams({
response_type: "code",
diff --git a/packages/ee/src/accounting/providers/xero/provider.ts b/packages/ee/src/accounting/providers/xero/provider.ts
index e8f40eddb3..9fbd794228 100644
--- a/packages/ee/src/accounting/providers/xero/provider.ts
+++ b/packages/ee/src/accounting/providers/xero/provider.ts
@@ -235,6 +235,7 @@ export class XeroProvider implements BaseProvider, SupportsIncrementalPull {
redirectUri: config.redirectUri,
tokenUrl: "https://identity.xero.com/connect/token",
onTokenRefresh: config.onTokenRefresh,
+ beforeRefresh: config.beforeRefresh,
getAuthUrl(scopes: string[], redirectURL: string): string {
const params = new URLSearchParams({
response_type: "code",
diff --git a/packages/jobs/src/inngest/functions/integrations/accounting-auth-failure.ts b/packages/jobs/src/inngest/functions/integrations/accounting-auth-failure.ts
new file mode 100644
index 0000000000..be1ef893bc
--- /dev/null
+++ b/packages/jobs/src/inngest/functions/integrations/accounting-auth-failure.ts
@@ -0,0 +1,182 @@
+/**
+ * Auth-failure handling for the accounting crons. Kept out of
+ * accounting-sync-operations.ts on purpose: that module is imported by the
+ * pure decision tests, and @carbon/kv boots @carbon/env on import.
+ */
+import type { Database } from "@carbon/database";
+import { AccountingAuthError } from "@carbon/ee/accounting";
+import { redis } from "@carbon/kv";
+import { trigger } from "@carbon/lib/trigger";
+import { NotificationEvent } from "@carbon/notifications";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import type { GetStepTools } from "inngest";
+import type { inngest } from "../../client";
+
+const AUTH_FAILURE_NOTIFY_TTL_SECONDS = 24 * 60 * 60;
+const AUTH_FAILURE_COUNTER_TTL_SECONDS = 7 * 24 * 60 * 60;
+/**
+ * Consecutive auth failures before the integration is switched off. The pull
+ * and outbound sweeps each hit it twice an hour, so this is roughly three
+ * hours of a provably dead grant — long enough that a reconnect in progress
+ * is not cut off, short enough that a dead integration does not sit "active"
+ * for weeks while every sync silently does nothing.
+ */
+export const AUTH_FAILURE_DISABLE_THRESHOLD = 12;
+
+const authFailureCounterKey = (companyId: string, providerId: string) =>
+ `integrations:${companyId}:${providerId}:auth-failures`;
+
+async function notifyIntegration(args: {
+ companyId: string;
+ providerId: string;
+ recipientId: string | null | undefined;
+ title: string;
+ body: string;
+}): Promise<void> {
+ const { companyId, providerId, recipientId, title, body } = args;
+ if (!recipientId || recipientId === "system") return;
+ try {
+ await trigger("notify", {
+ event: NotificationEvent.IntegrationSync,
+ companyId,
+ documentId: providerId,
+ title,
+ body,
+ recipient: { type: "user", userId: recipientId }
+ });
+ } catch (notifyError) {
+ console.error(
+ `[ACCOUNTING SYNC] ${companyId}/${providerId}: failed to send notification`,
+ notifyError
+ );
+ }
+}
+
+/**
+ * Record one auth failure against the integration. Below the threshold the
+ * configurer is told to reconnect (once a day — every cron hits the same dead
+ * token every 30 minutes); at the threshold the integration is deactivated so
+ * it stops being swept, and the configurer is told that instead. Reconnecting
+ * through the OAuth callback upserts `active: true` again. Never throws.
+ */
+export async function recordIntegrationAuthFailure(
+ client: SupabaseClient<Database>,
+ args: {
+ companyId: string;
+ providerId: string;
+ recipientId: string | null | undefined;
+ }
+): Promise<"notified" | "deactivated" | "muted"> {
+ const { companyId, providerId, recipientId } = args;
+ try {
+ const counterKey = authFailureCounterKey(companyId, providerId);
+ const failures = await redis.incr(counterKey);
+ await redis.expire(counterKey, AUTH_FAILURE_COUNTER_TTL_SECONDS);
+
+ if (failures >= AUTH_FAILURE_DISABLE_THRESHOLD) {
+ const deactivated = await client
+ .from("companyIntegration")
+ .update({ active: false, updatedAt: new Date().toISOString() })
+ .eq("id", providerId)
+ .eq("companyId", companyId);
+ if (deactivated.error) throw deactivated.error;
+ // Same keys apps/erp's clearCompanyIntegrationCache clears
+ await redis.del(
+ `integrations:${companyId}`,
+ `json:integrations:${companyId}`,
+ counterKey
+ );
+ await notifyIntegration({
+ companyId,
+ providerId,
+ recipientId,
+ title: "Accounting integration disabled",
+ body: `${providerId} was disabled after ${failures} consecutive authentication failures — reconnect it in Settings → Integrations to resume sync`
+ });
+ return "deactivated";
+ }
+
+ const first = await redis.set(
+ `integrations:${companyId}:${providerId}:auth-failed`,
+ "1",
+ "EX",
+ AUTH_FAILURE_NOTIFY_TTL_SECONDS,
+ "NX"
+ );
+ if (first !== "OK") return "muted";
+ await notifyIntegration({
+ companyId,
+ providerId,
+ recipientId,
+ title: "Accounting integration disconnected",
+ body: `Carbon can no longer authenticate with ${providerId} — reconnect it in Settings → Integrations to resume sync`
+ });
+ return "notified";
+ } catch (error) {
+ console.error(
+ `[ACCOUNTING SYNC] ${companyId}/${providerId}: failed to record auth failure`,
+ error
+ );
+ return "muted";
+ }
+}
+
+export type CompanySweepTarget = {
+ companyId: string;
+ providerId: string;
+ /** Who configured the integration — the auth-failure recipient. */
+ updatedBy?: string | null;
+};
+
+export type IsolatedStepOutcome<T> =
+ | T
+ | { authFailed: string }
+ | { error: string };
+
+/**
+ * Run one tenant's work as its own step inside a cron that walks every
+ * company. Two things must never happen: a dead OAuth grant must not be
+ * retried (nothing retries it back to life — the step returns `authFailed`,
+ * the failure is counted and the configurer is told), and a tenant that
+ * exhausts its retries must not fail the run for every tenant after it
+ * (`error` is returned and the loop continues).
+ */
+export async function runIsolatedCompanyStep<T>(args: {
+ step: Pick<GetStepTools<typeof inngest>, "run">;
+ client: SupabaseClient<Database>;
+ id: string;
+ target: CompanySweepTarget;
+ fn: () => Promise<T>;
+}): Promise<IsolatedStepOutcome<T>> {
+ const { step, client, id, target, fn } = args;
+ try {
+ // Step output is JSON-serialised on replay; the summaries here are plain
+ // JSON already, so the round-trip is the identity.
+ return (await step.run(id, async () => {
+ try {
+ const result = await fn();
+ // A successful pass proves the grant is alive again
+ await redis
+ .del(authFailureCounterKey(target.companyId, target.providerId))
+ .catch(() => {});
+ return result;
+ } catch (error) {
+ if (error instanceof AccountingAuthError) {
+ const outcome = await recordIntegrationAuthFailure(client, {
+ companyId: target.companyId,
+ providerId: target.providerId,
+ recipientId: target.updatedBy
+ });
+ return { authFailed: `${outcome}: ${error.message}` };
+ }
+ throw error;
+ }
+ })) as IsolatedStepOutcome<T>;
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ console.error(
+ `[ACCOUNTING SYNC] ${target.companyId}/${target.providerId}: ${id} failed after retries: ${message}`
+ );
+ return { error: message };
+ }
+}
diff --git a/packages/jobs/src/inngest/functions/integrations/accounting-consolidation.ts b/packages/jobs/src/inngest/functions/integrations/accounting-consolidation.ts
index 3bf4e6a4c8..27bbc7f2f5 100644
--- a/packages/jobs/src/inngest/functions/integrations/accounting-consolidation.ts
+++ b/packages/jobs/src/inngest/functions/integrations/accounting-consolidation.ts
@@ -72,6 +72,10 @@ import {
} from "@carbon/ee/accounting";
import { PostgresDriver } from "kysely";
import { inngest } from "../../client";
+import {
+ type IsolatedStepOutcome,
+ runIsolatedCompanyStep
+} from "./accounting-auth-failure";
import {
type ConsolidationGroup,
getSyncOperationActor,
@@ -718,7 +722,7 @@ export const accountingConsolidationFunction = inngest.createFunction(
// per-provider consolidation push.
const integrations = await client
.from("companyIntegration")
- .select("id, companyId, metadata")
+ .select("id, companyId, metadata, updatedBy")
.eq("id", ProviderID.XERO)
.eq("active", true);
@@ -736,7 +740,11 @@ export const accountingConsolidationFunction = inngest.createFunction(
hasDailySummarySourceTypes(settings)
);
})
- .map((row) => ({ companyId: row.companyId, providerId: row.id }));
+ .map((row) => ({
+ companyId: row.companyId,
+ providerId: row.id,
+ updatedBy: row.updatedBy
+ }));
}
);
@@ -745,26 +753,30 @@ export const accountingConsolidationFunction = inngest.createFunction(
}
const results: Array<
- { companyId: string; providerId: string } & ConsolidationSummary
+ {
+ companyId: string;
+ providerId: string;
+ } & IsolatedStepOutcome<ConsolidationSummary>
> = [];
for (const target of targets) {
- const result = await step.run(
- `consolidate-${target.companyId}-${target.providerId}`,
- async () => {
+ const result = await runIsolatedCompanyStep({
+ step,
+ client,
+ id: `consolidate-${target.companyId}-${target.providerId}`,
+ target,
+ fn: async () => {
+ // Process-lifetime cached pool shared with events/sync.ts and the
+ // pull sweep — never end it here (see accounting-pull-sweep.ts).
const pool = getPostgresConnectionPool(5);
const database = getPostgresClient(pool, PostgresDriver);
- try {
- return await consolidateCompany({
- companyId: target.companyId,
- providerId: target.providerId as ProviderID,
- database
- });
- } finally {
- await pool.end();
- }
+ return await consolidateCompany({
+ companyId: target.companyId,
+ providerId: target.providerId as ProviderID,
+ database
+ });
}
- );
+ });
results.push({
companyId: target.companyId,
diff --git a/packages/jobs/src/inngest/functions/integrations/accounting-outbound-sweep.ts b/packages/jobs/src/inngest/functions/integrations/accounting-outbound-sweep.ts
index 05fc23dd27..55d09729cd 100644
--- a/packages/jobs/src/inngest/functions/integrations/accounting-outbound-sweep.ts
+++ b/packages/jobs/src/inngest/functions/integrations/accounting-outbound-sweep.ts
@@ -36,6 +36,10 @@ import { NotificationEvent } from "@carbon/notifications";
import { today } from "@internationalized/date";
import { PostgresDriver } from "kysely";
import { inngest } from "../../client";
+import {
+ type IsolatedStepOutcome,
+ runIsolatedCompanyStep
+} from "./accounting-auth-failure";
import {
drainSyncOperations,
getSweepFloorDate,
@@ -405,7 +409,7 @@ export const accountingOutboundSweepFunction = inngest.createFunction(
const targets = await step.run("find-outbound-sweep-targets", async () => {
const integrations = await client
.from("companyIntegration")
- .select("id, companyId")
+ .select("id, companyId, updatedBy")
.in("id", Object.values(ProviderID))
.eq("active", true);
@@ -417,7 +421,8 @@ export const accountingOutboundSweepFunction = inngest.createFunction(
return (integrations.data ?? []).map((row) => ({
companyId: row.companyId,
- providerId: row.id as ProviderID
+ providerId: row.id as ProviderID,
+ updatedBy: row.updatedBy
}));
});
@@ -426,29 +431,37 @@ export const accountingOutboundSweepFunction = inngest.createFunction(
}
const results: Array<
- { companyId: string; providerId: ProviderID } & SweepSummary
+ {
+ companyId: string;
+ providerId: ProviderID;
+ } & IsolatedStepOutcome<SweepSummary>
> = [];
for (const target of targets) {
- const result = await step.run(
- `outbound-sweep-${target.providerId}-${target.companyId}`,
- async () => {
+ const result = await runIsolatedCompanyStep({
+ step,
+ client,
+ id: `outbound-sweep-${target.providerId}-${target.companyId}`,
+ target,
+ fn: async () => {
+ // Process-lifetime cached pool shared with events/sync.ts and the
+ // pull sweep — never end it here (see accounting-pull-sweep.ts).
const pool = getPostgresConnectionPool(5);
const database = getPostgresClient(pool, PostgresDriver);
- try {
- return await sweepCompanyProvider({
- companyId: target.companyId,
- providerId: target.providerId,
- database,
- scope: runId
- });
- } finally {
- await pool.end();
- }
+ return await sweepCompanyProvider({
+ companyId: target.companyId,
+ providerId: target.providerId,
+ database,
+ scope: runId
+ });
}
- );
+ });
- results.push({ ...target, ...result });
+ results.push({
+ companyId: target.companyId,
+ providerId: target.providerId,
+ ...result
+ });
}
return { targets: targets.length, results };
diff --git a/packages/jobs/src/inngest/functions/integrations/accounting-pull-sweep.ts b/packages/jobs/src/inngest/functions/integrations/accounting-pull-sweep.ts
index bf5cdb4100..9eb040ac9f 100644
--- a/packages/jobs/src/inngest/functions/integrations/accounting-pull-sweep.ts
+++ b/packages/jobs/src/inngest/functions/integrations/accounting-pull-sweep.ts
@@ -6,8 +6,8 @@
*
* Every 30 minutes, per company with an ACTIVE accounting integration
* whose provider implements SupportsIncrementalPull (QBO wraps Intuit's
- * Change Data Capture; Rillet lists changed invoice payments; Xero has no
- * implementation yet and is skipped):
+ * Change Data Capture; Rillet lists changed invoice payments; Xero lists
+ * changed /Payments via If-Modified-Since):
*
* 1. Resolve the cursor from `metadata.settings.pullCursor`; default = the
* integration row's `updatedAt` (at-or-after install, so pre-connect
@@ -58,6 +58,10 @@ import {
import { chunkArray } from "@carbon/utils";
import { PostgresDriver } from "kysely";
import { inngest } from "../../client";
+import {
+ type IsolatedStepOutcome,
+ runIsolatedCompanyStep
+} from "./accounting-auth-failure";
import {
drainSyncOperations,
getAdvancedPullCursor,
@@ -417,7 +421,7 @@ export const accountingPullSweepFunction = inngest.createFunction(
const targets = await step.run("find-pull-sweep-targets", async () => {
const integrations = await client
.from("companyIntegration")
- .select("id, companyId")
+ .select("id, companyId, updatedBy")
.in("id", Object.values(ProviderID))
.eq("active", true);
@@ -429,7 +433,8 @@ export const accountingPullSweepFunction = inngest.createFunction(
return (integrations.data ?? []).map((row) => ({
companyId: row.companyId,
- providerId: row.id as ProviderID
+ providerId: row.id as ProviderID,
+ updatedBy: row.updatedBy
}));
});
@@ -438,13 +443,19 @@ export const accountingPullSweepFunction = inngest.createFunction(
}
const results: Array<
- { companyId: string; providerId: ProviderID } & SweepSummary
+ {
+ companyId: string;
+ providerId: ProviderID;
+ } & IsolatedStepOutcome<SweepSummary>
> = [];
for (const target of targets) {
- const result = await step.run(
- `sweep-${target.providerId}-${target.companyId}`,
- async () => {
+ const result = await runIsolatedCompanyStep({
+ step,
+ client,
+ id: `sweep-${target.providerId}-${target.companyId}`,
+ target,
+ fn: async () => {
// getPostgresConnectionPool returns a process-lifetime singleton
// (cached, shared with any other caller requesting the same size) —
// never end it here, or a concurrent invocation queries an ended pool
@@ -457,9 +468,13 @@ export const accountingPullSweepFunction = inngest.createFunction(
database
});
}
- );
+ });
- results.push({ ...target, ...result });
+ results.push({
+ companyId: target.companyId,
+ providerId: target.providerId,
+ ...result
+ });
}
return { targets: targets.length, results };
diff --git a/packages/jobs/src/inngest/functions/integrations/accounting-reconciliation.ts b/packages/jobs/src/inngest/functions/integrations/accounting-reconciliation.ts
index caae5f7afe..b997dad4e3 100644
--- a/packages/jobs/src/inngest/functions/integrations/accounting-reconciliation.ts
+++ b/packages/jobs/src/inngest/functions/integrations/accounting-reconciliation.ts
@@ -61,6 +61,10 @@ import {
} from "@carbon/ee/accounting";
import { PostgresDriver } from "kysely";
import { inngest } from "../../client";
+import {
+ type IsolatedStepOutcome,
+ runIsolatedCompanyStep
+} from "./accounting-auth-failure";
import {
buildRemoteAccountRefIndex,
computeTieOutDeltas,
@@ -978,7 +982,7 @@ export const accountingReconciliationFunction = inngest.createFunction(
// the provider-agnostic fetchRemoteJournalTotals dispatcher.
const integrations = await client
.from("companyIntegration")
- .select("id, companyId, metadata")
+ .select("id, companyId, metadata, updatedBy")
.in("id", Object.values(ProviderID))
.eq("active", true);
@@ -990,7 +994,11 @@ export const accountingReconciliationFunction = inngest.createFunction(
return (integrations.data ?? [])
.filter((row) => resolvePostingSyncSettings(row.metadata).enabled)
- .map((row) => ({ companyId: row.companyId, providerId: row.id }));
+ .map((row) => ({
+ companyId: row.companyId,
+ providerId: row.id,
+ updatedBy: row.updatedBy
+ }));
});
if (targets.length === 0) {
@@ -998,26 +1006,30 @@ export const accountingReconciliationFunction = inngest.createFunction(
}
const results: Array<
- { companyId: string; providerId: string } & ReconciliationSummary
+ {
+ companyId: string;
+ providerId: string;
+ } & IsolatedStepOutcome<ReconciliationSummary>
> = [];
for (const target of targets) {
- const result = await step.run(
- `reconcile-${target.companyId}-${target.providerId}`,
- async () => {
+ const result = await runIsolatedCompanyStep({
+ step,
+ client,
+ id: `reconcile-${target.companyId}-${target.providerId}`,
+ target,
+ fn: async () => {
+ // Process-lifetime cached pool shared with events/sync.ts and the
+ // pull sweep — never end it here (see accounting-pull-sweep.ts).
const pool = getPostgresConnectionPool(5);
const database = getPostgresClient(pool, PostgresDriver);
- try {
- return await reconcileCompany({
- companyId: target.companyId,
- providerId: target.providerId as ProviderID,
- database
- });
- } finally {
- await pool.end();
- }
+ return await reconcileCompany({
+ companyId: target.companyId,
+ providerId: target.providerId as ProviderID,
+ database
+ });
}
- );
+ });
results.push({
companyId: target.companyId,
diff --git a/packages/jobs/src/inngest/functions/integrations/accounting-sync-operations.ts b/packages/jobs/src/inngest/functions/integrations/accounting-sync-operations.ts
index e2177c7cc6..a942488d92 100644
--- a/packages/jobs/src/inngest/functions/integrations/accounting-sync-operations.ts
+++ b/packages/jobs/src/inngest/functions/integrations/accounting-sync-operations.ts
@@ -28,6 +28,7 @@
*/
import type { Database } from "@carbon/database";
import {
+ AccountingAuthError,
type AccountingEntityType,
type AccountingProvider,
type BatchSyncResult,
@@ -698,9 +699,11 @@ export function getSyncOperationCloseDecision(
* through the JournalEntrySyncer.
*
* A RatelimitError propagates so the caller's retry machinery applies;
- * claimed rows stay In Flight and become re-claimable once stale. Any other
- * group-level error marks that group's operations Failed and the drain
- * continues with the next group.
+ * claimed rows stay In Flight and become re-claimable once stale. An
+ * AccountingAuthError propagates the same way — a dead grant fails every
+ * group identically, and the cron's per-tenant handler must see it to count
+ * it toward auto-disable. Any other group-level error marks that group's
+ * operations Failed and the drain continues with the next group.
*/
export async function drainSyncOperations(args: {
client: SupabaseClient<Database>;
@@ -842,6 +845,9 @@ export async function drainSyncOperations(args: {
});
}
} catch (error) {
+ if (error instanceof AccountingAuthError) {
+ throw error;
+ }
if (error instanceof RatelimitError) {
const { retryAfterSeconds } = error.rateLimitInfo;
console.warn(
diff --git a/packages/jobs/src/inngest/functions/scheduled/mrp.ts b/packages/jobs/src/inngest/functions/scheduled/mrp.ts
index ace1f8df22..7b67f9a174 100644
--- a/packages/jobs/src/inngest/functions/scheduled/mrp.ts
+++ b/packages/jobs/src/inngest/functions/scheduled/mrp.ts
@@ -11,7 +11,7 @@ export const mrpFunction = inngest.createFunction(
{ cron: "0 */3 * * *" },
async ({ step, logger }) => {
const serviceRole = getCarbonServiceRole();
- await step.run("run-mrp-for-all-companies", async () => {
+ const scheduled = await step.run("find-companies", async () => {
logger.info(
`Scheduled MRP Calculation Started: ${new Date().toISOString()}`
);
@@ -66,11 +66,21 @@ export const mrpFunction = inngest.createFunction(
logger.warn("No companies to run MRP for", {
companies: companies.data.length
});
- return;
}
- for (const company of scheduled) {
- try {
+ return scheduled;
+ });
+
+ // One step per company: each is its own invocation with its own retries
+ // and is memoized on replay, so a slow or failing tenant costs only
+ // itself. All companies in one step was one Vercel invocation, timed out
+ // as the tenant count grew, and every retry restarted from company #1.
+ // ponytail: 1000-step-per-run ceiling; fan out with step.sendEvent when
+ // the company count nears it.
+ const failed: string[] = [];
+ for (const company of scheduled) {
+ try {
+ await step.run(`mrp-${company.id}`, async () => {
// Run MRP in-process (Node) instead of invoking the `mrp` edge
// function; runMrp throws on failure.
await runMrp(serviceRole, getJobDatabaseClient(), {
@@ -80,12 +90,15 @@ export const mrpFunction = inngest.createFunction(
userId: "system"
});
logger.info(`Successfully ran MRP for company ${company.name}`);
- } catch (error) {
- logger.error(`Failed to run MRP for company ${company.name}`, {
- error
- });
- }
+ });
+ } catch (error) {
+ logger.error(`Failed to run MRP for company ${company.name}`, {
+ error
+ });
+ failed.push(company.id);
}
- });
+ }
+
+ return { companies: scheduled.length, failed };
}
);