Subject: Re: bug#54028: Window is not a valid window

From: martin rudalics <[email-masked]>
Date: Sat, 19 Feb 2022 10:38:45 +0100

> Thanks, it doesn't fail anymore, but wasn't the problem
 > somewhere in the invalid window state?

No.  The sequence of events leading to the bug is the following:
'window-state-put' has

       ;; Work on the windows of a temporary buffer to make sure that
       ;; splitting proceeds regardless of any buffer local values of
       ;; `window-size-fixed'.  Release that buffer after the buffers of
       ;; all live windows have been set by `window--state-put-2'.
       (with-temp-buffer
	(set-window-buffer window (current-buffer))
	(window--state-put-1 state window nil totals pixelwise)
	(window--state-put-2 ignore pixelwise))

When this calls 'window--state-put-2', the window's buffer is *temp*.
'window--state-put-2' has:

	    ;; We don't want to raise an error in case the buffer does
	    ;; not exist anymore, so we switch to a previous one and
	    ;; save the window with the intention of deleting it later
	    ;; if possible.
	    (switch-to-prev-buffer window)
	    (push window window-state-put-stale-windows)))))))

Here, since window has no previous buffer, *temp* remains that window's
buffer.  Now *temp* gets killed when the 'with-temp-buffer' form exits
and, since its window is deletable, that window simply gets deleted via
‘kill-buffer’.  Back in 'window-state-put' we do

       (while window-state-put-stale-windows
         (let ((window (pop window-state-put-stale-windows)))
           (when (eq (window-deletable-p window) t)
	    (delete-window window))))

and here the window is no more valid because it has been deleted in
the meantime.

So AFAICT we start with a valid window state 'window-state-put' can't
handle.  I have no idea why this didn't hit us before.  Maybe, because
such windows usually have a previous buffer 'switch-to-prev-buffer' can
switch to.

 >> I have no idea whether the state is restored as intended, though.
 >
 > Is it possible to find what window was invalid in this window state?

There is none as I tried to explain above.  The question is rather
whether the restored state resembles the saved state satisfactorily.
But that only the OP can tell.

martin