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.

feat(events): push-based event queue wake (replace cron poll) (#1193)

Sidcaea84c95d2d
diff --git a/.ai/lessons.md b/.ai/lessons.md
index a931de0e93..d85ecb385f 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -467,3 +467,23 @@ Format: `Context → Problem → Rule → Applies to`
**Rule:** When two `ValidatedForm`s occupy the same conditional slot (`cond ? <VF/> : <VF/>`), give each a distinct, stable `key` (`key="new-part"` / `key="existing-item"`) so switching forces a fresh mount + fresh store that hydrates with the correct branch's `defaultValues`. Consequence: the fresh mount also needs any Select value the branch relies on seeded in its own `defaultValues` (e.g. `changeType: "New Part"`, added to `changeOrderNewPartValidator`) — a value the shared store previously carried over from the user's click is gone after remount. Symptom to watch for: a controlled Select rendering blank / submitting `""` right after a branch switch.
**Applies to:** `apps/erp/app/modules/items/ui/ChangeOrder/AffectedItemForm.tsx`; any conditional twin-`ValidatedForm` pattern; `@carbon/form` controlled fields (`Select`/`Combobox`/anything on `useControlField`) that rely on `defaultValues` seeding.
+
+## A public SECURITY DEFINER function that calls net.http_post is a remote-DoS surface — put it in an internal schema
+
+**Context:** The push-based event-queue wake (`20260721184852_event-queue-wake.sql`) originally defined `wake_event_queue()` / `sweep_event_queue()` in the `public` schema. Both are SECURITY DEFINER and call `net.http_post` (pg_net) to POST to the `event-wake` edge function. The trigger (`dispatch_event_batch`) and pg_cron call them as the owner (superuser).
+
+**Problem:** Every `public` function is auto-exposed as a PostgREST RPC (`/rest/v1/rpc/<name>`), reachable by `anon`. Worse than mere exposure: referencing such a function as a **non-superuser** role segfaults the backend (pg_net 0.20 / PG15) — reproducible via `SET ROLE authenticated; EXPLAIN SELECT public.wake_event_queue();`, which crashed even though `EXPLAIN` never runs the body and the role lacked EXECUTE. The crash happens at plan/permission-resolution time, **before** the ACL check — so `REVOKE ALL … FROM PUBLIC, anon, authenticated` does NOT protect: an unauthenticated `POST /rpc/wake_event_queue` crash-loops the whole DB (postmaster reinitializes all backends → "database system is in recovery mode" for every client). Same-body call as superuser was fine, which is why the trigger/cron paths worked and masked it in end-to-end testing.
+
+**Rule:** Never define an internal SECURITY DEFINER helper (especially one calling `net.http_post` / pg_net) in `public`. Put it in the internal `util` schema (the existing Carbon/Supabase convention — cf. `util.process_embeddings`), where `anon`/`authenticated` have no `USAGE`, so the API can't reference it at all and a hostile call fails cleanly with `permission denied for schema util` before any crash-prone planning. Callers that are triggers/pg_cron run as owner and reach `util` fine; update their bodies to `util.<fn>()`. Keep `REVOKE ALL … FROM PUBLIC` on the util function as defense-in-depth, but the schema-USAGE gate is the real fix. Verify with `SET ROLE authenticated; SELECT util.<fn>();` → must be a clean `permission denied`, not a dropped connection. Note PostgREST-exposed schemas exclude `util`/`pgmq` but include `public`/`net` (`has_schema_privilege('anon', <schema>, 'USAGE')`).
+
+**Applies to:** any new SECURITY DEFINER function that calls pg_net/`net.http_post` or is meant to be trigger/cron-only (`packages/database/supabase/migrations/`). Trigger functions returning `trigger` are not RPC-exposed (safe in public), but VOID/scalar helpers are.
+
+## The local Inngest dev server (v1.19.4) can't handle `debounce` — it errors on every debounce item
+
+**Context:** The push-based event-queue drainer (`packages/jobs/src/inngest/functions/events/queue.ts`) was configured with `debounce: { period: "2s", timeout: "10s" }` to coalesce bursts of `carbon/event-queue.process` wake events into one run.
+
+**Problem:** The Dockerized dev server (`inngest/inngest:v1.19.4`, run by `crbn up`) logs `error unmarshalling debounce item: json: cannot unmarshal array into Go struct field DebounceItem.e.data of type map[string]interface {}` on every debounced event, fails to coalesce (a 20-write burst produced 21 runs, not ~1), and spams the error each time the function is triggered (including every pg_cron sweeper tick). Fails open — events still process, queue still drains, nothing is lost — but the optimization is absent in dev and the logs are noisy. Inngest Cloud honors debounce; the dev server does not.
+
+**Rule:** Don't rely on `debounce` for Carbon Inngest functions validated against the local dev server — it's broken there. For the event queue the coalescing was moved upstream: `dispatch_event_batch()` wakes at most once per transaction (txn-local GUC `carbon.event_wake_sent`), so the important bulk case (a CSV import = one transaction) is already one wake; `concurrency: 1` + loop-until-empty drain absorbs the rest (extra runs from many separate transactions are cheap no-ops that read an empty queue). If you must coalesce many *separate* transactions in a burst, do it at the DB/application layer, not with `debounce`. Verify any flow-control choice by watching `docker logs <inngest container>` for `error handling queue item` during a burst, not just by trusting the config.
+
+**Applies to:** `packages/jobs/src/inngest/functions/events/queue.ts`; any new Inngest function reaching for `debounce`/flow-control that will be exercised in local dev.
diff --git a/.claude/rules/event-system.md b/.claude/rules/event-system.md
index f3996f4115..27e0b450f9 100644
--- a/.claude/rules/event-system.md
+++ b/.claude/rules/event-system.md
@@ -7,20 +7,34 @@ paths:
# Event System
-Carbon's async event-processing infra: Postgres triggers + PGMQ + **Inngest** (not Trigger.dev — that was the old design). DB writes enqueue events; an Inngest cron drains the queue and fans out to handlers.
+Carbon's async event-processing infra: Postgres triggers + PGMQ + **Inngest** (not Trigger.dev — that was the old design). DB writes enqueue events; the database **pushes** a wake to Inngest and the `event-queue` function drains the queue (no polling cron since `20260721184852_event-queue-wake.sql`).
## Flow
-```
+```text
DB write → AFTER STATEMENT trigger → dispatch_event_batch() → pgmq.send_batch('event_system')
- ↓
- event-queue (Inngest cron, * * * * *) reads pgmq.read('event_system', 30, 100)
- ↓
+ → util.wake_event_queue() [pg_net POST, once per txn]
+ ↓
+ edge fn event-wake → Inngest event "carbon/event-queue.process"
+ ↓
+ event-queue (Inngest, event-triggered, concurrency 1)
+ loops pgmq.read('event_system', 30, 100) until empty (max 10 passes, re-wakes if more)
+ ↓
groups by handlerType → step.sendEvent("carbon/event-<handler>") → handler fn
- ↓
+ ↓
pgmq.delete() the processed msg_ids
+
+pg_cron 'event-queue-sweeper' (* * * * *, in-DB): if visible messages exist → util.wake_event_queue()
+ (safety net for lost pushes; no queue → no HTTP → no Inngest run)
```
+The wake path (`20260721184852_event-queue-wake.sql`) — both helpers live in the internal `util` schema (like `util.process_embeddings`), NOT `public`:
+- `util.wake_event_queue()` — SECURITY DEFINER; reads `apiUrl`/`anonKey` from the singleton `config` table (same as the webhook triggers) and `net.http_post`s to `/functions/v1/event-wake`. Error-swallowed and no-ops when `config` is unseeded — OLTP writes never fail on push failure. pg_net queues the request transactionally, so the wake fires only after commit.
+- `dispatch_event_batch()` calls it at most **once per transaction** via the txn-local GUC `carbon.event_wake_sent` (`set_config(..., true)`).
+- `util.sweep_event_queue()` — pg_cron job `event-queue-sweeper` re-wakes every minute while *visible* messages (`vt <= clock_timestamp()`) sit in `pgmq.q_event_system`.
+- **Why `util`, not `public`:** a public function is auto-exposed as a PostgREST RPC, and a non-superuser reference to a function that transitively calls `net.http_post` segfaults the backend (pg_net 0.20 / PG15) — a remote-DoS surface a `REVOKE` can't close because the crash precedes the privilege check. anon/authenticated have no `USAGE` on `util`, so the API can't reach it. The trigger and pg_cron call it as the owner (superuser), where the pg_net path is safe.
+- Edge fn `packages/database/supabase/functions/event-wake/index.ts` forwards the doorbell via `sendInngestEvent("carbon/event-queue.process", {})` (`functions/lib/inngest.ts`).
+
## Database (migrations)
`eventSystemSubscription` rows decide which table/operation routes to which handler. Final columns (after all migrations): `id`, `name`, `companyId`, `table`, `operations TEXT[]` (subset of `INSERT,UPDATE,DELETE,TRUNCATE`), `filter JSONB`, `handlerType`, `config JSONB`, `active`, `createdAt`. Unique on `(companyId, name, table)`. `batchSize` was removed (`20260204070000`).
@@ -48,7 +62,7 @@ Zod schemas + helpers. `QueueMessage` = `{ subscriptionId, triggerType: ROW|STAT
## Handlers — `packages/jobs/src/inngest/functions/events/`
-`queue.ts` is the cron dispatcher (id `event-queue`); it groups the batch and sends one Inngest event per handler type. Each handler is an Inngest function listening on `carbon/event-<name>`:
+`queue.ts` is the drainer (id `event-queue`), triggered by `carbon/event-queue.process` with `concurrency: 1`; it loops read → dispatch → delete until the queue is empty (max 10 passes of 100, then re-wakes itself). Burst coalescing is handled upstream — the trigger wakes at most once per transaction — not by `debounce` (the local Inngest dev server, v1.19.4, fails to unmarshal debounce items). Each handler is an Inngest function listening on `carbon/event-<name>`:
| handlerType | event name | file | purpose |
|---|---|---|---|
@@ -62,6 +76,7 @@ Zod schemas + helpers. `QueueMessage` = `{ subscriptionId, triggerType: ROW|STAT
All handlers (incl. `eventQueueFunction`) are exported from `events/index.ts` and registered in `packages/jobs/src/inngest/functions/index.ts`. Inngest client comes from `@carbon/lib/inngest`.
## Notes
-- Latency: up to ~1 min (cron cadence). Use sync interceptors, not subscriptions, for data-integrity / real-time needs.
+- Latency: typically ~3–5s (sub-second wake + the multi-step drain run). Worst case ~1 min if a push is lost (dead pg_net worker, edge fn down) — the pg_cron sweeper re-wakes while messages are pending. Still async: use sync interceptors, not subscriptions, for data-integrity / real-time needs.
+- The wake path depends on a seeded `config` row (`apiUrl`, `anonKey`). Dev seeds it automatically (`ensureConfigRow` in `packages/dev/src/services/migrations.ts`, apiUrl `http://kong:8000`). **Unseeded config (e.g. self-hosted) = events never process** — both the push and the sweeper wake no-op.
- Webhook/workflow handlers use `idempotency: event.data.msgId` and per-record concurrency keys.
- Don't hand-edit generated DB types; read the newest migration for schema truth.
diff --git a/.claude/rules/workflow-event-system.md b/.claude/rules/workflow-event-system.md
index e2af798cc5..bd8aa8fcbf 100644
--- a/.claude/rules/workflow-event-system.md
+++ b/.claude/rules/workflow-event-system.md
@@ -20,7 +20,8 @@ the procedure, not a re-description — it does not repeat that detail.
| --- | --- |
| Handler functions (one per type) | `packages/jobs/src/inngest/functions/events/<type>.ts` |
| Handler barrel | `packages/jobs/src/inngest/functions/events/index.ts` |
-| Cron dispatcher (drains pgmq, fans out) | `packages/jobs/src/inngest/functions/events/queue.ts` |
+| Drainer (event-triggered, drains pgmq, fans out) | `packages/jobs/src/inngest/functions/events/queue.ts` |
+| Wake edge fn (DB → Inngest doorbell) | `packages/database/supabase/functions/event-wake/index.ts` |
| Served `functions` array | `packages/jobs/src/inngest/index.ts` |
| Event-name type registry (`Events`) | `packages/lib/src/events.ts` (re-exported, NOT defined, by `packages/jobs/src/events.ts`) |
| Zod schemas + subscription helpers | `packages/database/src/event.ts` |
@@ -189,7 +190,7 @@ export const yourHandlerFunction = inngest.createFunction(
);
```
-### 5. Add a dispatch branch in the queue cron
+### 5. Add a dispatch branch in the queue drainer
In `packages/jobs/src/inngest/functions/events/queue.ts`:
@@ -200,8 +201,10 @@ In `packages/jobs/src/inngest/functions/events/queue.ts`:
YOUR_NEW_TYPE: [],
};
```
-2. Add a dispatch block. Use `chunk(..., CHUNK_SIZE)` to stay under Inngest's 256KB
- event limit. **Batched** (like SEARCH — one event per chunk, `data.records` is an array):
+2. Add a dispatch block **inside the drain loop** (the body runs once per `pass`;
+ step ids must include the pass suffix or replays break). Use
+ `chunk(..., CHUNK_SIZE)` to stay under Inngest's 256KB event limit.
+ **Batched** (like SEARCH — one event per chunk, `data.records` is an array):
```typescript
if (grouped.YOUR_NEW_TYPE.length > 0) {
const records = grouped.YOUR_NEW_TYPE.map((job) => ({
@@ -210,7 +213,7 @@ In `packages/jobs/src/inngest/functions/events/queue.ts`:
}));
const chunks = chunk(records, CHUNK_SIZE);
for (let i = 0; i < chunks.length; i++) {
- await step.sendEvent(`dispatch-your-new-type-${i}`, {
+ await step.sendEvent(`dispatch-your-new-type-${pass}-${i}`, {
name: "carbon/event-your-new-type" as const,
data: { records: chunks[i] },
});
@@ -248,17 +251,25 @@ that path; it does not exist.
SELECT * FROM "eventSystemSubscription" WHERE "companyId" = '…' AND "active";
SELECT * FROM "eventSystemTrigger" WHERE "table" = 'yourTable'; -- view over pg_trigger
```
-- **Inngest:** in the dashboard (or local Dev Server), confirm `event-queue` (cron,
- `* * * * *`) is draining, then check the downstream `event-handler-<type>` runs. Local:
+- **Wake path (push):** the DB posts to the `event-wake` edge fn via pg_net; check
+ ```sql
+ SELECT * FROM net._http_response ORDER BY created DESC LIMIT 5; -- 200 = wake delivered
+ SELECT * FROM cron.job_run_details WHERE jobid = (SELECT jobid FROM cron.job WHERE jobname = 'event-queue-sweeper') ORDER BY start_time DESC LIMIT 5;
+ SELECT * FROM "config"; -- must be seeded (apiUrl/anonKey) or wakes silently no-op
+ ```
+- **Inngest:** in the dashboard (or local Dev Server), confirm the
+ `carbon/event-queue.process` event arrives and `event-queue` (event-triggered,
+ `concurrency: 1`) drains, then check the downstream `event-handler-<type>` runs. Local:
```bash
npx inngest-cli@latest dev -u http://localhost:3000/api/inngest # UI at :8288
```
## Pitfalls
-1. **Latency** — handlers fire on the 1-minute cron cadence, not instantly. For
+1. **Latency** — handlers fire ~3–5s after the write (sub-second wake + the drain run), worst
+ case ~1 min via the pg_cron sweeper if a push is lost. Still async, not inline: for
data-integrity / real-time needs use sync interceptors (`attach_event_trigger`'s 2nd/3rd
- arg), not subscriptions.
+ arg), not subscriptions. A missing `config` row means events never process at all.
2. **Missing `companyId`** — events without a `companyId` are skipped; subscriptions are
company-scoped.
3. **Operation casing** — `["INSERT"]`, not `["insert"]`.
diff --git a/.claude/skills/inngest/SKILL.md b/.claude/skills/inngest/SKILL.md
index 9cd36b9cbb..636f30efa5 100644
--- a/.claude/skills/inngest/SKILL.md
+++ b/.claude/skills/inngest/SKILL.md
@@ -24,7 +24,7 @@ a step. Code outside steps executes again on every invocation.
| Concept | v3 (Carbon — USE THIS) | v4 (do NOT copy) |
|---|---|---|
| Function shape | `createFunction({ id, ... }, { event: "x" }, handler)` — trigger is the 2nd positional arg | `triggers: [...]` inside the first arg |
-| Multiple triggers | not supported | `triggers: [{event}, {cron}]` |
+| Multiple triggers | supported — pass an array as the 2nd positional arg: `createFunction(opts, [{event: "x"}, {cron: "..."}], handler)` (verified in [email protected] types: `SingleOrArray<InngestFunction.Trigger>`) | `triggers: [{event}, {cron}]` inside the first arg |
| Event typing | `EventSchemas` + the `Events` type in `packages/lib/src/events.ts` | `eventType()` / `staticSchema<T>()` |
| Testing | no `@inngest/test` (needs v4) — test handlers as plain functions with mocked services | `InngestTestEngine` |
| Local dev mode | v3 defaults to dev mode locally | v4 defaults to Cloud; needs `INNGEST_DEV=1` |
diff --git a/apps/erp/app/routes/api+/model.artifacts.$modelUploadId.ts b/apps/erp/app/routes/api+/model.artifacts.$modelUploadId.ts
index 3232466eb8..7454365c50 100644
--- a/apps/erp/app/routes/api+/model.artifacts.$modelUploadId.ts
+++ b/apps/erp/app/routes/api+/model.artifacts.$modelUploadId.ts
@@ -24,6 +24,16 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
.eq("companyId", companyId)
.maybeSingle();
+ // A real query failure is a 5xx, not a 404 — don't mask a backend error as
+ // "no such model".
+ if (model.error) throw new Response("Internal error", { status: 500 });
+ // No such model for this tenant → 404, don't fabricate an all-nulls body. An
+ // all-nulls 200 is indistinguishable from "exists but not optimised", so the
+ // viewer's reuse guard can't tell the two apart and would auto-fire an
+ // optimise against an id that doesn't exist (→ a reoptimise 404 loop). The
+ // client query treats this 404 as "no artifacts", and never auto-fires.
+ if (!model.data) throw new Response("Not found", { status: 404 });
+
// Raw-source pointer for the viewer's WASM fallback tier (renders the original
// upload when no artifact exists). `.zst`-compacted raws are skipped — they
// only exist after a successful optimise, which means an artifact exists too.
diff --git a/apps/mes/app/routes/api+/model.artifacts.$modelUploadId.ts b/apps/mes/app/routes/api+/model.artifacts.$modelUploadId.ts
index 29ae032c42..ede5cbb3f6 100644
--- a/apps/mes/app/routes/api+/model.artifacts.$modelUploadId.ts
+++ b/apps/mes/app/routes/api+/model.artifacts.$modelUploadId.ts
@@ -23,6 +23,16 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
.eq("companyId", companyId)
.maybeSingle();
+ // A real query failure is a 5xx, not a 404 — don't mask a backend error as
+ // "no such model".
+ if (model.error) throw new Response("Internal error", { status: 500 });
+ // No such model for this tenant → 404, don't fabricate an all-nulls body. An
+ // all-nulls 200 is indistinguishable from "exists but not optimised", so the
+ // viewer's reuse guard can't tell the two apart and would auto-fire an
+ // optimise against an id that doesn't exist (→ a reoptimise 404 loop). The
+ // client query treats this 404 as "no artifacts", and never auto-fires.
+ if (!model.data) throw new Response("Not found", { status: 404 });
+
// Raw-source pointer for the viewer's WASM fallback tier (renders the original
// upload when no artifact exists). `.zst`-compacted raws are skipped — they
// only exist after a successful optimise, which means an artifact exists too.
diff --git a/packages/database/supabase/config.toml b/packages/database/supabase/config.toml
index ac420efc7a..7369856755 100644
--- a/packages/database/supabase/config.toml
+++ b/packages/database/supabase/config.toml
@@ -212,6 +212,11 @@ entrypoint = "./functions/transcription/index.ts"
# For example, if you want to serve static HTML pages in your function:
# static_files = [ "./functions/transcription/*.html" ]
+[functions.event-wake]
+enabled = true
+verify_jwt = true
+entrypoint = "./functions/event-wake/index.ts"
+
[functions.embedding]
enabled = true
verify_jwt = true
diff --git a/packages/database/supabase/functions/event-wake/index.ts b/packages/database/supabase/functions/event-wake/index.ts
new file mode 100644
index 0000000000..9a04625e16
--- /dev/null
+++ b/packages/database/supabase/functions/event-wake/index.ts
@@ -0,0 +1,36 @@
+import { serve } from "https://deno.land/[email protected]/http/server.ts";
+
+import { corsHeaders } from "../lib/headers.ts";
+import { sendInngestEvent } from "../lib/inngest.ts";
+import { getFunctionLogger } from "../lib/logging.ts";
+
+const logger = getFunctionLogger("event-wake");
+
+/**
+ * Wake the Inngest event-queue drainer. Machine-called from Postgres via
+ * pg_net (dispatch_event_batch + the pg_cron sweeper) whenever messages are
+ * pending in the `event_system` PGMQ queue. The payload carries no data —
+ * the queue itself is the source of truth; this is only a doorbell.
+ */
+serve(async (req: Request) => {
+ if (req.method === "OPTIONS") {
+ return new Response("ok", { headers: corsHeaders });
+ }
+
+ try {
+ await sendInngestEvent("carbon/event-queue.process", {});
+
+ return new Response(JSON.stringify({ success: true }), {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ status: 200,
+ });
+ } catch (err) {
+ // A failed wake is harmless: the pg_cron sweeper re-fires while the
+ // queue is non-empty.
+ logger.error("Error in event-wake", { error: (err as Error).message });
+ return new Response(JSON.stringify({ error: (err as Error).message }), {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ status: 500,
+ });
+ }
+});
diff --git a/packages/database/supabase/migrations/20260721184852_event-queue-wake.sql b/packages/database/supabase/migrations/20260721184852_event-queue-wake.sql
new file mode 100644
index 0000000000..8ab60783de
--- /dev/null
+++ b/packages/database/supabase/migrations/20260721184852_event-queue-wake.sql
@@ -0,0 +1,280 @@
+-- =============================================================================
+-- Push-based wake for the event queue
+--
+-- The event-queue Inngest function used to poll PGMQ on a 1-minute cron.
+-- This migration makes the database push instead:
+--
+-- 1. util.wake_event_queue() POSTs (via pg_net, fire-and-forget) to the
+-- `event-wake` edge function, which forwards a
+-- `carbon/event-queue.process` event to Inngest. Reads apiUrl/anonKey
+-- from the singleton "config" table (same pattern as the webhook
+-- triggers); silently no-ops when config is missing and never raises,
+-- so OLTP writes can't fail on a push failure. pg_net queues the HTTP
+-- request transactionally, so the wake only fires after commit — it can
+-- never outrun the pgmq messages it announces.
+--
+-- 2. dispatch_event_batch() calls it after enqueueing, at most once per
+-- transaction (txn-local GUC carbon.event_wake_sent), so bulk writes
+-- produce one wake, not thousands.
+--
+-- 3. A pg_cron sweeper (every minute, in-DB) re-fires the wake only while
+-- visible messages are sitting in the queue — the safety net for lost
+-- pushes (dead pg_net worker, edge fn down, Inngest ingest failure).
+-- No queue → no HTTP → no Inngest run.
+--
+-- Both helpers live in the internal `util` schema (like util.process_embeddings),
+-- NOT public: public functions are auto-exposed as PostgREST RPCs, and a
+-- non-superuser reference to a function that transitively calls net.http_post
+-- segfaults the backend under pg_net 0.20 / PG15 — so exposing them in public
+-- is a remote-DoS surface that a REVOKE does not close (the crash precedes the
+-- privilege check). anon/authenticated have no USAGE on `util`, so the function
+-- is unreachable from the API before any of that can happen. The trigger and
+-- pg_cron call it as the owner (superuser), where the pg_net path is safe.
+-- =============================================================================
+
+-- Internal schema for trigger/cron-only helpers (created in 20250317_embeddings;
+-- guarded here so this migration is self-contained). anon/authenticated get no
+-- USAGE, which is what keeps these functions off the PostgREST RPC surface.
+CREATE SCHEMA IF NOT EXISTS util;
+
+-- ----------------------------------------------------------------------------
+-- 1. util.wake_event_queue(): fire-and-forget doorbell to the event-wake edge fn
+-- ----------------------------------------------------------------------------
+CREATE OR REPLACE FUNCTION util.wake_event_queue()
+RETURNS VOID
+LANGUAGE plpgsql
+SECURITY DEFINER
+SET search_path = public, extensions
+AS $$
+DECLARE
+ api_url TEXT;
+ anon_key TEXT;
+BEGIN
+ SELECT "apiUrl", "anonKey" INTO api_url, anon_key FROM "config" LIMIT 1;
+
+ IF api_url IS NULL THEN
+ RETURN;
+ END IF;
+
+ PERFORM net.http_post(
+ api_url || '/functions/v1/event-wake',
+ '{}'::jsonb,
+ '{}'::jsonb,
+ jsonb_build_object(
+ 'Content-Type', 'application/json',
+ 'Authorization', 'Bearer ' || anon_key
+ )
+ );
+EXCEPTION WHEN OTHERS THEN
+ RAISE LOG 'wake_event_queue failed: % %', SQLERRM, SQLSTATE;
+END;
+$$;
+
+COMMENT ON FUNCTION util.wake_event_queue() IS 'Fire-and-forget POST (pg_net) to the event-wake edge function, which sends carbon/event-queue.process to Inngest. Never raises; no-ops when the config row is missing. Internal (util schema): unreachable from the API.';
+
+REVOKE ALL ON FUNCTION util.wake_event_queue() FROM PUBLIC;
+
+-- ----------------------------------------------------------------------------
+-- 2. dispatch_event_batch(): wake the drainer after enqueueing
+-- (body copied forward from 20260427120000_audit-event-timestamp.sql;
+-- additions are did_enqueue + the wake block before RETURN NULL)
+-- ----------------------------------------------------------------------------
+CREATE OR REPLACE FUNCTION public.dispatch_event_batch()
+RETURNS TRIGGER
+LANGUAGE plpgsql
+SECURITY DEFINER
+SET search_path = public, pgmq, extensions
+AS $$
+DECLARE
+ sub RECORD;
+ msg_batch JSONB[];
+ rec_company_id TEXT;
+ has_subs BOOLEAN;
+ current_actor_id TEXT;
+ pk_column TEXT;
+ query_text TEXT;
+ did_enqueue BOOLEAN := FALSE;
+BEGIN
+ IF current_setting('app.sync_in_progress', true) = 'true' THEN
+ RETURN NULL;
+ END IF;
+
+ current_actor_id := auth.uid()::TEXT;
+ pk_column := public.get_primary_key_column(TG_TABLE_NAME);
+
+ IF TG_OP = 'DELETE' THEN
+ SELECT t."companyId" INTO rec_company_id FROM batched_old t LIMIT 1;
+ ELSIF TG_OP = 'INSERT' THEN
+ SELECT t."companyId" INTO rec_company_id FROM batched_new t LIMIT 1;
+ ELSE
+ SELECT t."companyId" INTO rec_company_id FROM batched_new t LIMIT 1;
+ END IF;
+
+ IF rec_company_id IS NULL THEN RETURN NULL; END IF;
+
+ SELECT EXISTS (
+ SELECT 1 FROM "eventSystemSubscription"
+ WHERE "table" = TG_TABLE_NAME
+ AND "companyId" = rec_company_id
+ AND "active" = TRUE
+ AND TG_OP = ANY("operations")
+ ) INTO has_subs;
+
+ IF NOT has_subs THEN RETURN NULL; END IF;
+
+ FOR sub IN
+ SELECT * FROM "eventSystemSubscription"
+ WHERE "table" = TG_TABLE_NAME
+ AND "companyId" = rec_company_id
+ AND "active" = TRUE
+ AND TG_OP = ANY("operations")
+ LOOP
+
+ IF TG_OP = 'INSERT' THEN
+ query_text := format('
+ SELECT array_agg(
+ jsonb_build_object(
+ ''subscriptionId'', $1,
+ ''triggerType'', $2,
+ ''handlerType'', $3,
+ ''handlerConfig'', $4,
+ ''companyId'', $5,
+ ''actorId'', $6,
+ ''event'', jsonb_build_object(
+ ''table'', $7,
+ ''operation'', $8,
+ ''recordId'', t.%I::TEXT,
+ ''new'', row_to_json(t)::jsonb,
+ ''old'', null,
+ ''timestamp'', clock_timestamp()
+ )
+ )
+ )
+ FROM batched_new t
+ WHERE t."companyId" = $5
+ AND ($9 = ''{}''::jsonb OR row_to_json(t)::jsonb @> $9)
+ ', pk_column);
+
+ EXECUTE query_text INTO msg_batch
+ USING sub.id, TG_LEVEL, sub."handlerType", sub."config", rec_company_id,
+ current_actor_id, TG_TABLE_NAME, TG_OP, sub.filter;
+
+ ELSIF TG_OP = 'DELETE' THEN
+ query_text := format('
+ SELECT array_agg(
+ jsonb_build_object(
+ ''subscriptionId'', $1,
+ ''triggerType'', $2,
+ ''handlerType'', $3,
+ ''handlerConfig'', $4,
+ ''companyId'', $5,
+ ''actorId'', $6,
+ ''event'', jsonb_build_object(
+ ''table'', $7,
+ ''operation'', $8,
+ ''recordId'', t.%I::TEXT,
+ ''new'', null,
+ ''old'', row_to_json(t)::jsonb,
+ ''timestamp'', clock_timestamp()
+ )
+ )
+ )
+ FROM batched_old t
+ WHERE t."companyId" = $5
+ AND ($9 = ''{}''::jsonb OR row_to_json(t)::jsonb @> $9)
+ ', pk_column);
+
+ EXECUTE query_text INTO msg_batch
+ USING sub.id, TG_LEVEL, sub."handlerType", sub."config", rec_company_id,
+ current_actor_id, TG_TABLE_NAME, TG_OP, sub.filter;
+
+ ELSIF TG_OP = 'UPDATE' THEN
+ query_text := format('
+ SELECT array_agg(
+ jsonb_build_object(
+ ''subscriptionId'', $1,
+ ''triggerType'', $2,
+ ''handlerType'', $3,
+ ''handlerConfig'', $4,
+ ''companyId'', $5,
+ ''actorId'', $6,
+ ''event'', jsonb_build_object(
+ ''table'', $7,
+ ''operation'', $8,
+ ''recordId'', n.%I::TEXT,
+ ''new'', row_to_json(n)::jsonb,
+ ''old'', row_to_json(o)::jsonb,
+ ''timestamp'', clock_timestamp()
+ )
+ )
+ )
+ FROM batched_new n
+ JOIN batched_old o ON n.%I = o.%I
+ WHERE n."companyId" = $5
+ AND ($9 = ''{}''::jsonb OR row_to_json(n)::jsonb @> $9)
+ ', pk_column, pk_column, pk_column);
+
+ EXECUTE query_text INTO msg_batch
+ USING sub.id, TG_LEVEL, sub."handlerType", sub."config", rec_company_id,
+ current_actor_id, TG_TABLE_NAME, TG_OP, sub.filter;
+ END IF;
+
+ IF msg_batch IS NOT NULL AND array_length(msg_batch, 1) > 0 THEN
+ PERFORM pgmq.send_batch('event_system', msg_batch);
+ did_enqueue := TRUE;
+ END IF;
+
+ END LOOP;
+
+ -- Wake the Inngest drainer, at most once per transaction. The GUC is
+ -- txn-local (set_config(..., true)), so multi-statement transactions and
+ -- bulk imports post a single doorbell instead of one per statement.
+ IF did_enqueue
+ AND current_setting('carbon.event_wake_sent', true) IS DISTINCT FROM 'true' THEN
+ PERFORM util.wake_event_queue();
+ PERFORM set_config('carbon.event_wake_sent', 'true', true);
+ END IF;
+
+ RETURN NULL;
+END;
+$$;
+
+COMMENT ON FUNCTION public.dispatch_event_batch() IS 'Dispatches database events to PGMQ and wakes the Inngest drainer via wake_event_queue() (once per transaction). Uses clock_timestamp() so each event has a unique microsecond timestamp even when batched.';
+
+-- ----------------------------------------------------------------------------
+-- 3. Sweeper: re-wake while visible messages are pending (safety net)
+-- ----------------------------------------------------------------------------
+CREATE OR REPLACE FUNCTION util.sweep_event_queue()
+RETURNS VOID
+LANGUAGE plpgsql
+SECURITY DEFINER
+SET search_path = public, pgmq, extensions
+AS $$
+BEGIN
+ -- Only visible messages count: rows hidden by a read's visibility timeout
+ -- are already being drained and must not trigger a spurious wake.
+ IF EXISTS (
+ SELECT 1 FROM pgmq.q_event_system WHERE vt <= clock_timestamp()
+ ) THEN
+ PERFORM util.wake_event_queue();
+ END IF;
+END;
+$$;
+
+COMMENT ON FUNCTION util.sweep_event_queue() IS 'pg_cron safety net: wakes the Inngest event-queue drainer if visible messages are sitting in the event_system PGMQ queue (i.e. a push wake was lost). Internal (util schema): unreachable from the API.';
+
+REVOKE ALL ON FUNCTION util.sweep_event_queue() FROM PUBLIC;
+
+DO $$
+BEGIN
+ IF EXISTS (SELECT 1 FROM cron.job WHERE jobname = 'event-queue-sweeper') THEN
+ PERFORM cron.unschedule('event-queue-sweeper');
+ END IF;
+
+ PERFORM cron.schedule(
+ 'event-queue-sweeper',
+ '* * * * *',
+ $job$ SELECT util.sweep_event_queue(); $job$
+ );
+END;
+$$;
diff --git a/packages/dev/src/commands/migrate.ts b/packages/dev/src/commands/migrate.ts
index 55246cfd9b..9816e0b46b 100644
--- a/packages/dev/src/commands/migrate.ts
+++ b/packages/dev/src/commands/migrate.ts
@@ -11,7 +11,11 @@ import {
ensureDockerRunning,
stopStack
} from "../services/compose.js";
-import { applyMigrations, waitForPostgres } from "../services/migrations.js";
+import {
+ applyMigrations,
+ ensureConfigRow,
+ waitForPostgres
+} from "../services/migrations.js";
import { branchToPrefix } from "../services/portless.js";
import {
ensureSlugAvailable,
@@ -73,6 +77,15 @@ async function migrateAgainstRunningDb(
return r.applied ? "migrations applied" : "schema already up to date";
}
},
+ {
+ title: "Seed pg_net config row",
+ task: async () => {
+ const anonKey = process.env.SUPABASE_ANON_KEY;
+ if (!anonKey) return "skipped (SUPABASE_ANON_KEY not set)";
+ await ensureConfigRow(portDb, anonKey);
+ return "config row upserted";
+ }
+ },
...(shouldRegen
? [
{
@@ -154,6 +167,15 @@ async function migrateStandalone(
return r.applied ? "migrations applied" : "schema already up to date";
}
},
+ {
+ title: "Seed pg_net config row",
+ task: async () => {
+ const anonKey = process.env.SUPABASE_ANON_KEY;
+ if (!anonKey) return "skipped (SUPABASE_ANON_KEY not set)";
+ await ensureConfigRow(portDb, anonKey);
+ return "config row upserted";
+ }
+ },
...(shouldRegen
? [
{
diff --git a/packages/dev/src/commands/up.ts b/packages/dev/src/commands/up.ts
index c69886c7a0..04426f95c9 100644
--- a/packages/dev/src/commands/up.ts
+++ b/packages/dev/src/commands/up.ts
@@ -33,6 +33,7 @@ import {
import {
applyBootstrapSql,
applyMigrations,
+ ensureConfigRow,
ensureSmokeTestUser,
waitForPostgres,
waitForStorageReady,
@@ -525,6 +526,19 @@ async function runDatabaseMigrations(
title: "Skip database migrations (--no-migrate)",
task: async () => "skipped"
},
+ // Gated on shouldMigrate: with --no-migrate on a fresh volume the
+ // "config" table doesn't exist yet and the upsert would abort the boot.
+ ...(cfg.shouldMigrate
+ ? [
+ {
+ title: "Seed pg_net config row",
+ task: async () => {
+ await ensureConfigRow(ctx.ports.PORT_DB, ctx.jwt.anonKey);
+ return "config row upserted";
+ }
+ }
+ ]
+ : []),
...(cfg.shouldRegen
? [
{
diff --git a/packages/dev/src/services/migrations.ts b/packages/dev/src/services/migrations.ts
index d7b814b8c0..29e34b4f11 100644
--- a/packages/dev/src/services/migrations.ts
+++ b/packages/dev/src/services/migrations.ts
@@ -232,6 +232,31 @@ async function repairStaleMigrations(
return stale.length;
}
+// ---------------------------------------------------------------------------
+// Config row (pg_net push targets)
+// ---------------------------------------------------------------------------
+
+// The singleton "config" row is what SECURITY DEFINER functions
+// (wake_event_queue, webhook_insert/update/delete) read to POST to edge
+// functions via pg_net. Without it those pushes silently no-op, so the
+// event-queue wake and local webhooks never fire in dev. `apiUrl` must be the
+// in-network Kong URL — pg_net runs inside the postgres container, which
+// can't reach host ports.
+export async function ensureConfigRow(
+ dbPort: number,
+ anonKey: string
+): Promise<void> {
+ await withClient(dbPort, (c) =>
+ c.query(
+ `INSERT INTO "config" ("id", "apiUrl", "anonKey")
+ VALUES (TRUE, 'http://kong:8000', $1)
+ ON CONFLICT ("id") DO UPDATE
+ SET "apiUrl" = EXCLUDED."apiUrl", "anonKey" = EXCLUDED."anonKey"`,
+ [anonKey]
+ )
+ );
+}
+
// ---------------------------------------------------------------------------
// Smoke-test user
// ---------------------------------------------------------------------------
diff --git a/packages/jobs/AGENTS.md b/packages/jobs/AGENTS.md
index c942172f25..2f9f8311c4 100644
--- a/packages/jobs/AGENTS.md
+++ b/packages/jobs/AGENTS.md
@@ -12,13 +12,13 @@ Background job system built on Inngest. Handles event system processing (webhook
## Ask First
- Adding new handler types to the event system — requires DB migration to widen the `handlerType` CHECK constraint.
-- Changing the event queue cron cadence (currently `* * * * *` / 1 min) — affects latency for all async event processing.
+- Changing the event queue's flow control (`concurrency: 1`) or the pg_cron sweeper cadence — affects latency and coalescing for all async event processing. The drainer is push-woken by `carbon/event-queue.process` (see `.claude/rules/event-system.md`), not cron-polled. Note: `debounce` is intentionally NOT used — the local Inngest dev server can't unmarshal debounce items; bursts are coalesced by the per-transaction wake instead.
- Adding new Inngest function registrations — they must be exported and registered in the functions index.
## Never
- Import Inngest internals or server-only job code in app bundles — use only the public exports from `@carbon/jobs` (`.` subpath: `trigger`, `batchTrigger`, schemas).
-- Use the event system for real-time / data-integrity needs — latency is up to ~1 min. Use sync interceptors instead.
+- Use the event system for real-time / data-integrity needs — it is async (typically ~3–5s, up to ~1 min if a push wake is lost). Use sync interceptors instead.
- Bypass the PGMQ queue by writing directly to handler tables — always go through `dispatch_event_batch()` triggers.
## Validation Commands
diff --git a/packages/jobs/src/inngest/functions/events/queue.ts b/packages/jobs/src/inngest/functions/events/queue.ts
index 60a85814d9..07952d00ed 100644
--- a/packages/jobs/src/inngest/functions/events/queue.ts
+++ b/packages/jobs/src/inngest/functions/events/queue.ts
@@ -8,9 +8,10 @@ import { type Kysely, PostgresDriver, sql } from "kysely";
import { inngest } from "../../client";
const QUEUE_NAME = "event_system"; // Name of the PGMQ queue
-const BATCH_SIZE = 100; // Number of messages to process per run
+const BATCH_SIZE = 100; // Number of messages to process per pass
const VISIBILITY_TIMEOUT = 30; // Seconds a message is hidden after being read
const CHUNK_SIZE = 10; // Max events per sendEvent call (keeps under 256KB limit)
+const MAX_PASSES = 10; // Max read/dispatch/delete passes per run (~1000 msgs)
function chunk<T>(arr: T[], size: number): T[][] {
const chunks: T[][] = [];
@@ -34,162 +35,193 @@ type QueueJob = {
};
/**
- * Event queue cron function - polls PGMQ every minute and routes events to handlers.
+ * Event queue drainer - woken by `carbon/event-queue.process` and routes
+ * queued PGMQ events to handlers. The database pushes the wake: the
+ * dispatch_event_batch() trigger (and a pg_cron sweeper while messages are
+ * pending) POSTs to the event-wake edge function, which sends the wake event.
+ * The drain loops until the queue is empty, so a single run absorbs a burst.
+ * `concurrency: 1` serializes runs; bulk writes are coalesced upstream — the
+ * trigger wakes at most once per transaction (carbon.event_wake_sent GUC).
* This is the critical bridge between PostgreSQL events and inngest handlers.
*/
export const eventQueueFunction = inngest.createFunction(
{
id: "event-queue",
- retries: 2
+ retries: 2,
+ concurrency: 1
},
- { cron: "* * * * *" }, // Every minute
+ { event: "carbon/event-queue.process" },
async ({ step }) => {
- // 1. Read batch from PGMQ (checkpointed so replays don't re-read)
- type ReadQueueResult = {
- grouped: Record<HandlerType, QueueJob[]>;
- allIds: number[];
- };
-
- const { grouped, allIds } = (await step.run("read-queue", async () => {
- const pg = getDatabaseClient(1);
- const { rows: jobs } =
- await sql<QueueJob>`SELECT * FROM pgmq.read(${QUEUE_NAME}, ${VISIBILITY_TIMEOUT}, ${BATCH_SIZE})`.execute(
- pg
- );
-
- const grouped: Record<HandlerType, QueueJob[]> = {
- WEBHOOK: [],
- WORKFLOW: [],
- SYNC: [],
- SEARCH: [],
- AUDIT: [],
- EMBEDDING: []
+ let routed = 0;
+ let lastPassFull = false;
+
+ for (let pass = 0; pass < MAX_PASSES; pass++) {
+ // 1. Read batch from PGMQ (checkpointed so replays don't re-read)
+ type ReadQueueResult = {
+ grouped: Record<HandlerType, QueueJob[]>;
+ allIds: number[];
};
- for (const job of jobs) {
- grouped[job.message.handlerType].push(job);
- }
-
- return {
- grouped,
- allIds: jobs.map((j) => j.msg_id)
- };
- })) as ReadQueueResult;
+ const { grouped, allIds } = (await step.run(
+ `read-queue-${pass}`,
+ async () => {
+ const pg = getDatabaseClient(1);
+ const { rows: jobs } =
+ await sql<QueueJob>`SELECT * FROM pgmq.read(${QUEUE_NAME}, ${VISIBILITY_TIMEOUT}, ${BATCH_SIZE})`.execute(
+ pg
+ );
+
+ const grouped: Record<HandlerType, QueueJob[]> = {
+ WEBHOOK: [],
+ WORKFLOW: [],
+ SYNC: [],
+ SEARCH: [],
+ AUDIT: [],
+ EMBEDDING: []
+ };
+
+ for (const job of jobs) {
+ grouped[job.message.handlerType].push(job);
+ }
+
+ return {
+ grouped,
+ allIds: jobs.map((j) => j.msg_id)
+ };
+ }
+ )) as ReadQueueResult;
- if (allIds.length === 0) {
- return { processed: 0 };
- }
+ if (allIds.length === 0) {
+ lastPassFull = false;
+ break;
+ }
- // 3. Dispatch webhooks
- if (grouped.WEBHOOK.length > 0) {
- const events = grouped.WEBHOOK.map((job) => ({
- name: "carbon/event-webhook" as const,
- data: {
- msgId: job.msg_id,
- url: job.message.handlerConfig.url,
- config: job.message.handlerConfig,
- data: job.message.event
+ // 3. Dispatch webhooks
+ if (grouped.WEBHOOK.length > 0) {
+ const events = grouped.WEBHOOK.map((job) => ({
+ name: "carbon/event-webhook" as const,
+ data: {
+ msgId: job.msg_id,
+ url: job.message.handlerConfig.url,
+ config: job.message.handlerConfig,
+ data: job.message.event
+ }
+ }));
+
+ const chunks = chunk(events, CHUNK_SIZE);
+ for (let i = 0; i < chunks.length; i++) {
+ await step.sendEvent(`dispatch-webhooks-${pass}-${i}`, chunks[i]!);
}
- }));
-
- const chunks = chunk(events, CHUNK_SIZE);
- for (let i = 0; i < chunks.length; i++) {
- await step.sendEvent(`dispatch-webhooks-${i}`, chunks[i]!);
}
- }
- // 4. Dispatch workflows
- if (grouped.WORKFLOW.length > 0) {
- const events = grouped.WORKFLOW.map((job) => ({
- name: "carbon/event-workflow" as const,
- data: {
- msgId: job.msg_id,
- workflowId: job.message.handlerConfig.workflowId,
- data: job.message.event
+ // 4. Dispatch workflows
+ if (grouped.WORKFLOW.length > 0) {
+ const events = grouped.WORKFLOW.map((job) => ({
+ name: "carbon/event-workflow" as const,
+ data: {
+ msgId: job.msg_id,
+ workflowId: job.message.handlerConfig.workflowId,
+ data: job.message.event
+ }
+ }));
+
+ const chunks = chunk(events, CHUNK_SIZE);
+ for (let i = 0; i < chunks.length; i++) {
+ await step.sendEvent(`dispatch-workflows-${pass}-${i}`, chunks[i]!);
}
- }));
+ }
- const chunks = chunk(events, CHUNK_SIZE);
- for (let i = 0; i < chunks.length; i++) {
- await step.sendEvent(`dispatch-workflows-${i}`, chunks[i]!);
+ // 5. Dispatch syncs (chunked)
+ if (grouped.SYNC.length > 0) {
+ const records = grouped.SYNC.map((job) => ({
+ event: job.message.event,
+ companyId: job.message.companyId,
+ handlerConfig: job.message.handlerConfig
+ }));
+
+ const chunks = chunk(records, CHUNK_SIZE);
+ for (let i = 0; i < chunks.length; i++) {
+ await step.sendEvent(`dispatch-syncs-${pass}-${i}`, {
+ name: "carbon/event-sync" as const,
+ data: { records: chunks[i] }
+ });
+ }
}
- }
- // 5. Dispatch syncs (chunked)
- if (grouped.SYNC.length > 0) {
- const records = grouped.SYNC.map((job) => ({
- event: job.message.event,
- companyId: job.message.companyId,
- handlerConfig: job.message.handlerConfig
- }));
-
- const chunks = chunk(records, CHUNK_SIZE);
- for (let i = 0; i < chunks.length; i++) {
- await step.sendEvent(`dispatch-syncs-${i}`, {
- name: "carbon/event-sync" as const,
- data: { records: chunks[i] }
- });
+ // 6. Dispatch searches (chunked)
+ if (grouped.SEARCH.length > 0) {
+ const records = grouped.SEARCH.map((job) => ({
+ event: job.message.event,
+ companyId: job.message.companyId
+ }));
+
+ const chunks = chunk(records, CHUNK_SIZE);
+ for (let i = 0; i < chunks.length; i++) {
+ await step.sendEvent(`dispatch-searches-${pass}-${i}`, {
+ name: "carbon/event-search" as const,
+ data: { records: chunks[i] }
+ });
+ }
}
- }
- // 6. Dispatch searches (chunked)
- if (grouped.SEARCH.length > 0) {
- const records = grouped.SEARCH.map((job) => ({
- event: job.message.event,
- companyId: job.message.companyId
- }));
-
- const chunks = chunk(records, CHUNK_SIZE);
- for (let i = 0; i < chunks.length; i++) {
- await step.sendEvent(`dispatch-searches-${i}`, {
- name: "carbon/event-search" as const,
- data: { records: chunks[i] }
- });
+ // 7. Dispatch audits (chunked)
+ if (grouped.AUDIT.length > 0) {
+ const records = grouped.AUDIT.map((job) => ({
+ event: job.message.event,
+ companyId: job.message.companyId,
+ actorId: job.message.actorId,
+ handlerConfig: job.message.handlerConfig
+ }));
+
+ const chunks = chunk(records, CHUNK_SIZE);
+ for (let i = 0; i < chunks.length; i++) {
+ await step.sendEvent(`dispatch-audits-${pass}-${i}`, {
+ name: "carbon/event-audit" as const,
+ data: { records: chunks[i] }
+ });
+ }
}
- }
- // 7. Dispatch audits (chunked)
- if (grouped.AUDIT.length > 0) {
- const records = grouped.AUDIT.map((job) => ({
- event: job.message.event,
- companyId: job.message.companyId,
- actorId: job.message.actorId,
- handlerConfig: job.message.handlerConfig
- }));
-
- const chunks = chunk(records, CHUNK_SIZE);
- for (let i = 0; i < chunks.length; i++) {
- await step.sendEvent(`dispatch-audits-${i}`, {
- name: "carbon/event-audit" as const,
- data: { records: chunks[i] }
- });
+ // 8. Dispatch embeddings (chunked)
+ if (grouped.EMBEDDING.length > 0) {
+ const records = grouped.EMBEDDING.map((job) => ({
+ event: job.message.event,
+ companyId: job.message.companyId
+ }));
+
+ const chunks = chunk(records, CHUNK_SIZE);
+ for (let i = 0; i < chunks.length; i++) {
+ await step.sendEvent(`dispatch-embeddings-${pass}-${i}`, {
+ name: "carbon/event-embedding" as const,
+ data: { records: chunks[i] }
+ });
+ }
}
- }
- // 8. Dispatch embeddings (chunked)
- if (grouped.EMBEDDING.length > 0) {
- const records = grouped.EMBEDDING.map((job) => ({
- event: job.message.event,
- companyId: job.message.companyId
- }));
-
- const chunks = chunk(records, CHUNK_SIZE);
- for (let i = 0; i < chunks.length; i++) {
- await step.sendEvent(`dispatch-embeddings-${i}`, {
- name: "carbon/event-embedding" as const,
- data: { records: chunks[i] }
- });
+ // 9. Delete processed messages from PGMQ
+ await step.run(`delete-processed-${pass}`, async () => {
+ const pg = getDatabaseClient(1);
+ await sql`SELECT pgmq.delete(${QUEUE_NAME}, id::bigint) FROM unnest(${allIds}::bigint[]) AS id`.execute(
+ pg
+ );
+ });
+
+ routed += allIds.length;
+ lastPassFull = allIds.length === BATCH_SIZE;
+ if (!lastPassFull) {
+ break;
}
}
- // 9. Delete processed messages from PGMQ
- await step.run("delete-processed", async () => {
- const pg = getDatabaseClient(1);
- await sql`SELECT pgmq.delete(${QUEUE_NAME}, id::bigint) FROM unnest(${allIds}::bigint[]) AS id`.execute(
- pg
- );
- });
+ // Hit MAX_PASSES with a full final batch: hand off to a fresh run rather
+ // than growing this one past Inngest's step limit.
+ if (lastPassFull) {
+ await step.sendEvent("re-wake", {
+ name: "carbon/event-queue.process",
+ data: {}
+ });
+ }
- return { routed: allIds.length };
+ return { routed };
}
);
diff --git a/packages/jobs/src/inngest/functions/tasks/model-optimize.ts b/packages/jobs/src/inngest/functions/tasks/model-optimize.ts
index dc0a9d00a4..05b882fdfb 100644
--- a/packages/jobs/src/inngest/functions/tasks/model-optimize.ts
+++ b/packages/jobs/src/inngest/functions/tasks/model-optimize.ts
@@ -53,7 +53,7 @@ export const modelOptimizeFunction = inngest.createFunction(
const client = getCarbonServiceRole();
const upload = await client
.from("modelUpload")
- .select("id, modelPath")
+ .select("id, modelPath, optimizeStatus, optimizedModelPath")
.eq("id", modelUploadId)
.eq("companyId", companyId)
.single();
@@ -62,6 +62,17 @@ export const modelOptimizeFunction = inngest.createFunction(
`Model upload ${modelUploadId} not found or has no file`
);
}
+ // Already optimised → reuse it, never redo. An optimise is deterministic,
+ // so a successful one is final; only a Failed row is worth re-firing
+ // (that's what the viewer's Retry does). Guards against any caller —
+ // client auto-fire, an errant retry — re-running the assembler on a model
+ // that already has its GLB.
+ if (
+ upload.data.optimizeStatus === "Success" &&
+ upload.data.optimizedModelPath
+ ) {
+ return { alreadyOptimized: true as const };
+ }
// Derive the source format from the stored file, not the caller — every
// attach point (part/quote/rfq create, generic upload) then triggers with
// just the id, and non-mesh inputs (stl/obj/iges/…) skip cleanly. Strips a
@@ -79,9 +90,21 @@ export const modelOptimizeFunction = inngest.createFunction(
client,
upload.data.modelPath
);
- return { modelPath: upload.data.modelPath, format, sourceBucket };
+ return {
+ modelPath: upload.data.modelPath,
+ format,
+ sourceBucket,
+ alreadyOptimized: false as const
+ };
});
+ if (model.alreadyOptimized) {
+ logger.info("model optimise skipped — already optimised", {
+ modelUploadId
+ });
+ return { modelUploadId, status: "AlreadyOptimized" as const };
+ }
+
if (!model.format) {
logger.info("model optimise skipped — not an optimisable mesh format", {
modelUploadId,
diff --git a/packages/lib/src/events.ts b/packages/lib/src/events.ts
index 635c3a7893..6320fc03d8 100644
--- a/packages/lib/src/events.ts
+++ b/packages/lib/src/events.ts
@@ -321,7 +321,8 @@ export type Events = {
};
};
- // Event queue processing (PGMQ consumer)
+ // Wake event for the PGMQ drainer (event-queue). Pushed by the database via
+ // the event-wake edge function whenever events are enqueued or pending.
"carbon/event-queue.process": {
data: Record<string, never>;
};
diff --git a/packages/viewer/src/useOptimizedModel.ts b/packages/viewer/src/useOptimizedModel.ts
index e7ad4d0bfb..ffd7081344 100644
--- a/packages/viewer/src/useOptimizedModel.ts
+++ b/packages/viewer/src/useOptimizedModel.ts
@@ -105,7 +105,12 @@ export function useOptimizedModel({
},
staleTime: 0,
gcTime: 5 * 60 * 1000,
+ // A missing model (unknown id → artifacts 404) settles as an error with no
+ // data; don't poll it forever. Auto-fire is already gated on `artifacts`
+ // being present, so an errored query never triggers an optimise.
+ retry: 1,
refetchInterval: (q) => {
+ if (q.state.status === "error") return false;
const d = q.state.data;
if (!d) return POLL_MS;
if (d.optimizedModelPath || d.glbPath) return false;