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
report a moved MiniMax H3 pin at Install/Repair instead of on a failed keyframe render (#4606)
[._.]/ Adam Eivy044ce0a7ce55
diff --git a/scripts/_minimax_h3_mlx_pins.py b/scripts/_minimax_h3_mlx_pins.pynew file mode 100644index 0000000000..fd18888f08--- /dev/null+++ b/scripts/_minimax_h3_mlx_pins.py@@ -0,0 +1,196 @@+"""What "the pinned MiniMax H3 MLX text encoder" means, stated once.++`generate_minimax_h3.py` patches four methods of+`minimax_h3_mlx.text_encoder.MiniMaxH3TextEncoder` at render time, and every one+of those patches is only correct against the exact implementation it was written+for. This module holds the facts that define "exact": which methods have to be+there, which of them has to still be a property, the merge line the encode+correction replaces, and the digest of the whole `encode` it copies.++Both readers import it, so there is one copy to re-record when the pin moves:++- the runner, whose corrections keep guarding their own seam — that is the last+ line of defence for a checkout overridden after install; and+- `minimax_h3_runtime_probe.py`, which runs at Install / Repair and calls+ `verify_pin_seams()` there, so whoever bumps `MINIMAX_H3_EXPECTED_REVISION`+ (server/services/videoGen/runtimes.js) hears about a moved pin at the action+ that moved it, rather than minutes into a failed keyframe render.++A failed seam therefore leaves the whole runtime reported unready, not just the+render mode that seam serves — deliberately. `verify_runtime_checkout()` already+byte-verifies the checkout against the expected revision, so a stock install can+never reach these assertions: the only way to fail one is to have moved the pin,+and stopping there is the point.++MLX only, deliberately: `generate_minimax_h3_cuda.py` runs diffusers'+`MiniMaxH3ModularPipeline` with no source checkout to pin and nothing to patch,+so none of this is true of it — checkpoint facts the two runners DO share live+in `_minimax_h3_common.py` instead.++Stdlib-only at import time like that sibling: `minimax_h3_mlx` and `mlx_vlm` are+imported inside the functions that need them, so importing this module never+assumes a registered source namespace or a loaded runtime.+"""++from __future__ import annotations++import hashlib+import importlib+import inspect++# The merge the pinned port performs instead of a scatter. Asserted before the+# runner's replacement is installed, so the day upstream fixes this the patch+# says so loudly rather than shadowing a working implementation forever.+PINNED_BROADCAST_MERGE = "mx.where(image_mask[..., None], hidden.astype(inputs_embeds.dtype)[None], inputs_embeds)"++# sha256 of the whole pinned `encode`, because the runner's replacement re-runs+# its body with one line changed rather than wrapping it. Matching only the merge+# line would let every OTHER edit a pin bump makes — a new `_hidden_states`+# argument, a different dtype, an added step — pass silently into a stale copy.+# Re-record this when bumping MINIMAX_H3_EXPECTED_REVISION, after re-reading+# `encode` and folding whatever changed into the replacement.+PINNED_ENCODE_DIGEST = "8047e407e797cd46cd7538024ca09d97402d369d97b1d825757a1590416bda7d"++def is_property(hook) -> bool:+ """Whether an attribute is the property the `processor` patch replaces."""+ return isinstance(hook, property)+++# Every attribute of the pinned encoder PortOS patches, as+# `name: (shape, consequence, remedy)`. `shape` is what the patch needs the+# attribute to BE, not merely that it is there: `processor` is read as a property+# by the pinned caller, so one that stopped being a property is as much a pin+# change as an absent one, and the other three are wrapped and then CALLED, so a+# name that survived a bump as a plain value would pass a presence check and then+# fail at the call site. The consequence and remedy are stated here rather than at+# each patch so the install-time probe cannot report a seam differently from the+# render-time guard that shares it.+PINNED_ENCODER_SEAMS = {+ "_wanted": (+ callable,+ "a substituted text encoder cannot be key-mapped onto it",+ "Render with the stock text encoder",+ ),+ "processor": (+ is_property,+ "a keyframe cannot be encoded without PyTorch",+ "Render text-only",+ ),+ "_load_weights": (+ callable,+ "its vision tower cannot be laid out for MLX",+ "Render text-only",+ ),+ "encode": (+ callable,+ "a keyframe cannot be merged into the prompt",+ "Render text-only",+ ),+}++# The mlx-vlm names the corrections borrow that the pinned port never imports+# itself, so `minimax_h3_mlx.pipeline` would keep importing cleanly after a pin+# bump onto an mlx-vlm that moved any of them. Each is stated down to the+# ATTRIBUTE the correction actually calls, not just the class holding it: an+# mlx-vlm that kept `Model` and renamed its merge is exactly the drift that would+# otherwise pass Install / Repair and die on the first keyframe. Only the probe+# checks these — the runner reaches for them inside the correction that needs+# them, where a plain ImportError/AttributeError already names what is gone.+BORROWED_MLX_VLM_ATTRS = (+ ("mlx_vlm.models.qwen3_vl.qwen3_vl", "Model.merge_input_ids_with_image_features",+ "a keyframe cannot be merged into the prompt"),+ ("mlx_vlm.models.qwen3_vl.language", "LanguageModel.get_rope_index",+ "a keyframe cannot be positioned in the prompt"),+ ("mlx_vlm.utils", "sanitize_weights", "its vision tower cannot be laid out for MLX"),+)+++def pinned_encoder_hook(name: str):+ """Return one seam of the pinned text encoder, or say the pin moved.++ Each correction in the runner wraps a different method of+ `MiniMaxH3TextEncoder`, and each is only correct against the implementation+ it was written for — so every one of them checks its hook is still there and+ still the shape it patches, and reports the same two ways out.+ """+ from minimax_h3_mlx.text_encoder import MiniMaxH3TextEncoder++ shape, consequence, remedy = PINNED_ENCODER_SEAMS[name]+ hook = getattr(MiniMaxH3TextEncoder, name, None)+ if hook is None or not shape(hook):+ raise RuntimeError(+ f"The pinned MiniMax H3 runtime no longer exposes MiniMaxH3TextEncoder.{name}, so "+ f"{consequence}. {remedy}, or update PortOS for the new pin."+ )+ return MiniMaxH3TextEncoder, hook+++def verify_pinned_encode_source(encode) -> None:+ """Check `encode` is still the implementation the merge correction copied."""+ source = inspect.getsource(encode)+ if PINNED_BROADCAST_MERGE not in source:+ raise RuntimeError(+ "The pinned MiniMax H3 runtime no longer merges keyframe embeddings the way PortOS "+ "corrects for; re-check the pin before rendering with a keyframe."+ )+ if hashlib.sha256(source.encode("utf-8")).hexdigest() != PINNED_ENCODE_DIGEST:+ raise RuntimeError(+ "The pinned MiniMax H3 runtime changed MiniMaxH3TextEncoder.encode outside the merge "+ "PortOS corrects; fold the change into the replacement and re-record "+ "PINNED_ENCODE_DIGEST before rendering with a keyframe."+ )+++def require_borrowed_attr(module_name: str, attr_path: str, consequence: str) -> None:+ """Check one borrowed mlx-vlm name resolves, without importing it to use.++ `attr_path` is walked a segment at a time, so `Model.merge_input_ids_with_image_features`+ reports the method the correction calls rather than only the class it hangs+ off — a renamed method on a still-present class is the drift most likely to+ survive a pin bump. Every borrowed name is CALLED by the correction that+ borrows it, so a name that survived as a plain value would pass a presence+ check here and then fail at the call site the check exists to protect.+ """+ try:+ found = importlib.import_module(module_name)+ except ImportError:+ found = None+ for part in attr_path.split("."):+ if found is None:+ break+ found = getattr(found, part, None)+ if not callable(found):+ raise RuntimeError(+ f"The pinned MiniMax H3 runtime's mlx-vlm no longer exposes {module_name}.{attr_path} "+ f"as a callable, so {consequence}. Update PortOS for the new pin."+ )+++def verify_pin_seams() -> None:+ """Assert every seam the render-time corrections patch, before a render.++ Called from the runtime probe, which runs at Install / Repair — the action+ that can move the pin — so the whole set is reported there instead of one+ seam at a time, minutes into whichever render happens to touch it first.+ """+ for name in PINNED_ENCODER_SEAMS:+ _, hook = pinned_encoder_hook(name)+ # Presence is not enough for `encode` alone: the correction re-runs a COPY+ # of its body, so the body itself is part of the seam.+ if name == "encode":+ verify_pinned_encode_source(hook)+ for entry in BORROWED_MLX_VLM_ATTRS:+ require_borrowed_attr(*entry)+++__all__ = [+ "BORROWED_MLX_VLM_ATTRS",+ "is_property",+ "PINNED_BROADCAST_MERGE",+ "PINNED_ENCODE_DIGEST",+ "PINNED_ENCODER_SEAMS",+ "pinned_encoder_hook",+ "require_borrowed_attr",+ "verify_pin_seams",+ "verify_pinned_encode_source",+]diff --git a/scripts/_minimax_h3_mlx_pins.test.js b/scripts/_minimax_h3_mlx_pins.test.jsnew file mode 100644index 0000000000..bc4a460071--- /dev/null+++ b/scripts/_minimax_h3_mlx_pins.test.js@@ -0,0 +1,241 @@+import { execFileSync } from 'node:child_process';+import { readFileSync, readdirSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { dirname, join } from 'node:path';+import { describe, expect, it } from 'vitest';+import { resolveTestPython } from '../server/lib/testHelper.js';++// The pin facts `generate_minimax_h3.py` patches against and+// `minimax_h3_runtime_probe.py` asserts at Install / Repair. They live in one+// module so those two cannot disagree about what the pin is; this suite covers+// the assertions themselves, and the last case covers the "one module" part.+const scriptsDir = dirname(fileURLToPath(import.meta.url));+const script = join(scriptsDir, '_minimax_h3_mlx_pins.py');++// Probe for an interpreter that actually RUNS rather than assuming a name. On+// Windows a box with no Store-installed Python still has `python` on PATH as an+// alias STUB: it exists, exits non-zero, and prints "Python was not found", so a+// name-only choice passes here and then every case dies with an opaque "Command+// failed". Null when there is genuinely none, so the suite skips.+const pyBin = resolveTestPython();+const runPython = (source) => execFileSync(pyBin, ['-c', source, script], {+ encoding: 'utf8',+});++// Load the module by path — it is stdlib-only at import time, which is what lets+// a bare interpreter here import it without the MLX venv or a registered source+// namespace behind it.+//+// `build_pin` writes a stand-in pinned encoder to a REAL file: the encode guard+// reads its body back with `inspect.getsource`, which a class declared inline+// cannot serve. Each case drops exactly one seam and leaves the rest conforming,+// so a message that matched for the wrong reason would show up as the wrong+// seam being named. `stub_mlx_vlm` does the same for the two borrowed names —+// the pinned port never imports either, so they are seams of their own.+const harness = [+ 'import atexit, hashlib, importlib.util, inspect, shutil, sys, tempfile, types',+ 'from pathlib import Path',+ 'spec = importlib.util.spec_from_file_location("_minimax_h3_mlx_pins", Path(sys.argv[1]))',+ 'pins = importlib.util.module_from_spec(spec)',+ 'spec.loader.exec_module(pins)',+ 'temp = Path(tempfile.mkdtemp())',+ 'atexit.register(shutil.rmtree, temp, True)',+ 'written = []',+ 'def build_pin(drop=(), value_only=(), processor_property=True, merge=None, extra=None, sync_digest=True):',+ ' merge = pins.PINNED_BROADCAST_MERGE if merge is None else merge',+ ' body = ["class MiniMaxH3TextEncoder:"]',+ ' if "_wanted" not in drop:',+ ' body += [" _wanted = \'a value, not a method\'"] if "_wanted" in value_only else [" def _wanted(self, key):", " return key"]',+ ' if "processor" not in drop:',+ ' body += [" @property", " def processor(self):", " return None"] if processor_property else [" processor = \'not-a-property\'"]',+ ' if "_load_weights" not in drop:',+ ' body += [" _load_weights = \'a value, not a method\'"] if "_load_weights" in value_only else [" def _load_weights(self, model_dir, dtype, verbose):", " return None"]',+ ' if "encode" not in drop:',+ ' body += [" encode = \'a value, not a method\'"] if "encode" in value_only else [" def encode(self, prompt, images=None):", " # " + merge] + ([" " + extra] if extra else []) + [" return None"]',+ ' body += [" pass"]',+ // A fresh filename per pin: `inspect.getsource` reads through linecache, which+ // caches by path, so reusing one would hand a second pin the first one's body.+ ' pin = temp / f"pinned_text_encoder_{len(written)}.py"',+ ' written.append(pin)',+ ' pin.write_text("\\n".join(body))',+ ' pin_spec = importlib.util.spec_from_file_location("minimax_h3_mlx.text_encoder", pin)',+ ' module = importlib.util.module_from_spec(pin_spec)',+ ' sys.modules["minimax_h3_mlx"] = types.ModuleType("minimax_h3_mlx")',+ ' sys.modules["minimax_h3_mlx.text_encoder"] = module',+ ' pin_spec.loader.exec_module(module)',+ ' encode = getattr(module.MiniMaxH3TextEncoder, "encode", None)',+ ' if sync_digest and callable(encode):',+ ' pins.PINNED_ENCODE_DIGEST = hashlib.sha256(inspect.getsource(encode).encode("utf-8")).hexdigest()',+ ' return module.MiniMaxH3TextEncoder',+ 'def stub_mlx_vlm(drop=()):',+ ' for name in ("mlx_vlm", "mlx_vlm.models", "mlx_vlm.models.qwen3_vl", "mlx_vlm.models.qwen3_vl.language", "mlx_vlm.models.qwen3_vl.qwen3_vl", "mlx_vlm.utils"):',+ ' sys.modules[name] = types.ModuleType(name)',+ // Each borrowed name is hung off a REAL holder so dropping only the method+ // leaves its class in place — that is the drift an mlx-vlm bump most easily+ // makes, and a stub that dropped the class too would pass for the wrong reason.+ ' model = type("Model", (), {})',+ ' if "Model.merge_input_ids_with_image_features" not in drop:',+ ' model.merge_input_ids_with_image_features = staticmethod(lambda *args: None)',+ ' sys.modules["mlx_vlm.models.qwen3_vl.qwen3_vl"].Model = model',+ ' language_model = type("LanguageModel", (), {})',+ ' if "LanguageModel.get_rope_index" not in drop:',+ ' language_model.get_rope_index = staticmethod(lambda *args, **kwargs: None)',+ ' sys.modules["mlx_vlm.models.qwen3_vl.language"].LanguageModel = language_model',+ ' if "sanitize_weights" not in drop:',+ ' sys.modules["mlx_vlm.utils"].sanitize_weights = lambda *args: None',+ 'def report():',+ ' try:',+ ' pins.verify_pin_seams()',+ ' except RuntimeError as exc:',+ ' print(str(exc))',+ ' else:',+ ' print("ACCEPTED")',+].join('\n');++describe.skipIf(!pyBin)('_minimax_h3_mlx_pins.py', () => {+ it('accepts a pin that still has every seam the corrections patch', () => {+ const output = runPython(`${harness}\n${[+ 'build_pin()',+ 'stub_mlx_vlm()',+ 'report()',+ ].join('\n')}`);+ // The positive case is what makes the refusals below mean something: without+ // it every case could be passing on the same unrelated breakage.+ expect(output.trim()).toBe('ACCEPTED');+ });++ // Install / Repair is the action that moves the pin, so it is where the whole+ // seam set gets reported — rather than one seam at a time, minutes into+ // whichever render happens to touch it first.+ it.each([+ ['_wanted', /no longer exposes MiniMaxH3TextEncoder\._wanted.*Render with the stock text encoder/],+ ['processor', /no longer exposes MiniMaxH3TextEncoder\.processor.*Render text-only/],+ ['_load_weights', /no longer exposes MiniMaxH3TextEncoder\._load_weights.*Render text-only/],+ ['encode', /no longer exposes MiniMaxH3TextEncoder\.encode.*Render text-only/],+ ])('reports a pin that dropped %s', (seam, expected) => {+ const output = runPython(`${harness}\n${[+ `build_pin(drop=("${seam}",))`,+ 'stub_mlx_vlm()',+ 'report()',+ ].join('\n')}`);+ expect(output).toMatch(expected);+ });++ // Presence alone is not the seam for the three the runner wraps and then calls:+ // a name that survived a bump as a plain value would pass a presence check and+ // fail at the call site the check exists to protect.+ it.each([+ ['_wanted', /no longer exposes MiniMaxH3TextEncoder\._wanted/],+ ['_load_weights', /no longer exposes MiniMaxH3TextEncoder\._load_weights/],+ ['encode', /no longer exposes MiniMaxH3TextEncoder\.encode/],+ ])('reports a pin where %s survived as a non-callable', (seam, expected) => {+ const output = runPython(`${harness}\n${[+ `build_pin(value_only=("${seam}",))`,+ 'stub_mlx_vlm()',+ 'report()',+ ].join('\n')}`);+ expect(output).toMatch(expected);+ });++ // A `processor` that is no longer a property is as much a pin change as an+ // absent one: the pinned caller would start calling it, and the replacement+ // the runner binds is a property.+ it('reports a processor that is no longer a property', () => {+ const output = runPython(`${harness}\n${[+ 'build_pin(processor_property=False)',+ 'stub_mlx_vlm()',+ 'report()',+ ].join('\n')}`);+ expect(output).toMatch(/no longer exposes MiniMaxH3TextEncoder\.processor/);+ });++ // `encode` is COPIED rather than wrapped, so its presence is not the seam —+ // its body is. Both halves matter: the merge line says the correction is still+ // needed at all, and the digest says nothing else in the body moved.+ it('reports a pin that stopped merging keyframe embeddings by broadcast', () => {+ const output = runPython(`${harness}\n${[+ // Upstream fixed the merge: the correction has to retire, not shadow it.+ 'build_pin(merge=pins.PINNED_BROADCAST_MERGE.replace("mx.where", "masked_scatter"))',+ 'stub_mlx_vlm()',+ 'report()',+ ].join('\n')}`);+ expect(output).toMatch(/no longer merges keyframe embeddings/);+ });++ it('reports a pin whose encode changed outside the merge', () => {+ const output = runPython(`${harness}\n${[+ // The digest is recorded against the un-drifted body...+ 'build_pin()',+ // ...and then the pin gains a step, with the merge line untouched. Drifting+ // the SOURCE rather than the expected digest is what makes this a probe of+ // the guard: matching the merge line alone could never see this edit.+ 'build_pin(extra="images = images", sync_digest=False)',+ 'stub_mlx_vlm()',+ 'report()',+ ].join('\n')}`);+ expect(output).toMatch(/changed MiniMaxH3TextEncoder\.encode outside the merge/);+ });++ // The pinned port imports neither of these itself, so `minimax_h3_mlx.pipeline`+ // would keep importing cleanly after a pin bump onto an mlx-vlm that dropped+ // one — and the render-time ImportError would be the first anyone heard of it.+ it.each([+ ['Model.merge_input_ids_with_image_features', /no longer exposes mlx_vlm\.models\.qwen3_vl\.qwen3_vl\.Model\.merge_input_ids_with_image_features/],+ ['LanguageModel.get_rope_index', /no longer exposes mlx_vlm\.models\.qwen3_vl\.language\.LanguageModel\.get_rope_index/],+ ['sanitize_weights', /no longer exposes mlx_vlm\.utils\.sanitize_weights/],+ ])('reports an mlx-vlm that dropped %s', (attr, expected) => {+ const output = runPython(`${harness}\n${[+ 'build_pin()',+ `stub_mlx_vlm(drop=("${attr}",))`,+ 'report()',+ ].join('\n')}`);+ expect(output).toMatch(expected);+ });++ // Presence is not the seam either: every borrowed name is CALLED by the+ // correction that borrows it, so one that survived a pin bump as a plain value+ // would pass a presence check and then fail at the call site.+ it('reports a borrowed mlx-vlm name that survived as a non-callable', () => {+ const output = runPython(`${harness}\n${[+ 'build_pin()',+ 'stub_mlx_vlm()',+ 'sys.modules["mlx_vlm.utils"].sanitize_weights = "no longer a function"',+ 'report()',+ ].join('\n')}`);+ expect(output).toMatch(/no longer exposes mlx_vlm\.utils\.sanitize_weights as a callable/);+ });++ it('reports a borrowed mlx-vlm module that no longer imports at all', () => {+ const output = runPython(`${harness}\n${[+ 'build_pin()',+ 'stub_mlx_vlm()',+ // Not merely attribute-less: the whole module is gone, which raises+ // ImportError rather than returning None from getattr.+ 'del sys.modules["mlx_vlm.utils"]',+ 'report()',+ ].join('\n')}`);+ expect(output).toMatch(/no longer exposes mlx_vlm\.utils\.sanitize_weights/);+ });++ // The point of the module: the runner and the probe read ONE copy of the pin,+ // so a bump re-records it once. A second literal anywhere under scripts/ is the+ // failure this whole change exists to prevent — one copy re-recorded, the other+ // left asserting the old pin and passing.+ // `PINNED_BROADCAST_MERGE not in source` is vacuously false for an empty+ // string, so blanking that constant would disarm half the encode guard without+ // failing a single case above — the guard would keep "passing" on any pin.+ it('states a merge line specific enough for the encode guard to mean anything', () => {+ const merge = readFileSync(script, 'utf8').match(/^PINNED_BROADCAST_MERGE = "(.+)"$/m)?.[1];+ expect(merge).toContain('mx.where(');+ expect(merge.length).toBeGreaterThan(40);+ });++ it('keeps the pinned digest in exactly one file', () => {+ const digest = readFileSync(script, 'utf8').match(/^PINNED_ENCODE_DIGEST = "([0-9a-f]{64})"$/m)?.[1];+ expect(digest).toMatch(/^[0-9a-f]{64}$/);+ const holders = readdirSync(scriptsDir)+ .filter((name) => name.endsWith('.py'))+ .filter((name) => readFileSync(join(scriptsDir, name), 'utf8').includes(digest));+ expect(holders).toEqual(['_minimax_h3_mlx_pins.py']);+ });+});diff --git a/scripts/generate_minimax_h3.py b/scripts/generate_minimax_h3.pyindex 2ce8e0e67e..1881a4c8f3 100644--- a/scripts/generate_minimax_h3.py+++ b/scripts/generate_minimax_h3.py@@ -14,9 +14,7 @@ Each `--image` needs its own `--anchor`, in the same order.from __future__ import annotationsimport argparse-import hashlibimport importlib.util-import inspectimport jsonimport reimport shutil@@ -34,6 +32,9 @@ from _minimax_h3_common import ( # noqa: E402FPS, add_h3_common_args, emit_result, load_keyframes, resolve_cached_snapshot,validate_h3_output_args,)+from _minimax_h3_mlx_pins import ( # noqa: E402+ pinned_encoder_hook, verify_pinned_encode_source,+)# The MLX port accepts H3's full documented 4-15s range. The diffusers CUDA@@ -131,15 +132,7 @@ def install_key_prefix_map(rules: list[tuple[str, str]]) -> None:Deliberately NOT a source edit: the checkout is verified clean above, and itmust stay that way."""- from minimax_h3_mlx.text_encoder import MiniMaxH3TextEncoder-- original = getattr(MiniMaxH3TextEncoder, "_wanted", None)- if original is None:- raise RuntimeError(- "The pinned MiniMax H3 runtime no longer exposes MiniMaxH3TextEncoder._wanted, "- "so a substituted text encoder cannot be key-mapped onto it. Render with the "- "stock text encoder, or update PortOS for the new pin."- )+ encoder, original = pinned_encoder_hook("_wanted")def _wanted(self, key: str):for source, target in rules:@@ -148,26 +141,7 @@ def install_key_prefix_map(rules: list[tuple[str, str]]) -> None:breakreturn original(self, key)- MiniMaxH3TextEncoder._wanted = _wanted---def pinned_encoder_hook(name: str, consequence: str, kind: type | None = None):- """Return one attribute of the pinned text encoder, or say the pin moved.-- Each keyframe correction below wraps a different method of- `MiniMaxH3TextEncoder`, and each is only correct against the implementation- it was written for — so every one of them checks its hook is still there and- still the shape it patches, and reports the same two ways out.- """- from minimax_h3_mlx.text_encoder import MiniMaxH3TextEncoder-- hook = getattr(MiniMaxH3TextEncoder, name, None)- if hook is None or (kind is not None and not isinstance(hook, kind)):- raise RuntimeError(- f"The pinned MiniMax H3 runtime no longer exposes MiniMaxH3TextEncoder.{name}, so "- f"{consequence}. Render text-only, or update PortOS for the new pin."- )- return MiniMaxH3TextEncoder, hook+ encoder._wanted = _wanteddef torch_image_stack_available() -> bool:@@ -226,9 +200,7 @@ def install_pil_image_processor() -> None:it doesn't use and — deliberately, like the key-prefix map above — leaves thepinned checkout untouched, because it is verified clean before this runs."""- encoder, _ = pinned_encoder_hook(- "processor", "a keyframe cannot be encoded without PyTorch", kind=property- )+ encoder, _ = pinned_encoder_hook("processor")def processor(self):if self._processor is None:@@ -259,9 +231,7 @@ def install_vision_weight_sanitizer() -> None:correctly-laid-out tensor as a no-op, so this stays right if a later pin (or alater mlx-vlm) starts handing the tower a sanitized weight."""- encoder, original = pinned_encoder_hook(- "_load_weights", "its vision tower cannot be laid out for MLX"- )+ encoder, original = pinned_encoder_hook("_load_weights")def _load_weights(self, model_dir, dtype, verbose):original(self, model_dir, dtype, verbose)@@ -288,20 +258,6 @@ def sanitize_vision_weights(vision) -> None:mx.eval(vision.parameters())-# The merge the pinned port performs instead of a scatter. Asserted before the-# replacement below is installed, so the day upstream fixes this the patch says-# so loudly rather than shadowing a working implementation forever.-PINNED_BROADCAST_MERGE = "mx.where(image_mask[..., None], hidden.astype(inputs_embeds.dtype)[None], inputs_embeds)"--# sha256 of the whole pinned `encode`, because the replacement below re-runs its-# body with one line changed rather than wrapping it. Matching only the merge-# line would let every OTHER edit a pin bump makes — a new `_hidden_states`-# argument, a different dtype, an added step — pass silently into a stale copy.-# Re-record this when bumping MINIMAX_H3_EXPECTED_REVISION, after re-reading-# `encode` and folding whatever changed into the replacement.-PINNED_ENCODE_DIGEST = "8047e407e797cd46cd7538024ca09d97402d369d97b1d825757a1590416bda7d"--def install_vision_embed_merge() -> None:"""Scatter a keyframe's vision rows into the tokens that stand for them.@@ -318,21 +274,8 @@ def install_vision_embed_merge() -> None:the broadcast could never check). A text-only request never reaches the merge,so it is handed straight back to the pinned implementation untouched."""- encoder, original = pinned_encoder_hook(- "encode", "a keyframe cannot be merged into the prompt"- )- source = inspect.getsource(original)- if PINNED_BROADCAST_MERGE not in source:- raise RuntimeError(- "The pinned MiniMax H3 runtime no longer merges keyframe embeddings the way PortOS "- "corrects for; re-check the pin before rendering with a keyframe."- )- if hashlib.sha256(source.encode("utf-8")).hexdigest() != PINNED_ENCODE_DIGEST:- raise RuntimeError(- "The pinned MiniMax H3 runtime changed MiniMaxH3TextEncoder.encode outside the merge "- "PortOS corrects; fold the change into the replacement and re-record "- "PINNED_ENCODE_DIGEST before rendering with a keyframe."- )+ encoder, original = pinned_encoder_hook("encode")+ verify_pinned_encode_source(original)def encode(self, prompt: str, images: list | None = None):# A text-only request never reaches the merge, so it goes back to thediff --git a/scripts/generate_minimax_h3.test.js b/scripts/generate_minimax_h3.test.jsindex 4ab03ea5d3..9cf6f1b654 100644--- a/scripts/generate_minimax_h3.test.js+++ b/scripts/generate_minimax_h3.test.js@@ -32,6 +32,13 @@ const hasMlx = (() => {}})();+// The pin facts these corrections guard against moved to `_minimax_h3_mlx_pins.py`+// so the install-time probe and these render-time guards read one copy. Reach the+// module the RUNNER imported rather than loading a second one by spec: a private+// copy would let a rebinding here pass while the code under test still read the+// shipped digest.+const importPins = 'pins = sys.modules["_minimax_h3_mlx_pins"]';+const importRunner = ['import importlib.util, sys','from pathlib import Path',@@ -715,9 +722,9 @@ describe.skipIf(!pyBin)('generate_minimax_h3.py', () => {// the pinned body with that one line swapped, so it is guarded twice: by the// line it replaces, and by a digest over the whole body it copied.it('corrects a pin that still merges by broadcast, and hands its text-only path back', () => {- const output = runPython(`${importRunner}\n${filePin(["runner.PINNED_BROADCAST_MERGE"])}\n${[+ const output = runPython(`${importRunner}\n${importPins}\n${filePin(["pins.PINNED_BROADCAST_MERGE"])}\n${['import hashlib, inspect',- 'runner.PINNED_ENCODE_DIGEST = hashlib.sha256(',+ 'pins.PINNED_ENCODE_DIGEST = hashlib.sha256(',' inspect.getsource(MiniMaxH3TextEncoder.encode).encode("utf-8")',').hexdigest()','runner.install_vision_embed_merge()',@@ -730,14 +737,14 @@ describe.skipIf(!pyBin)('generate_minimax_h3.py', () => {it.each([// Upstream fixed the merge: the correction has to retire, not shadow it.- [['runner.PINNED_BROADCAST_MERGE.replace("mx.where", "masked_scatter")'], 'digest-of-this-pin', /no longer merges keyframe embeddings/],+ [['pins.PINNED_BROADCAST_MERGE.replace("mx.where", "masked_scatter")'], 'digest-of-this-pin', /no longer merges keyframe embeddings/],// The merge is untouched but something else in the body moved — the copy is// stale in a way matching one line could never see.- [['runner.PINNED_BROADCAST_MERGE'], `"${'0'.repeat(64)}"`, /changed MiniMaxH3TextEncoder\.encode outside the merge/],+ [['pins.PINNED_BROADCAST_MERGE'], `"${'0'.repeat(64)}"`, /changed MiniMaxH3TextEncoder\.encode outside the merge/],])('refuses a pin the copied encode no longer matches (%j)', (body, digest, expected) => {- const output = runPython(`${importRunner}\n${filePin(body)}\n${[+ const output = runPython(`${importRunner}\n${importPins}\n${filePin(body)}\n${['import hashlib, inspect',- `runner.PINNED_ENCODE_DIGEST = ${digest === 'digest-of-this-pin'+ `pins.PINNED_ENCODE_DIGEST = ${digest === 'digest-of-this-pin'? 'hashlib.sha256(inspect.getsource(MiniMaxH3TextEncoder.encode).encode("utf-8")).hexdigest()': digest}`,'try:',diff --git a/scripts/minimax_h3_runtime_probe.py b/scripts/minimax_h3_runtime_probe.pyindex 2b76003ff6..48dc7dc090 100644--- a/scripts/minimax_h3_runtime_probe.py+++ b/scripts/minimax_h3_runtime_probe.py@@ -1,5 +1,13 @@#!/usr/bin/env python3-"""Import-probe a pinned MiniMax H3 source package without trusting its root."""+"""Import-probe a pinned MiniMax H3 source package without trusting its root.++Run at Install / Repair (`isByovRuntimeReady`, `scripts/setup-image-video.sh`),+so this is also where a moved pin gets reported: `verify_pin_seams()` asserts+every method `generate_minimax_h3.py` patches at render time is still there and+still the shape it patches. Those corrections keep their own guards — they are+the last line for a checkout overridden after install — but a pin bump that+breaks one should fail the bump, not the first keyframe render after it.+"""from __future__ import annotations@@ -8,6 +16,7 @@ import sysfrom pathlib import Pathfrom _runner_common import register_source_namespace+from _minimax_h3_mlx_pins import verify_pin_seamsdef main() -> int:@@ -19,7 +28,11 @@ def main() -> int:raise RuntimeError(f"MiniMax H3 runtime source is missing under {runtime_dir}.")register_source_namespace("minimax_h3_mlx", package_dir)importlib.import_module("minimax_h3_mlx.pipeline")+ # Kept ahead of verify_pin_seams even though that reaches into the same+ # package: a venv that never installed mlx-vlm has to report as an+ # ImportError naming the missing distribution, not as a pin that moved.importlib.import_module("mlx_vlm.models.qwen3_vl.language")+ verify_pin_seams()return 0diff --git a/scripts/minimax_h3_runtime_probe.test.js b/scripts/minimax_h3_runtime_probe.test.jsnew file mode 100644index 0000000000..858b0da4ff--- /dev/null+++ b/scripts/minimax_h3_runtime_probe.test.js@@ -0,0 +1,133 @@+import { execFileSync } from 'node:child_process';+import { fileURLToPath } from 'node:url';+import { dirname, join } from 'node:path';+import { describe, expect, it } from 'vitest';+import { resolveTestPython } from '../server/lib/testHelper.js';++// The probe `isByovRuntimeReady()` and scripts/setup-image-video.sh run at+// Install / Repair. It imports the pinned package out of a namespace that never+// exposes the checkout root, and — since the seams moved here — refuses a pin+// whose text encoder no longer fits the corrections generate_minimax_h3.py+// installs at render time.+const scriptsDir = dirname(fileURLToPath(import.meta.url));+const script = join(scriptsDir, 'minimax_h3_runtime_probe.py');++// Probe for an interpreter that actually RUNS rather than assuming a name (see+// _minimax_h3_mlx_pins.test.js for why a bare name is not enough on Windows).+const pyBin = resolveTestPython();++// Drive the probe as `__main__` through runpy rather than spawning it directly:+// the mlx-vlm and pinned-package imports have to be satisfied by stubs, and a+// bare interpreter has neither. Everything the probe itself does — the source+// namespace registration, the imports, verify_pin_seams — still runs for real.+const runProbe = (setup) => {+ const source = [+ 'import runpy, sys, tempfile, types',+ 'from pathlib import Path',+ 'probe = Path(sys.argv[1])',+ // The probe reaches its siblings through sys.path[0], which runpy does not+ // set for it.+ 'sys.path.insert(0, str(probe.parent))',+ 'runtime = Path(tempfile.mkdtemp()) / "runtime"',+ 'package = runtime / "minimax_h3_mlx"',+ 'package.mkdir(parents=True)',+ '(package / "pipeline.py").write_text("PIPELINE = True")',+ // mlx-vlm is not installed under a bare interpreter, and the two names the+ // corrections borrow are seams of their own, so stub the tree explicitly.+ 'for name in ("mlx_vlm", "mlx_vlm.models", "mlx_vlm.models.qwen3_vl", "mlx_vlm.models.qwen3_vl.language", "mlx_vlm.models.qwen3_vl.qwen3_vl", "mlx_vlm.utils"):',+ ' sys.modules[name] = types.ModuleType(name)',+ 'sys.modules["mlx_vlm.models.qwen3_vl.qwen3_vl"].Model = type("Model", (), {"merge_input_ids_with_image_features": staticmethod(lambda *args: None)})',+ 'sys.modules["mlx_vlm.models.qwen3_vl.language"].LanguageModel = type("LanguageModel", (), {"get_rope_index": staticmethod(lambda *args, **kwargs: None)})',+ 'sys.modules["mlx_vlm.utils"].sanitize_weights = lambda *args: None',+ ...setup,+ 'sys.argv = ["minimax_h3_runtime_probe.py", str(runtime)]',+ 'try:',+ ' runpy.run_path(str(probe), run_name="__main__")',+ 'except SystemExit as exc:',+ ' print(f"EXIT:{exc.code}")',+ 'except RuntimeError as exc:',+ ' print(str(exc))',+ ].join('\n');+ return execFileSync(pyBin, ['-c', source, script], { encoding: 'utf8' });+};++// Write the pinned encoder into the checkout the probe is pointed at, so+// `register_source_namespace` + `inspect.getsource` both see a real file — which+// is what the encode digest is computed over. `pins` is imported first and the+// digest re-recorded against this stand-in, because the probe's own import of+// the module resolves to the same sys.modules entry.+const conformingPin = [+ 'import hashlib, importlib, inspect',+ 'pins = importlib.import_module("_minimax_h3_mlx_pins")',+ '(package / "text_encoder.py").write_text("\\n".join([',+ ' "class MiniMaxH3TextEncoder:",',+ ' " def _wanted(self, key):",',+ ' " return key",',+ ' " @property",',+ ' " def processor(self):",',+ ' " return None",',+ ' " def _load_weights(self, model_dir, dtype, verbose):",',+ ' " return None",',+ ' " def encode(self, prompt, images=None):",',+ ' " # " + pins.PINNED_BROADCAST_MERGE,',+ ' " return None",',+ ']))',+];+const syncDigest = [+ 'from minimax_h3_mlx.text_encoder import MiniMaxH3TextEncoder as Pinned',+ 'pins.PINNED_ENCODE_DIGEST = hashlib.sha256(inspect.getsource(Pinned.encode).encode("utf-8")).hexdigest()',+];++describe.skipIf(!pyBin)('minimax_h3_runtime_probe.py', () => {+ it('passes a checkout whose text encoder still has every patched seam', () => {+ const output = runProbe([+ ...conformingPin,+ // Importing the pinned module needs the namespace the probe registers, so+ // register it here too — the probe's own call is idempotent.+ 'from _runner_common import register_source_namespace',+ 'register_source_namespace("minimax_h3_mlx", package)',+ ...syncDigest,+ ]);+ expect(output.trim()).toBe('EXIT:0');+ });++ // The whole point of moving the assertions here: a pin bump that breaks a+ // correction has to fail the bump, not the first keyframe render after it.+ it('refuses a checkout whose text encoder lost a patched seam', () => {+ const output = runProbe([+ ...conformingPin,+ 'from _runner_common import register_source_namespace',+ 'register_source_namespace("minimax_h3_mlx", package)',+ ...syncDigest,+ // Written after the digest is recorded, so `encode` is untouched and this+ // case can only be reported for the seam it actually broke.+ '(package / "text_encoder.py").write_text((package / "text_encoder.py").read_text().replace("_load_weights", "_load_weights_renamed"))',+ 'del sys.modules["minimax_h3_mlx.text_encoder"]',+ ]);+ expect(output).toMatch(/no longer exposes MiniMaxH3TextEncoder\._load_weights/);+ expect(output).not.toMatch(/EXIT:0/);+ });++ // The other half of what verify_pin_seams checks: names the corrections borrow+ // from mlx-vlm rather than from the pinned checkout. Nothing about the checkout+ // moved here, so only an mlx-vlm-side drift can produce this.+ it('refuses a runtime whose mlx-vlm dropped a borrowed name', () => {+ const output = runProbe([+ ...conformingPin,+ 'from _runner_common import register_source_namespace',+ 'register_source_namespace("minimax_h3_mlx", package)',+ ...syncDigest,+ 'del sys.modules["mlx_vlm.models.qwen3_vl.qwen3_vl"].Model.merge_input_ids_with_image_features',+ ]);+ expect(output).toMatch(/no longer exposes mlx_vlm\.models\.qwen3_vl\.qwen3_vl\.Model\.merge_input_ids_with_image_features/);+ expect(output).not.toMatch(/EXIT:0/);+ });++ it('still refuses a runtime directory with no pinned package in it', () => {+ const output = runProbe([+ ...conformingPin,+ '(package / "pipeline.py").unlink()',+ ]);+ expect(output).toMatch(/MiniMax H3 runtime source is missing/);+ });+});