Skip to content

classes

classes

Load the three capability-class layers without changing existing profile loading.

Classes

Functions:

class_source_paths

class_source_paths(*, user_path=None, venue_path=None)

One path owner for CLI, conductor, validator, and reload watcher.

Source code in src/marianne/instruments/classes.py
def class_source_paths(
    *,
    user_path: Path | None = None,
    venue_path: Path | None = None,
) -> tuple[Path, Path, Path]:
    """One path owner for CLI, conductor, validator, and reload watcher."""
    default = Path(__file__).parent / "classes" / "default.yaml"
    user = user_path if user_path is not None else Path.home() / ".marianne" / "classes.yaml"
    venue = venue_path if venue_path is not None else Path(".marianne") / "classes.yaml"
    return default.resolve(), user.resolve(), venue.resolve()

unloaded_venue_class_layer

unloaded_venue_class_layer(class_map, client_cwd, requested)

A venue class file beside the caller that this class map never read (GH #510).

The conductor resolves the venue layer from ITS working directory (under the shipped unit, $HOME, which makes "venue" the user file). A .marianne/classes.yaml beside the submitted score that defines one of the classes the score uses is then read by mzt validate from the project and ignored by dispatch. Returns (beside, loaded) when that is the case, else None. Only classes the score actually names count: a venue file that redefines nothing the job uses changes nothing.

Source code in src/marianne/instruments/classes.py
def unloaded_venue_class_layer(
    class_map: ClassMap,
    client_cwd: Path | None,
    requested: set[str],
) -> tuple[Path, Path] | None:
    """A venue class file beside the caller that this class map never read (GH #510).

    The conductor resolves the venue layer from ITS working directory (under
    the shipped unit, ``$HOME``, which makes "venue" the user file). A
    ``.marianne/classes.yaml`` beside the submitted score that defines one of
    the classes the score uses is then read by ``mzt validate`` from the
    project and ignored by dispatch. Returns ``(beside, loaded)`` when that is
    the case, else ``None``. Only classes the score actually names count: a
    venue file that redefines nothing the job uses changes nothing.
    """
    if client_cwd is None or not requested:
        return None
    beside = client_cwd / ".marianne" / "classes.yaml"
    if not beside.is_file():
        return None
    loaded = next((r.path for r in class_map.layers if r.layer == "venue"), None)
    if loaded is None:
        return None
    try:
        if beside.resolve() == loaded.resolve():
            return None
        data = parse_classes_file(beside.read_text(encoding="utf-8"))
    except (OSError, ValueError, yaml.YAMLError):
        # An unreadable or invalid file beside the caller is the validator's
        # report (V324), not this gate's.
        return None
    if not (set(data.classes) & requested):
        return None
    return beside, loaded

requested_class_names

requested_class_names(config, profile_names, class_map)

Class names this score resolves through the map (not aliases, not profiles).

Source code in src/marianne/instruments/classes.py
def requested_class_names(
    config: JobConfig, profile_names: set[str], class_map: ClassMap,
) -> set[str]:
    """Class names this score resolves through the map (not aliases, not profiles)."""
    names: set[str] = set()
    for _location, name in _instrument_positions(config):
        if name in config.instruments or name in profile_names:
            continue
        if name in class_map.classes or name in CLASS_VOCABULARY:
            names.add(name)
    return names

load_class_map

load_class_map(*, user_path=None, venue_path=None, profile_names=None)

Replace whole chains per layer; preserve lower entries on a broken layer.

Source code in src/marianne/instruments/classes.py
def load_class_map(
    *,
    user_path: Path | None = None,
    venue_path: Path | None = None,
    profile_names: set[str] | None = None,
) -> ClassMap:
    """Replace whole chains per layer; preserve lower entries on a broken layer."""
    names: tuple[LayerName, ...] = ("default", "user", "venue")
    paths = class_source_paths(user_path=user_path, venue_path=venue_path)
    merged: dict[str, ClassSnapshotEntry] = {}
    layers: list[ClassLayerRecord] = []
    failures: list[ClassLoadFailure] = []
    tombstones: set[str] = set()
    for layer, path in zip(names, paths, strict=True):
        if not path.exists():
            layers.append(ClassLayerRecord(layer=layer, path=path))
            continue
        try:
            content = path.read_bytes()
            digest = hashlib.sha256(content).hexdigest()
            data = parse_classes_file(content.decode("utf-8"))
            if profile_names is not None and layer != "default":
                collisions = set(data.classes) & profile_names
                if collisions:
                    raise ValueError(
                        "class name collides with a registered profile: "
                        + ", ".join(sorted(collisions))
                    )
        except (OSError, UnicodeError, yaml.YAMLError, ValueError, TypeError) as exc:
            # TypeError: a sequence or mapping used as a YAML key is unhashable
            # and escapes the duplicate-key check; a broken layer is refused,
            # lower layers stand (Forge Inspect P1, loader-unhashable-keys).
            layers.append(ClassLayerRecord(layer=layer, path=path))
            failures.append(ClassLoadFailure(layer=layer, path=path, reason=str(exc)))
            continue
        layers.append(ClassLayerRecord(layer=layer, path=path, sha256=digest))
        for name, chain in data.classes.items():
            if chain is None:
                merged.pop(name, None)
                tombstones.add(name)
            else:
                merged[name] = ClassSnapshotEntry(chain=chain, source_layer=layer)
                tombstones.discard(name)
    return ClassMap(merged, layers, failures, frozenset(tombstones))

resolve_job_classes

resolve_job_classes(config, profile_names, class_map, *, previous=None, phase='submit', expected_route=False)

Resolve only this job's class names, preserving its prior chains on resume.

The daemon owns registry membership and supplies it here. This function has no backend availability probe: a registered but unreachable entry remains in the frozen chain for the baton's existing fallback path.

Source code in src/marianne/instruments/classes.py
def resolve_job_classes(
    config: JobConfig,
    profile_names: set[str],
    class_map: ClassMap,
    *,
    previous: ClassSnapshot | None = None,
    phase: str = "submit",
    expected_route: bool = False,
) -> ClassSnapshot | None:
    """Resolve only this job's class names, preserving its prior chains on resume.

    The daemon owns registry membership and supplies it here. This function has
    no backend availability probe: a registered but unreachable entry remains
    in the frozen chain for the baton's existing fallback path.
    """
    for alias, definition in config.instruments.items():
        for alias_entry in definition.entries:
            if alias_entry.profile in class_map.classes or alias_entry.profile in CLASS_VOCABULARY:
                raise ValueError(
                    f"instrument alias '{alias}' names class '{alias_entry.profile}' as a "
                    "profile; an alias entry must name a profile",
                )
        # An alias naming a profile this machine lacks is not a class state
        # either (D-I1): main admitted it and V210 rates it; hello.yaml's
        # local-only aliases are exactly this on a fresh install.

    requested: set[str] = set()
    for location, name in _instrument_positions(config):
        if name in config.instruments or name in profile_names:
            continue
        if (previous is not None and name in previous.classes) or name in class_map.classes:
            requested.add(name)
        elif name in CLASS_VOCABULARY or name in class_map.tombstones:
            raise ValueError(
                f"{location}: class '{name}' has no instruments configured on this machine; "
                "run 'mzt instruments classes write' or define it in ~/.marianne/classes.yaml",
            )
        # Any other unknown name is NOT the class seam's business (D-I1,
        # Blueprint Integration C-I1): before classes, the daemon refused
        # nothing by instrument name — S3's V210/V211 rate it ERROR and
        # dispatch fails that seat only. Refusing it here changed admission
        # for scores that never use classes (6 of 68 tracked on a fresh
        # install, 1 on this machine). It is left to those owners.

    if expected_route and requested:
        raise ValueError("classes cannot be used with a reviewed route (expected_route)")

    if not requested and previous is None:
        return None
    selected = dict(previous.classes) if previous is not None else {}
    for name in requested - selected.keys():
        entry = class_map.classes[name]
        # A-C5 (Blueprint acceptance addendum, decided 2026-10-14): a chain
        # with SOME unregistered entries is admitted. The validator rates it
        # V311 WARN ("the job will start at the first available entry") and
        # dispatch types a registry miss INSTRUMENT_UNAVAILABLE and advances
        # at once (PO-C9, #425); refusing it here contradicted both, and made
        # a shared class map unusable on any machine lacking one entry. A
        # chain with NO registered entry is still refused (V310's state).
        if not any(step.profile in profile_names for step in entry.chain):
            entries = ", ".join(step.profile for step in entry.chain)
            raise ValueError(
                f"class '{name}' has no instruments registered on this machine "
                f"(chain: {entries}); run 'mzt instruments classes write' or register "
                "one of them",
            )
        selected[name] = entry.model_copy(update={"resolved_at": phase}, deep=True)
    layers = list(previous.layers) if previous is not None else list(class_map.layers)
    snapshot = ClassSnapshot.from_classes(selected, layers)

    # A score-level model would silently override the class's choice for only
    # one entry. Reject it at the same admission seam that freezes the chain.
    from marianne.core.sheet import build_sheets

    for sheet in build_sheets(config, classes=snapshot):
        resolution = sheet.instrument_resolution
        if resolution is None:
            continue
        movement = config.movements.get(sheet.movement)
        for scope in (
            config.instrument_config,
            movement.instrument_config if movement is not None else {},
            config.sheet.per_sheet_instrument_config.get(sheet.num, {}),
        ):
            if "model" in scope:
                raise ValueError(
                    f"sheet {sheet.num}: model '{scope['model']}' cannot apply to "
                    f"class '{resolution.requested}' (its entries are different instruments)",
                )
    return snapshot

write_user_classes

write_user_classes(*, path=None, force=False, if_absent=False, dry_run=False)

Generate a policy map and replace the user layer with provenance custody.

Existing handwritten or modified maps require force. A real replacement is backed up first and written through fsync + atomic rename.

Source code in src/marianne/instruments/classes.py
def write_user_classes(
    *,
    path: Path | None = None,
    force: bool = False,
    if_absent: bool = False,
    dry_run: bool = False,
) -> tuple[Path, str, bool]:
    """Generate a policy map and replace the user layer with provenance custody.

    Existing handwritten or modified maps require ``force``. A real replacement
    is backed up first and written through fsync + atomic rename.
    """
    from marianne.instruments.class_policy import (
        canonical_probe,
        explain_hinted_exclusions,
        probe_builtin_profiles,
        select_class_chains,
    )
    from marianne.instruments.loader import InstrumentProfileLoader, profile_source_dirs

    destination = path or class_source_paths()[1]
    if if_absent and destination.exists():
        return destination, destination.read_text(encoding="utf-8"), False
    builtins_dir, org_dir, venue_dir = profile_source_dirs()
    profiles = InstrumentProfileLoader.load_directories([builtins_dir])
    # GH #469: rank shipped names using their effective user/venue overrides.
    # Additional user/venue names opt in through their own `class_hints`.
    hinted = InstrumentProfileLoader.load_directories(
        [org_dir, venue_dir], lower_layers=[builtins_dir],
    )
    probe = probe_builtin_profiles(profiles, hinted)
    classes = select_class_chains(probe)
    # A hinted profile the policy refused is reported in the file's header
    # comment, so the user sees why `workhorse:` lacks their local server
    # without reading the policy (GH #494).
    exclusions = explain_hinted_exclusions(probe)
    body_digest = hashlib.sha256(canonical_json(classes)).hexdigest()
    probe_digest = hashlib.sha256(canonical_probe(probe)).hexdigest()
    data = {
        "version": 1,
        "generated": {
            "tool": "mzt-instruments-classes-write",
            "at": datetime.now(UTC).isoformat(),
            "probe_sha256": probe_digest,
            "body_sha256": body_digest,
        },
        "classes": classes,
    }
    content = yaml.safe_dump(data, sort_keys=False, allow_unicode=True)
    if exclusions:
        header = "".join(f"# not seated: {line}\n" for line in exclusions)
        content = (
            "# Hinted profiles the class policy refused (mzt instruments classes write):\n"
            + header + content
        )
    parse_classes_file(content)
    if destination.exists() and not force:
        old = parse_classes_file(destination.read_text(encoding="utf-8"))
        old_raw = yaml.load(destination.read_text(encoding="utf-8"), Loader=_UniqueKeyLoader)
        actual_digest = hashlib.sha256(canonical_json(old_raw["classes"])).hexdigest()
        if old.generated is None or old.generated.body_sha256 != actual_digest:
            raise ValueError(
                f"{destination} has hand edits; use --force to replace it after reviewing the diff"
            )
    if dry_run:
        return destination, content, False
    destination.parent.mkdir(parents=True, exist_ok=True)
    if destination.exists():
        backup_dir = destination.parent / "backups"
        backup_dir.mkdir(parents=True, exist_ok=True)
        timestamp = datetime.now(UTC).strftime("%Y%m%dT%H%M%S%fZ")
        shutil.copy2(destination, backup_dir / f"classes-{timestamp}.yaml")
    temporary: Path | None = None
    try:
        with tempfile.NamedTemporaryFile(
            mode="w", encoding="utf-8", dir=destination.parent,
            prefix=".classes-", suffix=".yaml", delete=False,
        ) as stream:
            temporary = Path(stream.name)
            os.chmod(temporary, 0o600)
            stream.write(content)
            stream.flush()
            os.fsync(stream.fileno())
        os.replace(temporary, destination)
        temporary = None
        directory_fd = os.open(destination.parent, os.O_RDONLY)
        try:
            os.fsync(directory_fd)
        finally:
            os.close(directory_fd)
    finally:
        if temporary is not None:
            temporary.unlink(missing_ok=True)
    return destination, content, True