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

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:

  1. Which edge of the graph does it remove (or add)?
  2. Which part of the certificate’s footprint does it remove?
  3. 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:

RuleExample reason in the reportCan a hint turn it off?
data flow: B reads a name A definesreads `user` no
shadowingrebinds `x` no
conflicting accesses to one place in memorywrites `self.cache` no
effects on one outside resource conflictwrite `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` runsspeculate
two plain statements keep their ordereffect orderno

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.

A: set_account_data(enabled)? B: set_account_data(disabled)? effects conflict (both write client) A may exit before B writes #[psync::independent] on A or B removes the solid edge #[psync::speculate] on B removes the dashed edge Only with both does A || B become possible.
Two reasons for one edge between the statements of the hint example. The report names the first (the conflict); remove it and the report names the second. Each hint removes one.

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, so seq can 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. The let itself stays where it is (a barrier). In addition, schedule.rs puts a copy of the let at 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" in schedule.rs). There is no longer one &mut shared 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 to w/<domain>/<target>, or a read of it. With independent, the statement’s outside effects are left out of its footprint.
  • An exit writes a place x/<i>, and a later write that is not speculate reads every earlier exit’s place. That read is what makes “write after a possible exit” a conflict. With speculate the 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

HintRule it turns offFootprint it shrinksChecked by
seqnone (adds a barrier)nonenothing needed: more order is always correct
freshnone: it removes the sharing, by giving each chain its own copy of the bindingnonethe borrow checker checks each copy; that a second value behaves like the first is your promise
independenteffect conflictthe statement’s outside effectsnobody. cargo psync check gets INDEP and skips its conflict check for the chain
speculatewrite after a possible exitthe reads of earlier exitsnobody. cargo psync check gets SPEC and skips speculative-write
par (synchronous code)none: it marks a statement worth a threadnonethe 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 every post_search in 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 a READS const 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:

Checklist for a new hint kind

  1. 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.
  2. Find the one rule it turns off, or the one barrier it adds. A hint that touches two rules is two hints. independent and speculate are separate for this reason.
  3. 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.
  4. Make the footprint agree. Change the node, not the schedule, so the certificate follows.
  5. Decide who checks it. The compiler, cargo psync check, or nobody. If nobody, list it under assumption 5.
  6. Add it to HINTS, re-export it, document it, and test it in both directions.

Exercises

  1. (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?;
  2. (Footprints.) For the set_account_data example, write the second statement’s footprint (reads and writes, with names, not numbers) with no hints, with only independent, and with only speculate. In each case, which place of the first statement does it overlap?

  3. (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.

  4. (Code, harder.) Finish step 5 the “trust it” way. Find where SPEC and INDEP are emitted in schedule.rs (search let spec =) and read in psync-check/src/driver/analysis.rs (search indep). Add READS, so the driver skips conflict for a pair when the reading side is marked and the other side does not write.

  5. (Design.) Why is seq safe to add anywhere, while independent is not? Answer in terms of edges.

  6. (New idea.) Someone proposes #[psync::idempotent]: “doing this twice is the same as doing it once”. Is that the same promise as speculate? What could psync do with it that it does not do today?

Answers
  1. get reads store with the target "index.html". delete writes store with 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 before delete runs:

      n0 (get index.html)? ──may exit before `delete` runs──▶ n1 (delete draft.html)
      
    • independent on the delete. Same picture. There was no effect edge to remove, and the exit edge stays.

    • speculate on the delete. No edges: n0 || n1. The delete may now run even when get fails, which is exactly what you promised is harmless. For a delete it rarely is.

    • Both. The same as speculate alone.

    The lesson: use the report before you use a hint. Here independent does nothing, because psync already knew the targets differ.

  2. With no hints, the second statement reads n/client, n/disabled, the memory paths of client and disabled, and x/0. It writes w/service/client and x/1. It overlaps the first statement twice: both write w/service/client, and it reads x/0, which the first writes. With only independent, w/service/client is gone, and the overlap on x/0 remains. With only speculate, the read of x/0 is gone, and the overlap on w/service/client remains. That is the certificate’s version of “each hint answers one question”.

  3. Compare against the branch. The usual mistakes are forgetting HINTS (the build fails with E0658), and testing only the hinted case.

  4. In outline:

    1. In schedule.rs, next to let spec = members.iter().any(|n| n.speculate);, compute reads the same way from a new Node field, and add it to the maybe_done_at arguments (and to the signature of maybe_done_at in src/graph_rt.rs).
    2. In the driver, read the new generic argument where indep is read.
    3. In the conflict loop, skip the pair when one chain is reads and the other has no write.
    4. Add a fixture to psync-check/tests/fixtures/hidden: two marked post-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 reads is narrower than independent.

  5. seq only adds edges. Every schedule that respects a set of edges also respects any subset of them, so the schedule with seq respects every edge the program needs. It cannot be wrong. independent removes 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.

  6. No, though they are often confused. Hints gives idempotent uploads as an example where speculate is safe, and that is the usual reason a speculative write is harmless, but the promises differ. speculate says “doing it once when the sequential program would have done it zero times is harmless”. idempotent says “doing it twice equals doing it once”. psync never performs a statement twice today, so idempotent would 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.