Introduction
Dedicated to Baba.
Async Rust is sequential unless you say otherwise. Every .await waits for the one before it to
finish, even when the two have nothing to do with each other:
async fn profile_page(api: &Api, user_id: u64) -> Result<Page, Error> {
let user = api.user(user_id).await?;
let posts = api.posts(user_id).await?; // waits for `user`, but doesn't need it
let avatar = api.avatar(&user.avatar_url).await?;
let friends = api.friends(user_id).await?; // waits for all three
Ok(Page { user, posts, avatar, friends })
}
This function makes four round trips one after another. Only one of them, avatar, needs an
earlier result. The others could run at the same time. Rust gives you the tools to do that:
join!, try_join!, FuturesUnordered, buffered(n). But you have to notice the chance, work out
the dependency graph by hand, and rewrite the function into a shape that is harder to read. In
practice this is often skipped. Even when someone does it, the result is usually not the best
schedule.
psync does that rewrite for you. Add one attribute:
#[psync::graph]
async fn profile_page(api: &Api, user_id: u64) -> Result<Page, Error> {
let user = api.user(user_id).await?;
let posts = api.posts(user_id).await?;
let avatar = api.avatar(&user.avatar_url).await?;
let friends = api.friends(user_id).await?;
Ok(Page { user, posts, avatar, friends })
}
At compile time, psync builds the function’s dependency graph. It then runs user → avatar,
posts and friends as three concurrent chains. The function returns the same values. It also
returns the same error: if both posts and friends fail, you still get the error from posts,
because that is the one the sequential code would have hit first.
What psync is
psync has two parts:
#[psync::graph]: a procedural macro that rewrites an async function so that awaits which do not depend on each other run concurrently. This covers straight-line code, loops (iterations run ahead, up to a bound) and work behindifguards. The generated code uses onlycoreandalloc. It runs on any executor: Tokio, smol, embassy, or psync’s own.psync::Executor: a smallno_std, heap-backed, cooperative executor with task priorities, written for the RP2350 microcontroller. It also runs on desktop and server machines.
You can use either part without the other. Most of this book is about the macro.
Why it is safe to try
psync only reorders code in ways the Rust compiler can still check:
- The generated code is ordinary Rust, so it is type-checked and borrow-checked like the rest of
your code. Suppose two branches both need
&mut x. psync’s analysis keeps them in order. If it ever failed to, the generated code would not compile. It would never race. - Results, bindings and early exits (
?,return,break,continue) behave as in the sequential code, and the function exits at the same place with the same value. - Ordinary statements keep their order. So do locks, permits, transactions, sleeps, clock reads,
and order-sensitive calls such as
send,writeandrecv. Everything else that is fixed in place is listed in Basic concepts. - One build switch,
PSYNC_GRAPH=off, compiles every annotated function exactly as written. This makes it easy to compare the two builds and to back psync out.
There is one thing you do accept when you add the attribute. Awaited operations may run speculatively: when the sequential code would have stopped early, psync may already have started work after that point. For reads this is harmless. For writes it may not be. The side-effects chapter describes how psync recognizes file-system, network and process effects and keeps them from running speculatively.
In numbers
| Result | Where it comes from |
|---|---|
| 9.2× faster end to end | kube-rs’s dynamic_api example (a kubectl get all), remote profile, whole process from start to exit |
| 4.1× faster end to end | datafusion-cli sessions on S3-like storage |
| 2.59× | geometric mean over all applications and network profiles, end to end |
| 0 failures in 320 runs | both builds printed the same output and sent the same API requests |
| 7 and 11 lines | the whole patch to kube-rs and to DataFusion: attributes, no rewrites |
| 84 of 90 | confirmed real-world findings that psync rewrites from the code as written; 5 more need one hint line |
| 3.79× | geometric mean over the 16 real-world shapes in graph_suite |
These come from measured runs against a real Kubernetes 1.36 control plane and an S3 store over TLS. The case studies cover them, including the cases where psync did not help or made things slower.
Where psync is going
psync started from a research proposal with two phases:
- Phase I, asynchronous concurrency. Extend the executor to several cores. Build the token-level dependency graph in a procedural macro. Then refine it with compiler information (HIR, THIR, MIR: types, resolved calls, aliasing, effects). The macro described in this book is Phase I step 2.
- Phase II, synchronous concurrency. Apply the same analyses to ordinary synchronous code. Split independent regions into tasks, and run them on parallel workers.
The macro sees tokens, not types. That is why it is deliberately conservative, and why some decisions need a hint from you. What is checked, what is assumed and Roadmap: beyond tokens say exactly where the line is.
How to read this book
- Getting started takes you from an empty project to your first concurrent function.
- Guide explains what psync does with each kind of code, how to read its report, and how to steer it with hints.
- How psync works walks through the implementation: classification, the token-level read/write analysis, the graph, the schedule and the generated code.
- Safety covers side effects: files, network, processes.
- Case studies show psync on real projects.
- Reference lists every option.
Getting started
This chapter takes you from an empty project to a function that psync runs concurrently. Then it shows how to see what psync did, and how to turn it off.
Requirements
- Rust 1.88 or newer. The analysis crate is written in edition 2024 with
letchains, and the generated loop code uses async closures, which became stable in 1.85. - An async runtime of your choice. The generated code needs only
coreandalloc, so Tokio, smol, embassy or psync’s own executor all work.
Add the dependency
psync is not on crates.io yet. Depend on the Git repository. #[psync::graph] currently lives on
the claude/initial_psync_graph branch:
[dependencies]
psync = { git = "https://github.com/sahastasai/psync", branch = "claude/initial_psync_graph", default-features = false }
tokio = { version = "1", features = ["macros", "rt-multi-thread", "time"] }
On a desktop or server, use default-features = false. The default feature, rp235x, adds the
RP2350 heap and hardware support, and you only want that for firmware.
Your first concurrent function
Here are three requests that do not depend on each other:
use std::time::{Duration, Instant};
use tokio::time::sleep;
async fn fetch(name: &str, ms: u64) -> Result<String, String> {
sleep(Duration::from_millis(ms)).await;
Ok(format!("{name} ({ms} ms)"))
}
#[psync::graph(explain)]
async fn dashboard() -> Result<Vec<String>, String> {
let user = fetch("user", 100).await?;
let orders = fetch("orders", 100).await?;
let weather = fetch("weather", 100).await?;
Ok(vec![user, orders, weather])
}
#[tokio::main]
async fn main() {
let started = Instant::now();
let parts = dashboard().await.unwrap();
println!("{parts:?} in {:?}", started.elapsed());
}
explain makes psync print the dependency graph while it compiles the function:
psync::graph `dashboard`:
region 0:
n0: user = fetch()? [await]
n1: orders = fetch()? [await]
n2: weather = fetch()? [await]
level 0: n0 || n1 || n2
Each statement is a node (n0, n1, n2). No edges are listed, so nothing waits for anything
else, and all three nodes run in one level (|| means “at the same time”). The program prints:
["user (100 ms)", "orders (100 ms)", "weather (100 ms)"] in 101.297078ms
Now build the same program with psync turned off:
PSYNC_GRAPH=off cargo run
["user (100 ms)", "orders (100 ms)", "weather (100 ms)"] in 303.846918ms
You get the same result in about a third of the time. Both outputs above are from real runs.
Cargo does not track
PSYNC_GRAPH. If you switch the variable between builds, touch the annotated files (or use separateCARGO_TARGET_DIRs). Otherwise Cargo reuses the previous expansion. Comparing builds has a recipe.
Running on psync’s executor
The same functions run on psync’s own executor. Here a hand-made future stands in for I/O. It stays pending for a number of polls:
use std::{cell::Cell, future::poll_fn, rc::Rc, task::Poll};
async fn work(polls: u32, value: u32) -> u32 {
let mut left = polls;
poll_fn(move |cx| {
if left == 0 {
return Poll::Ready(value);
}
left -= 1;
cx.waker().wake_by_ref();
Poll::Pending
})
.await
}
#[psync::graph]
async fn sum() -> u32 {
let a = work(10, 1).await;
let b = work(10, 2).await;
a + b
}
fn main() {
let executor = psync::Executor::default();
let out = Rc::new(Cell::new(0));
let o = out.clone();
executor.spawn(1, async move { o.set(sum().await) });
executor.run_until_stalled();
println!("sum = {}", out.get()); // sum = 3
}
The executor explains priorities, waking, and running on the RP2350.
Seeing the code psync generates
There are two ways to look at what psync did:
#[psync::graph(explain)]prints the graph at compile time, as shown above.psync-expandapplies the attribute to any function in any Rust file. It prints the generated code and the graph as JSON. You do not have to annotate the function first:
cargo run -p psync-graph --features cli --bin psync-expand -- path/to/file.rs LINE [BOUND]
LINE is any line inside the function. Reading the report explains the
output.
Turning it off
#[psync::graph(off)]compiles one function as written. Hint attributes are still removed.- Building with the environment variable
PSYNC_GRAPH=offdoes the same for every annotated function.
Running the project’s own checks
From a clone of the repository:
cargo test --no-default-features --test graph # behaviour tests for the macro
cargo test --no-default-features --test scheduling # executor tests
cargo run --example graph_suite --no-default-features # 16 real-world shapes, timed
Basic concepts
This chapter introduces the six words that the rest of the book uses: node, edge, region, barrier, chain and level. Every example comes with the report that psync really prints for it.
Nodes and edges
psync looks at each block of async code one statement at a time. A statement it may move is a node. There are three kinds:
- a
letbinding of an awaited value, or of a cheap pure value (let key = g * 10;); - an awaited expression statement (
client.flush().await;); - an ordinary statement with possible side effects, which psync calls an effect
(
out.push(x);,total += n;).
An edge a -> b means b must wait for a. psync adds an edge when one of these holds:
| Reason in the report | Meaning |
|---|---|
reads `x` | b uses a binding that a defines |
rebinds `x` / shadows `x` | the two statements bind the same name, or b rebinds a name a still reads |
writes `p` | one writes a variable or field (self.groups) that the other reads or writes |
effect order | both are ordinary statements, which never change order relative to each other |
Here is the example from the introduction:
#[psync::graph]
async fn profile_page(api: &Api, user_id: u64) -> Result<Page, Error> {
let user = api.user(user_id).await?;
let posts = api.posts(user_id).await?;
let avatar = api.avatar(&user.avatar_url).await?;
let friends = api.friends(user_id).await?;
Ok(Page { user, posts, avatar, friends })
}
region 0:
n0: user = user()? [await]
n1: posts = posts()? [await]
n2: avatar = avatar()? [await]
n3: friends = friends()? [await]
n0 -> n2 (reads `user`)
level 0: n0->n2 || n1 || n3
There is one edge: avatar reads user. Everything else is free. The final Ok(Page { .. }) is
the block’s value, so it stays last.
Chains and levels
A node with exactly one predecessor, whose predecessor has exactly one successor, joins that
predecessor’s chain. In the example, n0 -> n2 is a chain: avatar starts the moment user
arrives. It does not wait for posts or friends.
Chains are then grouped into levels. A chain’s level is one past the deepest chain it waits for.
All chains in a level run at the same time, joined together. When the level is done, its bindings
are handed back in program order, and the next level starts. n0->n2 || n1 || n3 is one level of
three concurrent chains.
Chains matter. Without them, a per-item pipeline would be held back by its slowest sibling.
Here is the chains test from tests/graph.rs:
#[graph]
async fn chains() -> (u32, u32) {
let a1 = io(T, 1).await;
let a2 = io(2 * T, 2).await;
let b1 = io(2 * T, a1 + 10).await;
let b2 = io(T, a2 + 10).await;
(b1, b2)
}
a1 -> b1 and a2 -> b2 are two chains. Each one takes 3T. Two levels of a1 || a2 then
b1 || b2 would take 2T + 2T = 4T. The test checks that the function finishes in 3T.
When edges cross between chains, you get more than one level. In this example two awaits
are hidden inside other statements (an argument of push and the scrutinee of a match):
async fn hoisted(api: &Api, names: Vec<String>) -> Vec<usize> {
let mut lens = Vec::new();
lens.push(api.len(&names[0]).await);
match api.kind(&names[1]).await {
Kind::A => lens.push(1),
Kind::B => lens.push(2),
}
lens
}
region 0:
n0: lens = Vec :: new ()
n1: __psync_h2 = len() [await]
n2: lens . push (__psync_h2)
n3: __psync_s3 = kind() [await]
n4: match __psync_s3 { Kind
n0 -> n2 (reads `lens`)
n1 -> n2 (reads `__psync_h2`)
n0 -> n4 (reads `lens`)
n2 -> n4 (writes `lens`)
n3 -> n4 (reads `__psync_s3`)
level 0: n0 || n1 || n3
level 1: n2
level 2: n4
psync first moved both awaits into their own bindings (__psync_h2, __psync_s3). This step
keeps the evaluation order, and Exposing hidden awaits explains how. The
two requests now run together in level 0. The two pushes still happen in their original order.
Regions and barriers
Some statements must stay exactly where they are. psync calls these barriers. A barrier splits the block into separate regions. Nodes never move across a barrier, and each region gets its own graph.
A statement is a barrier when:
| Barrier | Why |
|---|---|
it acquires something it keeps: an awaited lock, lock_owned, read, write, acquire, acquire_owned, acquire_many, begin, transaction | what runs while the guard is held is the point |
it awaits a deliberate delay: sleep, sleep_until, tick, yield_now, delay_for | its position is the point |
it reads a clock: now(), elapsed(), duration_since() | it measures the waits around it |
it is marked #[psync::seq] | you asked |
it hides an exit psync cannot rewrite: ? or return inside a macro, bail!, ensure!, yield, break with a value | psync cannot defer it |
it is a let without an initializer, an item, a ref binding, or a #[psync::fresh] binding | it cannot be handed between scopes |
| it is the block’s final value expression | it must come last |
Here is a lock:
async fn with_lock(state: &Mutex<State>, api: &Api) -> u32 {
let a = api.one().await;
let mut guard = state.lock().await;
guard.count += 1;
drop(guard);
let b = api.two().await;
let c = api.three().await;
a + b + c
}
region 0:
n0: guard . count += 1 ;
n1: drop (guard) ;
n2: b = two() [await]
n3: c = three() [await]
n0 -> n1 (writes `guard.count`)
level 0: n0->n1 || n2 || n3
barrier: line 3: `let mut guard = state . lock () . await ;`: awaits `lock`, whose position is meaningful
a is alone in the region before the lock, so there is nothing for it to overlap with. The lock
stays where it is. After it, b and c run together. (The guard.count += 1; drop(guard); chain
completes on its first poll, so the guard is released as early as before.)
A lock acquired inside a nested block, and released there, does not make the statement a barrier:
let taken = {
let mut guard = lock_buffer(&buffer).await;
std::mem::take(&mut *guard)
};
The critical section is contained in the statement, and the lock itself keeps it exclusive. The
critical_sections_inside_a_statement_may_move test covers this case.
Unique handles stay ordered
A &mut receiver is one handle. psync treats calls through it as writes, so they stay in order:
#[graph]
async fn twice(&mut self) -> (u32, u32) {
let a = self.hit().await;
let b = self.hit().await;
(a, b)
}
region 0 (unchanged):
n0: a = hit() [await]
n1: b = hit() [await]
n0 -> n1 (writes `self`)
level 0: n0->n1
(unchanged) means psync found nothing to overlap, so it emits the region exactly as written.
Suppose psync had ever missed such an edge. Then the generated code would need two &mut self
borrows at once, and it would not compile. It would never race.
Ordered calls on shared handles
Some calls take &self but still have an order you can observe. A channel’s send, a stream’s
next, an I/O write. psync treats these as writes to their receiver, whatever the receiver is:
async fn send_both(tx: &Sender<u32>, api: &Api) {
let a = api.one().await;
let b = api.two().await;
tx.send(a).await;
tx.send(b).await;
}
region 0:
n0: a = one() [await]
n1: b = two() [await]
n2: send() [await]
n3: send() [await]
n0 -> n2 (reads `a`)
n1 -> n3 (reads `b`)
n2 -> n3 (writes `tx`)
level 0: n0->n2 || n1
level 1: n3
Both requests run together, and a is sent as soon as it arrives. b is still sent second. The
full list of these methods is in Reads and writes from tokens.
What “the same” means
After the rewrite:
- every binding has the value it would have had sequentially;
- the function returns the same value, or exits at the same
?,return,breakorcontinuewith the same value (see Early exits and errors); - ordinary statements run in the same relative order.
What can differ is work that the sequential code would have skipped after an exit. That is the speculation you opt into with the attribute, and the next chapters come back to it.
Loops
The most common missed concurrency in real code is an await inside a loop. In the audit behind psync, it was 99 of 193 findings:
for key in keys {
let meta = store.head(key).await?; // one round trip per key, one at a time
total += meta.size;
}
psync rewrites for loops so that the awaited work at the front of each iteration runs ahead,
up to bound iterations at a time. The rest of each body still runs in order.
Prefetching
#[psync::graph(bound = 8)]
async fn sizes(store: &Store, keys: &[String]) -> Result<u64, Error> {
let mut total = 0;
for key in keys {
let meta = store.head(key).await?;
total += meta.size;
}
Ok(total)
}
loop `for key in keys`: prefetch [meta = head()?], 8 at a time
The leading awaited statements of the body are its prefix. Here that is
let meta = store.head(key).await?. psync turns the prefix into an async closure, runs it for
every item with at most 8 in flight, and then runs the rest of the body for each item, in order.
This is the real generated code, shortened:
let __psync_iter = keys;
let __psync_each = ::psync::__private::over(&__psync_iter, async |key| {
// the prefix, with `?` recorded instead of taken
let meta = match Branch::branch(store.head(key).await) { Ok(v) => v, Err(r) => { /* record r */ } };
Some((meta,))
});
let __psync_futures: Vec<_> = __psync_iter.into_iter().map(|item| __psync_each(item)).collect();
let __psync_items = ::psync::__private::join_all_bounded(__psync_futures.into_iter(), 8usize).await;
for (__psync_e, __psync_out) in __psync_items {
if let Some(r) = __psync_e { Rethrow::rethrow(r)?; } // the first failing key, in order
let (meta,) = __psync_out.unwrap();
total += meta.size;
}
Three things to know about this shape:
boundlimits how many prefixes are in flight, not how far ahead they run. Each item’s prefix starts as soon as a slot frees. All prefixes complete before the rest of the body runs for the first item.- Errors are replayed in order. If key 3 and key 7 both fail, the function returns key 3’s error, as the sequential loop would. But keys 4 to 7 (and every later key) were still looked up. That is the speculation the attribute allows. For reads it does not matter. For writes, see Side effects.
- All results are buffered. The loop holds every item’s prefix output until the rest of the
body runs. For very long loops, choose a
boundand think about memory.
bound defaults to 16. You set it per function: #[psync::graph(bound = 4)].
When a loop stays sequential
A prefix may only touch per-iteration data. That means the loop pattern and anything bound inside the body. If it reads something an earlier iteration writes, the iterations depend on each other:
for item in items {
let next = add(total, item).await; // reads `total`, which the previous iteration wrote
total = next;
}
loop `for item in items`: no awaited statement can run ahead
The reasons a loop is left alone are:
| Reason | Meaning |
|---|---|
writes `x`, which outlives the iteration | the prefix writes loop-carried state |
reads `x`, which the loop body writes | the prefix reads loop-carried state |
no awaited statement can run ahead | nothing awaited is left once the above are excluded |
`ref` in the loop pattern | ref bindings cannot be moved into a closure |
Read-modify-write caches are a common case:
for k in keys {
if !cache.contains_key(&k) {
let v = api.get(k).await;
cache.insert(k, v);
}
}
psync cannot know whether two keys are equal. Two iterations with the same key would do the lookup
twice instead of once. So this loop stays sequential. If you know the keys are distinct, or a
duplicate lookup is fine, say so with #[psync::independent]:
#[psync::independent]
for k in keys { /* same body */ }
Guards
Work behind an if runs ahead only for the items that reach it:
for g in all {
let key = g * 10;
if self.mode.is_queryable(g) {
let versions = self.client.query(g).await?;
self.groups.push((key, versions));
}
}
The prefix becomes let __psync_g = if <cond> { Some(<awaited work>) } else { None };. The rest of
the body unpacks it. Reads and writes are tracked per field, so writing self.groups does not
conflict with reading self.mode or self.client. The test
guarded_loop_bodies_prefetch_with_field_sensitivity checks this shape. It is kube-rs’s discovery
loop.
An early-exit guard works too. Here a pure condition comes first and leaves the iteration:
for split in splits {
if split == 0 {
continue;
}
let m = api.search(split).await?;
out.push(m);
}
loop `for split in splits`: prefetch [__psync_g2 = search()], 16 at a time
psync inverts the guard: the prefix is if !(split == 0) { Some(search) } else { None }. So no
search runs for an item that the guard skips. The continue is still performed in place.
Fission: loop-carried state first
Some loops update shared state before they await: a dedupe set, a map removal, a reservation counter. The awaited part depends on that state, but only on the current item’s share of it. psync splits the loop in two. First it runs the leading non-awaiting statements for every item. Then it prefetches the rest:
for d in digests {
if published.insert(d) { // carried state: runs first, for every item
let receipt = store.upload(d).await?;
uploaded.push(receipt);
}
}
loop `for d in digests`: prefetch [__psync_g8 = upload()], 8 at a time
The generated code first builds [(d, published.insert(d)) for each d] in a plain loop. Then it
prefetches upload for the entries whose flag is true. This is jdx/mise’s remote task cache. It is
the tools-13 shape in graph_suite, at 3.46×.
Exits in the first loop that would end the whole loop are deferred until the items before them are
done. These are return, ?, or a break to an outer loop. Sequential code performs them at that
point, too:
for table in tables {
let Some(batch) = pending.remove(&table) else { continue };
if batch == 0 {
return Err(Error("empty batch")); // first loop stops here; items before it are written,
} // then the error is returned
written += w.write_batch(batch).await;
}
Fission only applies when the two halves do not touch the same carried state. Per-iteration names flow from the first half to the second.
Nested loops
A loop whose body is only another loop is treated as one loop over the pairs:
for group in &groups {
for resource in group {
if *resource == 0 { continue; }
let items = api.list(*resource).await?;
listed.push(items);
}
}
loop `for group in & groups`: prefetch [__psync_g2 = list()], 16 at a time
All resources of all groups run ahead together, not just one group’s. This only happens when:
- the outer body is exactly the inner loop;
- neither loop is labeled;
- the inner body has no
break; - the outer item is a plain binding.
The outer item is paired with every inner item, so it must be Copy, for example a reference. If it
is not, the generated code does not compile. It does not silently change meaning.
When the inner loop is not the whole body, the two loops are rewritten separately, and their bounds multiply. An outer loop with bound 16 around an inner loop with bound 8 can have 16 × 8 = 128 requests in flight. Patterns and pitfalls shows what that did to a single storage server.
while loops
psync cannot reason about a while condition from tokens. It cannot tell that the condition is
driven only by the statements before the first await. So while loops are rewritten only when you
assert it:
#[psync::independent]
while size < min {
let guard = size as u32;
size += 1;
idle.push(connect(guard).await);
}
loop `while size < min`: prefetch [__psync_h4 = connect()], 16 at a time
The first half (guard, size += 1) runs as a plain while loop and collects each iteration’s
guard. The connections are then made concurrently. This is sqlx’s try_min_connections: reserve
in order, connect concurrently.
Early exits and errors
A ? is a branch. You might expect it to stop psync from moving anything past it. It doesn’t. psync
lets awaits run concurrently even when they contain ?, return, break or continue, and still
exits exactly where the sequential code would.
The rule
Every exit inside a concurrent node is recorded, not taken. When the node’s chain hits an exit,
the chain stops. After the join, psync goes through the recorded exits in program order and
performs the first one. Here is the first_error_wins test:
#[graph]
async fn first_error_wins(fail: [bool; 3]) -> Result<u32, Error> {
let x = io(T, if fail[0] { Err(Error("x")) } else { Ok(1) }).await?;
let y = io(T, if fail[1] { Err(Error("y")) } else { Ok(2) }).await?;
io(T, if fail[2] { Err(Error("z")) } else { Ok(()) }).await?;
Ok(x + y)
}
All three requests run at once (the test checks a peak of 3 in flight). With fail = [false, true, true] the function returns Err("y"). With [true, false, true] it returns Err("x"). Those are
the errors the sequential function returns.
What the generated code looks like
Each ? becomes a match that stores the residual in a slot and breaks out of the chain:
let user = match ::psync::__private::Branch::branch(api.user(user_id).await) {
Ok(v) => v,
Err(r) => {
__psync_e0_0_0 = Some(r);
break '__psync_chain0 (None);
}
};
After the join, the slots are re-raised in source order through your own ?:
if let Some(r) = __psync_e0_0_0 { ::psync::__private::Rethrow::rethrow(r)?; } // user
if let Some(r) = __psync_e1_0_0 { ::psync::__private::Rethrow::rethrow(r)?; } // posts
if let Some(r) = __psync_e0_1_0 { ::psync::__private::Rethrow::rethrow(r)?; } // avatar
if let Some(r) = __psync_e2_0_0 { ::psync::__private::Rethrow::rethrow(r)?; } // friends
Each re-raise uses the function’s own ?. So From conversions happen exactly as in the
original. ? on an Option works the same way (the option_question_mark test).
return v is recorded in a slot that holds v. A break or continue that leaves the node is
recorded as an index, and a match re-performs it. Exits aimed at loops or labeled blocks
inside the node stay as they are.
return in the middle
async fn early(stop: bool, api: &Api) -> Result<u32, Error> {
let a = api.one().await;
if stop {
return Ok(0);
}
let b = api.two().await;
Ok(a + b)
}
region 0:
n0: a = one() [await]
n1: if stop { return Ok (0) ?
n2: b = two() [await]
level 0: n0 || n1 || n2
All three run in one level. After the join:
if let Some(v) = __psync_r1_0 {
return v;
}
The function still returns Ok(0) when stop is true. But api.two() was called anyway. This
is speculation. The sequential code would not have made that call.
Speculation is the price of overlap
Overlapping an await with an earlier exit means starting it before you know whether you will need
it. psync accepts this for awaited bindings and await statements. That is the point of the
attribute. It does not accept it for ordinary statements: if an ordinary statement can exit, every
later ordinary statement waits for it (effect order).
For reads this is harmless. For writes it is not, so psync does not speculate the writes it
recognizes: an awaited delete, put, upload, create, a file write or a process waits for
every earlier statement that may exit. What you still assert by adding #[psync::graph] is that
the awaited calls psync could not classify tolerate running speculatively. explain lists them,
and #[psync::graph(strict)] treats them as writes instead.
These tools keep speculation away from code that must not speculate:
- Effects that psync recognizes as writes (file writes, service writes such as
deleteorupload, processes) wait for earlier exits. See Side effects: files, network and processes. #[psync::graph(strict)]treats unclassified awaited calls as writes.#[psync::seq]on a statement keeps it exactly in place.- A lock, transaction or permit around the critical part is a barrier.
The opposite hint, #[psync::speculate], lets a write run ahead anyway, for idempotent
operations where the extra work is harmless.
Loops
In prefetched loops, each item’s prefix records its own exits. The rest of the loop body replays
them item by item, in order (loop_exits_are_replayed_per_iteration):
for item in items {
let Some(found) = io(T, item).await else {
continue;
};
if found == 0 {
continue;
}
out.push(found);
}
let ... else { continue } inside the prefix becomes “record a continue”. The rest of the body
for that item performs it. Later items are unaffected.
A ? or return in a prefix ends the whole loop at that item, as it would sequentially. The
prefixes of later items have already run by then. The same speculation applies, so a prefix that
writes is not prefetched in a loop that can end early, unless the loop is #[psync::speculate].
What psync cannot rewrite
Some exits cannot be recorded, so the statement holding them becomes a barrier:
?orreturninside a macro call (my_macro!(x?)), and the macrosbail!,ensure!,try!,return_err!andfail!. Their tokens are opaque.breakwith a value.yield.
Logging macros (trace!, debug!, info!, warn!, error!, log!) are an exception. They use
?x and %x as field sigils, so a ? in them is not an exit.
Hints
psync reads tokens, and some things you know cannot be seen in tokens. Three hint attributes tell
psync what you know. Inside a #[psync::graph] function, psync reads them and removes them from
its output. Outside one, they do nothing.
| Hint | Goes on | Means |
|---|---|---|
#[psync::seq] | a statement | keep this statement exactly where it is |
#[psync::fresh] | a let | each concurrent branch evaluates the initializer again, instead of sharing the value |
#[psync::independent] | a for or while loop | iterations do not depend on each other, even where psync cannot prove it |
#[psync::seq]
Use seq when the order of two statements matters for a reason psync cannot see. For example, two
requests to a rate-limited API, an audit log, or a call that must happen before another for
business reasons:
#[graph]
async fn pinned() -> u32 {
let a = io(T, 1).await;
#[psync::seq]
let b = io(T, 2).await;
a + b
}
The marked statement is a barrier. It splits the block into regions, and nothing moves across it.
In the seq_marker_keeps_order test, the peak number of awaits in flight is 1.
#[psync::fresh]
A shared &mut stops concurrency. When the value behind it can be re-created cheaply, for example a
connection checked out of a pool, fresh gives each branch its own copy:
#[graph]
async fn fresh_pool(context: &Context) -> Result<u32, Error> {
#[psync::fresh]
let pool = &mut context.pool();
let a = read_row(pool, 1).await?;
let b = read_row(pool, 2).await?;
Ok(a + b)
}
region 0:
n0: a = read_row()? [await]
n1: b = read_row()? [await]
level 0: n0 || n1
Each chain begins with its own let pool = &mut context.pool();. Uses of pool do not count as
conflicts. Without the hint, both reads would go through the same &mut and stay sequential. In the audit,
this hint was needed once, for a Lemmy handler (web-16). The other four hinted findings needed
independent.
Only use fresh when evaluating the initializer again is correct. It is wrong if the branches must
share one transaction, or must see each other’s writes.
#[psync::independent]
independent on a loop tells psync to skip its loop-carried-state checks. Use it when:
-
The state is a cache or dedupe structure. Two iterations touching the same key would only repeat work:
#[psync::independent] for k in keys { if !cache.contains_key(&k) { let v = io(T, k * 2).await; cache.insert(k, v); } } -
The loop is a
whileloop. psync never rewriteswhileloops without the hint, because it cannot see from tokens that the condition depends only on the statements before the first await (see Loops). -
An API’s independence needs knowledge psync lacks. For example, writes to different keys of a store, through a handle psync treats as shared.
independent does not turn off the borrow checker. If the iterations really need the same &mut
at once, the code still fails to compile.
On an ordinary statement, independent says that its effects on outside resources commute with
those of the statements around it. Two writes to different event types through one client are an
example (finding app-19 in matrix-rust-sdk):
self.client.account().set_account_data(KeyBackupContent { enabled: true }).await?;
#[psync::independent]
#[psync::speculate]
self.client.account().set_account_data(BackupDisabledContent { disabled: false }).await?;
Data dependencies between the statements still hold.
#[psync::speculate]
psync does not run a recognized write (a put, delete, upload, file write or process) before
an earlier statement that may exit, and it does not prefetch a loop’s writes when the loop can end
early. speculate lifts that rule for one statement, one for loop, or (as
#[psync::graph(speculate)]) a whole function:
let mut published = BTreeSet::new();
#[psync::speculate] // content-addressed uploads are idempotent
for upload in uploads {
if published.insert(upload.clone()) {
client.put_blob(upload).await?;
}
}
Use it when performing the write although sequential code would have stopped first is harmless: idempotent uploads, cache fills, PUTs of the same value. Do not use it for payments, deletes or messages. See Side effects.
When to reach for off
When a function cannot be made correct with hints, leave it as written with
#[psync::graph(off)], or just remove the attribute. Here is one example from the audit: a
function that borrows &mut self in both branches. No reordering can make that run concurrently.
Reading the report
psync can show you its graph in two forms. explain prints text at compile time. psync-expand
prints JSON, together with the generated code. Both come from the same Report.
explain
#[psync::graph(explain)]
async fn profile_page(api: &Api, user_id: u64) -> Result<Page, Error> { /* ... */ }
The report is printed to stderr while the crate compiles. With Cargo, you see it when the annotated crate is rebuilt:
psync::graph `profile_page`:
region 0:
n0: user = user()? [await]
n1: posts = posts()? [await]
n2: avatar = avatar()? [await]
n3: friends = friends()? [await]
n0 -> n2 (reads `user`)
level 0: n0->n2 || n1 || n3
Line by line:
region Nis one run of nodes between barriers. Only regions with two or more awaits are analyzed and listed.(unchanged)means nothing overlapped, so the region is emitted as written.nK: labelis one node. A binding showsnames = callee(). A computed value shows its first characters.?marks a node that can exit early, and[await]marks one that awaits.nA -> nB (reason):nBwaits fornA. The reasons are listed in Basic concepts.level L: chain || chainlists chains (n0->n2) that run concurrently in levelL.loopfor x in xs: prefetch [labels], N at a timenames a rewritten loop. A loop that was left alone shows the reason instead.barrier: line L:stmt: reasonis an await-containing statement kept in place. Line numbers are only known underpsync-expand. Inside the proc macro they show as0.
Hoisted values appear under generated names: __psync_hN for an operand, __psync_sN for a
scrutinee, __psync_gN for a guarded branch, __psync_tN for a block’s tail.
psync-expand
psync-expand runs the same transformation on any function in any file, without changing the
file:
cargo run -p psync-graph --features cli --bin psync-expand -- src/discovery.rs 115 8
The arguments are the file, a line inside the function, and an optional bound (default 16). It picks
the innermost function containing the line. Free functions, impl methods and trait methods with
default bodies all work. The output is one JSON object:
{
"function": "profile_page",
"start_line": 1,
"end_line": 7,
"bound": 16,
"changed": true,
"explain": " region 0:\n n0: user = user()? [await]\n ...",
"report": {
"regions": [
{
"nodes": [
{ "label": "user = user()?", "awaits": true, "effect": false, "exits": true, "line": 2 },
...
],
"edges": [[0, 2, "reads `user`"]],
"chains": [[0, 2], [1], [3]],
"levels": [[0, 1, 2]],
"changed": true
}
],
"loops": [],
"barriers": []
},
"expanded": "async fn profile_page(api: &Api, user_id: u64) -> Result<Page, Error> { ... }"
}
levelsholds indices intochains, andchainsholds indices intonodes.effect: truemarks an ordinary statement. Effects keep their order with each other.loops[]entries havelabel,prefetched(labels of the prefix nodes),bound,changed,reason,lineandend_line.expandedis the pretty-printed generated function.
Pipe it through jq to get one part out:
psync-expand file.rs 42 | jq -r .explain
psync-expand file.rs 42 | jq -r .expanded
psync-expand was how the 90 audit findings were checked. It ran on each finding’s function at the
pinned commit, and the script confirmed that the concurrent region or prefetched loop fell inside the
finding’s source lines.
Comparing builds
The best evidence that psync helps your program is the same program built both ways. psync makes this a one-variable change.
Two switches
| Switch | Scope | Effect |
|---|---|---|
#[psync::graph(off)] | one function | compiled as written; hint attributes removed |
PSYNC_GRAPH=off at build time | every annotated function in the build | the same, everywhere |
Both produce exactly the code you wrote, so a regression in a psync build can be checked against an identical source tree with psync disabled.
Cargo does not see PSYNC_GRAPH
Proc-macro output is cached with the crate that uses it. Cargo does not know that the expansion
depends on an environment variable. So if you build once with PSYNC_GRAPH=off and once without,
the second build may silently reuse the first expansion. Do one of these:
-
Touch the annotated files before every build:
touch src/annotated.rs && PSYNC_GRAPH=off cargo build --release && cp target/release/app app-sequential touch src/annotated.rs && cargo build --release && cp target/release/app app-psync -
Use two target directories:
PSYNC_GRAPH=off CARGO_TARGET_DIR=target-off cargo build --release CARGO_TARGET_DIR=target-psync cargo build --release
The psync benchmark harnesses (bench/kube-harness/run.sh) touch every annotated file before
each build. This lesson came from a bad run: in its first attempt, the “sequential” binary had
reused the psync expansion.
A benchmark recipe
This is what the kube-rs and DataFusion campaigns did:
- Patch the project with attributes only. Add
psyncas a dependency and#[psync::graph]on the functions you want. The kube-rs patch was 7 lines. The DataFusion patch was 11. - Build both binaries from the same tree, as above.
- Alternate builds run by run (sequential, psync, sequential, …), so drift in the network or the machine hits both equally.
- Check that the outputs are identical. Compare what each build prints, and if you can, what it sends to the server. In the kube-rs runs, the API server’s audit log recorded every request of both builds.
- Check that the sequential build really is sequential. In the kube-rs runs, a sequential build must have at most one request in flight at a time. The report builder asserted this.
- Measure under realistic latency. psync turns waiting into overlap. With no latency there is less to overlap, and with a saturated server there is nothing to gain (see Patterns and pitfalls).
Where to annotate
#[psync::graph] works on any async fn, including methods, and on async blocks and async closures
inside an annotated function. Nested fn items need their own attribute. To annotate main, put
#[psync::graph] above #[tokio::main], so psync sees the async fn before Tokio rewrites it:
#[psync::graph]
#[tokio::main]
async fn main() -> anyhow::Result<()> { /* ... */ }
That is exactly how kube-rs’s dynamic_api example was annotated for the end-to-end runs.
Patterns and pitfalls
This chapter collects what running psync on real projects taught us: the shapes it handles well, the ones it deliberately leaves alone, and the ways overlap can hurt.
Shapes psync handles well
The audit of 35 popular Rust repositories sorted missed concurrency into patterns. psync covers the async ones:
| Pattern | Example | What psync does |
|---|---|---|
| P1 independent awaits | two RPCs in a row that share nothing | one level, several chains |
| P2 await in a loop | for key in keys { store.head(key).await? } | prefetch, bounded |
| P3 per-item chains | per shard: list, then fetch, then read the manifest | chain fusion, so each item proceeds on its own |
| P4 late start | a download that needs only the config, written after a long chain | moves into the first level |
Sixteen real-world shapes shows one function per pattern from real repositories, with timings.
Things that stay in place on purpose
- Locks, permits and transactions. An awaited
lock,read,write,acquireortransactionwhose guard outlives the statement is a barrier. If the guard is dropped inside the statement’s own block, the statement may still move. The critical section stays exclusive either way. - Sleeps and ticks.
sleep,sleep_until,tick,yield_nowanddelay_forare barriers. A retry backoff must wait for the failure before it. - Clock reads.
now(),elapsed()andduration_since()measure the waits around them. Before clock reads were made barriers, kube’sdynamic_apiexample timed its discovery as 0 ms: the clock was read before the requests it was meant to time. - Ordered channel and stream calls.
send,recv,next,write,flush,execute,commit, … keep their order per receiver.
&mut in two branches does not compile
psync tracks &mut handles and mut bindings, and keeps their uses in order. It does not see
types, though. A method taking &mut self behind a shared-looking binding can slip through. When
that happens, the generated code borrows the same value mutably in two concurrent futures, and
rustc rejects it:
error[E0499]: cannot borrow `*conn` as mutable more than once at a time
That is the intended failure mode: a missed dependency becomes a compile error, not a race. Fix
it with #[psync::seq] on one of the statements. Or, if each branch can get its own value,
with #[psync::fresh]. In the audit, one finding could not be done at all, because it needs
&mut self in both branches.
Send futures
A function whose future must be Send (because it is tokio::spawned, say) stays Send after
the rewrite when every branch is Send. One trap was found in DataFusion and fixed. rustc cannot
prove Send for an iterator adapter, or a generic helper’s future, over items like
Box<dyn Trait + Send>. So prefetched loops now create each item’s future inline, before the
await. The prefetched_trait_objects_stay_send test keeps it that way.
Nested loops multiply their bounds
Each prefetched loop has its own bound. An outer loop over tables (bound 16) whose body has an inner loop over files (bound 8) can hold 16 × 8 = 128 requests in flight from one client.
In the heavy-load run, 32 DataFusion clients refreshing their catalogs offered about 3,600 concurrent requests to one storage node behind one TLS terminator. The node’s throughput fell from 813 to 538 requests/s. The median request took 1.6 s instead of 50 ms. psync made that scenario 0.76× per client (0.54× fleet throughput). At 8 clients, by contrast, the DataFusion fleet still completed 1.7× more operations per second with psync.
What to do today:
- give inner loops a smaller
bound, or annotate only one level; - use a client that multiplexes (HTTP/2), so extra requests in flight do not each cost a new connection.
A process-wide in-flight budget in psync would fix this properly. It has not been built yet.
Overlap moves the bottleneck to the CPU
psync joins concurrent work inside one task. Once the waits overlap, whatever CPU work follows
them runs on one core. kube-rs’s dynamic_api (a kubectl get all) spends 98–99% of its
sequential run in the loop psync rewrites. From that loop’s own speedup, Amdahl’s law predicts
10.4–11.5× end to end. It measured 5.0–9.2×. With every response arriving at once, parsing and printing thousands of objects
became the bottleneck, and all of it ran on one core.
The fix is to spawn each iteration onto the runtime’s worker threads when its future is Send. That
would be a change inside psync, not in your code, and it is not built yet.
Many new connections at once
With no network latency at all, one scenario got slower. kube-rs’s legacy discovery at startup ran at 0.86×: each request took under a millisecond, and psync opened 23 TLS connections at once instead of reusing one. Warm re-discovery, with a pooled connection, was 4.0× faster on the same setup. Overlap is cheap when waiting dominates, and not free when connection setup does.
Servers push back
At 32 concurrent clients, the Kubernetes API server’s flow control queued psync’s requests, and rejected 467 of them with HTTP 429. kube-rs retried every one, and no run failed. Fleet throughput was then the same in both builds (1.03×). psync creates no work. It only turns waiting into overlap, and a saturated server has no waiting left to overlap.
Memory
Prefetched loops buffer every item’s prefix result until the rest of the body runs. kube-rs’s
dynamic_api went from 32 to 66 MB peak RSS, and from 118 to 262 MB on the 5× cluster. Choose
bound with memory in mind for very long loops.
The executor
psync’s executor is a small, no_std, heap-backed, cooperative async executor. It was written for the
RP2350’s ARM cores, and it runs on any target with alloc. #[psync::graph] does not need it. It is
here when you want priorities on a microcontroller.
The model
let executor = psync::Executor::default();
let handle = executor.spawn(10, async { /* work */ });
handle.set_priority(20);
executor.run_until_stalled(); // or executor.run() to park and wait forever
- Priority only. Each task has a
u16priority. Larger values run first. - FIFO among equals. The pool takes the first ready task of the highest priority. A task that is still pending goes to the back of the queue, so ready tasks of equal priority take turns.
- Sleeping tasks are not polled. A task is polled only after a wake. A wake that arrives during a poll is kept: the ready flag is cleared before polling.
- No preemption. A task that is always ready and has a higher priority starves the ones below it.
- One core. Keep each executor on one core.
Executorholds its pool in anRc. Wakers andTaskHandles areSend + Sync, so interrupts and other threads can wake tasks and change their priorities.
The scheduling tests (tests/scheduling.rs) pin these rules down. For example:
let executor = Executor::default();
for (priority, id) in [(1, 0), (8, 1), (8, 2), (3, 3)] {
let log = log.clone();
executor.spawn(priority, async move { log.borrow_mut().push(id) });
}
executor.run_until_stalled();
assert_eq!(*log.borrow(), [1, 2, 3, 0]); // 8, 8 (in spawn order), 3, 1
API
| Item | Purpose |
|---|---|
Executor::default() / Executor::new(pool) | an executor with the default pool, or with your own Pool |
spawn(priority, future) | schedule a 'static future with Output = (); returns a TaskHandle |
spawn_boxed(future), spawn_future(boxed), spawn_future_with_priority(p, boxed) | the same, at priority 0 or with a pre-boxed future |
poll_once() | poll one ready task; false when every remaining task is sleeping |
run_until_stalled() | poll until no task is ready |
run() -> ! | run forever, parking when nothing is ready |
is_empty() | no tasks left |
TaskHandle::priority(), set_priority(p), wake() | inspect or change a task from anywhere; set_priority also wakes it |
BoxFuture and LocalBoxFuture are the boxed future types the executor stores.
Pools and parking
Two traits make the executor portable:
/// A local task queue. `take_ready` must remove the highest-priority ready task.
pub trait Pool {
type Park: Park;
fn push(&self, task: Task);
fn take_ready(&self) -> Option<Task>;
fn is_empty(&self) -> bool;
}
/// Parking must preserve an unpark notification delivered just before park.
pub trait Park: Default + Send + Sync + 'static {
fn park(&self);
fn unpark(&self);
}
DefaultPool is a VecDeque scanned for the highest-priority ready task. DefaultPark uses
WFE/SEV on the RP2350 and spins elsewhere. To sleep properly on a host, plug in your own Park,
for example one built on a condition variable.
On the RP2350
With the default rp235x feature on thumbv8m.main-none-eabihf, psync provides the global
allocator. Initialize it once before the first allocation:
unsafe { psync::init_heap() };
The memory.x in the repository assumes 4 MiB of flash (Pico 2). It places the heap after all
statics and reserves the top 32 KiB of RAM for the stack. Firmware also needs the RP2350 image
definition and cortex-m-rt’s linker script (build.rs passes -Tlink.x to examples on that target).
rustup target add thumbv8m.main-none-eabihf
./scripts/test-rp2350.sh # host tests, then a linked RP2350 build
./scripts/test-rp2350.sh --flash # also download with probe-rs
The script builds an
rp2350example. That example is not on theclaude/initial_psync_graphbranch, which removed the missing entry fromCargo.toml. Until it is restored, the firmware build step fails, and the host tests still run.
With #[psync::graph]
The generated code joins futures by polling them in one task. On psync’s executor, an annotated function’s concurrent branches therefore share their task’s priority. Spawn separate tasks when different pieces of work need different priorities.
The pipeline
The rest of the book is about what psync does. This part is about how. The code lives in two crates:
| Crate | Role |
|---|---|
psync-macros | the proc-macro entry points (graph, seq, fresh, independent); graph calls psync_graph::expand |
psync-graph | the analysis and code generation, an ordinary library (also used by psync-expand) |
psync (src/graph_rt.rs, exported as psync::__private) | the small runtime the generated code calls |
The proc macro is a thin wrapper, so the whole analysis can be tested and run outside the compiler.
psync-expand does exactly that.
From attribute to code
psync_graph::expand(attr, item):
- Parses the options (
bound,explain,off,crate). Ifoffis set, orPSYNC_GRAPH=off, it only strips hint attributes and returns the function. - Builds a
Scopeof mutability facts for the whole function. These are themutbindings, the bindings that hold&mutvalues (including&mut selfand&mut Tparameters), and the#[psync::fresh]bindings with their initializers. - Runs the
Rewriter(rewrite.rs) over the body. It is asyn::visit_mut::VisitMutthat handles blocks innermost first. It only rewrites code insideasync fns, async blocks and async closures, and it skips nested items. - Strips the hints, and prints the report if
explainwas given.
For each block of async code, the rewriter does five steps:
statements
│ for/while loops ──► loops.rs: prefetch, guards, fission, flattening
▼
hoist_tail an awaited block value becomes `let t = ..; t`
▼
expose_awaits awaits in scrutinees, arguments, receivers and if-branches become bindings
▼
schedule_block classify each statement; split into regions at barriers
▼
schedule_region graph → chains → levels → generated joins
A block whose regions all stay sequential is emitted exactly as written. Hoisting is undone too. So psync never changes code it cannot speed up.
The modules
| Module | What it decides |
|---|---|
classify.rs | node or barrier; awaits, exits, effects; labels |
access.rs | which variables and field paths a statement reads and writes |
hoist.rs | how to split a statement so its await becomes its own node |
schedule.rs | edges, chain fusion, levels, and the generated join |
exits.rs | how ?/return/break/continue are recorded and replayed |
loops.rs | loop prefetch, guard hoisting and inversion, fission, nested-loop flattening |
rewrite.rs | the walk that ties it together |
The next chapters take them one at a time.
Classifying statements
classify(stmt, scope, relaxed) (classify.rs) decides what each statement is. The result is
either a Node, which carries everything the scheduler needs, or a Barrier with an optional
reason for the report.
What a node records
pub(crate) struct Node {
pub stmt: Stmt, // the statement as written
pub defs: Vec<(Ident, bool)>, // bindings it introduces, with their `mut` flag
pub acc: Access, // what it reads and writes (see the next chapter)
pub awaits: bool, // awaits outside nested closures and async blocks
pub effect: bool, // an ordinary statement: keeps its order with other effects
pub exits: bool, // contains ?, return, break or continue that leave it
pub label: String, // for reports
pub line: usize,
}
Finding awaits and exits
The Exits visitor walks an expression. It does not enter closures, async blocks or nested items,
because their awaits and exits belong to them. It records:
awaits, and the names of the awaited callees (methodforx.method(),Type::ffor a path call). A second list,awaited_unscoped, holds only the awaits outside any nested block. It is used to tell a guard that is kept from one that is dropped inside the statement.exits: any?,return, orbreak/continuethat leaves the statement. Loops and labeled blocks inside the expression are tracked, so abreakaimed at an inner loop does not count.- a
blocker: something psync cannot rewrite. That is an exit hidden in macro tokens,bail!-style macros,yield, orbreakwith a value.
The decision
In order, a statement is a barrier if:
- it is a
letwithout an initializer, or an item; - it carries
#[psync::seq]or#[psync::fresh]; Exitsfound a blocker;- it calls a clock function (
now,elapsed,duration_since) outside closures and async blocks; - its pattern binds by
ref; - it awaits a delay (
sleep,sleep_until,tick,yield_now,delay_for), or awaits a guard (lock,lock_owned,read,write,acquire,acquire_owned,acquire_many,begin,transaction) outside a nested block.
Otherwise, it is a node. It is an effect unless it is shaped (a let, an await expression
statement, or a logging macro) and either awaits or binds a pure value. The block’s last
expression, its value, is always made a barrier by the caller.
relaxed is used for a loop’s prefix. It admits bindings of non-pure values as movable, because
the loop code has already confined the prefix to per-iteration data. An ordinary statement may
join a prefix only if it writes nothing, for example a guard like if done { continue; }.
What is pure
is_pure accepts expressions with no side effects that are cheap to move:
- literals, paths, closures and ranges;
- field access,
&(not&mut), unary and binary operators, casts, indexing, tuples, arrays and struct literals built from pure parts; - method calls from a fixed list of read-only methods (
clone,to_string,len,iter,is_some, …); - constructor calls:
T::new,T::from,T::default,with_capacity,Some,Ok,Err, and tuple structs; format!,vec!,concat!andstringify!with pure arguments.
Everything else that does not await is an ordinary statement, an effect, and keeps its order.
Labels
Report labels are made from the bindings and the first awaited callee (user = user()?). A
non-awaited binding shows the first 23 characters of its value. A trailing ? means the node can
exit.
Reads and writes from tokens
The heart of the dependency analysis is access::scan. It approximates what a statement reads
and writes from its tokens alone. There are no types and no name resolution.
Access paths
pub(crate) struct Access {
pub uses: Set, // every variable-like identifier mentioned (drives def-use edges)
pub writes: Set, // root identifiers of written paths
pub rpaths: Set, // access paths read, such as `self.client`
pub wpaths: Set, // access paths written, such as `self.groups`
}
For each identifier that could be a variable, scan follows .field and [index] to the place
being accessed. That gives self.groups, conn.inner or buf. Identifiers right after a .,
before ::, lifetimes and keywords are skipped. Identifiers inside format!-style string literals
("{name}") count as reads.
Paths are compared by prefix. self.groups overlaps self and self.groups.len, but not
self.group. So a loop can write self.groups while its prefetched requests read self.client.
What counts as a write
A path is written when:
| Form | Example |
|---|---|
&mut path | read_row(&mut conn, 1) |
| assignment or compound assignment | total += x, self.state = s |
a method call on a mut binding or &mut handle, unless the method looks read-only | v.push(x) on let mut v |
| an ordered method on any receiver | tx.send(v), stream.next(), file.write_all(b) |
a &mut handle passed along whole | helper(conn) where conn: &mut Connection |
The ordered methods keep their relative order on one receiver even through &self:
send send_all try_send recv try_recv next try_next feed write write_all flush
read_exact read_to_end read_to_string shutdown close execute commit rollback
A method counts as read-only if it is in the pure list (clone, len, iter, is_some, …) or
starts with one of these prefixes:
is_ has_ get as_ to_ contains len iter keys values first last count unwrap expect
starts_with ends_with clone map ok err list fetch find load query lookup describe
stat head exists search resolve download retrieve
The prefix list only matters for receivers that psync already knows are mutable. A call like
v.get(k) on let mut v stays a read. v.insert(k, x) is a write.
Which statement owns which names
Bindings made inside a statement, such as match arms or nested lets, belong to that statement.
They are removed from its writes, so a match arm binding x does not conflict with an outer x.
Uses of #[psync::fresh] bindings are removed entirely, because each branch makes its own copy.
Edges
schedule::depends(a, b), for an earlier a and a later b, adds an edge for the first of:
- data flow:
buses a name thatadefines; - rebinding: both define the same name;
- shadowing:
bdefines a name thatauses; - conflict:
awrites a path that overlaps somethingbreads or writes, orbwrites a path thatareads; - effect order: both are ordinary statements.
Two reads of the same path never conflict.
What the token analysis cannot see
These limits come from working on tokens. Each one is either guarded by the compiler, or covered by a rule above:
- Aliasing through shared references.
a.f()andb.g()on two&handles to the sameRefCelllook independent. ARefCellborrowed mutably twice at once panics at run time. AMutexserializes, and an async lock is a barrier anyway. - Hidden
&mut. A method taking&mut selfon a binding not declaredmutlooks like a read. If two such calls overlap, the borrow checker rejects the generated code. - Effects behind calls.
store.put(k, v).awaiton a shared handle is neither ordered nor&mut. The side-effects chapter covers how psync recognizes such calls. - Method names are conventions. A method called
get_and_incrementstarts withget. Read-only prefixes only apply to receivers already known to be mutable, so this mostly matters formutbindings.
Exposing hidden awaits
Many awaits sit inside a larger statement:
lens.push(api.len(&names[0]).await);
match api.kind(&names[1]).await { /* ... */ }
let v = if cached { x } else { fetch().await? };
The await is evaluated before the rest of its statement anyway. If psync moves it into its own
binding, the order stays the same, and the await becomes a node that can overlap other work. That
is hoist.rs. Rewriter::expose_awaits applies it to every statement that hides an await,
repeatedly, up to a depth of 8, because a hoisted value may itself hide another await.
The splits
| Split | Before | After |
|---|---|---|
| scrutinee | match e.await {..}, if let p = e.await {..}, if e.await {..}, let p = e.await else {..} | let __psync_sN = e.await; + the statement reading __psync_sN |
| operands | awaited arguments of a call or method call, the right side of =/+=, elements of an array, tuple or vec! | let __psync_hN = <operand>; for each operand up to the last awaited one |
| receiver | x.await?.items() | let __psync_hN = x.await?; + __psync_hN.items() |
| branch | if c { let x = f().await?; rest } | let __psync_gN = if c { Some(<awaited prefix>) } else { None }; + the remainder |
| tail | an awaited block value foo().await? | let __psync_tN = foo().await?; __psync_tN |
Operands keep their order. When an awaited argument is hoisted, every earlier argument that is
not pure is hoisted too, in order. So f(g(), h().await) still evaluates g() before h(). Pure
arguments, which cannot observe the order, stay in place. Operands are only hoisted from calls with
side-effect-free callees: a method call whose receiver is a plain place, or a call to a path. For
x += y, the left side must be a place, so evaluating y first is unobservable.
Branches are the same split that loops use for guards. The branch’s leading awaited work runs
under the same condition, wrapped in Option. The rest of the branch unpacks it, re-raises any
recorded exit, and continues.
If nothing overlaps, nothing changes
Hoisting is speculative. If the region still has no level with two chains afterwards, the rewriter
returns the block’s original statements. So you never get __psync_h bindings in code that psync
did not speed up.
The graph and the schedule
A region is a run of nodes between barriers. Regions with fewer than two awaits are left alone.
schedule::plan(nodes) turns each remaining region into a schedule.
Edges
For every pair i < j, depends(nodes[i], nodes[j]) returns the reason j must wait for i, if
there is one. The rules are listed in Reads and writes from tokens. Edges always
point forward in program order, so the graph is acyclic by construction.
Chain fusion
Nodes are visited in program order. Node v joins the chain of its predecessor u when:
uisv’s only predecessor;uis currently the last node of its chain; and- either
uhas only one successor (v), orudoes not await and every other successor ofualso (transitively) waits forv.
The second case covers a cheap binding that two later nodes read:
let key = format!("{prefix}/{id}");
let resp = store.get(&key).await?; // reads key
cache.insert(key, resp); // reads key, and waits for resp anyway
Fusing key into resp’s chain delays nothing, and it keeps the per-item pipeline whole.
Any other node starts a new chain.
Levels
A chain’s level is one more than the highest level of any chain it waits for. Chains on the same level run concurrently. Levels run one after another.
level 0: n0->n2 || n1 || n3
Levels are a deliberate simplification. A level waits for all of its chains before the next level starts. So when edges cross chains, a later chain may wait longer than its own inputs need. Chain fusion removes the most common case of this, independent per-item pipelines. A general dataflow schedule, where every node starts the moment its own inputs are ready, would need a different kind of join. psync does not do this yet.
Emitting a level
A level with one chain is emitted as the original statements. A level with several chains becomes one block:
{
let (__psync_taken0, __psync_taken1) = {
let mut __psync_f0 = ::psync::__private::maybe_done(async { /* chain 0 */ });
let mut __psync_f1 = ::psync::__private::maybe_done(async { /* chain 1 */ });
::core::future::poll_fn(|__psync_cx| {
let __psync_done0 = __psync_f0.poll_step(__psync_cx);
let __psync_done1 = __psync_f1.poll_step(__psync_cx);
if true && __psync_done0 && __psync_done1 { Poll::Ready(()) } else { Poll::Pending }
})
.await;
(__psync_f0.take(), __psync_f1.take())
};
let (/* exit slots */, __psync_out0) = __psync_taken0;
let (/* exit slots */, __psync_out1) = __psync_taken1;
/* re-raise recorded exits, sorted by source position */
let (a, b) = __psync_out0.unwrap();
let (c,) = __psync_out1.unwrap();
}
Details that matter:
- The futures live in an inner block. They, and whatever they borrow, are dropped as soon as their outputs are taken. So later statements may move values the branches had only borrowed. A bug found while compiling kube-rs forced this.
- Each chain hands back only what later code needs. psync scans every later statement outside the chain. The last binding of each name wins, as shadowing does.
mutis dropped inside a chain for bindings the chain does not write. The handed-back binding keeps itsmut. This avoidsunused_mutwarnings without changing meaning.- Exits are re-raised in program order across all chains of the level, sorted by each node’s position in the block. That makes the first exit sequential code would hit the one that happens.
- The whole block is emitted in place of the region’s statements, and the statements after it see the same bindings as before.
Generated code
This chapter follows one function through code generation. The output below is real psync-expand
output, lightly trimmed.
async fn profile_page(api: &Api, user_id: u64) -> Result<Page, Error> {
let user = api.user(user_id).await?;
let posts = api.posts(user_id).await?;
let avatar = api.avatar(&user.avatar_url).await?;
let friends = api.friends(user_id).await?;
Ok(Page { user, posts, avatar, friends })
}
One chain
Each chain becomes an async block, labeled '__psync_chainK. Its exit slots are declared first:
let mut __psync_f0 = ::psync::__private::maybe_done(async {
let mut __psync_e0_0_0 = ::core::option::Option::None;
let mut __psync_e0_1_0 = ::core::option::Option::None;
#[allow(unused_labels, unreachable_code, clippy::let_unit_value)]
let __psync_out = '__psync_chain0: {
let user = match ::psync::__private::Branch::branch(api.user(user_id).await) {
::core::result::Result::Ok(v) => v,
::core::result::Result::Err(r) => {
__psync_e0_0_0 = ::core::option::Option::Some(r);
break '__psync_chain0 (::core::option::Option::None);
}
};
let avatar = match ::psync::__private::Branch::branch(api.avatar(&user.avatar_url).await) {
::core::result::Result::Ok(v) => v,
::core::result::Result::Err(r) => {
__psync_e0_1_0 = ::core::option::Option::Some(r);
break '__psync_chain0 (::core::option::Option::None);
}
};
::core::option::Option::Some((user, avatar))
};
(__psync_e0_0_0, __psync_e0_1_0, __psync_out)
});
- The chain’s value is
Some(bindings)if it ran to the end, andNoneif an exit stopped it. - Slot names encode the chain, the member and the
?index:__psync_e{chain}_{member}_{n}. There is also__psync_r…forreturnvalues and__psync_c…forbreak/continue. - Each
?is rewritten byexits::ExitRewriter, innermost first, soa.await?.b()?records both. Closures, async blocks and nested items keep their own exits.
The join
::core::future::poll_fn(|__psync_cx| {
let __psync_done0 = __psync_f0.poll_step(__psync_cx);
let __psync_done1 = __psync_f1.poll_step(__psync_cx);
let __psync_done2 = __psync_f2.poll_step(__psync_cx);
if true && __psync_done0 && __psync_done1 && __psync_done2 {
::core::task::Poll::Ready(())
} else {
::core::task::Poll::Pending
}
})
.await;
(__psync_f0.take(), __psync_f1.take(), __psync_f2.take())
Every poll of the join polls each unfinished chain once. Finished chains keep their output inside
MaybeDone until take(). Because the join is an ordinary poll_fn, it needs nothing from the
executor. It works on Tokio, embassy or psync’s executor alike.
Re-raising
let (__psync_e0_0_0, __psync_e0_1_0, __psync_out0) = __psync_taken0;
let (__psync_e1_0_0, __psync_out1) = __psync_taken1;
let (__psync_e2_0_0, __psync_out2) = __psync_taken2;
if let Some(r) = __psync_e0_0_0 { ::psync::__private::Rethrow::rethrow(r)?; } // line 2: user
if let Some(r) = __psync_e1_0_0 { ::psync::__private::Rethrow::rethrow(r)?; } // line 3: posts
if let Some(r) = __psync_e0_1_0 { ::psync::__private::Rethrow::rethrow(r)?; } // line 4: avatar
if let Some(r) = __psync_e2_0_0 { ::psync::__private::Rethrow::rethrow(r)?; } // line 5: friends
let (user, avatar) = __psync_out0.unwrap();
let (posts,) = __psync_out1.unwrap();
let (friends,) = __psync_out2.unwrap();
Ok(Page { user, posts, avatar, friends })
The re-raises are sorted by source position, not by chain, so posts’s error is checked before
avatar’s. The unwrap()s cannot fail: they run only when no exit was recorded, and a chain
without a recorded exit always ends in Some.
Branch and Rethrow
? cannot be stored and replayed directly. psync splits it into two traits in psync::__private:
pub trait Branch { // `?`-style split: the value, or a residual to rethrow later
type Output;
type Residual: Rethrow;
fn branch(self) -> Result<Self::Output, Self::Residual>;
}
pub trait Rethrow { // re-raise through the caller's own `?`
type Carrier;
fn rethrow(self) -> Self::Carrier;
}
Result<T, E> branches to ResultResidual<E>, which rethrows as Err::<(), E>(e). Option<T>
branches to OptionResidual, which rethrows as None::<()>. Applying the caller’s ? to the
rethrown carrier runs the same From conversion the original ? would have. So the function’s
error type and conversion are unchanged.
return, break, continue
return vbecomes{ __psync_r = Some(v); break 'chain None }. It is replayed asreturn v;.- A
breakorcontinuethat leaves the node is stored as an index into a list of targets. It is replayed bymatch __psync_c { Some(0) => { continue 'outer; } ... }. breakwith a value is not supported. It makes the statement a barrier.
Loop rewriting
loops.rs handles for loops (always considered) and while loops (only with
#[psync::independent]). For a for loop, rewrite_loop does three steps:
- Flatten a directly nested
forinto one loop over pairs, when that is the same loop. - Try prefetch.
- If prefetch is refused, try fission, then prefetch the second half.
Either way it records a LoopReport.
The loop scope
struct LoopScope {
local: Set, // the loop pattern and everything bound inside the body
carried: Set, // places the body writes that outlive an iteration
independent: bool, // #[psync::independent]
}
A candidate prefix node is refused when it writes a non-local path, or reads a path in carried.
independent skips both checks.
Taking the prefix
take_prefix walks the body from the front:
- Bindings and awaits are taken while they pass the scope check. They are classified in relaxed mode, so non-pure per-iteration bindings may join.
- Further on, an awaited statement may still join if nothing left behind before it could exit the iteration, or touches what it touches.
- Awaits in scrutinees, call arguments and
ifbranches are hoisted first (the same splits as Exposing hidden awaits). if c { <awaited work>; rest }becomes a guard binding,hoist_guard.if c { ..; continue }with a purec, followed by awaited work, becomes an inverted guard,invert_guard:let g = if !(c) { Some(<work>) } else { None };. The rest of the body then unpacksgwithlet Some(..) = g else { unreachable!(..) }after the original guard. When the guard did not exit, its condition was false, sogisSome.
Prefetch
The prefix becomes one chain (see Generated code). The pattern’s bindings and the prefix’s bindings are handed to the rest of the body:
let __psync_iter = <iter>;
let __psync_each = ::psync::__private::over(&__psync_iter, async |<pat>| { <prefix chain> });
let __psync_futures: ::psync::__private::Vec<_> = IntoIterator::into_iter(__psync_iter)
.map(|__psync_item| __psync_each(__psync_item))
.collect();
let __psync_items = ::psync::__private::join_all_bounded(__psync_futures.into_iter(), <bound>).await;
<label> for (<exit slots>, __psync_out) in __psync_items {
<re-raise this item's exits>
let <bindings> = __psync_out.unwrap();
<rest of the body>
}
Two parts of this shape exist because of real compile failures:
overis an identity function with a bound,F: AsyncFn(I::Item) -> T. A closure defined on its own cannot have its parameter type inferred from later use. Passing it throughovergives the parameter the iterator’s item type.- The futures are collected before the await, in the function itself, not inside a generic
helper. rustc can then prove the state held across the await is
Send, even when items carry lifetimes (Box<dyn Trait + Send>). It cannot prove that for an iterator adapter or a helper’s future. This came up in DataFusion’s writer shutdown.
Futures are lazy, so collecting them starts nothing. join_all_bounded starts at most bound at a
time.
Fission
fission_with(head, label, attrs, pattern, body):
-
First half: every statement before the first await. A leading
if/matchwhose branches await contributes only its condition, hoisted withhoist::condition. Any blocker refuses fission. -
Check: the two halves must not touch the same carried state, unless the loop is
independent. Per-iteration names may flow from the first half to the second. -
Carry: the first half’s bindings that the second half mentions, plus the pattern’s bindings.
-
Generate:
let __psync_first = { let mut __psync_v = ::std::vec::Vec::new(); '__psync_pre: <head> { <first half, with loop-ending exits recorded> __psync_v.push((<carried names>,)); } __psync_v }; <prefetched: for (<carried names>,) in __psync_first { <second half> }> <re-raise the first half's recorded exit>
The first half’s exits are rewritten in deferring mode. An exit that ends the whole loop
(return, ?, break to an outer loop) stops the first loop with a plain break and is recorded.
continue and break aimed at the loop itself stay as written. The second loop processes exactly
the items before the exit. The exit is then performed, as sequential code would after those items.
while loops use the same code with head = while <cond>. That is why they need independent: the
condition must be driven only by the first half, and tokens cannot show that.
Flattening
for a in xs { for b in f(a) { body } }
// becomes
for (a, b) in IntoIterator::into_iter(xs).flat_map(move |a| {
IntoIterator::into_iter(f(a)).map(move |__psync_inner| (a, __psync_inner))
}) { body }
This applies only when the outer body is exactly the inner loop, neither loop is labeled, body
has no break (which would end only the inner loop), and the outer pattern is a plain identifier.
a is copied into every pair, so it must be Copy. If it is not, the code fails to compile rather
than changing meaning.
Runtime support
The generated code calls a few items in psync::__private (src/graph_rt.rs). They are not a
public API. The macro’s output is the only intended caller, and they may change freely. Everything
here uses only core and alloc.
| Item | Used for |
|---|---|
maybe_done(future) -> MaybeDone<Pin<Box<F>>> | one branch of a level’s join |
MaybeDone::poll_step(cx) -> bool | poll if still pending; true once the output is available |
MaybeDone::take() | take the output (panics if called before completion, which generated code never does) |
join_all_bounded(iter, bound) | a prefetched loop: run at most bound futures, outputs in input order |
over(&iter, f) | type the async closure’s parameter from the iterator |
Branch, Rethrow, ResultResidual, OptionResidual | record ? and replay it through the caller’s ? |
Vec | re-exported so generated code can name alloc::vec::Vec |
MaybeDone
Each branch is boxed with Box::pin. That lets the join poll it through Pin::new without unsafe
pin projection. It costs one allocation per branch per level, which is small next to an I/O
round trip. A version without allocation would need pin projection in generated code.
join_all_bounded
pub struct JoinAllBounded<I: Iterator> where I::Item: Future {
iter: Option<Box<I>>,
active: Vec<(usize, Pin<Box<I::Item>>)>,
results: Vec<Option<<I::Item as Future>::Output>>,
bound: usize,
}
On each poll it:
- starts new items while fewer than
boundare active, so a freed slot is refilled at once; - polls every active future, and stores finished outputs at their input index;
- returns all outputs, in input order, when the iterator is exhausted and nothing is active;
- returns
Pendingif nothing finished during this pass. Nothing new can start until a wake.
It does not stop early on errors. Errors are values recorded in exit slots, and the loop body replays them in order. Every item’s future is therefore run to completion. This is the speculation described in Loops.
Known gap
Fission’s first loop collects into ::std::vec::Vec, not the re-exported alloc Vec. So a
function whose loop is split by fission currently needs std. Straight-line regions and plain
prefetch need only alloc.
What is checked, what is assumed
psync’s analysis is token-level. It sees no types, no name resolution and no function bodies other than the one it rewrites. This chapter states exactly which properties come from the compiler, which from psync’s rules, and which you assume when you add the attribute.
Checked by rustc
The generated code is ordinary Rust, compiled with the rest of your crate.
- Memory safety and data-race freedom. Two concurrent branches that need the same
&mutfail to compile (E0499/E0502). A missed write dependency through a unique borrow cannot race. It is a compile error. - Types. Every hoisted binding, handed-back tuple and replayed exit is type-checked. Because
Rethrowgoes through your own?, the error conversion is the original one. Send/Sync. If your function’s future had to beSend, the rewritten one does too, or it does not compile.- Lifetimes. Borrows made by branches end at the join, which rustc verifies.
Guaranteed by psync’s rules
These hold as long as the token analysis sees the dependency:
- Def-use order. A statement that uses a binding runs after the statement that made it.
- Write conflicts by path. Two statements touching overlapping paths, one of them writing,
keep their order. That covers assignment,
&mut, a mutating method on amutbinding or&muthandle, and an ordered method (send,write,next, …) on any receiver. - Effect order. Ordinary statements never pass each other.
- Exits.
?,return,breakandcontinueare performed in program order. The function exits at the same place, with the same value. - Fixed positions. Locks and permits held past their statement, sleeps, clock reads and
#[psync::seq]statements never move, and nothing moves across them. - Loops. A prefetched prefix touches only per-iteration data, and the rest of the body runs in order. Fission is applied only when its halves share no carried state.
Assumed by you
When you add #[psync::graph], you assert:
- Unclassified calls tolerate speculation. Awaited calls that psync recognizes as writes never
run before an earlier exit (see Side effects). Calls it cannot classify
are assumed to read, and may run when sequential code would have stopped at an earlier exit. In
loops, every item’s prefix runs, even after an earlier item fails.
strictremoves this assumption. - Different handles are different resources. Two calls through different receivers
(
self.cache,self.db) may run at the same time. That includes two handles to the same server, and interior mutability behind&self. ARefCellborrowed twice at once panics. It does not race. - Names mean what they say.
get,listandheadread;put,deleteandcreatewrite; onmutreceivers, read-only prefixes likegetandis_are taken as reads. - Loop items name different objects. A write target computed from the loop item is assumed to differ between iterations.
- Hints are true.
#[psync::independent],#[psync::fresh]and#[psync::speculate]turn checks off.
How this compares with dynamic languages
Tools that reorder awaits in JavaScript rely on a whole-program side-effect analysis. They state
that it is unsound (aliasing, dynamic calls). Then they validate the rewrites with the project’s
tests. psync has less information per statement, because it sees tokens rather than a call graph.
But it gets a guarantee those tools cannot have: every missed &mut dependency is caught by the
borrow checker before the program runs. The remaining assumptions are the ones listed above, and
each can be turned off locally with a hint.
Tested behaviour
tests/graph.rs runs generated code on psync’s executor, with I/O simulated by poll counting. It
checks results, peak in-flight counts and poll counts against the sequential schedule:
- trees and chains;
- first error wins,
Option?,returnorder; - shadowing and
mut,&mut self; - loop prefetch with a bound, loop-carried state, per-iteration exits;
- guards with field sensitivity, guard inversion, fission and deferred exits;
whilewithindependent, nested loops;- locks (kept and scoped), clock reads;
seq,fresh,independent;Sendover trait objects.
Side effects: files, network and processes
The analysis in Reads and writes from tokens sees the function’s own variables and fields. It cannot see the world outside the program. Take this function:
#[psync::graph]
async fn recreate(api: &Api, name: &str, obj: &Obj) -> Result<(), Error> {
api.delete(name).await?;
api.create(obj).await?;
Ok(())
}
Neither statement writes a variable the other reads, and api is a shared & handle. Without
more information, psync would start the create before the delete finished, even though both act
on the same object on the server. It would also start the create when the delete fails, which
sequential code never does. The same goes for fs::write("cfg.toml", ..) followed by
fs::read_to_string("cfg.toml"): the file connects the two statements, but no variable does.
The effect analysis closes this gap. It gives every statement a list of effects, each one a read or a write of a target in a domain. Statements whose effects conflict keep their order, and a write never runs before an earlier statement that might leave.
In numbers
| 23 of 89 | rewrites of real functions from the audit in which psync had run a write before an earlier exit, or reordered two operations on the same resource |
| 5 | of them need a one-line hint to rewrite at all (now 79 of 90 automatic and 10 with hints; 1 is still impossible) |
| 11 | functions in the kube-rs and DataFusion benchmark patches; 9 generate identical code, and 2 now keep their writes in order |
| 3.79× | graph_suite geometric mean (3.82× before); 4 examples gained a speculate hint, and one keeps two uploads of the same file in order |
Domains and targets
psync recognizes effects from the call itself. It sees tokens, not types, so it goes by paths and names:
| Domain | Recognized from | Reads | Writes | Target |
|---|---|---|---|---|
| file | a path through fs (std::fs::write, tokio::fs::read_to_string), File::create/File::open, OpenOptions, DirBuilder | read, read_to_string, read_dir, metadata, canonicalize, open, … | everything else (write, create_dir_all, remove_file, rename, copy, …) | the path argument; rename/copy also the second |
| network | TcpStream, UdpSocket, TcpListener, UnixStream, net:: | connect, bind, … | send_to, send, write, write_all | the address |
| environment | env:: | env::var, … | set_var, remove_var, set_current_dir | the variable name |
| process | Command::new, process:: | always a write | conflicts with every domain | |
| service | any other awaited call | its name starts with a read verb: get, list, head, fetch, query, describe, … | its name starts with a write verb: create, put, post, patch, delete, upload, insert, update, commit, … | the receiver path (api, self.s3) is the domain; the verb’s first argument is the target |
Some details:
- The first verb in a method chain decides.
client.get(url).header(..).send().awaitreads.s3.put_object().bucket(b).key(k).send().awaitwrites. A verb is the whole name or its first_-separated word, sodelete_namespaced_pod,put_blobandlist_objects_v2classify without any configuration. - Ordered verbs (
send,append,push,publish,enqueue,emit,notify,ack, …) are writes whose relative order is observable. Two of them on one domain never reorder, whatever their targets. - Different receivers are different services.
self.cacheandself.dbdo not conflict. An awaited free function (delete_user(id).await) reaches an unknown service, which may be behind any receiver. - Plain synchronous calls count only when they reach a known domain.
std::fs::write(..)is a write.map.get(k)is not a service call, because it is not awaited.
The lists live in psync-graph/src/effects.rs.
When two effects conflict
Two effects conflict when at least one writes, their domains may be the same, and their targets may be the same. Targets are compared only as far as tokens allow:
- Two string literals are either equal or not:
"a.toml"and"b.toml"differ. For files, a directory and the paths inside it overlap:remove_dir_all("out")conflicts withread("out/a.txt"). format!("prefix{x}")keeps its literal prefix.format!("m.secret_storage.key.{id}")cannot equal"m.megolm_backup.v1", but may equal"m.secret_storage.key.k1".- Anything else computed may be anything.
Reads never conflict with reads. Here is what psync now builds for a read-check-recreate function:
region 0:
n0: old = get()? [await] {read `api` `name` (get)}
n1: quota = get()? [await] {read `limits` `obj . ns` (get)}
n2: delete()? [await] {write `api` `name` (delete)}
n3: create()? [await] {write `api` `obj` (create)}
n0 -> n2 (write `api` `name` (delete) vs read `api` `name` (get))
n1 -> n2 (may exit before `delete` runs)
n0 -> n3 (write `api` `obj` (create) vs read `api` `name` (get))
n1 -> n3 (may exit before `create` runs)
n2 -> n3 (write `api` `name` (delete) vs write `api` `obj` (create))
level 0: n0 || n1
level 1: n2
level 2: n3
The two reads still overlap. The delete waits for both, and the create waits for the delete.
Files work the same way:
region 0:
n0: fs::write()? [await] {write file "app/cfg.toml" (fs::write)}
n1: cfg = fs::read_to_string()? [await] {read file "app/cfg.toml" (fs::read_to_string)}
n2: readme = fs::read_to_string()? [await] {read file "README.md" (fs::read_to_string)}
n0 -> n1 (write file "app/cfg.toml" (fs::write) vs read file "app/cfg.toml" (fs::read_to_string))
level 0: n0->n1 || n2
Writes are not speculated
Early exits explained that psync may start an await before it knows whether an
earlier ? leaves the function. For a read that is harmless. For a write it is not, because the
sequential program would not have written at all. So:
-
In a region, a statement with a write effect waits for every earlier statement that may exit (
may exit before `delete` runs). -
In a loop, prefetching starts the prefixes of later items before earlier items finish. In fact it runs every item’s prefix, as Runtime support explains. If the body can end the loop (
?,return,break, or a labeledcontinueto an outer loop), a prefix with a write is not prefetched:loop `for f in files`: would write `store` `f` (upload) for later items before knowing whether an earlier item ends the loop (`#[psync::speculate]` allows it) -
In fission, the first part runs for every item before the rest runs for any item. So it may not contain writes when the body can end the loop.
Writes across iterations
Prefetching also reorders iterations against each other: item 3’s prefix may run before item 2’s
rest. psync assumes that targets computed from the loop item name different objects in
different iterations. store.upload(f) for f in files touches a different object per item. A
target that does not mention the item, such as a literal, a field or an unknown free function, is
the same in every iteration:
- a prefetched write to such a target is refused (
would write ... in every iteration at once); - a prefetched read that conflicts with such a write elsewhere in the body is refused too.
If two items can name the same object, for example a list with duplicates, the assumption is
false. Deduplicate first (the fission pattern from jdx/mise does exactly this), or mark the loop
#[psync::seq].
Hints and options
| Hint or option | Says | Effect |
|---|---|---|
#[psync::speculate] on a statement or for loop | running these writes when sequential code would not have is harmless (idempotent uploads, cache fills, PUTs of the same value) | lifts the speculation rule only |
#[psync::graph(speculate)] | the same, for the whole function | |
#[psync::independent] on a statement | its effects commute with the statements around it (two writes to different objects through one client) | lifts effect conflicts for that statement; data dependencies stay |
#[psync::independent] on a loop | iterations do not depend on each other | lifts the cross-iteration rules; the speculation rule stays |
#[psync::graph(effects(read(..), write(..), ordered(..)))] | the listed names (whole names or first words) read, write, or write in order | extends the verb lists, for your own APIs |
#[psync::graph(strict)] | unclassified awaited calls may do anything | see below |
Hints are assertions. psync does not check them.
Unclassified calls and strict
An awaited call whose name has no known verb, such as client.request(req) or do_work(x), is
unclassified. By default it is assumed to read, which is how psync behaved before effects
existed. explain lists every such call, so you can see what you are trusting:
unclassified (assumed to read; `strict` treats them as writes): request
Under #[psync::graph(strict)], an unclassified call is a write to an unknown resource. It
conflicts with every effect and never runs speculatively. Use strict where a wrong guess is
expensive, and teach psync your API’s names with effects(..) to get the concurrency back.
What the audit found
Re-running psync over the 90 confirmed real-world findings showed the analysis at work.
Five rewrites now need a hint:
matrix-rust-sdkdelete_all_known_secretsandmark_backup_as_enabledwrite account data in a loop or one after another, behind?.apache/iggyroute_datawrites Iceberg tables in a loop behind?.zedopen(file diff view) performs twoproject.update(..)calls.zedget_git_committerrunsgit.run(..)twice, andruncounts as a write verb.
Eighteen more keep their concurrency but now order a write. Among them are deletes in
neon’s physical GC, puts in delta-rs, uploads in mise and GreptimeDB, send_to_device in
matrix-rust-sdk, post_validator_voluntary_exit in Lighthouse, create_dir_all in Quickwit, and
shutdown in DataFusion’s writer orchestration.
Each of these 23 was a place where the earlier psync could perform a write the sequential program would not have, or reorder two operations on one resource.
The analysis is also conservative where names mislead. DataFusion’s
ListingSchemaProvider::refresh calls self.factory.create(..), which builds a table provider in
memory. psync reads create as a write and no longer prefetches that loop. One line restores it:
#[psync::speculate] on the loop, or effects(read(create)) on the function.
Limits
This is still a token-level analysis:
- Names can lie. A
getthat writes, or an unclassified call that deletes, is trusted as named.strictremoves the second risk. Only types can remove the first (see the roadmap). - Aliasing outside the program is invisible. Two receivers that reach the same server, a symlink, or two paths to one file are treated as different.
- Callees are opaque. An awaited call to your own helper is classified by the helper’s name, not by what its body does.
- Panics are not exits. A write may still run ahead of an earlier
unwrap()that panics.
Roadmap: beyond tokens
The effect analysis closed the largest gap: psync no longer runs recognized writes before an earlier exit, and it keeps operations on one file or service in order. But it still reads names, not meaning. This chapter collects what would make the guarantees stronger, roughly in the order it would pay off. Each item says what problem it solves, the idea, and what it costs.
The goal stays the one in the proposal: the generated program is logically identical to the sequential one. In practice that means two properties:
- Same exits. The function returns the same value or error from the same place. psync guarantees this today by replaying exits in program order.
- Same effects. The outside world sees the same operations, each resource in the same order, and nothing the sequential program would not have done. psync guarantees this today only for effects it recognizes, and only as far as targets can be told apart from tokens.
Everything below strengthens the second property.
1. Runtime disambiguation of targets
Problem. fs::write(&a, ..) and fs::read(&b) conflict today, because a and b may name the
same file. In a loop, psync assumes that items name different objects, which is false for a list
with duplicates.
Idea. Do what vectorizing compilers do with runtime alias checks. When both targets are pure expressions, evaluate them first and branch:
if __psync_target(&a) != __psync_target(&b) {
/* concurrent schedule */
} else {
/* sequential schedule */
}
For loops, collect the targets of the prefetched writes into a set before starting. Fall back to
sequential order from the first duplicate. File paths can be compared after lexical normalization,
and optionally after canonicalize (one extra syscall per path).
Result. The loop assumption becomes a check, and computed targets stop blocking concurrency. Cost. Code size, one comparison per pair, and the rule that target expressions must be pure.
2. Effect contracts checked by the type system
Problem. Names lie. cache.get(k) may write a refresh, and factory.create(..) may only build a
value in memory. A proc macro cannot look up what a callee does.
Idea. Let crates declare effects on types, and let rustc check psync’s guess. Most client APIs
already give each operation its own type: AWS fluent builders (GetObjectFluentBuilder), kube’s
Api<K> methods, reqwest’s RequestBuilder. psync would ship a trait:
pub trait Effect { const KIND: EffectKind; } // Read, Write, Ordered
impl Effect for aws_sdk_s3::operation::get_object::builders::GetObjectFluentBuilder {
const KIND: EffectKind = EffectKind::Read;
}
Those impls would live in small psync-effects-* crates per ecosystem, which the orphan rule
allows because psync owns the trait. At every call it classified, the generated code would emit a
zero-cost assertion, psync::__private::claims::<Read, _>(&builder). When the type has an impl
that disagrees with the name, compilation fails with a message pointing at the call. For your own
functions, #[psync::effect(read)] on the definition would generate the impl for a marker type
that the function returns.
Result. Name-based classification becomes a checked claim wherever an ecosystem crate covers
the API, which is most of the I/O in the audit.
Cost. Maintaining impls for popular crates, and const evaluation in generated code.
3. An effect sanitizer for tests
Problem. Static analysis will always miss something: a callee that writes, two clients to one server, a symlink. ReSynchronizer and similar tools rely on the project’s tests passing, which says little about effects that tests do not assert on.
Idea. A dynamic checker in the spirit of ThreadSanitizer, but for the outside world:
- With
PSYNC_AUDIT=1, generated code wraps each chain’spoll_stepin__private::enter(chain_id)/leave(), which sets a thread-local current chain and records when each chain started and finished, and whether its result was used or discarded by an earlier exit. - An effect log captures what actually happened, attributed to the current chain:
- files and processes: an
LD_PRELOADshim, orseccompuser notification on Linux, recordsopenatwith write flags,unlink,rename,mkdir,execve; - network: a
tracinglayer, or atower/reqwestmiddleware that records method and URL, and a hyper header (x-psync-chain) for server-side logs; - services: kube’s and the AWS SDK’s existing interceptors.
- files and processes: an
- After the test, the checker reports
- speculative writes: a write in a chain whose output an earlier exit discarded;
- effect races: two chains in flight at once, touching one path, URL or object, at least one writing;
- unexplained effects: effects of calls the static analysis classified as reads or left
unclassified, with the call site, ready to paste into
effects(..).
A cheaper variant is differential tracing: run the test suite with PSYNC_GRAPH=off and with
psync, record effect traces, and require that each resource sees the same sequence of operations.
The end-to-end benchmarks already did this informally (“both builds sent the same API requests”).
Result. Every gap in the static model becomes a test failure with a precise report, instead of a silent behaviour change. Cost. A Linux-only shim for full coverage. Middleware alone is portable.
4. HTTP semantics
Problem. A service call is a read or a write, nothing finer. HTTP says more.
Idea. When a call names an HTTP method or uses a builder with a method argument
(request(Method::PUT, url)), use RFC 9110’s classes:
- GET, HEAD and OPTIONS are safe: they behave as reads;
- PUT and DELETE are idempotent, which makes retries safe, though not running them when sequential code would not have;
- POST and PATCH are neither.
When the URL is a literal or a format! with a literal prefix, use its host and path as the target,
so writes to different hosts or collections do not conflict.
Idempotency is not the same as being safe to speculate. Deleting an object the sequential program would have kept is still wrong. So idempotency only loosens ordering among repeated identical writes, never the speculation rule.
5. Staging speculative writes
Problem. A write must wait for every earlier exit, even when its result is not needed until much later.
Idea. For writes whose result only feeds ?, use write buffering as in thread-level
speculation:
- files: write to a temporary file in the same directory when the chain runs, then
renameit into place when the exits before it are replayed, or delete it if one of them leaves; - services with transactions or idempotency keys: prepare the operation, then commit it at the replay point;
- channels: queue the message locally and send it at the replay point.
Result. The slow part (uploading the bytes) overlaps earlier work, and the visible part (the rename or commit) still happens in program order, and only if sequential code would have done it. Cost. Only some APIs offer a prepare/commit split, and it changes when errors surface: a rename can fail after the upload succeeded.
6. Cancellation instead of completion
Today a join runs every chain to completion, and a loop runs every item’s prefix, even after an earlier exit. Dropping the futures of chains that an exit has made pointless would bound wasted work. But cancelling a future in the middle of a write leaves partial state: a half-written file, or a request the server got without the client reading the reply. So cancellation is only safe for chains with no write effects, which the effect analysis can now tell. A follow-up: cancel read-only chains early, and keep running chains that write.
7. Processes, the environment and the working directory
- Arguments of
Command.git config --get,lsandcatread. Recognizing read-only subcommands of common tools would stop every process from conflicting with everything. - Working directory.
env::set_current_dirchanges what every relative path means. Today it is an environment write. It should conflict with every file effect whose path is not absolute. - Environment variables are process-global, shared with other threads that psync does not see. A write to them should be a barrier, not just an ordered effect.
8. Resolved types and calls (proposal Phase I, step 3)
All of the above still works from tokens. A rustc driver that runs after type checking (on THIR or MIR) would know:
- the exact callee of every call;
- which arguments are
&mut; - whether a
&selfmethod uses interior mutability (Cell,RefCell,Mutex, atomics); - the callee’s own effects, transitively, as in the MOD/REF analyses that ReSynchronizer computes for JavaScript.
psync would keep the macro as the user interface and the code generator. The driver would refine the graph and fail the build when the macro’s token-level guess was too optimistic.
9. A machine-checked argument
The correctness argument is small enough to formalize. Model a region as statements with read/write sets over variables and effect targets, plus an exit flag. Then prove in Lean that every schedule which
- respects def-use and conflict edges,
- never starts a write before the exits preceding it, and
- replays exits in program order
produces the same final variable state, the same exit, and the same per-target sequence of effects as sequential execution. The proof needs commutation axioms for non-conflicting effects, which are exactly the assumptions this chapter lists. Formalizing it would turn “Assumed by you” in What is checked, what is assumed into the precise hypotheses of a theorem.
Priorities
| Step | Closes | Effort |
|---|---|---|
| 1. runtime target checks | the duplicate-item assumption, computed paths | small: code generation only |
| 3. effect sanitizer (middleware + differential traces) | everything the static model misses, in tests | medium |
| 2. type-checked effect contracts | lying names | medium, ongoing per ecosystem |
| 4. HTTP semantics | coarse service conflicts | small |
| 7. processes and cwd | over-conservative processes; cwd hazard | small |
| 5. staged writes, 6. cancellation | wasted work, writes waiting on exits | medium to large |
| 8. compiler driver, 9. Lean model | the token-level foundation | large |
Sixteen real-world shapes
examples/graph_suite rebuilds 16 functions from popular Rust repositories. Each one is taken from
the concurrency audit and named with its repository, file and finding id. Every I/O call is replaced
by a timer with realistic latency. For each function, the suite:
- prints the original code and times it;
- prints the code
#[psync::graph]generates and times it; - asserts that both versions return the same result.
Both versions run on psync’s executor.
cargo run --example graph_suite --no-default-features # everything
cargo run --example graph_suite --no-default-features -- --brief # timings only
cargo run --example graph_suite --no-default-features -- kube # matching examples
Results
From one run (--brief):
pattern initial rewrite speedup origin
P1 independent awaits 205.9 ms 60.2 ms 3.42x anza-xyz/agave
P1 independent awaits 271.6 ms 60.4 ms 4.50x matrix-org/matrix-rust-sdk
P1 independent awaits 55.6 ms 35.5 ms 1.57x loco-rs/loco
P1 independent awaits 48.7 ms 8.2 ms 5.94x LemmyNet/lemmy
P2 await in a loop 242.0 ms 40.5 ms 5.98x delta-io/delta-rs
P2 await in a loop 301.9 ms 50.3 ms 6.01x apache/datafusion
P2 await in a loop 225.7 ms 45.2 ms 5.00x LemmyNet/lemmy
P2 await in a loop (fission) 211.4 ms 60.3 ms 3.50x jdx/mise
P2 await in a loop (while-loop fission, hinted) 270.7 ms 45.1 ms 6.00x launchbadge/sqlx
P2 await in a loop (fission) 161.0 ms 40.5 ms 3.97x apache/iggy
P3 per-item chains 266.7 ms 45.3 ms 5.88x kube-rs/kube
P3 per-item chains 605.0 ms 191.9 ms 3.15x neondatabase/neon
P3 per-item chains 347.3 ms 50.5 ms 6.88x quickwit-oss/quickwit
P4 late start 110.3 ms 70.3 ms 1.57x GreptimeTeam/greptimedb
P4 late start 200.5 ms 120.5 ms 1.66x sigp/lighthouse
P4 late start 175.8 ms 70.4 ms 2.50x zed-industries/zed
geometric mean speedup over 16 examples: 3.79x
Four examples carry speculate hints since the effect analysis landed:
matrix-rust-sdk’s eight account-data PUTs, mise’s content-addressed uploads, iggy’s per-table
writes, and GreptimeDB’s SST uploads. Without them, psync keeps those writes behind the ?s before
them, and the four run at about 1.0×. GreptimeDB also dropped from 1.83× to 1.57×. Its two uploads
for the same file_id now keep their order, because tokens cannot show that they write different
files.
Timings come from simulated latency, so they show the schedule psync builds, not network behaviour. For real networks, see kube-rs and DataFusion.
What each pattern shows
- P1, independent awaits. These are straight-line regions with one level. The speedup is the sum of the waits over the longest one.
- P2, await in a loop. Loop prefetch is bounded by
bound. Three of these need fission:- mise dedupes blob digests before uploading;
- iggy takes each table’s batch out of a routing map before writing;
- sqlx reserves connection slots in a
whileloop before connecting, which needs#[psync::independent].
- P3, per-item chains. Each item’s requests depend on each other, but items do not.
- kube’s
Discovery::runlists API groups, then queries each queryable group. - neon’s tenant scan runs list, then index parts, then the manifest, for each shard.
- quickwit’s delete planner is an early-
continueguard between two awaits per split. Guard inversion lets the second await run ahead too.
- kube’s
- P4, late start. A request that needs little is written after a long chain. psync starts it in
the first level:
- GreptimeDB’s upload does not need the index;
- Lighthouse’s genesis download needs only the network config;
- Zed’s database read needs nothing from S3.
One shape in full
Here is kube’s discovery loop, reduced to its dependency structure. It is the
guarded_loop_bodies_prefetch_with_field_sensitivity test:
impl Discovery {
#[graph(bound = 8)]
async fn run(mut self, all: Vec<u32>) -> Result<Self, Error> {
self.groups.clear();
for g in all {
let key = g * 10;
if self.mode.is_queryable(g) {
let versions = io(T, if g == 99 { Err(Error("bad group")) } else { Ok(self.client + g) }).await?;
self.groups.push((key, versions));
}
}
Ok(self)
}
}
Two features make this loop concurrent:
- The guard: queries run ahead only for queryable groups.
- Field sensitivity:
self.groups.pushwritesself.groups, and the prefix readsself.modeandself.client. Those do not overlap.
An error on group 99 is still returned as the first failing group, in order.
kube-rs and DataFusion
Sixteen real-world shapes measures rewritten functions with simulated I/O. This chapter is about whole programs, against real servers. Two projects were annotated, and nothing else in them was changed:
- kube-rs, the Kubernetes client:
Discovery::run,Discovery::run_aggregated,ApiGroup::query_apis,ApiGroup::query_core, and themainof thedynamic_apiexample. The patch is 7 lines, including the Cargo dependencies. - DataFusion, the query engine: listing-schema
refresh, the listing-table factory’screate_inner,SessionContext::refresh_catalogs, Arrow and Avroinfer_schema, and the writer orchestration. The patch is 11 lines.
Each application was built twice from the same tree, sequential (PSYNC_GRAPH=off) and psync, with
the annotated files touched before every build. The builds ran alternately.
Production conditions
- kube-rs ran against a real Kubernetes 1.36 control plane (kube-apiserver and etcd) with 163 CRDs. It authenticated as a controller does, with a service-account token.
- DataFusion read from Garage, an S3 implementation, over TLS, with production-sized data.
- Network distance came from toxiproxy profiles: none (same machine), in-region (2 ms) and cross-region.
- There were 300 measured runs, 5 per build, scenario and profile.
| Result | Value |
|---|---|
| kube-rs discovery and inventory, in-region (geo. mean of 6 scenarios) | 4.8× |
| kube-rs at 40 ms | 8.4× |
| DataFusion, S3 Express-like to AWS guidance latency | 4.7× to 9.3× (6.4× at S3 p90) |
| no added latency at all, 8 of 9 scenarios | faster, geo. mean 3.0× |
| slowest case: startup legacy discovery, no latency | 0.86× (95% CI 0.79–1.06) |
| API rejections | 0 |
With no network latency there is still something to overlap: the servers’ own work (TLS, authentication, flow control, encoding, storage). The one slower case opened 23 TLS connections at once instead of reusing one, for requests that each took under a millisecond. With pooled connections, the same operation was 4.0× faster.
Whole applications, start to exit
The unmodified programs that call the rewritten functions were timed from exec to exit:
- kube-rs’s
dynamic_api(akubectl get all) andkubectlexamples; datafusion-cli.
The time spent inside the rewritten functions was measured in the same runs. For kube-rs it came from the API server’s audit log. For DataFusion it came from the CLI’s per-statement timings.
| Result | Value |
|---|---|
| best kube-rs application, end to end | 9.2× (dynamic_api, remote) |
| best DataFusion application, end to end | 4.1× |
| all applications and profiles, geometric mean | 2.59× |
| applications where the functions are under 10% of the run | 0.89–1.21× (every interval includes 1) |
| failures | none in 320 runs; both builds printed the same output and sent the same API requests |
How much of the speedup reaches the user depends on the share of time spent in the rewritten functions:
- Amdahl’s law predicted DataFusion’s end-to-end result to within 3%.
- kube-rs’s
dynamic_apigot about half its prediction. Once the waits overlapped, parsing and printing thousands of objects ran on one core, and that became the bottleneck (see Patterns and pitfalls). - psync used less CPU time in every application it sped up.
- It used more memory in
dynamic_api: 32 → 66 MB, and 118 → 262 MB on a 5× cluster.
Heavy load
Run 3 loaded the same servers four ways:
- up to 32 clients at once;
- 5× more data;
- busy neighbours on the server;
- a CPU-saturated client node.
There were 2,770 measured client runs.
| Condition | Result |
|---|---|
| one client at a time | 3.4–5.4× |
| 8 clients: kube-rs fleet throughput | 2.0× (DataFusion 1.7×) |
| 5× / 4× more data | 4.6× kube-rs, 3.9× DataFusion |
| busy server | 5.2× |
| CPU-saturated client | 4.4× |
| 32 clients: kube-rs fleet throughput | 1.03× (467 requests answered 429, all retried, no failures) |
| 32 clients: DataFusion catalog refresh | 0.76× per client, 0.54× throughput |
The 0.76× regression has a clear cause. DataFusion’s catalog refresh nests two prefetched loops, 16 × 8, so each psync client could hold up to 113 requests in flight. 32 clients offered about 3,600 concurrent requests to one storage node behind one TLS terminator, and overloaded it. psync creates no extra work. But it can offer the same work all at once. A process-wide in-flight budget is the psync change these results argue for.
What these runs say
- When the rewritten functions are most of the program and they wait on the network, most of their speedup reaches the user.
- When they are a small part of it, nothing visible changes. There is no penalty either.
- When the server is already saturated, overlap cannot help, and unbounded overlap can hurt.
- In every run, the two builds produced the same output.
Attributes and hints
#[psync::graph(...)]
Goes on an async fn, including methods and async fn main (put it above #[tokio::main]). It
also rewrites async blocks and async closures inside the function it is on. A bare #[graph]
works when psync::graph is imported.
| Option | Default | Meaning |
|---|---|---|
bound = N | 16 | at most N loop iterations’ prefixes in flight, per loop; must be at least 1 |
explain | off | print the dependency graph, loops and barriers to stderr at compile time |
off | off | compile the function as written; hint attributes are removed |
crate = path | ::psync | path to the psync crate in generated code, for re-exports |
strict | off | unclassified awaited calls are writes to an unknown resource: they conflict with every effect and never run speculatively |
speculate | off | writes may run before earlier exits everywhere in the function |
effects(read(a, ..), write(b, ..), ordered(c, ..)) | none | extra verbs (whole names or first _-separated words) for the effect analysis |
Options are comma-separated: #[psync::graph(bound = 4, explain)]. Anything else is a compile
error: expected `bound = N`, `explain`, `off`, `strict`, `speculate`, `effects(..)` or `crate = path` .
Hints
| Hint | On | Effect inside #[psync::graph] |
|---|---|---|
#[psync::seq] | any statement | the statement is a barrier: it and everything around it keep their order |
#[psync::fresh] | let x = init; with one binding | the let stays in place, and each concurrent chain that uses x begins with its own let x = init;; uses of x are not conflicts |
#[psync::independent] | for or while loop | skip loop-carried-state and cross-iteration effect checks for prefetch and fission; required for while loops |
#[psync::independent] | any other statement | its effects commute with those of the statements around it; data dependencies still apply |
#[psync::speculate] | statement or for loop | its writes may run before earlier exits, or for later items before an earlier item ends the loop |
Outside a #[psync::graph] function, the hints expand to their input unchanged.
Names psync treats specially
These lists are in classify.rs and access.rs.
| List | Names | Effect |
|---|---|---|
| guard awaits | lock lock_owned read write acquire acquire_owned acquire_many begin transaction | barrier, unless the guard is dropped inside the statement’s own block |
| delay awaits | sleep sleep_until tick yield_now delay_for | barrier |
| clock calls | now elapsed duration_since | barrier (outside closures and async blocks) |
| ordered methods | send send_all try_send recv try_recv next try_next feed write write_all flush read_exact read_to_end read_to_string shutdown close execute commit rollback | a write to the receiver, whatever its type |
| logging macros | trace debug info warn error log | movable, and their ?/% sigils are not exits |
| early-exit macros | bail ensure try return_err fail | barrier |
| pure macros | format vec concat stringify | pure if their arguments are |
The effect analysis described in Side effects adds its own lists.
Environment variables and tools
PSYNC_GRAPH
| Value | Effect |
|---|---|
off | every #[psync::graph] function in the build compiles as written |
| unset or anything else | normal rewriting |
The variable is read when the macro expands. Cargo does not track it, so touch the annotated
files, or use a separate CARGO_TARGET_DIR, whenever you change it. See
Comparing builds.
psync-expand
cargo run -p psync-graph --features cli --bin psync-expand -- FILE LINE [BOUND]
Applies #[psync::graph] to the innermost function containing LINE of FILE and prints JSON:
function, start_line, end_line, bound, changed, explain, report and expanded. The
cli feature enables span locations, so line numbers appear in reports. See
Reading the report.
graph_suite
cargo run --example graph_suite --no-default-features [-- --brief] [-- FILTER]
Times 16 real-world functions before and after the rewrite, and checks that the results match. See Sixteen real-world shapes.
Tests
cargo test --no-default-features --test graph # macro behaviour
cargo test --no-default-features --test scheduling # executor
cargo test -p psync-graph # analysis unit tests
./scripts/test-rp2350.sh [--flash] # host tests and RP2350 firmware build
Cargo features
| Crate | Feature | Effect |
|---|---|---|
psync | rp235x (default) | RP2350 heap (init_heap), WFE/SEV parking and HAL dependencies, on thumbv8m.main-none-eabihf only |
psync-graph | cli | the psync-expand binary, line numbers, JSON reports |
Glossary
Access path. A variable followed by fields, such as self.groups. Reads and writes are
tracked per path. Two paths overlap when one is a prefix of the other.
Barrier. A statement that stays exactly in place and splits its block into regions. Examples are
a held lock, a sleep, a clock read, #[psync::seq], an exit hidden in a macro, and the block’s
value.
Bound. The maximum number of a loop’s prefixes in flight at once (bound = N, default 16).
Nested loops multiply their bounds.
Chain. Nodes fused into one sequential future, because each one waits only for the one before it. A chain starts its next node as soon as its previous one finishes, whatever the other chains are doing.
Edge. a -> b: b must wait for a. The reasons are data flow, rebinding, shadowing, a
conflicting write, or effect order.
Effect. An ordinary statement that is not a binding of an awaited or pure value. Effects never change order relative to each other. (The side-effects chapter also uses the word for file-system, network and process operations.)
Exit slot. A variable in which a chain records a ? residual, a return value, or which
break/continue it took. The slot is replayed after the join, in program order.
Fission. Splitting a loop into a plain first loop, which updates carried state for every item, and a prefetched second loop.
Fresh binding. A #[psync::fresh] let whose initializer every concurrent chain evaluates
again.
Guard. An if around awaited work in a loop or block. Its work runs ahead only when the
condition holds. An inverted guard is an early continue/break/return whose negation guards
the awaited work after it.
Hoisting. Moving an await out of a larger statement (scrutinee, argument, receiver, branch, tail) into its own binding, while keeping evaluation order.
Level. A set of chains joined together. Each level waits for the one before it.
Node. A statement psync may move: a binding, an awaited statement, or an effect.
Prefetch. Running the awaited prefix of every loop iteration ahead, at most bound at a time,
before running the rest of each body in order.
Prefix. The leading statements of a loop body that touch only per-iteration data and may run ahead.
Region. A run of nodes between barriers. Each region gets its own graph and schedule.
Speculation. Work that runs although sequential code would have skipped it after an earlier exit. It is allowed for awaited operations, and limited by the side-effects analysis.