diff --git a/CHANGES.rst b/CHANGES.rst
index 218116b6..43d58729 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -5,6 +5,11 @@
 5.6.0 (unreleased)
 ==================
 
+- Fix race with invalidations when starting a new transaction. The bug
+  affected Storage implementations that rely on mvccadapter, and could result
+  in data corruption (oid loaded at wrong serial after a concurrent commit).
+  See `issue 290 <https://github.com/zopefoundation/ZODB/issues/290>`_.
+
 - Improve volatile attribute ``_v_`` documentation.
 
 - Make repozo's recover mode atomic by recovering the backup in a
diff --git a/src/ZODB/mvccadapter.py b/src/ZODB/mvccadapter.py
index 121e579b..c625c141 100644
--- a/src/ZODB/mvccadapter.py
+++ b/src/ZODB/mvccadapter.py
@@ -49,6 +49,7 @@ class MVCCAdapter(Base):
         instance = MVCCAdapterInstance(self)
         with self._lock:
             self._instances.add(instance)
+        instance._lastTransaction()
         return instance
 
     def before_instance(self, before=None):
@@ -77,13 +78,13 @@ class MVCCAdapter(Base):
     def invalidate(self, transaction_id, oids):
         with self._lock:
             for instance in self._instances:
-                instance._invalidate(oids)
+                instance._invalidate(transaction_id, oids)
 
-    def _invalidate_finish(self, oids, committing_instance):
+    def _invalidate_finish(self, tid, oids, committing_instance):
         with self._lock:
             for instance in self._instances:
                 if instance is not committing_instance:
-                    instance._invalidate(oids)
+                    instance._invalidate(tid, oids)
 
     references = serialize.referencesf
     transform_record_data = untransform_record_data = lambda self, data: data
@@ -98,14 +99,26 @@ class MVCCAdapterInstance(Base):
         'checkCurrentSerialInTransaction', 'tpc_abort',
         )
 
+    _start = None # Transaction start time
+    _ltid = None # Last storage transaction id
+
     def __init__(self, base):
         self._base = base
         Base.__init__(self, base._storage)
         self._lock = Lock()
         self._invalidations = set()
-        self._start = None # Transaction start time
         self._sync = getattr(self._storage, 'sync', lambda : None)
 
+    def _lastTransaction(self):
+        ltid = self._storage.lastTransaction()
+        # At this precise moment, a transaction may be
+        # committed and we have already received the new tid.
+        with self._lock:
+            # So make sure we won't override with a smaller value.
+            if self._ltid is None:
+                # Calling lastTransaction() here could result in a deadlock.
+                self._ltid = ltid
+
     def release(self):
         self._base._release(self)
 
@@ -115,8 +128,9 @@ class MVCCAdapterInstance(Base):
         with self._lock:
             self._invalidations = None
 
-    def _invalidate(self, oids):
+    def _invalidate(self, tid, oids):
         with self._lock:
+            self._ltid = tid
             try:
                 self._invalidations.update(oids)
             except AttributeError:
@@ -128,8 +142,8 @@ class MVCCAdapterInstance(Base):
             self._sync()
 
     def poll_invalidations(self):
-        self._start = p64(u64(self._storage.lastTransaction()) + 1)
         with self._lock:
+            self._start = p64(u64(self._ltid) + 1)
             if self._invalidations is None:
                 self._invalidations = set()
                 return None
@@ -175,7 +189,8 @@ class MVCCAdapterInstance(Base):
         self._modified = None
 
         def invalidate_finish(tid):
-            self._base._invalidate_finish(modified, self)
+            self._base._invalidate_finish(tid, modified, self)
+            self._ltid = tid
             func(tid)
 
         return self._storage.tpc_finish(transaction, invalidate_finish)
@@ -260,7 +275,7 @@ class UndoAdapterInstance(Base):
     def tpc_finish(self, transaction, func = lambda tid: None):
 
         def invalidate_finish(tid):
-            self._base._invalidate_finish(self._undone, None)
+            self._base._invalidate_finish(tid, self._undone, None)
             func(tid)
 
         self._storage.tpc_finish(transaction, invalidate_finish)

diff --git a/src/ZODB/FileStorage/tests.py b/src/ZODB/FileStorage/tests.py
index 64d08287..fb564d41 100644
--- a/src/ZODB/FileStorage/tests.py
+++ b/src/ZODB/FileStorage/tests.py
@@ -113,15 +113,15 @@ def pack_with_repeated_blob_records():
     fixed by the time you read this, but there might still be
     transactions in the wild that have duplicate records.
 
-    >>> fs = ZODB.FileStorage.FileStorage('t', blob_dir='bobs')
-    >>> db = ZODB.DB(fs)
+    >>> db = ZODB.DB(ZODB.FileStorage.FileStorage('t', blob_dir='bobs'))
     >>> conn = db.open()
     >>> conn.root()[1] = ZODB.blob.Blob()
     >>> transaction.commit()
     >>> tm = transaction.TransactionManager()
     >>> oid = conn.root()[1]._p_oid
-    >>> from ZODB.utils import load_current
-    >>> blob_record, oldserial = load_current(fs, oid)
+    >>> fs = db._mvcc_storage.new_instance()
+    >>> _ = fs.poll_invalidations()
+    >>> blob_record, oldserial = fs.load(oid)
 
     Now, create a transaction with multiple saves:
 
diff --git a/src/ZODB/tests/testConnection.py b/src/ZODB/tests/testConnection.py
index 88276b9c..2fe003eb 100644
--- a/src/ZODB/tests/testConnection.py
+++ b/src/ZODB/tests/testConnection.py
@@ -14,6 +14,7 @@
 """Unit tests for the Connection class."""
 from __future__ import print_function
 
+from contextlib import contextmanager
 import doctest
 import re
 import six
@@ -535,13 +536,13 @@ class InvalidationTests(unittest.TestCase):
 
         >>> mvcc_storage.invalidate(p64(1), {p1._p_oid: 1})
 
-        Transaction start times are based on storage's last
-        transaction. (Previousely, they were based on the first
-        invalidation seen in a transaction.)
+        Transaction start times are based on storage's last transaction,
+        which is known from invalidations. (Previousely, they were
+        based on the first invalidation seen in a transaction.)
 
         >>> mvcc_instance.poll_invalidations() == [p1._p_oid]
         True
-        >>> mvcc_instance._start == p64(u64(db.storage.lastTransaction()) + 1)
+        >>> mvcc_instance._start == p64(2)
         True
 
         >>> mvcc_storage.invalidate(p64(10), {p2._p_oid: 1, p64(76): 1})
@@ -570,6 +571,36 @@ class InvalidationTests(unittest.TestCase):
         >>> db.close()
         """
 
+    def test_mvccadapterNewTransactionVsInvalidations(self):
+        """
+        Check that polled invalidations are consistent with the TID at which
+        the transaction operates. Otherwise, it's like we miss invalidations.
+        """
+        db = databaseFromString("<zodb>\n<mappingstorage/>\n</zodb>")
+        try:
+            t1 = transaction.TransactionManager()
+            c1 = db.open(t1)
+            r1 = c1.root()
+            r1['a'] = 1
+            t1.commit()
+            t2 = transaction.TransactionManager()
+            c2 = db.open(t2)
+            c2.root()['b'] = 1
+            s1 = c1._storage
+            l1 = s1._lock
+            @contextmanager
+            def beforeLock1():
+                s1._lock = l1
+                t2.commit()
+                with l1:
+                    yield
+            s1._lock = beforeLock1()
+            t1.begin()
+            self.assertIs(s1._lock, l1)
+            self.assertIn('b', r1)
+        finally:
+            db.close()
+
 def doctest_invalidateCache():
     """The invalidateCache method invalidates a connection's cache.
 
@@ -1395,4 +1426,5 @@ def test_suite():
     s.addTest(doctest.DocTestSuite(checker=checker))
     s.addTest(unittest.makeSuite(TestConnection))
     s.addTest(unittest.makeSuite(EstimatedSizeTests))
+    s.addTest(unittest.makeSuite(InvalidationTests))
     return s
diff --git a/src/ZODB/tests/testmvcc.py b/src/ZODB/tests/testmvcc.py
index ff52af5c..4316e0e5 100644
--- a/src/ZODB/tests/testmvcc.py
+++ b/src/ZODB/tests/testmvcc.py
@@ -85,13 +85,14 @@ storage has seen.
 
 >>> cn = db.open()
 
->>> cn._storage._start == p64(u64(st.lastTransaction()) + 1)
+>>> ltid = u64(st.lastTransaction())
+>>> cn._storage._start == p64(ltid + 1)
 True
->>> cn.db()._mvcc_storage.invalidate(100, dict.fromkeys([1, 2]))
->>> cn._storage._start == p64(u64(st.lastTransaction()) + 1)
+>>> cn.db()._mvcc_storage.invalidate(p64(ltid+100), dict.fromkeys([1, 2]))
+>>> cn._storage._start == p64(ltid + 1)
 True
->>> cn.db()._mvcc_storage.invalidate(200, dict.fromkeys([1, 2]))
->>> cn._storage._start == p64(u64(st.lastTransaction()) + 1)
+>>> cn.db()._mvcc_storage.invalidate(p64(ltid+200), dict.fromkeys([1, 2]))
+>>> cn._storage._start == p64(ltid + 1)
 True
 
 A connection's high-water mark is set to the transaction id taken from
@@ -105,7 +106,7 @@ but that doesn't work unless an object is modified.  sync() will abort
 a transaction and process invalidations.
 
 >>> cn.sync()
->>> cn._storage._start == p64(u64(st.lastTransaction()) + 1)
+>>> cn._storage._start == p64(ltid + 201)
 True
 
 Basic functionality

Race in Connection.open() vs invalidations -> corrupt data
Hello up there,

For wendelin.core v2 I need a way to know at which particular database state application-level ZODB connection is viewing the database. I was looking for that in `Connection.open` / `MVCCAdapter` code and noticed concurrency bug that leads to wrong data returned by ZODB to application:

---- 8< ---- ([zopenrace.py](https://lab.nexedi.com/kirr/wendelin.core/blob/5fb60c76/zopenrace.py))
```py
#!/usr/bin/env python
"""Program zopenrace.py demonstrates concurrency bug in ZODB Connection.open()
that leads to stale live cache and wrong data provided by database to users.

The bug is that when a connection is opened, it syncs to storage and processes
invalidations received from the storage in two _separate_ steps, potentially
leading to situation where invalidations for transactions _past_ opened
connection's view of the database are included into opened connection's cache
invalidation. This leads to stale connection cache and old data provided by
ZODB.Connection when it is reopened next time.

That in turn can lead to loose of Consistency of the database if mix of current
and old data is used to process a transaction. A classic example would be bank
accounts A, B and C with A<-B and A<-C transfer transactions. If transaction
that handles A<-C sees stale data for A when starting its processing, it
results in A loosing what it should have received from B.

Below is timing diagram on how the bug happens on ZODB5:

    Client1 or Thread1                                  Client2 or Thread2

    # T1 begins transaction and opens zodb connection
    newTransaction():
        # implementation in Connection.py[1]
        ._storage.sync()
        invalidated = ._storage.poll_invalidations():
            # implementation in MVCCAdapterInstance [2]

            # T1 settles on as of which particular database state it will be
            # viewing the database.
            ._storage._start = ._storage._storage.lastTrasaction() + 1:
                s = ._storage._storage
                s._lock.acquire()
                head = s._ltid
                s._lock.release()
                return head
                                                        # T2 commits here.
                                                        # Time goes by and storage server sends
                                                        # corresponding invalidation message to T1,
                                                        # which T1 queues in its _storage._invalidations

            # T1 retrieves queued invalidations which _includes_
            # invalidation for transaction that T2 just has committed past @head.
            ._storage._lock.acquire()
                r = _storage._invalidations
            ._storage._lock.release()
            return r

        # T1 processes invalidations for [... head] _and_ invalidations for past-@head transaction.
        # T1 thus will _not_ process invalidations for that next transaction when
        # opening zconn _next_ time. The next opened zconn will thus see _stale_ data.
        ._cache.invalidate(invalidated)


The program simulates two clients: one (T2) constantly modifies two integer
objects preserving invariant that their values stay equal. The other client
(T1) constantly opens the database and verifies the invariant. T1 forces access
to one of the object to always go through loading from the database, and this
way if live cache becomes stale the bug is observed as invariant breakage.

Here is example failure:

    $ taskset -c 1,2 ./zopenrace.py
    Exception in thread Thread-1:
    Traceback (most recent call last):
      File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
        self.run()
      File "/usr/lib/python2.7/threading.py", line 754, in run
        self.__target(*self.__args, **self.__kwargs)
      File "./zopenrace.py", line 136, in T1
        t1()
      File "./zopenrace.py", line 130, in t1
        raise AssertionError("t1: obj1.i (%d)  !=  obj2.i (%d)" % (i1, i2))
    AssertionError: t1: obj1.i (147)  !=  obj2.i (146)

    Traceback (most recent call last):
      File "./zopenrace.py", line 179, in <module>
        main()
      File "./zopenrace.py", line 174, in main
        raise AssertionError('FAIL')
    AssertionError: FAIL

NOTE ZODB4 and ZODB3 do not have this particular open vs invalidation race.

[1] https://github.com/zopefoundation/ZODB/blob/5.5.1-29-g0b3db5aee/src/ZODB/Connection.py#L734-L742
[2] https://github.com/zopefoundation/ZODB/blob/5.5.1-29-g0b3db5aee/src/ZODB/mvccadapter.py#L130-L139
"""

from __future__ import print_function
from ZODB import DB
from ZODB.MappingStorage import MappingStorage
import transaction
from persistent import Persistent

# don't depend on pygolang
# ( but it is more easy and structured with sync.WorkGroup
#   https://pypi.org/project/pygolang/#concurrency )
#from golang import sync, context
import threading
def go(f, *argv, **kw):
    t = threading.Thread(target=f, args=argv, kwargs=kw)
    t.start()
    return t


# PInt is persistent integer.
class PInt(Persistent):
    def __init__(self, i):
        self.i = i


def main():
    zstor = MappingStorage()
    db = DB(zstor)


    # init initializes the database with two integer objects - obj1/obj2 that are set to 0.
    def init():
        transaction.begin()
        zconn = db.open()

        root = zconn.root()
        root['obj1'] = PInt(0)
        root['obj2'] = PInt(0)

        transaction.commit()
        zconn.close()


    okv = [False, False]

    # T1 accesses obj1/obj2 in a loop and verifies that obj1.i == obj2.i
    #
    # access to obj1 is organized to always trigger loading from zstor.
    # access to obj2 goes through zconn cache and so verifies whether the cache is not stale.
    def T1(N):
        def t1():
            transaction.begin()
            zconn = db.open()

            root = zconn.root()
            obj1 = root['obj1']
            obj2 = root['obj2']

            # obj1 - reload it from zstor
            # obj2 - get it from zconn cache
            obj1._p_invalidate()

            # both objects must have the same values
            i1 = obj1.i
            i2 = obj2.i
            if i1 != i2:
                raise AssertionError("T1: obj1.i (%d)  !=  obj2.i (%d)" % (i1, i2))

            transaction.abort() # we did not changed anything; also fails with commit
            zconn.close()

        for i in range(N):
            #print('T1.%d' % i)
            t1()
        okv[0] = True


    # T2 changes obj1/obj2 in a loop by doing `objX.i += 1`.
    #
    # Since both objects start from 0, the invariant that `obj1.i == obj2.i` is always preserved.
    def T2(N):
        def t2():
            transaction.begin()
            zconn = db.open()

            root = zconn.root()
            obj1 = root['obj1']
            obj2 = root['obj2']
            obj1.i += 1
            obj2.i += 1
            assert obj1.i == obj2.i

            transaction.commit()
            zconn.close()

        for i in range(N):
            #print('T2.%d' % i)
            t2()
        okv[1] = True


    # run T1 and T2 concurrently. As of 20191210, due to race condition in
    # Connection.open, it triggers the bug where T1 sees stale obj2 with obj1.i != obj2.i
    init()

    N = 1000
    t1 = go(T1, N)
    t2 = go(T2, N)
    t1.join()
    t2.join()

    if not all(okv):
        raise AssertionError('FAIL')
    print('OK')


if __name__ == '__main__':
    main()
```

Thanks beforehand,
Kirill

/cc @jimfulton 

P.S. It would be nice to provide `ZODB.Connection.at()` explicitly similarly to https://godoc.org/lab.nexedi.com/kirr/neo/go/zodb#Connection
src/ZODB/tests/testConnection.py::InvalidationTests::test_mvccadapterNewTransactionVsInvalidations
src/ZODB/FileStorage/tests.py::test_suite src/ZODB/tests/testConnection.py::ConnectionDotAdd::testCommit src/ZODB/tests/testConnection.py::ConnectionDotAdd::testModifyOnGetstate src/ZODB/tests/testConnection.py::ConnectionDotAdd::testResetOnAbort src/ZODB/tests/testConnection.py::ConnectionDotAdd::testResetOnTpcAbort src/ZODB/tests/testConnection.py::ConnectionDotAdd::testTpcAbortAfterCommit src/ZODB/tests/testConnection.py::ConnectionDotAdd::testUnusedAddWorks src/ZODB/tests/testConnection.py::ConnectionDotAdd::test__resetCacheResetsReader src/ZODB/tests/testConnection.py::ConnectionDotAdd::test_add src/ZODB/tests/testConnection.py::SetstateErrorLoggingTests::test_closed_connection_wont_setstate src/ZODB/tests/testConnection.py::EstimatedSizeTests::test_cache_garbage_collection src/ZODB/tests/testConnection.py::EstimatedSizeTests::test_cache_garbage_collection_shrinking_object src/ZODB/tests/testConnection.py::EstimatedSizeTests::test_configuration src/ZODB/tests/testConnection.py::EstimatedSizeTests::test_size_set_on_load src/ZODB/tests/testConnection.py::EstimatedSizeTests::test_size_set_on_write_commit src/ZODB/tests/testConnection.py::EstimatedSizeTests::test_size_set_on_write_savepoint src/ZODB/tests/testConnection.py::TestConnection::test_connection_interface src/ZODB/tests/testConnection.py::TestConnection::test_explicit_transactions_no_newTransactuon_on_afterCompletion src/ZODB/tests/testConnection.py::TestConnection::test_storage_afterCompletionCalled src/ZODB/tests/testConnection.py::test_suite src/ZODB/tests/testmvcc.py::test_suite