Manual backport of https://github.com/elastic/elasticsearch/pull/124312 and https://github.com/elastic/elasticsearch/pull/124742