diff --git a/.github/workflows/pr-tests.yml b/.github/workflows/pr-tests.yml index 30e583619..74f5c724b 100644 --- a/.github/workflows/pr-tests.yml +++ b/.github/workflows/pr-tests.yml @@ -83,13 +83,67 @@ jobs: | sed -u 's/^/resource-monitor out-of-memory /' ) & trap 'kill %1 %2 2>/dev/null || true' EXIT + # Fail fast if the target dies mid-run. If a server crashes, every + # remaining test otherwise blocks on connection timeouts against a + # dead target one by one, and the job burns the full 6h runner limit + # before failing. This watchdog polls the profile's containers and, if + # any expected service stops running, terminates the test run so the + # job fails in about a minute instead of hours. + PROFILE='${{ matrix.target.profile }}' + watch_target() { + set +e + local pid=$1 expected running low=0 + expected=$(docker compose -f dev/compose.yaml --profile "$PROFILE" config --services | grep -c .) + # Sanity-check the probe once. The stack is already up (compose + # --wait), so every service should read as running; if it does not, + # the ps query is unreliable on this runner and the watchdog steps + # aside rather than risk a false abort. + if [ "$(docker compose -f dev/compose.yaml --profile "$PROFILE" ps --status running -q 2>/dev/null | grep -c .)" -lt "$expected" ]; then + echo "resource-monitor target-watchdog disabled: could not read a healthy baseline" + return + fi + while kill -0 "$pid" 2>/dev/null; do + running=$(docker compose -f dev/compose.yaml --profile "$PROFILE" ps --status running -q 2>/dev/null | grep -c .) + # Require two consecutive low readings before aborting. A single + # low count can be a transient docker-CLI hiccup on this + # resource-heavy runner (a failed query reads as 0); a real crash + # stays low, so demanding two polls in a row rules out a false + # abort while adding only one poll interval to a genuine one. + if [ "$running" -lt "$expected" ]; then + low=$((low + 1)) + if [ "$low" -ge 2 ]; then + echo "::error::A $PROFILE target container exited mid-run (likely a server crash). Aborting the test run so the job fails fast instead of timing out every remaining test against a dead target." + docker compose -f dev/compose.yaml --profile "$PROFILE" ps -a + kill -TERM "$pid" 2>/dev/null; sleep 10; kill -KILL "$pid" 2>/dev/null + return + fi + else + low=0 + fi + sleep 15 + done + } + + # --timeout caps any single hung test as a backstop independent of the + # watchdog: a wedged query fails its own test (default signal method, + # as the crash-test job uses) instead of stalling a worker forever. pytest documentdb_tests/compatibility/tests \ --connection-string "${{ matrix.target.connection_string }}" \ --engine-name "${{ matrix.target.engine }}" \ -n auto \ -v \ + --timeout=120 \ --json-report --json-report-file=${{ github.workspace }}/.test-results/${{ matrix.target.name }}-report.json \ - --junitxml=${{ github.workspace }}/.test-results/${{ matrix.target.name }}-results.xml + --junitxml=${{ github.workspace }}/.test-results/${{ matrix.target.name }}-results.xml & + pytest_pid=$! + watch_target "$pytest_pid" & + watch_pid=$! + set +e + wait "$pytest_pid" + status=$? + set -e + kill "$watch_pid" 2>/dev/null || true + exit "$status" - name: Dump container logs if: always() diff --git a/dev/compose.yaml b/dev/compose.yaml index 60485a08f..4ab97e7a1 100644 --- a/dev/compose.yaml +++ b/dev/compose.yaml @@ -37,6 +37,21 @@ # cache keeps the combined footprint within the VM. There is intentionally no # per-container mem_limit: that caps total process memory (not just cache) and a # transient working-set spike then kills mongod even when the VM has room. +# +# Open files: each mongod raises its open-file limit (ulimits.nofile). The suite +# creates and drops tens of thousands of collections in a run, and WiredTiger +# holds an open file descriptor per table (collection + indexes) it has touched, +# closing idle ones only lazily, so the descriptor count tracks the number of +# collections created over the run, not the number live at once. On the replica +# set a dropped collection also becomes a drop-pending ident whose files linger +# until the drop timestamp is majority-committed and swept, so descriptors +# accumulate faster than they are reclaimed. The replica set peaks near 60k open files partway through the suite; when that +# reaches the ceiling mongod runs out of descriptors mid-run, which surfaces +# inside WiredTiger as a WT_PANIC and crashes the server (EMFILE -> fassert). +# 64000 was not enough headroom (the suite crashed at ~31k collections against +# it), so this is set to 1048576 -- the limit MongoDB's own packaging ships and +# well above the suite's peak. Standalone reclaims dropped files immediately so +# it never approaches the ceiling, but the limit is raised on both for parity. services: # mongo-standalone: a single standalone server. @@ -44,6 +59,12 @@ services: image: mongo:8.2.4 profiles: ["mongo-standalone", "all"] command: ["--wiredTigerCacheSizeGB", "1.5"] + # Raise the open-file limit above the container default so the suite's + # collection churn cannot exhaust mongod's descriptors (see header note). + ulimits: + nofile: + soft: 1048576 + hard: 1048576 ports: - "27017:27017" healthcheck: @@ -80,6 +101,14 @@ services: - "skipAuthenticationToMongot=true" - "--setParameter" - "skipAuthenticationToSearchIndexManagementServer=true" + # Raise the open-file limit well above the peak. This matters most here: the + # replica set defers dropped-collection files as drop-pending idents, so + # descriptors accumulate under churn and exhaust a lower limit mid-run, + # crashing mongod with a WT_PANIC (see header note). + ulimits: + nofile: + soft: 1048576 + hard: 1048576 ports: - "27018:27017" healthcheck: diff --git a/documentdb_tests/compatibility/tests/core/data-types/bson_types/types/test_types_string.py b/documentdb_tests/compatibility/tests/core/data-types/bson_types/types/test_types_string.py index a289cf867..682eb21d6 100644 --- a/documentdb_tests/compatibility/tests/core/data-types/bson_types/types/test_types_string.py +++ b/documentdb_tests/compatibility/tests/core/data-types/bson_types/types/test_types_string.py @@ -167,13 +167,15 @@ def test_string_round_trip(collection, test): def test_string_max_length(collection): """Test max-length string passes through the engine unchanged.""" max_str = "a" * (STRING_SIZE_LIMIT_BYTES - 1) + # A document holding the string would exceed the maximum document size, so + # it cannot be inserted; the string enters the pipeline as a literal instead. + collection.insert_one({}) result = execute_command( collection, { - "aggregate": 1, + "aggregate": collection.name, "pipeline": [ - {"$documents": [{"v": max_str}]}, - {"$project": {"_id": 0, "v": 1}}, + {"$project": {"_id": 0, "v": {"$literal": max_str}}}, ], "cursor": {}, }, diff --git a/documentdb_tests/compatibility/tests/core/operator/expressions/test_expressions_combination_variables.py b/documentdb_tests/compatibility/tests/core/operator/expressions/test_expressions_combination_variables.py index ff55a776f..43882418e 100644 --- a/documentdb_tests/compatibility/tests/core/operator/expressions/test_expressions_combination_variables.py +++ b/documentdb_tests/compatibility/tests/core/operator/expressions/test_expressions_combination_variables.py @@ -160,12 +160,12 @@ def test_let_nested_combinations(collection, test): # --------------------------------------------------------------------------- def test_let_two_lets_same_projection(collection): """Test two separate $let expressions in same projection with same variable name.""" + collection.insert_one({}) result = execute_command( collection, { - "aggregate": 1, + "aggregate": collection.name, "pipeline": [ - {"$documents": [{}]}, { "$project": { "_id": 0, @@ -248,12 +248,12 @@ def test_let_across_multiple_documents(collection): def test_let_error_cross_let_variable_ref(collection): """Test $let where variable defined in one $let is referenced in sibling $let.""" + collection.insert_one({}) result = execute_command( collection, { - "aggregate": 1, + "aggregate": collection.name, "pipeline": [ - {"$documents": [{}]}, { "$project": { "_id": 0, diff --git a/documentdb_tests/compatibility/tests/core/operator/expressions/utils/utils.py b/documentdb_tests/compatibility/tests/core/operator/expressions/utils/utils.py index ec6d21c75..e70d52dc4 100644 --- a/documentdb_tests/compatibility/tests/core/operator/expressions/utils/utils.py +++ b/documentdb_tests/compatibility/tests/core/operator/expressions/utils/utils.py @@ -39,6 +39,21 @@ def execute_project(collection, project): """ Execute a projection with literal input values. + Evaluates the projection against a single empty document. The document is + inserted into the collection and the pipeline runs over that collection, + rather than synthesizing the row with a ``$documents`` stage. This keeps the + helper free of any dependency on ``$documents`` support while producing the + same single-row input the projection sees. + + Note: the inserted document carries an auto-generated ``_id``, so the input + row is ``{_id: }`` rather than the field-less row ``$documents: + [{}]`` produces. Literal expressions and references to any other (missing) + field behave identically, and the output projection excludes ``_id``; but an + expression that reads ``$_id``, ``$$ROOT``, or ``$$CURRENT`` sees that id and + will diverge. Callers that need a truly field-less input (e.g. ``$$ROOT`` must + be ``{}``) or exactly one row over a pre-populated collection must shape their + own pipeline instead of using this helper. + Args: collection: MongoDB collection object project: Fields to project. Do not include _id; the function always @@ -51,12 +66,12 @@ def execute_project(collection, project): >>> execute_project(collection, {"sum": {"$add": [1, 2]}}) # Returns result with {"sum": 3} in firstBatch """ + collection.insert_one({}) return execute_command( collection, { - "aggregate": 1, + "aggregate": collection.name, "pipeline": [ - {"$documents": [{}]}, {"$project": {**materialize(project), "_id": 0}}, ], "cursor": {}, @@ -100,10 +115,26 @@ def execute_project_with_insert(collection, document, project): def execute_expression(collection, expression): """ - Execute an aggregation expression using $documents stage. - - Evaluates an expression against an empty document using the $documents - stage. Useful for testing expressions with literal values. + Execute an aggregation expression against a single empty document. + + Evaluates an expression against an empty document. The document is inserted + into the collection and the pipeline runs over that collection, rather than + synthesizing the row with a ``$documents`` stage. This keeps the helper free + of any dependency on ``$documents`` support while producing the same + single-row input the expression is evaluated against. Useful for testing + expressions with literal values; references to fields other than ``_id`` + resolve to missing, just as they would against a ``$documents: [{}]`` row. + + Note: the inserted document carries an auto-generated ``_id``, so the input + row is ``{_id: }`` rather than the field-less row ``$documents: + [{}]`` produces. Literal expressions and references to any other (missing) + field are unaffected, and the output projection excludes ``_id``; but an + expression that reads ``$_id``, ``$$ROOT``, or ``$$CURRENT`` sees that id and + will diverge. Callers that need a truly field-less input (e.g. ``$$ROOT`` must + be ``{}``) must shape their own pipeline instead of using this helper. Callers + whose collection is already populated should use + ``execute_expression_single_row``, since this helper would emit one row per + document. Args: collection: MongoDB collection object @@ -117,12 +148,49 @@ def execute_expression(collection, expression): >>> execute_expression(collection, {"$add": [1, 2]}) # Returns result with {"result": 3} in firstBatch """ + collection.insert_one({}) + return execute_command( + collection, + { + "aggregate": collection.name, + "pipeline": [ + {"$project": {"_id": 0, "result": expression}}, + ], + "cursor": {}, + }, + ) + + +def execute_expression_single_row(collection, expression): + """ + Execute an aggregation expression once over an already-populated collection. + + Evaluates the expression against the first document of the collection + (``$limit: 1``), so the result has exactly one row however many documents + the collection holds. Unlike ``execute_expression``, this helper does not + insert anything, so no write lands between the caller's own steps and the + evaluation. The collection must already hold at least one document; an + empty collection yields no rows. + + Args: + collection: MongoDB collection object holding at least one document + expression: The expression to evaluate (e.g., {"$add": [1, 2]}) + + Returns: + Result from execute_command with structure: + {"cursor": {"firstBatch": [{"result": }]}} + + Example: + >>> collection.insert_many([{"_id": 1}, {"_id": 2}]) + >>> execute_expression_single_row(collection, {"$add": [1, 2]}) + # Returns result with a single {"result": 3} in firstBatch + """ return execute_command( collection, { - "aggregate": 1, + "aggregate": collection.name, "pipeline": [ - {"$documents": [{}]}, + {"$limit": 1}, {"$project": {"_id": 0, "result": expression}}, ], "cursor": {}, diff --git a/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/cluster_time/test_cluster_time_clock_progression.py b/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/cluster_time/test_cluster_time_clock_progression.py index f49a9c390..3a537d494 100644 --- a/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/cluster_time/test_cluster_time_clock_progression.py +++ b/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/cluster_time/test_cluster_time_clock_progression.py @@ -7,6 +7,7 @@ from documentdb_tests.compatibility.tests.core.operator.expressions.utils.utils import ( # noqa: E501 assert_expression_result, execute_expression, + execute_expression_single_row, ) from documentdb_tests.framework.assertions import assertSuccess from documentdb_tests.framework.executor import execute_admin_command, execute_command @@ -398,29 +399,37 @@ def test_cluster_time_identical_across_thousand_references(collection): ) +def _clock_source(collection): + """Return a one-document side collection to read $$CLUSTER_TIME from. + + Reads run over a separate collection in the same database so they never add + documents to the test's own collection, which later assertions inspect as a + whole. The side collection is seeded once, on the first read, so every later + read is write-free and an idle interval between reads stays idle. + """ + source = collection.database[f"{collection.name}_clock"] + if source.find_one() is None: + source.insert_one({}) + return source + + def _read_cluster_time(collection): """Return a single $$CLUSTER_TIME value from its own aggregation.""" - result = execute_command( - collection, - { - "aggregate": 1, - "pipeline": [{"$documents": [{}]}, {"$project": {"_id": 0, "t": "$$CLUSTER_TIME"}}], - "cursor": {}, - }, - ) - return result["cursor"]["firstBatch"][0]["t"] + result = execute_expression_single_row(_clock_source(collection), "$$CLUSTER_TIME") + return result["cursor"]["firstBatch"][0]["result"] def _read_cluster_time_with_metadata(collection, command_extra=None): """Return the pipeline's value and the command response's own operationTime.""" + source = _clock_source(collection) command = { - "aggregate": 1, - "pipeline": [{"$documents": [{}]}, {"$project": {"_id": 0, "t": "$$CLUSTER_TIME"}}], + "aggregate": source.name, + "pipeline": [{"$limit": 1}, {"$project": {"_id": 0, "t": "$$CLUSTER_TIME"}}], "cursor": {}, } if command_extra: command.update(command_extra) - result = execute_command(collection, command) + result = execute_command(source, command) return result["cursor"]["firstBatch"][0]["t"], result["operationTime"] @@ -429,7 +438,7 @@ def test_cluster_time_advances_after_a_write(collection): earlier = _read_cluster_time(collection) collection.insert_one({"_id": "advance"}) - result = execute_expression(collection, {"$gt": ["$$CLUSTER_TIME", earlier]}) + result = execute_expression_single_row(collection, {"$gt": ["$$CLUSTER_TIME", earlier]}) assert_expression_result( result, expected=True, @@ -444,10 +453,8 @@ def test_cluster_time_monotonic_across_repeated_executions(collection): observed.append(_read_cluster_time(collection)) collection.insert_one({"_id": i}) - result = execute_expression( - collection, - {"$eq": [{"$sortArray": {"input": observed, "sortBy": 1}}, observed]}, - ) + non_decreasing = {"$eq": [{"$sortArray": {"input": observed, "sortBy": 1}}, observed]} + result = execute_expression_single_row(collection, non_decreasing) assert_expression_result( result, expected=True, @@ -462,7 +469,8 @@ def test_cluster_time_not_frozen_across_repeated_executions(collection): observed.append(_read_cluster_time(collection)) collection.insert_one({"_id": i}) - result = execute_expression(collection, {"$gt": [{"$size": {"$setUnion": [observed]}}, 1]}) + saw_more_than_one_value = {"$gt": [{"$size": {"$setUnion": [observed]}}, 1]} + result = execute_expression_single_row(collection, saw_more_than_one_value) assert_expression_result( result, expected=True, @@ -523,7 +531,7 @@ def test_cluster_time_is_not_later_than_a_following_write(collection): value = _read_cluster_time(collection) write = execute_command(collection, {"insert": collection.name, "documents": [{"_id": 1}]}) - result = execute_expression(collection, {"$lte": [value, write["operationTime"]]}) + result = execute_expression_single_row(collection, {"$lte": [value, write["operationTime"]]}) assert_expression_result( result, expected=True, @@ -536,7 +544,7 @@ def test_cluster_time_is_not_earlier_than_a_preceding_write(collection): write = execute_command(collection, {"insert": collection.name, "documents": [{"_id": 1}]}) write_time = write["operationTime"] - result = execute_expression(collection, {"$gte": ["$$CLUSTER_TIME", write_time]}) + result = execute_expression_single_row(collection, {"$gte": ["$$CLUSTER_TIME", write_time]}) assert_expression_result( result, expected=True, @@ -554,7 +562,7 @@ def test_cluster_time_is_not_earlier_than_after_cluster_time(collection): collection, {"readConcern": {"level": "majority", "afterClusterTime": after}} ) - result = execute_expression(collection, {"$gte": [pipeline_value, after]}) + result = execute_expression_single_row(collection, {"$gte": [pipeline_value, after]}) assert_expression_result( result, expected=True, @@ -565,12 +573,13 @@ def test_cluster_time_is_not_earlier_than_after_cluster_time(collection): @pytest.mark.requires(cluster_read_concern=True) def test_cluster_time_resolves_under_majority_read_concern(collection): """Test the variable resolves to a timestamp under majority read concern.""" + collection.insert_one({}) + result = execute_command( collection, { - "aggregate": 1, + "aggregate": collection.name, "pipeline": [ - {"$documents": [{}]}, {"$project": {"_id": 0, "kind": {"$type": "$$CLUSTER_TIME"}}}, ], "cursor": {}, @@ -721,7 +730,7 @@ def test_cursor_value_survives_writes_landing_between_batches(collection): values = _drain_cursor(collection, first, batch_size=3, write_between=True) - result = execute_expression(collection, {"$size": {"$setUnion": [values]}}) + result = execute_expression_single_row(collection, {"$size": {"$setUnion": [values]}}) assert_expression_result( result, expected=1, @@ -743,7 +752,7 @@ def test_writes_between_batches_do_advance_the_deployment_clock(collection): cursor_value = first["cursor"]["firstBatch"][0]["t"] _drain_cursor(collection, first, batch_size=3, write_between=True) - result = execute_expression(collection, {"$gt": ["$$CLUSTER_TIME", cursor_value]}) + result = execute_expression_single_row(collection, {"$gt": ["$$CLUSTER_TIME", cursor_value]}) assert_expression_result( result, expected=True, @@ -776,7 +785,7 @@ def test_idle_cursor_resumes_with_the_same_value(collection): ) resumed_value = resumed["cursor"]["nextBatch"][0]["t"] - result = execute_expression(collection, {"$eq": [first_value, resumed_value]}) + result = execute_expression_single_row(collection, {"$eq": [first_value, resumed_value]}) assert_expression_result( result, expected=True, @@ -809,7 +818,7 @@ def test_change_stream_resolves_the_variable_for_its_events(collection): ) values = [doc["t"] for doc in batch["cursor"]["nextBatch"]] - result = execute_expression(collection, {"$type": {"$arrayElemAt": [values, 0]}}) + result = execute_expression_single_row(collection, {"$type": {"$arrayElemAt": [values, 0]}}) assert_expression_result( result, expected="timestamp", @@ -843,7 +852,7 @@ def test_change_stream_value_is_frozen_for_the_life_of_the_stream(collection): batch = execute_command(collection, {"getMore": cursor_id, "collection": collection.name}) observed.extend(doc["t"] for doc in batch["cursor"]["nextBatch"]) - result = execute_expression(collection, {"$size": {"$setUnion": [observed]}}) + result = execute_expression_single_row(collection, {"$size": {"$setUnion": [observed]}}) assert_expression_result( result, expected=1, diff --git a/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/cluster_time/test_cluster_time_write_paths.py b/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/cluster_time/test_cluster_time_write_paths.py index 330d63226..ffb3b92e5 100644 --- a/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/cluster_time/test_cluster_time_write_paths.py +++ b/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/cluster_time/test_cluster_time_write_paths.py @@ -14,6 +14,10 @@ import pytest from bson import Timestamp +from documentdb_tests.compatibility.tests.core.operator.expressions.utils.utils import ( + assert_expression_result, + execute_expression_single_row, +) from documentdb_tests.framework.assertions import assertSuccess, assertSuccessPartial from documentdb_tests.framework.executor import execute_admin_command, execute_command from documentdb_tests.framework.parametrize import pytest_params @@ -646,21 +650,11 @@ def test_repeated_pipeline_shape_is_not_constant_folded(collection): collection, {"aggregate": collection.name, "pipeline": pipeline, "cursor": {}} )["cursor"]["firstBatch"][0]["t"] - result = execute_command( - collection, - { - "aggregate": 1, - "pipeline": [ - {"$documents": [{}]}, - {"$project": {"_id": 0, "advanced": {"$lt": [first, second]}}}, - ], - "cursor": {}, - }, - ) + result = execute_expression_single_row(collection, {"$lt": [first, second]}) - assertSuccess( + assert_expression_result( result, - [{"advanced": True}], + expected=True, msg="The same pipeline shape should not fold $$CLUSTER_TIME into a cached plan", ) @@ -685,21 +679,11 @@ def test_explain_does_not_freeze_the_value_for_later_executions(collection): collection, {"aggregate": collection.name, "pipeline": pipeline, "cursor": {}} )["cursor"]["firstBatch"][0]["t"] - result = execute_command( - collection, - { - "aggregate": 1, - "pipeline": [ - {"$documents": [{}]}, - {"$project": {"_id": 0, "advanced": {"$lt": [first, second]}}}, - ], - "cursor": {}, - }, - ) + result = execute_expression_single_row(collection, {"$lt": [first, second]}) - assertSuccess( + assert_expression_result( result, - [{"advanced": True}], + expected=True, msg="An explain should not bake a resolved timestamp into later executions", ) @@ -797,21 +781,11 @@ def test_view_value_is_not_frozen_at_creation_time(collection): collection.insert_one({"_id": 2}) second = _view_value(collection, f"{collection.name}_view") - result = execute_command( - collection, - { - "aggregate": 1, - "pipeline": [ - {"$documents": [{}]}, - {"$project": {"_id": 0, "advanced": {"$lt": [first, second]}}}, - ], - "cursor": {}, - }, - ) + result = execute_expression_single_row(collection, {"$lt": [first, second]}) - assertSuccess( + assert_expression_result( result, - [{"advanced": True}], + expected=True, msg="A stored view definition must not freeze $$CLUSTER_TIME at creation time", ) @@ -839,21 +813,11 @@ def test_view_on_view_value_is_not_frozen_at_creation_time(collection): collection.insert_one({"_id": 2}) second = _view_value(collection, f"{collection.name}_outer_view") - result = execute_command( - collection, - { - "aggregate": 1, - "pipeline": [ - {"$documents": [{}]}, - {"$project": {"_id": 0, "advanced": {"$lt": [first, second]}}}, - ], - "cursor": {}, - }, - ) + result = execute_expression_single_row(collection, {"$lt": [first, second]}) - assertSuccess( + assert_expression_result( result, - [{"advanced": True}], + expected=True, msg="A view nested on a view must not freeze $$CLUSTER_TIME either", ) diff --git a/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/current/test_current_document_and_pipeline.py b/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/current/test_current_document_and_pipeline.py index f91cd81a8..02c684857 100644 --- a/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/current/test_current_document_and_pipeline.py +++ b/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/current/test_current_document_and_pipeline.py @@ -166,12 +166,14 @@ def test_current_pipeline_rescoping(collection, test: StageTestCase): def test_current_returns_empty_object_for_empty_document(collection): """$$CURRENT resolves to an empty object when the current document has no fields.""" + collection.insert_one({}) result = execute_command( collection, { - "aggregate": 1, + "aggregate": collection.name, "pipeline": [ - {"$documents": [{}]}, + # Exclude the inserted document's _id so the row has no fields. + {"$project": {"_id": 0}}, {"$project": {"_id": 0, "doc": "$$CURRENT"}}, ], "cursor": {}, diff --git a/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/now/test_now_core_semantics.py b/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/now/test_now_core_semantics.py index 8dc17e8ec..14777ff3a 100644 --- a/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/now/test_now_core_semantics.py +++ b/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/now/test_now_core_semantics.py @@ -14,6 +14,7 @@ from documentdb_tests.compatibility.tests.core.operator.expressions.utils.utils import ( assert_expression_result, execute_expression, + execute_expression_single_row, ) from documentdb_tests.framework.assertions import assertSuccess from documentdb_tests.framework.executor import execute_command @@ -81,19 +82,13 @@ def test_now_type_and_semantics(collection, test: ExpressionTestCase): def test_now_has_millisecond_resolution(collection): """Test $$NOW carries a non-zero millisecond component, proving sub-second granularity.""" + collection.insert_one({}) samples = [] for _ in range(MILLISECOND_SAMPLE_COUNT): - sample = execute_command( - collection, - { - "aggregate": 1, - "pipeline": [{"$documents": [{}]}, {"$project": {"_id": 0, "t": "$$NOW"}}], - "cursor": {}, - }, - ) - samples.append(sample["cursor"]["firstBatch"][0]["t"]) + sample = execute_expression_single_row(collection, "$$NOW") + samples.append(sample["cursor"]["firstBatch"][0]["result"]) - result = execute_expression( + result = execute_expression_single_row( collection, { "$gt": [ @@ -198,7 +193,7 @@ def test_now_identical_across_getmore_batches(collection): seen.extend(doc["t"] for doc in batch["cursor"]["nextBatch"]) cursor_id = batch["cursor"]["id"] - result = execute_expression(collection, {"$size": {"$setUnion": [seen]}}) + result = execute_expression_single_row(collection, {"$size": {"$setUnion": [seen]}}) assert_expression_result( result, expected=1, @@ -208,17 +203,11 @@ def test_now_identical_across_getmore_batches(collection): def test_now_advances_across_executions(collection): """Test $$NOW advances after a delay between two separate executions.""" - first = execute_command( - collection, - { - "aggregate": 1, - "pipeline": [{"$documents": [{}]}, {"$project": {"_id": 0, "t": "$$NOW"}}], - "cursor": {}, - }, - ) - earlier = first["cursor"]["firstBatch"][0]["t"] + collection.insert_one({}) + first = execute_expression_single_row(collection, "$$NOW") + earlier = first["cursor"]["firstBatch"][0]["result"] time.sleep(0.05) - result = execute_expression(collection, {"$gt": ["$$NOW", earlier]}) + result = execute_expression_single_row(collection, {"$gt": ["$$NOW", earlier]}) assert_expression_result( result, expected=True, diff --git a/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/now/test_now_date_operations.py b/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/now/test_now_date_operations.py index f01b29be4..e5b09deb7 100644 --- a/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/now/test_now_date_operations.py +++ b/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/now/test_now_date_operations.py @@ -204,12 +204,12 @@ def test_now_elapsed_milliseconds_from_stored_date(collection): def test_now_decodes_as_timezone_aware_utc(collection): """Test a $$NOW-derived date decodes as a timezone-aware UTC datetime.""" + collection.insert_one({}) result = execute_command( collection, { - "aggregate": 1, + "aggregate": collection.name, "pipeline": [ - {"$documents": [{}]}, {"$project": {"_id": 0, "t": "$$NOW"}}, ], "cursor": {}, diff --git a/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/root/test_root_core_behavior.py b/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/root/test_root_core_behavior.py index 22ed192ed..059ec5b5a 100644 --- a/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/root/test_root_core_behavior.py +++ b/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/root/test_root_core_behavior.py @@ -17,10 +17,10 @@ ) from documentdb_tests.compatibility.tests.core.operator.expressions.utils.utils import ( assert_expression_result, - execute_expression, execute_expression_with_insert, ) from documentdb_tests.framework.assertions import assertSuccess +from documentdb_tests.framework.executor import execute_command from documentdb_tests.framework.parametrize import pytest_params from documentdb_tests.framework.test_constants import DOUBLE_PRECISION_LOSS, INT64_MAX @@ -122,27 +122,32 @@ def test_root_echoes_doc(collection, test): # Property [Empty Document]: $$ROOT is an empty object when the input document has # no fields. -ROOT_EMPTY_DOCUMENT_TESTS: list[ExpressionTestCase] = [ - ExpressionTestCase( - id="empty_document", - expression="$$ROOT", - doc=None, - expected={}, - msg="$$ROOT should return an empty object when the input document has no fields", - ), -] - - -@pytest.mark.parametrize("test", pytest_params(ROOT_EMPTY_DOCUMENT_TESTS)) -def test_root_empty_document(collection, test): +def test_root_empty_document(collection): """$$ROOT over a field-less input document. - ``doc=None`` selects execute_expression, which evaluates the expression over - a ``$documents: [{}]`` stage rather than inserting a document, since an - inserted document would always be given an ``_id``. + This case needs a truly field-less input row, so it cannot use the shared + ``execute_expression`` helper: that helper inserts a document (which always + carries an auto-generated ``_id``), which would make ``$$ROOT`` a one-field + document. Instead a document is inserted and a ``{$project: {_id: 0}}`` stage + strips it back to a field-less row before ``$$ROOT`` is read. """ - result = execute_expression(collection, test.expression) - assert_expression_result(result, expected=test.expected, msg=test.msg) + collection.insert_one({}) + result = execute_command( + collection, + { + "aggregate": collection.name, + "pipeline": [ + {"$project": {"_id": 0}}, + {"$project": {"_id": 0, "result": "$$ROOT"}}, + ], + "cursor": {}, + }, + ) + assertSuccess( + result, + [{"result": {}}], + msg="$$ROOT should return an empty object when the input document has no fields", + ) # Property [Reported Type]: $$ROOT always reports BSON type "object". diff --git a/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/test_system_variables_now_expression_engine.py b/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/test_system_variables_now_expression_engine.py index 92a29fd42..cc5a8a7f9 100644 --- a/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/test_system_variables_now_expression_engine.py +++ b/documentdb_tests/compatibility/tests/core/operator/expressions/variable/system_variables/test_system_variables_now_expression_engine.py @@ -151,12 +151,12 @@ def test_now_identical_within_one_pipeline_execution(collection): def test_now_usable_as_date_expression_operand(collection): """$$NOW is usable as the date operand wherever one is accepted: a unary argument ($dateToParts), a named field ($dateTrunc), and a pair of arguments ($dateDiff).""" + collection.insert_one({}) result = execute_command( collection, { - "aggregate": 1, + "aggregate": collection.name, "pipeline": [ - {"$documents": [{}]}, { "$project": { "_id": 0, diff --git a/documentdb_tests/compatibility/tests/core/operator/stages/lookup/test_lookup_verbose_let_wiring.py b/documentdb_tests/compatibility/tests/core/operator/stages/lookup/test_lookup_verbose_let_wiring.py index c144fc611..1637c4925 100644 --- a/documentdb_tests/compatibility/tests/core/operator/stages/lookup/test_lookup_verbose_let_wiring.py +++ b/documentdb_tests/compatibility/tests/core/operator/stages/lookup/test_lookup_verbose_let_wiring.py @@ -250,13 +250,11 @@ "pipeline": [ { "$unionWith": { - "pipeline": [ - {"$documents": [{"src": "union"}]}, - {"$addFields": {"lv": "$$v"}}, - ] + "coll": FOREIGN, + "pipeline": [{"$addFields": {"lv": "$$v"}}], } }, - {"$project": {"_id": 0, "type": 1, "src": 1, "lv": 1}}, + {"$project": {"_id": 0, "type": 1, "lv": 1}}, ], "as": "joined", } @@ -266,7 +264,7 @@ { "_id": 1, "cat": "A", - "joined": [{"type": "A"}, {"src": "union", "lv": "A"}], + "joined": [{"type": "A"}, {"type": "A", "lv": "A"}], } ], msg="$lookup sub-pipeline $unionWith should resolve an outer let variable in " diff --git a/documentdb_tests/compatibility/tests/core/operator/stages/lookup/utils/lookup_common.py b/documentdb_tests/compatibility/tests/core/operator/stages/lookup/utils/lookup_common.py index 2858eb1dc..11510a2dc 100644 --- a/documentdb_tests/compatibility/tests/core/operator/stages/lookup/utils/lookup_common.py +++ b/documentdb_tests/compatibility/tests/core/operator/stages/lookup/utils/lookup_common.py @@ -59,7 +59,7 @@ def _substitute_foreign( pipeline: list[dict[str, Any]], foreign_name: str, ) -> list[dict[str, Any]]: - """Replace the FOREIGN sentinel in $lookup and $graphLookup 'from' fields. + """Replace the FOREIGN sentinel in $lookup/$graphLookup 'from' and $unionWith 'coll'. Recurses into nested $lookup sub-pipelines. """ @@ -87,6 +87,12 @@ def _substitute_foreign( spec = dict(spec) spec["from"] = foreign_name result[i] = {"$graphLookup": spec} + elif "$unionWith" in stage: + spec = stage["$unionWith"] + if isinstance(spec, dict) and spec.get("coll") is FOREIGN: + spec = dict(spec) + spec["coll"] = foreign_name + result[i] = {"$unionWith": spec} return result diff --git a/documentdb_tests/compatibility/tests/core/operator/test_operator_combination_setField_stages.py b/documentdb_tests/compatibility/tests/core/operator/test_operator_combination_setField_stages.py index 2d5ae6fe4..4acab544c 100644 --- a/documentdb_tests/compatibility/tests/core/operator/test_operator_combination_setField_stages.py +++ b/documentdb_tests/compatibility/tests/core/operator/test_operator_combination_setField_stages.py @@ -11,12 +11,12 @@ def test_setField_dotted_remove(collection): """Test removing a dotted field name.""" + collection.insert_one({}) result = execute_command( collection, { - "aggregate": 1, + "aggregate": collection.name, "pipeline": [ - {"$documents": [{}]}, { "$replaceWith": { "$setField": { @@ -35,12 +35,12 @@ def test_setField_dotted_remove(collection): def test_setField_dollar_remove(collection): """Test removing a dollar-prefixed field name.""" + collection.insert_one({}) result = execute_command( collection, { - "aggregate": 1, + "aggregate": collection.name, "pipeline": [ - {"$documents": [{}]}, { "$replaceWith": { "$setField": { diff --git a/documentdb_tests/compatibility/tests/core/operator/test_operator_combination_unsetField_stages.py b/documentdb_tests/compatibility/tests/core/operator/test_operator_combination_unsetField_stages.py index f56839bd7..f356dafaf 100644 --- a/documentdb_tests/compatibility/tests/core/operator/test_operator_combination_unsetField_stages.py +++ b/documentdb_tests/compatibility/tests/core/operator/test_operator_combination_unsetField_stages.py @@ -73,12 +73,12 @@ def test_unsetField_original_not_modified(collection): def test_unsetField_equivalence_dotted(collection): """Test $unsetField and $setField+$$REMOVE equivalence for dotted field.""" + collection.insert_one({}) result = execute_command( collection, { - "aggregate": 1, + "aggregate": collection.name, "pipeline": [ - {"$documents": [{}]}, { "$replaceWith": { "$unsetField": { @@ -96,12 +96,12 @@ def test_unsetField_equivalence_dotted(collection): def test_unsetField_equivalence_dollar(collection): """Test $unsetField and $setField+$$REMOVE equivalence for dollar field.""" + collection.insert_one({}) result = execute_command( collection, { - "aggregate": 1, + "aggregate": collection.name, "pipeline": [ - {"$documents": [{}]}, { "$replaceWith": { "$unsetField": { diff --git a/documentdb_tests/framework/test_format_validator.py b/documentdb_tests/framework/test_format_validator.py index 4a769dabf..2c3394942 100644 --- a/documentdb_tests/framework/test_format_validator.py +++ b/documentdb_tests/framework/test_format_validator.py @@ -31,6 +31,7 @@ def validate_test_format(file_path: str) -> list[str]: "execute_project", "execute_project_with_insert", "execute_expression", + "execute_expression_single_row", "execute_expression_with_insert", "execute_admin_with_retry_command", "run_window_operator",