Changestate couchdb connection fix

This pull request supersedes pull request #4892 and contains patches which fixes #4833 rebased into one commit

Cheers
Alex