Do an optimization/issue-correcting step during opening the database

Optimization step detects broken databases, so it lowers chances of agents
hanging forever or segfaulting inside libtokyocabinet.
(cherry picked from commit 85c165bd072a1c5a64c11faa7d1541f555226df5)
Don't provoke database corruption by mixing read/write and cursor operations
(cherry picked from commit 15176584a52ffa09bef437a04c2a07985753aea9)