Repository navigation
Conversation
This properly sets the canceled flag when a timeout occurs, allowing tasks to detect timeout cancellation. Also added TODO comments for potential race conditions.
Simplifies timeout handling by using the new Timeout API: - Uses task's shared timer heap instead of per-call timer - Distinguishes timeout from explicit cancel via timeout.triggered - Handles fairness: re-signals if we stole a wakeup from signal()
…e mutex reacquisition - Round instead of truncate in Timeout.set to prevent sub-ms timeouts becoming 0ms - Clear timeout in Condition.timedWait before mutex.lockUncancelable() to prevent spurious timeout during contended lock - Add debug assertions that timeout.triggered is false on success paths
- Refactor Executor.sleep to use Timeout pattern instead of timedWaitForReady - Fix timeout_count leak: decrement in timeoutCallback when setting active=false - Clear timer userdata in timeoutCallback to prevent stale pointer comparisons - Fixes hang when multiple sleeps are called sequentially on same task
- Change task from *AnyTask to ?*AnyTask (null means inactive) - Remove redundant active boolean field - Remove unnecessary timeout_count field (heap already tracks timeouts) - Simplify init() from function to constant: Timeout.init - Update all callers to use Timeout.init instead of Timeout.init(runtime)
- Replace timedWaitForReadyWithCallback with Timeout + yield - Remove callback-based timeout handling - Simplify error handling with timeout.triggered check - Add debug assertion for success path
Replace simple boolean canceled flag with a packed struct (u32) that tracks: - user_canceled (u8): counter for user-initiated cancellations - timeout (u8): counter for timeout-triggered cancellations - pending_errors (u16): number of error.Canceled to return in yield This enables proper handling of concurrent cancellations from multiple sources and allows distinguishing between timeout and user cancellation. Key changes: - Add CanceledStatus packed struct and CAS-based atomic operations - Add AnyTask.checkTimeout() to check and consume timeout cancellations - Add AnyTask.checkCanceled() to check and consume pending errors - Add Runtime.checkTimeout() convenience wrapper - Update all timeout handling code to use checkTimeout() instead of checking timeout.triggered directly - Update Executor.yield() to use new checkCanceled() method All operations use optimized CAS loops that leverage returned previous values to avoid unnecessary atomic loads on retry.
Simplifies the API by making checkCanceled() automatically respect cancellation shields. This prevents accidentally consuming cancellation errors while shielded and makes the code more maintainable. The shield_count check is now internal to checkCanceled(), so callers in yield() only need to check cancel_mode without also checking shield_count.
WalkthroughReplaces a boolean cancel flag with a packed atomic Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes
Possibly related PRs
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/core/awaitable.zig (1)
24-90: Guard cancellation counters against overflow.
CanceledStatusstoresuser_canceled/timeoutinu8andpending_errorsinu16, yetcancel()just increments them. After 255 user cancels (or 255 timeouts, 65 535 total pending errors) the add will trap in Debug/ReleaseSafe and silently wrap in fast builds, causing us to lose track of queued errors. Long‑running tasks that retry on timeout can absolutely hit those limits. Please widen the counters and the backing atomic so the bookkeeping can’t roll over.-pub const CanceledStatus = packed struct(u32) { - user_canceled: u8 = 0, - timeout: u8 = 0, - pending_errors: u16 = 0, -}; +pub const CanceledStatus = packed struct(u64) { + user_canceled: u16 = 0, + timeout: u16 = 0, + pending_errors: u32 = 0, +}; … - canceled_status: std.atomic.Value(u32) = std.atomic.Value(u32).init(0), + canceled_status: std.atomic.Value(u64) = std.atomic.Value(u64).init(0), … - const new: u32 = @bitCast(status); + const new: u64 = @bitCast(status);
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (12)
src/core/awaitable.zig(3 hunks)src/core/blocking_task.zig(1 hunks)src/core/task.zig(4 hunks)src/core/timeout.zig(1 hunks)src/io/base.zig(1 hunks)src/runtime.zig(6 hunks)src/signal.zig(1 hunks)src/sync/Condition.zig(2 hunks)src/sync/Notify.zig(3 hunks)src/sync/ResetEvent.zig(3 hunks)src/zio.zig(1 hunks)vendor/libxev/src/main.zig(1 hunks)
🧰 Additional context used
🧠 Learnings (5)
📚 Learning: 2025-10-10T05:59:17.087Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 41
File: src/udp.zig:79-82
Timestamp: 2025-10-10T05:59:17.087Z
Learning: In UDP socket operations (src/udp.zig), error.Canceled from result_data.result represents OS/IO-level cancellation (e.g., io_uring), not user-requested cancellation. User cancellation is handled by waitForXevCompletion() via try. OS-level error.Canceled should be mapped to error.Unexpected as it represents an unexpected system event.
Applied to files:
src/core/awaitable.zigsrc/core/blocking_task.zigsrc/io/base.zigsrc/signal.zig
📚 Learning: 2025-10-15T19:38:44.659Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 47
File: src/sync/Mutex.zig:237-237
Timestamp: 2025-10-15T19:38:44.659Z
Learning: In the `unlock` method of `src/sync/Mutex.zig`, the `runtime` parameter is intentionally retained (marked with `_ = runtime;`) for API consistency and future-proofing, even though it's not currently used in the implementation.
Applied to files:
src/sync/Condition.zigsrc/runtime.zig
📚 Learning: 2025-10-21T10:00:56.962Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 62
File: src/utils/queue.zig:141-147
Timestamp: 2025-10-21T10:00:56.962Z
Learning: In work-stealing queues implemented in src/utils/queue.zig, stealers only modify the victim's head position, never the tail. The tail is exclusively owned by the owner thread, so no atomic acquire operations are needed when the owner reads its own tail.
Applied to files:
src/sync/Condition.zig
📚 Learning: 2025-10-16T14:33:19.718Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 48
File: src/core/ConcurrentAwaitableList.zig:254-269
Timestamp: 2025-10-16T14:33:19.718Z
Learning: In the zio repository's `src/core/ConcurrentAwaitableList.zig` and `src/core/Awaitable.zig`, the `in_list` field should remain debug-only (conditional compilation with `builtin.mode == .Debug`). Double-removal detection in `ConcurrentAwaitableList.remove()` uses pointer-based checks (comparing `prev`/`next` against `head`/`tail`) rather than relying on a regular `in_list` field.
Applied to files:
src/core/blocking_task.zig
📚 Learning: 2025-10-03T11:09:46.846Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 18
File: src/net.zig:18-25
Timestamp: 2025-10-03T11:09:46.846Z
Learning: In zio's `Runtime.BlockingTask`, calling `deinit()` on a blocking task only frees the task wrapper (TaskData) itself, not the result returned by the blocking function. The result remains valid and owned by the caller, who is responsible for its cleanup. This is the intended design for async blocking tasks.
Applied to files:
src/core/blocking_task.zigsrc/core/task.zig
⏰ 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)
…ock usage Changes checkTimeout signature to take the caught error as a parameter, making it explicit that this function should be called from a catch block. The function now returns either error.Timeout (if the timeout triggered) or the original error.Canceled (if user canceled). This improves the API by: - Making the usage pattern more explicit (must be in catch block) - Clearly showing the error transformation (Canceled -> Timeout) - Reducing the chance of incorrect usage Special handling in sleep() where timeout is the expected success case - it catches error.Timeout and returns void (success), while propagating error.Canceled.
Once user_canceled > 0, the task is "condemned" and must quit. This commit implements priority-based cancellation handling: In timeoutCallback: - If user_canceled > 0: Only increment pending_errors (task already condemned) - Otherwise: Increment both timeout and pending_errors, set triggered=true - This ensures timeout information is discarded once user cancels In checkTimeout: - Always check user_canceled first - if > 0, return error.Canceled - Only check timeout if no user cancellation exists - user_canceled is never decremented (permanent condemnation marker) - timeout counter is decremented when consumed This design ensures: - User cancellation is non-recoverable and has absolute priority - Multiple cancel() calls stack as multiple error.Canceled - Timeout cancellation is recoverable via checkTimeout - Once user cancels, subsequent timeouts don't set triggered flag - Clean semantics: condemned tasks always return error.Canceled
Since user_canceled is never decremented and only checked for > 0, it can be simplified to a bool flag. The "condemned" state is binary - either the user has requested cancellation or they haven't. Multiple cancel() calls still stack properly via the pending_errors counter, which gets decremented by checkCanceled(). Changes: - CanceledStatus.user_canceled: u8 -> bool (with u7 padding) - cancel(): Set flag instead of increment - timeoutCallback: Check bool instead of > 0 - checkTimeout: Check bool instead of > 0 This simplification makes the semantics clearer: user_canceled is a permanent condemnation flag, not a counter.
Adds 6 new tests covering key timeout scenarios: - Timeout fires and returns error.Timeout - Nested timeouts - earliest deadline fires first - Timeout cleared before firing doesn't trigger - User cancellation has priority over timeout - Multiple timeouts with different deadlines (heap ordering) - Set, clear, and re-set timeout lifecycle All tests verify correct behavior of the priority-based cancellation system where user_canceled takes precedence over timeout. 159 of 159 tests passing.
There was a problem hiding this comment.
Actionable comments posted: 2
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (8)
src/core/awaitable.zig(3 hunks)src/core/task.zig(4 hunks)src/io/base.zig(1 hunks)src/runtime.zig(6 hunks)src/select.zig(1 hunks)src/sync/Condition.zig(2 hunks)src/sync/Notify.zig(3 hunks)src/sync/ResetEvent.zig(3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- src/sync/Condition.zig
🧰 Additional context used
🧠 Learnings (3)
📚 Learning: 2025-10-10T05:59:17.087Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 41
File: src/udp.zig:79-82
Timestamp: 2025-10-10T05:59:17.087Z
Learning: In UDP socket operations (src/udp.zig), error.Canceled from result_data.result represents OS/IO-level cancellation (e.g., io_uring), not user-requested cancellation. User cancellation is handled by waitForXevCompletion() via try. OS-level error.Canceled should be mapped to error.Unexpected as it represents an unexpected system event.
Applied to files:
src/io/base.zigsrc/runtime.zigsrc/core/awaitable.zig
📚 Learning: 2025-10-03T11:09:46.846Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 18
File: src/net.zig:18-25
Timestamp: 2025-10-03T11:09:46.846Z
Learning: In zio's `Runtime.BlockingTask`, calling `deinit()` on a blocking task only frees the task wrapper (TaskData) itself, not the result returned by the blocking function. The result remains valid and owned by the caller, who is responsible for its cleanup. This is the intended design for async blocking tasks.
Applied to files:
src/runtime.zigsrc/core/task.zig
📚 Learning: 2025-10-16T14:33:19.718Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 48
File: src/core/ConcurrentAwaitableList.zig:254-269
Timestamp: 2025-10-16T14:33:19.718Z
Learning: In the zio repository's `src/core/ConcurrentAwaitableList.zig` and `src/core/Awaitable.zig`, the `in_list` field should remain debug-only (conditional compilation with `builtin.mode == .Debug`). Double-removal detection in `ConcurrentAwaitableList.remove()` uses pointer-based checks (comparing `prev`/`next` against `head`/`tail`) rather than relying on a regular `in_list` field.
Applied to files:
src/runtime.zig
🔇 Additional comments (13)
src/runtime.zig (5)
521-524: LGTM - Pre-yield cancellation check.The change correctly uses the new
checkCanceled()API to consume one pending error before yielding, which aligns with the new counter-based cancellation model.
559-562: LGTM - Post-resume cancellation check.Correctly checks for cancellation after resuming, ensuring cancellations that occurred during suspension are detected.
586-592: LGTM - Updated cancellation semantics.Documentation correctly describes the new behavior of consuming one pending error, and the implementation properly delegates to the task-level method.
622-639: LGTM - Clean timeout-based sleep implementation.The RAII-style Timeout with defer cleanup is elegant. The catch block correctly distinguishes between timeout expiration (returns successfully) and user cancellation (propagates error), with proper unreachable markers indicating the expected flow.
1172-1182: LGTM - Well-designed public timeout check API.The documentation clearly explains the usage pattern (call in catch blocks), and the implementation correctly delegates to the task-level logic with appropriate no-op behavior when not in a coroutine.
src/core/task.zig (8)
30-40: LGTM - Well-structured per-task timeout state.The fields support the new timeout infrastructure with a clear separation of concerns: heap storage (
timeouts), timer state (timer_c,timer_cancel_c), and behavioral controls (shield_count,pin_count).
80-85: LGTM - Correct migration check with new cancellation status.The change correctly checks the packed
CanceledStatus(any non-zero value prevents migration), maintaining the same safety guarantee with the new counter-based model.
87-103: LGTM - Correct timeout queue management.The method properly handles expired timeouts and calculates delays for the next valid timeout. The
unreachablemarker is correct since all paths through the loop return a value.
105-165: LGTM - Solid timer lifecycle management.The timer methods handle edge cases correctly (dead timer, null userdata) and the defensive clearing of userdata before cancellation prevents spurious callbacks. The
maybeUpdateTimeroptimization (only resetting when the timeout pointer changes) is a nice touch.
167-201: LGTM - Correct timeout priority logic.The implementation correctly enforces user cancellation priority (always returns
error.Canceledifuser_canceledis set) and only returnserror.Timeoutwhen the timeout actually triggered and hasn't been consumed yet. The documentation clearly notes thatpending_errorsis consumed separately bycheckCanceled(), which is the correct design.
203-230: LGTM - Clean cancellation check with shield support.The implementation correctly respects cancellation shields and uses a CAS loop to atomically consume one pending error. The early return when no errors are pending avoids unnecessary spinning.
320-382: LGTM - Careful timeout cancellation logic.The callback correctly handles the distinction between user-initiated and timeout-initiated cancellations using the
mark_as_triggeredflag. The CAS loop ensuresmark_as_triggeredreflects the state that was actually committed, and even in race scenarios,checkTimeoutcorrectly prioritizes user cancellation by checkinguser_canceledfirst.
384-396: LGTM - Standard noop callback.Consistent with the existing
noopTimerCancelCallbackpattern in the codebase (e.g., runtime.zig line 92).
| const builtin = @import("builtin"); | ||
| const Runtime = @import("runtime.zig").Runtime; | ||
| const Cancelable = @import("common.zig").Cancelable; | ||
| const Timeoutable = @import("common.zig").Timeoutable; |
There was a problem hiding this comment.
Fix unused Timeoutable import
const Timeoutable = @import("common.zig").Timeoutable; isn’t referenced anywhere in this file, so Zig will stop with an unused-declaration error. Drop the import or wire it into the code before merging.
-const Timeoutable = @import("common.zig").Timeoutable;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const Timeoutable = @import("common.zig").Timeoutable; |
🤖 Prompt for AI Agents
In src/select.zig around line 8, the declaration "const Timeoutable =
@import(\"common.zig\").Timeoutable;" is unused and causes an unused-declaration
error; fix by either removing that import line entirely if Timeoutable is not
needed, or wire it into the file by using Timeoutable in the relevant function
signature/variable/type where timeouts are handled so the symbol is referenced
(choose the removal if there is no intended timeout-related API to implement).
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (1)
src/core/timeout.zig (1)
43-43: Sub-millisecond rounding (previously discussed)This rounding converts timeouts < 0.5ms to zero milliseconds, which sets the deadline to
now()and triggers at the next yield point. Based on the previous discussion, this millisecond-granularity behavior appears intentional, but it means microsecond-precision timeouts aren't supported.
🧹 Nitpick comments (2)
src/core/timeout.zig (2)
31-31: Add a comment explaining when this is validThe
unreachablehere will crash ifset()is called outside of a task context. This is probably the intended behavior (timeouts must be associated with tasks), but a brief comment explaining this precondition would help future readers understand the requirement.+ // Must be called from within a task context const task = self.task orelse rt.getCurrentTask() orelse unreachable;
43-44: Potential overflow in @intcast is unlikely but uncheckedCasting the u64 result to i64 could overflow for extremely large timeout_ns values (tens of thousands of years worth of milliseconds). In practice this won't happen, but you could add a debug assert or use
@intCastwith explicit overflow handling if you want to be defensive.Example with assert:
const timeout_ms: i64 = @intCast((timeout_ns + std.time.ns_per_ms / 2) / std.time.ns_per_ms); + std.debug.assert(timeout_ms >= 0); // Verify no overflow occurred
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/core/timeout.zig(1 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-10-10T05:59:17.087Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 41
File: src/udp.zig:79-82
Timestamp: 2025-10-10T05:59:17.087Z
Learning: In UDP socket operations (src/udp.zig), error.Canceled from result_data.result represents OS/IO-level cancellation (e.g., io_uring), not user-requested cancellation. User cancellation is handled by waitForXevCompletion() via try. OS-level error.Canceled should be mapped to error.Unexpected as it represents an unexpected system event.
Applied to files:
src/core/timeout.zig
🔇 Additional comments (7)
src/core/timeout.zig (7)
1-4: LGTM - clean importsThe imports are minimal and cover what's needed for the timeout infrastructure.
6-18: LGTM - well-documented structThe doc comment clearly explains the nesting behavior, RAII pattern, and how
triggereddistinguishes timeout-induced cancellation from explicit cancellation. The field types are appropriate for the timeout heap infrastructure.
20-28: LGTM - correct cleanupThe method properly handles the inactive case (early return), removes from the heap, updates the shared timer, and clears the task reference to allow reuse. The debug assert provides a reasonable safety check.
30-47: LGTM - set() logic is soundThe method correctly handles both first-set and re-set cases. Line 31 ensures that when
self.taskis non-null,taskequalsself.task, so the remove operation at line 39 operates on the right heap. The triggered reset (line 42), deadline computation (line 44), heap insertion (line 45), and timer update (line 46) all follow the correct sequence.
50-53: LGTM - correct min-heap comparatorOrders by earliest deadline first, which is exactly what's needed for the timeout heap.
56-56: LGTMClean type alias for the intrusive heap. The void context and timeoutLess comparator are correct.
61-274: LGTM - comprehensive test coverageThe test suite covers the essential scenarios: basic set/clear, timeout firing, nested timeouts with priority, clearing before expiration, user cancellation priority over timeout (key design requirement), multiple concurrent timeouts, and re-use patterns. All tests correctly use the RAII defer pattern for cleanup and properly verify both error values and the
triggeredfield state.
When timer_reset() is called while a cancellation is in-flight and the timer is in .adding state, the reset wasn't being properly handled in backends that use process_cancellations (iocp, kqueue). The issue: - Timer in .adding state when timer_reset() is called - Cancel is already in-flight (c_cancel.state() == .active) - timer_reset() modifies next/userdata/callback but doesn't set reset field - When process_cancellations runs, it marks timer .dead without checking reset - Timer never gets rearmed with new deadline The fix: - In timer_reset() .adding branch: set reset field when cancel is active - In process_cancellations() .adding case (iocp/kqueue): check reset and re-add timer - epoll/wasi_poll already handle this correctly in stop_completion() This was causing timeout tests to hang on Windows/macOS.
Call checkTimeout before clearing timeout state to preserve the triggered flag, ensuring real timeouts return error.Timeout instead of error.Canceled
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (1)
src/io/base.zig (1)
75-81: Remove redundant explicit timeout.clear().Good fix on the classification order (line 77 calls checkTimeout before clear, preserving the timeout triggered flag). However, line 78's explicit
timeout.clear(rt)is redundant—the defer on line 60 already handles cleanup and will run immediately after return. Calling clear twice violates the RAII pattern and adds confusion.Apply this diff to rely on the defer:
executor.yield(.preparing_to_wait, .waiting, .allow_cancel) catch |err| { // Classify the error before clearing timeout state const classified_err = rt.checkTimeout(&timeout, err); - timeout.clear(rt); cancelIo(rt, completion); return classified_err; };The defer ensures cleanup happens before the caller regains control, and cancelIo doesn't require the timeout to be cleared first (it's shielded anyway).
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/io/base.zig(1 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: lalinsky
Repo: lalinsky/zio PR: 41
File: src/udp.zig:79-82
Timestamp: 2025-10-10T05:59:17.087Z
Learning: In UDP socket operations (src/udp.zig), error.Canceled from result_data.result represents OS/IO-level cancellation (e.g., io_uring), not user-requested cancellation. User cancellation is handled by waitForXevCompletion() via try. OS-level error.Canceled should be mapped to error.Unexpected as it represents an unexpected system event.
📚 Learning: 2025-10-10T05:59:17.087Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 41
File: src/udp.zig:79-82
Timestamp: 2025-10-10T05:59:17.087Z
Learning: In UDP socket operations (src/udp.zig), error.Canceled from result_data.result represents OS/IO-level cancellation (e.g., io_uring), not user-requested cancellation. User cancellation is handled by waitForXevCompletion() via try. OS-level error.Canceled should be mapped to error.Unexpected as it represents an unexpected system event.
Applied to files:
src/io/base.zig
⏰ 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/io/base.zig (2)
15-28: LGTM! Clear cancellation flow.The shield properly prevents user cancellations during the two-phase cancel+wait sequence. The unreachable on line 27 is justified since the shield guarantees no cancellation errors.
30-52: Solid state machine implementation.The preparing_to_wait optimization avoids suspension when IO completes during the transition window. The atomic CAS in yield (line 46) handles the race correctly, and the assertion on line 51 is safe since it only runs after successful yield (completion callback has disarmed).
Summary
This PR implements a comprehensive timeout mechanism for the zio runtime, replacing the previous ad-hoc timer management approach with a clean, heap-based system.
Key Changes
Cancellation Status Refactoring
canceledflag withCanceledStatuspacked struct tracking:user_canceled: Counter for user-initiated cancellationstimeout: Counter for timeout-triggered cancellationspending_errors: Counter for pending cancellation errors to consumeNew Timeout Infrastructure
src/core/timeout.zigwith RAII-styleTimeouttypeTimeoutHeap: Min-heap ordering timeouts by earliest deadlinetriggeredfield allows callers to distinguish timeout from user cancellationTask-Level Timeout Management
AnyTaskmaintains aTimeoutHeapfor active timeoutscheckTimeout(): Decrements timeout counter, returnserror.Timeoutif triggeredcheckCanceled(): Decrements pending_errors counter, returnserror.Canceled(respects shields)updateTimer(),maybeUpdateTimer(): Manage shared timer based on heap stateSimplified I/O Operations
waitForIo()andtimedWaitForIo()to use timeout infrastructurecancelIo(): Properly shields, cancels, and waits for I/O completiontimedWaitForIo()usesTimeoutobjects with RAII patternRuntime/Executor Improvements
sleep()reimplemented usingTimeoutinfrastructureyield()delegates totask.checkCanceled()for cleaner cancellation handlingBenefits
Testing
Existing tests pass with the new implementation.