Re: Races in sessions

2021-02-14 Thread 'Adam Johnson' via Django developers (Contributions to Django itself)
Indeed, locking is hard. I think it'd be better to warn more about how sessions do not have guarantees against parallel writes. And perhaps we could update the example to use the session as a cheap first check whether the user has commented, actually defending with a full query against the database

Re: Races in sessions

2021-02-07 Thread Matt
Thinking out loud: You can't just lock the session when you think you have a critical section of code in a view because the session data is stored in one field in the database, and is *completely overwritten* on write. Consider this case: Thread A: Read session data Thread B: Open transaction,

Re: Races in sessions

2021-02-07 Thread 'Adam Johnson' via Django developers (Contributions to Django itself)
Stephen - you're right that a constraint is the best way to enforce consistency in the DB. That doesn't fit every use case for sessions though - people use Django's built-ins with many different kinds of data stores that don't support locking or constraint semantics, such as remote API's. Matt - I

Re: Races in sessions

2021-02-07 Thread Stephen J. Butler
The way I'd solve this example is to create a unique constraint/index in the DB. The session check gives a quick pre-check, but in the event of a race the DB enforces absolute consistency. If the constraint isn't possible or is too complex, then your "SELECT... FOR UPDATE" belongs on the check for