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

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 delete or upload, 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:

  • ? or return inside a macro call (my_macro!(x?)), and the macros bail!, ensure!, try!, return_err! and fail!. Their tokens are opaque.
  • break with 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:

WorkWhat it doesHow 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).

  1. first_error_wins([true, true, true]): which error comes back? How many requests were in flight at the peak?

  2. In the later-level example above (exit_after_later_level), fail = [false, true]: does logged run? What is returned?

  3. Same function, fail = [true, false]: logged fails, four succeeds. Sequential code never starts four. Does psync? Is that a problem here?

  4. Change four into a write, for example store.put("c", 4).await?. What does psync do with it now, and why? (Check with psync-expand.)

  5. 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? and audit.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 would cargo psync check say?

  6. Why is futures::join!(a.fetch(), b.fetch()) a barrier, even though both calls only read?

Answers
  1. 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.
  2. Yes. four failed in level 0, but logged comes first in program order, so psync runs it (level 1) before replaying four’s error. It returns Err("four"), and the log is [3].
  3. Yes: four ran in level 0, before logged was even started. That is speculation, and it is harmless here because four only reads. Its result is dropped and logged’s error is returned.
  4. 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 when logged fails. #[psync::speculate] on the statement would let it overlap again.
  5. 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 check reports a cancellation note on the function naming both chains.
  6. 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.