From 2b7e42c2685824d9907d422170ea3f52154d1e52 Mon Sep 17 00:00:00 2001 From: Yunxuan Shi Date: Thu, 6 Aug 2026 16:16:19 -0700 Subject: [PATCH 1/9] Remove $documents dependency from expression test helpers The expression compatibility tests use a collectionless `{aggregate: 1}` + `$documents: [{}]` pipeline purely as a scaffold to feed a single empty document into $project. They do not test $documents itself, yet they inherit a hard dependency on $documents support from the shared helpers. Swap the scaffold for `collection.insert_one({})` plus an aggregate over the named collection. This is logically identical: both feed exactly one empty document to $project, so literal expressions and field references (which resolve to missing against an empty doc) behave the same. The `collection` fixture is function-scoped, so each test still runs against a fresh single-document collection. Updates the two shared helpers (execute_expression, execute_project) that ~205 files inherit, plus two inline call sites in test_expressions_combination_variables.py. The _with_insert sibling helpers are unchanged. Signed-off-by: Yunxuan Shi Signed-off-by: Samar Farooqi --- .../test_expressions_combination_variables.py | 8 +++--- .../core/operator/expressions/utils/utils.py | 25 +++++++++++++------ 2 files changed, 22 insertions(+), 11 deletions(-) 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..f4abbae74 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,12 @@ 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. + Args: collection: MongoDB collection object project: Fields to project. Do not include _id; the function always @@ -51,12 +57,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 +106,15 @@ def execute_project_with_insert(collection, document, project): def execute_expression(collection, expression): """ - Execute an aggregation expression using $documents stage. + Execute an aggregation expression against a single empty document. - Evaluates an expression against an empty document using the $documents - stage. Useful for testing expressions with literal values. + 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; field references resolve to missing, just + as they would against a ``$documents: [{}]`` row. Args: collection: MongoDB collection object @@ -117,12 +128,12 @@ 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": 1, + "aggregate": collection.name, "pipeline": [ - {"$documents": [{}]}, {"$project": {"_id": 0, "result": expression}}, ], "cursor": {}, From eb66ca9d7e4cf24d9d60eedf2cbf23be52dda7b6 Mon Sep 17 00:00:00 2001 From: Yunxuan Shi Date: Thu, 6 Aug 2026 18:22:11 -0700 Subject: [PATCH 2/9] Fix $$ROOT/$$NOW system-variable tests broken by helper change The $documents-removal commit made execute_expression/execute_project insert a document and aggregate over the whole collection. Two newly synced system-variable tests relied on the old $documents:[{}] contract and broke: - test_root_empty_document: needs a truly field-less input so $$ROOT is {}, but an inserted doc always carries an auto _id. It now shapes its own pipeline ($replaceWith:{$literal:{}}) instead of the shared helper. - test_now_identical_across_getmore_batches: pre-loads 300 docs, so the whole-collection helper emitted 300 rows. It now uses an inline pipeline with $limit:1 to collapse to the single expected row. The shared helpers stay on plain insert_one({}) so the ~359 literal expression call sites gain no $replaceWith/$limit dependency. Signed-off-by: Yunxuan Shi Signed-off-by: Samar Farooqi --- .../core/operator/expressions/utils/utils.py | 14 ++++++ .../now/test_now_core_semantics.py | 19 ++++++-- .../root/test_root_core_behavior.py | 43 +++++++++++-------- 3 files changed, 54 insertions(+), 22 deletions(-) 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 f4abbae74..f8d45ce5e 100644 --- a/documentdb_tests/compatibility/tests/core/operator/expressions/utils/utils.py +++ b/documentdb_tests/compatibility/tests/core/operator/expressions/utils/utils.py @@ -45,6 +45,13 @@ def execute_project(collection, project): 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`` and the helper + aggregates over the whole collection. The output projection excludes ``_id``, + so literal expressions and missing-field references behave identically to a + ``$documents: [{}]`` row. 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 @@ -116,6 +123,13 @@ def execute_expression(collection, expression): expressions with literal values; field references resolve to missing, just as they would against a ``$documents: [{}]`` row. + Note: the inserted document carries an auto-generated ``_id`` and the helper + aggregates over the whole collection. The output projection excludes ``_id``, + so literal expressions and missing-field references are unaffected. 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 expression: The expression to evaluate (e.g., {"$add": [1, 2]}) 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..bf1db1b59 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 @@ -198,10 +198,23 @@ 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]}}) - assert_expression_result( + # The collection is pre-populated (300 docs), so ``execute_expression`` — which + # aggregates over the whole collection — would emit one row per document. A + # ``$limit: 1`` reduces it to the single row this assertion expects. + result = execute_command( + collection, + { + "aggregate": collection.name, + "pipeline": [ + {"$limit": 1}, + {"$project": {"_id": 0, "result": {"$size": {"$setUnion": [seen]}}}}, + ], + "cursor": {}, + }, + ) + assertSuccess( result, - expected=1, + [{"result": 1}], msg="$$NOW should be identical across every getMore batch of one 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..38b93ab90 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 ``$replaceWith: {$literal: {}}`` + 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": [ + {"$replaceWith": {"$literal": {}}}, + {"$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". From 71bb0d4cece129ad5e84727e1e41a90a459d25eb Mon Sep 17 00:00:00 2001 From: Yunxuan Shi Date: Wed, 12 Aug 2026 15:23:22 -0700 Subject: [PATCH 3/9] CI: raise mongod nofile limit and fail fast when a target dies The replica-set test job was hitting GitHub's 6h max execution limit. Root cause: the suite creates and drops tens of thousands of collections per run; WiredTiger keeps an open fd per table it has touched (closing idle ones only very lazily) and, on the replica set, dropped collections become drop-pending idents whose files linger until majority-committed and swept. So the descriptor count tracks total collections created over the run, not the number live at once, and mid-run mongod runs out of descriptors. That surfaces as a WiredTiger WT_PANIC (EMFILE -> fassert) and crashes the server; every remaining test then blocks on connection timeouts and the job crawls for hours. Standalone is unaffected because it reclaims dropped tables immediately and never approaches the ceiling. Two changes: 1. Raise ulimits.nofile to 1048576 (the limit MongoDB's own packaging ships) on both mongod targets. The replica set peaks near 60k open files partway through the suite; 64000 was not enough headroom -- it still crashed at ~31k collections -- so this is set well above the peak. 2. Add a target-death watchdog and a per-test --timeout to the test job so that if a target ever does die mid-run, the job fails in about a minute instead of timing out every remaining test against a dead target for hours. The watchdog sanity-checks its probe first and steps aside if it cannot read a healthy baseline, so it cannot false-abort a healthy run. Signed-off-by: Yunxuan Shi Signed-off-by: Samar Farooqi --- .github/workflows/pr-tests.yml | 45 +++++++++++++++++++++++++++++++++- dev/compose.yaml | 31 +++++++++++++++++++++++ 2 files changed, 75 insertions(+), 1 deletion(-) diff --git a/.github/workflows/pr-tests.yml b/.github/workflows/pr-tests.yml index 30e583619..cec3aa14e 100644 --- a/.github/workflows/pr-tests.yml +++ b/.github/workflows/pr-tests.yml @@ -83,13 +83,56 @@ 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 + 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 + if [ "$(docker compose -f dev/compose.yaml --profile "$PROFILE" ps --status running -q 2>/dev/null | grep -c .)" -lt "$expected" ]; 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 + 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..e2c2fc80d 100644 --- a/dev/compose.yaml +++ b/dev/compose.yaml @@ -37,6 +37,23 @@ # 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) in its handle +# cache, closing idle ones only lazily. 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. WiredTiger also keeps a file handle open per table it has +# touched and closes idle ones only very lazily, so the descriptor count tracks +# the number of collections created over the run, not the number live at once. +# 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 +61,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 +103,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: From c79545a76a40132390bc896fa82cabb25f5a4c42 Mon Sep 17 00:00:00 2001 From: Yunxuan Shi Date: Wed, 12 Aug 2026 17:32:00 -0700 Subject: [PATCH 4/9] Fix 11 $$CLUSTER_TIME tests broken by the collection-backed helper These tests write documents to advance the logical clock (the behavior under test), then assert a variable/literal expression via execute_expression. The old helper ran collectionless ($documents: [{}]) so those writes never affected it. The new helper aggregates over collection.name, so every document the test wrote becomes an output row -- the assertion expected [{result: X}] but got one identical row per document. Each affected assertion evaluates only $$CLUSTER_TIME and Python-computed literals (never a document field), so the value is identical on any row. Add {$limit: 1} to collapse the aggregation to the single-row evaluation the $documents scaffold used to provide -- preserving exactly what each test verifies without reintroducing the $documents dependency this PR removes. This is the same shaping the PR already applied to test_now_identical_across_getmore_batches. The 5 tests whose collection stays empty are unaffected and still use the helper directly. Signed-off-by: Yunxuan Shi Signed-off-by: Samar Farooqi --- .../test_cluster_time_clock_progression.py | 133 ++++++++++++++++-- 1 file changed, 121 insertions(+), 12 deletions(-) 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..1ac073cb1 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 @@ -429,7 +429,17 @@ 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_command( + collection, + { + "aggregate": collection.name, + "pipeline": [ + {"$limit": 1}, + {"$project": {"_id": 0, "result": {"$gt": ["$$CLUSTER_TIME", earlier]}}}, + ], + "cursor": {}, + }, + ) assert_expression_result( result, expected=True, @@ -444,9 +454,17 @@ def test_cluster_time_monotonic_across_repeated_executions(collection): observed.append(_read_cluster_time(collection)) collection.insert_one({"_id": i}) - result = execute_expression( + non_decreasing = {"$eq": [{"$sortArray": {"input": observed, "sortBy": 1}}, observed]} + result = execute_command( collection, - {"$eq": [{"$sortArray": {"input": observed, "sortBy": 1}}, observed]}, + { + "aggregate": collection.name, + "pipeline": [ + {"$limit": 1}, + {"$project": {"_id": 0, "result": non_decreasing}}, + ], + "cursor": {}, + }, ) assert_expression_result( result, @@ -462,7 +480,18 @@ 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_command( + collection, + { + "aggregate": collection.name, + "pipeline": [ + {"$limit": 1}, + {"$project": {"_id": 0, "result": saw_more_than_one_value}}, + ], + "cursor": {}, + }, + ) assert_expression_result( result, expected=True, @@ -523,7 +552,17 @@ 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_command( + collection, + { + "aggregate": collection.name, + "pipeline": [ + {"$limit": 1}, + {"$project": {"_id": 0, "result": {"$lte": [value, write["operationTime"]]}}}, + ], + "cursor": {}, + }, + ) assert_expression_result( result, expected=True, @@ -536,7 +575,17 @@ 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_command( + collection, + { + "aggregate": collection.name, + "pipeline": [ + {"$limit": 1}, + {"$project": {"_id": 0, "result": {"$gte": ["$$CLUSTER_TIME", write_time]}}}, + ], + "cursor": {}, + }, + ) assert_expression_result( result, expected=True, @@ -554,7 +603,17 @@ 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_command( + collection, + { + "aggregate": collection.name, + "pipeline": [ + {"$limit": 1}, + {"$project": {"_id": 0, "result": {"$gte": [pipeline_value, after]}}}, + ], + "cursor": {}, + }, + ) assert_expression_result( result, expected=True, @@ -721,7 +780,17 @@ 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_command( + collection, + { + "aggregate": collection.name, + "pipeline": [ + {"$limit": 1}, + {"$project": {"_id": 0, "result": {"$size": {"$setUnion": [values]}}}}, + ], + "cursor": {}, + }, + ) assert_expression_result( result, expected=1, @@ -743,7 +812,17 @@ 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_command( + collection, + { + "aggregate": collection.name, + "pipeline": [ + {"$limit": 1}, + {"$project": {"_id": 0, "result": {"$gt": ["$$CLUSTER_TIME", cursor_value]}}}, + ], + "cursor": {}, + }, + ) assert_expression_result( result, expected=True, @@ -776,7 +855,17 @@ 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_command( + collection, + { + "aggregate": collection.name, + "pipeline": [ + {"$limit": 1}, + {"$project": {"_id": 0, "result": {"$eq": [first_value, resumed_value]}}}, + ], + "cursor": {}, + }, + ) assert_expression_result( result, expected=True, @@ -809,7 +898,17 @@ 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_command( + collection, + { + "aggregate": collection.name, + "pipeline": [ + {"$limit": 1}, + {"$project": {"_id": 0, "result": {"$type": {"$arrayElemAt": [values, 0]}}}}, + ], + "cursor": {}, + }, + ) assert_expression_result( result, expected="timestamp", @@ -843,7 +942,17 @@ 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_command( + collection, + { + "aggregate": collection.name, + "pipeline": [ + {"$limit": 1}, + {"$project": {"_id": 0, "result": {"$size": {"$setUnion": [observed]}}}}, + ], + "cursor": {}, + }, + ) assert_expression_result( result, expected=1, From 9c64031fdb7919f0da57f17a5eed4013c09e0724 Mon Sep 17 00:00:00 2001 From: Yunxuan Shi Date: Wed, 12 Aug 2026 18:10:31 -0700 Subject: [PATCH 5/9] Address review: harden target watchdog and clarify helper docstrings Watchdog (pr-tests.yml): require two consecutive low container-count readings before aborting. A single reading of the resource-heavy suite's `docker compose ps` can transiently error and read as 0, which would false-abort a healthy run; a real crash stays low across polls, so this rules out the false abort while adding at most one poll interval to a genuine fast-fail. Helper docstrings (utils.py): the insert+aggregate form leaves the input row with an auto-generated `_id` rather than the field-less row `$documents: [{}]` produced, so note that an expression reading `$_id`, `$$ROOT`, or `$$CURRENT` sees that id and diverges (references to any other missing field are still identical). Documentation only; no behavior change. Signed-off-by: Yunxuan Shi Signed-off-by: Samar Farooqi --- .github/workflows/pr-tests.yml | 23 +++++++++---- .../core/operator/expressions/utils/utils.py | 34 +++++++++++-------- 2 files changed, 36 insertions(+), 21 deletions(-) diff --git a/.github/workflows/pr-tests.yml b/.github/workflows/pr-tests.yml index cec3aa14e..74f5c724b 100644 --- a/.github/workflows/pr-tests.yml +++ b/.github/workflows/pr-tests.yml @@ -92,7 +92,7 @@ jobs: PROFILE='${{ matrix.target.profile }}' watch_target() { set +e - local pid=$1 expected + 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, @@ -103,11 +103,22 @@ jobs: return fi while kill -0 "$pid" 2>/dev/null; do - if [ "$(docker compose -f dev/compose.yaml --profile "$PROFILE" ps --status running -q 2>/dev/null | grep -c .)" -lt "$expected" ]; 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 + 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 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 f8d45ce5e..7918d55e6 100644 --- a/documentdb_tests/compatibility/tests/core/operator/expressions/utils/utils.py +++ b/documentdb_tests/compatibility/tests/core/operator/expressions/utils/utils.py @@ -45,12 +45,14 @@ def execute_project(collection, project): 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`` and the helper - aggregates over the whole collection. The output projection excludes ``_id``, - so literal expressions and missing-field references behave identically to a - ``$documents: [{}]`` row. 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. + 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 @@ -120,15 +122,17 @@ def execute_expression(collection, expression): 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; field references resolve to missing, just - as they would against a ``$documents: [{}]`` row. - - Note: the inserted document carries an auto-generated ``_id`` and the helper - aggregates over the whole collection. The output projection excludes ``_id``, - so literal expressions and missing-field references are unaffected. 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. + 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 ``{}``) or exactly one row over a pre-populated collection must shape their + own pipeline instead of using this helper. Args: collection: MongoDB collection object From 6cff5335481ec53fa55292a782e339f9e3fc5d7d Mon Sep 17 00:00:00 2001 From: Samar Farooqi Date: Thu, 5 Nov 2026 23:15:14 +0000 Subject: [PATCH 6/9] Add execute_expression_single_row helper Several tests evaluate a final expression over a collection they have already populated, where execute_expression would emit one row per document. They each hand-wrote an aggregate with $limit: 1 and a $project. Add a shared helper for that shape that evaluates the expression once and does not insert, and register it with the test format validator. Signed-off-by: Samar Farooqi --- .../core/operator/expressions/utils/utils.py | 43 ++++++++++++++++++- .../framework/test_format_validator.py | 1 + 2 files changed, 42 insertions(+), 2 deletions(-) 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 7918d55e6..e70d52dc4 100644 --- a/documentdb_tests/compatibility/tests/core/operator/expressions/utils/utils.py +++ b/documentdb_tests/compatibility/tests/core/operator/expressions/utils/utils.py @@ -131,8 +131,10 @@ def execute_expression(collection, expression): 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 ``{}``) or exactly one row over a pre-populated collection must shape their - own pipeline instead of using this helper. + 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 @@ -159,6 +161,43 @@ def execute_expression(collection, expression): ) +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": collection.name, + "pipeline": [ + {"$limit": 1}, + {"$project": {"_id": 0, "result": expression}}, + ], + "cursor": {}, + }, + ) + + def execute_expression_with_insert(collection, expression, document): """ Execute an aggregation expression with values from an inserted document. 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", From be2c0c8ee528e71ec662959707e0794d4970f44c Mon Sep 17 00:00:00 2001 From: Samar Farooqi Date: Thu, 5 Nov 2026 23:15:16 +0000 Subject: [PATCH 7/9] Remove $documents scaffolding from system variable tests Convert the remaining system variable tests that used $documents only to produce an input row so they run over the test collection instead: - Use execute_expression_single_row for the hand-written single-row aggregates in the $$CLUSTER_TIME and $$NOW tests and for the comparisons that used a $documents row. - Read $$CLUSTER_TIME from a one-document side collection in the same database, seeded once, so reads add nothing to the test's own collection and stay write-free after the first one. - Build the field-less row for $$ROOT and $$CURRENT by inserting a document and excluding _id with $project. - Insert a document and aggregate over the collection for the remaining $$NOW and majority read concern cases. Signed-off-by: Samar Farooqi --- .../test_cluster_time_clock_progression.py | 170 ++++-------------- .../test_cluster_time_write_paths.py | 68 ++----- .../test_current_document_and_pipeline.py | 6 +- .../now/test_now_core_semantics.py | 48 ++--- .../now/test_now_date_operations.py | 4 +- .../root/test_root_core_behavior.py | 4 +- ..._system_variables_now_expression_engine.py | 4 +- 7 files changed, 73 insertions(+), 231 deletions(-) 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 1ac073cb1..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,17 +438,7 @@ def test_cluster_time_advances_after_a_write(collection): earlier = _read_cluster_time(collection) collection.insert_one({"_id": "advance"}) - result = execute_command( - collection, - { - "aggregate": collection.name, - "pipeline": [ - {"$limit": 1}, - {"$project": {"_id": 0, "result": {"$gt": ["$$CLUSTER_TIME", earlier]}}}, - ], - "cursor": {}, - }, - ) + result = execute_expression_single_row(collection, {"$gt": ["$$CLUSTER_TIME", earlier]}) assert_expression_result( result, expected=True, @@ -455,17 +454,7 @@ def test_cluster_time_monotonic_across_repeated_executions(collection): collection.insert_one({"_id": i}) non_decreasing = {"$eq": [{"$sortArray": {"input": observed, "sortBy": 1}}, observed]} - result = execute_command( - collection, - { - "aggregate": collection.name, - "pipeline": [ - {"$limit": 1}, - {"$project": {"_id": 0, "result": non_decreasing}}, - ], - "cursor": {}, - }, - ) + result = execute_expression_single_row(collection, non_decreasing) assert_expression_result( result, expected=True, @@ -481,17 +470,7 @@ def test_cluster_time_not_frozen_across_repeated_executions(collection): collection.insert_one({"_id": i}) saw_more_than_one_value = {"$gt": [{"$size": {"$setUnion": [observed]}}, 1]} - result = execute_command( - collection, - { - "aggregate": collection.name, - "pipeline": [ - {"$limit": 1}, - {"$project": {"_id": 0, "result": saw_more_than_one_value}}, - ], - "cursor": {}, - }, - ) + result = execute_expression_single_row(collection, saw_more_than_one_value) assert_expression_result( result, expected=True, @@ -552,17 +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_command( - collection, - { - "aggregate": collection.name, - "pipeline": [ - {"$limit": 1}, - {"$project": {"_id": 0, "result": {"$lte": [value, write["operationTime"]]}}}, - ], - "cursor": {}, - }, - ) + result = execute_expression_single_row(collection, {"$lte": [value, write["operationTime"]]}) assert_expression_result( result, expected=True, @@ -575,17 +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_command( - collection, - { - "aggregate": collection.name, - "pipeline": [ - {"$limit": 1}, - {"$project": {"_id": 0, "result": {"$gte": ["$$CLUSTER_TIME", write_time]}}}, - ], - "cursor": {}, - }, - ) + result = execute_expression_single_row(collection, {"$gte": ["$$CLUSTER_TIME", write_time]}) assert_expression_result( result, expected=True, @@ -603,17 +562,7 @@ def test_cluster_time_is_not_earlier_than_after_cluster_time(collection): collection, {"readConcern": {"level": "majority", "afterClusterTime": after}} ) - result = execute_command( - collection, - { - "aggregate": collection.name, - "pipeline": [ - {"$limit": 1}, - {"$project": {"_id": 0, "result": {"$gte": [pipeline_value, after]}}}, - ], - "cursor": {}, - }, - ) + result = execute_expression_single_row(collection, {"$gte": [pipeline_value, after]}) assert_expression_result( result, expected=True, @@ -624,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": {}, @@ -780,17 +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_command( - collection, - { - "aggregate": collection.name, - "pipeline": [ - {"$limit": 1}, - {"$project": {"_id": 0, "result": {"$size": {"$setUnion": [values]}}}}, - ], - "cursor": {}, - }, - ) + result = execute_expression_single_row(collection, {"$size": {"$setUnion": [values]}}) assert_expression_result( result, expected=1, @@ -812,17 +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_command( - collection, - { - "aggregate": collection.name, - "pipeline": [ - {"$limit": 1}, - {"$project": {"_id": 0, "result": {"$gt": ["$$CLUSTER_TIME", cursor_value]}}}, - ], - "cursor": {}, - }, - ) + result = execute_expression_single_row(collection, {"$gt": ["$$CLUSTER_TIME", cursor_value]}) assert_expression_result( result, expected=True, @@ -855,17 +785,7 @@ def test_idle_cursor_resumes_with_the_same_value(collection): ) resumed_value = resumed["cursor"]["nextBatch"][0]["t"] - result = execute_command( - collection, - { - "aggregate": collection.name, - "pipeline": [ - {"$limit": 1}, - {"$project": {"_id": 0, "result": {"$eq": [first_value, resumed_value]}}}, - ], - "cursor": {}, - }, - ) + result = execute_expression_single_row(collection, {"$eq": [first_value, resumed_value]}) assert_expression_result( result, expected=True, @@ -898,17 +818,7 @@ def test_change_stream_resolves_the_variable_for_its_events(collection): ) values = [doc["t"] for doc in batch["cursor"]["nextBatch"]] - result = execute_command( - collection, - { - "aggregate": collection.name, - "pipeline": [ - {"$limit": 1}, - {"$project": {"_id": 0, "result": {"$type": {"$arrayElemAt": [values, 0]}}}}, - ], - "cursor": {}, - }, - ) + result = execute_expression_single_row(collection, {"$type": {"$arrayElemAt": [values, 0]}}) assert_expression_result( result, expected="timestamp", @@ -942,17 +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_command( - collection, - { - "aggregate": collection.name, - "pipeline": [ - {"$limit": 1}, - {"$project": {"_id": 0, "result": {"$size": {"$setUnion": [observed]}}}}, - ], - "cursor": {}, - }, - ) + 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 bf1db1b59..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,40 +193,21 @@ def test_now_identical_across_getmore_batches(collection): seen.extend(doc["t"] for doc in batch["cursor"]["nextBatch"]) cursor_id = batch["cursor"]["id"] - # The collection is pre-populated (300 docs), so ``execute_expression`` — which - # aggregates over the whole collection — would emit one row per document. A - # ``$limit: 1`` reduces it to the single row this assertion expects. - result = execute_command( - collection, - { - "aggregate": collection.name, - "pipeline": [ - {"$limit": 1}, - {"$project": {"_id": 0, "result": {"$size": {"$setUnion": [seen]}}}}, - ], - "cursor": {}, - }, - ) - assertSuccess( + result = execute_expression_single_row(collection, {"$size": {"$setUnion": [seen]}}) + assert_expression_result( result, - [{"result": 1}], + expected=1, msg="$$NOW should be identical across every getMore batch of one cursor", ) 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 38b93ab90..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 @@ -128,7 +128,7 @@ def test_root_empty_document(collection): 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 ``$replaceWith: {$literal: {}}`` + document. Instead a document is inserted and a ``{$project: {_id: 0}}`` stage strips it back to a field-less row before ``$$ROOT`` is read. """ collection.insert_one({}) @@ -137,7 +137,7 @@ def test_root_empty_document(collection): { "aggregate": collection.name, "pipeline": [ - {"$replaceWith": {"$literal": {}}}, + {"$project": {"_id": 0}}, {"$project": {"_id": 0, "result": "$$ROOT"}}, ], "cursor": {}, 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, From e988c9b6a231af2aa3867212ffab3c00010a3581 Mon Sep 17 00:00:00 2001 From: Samar Farooqi Date: Thu, 5 Nov 2026 23:15:17 +0000 Subject: [PATCH 8/9] Remove $documents scaffolding from field, string, and lookup tests - $setField/$unsetField: insert a document and aggregate over the collection; the stages build their output from literals. - Max-length string: pass the string as a $literal, since a document holding it would exceed the maximum document size. - $lookup let wiring: $unionWith the foreign collection instead of a $documents source, and substitute the FOREIGN sentinel in $unionWith.coll. Signed-off-by: Samar Farooqi --- .../data-types/bson_types/types/test_types_string.py | 8 +++++--- .../stages/lookup/test_lookup_verbose_let_wiring.py | 10 ++++------ .../core/operator/stages/lookup/utils/lookup_common.py | 8 +++++++- .../test_operator_combination_setField_stages.py | 8 ++++---- .../test_operator_combination_unsetField_stages.py | 8 ++++---- 5 files changed, 24 insertions(+), 18 deletions(-) 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/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": { From f5fb056d9546a9fa79f167bfbc1bf44180771a1f Mon Sep 17 00:00:00 2001 From: Samar Farooqi Date: Thu, 5 Nov 2026 23:15:18 +0000 Subject: [PATCH 9/9] Deduplicate the open-file note in dev/compose.yaml The header described WiredTiger's lazy file-handle closing twice. Merge it into one sentence. Signed-off-by: Samar Farooqi --- dev/compose.yaml | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/dev/compose.yaml b/dev/compose.yaml index e2c2fc80d..4ab97e7a1 100644 --- a/dev/compose.yaml +++ b/dev/compose.yaml @@ -40,14 +40,12 @@ # # 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) in its handle -# cache, closing idle ones only lazily. 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. WiredTiger also keeps a file handle open per table it has -# touched and closes idle ones only very lazily, so the descriptor count tracks -# the number of collections created over the run, not the number live at once. -# The replica set peaks near 60k open files partway through the suite; when that +# 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