Skip to content

fix: prevent Trainer handler leaks, make cache dirs lazy, and fix F821 bugs - #1757

Open
irvifa wants to merge 1 commit into
sunlabuiuc:masterfrom
irvifa:fix/core-and-f821-bugs
Open

irvifa wants to merge 1 commit into
sunlabuiuc:masterfrom
irvifa:fix/core-and-f821-bugs

Conversation

@irvifa

@irvifa irvifa commented Nov 30, 2026

Copy link
Copy Markdown
Contributor

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

  • Trainer handler cleanup & empty-dataloader guards (pyhealth/trainer.py):
    • Tag FileHandlers created by set_logger() so subsequent Trainer(..., enable_logging=True) instances detach and close only previous Trainer handlers while preserving external user-attached FileHandlers (fixes test_preexisting_trainer_handler_is_preserved).
    • Added Trainer.close(), guarded empty-dataloader divisions in train(), evaluate(), and inference() (ValueError on empty inference), fixed inference() return type annotation (-> list), and corrected load_ckpt() docstring.
  • Lazy, race-safe cache directory creation (pyhealth/__init__.py, pyhealth/utils.py, pyhealth/datasets/utils.py, pyhealth/medcode/utils.py):
    • Removed import-time os.makedirs(BASE_CACHE_PATH) and eager create_directory(MODULE_CACHE_PATH) calls (including the 20-directory loop in medcode/utils.py).
    • Added PYHEALTH_CACHE_DIR env override (safely falling back to default when empty) and ensure_cache_dir(), switched create_directory() to exist_ok=True, and ensured download_file() and save_pickle() lazily create parent directories.
  • Single-use Iterable exhaustion (pyhealth/datasets/base_dataset.py): Materialized patient_ids = list(patient_ids) before len(patient_ids) in _task_transform_fn().
  • Undefined names (F821):
    • pyhealth/sampler/sage_sampler.py: moved Adj(NamedTuple) to module scope (removing the dead duplicate local class in NeighborSampler.__init__).
    • pyhealth/models/molerec.py: replaced globals().update(...) with explicit module-level lazy OGB bindings.
    • pyhealth/tasks/medical_coding.py: removed dead references in main() to commented-out MIMIC-IV coding classes.
  • Unit tests: added tests/core/test_trainer_safety.py, tests/core/test_lazy_cache.py, and tests/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.

@solarsys

Copy link
Copy Markdown
Collaborator

Thanks for splitting #1750. Why this one has status: manual: it changes core and shared code: trainer.py, datasets/base_dataset.py, datasets/utils.py, medcode/utils.py, utils.py, plus molerec.py, sage_sampler.py and medical_coding.py. A maintainer needs to review that, and it's flagged in #1668. If you want parts to move faster, the fixes to individual models (molerec.py, sage_sampler.py) could go in their own small PRs and get automatic review, leaving the Trainer and cache-directory changes here.

@github-actions

Copy link
Copy Markdown

Test Coverage

Total: 88.40% (58589 / 66275 lines)

Modified file Coverage Lines
pyhealth/__init__.py 100.00% 16 / 16
pyhealth/datasets/base_dataset.py 93.21% 535 / 574
pyhealth/datasets/utils.py 47.92% 92 / 192
pyhealth/medcode/utils.py 62.50% 20 / 32
pyhealth/models/molerec.py 67.02% 250 / 373
pyhealth/sampler/sage_sampler.py 25.29% 22 / 87
pyhealth/tasks/medical_coding.py 72.00% 36 / 50
pyhealth/trainer.py 79.79% 233 / 292
pyhealth/utils.py 89.69% 87 / 97

Workflow run · 7c3c844

@solarsys

Copy link
Copy Markdown
Collaborator

/review

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed commit 7c3c844

Comment thread pyhealth/__init__.py
)


def ensure_cache_dir(path: str = BASE_CACHE_PATH) -> str:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Comment thread pyhealth/trainer.py
additional_outputs[key].append(output[key].cpu().numpy())
if return_patient_ids:
patient_ids.extend(data["patient_id"])
if not loss_all:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. 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 Adj with a real NeighborSampler;
    • test the molerec lazy-import path (_import_ogb and the ogb-missing fallback in graph_batch_from_smiles with non-empty SMILES);
    • test Trainer.train and Trainer.evaluate with a real labeled dataloader, to cover the new trainer branches.
  2. 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_DIR and Trainer.close().

Optional suggestions:

  • ensure_cache_dir has no caller in the library and duplicates create_directory. Consider using it in the writers or dropping it.
  • inference() raises ValueError on an empty loader, but evaluate() returns NaN. Consider making these consistent.
  • graph_batch_from_smiles silently returns placeholder graphs for real SMILES when ogb is missing. A warning would help users.

Reviewed commit 7c3c844

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

status: manual Pending maintainer's review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants