From 271fa9532bda61371db59f96c6fb32054a20766b Mon Sep 17 00:00:00 2001 From: Samar Farooqi Date: Fri, 6 Nov 2026 20:44:43 +0000 Subject: [PATCH 1/7] Route setup failures in create and dropIndexes tests through the assertion A few tests failed before reaching their assertion, so the real engine result could not be judged or handled by an override provider registered through the assertion hook. test_create_validator_errors[validator_objectid] passed a new random ObjectId on every run, so the command, and any engine reply that echoes it, changed between runs. It now uses a fixed ObjectId; the case still checks that an ObjectId validator is rejected with a type mismatch. test_dropIndexes_event_preserves_specification raised LookupError from index_specification when listIndexes did not return the index. The createIndexes error, or the missing index if createIndexes succeeded, is now the result passed to the test's single assertion. test_dropIndexes_start_after_star_returns_remaining_events indexed drops[1] and opened the startAfter stream unguarded. With fewer than two drop events it now reports the short count through the existing initial_count check, and a failed startAfter open or getMore is passed to the assertion as the result. No assertions are added, and MongoDB results are unchanged. Signed-off-by: Samar Farooqi --- .../dropIndexes/test_dropIndexes_resume.py | 42 ++++++++++----- .../test_dropIndexes_specification.py | 51 +++++++++++-------- .../create/test_create_validator_errors.py | 3 +- 3 files changed, 61 insertions(+), 35 deletions(-) diff --git a/documentdb_tests/compatibility/tests/changeStreams/dropIndexes/test_dropIndexes_resume.py b/documentdb_tests/compatibility/tests/changeStreams/dropIndexes/test_dropIndexes_resume.py index 05f3bde36..a1f00f103 100644 --- a/documentdb_tests/compatibility/tests/changeStreams/dropIndexes/test_dropIndexes_resume.py +++ b/documentdb_tests/compatibility/tests/changeStreams/dropIndexes/test_dropIndexes_resume.py @@ -2,7 +2,10 @@ from __future__ import annotations +from typing import Any + import pytest +from pymongo.errors import PyMongoError from documentdb_tests.compatibility.tests.changeStreams.dropIndexes.utils.drop_indexes import ( drop_index_events, @@ -131,25 +134,36 @@ def test_dropIndexes_start_after_star_returns_remaining_events(collection): collection.database.name, collection.name, ) - second_token = drops[1]["_id"] expected_remaining = sorted( event["operationDescription"]["indexes"][0]["name"] for event in drops[2:] ) - with open_change_stream( - collection, - scope="database", - start_after=second_token, - ) as resumed: - replayed_events = collect_until_marker(resumed, collection) - - summary = { - "drop_ok": drop_result.get("ok") if isinstance(drop_result, dict) else None, - "initial_count": len(drops), - "replayed_names": sorted(_event_names(replayed_events, collection)), - } + # With fewer than two drop events there is no token to start after; the + # initial_count check below reports the short event list instead of an + # IndexError here. A failed startAfter open or getMore is passed to the + # assertion as the result. + observed: Any = None + replayed_names = None + if len(drops) >= 2: + try: + with open_change_stream( + collection, + scope="database", + start_after=drops[1]["_id"], + ) as resumed: + replayed_events = collect_until_marker(resumed, collection) + replayed_names = sorted(_event_names(replayed_events, collection)) + except PyMongoError as error: + observed = error + + if observed is None: + observed = { + "drop_ok": drop_result.get("ok") if isinstance(drop_result, dict) else None, + "initial_count": len(drops), + "replayed_names": replayed_names, + } assertProperties( - summary, + observed, { "drop_ok": Eq(1.0), "initial_count": Eq(5), diff --git a/documentdb_tests/compatibility/tests/changeStreams/dropIndexes/test_dropIndexes_specification.py b/documentdb_tests/compatibility/tests/changeStreams/dropIndexes/test_dropIndexes_specification.py index 9276a2665..5cea6cb01 100644 --- a/documentdb_tests/compatibility/tests/changeStreams/dropIndexes/test_dropIndexes_specification.py +++ b/documentdb_tests/compatibility/tests/changeStreams/dropIndexes/test_dropIndexes_specification.py @@ -170,7 +170,7 @@ class DropIndexSpecificationTestCase(BaseTestCase): def test_dropIndexes_event_preserves_specification(collection, test): """Compare the dropped index definition with listIndexes before deletion.""" collection.insert_one(test.document) - execute_command( + create_result = execute_command( collection, { "createIndexes": collection.name, @@ -183,27 +183,38 @@ def test_dropIndexes_event_preserves_specification(collection, test): ], }, ) - expected_specification = index_specification(collection, test.index_name) + observed: Any + try: + expected_specification = index_specification(collection, test.index_name) + except LookupError as missing: + # listIndexes did not return the index, so there is no specification + # to compare against. Pass the createIndexes error, or the missing + # index if createIndexes reported success, to the assertion below. + observed = create_result if isinstance(create_result, Exception) else missing + expected_specification = None - with open_change_stream(collection, scope="database") as stream: - drop_result = execute_command( - collection, - { - "dropIndexes": collection.name, - "index": test.index_name, - }, - ) - events = collect_until_marker(stream, collection) + if expected_specification is not None: + with open_change_stream(collection, scope="database") as stream: + drop_result = execute_command( + collection, + { + "dropIndexes": collection.name, + "index": test.index_name, + }, + ) + events = collect_until_marker(stream, collection) - matching_events = drop_index_events( - events, - collection.database.name, - collection.name, - ) - observed = { - "dropSucceeded": (not isinstance(drop_result, Exception) and drop_result.get("ok") == 1), - "dropEvents": matching_events, - } + matching_events = drop_index_events( + events, + collection.database.name, + collection.name, + ) + observed = { + "dropSucceeded": ( + not isinstance(drop_result, Exception) and drop_result.get("ok") == 1 + ), + "dropEvents": matching_events, + } expected = { "dropSucceeded": Eq(True), "dropEvents": Len(1), diff --git a/documentdb_tests/compatibility/tests/core/collections/commands/create/test_create_validator_errors.py b/documentdb_tests/compatibility/tests/core/collections/commands/create/test_create_validator_errors.py index 62a5f65f9..305f32553 100644 --- a/documentdb_tests/compatibility/tests/core/collections/commands/create/test_create_validator_errors.py +++ b/documentdb_tests/compatibility/tests/core/collections/commands/create/test_create_validator_errors.py @@ -72,7 +72,8 @@ ("int64", Int64(42)), ("decimal128", Decimal128("1")), ("binary", Binary(b"hello")), - ("objectid", ObjectId()), + # A fixed value keeps the command identical on every run. + ("objectid", ObjectId("507f1f77bcf86cd799439011")), ("datetime", datetime(2024, 1, 1, tzinfo=timezone.utc)), ("regex", Regex("test")), ("code", Code("function(){}")), From 846998b63af10b4503cbea70d8e5736d27b2543b Mon Sep 17 00:00:00 2001 From: Samar Farooqi Date: Fri, 6 Nov 2026 20:52:27 +0000 Subject: [PATCH 2/7] Poll asynchronously published state instead of reading it once Some engines publish $indexStats accesses.ops and change-stream DDL events asynchronously. A test that reads once right after the query or DDL can then see a zero counter or an empty batch, even though the engine reports the expected state a moment later. The executor gains execute_command_until, which reruns a command until a predicate accepts the result or a bounded timeout (10 seconds by default) passes, and returns the last result. An error result is returned at once. On an engine that reports the state immediately, the command runs exactly once, so MongoDB behaviour is unchanged. The test format validator treats it like the other execute helpers, and framework/test_executor_polling.py covers it with unit tests. Callers: - test_smoke_changeStream_createIndexes reads getMore until the batch is non-empty. - test_indexStats_ops_counter reads $indexStats until accesses.ops >= 1. - test_hidden_behavior.py: test_indexstats_counter waits for the pre-use find to be counted before toggling hidden, and a case that expects a non-zero counter reads until it is non-zero. A case that expects zero still reads once. test_indexstats_nonhidden_accesses_increment_nonzero and test_indexstats_reset_only_affects_toggled_index_b_unchanged read until the index they check reports a use. Every assertion is unchanged; on timeout the last result is asserted exactly as before. Signed-off-by: Samar Farooqi --- .../test_smoke_changeStream_createIndexes.py | 10 ++- .../properties/hidden/test_hidden_behavior.py | 27 +++++--- .../properties/hidden/utils/helpers.py | 16 ++++- .../indexStats/test_indexStats_ops_counter.py | 16 ++++- documentdb_tests/framework/executor.py | 40 ++++++++++- .../framework/test_executor_polling.py | 69 +++++++++++++++++++ .../framework/test_format_validator.py | 1 + 7 files changed, 163 insertions(+), 16 deletions(-) create mode 100644 documentdb_tests/framework/test_executor_polling.py diff --git a/documentdb_tests/compatibility/tests/changeStreams/createIndexes/test_smoke_changeStream_createIndexes.py b/documentdb_tests/compatibility/tests/changeStreams/createIndexes/test_smoke_changeStream_createIndexes.py index 4e1f5cccc..037d3a338 100644 --- a/documentdb_tests/compatibility/tests/changeStreams/createIndexes/test_smoke_changeStream_createIndexes.py +++ b/documentdb_tests/compatibility/tests/changeStreams/createIndexes/test_smoke_changeStream_createIndexes.py @@ -7,7 +7,7 @@ import pytest from documentdb_tests.framework.assertions import assertChangeStreamEvent -from documentdb_tests.framework.executor import execute_command +from documentdb_tests.framework.executor import execute_command, execute_command_until pytestmark = pytest.mark.smoke @@ -38,7 +38,13 @@ def test_smoke_changeStream_createIndexes(collection): {"createIndexes": collection.name, "indexes": [{"key": {"x": 1}, "name": "x_1"}]}, ) - result = execute_command(collection, {"getMore": cursor_id, "collection": collection.name}) + # Some engines publish the DDL event after the first getMore returns, so + # read until a batch is non-empty or the timeout passes. + result = execute_command_until( + collection, + {"getMore": cursor_id, "collection": collection.name}, + lambda r: bool(r.get("cursor", {}).get("nextBatch")), + ) # An empty batch means the expanded createIndexes event was not emitted; fail # with a clear message instead of an IndexError when indexing nextBatch[0]. diff --git a/documentdb_tests/compatibility/tests/core/indexes/properties/hidden/test_hidden_behavior.py b/documentdb_tests/compatibility/tests/core/indexes/properties/hidden/test_hidden_behavior.py index 8a66bfd75..80ba45a00 100644 --- a/documentdb_tests/compatibility/tests/core/indexes/properties/hidden/test_hidden_behavior.py +++ b/documentdb_tests/compatibility/tests/core/indexes/properties/hidden/test_hidden_behavior.py @@ -10,10 +10,14 @@ IndexTestCase, ) from documentdb_tests.framework.assertions import assertSuccess -from documentdb_tests.framework.executor import execute_admin_command, execute_command +from documentdb_tests.framework.executor import ( + execute_admin_command, + execute_command, + execute_command_until, +) from documentdb_tests.framework.parametrize import pytest_params -from .utils.helpers import get_index_doc, get_index_ops +from .utils.helpers import get_index_doc, get_index_ops, index_stats_command, index_used pytestmark = pytest.mark.index @@ -91,6 +95,9 @@ def test_indexstats_counter(collection, test): execute_command( collection, {"find": collection.name, "filter": {"a": {"$gte": 0}}, "hint": "a_1"} ) + # Wait until the pre-use access is counted, so the toggles below act + # on a non-zero counter even where accesses.ops is updated lazily. + execute_command_until(collection, index_stats_command(collection), index_used("a_1")) for hidden_value in test.input["toggle_sequence"]: execute_command( collection, @@ -100,8 +107,12 @@ def test_indexstats_counter(collection, test): execute_command( collection, {"find": collection.name, "filter": {"a": {"$gte": 0}}, "hint": "a_1"} ) - result = execute_command( - collection, {"aggregate": collection.name, "pipeline": [{"$indexStats": {}}], "cursor": {}} + # A case that expects a non-zero counter reads until the use is counted; + # a case that expects zero reads once, as before. + result = execute_command_until( + collection, + index_stats_command(collection), + index_used("a_1") if test.expected else lambda r: True, ) assertSuccess( result, @@ -349,9 +360,7 @@ def test_indexstats_nonhidden_accesses_increment_nonzero(collection): execute_command( collection, {"find": collection.name, "filter": {"a": {"$gte": 0}}, "hint": "a_1"} ) - result = execute_command( - collection, {"aggregate": collection.name, "pipeline": [{"$indexStats": {}}], "cursor": {}} - ) + result = execute_command_until(collection, index_stats_command(collection), index_used("a_1")) ops = get_index_ops(result, "a_1") assertSuccess( ops >= 1, @@ -380,9 +389,7 @@ def test_indexstats_reset_only_affects_toggled_index_b_unchanged(collection): execute_command( collection, {"collMod": collection.name, "index": {"name": "a_1", "hidden": True}} ) - result = execute_command( - collection, {"aggregate": collection.name, "pipeline": [{"$indexStats": {}}], "cursor": {}} - ) + result = execute_command_until(collection, index_stats_command(collection), index_used("b_1")) b_ops = get_index_ops(result, "b_1") assertSuccess( b_ops >= 1, diff --git a/documentdb_tests/compatibility/tests/core/indexes/properties/hidden/utils/helpers.py b/documentdb_tests/compatibility/tests/core/indexes/properties/hidden/utils/helpers.py index 8e315fb4b..f32b3711f 100644 --- a/documentdb_tests/compatibility/tests/core/indexes/properties/hidden/utils/helpers.py +++ b/documentdb_tests/compatibility/tests/core/indexes/properties/hidden/utils/helpers.py @@ -1,6 +1,6 @@ """Helpers for hidden index property tests.""" -from typing import Any, Iterator, List, Optional +from typing import Any, Callable, Iterator, List, Optional def _walk(node: Any) -> Iterator[dict]: @@ -106,3 +106,17 @@ def get_index_ops(result, index_name): if doc is None: return None return doc["accesses"]["ops"] + + +def index_stats_command(collection) -> dict: + """Return the $indexStats aggregate command for a collection.""" + return {"aggregate": collection.name, "pipeline": [{"$indexStats": {}}], "cursor": {}} + + +def index_used(index_name: str) -> Callable[[dict], bool]: + """Return a predicate that is True once $indexStats reports a use of the index. + + Used with execute_command_until: some engines update accesses.ops + asynchronously, so a single read right after a query can still show 0. + """ + return lambda result: (get_index_ops(result, index_name) or 0) > 0 diff --git a/documentdb_tests/compatibility/tests/core/operator/stages/indexStats/test_indexStats_ops_counter.py b/documentdb_tests/compatibility/tests/core/operator/stages/indexStats/test_indexStats_ops_counter.py index f90bf06ab..8eb13dfca 100644 --- a/documentdb_tests/compatibility/tests/core/operator/stages/indexStats/test_indexStats_ops_counter.py +++ b/documentdb_tests/compatibility/tests/core/operator/stages/indexStats/test_indexStats_ops_counter.py @@ -11,10 +11,19 @@ populate_collection, ) from documentdb_tests.framework.assertions import assertResult -from documentdb_tests.framework.executor import execute_command +from documentdb_tests.framework.executor import execute_command_until from documentdb_tests.framework.parametrize import pytest_params from documentdb_tests.framework.property_checks import Gte + +def _index_used(result: dict) -> bool: + """Return True once any returned $indexStats document has accesses.ops >= 1.""" + return any( + doc.get("accesses", {}).get("ops", 0) >= 1 + for doc in result.get("cursor", {}).get("firstBatch", []) + ) + + # Property [Ops Increment]: accesses.ops increments after index usage. OPS_INCREMENT_TESTS: list[StageTestCase] = [ StageTestCase( @@ -36,13 +45,16 @@ def test_indexStats_ops_counter(collection: Collection, test_case: StageTestCase coll = populate_collection(collection, test_case) if test_case.setup: test_case.setup(coll) - result = execute_command( + # Some engines update accesses.ops asynchronously after the query, so + # read until a matching index reports a use or the timeout passes. + result = execute_command_until( coll, { "aggregate": coll.name, "pipeline": test_case.pipeline, "cursor": {}, }, + _index_used, ) assertResult( result, diff --git a/documentdb_tests/framework/executor.py b/documentdb_tests/framework/executor.py index 812aa70aa..7936c0f70 100644 --- a/documentdb_tests/framework/executor.py +++ b/documentdb_tests/framework/executor.py @@ -4,7 +4,7 @@ import time from datetime import timezone -from typing import Any, Dict, List, Tuple +from typing import Any, Callable, Dict, List, Tuple from bson.codec_options import CodecOptions @@ -126,3 +126,41 @@ def execute_admin_with_retry_command( if not should_retry or time.monotonic() >= deadline: return result time.sleep(interval) + + +def execute_command_until( + collection, + command: Dict, + done: Callable[[Dict], bool], + *, + timeout: float = 10.0, + interval: float = 0.1, +) -> Any: + """ + Run a command until ``done`` accepts its result, then return that result. + + For state that some engines publish asynchronously, such as $indexStats + counters or a change-stream event that lands after the first getMore. On + an engine that reports the state at once, the first result is returned + and the command runs exactly once. + + An error result is returned immediately without calling ``done``. On + timeout, the last result is returned as-is so the caller's assertion + reports it. + + Args: + collection: DocumentDB collection + command: Command to execute via runCommand + done: Predicate on a successful result; True stops polling + timeout: Maximum seconds to keep polling + interval: Seconds to wait between attempts + + Returns: + Result if successful, Exception if failed + """ + deadline = time.monotonic() + timeout + while True: + result = execute_command(collection, command) + if isinstance(result, Exception) or done(result) or time.monotonic() >= deadline: + return result + time.sleep(interval) diff --git a/documentdb_tests/framework/test_executor_polling.py b/documentdb_tests/framework/test_executor_polling.py new file mode 100644 index 000000000..828e086af --- /dev/null +++ b/documentdb_tests/framework/test_executor_polling.py @@ -0,0 +1,69 @@ +"""Unit tests for execute_command_until in the executor (no database needed).""" + +import pytest +from pymongo.errors import OperationFailure + +from documentdb_tests.framework import executor + + +class _FakeDatabase: + def __init__(self, results): + self.results = list(results) + self.calls = 0 + self.client = None + + def command(self, command, **kwargs): + self.calls += 1 + result = self.results.pop(0) if len(self.results) > 1 else self.results[0] + if isinstance(result, Exception): + raise result + return result + + +class _FakeCollection: + def __init__(self, results): + self.database = _FakeDatabase(results) + self.name = "coll" + + +def _ready(result): + return result.get("ready") is True + + +@pytest.mark.unit +def test_first_accepted_result_runs_command_once(): + collection = _FakeCollection([{"ready": True, "ok": 1.0}]) + result = executor.execute_command_until(collection, {"ping": 1}, _ready, interval=0) + assert result == {"ready": True, "ok": 1.0} + assert collection.database.calls == 1 + + +@pytest.mark.unit +def test_polls_until_result_is_accepted(): + collection = _FakeCollection([{"ready": False}, {"ready": False}, {"ready": True}]) + result = executor.execute_command_until(collection, {"ping": 1}, _ready, interval=0) + assert result == {"ready": True} + assert collection.database.calls == 3 + + +@pytest.mark.unit +def test_error_is_returned_without_polling(): + error = OperationFailure("boom", code=2) + collection = _FakeCollection([error]) + calls = [] + result = executor.execute_command_until( + collection, {"ping": 1}, lambda r: calls.append(r) or False, interval=0 + ) + assert result is error + assert collection.database.calls == 1 + assert calls == [] + + +@pytest.mark.unit +def test_timeout_returns_last_result(): + collection = _FakeCollection([{"ready": False}]) + result = executor.execute_command_until( + collection, {"ping": 1}, _ready, timeout=0.05, interval=0.01 + ) + assert result == {"ready": False} + assert collection.database.calls >= 2 diff --git a/documentdb_tests/framework/test_format_validator.py b/documentdb_tests/framework/test_format_validator.py index 2c3394942..d7aa5dc88 100644 --- a/documentdb_tests/framework/test_format_validator.py +++ b/documentdb_tests/framework/test_format_validator.py @@ -34,6 +34,7 @@ def validate_test_format(file_path: str) -> list[str]: "execute_expression_single_row", "execute_expression_with_insert", "execute_admin_with_retry_command", + "execute_command_until", "run_window_operator", ] ) From 3c7bbc2485b2d24e4533904eae2f99eef7c2393e Mon Sep 17 00:00:00 2001 From: Samar Farooqi Date: Fri, 6 Nov 2026 20:47:52 +0000 Subject: [PATCH 3/7] Compare killCursors replies with opened cursor IDs labelled test_killCursors_response_cursor and test_killCursors_list_indexes_cursor compare the whole killCursors reply, and the expected value embeds the cursor IDs the server assigned in this run. The compared value then differs on every run, so a recorded result for an engine whose reply differs from MongoDB can never match it. cursor_test_case.py gains label_cursor_ids, which replaces the opened cursor ID at position i with "cursor_" in the four killCursors ID lists (cursorsKilled, cursorsNotFound, cursorsAlive, cursorsUnknown). Both tests apply it to the reply and the expected value. Field names, list lengths, order and the ok field are compared exactly as before, and only an ID equal to an opened cursor gets a label, so the tests still prove which opened cursor is reported in which list. An engine error is passed through unchanged. MongoDB results are unchanged. Signed-off-by: Samar Farooqi --- .../killCursors/test_killCursors_lifecycle.py | 14 +++++++---- .../killCursors/test_killCursors_response.py | 7 ++++-- .../commands/utils/cursor_test_case.py | 24 +++++++++++++++++++ 3 files changed, 39 insertions(+), 6 deletions(-) diff --git a/documentdb_tests/compatibility/tests/core/cursors/commands/killCursors/test_killCursors_lifecycle.py b/documentdb_tests/compatibility/tests/core/cursors/commands/killCursors/test_killCursors_lifecycle.py index e60c6113f..713f6580f 100644 --- a/documentdb_tests/compatibility/tests/core/cursors/commands/killCursors/test_killCursors_lifecycle.py +++ b/documentdb_tests/compatibility/tests/core/cursors/commands/killCursors/test_killCursors_lifecycle.py @@ -10,6 +10,7 @@ from documentdb_tests.compatibility.tests.core.cursors.commands.utils.cursor_test_case import ( CursorCommandContext, CursorCommandTestCase, + label_cursor_ids, open_find_cursors, ) from documentdb_tests.framework import fixtures @@ -154,18 +155,23 @@ def test_killCursors_list_indexes_cursor(collection): {"listIndexes": collection.name, "cursor": {"batchSize": 1}}, ) cursor_id = None if isinstance(res, Exception) else res["cursor"]["id"] + # The reply is compared with the opened cursor ID replaced by "cursor_0", + # so the compared value does not embed this run's server-assigned ID. result = ( res if isinstance(res, Exception) - else execute_command( - collection, - {"killCursors": collection.name, "cursors": [cursor_id]}, + else label_cursor_ids( + execute_command( + collection, + {"killCursors": collection.name, "cursors": [cursor_id]}, + ), + [cursor_id], ) ) assertResult( result, expected={ - "cursorsKilled": [cursor_id], + "cursorsKilled": ["cursor_0"], "cursorsNotFound": [], "cursorsAlive": [], "cursorsUnknown": [], diff --git a/documentdb_tests/compatibility/tests/core/cursors/commands/killCursors/test_killCursors_response.py b/documentdb_tests/compatibility/tests/core/cursors/commands/killCursors/test_killCursors_response.py index 64090f510..38185f194 100644 --- a/documentdb_tests/compatibility/tests/core/cursors/commands/killCursors/test_killCursors_response.py +++ b/documentdb_tests/compatibility/tests/core/cursors/commands/killCursors/test_killCursors_response.py @@ -8,6 +8,7 @@ from documentdb_tests.compatibility.tests.core.cursors.commands.utils.cursor_test_case import ( CursorCommandContext, CursorCommandTestCase, + label_cursor_ids, open_find_cursors, ) from documentdb_tests.compatibility.tests.core.utils.command_test_case import ( @@ -179,8 +180,10 @@ def test_killCursors_response_cursor(database_client, collection, test): result, expected = cursors, None else: ctx = CursorCommandContext.from_collection(collection, cursors=cursors) - result = execute_command(collection, test.build_command(ctx)) - expected = test.build_expected(ctx) + # Compare with each opened cursor ID replaced by its position label, so + # the compared value does not embed this run's server-assigned IDs. + result = label_cursor_ids(execute_command(collection, test.build_command(ctx)), cursors) + expected = label_cursor_ids(test.build_expected(ctx), cursors) assertResult( result, expected=expected, diff --git a/documentdb_tests/compatibility/tests/core/cursors/commands/utils/cursor_test_case.py b/documentdb_tests/compatibility/tests/core/cursors/commands/utils/cursor_test_case.py index 124394b81..1450a6d0e 100644 --- a/documentdb_tests/compatibility/tests/core/cursors/commands/utils/cursor_test_case.py +++ b/documentdb_tests/compatibility/tests/core/cursors/commands/utils/cursor_test_case.py @@ -68,6 +68,30 @@ def open_cursor(collection: Collection, find_options: dict[str, Any]) -> Any: return res["cursor"]["id"] +KILL_CURSORS_ID_FIELDS = ("cursorsKilled", "cursorsNotFound", "cursorsAlive", "cursorsUnknown") + + +def label_cursor_ids(reply: Any, cursor_ids: tuple[Any, ...] | list[Any]) -> Any: + """Replace each opened cursor ID in a killCursors reply with a stable label. + + Cursor IDs are assigned by the server and differ on every run, so a reply + that embeds them cannot be compared against a recorded result. The ID at + position ``i`` of ``cursor_ids`` becomes ``"cursor_"`` wherever it + appears in the four killCursors ID lists; any other ID is kept as-is. + Field names, list lengths, order and every other field are unchanged, so + the comparison still proves which opened cursor landed in which list. + A non-dict reply (an engine error) is returned unchanged. + """ + if not isinstance(reply, dict): + return reply + labels = {cursor_id: f"cursor_{i}" for i, cursor_id in enumerate(cursor_ids)} + labelled = dict(reply) + for field in KILL_CURSORS_ID_FIELDS: + if isinstance(reply.get(field), list): + labelled[field] = [labels.get(cursor_id, cursor_id) for cursor_id in reply[field]] + return labelled + + @dataclass(frozen=True) class CursorCommandTestCase(CommandTestCase): """CommandTestCase that opens N find cursors before executing. From 3475b906e02523ca6092443b3969f7dc625e185a Mon Sep 17 00:00:00 2001 From: Samar Farooqi Date: Fri, 6 Nov 2026 22:38:27 +0000 Subject: [PATCH 4/7] Keep mergeObjects and planCacheClearFilters tests to one assertion test_accumulator_mergeObjects_input_forms and test_accumulator_mergeObjects_null_missing read result["cursor"] for a key-order check right after assertSuccess. When the engine returns an error and an override provider handles the assertion, assertSuccess returns and the read then raises TypeError outside the helper. The key order check now runs only on a successful result, so an error reply is judged by the single assertion. The check itself is unchanged. The planCacheClearFilters behavior tests called assertNotError in _set_filters as a setup check, then asserted the final listFilters reply, so a test made two assertion calls and one override entry could not cover both. _set_filters now sends the planCacheSetFilter commands through execute_command and returns the first setup error, which the test passes to its final assertion as the result. If the commands succeed but fewer than two filters are listed, it still raises a plain AssertionError, since the test would prove nothing. Each test now makes exactly one assertion call. MongoDB results are unchanged. Signed-off-by: Samar Farooqi --- ...st_accumulator_mergeObjects_input_forms.py | 5 ++ ...t_accumulator_mergeObjects_null_missing.py | 5 ++ .../test_planCacheClearFilters_behavior.py | 66 +++++++++---------- 3 files changed, 43 insertions(+), 33 deletions(-) diff --git a/documentdb_tests/compatibility/tests/core/operator/accumulators/mergeObjects/test_accumulator_mergeObjects_input_forms.py b/documentdb_tests/compatibility/tests/core/operator/accumulators/mergeObjects/test_accumulator_mergeObjects_input_forms.py index 33cf66668..5be6ea941 100644 --- a/documentdb_tests/compatibility/tests/core/operator/accumulators/mergeObjects/test_accumulator_mergeObjects_input_forms.py +++ b/documentdb_tests/compatibility/tests/core/operator/accumulators/mergeObjects/test_accumulator_mergeObjects_input_forms.py @@ -243,6 +243,11 @@ def test_accumulator_mergeObjects_input_forms(collection, test_case: Accumulator {"aggregate": collection.name, "pipeline": test_case.pipeline, "cursor": {}}, ) assertSuccess(result, test_case.expected, msg=test_case.msg) + # An error reply fails in assertSuccess, unless an override provider + # handled the call and it returned. Stop then, so the key-order check + # below only reads firstBatch from a successful result. + if isinstance(result, Exception): + return actual_docs = result["cursor"]["firstBatch"] for actual, exp in zip(actual_docs, test_case.expected): if "result" in exp and isinstance(exp["result"], dict): diff --git a/documentdb_tests/compatibility/tests/core/operator/accumulators/mergeObjects/test_accumulator_mergeObjects_null_missing.py b/documentdb_tests/compatibility/tests/core/operator/accumulators/mergeObjects/test_accumulator_mergeObjects_null_missing.py index ca5fb0cd8..590c9ff1c 100644 --- a/documentdb_tests/compatibility/tests/core/operator/accumulators/mergeObjects/test_accumulator_mergeObjects_null_missing.py +++ b/documentdb_tests/compatibility/tests/core/operator/accumulators/mergeObjects/test_accumulator_mergeObjects_null_missing.py @@ -278,6 +278,11 @@ def test_accumulator_mergeObjects_null_missing(collection, test_case: Accumulato {"aggregate": collection.name, "pipeline": test_case.pipeline, "cursor": {}}, ) assertSuccess(result, test_case.expected, msg=test_case.msg) + # An error reply fails in assertSuccess, unless an override provider + # handled the call and it returned. Stop then, so the key-order check + # below only reads firstBatch from a successful result. + if isinstance(result, Exception): + return actual_docs = result["cursor"]["firstBatch"] for actual, exp in zip(actual_docs, test_case.expected): if "result" in exp and isinstance(exp["result"], dict): diff --git a/documentdb_tests/compatibility/tests/core/query-planning/commands/planCacheClearFilters/test_planCacheClearFilters_behavior.py b/documentdb_tests/compatibility/tests/core/query-planning/commands/planCacheClearFilters/test_planCacheClearFilters_behavior.py index 3138249d5..9ed261de9 100644 --- a/documentdb_tests/compatibility/tests/core/query-planning/commands/planCacheClearFilters/test_planCacheClearFilters_behavior.py +++ b/documentdb_tests/compatibility/tests/core/query-planning/commands/planCacheClearFilters/test_planCacheClearFilters_behavior.py @@ -7,57 +7,58 @@ from __future__ import annotations +from typing import Any + from pymongo.collection import Collection -from documentdb_tests.framework.assertions import assertNotError, assertSuccess +from documentdb_tests.framework.assertions import assertSuccess from documentdb_tests.framework.executor import execute_command -def _set_filters(collection: Collection) -> None: +def _set_filters(collection: Collection) -> Any: """Set two distinct index filters on the collection. - Raises AssertionError if the filters are not visible via - planCacheListFilters after being set. + Returns the engine error if a setup command fails, so the caller can + forward it to the test's single assertion, or None on success. Raises + AssertionError if the commands succeed but the filters are not visible + via planCacheListFilters, since the test would then prove nothing. """ collection.insert_many([{"_id": i, "a": i, "b": i % 5} for i in range(10)]) collection.create_index("a") collection.create_index("b") - db = collection.database - db.command( - { - "planCacheSetFilter": collection.name, - "query": {"a": 1}, - "indexes": [{"a": 1}], - } - ) - db.command( - { - "planCacheSetFilter": collection.name, - "query": {"b": 1}, - "indexes": [{"b": 1}], - } - ) + for field in ("a", "b"): + set_result = execute_command( + collection, + { + "planCacheSetFilter": collection.name, + "query": {field: 1}, + "indexes": [{field: 1}], + }, + ) + if isinstance(set_result, Exception): + return set_result list_result = execute_command(collection, {"planCacheListFilters": collection.name}) - assertNotError(list_result, msg="planCacheListFilters precondition check") + if isinstance(list_result, Exception): + return list_result filters = list_result.get("filters", []) if len(filters) < 2: raise AssertionError( f"Precondition failed: expected at least 2 index filters " f"after setup, got {len(filters)}" ) + return None # Property [Clear All Filters]: planCacheClearFilters without query shape # parameters removes all index filters for the collection. def test_planCacheClearFilters_clears_all_filters(collection: Collection): """Test planCacheClearFilters removes all index filters.""" - _set_filters(collection) - - execute_command(collection, {"planCacheClearFilters": collection.name}) - - result = execute_command(collection, {"planCacheListFilters": collection.name}) + result = _set_filters(collection) + if result is None: + execute_command(collection, {"planCacheClearFilters": collection.name}) + result = execute_command(collection, {"planCacheListFilters": collection.name}) assertSuccess( result, {"filters": [], "ok": 1.0}, @@ -70,14 +71,13 @@ def test_planCacheClearFilters_clears_all_filters(collection: Collection): # only the matching filter and leaves other filters intact. def test_planCacheClearFilters_targeted_preserves_other_filters(collection: Collection): """Test planCacheClearFilters with query shape leaves non-targeted filters.""" - _set_filters(collection) - - execute_command( - collection, - {"planCacheClearFilters": collection.name, "query": {"a": 1}}, - ) - - result = execute_command(collection, {"planCacheListFilters": collection.name}) + result = _set_filters(collection) + if result is None: + execute_command( + collection, + {"planCacheClearFilters": collection.name, "query": {"a": 1}}, + ) + result = execute_command(collection, {"planCacheListFilters": collection.name}) assertSuccess( result, { From 05c436627b1264b002ed27ba1a4a2f05e0f5b2ed Mon Sep 17 00:00:00 2001 From: Samar Farooqi Date: Wed, 11 Nov 2026 19:56:00 +0000 Subject: [PATCH 5/7] Route more setup failures and late events through the assertion A few more tests failed outside their assertion, read an event that can arrive after the first getMore, or compared a value that embeds this run's cursor ID. test_changeStream_event_structure: the seed insert and the observed mutation ran unguarded, so an engine that rejects an _id type (for example Code or DBRef) raised before the event check. A failed seed, mutation or post-mutation write is now returned as the result and passed to the test's single assertion. test_changeStream_resume: _event_token_of_type now reads the stream with execute_command_until until a batch holds an event of the requested type, so test_expanded_only_token_fails_on_advance no longer fails in setup when the createIndexes event lands after the first getMore. When the event is in the first batch, getMore runs once. test_smoke_changeStream_dropIndexes reads getMore until the batch is non-empty, exactly like the createIndexes smoke test. test_listIndexes_killCursors_succeeds passes a failed listIndexes to the assertion instead of indexing into it, and compares the killCursors reply with the opened cursor ID labelled through label_cursor_ids. test_killCursors_timeseries_cursor never checked its time-series create. When the create was rejected, insert_many made a regular collection and the test passed without a time-series cursor. A failed create is now the result, and the reply is compared with the cursor ID labelled. No assertions are added, and MongoDB results are unchanged. Signed-off-by: Samar Farooqi --- .../test_smoke_changeStream_dropIndexes.py | 10 ++++- .../killCursors/test_killCursors_lifecycle.py | 43 ++++++++++++------- .../test_listIndexes_cursor_batching.py | 24 ++++++++--- .../changeStream/test_changeStream_events.py | 26 +++++++---- .../changeStream/test_changeStream_resume.py | 26 ++++++++--- 5 files changed, 91 insertions(+), 38 deletions(-) diff --git a/documentdb_tests/compatibility/tests/changeStreams/dropIndexes/test_smoke_changeStream_dropIndexes.py b/documentdb_tests/compatibility/tests/changeStreams/dropIndexes/test_smoke_changeStream_dropIndexes.py index 635ba9a4e..c381fda5e 100644 --- a/documentdb_tests/compatibility/tests/changeStreams/dropIndexes/test_smoke_changeStream_dropIndexes.py +++ b/documentdb_tests/compatibility/tests/changeStreams/dropIndexes/test_smoke_changeStream_dropIndexes.py @@ -7,7 +7,7 @@ import pytest from documentdb_tests.framework.assertions import assertChangeStreamEvent -from documentdb_tests.framework.executor import execute_command +from documentdb_tests.framework.executor import execute_command, execute_command_until pytestmark = pytest.mark.smoke @@ -36,7 +36,13 @@ def test_smoke_changeStream_dropIndexes(collection): execute_command(collection, {"dropIndexes": collection.name, "index": "x_1"}) - result = execute_command(collection, {"getMore": cursor_id, "collection": collection.name}) + # Some engines publish the DDL event after the first getMore returns, so + # read until a batch is non-empty or the timeout passes. + result = execute_command_until( + collection, + {"getMore": cursor_id, "collection": collection.name}, + lambda r: bool(r.get("cursor", {}).get("nextBatch")), + ) # An empty batch means the expanded dropIndexes event was not emitted; fail # with a clear message instead of an IndexError when indexing nextBatch[0]. diff --git a/documentdb_tests/compatibility/tests/core/cursors/commands/killCursors/test_killCursors_lifecycle.py b/documentdb_tests/compatibility/tests/core/cursors/commands/killCursors/test_killCursors_lifecycle.py index 713f6580f..2bb2c890a 100644 --- a/documentdb_tests/compatibility/tests/core/cursors/commands/killCursors/test_killCursors_lifecycle.py +++ b/documentdb_tests/compatibility/tests/core/cursors/commands/killCursors/test_killCursors_lifecycle.py @@ -218,28 +218,41 @@ def test_killCursors_view_cursor(database_client, collection): def test_killCursors_timeseries_cursor(database_client, collection): """Test killCursors kills a cursor opened against a time-series collection.""" ts_name = collection.name + "_ts" - execute_command( + created = execute_command( collection, {"create": ts_name, "timeseries": {"timeField": "ts"}}, ) - ts = database_client[ts_name] - ts.insert_many( - [{"ts": datetime.datetime(2024, 1, 1) + datetime.timedelta(minutes=i)} for i in range(20)] - ) - res = execute_command(ts, {"find": ts_name, "batchSize": 1}) - cursor_id = None if isinstance(res, Exception) else res["cursor"]["id"] - result = ( - res - if isinstance(res, Exception) - else execute_command( - ts, - {"killCursors": ts_name, "cursors": [cursor_id]}, + # A rejected time-series create is the result: inserting anyway would + # create a regular collection and test a non-time-series cursor instead. + if isinstance(created, Exception): + result = created + else: + ts = database_client[ts_name] + ts.insert_many( + [ + {"ts": datetime.datetime(2024, 1, 1) + datetime.timedelta(minutes=i)} + for i in range(20) + ] + ) + res = execute_command(ts, {"find": ts_name, "batchSize": 1}) + cursor_id = None if isinstance(res, Exception) else res["cursor"]["id"] + # The reply is compared with the opened cursor ID replaced by "cursor_0", + # so the compared value does not embed this run's server-assigned ID. + result = ( + res + if isinstance(res, Exception) + else label_cursor_ids( + execute_command( + ts, + {"killCursors": ts_name, "cursors": [cursor_id]}, + ), + [cursor_id], + ) ) - ) assertResult( result, expected={ - "cursorsKilled": [cursor_id], + "cursorsKilled": ["cursor_0"], "cursorsNotFound": [], "cursorsAlive": [], "cursorsUnknown": [], diff --git a/documentdb_tests/compatibility/tests/core/indexes/commands/listIndexes/test_listIndexes_cursor_batching.py b/documentdb_tests/compatibility/tests/core/indexes/commands/listIndexes/test_listIndexes_cursor_batching.py index e5909708e..4196b9e93 100644 --- a/documentdb_tests/compatibility/tests/core/indexes/commands/listIndexes/test_listIndexes_cursor_batching.py +++ b/documentdb_tests/compatibility/tests/core/indexes/commands/listIndexes/test_listIndexes_cursor_batching.py @@ -6,6 +6,9 @@ import pytest +from documentdb_tests.compatibility.tests.core.cursors.commands.utils.cursor_test_case import ( + label_cursor_ids, +) from documentdb_tests.framework.assertions import assertSuccess from documentdb_tests.framework.executor import execute_command @@ -121,17 +124,24 @@ def test_listIndexes_killCursors_succeeds(collection_with_3_indexes): collection_with_3_indexes, {"listIndexes": collection_with_3_indexes.name, "cursor": {"batchSize": 1}}, ) - cursor_id = result["cursor"]["id"] - - kill_result = execute_command( - collection_with_3_indexes, - {"killCursors": collection_with_3_indexes.name, "cursors": [cursor_id]}, - ) + if isinstance(result, Exception): + kill_result = result + else: + cursor_id = result.get("cursor", {}).get("id") + # The reply is compared with the opened cursor ID replaced by "cursor_0", + # so the compared value does not embed this run's server-assigned ID. + kill_result = label_cursor_ids( + execute_command( + collection_with_3_indexes, + {"killCursors": collection_with_3_indexes.name, "cursors": [cursor_id]}, + ), + [cursor_id], + ) assertSuccess( kill_result, { - "cursorsKilled": [cursor_id], + "cursorsKilled": ["cursor_0"], "cursorsNotFound": [], "cursorsAlive": [], "cursorsUnknown": [], diff --git a/documentdb_tests/compatibility/tests/core/operator/system-stages/changeStream/test_changeStream_events.py b/documentdb_tests/compatibility/tests/core/operator/system-stages/changeStream/test_changeStream_events.py index 4e07f5aa4..9d3601a4d 100644 --- a/documentdb_tests/compatibility/tests/core/operator/system-stages/changeStream/test_changeStream_events.py +++ b/documentdb_tests/compatibility/tests/core/operator/system-stages/changeStream/test_changeStream_events.py @@ -9,6 +9,7 @@ import pytest from bson import Binary, Code, DBRef, Int64, MaxKey, MinKey, ObjectId, Timestamp +from pymongo.errors import PyMongoError from utils.changeStream_common import change_stream_command, get_more_command from documentdb_tests.framework.assertions import assertProperties @@ -429,15 +430,19 @@ def _emit_event(collection, test_case: ChangeStreamEventTestCase) -> dict[str, A """Open a stream, perform the test case mutation, and return the matching event. The mutation happens after the stream is open, so its event is delivered by - the first getMore. If opening the stream or reading the batch fails, the - engine's exception is returned so the test's single assertion surfaces it. - If the batch has no event of the expected type, the getMore reply is - returned instead, so the assertion reports what the stream delivered. + the first getMore. If seeding, opening the stream, performing the mutation + or reading the batch fails, the engine's exception is returned so the + test's single assertion surfaces it. If the batch has no event of the + expected type, the getMore reply is returned instead, so the assertion + reports what the stream delivered. """ mutation = test_case.mutation assert mutation is not None # guaranteed by __post_init__ if mutation.seed is not None: - collection.insert_one(dict(mutation.seed)) + try: + collection.insert_one(dict(mutation.seed)) + except PyMongoError as error: + return error if test_case.pre_and_post_images: execute_command( collection, @@ -448,9 +453,14 @@ def _emit_event(collection, test_case: ChangeStreamEventTestCase) -> dict[str, A ) if isinstance(opened, Exception): return opened - mutation.apply(collection) - if test_case.post_mutation is not None: - test_case.post_mutation(collection) + # The mutation's own write can be rejected (for example an _id type an + # engine does not accept); that error is the result, not a crash. + try: + mutation.apply(collection) + if test_case.post_mutation is not None: + test_case.post_mutation(collection) + except PyMongoError as error: + return error batch_result = execute_command(collection, get_more_command(collection, opened["cursor"]["id"])) if isinstance(batch_result, Exception): return batch_result diff --git a/documentdb_tests/compatibility/tests/core/operator/system-stages/changeStream/test_changeStream_resume.py b/documentdb_tests/compatibility/tests/core/operator/system-stages/changeStream/test_changeStream_resume.py index 2fef043c8..3e320bde2 100644 --- a/documentdb_tests/compatibility/tests/core/operator/system-stages/changeStream/test_changeStream_resume.py +++ b/documentdb_tests/compatibility/tests/core/operator/system-stages/changeStream/test_changeStream_resume.py @@ -18,7 +18,7 @@ INVALID_RESUME_TOKEN_ERROR, OVERFLOW_ERROR, ) -from documentdb_tests.framework.executor import execute_command +from documentdb_tests.framework.executor import execute_command, execute_command_until from documentdb_tests.framework.property_checks import Eq, Len pytestmark = [pytest.mark.requires(change_streams=True), pytest.mark.aggregate] @@ -62,15 +62,29 @@ def _first_event_token(collection, seed, spec=None): def _event_token_of_type(collection, operation_type, seed, spec=None): - """Open a stream, seed events, and return the token of the first matching event.""" + """Open a stream, seed events, and return the token of the first matching event. + + Some engines publish an event (for example a DDL event) after the first + getMore returns, so the stream is read until a batch holds an event of + ``operation_type`` or the timeout passes. On an engine that delivers the + event in the first batch, getMore runs exactly once. + """ opened = _open_stream(collection, spec) if isinstance(opened, Exception): return opened seed(collection) - batch = _drain(collection, opened) - if isinstance(batch, Exception): - return batch - token = next((e["_id"] for e in batch if e["operationType"] == operation_type), None) + result = execute_command_until( + collection, + get_more_command(collection, opened["cursor"]["id"]), + lambda r: any( + e.get("operationType") == operation_type + for e in r.get("cursor", {}).get("nextBatch", []) + ), + ) + if isinstance(result, Exception): + return result + batch = result.get("cursor", {}).get("nextBatch", []) + token = next((e["_id"] for e in batch if e.get("operationType") == operation_type), None) if token is None: return LookupError(f"token-capture stream returned no {operation_type} event: {batch!r}") return token From 1dd138f65e14281c8859876f42b96293fbe113c7 Mon Sep 17 00:00:00 2001 From: Samar Farooqi Date: Wed, 11 Nov 2026 21:57:28 +0000 Subject: [PATCH 6/7] Re-trigger CI Signed-off-by: Samar Farooqi From f09989fec44e99ae015b48c41d6fd30660cb04b4 Mon Sep 17 00:00:00 2001 From: Samar Farooqi Date: Mon, 16 Nov 2026 20:56:22 +0000 Subject: [PATCH 7/7] Document when to use execute_command_until in TEST_FORMAT.md Signed-off-by: Samar Farooqi --- docs/testing/TEST_FORMAT.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/docs/testing/TEST_FORMAT.md b/docs/testing/TEST_FORMAT.md index 9050b16a0..328532138 100644 --- a/docs/testing/TEST_FORMAT.md +++ b/docs/testing/TEST_FORMAT.md @@ -121,6 +121,23 @@ Keep helpers in `utils/` at each test level. Helpers should reduce meaningful bo Minimize helper scope — one helper should do one thing. If a helper has many if/else branches handling different cases, split it into separate helpers at a lower folder level. +### Polling for Asynchronously Published State + +Use `execute_command_until()` only for state the server may publish asynchronously, such as `$indexStats` counters or a change-stream event that lands after the first `getMore`. It is not a generic retry: + +- The predicate checks that the state is present (for example, the counter is non-zero), not the value the test asserts. The assertion still judges the result. +- Errors are never retried. An error result is returned at once. +- On timeout, the last result is returned so the assertion reports it. + +```python +# ✅ Good: wait until the counter is published, then assert on it +result = execute_command_until(collection, index_stats_cmd, done=index_used("a_1")) +assertResult(result, expected={"accesses.ops": Gte(1)}) + +# ❌ Bad: the predicate repeats the assertion, so a wrong value is polled for the full timeout +# result = execute_command_until(collection, cmd, done=lambda r: r == expected) +``` + ## Parametrized Tests Use `@pytest.mark.parametrize` with dataclasses for operators with many test cases. Dataclasses give named fields instead of anonymous tuples, so `test.dividend` is readable where `test[0]` is not. They also provide automatic `__repr__` for clear test IDs in output, and `frozen=True` prevents accidental mutation between test runs: