Skip to content

Core

StudyContext

fleet.core.StudyContext

Runtime context that resolves configured study paths.

Source code in src/fleet/core/study_context.py
class StudyContext:
    """Runtime context that resolves configured study paths."""

    def __init__(self, study_root: Path, config: StudyConfig) -> None:
        self.study_root = study_root
        self.config = config

    @property
    def study_id(self) -> str:
        return self.config.study_id

    def resolve(self, relative_path: str) -> Path:
        """Resolve a configured relative path under study root."""
        return (self.study_root / relative_path).resolve()

    @property
    def raw_data_dir(self) -> Path:
        return self.resolve(self.config.paths.raw_data)

    @property
    def sdtm_data_dir(self) -> Path:
        return self.resolve(self.config.paths.sdtm_data)

    @property
    def adam_data_dir(self) -> Path:
        return self.resolve(self.config.paths.adam_data)

    @property
    def metadata_sdtm_dir(self) -> Path:
        return self.resolve(self.config.paths.metadata_sdtm)

    @property
    def metadata_adam_dir(self) -> Path:
        return self.resolve(self.config.paths.metadata_adam)

    def data_dir(self, standard: str) -> Path:
        """The configured data directory of one standard (``"sdtm"`` or ``"adam"``)."""
        if standard == "sdtm":
            return self.sdtm_data_dir
        if standard == "adam":
            return self.adam_data_dir
        raise ValueError(f"unknown standard {standard!r}: expected 'sdtm' or 'adam'")

    def metadata_dir(self, standard: str) -> Path:
        """The configured metadata directory of one standard (``"sdtm"`` or ``"adam"``)."""
        if standard == "sdtm":
            return self.metadata_sdtm_dir
        if standard == "adam":
            return self.metadata_adam_dir
        raise ValueError(f"unknown standard {standard!r}: expected 'sdtm' or 'adam'")

    @property
    def define_xml_dir(self) -> Path:
        return self.resolve(self.config.paths.define_xml)

    @property
    def outputs_dir(self) -> Path:
        return self.resolve(self.config.paths.outputs)

    @property
    def programs_sdtm_dir(self) -> Path:
        return self.resolve(self.config.paths.programs_sdtm)

    @property
    def programs_adam_dir(self) -> Path:
        return self.resolve(self.config.paths.programs_adam)

    @property
    def programs_tlg_dir(self) -> Path:
        return self.resolve(self.config.paths.programs_tlg)

    @property
    def rules_sdtm_dir(self) -> Path:
        return self.resolve(self.config.paths.rules_sdtm)

    @property
    def rules_adam_dir(self) -> Path:
        return self.resolve(self.config.paths.rules_adam)

    @property
    def programs_misc_dir(self) -> Path:
        return self.resolve(self.config.paths.programs_misc)

    @property
    def codelists_file(self) -> Path:
        """Resolve the generated codelists.py path (inside SDTM metadata dir)."""
        return self.metadata_sdtm_dir / "codelists.py"

    @property
    def custom_rules_dir(self) -> Path | None:
        """Resolve the custom validation rules directory, or None if not configured."""
        if self.config.validation.custom_rules is None:
            return None
        return self.resolve(self.config.validation.custom_rules)

    @property
    def engine_file(self) -> Path | None:
        """Resolve ``validation.engine_path``, or None if not configured."""
        if self.config.validation.engine_path is None:
            return None
        return self.resolve(self.config.validation.engine_path)

    def raw_file(self, file_name: str) -> Path:
        return self.raw_data_dir / file_name

    def sdtm_file(self, file_name: str) -> Path:
        return self.sdtm_data_dir / file_name

    def adam_file(self, file_name: str) -> Path:
        return self.adam_data_dir / file_name

    def sdtm_spec(self, file_name: str) -> Path:
        return self.metadata_sdtm_dir / file_name

    def adam_spec(self, file_name: str) -> Path:
        return self.metadata_adam_dir / file_name

    def define_yaml(self, file_name: str = "define.yaml") -> Path:
        return self.define_xml_dir / file_name

    @classmethod
    def init(
        cls,
        study_root: str | Path,
        study_id: str,
        company: str | None = None,
        protocol_name: str | None = None,
        description: str = "",
        paths: "StudyPathConfig | None" = None,
        sdtm: "SDTMConfig | None" = None,
        adam: "ADAMConfig | None" = None,
        ct: "CTConfig | None" = None,
        validation: "ValidationConfig | None" = None,
    ) -> "StudyContext":
        """Scaffold a new study workspace and return a ready-to-use StudyContext.

        Creates the directory layout defined by StudyPathConfig and writes
        ``study_config.yaml``.  Define specs and codelists are created by
        subsequent pipeline steps (``fleet init define``, ``fleet init ct``).

        Directories are created silently if they already exist.  If
        ``study_config.yaml`` already exists the method raises
        ``StudyConfigError`` to protect in-progress work.

        Args:
            study_root: Root directory for the study (created if absent).
            study_id:   Study identifier (e.g. ``"STUDY01"``).
            company:    Optional originator / company name.
            protocol_name: Optional protocol identifier.
            description: Optional study description.
            paths:      Custom path config; defaults to ``StudyPathConfig`` defaults.
            sdtm:       SDTM IG configuration (version, domains).
            adam:        ADaM IG configuration (version, datasets).
            ct:         CT package configuration.
            validation: Validation engine configuration (engine path, custom rules).

        Returns:
            Initialized ``StudyContext`` pointing at the new workspace.

        Raises:
            StudyConfigError: If ``study_config.yaml`` already exists.
        """
        study_root = Path(study_root).resolve()
        config = StudyConfig(
            study_id=study_id,
            company=company,
            protocol_name=protocol_name,
            description=description,
            paths=paths or StudyPathConfig(),
            sdtm=sdtm or SDTMConfig(),
            adam=adam or ADAMConfig(),
            ct=ct or CTConfig(),
            validation=validation or ValidationConfig(),
        )
        ctx = cls(study_root=study_root, config=config)

        # ── Guard: refuse to overwrite existing config ────────────────────
        config_file = study_root / "study_config.yaml"
        if config_file.exists():
            raise StudyConfigError(
                f"Study already initialized — '{config_file}' already exists. "
                "Use load_study_context() to load an existing study."
            )

        # ── Create directory tree (idempotent) ────────────────────────────
        for dir_path in (
            ctx.raw_data_dir,
            ctx.sdtm_data_dir,
            ctx.adam_data_dir,
            ctx.metadata_sdtm_dir,
            ctx.metadata_adam_dir,
            ctx.define_xml_dir,
            ctx.outputs_dir,
            ctx.rules_sdtm_dir,
            ctx.rules_adam_dir,
            ctx.programs_sdtm_dir,
            ctx.programs_adam_dir,
            ctx.programs_tlg_dir,
            ctx.programs_misc_dir,
            *([ctx.custom_rules_dir] if ctx.custom_rules_dir is not None else []),
        ):
            dir_path.mkdir(parents=True, exist_ok=True)

        # ── Create derivations package stub ──────────────────────────────
        derivations_dir = ctx.programs_adam_dir.parent / "derivations"
        derivations_dir.mkdir(parents=True, exist_ok=True)
        derivations_init = derivations_dir / "__init__.py"
        if not derivations_init.exists():
            derivations_init.write_text(
                "# Auto-generated by fleet init cfg.\n"
                "# Import study-specific derivations here so they are auto-registered.\n",
                encoding="utf-8",
            )

        # ── Write study_config.yaml ───────────────────────────────────────
        config_data = config.model_dump(exclude_none=True)
        # Drop empty defaults to keep the file lean
        if not config_data.get("description"):
            config_data.pop("description", None)
        config_file.write_text(
            yaml.dump(config_data, default_flow_style=False, allow_unicode=True, sort_keys=False),
            encoding="utf-8",
        )

        return ctx

codelists_file property

codelists_file

Resolve the generated codelists.py path (inside SDTM metadata dir).

custom_rules_dir property

custom_rules_dir

Resolve the custom validation rules directory, or None if not configured.

engine_file property

engine_file

Resolve validation.engine_path, or None if not configured.

resolve

resolve(relative_path)

Resolve a configured relative path under study root.

Source code in src/fleet/core/study_context.py
def resolve(self, relative_path: str) -> Path:
    """Resolve a configured relative path under study root."""
    return (self.study_root / relative_path).resolve()

data_dir

data_dir(standard)

The configured data directory of one standard ("sdtm" or "adam").

Source code in src/fleet/core/study_context.py
def data_dir(self, standard: str) -> Path:
    """The configured data directory of one standard (``"sdtm"`` or ``"adam"``)."""
    if standard == "sdtm":
        return self.sdtm_data_dir
    if standard == "adam":
        return self.adam_data_dir
    raise ValueError(f"unknown standard {standard!r}: expected 'sdtm' or 'adam'")

metadata_dir

metadata_dir(standard)

The configured metadata directory of one standard ("sdtm" or "adam").

Source code in src/fleet/core/study_context.py
def metadata_dir(self, standard: str) -> Path:
    """The configured metadata directory of one standard (``"sdtm"`` or ``"adam"``)."""
    if standard == "sdtm":
        return self.metadata_sdtm_dir
    if standard == "adam":
        return self.metadata_adam_dir
    raise ValueError(f"unknown standard {standard!r}: expected 'sdtm' or 'adam'")

init classmethod

init(
    study_root,
    study_id,
    company=None,
    protocol_name=None,
    description="",
    paths=None,
    sdtm=None,
    adam=None,
    ct=None,
    validation=None,
)

Scaffold a new study workspace and return a ready-to-use StudyContext.

Creates the directory layout defined by StudyPathConfig and writes study_config.yaml. Define specs and codelists are created by subsequent pipeline steps (fleet init define, fleet init ct).

Directories are created silently if they already exist. If study_config.yaml already exists the method raises StudyConfigError to protect in-progress work.

Parameters:

Name Type Description Default
study_root str | Path

Root directory for the study (created if absent).

required
study_id str

Study identifier (e.g. "STUDY01").

required
company str | None

Optional originator / company name.

None
protocol_name str | None

Optional protocol identifier.

None
description str

Optional study description.

''
paths StudyPathConfig | None

Custom path config; defaults to StudyPathConfig defaults.

None
sdtm SDTMConfig | None

SDTM IG configuration (version, domains).

None
adam ADAMConfig | None

ADaM IG configuration (version, datasets).

None
ct CTConfig | None

CT package configuration.

None
validation ValidationConfig | None

Validation engine configuration (engine path, custom rules).

None

Returns:

Type Description
StudyContext

Initialized StudyContext pointing at the new workspace.

Raises:

Type Description
StudyConfigError

If study_config.yaml already exists.

Source code in src/fleet/core/study_context.py
@classmethod
def init(
    cls,
    study_root: str | Path,
    study_id: str,
    company: str | None = None,
    protocol_name: str | None = None,
    description: str = "",
    paths: "StudyPathConfig | None" = None,
    sdtm: "SDTMConfig | None" = None,
    adam: "ADAMConfig | None" = None,
    ct: "CTConfig | None" = None,
    validation: "ValidationConfig | None" = None,
) -> "StudyContext":
    """Scaffold a new study workspace and return a ready-to-use StudyContext.

    Creates the directory layout defined by StudyPathConfig and writes
    ``study_config.yaml``.  Define specs and codelists are created by
    subsequent pipeline steps (``fleet init define``, ``fleet init ct``).

    Directories are created silently if they already exist.  If
    ``study_config.yaml`` already exists the method raises
    ``StudyConfigError`` to protect in-progress work.

    Args:
        study_root: Root directory for the study (created if absent).
        study_id:   Study identifier (e.g. ``"STUDY01"``).
        company:    Optional originator / company name.
        protocol_name: Optional protocol identifier.
        description: Optional study description.
        paths:      Custom path config; defaults to ``StudyPathConfig`` defaults.
        sdtm:       SDTM IG configuration (version, domains).
        adam:        ADaM IG configuration (version, datasets).
        ct:         CT package configuration.
        validation: Validation engine configuration (engine path, custom rules).

    Returns:
        Initialized ``StudyContext`` pointing at the new workspace.

    Raises:
        StudyConfigError: If ``study_config.yaml`` already exists.
    """
    study_root = Path(study_root).resolve()
    config = StudyConfig(
        study_id=study_id,
        company=company,
        protocol_name=protocol_name,
        description=description,
        paths=paths or StudyPathConfig(),
        sdtm=sdtm or SDTMConfig(),
        adam=adam or ADAMConfig(),
        ct=ct or CTConfig(),
        validation=validation or ValidationConfig(),
    )
    ctx = cls(study_root=study_root, config=config)

    # ── Guard: refuse to overwrite existing config ────────────────────
    config_file = study_root / "study_config.yaml"
    if config_file.exists():
        raise StudyConfigError(
            f"Study already initialized — '{config_file}' already exists. "
            "Use load_study_context() to load an existing study."
        )

    # ── Create directory tree (idempotent) ────────────────────────────
    for dir_path in (
        ctx.raw_data_dir,
        ctx.sdtm_data_dir,
        ctx.adam_data_dir,
        ctx.metadata_sdtm_dir,
        ctx.metadata_adam_dir,
        ctx.define_xml_dir,
        ctx.outputs_dir,
        ctx.rules_sdtm_dir,
        ctx.rules_adam_dir,
        ctx.programs_sdtm_dir,
        ctx.programs_adam_dir,
        ctx.programs_tlg_dir,
        ctx.programs_misc_dir,
        *([ctx.custom_rules_dir] if ctx.custom_rules_dir is not None else []),
    ):
        dir_path.mkdir(parents=True, exist_ok=True)

    # ── Create derivations package stub ──────────────────────────────
    derivations_dir = ctx.programs_adam_dir.parent / "derivations"
    derivations_dir.mkdir(parents=True, exist_ok=True)
    derivations_init = derivations_dir / "__init__.py"
    if not derivations_init.exists():
        derivations_init.write_text(
            "# Auto-generated by fleet init cfg.\n"
            "# Import study-specific derivations here so they are auto-registered.\n",
            encoding="utf-8",
        )

    # ── Write study_config.yaml ───────────────────────────────────────
    config_data = config.model_dump(exclude_none=True)
    # Drop empty defaults to keep the file lean
    if not config_data.get("description"):
        config_data.pop("description", None)
    config_file.write_text(
        yaml.dump(config_data, default_flow_style=False, allow_unicode=True, sort_keys=False),
        encoding="utf-8",
    )

    return ctx

options: show_root_heading: true heading_level: 3 filters: ["!^_"]

load_study_context

fleet.core.load_study_context

load_study_context(config_path)

Load study configuration and return a resolved context.

Parameters:

Name Type Description Default
config_path Path

Path to study_config.yaml

required

Returns:

Type Description
StudyContext

StudyContext with resolved paths

Raises:

Type Description
StudyConfigError

If the config file is missing or invalid

Source code in src/fleet/core/study_context.py
def load_study_context(config_path: Path) -> StudyContext:
    """Load study configuration and return a resolved context.

    Args:
        config_path: Path to study_config.yaml

    Returns:
        StudyContext with resolved paths

    Raises:
        StudyConfigError: If the config file is missing or invalid
    """
    if not config_path.exists():
        raise StudyConfigError(f"Study configuration file not found: {config_path}")

    try:
        with open(config_path, encoding="utf-8") as f:
            config_data = yaml.safe_load(f) or {}
    except yaml.YAMLError as e:
        raise StudyConfigError(f"Invalid YAML in study configuration: {e}") from e

    try:
        config = StudyConfig(**config_data)
    except Exception as e:
        raise StudyConfigError(f"Invalid study configuration schema: {e}") from e

    return StudyContext(study_root=config_path.parent, config=config)

options: show_root_heading: true heading_level: 3

PipelineDAG

fleet.core.PipelineDAG dataclass

Directed Acyclic Graph of pipeline dataset dependencies.

Build with :func:build_dag rather than constructing directly.

Source code in src/fleet/core/dag.py
@dataclass
class PipelineDAG:
    """Directed Acyclic Graph of pipeline dataset dependencies.

    Build with :func:`build_dag` rather than constructing directly.
    """

    nodes: dict[str, PipelineNode] = field(default_factory=dict)

    # ── queries ─────────────────────────────────────────────────────────── #

    def execution_order(self) -> list[str]:
        """Return all node names in a safe topological execution order.

        Uses Kahn's algorithm (BFS on in-degree).

        Raises
        ------
        ValueError
            If the graph contains a cycle (should have been caught by
            :func:`build_dag`, but re-checked here for safety).
        """
        in_degree: dict[str, int] = {n: 0 for n in self.nodes}
        for node in self.nodes.values():
            for upstream in node.inputs:
                if upstream in in_degree:
                    in_degree[node.name] += 1

        queue: deque[str] = deque(n for n, deg in in_degree.items() if deg == 0)
        order: list[str] = []

        while queue:
            n = queue.popleft()
            order.append(n)
            for downstream in self._downstream(n):
                in_degree[downstream] -= 1
                if in_degree[downstream] == 0:
                    queue.append(downstream)

        if len(order) != len(self.nodes):
            raise ValueError("DAG contains a cycle — cannot produce a linear execution order.")

        return order

    def impacted_by(self, name: str) -> list[str]:
        """Return all nodes that must be rerun when *name* changes.

        Performs a BFS downstream from *name*, then returns the results
        in topological execution order so callers get a ready-made run
        schedule.

        Parameters
        ----------
        name:
            Logical node name (dataset or raw source) that changed.

        Returns
        -------
        list[str]
            Topologically-ordered list of node names to rerun, inclusive
            of *name* itself.

        Raises
        ------
        KeyError
            If *name* is not a node in this DAG.
        """
        if name not in self.nodes:
            raise KeyError(f"Node '{name}' not found in DAG. Available nodes: {sorted(self.nodes)}")

        visited: set[str] = set()
        queue: deque[str] = deque([name])
        while queue:
            n = queue.popleft()
            if n in visited:
                continue
            visited.add(n)
            queue.extend(self._downstream(n))

        return [n for n in self.execution_order() if n in visited]

    def _downstream(self, name: str) -> list[str]:
        """Direct downstream dependents of *name* (nodes that list it in inputs)."""
        return [n.name for n in self.nodes.values() if name in n.inputs]

    # ── lineage injection ───────────────────────────────────────────────── #

    def inject_lineage(self, namespace: Any, dataset_name: str) -> None:
        """Merge variable-level and pin lineage from *namespace* into the DAG.

        Populates ``variables`` on the node named *dataset_name* (when a
        variable was derived more than once, the last derivation wins —
        matching what the materialised frame actually contains) and, for
        each ``PinDependency``, adds the pinned source domain to the
        node's ``inputs`` if it is not already present (creating the
        cross-domain edge in the DAG).

        Declared ``inputs:`` are reconciled against the runtime pin
        evidence in both directions:

        * a dataset-type input declared in the spec but never consulted
          at runtime emits a ``UserWarning`` (stale declaration);
        * a runtime pin source missing from the declaration emits a
          ``UserWarning`` *and* the edge is added (the DAG follows the
          evidence).

        Raw inputs carry no pin evidence and are exempt from the
        declared-but-unused check.

        Args:
            namespace: A namespace instance with ``_lineage`` and
                optionally ``_pin_lineage`` attributes.
            dataset_name: The logical node name to attach lineage to.
        """
        node = self.nodes.get(dataset_name)
        if node is None:
            return

        from fleet.core.lineage import lineage_of, pin_lineage_of

        declared = list(node.inputs)

        # Merge intra-frame variable lineage (last write wins per target)
        for vnode in lineage_of(namespace):
            node.variables[vnode.name] = vnode

        # Merge pin lineage → enrich variable nodes + add DAG edges
        runtime_domains: set[str] = set()
        for pdep in pin_lineage_of(namespace):
            runtime_domains.add(pdep.source_domain)
            if pdep.target_col in node.variables:
                vnode = node.variables[pdep.target_col]
                if pdep not in vnode.pin_sources:
                    vnode.pin_sources.append(pdep)
            # Ensure the source domain is an input edge
            if pdep.source_domain in self.nodes and pdep.source_domain not in node.inputs:
                warnings.warn(
                    f"inject_lineage('{dataset_name}'): runtime evidence shows a "
                    f"dependency on '{pdep.source_domain}' (via {pdep.verb}) that is "
                    f"not declared in the spec's inputs: {declared}. "
                    f"Adding the edge; declare it in the define.yaml to silence this.",
                    stacklevel=2,
                )
                node.inputs.append(pdep.source_domain)

        # Reverse direction: declared dataset inputs with no runtime evidence.
        for name in declared:
            upstream = self.nodes.get(name)
            if upstream is not None and upstream.node_type == "raw":
                continue  # raw sources are consumed as columns, not pins
            if name not in runtime_domains:
                warnings.warn(
                    f"inject_lineage('{dataset_name}'): input '{name}' is declared "
                    f"in the spec but no runtime pin/lineage evidence consumed it. "
                    f"Remove the declaration or check the pipeline wiring.",
                    stacklevel=2,
                )

    def trace(self, dataset: str, variable: str) -> list[dict[str, Any]]:
        """Return the full recursive provenance chain for a single variable.

        Walks the variable's ``sources`` transitively — including
        cross-domain pin sources into other DAG nodes — collecting every
        upstream *derived* variable exactly once (cycle-safe, deduped).
        Raw/leaf columns appear inside each entry's ``sources`` but do
        not get entries of their own.

        Args:
            dataset: Logical node name (e.g. ``"AE"``).
            variable: Column name (e.g. ``"AESTDY"``).

        Returns:
            list[dict]: Depth-first provenance entries from the output
                variable back to its sources, each with ``dataset``,
                ``name``, ``verb``, ``sources``, ``domain``, and
                ``pin_sources``.
        """
        chain: list[dict[str, Any]] = []
        visited: set[tuple[str, str]] = set()
        self._trace_into(dataset, variable, chain, visited)
        return chain

    def _trace_into(
        self,
        dataset: str,
        variable: str,
        chain: list[dict[str, Any]],
        visited: set[tuple[str, str]],
    ) -> None:
        """DFS helper for :meth:`trace` — appends entries in pre-order."""
        key = (dataset, variable)
        if key in visited:
            return
        visited.add(key)

        node = self.nodes.get(dataset)
        if node is None:
            return
        vnode = node.variables.get(variable)
        if vnode is None:
            return  # leaf: raw column or variable without lineage

        chain.append(
            {
                "dataset": dataset,
                "name": vnode.name,
                "verb": vnode.verb,
                "sources": vnode.sources,
                "domain": vnode.domain,
                "pin_sources": [
                    {
                        "source_domain": p.source_domain,
                        "source_cols": p.source_cols,
                        "join_key": p.join_key,
                        "relationship": p.relationship,
                    }
                    for p in vnode.pin_sources
                ],
            }
        )

        # Columns attributed to a pinned domain recurse into that domain,
        # not into the local frame (the local copy is a join artefact).
        pinned_cols: set[str] = set()
        for pdep in vnode.pin_sources:
            for col in pdep.source_cols:
                pinned_cols.add(col)
                self._trace_into(pdep.source_domain, col, chain, visited)

        for src in vnode.sources:
            if src not in pinned_cols:
                self._trace_into(dataset, src, chain, visited)

    # ── export ──────────────────────────────────────────────────────────── #

    def to_dict(self) -> dict:
        """Return a JSON-serializable adjacency representation.

        Shape::

            {
              "dm_raw": {"node_type": "raw",  "path": "datasets/.../dm_raw.csv", "inputs": []},
              "DM":     {"node_type": "sdtm", "path": "outputs/.../dm.parquet",  "inputs": ["dm_raw"]},
              "ADSL":   {"node_type": "adam", "path": "outputs/.../adsl.parquet","inputs": ["DM"]},
              ...
            }
        """
        return {
            name: {
                "node_type": node.node_type,
                "path": node.path,
                "inputs": node.inputs,
                **(
                    {
                        "variables": {
                            v.name: {
                                "verb": v.verb,
                                "sources": v.sources,
                                "method": v.method,
                                "cdisc_ref": v.cdisc_ref,
                                **(
                                    {
                                        "pin_sources": [
                                            {
                                                "source_domain": p.source_domain,
                                                "source_cols": p.source_cols,
                                                "join_key": p.join_key,
                                                "relationship": p.relationship,
                                            }
                                            for p in v.pin_sources
                                        ]
                                    }
                                    if v.pin_sources
                                    else {}
                                ),
                            }
                            for v in node.variables.values()
                        }
                    }
                    if node.variables
                    else {}
                ),
            }
            for name, node in self.nodes.items()
        }

    def to_snakemake(self) -> dict:
        """Return a Snakemake-compatible rule dict.

        Each entry maps a logical name to ``{"input": [...paths...], "output": path}``.
        Drop this into a Snakefile generator to produce concrete rules::

            for name, rule in dag.to_snakemake().items():
                # rule["input"]  → list of input file paths
                # rule["output"] → output file path

        Raw nodes are included with an empty ``input`` list and the source
        file as ``output``, so Snakemake can model them as source checkpoints.
        """
        rules: dict[str, dict] = {}
        for name, node in self.nodes.items():
            input_paths: list[str] = []
            for upstream_name in node.inputs:
                upstream = self.nodes.get(upstream_name)
                if upstream and upstream.path:
                    input_paths.append(upstream.path)
                else:
                    input_paths.append(upstream_name)
            rules[name] = {
                "input": input_paths,
                "output": node.path,
                "node_type": node.node_type,
            }
        return rules

    def to_airflow(self) -> dict:
        """Return an Airflow-compatible task dependency dict.

        Shape::

            {
              "DM":   [],           # no upstream tasks
              "ADSL": ["DM"],
              "ADVS": ["VS", "ADSL"],
            }

        Wire operators in a DAG file with::

            for task_id, upstreams in dag.to_airflow().items():
                for u in upstreams:
                    tasks[u] >> tasks[task_id]
        """
        return {name: list(node.inputs) for name, node in self.nodes.items()}

    def generate(self, output_path: str | Path) -> None:
        """Write the DAG to *output_path* as a JSON file.

        The file contains the full adjacency representation produced by
        :meth:`to_dict` plus the topological execution order, so it is
        self-contained and can be consumed by external tools without needing
        to re-parse the define YAMLs.

        Parameters
        ----------
        output_path:
            Destination path for the ``.json`` file (e.g.
            ``outputs/cdiscpilot01/pipeline_dag.json``).

        Example
        -------
        ::

            dag = build_dag(
                "examples/cdiscpilot01/sdtm/define.yaml",
                "examples/cdiscpilot01/adam/define.yaml",
                output_dir="outputs/cdiscpilot01",
            )
            dag.generate("outputs/cdiscpilot01/pipeline_dag.json")
        """
        import json

        out = Path(output_path)
        out.parent.mkdir(parents=True, exist_ok=True)
        payload = {
            "execution_order": self.execution_order(),
            "nodes": self.to_dict(),
            "snakemake": self.to_snakemake(),
            "airflow": self.to_airflow(),
        }
        out.write_text(json.dumps(payload, indent=2), encoding="utf-8")
        print(f"Pipeline DAG generated: {out}")

execution_order

execution_order()

Return all node names in a safe topological execution order.

Uses Kahn's algorithm (BFS on in-degree).

Raises

ValueError If the graph contains a cycle (should have been caught by :func:build_dag, but re-checked here for safety).

Source code in src/fleet/core/dag.py
def execution_order(self) -> list[str]:
    """Return all node names in a safe topological execution order.

    Uses Kahn's algorithm (BFS on in-degree).

    Raises
    ------
    ValueError
        If the graph contains a cycle (should have been caught by
        :func:`build_dag`, but re-checked here for safety).
    """
    in_degree: dict[str, int] = {n: 0 for n in self.nodes}
    for node in self.nodes.values():
        for upstream in node.inputs:
            if upstream in in_degree:
                in_degree[node.name] += 1

    queue: deque[str] = deque(n for n, deg in in_degree.items() if deg == 0)
    order: list[str] = []

    while queue:
        n = queue.popleft()
        order.append(n)
        for downstream in self._downstream(n):
            in_degree[downstream] -= 1
            if in_degree[downstream] == 0:
                queue.append(downstream)

    if len(order) != len(self.nodes):
        raise ValueError("DAG contains a cycle — cannot produce a linear execution order.")

    return order

impacted_by

impacted_by(name)

Return all nodes that must be rerun when name changes.

Performs a BFS downstream from name, then returns the results in topological execution order so callers get a ready-made run schedule.

Parameters

name: Logical node name (dataset or raw source) that changed.

Returns

list[str] Topologically-ordered list of node names to rerun, inclusive of name itself.

Raises

KeyError If name is not a node in this DAG.

Source code in src/fleet/core/dag.py
def impacted_by(self, name: str) -> list[str]:
    """Return all nodes that must be rerun when *name* changes.

    Performs a BFS downstream from *name*, then returns the results
    in topological execution order so callers get a ready-made run
    schedule.

    Parameters
    ----------
    name:
        Logical node name (dataset or raw source) that changed.

    Returns
    -------
    list[str]
        Topologically-ordered list of node names to rerun, inclusive
        of *name* itself.

    Raises
    ------
    KeyError
        If *name* is not a node in this DAG.
    """
    if name not in self.nodes:
        raise KeyError(f"Node '{name}' not found in DAG. Available nodes: {sorted(self.nodes)}")

    visited: set[str] = set()
    queue: deque[str] = deque([name])
    while queue:
        n = queue.popleft()
        if n in visited:
            continue
        visited.add(n)
        queue.extend(self._downstream(n))

    return [n for n in self.execution_order() if n in visited]

inject_lineage

inject_lineage(namespace, dataset_name)

Merge variable-level and pin lineage from namespace into the DAG.

Populates variables on the node named dataset_name (when a variable was derived more than once, the last derivation wins — matching what the materialised frame actually contains) and, for each PinDependency, adds the pinned source domain to the node's inputs if it is not already present (creating the cross-domain edge in the DAG).

Declared inputs: are reconciled against the runtime pin evidence in both directions:

  • a dataset-type input declared in the spec but never consulted at runtime emits a UserWarning (stale declaration);
  • a runtime pin source missing from the declaration emits a UserWarning and the edge is added (the DAG follows the evidence).

Raw inputs carry no pin evidence and are exempt from the declared-but-unused check.

Parameters:

Name Type Description Default
namespace Any

A namespace instance with _lineage and optionally _pin_lineage attributes.

required
dataset_name str

The logical node name to attach lineage to.

required
Source code in src/fleet/core/dag.py
def inject_lineage(self, namespace: Any, dataset_name: str) -> None:
    """Merge variable-level and pin lineage from *namespace* into the DAG.

    Populates ``variables`` on the node named *dataset_name* (when a
    variable was derived more than once, the last derivation wins —
    matching what the materialised frame actually contains) and, for
    each ``PinDependency``, adds the pinned source domain to the
    node's ``inputs`` if it is not already present (creating the
    cross-domain edge in the DAG).

    Declared ``inputs:`` are reconciled against the runtime pin
    evidence in both directions:

    * a dataset-type input declared in the spec but never consulted
      at runtime emits a ``UserWarning`` (stale declaration);
    * a runtime pin source missing from the declaration emits a
      ``UserWarning`` *and* the edge is added (the DAG follows the
      evidence).

    Raw inputs carry no pin evidence and are exempt from the
    declared-but-unused check.

    Args:
        namespace: A namespace instance with ``_lineage`` and
            optionally ``_pin_lineage`` attributes.
        dataset_name: The logical node name to attach lineage to.
    """
    node = self.nodes.get(dataset_name)
    if node is None:
        return

    from fleet.core.lineage import lineage_of, pin_lineage_of

    declared = list(node.inputs)

    # Merge intra-frame variable lineage (last write wins per target)
    for vnode in lineage_of(namespace):
        node.variables[vnode.name] = vnode

    # Merge pin lineage → enrich variable nodes + add DAG edges
    runtime_domains: set[str] = set()
    for pdep in pin_lineage_of(namespace):
        runtime_domains.add(pdep.source_domain)
        if pdep.target_col in node.variables:
            vnode = node.variables[pdep.target_col]
            if pdep not in vnode.pin_sources:
                vnode.pin_sources.append(pdep)
        # Ensure the source domain is an input edge
        if pdep.source_domain in self.nodes and pdep.source_domain not in node.inputs:
            warnings.warn(
                f"inject_lineage('{dataset_name}'): runtime evidence shows a "
                f"dependency on '{pdep.source_domain}' (via {pdep.verb}) that is "
                f"not declared in the spec's inputs: {declared}. "
                f"Adding the edge; declare it in the define.yaml to silence this.",
                stacklevel=2,
            )
            node.inputs.append(pdep.source_domain)

    # Reverse direction: declared dataset inputs with no runtime evidence.
    for name in declared:
        upstream = self.nodes.get(name)
        if upstream is not None and upstream.node_type == "raw":
            continue  # raw sources are consumed as columns, not pins
        if name not in runtime_domains:
            warnings.warn(
                f"inject_lineage('{dataset_name}'): input '{name}' is declared "
                f"in the spec but no runtime pin/lineage evidence consumed it. "
                f"Remove the declaration or check the pipeline wiring.",
                stacklevel=2,
            )

trace

trace(dataset, variable)

Return the full recursive provenance chain for a single variable.

Walks the variable's sources transitively — including cross-domain pin sources into other DAG nodes — collecting every upstream derived variable exactly once (cycle-safe, deduped). Raw/leaf columns appear inside each entry's sources but do not get entries of their own.

Parameters:

Name Type Description Default
dataset str

Logical node name (e.g. "AE").

required
variable str

Column name (e.g. "AESTDY").

required

Returns:

Type Description
list[dict[str, Any]]

list[dict]: Depth-first provenance entries from the output variable back to its sources, each with dataset, name, verb, sources, domain, and pin_sources.

Source code in src/fleet/core/dag.py
def trace(self, dataset: str, variable: str) -> list[dict[str, Any]]:
    """Return the full recursive provenance chain for a single variable.

    Walks the variable's ``sources`` transitively — including
    cross-domain pin sources into other DAG nodes — collecting every
    upstream *derived* variable exactly once (cycle-safe, deduped).
    Raw/leaf columns appear inside each entry's ``sources`` but do
    not get entries of their own.

    Args:
        dataset: Logical node name (e.g. ``"AE"``).
        variable: Column name (e.g. ``"AESTDY"``).

    Returns:
        list[dict]: Depth-first provenance entries from the output
            variable back to its sources, each with ``dataset``,
            ``name``, ``verb``, ``sources``, ``domain``, and
            ``pin_sources``.
    """
    chain: list[dict[str, Any]] = []
    visited: set[tuple[str, str]] = set()
    self._trace_into(dataset, variable, chain, visited)
    return chain

to_dict

to_dict()

Return a JSON-serializable adjacency representation.

Shape::

{
  "dm_raw": {"node_type": "raw",  "path": "datasets/.../dm_raw.csv", "inputs": []},
  "DM":     {"node_type": "sdtm", "path": "outputs/.../dm.parquet",  "inputs": ["dm_raw"]},
  "ADSL":   {"node_type": "adam", "path": "outputs/.../adsl.parquet","inputs": ["DM"]},
  ...
}
Source code in src/fleet/core/dag.py
def to_dict(self) -> dict:
    """Return a JSON-serializable adjacency representation.

    Shape::

        {
          "dm_raw": {"node_type": "raw",  "path": "datasets/.../dm_raw.csv", "inputs": []},
          "DM":     {"node_type": "sdtm", "path": "outputs/.../dm.parquet",  "inputs": ["dm_raw"]},
          "ADSL":   {"node_type": "adam", "path": "outputs/.../adsl.parquet","inputs": ["DM"]},
          ...
        }
    """
    return {
        name: {
            "node_type": node.node_type,
            "path": node.path,
            "inputs": node.inputs,
            **(
                {
                    "variables": {
                        v.name: {
                            "verb": v.verb,
                            "sources": v.sources,
                            "method": v.method,
                            "cdisc_ref": v.cdisc_ref,
                            **(
                                {
                                    "pin_sources": [
                                        {
                                            "source_domain": p.source_domain,
                                            "source_cols": p.source_cols,
                                            "join_key": p.join_key,
                                            "relationship": p.relationship,
                                        }
                                        for p in v.pin_sources
                                    ]
                                }
                                if v.pin_sources
                                else {}
                            ),
                        }
                        for v in node.variables.values()
                    }
                }
                if node.variables
                else {}
            ),
        }
        for name, node in self.nodes.items()
    }

to_snakemake

to_snakemake()

Return a Snakemake-compatible rule dict.

Each entry maps a logical name to {"input": [...paths...], "output": path}. Drop this into a Snakefile generator to produce concrete rules::

for name, rule in dag.to_snakemake().items():
    # rule["input"]  → list of input file paths
    # rule["output"] → output file path

Raw nodes are included with an empty input list and the source file as output, so Snakemake can model them as source checkpoints.

Source code in src/fleet/core/dag.py
def to_snakemake(self) -> dict:
    """Return a Snakemake-compatible rule dict.

    Each entry maps a logical name to ``{"input": [...paths...], "output": path}``.
    Drop this into a Snakefile generator to produce concrete rules::

        for name, rule in dag.to_snakemake().items():
            # rule["input"]  → list of input file paths
            # rule["output"] → output file path

    Raw nodes are included with an empty ``input`` list and the source
    file as ``output``, so Snakemake can model them as source checkpoints.
    """
    rules: dict[str, dict] = {}
    for name, node in self.nodes.items():
        input_paths: list[str] = []
        for upstream_name in node.inputs:
            upstream = self.nodes.get(upstream_name)
            if upstream and upstream.path:
                input_paths.append(upstream.path)
            else:
                input_paths.append(upstream_name)
        rules[name] = {
            "input": input_paths,
            "output": node.path,
            "node_type": node.node_type,
        }
    return rules

to_airflow

to_airflow()

Return an Airflow-compatible task dependency dict.

Shape::

{
  "DM":   [],           # no upstream tasks
  "ADSL": ["DM"],
  "ADVS": ["VS", "ADSL"],
}

Wire operators in a DAG file with::

for task_id, upstreams in dag.to_airflow().items():
    for u in upstreams:
        tasks[u] >> tasks[task_id]
Source code in src/fleet/core/dag.py
def to_airflow(self) -> dict:
    """Return an Airflow-compatible task dependency dict.

    Shape::

        {
          "DM":   [],           # no upstream tasks
          "ADSL": ["DM"],
          "ADVS": ["VS", "ADSL"],
        }

    Wire operators in a DAG file with::

        for task_id, upstreams in dag.to_airflow().items():
            for u in upstreams:
                tasks[u] >> tasks[task_id]
    """
    return {name: list(node.inputs) for name, node in self.nodes.items()}

generate

generate(output_path)

Write the DAG to output_path as a JSON file.

The file contains the full adjacency representation produced by :meth:to_dict plus the topological execution order, so it is self-contained and can be consumed by external tools without needing to re-parse the define YAMLs.

Parameters

output_path: Destination path for the .json file (e.g. outputs/cdiscpilot01/pipeline_dag.json).

Example

::

dag = build_dag(
    "examples/cdiscpilot01/sdtm/define.yaml",
    "examples/cdiscpilot01/adam/define.yaml",
    output_dir="outputs/cdiscpilot01",
)
dag.generate("outputs/cdiscpilot01/pipeline_dag.json")
Source code in src/fleet/core/dag.py
def generate(self, output_path: str | Path) -> None:
    """Write the DAG to *output_path* as a JSON file.

    The file contains the full adjacency representation produced by
    :meth:`to_dict` plus the topological execution order, so it is
    self-contained and can be consumed by external tools without needing
    to re-parse the define YAMLs.

    Parameters
    ----------
    output_path:
        Destination path for the ``.json`` file (e.g.
        ``outputs/cdiscpilot01/pipeline_dag.json``).

    Example
    -------
    ::

        dag = build_dag(
            "examples/cdiscpilot01/sdtm/define.yaml",
            "examples/cdiscpilot01/adam/define.yaml",
            output_dir="outputs/cdiscpilot01",
        )
        dag.generate("outputs/cdiscpilot01/pipeline_dag.json")
    """
    import json

    out = Path(output_path)
    out.parent.mkdir(parents=True, exist_ok=True)
    payload = {
        "execution_order": self.execution_order(),
        "nodes": self.to_dict(),
        "snakemake": self.to_snakemake(),
        "airflow": self.to_airflow(),
    }
    out.write_text(json.dumps(payload, indent=2), encoding="utf-8")
    print(f"Pipeline DAG generated: {out}")

options: show_root_heading: true heading_level: 3 filters: ["!^_"]

Derivation

fleet.core.derivation.Derivation dataclass

A registered custom derivation: callable + rich lineage metadata.

Created by the :func:derivation decorator. Instances are callable — invoking them dispatches to the underlying function according to kind.

Attributes:

Name Type Description
fn Callable

The wrapped callable.

name str

Function name (used as registry key).

kind Literal['column', 'frame']

Dispatch strategy: "column" or "frame".

targets list[str]

Output column names produced by this derivation. For kind="column" it is the function name, unless the expression has an explicit .alias().

sources list[str]

Input column names consumed (populated automatically for kind="column").

dotted_path str

Fully qualified import path for Define-XML MethodDef (e.g. "examples.cdiscpilot01.adam.derivations.AGEGR1").

Source code in src/fleet/core/derivation.py
@dataclass
class Derivation:
    """A registered custom derivation: callable + rich lineage metadata.

    Created by the :func:`derivation` decorator.  Instances are callable —
    invoking them dispatches to the underlying function according to ``kind``.

    Attributes:
        fn:            The wrapped callable.
        name:          Function name (used as registry key).
        kind:          Dispatch strategy: ``"column"`` or ``"frame"``.
        targets:       Output column names produced by this derivation.
                       For ``kind="column"`` it is the function name, unless
                       the expression has an explicit ``.alias()``.
        sources:       Input column names consumed (populated automatically
                       for ``kind="column"``).
        dotted_path:   Fully qualified import path for Define-XML MethodDef
                       (e.g. ``"examples.cdiscpilot01.adam.derivations.AGEGR1"``).
    """

    fn: Callable
    name: str
    kind: Literal["column", "frame"]
    targets: list[str]
    sources: list[str]
    dotted_path: str

    def __call__(self, df: pl.DataFrame | None = None) -> pl.Expr | pl.DataFrame:
        """Invoke the wrapped function.

        For ``kind="column"`` the function takes no arguments and returns a
        ``pl.Expr`` named as the target.  For ``kind="frame"`` the function
        receives the upstream DataFrame and returns a ``pl.DataFrame``.

        Args:
            df: Upstream DataFrame; required for frame derivations,
                ignored for column derivations.

        Returns:
            A ``pl.Expr`` (column kind) or ``pl.DataFrame`` (frame kind).
        """
        if self.kind == "column":
            expr: pl.Expr = self.fn()
            return expr if _has_alias(expr) else expr.alias(self.targets[0])
        return self.fn(df)

options: show_root_heading: true heading_level: 3 filters: ["!^_"]

derivation (decorator)

fleet.core.derivation.derivation

derivation(
    fn=None, *, targets=None, sources=None, **removed
)

Decorator that wraps a function as a typed :class:Derivation object.

Supports both bare and parameterised forms.

Bare form (kind inferred from return annotation)::

@derivation
def AGEGR1() -> pl.Expr:
    return pl.when(pl.col("AGE") < 65).then(pl.lit("<65 yrs")).otherwise(pl.lit(">=65 yrs"))

A column derivation writes to the column named as the function (AGEGR1 above). An explicit .alias() on the expression wins.

Parameterised form::

@derivation(targets=["SAFFL", "ITTFL"])
def add_pop_flags(df: pl.DataFrame) -> pl.DataFrame: ...

Kind inference rules:

+-------------------------------------------------------+-----------+ | Condition | Kind | +=======================================================+===========+ | Return annotation is pl.Expr | column| +-------------------------------------------------------+-----------+ | Return annotation is pl.DataFrame | frame | +-------------------------------------------------------+-----------+ | No parameters on the function | column| +-------------------------------------------------------+-----------+ | Otherwise | frame | +-------------------------------------------------------+-----------+

A new parameter row (PARAMCD = "BMI") is not a derivation: use .adam.derive_param().

After decoration the function name is auto-registered in the Fleet transform registry, making it referenceable by name in YAML specs.

Parameters:

Name Type Description Default
fn Callable | None

The function to decorate (bare form only; None in parameterised form).

None
targets list[str] | None

Explicit list of output column names. Inferred automatically for kind="column" derivations.

None
sources list[str] | None

Explicit list of input column names. Inferred automatically for kind="column" derivations.

None
**removed Any

by= and set_values_to= are refused.

{}

Returns:

Name Type Description
A Derivation | Callable[[Callable], Derivation]

class:Derivation object (bare form) or a decorator that returns

Derivation | Callable[[Callable], Derivation]

one (parameterised form).

Raises:

Type Description
VerbUsageError

When by= or set_values_to= is given: they appended no row and overwrote AVAL. Use .adam.derive_param().

Source code in src/fleet/core/derivation.py
def derivation(
    fn: Callable | None = None,
    *,
    targets: list[str] | None = None,
    sources: list[str] | None = None,
    **removed: Any,
) -> Derivation | Callable[[Callable], Derivation]:
    """Decorator that wraps a function as a typed :class:`Derivation` object.

    Supports both **bare** and **parameterised** forms.

    Bare form (``kind`` inferred from return annotation)::

        @derivation
        def AGEGR1() -> pl.Expr:
            return pl.when(pl.col("AGE") < 65).then(pl.lit("<65 yrs")).otherwise(pl.lit(">=65 yrs"))

    A column derivation writes to the column named as the function
    (``AGEGR1`` above).  An explicit ``.alias()`` on the expression wins.

    Parameterised form::

        @derivation(targets=["SAFFL", "ITTFL"])
        def add_pop_flags(df: pl.DataFrame) -> pl.DataFrame: ...

    Kind inference rules:

    +-------------------------------------------------------+-----------+
    | Condition                                             | Kind      |
    +=======================================================+===========+
    | Return annotation is ``pl.Expr``                      | ``column``|
    +-------------------------------------------------------+-----------+
    | Return annotation is ``pl.DataFrame``                 | ``frame`` |
    +-------------------------------------------------------+-----------+
    | No parameters on the function                         | ``column``|
    +-------------------------------------------------------+-----------+
    | Otherwise                                             | ``frame`` |
    +-------------------------------------------------------+-----------+

    A new parameter row (``PARAMCD = "BMI"``) is not a derivation: use
    ``.adam.derive_param()``.

    After decoration the function name is **auto-registered** in the Fleet
    transform registry, making it referenceable by name in YAML specs.

    Args:
        fn:            The function to decorate (bare form only; ``None`` in
                       parameterised form).
        targets:       Explicit list of output column names.  Inferred
                       automatically for ``kind="column"`` derivations.
        sources:       Explicit list of input column names.  Inferred
                       automatically for ``kind="column"`` derivations.
        **removed:     ``by=`` and ``set_values_to=`` are refused.

    Returns:
        A :class:`Derivation` object (bare form) or a decorator that returns
        one (parameterised form).

    Raises:
        VerbUsageError: When ``by=`` or ``set_values_to=`` is given: they
            appended no row and overwrote AVAL.  Use ``.adam.derive_param()``.
    """
    if removed:
        from fleet.core.exceptions import VerbUsageError

        names = ", ".join(f"{k}=" for k in removed)
        if set(removed) <= {"by", "set_values_to"}:
            raise VerbUsageError(
                f"@derivation does not take {names}: it appended no parameter row and "
                "overwrote AVAL on the input records. Use .adam.derive_param(...) to add "
                "a parameter row such as PARAMCD BMI."
            )
        raise TypeError(f"derivation() got unexpected keyword argument(s): {names}")

    if fn is not None:
        # Bare form: @derivation applied directly to the function.
        return _build_derivation(fn, targets=targets, sources=sources)

    # Parameterised form: @derivation(...) — return a decorator.
    def _decorator(func: Callable) -> Derivation:
        return _build_derivation(func, targets=targets, sources=sources)

    return _decorator

options: show_root_heading: true heading_level: 3

to_repr

fleet.core.repr_utils.to_repr

to_repr(df, *, max_cols=50, max_width=500, max_str_len=100)

Return a pl.from_repr()-ingestible table string for df.

Temporarily adjusts Polars display settings so that wide tables and long strings are never truncated, then restores original settings.

Parameters:

Name Type Description Default
df DataFrame | LazyFrame

A Polars DataFrame or LazyFrame to render.

required
max_cols int

Maximum number of columns to display (avoids …).

50
max_width int

Maximum character width for the table.

500
max_str_len int

Maximum string length before truncation.

100

Returns:

Name Type Description
str str

A Unicode box-drawing table string that can be pasted directly into pl.from_repr(...) to recreate the DataFrame.

Examples:

Generate a pasteable repr and use it to recreate the DataFrame::

import polars as pl
from fleet import to_repr

# Start with any DataFrame (e.g. from a CSV, query, or dict)
original = pl.DataFrame({
    "USUBJID": ["S001", "S002"],
    "AGE": [35, 42],
    "ARM": ["Drug A", "Placebo"],
})

# Generate the from_repr-ready string
print(to_repr(original))
# shape: (2, 3)
# ┌─────────┬─────┬─────────┐
# │ USUBJID ┆ AGE ┆ ARM     │
# │ ---     ┆ --- ┆ ---     │
# │ str     ┆ i64 ┆ str     │
# ╞═════════╪═════╪═════════╡
# │ S001    ┆ 35  ┆ Drug A  │
# │ S002    ┆ 42  ┆ Placebo │
# └─────────┴─────┴─────────┘

# Paste that output into pl.from_repr() in your test/example:
df = pl.from_repr("""\
┌─────────┬─────┬─────────┐
│ USUBJID ┆ AGE ┆ ARM     │
│ ---     ┆ --- ┆ ---     │
│ str     ┆ i64 ┆ str     │
╞═════════╪═════╪═════════╡
│ S001    ┆ 35  ┆ Drug A  │
│ S002    ┆ 42  ┆ Placebo │
└─────────┴─────┴─────────┘
""")
assert df.shape == (2, 3)
Source code in src/fleet/core/repr_utils.py
def to_repr(
    df: pl.DataFrame | pl.LazyFrame,
    *,
    max_cols: int = 50,
    max_width: int = 500,
    max_str_len: int = 100,
) -> str:
    """Return a ``pl.from_repr()``-ingestible table string for *df*.

    Temporarily adjusts Polars display settings so that wide tables and
    long strings are never truncated, then restores original settings.

    Args:
        df: A Polars DataFrame or LazyFrame to render.
        max_cols: Maximum number of columns to display (avoids ``…``).
        max_width: Maximum character width for the table.
        max_str_len: Maximum string length before truncation.

    Returns:
        str: A Unicode box-drawing table string that can be pasted directly
            into ``pl.from_repr(...)`` to recreate the DataFrame.

    Examples:
        Generate a pasteable repr and use it to recreate the DataFrame::

            import polars as pl
            from fleet import to_repr

            # Start with any DataFrame (e.g. from a CSV, query, or dict)
            original = pl.DataFrame({
                "USUBJID": ["S001", "S002"],
                "AGE": [35, 42],
                "ARM": ["Drug A", "Placebo"],
            })

            # Generate the from_repr-ready string
            print(to_repr(original))
            # shape: (2, 3)
            # ┌─────────┬─────┬─────────┐
            # │ USUBJID ┆ AGE ┆ ARM     │
            # │ ---     ┆ --- ┆ ---     │
            # │ str     ┆ i64 ┆ str     │
            # ╞═════════╪═════╪═════════╡
            # │ S001    ┆ 35  ┆ Drug A  │
            # │ S002    ┆ 42  ┆ Placebo │
            # └─────────┴─────┴─────────┘

            # Paste that output into pl.from_repr() in your test/example:
            df = pl.from_repr(\"\"\"\\\n            ┌─────────┬─────┬─────────┐
            │ USUBJID ┆ AGE ┆ ARM     │
            │ ---     ┆ --- ┆ ---     │
            │ str     ┆ i64 ┆ str     │
            ╞═════════╪═════╪═════════╡
            │ S001    ┆ 35  ┆ Drug A  │
            │ S002    ┆ 42  ┆ Placebo │
            └─────────┴─────┴─────────┘
            \"\"\")
            assert df.shape == (2, 3)
    """
    if isinstance(df, pl.LazyFrame):
        df = df.collect()

    with pl.Config(
        tbl_cols=max_cols,
        tbl_width_chars=max_width,
        fmt_str_lengths=max_str_len,
        tbl_rows=-1,
    ):
        return str(df)

options: show_root_heading: true heading_level: 3

SharedVerbsMixin

Verbs available on every namespace (df.sdtm, df.adam, df.adam.adsl, …).

fleet.core._verb_mixin.SharedVerbsMixin

Base mixin providing verbs shared across SDTM and ADaM namespaces.

Concrete namespace classes must provide
  • _lazy: pl.LazyFrame instance attribute (set in __init__)
Class-level constants for parameterised verbs
  • _STUDY_DAY_REF_COL: default reference date column (e.g. "RFSTDTC" or "TRTSDT")
  • _STUDY_DAY_REF_PIN: default pinned domain name (e.g. "DM" or "ADSL")
  • _SEQ_DEFAULT_GROUPS: default grouping columns for seq()
  • _VALIDATE_STANDARD: "sdtm" or "adam"
Source code in src/fleet/core/_verb_mixin.py
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
class SharedVerbsMixin:
    """Base mixin providing verbs shared across SDTM and ADaM namespaces.

    Concrete namespace classes must provide:
        - ``_lazy: pl.LazyFrame`` instance attribute (set in ``__init__``)

    Class-level constants for parameterised verbs:
        - ``_STUDY_DAY_REF_COL``: default reference date column (e.g. ``"RFSTDTC"`` or ``"TRTSDT"``)
        - ``_STUDY_DAY_REF_PIN``: default pinned domain name (e.g. ``"DM"`` or ``"ADSL"``)
        - ``_SEQ_DEFAULT_GROUPS``: default grouping columns for ``seq()``
        - ``_VALIDATE_STANDARD``: ``"sdtm"`` or ``"adam"``
    """

    _lazy: pl.LazyFrame

    # -- Subclass configuration constants (overridden per namespace) ----
    _STUDY_DAY_REF_COL: ClassVar[str] = "RFSTDTC"
    _STUDY_DAY_REF_PIN: ClassVar[str] = "DM"
    _SEQ_DEFAULT_GROUPS: ClassVar[list[str]] = ["STUDYID", "USUBJID"]
    _VALIDATE_STANDARD: ClassVar[Literal["sdtm", "adam"]] = "sdtm"

    # ------------------------------------------------------------------ #
    # Infrastructure (Group A)                                             #
    # ------------------------------------------------------------------ #

    def _chain(
        self,
        *exprs: pl.Expr,
        verb: str | None = None,
        params: dict[str, Any] | None = None,
    ) -> Self:
        """Append expressions to the lazy plan; return a *new* namespace.

        Every expression's root columns are validated against the
        accumulated lazy schema (schema resolution only — no data is
        read), so a column typo raises a verb-attributed
        ``DerivationError`` at the offending verb call instead of a raw
        Polars error at ``to_frame()``.  Columns chained by previous
        verbs are already part of the accumulated schema and validate
        fine.

        *verb* is the user-facing verb name recorded in the error and in
        lineage; when omitted it is derived from the calling function's
        name.  *params* are the verb's keyword arguments recorded in
        lineage for spec round-tripping (``to_spec_yaml``); when omitted
        a best-effort stack capture is attempted.
        """
        from fleet.core.lineage import record_lineage

        if verb is None:
            try:
                verb = sys._getframe(1).f_code.co_name.lstrip("_") or "unknown"
            except Exception:
                verb = "unknown"
        self._validate_chain_exprs(exprs, verb)
        new = copy.copy(self)
        new._lazy = self._lazy.with_columns(list(exprs))
        record_lineage(new, exprs, verb=verb, params=params)
        return new

    def _validate_chain_exprs(self, exprs: tuple[pl.Expr, ...], verb: str) -> None:
        """Validate expression root columns against the lazy schema.

        Cheap by construction: ``collect_schema()`` resolves the plan's
        schema without reading data.  Unresolvable roots (wildcards,
        regex selectors) are skipped.
        """
        if not exprs:
            return
        try:
            schema_names = self._lazy.collect_schema().names()
        except Exception:
            # Schema resolution failed for unrelated reasons — let Polars
            # surface its own error at collect time.
            return
        available = set(schema_names)
        for expr in exprs:
            try:
                roots = expr.meta.root_names()
            except Exception:
                continue
            for root in roots:
                if root in available or root == "*" or root.startswith("^"):
                    continue
                try:
                    out_name = expr.meta.output_name()
                except Exception:
                    out_name = None
                suggestion = difflib.get_close_matches(root, schema_names, n=1)
                hint = f" Did you mean '{suggestion[0]}'?" if suggestion else ""
                target_part = f"({out_name!r})" if out_name else ""
                shown = schema_names if len(schema_names) <= 25 else schema_names[:25]
                more = "" if len(schema_names) <= 25 else f" (+{len(schema_names) - 25} more)"
                raise DerivationError(
                    f"{verb}{target_part}: column '{root}' not found in the frame.{hint} "
                    f"Available columns: {shown}{more}"
                )

    def _materialise_then(self, df: pl.DataFrame) -> Self:
        """Return a fresh namespace wrapping *df* as a new lazy plan."""
        new = copy.copy(self)
        new._lazy = df.lazy()
        return new

    def _with_lazy(self, lf: pl.LazyFrame) -> Self:
        """Return a fresh namespace continuing from lazy plan *lf*.

        Like ``_chain`` but for verbs that restructure the plan (joins,
        sorts, filters) rather than appending column expressions; no
        lineage is recorded.
        """
        new = copy.copy(self)
        new._lazy = lf
        return new

    def to_frame(self) -> DataFrame:
        """Materialise the accumulated pipeline into a Polars DataFrame.

        Returns:
            DataFrame: The fully materialised result of all chained
                verbs — a plain ``pl.DataFrame`` at runtime, typed as
                :class:`fleet.DataFrame` so re-entering ``.sdtm`` /
                ``.adam`` / ``.tlg`` type-checks.

        Raises:
            DerivationError: When collection fails because a column is
                missing — enriched with the lineage entries that
                reference the column, so the error names the verb(s)
                involved.  Also when a ``merge(validate=...)`` fails, with
                the repeated keys named, or when a foreign-key check runs
                under ``fk_policy("error")``.

        Examples:
            Collect the pipeline result::

                result = (
                    df.sdtm
                    .assign("DOMAIN", value="DM")
                    .assign("USUBJID", source="subject_id")
                    .to_frame()
                )
        """
        try:
            df = self._lazy.collect()
        except (
            pl.exceptions.ColumnNotFoundError,
            pl.exceptions.SchemaFieldNotFoundError,
            pl.exceptions.StructFieldNotFoundError,
        ) as err:
            raise self._enrich_collect_error(err) from err
        except pl.exceptions.ComputeError as err:
            named = next(
                (
                    msg
                    for check in getattr(self, "_pending_join_checks", [])
                    if (msg := check.explain_validation()) is not None
                ),
                None,
            )
            if named is None:
                raise
            raise DerivationError(named) from err
        run_checks = getattr(self, "_run_pending_fk_checks", None)
        if run_checks is not None:
            run_checks(df)
        join_checks = getattr(self, "_pending_join_checks", [])
        # Rebind, never mutate: earlier chain copies keep their own queue.
        self._pending_join_checks = []
        for check in join_checks:
            check.warn_many_to_many()
        return cast("DataFrame", df)

    def _enrich_collect_error(self, err: Exception) -> DerivationError:
        """Translate a Polars missing-column error into a lineage-aware one."""
        raw = str(err)
        match = re.search(r'"([^"]+)"', raw)
        col = match.group(1) if match else None
        first_line = raw.splitlines()[0] if raw else type(err).__name__
        lines = [f"Pipeline collection failed: {first_line}"]
        if col is not None:
            nodes = [
                node
                for node in getattr(self, "_lineage", [])
                if node.name == col or col in node.sources
            ]
            if nodes:
                lines.append(f"Derivations referencing '{col}':")
                for node in nodes:
                    srcs = ", ".join(node.sources) if node.sources else "literal"
                    lines.append(f"  - {node.name} ← {node.verb}({srcs})")
        return DerivationError("\n".join(lines))

    def to_dataset_json(
        self,
        path: str | Path,
        *,
        domain: str,
        label: str | None = None,
    ) -> Path:
        """Materialise the pipeline and write a CDISC Dataset-JSON v1.1 file.

        This is a terminal verb — it collects the lazy plan and writes the
        result.  No further chaining is possible after this call.  After
        :meth:`from_spec` on a define.yaml, the file gets the define labels,
        lengths, key sequence and OIDs of the dataset.

        Args:
            path: Destination file path (should end in ``.json``).
            domain: Dataset / domain name (e.g. ``"DM"``, ``"ADSL"``).
            label: Optional human-readable dataset label; it wins over
                the define label.

        Returns:
            Path: Path to the written file.

        Raises:
            DerivationError: When a foreign-key check fails under
                ``fk_policy("error")``; no file is written.

        Examples:
            Export a dataset to Dataset-JSON::

                path = (
                    df.sdtm
                    .assign("DOMAIN", value="DM")
                    .assign("USUBJID", source="subject_id")
                    .to_dataset_json("outputs/dm.json", domain="DM")
                )
        """
        from fleet.io.dataset_json import metadata_from_define, save_dataset_json

        meta: dict[str, Any] = {}
        source = getattr(self, "_spec_source", None)
        if source is not None and source[1].upper() == domain.upper():
            meta = metadata_from_define(source[0], source[1])
        if label is not None:
            meta["label"] = label
        return save_dataset_json(self.to_frame(), path, domain=domain, **meta)

    def inspect(self, prefix: str = "DEBUG") -> Self:
        """Materialise the pipeline at this point and log its state.

        Creates a hard checkpoint: the pipeline resumes from the
        materialised frame, making it easy to isolate exactly where a
        derivation goes wrong.  Output goes through the ``"fleet"``
        logger (INFO level, stdout by default — see
        :mod:`fleet.core.log`).

        Args:
            prefix: Label logged alongside the diagnostic output.

        Returns:
            Self: A fresh namespace wrapping the materialised frame;
                call further verbs or ``.to_frame()`` to continue.

        Examples:
            Inspect the pipeline after assigning key variables::

                result = (
                    df.sdtm
                    .assign("DOMAIN", value="DM")
                    .inspect(prefix="After DOMAIN")
                    .assign("USUBJID", source="subject_id")
                    .to_frame()
                )
        """
        df = self._lazy.collect()
        fleet_log.ensure_default_handler()
        logger.info("[%s] Schema: %s", prefix, df.schema)
        logger.info("[%s] Shape:  %s", prefix, df.shape)
        logger.info("%s", df.head(5))
        return self._materialise_then(df)

    def explain(self) -> Self:
        """Log the current Polars query plan without materialising.

        Useful for understanding how Polars will optimise the accumulated
        derivation pipeline.  Output goes through the ``"fleet"`` logger
        (INFO level, stdout by default — see :mod:`fleet.core.log`).

        Returns:
            Self: The same namespace instance (unchanged); call
                further verbs or ``.to_frame()`` to continue.

        Examples:
            Log the query plan before collecting::

                result = (
                    df.sdtm
                    .assign("DOMAIN", value="DM")
                    .explain()
                    .to_frame()
                )
        """
        fleet_log.ensure_default_handler()
        logger.info("%s", self._lazy.explain())
        return self

    def trail(self) -> Self:
        """Log a table of each derived variable's origin in the pipeline.

        Renders the accumulated variable lineage — the verb that produced
        each column and the source columns it consumed, including
        cross-domain pin sources — as a table through the ``"fleet"``
        logger (INFO level, stdout by default — see
        :mod:`fleet.core.log`), then returns the namespace unchanged so
        the chain continues. Unlike ``inspect``, nothing is
        materialised: the trail is pure metadata captured automatically on
        every verb call.

        Only *derived* variables appear; columns that pass through untouched
        from the source frame are not listed. When a variable is derived more
        than once, each derivation is shown in pipeline order. Variables with
        no source column (e.g. hardcoded constants) are marked ``(literal)``.

        Returns:
            Self: The same namespace instance (unchanged); call further
                verbs or ``.to_frame()`` to continue.

        Examples:
            Print the origin of every derived variable before collecting::

                ae = (
                    ae_raw.sdtm
                    .assign("USUBJID", source="patient_number")
                    .assign("AESTDTC", source="ae_start_date")
                    .pin("DM", dm)
                    .study_day("AESTDY", date_col="AESTDTC")
                    .trail()
                    .to_frame()
                )
        """
        from fleet.core.lineage import lineage_of, pin_lineage_of

        fleet_log.ensure_default_handler()
        nodes = lineage_of(self)
        if not nodes:
            logger.info("Variable trail: (empty — no derivations recorded yet)")
            return self

        # Group cross-domain pin sources by the variable they feed.
        pin_origins: dict[str, list[str]] = {}
        pinned_cols: dict[str, set[str]] = {}
        for dep in pin_lineage_of(self):
            cols = ", ".join(dep.source_cols) if dep.source_cols else "*"
            label = f"{dep.source_domain}.{cols}"
            if dep.relationship != "derivation":
                label += f" [{dep.relationship}]"
            pin_origins.setdefault(dep.target_col, []).append(label)
            pinned_cols.setdefault(dep.target_col, set()).update(dep.source_cols)

        has_domain = any(node.domain for node in nodes)
        rows: list[dict[str, object]] = []
        for i, node in enumerate(nodes, start=1):
            # Drop bare local sources already attributed to a pinned domain.
            covered = pinned_cols.get(node.name, set())
            local = [src for src in node.sources if src not in covered]
            origins = list(dict.fromkeys([*local, *pin_origins.get(node.name, [])]))
            row: dict[str, object] = {
                "#": i,
                "Variable": node.name,
                "Verb": node.verb,
                "Origin": ", ".join(origins) if origins else "(literal)",
            }
            if has_domain:
                row["Domain"] = node.domain or "—"
            rows.append(row)

        table = pl.DataFrame(rows)
        logger.info("Variable trail (%d derivation(s)):", table.height)
        with pl.Config(
            tbl_hide_dataframe_shape=True,
            tbl_hide_column_data_types=True,
            fmt_str_lengths=100,
            tbl_rows=table.height,
        ):
            logger.info("%s", table)
        return self

    def write_parquet(
        self,
        path: str | Path,
        *,
        mkdir: bool = True,
    ) -> DataFrame:
        """Materialise the pipeline, write to Parquet, and return the DataFrame.

        This is a drop-in alternative to ``to_frame()`` when you want to
        persist the dataset as part of the chain.

        Args:
            path: Destination file path.
            mkdir: When ``True`` (default) any missing parent directories
                are created automatically.

        Returns:
            DataFrame: The materialised result (typed as
                :class:`fleet.DataFrame` — see ``to_frame()``).

        Examples:
            Write a domain to Parquet::

                dm = (
                    raw_df.sdtm
                    .assign("USUBJID", source="patient_number")
                    .write_parquet("outputs/dm.parquet")
                )
        """
        df = self.to_frame()
        dest = Path(path)
        if mkdir:
            dest.parent.mkdir(parents=True, exist_ok=True)
        df.write_parquet(dest)
        return df

    # ------------------------------------------------------------------ #
    # Canonical verbs (naming unification)                                 #
    # ------------------------------------------------------------------ #

    def assign(
        self,
        target: str,
        *,
        source: str | None = None,
        value: Any | None = None,
        ct: str | type | None = None,
        ct_map: dict[str, str] | None = None,
        ct_validator: CTValidator | None = None,
        validate_values: bool | None = None,
    ) -> Self:
        """Assign *target* from a source column or a literal value.

        The one canonical assignment verb.  Exactly one of *source* /
        *value* must be given; controlled-terminology behaviour is
        toggled by the presence of *ct* / *ct_map*.

        Args:
            target: Name of the output variable to create.
            source: Input column to copy from.  Mutually exclusive with
                *value*.
            value: Literal value to broadcast to every row.  Mutually
                exclusive with *source*.
            ct: CDISC CT codelist for validation — a generated codelist
                class (e.g. ``SEX``) or an NCI concept ID string
                (e.g. ``"C66731"``).  With *source* and no *ct_map*,
                values are passed through and validated; with *value*,
                the literal is validated at pipeline-build time.
            ct_map: Explicit ``{raw_value: ct_value}`` mapping applied to
                *source* (raw codes that need remapping).  Requires
                *source*.  Keys match the text form of the value, so
                ``{"1": "M"}`` and ``{1: "M"}`` both map a numeric 1; the
                result is text.  A raw value outside the map is kept as
                text, as SAS PUT with no OTHER= keeps it.
            ct_validator: Optional pre-built validator instance.
            validate_values: Controls the codelist check of the values the
                column will hold (after *ct_map*).  ``None`` (default):
                check whenever codelist terms are available, warn with the
                values not in the codelist, and warn about the degradation
                otherwise.  Null and blank values are never findings.
                ``False``: skip the check silently.

        Returns:
            Self: The namespace with *target* appended; call
                ``.to_frame()`` to materialise.

        Raises:
            DerivationError: When neither or both of *source* / *value*
                are given.
            VerbUsageError: When *ct_map* is combined with *value*.

        Examples:
            Copy, hardcode, and CT-map in one vocabulary::

                dm = (
                    raw_df.sdtm
                    .assign("USUBJID", source="subject_id")
                    .assign("DOMAIN", value="DM")
                    .assign("SEX", source="sex", ct=SEX,
                            ct_map={"1": "M", "2": "F"})
                    .to_frame()
                )
        """
        return self._assign_impl(
            target,
            source=source,
            value=value,
            ct=ct,
            ct_map=ct_map,
            ct_validator=ct_validator,
            validate_values=validate_values,
            verb="assign",
            fk=True,
        )

    def _assign_impl(
        self,
        target: str,
        *,
        source: str | None = None,
        value: Any | None = None,
        ct: str | type | None = None,
        ct_map: dict[str, str] | None = None,
        ct_validator: CTValidator | None = None,
        validate_values: bool | None = None,
        verb: str = "assign",
        fk: bool = True,
    ) -> Self:
        """Implementation behind ``assign``.

        *verb* is recorded in lineage/errors (spec-driven runs attribute
        the spec algorithm); *fk* controls the automatic foreign-key check.
        """
        if (source is None) == (value is None):
            raise DerivationError(f"{verb}('{target}'): pass exactly one of source= or value=.")
        if value is not None and ct_map is not None:
            raise VerbUsageError(
                f"{verb}('{target}'): ct_map= requires source= — a literal value "
                "cannot be mapped through a raw-to-CT dictionary."
            )

        ct_mode = ct is not None or ct_map is not None
        ct_cls: type | None = ct if (ct is not None and not isinstance(ct, str)) else None
        if ct_cls is not None:
            from fleet.ct.study_codelists import warn_if_class_stale

            warn_if_class_stale(ct_cls)
        ct_id: str | None = None
        if ct is not None:
            ct_id = ct if isinstance(ct, str) else (getattr(ct, "_concept_id", None) or ct.__name__)

        lineage_params = {
            "target": target,
            "source": source,
            "value": value,
            "ct": ct_id,
            "ct_map": ct_map,
        }

        # ── value path (hardcode) ──
        if value is not None:
            if ct_mode:
                from fleet.ct.validator import get_validator

                validator = ct_validator or get_validator()
                if ct_id is not None and validator.has_codelist(ct_id):
                    valid, msg = validator.validate_value(ct_id, str(value))
                    if not valid:
                        warnings.warn(msg, stacklevel=3)
                else:
                    warnings.warn(
                        f"{verb}('{target}'): codelist '{ct_id}' not found / CT not "
                        f"loaded — value {value!r} assigned unvalidated. Load CT via "
                        "fleet.get_validator().load_ct_file(...) or drop the ct= "
                        "parameter.",
                        stacklevel=3,
                    )
            ns = self._chain(pl.lit(value).alias(target), verb=verb, params=lineage_params)
            if target == "DOMAIN":
                ns._domain = str(value)
            if fk:
                ns._auto_fk_check(target)
            return ns

        # ── source path ──
        assert source is not None
        if ct_map:
            text = pl.col(source).cast(pl.String)
            mapped = text.replace_strict(
                {str(k): v for k, v in ct_map.items()}, default=text, return_dtype=pl.String
            )
            ns = self._chain(mapped.alias(target), verb=verb, params=lineage_params)
            if fk:
                ns._auto_fk_check(target)
            if validate_values is not False and ct_id:
                if ct_validator is None:
                    from fleet.ct.validator import get_validator

                    ct_validator = get_validator()
                # Validate the post-mapping values the column will contain.
                validated = self._warn_invalid_values(
                    source, ct_id, ct_validator, ct_cls, target=target, value_map=ct_map
                )
                if not validated:
                    warnings.warn(
                        f"{verb}('{target}'): codelist '{ct_id}' not found / CT not "
                        f"loaded — values mapped from '{source}' are unvalidated. Load CT "
                        "via fleet.get_validator().load_ct_file(...), or pass "
                        "validate_values=False to silence this warning.",
                        stacklevel=3,
                    )
            return ns

        ns = self._chain(pl.col(source).alias(target), verb=verb, params=lineage_params)
        if fk:
            ns._auto_fk_check(target)

        if not ct_mode or validate_values is False:
            return ns

        # No-mapping CT mode: validate-and-pass-through (values are never
        # rewritten — decoding submission values into NCI preferred terms
        # would corrupt conformant data).
        if ct_validator is None:
            from fleet.ct.validator import get_validator

            ct_validator = get_validator()
        validated = self._warn_invalid_values(
            source, ct_id or "", ct_validator, ct_cls, target=target
        )
        if not validated:
            warnings.warn(
                f"{verb}('{target}'): codelist '{ct_id}' not found / CT not "
                f"loaded — values from '{source}' copied unvalidated. Load CT via "
                "fleet.get_validator().load_ct_file(...), pass an explicit ct_map, "
                "or pass validate_values=False to silence this warning.",
                stacklevel=3,
            )
        return ns

    def _warn_invalid_values(
        self,
        source: str,
        ct_codelist: str,
        ct_validator: CTValidator | None,
        ct_codelist_cls: type | None = None,
        *,
        target: str | None = None,
        value_map: dict[str, str] | None = None,
    ) -> bool:
        """Eagerly check unique *source* values against the loaded codelist.

        Emits a UserWarning for any values not in the valid submission
        terms, naming the dataset (when known), the target variable, and
        the codelist.  Derives valid values from the validator cache
        first, falling back to introspecting the codelist class
        attributes when CT is not loaded.  When *value_map* is given the
        mapping is applied before checking, so the *post-mapping* column
        values are validated.

        Returns:
            True when validation was performed (valid terms were
            available), False when it could not be performed — callers
            use this to report the degradation.
        """
        valid_values: set[str] = set()

        # Strategy 1: from the validator cache
        if ct_validator is not None:
            valid_values = set(ct_validator.get_valid_values(ct_codelist))

        # Strategy 2: introspect the codelist class (works without CT loaded).
        # A term that starts with a digit (10^9/L) has an attribute name that
        # starts with "_", so only the class metadata is left out.
        if not valid_values and ct_codelist_cls is not None:
            valid_values = set(getattr(ct_codelist_cls, "_terms", ())) or {
                v
                for k, v in vars(ct_codelist_cls).items()
                if not k.startswith("__") and k not in _CODELIST_META and isinstance(v, str)
            }

        if not valid_values:
            return False

        try:
            unique_vals = (
                self._lazy.select(pl.col(source).drop_nulls().unique())
                .collect()
                .to_series()
                .to_list()
            )
        except pl.exceptions.PolarsError:
            # Source values not retrievable — validation did not happen.
            return False
        if value_map:
            text_map = {str(k): v for k, v in value_map.items()}
            unique_vals = list(dict.fromkeys(text_map.get(str(v), str(v)) for v in unique_vals))
        # Null and blank are missing values, not CT findings.
        invalid = [v for v in unique_vals if v not in (None, "") and v not in valid_values]
        if invalid:
            domain = getattr(self, "_domain", None)
            where = f"{domain}.{target}" if domain and target else (target or source)
            hint = (
                "Add the raw value to ct_map, or correct the map target."
                if value_map
                else "Consider providing a ct_map parameter."
            )
            warnings.warn(
                f"{where}: column '{source}' contains values not in codelist "
                f"'{ct_codelist}': {invalid}. "
                f"Valid values: {sorted(valid_values)}. {hint}",
                stacklevel=3,
            )
        return True

    def case_when(
        self,
        target: str,
        *,
        when: list[dict[str, Any]],
        else_: Any = None,
    ) -> Self:
        """Multi-branch conditional derivation (first matching branch wins).

        The one canonical conditional verb.

        Args:
            target: Name of the output variable.
            when: Ordered list of ``{"condition": expr, "value": any}``
                dicts.  ``condition`` may be a Polars expression or an
                expression string.
            else_: Fallback value when no branch matches.

        Returns:
            Self: The namespace with *target* appended; call
                ``.to_frame()`` to materialise.

        Examples:
            Derive an age group::

                adsl = (
                    dm_df.adam.adsl
                    .case_when("AGEGR1", when=[
                        {"condition": 'pl.col("AGE") < 65', "value": "<65"},
                        {"condition": 'pl.col("AGE") < 75', "value": "65-74"},
                    ], else_=">=75")
                    .to_frame()
                )
        """
        return self._case_when_impl(target, when=when, else_=else_, verb="case_when")

    def _case_when_impl(
        self,
        target: str,
        *,
        when: list[dict[str, Any]],
        else_: Any,
        verb: str = "case_when",
    ) -> Self:
        """Implementation behind ``case_when``."""
        from fleet.sdtm.utils import parse_expression

        schema = self._lazy.collect_schema()

        def _cond(raw: Any) -> pl.Expr:
            return raw if isinstance(raw, pl.Expr) else parse_expression(str(raw), schema)

        params = {"target": target, "when": when, "else_": else_}
        if not when:
            return self._chain(pl.lit(else_).alias(target), verb=verb, params=params)
        first = when[0]
        chain = pl.when(_cond(first["condition"])).then(pl.lit(first["value"]))
        for branch in when[1:]:
            chain = chain.when(_cond(branch["condition"])).then(pl.lit(branch["value"]))
        return self._chain(chain.otherwise(pl.lit(else_)).alias(target), verb=verb, params=params)

    def merge(
        self,
        dataset: pl.DataFrame | pl.LazyFrame | None = None,
        *,
        on: str | list[str] | None = None,
        how: str = "left",
        keep: list[str] | None = None,
        where: str | pl.Expr | None = None,
        validate: Literal["m:1", "1:m", "1:1"] | None = None,
    ) -> Self:
        """Join *dataset* into the pipeline using key column(s) *on*.

        The one canonical join verb.  The join is appended to the lazy
        plan; nothing is materialised.  It reads as SAS
        ``merge left right(keep=...)``: every pipeline column stays, and
        *keep* limits the columns taken from *dataset*.  Keys match
        exactly: ``"S1 "`` and ``"S1"`` are two keys.

        A non-key column on both sides raises: select or rename the
        columns of *dataset* first.  A key that repeats on both sides
        warns at ``to_frame()``, because the join then gives every pair
        of rows.  ``how="full"`` gives one key column, as SAS MERGE.

        Args:
            dataset: The ``pl.DataFrame`` / ``pl.LazyFrame`` to merge in.
            on: Key column name(s) for the join.
            how: Join strategy (default ``"left"``).
            keep: Optional columns of *dataset* to bring in, besides the
                *on* key(s).  When ``None``, every column of *dataset* is
                brought in.
            where: Optional filter expression applied to *dataset*
                before the join; it may use a column that *keep* leaves
                out.
            validate: Optional key rule, checked at ``to_frame()``:
                ``"m:1"`` (each key once in *dataset*), ``"1:m"`` (once in
                the pipeline) or ``"1:1"`` (once on both sides).

        Returns:
            Self: The namespace continuing from the joined plan.

        Raises:
            VerbUsageError: When *dataset* or *on* is missing.
            DerivationError: When a *keep* entry is absent from *dataset*
                (with a did-you-mean suggestion), or a non-key column is on
                both sides.  At ``to_frame()``, when *validate* fails; the
                message names the repeated keys.

        References:
            ADR-0032 (docs/adr/0032-merge-reads-as-sas-merge-and-stops-on-a-clash.md).
            admiral ``derive_vars_merged`` stops on a column on both sides.

        Examples:
            Merge one supplemental qualifier onto the DM domain::

                dm = (
                    raw_df.sdtm
                    .assign("DOMAIN", value="DM")
                    .merge(
                        suppdm_df,
                        on="USUBJID",
                        keep=["QVAL"],
                        where='pl.col("QNAM") == "RACE1"',
                        validate="m:1",
                    )
                    .to_frame()
                )
        """
        return self._merge_impl(
            dataset, on=on, how=how, keep=keep, where=where, validate=validate, verb="merge"
        )

    def _merge_impl(
        self,
        dataset: pl.DataFrame | pl.LazyFrame | None,
        *,
        on: str | list[str] | None,
        how: str = "left",
        keep: list[str] | None = None,
        where: str | pl.Expr | None = None,
        validate: Literal["m:1", "1:m", "1:1"] | None = None,
        verb: str = "merge",
    ) -> Self:
        """Implementation behind ``merge``."""
        from fleet.sdtm.utils import parse_expression

        if isinstance(dataset, pl.LazyFrame):
            right = dataset
        elif isinstance(dataset, pl.DataFrame):
            right = dataset.lazy()
        else:
            raise VerbUsageError(
                f"{verb}() requires dataset= (a DataFrame or LazyFrame), "
                f"got {type(dataset).__name__}."
            )
        if on is None:
            raise VerbUsageError(f"{verb}() requires on= (join key column(s)).")
        on_list = [on] if isinstance(on, str) else list(on)
        if where is not None:
            where_expr = where if isinstance(where, pl.Expr) else parse_expression(str(where))
            right = right.filter(where_expr)
        if keep:
            right_names = right.collect_schema().names()
            require_columns(f"{verb}(keep=...)", keep, right_names, where="the right dataset")
            right = right.select(list(dict.fromkeys(on_list + list(keep))))

        adds_columns = how not in ("semi", "anti")
        if adds_columns:
            refuse_shared_columns(
                verb,
                self._lazy.collect_schema().names(),
                right.collect_schema().names(),
                on_list,
                hint="Select or rename the columns of the right dataset, or drop them "
                "from the pipeline first.",
            )
        joined = self._lazy.join(
            right,
            on=on_list,
            how=how,  # type: ignore[arg-type]
            nulls_equal=True,
            coalesce=True if how == "full" else None,
            validate=validate or "m:m",
        )
        new = self._with_lazy(joined)
        if adds_columns:
            check = JoinCheck(verb, tuple(on_list), self._lazy, right, validate)
            new._pending_join_checks = [*getattr(self, "_pending_join_checks", []), check]
        return new

    def keep(self, *columns: str | list[str]) -> Self:
        """Restrict the frame to *columns*, in the given order.

        Accepts either variadic names — ``keep("STUDYID", "USUBJID")`` —
        or a single list — ``keep(["STUDYID", "USUBJID"])``.  Stays lazy.

        Args:
            *columns: Column names (or one list of names) to keep.

        Returns:
            Self: The namespace continuing from the restricted plan.

        Raises:
            DerivationError: When a requested column is absent (with a
                did-you-mean suggestion), or no columns are given.

        Examples:
            Keep only the submission variables::

                dm = (
                    raw_df.sdtm
                    .assign("USUBJID", source="subject_id")
                    .keep("STUDYID", "USUBJID", "SEX")
                    .to_frame()
                )
        """
        if len(columns) == 1 and isinstance(columns[0], list):
            cols: list[str] = list(columns[0])
        else:
            cols = [c for c in columns]  # type: ignore[misc]
        if not cols:
            raise DerivationError("keep() requires at least one column name.")
        require_columns("keep()", cols, self._lazy.collect_schema().names(), where="the frame")
        return self._with_lazy(self._lazy.select(cols))

    # ------------------------------------------------------------------ #
    # verbs — programmatic verb listing                                    #
    # ------------------------------------------------------------------ #

    #: Public methods that are infrastructure rather than verbs — kept
    #: out of the ``verbs()`` listing.
    _VERBS_EXCLUDE: ClassVar[frozenset[str]] = frozenset({"verbs"})

    def verbs(self) -> pl.DataFrame:
        """List the public verbs available on this namespace.

        Walks the class MRO collecting public Fleet-defined methods and
        returns a tidy frame with each verb's name, the first sentence
        of its docstring and the namespace that defines it.  This is
        the always-current alternative to hard-coded verb counts in
        docs, and the discovery seam for a sub-namespace: autocomplete
        shows every inherited verb, ``origin`` tells them apart.

        Returns:
            pl.DataFrame: Columns ``verb``, ``summary`` and ``origin``,
                sorted by verb name.  ``origin`` is the path a programmer
                types to reach the namespace that defines the verb
                (``"sdtm"``, ``"adam"``, ``"adam.metabolic"``), or
                ``"core"`` for the verbs every namespace shares.

        Examples:
            Discover what an SDTM pipeline can do::

                import fleet  # noqa: F401

                catalog = raw_df.sdtm.verbs()
                print(catalog)

            Keep only the verbs a therapeutic-area namespace adds::

                own = raw_df.adam.metabolic.verbs().filter(
                    pl.col("origin") == "adam.metabolic"
                )
        """
        from fleet.core.algorithm_resolver import docstring_summary

        rows: list[dict[str, str]] = []
        seen: set[str] = set(self._VERBS_EXCLUDE)
        for klass in type(self).__mro__:
            if not klass.__module__.startswith("fleet."):
                continue
            origin = _verb_origin(klass)
            for name, attr in vars(klass).items():
                if name.startswith("_") or name in seen:
                    continue
                seen.add(name)
                if isinstance(attr, (property, staticmethod, classmethod)):
                    continue
                if not callable(attr):
                    continue
                rows.append(
                    {"verb": name, "summary": docstring_summary(attr.__doc__), "origin": origin}
                )
        rows.sort(key=lambda r: r["verb"])
        return pl.DataFrame(
            rows, schema={"verb": pl.String, "summary": pl.String, "origin": pl.String}
        )

    # ------------------------------------------------------------------ #
    # Algorithmic (Group B)                                                #
    # ------------------------------------------------------------------ #

    @overload
    def derivation(
        self,
        target: str,
        *,
        expression: str | pl.Expr | Callable[[], pl.Expr],
    ) -> Self: ...

    @overload
    def derivation(self, target: Derivation) -> Self: ...

    def derivation(
        self,
        target: str | Derivation | None = None,
        *,
        expression: str | pl.Expr | Callable[[], pl.Expr] | None = None,
    ) -> Self:
        """Derive *target* using an expression, lambda, or ``Derivation`` object.

        Four call forms are supported:

        **Case 1 — string (AST-sandboxed, YAML-compatible)**::

            .derivation("COL", expression="pl.col('src').cast(pl.String)")

        **Case 2 — direct ``pl.Expr``**::

            .derivation("COL", expression=pl.col("src").cast(pl.String))

        **Case 3 — zero-arg lambda returning ``pl.Expr`` (full IDE support)**::

            .derivation("COL", expression=lambda: pl.col("src").cast(pl.Int32))

        **Case 4 — ``@derivation`` object (file-based, full lineage)**::

            from specs.study01.derivations import MY_DRULE
            .derivation(MY_DRULE)

        Args:
            target: For Cases 1–3, the name of the output variable
                (required).  For Case 4, the
                :class:`~fleet.core.derivation.Derivation` object to dispatch.
            expression: A Polars expression, expression string, or zero-arg
                callable returning ``pl.Expr``.  Required for Cases 1–3.

        Returns:
            Self: The namespace with *target* appended; call ``.to_frame()``
                to materialise.

        Raises:
            ValueError: If *target* is a string but *expression* is not
                provided, or vice-versa.
            TypeError: If a lambda-style *expression* does not return
                ``pl.Expr``.

        Examples:
            Case 1 — string expression::

                result = (
                    raw_df.sdtm
                    .derivation("SITEID", expression="pl.col('site_id').cast(pl.String)")
                    .to_frame()
                )

            Case 3 — lambda::

                result = (
                    raw_df.sdtm
                    .derivation("VISITNUM", expression=lambda: pl.col("visit").cast(pl.Int32))
                    .to_frame()
                )

            Case 4 — ``@derivation`` object::

                from specs.study01.derivations import MY_DRULE

                result = (
                    raw_df.sdtm
                    .derivation(MY_DRULE)
                    .to_frame()
                )
        """
        from fleet.sdtm.utils import parse_expression

        # Case 4: Derivation object passed as first positional arg.
        if target is not None and not isinstance(target, str):
            return self._apply_derivation(target)  # type: ignore[arg-type]

        # Cases 1–3 require a string target.
        if target is None:
            raise DerivationError("target is required when expression= is provided.")
        if expression is None:
            raise DerivationError("expression is required when target is a string.")

        params = {"target": target, "expression": expression}

        # Case 2: direct pl.Expr.
        if isinstance(expression, pl.Expr):
            return self._chain(expression.alias(target), verb="derivation", params=params)

        # Case 3: lambda / zero-arg callable.
        if callable(expression) and not isinstance(expression, str):
            expr = expression()
            if not isinstance(expr, pl.Expr):
                raise VerbUsageError(
                    f"expression callable must return pl.Expr, got {type(expr).__name__}"
                )
            return self._chain(expr.alias(target), verb="derivation", params=params)

        # Case 1: string through AST sandbox.
        return self._chain(
            parse_expression(str(expression), self._lazy.collect_schema()).alias(target),
            verb="derivation",
            params=params,
        )

    def _apply_derivation(self, drv: Derivation) -> Self:
        """Dispatch a :class:`~fleet.core.derivation.Derivation` object.

        Routing:

        * ``kind="column"`` — expression stays lazy; lineage via ``_chain()``.
        * ``kind="frame"`` — the frame is materialised, the function
          called, and the result re-wrapped.

        Args:
            drv: The :class:`~fleet.core.derivation.Derivation` to execute.

        Returns:
            Self: Updated namespace.

        Raises:
            TypeError: If a frame derivation returns a non-DataFrame.
        """
        from fleet.core.lineage import _append_lineage_nodes

        if drv.kind == "column":
            expr: pl.Expr = drv()
            ns = self._chain(expr.alias(drv.targets[0]), verb="derivation", params={})
            # Registered derivations round-trip via to_spec_yaml as
            # `algorithm: derivation` blocks with their dotted path as `callable:`.
            if ns._lineage:
                ns._lineage[-1].spec = {"algorithm": "derivation", "callable": drv.dotted_path}
            return ns

        df = self.to_frame()
        result = drv(df)
        if not isinstance(result, pl.DataFrame):
            raise VerbUsageError(
                f"Derivation '{drv.name}' is kind={drv.kind!r} but fn() returned "
                f"{type(result).__name__!r} — expected pl.DataFrame."
            )
        ns = self._materialise_then(result)
        return _append_lineage_nodes(ns, drv)

    # ------------------------------------------------------------------ #
    # duration                                                             #
    # ------------------------------------------------------------------ #

    def duration(
        self,
        target: str,
        *,
        start: str | pl.Expr,
        end: str | pl.Expr,
        unit: Literal["seconds", "minutes", "hours", "days", "weeks", "months", "years"] = "days",
        add_one: bool | None = None,
        out: Literal["numeric", "iso8601"] = "numeric",
    ) -> Self:
        """Compute the duration between two date/datetime columns.

        Supports column references (``str``) and Polars expressions
        for *start* and *end*; an expression is read by its type, as a
        column is.  ``--DTC`` text is read by its date part for
        day-based units and by its date-time for hours, minutes and
        seconds; a partial value gives null, and for hours, minutes and
        seconds a warning gives the count of text values with no time.

        The ``add_one`` parameter controls inclusive counting:

        - ``None`` (default): auto-resolves from the target suffix and the
          unit.  ``*DY`` targets in days use the CDISC study-day
          convention (no day 0).  Days, weeks, months and years add one
          **day** before the division; hours, minutes and seconds give
          the raw difference (PK elapsed time).
        - ``True``: add one day (day-based units) or one unit (sub-day).
        - ``False``: raw difference.

        One is added only when the end is on or after the start, as
        admiral ``compute_duration`` does: an end one day before the start
        gives -1, never 0.  Weeks, months and years divide the day count
        by 7, 30.4375 and 365.25, so this verb does not give a completed
        age in years.

        Args:
            target: Name of the output column.
            start: Start date column name or expression.
            end: End date column name or expression.
            unit: Duration unit — ``"seconds"``, ``"minutes"``, ``"hours"``,
                ``"days"`` (default), ``"weeks"``, ``"months"``, ``"years"``.
            add_one: Override for inclusive counting.
            out: Output format — ``"numeric"`` (default) or ``"iso8601"``.
                ``"iso8601"`` keeps the sign (``-PT15M``), writes hours,
                minutes and seconds from the total (``PT1H30M``) and adds
                one only when ``add_one=True`` is given (an elapsed time,
                ``P9D`` for 1 to 10 January).  Weeks give null with a
                warning for a span that is not whole weeks; months and
                years raise.  ``"iso8601"`` is incompatible with the
                ``*DY`` study-day convention: pass ``add_one`` explicitly
                (or use a non-DY target) to combine them.

        Returns:
            Self: The namespace with *target* appended; call ``.to_frame()``
                to materialise.

        Raises:
            DerivationError: On an unknown *unit*/*out* value, when
                ``out="iso8601"`` is combined with a ``*DY`` target while
                ``add_one`` is unset (the study-day convention would
                silently override the requested format), with months or
                years, or when a column holds numbers (no date origin is
                guessed).

        References:
            ISO 8601 durations and SDTMIG 3.4 ``--ELTM``; admiral
            ``compute_duration``; ADR-0011 and ADR-0022.

        Examples:
            ISO 8601 duration::

                ex = (
                    raw_df.sdtm
                    .date("EXSTDTC", source="dose_start")
                    .date("EXENDTC", source="dose_end")
                    .duration("EXDUR", start="EXSTDTC", end="EXENDTC",
                              out="iso8601")
                    .to_frame()
                )

            Treatment duration in days::

                adsl = (
                    dm_df.adam.adsl
                    .duration("TRTDURD", start="TRTSDT", end="TRTEDT")
                    .to_frame()
                )
        """
        if not isinstance(start, (str, pl.Expr)):
            raise VerbUsageError(f"start must be a column name (str) or pl.Expr, got {type(start)}")
        if not isinstance(end, (str, pl.Expr)):
            raise VerbUsageError(f"end must be a column name (str) or pl.Expr, got {type(end)}")
        if out not in ("numeric", "iso8601"):
            raise DerivationError(
                f"duration out={out!r} is not supported. Choose 'numeric' or 'iso8601'."
            )
        if out == "iso8601" and add_one is None and target.endswith("DY"):
            raise DerivationError(
                f"duration('{target}', out='iso8601'): targets ending in 'DY' follow the "
                "CDISC study-day convention (integer day count, no day 0) and always "
                "produce numeric output, so out='iso8601' would be ignored. Either use a "
                "target that does not end in 'DY', or pass add_one=True/False explicitly "
                "to opt out of the study-day convention and get ISO 8601 output."
            )

        duration_params = {
            "target": target,
            "start": start,
            "end": end,
            "unit": unit,
            "add_one": add_one,
            "out": out,
        }

        schema = self._lazy.collect_schema()
        sub_day = unit in ("seconds", "minutes", "hours")
        call = f"duration('{target}')"

        def _to_date_expr(col_or_expr: str | pl.Expr) -> pl.Expr:
            """Resolve a column or an expression to a date (day units) or a date-time (sub-day)."""
            if isinstance(col_or_expr, str):
                col, dtype = pl.col(col_or_expr), schema.get(col_or_expr)
            else:
                col = col_or_expr
                dtype = self._lazy.select(col).collect_schema().dtypes()[0]
            if not sub_day:
                return to_day(col, dtype, verb=call)
            refuse_number(
                col.meta.output_name(raise_if_undetermined=False) or "the column", dtype, verb=call
            )
            if dtype != pl.String:
                return col
            name = col.meta.output_name(raise_if_undetermined=False) or "the text"
            given = col.str.strip_chars().fill_null("") != ""
            return warn_on_collect(
                datetime_part(col),
                given & datetime_part(col).is_null(),
                lambda n, values: (
                    f"{call}: {n} value(s) of {name} have no hour and minute, or are not "
                    f"ISO 8601, so {target} is null for them. To impute a time with a flag, "
                    f"derive a *DTM variable with .date() first. Values: {values}"
                ),
                dtype=pl.Datetime("us"),
                shown=col,
            )

        s_expr = _to_date_expr(start)
        e_expr = _to_date_expr(end)

        valid_units = {
            "seconds",
            "minutes",
            "hours",
            "days",
            "weeks",
            "months",
            "years",
        }
        if unit not in valid_units:
            raise DerivationError(
                f"duration unit={unit!r} is not supported. Choose one of: {sorted(valid_units)}"
            )

        if sub_day:
            s_dtm = s_expr.cast(pl.Datetime("us"))
            e_dtm = e_expr.cast(pl.Datetime("us"))
            seconds = (e_dtm - s_dtm).dt.total_seconds()
            diff_s = seconds.cast(pl.Float64)
            if unit == "seconds":
                diff = diff_s.cast(pl.Int64)
            elif unit == "minutes":
                diff = diff_s / 60.0
            else:  # hours
                diff = diff_s / 3600.0
        else:
            diff_days = (e_expr - s_expr).dt.total_days()
            divisor = {"days": 1, "weeks": 7.0, "months": 30.4375, "years": 365.25}[unit]
            diff = diff_days if unit == "days" else diff_days.cast(pl.Float64) / divisor

        if out == "iso8601":
            if unit in ("months", "years"):
                raise DerivationError(
                    f"{call}: out='iso8601' with unit='{unit}' would cut the day count to whole "
                    f"{unit}, because a month or a year has no fixed length. Use unit='days'."
                )
            if sub_day:
                iso_expr = _iso_clock(seconds, unit, add_one=add_one is True)
            else:
                iso_expr = _iso_days(
                    diff_days, unit, add_one=add_one is True, call=call, target=target
                )
            return self._chain(iso_expr.alias(target), verb="duration", params=duration_params)

        # Resolve add_one
        if add_one is None:
            if target.endswith("DY") and unit == "days":
                # CDISC study day: +1 if >= 0, no day 0
                result_expr = (
                    (pl.when(diff >= 0).then(diff + 1).otherwise(diff)).cast(pl.Int64).alias(target)
                )
                return self._chain(result_expr, verb="duration", params=duration_params)
            add_one = not sub_day

        if add_one and sub_day:
            result_expr = pl.when(diff >= 0).then(diff + 1).otherwise(diff).alias(target)
        elif add_one:
            inclusive = pl.when(diff_days >= 0).then(diff_days + 1).otherwise(diff_days)
            result_expr = (
                inclusive if unit == "days" else inclusive.cast(pl.Float64) / divisor
            ).alias(target)
        else:
            result_expr = diff.alias(target)

        return self._chain(result_expr, verb="duration", params=duration_params)

    # ------------------------------------------------------------------ #
    # study_day                                                            #
    # ------------------------------------------------------------------ #

    def study_day(
        self,
        target: str,
        *,
        date_col: str,
        ref_col: str | None = None,
        ref_pin: str | None = None,
        ref_df: pl.DataFrame | None = None,
        dm: pl.DataFrame | None = None,
        adsl: pl.DataFrame | None = None,
    ) -> Self:
        """Derive a CDISC study day variable from a date column and reference date.

        Uses the CDISC algorithm: ``date - ref_date + 1`` when
        ``date >= ref_date``, else ``date - ref_date`` (no day 0), on the
        date portion of each value (SDTMIG 3.4 section 4.4.4): a time
        part is ignored, and a partial date gives null.

        The reference date is resolved in this order:

        1. Explicit ``ref_df=`` parameter (highest priority).  ``dm=``
           and ``adsl=`` are accepted aliases of ``ref_df=`` matching
           the SDTM/ADaM vocabulary.
        2. Pinned domain (via ``.pin(...)``).
        3. ``ref_col`` already present in the current frame.
        4. Actionable ``LookupError``.

        Args:
            target: Name of the output study day variable
                (e.g. ``"AESTDY"``, ``"ASTDY"``).
            date_col: Column containing the date to measure from.
            ref_col: Reference date column name.  Defaults to
                ``_STUDY_DAY_REF_COL`` class constant (``RFSTDTC`` on
                SDTM, ``TRTSDT`` on ADaM).
            ref_pin: Pinned domain name.  Defaults to
                ``_STUDY_DAY_REF_PIN`` class constant (``DM`` on SDTM,
                ``ADSL`` on ADaM).
            ref_df: Optional explicit DataFrame override — bypasses pinning.
            dm: Alias of *ref_df* (SDTM vocabulary).
            adsl: Alias of *ref_df* (ADaM vocabulary).

        Returns:
            Self: The namespace with *target* appended; call
                ``.to_frame()`` to materialise.

        Raises:
            LookupError: If the reference date cannot be resolved from
                any source.
            VerbUsageError: If more than one of *ref_df* / *dm* / *adsl*
                is given.
            DerivationError: If the reference frame has two different
                reference dates for one subject (ADR-0032).

        Examples:
            Derive study day from pinned reference::

                ae = (
                    ae_raw.sdtm
                    .pin("DM", dm_df)
                    .study_day("AESTDY", date_col="AESTDTC")
                    .to_frame()
                )

            ADaM study day::

                adae = (
                    ae_df.adam.occds("ADAE")
                    .pin("ADSL", adsl_df)
                    .study_day("ASTDY", date_col="ASTDT")
                    .to_frame()
                )
        """
        from fleet.core.lineage import record_pin_lineage

        provided = [f for f in (ref_df, dm, adsl) if f is not None]
        if len(provided) > 1:
            raise VerbUsageError(
                f"study_day() accepts only one of ref_df= / dm= / adsl= — got {len(provided)}."
            )
        ref_df = provided[0] if provided else None

        # Resolve defaults from class constants
        _ref_col = ref_col if ref_col is not None else self._STUDY_DAY_REF_COL
        _ref_pin = ref_pin if ref_pin is not None else self._STUDY_DAY_REF_PIN

        schema = self._lazy.collect_schema()

        # Resolve reference date source
        if ref_df is not None:
            source_df = ref_df
            join_key = ["USUBJID"]
        elif _ref_col in schema.names():
            # ref_col already in frame — no join needed; stays lazy.
            date_expr = to_day(pl.col(date_col), schema.get(date_col), verb="study_day")
            ref_expr = to_day(pl.col(_ref_col), schema.get(_ref_col), verb="study_day")
            diff = (date_expr - ref_expr).dt.total_days()
            study_day_expr = pl.when(diff >= 0).then(diff + 1).otherwise(diff).alias(target)
            return self._chain(
                study_day_expr,
                verb="study_day",
                params={"target": target, "date_col": date_col, "ref_col": _ref_col},
            )
        else:
            source_df = self._require_pin(_ref_pin.upper(), "study_day", columns=[_ref_col])
            join_key = self._pin_join_key(_ref_pin.upper())

        df = self._lazy.collect()

        # Join, compute, drop temp column
        ref_slim = refuse_repeated_keys(
            "study_day()",
            source_df.select(
                [c for c in dict.fromkeys(join_key + [_ref_col]) if c in source_df.columns]
            ),
            join_key,
            source=_ref_pin.upper() if ref_df is None else "the reference frame",
        )

        _ref_tmp = f"__pin_{_ref_col}__"
        ref_slim = ref_slim.rename({_ref_col: _ref_tmp})

        df = df.join(ref_slim, on=join_key, how="left", nulls_equal=True)

        date_expr = to_day(pl.col(date_col), df.schema.get(date_col), verb="study_day")
        ref_expr = to_day(pl.col(_ref_tmp), df.schema.get(_ref_tmp), verb="study_day")

        diff = (date_expr - ref_expr).dt.total_days()
        study_day_expr = pl.when(diff >= 0).then(diff + 1).otherwise(diff).alias(target)
        df = df.with_columns(study_day_expr).drop(_ref_tmp)

        new = self._materialise_then(df)

        # Record variable lineage
        from fleet.core.dag import VariableNode

        var_lineage: list = list(getattr(new, "_lineage", []))
        var_lineage.append(
            VariableNode(
                name=target,
                verb="study_day",
                sources=[date_col, _ref_col],
                method=f"{self.__class__.__module__}.{self.__class__.__qualname__}.study_day",
                domain=getattr(new, "_domain", None),
                params={
                    "target": target,
                    "date_col": date_col,
                    "ref_col": _ref_col,
                    "ref_pin": _ref_pin,
                },
            )
        )
        new._lineage = var_lineage

        # Record pin lineage
        record_pin_lineage(
            new,
            target_col=target,
            verb="study_day",
            source_domain=_ref_pin.upper(),
            source_cols=[_ref_col],
            join_key=join_key,
            relationship="derivation",
        )
        return new

    # ------------------------------------------------------------------ #
    # seq                                                                   #
    # ------------------------------------------------------------------ #

    def seq(
        self,
        target: str = "ASEQ",
        *,
        order_by: list[str] | None = None,
        by: list[str] | None = None,
        start_at: int = 1,
        check_uniqueness: bool = False,
    ) -> Self:
        """Derive a 1-based sequence number within each group.

        Generates a 1-based integer sequence that uniquely identifies each
        record within a grouping partition.  The dataset is sorted by
        *order_by* columns within each *by* partition before numbering
        — ensuring deterministic, reproducible sequence values.  The
        sort and the window numbering are appended to the lazy plan.

        Args:
            target: Name of the output sequence variable (e.g. ``"AESEQ"``,
                ``"ASEQ"``).
            order_by: Columns that define the sort order within each group.
                Records that tie keep their input order, as PROC SORT
                EQUALS.  When ``None``, the current row order is preserved.
            by: Partition columns.  Defaults to class constant
                ``_SEQ_DEFAULT_GROUPS``.
            start_at: First sequence value (default ``1``).
            check_uniqueness: If ``True``, emit a warning when the
                combination of *by* + *order_by* does not uniquely
                identify each row (requires reading the key columns).

        Returns:
            Self: A fresh namespace with *target* appended; call
                ``.to_frame()`` to materialise.

        Examples:
            SDTM sequence number::

                ae = (
                    raw_df.sdtm
                    .seq("AESEQ", order_by=["AESTDTC"])
                    .to_frame()
                )

            ADaM sequence number::

                adae = (
                    ae_df.adam.occds
                    .seq("ASEQ", order_by=["ASTDT"], by=["USUBJID"])
                    .to_frame()
                )
        """
        grps = by or list(self._SEQ_DEFAULT_GROUPS)

        lf = self._lazy
        if order_by:
            lf = lf.sort(order_by, maintain_order=True)

        if check_uniqueness and order_by:
            key_cols = grps + list(order_by)
            schema_names = lf.collect_schema().names()
            available = [c for c in key_cols if c in schema_names]
            counts = lf.select(
                pl.len().alias("__n_total__"),
                pl.struct(available).n_unique().alias("__n_unique__"),
            ).collect()
            n_total = int(counts["__n_total__"][0])
            n_unique = int(counts["__n_unique__"][0])
            if n_unique < n_total:
                warnings.warn(
                    f"Rows are not unique by {available}: "
                    f"{n_total} rows but only {n_unique} unique combinations. "
                    f"{target} values may be arbitrary for tied rows.",
                    stacklevel=2,
                )

        seq_expr = (pl.int_range(pl.len()).over(grps) + start_at).cast(pl.Int64).alias(target)
        from fleet.core.lineage import append_verb_node

        params = {"target": target, "order_by": order_by, "by": by}
        if start_at != 1:
            params["start_at"] = start_at
        return append_verb_node(
            self._with_lazy(lf.with_columns(seq_expr)),
            target,
            "seq",
            [*grps, *(order_by or [])],
            params,
        )

    # ------------------------------------------------------------------ #
    # validate                                                             #
    # ------------------------------------------------------------------ #

    @property
    def last_validation(self) -> ValidationResult | None:
        """The most recent ``ValidationResult`` produced by ``validate()``.

        ``None`` when ``validate()`` has not run on this chain.  Use it
        to gate CI on validation outcomes without breaking the fluent
        chain::

            ns = df.sdtm.assign("DOMAIN", value="DM").validate("DM")
            assert ns.last_validation is not None
            assert ns.last_validation.is_valid
        """
        return getattr(self, "_last_validation", None)

    def validate(
        self,
        dataset_or_domain: str,
        version: str | None = None,
        rules_engine_path: Path | None = None,
        custom_rules: str | Path | None = None,
        report: Literal["smart", "summary", "full"] = "smart",
        on_fail: Literal["warn", "raise", "ignore"] = "warn",
    ) -> Self:
        """Run CDISC conformance validation and report the findings.

        Returns a namespace copy so the chain can continue after
        validation; the full :class:`~fleet.validation.models.ValidationResult`
        is retrievable via the :attr:`last_validation` property.  The
        report is emitted through the ``"fleet.validation"`` logger
        (stdout by default — see :mod:`fleet.core.log`).

        Every input comes from a run setup
        (:func:`fleet.validation.run_setup.build_run_setup`): an explicit
        argument, then the study config found from the working directory,
        then ``FLEET_RULES_ENGINE`` (engine only), then the built-in
        default (SDTMIG 3.4, ADaMIG 1.3).  The namespace gives the
        standard.  The report header prints each input with its source.

        Issues are cross-linked to the chain's own variable lineage, so a
        finding on a column this pipeline derived also reports the verb
        that produced it (see
        :func:`fleet.validation.lineage_join.enrich_with_lineage`).

        Args:
            dataset_or_domain: Domain code (SDTM: e.g. ``"DM"``) or
                dataset name (ADaM: e.g. ``"ADSL"``).
            version: IG version, ``"3-4"`` or ``"3.4"``.  Defaults to
                ``sdtm.ig_version`` / ``adam.ig_version`` in the study
                config, else the built-in default.
            rules_engine_path: Engine executable.  Defaults to
                ``validation.engine_path``, then ``FLEET_RULES_ENGINE``,
                then the managed install.
            custom_rules: Directory of custom rule YAML files, passed to
                the engine via ``-lr``.  Defaults to
                ``validation.custom_rules``.
            report: Report detail level — ``"smart"`` (default) for a
                deduplicated view grouping identical findings with row
                ranges, ``"summary"`` for one line per issue, ``"full"``
                for every individual finding expanded.
            on_fail: What to do when a finding blocks (every CORE finding
                that ``validation.accepted`` in the study config does not
                list, ADR-0017) — ``"warn"`` (default) emits a
                ``UserWarning`` and continues, ``"raise"`` raises
                :class:`~fleet.core.exceptions.ValidationError`,
                ``"ignore"`` continues silently.

        Returns:
            Self: A namespace copy carrying the result in
                ``last_validation`` (for continued chaining).

        Raises:
            ValidationSetupError: The validation could not run, in every
                *on_fail* mode: the dataset name belongs to the other
                standard (``adae.adam.validate("AE")``), the IG version is
                not supported, the custom rules directory is missing, or
                the engine crashed, timed out (``validation.timeout``) or
                wrote no report.
            ValidationError: When a finding blocks and
                ``on_fail="raise"``.
            DerivationError: On an invalid *on_fail* value.

        Examples:
            Validate an SDTM domain::

                dm = (
                    raw_df.sdtm
                    .assign("DOMAIN", value="DM")
                    .validate("DM")
                    .to_frame()
                )

            Gate a CI pipeline on the ADaM validation outcome::

                adsl = (
                    dm_df.adam.adsl
                    .validate("ADSL", on_fail="raise")
                    .to_frame()
                )
        """
        from fleet.core.lineage import latest_lineage_of
        from fleet.validation.lineage_join import enrich_with_lineage
        from fleet.validation.run_setup import build_run_setup
        from fleet.validation.service import ValidationService

        _check_on_fail("validate", on_fail)
        setup = build_run_setup(
            name=dataset_or_domain,
            namespace=self._VALIDATE_STANDARD,
            version=version,
            custom_rules=custom_rules,
            engine=rules_engine_path,
        )
        svc = ValidationService(rules_engine_path=setup.engine.value)

        if setup.standard.value == "adam":
            result = svc.validate_adam(
                self.to_frame(),
                dataset=dataset_or_domain,
                version=setup.ig_version.value,
                custom_rules=setup.custom_rules.value,
                timeout=setup.timeout.value,
            )
        else:
            result = svc.validate_sdtm(
                self.to_frame(),
                domain=dataset_or_domain,
                version=setup.ig_version.value,
                custom_rules=setup.custom_rules.value,
                timeout=setup.timeout.value,
            )

        result.apply_setup(setup)
        enrich_with_lineage(result, latest_lineage_of(self))
        result.print_report(report_type=report)
        if result.could_not_run is not None:
            raise ValidationSetupError(
                f"CDISC validation of '{dataset_or_domain}' could not run: {result.could_not_run}"
            )

        new = copy.copy(self)
        new._last_validation = result
        if not result.is_valid:
            summary = (
                f"CDISC validation failed for '{dataset_or_domain}': "
                f"{len(result.errors)} error(s): findings that validation.accepted "
                "does not list. Access details via .last_validation."
            )
            _settle_on_fail(on_fail, summary, ValidationError)
        return new

    # ------------------------------------------------------------------ #
    # compare                                                              #
    # ------------------------------------------------------------------ #

    @property
    def last_comparison(self) -> ComparisonReport | None:
        """The most recent comparison report produced by ``compare()``.

        ``None`` when ``compare()`` has not run on this chain.  Use it to
        gate a script on the comparison outcome without breaking the
        fluent chain::

            ns = qc_df.adam.source("USUBJID").compare(adsl_prod, keys="USUBJID")
            assert ns.last_comparison is not None
            assert ns.last_comparison.is_equal, ns.last_comparison.raised_flags
        """
        return getattr(self, "_last_comparison", None)

    def compare(
        self,
        base: pl.DataFrame | pl.LazyFrame,
        *,
        keys: str | Sequence[str],
        by: str | Sequence[str] | None = None,
        pairs: Mapping[str, str] | None = None,
        variables: str | Sequence[str] | None = None,
        abs_tol: float = 0.0,
        rel_tol: float = 0.0,
        ignore_trailing_whitespace: bool = False,
        blank_is_missing: bool = False,
        allow_duplicates: bool = False,
        max_print: MaxPrint = 50,
        base_name: str | None = None,
        candidate_name: str | None = None,
        on_fail: Literal["warn", "raise", "ignore"] = "warn",
    ) -> Self:
        """Compare the chain against a base dataset, PROC COMPARE style.

        The chain is the **candidate** and *base* is the reference it is
        measured against.  The chain is materialised, paired with the base
        on *keys* through :func:`fleet.compare`, and the report is printed
        through the ``"fleet.comparison"`` logger (stdout by default — see
        :mod:`fleet.core.log`).  Differences never stop the chain by
        default: the verb returns a namespace copy carrying the
        :class:`~fleet.comparison.ComparisonReport` as
        :attr:`last_comparison`, so the pipeline continues.

        Args:
            base: The reference dataset, as a DataFrame or LazyFrame.
            keys: Variable(s) that identify one observation on each side.
                Required; the compare refuses to run when a key is missing
                or not unique on either side.
            by: Variable(s) the report is sectioned by.  They are prepended
                to *keys* automatically, label the listing's ``group``
                column, and give the observation and values summaries a
                per-group breakdown.  A group present on one side only
                raises a flag; the verdict stays global.
            pairs: Base variable names mapped to the names the chain gives
                them, on top of the automatic name matching, so a renamed
                column is compared rather than reported missing.  The report
                names a paired variable by its **base** name.
            variables: Restrict the comparison to these variables, in
                **base** names, so a work-in-progress chain is checked on
                the columns that are finished.  What is outside the
                restriction is neither compared nor reported as missing.
            abs_tol: Absolute tolerance on the numeric variables; ``0.0``
                (the default) is exact.
            rel_tol: Relative tolerance on the numeric variables, as a
                fraction of the **base** value; ``0.0`` (the default) is
                exact.  A numeric pair differs when the absolute difference
                exceeds ``max(abs_tol, rel_tol * abs(base))``.
            ignore_trailing_whitespace: Strip trailing whitespace from both
                sides of a string before comparing, so a legacy SAS dataset's
                padded values equal the chain's stripped ones.  Leading
                whitespace still differs.
            blank_is_missing: Read an empty string as null on both sides,
                keys included, as SAS does.  Off by default.
            allow_duplicates: Pair duplicate keys by their position within
                each key group instead of refusing to run; the report then
                counts them, raises ``duplicate_keys`` and warns.
            max_print: Print limits for the text report (differences per
                variable, a ``(per_variable, total)`` pair, or ``None`` for
                everything).  The report's listing is never truncated.
            base_name: Label for the base in the report, when known.
            candidate_name: Label for the chain in the report, when known.
            on_fail: What to do when the datasets differ — ``"warn"``
                (default) emits a ``UserWarning`` and continues,
                ``"raise"`` raises
                :class:`~fleet.core.exceptions.ComparisonError`,
                ``"ignore"`` continues silently.

        Returns:
            Self: A namespace copy carrying the report in
                ``last_comparison`` (for continued chaining).

        Raises:
            ComparisonError: When the datasets differ and
                ``on_fail="raise"``, or when the comparison cannot run
                (a key missing, duplicated or of an incompatible type).
            DerivationError: On an invalid *on_fail* value.

        Examples:
            Prove an independently programmed ADAE matches its base, and
            keep chaining::

                adae_qc = (
                    ae_df.adam.occds
                    .source("USUBJID")
                    .source("AESEQ")
                    .compare(adae_prod, keys=["USUBJID", "AESEQ"])
                    .to_frame()
                )

            Gate a CI script on the comparison outcome::

                adsl = (
                    dm_df.adam.adsl
                    .source("USUBJID")
                    .compare(adsl_prod, keys="USUBJID", on_fail="raise")
                    .to_frame()
                )

            Absorb the engine noise of a legacy SAS dataset without hiding
            a real difference::

                advs = (
                    vs_df.adam
                    .source("USUBJID")
                    .compare(
                        advs_legacy,
                        keys=["USUBJID", "PARAMCD", "AVISITN"],
                        rel_tol=1e-9,
                        ignore_trailing_whitespace=True,
                    )
                    .to_frame()
                )

            Section the comparison by treatment arm, so a difference in one
            arm stands out::

                adsl = (
                    dm_df.adam.adsl
                    .source("USUBJID")
                    .compare(adsl_prod, keys="USUBJID", by="TRT01P")
                    .to_frame()
                )

            Check a work-in-progress chain on the variables that are
            finished, one of which the base names differently::

                advs = (
                    vs_df.adam
                    .source("USUBJID")
                    .compare(
                        advs_prod,
                        keys=["USUBJID", "PARAMCD"],
                        pairs={"AVAL": "RESULT"},
                        variables=["AVAL", "AVISIT"],
                    )
                    .to_frame()
                )
        """
        from fleet.comparison import compare as compare_frames

        _check_on_fail("compare", on_fail)
        report = compare_frames(
            base,
            self.to_frame(),
            keys=keys,
            by=by,
            pairs=pairs,
            variables=variables,
            abs_tol=abs_tol,
            rel_tol=rel_tol,
            ignore_trailing_whitespace=ignore_trailing_whitespace,
            blank_is_missing=blank_is_missing,
            allow_duplicates=allow_duplicates,
            max_print=max_print,
            base_name=base_name,
            candidate_name=candidate_name,
        )
        report.print_report()

        new = copy.copy(self)
        new._last_comparison = report
        if not report.is_equal:
            summary = f"{report.summary}. Access details via .last_comparison."
            _settle_on_fail(on_fail, summary, ComparisonError)
        return new

    # ------------------------------------------------------------------ #
    # select                                                               #
    # ------------------------------------------------------------------ #

    def select(
        self,
        columns: str | list[str] | None = None,
        *,
        spec: str | Path | None = None,
        dataset: str | None = None,
        drop_pattern: str | None = r"^_",
    ) -> Self:
        """Select and reorder columns (lazily — nothing is materialised).

        Resolution order:

        1. ``spec`` + ``dataset``: derive the ordered column list from a
           ``define.yaml``.  Only columns present in the frame are kept.
        2. ``columns``: explicit list to keep (in that order).
        3. Neither: keep all current columns (subject to ``drop_pattern``).

        With a spec on an ADaM namespace, a text column the define types
        ``date`` becomes the date part of a complete date, and one typed
        ``datetime`` the date-time of a value with hours and minutes.
        Anything else becomes null, with one warning at collect: select
        never imputes.  SDTM columns and every ``*DTC`` stay text, because
        ``--DTC`` is character (SDTMIG 3.4 section 4.4).

        ``drop_pattern`` (default ``r"^_"``): regex applied *before* the
        explicit selection — columns whose names match are removed.  This
        enforces the convention that ``_``-prefixed columns are scratch
        variables.  Set to ``None`` to disable (e.g. during debugging).
        A scratch name listed in *columns* is removed too, unless
        ``drop_pattern=None``.

        Args:
            columns: Explicit list of columns to keep (in order).  A single
                string is one column name.
            spec: Path to a ``define.yaml`` file.
            dataset: Dataset name within the spec.
            drop_pattern: Regex for columns to auto-drop.

        Returns:
            Self: A fresh namespace continuing from the selected plan.

        Raises:
            DerivationError: When a name in *columns* is not in the frame
                (with a did-you-mean suggestion).

        Examples:
            Keep only spec columns::

                dm = (
                    raw_df.sdtm
                    .select(spec="specs/sdtm/define.yaml", dataset="DM")
                    .to_frame()
                )
        """
        schema = self._lazy.collect_schema()
        names = schema.names()

        if spec is None and columns is not None:
            columns = [columns] if isinstance(columns, str) else list(columns)
            require_columns("select(columns=...)", columns, names, where="the frame")

        # Step 1: drop scratch variables matching the pattern
        if drop_pattern is not None:
            pat = re.compile(drop_pattern)
            names = [c for c in names if not pat.search(c)]

        # Step 2: resolve explicit column list (spec takes priority over columns)
        col_list = columns
        type_map: dict[str, str] = {}
        if spec is not None:
            spec_path = Path(spec)
            col_list, type_map = self._spec_dataset_meta(spec_path, dataset)

        # Step 3: intersect with existing columns (preserving spec order)
        final_cols = names
        if col_list is not None:
            final_cols = [c for c in col_list if c in names]
            if spec is not None:
                missing = [c for c in col_list if c not in names]
                if missing:
                    warnings.warn(
                        f"select(spec=...): {len(missing)} spec-declared column(s) "
                        f"are absent from the frame and were skipped: {missing}",
                        stacklevel=2,
                    )
                computed = {node.name for node in getattr(self, "_lineage", [])}
                dropped = [c for c in names if c not in col_list and c in computed]
                if dropped:
                    warnings.warn(
                        f"select(spec=...): dropping computed column(s) that are "
                        f"not declared in the spec: {dropped}",
                        stacklevel=2,
                    )

        lf = self._lazy.select(final_cols)

        # Step 4: ADaM *DT and *DTM declared date/datetime are read from text.
        # SDTM and any *DTC stay text (SDTMIG 3.4 4.4); select never imputes.
        if type_map and self._VALIDATE_STANDARD == "adam":
            casts = []
            for col_name, spec_type in type_map.items():
                if col_name not in final_cols or col_name.upper().endswith("DTC"):
                    continue
                dtype = schema.get(col_name)
                raw = pl.col(col_name)
                if spec_type == "date" and isinstance(dtype, pl.Datetime):
                    casts.append(raw.cast(pl.Date))
                    continue
                if dtype != pl.String:
                    continue
                read = date_part(raw) if spec_type == "date" else datetime_part(raw)
                casts.append(
                    warn_on_collect(
                        read,
                        (raw.str.strip_chars().fill_null("") != "") & read.is_null(),
                        lambda n, values, c=col_name, t=spec_type: (
                            f"select(spec=): {n} value(s) of {c} are not a complete {t} and "
                            "become null; select never imputes, so use .date(impute=) for a "
                            f"SAP rule. Values: {values}"
                        ),
                        dtype=pl.Date if spec_type == "date" else pl.Datetime("us"),
                        shown=raw,
                    ).alias(col_name)
                )
            if casts:
                lf = lf.with_columns(casts)

        return self._with_lazy(lf)

    @staticmethod
    def _spec_dataset_meta(
        spec_path: Path, dataset: str | None
    ) -> tuple[list[str], dict[str, str]]:
        """Return ``(column_names, date_type_map)`` for *dataset* from a define.yaml."""
        ds = load_define_spec(spec_path).select(dataset)
        columns = [v.name for v in ds.variables]
        type_map = {v.name: v.type for v in ds.variables if v.type in ("date", "datetime")}
        return columns, type_map

    # ------------------------------------------------------------------ #
    # from_spec — registry-driven spec execution                           #
    # ------------------------------------------------------------------ #

    def from_spec(
        self,
        spec_path: str | Path,
        *,
        dataset: str | None = None,
        only: list[str] | None = None,
        omit: list[str] | None = None,
        strict: bool = True,
        overwrite: bool = False,
    ) -> Self:
        """Build a derivation pipeline from a YAML specification file.

        Reads either a ``define.yaml`` (top-level ``datasets`` list where
        each variable carries a ``derivation`` block) or a simplified
        single-dataset spec (top-level ``variables`` list).  Every
        ``algorithm:`` is resolved through the central spec registry
        (:mod:`fleet.core.spec_registry`), validated against its strict
        per-algorithm model, and executed via the matching namespace verb.

        A top-level ``ct:`` block opts the spec into controlled-terminology
        validation::

            ct:
              validate: true
              file: ct/cdisc_ct.yaml   # optional — loaded into the CT cache

        With ``validate: true`` every ``assign`` that has a codelist
        (``ct:``, or the variable's ``codelist:``) runs with
        ``validate_values=True``: out-of-codelist values emit the
        standard warning naming dataset, variable, and codelist.

        A derivation block is the verb call: ``algorithm:`` is the verb
        name and the keys are its keyword arguments (ADR-0008).  An
        ``assign`` without ``ct:`` on a variable with ``codelist:`` checks
        its values against that codelist.

        Inside a study, a ``ct:`` ID resolves to the class of
        that ID in the study's generated ``codelists.py`` (found from the
        first ``study_config.yaml`` above the spec's folder), so a spec
        step checks the same terms as ``assign(..., ct=<class>)``; an ID
        the file lacks falls back to the CT loaded in
        :func:`fleet.get_validator`.  A ``codelists.py`` that disagrees
        with the study warns once per process (see
        :mod:`fleet.ct.study_codelists`).

        Args:
            spec_path: Path to the YAML specification file.
            dataset: Dataset to execute from a multi-dataset define.yaml
                (e.g. ``dataset="DM"``).  May be omitted when the file
                contains a single dataset.
            only: Optional allow-list — process only these variable names.
            omit: Optional deny-list — skip these variable names; useful to
                override a spec variable with custom inline logic.
                Mutually exclusive with *only*.
            strict: When ``True`` (default) an unknown ``algorithm:`` raises
                :class:`~fleet.core.exceptions.SpecError`.  Pass ``False``
                to restore the legacy warn-and-skip behaviour.
            overwrite: When ``True``, allow spec variables to overwrite
                columns that already exist in the frame.  By default an
                overwrite raises ``SpecError`` unless the derivation is a
                declared carry-through (its source column *is* the target).

        Returns:
            Self: A namespace pre-loaded with all spec-driven derivations;
                call ``.to_frame()`` to materialise.

        Raises:
            SpecError: On unknown algorithms (strict mode), invalid or
                misspelled derivation fields, column overwrites, unknown
                ``fleet_spec_version``, a ``merge`` block that does not
                give its variable, or any error raised while executing
                a variable — always naming file, dataset, and variable.
            ValueError: When both *only* and *omit* are given, or when
                *dataset* is required/unknown.

        Examples:
            Build and materialise the DM domain from a spec::

                dm = (
                    raw_df.sdtm
                    .from_spec("examples/cdiscpilot01/sdtm/define.yaml", dataset="DM")
                    .to_frame()
                )

            Keep an inline derivation for one variable::

                adsl = (
                    dm_df.adam
                    .from_spec("define.yaml", dataset="ADSL", omit=["TRTSDT"])
                    .to_frame()
                )
        """
        from fleet.core import spec_registry

        if only is not None and omit is not None:
            raise DerivationError(
                "Cannot specify both only= and omit= in from_spec(). "
                "Use only= to allow-list variables, or omit= to deny-list them."
            )

        path = Path(spec_path)
        spec = load_define_spec(path)
        _check_spec_version(spec, source=str(path))
        _import_derivations_module(spec, source=str(path))

        standard = self._VALIDATE_STANDARD
        ds_name, raw_vars = _extract_spec_variables(spec, dataset)

        ns = self

        # Spec-level CT config: `ct: {validate: true, file: <path>}`.
        if spec.ct.enabled:
            ct_file = spec.ct.file
            if ct_file:
                from fleet.ct.validator import get_validator

                ct_path = Path(ct_file)
                if not ct_path.is_absolute():
                    ct_path = path.parent / ct_path
                try:
                    get_validator().load_ct_file(ct_path)
                except Exception as err:
                    raise SpecError(
                        f"{path}: ct.file '{ct_file}' could not be loaded: {err}"
                    ) from err
            ns = copy.copy(ns)
            ns._spec_ct_validate = True
        elif "enabled" in spec.ct.model_fields_set:
            # An explicit `ct: {validate: false}` switches the default CT check off.
            ns = copy.copy(ns)
            ns._spec_ct_validate = False

        # ct: IDs resolve to the study's codelists.py classes, as ct=<class> inline.
        if any(drv.get("ct") or codelist for _, drv, codelist in raw_vars):
            from fleet.ct.study_codelists import spec_codelists

            codelists = spec_codelists(path)
            if codelists:
                ns = copy.copy(ns)
                ns._spec_codelists = codelists
        # Row steps run after the variable they are anchored on (ADR-0034).
        all_names: list[str] = []
        row_steps: list[dict[str, Any]] = []
        if spec.datasets is not None:
            ds_entry = spec.select(dataset)
            all_names = [v.name for v in ds_entry.variables]
            row_steps = list(ds_entry.row_steps)
            _check_row_steps(row_steps, all_names, f"{path} → dataset {ds_name}")
        position = {n: i for i, n in enumerate(all_names)}

        def _flush(ns: Any, before: int) -> Any:
            while row_steps and position.get(row_steps[0].get("after"), -1) < before:
                ns = _run_row_step(ns, row_steps.pop(0), f"{path} → dataset {ds_name}")
            return ns

        for var_name, drv, codelist in raw_vars:
            ns = _flush(ns, position.get(var_name, len(all_names)))
            if only is not None and var_name not in only:
                continue
            if omit is not None and var_name in omit:
                continue

            context = f"{path} → dataset {ds_name} → variable {var_name}"
            alg = drv.get("algorithm")
            algo = spec_registry.get_algorithm(standard, str(alg)) if alg else None
            if algo is None:
                from fleet.tools.migrate_spec import ALGORITHM_RENAMES

                if str(alg) in ALGORITHM_RENAMES:
                    suffix = (
                        f" '{alg}' is the pre-ADR-0008 spelling of '{ALGORITHM_RENAMES[str(alg)]}';"
                        " rewrite the file with `fleet migrate --spec <define.yaml> --write`."
                    )
                else:
                    hint = spec_registry.suggest_algorithm(standard, str(alg))
                    suffix = f" Did you mean '{hint}'?" if hint else ""
                if strict:
                    raise SpecError(
                        f"{context}: unknown algorithm '{alg}' for the {standard} "
                        f"spec path.{suffix} Pass strict=False to warn and skip instead."
                    )
                warnings.warn(
                    f"from_spec: skipping variable '{var_name}' — "
                    f"algorithm '{alg}' is not supported in spec-driven mode.{suffix}",
                    stacklevel=2,
                )
                continue

            try:
                drv = spec_registry.with_codelist(standard, drv, codelist)
                model = spec_registry.model_for(standard, algo.name)
                var = model.model_validate({**drv, "target": var_name})
            except Exception as err:
                raise SpecError(f"{context}: {err}") from err

            columns = ns._lazy.collect_schema().names()

            # Auto-flush when a declared dependency is not yet committed.
            deps = getattr(var, "depends_on", None) or []
            if deps and any(d not in columns for d in deps):
                ns = ns._materialise_then(ns.to_frame())
                columns = ns._lazy.collect_schema().names()

            if (
                algo.takes_target
                and algo.overwrite_guard
                and not overwrite
                and var.target in columns
                and not spec_registry.is_identity_copy(var)
            ):
                raise SpecError(
                    f"{context}: would overwrite the existing column "
                    f"'{var.target}'. Pass overwrite=True to allow spec "
                    f"overwrites, or omit=[{var.target!r}] to keep the "
                    f"inline derivation."
                )

            try:
                ns = spec_registry.execute_variable(ns, var)
            except SpecError:
                raise
            except Exception as err:
                raise SpecError(f"{context}: {type(err).__name__}: {err}") from err
            if algo.name == "merge" and var_name not in ns._lazy.collect_schema().names():
                raise SpecError(
                    f"{context}: the merge block does not give the column '{var_name}'. "
                    f"Add it to keep:, or check that dataset '{drv.get('dataset')}' has it."
                )

        ns = _flush(ns, len(all_names) + 1)
        if spec.datasets is not None:
            ns = copy.copy(ns)
            ns._spec_source = (spec, ds_name)
        return ns

    # ------------------------------------------------------------------ #
    # to_spec_yaml — round-trip: pipeline lineage → define.yaml            #
    # ------------------------------------------------------------------ #

    def to_spec_yaml(
        self,
        dataset: str | None = None,
        path: str | Path | None = None,
        *,
        predecessor: str | None = None,
    ) -> str:
        """Serialise the pipeline's lineage into a define.yaml spec.

        The natural prototype-then-freeze workflow: build the dataset
        inline, then emit the equivalent ``derivation:`` blocks instead
        of retyping them.  Variables are emitted in frame column order:
        derived variables carry their ``derivation:`` block (last
        derivation wins when a target was re-derived); CDISC-named
        carry-through columns are listed as metadata-only entries; raw
        columns that violate the CDISC name pattern are skipped.  Verbs
        covered by the spec registry emit real blocks; verbs that are
        not spec-expressible (or whose arguments cannot be serialised,
        e.g. inline Polars expressions) emit an ``algorithm: derivation``
        stub with a ``callable:`` placeholder and a ``# TODO`` comment carrying the verb name and
        sources, and a warning names them.  A column that a verb added
        with no lineage node (``merge``) also gets a stub.  Auto-generated
        by-product columns (e.g. ``--DTF`` imputation flags) are listed
        without a derivation.

        A verb that removes or adds rows (``whereclauses``, ``nodup`` with
        ``keep=``, ``derive_param``) goes to the dataset key
        ``row_steps:``, in pipeline order, each step anchored ``after:``
        the variable it follows (ADR-0034).  A step a define.yaml cannot
        hold is written as ``algorithm: TODO`` and ``from_spec`` refuses
        it until it is edited.

        The output validates against Fleet's define-spec JSON schema;
        study-level fields are placeholders to review before use.

        Args:
            dataset: Dataset name for the emitted spec.  Defaults to the
                pipeline's domain context (set by ``assign("DOMAIN",
                ...)``) or ``"DATASET"``.
            path: Optional file path — when given, the YAML is also
                written there (parent directories are created).
            predecessor: Name of the upstream dataset this ADaM pipeline
                was built from (e.g. ``"DM"``).  When given, variables
                carried through unchanged — metadata-only entries and
                pure ``algorithm: assign`` copies of CDISC-named columns
                — are emitted with ``origin: Predecessor`` and
                ``predecessor: '<DATASET>.<SOURCE>'``.  The emitted YAML
                stays the explicit, reviewable source of truth; Fleet
                never infers Predecessor at Define-XML generation time.
                Only a column present at the start of the chain can be a
                Predecessor: a column a verb added with no lineage (for
                example ``merge()``) gets a TODO stub and the warning.
                ADaM pipelines only.

        Returns:
            str: The define.yaml document.

        Examples:
            Freeze an inline DM prototype to a spec::

                ns = (
                    raw_df.sdtm
                    .assign("DOMAIN", value="DM")
                    .assign("USUBJID", source="subject_id")
                )
                yaml_text = ns.to_spec_yaml(dataset="DM", path="specs/define_dm.yaml")
                dm = raw_df.sdtm.from_spec("specs/define_dm.yaml", dataset="DM").to_frame()

            Freeze an ADSL prototype, labelling DM carry-throughs::

                adsl_ns.to_spec_yaml(dataset="ADSL", predecessor="DM")
        """
        from fleet.core import spec_registry
        from fleet.core.lineage import latest_lineage_of
        from fleet.validation.run_setup import DEFAULT_IG_VERSIONS

        standard = self._VALIDATE_STANDARD
        ds_name = (dataset or getattr(self, "_domain", None) or "DATASET").upper()

        pred_ds = predecessor.upper() if predecessor else None
        if pred_ds:
            if standard != "adam":
                raise DerivationError(
                    "to_spec_yaml(predecessor=...) applies to ADaM pipelines only — "
                    "SDTM variables built from raw data are Collected/Derived, not "
                    "Predecessor."
                )
            if not re.match(r"^[A-Z_][A-Z0-9_]{0,7}$", pred_ds):
                raise DerivationError(
                    f"to_spec_yaml(): predecessor {predecessor!r} is not a valid "
                    "dataset name (expected e.g. 'DM' or 'ADSL')."
                )

        schema = self._lazy.collect_schema()
        derived = {n.name: n for n in latest_lineage_of(self)}
        name_pattern = re.compile(r"^[A-Z_][A-Z0-9_]{0,7}$")
        # The columns at the start of the chain: only they can be a carry-through
        # or a Predecessor; a column a verb added with no lineage node is a stub.
        root_lazy = getattr(self, "_root_lazy", None)
        root_cols = set(root_lazy.collect_schema().names()) if root_lazy is not None else None

        entries: list[tuple[dict[str, Any], str | None]] = []
        for col in schema.names():
            node = derived.get(col)
            if node is None and not name_pattern.match(col):
                continue  # raw scratch column — not part of the dataset spec
            entry: dict[str, Any] = {
                "name": col,
                "label": col,
                "type": _dtype_to_spec_type(schema.get(col)),
            }
            comment: str | None = None
            if node is None and root_cols is not None and col not in root_cols:
                comment = (
                    f"TODO: column {col} was added by a verb that records no lineage "
                    "(for example merge) — replace this stub with a registered "
                    "derivation (algorithm: derivation, callable: <name>)."
                )
                entry["derivation"] = {"algorithm": "derivation", "callable": f"TODO_{col}"}
            elif node is not None:
                status, block, meta = spec_registry.derivation_from_lineage(standard, node)
                if meta.get("label"):
                    entry["label"] = str(meta["label"])[:40]
                if meta.get("origin"):
                    entry["origin"] = meta["origin"]
                if status == "ok":
                    # A pure copy of a CDISC-named upstream column is a
                    # Predecessor in Define-XML terms; an explicit origin
                    # captured from the verb call wins.
                    source = str(block.get("source") or col) if block else col
                    if (
                        pred_ds
                        and "origin" not in entry
                        and block
                        and block.get("algorithm") == "assign"
                        and block.get("value") is None
                        and not block.get("ct")
                        and name_pattern.match(source)
                        and (root_cols is None or source in root_cols)
                    ):
                        entry["origin"] = "Predecessor"
                        entry["predecessor"] = f"{pred_ds}.{source}"
                    entry["derivation"] = block
                elif status == "stub":
                    srcs = ", ".join(node.sources) if node.sources else "none"
                    comment = (
                        f"TODO: verb '{node.verb}' (sources: {srcs}) is not spec-expressible "
                        f"— replace this stub with a registered derivation "
                        f"(algorithm: derivation, callable: <name>)."
                    )
                    entry["derivation"] = {
                        "algorithm": "derivation",
                        "callable": f"TODO_{col}",
                    }
                # status == "byproduct": metadata-only (auto-generated column).
            elif pred_ds:
                # Metadata-only carry-through — flowed in untouched.
                entry["origin"] = "Predecessor"
                entry["predecessor"] = f"{pred_ds}.{col}"
            entries.append((entry, comment))

        if not entries:
            raise DerivationError(
                "to_spec_yaml(): nothing to serialise — the frame has no derived "
                "variables and no CDISC-named columns."
            )

        stubs = [entry["name"] for entry, comment in entries if comment]
        if stubs:
            warnings.warn(
                f"to_spec_yaml: {len(stubs)} variable(s) are TODO stubs "
                f"({', '.join(stubs)}): from_spec fails on them until you replace each "
                "callable: TODO_<name> with a registered @derivation, and Define-XML has "
                "no method text for them.",
                stacklevel=2,
            )

        var_names = [e["name"] for e, _ in entries]
        keys = [k for k in ("STUDYID", "USUBJID") if k in var_names] or var_names[:1]
        row_steps = _freeze_row_steps(self, var_names)
        todo_steps = [st["verb"] for st in row_steps if st["algorithm"] == "TODO"]
        if todo_steps:
            warnings.warn(
                f"to_spec_yaml: {len(todo_steps)} row step(s) cannot be written "
                f"({', '.join(todo_steps)}): from_spec fails on algorithm: TODO in "
                "row_steps until you replace each one (ADR-0034).",
                stacklevel=2,
            )

        study = {
            "id": "STUDY",
            "name": "STUDY",
            "description": (
                "Generated by Fleet to_spec_yaml() — replace with the study description."
            ),
            "protocol_name": "STUDY",
            "originator": "Fleet",
            "standard": "SDTMIG" if standard == "sdtm" else "ADAMIG",
            "standard_version": DEFAULT_IG_VERSIONS[standard],
        }
        head = {"fleet_spec_version": SUPPORTED_SPEC_VERSION, "study": study}
        ds_head: dict[str, Any] = {
            "name": ds_name,
            "label": ds_name,
            "structure": "One record per observation (review)",
            "keys": keys,
        }
        if row_steps:
            ds_head["row_steps"] = row_steps

        lines: list[str] = [
            "# Generated by Fleet to_spec_yaml() — review study fields, labels, keys,",
            "# and TODO stubs before use.",
        ]
        if todo_steps:
            lines.append(
                "# TODO: row_steps holds algorithm: TODO for "
                f"{', '.join(todo_steps)} — write each step before from_spec runs."
            )
        lines += [
            yaml.safe_dump(head, sort_keys=False, allow_unicode=True).rstrip(),
            "datasets:",
            _indent_yaml(yaml.safe_dump([ds_head], sort_keys=False, allow_unicode=True), 2),
            "    variables:",
        ]
        for entry, comment in entries:
            block_text = _indent_yaml(
                yaml.safe_dump([entry], sort_keys=False, allow_unicode=True), 6
            )
            if comment:
                block_lines: list[str] = []
                for ln in block_text.splitlines():
                    if ln.strip().startswith("derivation:"):
                        pad = ln[: len(ln) - len(ln.lstrip())]
                        block_lines.append(f"{pad}# {comment}")
                    block_lines.append(ln)
                block_text = "\n".join(block_lines)
            lines.append(block_text)

        text = "\n".join(lines) + "\n"
        if path is not None:
            dest = Path(path)
            dest.parent.mkdir(parents=True, exist_ok=True)
            dest.write_text(text, encoding="utf-8")
        return text

    # ------------------------------------------------------------------ #
    # nodup — detect and optionally remove duplicates                      #
    # ------------------------------------------------------------------ #

    @property
    def last_nodup_report(self) -> pl.DataFrame | None:
        """Duplicate rows found by the most recent ``nodup()`` call.

        A ``pl.DataFrame`` containing every row that participated in a
        duplicate key group (empty frame when no duplicates were found),
        or ``None`` when ``nodup()`` has not run on this chain.  Makes
        report-only audits programmatically reachable::

            ns = df.sdtm.nodup(subset=["USUBJID", "AESEQ"])
            dups = ns.last_nodup_report
            assert dups is not None and dups.height == 0
        """
        return getattr(self, "_nodup_report", None)

    def nodup(
        self,
        *,
        subset: list[str],
        sort_by: list[str] | None = None,
        keep: Literal["first", "last"] | None = None,
        descending: bool | list[bool] = False,
    ) -> Self:
        """Detect duplicate rows and optionally deduplicate after sorting.

        Materialises the pipeline, logs duplicate diagnostics through the
        ``"fleet"`` logger (stdout by default — see :mod:`fleet.core.log`),
        and optionally removes duplicates.  When ``keep`` is ``None``
        (default) the verb operates in report-only mode — duplicates are
        reported but the frame is returned unchanged, making it safe to
        insert anywhere in a pipeline for auditing purposes.  The
        duplicate rows are also attached to the returned namespace and
        retrievable via :attr:`last_nodup_report`.

        Args:
            subset: Column(s) that define the uniqueness key.
            sort_by: Column(s) to sort by before deduplication.  Required
                when ``keep`` is not ``None``.
            keep: Which duplicate to retain after sorting:
                ``"first"``, ``"last"``, or ``None`` (report only, no removal).
            descending: Sort direction(s) for *sort_by*.  A single ``bool``
                applies to all columns; a list must match *sort_by* length.
                A missing value is the lowest value, as SAS: it sorts
                first when ascending and last when descending.  Records
                that tie on *sort_by* keep their input order, as PROC SORT
                EQUALS, so ``keep="last"`` takes the last input record of a
                tie.

        Returns:
            Self: A fresh namespace wrapping the (optionally deduplicated)
                frame, carrying the duplicates in ``last_nodup_report``;
                call ``.to_frame()`` to materialise.

        Raises:
            DerivationError: If ``keep`` is set but ``sort_by`` is not
                provided, or ``keep`` is not one of the accepted values.

        References:
            SAS PROC SORT with EQUALS and NODUPKEY; ADR-0023 for the place
            of a missing value.

        Examples:
            Report-only mode (audit duplicates without removing)::

                ae = (
                    raw_df.sdtm
                    .assign("USUBJID", source="subject_id")
                    .nodup(subset=["USUBJID", "AEDECOD", "AESTDTC"])
                    .to_frame()
                )

            Sort and deduplicate (keep latest record)::

                adae = (
                    ae_df.adam.occds
                    .nodup(
                        subset=["USUBJID", "AEDECOD"],
                        sort_by=["ASTDT", "ASEQ"],
                        keep="first",
                        descending=True,
                    )
                    .to_frame()
                )
        """
        if keep is not None and sort_by is None:
            raise DerivationError("sort_by is required when keep is set.")
        if keep is not None and keep not in ("first", "last"):
            raise DerivationError(f"keep must be 'first', 'last', or None — got {keep!r}.")

        fleet_log.ensure_default_handler()
        df = self._lazy.collect()

        # Detect duplicates
        dup_mask = df.select(pl.struct(subset).is_duplicated()).to_series()
        n_dup = dup_mask.sum()
        dup_rows = df.filter(dup_mask)

        if n_dup == 0:
            logger.info("[NODUP] No duplicates found (subset: %s)", ", ".join(subset))
            new = self._materialise_then(df)
            new._nodup_report = dup_rows
            return self._record_nodup(new, subset, sort_by, keep, descending)

        # Summarise duplicate groups
        dup_groups = (
            dup_rows.group_by(subset)
            .agg(pl.len().alias("__count"))
            .sort("__count", descending=True)
        )
        n_groups = len(dup_groups)

        logger.info(
            "[NODUP] %d duplicate rows across %d key group(s) (subset: %s)",
            n_dup,
            n_groups,
            ", ".join(subset),
        )
        # Show top offending groups (up to 5)
        top = dup_groups.head(5)
        logger.info("[NODUP] Top offenders:")
        for row in top.iter_rows(named=True):
            count = row.pop("__count")
            key_str = ", ".join(f"{k}={v}" for k, v in row.items())
            logger.info("  %s  (%d rows)", key_str, count)

        # Report-only mode
        if keep is None:
            logger.info("[NODUP] Action: report only (keep=None)")
            new = self._materialise_then(df)
            new._nodup_report = dup_rows
            return new

        # Sort then deduplicate: a missing value is lowest, as SAS (ADR-0023); ties keep input order.
        flags = list(descending) if isinstance(descending, list) else [descending] * len(sort_by)
        df = df.sort(sort_by, descending=flags, nulls_last=flags, maintain_order=True)
        df = df.unique(subset=subset, keep=keep, maintain_order=True)

        logger.info(
            "[NODUP] Action: keeping '%s' after sorting by %s (descending=%s)",
            keep,
            sort_by,
            descending,
        )
        logger.info("[NODUP] Result: %d rows (removed %d)", len(df), n_dup - n_groups)
        new = self._materialise_then(df)
        new._nodup_report = dup_rows
        return self._record_nodup(new, subset, sort_by, keep, descending)

    @staticmethod
    def _record_nodup(
        new: Any,
        subset: list[str],
        sort_by: list[str] | None,
        keep: str | None,
        descending: bool | list[bool],
    ) -> Any:
        """Record a removing ``nodup`` call as a row step (ADR-0034)."""
        if keep is None:
            return new
        from fleet.core.lineage import record_row_step

        params: dict[str, Any] = {"subset": subset, "sort_by": sort_by, "keep": keep}
        if descending:
            params["descending"] = descending
        return record_row_step(new, "nodup", params)

last_validation property

last_validation

The most recent ValidationResult produced by validate().

None when validate() has not run on this chain. Use it to gate CI on validation outcomes without breaking the fluent chain::

ns = df.sdtm.assign("DOMAIN", value="DM").validate("DM")
assert ns.last_validation is not None
assert ns.last_validation.is_valid

last_comparison property

last_comparison

The most recent comparison report produced by compare().

None when compare() has not run on this chain. Use it to gate a script on the comparison outcome without breaking the fluent chain::

ns = qc_df.adam.source("USUBJID").compare(adsl_prod, keys="USUBJID")
assert ns.last_comparison is not None
assert ns.last_comparison.is_equal, ns.last_comparison.raised_flags

last_nodup_report property

last_nodup_report

Duplicate rows found by the most recent nodup() call.

A pl.DataFrame containing every row that participated in a duplicate key group (empty frame when no duplicates were found), or None when nodup() has not run on this chain. Makes report-only audits programmatically reachable::

ns = df.sdtm.nodup(subset=["USUBJID", "AESEQ"])
dups = ns.last_nodup_report
assert dups is not None and dups.height == 0

to_frame

to_frame()

Materialise the accumulated pipeline into a Polars DataFrame.

Returns:

Name Type Description
DataFrame DataFrame

The fully materialised result of all chained verbs — a plain pl.DataFrame at runtime, typed as :class:fleet.DataFrame so re-entering .sdtm / .adam / .tlg type-checks.

Raises:

Type Description
DerivationError

When collection fails because a column is missing — enriched with the lineage entries that reference the column, so the error names the verb(s) involved. Also when a merge(validate=...) fails, with the repeated keys named, or when a foreign-key check runs under fk_policy("error").

Examples:

Collect the pipeline result::

result = (
    df.sdtm
    .assign("DOMAIN", value="DM")
    .assign("USUBJID", source="subject_id")
    .to_frame()
)
Source code in src/fleet/core/_verb_mixin.py
def to_frame(self) -> DataFrame:
    """Materialise the accumulated pipeline into a Polars DataFrame.

    Returns:
        DataFrame: The fully materialised result of all chained
            verbs — a plain ``pl.DataFrame`` at runtime, typed as
            :class:`fleet.DataFrame` so re-entering ``.sdtm`` /
            ``.adam`` / ``.tlg`` type-checks.

    Raises:
        DerivationError: When collection fails because a column is
            missing — enriched with the lineage entries that
            reference the column, so the error names the verb(s)
            involved.  Also when a ``merge(validate=...)`` fails, with
            the repeated keys named, or when a foreign-key check runs
            under ``fk_policy("error")``.

    Examples:
        Collect the pipeline result::

            result = (
                df.sdtm
                .assign("DOMAIN", value="DM")
                .assign("USUBJID", source="subject_id")
                .to_frame()
            )
    """
    try:
        df = self._lazy.collect()
    except (
        pl.exceptions.ColumnNotFoundError,
        pl.exceptions.SchemaFieldNotFoundError,
        pl.exceptions.StructFieldNotFoundError,
    ) as err:
        raise self._enrich_collect_error(err) from err
    except pl.exceptions.ComputeError as err:
        named = next(
            (
                msg
                for check in getattr(self, "_pending_join_checks", [])
                if (msg := check.explain_validation()) is not None
            ),
            None,
        )
        if named is None:
            raise
        raise DerivationError(named) from err
    run_checks = getattr(self, "_run_pending_fk_checks", None)
    if run_checks is not None:
        run_checks(df)
    join_checks = getattr(self, "_pending_join_checks", [])
    # Rebind, never mutate: earlier chain copies keep their own queue.
    self._pending_join_checks = []
    for check in join_checks:
        check.warn_many_to_many()
    return cast("DataFrame", df)

to_dataset_json

to_dataset_json(path, *, domain, label=None)

Materialise the pipeline and write a CDISC Dataset-JSON v1.1 file.

This is a terminal verb — it collects the lazy plan and writes the result. No further chaining is possible after this call. After :meth:from_spec on a define.yaml, the file gets the define labels, lengths, key sequence and OIDs of the dataset.

Parameters:

Name Type Description Default
path str | Path

Destination file path (should end in .json).

required
domain str

Dataset / domain name (e.g. "DM", "ADSL").

required
label str | None

Optional human-readable dataset label; it wins over the define label.

None

Returns:

Name Type Description
Path Path

Path to the written file.

Raises:

Type Description
DerivationError

When a foreign-key check fails under fk_policy("error"); no file is written.

Examples:

Export a dataset to Dataset-JSON::

path = (
    df.sdtm
    .assign("DOMAIN", value="DM")
    .assign("USUBJID", source="subject_id")
    .to_dataset_json("outputs/dm.json", domain="DM")
)
Source code in src/fleet/core/_verb_mixin.py
def to_dataset_json(
    self,
    path: str | Path,
    *,
    domain: str,
    label: str | None = None,
) -> Path:
    """Materialise the pipeline and write a CDISC Dataset-JSON v1.1 file.

    This is a terminal verb — it collects the lazy plan and writes the
    result.  No further chaining is possible after this call.  After
    :meth:`from_spec` on a define.yaml, the file gets the define labels,
    lengths, key sequence and OIDs of the dataset.

    Args:
        path: Destination file path (should end in ``.json``).
        domain: Dataset / domain name (e.g. ``"DM"``, ``"ADSL"``).
        label: Optional human-readable dataset label; it wins over
            the define label.

    Returns:
        Path: Path to the written file.

    Raises:
        DerivationError: When a foreign-key check fails under
            ``fk_policy("error")``; no file is written.

    Examples:
        Export a dataset to Dataset-JSON::

            path = (
                df.sdtm
                .assign("DOMAIN", value="DM")
                .assign("USUBJID", source="subject_id")
                .to_dataset_json("outputs/dm.json", domain="DM")
            )
    """
    from fleet.io.dataset_json import metadata_from_define, save_dataset_json

    meta: dict[str, Any] = {}
    source = getattr(self, "_spec_source", None)
    if source is not None and source[1].upper() == domain.upper():
        meta = metadata_from_define(source[0], source[1])
    if label is not None:
        meta["label"] = label
    return save_dataset_json(self.to_frame(), path, domain=domain, **meta)

inspect

inspect(prefix='DEBUG')

Materialise the pipeline at this point and log its state.

Creates a hard checkpoint: the pipeline resumes from the materialised frame, making it easy to isolate exactly where a derivation goes wrong. Output goes through the "fleet" logger (INFO level, stdout by default — see :mod:fleet.core.log).

Parameters:

Name Type Description Default
prefix str

Label logged alongside the diagnostic output.

'DEBUG'

Returns:

Name Type Description
Self Self

A fresh namespace wrapping the materialised frame; call further verbs or .to_frame() to continue.

Examples:

Inspect the pipeline after assigning key variables::

result = (
    df.sdtm
    .assign("DOMAIN", value="DM")
    .inspect(prefix="After DOMAIN")
    .assign("USUBJID", source="subject_id")
    .to_frame()
)
Source code in src/fleet/core/_verb_mixin.py
def inspect(self, prefix: str = "DEBUG") -> Self:
    """Materialise the pipeline at this point and log its state.

    Creates a hard checkpoint: the pipeline resumes from the
    materialised frame, making it easy to isolate exactly where a
    derivation goes wrong.  Output goes through the ``"fleet"``
    logger (INFO level, stdout by default — see
    :mod:`fleet.core.log`).

    Args:
        prefix: Label logged alongside the diagnostic output.

    Returns:
        Self: A fresh namespace wrapping the materialised frame;
            call further verbs or ``.to_frame()`` to continue.

    Examples:
        Inspect the pipeline after assigning key variables::

            result = (
                df.sdtm
                .assign("DOMAIN", value="DM")
                .inspect(prefix="After DOMAIN")
                .assign("USUBJID", source="subject_id")
                .to_frame()
            )
    """
    df = self._lazy.collect()
    fleet_log.ensure_default_handler()
    logger.info("[%s] Schema: %s", prefix, df.schema)
    logger.info("[%s] Shape:  %s", prefix, df.shape)
    logger.info("%s", df.head(5))
    return self._materialise_then(df)

explain

explain()

Log the current Polars query plan without materialising.

Useful for understanding how Polars will optimise the accumulated derivation pipeline. Output goes through the "fleet" logger (INFO level, stdout by default — see :mod:fleet.core.log).

Returns:

Name Type Description
Self Self

The same namespace instance (unchanged); call further verbs or .to_frame() to continue.

Examples:

Log the query plan before collecting::

result = (
    df.sdtm
    .assign("DOMAIN", value="DM")
    .explain()
    .to_frame()
)
Source code in src/fleet/core/_verb_mixin.py
def explain(self) -> Self:
    """Log the current Polars query plan without materialising.

    Useful for understanding how Polars will optimise the accumulated
    derivation pipeline.  Output goes through the ``"fleet"`` logger
    (INFO level, stdout by default — see :mod:`fleet.core.log`).

    Returns:
        Self: The same namespace instance (unchanged); call
            further verbs or ``.to_frame()`` to continue.

    Examples:
        Log the query plan before collecting::

            result = (
                df.sdtm
                .assign("DOMAIN", value="DM")
                .explain()
                .to_frame()
            )
    """
    fleet_log.ensure_default_handler()
    logger.info("%s", self._lazy.explain())
    return self

trail

trail()

Log a table of each derived variable's origin in the pipeline.

Renders the accumulated variable lineage — the verb that produced each column and the source columns it consumed, including cross-domain pin sources — as a table through the "fleet" logger (INFO level, stdout by default — see :mod:fleet.core.log), then returns the namespace unchanged so the chain continues. Unlike inspect, nothing is materialised: the trail is pure metadata captured automatically on every verb call.

Only derived variables appear; columns that pass through untouched from the source frame are not listed. When a variable is derived more than once, each derivation is shown in pipeline order. Variables with no source column (e.g. hardcoded constants) are marked (literal).

Returns:

Name Type Description
Self Self

The same namespace instance (unchanged); call further verbs or .to_frame() to continue.

Examples:

Print the origin of every derived variable before collecting::

ae = (
    ae_raw.sdtm
    .assign("USUBJID", source="patient_number")
    .assign("AESTDTC", source="ae_start_date")
    .pin("DM", dm)
    .study_day("AESTDY", date_col="AESTDTC")
    .trail()
    .to_frame()
)
Source code in src/fleet/core/_verb_mixin.py
def trail(self) -> Self:
    """Log a table of each derived variable's origin in the pipeline.

    Renders the accumulated variable lineage — the verb that produced
    each column and the source columns it consumed, including
    cross-domain pin sources — as a table through the ``"fleet"``
    logger (INFO level, stdout by default — see
    :mod:`fleet.core.log`), then returns the namespace unchanged so
    the chain continues. Unlike ``inspect``, nothing is
    materialised: the trail is pure metadata captured automatically on
    every verb call.

    Only *derived* variables appear; columns that pass through untouched
    from the source frame are not listed. When a variable is derived more
    than once, each derivation is shown in pipeline order. Variables with
    no source column (e.g. hardcoded constants) are marked ``(literal)``.

    Returns:
        Self: The same namespace instance (unchanged); call further
            verbs or ``.to_frame()`` to continue.

    Examples:
        Print the origin of every derived variable before collecting::

            ae = (
                ae_raw.sdtm
                .assign("USUBJID", source="patient_number")
                .assign("AESTDTC", source="ae_start_date")
                .pin("DM", dm)
                .study_day("AESTDY", date_col="AESTDTC")
                .trail()
                .to_frame()
            )
    """
    from fleet.core.lineage import lineage_of, pin_lineage_of

    fleet_log.ensure_default_handler()
    nodes = lineage_of(self)
    if not nodes:
        logger.info("Variable trail: (empty — no derivations recorded yet)")
        return self

    # Group cross-domain pin sources by the variable they feed.
    pin_origins: dict[str, list[str]] = {}
    pinned_cols: dict[str, set[str]] = {}
    for dep in pin_lineage_of(self):
        cols = ", ".join(dep.source_cols) if dep.source_cols else "*"
        label = f"{dep.source_domain}.{cols}"
        if dep.relationship != "derivation":
            label += f" [{dep.relationship}]"
        pin_origins.setdefault(dep.target_col, []).append(label)
        pinned_cols.setdefault(dep.target_col, set()).update(dep.source_cols)

    has_domain = any(node.domain for node in nodes)
    rows: list[dict[str, object]] = []
    for i, node in enumerate(nodes, start=1):
        # Drop bare local sources already attributed to a pinned domain.
        covered = pinned_cols.get(node.name, set())
        local = [src for src in node.sources if src not in covered]
        origins = list(dict.fromkeys([*local, *pin_origins.get(node.name, [])]))
        row: dict[str, object] = {
            "#": i,
            "Variable": node.name,
            "Verb": node.verb,
            "Origin": ", ".join(origins) if origins else "(literal)",
        }
        if has_domain:
            row["Domain"] = node.domain or "—"
        rows.append(row)

    table = pl.DataFrame(rows)
    logger.info("Variable trail (%d derivation(s)):", table.height)
    with pl.Config(
        tbl_hide_dataframe_shape=True,
        tbl_hide_column_data_types=True,
        fmt_str_lengths=100,
        tbl_rows=table.height,
    ):
        logger.info("%s", table)
    return self

write_parquet

write_parquet(path, *, mkdir=True)

Materialise the pipeline, write to Parquet, and return the DataFrame.

This is a drop-in alternative to to_frame() when you want to persist the dataset as part of the chain.

Parameters:

Name Type Description Default
path str | Path

Destination file path.

required
mkdir bool

When True (default) any missing parent directories are created automatically.

True

Returns:

Name Type Description
DataFrame DataFrame

The materialised result (typed as :class:fleet.DataFrame — see to_frame()).

Examples:

Write a domain to Parquet::

dm = (
    raw_df.sdtm
    .assign("USUBJID", source="patient_number")
    .write_parquet("outputs/dm.parquet")
)
Source code in src/fleet/core/_verb_mixin.py
def write_parquet(
    self,
    path: str | Path,
    *,
    mkdir: bool = True,
) -> DataFrame:
    """Materialise the pipeline, write to Parquet, and return the DataFrame.

    This is a drop-in alternative to ``to_frame()`` when you want to
    persist the dataset as part of the chain.

    Args:
        path: Destination file path.
        mkdir: When ``True`` (default) any missing parent directories
            are created automatically.

    Returns:
        DataFrame: The materialised result (typed as
            :class:`fleet.DataFrame` — see ``to_frame()``).

    Examples:
        Write a domain to Parquet::

            dm = (
                raw_df.sdtm
                .assign("USUBJID", source="patient_number")
                .write_parquet("outputs/dm.parquet")
            )
    """
    df = self.to_frame()
    dest = Path(path)
    if mkdir:
        dest.parent.mkdir(parents=True, exist_ok=True)
    df.write_parquet(dest)
    return df

assign

assign(
    target,
    *,
    source=None,
    value=None,
    ct=None,
    ct_map=None,
    ct_validator=None,
    validate_values=None
)

Assign target from a source column or a literal value.

The one canonical assignment verb. Exactly one of source / value must be given; controlled-terminology behaviour is toggled by the presence of ct / ct_map.

Parameters:

Name Type Description Default
target str

Name of the output variable to create.

required
source str | None

Input column to copy from. Mutually exclusive with value.

None
value Any | None

Literal value to broadcast to every row. Mutually exclusive with source.

None
ct str | type | None

CDISC CT codelist for validation — a generated codelist class (e.g. SEX) or an NCI concept ID string (e.g. "C66731"). With source and no ct_map, values are passed through and validated; with value, the literal is validated at pipeline-build time.

None
ct_map dict[str, str] | None

Explicit {raw_value: ct_value} mapping applied to source (raw codes that need remapping). Requires source. Keys match the text form of the value, so {"1": "M"} and {1: "M"} both map a numeric 1; the result is text. A raw value outside the map is kept as text, as SAS PUT with no OTHER= keeps it.

None
ct_validator CTValidator | None

Optional pre-built validator instance.

None
validate_values bool | None

Controls the codelist check of the values the column will hold (after ct_map). None (default): check whenever codelist terms are available, warn with the values not in the codelist, and warn about the degradation otherwise. Null and blank values are never findings. False: skip the check silently.

None

Returns:

Name Type Description
Self Self

The namespace with target appended; call .to_frame() to materialise.

Raises:

Type Description
DerivationError

When neither or both of source / value are given.

VerbUsageError

When ct_map is combined with value.

Examples:

Copy, hardcode, and CT-map in one vocabulary::

dm = (
    raw_df.sdtm
    .assign("USUBJID", source="subject_id")
    .assign("DOMAIN", value="DM")
    .assign("SEX", source="sex", ct=SEX,
            ct_map={"1": "M", "2": "F"})
    .to_frame()
)
Source code in src/fleet/core/_verb_mixin.py
def assign(
    self,
    target: str,
    *,
    source: str | None = None,
    value: Any | None = None,
    ct: str | type | None = None,
    ct_map: dict[str, str] | None = None,
    ct_validator: CTValidator | None = None,
    validate_values: bool | None = None,
) -> Self:
    """Assign *target* from a source column or a literal value.

    The one canonical assignment verb.  Exactly one of *source* /
    *value* must be given; controlled-terminology behaviour is
    toggled by the presence of *ct* / *ct_map*.

    Args:
        target: Name of the output variable to create.
        source: Input column to copy from.  Mutually exclusive with
            *value*.
        value: Literal value to broadcast to every row.  Mutually
            exclusive with *source*.
        ct: CDISC CT codelist for validation — a generated codelist
            class (e.g. ``SEX``) or an NCI concept ID string
            (e.g. ``"C66731"``).  With *source* and no *ct_map*,
            values are passed through and validated; with *value*,
            the literal is validated at pipeline-build time.
        ct_map: Explicit ``{raw_value: ct_value}`` mapping applied to
            *source* (raw codes that need remapping).  Requires
            *source*.  Keys match the text form of the value, so
            ``{"1": "M"}`` and ``{1: "M"}`` both map a numeric 1; the
            result is text.  A raw value outside the map is kept as
            text, as SAS PUT with no OTHER= keeps it.
        ct_validator: Optional pre-built validator instance.
        validate_values: Controls the codelist check of the values the
            column will hold (after *ct_map*).  ``None`` (default):
            check whenever codelist terms are available, warn with the
            values not in the codelist, and warn about the degradation
            otherwise.  Null and blank values are never findings.
            ``False``: skip the check silently.

    Returns:
        Self: The namespace with *target* appended; call
            ``.to_frame()`` to materialise.

    Raises:
        DerivationError: When neither or both of *source* / *value*
            are given.
        VerbUsageError: When *ct_map* is combined with *value*.

    Examples:
        Copy, hardcode, and CT-map in one vocabulary::

            dm = (
                raw_df.sdtm
                .assign("USUBJID", source="subject_id")
                .assign("DOMAIN", value="DM")
                .assign("SEX", source="sex", ct=SEX,
                        ct_map={"1": "M", "2": "F"})
                .to_frame()
            )
    """
    return self._assign_impl(
        target,
        source=source,
        value=value,
        ct=ct,
        ct_map=ct_map,
        ct_validator=ct_validator,
        validate_values=validate_values,
        verb="assign",
        fk=True,
    )

case_when

case_when(target, *, when, else_=None)

Multi-branch conditional derivation (first matching branch wins).

The one canonical conditional verb.

Parameters:

Name Type Description Default
target str

Name of the output variable.

required
when list[dict[str, Any]]

Ordered list of {"condition": expr, "value": any} dicts. condition may be a Polars expression or an expression string.

required
else_ Any

Fallback value when no branch matches.

None

Returns:

Name Type Description
Self Self

The namespace with target appended; call .to_frame() to materialise.

Examples:

Derive an age group::

adsl = (
    dm_df.adam.adsl
    .case_when("AGEGR1", when=[
        {"condition": 'pl.col("AGE") < 65', "value": "<65"},
        {"condition": 'pl.col("AGE") < 75', "value": "65-74"},
    ], else_=">=75")
    .to_frame()
)
Source code in src/fleet/core/_verb_mixin.py
def case_when(
    self,
    target: str,
    *,
    when: list[dict[str, Any]],
    else_: Any = None,
) -> Self:
    """Multi-branch conditional derivation (first matching branch wins).

    The one canonical conditional verb.

    Args:
        target: Name of the output variable.
        when: Ordered list of ``{"condition": expr, "value": any}``
            dicts.  ``condition`` may be a Polars expression or an
            expression string.
        else_: Fallback value when no branch matches.

    Returns:
        Self: The namespace with *target* appended; call
            ``.to_frame()`` to materialise.

    Examples:
        Derive an age group::

            adsl = (
                dm_df.adam.adsl
                .case_when("AGEGR1", when=[
                    {"condition": 'pl.col("AGE") < 65', "value": "<65"},
                    {"condition": 'pl.col("AGE") < 75', "value": "65-74"},
                ], else_=">=75")
                .to_frame()
            )
    """
    return self._case_when_impl(target, when=when, else_=else_, verb="case_when")

merge

merge(
    dataset=None,
    *,
    on=None,
    how="left",
    keep=None,
    where=None,
    validate=None
)

Join dataset into the pipeline using key column(s) on.

The one canonical join verb. The join is appended to the lazy plan; nothing is materialised. It reads as SAS merge left right(keep=...): every pipeline column stays, and keep limits the columns taken from dataset. Keys match exactly: "S1 " and "S1" are two keys.

A non-key column on both sides raises: select or rename the columns of dataset first. A key that repeats on both sides warns at to_frame(), because the join then gives every pair of rows. how="full" gives one key column, as SAS MERGE.

Parameters:

Name Type Description Default
dataset DataFrame | LazyFrame | None

The pl.DataFrame / pl.LazyFrame to merge in.

None
on str | list[str] | None

Key column name(s) for the join.

None
how str

Join strategy (default "left").

'left'
keep list[str] | None

Optional columns of dataset to bring in, besides the on key(s). When None, every column of dataset is brought in.

None
where str | Expr | None

Optional filter expression applied to dataset before the join; it may use a column that keep leaves out.

None
validate Literal['m:1', '1:m', '1:1'] | None

Optional key rule, checked at to_frame(): "m:1" (each key once in dataset), "1:m" (once in the pipeline) or "1:1" (once on both sides).

None

Returns:

Name Type Description
Self Self

The namespace continuing from the joined plan.

Raises:

Type Description
VerbUsageError

When dataset or on is missing.

DerivationError

When a keep entry is absent from dataset (with a did-you-mean suggestion), or a non-key column is on both sides. At to_frame(), when validate fails; the message names the repeated keys.

References

ADR-0032 (docs/adr/0032-merge-reads-as-sas-merge-and-stops-on-a-clash.md). admiral derive_vars_merged stops on a column on both sides.

Examples:

Merge one supplemental qualifier onto the DM domain::

dm = (
    raw_df.sdtm
    .assign("DOMAIN", value="DM")
    .merge(
        suppdm_df,
        on="USUBJID",
        keep=["QVAL"],
        where='pl.col("QNAM") == "RACE1"',
        validate="m:1",
    )
    .to_frame()
)
Source code in src/fleet/core/_verb_mixin.py
def merge(
    self,
    dataset: pl.DataFrame | pl.LazyFrame | None = None,
    *,
    on: str | list[str] | None = None,
    how: str = "left",
    keep: list[str] | None = None,
    where: str | pl.Expr | None = None,
    validate: Literal["m:1", "1:m", "1:1"] | None = None,
) -> Self:
    """Join *dataset* into the pipeline using key column(s) *on*.

    The one canonical join verb.  The join is appended to the lazy
    plan; nothing is materialised.  It reads as SAS
    ``merge left right(keep=...)``: every pipeline column stays, and
    *keep* limits the columns taken from *dataset*.  Keys match
    exactly: ``"S1 "`` and ``"S1"`` are two keys.

    A non-key column on both sides raises: select or rename the
    columns of *dataset* first.  A key that repeats on both sides
    warns at ``to_frame()``, because the join then gives every pair
    of rows.  ``how="full"`` gives one key column, as SAS MERGE.

    Args:
        dataset: The ``pl.DataFrame`` / ``pl.LazyFrame`` to merge in.
        on: Key column name(s) for the join.
        how: Join strategy (default ``"left"``).
        keep: Optional columns of *dataset* to bring in, besides the
            *on* key(s).  When ``None``, every column of *dataset* is
            brought in.
        where: Optional filter expression applied to *dataset*
            before the join; it may use a column that *keep* leaves
            out.
        validate: Optional key rule, checked at ``to_frame()``:
            ``"m:1"`` (each key once in *dataset*), ``"1:m"`` (once in
            the pipeline) or ``"1:1"`` (once on both sides).

    Returns:
        Self: The namespace continuing from the joined plan.

    Raises:
        VerbUsageError: When *dataset* or *on* is missing.
        DerivationError: When a *keep* entry is absent from *dataset*
            (with a did-you-mean suggestion), or a non-key column is on
            both sides.  At ``to_frame()``, when *validate* fails; the
            message names the repeated keys.

    References:
        ADR-0032 (docs/adr/0032-merge-reads-as-sas-merge-and-stops-on-a-clash.md).
        admiral ``derive_vars_merged`` stops on a column on both sides.

    Examples:
        Merge one supplemental qualifier onto the DM domain::

            dm = (
                raw_df.sdtm
                .assign("DOMAIN", value="DM")
                .merge(
                    suppdm_df,
                    on="USUBJID",
                    keep=["QVAL"],
                    where='pl.col("QNAM") == "RACE1"',
                    validate="m:1",
                )
                .to_frame()
            )
    """
    return self._merge_impl(
        dataset, on=on, how=how, keep=keep, where=where, validate=validate, verb="merge"
    )

keep

keep(*columns)

Restrict the frame to columns, in the given order.

Accepts either variadic names — keep("STUDYID", "USUBJID") — or a single list — keep(["STUDYID", "USUBJID"]). Stays lazy.

Parameters:

Name Type Description Default
*columns str | list[str]

Column names (or one list of names) to keep.

()

Returns:

Name Type Description
Self Self

The namespace continuing from the restricted plan.

Raises:

Type Description
DerivationError

When a requested column is absent (with a did-you-mean suggestion), or no columns are given.

Examples:

Keep only the submission variables::

dm = (
    raw_df.sdtm
    .assign("USUBJID", source="subject_id")
    .keep("STUDYID", "USUBJID", "SEX")
    .to_frame()
)
Source code in src/fleet/core/_verb_mixin.py
def keep(self, *columns: str | list[str]) -> Self:
    """Restrict the frame to *columns*, in the given order.

    Accepts either variadic names — ``keep("STUDYID", "USUBJID")`` —
    or a single list — ``keep(["STUDYID", "USUBJID"])``.  Stays lazy.

    Args:
        *columns: Column names (or one list of names) to keep.

    Returns:
        Self: The namespace continuing from the restricted plan.

    Raises:
        DerivationError: When a requested column is absent (with a
            did-you-mean suggestion), or no columns are given.

    Examples:
        Keep only the submission variables::

            dm = (
                raw_df.sdtm
                .assign("USUBJID", source="subject_id")
                .keep("STUDYID", "USUBJID", "SEX")
                .to_frame()
            )
    """
    if len(columns) == 1 and isinstance(columns[0], list):
        cols: list[str] = list(columns[0])
    else:
        cols = [c for c in columns]  # type: ignore[misc]
    if not cols:
        raise DerivationError("keep() requires at least one column name.")
    require_columns("keep()", cols, self._lazy.collect_schema().names(), where="the frame")
    return self._with_lazy(self._lazy.select(cols))

verbs

verbs()

List the public verbs available on this namespace.

Walks the class MRO collecting public Fleet-defined methods and returns a tidy frame with each verb's name, the first sentence of its docstring and the namespace that defines it. This is the always-current alternative to hard-coded verb counts in docs, and the discovery seam for a sub-namespace: autocomplete shows every inherited verb, origin tells them apart.

Returns:

Type Description
DataFrame

pl.DataFrame: Columns verb, summary and origin, sorted by verb name. origin is the path a programmer types to reach the namespace that defines the verb ("sdtm", "adam", "adam.metabolic"), or "core" for the verbs every namespace shares.

Examples:

Discover what an SDTM pipeline can do::

import fleet  # noqa: F401

catalog = raw_df.sdtm.verbs()
print(catalog)

Keep only the verbs a therapeutic-area namespace adds::

own = raw_df.adam.metabolic.verbs().filter(
    pl.col("origin") == "adam.metabolic"
)
Source code in src/fleet/core/_verb_mixin.py
def verbs(self) -> pl.DataFrame:
    """List the public verbs available on this namespace.

    Walks the class MRO collecting public Fleet-defined methods and
    returns a tidy frame with each verb's name, the first sentence
    of its docstring and the namespace that defines it.  This is
    the always-current alternative to hard-coded verb counts in
    docs, and the discovery seam for a sub-namespace: autocomplete
    shows every inherited verb, ``origin`` tells them apart.

    Returns:
        pl.DataFrame: Columns ``verb``, ``summary`` and ``origin``,
            sorted by verb name.  ``origin`` is the path a programmer
            types to reach the namespace that defines the verb
            (``"sdtm"``, ``"adam"``, ``"adam.metabolic"``), or
            ``"core"`` for the verbs every namespace shares.

    Examples:
        Discover what an SDTM pipeline can do::

            import fleet  # noqa: F401

            catalog = raw_df.sdtm.verbs()
            print(catalog)

        Keep only the verbs a therapeutic-area namespace adds::

            own = raw_df.adam.metabolic.verbs().filter(
                pl.col("origin") == "adam.metabolic"
            )
    """
    from fleet.core.algorithm_resolver import docstring_summary

    rows: list[dict[str, str]] = []
    seen: set[str] = set(self._VERBS_EXCLUDE)
    for klass in type(self).__mro__:
        if not klass.__module__.startswith("fleet."):
            continue
        origin = _verb_origin(klass)
        for name, attr in vars(klass).items():
            if name.startswith("_") or name in seen:
                continue
            seen.add(name)
            if isinstance(attr, (property, staticmethod, classmethod)):
                continue
            if not callable(attr):
                continue
            rows.append(
                {"verb": name, "summary": docstring_summary(attr.__doc__), "origin": origin}
            )
    rows.sort(key=lambda r: r["verb"])
    return pl.DataFrame(
        rows, schema={"verb": pl.String, "summary": pl.String, "origin": pl.String}
    )

derivation

derivation(
    target: str,
    *,
    expression: str | Expr | Callable[[], Expr]
) -> Self
derivation(target: Derivation) -> Self
derivation(target=None, *, expression=None)

Derive target using an expression, lambda, or Derivation object.

Four call forms are supported:

Case 1 — string (AST-sandboxed, YAML-compatible)::

.derivation("COL", expression="pl.col('src').cast(pl.String)")

Case 2 — direct pl.Expr::

.derivation("COL", expression=pl.col("src").cast(pl.String))

Case 3 — zero-arg lambda returning pl.Expr (full IDE support)::

.derivation("COL", expression=lambda: pl.col("src").cast(pl.Int32))

Case 4 — @derivation object (file-based, full lineage)::

from specs.study01.derivations import MY_DRULE
.derivation(MY_DRULE)

Parameters:

Name Type Description Default
target str | Derivation | None

For Cases 1–3, the name of the output variable (required). For Case 4, the :class:~fleet.core.derivation.Derivation object to dispatch.

None
expression str | Expr | Callable[[], Expr] | None

A Polars expression, expression string, or zero-arg callable returning pl.Expr. Required for Cases 1–3.

None

Returns:

Name Type Description
Self Self

The namespace with target appended; call .to_frame() to materialise.

Raises:

Type Description
ValueError

If target is a string but expression is not provided, or vice-versa.

TypeError

If a lambda-style expression does not return pl.Expr.

Examples:

Case 1 — string expression::

result = (
    raw_df.sdtm
    .derivation("SITEID", expression="pl.col('site_id').cast(pl.String)")
    .to_frame()
)

Case 3 — lambda::

result = (
    raw_df.sdtm
    .derivation("VISITNUM", expression=lambda: pl.col("visit").cast(pl.Int32))
    .to_frame()
)

Case 4 — @derivation object::

from specs.study01.derivations import MY_DRULE

result = (
    raw_df.sdtm
    .derivation(MY_DRULE)
    .to_frame()
)
Source code in src/fleet/core/_verb_mixin.py
def derivation(
    self,
    target: str | Derivation | None = None,
    *,
    expression: str | pl.Expr | Callable[[], pl.Expr] | None = None,
) -> Self:
    """Derive *target* using an expression, lambda, or ``Derivation`` object.

    Four call forms are supported:

    **Case 1 — string (AST-sandboxed, YAML-compatible)**::

        .derivation("COL", expression="pl.col('src').cast(pl.String)")

    **Case 2 — direct ``pl.Expr``**::

        .derivation("COL", expression=pl.col("src").cast(pl.String))

    **Case 3 — zero-arg lambda returning ``pl.Expr`` (full IDE support)**::

        .derivation("COL", expression=lambda: pl.col("src").cast(pl.Int32))

    **Case 4 — ``@derivation`` object (file-based, full lineage)**::

        from specs.study01.derivations import MY_DRULE
        .derivation(MY_DRULE)

    Args:
        target: For Cases 1–3, the name of the output variable
            (required).  For Case 4, the
            :class:`~fleet.core.derivation.Derivation` object to dispatch.
        expression: A Polars expression, expression string, or zero-arg
            callable returning ``pl.Expr``.  Required for Cases 1–3.

    Returns:
        Self: The namespace with *target* appended; call ``.to_frame()``
            to materialise.

    Raises:
        ValueError: If *target* is a string but *expression* is not
            provided, or vice-versa.
        TypeError: If a lambda-style *expression* does not return
            ``pl.Expr``.

    Examples:
        Case 1 — string expression::

            result = (
                raw_df.sdtm
                .derivation("SITEID", expression="pl.col('site_id').cast(pl.String)")
                .to_frame()
            )

        Case 3 — lambda::

            result = (
                raw_df.sdtm
                .derivation("VISITNUM", expression=lambda: pl.col("visit").cast(pl.Int32))
                .to_frame()
            )

        Case 4 — ``@derivation`` object::

            from specs.study01.derivations import MY_DRULE

            result = (
                raw_df.sdtm
                .derivation(MY_DRULE)
                .to_frame()
            )
    """
    from fleet.sdtm.utils import parse_expression

    # Case 4: Derivation object passed as first positional arg.
    if target is not None and not isinstance(target, str):
        return self._apply_derivation(target)  # type: ignore[arg-type]

    # Cases 1–3 require a string target.
    if target is None:
        raise DerivationError("target is required when expression= is provided.")
    if expression is None:
        raise DerivationError("expression is required when target is a string.")

    params = {"target": target, "expression": expression}

    # Case 2: direct pl.Expr.
    if isinstance(expression, pl.Expr):
        return self._chain(expression.alias(target), verb="derivation", params=params)

    # Case 3: lambda / zero-arg callable.
    if callable(expression) and not isinstance(expression, str):
        expr = expression()
        if not isinstance(expr, pl.Expr):
            raise VerbUsageError(
                f"expression callable must return pl.Expr, got {type(expr).__name__}"
            )
        return self._chain(expr.alias(target), verb="derivation", params=params)

    # Case 1: string through AST sandbox.
    return self._chain(
        parse_expression(str(expression), self._lazy.collect_schema()).alias(target),
        verb="derivation",
        params=params,
    )

duration

duration(
    target,
    *,
    start,
    end,
    unit="days",
    add_one=None,
    out="numeric"
)

Compute the duration between two date/datetime columns.

Supports column references (str) and Polars expressions for start and end; an expression is read by its type, as a column is. --DTC text is read by its date part for day-based units and by its date-time for hours, minutes and seconds; a partial value gives null, and for hours, minutes and seconds a warning gives the count of text values with no time.

The add_one parameter controls inclusive counting:

  • None (default): auto-resolves from the target suffix and the unit. *DY targets in days use the CDISC study-day convention (no day 0). Days, weeks, months and years add one day before the division; hours, minutes and seconds give the raw difference (PK elapsed time).
  • True: add one day (day-based units) or one unit (sub-day).
  • False: raw difference.

One is added only when the end is on or after the start, as admiral compute_duration does: an end one day before the start gives -1, never 0. Weeks, months and years divide the day count by 7, 30.4375 and 365.25, so this verb does not give a completed age in years.

Parameters:

Name Type Description Default
target str

Name of the output column.

required
start str | Expr

Start date column name or expression.

required
end str | Expr

End date column name or expression.

required
unit Literal['seconds', 'minutes', 'hours', 'days', 'weeks', 'months', 'years']

Duration unit — "seconds", "minutes", "hours", "days" (default), "weeks", "months", "years".

'days'
add_one bool | None

Override for inclusive counting.

None
out Literal['numeric', 'iso8601']

Output format — "numeric" (default) or "iso8601". "iso8601" keeps the sign (-PT15M), writes hours, minutes and seconds from the total (PT1H30M) and adds one only when add_one=True is given (an elapsed time, P9D for 1 to 10 January). Weeks give null with a warning for a span that is not whole weeks; months and years raise. "iso8601" is incompatible with the *DY study-day convention: pass add_one explicitly (or use a non-DY target) to combine them.

'numeric'

Returns:

Name Type Description
Self Self

The namespace with target appended; call .to_frame() to materialise.

Raises:

Type Description
DerivationError

On an unknown unit/out value, when out="iso8601" is combined with a *DY target while add_one is unset (the study-day convention would silently override the requested format), with months or years, or when a column holds numbers (no date origin is guessed).

References

ISO 8601 durations and SDTMIG 3.4 --ELTM; admiral compute_duration; ADR-0011 and ADR-0022.

Examples:

ISO 8601 duration::

ex = (
    raw_df.sdtm
    .date("EXSTDTC", source="dose_start")
    .date("EXENDTC", source="dose_end")
    .duration("EXDUR", start="EXSTDTC", end="EXENDTC",
              out="iso8601")
    .to_frame()
)

Treatment duration in days::

adsl = (
    dm_df.adam.adsl
    .duration("TRTDURD", start="TRTSDT", end="TRTEDT")
    .to_frame()
)
Source code in src/fleet/core/_verb_mixin.py
def duration(
    self,
    target: str,
    *,
    start: str | pl.Expr,
    end: str | pl.Expr,
    unit: Literal["seconds", "minutes", "hours", "days", "weeks", "months", "years"] = "days",
    add_one: bool | None = None,
    out: Literal["numeric", "iso8601"] = "numeric",
) -> Self:
    """Compute the duration between two date/datetime columns.

    Supports column references (``str``) and Polars expressions
    for *start* and *end*; an expression is read by its type, as a
    column is.  ``--DTC`` text is read by its date part for
    day-based units and by its date-time for hours, minutes and
    seconds; a partial value gives null, and for hours, minutes and
    seconds a warning gives the count of text values with no time.

    The ``add_one`` parameter controls inclusive counting:

    - ``None`` (default): auto-resolves from the target suffix and the
      unit.  ``*DY`` targets in days use the CDISC study-day
      convention (no day 0).  Days, weeks, months and years add one
      **day** before the division; hours, minutes and seconds give
      the raw difference (PK elapsed time).
    - ``True``: add one day (day-based units) or one unit (sub-day).
    - ``False``: raw difference.

    One is added only when the end is on or after the start, as
    admiral ``compute_duration`` does: an end one day before the start
    gives -1, never 0.  Weeks, months and years divide the day count
    by 7, 30.4375 and 365.25, so this verb does not give a completed
    age in years.

    Args:
        target: Name of the output column.
        start: Start date column name or expression.
        end: End date column name or expression.
        unit: Duration unit — ``"seconds"``, ``"minutes"``, ``"hours"``,
            ``"days"`` (default), ``"weeks"``, ``"months"``, ``"years"``.
        add_one: Override for inclusive counting.
        out: Output format — ``"numeric"`` (default) or ``"iso8601"``.
            ``"iso8601"`` keeps the sign (``-PT15M``), writes hours,
            minutes and seconds from the total (``PT1H30M``) and adds
            one only when ``add_one=True`` is given (an elapsed time,
            ``P9D`` for 1 to 10 January).  Weeks give null with a
            warning for a span that is not whole weeks; months and
            years raise.  ``"iso8601"`` is incompatible with the
            ``*DY`` study-day convention: pass ``add_one`` explicitly
            (or use a non-DY target) to combine them.

    Returns:
        Self: The namespace with *target* appended; call ``.to_frame()``
            to materialise.

    Raises:
        DerivationError: On an unknown *unit*/*out* value, when
            ``out="iso8601"`` is combined with a ``*DY`` target while
            ``add_one`` is unset (the study-day convention would
            silently override the requested format), with months or
            years, or when a column holds numbers (no date origin is
            guessed).

    References:
        ISO 8601 durations and SDTMIG 3.4 ``--ELTM``; admiral
        ``compute_duration``; ADR-0011 and ADR-0022.

    Examples:
        ISO 8601 duration::

            ex = (
                raw_df.sdtm
                .date("EXSTDTC", source="dose_start")
                .date("EXENDTC", source="dose_end")
                .duration("EXDUR", start="EXSTDTC", end="EXENDTC",
                          out="iso8601")
                .to_frame()
            )

        Treatment duration in days::

            adsl = (
                dm_df.adam.adsl
                .duration("TRTDURD", start="TRTSDT", end="TRTEDT")
                .to_frame()
            )
    """
    if not isinstance(start, (str, pl.Expr)):
        raise VerbUsageError(f"start must be a column name (str) or pl.Expr, got {type(start)}")
    if not isinstance(end, (str, pl.Expr)):
        raise VerbUsageError(f"end must be a column name (str) or pl.Expr, got {type(end)}")
    if out not in ("numeric", "iso8601"):
        raise DerivationError(
            f"duration out={out!r} is not supported. Choose 'numeric' or 'iso8601'."
        )
    if out == "iso8601" and add_one is None and target.endswith("DY"):
        raise DerivationError(
            f"duration('{target}', out='iso8601'): targets ending in 'DY' follow the "
            "CDISC study-day convention (integer day count, no day 0) and always "
            "produce numeric output, so out='iso8601' would be ignored. Either use a "
            "target that does not end in 'DY', or pass add_one=True/False explicitly "
            "to opt out of the study-day convention and get ISO 8601 output."
        )

    duration_params = {
        "target": target,
        "start": start,
        "end": end,
        "unit": unit,
        "add_one": add_one,
        "out": out,
    }

    schema = self._lazy.collect_schema()
    sub_day = unit in ("seconds", "minutes", "hours")
    call = f"duration('{target}')"

    def _to_date_expr(col_or_expr: str | pl.Expr) -> pl.Expr:
        """Resolve a column or an expression to a date (day units) or a date-time (sub-day)."""
        if isinstance(col_or_expr, str):
            col, dtype = pl.col(col_or_expr), schema.get(col_or_expr)
        else:
            col = col_or_expr
            dtype = self._lazy.select(col).collect_schema().dtypes()[0]
        if not sub_day:
            return to_day(col, dtype, verb=call)
        refuse_number(
            col.meta.output_name(raise_if_undetermined=False) or "the column", dtype, verb=call
        )
        if dtype != pl.String:
            return col
        name = col.meta.output_name(raise_if_undetermined=False) or "the text"
        given = col.str.strip_chars().fill_null("") != ""
        return warn_on_collect(
            datetime_part(col),
            given & datetime_part(col).is_null(),
            lambda n, values: (
                f"{call}: {n} value(s) of {name} have no hour and minute, or are not "
                f"ISO 8601, so {target} is null for them. To impute a time with a flag, "
                f"derive a *DTM variable with .date() first. Values: {values}"
            ),
            dtype=pl.Datetime("us"),
            shown=col,
        )

    s_expr = _to_date_expr(start)
    e_expr = _to_date_expr(end)

    valid_units = {
        "seconds",
        "minutes",
        "hours",
        "days",
        "weeks",
        "months",
        "years",
    }
    if unit not in valid_units:
        raise DerivationError(
            f"duration unit={unit!r} is not supported. Choose one of: {sorted(valid_units)}"
        )

    if sub_day:
        s_dtm = s_expr.cast(pl.Datetime("us"))
        e_dtm = e_expr.cast(pl.Datetime("us"))
        seconds = (e_dtm - s_dtm).dt.total_seconds()
        diff_s = seconds.cast(pl.Float64)
        if unit == "seconds":
            diff = diff_s.cast(pl.Int64)
        elif unit == "minutes":
            diff = diff_s / 60.0
        else:  # hours
            diff = diff_s / 3600.0
    else:
        diff_days = (e_expr - s_expr).dt.total_days()
        divisor = {"days": 1, "weeks": 7.0, "months": 30.4375, "years": 365.25}[unit]
        diff = diff_days if unit == "days" else diff_days.cast(pl.Float64) / divisor

    if out == "iso8601":
        if unit in ("months", "years"):
            raise DerivationError(
                f"{call}: out='iso8601' with unit='{unit}' would cut the day count to whole "
                f"{unit}, because a month or a year has no fixed length. Use unit='days'."
            )
        if sub_day:
            iso_expr = _iso_clock(seconds, unit, add_one=add_one is True)
        else:
            iso_expr = _iso_days(
                diff_days, unit, add_one=add_one is True, call=call, target=target
            )
        return self._chain(iso_expr.alias(target), verb="duration", params=duration_params)

    # Resolve add_one
    if add_one is None:
        if target.endswith("DY") and unit == "days":
            # CDISC study day: +1 if >= 0, no day 0
            result_expr = (
                (pl.when(diff >= 0).then(diff + 1).otherwise(diff)).cast(pl.Int64).alias(target)
            )
            return self._chain(result_expr, verb="duration", params=duration_params)
        add_one = not sub_day

    if add_one and sub_day:
        result_expr = pl.when(diff >= 0).then(diff + 1).otherwise(diff).alias(target)
    elif add_one:
        inclusive = pl.when(diff_days >= 0).then(diff_days + 1).otherwise(diff_days)
        result_expr = (
            inclusive if unit == "days" else inclusive.cast(pl.Float64) / divisor
        ).alias(target)
    else:
        result_expr = diff.alias(target)

    return self._chain(result_expr, verb="duration", params=duration_params)

study_day

study_day(
    target,
    *,
    date_col,
    ref_col=None,
    ref_pin=None,
    ref_df=None,
    dm=None,
    adsl=None
)

Derive a CDISC study day variable from a date column and reference date.

Uses the CDISC algorithm: date - ref_date + 1 when date >= ref_date, else date - ref_date (no day 0), on the date portion of each value (SDTMIG 3.4 section 4.4.4): a time part is ignored, and a partial date gives null.

The reference date is resolved in this order:

  1. Explicit ref_df= parameter (highest priority). dm= and adsl= are accepted aliases of ref_df= matching the SDTM/ADaM vocabulary.
  2. Pinned domain (via .pin(...)).
  3. ref_col already present in the current frame.
  4. Actionable LookupError.

Parameters:

Name Type Description Default
target str

Name of the output study day variable (e.g. "AESTDY", "ASTDY").

required
date_col str

Column containing the date to measure from.

required
ref_col str | None

Reference date column name. Defaults to _STUDY_DAY_REF_COL class constant (RFSTDTC on SDTM, TRTSDT on ADaM).

None
ref_pin str | None

Pinned domain name. Defaults to _STUDY_DAY_REF_PIN class constant (DM on SDTM, ADSL on ADaM).

None
ref_df DataFrame | None

Optional explicit DataFrame override — bypasses pinning.

None
dm DataFrame | None

Alias of ref_df (SDTM vocabulary).

None
adsl DataFrame | None

Alias of ref_df (ADaM vocabulary).

None

Returns:

Name Type Description
Self Self

The namespace with target appended; call .to_frame() to materialise.

Raises:

Type Description
LookupError

If the reference date cannot be resolved from any source.

VerbUsageError

If more than one of ref_df / dm / adsl is given.

DerivationError

If the reference frame has two different reference dates for one subject (ADR-0032).

Examples:

Derive study day from pinned reference::

ae = (
    ae_raw.sdtm
    .pin("DM", dm_df)
    .study_day("AESTDY", date_col="AESTDTC")
    .to_frame()
)

ADaM study day::

adae = (
    ae_df.adam.occds("ADAE")
    .pin("ADSL", adsl_df)
    .study_day("ASTDY", date_col="ASTDT")
    .to_frame()
)
Source code in src/fleet/core/_verb_mixin.py
def study_day(
    self,
    target: str,
    *,
    date_col: str,
    ref_col: str | None = None,
    ref_pin: str | None = None,
    ref_df: pl.DataFrame | None = None,
    dm: pl.DataFrame | None = None,
    adsl: pl.DataFrame | None = None,
) -> Self:
    """Derive a CDISC study day variable from a date column and reference date.

    Uses the CDISC algorithm: ``date - ref_date + 1`` when
    ``date >= ref_date``, else ``date - ref_date`` (no day 0), on the
    date portion of each value (SDTMIG 3.4 section 4.4.4): a time
    part is ignored, and a partial date gives null.

    The reference date is resolved in this order:

    1. Explicit ``ref_df=`` parameter (highest priority).  ``dm=``
       and ``adsl=`` are accepted aliases of ``ref_df=`` matching
       the SDTM/ADaM vocabulary.
    2. Pinned domain (via ``.pin(...)``).
    3. ``ref_col`` already present in the current frame.
    4. Actionable ``LookupError``.

    Args:
        target: Name of the output study day variable
            (e.g. ``"AESTDY"``, ``"ASTDY"``).
        date_col: Column containing the date to measure from.
        ref_col: Reference date column name.  Defaults to
            ``_STUDY_DAY_REF_COL`` class constant (``RFSTDTC`` on
            SDTM, ``TRTSDT`` on ADaM).
        ref_pin: Pinned domain name.  Defaults to
            ``_STUDY_DAY_REF_PIN`` class constant (``DM`` on SDTM,
            ``ADSL`` on ADaM).
        ref_df: Optional explicit DataFrame override — bypasses pinning.
        dm: Alias of *ref_df* (SDTM vocabulary).
        adsl: Alias of *ref_df* (ADaM vocabulary).

    Returns:
        Self: The namespace with *target* appended; call
            ``.to_frame()`` to materialise.

    Raises:
        LookupError: If the reference date cannot be resolved from
            any source.
        VerbUsageError: If more than one of *ref_df* / *dm* / *adsl*
            is given.
        DerivationError: If the reference frame has two different
            reference dates for one subject (ADR-0032).

    Examples:
        Derive study day from pinned reference::

            ae = (
                ae_raw.sdtm
                .pin("DM", dm_df)
                .study_day("AESTDY", date_col="AESTDTC")
                .to_frame()
            )

        ADaM study day::

            adae = (
                ae_df.adam.occds("ADAE")
                .pin("ADSL", adsl_df)
                .study_day("ASTDY", date_col="ASTDT")
                .to_frame()
            )
    """
    from fleet.core.lineage import record_pin_lineage

    provided = [f for f in (ref_df, dm, adsl) if f is not None]
    if len(provided) > 1:
        raise VerbUsageError(
            f"study_day() accepts only one of ref_df= / dm= / adsl= — got {len(provided)}."
        )
    ref_df = provided[0] if provided else None

    # Resolve defaults from class constants
    _ref_col = ref_col if ref_col is not None else self._STUDY_DAY_REF_COL
    _ref_pin = ref_pin if ref_pin is not None else self._STUDY_DAY_REF_PIN

    schema = self._lazy.collect_schema()

    # Resolve reference date source
    if ref_df is not None:
        source_df = ref_df
        join_key = ["USUBJID"]
    elif _ref_col in schema.names():
        # ref_col already in frame — no join needed; stays lazy.
        date_expr = to_day(pl.col(date_col), schema.get(date_col), verb="study_day")
        ref_expr = to_day(pl.col(_ref_col), schema.get(_ref_col), verb="study_day")
        diff = (date_expr - ref_expr).dt.total_days()
        study_day_expr = pl.when(diff >= 0).then(diff + 1).otherwise(diff).alias(target)
        return self._chain(
            study_day_expr,
            verb="study_day",
            params={"target": target, "date_col": date_col, "ref_col": _ref_col},
        )
    else:
        source_df = self._require_pin(_ref_pin.upper(), "study_day", columns=[_ref_col])
        join_key = self._pin_join_key(_ref_pin.upper())

    df = self._lazy.collect()

    # Join, compute, drop temp column
    ref_slim = refuse_repeated_keys(
        "study_day()",
        source_df.select(
            [c for c in dict.fromkeys(join_key + [_ref_col]) if c in source_df.columns]
        ),
        join_key,
        source=_ref_pin.upper() if ref_df is None else "the reference frame",
    )

    _ref_tmp = f"__pin_{_ref_col}__"
    ref_slim = ref_slim.rename({_ref_col: _ref_tmp})

    df = df.join(ref_slim, on=join_key, how="left", nulls_equal=True)

    date_expr = to_day(pl.col(date_col), df.schema.get(date_col), verb="study_day")
    ref_expr = to_day(pl.col(_ref_tmp), df.schema.get(_ref_tmp), verb="study_day")

    diff = (date_expr - ref_expr).dt.total_days()
    study_day_expr = pl.when(diff >= 0).then(diff + 1).otherwise(diff).alias(target)
    df = df.with_columns(study_day_expr).drop(_ref_tmp)

    new = self._materialise_then(df)

    # Record variable lineage
    from fleet.core.dag import VariableNode

    var_lineage: list = list(getattr(new, "_lineage", []))
    var_lineage.append(
        VariableNode(
            name=target,
            verb="study_day",
            sources=[date_col, _ref_col],
            method=f"{self.__class__.__module__}.{self.__class__.__qualname__}.study_day",
            domain=getattr(new, "_domain", None),
            params={
                "target": target,
                "date_col": date_col,
                "ref_col": _ref_col,
                "ref_pin": _ref_pin,
            },
        )
    )
    new._lineage = var_lineage

    # Record pin lineage
    record_pin_lineage(
        new,
        target_col=target,
        verb="study_day",
        source_domain=_ref_pin.upper(),
        source_cols=[_ref_col],
        join_key=join_key,
        relationship="derivation",
    )
    return new

seq

seq(
    target="ASEQ",
    *,
    order_by=None,
    by=None,
    start_at=1,
    check_uniqueness=False
)

Derive a 1-based sequence number within each group.

Generates a 1-based integer sequence that uniquely identifies each record within a grouping partition. The dataset is sorted by order_by columns within each by partition before numbering — ensuring deterministic, reproducible sequence values. The sort and the window numbering are appended to the lazy plan.

Parameters:

Name Type Description Default
target str

Name of the output sequence variable (e.g. "AESEQ", "ASEQ").

'ASEQ'
order_by list[str] | None

Columns that define the sort order within each group. Records that tie keep their input order, as PROC SORT EQUALS. When None, the current row order is preserved.

None
by list[str] | None

Partition columns. Defaults to class constant _SEQ_DEFAULT_GROUPS.

None
start_at int

First sequence value (default 1).

1
check_uniqueness bool

If True, emit a warning when the combination of by + order_by does not uniquely identify each row (requires reading the key columns).

False

Returns:

Name Type Description
Self Self

A fresh namespace with target appended; call .to_frame() to materialise.

Examples:

SDTM sequence number::

ae = (
    raw_df.sdtm
    .seq("AESEQ", order_by=["AESTDTC"])
    .to_frame()
)

ADaM sequence number::

adae = (
    ae_df.adam.occds
    .seq("ASEQ", order_by=["ASTDT"], by=["USUBJID"])
    .to_frame()
)
Source code in src/fleet/core/_verb_mixin.py
def seq(
    self,
    target: str = "ASEQ",
    *,
    order_by: list[str] | None = None,
    by: list[str] | None = None,
    start_at: int = 1,
    check_uniqueness: bool = False,
) -> Self:
    """Derive a 1-based sequence number within each group.

    Generates a 1-based integer sequence that uniquely identifies each
    record within a grouping partition.  The dataset is sorted by
    *order_by* columns within each *by* partition before numbering
    — ensuring deterministic, reproducible sequence values.  The
    sort and the window numbering are appended to the lazy plan.

    Args:
        target: Name of the output sequence variable (e.g. ``"AESEQ"``,
            ``"ASEQ"``).
        order_by: Columns that define the sort order within each group.
            Records that tie keep their input order, as PROC SORT
            EQUALS.  When ``None``, the current row order is preserved.
        by: Partition columns.  Defaults to class constant
            ``_SEQ_DEFAULT_GROUPS``.
        start_at: First sequence value (default ``1``).
        check_uniqueness: If ``True``, emit a warning when the
            combination of *by* + *order_by* does not uniquely
            identify each row (requires reading the key columns).

    Returns:
        Self: A fresh namespace with *target* appended; call
            ``.to_frame()`` to materialise.

    Examples:
        SDTM sequence number::

            ae = (
                raw_df.sdtm
                .seq("AESEQ", order_by=["AESTDTC"])
                .to_frame()
            )

        ADaM sequence number::

            adae = (
                ae_df.adam.occds
                .seq("ASEQ", order_by=["ASTDT"], by=["USUBJID"])
                .to_frame()
            )
    """
    grps = by or list(self._SEQ_DEFAULT_GROUPS)

    lf = self._lazy
    if order_by:
        lf = lf.sort(order_by, maintain_order=True)

    if check_uniqueness and order_by:
        key_cols = grps + list(order_by)
        schema_names = lf.collect_schema().names()
        available = [c for c in key_cols if c in schema_names]
        counts = lf.select(
            pl.len().alias("__n_total__"),
            pl.struct(available).n_unique().alias("__n_unique__"),
        ).collect()
        n_total = int(counts["__n_total__"][0])
        n_unique = int(counts["__n_unique__"][0])
        if n_unique < n_total:
            warnings.warn(
                f"Rows are not unique by {available}: "
                f"{n_total} rows but only {n_unique} unique combinations. "
                f"{target} values may be arbitrary for tied rows.",
                stacklevel=2,
            )

    seq_expr = (pl.int_range(pl.len()).over(grps) + start_at).cast(pl.Int64).alias(target)
    from fleet.core.lineage import append_verb_node

    params = {"target": target, "order_by": order_by, "by": by}
    if start_at != 1:
        params["start_at"] = start_at
    return append_verb_node(
        self._with_lazy(lf.with_columns(seq_expr)),
        target,
        "seq",
        [*grps, *(order_by or [])],
        params,
    )

validate

validate(
    dataset_or_domain,
    version=None,
    rules_engine_path=None,
    custom_rules=None,
    report="smart",
    on_fail="warn",
)

Run CDISC conformance validation and report the findings.

Returns a namespace copy so the chain can continue after validation; the full :class:~fleet.validation.models.ValidationResult is retrievable via the :attr:last_validation property. The report is emitted through the "fleet.validation" logger (stdout by default — see :mod:fleet.core.log).

Every input comes from a run setup (:func:fleet.validation.run_setup.build_run_setup): an explicit argument, then the study config found from the working directory, then FLEET_RULES_ENGINE (engine only), then the built-in default (SDTMIG 3.4, ADaMIG 1.3). The namespace gives the standard. The report header prints each input with its source.

Issues are cross-linked to the chain's own variable lineage, so a finding on a column this pipeline derived also reports the verb that produced it (see :func:fleet.validation.lineage_join.enrich_with_lineage).

Parameters:

Name Type Description Default
dataset_or_domain str

Domain code (SDTM: e.g. "DM") or dataset name (ADaM: e.g. "ADSL").

required
version str | None

IG version, "3-4" or "3.4". Defaults to sdtm.ig_version / adam.ig_version in the study config, else the built-in default.

None
rules_engine_path Path | None

Engine executable. Defaults to validation.engine_path, then FLEET_RULES_ENGINE, then the managed install.

None
custom_rules str | Path | None

Directory of custom rule YAML files, passed to the engine via -lr. Defaults to validation.custom_rules.

None
report Literal['smart', 'summary', 'full']

Report detail level — "smart" (default) for a deduplicated view grouping identical findings with row ranges, "summary" for one line per issue, "full" for every individual finding expanded.

'smart'
on_fail Literal['warn', 'raise', 'ignore']

What to do when a finding blocks (every CORE finding that validation.accepted in the study config does not list, ADR-0017) — "warn" (default) emits a UserWarning and continues, "raise" raises :class:~fleet.core.exceptions.ValidationError, "ignore" continues silently.

'warn'

Returns:

Name Type Description
Self Self

A namespace copy carrying the result in last_validation (for continued chaining).

Raises:

Type Description
ValidationSetupError

The validation could not run, in every on_fail mode: the dataset name belongs to the other standard (adae.adam.validate("AE")), the IG version is not supported, the custom rules directory is missing, or the engine crashed, timed out (validation.timeout) or wrote no report.

ValidationError

When a finding blocks and on_fail="raise".

DerivationError

On an invalid on_fail value.

Examples:

Validate an SDTM domain::

dm = (
    raw_df.sdtm
    .assign("DOMAIN", value="DM")
    .validate("DM")
    .to_frame()
)

Gate a CI pipeline on the ADaM validation outcome::

adsl = (
    dm_df.adam.adsl
    .validate("ADSL", on_fail="raise")
    .to_frame()
)
Source code in src/fleet/core/_verb_mixin.py
def validate(
    self,
    dataset_or_domain: str,
    version: str | None = None,
    rules_engine_path: Path | None = None,
    custom_rules: str | Path | None = None,
    report: Literal["smart", "summary", "full"] = "smart",
    on_fail: Literal["warn", "raise", "ignore"] = "warn",
) -> Self:
    """Run CDISC conformance validation and report the findings.

    Returns a namespace copy so the chain can continue after
    validation; the full :class:`~fleet.validation.models.ValidationResult`
    is retrievable via the :attr:`last_validation` property.  The
    report is emitted through the ``"fleet.validation"`` logger
    (stdout by default — see :mod:`fleet.core.log`).

    Every input comes from a run setup
    (:func:`fleet.validation.run_setup.build_run_setup`): an explicit
    argument, then the study config found from the working directory,
    then ``FLEET_RULES_ENGINE`` (engine only), then the built-in
    default (SDTMIG 3.4, ADaMIG 1.3).  The namespace gives the
    standard.  The report header prints each input with its source.

    Issues are cross-linked to the chain's own variable lineage, so a
    finding on a column this pipeline derived also reports the verb
    that produced it (see
    :func:`fleet.validation.lineage_join.enrich_with_lineage`).

    Args:
        dataset_or_domain: Domain code (SDTM: e.g. ``"DM"``) or
            dataset name (ADaM: e.g. ``"ADSL"``).
        version: IG version, ``"3-4"`` or ``"3.4"``.  Defaults to
            ``sdtm.ig_version`` / ``adam.ig_version`` in the study
            config, else the built-in default.
        rules_engine_path: Engine executable.  Defaults to
            ``validation.engine_path``, then ``FLEET_RULES_ENGINE``,
            then the managed install.
        custom_rules: Directory of custom rule YAML files, passed to
            the engine via ``-lr``.  Defaults to
            ``validation.custom_rules``.
        report: Report detail level — ``"smart"`` (default) for a
            deduplicated view grouping identical findings with row
            ranges, ``"summary"`` for one line per issue, ``"full"``
            for every individual finding expanded.
        on_fail: What to do when a finding blocks (every CORE finding
            that ``validation.accepted`` in the study config does not
            list, ADR-0017) — ``"warn"`` (default) emits a
            ``UserWarning`` and continues, ``"raise"`` raises
            :class:`~fleet.core.exceptions.ValidationError`,
            ``"ignore"`` continues silently.

    Returns:
        Self: A namespace copy carrying the result in
            ``last_validation`` (for continued chaining).

    Raises:
        ValidationSetupError: The validation could not run, in every
            *on_fail* mode: the dataset name belongs to the other
            standard (``adae.adam.validate("AE")``), the IG version is
            not supported, the custom rules directory is missing, or
            the engine crashed, timed out (``validation.timeout``) or
            wrote no report.
        ValidationError: When a finding blocks and
            ``on_fail="raise"``.
        DerivationError: On an invalid *on_fail* value.

    Examples:
        Validate an SDTM domain::

            dm = (
                raw_df.sdtm
                .assign("DOMAIN", value="DM")
                .validate("DM")
                .to_frame()
            )

        Gate a CI pipeline on the ADaM validation outcome::

            adsl = (
                dm_df.adam.adsl
                .validate("ADSL", on_fail="raise")
                .to_frame()
            )
    """
    from fleet.core.lineage import latest_lineage_of
    from fleet.validation.lineage_join import enrich_with_lineage
    from fleet.validation.run_setup import build_run_setup
    from fleet.validation.service import ValidationService

    _check_on_fail("validate", on_fail)
    setup = build_run_setup(
        name=dataset_or_domain,
        namespace=self._VALIDATE_STANDARD,
        version=version,
        custom_rules=custom_rules,
        engine=rules_engine_path,
    )
    svc = ValidationService(rules_engine_path=setup.engine.value)

    if setup.standard.value == "adam":
        result = svc.validate_adam(
            self.to_frame(),
            dataset=dataset_or_domain,
            version=setup.ig_version.value,
            custom_rules=setup.custom_rules.value,
            timeout=setup.timeout.value,
        )
    else:
        result = svc.validate_sdtm(
            self.to_frame(),
            domain=dataset_or_domain,
            version=setup.ig_version.value,
            custom_rules=setup.custom_rules.value,
            timeout=setup.timeout.value,
        )

    result.apply_setup(setup)
    enrich_with_lineage(result, latest_lineage_of(self))
    result.print_report(report_type=report)
    if result.could_not_run is not None:
        raise ValidationSetupError(
            f"CDISC validation of '{dataset_or_domain}' could not run: {result.could_not_run}"
        )

    new = copy.copy(self)
    new._last_validation = result
    if not result.is_valid:
        summary = (
            f"CDISC validation failed for '{dataset_or_domain}': "
            f"{len(result.errors)} error(s): findings that validation.accepted "
            "does not list. Access details via .last_validation."
        )
        _settle_on_fail(on_fail, summary, ValidationError)
    return new

compare

compare(
    base,
    *,
    keys,
    by=None,
    pairs=None,
    variables=None,
    abs_tol=0.0,
    rel_tol=0.0,
    ignore_trailing_whitespace=False,
    blank_is_missing=False,
    allow_duplicates=False,
    max_print=50,
    base_name=None,
    candidate_name=None,
    on_fail="warn"
)

Compare the chain against a base dataset, PROC COMPARE style.

The chain is the candidate and base is the reference it is measured against. The chain is materialised, paired with the base on keys through :func:fleet.compare, and the report is printed through the "fleet.comparison" logger (stdout by default — see :mod:fleet.core.log). Differences never stop the chain by default: the verb returns a namespace copy carrying the :class:~fleet.comparison.ComparisonReport as :attr:last_comparison, so the pipeline continues.

Parameters:

Name Type Description Default
base DataFrame | LazyFrame

The reference dataset, as a DataFrame or LazyFrame.

required
keys str | Sequence[str]

Variable(s) that identify one observation on each side. Required; the compare refuses to run when a key is missing or not unique on either side.

required
by str | Sequence[str] | None

Variable(s) the report is sectioned by. They are prepended to keys automatically, label the listing's group column, and give the observation and values summaries a per-group breakdown. A group present on one side only raises a flag; the verdict stays global.

None
pairs Mapping[str, str] | None

Base variable names mapped to the names the chain gives them, on top of the automatic name matching, so a renamed column is compared rather than reported missing. The report names a paired variable by its base name.

None
variables str | Sequence[str] | None

Restrict the comparison to these variables, in base names, so a work-in-progress chain is checked on the columns that are finished. What is outside the restriction is neither compared nor reported as missing.

None
abs_tol float

Absolute tolerance on the numeric variables; 0.0 (the default) is exact.

0.0
rel_tol float

Relative tolerance on the numeric variables, as a fraction of the base value; 0.0 (the default) is exact. A numeric pair differs when the absolute difference exceeds max(abs_tol, rel_tol * abs(base)).

0.0
ignore_trailing_whitespace bool

Strip trailing whitespace from both sides of a string before comparing, so a legacy SAS dataset's padded values equal the chain's stripped ones. Leading whitespace still differs.

False
blank_is_missing bool

Read an empty string as null on both sides, keys included, as SAS does. Off by default.

False
allow_duplicates bool

Pair duplicate keys by their position within each key group instead of refusing to run; the report then counts them, raises duplicate_keys and warns.

False
max_print MaxPrint

Print limits for the text report (differences per variable, a (per_variable, total) pair, or None for everything). The report's listing is never truncated.

50
base_name str | None

Label for the base in the report, when known.

None
candidate_name str | None

Label for the chain in the report, when known.

None
on_fail Literal['warn', 'raise', 'ignore']

What to do when the datasets differ — "warn" (default) emits a UserWarning and continues, "raise" raises :class:~fleet.core.exceptions.ComparisonError, "ignore" continues silently.

'warn'

Returns:

Name Type Description
Self Self

A namespace copy carrying the report in last_comparison (for continued chaining).

Raises:

Type Description
ComparisonError

When the datasets differ and on_fail="raise", or when the comparison cannot run (a key missing, duplicated or of an incompatible type).

DerivationError

On an invalid on_fail value.

Examples:

Prove an independently programmed ADAE matches its base, and keep chaining::

adae_qc = (
    ae_df.adam.occds
    .source("USUBJID")
    .source("AESEQ")
    .compare(adae_prod, keys=["USUBJID", "AESEQ"])
    .to_frame()
)

Gate a CI script on the comparison outcome::

adsl = (
    dm_df.adam.adsl
    .source("USUBJID")
    .compare(adsl_prod, keys="USUBJID", on_fail="raise")
    .to_frame()
)

Absorb the engine noise of a legacy SAS dataset without hiding a real difference::

advs = (
    vs_df.adam
    .source("USUBJID")
    .compare(
        advs_legacy,
        keys=["USUBJID", "PARAMCD", "AVISITN"],
        rel_tol=1e-9,
        ignore_trailing_whitespace=True,
    )
    .to_frame()
)

Section the comparison by treatment arm, so a difference in one arm stands out::

adsl = (
    dm_df.adam.adsl
    .source("USUBJID")
    .compare(adsl_prod, keys="USUBJID", by="TRT01P")
    .to_frame()
)

Check a work-in-progress chain on the variables that are finished, one of which the base names differently::

advs = (
    vs_df.adam
    .source("USUBJID")
    .compare(
        advs_prod,
        keys=["USUBJID", "PARAMCD"],
        pairs={"AVAL": "RESULT"},
        variables=["AVAL", "AVISIT"],
    )
    .to_frame()
)
Source code in src/fleet/core/_verb_mixin.py
def compare(
    self,
    base: pl.DataFrame | pl.LazyFrame,
    *,
    keys: str | Sequence[str],
    by: str | Sequence[str] | None = None,
    pairs: Mapping[str, str] | None = None,
    variables: str | Sequence[str] | None = None,
    abs_tol: float = 0.0,
    rel_tol: float = 0.0,
    ignore_trailing_whitespace: bool = False,
    blank_is_missing: bool = False,
    allow_duplicates: bool = False,
    max_print: MaxPrint = 50,
    base_name: str | None = None,
    candidate_name: str | None = None,
    on_fail: Literal["warn", "raise", "ignore"] = "warn",
) -> Self:
    """Compare the chain against a base dataset, PROC COMPARE style.

    The chain is the **candidate** and *base* is the reference it is
    measured against.  The chain is materialised, paired with the base
    on *keys* through :func:`fleet.compare`, and the report is printed
    through the ``"fleet.comparison"`` logger (stdout by default — see
    :mod:`fleet.core.log`).  Differences never stop the chain by
    default: the verb returns a namespace copy carrying the
    :class:`~fleet.comparison.ComparisonReport` as
    :attr:`last_comparison`, so the pipeline continues.

    Args:
        base: The reference dataset, as a DataFrame or LazyFrame.
        keys: Variable(s) that identify one observation on each side.
            Required; the compare refuses to run when a key is missing
            or not unique on either side.
        by: Variable(s) the report is sectioned by.  They are prepended
            to *keys* automatically, label the listing's ``group``
            column, and give the observation and values summaries a
            per-group breakdown.  A group present on one side only
            raises a flag; the verdict stays global.
        pairs: Base variable names mapped to the names the chain gives
            them, on top of the automatic name matching, so a renamed
            column is compared rather than reported missing.  The report
            names a paired variable by its **base** name.
        variables: Restrict the comparison to these variables, in
            **base** names, so a work-in-progress chain is checked on
            the columns that are finished.  What is outside the
            restriction is neither compared nor reported as missing.
        abs_tol: Absolute tolerance on the numeric variables; ``0.0``
            (the default) is exact.
        rel_tol: Relative tolerance on the numeric variables, as a
            fraction of the **base** value; ``0.0`` (the default) is
            exact.  A numeric pair differs when the absolute difference
            exceeds ``max(abs_tol, rel_tol * abs(base))``.
        ignore_trailing_whitespace: Strip trailing whitespace from both
            sides of a string before comparing, so a legacy SAS dataset's
            padded values equal the chain's stripped ones.  Leading
            whitespace still differs.
        blank_is_missing: Read an empty string as null on both sides,
            keys included, as SAS does.  Off by default.
        allow_duplicates: Pair duplicate keys by their position within
            each key group instead of refusing to run; the report then
            counts them, raises ``duplicate_keys`` and warns.
        max_print: Print limits for the text report (differences per
            variable, a ``(per_variable, total)`` pair, or ``None`` for
            everything).  The report's listing is never truncated.
        base_name: Label for the base in the report, when known.
        candidate_name: Label for the chain in the report, when known.
        on_fail: What to do when the datasets differ — ``"warn"``
            (default) emits a ``UserWarning`` and continues,
            ``"raise"`` raises
            :class:`~fleet.core.exceptions.ComparisonError`,
            ``"ignore"`` continues silently.

    Returns:
        Self: A namespace copy carrying the report in
            ``last_comparison`` (for continued chaining).

    Raises:
        ComparisonError: When the datasets differ and
            ``on_fail="raise"``, or when the comparison cannot run
            (a key missing, duplicated or of an incompatible type).
        DerivationError: On an invalid *on_fail* value.

    Examples:
        Prove an independently programmed ADAE matches its base, and
        keep chaining::

            adae_qc = (
                ae_df.adam.occds
                .source("USUBJID")
                .source("AESEQ")
                .compare(adae_prod, keys=["USUBJID", "AESEQ"])
                .to_frame()
            )

        Gate a CI script on the comparison outcome::

            adsl = (
                dm_df.adam.adsl
                .source("USUBJID")
                .compare(adsl_prod, keys="USUBJID", on_fail="raise")
                .to_frame()
            )

        Absorb the engine noise of a legacy SAS dataset without hiding
        a real difference::

            advs = (
                vs_df.adam
                .source("USUBJID")
                .compare(
                    advs_legacy,
                    keys=["USUBJID", "PARAMCD", "AVISITN"],
                    rel_tol=1e-9,
                    ignore_trailing_whitespace=True,
                )
                .to_frame()
            )

        Section the comparison by treatment arm, so a difference in one
        arm stands out::

            adsl = (
                dm_df.adam.adsl
                .source("USUBJID")
                .compare(adsl_prod, keys="USUBJID", by="TRT01P")
                .to_frame()
            )

        Check a work-in-progress chain on the variables that are
        finished, one of which the base names differently::

            advs = (
                vs_df.adam
                .source("USUBJID")
                .compare(
                    advs_prod,
                    keys=["USUBJID", "PARAMCD"],
                    pairs={"AVAL": "RESULT"},
                    variables=["AVAL", "AVISIT"],
                )
                .to_frame()
            )
    """
    from fleet.comparison import compare as compare_frames

    _check_on_fail("compare", on_fail)
    report = compare_frames(
        base,
        self.to_frame(),
        keys=keys,
        by=by,
        pairs=pairs,
        variables=variables,
        abs_tol=abs_tol,
        rel_tol=rel_tol,
        ignore_trailing_whitespace=ignore_trailing_whitespace,
        blank_is_missing=blank_is_missing,
        allow_duplicates=allow_duplicates,
        max_print=max_print,
        base_name=base_name,
        candidate_name=candidate_name,
    )
    report.print_report()

    new = copy.copy(self)
    new._last_comparison = report
    if not report.is_equal:
        summary = f"{report.summary}. Access details via .last_comparison."
        _settle_on_fail(on_fail, summary, ComparisonError)
    return new

select

select(
    columns=None,
    *,
    spec=None,
    dataset=None,
    drop_pattern="^_"
)

Select and reorder columns (lazily — nothing is materialised).

Resolution order:

  1. spec + dataset: derive the ordered column list from a define.yaml. Only columns present in the frame are kept.
  2. columns: explicit list to keep (in that order).
  3. Neither: keep all current columns (subject to drop_pattern).

With a spec on an ADaM namespace, a text column the define types date becomes the date part of a complete date, and one typed datetime the date-time of a value with hours and minutes. Anything else becomes null, with one warning at collect: select never imputes. SDTM columns and every *DTC stay text, because --DTC is character (SDTMIG 3.4 section 4.4).

drop_pattern (default r"^_"): regex applied before the explicit selection — columns whose names match are removed. This enforces the convention that _-prefixed columns are scratch variables. Set to None to disable (e.g. during debugging). A scratch name listed in columns is removed too, unless drop_pattern=None.

Parameters:

Name Type Description Default
columns str | list[str] | None

Explicit list of columns to keep (in order). A single string is one column name.

None
spec str | Path | None

Path to a define.yaml file.

None
dataset str | None

Dataset name within the spec.

None
drop_pattern str | None

Regex for columns to auto-drop.

'^_'

Returns:

Name Type Description
Self Self

A fresh namespace continuing from the selected plan.

Raises:

Type Description
DerivationError

When a name in columns is not in the frame (with a did-you-mean suggestion).

Examples:

Keep only spec columns::

dm = (
    raw_df.sdtm
    .select(spec="specs/sdtm/define.yaml", dataset="DM")
    .to_frame()
)
Source code in src/fleet/core/_verb_mixin.py
def select(
    self,
    columns: str | list[str] | None = None,
    *,
    spec: str | Path | None = None,
    dataset: str | None = None,
    drop_pattern: str | None = r"^_",
) -> Self:
    """Select and reorder columns (lazily — nothing is materialised).

    Resolution order:

    1. ``spec`` + ``dataset``: derive the ordered column list from a
       ``define.yaml``.  Only columns present in the frame are kept.
    2. ``columns``: explicit list to keep (in that order).
    3. Neither: keep all current columns (subject to ``drop_pattern``).

    With a spec on an ADaM namespace, a text column the define types
    ``date`` becomes the date part of a complete date, and one typed
    ``datetime`` the date-time of a value with hours and minutes.
    Anything else becomes null, with one warning at collect: select
    never imputes.  SDTM columns and every ``*DTC`` stay text, because
    ``--DTC`` is character (SDTMIG 3.4 section 4.4).

    ``drop_pattern`` (default ``r"^_"``): regex applied *before* the
    explicit selection — columns whose names match are removed.  This
    enforces the convention that ``_``-prefixed columns are scratch
    variables.  Set to ``None`` to disable (e.g. during debugging).
    A scratch name listed in *columns* is removed too, unless
    ``drop_pattern=None``.

    Args:
        columns: Explicit list of columns to keep (in order).  A single
            string is one column name.
        spec: Path to a ``define.yaml`` file.
        dataset: Dataset name within the spec.
        drop_pattern: Regex for columns to auto-drop.

    Returns:
        Self: A fresh namespace continuing from the selected plan.

    Raises:
        DerivationError: When a name in *columns* is not in the frame
            (with a did-you-mean suggestion).

    Examples:
        Keep only spec columns::

            dm = (
                raw_df.sdtm
                .select(spec="specs/sdtm/define.yaml", dataset="DM")
                .to_frame()
            )
    """
    schema = self._lazy.collect_schema()
    names = schema.names()

    if spec is None and columns is not None:
        columns = [columns] if isinstance(columns, str) else list(columns)
        require_columns("select(columns=...)", columns, names, where="the frame")

    # Step 1: drop scratch variables matching the pattern
    if drop_pattern is not None:
        pat = re.compile(drop_pattern)
        names = [c for c in names if not pat.search(c)]

    # Step 2: resolve explicit column list (spec takes priority over columns)
    col_list = columns
    type_map: dict[str, str] = {}
    if spec is not None:
        spec_path = Path(spec)
        col_list, type_map = self._spec_dataset_meta(spec_path, dataset)

    # Step 3: intersect with existing columns (preserving spec order)
    final_cols = names
    if col_list is not None:
        final_cols = [c for c in col_list if c in names]
        if spec is not None:
            missing = [c for c in col_list if c not in names]
            if missing:
                warnings.warn(
                    f"select(spec=...): {len(missing)} spec-declared column(s) "
                    f"are absent from the frame and were skipped: {missing}",
                    stacklevel=2,
                )
            computed = {node.name for node in getattr(self, "_lineage", [])}
            dropped = [c for c in names if c not in col_list and c in computed]
            if dropped:
                warnings.warn(
                    f"select(spec=...): dropping computed column(s) that are "
                    f"not declared in the spec: {dropped}",
                    stacklevel=2,
                )

    lf = self._lazy.select(final_cols)

    # Step 4: ADaM *DT and *DTM declared date/datetime are read from text.
    # SDTM and any *DTC stay text (SDTMIG 3.4 4.4); select never imputes.
    if type_map and self._VALIDATE_STANDARD == "adam":
        casts = []
        for col_name, spec_type in type_map.items():
            if col_name not in final_cols or col_name.upper().endswith("DTC"):
                continue
            dtype = schema.get(col_name)
            raw = pl.col(col_name)
            if spec_type == "date" and isinstance(dtype, pl.Datetime):
                casts.append(raw.cast(pl.Date))
                continue
            if dtype != pl.String:
                continue
            read = date_part(raw) if spec_type == "date" else datetime_part(raw)
            casts.append(
                warn_on_collect(
                    read,
                    (raw.str.strip_chars().fill_null("") != "") & read.is_null(),
                    lambda n, values, c=col_name, t=spec_type: (
                        f"select(spec=): {n} value(s) of {c} are not a complete {t} and "
                        "become null; select never imputes, so use .date(impute=) for a "
                        f"SAP rule. Values: {values}"
                    ),
                    dtype=pl.Date if spec_type == "date" else pl.Datetime("us"),
                    shown=raw,
                ).alias(col_name)
            )
        if casts:
            lf = lf.with_columns(casts)

    return self._with_lazy(lf)

from_spec

from_spec(
    spec_path,
    *,
    dataset=None,
    only=None,
    omit=None,
    strict=True,
    overwrite=False
)

Build a derivation pipeline from a YAML specification file.

Reads either a define.yaml (top-level datasets list where each variable carries a derivation block) or a simplified single-dataset spec (top-level variables list). Every algorithm: is resolved through the central spec registry (:mod:fleet.core.spec_registry), validated against its strict per-algorithm model, and executed via the matching namespace verb.

A top-level ct: block opts the spec into controlled-terminology validation::

ct:
  validate: true
  file: ct/cdisc_ct.yaml   # optional — loaded into the CT cache

With validate: true every assign that has a codelist (ct:, or the variable's codelist:) runs with validate_values=True: out-of-codelist values emit the standard warning naming dataset, variable, and codelist.

A derivation block is the verb call: algorithm: is the verb name and the keys are its keyword arguments (ADR-0008). An assign without ct: on a variable with codelist: checks its values against that codelist.

Inside a study, a ct: ID resolves to the class of that ID in the study's generated codelists.py (found from the first study_config.yaml above the spec's folder), so a spec step checks the same terms as assign(..., ct=<class>); an ID the file lacks falls back to the CT loaded in :func:fleet.get_validator. A codelists.py that disagrees with the study warns once per process (see :mod:fleet.ct.study_codelists).

Parameters:

Name Type Description Default
spec_path str | Path

Path to the YAML specification file.

required
dataset str | None

Dataset to execute from a multi-dataset define.yaml (e.g. dataset="DM"). May be omitted when the file contains a single dataset.

None
only list[str] | None

Optional allow-list — process only these variable names.

None
omit list[str] | None

Optional deny-list — skip these variable names; useful to override a spec variable with custom inline logic. Mutually exclusive with only.

None
strict bool

When True (default) an unknown algorithm: raises :class:~fleet.core.exceptions.SpecError. Pass False to restore the legacy warn-and-skip behaviour.

True
overwrite bool

When True, allow spec variables to overwrite columns that already exist in the frame. By default an overwrite raises SpecError unless the derivation is a declared carry-through (its source column is the target).

False

Returns:

Name Type Description
Self Self

A namespace pre-loaded with all spec-driven derivations; call .to_frame() to materialise.

Raises:

Type Description
SpecError

On unknown algorithms (strict mode), invalid or misspelled derivation fields, column overwrites, unknown fleet_spec_version, a merge block that does not give its variable, or any error raised while executing a variable — always naming file, dataset, and variable.

ValueError

When both only and omit are given, or when dataset is required/unknown.

Examples:

Build and materialise the DM domain from a spec::

dm = (
    raw_df.sdtm
    .from_spec("examples/cdiscpilot01/sdtm/define.yaml", dataset="DM")
    .to_frame()
)

Keep an inline derivation for one variable::

adsl = (
    dm_df.adam
    .from_spec("define.yaml", dataset="ADSL", omit=["TRTSDT"])
    .to_frame()
)
Source code in src/fleet/core/_verb_mixin.py
def from_spec(
    self,
    spec_path: str | Path,
    *,
    dataset: str | None = None,
    only: list[str] | None = None,
    omit: list[str] | None = None,
    strict: bool = True,
    overwrite: bool = False,
) -> Self:
    """Build a derivation pipeline from a YAML specification file.

    Reads either a ``define.yaml`` (top-level ``datasets`` list where
    each variable carries a ``derivation`` block) or a simplified
    single-dataset spec (top-level ``variables`` list).  Every
    ``algorithm:`` is resolved through the central spec registry
    (:mod:`fleet.core.spec_registry`), validated against its strict
    per-algorithm model, and executed via the matching namespace verb.

    A top-level ``ct:`` block opts the spec into controlled-terminology
    validation::

        ct:
          validate: true
          file: ct/cdisc_ct.yaml   # optional — loaded into the CT cache

    With ``validate: true`` every ``assign`` that has a codelist
    (``ct:``, or the variable's ``codelist:``) runs with
    ``validate_values=True``: out-of-codelist values emit the
    standard warning naming dataset, variable, and codelist.

    A derivation block is the verb call: ``algorithm:`` is the verb
    name and the keys are its keyword arguments (ADR-0008).  An
    ``assign`` without ``ct:`` on a variable with ``codelist:`` checks
    its values against that codelist.

    Inside a study, a ``ct:`` ID resolves to the class of
    that ID in the study's generated ``codelists.py`` (found from the
    first ``study_config.yaml`` above the spec's folder), so a spec
    step checks the same terms as ``assign(..., ct=<class>)``; an ID
    the file lacks falls back to the CT loaded in
    :func:`fleet.get_validator`.  A ``codelists.py`` that disagrees
    with the study warns once per process (see
    :mod:`fleet.ct.study_codelists`).

    Args:
        spec_path: Path to the YAML specification file.
        dataset: Dataset to execute from a multi-dataset define.yaml
            (e.g. ``dataset="DM"``).  May be omitted when the file
            contains a single dataset.
        only: Optional allow-list — process only these variable names.
        omit: Optional deny-list — skip these variable names; useful to
            override a spec variable with custom inline logic.
            Mutually exclusive with *only*.
        strict: When ``True`` (default) an unknown ``algorithm:`` raises
            :class:`~fleet.core.exceptions.SpecError`.  Pass ``False``
            to restore the legacy warn-and-skip behaviour.
        overwrite: When ``True``, allow spec variables to overwrite
            columns that already exist in the frame.  By default an
            overwrite raises ``SpecError`` unless the derivation is a
            declared carry-through (its source column *is* the target).

    Returns:
        Self: A namespace pre-loaded with all spec-driven derivations;
            call ``.to_frame()`` to materialise.

    Raises:
        SpecError: On unknown algorithms (strict mode), invalid or
            misspelled derivation fields, column overwrites, unknown
            ``fleet_spec_version``, a ``merge`` block that does not
            give its variable, or any error raised while executing
            a variable — always naming file, dataset, and variable.
        ValueError: When both *only* and *omit* are given, or when
            *dataset* is required/unknown.

    Examples:
        Build and materialise the DM domain from a spec::

            dm = (
                raw_df.sdtm
                .from_spec("examples/cdiscpilot01/sdtm/define.yaml", dataset="DM")
                .to_frame()
            )

        Keep an inline derivation for one variable::

            adsl = (
                dm_df.adam
                .from_spec("define.yaml", dataset="ADSL", omit=["TRTSDT"])
                .to_frame()
            )
    """
    from fleet.core import spec_registry

    if only is not None and omit is not None:
        raise DerivationError(
            "Cannot specify both only= and omit= in from_spec(). "
            "Use only= to allow-list variables, or omit= to deny-list them."
        )

    path = Path(spec_path)
    spec = load_define_spec(path)
    _check_spec_version(spec, source=str(path))
    _import_derivations_module(spec, source=str(path))

    standard = self._VALIDATE_STANDARD
    ds_name, raw_vars = _extract_spec_variables(spec, dataset)

    ns = self

    # Spec-level CT config: `ct: {validate: true, file: <path>}`.
    if spec.ct.enabled:
        ct_file = spec.ct.file
        if ct_file:
            from fleet.ct.validator import get_validator

            ct_path = Path(ct_file)
            if not ct_path.is_absolute():
                ct_path = path.parent / ct_path
            try:
                get_validator().load_ct_file(ct_path)
            except Exception as err:
                raise SpecError(
                    f"{path}: ct.file '{ct_file}' could not be loaded: {err}"
                ) from err
        ns = copy.copy(ns)
        ns._spec_ct_validate = True
    elif "enabled" in spec.ct.model_fields_set:
        # An explicit `ct: {validate: false}` switches the default CT check off.
        ns = copy.copy(ns)
        ns._spec_ct_validate = False

    # ct: IDs resolve to the study's codelists.py classes, as ct=<class> inline.
    if any(drv.get("ct") or codelist for _, drv, codelist in raw_vars):
        from fleet.ct.study_codelists import spec_codelists

        codelists = spec_codelists(path)
        if codelists:
            ns = copy.copy(ns)
            ns._spec_codelists = codelists
    # Row steps run after the variable they are anchored on (ADR-0034).
    all_names: list[str] = []
    row_steps: list[dict[str, Any]] = []
    if spec.datasets is not None:
        ds_entry = spec.select(dataset)
        all_names = [v.name for v in ds_entry.variables]
        row_steps = list(ds_entry.row_steps)
        _check_row_steps(row_steps, all_names, f"{path} → dataset {ds_name}")
    position = {n: i for i, n in enumerate(all_names)}

    def _flush(ns: Any, before: int) -> Any:
        while row_steps and position.get(row_steps[0].get("after"), -1) < before:
            ns = _run_row_step(ns, row_steps.pop(0), f"{path} → dataset {ds_name}")
        return ns

    for var_name, drv, codelist in raw_vars:
        ns = _flush(ns, position.get(var_name, len(all_names)))
        if only is not None and var_name not in only:
            continue
        if omit is not None and var_name in omit:
            continue

        context = f"{path} → dataset {ds_name} → variable {var_name}"
        alg = drv.get("algorithm")
        algo = spec_registry.get_algorithm(standard, str(alg)) if alg else None
        if algo is None:
            from fleet.tools.migrate_spec import ALGORITHM_RENAMES

            if str(alg) in ALGORITHM_RENAMES:
                suffix = (
                    f" '{alg}' is the pre-ADR-0008 spelling of '{ALGORITHM_RENAMES[str(alg)]}';"
                    " rewrite the file with `fleet migrate --spec <define.yaml> --write`."
                )
            else:
                hint = spec_registry.suggest_algorithm(standard, str(alg))
                suffix = f" Did you mean '{hint}'?" if hint else ""
            if strict:
                raise SpecError(
                    f"{context}: unknown algorithm '{alg}' for the {standard} "
                    f"spec path.{suffix} Pass strict=False to warn and skip instead."
                )
            warnings.warn(
                f"from_spec: skipping variable '{var_name}' — "
                f"algorithm '{alg}' is not supported in spec-driven mode.{suffix}",
                stacklevel=2,
            )
            continue

        try:
            drv = spec_registry.with_codelist(standard, drv, codelist)
            model = spec_registry.model_for(standard, algo.name)
            var = model.model_validate({**drv, "target": var_name})
        except Exception as err:
            raise SpecError(f"{context}: {err}") from err

        columns = ns._lazy.collect_schema().names()

        # Auto-flush when a declared dependency is not yet committed.
        deps = getattr(var, "depends_on", None) or []
        if deps and any(d not in columns for d in deps):
            ns = ns._materialise_then(ns.to_frame())
            columns = ns._lazy.collect_schema().names()

        if (
            algo.takes_target
            and algo.overwrite_guard
            and not overwrite
            and var.target in columns
            and not spec_registry.is_identity_copy(var)
        ):
            raise SpecError(
                f"{context}: would overwrite the existing column "
                f"'{var.target}'. Pass overwrite=True to allow spec "
                f"overwrites, or omit=[{var.target!r}] to keep the "
                f"inline derivation."
            )

        try:
            ns = spec_registry.execute_variable(ns, var)
        except SpecError:
            raise
        except Exception as err:
            raise SpecError(f"{context}: {type(err).__name__}: {err}") from err
        if algo.name == "merge" and var_name not in ns._lazy.collect_schema().names():
            raise SpecError(
                f"{context}: the merge block does not give the column '{var_name}'. "
                f"Add it to keep:, or check that dataset '{drv.get('dataset')}' has it."
            )

    ns = _flush(ns, len(all_names) + 1)
    if spec.datasets is not None:
        ns = copy.copy(ns)
        ns._spec_source = (spec, ds_name)
    return ns

to_spec_yaml

to_spec_yaml(dataset=None, path=None, *, predecessor=None)

Serialise the pipeline's lineage into a define.yaml spec.

The natural prototype-then-freeze workflow: build the dataset inline, then emit the equivalent derivation: blocks instead of retyping them. Variables are emitted in frame column order: derived variables carry their derivation: block (last derivation wins when a target was re-derived); CDISC-named carry-through columns are listed as metadata-only entries; raw columns that violate the CDISC name pattern are skipped. Verbs covered by the spec registry emit real blocks; verbs that are not spec-expressible (or whose arguments cannot be serialised, e.g. inline Polars expressions) emit an algorithm: derivation stub with a callable: placeholder and a # TODO comment carrying the verb name and sources, and a warning names them. A column that a verb added with no lineage node (merge) also gets a stub. Auto-generated by-product columns (e.g. --DTF imputation flags) are listed without a derivation.

A verb that removes or adds rows (whereclauses, nodup with keep=, derive_param) goes to the dataset key row_steps:, in pipeline order, each step anchored after: the variable it follows (ADR-0034). A step a define.yaml cannot hold is written as algorithm: TODO and from_spec refuses it until it is edited.

The output validates against Fleet's define-spec JSON schema; study-level fields are placeholders to review before use.

Parameters:

Name Type Description Default
dataset str | None

Dataset name for the emitted spec. Defaults to the pipeline's domain context (set by assign("DOMAIN", ...)) or "DATASET".

None
path str | Path | None

Optional file path — when given, the YAML is also written there (parent directories are created).

None
predecessor str | None

Name of the upstream dataset this ADaM pipeline was built from (e.g. "DM"). When given, variables carried through unchanged — metadata-only entries and pure algorithm: assign copies of CDISC-named columns — are emitted with origin: Predecessor and predecessor: '<DATASET>.<SOURCE>'. The emitted YAML stays the explicit, reviewable source of truth; Fleet never infers Predecessor at Define-XML generation time. Only a column present at the start of the chain can be a Predecessor: a column a verb added with no lineage (for example merge()) gets a TODO stub and the warning. ADaM pipelines only.

None

Returns:

Name Type Description
str str

The define.yaml document.

Examples:

Freeze an inline DM prototype to a spec::

ns = (
    raw_df.sdtm
    .assign("DOMAIN", value="DM")
    .assign("USUBJID", source="subject_id")
)
yaml_text = ns.to_spec_yaml(dataset="DM", path="specs/define_dm.yaml")
dm = raw_df.sdtm.from_spec("specs/define_dm.yaml", dataset="DM").to_frame()

Freeze an ADSL prototype, labelling DM carry-throughs::

adsl_ns.to_spec_yaml(dataset="ADSL", predecessor="DM")
Source code in src/fleet/core/_verb_mixin.py
def to_spec_yaml(
    self,
    dataset: str | None = None,
    path: str | Path | None = None,
    *,
    predecessor: str | None = None,
) -> str:
    """Serialise the pipeline's lineage into a define.yaml spec.

    The natural prototype-then-freeze workflow: build the dataset
    inline, then emit the equivalent ``derivation:`` blocks instead
    of retyping them.  Variables are emitted in frame column order:
    derived variables carry their ``derivation:`` block (last
    derivation wins when a target was re-derived); CDISC-named
    carry-through columns are listed as metadata-only entries; raw
    columns that violate the CDISC name pattern are skipped.  Verbs
    covered by the spec registry emit real blocks; verbs that are
    not spec-expressible (or whose arguments cannot be serialised,
    e.g. inline Polars expressions) emit an ``algorithm: derivation``
    stub with a ``callable:`` placeholder and a ``# TODO`` comment carrying the verb name and
    sources, and a warning names them.  A column that a verb added
    with no lineage node (``merge``) also gets a stub.  Auto-generated
    by-product columns (e.g. ``--DTF`` imputation flags) are listed
    without a derivation.

    A verb that removes or adds rows (``whereclauses``, ``nodup`` with
    ``keep=``, ``derive_param``) goes to the dataset key
    ``row_steps:``, in pipeline order, each step anchored ``after:``
    the variable it follows (ADR-0034).  A step a define.yaml cannot
    hold is written as ``algorithm: TODO`` and ``from_spec`` refuses
    it until it is edited.

    The output validates against Fleet's define-spec JSON schema;
    study-level fields are placeholders to review before use.

    Args:
        dataset: Dataset name for the emitted spec.  Defaults to the
            pipeline's domain context (set by ``assign("DOMAIN",
            ...)``) or ``"DATASET"``.
        path: Optional file path — when given, the YAML is also
            written there (parent directories are created).
        predecessor: Name of the upstream dataset this ADaM pipeline
            was built from (e.g. ``"DM"``).  When given, variables
            carried through unchanged — metadata-only entries and
            pure ``algorithm: assign`` copies of CDISC-named columns
            — are emitted with ``origin: Predecessor`` and
            ``predecessor: '<DATASET>.<SOURCE>'``.  The emitted YAML
            stays the explicit, reviewable source of truth; Fleet
            never infers Predecessor at Define-XML generation time.
            Only a column present at the start of the chain can be a
            Predecessor: a column a verb added with no lineage (for
            example ``merge()``) gets a TODO stub and the warning.
            ADaM pipelines only.

    Returns:
        str: The define.yaml document.

    Examples:
        Freeze an inline DM prototype to a spec::

            ns = (
                raw_df.sdtm
                .assign("DOMAIN", value="DM")
                .assign("USUBJID", source="subject_id")
            )
            yaml_text = ns.to_spec_yaml(dataset="DM", path="specs/define_dm.yaml")
            dm = raw_df.sdtm.from_spec("specs/define_dm.yaml", dataset="DM").to_frame()

        Freeze an ADSL prototype, labelling DM carry-throughs::

            adsl_ns.to_spec_yaml(dataset="ADSL", predecessor="DM")
    """
    from fleet.core import spec_registry
    from fleet.core.lineage import latest_lineage_of
    from fleet.validation.run_setup import DEFAULT_IG_VERSIONS

    standard = self._VALIDATE_STANDARD
    ds_name = (dataset or getattr(self, "_domain", None) or "DATASET").upper()

    pred_ds = predecessor.upper() if predecessor else None
    if pred_ds:
        if standard != "adam":
            raise DerivationError(
                "to_spec_yaml(predecessor=...) applies to ADaM pipelines only — "
                "SDTM variables built from raw data are Collected/Derived, not "
                "Predecessor."
            )
        if not re.match(r"^[A-Z_][A-Z0-9_]{0,7}$", pred_ds):
            raise DerivationError(
                f"to_spec_yaml(): predecessor {predecessor!r} is not a valid "
                "dataset name (expected e.g. 'DM' or 'ADSL')."
            )

    schema = self._lazy.collect_schema()
    derived = {n.name: n for n in latest_lineage_of(self)}
    name_pattern = re.compile(r"^[A-Z_][A-Z0-9_]{0,7}$")
    # The columns at the start of the chain: only they can be a carry-through
    # or a Predecessor; a column a verb added with no lineage node is a stub.
    root_lazy = getattr(self, "_root_lazy", None)
    root_cols = set(root_lazy.collect_schema().names()) if root_lazy is not None else None

    entries: list[tuple[dict[str, Any], str | None]] = []
    for col in schema.names():
        node = derived.get(col)
        if node is None and not name_pattern.match(col):
            continue  # raw scratch column — not part of the dataset spec
        entry: dict[str, Any] = {
            "name": col,
            "label": col,
            "type": _dtype_to_spec_type(schema.get(col)),
        }
        comment: str | None = None
        if node is None and root_cols is not None and col not in root_cols:
            comment = (
                f"TODO: column {col} was added by a verb that records no lineage "
                "(for example merge) — replace this stub with a registered "
                "derivation (algorithm: derivation, callable: <name>)."
            )
            entry["derivation"] = {"algorithm": "derivation", "callable": f"TODO_{col}"}
        elif node is not None:
            status, block, meta = spec_registry.derivation_from_lineage(standard, node)
            if meta.get("label"):
                entry["label"] = str(meta["label"])[:40]
            if meta.get("origin"):
                entry["origin"] = meta["origin"]
            if status == "ok":
                # A pure copy of a CDISC-named upstream column is a
                # Predecessor in Define-XML terms; an explicit origin
                # captured from the verb call wins.
                source = str(block.get("source") or col) if block else col
                if (
                    pred_ds
                    and "origin" not in entry
                    and block
                    and block.get("algorithm") == "assign"
                    and block.get("value") is None
                    and not block.get("ct")
                    and name_pattern.match(source)
                    and (root_cols is None or source in root_cols)
                ):
                    entry["origin"] = "Predecessor"
                    entry["predecessor"] = f"{pred_ds}.{source}"
                entry["derivation"] = block
            elif status == "stub":
                srcs = ", ".join(node.sources) if node.sources else "none"
                comment = (
                    f"TODO: verb '{node.verb}' (sources: {srcs}) is not spec-expressible "
                    f"— replace this stub with a registered derivation "
                    f"(algorithm: derivation, callable: <name>)."
                )
                entry["derivation"] = {
                    "algorithm": "derivation",
                    "callable": f"TODO_{col}",
                }
            # status == "byproduct": metadata-only (auto-generated column).
        elif pred_ds:
            # Metadata-only carry-through — flowed in untouched.
            entry["origin"] = "Predecessor"
            entry["predecessor"] = f"{pred_ds}.{col}"
        entries.append((entry, comment))

    if not entries:
        raise DerivationError(
            "to_spec_yaml(): nothing to serialise — the frame has no derived "
            "variables and no CDISC-named columns."
        )

    stubs = [entry["name"] for entry, comment in entries if comment]
    if stubs:
        warnings.warn(
            f"to_spec_yaml: {len(stubs)} variable(s) are TODO stubs "
            f"({', '.join(stubs)}): from_spec fails on them until you replace each "
            "callable: TODO_<name> with a registered @derivation, and Define-XML has "
            "no method text for them.",
            stacklevel=2,
        )

    var_names = [e["name"] for e, _ in entries]
    keys = [k for k in ("STUDYID", "USUBJID") if k in var_names] or var_names[:1]
    row_steps = _freeze_row_steps(self, var_names)
    todo_steps = [st["verb"] for st in row_steps if st["algorithm"] == "TODO"]
    if todo_steps:
        warnings.warn(
            f"to_spec_yaml: {len(todo_steps)} row step(s) cannot be written "
            f"({', '.join(todo_steps)}): from_spec fails on algorithm: TODO in "
            "row_steps until you replace each one (ADR-0034).",
            stacklevel=2,
        )

    study = {
        "id": "STUDY",
        "name": "STUDY",
        "description": (
            "Generated by Fleet to_spec_yaml() — replace with the study description."
        ),
        "protocol_name": "STUDY",
        "originator": "Fleet",
        "standard": "SDTMIG" if standard == "sdtm" else "ADAMIG",
        "standard_version": DEFAULT_IG_VERSIONS[standard],
    }
    head = {"fleet_spec_version": SUPPORTED_SPEC_VERSION, "study": study}
    ds_head: dict[str, Any] = {
        "name": ds_name,
        "label": ds_name,
        "structure": "One record per observation (review)",
        "keys": keys,
    }
    if row_steps:
        ds_head["row_steps"] = row_steps

    lines: list[str] = [
        "# Generated by Fleet to_spec_yaml() — review study fields, labels, keys,",
        "# and TODO stubs before use.",
    ]
    if todo_steps:
        lines.append(
            "# TODO: row_steps holds algorithm: TODO for "
            f"{', '.join(todo_steps)} — write each step before from_spec runs."
        )
    lines += [
        yaml.safe_dump(head, sort_keys=False, allow_unicode=True).rstrip(),
        "datasets:",
        _indent_yaml(yaml.safe_dump([ds_head], sort_keys=False, allow_unicode=True), 2),
        "    variables:",
    ]
    for entry, comment in entries:
        block_text = _indent_yaml(
            yaml.safe_dump([entry], sort_keys=False, allow_unicode=True), 6
        )
        if comment:
            block_lines: list[str] = []
            for ln in block_text.splitlines():
                if ln.strip().startswith("derivation:"):
                    pad = ln[: len(ln) - len(ln.lstrip())]
                    block_lines.append(f"{pad}# {comment}")
                block_lines.append(ln)
            block_text = "\n".join(block_lines)
        lines.append(block_text)

    text = "\n".join(lines) + "\n"
    if path is not None:
        dest = Path(path)
        dest.parent.mkdir(parents=True, exist_ok=True)
        dest.write_text(text, encoding="utf-8")
    return text

nodup

nodup(*, subset, sort_by=None, keep=None, descending=False)

Detect duplicate rows and optionally deduplicate after sorting.

Materialises the pipeline, logs duplicate diagnostics through the "fleet" logger (stdout by default — see :mod:fleet.core.log), and optionally removes duplicates. When keep is None (default) the verb operates in report-only mode — duplicates are reported but the frame is returned unchanged, making it safe to insert anywhere in a pipeline for auditing purposes. The duplicate rows are also attached to the returned namespace and retrievable via :attr:last_nodup_report.

Parameters:

Name Type Description Default
subset list[str]

Column(s) that define the uniqueness key.

required
sort_by list[str] | None

Column(s) to sort by before deduplication. Required when keep is not None.

None
keep Literal['first', 'last'] | None

Which duplicate to retain after sorting: "first", "last", or None (report only, no removal).

None
descending bool | list[bool]

Sort direction(s) for sort_by. A single bool applies to all columns; a list must match sort_by length. A missing value is the lowest value, as SAS: it sorts first when ascending and last when descending. Records that tie on sort_by keep their input order, as PROC SORT EQUALS, so keep="last" takes the last input record of a tie.

False

Returns:

Name Type Description
Self Self

A fresh namespace wrapping the (optionally deduplicated) frame, carrying the duplicates in last_nodup_report; call .to_frame() to materialise.

Raises:

Type Description
DerivationError

If keep is set but sort_by is not provided, or keep is not one of the accepted values.

References

SAS PROC SORT with EQUALS and NODUPKEY; ADR-0023 for the place of a missing value.

Examples:

Report-only mode (audit duplicates without removing)::

ae = (
    raw_df.sdtm
    .assign("USUBJID", source="subject_id")
    .nodup(subset=["USUBJID", "AEDECOD", "AESTDTC"])
    .to_frame()
)

Sort and deduplicate (keep latest record)::

adae = (
    ae_df.adam.occds
    .nodup(
        subset=["USUBJID", "AEDECOD"],
        sort_by=["ASTDT", "ASEQ"],
        keep="first",
        descending=True,
    )
    .to_frame()
)
Source code in src/fleet/core/_verb_mixin.py
def nodup(
    self,
    *,
    subset: list[str],
    sort_by: list[str] | None = None,
    keep: Literal["first", "last"] | None = None,
    descending: bool | list[bool] = False,
) -> Self:
    """Detect duplicate rows and optionally deduplicate after sorting.

    Materialises the pipeline, logs duplicate diagnostics through the
    ``"fleet"`` logger (stdout by default — see :mod:`fleet.core.log`),
    and optionally removes duplicates.  When ``keep`` is ``None``
    (default) the verb operates in report-only mode — duplicates are
    reported but the frame is returned unchanged, making it safe to
    insert anywhere in a pipeline for auditing purposes.  The
    duplicate rows are also attached to the returned namespace and
    retrievable via :attr:`last_nodup_report`.

    Args:
        subset: Column(s) that define the uniqueness key.
        sort_by: Column(s) to sort by before deduplication.  Required
            when ``keep`` is not ``None``.
        keep: Which duplicate to retain after sorting:
            ``"first"``, ``"last"``, or ``None`` (report only, no removal).
        descending: Sort direction(s) for *sort_by*.  A single ``bool``
            applies to all columns; a list must match *sort_by* length.
            A missing value is the lowest value, as SAS: it sorts
            first when ascending and last when descending.  Records
            that tie on *sort_by* keep their input order, as PROC SORT
            EQUALS, so ``keep="last"`` takes the last input record of a
            tie.

    Returns:
        Self: A fresh namespace wrapping the (optionally deduplicated)
            frame, carrying the duplicates in ``last_nodup_report``;
            call ``.to_frame()`` to materialise.

    Raises:
        DerivationError: If ``keep`` is set but ``sort_by`` is not
            provided, or ``keep`` is not one of the accepted values.

    References:
        SAS PROC SORT with EQUALS and NODUPKEY; ADR-0023 for the place
        of a missing value.

    Examples:
        Report-only mode (audit duplicates without removing)::

            ae = (
                raw_df.sdtm
                .assign("USUBJID", source="subject_id")
                .nodup(subset=["USUBJID", "AEDECOD", "AESTDTC"])
                .to_frame()
            )

        Sort and deduplicate (keep latest record)::

            adae = (
                ae_df.adam.occds
                .nodup(
                    subset=["USUBJID", "AEDECOD"],
                    sort_by=["ASTDT", "ASEQ"],
                    keep="first",
                    descending=True,
                )
                .to_frame()
            )
    """
    if keep is not None and sort_by is None:
        raise DerivationError("sort_by is required when keep is set.")
    if keep is not None and keep not in ("first", "last"):
        raise DerivationError(f"keep must be 'first', 'last', or None — got {keep!r}.")

    fleet_log.ensure_default_handler()
    df = self._lazy.collect()

    # Detect duplicates
    dup_mask = df.select(pl.struct(subset).is_duplicated()).to_series()
    n_dup = dup_mask.sum()
    dup_rows = df.filter(dup_mask)

    if n_dup == 0:
        logger.info("[NODUP] No duplicates found (subset: %s)", ", ".join(subset))
        new = self._materialise_then(df)
        new._nodup_report = dup_rows
        return self._record_nodup(new, subset, sort_by, keep, descending)

    # Summarise duplicate groups
    dup_groups = (
        dup_rows.group_by(subset)
        .agg(pl.len().alias("__count"))
        .sort("__count", descending=True)
    )
    n_groups = len(dup_groups)

    logger.info(
        "[NODUP] %d duplicate rows across %d key group(s) (subset: %s)",
        n_dup,
        n_groups,
        ", ".join(subset),
    )
    # Show top offending groups (up to 5)
    top = dup_groups.head(5)
    logger.info("[NODUP] Top offenders:")
    for row in top.iter_rows(named=True):
        count = row.pop("__count")
        key_str = ", ".join(f"{k}={v}" for k, v in row.items())
        logger.info("  %s  (%d rows)", key_str, count)

    # Report-only mode
    if keep is None:
        logger.info("[NODUP] Action: report only (keep=None)")
        new = self._materialise_then(df)
        new._nodup_report = dup_rows
        return new

    # Sort then deduplicate: a missing value is lowest, as SAS (ADR-0023); ties keep input order.
    flags = list(descending) if isinstance(descending, list) else [descending] * len(sort_by)
    df = df.sort(sort_by, descending=flags, nulls_last=flags, maintain_order=True)
    df = df.unique(subset=subset, keep=keep, maintain_order=True)

    logger.info(
        "[NODUP] Action: keeping '%s' after sorting by %s (descending=%s)",
        keep,
        sort_by,
        descending,
    )
    logger.info("[NODUP] Result: %d rows (removed %d)", len(df), n_dup - n_groups)
    new = self._materialise_then(df)
    new._nodup_report = dup_rows
    return self._record_nodup(new, subset, sort_by, keep, descending)

options: show_root_heading: false heading_level: 3 members_order: source filters: ["!^_"]

Exceptions

fleet.core.exceptions

Core exceptions for fleet.

The verb-layer exceptions use dual inheritance so both catch styles work: except FleetError (the Fleet-native style) and the legacy builtin style (except ValueError / except TypeError / except LookupError) that predates the hierarchy.

  • :class:DerivationError — a verb received invalid values or arguments (missing column, unparseable expression, unsupported option, ...). Catchable as ValueError.
  • :class:VerbUsageError — a verb was called with a wrong type. Catchable as TypeError.
  • :class:PinError — a cross-domain verb could not resolve a pinned reference domain. Catchable as LookupError.

FleetError

Bases: Exception

Base exception for all fleet errors.

Source code in src/fleet/core/exceptions.py
class FleetError(Exception):
    """Base exception for all fleet errors."""

DerivationError

Bases: FleetError, ValueError

Raised when a derivation verb receives invalid values or arguments.

Dual-inherits from ValueError so legacy except ValueError handlers keep working.

Source code in src/fleet/core/exceptions.py
class DerivationError(FleetError, ValueError):
    """Raised when a derivation verb receives invalid values or arguments.

    Dual-inherits from ``ValueError`` so legacy ``except ValueError``
    handlers keep working.
    """

VerbUsageError

Bases: FleetError, TypeError

Raised when a verb is called with arguments of the wrong type.

Dual-inherits from TypeError so legacy except TypeError handlers keep working.

Source code in src/fleet/core/exceptions.py
class VerbUsageError(FleetError, TypeError):
    """Raised when a verb is called with arguments of the wrong type.

    Dual-inherits from ``TypeError`` so legacy ``except TypeError``
    handlers keep working.
    """

PinError

Bases: FleetError, LookupError

Raised when a pinned reference domain cannot be resolved.

Dual-inherits from LookupError so legacy except LookupError handlers keep working.

Source code in src/fleet/core/exceptions.py
class PinError(FleetError, LookupError):
    """Raised when a pinned reference domain cannot be resolved.

    Dual-inherits from ``LookupError`` so legacy ``except LookupError``
    handlers keep working.
    """

SDTMError

Bases: FleetError

Raised when SDTM namespace operations fail.

Source code in src/fleet/core/exceptions.py
class SDTMError(FleetError):
    """Raised when SDTM namespace operations fail."""

ADAMError

Bases: FleetError

Raised when ADaM namespace operations fail.

Source code in src/fleet/core/exceptions.py
class ADAMError(FleetError):
    """Raised when ADaM namespace operations fail."""

CTError

Bases: FleetError

Raised when controlled terminology operations fail.

Source code in src/fleet/core/exceptions.py
class CTError(FleetError):
    """Raised when controlled terminology operations fail."""

CTNotFoundError

Bases: CTError, LookupError

Raised when the CDISC Library has no such resource (HTTP 404), unlike a 401 or a network error.

Source code in src/fleet/core/exceptions.py
class CTNotFoundError(CTError, LookupError):
    """Raised when the CDISC Library has no such resource (HTTP 404), unlike a 401 or a network error."""

IOError

Bases: FleetError

Raised when data loading or saving fails.

Source code in src/fleet/core/exceptions.py
class IOError(FleetError):  # noqa: A001
    """Raised when data loading or saving fails."""

SpecError

Bases: FleetError

Raised when a YAML specification is invalid.

Source code in src/fleet/core/exceptions.py
class SpecError(FleetError):
    """Raised when a YAML specification is invalid."""

SpecSchemaError

Bases: SpecError, ValueError

Raised when a define.yaml fails its JSON schema.

A ValueError too, so code written for the earlier ValueError keeps working; the CLI prints it as one clean message, with no traceback.

Source code in src/fleet/core/exceptions.py
class SpecSchemaError(SpecError, ValueError):
    """Raised when a define.yaml fails its JSON schema.

    A ``ValueError`` too, so code written for the earlier ``ValueError``
    keeps working; the CLI prints it as one clean message, with no traceback.
    """

ValidationError

Bases: FleetError

Raised when CDISC validation encounters a fatal error.

Source code in src/fleet/core/exceptions.py
class ValidationError(FleetError):
    """Raised when CDISC validation encounters a fatal error."""

ValidationSetupError

Bases: FleetError, ValueError

Raised when a validation could not run: its run setup was refused.

Examples: the namespace and the dataset name point to different standards, or the IG version is not supported. The verb raises it in every on_fail mode, because no rule was reached.

Source code in src/fleet/core/exceptions.py
class ValidationSetupError(FleetError, ValueError):
    """Raised when a validation could not run: its run setup was refused.

    Examples: the namespace and the dataset name point to different
    standards, or the IG version is not supported.  The verb raises it in
    every ``on_fail`` mode, because no rule was reached.
    """

StudyRunError

Bases: FleetError

Raised when a study run cannot plan or build a dataset.

Examples: no define file under the study's metadata directories, a dataset name the define files do not declare, an input that no seed, earlier step, declared path or data directory provides, or a seed that is also a step of the plan.

Source code in src/fleet/core/exceptions.py
class StudyRunError(FleetError):
    """Raised when a study run cannot plan or build a dataset.

    Examples: no define file under the study's metadata directories, a
    dataset name the define files do not declare, an input that no seed,
    earlier step, declared path or data directory provides, or a seed
    that is also a step of the plan.
    """

ComparisonError

Bases: FleetError, ValueError

Raised when a comparison cannot run: keys missing, duplicated or incompatible between the base and the candidate.

Differences between the two datasets never raise from :func:fleet.compare; they are reported. The pipeline verb .compare(..., on_fail="raise") is the one place that turns a difference into this error, on request. Dual-inherits from ValueError so except ValueError handlers keep working.

Source code in src/fleet/core/exceptions.py
class ComparisonError(FleetError, ValueError):
    """Raised when a comparison cannot run: keys missing, duplicated or
    incompatible between the base and the candidate.

    Differences between the two datasets never raise from
    :func:`fleet.compare`; they are reported.  The pipeline verb
    ``.compare(..., on_fail="raise")`` is the one place that turns a
    difference into this error, on request.  Dual-inherits from
    ``ValueError`` so ``except ValueError`` handlers keep working.
    """

TLGError

Bases: FleetError

Raised when TLG namespace operations fail.

Source code in src/fleet/core/exceptions.py
class TLGError(FleetError):
    """Raised when TLG namespace operations fail."""

SchemaError

Bases: TLGError

Raised when a DataFrame fails TLG spec validation.

Source code in src/fleet/core/exceptions.py
class SchemaError(TLGError):
    """Raised when a DataFrame fails TLG spec validation."""

options: show_root_heading: true heading_level: 3 filters: ["!^_"]