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.