Skip to content

B2: Pickle reader - #154

Open
Claptar wants to merge 3 commits into
mainfrom
fix/b2
Open

Claptar wants to merge 3 commits into
mainfrom
fix/b2

Conversation

@Claptar

@Claptar Claptar commented Dec 4, 2026

Copy link
Copy Markdown
Contributor

Batch B2 of #149 (wave 1, for 0.17.11): the pycisTopic pickle reader keeps its documented promise. A crafted pickle is refused with an Error: line, never a crash, and what it reads is written as anndata would. Pickles stay documented as trusted input, as agreed in #149.

Closes #136 (F174, F175, F176, F177, F178, F179, F180).

What changes

  • F174, a crafted pickle is refused instead of crashing the reader. Every object is now checked before numpy, scipy or pandas act on it, as the docs promise, and convert ends with an Error: line. The defect's details stay out of this description until the fix is released; the tests show them.
  • F180, lengths a pickle names are held to the bytes it holds. A range, a RangeIndex, or the shape of an empty array or a sparse matrix may be no longer than the pickle's own bytes. A frame's columns are counted against its blocks before pandas makes room for them, and a frame with no rows names no more columns than the bytes read. The converter compares the name counts with the matrix before listing any names.
  • F177, the sniffer reads only a file's head. At most SNIFF_BYTES (64 KiB), and it stops at the first byte unless that byte opens a pickle. Detecting a large text table (a header starting "B" read as an opcode taking 1.87 GB) no longer reads or inflates it.
  • F175, labels a store cannot hold are renamed, and such samples refused. A column label holding /, or empty, is renamed (a/b to a_b, "" to _) with a warning, to a name no other column has, as convert already renames a loom's fields. Before, /var wrote an h5ad anndata could not open, and /uns/x a stray uns["x"], both with exit 0. A path_to_fragments sample like that is refused before anything is written: renaming it would break its match with sample_id and the cell names, which end with it. anndata refuses both kinds of key itself.
  • F176, object integers keep their values. They are written as int64, or uint64 past it, as pandas reads them (263 used to come back as -263). They become floats, with a warning, only where no integer dtype holds them, or where a missing value sits beside an integer past 2**53.
  • F179, pickles saved by pandas 3 convert. pandas 3 keeps text in Arrow arrays, which pickle as pyarrow's own rebuilding. That layout is now decoded here, without pyarrow: every offset is checked to rise within the text it indexes, the validity bitmap to cover the values, and the text to be UTF-8, before a byte is read. pandas 2's string[pyarrow] and pre-2.3 StringDtype states read too. This also clears the STATUS.md follow-up "A pickle holding pandas 3's Arrow strings is refused".
  • F178, coverage of the hardening. formats/pickled.py goes from 83.4% to 99.6% (with the test files of this batch). The lines left are two __repr__s and two defensive repeats of checks every construction route already makes. Crafted pickles are still loaded in a child process first, then here once the child shows them refused, where coverage sees the check. One table-driven test reaches every refusal, a pickle crafted for each.

An independent review of the first commit found no memory-safety bypass, but a few gaps, fixed in the second commit with tests:

  • Three ways a pickle of a few hundred bytes still took 1.5 to 2 GB before its refusal: Arrow text sized before its offsets were counted; a Series' name or a frame's attrs, which pandas' setters hash, given a dtype over a huge index; pandas 1.5's manager state, checked only for its count of columns before pandas built from it. Arrow offsets are now counted first. Each pandas class takes only the state form pandas 1.5 to 3 pickles it in, with its values checked; a name and attrs' keys must be Python's own values. The manager state goes through the same full check as a built manager before pandas builds anything, so a block placed outside the columns is now a refusal rather than pandas' bounds error.
  • A regression in the first commit: names were counted with len and listed with list, which differ for a table. Names must now be a list, a 1-d array, an index or a Series.
  • Older costs, made worse by nothing here but cheap to fix: a frame's attrs were deep-copied once per column written, and frames sharing a manager each checked it in full. An integer past any float raised mid-write; it is now written as text, with a warning.

A second pass of the same review over that commit (third commit):

  • A regression from the second commit: Arrow text carrying pandas' cache was refused. pandas 3's read-only flag on a view was refused too, from the start; every pandas 3 Series with a text index carries one. Both now read.
  • An older amplification of the same kind as F180: a value whose parts a pickle shares, such as a tuple of the same tuple at each level, costs a few bytes a level but comes to twice as many values a level. It took seconds to hash as a key, gigabytes to show in a refusal, and gigabytes of text as a name. A key is now counted, its shared parts once, against the bytes the pickle holds before anything hashes it, and nests 32 deep at most. Refusals show what they name in brief. Names must be text or numbers. Only text, numbers and flat lists of them are written as text: a column holding more is left out with a warning, and such a label is refused.
  • pandas' NA was refused as a dict key under pandas 3, whose NA class moved module; it reads.

Docs: docs/reference/formats/cistopic.md (the checks, pandas 3, column labels and samples), docs/reference/commands.md (the new refusals under convert), docs/troubleshooting.md (both refusal messages), docs/reference/testing.md (the three test files' rows).

Tests

  • Each finding has a regression test whose docstring starts with its ref and says what went wrong, checked against an oracle:
    • F174: scipy's check_format and pandas' Categorical.from_codes call the crafted objects invalid;
    • F175: anndata reads every renamed column back, and refuses a / key itself;
    • F176: pd.to_numeric reads the integers as uint64;
    • F177: the 1.87 GB length pickletools read from "arco";
    • F179: pandas, with pyarrow, reads the same bytes; pyarrow's own validate(full=True) refuses each malformed layout we refuse;
    • F180: tracemalloc peak while refusing.
  • The first commit's 58 regression tests were run against main's sources: 57 fail there, and the one that passes is a case main already refused. Each review round's tests were written against cases reproduced on the commit before it.
  • Each audit repro now prints OK.
  • pytest -m "not integration": 4,203 passed, 9 skipped. pytest -m perf: 209 passed.
  • The two pandas 1.5 pickle tests in test_external_readers.py (integration) pass: written under pandas 1.5.3, converted here under pandas 3 and under pandas 2.2.3. The three pickle test files also pass at pandas 2.2.3, the floor.

Follow-ups noticed, outside this batch's files

  • util/names.storable renames /, "", . and .., but not the names Zarr v2 keeps for its metadata (.zarray, .zattrs, .zgroup, .zmetadata). A column or field with one of those labels still writes a Zarr v2 store (--zarr-format 2) that anndata cannot open, with exit 0. That affects loom's and SCope's fields as much as these frames, so the fix belongs in storable.
  • Lengths are held to a pickle's inflated bytes, so a gzipped pickle of a few KB can still name tens of millions of cells. Memory stays in proportion to the inflated pickle, which is held whole by design, as for any gzipped pickle.
  • The unit suite never runs at pandas 2.2.3, the pickle extra's floor: the floors job resolves the dev extra's pandas 3.0. This batch's reader tests pass at 2.2.3 locally. Tests that read output back with anndata cannot run there, because anndata 0.13 needs pandas 2.3. The integration test converting a pandas 1.5 pickle under pandas 2.2.3 passes.

Changelog entry

For 0.17.11's ### Fixed:

  • A crafted pycisTopic pickle is refused rather than crash convert
    (#136). Pickles are
    trusted input, but the reader promises to check what numpy, scipy and
    pandas are given before they act on it, and a crafted pickle could get
    past that: convert crashed, with no Error: line. Every object is now
    checked before they act on it.
  • A pickle cannot ask for memory out of proportion to its size
    (#136). A length it
    names without holding the data for it, or a value it builds from one part
    shared many times over, is held to the bytes it holds, and counted before
    anything is made for it: a pickle of a few hundred bytes made the reader
    take hundreds of MiB, or gigabytes, before refusing it. Names must be text
    or numbers, and only text, numbers and flat lists of them are written as
    text.
  • Detecting a large text table no longer reads it
    (#136). The pickle
    sniffer reads 64 KiB at most. A table whose header began with "B" was read
    as a pickle's 1.87 GB of bytes, and a gzipped one inflated.
  • Column labels holding /, or empty, are renamed with a warning
    (#136), as a loom's
    fields are: /var wrote an h5ad anndata could not open, and /uns/x a
    stray uns["x"], both with exit 0. A sample in path_to_fragments like
    that is refused instead, since a renamed key would no longer match
    sample_id and the cell names.
  • Integers held as object keep their values past int64
    (#136): 263 was
    written as -2
    63. They are written as uint64, as pandas reads them, and
    as floats, with a warning, only where no integer dtype holds them.
  • A pickle saved by pandas 3 converts
    (#136). pandas 3 keeps
    text in Arrow arrays, whose pickles were refused. Their text is now decoded
    without pyarrow, every offset checked first.

🤖 Generated with Claude Code

Claptar and others added 3 commits December 4, 2026 15:55
A crafted pickle is refused with an Error line rather than crash the
reader, as the docs promise. Lengths a pickle names are held to the bytes
it holds, and the sniffer reads only a file's head. Column labels a store
cannot hold as names are renamed, and such fragments samples refused.
Object integers past int64 keep their values. pandas 3's Arrow text
reads, without pyarrow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Each pandas class's state is taken only in the form pandas 1.5 to 3
pickles it in, with its values checked: a frame's name and attrs' keys,
which pandas' setters hash, must be Python's own values. pandas 1.5's
manager state is checked as a built manager is, shapes and positions
included, before pandas builds from it. Arrow text's offsets are counted
before room is made for its values. A manager shared by many frames is
checked once. Names that list otherwise than they count (a table) are
refused. A frame's attrs are copied once, not once per column, and an
integer past any float is written as text.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A value whose parts a pickle shares (a tuple of the same tuple at each
level) costs a few bytes a level but comes to twice as many values a
level. A key is counted, its shared parts once, against the bytes the
pickle holds before anything hashes it, and nested 32 deep at most;
refusals show what they name in brief; names must be text or numbers;
only text, numbers and flat lists of them are written as text. pandas
3's Arrow text read with its cache and a view's read-only flag, and
pandas' NA read as a key under pandas 3.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Copilot AI balanced review requested due to automatic review settings December 4, 2026 21:56

Copilot AI left a comment

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.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Dec 4, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-12-04T21:58:09.909727Z 999bf2d PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@github-actions

github-actions Bot commented Dec 4, 2026

Copy link
Copy Markdown
Contributor

Test Results (py3.13)

4 003 tests   3 990 ✅  9m 28s ⏱️
    1 suites     13 💤
    1 files        0 ❌

Results for commit 999bf2d.

@github-actions

github-actions Bot commented Dec 4, 2026

Copy link
Copy Markdown
Contributor

Test Results (py3.12)

4 003 tests   3 990 ✅  11m 13s ⏱️
    1 suites     13 💤
    1 files        0 ❌

Results for commit 999bf2d.

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

Development

Successfully merging this pull request may close these issues.

B2: Pickle reader

2 participants