Skip to content

Replace unique_lock with lock_guard in ivalue_inl.h - #195117

Closed
lakshayg wants to merge 1 commit into
pytorch:mainfrom
lakshayg:replace-unique-lock
Closed

lakshayg wants to merge 1 commit into
pytorch:mainfrom
lakshayg:replace-unique-lock

Conversation

@lakshayg

Copy link
Copy Markdown
Collaborator

No description provided.

@pytorch-bot

pytorch-bot Bot commented Aug 28, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/195117

Note: Links to docs will display an error until the docs builds have been completed.

✅ You can merge normally! (1 Unrelated Failure)

As of commit 22212dd with merge base 4380f31 (image):

FLAKY - The following job failed but was likely due to flakiness present on trunk:

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@lakshayg lakshayg self-assigned this Aug 28, 2026
@lakshayg lakshayg added ciflow/trunk Trigger trunk jobs on your pull request topic: not user facing topic category labels Aug 28, 2026
@lakshayg
lakshayg requested a review from Skylion007 August 28, 2026 08:36
@Skylion007

Copy link
Copy Markdown
Collaborator

@claude review this PR and generate a PR description. Also double check if this causes issue with executorch

@claude

claude Bot commented Aug 28, 2026 •

Copy link
Copy Markdown

Claude finished @Skylion007's task in 5m 53s —— View job


Review: unique_lock -> lock_guard in ivalue_inl.h

Semantics-preserving and correct — all 7 converted sites are plain scoped locks, and no ExecuTorch impact since ExecuTorch's runtime uses its own EValue, not c10::IValue.

  • Read the diff and surrounding code in aten/src/ATen/core/ivalue_inl.h
  • Verify no converted site needs unique_lock semantics (manual unlock/relock, condvar wait, move)
  • Check ExecuTorch impact
  • Post review + draft PR description
Full review details

Verdict

LGTM. Behavior-preserving cleanup. Nothing blocking.

Correctness check of each converted site

The only reason to keep std::unique_lock is if the site needs one of: (a) passing the lock to condition_variable::wait, (b) manual unlock()/lock(), (c) deferred/try/adopt locking, (d) moving the lock out of scope. I checked all 7 converted sites and none of them do:

Line Method Body
1015 value() assert, rethrow, return copy — scoped
1026 constValue() const asserts, return ref — scoped
1040 storages() const asserts, return ref — scoped
1131 tryRetrieveErrorMessage() const single call, return string — scoped
1141 hasValue() const single read — scoped
1146 hasError() const single read — scoped
1151 exception_ptr() const single read — scoped

Equally important, the diff correctly leaves alone every site that genuinely needs unique_lock:

  • wait() (L899) — passes lock to finished_cv_.wait(lock, ...)
  • markCompleted() (L953) — lock.unlock() at L974 before notify_all() and callback invocation
  • addCallback() (L1058) — lock.unlock() at L1060 on the already-completed fast path
  • setError() / setErrorIfNeeded() (L987, L992) — pass lock by reference into setErrorInternal(eptr, std::unique_lock<std::mutex>&) (L1223-1225), which unlocks at L1238

So the conversion is exactly the complement of the set that needs unique_lock. That's the right split.

Other things I verified

  • const methods still compile: mutex_ is declared mutable std::mutex mutex_; at L1377, so std::lock_guard<std::mutex> in the const accessors is fine.
  • No new deadlock via double-locking: tryRetrieveErrorMessage() (L1129-1133) calls hasError() — which itself locks — before taking its own lock at L1131. Two sequential lock/unlock pairs, not a recursive acquisition. Pre-existing shape, unaffected.
  • Repo style / lint: .clang-tidy line 69 disables -modernize-use-scoped-lock, and std::lock_guard<std::mutex> (explicit template arg, no CTAD) is the dominant form across ~169 files in aten/, c10/, and torch/csrc/. This PR matches house style. Lint and BC Lint are green.
  • TSan is green on this PR, which is the CI signal that most directly exercises this locking code.

Nits (non-blocking, take or leave)

  1. Missing direct #include <mutex>. The header uses std::mutex, std::lock_guard, and std::unique_lock, but only includes <condition_variable> (L3) — never <mutex>. On libstdc++ this works because <condition_variable> pulls in bits/std_mutex.h (which defines lock_guard) and bits/unique_lock.h. This is pre-existing (std::mutex/std::unique_lock were already relying on it), so the PR introduces no new exposure, and CI is green including libc++ builds. But since ivalue_inl.h is a widely-included public header and libc++'s header granularity has churned across releases, adding #include <mutex> alongside L3 would make it IWYU-correct for free. Fix this →

  2. Pre-existing issues this PR sensibly does not touch (flagging only so they're not mistaken for regressions): constValue() (L1025) and storages() (L1039) return references to members after the lock has been dropped at return, and completed() (L1136) reads completed_ unsynchronized. Both predate this PR and fixing them is a real semantics change — correctly out of scope for a mechanical cleanup.

ExecuTorch impact: none

Short answer: this cannot affect ExecuTorch.

  • ExecuTorch does not consume this header. Its runtime value type is executorch::runtime::EValue (runtime/core/evalue.h), which is an independent implementation — not c10::IValue. ivalue_inl.h is JIT/torch::jit-facing (it declares torch::jit::Function/CompilationUnit and defines ivalue::Future, ivalue::Await, ivalue::Object). ExecuTorch's dependency on the PyTorch tree is confined to c10/ scalar-type/utility headers (vendored under runtime/core/portable_type/c10/) plus torchgen for codegen. ivalue::Future is not part of the ExecuTorch runtime build at all.
  • I confirmed no build-system coupling in this repo: nothing in build_variables.bzl, buckbuild.bzl, or the CMake/Buck files references ivalue_inl.h, and the only in-tree includers are ATen/core/ivalue.h and four torch/csrc/jit/ files.
  • Even in the hypothetical, the change is a no-op at the ABI and semantic level: both lock_guard and unique_lock are RAII wrappers over the same std::mutex, they are function-local, and neither appears in any exported signature. There's no size/layout change to Future and no header-macro or exception-behavior change. lock_guard is if anything marginally leaner (no owns_lock bookkeeping).

One caveat on the evidence: no ExecuTorch job runs on this PR, so this is a code-reasoning conclusion rather than a CI-verified one. The ExecuTorch pin auto-update is commented out in .github/workflows/nightly.yml (L152-156: "executorch jobs are disabled since it needs some manual work for the hash update"), and the pin at .ci/docker/ci_commit_pins/executorch.txt (deb42f2) is only consumed by docker-builds.yml. So there is no ExecuTorch signal available on PRs regardless — but given the header isn't in ExecuTorch's include graph, there's nothing to gate on here.


Suggested PR description

Copy-paste into the PR body:

Replace `std::unique_lock` with `std::lock_guard` in the seven `ivalue::Future`
accessors that only need a plain scoped lock.

`std::unique_lock` is only necessary when the lock must be handed to a condition
variable, unlocked early, moved, or constructed deferred. None of these accessors
do any of that: each acquires `mutex_`, reads or copies a member, and releases on
scope exit. `std::lock_guard` states that intent directly and avoids
`unique_lock`'s ownership-flag bookkeeping and conditional unlock in its
destructor.

Converted (all in `aten/src/ATen/core/ivalue_inl.h`):

- `value()`, `constValue()`, `storages()`
- `tryRetrieveErrorMessage()`, `hasValue()`, `hasError()`, `exception_ptr()`

Deliberately left as `std::unique_lock`, since each relies on capabilities
`lock_guard` does not provide:

- `wait()` - passes the lock to `finished_cv_.wait()`
- `markCompleted()` and `addCallback()` - call `lock.unlock()` explicitly before
  invoking callbacks outside the critical section
- `setError()` and `setErrorIfNeeded()` - pass the lock by reference to
  `setErrorInternal()`, which unlocks before notifying waiters

No functional change; the locked regions and their boundaries are identical.
`mutex_` is already `mutable`, so the `const` accessors are unaffected.

## Test Plan

No new tests: this is a mechanical, semantics-preserving substitution with no
behavioral surface to assert on. Coverage comes from existing CI, with TSan
being the most relevant signal for this locking code.

Verified via CI on this PR (all green): `pull`, `TSan`, `Lint`, `BC Lint`,
`docs-build`. The single `trunk` failure is a known-flaky
`pr_time_benchmarks` job flagged as unrelated by Dr. CI.

Local sanity check that the file still compiles as part of an ATen build:

```bash
pip install -e . -v --no-build-isolation

Existing Future tests:

python test/test_jit.py -k Future
build/bin/test_jit --gtest_filter='*Future*'

---

_(Both the review and the description above are AI-generated; please read them before using. The description in particular should be checked against your own intent for the change before you paste it in.)_
 | Branch: [`replace-unique-lock`](https://github.com/pytorch/pytorch/tree/replace-unique-lock)

@lakshayg

Copy link
Copy Markdown
Collaborator Author

@pytorchmergebot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/trunk Trigger trunk jobs on your pull request Merged open source topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants