Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

classify the macOS GPU watchdog kill instead of reporting "generate exited 2"

Adam Eivy158f2b5a25c0
diff --git a/server/services/imageTo3d/trellis2.js b/server/services/imageTo3d/trellis2.js
index e893952700..c054145885 100644
--- a/server/services/imageTo3d/trellis2.js
+++ b/server/services/imageTo3d/trellis2.js
@@ -32,6 +32,11 @@ import {
probePythonModules,
} from './laneRunner.js';
import { renderOptionArgs } from './renderOptions.js';
+import {
+ selectTrellis2DecimationTarget,
+ trellis2MeshQualityArgs,
+ trellis2FillHolesStep,
+} from './trellis2MeshQuality.js';
const HOME = homedir();
const IS_WIN = platform() === 'win32';
@@ -369,6 +374,10 @@ export function buildInstallSteps(base, { exists = existsSync, installMetalToolc
}
steps.push(trellis2AppleDepsStep(base, exists));
steps.push({ stage: 'setup', command: 'bash', args: ['setup.sh'], cwd: root });
+ // AFTER setup, necessarily: `setup.sh` runs `patches/mps_compat.py`, which is
+ // what writes the `fill_holes` stub this step converts into an env gate. Run
+ // earlier and it would assert on an unstubbed file and fail every fresh install.
+ steps.push(trellis2FillHolesStep(trellis2VenvPython(base), root));
return steps;
}
@@ -461,8 +470,13 @@ export function selectTrellis2TextureSize(unifiedMemoryGb) {
* port's own default. `steps: null` deliberately omits `--steps` so the pipeline's
* per-phase default (12) applies — see renderOptions.js for the sentinel contract.
*
+ * `meshQuality` is forwarded verbatim to `trellis2MeshQualityArgs` (decimation
+ * target, hole filling, exporter knobs) — an empty object emits only the `--`
+ * separator, i.e. exactly upstream's behaviour.
+ *
* @param {{imagePath: string, outputPath?: string, base?: string, textureSize?: number,
- * pipelineType?: string, steps?: number|null, seed?: number|null}} opts
+ * pipelineType?: string, steps?: number|null, seed?: number|null,
+ * meshQuality?: object}} opts
* @returns {{command: string, args: string[]}}
*/
export function buildGenerateArgs({
@@ -473,6 +487,7 @@ export function buildGenerateArgs({
pipelineType = TRELLIS2_BASELINE_PIPELINE_TYPE,
steps = null,
seed = null,
+ meshQuality = {},
} = {}) {
if (!imagePath) throw new Error('buildGenerateArgs: imagePath is required');
if (!TRELLIS2_TEXTURE_SIZES.includes(textureSize)) {
@@ -489,9 +504,17 @@ export function buildGenerateArgs({
// neither the ranges nor the flag names can drift (renderOptions.js).
const optionArgs = renderOptionArgs('buildGenerateArgs', { steps, seed });
const generateScript = trellis2GenerateScript(base);
- const args = textureSize === TRELLIS2_HIGH_QUALITY_TEXTURE_SIZE
- ? [trellis2GenerateRunnerScript(), generateScript, imagePath]
- : [generateScript, imagePath];
+ // The runner adapter is now on EVERY invocation, not just the 4K one. It used
+ // to be conditional because widening `--texture-size` was its only job; it now
+ // also carries the mesh-quality overrides (decimation target, hole filling,
+ // exporter knobs), which apply at every memory tier. Its own flags come first
+ // and are terminated by `--`, after which upstream's argv begins verbatim.
+ const args = [
+ trellis2GenerateRunnerScript(),
+ ...trellis2MeshQualityArgs(meshQuality),
+ generateScript,
+ imagePath,
+ ];
if (outputPath) args.push('--output', trellis2OutputStem(outputPath));
args.push('--pipeline-type', pipelineType);
args.push('--texture-size', String(textureSize));
@@ -735,6 +758,66 @@ export function hfGatedRepoHelp(targetId) {
+ 'and try again.';
}
+/**
+ * Signatures of the macOS **GPU watchdog** killing a long-running Metal kernel
+ * mid-render — the one MPS-only failure mode that is neither a crash nor a setup
+ * problem, and the reason it needs its own classifier.
+ *
+ * The mechanism (documented by the port itself, in `generate.py`'s
+ * `_watchdog_help_message`): when a single Metal dispatch in the SLat decoder runs
+ * long enough, macOS kills the command buffer and prints
+ * `kIOGPUCommandBufferCallbackErrorImpactingInteractivity` to **stderr without
+ * raising a Python exception**. Execution continues over empty tensors and dies
+ * downstream, so the user-visible symptom is a bare non-zero exit after a render
+ * that had already run for many minutes.
+ *
+ * Keyed on the port's own help banner and the two downstream exception texts rather
+ * than on the Metal error itself: the Metal line is emitted early and
+ * `appendTail`'s 4000-char window has usually evicted it by the time the process
+ * exits, whereas the banner is the last thing printed before `sys.exit(2)`. Kept to
+ * phrases that cannot appear in a healthy render, since a false positive would
+ * mislabel an unrelated crash.
+ * @type {(text: string) => boolean}
+ */
+export const isMpsWatchdogError = textMatcher([
+ 'decoder produced an empty mesh',
+ 'macOS GPU watchdog',
+ 'kIOGPUCommandBufferCallbackErrorImpactingInteractivity',
+ 'BVH needs at least 8 triangles',
+]);
+
+/**
+ * What the user can actually do about a watchdog kill.
+ *
+ * Deliberately does NOT repeat the port's own suggestions from
+ * `generate.py:_watchdog_help_message`, two of which are now known not to work.
+ * trellis-mac#8 (M2 Ultra / macOS 26.4.1) records headless-over-SSH with displays
+ * physically unplugged, `SPARSE_CONV_BACKEND=none`, and per-block
+ * `torch.mps.synchronize()` as all TESTED AND FAILED; `MTL_CAPTURE_ENABLED=1` is a
+ * single-source claim that in that same report completed with a shattered mesh. What
+ * is reported to clear it is sleeping the *panel* — mlx#3267, where the env-var-plus-
+ * `pmset displaysleepnow` combination worked and the env var alone did not.
+ *
+ * Also deliberately does NOT tell the user to reduce steps: the watchdog fires on a
+ * single long *dispatch*, not on total render time, so fewer sampler steps shortens
+ * the run without making the offending kernel any shorter. Lowering the pipeline tier
+ * is the knob that actually shrinks the dispatch, which is why that is the one named.
+ *
+ * PortOS does not set `AGX_RELAX_CDM_CTXSTORE_TIMEOUT=1` on the user's behalf: in the
+ * mlx#3267 A/B, relaxing the timeout with the panel awake turned a clean kernel kill
+ * into a hard reboot. Trading a failed render for a lost session is not a default we
+ * get to pick for someone.
+ */
+export const TRELLIS2_WATCHDOG_HELP = 'The macOS GPU watchdog stopped this render: a '
+ + 'single Metal kernel in the shape decoder ran long enough for macOS to kill the '
+ + 'command buffer, which leaves an empty mesh rather than an error. Nothing is wrong '
+ + 'with your install. The mitigation that is actually reported to work is to put the '
+ + 'display to sleep (`pmset displaysleepnow`) and re-run — the watchdog tightens with '
+ + 'window-server load. Merely unplugging external displays, running headless over '
+ + 'SSH, or lowering sampler steps are all reported NOT to help, because the kill '
+ + 'targets one long dispatch rather than the render as a whole. Dropping to a lower '
+ + 'Detail tier does shorten that dispatch.'
+
/**
* Run a single image→GLB generation. The one real-subprocess boundary — GUARDED:
* throws `TRELLIS2_NOT_INSTALLED` unless the model is present, so it can never run
@@ -758,9 +841,22 @@ export function hfGatedRepoHelp(targetId) {
* documents OPAQUE as the default; leaving BLEND active turns prediction noise
* into visible holes in both PortOS and downloaded GLBs.
*
+ * **`decimationTarget`** defaults to the memory-derived tier rather than upstream's
+ * 200K clamp — see `trellis2MeshQuality.js` for why that clamp is now wrong. Pass an
+ * explicit value to override; pass `TRELLIS2_DECIMATION_UPSTREAM_CLAMP` to reproduce
+ * upstream output exactly.
+ *
+ * **`alphaMode`** suppresses the force-opaque post-process when it asks for
+ * transparency. Those two would otherwise fight: telling the exporter to emit BLEND
+ * and then rewriting every BLEND material back to OPAQUE is a silent no-op that
+ * looks like a broken exporter. `null` keeps the historical behaviour (exporter
+ * default + force-opaque normalization).
+ *
* @param {{imagePath: string, outputPath?: string, base?: string, textureSize?: number,
* pipelineType?: string, unifiedMemoryGb?: number,
* steps?: number|null, seed?: number|null,
+ * decimationTarget?: number|null, fillHoles?: boolean, remesh?: boolean,
+ * alphaMode?: string|null,
* onProgress?: (frame: object) => void,
* spawnImpl?: Function, exists?: (p: string) => boolean,
* env?: NodeJS.ProcessEnv, postprocessGlb?: (path: string) => void|Promise<void>}} opts
@@ -775,11 +871,15 @@ export function runTrellis2Generate({
unifiedMemoryGb = Math.round(totalmem() / 1024 ** 3),
steps = null,
seed = null,
+ decimationTarget = null,
+ fillHoles = false,
+ remesh = false,
+ alphaMode = null,
onProgress,
spawnImpl = spawn,
exists = existsSync,
env,
- postprocessGlb = rewriteGlbMaterialsOpaque,
+ postprocessGlb,
} = {}) {
if (!isTrellis2Installed({ base, exists })) {
const err = new Error('TRELLIS.2 is not installed — install it before generating.');
@@ -788,6 +888,8 @@ export function runTrellis2Generate({
}
const resolvedPipelineType = pipelineType ?? selectTrellis2PipelineType(unifiedMemoryGb);
const resolvedTextureSize = textureSize ?? selectTrellis2TextureSize(unifiedMemoryGb);
+ const resolvedDecimationTarget = decimationTarget
+ ?? selectTrellis2DecimationTarget(unifiedMemoryGb, TRELLIS2_HIGH_QUALITY_MIN_MEMORY_GB);
const { command, args } = buildGenerateArgs({
imagePath,
outputPath,
@@ -796,7 +898,21 @@ export function runTrellis2Generate({
pipelineType: resolvedPipelineType,
steps,
seed,
+ meshQuality: {
+ decimationTarget: resolvedDecimationTarget,
+ fillHoles,
+ remesh,
+ alphaMode,
+ },
});
+ // Force-opaque normalization is skipped exactly when the caller asked the
+ // exporter for a transparent material — see the `alphaMode` note above. The
+ // default (`null`) keeps the historical force-opaque behaviour, which still
+ // matters for installs carrying an older o_voxel that auto-promoted to BLEND
+ // off a single low-alpha texel.
+ const wantsTransparency = alphaMode !== null && alphaMode !== 'OPAQUE';
+ const resolvedPostprocess = postprocessGlb
+ ?? (wantsTransparency ? undefined : rewriteGlbMaterialsOpaque);
return runGenerateSubprocess({
command,
args,
@@ -808,11 +924,14 @@ export function runTrellis2Generate({
assetPath: outputPath || null,
onProgress,
spawnImpl,
- postprocessGlb,
+ postprocessGlb: resolvedPostprocess,
// A gated-dependency / HF-auth failure is a user-fixable setup problem, not a
// crash — surface it as such with actionable guidance instead of "exited N".
classifiers: [
{ test: isHfAuthError, code: `${CODE_PREFIX}_HF_AUTH_REQUIRED`, help: () => hfGatedRepoHelp('trellis2') },
+ // MPS-only: the watchdog exits non-zero with no exception, so without this it
+ // reads as a generic crash after a render the user already waited minutes for.
+ { test: isMpsWatchdogError, code: `${CODE_PREFIX}_MPS_WATCHDOG`, help: TRELLIS2_WATCHDOG_HELP },
],
});
}
diff --git a/server/services/imageTo3d/trellis2.test.js b/server/services/imageTo3d/trellis2.test.js
index 86d486dd5a..6194162baa 100644
--- a/server/services/imageTo3d/trellis2.test.js
+++ b/server/services/imageTo3d/trellis2.test.js
@@ -18,6 +18,8 @@ import {
installTrellis2,
isTransientInstallError,
isHfAuthError,
+ isMpsWatchdogError,
+ TRELLIS2_WATCHDOG_HELP,
probeTrellis2TextureBake,
probeMetalToolchain,
TRELLIS2_METAL_BAKE_MODULES,
@@ -36,6 +38,10 @@ import {
selectTrellis2TextureSize,
hfGatedRepoHelp,
} from './trellis2.js';
+import {
+ TRELLIS2_DECIMATION_BASELINE,
+ TRELLIS2_DECIMATION_HIGH,
+} from './trellis2MeshQuality.js';
import { getTarget } from './targets.js';
const flush = () => new Promise((resolve) => setTimeout(resolve, 0));
@@ -80,7 +86,7 @@ describe('buildInstallSteps', () => {
// apple-deps sits between the two for reasons both load-bearing: after the clone
// because `git clone <root>` refuses a non-empty root, before setup.sh because that
// is what makes upstream's `if [ ! -d deps/trellis2-apple ]` guard skip its clone.
- expect(steps.map((s) => s.stage)).toEqual(['clone', 'apple-deps', 'setup']);
+ expect(steps.map((s) => s.stage)).toEqual(['clone', 'apple-deps', 'setup', 'fill-holes-gate']);
expect(steps[0]).toMatchObject({ command: 'git' });
expect(steps[0].args).toContain(TRELLIS2_REPO);
expect(steps[0].args).toContain(trellis2Root(BASE));
@@ -91,21 +97,35 @@ describe('buildInstallSteps', () => {
// toolchain must land BEFORE it runs or those builds fail silently.
it('leads with the Metal Toolchain step when the toolchain is missing but fetchable', () => {
const steps = buildInstallSteps(BASE, { exists: () => false, installMetalToolchain: true });
- expect(steps.map((s) => s.stage)).toEqual(['metal-toolchain', 'clone', 'apple-deps', 'setup']);
+ expect(steps.map((s) => s.stage)).toEqual(['metal-toolchain', 'clone', 'apple-deps', 'setup', 'fill-holes-gate']);
expect(steps[0]).toMatchObject({ command: 'xcodebuild', args: ['-downloadComponent', 'MetalToolchain'] });
});
it('marks the bake-only steps optional — a missing bake degrades output, it does not break it', () => {
- // Only the two bake-dependency steps degrade. The clone and setup.sh stay
- // required, or a real failure would be swallowed.
+ // Only the quality-affecting steps degrade. The clone and setup.sh stay
+ // required, or a real failure would be swallowed. `fill-holes-gate` is
+ // optional because hole filling is opt-in anyway: without the gate the
+ // render behaves exactly as it does today, and asking for --fill-holes on
+ // such a host errors in the runner instead of silently skipping it.
const optionalStages = buildInstallSteps(BASE, { exists: () => false, installMetalToolchain: true })
.filter((s) => s.optional).map((s) => s.stage);
- expect(optionalStages).toEqual(['metal-toolchain', 'apple-deps']);
+ expect(optionalStages).toEqual(['metal-toolchain', 'apple-deps', 'fill-holes-gate']);
});
it('omits the toolchain step by default (already present / not macOS / not fetchable)', () => {
expect(buildInstallSteps(BASE, { exists: () => false }).map((s) => s.stage))
- .toEqual(['clone', 'apple-deps', 'setup']);
+ .toEqual(['clone', 'apple-deps', 'setup', 'fill-holes-gate']);
+ });
+
+ // Ordering is the whole correctness argument for this step: setup.sh runs
+ // patches/mps_compat.py, which is what WRITES the stub the gate rewrites.
+ it('puts the fill-holes gate after setup.sh, under the venv python', () => {
+ const steps = buildInstallSteps(BASE, { exists: () => false });
+ const setupIdx = steps.findIndex((s) => s.stage === 'setup');
+ const gateIdx = steps.findIndex((s) => s.stage === 'fill-holes-gate');
+ expect(gateIdx).toBeGreaterThan(setupIdx);
+ expect(steps[gateIdx].command).toBe(trellis2VenvPython(BASE));
+ expect(steps[gateIdx].args[1]).toBe(trellis2Root(BASE));
});
it('does not let a caller mutate the shared toolchain step template', () => {
@@ -121,7 +141,7 @@ describe('buildInstallSteps', () => {
// begin at the idempotent setup.sh.
const gitDir = join(trellis2Root(BASE), '.git');
const steps = buildInstallSteps(BASE, { exists: (p) => p === gitDir });
- expect(steps.map((s) => s.stage)).toEqual(['apple-deps', 'setup']);
+ expect(steps.map((s) => s.stage)).toEqual(['apple-deps', 'setup', 'fill-holes-gate']);
expect(steps[1]).toMatchObject({ command: 'bash', args: ['setup.sh'], cwd: trellis2Root(BASE) });
});
@@ -193,12 +213,20 @@ describe('trellis2OutputStem', () => {
});
});
+// The runner adapter now fronts EVERY generate invocation (it carries the mesh-quality
+// overrides, not just the 4K atlas widening), and its own flags are terminated by `--`
+// before upstream's argv begins. `head()` is that prefix, so a test asserting on
+// upstream's arguments does not have to restate the adapter's calling convention.
+const head = (base, extra = []) => [
+ trellis2GenerateRunnerScript(), ...extra, '--', trellis2GenerateScript(base),
+];
+
describe('buildGenerateArgs', () => {
it('invokes the venv python with generate.py, the image, and the default texture size', () => {
const { command, args } = buildGenerateArgs({ imagePath: '/data/images/x.png', base: BASE });
expect(command).toBe(trellis2VenvPython(BASE));
expect(args).toEqual([
- trellis2GenerateScript(BASE), '/data/images/x.png',
+ ...head(BASE), '/data/images/x.png',
'--pipeline-type', TRELLIS2_BASELINE_PIPELINE_TYPE,
'--texture-size', String(TRELLIS2_DEFAULT_TEXTURE_SIZE),
]);
@@ -206,7 +234,7 @@ describe('buildGenerateArgs', () => {
it('passes --output as a STEM — the port appends .glb, so a full path would double it', () => {
const { args } = buildGenerateArgs({ imagePath: 'in.png', outputPath: '/out/model.glb', base: BASE });
- expect(args.slice(0, 4)).toEqual([trellis2GenerateScript(BASE), 'in.png', '--output', '/out/model']);
+ expect(args.slice(0, 6)).toEqual([...head(BASE), 'in.png', '--output', '/out/model']);
});
it('defaults direct command building to the proven 2K atlas', () => {
@@ -217,7 +245,7 @@ describe('buildGenerateArgs', () => {
it('honors an explicit texture size', () => {
const { args } = buildGenerateArgs({ imagePath: 'in.png', base: BASE, textureSize: 1024 });
expect(args).toEqual([
- trellis2GenerateScript(BASE), 'in.png',
+ ...head(BASE), 'in.png',
'--pipeline-type', TRELLIS2_BASELINE_PIPELINE_TYPE,
'--texture-size', '1024',
]);
@@ -226,12 +254,34 @@ describe('buildGenerateArgs', () => {
it('uses the compatibility runner for the underlying exporter\'s 4K atlas size', () => {
const { args } = buildGenerateArgs({ imagePath: 'in.png', base: BASE, textureSize: 4096 });
expect(args).toEqual([
- trellis2GenerateRunnerScript(), trellis2GenerateScript(BASE), 'in.png',
+ ...head(BASE), 'in.png',
'--pipeline-type', TRELLIS2_BASELINE_PIPELINE_TYPE,
'--texture-size', '4096',
]);
});
+ it('forwards mesh-quality flags to the adapter, ahead of the `--` separator', () => {
+ const { args } = buildGenerateArgs({
+ imagePath: 'in.png',
+ base: BASE,
+ meshQuality: { decimationTarget: 1000000, fillHoles: true, alphaMode: 'auto' },
+ });
+ expect(args).toEqual([
+ ...head(BASE, ['--decimation-target', '1000000', '--fill-holes', '--alpha-mode', 'auto']),
+ 'in.png',
+ '--pipeline-type', TRELLIS2_BASELINE_PIPELINE_TYPE,
+ '--texture-size', String(TRELLIS2_DEFAULT_TEXTURE_SIZE),
+ ]);
+ });
+
+ it('emits only the separator when no mesh-quality override is requested', () => {
+ // Upstream-identical behaviour has to stay reachable: an empty override set
+ // must not smuggle in a decimation target.
+ const { args } = buildGenerateArgs({ imagePath: 'in.png', base: BASE });
+ expect(args).not.toContain('--decimation-target');
+ expect(args.indexOf('--')).toBe(1);
+ });
+
it('rejects a texture size outside the supported baker sizes instead of letting the render abort', () => {
expect(() => buildGenerateArgs({ imagePath: 'in.png', base: BASE, textureSize: 8192 }))
.toThrow(/textureSize must be one of/);
@@ -489,7 +539,7 @@ describe('runTrellis2Generate', () => {
expect(spawnImpl).toHaveBeenCalledWith(
trellis2VenvPython(BASE),
[
- trellis2GenerateScript(BASE), 'a.png',
+ ...head(BASE, ['--decimation-target', String(TRELLIS2_DECIMATION_BASELINE)]), 'a.png',
'--pipeline-type', TRELLIS2_BASELINE_PIPELINE_TYPE,
'--texture-size', String(TRELLIS2_DEFAULT_TEXTURE_SIZE),
],
@@ -569,10 +619,15 @@ describe('runTrellis2Generate', () => {
const args = spawnImpl.mock.calls[0][1];
expect(args).toContain(TRELLIS2_HIGH_QUALITY_PIPELINE_TYPE);
expect(args).toContain(String(TRELLIS2_HIGH_QUALITY_TEXTURE_SIZE));
- expect(args.slice(0, 2)).toEqual([
+ // High-memory host also gets the high decimation tier, so the runner's own
+ // flags sit between the adapter and the `--` separator.
+ expect(args).toContain(String(TRELLIS2_DECIMATION_HIGH));
+ expect(args.slice(0, 4)).toEqual([
trellis2GenerateRunnerScript(),
- trellis2GenerateScript(BASE),
+ '--decimation-target', String(TRELLIS2_DECIMATION_HIGH),
+ '--',
]);
+ expect(args[4]).toBe(trellis2GenerateScript(BASE));
child.emit('close', 0);
await expect(promise).resolves.toEqual({ assetPath: '/out/a.glb' });
});
@@ -663,7 +718,7 @@ describe('runTrellis2Generate', () => {
expect(spawnImpl).toHaveBeenCalledWith(
trellis2VenvPython(BASE),
[
- trellis2GenerateScript(BASE), 'a.png',
+ ...head(BASE, ['--decimation-target', String(TRELLIS2_DECIMATION_BASELINE)]), 'a.png',
'--pipeline-type', TRELLIS2_BASELINE_PIPELINE_TYPE,
'--texture-size', String(TRELLIS2_DEFAULT_TEXTURE_SIZE),
],
@@ -759,7 +814,93 @@ describe('isHfAuthError', () => {
});
});
+describe('isMpsWatchdogError', () => {
+ // Local copies: the equivalents in the runTrellis2Generate block are scoped to it.
+ const installed = () => true;
+ const makeChild = () => {
+ const child = new EventEmitter();
+ child.stdout = new EventEmitter();
+ child.stderr = new EventEmitter();
+ child.kill = vi.fn();
+ return child;
+ };
+
+ it.each([
+ 'ERROR: The decoder produced an empty mesh.',
+ 'On Apple Silicon this is almost always the macOS GPU watchdog',
+ "Error Domain=MTLCommandBufferErrorDomain Code=4 kIOGPUCommandBufferCallbackErrorImpactingInteractivity",
+ 'AssertionError: BVH needs at least 8 triangles, got 0',
+ ])('flags a watchdog kill: %s', (line) => {
+ expect(isMpsWatchdogError(line)).toBe(true);
+ });
+
+ it.each([
+ 'Baking PBR textures via Metal (4096x4096)...',
+ ' Simplifying mesh: 22,746,188 -> ~1,000,000 faces',
+ 'Mesh: 383,818 vertices, 196,918 triangles',
+ 'GatedRepoError: Access to model facebook/dinov3 is restricted.',
+ '',
+ null,
+ undefined,
+ ])('does NOT flag healthy or unrelated output: %s', (line) => {
+ expect(isMpsWatchdogError(line)).toBe(false);
+ });
+
+ // The help text is the deliverable here: the port's own suggestions include two
+ // remedies independently reported as ineffective, so the wording must not drift
+ // back toward them.
+ it('names sleeping the display and avoids the remedies reported not to work', () => {
+ expect(TRELLIS2_WATCHDOG_HELP).toMatch(/displaysleepnow/);
+ // Single-source claim that produced a shattered mesh in the one report — must
+ // never be offered as advice.
+ expect(TRELLIS2_WATCHDOG_HELP).not.toMatch(/MTL_CAPTURE_ENABLED/);
+ // Unplugging displays and lowering steps may be MENTIONED, but only as things
+ // that do not work — so each has to sit ahead of the "NOT help" clause.
+ const ineffective = TRELLIS2_WATCHDOG_HELP.indexOf('NOT to help');
+ expect(ineffective).toBeGreaterThan(-1);
+ for (const claim of [/unplugging/i, /sampler steps/i, /headless/i]) {
+ const at = TRELLIS2_WATCHDOG_HELP.search(claim);
+ expect(at).toBeGreaterThan(-1);
+ expect(at).toBeLessThan(ineffective);
+ }
+ });
+
+ it('classifies a watchdog exit distinctly from a generic failure', async () => {
+ const child = makeChild();
+ const { promise } = runTrellis2Generate({
+ imagePath: 'a.png',
+ base: BASE,
+ unifiedMemoryGb: 24,
+ exists: installed,
+ spawnImpl: () => child,
+ });
+ child.stdout.emit('data', 'ERROR: The decoder produced an empty mesh.\n');
+ child.emit('close', 2);
+ await expect(promise).rejects.toMatchObject({ code: 'TRELLIS2_MPS_WATCHDOG' });
+ });
+
+ it('leaves an unrecognized failure as the generic code', async () => {
+ const child = makeChild();
+ const { promise } = runTrellis2Generate({
+ imagePath: 'a.png',
+ base: BASE,
+ unifiedMemoryGb: 24,
+ exists: installed,
+ spawnImpl: () => child,
+ });
+ child.stdout.emit('data', 'RuntimeError: something else entirely\n');
+ child.emit('close', 1);
+ await expect(promise).rejects.toMatchObject({ code: 'TRELLIS2_GENERATE_FAILED' });
+ });
+});
+
describe('installTrellis2', () => {
+ // Deliberately larger than the install step count. These tests drive children
+ // positionally and assert exact spawn order, so spare entries are inert — but
+ // pre-sizing to the exact step count meant every added step (apple-deps, then
+ // fill-holes-gate) broke all ten tests at once.
+ const CHILD_POOL = () => Array.from({ length: 8 }, () => makeChild());
+
const makeChild = () => {
const child = new EventEmitter();
child.stdout = new EventEmitter();
@@ -769,7 +910,7 @@ describe('installTrellis2', () => {
};
it('runs each install step in order and emits stage + complete events', async () => {
- const children = [makeChild(), makeChild(), makeChild()];
+ const children = CHILD_POOL();
let i = 0;
const spawnImpl = vi.fn(() => children[i++]);
const events = [];
@@ -785,10 +926,12 @@ describe('installTrellis2', () => {
await flush();
expect(spawnImpl).toHaveBeenNthCalledWith(3, 'bash', ['setup.sh'], { cwd: trellis2Root(BASE) });
children[2].emit('close', 0);
+ await flush();
+ children[3].emit('close', 0); // fill-holes-gate
await expect(promise).resolves.toEqual({ ok: true });
expect(events.filter((e) => e.type === 'stage').map((e) => e.stage))
- .toEqual(['clone', 'apple-deps', 'setup']);
+ .toEqual(['clone', 'apple-deps', 'setup', 'fill-holes-gate']);
expect(events.at(-1)).toMatchObject({ type: 'complete' });
});
@@ -796,7 +939,7 @@ describe('installTrellis2', () => {
// install must verify what landed and report it BEFORE the terminal `complete`
// frame — which closes the client's EventSource (#2952).
const runToCompletion = async (probeBake) => {
- const children = [makeChild(), makeChild(), makeChild()];
+ const children = CHILD_POOL();
let i = 0;
const events = [];
const { promise } = installTrellis2({
@@ -807,6 +950,8 @@ describe('installTrellis2', () => {
children[1].emit('close', 0); // apple-deps
await flush();
children[2].emit('close', 0); // setup
+ await flush();
+ children[3].emit('close', 0); // fill-holes-gate
await promise;
return events;
};
@@ -814,7 +959,7 @@ describe('installTrellis2', () => {
// #3041: the caller (the route) resolves the toolchain situation and passes a
// plain boolean, so installTrellis2 keeps returning { promise, kill } synchronously.
it('downloads the Metal Toolchain first when the caller says it is needed', async () => {
- const children = [makeChild(), makeChild(), makeChild(), makeChild()];
+ const children = CHILD_POOL();
let i = 0;
const spawnImpl = vi.fn(() => children[i++]);
const { promise } = installTrellis2({
@@ -832,13 +977,15 @@ describe('installTrellis2', () => {
children[2].emit('close', 0); // apple-deps
await flush();
children[3].emit('close', 0); // setup
+ await flush();
+ children[4].emit('close', 0); // fill-holes-gate
await expect(promise).resolves.toEqual({ ok: true });
});
it('continues the install when the optional toolchain step fails, and still verifies', async () => {
// Geometry is unaffected by a missing bake, so a host that cannot fetch the
// toolchain must still end up with a working (if degraded) install.
- const children = [makeChild(), makeChild(), makeChild(), makeChild()];
+ const children = CHILD_POOL();
let i = 0;
const events = [];
const { promise } = installTrellis2({
@@ -855,6 +1002,8 @@ describe('installTrellis2', () => {
children[2].emit('close', 0); // apple-deps
await flush();
children[3].emit('close', 0); // setup
+ await flush();
+ children[4].emit('close', 0); // fill-holes-gate
await expect(promise).resolves.toEqual({ ok: true });
expect(events.find((e) => e.stage === 'metal-toolchain' && /Optional step/.test(e.message || ''))).toBeTruthy();
expect(events.find((e) => e.stage === 'verify')?.message).toContain('degraded');
@@ -863,7 +1012,7 @@ describe('installTrellis2', () => {
it('retries a TRANSIENT optional-step failure before giving up on it', async () => {
// Optional-ness must not short-circuit the retry path — a dropped connection
// during the toolchain download deserves the same retries as any other step.
- const children = [makeChild(), makeChild(), makeChild(), makeChild(), makeChild()];
+ const children = CHILD_POOL();
let i = 0;
const spawnImpl = vi.fn(() => children[i++]);
const { promise } = installTrellis2({
@@ -887,11 +1036,13 @@ describe('installTrellis2', () => {
children[3].emit('close', 0); // apple-deps
await flush();
children[4].emit('close', 0); // setup
+ await flush();
+ children[5].emit('close', 0); // fill-holes-gate
await expect(promise).resolves.toEqual({ ok: true });
});
it('still aborts when a REQUIRED step fails, so optional-ness is not blanket', async () => {
- const children = [makeChild(), makeChild()];
+ const children = CHILD_POOL();
let i = 0;
const { promise } = installTrellis2({
base: BASE,
@@ -925,7 +1076,7 @@ describe('installTrellis2', () => {
});
it('spawns install steps under the caller-supplied env, alongside each step cwd', async () => {
- const children = [makeChild(), makeChild(), makeChild()];
+ const children = CHILD_POOL();
let i = 0;
const spawnImpl = vi.fn(() => children[i++]);
const env = { PATH: '/usr/bin', HF_TOKEN: 'hf_test' };
@@ -941,6 +1092,8 @@ describe('installTrellis2', () => {
await flush();
expect(spawnImpl).toHaveBeenNthCalledWith(3, 'bash', ['setup.sh'], { cwd: trellis2Root(BASE), env });
children[2].emit('close', 0);
+ await flush();
+ children[3].emit('close', 0); // fill-holes-gate
await expect(promise).resolves.toEqual({ ok: true });
});
@@ -965,7 +1118,7 @@ describe('installTrellis2', () => {
// Re-running Install after a setup-stage failure must NOT re-clone into the
// existing root; it must go straight to the apple-deps fix and the idempotent
// setup.sh.
- const children = [makeChild(), makeChild()];
+ const children = CHILD_POOL();
let i = 0;
const spawnImpl = vi.fn(() => children[i++]);
const gitDir = join(trellis2Root(BASE), '.git');
@@ -978,12 +1131,14 @@ describe('installTrellis2', () => {
await flush();
expect(spawnImpl).toHaveBeenNthCalledWith(2, 'bash', ['setup.sh'], { cwd: trellis2Root(BASE) });
children[1].emit('close', 0);
+ await flush();
+ children[2].emit('close', 0); // fill-holes-gate
await expect(promise).resolves.toEqual({ ok: true });
});
it('retries a transient network failure in place and succeeds on the retry', async () => {
// clone attempt 1 (transient fail) → clone attempt 2 (ok) → apple-deps → setup
- const children = [makeChild(), makeChild(), makeChild(), makeChild()];
+ const children = CHILD_POOL();
let i = 0;
const spawnImpl = vi.fn(() => children[i++]);
const events = [];
@@ -1002,6 +1157,8 @@ describe('installTrellis2', () => {
children[2].emit('close', 0); // apple-deps
await flush();
children[3].emit('close', 0); // setup
+ await flush();
+ children[4].emit('close', 0); // fill-holes-gate
await expect(promise).resolves.toEqual({ ok: true });
expect(events.some((e) => e.type === 'log' && /retrying/i.test(e.message))).toBe(true);
@@ -1018,7 +1175,7 @@ describe('installTrellis2', () => {
});
it('gives up after maxRetries and surfaces a transient-flagged error', async () => {
- const children = [makeChild(), makeChild()];
+ const children = CHILD_POOL();
let i = 0;
const spawnImpl = vi.fn(() => children[i++]);
const { promise } = installTrellis2({
@@ -1036,7 +1193,7 @@ describe('installTrellis2', () => {
});
it('kill() SIGTERMs the running child and cancels before the next step', async () => {
- const children = [makeChild(), makeChild()];
+ const children = CHILD_POOL();
let i = 0;
const { promise, kill } = installTrellis2({ base: BASE, spawnImpl: () => children[i++] });
kill();