...

Text file src/go.mongodb.org/mongo-driver/testdata/transactions/README.rst

Documentation: go.mongodb.org/mongo-driver/testdata/transactions

     1==================
     2Transactions Tests
     3==================
     4
     5.. contents::
     6
     7----
     8
     9Introduction
    10============
    11
    12The YAML and JSON files in the ``legacy`` and ``unified`` sub-directories are
    13platform-independent tests that drivers can use to prove their conformance to
    14the Transactions Spec. The tests in the ``legacy`` directory are designed with
    15the intention of sharing some test-runner code with the CRUD Spec tests and the
    16Command Monitoring Spec tests. The format for these tests and instructions for
    17executing them are provided in the following sections. Tests in the
    18``unified`` directory are written using the `Unified Test Format
    19<../../unified-test-format/unified-test-format.rst>`_.
    20
    21Several prose tests, which are not easily expressed in YAML, are also presented
    22in this file. Those tests will need to be manually implemented by each driver.
    23
    24Server Fail Point
    25=================
    26
    27failCommand
    28```````````
    29
    30Some tests depend on a server fail point, expressed in the ``failPoint`` field.
    31For example the ``failCommand`` fail point allows the client to force the
    32server to return an error. Keep in mind that the fail point only triggers for
    33commands listed in the "failCommands" field. See `SERVER-35004`_ and
    34`SERVER-35083`_ for more information.
    35
    36.. _SERVER-35004: https://jira.mongodb.org/browse/SERVER-35004
    37.. _SERVER-35083: https://jira.mongodb.org/browse/SERVER-35083
    38
    39The ``failCommand`` fail point may be configured like so::
    40
    41    db.adminCommand({
    42        configureFailPoint: "failCommand",
    43        mode: <string|document>,
    44        data: {
    45          failCommands: ["commandName", "commandName2"],
    46          closeConnection: <true|false>,
    47          errorCode: <Number>,
    48          writeConcernError: <document>,
    49          appName: <string>,
    50          blockConnection: <true|false>,
    51          blockTimeMS: <Number>,
    52        }
    53    });
    54
    55``mode`` is a generic fail point option and may be assigned a string or document
    56value. The string values ``"alwaysOn"`` and ``"off"`` may be used to enable or
    57disable the fail point, respectively. A document may be used to specify either
    58``times`` or ``skip``, which are mutually exclusive:
    59
    60- ``{ times: <integer> }`` may be used to limit the number of times the fail
    61  point may trigger before transitioning to ``"off"``.
    62- ``{ skip: <integer> }`` may be used to defer the first trigger of a fail
    63  point, after which it will transition to ``"alwaysOn"``.
    64
    65The ``data`` option is a document that may be used to specify options that
    66control the fail point's behavior. ``failCommand`` supports the following
    67``data`` options, which may be combined if desired:
    68
    69- ``failCommands``: Required, the list of command names to fail.
    70- ``closeConnection``: Boolean option, which defaults to ``false``. If
    71  ``true``, the command will not be executed, the connection will be closed, and
    72  the client will see a network error.
    73- ``errorCode``: Integer option, which is unset by default. If set, the command
    74  will not be executed and the specified command error code will be returned as
    75  a command error.
    76- ``appName``: A string to filter which MongoClient should be affected by
    77  the failpoint. `New in mongod 4.4.0-rc2 <https://jira.mongodb.org/browse/SERVER-47195>`_.
    78- ``blockConnection``: Whether the server should block the affected commands.
    79  Default false.
    80- ``blockTimeMS``: The number of milliseconds the affect commands should be
    81  blocked for. Required when blockConnection is true.
    82  `New in mongod 4.3.4 <https://jira.mongodb.org/browse/SERVER-41070>`_.
    83
    84Speeding Up Tests
    85=================
    86
    87See `Speeding Up Tests <../../retryable-reads/tests/README.rst#speeding-up-tests>`_ in the retryable reads spec tests.
    88
    89Test Format
    90===========
    91
    92Each YAML file has the following keys:
    93
    94- ``runOn`` (optional): An array of server version and/or topology requirements
    95  for which the tests can be run. If the test environment satisfies one or more
    96  of these requirements, the tests may be executed; otherwise, this file should
    97  be skipped. If this field is omitted, the tests can be assumed to have no
    98  particular requirements and should be executed. Each element will have some or
    99  all of the following fields:
   100
   101  - ``minServerVersion`` (optional): The minimum server version (inclusive)
   102    required to successfully run the tests. If this field is omitted, it should
   103    be assumed that there is no lower bound on the required server version.
   104
   105  - ``maxServerVersion`` (optional): The maximum server version (inclusive)
   106    against which the tests can be run successfully. If this field is omitted,
   107    it should be assumed that there is no upper bound on the required server
   108    version.
   109
   110  - ``topology`` (optional): An array of server topologies against which the
   111    tests can be run successfully. Valid topologies are "single", "replicaset",
   112    and "sharded". If this field is omitted, the default is all topologies (i.e.
   113    ``["single", "replicaset", "sharded"]``).
   114
   115  - ``serverless``: Optional string. Whether or not the test should be run on
   116    serverless instances imitating sharded clusters. Valid values are "require",
   117    "forbid", and "allow". If "require", the test MUST only be run on serverless
   118    instances. If "forbid", the test MUST NOT be run on serverless instances. If
   119    omitted or "allow", this option has no effect.
   120
   121    The test runner MUST be informed whether or not serverless is being used in
   122    order to determine if this requirement is met (e.g. through an environment
   123    variable or configuration option). Since the serverless proxy imitates a
   124    mongos, the runner is not capable of determining this by issuing a server
   125    command such as ``buildInfo`` or ``hello``.
   126
   127- ``database_name`` and ``collection_name``: The database and collection to use
   128  for testing.
   129
   130- ``data``: The data that should exist in the collection under test before each
   131  test run.
   132
   133- ``tests``: An array of tests that are to be run independently of each other.
   134  Each test will have some or all of the following fields:
   135
   136  - ``description``: The name of the test.
   137
   138  - ``skipReason``: Optional, string describing why this test should be
   139    skipped.
   140
   141  - ``useMultipleMongoses`` (optional): If ``true``, the MongoClient for this
   142    test should be initialized with multiple mongos seed addresses. If ``false``
   143    or omitted, only a single mongos address should be specified. This field has
   144    no effect for non-sharded topologies.
   145
   146  - ``clientOptions``: Optional, parameters to pass to MongoClient().
   147
   148  - ``failPoint``: Optional, a server failpoint to enable expressed as the
   149    configureFailPoint command to run on the admin database. This option and
   150    ``useMultipleMongoses: true`` are mutually exclusive.
   151
   152  - ``sessionOptions``: Optional, map of session names (e.g. "session0") to
   153    parameters to pass to MongoClient.startSession() when creating that session.
   154
   155  - ``operations``: Array of documents, each describing an operation to be
   156    executed. Each document has the following fields:
   157
   158    - ``name``: The name of the operation on ``object``.
   159
   160    - ``object``: The name of the object to perform the operation on. Can be
   161      "database", "collection", "session0", "session1", or "testRunner". See
   162      the "targetedFailPoint" operation in `Special Test Operations`_.
   163
   164    - ``collectionOptions``: Optional, parameters to pass to the Collection()
   165      used for this operation.
   166
   167    - ``databaseOptions``: Optional, parameters to pass to the Database()
   168      used for this operation.
   169
   170    - ``command_name``: Present only when ``name`` is "runCommand". The name
   171      of the command to run. Required for languages that are unable preserve
   172      the order keys in the "command" argument when parsing JSON/YAML.
   173
   174    - ``arguments``: Optional, the names and values of arguments.
   175
   176    - ``error``: Optional. If true, the test should expect an error or
   177      exception. This could be a server-generated or a driver-generated error.
   178
   179    - ``result``: The return value from the operation, if any. This field may
   180      be a single document or an array of documents in the case of a
   181      multi-document read. If the operation is expected to return an error, the
   182      ``result`` is a single document that has one or more of the following
   183      fields:
   184
   185      - ``errorContains``: A substring of the expected error message.
   186
   187      - ``errorCodeName``: The expected "codeName" field in the server
   188        error response.
   189
   190      - ``errorLabelsContain``: A list of error label strings that the
   191        error is expected to have.
   192
   193      - ``errorLabelsOmit``: A list of error label strings that the
   194        error is expected not to have.
   195
   196  - ``expectations``: Optional list of command-started events.
   197
   198  - ``outcome``: Document describing the return value and/or expected state of
   199    the collection after the operation is executed. Contains the following
   200    fields:
   201
   202    - ``collection``:
   203
   204      - ``data``: The data that should exist in the collection after the
   205        operations have run, sorted by "_id".
   206
   207Use as Integration Tests
   208========================
   209
   210Run a MongoDB replica set with a primary, a secondary, and an arbiter,
   211**server version 4.0.0 or later**. (Including a secondary ensures that
   212server selection in a transaction works properly. Including an arbiter helps
   213ensure that no new bugs have been introduced related to arbiters.)
   214
   215A driver that implements support for sharded transactions MUST also run these
   216tests against a MongoDB sharded cluster with multiple mongoses and
   217**server version 4.2 or later**. Some tests require
   218initializing the MongoClient with multiple mongos seeds to ensures that mongos
   219transaction pinning and the recoveryToken works properly.
   220
   221Load each YAML (or JSON) file using a Canonical Extended JSON parser.
   222
   223Then for each element in ``tests``:
   224
   225#. If the ``skipReason`` field is present, skip this test completely.
   226#. Create a MongoClient and call
   227   ``client.admin.runCommand({killAllSessions: []})`` to clean up any open
   228   transactions from previous test failures. Ignore a command failure with
   229   error code 11601 ("Interrupted") to work around `SERVER-38335`_.
   230
   231   - Running ``killAllSessions`` cleans up any open transactions from
   232     a previously failed test to prevent the current test from blocking.
   233     It is sufficient to run this command once before starting the test suite
   234     and once after each failed test.
   235   - When testing against a sharded cluster run this command on ALL mongoses.
   236
   237#. Create a collection object from the MongoClient, using the ``database_name``
   238   and ``collection_name`` fields of the YAML file.
   239#. Drop the test collection, using writeConcern "majority".
   240#. Execute the "create" command to recreate the collection, using writeConcern
   241   "majority". (Creating the collection inside a transaction is prohibited, so
   242   create it explicitly.)
   243#. If the YAML file contains a ``data`` array, insert the documents in ``data``
   244   into the test collection, using writeConcern "majority".
   245#. When testing against a sharded cluster run a ``distinct`` command on the
   246   newly created collection on all mongoses. For an explanation see,
   247   `Why do tests that run distinct sometimes fail with StaleDbVersion?`_
   248#. If ``failPoint`` is specified, its value is a configureFailPoint command.
   249   Run the command on the admin database to enable the fail point.
   250#. Create a **new** MongoClient ``client``, with Command Monitoring listeners
   251   enabled. (Using a new MongoClient for each test ensures a fresh session pool
   252   that hasn't executed any transactions previously, so the tests can assert
   253   actual txnNumbers, starting from 1.) Pass this test's ``clientOptions`` if
   254   present.
   255
   256   - When testing against a sharded cluster and ``useMultipleMongoses`` is
   257     ``true`` the client MUST be created with multiple (valid) mongos seed
   258     addresses.
   259
   260#. Call ``client.startSession`` twice to create ClientSession objects
   261   ``session0`` and ``session1``, using the test's "sessionOptions" if they
   262   are present. Save their lsids so they are available after calling
   263   ``endSession``, see `Logical Session Id`_.
   264#. For each element in ``operations``:
   265
   266   - If the operation ``name`` is a special test operation type, execute it and
   267     go to the next operation, otherwise proceed to the next step.
   268   - Enter a "try" block or your programming language's closest equivalent.
   269   - Create a Database object from the MongoClient, using the ``database_name``
   270     field at the top level of the test file.
   271   - Create a Collection object from the Database, using the
   272     ``collection_name`` field at the top level of the test file.
   273     If ``collectionOptions`` or ``databaseOptions`` is present, create the
   274     Collection or Database object with the provided options, respectively.
   275     Otherwise create the object with the default options.
   276   - Execute the named method on the provided ``object``, passing the
   277     arguments listed. Pass ``session0`` or ``session1`` to the method,
   278     depending on which session's name is in the arguments list.
   279     If ``arguments`` contains no "session", pass no explicit session to the
   280     method.
   281   - If the driver throws an exception / returns an error while executing this
   282     series of operations, store the error message and server error code.
   283   - If the operation's ``error`` field is ``true``, verify that the method
   284     threw an exception or returned an error.
   285   - If the result document has an "errorContains" field, verify that the
   286     method threw an exception or returned an error, and that the value of the
   287     "errorContains" field matches the error string. "errorContains" is a
   288     substring (case-insensitive) of the actual error message.
   289
   290     If the result document has an "errorCodeName" field, verify that the
   291     method threw a command failed exception or returned an error, and that
   292     the value of the "errorCodeName" field matches the "codeName" in the
   293     server error response.
   294
   295     If the result document has an "errorLabelsContain" field, verify that the
   296     method threw an exception or returned an error. Verify that all of the
   297     error labels in "errorLabelsContain" are present in the error or exception
   298     using the ``hasErrorLabel`` method.
   299
   300     If the result document has an "errorLabelsOmit" field, verify that the
   301     method threw an exception or returned an error. Verify that none of the
   302     error labels in "errorLabelsOmit" are present in the error or exception
   303     using the ``hasErrorLabel`` method.
   304   - If the operation returns a raw command response, eg from ``runCommand``,
   305     then compare only the fields present in the expected result document.
   306     Otherwise, compare the method's return value to ``result`` using the same
   307     logic as the CRUD Spec Tests runner.
   308
   309#. Call ``session0.endSession()`` and ``session1.endSession``.
   310#. If the test includes a list of command-started events in ``expectations``,
   311   compare them to the actual command-started events using the
   312   same logic as the Command Monitoring Spec Tests runner, plus the rules in
   313   the Command-Started Events instructions below.
   314#. If ``failPoint`` is specified, disable the fail point to avoid spurious
   315   failures in subsequent tests. The fail point may be disabled like so::
   316
   317    db.adminCommand({
   318        configureFailPoint: <fail point name>,
   319        mode: "off"
   320    });
   321
   322#. For each element in ``outcome``:
   323
   324   - If ``name`` is "collection", verify that the test collection contains
   325     exactly the documents in the ``data`` array. Ensure this find reads the
   326     latest data by using **primary read preference** with
   327     **local read concern** even when the MongoClient is configured with
   328     another read preference or read concern.
   329     Note the server does not guarantee that documents returned by a find
   330     command will be in inserted order. This find MUST sort by ``{_id:1}``.
   331
   332.. _SERVER-38335: https://jira.mongodb.org/browse/SERVER-38335
   333
   334Special Test Operations
   335```````````````````````
   336
   337Certain operations that appear in the "operations" array do not correspond to
   338API methods but instead represent special test operations. Such operations are
   339defined on the "testRunner" object and documented here:
   340
   341targetedFailPoint
   342~~~~~~~~~~~~~~~~~
   343
   344The "targetedFailPoint" operation instructs the test runner to configure a fail
   345point on a specific mongos. The mongos to run the ``configureFailPoint`` is
   346determined by the "session" argument (either "session0" or "session1").
   347The session must already be pinned to a mongos server. The "failPoint" argument
   348is the ``configureFailPoint`` command to run.
   349
   350If a test uses ``targetedFailPoint``, disable the fail point after running
   351all ``operations`` to avoid spurious failures in subsequent tests. The fail
   352point may be disabled like so::
   353
   354    db.adminCommand({
   355        configureFailPoint: <fail point name>,
   356        mode: "off"
   357    });
   358
   359Here is an example which instructs the test runner to enable the failCommand
   360fail point on the mongos server which "session0" is pinned to::
   361
   362      # Enable the fail point only on the Mongos that session0 is pinned to.
   363      - name: targetedFailPoint
   364        object: testRunner
   365        arguments:
   366          session: session0
   367          failPoint:
   368            configureFailPoint: failCommand
   369            mode: { times: 1 }
   370            data:
   371              failCommands: ["commitTransaction"]
   372              closeConnection: true
   373
   374Tests that use the "targetedFailPoint" operation do not include
   375``configureFailPoint`` commands in their command expectations. Drivers MUST
   376ensure that ``configureFailPoint`` commands do not appear in the list of logged
   377commands, either by manually filtering it from the list of observed commands or
   378by using a different MongoClient to execute ``configureFailPoint``.
   379
   380assertSessionTransactionState
   381~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   382
   383The "assertSessionTransactionState" operation instructs the test runner to
   384assert that the transaction state of the given session is equal to the
   385specified value. The possible values are as follows: ``none``, ``starting``,
   386``in_progress``, ``committed``, ``aborted``::
   387
   388      - name: assertSessionTransactionState
   389        object: testRunner
   390        arguments:
   391          session: session0
   392          state: in_progress
   393
   394assertSessionPinned
   395~~~~~~~~~~~~~~~~~~~
   396
   397The "assertSessionPinned" operation instructs the test runner to assert that
   398the given session is pinned to a mongos::
   399
   400      - name: assertSessionPinned
   401        object: testRunner
   402        arguments:
   403          session: session0
   404
   405assertSessionUnpinned
   406~~~~~~~~~~~~~~~~~~~~~
   407
   408The "assertSessionUnpinned" operation instructs the test runner to assert that
   409the given session is not pinned to a mongos::
   410
   411      - name: assertSessionPinned
   412        object: testRunner
   413        arguments:
   414          session: session0
   415
   416assertCollectionExists
   417~~~~~~~~~~~~~~~~~~~~~~
   418
   419The "assertCollectionExists" operation instructs the test runner to assert that
   420the given collection exists in the database::
   421
   422      - name: assertCollectionExists
   423        object: testRunner
   424        arguments:
   425          database: db
   426          collection: test
   427
   428Use a ``listCollections`` command to check whether the collection exists. Note
   429that it is currently not possible to run ``listCollections`` from within a
   430transaction.
   431
   432assertCollectionNotExists
   433~~~~~~~~~~~~~~~~~~~~~~~~~
   434
   435The "assertCollectionNotExists" operation instructs the test runner to assert
   436that the given collection does not exist in the database::
   437
   438      - name: assertCollectionNotExists
   439        object: testRunner
   440        arguments:
   441          database: db
   442          collection: test
   443
   444Use a ``listCollections`` command to check whether the collection exists. Note
   445that it is currently not possible to run ``listCollections`` from within a
   446transaction.
   447
   448assertIndexExists
   449~~~~~~~~~~~~~~~~~
   450
   451The "assertIndexExists" operation instructs the test runner to assert that the
   452index with the given name exists on the collection::
   453
   454      - name: assertIndexExists
   455        object: testRunner
   456        arguments:
   457          database: db
   458          collection: test
   459          index: t_1
   460
   461Use a ``listIndexes`` command to check whether the index exists. Note that it is
   462currently not possible to run ``listIndexes`` from within a transaction.
   463
   464assertIndexNotExists
   465~~~~~~~~~~~~~~~~~~~~
   466
   467The "assertIndexNotExists" operation instructs the test runner to assert that
   468the index with the given name does not exist on the collection::
   469
   470      - name: assertIndexNotExists
   471        object: testRunner
   472        arguments:
   473          database: db
   474          collection: test
   475          index: t_1
   476
   477Use a ``listIndexes`` command to check whether the index exists. Note that it is
   478currently not possible to run ``listIndexes`` from within a transaction.
   479
   480Command-Started Events
   481``````````````````````
   482
   483The event listener used for these tests MUST ignore the security commands
   484listed in the Command Monitoring Spec.
   485
   486Logical Session Id
   487~~~~~~~~~~~~~~~~~~
   488
   489Each command-started event in ``expectations`` includes an ``lsid`` with the
   490value "session0" or "session1". Tests MUST assert that the command's actual
   491``lsid`` matches the id of the correct ClientSession named ``session0`` or
   492``session1``.
   493
   494Null Values
   495~~~~~~~~~~~
   496
   497Some command-started events in ``expectations`` include ``null`` values for
   498fields such as ``txnNumber``, ``autocommit``, and ``writeConcern``.
   499Tests MUST assert that the actual command **omits** any field that has a
   500``null`` value in the expected command.
   501
   502Cursor Id
   503^^^^^^^^^
   504
   505A ``getMore`` value of ``"42"`` in a command-started event is a fake cursorId
   506that MUST be ignored. (In the Command Monitoring Spec tests, fake cursorIds are
   507correlated with real ones, but that is not necessary for Transactions Spec
   508tests.)
   509
   510afterClusterTime
   511^^^^^^^^^^^^^^^^
   512
   513A ``readConcern.afterClusterTime`` value of ``42`` in a command-started event
   514is a fake cluster time. Drivers MUST assert that the actual command includes an
   515afterClusterTime.
   516
   517recoveryToken
   518^^^^^^^^^^^^^
   519
   520A ``recoveryToken`` value of ``42`` in a command-started event is a
   521placeholder for an arbitrary recovery token. Drivers MUST assert that the
   522actual command includes a "recoveryToken" field and SHOULD assert that field
   523is a BSON document.
   524
   525Mongos Pinning Prose Tests
   526==========================
   527
   528The following tests ensure that a ClientSession is properly unpinned after
   529a sharded transaction. Initialize these tests with a MongoClient connected
   530to multiple mongoses.
   531
   532These tests use a cursor's address field to track which server an operation
   533was run on. If this is not possible in your driver, use command monitoring
   534instead.
   535
   536#. Test that starting a new transaction on a pinned ClientSession unpins the
   537   session and normal server selection is performed for the next operation.
   538
   539   .. code:: python
   540
   541      @require_server_version(4, 1, 6)
   542      @require_mongos_count_at_least(2)
   543      def test_unpin_for_next_transaction(self):
   544        # Increase localThresholdMS and wait until both nodes are discovered
   545        # to avoid false positives.
   546        client = MongoClient(mongos_hosts, localThresholdMS=1000)
   547        wait_until(lambda: len(client.nodes) > 1)
   548        # Create the collection.
   549        client.test.test.insert_one({})
   550        with client.start_session() as s:
   551          # Session is pinned to Mongos.
   552          with s.start_transaction():
   553            client.test.test.insert_one({}, session=s)
   554
   555          addresses = set()
   556          for _ in range(50):
   557            with s.start_transaction():
   558              cursor = client.test.test.find({}, session=s)
   559              assert next(cursor)
   560              addresses.add(cursor.address)
   561
   562          assert len(addresses) > 1
   563
   564#. Test non-transaction operations using a pinned ClientSession unpins the
   565   session and normal server selection is performed.
   566
   567   .. code:: python
   568
   569      @require_server_version(4, 1, 6)
   570      @require_mongos_count_at_least(2)
   571      def test_unpin_for_non_transaction_operation(self):
   572        # Increase localThresholdMS and wait until both nodes are discovered
   573        # to avoid false positives.
   574        client = MongoClient(mongos_hosts, localThresholdMS=1000)
   575        wait_until(lambda: len(client.nodes) > 1)
   576        # Create the collection.
   577        client.test.test.insert_one({})
   578        with client.start_session() as s:
   579          # Session is pinned to Mongos.
   580          with s.start_transaction():
   581            client.test.test.insert_one({}, session=s)
   582
   583          addresses = set()
   584          for _ in range(50):
   585            cursor = client.test.test.find({}, session=s)
   586            assert next(cursor)
   587            addresses.add(cursor.address)
   588
   589          assert len(addresses) > 1
   590
   591Q & A
   592=====
   593
   594Why do some tests appear to hang for 60 seconds on a sharded cluster?
   595`````````````````````````````````````````````````````````````````````
   596
   597There are two cases where this can happen. When the initial commitTransaction
   598attempt fails on mongos A and is retried on mongos B, mongos B will block
   599waiting for the transaction to complete. However because the initial commit
   600attempt failed, the command will only complete after the transaction is
   601automatically aborted for exceeding the shard's
   602transactionLifetimeLimitSeconds setting. `SERVER-39726`_ requests that
   603recovering the outcome of an uncommitted transaction should immediately abort
   604the transaction.
   605
   606The second case is when a *single-shard* transaction is committed successfully
   607on mongos A and then explicitly committed again on mongos B. Mongos B will also
   608block until the transactionLifetimeLimitSeconds timeout is hit at which point
   609``{ok:1}`` will be returned. `SERVER-39349`_ requests that recovering the
   610outcome of a completed single-shard transaction should not block.
   611Note that this test suite only includes single shard transactions.
   612
   613To workaround these issues, drivers SHOULD decrease the transaction timeout
   614setting by running setParameter **on each shard**. Setting the timeout to 3
   615seconds significantly speeds up the test suite without a high risk of
   616prematurely timing out any tests' transactions. To decrease the timeout, run::
   617
   618  db.adminCommand( { setParameter: 1, transactionLifetimeLimitSeconds: 3 } )
   619
   620Note that mongo-orchestration >=0.6.13 automatically sets this timeout to 3
   621seconds so drivers using mongo-orchestration do not need to run these commands
   622manually.
   623
   624.. _SERVER-39726: https://jira.mongodb.org/browse/SERVER-39726
   625
   626.. _SERVER-39349: https://jira.mongodb.org/browse/SERVER-39349
   627
   628Why do tests that run distinct sometimes fail with StaleDbVersion?
   629``````````````````````````````````````````````````````````````````
   630
   631When a shard receives its first command that contains a dbVersion, the shard
   632returns a StaleDbVersion error and the Mongos retries the operation. In a
   633sharded transaction, Mongos does not retry these operations and instead returns
   634the error to the client. For example::
   635
   636  Command distinct failed: Transaction aa09e296-472a-494f-8334-48d57ab530b6:1 was aborted on statement 0 due to: an error from cluster data placement change :: caused by :: got stale databaseVersion response from shard sh01 at host localhost:27217 :: caused by :: don't know dbVersion.
   637
   638To workaround this limitation, a driver test runner MUST run a
   639non-transactional ``distinct`` command on each Mongos before running any test
   640that uses ``distinct``. To ease the implementation drivers can simply run
   641``distinct`` before *every* test.
   642
   643Note that drivers can remove this workaround once `SERVER-39704`_ is resolved
   644so that mongos retries this operation transparently. The ``distinct`` command
   645is the only command allowed in a sharded transaction that uses the
   646``dbVersion`` concept so it is the only command affected.
   647
   648.. _SERVER-39704: https://jira.mongodb.org/browse/SERVER-39704
   649
   650Changelog
   651=========
   652
   653:2019-05-15: Add operation level ``error`` field to assert any error.
   654:2019-03-25: Add workaround for StaleDbVersion on distinct.
   655:2019-03-01: Add top-level ``runOn`` field to denote server version and/or
   656             topology requirements requirements for the test file. Removes the
   657             ``topology`` top-level field, which is now expressed within
   658             ``runOn`` elements.
   659:2019-02-28: ``useMultipleMongoses: true`` and non-targeted fail points are
   660             mutually exclusive.
   661:2019-02-13: Modify test format for 4.2 sharded transactions, including
   662             "useMultipleMongoses", ``object: testRunner``, the
   663             ``targetedFailPoint`` operation, and recoveryToken assertions.

View as plain text