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.
Spec: Run the scheduling engine in-process (Node), not via the schedule edge function
Date: 2026-08-19 Status: In design → executing Owner: (agent, on Brad's request)
Problem
Every schedule regeneration in the app goes through the Supabase edge function
schedule (packages/database/supabase/functions/schedule/index.ts) via
serviceRole.functions.invoke("schedule", …). Observed: clicking the new
Regenerate button on the production Forecast takes >2s even with almost no
data, and can momentarily show an empty board.
Root cause of the latency is structural, not data volume:
- Edge cold start + HTTP round-trip. The app (Node) makes an HTTP call to the Deno edge runtime, which cold-starts an isolate and opens its own PG pool.
- Memory limits. Edge isolates are memory-constrained; a whole-location finite-scheduling pass is the wrong workload for that runtime.
The empty-board flash is a consequence of the same design: the caller fires the invoke and revalidates the loader; when the invoke is slow/errors, the page reads mid/post-regen state and the error is swallowed by the fetcher.
Goal
Run the scheduling engine in-process in Node wherever the app or background jobs trigger it, eliminating the edge cold-start + HTTP hop. Same engine, same determinism, same outputs — just executed locally.
Key discovery (why this is low-risk)
The engine and its whole transitive import graph are already Node-compatible:
packages/database/supabase/functions/lib/postgres/index.tsis explicitly dual-runtime (branches ontypeof Deno !== "undefined"; Node uses node-pg, Deno uses deno-postgres).…/lib/database.tsimportspg"so it can be imported as-is in Node".@carbon/databasealready re-exports scheduling-lib files into Node with no build step (packages/database/src/scheduling.ts→../supabase/functions/lib/scheduling/*.ts), consumed today byapps/erp/app/modules/production/forecastCalendar.server.ts. The.tsextension deep-imports resolve fine under Vite/esbuild.- The engine constructor takes
client(SupabaseClient) anddb(Kysely<DB>) as parameters — it does not import the pool factory, sopgnever enters the engine's value-import graph.
The only Node blocker in the entire graph is one line:
…/lib/logging.ts calls Deno.env.get("LOG_LEVEL") unguarded (imported solely
by scheduling-engine.ts). @logtape/* (which logging.ts uses) is
runtime-agnostic and already in the pnpm catalog (@carbon/logger uses it in
Node); it is simply not yet a declared dependency of packages/database.
Approach
Extract the orchestration currently inside the edge function's
serve()handler (job query + deterministic sort + expedite handling + sequential per-job engine loop + result aggregation) into a shared, runtime-neutral functionrunLocationSchedule(opts)in…/lib/scheduling/run-schedule.ts. It takes{ db, client, locationId, companyId, userId, expediteJobId? }and returns the same shape the edge function returns ({ locationId, jobsScheduled, conflictsDetected, newlyLate }or{ expedite }).Make
logging.tsdual-runtime — guard theDeno.envread, fall back toprocess.env.LOG_LEVELin Node. Add@logtape/logtape+@logtape/redactiontopackages/databasedependencies (catalog).Node bridge — re-export
runLocationSchedule(+ result types) from@carbon/database/scheduling.Edge function becomes a thin wrapper —
schedule/index.tskeeps itsserve+requirePermissions+ CORS, and delegates torunLocationSchedule. One orchestration, zero drift. The function stays deployed (config.toml unchanged) so nothing external breaks and self-hosted deploys are unaffected — but the app/jobs no longer call it.Repoint every in-app caller from
invoke("schedule", …)to a directrunLocationSchedulecall, passing the Node Kysely client (getDatabaseClient()in ERP,getJobDatabaseClient()in jobs) and a service-role SupabaseClient (getCarbonServiceRole()— matches the privileged execution the edge function did internally). Call sites:apps/erp/app/routes/api+/schedule.ts(the Regenerate button)apps/erp/app/modules/production/production.service.ts(recalculateJobOperationDependencies)apps/erp/app/routes/x+/job+/$jobId.status.tsxapps/erp/app/routes/api+/kanban.$id.tsxpackages/jobs/src/inngest/functions/tasks/recalculate.tspackages/jobs/src/inngest/functions/scheduled/schedule-inputs-changed.ts(the debounced replan wave)
Regenerate button correctness + UX — surface the
{ success, error }result with a toast (flash) so a failed regen is never silent, and the empty flash no longer reads as "no jobs". Because the call is now synchronous in-process and awaited before the action returns, the fetcher revalidation reads fully-committed state.
Non-goals
- Changing the scheduling algorithm, determinism, or outputs.
- Deleting the edge function or its
config.tomlentry (kept as a thin wrapper for compatibility / self-hosted / any external caller). - Changing the debounce/marking semantics of the reactive replan wave (only the per-location execution swaps HTTP-invoke → in-process call).
- Parallelizing locations in the wave (still sequential; out of scope).
Risks & mitigations
- A client bundle accidentally pulls in
pg/@logtape. Mitigated: every new importer is server-only (route actions,*.service.ts,*.server.ts, jobs).production.service.tsalready imports.servermodules, so it is already excluded from client bundles; adding another server-only import is consistent. Verified by a fullerpbuild. @logtapenot resolvable frompackages/databaseat runtime. Mitigated by adding it to that package's dependencies (catalog-pinned).- Behavioral drift between edge and Node paths. Mitigated by extracting ONE
runLocationScheduleboth call. - Auth. The edge function's
requirePermissionsis preserved for the edge path; the Node path is gated by the route's ownrequirePermissions(ERP) or runs assystem(jobs) — identical to how MRP's manual trigger already works.
Verification
turbo typecheckforerp,@carbon/jobs,@carbon/database.- Full
erpbuild (proves the engine imports resolve through the server/client split and no Node lib leaks into the client bundle). - Existing Deno scheduling unit tests remain valid (engine files untouched; only orchestration extracted and one logging line guarded).
- Manual: Regenerate button returns quickly and the board repopulates; a forced error shows a toast instead of an empty board.