Skip to content

Add instrumentation to help TSan understand fiber context switches - #566

Merged
lalinsky merged 1 commit into
mainfrom
tsan-instrumentation
Jul 10, 2026
Merged

lalinsky merged 1 commit into
mainfrom
tsan-instrumentation

Conversation

@lalinsky

Copy link
Copy Markdown
Owner

No description provided.

@coderabbitai

coderabbitai Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: a7a5ae8b-4f8d-4ad8-b16a-e26665963c6d

📥 Commits

Reviewing files that changed from the base of the PR and between 523b8ba and d4ab269.

📒 Files selected for processing (3)
  • src/coro/coroutines.zig
  • src/coro/tsan.zig
  • src/task.zig
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/task.zig
  • src/coro/tsan.zig
  • src/coro/coroutines.zig

📝 Walkthrough

Walkthrough

This change adds conditional TSan fiber wrappers, stores fiber handles in coroutine contexts, switches TSan fibers during context changes, and destroys fibers during coroutine and task teardown.

Changes

TSan coroutine integration

Layer / File(s) Summary
TSan fiber runtime wrappers
src/coro/tsan.zig
Defines enabled and disabled fiber representations, TSan runtime declarations, and wrappers for querying, creating, switching, and destroying fibers.
Context switch fiber tracking
src/coro/coroutines.zig
Adds TSan fiber fields to architecture-specific contexts and updates context switching to save the outgoing fiber and activate the incoming one.
Coroutine fiber lifecycle
src/coro/coroutines.zig, src/task.zig
Creates and deinitializes coroutine fibers, and invokes coroutine cleanup from AnyTask.destroy.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Possibly related PRs

Poem

Fibers wake, then fibers rest,
TSan records each context quest.
Switches marked and handles spun,
Cleanup waits when work is done.
Tiny hooks keep races bright.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Description check ❓ Inconclusive No pull request description was provided, so there is nothing meaningful to evaluate. Add a short description of the coroutine/TSan changes and the intended behavior.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title matches the main change: TSan fiber instrumentation for coroutine context switches.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch tsan-instrumentation

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.

@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

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/coro/tsan.zig`:
- Around line 40-48: Add a module-level `//!` documentation comment in
`src/coro/tsan.zig` explaining why `switchToFiber` passes `flags == 0` for
cooperative context switches, or remove the “see the module doc comment”
parenthetical from `switchToFiber`’s comment.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: aeecc22a-2839-427e-835c-8cf893a45e9e

📥 Commits

Reviewing files that changed from the base of the PR and between b111b42 and 523b8ba.

📒 Files selected for processing (3)
  • src/coro/coroutines.zig
  • src/coro/tsan.zig
  • src/task.zig

Comment thread src/coro/tsan.zig
Comment on lines +40 to +48
/// Tell TSan that `fiber` is now the running fiber on this OS thread. Call at
/// the moment of a context switch, just before the stacks are swapped. Uses
/// flags == 0 so the switch establishes the cooperative happens-before edge
/// (see the module doc comment).
pub inline fn switchToFiber(fiber: Fiber) void {
if (enabled) {
if (fiber) |f| c.__tsan_switch_to_fiber(f, 0);
}
}

@coderabbitai coderabbitai Bot Jul 10, 2026 •

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Dangling reference: there's no module doc comment to "see".

The comment says the flags==0 rationale is explained in "the module doc comment", but this file has no //! module doc — line 1 jumps straight into const builtin. For a module encoding subtle TSan happens-before semantics, the next reader will go looking for something that isn't there. Either add the //! doc that explains why flags==0 (sync) is the right choice for cooperative switches, or drop the parenthetical.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/coro/tsan.zig` around lines 40 - 48, Add a module-level `//!`
documentation comment in `src/coro/tsan.zig` explaining why `switchToFiber`
passes `flags == 0` for cooperative context switches, or remove the “see the
module doc comment” parenthetical from `switchToFiber`’s comment.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

try to assume why is the flag set that way

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.

@lalinsky Reasoning it out:

The __tsan_switch_to_fiber API has one documented flag: __tsan_switch_to_fiber_no_sync (value 1). Passing 0 means "no flags", i.e. use the default sync behavior — TSan establishes a happens-before edge between the fiber you're switching away from and the fiber you're switching to.

That's exactly what you want here. Coroutines are cooperatively scheduled — only one runs at a time on a given OS thread, and control is explicitly handed off via switchContext, like passing a baton. So any writes the outgoing coroutine did before yielding must be visible to whatever runs next when it reads that same state later. Using sync (0) tells TSan "this is a legitimate ordering point", so it won't flag those accesses as a data race just because they happened on "different" fibers.

The no_sync flag exists for cases where you don't want that ordering guarantee — e.g. a thread pool grabbing a fiber to run unrelated, independent work, where there's no real handoff relationship between whoever ran on that fiber last and whoever's running now. That's not this case: zio's coroutine switches are always resume/yield pairs with a defined program order, so sync is the correct choice.

So the flag isn't arbitrary — it's the deliberate choice to model coroutine switches as synchronization points, matching how a mutex handoff would be treated. Worth spelling this out in a //! module doc comment since it's the reasoning switchToFiber's own comment refers back to but doesn't currently exist.


✏️ Learnings added
Learnt from: lalinsky
Repo: lalinsky/zio PR: 566
File: src/coro/tsan.zig:40-48
Timestamp: 2026-07-10T21:51:36.493Z
Learning: In zio's src/coro/tsan.zig, `switchToFiber` calls `__tsan_switch_to_fiber(fiber, 0)` deliberately using flags=0 (sync, not `__tsan_switch_to_fiber_no_sync`). This is intentional: coroutine context switches are cooperative resume/yield handoffs with a defined program order (only one fiber runs at a time per OS thread), so TSan should establish a happens-before edge across the switch, same as a mutex handoff. The `no_sync` flag would be appropriate only for unrelated fiber reuse (e.g. thread pool grabbing an arbitrary fiber), not for zio's coroutine switching.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

@lalinsky
lalinsky force-pushed the tsan-instrumentation branch from 523b8ba to d4ab269 Compare July 10, 2026 21:58
@lalinsky
lalinsky merged commit 1ba25d6 into main Jul 10, 2026
26 checks passed
@lalinsky
lalinsky deleted the tsan-instrumentation branch July 10, 2026 22:01
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