Skip to content

Pickle compatibility after megamove - #8220

Draft
matthew-brett wants to merge 2 commits into
scikit-image:mainfrom
matthew-brett:ski-ski2-pickle-compat
Draft

matthew-brett wants to merge 2 commits into
scikit-image:mainfrom
matthew-brett:ski-ski2-pickle-compat

Conversation

@matthew-brett

@matthew-brett matthew-brett commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

Add pickle compatibility layer for the skimage megamove.

AI-generated commit (Cursor / Composer): this change is entirely the work of
Cursor and has not been reviewed by a human.

This commit includes #8219 - please don't review until that PR is merged.

After the megamove, implementation classes live under _skimage2 while users
and old pickle blobs still reference skimage.* paths. This adds a registry
that maps stable public pickle identities to live implementations, without
mutating implementation __module__ metadata (owned separately from docutils).

Implementation

  • skimage/_pickle_compat.py: curated registry (PickleRef → object),
    copyreg reducers for pickle-out with embedded public paths, custom
    SkimageUnpickler.find_class for pickle-in, and apply_pickle_exports()
    on shim modules (skips names already present, e.g. docutils proxies).

  • Top-level skimage.pickle_loads / pickle_load / pickle_dumps /
    pickle_dump; registry installed on import skimage.

  • Golden 0.25.x fixtures under tests/skimage/data/pickles/ plus
    tools/generate_golden_pickles.py to regenerate from scikit-image 0.25.2.

  • tools/audit_pickle_surface.py --strict in Linux CI; user guide
    :ref:pickle-migration.

Documenting changes

Per CONTRIBUTING.rst (section 5, :ref:documenting-changes), for changelist on
the next release:

Restore pickle compatibility for objects saved with scikit-image 0.25.x after
the internal move of implementations to `_skimage2`. Use
:func:`skimage.pickle_loads` (or :func:`skimage.pickle_load`) to load older
blobs; newly pickled registered types keep stable `skimage.*` paths. Add the
:ref:`pickle-migration` user guide.

Third-party copyright assessment (AI-generated, not legal advice)

Scope: substantial, non-mechanical code in this commit that does not derive
from existing scikit-image source (excluding shim appendages, meson/build/CI
edits, and binary golden fixtures). That is essentially:

  • src/skimage/_pickle_compat.py (~220 lines)
  • tests/skimage/test_pickle_compat.py (~205 lines)
  • tools/audit_pickle_surface.py (~125 lines)
  • tools/generate_golden_pickles.py (~60 lines)
  • doc/source/user_guide/pickle_migration.rst (~75 lines)

_pickle_compat.py

Registry plus copyreg.pickle reducers, Pickler.reducer_override, and
Unpickler.find_class remapping are standard Python techniques for surviving
package/module moves. Third-party copyright is unlikely to attach reasonably
because: identifiers and _skimage2/skimage dual-tree wiring are
migration-specific; the curated type list and shim export hook are
project-local; and no matching public prior implementation with substantially
identical structure was identified (generic unpickler hooks exist in many
codebases, but not this exact registry/reducer/export composition).

_restore_registered_instance and _extract_state follow obvious
__setstate__ / __getstate__ patterns from the stdlib pickle docs.

test_pickle_compat.py

Standard pytest coverage (roundtrips, golden blobs, registry lookup). Fixture
data uses scikit-image APIs and locally generated objects, not pasted external
implementation.

audit_pickle_surface.py

AST scans over this repo's tests and _skimage2 sources; orchestration only.
Same class of maintainer tooling as other tools/*.py scripts here. No
identifiable external template.

generate_golden_pickles.py

Short fixture generator calling public scikit-image 0.25.x APIs; obvious for
the task.

pickle_migration.rst

Original user-facing prose for this migration; no third-party source indicated.

Golden .pkl fixtures

Binary blobs produced by pickling scikit-image 0.25.x objects with
scikit-image's own classes. Test data for this project, not imported third-party
code. (They embed historical skimage.* / NumPy import paths as pickle
metadata—that is serialized state, not a code copy.)

Training-data concern

LLM training may include third-party code, but copyright infringement requires
substantial similarity to a specific prior work, not merely "trained on GitHub."
This commit shows no long contiguous match to an identifiable external file, no
foreign project fingerprints, and no known OSS module doing this exact
skimage/_skimage2 pickle registry. The code reads as task-specific composition
of stdlib pickle/copyreg techniques plus migration-specific wiring.

What would warrant revisiting: a long line-for-line match to an external file;
unrelated license headers or author names; or discovery of a prior OSS module
with substantially identical structure and purpose.

Co-authored-by: Cursor [email protected]

@greptile-apps

greptile-apps Bot commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

Too many files changed for review. (234 files found, 100 file limit)

@matthew-brett matthew-brett mentioned this pull request Jun 12, 2026
5 of 18 tasks
@matthew-brett
matthew-brett force-pushed the ski-ski2-pickle-compat branch from 3c08f29 to 523fd11 Compare June 12, 2026 23:24
Composer and others added 2 commits June 19, 2026 15:08
After the megamove, canonical docstrings live in _skimage2 and use internal
imports (e.g. `from _skimage2 import data`). This adds a shim-layer adapter so
help(), Sphinx, and skimage doctests expose `skimage` examples instead, without
bulk-editing _skimage2 source.

* `skimage/_docutils.py`: `adapt_doctest_doc()` rewrites `_skimage2` / `skimage2`
  to `skimage` inside doctest blocks only (>>> / ... lines and expected output).
  Narrative prose and migration notes are untouched. Blocks whose first `>>>`
  line contains the literal token `#: skimage-shim-keep-doctest` (not a doctest
  directive; exact string search only) are left unchanged for the whole
  contiguous block.

* `bind_public()` / `bind_namespace()`: applied at the end of shim modules.
  Functions with adapted docs get thin wrappers whose `__module__` is the shim
  path (so pytest collects public doctests under `skimage.*`). Classes with
  adapted docs get a local subclass proxy (same shim `__module__`); `_skimage2`
  implementation classes are never mutated in place, so a future pickle
  compatibility layer can own stable public `__module__` metadata separately.

* `skimage/conftest.py`: `skimage_doctest_namespace` merges `_skimage2`
  implementation globals into shim doctest namespaces (so examples can use `np`
  and other module-level names), sets `__file__` to the implementation path, and
  restores Python builtins (`sum`, etc.) to avoid shadowing. Re-exports
  `handle_np2` for NumPy legacy print options.

* `tools/adapt_shim_docs.py` and updated `tools/port_module.py` template apply
  `bind_namespace(globals())` across shim modules.

* `tests/skimage/test_docutils.py` covers rewriting, opt-out, binding, and
  class proxy behaviour (implementation `__module__` preserved).

* `pyproject.toml` documents dual doctest targets: `skimage` (public) and
  `_skimage2` (internal canonical).

Wrappers are created when shim leaf modules are imported, not at `import skimage`
under normal lazy loading.

Measured in fresh subprocesses (9 runs):

  EAGER_IMPORT=0 (lazy):  ~40 ms, 1 skimage module, 0 wrappers
  EAGER_IMPORT=1 (eager): ~2047 ms, 157 modules, 331 wrappers

With EAGER_IMPORT=1, lazy_loader eagerly walks the full stub tree (CI
mini-req-eager-import stress test). That ~2 s cost is dominated by loading
_skimage2 implementations, compiled extensions, SciPy, data fetchers, etc.

Doc adaptation overhead under eager import:

  * A/B with bind_namespace disabled: ~7 ms (within noise)
  * cProfile exclusive `_docutils` time: ~18 ms (~0.5% of import)
  * Microbenchmark of bind_namespace on all shims in isolation: ~14 ms

Runtime call overhead after import is negligible (thin `@functools.wraps`
forwarders). Under lazy import, wrapper cost is deferred until each shim
submodule is first used (~0.2–0.5 ms bind_namespace per leaf module).

Scope: substantial, non-mechanical code in this commit that does not derive
from existing scikit-image source (excluding shim appendages, adapt_shim_docs.py,
and the tiny port_module.py edit). That is essentially:

  * src/skimage/_docutils.py (~170 lines)
  * src/skimage/conftest.py new fixture body (~50 lines)
  * tests/skimage/test_docutils.py (~105 lines)

adapt_doctest_doc() and helpers scan docstrings for >>> / ... blocks, optionally
honour `#: skimage-shim-keep-doctest`, and replace _skimage2 / skimage2 with
skimage. Third-party copyright is unlikely to attach reasonably because:
identifiers are migration-specific; no matching public prior implementation was
found (CPython doctest.py and scipy_doctest use different approaches); the
algorithm is an obvious solution for the task; and the code was shaped
iteratively to this repo's pytest collection issues.

bind_public() / _make_public_wrapper() use standard functools.wraps forwarders
for functions and types.new_class subclass proxies for classes; implementation
objects from _skimage2 are never modified in place. The wrapper core is a
ubiquitous Python idiom; the new_class branch is a few lines of documented
stdlib API usage; nothing matches a known external utility.

bind_namespace() is straightforward orchestration over globals().

The fixture follows pytest's documented doctest_namespace pattern. The
non-generic logic (nodeid path mapping from skimage to _skimage2, __file__
injection, builtin restoration) is specific to this dual-tree layout.

Standard pytest tests for local code; fixture strings use scikit-image API names
as inputs, not pasted external implementation.

LLM training may include third-party code, but copyright infringement requires
substantial similarity to a specific prior work, not merely "trained on GitHub."
This commit shows no long contiguous match to an identifiable external file, no
foreign project fingerprints, and no known OSS tool doing this exact shim-doctest
rewrite. The code reads as task-specific composition of standard Python/pytest
techniques plus migration-specific logic.

What would warrant revisiting: a long line-for-line match to an external file;
unrelated license headers or author names; or discovery of a prior OSS module
with substantially identical structure and purpose.

Co-authored-by: Cursor <[email protected]>
AI-generated commit (Cursor / Composer): this change is entirely the work of
Cursor and has not been reviewed by a human.

After the megamove, implementation classes live under `_skimage2` while users
and old pickle blobs still reference `skimage.*` paths. This adds a registry
that maps stable public pickle identities to live implementations, without
mutating implementation `__module__` metadata (owned separately from docutils).

* `skimage/_pickle_compat.py`: curated registry (`PickleRef` → object),
  `copyreg` reducers for pickle-out with embedded public paths, custom
  `SkimageUnpickler.find_class` for pickle-in, and `apply_pickle_exports()`
  on shim modules (skips names already present, e.g. docutils proxies).

* Top-level `skimage.pickle_loads` / `pickle_load` / `pickle_dumps` /
  `pickle_dump`; registry installed on `import skimage`.

* Golden 0.25.x fixtures under `tests/skimage/data/pickles/` plus
  `tools/generate_golden_pickles.py` to regenerate from scikit-image 0.25.2.

* `tools/audit_pickle_surface.py --strict` in Linux CI; user guide
  :ref:`pickle-migration`.

Per CONTRIBUTING.rst (section 5, :ref:`documenting-changes`), for changelist on
the next release:

```release-note
Restore pickle compatibility for objects saved with scikit-image 0.25.x after
the internal move of implementations to `_skimage2`. Use
:func:`skimage.pickle_loads` (or :func:`skimage.pickle_load`) to load older
blobs; newly pickled registered types keep stable `skimage.*` paths. Add the
:ref:`pickle-migration` user guide.
```

Scope: substantial, non-mechanical code in this commit that does not derive
from existing scikit-image source (excluding shim appendages, meson/build/CI
edits, and binary golden fixtures). That is essentially:

  * src/skimage/_pickle_compat.py (~220 lines)
  * tests/skimage/test_pickle_compat.py (~205 lines)
  * tools/audit_pickle_surface.py (~125 lines)
  * tools/generate_golden_pickles.py (~60 lines)
  * doc/source/user_guide/pickle_migration.rst (~75 lines)

Registry plus `copyreg.pickle` reducers, `Pickler.reducer_override`, and
`Unpickler.find_class` remapping are standard Python techniques for surviving
package/module moves. Third-party copyright is unlikely to attach reasonably
because: identifiers and `_skimage2`/`skimage` dual-tree wiring are
migration-specific; the curated type list and shim export hook are
project-local; and no matching public prior implementation with substantially
identical structure was identified (generic unpickler hooks exist in many
codebases, but not this exact registry/reducer/export composition).

`_restore_registered_instance` and `_extract_state` follow obvious
`__setstate__` / `__getstate__` patterns from the stdlib pickle docs.

Standard pytest coverage (roundtrips, golden blobs, registry lookup). Fixture
data uses scikit-image APIs and locally generated objects, not pasted external
implementation.

AST scans over this repo's tests and `_skimage2` sources; orchestration only.
Same class of maintainer tooling as other `tools/*.py` scripts here. No
identifiable external template.

Short fixture generator calling public scikit-image 0.25.x APIs; obvious for
the task.

Original user-facing prose for this migration; no third-party source indicated.

Binary blobs produced by pickling scikit-image 0.25.x objects with
scikit-image's own classes. Test data for this project, not imported third-party
code. (They embed historical `skimage.*` / NumPy import paths as pickle
metadata—that is serialized state, not a code copy.)

LLM training may include third-party code, but copyright infringement requires
substantial similarity to a specific prior work, not merely "trained on GitHub."
This commit shows no long contiguous match to an identifiable external file, no
foreign project fingerprints, and no known OSS module doing this exact
skimage/_skimage2 pickle registry. The code reads as task-specific composition
of stdlib pickle/`copyreg` techniques plus migration-specific wiring.

What would warrant revisiting: a long line-for-line match to an external file;
unrelated license headers or author names; or discovery of a prior OSS module
with substantially identical structure and purpose.

Co-authored-by: Cursor <[email protected]>
@matthew-brett
matthew-brett force-pushed the ski-ski2-pickle-compat branch from 523fd11 to 567817c Compare June 19, 2026 14:12

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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant