Repository navigation
Conversation
|
Thanks for splitting #1750. Why this one has |
Test CoverageTotal: 88.40% (58589 / 66275 lines)
|
|
/review |
| ) | ||
|
|
||
|
|
||
| def ensure_cache_dir(path: str = BASE_CACHE_PATH) -> str: |
There was a problem hiding this comment.
[low] ensure_cache_dir is an unused public helper that duplicates create_directory
ensure_cache_dir has no caller in library code; its only use is its own doctest and the new test. It does the same thing as pyhealth.utils.create_directory, which the PR also changes to os.makedirs(..., exist_ok=True). Either drop ensure_cache_dir and use create_directory, or keep one helper and point the other at it. The new PYHEALTH_CACHE_DIR environment variable is also not mentioned in docs/ (for example next to the ~/.cache/pyhealth references in docs/api/medcode.rst), so users can't discover it.
| additional_outputs[key].append(output[key].cpu().numpy()) | ||
| if return_patient_ids: | ||
| patient_ids.extend(data["patient_id"]) | ||
| if not loss_all: |
There was a problem hiding this comment.
[low] Empty dataloader is handled differently in evaluate() for labeled and unlabeled models
inference() now raises ValueError("Dataloader is empty..."). evaluate() uses inference() when the model has a label processor, so an empty loader raises for labeled models. The unlabeled branch of evaluate() returns a NaN loss for the same input. The PR description says evaluate() guards empty dataloaders, but only the unlabeled path does, and the test covers only that path. Make the two branches agree (either NaN in both, or a documented ValueError in both) and add a test for a labeled model with an empty loader.
| if smiles2graph is None: | ||
| try: | ||
| _import_ogb() | ||
| except ImportError: |
There was a problem hiding this comment.
[low] graph_batch_from_smiles silently returns placeholder graphs when ogb is missing
When _import_ogb() raises ImportError, which includes an ogb version that is too old, non-empty SMILES input gets a one-node placeholder graph for every molecule with no warning. The old NameError fallback behaved the same way, so this is not new, but the PR now makes the fallback an explicit import attempt. MoleRec construction already requires ogb, so the placeholder is reachable only through direct calls. Consider raising for non-empty input and keeping the placeholder only for the empty-list case. The tests in tests/core/test_f821_fixes.py cover only the empty-list case.
There was a problem hiding this comment.
AI Review
suggestion: need change
decision: human review
Thank you for this audit-driven cleanup. It fixes Trainer handler leaks, makes cache directories lazy, and resolves several undefined-name bugs. Tests accompany each change.
This touches shared code: the Trainer (set_logger, train, evaluate, inference, close), the shared helpers in pyhealth/utils.py (create_directory, save_pickle, download_file), and the package-level BASE_CACHE_PATH in pyhealth/init.py. The last of these now has an env override that changes where every component caches. Because many components depend on these, a maintainer needs to review it, so it can't be approved automatically.
To get this merged:
- Coverage is below the 80% bar for several changed files. The CI numbers are: sage_sampler.py 25%, datasets/utils.py 48%, medcode/utils.py 62.5%, molerec.py 67%, medical_coding.py 72%, and trainer.py 79.8%. The whole repository is at 88.4%, which is fine. Please add tests for the code you changed. For example:
- exercise
Adjwith a realNeighborSampler; - test the molerec lazy-import path (
_import_ogband the ogb-missing fallback ingraph_batch_from_smileswith non-empty SMILES); - test
Trainer.trainandTrainer.evaluatewith a real labeled dataloader, to cover the new trainer branches.
- exercise
- The new env-var override and the lazy-cache behavior are user-facing, but the description doesn't say they are documented anywhere. Please add a short docs note on
PYHEALTH_CACHE_DIRandTrainer.close().
Optional suggestions:
ensure_cache_dirhas no caller in the library and duplicatescreate_directory. Consider using it in the writers or dropping it.inference()raises ValueError on an empty loader, butevaluate()returns NaN. Consider making these consistent.graph_batch_from_smilessilently returns placeholder graphs for real SMILES when ogb is missing. A warning would help users.
Reviewed commit 7c3c844
Summary
Fix several core reliability, resource-leak, and undefined-name (
F821) bugs found during a codebase audit, with unit tests for all changed behavior.(Split out from #1750 per maintainer feedback; checkpoint hardening and NLP runtime-pip removal are in separate PRs.)
Changes
Trainerhandler cleanup & empty-dataloader guards (pyhealth/trainer.py):FileHandlers created byset_logger()so subsequentTrainer(..., enable_logging=True)instances detach and close only previousTrainerhandlers while preserving external user-attachedFileHandlers (fixestest_preexisting_trainer_handler_is_preserved).Trainer.close(), guarded empty-dataloader divisions intrain(),evaluate(), andinference()(ValueErroron empty inference), fixedinference()return type annotation (-> list), and correctedload_ckpt()docstring.pyhealth/__init__.py,pyhealth/utils.py,pyhealth/datasets/utils.py,pyhealth/medcode/utils.py):os.makedirs(BASE_CACHE_PATH)and eagercreate_directory(MODULE_CACHE_PATH)calls (including the 20-directory loop inmedcode/utils.py).PYHEALTH_CACHE_DIRenv override (safely falling back to default when empty) andensure_cache_dir(), switchedcreate_directory()toexist_ok=True, and ensureddownload_file()andsave_pickle()lazily create parent directories.Iterableexhaustion (pyhealth/datasets/base_dataset.py): Materializedpatient_ids = list(patient_ids)beforelen(patient_ids)in_task_transform_fn().F821):pyhealth/sampler/sage_sampler.py: movedAdj(NamedTuple)to module scope (removing the dead duplicate local class inNeighborSampler.__init__).pyhealth/models/molerec.py: replacedglobals().update(...)with explicit module-level lazy OGB bindings.pyhealth/tasks/medical_coding.py: removed dead references inmain()to commented-out MIMIC-IV coding classes.tests/core/test_trainer_safety.py,tests/core/test_lazy_cache.py, andtests/core/test_f821_fixes.py.Verification
python3 tools/check_pr_rules.py— all PR contribution rules passed.pytest tests/core/test_trainer_safety.py tests/core/test_lazy_cache.py tests/core/test_f821_fixes.py tests/core/test_survival_benchmark.py -k "TestTrainerSafety or TestLazyCache or TestF821Fixes or test_preexisting_trainer_handler_is_preserved"— all passed.