Move as much of the postprocessing logic as we can to c++, and soak with unit tests. Fix regressions in layer sorting introduced by a46f3e9, and missing feature counts. Fixes #61146