I have three fixes for this, not all directly related to your error, will merge them tomorrow when my coworker can have a look at it:
https://github.com/discourse/discourse/pull/6396
https://github.com/discourse/discourse/pull/6392
https://github.com/discourse/discourse/pull/6391