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.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
perf(erp): stop the app shell downloading whole tables from the browser (#1663)
Sidd147872936b6
diff --git a/.claude/rules/database-patterns.md b/.claude/rules/database-patterns.mdindex 01f2d58237..0888e8dbcd 100644--- a/.claude/rules/database-patterns.md+++ b/.claude/rules/database-patterns.md@@ -75,7 +75,9 @@ Conventions (see also `conventions-services.md`):- The ten endpoints backed by the big multi-join **views** (`parts`, `materials`, `tools`, `consumables`, `services`, `purchaseOrders`, `quotes`, `salesOrders`, `purchaseInvoices`, `salesInvoices`) additionally select an explicit `*_LIST_COLUMNS` constant instead of `select("*")`, so Postgres can prune the views' unreferenced computed columns. Adding a column to one of those tables means adding it to the constant — `apps/erp/test/list-select-columns.test.ts` fails if an `accessorKey` is missing, because the CSV export reads accessors untyped. The rationale lives once on `LIST_COUNT` in `apps/erp/app/utils/query.ts`, not at each constant.- Use `sanitize(...)` (re-exported from `@carbon/utils`) to strip empty values before insert/update.- Upserts are done either with a manual `id ? update : insert` branch or supabase's native `.upsert(...)`; both are in use.-- `fetchAllFromTable(client, table, columns, qb)` (from `@carbon/database`) pages through large result sets.+- `fetchAllFromTable(client, table, columns, qb)` (from `@carbon/database`) pages through large result sets:+ the first page alone, then the rest in concurrent waves, and deliberately WITHOUT a count — `count: "exact"`+ there was a `COUNT(*) OVER ()` on every page (see `LIST_COUNT` above for the same trap on list endpoints).## N+1 readsdiff --git a/apps/erp/app/components/Form/Item.tsx b/apps/erp/app/components/Form/Item.tsxindex a47bcef456..e5ec615539 100644--- a/apps/erp/app/components/Form/Item.tsx+++ b/apps/erp/app/components/Form/Item.tsx@@ -27,6 +27,7 @@ import {useMount} from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";+import { useQuery } from "@tanstack/react-query";import { useEffect, useMemo, useRef, useState } from "react";import { LuFilter, LuTriangleAlert } from "react-icons/lu";import { useFetcher } from "react-router";@@ -40,6 +41,7 @@ import { itemType, methodItemType } from "~/modules/shared";import { useItems } from "~/stores";import { latestRevisionByReadableId } from "~/stores/items";import { path } from "~/utils/path";+import { getCompanyId, itemQuantitiesQuery } from "~/utils/react-query";import { MethodItemTypeIcon } from "../Icons";import { ItemLifecycleBadge } from "../ItemLifecycleBadge";import type { EntityKey } from "./emptyStates";@@ -100,6 +102,47 @@ const useTranslatedItemType = () => {};};+// Stable identity, so a picker with no quantities does not re-run its options+// memo on every render.+const NO_QUANTITIES: Record<string, number> = {};++/**+ * On-hand per item for the option badge, keyed by the location in play ("all"+ * totals every location). This used to ride on the items store, which meant the+ * whole `itemStockQuantities` table (item x location) was downloaded into the+ * browser on every page load, re-polled every 10 minutes and re-read in full on+ * every stock movement — to decorate a dropdown. Fetching it here means pages+ * with no item picker fetch nothing, and the shared client dedupes across every+ * picker on the page.+ *+ * An OBSERVED query, not the imperative `cachedApiQuery` read-through: a stock+ * movement invalidates this key (`RealtimeDataProvider`), and only an observer+ * re-fetches and re-renders. Copying one result into state left an open picker+ * showing yesterday's numbers until it remounted.+ */+function useItemQuantities(locationId?: string) {+ const scope = locationId ?? "all";+ const { queryKey, staleTime } = itemQuantitiesQuery(scope, getCompanyId());++ const { data } = useQuery({+ queryKey,+ staleTime,+ queryFn: async () => {+ const response = await fetch(path.to.api.itemQuantities(scope));+ if (!response.ok) {+ throw new Error(`Request failed with status ${response.status}`);+ }+ return (await response.json()) as {+ data: Record<string, number> | null;+ };+ }+ });++ // A badge is decoration — a failed read leaves it off rather than breaking+ // the picker.+ return data?.data ?? NO_QUANTITIES;+}+const Item = ({name,label,@@ -117,6 +160,7 @@ const Item = ({const { t } = useLingui();const translateItemType = useTranslatedItemType();const [items] = useItems();+ const quantities = useItemQuantities(props.locationId);const options = useMemo(() => {let filtered = items.filter((item) => {@@ -148,9 +192,7 @@ const Item = ({}let results = filtered.map((item) => {- const scopedQuantity = props.locationId- ? item.quantityByLocation?.[props.locationId]- : item.quantityOnHand;+ const scopedQuantity = quantities[item.id];return {value: item.id,label: item.supersessionMode ? (@@ -180,10 +222,10 @@ const Item = ({return results;}, [items,+ quantities,props?.includeInactive,props.blacklist,props.latestRevisionOnly,- props.locationId,props.replenishmentSystem,props.whitelist,type,diff --git a/apps/erp/app/components/RealtimeDataProvider.tsx b/apps/erp/app/components/RealtimeDataProvider.tsxindex 45eab49c73..2ff50191db 100644--- a/apps/erp/app/components/RealtimeDataProvider.tsx+++ b/apps/erp/app/components/RealtimeDataProvider.tsx@@ -3,8 +3,8 @@import { useCarbon } from "@carbon/auth";import { type Database, fetchAllFromTable } from "@carbon/database";import { getLogger } from "@carbon/logger";-import { useInterval, useRealtimeChannel } from "@carbon/react";-import { useEffect, useRef } from "react";+import { useRealtimeChannel } from "@carbon/react";+import { useEffect } from "react";import { useUser } from "~/hooks";import {upsertIntoListStore,@@ -15,6 +15,7 @@ import {} from "~/stores";import type { Item } from "~/stores/items";import type { ListItem } from "~/types";+import { ITEM_QUANTITIES_QUERY_KEY } from "~/utils/react-query";const logger = getLogger("erp", "realtime-data-provider");@@ -49,86 +50,6 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {const [, setCustomers] = useCustomers();const [, setPeople] = usePeople();- const fetchQuantities = async () => {- if (!carbon || !companyId) return;- // A company switch (including A -> B -> A) bumps this. Comparing ids alone- // would let a request from the FIRST visit to A land after returning to A- // and overwrite newer quantities.- const requestedGeneration = quantitiesGeneration.current;-- const { data, error } = await fetchAllFromTable<{- itemId: string;- locationId: string;- quantityOnHand: number;- }>(- carbon,- "itemStockQuantities",- "itemId, locationId, quantityOnHand",- // Ordered by the rest of the table's key: fetchAllFromTable pages, and- // without a stable sort a concurrent write can shift rows across a page- // boundary, dropping or duplicating one in `totalMap`.- (query) =>- query.eq("companyId", companyId).order("itemId").order("locationId")- );-- if (error || !data) return;- if (quantitiesGeneration.current !== requestedGeneration) return;-- const totalMap = new Map<string, number>();- const locationMap = new Map<string, Record<string, number>>();-- for (const row of data) {- if (!row.itemId) continue;- const qty = Number(row.quantityOnHand) || 0;- const locId = row.locationId || "";-- totalMap.set(row.itemId, (totalMap.get(row.itemId) ?? 0) + qty);-- if (!locationMap.has(row.itemId)) locationMap.set(row.itemId, {});- if (locId) locationMap.get(row.itemId)![locId] = qty;- }-- setItems((currentItems) =>- currentItems.map((item) => ({- ...item,- quantityOnHand: totalMap.get(item.id) ?? 0,- quantityByLocation: locationMap.get(item.id) ?? {}- }))- );- };-- // A posting writes one itemStockQuantities row per (item, location) it- // touched, so a single receipt can emit a burst. Coalesce them into one- // refetch — the same 1.5s quiet window `useDebouncedRealtime` uses.- const quantitiesRefresh = useRef<ReturnType<typeof setTimeout> | null>(null);- const quantitiesGeneration = useRef(0);-- // Bumped on every company change so in-flight reads and pending timers from- // the previous company are discarded rather than applied to the new one.- // biome-ignore lint/correctness/useExhaustiveDependencies: keyed on companyId by design- useEffect(() => {- quantitiesGeneration.current += 1;- if (quantitiesRefresh.current) {- clearTimeout(quantitiesRefresh.current);- quantitiesRefresh.current = null;- }- }, [companyId]);-- const scheduleQuantitiesRefresh = () => {- if (quantitiesRefresh.current) clearTimeout(quantitiesRefresh.current);- quantitiesRefresh.current = setTimeout(() => {- quantitiesRefresh.current = null;- fetchQuantities();- }, 1500);- };-- useEffect(- () => () => {- if (quantitiesRefresh.current) clearTimeout(quantitiesRefresh.current);- },- []- );-const hydrate = async () => {const idb = (await import("localforage")).default;const requestedCompanyId = companyId;@@ -261,8 +182,6 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {idb.setItem(`customers:${requestedCompanyId}`, customers.data),idb.setItem(`people:${requestedCompanyId}`, people.data)]);-- fetchQuantities();};// Re-run when auth becomes ready: `hydrate()` bails if `carbon` / `accessToken` are missing,@@ -274,8 +193,11 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {hydrate().catch((err) => logger.error("hydrate failed", { error: err }));}, [companyId, carbon, accessToken]);- useInterval(fetchQuantities, companyId ? 10 * 60 * 1000 : null);-+ // Every subscription below is filtered by `companyId` server-side. Without it+ // each tenant's row changes are fanned out to every connected client and then+ // discarded in JS — the client-side guards stay as defence in depth. The filter+ // holds on DELETE too: `companyId` is part of each table's composite PK, so it+ // is present in a payload that otherwise carries only key columns.useRealtimeChannel({topic: `realtime:core`,dependencies: [companyId],@@ -286,7 +208,8 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {{event: "*",schema: "public",- table: "item"+ table: "item",+ filter: `companyId=eq.${companyId}`},(payload) => {switch (payload.eventType) {@@ -366,10 +289,8 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {event: "*",schema: "public",// Quantities are maintained incrementally by triggers on itemLedger,- // so this fires on the posting itself rather than up to 40 min later- // (the old 30 min matview refresh + the 10 min poll below).- // Server-side filter: with ~1600 tenants an unfiltered subscription- // would fan every company's postings out to every client.+ // so this fires on the posting itself rather than up to 30 min later+ // (the matview refresh this replaced).table: "itemStockQuantities",filter: `companyId=eq.${companyId}`},@@ -380,7 +301,21 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {payload.eventType === "DELETE" ? payload.old : payload.new;if (row && "companyId" in row && row.companyId !== companyId)return;- scheduleQuantitiesRefresh();+ // Invalidate rather than refetch: the on-hand map is fetched by the+ // item picker (`useItemQuantities` in `~/components/Form/Item`) and+ // only when one is mounted. Re-reading the whole table here cost a+ // full download per burst of stock movements for a dropdown badge+ // that may not be on screen at all.+ // Every key under this prefix, not just this company's: the+ // companyId term of the key comes from `getCompanyId()`, which+ // reads `document.cookie` — and every cookie here is httpOnly, so+ // it is always "null". Matching on it invalidated nothing. Keys for+ // another company would only exist after a company switch, which+ // reloads the page and empties this in-memory cache anyway.+ window.clientCache?.invalidateQueries({+ predicate: (query) =>+ (query.queryKey as unknown[])[0] === ITEM_QUANTITIES_QUERY_KEY+ });}).on(@@ -388,7 +323,8 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {{event: "*",schema: "public",- table: "customer"+ table: "customer",+ filter: `companyId=eq.${companyId}`},(payload) => {switch (payload.eventType) {@@ -444,7 +380,8 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {{event: "*",schema: "public",- table: "supplier"+ table: "supplier",+ filter: `companyId=eq.${companyId}`},(payload) => {switch (payload.eventType) {@@ -502,7 +439,8 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {{event: "*",schema: "public",- table: "employee"+ table: "employee",+ filter: `companyId=eq.${companyId}`},async (payload) => {// TODO: there's a cleaner way of doing this, but since customers and suppliersdiff --git a/apps/erp/app/hooks/useRealtime.tsx b/apps/erp/app/hooks/useRealtime.tsxindex 7223ebe970..5fe3cfccde 100644--- a/apps/erp/app/hooks/useRealtime.tsx+++ b/apps/erp/app/hooks/useRealtime.tsx@@ -20,6 +20,15 @@ export function useRealtime(const revalidator = useRevalidator();const timeout = useRef<ReturnType<typeof setTimeout> | null>(null);+ // Default to the caller's company rather than subscribing to every tenant's+ // writes and discarding them below — with ~1600 tenants an unfiltered+ // subscription fans every company's changes out to every client. A caller+ // that passes its own narrower filter (`runId=eq.…`) keeps it. This assumes+ // the table has a `companyId` column; every table reached without a filter+ // does. Pass an explicit filter for one that does not — a filter on a column+ // that doesn't exist delivers nothing at all, silently.+ const scopedFilter = filter ?? `companyId=eq.${company.id}`;+useEffect(() => () => {if (timeout.current) clearTimeout(timeout.current);@@ -29,16 +38,14 @@ export function useRealtime(const channel = useRealtimeChannel({topic: `postgres_changes:${table}`,- dependencies: [company.id, filter, debounceMs],+ dependencies: [company.id, scopedFilter, debounceMs],setup(channel) {return channel.on("postgres_changes",- { event: "*", schema: "public", table: table, filter: filter },+ { event: "*", schema: "public", table: table, filter: scopedFilter },(payload) => {- // The row lives under `new`/`old`, never on the payload itself. This- // guard is what stops the subscriptions that pass no `filter`- // (journal, purchaseOrder, changeOrder, printJob, part) from- // revalidating on another tenant's writes.+ // The row lives under `new`/`old`, never on the payload itself.+ // Defence in depth behind the server-side filter above.const row = (payload.new ?? payload.old) as| { companyId?: string }| undefined;diff --git a/apps/erp/app/modules/items/items.service.ts b/apps/erp/app/modules/items/items.service.tsindex 36bfbedea3..a5261ce08a 100644--- a/apps/erp/app/modules/items/items.service.ts+++ b/apps/erp/app/modules/items/items.service.ts@@ -885,6 +885,47 @@ export async function getItemQuantities(.maybeSingle();}+/**+ * On-hand quantity per item for the Item picker's badge, as a plain map.+ *+ * `locationId` of "all" totals every location (including the '' bucket for+ * ledger rows with no location), matching what the picker shows when no+ * location is in play. Zero rows are dropped — the picker renders no badge for+ * an item it has no row for, so they carry no information and are the bulk of+ * the table on a tenant with history.+ */+export async function getItemStockQuantitiesByLocation(+ client: SupabaseClient<Database>,+ companyId: string,+ locationId: string+) {+ const { data, error } = await fetchAllFromTable<{+ itemId: string;+ quantityOnHand: number;+ }>(client, "itemStockQuantities", "itemId, quantityOnHand", (query) => {+ const scoped = query+ .eq("companyId", companyId)+ .neq("quantityOnHand", 0)+ // Total order across the whole key: fetchAllFromTable pages, and without+ // one a concurrent write can shift a row across a page boundary.+ .order("itemId")+ .order("locationId");++ return locationId === "all" ? scoped : scoped.eq("locationId", locationId);+ });++ if (error) return { data: null, error };++ const quantities: Record<string, number> = {};+ for (const row of data ?? []) {+ if (!row.itemId) continue;+ quantities[row.itemId] =+ (quantities[row.itemId] ?? 0) + (Number(row.quantityOnHand) || 0);+ }++ return { data: quantities, error: null };+}+export async function getItemReplenishment(client: SupabaseClient<Database>,itemId: string,diff --git a/apps/erp/app/routes/api+/items.quantities.$locationId.ts b/apps/erp/app/routes/api+/items.quantities.$locationId.tsnew file mode 100644index 0000000000..c6fbd7214a--- /dev/null+++ b/apps/erp/app/routes/api+/items.quantities.$locationId.ts@@ -0,0 +1,14 @@+import { requirePermissions } from "@carbon/auth/auth.server";+import type { LoaderFunctionArgs } from "react-router";+import { getItemStockQuantitiesByLocation } from "~/modules/items";++export async function loader({ request, params }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ view: "parts"+ });++ const { locationId } = params;+ if (!locationId) throw new Error("Could not find locationId");++ return await getItemStockQuantitiesByLocation(client, companyId, locationId);+}diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.jsonindex 1b49101fb4..79647020b6 100644--- a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json@@ -1,5 +1,5 @@{- "totalTools": 1577,+ "totalTools": 1578,"modules": 15,"tools": [{"name":"account_deleteUserAttributeValue","classification":"DESTRUCTIVE","paramCount":2,"schema":"0d38e12233b4","response":"bcde375ebd4c","injectAuth":"companyId","permission":"none","paginates":false},@@ -437,6 +437,7 @@{"name":"items_getItemQuantities","classification":"READ","paramCount":2,"schema":"ade4704d7338","response":"9fc7a6c9f2e3","injectAuth":"companyId","permission":"parts:view","paginates":false},{"name":"items_getItemReplenishment","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"f399bb7eda67","injectAuth":"companyId","permission":"parts:view","paginates":false},{"name":"items_getItemShelfLife","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"a406f3a83a89","injectAuth":"companyId","permission":"parts:view","paginates":false},+ {"name":"items_getItemStockQuantitiesByLocation","classification":"READ","paramCount":1,"schema":"de371a276a58","response":"96915ea19193","injectAuth":"companyId","permission":"parts:view","paginates":false},{"name":"items_getItemStorageUnitQuantities","classification":"READ","paramCount":2,"schema":"ade4704d7338","response":"880fa3aa7279","injectAuth":"companyId","permission":"parts:view","paginates":false},{"name":"items_getItemSupersededBy","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"8e2ea57c0664","injectAuth":"companyId","permission":"parts:view","paginates":false},{"name":"items_getItemSupersession","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"0c693c4f3dcb","injectAuth":"companyId","permission":"parts:view","paginates":false},diff --git a/apps/erp/app/stores/items.ts b/apps/erp/app/stores/items.tsindex af27de06f9..5f52a5ee03 100644--- a/apps/erp/app/stores/items.ts+++ b/apps/erp/app/stores/items.ts@@ -13,8 +13,6 @@ export type Item = ListItem & {unitOfMeasureCode: string;type: Database["public"]["Enums"]["itemType"];active: boolean;- quantityOnHand?: number;- quantityByLocation?: Record<string, number>;supersessionMode?: Database["public"]["Enums"]["supersessionMode"] | null;successorItemId?: string | null;};diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.tsindex 62de0b4253..0d81187149 100644--- a/apps/erp/app/utils/path.ts+++ b/apps/erp/app/utils/path.ts@@ -142,6 +142,8 @@ export const path = {generatePath(`${api}/items/${itemId}/make-method-status`),itemMpns: `${api}/items/mpns`,itemPostingGroups: `${api}/items/groups`,+ itemQuantities: (locationId: string) =>+ generatePath(`${api}/items/quantities/${locationId}`),itemRecipeProcesses: (itemId: string) =>generatePath(`${api}/items/${itemId}/recipe-processes`),jiraCreateIssue: `${api}/integrations/jira/issue/create`,diff --git a/apps/erp/app/utils/react-query.ts b/apps/erp/app/utils/react-query.tsindex 1801c60d70..86c050c9af 100644--- a/apps/erp/app/utils/react-query.ts+++ b/apps/erp/app/utils/react-query.ts@@ -123,6 +123,16 @@ export const itemPostingGroupsQuery = (companyId: string | null) => ({staleTime: RefreshRate.Low});+export const ITEM_QUANTITIES_QUERY_KEY = "itemQuantities";++export const itemQuantitiesQuery = (+ locationId: string,+ companyId: string | null+) => ({+ queryKey: [ITEM_QUANTITIES_QUERY_KEY, companyId ?? "null", locationId],+ staleTime: RefreshRate.High+});+export const locationsQuery = (companyId: string | null) => ({queryKey: ["locations", companyId ?? "null"],staleTime: RefreshRate.Lowdiff --git a/packages/database/AGENTS.md b/packages/database/AGENTS.mdindex acfd2247a8..efdce5e0a6 100644--- a/packages/database/AGENTS.md+++ b/packages/database/AGENTS.md@@ -8,7 +8,11 @@ DB types, Supabase/Kysely clients, audit config, event system types, rate limiti- Tables: composite PK `("id", "companyId")`, `id` default `id()` or `id('prefix')` — never raw UUID. Audit columns (`createdBy`/`createdAt`/`updatedBy`/`updatedAt`) with inline `REFERENCES "user"("id")`.- RLS: four policies named exactly `SELECT`/`INSERT`/`UPDATE`/`DELETE`. SELECT uses `get_companies_with_employee_role()`, writes use `get_companies_with_employee_permission('<module>_<action>')`. Schema-qualify tables, cast `::text[]`.- Import `Database` type from `@carbon/database`; `KyselyDatabase` / `Kysely` from `@carbon/database/client`. Never hand-edit `src/types.ts` — it's generated.-- Use `fetchAllFromTable` / `fetchAllRecords` for paginated reads that exceed the 1000-row Supabase limit.+- Use `fetchAllFromTable` for paginated reads that exceed the 1000-row Supabase limit. It pages+ without `count: "exact"` (a `COUNT(*) OVER ()` per page is not free) and fetches the pages past+ the first concurrently. `fetchAllRecords` is the same pager over a query FACTORY (`() => builder`)+ — a factory, because supabase-js builders are mutable, so concurrent awaits on one builder all+ fetch whichever `.range()` was set last.## Ask First@@ -35,7 +39,7 @@ pnpm --filter @carbon/database typecheck| Subpath | Provides ||---------|----------|-| `.` (index) | `Database` type, `fetchAllFromTable`, `fetchAllRecords`, `fetchRecordsInBatches` |+| `.` (index) | `Database` type, `fetchAllFromTable`, `fetchAllRecords` (takes a query factory), `fetchRecordsInBatches` || `./client` | `Kysely`, `KyselyDatabase`, Postgres pool factories (`getPostgresClient`, `getPostgresConnectionPool`) || `./datetime` | Node re-export of `supabase/functions/lib/datetime.ts` — the edge-runtime datetime helpers (`datetime`, `getCompanyTimeZone`, `getLocationTimeZone`) for Node consumers || `./methods` | Node re-export of `supabase/functions/lib/methods.ts` — shared make-method helpers |diff --git a/packages/database/package.json b/packages/database/package.jsonindex 0113e00506..f0570454c3 100644--- a/packages/database/package.json+++ b/packages/database/package.json@@ -13,7 +13,8 @@"tsup": "catalog:","tsx": "catalog:","typescript": "catalog:",- "uuid": "9.0.0"+ "uuid": "9.0.0",+ "vitest": "catalog:"},"exports": {".": "./src/index.ts",@@ -49,6 +50,8 @@"db:seed:dev": "tsx src/seed-dev.ts","deploy": "supabase link --project-ref $SUPABASE_PROJECT_ID && supabase db push","lint": "biome lint --write ",+ "test": "vitest run",+ "test:watch": "vitest","typecheck": "tsgo --noEmit"},"sideEffects": false,diff --git a/packages/database/src/utils.test.ts b/packages/database/src/utils.test.tsnew file mode 100644index 0000000000..214b9fb3c3--- /dev/null+++ b/packages/database/src/utils.test.ts@@ -0,0 +1,127 @@+import { describe, expect, it } from "vitest";+import { fetchAllRecords } from "./utils";++// `fetchAllRecords` is the only thing standing between a >1000-row read and a+// silently truncated one, and the local dev stack does not enforce `max_rows`, so+// the paging arithmetic can only be pinned here. The contract: every row in+// order, one request when the table fits in a page, pages past the first issued+// concurrently, an error on any page propagating instead of partial data, and a+// server that ignores `Range` tripping the backstop rather than hanging.++type Row = { id: number };++/**+ * Mimics the two calls fetchAllRecords makes: the factory produces a fresh+ * builder, then `.range(from, to)` resolves to a PostgREST-shaped result. A+ * single shared builder would be wrong — the real one is mutable, which is why+ * the function takes a factory at all.+ */+function fakeTable(+ rows: Row[],+ opts: { ignoreRange?: boolean; errorOnPage?: number } = {}+) {+ const ranges: [number, number][] = [];+ let inFlight = 0;+ let maxInFlight = 0;++ const build = () =>+ ({+ range: (from: number, to: number) => {+ ranges.push([from, to]);+ inFlight++;+ maxInFlight = Math.max(maxInFlight, inFlight);+ return new Promise((resolve) => {+ setTimeout(() => {+ inFlight--;+ if (opts.errorOnPage === from / 1000) {+ resolve({ data: null, error: { message: "boom" } });+ return;+ }+ resolve({+ data: opts.ignoreRange+ ? rows.slice(0, to - from + 1)+ : rows.slice(from, to + 1),+ error: null+ });+ }, 0);+ });+ }+ // biome-ignore lint/suspicious/noExplicitAny: test double for a postgrest builder+ }) as any;++ return { build, ranges, maxInFlight: () => maxInFlight };+}++const rowsOf = (n: number) => Array.from({ length: n }, (_, i) => ({ id: i }));++describe("fetchAllRecords", () => {+ it("makes exactly one request when the table fits in a page", async () => {+ const { build, ranges } = fakeTable(rowsOf(77));++ const result = await fetchAllRecords<Row>(build);++ expect(ranges).toEqual([[0, 999]]);+ expect(result.data).toHaveLength(77);+ expect(result.count).toBe(77);+ });++ it("returns every row in order across pages", async () => {+ const { build } = fakeTable(rowsOf(2500));++ const result = await fetchAllRecords<Row>(build);++ expect(result.error).toBeNull();+ expect(result.data).toHaveLength(2500);+ expect(result.data?.map((r) => r.id)).toEqual(+ rowsOf(2500).map((r) => r.id)+ );+ });++ it("stops on an exact multiple without duplicating rows", async () => {+ const { build } = fakeTable(rowsOf(2000));++ const result = await fetchAllRecords<Row>(build);++ expect(result.data).toHaveLength(2000);+ expect(new Set(result.data?.map((r) => r.id)).size).toBe(2000);+ });++ it("issues the pages past the first concurrently", async () => {+ const { build, maxInFlight } = fakeTable(rowsOf(4500));++ await fetchAllRecords<Row>(build);++ expect(maxInFlight()).toBeGreaterThan(1);+ });++ it("propagates an error rather than returning a partial read", async () => {+ const { build } = fakeTable(rowsOf(4500), { errorOnPage: 2 });++ const result = await fetchAllRecords<Row>(build);++ expect(result.data).toBeNull();+ expect(result.error?.message).toBe("boom");+ });++ it("ignores a failure on a speculative page past the end of the data", async () => {+ // 1500 rows: page 1 is short, so it ends the read. Pages 2-4 went out in+ // the same wave before that was known, and a read past the end can fail+ // (PostgREST answers an out-of-range `Range` with 416) — that must not+ // discard rows already in hand.+ const { build } = fakeTable(rowsOf(1500), { errorOnPage: 2 });++ const result = await fetchAllRecords<Row>(build);++ expect(result.error).toBeNull();+ expect(result.data).toHaveLength(1500);+ });++ it("refuses to return a partial read when the server ignores Range", async () => {+ const { build } = fakeTable(rowsOf(1000), { ignoreRange: true });++ const result = await fetchAllRecords<Row>(build);++ expect(result.data).toBeNull();+ expect(result.error?.message).toContain("exceeded");+ });+});diff --git a/packages/database/src/utils.ts b/packages/database/src/utils.tsindex 6ecdd6281d..f8a1f86c84 100644--- a/packages/database/src/utils.ts+++ b/packages/database/src/utils.ts@@ -38,6 +38,11 @@ export const isKysely = (db: AnyPostgresClient): db is Kysely<KyselyDatabase> =>typeof (db as Kysely<KyselyDatabase>).selectFrom === "function";const BATCH_SIZE = 1000;+// How many pages to request at once past the first. Serial paging made a 150k-row+// table 150 sequential round trips.+const PAGE_CONCURRENCY = 4;+// Backstop only: a server that ignored `Range` would otherwise loop forever.+const MAX_PAGES = 1000;export type PaginatedResult<T> =| {@@ -51,55 +56,72 @@ export type PaginatedResult<T> =error: PostgrestError;};+type PageQuery<T extends object> = PostgrestFilterBuilder<+ PostgrestClientOptions,+ Database["public"],+ Record<string, unknown>,+ T[]+>;+/*** Fetches all records from a table by automatically handling pagination- * to work around Supabase's 1000 row limit per request+ * to work around Supabase's 1000 row limit per request.+ *+ * Takes a FACTORY, not a query: supabase-js builders are mutable — `.range()`+ * sets `this.url.searchParams` and returns `this` — so concurrent awaits on one+ * builder would all fetch whichever range was set last. Mirrors the Deno sibling+ * `supabase/functions/lib/fetch-all.ts`.*/export async function fetchAllRecords<T extends object>(- baseQuery: PostgrestFilterBuilder<- PostgrestClientOptions,- Database["public"],- Record<string, unknown>,- T[]- >+ buildQuery: () => PageQuery<T>): Promise<PaginatedResult<T>> {- const allData: T[] = [];- let offset = 0;- let totalCount: number = 0;- let hasMore = true;-- while (hasMore) {- // Clone the query and add range for this batch- const query = baseQuery.range(offset, offset + BATCH_SIZE - 1);+ const fetchPage = async (page: number) =>+ await buildQuery().range(page * BATCH_SIZE, (page + 1) * BATCH_SIZE - 1);- const result = await query;-- if (result.error) {- return {- data: null,- count: null,- error: result.error- };- }+ // The first page alone, so a table that fits in one page stays at one request.+ const first = await fetchPage(0);+ if (first.error) {+ return { data: null, count: null, error: first.error };+ }- if (result.data) {- allData.push(...result.data);- }+ const allData: T[] = first.data ?? [];+ if (allData.length < BATCH_SIZE) {+ return { data: allData, count: allData.length, error: null };+ }- // Set total count from first request- if (offset === 0) {- totalCount = result.count ?? 0;+ for (let page = 1; page < MAX_PAGES; page += PAGE_CONCURRENCY) {+ const results = await Promise.all(+ Array.from({ length: PAGE_CONCURRENCY }, (_, i) => fetchPage(page + i))+ );++ // In page order, so the first SHORT page ends the read. Pages after it are+ // speculative — they were issued before we knew where the data stopped, and+ // a read past the end can legitimately fail (PostgREST answers an+ // out-of-range `Range` with 416). Scanning every result for an error first+ // would turn that into a failed fetch after the rows were already in hand.+ for (const result of results) {+ if (result.error) {+ return { data: null, count: null, error: result.error };+ }++ const rows = (result.data ?? []) as T[];+ allData.push(...rows);+ if (rows.length < BATCH_SIZE) {+ return { data: allData, count: allData.length, error: null };+ }}-- // Check if we have more data to fetch- hasMore = result.data && result.data.length === BATCH_SIZE;- offset += BATCH_SIZE;}return {- data: allData,- count: totalCount,- error: null+ data: null,+ count: null,+ error: {+ message: `fetchAllRecords exceeded ${MAX_PAGES} pages — refusing to return a partial read`,+ details: "",+ hint: "",+ code: "PGRST_PAGINATION_LIMIT",+ name: "PostgrestError"+ } as PostgrestError};}@@ -114,17 +136,18 @@ export async function fetchAllFromTable<T extends object>(selectColumns: string = "*",filterFn?: (query: any) => any): Promise<PaginatedResult<T>> {- let baseQuery = client- // @ts-expect-error- .from(tableName)- .select(selectColumns, { count: "exact" });-- if (filterFn) {- baseQuery = filterFn(baseQuery);- }+ // No `count: "exact"` — that is a COUNT(*) OVER () across the whole filtered+ // set on EVERY page, and no caller reads the returned count.+ const buildQuery = () => {+ const query = client+ // @ts-expect-error+ .from(tableName)+ .select(selectColumns);++ return (filterFn ? filterFn(query) : query) as PageQuery<T>;+ };- // @ts-expect-error- return fetchAllRecords(baseQuery);+ return fetchAllRecords<T>(buildQuery);}/**diff --git a/packages/database/vitest.config.ts b/packages/database/vitest.config.tsnew file mode 100644index 0000000000..cb2172bb25--- /dev/null+++ b/packages/database/vitest.config.ts@@ -0,0 +1,4 @@+import baseConfig from "@carbon/config/vitest";+import { defineConfig, mergeConfig } from "vitest/config";++export default mergeConfig(baseConfig, defineConfig({ test: {} }));diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex a472798b00..e97c547ec3 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -2150,6 +2150,9 @@ importers:uuid:specifier: 9.0.0version: 9.0.0+ vitest:+ specifier: 'catalog:'+ version: 4.1.6(@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/dev:dependencies: