Several major/minor bug fixes

This is still very much a work in progress. Changes made have been to address specific bugs we've noticed running the code in production, but they are likely still broken in important ways.

See individual commits for details.