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

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.

HintGoes onMeans
#[psync::seq]a statementkeep this statement exactly where it is
#[psync::fresh]a leteach concurrent chain evaluates the initializer again, instead of sharing the value
#[psync::independent]a for or while loop, or a statementon 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:

  1. the same resource: the same file system, or the same service handle (es, self.client);
  2. at least one writes: two reads never conflict;
  3. 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 (a and b, 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:

the edge's reason in the report reads / writes `x` write .. vs write .. may exit before .. no edge, but order matters a real data dependency same resource, both touched: do they commute? is doing the write anyway harmless? a rule psync cannot see no hint yes: independent yes: speculate seq restructure the code; a cheap shared &mut can be un-shared with fresh no: leave it no (payments, deletes, messages): leave it rate limits, audit logs, business order
Each hint answers one reason. When two reasons join the same two statements, the report shows the second only after you answer the first: it needs both hints.

What each hint costs you:

HintWhat you promiseWho checks it
seqnothingnothing needs to: it only adds order
freshevaluating the initializer again gives an equally good valuethe borrow checker checks the copies; the rest is your promise
independentthe statement’s outside effects commute with the others’nobody: the proof and cargo psync check take it as true
speculateperforming the write when sequential code would have stopped first is harmlessnobody, 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 while loop. psync never rewrites while loops 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.

  1. Remove #[psync::fresh] from fresh_pool. Which edges does the report show, how many chains, and does the region change? Why does reading through pool count as a write?
  2. Take the two set_account_data calls from the independent section, with no hints. Predict the edges. Then predict them with only #[psync::independent] on the second call, with only #[psync::speculate], and with both.
  3. Which hint, if any, do you reach for in each case?
    1. Two GETs to an API that allows one request at a time.
    2. A loop that charges a card for each order, and can stop at a ?.
    3. A loop that fills a cache with cache.insert(k, v) after an awaited lookup.
    4. Two queries that must see the same transaction.
Answers
  1. Three edges: n0 -> n1 and n0 -> n2 (both read pool), and n1 -> n2 (writes `pool`). That is one chain, n0->n1->n2, so the region is (unchanged). pool is 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).
  2. 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). independent removes 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. speculate alone 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 level n0 || n1.
    1. #[psync::seq] on the second GET. Nothing in the tokens says the API is limited.
    2. 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.
    3. #[psync::independent] on the loop, if a repeated lookup for a duplicate key is fine.
    4. Not fresh, which would give each query its own value. Without hints psync keeps the queries through one &mut transaction in order. If they go through a shared handle, mark the second one #[psync::seq].