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(assembler): memory-lean always-on service (#1822)
Sida6c2475c9142
diff --git a/Cargo.lock b/Cargo.lockindex 6be505d169..96f7178bb3 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -383,6 +383,7 @@ name = "converter"version = "0.1.0"dependencies = ["gltf",+ "libc","nalgebra","occt-bridge","regex",diff --git a/apps/assembler/AGENTS.md b/apps/assembler/AGENTS.mdindex 84d4a03212..0e19348995 100644--- a/apps/assembler/AGENTS.md+++ b/apps/assembler/AGENTS.md@@ -18,8 +18,8 @@ The service binary is `apps/assembler`; the heavy lifting lives in workspace cra```apps/assembler/ # axum HTTP: /health, /convert, /plan (async; long-poll GET /plan/{id}?wait=),- # /cache/invalidate; Memory|Redis job+result store (ASSEMBLER_REDIS_URL)- # + bearer auth, URL validation, concurrency semaphore, graceful shutdown+ # /cache/invalidate; Redis job+result store (REDIS_URL)+ # + bearer auth, URL validation, admission by memory, graceful shutdowncrates/├── collision/ # cxx bridge over C++ FCL 0.7.0. new_bvh / collide_pair / distance_pair.├── occt-bridge/ # cxx bridge over OpenCASCADE. read_step: XCAF walk + tessellation → flat node tree.@@ -91,61 +91,109 @@ cargo test -p collision -p converter -p planner --tests## Run```bash-ASSEMBLER_DEV_MODE=true cargo run -p assembler # listens on 0.0.0.0:8000 (ASSEMBLER_BIND to override)+REDIS_URL=redis://localhost:6379 ASSEMBLER_DEV_MODE=true cargo run -p assembler # listens on 0.0.0.0:8000 (PORT to override)```-Env: `ASSEMBLER_SERVICE_API_KEY` (bearer auth), `ASSEMBLER_DEV_MODE=true` (allow-unauth + http + skip TLS verify, local only), `ASSEMBLER_MAX_SOURCE_MB` (250),-`ASSEMBLER_MAX_PARTS` (5000), `ASSEMBLER_MAX_CONCURRENCY` (2),-`ASSEMBLER_SHUTDOWN_GRACE_S` (600), `ASSEMBLER_ALLOWED_URL_HOSTS`,-`ASSEMBLER_REDIS_URL` (unset ⇒ in-memory store), `ASSEMBLER_JOB_TTL_SECS`-(86400), `ASSEMBLER_RESULT_TTL_SECS` (86400), `ASSEMBLER_PENDING_TTL_SECS` (300),-`ASSEMBLER_MAX_LONG_POLL_S` (25).+Env: `REDIS_URL` (required — the job store; boot fails without it),+`ASSEMBLER_SERVICE_API_KEY` (bearer auth), `ASSEMBLER_DEV_MODE=true` (allow+unauth + http + skip TLS verify, local only), `PORT` (8000). Every other limit is+a constant or derived in `config.rs` (max parts 5000, shutdown grace 600 s, job+and result TTLs 24 h, pending TTL 5 min, long-poll cap 25 s) — deliberately not+env-tunable.## Completion & lifecycle-`/plan` is async: POST returns 202, the plan runs in a background task holding a-concurrency slot. Callers **long-poll** `GET /plan/{jobId}?wait=<secs>` — the-request is held open (server-capped at `ASSEMBLER_MAX_LONG_POLL_S`) until the job-reaches a terminal state, so completion is near-immediate and a whole plan costs-a handful of checkpointed Inngest steps rather than ~180 short polls (`?wait`-absent ⇒ immediate return, back-compat).--**Job status + pointers live in a backend-selectable store** (`plan_jobs.rs`),-chosen at boot by `ASSEMBLER_REDIS_URL`:-- unset ⇒ `Memory` (process-local DashMaps, single-process behavior);-- set + reachable ⇒ `Redis` (a set-but-unreachable URL logs and falls back to- memory — never refuses to boot).-Redis holds **only status + pointers, never plan/glb bytes**: `asm:job:{jobId}` →-`{status, planPath, stats, …}` (TTL `ASSEMBLER_JOB_TTL_SECS`). This is what makes-the service **stateless** — a restart or a sibling replica can still answer the-poll (no 404-on-restart loss).--**The plan artifact is offloaded to storage (late-mint).** The service has **no-persistent storage credentials**; instead the app mints a FRESH signed upload URL-on *each* long-poll and sends it as the `X-Plan-Upload-Url` header. On completion-the service marks the job `uploading` and parks the plan bytes in a short-TTL-hand-off buffer (`asm:pending:{jobId}` hash in Redis, or in-process in memory-mode); the next poll carrying a URL drains it — PUTting plan.json with a-seconds-old token, then returning the `{planPath, stats}` pointer. Minting late-(not at submit) keeps the token short-lived instead of needing one that outlives-the whole plan; buffering in Redis (not one replica's memory) means **any**-replica's poll can finalize, so it's not single-process/sticky. A plan not drained-within `ASSEMBLER_PENDING_TTL_SECS` is abandoned (the job re-plans). (Legacy: a job-with no `planPath` in meta returns the plan inline for the app to upload.)+Every action is an async job: POST returns 202 and the job runs in a background+task. Callers pass signed upload URLs at submit (`X-Carbon-Upload-Urls`) and a+`callback_url`; the job uploads its outputs and POSTs the terminal envelope the+moment compute ends. `GET /v1/jobs/{id}?wait=<secs>` long-polls (capped at 25 s)+and is the fallback when the callback is lost.++**Job status + pointers live in Redis** (`jobs.rs`): `asm:job:{jobId}` →+`{status, result, stats, …}`. Redis is required, so a restart, a sibling replica+or another Lambda invocation can answer a poll. It holds pointers, never artifact+bytes — with one exception below.++`GET /health` pings Redis (2 s limit) and answers 503 when it does not reply:+without Redis no job can be recorded or polled, so the instance is not healthy+and the container healthcheck / load balancer replaces it. The client+(`connect` in `jobs.rs`) bounds every connect (5 s) and reply (15 s) and+retries a lost connection with delays that double from 1 s to 5 s, so the+service is healthy again within seconds of Redis returning. The crate's+defaults wait forever and back off to a minute or two.++**Outputs go from memory to storage.** The service has no storage credentials.+When the submit carried a URL for every output, `finish()` PUTs them straight+from `Bytes` and stores nothing. Otherwise (no URLs at submit, or that upload+failed) the outputs are **parked** and the job stays `uploading` until a poll+brings fresh URLs (late-mint):++- on a standing service, as files under `<tmp>/asm-pending/<hash of job id>/`,+ memory-mapped for the upload and swept after the pending TTL;+- on Lambda, in Redis (`asm:pending:{jobId}`, same TTL), because the poll there+ is answered by a different invocation than the one that computed.++A parked job not drained within the TTL is abandoned (the caller resubmits).+Disk parking is per instance: with more than one standing replica a late-mint+poll must reach the replica that computed, so pass the URLs at submit. (Legacy:+a plan with no `planPath` returns the plan inline in the job record.)**Content-hash result cache** (`asm:result:{model}:{contentHash}:{optsHash}:v{CODE_VERSION}`-→ pointer, TTL `ASSEMBLER_RESULT_TTL_SECS`): a repeat of the same model + bytes +-options + code version reuses the prior plan's storage pointer, skipping the FCL-compute. `CODE_VERSION` (`cache.rs`, shared with the convert LRU) is the single-version lever — **bump it on any converter OR planner behavior change** to+→ pointer, 24 h): a repeat of the same model + bytes + options + code version+reuses the prior plan's storage pointer, skipping the FCL compute.+`CODE_VERSION` (`cache.rs`, shared with the convert cache) is the single version+lever — **bump it on any converter OR planner behavior change** toauto-invalidate every cache. `optsHash` includes `units`/`sequence`, so a freshregenerate that drops auto-swarm units misses automatically. `POST /cache/invalidate``{modelUploadId}` is the central explicit bust (called best-effort from the app's`invalidateAssemblyPlanCache`/`invalidateAssemblyModelCache`).-On SIGTERM/SIGINT the service stops accepting requests, drains in-flight converts-and plan jobs, then force-exits after `ASSEMBLER_SHUTDOWN_GRACE_S`.+On SIGTERM/SIGINT the service stops accepting requests, waits for the whole+memory budget to come back (every compute done), then force-exits after the+shutdown grace.++## Memory++Built to sit as a small always-on pod beside other workloads.++- **Admission is by memory** (`admission.rs`), not by core. The budget is the+ container's limit (`/sys/fs/cgroup/memory.max`, cgroup v1's+ `memory.limit_in_bytes`, else `/proc/meminfo`) less a 300 MB baseline. Each+ compute holds its estimate out of it: 8× the source bytes for convert,+ optimize, compact and thumbnail; for a plan, 10× the source until the model is+ read, then 8 MB per part (`plan_step_observed` reports the count). Jobs that+ fit run together; one that does not waits in arrival order; one estimated+ above the whole budget takes all of it and runs alone. Nothing is rejected.+ The reservation covers the compute only, not the download or the upload. CPU+ is bounded separately by the blocking pool (cores + 2).+- **The estimate is not a limit.** Nothing stops a job from using more than it+ was admitted for, and geometry can be far heavier than its file size: a+ 5 MB plate with 1,200 drilled holes still peaks at 840 MB, thirteen times its+ estimate. Such a job can still get the pod OOM-killed.+- **Flat faces with many holes are meshed lean** (`mesh()` in+ `crates/occt-bridge/src/occt.cc`). BRepMesh's default algorithm for a plane+ runs an interior-node pass whose memory grows with the square of the hole+ count; that 1,200-hole plate peaked at 6.2 GB. A part with more than 64 wires+ on one face is meshed with that pass off for planes only: 840 MB, and faster.+ The vertices are the same, so graph.json, nodeIds and geometry hashes do not+ change; the triangle wiring in the GLB can (co-circular ties on a regular hole+ pattern), and with it the contact-derived details of a plan for parts that+ touch such a face (one `needsSupport` flag flipped on a test assembly; the+ sequence, motions and contact graph did not). That is why parts under the+ threshold keep the default path and stay byte-identical. `ASSEMBLER_LEAN_PLANES=0` turns it off. OCCT's other+ mesher (Delabella) is not an answer: lean on memory, but minutes on the same+ plates.+- **The allocator** on Linux is jemalloc for the whole process (unprefixed, so+ OCCT and FCL use it too) with a background thread that returns freed pages+ after a second (`malloc_conf` in `main.rs`). `MALLOC_CONF=stats_print:true`+ prints its settings at exit.+- **The convert result cache** is files under `<tmp>/asm-cache` (2 GiB LRU, off+ on Lambda), memory-mapped when a hit is served and cleared at startup.+- **`<tmp>` must be real disk** with room for the cache, parked outputs and+ downloaded sources. A memory-backed `emptyDir` would charge all of it to the+ pod's memory limit. The server clears downloaded sources (`geometry-*`) left+ by an earlier process when it starts: a killed container skips its own+ cleanup and the volume outlives the restart.## Not yet donediff --git a/apps/assembler/Cargo.toml b/apps/assembler/Cargo.tomlindex 382b74efe9..04d0f02e73 100644--- a/apps/assembler/Cargo.toml+++ b/apps/assembler/Cargo.toml@@ -40,4 +40,8 @@ file-format = "0.26"tempfile = "3"[target.'cfg(target_os = "linux")'.dependencies]-tikv-jemallocator = "0.6"+# Unprefixed: jemalloc is `malloc` for the whole process, so OCCT and FCL (C++,+# which allocate through malloc) use it too and their freed memory is returned+# to the OS. Prefixed, it served Rust only and the C++ side stayed on glibc,+# whose arenas keep an idle service near its last job's peak.+tikv-jemallocator = { version = "0.6", features = ["unprefixed_malloc_on_supported_platforms", "background_threads"] }diff --git a/apps/assembler/src/actions/compact.rs b/apps/assembler/src/actions/compact.rsindex 64cdf2e6ab..c1e659878d 100644--- a/apps/assembler/src/actions/compact.rs+++ b/apps/assembler/src/actions/compact.rs@@ -18,9 +18,8 @@//! re-running compact on an already-compacted model is a no-op-safe passthrough.use crate::jobs::{Done, Output};-use crate::{http, AppState};+use crate::{admission, http, AppState};use serde_json::json;-use std::sync::Arc;use std::time::Instant;#[derive(Clone, Copy, PartialEq, Eq)]@@ -55,10 +54,9 @@ const ZSTD_LEVEL: i32 = 12;pub fn spawn(state: &AppState, job_id: &str, req: CompactReq) {let jobs = state.jobs.clone();- let slots = Arc::clone(&state.slots);+ let admission = state.admission.clone();let job_id = job_id.to_string();tokio::spawn(async move {- let _permit = slots.acquire().await;if jobs.is_canceled(&job_id).await {return;}@@ -77,7 +75,12 @@ pub fn spawn(state: &AppState, job_id: &str, req: CompactReq) {let mode = req.mode;let level = ZSTD_LEVEL;- let res = tokio::task::spawn_blocking(move || compress(&src_str, mode, level)).await;+ let res = {+ let _grant = admission+ .acquire(admission::estimate_mb(http::file_len(&src).await))+ .await;+ tokio::task::spawn_blocking(move || compress(&src_str, mode, level)).await+ };let _ = tokio::fs::remove_file(&src).await;let out = match res {@@ -117,7 +120,7 @@ pub fn spawn(state: &AppState, job_id: &str, req: CompactReq) {let outputs = vec![Output {name: "raw".into(),content_type: "application/zstd".into(),- bytes: out.bytes,+ bytes: out.bytes.into(),}];jobs.finish(&job_id, outputs, done, None).await;});diff --git a/apps/assembler/src/actions/convert.rs b/apps/assembler/src/actions/convert.rsindex 56680618e6..7d327956c0 100644--- a/apps/assembler/src/actions/convert.rs+++ b/apps/assembler/src/actions/convert.rs@@ -9,7 +9,7 @@use crate::cache::{CachedConvert, ResultCache};use crate::jobs::{Done, Output};-use crate::{config, http, progress, AppState};+use crate::{admission, config, http, progress, AppState};use serde_json::json;use std::sync::Arc;use std::time::Instant;@@ -33,10 +33,9 @@ pub fn spawn(state: &AppState, job_id: &str, req: ConvertReq) {let jobs = state.jobs.clone();let cache = Arc::clone(&state.cache);let progress_store = state.progress.clone();- let slots = Arc::clone(&state.slots);+ let admission = state.admission.clone();let job_id = job_id.to_string();tokio::spawn(async move {- let _permit = slots.acquire().await;if jobs.is_canceled(&job_id).await {return;}@@ -78,6 +77,11 @@ pub fn spawn(state: &AppState, job_id: &str, req: ConvertReq) {entry}None => {+ // Held for the tessellation only: the download before it streams+ // to disk and the upload after it holds just the outputs.+ let _grant = admission+ .acquire(admission::estimate_mb(http::file_len(&tmp).await))+ .await;let tmp_str = tmp.to_string_lossy().to_string();let cache_ins = Arc::clone(&cache);let (lin, ang, optimize) = (req.lin, req.ang, req.optimize);@@ -88,9 +92,15 @@ pub fn spawn(state: &AppState, job_id: &str, req: ConvertReq) {if converter::convert::is_xbf(&tmp_str) {converter::convert::convert_xbf(&tmp_str, lin, ang)} else {- // Unit detection scans at most the first 32MB of STEP text.- let text = read_head_lossy(&tmp_str, 32 * 1024 * 1024)?;- converter::convert::convert_step(&tmp_str, &text, lin, ang)+ // Unit detection scans the head of the mapped file — no+ // decoded copy of it.+ let head = http::map_file(std::path::Path::new(&tmp_str)).map_err(|e| {+ converter::convert::ConvertError::new(+ "READ_FAILED",+ format!("read temp: {e}"),+ )+ })?;+ converter::convert::convert_step_head(&tmp_str, &head, lin, ang)}.map(|conv| {let glb = if optimize {@@ -98,15 +108,16 @@ pub fn spawn(state: &AppState, job_id: &str, req: ConvertReq) {} else {conv.glb};- let entry = Arc::new(CachedConvert {- glb: glb.into(),- graph_bytes: serde_json::to_vec(&conv.graph).unwrap().into(),- component_count: conv.component_count,- triangles: conv.triangles,- unit: conv.graph["unit"].clone(),- });- cache_ins.insert(key, Arc::clone(&entry));- entry+ cache_ins.insert(+ key,+ CachedConvert {+ glb: glb.into(),+ graph_bytes: serde_json::to_vec(&conv.graph).unwrap().into(),+ component_count: conv.component_count,+ triangles: conv.triangles,+ unit: conv.graph["unit"].clone(),+ },+ )})}).await;@@ -180,12 +191,12 @@ async fn complete(Output {name: "glb".into(),content_type: "model/gltf-binary".into(),- bytes: entry.glb.to_vec(),+ bytes: entry.glb.clone(),},Output {name: "graph".into(),content_type: "application/json".into(),- bytes: entry.graph_bytes.to_vec(),+ bytes: entry.graph_bytes.clone(),},];// Convert output paths are job-scoped, so no result-pointer cache (the bytes@@ -215,19 +226,6 @@ fn optimize_glb(glb: Vec<u8>) -> Vec<u8> {}}-/// Read at most `cap` bytes from the head of a file, lossy-decoded.-fn read_head_lossy(path: &str, cap: usize) -> Result<String, converter::convert::ConvertError> {- use std::io::Read;- let file = std::fs::File::open(path).map_err(|e| {- converter::convert::ConvertError::new("READ_FAILED", format!("read temp: {e}"))- })?;- let mut buf = Vec::new();- file.take(cap as u64).read_to_end(&mut buf).map_err(|e| {- converter::convert::ConvertError::new("READ_FAILED", format!("read temp: {e}"))- })?;- Ok(String::from_utf8_lossy(&buf).into_owned())-}-fn convert_code(e: &converter::convert::ConvertError) -> &'static str {match e.code.as_str() {"READ_FAILED" => "READ_FAILED",diff --git a/apps/assembler/src/actions/optimize.rs b/apps/assembler/src/actions/optimize.rsindex 5b464cb949..6e099e9e0d 100644--- a/apps/assembler/src/actions/optimize.rs+++ b/apps/assembler/src/actions/optimize.rs@@ -14,9 +14,8 @@use crate::formats::{self, Format};use crate::jobs::{Done, Output};-use crate::{http, AppState};+use crate::{admission, http, AppState};use serde_json::json;-use std::sync::Arc;use std::time::{Duration, Instant};pub struct OptimizeReq {@@ -86,10 +85,9 @@ impl ActionErr {pub fn spawn(state: &AppState, job_id: &str, req: OptimizeReq) {let jobs = state.jobs.clone();- let slots = Arc::clone(&state.slots);+ let admission = state.admission.clone();let job_id = job_id.to_string();tokio::spawn(async move {- let _permit = slots.acquire().await;if jobs.is_canceled(&job_id).await {return;}@@ -114,10 +112,15 @@ pub fn spawn(state: &AppState, job_id: &str, req: OptimizeReq) {// Charge the download + tessellation already spent against the budget.opts.deadline = opts.budget.map(|b| started + b);- let res = tokio::task::spawn_blocking(move || {- run_optimize(&tmp_str, &declared, ext.as_deref(), &opts)- })- .await;+ let res = {+ let _grant = admission+ .acquire(admission::estimate_mb(http::file_len(&tmp).await))+ .await;+ tokio::task::spawn_blocking(move || {+ run_optimize(&tmp_str, &declared, ext.as_deref(), &opts)+ })+ .await+ };let _ = tokio::fs::remove_file(&tmp).await;let outcome = match res {@@ -173,7 +176,7 @@ pub fn spawn(state: &AppState, job_id: &str, req: OptimizeReq) {let outputs = vec![Output {name: "glb".into(),content_type: "model/gltf-binary".into(),- bytes: outcome.glb,+ bytes: outcome.glb.into(),}];jobs.finish(&job_id, outputs, done, None).await;});@@ -484,8 +487,7 @@ fn run_optimize(fn load_source(path: &str, format: Format, head: &[u8], opts: &Opts) -> Result<Src, ActionErr> {match format {Format::Step => {- let text = String::from_utf8_lossy(head).into_owned();- let glb = converter::convert::convert_step(path, &text, opts.lin, opts.ang)+ let glb = converter::convert::convert_step_head(path, head, opts.lin, opts.ang).map_err(|e| ActionErr::new("tessellation_failed", e.message))?.glb;Ok(Src::Owned(glb))diff --git a/apps/assembler/src/actions/plan.rs b/apps/assembler/src/actions/plan.rsindex 53f57d4601..1de95efc6f 100644--- a/apps/assembler/src/actions/plan.rs+++ b/apps/assembler/src/actions/plan.rs@@ -7,10 +7,9 @@//! late-mint uploaded (a `planPath` was given) or returned inline in the result.use crate::jobs::{opts_hash, Done, Output};-use crate::{config, http, AppState};+use crate::{admission, config, http, AppState};use planner::steps::PlanUnit;use serde_json::{json, Value};-use std::sync::Arc;use std::time::Instant;/// Everything a plan task needs from the request.@@ -26,10 +25,9 @@ pub struct PlanReq {pub fn spawn(state: &AppState, job_id: &str, req: PlanReq) {let jobs = state.jobs.clone();- let slots = Arc::clone(&state.slots);+ let admission = state.admission.clone();let job_id = job_id.to_string();tokio::spawn(async move {- let _permit = slots.acquire().await;if jobs.is_canceled(&job_id).await {return;}@@ -67,8 +65,16 @@ pub fn spawn(state: &AppState, job_id: &str, req: PlanReq) {parse_options(&req.options);let mp = config::max_parts();+ // Sized by the source until the model is read, then by its part count:+ // the sweeps, not the read, are where a plan's memory goes.+ let source_bytes = http::file_len(&tmp).await;+ let grant = admission+ .acquire(admission::plan_estimate_mb(source_bytes, None))+ .await;+ let runtime = tokio::runtime::Handle::current();let res = tokio::task::spawn_blocking(move || {- planner::steps::plan_step(+ let grant = std::sync::Mutex::new(grant);+ planner::steps::plan_step_observed(&tmp_str,lin,ang,@@ -78,6 +84,11 @@ pub fn spawn(state: &AppState, job_id: &str, req: PlanReq) {units,sequence,tolerance,+ &|parts| {+ let estimate = admission::plan_estimate_mb(source_bytes, Some(parts));+ let mut grant = grant.lock().unwrap_or_else(|e| e.into_inner());+ runtime.block_on(grant.resize(estimate));+ },)}).await;@@ -129,7 +140,7 @@ pub fn spawn(state: &AppState, job_id: &str, req: PlanReq) {let outputs = vec![Output {name: "plan".into(),content_type: "application/json".into(),- bytes,+ bytes: bytes.into(),}];jobs.finish(&job_id, outputs, done, cache).await;}diff --git a/apps/assembler/src/actions/thumbnail.rs b/apps/assembler/src/actions/thumbnail.rsindex 6059b6ee14..21996919bf 100644--- a/apps/assembler/src/actions/thumbnail.rs+++ b/apps/assembler/src/actions/thumbnail.rs@@ -9,9 +9,8 @@//! uploaded.use crate::jobs::{Done, Output};-use crate::{http, AppState};+use crate::{admission, http, AppState};use serde_json::json;-use std::sync::Arc;use std::time::Instant;pub struct ThumbnailReq {@@ -25,10 +24,9 @@ pub struct ThumbnailReq {pub fn spawn(state: &AppState, job_id: &str, req: ThumbnailReq) {let jobs = state.jobs.clone();- let slots = Arc::clone(&state.slots);+ let admission = state.admission.clone();let job_id = job_id.to_string();tokio::spawn(async move {- let _permit = slots.acquire().await;if jobs.is_canceled(&job_id).await {return;}@@ -46,7 +44,12 @@ pub fn spawn(state: &AppState, job_id: &str, req: ThumbnailReq) {let src_str = src.to_string_lossy().to_string();let size = req.size;- let res = tokio::task::spawn_blocking(move || render(&src_str, size)).await;+ let res = {+ let _grant = admission+ .acquire(admission::estimate_mb(http::file_len(&src).await))+ .await;+ tokio::task::spawn_blocking(move || render(&src_str, size)).await+ };let _ = tokio::fs::remove_file(&src).await;let png = match res {@@ -82,7 +85,7 @@ pub fn spawn(state: &AppState, job_id: &str, req: ThumbnailReq) {let outputs = vec![Output {name: "thumbnail".into(),content_type: "image/png".into(),- bytes: png,+ bytes: png.into(),}];jobs.finish(&job_id, outputs, done, None).await;});diff --git a/apps/assembler/src/admission.rs b/apps/assembler/src/admission.rsnew file mode 100644index 0000000000..0b8915fc10--- /dev/null+++ b/apps/assembler/src/admission.rs@@ -0,0 +1,279 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++//! Admission by memory. A job's peak is set by its model, not by a core: a+//! convert peaks near 8× its source, a plan near 8 MB per part. One slot per+//! core therefore admits a second multi-gigabyte plan into a pod that has room+//! for one, and the kernel kills the pod. Here every compute holds its+//! estimated megabytes out of a budget read from the container's memory limit,+//! so jobs that fit run together and one that does not waits.+//!+//! Nothing is rejected: a job estimated above the whole budget takes the whole+//! budget and runs alone. CPU is bounded separately by the blocking pool.++use std::sync::Arc;+use tokio::sync::{OwnedSemaphorePermit, Semaphore};++const MB: u64 = 1024 * 1024;+/// What the idle service holds (runtime, OCCT/FCL statics, HTTP), kept out of+/// the budget.+const BASELINE_MB: u64 = 300;+/// Smallest budget, so a tiny or unreadable limit still admits one job.+const MIN_BUDGET_MB: u64 = 256;+/// Smallest estimate: a kilobyte-sized source still costs a tessellation.+const MIN_ESTIMATE_MB: u64 = 64;+/// Peak memory of a convert, optimize, xbf compaction or render, per byte of source.+const SOURCE_FACTOR: u64 = 8;+/// A plan before its part count is known, per byte of source.+const PLAN_SOURCE_FACTOR: u64 = 10;+const PLAN_MB_PER_PART: u64 = 8;++#[derive(Clone)]+pub struct Admission {+ semaphore: Arc<Semaphore>,+ budget_mb: u32,+}++/// The megabytes one running job holds. Dropping it returns them.+pub struct Grant {+ admission: Admission,+ permit: Option<OwnedSemaphorePermit>,+}++impl Admission {+ pub fn from_env() -> Self {+ Self::with_budget_mb(budget_mb(memory_limit_bytes()))+ }++ pub fn with_budget_mb(budget_mb: u64) -> Self {+ let budget_mb = budget_mb.clamp(1, u32::MAX as u64) as u32;+ Admission {+ semaphore: Arc::new(Semaphore::new(budget_mb as usize)),+ budget_mb,+ }+ }++ pub fn budget_mb(&self) -> u32 {+ self.budget_mb+ }++ fn clamp(&self, estimate_mb: u64) -> u32 {+ estimate_mb.clamp(1, self.budget_mb as u64) as u32+ }++ /// Wait until `estimate_mb` (capped at the whole budget) is free. Waiters+ /// are served in order, so a large job is not starved by small ones.+ pub async fn acquire(&self, estimate_mb: u64) -> Grant {+ let want = self.clamp(estimate_mb);+ if self.semaphore.available_permits() < want as usize {+ eprintln!(+ "assembler: a job is waiting for {want} MB of the {} MB memory budget",+ self.budget_mb+ );+ }+ let permit = Arc::clone(&self.semaphore)+ .acquire_many_owned(want)+ .await+ .expect("admission semaphore is never closed");+ Grant {+ admission: self.clone(),+ permit: Some(permit),+ }+ }++ /// Wait for every running job to finish (shutdown drain).+ pub async fn drain(&self) {+ let _ = self.semaphore.acquire_many(self.budget_mb).await;+ }+}++impl Grant {+ pub fn held_mb(&self) -> u32 {+ self.permit.as_ref().map_or(0, |p| p.num_permits() as u32)+ }++ /// Re-weight a running job once a better estimate is known (a plan's part+ /// count). Shrinking frees the difference at once. Growing takes the+ /// difference if it is free; if not, the job gives back what it holds and+ /// queues for the whole amount — it never waits while holding, so two+ /// growing jobs cannot deadlock each other. During that wait the memory it+ /// already uses is uncounted, bounded by its first estimate.+ pub async fn resize(&mut self, estimate_mb: u64) {+ let target = self.admission.clamp(estimate_mb);+ let held = self.held_mb();+ if target == held {+ return;+ }+ if let Some(permit) = self.permit.as_mut() {+ if target < held {+ drop(permit.split((held - target) as usize));+ return;+ }+ let semaphore = Arc::clone(&self.admission.semaphore);+ if let Ok(extra) = semaphore.try_acquire_many_owned(target - held) {+ permit.merge(extra);+ return;+ }+ }+ self.permit = None;+ self.permit = self.admission.acquire(target as u64).await.permit.take();+ }+}++/// Megabytes a job is expected to peak at, from its source size.+pub fn estimate_mb(source_bytes: u64) -> u64 {+ (source_bytes.saturating_mul(SOURCE_FACTOR) / MB).max(MIN_ESTIMATE_MB)+}++/// A plan's estimate: by part count once known, by source size before.+pub fn plan_estimate_mb(source_bytes: u64, parts: Option<usize>) -> u64 {+ match parts {+ Some(parts) => (parts as u64).saturating_mul(PLAN_MB_PER_PART),+ None => source_bytes.saturating_mul(PLAN_SOURCE_FACTOR) / MB,+ }+ .max(MIN_ESTIMATE_MB)+}++fn budget_mb(limit_bytes: Option<u64>) -> u64 {+ // Unknown limit (not Linux, nothing readable): assume a small machine+ // rather than an unbounded one.+ let limit_mb = limit_bytes.map_or(8 * 1024, |bytes| bytes / MB);+ limit_mb.saturating_sub(BASELINE_MB).max(MIN_BUDGET_MB)+}++/// The container's memory limit, else the machine's memory.+fn memory_limit_bytes() -> Option<u64> {+ let read = |path: &str| std::fs::read_to_string(path).ok();+ let physical = read("/proc/meminfo").and_then(|s| parse_meminfo_total(&s));+ let cgroup = read("/sys/fs/cgroup/memory.max") // cgroup v2+ .or_else(|| read("/sys/fs/cgroup/memory/memory.limit_in_bytes")) // v1+ .and_then(|s| parse_cgroup_limit(&s));+ match (cgroup, physical) {+ // cgroup v1 reports "no limit" as a huge number, not a word.+ (Some(cgroup), Some(physical)) => Some(cgroup.min(physical)),+ (cgroup, physical) => cgroup.or(physical),+ }+}++fn parse_cgroup_limit(contents: &str) -> Option<u64> {+ contents.trim().parse().ok() // "max" (unlimited) does not parse+}++fn parse_meminfo_total(contents: &str) -> Option<u64> {+ let line = contents.lines().find(|l| l.starts_with("MemTotal:"))?;+ let kb: u64 = line.split_whitespace().nth(1)?.parse().ok()?;+ Some(kb * 1024)+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::time::Duration;++ #[test]+ fn the_budget_is_the_limit_less_the_baseline() {+ assert_eq!(budget_mb(Some(6 * 1024 * MB)), 6 * 1024 - BASELINE_MB);+ assert_eq!(budget_mb(Some(100 * MB)), MIN_BUDGET_MB);+ assert_eq!(budget_mb(None), 8 * 1024 - BASELINE_MB);+ }++ #[test]+ fn limits_parse_from_the_cgroup_and_meminfo_formats() {+ assert_eq!(parse_cgroup_limit("6442450944\n"), Some(6 * 1024 * MB));+ assert_eq!(parse_cgroup_limit("max\n"), None);+ let meminfo = "MemTotal: 16384000 kB\nMemFree: 1000 kB\n";+ assert_eq!(parse_meminfo_total(meminfo), Some(16_384_000 * 1024));+ }++ #[test]+ fn estimates_follow_the_measured_peaks() {+ assert_eq!(estimate_mb(83 * MB), 664); // measured 665 MB+ assert_eq!(estimate_mb(4 * 1024), MIN_ESTIMATE_MB);+ assert_eq!(plan_estimate_mb(80 * MB, None), 800);+ assert_eq!(plan_estimate_mb(80 * MB, Some(518)), 4144); // measured 4.1 GB+ }++ #[tokio::test]+ async fn jobs_that_fit_run_together_and_the_next_one_waits() {+ let admission = Admission::with_budget_mb(1000);+ let a = admission.acquire(400).await;+ let _b = admission.acquire(400).await;++ let waiting = tokio::spawn({+ let admission = admission.clone();+ async move { admission.acquire(400).await }+ });+ tokio::time::sleep(Duration::from_millis(20)).await;+ assert!(!waiting.is_finished());++ drop(a);+ assert_eq!(waiting.await.unwrap().held_mb(), 400);+ }++ #[tokio::test]+ async fn a_job_larger_than_the_budget_runs_alone_and_is_never_refused() {+ let admission = Admission::with_budget_mb(1000);+ let small = admission.acquire(100).await;+ let big = tokio::spawn({+ let admission = admission.clone();+ async move { admission.acquire(50_000).await }+ });+ tokio::time::sleep(Duration::from_millis(20)).await;+ assert!(!big.is_finished());++ drop(small);+ assert_eq!(big.await.unwrap().held_mb(), 1000);+ }++ #[tokio::test]+ async fn resizing_shrinks_at_once_and_grows_into_free_room() {+ let admission = Admission::with_budget_mb(1000);+ let mut grant = admission.acquire(800).await;+ grant.resize(200).await;+ assert_eq!(grant.held_mb(), 200);+ assert_eq!(admission.semaphore.available_permits(), 800);++ grant.resize(900).await;+ assert_eq!(grant.held_mb(), 900);+ assert_eq!(admission.semaphore.available_permits(), 100);+ }++ #[tokio::test]+ async fn two_jobs_growing_at_once_do_not_deadlock() {+ let admission = Admission::with_budget_mb(1000);+ let grow = |admission: Admission| async move {+ let mut grant = admission.acquire(400).await;+ tokio::time::sleep(Duration::from_millis(10)).await;+ grant.resize(900).await; // neither can grow while the other holds 400+ assert_eq!(grant.held_mb(), 900);+ tokio::time::sleep(Duration::from_millis(10)).await;+ };+ let both = async {+ tokio::join!(+ tokio::spawn(grow(admission.clone())),+ tokio::spawn(grow(admission.clone()))+ )+ };+ let (a, b) = tokio::time::timeout(Duration::from_secs(5), both)+ .await+ .expect("both jobs finish");+ a.unwrap();+ b.unwrap();+ assert_eq!(admission.semaphore.available_permits(), 1000);+ }++ #[tokio::test]+ async fn drain_waits_for_running_jobs() {+ let admission = Admission::with_budget_mb(500);+ let grant = admission.acquire(100).await;+ let drained = tokio::spawn({+ let admission = admission.clone();+ async move { admission.drain().await }+ });+ tokio::time::sleep(Duration::from_millis(20)).await;+ assert!(!drained.is_finished());+ drop(grant);+ drained.await.unwrap();+ }+}diff --git a/apps/assembler/src/cache.rs b/apps/assembler/src/cache.rsindex 6e6fe9beb9..54230df431 100644--- a/apps/assembler/src/cache.rs+++ b/apps/assembler/src/cache.rs@@ -8,13 +8,19 @@//! entirely and just re-uploads the cached GLB/graph. This is the throughput//! lever for the real workload — distinct models are still core-bound, but//! repeated ones become near-free.+//!+//! The entries are files, memory-mapped when served: the page cache holds them,+//! the kernel can drop them under pressure, and the process's own memory stays+//! flat however much is cached. (Held on the heap, half a gigabyte of GLBs sat+//! in a small pod for as long as it ran.)use bytes::Bytes;use lru::LruCache;+use std::path::{Path, PathBuf};use std::sync::{Arc, Mutex};-/// Single version lever for ALL cached geometry results — the in-process convert-/// LRU (below) AND the Redis job/result-pointer store (`store.rs`). Bump on ANY+/// Single version lever for ALL cached geometry results — the convert cache+/// (below) AND the Redis job/result-pointer store (`jobs.rs`). Bump on ANY/// converter OR planner behavior change so every stale entry, in every cache,/// auto-misses. This is the "content-hash key + CODE_VERSION" auto-invalidation.// v3: geometry_hash recipe changed to position-only (nodeIds renamed globally).@@ -29,27 +35,37 @@ pub struct CachedConvert {}impl CachedConvert {- fn size(&self) -> usize {- self.glb.len() + self.graph_bytes.len()+ fn size(&self) -> u64 {+ (self.glb.len() + self.graph_bytes.len()) as u64}}struct Inner {- lru: LruCache<String, Arc<CachedConvert>>,- bytes: usize,+ /// Key → the bytes its files take.+ lru: LruCache<String, u64>,+ bytes: u64,}-/// Byte-bounded LRU. A single mutex is fine here: the hit path is upload-bound-/// (ms), the lock is held for a map op (ns), and it's only ever taken from-/// sync/blocking contexts — never across an await.+/// Byte-bounded LRU of files under `dir`. A single mutex is fine here: it+/// guards the index only (a map op), never the file I/O.pub struct ResultCache {+ dir: PathBuf,inner: Mutex<Inner>,- budget: usize,+ budget: u64,}impl ResultCache {- pub fn new(budget_bytes: usize) -> Self {+ /// An empty cache in `dir`. Whatever a previous process left there is+ /// removed: its index is gone, so nothing could ever evict those files.+ pub fn new(dir: PathBuf, budget_bytes: u64) -> Self {+ let _ = std::fs::remove_dir_all(&dir);+ if budget_bytes > 0 {+ if let Err(e) = std::fs::create_dir_all(&dir) {+ eprintln!("assembler: convert cache disabled ({}: {e})", dir.display());+ }+ }ResultCache {+ dir,inner: Mutex::new(Inner {lru: LruCache::unbounded(),bytes: 0,@@ -73,26 +89,204 @@ impl ResultCache {format!("ch:{content_hash}:{lin}:{ang}:v{CODE_VERSION}")}+ /// A key's file stem. Keys carry a caller-declared hash, so the name is a+ /// hash of the key, never the key.+ fn path(&self, key: &str, extension: &str) -> PathBuf {+ let name = xxhash_rust::xxh3::xxh3_128(key.as_bytes());+ self.dir.join(format!("{name:032x}.{extension}"))+ }+pub fn get(&self, key: &str) -> Option<Arc<CachedConvert>> {// LruCache::get bumps recency.- self.inner.lock().unwrap().lru.get(key).map(Arc::clone)+ self.inner.lock().unwrap().lru.get(key)?;+ let entry = self.read(key);+ if entry.is_none() {+ // The files are gone or unreadable: forget the key.+ self.forget(key);+ }+ entry.map(Arc::new)}- pub fn insert(&self, key: String, value: Arc<CachedConvert>) {- if self.budget == 0 {- return;- }+ fn read(&self, key: &str) -> Option<CachedConvert> {+ let meta = std::fs::read(self.path(key, "json")).ok()?;+ let meta: serde_json::Value = serde_json::from_slice(&meta).ok()?;+ Some(CachedConvert {+ glb: crate::http::map_file(&self.path(key, "glb")).ok()?,+ graph_bytes: crate::http::map_file(&self.path(key, "graph")).ok()?,+ component_count: meta["componentCount"].as_i64()?,+ triangles: meta["triangles"].as_i64()?,+ unit: meta["unit"].clone(),+ })+ }++ /// Store a fresh result and hand it back backed by its files, so the heap+ /// copy dies with this call. When it cannot be stored (cache off, entry+ /// larger than the budget, disk full) the result is returned as it came.+ pub fn insert(&self, key: String, value: CachedConvert) -> Arc<CachedConvert> {let size = value.size();- let mut inner = self.inner.lock().unwrap();- if let Some((_, old)) = inner.lru.push(key, value) {- inner.bytes = inner.bytes.saturating_sub(old.size());+ if self.budget == 0 || size > self.budget {+ return Arc::new(value);}- inner.bytes += size;- while inner.bytes > self.budget {- match inner.lru.pop_lru() {- Some((_, v)) => inner.bytes = inner.bytes.saturating_sub(v.size()),- None => break,+ let stored = self.write(&key, &value).and_then(|()| {+ self.read(&key)+ .ok_or_else(|| std::io::Error::other("could not read the entry back"))+ });+ let entry = match stored {+ Ok(entry) => entry,+ Err(e) => {+ eprintln!("assembler: convert result not cached: {e}");+ self.remove_files(&key);+ return Arc::new(value);+ }+ };++ let mut evicted = Vec::new();+ {+ let mut inner = self.inner.lock().unwrap();+ if let Some((_, old)) = inner.lru.push(key, size) {+ inner.bytes = inner.bytes.saturating_sub(old);+ }+ inner.bytes += size;+ while inner.bytes > self.budget {+ match inner.lru.pop_lru() {+ Some((key, size)) => {+ inner.bytes = inner.bytes.saturating_sub(size);+ evicted.push(key);+ }+ None => break,+ }}}+ // An entry still being uploaded keeps its mapping: unlinking a mapped+ // file only frees the disk once the last map is dropped.+ for key in evicted {+ self.remove_files(&key);+ }+ Arc::new(entry)+ }++ fn write(&self, key: &str, value: &CachedConvert) -> std::io::Result<()> {+ let meta = serde_json::json!({+ "componentCount": value.component_count,+ "triangles": value.triangles,+ "unit": value.unit,+ });+ // Each file lands under its final name by rename, so a concurrent reader+ // of the same key sees a whole file or none.+ for (extension, bytes) in [+ ("glb", &value.glb[..]),+ ("graph", &value.graph_bytes[..]),+ ("json", meta.to_string().as_bytes()),+ ] {+ let path = self.path(key, extension);+ let tmp = unique_tmp(&path);+ std::fs::write(&tmp, bytes)?;+ std::fs::rename(&tmp, &path)?;+ }+ Ok(())+ }++ fn forget(&self, key: &str) {+ let mut inner = self.inner.lock().unwrap();+ if let Some(size) = inner.lru.pop(key) {+ inner.bytes = inner.bytes.saturating_sub(size);+ }+ drop(inner);+ self.remove_files(key);+ }++ fn remove_files(&self, key: &str) {+ for extension in ["glb", "graph", "json"] {+ let _ = std::fs::remove_file(self.path(key, extension));+ }+ }+}++fn unique_tmp(path: &Path) -> PathBuf {+ static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);+ let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);+ path.with_extension(format!("tmp{n}"))+}++#[cfg(test)]+mod tests {+ use super::*;++ fn entry(glb: &[u8], graph: &[u8]) -> CachedConvert {+ CachedConvert {+ glb: Bytes::copy_from_slice(glb),+ graph_bytes: Bytes::copy_from_slice(graph),+ component_count: 3,+ triangles: 12,+ unit: serde_json::json!({ "name": "mm" }),+ }+ }++ fn cache(budget: u64) -> (tempfile::TempDir, ResultCache) {+ let dir = tempfile::tempdir().unwrap();+ let cache = ResultCache::new(dir.path().join("cache"), budget);+ (dir, cache)+ }++ #[test]+ fn a_stored_result_is_served_back_from_its_files() {+ let (_dir, cache) = cache(1024);+ assert!(cache.get("k").is_none());++ let stored = cache.insert("k".into(), entry(b"glb-bytes", b"{\"graph\":1}"));+ assert_eq!(&stored.glb[..], b"glb-bytes");++ let hit = cache.get("k").unwrap();+ assert_eq!(&hit.glb[..], b"glb-bytes");+ assert_eq!(&hit.graph_bytes[..], b"{\"graph\":1}");+ assert_eq!((hit.component_count, hit.triangles), (3, 12));+ assert_eq!(hit.unit["name"], "mm");+ }++ #[test]+ fn the_least_recently_used_entry_goes_when_the_budget_is_passed() {+ let (dir, cache) = cache(25);+ cache.insert("a".into(), entry(b"0123456789", b""));+ cache.insert("b".into(), entry(b"0123456789", b""));+ cache.get("a").unwrap(); // a is now the more recent+ cache.insert("c".into(), entry(b"0123456789", b""));++ assert!(cache.get("b").is_none());+ assert!(cache.get("a").is_some() && cache.get("c").is_some());+ // Three files per entry, two entries left.+ let files = std::fs::read_dir(dir.path().join("cache")).unwrap().count();+ assert_eq!(files, 6);+ }++ #[test]+ fn an_evicted_entry_stays_readable_by_whoever_already_holds_it() {+ let (_dir, cache) = cache(10);+ let held = cache.insert("a".into(), entry(b"0123456789", b""));+ cache.insert("b".into(), entry(b"9876543210", b""));+ assert!(cache.get("a").is_none());+ assert_eq!(&held.glb[..], b"0123456789");+ }++ #[test]+ fn a_result_that_cannot_be_stored_is_still_returned() {+ let (_dir, off) = cache(0);+ assert_eq!(&off.insert("k".into(), entry(b"x", b"y")).glb[..], b"x");+ assert!(off.get("k").is_none());++ let (_dir, small) = cache(4);+ assert_eq!(&small.insert("k".into(), entry(b"too-large", b"")).glb[..], b"too-large");+ assert!(small.get("k").is_none());+ }++ #[test]+ fn files_from_a_previous_process_are_cleared_at_startup() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("cache");+ ResultCache::new(path.clone(), 1024).insert("k".into(), entry(b"x", b"y"));+ assert_eq!(std::fs::read_dir(&path).unwrap().count(), 3);++ let restarted = ResultCache::new(path.clone(), 1024);+ assert!(restarted.get("k").is_none());+ assert_eq!(std::fs::read_dir(&path).unwrap().count(), 0);}}diff --git a/apps/assembler/src/config.rs b/apps/assembler/src/config.rsindex 4b47ee1c17..bb77e87228 100644--- a/apps/assembler/src/config.rs+++ b/apps/assembler/src/config.rs@@ -28,19 +28,19 @@ pub fn shutdown_grace() -> std::time::Duration {std::time::Duration::from_secs(600)}-/// Result-cache budget.-pub fn cache_bytes() -> usize {- 512 * 1024 * 1024+/// Convert result-cache budget, on disk under [`cache_dir`]. Off on Lambda: a+/// worker invocation runs one job, and its /tmp is small and also holds the+/// downloaded source.+pub fn cache_bytes() -> u64 {+ if std::env::var("AWS_LAMBDA_FUNCTION_NAME").is_ok() {+ 0+ } else {+ 2 * 1024 * 1024 * 1024+ }}-/// Concurrent heavy jobs per instance — one per core, derived. Each job is-/// CPU-bound (rayon sweeps saturate cores), so more slots than cores just-/// thrashes; the semaphore also backs the 429-busy response and shutdown drain.-/// Lambda runs one job per worker invocation regardless.-pub fn max_concurrency() -> usize {- std::thread::available_parallelism()- .map(|n| n.get())- .unwrap_or(2)+pub fn cache_dir() -> std::path::PathBuf {+ std::env::temp_dir().join("asm-cache")}/// Wall-clock budget (seconds) for the optimize simplify ladder. When active, a@@ -85,17 +85,23 @@ pub fn pending_ttl_secs() -> u64 {300}+/// Where outputs wait on disk for a late-minted upload URL (see `jobs.rs`).+pub fn pending_dir() -> std::path::PathBuf {+ std::env::temp_dir().join("asm-pending")+}+/// Server-side cap on the `?wait=` long-poll hold (seconds). Kept under typical/// proxy/LB idle timeouts so a held request never trips them.pub fn max_long_poll_secs() -> u64 {25}-/// Cap on tokio's blocking pool — the implicit convert queue. OCCT scales to-/// ~core count; beyond that extra blocking threads just oversubscribe (c=64-/// measured: p99 7.2s uncapped). Excess spawn_blocking tasks queue inside the-/// pool, so overload degrades to waiting, never to 429s. +2 headroom keeps-/// tokio::fs ops from starving behind long converts.+/// Cap on tokio's blocking pool — the CPU half of admission (`admission.rs` is+/// the memory half). OCCT scales to ~core count; beyond that extra blocking+/// threads just oversubscribe (c=64 measured: p99 7.2s uncapped). Excess+/// spawn_blocking tasks queue inside the pool, so overload degrades to waiting,+/// never to 429s. +2 headroom keeps tokio::fs ops from starving behind long+/// converts.pub fn blocking_threads() -> usize {let cores = std::thread::available_parallelism().map_or(8, |n| n.get());(cores + 2).max(2)diff --git a/apps/assembler/src/http.rs b/apps/assembler/src/http.rsindex dd064e5c78..f4627c853e 100644--- a/apps/assembler/src/http.rs+++ b/apps/assembler/src/http.rs@@ -20,6 +20,25 @@ pub fn temp_path(ext: &str) -> PathBuf {std::env::temp_dir().join(format!("geometry-{}-{n}-{nanos}.{ext}", std::process::id()))}+/// Delete the sources an earlier process left behind. A killed process (an OOM+/// kill above all) skips its actions' own cleanup, and a pod's temp volume+/// outlives the container restart, so they would pile up. Only for the standing+/// server at startup, before it has a job of its own.+pub fn clear_stale_sources() {+ clear_sources_in(&std::env::temp_dir());+}++fn clear_sources_in(dir: &std::path::Path) {+ let Ok(entries) = std::fs::read_dir(dir) else {+ return;+ };+ for entry in entries.flatten() {+ if entry.file_name().to_string_lossy().starts_with("geometry-") {+ let _ = std::fs::remove_file(entry.path());+ }+ }+}+/// One shared client for the process: reuses connections (keep-alive/h2)/// instead of paying a fresh pool + TLS handshake per download/upload.fn client() -> &'static reqwest::Client {@@ -160,6 +179,24 @@ pub async fn download_hashed(Ok(hasher.digest128())}+/// A downloaded source's size, for the memory estimate. 0 if it cannot be read.+pub async fn file_len(path: &std::path::Path) -> u64 {+ tokio::fs::metadata(path).await.map_or(0, |m| m.len())+}++/// A file's bytes, memory-mapped: the page cache backs them, so uploading a+/// parked or cached artifact does not copy it onto the heap.+pub fn map_file(path: &std::path::Path) -> std::io::Result<bytes::Bytes> {+ let file = std::fs::File::open(path)?;+ if file.metadata()?.len() == 0 {+ return Ok(bytes::Bytes::new());+ }+ // SAFETY: these files are written once by this service and then only read+ // or unlinked; an unlinked file stays mapped until the map is dropped.+ let map = unsafe { memmap2::Mmap::map(&file) }?;+ Ok(bytes::Bytes::from_owner(map))+}+pub async fn upload(url: &str,body: impl Into<reqwest::Body>,@@ -212,3 +249,22 @@ pub async fn post_json(url: &str, body: &serde_json::Value) -> Result<(), ApiErr}Ok(())}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn stale_sources_are_cleared_and_nothing_else() {+ let dir = tempfile::tempdir().unwrap();+ let stale = dir.path().join("geometry-1-0-123.step");+ let other = dir.path().join("asm-cache");+ std::fs::write(&stale, b"x").unwrap();+ std::fs::create_dir(&other).unwrap();++ clear_sources_in(dir.path());++ assert!(!stale.exists());+ assert!(other.exists());+ }+}diff --git a/apps/assembler/src/jobs.rs b/apps/assembler/src/jobs.rsindex 90c641ac7d..0c28503caa 100644--- a/apps/assembler/src/jobs.rs+++ b/apps/assembler/src/jobs.rs@@ -14,15 +14,22 @@//! a silent in-memory fallback would strand cross-instance polls (Lambda//! dispatch depends on shared state) and hide the misconfiguration.//!-//! Artifacts are PUT to caller-signed URLs; only a `{result, stats}` POINTER is-//! stored — artifact bytes never enter Redis beyond the pending hand-off.--use crate::{cache::CODE_VERSION, config, http};+//! Artifacts are PUT to caller-signed URLs straight from memory when the submit+//! carried the URLs; only a `{result, stats}` POINTER is stored. Outputs that+//! could not be uploaded yet (no URL at submit, or the upload failed) are parked+//! for a late-mint poll: as files under the temp dir on a standing service, so+//! a large model never lands in a Redis the apps share, or in Redis on Lambda,+//! where the poll is answered by a different invocation than the one that+//! computed.++use crate::{cache::CODE_VERSION, config, dispatch, http};+use bytes::Bytes;use dashmap::DashMap;use redis::AsyncCommands;use serde::{Deserialize, Serialize};use serde_json::{json, Value};use std::collections::HashMap;+use std::path::PathBuf;use std::sync::Arc;use std::time::{Duration, Instant};use tokio::sync::Notify;@@ -53,12 +60,13 @@ struct JobRecord {callback_url: Option<String>,}-/// One artifact awaiting a late-minted upload URL (name → bytes + content type).+/// One artifact to upload (name → bytes + content type). `Bytes`, so handing it+/// to an upload or a retry is a refcount, never a copy.#[derive(Clone)]pub struct Output {pub name: String,pub content_type: String,- pub bytes: Vec<u8>,+ pub bytes: Bytes,}/// The terminal pointer to publish once every output is uploaded.@@ -68,16 +76,62 @@ pub struct Done {pub stats: Value,}+/// A parked job: its outputs, terminal pointer, and result-cache key.+type Parked = (Vec<Output>, Done, Option<(String, u128, u64)>);+/// Shared job + content-hash result store. Cloned into every handler via/// `AppState`; inner state is `Arc`/manager-cloned so clones share one store.-/// Computed-but-unuploaded artifacts (the late-mint hand-off) live in Redis-/// under a short TTL so ANY replica's/invocation's poll can drain them.#[derive(Clone)]pub struct JobStore {conn: redis::aio::ConnectionManager,+ /// Where outputs wait for a late-minted URL: this directory, or Redis when+ /// `None` (Lambda — see the module doc).+ park_dir: Option<PathBuf>,/// Per-job in-process wakeups so a same-replica long-poll returns the instant/// the worker finishes (cross-replica completion caught by the Redis re-check).- notifiers: Arc<DashMap<String, Arc<Notify>>>,+ notifiers: Notifiers,+}++/// One wakeup per job a long-poll is waiting on. An entry lives only while a+/// poll holds a [`Watch`] on it, so the map does not grow with every job the+/// process has ever been asked about.+#[derive(Clone, Default)]+struct Notifiers(Arc<DashMap<String, Arc<Notify>>>);++struct Watch {+ notifiers: Notifiers,+ id: String,+ notify: Arc<Notify>,+}++impl Notifiers {+ fn watch(&self, id: &str) -> Watch {+ let notify = self+ .0+ .entry(id.to_string())+ .or_insert_with(|| Arc::new(Notify::new()))+ .clone();+ Watch {+ notifiers: self.clone(),+ id: id.to_string(),+ notify,+ }+ }++ fn wake(&self, id: &str) {+ if let Some(n) = self.0.get(id) {+ n.notify_waiters();+ }+ }+}++impl Drop for Watch {+ fn drop(&mut self) {+ // The map's handle and this one: no other poll is waiting on the job.+ self.notifiers+ .0+ .remove_if(&self.id, |_, notify| Arc::strong_count(notify) <= 2);+ }}/// Outcome of a finalize attempt during a long-poll.@@ -107,7 +161,9 @@ impl JobStore {eprintln!("assembler: redis job store connected");JobStore {conn,- notifiers: Arc::new(DashMap::new()),+ park_dir: (dispatch::from_env() == dispatch::Dispatch::Local)+ .then(config::pending_dir),+ notifiers: Notifiers::default(),}}Err(e) => {@@ -117,16 +173,41 @@ impl JobStore {}}+ /// Whether Redis answers, for the health check. Bounded, so a connection+ /// that hangs fails the check instead of hanging it.+ pub async fn ping(&self) -> bool {+ let mut c = self.conn.clone();+ let ping = redis::cmd("PING");+ let answer = ping.query_async::<()>(&mut c);+ match tokio::time::timeout(Duration::from_secs(2), answer).await {+ Ok(Ok(())) => true,+ Ok(Err(e)) => {+ eprintln!("assembler: redis ping failed: {e}");+ false+ }+ Err(_) => {+ eprintln!("assembler: redis ping timed out");+ false+ }+ }+ }+// --- job status (pointer, not artifact bytes) --------------------------async fn read(&self, id: &str) -> Option<JobRecord> {+ self.try_read(id).await.ok().flatten()+ }++ /// `Err` when Redis could not be asked, as opposed to `Ok(None)` for a job+ /// it does not have.+ async fn try_read(&self, id: &str) -> Result<Option<JobRecord>, ()> {let mut c = self.conn.clone();match c.get::<_, Option<String>>(job_key(id)).await {- Ok(Some(s)) => serde_json::from_str(&s).ok(),- Ok(None) => None,+ Ok(Some(s)) => Ok(serde_json::from_str(&s).ok()),+ Ok(None) => Ok(None),Err(e) => {eprintln!("assembler: redis job read failed: {e}");- None+ Err(())}}}@@ -241,7 +322,7 @@ impl JobStore {if matches!(rec.status.as_str(), "pending" | "running" | "uploading") {rec.status = "canceled".into();self.write(id, &rec).await;- self.pending_remove(id).await;+ self.unpark(id).await;// Wake the event-driven waiter immediately (terminal state).self.send_callback(id).await;self.wake(id);@@ -249,13 +330,16 @@ impl JobStore {Some(Self::render(id, &rec))}- /// True once the job left the active set (terminal or canceled) — the compute- /// task polls this to abandon a canceled run.+ /// True when the job was canceled or its record is gone — the compute task+ /// asks this to abandon a run nobody waits for. A Redis that could not be+ /// asked is not a cancel: dropping a finished compute over one failed read+ /// would leave the job `running` until its TTL.pub async fn is_canceled(&self, id: &str) -> bool {- self.read(id)- .await- .map(|r| r.status == "canceled")- .unwrap_or(true)+ match self.try_read(id).await {+ Ok(Some(rec)) => rec.status == "canceled",+ Ok(None) => true,+ Err(()) => false,+ }}/// The uniform poll envelope: `{ ok, job: { id, action, status, result?,@@ -292,6 +376,7 @@ impl JobStore {max: Option<Duration>,) -> Option<Value> {let deadline = max.map(|m| Instant::now() + m);+ let mut watch = None;loop {let rec = self.read(id).await?;match rec.status.as_str() {@@ -311,75 +396,24 @@ impl JobStore {if now >= dl {return Some(Self::render(id, &rec));}- let notify = self.notifier(id);+ let watch = watch.get_or_insert_with(|| self.notifiers.watch(id));let tick = (dl - now).min(Duration::from_millis(500));tokio::select! {- _ = notify.notified() => {}+ _ = watch.notify.notified() => {}_ = tokio::time::sleep(tick) => {}}}}- fn notifier(&self, id: &str) -> Arc<Notify> {- self.notifiers- .entry(id.to_string())- .or_insert_with(|| Arc::new(Notify::new()))- .clone()- }-pub fn wake(&self, id: &str) {- if let Some(n) = self.notifiers.get(id) {- n.notify_waiters();- }- }-- // --- late-mint hand-off --------------------------------------------------- /// Hold computed-but-unuploaded artifacts for hand-off, stored in Redis- /// (bytes + pointer) under a short TTL so ANY replica's poll can drain them.- pub async fn pending_put(- &self,- id: &str,- outputs: Vec<Output>,- done: Done,- cache: Option<(String, u128, u64)>,- ) {- let manifest: Vec<Value> = outputs- .iter()- .map(|o| json!({ "name": o.name, "contentType": o.content_type }))- .collect();- let done_json = json!({ "result": done.result, "stats": done.stats }).to_string();- let mut c = self.conn.clone();- let mut pipe = redis::pipe();- pipe.hset(- pending_key(id),- "manifest",- Value::from(manifest).to_string(),- )- .ignore()- .hset(pending_key(id), "done", done_json)- .ignore();- for o in &outputs {- pipe.hset(pending_key(id), format!("b:{}", o.name), o.bytes.clone())- .ignore();- }- if let Some((m, ch, op)) = &cache {- pipe.hset(pending_key(id), "cache", format!("{m}|{ch:032x}|{op}"))- .ignore();- }- pipe.expire(pending_key(id), config::pending_ttl_secs() as i64)- .ignore();- if let Err(e) = pipe.query_async::<()>(&mut c).await {- eprintln!("assembler: redis pending_put failed: {e}");- }+ self.notifiers.wake(id);}- /// Complete a computed job: hold the artifacts for upload, and — when the- /// submit handed over upload URLs — finalize immediately (upload + publish- /// the terminal pointer + fire the completion callback), so no poll is ever- /// needed on the happy path. Without submit-time URLs the job parks in- /// `uploading` and a late-mint poll drains it (the legacy/retry path).- /// Replaces the pending_put + set_status("uploading") + wake trio in actions.+ /// Complete a computed job. When the submit handed over an upload URL for+ /// every output, upload them straight from memory and publish the terminal+ /// pointer + completion callback — nothing is stored anywhere. Otherwise+ /// (no URLs at submit, or that upload failed) park the outputs and leave the+ /// job `uploading` for a late-mint poll to drain.pub async fn finish(&self,id: &str,@@ -392,19 +426,22 @@ impl JobStore {eprintln!("[{id}] finished after cancel; result dropped");return;}- self.pending_put(id, outputs, done, cache).await;self.set_status(id, "uploading").await;- let urls = self.read(id).await.and_then(|r| r.upload_urls);- if let Some(urls) = urls {- if let Finalize::Uploaded = self.try_finalize(id, &urls).await {- // Terminal — deliver the callback from the action task, which- // owns the process lifetime on the server path (the Lambda- // worker re-sends after run_to_completion regardless).- // Retry/NotPending: submit-time URLs failed; a late-mint poll- // retries with fresh ones.- self.send_callback(id).await;- }+ let urls = self+ .read(id)+ .await+ .and_then(|r| r.upload_urls)+ .unwrap_or_default();+ if has_every_url(&outputs, &urls) && upload_all(id, &outputs, &urls).await {+ self.publish(id, done, cache).await;+ // Terminal — deliver the callback from the action task, which owns+ // the process lifetime on the server path (the Lambda worker+ // re-sends after run_to_completion regardless).+ self.send_callback(id).await;+ self.wake(id);+ return;}+ self.park(id, &outputs, &done, &cache).await;self.wake(id);}@@ -440,84 +477,126 @@ impl JobStore {eprintln!("[{id}] completion callback undelivered; caller falls back to poll");}- async fn pending_take(+ // --- late-mint hand-off -------------------------------------------------++ /// Hold computed-but-unuploaded outputs until a poll brings URLs for them.+ /// A failure is logged only: the job then sits `uploading` with nothing to+ /// drain until the caller times out and resubmits, as with an expired TTL.+ async fn park(&self,id: &str,- ) -> Option<(Vec<Output>, Done, Option<(String, u128, u64)>)> {- let mut c = self.conn.clone();- let res: redis::RedisResult<(Option<String>, Option<String>, Option<String>)> =- redis::pipe()- .hget(pending_key(id), "manifest")- .hget(pending_key(id), "done")- .hget(pending_key(id), "cache")- .query_async(&mut c)- .await;- let (manifest_s, done_s, cache_s) = match res {- Ok(t) => t,- Err(e) => {- eprintln!("assembler: redis pending_take failed: {e}");- return None;+ outputs: &[Output],+ done: &Done,+ cache: &Option<(String, u128, u64)>,+ ) {+ let manifest = json!({+ "outputs": outputs+ .iter()+ .map(|o| json!({ "name": o.name, "contentType": o.content_type }))+ .collect::<Vec<_>>(),+ "done": { "result": done.result, "stats": done.stats },+ "cache": cache.as_ref().map(|(m, ch, op)| format!("{m}|{ch:032x}|{op}")),+ })+ .to_string();+ let Some(dir) = self.park_path(id) else {+ let mut c = self.conn.clone();+ let mut pipe = redis::pipe();+ pipe.hset(pending_key(id), "manifest", manifest).ignore();+ for o in outputs {+ pipe.hset(pending_key(id), format!("b:{}", o.name), o.bytes.as_ref())+ .ignore();}+ pipe.expire(pending_key(id), config::pending_ttl_secs() as i64)+ .ignore();+ if let Err(e) = pipe.query_async::<()>(&mut c).await {+ eprintln!("assembler: redis park failed: {e}");+ }+ return;};- let manifest: Vec<Value> = serde_json::from_str(&manifest_s?).ok()?;- let mut outputs = Vec::with_capacity(manifest.len());- for m in &manifest {- let name = m["name"].as_str()?.to_string();- let content_type = m["contentType"]- .as_str()- .unwrap_or("application/octet-stream")- .to_string();- let bytes: Option<Vec<u8>> =- c.hget(pending_key(id), format!("b:{name}")).await.ok()?;- outputs.push(Output {- name,- content_type,- bytes: bytes?,- });+ if let Err(e) = park_on_disk(&dir, &manifest, outputs).await {+ eprintln!("[{id}] could not park outputs in {}: {e}", dir.display());+ let _ = tokio::fs::remove_dir_all(&dir).await;}- let done_v: Value = serde_json::from_str(&done_s?).ok()?;- let done = Done {- result: done_v["result"].clone(),- stats: done_v["stats"].clone(),+ }++ /// The parked outputs of a job, if any are parked here.+ async fn parked(&self, id: &str) -> Option<Parked> {+ let Some(dir) = self.park_path(id) else {+ let mut c = self.conn.clone();+ let manifest: Option<String> = c+ .hget(pending_key(id), "manifest")+ .await+ .map_err(|e| eprintln!("assembler: redis parked read failed: {e}"))+ .ok()?;+ let manifest: Value = serde_json::from_str(&manifest?).ok()?;+ let mut outputs = Vec::new();+ for (name, content_type) in manifest_outputs(&manifest)? {+ let bytes: Option<Vec<u8>> =+ c.hget(pending_key(id), format!("b:{name}")).await.ok()?;+ outputs.push(Output {+ name,+ content_type,+ bytes: bytes?.into(),+ });+ }+ return Some((outputs, manifest_done(&manifest), manifest_cache(&manifest)));};- Some((outputs, done, cache_s.and_then(parse_cache)))+ parked_on_disk(&dir).await}- async fn pending_remove(&self, id: &str) {- let mut c = self.conn.clone();- if let Err(e) = c.del::<_, ()>(pending_key(id)).await {- eprintln!("assembler: redis pending_remove failed: {e}");- }+ async fn unpark(&self, id: &str) {+ let Some(dir) = self.park_path(id) else {+ let mut c = self.conn.clone();+ if let Err(e) = c.del::<_, ()>(pending_key(id)).await {+ eprintln!("assembler: redis unpark failed: {e}");+ }+ return;+ };+ let _ = tokio::fs::remove_dir_all(&dir).await;+ }++ /// The directory a job's outputs park in. Job ids are caller-chosen+ /// (`Idempotency-Key`), so the name is a hash of the id, never the id.+ fn park_path(&self, id: &str) -> Option<PathBuf> {+ let name = format!("{:032x}", xxhash_rust::xxh3::xxh3_128(id.as_bytes()));+ self.park_dir.as_ref().map(|dir| dir.join(name))+ }++ /// Delete parked outputs older than the pending TTL — the job they belong to+ /// was never drained and has been (or will be) resubmitted. Redis expires+ /// its own keys, so this is the disk half of that TTL.+ pub async fn sweep_parked(&self) {+ let Some(dir) = &self.park_dir else {+ return;+ };+ sweep_dir(dir, Duration::from_secs(config::pending_ttl_secs())).await;}- /// Drain computed-but-unuploaded artifacts to their fresh signed URLs (from a- /// long-poll). Every output must have a matching URL; on success publishes the- /// terminal pointer, else keeps the artifacts for the next poll to retry.+ /// Drain parked outputs to fresh signed URLs (from a long-poll). Every+ /// output must have a matching URL; on success publishes the terminal+ /// pointer, else keeps the outputs for the next poll to retry.pub async fn try_finalize(&self, id: &str, urls: &HashMap<String, String>) -> Finalize {- let Some((outputs, done, cache)) = self.pending_take(id).await else {+ let Some((outputs, done, cache)) = self.parked(id).await else {return Finalize::NotPending;};- // Need a URL for every output before we can finalize.- if outputs.iter().any(|o| !urls.contains_key(&o.name)) {+ if !has_every_url(&outputs, urls) {return Finalize::NotPending;}- for o in &outputs {- let url = &urls[&o.name];- if let Err(e) = http::upload(url, o.bytes.clone(), &o.content_type).await {- eprintln!(- "[{id}] output '{}' upload failed (retry next poll): {}",- o.name, e.message- );- return Finalize::Retry;- }+ if !upload_all(id, &outputs, urls).await {+ return Finalize::Retry;}- self.pending_remove(id).await;+ self.unpark(id).await;+ self.publish(id, done, cache).await;+ Finalize::Uploaded+ }++ /// Every output is uploaded: record the result pointer and mark the job done.+ async fn publish(&self, id: &str, done: Done, cache: Option<(String, u128, u64)>) {if let Some((model, content, opts)) = cache {let pointer = json!({ "result": done.result, "stats": done.stats });self.result_put(&model, content, opts, pointer).await;}self.set_done(id, done).await;- Finalize::Uploaded}// --- content-hash result-pointer cache (CODE_VERSION-stamped) ----------@@ -583,9 +662,24 @@ impl JobStore {}}+/// The client's defaults suit nobody waiting on a job: no limit on a connect+/// or a reply, and a reconnect backoff that goes from one second straight to a+/// minute or two (its factor of 100 multiplies each delay). After a Redis+/// restart that left every job read and write failing for about two minutes.+/// Bounded waits, and retries that double from one second up to five.+const REDIS_CONNECT_TIMEOUT: Duration = Duration::from_secs(5);+const REDIS_RESPONSE_TIMEOUT: Duration = Duration::from_secs(15);+const REDIS_RETRY_FACTOR: u64 = 2;+const REDIS_RETRY_MAX_DELAY_MS: u64 = 5_000;+async fn connect(url: &str) -> redis::RedisResult<redis::aio::ConnectionManager> {let client = redis::Client::open(url)?;- let mut conn = client.get_connection_manager().await?;+ let config = redis::aio::ConnectionManagerConfig::new()+ .set_connection_timeout(REDIS_CONNECT_TIMEOUT)+ .set_response_timeout(REDIS_RESPONSE_TIMEOUT)+ .set_factor(REDIS_RETRY_FACTOR)+ .set_max_delay(REDIS_RETRY_MAX_DELAY_MS);+ let mut conn = client.get_connection_manager_with_config(config).await?;redis::cmd("PING").query_async::<()>(&mut conn).await?;Ok(conn)}@@ -614,6 +708,98 @@ fn pending_key(id: &str) -> String {format!("asm:pending:{id}")}+async fn park_on_disk(+ dir: &std::path::Path,+ manifest: &str,+ outputs: &[Output],+) -> std::io::Result<()> {+ tokio::fs::create_dir_all(dir).await?;+ for (i, o) in outputs.iter().enumerate() {+ tokio::fs::write(dir.join(i.to_string()), &o.bytes).await?;+ }+ // The manifest is written last, under its final name by rename, so a reader+ // never sees a job whose output files are still being written.+ tokio::fs::write(dir.join("manifest.tmp"), manifest).await?;+ tokio::fs::rename(dir.join("manifest.tmp"), dir.join("manifest.json")).await+}++async fn parked_on_disk(dir: &std::path::Path) -> Option<Parked> {+ let manifest = tokio::fs::read(dir.join("manifest.json")).await.ok()?;+ let manifest: Value = serde_json::from_slice(&manifest).ok()?;+ let mut outputs = Vec::new();+ for (i, (name, content_type)) in manifest_outputs(&manifest)?.into_iter().enumerate() {+ outputs.push(Output {+ name,+ content_type,+ bytes: http::map_file(&dir.join(i.to_string())).ok()?,+ });+ }+ Some((outputs, manifest_done(&manifest), manifest_cache(&manifest)))+}++/// Remove every entry of `dir` last modified more than `ttl` ago.+async fn sweep_dir(dir: &std::path::Path, ttl: Duration) {+ let Ok(mut entries) = tokio::fs::read_dir(dir).await else {+ return;+ };+ while let Ok(Some(entry)) = entries.next_entry().await {+ let age = entry+ .metadata()+ .await+ .and_then(|m| m.modified())+ .ok()+ .and_then(|modified| modified.elapsed().ok());+ if age.is_some_and(|age| age > ttl) {+ let _ = tokio::fs::remove_dir_all(entry.path()).await;+ }+ }+}++fn has_every_url(outputs: &[Output], urls: &HashMap<String, String>) -> bool {+ outputs.iter().all(|o| urls.contains_key(&o.name))+}++/// PUT every output to its URL. False on the first failure (logged).+async fn upload_all(id: &str, outputs: &[Output], urls: &HashMap<String, String>) -> bool {+ for o in outputs {+ if let Err(e) = http::upload(&urls[&o.name], o.bytes.clone(), &o.content_type).await {+ eprintln!(+ "[{id}] output '{}' upload failed (a poll retries with fresh URLs): {}",+ o.name, e.message+ );+ return false;+ }+ }+ true+}++fn manifest_outputs(manifest: &Value) -> Option<Vec<(String, String)>> {+ manifest["outputs"]+ .as_array()?+ .iter()+ .map(|o| {+ Some((+ o["name"].as_str()?.to_string(),+ o["contentType"]+ .as_str()+ .unwrap_or("application/octet-stream")+ .to_string(),+ ))+ })+ .collect()+}++fn manifest_done(manifest: &Value) -> Done {+ Done {+ result: manifest["done"]["result"].clone(),+ stats: manifest["done"]["stats"].clone(),+ }+}++fn manifest_cache(manifest: &Value) -> Option<(String, u128, u64)> {+ manifest["cache"].as_str().map(str::to_string).and_then(parse_cache)+}+/// Parse a `"model|contentHex|opts"` cache tuple stored alongside a pending job.fn parse_cache(s: String) -> Option<(String, u128, u64)> {let mut it = s.splitn(3, '|');@@ -628,3 +814,83 @@ fn parse_cache(s: String) -> Option<(String, u128, u64)> {pub fn opts_hash(options: &Value) -> u64 {xxhash_rust::xxh3::xxh3_64(options.to_string().as_bytes())}++#[cfg(test)]+mod tests {+ use super::*;++ fn output(name: &str, bytes: &'static [u8]) -> Output {+ Output {+ name: name.into(),+ content_type: "application/octet-stream".into(),+ bytes: Bytes::from_static(bytes),+ }+ }++ #[test]+ fn a_wakeup_lives_only_while_a_poll_waits_on_it() {+ let notifiers = Notifiers::default();+ let first = notifiers.watch("job");+ let second = notifiers.watch("job");+ assert!(Arc::ptr_eq(&first.notify, &second.notify));++ drop(first);+ assert_eq!(notifiers.0.len(), 1, "the second poll still waits");+ drop(second);+ assert!(notifiers.0.is_empty());+ }++ #[tokio::test]+ async fn parked_outputs_come_back_from_disk_as_they_went_in() {+ let dir = tempfile::tempdir().unwrap();+ let job = dir.path().join("job");+ let manifest = json!({+ "outputs": [+ { "name": "glb", "contentType": "model/gltf-binary" },+ { "name": "graph", "contentType": "application/json" },+ { "name": "empty", "contentType": "text/plain" },+ ],+ "done": { "result": { "componentCount": 3 }, "stats": { "ms": 7 } },+ "cache": "model-1|000000000000000000000000000000ff|42",+ })+ .to_string();+ let outputs = [output("glb", b"glTF-bytes"), output("graph", b"{}"), output("empty", b"")];++ assert!(parked_on_disk(&job).await.is_none());+ park_on_disk(&job, &manifest, &outputs).await.unwrap();++ let (back, done, cache) = parked_on_disk(&job).await.unwrap();+ let names: Vec<_> = back.iter().map(|o| (o.name.as_str(), &o.bytes[..])).collect();+ assert_eq!(+ names,+ [("glb", &b"glTF-bytes"[..]), ("graph", &b"{}"[..]), ("empty", &b""[..])]+ );+ assert_eq!(back[0].content_type, "model/gltf-binary");+ assert_eq!(done.result["componentCount"], 3);+ assert_eq!(done.stats["ms"], 7);+ assert_eq!(cache, Some(("model-1".to_string(), 0xff, 42)));+ }++ #[tokio::test]+ async fn a_job_without_its_manifest_is_not_parked() {+ // Output files land before the manifest; a reader in between sees nothing.+ let dir = tempfile::tempdir().unwrap();+ let job = dir.path().join("job");+ tokio::fs::create_dir_all(&job).await.unwrap();+ tokio::fs::write(job.join("0"), b"half-written").await.unwrap();+ assert!(parked_on_disk(&job).await.is_none());+ }++ #[tokio::test]+ async fn the_sweep_removes_only_what_outlived_the_ttl() {+ let dir = tempfile::tempdir().unwrap();+ let manifest = json!({ "outputs": [], "done": {} }).to_string();+ park_on_disk(&dir.path().join("old"), &manifest, &[]).await.unwrap();++ sweep_dir(dir.path(), Duration::from_secs(3600)).await;+ assert!(dir.path().join("old").exists());++ sweep_dir(dir.path(), Duration::ZERO).await;+ assert!(!dir.path().join("old").exists());+ }+}diff --git a/apps/assembler/src/main.rs b/apps/assembler/src/main.rsindex b0efe100bd..8ddf2a025e 100644--- a/apps/assembler/src/main.rs+++ b/apps/assembler/src/main.rs@@ -20,6 +20,7 @@//! fallback. Wires the `converter` and `planner` crates via `actions::*`.mod actions;+mod admission;mod cache;mod config;mod dispatch;@@ -41,7 +42,6 @@ use serde_json::{json, Value};use std::collections::HashMap;use std::sync::atomic::{AtomicU64, Ordering};use std::sync::Arc;-use tokio::sync::Semaphore;use tower_http::compression::{predicate::SizeAbove, CompressionLayer};const VERSION: &str = "0.1.0";@@ -57,9 +57,17 @@ const DEFAULT_MAX_RENDER_WEIGHT_BYTES: u64 = 419_430_400; // 400 MiB#[global_allocator]static GLOBAL: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc;+// Read by jemalloc at startup. A background thread purges freed pages after a+// second (and skips the lazy "muzzy" stage), so memory a finished job freed+// goes back to the OS instead of sitting in the allocator until the next job.+#[cfg(target_os = "linux")]+#[allow(non_upper_case_globals)]+#[export_name = "malloc_conf"]+pub static malloc_conf: &[u8] = b"background_thread:true,dirty_decay_ms:1000,muzzy_decay_ms:0\0";+#[derive(Clone)]pub struct AppState {- pub slots: Arc<Semaphore>,+ pub admission: admission::Admission,pub jobs: jobs::JobStore,pub cache: Arc<cache::ResultCache>,pub progress: progress::ProgressStore,@@ -84,17 +92,29 @@ fn main() {/// one-shot `run-job` CLI so both share one JobStore + cache + concurrency.pub async fn build_state() -> AppState {AppState {- slots: Arc::new(Semaphore::new(config::max_concurrency())),+ admission: admission::Admission::from_env(),jobs: jobs::JobStore::from_env().await,- cache: Arc::new(cache::ResultCache::new(config::cache_bytes())),+ cache: Arc::new(cache::ResultCache::new(+ config::cache_dir(),+ config::cache_bytes(),+ )),progress: progress::ProgressStore::default(),}}async fn serve() {- let max = config::max_concurrency();+ http::clear_stale_sources();let state = build_state().await;- let slots = Arc::clone(&state.slots);+ let admission = state.admission.clone();+ // Parked outputs nobody drained (see `jobs.rs`): the disk half of the+ // pending TTL, including whatever a previous process left behind.+ let sweeper = state.jobs.clone();+ tokio::spawn(async move {+ loop {+ sweeper.sweep_parked().await;+ tokio::time::sleep(std::time::Duration::from_secs(60)).await;+ }+ });let app = Router::new().route("/health", get(health)).route("/v1", get(discovery))@@ -120,7 +140,8 @@ async fn serve() {.with_state(state);eprintln!(- "assembler config: version={VERSION} concurrency={max} cacheMB={} maxParts={} maxSourceMB={} longPollCap={}s jobTtl={}s resultTtl={}s",+ "assembler config: version={VERSION} memoryBudgetMB={} cacheMB={} maxParts={} maxSourceMB={} longPollCap={}s jobTtl={}s resultTtl={}s",+ admission.budget_mb(),config::cache_bytes() / 1024 / 1024,config::max_parts(),config::max_source_bytes() / 1024 / 1024,@@ -140,11 +161,12 @@ async fn serve() {.await.unwrap();- // Jobs run detached (create returns 202) and each holds a slot; wait for- // every slot to free before exiting so a deploy/scale-down doesn't kill an- // in-flight job. The grace deadline in shutdown_signal force-exits a wedged one.+ // Jobs run detached (create returns 202) and each holds part of the memory+ // budget while it computes; wait for all of it to come back before exiting+ // so a deploy/scale-down doesn't kill an in-flight job. The grace deadline+ // in shutdown_signal force-exits a wedged one.eprintln!("assembler draining in-flight jobs");- let _ = slots.acquire_many(max as u32).await;+ admission.drain().await;eprintln!("assembler drained cleanly; exiting");}@@ -176,8 +198,16 @@ async fn shutdown_signal() {});}-async fn health() -> Json<Value> {- Json(json!({ "ok": true, "version": VERSION }))+/// Healthy means it can do its job, and it cannot without Redis: every job's+/// status lives there. A probe that fails here gets the instance replaced.+async fn health(State(state): State<AppState>) -> (StatusCode, Json<Value>) {+ if state.jobs.ping().await {+ return (StatusCode::OK, Json(json!({ "ok": true, "version": VERSION })));+ }+ (+ StatusCode::SERVICE_UNAVAILABLE,+ Json(json!({ "ok": false, "version": VERSION, "error": "redis unreachable" })),+ )}async fn discovery(headers: HeaderMap) -> Result<Json<Value>, ApiError> {diff --git a/crates/converter/Cargo.toml b/crates/converter/Cargo.tomlindex ef07d1e650..4c7cbaa6fa 100644--- a/crates/converter/Cargo.toml+++ b/crates/converter/Cargo.toml@@ -15,3 +15,6 @@ serde.workspace = trueserde_json.workspace = truesha1.workspace = trueregex = "1"++[dev-dependencies]+libc = "0.2"diff --git a/crates/converter/src/convert.rs b/crates/converter/src/convert.rsindex c79e084afd..ad24f91350 100644--- a/crates/converter/src/convert.rs+++ b/crates/converter/src/convert.rs@@ -8,7 +8,7 @@use crate::graph::{assign_node_ids, build_graph, compute_world_bboxes, count_leaves, count_triangles,- detect_source_unit, AssemblyNode, PartMesh,+ detect_source_unit_bytes, AssemblyNode, PartMesh,};use nalgebra::Matrix4;use serde_json::Value;@@ -209,7 +209,23 @@ pub fn convert_step(linear_deflection: f64,angular_deflection: f64,) -> Result<Conversion, ConvertError> {- let source_unit = detect_source_unit(step_text);+ convert_step_head(+ step_path,+ step_text.as_bytes(),+ linear_deflection,+ angular_deflection,+ )+}++/// [`convert_step`], taking the file's head as bytes (for unit detection) so a+/// caller can pass a memory-mapped slice instead of a decoded `String`.+pub fn convert_step_head(+ step_path: &str,+ step_head: &[u8],+ linear_deflection: f64,+ angular_deflection: f64,+) -> Result<Conversion, ConvertError> {+ let source_unit = detect_source_unit_bytes(step_head);let root = build_tree(step_path, linear_deflection, angular_deflection)?;let component_count = count_leaves(&root);let triangles = count_triangles(&root);diff --git a/crates/converter/src/graph.rs b/crates/converter/src/graph.rsindex 704d690ee4..f569e6b3ba 100644--- a/crates/converter/src/graph.rs+++ b/crates/converter/src/graph.rs@@ -7,7 +7,7 @@use crate::nodeid::{geometry_hash, node_id};use nalgebra::{Matrix4, Vector3};-use regex::Regex;+use regex::bytes::Regex;use serde_json::{json, Value};use std::collections::HashMap;use std::sync::OnceLock;@@ -88,40 +88,43 @@ fn si_prefix(p: &str) -> &'static str {/// `_detect_source_unit`: best-effort read of the STEP declared length unit.pub fn detect_source_unit(text: &str) -> String {+ detect_source_unit_bytes(text.as_bytes())+}++/// How much of a file's head is searched for its unit.+pub const SOURCE_UNIT_SCAN_BYTES: usize = 32 * 1024 * 1024;++/// [`detect_source_unit`] over raw bytes — a memory-mapped file's head — so a+/// caller need not decode tens of megabytes into a `String` to ask one+/// question. The answer is the one the lossy-decoded text gives: a byte that is+/// not valid UTF-8 counts as an ordinary character (as `�` did), and a unit+/// name is decoded the same lossy way.+pub fn detect_source_unit_bytes(head: &[u8]) -> String {static STMT: OnceLock<Regex> = OnceLock::new();static CONV: OnceLock<Regex> = OnceLock::new();static SI: OnceLock<Regex> = OnceLock::new();- let stmt =- STMT.get_or_init(|| Regex::new(r"(?s)\(([^;]*?LENGTH_UNIT\(\)[^;]*?)\)\s*;").unwrap());- let conv = CONV.get_or_init(|| Regex::new(r"CONVERSION_BASED_UNIT\s*\(\s*'([^']+)'").unwrap());+ // `(?-u:[^x])` is "any byte but x", valid UTF-8 or not; everything else+ // (`\s`, `\w`) keeps its Unicode meaning.+ let stmt = STMT.get_or_init(|| {+ Regex::new(r"(?s)\(((?-u:[^;])*?LENGTH_UNIT\(\)(?-u:[^;])*?)\)\s*;").unwrap()+ });+ let conv = CONV+ .get_or_init(|| Regex::new(r"CONVERSION_BASED_UNIT\s*\(\s*'((?-u:[^'])+)'").unwrap());let si =SI.get_or_init(|| Regex::new(r"SI_UNIT\s*\(\s*(?:\.(\w+)\.|\$)\s*,\s*\.METRE\.").unwrap());- // Lossy decoding expands invalid bytes to 3-byte `�`, so a byte-capped read- // can decode to MORE than `cap` bytes — floor to a char boundary or the- // slice panics mid-replacement-char (seen on binary xbf heads).- let cap = 32 * 1024 * 1024;- let text = if text.len() > cap {- let mut end = cap;- while !text.is_char_boundary(end) {- end -= 1;- }- &text[..end]- } else {- text- };-- for m in stmt.captures_iter(text) {+ let head = &head[..head.len().min(SOURCE_UNIT_SCAN_BYTES)];+ for m in stmt.captures_iter(head) {let body = &m[1];if let Some(c) = conv.captures(body) {- let name = c[1].to_uppercase();- return unit_names(&name)+ let name = String::from_utf8_lossy(&c[1]);+ return unit_names(&name.to_uppercase()).map(|s| s.to_string())- .unwrap_or_else(|| c[1].to_lowercase());+ .unwrap_or_else(|| name.to_lowercase());}if let Some(c) = si.captures(body) {- let prefix = c.get(1).map(|g| g.as_str()).unwrap_or("");- return si_prefix(prefix).to_string();+ let prefix = c.get(1).map(|g| g.as_bytes()).unwrap_or(b"");+ return si_prefix(&String::from_utf8_lossy(prefix)).to_string();}}OUTPUT_UNIT.to_string()@@ -279,6 +282,59 @@ mod tests {);}+ /// The detector as it was: over the lossy-decoded text.+ fn reference(head: &[u8]) -> String {+ use regex::Regex;+ let text = String::from_utf8_lossy(head);+ let stmt = Regex::new(r"(?s)\(([^;]*?LENGTH_UNIT\(\)[^;]*?)\)\s*;").unwrap();+ let conv = Regex::new(r"CONVERSION_BASED_UNIT\s*\(\s*'([^']+)'").unwrap();+ let si = Regex::new(r"SI_UNIT\s*\(\s*(?:\.(\w+)\.|\$)\s*,\s*\.METRE\.").unwrap();+ for m in stmt.captures_iter(&text) {+ let body = &m[1];+ if let Some(c) = conv.captures(body) {+ let name = c[1].to_uppercase();+ return unit_names(&name)+ .map(|s| s.to_string())+ .unwrap_or_else(|| c[1].to_lowercase());+ }+ if let Some(c) = si.captures(body) {+ return si_prefix(c.get(1).map(|g| g.as_str()).unwrap_or("")).to_string();+ }+ }+ OUTPUT_UNIT.to_string()+ }++ #[test]+ fn bytes_give_the_answer_the_decoded_text_gave() {+ let cases: &[&[u8]] = &[+ b"DATA;\n#41=( CONVERSION_BASED_UNIT('INCH',#38) LENGTH_UNIT() NAMED_UNIT(#40) );\nENDSEC;",+ b"#41=( LENGTH_UNIT() NAMED_UNIT(*) SI_UNIT($,.METRE.) );",+ b"#5=( LENGTH_UNIT() NAMED_UNIT(*) SI_UNIT(.MILLI.,.METRE.) );",+ b"#5=(\r\n LENGTH_UNIT()\r\n NAMED_UNIT(*)\r\n SI_UNIT(.CENTI.,.METRE.)\r\n)\r\n;",+ b"#9=( CONVERSION_BASED_UNIT('FurLong',#1) LENGTH_UNIT() NAMED_UNIT(#2) );",+ b"DATA;\nENDSEC;",+ b"",+ // Not UTF-8: in the header before the statement, inside it, and+ // inside the unit name.+ b"FILE_NAME('pi\xE8ce');\n#1=( LENGTH_UNIT() NAMED_UNIT(*) SI_UNIT(.MILLI.,.METRE.) );",+ b"#1=( LENGTH_UNIT() /* \xFF\xFE */ NAMED_UNIT(*) SI_UNIT($,.METRE.) );",+ b"#1=( CONVERSION_BASED_UNIT('IN\xC9CH',#3) LENGTH_UNIT() NAMED_UNIT(#4) );",+ // Unicode: a multi-byte name, and a no-break space between tokens.+ "#1=( CONVERSION_BASED_UNIT('Zoll\u{e4}',#3) LENGTH_UNIT() NAMED_UNIT(#4) );".as_bytes(),+ "#1=( LENGTH_UNIT() NAMED_UNIT(*) SI_UNIT\u{a0}(\u{a0}.MILLI.,.METRE.) )\u{a0};".as_bytes(),+ // The first LENGTH_UNIT statement names no unit; the second does.+ b"#1=( LENGTH_UNIT() NAMED_UNIT(#9) ); #2=( LENGTH_UNIT() NAMED_UNIT(*) SI_UNIT($,.METRE.) );",+ ];+ for case in cases {+ assert_eq!(+ detect_source_unit_bytes(case),+ reference(case),+ "{}",+ String::from_utf8_lossy(case)+ );+ }+ }+#[test]fn source_unit_truncation_respects_char_boundaries() {// A lossy-decoded binary head can exceed the 32MB byte cap (invaliddiff --git a/crates/converter/tests/lean_planes.rs b/crates/converter/tests/lean_planes.rsnew file mode 100644index 0000000000..69ab4219d4--- /dev/null+++ b/crates/converter/tests/lean_planes.rs@@ -0,0 +1,64 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++//! A plate with many holes is meshed without BRepMesh's interior-node pass on+//! its flat faces. That must leave the graph (nodeIds, geometry hashes) and the+//! triangle count as they were, and it must be what keeps the memory down. The+//! triangle wiring is not compared: on a regular hole pattern the two paths can+//! break a co-circular tie differently. One test, alone in its file: it flips+//! an environment variable and reads the process's peak memory.++use converter::convert::convert_step;++const HOLES: u32 = 240;++fn peak_rss_bytes() -> u64 {+ let mut usage = std::mem::MaybeUninit::<libc::rusage>::uninit();+ // SAFETY: getrusage fills the struct it is given.+ let usage = unsafe {+ assert_eq!(libc::getrusage(libc::RUSAGE_SELF, usage.as_mut_ptr()), 0);+ usage.assume_init()+ };+ // macOS reports bytes, Linux kilobytes.+ let scale = if cfg!(target_os = "macos") { 1 } else { 1024 };+ usage.ru_maxrss as u64 * scale+}++fn convert(path: &str) -> (String, usize) {+ let text = std::fs::read_to_string(path).unwrap();+ let converted = convert_step(path, &text, 0.1, 0.15).expect("convert");+ let graph = serde_json::to_string(&converted.graph).unwrap();+ (graph, converted.triangles as usize)+}++#[test]+fn a_perforated_plate_keeps_its_graph_in_far_less_memory() {+ let dir = std::env::temp_dir().join(format!("carbon-lean-planes-{HOLES}"));+ std::fs::create_dir_all(&dir).unwrap();+ let path = dir.join("plate.step");+ let path = path.to_str().unwrap();+ assert!(occt_bridge::write_test_plate_with_holes(+ path,+ 6.0 * HOLES as f64,+ 10.0,+ 2.0,+ HOLES+ ));++ // Lean first: peak memory only ever rises, so the default path must run last.+ let before = peak_rss_bytes();+ let lean = convert(path);+ let after_lean = peak_rss_bytes();+ std::env::set_var("ASSEMBLER_LEAN_PLANES", "0");+ let default = convert(path);+ let after_default = peak_rss_bytes();++ assert!(lean.1 > HOLES as usize * 100, "the holes were not meshed");+ assert_eq!(lean, default, "the lean path changed the plate's graph");+ assert!(+ after_default as f64 > after_lean as f64 * 1.5,+ "the default path should need far more memory than the lean one \+ (start {before}, lean {after_lean}, default {after_default} bytes)"+ );+}diff --git a/crates/occt-bridge/src/occt.cc b/crates/occt-bridge/src/occt.ccindex 7bf81c4b22..e10507fde8 100644--- a/crates/occt-bridge/src/occt.cc+++ b/crates/occt-bridge/src/occt.cc@@ -12,7 +12,10 @@#include <cstdlib>#include <BinXCAFDrivers.hxx>#include <BRepAlgoAPI_Cut.hxx>+#include <BRepMesh_Context.hxx>+#include <BRepMesh_FaceDiscret.hxx>#include <BRepMesh_IncrementalMesh.hxx>+#include <BRepMesh_MeshAlgoFactory.hxx>#include <BRepPrimAPI_MakeBox.hxx>#include <BRepPrimAPI_MakeCylinder.hxx>#include <BRep_Builder.hxx>@@ -20,6 +23,7 @@#include <Bnd_Box.hxx>#include <GProp_GProps.hxx>#include <IFSelect_ReturnStatus.hxx>+#include <IMeshTools_Parameters.hxx>#include <Interface_Static.hxx>#include <PCDM_ReaderStatus.hxx>#include <PCDM_StoreStatus.hxx>@@ -151,11 +155,74 @@ static double adaptive_deflection(const TopoDS_Shape &shape, double lin) {return std::min(lin, std::max(diag * 5e-4, lin * 0.05));}+// A flat face with many holes is where BRepMesh's memory goes: its default+// algorithm for a plane runs an interior-node pass whose bookkeeping grows with+// the square of the hole count (1,200 holes on one face: 5.6 GB), although a+// plane has no interior nodes to add. Past this many wires on one face the part+// is meshed with that pass off for planes only. The vertices are the same, so+// nodeIds and geometry hashes do not move; the triangle wiring can differ where+// a face's points are co-circular (a disc, a regular hole pattern), which is why+// smaller parts keep the default path and stay byte-identical.+static const int LEAN_PLANE_MIN_WIRES = 64;++// ASSEMBLER_LEAN_PLANES=0 turns it off (every part takes the default path).+// Read per call, not cached, so a test can flip it.+static bool lean_planes_enabled() {+ const char *e = std::getenv("ASSEMBLER_LEAN_PLANES");+ return !(e && e[0] == '0');+}++static bool has_perforated_face(const TopoDS_Shape &shape) {+ for (TopExp_Explorer face(shape, TopAbs_FACE); face.More(); face.Next()) {+ int wires = 0;+ for (TopExp_Explorer wire(face.Current(), TopAbs_WIRE); wire.More();+ wire.Next()) {+ if (++wires > LEAN_PLANE_MIN_WIRES) return true;+ }+ }+ return false;+}++// OCCT's default factory, except a plane gets the algorithm without the+// interior-node pass. Every other surface keeps the caller's parameters.+class LeanPlaneAlgoFactory : public IMeshTools_MeshAlgoFactory {+public:+ Handle(IMeshTools_MeshAlgo)+ GetAlgo(const GeomAbs_SurfaceType type,+ const IMeshTools_Parameters ¶ms) const override {+ if (type != GeomAbs_Plane) return base->GetAlgo(type, params);+ IMeshTools_Parameters lean = params;+ lean.InternalVerticesMode = false;+ return base->GetAlgo(type, lean);+ }++private:+ Handle(BRepMesh_MeshAlgoFactory) base = new BRepMesh_MeshAlgoFactory;+};++static void mesh(const TopoDS_Shape &shape, double lin, double ang) {+ const double deflection = adaptive_deflection(shape, lin);+ if (!lean_planes_enabled() || !has_perforated_face(shape)) {+ BRepMesh_IncrementalMesh(shape, deflection, Standard_False, ang,+ mesh_parallel() ? Standard_True : Standard_False);+ return;+ }+ // The same four parameters the constructor above sets.+ BRepMesh_IncrementalMesh mesher;+ mesher.SetShape(shape);+ IMeshTools_Parameters ¶ms = mesher.ChangeParameters();+ params.Deflection = deflection;+ params.Relative = false;+ params.Angle = ang;+ params.InParallel = mesh_parallel();+ Handle(BRepMesh_Context) context = new BRepMesh_Context(params.MeshAlgo);+ context->SetFaceDiscret(new BRepMesh_FaceDiscret(new LeanPlaneAlgoFactory));+ mesher.Perform(context);+}+static void tessellate(const TopoDS_Shape &shape, double lin, double ang,std::vector<float> &verts, std::vector<uint32_t> &indices) {- BRepMesh_IncrementalMesh(shape, adaptive_deflection(shape, lin),- Standard_False, ang,- mesh_parallel() ? Standard_True : Standard_False);+ mesh(shape, lin, ang);uint32_t offset = 0;for (TopExp_Explorer exp(shape, TopAbs_FACE); exp.More(); exp.Next()) {TopoDS_Face face = TopoDS::Face(exp.Current());diff --git a/crates/planner/src/steps.rs b/crates/planner/src/steps.rsindex 3907f461e6..d2324186d1 100644--- a/crates/planner/src/steps.rs+++ b/crates/planner/src/steps.rs@@ -173,6 +173,35 @@ pub struct PlanUnit {#[allow(clippy::too_many_arguments)]pub fn plan_step(+ step_path: &str,+ linear_deflection: f64,+ angular_deflection: f64,+ clearance: f64,+ path_samples: usize,+ max_parts: Option<usize>,+ units: Option<Vec<PlanUnit>>,+ sequence: Option<Vec<Vec<String>>>,+ tolerance: Option<f64>,+) -> Result<PlanResult, ConvertError> {+ plan_step_observed(+ step_path,+ linear_deflection,+ angular_deflection,+ clearance,+ path_samples,+ max_parts,+ units,+ sequence,+ tolerance,+ &|_| {},+ )+}++/// [`plan_step`], telling `on_parts` the part count as soon as the model is+/// read — before the sweeps, which are where a plan's memory goes. The service+/// sizes the job's memory reservation from it.+#[allow(clippy::too_many_arguments)]+pub fn plan_step_observed(step_path: &str,linear_deflection: f64,angular_deflection: f64,@@ -186,10 +215,12 @@ pub fn plan_step(// the tolerance must scale with tessellation error or clean seated// contacts read as collisions. Explicit values are honored as-is.tolerance: Option<f64>,+ on_parts: &dyn Fn(usize),) -> Result<PlanResult, ConvertError> {let root = build_tree(step_path, linear_deflection, angular_deflection)?;let mut parts = collect_world_parts(&root);let leaf_count = parts.len() as i64;+ on_parts(parts.len());// Caller units → merged bodies (expansion maps unit id → members).let mut expansion: HashMap<String, (Vec<String>, Option<String>)> = HashMap::new();