From 0c75f4b500dc2f511432a34cd035e22683483d74 Mon Sep 17 00:00:00 2001 From: Samar Farooqi Date: Wed, 21 Oct 2026 21:16:09 +0000 Subject: [PATCH 1/3] Assert explain hash fields through assertProperties The explain queryShapeHash / planCacheShapeHash tests pulled the hash out of the explain result in local helpers and raised RuntimeError when the field was missing or explain failed. That failure happened before any assertion helper ran, so an engine that does not report these fields failed every case with an exception instead of an assertion result. Replace the four helpers with explain_find / _explain_aggregate, which only return the raw explain result, and a shared assert_hash_relation helper in diagnostic/utils/explain_hash.py. It checks in a single assertProperties call that both hashes are non-empty strings and that they are equal (same shape) or different (different shape). An explain error is passed to assertProperties and fails there with the server error. Behavior change: a different-shape test now fails when the second explain has no hash, where before Ne passed on a missing field. Test expectations are otherwise unchanged; 168/168 still pass on MongoDB 8.2.4. Signed-off-by: Samar Farooqi --- .../test_explain_queryhash_pipeline.py | 72 +++++----------- .../explain/test_explain_queryhash_shape.py | 84 +++++-------------- .../system/diagnostic/utils/explain_hash.py | 78 +++++++++++++++++ 3 files changed, 121 insertions(+), 113 deletions(-) create mode 100644 documentdb_tests/compatibility/tests/system/diagnostic/utils/explain_hash.py diff --git a/documentdb_tests/compatibility/tests/system/diagnostic/commands/explain/test_explain_queryhash_pipeline.py b/documentdb_tests/compatibility/tests/system/diagnostic/commands/explain/test_explain_queryhash_pipeline.py index b185d5f16..3e8fbca21 100644 --- a/documentdb_tests/compatibility/tests/system/diagnostic/commands/explain/test_explain_queryhash_pipeline.py +++ b/documentdb_tests/compatibility/tests/system/diagnostic/commands/explain/test_explain_queryhash_pipeline.py @@ -20,54 +20,34 @@ import pytest -from documentdb_tests.framework.assertions import assertProperties +from documentdb_tests.compatibility.tests.system.diagnostic.utils.explain_hash import ( + PLAN_CACHE_SHAPE_HASH, + QUERY_SHAPE_HASH, + assert_hash_relation, +) from documentdb_tests.framework.executor import execute_command from documentdb_tests.framework.parametrize import pytest_params -from documentdb_tests.framework.property_checks import Eq, Ne from documentdb_tests.framework.test_case import BaseTestCase pytestmark = pytest.mark.admin -def _get_plan_cache_shape_hash(collection, pipeline: list) -> str: - """Return queryPlanner.planCacheShapeHash from explain for an aggregate pipeline.""" - cmd: dict[str, Any] = { - "aggregate": collection.name, - "pipeline": pipeline, - "cursor": {}, - } - result = execute_command(collection, {"explain": cmd, "verbosity": "queryPlanner"}) - if isinstance(result, Exception): - raise RuntimeError(f"explain command failed: {result}") - # Standard format: queryPlanner at top level. - query_planner = result.get("queryPlanner", {}) - if "planCacheShapeHash" in query_planner: - return str(query_planner["planCacheShapeHash"]) - # Stages format ($out/$merge): nested under stages.0.$cursor.queryPlanner. - stages = result.get("stages", []) - if stages: - cursor_stage = stages[0].get("$cursor", {}) - qp = cursor_stage.get("queryPlanner", {}) - if "planCacheShapeHash" in qp: - return str(qp["planCacheShapeHash"]) - raise RuntimeError( - f"explain did not return planCacheShapeHash in expected location; got: {result}" - ) +# Explain reports planCacheShapeHash under queryPlanner for most pipelines, and +# under stages.0.$cursor.queryPlanner when the pipeline ends in $out or $merge. +PIPELINE_PLAN_CACHE_SHAPE_HASH = ( + PLAN_CACHE_SHAPE_HASH, + f"stages.0.$cursor.{PLAN_CACHE_SHAPE_HASH}", +) -def _get_query_shape_hash(collection, pipeline: list) -> str: - """Return the top-level queryShapeHash from explain for an aggregate pipeline.""" +def _explain_aggregate(collection, pipeline: list) -> Any: + """Run explain on an aggregate pipeline and return the raw result (or the exception).""" cmd: dict[str, Any] = { "aggregate": collection.name, "pipeline": pipeline, "cursor": {}, } - result = execute_command(collection, {"explain": cmd, "verbosity": "queryPlanner"}) - if isinstance(result, Exception): - raise RuntimeError(f"explain command failed: {result}") - if "queryShapeHash" not in result: - raise RuntimeError(f"explain did not return queryShapeHash; got: {result}") - return str(result["queryShapeHash"]) + return execute_command(collection, {"explain": cmd, "verbosity": "queryPlanner"}) @dataclass(frozen=True) @@ -361,14 +341,10 @@ def test_pipeline_plancacheshapehash_stage_sensitivity(collection, test): collection.insert_many( [{"_id": i, "a": i % 5, "b": i % 3, "arr": [i, i + 1], "sub": {"x": i}} for i in range(20)] ) - hash_a = _get_plan_cache_shape_hash(collection, list(test.pipeline_a)) - hash_b = _get_plan_cache_shape_hash(collection, list(test.pipeline_b)) - check = Eq(hash_b) if test.plan_cache_same else Ne(hash_b) - assertProperties( - {"planCacheShapeHash": hash_a}, - {"planCacheShapeHash": check}, - msg=test.msg, - raw_res=True, + result_a = _explain_aggregate(collection, list(test.pipeline_a)) + result_b = _explain_aggregate(collection, list(test.pipeline_b)) + assert_hash_relation( + result_a, result_b, PIPELINE_PLAN_CACHE_SHAPE_HASH, same=test.plan_cache_same, msg=test.msg ) @@ -378,12 +354,8 @@ def test_pipeline_queryshapehash_considers_all_stages(collection, test): collection.insert_many( [{"_id": i, "a": i % 5, "b": i % 3, "arr": [i, i + 1], "sub": {"x": i}} for i in range(20)] ) - hash_a = _get_query_shape_hash(collection, list(test.pipeline_a)) - hash_b = _get_query_shape_hash(collection, list(test.pipeline_b)) - check = Eq(hash_b) if test.query_shape_same else Ne(hash_b) - assertProperties( - {"queryShapeHash": hash_a}, - {"queryShapeHash": check}, - msg=test.msg, - raw_res=True, + result_a = _explain_aggregate(collection, list(test.pipeline_a)) + result_b = _explain_aggregate(collection, list(test.pipeline_b)) + assert_hash_relation( + result_a, result_b, QUERY_SHAPE_HASH, same=test.query_shape_same, msg=test.msg ) diff --git a/documentdb_tests/compatibility/tests/system/diagnostic/commands/explain/test_explain_queryhash_shape.py b/documentdb_tests/compatibility/tests/system/diagnostic/commands/explain/test_explain_queryhash_shape.py index 0de460033..05e7a7a59 100644 --- a/documentdb_tests/compatibility/tests/system/diagnostic/commands/explain/test_explain_queryhash_shape.py +++ b/documentdb_tests/compatibility/tests/system/diagnostic/commands/explain/test_explain_queryhash_shape.py @@ -10,23 +10,26 @@ import pytest -from documentdb_tests.framework.assertions import assertProperties +from documentdb_tests.compatibility.tests.system.diagnostic.utils.explain_hash import ( + PLAN_CACHE_SHAPE_HASH, + QUERY_SHAPE_HASH, + assert_hash_relation, +) from documentdb_tests.framework.executor import execute_command from documentdb_tests.framework.parametrize import pytest_params -from documentdb_tests.framework.property_checks import Eq, Ne from documentdb_tests.framework.test_case import BaseTestCase pytestmark = pytest.mark.admin -def get_query_hash( +def explain_find( collection, find_filter: dict, sort: Optional[dict] = None, projection: Optional[dict] = None, collation: Optional[dict] = None, -) -> str: - """Return queryPlanner.planCacheShapeHash from explain for a find filter.""" +) -> Any: + """Run explain on a find and return the raw result (or the exception).""" cmd: dict[str, Any] = {"find": collection.name, "filter": find_filter} if sort is not None: cmd["sort"] = sort @@ -34,36 +37,7 @@ def get_query_hash( cmd["projection"] = projection if collation is not None: cmd["collation"] = collation - result = execute_command(collection, {"explain": cmd, "verbosity": "queryPlanner"}) - if isinstance(result, Exception): - raise RuntimeError(f"explain command failed: {result}") - query_planner = result.get("queryPlanner", {}) - if "planCacheShapeHash" not in query_planner: - raise RuntimeError(f"explain did not return queryPlanner.planCacheShapeHash; got: {result}") - return str(query_planner["planCacheShapeHash"]) - - -def get_query_shape_hash( - collection, - find_filter: dict, - sort: Optional[dict] = None, - projection: Optional[dict] = None, - collation: Optional[dict] = None, -) -> str: - """Return the top-level queryShapeHash from explain for a find filter.""" - cmd: dict[str, Any] = {"find": collection.name, "filter": find_filter} - if sort is not None: - cmd["sort"] = sort - if projection is not None: - cmd["projection"] = projection - if collation is not None: - cmd["collation"] = collation - result = execute_command(collection, {"explain": cmd, "verbosity": "queryPlanner"}) - if isinstance(result, Exception): - raise RuntimeError(f"explain command failed: {result}") - if "queryShapeHash" not in result: - raise RuntimeError(f"explain did not return queryShapeHash; got: {result}") - return str(result["queryShapeHash"]) + return execute_command(collection, {"explain": cmd, "verbosity": "queryPlanner"}) @dataclass(frozen=True) @@ -297,18 +271,13 @@ def test_explain_queryhash_same_shape(collection, test): collection.insert_many( [{"_id": i, "a": i % 5, "b": i % 3, "arr": [i, i + 1], "s": str(i)} for i in range(20)] ) - hash_a = get_query_hash( + result_a = explain_find( collection, test.filter_a, test.sort_a, test.projection_a, test.collation_a ) - hash_b = get_query_hash( + result_b = explain_find( collection, test.filter_b, test.sort_b, test.projection_b, test.collation_b ) - assertProperties( - {"planCacheShapeHash": hash_a}, - {"planCacheShapeHash": Eq(hash_b)}, - msg=test.msg, - raw_res=True, - ) + assert_hash_relation(result_a, result_b, PLAN_CACHE_SHAPE_HASH, same=True, msg=test.msg) DIFF_SHAPE_TESTS: list[QueryHashCase] = [ @@ -516,18 +485,13 @@ def test_explain_queryhash_different_shape(collection, test): collection.insert_many( [{"_id": i, "a": i % 5, "b": i % 3, "arr": [i, i + 1], "s": str(i)} for i in range(20)] ) - hash_a = get_query_hash( + result_a = explain_find( collection, test.filter_a, test.sort_a, test.projection_a, test.collation_a ) - hash_b = get_query_hash( + result_b = explain_find( collection, test.filter_b, test.sort_b, test.projection_b, test.collation_b ) - assertProperties( - {"planCacheShapeHash": hash_a}, - {"planCacheShapeHash": Ne(hash_b)}, - msg=test.msg, - raw_res=True, - ) + assert_hash_relation(result_a, result_b, PLAN_CACHE_SHAPE_HASH, same=False, msg=test.msg) @pytest.mark.parametrize("test", pytest_params(SAME_SHAPE_TESTS)) @@ -542,16 +506,13 @@ def test_explain_queryshapehash_same_shape(collection, test): collection.insert_many( [{"_id": i, "a": i % 5, "b": i % 3, "arr": [i, i + 1], "s": str(i)} for i in range(20)] ) - hash_a = get_query_shape_hash( + result_a = explain_find( collection, test.filter_a, test.sort_a, test.projection_a, test.collation_a ) - hash_b = get_query_shape_hash( + result_b = explain_find( collection, test.filter_b, test.sort_b, test.projection_b, test.collation_b ) - check = Eq(hash_b) if expected_same else Ne(hash_b) - assertProperties( - {"queryShapeHash": hash_a}, {"queryShapeHash": check}, msg=test.msg, raw_res=True - ) + assert_hash_relation(result_a, result_b, QUERY_SHAPE_HASH, same=expected_same, msg=test.msg) @pytest.mark.parametrize("test", pytest_params(DIFF_SHAPE_TESTS)) @@ -565,13 +526,10 @@ def test_explain_queryshapehash_different_shape(collection, test): collection.insert_many( [{"_id": i, "a": i % 5, "b": i % 3, "arr": [i, i + 1], "s": str(i)} for i in range(20)] ) - hash_a = get_query_shape_hash( + result_a = explain_find( collection, test.filter_a, test.sort_a, test.projection_a, test.collation_a ) - hash_b = get_query_shape_hash( + result_b = explain_find( collection, test.filter_b, test.sort_b, test.projection_b, test.collation_b ) - check = Eq(hash_b) if expected_same else Ne(hash_b) - assertProperties( - {"queryShapeHash": hash_a}, {"queryShapeHash": check}, msg=test.msg, raw_res=True - ) + assert_hash_relation(result_a, result_b, QUERY_SHAPE_HASH, same=expected_same, msg=test.msg) diff --git a/documentdb_tests/compatibility/tests/system/diagnostic/utils/explain_hash.py b/documentdb_tests/compatibility/tests/system/diagnostic/utils/explain_hash.py new file mode 100644 index 000000000..1b7f48d42 --- /dev/null +++ b/documentdb_tests/compatibility/tests/system/diagnostic/utils/explain_hash.py @@ -0,0 +1,78 @@ +"""Helpers for comparing the query hashes that explain reports. + +The hash tests run explain on two queries and assert that their hashes match +(same shape) or differ (different shape). The helpers here keep the explain +result raw and do every check, including that the hash is present at all, +through a single ``assertProperties`` call. A failed explain or a missing hash +field is therefore reported as an assertion failure instead of an error raised +before the assertion. +""" + +from __future__ import annotations + +from typing import Any, Union + +from documentdb_tests.framework.assertions import assertProperties +from documentdb_tests.framework.property_checks import Eq, Ne, NonEmptyStr + +PLAN_CACHE_SHAPE_HASH = "queryPlanner.planCacheShapeHash" +"""Dotted path of the plan cache shape hash in a standard explain result.""" + +QUERY_SHAPE_HASH = "queryShapeHash" +"""Dotted path of the top-level query shape hash in an explain result.""" + + +def _lookup(result: Any, path: str) -> Any: + """Return the value at a dotted path (dict keys and list indices), or None when absent.""" + value: Any = result + for part in path.split("."): + if isinstance(value, list) and part.isdigit() and int(part) < len(value): + value = value[int(part)] + elif isinstance(value, dict) and part in value: + value = value[part] + else: + return None + return value + + +def assert_hash_relation( + result_a: Any, + result_b: Any, + paths: Union[str, tuple[str, ...]], + same: bool, + msg: str, +) -> None: + """Assert both explain results report a hash, and that the two hashes match or differ. + + Args: + result_a: Raw explain result (or exception) for the first query. + result_b: Raw explain result (or exception) for the second query. + paths: Dotted path of the hash, or several candidate paths tried in + order (for explain output whose layout depends on the pipeline). + same: True to assert the hashes are equal, False to assert they differ. + msg: Failure message. + """ + candidates = (paths,) if isinstance(paths, str) else paths + for result in (result_a, result_b): + if isinstance(result, Exception): + # The failed explain is the result under test: assert on it and stop, + # so it is reported once rather than again as two missing hashes. + assertProperties(result, {candidates[0]: NonEmptyStr()}, msg=msg, raw_res=True) + return + hashes: dict[str, str] = {} + for key, result in (("hash_a", result_a), ("hash_b", result_b)): + for path in candidates: + value = _lookup(result, path) + if value is not None: + hashes[key] = str(value) + break + # Compare only when the second hash exists; its absence is reported on its own. + checks_a: list[Any] = [NonEmptyStr()] + if "hash_b" in hashes: + checks_a.append(Eq(hashes["hash_b"]) if same else Ne(hashes["hash_b"])) + assertProperties( + hashes, + {"hash_a": checks_a, "hash_b": NonEmptyStr()}, + msg=f"{msg} (hash at {' or '.join(candidates)})", + raw_res=True, + ) From 9272874a68e931f042ebfa7a4c876e1cb623af79 Mon Sep 17 00:00:00 2001 From: Samar Farooqi Date: Thu, 5 Nov 2026 23:04:22 +0000 Subject: [PATCH 2/3] Move explain hash helper next to the explain tests explain_hash.py is used only by the explain queryShapeHash / planCacheShapeHash tests, so move it from system/diagnostic/utils/ to system/diagnostic/commands/explain/utils/ and import it relatively, as the other command-local utils packages are. No behavior change. Signed-off-by: Samar Farooqi --- .../commands/explain/test_explain_queryhash_pipeline.py | 9 +++++---- .../commands/explain/test_explain_queryhash_shape.py | 9 +++++---- .../system/diagnostic/commands/explain/utils/__init__.py | 0 .../{ => commands/explain}/utils/explain_hash.py | 0 4 files changed, 10 insertions(+), 8 deletions(-) create mode 100644 documentdb_tests/compatibility/tests/system/diagnostic/commands/explain/utils/__init__.py rename documentdb_tests/compatibility/tests/system/diagnostic/{ => commands/explain}/utils/explain_hash.py (100%) diff --git a/documentdb_tests/compatibility/tests/system/diagnostic/commands/explain/test_explain_queryhash_pipeline.py b/documentdb_tests/compatibility/tests/system/diagnostic/commands/explain/test_explain_queryhash_pipeline.py index 3e8fbca21..b8844974d 100644 --- a/documentdb_tests/compatibility/tests/system/diagnostic/commands/explain/test_explain_queryhash_pipeline.py +++ b/documentdb_tests/compatibility/tests/system/diagnostic/commands/explain/test_explain_queryhash_pipeline.py @@ -20,14 +20,15 @@ import pytest -from documentdb_tests.compatibility.tests.system.diagnostic.utils.explain_hash import ( +from documentdb_tests.framework.executor import execute_command +from documentdb_tests.framework.parametrize import pytest_params +from documentdb_tests.framework.test_case import BaseTestCase + +from .utils.explain_hash import ( PLAN_CACHE_SHAPE_HASH, QUERY_SHAPE_HASH, assert_hash_relation, ) -from documentdb_tests.framework.executor import execute_command -from documentdb_tests.framework.parametrize import pytest_params -from documentdb_tests.framework.test_case import BaseTestCase pytestmark = pytest.mark.admin diff --git a/documentdb_tests/compatibility/tests/system/diagnostic/commands/explain/test_explain_queryhash_shape.py b/documentdb_tests/compatibility/tests/system/diagnostic/commands/explain/test_explain_queryhash_shape.py index 05e7a7a59..f89b95ed3 100644 --- a/documentdb_tests/compatibility/tests/system/diagnostic/commands/explain/test_explain_queryhash_shape.py +++ b/documentdb_tests/compatibility/tests/system/diagnostic/commands/explain/test_explain_queryhash_shape.py @@ -10,14 +10,15 @@ import pytest -from documentdb_tests.compatibility.tests.system.diagnostic.utils.explain_hash import ( +from documentdb_tests.framework.executor import execute_command +from documentdb_tests.framework.parametrize import pytest_params +from documentdb_tests.framework.test_case import BaseTestCase + +from .utils.explain_hash import ( PLAN_CACHE_SHAPE_HASH, QUERY_SHAPE_HASH, assert_hash_relation, ) -from documentdb_tests.framework.executor import execute_command -from documentdb_tests.framework.parametrize import pytest_params -from documentdb_tests.framework.test_case import BaseTestCase pytestmark = pytest.mark.admin diff --git a/documentdb_tests/compatibility/tests/system/diagnostic/commands/explain/utils/__init__.py b/documentdb_tests/compatibility/tests/system/diagnostic/commands/explain/utils/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/documentdb_tests/compatibility/tests/system/diagnostic/utils/explain_hash.py b/documentdb_tests/compatibility/tests/system/diagnostic/commands/explain/utils/explain_hash.py similarity index 100% rename from documentdb_tests/compatibility/tests/system/diagnostic/utils/explain_hash.py rename to documentdb_tests/compatibility/tests/system/diagnostic/commands/explain/utils/explain_hash.py From 995fb6ede42613b19bacefa9fc59ba274c04b527 Mon Sep 17 00:00:00 2001 From: Samar Farooqi Date: Thu, 5 Nov 2026 23:04:38 +0000 Subject: [PATCH 3/3] Check explain hashes as reported and reuse the framework path walk assert_hash_relation stringified each hash before NonEmptyStr ran, so an int, document or Binary hash passed the check. Store the value as explain reported it; Eq / Ne still compare two string hashes the same way. Also drop the local _lookup helper and walk the dotted path with the framework's _walk_path, which returns the _FIELD_ABSENT sentinel for a missing field. _lookup returned None for a missing field, so a hash that was present but null was reported as "field is missing"; it is now reported as "got None". Signed-off-by: Samar Farooqi --- .../commands/explain/utils/explain_hash.py | 27 ++++++------------- 1 file changed, 8 insertions(+), 19 deletions(-) diff --git a/documentdb_tests/compatibility/tests/system/diagnostic/commands/explain/utils/explain_hash.py b/documentdb_tests/compatibility/tests/system/diagnostic/commands/explain/utils/explain_hash.py index 1b7f48d42..96ac0ce88 100644 --- a/documentdb_tests/compatibility/tests/system/diagnostic/commands/explain/utils/explain_hash.py +++ b/documentdb_tests/compatibility/tests/system/diagnostic/commands/explain/utils/explain_hash.py @@ -12,8 +12,8 @@ from typing import Any, Union -from documentdb_tests.framework.assertions import assertProperties -from documentdb_tests.framework.property_checks import Eq, Ne, NonEmptyStr +from documentdb_tests.framework.assertions import _walk_path, assertProperties +from documentdb_tests.framework.property_checks import _FIELD_ABSENT, Eq, Ne, NonEmptyStr PLAN_CACHE_SHAPE_HASH = "queryPlanner.planCacheShapeHash" """Dotted path of the plan cache shape hash in a standard explain result.""" @@ -22,19 +22,6 @@ """Dotted path of the top-level query shape hash in an explain result.""" -def _lookup(result: Any, path: str) -> Any: - """Return the value at a dotted path (dict keys and list indices), or None when absent.""" - value: Any = result - for part in path.split("."): - if isinstance(value, list) and part.isdigit() and int(part) < len(value): - value = value[int(part)] - elif isinstance(value, dict) and part in value: - value = value[part] - else: - return None - return value - - def assert_hash_relation( result_a: Any, result_b: Any, @@ -59,12 +46,14 @@ def assert_hash_relation( # so it is reported once rather than again as two missing hashes. assertProperties(result, {candidates[0]: NonEmptyStr()}, msg=msg, raw_res=True) return - hashes: dict[str, str] = {} + # Keep each hash as explain reported it, so NonEmptyStr sees its real type + # and a present-but-null hash is reported as None rather than as missing. + hashes: dict[str, Any] = {} for key, result in (("hash_a", result_a), ("hash_b", result_b)): for path in candidates: - value = _lookup(result, path) - if value is not None: - hashes[key] = str(value) + value = _walk_path(result, path) + if value is not _FIELD_ABSENT: + hashes[key] = value break # Compare only when the second hash exists; its absence is reported on its own. checks_a: list[Any] = [NonEmptyStr()]