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 |
| 79 of 90 | confirmed real-world findings that psync rewrites from the code as written; 10 more need one hint line |
| 3.79× | geometric mean over the 16 real-world shapes in graph_suite |
The “findings” are from the audit that motivated psync: a search of 35 popular async Rust
repositories, at pinned commits, for awaits that ran one after another but did not need to. It found
193 verified examples, 90 of them confirmed unconditionally. Each has an id such as web-16 (a
Lemmy handler) or tools-13, which the book uses to cite it. 99 of the 193 were awaits in a loop.
The end-to-end numbers 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. In three steps: (1) extend the executor to several
cores; (2) build the token-level dependency graph in a procedural macro; (3) refine it with
compiler information (HIR, THIR, MIR: types, resolved calls, aliasing, effects). The macro
described in this book is step 2, and
cargo psyncis step 3. - Phase II, synchronous concurrency. Apply the same analyses to ordinary synchronous code. Split independent regions into tasks, and run them on parallel workers. A prototype runs independent blocking statements on threads, and the design covers the rest.
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.
- Foundations teaches the compiler ideas the rest of the book relies on, from zero: tokens, syntax trees, procedural macros, rustc’s HIR, THIR and MIR, dataflow, effect summaries, class-hierarchy analysis and proofs. Each chapter has runnable examples and exercises. Read it before How psync works if those words are new to you.
- 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.
- Contributing is a tour of every crate, and recipes for adding an effect rule, a check or a test.
- 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 a checkout of the repository:
[dependencies]
psync = { path = "../psync", default-features = false }
tokio = { version = "1", features = ["macros", "rt-multi-thread", "time"] }
Which version. This book describes the development branch, which is not published yet. The branch
claude/initial_psync_graphon GitHub (psync = { git = "https://github.com/sahastasai/psync", branch = "claude/initial_psync_graph" }) has an earlier#[psync::graph], with the scheduling of the Guide but without side effects,#[psync::speculate],strict,effects(..), theMultiExecutororcargo psync. Everything in Safety needs the development branch.
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] {read service "user" (fetch)}
n1: orders = fetch()? [await] {read service "orders" (fetch)}
n2: weather = fetch()? [await] {read service "weather" (fetch)}
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
Exercises
- In
dashboard, change the third request tofetch(&user, 100). What doesexplainprint now, and about how long does the program take? - You build once, then run
PSYNC_GRAPH=off cargo runand the program still takes about 100 ms. What happened? - In
sum, changebtolet b = work(10, a + 1).await;. Does psync still overlap anything? Check withpsync-expand.
Answers
-
region 0: n0: user = fetch()? [await] {read service "user" (fetch)} n1: orders = fetch()? [await] {read service "orders" (fetch)} n2: weather = fetch()? [await] {read service `user` (fetch)} n0 -> n2 (reads `user`) level 0: n0->n2 || n1The third request reads
user, so it waits for the first. They form a chain,n0->n2, next ton1. That takes about 200 ms: 100 foruser, then 100 for the request that needs it, whileordersruns beside them. (The target is now`user`, in backticks: a binding, not a string.) -
Cargo did not rebuild the crate, because it does not track
PSYNC_GRAPH. It reused the concurrent expansion. Touch the annotated file, or use a separateCARGO_TARGET_DIR. -
No.
breadsa, so the two awaits form one chain, and the region is(unchanged). The function runs exactly as written.
Project: concurrency by hand
Before letting a macro rewrite your code, do the rewrite yourself once. This chapter builds a small program three ways:
- as written, one
awaitafter another; - concurrently, by hand, with nothing but
std; - with
#[psync::graph], which writes version 2 for you.
You will need no compiler knowledge. By the end you will know what psync generates, why it is
safe, and how to read the graph it prints. The whole program is
examples/by_hand.rs
in the repository. Run it as you read:
cargo run --example by_hand --no-default-features
A future is a value you poll
An async fn does not run when you call it. It returns a future: a value with one method,
poll. Each poll runs the function until it reaches an .await on something that is not ready
yet. Then poll returns Poll::Pending, and the future remembers where it stopped. Polled again
later, it carries on from there. When the function returns, poll returns Poll::Ready(value).
Who calls poll? An executor. Here is a complete one, in ten lines:
struct Unpark(Thread);
impl Wake for Unpark {
fn wake(self: Arc<Self>) {
self.0.unpark();
}
}
fn block_on<F: Future>(future: F) -> F::Output {
let mut future = pin!(future);
let waker = Arc::new(Unpark(thread::current())).into();
let mut cx = Context::from_waker(&waker);
loop {
if let Poll::Ready(value) = future.as_mut().poll(&mut cx) {
return value;
}
thread::park();
}
}
block_on polls the future. If the future is not ready, the thread sleeps (park) until someone
calls the waker it handed over in the Context. The waker unparks the thread, and the loop
polls again.
The other half is a future that is actually waiting for something. Real programs wait for the network. Ours waits for a timer: a helper thread sleeps, then calls the waker, as a network driver would when a reply arrives.
async fn sleep_ms(ms: u64) {
let mut deadline = None;
poll_fn(|cx| {
let at = *deadline.get_or_insert_with(|| {
let waker = cx.waker().clone();
thread::spawn(move || {
thread::sleep(Duration::from_millis(ms));
waker.wake();
});
Instant::now() + Duration::from_millis(ms)
});
if Instant::now() >= at { Poll::Ready(()) } else { Poll::Pending }
})
.await
}
poll_fn turns a closure into a future: each poll calls the closure. This one starts the timer
on its first poll and is ready once the deadline has passed.
That is a whole async runtime. Tokio and embassy do the same with better timers and many tasks.
Version 1: as written
The program is a client for a remote API. Each call takes 100 ms:
#[psync::graph(off)]
async fn profile_page_sequential(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 })
}
(#[psync::graph(off)] leaves the function exactly as written. It is here so the file can
hold all three versions.)
Each .await waits for its call to finish before the next line starts, so the function takes
four round trips: about 400 ms. Yet only one line needs an earlier one. avatar reads
user.avatar_url, so it must wait for user. posts and friends need only user_id, which
we had from the start.
Drawing the graph
Write each statement as a box, and draw an arrow from a statement to every later statement that reads what it wrote:
profile_page. One arrow: avatar reads user.Every path through the graph is a chain: statements that must run in order. There are three
chains, user → avatar, posts and friends, and nothing connects them. Run the three chains at
the same time and the function takes as long as the longest chain: two round trips, about
200 ms.
Version 2: by hand
First, the chains. An async block is a future too, and like an async fn it does nothing until
it is polled. So writing the chains down does not start anything yet:
let chain0 = async {
let user = api.user(user_id).await?;
let avatar = api.avatar(&user.avatar_url).await?;
Ok::<_, Error>((user, avatar))
};
let chain1 = async { api.posts(user_id).await };
let chain2 = async { api.friends(user_id).await };
The ? inside an async block returns from the block, not from the function. So an error in
chain0 stops chain0 and becomes its output. The other chains carry on.
Next, the join: one future that polls all three chains, keeps each output as it arrives, and is ready when all three are.
let (mut f0, mut f1, mut f2) = (pin!(chain0), pin!(chain1), pin!(chain2));
let (mut out0, mut out1, mut out2) = (None, None, None);
poll_fn(|cx| {
if out0.is_none() && let Poll::Ready(v) = f0.as_mut().poll(cx) {
out0 = Some(v);
}
if out1.is_none() && let Poll::Ready(v) = f1.as_mut().poll(cx) {
out1 = Some(v);
}
if out2.is_none() && let Poll::Ready(v) = f2.as_mut().poll(cx) {
out2 = Some(v);
}
if out0.is_some() && out1.is_some() && out2.is_some() {
Poll::Ready(())
} else {
Poll::Pending
}
})
.await;
The first poll of the join starts all three chains: each runs until its first .await and starts
its timer. All three timers now run at once. Each timer wakes the same task when it fires, the
join is polled again, and it polls the chains that have not finished.
Notice what this needs: no threads for the chains, no Send, no 'static, no spawn. The chains
borrow api and user_id from the function, and that is fine, because they all live inside the
function’s own future. That is why psync works on any executor, including on a microcontroller.
Last, put the results back together. The original function returned the first error in source
order: if api.user failed, it never even called api.posts. The concurrent version may see
several errors at once, so it raises them in the original order:
let (user, avatar) = out0.expect("joined")?;
let posts = out1.expect("joined")?;
let friends = out2.expect("joined")?;
Ok(Page { user, posts, avatar, friends })
user’s error is on the first line, so it wins over posts’s on the second, as before.
One thing did change. If
api.userfails, version 1 never callsapi.posts. Version 2 has already sent it. For a read that is harmless. For a write, such as “charge the card”, it is not, and psync must not move it ahead of a check it used to wait for. Early exits and errors and Side effects explain how psync decides, and how you tell it.
Version 3: the macro
Now put the attribute on the original function, and ask it to explain itself:
#[psync::graph(explain)]
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 })
}
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
unclassified (assumed to read; `strict` treats them as writes): user, posts, avatar, friends
Read it against your drawing:
n0…n3are the statements, in source order.?marks an early exit and[await]an await.n0 -> n2 (readsuser)is the arrow you drew.level 0: …is the schedule.->joins the statements of one chain, and||separates chains that run at the same time: yourchain0,chain1andchain2.- The last line is psync being honest. It knows many library calls (
reqwest,tokio::fs,std::process, …) and what they touch outside the program. YourApimethods are not among them, so psync assumes they only read, and says so. Ifapi.postswrote something thatapi.userread, that assumption would be wrong. Hints and Side effects show how to tell psync, andstrictmakes it treat every unknown call as a write.
Generated code shows the code behind this report, and it is version 2:
an async block per chain, a poll_fn join, and the errors re-raised in source order. The only
differences are names and bookkeeping (it also handles return, break and continue in a
chain).
Run it
sequential 401 ms
by hand 200 ms
psync 200 ms
all three pages are equal
Same pages, half the time, and the third version is the code you started with.
Quiz
? You call `profile_page(&api, 7)` and drop the result without awaiting it. How many requests reach the server?
+ None
- One, `api.user`
- All four, concurrently
> Calling an `async fn` only builds a future. Nothing runs until something polls it.
? A future's `poll` returns `Poll::Pending`. What has it promised?
- To be ready on the next poll
+ To make sure its waker is called when polling it again is worth it
- To block the thread until it is ready
> `Pending` hands the job back to the executor. The future (or what it waits on) keeps the waker and calls it when there is progress to make; `block_on` parks until then.
? Which statements of `profile_page` share a chain?
+ `user` and `avatar`
- `user` and `posts`
- `posts` and `friends`
- All four
> `avatar` reads `user.avatar_url`. Nothing else reads anything an earlier statement wrote.
? Both `api.user` and `api.posts` fail. The posts error arrives first. Which error does the by-hand version return?
+ The user error
- The posts error
- Whichever arrived first, so it varies
> Errors are re-raised in source order, so the result does not depend on timing and matches the sequential version.
? Why can the chains borrow `api` without `Arc` or `'static`?
- psync clones `api` into each chain
+ The chains are polled inside the function's own future, on the same task, so the borrow outlives them
- `Api` is `Copy`
> Nothing is spawned. The join is an ordinary future that lives in the function's frame, so normal borrowing works. This is why psync runs on any executor.
Exercises
- Change
friendstoapi.friends(user.id), after givingUseranidfield. Draw the new graph. How long does the function take now? What doesexplainprint? - Swap the first two lines of
profile_page. Does the schedule change? Does the result? - In version 2, delete the
out0.is_none() &&test, so the join pollschain0again after it finished. What happens, and why does Rust allow you to write it? - Make
api.postsreturn an error andapi.usertoo. Which error does each version return? Why must version 2 not simply return the first error that arrives? - Our
sleep_msspawns a thread per call. Why would a real runtime not do that, and why does it not matter for what this chapter measures?
Answers
-
Now
friendsreadsusertoo, so the graph has two arrows out ofn0.usercannot sit in two chains, so psync splits the work into two levels:userandpostsfirst, thenavatarandfriends. Still two round trips, about 200 ms:n0 -> n2 (reads `user`) n0 -> n3 (reads `user`) level 0: n0 || n1 level 1: n2 || n3Basic concepts explains levels, and when they cost time.
-
No and no. The graph has the same arrow, so the chains are the same. psync numbers statements in source order, so the names change:
level 0: n0 || n1->n2 || n3. -
Polling a future after it returned
Readyis a logic error. Anasyncblock panics with"`async fn` resumed after completion". The compiler allows the call becausepollis an ordinary method; the “never poll again” rule is part of theFuturecontract, not of the type system. psync’s join keeps aMaybeDoneper chain for exactly this reason. -
Both return
user’s error. Version 1 stops at the first line. Version 2 gets both errors, but raises them in source order. Returning whichever arrived first would make the result depend on the network’s timing: a different error on each run. -
Threads cost memory and a system call each; a real timer keeps one sorted queue of deadlines (see
examples/graph_suite/runtime.rs). Here we measure how many round trips the function waits for, and a sleeping thread waits exactly as long as a queued deadline.
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;).
(Two words to keep apart. An effect node is a statement of your function, and the JSON report
marks it "effect": true. A side effect, in the Safety part, is what a
call does outside the program, such as writing a file, and the report lists those under
"effects". An effect node may have side effects, and so may an await.)
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 |
write file "a" (fs::write) vs read file "a" (fs::read) | both touch the same file, service or other outside resource, and one writes (Side effects) |
may exit before `op` runs | a may exit early, and b writes something outside the program, which sequential code would then never have done (Side effects) |
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
unclassified (assumed to read; `strict` treats them as writes): user, posts, avatar, friends
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 joins the chain of its predecessor when nothing else could start sooner by keeping
them apart. In the simplest case, the node has one predecessor, and that predecessor has no other
successor. In the example, n0 -> n2 is a chain: avatar starts the moment user arrives. It
does not wait for posts or friends. Two more cases fuse too:
- a node may have several predecessors, if they are all in one chain already;
- a predecessor with several successors fuses with the next one if it does not await (a
cheap binding, such as
let key = format!(..)), and its other successors wait for that next one anyway. Fusing then delays nothing.
The graph and the schedule gives the exact rule.
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
unclassified (assumed to read; `strict` treats them as writes): len, kind
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
unclassified (assumed to read; `strict` treats them as writes): two, three
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
unclassified (assumed to read; `strict` treats them as writes): hit
(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] {write `tx` `a` (send)}
n3: send() [await] {write `tx` `b` (send)}
n0 -> n2 (reads `a`)
n1 -> n3 (reads `b`)
n2 -> n3 (writes `tx`)
level 0: n0->n2 || n1
level 1: n3
unclassified (assumed to read; `strict` treats them as writes): one, two
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.
Prior work and novelty
Overlapping independent waits automatically is not new, and neither is grouping statements into chains joined in levels:
| Work | What it does | How psync differs |
|---|---|---|
| ReSynchronizer (Arteca, Tip, Schäfer, ECOOP 2021) | Rewrites JavaScript: starts each promise as early as its inputs allow and awaits it as late as possible, within one block. A side-effect analysis, with file-system and network calls in a table, keeps conflicting calls in order. | psync compares effects by target (two different files can overlap), works across ?, return and loops, adds run-time gates and certificates, and runs at compile time with no source change. ReSynchronizer’s authors say its analysis is unsound; psync’s assumptions are listed in What is checked. |
| ApplicativeDo (Marlow et al., Haskell 2016) | GHC splits a do block into independent segments and joins them, the same shape as psync’s chains and levels, decided from the bindings. | ApplicativeDo never reorders effects. psync does, when the effects are independent. |
| Haxl (Marlow et al., ICFP 2014) | Runs the data fetches of both sides of <*> concurrently, and batches them. | Haxl forbids observable writes; psync orders them. Haxl batches; psync does not. |
| AutoFutures (KIT, 2012) | Turns independent consecutive Java calls into futures. | AutoFutures has no effect model (its ImageJ port needed a hand fix); psync’s effect table exists for exactly that. |
What is new here is the combination: Rust, at compile time, effects by target, and a join that is one future on the caller’s task, so the chains may borrow and need no runtime. Where the speedup comes from: the sum of the waits becomes the longest chain per level; see the figure in What is new, and what is not.
Exercises
Predict the report, then check with psync-expand FILE LINE
(Environment variables and tools) on a file holding the function. The
types need not exist: the macro reads tokens.
-
In
profile_page, change the second line tolet posts = api.posts(user.id).await?;. Which edges are there now? How many levels? If every call takes time T, how long does the function take, against 4T sequentially? -
In
chains, changeb1tolet b1 = io(2 * T, a1 + a2).await;. Which chains and levels does psync build? How long does the function take now, and how long sequentially? -
Put
let t = std::time::Instant::now();betweenbandcin this function:async fn with_clock(api: &Api) -> u32 { let a = api.one().await; let b = api.two().await; let c = api.three().await; let d = api.four().await; a + b + c + d }How many regions are there, and which calls run together?
-
In
send_both, sendbon a second channel,rx.send(b).await. What happens to the edgen2 -> n3, and to the levels?
Answers
- Two edges:
n0 -> n1andn0 -> n2(both readuser).n0now has two successors, so it fuses with neither, and there are two levels:n0 || n3, thenn1 || n2. That takes 2T, against 4T sequentially. b1now reads botha1anda2, so it can join neither chain.b2readsa2, buta2now has two successors, so it does not fuse either. There are two levels,n0 || n1and thenn2 || n3. That takes max(T, 2T) + max(2T, T) = 4T, against 6T sequentially. This is also the best any schedule can do here, becauseb1cannot start beforea2ends at 2T.- Two regions, because reading the clock is a barrier.
a || brun together before it, andc || dafter it. The clock reads the time between the two pairs, as it did sequentially. - The edge disappears: the two sends are on different receivers. The level becomes
n0->n2 || n1->n3: each value is sent as soon as it arrives. The side effects in braces,{write `rx` `b` (send)}, name the receiver each send writes to.
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_at::<2, true, false, false, _, _, _>(&__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 (and creates every
item’s future up front) until the rest of the body runs.
bounddoes not reduce this. For very long loops over large results, batch the input yourself (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 = combine(total, item).await; // reads `total`, which the previous iteration wrote
total = next;
}
loop `for item in items`: reads `total`, which the loop body writes
The prefix may not have outside effects that later iterations would see either. A prefix that writes the same file or service in every iteration, or writes anything at all when an earlier item might end the loop, stays in order.
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 |
would <effect> in every iteration at once | the prefix writes a file or service whose target does not depend on the item, so every iteration would write the same thing |
<effect> vs <effect>, which every iteration performs | the prefix’s effect conflicts with one the rest of the body has |
would <effect> for later items before knowing whether an earlier item ends the loop | the body can ?, return or break, and the prefix writes; #[psync::speculate] allows it (see Fission) |
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 |
<effect> is written as in explain, for example write `store` `d` (upload).
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 { None } else { Some(search) }. 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);
}
}
As written, this loop stays sequential, for a reason that has nothing to do with the dedupe set:
loop `for d in digests`: would write `store` `d` (upload) for later items before knowing whether an earlier item ends the loop (`#[psync::speculate]` allows it)
upload writes, and its ? can end the loop. If item 3’s upload fails, sequential code never
uploads item 4, but a prefetching loop already has. Here that is harmless: uploads are
content-addressed, so uploading a blob nobody records is a no-op. Say so on the loop:
#[psync::speculate]
for d in digests { /* same body */ }
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, with the same hint, at about 3.5×.
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.
Prior work and novelty
| Work | What it does | How psync differs |
|---|---|---|
| Mowry, Demke, Krieger (OSDI 1996) | A compiler inserts I/O prefetch hints into loops of out-of-core programs. The hints are non-binding, so they can never change the result. | psync runs the real call early. That is why it needs per-item checks: two items naming the same file must stay in order. |
futures::StreamExt::buffered(n) and buffer_unordered(n) | Run up to n futures at once, without threads. | This is the hand-written form of psync’s bounded prefetch; psync writes it for you and checks the items’ effects. |
| ReSynchronizer (ECOOP 2021) | Does not move statements across a loop test. | Loops are where psync gains most: nine of the sixteen shapes in the graph suite are loops, at 3.1× to 6.9×. |
| Polyhedral compilers (Polly) and DOALL | Parallelize loops whose iterations are independent, for memory. | psync’s loops are independent in their effects: requests and files, not array cells. |
Exercises
Predict the loop line of the report, then check with psync-expand FILE LINE on a file holding
the function.
-
Add a second lookup to
sizes, aftermeta:let tags = store.tags(key).await?;, and addtags.len() as u64tototal. What does psync prefetch, and how many at a time? -
Instead, add
store.touch(key).await?;aftermeta. What is prefetched now? Why? What would#[psync::speculate]on the loop change? -
Predict the report for both of these. Why do they differ?
async fn save_all(items: &[Item]) { for item in items { let bytes = item.json(); tokio::fs::write("out.json", bytes).await; } }The second version writes
format!("{}.json", item.id)instead of"out.json". -
This function passes the previous size to each lookup. What does psync say?
async fn sizes(store: &Store, keys: &[String]) -> u64 { let mut total = 0; let mut last = 0; for key in keys { let meta = store.head(key, last).await; last = meta.size; total += meta.size; } total } -
This loop returns at the first big object:
async fn first_big(store: &Store, keys: &[String]) -> Option<u64> { for key in keys { let meta = store.head(key).await; if meta.size > 100 { return Some(meta.size); } } None }Is it rewritten? With 1000 keys, where the first one is big, how many
headrequests does the sequential loop make, and how many does the rewritten one make? When would that matter?
Answers
- Both:
prefetch [meta = head()?, tags = tags()?], 8 at a time. The prefix is every leading awaited statement that touches only the item, andbound = 8sets how many run at once. prefetch [meta = head()?], 8 at a time.touchis one of the method names psync treats as a write to its receiver (Side effects), andhead’s?can end the loop. A prefetching loop would touch later keys before knowing whether an earlier key failed, which sequential code never does. With#[psync::speculate]it saysprefetch [meta = head()?, touch()?]: you have said that touching a key that sequential code would not reach is fine.- The first stays sequential:
would write file "out.json" (fs::write) in every iteration at once. Every iteration writes the same file, and the last write must win.#[psync::speculate]does not change this, because it is about exits, not about order. The second is rewritten:prefetch [bytes = item . json (), fs::write()], 16 at a time; per-item targets checked at run time. The names differ per item, but psync cannot prove that two items never have the sameid. It compares the paths before starting, and falls back to the sequential loop if two are the same (Checking per-item files). reads `last`, which the loop body writes. Each lookup needs the previous iteration’s result, so the iterations really are a chain, and the loop stays as written.- Yes:
prefetch [meta = head()], 16 at a time. Thereturnis replayed in order, so the function returns the first key’s size as before. But all 1000headrequests run, at most 16 at a time, against 1 for the sequential loop. All prefixes complete before the rest of the body runs for the first item. That is fine when the big object is usually late, or not there. It is wasteful when it is usually early, and harmful against a rate-limited service. Then keep the loop sequential with#[psync::seq], or split the keys into batches.
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.
An exit is replayed only once every statement before it has run, because sequential code runs those first, and one of them might exit instead. That matters when an earlier statement lands in a later level:
let a = io(T, 1).await;
let b = io(T, 2).await;
logged(log, a + b, fail[0]).await?; // waits for a and b: level 1
let c = io(T, if fail[1] { Err(Error("four")) } else { Ok(4) }).await?; // level 0
c’s request overlaps a’s and b’s. If it fails, psync still runs logged, and returns
logged’s error if both fail, exactly as the sequential function does. Anything that waits for c
starts only after that replay. (The test exits_wait_for_earlier_statements_in_later_levels
checks every combination. An earlier version replayed c’s exit right after level 0, skipping
logged; the Lean theorem replay_correct states the rule that this broke.)
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
unclassified (assumed to read; `strict` treats them as writes): one, two
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.
Cancellation, timeouts and select!
An exit is something the function does. Cancellation is something done to it: the caller
drops the function’s future before it finishes, for example when a tokio::time::timeout fires
or another branch of a select! wins. The future simply stops at the await it was waiting on, and
nothing after that runs. There are two cases to know about.
Your function is cancelled. psync never cancels a chain on its own: within a level every chain
runs to its end (or to its recorded exit), and only then are exits replayed. But when the
caller drops the whole future, every chain in flight stops at once. Sequential code had at most
one write in progress at that moment; psync may have several, each stopped halfway: a file half
written, a request sent whose reply nobody reads. Reads lose nothing but the work. So if the
function may be cancelled, ask whether two of its writes being interrupted together is worse
than one. cargo psync check reports every function where it can happen, as a cancellation
note (Checking rewrites). The fixes are the usual ones: #[psync::seq] on
one of the writes keeps them apart, or make the writes safe to interrupt (write to a temporary
file and rename, idempotent requests), or don’t cancel the function (spawn it as a task and drop
only the handle’s result). Synchronous code (Phase II) cannot be cancelled
halfway, so the note does not apply to it.
Your function uses select! or join!. These macros await the futures you give them, with no
.await written anywhere, and psync cannot see the calls inside a macro. So a statement using
select!, select_biased!, join! or try_join! is a barrier, and its effects count as
unknown writes:
#[psync::graph(explain)]
async fn put_with_timeout(store: &Store, key: &str) -> Result<Obj, Error> {
let done = tokio::select! {
r = store.put_object(key) => r,
_ = tokio::time::sleep(T) => Err(Timeout),
};
let obj = store.get_object(key).await?;
let other = store.get_other(key).await?;
Ok(obj)
}
region 0:
n0: obj = get_object()? [await] {read `store` `key` (get_object)}
n1: other = get_other()? [await] {read `store` `key` (get_other)}
level 0: n0 || n1
barrier: line 3: `let done = tokio :: select ! { r = store . put_object (key) `: `select!` awaits calls psync cannot see inside the macro
The two reads after it still overlap each other. (Before psync knew these macros, the select!
looked like an ordinary statement with no effects and ran beside get_object, reading the key it
was writing. The test awaiting_macros_are_barriers keeps it fixed.) The same mistake showed in
real code: in the audit’s reth finding (debug_subscribe, chain-29), a loop body acquires a
trace permit with let permit = tokio::select! { _ = sink.closed() => break, permit = this.acquire_trace_permit() => .. } and then traces a block. psync used to start the trace
beside the select!, before the permit was held, slipping past the limit the permits exist to
enforce.
Now the trace waits for the permit, and the function is still rewritten elsewhere. A ? inside the macro’s
arms, as in r = store.put_object(key) => r?, makes it a barrier for that reason too. In a loop
body, the unknown writes stop the loop from being prefetched; mark the loop
#[psync::independent] if its iterations really are independent.
select! itself is where cancellation happens: the branches that lose are dropped. If you put a
#[psync::graph] function in a select! branch, the first case above applies to it.
Prior work and novelty
Raising failures in the order the sequential program would have is an old idea:
| Work | What it does | How psync differs |
|---|---|---|
| Haxl (ICFP 2014, §8.1) | When both sides of <*> may throw, the left exception wins, “otherwise the result would be non-determinism”. | psync does the same for Rust ?, return, break and continue, across chains on one task, and handles the values each exit carries. |
| Safe Futures for Java (OOPSLA 2005) | An exception in a future is delivered at the point the sequential program would have raised it. | Safe Futures rolls back speculative work. psync cannot roll back I/O, so a write after a possible exit waits for it, unless you mark it speculate. |
| ReSynchronizer (ECOOP 2021) | Never moves a statement across a return or an if test. | psync moves calls across ? and re-raises in source order, which matters in Rust, where calls are usually followed by ?. |
Exercises
Predict, then check by running the tests named (cargo test --no-default-features --test graph).
-
first_error_wins([true, true, true]): which error comes back? How many requests were in flight at the peak? -
In the later-level example above (
exit_after_later_level),fail = [false, true]: doesloggedrun? What is returned? -
Same function,
fail = [true, false]:loggedfails,foursucceeds. Sequential code never startsfour. Does psync? Is that a problem here? -
Change
fourinto a write, for examplestore.put("c", 4).await?. What does psync do with it now, and why? (Check withpsync-expand.) -
A request handler is wrapped in
tokio::time::timeout(Duration::from_secs(2), handler(..)). psync runs two of its statements together:cache.put_entry(k, v).await?andaudit.append(k).await?. The timeout fires while both are in flight. What can be left behind that the sequential handler could not leave, and what wouldcargo psync checksay? -
Why is
futures::join!(a.fetch(), b.fetch())a barrier, even though both calls only read?
Answers
Err("x"), the first in program order. All three ran at once, so the peak is 3: exits are recorded, not taken, until the join.- Yes.
fourfailed in level 0, butloggedcomes first in program order, so psync runs it (level 1) before replayingfour’s error. It returnsErr("four"), and the log is[3]. - Yes:
fourran in level 0, beforeloggedwas even started. That is speculation, and it is harmless here becausefouronly reads. Its result is dropped andlogged’s error is returned. - It stays after
logged: a write may not start before an earlier statement that may exit (may exit before `put` runs), because sequential code would not have written anything whenloggedfails.#[psync::speculate]on the statement would let it overlap again. - Both writes may stop halfway: the cache entry may be written while the audit line is not, or
the reverse, or each half done. Sequentially, the timeout could interrupt only the one in
progress, and the other was either finished or not started.
cargo psync checkreports acancellationnote on the function naming both chains. - psync cannot see inside a macro’s tokens, so it cannot tell that both calls only read. It assumes the worst: the statement awaits something unknown that may write anything.
Hints
psync reads tokens, and some things you know cannot be seen in tokens. Four hint attributes tell
psync what you know. (A fifth, #[psync::par], marks a slow call worth a thread in
synchronous code; this chapter is about async functions.) Inside a #[psync::graph] function, psync reads them and removes them from
its output, which matters: stable Rust does not allow a custom attribute on a statement or an
expression. Outside a #[psync::graph] function, a hint on a let or a for loop is a compile
error:
error[E0658]: custom attributes cannot be applied to statements
Inside one, the graph macro reads the hint and removes it before the compiler sees it.
| Hint | Goes on | Means |
|---|---|---|
#[psync::seq] | a statement | keep this statement exactly where it is |
#[psync::fresh] | a let | each concurrent chain evaluates the initializer again, instead of sharing the value |
#[psync::independent] | a for or while loop, or a statement | on a loop: iterations do not depend on each other, even where psync cannot prove it. On a statement: its outside effects commute with the others’ |
#[psync::speculate] | a statement, a loop, or the function (#[psync::graph(speculate)]) | its writes may run before an earlier statement that might exit, because doing them anyway is harmless |
Reading the report, in one box
Every hint answer starts from the report that #[psync::graph(explain)] or psync-expand FILE LINE prints (Reading the report has the whole format):
region 0 (unchanged): a stretch of the function psync scheduled; "(unchanged)": it runs as written
n0: x = post_search()? [await] {..} one statement (a node), with what it does to the outside world in {..}
n1: y = post_search()? [await] {..}
n0 -> n1 (reason) an edge: n1 must wait for n0, and why
level 0: n0->n1 "->" joins nodes into one chain, run in order;
"||" separates chains that run at the same time
A chain is a run of nodes that must stay in order. A level is a set of chains that run
concurrently. Levels run one after another. level 0: n0 || n1 is what you want to see.
When two effects conflict
The reason for an edge is often two effects on the outside world. Two effects conflict, and keep their order, when all three of these hold:
- the same resource: the same file system, or the same service handle (
es,self.client); - at least one writes: two reads never conflict;
- the targets may be the same. Two different string literals (
"index.html"and"draft.html") are known to differ, so they do not conflict. A variable or an expression (aandb,KeyBackupContent { .. }) could hold the same value, so psync assumes they may.
So store.get("index.html") and store.delete("draft.html") have no effect edge, but
es.post_search(a) and es.post_search(b) do: post_search writes, by its name, and a may
equal b. Side effects has the full rules.
One rule is about memory, not the outside world, and it explains many edges: a &mut handle
passed to a call counts as a memory write of that handle, because the call may change what
is behind it. The report shows it as writes `pool` , and no hint can remove it
(Unique handles stay ordered).
Which hint, if any?
Read the report first (#[psync::graph(explain)] or psync-expand). Every edge has a reason,
and the reason tells you which hint, if any, applies:
What each hint costs you:
| Hint | What you promise | Who checks it |
|---|---|---|
seq | nothing | nothing needs to: it only adds order |
fresh | evaluating the initializer again gives an equally good value | the borrow checker checks the copies; the rest is your promise |
independent | the statement’s outside effects commute with the others’ | nobody: the proof and cargo psync check take it as true |
speculate | performing the write when sequential code would have stopped first is harmless | nobody, as above |
Adding a hint follows each hint through the code and the proof.
#[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] {read service `pool` (read_row)}
n1: b = read_row()? [await] {read service `pool` (read_row)}
level 0: n0 || n1
Each chain begins with its own let pool = &mut context.pool();. Uses of pool do not count as
conflicts: psync draws no edge for pool at all, because each chain will have its own. The
let pool itself is a barrier, so it runs first and stays out of the region, which is why the
report starts at n0: a = ... The {read service pool} effect is read_row’s own: a read,
by its name. Without the hint, the let would be node n0, the two reads n1 and n2, and the
shared &mut would add the memory edge writes `pool` . 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). Four other findings needed independent on a
loop. Five more have needed a hint since psync started tracking side effects: speculate where a
loop writes behind a ?, or independent (or effects(..)) where two calls on one resource
really commute. Side effects lists them.
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] // an upload sequential code would have skipped does no harm
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.
Exercises
Check each answer with psync-expand FILE LINE.
- Remove
#[psync::fresh]fromfresh_pool. Which edges does the report show, how many chains, and does the region change? Why does reading throughpoolcount as a write? - Take the two
set_account_datacalls from theindependentsection, with no hints. Predict the edges. Then predict them with only#[psync::independent]on the second call, with only#[psync::speculate], and with both. - Which hint, if any, do you reach for in each case?
- Two
GETs to an API that allows one request at a time. - A loop that charges a card for each order, and can stop at a
?. - A loop that fills a cache with
cache.insert(k, v)after an awaited lookup. - Two queries that must see the same transaction.
- Two
Answers
- Three edges:
n0 -> n1andn0 -> n2(both readpool), andn1 -> n2 (writes `pool`). That is one chain,n0->n1->n2, so the region is(unchanged).poolis a&mut, and passing a unique handle to a call may change what is behind it, so psync treats it as a write (Unique handles stay ordered). - With no hints there is one edge, for the two writes to
self.client:write `self.client` `KeyBackupContent { enabled : t…` (set_account_data) vs write `self.client` `BackupDisabledContent { disabl…` (set_account_data).independentremoves that edge, but another one takes its place:n0 -> n1 (may exit before `set_account_data` runs). The first call’s?may leave, and the second call writes.speculatealone removes the exit edge but not the conflict, so the report shows the conflict again. Each hint answers one question. Only with both is the leveln0 || n1. -
#[psync::seq]on the secondGET. Nothing in the tokens says the API is limited.- None. Leave it sequential, and certainly do not add
speculate: a charge for an order that sequential code would never reach is not harmless. psync already refuses to prefetch it. #[psync::independent]on the loop, if a repeated lookup for a duplicate key is fine.- Not
fresh, which would give each query its own value. Without hints psync keeps the queries through one&muttransaction in order. If they go through a shared handle, mark the second one#[psync::seq].
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
unclassified (assumed to read; `strict` treats them as writes): user, posts, avatar, friends
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. A node with side effects outside the program ends with them in braces:{read service "user" (fetch)}is a read, by the callfetch, of the service named by the string"user".{write file "cfg.toml" (fs::write)}writes that file. The rules that produce these are in Side effects.nA -> nB (reason):nBwaits fornA. The reasons are listed in Basic concepts.unclassified (..): nameslists the awaited calls whose names say nothing about what they do (user, notget_user). psync assumes they only read, so they may run concurrently. Check that list: a call in it that really writes is the one place a token-level analysis can be wrong.#[psync::graph(strict)]treats them as writes instead, andcargo psync checkchecks them against the compiled callees.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, or a clock read (Instant::now(),t.elapsed()), which awaits nothing but splits the awaits around it into two regions. Other barriers without an await (a#[psync::fresh]binding, a nested item) are not listed. A prefetched loop that ends the function is listed as a loop, not as a barrier. 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.
Worked example: a false edge
A report is most useful when it shows an edge you did not expect. Take:
#[psync::graph(explain)]
async fn report(db: &Db, cache: &Cache) -> Result<Report, Error> {
let view = db.create_view("sales").await?;
let totals = db.get_totals("sales").await?;
let hits = cache.lookup("sales").await;
Ok(Report::new(view, totals, hits))
}
region 0:
n0: view = create_view()? [await] {write `db` "sales" (create_view)}
n1: totals = get_totals()? [await] {read `db` "sales" (get_totals)}
n2: hits = lookup() [await] {read `cache` "sales" (lookup)}
n0 -> n1 (write `db` "sales" (create_view) vs read `db` "sales" (get_totals))
level 0: n0->n1 || n2
Read it from the bottom. One level, two chains: create_view then get_totals in order, and
lookup beside them. Why must get_totals wait? The edge says: psync took create_view for a
write (create is a write verb) on the receiver db, with the target "sales", and get_totals
reads the same thing.
Is that true? It depends on your Db. If create_view only builds a query plan in memory, the
edge is false, and you can say so for this one name:
#[psync::graph(explain, effects(read(create_view)))]
region 0:
n0: view = create_view()? [await] {read `db` "sales" (create_view)}
n1: totals = get_totals()? [await] {read `db` "sales" (get_totals)}
n2: hits = lookup() [await] {read `cache` "sales" (lookup)}
level 0: n0 || n1 || n2
All three requests now start together. If create_view really does create a view on the server,
the first report was right, and changing it would let get_totals read before the view exists.
Before overriding a name, check what the callee does: cargo psync check
reads its body and tells you.
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, "effects": [],
"exits": true, "line": 2, "speculate": false },
...
],
"edges": [[0, 2, "reads `user`"]],
"chains": [[0, 2], [1], [3]],
"levels": [[0, 1, 2]],
"unclassified": [[2, "user"], [3, "posts"], [4, "avatar"], [5, "friends"]],
"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.
Exercises
-
Here is a function and its report:
#[psync::graph(explain)] async fn digest(api: &Api, ids: &[u64]) -> u64 { let mut seen = 0; let first = api.fetch(ids[0]).await; seen += first.len(); let second = api.fetch(ids[1]).await; let rank = api.rank(first.score + second.score).await; seen + rank }region 0: n0: seen = 0 n1: first = fetch() [await] {read `api` `ids [0]` (fetch)} n2: seen += first . len () ; n3: second = fetch() [await] {read `api` `ids [1]` (fetch)} n4: rank = rank() [await] n0 -> n2 (reads `seen`) n1 -> n2 (reads `first`) n1 -> n4 (reads `first`) n3 -> n4 (reads `second`) level 0: n0 || n1 || n3 level 1: n2 || n4 unclassified (assumed to read; `strict` treats them as writes): rank- Which requests are in flight together?
n1 -> n2is the only edge inton2from an await. Why isn1->n2not a chain?- Why does
rankappear underunclassified, butfetchdoes not? - What are
chainsandlevelsin this function’s JSON report?
-
In the false-edge example, change the second call to
db.get_totals("orders"). What happens to the edge, and why? -
In the same example, rename
cache.lookuptocache.refresh. The level does not change. What else changes in the report, and what should you do about it? -
Put
strictonprofile_page:#[psync::graph(strict)]. How many levels are there? Why doesunclassifiedstill list all four calls?
Answers
-
firstandsecond, in level 0.rankcomes later, in level 1.- A chain needs an edge from a node with exactly one successor, and
n1has two (n2andn4). Neither edge fuses, so bothn2andn4are in level 1. fetchis a read verb, so it gets an effect: a read ofapiwith the targetids [0].ranksays nothing about what it does. psync assumes it reads and lists it so that you can check."chains": [[0], [1], [2], [3], [4]], one chain per node, and"levels": [[0, 1, 3], [2, 4]], indices intochains.
- The edge disappears, and the level becomes
n0 || n1 || n2. The write is now todb"sales"and the read todb"orders". Two different literal targets in the same domain are taken to be different things (Side effects). n2loses its effect, which had been{read `cache` "sales" (lookup)}, andrefreshis listed underunclassified.refreshis not a read verb, and it is not in psync’s list of write names either. If it rebuilds the cache on the server, it is a write. Runcargo psync check, which reads its body, or say so witheffects(write(refresh)). That does change the schedule, though nothing else touchescache: a write may not start before an earlier statement that may exit, sorefreshnow waits for both?s (n0 -> n2 (may exit before `refresh` runs)), and the region is(unchanged). If a refresh that sequential code would have skipped is harmless,#[psync::speculate]on it lets it overlap again.- Four levels: every call becomes
{write unknown (user)}, two unknown writes always conflict, and the region is(unchanged). Theunclassifiedline lists names, not what psync did with them, and its text still says “assumed to read”. Withstrict, they are the calls that were made writes.
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.
Exercises
-
You build with
PSYNC_GRAPH=off, then without it, and both binaries take the same time. Before concluding that psync does not help, what two things do you check? -
Why alternate the two builds run by run, instead of running ten sequential runs and then ten psync runs?
-
Your sequential build shows three requests in flight at once. Name two possible causes.
-
Predict what psync rewrites in this function, then check with
psync-expand(give it the line ofinner(api).await + blk.await, or it picks the innermost function):#[psync::graph] async fn outer(api: &Api) -> u32 { async fn inner(api: &Api) -> u32 { let a = api.get_a().await; let b = api.get_b().await; a + b } let blk = async { let c = api.get_c().await; let d = api.get_d().await; c + d }; inner(api).await + blk.await }
Answers
- That the “off” binary really is sequential and the other really is not: Cargo may have reused
one expansion for both (Cargo does not see
PSYNC_GRAPH). Then that there is waiting to overlap: with no latency, or a saturated server, psync has nothing to gain. - The network and the machine drift: caches warm up, other load comes and goes. Alternating spreads that drift over both builds equally, so it does not show up as a difference between them.
- The expansion was reused from a psync build (touch the files, or use separate target
directories). Or the code was already concurrent without psync, for example through a
join!or a spawned task. The second is not a bug, but it means the sequential baseline is not one request at a time. - Only the async block:
c || d. The nestedfn inneris an item, which needs its own attribute, soaandbstay sequential. The last line is the block’s value, a barrier, soinner(api).awaitandblk.awaitrun one after the other, as written.
Predicting the speedup
Comparing builds measures what psync did. psync-predict tells you what it
would do, before you annotate anything, from one run of the code as it is. You give it the
function and a trace of that run: the source line of each call, and how long it took. It replays
psync’s schedule over those costs.
cargo run -p psync-graph --features cli --bin psync-predict -- src/profile.rs 3 run.trace
An example
Take profile_page from the introduction, and one measured run of it, in milliseconds:
#[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 })
}
# one sequential run, in ms: LINE COST
3 40
4 120
5 60
6 80
profile_page: 300 as measured, 120 predicted with psync
speedup: 2.50x
region: 300 -> 120
level 0: 120, set by n1 (line 4)
psync runs user then avatar (100 ms) next to posts (120 ms) and friends (80 ms). The level
takes as long as its slowest chain, posts on line 4: that is the critical path. Making user
or avatar faster would not help. Making posts faster would, down to 100 ms.
How the prediction works
The trace is of the code as written, so the calls in it are the ones that run took: a call on a branch that was not taken has no line in the trace. The prediction is for that path. To cover several paths, give several runs (below).
- A region costs, per level, its slowest chain, where a chain costs the sum of its calls. Levels run one after another.
- A prefetched loop first runs the prefix of every item, at most
boundat once, each starting as soon as a slot frees. The rest of each body then runs in order. - Everything else, such as calls before a lock or outside any region, costs what it cost.
This is psync’s schedule, not an ideal one. A level waits for all of its chains (Levels), and the prediction does too.
Checked against measurement
tests/predict.rs checks every prediction against the rewritten function’s measured time. Each
test function has two copies, one #[graph(off)] and one #[graph]. A traced timer records the
line it is called from. The sequential copy’s trace predicts the other copy’s time, and the test
measures it:
| Function | Sequential | Predicted | Measured |
|---|---|---|---|
| a tree of four calls (one waits for two) | 70 | 40 | 40 |
| two chains whose edges cross | 80 | 60 | 60 |
| a guarded call, branch taken | 70 | 40 | 40 |
| the same, branch not taken | 30 | 20 | 20 |
a loop of 6 items, bound = 3 | 96 | 33 | 33 |
the same loop, bound = 16 | 96 | 31 | 31 |
The same file checks profile too. A #[graph(profile)] copy of each function reports exactly
the trace the timer recorded, so its trace predicts the same time.
Time there is counted in executor rounds, and a simulated call is ready a fixed number of rounds after it starts, as a timer would be. (An earlier version of the test counted each call’s own polls. That made calls in a bounded join look faster than they are, because the join polls some futures more than once per round.)
Several runs: a critical path per path
A function with a branch has more than one critical path. Here the avatar comes from a cache, and only a miss asks the API:
#[psync::graph]
async fn profile_page(api: &Api, cache: &Cache, user_id: u64) -> Result<Page, Error> {
let user = api.user(user_id).await?;
let posts = api.posts(user_id).await?;
let mut avatar = cache.get_avatar(&user.avatar_url).await;
if avatar.is_none() {
let fetched = api.avatar(&user.avatar_url).await?;
avatar = Some(fetched);
}
let friends = api.friends(user_id).await?;
Ok(Page { user, posts, avatar, friends })
}
Put several runs in one trace, separated by ---. Two hits and a miss:
# three runs of the function as written, in ms: LINE COST
3 40
4 120
5 2
10 80
---
3 40
4 120
5 2
7 60
10 80
---
3 45
4 110
5 2
10 85
psync-predict groups the runs by the lines they ran, which is the path they took, and predicts
each path:
profile_page: 3 runs, 2 path(s); mean 262.0 as measured, 138.7 predicted with psync
path 0: 2 of 3 runs (67%), lines [3, 4, 5, 10]: 242.0 -> 117.0 (2.07x)
its slowest run (run 0): 242 -> 122
region: 242 -> 122
level 0: 120, set by n1 (line 4)
level 1: 2, set by n2 (line 5)
path 1: 1 of 3 runs (33%), lines [3, 4, 5, 7, 10]: 302.0 -> 182.0 (1.66x)
its slowest run (run 1): 302 -> 182
region: 302 -> 182
level 0: 120, set by n1 (line 4)
level 1: 2, set by n2 (line 5)
level 2: 60, set by n3 (line 6)
Each path is a condition (here: the cache missed, line 7 ran) with its own critical path,
and the share of runs that took it says how much that critical path matters. On a hit, posts
(line 4) sets the time. On a miss, the avatar request adds a level of its own, 60 ms after
everything in level 0, although it only needs user. That is psync’s schedule: the if waits for
the cache read, which waits for user, and user has two later statements depending on it, so
they are not fused into one chain with it, and each starts a new level
(Chain fusion). The what-if says what fixing it is
worth: overlapping the miss with posts would take path 1 from 182 to about 120 ms (the chain
user, cache, miss is 102 ms, under posts’ 120), on a third of the runs. Levels with no measured time (a branch not taken, a generated statement) are not
printed.
A path is told apart only by a statement that awaits inside the branch and is timed on its own
line. A match whose arm awaits (None => api.avatar(..).await?) is one statement, timed once,
so its hits and misses look like one path with two costs. Each group’s mean is then a mixture.
Getting a trace
Add profile to the attribute, install a clock and a sink, and run the program once:
#[psync::graph(profile)]
async fn profile_page(api: &Api, user_id: u64) -> Result<Page, Error> { /* as before */ }
fn main() {
static START: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
psync::profile::install(
|| START.get_or_init(std::time::Instant::now).elapsed().as_micros() as u64,
|line, cost| eprintln!("{line} {cost}"),
);
// ... run the program
}
profile compiles the function as written, like off. Every statement that awaits reports its
line and how long it took to the sink, which here prints one trace line to stderr, in
microseconds. A statement that awaits inside a nested block, such as the if of a guarded call,
is timed once, by the innermost statement. Async blocks and closures inside the function are
separate futures and are not timed. With no clock installed, profile reports nothing, so
psync needs no std for it.
Any other timing source works too, as long as it gives the line of each statement and its cost in
one unit. Spans inside a callee (#[instrument] on posts) record the callee’s line, though,
which is not what the prediction needs.
On the graph suite
graph_suite runs every example a third time, profiled, and
prints the prediction next to the measured rewrite, in its predicted column. Its timers are real,
so this checks the prediction against wall-clock time. All 16 predictions are within 0.3 ms of the
measured rewrite, for runs of 8 to 191 ms.
Getting there took three fixes, each found by a miss:
- A sample can sit inside its node. In matrix-rust-sdk, the node is an
if leton line 75 and the profiled call is on line 76. Matching by first line found no node, so the prediction counted that call as sequential (90 ms predicted, 60 ms measured). Nodes now carry their last line too, and a sample belongs to the node whose lines contain it. - A prefix may start without awaiting. In delta-rs, the prefix is a
format!and then a request. Only the request is profiled, so splitting items at the prefix’s first line found none. Items now start wherever the prefix starts again. - An inner loop runs once per outer item. In neon, the five downloads of each shard were pooled into one bounded run of twenty, which predicted 171 ms against 191 ms. A sample outside the loop now ends a run of it.
A fourth miss was in psync’s report itself. In quickwit, a guarded call hoisted into a loop’s prefix was reported on the guard’s line only, so its time could not be found. The node now spans the statements it took.
Limits
- A statement left by
?,returnorbreakreports nothing underprofile. Trace a run without an early exit, or expect the prediction to miss that statement’s time. - A statement in a region is matched by the lines it spans. Within a prefetched loop, items are told apart by where the prefix starts again, so a prefix must await before the rest of the body does.
- The prediction counts waiting only. With everything arriving at once, CPU work after the waits can become the bottleneck (Patterns and pitfalls), and servers may slow down under the extra load.
Prior work and novelty
| Work | What it does | How psync differs |
|---|---|---|
| Critical path analysis (Yang and Miller, ICDCS 1988) | The longest weighted path in the program activity graph decides the run time. | psync’s per-path critical path is this analysis, on the graph of the proposed schedule, grouped by control path with the share of runs that took each path. |
| Coz (Curtsinger and Berger, SOSP 2015) | Measures what would happen if a line were faster, by slowing everything else. | Coz runs an experiment per line. psync predicts one kind of change, overlapping waits, from traces and the static graph, without running it. |
| WebProphet (Li et al., NSDI 2010) | Predicts how a page’s load time changes when its fetches change, from a dependency graph inferred by perturbing timings. | The closest precursor. psync’s graph comes from the code, not from perturbation, and the change it predicts is an automatic rewrite. |
| Kremlin (PLDI 2011) | Reportedly predicts the speedup of parallelizing regions of C programs. | Not read yet. Until it is, psync does not claim its predictor is new. |
Exercises
- In the
profile_pagetrace,avatartakes 90 ms instead of 60. What doespsync-predictprint for the level, and which line sets it? - A loop of 8 items has a prefix of one request of 40 ms, and a body after it of 5 ms per
item. Predict its time with
bound = 4and withbound = 16. - You trace a run in which
fetch()?fails on its first item and the function returns early. What is wrong with predicting from that trace? - In the cache example, the miss rate rises to 90% (nine misses and one hit, same costs). What is the mean predicted time? Which line is worth making faster first?
Answers
userthenavataris now 40 + 90 = 130 ms, more thanposts(120 ms):level 0: 130, set by n0 (line 3) -> n2 (line 5), and 130 predicted against 330 measured. Speeding uppostsno longer helps at all.- With
bound = 4, the prefixes run in two rounds of four: 80 ms, then the bodies in order, 8 × 5 = 40 ms: 120 ms, against 8 × 45 = 360 ms sequentially. Withbound = 16, all eight prefixes run at once: 40 + 40 = 80 ms. - The trace has the path the run took: one request and an exit, not the loop. The
?also left its statement beforeprofilereported it, so even that request’s time is missing. Trace a run that takes the path you want predicted. - 0.9 × 182 + 0.1 × 122 = 176 ms, against 0.9 × 302 + 0.1 × 242 = 296 ms measured. On the
common path now, the miss’s level (60 ms, line 7) comes after the 120 ms level, so both add
up:
posts(line 4) and the avatar request (line 7) are both on the critical path, and shortening either one helps. Removing the extra level (overlapping the miss withposts) would save the 60 ms outright.
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, so a &mut returned by a method slips through:
pub struct Pool { conn: Conn }
impl Pool {
pub fn conn(&mut self) -> &mut Conn { &mut self.conn }
}
impl Conn {
pub async fn query(&mut self, q: u32) -> u32 { /* .. */ }
}
#[psync::graph]
pub async fn two_queries(pool: &mut Pool) -> u32 {
let conn = pool.conn(); // a `&mut Conn`, but nothing in the tokens says so
let a = conn.query(1).await;
let b = conn.query(2).await;
a + b
}
query is a read verb, so psync takes the two calls for reads of conn, and reads never
conflict:
region 0:
n0: conn = pool . conn ()
n1: a = query() [await] {read `conn` `1` (query)}
n2: b = query() [await] {read `conn` `2` (query)}
n0 -> n1 (reads `conn`)
n0 -> n2 (reads `conn`)
level 0: n0
level 1: n1 || n2
The two queries go into two concurrent chains. Both chains now need conn mutably at once, and
rustc rejects the generated code:
error[E0524]: two closures require unique access to `*conn` at the same time
--> src/lib.rs:10:1
|
10 | #[psync::graph]
| ^^^^^^^^^^^^^^^
| |
| closures are constructed here in different iterations of loop
| first borrow later captured here by closure
...
13 | let a = conn.query(1).await;
| ---- first borrow occurs due to use of `*conn` in coroutine
14 | let b = conn.query(2).await;
| ---- second borrow occurs due to use of `*conn` in coroutine
(The “different iterations of loop” is rustc describing the generated join. There is no loop in
your code. Other shapes give E0499: cannot borrow .. as mutable more than once. Both mean the
same thing.)
That is the intended failure mode: a missed dependency becomes a compile error, not a race. Two fixes:
-
#[psync::seq]on the second query keeps it in place. This always works, and here it is the right fix: the two queries share one connection, so they could not overlap anyway.let a = conn.query(1).await; #[psync::seq] let b = conn.query(2).await; -
#[psync::fresh]onlet conn = ..gives each branch its own connection, by running the initializer once per branch. It works only when the initializer itself can run twice at once. Here it cannot: each branch would callpool.conn(), which borrowspoolmutably, and the error moves topool(two closures require unique access to `*pool`).freshis for initializers likecontext.pool()that hand out a new value from a shared reference, as in Hints.
In the audit, one finding could not be done at all, because it needs &mut self in both branches.
Other attribute macros: #[async_trait], #[instrument], #[tokio::main]
Attribute macros run from the outside in: the attribute written first (highest) sees the
function as you wrote it and rewrites it, then the next one sees that result. So the order
matters, and the rule is short: put #[psync::graph] above every other attribute on the
function, so it reads your code rather than another macro’s output.
#[async_trait]
impl Loader for L1 {
#[psync::graph] // on the method, inside the #[async_trait] impl
async fn load(&self, api: &Api) -> u32 {
let a = api.get_a().await;
let b = api.get_b().await;
a + b
}
}
#[psync::graph] // above #[instrument]
#[tracing::instrument(skip(api))]
async fn traced(api: &Api) -> u32 { /* ... */ }
#[psync::graph] // above #[tokio::main]
#[tokio::main]
async fn main() { /* ... */ }
#[async_trait]goes on the trait and theimpl, which are outside the method, so it runs first. It turnsasync fn loadinto a plainfnreturningPin<Box<dyn Future>>, with your body in anasync moveblock.#[psync::graph]on an ordinaryfnrewrites the async blocks inside it, so it still finds both awaits:loadtakes one 100 ms wait instead of two.#[tracing::instrument]works on either side. Below#[psync::graph], psync sees your body and the report is clean. Above it, psync sees the bodytracinggenerated, and still finds the region, but the report gains abarrier: line 0: the block's valueline for each wrapper statement. Spans psync’s chains run in are those of the function, so events inside a chain are still recorded under the function’s span.#[tokio::main]turnsasync fn maininto a plainfn mainthat blocks on a runtime, so psync must run before it (Comparing builds).
These three were checked on a small crate with async-trait 0.1, tracing 0.1 and tokio 1: each
function took 100 ms with psync, where its two 100 ms waits take 200 ms in sequence.
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:
-
set a process-wide budget once at start-up:
fn main() { psync::set_in_flight_budget(32); // about what the server or the connection pool accepts // ... }Every prefetched loop item beyond the first one of its loop then needs a token from one budget shared by the whole process. The first item of each loop is free, so every loop always makes progress, and nested loops cannot deadlock, even with a budget of 0 (every loop then runs one item at a time). The cap is therefore the budget plus one item per loop running at that moment: with a budget of 3, the 4 × 4 nested loops of
tests/budget.rshold at most 4 requests, where they hold 16 without it. A loop refused a token tries again when one of its own items finishes, and a cancelled loop gives its tokens back.psync::in_flight_beyond_first()reports the tokens in use. The default is unlimited, so nothing changes until you call it. Concurrent statements outside loops are not counted: the code fixes how many there are. -
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.
The budget has not yet been measured on the 32-client DataFusion run; the test shows the cap, not the speedup it buys.
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.
bound does not change this. It limits how many prefixes are in flight, but the generated code
creates every item’s future before the first one starts, and keeps every result until the join
ends. Peak memory grows with the number of items, whatever the bound. For a very long loop over
large results, split the input into batches yourself and loop over the batches, or keep the loop
sequential with #[psync::seq].
Exercises
- Add
#[psync::seq]to the second query intwo_queries. What does the report say, and is the function changed at all? - A command spends 90% of its sequential run in one loop. psync makes that loop 10× faster. What end-to-end speedup does Amdahl’s law predict? What might make the measured speedup smaller?
- An outer loop with
#[psync::graph(bound = 4)]has an inner loop over files that is also prefetched. How many requests can be in flight at once? How would you cap it at 16? - A prefetched loop runs over 100,000 keys with
bound = 8, and each prefix returns about 50 KB. Roughly how much memory do the buffered results take at the peak?
Answers
barrier: line 5: `# [psync :: seq] let b = conn . query (2) . await ;`: marked #[psync::seq], andchangedisfalse. The marked statement is a barrier that splits the block. The region before it holds one await, and the region after it none, so there is nothing to overlap. The output is the function as written, which compiles.- 1 / (0.1 + 0.9 / 10) = 1 / 0.19 ≈ 5.3×. It is less when the work after the waits is CPU-bound: once all the responses arrive at once, parsing them runs on one core (Overlap moves the bottleneck to the CPU). New connections, server limits and memory can cost more too.
- Each loop has its own bound, and the function’s
bound = 4applies to both, so 4 × 4 = 16 are already the cap. With the default of 16 it would be 256. To cap a nested pair at N, give the function a bound of about √N, or leave one loop sequential with#[psync::seq]and give the other the full N. Or callpsync::set_in_flight_budget(15): the outer loop’s first item and each inner loop’s first request are free, and every other request or row takes one of the 15 tokens, so at most 16 requests are in flight. The budget also counts the loops of every other function running at the same time. - About 100,000 × 50 KB = 5 GB.
boundlimits the requests in flight, not the results: every result is kept until the rest of the body runs (Memory). Batch the keys.
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.
MultiExecutorcan bound that (Fairness), and yield injection gives long loops preemption points (Yield injection). - 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, which is not in the repository at the moment. 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.
Many cores: MultiExecutor
With the std feature, MultiExecutor runs Send futures on worker threads that share one ready
queue:
let executor = psync::MultiExecutor::new(4); // four workers
let ui = executor.spawn(20, async { /* latency-sensitive */ });
executor.spawn(1, async { /* batch work */ });
ui.set_priority(30); // moves it in the queue right away
let answer = executor.block_on(5, async { 6 * 7 }); // run and wait for an output
executor.wait_idle(); // until every task has finished
The rules are the single-core executor’s, across threads:
- A worker always takes the ready task with the highest priority. Tasks of equal priority run in the order they became ready.
- Changing the priority of a queued task re-keys it at once, keeping its age among equals.
- A wake that arrives while the task is being polled is never lost. The task goes idle, queued, running, or running-and-notified, and in the last state it is re-queued when the poll returns.
tests/multi.rs checks priority order, live priority changes, fairness, block_on, and that four
100 ms CPU-bound tasks on four workers finish in well under the 400 ms they take one after another.
Fairness
Strict priorities starve. A high-priority task that is always ready keeps every lower one waiting.
MultiExecutor::with_fairness(workers, n) makes every n-th pick take the task that has been
ready the longest, whatever its priority:
| Executor | When a low-priority task runs, next to a busy high-priority task that yields 200 times |
|---|---|
MultiExecutor::new(1) | after all 200 steps |
MultiExecutor::with_fairness(1, 4) | within the first 4 steps |
A ready task then waits at most about n times the number of tasks ahead of it in age order. The
cost is that 1 in n picks may run lower-priority work ahead of higher-priority work.
Yield injection
A cooperative executor cannot interrupt a task that does not await. A long loop of CPU work holds
its worker until it ends, even when a higher-priority task has become ready.
#[psync::graph(yield_every = N)] inserts a preemption point at the start of every loop body in
the async code it rewrites:
#[psync::graph(yield_every = 64)]
async fn index(docs: &[Doc]) -> Index {
let mut index = Index::default();
for doc in docs { // every 64th iteration: psync::yield_now().await
index.add(doc); // CPU work, no awaits
}
index
}
psync::yield_now() returns Pending once and wakes its own task. That works on any executor:
psync’s, tokio’s, or another. The yields change timing only, never results. In
tests/graph.rs, a loop of six steps wakes an urgent task in step 2. With yield_every = 2, the
urgent task runs before step 4 instead of after step 6.
Still open
- Dual-core RP2350.
MultiExecutorusesstdthreads. Running it on the RP2350’s second core needs the HAL’s multicore launch and a spinlock-protected queue, and has to be tested on a board. - Parallel async branches. The code
#[psync::graph]generates for async functions joins its branches in one task. After the I/O overlaps, CPU work in the branches runs on one core (see Patterns and pitfalls). Spawning them onto workers needs'staticfutures or scoped tasks, and the runtime’s spawner. For synchronous functions, Phase II already runs independent statements as jobs on threads (Synchronous code).
Exercises
The answers to 1 and 2 are tests in tests/scheduling.rs (book_*).
- Three tasks, spawned in this order:
aat priority 2,bat 2,cat 7. Each logs its name when polled, wakes itself, and returnsPendingthe first time andReadythe second. What is the log afterrun_until_stalled()? - Three tasks that log once:
aat 1,bat 2,cat 3. Before running the executor, you callset_priority(10)ona’s handle. What is the log? - A task at priority 3 runs an annotated function with two concurrent branches. Another task at priority 5 is ready the whole time. When do the branches run?
- On
MultiExecutor::with_fairness(1, 4), a priority-9 task is always ready, and a priority-1 task becomes ready. Roughly when does it run, and what does that cost?
Answers
c c a b a b.cis the only task at 7, so it runs again as soon as it wakes itself. Thenaandbtake turns: a task that is still pending goes to the back of the queue, behind its equals.a c b. The priority that counts is the one when the task is taken from the queue.- Not while the priority-5 task stays ready. The branches are joined inside the priority-3
task, so they share its priority, and the executor always takes the highest-priority ready
task. They run once the priority-5 task finishes or sleeps (or, on a fair
MultiExecutor, on its fairness picks). To give a branch its own priority, spawn it as a task. - Within about 4 picks: every 4th pick takes the task that has been ready longest. The cost is that the priority-9 task waits during that pick.
Compilers from zero
The rest of this book uses words like token, syntax tree, MIR, dataflow, effect
summary and class-hierarchy analysis. This part teaches them from the beginning. It
assumes you can read and write ordinary Rust, including async fn. It does not assume you
have taken a compilers course or read rustc’s source.
Each chapter introduces one idea, shows it on a small program you can run, and then shows where psync uses it. Each chapter ends with exercises, and their answers are behind a fold. By the end of the part you will be able to read every crate in this repository and know why each one is shaped the way it is.
What a compiler does to your code
A compiler is a chain of translations. Each step takes the program in one form and produces a form that makes the next question easier to answer. Here is the chain rustc runs, and where psync plugs in:
source text "let user = api.user(id).await?;"
│ lexing ── Tokens
▼
tokens let user = api . user ( id ) . await ? ;
│ parsing ── Syntax trees
▼
AST Local { pat: user, init: Try(Await(MethodCall(..))) }
│ macro expansion ◄── #[psync::graph] runs HERE: ── Procedural macros
│ tokens in, tokens out
│ name resolution
▼
HIR desugared: `?` is a match, `.await` is a loop ── Inside rustc
│ type checking
▼
THIR every expression has a type; method calls are resolved
│ building MIR
▼
MIR a control-flow graph of simple statements
│ borrow checking, optimization
│ ◄── psync-driver reads MIR HERE ── Effects and summaries
▼
LLVM IR → machine code
psync works at two points on this chain:
#[psync::graph]is a procedural macro. It runs during macro expansion, early on, before rustc has resolved a single name. It sees tokens: the words and symbols you wrote, with no types and no idea whatapi.userrefers to. That is why it judges a call by its name, and why it is conservative.psync-driver(cargo psync checkandbuild) is rustc itself, with an extra pass that runs after type checking. It reads MIR, where every call is resolved to the exact function it calls. That lets it check the macro’s guesses, and feed facts back to it.
The proofs in verify/ sit off to the side. They are not part of compilation. They show that
the idea behind the schedule is right, whatever the program.
The chapters
| Chapter | You will learn | psync code it explains |
|---|---|---|
| Tokens | what a lexer produces; token trees, spans | what #[psync::graph] receives |
| Syntax trees | parsing; syn; visitors | classify.rs, access.rs |
| Procedural macros | rewriting a tree; quote!; hygiene; errors | psync-macros, rewrite.rs, schedule.rs |
| Inside rustc: HIR, THIR, MIR | desugaring; types; control-flow graphs; how async and ? really compile | what psync-driver reads |
| Dependencies and dataflow | read/write sets; dependence; graphs, chains, levels; fixed points | schedule.rs, loops.rs |
| Effects and summaries | side effects; interprocedural analysis; soundness and precision | effects.rs, analysis.rs |
| Dynamic dispatch and class hierarchies | traits, dyn, monomorphization; closed-world resolution | the link step, facts.rs |
| Proofs | what a proof assistant checks; reading Lean | verify/Schedule.lean |
psync’s vocabulary, in brief
The chapters use a few words from psync itself. Each is defined in full in Basic concepts, and all of them are in the glossary:
- A node is a statement psync may move. A barrier is a statement that stays where it is (a lock, a sleep, the block’s final value). Barriers cut a block into regions, and each region is scheduled on its own.
- An edge
a -> bmeansbmust wait fora. A chain is a run of nodes that each wait only for the one before. A level is a set of chains that run at the same time in one join. - Hints are attributes you put on statements when tokens cannot show what you know:
#[psync::seq](keep this in place),#[psync::fresh],#[psync::independent]and#[psync::speculate](Hints). - Compiler facts are what
cargo psync buildhands the macro: for each call site in an annotated function, the effects the compiler found in the callee’s body, in a file the macro reads (Scheduling with compiler facts).
Running the examples
The examples live in psync-graph/examples/, so cargo test -p psync-graph builds them and
they cannot drift from the code. From the repository root:
cargo run -p psync-graph --example tokens # Tokens
cargo run -p psync-graph --example syntax_tree # Syntax trees
cargo run -p psync-graph --example mini_psync # Procedural macros
cargo run -p psync-graph --example dataflow # Dependencies and dataflow
cargo run -p psync-graph --example summaries # Effects and summaries; Dynamic dispatch
The rustc chapter uses the nightly toolchain that psync-check pins, because only nightly
rustc prints its internal forms:
rustup toolchain install nightly-2026-11-20 --component rustc-dev
rustc +nightly-2026-11-20 --edition 2024 --crate-type lib -Zunpretty=mir sample.rs
The proofs chapter needs Lean 4.22 (elan installs it).
Three ideas to carry through
Three ideas come back in every chapter.
- Each form answers some questions and not others. Tokens cannot tell you a type. MIR has forgotten your variable names in places. A good tool works at the form where its question is easy, and psync works at two forms for that reason.
- When an analysis does not know, it should assume the worst. An analysis of “what may
this code do?” is sound if it never leaves out something that can happen, and precise if it
never includes something that cannot. psync is sound almost everywhere: a file write with an
unknown path may be any file, and a child process may touch anything. Hints and compiler facts
win back the precision this costs. There are exactly two places where psync assumes the
best instead, both deliberate and both reported:
- The macro, on an awaited call it cannot classify by name (
api.user(id)): assumed to only read, so it may overlap other work. The report lists every such call asunclassified,strictturns the assumption off, andcargo psync checkchecks it against the callee’s body. - The driver, on a callee it cannot see through (a function pointer, a
dyntrait of another crate): it marks the summary opaque. With facts, the macro then keeps its own name-based guess as well as the compiler’s effects. The guess is no worse than having no facts, but it is not “assume it writes everything”.
- The macro, on an awaited call it cannot classify by name (
- Facts are checked where they can be. The macro’s guesses are checked by the driver, the generated code is checked by the type and borrow checkers, and the scheduling argument is checked by Lean. What is left unchecked is listed in What is checked, what is assumed.
Tokens
A Rust source file is, to begin with, a string of characters. The first thing any compiler does is cut that string into tokens, the smallest pieces that mean something: a word, a number, a symbol. This step is called lexing, and the part of the compiler that does it is the lexer.
"let user = api.user(id).await?;"
│ lexing
▼
let │ user │ = │ api │ . │ user │ ( │ id │ ) │ . │ await │ ? │ ;
Whitespace and comments are gone. api.user is three tokens, not one. Nothing yet says that
let starts a statement or that user(id) is a call. The lexer only knows which characters
belong together.
Token trees
Rust’s macros do not see a flat list. They see token trees. Every pair of matching brackets,
( ), [ ] or { }, becomes one group, and the tokens between them are the group’s
children. There are four kinds of tree:
| Kind | Examples | Notes |
|---|---|---|
Ident | let, user, await, self | names and keywords alike: the lexer does not tell them apart |
Punct | =, ., ?, ; | one character each; -> is - then >, marked joint |
Literal | 42, "cache.json", 'a', 1.5e3 | the text is kept as written |
Group | ( id ), { .. }, [ .. ] | a delimiter and a nested token stream |
Brackets are grouped already, so a macro can never be handed ( id without its ). Grouping is
the only structure tokens have.
Run the example:
cargo run -p psync-graph --example tokens
let user = api.user(id).await?;
Ident let
Ident user
Punct = (Alone)
Ident api
Punct . (Alone)
Ident user
Group ( … )
Ident id
Punct . (Alone)
Ident await
Punct ? (Joint)
Punct ; (Alone)
The program (psync-graph/examples/tokens.rs) parses a string into a
proc_macro2::TokenStream and walks it with a match on TokenTree. Each Punct records its
spacing. Joint means another punctuation character follows with no space, which is how
+=, :: and -> are represented. Here ? is joint because ; follows it directly.
Spans: where a token came from
Every token carries a span, a reference to the place in the source it came from. Spans are
how the compiler can say error at src/lib.rs:24:20 about code a macro produced. Inside a macro
you can attach your own errors to the tokens that caused them, and they then point at your user’s
code, not at the macro.
psync relies on spans twice:
- When
#[psync::graph]refuses something, its error has the span of the offending statement. - Compiler facts (see Scheduling with compiler facts) are keyed by the file, line and column of a callee’s name. The driver computes the key from MIR spans, and the macro computes the same key from token spans. That match is the only link between the two halves of psync.
proc_macro and proc_macro2
rustc gives procedural macros the type proc_macro::TokenStream. That type only exists while
the compiler is running a macro, so you cannot use it in a test, a binary or an example.
proc_macro2::TokenStream is the same interface, usable anywhere. Real macros convert at the
boundary. Here is psync’s entire macro crate, apart from the hint attributes (which return their input
unchanged):
#[proc_macro_attribute]
pub fn graph(attr: TokenStream, item: TokenStream) -> TokenStream {
psync_graph::expand(attr.into(), item.into()) // proc_macro → proc_macro2
.unwrap_or_else(|e| e.to_compile_error())
.into() // proc_macro2 → proc_macro
}
This is why psync-graph is an ordinary library with ordinary unit tests, and why
psync-expand can run psync’s analysis on a file outside the compiler.
What tokens cannot tell you
Look again at the token stream above and ask three questions:
- What type is
api? Unknown. It is an identifier. The type is declared somewhere else, maybe in another crate. - Which function does
.user(id)call? Unknown. That depends on the type ofapi, on which traits are in scope, and on auto-referencing rules. - Does that call write to a file? Unknown. Even if we knew which function it was, its body is elsewhere.
A procedural macro gets the tokens of the item it is attached to, and nothing else. That is the
fundamental limit of #[psync::graph]. It is why the macro reads names (user sounds like a read,
delete sounds like a write), why it has hints, and why cargo psync exists. The next chapters
climb the pipeline until each of these questions has an answer.
Exercises
- Run
cargo run -p psync-graph --example tokens -- 'x += a::b(&c[0]);'. Before you do, predict the trees. How many groups are there? WhichPuncts areJoint? - Is
'a(a lifetime) one token or two? Try it with-- "fn f<'a>()". - Why can a macro never receive the tokens
foo(bar? What does this guarantee to the writer of a macro? - The keyword
awaitis lexed as anIdent, likeuser. Give one reason this is convenient for the lexer, and one place in psync where the code has to tell them apart.
Answers
- Two groups:
( … )around&c[0], and inside it[ … ]around0.+=is+(Joint) then=(Alone).::is:(Joint) then:(Alone). The otherPuncts (&,;) are Alone. The lexer marks aPunctJoint whenever another punctuation character follows directly, so a?right before;is Joint too, as the output above shows. Spacing records adjacency, not meaning. - Two trees: a
Punct'(Joint) followed by anIdenta. The Joint spacing is what says they belong together, andsynreassembles them into oneLifetime. - The lexer matches brackets before any macro runs, and an unbalanced bracket is an error. A macro can therefore split its input at groups without counting brackets, and it can always copy a group through unchanged.
- Keywords depend on the edition (
asyncandawaitbecame keywords in 2018), and the lexer need not know the edition. psync tells them apart when it looks for awaits.synparsesx.awaitinto anExpr::Awaitnode, andclassify.rsmatches on that node, not on the token.
Syntax trees
Tokens say which characters belong together. They do not say how the pieces relate: that
api.user(id) is a method call whose receiver is api, or that .await applies to the whole
call and ? applies to the awaited result. Working that out is parsing, and its result is a
syntax tree.
tokens: let user = api . user ( id ) . await ? ;
tree: Local (a `let` statement)
├── pattern: user
└── init: Try the `?`
└── Await the `.await`
└── MethodCall .user
├── receiver: Path api
└── args: [Path id]
The tree makes evaluation order visible: inner nodes run first. The call runs, then its future
is awaited, then ? inspects the result. The same tokens could not be read any other way.
Rust’s grammar fixes exactly one tree for every valid program.
rustc’s own syntax tree is called the AST (abstract syntax tree). It is “abstract” because it
drops what only mattered for reading: the parentheses in (a + b) * c become the shape of the
tree, and the commas between arguments disappear.
syn: Rust’s syntax tree as a library
Procedural macros cannot use rustc’s AST, which is internal to the compiler. They use
syn, a parser for Rust that runs on a TokenStream and returns a tree of
ordinary Rust types. The types follow the grammar:
syn type | Is | Examples |
|---|---|---|
File, Item | a whole file; one item in it | fn, struct, impl, use |
ItemFn | a function: attributes, signature, body | async fn f(x: u32) -> u32 { .. } |
Block | { .. }: a list of statements | |
Stmt | one statement | Stmt::Local (a let), Stmt::Expr, Stmt::Item, Stmt::Macro |
Expr | an expression, about 40 variants | Expr::Await, Expr::Try, Expr::MethodCall, Expr::If, Expr::ForLoop |
Pat | a pattern | user, (a, b), Some(x), Page { user, .. } |
A Stmt::Expr carries an Option<Token![;]>. A block’s last expression with no semicolon is the
block’s value. psync cares about that difference. The value expression must stay last, so it is
always a barrier, psync’s word for a statement that never moves.
Run the example:
cargo run -p psync-graph --example syntax_tree
fn profile_page (5 statements, async: true)
s0: Try(Await(MethodCall(.user, receiver: Path(api), args: [Path(user_id)])))
binds {"user"} reads ["api", "user_id"] awaits 1
s1: Try(Await(MethodCall(.posts, receiver: Path(api), args: [Path(user_id)])))
binds {"posts"} reads ["api", "user_id"] awaits 1
s2: Try(Await(MethodCall(.avatar, receiver: Path(api), args: [Ref(Field(Path(user), avatar_url))])))
binds {"avatar"} reads ["api", "user"] awaits 1
s3: Try(Await(MethodCall(.friends, receiver: Path(api), args: [Path(user_id)])))
binds {"friends"} reads ["api", "user_id"] awaits 1
s4: Call(Path(Ok), [Struct(Page)])
binds {} reads ["Ok", "avatar", "friends", "posts", "user"] awaits 0
The program (psync-graph/examples/syntax_tree.rs) does two things. shape is a recursive
match on Expr that prints each node’s variant and children. Access walks each statement
with a visitor and records what it binds, what it reads and how many awaits it contains.
That record is the start of a dependency analysis. s2 reads user, which s0 binds, so s2
must wait for s0. Nothing else depends on anything.
Visitors
A syntax tree for real code has hundreds of node types. Matching all of them by hand to find,
say, every .await would be long and fragile. syn generates a visitor trait instead,
syn::visit::Visit, with one method per node type. Each default method just visits the node’s
children. You override the methods you care about and call the default to keep descending:
impl<'ast> Visit<'ast> for Access {
fn visit_expr_await(&mut self, a: &'ast syn::ExprAwait) {
self.awaits += 1;
visit::visit_expr_await(self, a); // keep walking into the awaited expression
}
fn visit_expr_path(&mut self, p: &'ast syn::ExprPath) {
if let Some(name) = p.path.get_ident() {
self.reads.insert(name.to_string());
}
visit::visit_expr_path(self, p);
}
}
There are three flavours:
Visitborrows the tree, for analyses.VisitMutborrows it mutably, for rewriting in place.Foldtakes it by value and rebuilds it.
psync uses the first two. Rewriter in rewrite.rs is a VisitMut. It overrides
visit_block_mut, first rewrites the inner blocks, and then schedules the statements of the
current one, which is why the book says psync works “innermost first”.
Leaving out the call to the default method is how a visitor stops descending. Rewriter does
that at nested fn items, which need their own attribute. It still walks into closures, but it
only rewrites async ones. The visitor in classify.rs that looks for awaits and exits stops at
closures and async blocks. Their code does not run when the statement that contains them
runs, and a ? inside a closure leaves the closure, not the function.
Two views of the same statement
psync reads each statement twice, in two different ways:
- As a tree (
classify.rs,hoist.rs,loops.rs). Questions about structure need the tree: is this aletor an expression? Is there an.awaitin the scrutinee of thismatch? Is the value of this block anif? Does a?sit inside a closure, where it would leave the closure rather than the function? - As tokens (
access.rs). Questions of the kind “which variables and fields does this touch” are answered by a scan over the statement’s raw tokens. A scan works equally well inside macro calls likeprintln!("{x}")orvec![a, b].syncannot see into those, because a macro’s arguments are just a token stream until the macro is expanded. The scan follows.fieldand[index]after an identifier, which gives access paths likeself.groups, and it treats assignments,&mut, and calls of mutating or order-sensitive methods as writes. The details are in Reads and writes from tokens.
What syntax cannot tell you
Look at s4 in the output: it “reads” Ok. The visitor saw a path with one segment and took it
for a variable. In the tree, Ok (a constructor), user (a local variable) and MAX (a constant)
all look the same: Expr::Path. Telling them apart is name resolution, which happens inside
rustc, after macro expansion. psync’s token scan skips keywords and records every other name as a
possible variable. Here that mistake is harmless: no statement binds Ok, so it never creates an
edge. But a constant and a variable of the same name would be confused, and in general tokens
cannot know.
The same goes for types. user.avatar_url might be a field of a struct, or a field reached by
auto-dereferencing through an Arc. Syntax cannot see the difference. In the next chapter,
psync gets to use a tree. The chapter after that climbs past the point where these questions
get answered.
Exercises
- Which statements must
let n = posts.len() + friends.len();wait for, if it is added before the finalOk(..)? Check your answer by passing a function to the example, as incargo run -p psync-graph --example syntax_tree -- 'async fn f() { let n = posts.len() + friends.len(); }'. Does the reportedreadsagree? synparsesa.b.c()as aMethodCallwhose receiver is aField. Write the shape thatshapewould print, then check it the same way.- Why does a visitor need the
'astlifetime onvisit_expr_path(&mut self, p: &'ast ExprPath)? What could an analysis store if the lifetime were not there? - A closure
|x| x.awaitis not valid Rust, butasync move { x.await }is. Why must psync not count the await insidelet f = async move { x.await };as an await of the enclosing statement? (Hint: when does the body of an async block run?)
Answers
- It reads
postsandfriends, so it waits fors1ands3. The example reportsreads ["friends", "posts"](lenis a method name after a., so it is not a path). MethodCall(.c, receiver: Field(Path(a), b), args: []). Field access and method calls are postfix operators, applied left to right: firsta.b, then.c()on the result. So the field is the receiver.- With
'ast, the visitor can keep references into the tree, for example aVec<&'ast Expr>of every awaited expression, and use them after the walk. Without it, the borrow would end with each call. - An async block does nothing until it is awaited, so the statement only creates a future.
The await runs later, whenever
fis awaited. The await finder inclassify.rsstops atasyncblocks for this reason. The statement therefore has no await of its own. Since it is not on the list of cheap pure expressions either, psync treats it as an ordinary statement, kept in order with the other ordinary statements.
Procedural macros
A procedural macro is a Rust function that the compiler calls while it compiles your code.
It receives tokens and returns tokens, and the compiler parses what it returns in place of what
you wrote. #[psync::graph] is an attribute macro, the kind that attaches to an item:
#[proc_macro_attribute]
pub fn graph(attr: TokenStream, item: TokenStream) -> TokenStream
// ^^^^ the tokens inside #[psync::graph(...)]
// ^^^^ the whole `async fn` it is attached to
That is the entire interface. The macro cannot ask the compiler anything: what a name means, what type an expression has, or what another function does. It sees the tokens of one item, and it must decide from them what to emit.
Almost every macro has the same three steps:
tokens ──parse──► syntax tree ──analyse + transform──► syntax tree ──quote──► tokens
syn::parse2 quote!
quote!: writing code that writes code
The quote crate turns Rust-like text back into tokens. #name
interpolates a variable that holds tokens (an Ident, an Expr, a TokenStream, anything that
implements ToTokens). #(#items),* repeats once for each element of an iterator, with a comma
between:
let names = [user, posts, friends]; // Idents
let futures = [f_user, f_posts, f_friends]; // Exprs
let stmt = quote! {
let (#(#names),*) = ::futures::join!(#(#futures),*);
};
// let (user, posts, friends) = ::futures::join!(api.user(user_id), api.posts(user_id), ...);
Generated code always names paths in full, as ::futures::join! or ::core::option::Option.
The user’s crate might have its own Option in scope. The toy below uses ::futures::join! for
brevity, which would require the user to depend on futures. psync’s real generated code calls
only ::core and its own runtime, through the path #krate::__private. The
user can change krate with #[psync::graph(crate = path)] when they re-export psync.
psync in a hundred lines
psync-graph/examples/mini_psync.rs is a working toy version of #[psync::graph]. Its function
mini_graph(item: TokenStream) -> syn::Result<TokenStream> has the signature of an attribute
macro, and it is called on a token stream built with quote!. It accepts one shape only: a
block of let name = <future>.await; statements, then a final value.
cargo run -p psync-graph --example mini_psync
analysis:
edge s0 -> s2 (reads `user`)
level 0: user || posts || friends
level 1: avatar
generated:
async fn profile_page(api: &Api, user_id: u64) -> Page {
const __MINI_GRAPH: () = ();
let (user, posts, friends) = ::futures::join!(
api.user(user_id), api.posts(user_id), api.friends(user_id)
);
let avatar = api.avatar(&user.avatar_url).await;
Page {
user,
posts,
avatar,
friends,
}
}
refused: mini_graph: the value must be `<future>.await` (no `?`)
Read the source next to this chapter. The three steps are marked in it:
- Analysis. For each statement, keep the bound name, the future (the expression under
.await), and every one-segment path the future mentions (its reads). - The graph. Draw an edge
j → iwhen statementireads the name statementjbinds. Put each statement on a level one past the deepest level it reads from. - Code generation. Emit one statement per level: the original
letif the level has one future, and ajoin!of all of them if it has more.
The output is correct for this input. It is also already worse than psync. avatar waits for
posts and friends as well, because they share a level. psync would run user → avatar as a
chain alongside the other two. Dependencies and dataflow explains chains.
Refusing is a feature
When mini_graph meets something it does not understand, it returns a syn::Error built with
new_spanned(tokens, message). A real macro turns that into code with to_compile_error(), which
expands to compile_error!("...") carrying the span of those tokens. The user then sees an
ordinary compiler error pointing at their own statement.
psync rarely refuses. When it cannot rewrite a statement, it leaves the statement alone. A
statement psync cannot move becomes a barrier, and a region with nothing to overlap is
emitted exactly as written. Its worst case is your original code. The toy refuses ? because
handling it correctly is subtle. The exercise at the end of this chapter shows why.
Hygiene and generated names
If a macro introduces a variable tmp, and the user’s code also has a tmp, which one does
tmp refer to? A hygienic macro system keeps them apart automatically. Rust’s
macro_rules! is partly hygienic for local variables. Procedural macros choose per token, via
spans:
Span::call_site(): the token behaves as if the user had written it. It can see the user’s variables, and they can see it.Span::mixed_site(): local variables are private to the macro, likemacro_rules!.
psync needs call-site behaviour. The code it moves into chains must still refer to the user’s
api and user_id. So psync prefixes everything it invents with __psync_
(__psync_f0, __psync_e0_1_0, '__psync_chain0) and counts names up within the function so
they never collide.
What psync actually generates
psync-expand FILE LINE runs the real analysis on the function containing LINE and prints the
graph and the generated code as JSON. Here it is on the introduction’s example, with ? this
time:
cargo run -p psync-graph --features cli --bin psync-expand -- page.rs 2
Shortened, and with the paths trimmed, this is the code that comes out:
async fn profile_page(api: &Api, user_id: u64) -> Result<Page, Error> {
const __PSYNC_GRAPH: Option<&str> = option_env!("PSYNC_FACTS_STAMP");
let (__psync_taken0, __psync_taken1, __psync_taken2) = {
// Chain 0: user -> avatar. Join 1 of this function, statements 0 to 2, may exit at 0.
let mut __psync_f0 = __private::maybe_done_at::<1, 0, 2, true, 0, false, false, _>(async {
let mut __psync_e0_0_0 = None; // where `user`'s `?` is recorded
let mut __psync_e0_1_0 = None; // where `avatar`'s `?` is recorded
let __psync_out = '__psync_chain0: {
let user = match Branch::branch(api.user(user_id).await) {
Ok(v) => v,
Err(r) => {
__psync_e0_0_0 = Some(r); // record the exit...
break '__psync_chain0 None; // ...and stop this chain only
}
};
let avatar = /* the same, into __psync_e0_1_0 */;
Some((user, avatar))
};
(__psync_e0_0_0, __psync_e0_1_0, __psync_out)
});
let mut __psync_f1 = /* chain 1: posts, starts at statement 1 */;
let mut __psync_f2 = /* chain 2: friends, starts at statement 3 */;
// Poll every chain until all are done: the join.
poll_fn(|cx| {
let d0 = __psync_f0.poll_step(cx);
let d1 = __psync_f1.poll_step(cx);
let d2 = __psync_f2.poll_step(cx);
if d0 && d1 && d2 { Poll::Ready(()) } else { Poll::Pending }
}).await;
(__psync_f0.take(), __psync_f1.take(), __psync_f2.take())
};
// Each chain returned (its exit slots..., Some(bindings) or None): unpack them.
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;
// Replay the exits in PROGRAM order:
if let Some(r) = __psync_e0_0_0 { Rethrow::rethrow(r)?; } // user (statement 0)
if let Some(r) = __psync_e1_0_0 { Rethrow::rethrow(r)?; } // posts (statement 1)
if let Some(r) = __psync_e0_1_0 { Rethrow::rethrow(r)?; } // avatar (statement 2)
if let Some(r) = __psync_e2_0_0 { Rethrow::rethrow(r)?; } // friends (statement 3)
let (user, avatar) = __psync_out0.unwrap();
let (posts,) = __psync_out1.unwrap();
let (friends,) = __psync_out2.unwrap();
Ok(Page { user, posts, avatar, friends })
}
The runtime pieces are small. maybe_done_at(future) boxes a chain’s future. poll_step(cx)
polls it if it is still running and returns true once it has finished. take() hands out its
output. Every part of this has a chapter in How psync works. Three
things matter here:
- Exits are data until the end. A
?inside a chain does not leave the function. It stores the error in a slot and ends only its own chain. After the join, the slots are checked in the order the statements were written, so the function fails at the same?, with the same error, as the sequential code would. This is whatexits.rsdoes. - The macro leaves notes for the compiler.
maybe_done_at::<1, 0, 2, true, 0, false, false, _>does nothing at run time beyondmaybe_done. Its const generic arguments record which join of the function the chain belongs to (they are numbered from 1), its first and last statements, whether it may exit and at which statement first, and thespeculateandindependenthints. Generic arguments survive all the way into MIR, sopsync-drivercan read back exactly what the macro assumed, and check it. The constant__PSYNC_GRAPHmarks the function as rewritten. Its value,option_env!("PSYNC_FACTS_STAMP"), makes cargo rebuild the crate when the compiler facts change. - rustc checks the result. Everything above is ordinary Rust. If psync had moved two uses of
one
&mutinto concurrent chains, this code would fail the borrow checker, so the mistake would show up as a compile error, never as a data race.
Debugging a macro
psync-expandshows psync’s output for any function, annotated or not.#[psync::graph(explain)]prints the graph while your crate compiles.cargo expand(a separate tool) prints any crate after all macros have run.- In tests, call the library directly.
psync-graph’s unit tests calltransform_fnon functions built withsyn::parse_quote!and assert on the report.
Exercises
mini_psyncignores shadowing: a statement’s level depends only on what it reads. Is that correct? Consider a statement 3 that islet user = ..again.- Why does
mini_graphrefuse?? Suppose it emitted, for each level, the join and then the?s of that level in program order. Find a program where this returns a different error from the sequential code. (Hint: use three statements, where the second depends on the first and the third depends on nothing.) - In the real output, why is
avatar’s exit replayed betweenposts’s andfriends’s, whenavatarbelongs to chain 0? - Why does generated code write
::core::option::Option::Noneinstead ofNone?
Answers
- It is not correct to ignore shadowing. If statement 3 rebinds
user, then the finalPage { user, .. }must see statement 3’s value. With both at level 0, the tuple patternlet (user, .., user) = ..would not even compile. psync adds a “rebinds” edge (both bind the name) and a “shadows” edge (a later statement rebinds a name an earlier one still reads). - Take
let a = f().await?; let b = g(a).await?; let c = h().await?;. Levels:aandcat 0,bat 1. Supposeasucceeds,bfails andcfails. Sequentially,b’s error is returned andhnever runs. The toy would runa || c, replay level 0’s exits, and returnc’s error, which is wrong. Exits must be replayed in program order across all the work that ran. psync achieves this by ending only the failing chain and replaying all exits after the join, and by keeping a write from starting before an earlier exit. - Replay follows statement order, not chain order:
user(0),posts(1),avatar(2),friends(3). Ifpostsandavatarboth fail, sequential code returnsposts’s error first. - The user may have shadowed
NoneorOption: a local enum, anuseof something else, or a#![no_implicit_prelude]crate. A full path from the crate root::corecannot be shadowed.
Inside rustc: HIR, THIR, MIR
A procedural macro sees tokens and syntax. After macro expansion, rustc turns your program into
three more forms. Each is simpler to analyse than the one before, and each knows more. This
chapter shows all three on two small functions, using rustc’s own printouts, and ends with how
psync-driver reads the last one.
To print these forms yourself you need a nightly compiler. The -Z flags are unstable. The
outputs below come from the toolchain psync-check pins:
rustc +nightly-2026-11-20 --edition 2024 --crate-type lib -Zunpretty=hir sample.rs
rustc +nightly-2026-11-20 --edition 2024 --crate-type lib -Zunpretty=thir-tree sample.rs
rustc +nightly-2026-11-20 --edition 2024 --crate-type lib -Zunpretty=mir sample.rs
Here is sample.rs:
use std::fs;
pub fn save(data: &str) -> std::io::Result<()> {
let text = data.to_uppercase();
fs::write("cache.json", text)?;
Ok(())
}
Between the AST and the HIR: expansion and resolution
After parsing, rustc first expands macros. It repeatedly finds a macro call or attribute,
runs it, and parses what it returns, until none are left. #[psync::graph] runs at this
point, as do #[derive], println! and #[tokio::main].
Then it resolves names. Every path is looked up, and fs::write becomes “the function
write in module fs of crate std”. Ok becomes “variant Ok of enum Result”, and text
becomes “the local variable bound on line 4”. This is the step that answers the question the
syntax-trees chapter could not: which name is a variable and which is a constructor.
HIR: the desugared program
The HIR (high-level intermediate representation) is the program after expansion and
resolution, desugared. Several pieces of Rust syntax are only shorthand for other syntax,
and the HIR writes the longhand. Here is save in HIR:
fn save(data: &'_ str) -> std::io::Result<()> {
let text = data.to_uppercase();
match branch(fs::write("cache.json", text)) {
Break { 0: residual } => return from_residual(residual),
Continue { 0: val } => val,
};
Ok(())
}
The ? is gone. In its place is a match on Try::branch, which returns
ControlFlow::Break(residual) for an error and ControlFlow::Continue(value) for a success. A
Break returns from the function, after converting the error with FromResidual. That is
exactly what ? means, and psync’s generated code uses the same two traits through its own
Branch and Rethrow wrappers.
async and .await desugar too:
pub async fn load() -> String {
std::fs::read_to_string("cache.json").unwrap()
}
pub async fn page() -> usize {
let a = load().await;
a.len()
}
async fn page() -> /*impl Trait*/ |mut _task_context: ResumeTy| {
let a = match into_future(load()) {
mut __awaitee => loop {
match unsafe { poll(new_unchecked(&mut __awaitee), get_context(_task_context)) } {
Ready { 0: result } => break result,
Pending {} => { }
}
_task_context = (yield ());
},
};
a.len()
}
Three names in it are compiler plumbing. _task_context holds the executor’s Context (the
waker) for the current poll, and ResumeTy is its type as the coroutine sees it. new_unchecked
pins the inner future in place, which is safe here because the coroutine itself is pinned. Then
the most useful thing in the chapter for understanding async Rust:
- An
async fnis a function that returns a coroutine, a closure-like value that can stop in the middle and be resumed later. Callingpage()runs none of its body. .awaitis a loop. It polls the inner future. If the future is ready, the loop breaks with its value. If not, it yields: the coroutine stops and returnsPendingto whoever polled it, normally an executor. When the executor polls again, execution resumes right after theyield, with a new task context.
So “sequential awaits” are literally sequential. The second loop cannot start until the first
breaks. psync’s join does what this loop does, but for several futures at once: it polls each
chain in turn and yields only when all of them are pending.
THIR: every expression typed
Next, type checking runs on the HIR. It infers the type of every expression, resolves each method call to the function it calls, and inserts the implicit operations you never write: auto-referencing, auto-dereferencing, and coercions. The THIR (typed HIR) writes all of that down. It is built one function body at a time, used to check patterns and to build MIR, and then thrown away.
Here is the THIR for data.to_uppercase(), much shortened (the real printout of this
seven-line function is 563 lines):
Call {
ty: FnDef(alloc::str::{impl#5}::to_uppercase)
fn_span: sample.rs:4:21: 4:35
args: [
Expr {
ty: &str
kind: Borrow (
borrow_kind: Shared
arg: Expr {
ty: str
kind: Deref { Expr { ty: &str, kind: VarRef { id: LocalVarId(..) } } }
}
)
}
]
}
Three things are new:
- Every node has a
ty. - The method is resolved.
.to_uppercase()is a call of one specific function, the methodto_uppercasein one particularimpl strblock ofalloc(rustc numbers a module’s impl blocks from 0, and{impl#5}is the one numbered 5). The receiver has become the first argument. - Nothing is implicit.
datawas auto-dereferenced (Deref) and borrowed again (Borrow) to make the&selfargument. In the source these steps were invisible.
This is the information the macro lacks. If api.user(id) is a method of a trait
implemented for Arc<Client>, the THIR says so.
MIR: a control-flow graph
The MIR (mid-level IR) is what the borrow checker, the optimizer and psync’s driver work on. It has no nested expressions at all. Each function is a control-flow graph (CFG):
- Basic blocks (
bb0,bb1, …) are runs of simple statements with one entry and one exit. - Each block ends in a terminator that says where control goes next:
goto,switchInt(a branch on an integer),return,Call(a call, then continue in a named block),drop, orassert. - Locals (
_0,_1, …) hold every value._0is the return value,_1..are the arguments, and the rest are variables and temporaries.debug text => _2records which local was calledtextin the source.
Here is save in MIR, complete:
fn save(_1: &str) -> Result<(), std::io::Error> {
debug data => _1;
let mut _0: std::result::Result<(), std::io::Error>;
let _2: std::string::String;
let mut _3: std::ops::ControlFlow<std::result::Result<!, std::io::Error>>;
let mut _4: std::result::Result<(), std::io::Error>;
let mut _5: isize;
scope 1 {
debug text => _2;
let _6: std::result::Result<!, std::io::Error>;
scope 2 {
debug residual => _6;
}
scope 3 {
debug val => const ();
}
}
bb0: {
_2 = str::<impl str>::to_uppercase(copy _1) -> [return: bb1, unwind continue];
}
bb1: {
_4 = std::fs::write::<&str, String>(const "cache.json", copy _2) -> [return: bb2, unwind continue];
}
bb2: {
_3 = <Result<(), std::io::Error> as Try>::branch(move _4) -> [return: bb3, unwind continue];
}
bb3: {
_5 = discriminant(_3);
switchInt(move _5) -> [0: bb5, 1: bb6, otherwise: bb4];
}
bb4: {
unreachable;
}
bb5: {
_0 = Result::<(), std::io::Error>::Ok(const ());
goto -> bb7;
}
bb6: {
_6 = move ((_3 as Break).0: std::result::Result<!, std::io::Error>);
_0 = <Result<(), std::io::Error> as FromResidual<Result<!, std::io::Error>>>::from_residual(copy _6) -> [return: bb7, unwind continue];
}
bb7: {
return;
}
}
Read it as a flowchart. bb0 calls to_uppercase and continues in bb1, which calls
fs::write. bb2 calls branch (the ?), and bb3 switches on the result’s variant. bb5 is the
Continue path, which builds Ok(()). bb6 is the Break path, which converts the error. Both
reach bb7, which returns _0. unwind continue says what happens if the call panics: the
panic continues to unwind into the caller.
Some vocabulary:
- A place is a location that can be read or written: a local (
_3), or a local with projections, such as a field (.0), a downcast to a variant (as Break), a dereference (*_1), or an index ([_8]).((_3 as Break).0)is “field 0 of_3viewed asBreak”. - An operand is how a value is passed:
copya place,moveit, or aconst. (copy _2for aStringlooks wrong. It appears because this printout is after some optimizations, which may replace amovefrom a local that is never used again with acopy.) - A constant such as
"cache.json"is stored in an allocation, printed at the end of the dump (alloc1 (size: 10, align: 1) { 63 61 63 68 .. │ cache.json }).
Every call is a Call terminator with its callee resolved to a path and generic arguments:
std::fs::write::<&str, String>. To find out what a function does to the outside world, you
visit its basic blocks and look at the calls. That is all psync’s driver does.
Loops are cycles
Here is a while loop, for contrast:
pub fn sum(v: &[u32]) -> u32 {
let mut s = 0;
let mut i = 0;
while i < v.len() { s += v[i]; i += 1; }
s
}
bb0: { _2 = const 0_u32; _3 = const 0_usize; goto -> bb1; }
bb1: { _5 = copy _3; _6 = PtrMetadata(copy _1); _4 = Lt(move _5, move _6);
switchInt(move _4) -> [0: bb6, otherwise: bb2]; }
bb2: { ... assert(move _10, "index out of bounds: ...") -> [success: bb3, ...]; }
bb3: { _7 = copy (*_1)[_8]; _11 = AddWithOverflow(copy _2, copy _7);
assert(!move (_11.1: bool), "attempt to compute `{} + {}`, which would overflow", ..) -> ...; }
bb4: { _2 = move (_11.0: u32); _12 = AddWithOverflow(copy _3, const 1_usize); ... }
bb5: { _3 = move (_12.0: usize); goto -> bb1; }
bb6: { _0 = copy _2; return; }
(Blocks are joined onto fewer lines here.) bb5 jumps back to bb1. That back edge makes
the graph cyclic, and the loop is that cycle. The bounds check on v[i] and the overflow
check on += are explicit assert terminators, each a possible panic. Analyses over a cyclic
graph need the fixed-point method of the next chapter.
async fn in MIR
The MIR of load shows the coroutine. The function itself only builds it:
fn load() -> {async fn body of load()} {
let mut _0: {async fn body of load()};
bb0: { _0 = {coroutine@asyncs.rs:1:31: 3:2 (#0)}; return; }
}
The body is a separate MIR function, load::{closure#0}. It takes the pinned coroutine and a
Context, and returns Poll<String>. Its blocks contain the actual calls:
fn load::{closure#0}(_1: Pin<&mut {async fn body of load()}>, _2: &mut Context<'_>) -> Poll<String> {
...
_3 = std::fs::read_to_string::<&str>(const "cache.json") -> [return: bb1, unwind: bb3];
...
_4 = Result::<String, std::io::Error>::unwrap(move _3) -> [return: bb2, unwind: bb3];
In page::{closure#0}, the load() future that is alive across the .await is stored as a
field of the coroutine (field _s0). The states the coroutine can be suspended in are its
variants (variant#3). This is the state machine that async compiles to.
For psync this has a practical consequence. To summarize an async fn, the driver must look
inside the coroutine it builds. In MIR, building a closure or coroutine is the statement
_0 = {coroutine@..}, an Rvalue::Aggregate of kind Coroutine(def_id, ..). The driver
follows that def_id (the coroutine’s name inside the compiler, explained in the next section)
into the body.
How psync-driver reads MIR
rustc is organized around queries. Instead of running passes in a fixed order, it asks a
central context, TyCtxt (usually named tcx), for what it needs: tcx.type_of(def_id),
tcx.optimized_mir(def_id). Each query computes its answer on first use and caches it. A
DefId names any definition: a function, closure, trait, impl or constant. It is a pair of a
crate number and an index within that crate. A DefPathHash is a hash of the definition’s
full path that stays the same between compilations, which is why psync uses it as the key in
summary files.
A custom driver is rustc with callbacks. psync-driver.rs implements
rustc_driver::Callbacks::after_analysis. That method runs once type and borrow checking
have succeeded, and it receives tcx. Cargo runs the driver in place of rustc for every crate,
because cargo psync sets it as RUSTC_WRAPPER.
The core loop of Analyzer::summarize in psync-check/src/driver/analysis.rs is the MIR you
just read, as code:
let body = tcx.optimized_mir(def_id);
for data in body.basic_blocks.iter() {
for stmt in &data.statements {
// `_0 = {coroutine@..}` or `{closure@..}`: summarize the nested body too.
if let StatementKind::Assign(assign) = &stmt.kind
&& let Rvalue::Aggregate(kind, _) = &assign.1
&& let AggregateKind::Closure(nested, _)
| AggregateKind::Coroutine(nested, _)
| AggregateKind::CoroutineClosure(nested, _) = **kind
{
let inner = self.summarize(nested);
summary.absorb(&inner, stmt.source_info.span, None);
}
}
// `_4 = std::fs::write::<&str, String>(const "cache.json", ..) -> ..`
if let TerminatorKind::Call { func, args, .. } = &data.terminator().kind {
match func.const_fn_def() {
Some((callee, generic_args)) => self.call(&mut summary, .., callee, generic_args, &args, span),
None => summary.opaque.push("call through a function pointer".into()),
}
}
}
func.const_fn_def()gives the callee’sDefIdand generic arguments when the call is direct. Iffuncis a local holding a function pointer, there is nothing to resolve statically, and the summary is marked opaque.self.call(..)decides what the call does. Calls intostdor tokio are recognized by path:std::fs::writewrites a file. If the first argument is a string constant, asconst "cache.json"is, that constant is the target. Calls to the user’s own functions are followed into their bodies. The effects chapter covers the rules.- Each
Span(stmt.source_info.span, the terminator’sfn_span) points back at the source text.span.from_expansion()tells whether a span came from a macro, which is how the driver separates the user’s calls from the code psync generated around them.
How these summaries are stored, named across crates and linked over the whole build is the subject of From MIR to summaries across crates.
Which form, for which question
| Question | Earliest form that answers it |
|---|---|
| Which statements bind which names? Where are the awaits? | syntax tree (macro) |
Is Ok a variable? Which fs is meant? | HIR (after resolution) |
What type is api? Which function does .user(id) call? | THIR (after type checking) |
| What does that function do, through every callee? | MIR of the whole build (driver) |
Do two &mut uses overlap? | MIR (the borrow checker) |
psync’s macro answers the first row and guesses the rest. The driver answers rows three and four exactly, and the borrow checker answers row five on the code psync generated.
Exercises
- Print the HIR of a
for x in v { .. }loop. What does it desugar to? Which method is called on each iteration? - In
save’s MIR, which basic blocks run whenfs::writereturnsOk? When it returnsErr? - In
sum’s MIR, list every terminator that can panic. Which source expression causes each? - Why does the driver look at
stmt.source_info.spanfor closures, but at the call’sfn_spanwhen it builds facts for the macro? (Hint: what span does the macro compute for a call?) - Run
-Zunpretty=miron anasync fnwith two.awaits. How many variants does the coroutine have, and what does each one represent?
Answers
-
match IntoIterator::into_iter(v) { mut iter => loop { match Iterator::next(&mut iter) { None => break, Some { 0: x } => { .. } } } }. On each iteration,Iterator::nextis called. psync’s loop rewriting replaces this iteration with its own runtime helper (over_at, see Loop rewriting), which keeps a bounded number of items’ awaited prefixes in flight. -
Ok:bb0 → bb1 → bb2 → bb3 → bb5 → bb7.Err:bb0 → bb1 → bb2 → bb3 → bb6 → bb7. (bb4is unreachable: aControlFlowhas only two variants.) -
The
assertinbb2(the bounds check ofv[i]), theassertinbb3(overflow ofs += v[i]) and theassertinbb4(overflow ofi += 1). In a release build the overflow checks disappear. Note that the driver counts only explicit panics in the user’s code (unwrap,expect,panic!) as exits. Bounds and overflow checks are everywhere, and counting them would make every statement an exit. -
A fact is keyed by where the callee starts in the source, which the macro can compute from its tokens. For a method call
x.foo(a),fn_spancoversfoo(a), and the macro uses the span of the method namefoo. The terminator’s own span covers the whole expression and would start at the receiverx, a position the macro would not use. For a path callfs::write(..)the two spans start at the same place, atfs, which is also where the macro starts (the span of the pathc.func). -
Every coroutine has three reserved states: unresumed (created, not yet polled), returned and panicked. On top of those it has one suspended state per
.await, which holds the locals alive across that await. Two awaits give 5 variants. Forlet a = one().await; let b = one().await; a + brustc prints the layout:Unresumed(0): [], Returned (1): [], Panicked (2): [], Suspend0 (3): [_s1], the first `one()` future Suspend1 (4): [_s0, _s2], `a`, and the second `one()` futureamust be stored in the coroutine because it is alive across the second await.
Dependencies and dataflow
psync’s whole job is to answer one question: which statements may run at the same time? The compiler-science answer has two parts. Dependence analysis decides which pairs of statements must keep their order. Scheduling turns the remaining freedom into concurrency. This chapter builds both from scratch. It ends with dataflow analysis, the general method compilers use for questions about programs with loops.
Reads, writes and three kinds of dependence
Describe each statement by what it writes (binds or mutates) and what it reads. Two
statements a (earlier) and b (later) must keep their order if one of these holds:
| Name | Pattern | Example | Why order matters |
|---|---|---|---|
| true dependence (read after write) | b reads what a writes | let u = f(); g(u); | b needs a’s value |
| anti-dependence (write after read) | b writes what a reads | g(x); x = 5; | a must see the old value |
| output dependence (write after write) | both write it | x = 1; x = 2; | the final value must be b’s |
If none holds, the two statements commute: running them in either order, or interleaved,
gives the same result. That fact is the first theorem in verify/Schedule.lean. Two statements
that only read the same thing have no dependence at all. Reads never conflict with reads.
psync’s depends function (psync-graph/src/schedule.rs) asks these questions in a fixed order
and reports the first that applies:
| Reason psync prints | Kind |
|---|---|
reads `x` | true dependence on a binding |
rebinds `x` | output dependence: both bind x |
shadows `x` | anti-dependence: b rebinds a name a reads |
writes `p` | a true, anti or output dependence on a place such as self.groups |
effect order | two ordinary statements with possible side effects (out.push(x), total += n), which psync never reorders relative to each other |
effect conflicts, may exit before | effects on files and services, and exits, the next chapter |
Places are compared by prefix. A write to self.groups overlaps a read of self or of
self.groups.len, but not of self.client. That keeps the analysis useful for methods on
self, where nearly everything starts with the same root.
From edges to a schedule
Draw a dependence graph: one node per statement, and an edge a → b for each dependence.
Edges always point forward in program order, so the graph has no cycles. It is a DAG
(directed acyclic graph). Any order of the nodes that respects every edge is a topological
order, and running the program in any topological order gives the same result.
Concurrency comes from nodes with no path between them. psync groups them in two steps.
- Chains. If
u → vis the only edge intovand the only edge out ofu, nothing else can happen between them that matters. Fuse them into one chain and run it as one task. (psync also fuses whenudoes not await and everything else that waits foruwaits forvtoo, as withlet key = ..;feeding a request; see Scheduling.) - Levels. A chain’s level is one past the deepest chain it waits for. All chains of a level run concurrently. The next level starts when they are all done. (One refinement for early exits, in Early exits: a chain whose exit must wait for an earlier statement in a later level hands its results on only after that level.)
The example runs this on the function hoisted from Basic concepts,
after psync has moved its two awaits into their own bindings (h2, s3). It runs it on the
chains test too:
cargo run -p psync-graph --example dataflow
Part A: the dependency graph of `hoisted`
n0: let mut lens = Vec::new();
n1: let h2 = api.len(&names[0]).await; [await]
n2: lens.push(h2);
n3: let s3 = api.kind(&names[1]).await; [await]
n4: match s3 { .. => lens.push(..) }
n0 -> n2 (reads `lens`)
n1 -> n2 (reads `h2`)
n0 -> n4 (reads `lens`)
n2 -> n4 (writes `lens`)
n3 -> n4 (reads `s3`)
chain 0: n0
chain 1: n1
chain 2: n2
chain 3: n3
chain 4: n4
level 0: n0 || n1 || n3
level 1: n2
level 2: n4
Part A: the dependency graph of `chains`
n0 -> n2 (reads `a1`)
n1 -> n3 (reads `a2`)
chain 0: n0 -> n2
chain 1: n1 -> n3
level 0: n0->n2 || n1->n3
For hoisted, every chain is a single node, and the graph and schedule are the ones psync itself
prints for that function. The two requests,
n1 and n3, start together. The two pushes keep their order because of the edge
n2 → n4 (writes lens).
Why chains, not just levels
Levels alone wait for the slowest member of the level. With a1 → b1 and a2 → b2, where
a1 takes 1 unit, a2 2, b1 2 and b2 1:
levels only: a1 ─┐ ┌─ b1 ──┐
a2 ─┴──────────┴─ b2 ──┴──► 2 + 2 = 4 units
chains: a1 ── b1 ──────┐
a2 ──── b2 ────┴──► max(1+2, 2+1) = 3 units
The length of the longest path through the DAG, weighted by time, is the critical path. No
schedule can beat it. Chains get much closer to it than levels do, and the chains test in
tests/graph.rs checks the 3-unit time. psync does not know how long anything takes, so it
cannot always find the best schedule. Chains are a cheap rule that never makes things worse.
Loops: dependences across iterations
Inside a loop body, the same analysis applies per iteration. The new question is whether
iteration k+1 depends on iteration k. That is a loop-carried dependence:
for key in keys {
let meta = store.head(key).await?; // reads only per-iteration data
total += meta.size; // writes `total`, which outlives the iteration
}
total is carried: each iteration reads what the previous one wrote. But the awaited prefix,
store.head(key), reads only key and store. It does not depend on any earlier iteration.
So psync runs the prefixes of up to bound iterations ahead (an option of the attribute,
16 by default), and then runs the rest of each body
(total += ..) in order. This is software pipelining. When the carried state is in the
middle of the body, psync first splits the loop into two loops, which is loop fission. Both
are described in Loop rewriting.
Dataflow analysis: questions about programs with cycles
A region’s dependence graph (one block’s run of movable statements between barriers) is acyclic, so one pass in program order computes every level. The control-flow graphs of the previous chapter have cycles wherever there is a loop, and many questions about them cannot be answered in one pass. Dataflow analysis is the general method for those questions.
The classic example is liveness. A variable is live at a point if its current value may
still be read later. The borrow checker uses liveness, and so does register allocation. For
each block, with uses the variables it reads before writing and defs those it writes:
live_out(b) = ∪ live_in(s) for every successor s of b
live_in(b) = uses(b) ∪ (live_out(b) − defs(b))
In a loop, live_in(bb1) depends on live_in(bb2), which depends on live_in(bb1). A circular
definition is solved by iterating to a fixed point. Start with every set empty, apply the
equations to every block, and repeat until nothing changes:
Part B: liveness, visiting blocks backward, fixed point after 2 rounds
bb0: i = 0; s = 0 live on entry: {"v"}
bb1: if i < v.len() live on entry: {"i", "s", "v"}
bb2: s += v[i]; i += 1 live on entry: {"i", "s", "v"}
bb3: return s live on entry: {"s"}
Why does this terminate, and why is the answer right?
- Monotone. Each equation can only grow a set when its inputs grow. The sets start empty, so they only ever grow.
- Finite. There are finitely many variables, so a set can grow only finitely often.
- Least. Starting from empty and growing only as forced gives the smallest solution of the equations, the least fixed point. Any variable in it really can be read later along some path.
That reasoning, with sets replaced by any lattice (a set of facts ordered by “knows more”),
is the general theory, and rustc’s rustc_mir_dataflow crate implements it for MIR. You will
meet it again in the next chapter. Effect summaries of recursive functions are a
fixed point over the call graph, in the same way.
Flow-sensitive and flow-insensitive
Liveness is flow-sensitive: the answer differs from point to point in the function. Many analyses do not need that. psync’s driver summarizes a function by taking the union of the effects of every call in every basic block, ignoring which blocks are reachable from which. That is flow-insensitive. It is simpler and faster. It is also sound for psync’s purpose (“what might this function do?”), at the cost of counting effects on paths that never run together.
Exercises
- In
psync-graph/examples/dataflow.rs, add a statementlet n = h2 + 1;tohoisted, betweenn2andn3. Each statement is anOplisting what it binds (defs), reads (uses) and mutates (writes), so this one isOp { text: "let n = h2 + 1;", defs: set(&["n"]), uses: set(&["h2"]), writes: set(&[]), awaits: false }. Which edges appear? Which chains? Does the number of levels change? - Two statements
x.push(1);andx.push(2);on alet mut x = Vec::new(). Which kind of dependence is this? What would go wrong if psync ran them concurrently? (There are two answers: one from the borrow checker, one about the result.) - In the liveness example, why is
slive on entry tobb1but not on entry tobb0? - Run the example with
-- --forward, which visits the blocks first to last instead of last to first. Does the answer change? Does the number of rounds? - The chain rule fuses
u → vonly ifuhas exactly one successor. Give a three-node example where fusingu → vanyway, even thoughualso has an edge tow, would delayw.
Answers
- One new edge,
n1 → n(readsh2). Nown1has two successors,n2andn, so neither edge out ofn1fuses.nlands in level 1 next ton2, and there are still 3 levels. (psync’s realplanfuses in one more case: whenudoes not await and everything else afteruwaits forvanyway.n1awaits, so that case does not apply.) - An output dependence on
x, together with a true and an anti-dependence, sincepushboth reads and writesx. Running them concurrently needs two&mut xat once, which the borrow checker rejects. Even with a lock, the order of the elements could change. bb0definess(s = 0) before anything reads it, so the valueshad beforebb0is never used. Inbb1, the currentswill be read later, inbb2orbb3.- The answer is the same: the least fixed point does not depend on the visiting order. The number of rounds grows from 2 to 3. Liveness flows backwards, from uses to earlier points, so visiting blocks in reverse lets one round carry information further.
let k = key(); let r = api.get(&k).await; let m = slow_other(&k).await;. Hereu = khas edges tov = randw = m. Fusingk → rinto one chain meansmwaits for the whole chain, including the requestr, when it only neededk. psync allows the fusion only whenudoes not await andwwould wait forvanyway.
Effects and summaries
The dependence analysis of the last chapter compares what statements read and write in the program’s own variables. But two statements with no variables in common can still interfere:
warm().await?; // writes cache.json
let s = load().await?; // reads cache.json
Nothing connects these two lines in the source. The connection is outside the program, in the file system. Anything a function does that is visible outside its own variables is a side effect, or just an effect: reading or writing a file, sending a request, starting a process, setting an environment variable, printing. A function with no effects is pure. You can run two pure functions in either order, or at the same time, and nothing outside can tell.
This chapter is about knowing which effects a call has. That needs interprocedural analysis, an analysis that looks past one function into the functions it calls.
Describing an effect
psync describes an effect by three things (Effect in psync-check/src/lib.rs):
| Part | Values | Example |
|---|---|---|
| domain: where it lands | file system, sockets, environment, a child process, standard output, or a named service (another crate’s API) | Fs, Service("kube::Api::<K>") |
| access: how | Read, Write, or Ordered (a write whose order is visible, like send or append) | Write |
| target: what exactly, when known | a file path or key, taken from a string constant | "cache.json" |
Two effects conflict, and must keep their order, when all of these hold (psync_check::conflict):
- at least one of them writes;
- they are in the same domain. A child process may touch anything, so it conflicts with everything except a read of the environment (the macro, with less to go on, does not make even that exception);
- their targets may be the same. Unknown targets may be anything. File paths overlap when they are equal or one is a directory containing the other. Two ordered writes on one domain always conflict, whatever their targets.
The two lines above conflict: one writes the file cache.json and the other reads it. Two reads
never conflict. Writes to a.txt and b.txt do not conflict. A write to logs/ and a read of
logs/today.txt do.
Effects and exits: speculation
Effects interact with early exits as well as with each other. In
s.check().await?;
let t = s.get_token().await; // writes the file "token"
sequential code never calls get_token if check fails. If psync started both calls at once,
the file would be written even when check fails. That is a speculative write: work done
before knowing it was needed, which cannot be undone. Running a read speculatively is harmless,
because a read changes nothing. So psync adds one more rule: a write never starts before an earlier
statement that may exit, unless you mark it #[psync::speculate]. A call that may panic
would count as an exit too, but the macro cannot see which calls panic: only the compiler can,
so this part needs compiler facts (see the end of this chapter). The theorem speculation_harmless in the proofs chapter is
half of the reason reads are safe to run past an exit: extra reads change no state. The other
half, replay_correct, says that recording every statement’s outcome and replaying the first exit
in program order then gives the sequential state and the sequential exit.
Two ways to know what a call does
By name. The macro sees only s.get_token(). It splits the name into words and looks for a
verb: get, list and read read, put, delete and create write, send and append are
ordered. That is effects.rs, and the table of verbs is in
Side effects. Names are a good guess and nothing more. get_token, it
turns out, writes a file.
By body. The driver sees the MIR of get_token. Its body calls std::fs::write with the
constant "token", so it writes the file token. That is what the function really does. It holds
whatever the function is called.
The second is better whenever it is available, and the rest of this chapter is about computing it.
Summaries
The summary of a function is the set of effects a call to it may have, through every function it calls. The effects of a single basic block are easy to find. The hard part is calls, because a function’s summary includes its callees’ summaries:
S(f) = own(f) ∪ S(g₁) ∪ S(g₂) ∪ ... for every function gᵢ that f calls
Here own(f) holds the effects of the calls f makes that psync recognizes directly, such as
std::fs::write, tokio::fs::read or Command::spawn. The driver looks those up by path. It
never follows calls into std or tokio. Their effects are what their paths say.
If the call graph (one node per function, an edge f → g when f calls g) has no cycles,
the equation can be solved bottom-up: summarize callees first and remember each result. This is
memoization. Each function is summarized once, however many callers it has.
Recursion: cycles in the call graph
Recursive functions make the call graph cyclic, and then “callees first” has no meaning. Run the example:
cargo run -p psync-graph --example summaries
memoized, cut cycles:
walk {"read net", "write file walk.log"}
visit {"read net"}
...
least fixed point:
walk {"read net", "write file walk.log"}
visit {"read net", "write file walk.log"}
walk writes walk.log and calls visit, and visit calls walk. The first method does a
depth-first walk with memoization, and it cuts a cycle by treating a function it is already in the
middle of as having no effects. Summarizing walk first, it computes visit while walk is
still unfinished, so visit gets no write. That wrong answer is then memoized, and every later
question about visit gets it. A call to visit really does write walk.log, through walk.
The equation is the same kind as liveness in the dataflow chapter: a set
defined in terms of itself. The cure is the same too. Start each summary at own(f), and keep
absorbing callees’ summaries until nothing grows. Sets only grow, and there are finitely many
effects, so this stops at the least fixed point, which gives each function exactly the effects
it can reach.
The driver does this efficiently in two steps (Analyzer::summarize and component in
analysis.rs):
- Strongly connected components. A strongly connected component (SCC) is a maximal set of
functions that can all reach each other. Here
{walk, visit}is one, and every non-recursive function is a component on its own. Tarjan’s algorithm finds the components in one depth-first walk, and it completes each component only after all the components it calls. So when a component is complete, everything outside it that it calls is already summarized. - A fixed point per component. Start each member at its own effects, and absorb its callees’ summaries, from the memo for those outside the component and from the current round for those inside, until no member’s summary grows. A component without a cycle takes one round.
An earlier version of the driver used the cut-cycle method. The fixture
psync-check/tests/fixtures/hidden now contains this exact pair (walk, visit), with walk
summarized first. The test checks that cargo psync check reports a call of visit as writing
walk.log:
warning: psync runs this concurrently with other work that has a conflicting effect: this does
`read file "walk.log"` (via read_log -> std::fs::read), the other does
`write file "walk.log"` (via visit -> walk -> std::fs::write)
The via chain is the path through the call graph that the effect came along.
Across crates
A crate is compiled before the crates that depend on it, and the crate graph has no cycles. So
the driver writes each crate’s summaries to a file, target/psync/summaries/<crate>-<id>.json.
When it compiles a dependent crate, it reads those files and looks callees up by their
DefPathHash. The crate graph is a DAG, so no fixed point is needed across crates. Cargo’s build
order is already “callees first”. You can print any crate’s summaries:
$ cargo psync summaries app
crate app
Session::get_token
write file "token" via std::fs::write
sync_dirs
write file via helpers::stamp -> std::fs::write
tour
write file "walk.log" via visit -> walk -> std::fs::write
read file "walk.log" via read_log -> std::fs::read
...
Crates from crates.io are summarized too, with one difference. In a library, only real I/O
counts (files, processes, the environment). Inside an HTTP client, every request writes to a
socket, and counting that would make every call a write. At the boundary between your code and a
published API, the API’s verb says what the call means. kube::Api::list reads, whatever bytes
it sends.
Sound, precise, and what the driver gives up
An analysis that answers “what may this function do?” is a may-analysis. It is sound if it never leaves out an effect that can happen, and precise if it never includes one that cannot. No analysis of real programs is both, so the question is what to give up.
The driver gives up precision in these places:
- Flow-insensitive. It takes the union over every call in every basic block. A write behind
if falsestill counts. - Unknown targets. A path built at run time (
format!("{dir}/.synced")) has no constant target, so it may be any file. - Whole processes. Starting
git statuscounts as touching everything.
It cannot see in these places, and marks the summary opaque:
- a call through a function pointer;
- a
dyncall of a trait from another published crate (dyn tower::Service), which could be implemented by anything. The common I/O traits are partly an exception. A call ofAsyncWrite,io::Write,AsyncReadorio::Readon any reader or writer that is not an in-memory buffer counts as a write or read of that object (named by its type). Throughdyn, the summary is also marked opaque, because the implementation may do more; - a trait method with no implementation in the build.
Opaque does not mean “assume the worst”. It means “the compiler’s effects are incomplete”.
cargo psync build then keeps the macro’s name-based guess as well as the compiler’s effects. So
with facts the macro is at least as cautious as without them. The remaining assumptions are
listed in What is checked, what is assumed.
Panics are a special case. Nearly every library function could panic somewhere, so the driver
counts only explicit panics in your own code (unwrap, expect, panic!, assert!,
unreachable!, todo!) as exits.
Exercises
- In the
summariesexample, add a functionsweepwhose own effect isread net(a read from the network) and which callsvisit. Without running it, what isS(sweep)? Which SCC doessweepbelong to? - Why can the cut-cycle method give the right answer for
walkbut the wrong one forvisit? State in one sentence which member of a cycle the method gets right. fs::write(&a, ..)andfs::read(&b), withaandbvariables: does psync keep them in order? Why? What would it take to let them overlap safely? (See the roadmap, item 1.)- A function calls
Command::new("ls").output(). Which domain, access and target does that effect get, and what does it conflict with? - Why would counting socket writes inside libraries make the driver useless for kube-rs?
Answers
S(sweep) = {read net, write file walk.log}, from its own read and fromvisit, which reacheswalk.sweepis its own SCC. Nothing calls back to it, so it is not in{walk, visit}.- The function where the depth-first walk enters the cycle is finished last, after every other member has been absorbed into it, so it alone sees the whole cycle. The other members were memoized while it was still incomplete.
- They overlap, behind a runtime check. Neither has a constant target, so either may be any
file, and one of them writes. psync compares the two paths when the function runs: the
concurrent schedule if they differ, the sequential one if they are the same file. The report
says
level 0: n0 || n1andtargets compared at run time: 1 pair(s) of chains wait for each other if their files, URLs or keys overlap(Paths compared at run time). - Domain
Process, accessWrite, no target. It conflicts with every other effect except a read of the environment, because the child can do anything to files, the network or services. (Recognizinglsas read-only is item 7 of the roadmap.) - Every API call (
list,get,watch) sends bytes over a socket, so each one would be a write to the network domain. Every pair of calls would conflict, and no two requests could ever overlap, which is the opposite of what the driver is for.
Dynamic dispatch and class hierarchies
The effect summaries of the last chapter need every call resolved to the function it runs. For most calls, the compiler already knows. For a call through a trait object, it does not, by design. This chapter explains why, and how psync answers the question anyway.
Static dispatch and monomorphization
trait Store { fn checkpoint(&self) -> io::Result<()>; }
struct FileStore;
impl Store for FileStore { fn checkpoint(&self) -> io::Result<()> { fs::write("state.db", b"x") } }
fn save_static(s: &FileStore) { s.checkpoint(); } // 1. concrete type
fn save_generic<S: Store>(s: &S) { s.checkpoint(); } // 2. generic
fn save_dyn(s: &dyn Store) { s.checkpoint(); } // 3. trait object
- In
save_staticthe receiver’s type is known, so the call resolves to<FileStore as Store>::checkpoint. This is static dispatch. - In
save_generic,Scould be any type. rustc compiles a separate copy ofsave_genericfor each type it is used with:save_generic::<FileStore>,save_generic::<MemStore>. This is monomorphization. In each copy, the call is static again. - In
save_dyn,&dyn Storeis a pointer to the data plus a pointer to a vtable, a table of function pointers that is filled in for the actual type when the reference is made. The call jumps through the table. This is dynamic dispatch. Nothing insave_dyn’s code says which implementation will run, and it may differ from call to call.
What the driver sees
In MIR, all three are Call terminators naming the trait method Store::checkpoint, with
generic arguments. The driver asks rustc to resolve each one:
let instance = Instance::try_resolve(tcx, typing_env, callee, generic_args).ok().flatten();
let unresolved = match instance {
Some(i) => matches!(i.def, InstanceKind::Virtual(..)), // a vtable call: `dyn`
None => true, // a generic it cannot pick yet
};
- In
save_static, it resolves to<FileStore as Store>::checkpoint, a local body to summarize. - In
save_generic, the driver analyses the generic body once, before monomorphization, soSis still a parameter and the call cannot be resolved (None). - In
save_dyn, it resolves toInstanceKind::Virtual: “look it up in the vtable”.
So cases 2 and 3 leave the same question open: which implementations of Store::checkpoint can
this call reach?
Class-hierarchy analysis
Compilers for object-oriented languages met this question long ago, for virtual method calls.
The classic answer is class-hierarchy analysis (CHA). A call of method m on a receiver of
type T can only reach implementations of m in T and the types derived from it. So collect
every implementation in the program and take that set as the possible targets. In Rust
the “hierarchy” is flat: a call of Trait::m can reach any impl Trait for X in the program.
CHA needs to know every implementation. That is a closed-world assumption: no code outside what was analysed can add one. Here psync meets a problem particular to Rust. When a crate is compiled, rustc sees only the crate and its dependencies. The implementation may live in a crate that depends on the caller, compiled later:
datafusion-catalog ListingSchemaProvider::refresh calls self.factory.create(..)
on an Arc<dyn TableProviderFactory>
▲ depends on
datafusion (core) impl TableProviderFactory for ListingTableFactory { fn create .. }
No single compilation sees both. So the driver puts the question off until the whole build has been compiled, and answers it at link time:
- Defer. An unresolved call of a trait method from the user’s workspace is recorded in the
summary as deferred, keyed by the
DefPathHashof the trait method, a stable name forStore::checkpointthat every crate computes the same way. - Record implementations. Each crate’s summary file lists which of its methods implement which trait methods.
- Link. After the build,
psync_check::linktakes, for every deferred trait method, the union of the summaries of all its implementations in the build. It does this transitively, because an implementation may itself defer further calls. - Use. The result goes to the macro, in the facts file. It also goes back to the driver:
cargo psyncwrites it tolinked.jsonand points the environment variablePSYNC_LINKEDat it. When the resolution changed,cargo psyncthen runs the check a second time, and that pass reports what onlydynresolution reveals.
The summaries example shows the table and the result:
class hierarchy: {"Store::checkpoint": ["FileStore::checkpoint", "MemStore::checkpoint"]}
snapshot {"write file state.db"}
snapshot calls Store::checkpoint through dyn. One implementation writes state.db and the
other does nothing, so a call may write state.db. The fixture has the real thing, with the
file called store.db:
#[graph]
pub async fn snapshot(store: &dyn Store) -> Result<usize, Error> {
store.checkpoint().await?; // FileStore's implementation writes store.db
let n = inspect_db().await?; // reads store.db
Ok(n)
}
warning: psync runs this concurrently with other work that has a conflicting effect: this does
`read file "store.db"` (via inspect_db -> std::fs::read), the other does
`write file "store.db"` (via Store::checkpoint -> std::fs::write)
Where the closed world ends
The assumption is only as good as the build. The driver treats these cases as opaque, not as “no effects”:
- Traits of published crates.
dyn AsyncWriteortower::Servicecan be implemented by any crate, so CHA over your build proves nothing about them. The driver classifies the common I/O traits by the receiver’s type instead (AsyncWriteon a real file or socket writes it). - No implementation in the build. A trait with no implementation is a sign that one comes from elsewhere: a plugin, or a caller in another workspace.
- Function pointers and closures passed in as values. These have no trait method to look up.
Facts are therefore valid for the build they were computed in. A different set of crates, or
different features, gives different facts, and cargo psync build recomputes them.
CHA is also imprecise in a way you can see. save_generic::<FileStore> gets the union over all
implementations, MemStore included, because the driver analyses the generic body once, not
each copy. That costs precision, never soundness. Analysing each monomorphized copy separately
would be more precise and much slower. Finer analyses narrow the set further. Rapid type analysis keeps only the implementations of
types the program actually constructs somewhere. Points-to analysis tracks which values can
flow to the call.
Exercises
- In the
summariesexample, add a third implementation,NetStore::checkpoint, that sends over the network. What doessnapshot’s summary become? Is that sound for a program that only ever passes aFileStore? Is it precise? - Why does the driver key deferred calls by
DefPathHashand not byDefId? - A crate has
fn run(f: fn() -> io::Result<()>) { f().unwrap() }. What does its summary say, and why can CHA not help? - Why is it safe for the link step to take a union over implementations, but unsafe for it to pick any single one?
Answers
{write file state.db, write net}(plus whatever elseNetStoredoes). It is sound: it includes everything that could happen. It is not precise for that program, which can never reachNetStore. Only a whole-program analysis of which types reach the call could tell.- A
DefIdis a crate number and an index, and crate numbers are assigned per compilation. The same trait method gets differentDefIds in different crates’ compilations. ADefPathHashis computed from the definition’s path and its crate’s stable identity, so it is the same everywhere, which a key shared between compilations needs. - “Call through a function pointer”, which is opaque, and it panics (
unwrapis an explicit panic). The callee is a runtime value with no trait method to look up, so there is no hierarchy to analyse. - The program may run any of them, so a sound summary must include the effects of every one. A single one would be right only for the programs that happen to pass that type.
Proofs
Tests show that psync is right on the programs that were tested. A proof shows it is right
on every program, given stated assumptions. verify/Schedule.lean is such a proof for the core
idea: running psync’s schedule concurrently ends in the same state as running the program in
order. This chapter teaches enough Lean to read that file, check it, and extend it.
What a proof assistant does
A proof assistant is a programming language in which a theorem is a type, and a proof is a value of that type. If the program type-checks, the proof is correct. You trust the small checker at the core of the tool, not the person who wrote the proof. Lean 4 is one such tool, and it is also an ordinary functional language, so definitions, programs and proofs live in one file.
Install it with elan, then check a file:
lean verify/Tutorial.lean # prints nothing when every proof checks
lean verify/Schedule.lean
Tutorial.lean holds every example in this chapter, and the solutions to its exercises.
First steps
def double (n : Nat) : Nat := n + n
theorem double_21 : double 21 = 42 := rfl
def defines a function. theorem name : statement := proof states something and proves it.
double 21 = 42 is a type, and rfl (reflexivity) is a value of it when both sides compute to
the same thing. To prove something for every n, computation is not enough:
theorem double_eq (n : Nat) : double n = 2 * n := by
unfold double
omega
by switches to tactic mode. Instead of writing the proof term yourself, you give commands
that transform the goal until nothing is left. The goal starts as double n = 2 * n. After
unfold double it is n + n = 2 * n. omega, a decision procedure for linear arithmetic, then
closes it. In an editor with Lean support you can see the goal after each line, which is the
normal way to write proofs.
Programs as lists of steps
Schedule.lean models a program as a list of operations, each a function from state to state.
Here is the same idea with numbers:
def applyAll : List (Nat → Nat) → Nat → Nat
| [], s => s
| f :: fs, s => applyAll fs (f s)
applyAll [f, g] s is g (f s): run f, then g. Now prove that running xs ++ ys means
running xs and then ys:
theorem applyAll_append (xs ys : List (Nat → Nat)) (s : Nat) :
applyAll (xs ++ ys) s = applyAll ys (applyAll xs s) := by
induction xs generalizing s with
| nil => rfl
| cons x xs ih => exact ih (x s)
This is induction on the list, the proof version of a recursive function. There are two
cases. For [], both sides compute to applyAll ys s, so rfl. For x :: xs we may assume
the statement for xs (the induction hypothesis ih). By the second equation of applyAll,
the goal is applyAll (xs ++ ys) (x s) = applyAll ys (applyAll xs (x s)), which is ih with the
state x s. generalizing s makes ih
hold for every starting state, which is needed because the state changes from one step to the
next. Schedule.lean has exactly this theorem, runAll_append.
Commutation
The heart of psync is that independent operations can be swapped. With two functions:
theorem swap2 (f g : Nat → Nat) (h : ∀ s, f (g s) = g (f s)) (s : Nat) :
applyAll [f, g] s = applyAll [g, f] s := by
show g (f s) = f (g s)
rw [h]
h is a hypothesis: the theorem only holds for f and g that commute. show restates the
goal in a form Lean can see is equal to it. rw [h] (rewrite) replaces f (g s) with
g (f s) using h, which closes the goal.
What makes two operations commute? In psync’s model, state is a function from locations (variables, fields, files) to values:
abbrev State := String → Nat
def set (x : String) (v : Nat) (s : State) : State := fun y => if y = x then v else s y
theorem set_comm (x y : String) (a b : Nat) (hxy : x ≠ y) (s : State) :
set x a (set y b s) = set y b (set x a s) := by
funext z
unfold set
by_cases hx : z = x <;> by_cases hy : z = y <;> simp_all
Writes to different locations commute. funext z says that two functions are equal if they agree
at every z. by_cases splits into the cases z = x or not, and z = y or not. <;> applies
the next tactic to every case, and simp_all simplifies each case, using hxy to rule out
z = x ∧ z = y.
Four more constructs
Schedule.lean uses four things the examples so far have not. All four are in section 4 of
Tutorial.lean.
-
Sets as predicates. A set of locations is written as a function to
Prop, the type of propositions:R : Loc → Prop, whereR lis the statement “lis inR”. The tutorial’sSmall : Nat → Prop := fun n => n < 10is the set of numbers below 10. -
Structures.
structuredeclares a record type. Its fields can be proofs as well as data, so a value of the type comes with guarantees attached:structure Bump where step : Nat → Nat grows : ∀ n, n ≤ step n -- every Bump comes with this proof -
Implicit arguments and
∧. Arguments in braces,{a b : Nat}, are filled in by Lean from the other arguments. A proofh : P ∧ Qis a pair:h.1 : Pandh.2 : Q. -
Inductive predicates.
inductivedefines a proposition by rules, and a proof is a derivation built from them:inductive Even : Nat → Prop | zero : Even 0 | step {n : Nat} : Even n → Even (n + 2) theorem four_even : Even 4 := Even.step (Even.step Even.zero)To prove something about every
Even n, do induction over the rules, one case per rule.
Finally, the tutorial’s State is fixed to String → Nat. Schedule.lean writes
State (Loc Val : Type) := Loc → Val, the same idea for any type of locations and values, which
is why its definitions carry the parameters Loc and Val around.
Reading Schedule.lean
Here is the file’s structure.
An operation with a footprint.
structure Op (Loc Val : Type) where
run : State Loc Val → State Loc Val
R : Loc → Prop -- the locations it may read
W : Loc → Prop -- the locations it may write
frame : ∀ s l, ¬ W l → run s l = s l
local_dep : ∀ s s', (∀ l, R l → s l = s' l) → ∀ l, W l → run s l = run s' l
A value of Op packages a function with two proofs about it. frame says it changes only what
it writes, and local_dep says what it writes depends only on what it reads. These are exactly the
promises psync’s access and effect analyses must keep. R and W are the read and write sets
from the dataflow chapter, with files and services as locations too.
Independence is “no edge”.
def Independent (a b : Op Loc Val) : Prop :=
(∀ l, a.W l → ¬ b.R l ∧ ¬ b.W l) ∧ (∀ l, b.W l → ¬ a.R l)
Neither writes what the other reads or writes. This is the negation of the three kinds of dependence, and psync draws an edge exactly when it does not hold.
The theorems build on each other.
| Theorem | Says | Proof idea |
|---|---|---|
commute | independent operations commute | look at one location l: at most one of them writes it, and frame and local_dep do the rest |
commute_list | an operation independent of a whole list commutes with the list | induction on the list, using commute |
interleave_correct | any interleaving of two independent chains equals one chain, then the other | induction on the interleaving, Interleave, using commute_list |
level_correct | the same for any number of chains: one level’s join | induction on the chains |
levels_correct | a whole schedule of levels | induction on the levels |
reorders_correct | moving operations earlier only past independent ones changes nothing | induction on the reordering |
speculation_harmless | operations that write nothing leave the state unchanged | frame, by induction |
replay_correct | running every statement and replaying the first recorded exit gives the sequential state and exit, if nothing after the first exit writes | speculation_harmless for the rest of the list, by induction |
recording_slot | a statement that records its outcome is an ordinary Op with that outcome in its slot | unfolding |
Interleave a b m is an inductive predicate. It defines “m is some interleaving of a and
b” by three rules: both empty, take the next element from a, or take it from b. Proving
something for every interleaving is then an induction over those rules. Each rule is one
possible next step of the executor. This is how the proof covers every way the executor might
poll the chains. Two more definitions tie it to psync’s schedule:
def PairwiseIndependent : List (List (Op Loc Val)) → Prop -- the chains of one level
| [] => True
| c :: cs => (∀ c' ∈ cs, ∀ x ∈ c, ∀ y ∈ c', Independent x y) ∧ PairwiseIndependent cs
inductive Runs : List (List (List (Op Loc Val))) → List (List (Op Loc Val)) → Prop
| nil : Runs [] []
| cons {cs m levels ms} :
PairwiseIndependent cs → InterleaveAll cs m → Runs levels ms → Runs (cs :: levels) (m :: ms)
Runs levels ms says that ms is one possible execution of the schedule levels. Each level is a
list of chains that must be pairwise independent, and its execution m is some interleaving of
them (InterleaveAll, built from Interleave).
What is proven, what is assumed
Read a theorem’s hypotheses as the list of things everything else must guarantee. For
levels_correct:
- Footprints are correct. Each
Op’sframeandlocal_dephold. In psync these are the obligations of the access analysis (variables and fields) and the effect analysis (files and services).cargo psync checkchecks the effect part against the compiled callees. - Chains in a level are pairwise independent. That is psync’s edge rule.
The last section, Early exits, adds statements that may exit. An XOp is an Op with an
exit function, whose outcome depends only on what the statement reads. seqX runs a list
sequentially and stops at the first exit. outcomes runs every statement and records each
outcome, as psync’s exit slots do, and firstExit replays the first one. replay_correct proves
that the two agree, in state and in exit, when no statement after the first exit writes. That is
the condition psync’s speculation rule enforces. XOp.recording turns an XOp into an ordinary
Op that also writes its outcome into its own slot, so the scheduling theorems apply to
statements that record their exits.
Note what the replay needs: every statement before an exit has run. psync once broke this, by replaying an exit before an earlier statement in a later level had run; see Early exits.
Not modeled: the generated Rust. rustc type- and borrow-checks it.
Exercises
Each has a solution at the end of verify/Tutorial.lean.
- Prove
theorem applyAll_nil (s : Nat) : applyAll [] s = s. - Prove that the later of two writes to one location wins:
set x a (set x b s) = set x a s. Why does this mean psync must keep two writes to one place in order? - Prove that a list of functions that each leave the state unchanged leaves it unchanged:
(∀ f ∈ fs, ∀ s, f s = s) → applyAll fs s = s. Which theorem ofSchedule.leanis this? - In
Independent, why is the condition not symmetric as written? Find the theorem inSchedule.leanthat shows it is symmetric anyway. - Suppose psync had a bug that put a read and a write of the same file into one level. Which
hypothesis of
levels_correctfails? What does the theorem then say about that program?
Answers
:= rfl.applyAll [] scomputes tosby the first equation.funext z; unfold set; by_cases hx : z = x <;> simp_all. Swapping the writes would leavebinstead ofa: the two orders give different states, so the writes are not independent (output dependence).- Induction on
fs, rewriting the head with the hypothesis (see the file). It isspeculation_harmless, for numbers instead ofOps. - The first conjunct covers
a’s writes againstb’s reads and writes, and the second coversb’s writes againsta’s reads.b’s writes againsta’s writes are covered by the first, so the condition is symmetric in meaning.Independent.symmproves it. - Pairwise independence fails for that level, so the
Runshypothesis cannot be proved. The theorem then says nothing about that program. A theorem never covers a case whose hypotheses fail. That is why the analyses that establish the hypotheses matter as much as the proof.
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, speculate, par); 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,strict,speculate,effects(..),yield_every,crate; see Attribute options). 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. - With
yield_every = N, inserts a yield to the executor at the start of every Nth iteration of each loop (YieldInjector), so a long loop cannot hold back other tasks. - Inserts
const __PSYNC_GRAPH: Option<&str> = option_env!("PSYNC_FACTS_STAMP");at the top of the body. It marks the function forcargo psync’s driver, and makes cargo rebuild the function when its compiler facts change. It has no effect at run time. - 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 a block it cannot speed up. (The function as a whole still gains the
__PSYNC_GRAPH constant of step 5.)
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.
Exercises
For each question, name the module (or step) where you would look first.
- The report shows
n1 -> n3 (writes `cache`)forcache.peek(k)onlet mut cache, and you knowpeekonly reads. let n = api.count().await.len();is one node, but you expected thelen()to be split off.- A loop’s prefix was not prefetched, and the report names a write that every iteration performs.
- An error came back from the wrong statement when two statements failed together.
- You want to see what psync does with a function without building your crate.
Answers
access.rs, which decides that a method on amutbinding writes unless it looks read-only.peekis neither in the pure list nor has a read-only prefix (get,is_,len, …), so it counts as a write. Called throughlet c = &cache;it does not: a shared reference is not amutbinding. (c.peek(2)is still an ordinary statement, so it keeps its order with other ordinary statements.)hoist.rs. A binding whose value is itself awaited is already its own node, so there is nothing to split:len()runs right after the await in the same chain, and costs nothing.loops.rs, which takes the prefix and checks what the rest of the body writes.exits.rs, which records exits and replays them in source order. A wrong order there would break the guarantee thatreplay_correctinverify/Schedule.leanproves for the model.psync-expand FILE LINE, which runspsync_graph::expandoutside the compiler. The proc macro is a thin wrapper around the same function.
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 effects: Vec<Effect>, // what it does to files, services, processes, the environment
pub unclassified: Vec<String>,// awaited calls whose names say nothing (assumed to read)
pub speculate: bool, // #[psync::speculate]: its writes may run ahead of exits
pub panics: bool, // compiler facts: it may panic on purpose (an exit for speculation)
pub independent: bool, // #[psync::independent]: its effects commute with the region's
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, …); joinwith one argument (Path::join,[T]::join);handle.join(), which waits for a thread, takes none and is not pure;ifwith a pure condition whose branches are each one pure expression (if arch == "i686" { "i386" } else { arch }), and blocks that are one pure expression;- 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.
Exercises
Classify each statement of this function as a barrier, an effect or another node, then check
with psync-expand FILE LINE (the JSON report’s nodes have "effect"):
async fn f(api: &Api, m: &Mutex<Vec<u32>>, id: u64, name: &str) -> u64 {
let a = api.one().await;
let k = id * 10;
let up = name.to_uppercase();
let n = {
let g = m.lock().await;
g.len()
};
println!("{a}");
let b = api.two(k).await;
let t0 = std::time::Instant::now();
let c = api.three().await;
let d = api.four().await;
a + b + c + d + n as u64 + up.len() as u64 + t0.elapsed().as_millis() as u64
}
- Which statements are barriers, and how many regions are there?
- Which nodes are effects? Why is there an edge
n2 -> n4 (effect order)? - The report also lists
barrier: line 6: `let g = m . lock () . await ;`(line 6 of the function as printed). Is the lock a barrier off?
Answers
let t0 = Instant::now();(a clock read) and the last line (the block’s value). So there are two regions: everything before the clock, andc,dafter it, wherec || drun together.up = name . to_uppercase ()andprintln!.k = id * 10is a pure binding.to_uppercaseis not on the list of read-only methods, so psync treats it as an ordinary statement, and two ordinary statements keep their order: hence the edge toprintln!. Every awaitingletis a node, not an effect.- No. The guard is dropped inside the block, so
n = lock()is an ordinary node off, and runs besideone,twoandto_uppercase. The barrier is in the nested block’s own statements, where the lock comes beforeg.len(), and psync reports it while scheduling that block.
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; - side-effect conflict: their effects on files, services or other outside resources conflict
(
effects::conflicts, see Side effects), unless either is marked#[psync::independent]. The reason names both effects; - exit before a write:
amay exit or panic andbwrites something outside the program, unlessbis marked#[psync::speculate]. The reason ismay exit before `op` runs; - 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.
Exercises
Predict the edges, then check with psync-expand FILE LINE:
async fn f(&mut self, api: &Api) -> usize {
let mut seen = Vec::new();
let a = self.client.fetch(1).await;
self.groups.push(a);
let n = seen.len();
let b = self.client.fetch(2).await;
seen.push(b);
let c = api.three(format!("{n}")).await;
n + c
}
selfis&mut. Why can the secondfetchrun whileself.groups.push(a)writesself?- Which edge keeps
seen.push(b)afterlet n = seen.len();, and what is its reason? threetakesformat!("{n}"). Is there an edge fromn?- Why does
seen.push(b)wait forself.groups.push(a), although they touch different places?
Answers
- Paths are compared by prefix:
self.groupsdoes not overlapself.client. Andfetchis a read-only prefix, so a call throughself.clientreads it, althoughselfis&mut. n3 -> n5 (writes `seen`):lenreadsseenandpushwrites it, an anti-dependence. Reordering them would changen.- Yes,
n3 -> n6 (reads `n`). Names insideformat!strings count as reads. n2 -> n5 (effect order): both are ordinary statements, and ordinary statements never change order relative to each other, whatever they touch. The level isn0->n3 || n1->n2 || n4, thenn5 || n6.
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.
Bindings are split too. In let total = combine(a, api.extra().await); the await is in the
binding’s value, not the value itself, so the operand split applies: extra() becomes its own
binding and need not wait for a, which only combine reads. The values that hoisting creates
are split again, so out.push((api.size().await, api.extra().await)) exposes both awaits. A
binding whose value is itself awaited (let x = f().await?;, let n = f().await.len();) is
already a node of its own. (Until this was fixed, only expression statements were split, and the
operands of a let waited for each other and for everything they followed. Test
awaits_inside_bindings_overlap.) The operands of a binary operator, as in
api.size().await + api.extra().await, are not split: bind them yourself.
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.
Exercises
Predict the nodes and levels, then check with psync-expand FILE LINE.
-
Why isasync fn f(api: &Api, log: &mut Vec<u32>) -> u32 { let a = api.one().await; let total = combine(log.pop().unwrap(), api.size().await); a + total }log.pop().unwrap()hoisted, although it does not await? -
Which calls overlap? How would you make all three overlap?async fn f(api: &Api) -> u32 { let a = api.one().await; let total = api.size().await + api.extra().await; a + total } -
The last line is the block’s value, a barrier. How doasync fn h(api: &Api) -> u32 { let a = api.one().await; api.two().await }oneandtwostill overlap?
Answers
- Three nodes in level 0,
a = one(),__psync_h2 = log . pop () . unwrap ()and__psync_h3 = size(), and thentotal = combine(..)in level 1.popis hoisted because it comes before the awaited operand and is not pure. Hoisting only the await would runsize()beforepop(), against the order of evaluation. Chains of a level are polled in program order, sopopstill runs beforesizestarts. oneand the pair:total = size()is one node,level 0: n0 || n1, and inside itextrastill waits forsize, because a binary operator’s operands are not split. Writelet s = api.size().await; let e = api.extra().await; let total = s + e;, and all three start together.- The tail split:
let __psync_t1 = api.two().await; __psync_t1. The await moves into a binding that can overlapone, and only the plain value__psync_t1stays last.
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 last predecessor, and all ofv’s predecessors are inu’s chain (members of a chain run in order, so whenuhas run, they all have);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.
The first condition allows several edges into v as long as they all come from one chain. In
tauri-bundler, the second download reads both linuxdeploy_arch and linuxdeploy, which is
computed from it:
let linuxdeploy_arch = if arch == "i686" { "i386" } else { arch };
let linuxdeploy = tools_path.join(format!("linuxdeploy-{linuxdeploy_arch}.AppImage"));
#[psync::par]
if !linuxdeploy.exists() { /* download */ } // reads both
The edge from linuxdeploy_arch is implied by the other two. Requiring a single predecessor left
the download in a chain of its own, a level after the first download.
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.
Exits add one constraint. A chain’s exits can be replayed only after every statement before them
in program order has run, so plan gives each chain a release level: its own level, or the
highest level of any chain holding an earlier statement, if a chain with an exit runs ahead of one.
Its exits are replayed, and its bindings handed back, after the release level. A chain that waits for it
gets a level after its release. Levels and releases are computed together until neither changes.
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.
Exercise: when levels cost time
#[graph]
async fn crossing() -> (u32, u32) {
let a1 = io(T, 1).await;
let a2 = io(3 * T, 2).await;
let b1 = io(3 * T, a1 + 10).await;
let b2 = io(T, a1 + a2).await;
(b1, b2)
}
Which chains and levels does psync build? How long does the function take, and how long would a schedule take in which every statement starts the moment its own inputs are ready?
Answer
a1 has two successors, b1 and b2, so it fuses with neither: level 0: n0 || n1, then
level 1: n2 || n3. Level 0 ends when a2 does, at 3T, and level 1 takes 3T more: 6T, against
8T sequentially (test book_levels_wait_for_all_their_chains). With every statement starting as
soon as it can, b1 would start at T and end at 4T, and b2 would run from 3T to 4T: 4T in
all. That is the cost of levels, which waiting for whole joins buys.
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_at::<1, 0, 2, true, 0, false, false, _>(async { /* chain 0 */ });
let mut __psync_f1 = ::psync::__private::maybe_done_at::<1, 1, 1, true, 1, false, false, _>(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, sorted by each node’s position in the block, after the
chain’s release level (see Levels). That makes the first exit sequential code would
hit the one that happens. Chains are numbered across the whole region (
__psync_out3), so a chain whose release comes later is not shadowed by a later level’s chain. - The whole block is emitted in place of the region’s statements, and the statements after it see the same bindings as before.
Paths compared at run time
fs::read_to_string(src) and fs::write(dst, ..) conflict on tokens, because src and dst
may name one file. When both paths can be evaluated at the start of the region, the macro
schedules them as if differently written paths named different files, and keeps
the order at run time instead (psync-graph/src/gates.rs).
A path qualifies under the rules the loop check uses:
- it is total: names, fields, references,
format!,joinand the like, with no indexing, no arithmetic and no other call; - it depends on nothing the region binds, except a
letbound once to a total value, which is substituted; - it depends on no
mutbinding.
So its value at the start of the region is its value when the statement runs. The same expression written twice stays one file, and the statements stay ordered.
A string literal keeps its own target. Two literals are already compared exactly while compiling
("out" contains "out/a.txt", and neither is "cfg.toml"), so they never need a gate. A
literal against a computed path is compared at run time like any other pair. (Until this was
fixed, literal paths were renamed too, so remove_dir_all("out") and read("out/a.txt") were
ordered by a gate whose condition was always true, and the report showed no edge between them.
Test literal_paths_are_compared_when_compiling.)
The region is planned twice: once as written, and once with each qualifying path replaced by a name for its expression. Every dependency that only the second plan drops must come from qualifying paths. Each one becomes a gate between its two chains:
let __psync_overlap = |a: &dyn AsRef<Path>, b: &dyn AsRef<Path>| { /* normalize; one contains the other */ };
let __psync_overlap1: bool = false || __psync_overlap(&(src), &(dst));
let (__psync_taken0, __psync_taken1) = {
let __psync_gate2_0 = ::psync::__private::Gate::new();
let mut __psync_f0 = maybe_done_at::<..>(async {
let __psync_r = { /* chain 0: the read */ };
__psync_gate2_0.open();
__psync_r
});
let mut __psync_f1 = maybe_done_at::<..>(async {
::psync::__private::gated_by::<0>(); // for `cargo psync check`: waits on the chain at statement 0
if __psync_overlap1 { __psync_gate2_0.wait().await; }
let __psync_r = { /* chain 1: the write */ };
__psync_r
});
/* the join, as before */
};
When the files overlap, the later chain waits for the earlier chain to end, which is the order the
statements were written in. Paths overlap when one is the other or a directory that contains it,
after Path::components (so dir/./a is dir/a). Two gated chains run in the same level. A
dependency into a later level needs no gate, since that level starts after the earlier one ends.
The relaxed plan is not used when:
- a gate would wait for a chain in a later level, which would never start;
- a gate would wait for a chain that starts later in program order. That rule makes gates acyclic, so they cannot deadlock.
gated_by::<ON>() does nothing at run time. It is a marker, like maybe_done_at: it tells
cargo psync check which chain the gated one waits for (by its first
statement), so the checker does not report the file effects the gate compares as a conflict.
Gate is an atomic flag and one waker. Every chain of a join is polled by one task, so that waker
is the join’s. It is Sync, so the function’s future stays Send.
URLs and Redis keys
Two other targets are compared the same way: an HTTP request’s URL
(client.request(Method::PUT, url), see HTTP) and a Redis command’s key
(redis::cmd("SET").arg(key)). Each kind has its own test, and a pair of different kinds (a path
against a URL) is never relaxed:
| Target | Overlap when | Function |
|---|---|---|
| file path | one is the other or a directory containing it | __psync_overlap (in the prelude) |
| URL | the same, on the path after the host, without ?query or #fragment | __private::urls_overlap |
| Redis key | equal | __private::keys_overlap |
A file path always has AsRef<Path>, because fs asks for it. A URL or a key can be any type
the client accepts, and some (a byte string, a type of your own) have no text. The generated code
asks for the text without requiring it:
let __psync_overlap1: bool = false
|| ::psync::__private::keys_overlap(
{ use ::psync::__private::{KeyText as _, NoKeyText as _}; (&::psync::__private::Key(&(a))).text() },
{ use ::psync::__private::{KeyText as _, NoKeyText as _}; (&::psync::__private::Key(&(b))).text() },
);
KeyText is implemented for Key<T> when T: Display, and NoKeyText for &Key<T> for every
T. Method lookup tries the receiver &Key<T> (which KeyText::text(&self) takes) before
&&Key<T> (which NoKeyText::text(&self) takes), so a key with Display gives Some(text), and
any other gives None, which overlaps everything: the statements stay in order. The trick is
known as autoref specialization. It decides on the concrete type at the call, so inside a generic
function whose T has no Display bound it picks None.
A POST, and a Redis command psync does not know, have no target at all (they may change
anything), so they are never relaxed. Two commands through one &mut con are ordered by the
borrow, whatever their keys. Only one connection per command (&mut pool.get()) leaves the keys
to decide. Test redis_keys_are_compared_at_run_time in tests/graph.rs runs a GET and a SET
through a stand-in client: with two keys they overlap, and with one key the SET waits and the GET
still returns the old value.
On threads
In synchronous code (Phase II) the chains of a level are jobs on threads,
and a job that must wait blocks. The gate there is SyncGate, a flag behind a mutex with a
condition variable:
let __psync_gate3_0 = ::psync::__private::SyncGate::new();
let mut __psync_f0 = Some(job_at::<..>(|| {
let __psync_opener = __psync_gate3_0.opener(); // opens the gate when dropped
/* chain 0: the read */
}));
let mut __psync_f1 = Some(job_at::<..>(|| {
::psync::__private::gated_by::<0>();
if __psync_overlap1 { __psync_gate3_0.wait(); } // blocks this thread
/* chain 1: the write */
}));
Two things differ from the asynchronous gate.
- The gate opens on drop. psync catches a job’s panic and replays it later, in program order
(Using Phase II). If the earlier job panicked before opening the gate,
the later one would wait forever, and so would
par_run, which returns only when every job has. The opener is a guard, so the gate opens as the panic unwinds. In the asynchronous version, a panic unwinds the whole join, and the waiting chain is never polled again. - Blocking must not deadlock.
par_runruns the first job on the calling thread, and gives every other job a worker of its own, up to 256 workers. Past that, jobs run on the calling thread, in order, after the first. A waiting job is always later in the level than the job it waits for, whichrelaxchecks: in program order and in the level’s job order. So the job it waits for has a thread of its own, or ran on the calling thread before the waiting job started there.
Test computed_paths_are_compared_at_run_time_on_threads in tests/sync.rs runs a blocking read
and write of two computed paths: they overlap when the files differ, the write waits when they are
one file (written dir/./a and dir/a), and when the read panics, the write is released and the
panic reaches the caller.
Limits:
- a URL is compared as text: two spellings of one resource (
/users/1and/users/01, or two hosts behind one service) count as different, the same assumption psync makes for two literals; - symbolic links, hard links and case-folding file systems can make two different paths one file,
but only under
path_text: by default psync compares files, not spellings; - the region’s certificate describes the relaxed plan, in which each qualifying path is its own place, so it holds only together with the gate;
cargo psync checkknows the gate fromgated_by, but exempts only the pair’s directfscalls. For a gated URL or key pair it still reports what MIR shows of the client (a conflict on the network), a false alarm.
tests/targets.rs runs a read of src and a write of dst. With two files they overlap. With
one file, written as dir/./a and dir/a, the write waits. Without the gate, the read returns the
new contents.
Owned files: files, not spellings
Everything above compares paths as text. After lexical normalization (. and repeated
separators are dropped), different text is taken to mean different files. That is wrong in three
ordinary ways:
| Two spellings | One file because |
|---|---|
current.json and data/v2.json | current.json is a symlink to data/v2.json |
a and backup/a | a hard link: two directory entries, one inode |
Readme.md and README.md | a case-insensitive file system (macOS, Windows defaults) |
Comparing text, psync would run a read of one beside a write of the other, and the read could see
the write. So by default psync takes the file’s identity from the operating system instead of the
path’s text. #[psync::graph(path_text)] goes back to comparing text (the behaviour before
2026-11-26), for a function whose paths you know are plain files with one name each.
What the standard library offers
These are the #[stable(since)] versions in the Rust source psync builds with:
| API | Stable since | What it settles |
|---|---|---|
std::fs::canonicalize | 1.5 | follows symlinks and resolves .., but only for paths that exist |
std::os::unix::fs::MetadataExt::{dev, ino} | 1.1 | device and inode: the file itself, which hard links share |
std::os::fd::{OwnedFd, AsFd} | 1.63 | an open file as an owned value, closed on drop (OwnedHandle on Windows) |
File::create_new | 1.77 | create, failing if the file exists, in one system call |
std::path::absolute | 1.79 | an absolute path without touching the disk: lexical only, symlinks are not followed |
std::fs::exists | 1.81 | whether a path exists, with errors reported instead of swallowed |
File::lock | 1.89 | an advisory lock on an open file |
None of these resolves paths by itself. path::absolute (1.79) is the one that sounds like it
does, but it only prefixes the working directory. canonicalize needs the file to exist, and the
inode needs it too. So psync combines them.
Identity
psync::__private::FileId (src/files.rs) resolves a path once:
- inode:
(dev, ino)frommetadata, when the file exists (Unix); - resolved path:
canonicalize(p)when it exists; for a file about to be created, the canonical parent joined with the name; as a last resort,path::absolute(p).
Two identities overlap when their inodes are equal, or when one resolved path is the other or a
directory containing it. A symlink and its target have one inode and one canonical path. A hard
link has one inode. A new file written through sub/../new.txt resolves to the same place as
new.txt.
What identity changes
- Literal paths are compared at run time too. Under
path_text,"current.json"and"data/v2.json"are different files while compiling, and run side by side with no check. By identity, the strict graph (what must stay ordered) widens every file target to “any file” (gates::widen_files), while the relaxed graph keeps the text. A pair whose text already overlaps ("out"and"out/a.txt") stays an edge, with no gate that would always wait. A pair whose text differs is put side by side behind the run-time gate, guarded byfiles_overlap(&a, &b). - Loop items are compared by identity. The per-item check
builds
ItemTarget::file(&path)instead ofItemTarget::path(&path).
#[psync::graph(speculate)] // identity is the default
fn read_then_write(src: &Path, dst: &Path) -> io::Result<String> {
#[psync::par]
let old = fs::read_to_string(src)?; // src = dir/link, a symlink to dir/a
#[psync::par]
fs::write(dst, "new")?; // dst = dir/a
Ok(old)
}
tests/sync.rs (owned_files_compare_files_not_spellings) runs this on threads. Under
path_text the read returns "new": it ran beside the write. By identity it returns "old",
and two really different files still run side by side (under 180 ms for two 100 ms calls).
psync-graph’s owned_files_compares_even_literal_paths_at_run_time checks the plan: two
literal paths give two chains and no check under path_text, and two chains with one check by
identity; out against out/a.txt is an edge.
Why not open the files ahead (owned file objects)
The owner’s question was whether psync should go further: open every file once, hold an
OwnedFd, and let the statements read and write through it. Then identity would be the open
file itself. We chose not to, for now:
- It changes the program.
fs::write(p, ..)truncates, creates, or replaces by rename; doing it through a descriptor opened earlier differs when a file is created or replaced in between (a rename gives a new inode; the old descriptor still names the old file). - It holds resources. A loop over 10,000 items would hold 10,000 descriptors, past the usual limit of 1,024.
- Identity is enough. The scheduler only needs to know whether two operations may touch one
file.
FileIdanswers that with two system calls (metadataandcanonicalize) per path, and the program still does its own opening.
Costs and limits
- Time: each compared path costs a
statand arealpathat the start of the region, about 2–5 µs on a local disk. That is nothing beside a 100 µs read, but it adds up for many tiny files. - A race (TOCTOU): identity is taken when the region starts. A symlink created or retargeted by another process after that is not seen, the same as any check-then-act. Within the function, a statement that creates a symlink is a file write, so it is already ordered against the others.
- Case folding: two names that differ only in case resolve the same only where the file
exists (
canonicalizereturns the stored name). Two files not yet created on a case-insensitive system are still compared as text. - Outside Unix there is no inode in
FileId; the resolved path decides. - On by default (the owner’s call, 2026-11-26): correctness first. A function with many
literal paths gets more gates;
path_textremoves them where you know the paths are plain.
Exercises
-
Predict the chains and levels of this function, and its time, where
io(d, v)waitsdand returnsv:#[graph] async fn crossing() -> (u32, u32) { let a1 = io(T, 1).await; let a2 = io(3 * T, 2).await; let b1 = io(3 * T, a1 + 10).await; let b2 = io(T, a1 + a2).await; (b1, b2) }What would a dataflow schedule, where every node starts when its inputs are ready, take?
-
Change
b2toio(T, a2 + 1). What changes, and how long does it take now? -
In the
key/resp/cache.insertexample,keyhas two successors. Which condition lets it fuse anyway, and why would that fail ifkeywerelet key = store.next_id().await;? -
A function reads
redis::cmd("GET").arg(&a)and then writesredis::cmd("SET").arg(&b), wherea: &[u8]andb: &[u8], each on its own connection. Does it get a gate? What does the gate do when the function runs with two different keys?
Answers
a1has two successors (b1andb2), so neither edge fuses.level 0: n0 || n1, thenlevel 1: n2 || n3. Level 0 takes 3T (it waits fora2), and level 1 takes 3T (forb1): 6T, against 8T sequentially. A dataflow schedule would startb1whena1ends, at T, and finish both at 4T. The testbook_levels_wait_for_all_their_chainsintests/graph.rschecks the 6T.- Each
anow has one successor, so both pairs fuse:level 0: n0->n2 || n1->n3, two chains of 4T each, so 4T. That is also the dataflow time: fusion is what removes the cost of levels for per-item pipelines. - The second case of fusion:
keydoes not await, and the other successor,cache.insert, waits forrespanyway. Withnext_id().await,keyawaits, so only the single-successor case could apply, and it has two.keyends its chain,respgets level 1, andinsert, whose predecessors are now in two chains, level 2. - Yes:
&aand&bare total, and neither is bound in the region ormut, so the two commands are planned as concurrent with a gate between them. But[u8]has noDisplay, so(&Key(&(&a))).text()findsNoKeyTextand givesNone, andkeys_overlapreturns true: the SET always waits for the GET. The function behaves as written and gains nothing. Keys built withformat!or held asStringhave text and are compared.
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_at::<1, 0, 2, true, 0, false, false, _>(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.
Exercises
- In
profile_page,userfails after 3 ms andpostsfails after 1 ms. Which error does the function return? Which calls ran? avataris inuser’s chain. Ifuserfails, doesavatarrun? Doesfriends?- Why can
__psync_out0.unwrap()never panic, even though a chain’s value may beNone? - The function returns
Result<Page, AppError>, andapi.userreturnsResult<User, HttpError>withimpl From<HttpError> for AppError. The generated code stores the residual ofapi.user(..). Where does the conversion toAppErrorhappen?
Answers
user’s error, althoughposts’s came first in time. Re-raises are sorted by source position, and sequential code would have stopped atuser.user,postsandfriendsall ran;avatardid not. Testerrors_are_replayed_in_program_orderintests/sync.rschecks the same thing with two#[psync::par]statements.avatardoes not: the chain breaks out atuser’s?, as sequential code would.friendsruns, because it is in another chain. That is why only calls psync takes as reads may be in chains that run beside an earlier exit (Side effects).- A chain ends in
Noneonly by abreakthat recorded an exit first. The re-raises run before theunwraps, and the first recorded exit leaves the function. So anunwrapis reached only when no chain recorded one, and then every chain ended inSome. - In the replay:
Rethrow::rethrow(r)?givesErr::<(), HttpError>(e), and the caller’s own?appliesFrom<HttpError> for AppError, just as the original?would have.
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]
terminates: bool, // the body may end the loop (`?`, `return`, `break`)
speculate: bool, // #[psync::speculate] on the loop or the function
carried_effects: Vec<Effect>, // side effects whose target is the same in every iteration
}
LoopScope::refuses refuses a candidate prefix node, in this order, when:
- the loop
terminates, the node writes something outside the program, and neither the loop nor the node is markedspeculate. Later items’ writes would happen before an earlier item ends the loop; - it writes a file or service whose target does not mention a per-iteration name, so every iteration writes the same thing;
- its side effects conflict with
carried_effects; - it writes a non-local path;
- it reads a path in
carried.
independent skips checks 2 to 5, but not 1: knowing that iterations do not depend on each other
says nothing about work done after the loop should have ended.
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 { None } else { Some(<work>) };. 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_at::<2, true, false, false, _, _, _>(&__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.
Checking per-item files
Prefetching runs item 3’s prefix before item 2’s rest. That is safe when each item touches its own files, which a list with duplicates breaks:
for name in names {
let path = dir.join(name);
let old: u32 = fs::read_to_string(&path).await?.parse()?;
std::fs::write(&path, (old + 1).to_string())?;
}
Run ahead over ["a", "b", "a"], both reads of a see 0, and a ends at 1 instead of 2.
So when a file the loop touches is computed from the item, and the prefix touches one of them,
and one is written, the macro evaluates those paths for every item before it starts any:
let __psync_iter: Vec<_> = IntoIterator::into_iter(<iter>).collect();
let __psync_distinct: bool = {
let mut __psync_seen = Vec::<(ItemTarget, bool)>::new(); // target, written
__psync_iter.iter().all(|__psync_r| {
let <pat> = __psync_r; // the item's names, by reference
let __psync_mine = [(ItemTarget::path(&(dir.join(name))), true), /* ... */];
// no target of this item overlaps one of an earlier item, where either writes it
let ok = __psync_mine.iter().all(|(k, w)| __psync_seen.iter().all(|(s, sw)| !((*w || *sw) && k.overlaps(s))));
__psync_seen.extend(__psync_mine);
ok
})
};
if __psync_distinct { <the prefetched loop> } else { <the loop as written> }
The paths that count are the prefix’s (reads and writes) and the rest’s writes. Two reads of one
file do not need ordering. A path is compared after Path::components, which drops . and
repeated separators, so dir/./a and dir/a are one file. Two paths overlap when one is the
other or a directory containing it: an item that writes out/a and one that removes out are
ordered. (The first version compared paths for equality, and missed that.) Symlinks, hard links, case-folding
file systems and a relative path against an absolute one can still make two different strings
name one file under path_text. By default items are compared by
file identity (ItemTarget::file), which sees
through symlinks and hard links.
A path is evaluated ahead only when that is harmless:
- it is total: names, fields, references,
format!,join,with_extension,to_path_bufand the like, andPath::new/PathBuf::from. There is no indexing, no arithmetic, and no other call, because evaluating it for an item the loop never reaches must not panic; - it depends only on the loop pattern, or on a
letin the body bound once to a total value (let path = dir.join(name)), which is substituted; - the pattern can bind by reference, which
mutinside a tuple pattern prevents.
When one of these fails, as for let path = api.locate(name).await?, distinct items are
assumed, as before. The report says which: psync-expand prints per-item targets checked at run time, or per-item targets assumed distinct: the path ... depends on path, computed in the body. #[psync::independent] on the loop skips the check.
HTTP URLs and Redis keys computed from the item are checked the same way, with the rules of
URLs and Redis keys: a PUT to format!("/items/{id}") per
item runs ahead when the ids differ. A file never overlaps a URL or a key; a URL and a key are
taken to overlap. Any other per-item target, such as a service object or an environment
variable, is still assumed to differ between items.
tests/targets.rs runs both cases. Without the check, a file named twice ends at 1.
Exercises
Each loop is for name in names { .. } in an async function with dir: &Path,
dirs: &[PathBuf] and api: &Api. Predict the loop line of the report, then check with
psync-expand.
-
let path = dir.join(name); let old = tokio::fs::read_to_string(&path).await; tokio::fs::write(&path, old).await; - The same, with
let path = api.locate(name).await;. - The same, with
let path = dirs[0].join(name);. -
let old = tokio::fs::read_to_string(dir.join(name)).await; tokio::fs::write(dir.join("total"), old).await;
Answers
prefetch [..], 16 at a time; per-item targets checked at run time. The path is total and depends only on the item, so the generated code compares every item’s path first, and runs the loop as written if two are the same file.per-item targets assumed distinct: the path `& path` depends on `path`, computed in the body. An awaited value cannot be computed ahead for every item, so psync falls back to assuming that different items name different files.- The same message.
dirs[0]is indexing, which may panic, so theletis not total, andpathis not substituted. Evaluating it for an item the loop never reaches must not panic. - Not prefetched:
write file `dir . join ("total")` (fs::write) vs read file `dir . join (name)` (fs::read_to_string), which every iteration performs. Every iteration writes the same file, which may be one that another iteration’s prefix reads (namecould be"total").
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 = ::psync::__private::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 |
maybe_done_at::<LEVEL, ORDER, LAST, EXITS, EXIT_AT, SPEC, INDEP, _>, job_at::<..> (synchronous jobs), over_at::<LOOP, TERMINATES, SPEC, INDEP, ..> | what generated code calls: the same helpers, tagged with the macro’s assumptions for cargo psync check; free at run time |
Branch, Rethrow, ResultResidual, OptionResidual | record ? and replay it through the caller’s ? |
Vec | re-exported so generated code can name alloc::vec::Vec |
tick(&counter, every) -> bool, yield_now() | yield_every = N: count a loop’s iterations in a counter static to that loop, and yield to the executor on every Nth |
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.
Generated async code names core or #krate::__private, so it compiles in no_std crates that
have alloc (the RP2350 build is one). Fission’s first loop collects into the re-exported Vec.
Three pieces name std, and each is generated only for code that already needs it: the
comparison of file paths at run time (std::path, for a function that uses std::fs or
tokio::fs), the per-item file check of a loop (std::collections::HashMap and std::path), and
the replay of a panic in synchronous #[psync::par] code (std::panic::resume_unwind, which
needs threads).
Exercise
A prefetched loop runs four items with bound = 2. Item 0 takes 3T, and items 1, 2 and 3 take
T each. Item 1 fails. How long does the join take, in what order are the outputs, and do items 2
and 3 still run? How long would it take if the join started items in batches of two?
Answer
3T. Item 0 holds one slot the whole time, and items 1, 2 and 3 take turns in the other, each
starting in the same poll in which the one before it finishes. The outputs come back in input
order, [Ok(0), Err("one"), Ok(2), Ok(3)], and items 2 and 3 do run: an error is a value, which
the loop body replays in order afterwards. Batches of two would take 4T: (3T, T), then (T, T).
Test book_bounded_join_refills_slots in tests/graph.rs.
From MIR to summaries across crates
#[psync::graph] sees the tokens of one function. When that function calls helpers::stamp(&d),
the macro knows only the name stamp. The macro classifies a call by the verb its name starts
with (get and list read, put and delete write; Effects has the
list), and stamp is not one, so it guesses “reads”. The body of
stamp, in another crate, writes a file. This chapter explains how psync gets the truth from the
compiler: what a summary is, how psync-driver computes one from MIR, how summaries cross
crate boundaries, how the link step resolves dyn calls over the whole build, and how the result
reaches the macro as facts.
It assumes Inside rustc: HIR, THIR, MIR, which shows the three forms
on a small function. Every example below is real output, from the test fixture in
psync-check/tests/fixtures/hidden (cargo psync build on it).
What a summary is
A summary of a function is a short description of everything the function may do to the world, through every function it calls, without its body. In psync it records four things:
| Field | Meaning | Example |
|---|---|---|
effects | what it may read or write outside memory: a domain (files, network, environment, processes, output, or a service such as kube::Api), an access (read, write, or ordered write: a write that must keep its order with every other ordered write of the domain, whatever the targets, such as printing) and a target when known ("store.db") | Fs Write "cache.json" via std::fs::write |
opaque | calls it could not see through: a function pointer, or a dyn method of a trait from a published crate (anything may implement AsyncWrite) | call through a function pointer |
panics | whether it may panic explicitly (unwrap, expect, panic!, assert!) | false |
deferred | methods of your workspace’s traits it calls through dyn or an unresolved generic, left for the link step | the DefPathHash (a stable name, explained below) of Store::checkpoint |
Here is the whole summary file of the fixture’s helpers crate:
{
"crate_name": "helpers",
"crate_id": "StableCrateId(11486981337079494651)",
"functions": {
"DefPathHash(Fingerprint(11486981337079494651, 10293074283500572899))": {
"path": "stamp",
"effects": [{ "domain": "Fs", "access": "Write", "target": null, "via": ["std::fs::write"] }],
"opaque": [], "panics": false, "deferred": []
},
"DefPathHash(Fingerprint(11486981337079494651, 1203218390450643680))": {
"path": "inspect",
"effects": [{ "domain": "Fs", "access": "Read", "target": null, "via": ["std::fs::read"] }],
"opaque": [], "panics": false, "deferred": []
}
},
"impls": {},
"calls": {}
}
stamp’s target is null because it writes format!("{dir}/.synced"), a path computed at run
time. An unknown target conflicts with every target in its domain.
An effect can also name a parameter instead of a target. In
fn write_it(p: &Path, d: &str) -> io::Result<()> { std::fs::write(p, d) }
the effect is { "domain": "Fs", "access": "Write", "target": null, "arg": 0 }: it writes the
file passed as parameter 0. Each caller replaces arg by what it passes there. A string constant
becomes the target, so write_it("a.json".as_ref(), ..) writes "a.json". The caller’s own
parameter becomes the caller’s arg. Anything else becomes unknown.
The one property a summary must have is over-approximation. Every effect the function can
really have must be covered by an effect in its summary. A summary may say too much, which only
makes psync more careful. It may never say too little, which would let psync run two conflicting
calls at once. The proof in verify/Footprint.lean states this exactly for a fragment of MIR:
a summary table is valid if each function’s summary covers the footprint of its own body,
reading calls from the table. If the table is valid, every statement changes nothing outside the
writes of its footprint (frame), and its result depends only on what the summary says it touches
(dep), where a statement’s footprint is computed from the summaries of what it calls. See Certified schedules.
Where psync enters the compiler
cargo psync check runs an ordinary cargo check, with one change: it sets RUSTC_WRAPPER to
psync-driver. Cargo then runs the driver wherever it would have run rustc, once per crate, in
dependency order. The driver is rustc, linked as a library (rustc_driver), plus one callback:
source ──parse──▶ tokens/AST ──expand macros──▶ AST ──resolve, lower──▶ HIR
(#[psync::graph] runs here, on tokens) │ type check
▼
borrow check ◀── MIR (built) ◀──build── THIR (every expression typed)
│
▼
after_analysis(tcx) ◀── psync-driver's callback
│ tcx.optimized_mir(f) for each function
▼
summaries, checks, facts ──▶ compilation continues (codegen, under cargo build)
In code (psync-check/src/bin/psync-driver.rs):
impl rustc_driver::Callbacks for Psync {
fn after_analysis<'tcx>(&mut self, _: &Compiler, tcx: TyCtxt<'tcx>) -> Compilation {
let mut analyzer = analysis::Analyzer::new(tcx);
let mut checker = analysis::Checker::new(&mut analyzer);
checker.run(); // compare #[psync::graph] levels with the summaries
checker.write_findings();
analyzer.write_summaries(); // target/psync/summaries/<crate>-<id>.json
Compilation::Continue
}
}
after_analysis runs only once type and borrow checking have succeeded, so every type is known
and every call is resolved as far as the compiler can resolve it. The macro has already run, so
the driver sees the code #[psync::graph] generated. That code wraps each chain of a level
(the chains psync runs at once) in a call such as maybe_done_at::<LEVEL, ORDER, ..> (a future),
or job_at::<LEVEL, ORDER, ..> (a job of synchronous code), whose
constant arguments record what the macro assumed. These markers are how the driver finds the
levels to check (cargo psync check).
The diagram draws the forms in the order each depends on the previous one. rustc does not run them as fixed passes, though: it computes each on demand, as the next section explains.
Queries
rustc is not a sequence of passes. It is a database of queries on a central context,
TyCtxt, usually named tcx. tcx.optimized_mir(def_id) asks for a function’s optimized MIR;
rustc computes it on first use (building THIR, then MIR, then running the MIR passes) and caches
it. The driver asks for little else:
| Query | What psync uses it for |
|---|---|
tcx.hir_body_owners() | every function, closure and constant with a body in this crate |
tcx.optimized_mir(def_id) | the body to walk |
tcx.is_mir_available(def_id) | whether a body exists here (another crate’s non-generic function has none) |
Instance::try_resolve(tcx, env, callee, args) | which function a call really runs: a trait method on a known type resolves to its impl |
tcx.def_path_hash(def_id), tcx.stable_crate_id(krate) | stable names for summary files |
tcx.trait_of_assoc(def_id), tcx.associated_item(..).trait_item_def_id() | which trait a method belongs to, and which trait method an impl method implements |
Why optimized MIR, and not the HIR or THIR? MIR is the form where a function is a graph of
simple statements and calls are terminators with an explicit callee. ?, for, .await
and method syntax are all gone. A call fs::write("cache.json", text) is one terminator:
_4 = std::fs::write::<&str, String>(const "cache.json", move _5). Walking every block’s
terminator visits every call the function can make, and nothing else.
Names that survive between compilations
Inside one compilation, a definition is named by a DefId: a crate number and an index into
that crate’s definitions. Crate numbers are assigned per compilation, so the DefId of
helpers::stamp differs between compiling helpers and compiling app (crate 0 is always the
crate being compiled). The index is no better as a name: it depends on the order of definitions,
so adding a function shifts it, and two versions of a crate can share a name. A summary file written
during one compilation must be read in another, so it needs a name that is the same in both.
That name is the DefPathHash: a 128-bit hash of the definition’s full path (helpers →
stamp), whose first half is the crate’s StableCrateId, itself a hash of the crate name and
its -C metadata (which cargo makes unique per package version). In the file above, both keys
start with 11486981337079494651, the crate_id of helpers. rustc uses the same hashes for
incremental compilation, for the same reason.
compiling helpers compiling app
───────────────── ─────────────
DefId(0:4) = stamp DefId(18:4) = helpers::stamp
│ def_path_hash │ def_path_hash
▼ ▼
DefPathHash(11486981337079494651, 10293074283500572899) ← the same key
│ │
└──▶ helpers-StableCrateId(...).json ───────┘ lookup
Inside one crate: walking MIR
For each function, Analyzer::local walks the optimized MIR once:
- each
Callterminator with a known callee goes toAnalyzer::call, which first runsInstance::try_resolve, so<FileStore as Store>::checkpointis found when the type is known; - a call of
std,core,tokioor similar is classified by path (std::fs::writewrites a file; a string constant argument becomes the target); - a call of a function in the same crate becomes an edge to that function, followed later;
- a statement
_0 = {closure@..}or{coroutine@..}is also an edge: anasync fnreturns a coroutine, and its body is where the work is; - a call through a function pointer is opaque.
Per-argument effects need to know what each argument of a call holds. sources reads every local
of the body once:
- A parameter is followed only if it is never assigned again and never borrowed mutably. Then it still holds what the caller passed.
- Any other local is followed only if it is assigned exactly once, from a copy, a move or a
shared borrow of a followed local (through
*), from a string constant, or from a standard-library conversion that keeps the value (as_ref,deref,to_path_buf,into, …) of one. - Anything else, such as
p.push("x")on a copy ofp, is unknown.
An edge records what its call passes, and absorbing a callee’s summary substitutes it. The
link step and dyn calls clear arg: the parameter is the implementation’s, not the call’s.
An async fn keeps its parameters in its coroutine. The function’s body only builds the
coroutine, _0 = {coroutine} { path: copy _1, data: copy _2 }, and the coroutine’s body reads them
as its captures, copy ((*_7).0), where _7 = copy (_1.0) is the pointer inside the
Pin<&mut Self>. Across an await they are first saved in a slot of the suspended state,
((*_7) as variant#3).0, and read from there. sources therefore follows three kinds of values:
locals, captures and slots. In a closure or coroutine, Param(k) means capture k, and the edge
from the body that builds it passes the sources of its operands. A slot is followed like a local
that is assigned once.
Awaiting the future reaches the coroutine a second time, through Future::poll, whose argument
is the Pin and says nothing about the captures. That edge would add the same effects with an
unknown target. It is skipped when the polled value comes, through into_future,
Pin::new_unchecked, borrows, moves and slots, from a call in the same body of the async fn
that builds that coroutine, because that call already brought its effects with the arguments
substituted. A future that comes from anywhere else, such as a parameter, keeps the edge.
keep in the fixture writes after an await:
async fn keep(path: &str, data: &str) -> std::io::Result<()> {
ready().await;
std::fs::write(path, data)
}
Its summary is Fs Write arg 0. keep("x.json", ..) and keep("y.json", ..) are two different
files (keep_both, accepted), and keep("x.json", ..) twice is a conflict (keep_same). An
async closure’s body is another coroutine, built by the closure. It is not followed yet.
The edges form a call graph, and a function’s summary is its own effects plus the summaries of everything it calls:
S(f) = own(f) ∪ ⋃ { S(g) : f calls g }
Recursion makes the graph cyclic, so summarize groups functions into strongly connected
components with Tarjan’s algorithm (callees before callers) and iterates each component until no
summary grows. Summaries only grow and there are finitely many effects, so this ends, and every
member of a cycle gets the effects of the whole cycle. This is the least solution of the equation
above. It is also exactly what Valid in Footprint.lean checks: each summary covers its body
with the calls read from the summaries.
Across crates: one file per crate
When cargo compiles app, helpers was compiled before it, by the same driver, which wrote
target/psync/summaries/helpers-StableCrateId(11486981337079494651).json. A call from app to
helpers::stamp cannot be followed into a body, because app’s compilation does not have
stamp’s MIR. rustc stores a function’s MIR in the crate’s metadata only when other crates
need it to generate code: generic functions, which are compiled anew for each type they are used
with, and #[inline] functions, whose body is copied into the caller. An ordinary function is
compiled once, in its own crate, and only linked. Even for a generic callee, the driver reads the
callee’s summary rather than its MIR, so that every crate is analysed once. The driver looks
the call up instead:
app's MIR: _7 = helpers::stamp(move _8) -> ...
│
│ def_path_hash
▼
summaries/helpers-*.json ── functions[DefPathHash(1148…, 1029…)] ── Fs Write (via std::fs::write)
│
▼
sync_dirs: Fs Write, via helpers::stamp -> std::fs::write
A function missing from a summarized crate’s file has no effects: the file omits functions whose
summary is empty, and crate_id tells the driver the crate was summarized. For a crate with no
file, the driver falls back to the macro’s rule. A call from your code to an async function
named by a verb is classified by the verb, and any other call has no effects.
Two rules keep library summaries honest. Inside crates.io and git crates, verbs are never used:
only real I/O counts (files, environment, processes, output). Socket traffic is left out there,
because inside an HTTP client every request, a GET too, is a socket write. Verbs apply only at
the boundary, to an async function of a published crate called from your workspace, as
cargo psync check explains.
The link step: dyn across the whole build
A call through dyn Store cannot be resolved while compiling the caller, because an
implementation may live in a crate compiled later. The fixture’s snapshot calls
store.checkpoint() on a &dyn Store:
pub trait Store {
fn checkpoint(&self) -> Pin<Box<dyn Future<Output = io::Result<()>> + '_>>;
}
impl Store for FileStore {
fn checkpoint(&self) -> Pin<Box<dyn Future<Output = io::Result<()>> + '_>> {
Box::pin(async { std::fs::write("store.db", b"x") })
}
}
async fn inspect_db() -> io::Result<usize> {
Ok(std::fs::read("store.db")?.len())
}
#[graph]
pub async fn snapshot(store: &dyn Store) -> Result<usize, Error> {
store.checkpoint().await?;
let n = inspect_db().await?;
Ok(n)
}
The tokens say nothing about store.db, so the macro puts the two awaits in one level. The
driver records the call as deferred, keyed by
the DefPathHash of the trait method Store::checkpoint, and each crate’s file lists which of
its methods implement which trait methods (impls).
After the build, cargo psync runs the link step (psync_check::link) over all summary
files at once:
every crate's file ─┐
├─▶ link: for each deferred trait method t,
impls: t → [i, …] ──┘ effects(t) = ⋃ summary(i) over implementations i,
following their own deferred calls (transitively)
│
┌──────────────────┴──────────────────┐
▼ ▼
linked.json (for the driver) facts.tsv (for the macro)
This is class-hierarchy analysis over a closed world: the build. A second cargo check pass
gets linked.json through PSYNC_LINKED, and now store.checkpoint() writes store.db. Two effects
conflict when one writes and both may reach the same resource (same domain, targets that may
be equal), so the driver reports a conflict between it and inspect_db(), which reads store.db,
in the same level. After that pass the link step runs again, because the summaries now include
the resolved effects, and facts.tsv must be written from them.
Only traits of your workspace are deferred. A dyn call of a published crate’s trait
(AsyncWrite, tower::Service) is opaque: its implementations need not be in the build at all. The driver registers
PSYNC_LINKED_STAMP as an environment dependency of each workspace crate, so cargo rechecks a
crate exactly when the linked resolution changes. A plugin implementing Store outside the build
is the closed world’s limit.
Facts: back to the macro
The macro runs before any of this, on tokens. To let it schedule with what the compiler knows,
the driver also writes one fact per call site inside a #[psync::graph] function (the
calls field of the summary file, keyed by file:line:column), and the link step turns them,
with dyn calls resolved, into facts.tsv. One line per call:
app/src/lib.rs:23:5 warm 0 0 fs␟w␟cache.json
app/src/lib.rs:51:9 stamp 0 0 fs␟w␟
app/src/lib.rs:110:11 checkpoint 0 0 fs␟w␟store.db
The columns are the call site (file, line and column of the callee’s name), the name as written,
whether it may panic, whether some callee was opaque, and the effects (␟ separates domain,
access and target; an empty target is unknown). A fourth field j says the target is the call’s
argument j, where 0 is a method’s receiver. The macro then takes the target from the argument
as written: write_and_make_executable(&apprun, &data) writes whatever apprun names. cargo psync build runs the compiler with PSYNC_FACTS set to the
file’s path, and the macro opens and reads it. It does so twice: once under cargo check, so the
driver can check the schedule built from the facts, and finally under cargo build, which
produces the program. The macro computes the same file:line:column key from its
tokens’ spans, and uses a fact only if the name there still matches, so a fact from before an
edit is ignored, never misapplied. The generated code reads option_env!("PSYNC_FACTS_STAMP"),
which makes cargo rebuild an annotated crate when the facts change.
The whole loop:
cargo psync build
1. cargo check, RUSTC_WRAPPER=psync-driver every crate, in dependency order:
summaries + impls + call facts → summaries/*.json
2. link → linked.json, facts.tsv
3. cargo check again, PSYNC_LINKED only if step 2 resolved deferred calls: the
driver re-checks with them, then links again
4. cargo check, PSYNC_FACTS the macro schedules with facts; the driver
checks that schedule too
5. cargo build, PSYNC_FACTS the real build, the same schedule
Dependence graphs: which branch decides a call
A summary says what a function may do. It does not say when. To find a function’s critical path
under each condition (Predicting a schedule), psync also needs to know which branch decides whether
each call runs. That is control dependence, the second half of the program dependence graph
(Related work).
After every check, the driver writes one for each #[psync::graph] function and local async fn, and for the closures and async blocks in them, to target/psync/pdg.
cargo psync pdg FUNCTION prints them. For the fixture’s guarded:
pub async fn guarded(path: &str) -> std::io::Result<()> {
let n = std::fs::read_to_string(path)?.len();
ready().await;
if n > 3 {
std::fs::write(path, "long")?;
}
Ok(())
}
guarded::{closure#0}
b29 line 253 call std::fs::read_to_string [read file (parameter 0)]
b7 line 254 call ready if b2 (line 253, `?` on b29) = ok
b13 line 254 await if b2 (line 253, `?` on b29) = ok
b16 line 256 call std::fs::write [write file (parameter 0)] if b15 (line 255, if on b29) = true
Each line is a point of interest: a call with effects or into the crate, or an await. It shows the
MIR block, the source line, and the branches the point depends on. guarded::{closure#0} is the
coroutine that holds the async fn’s body. “Parameter 0” is its first capture, path.
The algorithm. Block n is control dependent on the edge a -> b when every path from b
to the exit passes n (n post-dominates b), and not every path from a does. Post-dominators
are dominators of the reversed graph, computed from a virtual exit with Cooper, Harvey and
Kennedy’s iterative algorithm. Then, for each edge out of a branch, the walk goes up the
post-dominator tree from the edge’s target to the branch’s own immediate post-dominator. Every
block on the way depends on that edge (psync-check/src/pdg.rs, with unit tests for a diamond,
an early return, a loop and a loop without exit). Dependence is direct. The write above depends
on the if, and the if on the ?, so the write runs only when both allow it.
Undoing the state machine. optimized_mir of an async body is already a state machine. It
starts with a switch on the saved state, and each .await stores a state and returns Pending.
Read literally, everything would depend on that first switch (switch = 0, as the test shows
when the undo is removed). Before computing dependence, the driver rebuilds the source-level flow:
- the state switch is not a branch, and the first block goes only to the unresumed state’s target;
- each suspension (
SetDiscriminant(state k)followed byreturn) continues at the block the switch sends statekto; - the
Pollswitch of an.await’s own polling loop is not a branch, and an await takes the guards of the poll before it.
Edges into cleanup blocks are left out, so unwinding is not a branch. Labels come from the
switched value. An enum’s variant names it (Some, Err), a bool is true or false, and a
? (its ControlFlow switch, marked by the desugaring) is ok or exits.
Data edges. on b29 says the test uses what the call in block 29 returned. The ? tests the
read’s own result, and the if tests n, its length. For a call, uses lists the calls whose
results reach its arguments. In the fixture’s chained, the string read before the await is
written after it:
chained::{closure#0}
b27 line 263 call std::fs::read_to_string [read file (parameter 0)]
b4 line 264 call ready if b2 (line 263, `?` on b27) = ok
b11 line 264 await if b2 (line 263, `?` on b27) = ok
b13 line 265 call std::fs::write [write file (parameter 1)] uses b27 if b2 (line 263, `?` on b27) = ok
The flow is computed per value, flow-insensitively, as a fixpoint. A value holds the calls its
assignment’s operands hold. It follows moves, copies, borrows, casts, aggregates, and slots that a
coroutine keeps across an await (the same roots as the async summaries).
A call that is a point holds itself. Any other call, such as branch (the ?), unwrap or
into_future, holds what its arguments hold. Being flow-insensitive, it may add an edge, for a
local reused in a loop for example, but it does not miss one through these steps. Writes through
raw pointers, and values that reach a call only through memory it reads behind a reference it
got earlier, are not followed. The test fails when non-point calls do not pass their arguments
through.
Joins. In a rewritten function, the statements that run concurrently are async blocks (or,
in Phase II, closures run as jobs on threads), each with a graph of its own. The body that joins
them lists them, read back from the same markers cargo psync check uses
(Adding a check):
keep_both::{closure#0}
join 1: keep_both::{closure#0}::{closure#0} (statement 0) || keep_both::{closure#0}::{closure#1} (statement 1)
b9 line 223 await
keep_both::{closure#0}::{closure#0}
b7 line 225 await
b15 line 225 call keep [write file "x.json"]
stash_both
join 1: stash_both::{closure#0} (statement 0, thread) || stash_both::{closure#1} (statement 1, thread)
Each chain is listed with its statements, by position in the rewritten block, and its tags:
may exit, speculate, independent, and thread for a Phase II job. A prefetched loop is
listed as prefetch:, the async closure that runs ahead for later items, tagged the body may end the loop when it can. Together, the joins and each chain’s guards and data edges give the
conditional critical path (Predicting a schedule) its graph. A path through a function is one chain per join,
under the guards that hold.
Loops. Each loop of a body is listed with how often it runs and what runs in it.
backup_each in the fixture has a for loop whose body may end it, and a while loop around an
await:
backup_each::{closure#0}
loop b2 (line 272): runs once per item of `std::slice::Iter<'_, std::string::String>`: b5, b16; leaves at b3 = None, b7 = exits, b10 = true, b18 = exits
loop b23 (line 280): runs until a branch leaves it: b24, b30; leaves at b23 = false
b5 line 273 call std::fs::read_to_string [read file] if b3 (line 272, match on `Option`) = Some
b16 line 277 call std::fs::write [write file] uses b5 if b10 (line 274, if on b5) = false
A loop is found from its back edge: an edge to a block still on the depth-first search’s stack.
Its blocks are those that reach that edge without passing its header. Rust compiles to reducible
control flow, where these are exactly the natural loops that dominators would find
(natural_loops in psync-check/src/pdg.rs). A loop that calls Iterator::next is a for
loop, and runs once per item of the iterator, whose type is printed. Any other loop runs until
a branch leaves it. Its exits are the branch edges that leave its blocks: here the items running
out (b3 = None), the two ?s (exits) and the break (b10 = true). Edges to
unreachable are left out. An await’s poll loop is not a loop of the program, so it is not
listed. A loop inside another one says so (inside loop b2).
The trip count itself is a run-time quantity: the length of the slice, or how often the condition holds. The summary says what it depends on. The conditional critical path multiplies a loop body’s cost by the trip count it measures.
select! and join! in your code
psync generates no select!, but the code it reads often has one. Each such macro expands to the
same shape: pin the futures, poll them all inside one poll_fn, await that, and run the winner’s
handler. In MIR, that is one await, and nothing more says which calls belonged to which side of
it. The graph finds the macro again from the await’s span, which records the macro that wrote it
(select, select_biased, join or try_join, the names psync-graph also treats as
barriers). It then sorts the calls you wrote inside the macro’s call:
- futures: calls that can run before the await, because some path from the start of the body reaches them without passing it;
- handlers: calls that every such path reaches only through the await.
The driver fixture’s race::first_of selects between two fetches and keeps the winner:
select! {
x = fetch(a) => keep(&x),
y = fetch(b) => keep(&y),
}
race::first_of::{closure#0}
select! b11 (line 364): futures b30, b2; handlers b15, b17; the first to finish wins, the others are dropped
b11 line 364 await
b15 line 365 call race::keep [write file "winner.txt"] uses b2, b30 if b12 (line 364, match on `Result` on b2, b30) = Ok
b30 line 365 call race::fetch [read file (parameter 0)]
b2 line 366 call race::fetch [read file (parameter 1)]
b17 line 366 call race::keep [write file "winner.txt"] uses b2, b30 if b12 (line 364, match on `Result` on b2, b30) = Err
The await is its whole poll loop, not just the block where it yields: a poll that is Ready the
first time never yields, and the first version of this analysis, which cut only the yield,
counted both handlers as futures. The loser of a select! is dropped where it stopped, which is
why cargo psync check warns about cancellation (Cancellation).
For diagnosis, the time of a select! is its fastest future, and of a join! its slowest.
The fixture’s select! is a small one written like tokio’s. The driver recognizes the macro by its
name, so a macro called select that does something else would be misread.
Effects in the graph are written in terms of the body’s own parameters. For a closure or async block, those are its captures.
Entry points: where a request starts
A dependence graph is per function. To diagnose a request, you need the function the request
enters by, and then everything it calls. cargo psync pdg --entries lists the entry points the
driver found:
main, from rustc’sentry_fnquery;- a function or closure of the crate passed to a web framework’s registering call: axum’s
routing::get(h),post(h), … andMethodRouter::post(h), …; actix-web’sto(h), which its#[get("/x")]macros also expand to.
The driver reads every body of the crate for calls into the crates axum and actix_web. A
handler is an argument whose type is a local function item (ty::FnDef) or a closure. The
route comes from the string literal that names it. axum names it downstream: the MethodRouter
that get(h) returns is moved into .route("/users", ..), so the driver follows the call’s
result through moves and the framework’s calls until a route with a literal. actix-web names it
upstream: Resource::new("/items").name("items").to(h), so the driver follows to’s receiver
back to the call that made it (new, resource or scope, and not name, whose literal is
not a path).
The driver fixture registers four handlers, with stand-ins for both frameworks (same crate names and shapes, no server):
pub fn app() -> axum::Router {
axum::Router::new()
.route("/users", axum::routing::get(list_users).post(create_user))
.route("/health", axum::routing::get(|| async { "ok" }))
}
pub fn items() -> actix_web::Resource {
actix_web::Resource::new("/items").name("items").to(list_items)
}
$ cargo psync pdg --entries
app: axum post /users -> routes::create_user (line 384, registered at line 396)
app: axum get /users -> routes::list_users (line 375, registered at line 396)
app: axum get /health -> routes::app::{closure#0} (line 398, registered at line 398)
app: actix_web to /items -> routes::list_items (line 388, registered at line 404)
In MIR, the literal usually reaches the call through a local (_3 = const "/users", then
route(.., move _3, ..)), so the driver records which locals hold which string literals. The
first version read only constants passed directly, and found every handler but no route. A
build script’s main runs at build time, so it is not listed.
--from HANDLER prints what one request runs: the handler’s graph, then the graph of every
function of the crate it calls, transitively. A trace of that request
(Predicting the speedup) is joined to these graphs.
$ cargo psync pdg --from routes::list_users
routes::list_users::{closure#0}
b7 line 376 await
b25 line 376 call ready
b9 line 377 call routes::load [read file "users.json"]
b15 line 377 await
routes::load::{closure#0}
b7 line 381 call std::fs::read_to_string [read file "users.json"]
On a real project, rumqttd (the MQTT broker of bytebeamio/rumqtt, with axum 0.7), --entries
lists the nine routes of its console, as written in link/console.rs, and the broker’s main:
rumqttd: axum get / -> link::console::root (line 62, registered at line 48)
rumqttd: axum get /config -> link::console::config (line 66, registered at line 49)
...
rumqttd: axum get /device/:device_id -> link::console::device_with_id (line 86, registered at line 51)
...
rumqttd: axum post /logs -> link::console::logs (line 147, registered at line 56)
rumqttd: main -> main (line 34)
--from link::console::device_with_id says the handler has nothing to overlap: it puts a
message on a channel with a synchronous send and answers, with no await. The broker’s work
happens in its router thread, which the message reaches, not in the handler. Following a request
across a channel is not built.
Not found yet: routes built from a const or a format! (the entry is listed without a route),
handlers wrapped in a service before registering, other frameworks, and UI event handlers
(Dioxus’s onclick, GPUI’s actions), whose entry is a closure handed to the framework at render
time.
What is proved, and what is assumed
- Proved (
verify/Footprint.lean), for a fragment of MIR with places, assignments,if,whileand calls by reference: valid summaries over-approximate, and a schedule whose certificate covers them equals the sequential program. - Assumed for real Rust: that the driver’s classification of
stdand tokio calls by path is right; that MIR’s references, interior mutability andunsafebehave as the fragment’s places do, which the borrow checker makes true for safe code; that opaque calls are reported, not missed; and the closed world of the link step.
Prior work and novelty
| Work | What it does | How psync differs |
|---|---|---|
| Zhou, Sun, Criswell (arXiv 2023) | Summarizes every MIR function per crate, analyses the summaries together, and feeds the result back, after ThinLTO. | The same architecture. psync’s summaries hold outside-world effects and their targets, for scheduling, instead of unsafe memory accesses. |
| MirChecker (CCS 2021) | Abstract interpretation on MIR for crashes and memory bugs. Calls into dependency crates are skipped. | psync’s summaries cross crates, and dyn calls are resolved at link time. |
| Charon and Aeneas (2022–2025) | Extract MIR into a cleaner form (LLBC) and translate it to a prover. | psync uses Charon for its footprint proof (verify/CharonDrain.lean). |
| Prusti (OOPSLA 2019) | Verifies Rust functions against specifications the user writes. | psync needs no specifications for its summaries; it proves schedules, not functional correctness. |
Writing a rustc driver and hooking it into cargo is standard engineering. The contribution is what the summaries contain and how the macro uses them.
Exercises
- Run
cargo psync buildonpsync-check/tests/fixtures/hidden(withCARGO_TARGET_DIRset), and findstamp’s key inhelpers-*.json. Why are its first 64 bits the same as the file’scrate_id? Then find the call ofstampinapp-*.json’scalls: which effects did it get? - Add a second implementation of
Storethat only readsstore.db. What does the link step give forStore::checkpointnow, and does the conflict insnapshotremain? - Why can
app’s compilation not simply calltcx.optimized_mironhelpers::stamp? (Hint:tcx.is_mir_available.) Which functions ofhelperswould have MIR inapp’s compilation, and why does the driver still use their summaries?
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, each only after every statement before it has run. The function exits at the same place, with the same value.replay_correctinverify/Schedule.leanproves this rule. - 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. For files whose path can be evaluated ahead this is checked at run time, and with a duplicate the loop runs as written (Loop rewriting).
- Hints are true.
#[psync::independent],#[psync::fresh],#[psync::speculate]andcalls = ..turn checks off. - Calls that panic are not exits, without facts. The macro cannot tell which calls may
panic, so a write may run beside an earlier
unwrap()that panics, which sequential code would have stopped at.cargo psync checkreports such a write, and with compiler facts the macro keeps it behind explicit panics.
Machine-checked
verify/Schedule.lean proves the scheduling argument in Lean 4. It models a program as operations
with footprints (what each may read and write) and shows:
- independent operations commute;
- any interleaving of a level’s pairwise-independent chains equals running the chains one after another, and so does a whole schedule of levels;
- an order that moves operations earlier only past independent ones equals the program as written;
- operations that write nothing, which are the only ones psync may run past an exit, change nothing;
- recording every outcome and replaying the first exit in program order, after everything has
run, gives the sequential state and exit (
replay_correct).
So the concurrent execution ends in the state of the sequential program, provided two things
hold. The footprints must be right, and psync must draw an edge between every two operations that
are not independent. Those are the analyses’ obligations. Tokens cannot discharge them alone,
which is why cargo psync check verifies them against the compiled callees.
The generated Rust is not modeled. rustc checks it.
Exercises
For each mistake, say what catches it: rustc, psync’s rules, cargo psync check, or nothing
(one of your assumptions). Then say how to protect against it.
- Two concurrent chains both call
queryon a&mut Connthat a method returned. - Two chains call
self.primary.put(k, v)andself.replica.get(k), two handles to one database. notify_user(id).awaitruns before an earlier?would have left, and its body sends an email.- A prefetched loop calls
store.delete(item.key)for a list with a duplicate key. - A loop writes
fs::write(dir.join(name), ..)for a list with a duplicate name.
Answers
- rustc: the generated code needs two
&mutborrows at once and does not compile (&mutin two branches). Fix it with#[psync::seq]. - Nothing: different receivers are assumed to be different resources (assumption 2). Name the
relation with
effects(..), keep the read in place with#[psync::seq], or use one handle. - Nothing, usually.
notify_userhas no verb, so the macro assumes it reads (assumption 1).cargo psync checkreads its body, but a library’s summary leaves out socket traffic, so an email sent through an SMTP or HTTP client is not recorded. It would catch a process (say,sendmail) or a file write. Mark the call as a write witheffects(write(notify_user)), or usestrict, which makes every unclassified call a write. - Nothing: per-item targets of services are assumed to differ (assumption 4). Deduplicate the
list first, or mark the loop
#[psync::seq]. - psync’s rules, at run time: the path is total, so the generated code compares all items’ paths and runs the loop as written when two are the same file.
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 (cargo psync check, which knows more, exempts a read of the environment) | |
| SQL | an awaited chain with an SQL statement as a string literal: sqlx::query(".."), sqlx::query!(".."), client.query("..", &[]), client.execute("..", &[]) | SELECT, SHOW, EXPLAIN, VALUES, and a WITH that only selects | every other statement (INSERT, UPDATE, DELETE, DDL, BEGIN, SET, …), and reads that lock or write (FOR UPDATE, INTO, nextval, EXPLAIN ANALYZE) | none: an SQL write conflicts with every service call |
| HTTP | a Method::X argument (client.request(Method::PUT, url), any path ending in Method::X) or a builder’s .method(Method::X) / .method("X") | GET, HEAD, OPTIONS, TRACE (RFC 9110’s safe methods) | every other method | the URL argument (.uri(..) or .url(..) for a builder), compared as a path; a POST or an unknown method may touch anything on the service; the receiver is the service |
| Redis | the redis crate’s command methods (con.hget(k, f), con.lpush(q, x)), and redis::cmd("..") with a literal command | hget, mget, lrange, smembers, zrange, ttl, … | hset, hdel, mset, sadd, zadd, get_del, …; list pushes and pops and stream appends are ordered; a redis::cmd psync cannot read | the key (the first argument, or the first .arg(..)) |
| 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. A receiver bound inside one statement (its own socket or client) is a different receiver from another statement’s, even with the same name. -
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. -
An HTTP method decides.
client.request(Method::GET, url).send().awaitreads, althoughsendis an ordered verb: the method says what the request does, RFC 9110 says GET, HEAD, OPTIONS and TRACE are safe (they do not change the server), and a write is everything else. TwoGETs of one URL run together; aGETand aPUTof it keep their order; aPUTto another literal URL does not conflict. URLs compare as paths, so aDELETEofhttps://h/akeeps its order with aGETofhttps://h/a/x. APOSTmay do anything on the server, so it conflicts with every request to it (testhttp_methods_decide_by_rfc_9110). These are the rules of the HTTP specification in What psync guarantees. Safe is a promise the server makes. A server that changes state on aGET(a counter, a lazy migration) breaks it. The method decides before any verb list, soeffects(write(..))cannot override it; mark such a statement#[psync::seq]. -
Redis commands are known by name. The
rediscrate names its methods after the commands, and most command names are not verbs:hget,zcard,lpush. psync knows them (the list is on Names psync knows), matched before the verbs, becauseget_deldeletes although its first word reads.redis::cmd("HGET").arg(key)is classified by its command, like an SQL statement, with the key as the target;redis::cmd(name)with a command psync cannot read is a write (testredis_commands_classify). In the audit this mattered. loco’srequeue(web-34) removes a job from the processing set withconn.srem(..)afterjob.to_json()?.sremused to be unclassified, so a read, and psync ran it before the?: had serialization failed, the job would already have left the processing set, which sequential code never does. Nowsremis a write and waits for the?; web-33 is the same shape withzrem. -
SQL is decided by the statement.
queryis a read verb, so until this rulesqlx::query("DELETE FROM t").execute(db).awaitcounted as a read, and ran at the same time as aSELECTon the same table. Now the statement’s first word decides, and the name of the method does not. A statement psync cannot read, in a call it knows runs SQL (sqlx::query(&sql),diesel::sql_query(s)), may be anything, so it is a write. The database may be behind any receiver, and the statement’s tables are not compared, so an SQL write is ordered with every service call around it (testsql_statements_decide_read_or_write).#[psync::graph] async fn purge(db: &Pool) -> Result<(), Error> { let old = sqlx::query("SELECT id FROM jobs WHERE done").fetch_all(db).await?; let n = sqlx::query("SELECT count(*) FROM jobs").fetch_one(db).await?; sqlx::query("DELETE FROM jobs WHERE done").execute(db).await?; Ok(()) }region 0: n0: old = fetch_all()? [await] {read service (sqlx::query: SELECT)} n1: n = fetch_one()? [await] {read service (sqlx::query: SELECT)} n2: execute()? [await] {write service (sqlx::query: DELETE)} n0 -> n2 (write service (sqlx::query: DELETE) vs read service (sqlx::query: SELECT)) n1 -> n2 (write service (sqlx::query: DELETE) vs read service (sqlx::query: SELECT)) level 0: n0 || n1 level 1: n2The two
SELECTs run together, and theDELETEwaits for both. (It would wait anyway, for their?s, but theSELECTedge is also the reason underspeculate.)
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".- Two
format!strings whose placeholders are plain names or fields are compared piece by piece.format!("{dir}/AppRun")andformat!("{dir}/linuxdeploy")agree up to{dir}/and then differ in their text, so they name different files. Within one region a name has one value (a statement that rebinds or changes it is ordered with both), so this is exact. They still conflict if they first differ at a placeholder ({dir}against{other}, which may hold the same text), if one is a directory of the other ({dir}/aand{dir}/a/b), if the format specs differ ({dir:?}), or if a placeholder is computed ({}ofself.base(), which may return something new each call). - A target that is just a name,
fs::write(&a, ..), takes the value of the block’s latestlet a = ..;before it, when that binding is notmutand its value is a literal, aformat!or a join.let a = dir.join("a.json")names the file{dir}/a.json, the same template asformat!("{dir}/a.json"). A join counts only when the name cannot be absolute: its text must start with a character other than/or\, and not with a drive letter such asC:, becausePath::joinwith an absolute path replaces the base. The binding’s value must not depend on amutbinding, and a laterletof a name the value depends on forgets it. - Anything else computed may be anything. Two such file paths can still run concurrently, in
asynchronous code and on threads, and they are compared at run time
(Paths compared at run time). So can two
computed URLs of
Method::Xrequests, and two computed keys ofredis::cmd(..)(URLs and Redis keys).
Path::new(x), PathBuf::from(x) and the like name what x names, so
Path::new(&format!("{dir}/one")).exists() reads the file {dir}/one.
Like literals, templates compare paths as text. Two different names in one directory are taken to be different files, even though a symbolic link could make them one.
path.exists(), is_file(), metadata() and the other methods of std::path::Path that read
the file system are file reads of the receiver. They are also kept as reads of a service named by
the receiver, in case the receiver is some other type with a method of that name. Until this
change they were only the service read, so in synchronous code if !p.exists() { .. } and a
later fs::write(&p, ..) could run at once (test path_exists_reads_the_file_system).
Reads never conflict with reads. Here is a read-check-recreate function:
#[psync::graph]
async fn replace(api: &Api, limits: &Limits, name: &str, obj: &Obj) -> Result<(), Error> {
let old = api.get(name).await?;
let quota = limits.get(obj.ns).await?;
api.delete(name).await?;
api.create(obj).await?;
Ok(())
}
and what psync builds for it:
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. For files, psync checks it at run time. When every per-item path can be evaluated ahead
(dir.join(name), format!("{name}.json")), the generated code compares the paths of all items
first and runs the loop as written if two items share a file that one of them writes
(Loop rewriting). For other targets, or a path that
comes from awaited work, 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 |
#[psync::graph(calls = ..)] | how the whole function’s calls behave | see Marking a whole function |
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.
Marking a whole function
calls = .. says, for the whole function, what you know about its calls:
| Option | Unclassified calls | Statements’ effects |
|---|---|---|
| none | read (write with strict) | ordered where they conflict |
calls = read | read, even with strict | ordered where they conflict |
calls = write | write (the same as strict) | ordered where they conflict |
calls = write_independent | write: never run ahead of an earlier exit | commute: no effect order between statements |
calls = independent | read | commute: no effect order between statements |
Calls that psync does classify keep their verb: under calls = read, db.put(k).await is still
a write. The independent forms put #[psync::independent] on every statement, so data
dependencies and the exit rule still hold. Only conflicts between effects are lifted.
calls = write_independent fits a function that sends unrelated writes, such as a handler that
notifies several systems. None of them may happen if an earlier step failed, but they need not
wait for each other. A write never runs ahead of an earlier exit, so this helps only when the
writes have no ? between them. Check their results afterwards:
#[psync::graph(calls = write_independent)]
async fn on_signup(api: &Api, mail: &Mail, crm: &Crm, id: u64, email: &str) -> Result<(), Error> {
api.check_quota(id).await?;
let sent = mail.welcome(email).await;
let tracked = crm.track(id).await;
sent?;
tracked?;
Ok(())
}
welcome and track have no verb that psync knows. Here is what psync-expand prints for each
option:
| Option | Schedule |
|---|---|
| none | level 0: n0 || n1->n3 || n2: the email may go out although check_quota failed |
calls = write | n0, then n1, then n2 || n3, then n4: safe, and one call at a time |
calls = write_independent | n0, then n1->n3 || n2, then n4: after the quota check, both at once |
With mail.welcome(email).await? on each line instead, every call would wait for the one
before it, because that one’s ? might leave.
The test calls_marks_the_whole_function in psync-graph checks every row of the table.
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 to the macro. An awaited call to your own helper is classified by the
helper’s name, not by what its body does.
cargo psync checkreads the bodies and reports where that guess was wrong. - Panics are not exits, from tokens alone. The macro cannot tell which calls may panic, so
a write may still run ahead of an earlier call that panics. The compiler can:
cargo psync checkreports such a write, and with compiler facts the macro keeps it in order.
Prior work and novelty
| Work | What it does | How psync differs |
|---|---|---|
| ReSynchronizer (ECOOP 2021, Table 1) | Models the file system and the network as one pseudo-variable each; exec, spawn and eval touch everything. | psync’s effects have targets: a path, a URL, a key. A file read waits only for writes that may touch the same file, not for every file write. |
| Deterministic Parallel Java (OOPSLA 2009) | Methods declare reads and writes of nested regions, and the compiler checks that parallel tasks do not interfere. Regions nest, and overlap by prefix. | psync infers its effects instead of asking for annotations, and its places (w/fs/t/<path>, see Certified schedules) resemble DPJ’s region paths: nested, overlapping by prefix, here for files, URLs and keys. |
| Quasi-Static Scheduling for Safe Futures (PPoPP 2008) | Inserts barriers where a static alias analysis cannot rule out a conflict between futures. | psync’s gates compare the values at run time (paths, and since #197 file identity: device and inode), for resources outside the program. |
| Commutativity analysis (Rinard and Diniz, 1997) | Proves that in-memory operations commute, by symbolic execution. | psync takes commutativity of outside services as a specification (The outside world). |
Exercises
Predict the edges, then check with psync-expand FILE LINE.
-
async fn f1() -> std::io::Result<()> { tokio::fs::remove_dir_all("out").await?; let a = tokio::fs::read("out/a.txt").await?; let b = tokio::fs::read("cfg.toml").await?; Ok(()) } -
async fn f2(client: &Client, id: &str) -> Result<(), Error> { let backup = client.get_account_data("m.megolm_backup.v1").await; client.put_account_data(format!("m.secret_storage.key.{id}"), "{}").await; let key = client.get_account_data("m.secret_storage.key.k1").await; Ok(()) } -
Why doesasync fn f3(&self, id: u64) -> Result<(), Error> { let user = self.db.get_user(id).await?; self.cache.put(id, &user).await; let other = self.db.get_user(id + 1).await?; delete_user(id).await; let again = self.db.get_user(id).await?; Ok(()) }delete_userconflict with bothget_user(id)andget_user(id + 1)? -
async fn f4(api: &Api) -> Result<(), Error> { let cfg = api.get_config("main").await; let out = tokio::process::Command::new("ls").output().await; let home = std::env::var("HOME"); let more = api.get_config("other").await; Ok(()) } -
Which requests run together? Why does theasync fn f5(c: &Client) -> Result<(), Error> { let a = c.request(Method::GET, "https://h/users/1").send().await?; let b = c.request(Method::GET, "https://h/users/2").send().await?; c.request(Method::DELETE, "https://h/users/2").send().await?; let d = c.request(Method::GET, "https://h/groups").send().await?; c.request(Method::POST, "https://h/audit").send().await?; Ok(()) }POSTwait for every other request, even theGETof/groups?
Answers
- One edge,
n0 -> n1 (write file "out" (fs::remove_dir_all) vs read file "out/a.txt" (fs::read)): a directory contains the paths inside it.cfg.tomlis neither, so the level isn0->n1 || n2. The reads may run beforeremove_dir_allreturns, because reads are not held back by an earlier?. - Only
n1 -> n2. The templatem.secret_storage.key.{id}keeps its literal prefix, so it cannot bem.megolm_backup.v1, but it may bem.secret_storage.key.k1. The level isn0 || n1->n2. - Three edges into
delete_user(n3), fromn0,n1andn2, and one out of it, toagain. An awaited free function reaches an unknown service (write service `id` (delete_user)), which may be behind any receiver. Its targetidis computed, and so areidandid + 1, which tokens cannot tell apart, so it conflicts with every read and write around it. Thecache.putwaits foruser(data), andget_user(id)andget_user(id + 1)run together. The levels aren0 || n2, thenn1, thenn3->n4. - A process conflicts with every domain: it could read or write anything. So
n0 -> n1,n1 -> n2andn1 -> n3. The levels aren0->n1, thenn2 || n3. The twoget_configreads would have run together without the command. (cargo psync checkknows more, and lets the environment read through.) - The three
GETs run together (level 0: n0 || n1 || n3): safe methods only read. TheDELETEwaits for theGETof the same URL (a conflict) and for the firstGET’s?(a write may not run before an earlier exit). ThePOSTcomes last: RFC 9110 lets aPOSTdo anything the server decides, so its target is the whole servicec, and it conflicts with every request there,/groupsincluded. Levels:n0 || n1 || n3, thenn2, thenn4. (Check withpsync-expand.)
Checking rewrites: cargo psync check
#[psync::graph] sees only the tokens of the function it rewrites. When it meets
warm().await or session.get_token().await, it can only go by the name. warm has no verb,
so it is assumed to read. get_token starts with get, so it reads. If their bodies write files,
the macro cannot know.
cargo psync check reads those bodies. It runs the compiler with a custom driver, the way
cargo clippy does, that sees the program after type checking. It computes what every function
does to the outside world and compares that with the concurrency the macro generated.
cargo psync check # warnings, like clippy's
cargo psync check --deny # findings are errors (exit status 1), for CI
cargo psync check --notes # also output order, shared Cell/RefCell/Mutex state, cancellation
cargo psync summaries # what each function was found to do
cargo psync pdg guarded # its calls and awaits, and the branches that decide them
It does not change the rewrite. It tells you where the rewrite is wrong, so you can fix it with a
hint (#[psync::seq], #[psync::speculate], effects(..)).
An example
tests/fixtures/hidden in psync-check is a workspace whose rewrites look safe from their tokens:
async fn warm() -> std::io::Result<()> { // no verb: assumed to read
std::fs::write("cache.json", b"{}")
}
async fn load() -> std::io::Result<String> {
std::fs::read_to_string("cache.json")
}
#[graph]
pub async fn start() -> Result<String, Error> {
warm().await?; // these two now run concurrently
let s = load().await?;
Ok(s)
}
cargo psync check reports:
warning: psync runs this concurrently with other work that has a conflicting effect: this does
`read file "cache.json"` (via load -> std::fs::read_to_string), the other does
`write file "cache.json"` (via warm -> std::fs::write)
--> app/src/lib.rs:24:20
|
24 | let s = load().await?;
| ^^^^^
|
note: the conflicting effect
--> app/src/lib.rs:23:12
|
23 | warm().await?;
| ^^^^^
= note: in the code `#[psync::graph]` generated for `start`
The fixture has eighteen annotated functions, each hiding something different. The same run finds more. The first three:
-
session.get_token()writes a file although its name reads. psync starts it beforecheck()?has succeeded (speculative-write):warning: psync starts this before knowing whether an earlier statement exits early, and it does `write file "token"` (via Session::get_token -> std::fs::write); ... --> app/src/lib.rs:43:27 note: the earlier work that may exit --> app/src/lib.rs:42:5 | 42 | s.check().await?; -
A prefetched loop calls
helpers::stamp(&d).await?, a function in another crate whose name says nothing. Its summary, written when the driver compiledhelpers, shows a file write. The loop can end early at the?(loop-speculative-write):warning: psync runs this loop's prefix for every item before the loop body runs, and the body can end the loop early, but the prefix does `write file` (via helpers::stamp -> std::fs::write). ... --> app/src/lib.rs:51:9 | 51 | helpers::stamp(&d).await?; -
With
--notes, two concurrent chains that both use one&RefCell<Vec<u32>>: their updates now interleave (interior-mutability).
Others come from cases explained elsewhere in the book:
| Function | Finding | Explained in |
|---|---|---|
snapshot | conflict: a dyn Store call writes store.db, which the next call reads | Dynamic dispatch |
tour | conflict: visit writes walk.log through mutual recursion with walk | Effects and summaries |
release | conflict: fs::copy writes its second path, site.html | Adding an effect rule |
boot | speculative-write: a write starts before a call that may panic (unwrap) | Adding a check |
gated::read_then_log | conflict: a helper writes a file next to two gated chains, and the gate does not compare it | What it does not check |
Functions with nothing to report get no finding: sizes and walk_then_read read files nobody
writes, and gated::read_then_write’s two paths are compared at run time. The test
(psync-check/tests/fixture.rs) checks each of these findings, and the absence of the others.
Walkthrough: check, fix, build
A small crate, from scratch. One helper’s name hides a file write:
async fn refresh() -> io::Result<()> { std::fs::write("cache.json", b"{}") }
async fn load() -> io::Result<String> { std::fs::read_to_string("cache.json") }
async fn motd() -> io::Result<String> { std::fs::read_to_string("motd.txt") }
#[graph]
pub async fn start() -> io::Result<(String, String)> {
refresh().await?;
let cache = load().await?;
let banner = motd().await?;
Ok((cache, banner))
}
From tokens, refresh, load and motd say nothing, so the macro runs all three at once.
1. cargo psync check compiles the crate with the driver and reports what the schedule got
wrong:
warning: psync runs this concurrently with other work that has a conflicting effect: this does
`read file "cache.json"` (via load -> std::fs::read_to_string), the other does
`write file "cache.json"` (via refresh -> std::fs::write)
psync check: 1 concurrent level(s) and 0 prefetched loop(s) checked in 1 crate(s): 1 warning(s), 0 note(s)
(On a first run the warning can appear twice: the driver checks, links the summaries, and checks again. The summary line counts each finding once.)
2a. cargo psync fix inserts one #[psync::seq] per warning:
refresh().await?;
+ #[psync::seq]
let cache = load().await?;
Run check again and it reports nothing concurrent at all: a seq statement is a barrier, so
motd can no longer overlap refresh either. fix is the smallest edit that is certainly safe,
not the fastest one.
2b. cargo psync build, on the original code, does better. It hands the macro the compiler’s
facts, and the macro schedules with them. With #[graph(explain)]:
psync::graph `start`:
region 0:
n0: refresh()? [await] {write file "cache.json" (refresh, per the compiler)}
n1: cache = load()? [await] {read file "cache.json" (load, per the compiler)}
n2: banner = motd()? [await] {read file "motd.txt" (motd, per the compiler)}
n0 -> n1 (write file "cache.json" (refresh, per the compiler) vs read file "cache.json" (load, per the compiler))
level 0: n0->n1 || n2
psync build (with compiler facts): 1 concurrent level(s) and 0 prefetched loop(s) checked in 1 crate(s): 0 warning(s), 0 note(s)
load waits for refresh, and motd still overlaps both. No hint in the source, and the check of
the new schedule finds nothing. Use build (and check --facts in CI) when you can, and fix
when the code must also be right under a plain cargo build.
Findings are kept per crate between runs, so running check again without changing anything, or
fix straight after check, sees the same findings. (Before this was fixed, a second run reported
“0 warning(s)” for a crate cargo did not recompile, and --deny passed.)
How it works
1. Markers in the generated code
The macro now tags what it made concurrent. Each chain of a concurrent level is wrapped in
maybe_done_at::<LEVEL, ORDER, LAST, EXITS, EXIT_AT, SPEC, INDEP, _>(async { .. }) instead of
maybe_done, and
each prefetched loop prefix in over_at::<LOOP, TERMINATES, SPEC, INDEP, ..>. The const
generics record what the macro assumed:
LEVEL: which join the chain belongs to. It is numbered from 1 within each annotated function, in the order the macro emits joins, so it is not an index into the report’slevels. The driver only compares it: chains with the sameLEVELrun concurrently;ORDERandLAST: the positions of the chain’s first and last statements in its block;- whether it may exit early, and
EXIT_AT, the position of its first statement that may. A write in chain Y is speculative when another chain X may exit at a statement before Y’s last one: sequential code would have left before running it. Chains are interleaved in program order, so X need not start first. A chain whose callees may panic may leave from its first statement; - whether it carries
#[psync::speculate]or#[psync::independent]; - for loops, whether the body can end the loop.
The wrappers are #[inline(always)] calls to the old helpers, so they cost nothing at run time.
2. Effect summaries from MIR
psync-driver is rustc with one extra step after analysis. For every function of the crate it
walks the optimized MIR and classifies every call:
| Callee | How it is classified |
|---|---|
std, core, alloc, tokio, async-std, smol, fs-err | by path: fs::write, File::create and <File as Write>::write_all write files; fs::read_to_string reads; fs::copy(from, to) reads from and writes to, and rename, hard_link and symlink write both paths; net sends and receives; process::Command::output runs a process; env::set_var writes the environment; println! writes standard output (in order) |
| a function in the same crate | its body, recursively, including the closures and coroutines it creates (an async fn’s body is a coroutine). Recursive functions are solved together: each strongly connected component of the call graph is iterated to a fixed point, so every member of a cycle gets the effects of the whole cycle (Effects and summaries) |
an async function (or one returning a future) in a crates.io or git crate, named with a verb (delete_object, list), called from your workspace | the verb, as the macro does for awaited calls. The domain is the type or module the function belongs to (kube::Api::<K>), not a variable name |
| any other function of another crate | that crate’s summary, written when the driver compiled it (no entry: no effects) |
a function pointer, or dyn without a summary | opaque: listed by cargo psync summaries --all |
Names count only at the boundary between your code and a published API. Inside crates from
crates.io or git, verbs are not used at all. A library’s summary keeps only the real I/O it reaches:
files, the environment, processes and output. Socket traffic is left out, because at that level
every request, a GET included, is a socket write. Your workspace crates, including path
dependencies, are summarized fully, and calls between them follow the callee’s body, never its name.
Verbs also apply only to calls that return a future, as the macro applies them only to awaited
calls: HashMap::insert and Serializer::append_pair are not I/O. Blocking clients
(reqwest::blocking, synchronous database drivers) are therefore judged by their bodies’ real I/O
only. Without these rules, in-memory operations look like service writes:
HeaderMap::try_append (“append”), tracing‘s set_interest (“set”) and flatbuffers’
run_verifier (“run”). The first runs on kube-rs and DataFusion reported exactly these.
Calls are resolved exactly: a trait method call resolves to the impl that runs, whenever the types
are known. File paths that are string literals are kept as targets, so "a.txt" and "b.txt" do
not conflict. Each effect remembers the chain of calls that leads to it (via warm -> std::fs::write).
Summaries are written to target/psync/summaries/<crate>-<id>.json for every crate in the build,
dependencies included. Crates are compiled in dependency order, so a crate’s callees in other
crates already have summaries when it is analyzed.
3. Checks
For every function with markers, the driver groups the chains of each level and compares them in program order:
| Finding | When |
|---|---|
conflict | two chains of one level have conflicting effects: same domain, one writes, targets may be the same, and neither is independent |
speculative-write | a chain writes, another chain of the same level may exit at a statement before the writer’s last one (a ?, return, break or continue, or, from any of its statements, a callee that panics explicitly: unwrap, expect, panic!, assert!, unreachable!, todo!), and the writer is not speculate |
loop-speculative-write | a prefetched prefix writes, the body can end the loop, and the loop is not speculate |
interior-mutability (note) | two chains capture the same variable whose type, behind references, Rc, Arc or Box, is a Cell, RefCell, OnceCell, Mutex, RwLock or atomic |
output-order (note) | two chains both print |
cancellation (note) | two or more chains of one level write (outside standard output) in an async function: if its future is dropped, each may stop halfway (Cancellation) |
Every finding the driver reports is one the macro could not see. When the macro does recognize a conflict, it does not put the two chains in one level at all.
On real code
On the kube-rs and DataFusion benchmark branches (11 annotated functions: 6 concurrent levels and 7
prefetched loops), compiling every dependency through the driver from scratch takes 36 s
(kube-rs) and 52 s (DataFusion) on 16 cores. Both report no warnings. kube-rs gets one note:
dynamic_api’s main runs tracing_subscriber::fmt::init(), which may print to stderr,
concurrently with Client::try_default(), which may run a credential plugin process.
The first versions of the driver reported 12 false warnings on these branches. They came from
reading verbs inside libraries (tower::Service::call, HeaderMap::try_append, tracing’s
set_interest), from synchronous in-memory calls (hashbrown::HashMap::insert), and from treating
Metadata::is_dir and File::seek as file writes. The rules above remove them, and the fixture
test keeps the real findings.
Installing
psync-check links rustc’s internal crates, so it builds with a pinned nightly. Its
rust-toolchain.toml selects that toolchain automatically. The crate is not part of psync’s
workspace, so the stable build of psync is unaffected.
cd psync-check
cargo install --path . --locked # installs cargo-psync and psync-driver
cd /your/project
cargo psync check
cargo psync runs cargo check in a separate target directory (target/psync), with
psync-driver as RUSTC_WRAPPER. Your normal build is untouched. The whole build is compiled by
the pinned nightly, the same way cargo clippy compiles it with clippy’s.
Like any cargo check, an unchanged crate is not recompiled, and cargo replays its earlier
warnings. The findings summary covers only crates recompiled in this run.
What it does not check
- Targets computed at run time.
fs::write(&path)writes “some file”. Two such writes conflict, even when the paths differ at run time. The macro can run them concurrently with a gate that orders them when the paths overlap (Paths compared at run time). The gated chain carries agated_by::<ON>()marker, so the driver knows the pair is gated and does not report the file calls the gate compares: calls into anfsmodule made by the chain itself. A file written through another function in either chain (a helper,note(dst)) is not compared by the gate, and is still a conflict. The fixture has both cases:gated::read_then_write(no finding) andgated::read_then_log(a conflict through the helper). - Loop items naming different objects. The macro assumes that targets computed from the loop item differ between iterations. For files whose path it can evaluate ahead, the generated code checks this at run time instead (Loop rewriting). Other targets are still assumed.
- Calls it cannot see through: function pointers,
dynmethods of other crates, FFI, drop glue (Dropimpls), and the internals of async runtimes. - Verbs of other crates’ APIs are still names.
kube::Api::listreads because its name says so. The driver classifies other crates’ I/O by name, not by following them down to the socket: at that level, every HTTP request is a write. - Panics count as exits only when they are explicit and in your own code (
unwrap,expect,panic!,assert!,unreachable!,todo!). Panics inside libraries, and bounds and overflow checks, are not counted.
Exercises
Start from the walkthrough crate. The answers come from running cargo psync check on each
variant (delete target/psync between runs, or cargo replays the last findings).
-
Make
motdread"cache.json"too. How many warnings doescheckreport? What schedule doescargo psync buildproduce? -
Instead, add a helper that may panic, and call it first:
async fn banner_or_panic() -> String { std::fs::read_to_string("motd.txt").unwrap() } #[graph] pub async fn start() -> io::Result<(String, String)> { let banner = banner_or_panic().await; refresh().await?; let cache = load().await?; Ok((cache, banner)) }Which findings are there now, and why could the macro not see either?
-
Would
cargo psync fixon exercise 2 keep any concurrency? -
A colleague’s
refreshwrites the file through aBox<dyn Fn()>stored in a struct. What doescheckreport, and where would you look?
Answers
-
Two warnings, both
conflict:loadandmotdeach read the file thatrefreshwrites.buildorders both afterrefresh, and they still run together:n0 -> n1 (write file "cache.json" (refresh, per the compiler) vs read file "cache.json" (load, per the compiler)) n0 -> n2 (write file "cache.json" (refresh, per the compiler) vs read file "cache.json" (motd, per the compiler)) level 0: n0 level 1: n1 || n2Then the check of the new schedule reports 0 warnings.
-
Two warnings. The
conflictbetweenrefreshandload, as before. And aspeculative-write:psync starts this before knowing whether an earlier statement may panic, and it does `write file "cache.json"` (via refresh -> std::fs::write). Sequential code never writes the cache ifbanner_or_panicpanics. From tokens,banner_or_panic().awaithas no?, so the macro takes it for a statement that cannot exit. Theunwrapis in its body. -
It inserts two
#[psync::seq], one beforerefresh(the speculative write) and one beforeload(the conflict). Nothing overlaps any more. Herecargo psync buildends in the same place, because the compiler’s facts include the panic:region 0 (unchanged): n0: banner = banner_or_panic() [await] {read file "motd.txt" (banner_or_panic, per the compiler)} n1: refresh()? [await] {write file "cache.json" (refresh, per the compiler)} n2: cache = load()? [await] {read file "cache.json" (load, per the compiler)} n0 -> n1 (may exit before `refresh` runs) n1 -> n2 (write file "cache.json" (refresh, per the compiler) vs read file "cache.json" (load, per the compiler)) level 0: n0->n1->n2Every statement waits for the one before it.
buildstill has the advantage that the source needs no hints, and the schedule follows the code when it changes. -
Possibly nothing. A call through a function pointer or
dynwithout a summary is opaque: the driver cannot see what it does, so it reports no effect.cargo psync summaries --alllists opaque calls. Look there, and declare the effect witheffects(write(refresh)).
Scheduling with compiler facts: cargo psync build
cargo psync check tells you where the macro’s guesses were wrong.
cargo psync build stops it from guessing. The compiler’s knowledge of every callee goes back
into the macro, which schedules with it:
cargo psync build # facts, check the facts-driven schedule, then cargo build
cargo psync check --facts # the same, without the final build
cargo psync fix # insert #[psync::seq] wherever a plain build would be wrong
This closes the loop that step 3 of Phase I (Where psync is going) describes. The compiler (HIR and MIR, with types and calls resolved) refines the graph the macro builds from tokens, and separately validates the schedule that comes out.
The loop
1. cargo check + psync-driver every crate: effect summaries, trait impls, and a fact for
each call site in #[psync::graph] functions
2. link resolve dyn/generic trait calls over the whole build
-> target/psync/facts.tsv
3. cargo check + driver, PSYNC_FACTS the macro schedules with the facts; the driver checks
the result
4. cargo build, PSYNC_FACTS the real build, same schedule
A fact belongs to a source location: the file, line and column where the callee’s name is written.
The macro computes the same key from its tokens’ spans (proc_macro::Span::line and column). A
fact is used only if the callee’s name at that location still matches, so facts from before an edit
are ignored rather than misapplied. The generated code reads option_env!("PSYNC_FACTS_STAMP"),
which makes cargo rebuild an annotated crate whenever the facts change.
What the facts change
For each call with a fact, the macro uses the compiler’s effects instead of the name’s.
- Fewer false refusals.
catalog.create_view("a.sql")sounds like a write. If its body only reads, two calls overlap. - Effects hidden in callees. A helper named
warm()that writescache.jsonis a write to that file, so it stays ordered with a read of it. - Panics are exits. A callee that panics on purpose (
unwrap,expect,panic!,assert!,unreachable!, directly or through the user’s own functions) counts as an exit. A write after it waits for it, and a loop whose body may panic counts as one that can end early. Panics inside libraries are not counted; nearly every library function could panic somewhere. - Opaque calls stay conservative. When some callee could not be seen through, the fact is
marked opaque. Examples are a
dyntrait of another crate (AsyncWrite::poll_shutdown), a function pointer, or a trait with no implementation in the build. The macro then applies the compiler’s effects and the name’s guess.
The test fixture shows all of it. Without facts, cargo psync check reports 7 warnings and a
note. With facts, the macro produces a schedule with none. Seven functions are kept in order:
start, login, snapshot, tour (whose visit writes a file through a mutual recursion),
release (whose fs::copy writes its second path), boot (whose parse_config may panic before
a write) and the sync_dirs loop. One gains concurrency: views, whose
create_view only reads.
On real code
| Function | Names only | Compiler facts |
|---|---|---|
DataFusion ListingSchemaProvider::refresh | loop not prefetched (create reads as a write) | loop prefetched: the dyn TableProviderFactory::create resolves to implementations that only read |
DataFusion writer shutdown loop | sequential | sequential: AsyncWrite::shutdown on a real writer writes |
kube-rs dynamic_api main | client setup overlaps tracing init | in order: client setup may run a credential process, and tracing init may print |
| the other 8 annotated functions | unchanged |
Both benchmark branches report 0 warnings with and without facts. A from-scratch check takes 74 s
(kube-rs) and 95 s (DataFusion) on 16 cores. An incremental check --facts recompiles only the
annotated crates: 3.4 s on kube-rs and 26 s on DataFusion.
Two lessons from getting there:
- An early version marked
writer.shutdown()as having no effects. It resolves to tokio’s genericAsyncWriteExt::shutdown, which writes through adyn AsyncWritethe driver never sees. The driver now classifies the I/O traits themselves (AsyncWrite,io::Write,AsyncRead,io::Read) on real readers and writers. It marks any call through another crate’s trait object as opaque. - A crate built twice with different features contributes two facts for one site. They are merged conservatively: every effect from either, and panicking or opaque if either says so.
dyn calls: link-time class-hierarchy analysis
The compiler can only resolve a trait-object call to its implementations when it sees all of them.
When a crate is compiled, it sees only its dependencies. DataFusion’s
ListingSchemaProvider::refresh calls self.factory.create(..) on an
Arc<dyn TableProviderFactory>. Its main implementation, ListingTableFactory, is in the
datafusion crate, which depends on the crate that makes the call. No single compilation can
see the implementation from the call.
So the driver defers those calls:
- A call to a trait method through
dyn, or on a generic the compiler cannot resolve, is recorded as deferred, keyed by the trait method’s stable definition hash. This applies when the trait belongs to the user’s workspace. Traits of crates.io crates are opaque instead. - Every crate also records which of its methods implement which trait methods.
- After the build, the link step takes the union over every implementation in the build, transitively: an implementation may defer further calls. This is class-hierarchy analysis over a closed world, the build itself.
The result goes back to the driver too (PSYNC_LINKED). A second check pass then reports conflicts
that only dyn resolution reveals. In the fixture, store.checkpoint() on a &dyn Store writes
the file the next call reads.
The closed-world assumption is the limit. A crate outside the build can implement your trait and be passed in at run time, for example a plugin. Facts are valid for the build they were computed in. Trait methods with no implementation in the build are treated as opaque.
cargo psync fix
cargo psync fix runs the check and inserts #[psync::seq] before every statement with a
warning, or before the loop for a loop warning, with the statement’s indentation:
#[psync::seq]
for d in dirs {
helpers::stamp(&d).await?;
}
On a copy of the fixture it inserts 7 hints, after which cargo psync check reports 0 warnings.
#[psync::seq] is the safe fix, not always the best one. For idempotent writes,
#[psync::speculate] keeps the concurrency. With cargo psync build, no hint is needed at all.
Exercises
The answers to 1 and 2 come from cargo psync build on a one-file crate.
-
impl Db { pub async fn create_view(&self, name: &str) -> io::Result<String> { std::fs::read_to_string(format!("{name}.sql")) } pub async fn get_totals(&self, name: &str) -> io::Result<String> { std::fs::read_to_string(format!("{name}.csv")) } } #[graph(explain)] pub async fn report(db: &Db) -> io::Result<(String, String)> { let view = db.create_view("sales").await?; let totals = db.get_totals("sales").await?; Ok((view, totals)) }What does a plain build schedule, and what does
cargo psync buildschedule? -
Now
create_viewwritesformat!("{name}.sql")instead of reading it.get_totalsstill reads{name}.csv, a different file. What doescargo psync builddo, and why? -
You run
cargo psync build, then add a line at the top of the file and run a plaincargo buildwith the samePSYNC_FACTS. Can the old facts be applied to the wrong calls? -
Your crate defines
trait Store, and a plugin loaded at run time implements it. What do the facts say aboutstore.checkpoint()calls, and can they be wrong?
Answers
- A plain build keeps them in order:
createis a write verb, son0 -> n1 (write `db` "sales" (create_view) vs read `db` "sales" (get_totals)). With facts, both are reads,{read file (create_view, per the compiler)}, and the level isn0 || n1. - It keeps them in order:
n0 -> n1 (write file (create_view, per the compiler) vs read file (get_totals, per the compiler)). The driver keeps a file target only when it is a string literal. A path computed inside the callee is “some file”, and a write to some file may be the file the other call reads. - No. A fact is keyed by the file, line and column of the callee’s name, and is used only if the
name written there still matches. The shifted calls find no fact (or one for another name)
and fall back to their names. That is a plain build’s schedule, which may be less concurrent,
or miss what only the facts showed. The stamp makes cargo rebuild when the facts change, but
not when the source does, so run
cargo psync buildagain after editing. - The facts take the union of every implementation in the build. The plugin is not in the
build, so its effects are missing: the closed-world assumption fails. Declare what plugins may
do (
effects(write(checkpoint))), or keep such calls#[psync::seq].
What psync guarantees about the outside world
A fair objection to everything in this part: the compiler sees only the client. A server may
change its state even on a read. A GET may bump a rate-limit counter, refresh a session or fill a
cache, so two “reads” may not commute at the server, and no client-side analysis can tell, whether
it reads tokens, MIR, or anything else. So what can psync guarantee about concurrent accesses?
The objection is right that nothing can be guaranteed outright. It is wrong that nothing can be
guaranteed. Every correct reordering, by a person or a tool, is correct relative to a model of the
outside world. psync’s contribution is to make that model explicit, prove its schedules against
it, and make it testable. This chapter states the guarantee precisely. The proofs are in
verify/World.lean, checked by Lean in CI.
The guarantee, in four layers
| Layer | What psync knows | From | Strength |
|---|---|---|---|
| client memory | no two concurrent branches race on a variable; borrows end before moves | Rust’s ownership types, checked by rustc on the generated code | sound: rustc rejects the code otherwise |
| client I/O footprint | which files, services and processes each branch can reach, through every callee and every dyn implementation | MIR summaries and link-time class-hierarchy analysis (cargo psync check) | sound up to stated gaps: FFI, function pointers, callees it marks opaque |
| the outside world | which pairs of requests commute | a commutativity specification: psync’s built-in rule, or one you give | assumed, but explicit and testable |
| composition | the schedule behaves like the sequential program | world_levels_correct, in Lean | machine-checked |
The first row is what a tool for a language without ownership types cannot build soundly, and it is why the JavaScript tools in this space describe themselves as unsound.
The model
World.lean describes three things.
- The server is a labelled transition system: a function
stepthat takes a request and the server’s state to a new state and a response. Nothing is assumed about which requests change the state. A read that writes, such as a counter, is an ordinary transition. - The client program is psync’s statements. Each one reads and writes client locations, as in Proofs. It may send one request, computed from what it reads, and update the client from the response.
- The world is the client’s store, the server’s state, and the response each call received.
Two requests commute at the server when, in either order, the server ends in the same state and each gets the same response. A specification is a relation on requests, and it is sound for a server when every pair it allows really commutes.
Two statements are independent relative to the spec when their client footprints are disjoint (no edge between them) and any requests they send are ones the spec allows to commute.
The theorem
world_levels_correct. If the specification is sound for the server, then every concurrent execution of psync’s schedule, in whatever interleaving each level takes, ends with the same client state, the same server state, and the same response for every call as the sequential program.
The proof reuses the whole scheduling argument. Schedule.lean’s theorems are restated for any
state and any independence relation under which steps commute (the Kernel section). The only new
step is that two independent statements commute in the world (world_commute). Their client
updates commute because of the footprints, and their requests commute because the spec is sound.
With the empty specification, in which no two requests commute (empty_spec_sound), the theorem
holds for every server. Then no two calls overlap, and only client work and requests to different
servers can. That is the conservative end. strict
moves psync towards it for the calls it cannot classify.
psync’s built-in rule is a specification, and it can be wrong
By default, psync decides from names or, with compiler facts, from bodies. A call is a read, a write or an ordered write of a service, with a target when one is known. Two calls overlap unless one writes, both are on the same service, and their targets may be the same.
That rule is a commutativity specification, so the theorem says exactly when it is safe: when
the rule is sound for the servers involved. Its weakest clause is “two reads always commute”.
World.lean proves both sides on a small server that counts every request, as a rate limiter
does:
inductive Req
| get (k : Nat) -- returns the value, and bumps the counter
| count -- returns the counter, and bumps it
theorem psync_rule_sound_for_gets (k k' : Nat) : Commutes kv (.get k) (.get k')
theorem psync_rule_unsound_for_counters :
¬ Sound kv (fun a b => psyncSpec (kvEff a) (kvEff b))
Two gets commute: the counter ends the same either way, and neither response mentions it. A
get and a count do not: count’s answer depends on whether the get came first. psync’s rule
calls both reads (get_value, fetch_count) and would overlap them, so for this server the rule
is unsound, and the guarantee does not apply.
When your server is like this, say so. Make the call that observes the counter a write
(effects(write(fetch_count))) or keep it in place (#[psync::seq]). Either way, the
specification psync schedules with becomes sound again.
Specifications for HTTP, S3 and Kubernetes
verify/Specs.lean writes three real protocols as server models and proves a specification sound
for each. The models are the assumptions: one copy of the state, requests applied one at a time
(linearizable), and nothing else changing the state behind the client’s back.
| Server | The spec allows | Proved | And proved not to commute |
|---|---|---|---|
HTTP (RFC 9110): resources on paths; GET, HEAD, list are safe; PUT, DELETE change their target; POST does whatever the server does | two safe requests; or two non-POST requests on paths apart (neither a prefix of the other) | httpSpec_sound, for every meaning of POST | two identical PUTs (http_put_twice_not_commute) |
| S3, without versioning | the same; and the same PUT or DELETE twice | s3Spec_sound | two PUTs of different bodies to one key |
| Kubernetes API | for clients that ignore resourceVersion: two reads; writes to different objects; a list and a write in another namespace | kube_commutes_up_to_rv | two writes to different objects, exactly (kube_writes_not_commute) |
Two of these results correct intuitions that psync’s rule relies on:
- Idempotent is not commutative. RFC 9110 calls
PUTidempotent: doing it twice leaves the state as doing it once. But the firstPUTto a new path answers201 Createdand the second200 OK, so the two do not commute, and a client that looks at the status sees the order. S3’sPutObjectanswers with the ETag, which depends only on the body, so there two identicalPUTs do commute. - Kubernetes writes to different objects do not commute. Every write takes the next value of
one cluster-wide counter, the
resourceVersion, and returns it. Run twoapplys in the other order and each object gets the other’s version. psync’s built-in rule, which lets writes with different targets overlap, is therefore sound only for clients that do not compare resourceVersions across objects. The proof makes this precise. Erasing resourceVersions is a simulation: it commutes with every request (kube_simulation). On the erased server the spec is sound, so requests the spec allows commute up to resourceVersions. A client that usesresourceVersionfor optimistic concurrency on one object is unaffected. A client that orders events from different objects byresourceVersionsees the difference.
Testing the specification
The specification is the only assumption, and it is about something you can observe. A
server-side log (the Kubernetes API server’s audit log, S3 access logs) records which requests
were applied in which order. If two requests that psync ran concurrently were applied in an order
that changed the outcome, that log entry is a counterexample to the specification, not just a
failed test. The benchmark harnesses already record these logs (see
the case studies). scripts/spec-check/check_logs.py checks
those logs against the specifications above. For every pair of requests that may have been in
flight at once, it asks whether the spec lets them commute, using the Lean file’s definitions:
scripts/spec-check/check_logs.py --kube logs/audit.log --s3 logs/garage.log
On the logs of the production-shaped benchmark (kube-rs against a real API server, DataFusion against Garage, an S3-compatible store):
| Log | Requests | Pairs that may have overlapped | Allowed, and why | Not allowed |
|---|---|---|---|---|
| Kubernetes audit | 31,638 (31,078 list, 560 get) | 65,893 | two reads: all | 0 |
| S3 (Garage) | 77,149 (71,168 GET, 5,888 PUT, 93 list) | 4,533,859 | two reads: 3,678,981; keys apart: 854,878 | 0 |
No two requests the specification forbids were ever in flight together. For the Kubernetes log
this is a weak result, because the benchmark only reads, and two reads always commute. For S3 it
is a real one. While objects were being uploaded, 854,878 pairs that included a PUT overlapped
another request, and every one of them was on a key apart from the other request’s key.
How overlap is decided matters, and the checker errs towards checking more:
- An audit event records when the request was received and when its response completed, so its interval is exact.
- Garage logs only when a request starts. On one HTTP/1.1 connection, a request ends before the next one starts, so the next start bounds it. The last request on a connection is bounded by 5 seconds. Both bounds lengthen intervals, so every pair that really overlapped is checked.
The checker is tested on logs with planted violations (scripts/spec-check/selftest.sh, run in
CI): a GET and a PUT of one key, a listing and a PUT under its prefix, two writes to one
Kubernetes object, and a list and a create in the same namespace.
What this does not test is the server side: that the pairs the spec allows really commute at
the server. That needs bodies and resourceVersions, which these logs do not record (Metadata
audit level). A RequestResponse-level audit log would show it, as would S3 access logs with
ETags.
What is not modelled
- One client, one deterministic server. With other clients, even the sequential program’s result depends on their timing. The theorem compares the two runs against the same server behaviour, and a specification meant to hold under concurrent clients has to say so.
- The generated Rust, which rustc type- and borrow-checks.
- Footprint soundness for real Rust. That MIR summaries over-approximate what a function
touches is proved only for a small fragment of MIR (
verify/Footprint.lean, see Footprints, proved for a fragment of MIR). For the rest of Rust,cargo psync checkchecks it and nothing proves it.
Prior work and novelty
| Work | What it does | How psync differs |
|---|---|---|
| The Scalable Commutativity Rule (Clements et al., SOSP 2013) | Defines when operations commute as seen through an interface, depending on the state, and checks 18 POSIX calls. | The same notion of commutativity, used for a different end: psync uses it to justify reordering a client’s calls, not to design scalable kernels. |
| Linearizability (Herlihy and Wing, 1990) | Each operation appears to take effect at one instant between its call and its return. | psync’s world model makes each server operation one atomic step of a transition system; that is an assumption of linearizability, stated here. |
| CompCert (2009) | Treats I/O as a trace that must not change. | psync allows the trace to change where the specification says the operations commute, and must therefore state the specification, and test it against server logs. |
Exercises
- An API’s
get_item(k)returns the item and the number of times it has been read. psync runs twoget_itemcalls concurrently. Does the guarantee apply? What do you change? - Two identical
PUTs to one new path run concurrently. Do they commute on a generic HTTP server? On S3 without versioning? - A controller applies two different ConfigMaps concurrently, then logs which one has the larger
resourceVersion. Is the schedule still “the same as sequential”? - The audit-log check found 0 forbidden pairs in 65,893 Kubernetes pairs. Why does the chapter call that a weak result, and the S3 one a real one?
- Which planted violation would catch a psync bug that started an S3
PUTwhile aLISTof its bucket prefix was in flight?
Answers
- No. The response depends on how many reads came before, so two
get_items do not commute. This ispsync_rule_unsound_for_counterswith a different name: psync’s rule calls both reads, and the rule is unsound for this server. Declare the call a write (effects(write(get_item))), or keep one in place with#[psync::seq]. - Not on a generic HTTP server: the first answers
201 Created, the second200 OK, so the order is visible (http_put_twice_not_commute). On S3 they do: the ETag depends only on the body, ands3Specallows the samePUTtwice (s3Spec_sound). - Only up to resourceVersions. Each write takes the next value of one cluster-wide counter, so
in the other order each object gets the other’s version (
kube_writes_not_commute). A client that compares versions across objects sees the difference. Keep the second apply in place. - The Kubernetes benchmark only reads, and two reads always commute under the spec, so no
pair could have failed. On S3, 854,878 overlapping pairs included a
PUT, and each needed its keys to be apart. That is a check that could have failed. - “A listing and a
PUTunder its prefix”, one of the four inscripts/spec-check/selftest.sh.
Certified schedules
The theorems of Proofs and the outside world are about
every schedule that respects independence. They say nothing about whether the macro, on your
function, produced such a schedule. That is a property of about 5,000 lines of Rust (psync-graph and psync-macros). psync does not
prove the macro correct. It checks each of its outputs instead.
For every region it makes concurrent, psync can write a certificate: what each statement may read and write, and the levels of chains it chose. A small checker in Lean decides whether the schedule is safe, and the checker itself is proven sound. This is translation validation, the idea CompCert uses for some of its optimizations: rather than trusting the transformer, check each transformation’s result with something small enough to prove.
What a certificate says
Every reason psync can give for an edge becomes a place, a path of names. Two statements conflict when one writes a place that the other reads or writes, and places overlap when one is a prefix of the other:
Edge reason (depends) | Places |
|---|---|
reads `x` , rebinds `x` , shadows `x` | n/x: written where x is bound, read where it is mentioned |
writes `self.groups` | p/self/groups, which overlaps p/self |
| an effect conflict | w/<domain>/t/<target>: w/fs/t/ then the characters of cache.json/; w/svc/api/t/… for a service; w/svc/{receiver}/t/… for a service reached by a free function such as redis::cmd(..), where {receiver} is a hole, so it overlaps every receiver but two different keys still differ. An unknown target stops at the domain, and a process or unknown callee at w |
may exit before `op` runs | x/i: written by statement i if it may exit, read by later writes |
effect order | e: written by every ordinary effect statement |
Targets are spelled out character by character. That makes a format!("m.key.{id}") prefix
overlap exactly the strings that start with m.key., as psync’s own rule says. A placeholder in a
format! target is a hole segment (the certificate lists which segments are holes). Two
places overlap if they agree until one ends, or if they first differ where either has a hole,
since a hole may stand for any text. Without holes, that is exactly “one is a prefix of the
other”. format!("{dir}/a") and format!("{dir}/b") agree up to {dir}/ and then differ in
plain characters, so they do not overlap. Where psync’s rule
is finer than prefixes (services named by type, ordered writes), the place is cut short, so the
certificate only ever has more conflicts than psync. The property test
certificates_cover_every_edge checks that over every annotated function in the tests, the driver
fixture and graph_suite: each of psync’s edges is a conflict between places.
For profile_page, with names interned to numbers:
def profilePage : Cert where
nodes := [
{ reads := [[20], [30]], writes := [[10]] }, -- user = api.user(..)
{ reads := [[20], [30]], writes := [[11]] }, -- posts
{ reads := [[20], [10], [30]], writes := [[12]] }, -- avatar reads user
{ reads := [[20], [30]], writes := [[13]] } ] -- friends
levels := [[[0, 2], [1], [3]]]
theorem profilePage_ok : check profilePage = true := by decide
The checker, and why it is sound
check (in verify/Cert.lean) asks two questions:
- Are the chains of each level pairwise independent?
- Is running the levels’ chains one after another a reordering of the program past independent statements only? It walks the program in order. Each statement must find, scheduled ahead of it, only statements independent of it.
check_sound proves what a yes means:
If
check c = true, then for any meaning of the statements under which the certificate’s independence is real independence, every run of the schedule, in any interleaving of each level’s chains, ends as the program run in order does.
“Any meaning” includes World.lean’s client and server world. So with a sound commutativity
specification, a certified schedule preserves the server’s state and every response too.
Lean checks each certificate by decide: it runs check inside the proof checker and accepts
only if the answer is true. A wrong schedule does not compile:
error: Certs.lean:31:38: tactic 'decide' proved that the proposition
check c1 = true
is false
Running it
cargo run -p psync-graph --features cli --bin psync-cert -- src/lib.rs > verify/Certs.lean
cd verify && lake build GeneratedCerts
scripts/certify.sh does this for the repository’s own schedules: 46 certificates from the graph tests,
the Phase II tests, the driver fixture and graph_suite, checked in a few seconds. The checker is
the same for synchronous code: a level is a set of chains, whether they run as futures or on
threads. CI regenerates the certificates,
fails if they changed without being committed, and checks them with Lean.
Building the certificates found one false alarm, and no unsafe schedule. The first version of the
place encoding dropped format! targets, and Lean rejected graph_suite’s matrix-rust-sdk
disable because of it: psync had correctly overlapped a write to m.secret_storage.key.{id} with
writes to m.megolm_backup.v1 and five others. The character encoding fixed it.
Footprints, proved for a fragment of MIR
check_sound assumes that a certificate’s places are right: if the certificate says statement 3
writes only s.a, then it really does. verify/Footprint.lean proves that assumption for a small
language shaped like MIR, the compiler’s simplest form of a function
(From MIR to summaries across crates explains how psync reads MIR):
- Places are a local and a path of fields:
_5.0.1is field 1 of field 0 of local 5. - Statements assign the result of an operation on places and constants (
_1 = _1 + 1), move a whole struct (_2 = move _3), and combine through sequencing,if,whileand calls. A call passes places by reference, asdrain(&mut s.a, &mut s.b)does. - A summary of a function lists the places it may read and write, in terms of its own
parameters. A caller never looks at the callee’s body. It takes the summary and replaces each
parameter with the argument:
_0becomess.a. This is how psync’s summaries cross crates. - The link check (
Valid) asks, for every function, whether its summary covers what its body does, where the body’s calls are again read from summaries. It is one local check per function, so it works for recursion and for functions from other crates, and for a finite program it is decided by computation (Program.validB).
Two theorems follow, for every function and every input, provided the link check passes:
- Frame. A statement changes nothing outside the places it may write.
- Dependence. What it writes depends only on the places it may read or write. (Writes count
as reads, because a statement that only sometimes writes
xleaves the oldxotherwise.)
Together they make statements with disjoint footprints commute, and hind_of_cover turns a
certificate that covers the footprints into exactly the hind that check_sound needs. The
result, mir_schedule_sound, has no assumption left about footprints: if the link check passes,
the certificate covers the summaries, and check accepts, then every run of the schedule ends with
the same memory as the sequential program. The file’s example is a recursive drain called on two
fields of one struct, in one level. Its summary is checked against its own body, and a summary that
forgets one write is rejected.
From real Rust, through Charon
The fragment is small, but real compiler output fits it. Charon
extracts a crate’s MIR, after borrow checking, as a structured program (LLBC).
scripts/charon/llbc2lean.py translates that into the fragment:
*x = *x - 1on a&mut u64parameter becomes an assignment to the callee’s placex;_4 = &mut (*s).a, and the reborrow_3 = &mut *_4, are resolved to the place they borrow,s.a, as the borrow checker names it;- a call
drain(move _3, move _5)becomescall drain σ, withσsendingdrain’s parameters tos.aands.b, and its own locals to a frame region of the caller, one per call site; - an
ifwhose branch returns early takes the rest of the block into the other branch.
On the crate in scripts/charon/drain, the Rust version of the example above, the script writes
verify/CharonDrain.lean. Lean then decides, without trusting the script, that the summaries pass
the link check, that a certificate running both calls of callers in one level covers their
footprints, and that check accepts it. mir_schedule_sound then gives the theorem for the
compiled code. Two red checks show the pipeline can fail. If the second call is changed to
drain(&mut s.b, &mut s.d), Lean rejects the certificate. If drain’s summary forgets its write
to *y, Lean rejects the link check.
Aeneas, built on Charon, goes further: it turns the same LLBC into pure Lean functions, with
each &mut replaced by a value passed in and returned (scripts/charon/aeneas/Drain.lean.txt):
def callers (s : S) : Result S := do
let (i, i1) ← drain s.a s.b
let (i2, i3) ← drain s.c s.d
ok { a := i, b := i1, c := i2, d := i3 }
There, “the two calls commute” is an ordinary equation, callers s = callers_swapped s. It even
shows why psync replays exits in program order: in Result, if both calls failed, the two orders
would return different errors. The cost is a second proof world. Aeneas’s library needs Lean 4.36
and Mathlib, while verify/ uses Lean 4.22 and only Lean’s core library, and every function needs
its own functional proof. For psync, whose question is only which places a call touches,
the footprint route (Charon into the fragment, then decide) is the one that scales. Aeneas is
the tool for the rare call whose commutation depends on values.
The translation itself is not proved. It is a small script, it stops with an error on anything
outside the fragment (loops, dyn, by-value arguments, unwinding), and its output is checked, not
trusted, for everything except its faithfulness to the LLBC.
What the fragment leaves out, and so stays assumed for real Rust:
- References stored in memory (
*pwherepwas computed). The borrow checker is what lets psync name the place behind a&mut, and it is not modelled. - Interior mutability and
unsafe, which let a shared reference write. - Panics and unwinding.
- That real MIR is faithfully translated into the fragment, and that psync’s emitter writes certificate places that cover the summaries it computed.
What a certificate does not cover
- That the places describe the statements. This is the hypothesis
hindofcheck_sound. For a fragment of MIR it is now proved:verify/Footprint.lean(below). For real Rust, psync computes the places from tokens, and from compiler facts undercargo psync build, andcargo psync checkcompares them with MIR. The gap between real MIR and the fragment is what stays assumed. - Prefetched loops. Certificates cover regions. A loop’s prefix is checked by the macro’s refusal rules, and certifying it is the next step.
- Exit replay.
replay_correctinSchedule.leanproves the rule in general. Certificates do not yet record each statement’s exits. - The generated Rust, which rustc type- and borrow-checks.
Prior work and novelty
| Work | What it does | How psync differs |
|---|---|---|
| Translation validation (Pnueli et al., TACAS 1998; Necula, PLDI 2000) | After each compilation, a validator checks that the output means the same as the input. | psync’s certificates are translation validation for a concurrency rewrite. Note the difference: Pnueli and Necula validate the output code; psync validates an abstract certificate (reads, writes, levels), and its link to the Rust code is proved only for a MIR fragment. |
| CompCert (Leroy, 2009) | A compiler proved correct in Coq. Its I/O trace must be identical before and after. | psync lets I/O events reorder where a specification says they commute. That is weaker than identical traces, and it is why psync needs a model of the world. |
| Safe Futures for Java (OOPSLA 2005) | Proves every safe schedule equivalent to a serial one, by permutation, for memory. | psync’s theorems have the same shape, with outside-world effects in the trace, and are checked per function by a Lean checker that is itself proved sound. |
| Bell, A Proof Theory for Loop-Parallelizing Transformations (Princeton, 2014) | Coq proofs for DOALL, DOACROSS and pipelining, for memory. | psync covers I/O, per function. |
Exercises
Each answer is what check returns. To try them, add the lines to a file that imports Cert
and open PsyncCert, and run it with lake env lean in verify/:
#eval check { profilePage with levels := [[[0, 1], [2], [3]]] }
[[[0, 1], [2], [3]]]:userandpostsas one chain,avatarandfriendsbeside it.[[[0], [1, 2], [3]]]:avatarchained afterpostsinstead ofuser.[[[0], [1], [3]], [[2]]]:avataralone, in a second level.[[[0, 2, 1, 3]]]: one chain, withavatarmoved ahead ofposts.- psync’s edge reason is
writes `self.groups`. Why is the placep/self/groups, and why does it conflict with a statement that readsself, but not with one that readsself.mode?
Answers
false.avatarreads[10], whichuserwrites, and the two are in different chains of one level.false, for the same reason. Chaining it afterpostsdoes not order it afteruser.true. It is slower than psync’s schedule, but safe:avatarstarts after the first level, includinguser, has ended.true. A single chain runs in its own order, and the second question allows that order:avatarpasses onlyposts, which it is independent of.checkaccepts every safe schedule, not only psync’s.- A place is a path of names, and two places overlap when one is a prefix of the other.
p/selfis a prefix ofp/self/groups: reading all ofselfreadsgroups.p/self/modeandp/self/groupsfirst differ at the third segment, so they are apart.
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.
Status. Built for loops and files (Checking per-item files). When every per-item path can be evaluated ahead, the items’ paths are compared before the loop starts, and with a duplicate the loop runs as written. Straight-line asynchronous code is built too (Paths compared at run time). It does not branch between two schedules. Each dropped dependency becomes a gate that orders the two chains when their paths overlap. A canonicalizing option, other domains, Phase II and the checker’s view of gates are next.
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
Built, in part. A
Method::Xargument now decides read or write by RFC 9110, URLs compare as paths, and aPOSTconflicts with everything on its server (Side effects). Idempotency is not used yet.
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.
Status: built. cargo psync check is this driver. It resolves callees,
summarizes effects through function bodies and across crates, and reports conflicts, speculative
writes and shared interior-mutable state in the generated code.
cargo psync build feeds its facts back into the macro, which then schedules with
them. It also resolves dyn calls by link-time class-hierarchy analysis and treats explicit panics
as exits. Still open: &mut-precise argument effects (which parameter a callee writes through),
and interior mutability as an effect rather than a note.
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.
Status: the scheduling part is proven. verify/Schedule.lean proves commutation, the
correctness of every level’s join under any interleaving, the correctness of the whole schedule,
equivalence with program order for reorderings past independent operations, and the harmlessness
of read-only speculation, and early-exit replay (replay_correct: recording every outcome and
replaying the first exit in program order gives the sequential state and exit). Modeling the
replay found a real bug: an exit was replayed before an earlier statement in a later level had
run. Fixed, with a test.
The outside world is modelled too. verify/World.lean adds a server, as a labelled transition
system, and proves that the schedule preserves the server’s state and every response, relative to
a commutativity specification. It also proves that psync’s built-in rule is such a specification,
and that the rule is unsound for a server whose reads change state
(What psync guarantees about the outside world).
Schedules are certified. psync writes a certificate per concurrent region, and a Lean checker,
proven sound, accepts or rejects it; CI checks all of the repository’s schedules
(Certified schedules). The checker’s hypothesis, that footprints are right,
is proved for a fragment of MIR with cross-function summaries (verify/Footprint.lean).
Specifications for HTTP, the Kubernetes API and S3 are proved
(What psync guarantees about the outside world),
and scripts/spec-check checks recorded request logs against them. Next: certificates for
prefetched loops and exits.
10. Branches on several cores
Problem. The code #[psync::graph] generates joins its chains inside one task. Once the waits
overlap, the CPU work in the chains runs on one core. In kube-rs’s get_all
(Patterns and pitfalls), Amdahl’s law predicted 10.4–11.5× and the
measurement was 5.0–9.2×. Every response arrived at once, and decoding them took one core.
Where that CPU work is. In get_all it is inside the awaited future. api.list(..) decodes
the JSON before it returns. So running the statements after the awaits on threads, the way
Phase II runs synchronous jobs with par_run, would not help here. Each
item’s future has to be polled on another thread.
Why psync cannot simply spawn. Three ways were considered:
- Spawn the chain as a task. A task must be
'static, and the chains borrow from the function:client,discovery, andarandcapsfrom the group being walked. The macro sees tokens, not types, so it cannot tell which chains would compile. Spawning every chain would break the build of most rewritten functions. - Scoped spawning that waits in
Drop. The function’s future borrows the spawned tasks’ data, and itsDropwaits for them. This is unsound, because a future can be leaked (mem::forget(Box::pin(f))) without runningDrop, and the borrowed data is then freed while the tasks still use it. Libraries such asasync-scopedmark thisunsafefor that reason. - Block the current thread and poll the chains on psync’s workers (sound, like
par_run). The chains’ I/O needs the user’s runtime. hyper registers its sockets with the tokio reactor of the thread that polls it, and psync’s workers have none. It would also block a runtime worker for the whole join.
What would work. An opt-in that names the user’s spawner,
#[psync::graph(spawn = my_spawn)] with fn my_spawn<F: Future + Send + 'static>(f: F) -> impl Future<Output = F::Output>, and a statement or loop hint that asks for it. The programmer then
makes that chain 'static (owned clones instead of borrows), and the compiler checks it. Exits,
panics and results would come back through the same slots as today. Cost. psync’s generated
code depends on a runtime the user picks. For loops, item bodies must be written to own their data.
Status. Not built. The choice of interface (an option naming a spawner, or a feature for tokio) is open.
Priorities
| Step | Closes | Effort |
|---|---|---|
| 1. runtime target checks (built for files: loops and asynchronous straight-line code) | the duplicate-item assumption, computed paths | small: other domains, Phase II, the checker next |
| 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 (built: cargo psync check, build, fix; per-argument effects for synchronous helpers; synchronous levels checked) | the token-level foundation | per-argument effects also through async fn coroutines; exit positions in the checker; control dependence, data edges, the macro’s joins and loop summaries per async body (cargo psync pdg); next: paths computed by join in MIR; async closures |
9. Lean model (scheduling built: verify/Schedule.lean) | the token-level foundation | exit replay, the server model, certified schedules and footprint soundness (with real compiler output through Charon) built |
Synchronous code
Status: prototype. This chapter describes what works today. The design describes the rest and the reasons behind it.
#[psync::graph] also works on an ordinary fn. There, the statements that overlap are the ones
that block: they wait on the network or a child process. psync runs independent blocking
statements on threads, and keeps results, errors and panics as the sequential code has them. The
analysis, the schedule and the certificates are the ones you know from
async code. Only the way a level runs changes: its chains become jobs on a pool of threads instead
of futures in one task.
It needs psync’s std feature:
[dependencies]
psync = { path = "../psync", default-features = false, features = ["std"] } # a local checkout, as in Getting started
Which statements block
psync cannot see time, so it has to be told which statements are slow. It recognizes some by path, when the statement both names the resource and calls a method that waits for it:
- the network:
ureq,reqwest::blocking,TcpStreamorUdpSocket, withconnect,call,send,recvorread_to_end(and similar); - processes:
Command, with.output(),.status()or.wait().
Both halves are needed. Command::new("git") only builds a command, and Command::Reply or clap’s
Command::parse_from are not processes at all. Calls inside a macro’s arguments
(assert!(cmd.status()?.success())) never count: psync cannot see a macro’s effects, so it must
not move the statement as if it had none.
Everything else needs a hint. Most slow calls in real code go through a helper (download(url),
repo.infos_index()), and a helper’s name says nothing. Mark such a statement with
#[psync::par]:
#[psync::graph]
fn three_downloads(log: &Mutex<Vec<&'static str>>) -> (u32, u32, u32) {
#[psync::par]
let a = slow(log, "a", 100, 1);
#[psync::par]
let b = slow(log, "b", 100, 2);
#[psync::par]
let c = slow(log, "c", 100, a + 10);
(a, b, c)
}
region 0:
n0: a = slow (log , "a" , 100 ,… [blocks]
n1: b = slow (log , "b" , 100 ,… [blocks]
n2: c = slow (log , "c" , 100 ,… [blocks]
n0 -> n2 (reads `a`)
level 0: n0->n2 || n1
unclassified (assumed to read; `strict` treats them as writes): slow
[blocks] is the synchronous counterpart of [await]. slow is unclassified: psync cannot tell
from its name what it does to the world, so it assumes a read. See the next section. The schedule is the one async code would
get: c waits for a, and b runs beside both. The function takes two steps instead of three.
Two kinds of statement are deliberately not recognized as slow:
- Ordinary method names. In async code, an awaited
getis a request. In synchronous code,map.get(k)is a lookup in memory, so a name never makes a statement blocking. (Names still decide effects, below.) - Files.
std::fscalls are recognized as file effects, so they keep their order with conflicting ones, but they are not treated as slow. A cachedstattakes about 2 µs, and handing it to a thread costs more than that (see the measurements below). Mark a file statement with#[psync::par]when you know it is slow, for example on a network file system.
What a blocking statement does to the world
Effects are found as in async code, with one change: a call does not have to be awaited to be
classified by its verb. In synchronous code, every method chain and free function named by a
verb is a service call. client.delete(name) writes client, and client.get(name) reads it, so
the two keep their order:
region 0 (unchanged):
n0: # [psync :: par] client ? [blocks] {write `client` `name` (delete)}
n1: v = client . get (name) ?? [blocks] {read `client` `name` (get)}
n0 -> n1 (write `client` `name` (delete) vs read `client` `name` (get))
This only ever adds conflicts. A call without a known verb (len, Vec::new) has no effect and
is not reported, because most calls in synchronous code are computations. A blocking statement
whose calls all lack a verb is reported as unclassified, as an unclassified awaited call is,
and under strict it is a write to anything:
unclassified (assumed to read; `strict` treats them as writes): slow
A receiver bound inside a statement belongs to that statement. Two downloads that each open
their own socket s do not conflict, although both call s.write_all(..).
Different receivers are different services is the assumption psync makes
everywhere, and these are different receivers that happen to share a name. Two identical
statements still conflict.
Two blocking statements whose computed paths the tokens cannot tell apart (fs::read_to_string(src)
and fs::write(dst, ..)) still run side by side: the paths are compared when the function runs,
and the write’s thread blocks until the read ends if they are one file
(On threads). The same holds for computed HTTP URLs and
Redis keys.
What stays as it was
Errors. Every chain records its ?, return, break and continue instead of performing
them, and they are replayed in program order, exactly as in Early exits. If a
later statement fails first in time, the earlier one’s error still wins:
#[psync::par]
let a: u32 = slow(log, "a", 100, Err("first"))?;
#[psync::par]
let b: u32 = slow(log, "b", 10, Err("second"))?; // fails first, loses
Panics. A panic on a thread is caught. psync records which statement of the chain raised it,
and replays the panic at that statement’s place in program order, with its original payload. An
earlier Err therefore still wins over a later panic, as it would in sequential code, and a panic
that does propagate is the one that was raised, not a generic “a scoped thread panicked”.
Writes after a possible exit. A write is not performed early if an earlier statement may
leave the function, because sequential code would never have performed it. This is the rule that
decides tauri’s case below. #[psync::speculate] lifts it for one statement.
Locks. A let that keeps a guard (.lock(), .borrow_mut(), .read() or .write() without
arguments) stays where it is, and splits the block, like an awaited lock in async code.
What threads add: Send and Sync
A chain that runs on another thread may only borrow what can be shared between threads. If it cannot, rustc says so, at the attribute:
#[psync::graph]
fn not_sync(cell: &std::cell::Cell<u32>, log: &Mutex<Vec<&'static str>>) -> u32 {
#[psync::par]
let a = slow(log, "a", 1, cell.get());
#[psync::par]
let b = slow(log, "b", 1, 2);
a + b
}
error[E0277]: `Cell<u32>` cannot be shared between threads safely
--> tests/sync.rs:127:1
|
127 | #[psync::graph]
| ^^^^^^^^^^^^^^^ `Cell<u32>` cannot be shared between threads safely
|
= note: required for `&Cell<u32>` to implement `Send`
As with two &mut borrows in async code, this is a compile error, not a race. Mark the statement
#[psync::seq], or share the value in a form that is Sync.
One hazard has no type, and psync cannot see it yet: thread-local state. A callee that keeps a
cache, a connection or a tracing span in a thread_local! sees a different one on a pool
thread. The design plans a thread
effect, which the driver can find in compiled code. Until then, do not mark such calls
#[psync::par].
How the jobs run
A level of two or more chains becomes one call to psync::__private::par_run. The first chain
runs on the calling thread, and the others on a pool of parked worker threads, and the call
returns when all have finished. Because it waits, the jobs may borrow from the function’s stack,
as with std::thread::scope. Waking a parked worker costs about a tenth of what creating a thread
does (measured in the design). The pool grows
when every worker is busy, so a job that blocks never waits for a worker that is itself waiting.
Past 256 workers, a job runs on the calling thread. That changes when it runs, never what it
computes.
The pool is psync’s own, not rayon’s. Its jobs block on I/O, and blocking rayon’s CPU-sized pool would stall every other user of rayon in the process.
Measurements
examples/phase2.rs rebuilds three of the audit’s synchronous findings over real sockets and
files, written the way the projects write them. tauri calls a download(url) helper, and rustic
calls methods on a repository (repo.list_files(), repo.read_index()). A local server delays
every response by 50 ms, standing in for a remote backend. Each figure is the median of 21 runs
(2,001 for the microsecond rows), on a 32-thread machine that other jobs were also using (load
average about 50):
| Shape | Sequential | psync | Speedup |
|---|---|---|---|
tauri prepare_tools: three downloads, then three writes | 152.1 ms | 51.0 ms | 2.98× |
rustic repoinfo: list the repository, read its index | 101.1 ms | 50.5 ms | 2.00× |
tauri prepare_tools as written: three if !exists { download; write } | 152.0 ms | 152.1 ms | 1.00× |
the same, later ifs marked #[psync::speculate] | 152.3 ms | 51.0 ms | 2.99× |
two cached stats marked #[psync::par] (a miss) | 3.6 µs | 13.5 µs | 0.26× |
par_run with two empty jobs | 12–21 µs |
The machine’s load shows in the parallel versions, which need six threads to run at once (three jobs, and the server’s three). Across eight runs, the first row’s psync median ranged from 51 ms to 138 ms (1.1× to 3.0×), while the sequential medians stayed at 152 ms. Most runs gave the figures above. One early run also measured 488 ms for a sequential median, which no later run repeated.
The rows that do not speed up are the interesting ones:
- tauri as written: 1.00×, and correct. Each
ifdownloads a tool and writes it. If the first download fails, the function returns, and sequential code never writes the second file. psync keeps that:n0 -> n1 (may exit before fs::write runs). A complete file in a tool cache is harmless, so here the right answer is to say so with#[psync::speculate], which gives 2.99×. Building these rows also turned up two false edges and one missing one, all now fixed:- The targets
format!("{dir}/AppRun")andformat!("{dir}/linuxdeploy")used to conflict, because psync kept only the text before the first{. They are now compared piece by piece (When two effects conflict), in async code too. let data: u32 = ..inside a block was read as an assignment tou32, in async code too.- The first prototype gave synchronous method calls no effects, so a
#[psync::par]delete and get of one name would have overlapped. Verbs now classify synchronous calls (above).
- The targets
- Cached
stats: 0.26×. A thread costs more than a cachedstat. That is why file statements are not treated as slow by default, and why the design calls for an adaptive loop that times the first item before handing out the rest.
Checked by the compiler
Each job of a synchronous level is wrapped in job_at::<LEVEL, ORDER, LAST, EXITS, EXIT_AT, SPEC, INDEP, _>(|| ..),
which returns the closure unchanged. It is the marker maybe_done_at is for a future, so
cargo psync check checks synchronous levels as it checks async ones. Before
this marker, synchronous rewrites were not checked at all. Two differences:
- the cancellation note does not apply, because a synchronous call cannot be dropped halfway;
- with per-argument effects, a helper that writes the path it is given, such as
stash("a.json", ..)next tostash("b.json", ..), is checked per file.
psync-check/tests/fixtures/hidden has both cases: stash_both (two files, accepted) and
stash_same (one file twice, a conflict that cargo psync fix resolves with #[psync::seq]).
The checker knows where each chain may first exit and where it ends, so a chain that ends in
r1? after another chain’s write is not a speculative write: sequential code ran that write
before the exit too (stash_tail in the fixture).
Not yet
- Loops.
forandwhilein synchronous code are left as written. No prefetching or fission yet. - Compiler facts.
cargo psync buildrecords what each callee does, but the macro does not yet use those facts to decide which statements block, so helpers need#[psync::par]. - The thread effect, described above.
- The proof’s last step. The theorems are about whole statements, and threads interleave finer. The soundness argument explains why data-race freedom closes the gap. The Lean statement of it is still to be written.
Exercises
- In
three_downloads, makebuseatoo. What does the explanation print, and how long does the function take now? - Remove
#[psync::speculate]from one of the two laterifs inprepare_tools_speculate(examples/phase2.rs). Which edge comes back, and what does the measurement become? - Why is a
let guard = m.lock().unwrap();a barrier, while*m.lock().unwrap() += 1;may move? (Hint: when is the guard dropped?)
Answers
-
bnow readsa, so both later statements wait for it:region 0: n0: a = slow (log , "a" , 100 ,… [blocks] n1: b = slow (log , "b" , 100 ,… [blocks] n2: c = slow (log , "c" , 100 ,… [blocks] n0 -> n1 (reads `a`) n0 -> n2 (reads `a`) level 0: n0 level 1: n1 || n2Still two steps:
aalone, thenbandctogether, so about 200 ms, as before. Only the shape of the schedule changed. -
Without
#[psync::speculate]on the secondif, the edgen0 -> n1 (may exit before fs::write runs)comes back: the firstifmay return an error, and the second writes a file. The schedule becomeslevel 0: n0->n1 || n2. Two downloads run one after the other and the third beside them, so about 100 ms instead of 51 ms (about 1.5× instead of 3×). Measure it withcargo run --release --example phase2 --no-default-features --features std. -
The guard lives as long as its binding.
let guard = ..keeps the lock until the end of the block, so everything after it runs inside the critical section, and moving the statement would move the section’s start. In*m.lock().unwrap() += 1;the guard is a temporary, dropped at the end of that statement: the lock covers exactly the statement, wherever it runs, and the lock itself keeps the two updates from overlapping.
Phase II design: concurrency in synchronous code
Status: prototype. Regions of synchronous code run on threads (see Synchronous code for how to use it and what it measured). Not yet built: loops, adaptive loops, compiler facts for blocking callees, the thread effect and the micro-step proof. This chapter is the plan, and it records the measurements and decisions behind it.
Phase I makes independent awaits overlap. A lot of Rust waits without awaiting: build tools and
CLIs call std::fs, run Command::output, and download with ureq or reqwest::blocking, one
call after another. Phase II applies the same analysis, the same schedule, the same proofs and the
same certificates to synchronous code, and runs the chains on threads.
What the audit found
The audit has ten findings of this kind (pattern P6). They come in three shapes:
| Shape | Example (finding) | Today | With Phase II |
|---|---|---|---|
| independent blocking calls | rustic repoinfo (tools-29): files: repo.infos_files()?, index: repo.open(..)?.infos_index()? | t_list + t_index | max of the two, up to 2× on S3 or rclone backends |
| guarded downloads | tauri prepare_tools (app-16): three if !path.exists() { download(..)?; write(..)?; } | three sequential ureq GETs | up to about 3× on a cold cache |
| a loop over independent items | rustic backup (tools-31): one snapshot per source set | the sum over sets | about the maximum, if the sources are on different disks or the backend is latency-bound |
A fourth group is blocking calls inside async code: poem’s directory listing (web-41), pixi’s input and output walks (tools-17), and neon’s endpoint stops (dbc-11). These block an executor thread, and they are independent of each other. They need the same analysis with a different runtime: move the call off the executor and await it.
Two things stand out. The expensive calls are opaque by name: download, infos_files,
backup_snapshot, node_from_snapshot_and_path. And several gains depend on conditions
(remote backend, cold cache, different disks), so Phase II needs a cost model, not just a
dependence graph.
What carries over unchanged
- The analysis. Nodes, edges, barriers, chains, levels, loop prefixes and fission work on any block. Their inputs are footprints and effects, not awaits.
- Exits.
chain_codealready turns?,return,breakandcontinueinto recorded exits, and the replay is the same, including the release rule of Early exits. - The proofs and certificates.
check_soundholds for any meaning of the statements under which the certificate’s independence is real independence (see the soundness argument below). - The driver.
cargo psync checkreads the same markers, and compiler facts refine the same footprints.
What is new
1. Which statements are worth a thread
In async code, .await marks where the time goes. In synchronous code nothing does, and a
thread costs real time. Measured on the development machine (median of 2,000 runs, release
build):
| Mechanism | Cost |
|---|---|
std::thread::scope with 1 spawned thread | 126 µs |
| with 2 / 4 / 8 spawned threads | 150 / 263 / 451 µs |
| hand a job to a parked pool thread and wait for it | 10 µs |
A fresh thread per chain pays for itself only above about a quarter of a millisecond. A pool of
parked workers brings that down to tens of microseconds. So psync runs chains on a persistent
pool with a scoped API: borrowing jobs, joined before the level ends, like rayon::scope. It
does not use rayon itself, because rayon’s pool is sized for CPU work, and blocking I/O on it
starves everything else that uses rayon.
Statements fall into three cost classes:
| Class | Recognized by | Default |
|---|---|---|
| remote: network, processes | path (Command::output, TcpStream, ureq/reqwest::blocking calls), or a compiler fact that the callee’s summary reaches the network or a process | overlap, whenever two are independent |
| local I/O: files | std::fs paths, or a fact that the callee reaches the file system | overlap in loops, adaptively (below); pairs only with a hint |
| CPU | everything else | only with a hint, #[psync::par] |
The verb heuristics of Phase I do not decide what blocks in synchronous code:
map.get(k) is not a request. They do still decide effects, which can only add conflicts. That leaves names like download unrecognized without compiler facts, which is why
cargo psync build matters more in Phase II. The driver knows that download’s body calls
ureq::Request::call.
Adaptive loops. A cached stat takes 2.4 µs here (median, measured the same way), four
times less than handing it to a pool thread, while a stat on S3 or a cold network share takes
milliseconds. The same loop can be worth parallelizing on one machine and not on another. For a
loop of the local-I/O or CPU class, the generated code runs the first item’s prefix on the calling
thread and times it. It hands the remaining items to the pool only if
elapsed × remaining items > K × handoff cost, with K about 10. The result is the same either
way. Only the timing changes.
2. Threads are not tasks: three new hazards
Moving a call to another thread is visible in ways that moving it to another point of the same task is not.
SendandSync. A chain that captures&RefCell<..>,Rc<..>or a!Sendconnection cannot run on another thread. rustc rejects the generated code, as it rejects two&mutborrows in Phase I. That is again a compile error, not a race. The fix is the same:#[psync::seq].- Thread-local state. A callee that reads a
thread_local!(a cache, an RNG, atracingspan, a SQLite handle stored per thread) behaves differently on a pool thread, and no type says so. The driver can see it: a summary that reachesLocalKey::withgets a new effect, thread, which conflicts with every other thread effect and makes the call stay on the calling thread. Without facts, the macro cannot see thread-locals. This is a documented assumption, and the reason the remote class is the only default. - Panics.
std::thread::scopere-panics with a generic message, and a panicking chain would win over an earlier?that sequential code would have taken first. Each job instead runs undercatch_unwind, and a panic is recorded like any other exit and replayed in program order withresume_unwind. The original payload survives, and an earlierErrstill wins.
3. Output and ordering
println!, logging and progress bars are ordered writes to standard output. psync keeps them in
order relative to each other, as it does in async code. Findings such as rustic’s copy print
tables from inside the parallel part. There, the output stays in order only if each table is
written by its own statement, after the join.
Code generation
A level of two or more chains becomes a scoped join on the pool. Each chain body is exactly
chain_code’s body without the async wrapper:
let (__psync_taken0, __psync_taken1) = ::psync::__private::par_join2(
|| { /* chain 0: statements, exits recorded, returns (slots.., Option<bindings>) */ },
|| { /* chain 1 */ },
);
// unpack, replay exits and panics in program order, bind: as in Phase I
The calling thread runs chain 0 and the pool runs the rest. par_join2 is a function, not a
spawn, so the closures may borrow from the stack frame, and the borrow checker checks them as it
checks any closures. A loop prefix becomes par_map_bounded(items, bound, |item| prefix), with
results in item order and the adaptive first item.
Soundness argument
The Lean theorems are about interleavings of whole statements. Threads interleave finer: two chains’ machine instructions run at the same time. The argument that this changes nothing:
- Chains of one level have disjoint footprints. That is what
checkverifies. - Every location a statement touches is in its footprint: its variables, its fields, and, through effects, what it reaches through interior mutability and the outside world.
- So no location is accessed by two chains unless both only read it. The execution is data-race-free, and safe Rust’s memory model guarantees that a data-race-free execution behaves as some interleaving of its steps.
- Any interleaving of steps with disjoint footprints can be reordered, one commuting step at a
time, into whole statements in a level’s order.
level_correctcovers the rest.
Step 2 is the footprint-soundness obligation of Phase I, plus one new effect, thread. Step 4 is
a small extension of Schedule.lean: operations as sequences of micro-steps. That proof is part
of this work.
Experiments for the prototype and the audit
- Microbenchmarks. The cost classes’ thresholds: pool handoff, adaptive loops on a cached and a cold file system, and a slow network through a delay proxy.
- The ten P6 findings, reconstructed as
graph_suiteshapes with blocking timers, and then the real code where it builds: rustic against a local and a remote (rclone) repository, and tauri’s bundler with a cold cache. - The audit. Run the analysis over the 35 repositories’ synchronous functions, and report for each candidate: the class, whether facts were needed, the measured gain, and why there was none. Thread overhead, contention for one disk, and internal parallelism (pixi already hashes with rayon, and each rustic backup already parallelizes internally) are the expected reasons. Report the misses as prominently as the wins.
Prior work and novelty
| Work | What it does | How psync differs |
|---|---|---|
| Thread-level speculation (Steffan et al., ISCA 2000) | Runs possibly dependent code in parallel threads with hardware rollback. A thread that makes a system call stalls until it is safe. | I/O is exactly what Phase II overlaps. psync runs the real calls, and orders writes ahead of time instead of rolling back. |
| SpecHint (Chang and Gibson, OSDI 1999) | Pre-executes an unmodified program speculatively to issue prefetch hints for its future reads. | Reads only, as hints. psync performs the real reads, and writes in order. |
| AutoFutures (KIT, 2012) | Turns independent Java calls into futures on threads. | The closest precursor, without an effect model. |
| Rayon | Data parallelism you write by hand (par_iter, join), free of data races by Rust’s types. | Rayon does not order I/O; that is left to you. psync chooses what to run in parallel and orders effects. |
The audit: where Phase II helps
Status: done for the corpus scan and two projects, rustic and tauri-bundler.
The question is not whether threads can make synchronous code faster: they can. It is how often psync, as built, finds a place where they do, and whether that place is worth it. This chapter records the answer, including where the answer is “nowhere”.
The corpus scan
psync-scan applies #[psync::graph] with default options to every function of a set of files,
as if each one were annotated, and reports every region where two waiting statements share a
level in different chains: two awaits, or two blocking calls. A region where a wait only runs
beside a Vec::new() gains nothing, so it does not count.
cargo build --release -p psync-graph --features cli --bin psync-scan
find repos -name '*.rs' | xargs target/release/psync-scan --sync > sync.tsv
find repos -name '*.rs' | xargs target/release/psync-scan --async > async.tsv
Over the 43 repositories cloned for the audit (36,526 files):
| Functions | Functions with two overlapping waits | Outside tests, benches, examples, build scripts | |
|---|---|---|---|
| async | 96,360 | 14,641 (15,809 regions) | 7,100 functions in 42 repositories |
| synchronous | 427,313 | 0 | 0 |
Without hints, Phase II finds nothing. The 460 regions the scan reports inside synchronous
functions are all async blocks (Box::pin(async move { .. }), cx.spawn(async move { .. })),
which are Phase I code. There are three reasons, and they are the same three seen by hand in the
audit’s ten synchronous findings:
- Processes are ordered. Most recognizable blocking calls start processes (
git,xcrun,codesign,vswhere), and a child process may touch anything, so two of them never overlap. tauri’sbuild_tools_versionrunsvswheretwice, as two read-only queries, but nothing in the code says that the runs do not interfere.#[psync::independent]would. - Requests hide in helpers. The slow calls of the audit’s findings are
download(url),repo.infos_files(),opts.backup_snapshot(..). None of them names the network, so without a hint psync cannot know that they wait. - A recognizable network call rarely has a sibling. Code that opens a
TcpStreamusually does one thing with it.
So Phase II, as a source transformation, needs to be told where the time goes:
#[psync::par] on the statement, or compiler facts that a callee reaches the network (the
design’s next step). That is unlike Phase I. There, .await marks every wait, and the same scan
finds 7,100 production functions with independent awaits.
What the scan found in psync itself
Running psync over 36,000 files of other people’s code also tested psync, and found three bugs, all fixed:
- A crash in the loop rewriter, in 52 functions of DataFusion, greptimedb and lighthouse. A
loop body that ends in an await without a semicolon (
.run_test(..).await, valid Rust because its value is()) produced invalid code, and#[psync::graph]failed to compile. Chains now end every member with a;. The test isloop_bodies_may_end_in_an_awaitintests/graph.rs. - Blocking statements recognized too loosely. The first version treated any statement
mentioning
Commandas a process, including clap’sCommand::parse_fromandCommand::Reply, an enum variant. Only a path and a waiting method count now. - Blocking calls inside macros. Two
assert!(Command::new(..).status()..)statements were recognized as blocking, and since psync cannot see effects inside macro arguments, they would have run side by side with no effects at all. Macro arguments are no longer scanned for blocking calls.
Measured on real code
rustic, built with psync
rustic at commit 143d073, built twice: as released, and with the edits a user would make
(scripts/audit/rustic/):
repoinfo: the struct literalInfos { files: .., index: .. }becomes twolets marked#[psync::par], because psync schedules statements, not struct fields.repo.open(..)takes the repository by value while the other statement borrows it, so it opens a clone:Repo(repo.0.clone()).open(..).diff: the two snapshot lookups are marked#[psync::par].
Both run against a REST repository of 20 snapshots, behind toxiproxy, which adds latency to every response. Both binaries print the same output at every latency, and the harness checks this before timing. Medians of 11 runs, on the shared 32-thread machine (load average about 45):
| Added latency | repoinfo sequential | psync | Speedup | diff sequential | psync | Speedup |
|---|---|---|---|---|---|---|
| 0 ms | 372 ms | 366 ms | 1.02× | 384 ms | 390 ms | 0.98× |
| 5 ms | 408 ms | 440 ms | 0.93× | 594 ms | 551 ms | 1.08× |
| 20 ms | 578 ms | 539 ms | 1.07× | 951 ms | 961 ms | 0.99× |
| 50 ms | 867 ms | 668 ms | 1.30× | 1725 ms | 1740 ms | 0.99× |
These are smaller than the 2.00× of the repoinfo shape in examples/phase2.rs, and the reason
is the point of this audit:
repoinfogains 1.30× at 50 ms, and nothing on a local disk. Both statements run in parallel, but the command also opens the repository (config, keys, snapshot list) before them, and that part stays sequential. The shape inexamples/phase2.rshad only the two statements.diffgains nothing. The server’s log shows 46 requests, the same 46 for both binaries. The two lookups psync overlaps are 2 of them. The remaining 18 data reads come from comparing the two trees, insidediff(repo.ls(&node1)?, repo.ls(&node2)?, ..), which streams one tree against the other, and psync cannot split a stream. At most one round trip is saved, about 3%, which is less than the noise.
The diff edit also exposed a psync miss, now fixed. let path2 = path2.unwrap_or(path1);
sits between the two lookups and feeds the second one. psync did not know unwrap_or, so the
statement was its own chain, and it pushed the second lookup into a later level than the first.
unwrap_or with pure arguments is now pure (test cheap_statements_do_not_delay_waits).
tauri-bundler, built with psync
prepare_tools in tauri-bundler, at commit 548a369, fetches the tools that build an AppImage:
three downloads, each skipped if the file is already in the cache. It was built four ways
(scripts/audit/tauri/):
- seq: as released;
- par:
#[psync::graph]on the function and#[psync::par]on the threeif !path.exists() { download; write }statements, which is what a user marks first; - spec:
parand#[psync::speculate]on the second and third, built withcargo psync build, so the macro schedules with the compiler’s facts; - hinted:
spec, and also#[psync::independent]on the three, built without facts.
par alone overlaps nothing, and psync is right not to. Each statement calls download(..) and
write_and_make_executable(&path, ..), two helpers psync cannot see into. As far as it knows, the
first statement’s write may change what the second reads. The hints say what the code means:
each statement writes only its own cache file, and filling a cache is harmless even if an earlier
download fails.
The real code needed two more fixes in psync before even hinted overlapped. Between the
downloads sit let linuxdeploy = tools_path.join(..) and
let linuxdeploy_arch = if arch == "i686" { "i386" } else { arch };. psync did not know that
Path::join and an if that picks between two values are pure, so it kept them in order with the
downloads. Once they were pure, the second download had two edges into it, one from each binding.
A node joined a chain only when it had a single predecessor, so the download was left in a later
level. A node now joins the chain that ends in its last predecessor when all its edges come from
that chain, because members of a chain run in order (test
path_joins_and_pure_ifs_do_not_delay_downloads). join with one argument is pure, and
handle.join(), which waits for a thread, is not.
With the compiler’s facts, the independent hint is no longer needed. The driver finds that
write_and_make_executable(path, ..) writes the file passed as its parameter 0
(per-argument effects). The macro takes that file
from the call, &apprun, and from let apprun = tools_path.join(format!("AppRun-{arch}")) it
knows the target is {tools_path}/AppRun-{arch}, which differs from
{tools_path}/linuxdeploy-… (targets). So
the three writes are to three files. speculate stays: whether filling a cache before an earlier
download has failed is acceptable is about intent, not about effects.
The compiler pass checks the schedule and reports one warning. In MIR, the two paths are values
computed by join and format!, so the driver cannot tell them apart. The macro tells them
apart from the tokens, under the assumption above that different names in one directory are
different files. This is the one place in the audit where the macro knows more than the
checker.
The benchmark runs prepare_tools on an empty cache, against a local mirror of the GitHub
release files (through tauri’s own TAURI_BUNDLER_TOOLS_GITHUB_MIRROR), with files of the real
sizes (18 KB, 12 MB, 9 MB). toxiproxy adds latency, and in two rows caps each connection’s
bandwidth. All four builds write the same files at every setting. Medians of 21 runs, on the
shared machine (load average about 40):
| Latency | Bandwidth per connection | seq | par | spec | hinted | par | spec | hinted |
|---|---|---|---|---|---|---|---|---|
| 0 ms | unlimited | 80 ms | 60 ms | 43 ms | 43 ms | 1.34× | 1.84× | 1.85× |
| 20 ms | unlimited | 120 ms | 120 ms | 59 ms | 55 ms | 1.00× | 2.05× | 2.18× |
| 100 ms | unlimited | 359 ms | 360 ms | 135 ms | 136 ms | 1.00× | 2.66× | 2.65× |
| 100 ms | 20 MB/s | 1385 ms | 1385 ms | 720 ms | 720 ms | 1.00× | 1.92× | 1.92× |
| 100 ms | 5 MB/s | 4537 ms | 4558 ms | 2540 ms | 2521 ms | 1.00× | 1.79× | 1.80× |
spec and hinted build the same schedule, and their times agree. The 0 ms row is within the
noise of the machine: an earlier run of the same binaries measured 57 ms for seq.
This is the best case the audit found: a command that is a few independent requests and little else. With a bandwidth cap, the parallel time is bounded by the largest file (12 MB at 5 MB/s is 2.4 s), so the gain falls toward the ratio of the total to the largest. The cap here applies to each connection. On a link that is itself the bottleneck, parallel downloads share it, and the gain would be smaller.
The shapes
Three of the audit’s ten synchronous findings, rebuilt as shapes over real sockets in
examples/phase2.rs, are in Synchronous code: 2.0× to 3.0× where
the downloads or reads are independent, 1.00× (correctly) for tauri’s code as written, and a
slowdown where a statement is cheaper than a thread.
What this means
Phase II works: the code it runs in parallel is correct, and the overlap is real. But it helps
real synchronous code much less than Phase I helps async code. It needs hints to find anything,
and where it finds something, other sequential work in the same command dilutes the gain. The
largest gains sit where a command is a few independent requests and little else, as in tauri’s
prepare_tools: 2.0× to 2.7× on the real code once latency matters. With cargo psync build, it
takes one hint, speculate, which states intent. The effects come from the compiler.
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 predicted speedup origin
P1 independent awaits 205.6 ms 60.2 ms 60.1 ms 3.41x anza-xyz/agave
P1 independent awaits 271.3 ms 60.3 ms 60.3 ms 4.50x matrix-org/matrix-rust-sdk
P1 independent awaits 55.3 ms 35.2 ms 35.1 ms 1.57x loco-rs/loco
P1 independent awaits 48.8 ms 8.1 ms 8.2 ms 5.99x LemmyNet/lemmy
P2 await in a loop 241.8 ms 40.4 ms 40.3 ms 5.99x delta-io/delta-rs
P2 await in a loop 302.0 ms 50.5 ms 50.3 ms 5.98x apache/datafusion
P2 await in a loop 225.9 ms 45.2 ms 45.2 ms 4.99x LemmyNet/lemmy
P2 await in a loop (fission) 211.0 ms 60.5 ms 60.3 ms 3.49x jdx/mise
P2 await in a loop (while-loop fission, hinted) 270.9 ms 45.2 ms 45.2 ms 5.99x launchbadge/sqlx
P2 await in a loop (fission) 160.8 ms 40.3 ms 40.2 ms 3.99x apache/iggy
P3 per-item chains 267.0 ms 45.4 ms 45.3 ms 5.88x kube-rs/kube
P3 per-item chains 604.2 ms 191.6 ms 191.4 ms 3.15x neondatabase/neon
P3 per-item chains 347.2 ms 50.4 ms 50.3 ms 6.89x quickwit-oss/quickwit
P4 late start 110.4 ms 70.3 ms 70.3 ms 1.57x GreptimeTeam/greptimedb
P4 late start 200.6 ms 120.5 ms 120.4 ms 1.66x sigp/lighthouse
P4 late start 176.0 ms 70.4 ms 70.3 ms 2.50x zed-industries/zed
geometric mean speedup over 16 examples: 3.79x
predicted is the rewrite’s time as psync predicts it from a third, profiled run of the
original, before the rewrite runs (Predicting the speedup).
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.
Exercises
- A P1 region awaits three independent calls of 20, 30 and 50 ms. What does it take before and after the rewrite, and what is the speedup?
- A P2 loop looks up 6 keys at 40 ms each. What does it take with the default
bound, and withbound = 4? - Why does the suite report a geometric mean, not an arithmetic one?
- Without its
speculatehint, matrix-rust-sdk’s example runs at about 1.0×. What does psync keep in order there, and why does the hint make that safe?
Answers
- 100 ms before, 50 ms after (the longest wait), so 2×: the sum of the waits over the longest.
- 240 ms sequentially. With the default of 16 all six run at once: 40 ms, 6×. With
bound = 4the first four take 40 ms, then the last two another 40 ms: 80 ms, 3×. - Speedups are ratios. A geometric mean treats 2× faster and 2× slower as cancelling out, and is not dominated by one large ratio the way an arithmetic mean is.
- The PUTs go to distinct event types, so they do not conflict with each other. But each PUT
writes, and each one comes after a
?that may leave. psync does not start a write before an earlier statement that may exit, so the eight PUTs stay one after another. The PUTs set account data to fixed values, so doing one that sequential code would have skipped after an error is harmless. That is whatspeculatesays.
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 128 requests in flight. 32 clients offered about
3,600 concurrent requests (about 113 each) 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, and it now exists: psync::set_in_flight_budget
(Nested loops multiply their bounds).
This run has not been repeated with it yet.
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.
What is new, and what is not
psync stands on a lot of earlier work. This chapter says, idea by idea, who did it first, what psync does differently, and where its speedups come from. Every chapter that introduces one of these ideas ends with a short Prior work and novelty section that goes into more detail.
Each source below was read from the paper or the official documentation (the research notes, with
a quote and section for each, are in the repository at research/prior-work-verified.md). Where a
source could not be read, this chapter says so rather than guess.
The short version
Almost every single idea in psync has been done before, often decades ago:
- Overlapping independent awaits automatically. ReSynchronizer did it for JavaScript in 2021, with a side-effect analysis and a table of file-system and network calls.
- Joining independent chains at compile time. GHC’s ApplicativeDo does it for Haskell.
- Raising failures in their sequential order. Haxl and Safe Futures both do it.
- Prefetching I/O in loops. Compilers have done it since 1996.
- Proving that a concurrent schedule equals the serial one. Safe Futures proves it.
- Cross-crate summaries over MIR. These exist for memory-safety analysis.
- Predicting a speedup from a dependency graph. WebProphet does it for web pages.
Measured on the same 16 real-world functions, scheduling them by ReSynchronizer’s rules gives a geometric mean of 1.28×, and psync 3.79× (details below).
What psync adds is the combination, and a few specific differences in each idea that the earlier systems do not have:
- Effects compared by target, not by kind. ReSynchronizer keeps every file read behind every file write. psync compares paths, URLs and keys, so two writes to different files overlap. When the targets are only known at run time, a gate compares the values, file identity included, and falls back to the original order when they collide. The closest precursor, Quasi-Static Scheduling for Safe Futures, places barriers by static alias analysis, for memory only.
- Rust’s control flow.
?,return,breakandcontinueinside chains, and loops turned into bounded prefetch. ReSynchronizer never moves code across areturnor a loop test; ApplicativeDo never reorders effects at all. - No new runtime, no threads, no annotations. The rewrite is one future that polls its chains on the caller’s task. It works on Tokio, embassy or a microcontroller, with borrowed data. Haxl needs its own monad, Safe Futures a modified JVM, Æminium a new language, DPJ annotations.
- A certificate per function, checked by a proven-sound checker, against a model of the outside world. Translation validation (Pnueli, Necula) checks a compiler’s output once per run; Safe Futures proves schedules equivalent for memory. psync’s Lean checker validates each rewritten function’s schedule, with I/O events allowed to reorder only where a commutativity specification of the service says they commute.
Idea by idea
| Idea | Closest prior work | What it already did | What psync does differently | More |
|---|---|---|---|---|
| Overlap independent awaits | ReSynchronizer (ECOOP 2021), AutoFutures (2012) | automatic await overlap in JavaScript, with a file/network effect table; futures for independent Java calls | Rust, at compile time, in a macro; effects by target; exits and loops; gates and certificates | Basic concepts |
| Chains joined in levels | ApplicativeDo (Haskell 2016), Haxl (ICFP 2014) | independent segments joined concurrently, decided from bindings | reorders past statements whose effects are independent, not only their bindings | Basic concepts |
| Early exits | Haxl §8.1, Safe Futures (OOPSLA 2005) | the leftmost exception wins, so the result is deterministic | Rust ?, return, break, continue, across chains on one task | Early exits |
| Loops | Mowry et al. (OSDI 1996), futures::StreamExt::buffered | compiler-inserted I/O prefetch hints; hand-written bounded concurrency | runs the real calls early, so it checks items for conflicts | Loops |
| Effects of the outside world | ReSynchronizer Table 1, DPJ (OOPSLA 2009), QSS (PPoPP 2008) | effect tables per environment; nested regions; barriers from alias analysis | targets that overlap by prefix, value gates with file identity | Side effects |
| Summaries across crates | Zhou, Sun and Criswell (2023), MirChecker (CCS 2021) | per-function MIR summaries for whole programs | the summaries hold effects and their targets, fed back to the macro | From MIR to summaries |
| Certificates | Translation validation (1998, 2000), CompCert, Safe Futures | per-run validation; a verified compiler with identical I/O traces; serial equivalence for memory | I/O may reorder under a commutativity spec; a Lean checker proved sound | Certified schedules |
| World model | Scalable Commutativity Rule (SOSP 2013), linearizability (1990) | interface-level commutativity of POSIX calls; atomic operations | the same idea, used to justify reordering a client’s calls | The outside world |
| Predicting the speedup | Coz (SOSP 2015), Yang and Miller (1988), WebProphet (NSDI 2010) | virtual speedups; critical paths; what-if latency from a fetch graph | the graph comes from the code, per control path, for one automatic rewrite | Predicting the speedup |
| Synchronous code (Phase II) | thread-level speculation (ISCA 2000), SpecHint (OSDI 1999), Rayon | speculative threads that stall on system calls; speculative read hints; data parallelism by hand | real calls, reads and ordered writes, on worker threads, chosen automatically | Phase II design |
Where the speedup comes from
psync does no work faster. It waits less. When a function makes several calls that wait on the network or the disk, the sequential code waits for each in turn: the sum of the waits. After the rewrite, each level waits as long as its slowest chain. So the speedup is roughly
speedup ≈ (sum of all waits) / (sum over levels of the longest chain in each level)
and psync can compute that number before it rewrites anything (Predicting the speedup). This is why the speedups below are 1.6× to 6.9×. Three waits of equal length give 3×; a loop of six items with a bound of 16 gives 6×; a function whose second half must wait for its first gains little.
Measured: the same functions under ReSynchronizer’s rules
The closest earlier tool, ReSynchronizer, works on JavaScript, so it cannot run on these Rust
functions. Instead, psync can schedule a function by ReSynchronizer’s rules, with
#[psync::graph(baseline = resync)]:
- an await may start earlier and be awaited later, but only within one block: nothing moves across a loop or a branch (its §4.6);
- effects are one per environment (its §4.4): every file effect touches “the file system”, every network or service call “the network”, so a write orders every other access to its environment;
- no run-time checks, and none of psync’s hints (
speculate,independent).
cargo run --example graph_suite --no-default-features -- --brief --resync times each of the 16
functions three ways: as written, by these rules, and by psync. Two runs agreed to 0.02×.
graph_suite --resync; the baseline is ReSynchronizer's rules applied to Rust by psync, not the JavaScript tool.| Functions | ReSynchronizer’s rules | psync | |
|---|---|---|---|
| all | 16 | 1.28× | 3.79× |
without a scheduling hint (speculate, independent) | 11 | 1.44× | 3.89× |
| loops (P2, P3) | 9 | 1.00× | 4.99× |
| straight-line code (P1, P4) | 7 | 1.77× | 2.67× |
Read the figure row by row and the differences have three causes:
- Loops: 1.00× against 3.1× to 6.9×. All nine loops stay sequential under the rules, because nothing moves across a loop test. psync prefetches the items, with a check per item.
- Moving past a loop or a branch. zed reads the database after a loop over S3 manifests, and the read needs nothing from the loop. psync starts it before the loop: 2.50×. By the rules it must wait: 1.00×.
- Targets, and hints. matrix-rust-sdk makes eight PUTs to distinct account-data event types;
greptimedb uploads a Parquet file that does not need the index it builds first. By the rules
every write is “the network”, so each waits for the one before: 1.00×. psync compares the
targets, and with the function’s
speculatehint (the PUTs and the upload are idempotent, so they may run before an earlier call has succeeded) reaches 4.49× and 1.57×.
Where the rules apply, they match psync exactly: agave, loco, lemmy’s six reads and lighthouse run at the same speed both ways (3.41×, 1.57×, 5.98×, 1.67×). For straight-line awaits without writes, ReSynchronizer already had the idea, and psync adds nothing to the speed.
Two cautions. The baseline is psync’s reading of ReSynchronizer’s published rules, applied to Rust; it is not the JavaScript tool, whose analysis of particular libraries may differ. And these 16 shapes come from psync’s own audit, which looked for what psync rewrites; a sample chosen by ReSynchronizer’s authors might show a smaller gap.
What psync does not claim
- It is not sound on its own. It assumes that names mean what they say (
getreads,putwrites), that unknown calls only read, and that different receivers are different resources (What is checked, what is assumed). A certificate proves a schedule safe given the effects psync found, not that it found the right ones; the proof that summaries over-approximate real accesses covers a fragment of MIR (Certified schedules). - It does not batch or cache. Haxl, Stitch and DataLoader merge many small reads into one request. psync sends the same requests, at the same time.
- It can hurt under load. Offering every request at once can overload a server: 32 clients refreshing DataFusion’s catalog together ran at 0.76× (kube-rs and DataFusion).
Sources
- Arteca, Tip, Schäfer. Enabling Additional Parallelism in Asynchronous JavaScript Applications (ReSynchronizer). ECOOP 2021.
- Marlow, Brandy, Coens, Purdy. There is No Fork (Haxl). ICFP 2014.
- Marlow, Peyton Jones, Kmett, Mokhov. Desugaring Haskell’s do-notation into Applicative Operations (ApplicativeDo). Haskell Symposium 2016.
- Molitorisz, Schimmel, Otto. Automatic Parallelization using AutoFutures. KIT, 2012 (extended abstract).
- Stork et al. Æminium: A Permission-Based Concurrent-by-Default Programming Language Approach. TOPLAS 2014.
- Bocchino et al. A Type and Effect System for Deterministic Parallel Java. OOPSLA 2009.
- Welc, Jagannathan, Hosking. Safe Futures for Java. OOPSLA 2005.
- Navabi, Zhang, Jagannathan. Quasi-Static Scheduling for Safe Futures. PPoPP 2008.
- Rinard, Diniz. Commutativity Analysis. TOPLAS 1997.
- Clements et al. The Scalable Commutativity Rule. SOSP 2013.
- Herlihy, Wing. Linearizability. TOPLAS 1990.
- Li et al. MirChecker. CCS 2021. Zhou, Sun, Criswell. Fast Summary-based Whole-program Analysis to Identify Unsafe Memory Accesses in Rust. arXiv 2310.10298, 2023.
- Ho et al. Charon. arXiv 2410.18042. Ho, Protzenko. Aeneas. ICFP 2022.
- Pnueli, Siegel, Singerman. Translation Validation. TACAS 1998. Necula. Translation Validation for an Optimizing Compiler. PLDI 2000.
- Leroy. Formal Verification of a Realistic Compiler. CACM 2009. Bell. A Proof Theory for Loop-Parallelizing Transformations. Princeton, 2014.
- Mowry, Demke, Krieger. Automatic Compiler-Inserted I/O Prefetching for Out-of-Core Applications. OSDI 1996.
- Curtsinger, Berger. Coz. SOSP 2015. Yang, Miller. Critical Path Analysis for the Execution of Parallel and Distributed Programs. ICDCS 1988. Zhou et al. wPerf. OSDI 2018. Li et al. WebProphet. NSDI 2010.
- Steffan et al. A Scalable Approach to Thread-Level Speculation. ISCA 2000. Chang, Gibson. Automatic I/O Hint Generation through Speculative Execution (SpecHint). OSDI 1999.
Not read, so not relied on: Kremlin (PLDI 2011), which reportedly predicts parallel speedup and must be checked before psync claims its predictor is new; Hollingsworth and Miller’s slack; the Asynchronizer tools for Android and C#; Rudra’s paper.
A tour of the repository
This part is for people who want to change psync. It assumes the Foundations part, or the same background. It shows where everything lives, how a change travels through the code, how to set up a development environment, and how to check a change before you send it.
The crates
| Path | What it is | Built with |
|---|---|---|
psync-macros/ | the proc-macro crate: #[graph] and the hint attributes, all thin wrappers | stable |
psync-graph/ | the analysis and code generation behind #[graph], as an ordinary library; the psync-expand tool; the Foundations examples | stable |
src/ (crate psync) | what users depend on: re-exports the macros, the runtime the generated code calls (graph_rt.rs, as psync::__private), and the executors | stable, no_std |
psync-check/ | cargo psync and psync-driver, the compiler-level checks and facts | the pinned nightly |
verify/ | the Lean proofs and the Lean tutorial | Lean 4.22 |
tests/ | behaviour tests of the macro and the executors | stable |
examples/graph_suite/ | sixteen real-world shapes, each run sequentially and with psync | stable |
book/ | this book (mdBook) | mdbook |
psync-check is outside the Cargo workspace (exclude in the root Cargo.toml), because it
links rustc’s internal crates and needs its own toolchain.
The life of an annotated function
Follow one #[psync::graph] async fn through the code, in the order things happen.
psync-macros/src/lib.rsgraph(attr, item)converts the token streams and callspsync_graph::expand.psync-graph/src/lib.rsexpandparses the options (Options::parse), honoursoffandPSYNC_GRAPH=off, and callstransform_fn. That builds theScope(which bindings aremut,&muthandles or#[psync::fresh]), loads the compiler facts ifPSYNC_FACTSis set (facts.rs), runs theRewriter, strips the hints, and adds the__PSYNC_GRAPHmarker.rewrite.rsRewriteris aVisitMut. For each block of async code, innermost first, it sendsforandwhileloops toloops.rs, then calls the hoisting and scheduling steps.hoist.rssplits statements so each hidden await becomes its own binding.classify.rsdecides for each statement: node or barrier, and for a node, what it binds, whether it awaits, may exit or may panic, and its effects (fromeffects.rs) and accesses (fromaccess.rs).schedule.rsplandraws the edges (depends), fuses chains and assigns levels.emitgenerates each level’s join, withexits.rsproviding the code that records exits and replays them.src/graph_rt.rsis what the generated code calls at run time:maybe_done_at(a chain),over_atandjoin_all_bounded(a prefetched loop), andBranchandRethrow(the?plumbing).
#[graph(explain)] prints the report that steps 5 and 6 build (Report in lib.rs), and
psync-expand prints it as JSON with the generated code.
The life of cargo psync build
psync-check/src/bin/cargo-psync.rsrunscargo checkintarget/psync, withRUSTC_WRAPPERset topsync-driverand the environment variables inpsync_check::env.src/bin/psync-driver.rsis rustc with a callback. After analysis it runs theCheckerand theAnalyzerfromsrc/driver/analysis.rs.analysis.rs:Analyzer::summarizecomputes summaries from MIR. Each body’s own effects come fromlocalandcall, and summaries are fixed points over call-graph components (component).call_factswrites a fact for every call site in annotated functions, andwrite_summarieswrites the crate’s summary file.Checker::runfinds the macro’s markers (markers) and checks each level and loop prefix.src/lib.rs(psync_check, no compiler dependency) holds the shared model:Effect,conflict, the summary and findings file formats, andlink, which resolves deferreddyncalls over the whole build.facts_textwritesfacts.tsv.- Back in
cargo-psync.rs,check_and_linkre-runs the check when linking resolved new calls.buildthen runs one more check pass withPSYNC_FACTSpointing atfacts.tsv. In it, the macro (step 2 above) schedules with the facts, and the driver checks the schedule that results. Last, it runs a plaincargo build(no driver, the normal target directory) with the samePSYNC_FACTS, so the binary gets the schedule that was just checked.
Setting up
git clone <the repository> && cd psync
cargo test --no-default-features # the macro and the single-core executor
The default feature rp235x builds the embedded executor for the RP2350. On a host,
--no-default-features (and --features std for MultiExecutor) is what you want.
For psync-check you need rustup, which reads psync-check/rust-toolchain.toml and installs the
pinned nightly with rustc-dev on first use:
cd psync-check
cargo test # builds the driver and runs it on the fixture
cargo install --path . --locked # puts cargo-psync and psync-driver on your PATH
rust-analyzer needs rustc_private support to understand the driver. psync-check/Cargo.toml
sets [package.metadata.rust-analyzer] rustc_private = true. Open psync-check/ as its own
project so the pinned toolchain is used.
Lean: install elan. lean verify/Schedule.lean fetches nothing, because the proofs use only
Lean’s core library.
The book: cd book && mdbook build, then open book/book/index.html.
Before you send a change
Run all of these. Each takes from seconds to a couple of minutes.
cargo test --no-default-features # graph + scheduling tests
cargo test --no-default-features --features std --test multi # MultiExecutor
cargo test -p psync-graph # analysis unit tests, Foundations examples
cargo run --example graph_suite --no-default-features -- --brief # speedups: geometric mean ~3.8x
(cd psync-check && cargo test) # driver: check, --facts, fix
lean verify/Schedule.lean && lean verify/Tutorial.lean # proofs
(cd book && mdbook build) # the book
If your change alters what psync does, it changes the book too. Update the chapter that describes the behaviour, and the report output it shows. The rest of this part gives the recipes for the most common changes:
- Adding an effect rule: teach the macro or the driver what a call does.
- Adding a check: a new warning in
cargo psync check. - Adding a test: which suite, and how.
Writing for the book
-
Reports you show after a Rust example (a
textblock starting withregion, or with thepsync::graphheader) are checked against what psync prints, byscripts/check-book-examples.py. Paste real output. -
Quizzes are plain fenced blocks, turned into widgets by
book/theme/quiz.js. No preprocessor is needed, and the block reads well as text:```quiz ? The question. `code` works. + A right answer (several `+` make it "pick all that apply"). - A wrong answer. > Why, shown after the reader answers. ``` -
Benchmark figures are SVG drawn by
scripts/figures.pyintobook/src/figures/and included with{{#include ../figures/NAME.svg}}. The numbers live in the script, next to the name of the chapter that measured them: change both together, then run the script.
Adding an effect rule
An effect rule teaches psync what a call does to the outside world. There are two places for rules, one for each half of psync, and a complete change usually touches both:
| Where | Decides from | Used by |
|---|---|---|
psync-graph/src/effects.rs | the call’s tokens: path, method name, literal arguments | the macro, always |
psync-check/src/driver/analysis.rs, io_effect and its neighbours | the resolved callee path in MIR, and constant arguments | cargo psync check, and the macro through facts |
If the two halves disagree, the danger is in the driver. Under cargo psync build, a compiler
fact replaces the macro’s own guess for that call. So a driver rule that misses an effect the
macro would have seen makes psync less safe with facts than without them.
The shape of a rule
Both halves describe an effect the same way: a domain (file system, network, environment,
process, output, or a named service), an access (read, write, or ordered write) and an
optional target (a path or key from a string literal). Two effects conflict when at least
one writes, the domains match, and the targets may be equal (psync_check::conflict; see
Effects and summaries).
Worked example: file operations on two paths
This is a real change, made while this chapter was written.
The bug. The driver’s io_effect recognizes std::fs::copy as a file write and takes the
target from the first argument:
std::fs::copy("draft.html", "site.html") // driver said: write file "draft.html"
That is wrong twice over. copy reads its first path and writes its second. So a read of
site.html running at the same time was not reported as a conflict. With facts, the macro
would even schedule it concurrently. rename, hard_link and symlink had the same problem.
The macro’s own rule in effects.rs already pushed a second write for these functions:
// `rename(from, to)`, `copy(from, to)`, `hard_link(src, dst)` also touch the second.
if kind == Kind::Write && c.args.len() >= 2
&& matches!(last.as_str(), "rename" | "copy" | "hard_link" | "symlink" | "soft_link")
{
self.push(Domain::Fs, Kind::Write, target_of(c.args.iter().nth(1)), op, false);
}
Step 1: write the failing test first. Effects hidden in a callee are the driver’s job, so
the test belongs in the driver’s fixture, psync-check/tests/fixtures/hidden/app/src/lib.rs.
Choose names that are not verbs the macro knows (grep the verb lists in effects.rs).
Otherwise the macro orders the calls by itself, there is nothing concurrent left to check, and
the test proves nothing. publish is a known verb, so the fixture uses promote:
/// `fs::copy` writes its *second* path: `promote` writes `site.html`, which `read_site` reads.
async fn promote() -> std::io::Result<()> {
std::fs::copy("draft.html", "site.html").map(|_| ())
}
async fn read_site() -> std::io::Result<usize> {
Ok(std::fs::read("site.html")?.len())
}
#[graph]
pub async fn release() -> Result<usize, Error> {
promote().await?;
let n = read_site().await?;
Ok(n)
}
Then, in psync-check/tests/fixture.rs, assert the new finding, raise the total, and add
release to the functions that facts must keep sequential:
assert!(
app.findings.iter().any(|f| f.kind == "conflict"
&& f.function == "release"
&& f.message.contains("write file \"site.html\"")),
"{:#?}", app.findings
);
Run cargo test in psync-check/ and watch it fail.
Step 2: the rule. In analysis.rs, next to io_effect:
/// File operations on two paths, which write the second: the access to the first.
fn two_path_fs(name: &str) -> Option<Access> {
match name {
"copy" => Some(Access::Read),
"rename" | "hard_link" | "symlink" | "soft_link" | "symlink_file" | "symlink_dir" => {
Some(Access::Write)
}
_ => None,
}
}
And where call applies io_effect, it records two effects for these functions, reading the
second constant argument with string_constant:
let second = (domain == Domain::Fs && keeps_target).then(|| two_path_fs(&name)).flatten();
match second {
Some(first_access) => {
let to = args.get(1).and_then(|a| self.string_constant(a));
add(Domain::Fs, first_access, target);
add(Domain::Fs, Access::Write, to);
}
None => add(domain, access, if keeps_target { target } else { None }),
}
Note two choices that keep the rule sound:
- When unsure, write.
hard_linkchanges the original’s link count andsymlinkmay replace an existing link, so they count as writes on both paths. Onlycopy, which certainly does not change its source, gets a read. - A missing constant means “any file”. If the second argument is not a string literal,
toisNone, and the write conflicts with every file effect.
Step 3: run everything. cargo test in psync-check/ now passes, and cargo psync fix on
the fixture inserts one more hint. Then run cargo psync check on a real project (the
benchmark branches of kube-rs and DataFusion are what the book’s numbers come from), because a new rule can
create warnings in code that was clean.
Step 4: the book. Say what changed where users will look for it. Here that is the list of recognized operations in Side effects and the fixture counts in Scheduling with compiler facts.
Other kinds of rules
| You want to | Change | Test with |
|---|---|---|
a new verb (refresh reads) | READ_VERBS / WRITE_VERBS / ORDERED_VERBS in effects.rs; the driver reuses them via psync_graph::verb_of for other crates’ APIs | a unit test in effects.rs (report(..), assert the edge) |
| a new I/O function of std or a runtime | io_effect in analysis.rs, and the matching token rule in effects.rs | the fixture |
| a new crate whose I/O is known by path (like tokio’s) | IO_CRATES in analysis.rs | the fixture, with that crate as a dependency |
| a new barrier (an await whose position matters) | DELAY_AWAITS / GUARD_AWAITS in classify.rs | a tests/graph.rs test that checks timing and order |
| a new pure method (may move freely) | PURE_METHODS in access.rs | a unit test asserting no edge |
Users can also extend the verbs without changing psync, with
#[psync::graph(effects(read(..), write(..), ordered(..)))]. A rule belongs in psync itself when
it holds for everyone who uses that API.
Adding a hint
Hints showed what each hint is for. This chapter shows what a hint is inside psync, follows one through every stage, from the attribute to the proof, and then builds a new hint with you, step by step. By the end you will be able to answer three questions about any hint, existing or proposed:
- Which edge of the graph does it remove (or add)?
- Which part of the certificate’s footprint does it remove?
- Who checks the fact it states: the compiler,
cargo psync check, or nobody?
You need The graph and the schedule and
Certified schedules first. Have psync-graph/src/classify.rs and
psync-graph/src/schedule.rs open beside this page.
A hint is a flag that turns off one rule
psync draws an edge between two statements when one of six rules says their order matters
(edge in schedule.rs, see Dependency edges). The rules are tried
in order and the first that matches is the reason the report shows, so an edge with two reasons
shows one at a time:
| Rule | Example reason in the report | Can a hint turn it off? |
|---|---|---|
| data flow: B reads a name A defines | reads `user` | no |
| shadowing | rebinds `x` | no |
| conflicting accesses to one place in memory | writes `self.cache` | no |
| effects on one outside resource conflict | write `client` .. vs write `client` .. | independent |
B writes, and A may exit before it (a ?, return, break, or a call that panics explicitly) | may exit before `set` runs | speculate |
| two plain statements keep their order | effect order | no |
The first three are about memory inside the program. The Rust compiler checks them anyway: if psync got one wrong, the borrow checker would reject the generated code. No hint may switch them off, because no fact you know can make two lanes safely write the same variable.
The fourth and fifth are about the outside world: files, servers, processes. psync cannot see that world from tokens, so it guesses on the safe side, and these two guesses can be overruled.
The sixth keeps plain statements in order: statements that are neither a binding nor an await,
such as v.push(x); or println!(..). They change state in place and are cheap, so moving them
buys nothing. No hint touches this rule.
That is all a hint is: a statement-level flag that turns off one rule for one statement.
Here is where the flags are set, in classify (classify.rs):
let speculate = scope.effects.speculate || attrs.iter().any(|a| is_psync_attr(a, "speculate"));
Class::Node(Box::new(Node {
effects: found.effects,
unclassified: found.unclassified,
panics: found.panics,
speculate,
independent: scope.effects.independent()
|| attrs.iter().any(|a| is_psync_attr(a, "independent")),
And here is where they act, in edge (schedule.rs):
// Effects on the same file, service or other outside resource keep their order.
if !(a.independent || b.independent)
&& let Some(why) = crate::effects::conflicts(&a.effects, &b.effects)
{
return Some(why);
}
// A write is not performed before an earlier statement that may leave: sequential code
// would not have performed it at all.
if (a.exits || a.panics)
&& !b.speculate
&& let Some(w) = b.effects.iter().find(|e| e.writes())
{
// The call's name; where the effect came from is said with the effect itself.
let op = w.op.strip_suffix(", per the compiler").unwrap_or(&w.op);
return Some(format!("may exit before `{op}` runs"));
}
Read the two ifs slowly. independent on either statement drops the effect edge between
them. speculate on the later statement, the one that writes, drops the exit edge. Neither
touches the data-flow rules above them.
seq and fresh work differently
seq and fresh do not set a flag that removes an edge. In classify they turn the statement
into a barrier: the block is split there and nothing moves across it.
#[psync::seq]only adds order. A schedule with more order than needed is still correct, soseqcan never make a program wrong. The worst it can do is make it slower.#[psync::fresh]does not switch off a memory rule; it removes the sharing the rule is about. Theletitself stays where it is (a barrier). In addition,schedule.rsputs a copy of theletat the start of every later chain that uses the name, so each chain evaluates the initializer itself and owns its own value (search for"fresh"inschedule.rs). There is no longer one&mutshared by two chains, so the memory rules have nothing to order, and the borrow checker still checks each copy. What you promise is that evaluating it again is correct, for example that two connections from a pool behave like one.
Hints on loops
On a for or while loop, independent and speculate are read in loops.rs, not in
classify. independent skips the checks that one iteration’s awaited work does not depend on
state an earlier iteration changed. speculate allows a prefetched prefix to write even when the
body can end the loop early. The rule is the same: one flag, one check off.
What the proof assumes
A certificate gives every statement a footprint: the list of
places it may read and write. A place is a short path of names, such as n/user (the variable
user) or w/service/client (the outside resource behind client). Two statements conflict when
one writes a place the other reads or writes. Lean, a proof checker, then checks that the schedule only reorders statements whose footprints do
not conflict. The hint flags change the footprint psync writes into the certificate
(cert_nodes in schedule.rs):
if !n.independent {
for e in &n.effects {
if e.writes() {
c.writes.push(e.place());
} else {
c.reads.push(e.place());
}
}
}
if n.exits || n.panics {
c.writes.push(one("x", &[&j.to_string()]));
}
if !n.speculate && n.effects.iter().any(|e| e.writes()) {
for (i, m) in nodes[..j].iter().enumerate() {
if m.exits || m.panics {
c.reads.push(one("x", &[&i.to_string()]));
}
}
}
- Without
independent, every outside effect becomes a place in the footprint: a write tow/<domain>/<target>, or a read of it. Withindependent, the statement’s outside effects are left out of its footprint. - An exit writes a place
x/<i>, and a later write that is notspeculatereads every earlier exit’s place. That read is what makes “write after a possible exit” a conflict. Withspeculatethe read is left out.
Here is the real certificate for the hint example with both hints (generated by psync-cert; the
numbers stand for names, numbered in order of first use to keep the file short):
nodes := [
{ reads := [[0, 1], [0, 2], [3, 1], [3, 2]], writes := [[4, 5, 1], [6, 7]] },
{ reads := [[0, 1], [0, 8], [3, 1], [3, 8]], writes := [[6, 9]] }]
levels := [[[0], [1]]]
The names are 0 = n (a name), 1 = client, 2 = enabled, 8 = disabled, 3 = a
memory path, 4 5 1 = w/service/client (a write to the client), and 6 7 and 6 9 are
x/0 and x/1 (the two exits). The second statement writes only its own exit, x/1. Its write
to the client is gone (independent), and so is its read of x/0 (speculate). Nothing it
touches overlaps the first statement’s footprint, so Lean accepts them in one level.
This is exactly what What is checked, what is assumed calls
assumption 5, hints are true. The theorem check_sound says that the schedule equals the
program for any meaning of the statements under which the footprints are right. A hint makes
the footprint smaller. If the hint is true, the smaller footprint is still right, and the proof
covers your program. If it is false, the proof is still valid, but it is a proof about a
different program from the one you run.
Who checks the fact
| Hint | Rule it turns off | Footprint it shrinks | Checked by |
|---|---|---|---|
seq | none (adds a barrier) | none | nothing needed: more order is always correct |
fresh | none: it removes the sharing, by giving each chain its own copy of the binding | none | the borrow checker checks each copy; that a second value behaves like the first is your promise |
independent | effect conflict | the statement’s outside effects | nobody. cargo psync check gets INDEP and skips its conflict check for the chain |
speculate | write after a possible exit | the reads of earlier exits | nobody. cargo psync check gets SPEC and skips speculative-write |
par (synchronous code) | none: it marks a statement worth a thread | none | the compiler: data sent to a thread must be Send |
The checker is told about the two trusted hints through the const generics of the chain wrapper,
maybe_done_at::<LEVEL, ORDER, LAST, EXITS, EXIT_AT, SPEC, INDEP, _>
(Certified schedules). In psync-check/src/driver/analysis.rs you
will find if !(earlier.indep || later.indep) before the conflict report, and if !later.spec
before the speculative-write report. It is the same rule, once more, on the compiled code.
So independent and speculate are the hints to review in a pull request. Each is a promise
about a server, a file system or a business rule that no tool in psync can see.
Tutorial: a #[psync::reads] hint
We now add a hint. The finished change is on the branch tutorial/reads-hint of the repository:
four files, 46 lines. Try each step before you look.
The problem
Many search APIs take the query as the body of a POST. Elasticsearch’s _search is one example.
psync reads the name post_search, sees the verb post, and treats it as a write:
#[psync::graph]
async fn search(es: &Search, a: &str, b: &str) -> Result<(Hits, Hits), E> {
let x = es.post_search(a).await?;
let y = es.post_search(b).await?;
Ok((x, y))
}
region 0 (unchanged):
n0: x = post_search()? [await] {write `es` `a` (post_search)}
n1: y = post_search()? [await] {write `es` `b` (post_search)}
n0 -> n1 (write `es` `a` (post_search) vs write `es` `b` (post_search))
level 0: n0->n1
Two searches, one after the other, although neither changes anything. There are two existing ways out, and both are too blunt:
#[psync::graph(effects(read(post_search)))]makes everypost_searchin the function a read.#[psync::independent]turns off the conflict check altogether. If one of the statements really wrote, nothing would catch it.
What we want is narrower: this statement’s effects are reads. A read still conflicts with a write to the same service, so the rest of the protection stays in place.
Step 1: the attribute
Hints are attribute macros in psync-macros/src/lib.rs that return their input unchanged. They
exist so that #[psync::reads] resolves to something and has documentation. Add one next to
speculate:
/// Hint on a statement: every effect psync found in it only reads, whatever the call's name says
/// (a search sent as `POST`). ...
#[proc_macro_attribute]
pub fn reads(_attr: TokenStream, item: TokenStream) -> TokenStream {
item
}
Then re-export it from the psync crate, in src/lib.rs:
pub use psync_macros::{fresh, graph, independent, par, reads, seq, speculate};
Step 2: teach psync the name
/// The hint attributes psync reads and removes from its output.
pub(crate) const HINTS: &[&str] = &["seq", "fresh", "independent", "speculate", "par"];
Add "reads" to the list. The list decides which attributes schedule.rs removes from the
generated code (attrs.retain(|a| !HINTS.iter().any(..))). If you forget this step, the
attribute stays on the let in the output, and the build fails with
error[E0658]: custom attributes cannot be applied to statements: stable Rust does not run an
attribute macro on a statement. That is also why a hint outside #[psync::graph] does not
compile.
Step 3: change the node
In classify, just above the hint_flags lines shown earlier, turn every effect of a marked
statement into a read:
if attrs.iter().any(|a| is_psync_attr(a, "reads")) {
for e in &mut found.effects {
e.kind = effects::Kind::Read;
}
}
That is the whole change to the analysis. Everything downstream follows from the node’s effects:
effects::conflicts finds no write-write conflict, the exit rule finds no write to protect, and
cert_nodes writes reads, not writes, into the footprint. The certificate stays honest by itself,
because it describes the node as it now is.
Step 4: the test
In the tests of psync-graph/src/lib.rs, next to the other report(..) tests:
#[test]
fn reads_hint_lets_searches_sent_as_post_overlap() {
// `search` as above, without hints:
let plain: ItemFn = syn::parse_quote! { /* ... */ };
assert!(!report(Options::default(), plain).regions[0].changed);
let hinted: ItemFn = syn::parse_quote! {
async fn search(es: &Search, a: &str, b: &str) -> Result<(Hits, Hits), E> {
#[psync::reads]
let x = es.post_search(a).await?;
#[psync::reads]
let y = es.post_search(b).await?;
Ok((x, y))
}
};
let r = report(Options::default(), hinted);
assert!(r.regions[0].changed);
assert!(r.regions[0].nodes.iter().all(|n| n.effects.iter().all(|e| e.starts_with("read"))));
}
Always test both sides: without the hint the order is kept, and with it the order is relaxed. A test that checks only the second half also passes when psync relaxes the order without any hint.
Built from the tutorial branch, psync-expand now reports, for the hinted function:
region 0:
n0: x = post_search()? [await] {read `es` `a` (post_search)}
n1: y = post_search()? [await] {read `es` `b` (post_search)}
level 0: n0 || n1
Step 5: the checker
Now the hard question: who checks reads? Not the certificate, which takes the effects as
given. And cargo psync check is not told about the hint at all: the wrapper’s const generics
carry SPEC and INDEP, not READS. The checker computes the callee’s effects from the compiled
code. If post_search sends an HTTP request that the driver counts as a network write, the checker
reports the overlap as a conflict, with no way to know that you meant it.
There are two honest ways to finish the hint, and choosing between them is a design decision:
- Trust it, like
independent. Add aREADSconst generic, and have the driver treat the chain’s effects as reads. The hint then joins the list of facts to review by hand. - Check it. Keep the checker blind to the hint. A warning then means “psync thinks this writes”. That is safer, but noisy for exactly the APIs the hint is for.
The tutorial branch stops before this step, which is why reads is not in the main line. It is
exercise 4.
Step 6: the documentation
A hint is not finished until a user can find it:
- a row in Attributes and hints;
- a section in Hints, with when to use it and when not to;
- a line under assumption 5 in What is checked, what is assumed, if the hint is trusted.
Checklist for a new hint kind
- State the fact in one sentence, about the world, not about psync: “this call only reads”, “these two keys are different”. If you cannot, the hint is not ready.
- Find the one rule it turns off, or the one barrier it adds. A hint that touches two rules
is two hints.
independentandspeculateare separate for this reason. - Never touch the memory rules (data flow, shadowing, conflicting places). The borrow checker would reject the code anyway, and a hint must not imply otherwise.
- Make the footprint agree. Change the node, not the schedule, so the certificate follows.
- Decide who checks it. The compiler,
cargo psync check, or nobody. If nobody, list it under assumption 5. - Add it to
HINTS, re-export it, document it, and test it in both directions.
Exercises
-
(Diagram.) Draw the graph psync builds for this function: no hints; then
#[psync::independent]on the delete; then#[psync::speculate]on the delete; then both. Mark each edge with its rule.let page = store.get("index.html").await?; store.delete("draft.html").await?; -
(Footprints.) For the
set_account_dataexample, write the second statement’s footprint (reads and writes, with names, not numbers) with no hints, with onlyindependent, and with onlyspeculate. In each case, which place of the first statement does it overlap? -
(Code.) Implement
#[psync::reads]from steps 1 to 4 yourself, without looking at the branch. Then compare with the tutorial’s single commit:git show tutorial/reads-hint. -
(Code, harder.) Finish step 5 the “trust it” way. Find where
SPECandINDEPare emitted inschedule.rs(searchlet spec =) and read inpsync-check/src/driver/analysis.rs(searchindep). AddREADS, so the driver skipsconflictfor a pair when the reading side is marked and the other side does not write. -
(Design.) Why is
seqsafe to add anywhere, whileindependentis not? Answer in terms of edges. -
(New idea.) Someone proposes
#[psync::idempotent]: “doing this twice is the same as doing it once”. Is that the same promise asspeculate? What could psync do with it that it does not do today?
Answers
-
getreadsstorewith the target"index.html".deletewritesstorewith the target"draft.html".-
No hints. There is no effect conflict: the two literal targets differ, so a read of one and a write of the other commute. The only edge is the exit rule,
get(..)?may leave beforedeleteruns:n0 (get index.html)? ──may exit before `delete` runs──▶ n1 (delete draft.html) -
independenton the delete. Same picture. There was no effect edge to remove, and the exit edge stays. -
speculateon the delete. No edges:n0 || n1. The delete may now run even whengetfails, which is exactly what you promised is harmless. For a delete it rarely is. -
Both. The same as
speculatealone.
The lesson: use the report before you use a hint. Here
independentdoes nothing, because psync already knew the targets differ. -
-
With no hints, the second statement reads
n/client,n/disabled, the memory paths ofclientanddisabled, andx/0. It writesw/service/clientandx/1. It overlaps the first statement twice: both writew/service/client, and it readsx/0, which the first writes. With onlyindependent,w/service/clientis gone, and the overlap onx/0remains. With onlyspeculate, the read ofx/0is gone, and the overlap onw/service/clientremains. That is the certificate’s version of “each hint answers one question”. -
Compare against the branch. The usual mistakes are forgetting
HINTS(the build fails with E0658), and testing only the hinted case. -
In outline:
- In
schedule.rs, next tolet spec = members.iter().any(|n| n.speculate);, computereadsthe same way from a newNodefield, and add it to themaybe_done_atarguments (and to the signature ofmaybe_done_atinsrc/graph_rt.rs). - In the driver, read the new generic argument where
indepis read. - In the conflict loop, skip the pair when one chain is
readsand the other has no write. - Add a fixture to
psync-check/tests/fixtures/hidden: two markedpost-style calls with no finding, and one marked call beside a real write that is still reported.
The test of the last point is the important one. It shows that
readsis narrower thanindependent. - In
-
seqonly adds edges. Every schedule that respects a set of edges also respects any subset of them, so the schedule withseqrespects every edge the program needs. It cannot be wrong.independentremoves an edge that psync’s rules said was needed. It is right only if the fact it states is true, and no tool checks that. -
No, though they are often confused. Hints gives idempotent uploads as an example where
speculateis safe, and that is the usual reason a speculative write is harmless, but the promises differ.speculatesays “doing it once when the sequential program would have done it zero times is harmless”.idempotentsays “doing it twice equals doing it once”. psync never performs a statement twice today, soidempotentwould remove no edge, and by the checklist it is not a hint yet. It would become one with retries or hedged requests: send the same request to two replicas and take the first answer. That is a new idea in the Phase II direction, and a good one to propose in an issue, with the one rule it would turn off.
? A hint can remove which kinds of edge?
- Data flow (B reads a name A defines)
- Conflicting writes to one place in memory
+ Edges about the outside world: an effect conflict, or a write after a possible exit
- Any edge, if the programmer is sure
> Memory edges are checked by the borrow checker anyway, so no hint may remove them. Only the two outside-world rules can be turned off: `independent` for effect conflicts, `speculate` for writes after a possible exit.
? What does `#[psync::independent]` change in the certificate?
- It adds a proof obligation
+ It leaves the statement's outside effects out of its footprint
- It marks the statement as a barrier
- Nothing; certificates ignore hints
> `cert_nodes` pushes effect places only `if !n.independent`. The proof is then about the smaller footprint, which is right exactly when the hint is true.
? Why does a hint on a `let` outside `#[psync::graph]` fail to compile?
- The psync crate does not export it
+ Stable Rust does not run a custom attribute on a statement (E0658); only the graph macro, which removes it, makes it legal
- It needs a feature flag on psync
> Hints work because `#[psync::graph]` reads them and removes them (the `HINTS` list) before the compiler sees the function body.
? Which hint can never make a program wrong?
+ `seq`
- `fresh`
- `independent`
- `speculate`
> `seq` only adds order. A schedule that respects more edges still respects all the needed ones.
Adding a check
A check is a warning (or a note) that cargo psync check prints when the code
#[psync::graph] generated does something the sequential code would not. All checks live in
Checker, in psync-check/src/driver/analysis.rs. This chapter shows how a check gets its
information, and walks through a real change: treating a callee that may panic as an exit.
How a check sees the macro’s work
The driver does not re-run psync’s analysis. It reads what the macro did, from the generated code’s MIR, and compares that with what the compiled callees do.
- Markers. The macro wraps each concurrent chain in
psync::__private::maybe_done_at::<LEVEL, ORDER, LAST, EXITS, EXIT_AT, SPEC, INDEP, _>(async { .. })(in synchronous code, each job injob_at::<..>(|| ..)), and each prefetched loop prefix inover_at::<LOOP, TERMINATES, SPEC, INDEP, ..>.Checker::markersfinds these calls in a function’s MIR, reads the const generic arguments, and finds the body of theasyncblock from the last type argument (coroutine_of). The result is a list of joins, each a list ofChain { body, order, exits, spec, indep, span }sorted by program order, and a list ofPrefix { body, terminates, spec }. - Summaries.
self.analyzer.summarize(chain.body)gives everything a chain may do: effects with their spans and call chains,panics,opaquecallees. - Comparison.
check_levellooks at every pair of chains in a join, earlier and later in program order.check_prefixlooks at a loop’s prefix, andcheck_interiorat sharedCell/RefCell/Mutex/atomic values. - Reporting.
self.report(severity, kind, function, span, message, note)emits a rustc diagnostic atspan(so it appears in the editor like any warning) and records aFinding.write_findingssaves those findings totarget/psync/findings/, wherecargo-psync.rsprints the summary line, andfixreads each warning’s suggested#[psync::seq].
The macro’s tags are the contract between the two halves. If you add a new hint or a new kind of rewrite, give its marker the facts a check will need, as const generics, which cost nothing at run time and survive into MIR.
Worked example: panics are exits
The gap. The speculative-write check fired when an earlier chain was tagged EXITS (it
contains a ?, return, break or continue) and a later chain writes. But a chain can also
stop the function by panicking inside a callee:
async fn parse_config() -> usize {
std::fs::read_to_string("app.toml").unwrap().len() // panics if the file is missing
}
async fn stamp_run() -> std::io::Result<()> {
std::fs::write("run.stamp", b"1")
}
#[graph]
pub async fn boot() -> Result<usize, Error> {
let n = parse_config().await; // no `?`: the macro sees no exit
stamp_run().await?; // runs alongside it
Ok(n)
}
Sequentially, a missing app.toml panics before the stamp is written. With psync, the stamp may
already be on disk when the panic happens. The macro cannot know, because unwrap is in another
function. The driver does know: parse_config’s summary has panics: true. With
cargo psync build, the macro gets that fact and orders the two. But plain cargo psync check
said nothing.
The test. Add boot and its helpers to the fixture, and assert the finding in
tests/fixture.rs:
// A callee that may panic is an exit: the write after it is speculative.
assert!(
app.findings.iter().any(|f| f.kind == "speculative-write"
&& f.function == "boot"
&& f.message.contains("may panic")),
"{:#?}", app.findings
);
Also raise the total number of findings, add boot to the functions that facts make sequential,
and raise the number of hints cargo psync fix inserts. The fixture test pins all of these, so a
change in behaviour you did not intend shows up as a failure.
The change. In check_level, the condition becomes “the earlier chain exits or panics”,
with a message that says which:
let panics = !earlier.exits && summaries[i].panics;
if (earlier.exits || panics)
&& !later.spec
&& let Some(w) = summaries[j].effects.iter()
.find(|l| l.effect.writes() && l.effect.domain != Domain::Output)
{
let how = if panics { "may panic" } else { "exits early" };
self.report(Severity::Warning, "speculative-write", function, w.span,
format!("psync starts this before knowing whether an earlier statement {how}, ..."),
Some((user_span(..), "the earlier work that may exit".to_string())));
}
Reusing the kind speculative-write means cargo psync fix, --deny and the report need no
change. A new kind of problem would get a new kind string, and cargo-psync.rs would print it
like the others.
On real code. Run cargo psync check on a large project before and after. A check that
fires everywhere is worse than none. This one counts only explicit panics in your own code (the
driver does not count panics inside libraries, nor bounds or overflow checks), so it fires
rarely, and only where the fix is warranted.
Checklist for a new check
- Can the problem be seen from the markers and the summaries? If the check needs a fact the
macro did not record, add it to the marker first, in
schedule.rsorloops.rsand ingraph_rt.rs. - Is it a warning (behaviour differs from sequential code) or a note (worth knowing, often fine,
shown with
--notes)? - Does the message say what psync did, what the callee does (
describe()andpath()of the effect), and which hint fixes it? - Does
fixknow where to put the hint?seq_fixplaces it before the statement, or before the loop for a loop finding. - Fixture test, real-code run, and the book: Checking rewrites lists every kind of finding.
Adding a test
psync has a test suite for each kind of claim it makes. Pick the suite by the question your test answers:
| Question | Suite | Run |
|---|---|---|
| Does the analysis draw this edge, place this barrier, refuse this loop? | unit tests in psync-graph/src/*.rs | cargo test -p psync-graph |
| Does the rewritten function return the same thing, and overlap what it should? | tests/graph.rs | cargo test --no-default-features --test graph |
| Do the executors schedule as documented? | tests/scheduling.rs, tests/multi.rs | cargo test --no-default-features; --features std --test multi |
| Does the driver find this effect, report this finding, compute these facts? | the fixture, psync-check/tests/fixture.rs | cd psync-check && cargo test |
| Does a synchronous function keep its results, errors and panics on threads? | tests/sync.rs | cargo test --no-default-features --features std --test sync |
| Is this real-world shape faster, and still correct? | examples/graph_suite/ | cargo run --example graph_suite --no-default-features -- --brief |
| How much do synchronous shapes gain, over real sockets? | examples/phase2.rs | cargo run --release --example phase2 --no-default-features --features std |
| Is the scheduling argument right? | verify/Schedule.lean | lean verify/Schedule.lean |
| Is it right against a server, relative to a spec? | verify/World.lean | lean verify/World.lean |
| Is this schedule safe? | certificates, verify/Cert.lean | scripts/certify.sh (regenerate verify/Certs.lean, then lake build) |
| Do the book’s examples still run? | psync-graph/examples/, verify/Tutorial.lean | cargo test -p psync-graph; lean verify/Tutorial.lean |
Analysis decisions: psync-graph unit tests
These tests run the analysis on a function built with syn::parse_quote! and assert on the
report. They do not compile or run the generated code, so they are fast and precise about why:
#[test]
fn files_and_services_order_conflicting_awaits() {
let r = report(
Options::default(),
syn::parse_quote! {
async fn f(api: &Api) -> Result<(), E> {
tokio::fs::write("cfg.toml", b"x").await?;
let s = tokio::fs::read_to_string("cfg.toml").await?;
let o = tokio::fs::read_to_string("other.toml").await?;
api.delete(name).await?;
Ok(())
}
},
);
// ... assert on edges(&r): the write and the read of cfg.toml are ordered,
// other.toml is free
}
report and edges are helpers in the tests module of lib.rs. The report has everything
explain prints: regions with nodes, edges and their reasons, levels, barriers with reasons, and
loops with refusals.
Behaviour: tests/graph.rs
These tests compile real annotated functions and run them on psync’s Executor. Time is counted
in executor polls, so the tests are deterministic. The helper io(ticks, value) is a future that
stays pending for ticks polls and records how many are in flight. run(future) returns the
output, the polls taken and the peak in flight. A typical test writes the function twice, plainly
and with #[graph], and asserts three things:
#[test]
fn tree_overlaps_independent_waits() {
let (seq, seq_polls, seq_peak) = run(sequential_tree());
let (par, par_polls, par_peak) = run(graph_tree());
assert_eq!(seq, par); // 1. same result
assert_eq!((seq_peak, par_peak), (1, 4)); // 2. the concurrency it should have
assert_eq!(seq_polls, 7 * T as usize + 1); // 3. the time it should take
assert_eq!(par_polls, 3 * T as usize + 1);
}
For exits, test that the same error comes back when several statements fail. For effects and barriers, test the order of side effects, for example by pushing to a shared log and comparing logs. A test that only checks the result would pass for a rewrite that does nothing.
The driver: the fixture
psync-check/tests/fixtures/hidden is a small workspace (app and helpers) whose functions
hide effects where the macro cannot see them. tests/fixture.rs runs cargo psync check,
check --facts and fix on it, and asserts on the findings files:
- each finding, by kind, function and message;
- the total, so a new false positive fails the test;
- with facts, which functions become sequential and which gain concurrency;
- fix, how many hints it inserts, and that the result checks clean.
When you add a case, every one of those numbers may change, and each change should be one you can explain. Adding an effect rule and Adding a check show complete examples. The test compiles the fixture from scratch, so expect about a minute.
Real-world shapes: graph_suite
Each shape is a function reconstructed from an open-source project, with its I/O replaced by
timers of realistic latency. The example! macro in show.rs compiles the function twice, as
#[psync::graph(off)] and #[psync::graph(options)], and the suite checks that both give the
same result before it reports the speedup:
example! {
origin: "kube-rs/kube kube-client/src/discovery/mod.rs Discovery::run (infra-08)",
pattern: "P3 per-item chains",
summary: "list the API groups, then query each queryable group one after another",
options: (bound = 16),
call: |f| f(Discovery { /* .. */ }),
async fn run(mut discovery: Discovery) -> Result<usize, String> { /* the original code */ }
}
Add the module’s example() to its file’s examples() list. Keep the code as close to the
original as the stubs allow, and cite the file and function in origin. The suite’s geometric
mean (about 3.8×) is quoted in the book, so update Sixteen real-world shapes
when it changes.
Proofs
A new theorem goes in verify/Schedule.lean, with a docstring that says in words what it means
for psync. It must contain no sorry. Lean prints a warning for each one, and CI runs
lean verify/Schedule.lean. The proofs use only Lean’s core library, so the file checks in
about a second with no downloads. Update the theorem table in verify/README.md and in
Proofs.
The book’s examples
A Rust example in the book that is directly followed by a text block holding a report (one
that starts with region) is checked in CI. scripts/check-book-examples.py runs psync-expand
on the example and compares its explanation with the block, line for line. When a change to the
macro changes a report, run the script, and paste what it prints into the chapter. If the report
belongs to a function the book does not show, show the function. A reader must be able to
reproduce every report.
Attributes and hints
#[psync::graph(...)]
Goes on an async fn, including methods and async fn main (put it above #[tokio::main], #[tracing::instrument] and other attributes; inside an #[async_trait] impl, on the method: Other attribute macros). It
also rewrites async blocks and async closures inside the function it is on. On an ordinary fn
it runs statements marked #[psync::par] on threads (Synchronous code,
with the std feature). 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 |
profile | off | compile the function as written, and report each statement that awaits, with its line and time, to the clock and sink given to psync::profile::install (Getting a trace) |
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 |
calls = read / write / write_independent / independent | none | a mark for the whole function: unclassified calls read (even with strict) or write; the independent forms also make every statement #[psync::independent] (Marking a whole function) |
speculate | off | writes may run before earlier exits everywhere in the function |
path_text | off | compare files by path text, as before 2026-11-26, instead of by identity (device and inode, resolved symlinks); literal paths that differ are then never gated (Owned files). owned_files names the default explicitly |
yield_every = N | off | insert psync::yield_now().await at the start of every loop body in async code, every N iterations (Yield injection) |
effects(read(a, ..), write(b, ..), ordered(c, ..)) | none | extra verbs (whole names or first _-separated words) for the effect analysis |
baseline = resync | none | for comparisons only: schedule by ReSynchronizer’s rules (within one block, one effect per environment, no gates, no hints); see Measured: the same functions under ReSynchronizer’s rules |
Options are comma-separated: #[psync::graph(bound = 4, explain)]. Anything else is a compile
error: expected `bound = N`, `explain`, `off`, `strict`, `speculate`, `effects(..)`, `calls = ..`, `yield_every = N`, `profile`, `owned_files`, `path_text` 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; on a for loop, the loop is not prefetched |
#[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::par] | a statement of a synchronous (fn) function | worth a thread: it may run on another thread beside independent statements; does nothing in async code |
#[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
Every list of names psync reads (verbs, pure and ordered methods, guards, delays, clock calls, blocking calls, SQL words, logging and pure macros) is on Names psync knows, included from the source.
Names psync knows
psync reads tokens, not types, so much of what it decides comes from names: a method called
delete_pod writes, a call to sleep is a barrier, len does not change its receiver. This page
shows every such list, included straight from the source when the book is built, so it is always
the list psync uses. Each list is a Rust constant; the comment above it says what it is for.
You can extend the verb lists for your own API with
#[psync::graph(effects(read(..), write(..), ordered(..)))] (Attributes), mark a
whole function with calls = .., or mark one statement with a hint. To change a list for
everyone, see Adding an effect rule: every list change needs a
test.
How a name is matched
For the verbs (the first three lists), psync takes the called method’s name, and its first
word: the name with a leading try_ or async_ removed, cut at the first _. The name matches
a list when either the whole name or its first word is in it. delete_namespaced_pod has the first
word delete, a write verb; try_send has send, an ordered verb; list_objects_v2 has
list, a read verb. The lists are tried in this order, and the first match wins:
- your
ordered(..), then yourwrite(..), then yourread(..); - the Redis commands (ordered, then writes, then reads);
- the ordered verbs, then the write verbs, then the read verbs.
An HTTP method (Method::GET) and an SQL statement or Redis command given as a literal decide
before any of these.
A name in none of them is unclassified: the call is taken as a read, or as a write with
strict or calls = write, and the explanation lists it. In a method chain, the first verb decides
(client.get(url).header(..).send() reads).
The other lists match a method or macro name exactly, except the read prefixes, which match the start of a method name.
Service verbs (effects.rs)
Used for any awaited call that is not a file, network, environment, process or SQL operation.
/// First words of names that read.
const READ_VERBS: &[&str] = &[
"get",
"head",
"list",
"fetch",
"read",
"load",
"query",
"select",
"find",
"lookup",
"describe",
"stat",
"exists",
"search",
"resolve",
"download",
"retrieve",
"watch",
"scan",
"count",
"check",
"peek",
"options",
"metadata",
"open",
"inspect",
"show",
"info",
"status",
"health",
"ping",
"poll",
"receive",
"batch_get",
"is",
"has",
"try_exists",
"canonicalize",
"verify",
"validate",
"connect",
"probe",
"discover",
];
/// First words of names that write.
const WRITE_VERBS: &[&str] = &[
"create",
"insert",
"put",
"post",
"patch",
"delete",
"del",
"remove",
"rm",
"update",
"replace",
"upsert",
"set",
"write",
"rename",
"copy",
"upload",
"execute",
"exec",
"commit",
"rollback",
"spawn",
"kill",
"apply",
"merge",
"truncate",
"drop",
"evict",
"invalidate",
"purge",
"register",
"unregister",
"grant",
"revoke",
"restart",
"scale",
"cancel",
"transfer",
"incr",
"increment",
"decr",
"decrement",
"save",
"store",
"persist",
"flush",
"sync",
"mark",
"reset",
"clear",
"add",
"modify",
"edit",
"approve",
"reject",
"submit",
"deploy",
"install",
"uninstall",
"mkdir",
"rmdir",
"unlink",
"chmod",
"chown",
"touch",
"link",
"symlink",
"compact",
"migrate",
"seed",
"move",
"mv",
"claim",
"release",
"renew",
"expire",
"lease",
"start",
"stop",
"terminate",
"shutdown",
"close",
"run",
"invoke",
"call",
"trigger",
"charge",
"refund",
"pay",
"mint",
"burn",
"sign",
"issue",
"reserve",
"allocate",
"free",
"destroy",
"provision",
"attach",
"detach",
"mount",
"unmount",
"bind",
"unbind",
];
/// First words of names whose relative order is observable on one domain.
const ORDERED_VERBS: &[&str] = &[
"send",
"append",
"push",
"publish",
"enqueue",
"emit",
"notify",
"ack",
"nack",
"pop",
"dequeue",
"broadcast",
"log",
"produce",
"write_all",
"feed",
];
Redis (effects.rs)
The redis crate’s methods are named after the commands, and most command names are not verbs.
These lists are tried before the verbs, by the whole name or its first word, so get_del (which
deletes) is a write. A redis::cmd("..") with a literal command is looked up here and then in the
verbs; one psync cannot read is a write. See Side effects.
/// Redis commands, as the `redis` crate names its methods (`con.hget(k, f)`, `con.get_del(k)`)
/// and as `redis::cmd("HGET")` names them. Matched by the whole name or its first word, before
/// the verbs: `get_del` deletes, though its first word reads.
const REDIS_READS: &[&str] = &[
"hget",
"hgetall",
"hmget",
"hkeys",
"hvals",
"hlen",
"hexists",
"hstrlen",
"mget",
"lrange",
"llen",
"lindex",
"lpos",
"smembers",
"sismember",
"smismember",
"scard",
"srandmember",
"sdiff",
"sinter",
"sunion",
"zrange",
"zrevrange",
"zrangebyscore",
"zrevrangebyscore",
"zscore",
"zmscore",
"zcard",
"zrank",
"zrevrank",
"zcount",
"zlexcount",
"ttl",
"pttl",
"strlen",
"getrange",
"keys",
"xrange",
"xrevrange",
"xlen",
"xread",
"pfcount",
"bitcount",
"getbit",
"geopos",
"geodist",
"georadius",
"dbsize",
"randomkey",
];
const REDIS_WRITES: &[&str] = &[
"hset",
"hsetnx",
"hmset",
"hdel",
"hincr",
"hincrby",
"mset",
"msetnx",
"setex",
"setnx",
"psetex",
"getset",
"getdel",
"get_del",
"getex",
"get_ex",
"setrange",
"setbit",
"sadd",
"srem",
"spop",
"smove",
"sdiffstore",
"sinterstore",
"sunionstore",
"zadd",
"zrem",
"zincr",
"zincrby",
"zpopmin",
"zpopmax",
"zremrangebyscore",
"zremrangebyrank",
"lset",
"ltrim",
"linsert",
"lrem",
"pexpire",
"expireat",
"pexpireat",
"pfadd",
"pfmerge",
"geoadd",
"xtrim",
"xdel",
"xgroup",
"flushdb",
"flushall",
"renamenx",
];
/// Commands whose order on one key is visible: list pushes and pops, stream appends.
const REDIS_ORDERED: &[&str] = &[
"lpush",
"rpush",
"lpushx",
"rpushx",
"lpop",
"rpop",
"blpop",
"brpop",
"rpoplpush",
"brpoplpush",
"lmove",
"blmove",
"xadd",
"xack",
"xreadgroup",
];
Files and the network (effects.rs)
A call through fs, File, OpenOptions or DirBuilder reads if its last path segment is in
FS_READS (and it is not built with OpenOptions), and writes otherwise. A method of a
Path with no arguments reads the file system when it is in PATH_FS_READS. A call through
TcpStream, UdpSocket, TcpListener, UnixStream or net writes if its last segment is in
NET_WRITES, and reads otherwise.
/// File-system functions (last path segment) that only read.
const FS_READS: &[&str] = &[
"read",
"read_to_string",
"read_dir",
"metadata",
"symlink_metadata",
"canonicalize",
"read_link",
"try_exists",
"exists",
"open",
];
/// Methods of `std::path::Path` without arguments that read the file system at the path.
const PATH_FS_READS: &[&str] = &[
"exists",
"try_exists",
"is_file",
"is_dir",
"is_symlink",
"metadata",
"symlink_metadata",
"read_dir",
"read_link",
"canonicalize",
];
/// Network functions that write (send data); the rest of `net` only connects or reads.
const NET_WRITES: &[&str] = &["send_to", "send", "write", "write_all"];
SQL statements (effects.rs)
For a call that runs SQL from a string literal, the statement’s first word decides (a WITH is
read through to the statement it introduces). Any word of SQL_WRITE_WORDS in a reading statement
makes it a write. A first word in neither list, or a statement psync cannot read, is a write.
/// Statements that only read, by their first word. `EXPLAIN` without `ANALYZE` only plans.
const SQL_READS: &[&str] = &[
"SELECT", "SHOW", "EXPLAIN", "DESCRIBE", "DESC", "VALUES", "TABLE", "PRAGMA",
];
/// Statements that change the database or the session, by their first word.
const SQL_WRITES: &[&str] = &[
"INSERT",
"UPDATE",
"DELETE",
"MERGE",
"UPSERT",
"REPLACE",
"CREATE",
"DROP",
"ALTER",
"TRUNCATE",
"GRANT",
"REVOKE",
"COPY",
"CALL",
"EXEC",
"EXECUTE",
"DO",
"LOCK",
"BEGIN",
"START",
"COMMIT",
"ROLLBACK",
"SAVEPOINT",
"RELEASE",
"SET",
"RESET",
"VACUUM",
"ANALYZE",
"REINDEX",
"CLUSTER",
"REFRESH",
"COMMENT",
"DISCARD",
"LISTEN",
"NOTIFY",
"UNLISTEN",
"PREPARE",
"DEALLOCATE",
"ATTACH",
"DETACH",
"LOAD",
"IMPORT",
];
/// Words that make a reading statement write or lock: `SELECT .. FOR UPDATE`, `SELECT .. INTO`,
/// `nextval(..)`, a data-modifying `WITH`, `EXPLAIN ANALYZE` (which runs the statement).
const SQL_WRITE_WORDS: &[&str] = &[
"INSERT",
"UPDATE",
"DELETE",
"MERGE",
"INTO",
"NEXTVAL",
"SETVAL",
"LOCK",
"ANALYZE",
"PG_ADVISORY_LOCK",
"PG_ADVISORY_XACT_LOCK",
"GET_LOCK",
];
Reads and writes of variables (access.rs)
A method call on a variable that is mut (or a handle such as &mut) writes the variable,
unless the method is in PURE_METHODS or starts with one of READ_PREFIXES. A method in
ORDERED_METHODS writes its receiver whatever the receiver is, even through &self: a channel
or a socket changes when you use it. See Reads and writes from tokens.
/// Methods assumed not to mutate their receiver.
pub(crate) const PURE_METHODS: &[&str] = &[
"clone",
"to_string",
"to_owned",
"into",
"as_ref",
"as_str",
"as_slice",
"len",
"is_empty",
"unwrap_or",
"unwrap_or_default",
"as_deref",
"iter",
"to_vec",
"copied",
"cloned",
"is_some",
"is_none",
];
/// Prefixes of further read-only method names (`is_*`, `get*`, `as_*`, ...).
const READ_PREFIXES: &[&str] = &[
"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",
];
/// Calls whose relative order is observable even through `&self`: channel, stream and I/O
/// operations on one receiver must stay in program order.
const ORDERED_METHODS: &[&str] = &[
"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",
];
Barriers and blocking calls (classify.rs)
A statement that awaits one of GUARD_AWAITS and keeps the guard, awaits one of DELAY_AWAITS,
or calls one of CLOCK_CALLS (outside closures and async blocks) is a barrier: it keeps its
place. In a synchronous function, so is a let whose value calls one of GUARD_METHODS with no
arguments (let g = m.lock().unwrap();): the guard is held afterwards. The early-exit
macros bail!, ensure!, try!, return_err! and fail! are exits. See
Classifying statements.
A statement using one of AWAITING_MACROS is a barrier too, and its effects are unknown writes:
the macro awaits calls psync cannot see (Cancellation, timeouts and
select!).
/// Macros that await the futures they are given, with no `.await` in their tokens
/// (`tokio::select!`, `futures::join!`). psync cannot see the calls inside them, so a statement
/// using one is a barrier, and its effects are unknown writes.
pub(crate) const AWAITING_MACROS: &[&str] = &["select", "select_biased", "join", "try_join"];
/// Awaited operations that acquire something held afterwards (a lock, permit or transaction).
/// A statement that keeps the guard is a barrier; one that drops it inside a nested block (its own
/// critical section) may still move, since the lock itself keeps mutual exclusion.
const GUARD_AWAITS: &[&str] = &[
"lock",
"lock_owned",
"read",
"write",
"acquire",
"acquire_owned",
"acquire_many",
"begin",
"transaction",
];
/// Deliberate delays: their position is the point. Statements awaiting these are barriers.
const DELAY_AWAITS: &[&str] = &["sleep", "sleep_until", "tick", "yield_now", "delay_for"];
/// Clock reads (`Instant::now()`, `started.elapsed()`): when they run relative to the waits
/// around them is what they measure, so statements making them are barriers.
const CLOCK_CALLS: &[&str] = &["now", "elapsed", "duration_since"];
/// Methods whose result, bound by a `let`, is a guard held afterwards (synchronous locks and
/// `RefCell` borrows; `read` and `write` only without arguments, as on `RwLock`).
const GUARD_METHODS: &[&str] = &["lock", "try_lock", "borrow", "borrow_mut", "read", "write"];
In synchronous code (Phase II) a statement blocks, and so plays the part of
an await, when it names one of NET_PATHS (or reqwest::blocking) and calls one of
NET_WAITS, or builds a Command and calls one of PROCESS_WAITS.
/// Synchronous calls that wait on the network or a process (Phase II): in a synchronous function,
/// a statement making one plays the part of an await. A statement blocks when it names one of
/// these paths *and* calls one of the methods that wait: `Command::new("git")` builds a command,
/// `.output()` runs it, and `Command::Reply` or clap's `Command::parse_from` are no process at all.
/// `reqwest` counts only through `reqwest::blocking`.
const NET_PATHS: &[&str] = &["ureq", "TcpStream", "UdpSocket"];
const NET_WAITS: &[&str] = &[
"connect",
"call",
"send",
"send_to",
"recv",
"recv_from",
"read_to_end",
"read_to_string",
"read_exact",
];
const PROCESS_WAITS: &[&str] = &["output", "status", "wait", "wait_with_output"];
Pure code (classify.rs, loops.rs)
Logging macros are treated as pure, so a debug! between two awaits does not split them. The pure
macros build values. TOTAL_METHODS are the methods an expression may call and still be
evaluated ahead of a loop for every item (to compute a file path for a run-time check).
/// Logging statements: treated as pure so they do not split regions.
const LOG_MACROS: &[&str] = &["trace", "debug", "info", "warn", "error", "log"];
/// Macros that build values without side effects.
const PURE_MACROS: &[&str] = &["format", "vec", "concat", "stringify"];
/// Methods whose call on a total receiver neither panics nor touches anything: what a file
/// path is usually built with.
const TOTAL_METHODS: &[&str] = &[
"clone",
"to_string",
"to_owned",
"as_ref",
"as_str",
"as_path",
"as_os_str",
"to_path_buf",
"join",
"with_extension",
"with_file_name",
"path",
];
Hints (classify.rs)
The attribute names psync reads on statements, as #[psync::NAME] (only graph may also be written bare, when imported)
(Hints):
/// The hint attributes psync reads and removes from its output.
pub(crate) const HINTS: &[&str] = &["seq", "fresh", "independent", "speculate", "par"];
Exercises
- Is
client.try_publish_batch(msgs).awaita read, a write or an ordered write? Andstore.fetch_or_create(key).await? let n = queue.len();andqueue.drain(..);both use amut queue. Which writesqueue?- In a synchronous function, which of these is a barrier:
let t = Instant::now();,let g = m.lock().unwrap();,let s = name.to_string();?
Answers
try_publish_batchlosestry_, and its first word ispublish: an ordered write.fetch_or_createhas the first wordfetch, a read verb, so psync takes it as a read. The name misleads: it may create. Your own lists are tried first and match whole names, so#[psync::graph(effects(write(fetch_or_create)))]makes it a write.lenis inPURE_METHODS, so it reads.drainis in no list and does not start with a read prefix, so on amutvariable it writes.- The first (a clock call) and the second (a lock guard bound with
let).to_stringis pure.
API reference (Rustdoc)
The Rustdoc of every crate is published next to this book, generated from the source on each deploy. It includes the internals: private modules and functions are documented too, because contributors read them.
| Crate | What it holds |
|---|---|
| psync | #[psync::graph] and the hints, the executors (Executor, MultiExecutor), yield_now, and runtime support for generated code |
| psync-macros | the attribute entry points |
| psync-graph | the analysis and code generation: classification, access paths, effects, facts, hoisting, scheduling, loops, exits |
| psync-check | the effect model, summary files, the link step, facts for the macro |
| psync-driver | the rustc driver: MIR summaries and the checks |
| cargo-psync | cargo psync check, build, fix, summaries |
| Lean proofs (doc-gen4) | every theorem of verify/, each with its statement in mathematical notation: Schedule, World, Cert, Footprint, Certs, Tutorial |
The index page links them all. To build the site yourself:
scripts/build-site.sh. It builds the book, runs cargo doc --document-private-items for the
workspace and for psync-check (with its pinned nightly), and runs doc-gen4 on the Lean proofs
(verify/docbuild, which keeps verify/ itself free of dependencies).
In the proofs, every theorem’s documentation begins with its statement in LaTeX, so the HTML shows the mathematics first and the Lean code second. New theorems follow the same convention.
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.
cargo psync
cargo psync check [--deny] [--notes] [--facts] [CARGO CHECK ARGS...]
cargo psync build [--deny] [--notes] [CARGO BUILD ARGS...]
cargo psync fix [CARGO CHECK ARGS...]
cargo psync summaries [CRATE] [--all]
cargo psync pdg [FUNCTION] [--entries] [--from HANDLER]
pdg prints the dependence graphs the last check built; --entries lists the entry points
(main, axum and actix-web handlers with their routes) and --from HANDLER the graphs of what
one request runs (Entry points).
Checks #[psync::graph] rewrites against the compiled bodies of callees. Built from psync-check/
with a pinned nightly (cd psync-check && cargo install --path .). See
Checking rewrites.
| Variable | Set by cargo psync | Meaning |
|---|---|---|
PSYNC_SUMMARY_DIR | target/psync/summaries | where the driver writes and reads per-crate effect summaries |
PSYNC_FINDINGS_DIR | target/psync/findings | where the driver writes per-crate findings (JSON) |
PSYNC_CHECK_DENY | --deny | 1: findings are errors |
PSYNC_CHECK_NOTES | --notes | 1: also report output order and interior mutability |
PSYNC_LINKED | target/psync/linked.json | the driver reads the link step’s resolution of dyn calls |
PSYNC_LINKED_STAMP | hash of linked.json | tracked by the driver, so workspace crates are re-checked when it changes |
PSYNC_FACTS | target/psync/facts.tsv (build, check --facts) | the macro schedules with these facts (Scheduling with compiler facts) |
PSYNC_FACTS_STAMP | hash of facts.tsv | read through option_env! in generated code, so cargo rebuilds when facts change |
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, and the report’s fields below.
psync-scan
cargo build --release -p psync-graph --features cli --bin psync-scan
target/release/psync-scan [--sync | --async] FILE...
Applies #[psync::graph] with default options to every function of every file, as if each were
annotated, without changing the files. It prints one tab-separated line per region where two
waiting statements (awaits, or blocking calls) share a level in different chains:
| Column | Meaning |
|---|---|
| 1 | file |
| 2 | the function’s first line |
| 3 | the function’s name |
| 4 | blocking (synchronous code, Phase II) or async |
| 5 | the region’s number of statements |
| 6 | the number of levels in which two or more chains wait |
| 7 | the first four waiting statements, separated by | |
A summary line (files, functions, functions with a concurrent region, regions) goes to stderr.
--sync scans only synchronous functions, --async only async ones; const fns are skipped.
A panic in the analysis prints PANIC in column 4 and the scan continues: report it, it is a
psync bug. The scan measures what psync finds without hints, so helpers that hide a request
are not seen. See The audit.
psync-cert
cargo run -q -p psync-graph --features cli --bin psync-cert -- FILE... > verify/Certs.lean
Writes a Lean module with a certificate for every concurrent region of every #[psync::graph]
function in the files (and every example! of graph_suite), each with a theorem
check cert = true proved by decide. scripts/certify.sh regenerates the repository’s own
certificates and checks them with Lean; CI fails if verify/Certs.lean is out of date. See
Certified schedules.
psync-predict
cargo run -p psync-graph --features cli --bin psync-predict -- FILE LINE TRACE [BOUND]
Predicts the time of one measured run under psync’s schedule. TRACE has one LINE COST pair per
line, for each call of the function as written. Prints the measured and predicted time, and the
chain that sets each level. A trace of several runs separated by --- lines is grouped by path
(the lines each run ran): each path gets its share of the runs, its mean measured and predicted
time, and the critical path of its slowest run. See Predicting the
speedup.
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. A third, profiled run of each predicts the rewrite’s time (Predicting the speedup). See Sixteen real-world shapes.
Scripts
| Script | What it does |
|---|---|
scripts/certify.sh | regenerate verify/Certs.lean with psync-cert, then lake build it |
scripts/check-book-examples.py | run psync-expand on every book example that is followed by a report, and fail with a diff if psync now prints something else |
scripts/spec-check/check_logs.py | check Kubernetes audit logs (--kube) or S3 server logs (--s3) against the commutativity specifications (What psync guarantees) |
scripts/spec-check/selftest.sh | the log checker on logs with planted violations |
scripts/charon/ | Rust → Charon → the MIR fragment of verify/Footprint.lean (its README.md) |
scripts/audit/ | the Phase II audit’s harnesses for rustic and tauri (The audit) |
scripts/build-site.sh | this book, every crate’s Rustdoc under /api/ and the Lean docs under /api/lean/ |
scripts/test-rp2350.sh | host tests and the RP2350 firmware build (--flash to flash a board) |
The JSON report
psync-expand prints one object. Its report is the Report struct of psync-graph
(psync-graph/src/lib.rs), serialized field by field; indices are 0-based, lines 1-based, and a
line is 0 when the tokens carry no location (only the cli feature turns locations on).
| Field | Type | Meaning |
|---|---|---|
function, start_line, end_line | string, number | the function chosen and its lines |
bound | number | the loop prefetch bound used |
changed | bool | some region runs two chains together, or some loop is prefetched |
explain | string | the text #[psync::graph(explain)] prints |
expanded | string | the generated function, pretty-printed |
report.regions[] | object | one per analyzed region (two or more waits), below |
report.loops[] | object | one per for loop considered for prefetching, below |
report.barriers[] | string | waiting statements kept in place, each with the reason |
report.unclassified_writes | bool | unclassified calls were taken as writes (strict, or calls = write..) |
A region:
| Field | Type | Meaning |
|---|---|---|
nodes[] | object | its statements, in program order, below |
edges[] | [from, to, reason] | to waits for from; reason is the text of the explain line (for example, reads user) |
chains[] | array of node indices | statements fused into one chain, in program order |
levels[] | array of chain indices | the chains that run together, level by level |
changed | bool | some level has two or more chains |
unclassified[] | [line, call] | awaited calls whose effect psync could not tell from the name |
cert[] | {reads, writes} | per node, the places it may read and write, each a list of path segments: the certificate psync-cert turns into Lean |
runtime_checks | number | chain pairs that run together because their computed file paths differ, and are ordered at run time if they turn out to overlap |
A node:
| Field | Type | Meaning |
|---|---|---|
label | string | the statement’s source, shortened |
line, end_line | number | its first and last line |
awaits | bool | it contains an .await |
blocks | bool | synchronous code that blocks (Phase II), run on another thread |
effect | bool | an ordinary statement with an effect: effects keep their order with each other |
effects[] | string | its effects on files, the network, services, processes and the environment, as explain describes them |
exits | bool | it may leave the function (?, return, break, a panic with facts) |
speculate | bool | its writes may run ahead of earlier exits (#[psync::speculate]) |
A loop:
| Field | Type | Meaning |
|---|---|---|
label | string | the loop header |
line, end_line | number | its first and last line |
prefetched[], prefetched_lines[] | strings, [first, last] | the statements run ahead for each item, and their lines |
bound | number | how many items may be in flight |
changed | bool | it was prefetched |
reason | string | why it was left alone (empty when prefetched) |
check | string | for items that name their own files: checked at run time, or why they could not be and distinct items are assumed |
cargo psync check writes one more JSON file per crate, target/psync/findings/<crate>.json
(CrateFindings in psync-check/src/lib.rs): crate_name; checked_levels and
checked_loops, the counts it checked; functions, a map from each rewritten function to
[concurrent levels, prefetched loops]; and findings[], each with severity (Warning or
Note), kind (conflict, speculative-write, loop-speculative-write,
interior-mutability, output-order or cancellation), message, location
(file:line:column), function, and fix, either null or the #[psync::seq] insertion
cargo psync fix applies ({file, offset, insert}). The summaries’ format is in
From MIR to summaries.
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, psync-scan, psync-cert and psync-predict binaries, 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.
AST. Abstract syntax tree: the program as a tree that follows Rust’s grammar. Macros see it through syn. See Syntax trees.
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, a select! or
join!, and the block’s value.
Basic block. A run of MIR statements with one entry and one exit, ended by a terminator (goto, switchInt, Call, return, …). See Inside rustc.
Bound. The maximum number of a loop’s prefixes in flight at once (bound = N, default 16).
Nested loops multiply their bounds.
Cancellation. Dropping a future before it finishes (a timeout, the losing branch of a select!).
It stops every chain in flight at once. See Cancellation.
Certificate. What psync claims about one region: each statement’s places and the levels of chains it chose. A Lean checker, proven sound, accepts or rejects it. See Certified schedules.
Chain. Nodes fused into one sequential future, where keeping them apart would let nothing start sooner (usually: each waits only for the one before it, and nothing else waits for that one). A chain starts its next node as soon as its previous one finishes, whatever the other chains are doing. The exact rule is in Chain fusion.
Class-hierarchy analysis (CHA). Resolving a call through dyn or a generic to every implementation of the trait method in the program. psync does it at link time, over the whole build. See Dynamic dispatch.
Closed world. The assumption that the analysed build contains every implementation that can run. Facts hold for the build they were computed in.
Commutativity specification. Which requests to a server commute: in either order, the server ends in the same state and each gets the same response. psync’s schedules are proven correct relative to one; psync’s built-in rule is one. See the outside world.
Conflict. Two effects that must keep their order: one writes, they are in the same domain, and their targets may be the same.
Coroutine. The state machine an async fn or block compiles to. Each .await is a point where it can suspend.
DefId, DefPathHash. rustc’s name for a definition within one compilation, and a stable hash of its path that is the same in every compilation. Summary files use the hash.
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.
Fact. What the compiler knows about a call psync’s tokens cannot classify, written by
cargo psync build for the macro to read on the next build: the call’s effects, and whether it
may panic (Compiler facts).
Fission. Splitting a loop into a plain first loop, which updates carried state for every item, and a prefetched second loop.
Fixed point. The solution of equations that define a set in terms of itself (liveness, summaries of recursive functions), found by iterating until nothing changes.
Fresh binding. A #[psync::fresh] let whose initializer every concurrent chain evaluates
again.
Gate. A comparison of two file paths when the function runs: two chains whose paths may name one file run concurrently if the paths differ, and in order if they are the same (Paths compared at run time).
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.
HIR, THIR, MIR. rustc’s forms after macro expansion: the desugared program (HIR), with every expression typed and every method call resolved (THIR), and as a control-flow graph of simple statements (MIR). psync-driver reads MIR.
Hoisting. Moving an await out of a larger statement (scrutinee, argument, receiver, branch, tail) into its own binding, while keeping evaluation order.
Labelled transition system. A model of a server: each request (the label) takes its state to a new state and a response. Reads that change state are ordinary transitions.
Join. The point where a level’s chains are polled together until all have finished
(poll_fn over each chain’s MaybeDone); their bindings are handed back after it
(Generated code).
Level. A set of chains joined together. Each level waits for the one before it.
Marker. The maybe_done_at::<..>, job_at::<..> and over_at::<..> calls in generated
code, whose const parameters record what the macro assumed (level, order, exits, speculate,
independent), so that cargo psync check can read them from MIR. They cost nothing at run time.
Node. A statement psync may move: a binding, an awaited statement, or an effect.
Opaque. A summary with a callee the driver could not see through (a function pointer, a dyn trait of another crate). The macro then keeps its name-based guess as well.
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.
Release level. The level after which a chain’s exits are replayed and its bindings handed back. It is the chain’s own level, or later, if an earlier statement in program order runs in a later level (Levels).
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.
Strongly connected component (SCC). A maximal set of functions that can all reach each other through calls. The driver solves each one as a fixed point.
Summary. Every effect a call to a function may have, through every function it calls.
Token tree. What a procedural macro receives: identifiers, punctuation, literals, and bracketed groups of further trees. See Tokens.
Related work: dependence and diagnosis
psync rewrites programs, but two questions it raises come from older work on measuring them. Which waits sit on the critical path of a request? Would making one part faster make the whole faster? This page lists the work psync’s diagnosis features build on: the conditional critical path (Predicting the speedup, built: per path, from traces of several runs) and a dependence graph of async code from MIR (Dependence graphs, built). For each, it says what the work does and what psync takes from it.
The program dependence graph (Ferrante, Ottenstein and Warren, 1987)
Jeanne Ferrante, Karl Ottenstein and Joe Warren, The Program Dependence Graph and Its Use in Optimization, ACM TOPLAS 9(3), 1987.
The PDG puts two kinds of edges in one graph. Data dependences say a statement uses a value
another defines. Control dependences say a statement runs only if a branch goes a certain way.
Control dependence is computed from post-dominators: B is control dependent on branch A when
one of A’s successors always leads to B and another may avoid it. With both in one graph, a
transformation that reorders code only needs to respect the edges, which is what psync’s scheduler
does on its token-level graph (Dependencies and dataflow).
For psync. The macro’s graph has data and effect edges, and early exits stand in for control
dependence: a write after a ? waits, or needs speculate. The PDG built from MIR
(cargo psync pdg) gives exact control dependences, including branches inside callees, and guards
for statements that only run on one path.
AppInsight (Ravindranath et al., OSDI 2012)
Lenin Ravindranath, Jitendra Padhye, Sharad Agarwal, Ratul Mahajan, Ian Obermiller and Shahin Shayandeh, AppInsight: Mobile App Performance Monitoring in the Wild, OSDI 2012.
AppInsight rewrites the binaries of mobile apps to follow a user transaction: from a tap, through the asynchronous callbacks and threads it starts, to the screen update that ends it. From the recorded edges it finds the transaction’s critical path, the chain of waits and work that decided how long the user waited. It does this in deployed apps, without changing the developer’s code.
For psync. A function rewritten by psync is a small transaction: chains joined in levels. Its critical path is the slowest chain of each level, and only shortening that chain helps. Joining measured span latencies to psync’s graph (Predicting a schedule) is AppInsight’s idea applied to one function, with the graph known statically instead of recovered from callbacks.
Panappticon (Zhang et al., CODES+ISSS 2013)
Lide Zhang, David Bild, Robert Dick, Z. Morley Mao and Peter Dinda, Panappticon: Event-Based Tracing to Measure Mobile Application and Platform Performance, CODES+ISSS 2013.
Panappticon traces events in the Android framework and the kernel, such as message queues, binder calls, locks and I/O. It links them into the transactions of an app, so a delay can be traced to the platform and not only to the app’s code.
For psync. Delays outside the function also count: a connection pool, a server’s flow control (Patterns and pitfalls), or the executor’s queue. Diagnosis from spans alone sees them only as long waits, and Panappticon shows the value of tracing below the application.
Timecard (Ravindranath et al., SOSP 2013)
Lenin Ravindranath, Jitendra Padhye, Ratul Mahajan and Hari Balakrishnan, Timecard: Controlling User-Perceived Delays in Server-Based Mobile Applications, SOSP 2013.
Timecard tells the server, while it handles a request, how much time the request has already spent and how long the rest of its trip, the response’s way back and its rendering, is predicted to take. The server can then change its work, for example by returning a cheaper answer, to meet a deadline for the whole transaction.
For psync. psync changes only the order of a function’s work, not its amount. Timecard is a reminder that latency belongs to the whole request, and that a rewrite which shortens one function matters only if that function is on the request’s critical path.
Coz (Curtsinger and Berger, SOSP 2015)
Charlie Curtsinger and Emery Berger, Coz: Finding Code that Counts with Causal Profiling, SOSP 2015.
A conventional profiler shows where time is spent. Coz shows what would happen if a line were faster. It runs a virtual speedup: while the chosen line runs, every other thread is paused for a fraction of that time, which has the same relative effect as making the line faster. It then measures how the rate of progress points, such as requests completed, changes. Code that takes a lot of time but is not on the critical path shows no effect.
For psync. psync’s question before a rewrite is the same: if these waits overlapped, how much
faster would the function be? The schedule implies an answer: each level takes as long as its
slowest chain. psync-predict computes it from measured spans (Predicting the speedup),
and Comparing builds measures the real answer to check it. That is a causal
profile for one kind of change, reordering waits, with the graph saying which reorderings are
allowed. WebProphet (Li et al., NSDI 2010) made the same kind of what-if prediction from a graph of
a web page’s fetches; What is new, and what is not compares the two.
Where psync differs
All four diagnosis tools observe a program and tell a person where to look. psync changes the
program. It proves from the graph which waits may overlap, and it checks the rewrite with the
compiler (Checking rewrites). The diagnosis features close part of the loop.
psync-predict measures which chains are on the critical path of each path through a function,
with the share of runs that took it, and graph_suite checks the predictions against the measured
rewrite, and cargo psync pdg --entries finds where requests enter (main, axum and actix-web
handlers; Entry points). Still to
come: predicting the gain of a hint such as speculate or independent before adding it, and UI
events as entry points.