KeyError: 'st.session_state has no key "$$GENERATED_WIDGET_ID--None". Did you forget to initialize it? More info:

Summary

Unable to find where this key error is coming from. I don’t know which part of my code is producing the error.

Steps to reproduce

You can now view your Streamlit app in your browser.

Local URL: http://localhost:8503
Network URL: http://10.0.0.29:8503

2023-03-14 06:23:31.376 API queries_quota: 60
2023-03-14 06:23:35.301 Uncaught app exception
Traceback (most recent call last):
File “C:\Users\Ryan\anaconda3\envs\render\lib\site-packages\streamlit\runtime\state\session_state.py”, line 368, in getitem
return self._getitem(widget_id, key)
File “C:\Users\Ryan\anaconda3\envs\render\lib\site-packages\streamlit\runtime\state\session_state.py”, line 413, in _getitem
raise KeyError
KeyError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File “C:\Users\Ryan\anaconda3\envs\render\lib\site-packages\streamlit\runtime\scriptrunner\script_runner.py”, line 561, in _run_script
self._session_state.on_script_will_rerun(rerun_data.widget_states)
File “C:\Users\Ryan\anaconda3\envs\render\lib\site-packages\streamlit\runtime\state\safe_session_state.py”, line 68, in on_script_will_rerun
self._state.on_script_will_rerun(latest_widget_states)
File “C:\Users\Ryan\anaconda3\envs\render\lib\site-packages\streamlit\runtime\state\session_state.py”, line 472, in on_script_will_rerun
self._compact_state()
File “C:\Users\Ryan\anaconda3\envs\render\lib\site-packages\streamlit\runtime\state\session_state.py”, line 290, in _compact_state
self._old_state[key_or_wid] = self[key_or_wid]
File “C:\Users\Ryan\anaconda3\envs\render\lib\site-packages\streamlit\runtime\state\session_state.py”, line 370, in getitem
raise KeyError(_missing_key_error_message(key))
KeyError: ‘st.session_state has no key “$$GENERATED_WIDGET_ID-5c25878daf63004803a7aa172ece84aa-None”. Did you forget to initialize it? More info: Add statefulness to apps - Streamlit Docs

Expected behavior:

Explain what you expect to happen when you run the code above.

Actual behavior:

Explain the undesired behavior or error you see when you run the code above.
If you’re seeing an error message, share the full contents of the error message here.

Debug info

  • Streamlit version: (get it with $ streamlit version)
  • Python version: (get it with $ python --version)
  • Using Conda? PipEnv? PyEnv? Pex?
  • OS version:
  • Browser version:

Requirements file

Using Conda? PipEnv? PyEnv? Pex? Share the contents of your requirements file here.
Not sure what a requirements file is? Check out this doc and add a requirements file to your app.

Links

  • Link to your GitHub repo:
  • Link to your deployed app:

Additional information

If needed, add any other context about the problem here.

3 Likes

Hi @ryanshrott, welcome to the forum! Thanks for including all that info, but it’s not going to be possible to help debug your issue without actually seeing your code. Could you either share a link to your code, or share a small snippet of code which reproduces the issue?

Same issue here, I got an error today saying:
KeyError: 'st.session_state has no key "$$GENERATED_WIDGET_ID-7073a26a98df597ec168910028c90688-None". Did you forget to initialize it? More info: https://docs.streamlit.io/library/advanced-features/session-state#initialization'

I don’t have any widget like this, and I wonder what’s the issue there

Hi Blackary!

I just have a similar problem:
KeyError: 'st.session_state has no key "$$GENERATED_WIDGET_ID-7073a26a98df597ec168910028c90688-None". Did you forget to initialize it? More info: https://docs.streamlit.io/library/advanced-features/session-state#initialization'

I don’t have any key like this in session, and after refreshing the error disappears, I wonder any clue of why this happens?

Hi @Eva_S, I have the same request for you as for the original poster – it’s very difficult to debug an issues like this without a reproducible code snippet. Take a look at this post Using Streamlit: how to post a question in the Streamlit forum and then please share more details so that people on the forum know how to help answer your question.

I have deployed my streamlit app to aws ec2 instance and overall my streamlit app is working fine with no errors.
But if I leave my application open on a web page for a long time and my computer goes to sleep, then when I log in to the computer, I sometimes get the following error:
KeyError: ‘st.session_state has no key ‘$$GENERATED_WIDGET_ID-9ac853935eda43e455d26f699b8f0282-text_area_summary’. Did you forget to initialize it? More info: Add statefulness to apps - Streamlit Docs
Traceback:
File ‘/opt/Python-3.9.16/env/lib/python3.9/site-packages/streamlit/runtime/scriptrunner/script_runner.py’, line 561, in _run_script
self._session_state.on_script_will_rerun(rerun_data.widget_states)
File ‘/opt/Python-3.9.16/env/lib/python3.9/site-packages/streamlit/runtime/state/safe_session_state.py’, line 68, in on_script_will_rerun
self._state.on_script_will_rerun(latest_widget_states)
File ‘/opt/Python-3.9.16/env/lib/python3.9/site-packages/streamlit/runtime/state/session_state.py’, line 472, in on_script_will_rerun
self._compact_state()
File ‘/opt/Python-3.9.16/env/lib/python3.9/site-packages/streamlit/runtime/state/session_state.py’, line 290, in _compact_state
self._old_state[key_or_wid] = self[key_or_wid]
File ‘/opt/Python-3.9.16/env/lib/python3.9/site-packages/streamlit/runtime/state/session_state.py’, line 370, in getitem
raise KeyError(_missing_key_error_message(key))

What could be the reason for such an error?
Below is a snippet of my code.

from st_aggrid import AgGrid
from st_aggrid import GridOptionsBuilder, JsCode
import streamlit_authenticator as stauth
import pandas as pd
import streamlit as st
import constants
import RequestScraper
import MessageProc
import yaml

if 'text_area_summary' not in st.session_state:
  st.session_state['text_area_summary'] = ''

logo = constants.APP_LOGO_PATH

st.set_page_config(page_title="Argonauts",
                   page_icon=logo,
                   layout="wide"
                   )


## load hashed passwords
with open(constants.AUTHENTICATION_CONFIG_FILE_PATH) as file:
    config = yaml.load(file, Loader=yaml.SafeLoader)

authenticator = stauth.Authenticate(
    config['credentials'],
    config['cookie']['name'],
    config['cookie']['key'],
    config['cookie']['expiry_days'],
    config['preauthorized']
)
# --- USER AUTHENTICATION ---
name, authentication_status, username = authenticator.login("Login", "main")

if authentication_status == False:
    st.error('Username/password is incorrect')
if authentication_status == None:
    st.warning('Please enter your username and password')

if authentication_status:

    st.sidebar.markdown('<h1 style="text-align: center;">-- ARGONAUTS --</h1>', unsafe_allow_html=True)
    st.sidebar.image(logo, width=constants.IMAGE_LOGO_SIZE)

#  hidden part of my code...

# continues my code
with analyse_col:
        st.header("Analyse")
        with st.form(key='Analyse_channel_form'):
            analyse_table = AgGrid(analyse_data,
                                   gridOptions=go_analyse,
                                   height=constants.MESSAGE_TABLE_HEIGHT,
                                   width=constants.MESSAGE_TABLE_WIDTH,
                                   fit_columns_on_grid_load=True,
                                   # columns_auto_size_mode=ColumnsAutoSizeMode.FIT_CONTENTS,
                                   reload_data=True,
                                   allow_unsafe_jscode=True,
                                   key='analyse_table_key')

            col_del_all_button, col_del_sel_button = st.columns(2, gap='small')

            del_button_analyse = st.form_submit_button(label='Delete selected messages',
                                                       on_click=delete_analyse)

            st.text_area(label='Summary', key='text_area_summary')

            col_button, col_check_box = st.columns(2, gap='small')

            with col_button:
                submit_button_analyse = st.form_submit_button(label='Submit summary',
                                                              on_click=submit_analyse_messages_to_discord)
            with col_check_box:
                st.checkbox(label='Delete selected after submit', key='delete_selected_after_submit')

It looks like this issue might be related to the streamlit-authenticator component (I was helping someone today who is seeing the same error). @mkhorasani any chance you’ve seen this error before with the component?

Hey Caroline, honestly, this is the first time I have seen such an error message, and for the life of me, I can’t figure out what is causing it. With streamlit-authenticator, four variables are being saved to the session state as follows: ‘name’, ‘username’, ‘authentication_status’, and ‘logout’. These variable names are static and will never change. Aside from that there is no other interaction with the session state. Is it possible that some other library or code is causing this?

1 Like

Hey @mkhorasani, totally possible it’s another library. Thanks for looking into it!

1 Like

Hello colleagues! Do you have any other suggestions as to what might be causing this error? I could upload the whole code of my streamlit app if that helps.

1 Like

No, but this is still unresolved for me:(

I have created a dashboard with AgGrid, extra-streamlit-components (cookie manager) and streamlit-options-menu and I get the same error. If this relates to streamlit-authenticator for sure, then potentially this can be narrowed to the cookie manager specifically, as I occasionally get the same error message in my app despite not using the authenticator per se.

I am getting the same error. Also using streamlit-authenticator.
It seems to occur when the page is open in the background for longer periods of time.
Could it be that session_state expires after a certain amount of time?

1 Like

This is definitely related to the streamlit-authenticator. A barebone app with the authenticator and no other dependency, stopping and restarting streamlit keeping the old browser tab open is usually enough to show the error (note that since this seems correlated with browser tab it may have something to do with cookie management).

Like @dmitrkuzin I also observed this on an AWS deployment which would also suggest something to do with how streamlit handles reruns over time.

I don’t have enough understanding of streamlit’s code but maybe it could be possible to allow streamlit to not recover some keys on reruns and just ignore that instead of throwing an error? (e.g. rerun as if it was the first time)

PS: a workaround to catch exceptions thrown by ScriptRunner (?) would be nice; I tried to have the content of pages in a try/except but it looks like the ScriptRunner is called ahead of that which makes sense (but then I can’t filter these errors which pollute my cloudwatch logs even though the app works fine).

3 Likes

I’m not very experienced with the streamlit application framework and I received this error when deploying an app to Cloud Run. This thread was created at the beginning of March 2023, which means changes in streamlit or streamlit-authenticator that occured end of February or beginning of March 2023 might be the cause of the issue. There are no breaking changes in “streamlit-authenticator” since December 2022. Whereas in the “streamlit” repository there are more regular updates.
For me personally what it worked was the installation (downgrade to) of streamlit version 1.18.0 (streamlit==1.18.0) where experimentally the “@st.cache_resource()” was introduced (which I also include in my code).

3 Likes

Same as @lampros, using both streamlit and streamlit-authenticator, and using streamlit 1.18.0 fixes the problem (using the same version of streamlit-authenticator).

I also get a KeyError on ‘name’, which is being set in streamlit-authenticator, but again only with streamlit > 1.18.0.

I’m working on my first streamlit app, so I don’t know enough about how the code works to debug this, but there’s definately something wrong in there…

Hi @ ryanshrott
I believe the issue has to do with not initializing the session state elements before the authentication status is true.

so instead of doing

if authentication_status:
  if "cols" not in st.session_state:
      st.session_state.cols = "col1"

do this:

if "cols" not in st.session_state:
    st.session_state.cols = "col1"
if authentication_status:
   #do something else

that should solve it, hope that helps.

1 Like

Hey there!

I confirm this key error. Added some debug comments through the code. The error happens when importing streamlit_authenticator, as seen in the logs.

To raise the error, I did login, stopped the app and restarted it.

print('*** before streamlit import')

import streamlit as st

print('*** before streamlit_authenticator import')

import streamlit_authenticator as stauth

import yaml
from yaml.loader import SafeLoader

print('*** before yaml.load')

with open('config.yaml') as file:
    config = yaml.load(file, Loader=SafeLoader)

# hash passwords
users = config['credentials']['usernames']
for user in config['credentials']['usernames']:
    users[user]['password'] = stauth.Hasher([users[user]['password']]).generate()[0]

print('*** before stauth.Authenticate')

authenticator = stauth.Authenticate(
    config['credentials'],
    config['cookie']['name'],
    config['cookie']['key'],
    config['cookie']['expiry_days'],
    config['preauthorized']
)

print('*** before authenticator.login')

name, authentication_status, username = authenticator.login('Login', 'main')

print('*** after authenticator.login, name = ', name, ', authentication_status = ', authentication_status, ', username = ', username)

if authentication_status:
    authenticator.logout('Logout', 'main', key='unique_key')
    st.write(f'Welcome *{name}*')
    st.title('Some content')
elif authentication_status is False:
    st.error('Username/password is incorrect')
elif authentication_status is None:
    st.warning('Please enter your username and password')
streamlit run main.py 

  You can now view your Streamlit app in your browser.

  Local URL: http://localhost:8501
  Network URL: http://172.19.209.86:8501

*** before streamlit import
*** before streamlit_authenticator import
2023-05-24 17:56:56.384 Uncaught app exception
Traceback (most recent call last):
  File "/home/junior/dev/python/authenticator-example/venv/lib/python3.10/site-packages/streamlit/runtime/state/session_state.py", line 376, in __getitem__
    return self._getitem(widget_id, key)
  File "/home/junior/dev/python/authenticator-example/venv/lib/python3.10/site-packages/streamlit/runtime/state/session_state.py", line 421, in _getitem
    raise KeyError
KeyError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/junior/dev/python/authenticator-example/venv/lib/python3.10/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 561, in _run_script
    self._session_state.on_script_will_rerun(rerun_data.widget_states)
  File "/home/junior/dev/python/authenticator-example/venv/lib/python3.10/site-packages/streamlit/runtime/state/safe_session_state.py", line 68, in on_script_will_rerun
    self._state.on_script_will_rerun(latest_widget_states)
  File "/home/junior/dev/python/authenticator-example/venv/lib/python3.10/site-packages/streamlit/runtime/state/session_state.py", line 480, in on_script_will_rerun
    self._compact_state()
  File "/home/junior/dev/python/authenticator-example/venv/lib/python3.10/site-packages/streamlit/runtime/state/session_state.py", line 298, in _compact_state
    self._old_state[key_or_wid] = self[key_or_wid]
  File "/home/junior/dev/python/authenticator-example/venv/lib/python3.10/site-packages/streamlit/runtime/state/session_state.py", line 378, in __getitem__
    raise KeyError(_missing_key_error_message(key))
KeyError: 'st.session_state has no key "$$WIDGET_ID-1a8279410f90d35adda3725d5aedbfc0-init". Did you forget to initialize it? More info: https://docs.streamlit.io/library/advanced-features/session-state#initialization'
*** before yaml.load
*** before stauth.Authenticate
*** before streamlit import
*** before streamlit_authenticator import
*** before yaml.load
*** before stauth.Authenticate
*** before authenticator.login
*** after authenticator.login, name =  None , authentication_status =  None , username =  
*** before streamlit import
*** before streamlit_authenticator import
*** before yaml.load
*** before stauth.Authenticate
*** before authenticator.login
*** after authenticator.login, name =  Junior Vidotti , authentication_status =  True , username =  jrvidotti

I have the same issue. I also use streamlit_authenticator. on local run everything is fine, but when I deployed the app on digital-ocean I got the exact same error.

1 Like

@mkhorasani

I’ve tried to debug the source code, but couldn’t figure out what’s happening.

It’s in the inner works of Streamlit.