A Raspberry Pi that behaves strangely is often short of power, and the cause is easy to miss. Raspberry Pi OS keeps a record of it.
vcgencmd get_throttled
vcgencmd measure_temp
The answer is a hexadecimal number. 0x0 means all clear. Otherwise each bit means something: bit 0 is under-voltage right now, bit 2 is throttling right now, and bits 16 and 18 mean under-voltage and throttling happened since boot. A value like 0x50005 therefore has both the current and the past problem set.
A power supply that cannot deliver enough, or a thin cable, is the usual reason. Fix that before you hunt for software causes.
Caveat: the flags reset at reboot, so run the command while the problem is happening or soon after.
Further reading: Raspberry Pi OS documentation