Yet Another Performance Footgun in Rust - Multithreading Lock Edition

I went to look at that on my phone (pixel 6a), but botstopper/anubis was computing for like 3min straight at difficulty 6, can you or whoever has access turn down the difficulty somewhat? apparently for the fast challenge the time needed scales proportionally to 16^difficulty

Replying directly to avoid exposing setup details publicly.

Not really. A footgun is something that catches you by surprise and blows your foot off. What you describe is something that catches you by surprise and make you run less fast. Not a footgun. More like a rock in your shoe. A rock you can feel and remove easily.

2 Likes

To add to which: something that makes it easy for a programmer to think some group of statements are protected by a lock, when in reality they aren't? That's a footgun.

4 Likes

One might suggest calling drop explicitly or wrapping the logic in an inner scope, but neither is a robust or reliable solution. Why? Because both require manual awareness, in other words, they rely on the developer's skill to do so.

This is necessary anyway to avoid

  • deadlocks (inconsistent lock ordering)
  • holding locks across await points
  • expensive work in a critical section

To adapt your example:

{
    let data = data.lock()
    // ... A ...
    data.update(10) 
    // ... B ...
}

B isn't the only problem, A is too.

So making the whole thing explicit as a lock scope is good practice when there's some surrounding code.

async fn foo() {
   // ... some async stuff

   // explicit lock scope!
   {
      let bar = bar.lock().unwrap();
      // {critical section}
   }

   // ... moar async stuff
}
4 Likes

It is easy

  • Vanilla Rust coder just write normal code, the design already takes care the performance thing

Eg :

fn task(name: &str, mut input: i32) -> i32 {

    let data = DATA.lock()

    data.name = name

    for val in data.iter_mut() {
        data.number *= 2
    }

    for i in 0..input {
        input = (input + name.len()) * i
    }

    return input
}

Clean, linear, correct performance out of the box.

  • if needs manual placement, just recall the variable with let _ =. 95% cases you won't do this. In scope based, you this very often, because its design is not optimized for the common use cases, so you have to use more manual effort if wants to do multithread locking corectly not the performace footgun. Note, inserting child scope is equal to inserting let _ = just different syntax.

Eg :

fn abc(input: Data) {
    let data = input.lock()

    // I want to unlock it at far longer place



    // simply place this anywhere you want
    let _ = data

    // the data is not dropped from memory, but only the lock is removed, aka unlocked. The dropping from memory is handled by the ASAP drop of the original variable
}
  • variable that is converted to raw pointer uses scope based drop. ASAP drop becomes manual using keyword asap and manual verification just like scope based drop. Eg:
#[derive(unsafe_asap)]
struct Vec {
    ptr: *mut u8,
    capacity: usize,
    len: usize
}

// Or if want individually
name: asap TypeName

let name = asap String::new("abc")
  • everything else about async is same to scope based drop, like deadlock in cross await

Any pointer does not auto use ASAP drop, but the existing scope drop. It is detected when the compiler compile the code, it will read all code and eventually find the convertion site "T as *mut T", then T is marked as variable that is converted to pointer. If it sees variables that are annotated to use ASAP drop explicitely, it skips the pointer convertion analysis

I never said every drawback has been sufficiently addressed. But "every drawback that I know has been addressed by me, using my own skill", then I shared it to get more improvements

It doesn't uses borrow checker, but it uses the intermediate analysis that is done by NLL borrow. It only uses the function that analysis where is the last user of T, so it has nothing to do with borrow checker. For analogy, a socket and tokio, it doesn't use tokio, but only the socket

The function that does last user analysis already fullfill the ASAP drop needs, so if borrow checker changes it does not need to remove the last user analyzer, because if you drop memory manually, you will do it after nobody uses it, so you place it after the last user

Clippy has its own drawback in human experience

  • you write many code, you don't know where to place it, you run clippy, it tells you to place the manual drop here and here and here, you reedit the code, then you write many new code again, you don't know where to place it, you run clippy again, it prints message to place drop here and here and here and here, you scroll and edit the code again to any code and any file. Then the code is filled with memory management ceremony not business logic
  • you can not get ASAP drop if it is code written by other people, eg 3rd party libraries. Because Clippy needs to insert drop manually physically by hand, not compiler magic, and you don't have access to the code

No, footgun is not just thing that makes the app crash etc. It is anything that results to unwanted result, including making performance low unnecerery. Eg, N+1 query, blocking event loop thread. If you use feature A, with the hope to get result B, but you get result C instead without you realise it when writing it, the feature A has footgun. I use lock, with the hope of lock the data if it is used, and unlock the data after not used, but what happens is I without realizing it resulting a result that lock the data for the entire scope duration, so the lock mechanism has footgun

However, starting as a Clippy lint is a good way to prove that something is generally useful - a lint can go from "nursery" to "suspicious" to being a deny-by-default rustc lint to changing the way the language works in line with the lint.

At core, changing the language is a big deal - it means forcing people to audit all existing code and documentation to confirm that it's still correct even in the presence of a change. Adding a lint is a very good way to gather data to show that the language change makes sense - first get the lint stable as an allow-by-default Clippy lint, then persuade people to make it warn-by-default (e.g., then you'll get examples of cases where people think this change is bad because it's warning on code they think is perfectly reasonable).

Remember that, fundamentally, evolving existing parts of a language has to be conservative - every time you change something that people are depending on, you force people to do "busy work" that they don't want to do, and if you do that enough times, they abandon the language and move on. Adding new things that have no impact on existing code is where you don't have to be conservative.

3 Likes

You talk about someting that has nothing to do with what I said. I said, you have to put manual effort to get the same performance of ASAP drop. But then you expand it to deadlock, await, etc

So your saying isn't even a problem to ASAP drop benefits offer

Because ASAP drop can do all you say while preserving the automatic benefits for the 95% cases

So what? Your code require manual awareness, so easy if done in asap drop. Explisit scope is equal to manual drop = manual awareness

ASAP drop version :

async fn foo() {
   // ... some async stuff

   
   let bar = bar.lock().unwrap();
   // {critical section}
   let _ = bar; // or drop(bar)

   // ... moar async stuff
}

It is not like explisit scope drop has upper hand than manual drop in manual awareness cases. They are in same level

But ASAP drop has the upper hand in the 95% cases, where lock is used to lock its inner data not a token gate for outside code. Still ASAP drop can do whatever scope drop does, but scope drop doesn't has the automatic benefits of ASAP drop when it meets

Making Clippy lint deny by default in rustc level does not solve the problems of a lint that I stated earlier. So I recommend you reread it

To put it simple, lint/error is not compiler magic. Lint/error just tells you the info, you have to do the grunge work to fix it yourself manually, which result in bad user experience because people get something in ther way that could actually be moved to compiler magic. Compiler magic is the compiler handles it all automatically user just receive the clean result, user does not see warning or error message, user does not need to do the fix manually (writing manual drop), compiler already insert the drop code automatically when later compiling the code, it does not edit your code but its own internal state when compiling and the cache in target folder. So rustc level deny will still has these problems

It can be experimented in a fork of rust compiler

I have read what you've written before - you're simply shouting at me because I don't fall into line with you.

The counter to everything in that block is that if you change the language definition, you force everyone who's written anything in Rust that uses Drop to audit their code (and their documentation) for correctness in the face of this change, or you stop them upgrading their toolchain for fear of subtle bugs.

Even if you wanted to make a change to existing Rust semantics, you would have to start with a deny-by-default lint in rustc for several toolchain versions so that we can get everyone's extant Rust code to a point where it's safe to make this change without fear of breaking users - you can't just make the compiler change as step 1, because then my code that depends on scoped Drop either breaks or becomes unsound if I'm using unsafe, having been sound when it was written.

But, given that we need a deny-by-default lint in rustc for several toolchain versions anyway, why not go through the normal process of "Clippy lint in nursery, promote to suspicious, promote to warn-by-default rustc lint, promote to deny-by-default, then make the language change that this lint makes safe"?

1 Like

I disagree. A gun blows your foot off (meaning you get undefined behavior). The things you describe are not foot guns. They are normal programming and usage where it is up to you to do what makes sense for your use case. If everything you could get wrong were a foot gun, then everything would be a foot gun.

3 Likes

Please understand that this all by itself is a deal-breaker for me and probably a lot of other people in this thread.

The scope protected by a lock needs to be obvious to people reading code in a hurry while tired. This is more important than performance. Introducing compiler magic that make lock guard drops happen as early as possible -- even if it was provably correct about when the drop needed to happen, 100% of the time -- would break that.

(Rust could stand to make lock scope more obvious -- I'd be in favor of introducing a with statement along the lines of Python or C#, just to make the presence of a guard stand out more -- but what we have now is pretty good.)

8 Likes

this can almost be done in user code, if you accept a closure instead of a keyword Rust Playground (missing: poison handling)

And I dissagree with you, and yes everything that could lead to human mistake that can be costly, it is footgun. Nowhere footgun must be a crash, if you search keyword "performance footgun" in internet, you will find it is used way many times since years ago, and even used by Rust developers eg this one : Large tuples are a performance footgun · Issue #237 · winnow-rs/winnow · GitHub

Footgun, you shoot your own foot, you created a mistake that it does something bad to your own app in a level that is costly enough. rm -rf is also footgun, it does not crash an app, so it is not a footgun? You are wrong, it is still footgun. React use effect was used to be able to cause double request to server, can scale big cost, eg 100k req will be 200k req, it is also footgun, more specifically performance footgun. There is other popular term, engineering footgun where your architecture makes some big problem in the future. Extending lock lifetime can also become costly, eg :

// spawns these tasks to 8 thread
{
    let data = data.lock().unwrap()
    // many code
    data.push(new_val);
    // many code
    data.push(new_val);
    data.update(new_val);
    for val in big_sales_data {
        // processing, takes 10 minutes
    }
}

Every thread is forced to take unnecerery additional wait duration (10 minutes), so in total you waste 10 * 8 = 80 minutes, 1 hour 20 minutes. You think it is because processing many data, but actually because each thread gets blocked for unnecerery additional 10 minutes. Additional 1 hour 20 minutes processing time, is a big enough cost, thus it is a footgun, more specifically performance footgun. The term itself already tells it, performance footgun, so it is a human mistake that can lead to severe performance drop

Let's not continue this unnecerery concern, it has nothing to do with the technical to not pollute and waste time. The conclusion is simple, performance footgun, a human mistake that can lead to severe performance drop

The big thing I think you lose with that approach is the ability to exit early from a block outside the closure (e.g. ? will exit the closure, not the entire function). That's not a problem for thread scopes because it doesn't make sense for a thread procedure to make some other thread's code do an early exit, but I think it'd be a severe limitation for lock scopes.

I don't see any problem with it, because ASAP drop is also obvious, you just take a look at where the variable name is typed latest

You can add with keywoard, but I need to point this out, it have to be only receive single statement, because if it receive multi lines code then it just goes back to the performance footguns. So the lock is unlocked after the latest with

  • no longer a lock is accidentally extended for the whole execution duration of all the code in the scope, but only until the last user exactly real equal performance to manual management language like C and Zig but even without needing skill
  • free additional guard against deadlock
  • Rust code has optimal result out of the box