Commit 8e7eab33 authored by Kirill Smelkov's avatar Kirill Smelkov

[ZODB4] Backport the way MVCC is handled from ZODB5

This backports to ZODB4 Connection ZODB5's approach to handle MVCC via
always calling storage.loadBefore() instead of "load for latest version
+ loadBefore if we were notified of database changes" approach.


Short answer: because Wendelin.core 2 needs to know at which particular
database state application-level ZODB connection is viewing the
database, and it is hard to implement such functionality correctly
without this backport. Please see appendix for the explanation.


This backports to ZODB4 the minimum necessary part of upstream commit 227953b9
(Simplify MVCC by determining transaction start time using lastTransaction) +
follow-up correctness fixes:

In short:

- a Connection is always opened with explicitly corresponding to a particular database revision
- Connection uses only loadBefore with that revision to load objects
- every time a Connection is (re)opened, the result of queued invalidations and
  explicit query to storage.lastTransaction is carefully merged to refresh
  Connection's idea about which database state it corresponds to.

The "careful" in last point is important. Historically ZODB5 was first reworked
in commit 227953b9 ( to always
call lastTransaction to refresh state of Connection view. Since there
was no proper synchronisation with respect to process of handling
invalidations, that lead to data corruption issue due to race in vs invalidations:

That race and data corruption was fixed in commit b5895a5c
( by way of avoiding
lastTransaction call and relying only on invalidations channel when
refreshing Connection view.

This fix in turn led to another data corruption issue because in
presence of client-server reconnections, ZODB storage drivers can partly
skip notifying client with detailed invalidation messages:

A fix to that issue (
proposed to change back to query storage for lastTransaction on every
Connection refresh, but to implement careful merging of lastTransaction
result and data from invalidation channel. However it was found that the
"careful merging" can work correctly only if we require from storage
drivers a particular ordering of invalidation events wrt lastTransaction
return and result:

While ZEO was already complying with that requirements, NEO had to be
fixed to support that:

Patch details

We change Connection._txn_time to be a "before" for the database state
to which Connection view corresponds. This state is hooked to be
initialized and updated in Connection._flush_invalidations - the
function that is called from both explicit Connection (re)open and at
transaction boundaries via Connection.afterCompletion hook.

Objects loading is factored into Connection._load which replaces old
"load + check invalidated + fallback to loadBefore" game in
Connection._setstate. now calls Connection._flush_invalidations
unconditionally - even if it was global cache reset event - because
besides invalidation flushes the latter is now responsible for querying
storage lastTransaction.

TmpStore - a "storage" that provides runtime support for savepoints - is
refactored correspondingly to delegate loading of original objects back
to underlying Connection.

DB.close is modified - similarly to ZODB5 - to release DB's Connections
carefully with preventing connections from DB poll from implicitly
starting new transactions via afterCompletion hook.

ZODB.nxd_patches is introduced to indicate to client software that this
particular patch is present and can be relied upon.

Tests are updated correspondingly. In 227953b9 Jim talks about
converting many tests - because

	"Lots of tests didn't clean up databases and connections properly"

and because new MVCC approach

	"makes database and connection hygiene a bit more important,
	especially for tests, because a connection will continue to interact
	with storages if it isn't properly closed, which can lead to errors if
	the storage is closed."

but finally implementing automatic cleanup at transaction boundaries
because there are too many tests to fix. We backport only automatic
cleanup + necessary explicit test fixes to keep the diff minimal.

All tests pass. This includes tests for ZODB itself, ZEO and NEO test
over hereby modified ZODB(*), my test programs from	and

and ERP5 tests. Upcoming wendelin.core 2 also work with this change.

(*) ZEO, NEO and ERP5 tests fail sometimes, but there is no regression
here because ZEO, NEO and ERP5 tests are failing regularly, and in the
same way, even with unmodified ZODB.

Appendix. zconn_at

This appendix provides motivation for the backport:

For wendelin.core v2 we need a way to know at which particular database
state application-level ZODB connection is viewing the database. Knowing
that state, WCFS client library interacts with WCFS filesystem server
and, in simple terms, requests the server to provide data as of that
particular database state. Let us call the function that for a client
ZODB connection returns database state corresponding to its database
view zconn_at.

Now here is the problem: zconn_at is relatively easy to implement for
ZODB5 - see e.g. here:

however, for ZODB4, since its operational models is not
directly MVCC, it is not that straightforward. Still, even for older
ZODB4, for every client connection, there _is_ such at that corresponds
to that connection view of the database.

We need ZODB4 support, because ZODB4 is currently the version that
Nexedi uses, and my understanding is that it will stay like this for not
a small time. I have the feeling that ZODB5 was reworked in better
direction, but without caring enough about quality which resulted in
concurrency bugs with data corruption effects like

Even though the first one is now fixed (but it broke other parts and so
both ZODB had to be fixed again _and_ NEO had to be fixed for that ZODB
fix to work currently), I feel that upgrading into ZODB5 for Nexedi will
require some non-negligible amount of QA work, and thus it is better if
we move step-by-step - even if we eventually upgrade to ZODB5 - it is
better we first migrate wendelin.core 1 -> wendelin.core 2 with keeping
current version of ZODB.

Now please note what would happen if zconn_at gives, even a bit, wrong
answer: wcfs client will ask wcfs server to provide array data as of
different database state compared to current on-client ZODB connection.
This will result in that data accessed via ZBigArray will _not_
correspond to all other data accessed via regular ZODB mechanism.
It is, in other words, a data corruptions.
In some scenarios it can be harmless, but generally it is the worst
that can happen to a database.

It is good to keep in mind ZODB issue290 when imagining corner cases
that zconn_at has to deal with. Even though that issue is ZODB5 only, it
shows what kind of bugs it can be in zconn_at implementation for ZODB4.

Just for the reference: in Wendelin-based systems there is usually constant
stream of database ingestions coming from many places simultaneously. Plus many
activities crunching on the DB at the same time as well. And the more clients a
system handles, the more there will be level-of-concurrency increase. This
means that the problem of correctly handling concurrency issues in zconn_at is
not purely theoretical, but has direct relation to our systems.


With this backport, zconn_at for ZODB4 becomes trivial and robust to implement:

I would like to thank Joshua Wölfel whose internship helped this topic
to shape up:

/cc @nexedi, @jwolf083Signed-off-by: Kirill Smelkov's avatarKirill Smelkov <>
parent 40116375
This diff is collapsed.
......@@ -626,12 +626,25 @@ class DB(object):
noop = lambda *a: None
self.close = noop
# go over all connections and prepare them to handle last txn.abort()
txn_managers = set() # of conn.transaction_manager
def _(c):
if c.transaction_manager is not None:
c.afterCompletion = c.newTransaction = c.close = noop
def _(conn):
if conn.transaction_manager is not None:
for c in six.itervalues(conn.connections):
# Prevent connections from implicitly starting new
# transactions.
c.afterCompletion = c.newTransaction = noop
conn.close = noop
# abort transaction managers for all above connections
# call txn.abort only after all connections are prepared, as else - if
# we call txn.abort() above - some connections could be not yet
# prepared and with still active afterCompletion callback.
for transaction_manager in txn_managers:
......@@ -26,3 +26,15 @@ sys.modules['ZODB.PersistentList'] = sys.modules['persistent.list']
del mapping, list, sys
from ZODB.DB import DB, connection
# set of changes backported by Nexedi.
nxd_patches = {
# Rework Connection MVCC implementation to always call
# storage.loadBefore(zconn._txn_time) to load objects.
# storage.load() is no longer called at all.
# ...
......@@ -776,5 +776,5 @@ def IExternalGC_suite(factory):
return doctest.DocFileSuite(
setUp=setup, tearDown=zope.testing.setupstack.tearDown,
setUp=setup, tearDown=ZODB.tests.util.tearDown,
......@@ -61,7 +61,7 @@ While it's boring, it's important to verify that the same relationships
hold if the default pool size is overridden.
>>> handler.clear()
>>> st.close()
>>> db.close()
>>> st = Storage()
>>> PS = 2 # smaller pool size
>>> db = DB(st, pool_size=PS)
......@@ -117,7 +117,7 @@ We can change the pool size on the fly:
Enough of that.
>>> handler.clear()
>>> st.close()
>>> db.close()
More interesting is the stack-like nature of connection reuse. So long as
we keep opening new connections, and keep them alive, all connections
......@@ -256,7 +256,7 @@ Nothing in that last block should have logged any msgs:
If "too many" connections are open, then closing one may kick an older
closed one out of the available connection stack.
>>> st.close()
>>> db.close()
>>> st = Storage()
>>> db = DB(st, pool_size=3)
>>> conns = [ for dummy in range(6)]
......@@ -324,7 +324,7 @@ gc to reclaim the Connection and its cache eventually works, but that can
take "a long time" and caches can hold on to many objects, and limited
resources (like RDB connections), for the duration.
>>> st.close()
>>> db.close()
>>> st = Storage()
>>> db = DB(st, pool_size=2)
>>> conn0 =
......@@ -22,7 +22,8 @@ import unittest
import transaction
import ZODB.tests.util
from ZODB.config import databaseFromString
from ZODB.utils import p64
from ZODB.utils import p64, u64, z64, newTid
from ZODB.POSException import ConflictError
from persistent import Persistent
from zope.interface.verify import verifyObject
from zope.testing import loggingsupport, renormalizing
......@@ -521,17 +522,18 @@ class InvalidationTests(unittest.TestCase):
Transaction ids are 8-byte strings, just like oids; p64() will
create one from an int.
>>> cn.invalidate(p64(1), {p1._p_oid: 1})
>>> cn._txn_time
>>> t = u64(cn._txn_time)
>>> cn.invalidate(p64(t+1), {p1._p_oid: 1})
>>> cn._txn_time == p64(t)
>>> p1._p_oid in cn._invalidated
>>> p2._p_oid in cn._invalidated
>>> cn.invalidate(p64(10), {p2._p_oid: 1, p64(76): 1})
>>> cn._txn_time
>>> cn.invalidate(p64(t+10), {p2._p_oid: 1, p64(76): 1})
>>> cn._txn_time == p64(t)
>>> p1._p_oid in cn._invalidated
>>> p2._p_oid in cn._invalidated
......@@ -586,51 +588,29 @@ def doctest_invalidateCache():
>>> connection.invalidateCache()
Now, if we try to load an object, we'll get a read conflict:
This won't have any effect until the next transaction:
>>> connection.root()['b'].x
Traceback (most recent call last):
ReadConflictError: database read conflict error
>>> connection.root()['a']._p_changed
>>> connection.root()['b']._p_changed
>>> connection.root()['c']._p_changed
If we try to commit the transaction, we'll get a conflict error:
But if we sync():
>>> tm.commit()
Traceback (most recent call last):
ConflictError: database conflict error
>>> connection.sync()
and the cache will have been cleared:
All of our data was invalidated:
>>> print(connection.root()['a']._p_changed)
>>> print(connection.root()['b']._p_changed)
>>> print(connection.root()['c']._p_changed)
>>> connection.root()['a']._p_changed
>>> connection.root()['b']._p_changed
>>> connection.root()['c']._p_changed
But we'll be able to access data again:
But we can load data as usual:
>>> connection.root()['b'].x
Aborting a transaction after a read conflict also lets us read data and go
on about our business:
>>> connection.invalidateCache()
>>> connection.root()['c'].x
Traceback (most recent call last):
ReadConflictError: database read conflict error
>>> tm.abort()
>>> connection.root()['c'].x
>>> connection.root()['c'].x = 2
>>> tm.commit()
>>> db.close()
......@@ -1244,12 +1224,16 @@ class StubStorage:
def __init__(self):
# internal
self._head = z64
self._stored = []
self._finished = []
self._data = {}
self._transdata = {}
self._transstored = []
def lastTransaction(self):
return self._head
def new_oid(self):
oid = str(self._oid)
self._oid += 1
......@@ -1283,7 +1267,11 @@ class StubStorage:
raise RuntimeError(
'StubStorage uses only one transaction at a time')
tid = newTid(None)
for oid,p in self._transdata.items():
self._data[oid] = (p, tid)
self._head = tid
del self._transaction
......@@ -1294,6 +1282,12 @@ class StubStorage:
raise TypeError('StubStorage does not support versions.')
return self._data[oid]
def loadBefore(self, oid, before):
if u64(before) != u64(self._head) + 1:
raise ValueError('noncurrent loadBefore not supported')
p, serial = self.load(oid)
return p, serial, None
def store(self, oid, serial, p, version, transaction):
if version != '':
raise TypeError('StubStorage does not support versions.')
......@@ -1302,9 +1296,12 @@ class StubStorage:
elif self._transaction != transaction:
raise RuntimeError(
'StubStorage uses only one transaction at a time')
serialOK = self._data.get(oid, z64)
if serial != serialOK:
raise ConflictError(oid=oid)
self._transdata[oid] = (p, serial)
self._transdata[oid] = p
# Explicitly returning None, as we're not pretending to be a ZEO
# storage
return None
......@@ -89,28 +89,33 @@ def test_invalidateCache():
>>> tm1.commit()
>>> tm2 = transaction.TransactionManager()
>>> c2 =
>>> c1.root()['a']._p_deactivate()
>>> c2.root()['a'].value
>>> tm3 = transaction.TransactionManager()
>>> c3 =
>>> c3.root()['a'].value
>>> c3.close()
>>> db.invalidateCache()
>>> c1.root.a._p_changed
>>> c1.sync()
>>> c1.root.a._p_changed
>>> c2.root.a._p_changed
>>> c2.sync()
>>> c2.root.a._p_changed
>>> c3 is
>>> c3.root.a._p_changed
>>> c1.root()['a'].value
Traceback (most recent call last):
ReadConflictError: database read conflict error
>>> c2.root()['a'].value
Traceback (most recent call last):
ReadConflictError: database read conflict error
>>> c3 is
>>> print(c3.root()['a']._p_changed)
>>> c3.root()['a'].value
>>> db.close()
......@@ -121,6 +121,9 @@ class MinimalMemoryStorage(BaseStorage, object):
end_tid = None
end_tid = tids[j]
self.hook(the_oid, self._cur[the_oid], '')
return self._index[(the_oid, tid)], tid, end_tid
def loadSerial(self, oid, serial):
......@@ -54,6 +54,8 @@ except NameError:
import io
file_type = io.BufferedReader
from . import util
def new_time():
"""Create a _new_ time stamp.
......@@ -548,10 +550,8 @@ def loadblob_tmpstore():
Now we open a database with a TmpStore in front:
>>> database.close()
>>> from ZODB.Connection import TmpStore
>>> tmpstore = TmpStore(blob_storage)
>>> tmpstore = TmpStore(connection)
We can access the blob correctly:
......@@ -757,7 +757,7 @@ def storage_reusable_suite(prefix, factory,
setUp=setup, tearDown=zope.testing.setupstack.tearDown,
setUp=setup, tearDown=util.tearDown,
# Py3k renders bytes where Python2 used native strings...
(re.compile(r"^b'"), "'"),
......@@ -780,10 +780,10 @@ def storage_reusable_suite(prefix, factory,
if test_packing:
setUp=setup, tearDown=zope.testing.setupstack.tearDown,
setUp=setup, tearDown=util.tearDown,
setUp=setup, tearDown=zope.testing.setupstack.tearDown,
setUp=setup, tearDown=util.tearDown,
checker = ZODB.tests.util.checker + \
(re.compile(r'\%(sep)s\%(sep)s' % dict(sep=os.path.sep)), '/'),
......@@ -823,7 +823,7 @@ def test_suite():
......@@ -831,7 +831,7 @@ def test_suite():
checker=ZODB.tests.util.checker +
(re.compile(r'\%(sep)s\%(sep)s' % dict(sep=os.path.sep)), '/'),
......@@ -33,9 +33,17 @@ This note includes doctests that explain how MVCC is implemented (and
test that the implementation is correct). The tests use a
MinimalMemoryStorage that implements MVCC support, but not much else.
***IMPORTANT***: The MVCC approach has changed since these tests were
originally written. The new approach is much simpler because we no
longer call load to get the current state of an object. We call
loadBefore instead, having gotten a transaction time at the start of a
transaction. As a result, the rhythm of the tests is a little odd,
because we no longer need to probe a complex dance that doesn't exist any more.
>>> from ZODB.tests.test_storage import MinimalMemoryStorage
>>> from ZODB import DB
>>> db = DB(MinimalMemoryStorage())
>>> st = MinimalMemoryStorage()
>>> db = DB(st)
We will use two different connections with different transaction managers
to make sure that the connections act independently, even though they'll
......@@ -59,6 +67,10 @@ Now open a second connection.
>>> tm2 = transaction.TransactionManager()
>>> cn2 =
>>> from ZODB.utils import p64, u64
>>> cn2._txn_time == p64(u64(st.lastTransaction()) + 1)
>>> txn_time2 = cn2._txn_time
Connection high-water mark
......@@ -67,22 +79,20 @@ The ZODB Connection tracks a transaction high-water mark, which
bounds the latest transaction id that can be read by the current
transaction and still present a consistent view of the database.
Transactions with ids up to but not including the high-water mark
are OK to read. When a transaction commits, the database sends
invalidations to all the other connections; the invalidation contains
the transaction id and the oids of modified objects. The Connection
stores the high-water mark in _txn_time, which is set to None until
an invalidation arrives.
are OK to read. At the beginning of a transaction, a connection
sets the high-water mark to just over the last transaction time the
storage has seen.
>>> cn =
>>> print(cn._txn_time)
>>> cn.invalidate(100, dict.fromkeys([1, 2]))
>>> cn._txn_time
>>> cn.invalidate(200, dict.fromkeys([1, 2]))
>>> cn._txn_time
>>> cn._txn_time == p64(u64(st.lastTransaction()) + 1)
>>> cn.db().invalidate(p64(100), dict.fromkeys([1, 2]))
>>> cn._txn_time == p64(u64(st.lastTransaction()) + 1)
>>> cn.db().invalidate(p64(200), dict.fromkeys([1, 2]))
>>> cn._txn_time == p64(u64(st.lastTransaction()) + 1)
A connection's high-water mark is set to the transaction id taken from
the first invalidation processed by the connection. Transaction ids are
......@@ -95,8 +105,8 @@ but that doesn't work unless an object is modified. sync() will abort
a transaction and process invalidations.
>>> cn.sync()
>>> print(cn._txn_time) # the high-water mark got reset to None
>>> cn._txn_time == p64(u64(st.lastTransaction()) + 1)
Basic functionality
......@@ -109,9 +119,9 @@ will modify "a." The other transaction will then modify "b" and commit.
>>> tm1.get().commit()
>>> txn = db.lastTransaction()
The second connection has its high-water mark set now.
The second connection already has its high-water mark set.
>>> cn2._txn_time == txn
>>> cn2._txn_time == txn_time2
It is safe to read "b," because it was not modified by the concurrent
......@@ -153,22 +163,23 @@ ConflictError: database conflict error (oid 0x01, class ZODB.tests.MinPO.MinPO)
This example will demonstrate that we can commit a transaction if we only
modify current revisions.
>>> print(cn2._txn_time)
>>> cn2._txn_time == p64(u64(st.lastTransaction()) + 1)
>>> txn_time2 = cn2._txn_time
>>> r1 = cn1.root()
>>> r1["a"].value = 3
>>> tm1.get().commit()
>>> txn = db.lastTransaction()
>>> cn2._txn_time == txn
>>> cn2._txn_time == txn_time2
>>> r2["b"].value = r2["a"].value + 1
>>> r2["b"].value
>>> tm2.get().commit()
>>> print(cn2._txn_time)
>>> cn2._txn_time == p64(u64(st.lastTransaction()) + 1)
Object cache
......@@ -302,22 +313,18 @@ same things now.
>>> r2["a"].value, r2["b"].value
(42, 43)
>>> db.close()
Late invalidation
The combination of ZEO and MVCC adds more complexity. Since
invalidations are delivered asynchronously by ZEO, it is possible for
an invalidation to arrive just after a request to load the invalidated
object is sent. The connection can't use the just-loaded data,
because the invalidation arrived first. The complexity for MVCC is
that it must check for invalidated objects after it has loaded them,
just in case.
The combination of ZEO and MVCC used to add more complexity. That's
why ZODB no-longer calls load. :)
Rather than add all the complexity of ZEO to these tests, the
MinimalMemoryStorage has a hook. We'll write a subclass that will
deliver an invalidation when it loads an object. The hook allows us
to test the Connection code.
deliver an invalidation when it loads (or loadBefore's) an object.
The hook allows us to test the Connection code.
>>> class TestStorage(MinimalMemoryStorage):
... def __init__(self):
......@@ -351,6 +358,12 @@ non-current revision to load.
>>> oid = r1["b"]._p_oid
>>> ts.hooked[oid] = 1
This test is kinda screwy because it depends on an old approach that
has changed. We'll hack the _txn_time to get the original expected
result, even though what's going on now is much simpler.
>>> cn1._txn_time = ts.lastTransaction()
Once the oid is hooked, an invalidation will be delivered the next
time it is activated. The code below activates the object, then
confirms that the hook worked and that the old state was retrieved.
......@@ -395,14 +408,12 @@ section above, this is no older state to retrieve.
>>> r1["b"]._p_state
>>> r1["b"]._p_activate()
>>> cn1._txn_time = st.lastTransaction()
>>> r1["b"]._p_activate() # doctest: +ELLIPSIS
Traceback (most recent call last):
ReadConflictError: database read conflict error (oid 0x02, class ZODB.tests.MinPO.MinPO)
>>> oid in cn1._invalidated
>>> ts.count
ReadConflictError: ...
import doctest
import re
......@@ -61,6 +61,7 @@ checker = renormalizing.RENormalizing([
def setUp(test, name='test'):
d = tempfile.mkdtemp(prefix=name)
zope.testing.setupstack.register(test, zope.testing.setupstack.rmtree, d)
......@@ -71,7 +72,9 @@ def setUp(test, name='test'):
zope.testing.setupstack.register(test, transaction.abort)
tearDown = zope.testing.setupstack.tearDown
def tearDown(test):
class TestCase(unittest.TestCase):
......@@ -186,3 +189,18 @@ def mess_with_time(test=None, globs=None, now=1278864701.5):
time.time = staticmethod(faux_time) # jython
time.time = faux_time
def clear_transaction_syncs():
"""Clear data managers registered with the global transaction manager
Many tests don't clean up synchronizer's registered with the
global transaction managers, which can wreak havoc with following
tests, now that connections interact with their storages at
transaction boundaries. We need to make sure that we clear any
registered data managers.
For now, we'll use the transaction manager's
underware. Eventually, an transaction managers need to grow an API
for this.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment