Cherry-pick the fix for TRQ-2369 into ascent. Some of the code here helps with TRQ-1539 and its better to import it than to reproduce it.