Repository navigation
Conversation
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>
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>
Test CoverageTotal: 87.26% (51238 / 58722 lines)
|
|
I have merged The conflict was not textual, and the resolution changes this PR's API, so it needs your opinion. Since the merge base,
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. I had to modify a test you added recently, and I would rather flag it than let it pass unnoticed. 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 |
|
/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__.
| "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"), |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
|
/review |
| ] | ||
| if isinstance(obj, type): | ||
| return ["class", _qualname(obj)] | ||
| if isinstance(obj, (types.FunctionType, types.MethodType, types.BuiltinFunctionType)): |
There was a problem hiding this comment.
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.
| import pandas as pd | ||
|
|
||
| if isinstance(obj, (pd.DataFrame, pd.Series)): | ||
| values = pd.util.hash_pandas_object(obj, index=True).values |
There was a problem hiding this comment.
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") |
There was a problem hiding this comment.
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") |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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:
- Bound methods are fingerprinted by function source and qualname only, and
__self__is ignored (_canon_callable, aroundfingerprint.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 raiseUnfingerprintableError. - The pandas and polars digests leave out column labels (around
fingerprint.py:258and265). 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. - Several branches have no tests: the non-strict fallback (
PYHEALTH_FINGERPRINT_STRICT=0),PYHEALTH_FINGERPRINT_SOURCE, the callable andpartialhandling, 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_taskdocstring say configurations "can never share a cache". Please soften that wording, or make it true once items 1 and 2 are fixed. -
The
skipTestonImportErrorin 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 tostatus: 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.
| ] | ||
| if isinstance(obj, type): | ||
| return ["class", _qualname(obj)] | ||
| if isinstance(obj, (types.FunctionType, types.MethodType, types.BuiltinFunctionType)): |
There was a problem hiding this comment.
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.
| import pandas as pd | ||
|
|
||
| if isinstance(obj, (pd.DataFrame, pd.Series)): | ||
| values = pd.util.hash_pandas_object(obj, index=True).values |
There was a problem hiding this comment.
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") |
There was a problem hiding this comment.
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") |
There was a problem hiding this comment.
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.
|
Pushed fixes for the three requested items. Also done:
This PR is a change to the core by nature (the |
|
/review |
| # Scripts and sessions all share the module name ``__main__``. | ||
| if src is None and not (importable and fn.__module__ != "__main__"): | ||
| if _STRICT: | ||
| raise UnfingerprintableError( |
There was a problem hiding this comment.
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): |
There was a problem hiding this comment.
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]: |
There was a problem hiding this comment.
Added to the description.
| 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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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:
- In
fingerprint.py(_structural_sourceand_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 inNone).ast.parsethen 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. - In
_canon_numpy, numpy scalars are converted with.item(). As a resultnp.float32(0.5),np.float64(0.5)and0.5share one key, and so donp.int32(1),np.int64(1)and1. 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_taskdocstring describes full digests and the rawtask_name. The code uses a slugified name capped at 48 characters, a 16-character task digest andproc_fingerprint[:16]. Please align the docs with the code. -
Mention the
__pyhealth_fingerprint__hooks and the docstring changes inehr_text_serialization.pyin the description. -
pyhealth/benchmarksalready 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( |
There was a problem hiding this comment.
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): |
There was a problem hiding this comment.
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]: |
There was a problem hiding this comment.
Added to the description.
| 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 |
There was a problem hiding this comment.
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.
|
Pushed ad2c214 for the review: the lambda and numpy scalar fixes, the cache layout docstrings, and a note in the module docstring on why The five new tests fail on the previous commit and pass now. On Linux, |
|
/review |
| logger.info( | ||
| "Task cache key %s -- derived from instance state, schemas and task " | ||
| "version. Full spec: %s", | ||
| task_cache_name(task), |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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_taskand_task_cache_dir. - It adds the
versionandfingerprint_excludeclass attributes to theBaseTaskbase class. - It changes every task and processor cache key.
- Strict mode now makes
set_taskraiseUnfingerprintableErrorwhere 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 withjson.dumps(vars(base_task), default=str). The fingerprint no longer uses that string, and the call can raiseTypeErroron mixed-key attributes. Consider simplifying it. set_taskcomputes 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.rstsays 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.
| logger.info( | ||
| "Task cache key %s -- derived from instance state, schemas and task " | ||
| "version. Full spec: %s", | ||
| task_cache_name(task), |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
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.
|
/review |
|
|
||
| # 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") |
There was a problem hiding this comment.
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): |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Correction to the count above: the test finds 107 concrete tasks and builds 105 of them, not 102.
There was a problem hiding this comment.
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.
| def write_task_metadata( | ||
| cache_dir: Path, | ||
| task: Any, | ||
| extra: dict[str, Any] | None = None, |
There was a problem hiding this comment.
Removed in 8ead696. tests/core/test_llm_ehr_encoder.py also checks task_fingerprint now instead of json.dumps(vars(task)).
There was a problem hiding this comment.
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:
- The strict default (
PYHEALTH_FINGERPRINT_STRICT=1) makesset_taskraiseUnfingerprintableErrorfor inputs that used to work. Examples are lambdas or closures defined in notebooks orexec'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. - Strict mode now applies to every shipped task, but
TestRealTaskschecks only a handful of them. Please add a test that instantiates each concrete shippedBaseTasksubclass with its defaults and confirmstask_fingerprintsucceeds. Tasks that need arguments can be skipped explicitly. This shows the strict default doesn't break existing tasks.
Optional suggestions:
- The
extraparameter ofwrite_task_metadatais unused. Consider removing it. tests/core/test_llm_ehr_encoder.pystill asserts onjson.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.rstand theset_taskdocstring). 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") |
There was a problem hiding this comment.
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): |
There was a problem hiding this comment.
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.
| def write_task_metadata( | ||
| cache_dir: Path, | ||
| task: Any, | ||
| extra: dict[str, Any] | None = None, |
There was a problem hiding this comment.
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.
|
/review |
|
|
||
| # 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") |
There was a problem hiding this comment.
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.
| "fingerprint_version": FINGERPRINT_VERSION, | ||
| "task_class": _qualname(type(task)), | ||
| "task_name": getattr(task, "task_name", None), | ||
| "task_version": getattr(task, "version", "1"), |
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 examplestr(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") |
There was a problem hiding this comment.
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.
| "fingerprint_version": FINGERPRINT_VERSION, | ||
| "task_class": _qualname(type(task)), | ||
| "task_name": getattr(task, "task_name", None), | ||
| "task_version": getattr(task, "version", "1"), |
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
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.
|
/review |
There was a problem hiding this comment.
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:
BaseTaskgains theversionandfingerprint_excludeattributes.BaseDataset.set_taskand_task_cache_dirnow build their cache keys through the new fingerprint module.- Every existing task cache key changes, which orphans existing caches.
- Strict mode now raises
UnfingerprintableErrorwhere 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:
- In
tests/core/test_tuple_time_text_tokenizer.py, the insertion oftest_processor_with_a_tokenizer_has_a_cache_keylanded between the existing@pytest.mark.skipif(not TRANSFORMERS_AVAILABLE, ...)decorator andtest_tokenizer_integration_in_pyhealth_workflow. The decorator now guards the new test, and the integration test has no skip guard. Withouttransformersinstalled, 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 needstransformers.
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/pyhealthwould be helpful to include in the release notes.
Reviewed commit c10fc3d
Summary
The literal request in #916 is already satisfied on current master:
set_taskalready hashesvars(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 (PYTHONHASHSEEDreorders sets; defaultrepr()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 tovars(), no code version, unsanitisedtask_namepath 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.pyhealth.tasks.fingerprint: deterministic, lossless fingerprints; raisesUnfingerprintableErrorinstead of silently hashingrepr().__init__leaves them (soTask()≡Task(window=15d)when that is the default, and spellings a task normalises, such asSeizureDetectionCHBMIT(subjects=["chb01"])andsubjects=["1"], share a key), class-level config on the MRO, and an explicitBaseTask.versionfor logic changes.fingerprint_excludedenylist for non-semantic args (num_workers,verbose, …).task_meta.jsonsidecar next to the cache so an opaque digest is auditable;set_tasklogs its path.OSError(they run outside the build lock).CrossMap/ mixed-keycode_vocab).task_nameis slugified before it is used as a path component (BenchmarkEHRShot/guo_los).CodeDescriberand_Keyedinehr_text_serialization.pyget a__pyhealth_fingerprint__hook, so the keys of EHR text serialization tasks change too: a describer is keyed on its lookup andraw_fallback, not on its memoized lookups, which grew with use, and a wrapped task counts with itsversionand schemas.versionmust be bumped when__call__changes,fingerprint_exclude,UnfingerprintableError.Breaking
Cache only.
FINGERPRINT_VERSION = 5changes every key, orphaning existing<cache_dir>/tasksdirectories. 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 suggestdu -sh ~/.cache/pyhealthbefore upgrading.API, potential. Strict mode now raises
UnfingerprintableErroron an argument that cannot be fingerprinted, where the old code produced a silent key.PYHEALTH_FINGERPRINT_STRICT=0restores the fallback with a warning. Review call: invert the default for a transition release?Open questions for maintainers
versionvs source hash.PYHEALTH_FINGERPRINT_SOURCE=1folds a structural (AST) hash of__call__/pre_filterinto 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.PurePathis 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.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 teardownWinError 32from litdata file locks is pre-existing on master (identical 6 passed / 5 failed / 1 error on unmodified0a75f99)PYTHONHASHSEEDin{1, 42, 999}: identical fingerprints.tmp, validtask_meta.jsontools/check_pr_rules.pyagainst0a75f99Refs #916