Skip to content

fix(cache): make task fingerprints deterministic and collision-free - #1207

Open
AxelNoun wants to merge 12 commits into
sunlabuiuc:masterfrom
AxelNoun:fix/task-fingerprint-916
Open

AxelNoun wants to merge 12 commits into
sunlabuiuc:masterfrom
AxelNoun:fix/task-fingerprint-916

Conversation

@AxelNoun

@AxelNoun AxelNoun commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Summary

The literal request in #916 is already satisfied on current master: set_task already hashes vars(task) (init args as instance attributes) together with the input/output schemas. This PR does not add that hashing; it replaces the mechanism. json.dumps(..., default=str) is neither injective (str() truncates numpy arrays past 1000 elements) nor stable across processes (PYTHONHASHSEED reorders sets; default repr() embeds memory addresses). Two different task configurations could share a cache directory, and identical configurations could fail to reuse one. The same bugs apply to the processors cache key.

That is why the diff is a typed canonicaliser rather than a one-line hash tweak: nine concrete failure modes (silent collisions, non-determinism, mixed-key TypeError, class-level config invisible to vars(), no code version, unsanitised task_name path component, and tests that reimplemented the hashing expression). Keep Refs #916 rather than Closes: the original ask was already in place; whether the issue should close is a maintainer call.

  • New pyhealth.tasks.fingerprint: deterministic, lossless fingerprints; raises UnfingerprintableError instead of silently hashing repr().
  • Fingerprints the task's effective state: instance attributes as __init__ leaves them (so Task() ≡ Task(window=15d) when that is the default, and spellings a task normalises, such as SeizureDetectionCHBMIT(subjects=["chb01"]) and subjects=["1"], share a key), class-level config on the MRO, and an explicit BaseTask.version for logic changes.
  • fingerprint_exclude denylist for non-semantic args (num_workers, verbose, …).
  • task_meta.json sidecar next to the cache so an opaque digest is auditable; set_task logs its path.
  • Sidecar writes use a per-writer temp name, skip rewrite on cache hit, and never abort a build on OSError (they run outside the build lock).
  • Processor cache key uses the same canonicaliser (covers CrossMap / mixed-key code_vocab).
  • task_name is slugified before it is used as a path component (BenchmarkEHRShot/guo_los).
  • CodeDescriber and _Keyed in ehr_text_serialization.py get a __pyhealth_fingerprint__ hook, so the keys of EHR text serialization tasks change too: a describer is keyed on its lookup and raw_fallback, not on its memoized lookups, which grew with use, and a wrapped task counts with its version and schemas.
  • Docs: what counts as the same configuration, version must be bumped when __call__ changes, fingerprint_exclude, UnfingerprintableError.

Breaking

Cache only. FINGERPRINT_VERSION = 5 changes every key, orphaning existing <cache_dir>/tasks directories. They are not deleted. This is deliberate: an unknown subset of them is wrong (findings 3, 5 and 7 mean two different task configurations could share a directory), and nothing distinguishes the good ones from the bad. Invalidating all of them is the only safe option. Changelog should suggest du -sh ~/.cache/pyhealth before upgrading.

API, potential. Strict mode now raises UnfingerprintableError on an argument that cannot be fingerprinted, where the old code produced a silent key. PYHEALTH_FINGERPRINT_STRICT=0 restores the fallback with a warning. Review call: invert the default for a transition release?

Open questions for maintainers

  1. version vs source hash. PYHEALTH_FINGERPRINT_SOURCE=1 folds a structural (AST) hash of __call__ / pre_filter into the key. Off by default: renaming a local variable should not invalidate a 40-minute cache. A version bump at review time is more predictable, but it depends on human discipline.
  2. Absolute paths. PurePath is hashed as-is, so a cache is not portable across machines if a path appears in the args. That is probably the right default (a different root is a different config) but it should be explicit in the docs.
  3. Cache migration. Should we ship pyhealth.datasets.prune_task_caches() to list/delete orphaned directories, or leave that to the user?

Test plan

  • pytest tests/core/test_task_fingerprint.py -q: 74 passed on Linux (Python 3.12) and Windows (3.13)
  • pytest tests/core/test_caching.py -q: 19 passed on Linux; Windows teardown WinError 32 from litdata file locks is pre-existing on master (identical 6 passed / 5 failed / 1 error on unmodified 0a75f99)
  • PYTHONHASHSEED in {1, 42, 999}: identical fingerprints
  • Concurrent sidecar writes (24 threads): no leftover .tmp, valid task_meta.json
  • tools/check_pr_rules.py against 0a75f99

Refs #916

set_task derived its cache key from json.dumps(vars(task), default=str). The default=str fallback silently stringifies anything not JSON-serialisable, which is neither injective (str() truncates numpy arrays past 1000 elements) nor stable across processes (set ordering depends on PYTHONHASHSEED, and default reprs embed memory addresses). Two different task configurations could therefore share a cache directory, and identical configurations could fail to reuse one.

Replace it with an explicit canonicaliser in pyhealth/tasks/fingerprint.py that raises on anything it cannot represent deterministically, records effective __init__ arguments with defaults applied, covers class-level configuration, and adds an explicit BaseTask.version for logic changes. Also fixes the same bug in the processors cache key, and slugifies task_name before using it as a path component.

Cache keys change, so existing task caches under <cache_dir>/tasks are orphaned. This is intentional: some of them are wrong.

Refs sunlabuiuc#916

Co-authored-by: Cursor <cursoragent@cursor.com>
@Logiquo Logiquo added the status: conflict There is a merge conflict label Oct 26, 2026
master a ajouté deux entrées à la clé du cache des échantillons depuis le
point de divergence : STORAGE_FORMAT, car un changement de disposition rend
les *.bin antérieurs illisibles, et split.to_dict(), car le split décide
quels patients ajustent les processeurs. Cette PR remplace le bloc
proc_params qui les portait par processors_fingerprint(), qui ne connaissait
que les processeurs : conserver la résolution naïve aurait silencieusement
retiré ces deux entrées de la clé, et deux splits distincts auraient alors
partagé un même répertoire samples_*.ld.

processors_fingerprint() reçoit donc storage_format et split en paramètres
nommés, absents de la charge utile quand ils valent None, afin que
l'empreinte à deux arguments reste inchangée.

Porter aussi test_unsplit_cache_key_has_no_split_entry, qui reconstruisait
le nom attendu en uuid5(json.dumps(...)) : il vérifiait l'implémentation de
la clé et non la propriété annoncée par son nom. Il s'appuie désormais sur
processors_fingerprint. Même raison pour
test_caches_from_the_old_storage_layout_are_not_reused, devenu vacuement
vrai, et ajout de test_a_split_changes_the_cache_key.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@github-actions

github-actions Bot commented Oct 26, 2026 •

Copy link
Copy Markdown

Test Coverage

Total: 87.26% (51238 / 58722 lines)

Modified file Coverage Lines
pyhealth/autoimprove/__init__.py 100.00% 10 / 10
pyhealth/autoimprove/evaluate.py 93.16% 177 / 190
pyhealth/autoimprove/explain.py 94.21% 293 / 311
pyhealth/autoimprove/improver.py 94.25% 869 / 922
pyhealth/autoimprove/llm.py 97.09% 100 / 103
pyhealth/autoimprove/report.py 96.52% 666 / 690
pyhealth/calib/predictionset/__init__.py 100.00% 10 / 10
pyhealth/calib/predictionset/group_conditional.py 95.04% 115 / 121
pyhealth/datasets/__init__.py 100.00% 85 / 85
pyhealth/datasets/abide.py 97.62% 123 / 126
pyhealth/datasets/ahepa_dementia.py 100.00% 74 / 74
pyhealth/datasets/base_dataset.py 93.22% 536 / 575
pyhealth/datasets/bciiv2a.py 95.00% 95 / 100
pyhealth/datasets/bcss.py 96.18% 151 / 157
pyhealth/datasets/brain_tumor_mri.py 95.65% 88 / 92
pyhealth/datasets/cardiology.py 98.61% 71 / 72
pyhealth/datasets/cbis_ddsm.py 95.42% 125 / 131
pyhealth/datasets/cdc_covid.py 92.59% 25 / 27
pyhealth/datasets/chapman_shaoxing.py 91.45% 107 / 117
pyhealth/datasets/covid_blues.py 96.08% 147 / 153
pyhealth/datasets/ham10000.py 93.46% 100 / 107
pyhealth/datasets/helsinki_neonatal.py 97.06% 66 / 68
pyhealth/datasets/hmc.py 97.62% 41 / 42
pyhealth/datasets/hup_ieeg.py 96.00% 96 / 100
pyhealth/datasets/isic2019.py 93.94% 124 / 132
pyhealth/datasets/isic2020.py 96.00% 96 / 100
pyhealth/datasets/jichi.py 94.32% 83 / 88
pyhealth/datasets/kits23.py 100.00% 75 / 75
pyhealth/datasets/lndb.py 93.20% 137 / 147
pyhealth/datasets/meds.py 93.67% 74 / 79
pyhealth/datasets/mimic3.py 100.00% 21 / 21
pyhealth/datasets/mimic4.py 95.80% 114 / 119
pyhealth/datasets/nsrr_sleep.py 100.00% 46 / 46
pyhealth/datasets/omop.py 96.88% 31 / 32
pyhealth/datasets/pad_ufes_20.py 95.89% 70 / 73
pyhealth/datasets/pbc.py 96.77% 30 / 31
pyhealth/datasets/ph2.py 95.60% 87 / 91
pyhealth/datasets/rotterdam.py 100.00% 71 / 71
pyhealth/datasets/tcga_rna_seq.py 92.31% 24 / 26
pyhealth/interpret/__init__.py 100.00% 4 / 4
pyhealth/interpret/uni_acs.py 82.35% 182 / 221
pyhealth/metrics/__init__.py 100.00% 16 / 16
pyhealth/metrics/competing_risks.py 97.22% 70 / 72
pyhealth/metrics/survival.py 94.25% 82 / 87
pyhealth/models/__init__.py 100.00% 102 / 102
pyhealth/models/behrt.py 93.37% 183 / 196
pyhealth/models/bitenet.py 92.96% 251 / 270
pyhealth/models/bulk_rna_bert.py 95.77% 68 / 71
pyhealth/models/chet.py 92.80% 245 / 264
pyhealth/models/clip_stress.py 91.67% 154 / 168
pyhealth/models/clip_stress_layers.py 98.39% 61 / 62
pyhealth/models/clip_stress_utils.py 86.86% 119 / 137
pyhealth/models/clmbr.py 95.70% 289 / 302
pyhealth/models/concare.py 77.09% 286 / 371
pyhealth/models/convirt.py 96.18% 151 / 157
pyhealth/models/daft.py 93.64% 221 / 236
pyhealth/models/dearllm.py 93.55% 145 / 155
pyhealth/models/deepsleepnet.py 99.22% 127 / 128
pyhealth/models/delphi.py 95.24% 240 / 252
pyhealth/models/descemb.py 91.32% 284 / 311
pyhealth/models/ecg_jepa.py 100.00% 121 / 121
pyhealth/models/eegnet.py 96.43% 81 / 84
pyhealth/models/ehr_cxr_early_fusion.py 93.33% 98 / 105
pyhealth/models/ehr_fm.py 91.95% 297 / 323
pyhealth/models/evicare.py 99.68% 313 / 314
pyhealth/models/game.py 86.96% 240 / 276
pyhealth/models/generators/__init__.py 100.00% 8 / 8
pyhealth/models/generators/tardiff.py 99.60% 251 / 252
pyhealth/models/joint_seq_image.py 99.29% 278 / 280
pyhealth/models/maestro.py 95.14% 176 / 185
pyhealth/models/medtok.py 99.51% 202 / 203
pyhealth/models/mensa.py 95.65% 220 / 230
pyhealth/models/mira.py 97.12% 337 / 347
pyhealth/models/neural_fine_gray.py 92.59% 125 / 135
pyhealth/models/protoecgnet.py 97.91% 374 / 382
pyhealth/models/query_focused_ehr.py 90.64% 155 / 171
pyhealth/models/rasc.py 98.63% 72 / 73
pyhealth/models/sleepkd.py 98.80% 82 / 83
pyhealth/models/stagenet.py 96.10% 197 / 205
pyhealth/models/stagenet_mha.py 94.33% 266 / 282
pyhealth/models/td_cnn_lstm.py 90.34% 346 / 383
pyhealth/models/text_embedding.py 95.70% 89 / 93
pyhealth/models/time_series_images.py 100.00% 126 / 126
pyhealth/models/udc.py 92.34% 229 / 248
pyhealth/processors/nested_sequence_processor.py 93.75% 165 / 176
pyhealth/processors/stagenet_processor.py 90.20% 184 / 204
pyhealth/processors/utils.py 96.61% 57 / 59
pyhealth/tasks/__init__.py 98.29% 115 / 117
pyhealth/tasks/abide_classification.py 97.83% 45 / 46
pyhealth/tasks/base_task.py 86.67% 26 / 30
pyhealth/tasks/bciiv2a_left_right_imagery.py 100.00% 8 / 8
pyhealth/tasks/bciiv2a_motor_imagery.py 95.45% 63 / 66
pyhealth/tasks/bcss_tile_classification.py 100.00% 24 / 24
pyhealth/tasks/bcss_tissue_segmentation.py 98.11% 52 / 53
pyhealth/tasks/brain_tumor_mri_classification.py 100.00% 13 / 13
pyhealth/tasks/cardiology_detect.py 100.00% 134 / 134
pyhealth/tasks/cbis_ddsm_abnormality_classification.py 100.00% 18 / 18
pyhealth/tasks/cbis_ddsm_classification.py 97.67% 42 / 43
pyhealth/tasks/cbis_ddsm_density_classification.py 91.67% 22 / 24
pyhealth/tasks/cdc_covid_mortality.py 91.55% 65 / 71
pyhealth/tasks/chaos_segmentation.py 97.98% 97 / 99
pyhealth/tasks/chapman_heartlang.py 96.23% 102 / 106
pyhealth/tasks/chapman_shaoxing_classification.py 94.38% 84 / 89
pyhealth/tasks/climb_ecg.py 98.59% 70 / 71
pyhealth/tasks/competing_risks.py 88.46% 46 / 52
pyhealth/tasks/competing_risks_pbc.py 100.00% 56 / 56
pyhealth/tasks/covid_blues_classification.py 100.00% 11 / 11
pyhealth/tasks/covid_blues_severity.py 100.00% 15 / 15
pyhealth/tasks/cpsc2018_heartlang.py 97.98% 97 / 99
pyhealth/tasks/dearllm_mortality.py 98.29% 115 / 117
pyhealth/tasks/delphi_trajectory.py 91.28% 157 / 172
pyhealth/tasks/dementia_classification_ahepa.py 100.00% 93 / 93
pyhealth/tasks/dermoscopy_artifact_views.py 100.00% 130 / 130
pyhealth/tasks/ehr_foundation_model.py 94.12% 112 / 119
pyhealth/tasks/ehr_text_serialization.py 95.20% 238 / 250
pyhealth/tasks/ethos_tasks.py 100.00% 86 / 86
pyhealth/tasks/evicare_diagnosis.py 99.58% 238 / 239
pyhealth/tasks/fingerprint.py 98.29% 402 / 409
pyhealth/tasks/ham10000_classification.py 96.77% 30 / 31
pyhealth/tasks/isic2019_classification.py 100.00% 36 / 36
pyhealth/tasks/isic2020_melanoma_classification.py 100.00% 12 / 12
pyhealth/tasks/jichi_davis_grading.py 95.83% 23 / 24
pyhealth/tasks/kits23_classification.py 98.61% 71 / 72
pyhealth/tasks/kits23_segmentation.py 97.37% 37 / 38
pyhealth/tasks/length_of_stay_prediction.py 77.30% 109 / 141
pyhealth/tasks/lndb_classification.py 98.36% 60 / 61
pyhealth/tasks/lndb_texture.py 100.00% 26 / 26
pyhealth/tasks/maestro_mortality_mimic4.py 95.00% 38 / 40
pyhealth/tasks/medmod_decompensation_mimic4.py 95.40% 83 / 87
pyhealth/tasks/meds_outcome_tasks.py 100.00% 125 / 125
pyhealth/tasks/mortality_prediction.py 90.29% 400 / 443
pyhealth/tasks/multi_event_survival_rotterdam.py 100.00% 26 / 26
pyhealth/tasks/pad_ufes_20_classification.py 96.55% 28 / 29
pyhealth/tasks/ph2_artifact_classification.py 100.00% 41 / 41
pyhealth/tasks/physionet2012_inhospital_mortality.py 94.52% 138 / 146
pyhealth/tasks/physionet2012_mortality.py 96.20% 76 / 79
pyhealth/tasks/prior_exam_preference.py 93.64% 162 / 173
pyhealth/tasks/ptbxl_heartbeat.py 97.33% 73 / 75
pyhealth/tasks/query_focused_ehr.py 91.88% 147 / 160
pyhealth/tasks/readmission_prediction.py 94.76% 217 / 229
pyhealth/tasks/rsna_pneumonia_classification.py 92.31% 12 / 13
pyhealth/tasks/seizure_detection_helsinki.py 100.00% 149 / 149
pyhealth/tasks/signal_forecasting.py 100.00% 99 / 99
pyhealth/tasks/sleep_staging_hmc.py 99.06% 105 / 106
pyhealth/tasks/sleep_staging_isruc.py 100.00% 121 / 121
pyhealth/tasks/sleep_staging_nsrr.py 96.15% 125 / 130
pyhealth/tasks/sleep_staging_v2.py 98.75% 79 / 80
pyhealth/tasks/soz_localization_hup.py 98.96% 190 / 192
pyhealth/tasks/survival_time_to_event.py 95.10% 136 / 143
pyhealth/tasks/tcga_survival_prediction.py 84.21% 48 / 57
pyhealth/tasks/temple_university_EEG_tasks.py 83.24% 154 / 185
pyhealth/tasks/value_set_pair_classification.py 98.95% 188 / 190
pyhealth/tasks/variant_classification.py 89.29% 50 / 56
pyhealth/utils.py 83.70% 77 / 92

Workflow run · c10fc3d

@AxelNoun

Copy link
Copy Markdown
Contributor Author

I have merged upstream/master (4a173f7) into this branch. build and contribution-rules both pass on the merge commit, and the PR reports mergeable: true again.

The conflict was not textual, and the resolution changes this PR's API, so it needs your opinion.

Since the merge base, master added two inputs to the processed samples cache key, through proc_params in set_task: STORAGE_FORMAT, because a layout change makes the existing *.bin files unreadable, and split.to_dict() when a split= is given, because the split decides which patients fit the processors. This PR replaces that whole proc_params block with processors_fingerprint(), which only knew about the processors. Keeping my side of the conflict unchanged would therefore have silently dropped both inputs from the key: two different splits would have shared one samples_*.ld directory, and split.npz would have been read back from a cache built under a different split.

processors_fingerprint() now takes them as keyword arguments, left out of the payload when they are None, so a caller that passes neither keeps the two argument digest:

proc_fingerprint = processors_fingerprint(
    input_processors, output_processors,
    storage_format=STORAGE_FORMAT,
    split=split.to_dict() if split is not None else None,
)

Two consequences worth your attention.

It changes the digest. set_task always passes storage_format, so the samples directory name differs from the one this branch produced before the merge. Caches built from this branch are rebuilt once. That seemed preferable to keying them on an incomplete input set, but say so if you would rather handle it another way.

I had to modify a test you added recently, and I would rather flag it than let it pass unnoticed. tests/core/test_split_set_task.py::test_unsplit_cache_key_has_no_split_entry rebuilt the expected directory name as uuid.uuid5(uuid.NAMESPACE_DNS, json.dumps({...})). That asserts the implementation of the key rather than the property its name states, so it could not survive any change of scheme, including this one. I rewrote it against processors_fingerprint(..., split=None), which checks the same property without depending on how the digest is computed. For the same reason I made test_caches_from_the_old_storage_layout_are_not_reused meaningful again: as written it was an assertFalse against a key from a scheme this PR removes, so it had become vacuously true. I also added test_a_split_changes_the_cache_key. If you would rather keep the original assertions and have this PR preserve the uuid5 scheme, tell me and I will rework it that way instead.

This is also where the cache key question discussed in #916 is addressed, in case that helps when you triage either of them.

One request I cannot carry out myself: the status: conflict label is still on this PR although the conflict is resolved. It was applied by hand rather than by a workflow, and I only have read access here, so a maintainer needs to remove it.

Copy link
Copy Markdown
Collaborator

/review


Generated by Claude Code

master a ajouté BaseDataset._task_cache_dir(), qu'utilisent set_task et le
nouveau clear_task_cache, avec l'ancienne clé uuid5(json.dumps(vars(task))).
La méthode est conservée mais calcule désormais task_cache_name(task) : sans
cela, clear_task_cache chercherait un répertoire que set_task ne crée plus.

Autres conflits :
- base_task.py : docstring et task_card de master, import de
  record_init_args et paragraphe sur version de cette branche ;
- test_split_set_task.py : garder l'import de mock (nouveau test de master),
  retirer celui d'uuid, que plus aucun test n'utilise ;
- docs/api/tasks.rst : garder les entrées Task Fingerprint et Task Card.
record_init_args stored the raw init arguments in the instance
__dict__. Their default repr carries a memory address, so anything
that serialises vars(task) became unstable: the two cache-key tests
of EHRTextSerializationTask failed in CI. BaseTask now declares a
slot for them; they are still pickled, copied and fingerprinted, and
subclasses keep their __dict__.
Comment thread pyhealth/tasks/fingerprint.py Outdated
"task_class": _qualname(type(task)),
"task_name": getattr(task, "task_name", None),
"task_version": getattr(task, "version", "1"),
"init_args": _canon({k: v for k, v in init_args.items() if k not in excluded}, "init_args"),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Recording the raw init arguments here undoes the normalisation some tasks do on purposes, eg inside of SeizureDetectionCHBMIT stores subjects as tuple(sorted({normalize_subject(s) for s in subjects})) so that subjects=["chb01"] and subjects=["1"] share a cache. With the raw list in init_args, they get different keys again.

Instance_state already holds the effective configuration, so could the fingerprint use instance and class state only, and keep the recorded arguments in task_meta.json for readability? That would also let you drop the init wrapper and the slots / init_subclass on BaseTask?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good catch, thanks. I checked whether instance state alone is enough before changing it: every task in pyhealth/tasks stores each __init__ parameter (directly or after transformation) on the instance, and perturbing each parameter one at a time changes the state-only fingerprint in every case except the intended normalisations. Besides SeizureDetectionCHBMIT.subjects, LabNowcasting(event_tables=None) vs event_tables=["labevents"] hit the same issue (and LabNowcastingMIMIC3, which inherits it).

So the fingerprint now uses instance and class state only, and I removed the __init__ wrapper and the __slots__ / __init_subclass__ on BaseTask. One trade-off: without the wrapper there are no raw arguments left to record, so task_meta.json shows the effective configuration (instance and class state) rather than the arguments as passed. That felt like the more accurate thing to show, since it's what the key is computed from, but I'm happy to bring back a lightweight record of raw args for the sidecar only if you'd prefer. I also bumped FINGERPRINT_VERSION to 3 and added a regression test for both normalisation cases.

Raw __init__ arguments undid the normalisation some tasks apply on
purpose (SeizureDetectionCHBMIT.subjects, LabNowcasting.event_tables),
giving equivalent configurations different cache keys. The fingerprint
now uses instance and class state only, which already hold the
effective configuration. This removes the __init__ wrapper and the
__slots__/__init_subclass__ hooks on BaseTask. FINGERPRINT_VERSION -> 3.
@rianfyi rianfyi added status: automatic The PR will go through automatic review process. and removed status: conflict There is a merge conflict labels Nov 25, 2026
@rianfyi

rianfyi commented Nov 25, 2026

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.

Previous review

Reviewed commit 734c1eb

Comment thread pyhealth/tasks/fingerprint.py Outdated
]
if isinstance(obj, type):
return ["class", _qualname(obj)]
if isinstance(obj, (types.FunctionType, types.MethodType, types.BuiltinFunctionType)):

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed. A bound method now includes its instance's state, also for builtin methods such as {"a": 1}.get. End to end, set_task on two tasks differing only by Scaler(1).f / Scaler(2).f returned the first task's samples for both before this change, and builds two directories now.

Closures had the same gap (two closures from one factory share their source), so captured values, defaults and function attributes are included too. Functions with no source of their own, including several lambdas on one line, now raise in strict mode. Tests are in TestCallables.

Comment thread pyhealth/tasks/fingerprint.py Outdated
import pandas as pd

if isinstance(obj, (pd.DataFrame, pd.Series)):
values = pd.util.hash_pandas_object(obj, index=True).values

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed. The key now has column labels, Series name, index names, dtypes (with categories) and values, for pandas and polars. I dropped hash_pandas_object and hash_rows: the former also conflated 1 with "1" in object columns and raised on list cells. Cost for a 1M-row table: 1.3 s for a pandas string column, 2.9 s for a two-column polars frame. Tests are in TestTables.


# Include a structural hash of ``__call__``/``pre_filter`` source. Off by
# default: editing a comment should not invalidate a 40-minute cache build.
_HASH_SOURCE = os.environ.get("PYHEALTH_FINGERPRINT_SOURCE", "0") in ("1", "true", "True")

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added 39 tests: both environment variables, the non-strict fallbacks, source mode, callables, partial, pandas, polars, numpy, torch, dataclass, enum, path and other value types. Coverage of fingerprint.py from test_task_fingerprint.py alone is 99%.

They exposed more collisions of the same kind, fixed here: IntEnum and str enums, namedtuples, defaultdict and other container subclasses, array and tensor subclasses, masked and structured arrays, long regular expressions. bfloat16 and conjugated tensors crashed.


# Opt-out for environments with exotic task arguments. Strict mode is the
# default because a non-strict fallback reintroduces silent collisions.
_STRICT = os.environ.get("PYHEALTH_FINGERPRINT_STRICT", "1") not in ("0", "false", "False")

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Unchanged: the old keys in those cases were unstable or could collide. Happy to switch to warn-and-fall-back for one release if a maintainer prefers; it is a one-line change.

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

Previous review

AI Review

suggestion: need change
decision: need change

Thank you for this contribution. It replaces the json.dumps(default=str) cache keys with a typed, deterministic fingerprinter, and it adds a task_meta.json sidecar, BaseTask.version and fingerprint_exclude. The audit of failure modes is thorough, and the tests cover the main ones well. Coverage is good: the repository total is 85.08% against the 60% bar, and fingerprint.py is 83.4% against the 80% bar.

This touches the core part of the codebase. It adds class attributes (version, fingerprint_exclude) to BaseTask, which every task inherits. It also changes how BaseDataset.set_task and _task_cache_dir compute cache keys, and all components share those. It also orphans every existing task cache directory. That is why it can't be approved automatically, and a maintainer will need to decide.

To get this merged:

  1. Bound methods are fingerprinted by function source and qualname only, and __self__ is ignored (_canon_callable, around fingerprint.py:201). Methods of two differently configured instances therefore produce the same key, which is a silent stale-cache collision. Please include the bound instance's canonical state, or raise UnfingerprintableError.
  2. The pandas and polars digests leave out column labels (around fingerprint.py:258 and 265). Two DataFrames with renamed columns and the same values therefore share a key. Please include the column names (and the index names or dtypes) in the canonical form.
  3. Several branches have no tests: the non-strict fallback (PYHEALTH_FINGERPRINT_STRICT=0), PYHEALTH_FINGERPRINT_SOURCE, the callable and partial handling, and the pandas, polars, torch, dataclass and enum branches. Please add tests for them, including regression tests for items 1 and 2.

Optional suggestions:

  • The docs and the set_task docstring say configurations "can never share a cache". Please soften that wording, or make it true once items 1 and 2 are fixed.

  • The skipTest on ImportError in the normalisation test could hide a regression in CI. Consider making those optional dependencies available there.

  • The module docstring still reads as a proposal ("Proposed replacement..."). Please reword it to describe the current behaviour.

  • You asked whether to default to non-strict mode for a transition release. A maintainer is best placed to decide that. The current default is defensible, since the old silent keys could be wrong.

  • Warning: this PR can't be approved automatically because it touches the core part of PyHealth (base classes or shared code). To stay on automatic review, back out that part, or ask a maintainer to review it, then comment /review. If the next review finds this again, the PR switches to status: manual.

Reviewed commit 734c1eb

Bound methods and closures were keyed by name and source only, and
pandas/polars tables by their values only, so distinct configurations
could share a cache. Include the bound instance, captured values and
defaults, table labels and dtypes. Also cover enum mixins, container,
array and tensor subclasses, masked and structured arrays and long
regular expressions, and hash source with ast.unparse so that keys
match between Python 3.12 and 3.13. Wrapped tasks now contribute their
version, and memoized lookups no longer change the key.
FINGERPRINT_VERSION -> 4.
Comment thread pyhealth/tasks/fingerprint.py Outdated
]
if isinstance(obj, type):
return ["class", _qualname(obj)]
if isinstance(obj, (types.FunctionType, types.MethodType, types.BuiltinFunctionType)):

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed. A bound method now includes its instance's state, also for builtin methods such as {"a": 1}.get. End to end, set_task on two tasks differing only by Scaler(1).f / Scaler(2).f returned the first task's samples for both before this change, and builds two directories now.

Closures had the same gap (two closures from one factory share their source), so captured values, defaults and function attributes are included too. Functions with no source of their own, including several lambdas on one line, now raise in strict mode. Tests are in TestCallables.

Comment thread pyhealth/tasks/fingerprint.py Outdated
import pandas as pd

if isinstance(obj, (pd.DataFrame, pd.Series)):
values = pd.util.hash_pandas_object(obj, index=True).values

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed. The key now has column labels, Series name, index names, dtypes (with categories) and values, for pandas and polars. I dropped hash_pandas_object and hash_rows: the former also conflated 1 with "1" in object columns and raised on list cells. Cost for a 1M-row table: 1.3 s for a pandas string column, 2.9 s for a two-column polars frame. Tests are in TestTables.


# Include a structural hash of ``__call__``/``pre_filter`` source. Off by
# default: editing a comment should not invalidate a 40-minute cache build.
_HASH_SOURCE = os.environ.get("PYHEALTH_FINGERPRINT_SOURCE", "0") in ("1", "true", "True")

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added 39 tests: both environment variables, the non-strict fallbacks, source mode, callables, partial, pandas, polars, numpy, torch, dataclass, enum, path and other value types. Coverage of fingerprint.py from test_task_fingerprint.py alone is 99%.

They exposed more collisions of the same kind, fixed here: IntEnum and str enums, namedtuples, defaultdict and other container subclasses, array and tensor subclasses, masked and structured arrays, long regular expressions. bfloat16 and conjugated tensors crashed.


# Opt-out for environments with exotic task arguments. Strict mode is the
# default because a non-strict fallback reintroduces silent collisions.
_STRICT = os.environ.get("PYHEALTH_FINGERPRINT_STRICT", "1") not in ("0", "false", "False")

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Unchanged: the old keys in those cases were unstable or could collide. Happy to switch to warn-and-fall-back for one release if a maintainer prefers; it is a one-line change.

@AxelNoun

Copy link
Copy Markdown
Contributor Author

Pushed fixes for the three requested items. Also done:

  • The "can never share a cache" wording is gone; the module docstring now lists what the fingerprint does not see.
  • The normalisation test no longer skips on ImportError; those imports are core dependencies.
  • Function keys use ast.unparse instead of ast.dump, whose output changed between Python 3.12 and 3.13. Keys of the 140 shipped tasks that build without arguments are identical on 3.12 (Linux) and 3.13 (Windows).
  • EHRTextSerializationTask: using a task no longer changes its key (memoized lookups), and the wrapped task's version now counts.
  • The fingerprint API page no longer documents the module's imports (Any, Mapping, Path, PurePath), which imported-members in docs/conf.py pulled in.
  • FINGERPRINT_VERSION is 4. I updated the version and test counts in the description.

This PR is a change to the core by nature (the set_task cache key), so it needs a maintainer's decision rather than an automatic approval.

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

Previous review

Reviewed commit ebe269e

# Scripts and sessions all share the module name ``__main__``.
if src is None and not (importable and fn.__module__ != "__main__"):
if _STRICT:
raise UnfingerprintableError(

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in ad2c214. A lambda is now found in its parsed file rather than in the lines getsource() returns, so a lambda passed as the last argument of a multi-line call works. Lambdas that start on the same line are told apart by the source positions of their code, so (lambda x: x, lambda x: x + 1) no longer raises either. Only a callable whose source cannot be read raises, and the message now says that. Tests: test_lambda_on_a_line_that_is_not_a_statement, test_nested_lambdas, and test_lambdas_without_source_positions, which checks that under -X no_debug_ranges two different lambdas on one line still raise.

if isinstance(obj, np.generic):
# item() turns a datetime64[ns] into a bare int, drops the field names
# of a record and returns a longdouble unchanged.
if obj.dtype.kind in "biufc" and not isinstance(obj.item(), np.generic):

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in ad2c214. Numpy scalars now carry their dtype. They are handled before the Python scalars, because np.float64 and np.complex128 are also float and complex. test_numpy_scalars_keep_their_dtype covers float, int, bool, complex and str_.

args.append("raw_fallback=True")
return f"CodeDescriber({', '.join(args)})"

def __pyhealth_fingerprint__(self) -> dict[str, Any]:

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added to the description.

Comment thread pyhealth/datasets/base_dataset.py Outdated
schema.pkl # Saved SampleBuilder schema
split.npz # Sample indices per split part (with split= only)
*.bin # Processed sample files
{task_name}_{task_fingerprint}/ # One task configuration

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in ad2c214. Both docstrings show {slug}_{task_digest}/ and samples_{proc_digest}.ld/, and set_task says what the slug and the 16-character digests are.

@github-actions github-actions Bot added status: manual Pending maintainer's review and removed status: automatic The PR will go through automatic review process. labels Nov 26, 2026

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

Previous review

AI Review

suggestion: need change
decision: human review

Thank you for this thorough contribution. It replaces the fragile json.dumps(default=str) cache keys with a deterministic, typed fingerprint. It also adds a task_meta.json sidecar, BaseTask.version, fingerprint_exclude, and docs and tests for them. Coverage is well above the bar: fingerprint.py is at 99.7%, base_dataset.py at 93%, base_task.py at 87%, and the repository total is 86.7%.

This touches the core part of the codebase. It changes BaseTask by adding the inherited version and fingerprint_exclude attributes. It also changes BaseDataset.set_task, _task_cache_dir and the processor cache key. Every user's on-disk cache names change (FINGERPRINT_VERSION = 4), and strict mode now raises by default. A maintainer therefore needs to review it, so it can't be approved automatically.

The change is close. Two behaviours look wrong from reading the code:

To get this merged:

  1. In fingerprint.py (_structural_source and _canon_callable), a valid lambda can fail to get a source hash. This happens when its source line isn't a complete statement, for example the last argument of a multi-line call ending in None). ast.parse then fails and strict mode raises. The error message blames "one of several lambdas on a line", which is misleading. Please handle that case, for example by parsing the enclosing statement or wrapping the fragment. Failing that, make the error message accurate. Add a test for it.
  2. In _canon_numpy, numpy scalars are converted with .item(). As a result np.float32(0.5), np.float64(0.5) and 0.5 share one key, and so do np.int32(1), np.int64(1) and 1. That contradicts the module's "lossless, types not conflated" goal. Either tag numpy scalars with their dtype, or document the conflation as intentional. Add a test either way.

Optional suggestions:

  • The set_task docstring describes full digests and the raw task_name. The code uses a slugified name capped at 48 characters, a 16-character task digest and proc_fingerprint[:16]. Please align the docs with the code.

  • Mention the __pyhealth_fingerprint__ hooks and the docstring changes in ehr_text_serialization.py in the description.

  • pyhealth/benchmarks already canonicalises benchmark params. A one-line note on why this module is separate would help.

  • Switched to status: manual: it touches the core part of PyHealth (base classes or shared code), again after an earlier warning, so a maintainer will review this PR.

Reviewed commit ebe269e

# Scripts and sessions all share the module name ``__main__``.
if src is None and not (importable and fn.__module__ != "__main__"):
if _STRICT:
raise UnfingerprintableError(

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in ad2c214. A lambda is now found in its parsed file rather than in the lines getsource() returns, so a lambda passed as the last argument of a multi-line call works. Lambdas that start on the same line are told apart by the source positions of their code, so (lambda x: x, lambda x: x + 1) no longer raises either. Only a callable whose source cannot be read raises, and the message now says that. Tests: test_lambda_on_a_line_that_is_not_a_statement, test_nested_lambdas, and test_lambdas_without_source_positions, which checks that under -X no_debug_ranges two different lambdas on one line still raise.

if isinstance(obj, np.generic):
# item() turns a datetime64[ns] into a bare int, drops the field names
# of a record and returns a longdouble unchanged.
if obj.dtype.kind in "biufc" and not isinstance(obj.item(), np.generic):

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in ad2c214. Numpy scalars now carry their dtype. They are handled before the Python scalars, because np.float64 and np.complex128 are also float and complex. test_numpy_scalars_keep_their_dtype covers float, int, bool, complex and str_.

args.append("raw_fallback=True")
return f"CodeDescriber({', '.join(args)})"

def __pyhealth_fingerprint__(self) -> dict[str, Any]:

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added to the description.

Comment thread pyhealth/datasets/base_dataset.py Outdated
schema.pkl # Saved SampleBuilder schema
split.npz # Sample indices per split part (with split= only)
*.bin # Processed sample files
{task_name}_{task_fingerprint}/ # One task configuration

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in ad2c214. Both docstrings show {slug}_{task_digest}/ and samples_{proc_digest}.ld/, and set_task says what the slug and the 16-character digests are.

@AxelNoun

Copy link
Copy Markdown
Contributor Author

Pushed ad2c214 for the review: the lambda and numpy scalar fixes, the cache layout docstrings, and a note in the module docstring on why pyhealth.benchmarks keeps its own serialisation (its params must decode back into Python objects, so it accepts only JSON values and importable classes and functions). FINGERPRINT_VERSION is 5, since numpy scalar keys change.

The five new tests fail on the previous commit and pass now. On Linux, tests/core gives the same results as master except for this PR's tests: the remaining failures come from optional packages missing in my environment (MONAI, nibabel, a tokenizer backend). The keys of the 98 tasks that build without arguments are identical on Python 3.12 (Linux) and 3.13 (Windows). I updated the description: version 5, the EHR task keys, and the test counts.

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

Previous review

Reviewed commit ad2c214

Comment thread pyhealth/datasets/base_dataset.py Outdated
logger.info(
"Task cache key %s -- derived from instance state, schemas and task "
"version. Full spec: %s",
task_cache_name(task),

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in c0234ba. write_task_metadata now walks the task once and digests the spec it writes, and the log line uses the directory name instead of recomputing it. A cache hit walks the task once and a miss twice, where it was two and four times. A new test checks that the sidecar fingerprint equals task_fingerprint.


def __pyhealth_fingerprint__(self) -> Any:
"""The wrapped object; for a task, its ``version`` and schemas too."""
return task_spec(self.obj) if isinstance(self.obj, BaseTask) else self.obj

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in c0234ba. The wrapped task is no longer printed with json.dumps(vars(...)); _Keyed gets its class name as a readable string, and the key comes from the hook as before. test_base_task_with_mixed_dict_keys wraps a task holding {1: "a", "1": "b"}, which raised before.

Comment thread docs/api/datasets.rst
the body of ``__call__``. Neither does upgrading PyHealth to a version whose
task or processor code changed. In those cases the old samples are reused
without a warning. Clear the cache to rebuild them:
task or processor code changed, unless the task's ``version`` changed too. In

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in c0234ba. The page now says that functions stored on a task are the exception: their code is part of the hash, so editing one, in user code or in PyHealth, gives a new cache.

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

Previous review

AI Review

suggestion: approve
decision: human review

Thank you for this contribution. It replaces the json.dumps(default=str) cache keys with a deterministic, typed fingerprint. It also adds a task_meta.json sidecar, BaseTask.version and fingerprint_exclude, slugified task directory names, and docs and tests for all of it. The diff looks correct and complete to me, and the description explains the intent well.

Why a maintainer needs to look at it: the change touches the core part of the codebase.

  • It changes BaseDataset.set_task and _task_cache_dir.
  • It adds the version and fingerprint_exclude class attributes to the BaseTask base class.
  • It changes every task and processor cache key.
  • Strict mode now makes set_task raise UnfingerprintableError where the old code silently produced a key.

Because it changes these shared contracts, it can't be approved automatically. I'm not seeing a blocking problem in the code itself.

Coverage meets the bar:

  • Whole repository: 87.12%, against a 60% bar.
  • New pyhealth/tasks/fingerprint.py: 98.28%.
  • base_dataset.py: 93.22%.
  • ehr_text_serialization.py: 95.63%.
  • base_task.py: 86.67%.

Sharing: the new fingerprint module is shared utility code, and the description states the purpose, so no extra explanation is needed.

Optional suggestions:

  • In ehr_text_serialization.py, _Keyed's key is still built with json.dumps(vars(base_task), default=str). The fingerprint no longer uses that string, and the call can raise TypeError on mixed-key attributes. Consider simplifying it.
  • set_task computes the task fingerprint several times (the cache name, the sidecar and the log line). You could compute it once and reuse it.
  • docs/api/datasets.rst says upgrading PyHealth doesn't invalidate caches. Function-valued task attributes do have their source hashed, so the wording could be more precise.
  • Your description's "review call" on strict mode and the cache-pruning question are best settled by a maintainer.

Reviewed commit ad2c214

…tring

write_task_metadata computed the spec twice and set_task recomputed the
cache name for its log line; the sidecar now digests the spec it writes,
and the log uses the directory name. EHRTextSerializationTask no longer
builds the wrapped task's string with json.dumps(vars(...)), which the
fingerprint ignores and which raised on dicts with mixed key types. The
cache docs say that functions stored on a task are keyed by their code.
Comment thread pyhealth/datasets/base_dataset.py Outdated
logger.info(
"Task cache key %s -- derived from instance state, schemas and task "
"version. Full spec: %s",
task_cache_name(task),

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in c0234ba. write_task_metadata now walks the task once and digests the spec it writes, and the log line uses the directory name instead of recomputing it. A cache hit walks the task once and a miss twice, where it was two and four times. A new test checks that the sidecar fingerprint equals task_fingerprint.


def __pyhealth_fingerprint__(self) -> Any:
"""The wrapped object; for a task, its ``version`` and schemas too."""
return task_spec(self.obj) if isinstance(self.obj, BaseTask) else self.obj

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in c0234ba. The wrapped task is no longer printed with json.dumps(vars(...)); _Keyed gets its class name as a readable string, and the key comes from the hook as before. test_base_task_with_mixed_dict_keys wraps a task holding {1: "a", "1": "b"}, which raised before.

Comment thread docs/api/datasets.rst
the body of ``__call__``. Neither does upgrading PyHealth to a version whose
task or processor code changed. In those cases the old samples are reused
without a warning. Clear the cache to rebuild them:
task or processor code changed, unless the task's ``version`` changed too. In

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in c0234ba. The page now says that functions stored on a task are the exception: their code is part of the hash, so editing one, in user code or in PyHealth, gives a new cache.

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

Previous review

Reviewed commit c0234ba


# Opt-out for environments with exotic task arguments. Strict mode is the
# default because a non-strict fallback reintroduces silent collisions.
_STRICT = os.environ.get("PYHEALTH_FINGERPRINT_STRICT", "1") not in ("0", "false", "False")

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Kept strict as the default, and said so in 8ead696: docs/api/tasks.rst now states that strict mode is the default and a change, and names what raises (an iterator, a sparse tensor, a function whose source cannot be read, such as one made by exec()). A lambda defined in a notebook cell keeps working: its source is read from the cell. The non-strict fallback gives those tasks the same key on every run, so two configurations can share a cache, which is the failure this PR removes; I would rather not make it the default. The "Breaking" section of the description is written to be copied into the release notes, since CHANGELOG.md is filled at release time. If a maintainer prefers warn-and-fallback for one release, it is the default of _STRICT on one line.

self.assertEqual(payload["spec"], json.loads(json.dumps(task_spec(Readmission()))))


class TestRealTasks(unittest.TestCase):

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added in 8ead696: TestShippedTasks.test_every_shipped_task_fingerprints imports every module of pyhealth.tasks, builds each concrete task (102 at present), with arguments listed for the six that need them, and checks task_fingerprint and task_cache_name. Two are not built, with the reason: _CHAOSSegmentationBase refuses construction and ValueSetCompletion reads an index built from data. A task whose constructor needs a missing optional package (soundfile for BMDHSDiseaseClassification) is skipped with the import message.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Correction to the count above: the test finds 107 concrete tasks and builds 105 of them, not 102.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Follow-up in 4088040: on the merge with current master the test failed on seven tasks added there that need constructor arguments (CardiologyDetection, CLIMBECGClassification and others). Listing every such task would break the test each time master gains one, so the six tasks listed with arguments must still build, any other task whose constructor refuses its defaults is skipped with the reason, and the test fails if a built task cannot be fingerprinted or if fewer than 90 are built. On the merge with master 5213360, 77 tests pass, with 10 tasks skipped.

Comment thread pyhealth/tasks/fingerprint.py Outdated
def write_task_metadata(
cache_dir: Path,
task: Any,
extra: dict[str, Any] | None = None,

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Removed in 8ead696. tests/core/test_llm_ehr_encoder.py also checks task_fingerprint now instead of json.dumps(vars(task)).

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

Previous review

AI Review

suggestion: need change
decision: human review

Thank you for this thorough contribution. Replacing the json.dumps(..., default=str) cache keys with a deterministic, typed canonicaliser, a task_meta.json sidecar, BaseTask.version and fingerprint_exclude is a real improvement. The tests are extensive, and coverage is well above the bar: fingerprint.py is at 98.3%, base_task.py at 86.7%, base_dataset.py at 93.2%, and the whole repository at 87.1%.

The change is close. These points need to be settled before merging.

Core code touched: The change edits BaseTask, which gains version and fingerprint_exclude that every task inherits. It also rewrites BaseDataset.set_task and _task_cache_dir, which compute the cache key for every task. Every existing task cache key changes. This is shared base-class behaviour, so it can't be approved automatically and a maintainer will need to decide.

To get this merged:

  1. The strict default (PYHEALTH_FINGERPRINT_STRICT=1) makes set_task raise UnfingerprintableError for inputs that used to work. Examples are lambdas or closures defined in notebooks or exec'd code, iterators, and sparse or meta tensors. Your description leaves this open as a review call. Please resolve it in the PR. I suggest defaulting to warn-and-fallback for this transition release, with strict mode opt-in. If you keep strict as the default, say so clearly in the docs and changelog.
  2. Strict mode now applies to every shipped task, but TestRealTasks checks only a handful of them. Please add a test that instantiates each concrete shipped BaseTask subclass with its defaults and confirms task_fingerprint succeeds. Tasks that need arguments can be skipped explicitly. This shows the strict default doesn't break existing tasks.

Optional suggestions:

  • The extra parameter of write_task_metadata is unused. Consider removing it.
  • tests/core/test_llm_ehr_encoder.py still asserts on json.dumps(vars(task)) rather than the real key. Consider updating it.
  • The description of what counts as the same configuration appears in three doc locations (datasets.rst, tasks.rst and the set_task docstring). Consider trimming the repetition.
  • Open questions 2 and 3 (absolute paths and cache pruning) are fine to leave to maintainers.

Reviewed commit c0234ba

Strict mode is the default, so a shipped task whose state cannot be
fingerprinted would fail in set_task. A new test builds every concrete task
in pyhealth.tasks, with the arguments listed for the few that need them, and
checks that it fingerprints. The EHR serialization tests check the real key
instead of json.dumps(vars(task)), write_task_metadata loses its unused
extra argument, and the task docs say that strict mode is the default and
what now raises.

# Opt-out for environments with exotic task arguments. Strict mode is the
# default because a non-strict fallback reintroduces silent collisions.
_STRICT = os.environ.get("PYHEALTH_FINGERPRINT_STRICT", "1") not in ("0", "false", "False")

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Kept strict as the default, and said so in 8ead696: docs/api/tasks.rst now states that strict mode is the default and a change, and names what raises (an iterator, a sparse tensor, a function whose source cannot be read, such as one made by exec()). A lambda defined in a notebook cell keeps working: its source is read from the cell. The non-strict fallback gives those tasks the same key on every run, so two configurations can share a cache, which is the failure this PR removes; I would rather not make it the default. The "Breaking" section of the description is written to be copied into the release notes, since CHANGELOG.md is filled at release time. If a maintainer prefers warn-and-fallback for one release, it is the default of _STRICT on one line.

self.assertEqual(payload["spec"], json.loads(json.dumps(task_spec(Readmission()))))


class TestRealTasks(unittest.TestCase):

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added in 8ead696: TestShippedTasks.test_every_shipped_task_fingerprints imports every module of pyhealth.tasks, builds each concrete task (102 at present), with arguments listed for the six that need them, and checks task_fingerprint and task_cache_name. Two are not built, with the reason: _CHAOSSegmentationBase refuses construction and ValueSetCompletion reads an index built from data. A task whose constructor needs a missing optional package (soundfile for BMDHSDiseaseClassification) is skipped with the import message.

Comment thread pyhealth/tasks/fingerprint.py Outdated
def write_task_metadata(
cache_dir: Path,
task: Any,
extra: dict[str, Any] | None = None,

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Removed in 8ead696. tests/core/test_llm_ehr_encoder.py also checks task_fingerprint now instead of json.dumps(vars(task)).

On the merge with master the new test failed on seven new tasks that need
constructor arguments. The tasks listed with arguments must still build;
any other task whose constructor refuses its defaults is skipped with the
reason, and the test fails if a built task cannot be fingerprinted or if
fewer than 90 tasks were built.
@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.

Previous review

Reviewed commit 4088040


# Opt-out for environments with exotic task arguments. Strict mode is the
# default because a non-strict fallback reintroduces silent collisions.
_STRICT = os.environ.get("PYHEALTH_FINGERPRINT_STRICT", "1") not in ("0", "false", "False")

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Checked: a TupleTimeTextProcessor holding the prajjwal1/bert-tiny tokenizer fingerprints without error. Its key is the same in two processes and changes with the model and with max_length. c10fc3d adds test_processor_with_a_tokenizer_has_a_cache_key to test_tuple_time_text_tokenizer.py. The strict default is kept, as discussed in the thread above.

Comment thread pyhealth/tasks/fingerprint.py Outdated
"fingerprint_version": FINGERPRINT_VERSION,
"task_class": _qualname(type(task)),
"task_name": getattr(task, "task_name", None),
"task_version": getattr(task, "version", "1"),

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in c10fc3d: task_name and version now go through _canon like the rest of the spec. test_version_and_name_are_canonicalised checks that a numpy.int64 version fingerprints, and that 2, "2" and np.int64(2) give three keys.

"fingerprint": _spec_digest(spec),
"created_at": _dt.datetime.now(_dt.UTC).isoformat(),
"pyhealth_version": pyhealth_version,
"spec": spec,

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Documented in c10fc3d: docs/api/tasks.rst now says that task_meta.json holds the task attributes as they are, strings included, and that fingerprint_exclude keeps an attribute such as a credential out of it.

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

Previous review

AI Review

suggestion: approve
decision: human review

Thank you for this contribution. It replaces the json.dumps(..., default=str) cache keys with a deterministic, typed fingerprint for tasks and processors. It adds a task_meta.json sidecar, BaseTask.version and fingerprint_exclude, path-safe task names, and docs and tests to match. The problems it targets (silent collisions, PYTHONHASHSEED dependence, mixed-key crashes) are real, and the description and docs state the cache-invalidation break clearly.

The change looks ready to merge from a code, docs and test point of view. Coverage is well above the bar: the whole repository is at 87.23% against the 60% guideline, and the new fingerprint.py is at 98.29% against 80%. The modified files I checked are also above 80%.

This touches the core part of the codebase, so it can't be approved automatically and a maintainer will need to decide. It modifies BaseDataset.set_task and BaseDataset._task_cache_dir, which are the shared dataset-to-task caching path. It adds the version and fingerprint_exclude class attributes to the BaseTask base class, which every task inherits. It also changes every task and processor cache key, and strict mode now raises on attributes that can't be fingerprinted. That is a shared cache-format contract affecting all components, and your description already raises it as a review call.

Optional suggestions:

  • Canonicalise version (for example str(version)) so a non-string value can't make the key unstable.
  • The sidecar writes raw instance state to disk, which is worth a short docs note.
  • Consider whether to ship a pruning helper for orphaned caches, as you ask in your open questions.

Reviewed commit 4088040

task_name and version bypassed the canonicaliser, so a numpy integer or a
packaging Version made json.dumps raise a bare TypeError. Both now go
through _canon like the rest of the spec. The task docs say that
task_meta.json holds attributes verbatim and how to keep one out, and a
test checks that a pre-fitted processor holding a HuggingFace tokenizer
gets a stable cache key.

# Opt-out for environments with exotic task arguments. Strict mode is the
# default because a non-strict fallback reintroduces silent collisions.
_STRICT = os.environ.get("PYHEALTH_FINGERPRINT_STRICT", "1") not in ("0", "false", "False")

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Checked: a TupleTimeTextProcessor holding the prajjwal1/bert-tiny tokenizer fingerprints without error. Its key is the same in two processes and changes with the model and with max_length. c10fc3d adds test_processor_with_a_tokenizer_has_a_cache_key to test_tuple_time_text_tokenizer.py. The strict default is kept, as discussed in the thread above.

Comment thread pyhealth/tasks/fingerprint.py Outdated
"fingerprint_version": FINGERPRINT_VERSION,
"task_class": _qualname(type(task)),
"task_name": getattr(task, "task_name", None),
"task_version": getattr(task, "version", "1"),

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in c10fc3d: task_name and version now go through _canon like the rest of the spec. test_version_and_name_are_canonicalised checks that a numpy.int64 version fingerprints, and that 2, "2" and np.int64(2) give three keys.

"fingerprint": _spec_digest(spec),
"created_at": _dt.datetime.now(_dt.UTC).isoformat(),
"pyhealth_version": pyhealth_version,
"spec": spec,

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Documented in c10fc3d: docs/api/tasks.rst now says that task_meta.json holds the task attributes as they are, strings included, and that fingerprint_exclude keeps an attribute such as a credential out of it.

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

AI Review

suggestion: need change
decision: human review

Thank you for this PR. It replaces the json.dumps(..., default=str) cache key with a deterministic, typed fingerprint for tasks and processors. It also adds a readable task_meta.json sidecar, a version attribute, fingerprint_exclude, and path-safe task names. The tests are thorough and coverage is well above the bar: fingerprint.py is at 98%, base_dataset.py at 93%, and the whole repository at 87%. The change is close, but one problem needs fixing first.

Core change. The PR touches shared code that every task and dataset depends on:

  • BaseTask gains the version and fingerprint_exclude attributes.
  • BaseDataset.set_task and _task_cache_dir now build their cache keys through the new fingerprint module.
  • Every existing task cache key changes, which orphans existing caches.
  • Strict mode now raises UnfingerprintableError where the old code silently produced a key.

Changes to a base class and to a shared API contract can't be approved automatically. A maintainer will need to decide, and your open questions on the default strict mode and cache migration are theirs to weigh.

To get this merged:

  1. In tests/core/test_tuple_time_text_tokenizer.py, the insertion of test_processor_with_a_tokenizer_has_a_cache_key landed between the existing @​pytest.mark.skipif(not TRANSFORMERS_AVAILABLE, ...) decorator and test_tokenizer_integration_in_pyhealth_workflow. The decorator now guards the new test, and the integration test has no skip guard. Without transformers installed, the integration test will fail. Please put the decorator back on the integration test, and add it to the new test too if that one also needs transformers.

Optional suggestions:

  • Add a short note in the docs that absolute paths are hashed as-is (your open question 2), so caches aren't portable across machines.
  • The changelog suggestion about du -sh ~/.cache/pyhealth would be helpful to include in the release notes.

Reviewed commit c10fc3d

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.

5 participants