diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 7b5acdb..4623ba1 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -1,7 +1,6 @@ name: Docs -# Checks the documentation on every pull request. GitHub Pages publishing remains enabled during the -# Read the Docs transition; see docs/index.md for the cutover and old-URL redirect steps. +# Read the Docs hosts the site. This workflow only validates documentation changes. on: pull_request: @@ -18,26 +17,13 @@ jobs: - uses: actions/checkout@v4 - uses: astral-sh/setup-uv@v6 - run: uv sync --locked --group docs + - uses: actions/setup-node@v4 + with: + node-version: "24" + - run: npm ci --ignore-scripts + - run: npm test - run: uv run --group docs pytest -q docs/tests - run: uv run --group docs python docs/catalogue.py - run: uv run ruff check docs - run: uv run ruff format --check docs - run: uv run --group docs mkdocs build --strict - - if: github.event_name == 'push' - uses: actions/upload-pages-artifact@v3 - with: - path: site - - deploy: - if: github.event_name == 'push' - needs: build - runs-on: ubuntu-latest - permissions: - pages: write - id-token: write - environment: - name: github-pages - url: ${{ steps.deployment.outputs.page_url }} - steps: - - id: deployment - uses: actions/deploy-pages@v4 diff --git a/.gitignore b/.gitignore index b17017b..d51a596 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,6 @@ __pycache__/ build/ dist/ site/ + +.cache/ +node_modules/ diff --git a/README.md b/README.md index 4b0dafe..b0753cc 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,11 @@ Browse the [algorithm catalogue](https://meds-algorithm.readthedocs.io/en/latest for implementations, reviewed installation commands and validation evidence. Register or update an entry through `catalogue/algorithms.yaml`; documentation builds and release observations are independent of the runtime package and never query private source repositories. See -[site maintenance](https://github.com/McDermottHealthAI/meds-algorithm/blob/main/docs/index.md). +[site maintenance](https://meds-algorithm.readthedocs.io/en/latest/documentation/). + +The [unified documentation](https://meds-algorithm.readthedocs.io/en/latest/) also contains the +template workflow, [implementation prompt builder](https://meds-algorithm.readthedocs.io/en/latest/prompt-builder/), +manual tutorial, publishing guides and API/UML references. ## Package layout @@ -142,8 +146,10 @@ training. Keep each algorithm's data-access and cluster approval rules in its ow ### Unreleased +- Consolidate the template guides, implementation prompt and interactive builder on Read the Docs; + use Read the Docs as the only documentation host. - Configure Read the Docs hosting with the existing MkDocs theme and docs dependency group; update - documentation links and document the transition from GitHub Pages. + documentation links and document Read the Docs hosting. - Host the algorithm catalogue and its release-observation workflow in this ecosystem repository. - Add independently built documentation; catalogue metadata and tooling are excluded from Python distributions. diff --git a/docs/assets/prompt-builder.css b/docs/assets/prompt-builder.css new file mode 100644 index 0000000..c7da175 --- /dev/null +++ b/docs/assets/prompt-builder.css @@ -0,0 +1,19 @@ +.prompt-builder { --pb-line: var(--md-default-fg-color--lightest, #dce5eb); --pb-bg: var(--md-default-bg-color, #fff); --pb-ink: var(--md-default-fg-color, #182b3d); color: var(--pb-ink); } +.prompt-builder fieldset { min-width: 0; border: 1px solid var(--pb-line); border-radius: 8px; margin: 1.6em 0; padding: 1em 1.25em; } +.prompt-builder legend { padding: 0 .4em; font-weight: 700; } +.prompt-builder label { display: block; margin: .8em 0; font-weight: 600; } +.prompt-builder .pb-hint { display: block; font-size: .86em; font-weight: 400; opacity: .8; margin: .3em 0; } +.prompt-builder input:not([type="checkbox"]), .prompt-builder select, .prompt-builder textarea { display: block; width: 100%; min-width: 0; margin-top: .4em; padding: .65em .75em; border: 1px solid var(--pb-line); border-radius: 5px; color: var(--pb-ink); background: var(--pb-bg); font: inherit; font-weight: 400; } +.prompt-builder input:not([type="checkbox"]) { line-height: 1.4; } +.prompt-builder textarea { resize: vertical; line-height: 1.5; } +.prompt-builder [data-prompt-output] { font: .85em/1.6 Consolas, monospace; white-space: pre-wrap; } +.prompt-builder .pb-check { display: flex; align-items: baseline; gap: .6em; font-weight: 400; } +.prompt-builder input[type="checkbox"] { flex: 0 0 auto; width: 1em; height: 1em; } +.prompt-builder .pb-actions { display: flex; flex-wrap: wrap; gap: .7em; margin: 1em 0; } +.prompt-builder button { padding: .6em 1em; border: 1px solid var(--pb-line); border-radius: 5px; color: var(--pb-ink); background: var(--pb-bg); cursor: pointer; font: inherit; } +.prompt-builder [data-generate] { background: #116b7b; color: #fff; border-color: #116b7b; } +.prompt-builder button:disabled { opacity: .45; cursor: not-allowed; } +.prompt-builder :focus-visible { outline: 3px solid #208bba; outline-offset: 3px; } +.prompt-builder .pb-status { min-height: 1.6em; } +.prompt-builder [hidden] { display: none !important; } +@media (max-width: 600px) { .prompt-builder fieldset { padding: .75em; } } diff --git a/docs/assets/prompt-builder.js b/docs/assets/prompt-builder.js new file mode 100644 index 0000000..57ba30f --- /dev/null +++ b/docs/assets/prompt-builder.js @@ -0,0 +1,173 @@ +/* No network calls or persisted inputs: the documentation embeds the canonical implementation prompt. */ +(function () { + "use strict"; + const profiles = ["supervised", "finetune", "probe", "zero_shot_direct", "zero_shot_materialized", "predict_only"]; + const scopes = { + local: "Implementation and local tests only.", + integration: "Implementation, local tests and MEDS-DEV integration; stop before the demo.", + full: "Implementation, local tests, MEDS-DEV integration and preparation for demo/full-data evaluation; wait for the existing execution approvals." + }; + const clean = (value) => String(value ?? "").trim(); + function required(value, label) { + const result = clean(value); + if (!result) throw new Error(`Supply ${label}.`); + return result; + } + function choice(value, allowed, label) { + if (!allowed.includes(value)) throw new Error(`Choose a valid ${label}.`); + return value; + } + function renderPrompt(template, values) { + const source = choice(values.source_kind, ["paper", "code", "both"], "source type"); + const destination = choice(values.destination_kind, ["local", "github"], "destination"); + const mode = choice(values.profile_mode, ["automatic", "manual"], "profile selection"); + const tasks = choice(values.tasks_mode, ["none", "ready"], "task-input option"); + const scope = choice(values.scope, Object.keys(scopes), "work scope"); + if (values.exploratory_mode !== undefined && typeof values.exploratory_mode !== "boolean") { + throw new Error("Exploratory mode must be an explicit checkbox selection."); + } + let repository = "New local Git repository only; do not create a GitHub repository."; + if (destination === "github") { + const name = required(values.github_repo, "the new GitHub repository") + .replace(/^https:\/\/github\.com\//, "").replace(/\/$/, ""); + if (!/^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?\/[A-Za-z0-9_.-]+$/.test(name) + || [".", ".."].includes(name.split("/")[1])) { + throw new Error("Use owner/name or https://github.com/owner/name for the new repository."); + } + const visibility = choice(values.visibility, ["private", "public"], "repository visibility"); + repository = `New GitHub repository: https://github.com/${name}; visibility: ${visibility}.`; + } + let selection = "automatic"; + if (mode === "manual") { + const selected = Array.isArray(values.profiles) ? [...new Set(values.profiles)] : []; + if (!selected.length || selected.some((name) => !profiles.includes(name))) { + throw new Error("Select at least one supported profile."); + } + selection = `Explicit profiles: ${selected.join(", ")}.`; + } + let bundle = "Not supplied. Continue implementation and synthetic tests; defer evaluation on external task bundles."; + if (tasks === "ready") { + required(values.dataset, "the dataset name, revision and MEDS path for these tasks"); + bundle = [ + `Prepared labels: ${required(values.labels_path, "the prepared labels location")}`, + `Prepared task configs: ${required(values.configs_path, "the prepared task-config location")}`, + `Bundle revision/identifier: ${required(values.bundle_revision, "the bundle revision or identifier")}`, + `Task subset: ${clean(values.task_subset) || "All tasks already present in this bundle."}` + ].join("\n"); + } + const replacements = { + PAPER_REFERENCES_OR_NOT_SUPPLIED: source === "code" ? "Not supplied." : required(values.papers, "at least one paper reference"), + CODE_REFERENCES_OR_NOT_SUPPLIED: source === "paper" ? "Not supplied." : required(values.code, "at least one code/repository reference"), + NEW_REPOSITORY_DESTINATION: repository, + NEW_LOCAL_REPOSITORY_PATH: required(values.local_path, "a new local repository path"), + PROFILE_SELECTION: selection, + DATASET_CONTEXT_OR_NOT_SUPPLIED: clean(values.dataset) || "Not supplied; use synthetic data for local implementation tests.", + PREPARED_TASK_BUNDLE_OR_NOT_SUPPLIED: bundle, + WORK_SCOPE: scopes[scope], + SCIENTIFIC_AMBIGUITY_MODE: values.exploratory_mode === true + ? "Exploratory mode explicitly enabled: provisional algorithm-design assumptions are permitted under the policy below." + : "Confirmation required (default): ask before implementing material unresolved scientific choices.", + ADDITIONAL_CONSTRAINTS_OR_NONE: clean(values.constraints) || "None." + }; + return template.replace(/<([A-Z][A-Z0-9_]*)>/g, (token, key) => { + if (!Object.hasOwn(replacements, key)) throw new Error(`Unknown prompt field: ${token}`); + return replacements[key]; + }); + } + function init(root) { + if (root.dataset.initialized) return; + const source = root.querySelector("[data-prompt-template]"); + if (!source) return; + const template = JSON.parse(source.textContent); + const form = root.querySelector("[data-builder-form]"); + const output = root.querySelector("[data-prompt-output]"); + const status = root.querySelector("[data-status]"); + const copy = root.querySelector("[data-copy]"); + const download = root.querySelector("[data-download]"); + const generate = root.querySelector("[data-generate]"); + const reset = root.querySelector("[data-reset]"); + root.dataset.initialized = "true"; + let stale = true; + const field = (name) => form.elements.namedItem(name); + function section(name, visible, requiredNames = []) { + const block = root.querySelector(`[data-section="${name}"]`); + block.hidden = !visible; + block.querySelectorAll("input, textarea, select").forEach((input) => { + input.disabled = !visible; + input.required = visible && requiredNames.includes(input.name); + }); + } + function update() { + section("papers", field("source_kind").value !== "code", ["papers"]); + section("code", field("source_kind").value !== "paper", ["code"]); + section("github", field("destination_kind").value === "github", ["github_repo"]); + section("profiles", field("profile_mode").value === "manual"); + const ready = field("tasks_mode").value === "ready"; + section("tasks", ready, ["labels_path", "configs_path", "bundle_revision"]); + field("dataset").required = ready; + } + form.addEventListener("input", () => { + update(); + stale = true; + copy.disabled = download.disabled = true; + status.textContent = output.value ? "Inputs changed. Generate again to update the prompt; existing edits remain below." : "Fill in the inputs, then generate your prompt."; + }); + form.addEventListener("submit", (event) => { + event.preventDefault(); + if (!form.reportValidity()) return; + const data = new FormData(form); + const values = Object.fromEntries(data.entries()); + values.profiles = data.getAll("profiles"); + values.exploratory_mode = field("exploratory_mode").checked; + try { + output.value = renderPrompt(template, values); + output.readOnly = false; + stale = false; + copy.disabled = download.disabled = false; + status.textContent = "Prompt ready. Review or edit it, then copy or download."; + } catch (error) { + copy.disabled = download.disabled = true; + status.textContent = error.message; + } + }); + output.addEventListener("input", () => { + download.disabled = copy.disabled = stale || !output.value.trim(); + }); + copy.addEventListener("click", async () => { + try { + await navigator.clipboard.writeText(output.value); + status.textContent = "Prompt copied."; + } catch (_) { + output.focus(); + output.select(); + status.textContent = "Clipboard access is unavailable. The prompt is selected; use Ctrl+C or Command+C."; + } + }); + download.addEventListener("click", () => { + const url = URL.createObjectURL(new Blob([output.value], {type: "text/plain;charset=utf-8"})); + const anchor = document.createElement("a"); + anchor.href = url; + anchor.download = "meds-algorithm-implementation.txt"; + anchor.click(); + setTimeout(() => URL.revokeObjectURL(url), 0); + }); + reset.addEventListener("click", () => { + form.reset(); + stale = true; + update(); + output.value = ""; + output.readOnly = true; + copy.disabled = download.disabled = true; + status.textContent = "Reset. Fill in the inputs, then generate your prompt."; + }); + update(); + generate.disabled = reset.disabled = false; + } + if (typeof module !== "undefined" && module.exports) module.exports = {renderPrompt, init}; + if (typeof document !== "undefined") { + const start = () => document.querySelectorAll("[data-prompt-builder]").forEach(init); + if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", start); + else start(); + if (typeof document$ !== "undefined") document$.subscribe(start); + } +})(); diff --git a/docs/concepts.md b/docs/concepts.md new file mode 100644 index 0000000..efbe2db --- /dev/null +++ b/docs/concepts.md @@ -0,0 +1,207 @@ +# Concepts + +This page walks through the objects the contract talks about, in the order data flows through an algorithm: +the dataset, the task, the predicates, the task specification (zero-shot only), the artifacts each +command publishes, the final predictions, and the measurements attached to all of them. + +## The MEDS dataset and its splits + +The input data is a split-sharded [MEDS](https://medical-event-data-standard.github.io/) dataset, passed +as `external_meds_dir`. MEDS fixes what `subject_id`, `time`, `code`, the value columns, static events +(`time = null`) and code metadata mean; an algorithm may not reinterpret them. + +The dataset comes with three splits: `train`, `tuning` and `held_out`. They are a **boundary**: + +!!! warning "Fit population statistics on `train` only" + Anything fitted over a population — vocabularies, code frequencies, quantile bins, normalization + constants, feature selections — must be fitted on the training split alone. Fitting over all splits is + *transductive leakage*. It is easy to miss because it is not label leakage: code frequencies do not + depend on labels, so an algorithm can pass every label-leakage check and still carry it. If preprocessing + is delegated upstream and the scope is not yours to control, declare which quantity was fitted over + which population. + +The generated end-to-end test checks this: it plants a canary code in every tuning and held-out subject of +its fixture, and none may appear among the codes the algorithm fitted statistics for (see the +[FAQ](faq.md#how-do-the-tests-catch-label-leakage-and-transductive-fitting)). + +The MIMIC-IV demo in MEDS form is the canonical real-data example used by the tests; it is not a separate +schema. + +## The task index (built upstream) + +An upstream task extraction can store both keys and outcomes. Inference/scoring receives its key-only +view as `external_index_dir`; training receives permitted targets through `external_labels_dir`: + +- **keys**: `(subject_id, prediction_time)`, the rows to predict, in every split; +- **labels**: a value column such as `boolean_value`. + +### Who reads which labels + +Keys identify where to predict; ground-truth values describe what happened. They are not interchangeable. +The [canonical argument table](reference/spec.md#step-arguments-and-artifacts) defines each step's access. +Inference and ordinary scoring read only keys. The core index reader projects those columns at Parquet +read time, even when MEDS-DEV supplies a directory whose files also contain outcomes. + +The index is never built in the algorithm repository. One ACES extraction, run upstream, applies the task's +trigger, inclusion/exclusion criteria and splits, so every algorithm scores exactly the same rows: + +| Run | Who builds the index | +|---|---| +| MIMIC-IV demo (smoke test) | MEDS-DEV's `meds-dev-task`, task `mortality/in_icu/first_24h` | +| Full-data evaluation | a shared, reviewed task bundle for the target dataset, built once upstream: clinical tasks defined and extracted with [ACES](https://eventstreamaces.readthedocs.io/), or randomly sampled code-by-horizon tasks (generated with [meds-random-task-sampler](https://github.com/florian6973/meds-random-task-sampler) and selected with [meds-task-selection](https://github.com/florian6973/meds-task-selection)), containing each task's definition and its per-task index and labels | + +Every algorithm compared on a dataset uses the same bundle. Zero-shot runs additionally need each task's ACES +criteria file. + +An algorithm repository must not re-extract, filter or extend the index. If an algorithm rebuilt the cohort itself, +two algorithms could silently be evaluated on different patients, and a zero-shot algorithm would read the labels +it is supposed to be blind to. + +### Reading labels: the one rule + +The contract rule is: evaluated-split labels are never read, and only `train_supervised` / `train_finetune` / `train_probe` +and a `predict_only` in-context learner read train/tuning labels. There is exactly one sanctioned exception: once every probability is final, `predict` may join the label column onto the predictions by +key (`attach_ground_truth`), because meds-evaluation reads ground truth from the predictions file. Nothing +computed from that join may feed back into a prediction. + +## Dataset predicates + +Tasks are written against named *predicates* (for example `icu_admission`, `death`, or +`abnormally_low_sodium` with a value threshold). A dataset's predicates file binds those names to that +dataset's codes. It is passed as `external_predicates_file` (MEDS-DEV's `{predicates_path}`). + +- When MEDS-DEV provides predicates for a dataset, reuse them; the MIMIC-IV demo must use MEDS-DEV's + MIMIC-IV predicates. +- The algorithm decides whether and how to use them: selecting tokens, building SQL or columns, matching + events directly, or not at all. +- Any command that consumes the file records its digest and origin in its manifest. +- An algorithm that relies on particular predicate names declares and validates them in its own configuration. + The contract deliberately has no generic "predicate features" format. + +### Additional feature predicates per dataset + +Every generated configuration inherits optional `additional_predicates_file` from `AlgorithmConfig`. +Select the dataset configuration explicitly, for example `config_file=/repo/dataset_configs/mimic_iv.yaml`: + +```yaml +additional_predicates_file: ../predicates/mimic_iv_additional.yaml +``` + +Paths resolve relative to the configuration file. The additional file has the same predicate-only +shape as MEDS-DEV's dataset file: + +```yaml +predicates: + algorithm_specific_event: + code: YOUR_DATASET_EVENT_CODE +``` + +During `preprocess_data`, core combines this file with `external_predicates_file`, or uses it alone if +no base was supplied. Duplicate names are errors even if their definitions agree; duplicate YAML keys +and task/cohort sections are also rejected. Expression semantics and dataset compatibility remain the +algorithm's responsibility. The runner passes the resolved path as `request.predicates_file` to both +the compatibility hook and preprocessing. Implementations must read that path rather than merge files. + +Core saves `resolved_feature_predicates.yaml` in the prepared-data artifact, records both source paths +and content digests plus the resolved digest, and includes them in the configuration digest. The source +additions file can be temporary: later steps use persisted features and do not reopen or merge it. +Keep the same configuration across the lifecycle; use a separate config file for each dataset. + +These are feature additions only. They never modify `TaskSpec`, evaluated labels, or the cohort. Task +predicates continue to reach only the task-conditioned commands through the original task binding. +Preprocessing must not include outcome-dependent definitions or read events beyond each permitted cutoff. +For a changed target or cohort, update the shared upstream task bundle instead. + +## The task specification (zero-shot only) + +A supervised algorithm learns *what* to predict from labels. A zero-shot algorithm never sees labels, so the task +itself must be an input. The task language is [ACES](https://eventstreamaces.readthedocs.io/): a criteria +file passed as `external_task_criteria_file`, bound to the dataset predicates. The pair is the **task +specification** (`TaskSpec`). + +```mermaid +flowchart LR + crit[ACES criteria file
e.g. mortality/in_icu/first_24h.yaml] --> spec[TaskSpec] + pred[Dataset predicates
e.g. MIMIC-IV predicates.yaml] --> spec + spec --> digest["semantics_digest
sha256 of criteria + predicates"] +``` + +The **semantics digest** hashes the criteria bytes together with the predicates bytes. MEDS-DEV task files +leave dataset codes as `???`, so the same criteria bound to MIMIC-IV and to eICU predicates are different +tasks with different digests. Every task-conditioned artifact records this digest, so an artifact can never +be silently reused for another task. See [Zero-shot in practice](zero-shot.md). + +## Artifacts and the manifest envelope + +Every command publishes one **artifact**: a directory containing whatever payload the algorithm wants plus a +`manifest.yaml` that follows a fixed envelope. + +```mermaid +flowchart LR + p[preprocess_data] -->|patients| pt[pretrain] + pt -->|pretrained_algorithm| i[infer_embeddings] + i -->|embeddings| st[train_probe] + st -->|probe_algorithm| pr[predict_probe] + pr -->|predictions| out[(final output)] +``` + +*(The `probe` profile shown; other profiles skip some commands. See [Choosing a profile](profiles.md).)* + +| Artifact type | Produced by | Meaning | +|---|---|---| +| `patients` | `preprocess_data` | the algorithm's own representation of the dataset | +| `pretrained_algorithm` | `pretrain` | a task-independent algorithm | +| `embeddings` / `trajectories` | `infer_embeddings` / `infer_trajectories` | separate task-independent representations and generated futures | +| `supervised_algorithm` / `finetuned_algorithm` / `probe_algorithm` | `train_supervised` / `train_finetune` / `train_probe` | a complete task-specific inference bundle | +| `predictions` | `predict` | the normative final output | + +Four properties hold for every artifact: + +- **The payload format is the algorithm's.** The manifest declares it (`payload_format: name/version`), and + consumers reject an incompatible type, contract version or payload format *before* doing expensive work. +- **Publication preserves complete artifacts.** The command writes its manifest last in unique staging. + New outputs appear by one rename. Overwrite retains the old output until replacement succeeds and + restores it on failure; readers may briefly see no destination during the two renames. Process crashes + can leave recovery files. See [publication behavior](reference/manifest.md). +- **Inputs and configuration are traceable.** The manifest records stable identifiers or digests of its + inputs (including the predicates digest and, for task-conditioned artifacts, the task's provenance and + digest), a `config_digest` over the command's arguments and resolved settings, and the git commit and + dirty state of the code that produced it. +- **Artifacts are never nested.** Each artifact is its own directory; `infer_embeddings`, for example, writes a + sibling of the data artifact rather than a subdirectory of it, so runs over different indexes cannot + overwrite each other. + +Core's `StepRunner` owns this work through `measured_artifact(...)`; algorithm methods write payloads into +the supplied staging directory. See the [manifest reference](reference/manifest.md). + +## Final predictions + +`predict` writes `predictions.parquet` in the +[meds-evaluation](https://github.com/kamilest/meds-evaluation) prediction schema of the version MEDS-DEV +evaluates with (currently `meds-evaluation==0.0.3`, checked with `validate_binary_classification_schema`): + +- exactly **one row per requested key**, with **unique keys**; +- row order means nothing and must never be used to match outputs to keys; +- conformance tests compare the written keys directly with the requested index — a self-reported count is + not proof of coverage; +- rows may be left out only under an explicitly declared exclusion policy that lists the excluded keys; +- every parquet file in the predictions artifact is read as predictions (MEDS-DEV evaluates + `**/*.parquet`), so supporting tables use another format. + +For zero-shot algorithms, predictions are always evaluated against the labels of the *requested* task, and the +predictions artifact carries or references the `relaxations.yaml` describing what the algorithm actually +answered. + +## Measurements + +Every command invocation records its resource use in the manifest, wherever it runs (tests, MEDS-DEV, +SLURM): + +- **wall time** on a monotonic clock; +- **memory** sampled over the whole process tree; on Linux, PSS (which apportions shared pages) is the + comparison value and RSS is kept as a diagnostic; +- **GPU** peak allocated/reserved memory when measured; +- optional work units (subjects, events, rows, optimizer steps). + +`null` means *not measured*; `0` means *measured, nothing used*. Measurements are observations for +comparing algorithms, never pass/fail thresholds. diff --git a/docs/core-package.md b/docs/core-package.md new file mode 100644 index 0000000..1034c77 --- /dev/null +++ b/docs/core-package.md @@ -0,0 +1,25 @@ +# Shared core package + +The core lives in its own [repository](https://github.com/McDermottHealthAI/meds-algorithm), pinned by the template to PyPI version `0.4.0a5`. +See its [layout and usage](https://github.com/McDermottHealthAI/meds-algorithm/blob/v0.4.0a5/README.md) for its artifact, runtime, task, evaluation, integration and conformance APIs. +The [specification](reference/spec.md) and [architecture and UML](reference/architecture.md) are +rendered directly from this core checkout, the same sources included in its distributions. +The `latest` documentation follows core `main`; generated algorithms use their pinned installed release. + +`AlgorithmConfig` is the shared configuration parent. Neural implementations can extend `NNConfig`; +the [neural configuration and scaling guide](reference/architecture.md#neural-network-configuration-and-scaling-experiments) +shows a concrete subclass, YAML settings and a capacity sweep. It also explains why data-subset selection +belongs upstream and which measurements an algorithm must report for a later scaling-law analysis. +The template keeps this example in the core guide rather than maintaining a second specification. + +Family-specific sharing belongs in one algorithm-family repository with multiple profiles and shared internal +modules. Tokenizers, neural architectures, objectives and algorithm-specific task translators stay there. + +Generated repositories import `meds_algorithm` directly. Their package contains a typed algorithm +implementation and an algorithm-owned immutable configuration. `tests/e2e.py` invokes the same shared runner +as the CLI and supplies fitted-feature inspection hooks. +Reusable assertions, fixtures and MEDS-DEV provisioning live in core. No compatibility package is copied. + +Publication uses exclusive writers and overwrite rollback. Algorithm provenance must be supplied explicitly; +the installed package cannot infer an algorithm checkout. See the core README for crash recovery, reader +visibility during overwrite, optional dependencies, and measurement limits. diff --git a/docs/documentation-tests.md b/docs/documentation-tests.md new file mode 100644 index 0000000..2b8956f --- /dev/null +++ b/docs/documentation-tests.md @@ -0,0 +1,40 @@ +# Documentation tests + +Documentation tests run separately from the installed runtime suite. They do not train algorithms, +access clinical data, or establish scientific validity. + +Run `uv run --group docs pytest -q docs/tests` and, with Node 24, `npm ci --ignore-scripts && npm test`. +The strict MkDocs build additionally validates page links, anchors, snippets, template-source hashes +and rendered reference pages. See [site maintenance](documentation.md) for the full commands. + +## Python source and rendering tests + +| Test | What it checks | Why | +|---|---|---| +| Canonical prompt embedding | Decodes embedded JSON and compares it with the static prompt's text block | Keep the copyable and interactive prompts identical | +| Release guide rendering | Renders the template source with example package names | Avoid showing unresolved Jinja placeholders | +| Script boundary escaping | Embeds prompt text containing a script closer | Keep source text inert inside HTML | +| Core reference sources | Compares contract, UML, test catalogue and orchestration with this checkout | Prevent stale installed-wheel docs from masking code changes | +| Immutable source and cache | Checks the requested commit URL and verifies a cache hit avoids another fetch | Make template-owned guides reproducible and support offline rebuilds | +| Corrupt downloaded/cached sources | Rejects content whose SHA-256 differs from the manifest | Never silently publish changed source content | +| Mutable revision rejection | Rejects a branch name instead of a full commit SHA | Keep builds independent of moving template branches | +| Download failure | Propagates unavailable-source errors | Fail instead of substituting stale or unrelated guidance | + +The [catalogue test inventory](catalogue-testing.md) documents its separate registry checks. + +## Browser tests + +The prompt builder uses plain JavaScript with no runtime dependencies, network requests or persisted +form inputs. jsdom is used only in tests. + +| Test | What it checks | Why | +|---|---|---| +| All 144 input combinations | Source, destination, profiles, task bundle, scope and ambiguity mode | Preserve the user's choices and scientific/execution gates | +| Ambiguity defaults | Missing/false mode requires confirmation; non-booleans fail | Prevent accidental exploratory opt-in | +| Checkbox lifecycle | Unchecked initial state, explicit toggle, stale output and reset | Keep exploratory mode intentional | +| Invalid plans | Missing sources, destination, profiles and prepared-task metadata | Avoid apparently executable incomplete prompts | +| Task subsets and literal text | Existing task identifiers and non-recursive substitutions | Preserve supplied scope and constraints | +| Conditional fields | Visibility, required fields and several selected profiles | Prevent hidden inputs from overriding user choices | +| Edits, copy, download, reset | Exact edited text and stale-output invalidation | Prevent copying outdated instructions | +| Clipboard fallback | Selection after denied clipboard access | Support local previews and restricted browser contexts | +| Inert HTML and repeated initialization | HTML-like user text and repeated page initialization | Prevent injection and lost edits | diff --git a/docs/documentation.md b/docs/documentation.md new file mode 100644 index 0000000..e6a4c69 --- /dev/null +++ b/docs/documentation.md @@ -0,0 +1,60 @@ +# Maintaining documentation + +The full MEDS algorithms site is maintained in `McDermottHealthAI/meds-algorithm` and hosted at +. `latest` follows core `main`; it may describe changes +newer than the released core version pinned by an algorithm. Use its installed contract for that version. + +## One maintained source per document + +| Content | Canonical source | +|---|---| +| Concepts, profiles, workflow, tutorials, prompt builder and static prompt | This repository's `docs/` | +| Contract, architecture/UML, shared tests and orchestration | Core's `src/meds_algorithm/*.md` and `ARCHITECTURE.md`, rendered directly from this checkout | +| Catalogue | `catalogue/algorithms.yaml` and `catalogue/updates.json` | +| Template contributor release/test guides | `RELEASING.md` and `TESTING.md` in the template repository | +| Generated algorithm release/test guides | `template/RELEASING.md.jinja` and `template/docs/TESTING.md` in the template repository | + +The last two rows are included at build time from the immutable template commit recorded in +`docs/template-source.json`. Each file is SHA-256 checked and cached under `.cache/template-docs/`. +Only these public documentation files are fetched; the build does not clone private algorithms or run +template code. A missing source or checksum mismatch fails the build. The cached files permit offline +rebuilds, but a clean checkout needs network access for its first build. + +When template-owned guides change, update the revision and four hashes in `docs/template-source.json` +in a core PR, then run the strict build. Keep their content in the template so generated projects and +the documentation use the same instructions. Do not copy those files into this repository. + +The static implementation prompt lives in `docs/implementation-prompt.md`; the interactive builder embeds +its text block. Edit that single source to update both. Template README links point here. + +## Local checks and preview + +From the root of this core checkout: + +```bash +uv sync --locked --group docs +uv run --group docs pytest -q docs/tests +uv run ruff check docs +uv run ruff format --check docs +npm ci --ignore-scripts +npm test +uv run --group docs mkdocs build --strict +uv run --group docs mkdocs serve +``` + +Node 24 is needed only for browser tests, not for building or serving the site. See +[documentation tests](documentation-tests.md) and [catalogue tests](catalogue-testing.md) for what each checks. +Runtime tests remain under `tests/`; their inventory is [Shared-package tests](reference/tests.md). + +## Hosting + +Read the Docs builds with `.readthedocs.yaml`, Python 3.12, uv's `docs` dependency group and MkDocs Material. +`READTHEDOCS_CANONICAL_URL` supplies the version-specific canonical URL, with a `latest` fallback locally. +GitHub Actions runs documentation checks independently. Enable Read the Docs pull request builds in the +project settings for hosted previews. Older release tags without this configuration cannot build this site. + +Read the Docs is the only documentation host. The template repository has no documentation deployment +workflow; all MkDocs and prompt-builder checks run here. + +The catalogue update workflow still needs permission for Actions to create pull requests; see +[catalogue maintenance](implemented-algorithms.md#register-or-update-an-algorithm) for its report fallback. diff --git a/docs/examples/manual-supervised.sh b/docs/examples/manual-supervised.sh new file mode 100644 index 0000000..3c6255e --- /dev/null +++ b/docs/examples/manual-supervised.sh @@ -0,0 +1,216 @@ +#!/usr/bin/env bash +# --8<-- [start:setup] +# A complete local tutorial. Prerequisites: Bash, Git, uv, and network access for dependencies. +set -euo pipefail +command -v git >/dev/null +command -v uv >/dev/null + +# Use a NEW directory. Nothing is deleted or overwritten outside this tutorial. +WORKSPACE="${1:-$PWD/manual-meds-example}" +if [[ -e "$WORKSPACE" ]]; then + echo "Choose a new directory: $WORKSPACE already exists" >&2 + exit 1 +fi +mkdir -p "$WORKSPACE" +cd "$WORKSPACE" +WORKSPACE="$PWD" + +# 1. Render a named, single-profile repository from a reproducible template revision. +cat > answers.yaml <<'YAML' +algorithm_name: Manual baseline +algorithm_slug: manual_baseline +algorithm_class: ManualBaseline +algorithm_description: Synthetic tutorial estimating training-label prevalence. +profiles: [supervised] +uses_predicates: true +implementation_source: This tutorial; not a reproduction of a published clinical algorithm. +YAML +uvx --from 'copier==9.17.1' copier copy --defaults --trust \ + --vcs-ref=55ddd290d20a39dd19954321580c616cc11a74ae \ + --data-file answers.yaml \ + https://github.com/McDermottHealthAI/MEDS_algorithm_template.git manual-baseline +cd manual-baseline +# --8<-- [end:setup] + +# --8<-- [start:environment] +# 2. Create the Python environment and install the generated package and test dependencies. +uv python install 3.11 +uv sync --python 3.11 --extra test +uv run manual-baseline profiles +uv run manual-baseline commands --profile supervised +uv run meds-algorithm-spec > installed-contract.txt +# --8<-- [end:environment] + +# 3. Implement the generated stubs manually. No agent or MEDS-DEV runner is involved. +# --8<-- [start:configuration] +cat > src/manual_baseline/config.py <<'PY' +from dataclasses import dataclass +from meds_algorithm import AlgorithmConfig + + +@dataclass(frozen=True) +class ManualBaselineConfig(AlgorithmConfig): + smoothing: float = 1.0 + + def validate(self): + if self.smoothing <= 0: + raise ValueError("smoothing must be positive") +PY +# --8<-- [end:configuration] + +# --8<-- [start:algorithm] +cat > src/manual_baseline/manual_baseline.py <<'PY' +import json +from pathlib import Path + +import polars as pl +import yaml + +from meds_algorithm import AlgorithmRepository, PayloadMetadata, SupervisedAlgorithm +from meds_algorithm.requests import ( + PreprocessDataRequest, TrainSupervisedRequest, PredictSupervisedRequest, +) +from .config import ManualBaselineConfig + + +class ManualBaseline(SupervisedAlgorithm): + name = "manual_baseline" + config_type = ManualBaselineConfig + + def preprocess_data(self, request: PreprocessDataRequest) -> PayloadMetadata: + events = pl.read_parquet(str(request.meds_dir / "data" / "*.parquet")) + events.write_parquet(request.output.directory / "events.parquet") + # Core supplies the composed feature predicates; keep its reserved file unchanged. + predicates = yaml.safe_load(request.predicates_file.read_text())["predicates"] + (request.output.directory / "summary.json").write_text(json.dumps({ + "events": events.height, "predicate_names": sorted(predicates), + })) + return PayloadMetadata("tutorial-events") + + def train_supervised(self, request: TrainSupervisedRequest) -> PayloadMetadata: + outcomes = request.labels.read("train")["boolean_value"] + if len(outcomes) == 0: + raise ValueError("Training labels must not be empty") + alpha = self.config.smoothing + probability = (outcomes.sum() + alpha) / (len(outcomes) + 2 * alpha) + (request.output.directory / "probability.json").write_text(json.dumps(probability)) + return PayloadMetadata("tutorial-prevalence") + + def predict_supervised(self, request: PredictSupervisedRequest) -> PayloadMetadata: + probability = json.loads((request.fitted_algorithm.directory / "probability.json").read_text()) + request.index.read().with_columns( + pl.lit(probability).alias("predicted_boolean_probability") + ).write_parquet(request.output.directory / "predictions.parquet") + return PayloadMetadata("tutorial-predictions") + + +IMPLEMENTATIONS = {"supervised": ManualBaseline} +PROFILES = tuple(IMPLEMENTATIONS) +# Keep the completion gate: this tutorial does not implement the full conformance adapters/report. +STUB_PROFILES = set(PROFILES) + + +def create_repository(): + return AlgorithmRepository(IMPLEMENTATIONS, repo=Path(__file__).resolve().parents[2]) +PY +# --8<-- [end:algorithm] + +# --8<-- [start:inputs] +# 4. Create tiny synthetic MEDS events and an upstream label/index bundle. +# Real work should reuse a reviewed task bundle, not derive labels inside the algorithm. +mkdir -p inputs/meds/data inputs/labels dataset_configs predicates +uv run python - <<'PY' +from datetime import datetime +import polars as pl + +pl.DataFrame({ + "subject_id": [1, 2, 3, 4, 5], + "time": [datetime(2020, 1, 1)] * 5, + "code": ["DEMO//encounter"] * 5, + "numeric_value": [None] * 5, +}, schema_overrides={"numeric_value": pl.Float64}).write_parquet("inputs/meds/data/events.parquet") +for split, ids, outcomes in ( + ("train", [1, 2, 3], [True, True, False]), + ("held_out", [4, 5], [True, False]), +): + pl.DataFrame({ + "subject_id": ids, + "prediction_time": [datetime(2020, 1, 2)] * len(ids), + "boolean_value": outcomes, + }).write_parquet(f"inputs/labels/{split}.parquet") +PY +cat > predicates/base.yaml <<'YAML' +predicates: + encounter: + code: DEMO//encounter +YAML +cat > predicates/demo_additional.yaml <<'YAML' +predicates: + demo_measurement: + code: DEMO//measurement +YAML +cat > dataset_configs/demo.yaml <<'YAML' +smoothing: 1.0 +additional_predicates_file: ../predicates/demo_additional.yaml +YAML +# --8<-- [end:inputs] + +# --8<-- [start:paths] +# 5. Run the complete supervised lifecycle, one independent process per step. +CONFIG="$PWD/dataset_configs/demo.yaml" +MEDS="$PWD/inputs/meds" +LABELS="$PWD/inputs/labels" +BASE_PREDICATES="$PWD/predicates/base.yaml" +ARTIFACTS="$PWD/runs/manual/supervised/artifacts" +# --8<-- [end:paths] + +# --8<-- [start:preprocess] +uv run manual-baseline preprocess_data --profile supervised \ + "config_file=$CONFIG" "external_meds_dir=$MEDS" \ + "external_predicates_file=$BASE_PREDICATES" "output_data_dir=$ARTIFACTS/data" +# --8<-- [end:preprocess] + +# --8<-- [start:train] +uv run manual-baseline train_supervised --profile supervised \ + "config_file=$CONFIG" "input_data_dir=$ARTIFACTS/data" \ + "external_labels_dir=$LABELS" "output_supervised_algorithm_dir=$ARTIFACTS/algorithm" +# --8<-- [end:train] + +# --8<-- [start:predict] +uv run manual-baseline predict_supervised --profile supervised \ + "config_file=$CONFIG" "input_data_dir=$ARTIFACTS/data" \ + "input_supervised_algorithm_dir=$ARTIFACTS/algorithm" "external_index_dir=$LABELS" \ + 'splits=[held_out]' "output_predictions_dir=$ARTIFACTS/predictions" \ + "external_evaluation_labels_dir=$LABELS" +# --8<-- [end:predict] + +# --8<-- [start:verify] +# 6. Inspect and verify the outputs. Only the runner attaches the held-out truth after scoring. +uv run python - <<'PY' +from pathlib import Path +import polars as pl +import yaml +from meds_algorithm import read_manifest +from meds_algorithm.conformance.assertions import assert_prediction_schema +from manual_baseline import ManualBaseline, ManualBaselineConfig + +root = Path("runs/manual/supervised/artifacts") +predictions = pl.read_parquet(root / "predictions/predictions.parquet") +assert predictions["subject_id"].to_list() == [4, 5] +assert predictions["predicted_boolean_probability"].to_list() == [0.6, 0.6] +assert predictions["boolean_value"].to_list() == [True, False] +assert_prediction_schema(predictions) +print(predictions) +for stage in ("data", "algorithm", "predictions"): + manifest = read_manifest(root / stage) + assert (root / stage / "config.json").is_file() + assert (root / stage / "request.json").is_file() + print(stage, manifest["command"]["name"], manifest["resources"]["wall_seconds"]) +resolved = yaml.safe_load((root / "data/resolved_feature_predicates.yaml").read_text()) +assert set(resolved["predicates"]) == {"encounter", "demo_measurement"} +config = ManualBaselineConfig.load(root / "algorithm/config.json") +assert ManualBaseline(config).name == "manual_baseline" +PY +uv run pytest -q tests/test_contract.py tests/test_operations.py +printf 'Tutorial completed in %s\n' "$PWD" +# --8<-- [end:verify] diff --git a/docs/faq.md b/docs/faq.md new file mode 100644 index 0000000..d221e32 --- /dev/null +++ b/docs/faq.md @@ -0,0 +1,88 @@ +# FAQ + +## Why can't my algorithm build or filter its own cohort? + +Because then two algorithms could be evaluated on different patients and nobody would notice. The index and +its labels come from one extraction run upstream (MEDS-DEV's `meds-dev-task` for the demo, a shared, +reviewed task bundle for full data). An algorithm predicts every requested row; rows can be left out +only under a declared exclusion policy that lists them. + +## My algorithm needs a statistic over the whole dataset. Can I compute it on all splits? + +No. Fit vocabularies, frequencies, bins and normalizers on `train` only. Computing them over all splits is +transductive leakage: it uses held-out patients' data even though it never touches a label. + +## Why do some algorithms run in two Python environments? + +Because their dependencies cannot coexist. An algorithm's training stack may pin an older `meds` (for example +femr 0.2.4 requires `meds==0.3.3`), while the ACES tooling a zero-shot adapter uses for task translation +(aces-relaxations, es-aces ≥ 0.7.3) requires `meds ≥ 0.4`. The two sides can run in separate environments +and exchange only files. The contract does not care how a command +is executed, so this is allowed; document it in the repository. + +## What does it mean that a task is "refused"? + +A zero-shot algorithm must raise rather than answer a task it cannot pose; the command fails and writes no +predictions. The common case is a direct algorithm given a task whose label is not *future-only* in +aces-relaxations' structural sense — for example MEDS-DEV's `mortality/in_icu/first_24h`, whose `gap` +window is anchored at the trigger and straddles the prediction time. A re-anchoring step makes it +posable; see [Zero-shot in practice](zero-shot.md#windows-that-straddle-the-prediction-time). +Materialized algorithms are not affected. + +## Why is the AUROC on the MIMIC-IV demo undefined (or meaningless)? + +The demo has 100 patients. For `mortality/in_icu/first_24h` the held-out split has a handful of rows and +may have no positive label at all, in which case AUROC is undefined. Training rows cannot stand in for a +pretrained algorithm: pretraining saw those patients' futures. The demo gate validates that the pipeline runs +on real data — formats, scale transitions, coverage, resources — not how good the algorithm is. Performance +comes from the full-data run. + +## My algorithm writes several files next to `predictions.parquet`. Is that allowed? + +Yes, with one rule: every parquet file in the predictions artifact must be a predictions file. MEDS-DEV +evaluates every `**/*.parquet` under the predictions directory, and the key check does the same. Store +supporting tables — a zero-shot query bundle, a coverage table — in another format such as Arrow IPC; +`relaxations.yaml` and JSON files are fine. + +## How do the tests catch label leakage and transductive fitting? + +The end-to-end check validates the original run and a fresh full-lifecycle rerun: + +- **Label leakage:** every stage runs again with evaluated outcome columns removed (all outcomes for + zero-shot). Separate input roots remain separate; permitted training/context labels are retained. + Both runs use the recorded fixture seed and deterministic settings. They must produce the same keyed + scores within the contract's tolerance. Original and rerun probabilities are checked across every shard. +- **Transductive fitting:** `meds_algorithm.conformance.signal.add_split_canaries` gives every tuning and held-out subject a + canary code that no training subject has. Your `fitted_codes(artifacts)` hook reports every code the + algorithm fitted a statistic for (vocabulary, frequencies, bins); no canary may appear in it. + +## Can a non-zero-shot algorithm use the ACES task? + +Only `predict_only` may accept optional `external_task_criteria_file` as provenance, with +`semantics_digest: null`. Other non-zero-shot commands reject it. Supervised, finetune and probe algorithms +learn the task from its labels. + +## What does `scripts/github-sync.sh` push? + +Only `runs//spec.yaml` (dataset name and counts, task, predicates digest), `runs//result.yaml` +(status, git commit and dirty state, environment, SLURM job id, per-command resource summary) and +`runs//manifests/*.yaml`, on a `runs//` branch with a draft PR. It never pushes +predictions, labels, data, checkpoints, raw logs or metrics. The template computes no metrics at all: +MEDS-DEV's evaluation step (meds-evaluation) does. + +## How do I bring template changes into an existing repository? + +Review your working tree, then run in the generated repository: + +```bash +copier update --trust +``` + +The repository's `.copier-answers.yml` records the template source, revision and answers, so Copier can +apply the template's changes as a three-way merge. Render from the Git URL rather than a local checkout so +updates work on every machine. + +## Where is the authoritative rule for X? + +In the [specification](reference/spec.md), which this site renders from core's `src/meds_algorithm/CONTRACT.md`. +Generated repositories' `SPEC.md` points to the contract in their installed core version. diff --git a/docs/hooks.py b/docs/hooks.py new file mode 100644 index 0000000..8a7ac61 --- /dev/null +++ b/docs/hooks.py @@ -0,0 +1,94 @@ +"""Render canonical core documents and immutable template-owned guides in one site.""" + +import hashlib +import json +import re +from pathlib import Path +from urllib.request import urlopen + +from jinja2 import Environment, StrictUndefined + + +class _TemplateGuides: + """Read hash-verified guide sources from a pinned public template commit.""" + + def __init__(self, root: Path): + self.root = root + self.manifest = json.loads((root / "docs/template-source.json").read_text(encoding="utf-8")) + if not re.fullmatch(r"[0-9a-f]{40}", self.manifest["revision"]): + raise ValueError("Template documentation source must pin a full commit SHA") + + def read(self, name: str) -> str: + digest = self.manifest["files"][name] + revision = self.manifest["revision"] + cache = self.root / ".cache/template-docs" / revision / name + if not cache.resolve().is_relative_to((self.root / ".cache/template-docs").resolve()): + raise ValueError("Guide source must stay inside the documentation cache") + if cache.is_file(): + content = cache.read_bytes() + else: + url = f"https://raw.githubusercontent.com/McDermottHealthAI/MEDS_algorithm_template/{revision}/{name}" + with urlopen(url, timeout=30) as response: + content = response.read() + if hashlib.sha256(content).hexdigest() != digest: + raise ValueError(f"Template guide checksum mismatch: {name}") + cache.parent.mkdir(parents=True, exist_ok=True) + cache.write_bytes(content) + return content.decode("utf-8") + + def provenance(self) -> str: + revision = self.manifest["revision"] + return ( + '!!! note "Template source version"\n' + f" Template-owned guides below come from [revision `{revision[:12]}`]" + f"(https://github.com/McDermottHealthAI/MEDS_algorithm_template/tree/{revision}). " + "Use your generated repository's guides for its exact version.\n\n" + ) + + +def on_page_markdown(markdown, page, **kwargs): + root = Path(__file__).resolve().parents[1] + source = page.file.src_uri + if source in {"publishing-algorithms.md", "releasing.md", "testing.md"}: + guides = _TemplateGuides(root) + if source == "publishing-algorithms.md": + guide = ( + Environment(undefined=StrictUndefined) + .from_string(guides.read("template/RELEASING.md.jinja")) + .render( + algorithm_name="My Algorithm", algorithm_slug="my_algorithm", package_name="my-algorithm" + ) + ) + return markdown.replace("", guides.provenance() + guide) + if source == "releasing.md": + return markdown.replace( + "", guides.provenance() + guides.read("RELEASING.md") + ) + return markdown.replace( + "", guides.provenance() + guides.read("TESTING.md") + ).replace("", guides.read("template/docs/TESTING.md")) + if source == "running.md": + return markdown.replace( + "", + (root / "src/meds_algorithm/ORCHESTRATION.md").read_text(encoding="utf-8"), + ) + if source == "reference/spec.md": + return markdown + "\n\n" + (root / "src/meds_algorithm/CONTRACT.md").read_text(encoding="utf-8") + if source == "reference/architecture.md": + return ( + (root / "ARCHITECTURE.md") + .read_text(encoding="utf-8") + .replace("(src/meds_algorithm/CONTRACT.md)", "(spec.md)") + ) + if source == "reference/tests.md": + return (root / "src/meds_algorithm/TESTING.md").read_text(encoding="utf-8") + if source == "prompt-builder.md": + document = (root / "docs/implementation-prompt.md").read_text(encoding="utf-8") + prompt = re.search(r"```text\n(.*?)\n```", document, re.DOTALL).group(1) + # JSON lives inside an HTML script element: source text must not close it. + payload = json.dumps(prompt).replace("<", "\\u003c") + return markdown.replace( + "", + f'', + ) + return markdown diff --git a/docs/implementation-prompt.md b/docs/implementation-prompt.md new file mode 100644 index 0000000..dc7a713 --- /dev/null +++ b/docs/implementation-prompt.md @@ -0,0 +1,235 @@ +# Copyable algorithm-implementation prompt + +Use the [interactive prompt builder](https://meds-algorithm.readthedocs.io/en/latest/prompt-builder/) +or fill in the fields below. The agent inspects sources and selects profiles before generating a new +local or GitHub repository. The builder runs locally in your browser; it does not launch an agent. +The provided `real_data` test remains the MIMIC-IV demo smoke test, independent of supplied evaluation tasks. + +The prompt adapts [Ponytail's implementation principles](https://github.com/DietrichGebert/ponytail/blob/main/skills/ponytail/SKILL.md) +to scientific algorithm development. It works with Claude and other coding agents without installing a plugin. + +```text +Implement a MEDS algorithm from the following inputs. + +Paper(s), supplementary material and versions: + + +Code/repository source(s), revisions, configurations and checkpoints: + + +Destination (a NEW local repository or a NEW GitHub repository, including visibility): + + +Local working directory for the new repository: + + +Profile selection (automatic, or an explicit list of one or more profiles): + + +Dataset context (name, revision and MEDS path, if available): + + +Already prepared evaluation tasks (labels location, task-config location, bundle revision and +optional task subset; or explicitly not supplied): + + +Work scope (implementation/local tests, also MEDS-DEV integration, or preparation for full evaluation): + + +Scientific ambiguity mode (confirmation required by default; exploratory only if explicitly enabled): + + +Additional implementation constraints: + + +Inspect the supplied sources before generating the repository. If both paper and code are provided, +compare them, record discrepancies and identify which behavior is implemented; do not silently assume +one always overrides the other. If only a paper is provided, distinguish source-backed choices from +necessary assumptions. If only code is provided, inspect its revision, configuration and checkpoint +requirements; do not claim fidelity to an unavailable paper. + +Resolve scientific ambiguities before implementing the affected behavior. Check the paper, supplements, +official code and available configurations first; record sources and material conflicts. Ask whether two +reasonable interpretations could produce materially different algorithms or change what evaluation measures. +A missing learning rate or batch size can usually use a plausible, configurable default with its rationale +recorded, unless that choice is central to the scientific claim. Missing feature construction, temporal +aggregation, architecture components or training objectives are material ambiguities, not routine defaults. + +In confirmation-required mode (also the default if no mode is supplied), pause dependent implementation +and request confirmation for a material unresolved ambiguity. Explain what is missing, the evidence +consulted, plausible interpretations and their consequences; recommend an option when justified. Continue +independent work while waiting. An earlier explicit decision covering the same choice is sufficient unless +new evidence or a scope change invalidates it; silence is not confirmation. + +Only when exploratory mode is explicitly enabled may you implement provisional interpretations of material +algorithm-design ambiguities without first obtaining a decision. Record each as provisional before using +it, expose the choice in configuration where appropriate, and label affected code, tests and results as an +exploratory adaptation. Require review of these decisions before claiming faithful reproduction. Do not +present an assumption as source-backed behavior or silently substitute a familiar method for a missing one. + +In BOTH modes, ambiguities about leakage, permitted label access, cohort/target definitions or evaluation +validity remain blocking for dependent work until explicitly resolved. Exploratory mode does not authorize +changing supplied tasks, weakening acceptance tests, accessing data or running demo/full-data/cluster jobs +without the existing approvals. Record the mode, routine defaults, unresolved questions, provisional choices +and explicit decisions in IMPLEMENTATION_REPORT.md under "Scientific assumptions and decisions"; update the +existing report rather than creating another specification file. + +For automatic profile selection, choose one or more profiles supported by documented source behavior: +supervised, finetune, probe, zero_shot_direct, zero_shot_materialized or predict_only. Record evidence for +each choice and proceed when the evidence is clear. Do not add speculative capabilities merely because +a profile exists. For an explicit list, implement that scope; report material incompatibilities before +implementing unsupported behavior, and do not silently replace or expand it. Shared methods may be +implemented once through multiple profile inheritance when their semantics match, or through separate +classes with shared components. Each selected profile gets its own MEDS-DEV YAML and acceptance tests. + +Generate the new repository with the MEDS algorithm template at +https://github.com/McDermottHealthAI/MEDS_algorithm_template using a reviewed immutable revision, and +record it in .copier-answers.yml. Pass the selected profiles explicitly; do not accidentally accept the +single-profile default. Never overwrite an existing local directory or GitHub repository. For a local +destination, initialize Git without creating a remote. For a GitHub destination, create the specified +repository with the specified visibility and connect the local checkout; report missing access without +changing the destination or visibility. Respect any more specific workspace repository-routing rules. + +Supplied evaluation tasks are already prepared: use their labels and task configs as fixed inputs. +Verify their dataset/revision, task identities, splits, prediction times and consistency before use. +An optional task subset selects only tasks already present in that bundle. Do not generate new tasks, +extract new labels, relabel examples or silently modify the task definitions. Use supplied indices or +read only the supplied prediction keys through the core index reader; evaluation outcomes must never +enter scoring. Zero-shot profiles additionally require executable task criteria and matching predicates. +If the bundle is not supplied, continue implementation and synthetic tests; report evaluation as +pending. An incomplete bundle blocks only the dependent evaluation, not unrelated implementation. + +Read AGENTS.md, SPEC.md, README.md, and docs/IMPLEMENTATION_GUIDE.md in the generated repository +completely before writing code. Inspect the paper, supplementary material, source repository, +configuration files, checkpoints, preprocessing code, and evaluation code available from the supplied +source. + +Apply the Ponytail principle of the smallest complete change: implement the complete source-defined +algorithm with the least additional infrastructure. Check meds-algorithm, existing algorithm-family code, +standard libraries and installed dependencies before creating helpers. If the source ships an installable +package or executable, depend on it pinned to the exact reviewed revision and call it; write only contract +glue (label-free preprocessing, cohort/key adaptation, explicit key association, coverage). Install it in the +algorithm environment; if it breaks meds-algorithm within core's declared dependency ranges, fix core. For a +genuine conflict with core, run the source as an external executable from a separate environment that the +algorithm package creates and manages (committed lockfile, built at install or first use, digest recorded in +manifests; MEDS-DEV installs only requirements.txt). Reimplement only when the source cannot run even in +isolation or its code cannot meet the contract even with glue, and record why in IMPLEMENTATION_REPORT.md; +local hardware alone is not a reason, since CPU or other hardware is acceptable. +Choose an algorithm_slug that does not shadow the source's distribution or import name (for example +genhpf_meds, not genhpf), so both can be installed together. Keep shared fixes in their +owning package; do not copy core utilities into the algorithm repository. Avoid speculative wrappers, +configuration options and compatibility layers. Trace affected commands, callers, fixtures and +documentation, and finish all required changes. Simplicity must preserve scientific fidelity, temporal +and label isolation, artifact validation, reproducibility, required evaluation evidence and human +review gates. Write focused tests for new behavior and failure cases. Report deviations and checks +that were not run. + +Write minimalist, auditable, object-oriented algorithm code. Put source-defined hyperparameters and defaults +in the algorithm-owned frozen Config class in config.py; validate values and prove +serialization round trips. Keep the implementation in .py and expose the named algorithm +and configuration classes from the package, so callers can import them meaningfully. +Keep the public API intentional and small. Classes, functions and modules used only inside the implementation +should use a single leading underscore (for example _FeatureEncoder or _features.py) and should not be +re-exported from the package __init__.py. List only intended public exports in __all__. Keep contract-required +methods and integration hooks publicly named where required. A leading underscore signals an internal, +unstable interface in Python; it does not enforce access control. Prefer it over double-underscore name +mangling unless avoiding a specific inheritance collision. Do not create extra classes just to organize +private helpers, and do not hide the algorithm/configuration classes callers are expected to import. +For neural algorithms with matching semantics, extend core NNConfig rather than +duplicating shared capacity, learning_rate, batch_size, weight_decay and dropout settings. Define +source-backed defaults and the capacity-multiplier mapping (reference architecture, dimensions, rounding +and minimums); call super().validate() for inherited +constraints. Test that the settings actually control construction/training. See the installed architecture +guide for units, extension examples and scaling ownership. Keep cohort selection upstream; record actual +parameter counts and consumed data separately rather than inferring them from capacity or a data fraction. +Use inherited additional_predicates_file for dataset-specific feature additions when needed. Read the +runner-resolved request.predicates_file in preprocessing; do not override base definitions, merge again, +or change task predicates. Preserve temporal isolation and use the same configuration across steps. +Implement the selected Algorithm profile methods with their typed request classes. Prefer small cohesive +components and explicit constructor dependencies; use inheritance for the profile contract and composition +for algorithm internals. Do not add unnecessary classes, wrappers, mutable module-level runtime state, hidden +singletons, import-time work, broad exception swallowing, or duplicated contract tables. Declarative +constants and the profile-to-implementation association are appropriate; fitted state belongs in artifacts. +Use core's runner for both CLI execution and tests. Algorithm methods write only to its staging destination +and return PayloadMetadata; do not reimplement publication, measurements or manifest/config/request writing. +Implement explicit payload compatibility checks. Prediction outputs contain keys and probabilities; +only the runner attaches evaluation truth after scoring. Demonstrate that saved configuration and requests +can be reloaded in a fresh process and executed without an earlier call on the same algorithm instance. + +Preserve all selected algorithm profiles and standardized command arguments, MEDS input boundary, artifact +manifest envelopes, MEDS-DEV model.yaml interface, and final MEDS prediction output. Intermediate payload +formats and execution mechanisms are algorithm-owned: choose whatever preprocessing, featurization, framework, +batching or non-batching strategy, external executable, storage format, and algorithm architecture most +faithfully reproduce the source. + +When predicates are needed, reuse MEDS-DEV predicates for the selected dataset if available; otherwise, +use reviewed external predicates for that dataset and record their provenance. Decide within the algorithm +how those predicates become inputs. Validate dataset-specific codes, units, task definitions, and label mappings; +do not assume MIMIC mappings apply to another dataset. Keep such mappings in dataset-specific +configuration or algorithm-owned code. Do not introduce a generic predicate-derived feature representation +into the contract package. Keep the provided MIMIC-IV demo code, task, and MEDS-DEV predicates as the +canonical smoke test, regardless of the full-data target. + +For a zero_shot_direct algorithm (answers queries directly, e.g. MOTOR, EveryQuery) or a zero_shot_materialized +algorithm (generates futures and evaluates the task on them; infer is task-independent and only predict +receives the task): the algorithm receives the original ACES task through +external_task_criteria_file (with the dataset predicates) and the upstream-built index through +external_index_dir. Never build, filter, or extend the cohort, and read the index only through +meds_algorithm.read_index. Reuse an existing aces-to- adapter for this algorithm if one exists; +otherwise write one on aces-relaxations, pinned to an exact version: reject tasks that are not future-only +or are degenerate, normalize, then apply only the approximations and assumptions the algorithm's query +language forces. Publish relaxations.yaml with each zero-shot prediction artifact, and report per task whether +the answer is exact. +A materialized algorithm evaluates the task on generated futures instead and needs no relaxation beyond +sampling. Follow the shape for the selected profile in docs/IMPLEMENTATION_GUIDE.md. +Do not omit source behavior because it is inconvenient for a fixture; adapt the implementation or fixture +instead. + +Record every material source element as ported, adapted, or omitted, with evidence and justification, in +IMPLEMENTATION_REPORT.md. Implement every selected typed algorithm method, finalize the implementation-specific +command strings in model.yaml, and implement tests/e2e.py. Configure representative config instances +in tests/conftest.py. Keep TestConformance inheriting the shared meds-algorithm acceptance suite; +do not copy its test bodies or override its checks to suppress failures. Remove each profile from STUB_PROFILES only +after that profile completes and produces standards-conformant predictions; complete every selected profile. + +Always run: + + uv run pytest -rs + +Also run `bash scripts/check_distribution.sh` to verify installed imports, CLI commands and bundled +defaults outside the checkout. Extend `tests/wheel_smoke.py` for required algorithm configuration or +resources. Follow RELEASING.md for publication readiness; package publication itself requires an explicit +user request. Do not choose a license on the user's behalf or bundle datasets, credentials or fitted weights. + +If the selected scope includes MEDS-DEV integration or full-evaluation preparation, also run: + + uv run pytest -m meds_dev -rs + +For implementation/local-tests scope, finish with implementation and local validation evidence. For +MEDS-DEV integration scope, finish after its integration evidence. Report unavailable dependencies or +adapters explicitly; do not weaken tests. The following demo and full-data stages apply only when the +selected scope is preparation for full evaluation; selecting that scope is not execution approval. + +Complete the pre-demo sections of IMPLEMENTATION_REPORT.md and ask for human review of source fidelity, +predicate interpretation, and the proposed MIMIC-IV demo execution. Only after approval, run: + + uv run pytest -m real_data -rs + +There must be zero algorithm_stub skips. Report exact pass/skip counts and account for every remaining skip. +Update IMPLEMENTATION_REPORT.md with the demo cohort, final-output coverage, predicate provenance, +environment, wall time, peak process-tree PSS/RSS, GPU measurements when available, failures, and fixes. +Ask for a second human review before launching the selected full dataset through the repository's SLURM +interface. Review target-dataset compatibility, access, and resources separately from the MIMIC-IV demo. +Use the supplied, already prepared task bundle for the selected dataset. It must contain task configs, +per-task labels/keys and split assignments; zero-shot runs additionally require the original ACES criteria +and matching predicates. Do not generate or extract replacement evaluation tasks. Canonical synthetic +fixtures and the built-in MIMIC-IV demo smoke task remain separate from this supplied evaluation bundle. If the bundle is absent +or inconsistent, report the evaluation blocker and the exact missing inputs. +Record the dataset name/revision, predicate provenance, bundle location, supplied bundle revision and +available upstream build provenance, and a digest of its task definitions. Keep the bundle external to Git. +Commit the implementation, configuration and report-so-far; push when a remote is configured. Run the +cluster job from that exact clean commit. After the authorized run, complete the report with full-data evidence, scientific deviations, and known limitations, then +synchronize structured results through the GitHub workflow when the destination has a GitHub remote. +For a local-only repository, retain the committed report and run evidence locally. Treat +docs/IMPLEMENTATION_GUIDE.md as the authority for the ordered gates and their evidence. +``` diff --git a/docs/index.md b/docs/index.md index 32d709f..1dca57a 100644 --- a/docs/index.md +++ b/docs/index.md @@ -1,66 +1,81 @@ # MEDS algorithms -`meds-algorithm` provides shared contracts and infrastructure for algorithms consuming MEDS data: -profile interfaces, typed step requests, artifact provenance, prediction validation and conformance tests. +This site documents the `meds-algorithm` shared package and the +[MEDS algorithm template](https://github.com/McDermottHealthAI/MEDS_algorithm_template), a +[Copier](https://copier.readthedocs.io) template for packaging a clinical +prediction algorithm as a repository that anyone can run, compare, and audit the same way. You render a new +repository from it, implement your algorithm inside a fixed set of commands, and get, for free, the parts +that make algorithms comparable: a standard input and output, artifact manifests with measurements, MEDS-DEV +registration, a SLURM interface, and a staged test workflow ending in a full-data run. -- Browse [implemented algorithms](implemented-algorithms.md), their declared profiles, reviewed PyPI - versions and validation evidence. -- Read the [package README](https://github.com/McDermottHealthAI/meds-algorithm#readme), - [architecture and UML](https://github.com/McDermottHealthAI/meds-algorithm/blob/main/ARCHITECTURE.md), - and [canonical contract](https://github.com/McDermottHealthAI/meds-algorithm/blob/main/src/meds_algorithm/CONTRACT.md). -- Build an implementation using the - [algorithm template and its workflow documentation](https://mcdermotthealthai.github.io/MEDS_algorithm_template/). +!!! note "Who this site is for" + Generated repositories' `README.md`, `AGENTS.md` and `SPEC.md` are written as instructions for coding + agents that port algorithms. This site explains the same contract to people: algorithm implementers, + reviewers, and benchmark organizers. The [specification](reference/spec.md) remains the normative + source; where this site and the spec differ, the spec wins. -The catalogue belongs to this ecosystem repository and is maintained independently of Python package -releases. Its registry, renderer and tests are excluded from both wheel and source distributions. -Updating a listing rebuilds this site; it does not require publishing another `meds-algorithm` version. +## The picture in one diagram -## Maintaining this documentation - -```bash -uv sync --locked --group docs -uv run --group docs pytest docs/tests -q -uv run --group docs mkdocs serve +```mermaid +flowchart LR + subgraph upstream["Upstream (shared by every algorithm)"] + meds[(MEDS dataset
train / tuning / held_out)] + task[ACES task
criteria + predicates] + aces[[ACES extraction]] + index[(Task index
subject_id, prediction_time,
boolean_value)] + meds --> aces + task --> aces + aces --> index + end + subgraph repo["Algorithm repository (rendered from the template)"] + cmds["Commands of the selected profile
preprocess_data → … → predict"] + end + meds --> cmds + index --> cmds + task -. zero-shot only .-> cmds + cmds --> preds[(predictions.parquet
one row per requested key)] + preds --> eval[[meds-evaluation / MEDS-DEV]] ``` -See [catalogue registration and updates](implemented-algorithms.md#register-or-update-an-algorithm) and -the [catalogue test inventory](catalogue-testing.md). Runtime tests remain under `tests/` and their -inventory remains in the packaged -[TESTING.md](https://github.com/McDermottHealthAI/meds-algorithm/blob/main/src/meds_algorithm/TESTING.md). - -### Read the Docs hosting +Everything left of the algorithm repository is built **once, upstream**: the dataset, the task definition, +and the cohort (which patients, at which prediction times, with which labels). Every algorithm receives the +same inputs and must return one prediction for every requested `(subject_id, prediction_time)`. That is +what makes results comparable. -The repository-root `.readthedocs.yaml` builds this site with Python 3.12, the existing `docs` -dependency group and MkDocs Material. It uses uv to install dependencies from `pyproject.toml` and -`uv.lock`, and fails on documentation warnings. GitHub Actions continues running catalogue tests, -validation, lint and the strict documentation build independently of the hosting service. +## Fixed by the contract, owned by the algorithm -To enable hosting: +| Fixed by the contract | Owned by the algorithm | +|---|---| +| Inputs: a split-sharded MEDS dataset, a task index, optional dataset predicates, and (zero-shot) an ACES task | Preprocessing, featurization, tokenization | +| Six **algorithm profiles**, each a fixed sequence of commands | Architecture, framework, batching, hardware | +| Standard command arguments (`external_meds_dir`, `output_predictions_dir`, …) | Intermediate payload formats (checkpoints, embeddings, caches) | +| A `manifest.yaml` envelope on every artifact, written last and published with rollback | How the payload inside an artifact is laid out | +| Wall time and memory measurements on every command | How fast the algorithm is | +| Final predictions in the meds-evaluation schema, keyed and complete | How probabilities are computed | +| `algorithms//model.yaml` for MEDS-DEV, SLURM scripts, GitHub result sync | The command strings inside them, once finalized | -1. Import `McDermottHealthAI/meds-algorithm` into Read the Docs and use `meds-algorithm` as the project - slug. If a different slug is needed, update the README badge and links, `pyproject.toml` documentation - URL and the fallback `site_url` in `mkdocs.yml` together. -2. Set the default branch to `main`, build its `latest` version, and use `latest` as the default - documentation version initially. Older release tags do not contain this hosting configuration. -3. Verify the build and the catalogue at - , and enable pull request builds if desired. +The contract fixes **boundaries**, not methods. An algorithm can be a PyTorch transformer, a gradient-boosted +tree, an external executable or a call to a service; the template only cares that each command consumes +the right artifacts and publishes the right one. -MkDocs reads `READTHEDOCS_CANONICAL_URL` during hosted builds so canonical links use the appropriate -version URL. Local builds fall back to the `latest` URL. The source pages, navigation and theme are -shared between local builds and hosting; no second copy of the documentation is needed. +## Where to go next -### GitHub Pages transition +- **Find an implementation:** browse the [algorithm catalogue](implemented-algorithms.md). +- **Getting started:** read [Concepts](concepts.md), [Choosing a profile](profiles.md), then the + [Workflow](workflow.md) from implementation to validation. +- **Building an algorithm:** prepare instructions with the [prompt builder](prompt-builder.md), + learn the [run commands](running.md), or follow the [fully manual example](manual-example.md). +- **Development:** explore the [core package](core-package.md) and + [what belongs in the template or shared package](shared-package-assessment.md). Use the + [migration guide](migration-v4.md) and [publishing guide](releasing.md) when maintaining packages. +- **Reference:** consult the [specification](reference/spec.md), + [tests and acceptance](testing.md), or [zero-shot guide](zero-shot.md) for the details. -The existing GitHub Pages deployment remains active until Read the Docs has built successfully. -After verifying the new site, replace the Pages publication with a small redirect site that preserves -the old page paths and fragments at . Keep those -redirects hosted on Pages so existing links continue working; Read the Docs cannot redirect requests -made to the old GitHub Pages domain. Retain the GitHub Actions documentation checks when replacing -the old full-site deployment. +## Preview this site locally -This change only moves hosting for this repository. The algorithm template's documentation remains -at its existing GitHub Pages URL. +From a checkout of `McDermottHealthAI/meds-algorithm`: -The weekly catalogue workflow additionally needs permission for Actions to create pull requests; its -registration guide documents the setting and the report-artifact fallback. No private-repository -credentials are required. +```bash +uv sync --locked --group docs +uv run --group docs mkdocs serve +``` diff --git a/docs/manual-example.md b/docs/manual-example.md new file mode 100644 index 0000000..cb0ac16 --- /dev/null +++ b/docs/manual-example.md @@ -0,0 +1,177 @@ +# Fully manual example: setup to predictions + +This walkthrough generates a repository, implements its three supervised methods by hand, creates +synthetic inputs, and runs **preprocessing → training → prediction** locally. No coding agent, MEDS-DEV +installation, clinical dataset, GPU or cluster is needed. All commands appear in execution order below. + +The example is a **constant-prevalence baseline**, not a clinical algorithm reproduction. It learns one +smoothed probability from the training labels and emits it for every requested held-out key. It copies +events during preprocessing but does not use event features to predict. Additional predicates are +included to demonstrate composition and provenance, not to claim feature-dependent behavior. + +## Setup and expected result + +Use Bash on Linux/macOS or inside WSL on Windows, with **Git and uv installed** and network access for +Python/packages. Run the commands in a new workspace; the script refuses an existing directory. +`uv python install 3.11` installs the tutorial's Python, and `uv sync --extra test` installs the generated +package, core, Polars and the conformance dependencies into its `.venv`. No global Python environment +is modified. Copier and the template revision are pinned so the tutorial can be reproduced. + +Run the numbered sections below **in order, in the same Bash session**. Alternatively, expand +[All commands](#all-commands) at the end to copy the complete script, or download the +[same script](examples/manual-supervised.sh) and run +`bash manual-supervised.sh /absolute/path/to/a/new/tutorial-directory`. + +The generated package is `manual_baseline`, its class is `ManualBaseline`, and its named command is +`manual-baseline`. Each lifecycle command starts a fresh +process, using the same `config_file`. There are three training outcomes (`true, true, false`) and a +smoothing value of 1, so the resulting probability is `(2 + 1) / (3 + 2) = 0.6` for both held-out rows. + +--- + +## 1. Create the workspace and generate the repository + +Choose a new directory and render the supervised profile. These commands create `manual-baseline/` +and change into it; all subsequent paths are relative to that generated repository. + +```bash +--8<-- "docs/examples/manual-supervised.sh:setup" +``` + +--- + +## 2. Install the environment + +Install Python and the generated package, then inspect its profiles, commands and installed contract. + +```bash +--8<-- "docs/examples/manual-supervised.sh:environment" +``` + +--- + +## 3. Implement the algorithm + +The code-writing commands below intentionally replace the generated tutorial stubs. The template alone +does not contain an implemented algorithm. Leave its completion gate in place: this short tutorial does +not implement `tests/e2e.py`, the full implementation report, or the MEDS-DEV/demo acceptance tiers. +The final pytest command runs only the generated contract and operations checks; its success does not +mean a production port has passed the [complete workflow](workflow.md). + +### Typed configuration + +Define the smoothing parameter and validate it when configuration is loaded. + +```bash +--8<-- "docs/examples/manual-supervised.sh:configuration" +``` + +### Algorithm class + +Implement preprocessing, supervised training and prediction. The learned probability is saved to disk +so prediction can run in a separate process. + +```bash +--8<-- "docs/examples/manual-supervised.sh:algorithm" +``` + +--- + +## 4. Prepare synthetic inputs and dataset settings + +Create the event table, separate training and held-out label/index files, base and additional +predicates, and the dataset configuration that refers to those additions. + +```bash +--8<-- "docs/examples/manual-supervised.sh:inputs" +``` + +--- + +## 5. Run each lifecycle step + +Set the shared paths once. Each command below then starts its own process. + +```bash +--8<-- "docs/examples/manual-supervised.sh:paths" +``` + +### Preprocess the data + +Compose the feature predicates and write the prepared data artifact. + +```bash +--8<-- "docs/examples/manual-supervised.sh:preprocess" +``` + +### Train the algorithm + +Estimate the smoothed probability from the training outcomes and persist it in the algorithm artifact. + +```bash +--8<-- "docs/examples/manual-supervised.sh:train" +``` + +### Predict on the held-out index + +Load the saved probability and emit one prediction per requested key. The runner attaches evaluation +labels after scoring. + +```bash +--8<-- "docs/examples/manual-supervised.sh:predict" +``` + +--- + +## 6. Inspect and verify the outputs + +Check the two expected probabilities, the prediction schema, artifact metadata and composed predicates. +Then run the generated contract and operations checks. + +```bash +--8<-- "docs/examples/manual-supervised.sh:verify" +``` + +--- + +## What was produced + +Under `manual-meds-example/manual-baseline/` (or your chosen workspace): + +| Path | Contents | +|---|---| +| `src/manual_baseline/manual_baseline.py` | Concrete algorithm methods and profile association | +| `src/manual_baseline/config.py` | Named, typed configuration with positive smoothing validation | +| `dataset_configs/demo.yaml` | Dataset-specific settings and relative additional-predicates path | +| `inputs/meds/data/`, `inputs/labels/` | Synthetic events and the separate label/index bundle | +| `runs/manual/supervised/artifacts/data/` | Prepared events, summary, resolved feature predicates and core metadata | +| `runs/manual/supervised/artifacts/algorithm/` | Persisted learned probability and core metadata | +| `runs/manual/supervised/artifacts/predictions/` | Held-out probabilities, post-score truth and core metadata | + +Each artifact has `manifest.yaml`, `config.json` and `request.json`. The manifest records measurements, +input identities and the configuration. Because this example does not create a Git commit for the +generated implementation, its commit provenance may be unavailable; commit reviewed implementation +code before reproducible production runs. Keep input data and artifact payloads out of source control. + +The index and evaluation labels happen to share a directory in this example. Prediction reads only +keys through `request.index.read()`; the runner attaches `boolean_value` afterward. In real work, +reuse the upstream reviewed task bundle, respect all temporal cutoffs, and do not create labels inside +the algorithm. Additional feature predicates must not redefine the evaluated task. + +To rerun, choose fresh output paths. Explicit `do_overwrite=true` opts into replacing an artifact with +rollback; do not add it automatically to every command. Other profiles have different intermediate +steps: use the [profile lifecycle table](reference/spec.md#3-commands-and-algorithm-profiles) and +[per-step arguments](reference/spec.md#9-software-interfaces) when adapting this example. + +--- + +## All commands + +This is the complete script used by the sections above. Run it from a fresh workspace instead of +running it again in the directory you just created. + +??? example "All commands — complete runnable script" + + ```bash + --8<-- "docs/examples/manual-supervised.sh" + ``` diff --git a/docs/migration-v4.md b/docs/migration-v4.md new file mode 100644 index 0000000..602671d --- /dev/null +++ b/docs/migration-v4.md @@ -0,0 +1,103 @@ +# Migrating to algorithm terminology and typed profiles + +Version 4 changes command names, artifact types, descriptor locations and repository dispatch. Do not +reuse version 2 or 3 artifacts by editing their manifest version: validate or rebuild their payloads against +the new contract. The template emits and reads version 4 envelopes. + +## From version 3 + +This is an intentional naming change, with no old-name aliases: + +| Previous name | Current name | +|---|---| +| `meds-model-core`, `meds_model_core` | `meds-algorithm`, `meds_algorithm` | +| `ModelConfig`, `MODEL_PROFILES` | `AlgorithmConfig`, `ALGORITHM_PROFILES` | +| `ModelRepository` (mapping-based adapter) | Replace with typed `AlgorithmRepository` | +| `SupervisedModelArtifact` (and pretrained/finetuned/probe equivalents) | `SupervisedAlgorithmArtifact` (and corresponding equivalents) | +| Request field `model` or `algorithm` for fitted prediction state | `fitted_algorithm` | +| `meds-model`, `meds-model-*` helper commands | `meds-algorithm`, `meds-algorithm-*` | +| `input_*_model_dir`, `output_*_model_dir`, `*_model` artifact types | `input_*_algorithm_dir`, `output_*_algorithm_dir`, `*_algorithm` | +| Copier `model_name`, `model_slug`, `model_description` | `algorithm_name`, `algorithm_slug`, `algorithm_description` | +| `commands.py` with `ModelAlgorithm` and generic `Config` | `.py` with `` and `Config` | +| `models//model.yaml` | `algorithms//model.yaml` | + +Set the new `algorithm_class` answer explicitly for acronyms, such as `RETAIN`. Update imports, scripts, +SLURM environment variables (`MEDS_ALGORITHM_*`), lockfiles and persisted invocation descriptions together. +Serialization records concrete class identifiers; old JSON envelopes require an explicit migration. +MEDS-DEV still owns `model.yaml`, its `models/` directory, `meds-dev-model`, `model=`, and +`{model_initialization_dir}`. Those upstream names are intentionally unchanged. + +## From older single-profile repositories + +1. Replace the Copier `profile` answer with `profiles: [, ...]`. Rename `packaged` to `predict_only`. + Keep the original source/revision metadata in `.copier-answers.yml` and review the Copier update diff. +2. Implement the selected profile ABCs and associate profiles with concrete classes in `IMPLEMENTATIONS`. + Shared methods appear once where their semantics match. +3. Rename commands according to the table below. Split previously conditional implementations into + distinct profile methods, sharing cohesive components where their semantics really match. +4. Update every invocation, manifest producer, output argument, test adapter and SLURM stage selection. +5. Move the MEDS-DEV descriptor to `algorithms//model.yaml`; add one for each declared profile. + Register them independently using `--profile`; the registered name is `__`. +6. Supply explicit split lists for inference and prediction. Supervised/fine-tuned prediction receives `input_data_dir`; probe prediction receives + `input_embeddings_dir`. Scoring and inference use `external_index_dir`, not the training-label argument. +7. Replace the global `IS_STUB` boolean with `STUB_PROFILES`. Run the acceptance suite for every profile. + Record the profile in `write_run_result(..., profile=...)`. + +| Profile | Old command | New command | +|---|---|---| +| All | `preprocess_data`, `pretrain` where present | Unchanged | +| supervised | `supervised_train`, `predict` | `train_supervised`, `predict_supervised` | +| finetune | `supervised_train`, `predict` | `train_finetune`, `predict_finetune` | +| probe | `infer`, `supervised_train`, `predict` | `infer_embeddings`, `train_probe`, `predict_probe` | +| zero_shot_direct | `predict` | `predict_zero_shot_direct` | +| zero_shot_materialized | `infer`, `predict` | `infer_trajectories`, `predict_zero_shot_materialized` | +| predict_only (formerly packaged) | `predict` | `predict_only` | + +`inference` splits into `embeddings` and `trajectories`, with matching +`input_embeddings_dir`/`output_embeddings_dir` and `input_trajectories_dir`/`output_trajectories_dir`. +Task-algorithm artifacts split into `supervised_algorithm`, `finetuned_algorithm`, and `probe_algorithm`, with matching +input/output argument names. Prediction output remains `output_predictions_dir`. + +Use Copier 9.17.1 or newer; the template uses its yield extension to generate a directory for each +selected profile. A single-profile repository may omit CLI `--profile`; a repository with multiple +profiles must select one. There is no ambiguous compatibility alias for the old generic command names. + +This revision supplies the interfaces and tests. It does not automatically migrate downstream algorithm +implementations or publish a shared runtime package. See the [package assessment](shared-package-assessment.md). + +The core package now owns the single normative `CONTRACT.md`. Generated `SPEC.md` is a pointer to the +installed package version, readable with `meds-algorithm-spec`. The template and generated projects +install the alpha from an immutable Git commit in the separate core repository; no PyPI release is required. + +Replace imports from `meds_model_contract` with `meds_algorithm` and remove the generated compatibility +package. Core supplies the registration/input-resolution CLI entry points; keep only the algorithm's own +CLI in its project configuration. Import shared fixtures and checks from `meds_algorithm.conformance`. +For the typed API, pass algorithm provenance explicitly to `AlgorithmRepository(..., repo=algorithm_root)`. +Return `E2EResult` from core's `conformance.types`, recording all external inputs; +the lifecycle checker now reruns every step with forbidden outcomes absent and fresh output paths. +Existing algorithm repositories are not migrated by this template change. + +## From mapping-based commands to typed algorithms + +Core 0.4.0a5 removes `Command` and `LegacyAlgorithmRepository`. The supported execution path is +`AlgorithmRepository` with typed requests and `StepRunner`. Migrate deliberately: + +1. Move command bodies to the selected `Algorithm` profile methods. Use their typed request fields. +2. Put algorithm settings/defaults in a frozen `AlgorithmConfig` subclass; test validation and JSON round trips. +3. Replace internal publication contexts with writes to `request.output.directory` and a returned + `PayloadMetadata`. Remove algorithm-written manifests and truth attachment; the runner owns those. +4. Extend `validate_inputs` for payload compatibility. Document any override of its default same-algorithm, + same-config rule, especially for external pretrained artifacts or legacy manifests without config. +5. Route the CLI and end-to-end adapters through `AlgorithmRepository`/`StepRunner`. Verify saved + requests/configuration and fitted artifacts work in a fresh process. + +See [architecture and UML](reference/architecture.md). No private algorithm migration is included here. + + +## Fitted prediction requests in core 0.4.0a5 + +`PredictSupervisedRequest`, `PredictFinetuneRequest` and `PredictProbeRequest` now name their saved fitted +artifact `fitted_algorithm`, distinguishing it from the executing Python algorithm instance. Their JSON +schema version is 2; version 1 envelopes are rejected. Reconstruct requests with the current typed API +rather than editing version numbers. External `input_*_algorithm_dir` names are unchanged. Fitted input +manifests must contain the complete resolved config; missing historical fields are no longer filled in. diff --git a/docs/profiles.md b/docs/profiles.md new file mode 100644 index 0000000..e8662a2 --- /dev/null +++ b/docs/profiles.md @@ -0,0 +1,67 @@ +# Choosing profiles + +A profile describes an algorithm's lifecycle. A repository may declare several profiles and implement them +in one package. Choose them with Copier's `profiles` multiselect, or supply a data file: + +```yaml +profiles: [finetune, probe, zero_shot_direct] +``` + +The [prompt builder](prompt-builder.md) supports automatic selection from paper/code evidence or an +explicit selection of several profiles before repository generation. + +The [canonical lifecycle table](reference/spec.md#3-commands-and-algorithm-profiles) lists the exact steps. + +Only preprocessing and pretraining share command names. They may share artifacts when input identities, +configuration, payload format and training scope match. Selecting two profiles does not automatically +make their artifacts compatible. + +| Profile | Use when | +|---|---| +| `supervised` | Learning a task-specific algorithm directly from the dataset's training labels. | +| `finetune` | Updating a pretrained encoder together with a task-specific head. | +| `probe` | Fitting a task-specific head on frozen encoder representations. | +| `zero_shot_direct` | Translating an ACES task into direct algorithm queries and decoding probabilities without labels. | +| `zero_shot_materialized` | Generating task-independent futures, then evaluating the task on history plus those futures. | +| `predict_only` | Preprocessing then applying a supplied fixed algorithm or an in-context learner, without a training command. | + +`predict_only` is the renamed packaged profile. It does not mean probe training. In-context learners may +read explicitly selected train/tuning examples; fixed scores need no labels. Neither may read evaluated +labels before its probabilities are final. + +## Select a profile when running commands + +Each invocation selects one of the repository's declared profiles. The executable is named after your +algorithm's slug, with underscores replaced by hyphens: `algorithm_slug: my_algorithm` creates the +command `my-algorithm`. Substitute your own command name below. + +From the generated repository's root, with the `probe` profile declared: + +```bash +uv sync --extra test + +# List the profiles implemented by this repository. +uv run my-algorithm profiles + +# List the commands in the probe lifecycle. +uv run my-algorithm commands --profile probe + +# Register its descriptor in an existing MEDS-DEV checkout. +uv run meds-algorithm-add-to-meds-dev \ + --meds-dev /path/to/MEDS-DEV --name my-algorithm --profile probe +``` + +Replace `/path/to/MEDS-DEV` with your checkout. Registration copies +`algorithms/probe/model.yaml` into MEDS-DEV under `my-algorithm__probe`. +Here `--name my-algorithm` chooses the registration name; it does not rename the executable. +For SLURM, select the profile with `PROFILE=probe`; see [Running an algorithm](running.md) +for input paths, dry runs and execution settings. + +The probe's `infer_embeddings` stage materializes keyed representations without labels. `train_probe` +fits a head on training representations, and `predict_probe` applies it to explicit evaluated embeddings. +Supervised/fine-tuned prediction instead takes `input_data_dir` and the fitted algorithm. Neither dependency +is assumed to disappear just because training recorded its path. + +The [software contract](reference/spec.md#9-software-interfaces) gives every command's arguments, artifact type, label +access, class responsibilities, compatibility checks, and acceptance requirements. See +[migration](migration-v4.md) for an existing repository. diff --git a/docs/prompt-builder.md b/docs/prompt-builder.md new file mode 100644 index 0000000..9f302ee --- /dev/null +++ b/docs/prompt-builder.md @@ -0,0 +1,88 @@ +# Implementation prompt builder + +Prepare instructions for Claude or another coding agent. Choose paper/code sources, a **new local or +GitHub repository**, and automatic or explicit profile selection. Evaluation tasks, if supplied, must +already have **labels and task configs**. This form assembles text locally; it does not read your files, +contact GitHub, upload inputs or run an agent. + +The generated prompt uses the same maintained instructions as the [static workflow prompt](implementation-prompt.md). +You can edit the result before copying. Demo and full-data execution retain their human review gates. + +
+ + +
+
+1. Sources + +
+ +
+
+ +
+
+
+2. New repository + + + +
+
+3. Profiles + +

Automatic selection happens in the implementation agent, before generation. It may select several profiles when the sources support them.

+ +
+
+4. Dataset and prepared tasks + + + +

The prompt does not ask the agent to invent tasks or extract labels. Missing or inconsistent inputs defer only the dependent evaluation.

+
+
+5. Scope and constraints + +

Preparing for full evaluation does not authorize a demo, dataset download or cluster run. The existing review gates still apply.

+ +

Off by default. The agent normally asks before implementing a major unresolved scientific choice, such as unspecified feature construction; routine defaults may proceed with documentation. When enabled, provisional design choices must be recorded and reviewed before claiming faithful reproduction. Leakage, cohort/target definitions, evaluation validity and execution approvals still require resolution.

+ +
+
+
+

Fill in the inputs, then generate your prompt.

+ +
+
diff --git a/docs/publishing-algorithms.md b/docs/publishing-algorithms.md new file mode 100644 index 0000000..84e488a --- /dev/null +++ b/docs/publishing-algorithms.md @@ -0,0 +1,13 @@ +# Publishing an implemented algorithm + +Newly generated repositories include package metadata, a distribution check, a manual publishing +workflow, and their own `RELEASING.md`. Copier asks for `package_name`, `repository_url`, and +`license_expression`; the latter two may remain blank during implementation, but must be completed +before publishing. Licensing remains the algorithm author's choice. + +The guide below is rendered directly from the generated guide with example names, so these instructions +are maintained in one place. For an existing generated repository, use `copier update` and review its +changes, especially existing metadata and CI customizations. The current published generator 0.4.0a2 +predates this support; use the template revision containing this change until the next generator release. + + diff --git a/docs/reference/api.md b/docs/reference/api.md new file mode 100644 index 0000000..25261b0 --- /dev/null +++ b/docs/reference/api.md @@ -0,0 +1,44 @@ +# Contract API + +The [normative software interfaces](spec.md#9-software-interfaces) define the public classes, arguments, +label-access rules and artifact compatibility requirements. Import them directly from `meds_algorithm`. +There is no generated compatibility package. + +| Module | Responsibility | +|---|---| +| `algorithms` | Algorithm/profile ABCs and ordered lifecycles | +| `requests` | Typed per-step inputs and CLI field mappings | +| `configuration`, `serialization` | Algorithm-owned config base, strict versioned JSON round trips | +| `runner` | Shared execution, validation, staging, measurements and publication | +| `contracts.commands` | Derived step specifications and validation | +| `artifacts` | Manifests, publication with rollback, upstream references and run results | +| `runtime` | Explicit algorithm provenance, memory measurement and subprocess execution | +| `data` | Strict split selection, key-only index reads and permitted context targets | +| `tasks.spec` | Task identity and relaxation ledgers | +| `evaluation.predictions` | Keyed probabilities and post-score truth attachment | +| `integrations.meds_dev` | Per-profile registration | +| `conformance` | Reusable assertions, synthetic fixtures and explicitly selected integration tests | + +See the [architecture and UML](architecture.md) for profile inheritance and request/artifact types. +Pass the algorithm checkout as `repo=` to `AlgorithmRepository` or `StepRunner`; unavailable provenance is +recorded as null. Algorithm methods return `PayloadMetadata`, while the runner returns a typed published +artifact. Algorithm methods must not bypass the runner or publish artifacts twice. +Use explicit `splits` for outcome attachment. Install the `data` extra for dataframe helpers and the +`conformance` extra for shared tests. The base package does not import data or algorithm frameworks. + +`meds-algorithm-spec` prints the installed specification. `meds-algorithm-resolve-input +` resolves a recorded upstream path and checks its envelope type; the consumer still +validates scientific compatibility. Core also supplies `meds-algorithm-add-to-meds-dev`. + +Algorithm-owned adapters remain `run_e2e(tmp_path, *, profile, **inputs)`, `fitted_codes(artifacts)`, and +`prepare_meds_dev_run(meds_dev, tmp_path, *, profile)`. The shared lifecycle check reruns the selected +profile with evaluated labels removed and fresh outputs; adapters must honor those input overrides, +record and apply the fixture seed, and produce reproducible keyed scores. Use `read_predictions` from +`conformance.assertions` to validate all shards. For separate context/evaluation directories, supply +`evaluation_index_dir` to `read_context_labels`. `conformance.reports.assert_implementation_report` +validates shared evidence and completed profiles independently of unfinished profiles. + +`conformance.cases.AlgorithmCase` connects those adapters and representative configurations to +`conformance.suite.AlgorithmConformanceTests`. Generated tests inherit the suite, with a session-scoped +`algorithm_case` fixture and a `profile` fixture parametrized from repository registration. See the +[canonical acceptance inventory](tests.md#downstream-acceptance-suite) for each check and its purpose. diff --git a/docs/reference/architecture.md b/docs/reference/architecture.md new file mode 100644 index 0000000..454975a --- /dev/null +++ b/docs/reference/architecture.md @@ -0,0 +1,3 @@ +# Architecture + +This page is rendered from the checkout's canonical ARCHITECTURE.md; do not duplicate the UML here. diff --git a/docs/reference/manifest.md b/docs/reference/manifest.md new file mode 100644 index 0000000..bea4f45 --- /dev/null +++ b/docs/reference/manifest.md @@ -0,0 +1,19 @@ +# Reading artifact manifests + +The [normative manifest schema](spec.md#4-intermediate-artifacts) and +[measurement schema](spec.md#6-measurements) live in the core contract. This page does not duplicate +their field tables. + +When comparing runs, check the producer and payload format, configuration digest, source revision, +input content identities, and task semantics before comparing measurements. A configuration hash alone +does not identify the dataset or weights. A copied path is provenance, not proof of compatibility. + +`null` means not measured or not applicable; zero is an observed value. Sampled live process-tree +memory and scheduler peak memory measure different things. Coverage counts are diagnostics; compare +actual prediction keys with the requested index. + +Core's runner uses `measured_artifact` for publication and measurements. Pass `repo=algorithm_root` explicitly +to identify the algorithm checkout. Overwrite preserves a backup until publication succeeds; a failed +replacement restores it, or reports its recovery path if restoration also fails. New outputs use one +rename; overwrite uses two and can briefly hide the destination. Prefer immutable artifact paths for +concurrent readers. See the [core package](../core-package.md) for implementation ownership and limits. diff --git a/docs/reference/spec.md b/docs/reference/spec.md new file mode 100644 index 0000000..09b6209 --- /dev/null +++ b/docs/reference/spec.md @@ -0,0 +1,6 @@ +# Specification (normative) + +This page includes the same contract source shipped in the core wheel. Generated algorithm repositories +refer to their installed core version rather than copying the specification. + + diff --git a/docs/reference/tests.md b/docs/reference/tests.md new file mode 100644 index 0000000..2de21c4 --- /dev/null +++ b/docs/reference/tests.md @@ -0,0 +1,3 @@ +# Shared-package tests + +This page is rendered from the checkout's packaged test catalogue; do not duplicate its catalogue here. diff --git a/docs/releasing.md b/docs/releasing.md new file mode 100644 index 0000000..2a06adc --- /dev/null +++ b/docs/releasing.md @@ -0,0 +1,4 @@ +For an implemented algorithm repository, follow [Publishing an algorithm](publishing-algorithms.md). +This page is for maintainers releasing the shared core and template generator themselves. + + diff --git a/docs/running.md b/docs/running.md new file mode 100644 index 0000000..8e18c04 --- /dev/null +++ b/docs/running.md @@ -0,0 +1,130 @@ +# Running an algorithm + +A generated repository exposes one command-line entry point, a MEDS-DEV descriptor, and a SLURM +interface. All three run the same commands with the same standard arguments. + +For a copyable sequence from an empty directory to verified predictions, start with the +[fully manual example](manual-example.md). It includes setup, implementation code and synthetic inputs. + + + +## Individual step commands + +Run these commands from the generated repository after `uv sync --extra test`. The examples assume +`algorithm_slug: my_algorithm`, which installs the command `my-algorithm`; replace it with your own +algorithm's command (the slug with underscores changed to hyphens). + +Pass `config_file=/absolute/path/dataset_configs/mimic_iv.yaml` to each lifecycle invocation to select +algorithm settings, including optional `additional_predicates_file`. See [feature additions](concepts.md#additional-feature-predicates-per-dataset). +For MEDS-DEV, add the same `config_file=...` argument to each command in the selected descriptor; use a +path accessible inside its execution environment. MEDS-DEV still supplies the base `{predicates_path}`. +For SLURM, set `ALGORITHM_CONFIG_FILE` to an absolute configuration path; generated `stage_args` passes +it to every selected step. No dataset is inferred from a directory name, and no upstream file is edited. + +```bash +uv run my-algorithm profiles +uv run my-algorithm commands --profile zero_shot_direct +uv run my-algorithm predict_zero_shot_direct --profile zero_shot_direct \ + input_data_dir=runs/x/data input_pretrained_algorithm_dir=runs/x/pretrained \ + external_index_dir=/task/index external_task_criteria_file=/task/criteria.yaml \ + splits=[held_out] output_predictions_dir=runs/x/predictions +``` + +Multiple profiles require explicit selection; a single-profile repository may omit `--profile`. +Arguments are `key=value`; booleans and numeric values are decoded, and `splits=[train,tuning]` is a list. +Inference and prediction require a nonempty explicit split list. Additional algorithm settings must be +validated and included in the resolved configuration digest. See the +[per-step argument table](reference/spec.md#9-software-interfaces). + +Scoring and inference take `external_index_dir` (keys only). Training and optional in-context examples +use `external_labels_dir`. `external_evaluation_labels_dir` is optional and only attaches outcomes after +scores are fixed. The two directories may physically share files; their reader roles remain separate. + +Supervised/fine-tuned prediction requires `input_data_dir`; probe prediction requires +`input_embeddings_dir`. MEDS-DEV resolves recorded upstream paths into explicit CLI arguments with +`meds-algorithm-resolve-input`; SLURM passes the chosen artifact paths directly. + +## MEDS-DEV + +`algorithms//model.yaml` is the [MEDS-DEV](https://github.com/Medical-Event-Data-Standard/MEDS-DEV) descriptor. Its +`unsupervised` / `supervised` × `train` / `predict` slots hold command strings with these template +variables: + +| Variable | Filled by MEDS-DEV with | +|---|---| +| `{dataset_dir}` | the MEDS dataset | +| `{labels_dir}` | the task's labels (the index) | +| `{output_dir}` | this stage's output directory | +| `{model_initialization_dir}` | the previous stage's `{output_dir}` | +| `{split}` | the split to predict (`held_out` in full mode) | +| `{predicates_path}` | the dataset's predicates file (`predicates_path` argument; MEDS-DEV PR #325) | +| `{task_criteria_path}` | the task's ACES criteria: the `task_criteria_path` argument, else the registered criteria file of `task_name` (MEDS-DEV PR #330) | + +Every artifact gets its own subdirectory of the MEDS-DEV run directory: `data/`, `pretrained/`, `algorithm/`, +`embeddings/` or `trajectories/`, `predictions/`. Nothing is written to `{output_dir}` itself, because MEDS-DEV keeps its own +`cmd.sh` and `.done` marker there and artifacts are published by publishing their destination +directory. Artifacts are never nested inside one another, so runs over different indexes or splits cannot +overwrite each other's outputs. + +MEDS-DEV evaluates every `**/*.parquet` under the predictions directory with meds-evaluation 0.0.3, so +every parquet file there must be a predictions file (see the [FAQ](faq.md)). + +Register a completed repository with MEDS-DEV by copying its descriptor into a MEDS-DEV checkout: + +```bash +uv run meds-algorithm-add-to-meds-dev --meds-dev /path/to/MEDS-DEV --name my_algorithm --profile probe +``` + +This registers `algorithms/probe/model.yaml` as `my_algorithm__probe`. Register each desired profile separately. + +The `meds_dev` test tier +provisions MEDS-DEV at a pinned commit that supplies both passthroughs (currently the head of PR #330, which +builds on PR #325); set `MEDS_DEV_REF` to use another revision. A checkout supplied through +`MEDS_DEV_DIR` is capability-checked rather than silently used; only zero-shot repositories require +`{task_criteria_path}`. + +## SLURM + +`slurm/config.sh` is the only SLURM file meant for routine edits: partitions, time limits, CPUs, memory, +GPUs, and `stage_args`, which prints each command's `key=value` arguments from environment variables +(`MEDS_ROOT`, `INDEX_DIR`, `LABELS_DIR`, `TASK_CRITERIA_FILE`, `RUN_DIR`). + +```bash +$EDITOR slurm/config.sh +PROFILE=probe ./slurm/submit.sh --dry-run # prints every sbatch call and each command's arguments; changes nothing +PROFILE=probe ./slurm/submit.sh # submits the profile as dependent jobs +``` + +- `stage_args` covers the declared union; submission validates and lists only the selected profile's commands. +- Each command is one job; later commands depend on earlier ones (`afterok`). `preprocess_data` runs on the + CPU partition, the others on the GPU partition. +- Submission refuses a dirty working tree, so every cluster run corresponds to a commit. `--dry-run` only + warns, so a run can be reviewed before it is committed. +- Artifacts land under `runs///artifacts`. + +## Run results and GitHub sync + +`write_run_result(..., profile="probe")` assembles a run's structured evidence under `runs//`, and + +```bash +scripts/github-sync.sh +``` + +commits exactly these files on a new `runs//` branch, pushes that branch, and opens a draft +PR for it. It changes nothing else. + +| Pushed | Contents | +|---|---| +| `runs//spec.yaml` | the dataset (name and counts as given), the task, and the predicates file's path and digest | +| `runs//result.yaml` | status; git commit and dirty state; environment (host, platform, Python, CPU count, SLURM job id); per-command resource summary | +| `runs//manifests/*.yaml` | a copy of every command's `manifest.yaml` | + +| Never pushed | Why | +|---|---| +| predictions | they are artifacts under `runs///artifacts`, not evidence files | +| labels, datasets | patient data stays where it is | +| checkpoints and other artifact payloads | large and algorithm-owned | +| raw logs, credentials | may contain anything | +| metrics (AUROC, …) | the template computes no metrics; MEDS-DEV's evaluation step (meds-evaluation) does | + +If the push fails, the result stays committed locally on the run branch. diff --git a/docs/shared-package-assessment.md b/docs/shared-package-assessment.md new file mode 100644 index 0000000..e6ef40f --- /dev/null +++ b/docs/shared-package-assessment.md @@ -0,0 +1,42 @@ +# Template and shared package + +The template should generate repository structure, algorithm command stubs, profile descriptors, test +adapters, CI and cluster configuration. Executable infrastructure that needs coordinated bug fixes +belongs in the versioned `meds-algorithm` dependency. The [shared core package](core-package.md) now +contains the reusable template infrastructure and conformance helpers, and owns the canonical +specification. It is available from its public Git repository; downstream migrations remain separate. + +An inspection of 12 local algorithm-repository snapshots found 5,087 lines across their copied contract +modules. Four modules are byte-identical in all 12: `contract.py` (86 lines), `results.py` (76), +`meds_dev.py` (31), and `__init__.py` (16). `manifest.py` has four variants across groups of 5, 3, 2 and 2 +repositories. These are physical source-line counts, not a claim that every line is safely extractable. +The private remotes could not be refreshed during this assessment; conclusions concern the inspected +local `origin/main` snapshots, not verified current remote heads. + +| Destination | Candidates | Qualification | +|---|---|---| +| Core runtime | Profile ABCs, typed requests/configuration, shared runner, manifest schema and compatibility checks, provenance, artifact publication, wall-time and process-tree measurements, structured results, MEDS-DEV registration | Core owns these implementations, including replacement rollback and worker-thread child discovery; downstream algorithms still need migration. Keep GPU/framework integrations optional. | +| Optional conformance package | Prediction schema/key checks, integration provisioning, train-only canaries, generic synthetic signal fixture | `meds_algorithm.conformance.meds_dev` and `meds_algorithm.conformance.signal` are identical in 11 repositories. Keep algorithm execution and feature inspection as adapters. | +| Shared data-boundary helpers | Explicit split selection, label-blind index reading, uniqueness/conflict validation, keyed prediction writing | Existing helpers disagree on duplicate and split behavior. Specify one fail-closed policy before extraction. | +| Family repositories | MOTOR FT/LP backend/provenance utilities; MEDS-Tab large/LR tabularization and runtime; MEDS-EIC-AR and supervised variant tokenization/I/O/runtime | Prefer one repository per family with multiple profiles and shared internal modules; keep algorithms outside the generic core. | +| Template/algorithm repository | Algorithm architectures, objectives, feature semantics, task translators, pooling, trajectory generation, tuned defaults, concrete integration adapters | Their apparent similarity does not make them backend-neutral. | + +Examples of exact family-level copies include MEDS-Tab runtime (159 lines), MOTOR FT/LP provenance +(86 lines), and MEDS-EIC-AR I/O (224 lines). Additional identical functions occur across algorithm families, +including dataset identity and artifact checks. Some dataset-identity helpers hash only paths and file +sizes, which is insufficient to prove content equality. A common implementation must first resolve +that semantic problem rather than preserve it more widely. + +## Update algorithm + +1. Publish the audited runtime with a documented supported contract version and optional test extras. +2. Pilot two structurally different algorithms and test a multi-profile family repository before migrating all. +3. Replace copied contract/runtime modules with pinned package dependencies. Keep the import + namespace stable where possible, and verify installed package discovery cannot select a stale local copy. +4. Use dependency-update PRs in every private algorithm repository to move runtime versions and rerun its + conformance adapters. Use Copier updates for changes to scaffolding and workflow files. +5. Treat contract-major upgrades as explicit migrations, not automatic cross-repository rewrites. + +This avoids maintaining an updater that copies Python implementation files into every algorithm. One +shared-package release makes a fix available everywhere; each repository adopts it through a visible, +tested dependency change. Algorithm implementations retain their own release and scientific-validation gates. diff --git a/docs/template-source.json b/docs/template-source.json new file mode 100644 index 0000000..6d42257 --- /dev/null +++ b/docs/template-source.json @@ -0,0 +1,9 @@ +{ + "revision": "3cf2969d7c15a78e4bf43994ed2121e0aea8ba65", + "files": { + "RELEASING.md": "9e454e07cfb128f45009eeabc689e39dd0ba7ad4fb6605f06e034a695f9c3764", + "TESTING.md": "8d2807417ef0d5c7bd299d2323e67bd65a63d6600b8e761a05ee30b6daf13d92", + "template/RELEASING.md.jinja": "b01983b0cd1bb9f548d8cd6e893fbde4d0229f6caf3f6c9643e5efd4a4f6cea3", + "template/docs/TESTING.md": "7259c80d9b8f40d9d801fd1e45389c012a2a86f3979e3c34aa1623abb0afeb74" + } +} diff --git a/docs/testing.md b/docs/testing.md new file mode 100644 index 0000000..21464b0 --- /dev/null +++ b/docs/testing.md @@ -0,0 +1,10 @@ +# Tests and acceptance + +The following catalogues separate template checks from algorithm acceptance checks. +The [shared acceptance inventory](reference/tests.md#downstream-acceptance-suite) describes the eight +inherited checks. Generated repositories keep only fixture wiring, execution adapters and scientific +tests. See also [Shared-package tests](reference/tests.md) for tests of the runtime and suite itself. + + + + diff --git a/docs/tests/prompt_builder.test.cjs b/docs/tests/prompt_builder.test.cjs new file mode 100644 index 0000000..307272a --- /dev/null +++ b/docs/tests/prompt_builder.test.cjs @@ -0,0 +1,189 @@ +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const path = require("node:path"); +const {test} = require("node:test"); +const {JSDOM} = require("jsdom"); +const {renderPrompt} = require("../assets/prompt-builder.js"); +const root = path.join(__dirname, "../.."); +const read = (name) => fs.readFileSync(path.join(root, name), "utf8").replace(/\r\n/g, "\n"); +const section = read("docs/implementation-prompt.md"); +const template = section.match(/```text\n([\s\S]*?)\n```/)[1]; +const base = { + source_kind: "both", papers: "paper.pdf", code: "https://github.com/example/source @ abc123", + destination_kind: "local", local_path: "/work/new-algorithm", profile_mode: "automatic", + tasks_mode: "none", scope: "local", visibility: "private", profiles: ["finetune", "probe"], + github_repo: "example/new-algorithm", dataset: "Demo dataset v1 at /data/meds", + labels_path: "/data/tasks/labels", configs_path: "/data/tasks/configs", bundle_revision: "tasks-v1" +}; +function browser() { + const html = read("docs/prompt-builder.md").replace("", ``); + const dom = new JSDOM(html, {url: "https://example.test/docs/prompt-builder/", runScripts: "outside-only"}); + dom.window.eval(read("docs/assets/prompt-builder.js")); + dom.window.document.dispatchEvent(new dom.window.Event("DOMContentLoaded")); + const doc = dom.window.document; + const form = doc.querySelector("form"); + const field = (name) => form.elements.namedItem(name); + const set = (name, value) => { field(name).value = value; field(name).dispatchEvent(new dom.window.Event("input", {bubbles: true})); }; + const output = doc.querySelector("[data-prompt-output]"); + return {dom, doc, form, field, set, output}; +} +test("all source, destination, profile, task, scope and ambiguity modes preserve the shared contract", () => { + for (const source_kind of ["paper", "code", "both"]) + for (const destination_kind of ["local", "github"]) + for (const profile_mode of ["automatic", "manual"]) + for (const tasks_mode of ["none", "ready"]) + for (const scope of ["local", "integration", "full"]) + for (const exploratory_mode of [false, true]) { + const prompt = renderPrompt(template, {...base, source_kind, destination_kind, profile_mode, tasks_mode, scope, exploratory_mode}); + assert(!/<[A-Z][A-Z0-9_]*>/.test(prompt)); + assert(prompt.includes("Only after approval, run:")); + assert(prompt.includes("minimalist, auditable, object-oriented")); + assert(prompt.includes("Do not generate new tasks,")); + assert(prompt.includes("In BOTH modes, ambiguities about leakage")); + assert(prompt.includes("Require review of these decisions before claiming faithful reproduction.")); + assert.equal(prompt.includes("Exploratory mode explicitly enabled:"), exploratory_mode); + assert.equal(prompt.includes("Confirmation required (default):"), !exploratory_mode); + assert.equal(prompt.includes("paper.pdf"), source_kind !== "code"); + assert.equal(prompt.includes(base.code), source_kind !== "paper"); + assert.equal(prompt.includes("New GitHub repository:"), destination_kind === "github"); + assert.equal(prompt.includes("Explicit profiles: finetune, probe."), profile_mode === "manual"); + assert.equal(prompt.includes("Prepared labels: /data/tasks/labels"), tasks_mode === "ready"); + } +}); +test("omitted ambiguity mode defaults to confirmation and non-boolean opt-ins are rejected", () => { + assert.equal(renderPrompt(template, base), renderPrompt(template, {...base, exploratory_mode: false})); + assert(renderPrompt(template, base).includes("Confirmation required (default):")); + for (const exploratory_mode of ["false", "true", "on", null, 0, 1]) { + assert.throws(() => renderPrompt(template, {...base, exploratory_mode}), /explicit checkbox/); + } +}); +test("exploratory checkbox is opt-in, invalidates the previous prompt and resets to confirmation", () => { + const {dom, doc, form, field, set, output} = browser(); + try { + const checkbox = field("exploratory_mode"); + assert.equal(checkbox.checked, false); + assert.equal(checkbox.defaultChecked, false); + assert(doc.getElementById(checkbox.getAttribute("aria-describedby"))); + set("papers", base.papers); set("code", base.code); set("local_path", base.local_path); + form.requestSubmit(); + assert(output.value.includes("Confirmation required (default):")); + const original = output.value; + checkbox.click(); + assert.equal(checkbox.checked, true); + assert(doc.querySelector("[data-copy]").disabled && doc.querySelector("[data-download]").disabled); + assert.equal(output.value, original); + form.requestSubmit(); + assert(output.value.includes("Exploratory mode explicitly enabled:")); + assert(!output.value.includes("Confirmation required (default):")); + assert(output.value.includes("Only after approval, run:")); + checkbox.click(); + form.requestSubmit(); + assert.equal(output.value, original); + checkbox.click(); + form.requestSubmit(); + doc.querySelector("[data-reset]").click(); + assert.equal(checkbox.checked, false); + assert.equal(output.value, ""); + } finally { dom.window.close(); } +}); +test("incomplete or invalid plans fail instead of yielding an executable-looking prompt", () => { + for (const bad of [ + {papers: ""}, {code: ""}, {local_path: ""}, {source_kind: "unknown"}, + {profile_mode: "manual", profiles: []}, {profile_mode: "manual", profiles: ["invented"]}, + {destination_kind: "github", github_repo: "https://other.test/owner/repo"}, + {destination_kind: "github", visibility: "internal"}, + {tasks_mode: "ready", dataset: ""}, {tasks_mode: "ready", labels_path: ""}, + {tasks_mode: "ready", configs_path: ""}, {tasks_mode: "ready", bundle_revision: ""} + ]) assert.throws(() => renderPrompt(template, {...base, ...bad})); +}); +test("selected task subsets and literal user text are preserved without recursive substitution", () => { + const literal = ' $&'; + const prompt = renderPrompt(template, {...base, tasks_mode: "ready", task_subset: "mortality_30d", constraints: literal}); + assert(prompt.includes("Task subset: mortality_30d")); + assert(prompt.includes(literal)); + assert(prompt.includes("selects only tasks already present")); +}); +test("the form reveals only relevant required fields and renders multiple profiles", () => { + const {dom, doc, form, field, set, output} = browser(); + try { + set("source_kind", "code"); + assert(field("papers").disabled); + assert(!field("papers").required); + set("code", base.code); + set("local_path", base.local_path); + set("destination_kind", "github"); + assert(field("github_repo").required); + set("github_repo", base.github_repo); + set("profile_mode", "manual"); + form.requestSubmit(); + assert(doc.querySelector("[data-status]").textContent.includes("Select at least one")); + for (const name of ["finetune", "probe"]) doc.querySelector(`[value="${name}"]`).checked = true; + set("tasks_mode", "ready"); + assert(field("dataset").required && field("labels_path").required && field("configs_path").required); + for (const name of ["dataset", "labels_path", "configs_path", "bundle_revision"]) set(name, base[name]); + form.requestSubmit(); + assert(output.value.includes("Explicit profiles: finetune, probe.")); + assert(output.value.includes("visibility: private")); + assert(output.value.includes("Prepared task configs: /data/tasks/configs")); + assert(!doc.querySelector("[data-copy]").disabled); + set("tasks_mode", "none"); + assert(field("labels_path").disabled && !field("dataset").required); + form.requestSubmit(); + assert(!output.value.includes("Prepared labels:")); + } finally { dom.window.close(); } +}); +test("edited output copies and downloads exactly; input changes invalidate it and reset clears it", async () => { + const {dom, doc, form, set, output} = browser(); + try { + set("papers", base.papers); set("code", base.code); set("local_path", base.local_path); + form.requestSubmit(); + const copy = doc.querySelector("[data-copy]"); + const download = doc.querySelector("[data-download]"); + let copied, blob, filename; + Object.defineProperty(dom.window.navigator, "clipboard", {value: {writeText: async (value) => {copied = value;}}}); + dom.window.URL.createObjectURL = (value) => {blob = value; return "blob:test";}; + dom.window.URL.revokeObjectURL = () => {}; + dom.window.HTMLAnchorElement.prototype.click = function () { filename = this.download; }; + output.value += "\nUser edit."; + output.dispatchEvent(new dom.window.Event("input", {bubbles: true})); + copy.click(); await new Promise(setImmediate); + assert.equal(copied, output.value); + download.click(); + const downloaded = await new Promise((resolve) => { const reader = new dom.window.FileReader(); reader.onload = () => resolve(reader.result); reader.readAsText(blob); }); + assert.equal(downloaded, output.value); + assert.equal(filename, "meds-algorithm-implementation.txt"); + const previous = output.value; + set("constraints", "new constraint"); + assert(copy.disabled && download.disabled); + assert.equal(output.value, previous); + form.requestSubmit(); + output.value = ""; output.dispatchEvent(new dom.window.Event("input")); assert(copy.disabled); + output.value = "Restored edit"; output.dispatchEvent(new dom.window.Event("input")); assert(!copy.disabled); + doc.querySelector("[data-reset]").click(); + assert.equal(output.value, ""); assert(copy.disabled && output.readOnly); + } finally { dom.window.close(); } +}); +test("clipboard denial provides a selectable fallback without losing edited content", async () => { + const {dom, doc, form, set, output} = browser(); + try { + set("papers", base.papers); set("code", base.code); set("local_path", base.local_path); + form.requestSubmit(); + Object.defineProperty(dom.window.navigator, "clipboard", {value: {writeText: async () => {throw new Error("denied");}}}); + doc.querySelector("[data-copy]").click(); await new Promise(setImmediate); + assert(doc.querySelector("[data-status]").textContent.includes("Ctrl+C")); + assert.equal(output.selectionStart, 0); assert.equal(output.selectionEnd, output.value.length); + } finally { dom.window.close(); } +}); +test("HTML-like references remain inert text and repeated initialization preserves edits", () => { + const {dom, doc, form, set, output} = browser(); + try { + const hostile = ''; + set("papers", hostile); set("code", base.code); set("local_path", base.local_path); + form.requestSubmit(); + assert(output.value.includes(hostile)); assert.equal(doc.querySelector("img"), null); + assert.equal(dom.window.injected, undefined); + output.value = "My edited prompt"; + doc.dispatchEvent(new dom.window.Event("DOMContentLoaded")); + assert.equal(output.value, "My edited prompt"); + } finally { dom.window.close(); } +}); diff --git a/docs/tests/test_hooks.py b/docs/tests/test_hooks.py new file mode 100644 index 0000000..46ed6f6 --- /dev/null +++ b/docs/tests/test_hooks.py @@ -0,0 +1,133 @@ +"""Documentation sources remain canonical, pinned and inert in browser HTML.""" + +import hashlib +import importlib.util +import io +import json +import re +from pathlib import Path +from types import SimpleNamespace + +import pytest + +ROOT = Path(__file__).resolve().parents[2] + + +def load_hooks(): + spec = importlib.util.spec_from_file_location("docs_hooks", ROOT / "docs/hooks.py") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def page(name): + return SimpleNamespace(file=SimpleNamespace(src_uri=name)) + + +def test_prompt_builder_embeds_the_canonical_prompt(): + hooks = load_hooks() + result = hooks.on_page_markdown((ROOT / "docs/prompt-builder.md").read_text(), page("prompt-builder.md")) + payload = re.search(r"data-prompt-template>(.*?)", result, re.DOTALL).group(1) + document = (ROOT / "docs/implementation-prompt.md").read_text() + expected = re.search(r"```text\n(.*?)\n```", document, re.DOTALL).group(1) + assert json.loads(payload) == expected + assert "" not in result + + +def test_algorithm_release_guide_renders_template_source(monkeypatch): + hooks = load_hooks() + monkeypatch.setattr(hooks._TemplateGuides, "read", lambda self, name: "Release {{ package_name }}") + result = hooks.on_page_markdown("", page("publishing-algorithms.md")) + assert "Release my-algorithm" in result + assert "Template source version" in result + assert "{{" not in result + + +def test_prompt_source_cannot_close_its_json_script_element(tmp_path, monkeypatch): + hooks = load_hooks() + monkeypatch.setattr(hooks, "__file__", str(tmp_path / "docs/hooks.py")) + prompt = '' + (tmp_path / "docs").mkdir() + (tmp_path / "docs/implementation-prompt.md").write_text("```text\n" + prompt + "\n```\n") + result = hooks.on_page_markdown("", page("prompt-builder.md")) + assert result.count("") == 1 + assert json.loads(result.split("data-prompt-template>", 1)[1].split("", 1)[0]) == prompt + + +@pytest.mark.parametrize( + ("name", "source"), + [ + ("reference/spec.md", "src/meds_algorithm/CONTRACT.md"), + ("reference/architecture.md", "ARCHITECTURE.md"), + ("reference/tests.md", "src/meds_algorithm/TESTING.md"), + ("running.md", "src/meds_algorithm/ORCHESTRATION.md"), + ], +) +def test_core_references_use_this_checkout(name, source): + hooks = load_hooks() + expected = ( + (ROOT / source).read_text(encoding="utf-8").replace("(src/meds_algorithm/CONTRACT.md)", "(spec.md)") + ) + result = hooks.on_page_markdown("", page(name)) + assert expected in result + + +def source_manifest(root, content=b"guide", revision="a" * 40): + (root / "docs").mkdir() + (root / "docs/template-source.json").write_text( + json.dumps( + { + "revision": revision, + "files": {"TESTING.md": hashlib.sha256(content).hexdigest()}, + } + ) + ) + + +def test_template_guides_fetch_immutable_source_and_reuse_verified_cache(tmp_path, monkeypatch): + hooks = load_hooks() + source_manifest(tmp_path) + requests = [] + + def fetch(url, timeout): + requests.append((url, timeout)) + return io.BytesIO(b"guide") + + monkeypatch.setattr(hooks, "urlopen", fetch) + guides = hooks._TemplateGuides(tmp_path) + assert guides.read("TESTING.md") == "guide" + assert guides.read("TESTING.md") == "guide" + assert len(requests) == 1 + assert "/" + "a" * 40 + "/TESTING.md" in requests[0][0] + assert requests[0][1] == 30 + + +@pytest.mark.parametrize("cached", [False, True]) +def test_template_guide_corruption_fails_closed(tmp_path, monkeypatch, cached): + hooks = load_hooks() + source_manifest(tmp_path) + if cached: + cache = tmp_path / ".cache/template-docs" / ("a" * 40) / "TESTING.md" + cache.parent.mkdir(parents=True) + cache.write_bytes(b"changed") + monkeypatch.setattr(hooks, "urlopen", lambda *args, **kwargs: io.BytesIO(b"changed")) + with pytest.raises(ValueError, match="checksum mismatch"): + hooks._TemplateGuides(tmp_path).read("TESTING.md") + + +def test_template_source_requires_immutable_revision(tmp_path): + source_manifest(tmp_path, revision="main") + with pytest.raises(ValueError, match="full commit SHA"): + load_hooks()._TemplateGuides(tmp_path) + + +def test_template_download_failure_does_not_silently_change_source(tmp_path, monkeypatch): + hooks = load_hooks() + source_manifest(tmp_path) + + def unavailable(*args, **kwargs): + raise OSError("Source unavailable") + + monkeypatch.setattr(hooks, "urlopen", unavailable) + with pytest.raises(OSError, match="Source unavailable"): + hooks._TemplateGuides(tmp_path).read("TESTING.md") diff --git a/docs/workflow.md b/docs/workflow.md new file mode 100644 index 0000000..ff710ae --- /dev/null +++ b/docs/workflow.md @@ -0,0 +1,149 @@ +# Workflow: from render to full-data run + +A port moves through a fixed sequence of gates. Each automated gate must pass before the next starts, with +human reviews before the demo and before full-data execution. The generated repository's +`docs/IMPLEMENTATION_GUIDE.md` is the authority for the ordered gates and their evidence; this page explains +what each gate is for. + +```mermaid +flowchart TD + r[1. Supply sources and choose profiles
manually or through the agent] --> i[2. Agent: implement commands,
tests/e2e.py, model.yaml, slurm/config.sh] + i --> g1[3. Agent: local gate
uv run pytest -rs] + g1 --> g2[4. Agent: MEDS-DEV gate
uv run pytest -m meds_dev -rs] + g2 --> h1{{5. Pre-demo human review
source fidelity, predicates, demo plan}} + h1 --> g3[6. MIMIC-IV demo gate
uv run pytest -m real_data -rs] + g3 --> h2{{7. Demo human review
target dataset, task bundle, resources}} + h2 --> c[8. Commit and push
clean tree, immutable SHA] + c --> f[9. Full-data run via SLURM
shared reviewed task bundle] + f --> rep[10. Final report +
scripts/github-sync.sh RUN_ID] +``` + +## 1. Render + +The [implementation prompt builder](prompt-builder.md) can ask the agent to create a **new local or +GitHub repository**. Supply paper/code references, choose profiles automatically or explicitly, and +optionally identify an already prepared task bundle with labels and configs. The agent inspects sources +and selects profiles before rendering. To render manually instead: + +```bash +uv tool install copier +copier copy --trust https://github.com/McDermottHealthAI/MEDS_algorithm_template ../my-meds-algorithm +``` + +Copier asks for the algorithm name and slug, the **profiles**, whether MEDS-DEV commands should pass +predicates, and the implementation source (paper and/or repository). The answers are recorded in +`.copier-answers.yml`, so `copier update` can bring later template changes in. + +The generated commands are deliberately stubs: `STUB_PROFILES = set(PROFILES)` in `src//.py` makes the +end-to-end tests skip with an explicit `algorithm_stub` reason until the real algorithm runs. + +## 2. Implement + +### Using an agent for automated implementation + +Use the [implementation prompt builder](prompt-builder.md) to prepare input for a coding agent such +as Claude. The prompt supports paper references, code/repositories, or both. Its destination is a new +local repository or a new GitHub repository with an explicit local checkout and visibility. +Automatic profile selection must follow source evidence; manual selection may include several profiles. +The agent records the choice before generation, then implements every selected profile. + +By default, the agent asks for confirmation before implementing a material unresolved scientific choice +(for example, unspecified featurization). Routine defaults such as a missing learning rate may proceed +with a documented rationale unless central to the paper's claim. The builder's **Exploratory mode** +checkbox is unchecked by default: enabling it permits provisional design assumptions, which must be +recorded and reviewed before claiming faithful reproduction. In both modes, unresolved leakage, +cohort/target definitions or evaluation validity block dependent work. Independent work can continue. + +Evaluation tasks, when supplied, are already ready: labels plus task configs, bundle identity and dataset +context. The builder does not ask the agent to invent tasks or extract new labels. Missing tasks defer +only the corresponding evaluation. Choose the intended work scope explicitly; demo and full-data runs +still require their existing human approvals. The [static prompt](#copyable-algorithm-implementation-prompt) +below is the same maintained source used by the builder. + +The template supplies instructions, interfaces and executable checks. It does **not** launch an agent +or run an unattended implementation service. The prompt works as ordinary agent input and includes +the Ponytail implementation principles; installing a separate agent plugin is not required. + +| Stage | Agent's work | Human's responsibility | +|---|---|---| +| Handoff | Read `AGENTS.md`, `SPEC.md`, `README.md` and `docs/IMPLEMENTATION_GUIDE.md`; inspect the paper, source code and configurations; identify missing evidence. | Supply the intended source, profiles and dataset context; resolve scientific choices the source leaves ambiguous. | +| Implementation | Implement the algorithm and every declared profile's commands, descriptors, fixture adapter and primary-behavior tests. Reuse `meds-algorithm` for shared contract behavior. Record source fidelity and deviations in `IMPLEMENTATION_REPORT.md`. | Resolve missing inputs or consequential departures from the source when the agent raises them. | +| Automated verification | Run the local and MEDS-DEV gates, inspect failures, fix their causes and rerun the affected checks. Report exact commands, results, skips and remaining limitations. | Review the evidence, source fidelity, predicates and demo plan at the pre-demo gate. | +| Approved demo | After approval, run the MIMIC-IV demo gate and report execution, coverage and resource evidence. | Review the demo results and approve the full dataset, task bundle, access and resource plan separately. | +| Approved full run | Commit and push the completed implementation, run the approved SLURM job from its immutable commit, and prepare the final report and permitted structured run evidence. | Assess the scientific results and review the implementation and run evidence before merging. | + +Within the implementation and verification stages, the agent should continue the edit–test–inspect +cycle without asking for approval for each routine change. It must surface missing source material, +credentials or task bundles as blockers, and wait at the two human review gates before the corresponding +data run. If work spans several sessions, the next agent reads the repository's implementation report +and recorded evidence, identifies the last completed gate, and resumes there. Approval must be explicit; +a passing test or an agent-written report does not grant it. + +Tests must exercise the real algorithm behavior, including negative controls. The agent must not make a gate +pass by weakening checks, substituting fixture-only behavior, or hiding an unfinished profile with a +stub skip. Passing automated checks establishes the properties listed below; it does not independently +establish fidelity to the paper or scientific validity. Keep the detailed instructions in the shared +prompt and generated implementation guide rather than maintaining a separate prompt for each agent. + +### Typed implementation and audit trail + +The generated algorithm owns its named class and frozen configuration (for example, `RETAIN` and +`RETAINConfig` in the `retain` package). Profile ABCs require its +methods; typed request objects carry artifact references and permitted inputs. The shared runner owns +validation, measurement, staging, metadata and publication. Agents should implement cohesive algorithm +components with explicit dependencies, without mutable global runtime state, unnecessary wrappers or +copies of core utilities. Test config/request serialization and execution in a fresh process. See the +[shared architecture and UML](reference/architecture.md) for the implemented design. + +### Implementation deliverables + +Implement every command in the union of declared profiles, `tests/e2e.py`, `algorithms//model.yaml`, and `slurm/config.sh`. In +`tests/e2e.py`, `run_e2e` runs the real profile on a small fixture to which it applies +`meds_algorithm.conformance.signal.add_split_canaries`, and returns the artifacts, the evaluated index and splits, the exact +external inputs, deterministic fixture seed and the canaries; `fitted_codes` reports every code the algorithm fitted a population +statistic for; `prepare_meds_dev_run` configures the MEDS-DEV run. Complete `tests/test_primary_behavior.py`, +which fails on purpose until it shows the algorithm's claimed behavior on a known signal, with a negative +control. Record every source element as ported, adapted or omitted in `IMPLEMENTATION_REPORT.md`. + +## What each gate proves + +| Gate | Proves | Does not prove | +|---|---|---| +| **Local** (`pytest -rs`) | the contract holds (command registry, manifests and `config_digest`, publication and rollback, measurements, key coverage, prediction schema), the real profile runs end to end on a synthetic fixture with no evaluated-split label read across a fresh full-lifecycle rerun (no label at all for zero-shot) and no statistic fitted on tuning or held-out subjects, and the primary behavior appears | anything about real data | +| **MEDS-DEV** (`-m meds_dev`) | the package installs in MEDS-DEV's isolated environment and the `algorithms//model.yaml` command strings run | scale or real-data behavior | +| **Pre-demo review** (human) | the port is faithful to the source, predicates are interpreted correctly, the demo plan is sound | — | +| **MIMIC-IV demo** (`-m real_data`) | the pipeline survives real data: serialization, scale transitions, resources, key coverage on MEDS-DEV's `mortality/in_icu/first_24h` with MEDS-DEV's MIMIC-IV predicates | **algorithm quality**: the demo validates execution only (its held-out split is tiny and may have no positives) | +| **Demo review** (human) | the evidence is sufficient; target-dataset, task and predicate compatibility; access and resources for the full run | — | +| **Full data** (SLURM) | the scientific result on the shared task bundle | — | + +A plain `pytest` run never clones MEDS-DEV or downloads data: the `meds_dev` and `real_data` tiers are +opt-in markers. Set `MEDS_DEV_DIR` to reuse a MEDS-DEV checkout and `MEDS_DEMO_DIR` to reuse a built +demo. + +## The full-data run + +- The cluster runs an **immutable commit** from a clean checkout: `slurm/submit.sh` refuses to submit from + a dirty tree. +- The tasks come from a shared, reviewed task bundle for the target dataset, built once upstream: clinical tasks defined and extracted with [ACES](https://eventstreamaces.readthedocs.io/), or randomly sampled code-by-horizon tasks (generated with [meds-random-task-sampler](https://github.com/florian6973/meds-random-task-sampler) and selected with [meds-task-selection](https://github.com/florian6973/meds-task-selection)), containing each task's definition and its per-task index and labels. Zero-shot runs additionally need each task's ACES criteria. + Every algorithm compared on a dataset uses the same bundle, and the bundle stays outside Git. +- Record the dataset name and revision, predicate provenance, bundle location, the commit of the tool that built the bundle, + a digest of its task definitions, algorithm commit, configuration and job IDs. + +## Reporting results + +`scripts/github-sync.sh ` pushes only the run's structured evidence (`spec.yaml`, `result.yaml` and +the command manifests) on a `runs//` branch and opens a draft PR. Predictions, labels, data, +checkpoints, raw logs and metrics are never pushed; metrics come from MEDS-DEV's evaluation step. See +[Running an algorithm](running.md#run-results-and-github-sync) for the exact list. + +The [copyable implementation prompt](implementation-prompt.md) and the +[interactive prompt builder](prompt-builder.md) use the same maintained instructions. + + + +## Optional profile-runner prototype + +After implementation and the required review gates, the [profile runner](running.md#profile-runner-prototype) +can orchestrate local or SLURM execution from `configs/runs/run.yaml`. Start with `--dry-run` to inspect +all step arguments and resources. It changes how steps are launched; it does not bypass acceptance tests, +source-fidelity reviews or dataset/cluster approvals. Per-step commands remain the MEDS-DEV interface. diff --git a/docs/zero-shot.md b/docs/zero-shot.md new file mode 100644 index 0000000..04c23c0 --- /dev/null +++ b/docs/zero-shot.md @@ -0,0 +1,202 @@ +# Zero-shot in practice + +A zero-shot algorithm answers a downstream task without fitting on that task's labels. This guide explains +the two [zero-shot profiles](profiles.md), task translation, and how to read their results. +The core contract owns the normative [task interface](reference/spec.md#24-task-specification-zero-shot-profiles), +[prediction requirements](reference/spec.md#31-zero-shot-prediction), and +[per-command arguments](reference/spec.md#step-arguments-and-artifacts). Examples here illustrate those rules. + +## Who builds what + +| Product | Owner | +|---|---| +| Cohort, prediction index and evaluation labels | Upstream task extraction, shared across algorithms | +| Algorithm query and any task approximations | The algorithm's task adapter | +| Probabilities for the supplied index | The algorithm's prediction command | + +The task definition tells the algorithm what to predict for the supplied rows. It is not permission to +rebuild the cohort: doing so could change the population being compared or expose evaluation labels. + +## What a zero-shot algorithm receives + +```mermaid +flowchart LR + crit[ACES criteria
external_task_criteria_file] --> pr + pred[Dataset predicates
external_predicates_file] --> pr + idx[(Index
external_index_dir)] -- keys only --> pr + data[(MEDS data /
algorithm's own artifacts)] --> pr + pr[zero-shot prediction command] --> out[(predictions.parquet)] + pr --> led[relaxations.yaml] +``` + +| Input | Why | +|---|---| +| The **ACES task** (criteria + predicates) | without labels, this is the only way to know *what* to predict | +| The **index**, keys only | the rows to predict, built upstream; read with `read_index`, which never loads a label column | +| The algorithm's artifacts (and, for materialized algorithms, the raw MEDS dataset) | the history to predict from | + +The task is the *original* task; adapting it to what the algorithm can answer is the algorithm's job. +The [MEDS-DEV integration](#meds-dev-integration) must supply it as `{task_criteria_path}`. + +Criteria and predicates jointly identify a task. Criteria can leave dataset-specific event codes open; +the predicates file supplies those bindings. Changing the bindings changes the task's meaning, even +when its criteria are unchanged. The task semantics digest therefore covers both files. + +## Direct queries or generated trajectories + +| | `zero_shot_direct` | `zero_shot_materialized` | +|---|---|---| +| Algorithm behavior | Answers a query, such as a hazard or code-in-window probability | Generates possible futures | +| Typical example | A time-to-event or code-query algorithm | An autoregressive EHR generator | +| Prediction | Translates the task into a query, then decodes algorithm outputs | Evaluates the task on history plus generated futures | +| Main approximation to inspect | Query expressiveness and decoding assumptions | Sampling, truncation and generation policies | + +Only the prediction command is task-conditioned. In `zero_shot_materialized`, `infer_trajectories` never receives +the task and records `semantics_digest: null`. Reuse across tasks still requires compatible history, +index, generation settings, and sufficient trajectory coverage for the requested windows. + +For a direct algorithm, an encode → algorithm → decode adapter is a useful internal design: encode the task +into a supported query, run the algorithm, and decode keyed probabilities. Keep query and decoding evidence +with the predictions so reviewers can inspect what was answered. These internal class boundaries and +the `ZeroShotTranslator` sketch in the generated implementation guide are recommendations, not a +required framework. Neither the template nor core requires an aces-relaxations dependency. + +The core reader projects key columns at I/O, but using that helper alone does not establish that the +whole algorithm is label-blind. Conformance must cover the preceding stages and any other reads, with +controlled randomness when comparing sampling-based runs; see [conformance](reference/spec.md#8-conformance). + +## Relaxations: what the algorithm actually answered + +Most algorithms cannot answer an arbitrary ACES task exactly. A time-to-event algorithm cannot express +"no discharge in the next 24h *and then* death before ICU discharge"; a code-in-window algorithm cannot express +"sodium below 135" when its vocabulary only has decile bins. They answer a **related** question. The +`relaxations.yaml` ledger states which one, so a reader can separate *algorithm error* from *relaxation error*. + +```yaml +query_language: MOTOR first-occurrence time-to-event over task-head codes # required +decoded_quantity: P(any of {MEDS_DEATH} first occurs before the first of {ICU_DISCHARGE, MEDS_DEATH}) # required +exact: false # required +steps: # free-form, recommended + - {name: normalize, kind: label_preserving, direction: exact, detail: re-rooted at the prediction time} + - {name: label_only, kind: algorithm_assumption, direction: unknown, detail: dropped 2 criteria branches} +``` + +`exact: true` claims that the decoded quantity *is* the requested label's probability under the algorithm. The +recommended step vocabulary separates three kinds of difference: + +| `kind` | Where it comes from | Effect on labels | Typical `direction` | +|---|---|---|---| +| `label_preserving` | a rewrite proven not to change any label on cohort rows (`normalize`, `require_bounding_events`, re-anchoring) | none | `exact` | +| `approximation` | a task rewrite with a known effect (`simplify_constraints`, `last_link_target`, a value threshold mapped onto bins) | changes labels in a stated direction | `weakening` (more positives) or `strengthening` (fewer) | +| `algorithm_assumption` | what the query language forces (vocabulary restriction, dropping criteria, independence between codes) | depends on the data | usually `unknown` | + +Rules: an algorithm **must not** omit a step because it is expected to be small, and it **must raise** rather +than answer a task it cannot pose — the command fails and writes no predictions. + +Two cases deserve particular scrutiny: a criterion sharing codes with the label cannot simply be +assumed independent of it, and a same-timestamp conjunction is not equivalent to both codes occurring +somewhere in a window. Record such substitutions explicitly rather than hiding them in decoding. + +### What ledgers look like for three kinds of algorithm + +Illustrative ledgers for MEDS-DEV's `mortality/in_icu/first_24h` and an abnormal-lab task. They show what a +reader should expect from each kind of algorithm, not values to copy. + +#### Code-in-window query algorithm (direct) + +For example EveryQuery. Its windows can start after a delay or at an event and end at a duration or a +bound event, so much of the task maps exactly. The algorithm is asked *P(death in (t₀ + 1 day, next ICU +discharge) | no ICU discharge, death or ICU admission in the first day)*. `exact: false`. + +| Step | Kind | Direction | +|---|---|---| +| re-anchor the trigger-rooted `gap` window on the prediction time | label_preserving | exact | +| normalize | label_preserving | exact | +| remove death from the window's end event (`discharge_or_death`) | approximation | exact except on timestamp ties (strengthening) | +| criteria that hold on every cohort row, given to the algorithm as answered conditions | label_preserving | exact | +| a criterion spanning several codes, which cannot be given as a condition, dropped | algorithm_assumption | unknown | + +#### Time-to-event algorithm (direct) + +For example MOTOR. The algorithm has hazards for a fixed vocabulary of codes, so predicates are restricted +to that vocabulary and criteria branches are dropped. On an abnormal-lab task such as hyponatremia, the +`< 135 mEq/L` threshold cannot be expressed over codes without values and the "measured at least once" +criterion is dropped, so the decoded quantity becomes *P(any sodium measurement in the next 24h)*. + +| Step | Kind | Direction | +|---|---|---| +| require_bounding_events, normalize | label_preserving | exact | +| vocabulary restriction (value bounds dropped) | algorithm_assumption | weakening | +| drop criteria branches | algorithm_assumption | unknown | +| single label window promoted to the prediction time (time-to-event stationarity) | approximation / algorithm_assumption | unknown unless exact | +| decode `and`/`or` under independence | algorithm_assumption | unknown | + +#### Autoregressive generator (materialized) + +For example MEDS-EIC-AR. The task is evaluated as written on real history plus each sampled future, so +the only intrinsic step is the Monte Carlo estimate. Effects that change the answer are recorded when +they happen: samples that end before the task resolves (ACES would count them as negatives), generated +events that land before the prediction time, samples that violate a future criterion (rejecting them +estimates *P(label | criteria hold)*), and rows with no usable sample (handled by a declared policy that +lists their keys). + +## Windows that straddle the prediction time + +Many MEDS-DEV tasks anchor their windows at the **trigger** (e.g. ICU admission), not at the prediction +time. In `mortality/in_icu/first_24h`, the prediction time is `trigger + 24h`, but the `gap` window spans +`(trigger, trigger + 48h]` and the label window hangs off its end: + +```text +trigger +├── (+1 day) input.end ← prediction time +└── (+2 days) gap.end (no ICU admission, discharge or death) + └── (next discharge or death) target.end ← label: death +``` + +The first half of `gap` is past history (already enforced when the cohort was extracted); the second half +is a real condition on the future. A structural future-only check can reject this layout; a rewrite +that treats the whole window as past can instead discard its future condition. Test both cases against +the adapter's pinned task-library revision, including analogous `no_discharge` windows in lab tasks. + +The fix is a **re-anchoring** step: a trigger-rooted window ending at `trigger + L` with `L > Δ` (where the +prediction time is `trigger + Δ`) becomes `(prediction time, prediction time + (L − Δ)]`; "never" +constraints can be retained over the remaining future interval. Other constraints require individual +analysis: the past portion may already satisfy them, but removing a remaining future requirement would +change the task. Claim label preservation only after checking the rewrite on the same cohort keys. +Generic, proven rewrites belong in the task library; algorithm-specific assumptions belong in the adapter. +Materialized algorithms can evaluate the original task on real history plus generated futures. + +## Adapters are algorithm-specific + +Translating an ACES task into an algorithm's query language is algorithm-specific, so it lives with the algorithm, not +in the template: + +- **Task rewriting library**, such as aces-relaxations: provides structural checks and rewrites with + documented semantic effects. Verify the available API and guarantees at the pinned revision. +- **aces-to-<algorithm>** (algorithm-specific): chooses which rewrites and assumptions the query language + forces, runs the algorithm, decodes probabilities, and writes the ledger. aces-to-motor (for MOTOR) is one + example. + +Pin aces-relaxations to an exact version or commit in the algorithm repository; the template does not depend +on it. + +## MEDS-DEV integration + +Each zero-shot descriptor in `algorithms//model.yaml` uses `{task_criteria_path}` and +`{predicates_path}`. The MEDS-DEV revision used to execute it must support these placeholders and pass +the original task definition, not an algorithm-specific relaxation. Check that capability before launching +the run; the template's integration helper records the revision used by its tests. + +`{labels_dir}` can also supply `external_index_dir`: the algorithm reads only its key columns for scoring. +This does not require generating a second physical dataset. The evaluation-only truth join happens +after scores are fixed, as specified in the [core contract](reference/spec.md#step-arguments-and-artifacts). +For SLURM, supply `TASK_CRITERIA_FILE` and the task predicate binding through the generated configuration; +see [running an algorithm](running.md). + +## Reading zero-shot results + +- Predictions are scored against the **requested** task's labels; the relaxation is part of the algorithm. +- Compare algorithms on the same task with their ledgers side by side: an algorithm that answers an easier, + relaxed question can look better or worse for reasons unrelated to its quality. +- A useful extra analysis for direct algorithms: extract the *relaxed* task's labels with + `aces_relaxations.extract_at` on the same index and report performance against both label sets. diff --git a/mkdocs.yml b/mkdocs.yml index d039559..594cdda 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -1,32 +1,100 @@ site_name: MEDS algorithms -site_description: Shared MEDS algorithm infrastructure and implementation catalogue. site_url: !ENV [READTHEDOCS_CANONICAL_URL, "https://meds-algorithm.readthedocs.io/en/latest/"] +site_description: >- + A contract for MEDS algorithm repositories: MEDS data and a task in, MEDS predictions out, with every step + measured and reproducible. repo_url: https://github.com/McDermottHealthAI/meds-algorithm repo_name: McDermottHealthAI/meds-algorithm edit_uri: edit/main/docs/ -docs_dir: docs -strict: true hooks: + - docs/hooks.py - docs/catalogue.py + +extra_css: + - assets/prompt-builder.css +extra_javascript: + - assets/prompt-builder.js + +docs_dir: docs +strict: true +validation: + nav: + omitted_files: warn + not_found: warn + links: + not_found: warn + anchors: warn + absolute_links: info + unrecognized_links: warn + theme: name: material features: - navigation.sections + - navigation.top + - navigation.footer - content.code.copy + - search.highlight + palette: + - media: "(prefers-color-scheme: light)" + scheme: default + toggle: + icon: material/brightness-7 + name: Switch to dark mode + - media: "(prefers-color-scheme: dark)" + scheme: slate + toggle: + icon: material/brightness-4 + name: Switch to light mode + markdown_extensions: + - admonition + - attr_list + - def_list + - footnotes - tables - toc: permalink: true - - pymdownx.superfences -validation: - nav: - omitted_files: warn - not_found: warn - links: - not_found: warn - anchors: warn + - pymdownx.details + - pymdownx.highlight + - pymdownx.inlinehilite + - pymdownx.snippets: + base_path: ["."] + check_paths: true + - pymdownx.superfences: + custom_fences: + - name: mermaid + class: mermaid + format: !!python/name:pymdownx.superfences.fence_code_format + nav: - - Overview: index.md - - Implemented algorithms: implemented-algorithms.md + - Getting started: + - Overview: index.md + - Implemented algorithms: implemented-algorithms.md + - Concepts: concepts.md + - Choosing a profile: profiles.md + - Workflow: workflow.md + - Building an algorithm: + - Implementation prompt builder: prompt-builder.md + - Copyable implementation prompt: implementation-prompt.md + - Running an algorithm: running.md + - Fully manual example: manual-example.md - Development: + - Core package layout: core-package.md + - Template and shared package: shared-package-assessment.md + - Migrating to version 4: migration-v4.md + - Publishing an algorithm: publishing-algorithms.md + - Releasing core and template: releasing.md + - Maintaining documentation: documentation.md + - Documentation tests: documentation-tests.md - Catalogue tests: catalogue-testing.md + - Zero-shot algorithms: + - Zero-shot in practice: zero-shot.md + - Reference: + - Specification (normative): reference/spec.md + - Manifest fields: reference/manifest.md + - Contract API: reference/api.md + - Architecture and UML: reference/architecture.md + - Tests and acceptance: testing.md + - Shared-package tests: reference/tests.md + - FAQ: faq.md diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..c9951be --- /dev/null +++ b/package-lock.json @@ -0,0 +1,532 @@ +{ + "name": "meds-algorithm-docs-tests", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "meds-algorithm-docs-tests", + "devDependencies": { + "jsdom": "^30.1.3" + }, + "engines": { + "node": ">=24" + } + }, + "node_modules/@asamuzakjp/css-color": { + "version": "7.1.9", + "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-7.1.9.tgz", + "integrity": "sha512-vZ6JQVq8Ivgz6b/IBlAf90wZviXdluY13cQOPO+nJHbmXwGrPl2GcpqUY7a55/8ZVdfONXpCFMpRijOBCHNlcQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@csstools/css-calc": "^3.4.3", + "@csstools/css-color-parser": "^4.2.6", + "@csstools/css-parser-algorithms": "^4.0.2", + "@csstools/css-tokenizer": "^4.0.2", + "lru-cache": "^11.5.3" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/@asamuzakjp/dom-selector": { + "version": "10.0.5", + "resolved": "https://registry.npmjs.org/@asamuzakjp/dom-selector/-/dom-selector-10.0.5.tgz", + "integrity": "sha512-EgmJ7oEaGQECTn3H3wmnQpEy4hKY66VvM7VQndwPIQob3p877BgbyOUE3EX0LgXQCciF2H8KMdR+RznqjMNOLw==", + "dev": true, + "license": "MIT", + "dependencies": { + "bidi-js": "^1.1.0", + "css-tree": "^3.2.1", + "is-potential-custom-element-name": "^1.0.1", + "lru-cache": "^11.5.3" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/@bramus/specificity": { + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/@bramus/specificity/-/specificity-2.4.3.tgz", + "integrity": "sha512-0GEz8qJWokkUVYQYRukmkSHIFNoBH8QTreeHrAFbvz1XFYc3Y+puhMs8PQ5x8GNugiC2l5jvDBXKLbBIByeSBw==", + "dev": true, + "license": "MIT", + "dependencies": { + "css-tree": "^3.2.1" + }, + "bin": { + "specificity": "bin/cli.js" + } + }, + "node_modules/@csstools/color-helpers": { + "version": "6.1.2", + "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-6.1.2.tgz", + "integrity": "sha512-grhRy3OKmniaAEKXMjua5z/EODX0MSqBGjunw8+j/3HQjOnahs2AGhvEOIYVUWcU6ScApbhLhVrQTX8XqrMrow==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "engines": { + "node": ">=20.19.0" + } + }, + "node_modules/@csstools/css-calc": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-3.4.3.tgz", + "integrity": "sha512-iex20d8CHVkyvg6B7UKV7uHnI2Bqo9g+EFfT9E0y+GvTvhZ/DwONJ+9aKb1dlqm0ZiGsL5RXjp0fCoJYnkeDjA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=20.19.0" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^4.0.2", + "@csstools/css-tokenizer": "^4.0.2" + } + }, + "node_modules/@csstools/css-color-parser": { + "version": "4.2.7", + "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-4.2.7.tgz", + "integrity": "sha512-zgm9yjQz5iJB4VL8RyVwd71TWB8Q89FSxt/NzXoWqPSkEBOVtn9L6vAPtSc9hpKfB0Awo/AL2VKFHjYetBLFHQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "dependencies": { + "@csstools/color-helpers": "^6.1.2", + "@csstools/css-calc": "^3.4.3" + }, + "engines": { + "node": ">=20.19.0" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^4.0.2", + "@csstools/css-tokenizer": "^4.0.2" + } + }, + "node_modules/@csstools/css-parser-algorithms": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-4.0.2.tgz", + "integrity": "sha512-40cSKyMvK+tq4qz6Awrlye2WGuOKt3FwPgtGg6KTfbHOWNw+Rk1rzbAtZnZ6IBhsY491HLRnDXwoyBAijmmILA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=20.19.0" + }, + "peerDependencies": { + "@csstools/css-tokenizer": "^4.0.2" + } + }, + "node_modules/@csstools/css-syntax-patches-for-csstree": { + "version": "1.1.16", + "resolved": "https://registry.npmjs.org/@csstools/css-syntax-patches-for-csstree/-/css-syntax-patches-for-csstree-1.1.16.tgz", + "integrity": "sha512-LsDbJPP/B8cPasUJyTA5S99F7C4G93ngW8hUluXz8CFeOaaRnBPtBiIlvgcPYU0HmHNz8CXg+1vwFrIB4F6Dgw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "peerDependencies": { + "css-tree": "^3.2.1" + }, + "peerDependenciesMeta": { + "css-tree": { + "optional": true + } + } + }, + "node_modules/@csstools/css-tokenizer": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-4.0.2.tgz", + "integrity": "sha512-OoKoR0f76dCY666JlcbhmVTs2drYj1GUXZTYTcbUgJjh9Nv41aFfZ21bPQTERm5+L5cBDo466NltB2lplS5GBw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=20.19.0" + } + }, + "node_modules/@exodus/bytes": { + "version": "1.16.0", + "resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.16.0.tgz", + "integrity": "sha512-IcpW84uEn3N7ETtNZMlxKhfl6Pec8rUNGOTBtWbK1FKhJxIFAptZyVrvVRVBimAJxJCgc3PxepxkdWWG4DVzfA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + }, + "peerDependencies": { + "@noble/hashes": "^1.8.0 || ^2.0.0" + }, + "peerDependenciesMeta": { + "@noble/hashes": { + "optional": true + } + } + }, + "node_modules/bidi-js": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/bidi-js/-/bidi-js-1.1.0.tgz", + "integrity": "sha512-fX1Onk0tdVPC7obPWB5EbJ1z7NVhLq4m2xZLq2YXBkxzMXIGRpNMU88n0EPgWseKl12J7zXs7qrDxPK4sRs2fg==", + "dev": true, + "license": "MIT", + "dependencies": { + "require-from-string": "^2.0.2" + } + }, + "node_modules/css-tree": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-3.2.1.tgz", + "integrity": "sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==", + "dev": true, + "license": "MIT", + "dependencies": { + "mdn-data": "2.27.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0" + } + }, + "node_modules/data-urls": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-8.0.0.tgz", + "integrity": "sha512-JQUCCK+/CAGbGGx618PlFZMXH81Jtj7t73CHv9dd/zVWvxgGT2zLFRjnKb+Ng46GIwcy+f7f88qd4duqllK+WQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-mimetype": "^5.0.0", + "whatwg-url": "^17.1.2" + }, + "engines": { + "node": "^22.14.0 || >=24.0.0" + } + }, + "node_modules/decimal.js": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz", + "integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==", + "dev": true, + "license": "MIT" + }, + "node_modules/entities": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-9.0.0.tgz", + "integrity": "sha512-oJFNDJg3kTPwAD1cNn2+WmUq4wFoo09npc3Ydf1D7ED4smRiWrsKnaLxykrTWgyGEcusc87P5dxlAleol9kpkg==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/html-encoding-sniffer": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-7.0.0.tgz", + "integrity": "sha512-UikN5yr7xsCDAq87Or5or0PAlD3HJJOKVzM05az588WnpDJ4Ux7a2A53Qi6gofGg2/EtvF/H4hCi/TXfCW4Y6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@exodus/bytes": "^1.15.1" + }, + "engines": { + "node": "^22.13.0 || >=24.0.0" + } + }, + "node_modules/is-potential-custom-element-name": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", + "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/jsdom": { + "version": "30.1.3", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-30.1.3.tgz", + "integrity": "sha512-hQMUPvRgN7KxsfIytDQji7bimuJeRQa6Qo5+iuiZQk5CafeRxLIA10/cG5YCBFNpD9RO3oqIiN4CO1Y44kxqXg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@asamuzakjp/css-color": "^7.1.3", + "@asamuzakjp/dom-selector": "^10.0.3", + "@bramus/specificity": "^2.4.2", + "@csstools/css-syntax-patches-for-csstree": "^1.1.15", + "@exodus/bytes": "^1.16.0", + "css-tree": "^3.2.1", + "data-urls": "^8.0.0", + "decimal.js": "^10.6.0", + "html-encoding-sniffer": "^7.0.0", + "is-potential-custom-element-name": "^1.0.1", + "lru-cache": "^11.5.3", + "parse5": "^8.0.1", + "saxes": "^6.0.0", + "tough-cookie": "^6.0.2", + "undici": "^8.12.1", + "w3c-xmlserializer": "^6.0.0", + "webidl-conversions": "^8.0.1", + "whatwg-mimetype": "^5.0.0", + "whatwg-url": "^17.2.0", + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + }, + "peerDependencies": { + "canvas": "^3.2.3" + }, + "peerDependenciesMeta": { + "canvas": { + "optional": true + } + } + }, + "node_modules/lru-cache": { + "version": "11.5.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz", + "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/mdn-data": { + "version": "2.27.1", + "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.27.1.tgz", + "integrity": "sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==", + "dev": true, + "license": "CC0-1.0" + }, + "node_modules/parse5": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-8.1.0.tgz", + "integrity": "sha512-sq3qBFpee5jeocbFbO48VHlGr8sT7mbXS0vxlKN6sottBtJzrOG3998sr0llSZcQAGgfpdmEYAIZE0P9z0dE8w==", + "dev": true, + "license": "MIT", + "dependencies": { + "entities": "^9.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/saxes": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz", + "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==", + "dev": true, + "license": "ISC", + "dependencies": { + "xmlchars": "^2.2.0" + }, + "engines": { + "node": ">=v12.22.7" + } + }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/tldts": { + "version": "7.4.19", + "resolved": "https://registry.npmjs.org/tldts/-/tldts-7.4.19.tgz", + "integrity": "sha512-48dH6aSpQnpbzDUc4vIQZ1VjB8tkK+e8c1yx05/SZK+rkssgjEOlxDd/yU8/a4vGYQ9vRgJr9dwMq9TJ0b3X2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "tldts-core": "^7.4.19" + }, + "bin": { + "tldts": "bin/cli.js" + } + }, + "node_modules/tldts-core": { + "version": "7.4.20", + "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-7.4.20.tgz", + "integrity": "sha512-C630TWXZCZmLq0F2bW4QqwnaaxCQ/svpAqvJwnC4JvgEM5ohhBnGsEzTLSOXcN+xjz+kEaHS5uoWIw2klnqd0A==", + "dev": true, + "license": "MIT" + }, + "node_modules/tough-cookie": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-6.0.2.tgz", + "integrity": "sha512-exgYmnmL/sJpR3upZfXG5PoatXQii55xAiXGXzY+sROLZ/Y+SLcp9PgJNI9Vz37HpQ74WvDcLT8eqm+kV3FzrA==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "tldts": "^7.0.5" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/tr46": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-7.0.0.tgz", + "integrity": "sha512-BcDSDW+SIGWVOns1Zm6Yg91q9AEj7eaID0QDY9oIqJD1A8dscNwMcl9Sms2DeuWCNov1X0/oXanHGYQBSLwZsg==", + "dev": true, + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "engines": { + "node": "^22.14.0 || >=24.0.0" + } + }, + "node_modules/undici": { + "version": "8.12.3", + "resolved": "https://registry.npmjs.org/undici/-/undici-8.12.3.tgz", + "integrity": "sha512-+fdndUTwBP86cVjihTp21hZHo7d6oj1c/47XPA3lL8mM0XHs+C4EkcjmgRsFnFk2f/UONGDy9ItBItmXsLOQHw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=22.19.0" + } + }, + "node_modules/w3c-xmlserializer": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-6.0.0.tgz", + "integrity": "sha512-4Nsy8K5Tr6SPDH9jhKJOHf7ChDrc1zufZTVSF7x72hwuEXBqxqk9G6cK+K2NRUtB3iELRJqjXb4JPDMBjMTl2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/webidl-conversions": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-8.0.1.tgz", + "integrity": "sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=20" + } + }, + "node_modules/whatwg-mimetype": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-5.0.0.tgz", + "integrity": "sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20" + } + }, + "node_modules/whatwg-url": { + "version": "17.3.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-17.3.0.tgz", + "integrity": "sha512-KwOAJrpf+GTgBvcBQJcP38sMF0DsQKdwtG+TxM2pW44P6E5k0hDbWrDmyuJDIF0Uef0aQq0ZoJs+5oI+k8ddhg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@exodus/bytes": "^1.16.0", + "tr46": "^7.0.0", + "webidl-conversions": "^8.0.1" + }, + "engines": { + "node": "^22.14.0 || >=24.0.0" + } + }, + "node_modules/xml-name-validator": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz", + "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/xmlchars": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz", + "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", + "dev": true, + "license": "MIT" + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..0d9831c --- /dev/null +++ b/package.json @@ -0,0 +1,13 @@ +{ + "name": "meds-algorithm-docs-tests", + "private": true, + "scripts": { + "test": "node --test docs/tests/*.test.cjs" + }, + "engines": { + "node": ">=24" + }, + "devDependencies": { + "jsdom": "^30.1.3" + } +} diff --git a/pyproject.toml b/pyproject.toml index 61e4da9..1504a59 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -31,7 +31,7 @@ packages = ["src/meds_algorithm"] # Discovery metadata and its documentation tooling evolve independently of runtime releases. [tool.hatch.build.targets.sdist] -exclude = ["/catalogue", "/docs", "/mkdocs.yml"] +exclude = ["/catalogue", "/docs", "/mkdocs.yml", "/node_modules", "/package.json", "/package-lock.json", "/.cache"] [tool.pytest.ini_options] testpaths = ["tests"] @@ -47,7 +47,7 @@ Documentation = "https://meds-algorithm.readthedocs.io/en/latest/" [dependency-groups] dev = ["ruff"] -docs = ["mkdocs>=1.6,<2", "mkdocs-material>=9.5,<10", "packaging>=24", "pytest>=8"] +docs = ["mkdocs>=1.6,<2", "mkdocs-material>=9.5,<10", "jinja2>=3.1", "packaging>=24", "pytest>=8"] [tool.ruff] line-length = 110 diff --git a/uv.lock b/uv.lock index 72a02df..8be283b 100644 --- a/uv.lock +++ b/uv.lock @@ -472,6 +472,7 @@ dev = [ { name = "ruff" }, ] docs = [ + { name = "jinja2" }, { name = "mkdocs" }, { name = "mkdocs-material" }, { name = "packaging" }, @@ -500,6 +501,7 @@ provides-extras = ["data", "orchestration", "conformance", "test"] [package.metadata.requires-dev] dev = [{ name = "ruff" }] docs = [ + { name = "jinja2", specifier = ">=3.1" }, { name = "mkdocs", specifier = ">=1.6,<2" }, { name = "mkdocs-material", specifier = ">=9.5,<10" }, { name = "packaging", specifier = ">=24" },