Skip to content

Task migration and scheduling optimizations - #61

Merged
lalinsky merged 6 commits into
mainfrom
task-migration
Oct 21, 2025
Merged

lalinsky merged 6 commits into
mainfrom
task-migration

Conversation

@lalinsky

@lalinsky lalinsky commented Oct 20, 2025 •

Copy link
Copy Markdown
Owner

Summary

Implements task migration and LIFO slot optimization to improve multi-threaded runtime performance by reducing cross-thread wakeup overhead and improving cache locality.

Changes

1. Task State Differentiation (0bc15fd)

  • Split .waiting into .waiting_io and .waiting_sync states
  • Enables selective migration: sync tasks can migrate, I/O tasks cannot
  • Updated all synchronization primitives and I/O operations

2. LIFO Slot Optimization (d66a60d)

  • Added LIFO slot for recently woken tasks (immediate execution)
  • Changed queues from LIFO stack to FIFO queue for fairness
  • Added starvation prevention (max 3 consecutive LIFO polls)
  • Yields always go to next_ready_queue (bypasses LIFO for fairness)

3. Task Migration (6953096)

  • Sync tasks (.waiting_sync) migrate to waker's executor when woken from different thread
  • I/O tasks (.waiting_io) stay pinned to home executor (I/O callbacks are executor-bound)
  • Migration updates parent_context_ptr to point to new executor's context
  • Eliminates expensive remote wakeup notifications for sync operations

Performance Impact

Task Migration: When task A on executor 1 wakes task B (originally on executor 0), B now migrates to executor 1. This avoids:

  • Cross-thread notification (remote queue push + async wakeup)
  • Thread context switches
  • Remote memory access

LIFO Slot: Recently woken tasks execute immediately with hot cache, improving:

  • Cache locality for producer-consumer patterns
  • Latency for quick operations after wakeup

Test Results

All 99 tests pass, including multi-threaded tests that exercise migration across executors.

Summary by CodeRabbit

  • New Features

    • Configurable LIFO-slot wakeup optimization enabled by default.
    • Task pinning to keep tasks on their home executor, with runtime- and executor-level pin controls and an API to distinguish specific executors.
    • New scheduling primitives to route tasks locally or remotely for better locality.
  • Improvements

    • Reworked scheduling loop for improved cache locality and fewer cross-thread wakeups.
    • Starvation guards with smarter FIFO fallback to preserve fairness.
    • Exposed observability for LIFO and pinning state.

Implement a LIFO slot optimization inspired by Tokio's scheduler to improve
cache locality when tasks wake other tasks. When a task wakes another task,
the woken task is placed in a LIFO slot for immediate execution on the same
thread, maximizing the chance that data is still in the CPU cache.

Key changes:
- Add lifo_slot field to Executor for immediate task execution
- Change ready_queue and next_ready_queue from LIFO stack to FIFO queue
- Add getNextTask() helper that checks LIFO slot before ready_queue
- Add scheduleLocal() helper for local task scheduling with LIFO logic
- Implement starvation prevention (MAX_LIFO_POLLS_PER_TICK = 3)
- Fix event loop blocking to check both ready_queue and lifo_slot
- Refactor spin loop to track count across iterations

The LIFO slot is enabled by default as it provides both better cache locality
and maintains backward-compatible timing (woken tasks run immediately).

Displaced LIFO tasks and yields go to the FIFO ready_queue for fairness.
Tasks waiting on synchronization primitives now migrate between executors
when woken from a different thread, avoiding expensive remote wakeup notifications.

When task A on executor 1 wakes task B (originally on executor 0):
- If B is in waiting_sync state: B migrates to executor 1 by updating parent_context_ptr
- If B is in waiting_io state: B stays on executor 0 (I/O callbacks are executor-bound)

This eliminates the need for cross-thread notification (remote queue + async wakeup)
when tasks wake each other, significantly reducing wakeup latency.

Implementation:
- scheduleTask() now handles state swap and migration logic
- Sync tasks (.waiting_sync) migrate by updating coro.parent_context_ptr
- I/O tasks (.waiting_io) are pinned to home executor
- yield() re-derives executor after resuming to handle migration
- Added scheduleTaskLocal() and scheduleTaskRemote() helpers
@coderabbitai

coderabbitai Bot commented Oct 20, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Adds task pinning and a LIFO wakeup slot, converts ready queues to FIFO, introduces local/remote scheduling primitives and getNextTask, updates resume/yield flow to use new scheduling, and exposes pin/lifo state via Runtime/Executor public APIs. (≤50 words)

Changes

Cohort / File(s) Summary
Configuration & Spawn API
src/runtime.zig
Added RuntimeOptions.lifo_slot_enabled: bool = true, SpawnOptions.pinned: bool = false, and ExecutorId.isId() method.
Task state
src/runtime.zig
AnyTask gains pin_count: u32 to track pinned residency on home executor.
Executor state & queues
src/runtime.zig
Executor exposes lifo_slot: ?*WaitNode, lifo_slot_enabled: bool, lifo_slot_used: u8; changed ready_queue/next_ready_queue from SimpleStack to SimpleQueue.
Scheduling primitives & pinning
src/runtime.zig
New Executor APIs: scheduleTask, scheduleTaskLocal, scheduleTaskRemote, getNextTask, beginPin, endPin; Runtime exposes beginPin/endPin. Resume/yield updated to use these.
Scheduler loop & wakeup flow
src/runtime.zig
Drain remote-ready into local queues; prefer LIFO slot when enabled with starvation guard; cooperative yields and resume routing updated; pinning prevents cross-executor migration when active.

Sequence Diagram(s)

sequenceDiagram
    participant Runtime
    participant Executor
    participant LIFO as LIFO_Slot
    participant ReadyQ as Ready_Queue
    participant Remote as Remote_Queue
    participant Task

    rect rgb(247,249,255)
    Task->>Executor: scheduleTask(mode)
    alt local && lifo_enabled
        Executor->>LIFO: try_place(task)
    else remote_or_lifo_unavailable
        Executor->>Remote: scheduleTaskRemote -> enqueue(remote)
    end
    end

    rect rgb(255,250,245)
    Executor->>Executor: drain_remote_into_ready()
    Executor->>LIFO: poll_lifo()
    alt lifo_returns && not_starving
        LIFO-->>Executor: task
    else
        ReadyQ-->>Executor: dequeue()
    end
    Executor->>Task: resume/execute
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

🐰
I tuck a task where LIFO sings,
pin snug like burrows, safe and snug,
FIFO hums to keep the rings,
no hop is wasted, no task unplug,
tiny paws guard every scheduler hug.

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title "Task migration and scheduling optimizations" directly aligns with the core objectives of this pull request. According to the PR objectives, the pull request implements two main features: (1) task migration where sync tasks migrate to the waker's executor to reduce cross-thread overhead, and (2) LIFO slot optimization along with queue fairness improvements to enhance cache locality and scheduling efficiency. The title concisely captures both of these primary changes without vague language, file lists, or unnecessary noise, making it clear for developers scanning history that this PR focuses on performance improvements through task relocation and scheduling refinements.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch task-migration

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

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

Actionable comments posted: 0

🧹 Nitpick comments (7)
src/runtime.zig (7)

55-61: LIFO toggle looks good; consider exposing the starvation cap as an option.

Default‑on LIFO makes sense and matches the documented timing. Recommend adding a RuntimeOptions knob for MAX_LIFO_POLLS_PER_TICK (currently hardcoded to 3) to ease tuning across workloads.


845-861: Queue swap to FIFO + LIFO slot fields—LGTM; add an invariant/assert for thread‑affinity.

ready_queue/next_ready_queue moving to SimpleQueue improves fairness; LIFO fields are clear. Since scheduleTaskLocal must run on the owning executor thread, add a debug assert to catch accidental cross‑thread use.

Apply this diff near the start of scheduleTaskLocal:

 fn scheduleTaskLocal(self: *Executor, task: *AnyTask, is_yield: bool) void {
+    if (builtin.mode == .Debug or builtin.mode == .ReleaseSafe) {
+        std.debug.assert(Runtime.current_executor == self);
+    }

Also applies to: 907-907


1068-1072: Yield fairness and direct handoff look right; gate the TLS assert to debug builds.

  • Yields bypass the LIFO slot—good for fairness.
  • Directly switching to getNextTask() preserves locality.
  • The TLS re‑derive/assert is great for safety but can be debug‑only.

Apply this diff:

-        const resumed_executor = Runtime.current_executor orelse unreachable;
-        std.debug.assert(resumed_executor.current_coroutine == current_coro);
+        if (builtin.mode == .Debug or builtin.mode == .ReleaseSafe) {
+            const resumed_executor = Runtime.current_executor orelse unreachable;
+            std.debug.assert(resumed_executor.current_coroutine == current_coro);
+        }

Also applies to: 1080-1090, 1091-1095


1197-1197: Event loop spin budget: good latency hedge; make the threshold configurable and add a backoff cap.

  • Atomic drain of remote ready to local ready_queue is correct.
  • Single‑tick processing then moving next_ready_queue → ready_queue preserves fairness.
  • Spin with .no_wait for up to 16 iterations reduces cross‑thread wake latency. Suggest:
    • Expose the spin threshold (16) in RuntimeOptions for tuning.
    • Optionally track a simple exponential backoff or a max busy‑time budget to avoid wasted CPU on idle systems.

Also applies to: 1210-1215, 1217-1219, 1257-1258, 1259-1273


1276-1315: LIFO starvation guard is clear; consider making MAX_LIFO_POLLS_PER_TICK configurable.

The “move LIFO to FIFO when hitting the cap” logic is sound and resets on FIFO pops. Surfacing the “3” as an option alongside lifo_slot_enabled would help portability across workloads.


1343-1357: Remote notify: keep the guard; prefer std.log.warn for visibility.

Guarding on remote_initialized avoids use before init. For the warning, use std.log.warn to integrate with logging.

Apply this diff:

-            self.remote_wakeup.notify() catch |err| {
-                std.debug.print("WARNING: remote_wakeup.notify() failed for executor {}: {}\n", .{ self.id, err });
-            };
+            self.remote_wakeup.notify() catch |err| {
+                std.log.warn("remote_wakeup.notify() failed for executor {}: {}", .{ self.id, err });
+            };

1359-1429: State machine in scheduleTask(): tighten unexpected‑state handling and add a safe release path.

The state transitions look correct (including .preparing_to_wait short‑circuit and IO pinning). Two improvements:

  • Don’t hard‑panic on unexpected states in release; log and return to avoid crashing production on rare double‑resume bugs.
  • Optionally special‑case .dead to no‑op (defensive).

Apply this diff:

-        if (old_state != .waiting_sync and old_state != .ready) {
-            std.debug.panic("scheduleTask: unexpected state {} for task {*}", .{ old_state, task });
-        }
+        if (old_state != .waiting_sync and old_state != .ready) {
+            if (builtin.mode == .Debug or builtin.mode == .ReleaseSafe) {
+                std.debug.panic("scheduleTask: unexpected state {} for task {*}", .{ old_state, task });
+            } else {
+                // Defensive no-op in release to avoid taking down the process.
+                std.log.err("scheduleTask: unexpected state {} for task {*}, ignoring", .{ old_state, task });
+                return;
+            }
+        }

Please run your stress/migration tests with a forced error injection (simulate a spurious resume) to confirm the no‑op path behaves safely under release builds.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 347fe8a and 6953096.

📒 Files selected for processing (1)
  • src/runtime.zig (9 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: test (windows-latest)
🔇 Additional comments (2)
src/runtime.zig (2)

340-345: Centralizing wakeups via home executor is a solid simplification.

Routing resumeTask() through Executor.scheduleTask() on the task’s home executor removes foot‑guns and cleanly enables migration. No issues spotted.

Also applies to: 347-349


1317-1341: Local scheduling paths and displacement policy—LGTM.

  • Yields → next_ready_queue is the right fairness call.
  • LIFO displacement to FIFO avoids losing locality while preventing bubbles.
    No changes needed.

Adds fine-grained control over task migration with per-task pin counters.
Pinned tasks always stay on their home executor, even when woken from other threads.

Features:
- SpawnOptions.pinned: Pin tasks at spawn time
- AnyTask.pin_count: Nestable pin counter (like shield_count)
- Runtime.beginPin()/endPin(): Dynamic pinning control
- scheduleTask() checks pin_count before migrating

Use cases:
- Tasks with thread-local state or executor-specific resources
- Tasks requiring specific thread affinity
- Fine-grained control over migration behavior

Tasks with pin_count > 0 skip migration and stay on home executor.
- Add ExecutorId.isId() helper method
- Tasks spawned with .executor = .id(N) are now automatically pinned
- Ensures tasks with explicit executor assignment stay on that executor
- Cleaner code with executor.isId() vs manual comparisons

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/runtime.zig (1)

1226-1303: LGTM: Spin loop reduces cross-thread wakeup latency.

The spin loop (up to 16 iterations) before blocking reduces latency for cross-thread wakeups. The logic correctly checks both ready_queue and lifo_slot for available work and properly resets/increments the spin counter.

Consider making the spin count (currently hard-coded to 16) configurable via RuntimeOptions if fine-tuning is needed for different workloads in the future.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6953096 and cfd8c4c.

📒 Files selected for processing (1)
  • src/runtime.zig (14 hunks)
🔇 Additional comments (10)
src/runtime.zig (10)

44-47: LGTM: Clear documentation for pinning behavior.

The pinned field is well-documented and the default value of false maintains backward compatibility.


59-64: LGTM: LIFO slot feature is well-documented.

The documentation clearly explains both the performance benefit and the backward-compatibility rationale for the default value.


342-353: LGTM: Correctly derives home executor for migration support.

The change to derive home_executor from the task (via Executor.fromCoroutine) is essential for migration, as parent_context_ptr may have been updated when the task migrated to a different executor.


363-363: LGTM: Pin counter supports nested pinning.

The pin_count field allows for nested beginPin()/endPin() calls, similar to the existing shield_count pattern.


850-865: LGTM: Queue type change and LIFO slot design are sound.

The change from SimpleStack (LIFO) to SimpleQueue (FIFO) for the regular ready queues, combined with the separate LIFO slot for recently woken tasks, provides a good balance between cache locality and fairness. The starvation prevention counter using u8 is sufficient.


1101-1104: LGTM: Correctly handles post-migration executor context.

Re-deriving the executor from TLS after resuming is essential because the task may have migrated to a different executor during the yield. The comment clearly explains this critical detail.


1146-1163: LGTM: Pin methods follow established pattern.

The beginPin()/endPin() implementation mirrors the existing beginShield()/endShield() pattern, providing a consistent API for nested resource management.


1305-1344: LGTM: Starvation prevention logic is sound.

The LIFO slot starvation prevention correctly limits consecutive LIFO polls to 3 (matching Tokio's MAX_LIFO_POLLS_PER_TICK), and when the limit is hit, moves the LIFO task to the back of the ready queue to ensure fairness.


1346-1386: LGTM: Local and remote scheduling logic is correct.

scheduleTaskLocal() correctly routes yields to next_ready_queue to bypass the LIFO slot for fairness, while woken tasks use the LIFO slot for cache locality. scheduleTaskRemote() safely handles cross-thread scheduling with proper initialization checks.


1971-1991: LGTM: Runtime pin methods follow established delegation pattern.

The beginPin()/endPin() methods correctly delegate to the current executor and handle the case where they're called outside of a coroutine context.

Comment thread src/runtime.zig Resolved
When a task waits on select() with multiple branches that complete at the
same time on different threads, both threads call scheduleTask() concurrently.
The first thread sees old_state=.waiting_sync and schedules the task correctly.
The second thread sees old_state=.ready (already changed by first thread) and
would reach the default path, scheduling the task again.

Fixed by:
1. Initialize spawned tasks with .waiting_sync instead of .ready
2. Add early return in default path if old_state==.ready to detect
   and skip tasks already transitioned by another thread

This prevents tasks from being enqueued twice while preserving correct
spawn and normal wake behavior.

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

Actionable comments posted: 0

♻️ Duplicate comments (1)
src/runtime.zig (1)

1393-1466: Critical: Incomplete fix for double-scheduling race.

Line 1453 adds an early return for old_state == .ready to prevent double-scheduling when multiple SelectWaiter instances wake the same task concurrently (as discussed in past review). However, this creates a new problem:

Issue: The spawn path (lines 1000-1022) starts with task state .waiting_sync (line 1000), then calls scheduleTask() at line 1022. At that point:

  • old_state = task.coro.state.swap(.ready, ...) returns .waiting_sync (initial state)
  • Line 1426 assertion passes: old_state == .waiting_sync
  • Code proceeds to migration logic (lines 1431-1449)
  • Eventually reaches default path (lines 1455-1466) and schedules the task

But for spawn, we're on the correct executor (self), and there's no prior state to migrate from. The current code works, but the logic is convoluted.

Recommended fix: Add explicit spawn detection before migration logic:

     // Handle .waiting_sync or .ready (spawn) states
     if (old_state != .waiting_sync and old_state != .ready) {
         std.debug.panic("scheduleTask: unexpected state {} for task {*}", .{ old_state, task });
     }
+
+    // Double-wake: another thread already scheduled this task (select() race)
+    if (old_state == .ready) return;
 
     // Sync tasks can migrate for cache locality (waiting_sync state only)
     if (old_state == .waiting_sync and mode == .maybe_remote and task.pin_count == 0) {
         ...
     }
 
     // Different runtime - use remote scheduling on home executor
     self.scheduleTaskRemote(task);
     return;
 }
-
-    // Task already transitioned to .ready by another thread - avoid double-schedule
-    if (old_state == .ready) return;

This way:

  • Double-wake returns early (before migration logic)
  • Spawn (initial .waiting_sync) goes through migration logic as intended
  • Migration check explicitly requires old_state == .waiting_sync
🧹 Nitpick comments (1)
src/runtime.zig (1)

1155-1158: Consider pin_count overflow protection.

The pin_count field (u32) has no overflow protection. While 4 billion nested pins is unrealistic in practice, a buggy caller could trigger wraparound in a loop, causing the assertion at line 1166 to fire incorrectly.

Consider saturation arithmetic:

 pub fn beginPin(self: *Executor) void {
     const current_coro = self.current_coroutine orelse unreachable;
     const current_task = AnyTask.fromCoroutine(current_coro);
-    current_task.pin_count += 1;
+    if (current_task.pin_count < std.math.maxInt(u32)) {
+        current_task.pin_count += 1;
+    }
 }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c306427 and 2f3f020.

📒 Files selected for processing (1)
  • src/runtime.zig (15 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: test (windows-latest)
🔇 Additional comments (16)
src/runtime.zig (16)

39-42: LGTM!

The isId() method cleanly distinguishes specific executor IDs from sentinel values (.any and .same), providing a clear API for pinning logic.


49-52: LGTM!

The pinned field is well-documented and correctly defaults to false, allowing migration by default while providing explicit control when needed.


64-69: LGTM!

The LIFO slot option is well-documented with clear explanation of both the cache locality benefits and the backward-compatibility rationale for enabling it by default.


349-357: LGTM!

The refactor correctly derives the home executor from the task's parent_context_ptr, ensuring that scheduling respects potential task migration.


855-870: LGTM!

The queue structure changes are well-documented:

  • Migration to FIFO queues provides fairness for regular tasks
  • LIFO slot enables cache locality for recently woken tasks
  • Starvation counter prevents LIFO slot monopolization

1009-1012: LGTM!

The pinning logic correctly sets pin_count = 1 for both explicitly pinned tasks and tasks assigned to specific executors, ensuring they remain on their designated executor.


1095-1109: Excellent migration safety fix!

Lines 1106-1109 correctly re-derive the executor from TLS (Runtime.current_executor) after resuming, since the task may have migrated to a different executor during suspension. Using the captured self would be incorrect and lead to memory safety issues.


1151-1168: LGTM!

The pinning API is straightforward with proper assertion to catch unbalanced beginPin()/endPin() calls. Documentation clearly explains the purpose and usage.


1310-1349: LGTM! Well-designed starvation prevention.

The LIFO slot optimization correctly balances cache locality with fairness:

  • Allows up to 3 consecutive LIFO polls for cache-hot execution
  • At limit, displaces LIFO task to back of FIFO queue
  • Counter resets only when polling from ready_queue, ensuring fairness

The MAX_LIFO_POLLS_PER_TICK = 3 value matches Tokio's approach (as noted in comment), providing battle-tested behavior.


1351-1374: LGTM! Clear scheduling policy.

The scheduleTaskLocal() routing is well-designed:

  • Yields bypass LIFO slot (not cache-hot, should wait their turn)
  • Wakeups use LIFO slot when enabled (cache-hot, immediate execution)
  • Displaced tasks go to FIFO queue for fairness

1376-1391: LGTM!

The remote scheduling correctly uses the thread-safe next_ready_queue_remote and guards notification with remote_initialized check to avoid notifying before the event loop is ready.


1979-1999: LGTM!

The Runtime-level pinning API correctly delegates to the executor and handles non-coroutine contexts gracefully with no-op behavior.


1244-1248: LGTM!

The remote queue draining is correct: popAll() atomically captures all remote tasks, then pushes them to the local ready_queue for FIFO processing.


917-917: LGTM!

The LIFO slot configuration is correctly initialized from RuntimeOptions.lifo_slot_enabled with appropriate default (true).


1293-1306: Concern #2 is based on a misunderstanding of queue flow; the other concerns are either valid but not bugs or consistent with codebase patterns.

The next_ready_queue is merged into ready_queue at line 1291 via concatByMoving() before the work detection check at line 1295. By that point, next_ready_queue is empty, so checking next_ready_queue.head would be incorrect—it would not reflect actual work availability.

The work detection correctly checks ready_queue.head (which now includes merged yield tasks) and lifo_slot. This is sound.

Regarding the wrapping behavior (concern #3): The +%= pattern is intentional and consistent with similar spin loops elsewhere in the codebase (e.g., concurrent_queue.zig). Since spin_count exits at 16 and is u8, wrapping won't occur during normal operation—the pattern is safe.

The hardcoded threshold of 16 (concern #1) is reasonable for reducing cross-thread wakeup latency, though it could be made configurable if platform-specific tuning becomes necessary.

Likely an incorrect or invalid review comment.


1441-1441: The race condition in the original review comment is valid. Move parent_context_ptr update before the state change to .ready.

The migration sequence has a genuine synchronization issue:

  1. At line 1405, the task state transitions to .ready with .release semantics
  2. At line 1441, parent_context_ptr is updated (after the state change)
  3. Meanwhile, external code could call resumeTask() (line 347) with the task's coroutine pointer, which immediately calls Executor.fromCoroutine(&task.coro) at line 356—reading parent_context_ptr

The .release memory ordering on the state store does not guarantee visibility of the subsequent pointer update at line 1441 to readers who observe the .ready state via .acquire semantics. Another thread could see the task in .ready state but read the stale parent_context_ptr value, causing it to route to the wrong executor.

Fix: Update parent_context_ptr atomically with the state transition or immediately before it, ensuring both changes are visible together.

@lalinsky
lalinsky merged commit aa52d09 into main Oct 21, 2025
@lalinsky
lalinsky deleted the task-migration branch October 21, 2025 07:09
lalinsky added a commit that referenced this pull request Jan 6, 2026
* Add dir_open and dir_close operations

Implements directory opening and closing operations with async I/O support:

- Add DirOpenFlags structure with follow_symlinks and iterate options
- Add opendirat() function for POSIX (O_DIRECTORY) and Windows (FILE_FLAG_BACKUP_SEMANTICS)
- Add DirOpen and DirClose completion types
- Add native io_uring backend support
- Add thread pool fallback for other backends
- Export new operations in public API

* Add dir_open and dir_close to all backends
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