I don't understand why `st.text_input` behaves weird as in my example

See code sample. It has to implementations. Impl #1 works as expected. Impl #2 behaves weird, and I don’t understand, why sometimes default value overrides value in state and sometimes doesn’t override.


import streamlit as st
st.write("Scenario.")
st.write("* Write 10, press 'ENTER' => value should change to 10")
st.write("* Write 20, press 'ENTER' => value should change to 20, but actually is changed back to 10")
st.write("* Write 20, press 'ENTER' => expect behaviour as before, but now value is 20 and not changed to 10")
st.write("* Write 30, press 'ENTER' => value again changed back to 20")

st.session_state.setdefault("ui", 0)
st.write(f"BEFORE: [actual] = {st.session_state.get('k1', 'N/A')} [default] = {st.session_state.ui}", )
# -----

# [Impl #1] This works as expected, after change - no roll backs
# st.session_state.setdefault("k1", "0")
# new_value = st.text_input("F1", key="k1")

# [Impl #2] This works weird, see scenario..
new_value = st.text_input("F1", st.session_state.ui, key="k1")

# -----
st.write(f"AFTER: [new_value] = {new_value}, [state] = {st.session_state.get('k1', 'N/A')}")
st.session_state.ui = new_value

I understand, that there could be some workarounds using ‘on_change’ handler. But at first I’d like to understand why for the impl #2 default value is not applied each time. I assume some consistent behaviour: a) default value is used only if comp key is missing in cache b) default value is used every tiem. But here I see some mixture of a) and b)