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.