Skip to content

API reference

Generated from the source. The documented public surface is everything exported from the top-level ehrlint package; the modules below are where it lives.

Running an audit

ehrlint.audit

Running the check battery and assembling a report.

One function, :func:run_audit. It resolves the checks, runs each one, records skips separately from passes, validates that every finding's evidence really exists in the input, and computes the exit code.

The distinction the whole report hangs on: a skipped check is not a passed check. A clean report that quietly skipped six of ten checks is worse than a dirty one, because it reads as reassurance. Skips are first-class in the summary and the exit code logic, and the report prints them above the findings.

AuditSummary dataclass

Counts a reader needs before looking at anything else.

Source code in src/ehrlint/audit.py
@dataclass
class AuditSummary:
    """Counts a reader needs before looking at anything else."""

    n_checks_requested: int = 0
    n_checks_run: int = 0
    n_checks_skipped: int = 0
    n_findings: int = 0
    n_fired: int = 0
    n_errors: int = 0
    n_warnings: int = 0
    n_info: int = 0
    n_subjects: int = 0
    n_events: int = 0
    worst_severity: str | None = None

    def to_dict(self) -> dict[str, Any]:
        """JSON-safe dict."""
        return {
            "n_checks_requested": self.n_checks_requested,
            "n_checks_run": self.n_checks_run,
            "n_checks_skipped": self.n_checks_skipped,
            "n_findings": self.n_findings,
            "n_fired": self.n_fired,
            "n_errors": self.n_errors,
            "n_warnings": self.n_warnings,
            "n_info": self.n_info,
            "n_subjects": self.n_subjects,
            "n_events": self.n_events,
            "worst_severity": self.worst_severity,
        }

    def to_markdown(self) -> str:
        """A compact summary table."""
        lines = [
            "| metric | value |",
            "| --- | --- |",
            f"| subjects | {self.n_subjects} |",
            f"| events | {self.n_events} |",
            f"| checks run | {self.n_checks_run} of {self.n_checks_requested} |",
            f"| checks skipped | {self.n_checks_skipped} |",
            f"| findings that fired | {self.n_fired} |",
            f"| errors | {self.n_errors} |",
            f"| warnings | {self.n_warnings} |",
            f"| worst severity | {self.worst_severity or 'none'} |",
        ]
        if self.n_checks_skipped:
            lines.append("")
            lines.append(
                f"> {self.n_checks_skipped} check(s) did not run. A skipped check is not "
                "a passed check -- see the Skipped section for why."
            )
        return "\n".join(lines)

to_dict

to_dict() -> dict[str, Any]

JSON-safe dict.

Source code in src/ehrlint/audit.py
def to_dict(self) -> dict[str, Any]:
    """JSON-safe dict."""
    return {
        "n_checks_requested": self.n_checks_requested,
        "n_checks_run": self.n_checks_run,
        "n_checks_skipped": self.n_checks_skipped,
        "n_findings": self.n_findings,
        "n_fired": self.n_fired,
        "n_errors": self.n_errors,
        "n_warnings": self.n_warnings,
        "n_info": self.n_info,
        "n_subjects": self.n_subjects,
        "n_events": self.n_events,
        "worst_severity": self.worst_severity,
    }

to_markdown

to_markdown() -> str

A compact summary table.

Source code in src/ehrlint/audit.py
def to_markdown(self) -> str:
    """A compact summary table."""
    lines = [
        "| metric | value |",
        "| --- | --- |",
        f"| subjects | {self.n_subjects} |",
        f"| events | {self.n_events} |",
        f"| checks run | {self.n_checks_run} of {self.n_checks_requested} |",
        f"| checks skipped | {self.n_checks_skipped} |",
        f"| findings that fired | {self.n_fired} |",
        f"| errors | {self.n_errors} |",
        f"| warnings | {self.n_warnings} |",
        f"| worst severity | {self.worst_severity or 'none'} |",
    ]
    if self.n_checks_skipped:
        lines.append("")
        lines.append(
            f"> {self.n_checks_skipped} check(s) did not run. A skipped check is not "
            "a passed check -- see the Skipped section for why."
        )
    return "\n".join(lines)

AuditReport dataclass

The complete result of one audit.

Source code in src/ehrlint/audit.py
@dataclass
class AuditReport:
    """The complete result of one audit."""

    task: str
    data_hash: str
    findings: list[Finding] = field(default_factory=list)
    skipped: list[SkippedCheck] = field(default_factory=list)
    summary: AuditSummary = field(default_factory=AuditSummary)
    warnings: list[str] = field(default_factory=list)
    context: dict[str, Any] = field(default_factory=dict)
    check_metadata: list[dict[str, str]] = field(default_factory=list)
    started: datetime | None = None
    duration_s: float = 0.0
    fail_on: Severity = Severity.ERROR

    @property
    def fired(self) -> list[Finding]:
        """Findings that actually report a problem, worst first."""
        return sorted(
            [f for f in self.findings if f.fired],
            key=lambda f: (-f.severity.rank, f.check_id),
        )

    @property
    def passed(self) -> list[Finding]:
        """Findings from checks that ran and found nothing."""
        return [f for f in self.findings if not f.fired]

    @property
    def ok(self) -> bool:
        """Whether nothing fired at or above ``fail_on``."""
        return not any(f.severity.at_least(self.fail_on) for f in self.fired)

    @property
    def exit_code(self) -> int:
        """SPEC §5.1: 0 when clean at the threshold, 1 otherwise."""
        return 0 if self.ok else 1

    def by_severity(self, severity: Severity) -> list[Finding]:
        """Fired findings at one severity."""
        return [f for f in self.fired if f.severity is severity]

    def findings_for(self, check_id: str) -> list[Finding]:
        """Every finding from one check, worst first.

        A check may emit more than one: LK001 describes post-index events as an
        observation *and* flags a leaky feature matrix as an error.
        """
        key = check_id.strip().upper()
        return sorted(
            [f for f in self.findings if f.check_id == key],
            key=lambda f: (-f.severity.rank, f.name),
        )

    def finding(self, check_id: str) -> Finding | None:
        """The most serious finding from one check, or None if it skipped.

        Returns the one that **fired** where there is one, not the first
        emitted. A caller asking "what did LK001 find?" must not be handed the
        descriptive observation while an error sits behind it.
        """
        candidates = self.findings_for(check_id)
        if not candidates:
            return None
        return next((f for f in candidates if f.fired), candidates[0])

    def was_skipped(self, check_id: str) -> bool:
        """Whether a check skipped."""
        key = check_id.strip().upper()
        return any(s.check_id == key for s in self.skipped)

    def to_dict(self) -> dict[str, Any]:
        """The SPEC §6.4 report JSON."""
        return {
            "task": self.task,
            "data_hash": self.data_hash,
            "findings": [f.to_dict() for f in self.findings],
            "skipped": [s.to_dict() for s in self.skipped],
            "summary": self.summary.to_dict(),
            "warnings": self.warnings,
            "context": self.context,
            "check_metadata": self.check_metadata,
            "fail_on": self.fail_on.value,
            "exit_code": self.exit_code,
            "started": self.started.isoformat() if self.started else None,
            "duration_s": round(self.duration_s, 4),
            "ehrlint_version": _version(),
        }

    def write_json(self, path: str | Path) -> Path:
        """Write the report JSON."""
        import json

        target = Path(path)
        target.parent.mkdir(parents=True, exist_ok=True)
        target.write_text(json.dumps(self.to_dict(), indent=2, default=str))
        return target

    def write_findings_jsonl(self, path: str | Path) -> Path:
        """Write the findings as JSONL (SPEC §6.3)."""
        from ehrlint.schemas.findings import write_findings_jsonl

        write_findings_jsonl(self.findings, str(path))
        return Path(path)

    def write_markdown(self, path: str | Path) -> Path:
        """Write the Markdown report."""
        from ehrlint.report.builder import render_markdown

        target = Path(path)
        target.parent.mkdir(parents=True, exist_ok=True)
        target.write_text(render_markdown(self), encoding="utf-8")
        return target

    def write_html(self, outdir: str | Path) -> Path:
        """Write the HTML report and its figures."""
        from ehrlint.report.builder import write_report

        return write_report(self, outdir)["html"]

    def write_all(self, outdir: str | Path) -> dict[str, Path]:
        """Write every artifact: HTML, Markdown, JSON, findings JSONL, figures."""
        from ehrlint.report.builder import write_report

        return write_report(self, outdir)

    def to_markdown(self) -> str:
        """Render the full Markdown report as a string."""
        from ehrlint.report.builder import render_markdown

        return render_markdown(self)

fired property

fired: list[Finding]

Findings that actually report a problem, worst first.

passed property

passed: list[Finding]

Findings from checks that ran and found nothing.

ok property

ok: bool

Whether nothing fired at or above fail_on.

exit_code property

exit_code: int

SPEC §5.1: 0 when clean at the threshold, 1 otherwise.

by_severity

by_severity(severity: Severity) -> list[Finding]

Fired findings at one severity.

Source code in src/ehrlint/audit.py
def by_severity(self, severity: Severity) -> list[Finding]:
    """Fired findings at one severity."""
    return [f for f in self.fired if f.severity is severity]

findings_for

findings_for(check_id: str) -> list[Finding]

Every finding from one check, worst first.

A check may emit more than one: LK001 describes post-index events as an observation and flags a leaky feature matrix as an error.

Source code in src/ehrlint/audit.py
def findings_for(self, check_id: str) -> list[Finding]:
    """Every finding from one check, worst first.

    A check may emit more than one: LK001 describes post-index events as an
    observation *and* flags a leaky feature matrix as an error.
    """
    key = check_id.strip().upper()
    return sorted(
        [f for f in self.findings if f.check_id == key],
        key=lambda f: (-f.severity.rank, f.name),
    )

finding

finding(check_id: str) -> Finding | None

The most serious finding from one check, or None if it skipped.

Returns the one that fired where there is one, not the first emitted. A caller asking "what did LK001 find?" must not be handed the descriptive observation while an error sits behind it.

Source code in src/ehrlint/audit.py
def finding(self, check_id: str) -> Finding | None:
    """The most serious finding from one check, or None if it skipped.

    Returns the one that **fired** where there is one, not the first
    emitted. A caller asking "what did LK001 find?" must not be handed the
    descriptive observation while an error sits behind it.
    """
    candidates = self.findings_for(check_id)
    if not candidates:
        return None
    return next((f for f in candidates if f.fired), candidates[0])

was_skipped

was_skipped(check_id: str) -> bool

Whether a check skipped.

Source code in src/ehrlint/audit.py
def was_skipped(self, check_id: str) -> bool:
    """Whether a check skipped."""
    key = check_id.strip().upper()
    return any(s.check_id == key for s in self.skipped)

to_dict

to_dict() -> dict[str, Any]

The SPEC §6.4 report JSON.

Source code in src/ehrlint/audit.py
def to_dict(self) -> dict[str, Any]:
    """The SPEC §6.4 report JSON."""
    return {
        "task": self.task,
        "data_hash": self.data_hash,
        "findings": [f.to_dict() for f in self.findings],
        "skipped": [s.to_dict() for s in self.skipped],
        "summary": self.summary.to_dict(),
        "warnings": self.warnings,
        "context": self.context,
        "check_metadata": self.check_metadata,
        "fail_on": self.fail_on.value,
        "exit_code": self.exit_code,
        "started": self.started.isoformat() if self.started else None,
        "duration_s": round(self.duration_s, 4),
        "ehrlint_version": _version(),
    }

write_json

write_json(path: str | Path) -> Path

Write the report JSON.

Source code in src/ehrlint/audit.py
def write_json(self, path: str | Path) -> Path:
    """Write the report JSON."""
    import json

    target = Path(path)
    target.parent.mkdir(parents=True, exist_ok=True)
    target.write_text(json.dumps(self.to_dict(), indent=2, default=str))
    return target

write_findings_jsonl

write_findings_jsonl(path: str | Path) -> Path

Write the findings as JSONL (SPEC §6.3).

Source code in src/ehrlint/audit.py
def write_findings_jsonl(self, path: str | Path) -> Path:
    """Write the findings as JSONL (SPEC §6.3)."""
    from ehrlint.schemas.findings import write_findings_jsonl

    write_findings_jsonl(self.findings, str(path))
    return Path(path)

write_markdown

write_markdown(path: str | Path) -> Path

Write the Markdown report.

Source code in src/ehrlint/audit.py
def write_markdown(self, path: str | Path) -> Path:
    """Write the Markdown report."""
    from ehrlint.report.builder import render_markdown

    target = Path(path)
    target.parent.mkdir(parents=True, exist_ok=True)
    target.write_text(render_markdown(self), encoding="utf-8")
    return target

write_html

write_html(outdir: str | Path) -> Path

Write the HTML report and its figures.

Source code in src/ehrlint/audit.py
def write_html(self, outdir: str | Path) -> Path:
    """Write the HTML report and its figures."""
    from ehrlint.report.builder import write_report

    return write_report(self, outdir)["html"]

write_all

write_all(outdir: str | Path) -> dict[str, Path]

Write every artifact: HTML, Markdown, JSON, findings JSONL, figures.

Source code in src/ehrlint/audit.py
def write_all(self, outdir: str | Path) -> dict[str, Path]:
    """Write every artifact: HTML, Markdown, JSON, findings JSONL, figures."""
    from ehrlint.report.builder import write_report

    return write_report(self, outdir)

to_markdown

to_markdown() -> str

Render the full Markdown report as a string.

Source code in src/ehrlint/audit.py
def to_markdown(self) -> str:
    """Render the full Markdown report as a string."""
    from ehrlint.report.builder import render_markdown

    return render_markdown(self)

run_audit

run_audit(
    ctx: AuditContext,
    checks: list[str] | None = None,
    *,
    fail_on: Severity | str = Severity.ERROR,
    validate_evidence: bool = True,
) -> AuditReport

Run the check battery against a context.

Parameters:

Name Type Description Default
ctx AuditContext

The resolved inputs.

required
checks list[str] | None

Check ids to run. None or empty runs all of them.

None
fail_on Severity | str

The severity at which the audit is considered failed.

ERROR
validate_evidence bool

Assert each finding's example subjects exist in the input. On by default — it is the mechanical guard against a check reporting rows it invented.

True

Returns:

Name Type Description
An AuditReport

class:AuditReport.

Source code in src/ehrlint/audit.py
def run_audit(
    ctx: AuditContext,
    checks: list[str] | None = None,
    *,
    fail_on: Severity | str = Severity.ERROR,
    validate_evidence: bool = True,
) -> AuditReport:
    """Run the check battery against a context.

    Args:
        ctx: The resolved inputs.
        checks: Check ids to run. None or empty runs all of them.
        fail_on: The severity at which the audit is considered failed.
        validate_evidence: Assert each finding's example subjects exist in the
            input. On by default — it is the mechanical guard against a check
            reporting rows it invented.

    Returns:
        An :class:`AuditReport`.
    """
    import time

    threshold = Severity(fail_on) if isinstance(fail_on, str) else fail_on
    selected: list[Check] = resolve_checks(checks)
    started = datetime.now(UTC)
    clock = time.perf_counter()

    findings: list[Finding] = []
    skipped: list[SkippedCheck] = []

    for check in selected:
        try:
            result = check.run(ctx)
        except Exception as exc:
            # A crashing check is recorded as skipped, not as a pass. Letting
            # it abort the run would lose the other nine checks' results.
            skipped.append(
                SkippedCheck(
                    check_id=check.id,
                    name=check.name,
                    reason=(
                        f"the check raised {type(exc).__name__}: {exc}. This is a bug in "
                        "ehrlint, not a finding about your data"
                    ),
                )
            )
            continue

        if isinstance(result, SkippedCheck):
            skipped.append(result)
            continue

        for finding in result:
            if validate_evidence:
                try:
                    finding.validate_evidence(ctx.events)
                except ValueError as exc:
                    raise CheckError(str(exc), check_id=check.id) from exc
            findings.append(finding)

    duration = time.perf_counter() - clock
    findings.sort(key=lambda f: (f.check_id, f.name))

    fired = [f for f in findings if f.fired]
    worst = max((f.severity for f in fired), key=lambda s: s.rank, default=None)

    summary = AuditSummary(
        n_checks_requested=len(selected),
        n_checks_run=len(selected) - len(skipped),
        n_checks_skipped=len(skipped),
        n_findings=len(findings),
        n_fired=len(fired),
        n_errors=len([f for f in fired if f.severity is Severity.ERROR]),
        n_warnings=len([f for f in fired if f.severity is Severity.WARNING]),
        n_info=len([f for f in findings if f.severity is Severity.INFO]),
        n_subjects=ctx.n_subjects,
        n_events=ctx.events.height,
        worst_severity=worst.value if worst else None,
    )

    return AuditReport(
        task=ctx.task.task,
        data_hash=ctx.data_hash,
        findings=findings,
        skipped=sorted(skipped, key=lambda s: s.check_id),
        summary=summary,
        warnings=ctx.all_warnings(),
        context=ctx.describe(),
        check_metadata=[
            c.metadata() if hasattr(c, "metadata") else {"id": c.id, "name": c.name}
            for c in selected
        ],
        started=started,
        duration_s=duration,
        fail_on=threshold,
    )

The context

ehrlint.context

The audit context: everything a check needs, resolved once.

Index dates are the expensive, fiddly part — they come either from an event code or from a labels table, and every check needs them — so they are resolved once here and cached rather than recomputed per check.

This module is an addition to the SPEC §4.1 layout. §5.2 names AuditContext.from_meds(...) as public API but gives it no home; putting it in checks/base.py would make the check protocol import the loaders, and putting it in cli.py would make it unavailable to the Python API. See docs/decisions.md D-005.

AuditContext dataclass

The resolved inputs for one audit.

Attributes:

Name Type Description
events DataFrame

The canonical event table.

task TaskSpec

The task specification.

splits Splits | None

Split assignments, if supplied.

features FeatureMatrix | None

A feature matrix, if supplied.

labels DataFrame | None

A labels frame with subject_id, index_date, label.

source_format str

meds or omop.

source_path str | None

Where the data came from.

dataset_metadata dict[str, Any]

Whatever the MEDS manifest said.

warnings list[str]

Non-fatal problems found while loading.

Source code in src/ehrlint/context.py
@dataclass
class AuditContext:
    """The resolved inputs for one audit.

    Attributes:
        events: The canonical event table.
        task: The task specification.
        splits: Split assignments, if supplied.
        features: A feature matrix, if supplied.
        labels: A labels frame with ``subject_id``, ``index_date``, ``label``.
        source_format: ``meds`` or ``omop``.
        source_path: Where the data came from.
        dataset_metadata: Whatever the MEDS manifest said.
        warnings: Non-fatal problems found while loading.
    """

    events: pl.DataFrame
    task: TaskSpec
    splits: Splits | None = None
    features: FeatureMatrix | None = None
    labels: pl.DataFrame | None = None
    source_format: str = "canonical"
    source_path: str | None = None
    dataset_metadata: dict[str, Any] = field(default_factory=dict)
    warnings: list[str] = field(default_factory=list)

    _index_cache: pl.DataFrame | None = field(default=None, repr=False, compare=False)

    # -- construction ---------------------------------------------------

    @classmethod
    def from_meds(
        cls,
        data_dir: str | Path,
        *,
        task_spec: str | Path | TaskSpec,
        splits_path: str | Path | None = None,
        labels_path: str | Path | None = None,
        features_path: str | Path | None = None,
        encounter_column: str | None = None,
    ) -> AuditContext:
        """Build a context from a MEDS dataset directory.

        When ``splits_path`` is omitted, the dataset's own
        ``metadata/subject_splits.parquet`` is used if present — that is where
        MEDS keeps them, and requiring a separate file would be busywork.
        """
        events = read_meds_events(data_dir, encounter_column=encounter_column)
        task = _resolve_task(task_spec)

        warnings = validate_events(events, source="meds")
        warnings.extend(validate_with_meds_package(events))

        resolved_splits = None
        if splits_path is not None:
            resolved_splits = _load_splits(splits_path)
        else:
            discovered = find_meds_splits(data_dir)
            if discovered is not None:
                resolved_splits = Splits.from_meds(discovered, id_map=read_subject_id_map(data_dir))
                warnings.append(
                    f"using the dataset's own splits at {discovered.name}; pass "
                    "--splits to override"
                )

        return cls(
            events=events,
            task=task,
            splits=resolved_splits,
            features=read_feature_matrix(features_path) if features_path else None,
            labels=read_labels(labels_path) if labels_path else None,
            source_format="meds",
            source_path=str(data_dir),
            dataset_metadata=read_dataset_metadata(data_dir),
            warnings=warnings,
        )

    @classmethod
    def from_omop(
        cls,
        data_dir: str | Path,
        *,
        task_spec: str | Path | TaskSpec,
        splits_path: str | Path | None = None,
        labels_path: str | Path | None = None,
        features_path: str | Path | None = None,
    ) -> AuditContext:
        """Build a context from an OMOP CDM extract."""
        events = read_omop_events(data_dir)
        task = _resolve_task(task_spec)
        warnings = validate_events(events, source="omop")
        warnings.append("OMOP tables found: " + ", ".join(omop_tables_present(data_dir)))
        return cls(
            events=events,
            task=task,
            splits=_load_splits(splits_path) if splits_path else None,
            features=read_feature_matrix(features_path) if features_path else None,
            labels=read_labels(labels_path) if labels_path else None,
            source_format="omop",
            source_path=str(data_dir),
            warnings=warnings,
        )

    @classmethod
    def from_frames(
        cls,
        events: pl.DataFrame,
        *,
        task_spec: str | Path | TaskSpec,
        splits: Splits | dict[str, list[str]] | None = None,
        labels: pl.DataFrame | None = None,
        features: FeatureMatrix | None = None,
    ) -> AuditContext:
        """Build a context from in-memory frames, for tests and the library API."""
        from ehrlint.schemas.events import coerce_events

        resolved_splits: Splits | None
        if isinstance(splits, dict):
            resolved_splits = Splits.from_mapping(splits, source="<dict>")
        else:
            resolved_splits = splits

        coerced = coerce_events(events, source="frames")
        return cls(
            events=coerced,
            task=_resolve_task(task_spec),
            splits=resolved_splits,
            features=features,
            labels=labels,
            source_format="canonical",
            warnings=validate_events(coerced, source="frames"),
        )

    # -- derived views --------------------------------------------------

    @property
    def n_subjects(self) -> int:
        """Distinct subjects in the event data. The denominator for every rate."""
        return len(self.subject_ids)

    @property
    def subject_ids(self) -> list[str]:
        """Distinct subject ids, sorted."""
        return subjects(self.events)

    @property
    def data_hash(self) -> str:
        """Content hash of the event table, recorded in the report."""
        return events_hash(self.events)

    @property
    def has_encounters(self) -> bool:
        """Whether any event carries an encounter id."""
        return (
            ENCOUNTER_ID in self.events.columns
            and self.events[ENCOUNTER_ID].null_count() < self.events.height
        )

    @property
    def has_code_systems(self) -> bool:
        """Whether any event carries a code system."""
        return (
            CODE_SYSTEM in self.events.columns
            and self.events[CODE_SYSTEM].null_count() < self.events.height
        )

    def timed(self) -> pl.DataFrame:
        """Events with a timestamp. Static events are excluded."""
        return timed_events(self.events)

    def index_dates(self) -> pl.DataFrame:
        """Each subject's index date, resolved once and cached.

        Two sources, in this order:

        1. a labels table, whose ``prediction_time`` is the index date — this
           wins because it is what the model was actually trained against;
        2. the task spec's index event code.

        Returns:
            A frame with ``subject_id`` and ``index_date``. Subjects with no
            resolvable index date are **absent**, not given a fabricated one.
        """
        if self._index_cache is not None:
            return self._index_cache

        resolved: pl.DataFrame
        if self.labels is not None and "index_date" in self.labels.columns:
            resolved = (
                self.labels.select(["subject_id", "index_date"])
                .drop_nulls()
                .unique(subset=["subject_id"], keep="first")
            )
        elif self.task.index.event:
            matched = self._match_codes(
                self.timed(), {self.task.index.event}, self.task.index.code_system
            )
            aggregator = (
                pl.col(TIME).min() if self.task.index.occurrence == "first" else pl.col(TIME).max()
            )
            resolved = (
                matched.group_by(SUBJECT_ID)
                .agg(aggregator.alias("index_date"))
                .rename({SUBJECT_ID: "subject_id"})
            )
        else:
            resolved = pl.DataFrame(
                schema={"subject_id": pl.String, "index_date": pl.Datetime("us")}
            )

        self._index_cache = resolved.sort("subject_id")
        return self._index_cache

    def events_with_index(self) -> pl.DataFrame:
        """Timed events joined to their subject's index date.

        An inner join: a subject with no index date has no task to leak
        relative to, so their events are excluded rather than compared against
        a null.
        """
        index = self.index_dates()
        if index.height == 0:
            return (
                self.timed()
                .with_columns(pl.lit(None, dtype=pl.Datetime("us")).alias("index_date"))
                .clear()
            )
        return self.timed().join(index, left_on=SUBJECT_ID, right_on="subject_id", how="inner")

    def _match_codes(self, df: pl.DataFrame, codes: set[str], system: str | None) -> pl.DataFrame:
        """Filter events to a code set, honouring the system when given."""
        if not codes:
            return df.clear()
        predicate = pl.col(CODE).is_in(list(codes))
        if system is not None and self.has_code_systems:
            predicate = predicate & (pl.col(CODE_SYSTEM) == system)
        return df.filter(predicate)

    def match_code_sets(self, df: pl.DataFrame, code_sets: list[Any]) -> pl.DataFrame:
        """Filter events to any of several :class:`CodeSet` objects.

        A code set with no system matches the bare code in any vocabulary,
        which can cross-match; the context records a warning for that rather
        than refusing, since many datasets carry no systems at all.
        """
        if not code_sets:
            return df.clear()
        frames = [self._match_codes(df, set(cs.values), cs.system) for cs in code_sets]
        present = [f for f in frames if f.height]
        if not present:
            return df.clear()
        return pl.concat(present, how="vertical").unique()

    def subject_split(self) -> pl.DataFrame:
        """Subject id to split name, or an empty frame when no splits exist."""
        if self.splits is None:
            return pl.DataFrame(schema={"subject_id": pl.String, "split": pl.String})
        return self.splits.as_frame()

    def describe(self) -> dict[str, Any]:
        """Summary for the report header."""
        return {
            "source_format": self.source_format,
            "source_path": self.source_path,
            "data_hash": self.data_hash,
            "n_events": self.events.height,
            "n_subjects": self.n_subjects,
            "n_timed_events": self.timed().height,
            "n_static_events": self.events.height - self.timed().height,
            "has_encounters": self.has_encounters,
            "has_code_systems": self.has_code_systems,
            "n_index_dates": self.index_dates().height,
            "task": self.task.describe(),
            "splits": self.splits.describe() if self.splits else None,
            "features": self.features.describe() if self.features else None,
            "dataset_metadata": self.dataset_metadata,
        }

    def all_warnings(self) -> list[str]:
        """Loading warnings plus anything the task and splits flag.

        Collected here so the report shows every reason a result might be
        weaker than it looks, in one place above the findings.
        """
        out = list(self.warnings)
        out.extend(self.task.warnings())
        if self.splits is not None:
            out.extend(self.splits.warnings(set(self.subject_ids)))
        if self.features is not None:
            out.extend(self.features.warnings())
        if self.index_dates().height == 0:
            out.append(
                "no index date could be resolved for any subject, so every check that "
                "needs one will skip. Either set `index.event` to a code present in the "
                "data, or supply a labels table with prediction_time"
            )
        elif self.index_dates().height < self.n_subjects:
            missing = self.n_subjects - self.index_dates().height
            out.append(
                f"{missing} of {self.n_subjects} subject(s) have no resolvable index "
                "date and are excluded from index-relative checks"
            )
        return out

n_subjects property

n_subjects: int

Distinct subjects in the event data. The denominator for every rate.

subject_ids property

subject_ids: list[str]

Distinct subject ids, sorted.

data_hash property

data_hash: str

Content hash of the event table, recorded in the report.

has_encounters property

has_encounters: bool

Whether any event carries an encounter id.

has_code_systems property

has_code_systems: bool

Whether any event carries a code system.

from_meds classmethod

from_meds(
    data_dir: str | Path,
    *,
    task_spec: str | Path | TaskSpec,
    splits_path: str | Path | None = None,
    labels_path: str | Path | None = None,
    features_path: str | Path | None = None,
    encounter_column: str | None = None,
) -> AuditContext

Build a context from a MEDS dataset directory.

When splits_path is omitted, the dataset's own metadata/subject_splits.parquet is used if present — that is where MEDS keeps them, and requiring a separate file would be busywork.

Source code in src/ehrlint/context.py
@classmethod
def from_meds(
    cls,
    data_dir: str | Path,
    *,
    task_spec: str | Path | TaskSpec,
    splits_path: str | Path | None = None,
    labels_path: str | Path | None = None,
    features_path: str | Path | None = None,
    encounter_column: str | None = None,
) -> AuditContext:
    """Build a context from a MEDS dataset directory.

    When ``splits_path`` is omitted, the dataset's own
    ``metadata/subject_splits.parquet`` is used if present — that is where
    MEDS keeps them, and requiring a separate file would be busywork.
    """
    events = read_meds_events(data_dir, encounter_column=encounter_column)
    task = _resolve_task(task_spec)

    warnings = validate_events(events, source="meds")
    warnings.extend(validate_with_meds_package(events))

    resolved_splits = None
    if splits_path is not None:
        resolved_splits = _load_splits(splits_path)
    else:
        discovered = find_meds_splits(data_dir)
        if discovered is not None:
            resolved_splits = Splits.from_meds(discovered, id_map=read_subject_id_map(data_dir))
            warnings.append(
                f"using the dataset's own splits at {discovered.name}; pass "
                "--splits to override"
            )

    return cls(
        events=events,
        task=task,
        splits=resolved_splits,
        features=read_feature_matrix(features_path) if features_path else None,
        labels=read_labels(labels_path) if labels_path else None,
        source_format="meds",
        source_path=str(data_dir),
        dataset_metadata=read_dataset_metadata(data_dir),
        warnings=warnings,
    )

from_omop classmethod

from_omop(
    data_dir: str | Path,
    *,
    task_spec: str | Path | TaskSpec,
    splits_path: str | Path | None = None,
    labels_path: str | Path | None = None,
    features_path: str | Path | None = None,
) -> AuditContext

Build a context from an OMOP CDM extract.

Source code in src/ehrlint/context.py
@classmethod
def from_omop(
    cls,
    data_dir: str | Path,
    *,
    task_spec: str | Path | TaskSpec,
    splits_path: str | Path | None = None,
    labels_path: str | Path | None = None,
    features_path: str | Path | None = None,
) -> AuditContext:
    """Build a context from an OMOP CDM extract."""
    events = read_omop_events(data_dir)
    task = _resolve_task(task_spec)
    warnings = validate_events(events, source="omop")
    warnings.append("OMOP tables found: " + ", ".join(omop_tables_present(data_dir)))
    return cls(
        events=events,
        task=task,
        splits=_load_splits(splits_path) if splits_path else None,
        features=read_feature_matrix(features_path) if features_path else None,
        labels=read_labels(labels_path) if labels_path else None,
        source_format="omop",
        source_path=str(data_dir),
        warnings=warnings,
    )

from_frames classmethod

from_frames(
    events: DataFrame,
    *,
    task_spec: str | Path | TaskSpec,
    splits: Splits | dict[str, list[str]] | None = None,
    labels: DataFrame | None = None,
    features: FeatureMatrix | None = None,
) -> AuditContext

Build a context from in-memory frames, for tests and the library API.

Source code in src/ehrlint/context.py
@classmethod
def from_frames(
    cls,
    events: pl.DataFrame,
    *,
    task_spec: str | Path | TaskSpec,
    splits: Splits | dict[str, list[str]] | None = None,
    labels: pl.DataFrame | None = None,
    features: FeatureMatrix | None = None,
) -> AuditContext:
    """Build a context from in-memory frames, for tests and the library API."""
    from ehrlint.schemas.events import coerce_events

    resolved_splits: Splits | None
    if isinstance(splits, dict):
        resolved_splits = Splits.from_mapping(splits, source="<dict>")
    else:
        resolved_splits = splits

    coerced = coerce_events(events, source="frames")
    return cls(
        events=coerced,
        task=_resolve_task(task_spec),
        splits=resolved_splits,
        features=features,
        labels=labels,
        source_format="canonical",
        warnings=validate_events(coerced, source="frames"),
    )

timed

timed() -> pl.DataFrame

Events with a timestamp. Static events are excluded.

Source code in src/ehrlint/context.py
def timed(self) -> pl.DataFrame:
    """Events with a timestamp. Static events are excluded."""
    return timed_events(self.events)

index_dates

index_dates() -> pl.DataFrame

Each subject's index date, resolved once and cached.

Two sources, in this order:

  1. a labels table, whose prediction_time is the index date — this wins because it is what the model was actually trained against;
  2. the task spec's index event code.

Returns:

Type Description
DataFrame

A frame with subject_id and index_date. Subjects with no

DataFrame

resolvable index date are absent, not given a fabricated one.

Source code in src/ehrlint/context.py
def index_dates(self) -> pl.DataFrame:
    """Each subject's index date, resolved once and cached.

    Two sources, in this order:

    1. a labels table, whose ``prediction_time`` is the index date — this
       wins because it is what the model was actually trained against;
    2. the task spec's index event code.

    Returns:
        A frame with ``subject_id`` and ``index_date``. Subjects with no
        resolvable index date are **absent**, not given a fabricated one.
    """
    if self._index_cache is not None:
        return self._index_cache

    resolved: pl.DataFrame
    if self.labels is not None and "index_date" in self.labels.columns:
        resolved = (
            self.labels.select(["subject_id", "index_date"])
            .drop_nulls()
            .unique(subset=["subject_id"], keep="first")
        )
    elif self.task.index.event:
        matched = self._match_codes(
            self.timed(), {self.task.index.event}, self.task.index.code_system
        )
        aggregator = (
            pl.col(TIME).min() if self.task.index.occurrence == "first" else pl.col(TIME).max()
        )
        resolved = (
            matched.group_by(SUBJECT_ID)
            .agg(aggregator.alias("index_date"))
            .rename({SUBJECT_ID: "subject_id"})
        )
    else:
        resolved = pl.DataFrame(
            schema={"subject_id": pl.String, "index_date": pl.Datetime("us")}
        )

    self._index_cache = resolved.sort("subject_id")
    return self._index_cache

events_with_index

events_with_index() -> pl.DataFrame

Timed events joined to their subject's index date.

An inner join: a subject with no index date has no task to leak relative to, so their events are excluded rather than compared against a null.

Source code in src/ehrlint/context.py
def events_with_index(self) -> pl.DataFrame:
    """Timed events joined to their subject's index date.

    An inner join: a subject with no index date has no task to leak
    relative to, so their events are excluded rather than compared against
    a null.
    """
    index = self.index_dates()
    if index.height == 0:
        return (
            self.timed()
            .with_columns(pl.lit(None, dtype=pl.Datetime("us")).alias("index_date"))
            .clear()
        )
    return self.timed().join(index, left_on=SUBJECT_ID, right_on="subject_id", how="inner")

match_code_sets

match_code_sets(
    df: DataFrame, code_sets: list[Any]
) -> pl.DataFrame

Filter events to any of several :class:CodeSet objects.

A code set with no system matches the bare code in any vocabulary, which can cross-match; the context records a warning for that rather than refusing, since many datasets carry no systems at all.

Source code in src/ehrlint/context.py
def match_code_sets(self, df: pl.DataFrame, code_sets: list[Any]) -> pl.DataFrame:
    """Filter events to any of several :class:`CodeSet` objects.

    A code set with no system matches the bare code in any vocabulary,
    which can cross-match; the context records a warning for that rather
    than refusing, since many datasets carry no systems at all.
    """
    if not code_sets:
        return df.clear()
    frames = [self._match_codes(df, set(cs.values), cs.system) for cs in code_sets]
    present = [f for f in frames if f.height]
    if not present:
        return df.clear()
    return pl.concat(present, how="vertical").unique()

subject_split

subject_split() -> pl.DataFrame

Subject id to split name, or an empty frame when no splits exist.

Source code in src/ehrlint/context.py
def subject_split(self) -> pl.DataFrame:
    """Subject id to split name, or an empty frame when no splits exist."""
    if self.splits is None:
        return pl.DataFrame(schema={"subject_id": pl.String, "split": pl.String})
    return self.splits.as_frame()

describe

describe() -> dict[str, Any]

Summary for the report header.

Source code in src/ehrlint/context.py
def describe(self) -> dict[str, Any]:
    """Summary for the report header."""
    return {
        "source_format": self.source_format,
        "source_path": self.source_path,
        "data_hash": self.data_hash,
        "n_events": self.events.height,
        "n_subjects": self.n_subjects,
        "n_timed_events": self.timed().height,
        "n_static_events": self.events.height - self.timed().height,
        "has_encounters": self.has_encounters,
        "has_code_systems": self.has_code_systems,
        "n_index_dates": self.index_dates().height,
        "task": self.task.describe(),
        "splits": self.splits.describe() if self.splits else None,
        "features": self.features.describe() if self.features else None,
        "dataset_metadata": self.dataset_metadata,
    }

all_warnings

all_warnings() -> list[str]

Loading warnings plus anything the task and splits flag.

Collected here so the report shows every reason a result might be weaker than it looks, in one place above the findings.

Source code in src/ehrlint/context.py
def all_warnings(self) -> list[str]:
    """Loading warnings plus anything the task and splits flag.

    Collected here so the report shows every reason a result might be
    weaker than it looks, in one place above the findings.
    """
    out = list(self.warnings)
    out.extend(self.task.warnings())
    if self.splits is not None:
        out.extend(self.splits.warnings(set(self.subject_ids)))
    if self.features is not None:
        out.extend(self.features.warnings())
    if self.index_dates().height == 0:
        out.append(
            "no index date could be resolved for any subject, so every check that "
            "needs one will skip. Either set `index.event` to a code present in the "
            "data, or supply a labels table with prediction_time"
        )
    elif self.index_dates().height < self.n_subjects:
        missing = self.n_subjects - self.index_dates().height
        out.append(
            f"{missing} of {self.n_subjects} subject(s) have no resolvable index "
            "date and are excluded from index-relative checks"
        )
    return out

Checks

ehrlint.checks.base

The check protocol and registry.

A check is a small class with an id, a name, a rationale, a default severity, and a run(ctx) that returns findings. Third parties register their own with :func:register_check.

Two rules every check obeys:

  1. Evidence or nothing. A finding with a non-zero subject count must carry the rows that produced it. :func:~ehrlint.schemas.findings.make_finding is the only constructor, and it derives counts from the offending frame rather than taking them on trust.
  2. Skip loudly. A check that cannot run — no encounter ids, no horizon, no splits — returns a :class:~ehrlint.schemas.findings.SkippedCheck with a reason. It never returns "no findings", because a skipped check is not a pass and a reader must be able to tell the difference.

Checks are also expected to be deterministic: same input, same findings, same examples, same order. A property test asserts it.

Check

Bases: Protocol

Anything that can audit an :class:~ehrlint.context.AuditContext.

Source code in src/ehrlint/checks/base.py
@runtime_checkable
class Check(Protocol):
    """Anything that can audit an :class:`~ehrlint.context.AuditContext`."""

    id: str
    name: str
    description: str
    severity_default: Severity

    def run(self, ctx: AuditContext) -> CheckResult:
        """Audit the context and return findings, or a skip with a reason."""
        ...

run

run(ctx: AuditContext) -> CheckResult

Audit the context and return findings, or a skip with a reason.

Source code in src/ehrlint/checks/base.py
def run(self, ctx: AuditContext) -> CheckResult:
    """Audit the context and return findings, or a skip with a reason."""
    ...

BaseCheck

Convenience base for the built-in checks.

Supplies the metadata attributes and a few helpers every check wants: building a skip, counting the denominator, and resolving code sets.

Source code in src/ehrlint/checks/base.py
class BaseCheck:
    """Convenience base for the built-in checks.

    Supplies the metadata attributes and a few helpers every check wants:
    building a skip, counting the denominator, and resolving code sets.
    """

    id: str = ""
    name: str = ""
    description: str = ""
    rationale: str = ""
    severity_default: Severity = Severity.WARNING

    def run(self, ctx: AuditContext) -> CheckResult:  # pragma: no cover - abstract
        raise NotImplementedError

    # -- helpers --------------------------------------------------------

    def skip(self, reason: str) -> SkippedCheck:
        """Record that this check could not run, and why."""
        return SkippedCheck(check_id=self.id, name=self.name, reason=reason)

    def clean(self, ctx: AuditContext, message: str, query: str) -> list[Finding]:
        """A zero-count finding, meaning the check ran and found nothing.

        Distinct from a skip: this is a genuine pass, and it appears in the
        report as such so a reader can see what was actually verified.
        """
        import polars as pl

        from ehrlint.schemas.findings import make_finding

        return [
            make_finding(
                self.id,
                name=self.name,
                severity=self.severity_default,
                message=message,
                offending=pl.DataFrame(),
                n_total_subjects=ctx.n_subjects,
                query=query,
            )
        ]

    def metadata(self) -> dict[str, str]:
        """Check metadata for the report and the docs."""
        return {
            "id": self.id,
            "name": self.name,
            "description": self.description,
            "rationale": self.rationale,
            "severity_default": self.severity_default.value,
        }

skip

skip(reason: str) -> SkippedCheck

Record that this check could not run, and why.

Source code in src/ehrlint/checks/base.py
def skip(self, reason: str) -> SkippedCheck:
    """Record that this check could not run, and why."""
    return SkippedCheck(check_id=self.id, name=self.name, reason=reason)

clean

clean(
    ctx: AuditContext, message: str, query: str
) -> list[Finding]

A zero-count finding, meaning the check ran and found nothing.

Distinct from a skip: this is a genuine pass, and it appears in the report as such so a reader can see what was actually verified.

Source code in src/ehrlint/checks/base.py
def clean(self, ctx: AuditContext, message: str, query: str) -> list[Finding]:
    """A zero-count finding, meaning the check ran and found nothing.

    Distinct from a skip: this is a genuine pass, and it appears in the
    report as such so a reader can see what was actually verified.
    """
    import polars as pl

    from ehrlint.schemas.findings import make_finding

    return [
        make_finding(
            self.id,
            name=self.name,
            severity=self.severity_default,
            message=message,
            offending=pl.DataFrame(),
            n_total_subjects=ctx.n_subjects,
            query=query,
        )
    ]

metadata

metadata() -> dict[str, str]

Check metadata for the report and the docs.

Source code in src/ehrlint/checks/base.py
def metadata(self) -> dict[str, str]:
    """Check metadata for the report and the docs."""
    return {
        "id": self.id,
        "name": self.name,
        "description": self.description,
        "rationale": self.rationale,
        "severity_default": self.severity_default.value,
    }

register

register(check: Check, *, replace: bool = False) -> Check

Add a check instance to the registry.

Parameters:

Name Type Description Default
check Check

The check.

required
replace bool

Allow overwriting an existing id. Off by default, because two checks silently sharing an id would make findings ambiguous.

False

Raises:

Type Description
RegistryError

On a duplicate id, or on a check missing its metadata.

Source code in src/ehrlint/checks/base.py
def register(check: Check, *, replace: bool = False) -> Check:
    """Add a check instance to the registry.

    Args:
        check: The check.
        replace: Allow overwriting an existing id. Off by default, because two
            checks silently sharing an id would make findings ambiguous.

    Raises:
        RegistryError: On a duplicate id, or on a check missing its metadata.
    """
    if not getattr(check, "id", ""):
        raise RegistryError(f"{type(check).__name__} has no id")
    if not getattr(check, "name", ""):
        raise RegistryError(f"check {check.id} has no name")
    if check.id in _REGISTRY and not replace:
        existing = type(_REGISTRY[check.id]).__name__
        raise RegistryError(
            f"check id {check.id!r} is already registered to {existing}. Pass "
            "replace=True to override deliberately."
        )
    _REGISTRY[check.id] = check
    return check

register_check

register_check(
    *,
    id: str,
    name: str,
    severity: Severity | str = Severity.WARNING,
    description: str = "",
    rationale: str = "",
    replace: bool = False,
) -> Callable[
    [Callable[[AuditContext], CheckResult]],
    Callable[[AuditContext], CheckResult],
]

Decorator registering a plain function as a check.

The SPEC §5.2 extension point::

@el.register_check(id="LK099", name="my_check", severity="warning")
def my_check(ctx: el.AuditContext) -> list[el.Finding]:
    ...

Returns the undecorated function, so it stays directly callable and testable.

Source code in src/ehrlint/checks/base.py
def register_check(
    *,
    id: str,
    name: str,
    severity: Severity | str = Severity.WARNING,
    description: str = "",
    rationale: str = "",
    replace: bool = False,
) -> Callable[[Callable[[AuditContext], CheckResult]], Callable[[AuditContext], CheckResult]]:
    """Decorator registering a plain function as a check.

    The SPEC §5.2 extension point::

        @el.register_check(id="LK099", name="my_check", severity="warning")
        def my_check(ctx: el.AuditContext) -> list[el.Finding]:
            ...

    Returns the undecorated function, so it stays directly callable and
    testable.
    """
    severity_value = Severity(severity) if isinstance(severity, str) else severity

    def decorator(
        fn: Callable[[AuditContext], CheckResult],
    ) -> Callable[[AuditContext], CheckResult]:
        class _FunctionCheck(BaseCheck):
            pass

        _FunctionCheck.id = id
        _FunctionCheck.name = name
        _FunctionCheck.description = description or (fn.__doc__ or "").strip().split("\n")[0]
        _FunctionCheck.rationale = rationale
        _FunctionCheck.severity_default = severity_value
        _FunctionCheck.run = staticmethod(fn)  # type: ignore[assignment]
        _FunctionCheck.__name__ = f"Check_{id}"
        _FunctionCheck.__qualname__ = f"Check_{id}"

        register(_FunctionCheck(), replace=replace)
        return fn

    return decorator

get_check

get_check(check_id: str) -> Check

Look up a check by id.

Raises:

Type Description
RegistryError

If unknown, listing what is registered — a typo in a --checks list should not silently run nothing.

Source code in src/ehrlint/checks/base.py
def get_check(check_id: str) -> Check:
    """Look up a check by id.

    Raises:
        RegistryError: If unknown, listing what is registered — a typo in a
            `--checks` list should not silently run nothing.
    """
    key = check_id.strip().upper()
    if key not in _REGISTRY:
        raise RegistryError(
            f"unknown check {check_id!r}; registered: {', '.join(sorted(_REGISTRY))}"
        )
    return _REGISTRY[key]

all_checks

all_checks() -> list[Check]

Every registered check, in id order so runs are reproducible.

Source code in src/ehrlint/checks/base.py
def all_checks() -> list[Check]:
    """Every registered check, in id order so runs are reproducible."""
    return [_REGISTRY[k] for k in sorted(_REGISTRY)]

check_ids

check_ids() -> list[str]

Registered check ids, sorted.

Source code in src/ehrlint/checks/base.py
def check_ids() -> list[str]:
    """Registered check ids, sorted."""
    return sorted(_REGISTRY)

resolve_checks

resolve_checks(
    selection: list[str] | None = None,
) -> list[Check]

Resolve a selection of check ids to check instances.

Parameters:

Name Type Description Default
selection list[str] | None

Ids to run. None or empty means all of them.

None

Returns:

Type Description
list[Check]

Checks in id order.

Source code in src/ehrlint/checks/base.py
def resolve_checks(selection: list[str] | None = None) -> list[Check]:
    """Resolve a selection of check ids to check instances.

    Args:
        selection: Ids to run. None or empty means all of them.

    Returns:
        Checks in id order.
    """
    if not selection:
        return all_checks()
    wanted = [s.strip().upper() for s in selection if s and s.strip()]
    return [get_check(cid) for cid in sorted(dict.fromkeys(wanted))]

clear_registry

clear_registry() -> None

Empty the registry. For tests that register throwaway checks.

Source code in src/ehrlint/checks/base.py
def clear_registry() -> None:
    """Empty the registry. For tests that register throwaway checks."""
    _REGISTRY.clear()

registry_snapshot

registry_snapshot() -> dict[str, Check]

A copy of the registry, so a test can restore it.

Source code in src/ehrlint/checks/base.py
def registry_snapshot() -> dict[str, Check]:
    """A copy of the registry, so a test can restore it."""
    return dict(_REGISTRY)

restore_registry

restore_registry(snapshot: dict[str, Check]) -> None

Replace the registry contents with a snapshot.

Source code in src/ehrlint/checks/base.py
def restore_registry(snapshot: dict[str, Check]) -> None:
    """Replace the registry contents with a snapshot."""
    _REGISTRY.clear()
    _REGISTRY.update(snapshot)

ehrlint.checks.leakage

The check battery: LK001 through LK010.

Each check documents its rationale, runs one stated query, and returns findings that carry the rows that triggered them. The query string on every finding is SQL-ish pseudocode of the exact logic, so a reader can reproduce the result by hand rather than trusting the implementation.

The checks live in one module rather than ten files. SPEC §4.1 sketches lk001_post_index.py, lk002_same_encounter.py, and so on, but they share the index-date join, the code-set matcher, and the skip vocabulary — splitting them would mean ten files importing the same six helpers and a reader hopping between them to compare two checks that differ by one predicate. See docs/decisions.md D-006.

PostIndexFeatures

Bases: BaseCheck

LK001 — events used as predictors that happen after the index date.

Source code in src/ehrlint/checks/leakage.py
class PostIndexFeatures(BaseCheck):
    """LK001 — events used as predictors that happen after the index date."""

    id = "LK001"
    name = "post_index_features"
    description = "Events or features timestamped after the index date."
    rationale = (
        "A model that sees the future cannot be deployed. This is the most common and "
        "most damaging leak: a feature computed over a window that extends past the "
        "prediction time will often be the model's strongest signal, and it will be "
        "entirely unavailable at inference."
    )
    severity_default = Severity.ERROR

    def run(self, ctx: AuditContext) -> CheckResult:
        if ctx.index_dates().height == 0:
            return self.skip(
                "no index date could be resolved for any subject, so 'after the index "
                "date' is undefined"
            )

        findings: list[Finding] = []

        # The feature matrix is the stronger evidence when it exists: it shows
        # what the model actually saw rather than what the event stream allows.
        if ctx.features is not None and ctx.features.time_column is not None:
            findings.append(self._check_matrix(ctx))

        joined = ctx.events_with_index()
        query = (
            "SELECT * FROM events e JOIN index_dates i USING (subject_id)\n"
            "WHERE e.time > i.index_date"
        )
        offending = joined.filter(pl.col(TIME) > pl.col("index_date"))

        # Reported as `info`, not `error`. Post-index events are not a bug --
        # outcomes and follow-up live there, so every real dataset has them,
        # and flagging their mere presence as an error would make LK001
        # permanently red and teach users to ignore it. What matters is whether
        # the *feature pipeline* consumed them, which ehrlint cannot see from
        # the event stream alone. Supply --features for the real check.
        findings.append(
            make_finding(
                self.id,
                name=f"{self.name}_events",
                severity=Severity.INFO,
                message=(
                    f"{offending[SUBJECT_ID].n_unique()} of {ctx.n_subjects} subject(s) "
                    f"have {offending.height} event(s) after their index date. That is "
                    "expected -- outcomes live there. ehrlint cannot tell which events "
                    "your feature pipeline consumed; supply --features to check the "
                    "matrix directly."
                    if offending.height
                    else "No event falls after its subject's index date."
                ),
                offending=offending,
                n_total_subjects=ctx.n_subjects,
                query=query,
                example_columns=_EVENT_EXAMPLE_COLUMNS,
                detail={
                    "n_post_index_events": offending.height,
                    "severity_note": (
                        "info rather than error: the presence of post-index events is "
                        "normal. Only a feature matrix can show that they leaked."
                    ),
                },
            )
        )
        return findings

    def _check_matrix(self, ctx: AuditContext) -> Finding:
        """The direct check: feature rows stamped after the index date."""
        features = ctx.features
        assert features is not None and features.time_column is not None
        index = ctx.index_dates()
        joined = features.df.join(index, on="subject_id", how="inner")
        offending = joined.filter(pl.col(features.time_column) > pl.col("index_date"))
        return make_finding(
            f"{self.id}",
            name=f"{self.name}_matrix",
            severity=Severity.ERROR,
            message=(
                f"{offending['subject_id'].n_unique()} feature row(s) are stamped after "
                "the index date, so the matrix itself contains future information."
                if offending.height
                else "Every feature row is stamped at or before its index date."
            ),
            offending=offending,
            n_total_subjects=ctx.n_subjects,
            query=(
                f"SELECT * FROM features f JOIN index_dates i USING (subject_id)\n"
                f"WHERE f.{features.time_column} > i.index_date"
            ),
            example_columns=["subject_id", features.time_column, "index_date"],
            detail={"source": "feature_matrix", "time_column": features.time_column},
        )

SameEncounter

Bases: BaseCheck

LK002 — outcome codes recorded in the same encounter as the index event.

Source code in src/ehrlint/checks/leakage.py
class SameEncounter(BaseCheck):
    """LK002 — outcome codes recorded in the same encounter as the index event."""

    id = "LK002"
    name = "same_encounter"
    description = "Outcome codes from the index encounter itself."
    rationale = (
        "Codes are often entered at the end of an encounter, after the outcome is "
        "known. A diagnosis coded during the index visit may postdate the prediction "
        "moment even though its timestamp does not, because the timestamp is the "
        "visit's, not the moment of entry. Same-encounter outcome codes are therefore "
        "suspect regardless of their recorded time."
    )
    severity_default = Severity.ERROR

    def run(self, ctx: AuditContext) -> CheckResult:
        if not ctx.has_encounters:
            return self.skip(
                "no event carries an encounter_id. MEDS has no encounter column; supply "
                "one via --encounter-column, or use OMOP input where "
                "visit_occurrence_id is available"
            )
        if ctx.index_dates().height == 0:
            return self.skip("no index date could be resolved for any subject")
        outcome_codes = ctx.task.outcome.codes
        if not outcome_codes:
            return self.skip(
                "the task spec declares no outcome codes, so there is nothing to look "
                "for in the index encounter"
            )

        joined = ctx.events_with_index()
        if joined.height == 0:
            return self.skip("no timed event could be joined to an index date")

        # The encounter that contains the index moment, per subject.
        index_encounters = (
            joined.filter(pl.col(TIME) == pl.col("index_date"))
            .select([SUBJECT_ID, ENCOUNTER_ID])
            .drop_nulls()
            .unique()
            .rename({ENCOUNTER_ID: "index_encounter"})
        )
        if index_encounters.height == 0:
            return self.skip(
                "no event sits exactly at an index date, so the index encounter could "
                "not be identified"
            )

        outcomes = ctx.match_code_sets(joined, outcome_codes)
        if outcomes.height == 0:
            return self.clean(
                ctx,
                "No outcome code appears anywhere in the event data.",
                "SELECT * FROM events WHERE code IN outcome_codes",
            )

        offending = outcomes.join(index_encounters, on=SUBJECT_ID, how="inner").filter(
            pl.col(ENCOUNTER_ID) == pl.col("index_encounter")
        )

        return [
            make_finding(
                self.id,
                name=self.name,
                severity=self.severity_default,
                message=(
                    f"{offending[SUBJECT_ID].n_unique()} subject(s) have an outcome code "
                    "recorded in the same encounter as the index event. Coding often "
                    "happens after the outcome is known."
                    if offending.height
                    else "No outcome code shares an encounter with the index event."
                ),
                offending=offending,
                n_total_subjects=ctx.n_subjects,
                query=(
                    "WITH idx AS (\n"
                    "  SELECT subject_id, encounter_id AS index_encounter FROM events e\n"
                    "  JOIN index_dates i USING (subject_id) WHERE e.time = i.index_date\n"
                    ")\n"
                    "SELECT * FROM events e JOIN idx USING (subject_id)\n"
                    "WHERE e.code IN outcome_codes AND e.encounter_id = idx.index_encounter"
                ),
                example_columns=[SUBJECT_ID, TIME, CODE, ENCOUNTER_ID, "index_encounter"],
            )
        ]

OutcomeProxy

Bases: BaseCheck

LK003 — proxy codes for the outcome present before the index date.

Source code in src/ehrlint/checks/leakage.py
class OutcomeProxy(BaseCheck):
    """LK003 — proxy codes for the outcome present before the index date."""

    id = "LK003"
    name = "outcome_proxy"
    description = "User-listed proxy codes occurring pre-index."
    rationale = (
        "A treatment given only to cases is a label in disguise. If insulin infusion "
        "appears pre-index in a DKA prediction task, the model learns the treatment, "
        "not the risk, and will fail on patients who have not yet been treated. "
        "Proxies are task-specific and cannot be inferred, so they must be declared in "
        "the task spec."
    )
    severity_default = Severity.WARNING

    def run(self, ctx: AuditContext) -> CheckResult:
        proxies = ctx.task.outcome.proxy_codes
        if not proxies:
            return self.skip(
                "the task spec declares no outcome.proxy_codes. ehrlint cannot infer "
                "which codes imply your outcome -- list the treatments or findings that "
                "only cases receive"
            )
        if ctx.index_dates().height == 0:
            return self.skip("no index date could be resolved for any subject")

        joined = ctx.events_with_index()
        matched = ctx.match_code_sets(joined, proxies)
        offending = matched.filter(pl.col(TIME) <= pl.col("index_date"))

        return [
            make_finding(
                self.id,
                name=self.name,
                severity=self.severity_default,
                message=(
                    f"{offending[SUBJECT_ID].n_unique()} subject(s) have a declared "
                    "outcome proxy before the index date. A model may be learning the "
                    "treatment rather than the risk."
                    if offending.height
                    else "No declared outcome proxy appears before the index date."
                ),
                offending=offending,
                n_total_subjects=ctx.n_subjects,
                query=(
                    "SELECT * FROM events e JOIN index_dates i USING (subject_id)\n"
                    "WHERE e.code IN proxy_codes AND e.time <= i.index_date"
                ),
                example_columns=_EVENT_EXAMPLE_COLUMNS,
                detail={"n_proxy_codes": len(ctx.task.outcome.all_proxies())},
            )
        ]

ImmortalTime

Bases: BaseCheck

LK004 — negatives who were not observed for the full horizon.

Source code in src/ehrlint/checks/leakage.py
class ImmortalTime(BaseCheck):
    """LK004 — negatives who were not observed for the full horizon."""

    id = "LK004"
    name = "immortal_time"
    description = "Subjects who could not have had the outcome during follow-up."
    rationale = (
        "A subject labelled negative who left the data after one month is not a "
        "two-year negative -- they are censored. Counting them as negatives means the "
        "negative class is partly made of people who had no opportunity to have the "
        "outcome, which inflates every metric and is the classic immortal-time error."
    )
    severity_default = Severity.ERROR

    def run(self, ctx: AuditContext) -> CheckResult:
        if ctx.task.horizon is None:
            return self.skip("the task spec declares no horizon, so follow-up cannot be checked")
        if not ctx.task.followup.require_full_horizon_for_negatives:
            return self.skip(
                "followup.require_full_horizon_for_negatives is false, so the task "
                "accepts partial follow-up for negatives by design"
            )
        index = ctx.index_dates()
        if index.height == 0:
            return self.skip("no index date could be resolved for any subject")

        horizon_days = ctx.task.horizon.days
        timed = ctx.timed()

        # Last observed event per subject: the end of their follow-up.
        last_seen = (
            timed.group_by(SUBJECT_ID)
            .agg(pl.col(TIME).max().alias("last_event_time"))
            .rename({SUBJECT_ID: "subject_id"})
        )

        # Subjects who had the outcome do not need full follow-up -- the event
        # happened, so there is no immortal time to worry about.
        outcome_subjects: set[str] = set()
        if ctx.task.outcome.codes:
            matched = ctx.match_code_sets(timed, ctx.task.outcome.codes)
            outcome_subjects = set(matched[SUBJECT_ID].drop_nulls().unique().to_list())

        # Death (or another competing event) legitimately ends follow-up.
        censored: set[str] = set()
        if ctx.task.followup.allow_death_as_censoring:
            competing = ctx.task.outcome.all_competing() or {MEDS_DEATH_CODE}
            died = timed.filter(pl.col(CODE).is_in(list(competing)))
            censored = set(died[SUBJECT_ID].drop_nulls().unique().to_list())

        frame = index.join(last_seen, on="subject_id", how="left").with_columns(
            ((pl.col("last_event_time") - pl.col("index_date")).dt.total_seconds() / 86400.0).alias(
                "observed_days"
            )
        )

        exempt = outcome_subjects | censored
        offending = frame.filter(
            (pl.col("observed_days").is_null() | (pl.col("observed_days") < horizon_days))
            & ~pl.col("subject_id").is_in(list(exempt) or [""])
        ).with_columns(
            pl.lit(horizon_days).alias("required_days"),
            pl.lit(str(ctx.task.horizon)).alias("horizon"),
        )

        return [
            make_finding(
                self.id,
                name=self.name,
                severity=self.severity_default,
                message=(
                    f"{offending['subject_id'].n_unique()} subject(s) are observed for "
                    f"less than the {ctx.task.horizon} horizon without having the "
                    "outcome or a competing event. Labelling them negative counts "
                    "people who had no opportunity to have the outcome."
                    if offending.height
                    else f"Every negative subject is observed for the full "
                    f"{ctx.task.horizon} horizon."
                ),
                offending=offending,
                n_total_subjects=ctx.n_subjects,
                subject_column="subject_id",
                query=(
                    "WITH followup AS (\n"
                    "  SELECT subject_id, MAX(time) AS last_event_time FROM events\n"
                    "  WHERE time IS NOT NULL GROUP BY subject_id\n"
                    ")\n"
                    "SELECT * FROM index_dates i LEFT JOIN followup f USING (subject_id)\n"
                    f"WHERE DATEDIFF('day', i.index_date, f.last_event_time) < {horizon_days:g}\n"
                    "  AND subject_id NOT IN (outcome_subjects UNION competing_event_subjects)"
                ),
                example_columns=[
                    "subject_id",
                    "index_date",
                    "last_event_time",
                    "observed_days",
                    "required_days",
                    "horizon",
                ],
                detail={
                    "horizon_days": horizon_days,
                    "n_outcome_subjects_exempt": len(outcome_subjects),
                    "n_censored_exempt": len(censored),
                    "allow_death_as_censoring": ctx.task.followup.allow_death_as_censoring,
                },
            )
        ]

SplitOverlap

Bases: BaseCheck

LK005 — a subject appearing in more than one split.

Source code in src/ehrlint/checks/leakage.py
class SplitOverlap(BaseCheck):
    """LK005 — a subject appearing in more than one split."""

    id = "LK005"
    name = "split_overlap"
    description = "Subject ids present in more than one split."
    rationale = (
        "The same patient in train and test means the test metric is partly measuring "
        "memorization. In EHR data this happens easily: splitting on encounters, "
        "admissions, or rows rather than on people puts one patient's records on both "
        "sides."
    )
    severity_default = Severity.ERROR

    def run(self, ctx: AuditContext) -> CheckResult:
        if ctx.splits is None:
            return self.skip("no splits were supplied")
        if len(ctx.splits.names) < 2:
            return self.skip(
                f"only {len(ctx.splits.names)} split is defined, so there is nothing to "
                "overlap with"
            )

        rows: list[dict[str, object]] = []
        for subject, names in sorted(ctx.splits.split_of().items()):
            if len(names) > 1:
                rows.append({"subject_id": subject, "splits": ",".join(sorted(names))})

        offending = (
            pl.DataFrame(rows)
            if rows
            else pl.DataFrame(schema={"subject_id": pl.String, "splits": pl.String})
        )
        n_assigned = len(ctx.splits.all_subjects())

        return [
            make_finding(
                self.id,
                name=self.name,
                severity=self.severity_default,
                message=(
                    f"{len(rows)} subject(s) appear in more than one split, so the test "
                    "metric is partly measuring memorization."
                    if rows
                    else f"The {len(ctx.splits.names)} splits are disjoint by subject."
                ),
                offending=offending,
                n_total_subjects=n_assigned or ctx.n_subjects,
                subject_column="subject_id",
                query=(
                    "SELECT subject_id, COUNT(DISTINCT split) AS n_splits\n"
                    "FROM subject_splits GROUP BY subject_id HAVING n_splits > 1"
                ),
                example_columns=["subject_id", "splits"],
                detail={
                    "split_sizes": ctx.splits.sizes(),
                    "overlapping_pairs": {
                        f"{a}|{b}": len(ids) for (a, b), ids in ctx.splits.overlaps().items()
                    },
                },
            )
        ]

TemporalSplit

Bases: BaseCheck

LK006 — a temporal split that does not actually respect time.

Source code in src/ehrlint/checks/leakage.py
class TemporalSplit(BaseCheck):
    """LK006 — a temporal split that does not actually respect time."""

    id = "LK006"
    name = "temporal_split"
    description = "Test index dates that precede the training period's end."
    rationale = (
        "A split described as temporal but not ordered in time reports an optimistic "
        "number: the model is evaluated on a period it was partly trained on, so it "
        "benefits from knowing the era's coding practices, formulary, and case mix."
    )
    severity_default = Severity.WARNING

    def run(self, ctx: AuditContext) -> CheckResult:
        if ctx.splits is None:
            return self.skip("no splits were supplied")
        from ehrlint.schemas.splits import TEST, TRAIN

        if TRAIN not in ctx.splits.assignments or TEST not in ctx.splits.assignments:
            return self.skip(f"a train and a test split are both needed; found {ctx.splits.names}")
        index = ctx.index_dates()
        if index.height == 0:
            return self.skip("no index date could be resolved for any subject")

        # A split declared temporal is an error when violated; one that never
        # claimed to be is only a warning.
        severity = Severity.ERROR if ctx.task.splits.temporal else Severity.WARNING

        train_ids = ctx.splits.get(TRAIN)
        test_ids = ctx.splits.get(TEST)
        train_index = index.filter(pl.col("subject_id").is_in(train_ids))
        if train_index.height == 0:
            return self.skip("no training subject has a resolvable index date")

        train_max = train_index["index_date"].max()
        # Rendered once: a Polars `.max()` is typed loosely enough that
        # interpolating it directly could stringify bytes as `b'...'`.
        train_max_text = str(train_max)
        offending = (
            index.filter(pl.col("subject_id").is_in(test_ids))
            .filter(pl.col("index_date") < train_max)
            .with_columns(pl.lit(train_max).alias("train_max_index_date"))
        )

        return [
            make_finding(
                self.id,
                name=self.name,
                severity=severity,
                message=(
                    f"{offending['subject_id'].n_unique()} test subject(s) have an index "
                    f"date before the training period ends ({train_max_text}). "
                    + (
                        "The task spec declares this split temporal, so this invalidates it."
                        if ctx.task.splits.temporal
                        else "The split does not claim to be temporal; this is reported for review."
                    )
                    if offending.height
                    else f"Every test index date falls at or after the training maximum "
                    f"({train_max_text})."
                ),
                offending=offending,
                n_total_subjects=len(test_ids) or ctx.n_subjects,
                subject_column="subject_id",
                query=(
                    "WITH train_max AS (\n"
                    "  SELECT MAX(index_date) AS t FROM index_dates\n"
                    "  WHERE subject_id IN train_split\n"
                    ")\n"
                    "SELECT * FROM index_dates WHERE subject_id IN test_split\n"
                    "  AND index_date < (SELECT t FROM train_max)"
                ),
                example_columns=["subject_id", "index_date", "train_max_index_date"],
                detail={
                    "train_max_index_date": train_max_text,
                    "declared_temporal": ctx.task.splits.temporal,
                    "n_test_subjects": len(test_ids),
                },
            )
        ]

LabelDefinition

Bases: BaseCheck

LK007 — the outcome ascertained with information from after the window.

Source code in src/ehrlint/checks/leakage.py
class LabelDefinition(BaseCheck):
    """LK007 — the outcome ascertained with information from after the window."""

    id = "LK007"
    name = "label_definition"
    description = "Labels that depend on information outside the outcome window."
    rationale = (
        "If a subject is labelled positive on the strength of an outcome code that "
        "falls outside the declared window, the label is not the label the task "
        "defines. The model is then trained toward a target nobody specified, and the "
        "reported task definition does not describe what was learned."
    )
    severity_default = Severity.ERROR

    def run(self, ctx: AuditContext) -> CheckResult:
        if ctx.labels is None or "label" not in ctx.labels.columns:
            return self.skip(
                "no labels table was supplied, so ehrlint cannot compare the given "
                "labels against the outcome definition"
            )
        if not ctx.task.outcome.codes:
            return self.skip("the task spec declares no outcome codes")
        if ctx.task.horizon is None:
            return self.skip("the task spec declares no horizon")
        if ctx.labels["label"].null_count() == ctx.labels.height:
            return self.skip("the labels table carries no label values")

        index = ctx.index_dates()
        horizon_days = ctx.task.horizon.days
        timed = ctx.timed()
        outcomes = ctx.match_code_sets(timed, ctx.task.outcome.codes)

        # Outcome occurrences inside the declared window, per subject.
        in_window = (
            outcomes.join(index, left_on=SUBJECT_ID, right_on="subject_id", how="inner")
            .filter(
                (pl.col(TIME) > pl.col("index_date"))
                & (
                    (pl.col(TIME) - pl.col("index_date")).dt.total_seconds() / 86400.0
                    <= horizon_days
                )
            )
            .select(SUBJECT_ID)
            .unique()
            .rename({SUBJECT_ID: "subject_id"})
            .with_columns(pl.lit(True).alias("outcome_in_window"))
        )

        labelled = (
            ctx.labels.select(["subject_id", "label"])
            .drop_nulls("label")
            .join(in_window, on="subject_id", how="left")
            .with_columns(pl.col("outcome_in_window").fill_null(False))
        )

        # A positive label with no in-window outcome: the label came from
        # somewhere the task definition does not reach.
        offending = labelled.filter(pl.col("label") & ~pl.col("outcome_in_window")).with_columns(
            pl.lit(str(ctx.task.horizon)).alias("horizon"),
            pl.lit(
                "positive label with no outcome code strictly after the index date "
                "and within the horizon"
            ).alias("why"),
        )

        return [
            make_finding(
                self.id,
                name=self.name,
                severity=self.severity_default,
                message=(
                    f"{offending['subject_id'].n_unique()} subject(s) are labelled "
                    f"positive with no outcome code strictly after the index date and "
                    f"within {ctx.task.horizon} of it, so the label was ascertained "
                    "from information the task definition does not describe. An "
                    "occurrence stamped at exactly the index date does not count here "
                    "-- it is not predictable from that moment, and LK002 reports it."
                    if offending.height
                    else f"Every positive label is supported by an outcome code "
                    f"strictly after the index date and within {ctx.task.horizon}."
                ),
                offending=offending,
                n_total_subjects=labelled.height or ctx.n_subjects,
                subject_column="subject_id",
                query=(
                    "WITH in_window AS (\n"
                    "  SELECT DISTINCT e.subject_id FROM events e\n"
                    "  JOIN index_dates i USING (subject_id)\n"
                    "  WHERE e.code IN outcome_codes AND e.time > i.index_date\n"
                    f"    AND DATEDIFF('day', i.index_date, e.time) <= {horizon_days:g}\n"
                    ")\n"
                    "SELECT * FROM labels l WHERE l.label = TRUE\n"
                    "  AND l.subject_id NOT IN (SELECT subject_id FROM in_window)"
                ),
                example_columns=["subject_id", "label", "outcome_in_window", "horizon", "why"],
                detail={"horizon_days": horizon_days, "n_labelled": labelled.height},
            )
        ]

EncounterGroup

Bases: BaseCheck

LK008 — one encounter or provider contributing to two splits.

Source code in src/ehrlint/checks/leakage.py
class EncounterGroup(BaseCheck):
    """LK008 — one encounter or provider contributing to two splits."""

    id = "LK008"
    name = "encounter_group"
    description = "A group (encounter, provider) straddling two splits."
    rationale = (
        "Records from one encounter share a clinician, a note template, and a coding "
        "pattern. When the same group appears in train and test, the model can "
        "recognize the group rather than the clinical signal -- the same failure as "
        "subject overlap, one level up."
    )
    severity_default = Severity.ERROR

    def run(self, ctx: AuditContext) -> CheckResult:
        if ctx.splits is None:
            return self.skip("no splits were supplied")
        if len(ctx.splits.names) < 2:
            return self.skip("fewer than two splits are defined")

        group_column = ctx.task.splits.group_column or ENCOUNTER_ID
        if group_column not in ctx.events.columns:
            return self.skip(
                f"the group column {group_column!r} is not in the event data; set "
                "splits.group_column in the task spec or supply encounter ids"
            )
        if ctx.events[group_column].null_count() == ctx.events.height:
            return self.skip(f"every {group_column} is null")

        assignment = ctx.subject_split()
        grouped = (
            ctx.events.select([SUBJECT_ID, group_column])
            .drop_nulls()
            .unique()
            .join(assignment, left_on=SUBJECT_ID, right_on="subject_id", how="inner")
        )
        if grouped.height == 0:
            return self.skip(
                "no event could be joined to a split; the subject ids in the splits may "
                "not match those in the event data"
            )

        straddling = (
            grouped.group_by(group_column)
            .agg(
                pl.col("split").n_unique().alias("n_splits"),
                pl.col("split").unique().sort().str.join(",").alias("splits"),
                pl.col(SUBJECT_ID).n_unique().alias("n_subjects_in_group"),
            )
            .filter(pl.col("n_splits") > 1)
            .sort(group_column)
        )

        # One row per (group, subject), not one per group. A straddling group
        # has at least two subjects by definition, and naming one of them
        # leaves the reader to re-derive the rest -- while `n_subjects` and the
        # machine-readable subject list would both understate the damage by
        # half. The group count stays in the message and in `detail`.
        members = (
            grouped.join(
                straddling.select(group_column, "splits", "n_splits"),
                on=group_column,
                how="inner",
            )
            .unique()
            .sort([group_column, SUBJECT_ID])
        )

        return [
            make_finding(
                self.id,
                name=self.name,
                severity=self.severity_default,
                message=(
                    f"{straddling.height} {group_column} value(s) spanning "
                    f"{members[SUBJECT_ID].n_unique()} subject(s) contribute to more "
                    "than one split, so the model can learn the group rather than the "
                    "clinical signal."
                    if straddling.height
                    else f"No {group_column} value spans two splits."
                ),
                offending=members,
                n_total_subjects=ctx.n_subjects,
                subject_column=SUBJECT_ID,
                query=(
                    f"SELECT {group_column}, COUNT(DISTINCT split) AS n_splits\n"
                    f"FROM events e JOIN subject_splits s USING (subject_id)\n"
                    f"WHERE {group_column} IS NOT NULL\n"
                    f"GROUP BY {group_column} HAVING n_splits > 1"
                ),
                example_columns=[group_column, SUBJECT_ID, "split", "splits", "n_splits"],
                detail={"group_column": group_column, "n_groups": straddling.height},
            )
        ]

DuplicateSubjects

Bases: BaseCheck

LK009 — one person under more than one subject id.

Source code in src/ehrlint/checks/leakage.py
class DuplicateSubjects(BaseCheck):
    """LK009 — one person under more than one subject id."""

    id = "LK009"
    name = "duplicate_subjects"
    description = "Subjects that look like the same person under two ids."
    rationale = (
        "Patients get duplicate records across registrations, sites, and merges. Two "
        "ids for one person defeat a subject-level split in exactly the way LK005 "
        "guards against, but invisibly -- the split is disjoint by id while not being "
        "disjoint by person."
    )
    severity_default = Severity.WARNING

    def run(self, ctx: AuditContext) -> CheckResult:
        static = ctx.events.filter(pl.col(TIME).is_null())
        if static.height == 0:
            return self.skip(
                "no static (null-time) events are present, so there are no demographics "
                "to match on. Deterministic matching needs demographic facts"
            )

        # A deterministic signature: the sorted multiset of a subject's static
        # codes. Deliberately not probabilistic -- a fuzzy match would produce
        # findings nobody can verify, and §0 forbids unverifiable statistics.
        signatures = (
            static.select([SUBJECT_ID, CODE])
            .drop_nulls()
            .unique()
            .group_by(SUBJECT_ID)
            .agg(pl.col(CODE).unique().sort().str.join("|").alias("signature"))
        )
        if signatures.height == 0:
            return self.skip("no subject has any static code to build a signature from")

        # Only signatures with enough facts to be discriminating. One shared
        # demographic code is not evidence of anything.
        signatures = signatures.with_columns(
            pl.col("signature").str.count_matches(r"\|").add(1).alias("n_facts")
        ).filter(pl.col("n_facts") >= 2)

        collisions = (
            signatures.group_by("signature")
            .agg(
                pl.col(SUBJECT_ID).n_unique().alias("n_subject_ids"),
                pl.col(SUBJECT_ID).unique().sort().str.join(",").alias("subject_ids"),
                pl.col("n_facts").first().alias("n_facts"),
            )
            .filter(pl.col("n_subject_ids") > 1)
            .sort("signature")
        )

        # Guard against a signature too coarse to mean anything. If the
        # demographics in this dataset only distinguish a handful of profiles,
        # collisions are arithmetic rather than evidence -- and listing them as
        # candidate duplicates would be exactly the fabricated statistic §0
        # forbids. Refuse to conclude instead.
        n_signatures = signatures["signature"].n_unique()
        n_signed_subjects = signatures[SUBJECT_ID].n_unique()
        if n_signed_subjects and n_signatures / n_signed_subjects < MIN_SIGNATURE_DISTINCTNESS:
            return self.skip(
                f"the static demographics distinguish only {n_signatures} profile(s) "
                f"across {n_signed_subjects} subject(s), so collisions are expected by "
                "arithmetic rather than evidence of duplication. Deterministic matching "
                "needs higher-cardinality facts (a birth date, a postal code) than this "
                "dataset carries"
            )

        # One row per colliding id, not one per group. A duplicate finding whose
        # subject list names one of the two ids is not actionable: the whole
        # claim is that *these two ids* are one person.
        members = signatures.join(
            collisions.select("signature", "n_subject_ids", "subject_ids"),
            on="signature",
            how="inner",
        ).sort(["signature", SUBJECT_ID])

        return [
            make_finding(
                self.id,
                name=self.name,
                severity=self.severity_default,
                message=(
                    f"{collisions.height} group(s) covering "
                    f"{members[SUBJECT_ID].n_unique()} subject id(s) share an identical "
                    "static demographic signature and may be the same person under "
                    "multiple ids."
                    if collisions.height
                    else "No two subject ids share an identical demographic signature."
                ),
                offending=members,
                n_total_subjects=ctx.n_subjects,
                subject_column=SUBJECT_ID,
                query=(
                    "WITH sig AS (\n"
                    "  SELECT subject_id, STRING_AGG(DISTINCT code, '|' ORDER BY code) AS signature\n"
                    "  FROM events WHERE time IS NULL GROUP BY subject_id\n"
                    ")\n"
                    "SELECT signature, COUNT(DISTINCT subject_id) AS n_subject_ids\n"
                    "FROM sig GROUP BY signature HAVING n_subject_ids > 1"
                ),
                example_columns=[SUBJECT_ID, "signature", "subject_ids", "n_subject_ids"],
                detail={
                    "method": "deterministic match on the sorted set of static codes",
                    "min_facts": 2,
                    "n_groups": collisions.height,
                    "note": (
                        "Deterministic, not probabilistic. A shared signature is a "
                        "candidate for review, not a confirmed duplicate -- twins and "
                        "sparse demographics both produce collisions."
                    ),
                },
            )
        ]

HorizonViolation

Bases: BaseCheck

LK010 — outcomes outside the declared horizon counted as positives.

Source code in src/ehrlint/checks/leakage.py
class HorizonViolation(BaseCheck):
    """LK010 — outcomes outside the declared horizon counted as positives."""

    id = "LK010"
    name = "horizon_violation"
    description = "Outcome occurrences beyond the declared horizon."
    rationale = (
        "A two-year task whose outcome window actually reaches five years is a "
        "five-year task reported as two. Every metric is then describing a different "
        "question from the one the paper states, and the model will underperform when "
        "deployed against the stated horizon."
    )
    severity_default = Severity.ERROR

    def run(self, ctx: AuditContext) -> CheckResult:
        if ctx.task.horizon is None:
            return self.skip("the task spec declares no horizon")
        if not ctx.task.outcome.codes:
            return self.skip("the task spec declares no outcome codes")
        index = ctx.index_dates()
        if index.height == 0:
            return self.skip("no index date could be resolved for any subject")

        horizon_days = ctx.task.horizon.days
        outcomes = ctx.match_code_sets(ctx.timed(), ctx.task.outcome.codes)
        if outcomes.height == 0:
            return self.clean(
                ctx,
                "No outcome code appears in the event data.",
                "SELECT * FROM events WHERE code IN outcome_codes",
            )

        joined = outcomes.join(
            index, left_on=SUBJECT_ID, right_on="subject_id", how="inner"
        ).with_columns(
            ((pl.col(TIME) - pl.col("index_date")).dt.total_seconds() / 86400.0).alias(
                "days_after_index"
            )
        )

        # Subjects whose *only* outcome occurrence is beyond the horizon. A
        # subject with an in-window occurrence is a legitimate positive, and
        # their later recurrences are not a violation.
        in_window = set(
            joined.filter(
                (pl.col("days_after_index") > 0) & (pl.col("days_after_index") <= horizon_days)
            )[SUBJECT_ID]
            .unique()
            .to_list()
        )
        offending = joined.filter(
            (pl.col("days_after_index") > horizon_days)
            & ~pl.col(SUBJECT_ID).is_in(list(in_window) or [""])
        ).with_columns(
            pl.lit(horizon_days).alias("horizon_days"),
            pl.lit(str(ctx.task.horizon)).alias("horizon"),
        )

        return [
            make_finding(
                self.id,
                name=self.name,
                severity=self.severity_default,
                message=(
                    f"{offending[SUBJECT_ID].n_unique()} subject(s) have their only "
                    f"outcome occurrence beyond the declared {ctx.task.horizon} horizon. "
                    "If they are labelled positive, the task's real horizon is longer "
                    "than stated."
                    if offending.height
                    else f"Every outcome occurrence falls within the declared "
                    f"{ctx.task.horizon} horizon."
                ),
                offending=offending,
                n_total_subjects=ctx.n_subjects,
                query=(
                    "SELECT * FROM events e JOIN index_dates i USING (subject_id)\n"
                    "WHERE e.code IN outcome_codes\n"
                    f"  AND DATEDIFF('day', i.index_date, e.time) > {horizon_days:g}\n"
                    "  AND e.subject_id NOT IN (subjects with an in-window occurrence)"
                ),
                example_columns=[
                    SUBJECT_ID,
                    TIME,
                    CODE,
                    "index_date",
                    "days_after_index",
                    "horizon_days",
                    "horizon",
                ],
                detail={
                    "horizon_days": horizon_days,
                    "n_in_window_subjects": len(in_window),
                },
            )
        ]

register_builtins

register_builtins(*, replace: bool = True) -> None

Register every built-in check.

Called at import time of :mod:ehrlint.checks. Idempotent by default, so re-importing does not raise on duplicate ids.

Source code in src/ehrlint/checks/leakage.py
def register_builtins(*, replace: bool = True) -> None:
    """Register every built-in check.

    Called at import time of :mod:`ehrlint.checks`. Idempotent by default, so
    re-importing does not raise on duplicate ids.
    """
    for cls in BUILTIN_CHECKS:
        register(cls(), replace=replace)

Schemas

ehrlint.schemas.events

The canonical event table.

Everything ehrlint audits is reduced to one long-format table:

column type meaning
subject_id string the person. String, always -- see below
time datetime, nullable when it happened; null for static facts
code string what happened
code_system string, nullable which vocabulary code belongs to
numeric_value float, nullable a measured value
text_value string, nullable a free-text value
encounter_id string, nullable for the same-encounter and group checks

subject_id is normalized to string even though MEDS types it int64. ehrlint joins subject ids against splits files, feature matrices, and label tables that come from different tools, and an int/string mismatch between two of them produces an empty join that looks like "no leakage found". A silent false-clean is the worst failure mode an auditor can have, so everything is coerced to string at the boundary and compared as strings throughout.

encounter_id and code_system are extensions beyond MEDS, which has neither. See docs/decisions.md D-002. Both are nullable, and the checks that need them skip with a stated reason rather than silently passing when they are absent.

empty_events

empty_events() -> pl.DataFrame

An empty canonical event table with the right dtypes.

Returned rather than a bare pl.DataFrame() so that downstream filters and joins behave identically on empty input. An auditor that crashes on an empty table is an auditor nobody runs twice.

Source code in src/ehrlint/schemas/events.py
def empty_events() -> pl.DataFrame:
    """An empty canonical event table with the right dtypes.

    Returned rather than a bare ``pl.DataFrame()`` so that downstream filters
    and joins behave identically on empty input. An auditor that crashes on an
    empty table is an auditor nobody runs twice.
    """
    return pl.DataFrame(schema=CANONICAL_SCHEMA)

coerce_events

coerce_events(
    df: DataFrame, *, source: str = "events"
) -> pl.DataFrame

Coerce a frame to the canonical schema.

Adds any missing optional columns as all-null, casts every column to its canonical dtype, and orders the columns. subject_id and encounter_id become strings, which is the normalization that prevents a silent empty join later.

Parameters:

Name Type Description Default
df DataFrame

The frame to coerce.

required
source str

Named in error messages.

'events'

Returns:

Type Description
DataFrame

A frame with exactly :data:CANONICAL_COLUMNS, in order.

Raises:

Type Description
SchemaError

If a required column is missing, naming which.

Source code in src/ehrlint/schemas/events.py
def coerce_events(df: pl.DataFrame, *, source: str = "events") -> pl.DataFrame:
    """Coerce a frame to the canonical schema.

    Adds any missing optional columns as all-null, casts every column to its
    canonical dtype, and orders the columns. ``subject_id`` and
    ``encounter_id`` become **strings**, which is the normalization that
    prevents a silent empty join later.

    Args:
        df: The frame to coerce.
        source: Named in error messages.

    Returns:
        A frame with exactly :data:`CANONICAL_COLUMNS`, in order.

    Raises:
        SchemaError: If a required column is missing, naming which.
    """
    from ehrlint.exceptions import SchemaError

    missing = [c for c in REQUIRED_COLUMNS if c not in df.columns]
    if missing:
        raise SchemaError(
            f"canonical event table is missing required column(s) {missing}; "
            f"required: {list(REQUIRED_COLUMNS)}, found: {df.columns}",
            table=source,
        )

    out = df
    for column in OPTIONAL_COLUMNS:
        if column not in out.columns:
            out = out.with_columns(pl.lit(None).cast(CANONICAL_SCHEMA[column]).alias(column))

    casts = []
    for column, dtype in CANONICAL_SCHEMA.items():
        casts.append(pl.col(column).cast(dtype, strict=False).alias(column))

    return out.with_columns(casts).select(list(CANONICAL_COLUMNS))

split_meds_code

split_meds_code(df: DataFrame) -> pl.DataFrame

Recover code_system from the MEDS SYSTEM//code convention.

MEDS has no code_system column; the convention is to namespace inside the code string. This splits on the first separator, leaving code as the local part. A code with no separator keeps a null system rather than being assigned a guessed one.

Source code in src/ehrlint/schemas/events.py
def split_meds_code(df: pl.DataFrame) -> pl.DataFrame:
    """Recover ``code_system`` from the MEDS ``SYSTEM//code`` convention.

    MEDS has no ``code_system`` column; the convention is to namespace inside
    the code string. This splits on the first separator, leaving ``code`` as
    the local part. A code with no separator keeps a **null** system rather
    than being assigned a guessed one.
    """
    if CODE not in df.columns:
        return df
    has_sep = pl.col(CODE).str.contains(MEDS_CODE_SEPARATOR, literal=True)
    parts = pl.col(CODE).str.splitn(MEDS_CODE_SEPARATOR, 2)
    return df.with_columns(
        pl.when(has_sep).then(parts.struct.field("field_0")).otherwise(None).alias(CODE_SYSTEM),
        pl.when(has_sep).then(parts.struct.field("field_1")).otherwise(pl.col(CODE)).alias(CODE),
    )

validate_events

validate_events(
    df: DataFrame, *, source: str = "events"
) -> list[str]

Check an event table for problems worth warning about.

Returns human-readable warnings rather than raising: every one of these is survivable, and a completed audit is more useful than a hard stop. An empty list means nothing notable.

Source code in src/ehrlint/schemas/events.py
def validate_events(df: pl.DataFrame, *, source: str = "events") -> list[str]:
    """Check an event table for problems worth warning about.

    Returns human-readable warnings rather than raising: every one of these is
    survivable, and a completed audit is more useful than a hard stop. An empty
    list means nothing notable.
    """
    warnings: list[str] = []

    if df.height == 0:
        warnings.append(f"{source} is empty, so every check will skip")
        return warnings

    n_null_subject = df[SUBJECT_ID].null_count()
    if n_null_subject:
        warnings.append(
            f"{n_null_subject} event(s) have a null subject_id and cannot be attributed "
            "to anyone; they are excluded from per-subject checks"
        )

    n_null_code = df[CODE].null_count()
    if n_null_code:
        warnings.append(f"{n_null_code} event(s) have a null code")

    n_null_time = df[TIME].null_count()
    if n_null_time:
        warnings.append(
            f"{n_null_time} event(s) have a null time. In MEDS these are static facts "
            "(demographics, birth); they are excluded from time-ordering checks rather "
            "than treated as occurring at the epoch"
        )

    if CODE_SYSTEM in df.columns and df[CODE_SYSTEM].null_count() == df.height:
        warnings.append(
            "no event carries a code_system. Checks that match codes by system fall back "
            "to matching the bare code, which can cross-match between vocabularies"
        )

    if ENCOUNTER_ID in df.columns and df[ENCOUNTER_ID].null_count() == df.height:
        warnings.append(
            "no event carries an encounter_id, so the same-encounter (LK002) and "
            "encounter-group (LK008) checks will skip"
        )

    return warnings

events_hash

events_hash(df: DataFrame) -> str

A stable content hash of an event table.

Recorded in the report so two audits can be compared and a finding can be tied to the exact data that produced it. Computed from the shape plus a digest of the sorted contents, so it is invariant to row order — the same data loaded by two different readers hashes the same.

Source code in src/ehrlint/schemas/events.py
def events_hash(df: pl.DataFrame) -> str:
    """A stable content hash of an event table.

    Recorded in the report so two audits can be compared and a finding can be
    tied to the exact data that produced it. Computed from the shape plus a
    digest of the sorted contents, so it is **invariant to row order** — the
    same data loaded by two different readers hashes the same.
    """
    hasher = hashlib.sha256()
    hasher.update(f"{df.height}x{df.width}".encode())
    hasher.update(",".join(sorted(df.columns)).encode())
    if df.height:
        ordered = df.sort([c for c in (SUBJECT_ID, TIME, CODE) if c in df.columns], nulls_last=True)
        for column in CANONICAL_COLUMNS:
            if column in ordered.columns:
                hasher.update(column.encode())
                values = ordered[column].cast(pl.String, strict=False).to_list()
                hasher.update(repr(values).encode())
    return hasher.hexdigest()[:16]

subjects

subjects(df: DataFrame) -> list[str]

Distinct non-null subject ids, sorted. Deterministic ordering.

Source code in src/ehrlint/schemas/events.py
def subjects(df: pl.DataFrame) -> list[str]:
    """Distinct non-null subject ids, sorted. Deterministic ordering."""
    if df.height == 0 or SUBJECT_ID not in df.columns:
        return []
    return sorted(df[SUBJECT_ID].drop_nulls().unique().to_list())

timed_events

timed_events(df: DataFrame) -> pl.DataFrame

Events that carry a timestamp.

Static events (null time) are excluded from every time-ordering check. Treating a null time as the epoch would make every static fact look like a pre-index event, which is both wrong and the kind of wrong that produces confident false findings.

Source code in src/ehrlint/schemas/events.py
def timed_events(df: pl.DataFrame) -> pl.DataFrame:
    """Events that carry a timestamp.

    Static events (null ``time``) are excluded from every time-ordering check.
    Treating a null time as the epoch would make every static fact look like a
    pre-index event, which is both wrong and the kind of wrong that produces
    confident false findings.
    """
    return df.filter(pl.col(TIME).is_not_null())

ehrlint.schemas.task

The task specification: index date, outcome, horizon, follow-up.

This is the object every check reasons against. A leak is only definable relative to a task: "post-index features" needs an index date, and "immortal-time bias" needs a follow-up rule.

The spec is deliberately strict. A task definition that is ambiguous about its own horizon cannot be audited meaningfully, so ehrlint refuses it at load time rather than producing findings whose meaning depends on a guess.

SplitStrategy

Bases: StrEnum

How the dataset was split.

Source code in src/ehrlint/schemas/task.py
class SplitStrategy(StrEnum):
    """How the dataset was split."""

    SUBJECT = "subject"
    ENCOUNTER = "encounter"
    TEMPORAL = "temporal"
    RANDOM = "random"

Duration

Bases: BaseModel

A horizon or window length, e.g. 2y.

Source code in src/ehrlint/schemas/task.py
class Duration(BaseModel):
    """A horizon or window length, e.g. ``2y``."""

    model_config = ConfigDict(extra="forbid", frozen=True)

    n: float = Field(gt=0)
    unit: str = Field(pattern="^[dwmy]$")

    @classmethod
    def parse(cls, value: str | Duration | None) -> Duration | None:
        """Parse ``"2y"`` into ``Duration(n=2, unit="y")``.

        Raises:
            TaskSpecError: On anything unparseable, with the accepted forms
                named. A horizon is load-bearing, so a typo must not become a
                silently different number.
        """
        if value is None:
            return None
        if isinstance(value, Duration):
            return value
        match = _DURATION_RE.match(str(value))
        if not match:
            raise TaskSpecError(
                f"cannot parse duration {value!r}; expected forms like '30d', '12w', '6m', '2y'"
            )
        n = float(match.group(1))
        if n <= 0:
            # Caught here rather than left to the field constraint, which would
            # surface a raw pydantic error from a user-facing YAML file.
            raise TaskSpecError(
                f"duration {value!r} is not positive. A zero-length horizon has no "
                "window to audit; expected forms like '30d', '12w', '6m', '2y'"
            )
        return cls(n=n, unit=match.group(2).lower())

    def __str__(self) -> str:
        n = int(self.n) if float(self.n).is_integer() else self.n
        return f"{n}{self.unit}"

    @property
    def days(self) -> float:
        """Length in days.

        Months and years use 30.4375 and 365.25 days. That is an
        approximation, and it is the right one for a *horizon*: "within two
        years of the index date" is a study design choice with a tolerance of
        days, not a calendar-exact boundary. Where exactness matters, express
        the horizon in days.
        """
        return self.n * _DAYS_PER_UNIT[self.unit]

    def to_timedelta(self) -> timedelta:
        """Length as a ``timedelta``."""
        return timedelta(days=self.days)

days property

days: float

Length in days.

Months and years use 30.4375 and 365.25 days. That is an approximation, and it is the right one for a horizon: "within two years of the index date" is a study design choice with a tolerance of days, not a calendar-exact boundary. Where exactness matters, express the horizon in days.

parse classmethod

parse(value: str | Duration | None) -> Duration | None

Parse "2y" into Duration(n=2, unit="y").

Raises:

Type Description
TaskSpecError

On anything unparseable, with the accepted forms named. A horizon is load-bearing, so a typo must not become a silently different number.

Source code in src/ehrlint/schemas/task.py
@classmethod
def parse(cls, value: str | Duration | None) -> Duration | None:
    """Parse ``"2y"`` into ``Duration(n=2, unit="y")``.

    Raises:
        TaskSpecError: On anything unparseable, with the accepted forms
            named. A horizon is load-bearing, so a typo must not become a
            silently different number.
    """
    if value is None:
        return None
    if isinstance(value, Duration):
        return value
    match = _DURATION_RE.match(str(value))
    if not match:
        raise TaskSpecError(
            f"cannot parse duration {value!r}; expected forms like '30d', '12w', '6m', '2y'"
        )
    n = float(match.group(1))
    if n <= 0:
        # Caught here rather than left to the field constraint, which would
        # surface a raw pydantic error from a user-facing YAML file.
        raise TaskSpecError(
            f"duration {value!r} is not positive. A zero-length horizon has no "
            "window to audit; expected forms like '30d', '12w', '6m', '2y'"
        )
    return cls(n=n, unit=match.group(2).lower())

to_timedelta

to_timedelta() -> timedelta

Length as a timedelta.

Source code in src/ehrlint/schemas/task.py
def to_timedelta(self) -> timedelta:
    """Length as a ``timedelta``."""
    return timedelta(days=self.days)

CodeSet

Bases: BaseModel

A set of codes in one vocabulary.

Source code in src/ehrlint/schemas/task.py
class CodeSet(BaseModel):
    """A set of codes in one vocabulary."""

    model_config = ConfigDict(extra="forbid")

    system: str | None = Field(
        default=None,
        description="Vocabulary name. Null matches the bare code in any system, which "
        "can cross-match -- ehrlint warns when it has to do that.",
    )
    values: list[str] = Field(min_length=1)

    @field_validator("values")
    @classmethod
    def _strip(cls, v: list[str]) -> list[str]:
        out = [s.strip() for s in v if s and s.strip()]
        if not out:
            raise ValueError("a code set needs at least one non-blank value")
        return out

    def matches_any(self) -> set[str]:
        """The code values, as a set."""
        return set(self.values)

matches_any

matches_any() -> set[str]

The code values, as a set.

Source code in src/ehrlint/schemas/task.py
def matches_any(self) -> set[str]:
    """The code values, as a set."""
    return set(self.values)

IndexDef

Bases: BaseModel

How each subject's index date is determined.

Source code in src/ehrlint/schemas/task.py
class IndexDef(BaseModel):
    """How each subject's index date is determined."""

    model_config = ConfigDict(extra="forbid")

    event: str | None = Field(
        default=None,
        description="Code marking the index event. Null when index dates are supplied "
        "in a labels table instead.",
    )
    code_system: str | None = None
    occurrence: str = Field(
        default="first",
        pattern="^(first|last)$",
        description="Which occurrence of the index event to use when a subject has "
        "several. Defaults to 'first'.",
    )

    @property
    def from_labels(self) -> bool:
        """Whether index dates come from a labels table rather than an event code."""
        return self.event is None

from_labels property

from_labels: bool

Whether index dates come from a labels table rather than an event code.

OutcomeDef

Bases: BaseModel

How the outcome is ascertained.

Source code in src/ehrlint/schemas/task.py
class OutcomeDef(BaseModel):
    """How the outcome is ascertained."""

    model_config = ConfigDict(extra="forbid")

    codes: list[CodeSet] = Field(default_factory=list)
    window: list[str] | None = Field(
        default=None,
        description="Two expressions, e.g. ['index_date', 'index_date + 2y']. Used to "
        "detect a window that extends past the declared horizon.",
    )
    proxy_codes: list[CodeSet] = Field(
        default_factory=list,
        description="Codes that imply the outcome without being it -- a treatment only "
        "given to cases, say. Pre-index occurrences are flagged by LK003.",
    )
    competing_codes: list[CodeSet] = Field(
        default_factory=list,
        description="Competing events, typically death, that end follow-up without the "
        "outcome. Used by LK004.",
    )

    def all_codes(self) -> set[str]:
        """Every outcome code value."""
        return {v for cs in self.codes for v in cs.values}

    def all_proxies(self) -> set[str]:
        """Every proxy code value."""
        return {v for cs in self.proxy_codes for v in cs.values}

    def all_competing(self) -> set[str]:
        """Every competing-event code value."""
        return {v for cs in self.competing_codes for v in cs.values}

all_codes

all_codes() -> set[str]

Every outcome code value.

Source code in src/ehrlint/schemas/task.py
def all_codes(self) -> set[str]:
    """Every outcome code value."""
    return {v for cs in self.codes for v in cs.values}

all_proxies

all_proxies() -> set[str]

Every proxy code value.

Source code in src/ehrlint/schemas/task.py
def all_proxies(self) -> set[str]:
    """Every proxy code value."""
    return {v for cs in self.proxy_codes for v in cs.values}

all_competing

all_competing() -> set[str]

Every competing-event code value.

Source code in src/ehrlint/schemas/task.py
def all_competing(self) -> set[str]:
    """Every competing-event code value."""
    return {v for cs in self.competing_codes for v in cs.values}

FollowUp

Bases: BaseModel

Follow-up requirements, which is where immortal-time bias lives.

Source code in src/ehrlint/schemas/task.py
class FollowUp(BaseModel):
    """Follow-up requirements, which is where immortal-time bias lives."""

    model_config = ConfigDict(extra="forbid")

    require_full_horizon_for_negatives: bool = Field(
        default=True,
        description="A subject labelled negative must have been observed for the whole "
        "horizon. Without this, a subject who left the data after one month counts as "
        "a two-year negative -- the classic immortal-time error.",
    )
    min_days: float | None = Field(
        default=None,
        ge=0,
        description="Minimum observed follow-up for any subject, in days.",
    )
    allow_death_as_censoring: bool = Field(
        default=True,
        description="Treat death as censoring rather than as a failed negative. When "
        "false, a subject who dies mid-horizon without the outcome is flagged.",
    )

SplitsSpec

Bases: BaseModel

How the splits were constructed, so the split checks know what to expect.

Source code in src/ehrlint/schemas/task.py
class SplitsSpec(BaseModel):
    """How the splits were constructed, so the split checks know what to expect."""

    model_config = ConfigDict(extra="forbid")

    strategy: SplitStrategy = SplitStrategy.SUBJECT
    temporal: bool = Field(
        default=False,
        description="Whether the split is meant to respect time. When true, LK006 "
        "becomes an error rather than a warning.",
    )
    group_column: str | None = Field(
        default=None,
        description="Column defining a group that must not straddle splits, e.g. "
        "encounter_id or provider_id. Used by LK008.",
    )

TaskSpec

Bases: BaseModel

A complete task definition.

Source code in src/ehrlint/schemas/task.py
class TaskSpec(BaseModel):
    """A complete task definition."""

    model_config = ConfigDict(extra="forbid")

    task: str = Field(min_length=1)
    index: IndexDef = Field(default_factory=IndexDef)
    outcome: OutcomeDef = Field(default_factory=OutcomeDef)
    horizon: Duration | None = None
    followup: FollowUp = Field(default_factory=FollowUp)
    exclusion: list[CodeSet] = Field(default_factory=list)
    splits: SplitsSpec = Field(default_factory=SplitsSpec)
    description: str | None = None

    @field_validator("horizon", mode="before")
    @classmethod
    def _coerce_horizon(cls, v: object) -> object:
        return Duration.parse(v) if isinstance(v, str) else v

    @model_validator(mode="after")
    def _check_consistency(self) -> TaskSpec:
        """Reject combinations that cannot be audited meaningfully."""
        if self.followup.require_full_horizon_for_negatives and self.horizon is None:
            raise TaskSpecError(
                "followup.require_full_horizon_for_negatives is true but no horizon is "
                "declared, so there is no window to require. Set `horizon` or turn the "
                "requirement off."
            )
        if self.outcome.window is not None and len(self.outcome.window) != 2:
            raise TaskSpecError(
                f"outcome.window needs exactly two expressions (start and end), got "
                f"{len(self.outcome.window)}"
            )
        return self

    # -- loading --------------------------------------------------------

    @classmethod
    def from_yaml(cls, path: str | Path) -> TaskSpec:
        """Load a task spec from YAML."""
        source = Path(path)
        if not source.exists():
            raise TaskSpecError(f"task spec not found: {source}")
        try:
            raw = yaml.safe_load(source.read_text()) or {}
        except yaml.YAMLError as exc:
            raise TaskSpecError(f"invalid YAML in {source}: {exc}") from exc
        if not isinstance(raw, dict):
            raise TaskSpecError(
                f"{source}: the task spec root must be a mapping, got {type(raw).__name__}"
            )
        return cls.from_dict(raw, source=str(source))

    @classmethod
    def from_dict(cls, raw: dict[str, Any], *, source: str = "<dict>") -> TaskSpec:
        """Build a task spec from a plain dict, accepting documented shorthands."""
        data = dict(raw)

        # §6.1 writes outcome.codes as a list of {system, values} mappings, and
        # allows a bare list of code strings as a shorthand.
        outcome = data.get("outcome")
        if isinstance(outcome, dict):
            outcome = dict(outcome)
            for key in ("codes", "proxy_codes", "competing_codes"):
                outcome[key] = _normalize_code_sets(outcome.get(key))
            data["outcome"] = outcome
        data["exclusion"] = _normalize_code_sets(data.get("exclusion"))

        try:
            return cls.model_validate(data)
        except TaskSpecError:
            raise
        except Exception as exc:
            raise TaskSpecError(f"{source}: invalid task spec: {_detail(exc)}") from exc

    def to_yaml(self, path: str | Path) -> Path:
        """Write the task spec to YAML, round-trippable through `from_yaml`."""
        import json

        target = Path(path)
        target.parent.mkdir(parents=True, exist_ok=True)
        payload = json.loads(self.model_dump_json(exclude_none=True))
        # Durations round-trip as their shorthand rather than as a nested dict.
        if self.horizon is not None:
            payload["horizon"] = str(self.horizon)
        target.write_text(yaml.safe_dump(payload, sort_keys=True))
        return target

    def describe(self) -> dict[str, Any]:
        """Short summary for the report header."""
        return {
            "task": self.task,
            "index_event": self.index.event or "(from labels)",
            "horizon": str(self.horizon) if self.horizon else None,
            "n_outcome_codes": len(self.outcome.all_codes()),
            "n_proxy_codes": len(self.outcome.all_proxies()),
            "n_competing_codes": len(self.outcome.all_competing()),
            "split_strategy": self.splits.strategy.value,
            "temporal_split": self.splits.temporal,
            "require_full_horizon_for_negatives": (
                self.followup.require_full_horizon_for_negatives
            ),
        }

    def warnings(self) -> list[str]:
        """Things about this spec that will limit what can be audited.

        Returned rather than raised: an under-specified task is still worth
        auditing for what it does declare, but the report should say which
        checks were weakened.
        """
        out: list[str] = []
        if not self.outcome.codes:
            out.append(
                "no outcome codes are declared, so the label and horizon checks "
                "(LK007, LK010) cannot verify the outcome and will skip"
            )
        if not self.outcome.proxy_codes:
            out.append(
                "no proxy codes are declared, so LK003 has nothing to look for. Proxies "
                "are task-specific and ehrlint cannot infer them -- list the treatments "
                "or codes that imply your outcome"
            )
        if self.horizon is None:
            out.append("no horizon is declared, so LK010 will skip")
        if self.splits.group_column is None:
            out.append(
                "no splits.group_column is declared, so LK008 falls back to encounter_id "
                "if present and skips otherwise"
            )
        if any(cs.system is None for cs in self.outcome.codes):
            out.append(
                "some outcome code sets declare no system, so matching falls back to the "
                "bare code and may cross-match between vocabularies"
            )
        return out

from_yaml classmethod

from_yaml(path: str | Path) -> TaskSpec

Load a task spec from YAML.

Source code in src/ehrlint/schemas/task.py
@classmethod
def from_yaml(cls, path: str | Path) -> TaskSpec:
    """Load a task spec from YAML."""
    source = Path(path)
    if not source.exists():
        raise TaskSpecError(f"task spec not found: {source}")
    try:
        raw = yaml.safe_load(source.read_text()) or {}
    except yaml.YAMLError as exc:
        raise TaskSpecError(f"invalid YAML in {source}: {exc}") from exc
    if not isinstance(raw, dict):
        raise TaskSpecError(
            f"{source}: the task spec root must be a mapping, got {type(raw).__name__}"
        )
    return cls.from_dict(raw, source=str(source))

from_dict classmethod

from_dict(
    raw: dict[str, Any], *, source: str = "<dict>"
) -> TaskSpec

Build a task spec from a plain dict, accepting documented shorthands.

Source code in src/ehrlint/schemas/task.py
@classmethod
def from_dict(cls, raw: dict[str, Any], *, source: str = "<dict>") -> TaskSpec:
    """Build a task spec from a plain dict, accepting documented shorthands."""
    data = dict(raw)

    # §6.1 writes outcome.codes as a list of {system, values} mappings, and
    # allows a bare list of code strings as a shorthand.
    outcome = data.get("outcome")
    if isinstance(outcome, dict):
        outcome = dict(outcome)
        for key in ("codes", "proxy_codes", "competing_codes"):
            outcome[key] = _normalize_code_sets(outcome.get(key))
        data["outcome"] = outcome
    data["exclusion"] = _normalize_code_sets(data.get("exclusion"))

    try:
        return cls.model_validate(data)
    except TaskSpecError:
        raise
    except Exception as exc:
        raise TaskSpecError(f"{source}: invalid task spec: {_detail(exc)}") from exc

to_yaml

to_yaml(path: str | Path) -> Path

Write the task spec to YAML, round-trippable through from_yaml.

Source code in src/ehrlint/schemas/task.py
def to_yaml(self, path: str | Path) -> Path:
    """Write the task spec to YAML, round-trippable through `from_yaml`."""
    import json

    target = Path(path)
    target.parent.mkdir(parents=True, exist_ok=True)
    payload = json.loads(self.model_dump_json(exclude_none=True))
    # Durations round-trip as their shorthand rather than as a nested dict.
    if self.horizon is not None:
        payload["horizon"] = str(self.horizon)
    target.write_text(yaml.safe_dump(payload, sort_keys=True))
    return target

describe

describe() -> dict[str, Any]

Short summary for the report header.

Source code in src/ehrlint/schemas/task.py
def describe(self) -> dict[str, Any]:
    """Short summary for the report header."""
    return {
        "task": self.task,
        "index_event": self.index.event or "(from labels)",
        "horizon": str(self.horizon) if self.horizon else None,
        "n_outcome_codes": len(self.outcome.all_codes()),
        "n_proxy_codes": len(self.outcome.all_proxies()),
        "n_competing_codes": len(self.outcome.all_competing()),
        "split_strategy": self.splits.strategy.value,
        "temporal_split": self.splits.temporal,
        "require_full_horizon_for_negatives": (
            self.followup.require_full_horizon_for_negatives
        ),
    }

warnings

warnings() -> list[str]

Things about this spec that will limit what can be audited.

Returned rather than raised: an under-specified task is still worth auditing for what it does declare, but the report should say which checks were weakened.

Source code in src/ehrlint/schemas/task.py
def warnings(self) -> list[str]:
    """Things about this spec that will limit what can be audited.

    Returned rather than raised: an under-specified task is still worth
    auditing for what it does declare, but the report should say which
    checks were weakened.
    """
    out: list[str] = []
    if not self.outcome.codes:
        out.append(
            "no outcome codes are declared, so the label and horizon checks "
            "(LK007, LK010) cannot verify the outcome and will skip"
        )
    if not self.outcome.proxy_codes:
        out.append(
            "no proxy codes are declared, so LK003 has nothing to look for. Proxies "
            "are task-specific and ehrlint cannot infer them -- list the treatments "
            "or codes that imply your outcome"
        )
    if self.horizon is None:
        out.append("no horizon is declared, so LK010 will skip")
    if self.splits.group_column is None:
        out.append(
            "no splits.group_column is declared, so LK008 falls back to encounter_id "
            "if present and skips otherwise"
        )
    if any(cs.system is None for cs in self.outcome.codes):
        out.append(
            "some outcome code sets declare no system, so matching falls back to the "
            "bare code and may cross-match between vocabularies"
        )
    return out

ehrlint.schemas.splits

Train/validation/test splits.

Two input shapes, one model:

  • ehrlint's own JSON — {"train": ["s1", ...], "valid": [...], "test": [...]} (SPEC §6.2);
  • a MEDS subject_splits.parquet with subject_id and split, whose split names are train, tuning, held_out rather than train/valid/test.

Those two vocabularies are reconciled here, with an alias map, because tuning and valid mean the same thing and a user should not have to rename their splits to run an audit. See docs/decisions.md D-003.

Subject ids are normalized to string for the same reason as in the event table: an int/string mismatch between a splits file and an event table produces an empty intersection, which looks exactly like "no overlap found".

Splits

Bases: BaseModel

Subject ids per split.

Source code in src/ehrlint/schemas/splits.py
class Splits(BaseModel):
    """Subject ids per split."""

    model_config = ConfigDict(extra="forbid")

    assignments: dict[str, list[str]] = Field(default_factory=dict)
    source: str | None = None
    original_names: dict[str, str] = Field(
        default_factory=dict,
        description="Canonical name -> the name in the source file, so the report can "
        "echo the user's own vocabulary.",
    )

    @field_validator("assignments")
    @classmethod
    def _normalize(cls, v: dict[str, list[str]]) -> dict[str, list[str]]:
        return {str(k): sorted({str(s) for s in ids if s is not None}) for k, ids in v.items()}

    def __len__(self) -> int:
        return len(self.assignments)

    def __bool__(self) -> bool:
        return bool(self.assignments)

    @property
    def names(self) -> list[str]:
        """Split names, canonical ones first in a stable order."""
        known = [n for n in SPLIT_ORDER if n in self.assignments]
        extra = sorted(set(self.assignments) - set(SPLIT_ORDER))
        return known + extra

    def get(self, name: str) -> list[str]:
        """Subject ids in one split, or an empty list."""
        return self.assignments.get(name, [])

    def all_subjects(self) -> set[str]:
        """Every subject id mentioned in any split."""
        return {s for ids in self.assignments.values() for s in ids}

    def sizes(self) -> dict[str, int]:
        """Subject count per split."""
        return {name: len(self.assignments[name]) for name in self.names}

    def overlaps(self) -> dict[tuple[str, str], list[str]]:
        """Subject ids appearing in more than one split.

        Returns:
            ``{(split_a, split_b): [subject_id, ...]}`` for every pair that
            intersects, sorted. Empty when the splits are disjoint.
        """
        out: dict[tuple[str, str], list[str]] = {}
        names = self.names
        for i, a in enumerate(names):
            for b in names[i + 1 :]:
                shared = sorted(set(self.assignments[a]) & set(self.assignments[b]))
                if shared:
                    out[(a, b)] = shared
        return out

    def split_of(self) -> dict[str, list[str]]:
        """Subject id -> the splits it appears in.

        A subject with more than one entry is an LK005 finding.
        """
        out: dict[str, list[str]] = {}
        for name in self.names:
            for subject in self.assignments[name]:
                out.setdefault(subject, []).append(name)
        return out

    def as_frame(self) -> pl.DataFrame:
        """Long-format frame with ``subject_id`` and ``split``."""
        rows = [
            {"subject_id": subject, "split": name}
            for name in self.names
            for subject in self.assignments[name]
        ]
        if not rows:
            return pl.DataFrame(schema={"subject_id": pl.String, "split": pl.String})
        return pl.DataFrame(rows)

    def describe(self) -> dict[str, Any]:
        """Summary for the report header."""
        return {
            "source": self.source,
            "names": self.names,
            "sizes": self.sizes(),
            "n_subjects": len(self.all_subjects()),
            "n_overlapping_pairs": len(self.overlaps()),
            "original_names": self.original_names,
        }

    # -- loading --------------------------------------------------------

    @classmethod
    def from_json(cls, path: str | Path) -> Splits:
        """Load ehrlint's own splits JSON (SPEC §6.2)."""
        source = Path(path)
        if not source.exists():
            raise SplitsError(f"splits file not found: {source}")
        try:
            raw = json.loads(source.read_text())
        except json.JSONDecodeError as exc:
            raise SplitsError(f"{source}: malformed JSON: {exc.msg}") from exc
        if not isinstance(raw, dict):
            raise SplitsError(
                f"{source}: expected an object mapping split name to subject id list, "
                f"got {type(raw).__name__}"
            )
        return cls.from_mapping(raw, source=str(source))

    @classmethod
    def from_mapping(cls, raw: dict[str, Any], *, source: str | None = None) -> Splits:
        """Build from a plain mapping of split name to subject ids."""
        assignments: dict[str, list[str]] = {}
        original: dict[str, str] = {}
        for name, ids in raw.items():
            if not isinstance(ids, (list, tuple, set)):
                raise SplitsError(
                    f"split {name!r} must map to a list of subject ids, got {type(ids).__name__}"
                )
            canonical = canonical_split_name(name)
            original[canonical] = str(name)
            assignments.setdefault(canonical, [])
            assignments[canonical].extend(str(s) for s in ids if s is not None)
        if not assignments:
            raise SplitsError(f"{source or 'splits'} defines no splits")
        return cls(assignments=assignments, source=source, original_names=original)

    @classmethod
    def from_meds(cls, path: str | Path, *, id_map: dict[str, str] | None = None) -> Splits:
        """Load a MEDS ``subject_splits.parquet``.

        Expects ``subject_id`` and ``split``. MEDS split names (`train`,
        `tuning`, `held_out`) are mapped to ehrlint's canonical ones.

        Args:
            path: The splits parquet.
            id_map: Surrogate-to-original subject id mapping, when the dataset
                carries one. The splits file has to use the same int64 ids as
                the event shards; without the same mapping applied here, the
                splits would name subjects the event table does not contain and
                LK005 and LK008 would both find nothing to compare.
        """
        source = Path(path)
        if not source.exists():
            raise SplitsError(f"MEDS subject splits not found: {source}")
        try:
            df = pl.read_parquet(source)
        except Exception as exc:
            raise SplitsError(f"{source}: could not read parquet: {exc}") from exc

        missing = [c for c in ("subject_id", "split") if c not in df.columns]
        if missing:
            raise SplitsError(
                f"{source}: MEDS subject splits need column(s) {missing}; found {df.columns}"
            )

        df = df.with_columns(
            pl.col("subject_id").cast(pl.String, strict=False),
            pl.col("split").cast(pl.String, strict=False),
        )
        raw: dict[str, list[str]] = {}
        for row in df.drop_nulls("split").iter_rows(named=True):
            subject = str(row["subject_id"])
            if id_map is not None:
                if subject not in id_map:
                    raise SplitsError(
                        f"{source}: subject id {subject!r} is not in the dataset's "
                        "subject id map. Mixing mapped and unmapped ids would make "
                        "the split comparisons silently vacuous"
                    )
                subject = id_map[subject]
            raw.setdefault(str(row["split"]), []).append(subject)
        return cls.from_mapping(raw, source=str(source))

    @classmethod
    def from_frame(cls, df: pl.DataFrame, *, source: str | None = None) -> Splits:
        """Build from a long-format frame with ``subject_id`` and ``split``."""
        missing = [c for c in ("subject_id", "split") if c not in df.columns]
        if missing:
            raise SplitsError(f"splits frame needs column(s) {missing}; found {df.columns}")
        raw: dict[str, list[str]] = {}
        for row in df.drop_nulls("split").iter_rows(named=True):
            raw.setdefault(str(row["split"]), []).append(str(row["subject_id"]))
        return cls.from_mapping(raw, source=source)

    def write_json(self, path: str | Path) -> Path:
        """Write in ehrlint's splits JSON format."""
        target = Path(path)
        target.parent.mkdir(parents=True, exist_ok=True)
        target.write_text(json.dumps({n: self.assignments[n] for n in self.names}, indent=2))
        return target

    def warnings(self, known_subjects: set[str] | None = None) -> list[str]:
        """Problems worth reporting that are not themselves findings."""
        out: list[str] = []
        empty = [n for n in self.names if not self.assignments[n]]
        if empty:
            out.append(f"split(s) {empty} contain no subjects")
        if len(self.names) < 2:
            out.append(
                f"only {len(self.names)} split is defined, so the split checks "
                "(LK005, LK006, LK008) have nothing to compare"
            )
        if known_subjects is not None:
            assigned = self.all_subjects()
            unknown = sorted(assigned - known_subjects)
            if unknown:
                out.append(
                    f"{len(unknown)} subject(s) in the splits do not appear in the event "
                    f"data, e.g. {unknown[:5]}. This usually means a subject-id type or "
                    "format mismatch between the two files"
                )
            unassigned = sorted(known_subjects - assigned)
            if unassigned:
                out.append(
                    f"{len(unassigned)} subject(s) in the event data are in no split, "
                    f"e.g. {unassigned[:5]}"
                )
        return out

names property

names: list[str]

Split names, canonical ones first in a stable order.

get

get(name: str) -> list[str]

Subject ids in one split, or an empty list.

Source code in src/ehrlint/schemas/splits.py
def get(self, name: str) -> list[str]:
    """Subject ids in one split, or an empty list."""
    return self.assignments.get(name, [])

all_subjects

all_subjects() -> set[str]

Every subject id mentioned in any split.

Source code in src/ehrlint/schemas/splits.py
def all_subjects(self) -> set[str]:
    """Every subject id mentioned in any split."""
    return {s for ids in self.assignments.values() for s in ids}

sizes

sizes() -> dict[str, int]

Subject count per split.

Source code in src/ehrlint/schemas/splits.py
def sizes(self) -> dict[str, int]:
    """Subject count per split."""
    return {name: len(self.assignments[name]) for name in self.names}

overlaps

overlaps() -> dict[tuple[str, str], list[str]]

Subject ids appearing in more than one split.

Returns:

Type Description
dict[tuple[str, str], list[str]]

{(split_a, split_b): [subject_id, ...]} for every pair that

dict[tuple[str, str], list[str]]

intersects, sorted. Empty when the splits are disjoint.

Source code in src/ehrlint/schemas/splits.py
def overlaps(self) -> dict[tuple[str, str], list[str]]:
    """Subject ids appearing in more than one split.

    Returns:
        ``{(split_a, split_b): [subject_id, ...]}`` for every pair that
        intersects, sorted. Empty when the splits are disjoint.
    """
    out: dict[tuple[str, str], list[str]] = {}
    names = self.names
    for i, a in enumerate(names):
        for b in names[i + 1 :]:
            shared = sorted(set(self.assignments[a]) & set(self.assignments[b]))
            if shared:
                out[(a, b)] = shared
    return out

split_of

split_of() -> dict[str, list[str]]

Subject id -> the splits it appears in.

A subject with more than one entry is an LK005 finding.

Source code in src/ehrlint/schemas/splits.py
def split_of(self) -> dict[str, list[str]]:
    """Subject id -> the splits it appears in.

    A subject with more than one entry is an LK005 finding.
    """
    out: dict[str, list[str]] = {}
    for name in self.names:
        for subject in self.assignments[name]:
            out.setdefault(subject, []).append(name)
    return out

as_frame

as_frame() -> pl.DataFrame

Long-format frame with subject_id and split.

Source code in src/ehrlint/schemas/splits.py
def as_frame(self) -> pl.DataFrame:
    """Long-format frame with ``subject_id`` and ``split``."""
    rows = [
        {"subject_id": subject, "split": name}
        for name in self.names
        for subject in self.assignments[name]
    ]
    if not rows:
        return pl.DataFrame(schema={"subject_id": pl.String, "split": pl.String})
    return pl.DataFrame(rows)

describe

describe() -> dict[str, Any]

Summary for the report header.

Source code in src/ehrlint/schemas/splits.py
def describe(self) -> dict[str, Any]:
    """Summary for the report header."""
    return {
        "source": self.source,
        "names": self.names,
        "sizes": self.sizes(),
        "n_subjects": len(self.all_subjects()),
        "n_overlapping_pairs": len(self.overlaps()),
        "original_names": self.original_names,
    }

from_json classmethod

from_json(path: str | Path) -> Splits

Load ehrlint's own splits JSON (SPEC §6.2).

Source code in src/ehrlint/schemas/splits.py
@classmethod
def from_json(cls, path: str | Path) -> Splits:
    """Load ehrlint's own splits JSON (SPEC §6.2)."""
    source = Path(path)
    if not source.exists():
        raise SplitsError(f"splits file not found: {source}")
    try:
        raw = json.loads(source.read_text())
    except json.JSONDecodeError as exc:
        raise SplitsError(f"{source}: malformed JSON: {exc.msg}") from exc
    if not isinstance(raw, dict):
        raise SplitsError(
            f"{source}: expected an object mapping split name to subject id list, "
            f"got {type(raw).__name__}"
        )
    return cls.from_mapping(raw, source=str(source))

from_mapping classmethod

from_mapping(
    raw: dict[str, Any], *, source: str | None = None
) -> Splits

Build from a plain mapping of split name to subject ids.

Source code in src/ehrlint/schemas/splits.py
@classmethod
def from_mapping(cls, raw: dict[str, Any], *, source: str | None = None) -> Splits:
    """Build from a plain mapping of split name to subject ids."""
    assignments: dict[str, list[str]] = {}
    original: dict[str, str] = {}
    for name, ids in raw.items():
        if not isinstance(ids, (list, tuple, set)):
            raise SplitsError(
                f"split {name!r} must map to a list of subject ids, got {type(ids).__name__}"
            )
        canonical = canonical_split_name(name)
        original[canonical] = str(name)
        assignments.setdefault(canonical, [])
        assignments[canonical].extend(str(s) for s in ids if s is not None)
    if not assignments:
        raise SplitsError(f"{source or 'splits'} defines no splits")
    return cls(assignments=assignments, source=source, original_names=original)

from_meds classmethod

from_meds(
    path: str | Path,
    *,
    id_map: dict[str, str] | None = None,
) -> Splits

Load a MEDS subject_splits.parquet.

Expects subject_id and split. MEDS split names (train, tuning, held_out) are mapped to ehrlint's canonical ones.

Parameters:

Name Type Description Default
path str | Path

The splits parquet.

required
id_map dict[str, str] | None

Surrogate-to-original subject id mapping, when the dataset carries one. The splits file has to use the same int64 ids as the event shards; without the same mapping applied here, the splits would name subjects the event table does not contain and LK005 and LK008 would both find nothing to compare.

None
Source code in src/ehrlint/schemas/splits.py
@classmethod
def from_meds(cls, path: str | Path, *, id_map: dict[str, str] | None = None) -> Splits:
    """Load a MEDS ``subject_splits.parquet``.

    Expects ``subject_id`` and ``split``. MEDS split names (`train`,
    `tuning`, `held_out`) are mapped to ehrlint's canonical ones.

    Args:
        path: The splits parquet.
        id_map: Surrogate-to-original subject id mapping, when the dataset
            carries one. The splits file has to use the same int64 ids as
            the event shards; without the same mapping applied here, the
            splits would name subjects the event table does not contain and
            LK005 and LK008 would both find nothing to compare.
    """
    source = Path(path)
    if not source.exists():
        raise SplitsError(f"MEDS subject splits not found: {source}")
    try:
        df = pl.read_parquet(source)
    except Exception as exc:
        raise SplitsError(f"{source}: could not read parquet: {exc}") from exc

    missing = [c for c in ("subject_id", "split") if c not in df.columns]
    if missing:
        raise SplitsError(
            f"{source}: MEDS subject splits need column(s) {missing}; found {df.columns}"
        )

    df = df.with_columns(
        pl.col("subject_id").cast(pl.String, strict=False),
        pl.col("split").cast(pl.String, strict=False),
    )
    raw: dict[str, list[str]] = {}
    for row in df.drop_nulls("split").iter_rows(named=True):
        subject = str(row["subject_id"])
        if id_map is not None:
            if subject not in id_map:
                raise SplitsError(
                    f"{source}: subject id {subject!r} is not in the dataset's "
                    "subject id map. Mixing mapped and unmapped ids would make "
                    "the split comparisons silently vacuous"
                )
            subject = id_map[subject]
        raw.setdefault(str(row["split"]), []).append(subject)
    return cls.from_mapping(raw, source=str(source))

from_frame classmethod

from_frame(
    df: DataFrame, *, source: str | None = None
) -> Splits

Build from a long-format frame with subject_id and split.

Source code in src/ehrlint/schemas/splits.py
@classmethod
def from_frame(cls, df: pl.DataFrame, *, source: str | None = None) -> Splits:
    """Build from a long-format frame with ``subject_id`` and ``split``."""
    missing = [c for c in ("subject_id", "split") if c not in df.columns]
    if missing:
        raise SplitsError(f"splits frame needs column(s) {missing}; found {df.columns}")
    raw: dict[str, list[str]] = {}
    for row in df.drop_nulls("split").iter_rows(named=True):
        raw.setdefault(str(row["split"]), []).append(str(row["subject_id"]))
    return cls.from_mapping(raw, source=source)

write_json

write_json(path: str | Path) -> Path

Write in ehrlint's splits JSON format.

Source code in src/ehrlint/schemas/splits.py
def write_json(self, path: str | Path) -> Path:
    """Write in ehrlint's splits JSON format."""
    target = Path(path)
    target.parent.mkdir(parents=True, exist_ok=True)
    target.write_text(json.dumps({n: self.assignments[n] for n in self.names}, indent=2))
    return target

warnings

warnings(
    known_subjects: set[str] | None = None,
) -> list[str]

Problems worth reporting that are not themselves findings.

Source code in src/ehrlint/schemas/splits.py
def warnings(self, known_subjects: set[str] | None = None) -> list[str]:
    """Problems worth reporting that are not themselves findings."""
    out: list[str] = []
    empty = [n for n in self.names if not self.assignments[n]]
    if empty:
        out.append(f"split(s) {empty} contain no subjects")
    if len(self.names) < 2:
        out.append(
            f"only {len(self.names)} split is defined, so the split checks "
            "(LK005, LK006, LK008) have nothing to compare"
        )
    if known_subjects is not None:
        assigned = self.all_subjects()
        unknown = sorted(assigned - known_subjects)
        if unknown:
            out.append(
                f"{len(unknown)} subject(s) in the splits do not appear in the event "
                f"data, e.g. {unknown[:5]}. This usually means a subject-id type or "
                "format mismatch between the two files"
            )
        unassigned = sorted(known_subjects - assigned)
        if unassigned:
            out.append(
                f"{len(unassigned)} subject(s) in the event data are in no split, "
                f"e.g. {unassigned[:5]}"
            )
    return out

canonical_split_name

canonical_split_name(name: str) -> str

Map a split name to its canonical form.

An unrecognized name is kept as-is rather than guessed at: a project may legitimately have a fourth split, and renaming it would hide that.

Source code in src/ehrlint/schemas/splits.py
def canonical_split_name(name: str) -> str:
    """Map a split name to its canonical form.

    An unrecognized name is kept as-is rather than guessed at: a project may
    legitimately have a fourth split, and renaming it would hide that.
    """
    return SPLIT_ALIASES.get(str(name).strip().lower(), str(name).strip())

ehrlint.schemas.findings

Findings: what a check reports, and the evidence it must carry.

The §0 rule this module exists to enforce: do not fabricate leakage statistics. Every finding references the concrete rows that triggered it — subject ids, event times, feature names — not just a count.

A Finding with a non-zero n_subjects and no examples is a contradiction, and :meth:Finding.validate_evidence raises on it. That is deliberate: a count without rows is an assertion a user cannot check, and an auditor whose claims cannot be checked is worse than no auditor.

Findings are also deterministic: given the same inputs, the same findings in the same order with the same examples. Example rows are sorted before truncation so a run on shuffled input produces identical output. A property test asserts it.

Severity

Bases: StrEnum

What a finding means for the task.

  • error -- the task is invalid as defined. Post-index features, split overlap, a label using future information.
  • warning -- a suspicious pattern needing human review. Proxies, temporal edge cases.
  • info -- descriptive statistics, not a problem.
Source code in src/ehrlint/schemas/findings.py
class Severity(StrEnum):
    """What a finding means for the task.

    * ``error`` -- the task is invalid as defined. Post-index features, split
      overlap, a label using future information.
    * ``warning`` -- a suspicious pattern needing human review. Proxies,
      temporal edge cases.
    * ``info`` -- descriptive statistics, not a problem.
    """

    ERROR = "error"
    WARNING = "warning"
    INFO = "info"

    @property
    def rank(self) -> int:
        """Ordering for threshold comparisons; higher is more severe."""
        return {"info": 0, "warning": 1, "error": 2}[self.value]

    def at_least(self, threshold: Severity) -> bool:
        """Whether this severity meets or exceeds ``threshold``."""
        return self.rank >= threshold.rank

rank property

rank: int

Ordering for threshold comparisons; higher is more severe.

at_least

at_least(threshold: Severity) -> bool

Whether this severity meets or exceeds threshold.

Source code in src/ehrlint/schemas/findings.py
def at_least(self, threshold: Severity) -> bool:
    """Whether this severity meets or exceeds ``threshold``."""
    return self.rank >= threshold.rank

Finding

Bases: BaseModel

One leakage finding, with the evidence that produced it.

Source code in src/ehrlint/schemas/findings.py
class Finding(BaseModel):
    """One leakage finding, with the evidence that produced it."""

    model_config = ConfigDict(extra="forbid")

    check_id: str = Field(min_length=1)
    name: str = ""
    severity: Severity
    message: str = Field(min_length=1, description="One sentence a reviewer can act on.")
    n_subjects: int = Field(default=0, ge=0)
    n_total_subjects: int = Field(default=0, ge=0, description="Denominator for `subject_rate`.")
    n_rows: int = Field(default=0, ge=0, description="Offending rows, which may exceed n_subjects.")
    examples: list[dict[str, Any]] = Field(
        default_factory=list,
        description="Concrete rows that triggered this finding. Never aggregates.",
    )
    example_columns: list[str] = Field(default_factory=list)
    query: str = Field(
        default="",
        description="The exact logic, in SQL-ish pseudocode, so a reader can "
        "reproduce the finding by hand.",
    )
    subjects: list[str] = Field(
        default_factory=list,
        description="Affected subject ids, truncated. The audit trail for who.",
    )
    detail: dict[str, Any] = Field(default_factory=dict)

    @property
    def subject_rate(self) -> float | None:
        """Affected fraction of subjects, or None when the denominator is zero.

        ``None`` rather than ``0.0``: a rate with no denominator is undefined,
        and reporting zero would read as "no subjects affected".
        """
        if self.n_total_subjects <= 0:
            return None
        return self.n_subjects / self.n_total_subjects

    @property
    def fired(self) -> bool:
        """Whether this finding reports a problem."""
        return self.severity is not Severity.INFO and self.n_subjects > 0

    @model_validator(mode="after")
    def _evidence_present(self) -> Finding:
        """A non-zero count must be backed by rows.

        SPEC §0: no fabricated statistics. An `info` finding is exempt, since
        descriptive statistics are aggregates by nature.
        """
        if self.severity is not Severity.INFO and self.n_subjects > 0 and not self.examples:
            raise ValueError(
                f"{self.check_id} reports {self.n_subjects} affected subject(s) but "
                "carries no example rows. Every finding must reference the concrete "
                "rows that triggered it (SPEC §0)."
            )
        return self

    def validate_evidence(self, events: pl.DataFrame | None = None) -> None:
        """Assert the example rows exist in the source data.

        Args:
            events: The canonical event table, when the examples are events.

        Raises:
            ValueError: If an example references a subject absent from the
                data, which would mean the finding was constructed rather than
                observed.
        """
        if events is None or not self.subjects:
            return
        from ehrlint.schemas.events import SUBJECT_ID

        if SUBJECT_ID not in events.columns:
            return
        known = set(events[SUBJECT_ID].drop_nulls().unique().to_list())
        unknown = [s for s in self.subjects if s not in known]
        if unknown:
            raise ValueError(
                f"{self.check_id} references subject(s) {unknown[:5]} that do not appear "
                "in the input data"
            )

    def to_dict(self) -> dict[str, Any]:
        """JSON-safe dict, the §6.3 findings-JSONL shape."""
        return {
            "check_id": self.check_id,
            "name": self.name,
            "severity": self.severity.value,
            "message": self.message,
            "n_subjects": self.n_subjects,
            "n_total_subjects": self.n_total_subjects,
            "subject_rate": self.subject_rate,
            "n_rows": self.n_rows,
            "examples": self.examples,
            "example_columns": self.example_columns,
            "subjects": self.subjects,
            "query": self.query,
            "detail": self.detail,
        }

    def examples_frame(self) -> pl.DataFrame:
        """The example rows as a frame, for `finding.examples.head()` ergonomics."""
        if not self.examples:
            return pl.DataFrame()
        return pl.DataFrame(self.examples)

subject_rate property

subject_rate: float | None

Affected fraction of subjects, or None when the denominator is zero.

None rather than 0.0: a rate with no denominator is undefined, and reporting zero would read as "no subjects affected".

fired property

fired: bool

Whether this finding reports a problem.

validate_evidence

validate_evidence(events: DataFrame | None = None) -> None

Assert the example rows exist in the source data.

Parameters:

Name Type Description Default
events DataFrame | None

The canonical event table, when the examples are events.

None

Raises:

Type Description
ValueError

If an example references a subject absent from the data, which would mean the finding was constructed rather than observed.

Source code in src/ehrlint/schemas/findings.py
def validate_evidence(self, events: pl.DataFrame | None = None) -> None:
    """Assert the example rows exist in the source data.

    Args:
        events: The canonical event table, when the examples are events.

    Raises:
        ValueError: If an example references a subject absent from the
            data, which would mean the finding was constructed rather than
            observed.
    """
    if events is None or not self.subjects:
        return
    from ehrlint.schemas.events import SUBJECT_ID

    if SUBJECT_ID not in events.columns:
        return
    known = set(events[SUBJECT_ID].drop_nulls().unique().to_list())
    unknown = [s for s in self.subjects if s not in known]
    if unknown:
        raise ValueError(
            f"{self.check_id} references subject(s) {unknown[:5]} that do not appear "
            "in the input data"
        )

to_dict

to_dict() -> dict[str, Any]

JSON-safe dict, the §6.3 findings-JSONL shape.

Source code in src/ehrlint/schemas/findings.py
def to_dict(self) -> dict[str, Any]:
    """JSON-safe dict, the §6.3 findings-JSONL shape."""
    return {
        "check_id": self.check_id,
        "name": self.name,
        "severity": self.severity.value,
        "message": self.message,
        "n_subjects": self.n_subjects,
        "n_total_subjects": self.n_total_subjects,
        "subject_rate": self.subject_rate,
        "n_rows": self.n_rows,
        "examples": self.examples,
        "example_columns": self.example_columns,
        "subjects": self.subjects,
        "query": self.query,
        "detail": self.detail,
    }

examples_frame

examples_frame() -> pl.DataFrame

The example rows as a frame, for finding.examples.head() ergonomics.

Source code in src/ehrlint/schemas/findings.py
def examples_frame(self) -> pl.DataFrame:
    """The example rows as a frame, for `finding.examples.head()` ergonomics."""
    if not self.examples:
        return pl.DataFrame()
    return pl.DataFrame(self.examples)

SkippedCheck

Bases: BaseModel

A check that could not run, and why.

Recorded explicitly so a clean report is distinguishable from an incomplete one. A skipped check is not a pass.

Source code in src/ehrlint/schemas/findings.py
class SkippedCheck(BaseModel):
    """A check that could not run, and why.

    Recorded explicitly so a clean report is distinguishable from an
    incomplete one. A skipped check is **not** a pass.
    """

    model_config = ConfigDict(extra="forbid")

    check_id: str
    name: str = ""
    reason: str = Field(min_length=1)

    def to_dict(self) -> dict[str, Any]:
        """JSON-safe dict."""
        return {"check_id": self.check_id, "name": self.name, "reason": self.reason}

to_dict

to_dict() -> dict[str, Any]

JSON-safe dict.

Source code in src/ehrlint/schemas/findings.py
def to_dict(self) -> dict[str, Any]:
    """JSON-safe dict."""
    return {"check_id": self.check_id, "name": self.name, "reason": self.reason}

make_finding

make_finding(
    check_id: str,
    *,
    name: str,
    severity: Severity,
    message: str,
    offending: DataFrame,
    n_total_subjects: int,
    query: str,
    subject_column: str = "subject_id",
    example_columns: list[str] | None = None,
    detail: dict[str, Any] | None = None,
    max_examples: int = MAX_EXAMPLES,
) -> Finding

Build a finding from the rows that triggered it.

The single constructor every check uses, so evidence handling is uniform: counts come from the offending frame, examples are sorted before truncation for determinism, and the subject list is derived rather than passed in.

Parameters:

Name Type Description Default
check_id str

e.g. LK001.

required
name str

Human-readable check name.

required
severity Severity

Finding severity.

required
message str

One actionable sentence.

required
offending DataFrame

The rows that triggered the finding. Empty means the check did not fire, and a zero-count finding is returned.

required
n_total_subjects int

Denominator for the rate.

required
query str

SQL-ish pseudocode of the logic.

required
subject_column str

Which column holds the subject id.

'subject_id'
example_columns list[str] | None

Columns to include in examples. Defaults to all.

None
detail dict[str, Any] | None

Extra structured context.

None
max_examples int

How many example rows to carry.

MAX_EXAMPLES

Returns:

Name Type Description
A Finding

class:Finding.

Source code in src/ehrlint/schemas/findings.py
def make_finding(
    check_id: str,
    *,
    name: str,
    severity: Severity,
    message: str,
    offending: pl.DataFrame,
    n_total_subjects: int,
    query: str,
    subject_column: str = "subject_id",
    example_columns: list[str] | None = None,
    detail: dict[str, Any] | None = None,
    max_examples: int = MAX_EXAMPLES,
) -> Finding:
    """Build a finding from the rows that triggered it.

    The single constructor every check uses, so evidence handling is uniform:
    counts come from the offending frame, examples are sorted before truncation
    for determinism, and the subject list is derived rather than passed in.

    Args:
        check_id: e.g. ``LK001``.
        name: Human-readable check name.
        severity: Finding severity.
        message: One actionable sentence.
        offending: The rows that triggered the finding. **Empty means the check
            did not fire**, and a zero-count finding is returned.
        n_total_subjects: Denominator for the rate.
        query: SQL-ish pseudocode of the logic.
        subject_column: Which column holds the subject id.
        example_columns: Columns to include in examples. Defaults to all.
        detail: Extra structured context.
        max_examples: How many example rows to carry.

    Returns:
        A :class:`Finding`.
    """
    columns = example_columns or list(offending.columns)
    columns = [c for c in columns if c in offending.columns]

    if offending.height == 0:
        return Finding(
            check_id=check_id,
            name=name,
            severity=severity,
            message=message,
            n_subjects=0,
            n_total_subjects=n_total_subjects,
            n_rows=0,
            examples=[],
            example_columns=columns,
            query=query,
            subjects=[],
            detail=detail or {},
        )

    subject_ids: list[str] = []
    if subject_column in offending.columns:
        subject_ids = sorted({str(s) for s in offending[subject_column].drop_nulls().to_list()})

    # Sort before truncating so the examples are the same rows regardless of
    # input row order. Determinism is a tested property, not a nicety.
    #
    # The sort key has to be **total**. Sorting only by subject and time leaves
    # tied rows in whatever order the frame happened to hold them, and a
    # truncation of a tie picks different rows on different runs -- which was
    # observable in LK008, where one subject contributes several rows that
    # agree on every preferred key. The preferred columns come first so the
    # examples still read in a sensible order; the rest are appended only to
    # break ties.
    preferred = [c for c in (subject_column, "time", "code") if c in offending.columns]
    tiebreak = [
        c for c in offending.columns if c not in preferred and _is_sortable(offending.schema[c])
    ]
    sort_by = preferred + tiebreak
    ordered = offending.sort(sort_by, nulls_last=True) if sort_by else offending

    examples = [
        {k: _jsonable(v) for k, v in row.items()}
        for row in ordered.select(columns).head(max_examples).to_dicts()
    ]

    return Finding(
        check_id=check_id,
        name=name,
        severity=severity,
        message=message,
        n_subjects=len(subject_ids),
        n_total_subjects=n_total_subjects,
        n_rows=offending.height,
        examples=examples,
        example_columns=columns,
        query=query,
        subjects=subject_ids[:50],
        detail=detail or {},
    )

write_findings_jsonl

write_findings_jsonl(
    findings: list[Finding], path: str
) -> int

Write findings as JSONL, the §6.3 format. Returns the count.

Source code in src/ehrlint/schemas/findings.py
def write_findings_jsonl(findings: list[Finding], path: str) -> int:
    """Write findings as JSONL, the §6.3 format. Returns the count."""
    from pathlib import Path

    target = Path(path)
    target.parent.mkdir(parents=True, exist_ok=True)
    with target.open("w", encoding="utf-8") as fh:
        for finding in findings:
            fh.write(json.dumps(finding.to_dict(), default=str))
            fh.write("\n")
    return len(findings)

Input and output

ehrlint.io.meds

MEDS ingestion.

Verified against meds 0.4.1, by installing and introspecting the package rather than reading about it (docs/decisions.md D-002). The data schema is:

column type required
subject_id int64 yes
time timestamp[us] yes (nullable for static events)
code string yes
numeric_value float no
text_value large_string no

Three differences from the spec's §2 sketch, all handled here:

  1. There is no code_system column. MEDS namespaces the vocabulary inside the code string by convention, as ICD10CM//E11.9. ehrlint splits on the first // to recover a system, and leaves it null when there is no separator rather than guessing one.
  2. There is no encounter_id column. The same-encounter checks (LK002, LK008) therefore skip on plain MEDS input unless an extra column supplies one — MEDS sets allow_extra_columns = True, so a dataset may carry one.
  3. subject_id is int64, while ehrlint compares subject ids as strings everywhere. It is cast at ingestion.

Dataset layout, from the package's own constants:

<root>/data/**/*.parquet          the event shards
<root>/metadata/dataset.json      dataset metadata
<root>/metadata/codes.parquet     code metadata (description, parent_codes)
<root>/metadata/subject_splits.parquet   subject_id, split

read_meds_events

read_meds_events(
    data_dir: str | Path,
    *,
    encounter_column: str | None = None,
) -> pl.DataFrame

Read a MEDS dataset directory into the canonical event table.

Parameters:

Name Type Description Default
data_dir str | Path

The MEDS dataset root, or a directory of parquet shards.

required
encounter_column str | None

An extra column holding an encounter id. When None, the candidates in :data:ENCOUNTER_COLUMN_CANDIDATES are tried.

None

Returns:

Type Description
DataFrame

A canonical event table.

Raises:

Type Description
InputError

If the path is missing or holds no parquet.

SchemaError

If a required MEDS column is absent, naming which.

Source code in src/ehrlint/io/meds.py
def read_meds_events(data_dir: str | Path, *, encounter_column: str | None = None) -> pl.DataFrame:
    """Read a MEDS dataset directory into the canonical event table.

    Args:
        data_dir: The MEDS dataset root, or a directory of parquet shards.
        encounter_column: An extra column holding an encounter id. When None,
            the candidates in :data:`ENCOUNTER_COLUMN_CANDIDATES` are tried.

    Returns:
        A canonical event table.

    Raises:
        InputError: If the path is missing or holds no parquet.
        SchemaError: If a required MEDS column is absent, naming which.
    """
    root = Path(data_dir)
    if not root.exists():
        raise InputError("MEDS data path not found", path=str(root))

    shards = [root] if root.is_file() else _find_shards(root)
    if not shards:
        raise InputError(
            f"no parquet files found under {root}. A MEDS dataset keeps its shards in "
            f"a '{DATA_SUBDIRECTORY}/' subdirectory",
            path=str(root),
        )

    frames: list[pl.DataFrame] = []
    for shard in shards:
        try:
            df = pl.read_parquet(shard)
        except Exception as exc:
            raise InputError(f"could not read parquet: {exc}", path=str(shard)) from exc

        missing = [c for c in MEDS_REQUIRED_COLUMNS if c not in df.columns]
        if missing:
            raise SchemaError(
                f"MEDS shard is missing required column(s) {missing}; MEDS requires "
                f"{list(MEDS_REQUIRED_COLUMNS)} and found {df.columns}",
                path=str(shard),
            )
        frames.append(df)

    combined = pl.concat(frames, how="diagonal_relaxed")
    events = meds_frame_to_canonical(combined, encounter_column=encounter_column)
    return _restore_subject_ids(events, root)

read_subject_id_map

read_subject_id_map(
    data_dir: str | Path,
) -> dict[str, str] | None

The dataset's surrogate-to-original subject id mapping, or None.

Anything reading a sibling file keyed by subject id -- splits, labels, a feature matrix -- has to apply the same mapping the event shards used, or it will name subjects the event table does not contain.

Source code in src/ehrlint/io/meds.py
def read_subject_id_map(data_dir: str | Path) -> dict[str, str] | None:
    """The dataset's surrogate-to-original subject id mapping, or None.

    Anything reading a sibling file keyed by subject id -- splits, labels, a
    feature matrix -- has to apply the same mapping the event shards used, or
    it will name subjects the event table does not contain.
    """
    root = Path(data_dir)
    if root.is_file():
        root = root.parent
    path = root / SUBJECT_ID_MAP_FILEPATH
    if not path.exists():
        return None
    mapping = pl.read_parquet(path)
    needed = {"subject_id", "original_subject_id"}
    if not needed.issubset(mapping.columns):
        raise SchemaError(
            f"{SUBJECT_ID_MAP_FILEPATH} must have columns {sorted(needed)}; found "
            f"{mapping.columns}",
            path=str(path),
        )
    rows = mapping.select(
        pl.col("subject_id").cast(pl.String, strict=False),
        pl.col("original_subject_id").cast(pl.String, strict=False),
    ).iter_rows()
    return {surrogate: original for surrogate, original in rows if surrogate is not None}

meds_frame_to_canonical

meds_frame_to_canonical(
    df: DataFrame, *, encounter_column: str | None = None
) -> pl.DataFrame

Convert a MEDS-shaped frame to the canonical event table.

Source code in src/ehrlint/io/meds.py
def meds_frame_to_canonical(
    df: pl.DataFrame, *, encounter_column: str | None = None
) -> pl.DataFrame:
    """Convert a MEDS-shaped frame to the canonical event table."""
    missing = [c for c in MEDS_REQUIRED_COLUMNS if c not in df.columns]
    if missing:
        raise SchemaError(
            f"MEDS frame is missing required column(s) {missing}; found {df.columns}",
            table="meds",
        )

    out = df
    chosen = encounter_column
    if chosen is None:
        chosen = next((c for c in ENCOUNTER_COLUMN_CANDIDATES if c in out.columns), None)
    if chosen is not None:
        if chosen not in out.columns:
            raise SchemaError(
                f"encounter column {chosen!r} is not in the MEDS data; found {out.columns}",
                table="meds",
                column=chosen,
            )
        out = out.with_columns(pl.col(chosen).cast(pl.String, strict=False).alias("encounter_id"))

    # Recover `code_system` from the SYSTEM//code convention before coercing.
    out = split_meds_code(out)
    return coerce_events(out, source="meds")

read_dataset_metadata

read_dataset_metadata(
    data_dir: str | Path,
) -> dict[str, Any]

Read metadata/dataset.json, or return an empty dict.

Absence is not an error: a hand-made extract often has no manifest, and the audit does not depend on one. What is in it goes into the report header so a reader knows which ETL produced the data.

Source code in src/ehrlint/io/meds.py
def read_dataset_metadata(data_dir: str | Path) -> dict[str, Any]:
    """Read ``metadata/dataset.json``, or return an empty dict.

    Absence is not an error: a hand-made extract often has no manifest, and the
    audit does not depend on one. What is in it goes into the report header so a
    reader knows which ETL produced the data.
    """
    path = Path(data_dir) / DATASET_METADATA_FILEPATH
    if not path.exists():
        return {}
    try:
        raw = json.loads(path.read_text())
    except json.JSONDecodeError as exc:
        raise InputError(f"malformed dataset metadata: {exc.msg}", path=str(path)) from exc
    return raw if isinstance(raw, dict) else {}

read_code_metadata

read_code_metadata(
    data_dir: str | Path,
) -> pl.DataFrame | None

Read metadata/codes.parquet, or return None.

MEDS code metadata carries code, description, and parent_codes. ehrlint uses it only to make findings readable — a code's description alongside its id — never to expand a code set, because silently matching a parent code would change what the task means.

Source code in src/ehrlint/io/meds.py
def read_code_metadata(data_dir: str | Path) -> pl.DataFrame | None:
    """Read ``metadata/codes.parquet``, or return None.

    MEDS code metadata carries ``code``, ``description``, and ``parent_codes``.
    ehrlint uses it only to make findings readable — a code's description
    alongside its id — never to expand a code set, because silently matching a
    parent code would change what the task means.
    """
    path = Path(data_dir) / CODE_METADATA_FILEPATH
    if not path.exists():
        return None
    try:
        return pl.read_parquet(path)
    except Exception as exc:
        raise InputError(f"could not read code metadata: {exc}", path=str(path)) from exc

find_meds_splits

find_meds_splits(data_dir: str | Path) -> Path | None

Locate metadata/subject_splits.parquet if the dataset has one.

Source code in src/ehrlint/io/meds.py
def find_meds_splits(data_dir: str | Path) -> Path | None:
    """Locate ``metadata/subject_splits.parquet`` if the dataset has one."""
    path = Path(data_dir) / SUBJECT_SPLITS_FILEPATH
    return path if path.exists() else None

validate_with_meds_package

validate_with_meds_package(df: DataFrame) -> list[str]

Validate a MEDS frame with the meds package, if it is installed.

Returns a list of warnings. The meds extra is optional, so its absence is reported as a single informational line rather than failing the audit.

Source code in src/ehrlint/io/meds.py
def validate_with_meds_package(df: pl.DataFrame) -> list[str]:
    """Validate a MEDS frame with the ``meds`` package, if it is installed.

    Returns a list of warnings. The ``meds`` extra is optional, so its absence
    is reported as a single informational line rather than failing the audit.
    """
    try:
        import meds
        import pyarrow as pa
    except ImportError:
        return [
            "the `meds` package is not installed, so MEDS schema validation was "
            "skipped. Install it with: pip install 'ehrlint[meds]'"
        ]

    warnings: list[str] = []
    try:
        required = list(meds.DataSchema.required_columns())
    except Exception:  # pragma: no cover - defensive against API change
        required = list(MEDS_REQUIRED_COLUMNS)

    missing = [c for c in required if c not in df.columns]
    if missing:
        warnings.append(
            f"the installed meds {meds.__version__} requires column(s) {missing}, which "
            "the input lacks"
        )

    if set(required) != set(MEDS_REQUIRED_COLUMNS):
        warnings.append(
            f"the installed meds {meds.__version__} requires {required}, but ehrlint was "
            f"written against {list(MEDS_REQUIRED_COLUMNS)}. Re-read "
            "docs/decisions.md D-002 before trusting the ingestion."
        )

    try:
        table = df.to_arrow()
        _ = pa.schema(meds.DataSchema.schema())
        _ = table  # shape check only; MEDS allows extra columns
    except Exception as exc:  # pragma: no cover
        warnings.append(f"meds schema comparison failed: {type(exc).__name__}: {exc}")

    return warnings

write_meds_dataset

write_meds_dataset(
    events: DataFrame,
    out_dir: str | Path,
    *,
    dataset_name: str = "ehrlint-synthetic",
    dataset_version: str = "1.0.0",
    splits: DataFrame | None = None,
) -> dict[str, Path]

Write a canonical event table out in MEDS layout.

Used by the synthetic generator so the demo exercises the real MEDS reader rather than a shortcut. Codes are re-joined into the SYSTEM//code form so a round trip is faithful.

MEDS requires an int64 subject_id. Where ehrlint's string ids are not integers, a deterministic surrogate is assigned and the original is written to :data:SUBJECT_ID_MAP_FILEPATH, which the reader uses to restore them. A plain cast(Int64, strict=False) would turn every "S000042" into null, and a dataset with no subject ids audits perfectly clean.

Returns:

Type Description
dict[str, Path]

A mapping of artifact name to path.

Source code in src/ehrlint/io/meds.py
def write_meds_dataset(
    events: pl.DataFrame,
    out_dir: str | Path,
    *,
    dataset_name: str = "ehrlint-synthetic",
    dataset_version: str = "1.0.0",
    splits: pl.DataFrame | None = None,
) -> dict[str, Path]:
    """Write a canonical event table out in MEDS layout.

    Used by the synthetic generator so the demo exercises the real MEDS reader
    rather than a shortcut. Codes are re-joined into the `SYSTEM//code` form so
    a round trip is faithful.

    MEDS requires an int64 ``subject_id``. Where ehrlint's string ids are not
    integers, a deterministic surrogate is assigned and the original is written
    to :data:`SUBJECT_ID_MAP_FILEPATH`, which the reader uses to restore them.
    A plain ``cast(Int64, strict=False)`` would turn every ``"S000042"`` into
    null, and a dataset with no subject ids audits perfectly clean.

    Returns:
        A mapping of artifact name to path.
    """
    root = Path(out_dir)
    (root / DATA_SUBDIRECTORY).mkdir(parents=True, exist_ok=True)
    (root / "metadata").mkdir(parents=True, exist_ok=True)
    written: dict[str, Path] = {}

    surrogates = _subject_id_surrogates(events)

    meds_df = events.with_columns(
        pl.when(pl.col("code_system").is_not_null())
        .then(pl.concat_str([pl.col("code_system"), pl.lit("//"), pl.col("code")]))
        .otherwise(pl.col("code"))
        .alias("code"),
        pl.col("numeric_value").cast(pl.Float32, strict=False),
    )
    meds_df = _apply_subject_surrogates(meds_df, surrogates)
    keep = ["subject_id", "time", "code", "numeric_value", "text_value"]
    if "encounter_id" in meds_df.columns and meds_df["encounter_id"].null_count() < meds_df.height:
        keep.append("encounter_id")

    data_path = root / DATA_SUBDIRECTORY / "shard_0.parquet"
    meds_df.select(keep).write_parquet(data_path)
    written["data"] = data_path

    metadata = {
        "dataset_name": dataset_name,
        "dataset_version": dataset_version,
        "etl_name": "ehrlint.synth",
        "etl_version": "1.0.0",
        "meds_version": "0.4.1",
    }
    metadata_path = root / DATASET_METADATA_FILEPATH
    metadata_path.write_text(json.dumps(metadata, indent=2))
    written["dataset_metadata"] = metadata_path

    if splits is not None:
        splits_path = root / SUBJECT_SPLITS_FILEPATH
        _apply_subject_surrogates(splits, surrogates).write_parquet(splits_path)
        written["subject_splits"] = splits_path

    if surrogates is not None:
        map_path = root / SUBJECT_ID_MAP_FILEPATH
        surrogates.write_parquet(map_path)
        written["subject_id_map"] = map_path

    return written

ehrlint.io.omop

OMOP CDM ingestion.

Reads the seven clinical tables SPEC §3.1 lists and converts them to the canonical event table. Parquet or CSV, whichever is present.

The conversion is a per-table mapping of which column is the event time and which column is the code. That choice is the interesting part, and each one is stated below rather than buried, because picking the wrong date column is itself a leakage bug: using condition_end_date as the event time would place a diagnosis at its resolution rather than its onset, and every post-index check downstream would be measuring the wrong thing.

OMOP carries visit_occurrence_id on most clinical tables, which is what makes the same-encounter checks (LK002, LK008) runnable on OMOP input where they cannot run on plain MEDS.

OmopTableSpec dataclass

How one OMOP table becomes canonical events.

Attributes:

Name Type Description
table str

OMOP table name.

time_column tuple[str, ...]

The column taken as the event time, in preference order.

code_column str

The concept id column.

code_system str

The vocabulary label written to code_system.

numeric_column str | None

A numeric value column, if the table has one.

text_column str | None

A text value column, if the table has one.

source_value_column str | None

The source code, used when the concept id is 0 -- OMOP's "no mapping" sentinel.

required bool

Whether a missing table is an error.

Source code in src/ehrlint/io/omop.py
@dataclass(frozen=True, slots=True)
class OmopTableSpec:
    """How one OMOP table becomes canonical events.

    Attributes:
        table: OMOP table name.
        time_column: The column taken as the event time, in preference order.
        code_column: The concept id column.
        code_system: The vocabulary label written to ``code_system``.
        numeric_column: A numeric value column, if the table has one.
        text_column: A text value column, if the table has one.
        source_value_column: The source code, used when the concept id is 0 --
            OMOP's "no mapping" sentinel.
        required: Whether a missing table is an error.
    """

    table: str
    time_column: tuple[str, ...]
    code_column: str
    code_system: str
    numeric_column: str | None = None
    text_column: str | None = None
    source_value_column: str | None = None
    required: bool = False

read_omop_events

read_omop_events(
    data_dir: str | Path, *, include_person: bool = True
) -> pl.DataFrame

Read an OMOP CDM extract into the canonical event table.

Parameters:

Name Type Description Default
data_dir str | Path

Directory of OMOP tables, as parquet or CSV.

required
include_person bool

Convert person demographics to static events.

True

Returns:

Type Description
DataFrame

A canonical event table.

Raises:

Type Description
InputError

If the path is missing, or no recognized table was found — with the names it looked for, since a silently empty audit is worse than an error.

Source code in src/ehrlint/io/omop.py
def read_omop_events(data_dir: str | Path, *, include_person: bool = True) -> pl.DataFrame:
    """Read an OMOP CDM extract into the canonical event table.

    Args:
        data_dir: Directory of OMOP tables, as parquet or CSV.
        include_person: Convert `person` demographics to static events.

    Returns:
        A canonical event table.

    Raises:
        InputError: If the path is missing, or no recognized table was found —
            with the names it looked for, since a silently empty audit is worse
            than an error.
    """
    root = Path(data_dir)
    if not root.exists():
        raise InputError("OMOP data path not found", path=str(root))

    frames: list[pl.DataFrame] = []
    found: list[str] = []

    for spec in OMOP_TABLES:
        df = _read_table(root, spec.table)
        if df is None or df.height == 0:
            continue
        found.append(spec.table)
        frames.append(_convert_table(df, spec))

    if include_person:
        person = _read_table(root, PERSON_TABLE)
        if person is not None and person.height:
            found.append(PERSON_TABLE)
            frames.append(_convert_person(person))

    if not frames:
        expected = [s.table for s in OMOP_TABLES] + [PERSON_TABLE]
        raise InputError(
            f"no OMOP tables found under {root}. Looked for {expected} as .parquet, "
            ".csv, or a subdirectory of either",
            path=str(root),
        )

    combined = pl.concat(frames, how="vertical_relaxed")
    return coerce_events(combined, source="omop")

omop_tables_present

omop_tables_present(data_dir: str | Path) -> list[str]

Which recognized OMOP tables exist, for the report header.

Source code in src/ehrlint/io/omop.py
def omop_tables_present(data_dir: str | Path) -> list[str]:
    """Which recognized OMOP tables exist, for the report header."""
    root = Path(data_dir)
    if not root.exists():
        return []
    names = [s.table for s in OMOP_TABLES] + [PERSON_TABLE]
    return [n for n in names if _read_table(root, n) is not None]

ehrlint.io.features

The optional feature matrix.

When a user supplies the actual training features, ehrlint can check them directly rather than inferring what they must have contained from the event stream. That is a strictly stronger audit: the event stream tells you what could have leaked, the matrix tells you what did.

Expected shape: one row per prediction unit, with a subject_id column and optionally a timestamp column naming when each feature was computed as of. Everything else is treated as a feature.

FeatureMatrix

A training feature matrix, with its identifier columns located.

Attributes:

Name Type Description
df

The frame, with subject_id normalized to string.

subject_column

The resolved subject id column, always renamed to subject_id.

time_column

The as-of timestamp column, or None.

feature_columns

Everything treated as a feature.

label_column

A detected label column, or None.

source

Where it came from.

Source code in src/ehrlint/io/features.py
class FeatureMatrix:
    """A training feature matrix, with its identifier columns located.

    Attributes:
        df: The frame, with ``subject_id`` normalized to string.
        subject_column: The resolved subject id column, always renamed to
            ``subject_id``.
        time_column: The as-of timestamp column, or None.
        feature_columns: Everything treated as a feature.
        label_column: A detected label column, or None.
        source: Where it came from.
    """

    def __init__(
        self,
        df: pl.DataFrame,
        *,
        subject_column: str,
        time_column: str | None,
        feature_columns: list[str],
        label_column: str | None = None,
        source: str | None = None,
    ) -> None:
        self.df = df
        self.subject_column = subject_column
        self.time_column = time_column
        self.feature_columns = feature_columns
        self.label_column = label_column
        self.source = source

    def __len__(self) -> int:
        return self.df.height

    @property
    def n_features(self) -> int:
        """How many columns are treated as features."""
        return len(self.feature_columns)

    def subjects(self) -> set[str]:
        """Distinct subject ids in the matrix."""
        return set(self.df["subject_id"].drop_nulls().unique().to_list())

    def numeric_features(self) -> list[str]:
        """Feature columns with a numeric dtype."""
        return [c for c in self.feature_columns if self.df.schema[c].is_numeric()]

    def describe(self) -> dict[str, object]:
        """Summary for the report header."""
        return {
            "source": self.source,
            "n_rows": self.df.height,
            "n_features": self.n_features,
            "subject_column": self.subject_column,
            "time_column": self.time_column,
            "label_column": self.label_column,
            "n_subjects": len(self.subjects()),
        }

    def warnings(self) -> list[str]:
        """Things that limit what can be checked on this matrix."""
        out: list[str] = []
        if self.time_column is None:
            out.append(
                "the feature matrix has no as-of timestamp column, so ehrlint cannot "
                "verify from the matrix alone that features predate the index date. "
                f"Add one of {list(TIME_CANDIDATES)} to enable the direct check"
            )
        if not self.feature_columns:
            out.append("no feature columns were identified in the matrix")
        duplicated = self.df.height - self.df["subject_id"].n_unique()
        if duplicated > 0 and self.time_column is None:
            out.append(
                f"{duplicated} row(s) repeat a subject_id with no timestamp to "
                "distinguish them, so per-subject checks treat them as one unit"
            )
        return out

n_features property

n_features: int

How many columns are treated as features.

subjects

subjects() -> set[str]

Distinct subject ids in the matrix.

Source code in src/ehrlint/io/features.py
def subjects(self) -> set[str]:
    """Distinct subject ids in the matrix."""
    return set(self.df["subject_id"].drop_nulls().unique().to_list())

numeric_features

numeric_features() -> list[str]

Feature columns with a numeric dtype.

Source code in src/ehrlint/io/features.py
def numeric_features(self) -> list[str]:
    """Feature columns with a numeric dtype."""
    return [c for c in self.feature_columns if self.df.schema[c].is_numeric()]

describe

describe() -> dict[str, object]

Summary for the report header.

Source code in src/ehrlint/io/features.py
def describe(self) -> dict[str, object]:
    """Summary for the report header."""
    return {
        "source": self.source,
        "n_rows": self.df.height,
        "n_features": self.n_features,
        "subject_column": self.subject_column,
        "time_column": self.time_column,
        "label_column": self.label_column,
        "n_subjects": len(self.subjects()),
    }

warnings

warnings() -> list[str]

Things that limit what can be checked on this matrix.

Source code in src/ehrlint/io/features.py
def warnings(self) -> list[str]:
    """Things that limit what can be checked on this matrix."""
    out: list[str] = []
    if self.time_column is None:
        out.append(
            "the feature matrix has no as-of timestamp column, so ehrlint cannot "
            "verify from the matrix alone that features predate the index date. "
            f"Add one of {list(TIME_CANDIDATES)} to enable the direct check"
        )
    if not self.feature_columns:
        out.append("no feature columns were identified in the matrix")
    duplicated = self.df.height - self.df["subject_id"].n_unique()
    if duplicated > 0 and self.time_column is None:
        out.append(
            f"{duplicated} row(s) repeat a subject_id with no timestamp to "
            "distinguish them, so per-subject checks treat them as one unit"
        )
    return out

read_feature_matrix

read_feature_matrix(
    path: str | Path,
    *,
    subject_column: str | None = None,
    time_column: str | None = None,
) -> FeatureMatrix

Read a feature matrix from parquet or CSV.

Parameters:

Name Type Description Default
path str | Path

The file.

required
subject_column str | None

Override the subject id column.

None
time_column str | None

Override the as-of timestamp column.

None

Returns:

Name Type Description
A FeatureMatrix

class:FeatureMatrix.

Raises:

Type Description
InputError

If the file is missing or unreadable.

SchemaError

If no subject id column can be found, listing the names it looked for — guessing one would risk auditing the wrong column.

Source code in src/ehrlint/io/features.py
def read_feature_matrix(
    path: str | Path,
    *,
    subject_column: str | None = None,
    time_column: str | None = None,
) -> FeatureMatrix:
    """Read a feature matrix from parquet or CSV.

    Args:
        path: The file.
        subject_column: Override the subject id column.
        time_column: Override the as-of timestamp column.

    Returns:
        A :class:`FeatureMatrix`.

    Raises:
        InputError: If the file is missing or unreadable.
        SchemaError: If no subject id column can be found, listing the names it
            looked for — guessing one would risk auditing the wrong column.
    """
    source = Path(path)
    if not source.exists():
        raise InputError("feature matrix not found", path=str(source))

    try:
        if source.suffix in (".parquet", ".pq"):
            df = pl.read_parquet(source)
        elif source.suffix in (".csv", ".tsv"):
            separator = "\t" if source.suffix == ".tsv" else ","
            df = pl.read_csv(
                source, separator=separator, infer_schema_length=10000, try_parse_dates=True
            )
        else:
            raise InputError(
                f"unsupported feature matrix format {source.suffix!r}; use .parquet or .csv",
                path=str(source),
            )
    except InputError:
        raise
    except Exception as exc:
        raise InputError(f"could not read feature matrix: {exc}", path=str(source)) from exc

    return build_feature_matrix(
        df, subject_column=subject_column, time_column=time_column, source=str(source)
    )

build_feature_matrix

build_feature_matrix(
    df: DataFrame,
    *,
    subject_column: str | None = None,
    time_column: str | None = None,
    source: str | None = None,
) -> FeatureMatrix

Locate the identifier columns in a frame and wrap it.

Source code in src/ehrlint/io/features.py
def build_feature_matrix(
    df: pl.DataFrame,
    *,
    subject_column: str | None = None,
    time_column: str | None = None,
    source: str | None = None,
) -> FeatureMatrix:
    """Locate the identifier columns in a frame and wrap it."""
    lower = {c.lower(): c for c in df.columns}

    resolved_subject = subject_column
    if resolved_subject is None:
        resolved_subject = next((lower[c] for c in SUBJECT_CANDIDATES if c in lower), None)
    if resolved_subject is None:
        raise SchemaError(
            f"could not find a subject id column in the feature matrix. Looked for "
            f"{list(SUBJECT_CANDIDATES)}; found {df.columns}. Pass --feature-subject-column "
            "to name it explicitly",
            path=source,
            table="features",
        )
    if resolved_subject not in df.columns:
        raise SchemaError(
            f"subject column {resolved_subject!r} is not in the feature matrix; found {df.columns}",
            path=source,
            table="features",
            column=resolved_subject,
        )

    resolved_time = time_column
    if resolved_time is None:
        resolved_time = next((lower[c] for c in TIME_CANDIDATES if c in lower), None)
    if resolved_time is not None and resolved_time not in df.columns:
        raise SchemaError(
            f"time column {resolved_time!r} is not in the feature matrix; found {df.columns}",
            path=source,
            table="features",
            column=resolved_time,
        )

    label = next(
        (lower[c] for c in ("label", "y", "outcome", "target", "boolean_value") if c in lower),
        None,
    )

    casts = [pl.col(resolved_subject).cast(pl.String, strict=False).alias("subject_id")]
    if resolved_time is not None:
        casts.append(
            pl.col(resolved_time).cast(pl.Datetime("us"), strict=False).alias(resolved_time)
        )
    out = df.with_columns(casts)

    non_features = {c.lower() for c in NON_FEATURE_CANDIDATES}
    non_features.add("subject_id")
    if resolved_time:
        non_features.add(resolved_time.lower())
    features = [c for c in out.columns if c.lower() not in non_features]

    return FeatureMatrix(
        df=out,
        subject_column=resolved_subject,
        time_column=resolved_time,
        feature_columns=features,
        label_column=label,
        source=source,
    )

read_labels

read_labels(path: str | Path) -> pl.DataFrame

Read a labels table, MEDS-shaped or ehrlint-shaped.

MEDS LabelSchema is subject_id, prediction_time, boolean_value, integer_value, float_value, categorical_value — verified against meds 0.4.1. ehrlint normalizes whichever typed value column is populated into a single label column, and takes prediction_time as the index date when the task spec does not define one from an event code.

Returns:

Type Description
DataFrame

A frame with subject_id, index_date, and label.

Source code in src/ehrlint/io/features.py
def read_labels(path: str | Path) -> pl.DataFrame:
    """Read a labels table, MEDS-shaped or ehrlint-shaped.

    MEDS `LabelSchema` is ``subject_id, prediction_time, boolean_value,
    integer_value, float_value, categorical_value`` — verified against `meds`
    0.4.1. ehrlint normalizes whichever typed value column is populated into a
    single ``label`` column, and takes ``prediction_time`` as the index date
    when the task spec does not define one from an event code.

    Returns:
        A frame with ``subject_id``, ``index_date``, and ``label``.
    """
    source = Path(path)
    if not source.exists():
        raise InputError("labels file not found", path=str(source))

    try:
        if source.suffix in (".parquet", ".pq"):
            df = pl.read_parquet(source)
        else:
            df = pl.read_csv(source, infer_schema_length=10000, try_parse_dates=True)
    except Exception as exc:
        raise InputError(f"could not read labels: {exc}", path=str(source)) from exc

    lower = {c.lower(): c for c in df.columns}
    subject = next((lower[c] for c in SUBJECT_CANDIDATES if c in lower), None)
    if subject is None:
        raise SchemaError(
            f"labels table has no subject id column; looked for {list(SUBJECT_CANDIDATES)}, "
            f"found {df.columns}",
            path=str(source),
            table="labels",
        )

    time_col = next(
        (lower[c] for c in ("prediction_time", "index_date", "index_time", "time") if c in lower),
        None,
    )
    if time_col is None:
        raise SchemaError(
            "labels table has no prediction_time or index_date column, so index dates "
            f"cannot be read from it; found {df.columns}",
            path=str(source),
            table="labels",
        )

    label_col = next(
        (
            lower[c]
            for c in (
                "boolean_value",
                "label",
                "y",
                "outcome",
                "target",
                "integer_value",
                "float_value",
            )
            if c in lower
        ),
        None,
    )

    exprs = [
        pl.col(subject).cast(pl.String, strict=False).alias("subject_id"),
        pl.col(time_col).cast(pl.Datetime("us"), strict=False).alias("index_date"),
    ]
    if label_col is not None:
        exprs.append(pl.col(label_col).cast(pl.Boolean, strict=False).alias("label"))
    else:
        exprs.append(pl.lit(None, dtype=pl.Boolean).alias("label"))

    return df.select(exprs)

Reports

ehrlint.report.builder

Report generation: a single offline HTML file, Markdown, and JSON.

The HTML is one self-contained file: figures are inlined as base64 data URIs and there is no JavaScript. An audit report gets attached to a review, a ticket, or a submission, and a report that breaks when its figures/ directory is lost is a report that will be seen broken.

The ordering is deliberate and is the opposite of a dashboard's. Warnings and skipped checks come before the findings, because "six of ten checks did not run" changes how every result below should be read, and a reader who sees a green summary first will stop there.

plot_severity_summary

plot_severity_summary(report: AuditReport) -> str | None

Horizontal bars of check outcome by severity, including the zeros.

Source code in src/ehrlint/report/builder.py
def plot_severity_summary(report: AuditReport) -> str | None:
    """Horizontal bars of check outcome by severity, including the zeros."""
    counts = {
        "error": report.summary.n_errors,
        "warning": report.summary.n_warnings,
        "passed": len(report.passed),
        "skipped": report.summary.n_checks_skipped,
    }
    if not any(counts.values()):
        return None

    labels = list(counts)
    values = [counts[k] for k in labels]
    colours = [
        SEVERITY_COLOURS["error"],
        SEVERITY_COLOURS["warning"],
        "#2E7D32",
        "#7F8C8D",
    ]

    fig, ax = plt.subplots(figsize=(6.4, 2.6))
    bars = ax.barh(labels, values, color=colours, edgecolor="white", height=0.62)
    ax.invert_yaxis()
    ax.set_xlabel("checks")
    ax.set_title("Audit outcome")
    ax.spines[["top", "right"]].set_visible(False)
    ax.grid(axis="x", alpha=0.25, linewidth=0.6)
    for bar, value in zip(bars, values, strict=True):
        if value == 0:
            ax.text(
                0.06,
                bar.get_y() + bar.get_height() / 2,
                "none",
                va="center",
                fontsize=8,
                color="#777777",
            )
    ax.set_xlim(0, max(max(values), 1) * 1.15)
    fig.tight_layout()
    return _as_data_uri(fig)

plot_subject_rates

plot_subject_rates(report: AuditReport) -> str | None

Affected subject rate per fired check.

A rate, not a count: "42 subjects" means something different in a cohort of 100 than in one of 100,000, and the denominator is what a reviewer needs.

Source code in src/ehrlint/report/builder.py
def plot_subject_rates(report: AuditReport) -> str | None:
    """Affected subject rate per fired check.

    A rate, not a count: "42 subjects" means something different in a cohort
    of 100 than in one of 100,000, and the denominator is what a reviewer
    needs.
    """
    fired = [f for f in report.fired if f.subject_rate is not None]
    if not fired:
        return None

    labels = [f"{f.check_id} {f.name}" for f in fired]
    rates = [(f.subject_rate or 0.0) * 100 for f in fired]
    colours = [SEVERITY_COLOURS.get(f.severity.value, NEUTRAL) for f in fired]

    fig, ax = plt.subplots(figsize=(7.2, max(2.2, 0.46 * len(fired) + 1.1)))
    ax.barh(labels, rates, color=colours, edgecolor="white", height=0.62)
    ax.invert_yaxis()
    ax.set_xlabel("affected subjects (%)")
    ax.set_title("Affected subject rate by check")
    ax.spines[["top", "right"]].set_visible(False)
    ax.grid(axis="x", alpha=0.25, linewidth=0.6)
    for i, rate in enumerate(rates):
        ax.text(rate + max(rates) * 0.015, i, f"{rate:.1f}%", va="center", fontsize=8)
    ax.set_xlim(0, max(max(rates), 1.0) * 1.2)
    fig.tight_layout()
    return _as_data_uri(fig)

render_markdown

render_markdown(
    report: AuditReport,
    *,
    figures: dict[str, str] | None = None,
) -> str

Render the Markdown report.

Source code in src/ehrlint/report/builder.py
def render_markdown(report: AuditReport, *, figures: dict[str, str] | None = None) -> str:
    """Render the Markdown report."""
    try:
        template = _env().get_template("report.md.j2")
    except Exception as exc:  # pragma: no cover
        raise ReportError(f"could not load the Markdown template: {exc}") from exc
    return template.render(**_context(report, figures=figures or {}))

render_html

render_html(
    report: AuditReport, *, embed_figures: bool = True
) -> str

Render the HTML report as a single self-contained string.

Source code in src/ehrlint/report/builder.py
def render_html(report: AuditReport, *, embed_figures: bool = True) -> str:
    """Render the HTML report as a single self-contained string."""
    figures: dict[str, str] = {}
    if embed_figures:
        severity = plot_severity_summary(report)
        rates = plot_subject_rates(report)
        if severity:
            figures["severity"] = severity
        if rates:
            figures["rates"] = rates
    try:
        template = _env().get_template("report.html.j2")
    except Exception as exc:  # pragma: no cover
        raise ReportError(f"could not load the HTML template: {exc}") from exc
    return template.render(**_context(report, figures=figures))

write_report

write_report(
    report: AuditReport,
    outdir: str | Path,
    *,
    embed_figures: bool = True,
) -> dict[str, Path]

Write every report artifact into outdir.

Produces report.html (one self-contained file), report.md, report.json, and findings.jsonl.

Returns:

Type Description
dict[str, Path]

A mapping of artifact name to path.

Source code in src/ehrlint/report/builder.py
def write_report(
    report: AuditReport, outdir: str | Path, *, embed_figures: bool = True
) -> dict[str, Path]:
    """Write every report artifact into ``outdir``.

    Produces ``report.html`` (one self-contained file), ``report.md``,
    ``report.json``, and ``findings.jsonl``.

    Returns:
        A mapping of artifact name to path.
    """
    target = Path(outdir)
    target.mkdir(parents=True, exist_ok=True)
    written: dict[str, Path] = {}

    html_path = target / "report.html"
    html_path.write_text(render_html(report, embed_figures=embed_figures), encoding="utf-8")
    written["html"] = html_path

    md_path = target / "report.md"
    md_path.write_text(render_markdown(report), encoding="utf-8")
    written["markdown"] = md_path

    written["json"] = report.write_json(target / "report.json")
    written["findings"] = report.write_findings_jsonl(target / "findings.jsonl")
    return written

Synthetic data and injectors

ehrlint.synth.generator

Clean synthetic EHR data, deterministic given a seed.

This is the only data ehrlint ships or tests against. Nothing here derives from a real record: subjects are sequential, codes come from a fixed vocabulary, and every timestamp is computed from a constant epoch.

The baseline is clean by construction — no post-index events used as features, full follow-up for negatives, disjoint splits, outcomes inside the horizon. That matters because the test strategy is differential: generate clean data, assert no check fires, inject one specific leak, assert exactly that check fires. A baseline that already leaked would make every injector test meaningless.

SyntheticDataset dataclass

Generated events, labels, splits, and the task they describe.

Attributes:

Name Type Description
events DataFrame

The canonical event table.

labels DataFrame

subject_id, index_date, label.

splits DataFrame

subject_id, split.

task TaskSpec

The task spec these data satisfy.

features DataFrame | None

An optional feature matrix. The clean generator produces none; inject.inject_lk001 attaches one, because a leak in the matrix is the unambiguous LK001 case.

seed int

The seed used.

injected list[str]

Check ids whose leak has been planted, in injection order.

Source code in src/ehrlint/synth/generator.py
@dataclass
class SyntheticDataset:
    """Generated events, labels, splits, and the task they describe.

    Attributes:
        events: The canonical event table.
        labels: ``subject_id``, ``index_date``, ``label``.
        splits: ``subject_id``, ``split``.
        task: The task spec these data satisfy.
        features: An optional feature matrix. The clean generator produces
            none; `inject.inject_lk001` attaches one, because a leak in the
            matrix is the unambiguous LK001 case.
        seed: The seed used.
        injected: Check ids whose leak has been planted, in injection order.
    """

    events: pl.DataFrame
    labels: pl.DataFrame
    splits: pl.DataFrame
    task: TaskSpec
    features: pl.DataFrame | None = None
    seed: int = 0
    injected: list[str] = field(default_factory=list)

    @property
    def n_subjects(self) -> int:
        """Distinct subjects."""
        return self.events["subject_id"].n_unique()

    def splits_mapping(self) -> dict[str, list[str]]:
        """Splits as the ``{name: [subject_id]}`` mapping ehrlint's JSON uses."""
        out: dict[str, list[str]] = {}
        for row in self.splits.iter_rows(named=True):
            out.setdefault(str(row["split"]), []).append(str(row["subject_id"]))
        return {k: sorted(v) for k, v in out.items()}

    def copy(self) -> SyntheticDataset:
        """A deep-enough copy for an injector to mutate."""
        return SyntheticDataset(
            events=self.events.clone(),
            labels=self.labels.clone(),
            splits=self.splits.clone(),
            task=self.task.model_copy(deep=True),
            features=None if self.features is None else self.features.clone(),
            seed=self.seed,
            injected=list(self.injected),
        )

    def describe(self) -> dict[str, Any]:
        """Summary for the manifest."""
        return {
            "n_subjects": self.n_subjects,
            "n_events": self.events.height,
            "n_labels": self.labels.height,
            "n_positive": int(self.labels["label"].sum() or 0),
            "splits": {k: len(v) for k, v in self.splits_mapping().items()},
            "n_feature_rows": 0 if self.features is None else self.features.height,
            "seed": self.seed,
            "injected": self.injected,
            "task": self.task.task,
        }

    def write(self, outdir: str | Path) -> dict[str, Path]:
        """Write the dataset in MEDS layout plus ehrlint's own side files."""
        import json

        from ehrlint.io.meds import write_meds_dataset

        root = Path(outdir)
        root.mkdir(parents=True, exist_ok=True)
        written = dict(
            write_meds_dataset(
                self.events,
                root,
                dataset_name="ehrlint-synthetic",
                splits=self.splits,
            )
        )

        labels_path = root / "labels.parquet"
        self.labels.write_parquet(labels_path)
        written["labels"] = labels_path

        splits_path = root / "splits.json"
        splits_path.write_text(json.dumps(self.splits_mapping(), indent=2))
        written["splits_json"] = splits_path

        task_path = root / "task.yaml"
        self.task.to_yaml(task_path)
        written["task"] = task_path

        if self.features is not None:
            features_path = root / "features.parquet"
            self.features.write_parquet(features_path)
            written["features"] = features_path

        manifest = {
            "generator": "ehrlint.synth",
            **self.describe(),
            "note": (
                "Every record here is synthetic. Subjects are sequential, codes come "
                "from a fixed vocabulary, and timestamps derive from a constant epoch. "
                "No real patient record was involved."
            ),
        }
        manifest_path = root / "manifest.json"
        manifest_path.write_text(json.dumps(manifest, indent=2))
        written["manifest"] = manifest_path
        return written

n_subjects property

n_subjects: int

Distinct subjects.

splits_mapping

splits_mapping() -> dict[str, list[str]]

Splits as the {name: [subject_id]} mapping ehrlint's JSON uses.

Source code in src/ehrlint/synth/generator.py
def splits_mapping(self) -> dict[str, list[str]]:
    """Splits as the ``{name: [subject_id]}`` mapping ehrlint's JSON uses."""
    out: dict[str, list[str]] = {}
    for row in self.splits.iter_rows(named=True):
        out.setdefault(str(row["split"]), []).append(str(row["subject_id"]))
    return {k: sorted(v) for k, v in out.items()}

copy

copy() -> SyntheticDataset

A deep-enough copy for an injector to mutate.

Source code in src/ehrlint/synth/generator.py
def copy(self) -> SyntheticDataset:
    """A deep-enough copy for an injector to mutate."""
    return SyntheticDataset(
        events=self.events.clone(),
        labels=self.labels.clone(),
        splits=self.splits.clone(),
        task=self.task.model_copy(deep=True),
        features=None if self.features is None else self.features.clone(),
        seed=self.seed,
        injected=list(self.injected),
    )

describe

describe() -> dict[str, Any]

Summary for the manifest.

Source code in src/ehrlint/synth/generator.py
def describe(self) -> dict[str, Any]:
    """Summary for the manifest."""
    return {
        "n_subjects": self.n_subjects,
        "n_events": self.events.height,
        "n_labels": self.labels.height,
        "n_positive": int(self.labels["label"].sum() or 0),
        "splits": {k: len(v) for k, v in self.splits_mapping().items()},
        "n_feature_rows": 0 if self.features is None else self.features.height,
        "seed": self.seed,
        "injected": self.injected,
        "task": self.task.task,
    }

write

write(outdir: str | Path) -> dict[str, Path]

Write the dataset in MEDS layout plus ehrlint's own side files.

Source code in src/ehrlint/synth/generator.py
def write(self, outdir: str | Path) -> dict[str, Path]:
    """Write the dataset in MEDS layout plus ehrlint's own side files."""
    import json

    from ehrlint.io.meds import write_meds_dataset

    root = Path(outdir)
    root.mkdir(parents=True, exist_ok=True)
    written = dict(
        write_meds_dataset(
            self.events,
            root,
            dataset_name="ehrlint-synthetic",
            splits=self.splits,
        )
    )

    labels_path = root / "labels.parquet"
    self.labels.write_parquet(labels_path)
    written["labels"] = labels_path

    splits_path = root / "splits.json"
    splits_path.write_text(json.dumps(self.splits_mapping(), indent=2))
    written["splits_json"] = splits_path

    task_path = root / "task.yaml"
    self.task.to_yaml(task_path)
    written["task"] = task_path

    if self.features is not None:
        features_path = root / "features.parquet"
        self.features.write_parquet(features_path)
        written["features"] = features_path

    manifest = {
        "generator": "ehrlint.synth",
        **self.describe(),
        "note": (
            "Every record here is synthetic. Subjects are sequential, codes come "
            "from a fixed vocabulary, and timestamps derive from a constant epoch. "
            "No real patient record was involved."
        ),
    }
    manifest_path = root / "manifest.json"
    manifest_path.write_text(json.dumps(manifest, indent=2))
    written["manifest"] = manifest_path
    return written

default_task

default_task() -> TaskSpec

The task spec the generated data satisfies.

A two-year DKA-style task: index on an ED visit, outcome from two ICD-10 codes, full follow-up required for negatives, temporal subject split.

Source code in src/ehrlint/synth/generator.py
def default_task() -> TaskSpec:
    """The task spec the generated data satisfies.

    A two-year DKA-style task: index on an ED visit, outcome from two ICD-10
    codes, full follow-up required for negatives, temporal subject split.
    """
    return TaskSpec.from_dict(
        {
            "task": "dka_2y",
            "description": "Synthetic two-year outcome task, for exercising ehrlint.",
            "index": {"event": INDEX_CODE, "code_system": INDEX_SYSTEM},
            "outcome": {
                "codes": [{"system": OUTCOME_SYSTEM, "values": list(OUTCOME_CODES)}],
                "window": ["index_date", "index_date + 2y"],
                "proxy_codes": [{"system": PROXY_SYSTEM, "values": list(PROXY_CODES)}],
                "competing_codes": [{"system": None, "values": ["MEDS_DEATH"]}],
            },
            "horizon": "2y",
            "followup": {
                "require_full_horizon_for_negatives": True,
                "allow_death_as_censoring": True,
            },
            "splits": {
                "strategy": "subject",
                "temporal": True,
                "group_column": "encounter_id",
            },
        }
    )

generate

generate(
    n_subjects: int = 500,
    *,
    seed: int = 0,
    positive_rate: float = 0.2,
    horizon_days: float = 730.5,
    history_years: float = 2.0,
) -> SyntheticDataset

Generate a clean synthetic dataset.

Clean means: every predictor event predates the index date, every negative is observed for the full horizon, splits are disjoint and time-ordered, and every positive's outcome falls inside the horizon.

Parameters:

Name Type Description Default
n_subjects int

How many subjects.

500
seed int

Seed for all randomness; identical arguments give identical output.

0
positive_rate float

Share of subjects with the outcome.

0.2
horizon_days float

The task horizon, in days.

730.5
history_years float

How much pre-index history to generate.

2.0

Returns:

Name Type Description
A SyntheticDataset

class:SyntheticDataset.

Raises:

Type Description
ValueError

On arguments that cannot produce a usable dataset.

Source code in src/ehrlint/synth/generator.py
def generate(
    n_subjects: int = 500,
    *,
    seed: int = 0,
    positive_rate: float = 0.2,
    horizon_days: float = 730.5,
    history_years: float = 2.0,
) -> SyntheticDataset:
    """Generate a clean synthetic dataset.

    Clean means: every predictor event predates the index date, every negative
    is observed for the full horizon, splits are disjoint and time-ordered, and
    every positive's outcome falls inside the horizon.

    Args:
        n_subjects: How many subjects.
        seed: Seed for all randomness; identical arguments give identical output.
        positive_rate: Share of subjects with the outcome.
        horizon_days: The task horizon, in days.
        history_years: How much pre-index history to generate.

    Returns:
        A :class:`SyntheticDataset`.

    Raises:
        ValueError: On arguments that cannot produce a usable dataset.
    """
    if n_subjects < 1:
        raise ValueError(f"n_subjects must be at least 1, got {n_subjects}")
    if not 0.0 <= positive_rate <= 1.0:
        raise ValueError(f"positive_rate must be in [0, 1], got {positive_rate}")
    if horizon_days <= 0:
        raise ValueError(f"horizon_days must be positive, got {horizon_days}")

    rng = random.Random(seed)
    events: list[dict[str, Any]] = []
    labels: list[dict[str, Any]] = []
    split_rows: list[dict[str, Any]] = []

    # Index dates spread over three years so a temporal split is meaningful.
    index_span_days = 365 * 3

    for i in range(n_subjects):
        subject = f"S{i + 1:06d}"
        index_offset = rng.uniform(0, index_span_days)
        index_date = EPOCH + timedelta(days=index_offset)
        is_positive = rng.random() < positive_rate

        # --- static demographics (null time), the LK009 signature ------
        for code in (
            rng.choice(GENDER_CODES),
            rng.choice(RACE_CODES),
            rng.choice(BIRTH_DECADE_CODES),
            f"POSTAL_{rng.randrange(N_POSTAL_CODES):05d}",
            f"{BIRTHDATE_CODE_PREFIX}{i + 1:08d}",
        ):
            events.append(
                {
                    "subject_id": subject,
                    "time": None,
                    "code": code,
                    "code_system": STATIC_SYSTEM,
                    "numeric_value": None,
                    "text_value": None,
                    "encounter_id": None,
                }
            )

        # --- pre-index history, in its own encounters ------------------
        n_history_encounters = rng.randint(1, 4)
        for e in range(n_history_encounters):
            encounter = f"{subject}-E{e}"
            offset = rng.uniform(1.0, history_years * 365.0)
            when = index_date - timedelta(days=offset)
            for code in rng.sample(HISTORY_CODES, k=rng.randint(1, 3)):
                events.append(
                    {
                        "subject_id": subject,
                        "time": when,
                        "code": code,
                        "code_system": HISTORY_SYSTEM,
                        "numeric_value": None,
                        "text_value": None,
                        "encounter_id": encounter,
                    }
                )
            lab, low, high = rng.choice(LAB_CODES)
            events.append(
                {
                    "subject_id": subject,
                    "time": when + timedelta(hours=1),
                    "code": lab,
                    "code_system": LAB_SYSTEM,
                    "numeric_value": round(rng.uniform(low, high), 2),
                    "text_value": None,
                    "encounter_id": encounter,
                }
            )

        # --- the index event, in its own encounter ---------------------
        index_encounter = f"{subject}-IDX"
        events.append(
            {
                "subject_id": subject,
                "time": index_date,
                "code": INDEX_CODE,
                "code_system": INDEX_SYSTEM,
                "numeric_value": None,
                "text_value": None,
                "encounter_id": index_encounter,
            }
        )

        # --- follow-up -------------------------------------------------
        if is_positive:
            # The outcome lands strictly inside the horizon.
            outcome_offset = rng.uniform(1.0, horizon_days - 1.0)
            outcome_time = index_date + timedelta(days=outcome_offset)
            events.append(
                {
                    "subject_id": subject,
                    "time": outcome_time,
                    "code": rng.choice(OUTCOME_CODES),
                    "code_system": OUTCOME_SYSTEM,
                    "numeric_value": None,
                    "text_value": None,
                    "encounter_id": f"{subject}-OUT",
                }
            )
            last_time = outcome_time
        else:
            # A negative is observed for the whole horizon, so LK004 is clean.
            last_time = index_date + timedelta(days=horizon_days + rng.uniform(1.0, 60.0))
            n_followup = rng.randint(1, 3)
            for f in range(n_followup):
                when = index_date + timedelta(days=rng.uniform(1.0, horizon_days))
                events.append(
                    {
                        "subject_id": subject,
                        "time": when,
                        "code": rng.choice(HISTORY_CODES),
                        "code_system": HISTORY_SYSTEM,
                        "numeric_value": None,
                        "text_value": None,
                        "encounter_id": f"{subject}-F{f}",
                    }
                )
            # A final visit at the end of follow-up, so last_event_time clears
            # the horizon and the negative is a genuine negative.
            events.append(
                {
                    "subject_id": subject,
                    "time": last_time,
                    "code": INDEX_CODE,
                    "code_system": INDEX_SYSTEM,
                    "numeric_value": None,
                    "text_value": None,
                    "encounter_id": f"{subject}-END",
                }
            )

        labels.append({"subject_id": subject, "index_date": index_date, "label": is_positive})
        split_rows.append({"subject_id": subject, "index_offset": index_offset})

    # --- temporal, disjoint splits by subject --------------------------
    split_rows.sort(key=lambda r: r["index_offset"])
    n = len(split_rows)
    n_train, n_valid = int(n * 0.6), int(n * 0.2)
    assignments: list[dict[str, Any]] = []
    for i, row in enumerate(split_rows):
        if i < n_train:
            name = TRAIN
        elif i < n_train + n_valid:
            name = VALID
        else:
            name = TEST
        assignments.append({"subject_id": row["subject_id"], "split": name})

    events_df = coerce_events(pl.DataFrame(events), source="synth")
    labels_df = pl.DataFrame(labels).with_columns(
        pl.col("subject_id").cast(pl.String),
        pl.col("index_date").cast(pl.Datetime("us")),
        pl.col("label").cast(pl.Boolean),
    )
    splits_df = pl.DataFrame(assignments).with_columns(
        pl.col("subject_id").cast(pl.String), pl.col("split").cast(pl.String)
    )

    return SyntheticDataset(
        events=events_df,
        labels=labels_df,
        splits=splits_df,
        task=default_task(),
        seed=seed,
    )

ehrlint.inject

Leak injectors: one per check.

The testing strategy this module exists for. Generate clean data, assert no check fires. Inject one specific leak, assert that check fires and names the subjects it was planted into. That is ground truth no amount of staring at a real dataset can give you.

Each injector returns the mutated dataset and the subject ids it touched, so a test can assert the check found the right people rather than merely finding someone. A check that fires on the wrong subjects is as broken as one that does not fire.

SPEC §11 requires injector/check duality: every check has an injector, and an injected leak is always caught. A property test asserts it over seeds and subject counts.

Injection dataclass

The result of planting a leak.

Attributes:

Name Type Description
dataset SyntheticDataset

The mutated dataset.

check_id str

The check this leak should trigger.

subjects list[str]

Subject ids the leak was planted into. The ground truth a test compares the finding against.

description str

What was done, for the test's failure message.

Source code in src/ehrlint/inject.py
@dataclass
class Injection:
    """The result of planting a leak.

    Attributes:
        dataset: The mutated dataset.
        check_id: The check this leak should trigger.
        subjects: Subject ids the leak was planted into. The ground truth a
            test compares the finding against.
        description: What was done, for the test's failure message.
    """

    dataset: SyntheticDataset
    check_id: str
    subjects: list[str]
    description: str

inject_lk001

inject_lk001(
    dataset: SyntheticDataset,
    *,
    n: int = 5,
    seed: int = 0,
    exclude: set[str] | None = None,
) -> Injection

LK001 — add a feature matrix whose rows postdate the index date.

The clean baseline already contains post-index events (outcomes live there), so planting more would not distinguish a leak from normal data. The unambiguous leak is a feature matrix stamped after the index date, which is what LK001's matrix branch checks.

Source code in src/ehrlint/inject.py
def inject_lk001(
    dataset: SyntheticDataset,
    *,
    n: int = 5,
    seed: int = 0,
    exclude: set[str] | None = None,
) -> Injection:
    """LK001 — add a feature matrix whose rows postdate the index date.

    The clean baseline already contains post-index *events* (outcomes live
    there), so planting more would not distinguish a leak from normal data.
    The unambiguous leak is a **feature matrix** stamped after the index date,
    which is what LK001's matrix branch checks.
    """
    rng = random.Random(seed)
    out = dataset.copy()
    chosen = _pick(out, rng, n, exclude)
    index = _index_dates(out)

    rows = []
    for subject, when in index.items():
        leaked = subject in chosen
        as_of = when + timedelta(days=90) if leaked else when
        rows.append(
            {
                "subject_id": subject,
                "prediction_time": as_of,
                "n_prior_visits": rng.randint(0, 9),
                "last_a1c": round(rng.uniform(5.0, 12.0), 2),
            }
        )

    out.features = pl.DataFrame(rows)
    out.injected.append("LK001")
    return Injection(
        dataset=out,
        check_id="LK001",
        subjects=chosen,
        description=(
            f"attached a feature matrix whose rows for {len(chosen)} subject(s) are "
            "stamped 90 days after their index date"
        ),
    )

inject_lk002

inject_lk002(
    dataset: SyntheticDataset,
    *,
    n: int = 5,
    seed: int = 0,
    exclude: set[str] | None = None,
) -> Injection

LK002 — put an outcome code inside the index encounter.

Source code in src/ehrlint/inject.py
def inject_lk002(
    dataset: SyntheticDataset,
    *,
    n: int = 5,
    seed: int = 0,
    exclude: set[str] | None = None,
) -> Injection:
    """LK002 — put an outcome code inside the index encounter."""
    rng = random.Random(seed)
    out = dataset.copy()
    chosen = _pick(out, rng, n, exclude)
    index = _index_dates(out)

    rows = []
    for subject in chosen:
        when = index.get(subject)
        if when is None:
            continue
        rows.append(
            {
                "subject_id": subject,
                "time": when,
                "code": rng.choice(OUTCOME_CODES),
                "code_system": OUTCOME_SYSTEM,
                "numeric_value": None,
                "text_value": None,
                # The index encounter, which is what makes this the leak.
                "encounter_id": f"{subject}-IDX",
            }
        )
    _append_events(out, rows)
    out.injected.append("LK002")
    return Injection(
        dataset=out,
        check_id="LK002",
        subjects=sorted({r["subject_id"] for r in rows}),
        description=f"added an outcome code to the index encounter of {len(rows)} subject(s)",
    )

inject_lk003

inject_lk003(
    dataset: SyntheticDataset,
    *,
    n: int = 5,
    seed: int = 0,
    exclude: set[str] | None = None,
) -> Injection

LK003 — put the outcome proxy before the index date.

Source code in src/ehrlint/inject.py
def inject_lk003(
    dataset: SyntheticDataset,
    *,
    n: int = 5,
    seed: int = 0,
    exclude: set[str] | None = None,
) -> Injection:
    """LK003 — put the outcome proxy before the index date."""
    rng = random.Random(seed)
    out = dataset.copy()
    chosen = _pick(out, rng, n, exclude)
    index = _index_dates(out)

    rows = []
    for subject in chosen:
        when = index.get(subject)
        if when is None:
            continue
        rows.append(
            {
                "subject_id": subject,
                "time": when - timedelta(days=rng.uniform(1.0, 30.0)),
                "code": rng.choice(PROXY_CODES),
                "code_system": PROXY_SYSTEM,
                "numeric_value": None,
                "text_value": None,
                "encounter_id": f"{subject}-PROXY",
            }
        )
    _append_events(out, rows)
    out.injected.append("LK003")
    return Injection(
        dataset=out,
        check_id="LK003",
        subjects=sorted({r["subject_id"] for r in rows}),
        description=f"added a pre-index outcome proxy for {len(rows)} subject(s)",
    )

inject_lk004

inject_lk004(
    dataset: SyntheticDataset,
    *,
    n: int = 5,
    seed: int = 0,
    exclude: set[str] | None = None,
) -> Injection

LK004 — truncate a negative's follow-up well inside the horizon.

Every event after index + 30 days is removed for the chosen subjects, and they keep their negative label. They are now censored patients counted as two-year negatives, which is the immortal-time error exactly.

Source code in src/ehrlint/inject.py
def inject_lk004(
    dataset: SyntheticDataset,
    *,
    n: int = 5,
    seed: int = 0,
    exclude: set[str] | None = None,
) -> Injection:
    """LK004 — truncate a negative's follow-up well inside the horizon.

    Every event after index + 30 days is removed for the chosen subjects, and
    they keep their negative label. They are now censored patients counted as
    two-year negatives, which is the immortal-time error exactly.
    """
    rng = random.Random(seed)
    out = dataset.copy()
    negatives = sorted(out.labels.filter(~pl.col("label"))["subject_id"].to_list())
    if not negatives:
        raise EhrlintError("no negative subjects available to truncate")
    chosen = _sample(negatives, rng, n, exclude)
    index = _index_dates(out)

    cutoffs = pl.DataFrame(
        [{"subject_id": s, "cutoff": index[s] + timedelta(days=30)} for s in chosen if s in index]
    )
    if cutoffs.height == 0:
        raise EhrlintError("no chosen negative subject has an index date")

    joined = out.events.join(cutoffs, on="subject_id", how="left")
    out.events = (
        joined.filter(
            pl.col("cutoff").is_null()
            | pl.col("time").is_null()
            | (pl.col("time") <= pl.col("cutoff"))
        )
        .drop("cutoff")
        .select(out.events.columns)
    )
    out.injected.append("LK004")
    return Injection(
        dataset=out,
        check_id="LK004",
        subjects=sorted(cutoffs["subject_id"].to_list()),
        description=(
            f"truncated follow-up to 30 days for {cutoffs.height} negative subject(s) "
            "while keeping their negative label"
        ),
    )

inject_lk005

inject_lk005(
    dataset: SyntheticDataset,
    *,
    n: int = 5,
    seed: int = 0,
    exclude: set[str] | None = None,
) -> Injection

LK005 — copy test subjects into the train split.

Source code in src/ehrlint/inject.py
def inject_lk005(
    dataset: SyntheticDataset,
    *,
    n: int = 5,
    seed: int = 0,
    exclude: set[str] | None = None,
) -> Injection:
    """LK005 — copy test subjects into the train split."""
    rng = random.Random(seed)
    out = dataset.copy()
    test_subjects = sorted(out.splits.filter(pl.col("split") == TEST)["subject_id"].to_list())
    if not test_subjects:
        raise EhrlintError("no test subjects available to duplicate")
    chosen = _sample(test_subjects, rng, n, exclude)

    extra = pl.DataFrame({"subject_id": chosen, "split": [TRAIN] * len(chosen)})
    out.splits = pl.concat([out.splits, extra], how="vertical")
    out.injected.append("LK005")
    return Injection(
        dataset=out,
        check_id="LK005",
        subjects=chosen,
        description=f"added {len(chosen)} test subject(s) to the train split as well",
    )

inject_lk006

inject_lk006(
    dataset: SyntheticDataset,
    *,
    n: int = 5,
    seed: int = 0,
    exclude: set[str] | None = None,
) -> Injection

LK006 — move the earliest train subjects into the test split.

The split stays disjoint — this is not LK005 — but the test set now contains the oldest index dates, so a split declared temporal is not.

Source code in src/ehrlint/inject.py
def inject_lk006(
    dataset: SyntheticDataset,
    *,
    n: int = 5,
    seed: int = 0,
    exclude: set[str] | None = None,
) -> Injection:
    """LK006 — move the earliest train subjects into the test split.

    The split stays disjoint — this is not LK005 — but the test set now
    contains the oldest index dates, so a split declared temporal is not.
    """
    rng = random.Random(seed)
    _ = rng
    out = dataset.copy()
    index = out.labels.select(["subject_id", "index_date"])
    train_subjects = (
        out.splits.filter(pl.col("split") == TRAIN)
        .join(index, on="subject_id", how="inner")
        .sort("index_date")
    )
    if train_subjects.height == 0:
        raise EhrlintError("no train subjects available to move")
    # The earliest ones specifically -- not a sample -- because that is what
    # breaks a temporal split. `exclude` is honoured by skipping them in order
    # rather than by sampling, so the choice stays deterministic.
    eligible = [
        s for s in train_subjects["subject_id"].to_list() if not exclude or s not in exclude
    ]
    if not eligible:
        raise EhrlintError(
            "every train subject already carries a planted leak, so LK006 has none left to move"
        )
    chosen = sorted(eligible[:n])

    out.splits = out.splits.with_columns(
        pl.when(pl.col("subject_id").is_in(chosen))
        .then(pl.lit(TEST))
        .otherwise(pl.col("split"))
        .alias("split")
    )
    out.injected.append("LK006")
    return Injection(
        dataset=out,
        check_id="LK006",
        subjects=chosen,
        description=(
            f"moved the {len(chosen)} earliest train subject(s) into the test split, so "
            "test index dates now precede the training maximum"
        ),
    )

inject_lk007

inject_lk007(
    dataset: SyntheticDataset,
    *,
    n: int = 5,
    seed: int = 0,
    exclude: set[str] | None = None,
) -> Injection

LK007 — flip negatives to positive without any in-window outcome.

The label now asserts an outcome the event data does not support inside the declared window, which is what "ascertained with post-index information" looks like from the outside.

Source code in src/ehrlint/inject.py
def inject_lk007(
    dataset: SyntheticDataset,
    *,
    n: int = 5,
    seed: int = 0,
    exclude: set[str] | None = None,
) -> Injection:
    """LK007 — flip negatives to positive without any in-window outcome.

    The label now asserts an outcome the event data does not support inside
    the declared window, which is what "ascertained with post-index
    information" looks like from the outside.
    """
    rng = random.Random(seed)
    out = dataset.copy()
    negatives = sorted(out.labels.filter(~pl.col("label"))["subject_id"].to_list())
    if not negatives:
        raise EhrlintError("no negative subjects available to relabel")
    chosen = _sample(negatives, rng, n, exclude)

    out.labels = out.labels.with_columns(
        pl.when(pl.col("subject_id").is_in(chosen))
        .then(pl.lit(True))
        .otherwise(pl.col("label"))
        .alias("label")
    )
    out.injected.append("LK007")
    return Injection(
        dataset=out,
        check_id="LK007",
        subjects=chosen,
        description=(
            f"relabelled {len(chosen)} subject(s) positive with no outcome code inside "
            "the declared window"
        ),
    )

inject_lk008

inject_lk008(
    dataset: SyntheticDataset,
    *,
    n: int = 3,
    seed: int = 0,
    exclude: set[str] | None = None,
) -> Injection

LK008 — give a train and a test subject the same encounter id.

Subject-level splits stay disjoint, so LK005 is clean; the encounter is what straddles.

Source code in src/ehrlint/inject.py
def inject_lk008(
    dataset: SyntheticDataset,
    *,
    n: int = 3,
    seed: int = 0,
    exclude: set[str] | None = None,
) -> Injection:
    """LK008 — give a train and a test subject the same encounter id.

    Subject-level splits stay disjoint, so LK005 is clean; the encounter is
    what straddles.
    """
    rng = random.Random(seed)
    out = dataset.copy()
    train_subjects = sorted(out.splits.filter(pl.col("split") == TRAIN)["subject_id"].to_list())
    test_subjects = sorted(out.splits.filter(pl.col("split") == TEST)["subject_id"].to_list())
    if not train_subjects or not test_subjects:
        raise EhrlintError("both a train and a test split are needed")

    pairs = list(
        zip(
            _sample(train_subjects, rng, n, exclude),
            _sample(test_subjects, rng, n, exclude),
            strict=False,
        )
    )
    index = _index_dates(out)

    rows = []
    touched: list[str] = []
    for i, (train_subject, test_subject) in enumerate(pairs):
        shared = f"SHARED-ENC-{i}"
        for subject in (train_subject, test_subject):
            when = index.get(subject)
            if when is None:
                continue
            rows.append(
                {
                    "subject_id": subject,
                    "time": when - timedelta(days=5),
                    "code": "I10",
                    "code_system": HISTORY_SYSTEM,
                    "numeric_value": None,
                    "text_value": None,
                    "encounter_id": shared,
                }
            )
            touched.append(subject)
    _append_events(out, rows)
    out.injected.append("LK008")
    return Injection(
        dataset=out,
        check_id="LK008",
        subjects=sorted(set(touched)),
        description=(
            f"gave {len(pairs)} train/test subject pair(s) a shared encounter id while "
            "keeping the subject split disjoint"
        ),
    )

inject_lk009

inject_lk009(
    dataset: SyntheticDataset,
    *,
    n: int = 3,
    seed: int = 0,
    exclude: set[str] | None = None,
) -> Injection

LK009 — duplicate a subject under a second id with identical demographics.

Source code in src/ehrlint/inject.py
def inject_lk009(
    dataset: SyntheticDataset,
    *,
    n: int = 3,
    seed: int = 0,
    exclude: set[str] | None = None,
) -> Injection:
    """LK009 — duplicate a subject under a second id with identical demographics."""
    rng = random.Random(seed)
    out = dataset.copy()
    chosen = _pick(out, rng, n, exclude)

    rows: list[dict[str, Any]] = []
    touched: list[str] = []
    for subject in chosen:
        twin = f"{subject}-DUP"
        own = out.events.filter(pl.col("subject_id") == subject)
        for row in own.iter_rows(named=True):
            copy = dict(row)
            copy["subject_id"] = twin
            if copy.get("encounter_id"):
                copy["encounter_id"] = str(copy["encounter_id"]).replace(subject, twin)
            rows.append(copy)
        touched.extend([subject, twin])

    _append_events(out, rows)

    # The duplicate needs a label and a split, or the duplicate id would be
    # invisible to every other check and the dataset would be inconsistent.
    index = _index_dates(out)
    new_labels = [
        {
            "subject_id": f"{s}-DUP",
            "index_date": index.get(s),
            "label": bool(out.labels.filter(pl.col("subject_id") == s)["label"].first()),
        }
        for s in chosen
        if index.get(s) is not None
    ]
    if new_labels:
        out.labels = pl.concat(
            [out.labels, pl.DataFrame(new_labels).select(out.labels.columns)],
            how="vertical",
        )
    existing_split = {
        str(r["subject_id"]): str(r["split"]) for r in out.splits.iter_rows(named=True)
    }
    new_splits = [{"subject_id": f"{s}-DUP", "split": existing_split.get(s, TRAIN)} for s in chosen]
    out.splits = pl.concat([out.splits, pl.DataFrame(new_splits)], how="vertical")

    out.injected.append("LK009")
    return Injection(
        dataset=out,
        check_id="LK009",
        subjects=sorted(set(touched)),
        description=(
            f"duplicated {len(chosen)} subject(s) under a second id with identical "
            "static demographics"
        ),
    )

inject_lk010

inject_lk010(
    dataset: SyntheticDataset,
    *,
    n: int = 5,
    seed: int = 0,
    exclude: set[str] | None = None,
) -> Injection

LK010 — give negatives an outcome occurrence beyond the horizon.

They have no in-window occurrence, so if they are counted as positives the task's real horizon is longer than declared.

Source code in src/ehrlint/inject.py
def inject_lk010(
    dataset: SyntheticDataset,
    *,
    n: int = 5,
    seed: int = 0,
    exclude: set[str] | None = None,
) -> Injection:
    """LK010 — give negatives an outcome occurrence beyond the horizon.

    They have no in-window occurrence, so if they are counted as positives the
    task's real horizon is longer than declared.
    """
    rng = random.Random(seed)
    out = dataset.copy()
    negatives = sorted(out.labels.filter(~pl.col("label"))["subject_id"].to_list())
    if not negatives:
        raise EhrlintError("no negative subjects available")
    chosen = _sample(negatives, rng, n, exclude)
    index = _index_dates(out)
    horizon_days = out.task.horizon.days if out.task.horizon else 730.5

    rows = []
    for subject in chosen:
        when = index.get(subject)
        if when is None:
            continue
        rows.append(
            {
                "subject_id": subject,
                "time": when + timedelta(days=horizon_days + rng.uniform(30.0, 400.0)),
                "code": rng.choice(OUTCOME_CODES),
                "code_system": OUTCOME_SYSTEM,
                "numeric_value": None,
                "text_value": None,
                "encounter_id": f"{subject}-LATE",
            }
        )
    _append_events(out, rows)
    out.injected.append("LK010")
    return Injection(
        dataset=out,
        check_id="LK010",
        subjects=sorted({r["subject_id"] for r in rows}),
        description=(
            f"added an outcome occurrence beyond the horizon for {len(rows)} subject(s) "
            "with no in-window occurrence"
        ),
    )

inject

inject(
    dataset: SyntheticDataset,
    check_id: str,
    *,
    n: int = 5,
    seed: int = 0,
    exclude: set[str] | None = None,
) -> Injection

Plant the leak that should trigger check_id.

Parameters:

Name Type Description Default
dataset SyntheticDataset

The dataset to copy and mutate.

required
check_id str

Which leak to plant.

required
n int

How many subjects to affect.

5
seed int

Seed; the same arguments plant the same leak.

0
exclude set[str] | None

Subjects to leave alone, normally those already carrying a planted leak.

None

Raises:

Type Description
EhrlintError

If no injector exists for the check, listing those that do.

Source code in src/ehrlint/inject.py
def inject(
    dataset: SyntheticDataset,
    check_id: str,
    *,
    n: int = 5,
    seed: int = 0,
    exclude: set[str] | None = None,
) -> Injection:
    """Plant the leak that should trigger ``check_id``.

    Args:
        dataset: The dataset to copy and mutate.
        check_id: Which leak to plant.
        n: How many subjects to affect.
        seed: Seed; the same arguments plant the same leak.
        exclude: Subjects to leave alone, normally those already carrying a
            planted leak.

    Raises:
        EhrlintError: If no injector exists for the check, listing those that
            do.
    """
    key = check_id.strip().upper()
    if key not in INJECTORS:
        raise EhrlintError(
            f"no injector for {check_id!r}; available: {', '.join(sorted(INJECTORS))}"
        )
    return INJECTORS[key](dataset, n=n, seed=seed, exclude=exclude)

inject_many

inject_many(
    dataset: SyntheticDataset,
    check_ids: list[str],
    *,
    n: int = 5,
    seed: int = 0,
) -> tuple[SyntheticDataset, dict[str, list[str]]]

Plant several leaks in sequence, on disjoint subjects.

Disjoint because every injector is seeded identically and would otherwise choose the same people -- and then one leak masks another. Giving a negative an outcome long after the horizon (LK010) extends the follow-up that LK004 had just truncated, and LK004 goes quiet. A dataset built to be ground truth cannot have that in it.

Returns:

Type Description
SyntheticDataset

(dataset, {check_id: [subject_id]}). Injectors are applied in

dict[str, list[str]]

sorted id order so the result is deterministic regardless of the order

tuple[SyntheticDataset, dict[str, list[str]]]

the caller listed them.

Source code in src/ehrlint/inject.py
def inject_many(
    dataset: SyntheticDataset, check_ids: list[str], *, n: int = 5, seed: int = 0
) -> tuple[SyntheticDataset, dict[str, list[str]]]:
    """Plant several leaks in sequence, on disjoint subjects.

    Disjoint because every injector is seeded identically and would otherwise
    choose the same people -- and then one leak masks another. Giving a
    negative an outcome long after the horizon (LK010) extends the follow-up
    that LK004 had just truncated, and LK004 goes quiet. A dataset built to be
    ground truth cannot have that in it.

    Returns:
        ``(dataset, {check_id: [subject_id]})``. Injectors are applied in
        sorted id order so the result is deterministic regardless of the order
        the caller listed them.
    """
    current = dataset
    planted: dict[str, list[str]] = {}
    touched: set[str] = set()
    for check_id in sorted({c.strip().upper() for c in check_ids if c.strip()}):
        result = inject(current, check_id, n=n, seed=seed, exclude=touched)
        touched.update(result.subjects)
        current = result.dataset
        planted[check_id] = result.subjects
    return current, planted

injector_ids

injector_ids() -> list[str]

Check ids that have an injector, sorted.

Source code in src/ehrlint/inject.py
def injector_ids() -> list[str]:
    """Check ids that have an injector, sorted."""
    return sorted(INJECTORS)

Errors

ehrlint.exceptions

Exception hierarchy for ehrlint.

Errors carry enough context to locate the problem: a file path, a column name, a subject id. None of them carry patient data beyond the identifiers needed to find the offending row -- which is the same discipline the findings follow.

EhrlintError

Bases: Exception

Base class for every error raised by ehrlint.

Source code in src/ehrlint/exceptions.py
class EhrlintError(Exception):
    """Base class for every error raised by ehrlint."""

InputError

Bases: EhrlintError

Input data could not be read, or is missing something required.

Source code in src/ehrlint/exceptions.py
class InputError(EhrlintError):
    """Input data could not be read, or is missing something required."""

    def __init__(
        self,
        message: str,
        *,
        path: str | None = None,
        table: str | None = None,
        column: str | None = None,
    ) -> None:
        self.path = path
        self.table = table
        self.column = column
        bits = [b for b in (path, table and f"table={table}", column and f"column={column}") if b]
        suffix = f" [{', '.join(bits)}]" if bits else ""
        super().__init__(f"{message}{suffix}")

SchemaError

Bases: InputError

Input data does not satisfy the schema ehrlint requires.

Source code in src/ehrlint/exceptions.py
class SchemaError(InputError):
    """Input data does not satisfy the schema ehrlint requires."""

TaskSpecError

Bases: EhrlintError

A task specification is missing, malformed, or self-contradictory.

Source code in src/ehrlint/exceptions.py
class TaskSpecError(EhrlintError):
    """A task specification is missing, malformed, or self-contradictory."""

SplitsError

Bases: EhrlintError

A splits definition is missing, malformed, or inconsistent with the data.

Source code in src/ehrlint/exceptions.py
class SplitsError(EhrlintError):
    """A splits definition is missing, malformed, or inconsistent with the data."""

CheckError

Bases: EhrlintError

A check could not run.

Distinct from a check firing: a finding means a leak was found, this means the check itself failed. The audit records it as skipped with a reason rather than silently reporting a clean result.

Source code in src/ehrlint/exceptions.py
class CheckError(EhrlintError):
    """A check could not run.

    Distinct from a check *firing*: a finding means a leak was found, this means
    the check itself failed. The audit records it as skipped with a reason
    rather than silently reporting a clean result.
    """

    def __init__(self, message: str, *, check_id: str | None = None) -> None:
        self.check_id = check_id
        prefix = f"{check_id}: " if check_id else ""
        super().__init__(f"{prefix}{message}")

RegistryError

Bases: EhrlintError

A check could not be registered or resolved.

Source code in src/ehrlint/exceptions.py
class RegistryError(EhrlintError):
    """A check could not be registered or resolved."""

ReportError

Bases: EhrlintError

A report could not be rendered or written.

Source code in src/ehrlint/exceptions.py
class ReportError(EhrlintError):
    """A report could not be rendered or written."""