selective backport of the bug fixes from pr #6863

selective backports of the bug fixes from pr #6863 which should fix #6729 on stable6

cc @DeepDiver1975 @PVince81 @karlitschek