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(models): decouple raw compaction from optimize, STEP → xbf, orphan-only prune

Sidwebworks0dd3e8911509
diff --git a/.ai/plans/2026-07-22-model-compact-xbf.md b/.ai/plans/2026-07-22-model-compact-xbf.md
new file mode 100644
index 0000000000..dd3b1a38fb
--- /dev/null
+++ b/.ai/plans/2026-07-22-model-compact-xbf.md
@@ -0,0 +1,44 @@
+# Model raw retention: decoupled compact + xbf mode + orphan-only prune
+
+Problem: STEP raws >50MB get lost. Compact (raw → `.zst`) only runs inside the
+optimize success path (best-effort), and the nightly prune deletes any
+non-`.zst` `temp-staging` raw >50MB older than 7 days — including raws whose
+optimize failed/was skipped, legacy pre-pipeline raws, and compact-failed raws.
+Result: `modelUpload.modelPath` points at a deleted object → assemblies say
+"no model".
+
+Decisions (user-approved 2026-07-22):
+- Compact STEP raws to **xbf** (`STEP → OCCT BinXCAF → zstd`, mode `xbf`) —
+ far smaller than zstd'd ASCII STEP. Mesh raws keep mode `zstd`.
+- xbf raws are **not downloadable** (OCCT-internal format) — hide the download
+ action in the files lists.
+- Compact is decoupled from optimize success; prune becomes orphan-only.
+
+## Tasks
+
+- [x] 1. `packages/lib/src/events.ts` — add `carbon/model-compact` event
+ `{ modelUploadId, companyId }`.
+- [x] 2. `packages/utils/src/file.ts` — add `isModelRawDownloadable(modelPath)`:
+ false when the `.zst`-peeled path ends `.xbf`. Export via utils barrel.
+- [x] 3. New `packages/jobs/src/inngest/functions/tasks/model-compact.ts` —
+ standalone Inngest function (retries 3): load row; skip if already
+ `.zst`, non-`temp-staging` bucket, no optimizable format, or assembler
+ disabled; mode `xbf` for `step` (output `{id}.xbf.zst`) else `zstd`
+ (output `{id}.{format}.zst`); persist repoint (freeze `originalSize`,
+ rewrite `size`), delete fat original.
+- [x] 4. `model-optimize.ts` — remove inline compact block; fire
+ `carbon/model-compact` on success, on alreadyOptimized (heals legacy
+ fat raws), and in `onFailure`.
+- [x] 5. Register function in `tasks/index.ts` + `inngest/index.ts`.
+- [x] 6. `cleanup.ts` prune — exclude any candidate still referenced by a
+ `modelUpload.modelPath` (orphan-only delete).
+- [x] 7. `production.models.ts` `getAssemblyModelState` — accept `.xbf`.
+- [x] 8. Hide download for non-downloadable raws in `Documents.tsx`,
+ `OpportunityLineDocuments.tsx`, `JobDocuments.tsx`, `ItemDocuments.tsx`.
+- [x] 9. Update stale comments (`const.ts` prune note, model-optimize header).
+
+## Verification
+
+- `pnpm exec turbo run typecheck --filter=@carbon/utils --filter=@carbon/jobs --filter=erp`
+- Existing behavior preserved: already-compacted `.step.zst` rows still read
+ (assembler content-sniffs; state check peels `.zst`).
diff --git a/apps/erp/app/components/Documents.tsx b/apps/erp/app/components/Documents.tsx
index cd24951e4d..4d30755a8b 100644
--- a/apps/erp/app/components/Documents.tsx
+++ b/apps/erp/app/components/Documents.tsx
@@ -21,7 +21,11 @@ import {
Tr,
toast
} from "@carbon/react";
-import { convertKbToString, MODEL_RAW_KEEP_MAX_BYTES } from "@carbon/utils";
+import {
+ convertKbToString,
+ isModelRawDownloadable,
+ MODEL_RAW_KEEP_MAX_BYTES
+} from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import type { ChangeEvent } from "react";
import { useCallback } from "react";
@@ -328,11 +332,13 @@ const Documents = ({
/>
</DropdownMenuTrigger>
<DropdownMenuContent>
- <DropdownMenuItem
- onClick={() => downloadModel(modelUpload)}
- >
- <Trans>Download</Trans>
- </DropdownMenuItem>
+ {isModelRawDownloadable(modelUpload.modelPath) && (
+ <DropdownMenuItem
+ onClick={() => downloadModel(modelUpload)}
+ >
+ <Trans>Download</Trans>
+ </DropdownMenuItem>
+ )}
<DropdownMenuItem asChild>
<Link
to={
diff --git a/apps/erp/app/modules/items/ui/Item/ItemDocuments.tsx b/apps/erp/app/modules/items/ui/Item/ItemDocuments.tsx
index 8017138675..f41ece9713 100644
--- a/apps/erp/app/modules/items/ui/Item/ItemDocuments.tsx
+++ b/apps/erp/app/modules/items/ui/Item/ItemDocuments.tsx
@@ -21,7 +21,11 @@ import {
Tr,
toast
} from "@carbon/react";
-import { convertKbToString, MODEL_RAW_KEEP_MAX_BYTES } from "@carbon/utils";
+import {
+ convertKbToString,
+ isModelRawDownloadable,
+ MODEL_RAW_KEEP_MAX_BYTES
+} from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import type { FileObject } from "@supabase/storage-js";
import type { ChangeEvent } from "react";
@@ -163,11 +167,13 @@ const ItemDocuments = ({
<Trans>View</Trans>
</Link>
</DropdownMenuItem>
- <DropdownMenuItem
- onClick={() => downloadModel(modelUpload)}
- >
- Download
- </DropdownMenuItem>
+ {isModelRawDownloadable(modelUpload.modelPath) && (
+ <DropdownMenuItem
+ onClick={() => downloadModel(modelUpload)}
+ >
+ Download
+ </DropdownMenuItem>
+ )}
<DropdownMenuItem
destructive
disabled={isReadOnly || !canDelete}
diff --git a/apps/erp/app/modules/production/production.models.ts b/apps/erp/app/modules/production/production.models.ts
index a7f2c96f61..65cc87e1a2 100644
--- a/apps/erp/app/modules/production/production.models.ts
+++ b/apps/erp/app/modules/production/production.models.ts
@@ -1183,12 +1183,13 @@ export function getAssemblyModelState(
) {
return "converted";
}
- // The retained raw is zstd-compacted in place after a successful optimise
- // (`x.step` -> `x.step.zst`), so peel the `.zst` wrapper before the extension
- // check — the compacted file is still a valid STEP the converter reads
- // transparently.
+ // The retained raw is compacted in place after upload (`x.step` ->
+ // `x.xbf.zst`, legacy `x.step.zst`), so peel the `.zst` wrapper before the
+ // extension check. Both STEP and its BinXCAF (`.xbf`) compacted form are
+ // convertible — the assembler content-sniffs and loads either through the
+ // same OCCT walk, yielding identical nodeIds.
const base = (model.modelPath ?? "").toLowerCase().replace(/\.zst$/, "");
- const isStep = [".step", ".stp"].some((ext) => base.endsWith(ext));
+ const isStep = [".step", ".stp", ".xbf"].some((ext) => base.endsWith(ext));
if (!isStep) return "none";
if (
model.processingStatus === "Queued" ||
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobDocuments.tsx b/apps/erp/app/modules/production/ui/Jobs/JobDocuments.tsx
index 2b438d9c55..1bfdcca83f 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobDocuments.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobDocuments.tsx
@@ -27,7 +27,11 @@ import {
toast,
VStack
} from "@carbon/react";
-import { convertKbToString, MODEL_RAW_KEEP_MAX_BYTES } from "@carbon/utils";
+import {
+ convertKbToString,
+ isModelRawDownloadable,
+ MODEL_RAW_KEEP_MAX_BYTES
+} from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import type { FileObject } from "@supabase/storage-js";
import type { ChangeEvent } from "react";
@@ -449,11 +453,13 @@ const JobDocuments = ({
<Trans>View</Trans>
</Link>
</DropdownMenuItem>
- <DropdownMenuItem
- onClick={() => downloadModel(modelUpload)}
- >
- Download
- </DropdownMenuItem>
+ {isModelRawDownloadable(modelUpload.modelPath) && (
+ <DropdownMenuItem
+ onClick={() => downloadModel(modelUpload)}
+ >
+ Download
+ </DropdownMenuItem>
+ )}
<DropdownMenuItem
destructive
disabled={!canDelete || isReadOnly}
diff --git a/apps/erp/app/modules/sales/ui/Opportunity/OpportunityLineDocuments.tsx b/apps/erp/app/modules/sales/ui/Opportunity/OpportunityLineDocuments.tsx
index 462bf17959..5af7313575 100644
--- a/apps/erp/app/modules/sales/ui/Opportunity/OpportunityLineDocuments.tsx
+++ b/apps/erp/app/modules/sales/ui/Opportunity/OpportunityLineDocuments.tsx
@@ -27,7 +27,11 @@ import {
toast,
VStack
} from "@carbon/react";
-import { convertKbToString, MODEL_RAW_KEEP_MAX_BYTES } from "@carbon/utils";
+import {
+ convertKbToString,
+ isModelRawDownloadable,
+ MODEL_RAW_KEEP_MAX_BYTES
+} from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import type { FileObject } from "@supabase/storage-js";
import type { ChangeEvent } from "react";
@@ -519,11 +523,13 @@ const OpportunityLineDocuments = ({
<Trans>View</Trans>
</Link>
</DropdownMenuItem>
- <DropdownMenuItem
- onClick={() => downloadModel(modelUpload)}
- >
- <Trans>Download</Trans>
- </DropdownMenuItem>
+ {isModelRawDownloadable(modelUpload.modelPath) && (
+ <DropdownMenuItem
+ onClick={() => downloadModel(modelUpload)}
+ >
+ <Trans>Download</Trans>
+ </DropdownMenuItem>
+ )}
<DropdownMenuItem
destructive
disabled={!canDelete}
diff --git a/packages/jobs/src/inngest/functions/scheduled/cleanup.ts b/packages/jobs/src/inngest/functions/scheduled/cleanup.ts
index 1564f2f365..8976f6d1c5 100644
--- a/packages/jobs/src/inngest/functions/scheduled/cleanup.ts
+++ b/packages/jobs/src/inngest/functions/scheduled/cleanup.ts
@@ -336,11 +336,9 @@ export const cleanupFunction = inngest.createFunction(
return;
}
- // Prune only UNCOMPACTED fat raws — a successful optimise replaces its raw
- // with a compacted `raw.<ext>.zst` (the permanent lazy-plan source, never
- // pruned even when its compressed size still exceeds the cap). A leftover
- // non-`.zst` raw over the cap means optimise never completed, so it's dead
- // weight past the TTL.
+ // Prune only UNCOMPACTED fat raws — the compact pipeline replaces a raw
+ // with `raw.<ext>.zst` / `raw.xbf.zst` (the permanent lazy-plan source,
+ // never pruned even when its compressed size still exceeds the cap).
const big = (stale.data ?? [])
.filter(
(o) =>
@@ -356,13 +354,44 @@ export const cleanupFunction = inngest.createFunction(
return;
}
+ // Orphans only — never delete an object a modelUpload still points at.
+ // A referenced fat raw means compaction hasn't succeeded yet (compact
+ // retries independently of optimise); deleting it would destroy the only
+ // copy of the model and break assemblies. True strays (upload recorded
+ // no row, or the row was repointed/deleted) are the actual dead weight.
+ const referenced = await serviceRole
+ .from("modelUpload")
+ .select("modelPath")
+ .in("modelPath", big);
+ if (referenced.error) {
+ logger.error(
+ "Error resolving referenced staged raws — skipping prune",
+ {
+ error: referenced.error
+ }
+ );
+ return;
+ }
+ const referencedPaths = new Set(
+ (referenced.data ?? []).map((r) => r.modelPath)
+ );
+ const orphans = big.filter((n) => !referencedPaths.has(n));
+ if (orphans.length === 0) {
+ logger.info("No orphaned large staged raws to prune", {
+ referenced: big.length
+ });
+ return;
+ }
+
const removed = await serviceRole.storage
.from("temp-staging")
- .remove(big);
+ .remove(orphans);
if (removed.error) {
logger.error("Error pruning staged raws", { error: removed.error });
} else {
- logger.info("Pruned large staged raw models", { count: big.length });
+ logger.info("Pruned orphaned staged raw models", {
+ count: orphans.length
+ });
}
});
}
diff --git a/packages/jobs/src/inngest/functions/tasks/index.ts b/packages/jobs/src/inngest/functions/tasks/index.ts
index f5387204c2..02d95755c0 100644
--- a/packages/jobs/src/inngest/functions/tasks/index.ts
+++ b/packages/jobs/src/inngest/functions/tasks/index.ts
@@ -7,6 +7,7 @@ export {
companyRestoreFunction,
companyRestoreRevertFunction
} from "./company-restore";
+export { modelCompactFunction } from "./model-compact";
export { modelOptimizeFunction } from "./model-optimize";
export { modelThumbnailFunction } from "./model-thumbnail";
export { onboardFunction } from "./onboard";
diff --git a/packages/jobs/src/inngest/functions/tasks/model-compact.ts b/packages/jobs/src/inngest/functions/tasks/model-compact.ts
new file mode 100644
index 0000000000..480ea7e4c7
--- /dev/null
+++ b/packages/jobs/src/inngest/functions/tasks/model-compact.ts
@@ -0,0 +1,152 @@
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { modelPathOptimizeFormat } from "@carbon/utils";
+import { inngest } from "../../client";
+import {
+ assemblerEnabled,
+ internalizeStorageUrl,
+ resolveModelSourceBucket,
+ runAssemblerJob
+} from "./assembler-client";
+
+const SIGNED_URL_EXPIRY = 60 * 60; // seconds — the source (read) URL only.
+const MAX_COMPACT_WAIT_MS = 15 * 60 * 1000;
+
+/**
+ * Compact the retained raw so it never lingers as the fat upload. STEP sources
+ * become OCCT BinXCAF (`{id}.xbf.zst` — lossless B-rep + assembly tree, far
+ * smaller than zstd'd ASCII STEP, same nodeIds when converted); mesh sources
+ * are zstd'd in their original format (`{id}.{ext}.zst`, decompresses back to
+ * the openable source file). On success `modelPath` is repointed at the
+ * compacted raw and the fat original is deleted.
+ *
+ * Decoupled from model-optimize: fired after optimize settles regardless of
+ * outcome, so a failed or skipped optimize can't strand a fat raw for the
+ * scheduled prune. Own retries — compaction is cheap relative to optimize
+ * (zstd only, or a tessellation-free OCCT parse for xbf), so it can succeed
+ * where optimize can't.
+ */
+export const modelCompactFunction = inngest.createFunction(
+ { id: "model-compact", retries: 3 },
+ { event: "carbon/model-compact" },
+ async ({ event, step, logger }) => {
+ const { modelUploadId, companyId } = event.data;
+
+ if (!assemblerEnabled()) {
+ logger.info("model compact skipped — assembler is not configured", {
+ modelUploadId
+ });
+ return { modelUploadId, status: "Skipped" as const };
+ }
+
+ const model = await step.run("resolve", async () => {
+ const client = getCarbonServiceRole();
+ const upload = await client
+ .from("modelUpload")
+ .select("id, modelPath")
+ .eq("id", modelUploadId)
+ .eq("companyId", companyId)
+ .single();
+ if (upload.error || !upload.data?.modelPath) {
+ throw new Error(
+ `Model upload ${modelUploadId} not found or has no file`
+ );
+ }
+ const sourceBucket = await resolveModelSourceBucket(
+ client,
+ upload.data.modelPath
+ );
+ return {
+ modelPath: upload.data.modelPath,
+ format: modelPathOptimizeFormat(upload.data.modelPath),
+ sourceBucket
+ };
+ });
+
+ // Only temp-staging sources compact: the flow writes the .zst there,
+ // deletes the fat original there, and the prune covers strays there.
+ // Legacy `private` raws predate the pipeline — leave them where they are.
+ if (
+ model.modelPath.toLowerCase().endsWith(".zst") ||
+ model.sourceBucket !== "temp-staging" ||
+ !model.format
+ ) {
+ logger.info("model compact skipped", {
+ modelUploadId,
+ modelPath: model.modelPath,
+ sourceBucket: model.sourceBucket
+ });
+ return { modelUploadId, status: "Skipped" as const };
+ }
+
+ // STEP → BinXCAF; everything else → plain zstd of the raw. Flat path
+ // mirroring the original raw so the model id stays recoverable from the
+ // path (CadModel's `modelIdFromPath`) and the download route resolves the
+ // underlying format from the extension.
+ const mode = model.format === "step" ? "xbf" : "zstd";
+ const compactExt = mode === "xbf" ? "xbf" : model.format;
+ const compactPath = `${companyId}/models/${modelUploadId}.${compactExt}.zst`;
+ const jobId = `compact-${modelUploadId}`;
+
+ const compact = await runAssemblerJob(step, {
+ idPrefix: "compact",
+ action: "compact",
+ jobId,
+ maxWaitMs: MAX_COMPACT_WAIT_MS,
+ logger,
+ buildBody: async () => {
+ const client = getCarbonServiceRole();
+ const source = await client.storage
+ .from("temp-staging")
+ .createSignedUrl(model.modelPath, SIGNED_URL_EXPIRY);
+ if (source.error) {
+ throw new Error(`sign source: ${source.error.message}`);
+ }
+ return {
+ source: { url: internalizeStorageUrl(source.data.signedUrl) },
+ mode,
+ output: { path: compactPath }
+ };
+ },
+ mintUploadUrls: async () => {
+ const client = getCarbonServiceRole();
+ const upload = await client.storage
+ .from("temp-staging")
+ .createSignedUploadUrl(compactPath, { upsert: true });
+ const urls: Record<string, string> = {};
+ if (upload.data)
+ urls.raw = internalizeStorageUrl(upload.data.signedUrl);
+ return urls;
+ }
+ });
+ const compactedSize =
+ (compact.stats as { outputBytes?: number } | null)?.outputBytes ?? null;
+
+ await step.run("persist", async () => {
+ const client = getCarbonServiceRole();
+ // Repoint modelPath at the compacted raw and record its (compressed)
+ // stored size so the files list reflects what's actually on disk, then
+ // drop the fat original. Freeze the as-uploaded bytes into originalSize
+ // first (rows from before the column exist with null) — the viewer's
+ // reduction badge compares the ORIGINAL, not the .zst.
+ const existing = await client
+ .from("modelUpload")
+ .select("size, originalSize")
+ .eq("id", modelUploadId)
+ .maybeSingle();
+ await client
+ .from("modelUpload")
+ .update({
+ modelPath: compactPath,
+ ...(existing.data && existing.data.originalSize == null
+ ? { originalSize: existing.data.size }
+ : {}),
+ ...(compactedSize != null ? { size: compactedSize } : {})
+ })
+ .eq("id", modelUploadId);
+ await client.storage.from("temp-staging").remove([model.modelPath]);
+ });
+
+ logger.info("raw compacted", { modelUploadId, compactPath, mode });
+ return { modelUploadId, status: "Success" as const };
+ }
+);
diff --git a/packages/jobs/src/inngest/functions/tasks/model-optimize.ts b/packages/jobs/src/inngest/functions/tasks/model-optimize.ts
index 05b882fdfb..4567354e3e 100644
--- a/packages/jobs/src/inngest/functions/tasks/model-optimize.ts
+++ b/packages/jobs/src/inngest/functions/tasks/model-optimize.ts
@@ -25,7 +25,7 @@ export const modelOptimizeFunction = inngest.createFunction(
id: "model-optimize",
retries: 2,
onFailure: async ({ event }) => {
- const { modelUploadId } = event.data.event.data;
+ const { modelUploadId, companyId } = event.data.event.data;
const client = getCarbonServiceRole();
await client
.from("modelUpload")
@@ -34,6 +34,12 @@ export const modelOptimizeFunction = inngest.createFunction(
optimizeError: event.data.error.message
})
.eq("id", modelUploadId);
+ // A failed optimise must not strand the fat raw for the prune — compact
+ // is cheaper than optimise (no simplify ladder) and often still succeeds.
+ await inngest.send({
+ name: "carbon/model-compact",
+ data: { modelUploadId, companyId }
+ });
}
},
{ event: "carbon/model-optimize" },
@@ -99,6 +105,13 @@ export const modelOptimizeFunction = inngest.createFunction(
});
if (model.alreadyOptimized) {
+ // Still fire compact — legacy rows optimised before the compact pipeline
+ // (or after a compact failure) may hold an uncompacted fat raw; the
+ // compact function no-ops on already-`.zst` paths.
+ await step.sendEvent("compact", {
+ name: "carbon/model-compact",
+ data: { modelUploadId, companyId }
+ });
logger.info("model optimise skipped — already optimised", {
modelUploadId
});
@@ -183,92 +196,14 @@ export const modelOptimizeFunction = inngest.createFunction(
.eq("id", modelUploadId);
});
- // Compact the retained raw so it never lingers as the fat upload. Every
- // optimisable source (any size) is zstd-compressed IN ITS ORIGINAL FORMAT —
- // `raw.<ext>.zst` stays a valid STEP/glTF/… that the download route
- // decompresses back to the source file, and the assembler reads it back
- // transparently (zstd-decoded on fetch), so plan/convert/reoptimise need no
- // change. Already-compacted (`.zst`) raws are skipped. Best-effort: a
- // compaction failure must not fail the already-succeeded optimise (the
- // scheduled big-raw TTL prune is the safety net).
- // Only temp-staging sources compact: the flow writes the .zst there, deletes
- // the fat original there, and the TTL prune covers strays there. Legacy
- // `private` raws predate the pipeline — leave them where they are.
- const alreadyCompacted = model.modelPath.toLowerCase().endsWith(".zst");
- if (!alreadyCompacted && model.sourceBucket === "temp-staging") {
- // Flat, mirroring the original raw (`${id}.step` → `${id}.step.zst`), so the
- // model id stays recoverable from the path (CadModel's `modelIdFromPath`)
- // and the download route resolves the underlying format from the extension.
- const compactPath = `${companyId}/models/${modelUploadId}.${format}.zst`;
- const compactJobId = `compact-${modelUploadId}`;
- try {
- const compact = await runAssemblerJob(step, {
- idPrefix: "compact",
- action: "compact",
- jobId: compactJobId,
- maxWaitMs: MAX_OPTIMIZE_WAIT_MS,
- logger,
- buildBody: async () => {
- const client = getCarbonServiceRole();
- const source = await client.storage
- .from("temp-staging")
- .createSignedUrl(model.modelPath, SIGNED_URL_EXPIRY);
- if (source.error) {
- throw new Error(`sign source: ${source.error.message}`);
- }
- return {
- source: { url: internalizeStorageUrl(source.data.signedUrl) },
- mode: "zstd",
- output: { path: compactPath }
- };
- },
- mintUploadUrls: async () => {
- const client = getCarbonServiceRole();
- const upload = await client.storage
- .from("temp-staging")
- .createSignedUploadUrl(compactPath, { upsert: true });
- const urls: Record<string, string> = {};
- if (upload.data)
- urls.raw = internalizeStorageUrl(upload.data.signedUrl);
- return urls;
- }
- });
- const compactedSize =
- (compact.stats as { outputBytes?: number } | null)?.outputBytes ??
- null;
-
- await step.run("compact-persist", async () => {
- const client = getCarbonServiceRole();
- // Repoint modelPath at the compacted raw and record its (compressed)
- // stored size so the files list reflects what's actually on disk, then
- // drop the fat original. Freeze the as-uploaded bytes into
- // originalSize first (rows from before the column exist with null) —
- // the viewer's reduction badge compares the ORIGINAL, not the .zst.
- const existing = await client
- .from("modelUpload")
- .select("size, originalSize")
- .eq("id", modelUploadId)
- .maybeSingle();
- await client
- .from("modelUpload")
- .update({
- modelPath: compactPath,
- ...(existing.data && existing.data.originalSize == null
- ? { originalSize: existing.data.size }
- : {}),
- ...(compactedSize != null ? { size: compactedSize } : {})
- })
- .eq("id", modelUploadId);
- await client.storage.from("temp-staging").remove([model.modelPath]);
- });
- logger.info("raw compacted", { modelUploadId, compactPath });
- } catch (err) {
- logger.warn("raw compaction skipped", {
- modelUploadId,
- error: (err as Error).message
- });
- }
- }
+ // Compact the retained raw (STEP → `.xbf.zst`, mesh → `.{ext}.zst`) in its
+ // own function with its own retries — decoupled so this optimise's outcome
+ // never decides whether the raw survives (see model-compact.ts; onFailure
+ // fires the same event).
+ await step.sendEvent("compact", {
+ name: "carbon/model-compact",
+ data: { modelUploadId, companyId }
+ });
logger.info("model optimise finalized", { modelUploadId, stats });
return { modelUploadId, status: "Success" as const };
diff --git a/packages/jobs/src/inngest/index.ts b/packages/jobs/src/inngest/index.ts
index 7cd8410e83..f6d84330ab 100644
--- a/packages/jobs/src/inngest/index.ts
+++ b/packages/jobs/src/inngest/index.ts
@@ -47,6 +47,7 @@ import {
companyRestoreFinalizeFunction,
companyRestoreFunction,
companyRestoreRevertFunction,
+ modelCompactFunction,
modelOptimizeFunction,
modelThumbnailFunction,
onboardFunction,
@@ -81,6 +82,7 @@ export const functions = [
companyRestoreFunction,
companyRestoreFinalizeFunction,
companyRestoreRevertFunction,
+ modelCompactFunction,
modelOptimizeFunction,
modelThumbnailFunction,
updatePermissionsFunction,
diff --git a/packages/lib/src/events.ts b/packages/lib/src/events.ts
index 6320fc03d8..2f244dd21a 100644
--- a/packages/lib/src/events.ts
+++ b/packages/lib/src/events.ts
@@ -133,6 +133,17 @@ export type Events = {
};
};
+ // Compact the retained raw (STEP → BinXCAF `.xbf.zst`, mesh → `.{ext}.zst`)
+ // so it never lingers as the fat upload. Fired after model-optimize settles
+ // (success, already-optimized, or failure) — decoupled so an optimize
+ // failure can't strand a fat raw for the prune to delete.
+ "carbon/model-compact": {
+ data: {
+ modelUploadId: string;
+ companyId: string;
+ };
+ };
+
// Company backup export — snapshot all company-scoped rows (and
// optionally storage files) into a gzipped backup in the company bucket
"carbon/company-export": {
diff --git a/packages/utils/src/const.ts b/packages/utils/src/const.ts
index ee07c6cd11..ed37d4031d 100644
--- a/packages/utils/src/const.ts
+++ b/packages/utils/src/const.ts
@@ -16,9 +16,11 @@ export const FILE_SIZE_LIMIT_MB = {
DOCUMENT_UPLOAD: 50
} as const;
-// Raw CAD source is kept in `temp-staging` and shown as a downloadable file in the
-// documents list only when <= this (the served-bucket cap). Larger raws are hidden
-// from the files list and TTL-pruned from staging — only the optimised GLB is kept.
+// Raw CAD source is kept in `temp-staging` and shown as a file in the documents
+// list only when <= this (the served-bucket cap). Larger raws are hidden from
+// the files list until the compact pipeline shrinks them (`.xbf.zst` /
+// `.{ext}.zst`); the scheduled prune deletes only ORPHANED fat raws — anything
+// a modelUpload still points at is kept until compaction succeeds.
export const MODEL_RAW_KEEP_MAX_BYTES = 50 * 1024 * 1024;
export const PO_EMAIL_ATTACHMENT_LIMIT_MB = 25;
diff --git a/packages/utils/src/file.ts b/packages/utils/src/file.ts
index fdac33a0f2..9374ddb931 100644
--- a/packages/utils/src/file.ts
+++ b/packages/utils/src/file.ts
@@ -79,6 +79,18 @@ export function modelPathOptimizeFormat(modelPath: string) {
return optimizableModelFormat(ext);
}
+// Whether the retained raw is worth offering as a download. STEP raws are
+// compacted to OCCT BinXCAF (`{id}.xbf.zst`) — an OCCT-internal container no
+// CAD tool opens, so downloading it would hand the user garbage bytes under the
+// original `.step` filename. Mesh raws stay zstd'd in their original format and
+// decompress back to the openable source file.
+export function isModelRawDownloadable(modelPath: string | null | undefined) {
+ if (!modelPath) return false;
+ const lower = modelPath.toLowerCase();
+ const base = lower.endsWith(".zst") ? lower.slice(0, -4) : lower;
+ return !base.endsWith(".xbf");
+}
+
// Every format here is renderable in the browser (viewer raw tier: three-stdlib
// loaders + occt/rhino3dm WASM). ifc and fcstd were dropped 2026-07-18: nothing
// in the stack can preview them (each needs its own heavy WASM dep) and both