Adding a hint
Hints showed what each hint is for. This chapter shows what a hint is inside psync, follows one through every stage, from the attribute to the proof, and then builds a new hint with you, step by step. By the end you will be able to answer three questions about any hint, existing or proposed:
- Which edge of the graph does it remove (or add)?
- Which part of the certificate’s footprint does it remove?
- Who checks the fact it states: the compiler,
cargo psync check, or nobody?
You need The graph and the schedule and
Certified schedules first. Have psync-graph/src/classify.rs and
psync-graph/src/schedule.rs open beside this page.
A hint is a flag that turns off one rule
psync draws an edge between two statements when one of six rules says their order matters
(edge in schedule.rs, see Dependency edges). The rules are tried
in order and the first that matches is the reason the report shows, so an edge with two reasons
shows one at a time:
| Rule | Example reason in the report | Can a hint turn it off? |
|---|---|---|
| data flow: B reads a name A defines | reads `user` | no |
| shadowing | rebinds `x` | no |
| conflicting accesses to one place in memory | writes `self.cache` | no |
| effects on one outside resource conflict | write `client` .. vs write `client` .. | independent |
B writes, and A may exit before it (a ?, return, break, or a call that panics explicitly) | may exit before `set` runs | speculate |
| two plain statements keep their order | effect order | no |
The first three are about memory inside the program. The Rust compiler checks them anyway: if psync got one wrong, the borrow checker would reject the generated code. No hint may switch them off, because no fact you know can make two lanes safely write the same variable.
The fourth and fifth are about the outside world: files, servers, processes. psync cannot see that world from tokens, so it guesses on the safe side, and these two guesses can be overruled.
The sixth keeps plain statements in order: statements that are neither a binding nor an await,
such as v.push(x); or println!(..). They change state in place and are cheap, so moving them
buys nothing. No hint touches this rule.
That is all a hint is: a statement-level flag that turns off one rule for one statement.
Here is where the flags are set, in classify (classify.rs):
let speculate = scope.effects.speculate || attrs.iter().any(|a| is_psync_attr(a, "speculate"));
Class::Node(Box::new(Node {
effects: found.effects,
unclassified: found.unclassified,
panics: found.panics,
speculate,
independent: scope.effects.independent()
|| attrs.iter().any(|a| is_psync_attr(a, "independent")),
And here is where they act, in edge (schedule.rs):
// Effects on the same file, service or other outside resource keep their order.
if !(a.independent || b.independent)
&& let Some(why) = crate::effects::conflicts(&a.effects, &b.effects)
{
return Some(why);
}
// A write is not performed before an earlier statement that may leave: sequential code
// would not have performed it at all.
if (a.exits || a.panics)
&& !b.speculate
&& let Some(w) = b.effects.iter().find(|e| e.writes())
{
// The call's name; where the effect came from is said with the effect itself.
let op = w.op.strip_suffix(", per the compiler").unwrap_or(&w.op);
return Some(format!("may exit before `{op}` runs"));
}
Read the two ifs slowly. independent on either statement drops the effect edge between
them. speculate on the later statement, the one that writes, drops the exit edge. Neither
touches the data-flow rules above them.
seq and fresh work differently
seq and fresh do not set a flag that removes an edge. In classify they turn the statement
into a barrier: the block is split there and nothing moves across it.
#[psync::seq]only adds order. A schedule with more order than needed is still correct, soseqcan never make a program wrong. The worst it can do is make it slower.#[psync::fresh]does not switch off a memory rule; it removes the sharing the rule is about. Theletitself stays where it is (a barrier). In addition,schedule.rsputs a copy of theletat the start of every later chain that uses the name, so each chain evaluates the initializer itself and owns its own value (search for"fresh"inschedule.rs). There is no longer one&mutshared by two chains, so the memory rules have nothing to order, and the borrow checker still checks each copy. What you promise is that evaluating it again is correct, for example that two connections from a pool behave like one.
Hints on loops
On a for or while loop, independent and speculate are read in loops.rs, not in
classify. independent skips the checks that one iteration’s awaited work does not depend on
state an earlier iteration changed. speculate allows a prefetched prefix to write even when the
body can end the loop early. The rule is the same: one flag, one check off.
What the proof assumes
A certificate gives every statement a footprint: the list of
places it may read and write. A place is a short path of names, such as n/user (the variable
user) or w/service/client (the outside resource behind client). Two statements conflict when
one writes a place the other reads or writes. Lean, a proof checker, then checks that the schedule only reorders statements whose footprints do
not conflict. The hint flags change the footprint psync writes into the certificate
(cert_nodes in schedule.rs):
if !n.independent {
for e in &n.effects {
if e.writes() {
c.writes.push(e.place());
} else {
c.reads.push(e.place());
}
}
}
if n.exits || n.panics {
c.writes.push(one("x", &[&j.to_string()]));
}
if !n.speculate && n.effects.iter().any(|e| e.writes()) {
for (i, m) in nodes[..j].iter().enumerate() {
if m.exits || m.panics {
c.reads.push(one("x", &[&i.to_string()]));
}
}
}
- Without
independent, every outside effect becomes a place in the footprint: a write tow/<domain>/<target>, or a read of it. Withindependent, the statement’s outside effects are left out of its footprint. - An exit writes a place
x/<i>, and a later write that is notspeculatereads every earlier exit’s place. That read is what makes “write after a possible exit” a conflict. Withspeculatethe read is left out.
Here is the real certificate for the hint example with both hints (generated by psync-cert; the
numbers stand for names, numbered in order of first use to keep the file short):
nodes := [
{ reads := [[0, 1], [0, 2], [3, 1], [3, 2]], writes := [[4, 5, 1], [6, 7]] },
{ reads := [[0, 1], [0, 8], [3, 1], [3, 8]], writes := [[6, 9]] }]
levels := [[[0], [1]]]
The names are 0 = n (a name), 1 = client, 2 = enabled, 8 = disabled, 3 = a
memory path, 4 5 1 = w/service/client (a write to the client), and 6 7 and 6 9 are
x/0 and x/1 (the two exits). The second statement writes only its own exit, x/1. Its write
to the client is gone (independent), and so is its read of x/0 (speculate). Nothing it
touches overlaps the first statement’s footprint, so Lean accepts them in one level.
This is exactly what What is checked, what is assumed calls
assumption 5, hints are true. The theorem check_sound says that the schedule equals the
program for any meaning of the statements under which the footprints are right. A hint makes
the footprint smaller. If the hint is true, the smaller footprint is still right, and the proof
covers your program. If it is false, the proof is still valid, but it is a proof about a
different program from the one you run.
Who checks the fact
| Hint | Rule it turns off | Footprint it shrinks | Checked by |
|---|---|---|---|
seq | none (adds a barrier) | none | nothing needed: more order is always correct |
fresh | none: it removes the sharing, by giving each chain its own copy of the binding | none | the borrow checker checks each copy; that a second value behaves like the first is your promise |
independent | effect conflict | the statement’s outside effects | nobody. cargo psync check gets INDEP and skips its conflict check for the chain |
speculate | write after a possible exit | the reads of earlier exits | nobody. cargo psync check gets SPEC and skips speculative-write |
par (synchronous code) | none: it marks a statement worth a thread | none | the compiler: data sent to a thread must be Send |
The checker is told about the two trusted hints through the const generics of the chain wrapper,
maybe_done_at::<LEVEL, ORDER, LAST, EXITS, EXIT_AT, SPEC, INDEP, _>
(Certified schedules). In psync-check/src/driver/analysis.rs you
will find if !(earlier.indep || later.indep) before the conflict report, and if !later.spec
before the speculative-write report. It is the same rule, once more, on the compiled code.
So independent and speculate are the hints to review in a pull request. Each is a promise
about a server, a file system or a business rule that no tool in psync can see.
Tutorial: a #[psync::reads] hint
We now add a hint. The finished change is on the branch tutorial/reads-hint of the repository:
four files, 46 lines. Try each step before you look.
The problem
Many search APIs take the query as the body of a POST. Elasticsearch’s _search is one example.
psync reads the name post_search, sees the verb post, and treats it as a write:
#[psync::graph]
async fn search(es: &Search, a: &str, b: &str) -> Result<(Hits, Hits), E> {
let x = es.post_search(a).await?;
let y = es.post_search(b).await?;
Ok((x, y))
}
region 0 (unchanged):
n0: x = post_search()? [await] {write `es` `a` (post_search)}
n1: y = post_search()? [await] {write `es` `b` (post_search)}
n0 -> n1 (write `es` `a` (post_search) vs write `es` `b` (post_search))
level 0: n0->n1
Two searches, one after the other, although neither changes anything. There are two existing ways out, and both are too blunt:
#[psync::graph(effects(read(post_search)))]makes everypost_searchin the function a read.#[psync::independent]turns off the conflict check altogether. If one of the statements really wrote, nothing would catch it.
What we want is narrower: this statement’s effects are reads. A read still conflicts with a write to the same service, so the rest of the protection stays in place.
Step 1: the attribute
Hints are attribute macros in psync-macros/src/lib.rs that return their input unchanged. They
exist so that #[psync::reads] resolves to something and has documentation. Add one next to
speculate:
/// Hint on a statement: every effect psync found in it only reads, whatever the call's name says
/// (a search sent as `POST`). ...
#[proc_macro_attribute]
pub fn reads(_attr: TokenStream, item: TokenStream) -> TokenStream {
item
}
Then re-export it from the psync crate, in src/lib.rs:
pub use psync_macros::{fresh, graph, independent, par, reads, seq, speculate};
Step 2: teach psync the name
/// The hint attributes psync reads and removes from its output.
pub(crate) const HINTS: &[&str] = &["seq", "fresh", "independent", "speculate", "par"];
Add "reads" to the list. The list decides which attributes schedule.rs removes from the
generated code (attrs.retain(|a| !HINTS.iter().any(..))). If you forget this step, the
attribute stays on the let in the output, and the build fails with
error[E0658]: custom attributes cannot be applied to statements: stable Rust does not run an
attribute macro on a statement. That is also why a hint outside #[psync::graph] does not
compile.
Step 3: change the node
In classify, just above the hint_flags lines shown earlier, turn every effect of a marked
statement into a read:
if attrs.iter().any(|a| is_psync_attr(a, "reads")) {
for e in &mut found.effects {
e.kind = effects::Kind::Read;
}
}
That is the whole change to the analysis. Everything downstream follows from the node’s effects:
effects::conflicts finds no write-write conflict, the exit rule finds no write to protect, and
cert_nodes writes reads, not writes, into the footprint. The certificate stays honest by itself,
because it describes the node as it now is.
Step 4: the test
In the tests of psync-graph/src/lib.rs, next to the other report(..) tests:
#[test]
fn reads_hint_lets_searches_sent_as_post_overlap() {
// `search` as above, without hints:
let plain: ItemFn = syn::parse_quote! { /* ... */ };
assert!(!report(Options::default(), plain).regions[0].changed);
let hinted: ItemFn = syn::parse_quote! {
async fn search(es: &Search, a: &str, b: &str) -> Result<(Hits, Hits), E> {
#[psync::reads]
let x = es.post_search(a).await?;
#[psync::reads]
let y = es.post_search(b).await?;
Ok((x, y))
}
};
let r = report(Options::default(), hinted);
assert!(r.regions[0].changed);
assert!(r.regions[0].nodes.iter().all(|n| n.effects.iter().all(|e| e.starts_with("read"))));
}
Always test both sides: without the hint the order is kept, and with it the order is relaxed. A test that checks only the second half also passes when psync relaxes the order without any hint.
Built from the tutorial branch, psync-expand now reports, for the hinted function:
region 0:
n0: x = post_search()? [await] {read `es` `a` (post_search)}
n1: y = post_search()? [await] {read `es` `b` (post_search)}
level 0: n0 || n1
Step 5: the checker
Now the hard question: who checks reads? Not the certificate, which takes the effects as
given. And cargo psync check is not told about the hint at all: the wrapper’s const generics
carry SPEC and INDEP, not READS. The checker computes the callee’s effects from the compiled
code. If post_search sends an HTTP request that the driver counts as a network write, the checker
reports the overlap as a conflict, with no way to know that you meant it.
There are two honest ways to finish the hint, and choosing between them is a design decision:
- Trust it, like
independent. Add aREADSconst generic, and have the driver treat the chain’s effects as reads. The hint then joins the list of facts to review by hand. - Check it. Keep the checker blind to the hint. A warning then means “psync thinks this writes”. That is safer, but noisy for exactly the APIs the hint is for.
The tutorial branch stops before this step, which is why reads is not in the main line. It is
exercise 4.
Step 6: the documentation
A hint is not finished until a user can find it:
- a row in Attributes and hints;
- a section in Hints, with when to use it and when not to;
- a line under assumption 5 in What is checked, what is assumed, if the hint is trusted.
Checklist for a new hint kind
- State the fact in one sentence, about the world, not about psync: “this call only reads”, “these two keys are different”. If you cannot, the hint is not ready.
- Find the one rule it turns off, or the one barrier it adds. A hint that touches two rules
is two hints.
independentandspeculateare separate for this reason. - Never touch the memory rules (data flow, shadowing, conflicting places). The borrow checker would reject the code anyway, and a hint must not imply otherwise.
- Make the footprint agree. Change the node, not the schedule, so the certificate follows.
- Decide who checks it. The compiler,
cargo psync check, or nobody. If nobody, list it under assumption 5. - Add it to
HINTS, re-export it, document it, and test it in both directions.
Exercises
-
(Diagram.) Draw the graph psync builds for this function: no hints; then
#[psync::independent]on the delete; then#[psync::speculate]on the delete; then both. Mark each edge with its rule.let page = store.get("index.html").await?; store.delete("draft.html").await?; -
(Footprints.) For the
set_account_dataexample, write the second statement’s footprint (reads and writes, with names, not numbers) with no hints, with onlyindependent, and with onlyspeculate. In each case, which place of the first statement does it overlap? -
(Code.) Implement
#[psync::reads]from steps 1 to 4 yourself, without looking at the branch. Then compare with the tutorial’s single commit:git show tutorial/reads-hint. -
(Code, harder.) Finish step 5 the “trust it” way. Find where
SPECandINDEPare emitted inschedule.rs(searchlet spec =) and read inpsync-check/src/driver/analysis.rs(searchindep). AddREADS, so the driver skipsconflictfor a pair when the reading side is marked and the other side does not write. -
(Design.) Why is
seqsafe to add anywhere, whileindependentis not? Answer in terms of edges. -
(New idea.) Someone proposes
#[psync::idempotent]: “doing this twice is the same as doing it once”. Is that the same promise asspeculate? What could psync do with it that it does not do today?
Answers
-
getreadsstorewith the target"index.html".deletewritesstorewith the target"draft.html".-
No hints. There is no effect conflict: the two literal targets differ, so a read of one and a write of the other commute. The only edge is the exit rule,
get(..)?may leave beforedeleteruns:n0 (get index.html)? ──may exit before `delete` runs──▶ n1 (delete draft.html) -
independenton the delete. Same picture. There was no effect edge to remove, and the exit edge stays. -
speculateon the delete. No edges:n0 || n1. The delete may now run even whengetfails, which is exactly what you promised is harmless. For a delete it rarely is. -
Both. The same as
speculatealone.
The lesson: use the report before you use a hint. Here
independentdoes nothing, because psync already knew the targets differ. -
-
With no hints, the second statement reads
n/client,n/disabled, the memory paths ofclientanddisabled, andx/0. It writesw/service/clientandx/1. It overlaps the first statement twice: both writew/service/client, and it readsx/0, which the first writes. With onlyindependent,w/service/clientis gone, and the overlap onx/0remains. With onlyspeculate, the read ofx/0is gone, and the overlap onw/service/clientremains. That is the certificate’s version of “each hint answers one question”. -
Compare against the branch. The usual mistakes are forgetting
HINTS(the build fails with E0658), and testing only the hinted case. -
In outline:
- In
schedule.rs, next tolet spec = members.iter().any(|n| n.speculate);, computereadsthe same way from a newNodefield, and add it to themaybe_done_atarguments (and to the signature ofmaybe_done_atinsrc/graph_rt.rs). - In the driver, read the new generic argument where
indepis read. - In the conflict loop, skip the pair when one chain is
readsand the other has no write. - Add a fixture to
psync-check/tests/fixtures/hidden: two markedpost-style calls with no finding, and one marked call beside a real write that is still reported.
The test of the last point is the important one. It shows that
readsis narrower thanindependent. - In
-
seqonly adds edges. Every schedule that respects a set of edges also respects any subset of them, so the schedule withseqrespects every edge the program needs. It cannot be wrong.independentremoves an edge that psync’s rules said was needed. It is right only if the fact it states is true, and no tool checks that. -
No, though they are often confused. Hints gives idempotent uploads as an example where
speculateis safe, and that is the usual reason a speculative write is harmless, but the promises differ.speculatesays “doing it once when the sequential program would have done it zero times is harmless”.idempotentsays “doing it twice equals doing it once”. psync never performs a statement twice today, soidempotentwould remove no edge, and by the checklist it is not a hint yet. It would become one with retries or hedged requests: send the same request to two replicas and take the first answer. That is a new idea in the Phase II direction, and a good one to propose in an issue, with the one rule it would turn off.
? A hint can remove which kinds of edge?
- Data flow (B reads a name A defines)
- Conflicting writes to one place in memory
+ Edges about the outside world: an effect conflict, or a write after a possible exit
- Any edge, if the programmer is sure
> Memory edges are checked by the borrow checker anyway, so no hint may remove them. Only the two outside-world rules can be turned off: `independent` for effect conflicts, `speculate` for writes after a possible exit.
? What does `#[psync::independent]` change in the certificate?
- It adds a proof obligation
+ It leaves the statement's outside effects out of its footprint
- It marks the statement as a barrier
- Nothing; certificates ignore hints
> `cert_nodes` pushes effect places only `if !n.independent`. The proof is then about the smaller footprint, which is right exactly when the hint is true.
? Why does a hint on a `let` outside `#[psync::graph]` fail to compile?
- The psync crate does not export it
+ Stable Rust does not run a custom attribute on a statement (E0658); only the graph macro, which removes it, makes it legal
- It needs a feature flag on psync
> Hints work because `#[psync::graph]` reads them and removes them (the `HINTS` list) before the compiler sees the function body.
? Which hint can never make a program wrong?
+ `seq`
- `fresh`
- `independent`
- `speculate`
> `seq` only adds order. A schedule that respects more edges still respects all the needed ones.