Skip to content

Wait for the timer to be canceled - #120

Merged
lalinsky merged 1 commit into
mainfrom
timeout-clear
Nov 3, 2025
Merged

lalinsky merged 1 commit into
mainfrom
timeout-clear

Conversation

@lalinsky

@lalinsky lalinsky commented Nov 3, 2025

Copy link
Copy Markdown
Owner

If we are calling timeout.clear(), we need to wait until the backing timer is canceled. It's because if we exit sooner, the task might actually exit, and cause memory corruption.

This is a WIP hack, needs proper waiting.

@coderabbitai

coderabbitai Bot commented Nov 3, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

A busy-wait loop was added to the Timeout.clear method in src/core/timeout.zig. After detaching and nulling the timeout reference, the method now yields to the executor while the active timer is not dead, marked as a temporary hack.

Changes

Cohort / File(s) Change Summary
Timeout cancellation synchronization
src/core/timeout.zig
Added busy-wait loop in Timeout.clear that yields to the executor until the active timer becomes dead; implementation flagged as hack pending refactoring

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

  • Clarify the root cause: why is this synchronization barrier needed? Is there a race condition being masked?
  • Verify that yielding is the intended synchronization primitive here—this pattern can hide deadlocks if the executor isn't making progress on the timer cancellation elsewhere.
  • Check whether the TODO indicates a known limitation or if this is a temporary workaround for a larger architectural issue.

Poem

A timeout yields its final breath,
spinning softly 'til the end,
the executor shepherds it to death—
a hack, but one that bends. ⏳✨

Pre-merge checks and finishing touches

✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: adding a busy-wait loop to wait for timer cancellation in Timeout.clear.
Description check ✅ Passed The description clearly explains why the change is needed (race condition preventing memory corruption) and acknowledges it's a temporary hack.
✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch timeout-clear

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: 2

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 32644e4 and 65015c8.

📒 Files selected for processing (1)
  • src/core/timeout.zig (1 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
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.
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.
📚 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/timeout.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)

Comment thread src/core/timeout.zig
Comment on lines +29 to +33
// TODO: HUGE HACK: this needs proper waiting
// If we are the active timeout, we need to wait until it's cleared!!!
while (task.timer_cancel_c.state() != .dead) {
executor.yield(.ready, .ready, .no_cancel);
}

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.

⚠️ Potential issue | 🔴 Critical

Replace busy-wait with proper synchronization primitive.

This busy-wait loop solves the race condition but creates new problems:

  1. Performance overhead: Even with yields, spinning wastes CPU cycles and adds latency to clear() calls.
  2. No timeout: If timer_cancel_c never reaches .dead state (due to a bug or deadlock), this hangs forever.
  3. Potential deadlock: If timer cancellation completion depends on this task making progress through other code paths, you have a deadlock.

Consider using a completion/future mechanism where the timer cancellation operation can signal completion that clear() awaits properly, or add a counted reference with proper synchronization.

Do you want me to search the codebase for similar synchronization patterns or help design a proper completion mechanism?

🤖 Prompt for AI Agents
In src/core/timeout.zig around lines 29 to 33, the current busy-wait loop
spinning on task.timer_cancel_c.state() must be replaced with a proper
synchronization primitive: add a completion/event/future that the timer
cancellation path will signal when it reaches the .dead state, and have clear()
await that completion instead of looping; include a configurable timeout and
return an error if the wait times out to avoid indefinite hang, and ensure the
completion is signalled under the same lock/ownership rules as the timer to
prevent races/deadlocks (or use a counted reference + atomic/state transition
with a condition variable or executor-supported await API if available). Ensure
the cancel path signals the completion on all code paths (success and error) and
that clear() handles cancellation/interrupts and cleans up the waiter to avoid
leaks.

Comment thread src/core/timeout.zig

// TODO: HUGE HACK: this needs proper waiting
// If we are the active timeout, we need to wait until it's cleared!!!
while (task.timer_cancel_c.state() != .dead) {

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.

🛠️ Refactor suggestion | 🟠 Major

Add defensive iteration limit.

Even as a temporary hack, this unbounded loop is dangerous. Add a maximum iteration count and fail fast if exceeded—it'll catch bugs in testing rather than hanging mysteriously in production.

+        // TODO: HUGE HACK: this needs proper waiting
+        // If we are the active timeout, we need to wait until it's cleared!!!
+        var spin_count: usize = 0;
+        const max_spins: usize = 10000;
         while (task.timer_cancel_c.state() != .dead) {
+            spin_count += 1;
+            std.debug.assert(spin_count < max_spins); // Fail fast if cancellation hangs
             executor.yield(.ready, .ready, .no_cancel);
         }
📝 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.

Suggested change
while (task.timer_cancel_c.state() != .dead) {
// TODO: HUGE HACK: this needs proper waiting
// If we are the active timeout, we need to wait until it's cleared!!!
var spin_count: usize = 0;
const max_spins: usize = 10000;
while (task.timer_cancel_c.state() != .dead) {
spin_count += 1;
std.debug.assert(spin_count < max_spins); // Fail fast if cancellation hangs
executor.yield(.ready, .ready, .no_cancel);
}
🤖 Prompt for AI Agents
In src/core/timeout.zig around line 31, the while loop "while
(task.timer_cancel_c.state() != .dead)" is unbounded; add a defensive maximum
iteration count (e.g., an integer max_iters constant) and increment a counter
each loop iteration, and if the counter exceeds max_iters return an error (or
call unreachable/asserterror/log and fail fast) to avoid hanging; update
function signature/propagate the error as needed and include a short log message
explaining the exceeded iterations for debugging.

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