Interference/Crosstalk using python libraries across sessions

Hello,

We notice there is interference while using standard libraries across sessions. We noticed this in the random and matplotlib libraries in our project.

We reproduce this error with this snippet of code :

Please run two sessions (open two windows or browsers with the same app) and click on start such that both apps run simultaneously.

import streamlit as st
import random

button1 = st.button("Start")
if button1:
    random.seed(1)
    for i in range(100000000):
        random.random()
    st.write(random.random())

When we run them independently, the apps run as expected. But, when there is overlap or while the app is run on both sessions simultaneously, there is interference. This can be seen in the changed value of the write. Even Matplotlib library has a similar issue while trying to plot.

This is a workaround for the code discussed above such that even with overlapping computation or simultaneous run, the returned answer is identical.

import streamlit as st
import random

button1 = st.button("Start")
if button1:
    i=0
    for i in range(500000):
        random.seed(i)
        random.random()
    random.seed(i)
    st.write(random.random())

This workaround involves constant re-setting of the seed value. Please advise.

1 Like

An example for the interference with the Matplotlib library is as follows :

With two sessions opened, click on button 2 on one of the sessions and immediately click on button 1 in the other session.

import matplotlib.pyplot as plt
import streamlit as st
import time

one = st.button("1")
two = st.button("2")

if one:
    x = [0,1,2,3,4]
    y = x
    plt.title("Hello 1")
    plt.plot(x,y)
    st.pyplot(plt)

if two:
    plt.title("Hello 2")
    x = [0,1,2,3,4]
    y = x
    plt.plot(x,y)
    plt.title("Hello 1")
    
    time.sleep(5)

    x = [4,3,2,1,0]
    plt.plot(x,y)
    st.pyplot(plt)

Notice that while both buttons are pressed with overlap, the plot in button 2 changes.

Screenshots -

Running button 2 independently -

Running button 2 overlapping with running button 1 on another session -

1 Like

Hello @suryadheeshjith,

Quite interesting. Streamlit sessions run in different threads, and matplotlib seems to use the same plot stack across them. And in your example, the plot Hello 1 actually displays two overlapping lines.

Some solutions exist, for example this one which recommends to use subplots:

In the case of random, the library is not thread-safe:

Oh and apparently this is a known issue that is described in Streamlit docs (thank you @randyzwitch):

Yepp, using subplots worked out for us. We didn’t have to use matplotlib locks.

Thank you.