The clear loop is right to skip anything that isn't closing, but sudo is on the wrong side of the pipe. stdin is the session list, so the password prompt consumes the next IDs, or sudo fails once the timestamp expires, and the closing count stays put. Pull the IDs out first, then call sudo loginctl terminate-session from a for-loop whose stdin is still the tty.
KillUserProcesses=no is the other half. A leftover sftp-server or a backgrounded job is enough to pin the session in closing, which is what walks you into the 8192 cap. Setting it to yes reaps those at logout, and it also takes tmux and nohup with them unless they were started under a lingering user manager. That tradeoff is why the Ubuntu default stays no and a sweep of closing sessions is the safer fix.