Skip to content

[core] Add a thread checker - #47966

Merged
rynewang merged 2 commits into
ray-project:masterfrom
dentiny:hjiang/thread-checker
Oct 12, 2024
Merged

rynewang merged 2 commits into
ray-project:masterfrom
dentiny:hjiang/thread-checker

Conversation

@dentiny

@dentiny dentiny commented Oct 10, 2024 •

Copy link
Copy Markdown
Contributor

As @rynewang mentioned at comment #47793 (comment), ray core uses ASIO io context for event scheduling and callback execution.

Merely reading through the code, it's not always easy to justify correct threading usage, whether data race.

TSAN is a great tool to verify against data race and invalid memory access at runtime, but is generally not enough, since

  • It completely relies on the coverage for unit tests, which is hard to enforce along the codebase;
  • Certain tests cannot run with TSAN, for example, if we have non-default memory allocator (i.e. tcmalloc); or large tests which exceeds binary size (for static link), or too long runtime (usually for dynamic link)

ThreadChecker is a cheap runtime checker, which only takes two atomic operations, which

  • guards against threading invariants;
  • serves for better code readability, so code readers and developers are easy to understand thread execution status

Intended usage for GcsJobManager:

void CreateJob() {
  auto callback = [this]() {
    RAY_CHECK(this->thread_checker.ok());
  };
}

Signed-off-by: dentiny <[email protected]>
@dentiny dentiny mentioned this pull request Oct 10, 2024
8 tasks
Comment thread src/ray/util/BUILD
],
)

cc_library(

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.

I would like to propose we separate libraries and binaries into separate targets, as I mentioned here: #47928 (comment)

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.

I understand thread_checker is duplicate in two targets: utils and thread_checker, since utils simply declares all header/impls as its dependency; I will make another PR to cleanup.

Comment thread src/ray/util/thread_checker.cc Outdated

namespace ray {

bool ThreadChecker::ok() const {

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.

The overall runtime cost is ignorably small -- I'm pretty confident I could squeeze these CPU cycles from elsewhere.

If developers are really concerns about it (which means they care about nano seconds latency), they could use RAY_DCHECK to ignore at release.

@dentiny

dentiny commented Oct 10, 2024

Copy link
Copy Markdown
Contributor Author

@rynewang / @jjyao would appreciate a code review :)

@rynewang

Copy link
Copy Markdown
Contributor

hmm. I'm ok with this since std::this_thread::get_id() overhead is arguably small, as compared to the lots of "generous" copies sprinkled around the code base.

However let's come up with a good name. ThreadChecker::ok() is kinda vague - there are a lot of possible thread properties. Maybe: SingleThreadAccess::check()? or ThreadChecker::CheckOnSameThread()? or something understandable by looking at callsite.

Next, I don't think we need the mutable and const ok(). We can just expose it as a non-const method and it's totally fine.

Next. do we want it copyable/movable? needs some thoughts.

  • maybe we need copyable, because we want to check 1 callsite affines with 2 callsites in 2 callbacks.
  • maybe we should disable move, since it's easy to accidentally use the moved-from one, leading to false negative.

thoughts?

@dentiny

dentiny commented Oct 10, 2024 •

Copy link
Copy Markdown
Contributor Author

Next. do we want it copyable/movable? needs some thoughts.
maybe we need copyable, because we want to check 1 callsite affines with 2 callsites in 2 callbacks.
maybe we should disable move, since it's easy to accidentally use the moved-from one, leading to false negative.
thoughts?

Atomic variable is not copiable or movable, so same as ThreadChecker.

@dentiny

dentiny commented Oct 10, 2024

Copy link
Copy Markdown
Contributor Author

However let's come up with a good name. ThreadChecker::ok() is kinda vague - there are a lot of possible thread properties. Maybe: SingleThreadAccess::check()? or ThreadChecker::CheckOnSameThread()? or something understandable by looking at callsite.

Sounds good! Updated to IsOnSameThread, hopefully it reads better.

@rynewang

Copy link
Copy Markdown
Contributor

Next. do we want it copyable/movable? needs some thoughts.
maybe we need copyable, because we want to check 1 callsite affines with 2 callsites in 2 callbacks.
maybe we should disable move, since it's easy to accidentally use the moved-from one, leading to false negative.
thoughts?

Atomic variable is not copiable or movable, so same as ThreadChecker.

then we'd have some bad times. Most of our usage is about "this function and its callbacks are on same thread". if we can't copy/move the atomic to lambda callback we can't really use it.

@dentiny

dentiny commented Oct 10, 2024 •

Copy link
Copy Markdown
Contributor Author

then we'd have some bad times. Most of our usage is about "this function and its callbacks are on same thread". if we can't copy/move the atomic to lambda callback we can't really use it.

No worries at all, generally thread checker should be data member, a this pointer is enough.

Checkout current code impl,

auto on_done = [this, job_id, mutable_job_table_data, reply, send_reply_callback](

the callback is already capturing this.

@dentiny

dentiny commented Oct 11, 2024

Copy link
Copy Markdown
Contributor Author

@rynewang Let me clarify more

Intended use case is

class GcsJobManager {
 public:
  void HandleDone() {
    auto on_done = [this]() {
      thread_checker_.CheckThread();
    };
  }

 private:
  ThreadChecker thread_checker_;
};

No copy or move is needed.

Let me know if you have another thought, thanks.

@rynewang

Copy link
Copy Markdown
Contributor

Makes sense. I found actually we already have something similar to yours - with mutex. Once this PR is merged we can replace that thing with yours.

void ThreadCheck() const {

@dentiny

dentiny commented Oct 11, 2024

Copy link
Copy Markdown
Contributor Author

Makes sense. I found actually we already have something similar to yours - with mutex. Once this PR is merged we can replace that thing with yours.

Sounds good, I could followup with another PR after this one merged.

@dentiny

dentiny commented Oct 12, 2024

Copy link
Copy Markdown
Contributor Author

@rynewang Could you please help me to merge the PR? Thanks!

@rynewang
rynewang enabled auto-merge (squash) October 12, 2024 18:19
@github-actions github-actions Bot added the go add ONLY when ready to merge, run all tests label Oct 12, 2024
@rynewang
rynewang merged commit b539440 into ray-project:master Oct 12, 2024
ujjawal-khare pushed a commit to ujjawal-khare-27/ray that referenced this pull request Oct 15, 2024
`ThreadChecker` is a cheap runtime checker, which only takes two atomic
operations, which
- guards against threading invariants;
- serves for better code readability, so code readers and developers are
easy to understand thread execution status

Signed-off-by: dentiny <[email protected]>
Signed-off-by: ujjawal-khare <[email protected]>
goutamvenkat-anyscale added a commit that referenced this pull request Nov 11, 2026
#68005)

## Summary

Raises Ray Data's minimum supported pyarrow from 17.0.0 to 23.0.0 and
moves the tested ceiling from 23.0.1 to 26.0.1, deleting all version
gates and test skips that the new floor makes permanently true or false.

Two upstream constraints shape the lock layout: every released daft caps
`pyarrow < 26` (daft is part of the data requirements), and pyarrow 26
dropped Python 3.10. Locks therefore resolve at 25.0.1, and the data
"arrow latest" image force-installs 26.0.1 on Python ≥ 3.11 — the same
mechanism the arrow-nightly image already uses.

## Before

- Floor `pyarrow >= 17.0.0`; data CI matrix: v17 (premerge min lane) /
v23.0.1 ("latest") / nightly.
- ~30 library gates and ~130 test skips branching on pyarrow versions
between 7 and 22, all dead weight on any supported installation.
- Release/BYOD configs pinned pyarrow 14–19 in places that would fail
the new import-time check.

## After

- Floor `pyarrow >= 23.0.0` enforced in `setup.py`, `requirements.txt`,
and `_check_pyarrow_version`; no upper bound.
- Data CI matrix: **v23.0.0** (premerge min lane, py3.10) / **v25.0.1**
(latest resolvable with daft, py3.10) / **v26.0.1** (force-installed
over the lock, py3.12) / nightly (unchanged).
- Monorepo `requirements_compiled.txt`: pyarrow 23.0.1 → 25.0.1, mlflow
≥ 3.18 (older mlflow caps pyarrow < 24), daft 0.7.26. All deplocks
regenerated.
- Version-gated branches collapsed to their modern arm; the
`_S3FileSystemWrapper` pickling workaround (marked "remove once min >
14") and the pre-22 parquet schema-unification fallback are gone.
- Exception kept: the `PyExtensionType` autoload block in
`ray/data/__init__.py`. The pyarrow19 `image_classification*` release
tests still read datasets written with the legacy pickled tensor type;
they now set `RAY_DISABLE_PYARROW_VERSION_CHECK=1` and keep their
pyarrow 19 pin until those datasets are migrated.

```mermaid
flowchart TD
    subgraph Before
        subgraph BS[Subsystem: block/data format + IO]
            B1[pyarrow >= 17 floor] --> B2[version gates: 7/9/12/13/14/16/20/22]
            B2 --> B3[legacy arms: promote=True, manual unify_schemas,
            S3 FS pickle workaround, FixedShapeTensor fallback]
        end
        subgraph BCI[CI matrix]
            B4[v17 min lane] --> B5[v23 latest lane]
        end
    end
    subgraph After
        subgraph AS[Subsystem: block/data format + IO]
            A1[pyarrow >= 23 floor] --> A3[single modern code path]
        end
        subgraph ACI[CI matrix]
            A4[v23 min lane] --> A5[v25 locked latest]
            A5 --> A6[v26 force-installed, py3.12]
        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 B2,B3 removed
    class A6 added
    class A1,A4,A5 changed
```

Behavior on pyarrow ≥ 23 is unchanged: the deleted branches were
unreachable there, and the surviving arms are byte-identical to what
those versions already executed.

## Subsystems

Block/data format (carries the cleanup), IO (parquet datasource,
file-based datasource), execution (join type checks) — plus mechanical
CI/requirements/lock changes.

## Relevant pyarrow changes between 17 and 23 (from the Arrow release
notes)

What in the 18–23 window makes this bump load-bearing, and what the new
floor buys:

- **21.0 removed `PyExtensionType`** (GH-46198), including
`set_auto_load`; `UnknownExtensionType` now subclasses `ExtensionType`
directly and pickle-based auto-loading of extension classes is gone.
This is why the autoload block in `ray/data/__init__.py` stays
version-guarded for the pyarrow-19 release tests, why the
`parquet_utils.py` check reduces to `isinstance(type,
pa.UnknownExtensionType)`, and why its error message now says to install
pyarrow < 21 to read legacy pickled tensor data.
- **22.0 added `DatasetFactory.inspect(fragments=, promote_options=)`**
(GH-46629 / apache/arrow#46961) — both kwargs landed together in 22.0
(verified against `_dataset.pyx` at the 21.0.0 tag). The
now-unconditional `factory.inspect(fragments=...,
promote_options="permissive")` in `_infer_schema` is the hardest
constraint forcing the floor to ≥ 22; it also replaces the manual
`unify_schemas` fallback for null→concrete promotion. Context: 20.0
started preserving Parquet dictionary index bitwidth (GH-30302), which
broke multi-file datasets with mismatched index widths —
`promote_options="permissive"` is the upstream fix.
- **Why 23 rather than 22**: 22.0's new pandas `DataFrame.attrs`
round-tripping crashed on non-serializable attrs, fixed in 23.0
(GH-47966); 23.0 also added stricter type checking on the hash-join
residual filter (GH-48268) and `to_pandas` fixes (unsigned dictionary
indices GH-47022, extension-column memory GH-47861, pandas 3.0
datetime-unit compat GH-48314).
- **Behavior changes users inherit at the new floor** (no code impact in
this PR): 19.0 Parquet writer rejects nulls in non-nullable columns
(GH-41667); 20.0 writer enables Page Index + Size Statistics by default
(GH-45227); 21.0 `pyarrow.parquet` reads map Parquet logical types to
Arrow extension types by default (GH-44500) — Ray reads via
`pyarrow.dataset`, where this defaults off; 18.0 made NumPy an optional
pyarrow dependency (GH-43846).
- **Python support**: 18.0 dropped py3.8, 22.0 dropped py3.9, 23.0
supports 3.10–3.14 — so the floor implicitly requires Python ≥ 3.10,
matching Ray's minimum (py3.10 is only dropped later, in pyarrow 26,
handled here by the py3.12 force-install lane).
- **Non-events confirming the deleted gates were safe**:
`concat_tables`/`unify_schemas` `promote_options` signatures are
unchanged from 14 through 23 (the deprecated `promote=` kwarg still
works through 23); `zero_copy_only` on `ChunkedArray.to_numpy` (13+),
the view-type predicates (16+), `FixedShapeTensorType`/`Array`/`Scalar`
(16+), native `S3FileSystem` pickling (14+, incl. the kwargs 21.0
added), and Scanner `batch_readahead`/`fragment_readahead` all exist
unmodified at 23 — every deleted branch collapses to an arm that behaves
identically on 23–26. The only Python-binding removal in 23.0 itself is
the deprecated `Array.format` (GH-48102), which Ray doesn't use.

## Testing

- `pytest python/ray/data/tests/unit` on pyarrow 26.0.1 (py3.12): 2,485
passed, 121 skipped; the 2 failures (`test_dynamic_work_queue`
thread-leak) reproduce identically without this change and touch no
pyarrow code.
- `_check_pyarrow_version` verified directly: passes on 26.0.1, raises
`Dataset requires pyarrow >= 23.0.0, but 22.0.0 is installed` on 22.0.0.
- `ci/ci.sh compile_pip_dependencies` + `compile_pip_dependencies_py314`
(linux/amd64 py3.11 container, matching the CI job) and `raydepsets
build --all-configs --check`: clean.
- Lock audit: every lock resolves pyarrow ≥ 23; the only below-floor pin
left is the intentional
`torch_cu128_image_classification_pyarrow19_py3.11.lock`. An orphaned
`ray_img_py39.lock` (unreferenced, pinned 19.0.1) was deleted.
- `pre-commit run` on all changed files: green, except the
`pyrefly-data` hook, which fails identically on master in a local
environment without the optional `databricks`/`azure` packages; the
in-image CI pyrefly job is the authoritative check.

Worth watching on the first CI run: `data: arrow v26 py3.12` exercises
daft 0.7.26 against force-installed pyarrow 26.0.1, a combination daft
does not test upstream (`test_daft.py` is the canary).

## Contribution policy

- Not a duplicate: searched open PRs for `pyarrow minimum` / `pyarrow
23` / `bump pyarrow`; no open PR changes the supported pyarrow range.
- AI assistance (Claude Code) was used to implement this change; every
edit was reviewed and the test commands above were run locally with the
results stated.

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

---------

Signed-off-by: Goutam <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: Cursor <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

go add ONLY when ready to merge, run all tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants