Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

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:

  • u is v’s last predecessor, and all of v’s predecessors are in u’s chain (members of a chain run in order, so when u has run, they all have);
  • u is currently the last node of its chain; and
  • either u has only one successor (v), or u does not await and every other successor of u also (transitively) waits for v.

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.
  • mut is dropped inside a chain for bindings the chain does not write. The handed-back binding keeps its mut. This avoids unused_mut warnings 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!, join and the like, with no indexing, no arithmetic and no other call;
  • it depends on nothing the region binds, except a let bound once to a total value, which is substituted;
  • it depends on no mut binding.

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:

TargetOverlap whenFunction
file pathone is the other or a directory containing it__psync_overlap (in the prelude)
URLthe same, on the path after the host, without ?query or #fragment__private::urls_overlap
Redis keyequal__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_run runs 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, which relax checks: 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/1 and /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 check knows the gate from gated_by, but exempts only the pair’s direct fs calls. 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 spellingsOne file because
current.json and data/v2.jsoncurrent.json is a symlink to data/v2.json
a and backup/aa hard link: two directory entries, one inode
Readme.md and README.mda 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:

APIStable sinceWhat it settles
std::fs::canonicalize1.5follows symlinks and resolves .., but only for paths that exist
std::os::unix::fs::MetadataExt::{dev, ino}1.1device and inode: the file itself, which hard links share
std::os::fd::{OwnedFd, AsFd}1.63an open file as an owned value, closed on drop (OwnedHandle on Windows)
File::create_new1.77create, failing if the file exists, in one system call
std::path::absolute1.79an absolute path without touching the disk: lexical only, symlinks are not followed
std::fs::exists1.81whether a path exists, with errors reported instead of swallowed
File::lock1.89an 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) from metadata, 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

  1. 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 by files_overlap(&a, &b).
  2. Loop items are compared by identity. The per-item check builds ItemTarget::file(&path) instead of ItemTarget::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. FileId answers that with two system calls (metadata and canonicalize) per path, and the program still does its own opening.

Costs and limits

  • Time: each compared path costs a stat and a realpath at 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 (canonicalize returns 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_text removes them where you know the paths are plain.

Exercises

  1. Predict the chains and levels of this function, and its time, where io(d, v) waits d and returns v:

    #[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?

  2. Change b2 to io(T, a2 + 1). What changes, and how long does it take now?

  3. In the key / resp / cache.insert example, key has two successors. Which condition lets it fuse anyway, and why would that fail if key were let key = store.next_id().await;?

  4. A function reads redis::cmd("GET").arg(&a) and then writes redis::cmd("SET").arg(&b), where a: &[u8] and b: &[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
  1. a1 has two successors (b1 and b2), so neither edge fuses. level 0: n0 || n1, then level 1: n2 || n3. Level 0 takes 3T (it waits for a2), and level 1 takes 3T (for b1): 6T, against 8T sequentially. A dataflow schedule would start b1 when a1 ends, at T, and finish both at 4T. The test book_levels_wait_for_all_their_chains in tests/graph.rs checks the 6T.
  2. Each a now 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.
  3. The second case of fusion: key does not await, and the other successor, cache.insert, waits for resp anyway. With next_id().await, key awaits, so only the single-successor case could apply, and it has two. key ends its chain, resp gets level 1, and insert, whose predecessors are now in two chains, level 2.
  4. Yes: &a and &b are total, and neither is bound in the region or mut, so the two commands are planned as concurrent with a gate between them. But [u8] has no Display, so (&Key(&(&a))).text() finds NoKeyText and gives None, and keys_overlap returns true: the SET always waits for the GET. The function behaves as written and gains nothing. Keys built with format! or held as String have text and are compared.