Skip to content

[Data] Block unpickling of untrusted bytes during datasource reads - #66402

Open
sampan-s-nayak wants to merge 19 commits into
ray-project:masterfrom
sampan-s-nayak:data-untrusted-unpickling-guard
Open

sampan-s-nayak wants to merge 19 commits into
ray-project:masterfrom
sampan-s-nayak:data-untrusted-unpickling-guard

Conversation

@sampan-s-nayak

@sampan-s-nayak sampan-s-nayak commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Ray Data now refuses to unpickle untrusted bytes while datasource code runs. Unpickling bytes from a file or an external service can run arbitrary code, and Ray Data hits this in two ways:

  1. Pickled-object Arrow columns. A table can hold a column stored as ray.data.arrow_pickled_object, and any later task in the job unpickles it, not necessarily the read task. Affected sources include Parquet, Arrow IPC, Lance, Delta, Iceberg, Hudi, BigQuery, ClickHouse, Databricks UC and HuggingFace.
  2. Libraries that unpickle during the read, such as np.load(allow_pickle=True), torch.load(weights_only=False), webdataset .pkl and the zarr Pickle codec.

Before

A few readers called raise_on_pickle_object_columns on the tables they produced. Every other format, every library unpickle inside a read and every driver-side read (for example in a datasource constructor) went unchecked.

After

  • Mechanism. An audit hook on pickle.find_class and a per-thread forbid flag. While the flag is set, any unpickle that loads a class or function raises UntrustedUnpicklingError, a ValueError. Nothing is exempt, including ray.cloudpickle.
  • Pickled-object columns. ArrowPythonObjectType.__arrow_ext_deserialize__ refuses while the flag is set. A file or stream whose schema declares the type is therefore refused when pyarrow parses the schema, before any row is read, so the column never reaches a block that a later task could unpickle.
  • Where the flag is set:
    • Datasource construction, through a metaclass on Datasource.
    • The new guarded_get_read_tasks() and guarded_estimate_inmemory_data_size() entry points. Authors still implement get_read_tasks() and estimate_inmemory_data_size(), and the framework calls only the guarded methods.
    • Each next() on a read function's iterator, so a fused UDF that runs between yields is not covered.
    • Driver-side DSv2 schema inference and reader creation.
    • The deprecated create_reader().
  • Opt-outs:
    • allow_unsafe_unpickling() around a single call. Ray uses it for ray.get of its own objects; readers use it behind an explicit option such as allow_pickle.
    • RAY_DATA_AUTOLOAD_PICKLE_OBJECT_SCALAR=1 turns the guard off for a whole job.

Changes users can see:

  • A file whose schema has a pickled-object column is refused even when the read doesn't select that column (read_parquet(f, columns=["id"])). pyarrow rebuilds the type of every column in the schema, and this is where the check runs. The error message says so and names the env var.
  • A Datasource subclass that also inherits from a class with its own metaclass needs a metaclass derived from both, for example class Meta(type(Datasource), type(Other)).
  • A legacy create_reader() that returns an object without subclassing Reader is wrapped in an adapter and keeps working.
flowchart TD
    subgraph Before
        subgraph BS[Subsystem: IO]
            B1[Datasource constructor / get_read_tasks] --> B2[read fn]
            B2 --> B3[a few readers: raise_on_pickle_object_columns]
            B3 --> B4[block with pickled column]
            B4 --> B5[any downstream task unpickles]
        end
    end
    subgraph After
        subgraph AS[Subsystem: IO]
            A0[audit hook on pickle.find_class + per-thread forbid flag]
            A1[construction via metaclass, guarded_get_read_tasks / guarded_estimate_inmemory_data_size]
            A2[read fn: each next under the flag]
            A3[arrow_pickled_object schema refused at parse]
            A4[allow_unsafe_unpickling around ray.get / explicit opt-ins]
            A1 --> A2 --> A3
            A0 -.-> A1
            A0 -.-> A2
            A4 -.-> A2
        end
    end
    classDef removed fill:#ffcdd2,stroke:#c62828,color:#000
    classDef added fill:#c8e6c9,stroke:#2e7d32,color:#000
    classDef changed fill:#fff9c4,stroke:#f9a825,color:#000
    class B3,B5 removed
    class A0,A3,A4 added
    class A1,A2 changed
Loading

Not covered: helper threads that a reader starts itself. The flag is per-thread, and today those threads (the schema-inference pool, footer reader actors, the mcap summary pool) read only metadata. The datasource agent rules and BUGBOT.md flag:

  • New unguarded entry points or threads.
  • Direct calls to the hooks instead of the guarded_* methods.
  • allow_unsafe_unpickling() without an explicit opt-in.

Subsystems

IO carries the behavioral change: the guard module, the datasource base classes and the readers' opt-ins. The block / data format change is the ArrowPythonObjectType refusal. The edits in API (read_api), logical planning and physical planning only switch callers to the guarded entry points.

Testing

  • pytest python/ray/data/tests/unit/test_untrusted_unpickling.py python/ray/data/tests/unit/test_object_extension.py: all pass locally.
  • The cluster tests in python/ray/data/tests/test_untrusted_unpickling.py and the existing datasource suites run in CI. I couldn't start a local cluster on my dev box.
  • Reviewer verification on 58d5c9c: a Parquet file whose pickled column runs os.system on load was refused on V1 and V2, and the payload never ran.

Duplicate check

I searched open PRs for unpickling, pickle data, arrow_pickled_object and pickle guard. The only match is this PR.

AI assistance

I wrote this PR with AI assistance (Claude Code). I reviewed every changed line and ran the tests listed above.

🤖 Generated with Claude Code

@sampan-s-nayak sampan-s-nayak added the go add ONLY when ready to merge, run all tests label Sep 23, 2026
@sampan-s-nayak
sampan-s-nayak force-pushed the data-untrusted-unpickling-guard branch from bcb76d2 to 14e4db2 Compare September 23, 2026 09:03
dstrodtman added a commit that referenced this pull request Sep 24, 2026
## Why are these changes needed?

MyST Markdown is the standard for Ray doc pages. This PR converts the
`ray-core/` user guide from reStructuredText to MyST: 80 pages across
the top-level directory and the `actors/`, `objects/`, `scheduling/`,
`patterns/`, `fault_tolerance/`, `internals/`, `compiled-graph/`,
`direct-transport/`, `examples/`, and `tasks/` subtrees.

The conversion is **format-only and faithful**. No prose changed. Every
cross-reference label is kept byte-for-byte, so external `{ref}` and
`:ref:` callers keep resolving, and no URLs change, because Sphinx maps
`foo.rst` and `foo.md` to the same `foo.html`. The rendered HTML matches
`/en/master` except for the small, explained differences listed under
[Render differences from
`/en/master`](#render-differences-from-enmaster).

This PR combines nine PRs that were developed separately to make each
construct class easier to verify: #66353, #66355, #66377, #66380,
#66410, #66414, #66415, #66417, and #66425. This PR supersedes them.
Apart from the last two commits, its diff is identical to their union.

### How to review

There's one commit per original PR, so you can review commit by commit.
Each commit is that PR's full diff squashed, and within each one the
conversion and the soft-wrap reflow are already combined. The last two
commits are a one-line toctree fix in `user-guide.rst` and that page's
own conversion to `user-guide.md`, which the separate PRs left for last
to avoid churning the shared toctree page.

| Commit | Pages | New constructs |
|---|---|---|
| `patterns/` (#66353) | 22 design-pattern and anti-pattern pages |
Prose, `literalinclude`, figures |
| Top-level prose (#66355) | `accelerator-types`, `advanced-topics`,
`fault-tolerance`, `head-node-memory-management`, `internals`,
`ray-generator` | Toctree normalization, `orphan` frontmatter |
| Tab pages (#66377) | `tasks`, `namespaces`, `ray-dag` | sphinx-design
tabs |
| Doctest pages (#66380) | `actors`, `configure`, `miscellaneous`,
`objects`, `starting-ray`, `tips-for-first-time`, `user-spawn-processes`
| Executed `testcode`, autodoc in `{eval-rst}` |
| Table pages (#66410) | `cross-language`,
`resource-isolation-with-cgroupv2` | `{list-table}`, tables inside
definition lists |
| Prose subtrees (#66414) | `fault_tolerance/` (5), `internals/` (8),
`compiled-graph/` (5 of 6), `direct-transport/` (2),
`examples/monte_carlo_pi`, `examples/overview`,
`tasks/dynamic_generators` | Definition lists, Mermaid in comments |
| `actors/` and `objects/` (#66415) | 7 + 2 pages | Doctest-heavy tabs |
| `scheduling/` (#66417) | 6 pages | Shared help partial |
| Jupyter (#66425) | `using-ray-with-jupyter` | Paragraphs that start
with a number |

Three pages under `ray-core/`, outside `api/`, stay RST:

- `compiled-graph/compiled-graph-api.rst` is four `autosummary` blocks
and nothing else, so it stays RST like the other API reference trees.
- `tasks/nested-tasks.rst` and `handling-dependencies.rst` are named in
`doc/BUILD.bazel`'s `doctest[core]` exclusions, so they convert in a
later PR that also updates that file.

### Other files this PR touches

- `ray-core/user-guide`: the section's toctree page converts to MyST
too. Its `patterns/index.rst` and `scheduling/index.rst` entries are now
extensionless, like their siblings. Sphinx resolves either form, so that
part is for consistency, not a fix. The only reference to the page, the
toctree entry in `walkthrough.md`, is already extensionless.
- `_includes/_help-links.md` is new. `scheduling/memory-management` and
`scheduling/ray-oom-prevention` end with the shared `_help.rst` partial,
which MyST can't include natively. `_help-links.md` is the same
four-item list in Markdown. It can't be named `_help.md`, because Sphinx
treats `_help.md` and `_help.rst` as the same document. `_help.rst`
stays for the three RST pages that still include it:
`ray-references/faq`, `cluster/vms/user-guides/community/yarn`, and
`tune/key-concepts`.
- `ray-core/examples/gentle_walkthrough.ipynb`,
`ray-core/examples/map_reduce.ipynb`, and
`ray-contribute/publishing-examples-legacy.md` pointed at
`examples/overview.rst` and now point at the `.md`.

No other file changes. Every other reference to these pages is
extensionless or goes through a label.

## Render differences from `/en/master`

`render_diff.py` against `/en/master` over all 80 converted pages: 65
render identically, and the other 15 differ only in the ways listed
below.

### Intended changes, where MyST renders what the source meant

- **`configure`, TLS step 1.** On `/en/master`, the `# Alternatively,
this command automatically encode ...` paragraph has no blank line
before its `.. code-block:: bash`, so docutils swallows the directive
into the paragraph. The `kubectl` command renders as a block quote with
its `--` flags turned into en-dashes. It now renders as the bash code
block the author intended. The leading `#` is escaped (`\#`) so the
paragraph stays a paragraph rather than becoming an H1.
- **`miscellaneous`, Benchmark.** "Increase the ARP cache size:" renders
on `/en/master` as a definition list, because its sub-items are indented
four spaces rather than two. It now renders as the nested bullet list
the source describes.
- **`objects/serialization`, custom-serialization list.** On
`/en/master`, the first item's `testoutput` is indented 2 spaces under
an item whose content starts at column 3. docutils ends the list,
renders the output in a stray block quote, and restarts the list at 2.
The MyST keeps the output inside item 1, so the three items render as
one list.

### Link changes

Relative `.html` links become Sphinx roles, because MyST reads a
scheme-less link target as a cross-reference and fails
`fail_on_warning`. They render as internal references rather than
external links. Four of them only worked on `/en/master` through a site
redirect, so each now points at the page the redirect already lands on.

- `tasks`: `` `Object refs <objects.html>`__ `` becomes `` {doc}`Object
refs <objects>` ``.
- `namespaces`: `` `Driver Options <configure.html#driver-options>`__ ``
becomes `` {ref}`Driver Options <java-driver-options>` ``. The href
anchor changes from `#driver-options` to `#java-driver-options`, and
both ids sit on the same section.
- `configure`: `` `documentation <package-ref.html#ray.init>`__ ``
becomes `` {doc}`documentation <api/index>` ``, where
`ray-core/package-ref.html` already redirects.
- `configure`: `` `Python time format <strftime.org>`__ `` becomes
`[Python time format](https://strftime.org/)`. The scheme-less target
resolved as a relative path that redirected to `https://strftime.org/`.
- `configure`: the `` `Java Applications`_ `` named reference becomes
`[Java Applications](#java-applications)`, the same href it renders to
today.
- `miscellaneous`: `` `Prometheus endpoint <ray-metrics.html>`_ ``
becomes `` {ref}`Prometheus endpoint <collect-metrics>` ``.
`ray-core/ray-metrics.html` redirects to `cluster/metrics.html`, whose
top label is `collect-metrics`.
- `starting-ray`: the `Configuration`, `Deployment section`,
`Kubernetes`, `YARN`, and `SLURM` links become `{doc}` roles to the same
pages.

### Anchor changes

- **`starting-ray`, "What's next?"** MyST slugs the heading `whats-next`
where docutils produced `what-s-next`. A compat target isn't possible,
because `what-s-next` is already a global label in
`cluster/getting-started.md`. No authored link in the repo points at
this anchor. The generated toctree entries in `advanced-topics` and
`user-guide` follow the new slug automatically, so those two pages'
render diffs show the same `#whats-next` change and nothing else.
- **`objects/serialization`, "Plasma Object Store".** On `/en/master`,
the link `` `Plasma object store <…>`_ `` creates a named target that
collides with the heading's implicit name, so docutils gives the section
the id `plasma-store`, plus a stray `id1`. MyST creates no named target
for a link, so the section takes its heading slug,
`plasma-object-store`. The `plasma-store` label still renders as an
anchor on the section, so `#plasma-store` links keep working.

### Constructs with no MyST equivalent

- **Line blocks** become Markdown hard line breaks, which render as
`<p>` plus `<br>` instead of `div.line-block`, with the same lines
visible. This affects the two links at the end of `ray-dag` and five
cells in the `tips-for-first-time` API table.

### Invisible markup differences

These don't change what a reader sees:

- **Definition-list class.** MyST's `<dl>` carries `class="simple myst"`
where docutils emits no class or `simple`. The class has no styling. It
appears in `cross-language` (3), `internals/metric-exporter`,
`direct-transport`, and `scheduling/memory-management`.
- **RST comments become HTML comments** in `examples/overview` and
`scheduling/memory-management`, so the author's note stays in the
source. RST emits no node for a comment, so the diff shows the `<!-- …
-->`, but it doesn't render. The five comments in
`internals/object-spilling` hold Mermaid source whose `-->` arrows would
end an HTML comment early. They're MyST `%` comments instead, which emit
nothing, like the RST.

`render_diff.py` filters the two inert differences every MyST page shows
against an RST page: `class="tex2jax_ignore mathjax_ignore"` on the root
`<section>`, and the missing `code` class on inline literals. Neither
class carries any styling.

## Verification

- **Static checks** on all 81 new `.md` files: frontmatter parses,
backtick and colon fences balance, there's no residual RST outside
fences, every label is preserved, directive counts match the `.rst`, and
there are no relative `.html`, `.rst`, or scheme-less links.
- **Soft-wrap.** Each page's reflow to one line per paragraph is
whitespace-only. `ray-soft-wrap`'s `verify.py` reports `content=ok
render=ok idempotent=ok` for every file.
- **Doctest coverage is unchanged.** `doctest[core]` runs
`pytest-sphinx`, which yields one pytest item per file, so `pytest
--collect-only` counts files, not blocks. To count blocks, I ran
`pytest-sphinx`'s own parser over each `.rst` on master and each new
`.md`. It builds 120 examples before and 120 after. That's every example
`doctest[core]` collects from `ray-core/` on master: this PR moves all
16 of that target's executed files to MyST. Every parsed section is
identical, including directive, body, `:options:`, and `:skipif:`, apart
from trailing whitespace dropped from a comment line in
`compiled-graph/quickstart`'s skipped block and from two lines of a
`serialization` code block.

  | Page | Examples before | Examples after |
  |---|---|---|
  | `scheduling/accelerators` | 35 | 35 |
  | `tips-for-first-time` | 14 | 14 |
  | `actors/async_api` | 10 | 10 |
  | `starting-ray` | 8 | 8 |
  | `objects/serialization` | 8 | 8 |
  | `actors` | 7 | 7 |
  | `miscellaneous` | 7 | 7 |
  | `scheduling/memory-management` | 7 | 7 |
  | `configure` | 6 | 6 |
  | `objects` | 4 | 4 |
  | `actors/concurrency_group_api` | 3 | 3 |
  | `actors/named-actors` | 3 | 3 |
  | `actors/task-orders` | 3 | 3 |
  | `actors/terminating-actors` | 3 | 3 |
  | `internals/task-lifecycle` | 1 | 1 |
  | `user-spawn-processes` | 1 | 1 |
  | **Total** | **120** | **120** |

None of the converted pages is in a doctest `exclude` list, and
`doctest[core]` globs both `.md` and `.rst`, so `doc/BUILD.bazel`
doesn't change.
- **Doctests executed locally.** This PR only touches doc sources, so
`.buildkite/test.rules.txt` routes it to no test steps, and
`doctest[core]` doesn't run premerge. I ran the converted doctest pages
through pytest locally, with the `doctest` macro's arguments, Ray's
pinned `pytest==7.4.4`, and the Ray nightly wheel (`674900c91faa`), on
Python 3.10 with `RAY_USAGE_STATS_PROMPT_ENABLED=0`. All pass except
`scheduling/accelerators`, which fails on a missing
`CUDA_VISIBLE_DEVICES` on a machine with no GPU. The master `.rst` fails
the same way, so that page's evidence is the parity check.
- **Build.** The Read the Docs preview is green under `fail_on_warning`.
- **Render diff.** `render_diff.py` against `/en/master` over all 80
pages: 65 identical, and every difference on the other 15 is listed
under [Render differences from
`/en/master`](#render-differences-from-enmaster).

**Duplicate check.** No other open PR converts these pages. Six open PRs
edit pages this PR converts, and each will need to move its change onto
the `.md` file when this lands: #64137 and #65979
(`direct-transport/direct-transport`), #66402 (`objects/serialization`),
#66368 (`scheduling/accelerators`), #65974 (`scheduling/placement-group`
and `scheduling/resources`), and #65792 (`tasks`).

This PR was prepared with AI assistance (Claude Code). I reviewed the
changes and ran the checks above.

## Related issue number

Part of the RST-to-MyST migration.

## Checks

- [x] I've signed off every commit (`git commit -s`).
- [x] I've made sure the tests are passing: the static checks, soft-wrap
verification, doctest parity check, and local doctest run pass, the RtD
build is green, and every render diff is explained above.
- Testing Strategy
   - [ ] Unit tests
   - [ ] Release tests
- [x] Docs-only change, verified with the static checks, doctest parity
check, RtD build, and render diff described above

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: Douglas Strodtman <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
@dstrodtman

Copy link
Copy Markdown
Contributor

Hi @sampan-s-nayak, a heads-up on a docs conflict. #66430 just merged, converting the ray-core/ user guide from RST to MyST Markdown. It includes doc/source/ray-core/objects/serialization.rst, which is now serialization.md on master. The "Blocking untrusted unpickling" section here will conflict on rebase. Git recorded the change as a delete plus an add, not a rename, so it won't carry the hunk over for you.

Your section is self-contained, so the port is small. I'm happy to help with whichever path fits:

  • If this ships after 2.59.0: I can convert the section to MyST and push it to your branch, or post it as a suggestion if you'd rather apply it yourself.
  • If this needs to go into 2.59.0: releases/2.59.0 still has the RST files, so the master PR and the cherry-pick need the section in different formats. I can help you rebase onto master with the MyST version, then open the cherry-pick against releases/2.59.0 with your original .rst hunk.

Let me know which you'd prefer.

@dstrodtman

Copy link
Copy Markdown
Contributor

Hi @sampan-s-nayak, heads-up: master converted doc pages this PR edits from reStructuredText to MyST Markdown, so those edits need to move to the .md files when you rebase:

If you'd like help translating your edits to Markdown, DM me (Douglas Strodtman) on the Ray Slack and I'll help. If you'd rather handle it yourself, the repo has a Claude Code skill for this conversion at doc/.claude/skills/rst-to-myst/. Most small edits don't need it, though: any coding agent can translate them without the skill loaded.

@sampan-s-nayak
sampan-s-nayak marked this pull request as ready for review September 30, 2026 10:38
@sampan-s-nayak
sampan-s-nayak requested review from a team as code owners September 30, 2026 10:38

@gemini-code-assist gemini-code-assist Bot 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.

Code Review

This pull request implements a security guard against untrusted unpickling in Ray Data by introducing a process-wide audit hook that refuses unpickling of arbitrary classes or functions while a forbid flag is set. The changes include adding a pickle_guard utility, wrapping datasource methods and read tasks with this guard, and updating various datasources to remove manual pickle checks in favor of this centralized mechanism. I have provided feedback on ensuring robust method wrapping in Datasource, improving resource cleanup in guard_iterator, and addressing a critical security flaw in the webdataset_datasource where torch.load was being called without proper user opt-in.

Comment on lines +289 to +291
# Explicit opt-in: lift the forbid flag for this call only.
with allow_unsafe_unpickling():
sample[key] = torch.load(io.BytesIO(value), weights_only=False)

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.

security-critical critical

The torch.load call with weights_only=False is wrapped in allow_unsafe_unpickling() unconditionally, without checking if the user has opted in via allow_unsafe. This allows untrusted .pth files to execute arbitrary code even when unsafe unpickling is disabled. Please guard this call with allow_unsafe just like the pickle block below.

            # Explicit opt-in: lift the forbid flag for this call only.
            if not allow_unsafe:
                raise ValueError(
                    "Loading torch files with weights_only=False requires "
                    "explicit opt-in via allow_unsafe=True."
                )
            with allow_unsafe_unpickling():
                sample[key] = torch.load(io.BytesIO(value), weights_only=False)

Comment on lines +203 to +206
for name in ("__init__", "get_read_tasks", "estimate_inmemory_data_size"):
fn = cls.__dict__.get(name)
if isinstance(fn, types.FunctionType):
setattr(cls, name, guard_datasource_call(fn))

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.

medium

Using cls.__dict__.get(name) only retrieves methods defined directly on the subclass, which fails to wrap methods inherited from mixins or other non-Datasource base classes. Since guard_datasource_call is idempotent, using getattr(cls, name, None) is safer and more robust.

Suggested change
for name in ("__init__", "get_read_tasks", "estimate_inmemory_data_size"):
fn = cls.__dict__.get(name)
if isinstance(fn, types.FunctionType):
setattr(cls, name, guard_datasource_call(fn))
for name in ("__init__", "get_read_tasks", "estimate_inmemory_data_size"):
fn = getattr(cls, name, None)
if isinstance(fn, types.FunctionType):
setattr(cls, name, guard_datasource_call(fn))

Comment thread python/ray/util/pickle_guard.py Outdated
Comment on lines +115 to +123
with forbid_untrusted_unpickling(hint):
it = iter(get_iterable())
while True:
with forbid_untrusted_unpickling(hint):
try:
item = next(it)
except StopIteration:
return
yield item

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.

medium

If the generator wrapped by guard_iterator is closed early (e.g., due to a break or exception in the consumer), the underlying iterator it is not closed. If it is a generator, this can delay resource cleanup. Adding a finally block to close it if it has a close method ensures prompt cleanup.

Suggested change
with forbid_untrusted_unpickling(hint):
it = iter(get_iterable())
while True:
with forbid_untrusted_unpickling(hint):
try:
item = next(it)
except StopIteration:
return
yield item
with forbid_untrusted_unpickling(hint):
it = iter(get_iterable())
try:
while True:
with forbid_untrusted_unpickling(hint):
try:
item = next(it)
except StopIteration:
return
yield item
finally:
if hasattr(it, "close"):
try:
it.close()
except Exception:
pass

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

Stale Bugbot comment from a previous run.

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

Stale Bugbot comment from a previous run.

@ray-gardener ray-gardener Bot added docs An issue or change related to documentation data Ray Data-related issues labels Sep 30, 2026

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

Stale Bugbot comment from a previous run.

Add a process-wide untrusted-unpickling guard (`ray.util.pickle_guard`) built
on the `pickle.find_class` audit event, and run all Ray Data datasource code
under it: on the driver (constructor, `get_read_tasks`,
`estimate_inmemory_data_size`, V2 schema sampling) and in read tasks around
each `next()` of a read function. While the flag is set, any unpickle that
names a class or function raises `UntrustedUnpicklingError`, and
`ArrowPythonObjectType` refuses to be rebuilt from a file or stream, so
pickled-object columns never enter the pipeline. This replaces the per-reader
`raise_on_pickle_object_columns` checks.

Ray's own transport (`ray.get`, task arguments, function loading) goes through
`ray.cloudpickle.loads`, which is exempt. Readers whose format carries pickle
(`read_numpy(allow_pickle=True)`, webdataset's unsafe decoders) wrap only that
call in `allow_unsafe_unpickling()`. `RAY_DATA_AUTOLOAD_PICKLE_OBJECT_SCALAR=1`
turns the guard off for a job.

Signed-off-by: sampan <[email protected]>
… and Sphinx references

The serialization.rst example defined its class inside the doctest namespace,
so pickle.dumps failed before the guard ran. Use collections.OrderedDict
instead. Docstrings referenced forbid_untrusted_unpickling with a bare
:func: role that Sphinx cannot resolve from the autosummary pages; use
literals.

Signed-off-by: sampan <[email protected]>
…led-column check

- make_async_gen runs worker threads in a copy of the caller's context so the
  forbid flag covers threaded file reads (V1 and V2).
- HuggingFace datasets arrive with Arrow types already rebuilt outside the
  guard, so check the schema explicitly via raise_on_pickle_object_columns.
- Datasource.__init_subclass__ also guards methods inherited from mixins.
- guard_iterator closes the producer on early exit, under the flag.

Signed-off-by: sampan <[email protected]>
@sampan-s-nayak
sampan-s-nayak force-pushed the data-untrusted-unpickling-guard branch from 7252176 to 56464c2 Compare October 5, 2026 03:50

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

Stale Bugbot comment from a previous run.

sampan-s-nayak and others added 2 commits October 5, 2026 04:38
Native readers such as Hudi and Lance get batches from Rust through the
Arrow C Data Interface, which rebuilds extension types on import, so the
pickled-object check fires there too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: sampan <[email protected]>
@richardliaw

Copy link
Copy Markdown
Contributor

@sampan-s-nayak - should we just keep all the changes in Ray Data?

Also I would make it so that Datasource and DatasourceV2 have the right interfaces that users need to use in order to not need to worry about this

@sampan-s-nayak

Copy link
Copy Markdown
Contributor Author

@richardliaw changes mostly affect ray data only, I had to keep the pickle helpers in util because we need to allow rays internal pickle operation (cloud pickle) to go through when we are blocking other pickle op's. I also felt these functions could be reused in other places if need arises in the future.

users will just need to set RAY_DATA_AUTOLOAD_PICKLE_OBJECT_SCALAR to True (False by default) to bypass this. as I am making changes in the read tasks submission side itself this should cover both datasource and DatasourceV2 and should extend to any new datasources being added (apart from a few special cases)

@sampan-s-nayak

Copy link
Copy Markdown
Contributor Author

@richardliaw the cloud pickle changes are required because we want to allow ray originated ser-de operations to go through while blocking other user code originated ser-de (eg ray.put get calls inside the pickle guard.

@github-actions github-actions Bot added unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it. and removed stale The issue is stale. It will be closed within 7 days unless there are further conversation labels Nov 11, 2026
Resolve conflicts with the guard design: drop the per-reader
raise_on_pickle_object_columns gates upstream added to ORC v2 and
hive_direct readers (and their tests), keep the guard around V2
schema sampling in read_api.

Signed-off-by: sampan <[email protected]>

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

Stale Bugbot comment from a previous run.

Run the mcap mixed-JSON refusal test under forbid_untrusted_unpickling,
as real read tasks do; raise_on_pickle_object_columns only raises there.
Compare pa.__version__ directly so pyrefly doesn't see an Optional.

Signed-off-by: sampan <[email protected]>
Ray requires pyarrow>=23, and pyrefly rejects pa.__version__ as Optional.

Signed-off-by: sampan <[email protected]>
…le exemption

Revert the ray.util.pickle_guard module, the cloudpickle change and core docs.
Ray Data now whitelists Ray-internal fetches with ray_get_trusted, guards the
DSv2 count pushdown and scanner calls in read tasks, and its agent and Bugbot
rules cover new code paths that read external bytes.

Signed-off-by: sampan <[email protected]>
@sampan-s-nayak
sampan-s-nayak requested a review from a team as a code owner November 17, 2026 06:39

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

Stale Bugbot comment from a previous run.

…lete

Parquet sampling and parallel file-metadata fetches run in guarded datasource
constructors and fetch Ray task results through this helper; a plain ray.get
there is refused by the unpickling guard.

Signed-off-by: sampan <[email protected]>
…uard

ray.cloudpickle is no longer exempt from the unpickling guard; the mock setup
pickle is written by the test itself.

Signed-off-by: sampan <[email protected]>
…pickling-guard

Signed-off-by: sampan <[email protected]>

# Conflicts:
#	python/ray/data/read_api.py

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

Cursor Bugbot has reviewed your changes using default effort and found 2 potential issues.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 4aec2d6. Configure here.

Comment on lines +79 to +82
for ref, result in zip(done, ray.get(done)):
# Ray task results, fetched by datasource code that runs under the
# unpickling guard (e.g. Parquet sampling, metadata fetches).
for ref, result in zip(done, ray_get_trusted(done)):

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.

instead of introducing a new call, can we just do:

 with allow_unsafe_unpickling():
      results = ray.get(refs, **kwargs)

for ref, result in zip(done, results)

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.

(everywhere instead of using ray_get_untrusted)

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.

sure

Comment on lines +127 to +136
def ray_get_trusted(refs: Any, **kwargs) -> Any:
"""``ray.get`` for objects Ray itself produced, allowed inside the guard.

``ray.get`` unpickles, so datasource code that fetches its own shared state
(paths, read-task state, actor results) goes through this.
"""
import ray

with allow_unsafe_unpickling():
return ray.get(refs, **kwargs)

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.

see above comment but we should avoid this new abstraction

…usted

Per review, drop the ray_get_trusted helper: call sites that fetch Ray's own
objects inside the unpickling guard now wrap ray.get in
allow_unsafe_unpickling() and iterate the results outside the block. Update
the schema-worker test: a pickled-object column is refused during schema
inference unless the user opts in.

Signed-off-by: sampan <[email protected]>
@sampan-s-nayak

Copy link
Copy Markdown
Contributor Author

@richardliaw addressed

ARROW_PYTHON_OBJECT_EXTENSION_NAME = "ray.data.arrow_pickled_object"


def raise_on_pickle_object_columns(table: "pa.Table") -> None:

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.

so does this still get called anywhere?

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.

yeah still required for hugging face datasets for which the dataset is built before the read (hence outside pickle guard). in the user code they call datasets.load_dataset(...) before calling from_huggingface

Comment on lines +198 to +209
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
# Driver-side datasource code runs with the forbid flag set (read tasks
# are covered by the read operator). ``getattr`` also catches methods
# inherited from mixins; wrapping is idempotent. ``Datasource``'s own
# stubs stay unwrapped so ``should_create_reader`` can detect them.
for name in ("__init__", "get_read_tasks", "estimate_inmemory_data_size"):
fn = getattr(cls, name, None)
if fn is Datasource.__dict__.get(name):
continue
if isinstance(fn, types.FunctionType):
setattr(cls, name, guard_datasource_call(fn))

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.

is there no better way to do this than override attributes in this way?

surely we can do something like force all the datasource methods to go through some higher level method when invoked? like:

user implements get_read_task
system implement a system side protected_get_read_task

we only call the system side method

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.

yeah we can do that

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.

updated, PTAL

goutamvenkat-anyscale added a commit that referenced this pull request Nov 23, 2026
- Fix the directory list: datasource_v2 is interfaces/, common/, formats/<name>/;
  listing/, readers/, scanners/, chunkers/ and partitioners/ no longer exist.
- Define "Important" from v2's own invariants instead of deferring to the
  deprecated v1 file.
- Separate FilePartitioner (regrouping manifest rows into read tasks) from
  hive-style partition columns, which the old wording conflated.
- State the no-untrusted-unpickling invariant and note the enforcement is
  being centralized, so the guidance survives #66402.
- Add the checks that keep coming up in DSv2 format PRs: conservative pruning,
  pushdowns not weakening each other, no-stored-column reads, scanner
  docstrings matching reader enforcement, duplicate paths read twice, per-file
  failure isolation, planned-schema conformance, sizing by peak decoded memory
  (None not 0), incremental indexing that honors a pushed limit, interfaces
  using only types every format has, use_datasource_v2 over per-format flags,
  driver-side work minimized, predicates pushed to listing, and version
  compatibility across supported library versions.

Signed-off-by: Goutam <[email protected]>
…class

Per review, drop the __init_subclass__ method patching. Ray Data now calls
datasource hooks only through the public, final guarded_get_read_tasks and
guarded_estimate_inmemory_data_size, and Datasource's metaclass constructs
every datasource under the unpickling guard. A unit test fails on any direct
get_read_tasks / estimate_inmemory_data_size call from Ray Data code.

Signed-off-by: sampan <[email protected]>

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

ok this looks great! fix merge

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

I ran this on 58d5c9c against the merge base afc0657 (pyarrow 25.0.1, Parquet on V1 and V2). The guard itself holds: a Parquet file whose pickled column runs os.system on load is refused on both paths and the payload never runs, and objects created inside a pipeline (from_items -> map_batches -> materialize) still go through. The two new test files pass (53 tests).

The driver segfault on multi-file V2 reads (in the Cursor thread below) is the one I'd fix before merging. The other three comments below are behavior changes compared with the merge base.

# a read that means untrusted bytes declare a column that unpickles on
# access, so refuse it. Ray's own transport rebuilds the type outside
# reads or under ``allow_unsafe_unpickling()``, where the flag is off.
if is_unpickling_forbidden():

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.

Is it intended that this also refuses reads that don't select the pickled column? With a file holding an id column and an arrow_pickled_object column, read_parquet(f, columns=["id"]) returns the rows on afc0657 (V1 and V2; the old ORC check only looked at the columns it would decode) but raises here on both paths, since pyarrow rebuilds every field of the file schema. Same for Ray's own write_parquet output when the object column isn't selected. If it's intended, a line in the description would help, since it's a visible change for those users.

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.

updated doc and error message, thanks for catching this!


if mem_size is None and datasource_or_legacy_reader:
mem_size = datasource_or_legacy_reader.estimate_inmemory_data_size()
mem_size = datasource_or_legacy_reader.guarded_estimate_inmemory_data_size()

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.

This is the data: arrow v23 tests failure in premerge build 77768: the MockReader in test_autodetect_parallelism doesn't inherit Reader, so all 13 cases fail with AttributeError: ... has no attribute 'guarded_estimate_inmemory_data_size'. It isn't only the test. A deprecated create_reader that returns a reader written to the interface without subclassing Reader reads fine on afc0657 and fails the same way here.

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!

class Datasource(
_DatasourceProjectionPushdownMixin,
_DatasourcePredicatePushdownMixin,
metaclass=_GuardedConstructionMeta,

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.

Datasource is a public base class, so this changes what user subclasses can inherit: class MyDS(Datasource, Registered), where Registered has its own metaclass (class Meta(type)), now fails at class definition with TypeError: metaclass conflict. It works on afc0657. Probably rare, but it fails at import time instead of read time, so it may deserve a note.

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.

addressed

pyarrow rebuilds an extension type's Python instance through
__arrow_ext_deserialize__ once the old instance is collected. Inside the
guard that rebuild refuses, and from internal paths such as schema merging
the error crashed the process. ArrowPythonObjectType is now a single
long-lived instance, so the rebuild never happens.

A deprecated create_reader() may return an object that implements the
reader interface without subclassing Reader. Wrap it in an adapter that
provides the guarded entry points, and run create_reader() under the guard.

Also note in the error message and docs that a file with a pickled-object
column is refused even when the read doesn't select it, and document the
Datasource metaclass.

Signed-off-by: sampan <[email protected]>
…strings

Relative :meth: references don't resolve on the API reference pages that
inherit these methods, which fails the docs build.

Signed-off-by: sampan <[email protected]>

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

All four are handled on 5e999b1. The multi-file V2 read that segfaulted now raises UntrustedUnpicklingError, and reads fine with RAY_DATA_AUTOLOAD_PICKLE_OBJECT_SCALAR=1. The repro without Ray (schemas read outside the guard, unified inside it) no longer crashes on pyarrow 23.0.1, 25.0.1 or 26.0.0. I also ran merge_schema=True, which reads every footer in remote tasks and which I hadn't covered last time: same clean error, and it reads with the env var set.

The duck-typed create_reader case reads again, and unit/test_untrusted_unpickling.py plus test_auto_parallelism.py pass (61, including the 13 that failed in build 77768). A malicious single file is still refused on V1 and V2 without the payload running, and objects created inside a pipeline still go through. The docs now cover the projection and metaclass changes, which answers my questions there.

One side effect, just so it's known: on V2 the refusal moved from schema inference on the driver into the read task, so it now surfaces as RayTaskError(UntrustedUnpicklingError) after tasks start. The message is the same.

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

data Ray Data-related issues docs An issue or change related to documentation go add ONLY when ready to merge, run all tests unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants