Fix glass bug with WritableDatabase cursors
commit40ebb71ef2ebe7581e7c508486cdf4e0b0a3e0f3
authorOlly Betts <olly@survex.com>
Wed, 11 Jul 2018 23:24:23 +0000 (12 11:24 +1200)
committerOlly Betts <olly@survex.com>
Wed, 11 Jul 2018 23:24:23 +0000 (12 11:24 +1200)
tree97acacae77c83f2ef1106ae43ce64fceda2c115b
parent0d69ecb660fb8ba63e2a6018291052e067b5985b
Fix glass bug with WritableDatabase cursors

A long-lived cursor on a table in a WritableDatabase could get into
an invalid state, which typically resulted in a DatabaseCorruptError
being thrown with the message:

    Db block overwritten - are there multiple writers?

But in fact the on-disk database is not corrupted - it's just that
the cursor in memory has got into an inconsistent state.  It looks
like we'll always detect the inconsistency before it can cause on-disk
corruption but it's hard to be complete certain.

The bug is in code to rebuild the cursor when the underlying table
changes in ways which require that.  That's a fairly rare occurrence
(with my C++ reproducer it happens 99 times out of 5000 commits).

In chert the equivalent code just marks the cursor's blocks as not yet
read, but in glass cursor blocks are reference counted and shared so we
can't simply do that as it could affect other cursors sharing the same
blocks.

So instead the glass code was leaving them with the contents they
previously had, except for copying the current root block from the
table's "built-in cursor".  After the rebuild we seek the cursor to the
same key it was on before, and that mostly works because we follow down
each level in the Btree from the new root, except it can happen that the
old cursor contained a block number which has since been released and
reallocated, and in that case the block doesn't get reread and we try to
use its old contents, which violates the rule that a parent can't be
younger than its child and causes the exception.

This commit fixes this by simply resetting the rebuilt cursor to match
the current "built-in cursor" at all levels (not just the root), which
is cheap because of the reference counting.

Reported with a reproducer by Sylvain Taverne.  Confirmed by David
Bremner as fixing a problem in notmuch without a reduced reproducer.
xapian-core/backends/glass/glass_cursor.cc