diff --git a/template/AGENTS.md.jinja b/template/AGENTS.md.jinja index 942be25..c6a2bb4 100644 --- a/template/AGENTS.md.jinja +++ b/template/AGENTS.md.jinja @@ -31,6 +31,9 @@ for material unresolved choices; exploratory assumptions require explicit opt-in - Intermediate payloads are opaque. Generic tests validate their envelopes, not their contents. - MEDS-DEV owns dataset-specific predicates; the algorithm owns their interpretation. - Never associate outputs with prediction keys by row order. +- Long-running steps stream progress through `logging` (phases with planned sizes, step/epoch out of total, + training and tuning loss, kept checkpoint, inference counts; see "Progress logging" in the guide). Log only + aggregates and configuration: never subject IDs, times, codes, values, labels, predictions or sample rows. - Keep `STUB_PROFILES = set(PROFILES)` until every registered command and the real end-to-end adapter work. - Replace the intentional failure in `tests/test_primary_behavior.py`. Prove that a known signal reaches the algorithm's real selected codes/features and produces the expected behavior, with a shuffled-label diff --git a/template/docs/IMPLEMENTATION_GUIDE.md.jinja b/template/docs/IMPLEMENTATION_GUIDE.md.jinja index 87015c4..2a5893e 100644 --- a/template/docs/IMPLEMENTATION_GUIDE.md.jinja +++ b/template/docs/IMPLEMENTATION_GUIDE.md.jinja @@ -101,6 +101,33 @@ dependencies and persisted fitted state. Avoid speculative abstractions, mutable hidden singletons, import-time computation and duplicated core behavior. Use the same runner from the CLI and `tests/e2e.py`; demonstrate independent execution after reopening serialized inputs. +### Progress logging + +Steps that can run for minutes or more must report progress while they run, so a long job can be told apart +from a hung one from its log alone. Use `logging.getLogger(__name__)` and never `print` for progress: the +generated CLI configures logging to stderr with one flushed line per record (level from `LOG_LEVEL`, +default `INFO`), and core streams each step's output into `logs/.log` and, under SLURM, the job's +output files as it is written. Log from the algorithm, including from loops in long-running dependencies +(through their own callbacks or logging, configured to the same stream). + +Log at least: + +- each phase as it starts, with its planned size (for example `stage 2: context 16384, 1015 optimizer steps`) + and its elapsed time when it ends; +- for iterative training, every epoch or every N optimizer steps (bounded, e.g. at most a line a minute at + steady state): step or epoch out of the total, training loss, learning rate, elapsed time and throughput; +- every tuning evaluation (tuning loss or metric), early-stopping decisions and which checkpoint is kept; +- for inference and generation, items done out of the total (subjects, prediction times, samples) with rate. + +Logs must never reveal patient-level data. Log only aggregates over many subjects and configuration values: +counts, sizes, timings, losses and metrics computed over a split or a batch, vocabulary size, resource use. +Never log subject IDs, prediction times, dates, event or code sequences, individual values, labels or +predictions of a subject, generated trajectories, sample rows of any table, or the free text of codes and +values; never log a batch's contents, and avoid exceptions whose message embeds such values (catch and +re-raise with an aggregate message). Do not log code names or vocabulary entries either: a rare code can +identify a patient in a small cohort. Paths, digests and configuration are fine. Logs are copied off +clusters and into CI output, so treat them as shareable. + ### Public API and internal helpers Expose the named algorithm and configuration classes for callers. Give implementation-only classes, diff --git a/template/src/{{ algorithm_slug }}/__main__.py.jinja b/template/src/{{ algorithm_slug }}/__main__.py.jinja index 8bb7f72..b117262 100644 --- a/template/src/{{ algorithm_slug }}/__main__.py.jinja +++ b/template/src/{{ algorithm_slug }}/__main__.py.jinja @@ -2,6 +2,8 @@ import argparse import json +import logging +import os import sys from pathlib import Path @@ -18,6 +20,20 @@ def _value(text: str): return text +def _configure_logging() -> None: + """Stream step progress to stderr, one flushed line per record, so it reaches the step log while running. + + Core sends a step's stdout and stderr to ``logs/.log`` (and, under SLURM, the job's output files) as they + are written. Python block-buffers ``print`` to a file, whereas a logging handler flushes every record. + ``LOG_LEVEL`` (default ``INFO``) sets the level. An existing configuration is kept. + """ + logging.basicConfig( + level=os.environ.get("LOG_LEVEL", "INFO").upper(), + stream=sys.stderr, + format="%(asctime)s %(levelname)s %(name)s: %(message)s", + ) + + def main() -> None: repository = create_repository() if len(sys.argv) > 1 and sys.argv[1] == "run": @@ -56,6 +72,7 @@ def main() -> None: if not key or key in arguments: parser.error(f"Empty or duplicate argument {key!r}") arguments[key] = _value(value) + _configure_logging() repository.run(args.command, arguments, profile=profile) except (ValueError, TypeError, FileNotFoundError) as error: parser.error(str(error)) diff --git a/tests/test_typed_execution.py b/tests/test_typed_execution.py index 1aecf84..21a6d1b 100644 --- a/tests/test_typed_execution.py +++ b/tests/test_typed_execution.py @@ -41,7 +41,10 @@ def preprocess_data(self, request): return PayloadMetadata("fixture-data") def train_supervised(self, request): + import logging + outcomes = request.labels.read()["boolean_value"] + logging.getLogger(__name__).info("fitting on %d labels", len(outcomes)) alpha = self.config.smoothing probability = (outcomes.sum() + alpha) / (len(outcomes) + 2 * alpha) (request.output.directory / "probability.txt").write_text(str(probability)) @@ -103,6 +106,8 @@ def run(step, **arguments): output_supervised_algorithm_dir=algorithm, ) assert result.returncode == 0, result.stderr + # The generated CLI configures logging, so a step's progress records reach its output. + assert f"INFO {slug}.{slug}: fitting on 3 labels" in result.stderr args = { "input_data_dir": data, "input_supervised_algorithm_dir": algorithm,