Skip to content

fix: harden checkpoint loading, remove runtime pip install, and fix core bugs - #1750

Closed
irvifa wants to merge 2 commits into
sunlabuiuc:masterfrom
irvifa:fix/security-and-core-bugs
Closed

irvifa wants to merge 2 commits into
sunlabuiuc:masterfrom
irvifa:fix/security-and-core-bugs

Conversation

@irvifa

@irvifa irvifa commented Nov 30, 2026

Copy link
Copy Markdown
Contributor

Summary

This PR addresses several security and reliability bugs identified during a codebase audit:

Security & Deserialization

  • Remove runtime os.system pip install (pyhealth/nlp/metrics.py): Removed Scorer._install() and _install_all() so scoring never shells out or mutates the user's Python environment at runtime. Fixed the missing variable shadowing bug in _get_missing_modules() that raised AttributeError: 'tuple' object has no attribute 'extend' when a dependency was missing, and logged a warning directing users to pip install pyhealth[nlp].
  • Enforce weights_only=True in generator torch.load() calls: Updated CorGAN, GPT2, HALO, MedGAN, and PromptEHR to load checkpoints with weights_only=True, aligning with SECURITY.md.

Core Bug Fixes

  • Undefined names (F821):
    • pyhealth/sampler/sage_sampler.py: Defined Adj(NamedTuple) (with .to()) used when is_sparse_tensor=True.
    • pyhealth/models/molerec.py: Replaced globals().update(...) with explicit module-level lazy bindings (smiles2graph, AtomEncoder, BondEncoder) and ensured GINConv, GINGraph, and graph_batch_from_smiles load OGB on demand.
    • pyhealth/tasks/medical_coding.py: Removed dead calls in main() to the commented-out MIMIC4ICD9Coding and MIMIC4ICD10Coding classes.
  • Trainer resource leak & edge cases (pyhealth/trainer.py):
    • set_logger() now detaches and closes any existing FileHandler on the module logger before adding a new one (preventing FD leaks and duplicate writes across multiple Trainer instances), and Trainer.close() was added.
    • Guarded empty-dataloader divisions in train(), evaluate(), and inference() (raising ValueError in inference() instead of ZeroDivisionError).
    • Fixed inference() return type annotation (-> list) and load_ckpt() docstring.
  • Single-use Iterable exhaustion (pyhealth/datasets/base_dataset.py): Materialized patient_ids = list(patient_ids) before len(patient_ids) in _task_transform_fn() so iterators are not exhausted prior to itertools.batched(...).
  • 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 override and ensure_cache_dir(), switched create_directory() to os.makedirs(..., exist_ok=True), and ensured download_file() and save_pickle() lazily create parent directories.

Verification

  • ruff check --select F821,E9 pyhealth — 0 errors.
  • Core pytest suites (test_default_cache_dir.py, test_base_dataset.py, test_corgan.py, test_medgan.py, test_gpt2.py, test_halo.py, test_promptehr.py, test_molerec.py) — 58 passed, 5 skipped.
  • Verified lazy BASE_CACHE_PATH on import in an isolated subprocess, Scorer._get_missing_modules() with missing dependencies, Trainer FileHandler cleanup + empty-dataloader guards, and sage_sampler.Adj.

…ore bugs

    - Remove runtime os.system pip installation from pyhealth.nlp.metrics.Scorer
      and fix variable shadowing in _get_missing_modules() that raised AttributeError.
    - Pass weights_only=True to torch.load() in all five generator models
      (CorGAN, GPT2, HALO, MedGAN, PromptEHR) to match SECURITY.md.
    - Fix F821 undefined names in sage_sampler.py (define Adj), molerec.py
      (explicit module-level lazy OGB bindings), and medical_coding.py (remove
      dead references to commented-out MIMIC-IV coding tasks in main()).
    - Fix Trainer FileHandler leak across instances (close/detach prior handlers
      and add Trainer.close()), guard empty-dataloader divisions in train/evaluate/
      inference, fix inference() return type annotation, and fix load_ckpt() docstring.
    - Materialize patient_ids before len() in BaseDataset._task_transform_fn() so
      single-use iterables are not exhausted before batching.
    - Make BASE_CACHE_PATH and module cache directories lazy with exist_ok=True
      (supporting PYHEALTH_CACHE_DIR), avoiding import-time filesystem side effects.
@github-actions

github-actions Bot commented Nov 30, 2026 •

Copy link
Copy Markdown

Test Coverage

Warning

Tests failure; coverage may be incomplete.

Total: 88.43% (58590 / 66256 lines)

Modified file Coverage Lines
pyhealth/__init__.py 100.00% 16 / 16
pyhealth/datasets/__init__.py 100.00% 93 / 93
pyhealth/datasets/base_dataset.py 93.21% 535 / 574
pyhealth/datasets/seer.py 92.19% 59 / 64
pyhealth/datasets/utils.py 47.92% 92 / 192
pyhealth/medcode/utils.py 62.50% 20 / 32
pyhealth/models/duett.py 93.52% 101 / 108
pyhealth/models/generators/corgan.py 98.77% 241 / 244
pyhealth/models/generators/gpt2.py 85.31% 122 / 143
pyhealth/models/generators/halo.py 91.50% 323 / 353
pyhealth/models/generators/medgan.py 98.95% 189 / 191
pyhealth/models/generators/promptehr.py 88.41% 183 / 207
pyhealth/models/molerec.py 67.02% 250 / 373
pyhealth/nlp/metrics.py 84.17% 218 / 259
pyhealth/processors/seer_processor.py 95.40% 83 / 87
pyhealth/sampler/sage_sampler.py 25.29% 22 / 87
pyhealth/tasks/__init__.py 98.59% 140 / 142
pyhealth/tasks/medical_coding.py 72.00% 36 / 50
pyhealth/tasks/seer_survival.py 96.97% 32 / 33
pyhealth/trainer.py 79.73% 232 / 291
pyhealth/utils.py 89.69% 87 / 97

Workflow run · f6bc9ba

@solarsys solarsys added the status: manual Pending maintainer's review label Nov 30, 2026
@solarsys

Copy link
Copy Markdown
Collaborator

Why this PR has status: manual: it changes several shared modules: datasets/base_dataset.py, datasets/utils.py, medcode/utils.py and the generator models. Removing runtime pip install and hardening checkpoint loading are worthwhile security fixes, so we've flagged this for a maintainer in #1668.

To help it along:

  • The build is failing. Please fix that first.
  • Add tests for the changed behavior, for example that checkpoint loading rejects pickled objects, or that no pip call happens at runtime.
  • Consider splitting it by area: checkpoint loading, the runtime-install removal, and the other fixes. Each piece is then easy to review on its own.

@irvifa

irvifa commented Nov 30, 2026

Copy link
Copy Markdown
Contributor Author

replaced by:
#1755
#1756
#1757

@irvifa irvifa closed this Nov 30, 2026
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