Changing window size to constant aspect ratio doesn't work

Godot Version

4.2.1 stable

Question

I don’t like the way “viewport” and “expand”/“keep” work with sprites in my game, so I want to create my own function to resize window with the change of scale and constant aspect ratio. I created the following function, connected by get_window().size_changed.connect(_window_size_changed):

var prevWindowSize: Vector2i
var aspectRatio: float = 16.0/9

func _ready():
	prevWindowSize = get_window().size
	get_window().size_changed.connect(_window_size_changed)
	load_position(savePath)

func _window_size_changed():
	print("oldSize: ", prevWindowSize)
	print("newSize: ", get_window().size)
	if (get_window().size.x != prevWindowSize.x):
		get_window().size.y = get_window().size.x / aspectRatio
	elif (get_window().size.y != prevWindowSize.y):
		print("2 ", prevWindowSize, get_window().size)
		get_window().size.x = get_window().size.y * aspectRatio
	var dX = float(get_window().size.x) / prevWindowSize.x
	scale = Vector2(dX, dX)
	prevWindowSize = get_window().size

Here is console log:

...
oldSize: (1471, 827)
newSize: (1473, 720)
oldSize: (1471, 827)
newSize: (1473, 828)
oldSize: (1473, 828)
newSize: (1476, 720)
oldSize: (1473, 828)
newSize: (1476, 830)
oldSize: (1476, 830)
newSize: (1476, 720)
2 (1476, 830)(1476, 720)
oldSize: (1476, 830)
newSize: (1280, 720)

It seems that every time I drag a window, for example expanding it by the right border, it changes Y as I coded, but when I release the border (or in some random moments as you can see from log), Y becomes 720 (I use 1280x720 resolution). What can I do to prevent this strange behaviour?

Please note, that size and size_changed depend on the size of the viewport and not the size of the window. This issue is currently discussed here: Notify users about window size changes · Issue #8788 · godotengine/godot-proposals · GitHub