Skip to content

Commit 8c946d7

Browse files
justinchubyCopilot
andcommitted
Fix atomic GGUF runtime CLI publication
Route runtime preflight and publication through canonical GGUF shard discovery, bind evidence to the full stable source set, and delay success output until atomic package publication completes. Add regressions for incomplete and invalid shards, publication failures, cleanup, identity, and output ordering. Signed-off-by: Justin Chu <[email protected]> Co-authored-by: Copilot App <[email protected]>
1 parent b2f4334 commit 8c946d7

8 files changed

Lines changed: 363 additions & 49 deletions

File tree

‎src/mobius/__main__.py‎

Lines changed: 33 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
import os
1313
import re
1414
from collections.abc import Sequence
15-
from typing import TYPE_CHECKING
15+
from typing import TYPE_CHECKING, Any
1616

1717
import tqdm
1818

@@ -660,13 +660,13 @@ def _cmd_build_gguf(args: argparse.Namespace) -> None:
660660
_resolve_gguf_path,
661661
_validate_gguf_model,
662662
)
663-
from mobius.integrations.gguf._reader import GGUFModel
663+
from mobius.integrations.gguf._shard_set import open_gguf_model
664664
from mobius.integrations.gguf._spec import Support
665665

666666
# Resolve and validate the exact selected source before graph construction
667667
# so a deferred tokenizer cannot leave a graph-only directory behind.
668668
resolved_gguf_path = _resolve_gguf_path(gguf_path)
669-
gguf_model = GGUFModel(resolved_gguf_path)
669+
gguf_model = open_gguf_model(resolved_gguf_path)
670670
_validate_gguf_model(gguf_model, source=str(resolved_gguf_path))
671671
architecture_spec = get_arch_spec(gguf_model.architecture)
672672
if architecture_spec.runtime is not Support.SUPPORTED:
@@ -715,27 +715,24 @@ def _cmd_build_gguf(args: argparse.Namespace) -> None:
715715
),
716716
max_workers=args.max_workers,
717717
)
718-
for name in pkg:
719-
use_subfolders = len(pkg) > 1
720-
if use_subfolders:
721-
path = os.path.join(output_dir, name, "model.onnx")
722-
else:
723-
path = os.path.join(output_dir, "model.onnx")
724-
print(f"Saved {name} to {path}")
718+
_print_saved_gguf_models(pkg, output_dir)
725719

726-
# Save the trailing MTP / "nextn" self-speculative head sidecar (when the
727-
# GGUF shipped one). ModelPackage.save() persisted it into ``mtp/``.
728-
mtp_head = getattr(pkg, "mtp_head", None)
729-
if mtp_head is not None:
730-
mtp_dir = os.path.join(output_dir, "mtp")
731-
print(f"Saved mtp head to {os.path.join(mtp_dir, 'model.onnx')}")
720+
# ModelPackage.save() persisted the MTP sidecar into its manifest-selected
721+
# collision-safe directory.
722+
mtp_head = getattr(pkg, "mtp_head", None)
723+
if mtp_head is not None:
724+
from mobius._model_package import _read_mtp_sidecar_name
732725

733-
draft_manifest = getattr(pkg, "draft_manifest", None)
734-
if draft_manifest is not None:
735-
from mobius.integrations.gguf._draft import write_draft_manifest
726+
mtp_dir = _read_mtp_sidecar_name(output_dir)
727+
assert mtp_dir is not None
728+
print(f"Saved mtp head to {os.path.join(output_dir, mtp_dir, 'model.onnx')}")
736729

737-
manifest_path = write_draft_manifest(draft_manifest, output_dir)
738-
print(f"Saved draft pairing manifest to {manifest_path}")
730+
draft_manifest = getattr(pkg, "draft_manifest", None)
731+
if draft_manifest is not None:
732+
from mobius.integrations.gguf._draft import write_draft_manifest
733+
734+
manifest_path = write_draft_manifest(draft_manifest, output_dir)
735+
print(f"Saved draft pairing manifest to {manifest_path}")
739736

740737
if runtime in ("onnx-genai", "ort-genai"):
741738
from mobius.integrations.gguf import write_gguf_runtime_package
@@ -755,10 +752,25 @@ def _cmd_build_gguf(args: argparse.Namespace) -> None:
755752
),
756753
max_workers=args.max_workers,
757754
)
755+
# The writer returns only after atomically publishing the complete graph,
756+
# tokenizer, and runtime configuration directory.
757+
_print_saved_gguf_models(pkg, output_dir)
758758
for name, path in artifacts.items():
759759
print(f" {name}: {path}")
760760

761761

762+
def _print_saved_gguf_models(pkg: Any, output_dir: str) -> None:
763+
"""Report model paths only after their containing package is durable."""
764+
use_subfolders = len(pkg) > 1
765+
for name in pkg:
766+
path = (
767+
os.path.join(output_dir, name, "model.onnx")
768+
if use_subfolders
769+
else os.path.join(output_dir, "model.onnx")
770+
)
771+
print(f"Saved {name} to {path}")
772+
773+
762774
def _cmd_convert_comfyui(args: argparse.Namespace) -> None:
763775
"""Execute the 'convert-comfyui' subcommand."""
764776
from mobius.integrations.onnx_genai import convert_comfyui_workflow

‎src/mobius/integrations/gguf/_builder.py‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3912,7 +3912,14 @@ def build_from_gguf(
39123912

39133913
if draft_manifest is not None:
39143914
pkg.draft_manifest = draft_manifest
3915-
pkg.gguf_source_path = str(Path(gguf_path).resolve())
3915+
canonical_source_path = (
3916+
gguf_model.shard_paths[0] if isinstance(gguf_model, GgufShardSet) else Path(gguf_path)
3917+
)
3918+
if isinstance(gguf_model, GgufShardSet):
3919+
logical_source_filename = (
3920+
Path(logical_source_filename).with_name(canonical_source_path.name).as_posix()
3921+
)
3922+
pkg.gguf_source_path = str(canonical_source_path.resolve())
39163923
pkg.gguf_source_filename = logical_source_filename
39173924
pkg.gguf_architecture = spec.gguf_arch
39183925
pkg.gguf_execution_provider = execution_provider

‎src/mobius/integrations/gguf/_runtime_evidence.py‎

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -366,14 +366,33 @@ def gguf_artifact_identity(
366366
filename: str | None = None,
367367
) -> GGUFArtifactIdentity:
368368
"""Fingerprint source bytes and parsed tensor census under a canonical architecture."""
369-
stat, sha256 = _hash_regular_file(source_path)
370-
qtypes = Counter(tensor.tensor_type.name for tensor in gguf_model._reader.tensors)
369+
shard_paths = getattr(gguf_model, "shard_paths", None)
370+
if shard_paths is None:
371+
stat, sha256 = _hash_regular_file(source_path)
372+
size = stat.st_size
373+
else:
374+
paths = tuple(Path(path) for path in shard_paths)
375+
if not paths:
376+
raise ValueError("A GGUF shard set must contain at least one source file.")
377+
digest = hashlib.sha256()
378+
size = 0
379+
for path in paths:
380+
stat, file_sha256 = _hash_regular_file(path)
381+
encoded = path.name.encode("utf-8")
382+
digest.update(len(encoded).to_bytes(8, "big"))
383+
digest.update(encoded)
384+
digest.update(stat.st_size.to_bytes(8, "big"))
385+
digest.update(bytes.fromhex(file_sha256))
386+
size += stat.st_size
387+
sha256 = digest.hexdigest()
388+
tensors = gguf_model.reader_tensors()
389+
qtypes = Counter(tensor.tensor_type.name for tensor in tensors)
371390
return GGUFArtifactIdentity(
372391
architecture=architecture,
373392
filename=filename or source_path.name,
374-
size=stat.st_size,
393+
size=size,
375394
sha256=sha256,
376-
tensor_count=len(gguf_model._reader.tensors),
395+
tensor_count=len(tensors),
377396
tensor_qtypes=tuple(sorted(qtypes.items())),
378397
)
379398

‎src/mobius/integrations/gguf/_runtime_evidence_test.py‎

Lines changed: 42 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -53,13 +53,13 @@ def _record(payload: bytes) -> GGUFRuntimeEvidence:
5353

5454

5555
def _model():
56+
tensors = [
57+
SimpleNamespace(tensor_type=SimpleNamespace(name="Q4_K")),
58+
SimpleNamespace(tensor_type=SimpleNamespace(name="F32")),
59+
]
5660
return SimpleNamespace(
57-
_reader=SimpleNamespace(
58-
tensors=[
59-
SimpleNamespace(tensor_type=SimpleNamespace(name="Q4_K")),
60-
SimpleNamespace(tensor_type=SimpleNamespace(name="F32")),
61-
]
62-
)
61+
_reader=SimpleNamespace(tensors=tensors),
62+
reader_tensors=lambda: tensors,
6363
)
6464

6565

@@ -153,6 +153,42 @@ def test_matching_evidence_rejects_source_replaced_after_build(tmp_path, monkeyp
153153
)
154154

155155

156+
def test_sharded_artifact_identity_frames_every_shard_and_tensor(tmp_path) -> None:
157+
first = tmp_path / "model-00001-of-00002.gguf"
158+
second = tmp_path / "model-00002-of-00002.gguf"
159+
first.write_bytes(b"first")
160+
second.write_bytes(b"second")
161+
tensors = [
162+
SimpleNamespace(tensor_type=SimpleNamespace(name="F32")),
163+
SimpleNamespace(tensor_type=SimpleNamespace(name="Q4_K")),
164+
]
165+
model = SimpleNamespace(
166+
shard_paths=[first, second],
167+
reader_tensors=lambda: tensors,
168+
)
169+
170+
identity = gguf_artifact_identity(
171+
second,
172+
model,
173+
architecture="llama",
174+
filename=first.name,
175+
)
176+
177+
assert identity.filename == first.name
178+
assert identity.size == len(b"firstsecond")
179+
assert identity.tensor_count == 2
180+
assert identity.tensor_qtypes == (("F32", 1), ("Q4_K", 1))
181+
182+
second.write_bytes(b"change")
183+
changed = gguf_artifact_identity(
184+
first,
185+
model,
186+
architecture="llama",
187+
filename=first.name,
188+
)
189+
assert changed.sha256 != identity.sha256
190+
191+
156192
def test_evidence_id_cannot_cross_architectures(monkeypatch) -> None:
157193
record = _record(b"pinned-gguf")
158194
monkeypatch.setattr(

‎src/mobius/integrations/gguf/_runtime_package.py‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,11 +25,11 @@
2525
from typing import Any, Literal
2626

2727
from mobius.integrations.gguf._arch_registry import get_arch_spec
28-
from mobius.integrations.gguf._reader import GGUFModel
2928
from mobius.integrations.gguf._runtime_evidence import (
3029
gguf_graph_package_identity,
3130
matching_runtime_evidence,
3231
)
32+
from mobius.integrations.gguf._shard_set import open_gguf_model
3333
from mobius.integrations.gguf._spec import Support
3434
from mobius.integrations.gguf._tokenizer import (
3535
GGUFTokenizerAsset,
@@ -197,7 +197,12 @@ def write_gguf_runtime_package(
197197
)
198198

199199
source_path = Path(getattr(pkg, "gguf_source_path", gguf_path))
200-
source_model = GGUFModel(source_path)
200+
source_model = open_gguf_model(source_path)
201+
if not source_model.source_matches_path():
202+
raise ValueError(
203+
"The GGUF source changed while the canonical reader was opening it; "
204+
"refusing runtime publication."
205+
)
201206
source_architecture = get_arch_spec(source_model.architecture).gguf_arch
202207
if source_architecture != architecture:
203208
raise ValueError(
@@ -217,6 +222,11 @@ def write_gguf_runtime_package(
217222
tokenizer_repository=tokenizer_repository,
218223
tokenizer_revision=tokenizer_revision,
219224
)
225+
if not source_model.source_matches_path():
226+
raise ValueError(
227+
"The GGUF source changed while runtime evidence was being matched; "
228+
"refusing runtime publication."
229+
)
220230
source_metadata = source_model.metadata
221231
verdict = inspect_gguf_tokenizer(
222232
source_metadata,

‎src/mobius/integrations/gguf/_runtime_package_test.py‎

Lines changed: 55 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,9 @@ def test_deferred_architecture_rejects_before_source_read_or_output(self, tmp_pa
129129
reason="independent parity is missing",
130130
),
131131
),
132-
mock.patch("mobius.integrations.gguf._runtime_package.GGUFModel") as read_source,
132+
mock.patch(
133+
"mobius.integrations.gguf._runtime_package.open_gguf_model"
134+
) as read_source,
133135
pytest.raises(ValueError, match=r"runtime packaging.*deferred"),
134136
):
135137
_write_runtime(pkg, tmp_path / "m.gguf", out)
@@ -141,8 +143,12 @@ def test_atomically_emits_graph_tokenizer_and_runtime_config(self, tmp_path):
141143
out = tmp_path / "out"
142144
with (
143145
mock.patch(
144-
"mobius.integrations.gguf._runtime_package.GGUFModel",
145-
return_value=SimpleNamespace(metadata={}, architecture="llama"),
146+
"mobius.integrations.gguf._runtime_package.open_gguf_model",
147+
return_value=SimpleNamespace(
148+
metadata={},
149+
architecture="llama",
150+
source_matches_path=lambda: True,
151+
),
146152
),
147153
mock.patch(
148154
"mobius.integrations.gguf._runtime_package.inspect_gguf_tokenizer",
@@ -164,11 +170,41 @@ def test_atomically_emits_graph_tokenizer_and_runtime_config(self, tmp_path):
164170
assert Path(artifacts["inference_metadata"]) == out / "inference_metadata.yaml"
165171
assert not list(tmp_path.glob(".out.*.tmp"))
166172

173+
def test_failure_after_graph_save_removes_staging_and_publishes_nothing(self, tmp_path):
174+
pkg = _FakePackage()
175+
out = tmp_path / "out"
176+
with (
177+
mock.patch(
178+
"mobius.integrations.gguf._runtime_package.open_gguf_model",
179+
return_value=SimpleNamespace(
180+
metadata={},
181+
architecture="llama",
182+
source_matches_path=lambda: True,
183+
),
184+
),
185+
mock.patch(
186+
"mobius.integrations.gguf._runtime_package.inspect_gguf_tokenizer",
187+
return_value=_materialized(),
188+
),
189+
mock.patch(
190+
"mobius.integrations.gguf._runtime_package.materialize_gguf_tokenizer",
191+
side_effect=OSError("tokenizer asset write failed"),
192+
),
193+
pytest.raises(OSError, match="tokenizer asset write failed"),
194+
):
195+
_write_runtime(pkg, tmp_path / "m.gguf", out)
196+
197+
assert pkg.saved_to is not None
198+
assert not out.exists()
199+
assert not list(tmp_path.glob(".out.*.tmp"))
200+
167201
def test_missing_pinned_tokenizer_source_rejects_before_save_or_output(self, tmp_path):
168202
pkg = _FakePackage()
169203
out = tmp_path / "out"
170204
with (
171-
mock.patch("mobius.integrations.gguf._runtime_package.GGUFModel") as read_source,
205+
mock.patch(
206+
"mobius.integrations.gguf._runtime_package.open_gguf_model"
207+
) as read_source,
172208
pytest.raises(ValueError, match="explicit tokenizer_repository"),
173209
):
174210
write_gguf_runtime_package(pkg, tmp_path / "m.gguf", out)
@@ -181,8 +217,12 @@ def test_replaced_source_tokenizer_rejects_before_save_or_output(self, tmp_path)
181217
out = tmp_path / "out"
182218
with (
183219
mock.patch(
184-
"mobius.integrations.gguf._runtime_package.GGUFModel",
185-
return_value=SimpleNamespace(metadata={}, architecture="llama"),
220+
"mobius.integrations.gguf._runtime_package.open_gguf_model",
221+
return_value=SimpleNamespace(
222+
metadata={},
223+
architecture="llama",
224+
source_matches_path=lambda: True,
225+
),
186226
),
187227
mock.patch(
188228
"mobius.integrations.gguf._runtime_package.inspect_gguf_tokenizer",
@@ -205,7 +245,9 @@ def test_existing_output_is_never_replaced(self, tmp_path):
205245
sentinel = out / "sentinel.bin"
206246
sentinel.write_bytes(b"unchanged")
207247
with (
208-
mock.patch("mobius.integrations.gguf._runtime_package.GGUFModel") as read_source,
248+
mock.patch(
249+
"mobius.integrations.gguf._runtime_package.open_gguf_model"
250+
) as read_source,
209251
pytest.raises(FileExistsError, match="non-atomic directory replacement"),
210252
):
211253
_write_runtime(pkg, tmp_path / "m.gguf", out)
@@ -246,7 +288,9 @@ def test_runtime_rejects_unevidenced_mtp_before_source_read(self, tmp_path, runt
246288
pkg.mtp_head = SimpleNamespace(config=object())
247289
out = tmp_path / "out"
248290
with (
249-
mock.patch("mobius.integrations.gguf._runtime_package.GGUFModel") as read_source,
291+
mock.patch(
292+
"mobius.integrations.gguf._runtime_package.open_gguf_model"
293+
) as read_source,
250294
pytest.raises(ValueError, match="runtime-evidenced GGUF MTP"),
251295
):
252296
_write_runtime(pkg, tmp_path / "m.gguf", out, runtime=runtime)
@@ -261,7 +305,9 @@ def test_unknown_runtime_rejects_before_source_read(self, tmp_path):
261305

262306
def test_save_model_false_is_rejected_before_source_read(self, tmp_path):
263307
with (
264-
mock.patch("mobius.integrations.gguf._runtime_package.GGUFModel") as read_source,
308+
mock.patch(
309+
"mobius.integrations.gguf._runtime_package.open_gguf_model"
310+
) as read_source,
265311
pytest.raises(ValueError, match="save_model=False is not supported"),
266312
):
267313
write_gguf_runtime_package(

‎src/mobius/integrations/gguf/_shard_set.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -442,6 +442,10 @@ def manifest(self) -> GgufShardManifest:
442442
def shard_paths(self) -> list[Path]:
443443
return [Path(shard._path) for shard in self._shards]
444444

445+
def source_matches_path(self) -> bool:
446+
"""Return whether every shard still names the exact file that was opened."""
447+
return all(shard.source_matches_path() for shard in self._shards)
448+
445449
def _safe_architecture(self) -> str | None:
446450
try:
447451
return self._primary.architecture

0 commit comments

Comments
 (0)