""" Generates schema reference for dstack models. """ import importlib import inspect import json import logging import re from enum import Enum from fnmatch import fnmatch from typing import Annotated, Any, Dict, Literal, Optional, Type, Union, get_args, get_origin import mkdocs_gen_files import yaml from pydantic import BaseModel, RootModel from pydantic_core import PydanticUndefined from dstack._internal.core.models.resources import Range from mkdocs.structure.files import File FILE_PATTERN = "docs/reference/**.md" logger = logging.getLogger("mkdocs.plugins.dstack.schema") logger.info("Generating schema reference...") def _unwrap_optional(annotation: Any) -> Any: """The non-`None` member of an `Optional[...]`, or the annotation unchanged.""" if get_origin(annotation) is Union: args = [a for a in get_args(annotation) if a is not type(None)] if len(args) == 1: return args[0] return annotation def _linkable_model(annotation: Any) -> Optional[type]: """ The `BaseModel` subclass a field links to in the reference, if any. pydantic v2 strips `Annotated` off `FieldInfo.annotation`, so the shape this used to unwrap by hand (`Annotated[Optional[SSHParams], Field(...)]`) now arrives as plain `Optional[SSHParams]`. Recursing over the annotation covers both, and also catches a bare model field, which the old `get_args(...)[0]` approach silently missed. """ origin = get_origin(annotation) # The container cases come first: `get_origin(Annotated[X, ...])` is `Annotated`, which is # itself a class, so testing `inspect.isclass` first would stop before ever unwrapping it. if origin in (Annotated, Union, list): for arg in get_args(annotation): if arg is type(None): continue found = _linkable_model(arg) if found is not None: return found return None type_ = origin if origin is not None else annotation if inspect.isclass(type_) and issubclass(type_, BaseModel) and not issubclass(type_, Range): return type_ return None # Scalar JSON Schema types, mapped to how the docs spell them. Deliberately an allowlist rather # than a full mapping: `array` and `object` would only restate what the annotation already renders # more precisely (`list[str]` gaining a bare `list`, `dict` gaining `object`), and merging anything # into a bracketed type corrupts it, since `_enrich_type_from_schema` splits the rendered type on # `" | "` — which `list["no-capacity" | "interruption"]` contains. _ENRICHABLE = {"string": "str", "integer": "int", "boolean": "bool", "number": "float"} def _shorthand_primitives(model: Type) -> list: """ The primitive types a model accepts in place of its object form, e.g. `8` or `arm:8` for `CPUSpec`. Taken from the model's own validation JSON Schema, which is the same declaration that produces the published `configuration.json`. """ try: schema = model.model_json_schema(mode="validation") except Exception: return [] found = { _ENRICHABLE[entry["type"]] for entry in schema.get("anyOf", []) if entry.get("type") in _ENRICHABLE } return sorted(found, key=_type_sort_key) def _type_sort_key(t: str) -> tuple: """Sort key for type parts: primitives first, then literals, then compound types.""" order = {"bool": 0, "int": 1, "float": 2, "str": 3} if t in order: return (0, order[t]) if t.startswith('"'): return (1, t) if t.startswith("list"): return (2, t) if t == "dict": return (3, "") if t == "object": return (4, "") return (5, t) def get_friendly_type(annotation: Any) -> str: """Get a user-friendly type string for documentation. Produces types like: ``int | str``, ``"vscode" | "cursor"``, ``list[object]``. """ # Unwrap Annotated if get_origin(annotation) is Annotated: return get_friendly_type(get_args(annotation)[0]) # Handle Union (including Optional) if get_origin(annotation) is Union: args = [a for a in get_args(annotation) if a is not type(None)] if not args: return "" parts: list = [] for arg in args: friendly = get_friendly_type(arg) # Split compound types (e.g., "int | str" from Range) to deduplicate, # but avoid splitting types that contain brackets (e.g., list[...]) if "[" not in friendly: for part in friendly.split(" | "): if part and part not in parts: parts.append(part) else: if friendly and friendly not in parts: parts.append(friendly) parts.sort(key=_type_sort_key) return " | ".join(parts) # Handle Literal — list values if get_origin(annotation) is Literal: values = [v.value if isinstance(v, Enum) else v for v in get_args(annotation)] return " | ".join(f'"{v}"' for v in values) # Handle list if get_origin(annotation) is list: args = get_args(annotation) if args: inner = get_friendly_type(args[0]) return f"list[{inner}]" return "list" # Handle dict if get_origin(annotation) is dict: return "dict" # Handle concrete classes if inspect.isclass(annotation): # Enum — list values if issubclass(annotation, Enum): values = [e.value for e in annotation] return " | ".join(f'"{v}"' for v in values) # Range — depends on inner type parameter if issubclass(annotation, Range): min_field = annotation.model_fields.get("min") inner = _unwrap_optional(min_field.annotation) if min_field else None if inspect.isclass(inner): # Range[Memory] → str, Range[int] → int | str if issubclass(inner, float): return "str" return "int | str" # Memory (float subclass that parses "8GB" strings) from dstack._internal.core.models.resources import Memory as _Memory if issubclass(annotation, _Memory): return "str" # BaseModel subclass (not Range) if issubclass(annotation, BaseModel) and not issubclass(annotation, Range): # Root models — resolve from the root type if issubclass(annotation, RootModel): return get_friendly_type(annotation.model_fields["root"].annotation) # Models that define their own core schema also accept a shorthand. Read which # primitives from the model's own JSON Schema rather than assuming `int | str`: # `CPUSpec` takes both, but `FilePathMapping` and `RepoSpec` take only a string. if "__get_pydantic_core_schema__" in annotation.__dict__: shorthand = _shorthand_primitives(annotation) if shorthand: return " | ".join([*shorthand, "object"]) return "object" # ComputeCapability (tuple subclass that parses "7.5" strings) if annotation.__name__ == "ComputeCapability": return "float | str" # Constrained and primitive types — check MRO # bool must come before int (bool is a subclass of int) if issubclass(annotation, bool): return "bool" if issubclass(annotation, int): # Duration (int subclass that parses "5m" strings) if annotation.__name__ == "Duration": return "int | str" return "int" if issubclass(annotation, float): return "float" if issubclass(annotation, str): return "str" if issubclass(annotation, (list, tuple)): return "list" if issubclass(annotation, dict): return "dict" return annotation.__name__ return str(annotation) def _enrich_type_from_schema(friendly_type: str, prop_schema: Dict[str, Any]) -> str: """Enrich the friendly type with extra accepted types from the JSON schema. A field's annotation is its *post-validation* type, so it does not show what a before-validator also accepts — a duration typed ``int`` takes ``"5m"``, ``false`` and ``"off"`` as well. Those come from the type's ``json_schema_input_type``, i.e. the same declaration that produces the published schema. """ any_of = prop_schema.get("anyOf") if not any_of: return friendly_type schema_types = set() for entry in any_of: # A single accepted value (`Literal["off"]`) is more useful spelled out than as `str`. # Duplicates are removed below, so an annotation that already shows it is unaffected. literals = [entry["const"]] if "const" in entry else entry.get("enum", []) if literals: schema_types.update(f'"{v}"' for v in literals if isinstance(v, str)) continue mapped = _ENRICHABLE.get(entry.get("type", "")) if mapped: schema_types.add(mapped) # Add any schema types not already present in the friendly type current_parts = [p.strip() for p in friendly_type.split(" | ")] new_parts = schema_types - set(current_parts) if not new_parts: return friendly_type all_parts = list(set(current_parts) | new_parts) all_parts.sort(key=_type_sort_key) return " | ".join(all_parts) def generate_schema_reference( model_path: str, *, overrides: Optional[dict[str, dict[str, Any]]] = None, prefix: str = "", ) -> str: module, model_name = model_path.rsplit(".", maxsplit=1) cls = getattr(importlib.import_module(module), model_name) assert issubclass(cls, BaseModel) rows = [] if ( not overrides or "show_root_heading" not in overrides or overrides.get("show_root_heading") is True ): rows.extend( [ prefix + f"### {cls.__name__}", "", ] ) # The schema says what a field *accepts*, which is wider than its annotation wherever a # before-validator coerces. `mode="validation"` is pydantic's default, but state it: the # serialization schema carries the narrow type and would defeat the whole point. try: schema_props = cls.model_json_schema(mode="validation").get("properties", {}) except Exception: schema_props = {} for name, field in cls.model_fields.items(): default = field.default default_repr: Optional[str] if default is None or default is PydanticUndefined: default_repr = None elif isinstance(default, (list, tuple, dict)) and len(default) == 0: default_repr = None elif isinstance(default, Enum): default_repr = str(default.value) elif isinstance(default, BaseModel): default_repr = str(default) elif isinstance(default, str): default_repr = default else: default_repr = json.dumps(default) friendly_type = get_friendly_type(field.annotation) friendly_type = _enrich_type_from_schema(friendly_type, schema_props.get(name, {})) values = dict( name=name, description=field.description, type=friendly_type, default=default_repr, required=field.is_required(), ) # TODO: If the field doesn't have description (e.g. BaseConfiguration.type), we could fallback to docstring if values["description"]: if overrides and name in overrides: values.update(overrides[name]) field_type = _linkable_model(field.annotation) base_model = field_type is not None _defaults = ( f"Defaults to `{values['default']}`." if not base_model and values.get("default") else "" ) _must_be = ( f"Must be `{values['default']}`." if not base_model and values.get("default") else "" ) if overrides and "item_id_prefix" in overrides: item_id_prefix = overrides["item_id_prefix"] else: item_id_prefix = "" if hasattr(field_type, "__name__") and overrides and "item_id_mapping" in overrides: link_name = overrides["item_id_mapping"].get(values["name"]) or values["name"] else: link_name = values["name"] item_header = ( f"`{values['name']}`" if not base_model else f"[`{values['name']}`](#{item_id_prefix}{link_name})" ) item_required_marker = "(Required)" if values["required"] else "(Optional)" item_type_display = f"`{values['type']}`" if values.get("type") else "" item_description = (values["description"]).replace("\n", "
") + "." item_default = _defaults if not values["required"] else _must_be item_id = f"#{values['name']}" if not base_model else f"#_{values['name']}" item_toc_label = f"data-toc-label='{values['name']}'" item_css_cass = "class='reference-item'" parts = [ f"###### {item_header}", "-", item_required_marker, item_type_display, item_description, item_default, "{", item_id, item_toc_label, item_css_cass, "}", ] rows.append(prefix + " ".join(p for p in parts if p)) return "\n".join(rows) def sub_schema_reference(match: re.Match) -> str: logger.debug("Generating schema reference for `%s`", match.group(2)) options = yaml.safe_load("\n".join(row[4:] for row in match.group(3).split("\n"))) logger.debug("Options: %s", options) return ( generate_schema_reference(match.group(2), **(options or {}), prefix=match.group(1)) + "\n\n" ) def expand_schema_references(text: str) -> str: """Expand #SCHEMA# placeholders in markdown text. Used by hooks when gen-files is not used.""" return re.sub( r"( *)#SCHEMA#\s+(dstack\.[.a-z_0-9A-Z]+)\s*((?:\n {4}[^\n]+)*)\n", sub_schema_reference, text, ) def process_file(file: File): if not fnmatch(file.src_uri, FILE_PATTERN): return logger.debug("Looking for schema references in `%s`", file.src_uri) with mkdocs_gen_files.open(file.src_uri, "r") as f: text = f.read() # Pattern: # #SCHEMA# dstack.. # overrides: # name: # required: true text = expand_schema_references(text) with mkdocs_gen_files.open(file.src_uri, "w") as f: f.write(text) def main(): # Processing sequentially since there is no speed up with concurrent processing for file in mkdocs_gen_files.files: process_file(file) main()