Skip to content

Give every scheduled event its own heap node - #193

Merged
Simn merged 10 commits into
masterfrom
scheduler-heap
Oct 29, 2026
Merged

Simn merged 10 commits into
masterfrom
scheduler-heap

Conversation

@Simn

@Simn Simn commented Oct 29, 2026 •

Copy link
Copy Markdown
Member

This replaces the child-event grouping in MinimumHeap with a plain binary heap that gives every event its own node. The schedulers now dispatch one event at a time.

Why

The heap used to attach events with the same due time to an existing node as child events. This had three problems:

  • Lost events: dispatching a node dispatched its children too. With a dispatcher that runs events right away, such as TrampolineDispatcher, an exception from one event dropped the others due at the same millisecond. Those could be other tasks' delay resumptions, which then never resumed. Don't let exceptions from callbacks strand unrelated work #191 works around this with a requeue callback. This PR fixes it at the source instead.
  • Slow worst case: insert searched subtrees for an event with the same due time, and undid the sift when it found one. That made insertion O(n) in the worst case.
  • Unreliable order: FIFO among equal due times only held when the search found the match. Otherwise the order was arbitrary.

What changes

  • MinimumHeap orders events by due time, then by an insertion sequence number. Equal due times now always come out in insertion order.
    • Insertion: O(log n).
    • Sequence numbers: they are compared by subtraction, so a wrapped counter still orders correctly.
  • The schedulers extract and dispatch one event at a time. If a dispatch throws, the events that were not dispatched yet are still in the heap.
  • ThreadAwareScheduler moves the events from the thread queues into the heap, then dispatches the due ones from there. It used to collect them into a linked list of its own, which lost the rest of the list when one event threw.
  • ScheduledEvent loses addChildEvent, its child events and next.

Benchmarks

The new benchmarks are:

  • scheduler/yield_burst: many coroutines that only yield(), run through CoroRun.run.
  • scheduler/heap_same_time and scheduler/heap_mixed: the heap on its own, on a VirtualTimeScheduler. The first uses one due time for all events, the second spreads them over 1000.

The results are in ops/sec, from single runs on one machine. Other benchmarks varied by up to about 10% between runs.

Target Benchmark Old heap This PR
eval yield_burst 52,041 51,979
eval heap_same_time 194,504 87,197
eval heap_mixed 67,202 79,180
jvm yield_burst 1,666,666 1,395,349
jvm heap_same_time 22,222,067 3,896,103
jvm heap_mixed 1,445,782 1,764,705
hl yield_burst 684,635 713,975
hl heap_same_time 1,874,373 2,365,774
hl heap_mixed 1,428,038 1,855,304
neko yield_burst 17,873 16,340
neko heap_same_time 185,714 40,404
neko heap_mixed 44,828 45,574
js yield_burst 472,605 409,659
js heap_same_time 2,620,288 1,193,683
js heap_mixed 298,195 395,691
  • Mixed due times: this PR is faster on every target, by 2% to 33%.
  • One shared due time: this PR is much slower except on hl. The old grouping only appended to an array there. Now every extraction sifts down the heap, and Int64 comparisons are expensive on eval, neko and js.
  • End to end: yield_burst moves between −16% and +4%. That is within the noise of single runs.

Alternative I tried: an event whose due time equals the previously inserted event's could join that event's FIFO group. Extraction would still take one event at a time, so it stays exception-safe, and it never searches the tree.

Target yield_burst heap_same_time heap_mixed
eval 51,373 232,287 66,691
jvm 1,500,001 20,000,019 1,174,168
hl 733,815 3,809,229 935,229
neko 17,825 200,000 39,695
js 457,361 2,980,061 324,405

It brings back the same-time speed, but every new due time then allocates a group, so mixed due times get slower than in this PR. End to end it's within noise as well. So I kept the simpler plain heap. The variant is about 30 more lines, if we ever want it.

Tests

🤖 Generated with Claude Code

Simn and others added 4 commits October 29, 2026 20:11
Each thread schedules events into its own queue, which the loop thread
drains. The queue's read and write indices were plain fields, so the
loop thread could see an advanced write index before the event in the
slot, or keep reading a storage array that a resize had replaced. It
then lost the event, and a coroutine waiting for it never resumed.

On the JVM, bursts of yields on a thread pool hung within a few rounds.
The indices are now atomic, so storing the write index after the slot
publishes both to the loop thread.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
scheduler/yield_burst runs many coroutines that only yield, through
CoroRun.run. scheduler/heap_same_time and scheduler/heap_mixed measure
the heap on its own with a VirtualTimeScheduler, with one due time for
all events and with 1000 different due times.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
MinimumHeap used to attach events with the same due time to an existing
node as child events, found by searching subtrees and undoing the sift
when a match turned up. That made insertion O(n) in the worst case, and
FIFO among equal due times only held when the search found the match.
Dispatching a node also dispatched its children, so if one of them threw,
the rest were lost.

The heap now orders events by due time and then by insertion sequence,
with one node per event. The schedulers extract and dispatch one event at
a time, so the events after a throwing one stay in the heap.
ThreadAwareScheduler moves the events from the thread queues into the
heap instead of collecting due events into a list of its own.
ScheduledEvent loses addChildEvent, its child events and next.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
With atomic indices, the scheduler's CircularQueue had become the same
data structure as WorkStealingQueue, so the scheduler now uses that. The
loop thread is the only consumer, so steal only returns null when the
queue is empty.

WorkStealingQueue now also publishes its storage atomically. A consumer
that loaded the write index before a resize could still read the new
storage afterwards through a plain field, without seeing the slots that
were copied into it. It would then take an empty slot and lose that
element. This affected both the thread pool and the scheduler.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Simn and others added 5 commits October 29, 2026 20:51
# Conflicts:
#	src/hxcoro/schedulers/ThreadAwareScheduler.hx
On hxcpp, AtomicObject.load returns an untyped hx::Object, so accessing
a field directly on its result generated a member access on hx::Object,
which doesn't compile. The slots are now loaded through a non-inline
function with a declared return type, which makes hxcpp convert the
object first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
On neko, assigning a declared field for the first time adds it to the
object, which is not safe while another thread reads the object. The
thread pool shares continuations between threads like that, so the test
failed there for reasons unrelated to the scheduler. This is tracked in
HaxeFoundation/neko#335.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Base automatically changed from fix-thread-queue-publication to master October 29, 2026 21:18
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

# Conflicts:
#	src/hxcoro/schedulers/ThreadAwareScheduler.hx
@Simn

Simn commented Oct 29, 2026

Copy link
Copy Markdown
Member Author

The benchmark times don't look particularly great but I think I've been paying too much attention to yield() micro benchmarks, and the reduction of complexity is nice here. The HL time changes are curious but then again it seems like having strange performance characteristics is basically HL's special move.

@Simn

Simn commented Oct 29, 2026

Copy link
Copy Markdown
Member Author

The C++ failures are unrelated with master failing too. We're currently not sure yet where they come from.

@Simn
Simn merged commit 3049c33 into master Oct 29, 2026
52 of 54 checks passed
@Simn
Simn deleted the scheduler-heap branch October 29, 2026 22:14
Simn added a commit that referenced this pull request Oct 29, 2026
This reverts commit d32d175. #193 fixed the same problem by giving every
scheduled event its own heap node and dispatching one event at a time,
so the requeue workaround is no longer needed. Its tests are on master
now, as part of #193.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Simn added a commit that referenced this pull request Oct 30, 2026
* Keep TrampolineDispatcher usable after a dispatched object throws

The exception still propagates to the caller of dispatch, but the
trampoline no longer stays marked as running, which made every later
dispatch on that thread queue up forever. Objects that were queued
behind the throwing one stay queued and run first on the next dispatch,
which keeps FIFO order.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Don't lose due scheduler events when dispatching one throws

The heap merges events with the same due time into child events of the
first one, and ThreadAwareScheduler collects all due events into a list
before dispatching them. With a dispatcher that runs events right away,
such as TrampolineDispatcher, an exception from one event dropped the
rest, e.g. other tasks' delay resumptions, which then never resumed.

The exception still propagates immediately, but the events that were
not dispatched yet go back into the heap, so the next loop runs them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Don't let a throwing task callback stop the others

ThreadSafeCallbacks.run stopped at the first callback that threw. For a
task's awaiters, that left the other awaiting tasks waiting forever. For
cancellation callbacks, the exception also escaped from cancel() and
skipped cancelling the children and the completion check.

Every callback now runs. An exception from one is reported by rethrowing
it from a separately scheduled event, so it surfaces like any uncaught
exception on the task's dispatcher without unwinding through the task
machinery. Rethrowing it synchronously after the other callbacks would
not be enough, because task completion nests: a child completes its
parent before resuming its own awaiters.

The same applies to a callback that is registered after the task
completed, which used to throw into the caller of onCompletion.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Test a throwing completion callback with the default test setup

On the targets whose CI runs use a thread pool, this checks that the
reported exception only aborts a worker thread and the run carries on.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Revert "Don't lose due scheduler events when dispatching one throws"

This reverts commit d32d175. #193 fixed the same problem by giving every
scheduled event its own heap node and dispatching one event at a time,
so the requeue workaround is no longer needed. Its tests are on master
now, as part of #193.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* simplify trampoline dispatch

* catch dispatch exception in LuvDispatcher too

* use @:allow instead of @:privateAccess

---------

Co-authored-by: Claude Opus 5.5 <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.

1 participant