Everything above is remedial. It measures a page that is off the grid and pushes each block into place, and what you get back is a list of pixel corrections that describe one arrangement of line breaks. There is a better answer, and it does not ask you to change a single size.
Trim the boxes. Under text-box-trim: trim-both with text-box-edge: cap alphabetic, a block starts at its cap height and ends at its baseline, so the distance from one baseline to the next across a block boundary is
(lines − 1) × leading + space + cap
lines is the only term that changes with the viewport, and it is multiplied by a leading that is already a whole number of rows. So modulo the pitch what is left is space + cap, and every term in that belongs to one block by itself. Nothing relates one size to another. The sizes are free.
So a design keeps every size it asked for. The leading is snapped to the nearest whole number of rows, which is the one thing that moves and is the same thing InDesign moves when you tick the box. The space before each block is then solved to close that block's own cap height.