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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: bound MiniMax H3 memory by measured capability instead of one advisory number (#5420)
[._.]/ Adam Eivy934171ab6b01
diff --git a/client/src/components/videoGen/ModelDisclosure.jsx b/client/src/components/videoGen/ModelDisclosure.jsxindex 2e6999a39b..f4051e4516 100644--- a/client/src/components/videoGen/ModelDisclosure.jsx+++ b/client/src/components/videoGen/ModelDisclosure.jsx@@ -19,6 +19,7 @@import { Server, Cloud } from 'lucide-react';import FactLink from './FactLink.jsx';import { formatDownloadGb } from '../../utils/formatters';+import { VIDEO_MEMORY_RESERVE_GB, selectVideoMemoryProfile } from '../../lib/videoGenParams';const UNKNOWN = 'Unknown';@@ -63,6 +64,36 @@ function MemoryFact({ model, systemMemoryGb }) {);}+// Which weight-placement profile this machine will actually get, for a model+// that declares them (#5420 — MiniMax H3 today). This is the HONEST capacity+// fact next to the headline `memoryGb`: that number never accounted for the+// reserve PortOS keeps for the OS, so a machine sitting exactly on it read as a+// fit while a render would have taken the whole box. Renders nothing at all for+// a model with no declared profiles, so no other entry gains a row.+function MemoryProfileFact({ model, systemMemoryGb }) {+ const { profile, usableGb, floorGb } = selectVideoMemoryProfile(model, systemMemoryGb);+ if (floorGb === null) return null;+ return (+ <Fact label="Memory profile">+ {usableGb === null ? (+ <>+ Needs {floorGb} GB usable · <span className="text-gray-500">this system: {UNKNOWN}</span>+ </>+ ) : profile ? (+ <span className="text-port-success">+ {profile.name || profile.id} · needs {profile.minMemoryGb} GB usable, this system has {Math.round(usableGb)} GB+ {' '}after the {VIDEO_MEMORY_RESERVE_GB} GB reserve+ </span>+ ) : (+ <span className="text-port-warning">+ None — the smallest profile needs {floorGb} GB usable and this system has {Math.round(usableGb)} GB+ {' '}after the {VIDEO_MEMORY_RESERVE_GB} GB reserve. Renders are refused rather than started.+ </span>+ )}+ </Fact>+ );+}+export default function ModelDisclosure({backend = 'local',backendDisclosures,@@ -140,6 +171,7 @@ export default function ModelDisclosure({)}<Fact label="Estimated download">{formatDownloadGb(disclosure?.estimatedDownloadGb)}</Fact><MemoryFact model={model} systemMemoryGb={systemMemoryGb} />+ <MemoryProfileFact model={model} systemMemoryGb={systemMemoryGb} /><Fact label="Supported modes">{modes}</Fact><Fact label="Runtime">{model?.runtime || null}</Fact></dl>diff --git a/client/src/components/videoGen/ModelDisclosure.test.jsx b/client/src/components/videoGen/ModelDisclosure.test.jsxindex 6dd2cd365c..4967bc5a8e 100644--- a/client/src/components/videoGen/ModelDisclosure.test.jsx+++ b/client/src/components/videoGen/ModelDisclosure.test.jsx@@ -95,6 +95,47 @@ describe('ModelDisclosure', () => {expect(screen.getByText(/below the stated minimum/)).toBeInTheDocument();});+ // The headline `memoryGb` never accounted for the reserve PortOS holds back,+ // so a machine sitting exactly on it read as a fit while the render would have+ // claimed the whole box. The profile fact is the honest number beside it.+ describe('memory profile (#5420)', () => {+ const PROFILED_MODEL = {+ ...SHIPPED_MODEL,+ memoryGb: 96,+ memoryProfiles: [+ { id: 'rich', name: 'Rich placement', minMemoryGb: 96, minVramGb: 60, unified: false },+ { id: 'lean', name: 'Lean placement', minMemoryGb: 48, minVramGb: 12, unified: false },+ ],+ };++ it('names the best profile the usable memory can hold', () => {+ renderDisclosure({ backend: 'local', model: PROFILED_MODEL, systemMemoryGb: 128 });+ expect(screen.getByText(/Rich placement/)).toBeInTheDocument();+ expect(screen.getByText(/this system has 112 GB/)).toBeInTheDocument();+ });++ it('steps down to a leaner profile once the reserve puts the richer one out of reach', () => {+ renderDisclosure({ backend: 'local', model: PROFILED_MODEL, systemMemoryGb: 96 });+ expect(screen.getByText(/Lean placement/)).toBeInTheDocument();+ });++ it('says renders are refused when nothing fits', () => {+ renderDisclosure({ backend: 'local', model: PROFILED_MODEL, systemMemoryGb: 32 });+ expect(screen.getByText(/Renders are refused rather than started/)).toBeInTheDocument();+ });++ it('says Unknown rather than "too small" when the system memory is unmeasured', () => {+ render(<ModelDisclosure backendDisclosures={BACKENDS} backend="local" model={PROFILED_MODEL} />);+ expect(screen.getByText(/Needs 48 GB usable/)).toBeInTheDocument();+ expect(screen.queryByText(/Renders are refused/)).not.toBeInTheDocument();+ });++ it('renders no profile row at all for a model that declares none', () => {+ renderDisclosure({ backend: 'local', model: SHIPPED_MODEL, systemMemoryGb: 128 });+ expect(screen.queryByText('Memory profile')).not.toBeInTheDocument();+ });+ });+it('renders Unknown for every fact a custom model does not carry', () => {const custom = { id: 'mine', name: 'My Model', source: 'user' };renderDisclosure({ backend: 'local', model: custom });diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 5cba37db25..c108eb75e0 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -77,7 +77,7 @@ grep -i "what you want to do" client/src/lib/README.md| `importerDeepLink.js` | The Importer deep-link contract both ways: `buildImporterLink({ universeId, seriesId, seriesName })` builds the `/importer?…` URL a Series Pipeline page navigates to; `resolveImporterDeepLink(...)` reads those params back into the universe + series names the importer matches on. || `muscriptorModels.js` | `MUSCRIPTOR_MODELS` (audio → MIDI size tiers `small`/`medium`/`large`) + `DEFAULT_MUSCRIPTOR_MODEL`. Single source consumed by the transcribe `<select>`s in `MusicVideo.jsx` and `ReferenceAnalysis.jsx`. Mirrors the server's `MUSCRIPTOR_MODELS` in `server/services/audioMidiTranscription.js`. || `videoFinish.js` | Finish-a-draft gate (#3696). `isReproducibleTextToVideo(record)` is true only for a single text-to-video render whose history record already carries everything a re-render needs — `renderInputsVersion` (the positive marker that its conditioning inventory is trustworthy, so legacy records degrade to not-finishable rather than reading as unconditioned), an empty `conditioning` array, a resolved seed, a real prompt, and no stitched/chained/upscaled provenance. `finishTargetForRecord(record, models)` additionally resolves the draft model's server-declared `finishModelId` against the models this install can actually run, returning the delivery model entry or `null`. Mirrors `finishTargetForModel` in `server/lib/videoFinishProfiles.js`; the pair table itself stays server-side. |-| `videoGenParams.js` | Pure VideoGen param helpers: `FRAME_OPTIONS`/`FPS_OPTIONS`/`VIDEO_EDGE_BOUNDS`/`MAX_CHUNKS`/`CHUNK_OPTIONS`/`DEFAULT_CONTEXT_FRAMES`/`CONTEXT_FRAME_OPTIONS` constants, model-aware frame/fps/resolution-grid normalization, separate mute vs prompt-audio capability checks, `supportsContextWindow(model)` (does this runtime have an extend pipeline to feed a continuation window to — display mirror of `server/lib/videoContinuity.js`, pinned by `server/lib/videoContinuity.parity.test.js`), `videoModelMemoryGb()` (model memory footprint), `computeFflfSafeFrames()` (FFLF/ltx2 pixel-budget back-solve, mirrors `server/services/videoGen/local.js`), and `isModelAllowedForMode()` (a2v + IC-remix → ltx2 gate). Speed profiles (#4875) mirror the conditioner shape: `DEFAULT_SPEED_PROFILE_ID` (must equal `SPEED_PROFILE_DEFAULT_ID` in `server/lib/videoSpeedProfiles.js` — absence and `'quality'` are the same request), `isDefaultSpeedProfileId()` mirrors the server's absence-is-the-default rule, `speedProfilesForModel()` reads the server-decorated `speedProfiles` off the entry, `speedProfilesForMode(model, mode)` applies the SAME mode gate the server's `speedProfileDeclineReason` does (so a profile the server would decline is never offered, nor allowed to lock the dials), `normalizeSpeedProfileForModel()` snaps a selection onto what a just-switched model declares (mode-independent, so switching to fflf hides the picker without rewriting the choice), `speedProfileIdFromRecord()` reads one back out of a history entry / resumed job, `selectedSpeedProfile(id, model, mode)` resolves the profile actually driving the render — what the picker shows and what disables Steps+CFG — and `videoChainChunkModes({ model, mode, chaining, contextFrames, hasSourceImage })` derives the modes a CHAINED request’s chunks will run in (chunk 0 the request’s, chunks 1+ `extend` on a window-continuity chain or `image` on a frame hop), mirroring `generateChainedVideo`’s dispatch and `resolveContinuityStrategy`; `resolveContextFramesForDisplay()` is the absent/invalid→`DEFAULT_CONTEXT_FRAMES` half of `resolveContextFrames` that gate depends on. All pinned by `server/lib/videoSpeedProfiles.parity.test.js`. Also mirrors the IC-LoRA remix registry (`IC_LORA_MODES`/`IC_LORA_MODE_VALUES`/`isIcLoraMode()`/`icLoraSpecForMode()`/`icResolutionIssue()`) from `server/lib/icLoraWeights.js` so the form validates a reference render pre-submit — pinned by `server/lib/icLoraWeights.parity.test.js`. |+| `videoGenParams.js` | Pure VideoGen param helpers: `FRAME_OPTIONS`/`FPS_OPTIONS`/`VIDEO_EDGE_BOUNDS`/`MAX_CHUNKS`/`CHUNK_OPTIONS`/`DEFAULT_CONTEXT_FRAMES`/`CONTEXT_FRAME_OPTIONS` constants, model-aware frame/fps/resolution-grid normalization, separate mute vs prompt-audio capability checks, `supportsContextWindow(model)` (does this runtime have an extend pipeline to feed a continuation window to — display mirror of `server/lib/videoContinuity.js`, pinned by `server/lib/videoContinuity.parity.test.js`), `videoModelMemoryGb()` (model memory footprint), `selectVideoMemoryProfile(model, systemMemoryGb)` + `VIDEO_MEMORY_RESERVE_GB` (#5420 — which declared weight-placement profile this machine can actually hold, out of the `memoryProfiles` the server decorates onto the entry; the floors ride on the model so only the reserve is mirrored, and an unmeasured `systemMemoryGb` returns a `null` usable figure rather than reading as a box that is too small), `computeFflfSafeFrames()` (FFLF/ltx2 pixel-budget back-solve, mirrors `server/services/videoGen/local.js`), and `isModelAllowedForMode()` (a2v + IC-remix → ltx2 gate). Speed profiles (#4875) mirror the conditioner shape: `DEFAULT_SPEED_PROFILE_ID` (must equal `SPEED_PROFILE_DEFAULT_ID` in `server/lib/videoSpeedProfiles.js` — absence and `'quality'` are the same request), `isDefaultSpeedProfileId()` mirrors the server's absence-is-the-default rule, `speedProfilesForModel()` reads the server-decorated `speedProfiles` off the entry, `speedProfilesForMode(model, mode)` applies the SAME mode gate the server's `speedProfileDeclineReason` does (so a profile the server would decline is never offered, nor allowed to lock the dials), `normalizeSpeedProfileForModel()` snaps a selection onto what a just-switched model declares (mode-independent, so switching to fflf hides the picker without rewriting the choice), `speedProfileIdFromRecord()` reads one back out of a history entry / resumed job, `selectedSpeedProfile(id, model, mode)` resolves the profile actually driving the render — what the picker shows and what disables Steps+CFG — and `videoChainChunkModes({ model, mode, chaining, contextFrames, hasSourceImage })` derives the modes a CHAINED request’s chunks will run in (chunk 0 the request’s, chunks 1+ `extend` on a window-continuity chain or `image` on a frame hop), mirroring `generateChainedVideo`’s dispatch and `resolveContinuityStrategy`; `resolveContextFramesForDisplay()` is the absent/invalid→`DEFAULT_CONTEXT_FRAMES` half of `resolveContextFrames` that gate depends on. All pinned by `server/lib/videoSpeedProfiles.parity.test.js`. Also mirrors the IC-LoRA remix registry (`IC_LORA_MODES`/`IC_LORA_MODE_VALUES`/`isIcLoraMode()`/`icLoraSpecForMode()`/`icResolutionIssue()`) from `server/lib/icLoraWeights.js` so the form validates a reference render pre-submit — pinned by `server/lib/icLoraWeights.parity.test.js`. || `videoGenResolutions.js` | Shared resolution presets/default for video generation, model-specific preset/default resolvers (for native canvases such as MiniMax H3), and `snapAspectToImage()` to pick the closest-aspect preset for an I2V source. || `videoGenSubmission.js` | Builds the local, Grok, and federated video-generation request bodies from validated form state, including prompt envelopes and empty-value wire sentinels. || `videoReferenceModes.js` | Mirror of `server/lib/videoReferenceModes.js` (parity enforced by `server/lib/videoReferenceModes.mirror.test.js`) — the i2v reference-mode contract: `I2V_REFERENCE_MODES`, `I2V_REFERENCE_MODE_OPTIONS` (label + the promise sentence `AdvancedParamsPanel` and the source-frame note print), `runtimeSupportsI2vReferenceMode` (gates which options the picker offers), `resolveI2vReferenceStrength` (the effective strength the panel displays), and `i2vReferenceModeViolation` for pre-submit feedback. |diff --git a/client/src/lib/videoGenParams.js b/client/src/lib/videoGenParams.jsindex 7400967dc9..817ca8f093 100644--- a/client/src/lib/videoGenParams.js+++ b/client/src/lib/videoGenParams.js@@ -233,6 +233,46 @@ export const videoModelMemoryGb = (model) => {return match ? Number(match[1]) : Number.POSITIVE_INFINITY;};+// Host RAM PortOS holds back for the operating system and itself before a+// MiniMax H3 render may claim the rest. Mirrors MINIMAX_H3_HOST_RESERVE_GB in+// server/lib/minimaxH3Memory.js — the only number mirrored here, because the+// per-profile floors ride on the model entry the client already fetches.+export const VIDEO_MEMORY_RESERVE_GB = 16;++// The weight-placement profile this machine can hold, out of the ones the model+// declares (#5420). Entries carry `memoryProfiles` best-first, each with an+// honest `minMemoryGb` host floor, so the picker and the disclosure can state+// the capacity a render will REALLY need instead of the single headline+// `memoryGb` that never accounted for what the OS keeps.+//+// Returns `{ profile, usableGb, floorGb }`:+// profile the best profile that fits, or `null` when none does+// usableGb system memory minus the reserve, or `null` when unmeasured — the+// "not measured" sentinel, deliberately distinct from a small number+// so an absent /status field never renders as "this box is too small"+// floorGb the smallest floor any declared profile has, so a UI that has to+// say what it would take has the number+export const selectVideoMemoryProfile = (model, systemMemoryGb) => {+ const profiles = Array.isArray(model?.memoryProfiles)+ ? model.memoryProfiles.filter((profile) => typeof profile?.id === 'string' && profile.id)+ : [];+ const floors = profiles+ .map((profile) => Number(profile.minMemoryGb))+ .filter((floor) => Number.isFinite(floor) && floor > 0);+ const floorGb = floors.length > 0 ? Math.min(...floors) : null;+ const system = Number(systemMemoryGb);+ const usableGb = Number.isFinite(system) && system > 0+ ? Math.max(0, system - VIDEO_MEMORY_RESERVE_GB)+ : null;+ if (profiles.length === 0) return { profile: null, usableGb, floorGb };+ if (usableGb === null) return { profile: profiles[0], usableGb, floorGb };+ const profile = profiles.find((candidate) => {+ const floor = Number(candidate.minMemoryGb);+ return !Number.isFinite(floor) || floor <= 0 || usableGb >= floor;+ }) || null;+ return { profile, usableGb, floorGb };+};+// Mirror of server computeFflfSafeFrames (server/services/videoGen/local.js):// the largest numFrames that fits the FFLF/ltx2 stage-2 pixel-frame budget at// this resolution, rounded down to the LTX 8k+1 latent boundary. The budgetdiff --git a/data.reference/media-models.json b/data.reference/media-models.jsonindex 1aae9c1e8c..52390d7c77 100644--- a/data.reference/media-models.json+++ b/data.reference/media-models.json@@ -260,7 +260,17 @@"Republic of Korea","United States of America"]- }+ },+ "memoryProfiles": [+ {+ "id": "unified-8bit",+ "name": "Unified 8-bit",+ "description": "8-bit quantized DiT with the bf16 Qwen3-VL conditioner, resident in unified memory.",+ "minMemoryGb": 128,+ "minVramGb": null,+ "unified": true+ }+ ]},{"id": "wan22_ti2v_5b",@@ -736,7 +746,33 @@"Republic of Korea","United States of America"]- }+ },+ "memoryProfiles": [+ {+ "id": "bf16",+ "name": "bf16 with CPU offload",+ "description": "Unquantized components swapped by the components manager, with a 12 GB device reserve.",+ "minMemoryGb": 96,+ "minVramGb": 60,+ "unified": false+ },+ {+ "id": "int8-stream",+ "name": "int8, streamed blocks",+ "description": "int8 weight-only quantization with block-level transformer offload streamed onto the card.",+ "minMemoryGb": 96,+ "minVramGb": 20,+ "unified": false+ },+ {+ "id": "int8-lean",+ "name": "int8, leaf-level",+ "description": "int8 weight-only quantization with leaf-level offload for the transformer, conditioner and video VAE.",+ "minMemoryGb": 96,+ "minVramGb": 12,+ "unified": false+ }+ ]}],"defaultMlx": "ltx23_distilled_q4",diff --git a/scripts/_minimax_h3_common.py b/scripts/_minimax_h3_common.pyindex bb3a398a94..19a75016e1 100644--- a/scripts/_minimax_h3_common.py+++ b/scripts/_minimax_h3_common.py@@ -28,6 +28,7 @@ from __future__ import annotationsimport argparseimport json+import osimport sysfrom pathlib import Path@@ -68,9 +69,88 @@ def add_h3_common_args(parser.add_argument("--anchor", action="append", default=[], choices=["first", "last"],help="latent anchor for each --image, in the same order")parser.add_argument("--output", required=True)+ parser.add_argument("--memory-profile", default=None,+ help="id of the weight-placement profile PortOS selected (reported back, not re-derived)")+ parser.add_argument("--min-system-memory-gb", type=float, default=None,+ help="host RAM below which NO declared placement profile can run")+ parser.add_argument("--memory-headroom-gb", type=float, default=0.0,+ help="host RAM held back for the operating system and PortOS itself")return parser+def total_system_memory_gb() -> float | None:+ """Total physical RAM in GB, or None when it could not be measured.++ None is the "not measured" sentinel and is deliberately distinct from a+ small measured number: a probe that fails on an unusual host must not read+ as a box with no memory and refuse a render that would have worked.+ """+ page_size = None+ page_count = None+ if hasattr(os, "sysconf"):+ names = getattr(os, "sysconf_names", {})+ if "SC_PAGE_SIZE" in names and "SC_PHYS_PAGES" in names:+ try:+ page_size = os.sysconf("SC_PAGE_SIZE")+ page_count = os.sysconf("SC_PHYS_PAGES")+ except (OSError, ValueError):+ page_size = page_count = None+ if page_size and page_count and page_size > 0 and page_count > 0:+ return page_size * page_count / 1e9+ if sys.platform == "win32":+ # GlobalMemoryStatusEx is the only stdlib-reachable total on Windows —+ # os.sysconf does not exist there, and the CUDA runner is the lane that+ # actually runs on it.+ import ctypes++ class _MemoryStatusEx(ctypes.Structure):+ _fields_ = [+ ("dwLength", ctypes.c_ulong),+ ("dwMemoryLoad", ctypes.c_ulong),+ ("ullTotalPhys", ctypes.c_ulonglong),+ ("ullAvailPhys", ctypes.c_ulonglong),+ ("ullTotalPageFile", ctypes.c_ulonglong),+ ("ullAvailPageFile", ctypes.c_ulonglong),+ ("ullTotalVirtual", ctypes.c_ulonglong),+ ("ullAvailVirtual", ctypes.c_ulonglong),+ ("ullAvailExtendedVirtual", ctypes.c_ulonglong),+ ]++ status = _MemoryStatusEx()+ status.dwLength = ctypes.sizeof(_MemoryStatusEx)+ if ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(status)):+ return status.ullTotalPhys / 1e9+ return None+++def enforce_system_memory(args) -> float | None:+ """Refuse a render this machine cannot hold, and return the usable RAM.++ H3's components fit nowhere unassisted, so loading them takes minutes to+ hours before an out-of-memory kill would land — long after the job has taken+ the queue. PortOS gates this at submit time too; this is the runner-side+ half, which catches a render that reached the helper by any other route+ (a persisted-queue replay, a retry, a peer submission, a direct call).++ Fails closed only on a MEASURED shortfall: an unmeasurable host returns None+ and the render proceeds, because "the probe returned nothing" is not the+ same fact as "this box has no memory".+ """+ total_gb = total_system_memory_gb()+ if total_gb is None:+ return None+ headroom_gb = max(0.0, args.memory_headroom_gb or 0.0)+ usable_gb = max(0.0, total_gb - headroom_gb)+ minimum = args.min_system_memory_gb+ if minimum is not None and usable_gb < minimum:+ raise SystemExit(+ f"MiniMax H3 needs at least {minimum:.0f} GB of memory for its smallest weight-placement "+ f"profile. This machine has {total_gb:.0f} GB, of which {usable_gb:.0f} GB is usable after "+ f"the {headroom_gb:.0f} GB reserve PortOS keeps for the operating system."+ )+ return usable_gb++def snapshot_root(resolved_file: str | Path, repo_filename: str) -> Path:"""Return the HF snapshot directory containing one resolved repo file."""levels = len(Path(repo_filename).parts)@@ -181,6 +261,8 @@ __all__ = ["FPS","add_h3_common_args","emit_result",+ "enforce_system_memory",+ "total_system_memory_gb","load_keyframes","resolve_cached_snapshot","validate_h3_output_args",diff --git a/scripts/_minimax_h3_common.test.js b/scripts/_minimax_h3_common.test.jsindex d9a6465faf..c71c4c8810 100644--- a/scripts/_minimax_h3_common.test.js+++ b/scripts/_minimax_h3_common.test.js@@ -87,9 +87,50 @@ describe.skipIf(!pyBin)('_minimax_h3_common.py — checkpoint facts shared by bo'image:False:[]','anchor:False:[]','output:True:None',+ // The capacity contract PortOS passes down (#5420). Shared rather than+ // per-runner because both lanes enforce the same host floor before they+ // load anything; only the VRAM half is the CUDA runner's own.+ 'memory_profile:False:None',+ 'min_system_memory_gb:False:None',+ 'memory_headroom_gb:False:0.0',]);});+ // The runner-side half of the capacity gate (#5420). H3's components fit+ // nowhere unassisted, so this has to refuse BEFORE the multi-GB load — and it+ // has to distinguish "measured and short" from "could not measure", because+ // an unreadable capacity probe must not read as a box with no memory.+ describe('enforce_system_memory', () => {+ const enforce = ({ total, minimum, headroom = 16 }) => runPython(`${importShared}\n${[+ 'import argparse',+ `shared.total_system_memory_gb = lambda: ${total === null ? 'None' : `float(${total})`}`,+ `args = argparse.Namespace(min_system_memory_gb=${minimum === null ? 'None' : minimum},`+ + ` memory_headroom_gb=${headroom})`,+ 'try:',+ ' print(f"OK:{shared.enforce_system_memory(args)}")',+ 'except SystemExit as exc:',+ ' print(f"REJECTED:{exc}")',+ ].join('\n')}`).trim();++ it('refuses a measured box below the floor once the reserve is taken out', () => {+ // 128 GB nameplate against a 128 GB floor used to read as a fit; it is+ // 112 GB usable, which is the number the render actually gets.+ expect(enforce({ total: 128, minimum: 128 })).toMatch(/^REJECTED:.*at least 128 GB.*112 GB is usable/);+ });++ it('accepts a box with the floor still free after the reserve', () => {+ expect(enforce({ total: 144, minimum: 128 })).toBe('OK:128.0');+ });++ it('proceeds, rather than refusing, when the host could not be measured', () => {+ expect(enforce({ total: null, minimum: 128 })).toBe('OK:None');+ });++ it('is a no-op when PortOS passed no floor', () => {+ expect(enforce({ total: 8, minimum: null })).toBe('OK:0.0');+ });+ });+it('states the fixed fps and frame grid once', () => {const output = lines(runPython(`${importShared}\n${['print(f"{shared.FPS},{shared.FRAME_MODULUS},{shared.FRAME_REMAINDER}")',diff --git a/scripts/generate_minimax_h3.py b/scripts/generate_minimax_h3.pyindex e6315d65c2..d84c6f6684 100644--- a/scripts/generate_minimax_h3.py+++ b/scripts/generate_minimax_h3.py@@ -9,6 +9,14 @@ joint video-and-audio MP4.Conditioning is H3's own `fl2va` keyframe path: zero images is text-to-video,one `--image first` is image-to-video, and a `first` + `last` pair is FFLF.Each `--image` needs its own `--anchor`, in the same order.++Memory: unified memory means this render and the rest of the machine draw on one+pool. PortOS passes the host floor its declared placement profile needs+(`--min-system-memory-gb`) and the reserve it holds back for the operating+system (`--memory-headroom-gb`); `enforce_system_memory` refuses a box below the+floor before any weight is read, and `apply_memory_limit` caps MLX's allocator+at the rest so a render that overruns fails as a job instead of wedging the+machine."""from __future__ import annotations@@ -30,8 +38,8 @@ from _runner_common import ( # noqa: E402write_stepwise_preview,)from _minimax_h3_common import ( # noqa: E402- FPS, add_h3_common_args, emit_result, load_keyframes, resolve_cached_snapshot,- validate_h3_output_args,+ FPS, add_h3_common_args, emit_result, enforce_system_memory, load_keyframes,+ resolve_cached_snapshot, total_system_memory_gb, validate_h3_output_args,)from _minimax_h3_mlx_pins import ( # noqa: E402pinned_encoder_hook, verify_pinned_encode_source,@@ -74,6 +82,58 @@ def parse_args() -> argparse.Namespace:return parser.parse_args()+def apply_memory_limit(args: argparse.Namespace, vision_loaded: bool) -> None:+ """Cap MLX's allocator at the machine's RAM minus PortOS's reserve.++ Unified memory means an H3 render and the rest of the machine draw on the+ same pool, and MLX's default limit is the whole of it. A render that grows+ into the last gigabyte does not fail on its own — it takes PortOS, Postgres+ and the desktop down with it, and what the user sees is a hung machine+ rather than a failed job. An explicit limit converts that into an+ out-of-memory error the runner reports normally.++ Best-effort by design: the limit setters have moved between `mx` and+ `mx.metal` across MLX releases and the wired limit is Metal-only, so each is+ probed rather than assumed. A pin without them still renders — it just keeps+ the old unbounded behaviour, which is what it had before this existed.+ """+ total_gb = total_system_memory_gb()+ headroom_gb = max(0.0, args.memory_headroom_gb or 0.0)+ if total_gb is None:+ print(+ f"STATUS:MiniMax H3 placement: {args.memory_profile or 'unified'} "+ f"· host memory unknown, allocator left unbounded "+ f"· vision tower {'loaded' if vision_loaded else 'skipped'}",+ file=sys.stderr, flush=True,+ )+ return+ limit_gb = max(1.0, total_gb - headroom_gb)+ limit_bytes = int(limit_gb * 1e9)++ import mlx.core as mx++ applied = []+ for module, name in ((mx, "set_memory_limit"), (getattr(mx, "metal", None), "set_memory_limit")):+ setter = getattr(module, name, None)+ if setter is not None:+ setter(limit_bytes)+ applied.append("allocator")+ break+ for module, name in ((mx, "set_wired_limit"), (getattr(mx, "metal", None), "set_wired_limit")):+ setter = getattr(module, name, None)+ if setter is not None:+ setter(limit_bytes)+ applied.append("wired")+ break+ placement = ", ".join(applied) if applied else "no limit lever on this MLX build"+ print(+ f"STATUS:MiniMax H3 placement: {args.memory_profile or 'unified'} "+ f"· {limit_gb:.0f} GB of {total_gb:.0f} GB (reserve {headroom_gb:.0f} GB) [{placement}] "+ f"· vision tower {'loaded' if vision_loaded else 'skipped'}",+ file=sys.stderr, flush=True,+ )++def require_ffmpeg() -> str:"""Fail before loading tens of GB of weights when muxing cannot succeed.@@ -592,6 +652,15 @@ def main() -> int:require_ffmpeg()+ # Capacity before anything is loaded. PortOS gates this at submit time too;+ # this is the runner-side half, which also catches a render that reached the+ # helper by another route (a persisted-queue replay, a retry, a direct call).+ enforce_system_memory(args)+ # `images` decides whether the Qwen3-VL vision tower loads at all, so the+ # placement report can state what is actually resident rather than what the+ # entry could hold in the worst case.+ apply_memory_limit(args, vision_loaded=bool(images))+runtime_dir = Path(args.runtime_dir).resolve()verify_runtime_checkout(runtime_dir, args.runtime_revision)diff --git a/scripts/generate_minimax_h3_cuda.py b/scripts/generate_minimax_h3_cuda.pyindex ad8345912c..287db866d8 100644--- a/scripts/generate_minimax_h3_cuda.py+++ b/scripts/generate_minimax_h3_cuda.py@@ -19,8 +19,11 @@ Each `--image` needs its own `--anchor`, in the same order.Memory: the bf16 components are 66.3 GB (transformer) + 66.7 GB (Qwen3-VLconditioner), so nothing fits on a consumer card unquantized. The offload-profiles below are the recipes upstream documents, chosen from the card's own-VRAM unless `--offload-profile` pins one.+profiles below are the recipes upstream documents, sized from the card's own+VRAM unless `--offload-profile` pins one — and every recipe, pinned or not, is+checked against `PROFILE_MIN_VRAM_GB` plus the host floor PortOS passes on+`--min-system-memory-gb`. Both gates run BEFORE the multi-GB load, so a box that+cannot hold this model says so in seconds rather than being killed an hour in."""from __future__ import annotations@@ -32,8 +35,8 @@ from pathlib import Pathsys.path.insert(0, str(Path(__file__).resolve().parent))from _runner_common import emit_runtime_fingerprint, establish_process_group, heartbeat # noqa: E402from _minimax_h3_common import ( # noqa: E402- FPS, add_h3_common_args, emit_result, load_keyframes, resolve_cached_snapshot,- validate_h3_output_args,+ FPS, add_h3_common_args, emit_result, enforce_system_memory, load_keyframes,+ resolve_cached_snapshot, validate_h3_output_args,)@@ -46,6 +49,27 @@ MIN_FRAMES = 124 # first 17n+5 grid point at or above 5 secondsMAX_FRAMES = 345 # last 17n+5 grid point at or below 15 secondsOFFLOAD_PROFILES = ("auto", "bf16", "int8-stream", "int8-lean")+# Device-VRAM floor per recipe, richest first. This is the same table PortOS+# declares in server/lib/minimaxH3Memory.js (pinned by runtimes.test.js), and it+# is now a FLOOR rather than a one-way ladder: a card below the leanest entry+# gets a clean error naming what it would take, instead of the leanest recipe+# and an out-of-memory kill an hour into the load. An explicitly pinned profile+# is checked against it too — the registry entry syncs between peers and can+# name a recipe the card on this end cannot run.+#+# bf16 60 — the floor for holding one bf16 component resident while+# the components manager swaps the other+# int8-stream 20 — below this a streamed transformer block plus its+# activations stops fitting beside the video VAE+# int8-lean 12 — the documented 12-16 GB card path, and the last recipe+# there is+PROFILE_MIN_VRAM_GB = (("bf16", 60), ("int8-stream", 20), ("int8-lean", 12))++# Device memory the bf16 recipe leaves free for activations while the components+# manager swaps a component in. Paired with the 60 GB floor above — the floor is+# what makes this reserve affordable, so the two move together.+BF16_DEVICE_RESERVE = "12GB"+# int8 weight-only quantization must skip the projection / embedding / norm# layers on each component — they are small, numerically sensitive, and# quantizing them is what degrades the output rather than saving memory. These@@ -93,13 +117,18 @@ def validate_args(args: argparse.Namespace) -> None:raise SystemExit("MiniMax H3 needs its pinned component file list (--repo-file).")-def resolve_offload_profile(requested: str) -> str:- """Pick a weight-placement recipe from the visible CUDA device's VRAM.+def resolve_offload_profile(requested: str) -> tuple[str, float]:+ """Pick a weight-placement recipe the visible CUDA device can actually run.++ Returns the effective profile and the device's total VRAM, so the caller can+ report the placement it really got rather than only the name it asked for.- An explicit request always wins — the registry entry can pin one, and a user- who knows their box better than a capacity heuristic does should not be- overridden. 'auto' is the default because the entry is shared across every- install that syncs it and cannot know what GPU is on the other end.+ An explicit request still expresses intent — a user who knows their box+ better than a capacity heuristic does should not be silently overridden —+ but it no longer bypasses the check: the registry entry carrying it syncs+ between peers and cannot know what GPU is on this end, so a pin the card+ cannot hold is refused up front instead of OOMing after the load. 'auto'+ remains the shipped default for exactly that reason."""import torch@@ -107,16 +136,29 @@ def resolve_offload_profile(requested: str) -> str:raise RuntimeError("MiniMax H3 CUDA needs a visible NVIDIA device. Repair the MiniMax H3 CUDA runtime from Video Gen.")- if requested != "auto":- return requestedtotal_gb = torch.cuda.get_device_properties(0).total_memory / 1e9- # 60 GB is the floor for holding one bf16 component resident while the- # manager swaps the other; below it, int8 is the only thing that fits.- # 20 GB is where streamed block-level offload stops fitting a block plus- # its activations, and the leaner leaf-level recipe takes over.- if total_gb >= 60:- return "bf16"- return "int8-stream" if total_gb >= 20 else "int8-lean"+ affordable = [name for name, floor in PROFILE_MIN_VRAM_GB if total_gb >= floor]+ if requested != "auto":+ floor = dict(PROFILE_MIN_VRAM_GB).get(requested)+ if floor is not None and total_gb < floor:+ alternative = (+ f"This card can run the {affordable[0]} profile."+ if affordable+ else f"No MiniMax H3 profile runs on under {PROFILE_MIN_VRAM_GB[-1][1]} GB of VRAM."+ )+ raise RuntimeError(+ f"MiniMax H3 offload profile '{requested}' needs {floor} GB of VRAM; this device has "+ f"{total_gb:.0f} GB. {alternative} Change offloadProfile on the model entry, or remove it "+ f"to let PortOS size a recipe from the card."+ )+ return requested, total_gb+ if not affordable:+ raise RuntimeError(+ f"MiniMax H3 needs at least {PROFILE_MIN_VRAM_GB[-1][1]} GB of VRAM for its leanest weight "+ f"placement; this device has {total_gb:.0f} GB. Render on a peer with a larger card, or pick a "+ f"smaller model."+ )+ return affordable[0], total_gbdef load_pipeline(snapshot: Path, profile: str):@@ -134,7 +176,7 @@ def load_pipeline(snapshot: Path, profile: str):manager = ComponentsManager()pipe = ModularPipeline.from_pretrained(str(snapshot), components_manager=manager)pipe.load_components(workflow="fl2va", dtype=torch.bfloat16)- manager.enable_auto_cpu_offload(device="cuda", memory_reserve_margin="12GB")+ manager.enable_auto_cpu_offload(device="cuda", memory_reserve_margin=BF16_DEVICE_RESERVE)return pipefrom diffusers import MiniMaxH3Transformer3DModel, TorchAoConfig@@ -228,8 +270,18 @@ def main() -> int:extra_versions={"cuda": getattr(torch.version, "cuda", None)},)- profile = resolve_offload_profile(args.offload_profile)- log(f"STATUS:MiniMax H3 CUDA offload profile: {profile}")+ # Both halves of the capacity gate, before the multi-GB load rather than+ # after it: the host floor (which is where the int8 recipes keep ~75 GB of+ # weights resident for the whole render) and the device floor.+ usable_host_gb = enforce_system_memory(args)+ profile, vram_gb = resolve_offload_profile(args.offload_profile)+ host_report = "host memory unknown" if usable_host_gb is None else f"{usable_host_gb:.0f} GB usable host memory"+ log(+ f"STATUS:MiniMax H3 CUDA placement: {profile} "+ f"({'pinned' if args.offload_profile != 'auto' else 'auto'}) "+ f"· {vram_gb:.0f} GB VRAM · {host_report} "+ f"(reserve {max(0.0, args.memory_headroom_gb or 0.0):.0f} GB)"+ )log("STAGE:load-pipeline")with heartbeat("minimax-h3-cuda-load"):diff --git a/scripts/generate_minimax_h3_cuda.test.js b/scripts/generate_minimax_h3_cuda.test.jsindex 182f88832b..2dd85e2a9f 100644--- a/scripts/generate_minimax_h3_cuda.test.js+++ b/scripts/generate_minimax_h3_cuda.test.js@@ -95,7 +95,7 @@ describe.skipIf(!pyBin)('generate_minimax_h3_cuda.py', () => {expect(output[2]).toBe('{}');});- it('sizes the offload recipe from VRAM, and lets an explicit profile win', () => {+ it('sizes the offload recipe from VRAM, and honors an affordable pin', () => {const output = lines(runPython(`${importRunner}\n${['import types','fake = types.ModuleType("torch")',@@ -105,9 +105,9 @@ describe.skipIf(!pyBin)('generate_minimax_h3_cuda.py', () => {')','sys.modules["torch"] = fake','for TOTAL_GB in (80, 32, 24, 16, 12):',- ' print(f"{TOTAL_GB}:{runner.resolve_offload_profile(\'auto\')}")',- 'TOTAL_GB = 12',- "print('pinned:' + runner.resolve_offload_profile('bf16'))",+ ' print(f"{TOTAL_GB}:{runner.resolve_offload_profile(\'auto\')[0]}")',+ 'TOTAL_GB = 80',+ "print('pinned:' + runner.resolve_offload_profile('int8-lean')[0])",].join('\n')}`));expect(output).toEqual(['80:bf16',@@ -115,13 +115,37 @@ describe.skipIf(!pyBin)('generate_minimax_h3_cuda.py', () => {'24:int8-stream','16:int8-lean','12:int8-lean',- // An explicit request always wins: the registry entry is shared across- // every install that syncs it and can't know the GPU on the other end,- // but a user who pins one knows their box better than the heuristic.- 'pinned:bf16',+ // A pin the card can afford still wins over the heuristic: a user who+ // sets one knows their box better than a capacity table does, and a+ // leaner recipe on a big card is a legitimate choice.+ 'pinned:int8-lean',]);});+ // Both of these used to succeed and then die out of memory an hour into the+ // load — the leanest recipe was returned for any card, and a pin was returned+ // without ever being checked against the device (#5420).+ it('refuses a card below every recipe, and a pin the card cannot hold', () => {+ const output = lines(runPython(`${importRunner}\n${[+ 'import types',+ 'fake = types.ModuleType("torch")',+ 'fake.cuda = types.SimpleNamespace(',+ ' is_available=lambda: True,',+ ' get_device_properties=lambda i: types.SimpleNamespace(total_memory=int(TOTAL_GB * 1e9)),',+ ')',+ 'sys.modules["torch"] = fake',+ 'for TOTAL_GB, requested in ((8, "auto"), (12, "bf16")):',+ ' try:',+ ' runner.resolve_offload_profile(requested)',+ ' print("ACCEPTED")',+ ' except RuntimeError as exc:',+ ' print(f"REFUSED:{exc}")',+ ].join('\n')}`));+ expect(output[0]).toMatch(/^REFUSED:.*at least 12 GB of VRAM/);+ // The message names the recipe this card CAN run, so the fix is obvious.+ expect(output[1]).toMatch(/^REFUSED:.*needs 60 GB of VRAM.*can run the int8-lean profile/);+ });+it('refuses to run when no CUDA device is visible', () => {// A CPU-only torch wheel installs cleanly on Windows and would otherwise// just render unusably slowly instead of saying what is wrong.diff --git a/scripts/migrations/317-minimax-h3-memory-profiles.js b/scripts/migrations/317-minimax-h3-memory-profiles.jsnew file mode 100644index 0000000000..7bbb9ff2b0--- /dev/null+++ b/scripts/migrations/317-minimax-h3-memory-profiles.js@@ -0,0 +1,72 @@+/**+ * Attach `memoryProfiles` to the shipped MiniMax H3 entries (issue #5420) in+ * existing installs.+ *+ * `data.reference/media-models.json` ships the table for fresh installs and+ * `mediaModels.js` backfills it at load — but `data/media-models.json` is the+ * gitignored, user-editable copy that is never merge-updated, so this migration+ * makes the change durable on disk instead of relying on the in-memory backfill+ * running every boot. Same arrangement as migration 295 (speed profiles), 237+ * (disclosures) and 238 (Finish edges).+ *+ * Preservation contract (identical to `applyMiniMaxH3MemoryProfiles`):+ * - an entry that already has a `memoryProfiles` key is left alone (user+ * edit, including an explicit `null` / `[]`)+ * - an id the user deleted is NOT recreated+ * - a custom / user-added model is untouched (no shipped table exists)+ * - an entry whose `repo` OR `revision` was re-pointed is skipped — a+ * capacity claim must not be made for weights we did not validate against+ * - entry order is preserved; nothing else on the entry is modified+ *+ * Additive only: an entry the sanitizer merely STRIPPED is never rewritten, so+ * a hand-edited bad table is left for the load-time sanitizer to warn about+ * rather than being silently deleted from the user's file here.+ */++import { readFile } from 'fs/promises';+import { join } from 'path';+import { atomicWrite } from '../../server/lib/fileUtils.js';+import { applyMiniMaxH3MemoryProfiles } from '../../server/lib/minimaxH3Memory.js';+import { LEGACY_VIDEO_BUCKET_KEYS, VIDEO_BUCKETS } from '../../server/lib/mediaModelBuckets.js';++const REL_PATH = 'data/media-models.json';+// Both the canonical (#4142) and the legacy bucket spellings — an install that+// predates the rename can still be on either shape. Only keys actually holding+// an array are touched, so listing all four is safe on both.+const BUCKET_KEYS = [...VIDEO_BUCKETS, ...Object.values(LEGACY_VIDEO_BUCKET_KEYS)];++export default {+ async up({ rootDir }) {+ const path = join(rootDir, REL_PATH);+ const raw = await readFile(path, 'utf-8').catch((err) => {+ if (err.code === 'ENOENT') return null;+ throw err;+ });+ if (raw == null) return;+ let config;+ try {+ config = JSON.parse(raw);+ } catch (err) {+ throw new Error(`Cannot migrate ${REL_PATH}: invalid JSON (${err.message})`, { cause: err });+ }+ if (!config?.video || typeof config.video !== 'object') return;++ let profiled = 0;+ for (const platform of BUCKET_KEYS) {+ const list = config.video[platform];+ if (!Array.isArray(list)) continue;+ const next = applyMiniMaxH3MemoryProfiles(list);+ config.video[platform] = list.map((entry, i) => {+ const gained = Array.isArray(next[i]?.memoryProfiles) && !(entry && 'memoryProfiles' in entry);+ if (!gained) return entry;+ profiled += 1;+ return next[i];+ });+ }++ if (profiled > 0) {+ await atomicWrite(path, `${JSON.stringify(config, null, 2)}\n`);+ console.log(`📝 ${REL_PATH}: attached memory profiles to ${profiled} video ${profiled === 1 ? 'entry' : 'entries'}`);+ }+ },+};diff --git a/scripts/migrations/317-minimax-h3-memory-profiles.test.js b/scripts/migrations/317-minimax-h3-memory-profiles.test.jsnew file mode 100644index 0000000000..ffee1c2db9--- /dev/null+++ b/scripts/migrations/317-minimax-h3-memory-profiles.test.js@@ -0,0 +1,107 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { mkdtempSync, readFileSync, rmSync, writeFileSync, mkdirSync, existsSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++import migration from './317-minimax-h3-memory-profiles.js';+import { MINIMAX_H3_MEMORY_PROFILES } from '../../server/lib/minimaxH3Memory.js';++const writeJson = (path, value) => writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`);+const readJson = (path) => JSON.parse(readFileSync(path, 'utf-8'));++const MLX_ID = 'minimax_h3_8bit';+const CUDA_ID = 'minimax_h3_cuda';+const mlxSpec = MINIMAX_H3_MEMORY_PROFILES[MLX_ID];+const cudaSpec = MINIMAX_H3_MEMORY_PROFILES[CUDA_ID];++// The registry as an existing install stores it, pre-migration — on the LEGACY+// bucket spellings, which is the shape a pre-#4142 install is still on.+const baseRegistry = (overrides = {}) => ({+ video: {+ macos: [+ {+ id: MLX_ID,+ name: 'MiniMax H3 MLX 8-bit',+ repo: mlxSpec.shippedRepo,+ revision: mlxSpec.shippedRevision,+ runtime: 'minimax_h3',+ memoryGb: 128,+ ...overrides,+ },+ { id: 'my_custom_model', name: 'My Custom Model', repo: 'example-org/example-video', source: 'user' },+ ],+ windows: [{+ id: CUDA_ID,+ name: 'MiniMax H3 CUDA int8',+ repo: cudaSpec.shippedRepo,+ revision: cudaSpec.shippedRevision,+ runtime: 'minimax_h3_cuda',+ memoryGb: 96,+ }],+ defaultMacos: MLX_ID,+ },+});++const findMacos = (path, id) => readJson(path).video.macos.find((entry) => entry.id === id);++describe('migration 317 — MiniMax H3 memory profiles', () => {+ let rootDir;+ let path;++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-317-'));+ mkdirSync(join(rootDir, 'data'), { recursive: true });+ path = join(rootDir, 'data', 'media-models.json');+ });++ afterEach(() => {+ rmSync(rootDir, { recursive: true, force: true });+ vi.restoreAllMocks();+ });++ it('attaches the shipped table to both H3 entries across bucket spellings', async () => {+ writeJson(path, baseRegistry());+ await migration.up({ rootDir });+ expect(findMacos(path, MLX_ID).memoryProfiles).toEqual([...mlxSpec.profiles]);+ expect(readJson(path).video.windows[0].memoryProfiles).toEqual([...cudaSpec.profiles]);+ });++ it('leaves everything else on the entry, and its position, untouched', async () => {+ const before = baseRegistry();+ writeJson(path, before);+ await migration.up({ rootDir });+ const after = readJson(path);+ expect(after.video.macos.map((entry) => entry.id)).toEqual(before.video.macos.map((entry) => entry.id));+ const { memoryProfiles: _added, ...rest } = after.video.macos[0];+ expect(rest).toEqual(before.video.macos[0]);+ expect(after.video.macos[1]).toEqual(before.video.macos[1]);+ });++ it('preserves a user value, including a deliberate empty list', async () => {+ writeJson(path, baseRegistry({ memoryProfiles: [] }));+ await migration.up({ rootDir });+ expect(findMacos(path, MLX_ID).memoryProfiles).toEqual([]);+ });++ it('skips an entry re-pointed off the pinned weights', async () => {+ writeJson(path, baseRegistry({ revision: 'deadbeefdeadbeef' }));+ await migration.up({ rootDir });+ expect(findMacos(path, MLX_ID)).not.toHaveProperty('memoryProfiles');+ });++ it('is a no-op on a fresh install with no registry file yet', async () => {+ await expect(migration.up({ rootDir })).resolves.toBeUndefined();+ expect(existsSync(path)).toBe(false);+ });++ it('rewrites nothing when every entry already carries the key', async () => {+ writeJson(path, baseRegistry({ memoryProfiles: [...mlxSpec.profiles] }));+ const before = readFileSync(path, 'utf-8');+ // The CUDA entry still gains one, so assert idempotence on a second pass.+ await migration.up({ rootDir });+ const once = readFileSync(path, 'utf-8');+ await migration.up({ rootDir });+ expect(readFileSync(path, 'utf-8')).toBe(once);+ expect(once).not.toBe(before);+ });+});diff --git a/server/lib/README.md b/server/lib/README.mdindex 7f31b24729..0d1982d804 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -148,6 +148,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `promptPartials.js` | Mustache-style partial expansion. || `mediaModelBuckets.js` | Names and resolves the video registry's two model buckets (#4142). The split is by RUNTIME FAMILY — `mlx` (Apple MLX runtimes) vs `cuda` (plain torch+CUDA, which runs on Windows *and* Linux) — not by operating system, which is why `activeVideoBucket()` keys on `process.platform === 'darwin'` instead of on "is this Windows". `readVideoBucket` / `readVideoDefault` / `matchesVideoBucket` resolve the canonical key first and fall back to the pre-#4142 `macos` / `windows` / `defaultMacos` / `defaultWindows` spellings, so any registry written by an older install still loads untouched; `canonicalizeVideoBuckets` performs the one-time rename (migration 270 and the load-time twin in `mediaModels.js`). Kept separate from `mediaModels.js` so `scripts/migrations/` can share the alias resolution without importing the registry loader, which seeds `data/` as a side effect. || `mediaModels.js` | Single source of truth for image/video model metadata. Entry fields are documented in the module docblock — note `repoFiles[]`, which narrows a model's own repo to an explicit file list for an aggregate repo that holds far more than the runner loads (MiniMax H3 CUDA). |+| `minimaxH3Memory.js` | The declared weight-placement table for the two MiniMax H3 entries (#5420) — H3 is the one video model whose components fit nowhere unassisted, so "does this box have enough" is a render gate, not a UI fact. `MINIMAX_H3_MEMORY_PROFILES` maps entry id → `{ shippedRepo, shippedRevision, profiles }`, each profile carrying an honest `minMemoryGb` host floor and (CUDA only) a `minVramGb` device floor, ordered best-first. Every capacity number is HOISTED from what already existed — the CUDA tiers are `resolve_offload_profile()`'s own thresholds in `scripts/generate_minimax_h3_cuda.py`, the host floors are the entries' `memoryGb` — the sole new number being `MINIMAX_H3_HOST_RESERVE_GB`, a policy reserve held back for the OS. `applyMiniMaxH3MemoryProfiles(list)` is the load-time backfill (twin of migration 317) and guards BOTH `repo` and `revision`, like the speed-profile decorator. `selectMiniMaxH3MemoryProfile({ model, totalMemoryGb })` picks the best profile the HOST can hold (VRAM is the runner's call — the server has no synchronous device view); `miniMaxH3MemoryDeclineReason()` RETURNS the fail-closed reason so the render path can 400 it and a status surface can show it, and returns `null` on an UNMEASURED host — "not measured" is a deferral to the runner, never the same as zero. `validateMiniMaxH3MemoryProfileTable` / `sanitizeMiniMaxH3MemoryProfiles` warn + strip a hand-edited table (NaN floor, duplicate/reserved id, mis-ordered tiers) at load. || `videoContinuity.js` | How chunk N+1 of a chained video render is conditioned on chunk N. `resolveContextFrames(requested)` normalizes the tail-window size (absent → `DEFAULT_CONTEXT_FRAMES` = 22 ≈ 1s @ 24fps; an explicit `0` is preserved as "last frame only", NOT collapsed into the default) and clamps to `MIN_CONTEXT_FRAMES`..`MAX_CONTEXT_FRAMES`. `resolveContinuityStrategy({model, contextFrames})` picks `'window'` (LTX-2 `extend_from_video` conditioned on the prior chunk's last N frames — motion, not just a pose) or `'frame'` (extract the last frame, run i2v), degrading to `'frame'` on any runtime outside `CONTEXT_WINDOW_RUNTIMES` rather than rejecting. `extendLatentFrames` / `extendedPixelFrames` convert across the VAE's `LATENT_FRAME_STRIDE` (8 pixel frames per latent), `contextPrefixFrames({totalFrames, extendLatents})` measures how much of an extend render is echoed context to trim back off before stitching (0 = leave it alone), and `tailWindowStartFrame` gives the cut index for the window itself. Pure — importable from `prepareParams.js` without dragging in `local.js`. Mirrored for the picker in `client/src/lib/videoGenParams.js`, pinned by `videoContinuity.parity.test.js`. || `videoDisclosure.js` | Video Gen provenance/licensing + backend policy-scope facts (#3674). `VIDEO_MODEL_DISCLOSURES` maps each shipped video model id to `{ shippedRepo, disclosure }` (model card URL, weights license, runtime license, pinned-snapshot download size in decimal GB, review date) — every value checked against a primary upstream source, and any fact that could not be established is OMITTED so the UI renders "Unknown" instead of guessing. `applyVideoDisclosures(list)` is the load-time backfill (twin of migration 237) with the same preservation guards: an existing `disclosure` key wins, a custom id is skipped, and a `repo` pointed at a fork keeps Unknown. `VIDEO_BACKEND_DISCLOSURES` / `videoBackendDisclosure(id)` state where inference runs (`execution: local or hosted`) and whose policy applies — execution facts only, never a restrictiveness ranking. `APACHE_2` / `GEMMA_TERMS` are the shared license descriptors `videoTextEncoders.js` reuses, so a license-text correction reaches both tables from one edit. || `videoFinishProfiles.js` | Draft → delivery ("Finish") relationships between video models (#3696). `VIDEO_FINISH_PROFILES` declares each fast draft entry id → `{ shippedRepo, finishModelId }`, only for pairs that share a runtime, base repo and supported modes (the same weights at a different step budget), so re-rendering the draft's seed reproduces its composition instead of re-rolling it. `applyVideoFinishProfiles(list)` is the load-time backfill (twin of migration 238) with the usual preservation guards (existing key wins, custom id skipped, forked `repo` skipped); `validateFinishProfileGraph(list)` returns the graph problems (missing / self-referencing / chained target, runtime / repo / supportedModes mismatch) and `sanitizeFinishProfiles(list)` warns + strips them at load so a typo can never surface a Finish button targeting nothing. `finishTargetForModel(model, availableModels)` resolves the delivery entry scoped to what this install can run. |diff --git a/server/lib/index.js b/server/lib/index.jsindex 8aab3fe517..a01026517d 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -141,6 +141,7 @@ export * from './installLogger.js';export * from './kimi.js';export * from './mediaModelBuckets.js';export * from './mediaModels.js';+export * from './minimaxH3Memory.js';export * from './videoContinuity.js';export * from './videoDisclosure.js';export * from './videoFinishProfiles.js';diff --git a/server/lib/mediaModels.js b/server/lib/mediaModels.jsindex 055c77560f..f39cc89d1d 100644--- a/server/lib/mediaModels.js+++ b/server/lib/mediaModels.js@@ -32,6 +32,12 @@* absent on the shipped entry deliberately: the registry syncs between* peers and cannot know what GPU is on the other end. Validated in* services/videoGen/local.js against MINIMAX_H3_CUDA_OFFLOAD_PROFILES.+ * `memoryProfiles` (issue #5420) is the declared, capability-checked+ * weight-placement table for the two MiniMax H3 entries — each profile's+ * honest host-RAM and device-VRAM floor, best-first. Declared in+ * lib/minimaxH3Memory.js and backfilled at load like `disclosure` and+ * `speedProfiles`; the render path fails closed when no profile fits the+ * measured machine, and the runners re-select on the same table.* `disclosure` is optional provenance/licensing metadata (issue #3674):* { modelCardUrl?, weightsLicense?: { name, url }, runtimeLicense?: { name, url },* estimatedDownloadGb?, reviewedAt? }. Every key is optional and an@@ -72,6 +78,7 @@ import { ServerError } from './errorHandler.js';import { applyVideoDisclosures } from './videoDisclosure.js';import { applyVideoFinishProfiles, sanitizeFinishProfiles } from './videoFinishProfiles.js';import { applyVideoSpeedProfiles, sanitizeSpeedProfiles } from './videoSpeedProfiles.js';+import { applyMiniMaxH3MemoryProfiles, sanitizeMiniMaxH3MemoryProfiles } from './minimaxH3Memory.js';import { applyVideoSupportedModes } from './videoModeProfiles.js';import {captureSystemCapabilities,@@ -274,7 +281,7 @@ const DEFAULT_REGISTRY = {// decorator: it attaches the shipped `speedProfiles` a model offers, pin-// guarded on repo AND revision so a re-pointed entry keeps no schedule// claim we can't back.- mlx: applyVideoSpeedProfiles(applyVideoFinishProfiles(applyVideoDisclosures([+ mlx: applyMiniMaxH3MemoryProfiles(applyVideoSpeedProfiles(applyVideoFinishProfiles(applyVideoDisclosures([// notapalindrome's mlx-video-with-audio runtime — single PyPI package,// T2V/I2V only, FFLF degrades to last-frame conditioning (one --image arg).// LTX-2 Unified (the older 42 GB model) was retired in favour of 2.3 —@@ -523,8 +530,8 @@ const DEFAULT_REGISTRY = {samplerLocked: true,samplerNote: 'FastMetal models are DMD2-distilled 3-step models with affine INT8 quantization.',},- ]))),- cuda: applyVideoSpeedProfiles(applyVideoFinishProfiles(applyVideoDisclosures([+ ])))),+ cuda: applyMiniMaxH3MemoryProfiles(applyVideoSpeedProfiles(applyVideoFinishProfiles(applyVideoDisclosures([{ id: 'ltx_video', name: 'LTX-Video 0.9.5 — T2V + I2V (~9.5 GB, auto-downloads)', runtime: 'cuda_video', steps: 25, guidance: 3.0 },// MiniMax H3 on NVIDIA, through diffusers' MiniMaxH3ModularPipeline —// the same joint video+audio model the MLX list runs on Apple Silicon, so it@@ -560,7 +567,7 @@ const DEFAULT_REGISTRY = {supportsTiling: false,supportsDisableAudio: false,},- ]))),+ ])))),defaultMlx: 'ltx23_distilled_q4',defaultCuda: 'ltx_video',},@@ -1113,7 +1120,13 @@ const normalizeRegistry = (parsed) => {// sanitizeSpeedProfiles is its sibling of sanitizeFinishProfiles: a// hand-edited profile with a NaN step count would otherwise reach the// picker and spawn a broken render, so it is warned about and stripped.- return sanitizeSpeedProfiles(applyVideoSpeedProfiles(decorated));+ const withSpeed = sanitizeSpeedProfiles(applyVideoSpeedProfiles(decorated));+ // applyMiniMaxH3MemoryProfiles is the load-time twin of migration 317, and+ // its sanitizer the sibling of the two above: a hand-edited profile with a+ // NaN memory floor would otherwise make every capacity comparison false and+ // refuse H3 renders on a machine that can run them, so it is warned about+ // and stripped.+ return sanitizeMiniMaxH3MemoryProfiles(applyMiniMaxH3MemoryProfiles(withSpeed));};const normalizedBuckets = Object.fromEntries(VIDEO_BUCKETS.map((bucket) => [bucket, videoEntries(bucketResults[bucket].entries, {diff --git a/server/lib/minimaxH3Memory.js b/server/lib/minimaxH3Memory.jsnew file mode 100644index 0000000000..7366b4d533--- /dev/null+++ b/server/lib/minimaxH3Memory.js@@ -0,0 +1,347 @@+/**+ * MiniMax H3 memory profiles (issue #5420).+ *+ * A *memory profile* is one runner-proven weight-placement recipe together with+ * the capacity it honestly needs: a host-RAM floor, and — on the CUDA lane — a+ * device-VRAM floor. H3 is the one video model in the catalog whose components+ * do not fit anywhere unassisted (66.3 GB transformer + 66.7 GB Qwen3-VL+ * conditioner at bf16), so "does this box have enough" is not a display detail+ * here: picking wrong costs a multi-hour load that OOMs at the far end.+ *+ * Before this table there were two independent, unenforced answers to that+ * question:+ *+ * - the registry entry's single `memoryGb` number (128 MLX / 96 CUDA), which+ * nothing checked at render time — it only ever rendered as a UI fact; and+ * - a VRAM heuristic living inside `resolve_offload_profile()` in+ * scripts/generate_minimax_h3_cuda.py, which picked a recipe from the+ * card's nameplate VRAM, never failed closed below the smallest recipe's+ * floor, and returned an explicitly pinned profile without checking the+ * device could run it at all.+ *+ * This module is the single declaration both sides now read. **Every capacity+ * number below already existed in the codebase** — the CUDA tiers are the exact+ * thresholds hoisted out of that heuristic, and the host floors are the+ * entries' own `memoryGb`. The one new number is `MINIMAX_H3_HOST_RESERVE_GB`,+ * which is a policy reserve (headroom left for the OS and PortOS itself), not a+ * claim about the model.+ *+ * ## Why the profiles attach to entries rather than being looked up+ *+ * `applyMiniMaxH3MemoryProfiles` is the same load-time backfill the three+ * sibling decorators use (`applyVideoDisclosures`, `applyVideoFinishProfiles`,+ * `applyVideoSpeedProfiles`), so the client receives the table on the model it+ * already fetches — no second endpoint, and no client-side mirror of the+ * numbers to drift. It carries the same pin guard for the same reason a speed+ * profile does: a placement recipe is validated against ONE set of weights, so+ * an entry re-pointed at a fork or moved off the pinned revision keeps no+ * capacity claim we can no longer back.+ *+ * ## Fail closed, and only on a MEASURED shortfall+ *+ * `miniMaxH3MemoryError` refuses a render whose box cannot hold any declared+ * profile. It refuses only when the shortfall was actually measured: an unknown+ * `totalMemoryGb` is "not measured", which is NOT the same as zero, and must+ * not block a render on a host whose capacity probe simply returned nothing.+ * The runners re-check with their own view of the machine, so an unknown here+ * is a deferral rather than a bypass.+ *+ * Pure module: no I/O, no imports out to services.+ */++/**+ * Host RAM held back from the model, in GB.+ *+ * A render is not the only thing on the machine: PortOS itself, Postgres, the+ * client build and the OS all need to stay resident, and an H3 render that+ * consumes the last gigabyte takes the install down with it rather than+ * failing. This is a deliberate policy reserve — the only number in this module+ * that is not lifted from an existing runner-proven constant.+ */+export const MINIMAX_H3_HOST_RESERVE_GB = 16;++/**+ * The auto-selection request. Absence and `'auto'` are the same request, the+ * way `'quality'` and absence are for a speed profile: the runner sizes a+ * recipe from the hardware it can actually see.+ */+export const MINIMAX_H3_AUTO_PROFILE_ID = 'auto';++/**+ * Shipped profiles, keyed by registry entry id, best-first.+ *+ * `shippedRepo` / `shippedRevision` are the pin guards. Each profile:+ *+ * id stable key. On the CUDA lane this IS the `--offload-profile`+ * value the runner takes, so the two cannot name a recipe+ * differently (pinned by runtimes.test.js).+ * name label for the UI+ * description one line stating what the recipe actually does+ * minMemoryGb host-RAM floor, EXCLUSIVE of MINIMAX_H3_HOST_RESERVE_GB+ * minVramGb device-VRAM floor, or null when the device memory IS the host+ * memory (Apple unified memory)+ * unified true when host and device memory are the same pool+ */+export const MINIMAX_H3_MEMORY_PROFILES = Object.freeze({+ // PipeNetwork's Apple-Silicon MLX port. ONE profile deliberately: the port+ // has a single placement (8-bit DiT plus the bf16 conditioner, all in unified+ // memory), and 128 GB is the figure the shipped entry has always stated. A+ // lower "compact" tier would need a measurement on real hardware that this+ // repo does not have, and a fabricated floor on a multi-hour render is worse+ // than no tier at all. Adding one later is pure data.+ minimax_h3_8bit: Object.freeze({+ shippedRepo: 'pipenetwork/MiniMax-H3-MLX-8bit',+ shippedRevision: '3ac52081470b0488921c3ec3ba84a39097bf2361',+ profiles: Object.freeze([+ Object.freeze({+ id: 'unified-8bit',+ name: 'Unified 8-bit',+ description: '8-bit quantized DiT with the bf16 Qwen3-VL conditioner, resident in unified memory.',+ minMemoryGb: 128,+ minVramGb: null,+ unified: true,+ }),+ ]),+ }),+ // diffusers' MiniMaxH3ModularPipeline on NVIDIA. The three recipes and their+ // thresholds are `resolve_offload_profile()`'s own, moved here so the server+ // can preflight them and the runner can fail closed on the same table instead+ // of silently returning the leanest recipe for a card that cannot run it.+ // The host floor is 96 GB on all three: at int8 roughly 75 GB of weights stay+ // resident in CPU memory for the whole render regardless of which recipe+ // streams them, and bf16's auto-CPU-offload holds a whole component there.+ minimax_h3_cuda: Object.freeze({+ shippedRepo: 'MiniMaxAI/MiniMax-H3',+ shippedRevision: '42ed227ee7df40d41602854ae760620d6eb651fe',+ profiles: Object.freeze([+ Object.freeze({+ id: 'bf16',+ name: 'bf16 with CPU offload',+ description: 'Unquantized components swapped by the components manager, with a 12 GB device reserve.',+ minMemoryGb: 96,+ // The floor for holding one bf16 component resident while the manager+ // swaps the other.+ minVramGb: 60,+ unified: false,+ }),+ Object.freeze({+ id: 'int8-stream',+ name: 'int8, streamed blocks',+ description: 'int8 weight-only quantization with block-level transformer offload streamed onto the card.',+ minMemoryGb: 96,+ // Below this a transformer block plus its activations stops fitting+ // beside the video VAE, and the leaf-level recipe takes over.+ minVramGb: 20,+ unified: false,+ }),+ Object.freeze({+ id: 'int8-lean',+ name: 'int8, leaf-level',+ description: 'int8 weight-only quantization with leaf-level offload for the transformer, conditioner and video VAE.',+ minMemoryGb: 96,+ // The runner documents this recipe as the 12-16 GB card path. Below it+ // nothing in the table fits, which is now an error rather than a+ // silently-returned recipe that OOMs after the load.+ minVramGb: 12,+ unified: false,+ }),+ ]),+ }),+});++const isEntry = (entry) => !!entry && typeof entry === 'object' && typeof entry.id === 'string';++const positiveNumber = (value) => (Number.isFinite(Number(value)) && Number(value) > 0 ? Number(value) : null);++/**+ * Attach `memoryProfiles` to shipped entries that don't already carry the key.+ * Pure; returns a new array and never mutates the input entries.+ *+ * Preservation contract (mirrors migration 317 and the sibling decorators):+ * - `'memoryProfiles' in entry` → user/existing value wins (including `null`+ * or `[]`, the explicit "no declared profiles" override)+ * - entry id not shipped → custom model, left as-is+ * - `repo` or `revision` differs from the pin → left as-is+ */+export const applyMiniMaxH3MemoryProfiles = (list) => {+ if (!Array.isArray(list)) return list;+ return list.map((entry) => {+ if (!isEntry(entry)) return entry;+ if ('memoryProfiles' in entry) return entry;+ const spec = MINIMAX_H3_MEMORY_PROFILES[entry.id];+ if (!spec) return entry;+ if (spec.shippedRepo !== null && entry.repo !== spec.shippedRepo) return entry;+ if (spec.shippedRevision !== null && entry.revision !== spec.shippedRevision) return entry;+ return { ...entry, memoryProfiles: spec.profiles.map((profile) => ({ ...profile })) };+ });+};++/**+ * The profiles a model declares, best-first, or `[]`.+ */+export const miniMaxH3MemoryProfiles = (model) => (+ Array.isArray(model?.memoryProfiles)+ ? model.memoryProfiles.filter((profile) => typeof profile?.id === 'string' && profile.id)+ : []+);++/**+ * Usable host RAM after the reserve, or `null` when capacity wasn't measured.+ *+ * `null` is the sentinel for "not measured" and is deliberately distinct from+ * a measured small number — a capacity probe that returned nothing must not+ * read as a box with no memory.+ */+export const miniMaxH3UsableMemoryGb = (totalMemoryGb) => {+ const total = positiveNumber(totalMemoryGb);+ return total === null ? null : Math.max(0, total - MINIMAX_H3_HOST_RESERVE_GB);+};++/**+ * The best profile this box's HOST memory can hold, plus what it was measured+ * against. VRAM is deliberately not considered here: the server has no+ * synchronous view of the device, and the runner — which does — re-selects on+ * the same table before it loads anything.+ *+ * @returns {{ profile, usableMemoryGb, totalMemoryGb }} with `profile: null`+ * when the model declares none or nothing fits. `usableMemoryGb: null` means+ * the host was not measured, in which case the best declared profile is+ * returned unjudged for the runner to confirm.+ */+export const selectMiniMaxH3MemoryProfile = ({ model, totalMemoryGb } = {}) => {+ const profiles = miniMaxH3MemoryProfiles(model);+ const usableMemoryGb = miniMaxH3UsableMemoryGb(totalMemoryGb);+ const total = positiveNumber(totalMemoryGb);+ if (profiles.length === 0) return { profile: null, usableMemoryGb, totalMemoryGb: total };+ if (usableMemoryGb === null) return { profile: profiles[0], usableMemoryGb, totalMemoryGb: total };+ const profile = profiles.find((candidate) => {+ const floor = positiveNumber(candidate.minMemoryGb);+ return floor === null || usableMemoryGb >= floor;+ }) || null;+ return { profile, usableMemoryGb, totalMemoryGb: total };+};++/**+ * The smallest host-RAM floor any declared profile has, or `null`.+ */+const smallestHostFloorGb = (profiles) => profiles.reduce((smallest, profile) => {+ const floor = positiveNumber(profile.minMemoryGb);+ if (floor === null) return smallest;+ return smallest === null || floor < smallest ? floor : smallest;+}, null);++/**+ * Why this machine cannot run H3, or `null` when it can (or when capacity was+ * not measured, which defers to the runner rather than blocking).+ *+ * Returned as a plain `{ code, message }` rather than thrown so the caller+ * decides the boundary — the render path turns it into a `ServerError`, and a+ * status/readiness surface can render it as a fact.+ */+export const miniMaxH3MemoryDeclineReason = ({ model, modelId, totalMemoryGb } = {}) => {+ const profiles = miniMaxH3MemoryProfiles(model);+ if (profiles.length === 0) return null;+ const { profile, usableMemoryGb } = selectMiniMaxH3MemoryProfile({ model, totalMemoryGb });+ if (usableMemoryGb === null || profile) return null;+ const floor = smallestHostFloorGb(profiles);+ const name = model?.name || modelId || model?.id || 'This model';+ return {+ code: 'MINIMAX_H3_MEMORY_INSUFFICIENT',+ message: `${name} needs at least ${floor} GB of memory for its smallest weight-placement profile. `+ + `This machine has ${Math.round(Number(totalMemoryGb))} GB, of which ${Math.round(usableMemoryGb)} GB is usable `+ + `after the ${MINIMAX_H3_HOST_RESERVE_GB} GB reserve PortOS keeps for the operating system. `+ + `Render on a peer with more memory, or pick a smaller model.`,+ };+};++/**+ * Validate one platform's video list for memory-profile problems. Pure —+ * returns `{ id, profileId, reason }` rows (empty when sound). Same division of+ * labour as `validateSpeedProfileTable`: callers decide whether to+ * warn-and-strip (load path) or fail (the test pinning the shipped registry).+ *+ * Checked, in the order a hand-edit is most likely to break it:+ * - `memoryProfiles` is an array (or absent)+ * - every profile has a non-empty string id, unique within the entry+ * - no profile claims the reserved auto id+ * - `minMemoryGb` is a positive finite number — a NaN floor would make every+ * comparison false and silently refuse every render+ * - `minVramGb`, when present, is a positive finite number+ * - profiles are ordered best-first by host floor, since selection takes the+ * FIRST that fits and a mis-ordered table would hand a big box the leanest+ * recipe+ */+export const validateMiniMaxH3MemoryProfileTable = (list) => {+ if (!Array.isArray(list)) return [];+ const problems = [];+ const fail = (id, profileId, reason) => problems.push({ id, profileId, reason });+ for (const entry of list) {+ if (!isEntry(entry)) continue;+ if (!('memoryProfiles' in entry) || entry.memoryProfiles == null) continue;+ if (!Array.isArray(entry.memoryProfiles)) {+ fail(entry.id, null, 'memoryProfiles must be an array');+ continue;+ }+ const seen = new Set();+ let previousFloor = null;+ let entryFailed = false;+ for (const profile of entry.memoryProfiles) {+ const pid = profile?.id;+ if (typeof pid !== 'string' || pid.length === 0) {+ fail(entry.id, pid ?? null, 'profile id must be a non-empty string');+ entryFailed = true;+ break;+ }+ if (pid === MINIMAX_H3_AUTO_PROFILE_ID) {+ fail(entry.id, pid, `"${MINIMAX_H3_AUTO_PROFILE_ID}" is the reserved auto-selection id`);+ entryFailed = true;+ break;+ }+ if (seen.has(pid)) {+ fail(entry.id, pid, `duplicate profile id "${pid}"`);+ entryFailed = true;+ break;+ }+ seen.add(pid);+ const floor = positiveNumber(profile.minMemoryGb);+ if (floor === null) {+ fail(entry.id, pid, 'minMemoryGb must be a positive number');+ entryFailed = true;+ break;+ }+ if (profile.minVramGb != null && positiveNumber(profile.minVramGb) === null) {+ fail(entry.id, pid, 'minVramGb must be a positive number when present');+ entryFailed = true;+ break;+ }+ if (previousFloor !== null && floor > previousFloor) {+ fail(entry.id, pid, 'memoryProfiles must be ordered best-first (non-increasing minMemoryGb)');+ entryFailed = true;+ break;+ }+ previousFloor = floor;+ }+ if (entryFailed) continue;+ }+ return problems;+};++/**+ * Load-time guard: strip every invalid `memoryProfiles` list, logging each+ * problem. A hand-edited registry must not be able to refuse every render with+ * a NaN floor, and must not crash boot (`loadMediaModels` runs at import time).+ * Returns the input array unchanged when the table is sound.+ */+export const sanitizeMiniMaxH3MemoryProfiles = (list) => {+ const problems = validateMiniMaxH3MemoryProfileTable(list);+ if (problems.length === 0) return list;+ const bad = new Set(problems.map((problem) => problem.id));+ for (const problem of problems) {+ console.log(`⚠️ media-models: dropping memoryProfiles on "${problem.id}" — ${problem.reason}`);+ }+ return list.map((entry) => {+ if (!isEntry(entry) || !bad.has(entry.id)) return entry;+ const { memoryProfiles: _dropped, ...rest } = entry;+ return rest;+ });+};diff --git a/server/lib/minimaxH3Memory.test.js b/server/lib/minimaxH3Memory.test.jsnew file mode 100644index 0000000000..3ea9f9def9--- /dev/null+++ b/server/lib/minimaxH3Memory.test.js@@ -0,0 +1,160 @@+import { describe, expect, it, vi } from 'vitest';+import { readFileSync } from 'fs';+import { dirname, join } from 'path';+import { fileURLToPath } from 'url';+import {+ MINIMAX_H3_HOST_RESERVE_GB,+ MINIMAX_H3_MEMORY_PROFILES,+ applyMiniMaxH3MemoryProfiles,+ miniMaxH3MemoryDeclineReason,+ sanitizeMiniMaxH3MemoryProfiles,+ selectMiniMaxH3MemoryProfile,+ validateMiniMaxH3MemoryProfileTable,+} from './minimaxH3Memory.js';++const MLX_SPEC = MINIMAX_H3_MEMORY_PROFILES.minimax_h3_8bit;+const CUDA_SPEC = MINIMAX_H3_MEMORY_PROFILES.minimax_h3_cuda;++const mlxEntry = (overrides = {}) => ({+ id: 'minimax_h3_8bit',+ repo: MLX_SPEC.shippedRepo,+ revision: MLX_SPEC.shippedRevision,+ ...overrides,+});++const cudaEntry = (overrides = {}) => ({+ id: 'minimax_h3_cuda',+ repo: CUDA_SPEC.shippedRepo,+ revision: CUDA_SPEC.shippedRevision,+ ...overrides,+});++const decorated = (entry) => applyMiniMaxH3MemoryProfiles([entry])[0];++describe('applyMiniMaxH3MemoryProfiles', () => {+ it('attaches the shipped table to a pinned entry without mutating it', () => {+ const entry = mlxEntry();+ const next = decorated(entry);+ expect(next).not.toBe(entry);+ expect(entry).not.toHaveProperty('memoryProfiles');+ expect(next.memoryProfiles).toEqual([...MLX_SPEC.profiles]);+ });++ it('leaves an explicit user value alone, including a deliberate empty list', () => {+ expect(decorated(mlxEntry({ memoryProfiles: [] })).memoryProfiles).toEqual([]);+ expect(decorated(mlxEntry({ memoryProfiles: null })).memoryProfiles).toBeNull();+ });++ it('skips an entry re-pointed off the pinned weights', () => {+ // A placement recipe is validated against ONE set of weights, so a fork or a+ // moved revision must not inherit a capacity claim we cannot back.+ expect(decorated(mlxEntry({ repo: 'someone/h3-fork' }))).not.toHaveProperty('memoryProfiles');+ expect(decorated(mlxEntry({ revision: 'deadbeef' }))).not.toHaveProperty('memoryProfiles');+ });++ it('leaves a custom model untouched', () => {+ expect(decorated({ id: 'user-model', repo: 'example/custom' })).not.toHaveProperty('memoryProfiles');+ });+});++describe('selectMiniMaxH3MemoryProfile', () => {+ it('picks the richest CUDA profile the usable host memory can hold', () => {+ const model = decorated(cudaEntry());+ const { profile, usableMemoryGb } = selectMiniMaxH3MemoryProfile({+ model,+ totalMemoryGb: 96 + MINIMAX_H3_HOST_RESERVE_GB,+ });+ expect(profile.id).toBe('bf16');+ expect(usableMemoryGb).toBe(96);+ });++ it('subtracts the reserve, so a box sitting exactly on the headline floor does NOT fit', () => {+ // The whole point of the reserve: 128 GB nameplate against a 128 GB floor+ // used to read as a fit while a render would have claimed the whole machine.+ const model = decorated(mlxEntry());+ expect(selectMiniMaxH3MemoryProfile({ model, totalMemoryGb: 128 }).profile).toBeNull();+ expect(+ selectMiniMaxH3MemoryProfile({ model, totalMemoryGb: 128 + MINIMAX_H3_HOST_RESERVE_GB }).profile.id,+ ).toBe('unified-8bit');+ });++ it('defers to the runner when the host was not measured', () => {+ // "Probe returned nothing" is not "this box has no memory" — an unmeasured+ // host gets the best profile unjudged rather than a refusal.+ const model = decorated(cudaEntry());+ const result = selectMiniMaxH3MemoryProfile({ model, totalMemoryGb: null });+ expect(result.usableMemoryGb).toBeNull();+ expect(result.profile.id).toBe('bf16');+ });+});++describe('miniMaxH3MemoryDeclineReason', () => {+ it('refuses a measured box below every declared floor, naming what it would take', () => {+ const reason = miniMaxH3MemoryDeclineReason({+ model: decorated(mlxEntry({ name: 'MiniMax H3 MLX 8-bit' })),+ totalMemoryGb: 64,+ });+ expect(reason.code).toBe('MINIMAX_H3_MEMORY_INSUFFICIENT');+ expect(reason.message).toContain('128 GB');+ expect(reason.message).toContain('64 GB');+ expect(reason.message).toContain(`${MINIMAX_H3_HOST_RESERVE_GB} GB reserve`);+ });++ it('stays null for a box that fits, an unmeasured host, and a model with no table', () => {+ const model = decorated(cudaEntry());+ expect(miniMaxH3MemoryDeclineReason({ model, totalMemoryGb: 256 })).toBeNull();+ expect(miniMaxH3MemoryDeclineReason({ model, totalMemoryGb: null })).toBeNull();+ expect(miniMaxH3MemoryDeclineReason({ model: { id: 'ltx_video' }, totalMemoryGb: 8 })).toBeNull();+ });+});++describe('validateMiniMaxH3MemoryProfileTable / sanitize', () => {+ const problemFor = (memoryProfiles) => validateMiniMaxH3MemoryProfileTable([{ id: 'x', memoryProfiles }])[0];++ it('accepts the shipped table and absent/null keys', () => {+ expect(validateMiniMaxH3MemoryProfileTable(applyMiniMaxH3MemoryProfiles([mlxEntry(), cudaEntry()]))).toEqual([]);+ expect(validateMiniMaxH3MemoryProfileTable([{ id: 'x' }, { id: 'y', memoryProfiles: null }])).toEqual([]);+ });++ it('rejects a NaN floor, which would otherwise refuse every render silently', () => {+ expect(problemFor([{ id: 'a', minMemoryGb: 'lots' }]).reason).toMatch(/minMemoryGb/);+ });++ it('rejects a duplicate id, the reserved auto id, and a mis-ordered table', () => {+ expect(problemFor([{ id: 'a', minMemoryGb: 96 }, { id: 'a', minMemoryGb: 96 }]).reason).toMatch(/duplicate/);+ expect(problemFor([{ id: 'auto', minMemoryGb: 96 }]).reason).toMatch(/reserved/);+ // Selection takes the FIRST profile that fits, so a table ordered+ // lean-first would hand a large box the smallest recipe.+ expect(problemFor([{ id: 'a', minMemoryGb: 24 }, { id: 'b', minMemoryGb: 96 }]).reason).toMatch(/best-first/);+ });++ it('strips a bad table at load rather than crashing boot', () => {+ const log = vi.spyOn(console, 'log').mockImplementation(() => {});+ const list = sanitizeMiniMaxH3MemoryProfiles([+ { id: 'bad', memoryProfiles: [{ id: 'a', minMemoryGb: 0 }] },+ { id: 'good', memoryProfiles: [{ id: 'a', minMemoryGb: 96 }] },+ ]);+ expect(list[0]).not.toHaveProperty('memoryProfiles');+ expect(list[1].memoryProfiles).toHaveLength(1);+ expect(log).toHaveBeenCalled();+ log.mockRestore();+ });+});++// The CUDA runner re-selects a recipe from the device's VRAM, which the server+// cannot see. That only stays honest while its floors agree with the ones this+// module declares and the UI renders — hand-synced across a language boundary,+// the same shape MINIMAX_H3_CUDA_OFFLOAD_PROFILES already has.+describe('CUDA VRAM floors', () => {+ it('match PROFILE_MIN_VRAM_GB in the Python runner', () => {+ const runner = readFileSync(+ join(dirname(fileURLToPath(import.meta.url)), '..', '..', 'scripts', 'generate_minimax_h3_cuda.py'),+ 'utf8',+ );+ const declared = runner.match(/^PROFILE_MIN_VRAM_GB = \((.*)\)$/m);+ expect(declared).not.toBeNull();+ const fromPython = [...declared[1].matchAll(/\("([^"]+)",\s*(\d+)\)/g)]+ .map(([, id, floor]) => ({ id, minVramGb: Number(floor) }));+ expect(fromPython).toEqual(CUDA_SPEC.profiles.map(({ id, minVramGb }) => ({ id, minVramGb })));+ });+});diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.jsindex 1bdcedbd41..c9121fa4e3 100644--- a/server/services/videoGen/local.test.js+++ b/server/services/videoGen/local.test.js@@ -8,6 +8,7 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';import { basename, join } from 'path';import { tmpdir, totalmem } from 'os';+import { MINIMAX_H3_HOST_RESERVE_GB } from '../../lib/minimaxH3Memory.js';import { randomUUID } from 'crypto';// Pure table, no mocking involved — a static import survives vi.resetModules().import { INSPIRE_DEFAULT_IMAGE_STRENGTH } from '../../lib/videoReferenceModes.js';@@ -127,6 +128,11 @@ vi.mock('../../lib/mediaModels.js', async () => {revision: '6818f6c32d12b210915e44ad56a4228c2608f160',files: ['LICENSE', 'FL2VA/vae/video/config.json'],}],+ // Deliberately a 1 GB floor rather than the shipped 128 GB: these suites+ // must assert the same thing on every machine and in CI, and a real floor+ // would make the capacity gate pass or fail with the runner's own RAM.+ // The shipped table's numbers are pinned in lib/minimaxH3Memory.test.js.+ memoryProfiles: [{ id: 'unified-8bit', name: 'Unified 8-bit', minMemoryGb: 1, minVramGb: null, unified: true }],},{id: 'minimax_h3_cuda', name: 'MiniMax H3 CUDA int8', runtime: 'minimax_h3_cuda',@@ -141,6 +147,7 @@ vi.mock('../../lib/mediaModels.js', async () => {defaultWidth: 1344, defaultHeight: 768, resolutionStep: 32,steps: 8, guidance: 0, samplerLocked: true,termsGate: { id: 'minimax-h3-community-license-2026-08-02' },+ memoryProfiles: [{ id: 'int8-lean', name: 'int8, leaf-level', minMemoryGb: 1, minVramGb: 12, unified: false }],},{id: 'wan22_ti2v_5b', name: 'Wan TI2V', runtime: 'wan22',@@ -2951,6 +2958,64 @@ describe('generateVideo — MiniMax H3 MLX contract', () => {expect(args[args.indexOf('--width') + 1]).toBe('768');expect(args[args.indexOf('--height') + 1]).toBe('512');});++ // Capacity bounding (#5420). The floors live in lib/minimaxH3Memory.js and are+ // unit-tested there; what these two pin is that the render boundary is WIRED+ // to them — that the contract reaches the helper's argv, and that a box below+ // every profile is refused before a child exists rather than after an hour of+ // loading weights it can never hold.+ it.each([+ ['minimax_h3_8bit', 'generate_minimax_h3.py', 'unified-8bit'],+ ['minimax_h3_cuda', 'generate_minimax_h3_cuda.py', null],+ ])('hands %s its host-memory contract', async (modelId, helper, expectedProfile) => {+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');+ const spawnMock = vi.mocked(spawnDetached);+ spawnMock.mockClear();++ await generateVideo({+ jobId: `h3-memory-${modelId}`,+ modelId,+ prompt: 'a fox watches the rain',+ width: 1344, height: 768, numFrames: 124, fps: 24, mode: 'text',+ });++ const [, args] = spawnMock.mock.calls.find(([, childArgs]) => (+ Array.isArray(childArgs) && childArgs.some((arg) => basename(String(arg)) === helper)+ ));+ expect(args[args.indexOf('--min-system-memory-gb') + 1]).toBe('1');+ expect(args[args.indexOf('--memory-headroom-gb') + 1]).toBe(String(MINIMAX_H3_HOST_RESERVE_GB));+ // Only the MLX lane takes a server-selected profile: on CUDA the tier is+ // VRAM-driven, so it stays the runner's call on --offload-profile.+ if (expectedProfile) expect(args[args.indexOf('--memory-profile') + 1]).toBe(expectedProfile);+ else expect(args).not.toContain('--memory-profile');+ });++ it('refuses a render this machine cannot hold, before any child is spawned', async () => {+ const mediaModels = await import('../../lib/mediaModels.js');+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');+ const getVideoModelsMock = vi.mocked(mediaModels.getVideoModels);+ const catalog = getVideoModelsMock();+ const spawnMock = vi.mocked(spawnDetached);+ spawnMock.mockClear();+ getVideoModelsMock.mockReturnValue(catalog.map((model) => (+ model.id === 'minimax_h3_8bit'+ ? { ...model, memoryProfiles: [{ ...model.memoryProfiles[0], minMemoryGb: 1e6 }] }+ : model+ )));++ try {+ await expect(generateVideo({+ jobId: 'h3-memory-refused',+ modelId: 'minimax_h3_8bit',+ prompt: 'a fox watches the rain',+ width: 1344, height: 768, numFrames: 124, fps: 24, mode: 'text',+ })).rejects.toMatchObject({ code: 'MINIMAX_H3_MEMORY_INSUFFICIENT', status: 400 });+ } finally {+ getVideoModelsMock.mockReturnValue(catalog);+ }++ expect(spawnMock).not.toHaveBeenCalled();+ });});// H3's DiT is quantized, so LoRAs ride along only if the installed runnerdiff --git a/server/services/videoGen/renderArgs.js b/server/services/videoGen/renderArgs.jsindex 2e93a81a05..9c900c6f70 100644--- a/server/services/videoGen/renderArgs.js+++ b/server/services/videoGen/renderArgs.js@@ -24,6 +24,12 @@ import {} from '../../lib/icLoraWeights.js';import { videoModeContractError, videoReferenceModeError } from './modeContract.js';import { minimaxH3ControlError } from './minimaxH3Controls.js';+import {+ MINIMAX_H3_HOST_RESERVE_GB,+ miniMaxH3MemoryDeclineReason,+ miniMaxH3MemoryProfiles,+ selectMiniMaxH3MemoryProfile,+} from '../../lib/minimaxH3Memory.js';import {LTX2_HELPER_SCRIPT,LTX25_ENCODER_SHIM_DIR,@@ -630,6 +636,37 @@ const assertMiniMaxH3Preflight = ({{ status: 500, code: 'VIDEO_MODEL_MISCONFIGURED' },);}+ // Capacity, before anything is spawned (issue #5420). H3's components fit+ // nowhere unassisted, so a box below every declared placement profile is not+ // a slow render — it is a multi-hour load that OOMs at the far end, after the+ // job has already taken the queue. A 400 here names the shortfall while the+ // user is still looking at the form. `null` when the host was not measured,+ // which defers to the runner's own check rather than blocking.+ const memoryDecline = miniMaxH3MemoryDeclineReason({+ model,+ modelId: model.id,+ totalMemoryGb: totalmem() / 1024 ** 3,+ });+ if (memoryDecline) throw new ServerError(memoryDecline.message, { status: 400, code: memoryDecline.code });+};++// The capacity contract both H3 runners are handed: the host floor below which+// NO declared placement profile can run, and the reserve PortOS holds back for+// the OS. Sent as argv rather than left to each runner's own constants so the+// server-side gate above and the runner-side enforcement cannot state different+// numbers. The floor is the SMALLEST across the entry's profiles, not the one+// the host-side selection landed on: on the CUDA lane the runner picks the tier+// from VRAM (the only side that can see the device), so a floor taken from a+// richer tier would reject a box that can in fact run a leaner one.+const miniMaxH3HostMemoryArgs = (model) => {+ const floors = miniMaxH3MemoryProfiles(model)+ .map((profile) => Number(profile.minMemoryGb))+ .filter((floor) => Number.isFinite(floor) && floor > 0);+ if (floors.length === 0) return [];+ return [+ '--min-system-memory-gb', String(Math.min(...floors)),+ '--memory-headroom-gb', String(MINIMAX_H3_HOST_RESERVE_GB),+ ];};// Build args for PipeNetwork's pinned MiniMax H3 MLX port. The helper resolves@@ -667,7 +704,14 @@ const buildMiniMaxH3Args = ({ model, prompt, negativePrompt, width, height, numF'--steps', String(steps),'--seed', String(seed),'--output', outputPath,+ ...miniMaxH3HostMemoryArgs(model),];+ // The MLX lane's placement is unified-memory only, so the server picks the+ // profile and the runner enforces its limit against the machine's own RAM.+ // (The CUDA lane is the opposite: the tier is VRAM-driven, so it stays the+ // runner's call and rides on --offload-profile instead.)+ const mlxProfile = selectMiniMaxH3MemoryProfile({ model, totalMemoryGb: totalmem() / 1024 ** 3 }).profile;+ if (mlxProfile) args.push('--memory-profile', mlxProfile.id);if (previewDir) args.push('--preview-dir', previewDir);for (const file of files) args.push('--checkpoint-file', file);// Anchor order is packed order: the helper stretches the FIRST keyframe onto@@ -741,6 +785,7 @@ const buildMiniMaxH3CudaArgs = ({ model, prompt, negativePrompt, width, height,'--steps', String(steps),'--seed', String(seed),'--output', outputPath,+ ...miniMaxH3HostMemoryArgs(model),];for (const file of files) args.push('--repo-file', file);// A user-pinned offload recipe from data/media-models.json. Omitted, the