Skip to content

[eval] Use libuv mutex and condition for Lock and Semaphore - #13110

Merged
Simn merged 2 commits into
developmentfrom
claude/eval-luv-lock-semaphore
Nov 1, 2026
Merged

Simn merged 2 commits into
developmentfrom
claude/eval-luv-lock-semaphore

Conversation

@Simn

@Simn Simn commented Nov 1, 2026

Copy link
Copy Markdown
Member

In eval, Lock.wait(timeout) and Semaphore.tryAcquire(timeout) spun on a non-blocking acquire with Unix.sleepf 0.0 until the deadline, because OCaml's Condition has no timed wait. That kept a core busy for the whole timeout.

This PR makes both use one counting semaphore built on Luv.Mutex and Luv.Condition:

  • uv_cond_timedwait blocks with a timeout on every platform: SleepConditionVariableCS on Windows, pthread_cond_timedwait with CLOCK_MONOTONIC on Linux, and pthread_cond_timedwait_relative_np on macOS.
  • luv's bindings for uv_cond_wait, uv_cond_timedwait and uv_mutex_lock are in the Blocking group of luv_c_function_descriptions.ml, which generate_c_functions.ml generates with ~concurrency:Cstubs.unlocked. So they release the OCaml runtime lock while they block, which is what the Unix.sleepf 0.0 in the old loops was there for.
  • The libuv mutex and condition are destroyed in a Gc.finalise.
  • Timeouts are clamped to 1e9 s so the nanosecond count can't overflow. Zero, negative and NaN timeouts return straight away, unless a unit is available.

This is a first step toward a non-polling timed Condition.wait in eval (discussed in #13109). Condition can then reuse the same structure. This PR doesn't depend on #13109.

Testing

I built the compiler locally (OCaml 5.3.0, luv 0.5.14) and ran:

  • tests/threads with --interp: 148 assertions, all OK. That covers TestLock, TestSemaphore, TestCondition and TestEval. Thread.create spawns domains, so this is the parallel case.
  • hxcoro's eval suites, which make heavy use of Lock and Semaphore:
    • tests with the default, trampoline and threadpool dispatchers: 369/369 each.
    • tests with -debug -D coro.stack-traces: 369/369.
    • thread-tests: 3/3. callstack-tests: 15/15.
    • All three examples pass.
  • A small program on the old and new compiler:
development this PR
Lock.wait(1.0), no release 1000 ms wall, 260 ms CPU 1000 ms wall, 0 ms CPU
Semaphore.tryAcquire(1.0), no release 1000 ms wall, 274 ms CPU 1000 ms wall, 0 ms CPU

With this PR, tryAcquire(0), (-1) and (NaN) return false. tryAcquire(1e12) and Lock.wait(1e12) return true when another thread releases after 200 ms, and new Semaphore(2) hands out exactly two units.

One behaviour change: a negative initial count for new Semaphore(n) used to raise Invalid_argument from OCaml's Semaphore.Counting.make. Now it's accepted, and acquiring waits until enough releases have happened.


Generated by Claude Code

Lock.wait and Semaphore.tryAcquire with a timeout used to spin on a
non-blocking acquire with Unix.sleepf 0.0, because OCaml's Condition has
no timed wait. Both now share a counting semaphore built on Luv.Mutex and
Luv.Condition: uv_cond_timedwait blocks with a timeout on every platform,
and luv's bindings for the blocking calls release the OCaml runtime lock
while they block.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Va4FXDYWEo4mt53psuM5hu
@Simn

Simn commented Nov 1, 2026

Copy link
Copy Markdown
Member Author

I feel like I tried doing this before and there was some reason for not relying on the luv primitives, but I can't remember and I also don't find anything in the commit history. There's a good chance that this was before we moved from threads to domains, so whatever concerns I had would no longer be relevant.

Still, could you just briefly pretend to be a grumpy maintainer who hates change, and try to come up with potential risks and arguments against this change?

- Luv's binding for uv_mutex_lock releases and reacquires the OCaml
  runtime lock even when the mutex is free, which made uncontended
  Lock and Semaphore operations about 3 times slower than before. Try
  the non-blocking trylock first.
- On Windows, uv_cond_timedwait converts its timeout to a DWORD of
  milliseconds, so cap each wait at about 24 days. The wait loop
  already re-checks the remaining time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Va4FXDYWEo4mt53psuM5hu

Simn commented Nov 1, 2026

Copy link
Copy Markdown
Member Author

Putting on the grumpy-maintainer hat. I checked each point against the vendored libuv in luv 0.5.14 or with a measurement, and fixed the two that were real defects in this PR in ada7739.

1. "It's slower." Partly true, measured with 1M operations on eval:

development 737cc9d ada7739
create 1M Locks ~0.2 s ~1.5 s ~0.8–1.3 s
1M uncontended release+wait 0.11–0.17 s 0.37–0.43 s 0.13 s
1M uncontended acquire+release 0.12–0.16 s 0.34 s 0.11–0.12 s
100k ping-pongs between two threads ~2.9 s ~2.8 s ~2.9 s

The uncontended slowdown came from luv's uv_mutex_lock binding, which releases and re-takes the runtime lock even when the mutex is free. ada7739 tries the non-blocking trylock binding first, which brings it back to parity. Construction is still 4–6× slower (two ctypes allocations and a Gc.finalise per object). hxcoro only creates these per thread pool, scheduler or run loop, so I don't think that matters, but it is a real cost.

2. "Windows does something weird." It did. uv_cond_timedwait on Windows calls SleepConditionVariableCS(..., (DWORD)(timeout / 1e6)), so my 1e9 s clamp overflowed the DWORD. ada7739 caps each wait at 2e6 s, and the loop waits again for the remaining time. One wrinkle remains: a remainder under 1 ms rounds to 0 ms, so the last fraction of a millisecond loops without sleeping.

3. "libuv calls abort() where OCaml raises." uv_mutex_lock, uv_mutex_unlock and uv_cond_wait call abort() on any pthread error (unix/thread.c), and luv builds libuv with -DNDEBUG, so its mutexes are plain rather than error-checking. That can't happen in this PR, because the mutex is internal and always locked and unlocked in the same function. It does matter for moving Condition over, where user code calls acquire/release. A release from the wrong thread is currently a Sys_error with OCaml 5's error-checking mutex. With libuv it would be silent undefined behaviour on POSIX.

4. "Windows mutexes are recursive." uv_mutex_init on Windows is InitializeCriticalSection, which is recursive. Also irrelevant here, but for Condition it would make tryAcquire twice succeed on Windows and fail elsewhere. That's exactly the TestCondition.testTryAcquire comment. A Condition port would need its own owner check to keep the platforms consistent.

5. "Asynchronous exceptions leave the mutex locked." If a signal handler raises (e.g. Sys.Break) at an allocation point inside a critical section, the mutex is never unlocked. The timed path allocates through Extc.time. The old code had the same pattern, so this isn't a regression, but wrapping the critical sections in Fun.protect ~finally would be cheap hardening if you want it.

6. "Finalisers." Each object gets a Gc.finalise. That relies on our finaliser running before ctypes frees the underlying buffer. OCaml runs finalisers of values that die together in reverse registration order, and ours is registered after the ctypes allocation, so it runs first. I haven't verified what happens to finalisers registered by a domain that has since exited. The worst case is a leak: pthread_mutex_destroy/pthread_cond_destroy free nothing on Linux, and DeleteCriticalSection only frees debug info on Windows.

7. "More coupling to luv." sys.thread.Lock and Semaphore on eval now depend on luv's bindings, not just eval.luv.*. There's no new build dependency, since luv is already required, but if luv were ever dropped, these would need replacing too. LuvThread mode (luv thread-pool workers) isn't covered by the tests; Thread.create uses domains.

8. "Behaviour change." new Semaphore(-1) used to raise Invalid_argument and is now accepted.

As for your earlier concern: I couldn't find a trace of it either. In luv 0.5.14 the blocking bindings explicitly release the runtime lock, so a Thread-era deadlock wouldn't happen today. I can't tell whether older luv versions behaved the same.

After ada7739, I re-ran the eval thread tests (all OK) and hxcoro's eval suites: 369/369 with each dispatcher, thread-tests 3/3 and callstack-tests 15/15.


Generated by Claude Code

@Simn
Simn merged commit 0f7251b into development Nov 1, 2026
60 checks passed
@Simn
Simn deleted the claude/eval-luv-lock-semaphore branch November 1, 2026 20:05
Simn pushed a commit that referenced this pull request Nov 1, 2026
Replace the polling timed wait with Luv.Condition.timedwait, like Lock
and Semaphore since #13110, which also removes the notification counter.

libuv's mutex is recursive on Windows and aborts the process on misuse on
POSIX, while OCaml's mutex raised Sys_error. Track the owning eval thread
so that the mutex stays non-recursive on every platform and acquiring
twice, or releasing or waiting without holding the mutex, throws a Haxe
exception instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Va4FXDYWEo4mt53psuM5hu
@Simn Simn mentioned this pull request Nov 1, 2026
13 tasks done
Simn added a commit that referenced this pull request Nov 6, 2026
* Add optional timeout to sys.thread.Condition.wait

Declare `wait(?timeout:Float):Bool` and document its semantics. The
target implementations follow in later commits.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Va4FXDYWEo4mt53psuM5hu

* [cpp] Implement Condition.wait with timeout, add tests

Use the new hxcpp `ConditionVariable::timedWait`, and install the hxcpp
branch that adds it in CI until HaxeFoundation/hxcpp#1456 is merged.

Add thread tests for timed waits: timing out with the mutex still held,
being signaled, non-positive and NaN timeouts, and huge timeouts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Va4FXDYWEo4mt53psuM5hu

* [hl] [neko] Implement Condition.wait with timeout

hl uses the existing `condition_timed_wait` native and clamps the timeout
itself, because older runtimes don't. CI builds the HashLink branch with
the native fixes until HaxeFoundation/hashlink#1008 is merged.

neko uses the new `cond_timed_wait` primitive when it is available
(HaxeFoundation/neko#336), and otherwise polls with growing sleeps,
using a counter that `signal` and `broadcast` increment to detect
notifications.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Va4FXDYWEo4mt53psuM5hu

* [jvm] [python] [eval] Implement Condition.wait with timeout

The build job's xmldoc step checks every target's std against the core
API, so jvm and python must implement the new signature before CI can
run any tests.

- jvm: Condition.await with nanoseconds, like Semaphore.tryAcquire.
- python: threading.Condition.wait, clamped to threading.TIMEOUT_MAX,
  above which Python raises an OverflowError.
- eval: OCaml's Condition has no timed wait, so poll with growing sleeps
  like StdLock.wait and detect notifications with a counter that
  signal and broadcast increment.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Va4FXDYWEo4mt53psuM5hu

* [ci] Use the hxcpp branch with timedWait for docgen as well

The docgen job builds dox for cpp, which includes sys.thread.Condition,
and installs hxcpp separately from the cpp tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Va4FXDYWEo4mt53psuM5hu

* [jvm] Fix Condition.wait with huge timeouts

Int64.fromFloat throws for values above 2^53, so a timeout above about
104 days threw while the mutex was held, and testTimedWaitHuge hung.
Cap the wait at 9e6 seconds and report a capped wait that runs out as a
spurious wakeup instead of a timeout.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Va4FXDYWEo4mt53psuM5hu

* [eval] Use libuv mutex and condition for Condition

Replace the polling timed wait with Luv.Condition.timedwait, like Lock
and Semaphore since #13110, which also removes the notification counter.

libuv's mutex is recursive on Windows and aborts the process on misuse on
POSIX, while OCaml's mutex raised Sys_error. Track the owning eval thread
so that the mutex stays non-recursive on every platform and acquiring
twice, or releasing or waiting without holding the mutex, throws a Haxe
exception instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Va4FXDYWEo4mt53psuM5hu

* [ci] Build HashLink from its default branch again

HaxeFoundation/hashlink#1008 has been merged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Va4FXDYWEo4mt53psuM5hu

* [ci] Install hxcpp from its default branch again

HaxeFoundation/hxcpp#1456 has been merged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Va4FXDYWEo4mt53psuM5hu

* [tests] Allow spurious wakeups in testTimedWaitTimesOut

On Windows, MSVC's condition_variable_any::wait_for reports no_timeout
when the OS wait returns slightly before the deadline, so a single
wait(0.1) can return true. The API allows that as a spurious wakeup, so
wait in a loop until a timeout is reported, like callers are expected to.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Va4FXDYWEo4mt53psuM5hu

* Split Condition.wait(?timeout) into wait() and timedWait(timeout)

As discussed in review: wait() keeps its original signature and
documentation, and the timed variant becomes timedWait(timeout):Bool,
whose result always means something. This follows Semaphore, which has a
blocking acquire():Void and a separate tryAcquire(?timeout):Bool.

The target implementations are unchanged apart from the split.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Va4FXDYWEo4mt53psuM5hu

* Treat capped timedWait as spurious wakeup on all targets

Relax the documentation: very large timeouts may be cut short at a
target-specific limit, and such a wait returns true. Make python, cpp,
hl and neko return true when the timeout exceeds their cap, as jvm and
eval already do.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Va4FXDYWEo4mt53psuM5hu

---------

Co-authored-by: Claude <noreply@anthropic.com>
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.

2 participants