Skip to content

Key the dataset cache on the config and source files - #1265

Merged
jhnwu3 merged 1 commit into
sunlabuiuc:masterfrom
solarsys:feat/dataset-cache-key-content
Oct 2, 2026
Merged

jhnwu3 merged 1 commit into
sunlabuiuc:masterfrom
solarsys:feat/dataset-cache-key-content

Conversation

@solarsys

@solarsys solarsys commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator

Problem

The dataset cache key (BaseDataset._init_cache_dir) covered only {root, tables, dataset_name, dev}. So:

  • rewriting a source file at the same path (for example regenerating a cohort extract) silently reused the stale cached global_event_df;
  • editing the YAML config (attributes, joins, timestamp columns) also reused the stale cache.

A downstream EHR project hit both and had to delete caches by hand.

Change

The key now also includes:

  • a SHA-256 of the YAML config (DatasetConfig.model_dump);
  • for each requested table, [file, size, mtime_ns] of every source file it reads: the table file and its .csv/.csv.gz twin, joined files, glob matches, and the files under a Parquet directory (MEDS shards).

Design choices:

  • Size plus modification time, not a content hash, like make. Startup stays cheap for multi-GB sources. Copying files with new timestamps triggers a rebuild, which errs on the safe side.
  • URLs are keyed by the URL alone, so creating a dataset makes no network requests.
  • Datasets without a config are unchanged. MEDSDataset builds on the base key, and the FHIR dataset already hashes its YAML in its own key.

Scope

This is the dataset half. The task cache key (task code and attributes) is being reworked in #1207, so this PR doesn't touch it.

Upgrade note

Existing caches get a new key, so they're rebuilt once after upgrading. Old cache folders are left in place; the docs say they can be deleted.

Tests, docs, example

  • New tests/core/test_dataset_cache_key.py, on a real CSV and YAML in a temp folder:

    • a source rewritten at the same path is reloaded (3 → 5 patients, new cache folder);
    • an unchanged rerun reuses the cache;
    • an edited config gives a new cache;
    • a changed modification time gives a new cache.

    Three of these fail on master.

  • Existing base-dataset, caching and MEDS tests pass.

  • docs/api/datasets.rst ("How PyHealth Loads Data") explains what "the same configuration" means now.

  • New examples/dataset_cache_refresh.py: v1 has 2 patients; after rewriting the file, v2 has 4 patients in a fresh cache, and an unchanged rerun reuses it.

  • Full core suite: Ran 1385 tests … OK (skipped=76). tools/check_pr_rules.py passes.

This PR and #1264 (the default cache warning) edit different parts of docs/api/datasets.rst, so they merge in either order.

🤖 Generated with Claude Code

The dataset cache key covered only {root, tables, dataset_name, dev}.
Rewriting a source file at the same path, or editing the YAML config,
silently reused the stale cached event table.

- The key now also includes a SHA-256 of the YAML config and, for each
  requested table, [file, size, mtime_ns] of every source file it reads:
  the table file, its .csv/.csv.gz twin, joined files, glob matches, and
  files under a Parquet directory. Contents are not hashed, so startup
  stays cheap on large sources; URLs are keyed by the URL alone, so no
  network calls are made at init. Datasets without a config are unchanged.
- MEDSDataset builds on the base key and gets this too.
- tests/core/test_dataset_cache_key.py: a rewritten source is reloaded
  (3 -> 5 patients), an unchanged rerun reuses the cache, an edited
  config and a changed mtime give a new cache.
- docs/api/datasets.rst: what "same configuration" means for the cache.
- examples/dataset_cache_refresh.py.

Existing caches get a new key once after upgrading; old cache folders are
left in place.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@solarsys
solarsys requested a review from jhnwu3 October 2, 2026 13:08

@jhnwu3 jhnwu3 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

lgtm

@jhnwu3
jhnwu3 merged commit 85bfcf7 into sunlabuiuc:master Oct 2, 2026
2 checks passed
AxelNoun added a commit to AxelNoun/PyHealth that referenced this pull request Oct 7, 2026
…ataset

BaseDataset._init_cache_dir now also hashes the resolved config and
fingerprints the table sources. The source fingerprint resolves the
derived CSV against the user data root, where it does not live, so it
is empty for PTBXLDataset; say so, and say what the cache identity
rests on instead.
@AxelNoun AxelNoun mentioned this pull request Oct 7, 2026
5 tasks done
@solarsys
solarsys deleted the feat/dataset-cache-key-content branch October 9, 2026 04:30
Logiquo pushed a commit that referenced this pull request Oct 26, 2026
* feat(datasets): add PTB-XL ECG loader and YAML config

Introduce PTBXLDataset (BaseDataset + YAML) with optional wfdb extra,
root-keyed metadata cache, and a resolved cache YAML so file_path is
correct before BaseDataset init.

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat: add PTB-XL 5-superclass task and strat_fold split

Add PTBXLSuperclassClassification and split_by_strat_fold (folds 1-8 /
9 / 10) in separate modules so they can move to benchmarks later.

Co-authored-by: Cursor <cursoragent@cursor.com>

* test: add PTB-XL synthetic fixtures and end-to-end coverage

Cover helpers, metadata cache keyed by root, event reads via
PTBXLDataset, waveform IO (wfdb), and the 5-superclass task path.

Co-authored-by: Cursor <cursoragent@cursor.com>

* docs: add PTB-XL API pages and quickstart example

Document the dataset/task Overview RST pages and a minimal ECG
superclass example for CPBench users.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(datasets): isolate PTB-XL cache identity and write metadata atomically

BaseDataset keys global_event_df on root+dataset_name; hash data-root path
and CSV bytes into dataset_name (EEGBCI pattern) and write CSV/YAML via
tmp+os.replace under FileLock so DDP cannot read a truncated file.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(tasks): keep PTB-XL task cache keys stable and emit integer ages

Move the SCP class map to functools.cache so vars(task) is unchanged
after __call__. Emit age=-1 when missing and clip HIPAA-censored 300
to 90 so litdata can serialize the field.

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor(datasets): avoid decoding samples in split_by_strat_fold

Accept a precomputed folds sequence and a generic fold_field so callers
need not materialize 12-lead signals just to read an integer. Error
messages no longer mention PTB-XL.

Co-authored-by: Cursor <cursoragent@cursor.com>

* test: cover PTB-XL set_task, cache isolation, and age sentinels

Exercise the real litdata path without mocking wfdb, assert
MultiLabelProcessor vocab order, and pin cache-dir uniqueness plus
vars(task) stability.

Co-authored-by: Cursor <cursoragent@cursor.com>

* docs: correct PTB-XL v1.0.3 counts, label order, and API toctree

v1.0.3 is 21,799 records / 18,869 patients. Document that
MultiLabelProcessor emits CD, HYP, MI, NORM, STTC. Harmonize the
datasets toctree and reuse the ptbxl extra in the pixi test env.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(datasets): keep split_by_strat_fold re-export alias for ruff F401

The redundant-looking 'as' is required by ruff's unused-import rule for
module re-exports, same as EEGBCIDataset / PTBXLDataset in this file.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(datasets): keep PTBXLDataset.root as the user data path

BaseDataset.load_table concatenates root/file_path and rejects absolute
paths, so override load_table to read the derived CSV from
metadata_cache_dir while leaving self.root equal to the constructor path.

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat(datasets): add check_patient_disjoint to split_by_strat_fold

Official PTB-XL folds are patient-disjoint; this flag verifies that
property via patient_to_index. Default False keeps current callers
working. The synthetic fixture leaks patient 15709 across folds 1 and 9
so the check is actually exercised.

Co-authored-by: Cursor <cursoragent@cursor.com>

* docs(datasets): describe the post-#1265 cache key in PTBXLDataset

BaseDataset._init_cache_dir now also hashes the resolved config and
fingerprints the table sources. The source fingerprint resolves the
derived CSV against the user data root, where it does not live, so it
is empty for PTBXLDataset; say so, and say what the cache identity
rests on instead.

* docs(ptbxl): correct sex encoding to 0 = male, 1 = female

Wagner et al. (Scientific Data 7:154, 2020), Table 2, defines the sex
column of ptbxl_database.csv as "male 0, female 1". The PTBXLDataset
docstring, configs/ptbxl.yaml and the task comment stated the inverse.
Values were always passed through unchanged; only the documentation
was wrong.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(ptbxl): cover the 500 Hz records500 path

Check that sampling_rate=500 points every derived signal_file at
records500/..._hr, and that set_task at 500 Hz yields (12, 250)
signals. Both tests fail if filename_lr is used at 500 Hz.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(ptbxl): clarify version support, cache-dir write order, example cost

- State what distinguishes v1.0.1/v1.0.2 (duplicate records removed
  later: 21,837 vs 21,799 records) and that the release version is not
  detected, instead of an unverified claim about differing columns.
- Note that the derived CSV and resolved YAML are written before
  BaseDataset raises under PYHEALTH_REQUIRE_CACHE_DIR.
- Comment in the quickstart that split_by_strat_fold without folds=
  decodes every stored sample once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants