From 684676e57e31ea78162783a1eea545b397e49659 Mon Sep 17 00:00:00 2001 From: evanchooly Date: Mon, 23 Nov 2026 08:20:11 -0500 Subject: [PATCH] Compare declared result arrays as multisets and convert the $graphLookup cases A scenario's comparison.unorderedArrays names result arrays, by pointer within each result, that the server builds in no defined order. The strict and printed-result comparators in both the audits module and core match them as multisets, held together by new golden vectors. A form-review declaration lists each with its evidence; capture checks it and carries it into the scenario. Both $graphLookup cases declare the array $graphLookup builds, convert, and pass under both mappers; their bodies now look up the documented collections, recorded as reviewed body edits. Closes #4562. --- audits/README.md | 6 +- audits/catalog/cutover.json | 8 - audits/catalog/fixture-migration.json | 171 ++++++ audits/catalog/form-migration.json | 116 +--- audits/catalog/form-review.json | 132 ++--- .../audits/published/PublishedComparison.kt | 80 +-- .../audits/repairs/FixtureMigration.kt | 8 + .../morphia/audits/repairs/FormMigration.kt | 37 ++ .../audits/semantics/BsonComparison.kt | 75 ++- .../semantics/BsonComparisonContracts.kt | 11 +- .../dev/morphia/audits/semantics/Matching.kt | 50 ++ .../audits/offline/FormMigrationTest.kt | 34 +- .../audits/offline/PrintedVectorsTest.kt | 1 + .../audits/offline/StrictVectorsTest.kt | 13 + .../dev/morphia/test/OperatorCaseRunner.java | 25 +- .../java/dev/morphia/test/PrintedResults.java | 62 ++- .../dev/morphia/test/PrintedResultsTest.java | 4 +- .../java/dev/morphia/test/StrictBson.java | 50 +- .../java/dev/morphia/test/StrictBsonTest.java | 12 +- .../aggregation/stages/TestGraphLookup.java | 4 +- .../graphLookup/withAQueryFilter/action.json | 18 - .../graphLookup/withAQueryFilter/data.json | 6 - .../withAQueryFilter/expected.json | 1 - .../stages/graphLookup/withAQueryFilter/name | 1 - .../withAQueryFilter/scenario.json | 217 ++++++++ .../withinASingleCollection/action.json | 11 - .../withinASingleCollection/data.json | 6 - .../withinASingleCollection/expected.json | 6 - .../graphLookup/withinASingleCollection/name | 1 - .../withinASingleCollection/scenario.json | 508 ++++++++++++++++++ .../dev/morphia/test/generated/manifest.json | 22 +- .../test/generated/vectors/printed.json | 310 +++++++++++ .../test/generated/vectors/strict.json | 26 +- design/operator-audits-bson-comparison.md | 10 +- design/operator-audits-design.md | 19 +- design/operator-audits-progress.md | 26 +- design/operator-audits-reference.md | 5 +- 37 files changed, 1718 insertions(+), 374 deletions(-) create mode 100644 audits/src/main/kotlin/dev/morphia/audits/semantics/Matching.kt delete mode 100644 core/src/test/resources/dev/morphia/test/aggregation/stages/graphLookup/withAQueryFilter/action.json delete mode 100644 core/src/test/resources/dev/morphia/test/aggregation/stages/graphLookup/withAQueryFilter/data.json delete mode 100644 core/src/test/resources/dev/morphia/test/aggregation/stages/graphLookup/withAQueryFilter/expected.json delete mode 100644 core/src/test/resources/dev/morphia/test/aggregation/stages/graphLookup/withAQueryFilter/name create mode 100644 core/src/test/resources/dev/morphia/test/aggregation/stages/graphLookup/withAQueryFilter/scenario.json delete mode 100644 core/src/test/resources/dev/morphia/test/aggregation/stages/graphLookup/withinASingleCollection/action.json delete mode 100644 core/src/test/resources/dev/morphia/test/aggregation/stages/graphLookup/withinASingleCollection/data.json delete mode 100644 core/src/test/resources/dev/morphia/test/aggregation/stages/graphLookup/withinASingleCollection/expected.json delete mode 100644 core/src/test/resources/dev/morphia/test/aggregation/stages/graphLookup/withinASingleCollection/name create mode 100644 core/src/test/resources/dev/morphia/test/aggregation/stages/graphLookup/withinASingleCollection/scenario.json diff --git a/audits/README.md b/audits/README.md index 3b5981ac02b..e2c023f5b11 100644 --- a/audits/README.md +++ b/audits/README.md @@ -164,11 +164,11 @@ These remain because coverage has not fully moved off them yet. Each one goes wh its users does. - **Core's legacy fixture loader** (`data.json`, `action.json`, `expected.json` through - `TemplatedTestBase`). It runs 207 legacy fixture directories; 349 cases have moved to the runner. - Of the 207: + `TemplatedTestBase`). It runs 205 legacy fixture directories; 351 cases have moved to the runner. + Of the 205: - 98 are still locked: 96 have no documented source that reproduces them, and are listed under `unresolved` in `form-review.json`; - - 25 are tracked as legacy-only in `cutover.json`; + - 23 are tracked as legacy-only in `cutover.json`; - 81 never-locked fixtures have no pinned reference. - **The legacy RST extractor** (`rst/`, `model/CodeBlock`). Cutover and the example inventory read pages through it. It goes once the structured parser (`scenarios/`) owns example diff --git a/audits/catalog/cutover.json b/audits/catalog/cutover.json index 62f83136070..278ff46532d 100644 --- a/audits/catalog/cutover.json +++ b/audits/catalog/cutover.json @@ -56,14 +56,6 @@ "check" : "SOURCE", "detail" : "the shell normalizer cannot read the documented results (expected syntax)", "fixture" : "aggregation/stages/graphLookup/acrossMultipleCollections" - }, { - "check" : "BEHAVIOR", - "detail" : "$graphLookup does not order the array it builds, so the reference and Morphia runs list it differently; it needs an unordered-array comparison (with the documented collection name its serialization passes)", - "fixture" : "aggregation/stages/graphLookup/withAQueryFilter" - }, { - "check" : "BEHAVIOR", - "detail" : "$graphLookup does not order the array it builds, so the reference and Morphia runs list it differently; it needs an unordered-array comparison (with the documented collection name its serialization passes)", - "fixture" : "aggregation/stages/graphLookup/withinASingleCollection" }, { "check" : "SOURCE", "detail" : "the page documents a projection, which needs the unmapped findOptions", diff --git a/audits/catalog/fixture-migration.json b/audits/catalog/fixture-migration.json index 1481bdc7ed1..e28103de374 100644 --- a/audits/catalog/fixture-migration.json +++ b/audits/catalog/fixture-migration.json @@ -15188,6 +15188,177 @@ "scenario" : "core/src/test/resources/dev/morphia/test/aggregation/stages/fill/indicateIfAFieldWasPopulatedUsingFill/scenario.json", "scenarioSha256" : "9fc2340e7a6542e49d906f0db3657c46fb4b65cf627837632b5c69e957eb6f53", "test" : "dev.morphia.test.aggregation.stages.TestFill#testIndicateIfAFieldWasPopulatedUsingFill" + }, { + "bodyEdit" : { + "fromSha256" : "be99e62f8d7654e071cbb5313f691b83f1f0d31e23a991993402642e7e273974", + "reason" : "looks up the documented collection people instead of the legacy harness collection example_test, since the runner seeds the documented names" + }, + "files" : { + "action.json" : "17dbed0c71ec223106f9884c01fd811518d18faa80a550128c1981dba4a5d76a", + "data.json" : "474ba791ce2047fac6f9a4d94242fd57fba8a3b8ae59d03bf5ada45ef9455940", + "expected.json" : "b774f0279452d94bbad0b9c29ffa1cb4efe8ec00941f572372e39384e237d849", + "lock" : "d9c4a31198b52fba50dfc279422c563f8ef5afe9a1d43934de8b5ff2049ea4a9", + "name" : "6efdea19495038d85b762221880d7a4f066591e872668fde590631db219480a8" + }, + "fixture" : "aggregation/stages/graphLookup/withAQueryFilter", + "kind" : "CONVERTED", + "legacyBody" : "{\n testPipeline(new ActionTestOptions().orderMatters(false), (aggregation) -> aggregation.pipeline(\n match(eq(\"name\", \"Tanya Jordan\")),\n graphLookup(\"people\").startWith(\"$friends\").connectFromField(\"friends\")\n .connectToField(\"name\").as(\"golfers\").restrict(eq(\"hobbies\", \"golf\")),\n project().include(\"name\").include(\"friends\").include(\"connections who play golf\", \"$golfers.name\")\n\n ));\n }", + "legacyBodySha256" : "7b5f3d066507e327c48e53b3ec93445ade9646812a10f9b4ba7d760eb96b797f", + "legacyMethod" : "testWithAQueryFilter", + "legacyType" : "dev.morphia.test.aggregation.stages.TestGraphLookup", + "options" : [ ], + "ordered" : false, + "override" : { + "blocks" : [ { + "role" : "ACTION", + "sha256" : "e487b229fb6a3135eba8776386efa1ce404cfa7bac8f164cc44aa948771f5755", + "text" : "db.people.aggregate( [\n { $match: { \"name\": \"Tanya Jordan\" } },\n { $graphLookup: {\n from: \"people\",\n startWith: \"$friends\",\n connectFromField: \"friends\",\n connectToField: \"name\",\n as: \"golfers\",\n restrictSearchWithMatch: { \"hobbies\" : \"golf\" }\n }\n },\n { $project: {\n \"name\": 1,\n \"friends\": 1,\n \"connections who play golf\": \"$golfers.name\"\n }\n }\n] )" + }, { + "role" : "DATA", + "sha256" : "d4eefac25e853e8412b4d493387752448c3658ce37b18f165d2dd7ea25a3bb14", + "text" : "{\n \"_id\" : 1,\n \"name\" : \"Tanya Jordan\",\n \"friends\" : [ \"Shirley Soto\", \"Terry Hawkins\", \"Carole Hale\" ],\n \"hobbies\" : [ \"tennis\", \"unicycling\", \"golf\" ]\n}\n{\n \"_id\" : 2,\n \"name\" : \"Carole Hale\",\n \"friends\" : [ \"Joseph Dennis\", \"Tanya Jordan\", \"Terry Hawkins\" ],\n \"hobbies\" : [ \"archery\", \"golf\", \"woodworking\" ]\n}\n{\n \"_id\" : 3,\n \"name\" : \"Terry Hawkins\",\n \"friends\" : [ \"Tanya Jordan\", \"Carole Hale\", \"Angelo Ward\" ],\n \"hobbies\" : [ \"knitting\", \"frisbee\" ]\n}\n{\n \"_id\" : 4,\n \"name\" : \"Joseph Dennis\",\n \"friends\" : [ \"Angelo Ward\", \"Carole Hale\" ],\n \"hobbies\" : [ \"tennis\", \"golf\", \"topiary\" ]\n}\n{\n \"_id\" : 5,\n \"name\" : \"Angelo Ward\",\n \"friends\" : [ \"Terry Hawkins\", \"Shirley Soto\", \"Joseph Dennis\" ],\n \"hobbies\" : [ \"travel\", \"ceramics\", \"golf\" ]\n}\n{\n \"_id\" : 6,\n \"name\" : \"Shirley Soto\",\n \"friends\" : [ \"Angelo Ward\", \"Tanya Jordan\", \"Carole Hale\" ],\n \"hobbies\" : [ \"frisbee\", \"set theory\" ]\n }" + }, { + "role" : "EXPECTED", + "sha256" : "413b53f4f00b391c62a173a293358d0f2b48ce6dba539c1f0c016c656cfe30b7", + "text" : "{\n \"_id\" : 1,\n \"name\" : \"Tanya Jordan\",\n \"friends\" : [\n \"Shirley Soto\",\n \"Terry Hawkins\",\n \"Carole Hale\"\n ],\n \"connections who play golf\" : [\n \"Joseph Dennis\",\n \"Tanya Jordan\",\n \"Angelo Ward\",\n \"Carole Hale\"\n ]\n}" + } ], + "collections" : { }, + "corrections" : [ { + "curated" : "{\"v\": \"example_test\"}", + "documented" : "{\"v\": \"people\"}", + "file" : "action.json", + "index" : null, + "pointer" : "/1/$graphLookup/from" + } ], + "example" : "With a Query Filter", + "fixture" : "aggregation/stages/graphLookup/withAQueryFilter", + "fixtureFiles" : { + "action.json" : "17dbed0c71ec223106f9884c01fd811518d18faa80a550128c1981dba4a5d76a", + "data.json" : "474ba791ce2047fac6f9a4d94242fd57fba8a3b8ae59d03bf5ada45ef9455940", + "expected.json" : "b774f0279452d94bbad0b9c29ffa1cb4efe8ec00941f572372e39384e237d849", + "name" : "6efdea19495038d85b762221880d7a4f066591e872668fde590631db219480a8" + }, + "includes" : [ { + "blob" : "88a019ea44d91726953d31d21e664e1333190efd", + "path" : "source/includes/graphLookup-sharded-coll-transaction-note.rst" + }, { + "blob" : "6beb75178564cf0b943050f7e6ef2d96165ce728", + "path" : "source/includes/fact-graphlookup-memory-restrictions.rst" + }, { + "blob" : "621353fe8533a76f297866363e194e3e42cf03a0", + "path" : "source/includes/extracts-views.yaml" + } ], + "origin" : "7ad9ac5e4d31c5035284090ab13521e17467015f", + "pageBlob" : "d00d3c58699ec5ad0505fdcab3026e35f522ce87", + "retiredLock" : { + "name" : "lock", + "sha256" : "d9c4a31198b52fba50dfc279422c563f8ef5afe9a1d43934de8b5ff2049ea4a9", + "text" : "update the lookup collection name" + }, + "retypes" : [ ], + "rules" : [ ], + "shape" : "PIPELINE", + "source" : { + "commit" : "fbff8bd22e055259d67b394c854f128340571b1f", + "path" : "source/reference/operator/aggregation/graphLookup.txt", + "relation" : "AT_ORIGIN" + }, + "unexpandedIncludes" : [ ], + "unorderedArrays" : [ { + "path" : "/connections who play golf", + "reason" : "connections who play golf is projected from the golfers array that $graphLookup's as field builds. The page says: \"Documents returned in the as field are not guaranteed to be in any order\", and the server lists them in a different order between runs on identical data (#4562)." + } ] + }, + "scenario" : "core/src/test/resources/dev/morphia/test/aggregation/stages/graphLookup/withAQueryFilter/scenario.json", + "scenarioSha256" : "386b91b708f76eac8a815bfe7b8742266d28c404d9553fdd0bfe5acca6bfd5e9", + "test" : "dev.morphia.test.aggregation.stages.TestGraphLookup#testWithAQueryFilter" + }, { + "bodyEdit" : { + "fromSha256" : "9bd7f6c0015a2a851deabde5ce13f9ccff423c1d0372eff02b435cb1b84f4c18", + "reason" : "looks up the documented collection employees instead of the legacy harness collection example_test, since the runner seeds the documented names" + }, + "files" : { + "action.json" : "4f0cd2bf7cea6692e78ce284021e86b302a96c86c98703a3f29dc16ca30ce03d", + "data.json" : "aab822acc12c8f949d7229e5bb4f6bef9e6d08c1bb8aad35e0805a1bc67eaaa5", + "expected.json" : "95f921747af351d01ef6de1c6b808c7f73aef420cfddb3403fac92e06b4ee04b", + "lock" : "95ddbc5b5eb802ffd82bb3fce30da8cce5a58186090c4d6c09def91fb006a333", + "name" : "c0efb517f283d52fc34a387110a1961760da0075b1c6a53ee935eb9776b2705a" + }, + "fixture" : "aggregation/stages/graphLookup/withinASingleCollection", + "kind" : "CONVERTED", + "legacyBody" : "{\n testPipeline(new ActionTestOptions().removeIds(true).orderMatters(false),\n (aggregation) -> aggregation.pipeline(graphLookup(\"employees\").startWith(\"$reportsTo\")\n .connectFromField(\"reportsTo\").connectToField(\"name\").as(\"reportingHierarchy\")));\n }", + "legacyBodySha256" : "1ccdc95b8cba0f72e9556e31433a45cc18c4605eabdb4eb4cce98c56a7f8692c", + "legacyMethod" : "testWithinASingleCollection", + "legacyType" : "dev.morphia.test.aggregation.stages.TestGraphLookup", + "options" : [ { + "argument" : "true", + "name" : "removeIds" + } ], + "ordered" : false, + "override" : { + "blocks" : [ { + "role" : "ACTION", + "sha256" : "bdfbfa1a97b4b0b8899a202580ff4f9bb82aab5a769e59a69b42d658cdd1fd68", + "text" : "db.employees.aggregate( [\n {\n $graphLookup: {\n from: \"employees\",\n startWith: \"$reportsTo\",\n connectFromField: \"reportsTo\",\n connectToField: \"name\",\n as: \"reportingHierarchy\"\n }\n }\n] )" + }, { + "role" : "DATA", + "sha256" : "3579008d10ee3ed3fa240f0561659a294a558e8cb36d7e208d5f2da075e8d1dc", + "text" : "{ \"_id\" : 1, \"name\" : \"Dev\" }\n{ \"_id\" : 2, \"name\" : \"Eliot\", \"reportsTo\" : \"Dev\" }\n{ \"_id\" : 3, \"name\" : \"Ron\", \"reportsTo\" : \"Eliot\" }\n{ \"_id\" : 4, \"name\" : \"Andrew\", \"reportsTo\" : \"Eliot\" }\n{ \"_id\" : 5, \"name\" : \"Asya\", \"reportsTo\" : \"Ron\" }\n{ \"_id\" : 6, \"name\" : \"Dan\", \"reportsTo\" : \"Andrew\" }" + }, { + "role" : "EXPECTED", + "sha256" : "dd29acb0907de88e965e45617260f200f641d97affab0df9b3888fbcdf011497", + "text" : "{\n \"_id\" : 1,\n \"name\" : \"Dev\",\n \"reportingHierarchy\" : [ ]\n}\n{\n \"_id\" : 2,\n \"name\" : \"Eliot\",\n \"reportsTo\" : \"Dev\",\n \"reportingHierarchy\" : [\n { \"_id\" : 1, \"name\" : \"Dev\" }\n ]\n}\n{\n \"_id\" : 3,\n \"name\" : \"Ron\",\n \"reportsTo\" : \"Eliot\",\n \"reportingHierarchy\" : [\n { \"_id\" : 1, \"name\" : \"Dev\" },\n { \"_id\" : 2, \"name\" : \"Eliot\", \"reportsTo\" : \"Dev\" }\n ]\n}\n{\n \"_id\" : 4,\n \"name\" : \"Andrew\",\n \"reportsTo\" : \"Eliot\",\n \"reportingHierarchy\" : [\n { \"_id\" : 1, \"name\" : \"Dev\" },\n { \"_id\" : 2, \"name\" : \"Eliot\", \"reportsTo\" : \"Dev\" }\n ]\n}\n{\n \"_id\" : 5,\n \"name\" : \"Asya\",\n \"reportsTo\" : \"Ron\",\n \"reportingHierarchy\" : [\n { \"_id\" : 1, \"name\" : \"Dev\" },\n { \"_id\" : 2, \"name\" : \"Eliot\", \"reportsTo\" : \"Dev\" },\n { \"_id\" : 3, \"name\" : \"Ron\", \"reportsTo\" : \"Eliot\" }\n ]\n}\n{\n \"_id\" : 6,\n \"name\" : \"Dan\",\n \"reportsTo\" : \"Andrew\",\n \"reportingHierarchy\" : [\n { \"_id\" : 1, \"name\" : \"Dev\" },\n { \"_id\" : 2, \"name\" : \"Eliot\", \"reportsTo\" : \"Dev\" },\n { \"_id\" : 4, \"name\" : \"Andrew\", \"reportsTo\" : \"Eliot\" }\n ]\n}" + } ], + "collections" : { }, + "corrections" : [ { + "curated" : "{\"v\": \"example_test\"}", + "documented" : "{\"v\": \"employees\"}", + "file" : "action.json", + "index" : null, + "pointer" : "/0/$graphLookup/from" + } ], + "example" : "Within a Single Collection", + "fixture" : "aggregation/stages/graphLookup/withinASingleCollection", + "fixtureFiles" : { + "action.json" : "4f0cd2bf7cea6692e78ce284021e86b302a96c86c98703a3f29dc16ca30ce03d", + "data.json" : "aab822acc12c8f949d7229e5bb4f6bef9e6d08c1bb8aad35e0805a1bc67eaaa5", + "expected.json" : "95f921747af351d01ef6de1c6b808c7f73aef420cfddb3403fac92e06b4ee04b", + "name" : "c0efb517f283d52fc34a387110a1961760da0075b1c6a53ee935eb9776b2705a" + }, + "includes" : [ { + "blob" : "88a019ea44d91726953d31d21e664e1333190efd", + "path" : "source/includes/graphLookup-sharded-coll-transaction-note.rst" + }, { + "blob" : "6beb75178564cf0b943050f7e6ef2d96165ce728", + "path" : "source/includes/fact-graphlookup-memory-restrictions.rst" + }, { + "blob" : "621353fe8533a76f297866363e194e3e42cf03a0", + "path" : "source/includes/extracts-views.yaml" + } ], + "origin" : "7ad9ac5e4d31c5035284090ab13521e17467015f", + "pageBlob" : "d00d3c58699ec5ad0505fdcab3026e35f522ce87", + "retiredLock" : { + "name" : "lock", + "sha256" : "95ddbc5b5eb802ffd82bb3fce30da8cce5a58186090c4d6c09def91fb006a333", + "text" : "updated the collection name in from" + }, + "retypes" : [ ], + "rules" : [ ], + "shape" : "PIPELINE", + "source" : { + "commit" : "fbff8bd22e055259d67b394c854f128340571b1f", + "path" : "source/reference/operator/aggregation/graphLookup.txt", + "relation" : "AT_ORIGIN" + }, + "unexpandedIncludes" : [ ], + "unorderedArrays" : [ { + "path" : "/reportingHierarchy", + "reason" : "reportingHierarchy is built by $graphLookup's as field. The page says: \"Documents returned in the as field are not guaranteed to be in any order\", and the server lists them in a different order between runs on identical data (#4562)." + } ] + }, + "scenario" : "core/src/test/resources/dev/morphia/test/aggregation/stages/graphLookup/withinASingleCollection/scenario.json", + "scenarioSha256" : "b27a28f73a06a6c9fd8f53eacfc6c7e9568056f56594cb72635c5c9e572998f7", + "test" : "dev.morphia.test.aggregation.stages.TestGraphLookup#testWithinASingleCollection" }, { "bodyEdit" : null, "files" : { diff --git a/audits/catalog/form-migration.json b/audits/catalog/form-migration.json index 7417b78ead1..a7b2082e9f5 100644 --- a/audits/catalog/form-migration.json +++ b/audits/catalog/form-migration.json @@ -156,118 +156,6 @@ "relation" : "AT_ORIGIN" }, "unexpandedIncludes" : [ ] - }, { - "blocks" : [ { - "role" : "ACTION", - "sha256" : "e487b229fb6a3135eba8776386efa1ce404cfa7bac8f164cc44aa948771f5755", - "text" : "db.people.aggregate( [\n { $match: { \"name\": \"Tanya Jordan\" } },\n { $graphLookup: {\n from: \"people\",\n startWith: \"$friends\",\n connectFromField: \"friends\",\n connectToField: \"name\",\n as: \"golfers\",\n restrictSearchWithMatch: { \"hobbies\" : \"golf\" }\n }\n },\n { $project: {\n \"name\": 1,\n \"friends\": 1,\n \"connections who play golf\": \"$golfers.name\"\n }\n }\n] )" - }, { - "role" : "DATA", - "sha256" : "d4eefac25e853e8412b4d493387752448c3658ce37b18f165d2dd7ea25a3bb14", - "text" : "{\n \"_id\" : 1,\n \"name\" : \"Tanya Jordan\",\n \"friends\" : [ \"Shirley Soto\", \"Terry Hawkins\", \"Carole Hale\" ],\n \"hobbies\" : [ \"tennis\", \"unicycling\", \"golf\" ]\n}\n{\n \"_id\" : 2,\n \"name\" : \"Carole Hale\",\n \"friends\" : [ \"Joseph Dennis\", \"Tanya Jordan\", \"Terry Hawkins\" ],\n \"hobbies\" : [ \"archery\", \"golf\", \"woodworking\" ]\n}\n{\n \"_id\" : 3,\n \"name\" : \"Terry Hawkins\",\n \"friends\" : [ \"Tanya Jordan\", \"Carole Hale\", \"Angelo Ward\" ],\n \"hobbies\" : [ \"knitting\", \"frisbee\" ]\n}\n{\n \"_id\" : 4,\n \"name\" : \"Joseph Dennis\",\n \"friends\" : [ \"Angelo Ward\", \"Carole Hale\" ],\n \"hobbies\" : [ \"tennis\", \"golf\", \"topiary\" ]\n}\n{\n \"_id\" : 5,\n \"name\" : \"Angelo Ward\",\n \"friends\" : [ \"Terry Hawkins\", \"Shirley Soto\", \"Joseph Dennis\" ],\n \"hobbies\" : [ \"travel\", \"ceramics\", \"golf\" ]\n}\n{\n \"_id\" : 6,\n \"name\" : \"Shirley Soto\",\n \"friends\" : [ \"Angelo Ward\", \"Tanya Jordan\", \"Carole Hale\" ],\n \"hobbies\" : [ \"frisbee\", \"set theory\" ]\n }" - }, { - "role" : "EXPECTED", - "sha256" : "413b53f4f00b391c62a173a293358d0f2b48ce6dba539c1f0c016c656cfe30b7", - "text" : "{\n \"_id\" : 1,\n \"name\" : \"Tanya Jordan\",\n \"friends\" : [\n \"Shirley Soto\",\n \"Terry Hawkins\",\n \"Carole Hale\"\n ],\n \"connections who play golf\" : [\n \"Joseph Dennis\",\n \"Tanya Jordan\",\n \"Angelo Ward\",\n \"Carole Hale\"\n ]\n}" - } ], - "collections" : { }, - "corrections" : [ { - "curated" : "{\"v\": \"example_test\"}", - "documented" : "{\"v\": \"people\"}", - "file" : "action.json", - "index" : null, - "pointer" : "/1/$graphLookup/from" - } ], - "example" : "With a Query Filter", - "fixture" : "aggregation/stages/graphLookup/withAQueryFilter", - "fixtureFiles" : { - "action.json" : "17dbed0c71ec223106f9884c01fd811518d18faa80a550128c1981dba4a5d76a", - "data.json" : "474ba791ce2047fac6f9a4d94242fd57fba8a3b8ae59d03bf5ada45ef9455940", - "expected.json" : "b774f0279452d94bbad0b9c29ffa1cb4efe8ec00941f572372e39384e237d849", - "name" : "6efdea19495038d85b762221880d7a4f066591e872668fde590631db219480a8" - }, - "includes" : [ { - "blob" : "88a019ea44d91726953d31d21e664e1333190efd", - "path" : "source/includes/graphLookup-sharded-coll-transaction-note.rst" - }, { - "blob" : "6beb75178564cf0b943050f7e6ef2d96165ce728", - "path" : "source/includes/fact-graphlookup-memory-restrictions.rst" - }, { - "blob" : "621353fe8533a76f297866363e194e3e42cf03a0", - "path" : "source/includes/extracts-views.yaml" - } ], - "origin" : "7ad9ac5e4d31c5035284090ab13521e17467015f", - "pageBlob" : "d00d3c58699ec5ad0505fdcab3026e35f522ce87", - "retiredLock" : { - "name" : "lock", - "sha256" : "d9c4a31198b52fba50dfc279422c563f8ef5afe9a1d43934de8b5ff2049ea4a9", - "text" : "update the lookup collection name" - }, - "retypes" : [ ], - "rules" : [ ], - "shape" : "PIPELINE", - "source" : { - "commit" : "fbff8bd22e055259d67b394c854f128340571b1f", - "path" : "source/reference/operator/aggregation/graphLookup.txt", - "relation" : "AT_ORIGIN" - }, - "unexpandedIncludes" : [ ] - }, { - "blocks" : [ { - "role" : "ACTION", - "sha256" : "bdfbfa1a97b4b0b8899a202580ff4f9bb82aab5a769e59a69b42d658cdd1fd68", - "text" : "db.employees.aggregate( [\n {\n $graphLookup: {\n from: \"employees\",\n startWith: \"$reportsTo\",\n connectFromField: \"reportsTo\",\n connectToField: \"name\",\n as: \"reportingHierarchy\"\n }\n }\n] )" - }, { - "role" : "DATA", - "sha256" : "3579008d10ee3ed3fa240f0561659a294a558e8cb36d7e208d5f2da075e8d1dc", - "text" : "{ \"_id\" : 1, \"name\" : \"Dev\" }\n{ \"_id\" : 2, \"name\" : \"Eliot\", \"reportsTo\" : \"Dev\" }\n{ \"_id\" : 3, \"name\" : \"Ron\", \"reportsTo\" : \"Eliot\" }\n{ \"_id\" : 4, \"name\" : \"Andrew\", \"reportsTo\" : \"Eliot\" }\n{ \"_id\" : 5, \"name\" : \"Asya\", \"reportsTo\" : \"Ron\" }\n{ \"_id\" : 6, \"name\" : \"Dan\", \"reportsTo\" : \"Andrew\" }" - }, { - "role" : "EXPECTED", - "sha256" : "dd29acb0907de88e965e45617260f200f641d97affab0df9b3888fbcdf011497", - "text" : "{\n \"_id\" : 1,\n \"name\" : \"Dev\",\n \"reportingHierarchy\" : [ ]\n}\n{\n \"_id\" : 2,\n \"name\" : \"Eliot\",\n \"reportsTo\" : \"Dev\",\n \"reportingHierarchy\" : [\n { \"_id\" : 1, \"name\" : \"Dev\" }\n ]\n}\n{\n \"_id\" : 3,\n \"name\" : \"Ron\",\n \"reportsTo\" : \"Eliot\",\n \"reportingHierarchy\" : [\n { \"_id\" : 1, \"name\" : \"Dev\" },\n { \"_id\" : 2, \"name\" : \"Eliot\", \"reportsTo\" : \"Dev\" }\n ]\n}\n{\n \"_id\" : 4,\n \"name\" : \"Andrew\",\n \"reportsTo\" : \"Eliot\",\n \"reportingHierarchy\" : [\n { \"_id\" : 1, \"name\" : \"Dev\" },\n { \"_id\" : 2, \"name\" : \"Eliot\", \"reportsTo\" : \"Dev\" }\n ]\n}\n{\n \"_id\" : 5,\n \"name\" : \"Asya\",\n \"reportsTo\" : \"Ron\",\n \"reportingHierarchy\" : [\n { \"_id\" : 1, \"name\" : \"Dev\" },\n { \"_id\" : 2, \"name\" : \"Eliot\", \"reportsTo\" : \"Dev\" },\n { \"_id\" : 3, \"name\" : \"Ron\", \"reportsTo\" : \"Eliot\" }\n ]\n}\n{\n \"_id\" : 6,\n \"name\" : \"Dan\",\n \"reportsTo\" : \"Andrew\",\n \"reportingHierarchy\" : [\n { \"_id\" : 1, \"name\" : \"Dev\" },\n { \"_id\" : 2, \"name\" : \"Eliot\", \"reportsTo\" : \"Dev\" },\n { \"_id\" : 4, \"name\" : \"Andrew\", \"reportsTo\" : \"Eliot\" }\n ]\n}" - } ], - "collections" : { }, - "corrections" : [ { - "curated" : "{\"v\": \"example_test\"}", - "documented" : "{\"v\": \"employees\"}", - "file" : "action.json", - "index" : null, - "pointer" : "/0/$graphLookup/from" - } ], - "example" : "Within a Single Collection", - "fixture" : "aggregation/stages/graphLookup/withinASingleCollection", - "fixtureFiles" : { - "action.json" : "4f0cd2bf7cea6692e78ce284021e86b302a96c86c98703a3f29dc16ca30ce03d", - "data.json" : "aab822acc12c8f949d7229e5bb4f6bef9e6d08c1bb8aad35e0805a1bc67eaaa5", - "expected.json" : "95f921747af351d01ef6de1c6b808c7f73aef420cfddb3403fac92e06b4ee04b", - "name" : "c0efb517f283d52fc34a387110a1961760da0075b1c6a53ee935eb9776b2705a" - }, - "includes" : [ { - "blob" : "88a019ea44d91726953d31d21e664e1333190efd", - "path" : "source/includes/graphLookup-sharded-coll-transaction-note.rst" - }, { - "blob" : "6beb75178564cf0b943050f7e6ef2d96165ce728", - "path" : "source/includes/fact-graphlookup-memory-restrictions.rst" - }, { - "blob" : "621353fe8533a76f297866363e194e3e42cf03a0", - "path" : "source/includes/extracts-views.yaml" - } ], - "origin" : "7ad9ac5e4d31c5035284090ab13521e17467015f", - "pageBlob" : "d00d3c58699ec5ad0505fdcab3026e35f522ce87", - "retiredLock" : { - "name" : "lock", - "sha256" : "95ddbc5b5eb802ffd82bb3fce30da8cce5a58186090c4d6c09def91fb006a333", - "text" : "updated the collection name in from" - }, - "retypes" : [ ], - "rules" : [ ], - "shape" : "PIPELINE", - "source" : { - "commit" : "fbff8bd22e055259d67b394c854f128340571b1f", - "path" : "source/reference/operator/aggregation/graphLookup.txt", - "relation" : "AT_ORIGIN" - }, - "unexpandedIncludes" : [ ] }, { "blocks" : [ { "role" : "ACTION", @@ -369,8 +257,8 @@ "gap.REJECTED" : 1, "gap.RESIDUAL_DIFFERENCE" : 48, "gap.SOURCE_UNSUPPORTED" : 34, - "overrides" : 6, - "overrides.corrected" : 2, + "overrides" : 4, + "overrides.corrected" : 0, "overrides.exact" : 1, "overrides.retyped" : 0, "rule.ALTERNATIVE_COMMANDS" : 1, diff --git a/audits/catalog/form-review.json b/audits/catalog/form-review.json index e80eec7f3d8..bc197daa823 100644 --- a/audits/catalog/form-review.json +++ b/audits/catalog/form-review.json @@ -74,68 +74,6 @@ "path" : "source/reference/operator/aggregation/graphLookup.txt", "relation" : "AT_ORIGIN" } - }, { - "corrections" : [ { - "curated" : "{\"v\": \"example_test\"}", - "documented" : "{\"v\": \"people\"}", - "file" : "action.json", - "index" : null, - "pointer" : "/1/$graphLookup/from" - } ], - "fixture" : "aggregation/stages/graphLookup/withAQueryFilter", - "includes" : [ { - "blob" : "88a019ea44d91726953d31d21e664e1333190efd", - "path" : "source/includes/graphLookup-sharded-coll-transaction-note.rst" - }, { - "blob" : "6beb75178564cf0b943050f7e6ef2d96165ce728", - "path" : "source/includes/fact-graphlookup-memory-restrictions.rst" - }, { - "blob" : "621353fe8533a76f297866363e194e3e42cf03a0", - "path" : "source/includes/extracts-views.yaml" - } ], - "justification" : null, - "lock" : "update the lookup collection name", - "marker" : "lock", - "origin" : "7ad9ac5e4d31c5035284090ab13521e17467015f", - "pageBlob" : "d00d3c58699ec5ad0505fdcab3026e35f522ce87", - "retypes" : [ ], - "rules" : [ ], - "source" : { - "commit" : "fbff8bd22e055259d67b394c854f128340571b1f", - "path" : "source/reference/operator/aggregation/graphLookup.txt", - "relation" : "AT_ORIGIN" - } - }, { - "corrections" : [ { - "curated" : "{\"v\": \"example_test\"}", - "documented" : "{\"v\": \"employees\"}", - "file" : "action.json", - "index" : null, - "pointer" : "/0/$graphLookup/from" - } ], - "fixture" : "aggregation/stages/graphLookup/withinASingleCollection", - "includes" : [ { - "blob" : "88a019ea44d91726953d31d21e664e1333190efd", - "path" : "source/includes/graphLookup-sharded-coll-transaction-note.rst" - }, { - "blob" : "6beb75178564cf0b943050f7e6ef2d96165ce728", - "path" : "source/includes/fact-graphlookup-memory-restrictions.rst" - }, { - "blob" : "621353fe8533a76f297866363e194e3e42cf03a0", - "path" : "source/includes/extracts-views.yaml" - } ], - "justification" : null, - "lock" : "updated the collection name in from", - "marker" : "lock", - "origin" : "7ad9ac5e4d31c5035284090ab13521e17467015f", - "pageBlob" : "d00d3c58699ec5ad0505fdcab3026e35f522ce87", - "retypes" : [ ], - "rules" : [ ], - "source" : { - "commit" : "fbff8bd22e055259d67b394c854f128340571b1f", - "path" : "source/reference/operator/aggregation/graphLookup.txt", - "relation" : "AT_ORIGIN" - } }, { "corrections" : [ ], "fixture" : "query/filters/type/queryingByMultipleDataTypes", @@ -2108,6 +2046,76 @@ "path" : "source/reference/operator/aggregation/fill.txt", "relation" : "AT_ORIGIN" } + }, { + "corrections" : [ { + "curated" : "{\"v\": \"example_test\"}", + "documented" : "{\"v\": \"people\"}", + "file" : "action.json", + "index" : null, + "pointer" : "/1/$graphLookup/from" + } ], + "fixture" : "aggregation/stages/graphLookup/withAQueryFilter", + "includes" : [ { + "blob" : "88a019ea44d91726953d31d21e664e1333190efd", + "path" : "source/includes/graphLookup-sharded-coll-transaction-note.rst" + }, { + "blob" : "6beb75178564cf0b943050f7e6ef2d96165ce728", + "path" : "source/includes/fact-graphlookup-memory-restrictions.rst" + }, { + "blob" : "621353fe8533a76f297866363e194e3e42cf03a0", + "path" : "source/includes/extracts-views.yaml" + } ], + "justification" : null, + "lock" : "update the lookup collection name", + "marker" : "lock", + "origin" : "7ad9ac5e4d31c5035284090ab13521e17467015f", + "pageBlob" : "d00d3c58699ec5ad0505fdcab3026e35f522ce87", + "retypes" : [ ], + "rules" : [ ], + "source" : { + "commit" : "fbff8bd22e055259d67b394c854f128340571b1f", + "path" : "source/reference/operator/aggregation/graphLookup.txt", + "relation" : "AT_ORIGIN" + }, + "unorderedArrays" : [ { + "path" : "/connections who play golf", + "reason" : "connections who play golf is projected from the golfers array that $graphLookup's as field builds. The page says: \"Documents returned in the as field are not guaranteed to be in any order\", and the server lists them in a different order between runs on identical data (#4562)." + } ] + }, { + "corrections" : [ { + "curated" : "{\"v\": \"example_test\"}", + "documented" : "{\"v\": \"employees\"}", + "file" : "action.json", + "index" : null, + "pointer" : "/0/$graphLookup/from" + } ], + "fixture" : "aggregation/stages/graphLookup/withinASingleCollection", + "includes" : [ { + "blob" : "88a019ea44d91726953d31d21e664e1333190efd", + "path" : "source/includes/graphLookup-sharded-coll-transaction-note.rst" + }, { + "blob" : "6beb75178564cf0b943050f7e6ef2d96165ce728", + "path" : "source/includes/fact-graphlookup-memory-restrictions.rst" + }, { + "blob" : "621353fe8533a76f297866363e194e3e42cf03a0", + "path" : "source/includes/extracts-views.yaml" + } ], + "justification" : null, + "lock" : "updated the collection name in from", + "marker" : "lock", + "origin" : "7ad9ac5e4d31c5035284090ab13521e17467015f", + "pageBlob" : "d00d3c58699ec5ad0505fdcab3026e35f522ce87", + "retypes" : [ ], + "rules" : [ ], + "source" : { + "commit" : "fbff8bd22e055259d67b394c854f128340571b1f", + "path" : "source/reference/operator/aggregation/graphLookup.txt", + "relation" : "AT_ORIGIN" + }, + "unorderedArrays" : [ { + "path" : "/reportingHierarchy", + "reason" : "reportingHierarchy is built by $graphLookup's as field. The page says: \"Documents returned in the as field are not guaranteed to be in any order\", and the server lists them in a different order between runs on identical data (#4562)." + } ] }, { "corrections" : [ ], "fixture" : "aggregation/stages/group/pivotData", diff --git a/audits/src/main/kotlin/dev/morphia/audits/published/PublishedComparison.kt b/audits/src/main/kotlin/dev/morphia/audits/published/PublishedComparison.kt index b8e73a5a2b2..e62c9283fd5 100644 --- a/audits/src/main/kotlin/dev/morphia/audits/published/PublishedComparison.kt +++ b/audits/src/main/kotlin/dev/morphia/audits/published/PublishedComparison.kt @@ -10,14 +10,19 @@ import org.bson.* * BsonComparison. */ object PublishedComparison { + /** + * [unorderedArrays] names arrays, relative to each row, whose items match as a multiset: each + * printed item needs a distinct result item that satisfies it. + */ fun compareResults( expected: List, actual: List, order: ResultOrder = ResultOrder.ORDERED, limits: BsonComparisonLimits = BsonComparisonLimits(), + unorderedArrays: Set = emptySet(), ): BsonComparisonResult = try { - val mismatch = Engine(limits).compare(expected, actual, order) + val mismatch = Engine(limits, unorderedArrays.toSet()).compare(expected, actual, order) BsonComparisonResult( if (mismatch == null) BsonComparisonState.EQUAL else BsonComparisonState.DIFFERENT, mismatch, @@ -28,7 +33,7 @@ object PublishedComparison { private class Invalid(message: String) : RuntimeException(message) - private class Engine(val limits: BsonComparisonLimits) { + private class Engine(val limits: BsonComparisonLimits, val unorderedArrays: Set) { var work = 0L val scalars = IdentityHashMap() @@ -204,6 +209,32 @@ object PublishedComparison { if (!actual.isArray) return mismatch(BsonDifferenceKind.TYPE) if (expected.items.size != actual.asArray().size) return mismatch(BsonDifferenceKind.ARRAY_LENGTH) + if (path in unorderedArrays) { + val items = actual.asArray() + check( + expected.items.size.toLong() * items.size <= limits.maximumResultPairs, + "Unordered array pair count exceeds comparison limit", + ) + // Constraints overlap, as rows do, so this is a matching too. + return Matching.firstUnmatched( + expected.items.size, + items.size, + { spend() }, + ) { left, right -> + difference( + expected.items[left], + items[right], + path.child("$left"), + ) == null + } + ?.let { + BsonDifference( + path.child("$it"), + BsonDifferenceKind.UNMATCHED_ITEM, + "No distinct item of the unordered array satisfies item $it", + ) + } + } expected.items.forEachIndexed { index, item -> difference(item, actual.asArray()[index], path.child(index.toString())) ?.let { @@ -274,9 +305,10 @@ object PublishedComparison { "Result counts differ", ) if (order == ResultOrder.ORDERED) { + // Paths are relative to the row, as the unordered arrays are, then placed in it. expected.indices.forEach { index -> - difference(expected[index], actual[index], BsonPath("/$index"))?.let { - return it + difference(expected[index], actual[index], BsonPath.ROOT)?.let { + return it.copy(path = BsonPath("/$index" + it.path.pointer)) } } return null @@ -285,48 +317,18 @@ object PublishedComparison { expected.size.toLong() * actual.size <= limits.maximumResultPairs, "Result pair count exceeds comparison limit", ) - val candidates = - expected.map { left -> - actual.map { right -> difference(left, right, BsonPath.ROOT) == null } - } // Constraints overlap: an Int32-or-Double row must not consume the sole match of an // exact Double row. - val owners = IntArray(actual.size) { -1 } - val assigned = IntArray(expected.size) { -1 } - for (root in expected.indices) { - val previous = IntArray(actual.size) { -1 } - val queue = ArrayDeque() - queue.add(root) - var free = -1 - search@ while (queue.isNotEmpty()) { - val left = queue.removeFirst() - for (right in actual.indices) { - spend() - if (!candidates[left][right] || previous[right] != -1) continue - previous[right] = left - if (owners[right] == -1) { - free = right - break@search - } - queue.add(owners[right]) - } + return Matching.firstUnmatched(expected.size, actual.size, { spend() }) { left, right -> + difference(expected[left], actual[right], BsonPath.ROOT) == null } - if (free == -1) - return BsonDifference( - BsonPath("/$root"), + ?.let { + BsonDifference( + BsonPath("/$it"), BsonDifferenceKind.UNMATCHED_RESULT, "No multiplicity-preserving assignment", ) - while (free != -1) { - spend() - val left = previous[free] - val old = assigned[left] - owners[free] = left - assigned[left] = free - free = old } - } - return null } } } diff --git a/audits/src/main/kotlin/dev/morphia/audits/repairs/FixtureMigration.kt b/audits/src/main/kotlin/dev/morphia/audits/repairs/FixtureMigration.kt index 02242fbcff4..0eafa2d8c84 100644 --- a/audits/src/main/kotlin/dev/morphia/audits/repairs/FixtureMigration.kt +++ b/audits/src/main/kotlin/dev/morphia/audits/repairs/FixtureMigration.kt @@ -331,6 +331,14 @@ object FixtureMigration { ) ), ) + .also { comparison -> + // Only a case that declares one carries the key. + if (override.unorderedArrays.isNotEmpty()) + comparison.append( + "unorderedArrays", + BsonArray(override.unorderedArrays.map { BsonString(it.path) }), + ) + } .append("tolerance", BsonNull.VALUE), ) .append( diff --git a/audits/src/main/kotlin/dev/morphia/audits/repairs/FormMigration.kt b/audits/src/main/kotlin/dev/morphia/audits/repairs/FormMigration.kt index 495da50c5bf..67bccce72e2 100644 --- a/audits/src/main/kotlin/dev/morphia/audits/repairs/FormMigration.kt +++ b/audits/src/main/kotlin/dev/morphia/audits/repairs/FormMigration.kt @@ -1,5 +1,6 @@ package dev.morphia.audits.repairs +import com.fasterxml.jackson.annotation.JsonInclude import dev.morphia.audits.model.Operator import dev.morphia.audits.model.OperatorType import dev.morphia.audits.published.PublishedComparison @@ -9,6 +10,7 @@ import dev.morphia.audits.semantics.BsonComparison import dev.morphia.audits.semantics.BsonComparisonState import dev.morphia.audits.semantics.BsonDifference import dev.morphia.audits.semantics.BsonDifferenceKind +import dev.morphia.audits.semantics.BsonPath import dev.morphia.audits.shell.AggregateOperation import dev.morphia.audits.shell.FindOperation import dev.morphia.audits.shell.InsertOperation @@ -89,8 +91,17 @@ data class FormDeclaration( val corrections: List = emptyList(), /** File name of the lock marker: `lock`, or `lockd` for the one fixture that spells it so. */ val marker: String = "lock", + /** Result arrays the server builds in no defined order; omitted from the review when empty. */ + @get:JsonInclude(JsonInclude.Include.NON_EMPTY) + val unorderedArrays: List = emptyList(), ) +/** + * A result array compared as a multiset: [path] is its RFC 6901 pointer within each result, and + * [reason] is the reviewed evidence that the server does not order it. + */ +data class UnorderedArray(val path: String, val reason: String) + /** * What the repair inventory knows about a fixture's test: its lock categories, which decide what an * override may declare (form rules for MORPHIA_FORM, retypes for NUMERIC_TYPE), the extra @@ -206,6 +217,8 @@ data class FormOverride( val collections: Map = emptyMap(), val retypes: List = emptyList(), val corrections: List = emptyList(), + @get:JsonInclude(JsonInclude.Include.NON_EMPTY) + val unorderedArrays: List = emptyList(), ) data class FormInclude(val path: String, val blob: String) @@ -379,6 +392,7 @@ object FormMigration { "${declaration.fixture}: a justification is required exactly " + "when ALTERNATIVE_COMMANDS is declared" } + problems += unordered(declaration) if (outcome.rules != declaration.rules) { problems += "${declaration.fixture}: needs rules ${outcome.rules}, " + @@ -422,6 +436,7 @@ object FormMigration { collections = known.collections, retypes = declaration.retypes, corrections = declaration.corrections, + unorderedArrays = declaration.unorderedArrays, ) } } @@ -764,6 +779,28 @@ object FormMigration { it.fixture to FixtureFacts(it.categories, it.collections, it.helpers) } + /** + * Problems with a declaration's unordered arrays: each a distinct result pointer, with a + * reason. + */ + private fun unordered(declaration: FormDeclaration): List { + val paths = declaration.unorderedArrays.map { it.path } + return declaration.unorderedArrays.flatMap { + listOfNotNull( + "${declaration.fixture}: ${it.path} is not a pointer into a result" + .takeIf { _ -> + !it.path.startsWith('/') || runCatching { BsonPath(it.path) }.isFailure + }, + "${declaration.fixture}: unordered array ${it.path} needs a reason" + .takeIf { _ -> it.reason.isBlank() }, + ) + } + + listOfNotNull( + "${declaration.fixture}: an unordered array is declared twice" + .takeIf { paths.distinct().size != paths.size } + ) + } + private fun facts(facts: Map, fixture: String): FixtureFacts = requireNotNull(facts[fixture]) { "$fixture is not in the repair inventory" } diff --git a/audits/src/main/kotlin/dev/morphia/audits/semantics/BsonComparison.kt b/audits/src/main/kotlin/dev/morphia/audits/semantics/BsonComparison.kt index 6c958da373e..31b23aab37a 100644 --- a/audits/src/main/kotlin/dev/morphia/audits/semantics/BsonComparison.kt +++ b/audits/src/main/kotlin/dev/morphia/audits/semantics/BsonComparison.kt @@ -22,7 +22,10 @@ object BsonComparison { difference(expected!!, actual!!, BsonPath.ROOT) } - /** Unordered means a top-level multiset of rows, never unordered nested arrays. */ + /** + * Unordered means a top-level multiset of rows; nested arrays stay ordered unless the policy + * names them. + */ fun compareResults( expected: List, actual: List, @@ -54,52 +57,17 @@ object BsonComparison { check(expected.size.toLong() * actual.size <= limits.maximumResultPairs) { "Result pair count exceeds comparison limit" } - // Tolerance makes equivalence non-transitive. A greedy removal can reject a valid - // assignment, so compute a perfect bipartite matching with augmenting paths. - val candidates = - expected.map { left -> - actual.map { right -> difference(left, right, BsonPath.ROOT) == null } + // Tolerance makes equivalence non-transitive, so this is a matching, not a removal. + Matching.firstUnmatched(expected.size, actual.size, ::spend) { left, right -> + difference(expected[left], actual[right], BsonPath.ROOT) == null } - val owner = IntArray(actual.size) { -1 } - val assigned = IntArray(expected.size) { -1 } - fun assign(root: Int): Boolean { - // Iterative augmentation keeps the call stack independent of result count. - val previous = IntArray(actual.size) { -1 } - val queue = ArrayDeque() - queue.add(root) - while (queue.isNotEmpty()) { - val left = queue.removeFirst() - for (right in actual.indices) { - spend() - if (!candidates[left][right] || previous[right] != -1) continue - previous[right] = left - if (owner[right] != -1) { - queue.add(owner[right]) - continue - } - var next = right - while (next != -1) { - spend() - val match = previous[next] - val old = assigned[match] - owner[next] = match - assigned[match] = next - next = old - } - return true - } - } - return false - } - expected.indices.forEach { left -> - if (!assign(left)) - return@run BsonDifference( - BsonPath("/$left"), + ?.let { + BsonDifference( + BsonPath("/$it"), BsonDifferenceKind.UNMATCHED_RESULT, - "Multiplicity-preserving matching fails at expected row $left", + "Multiplicity-preserving matching fails at expected row $it", ) - } - null + } } private fun run( @@ -113,6 +81,7 @@ object BsonComparison { policy.copy( unorderedDocuments = policy.unorderedDocuments.toSet(), numericTolerances = policy.numericTolerances.toMap(), + unorderedArrays = policy.unorderedArrays.toSet(), ), limits, ) @@ -222,6 +191,24 @@ object BsonComparison { BsonDifferenceKind.ARRAY_LENGTH, "Expected ${expected.size} array items, observed ${actual.size}", ) + if (path in policy.unorderedArrays) { + check(expected.size.toLong() * actual.size <= limits.maximumResultPairs) { + "Unordered array pair count exceeds comparison limit" + } + return Matching.firstUnmatched(expected.size, actual.size, ::spend) { + left, + right -> + difference(expected[left], actual[right], path.child("$left")) == + null + } + ?.let { + BsonDifference( + path.child("$it"), + BsonDifferenceKind.UNMATCHED_ITEM, + "No distinct item of the unordered array matches item $it", + ) + } + } expected.indices.forEach { difference(expected[it], actual[it], path.child(it.toString()))?.let { return it diff --git a/audits/src/main/kotlin/dev/morphia/audits/semantics/BsonComparisonContracts.kt b/audits/src/main/kotlin/dev/morphia/audits/semantics/BsonComparisonContracts.kt index ba8aefc7e11..873092c0ca9 100644 --- a/audits/src/main/kotlin/dev/morphia/audits/semantics/BsonComparisonContracts.kt +++ b/audits/src/main/kotlin/dev/morphia/audits/semantics/BsonComparisonContracts.kt @@ -40,13 +40,16 @@ data class NumericTolerance( } /** - * Defaults preserve every document's key order and all BSON types and representations. Rules name - * exact paths; array order is never relaxed. Result rules are relative to each row, independent of - * its position in the result set. Callers must not mutate inputs during comparison. + * Defaults preserve every document's key order, every array's order and all BSON types and + * representations. Rules name exact paths. Result rules are relative to each row, independent of + * its position in the result set; a path below an unordered array addresses its items by their + * expected position. Callers must not mutate inputs during comparison. */ data class BsonComparisonPolicy( val unorderedDocuments: Set = emptySet(), val numericTolerances: Map = emptyMap(), + /** Arrays compared as multisets: the same items, as often, in any order. */ + val unorderedArrays: Set = emptySet(), ) enum class ResultOrder { @@ -69,6 +72,8 @@ enum class BsonDifferenceKind { ARRAY_LENGTH, RESULT_COUNT, UNMATCHED_RESULT, + /** An item of an unordered array has no distinct counterpart. */ + UNMATCHED_ITEM, } data class BsonDifference(val path: BsonPath, val kind: BsonDifferenceKind, val message: String) diff --git a/audits/src/main/kotlin/dev/morphia/audits/semantics/Matching.kt b/audits/src/main/kotlin/dev/morphia/audits/semantics/Matching.kt new file mode 100644 index 00000000000..f55f89077ed --- /dev/null +++ b/audits/src/main/kotlin/dev/morphia/audits/semantics/Matching.kt @@ -0,0 +1,50 @@ +package dev.morphia.audits.semantics + +/** Multiset matching for the comparators, where equivalence need not be transitive. */ +internal object Matching { + /** + * Finds a perfect bipartite matching of [lefts] onto [rights] with augmenting paths (a greedy + * removal can reject a valid assignment) and returns the first left index it cannot place, or + * null when every one is matched. [spend] is charged for each step. + */ + fun firstUnmatched( + lefts: Int, + rights: Int, + spend: () -> Unit, + candidate: (Int, Int) -> Boolean, + ): Int? { + val candidates = Array(lefts) { left -> BooleanArray(rights) { candidate(left, it) } } + val owners = IntArray(rights) { -1 } + val assigned = IntArray(lefts) { -1 } + for (root in 0 until lefts) { + // Iterative augmentation keeps the call stack independent of the input size. + val previous = IntArray(rights) { -1 } + val queue = ArrayDeque() + queue.add(root) + var free = -1 + search@ while (queue.isNotEmpty()) { + val left = queue.removeFirst() + for (right in 0 until rights) { + spend() + if (!candidates[left][right] || previous[right] != -1) continue + previous[right] = left + if (owners[right] == -1) { + free = right + break@search + } + queue.add(owners[right]) + } + } + if (free == -1) return root + while (free != -1) { + spend() + val left = previous[free] + val old = assigned[left] + owners[free] = left + assigned[left] = free + free = old + } + } + return null + } +} diff --git a/audits/src/test/kotlin/dev/morphia/audits/offline/FormMigrationTest.kt b/audits/src/test/kotlin/dev/morphia/audits/offline/FormMigrationTest.kt index b53f4e267d4..1cba11963d8 100644 --- a/audits/src/test/kotlin/dev/morphia/audits/offline/FormMigrationTest.kt +++ b/audits/src/test/kotlin/dev/morphia/audits/offline/FormMigrationTest.kt @@ -14,6 +14,7 @@ import dev.morphia.audits.repairs.FormUnresolved import dev.morphia.audits.repairs.NumericRetype import dev.morphia.audits.repairs.NumericType import dev.morphia.audits.repairs.RepairDisposition +import dev.morphia.audits.repairs.UnorderedArray import java.nio.file.Files import java.nio.file.Path import kotlin.io.path.createDirectories @@ -911,6 +912,37 @@ class FormMigrationTest { ) } assertTrue("a justification is required" in unneeded.message!!, unneeded.message) + + // An unordered array is a reviewed result pointer with its evidence, carried to the case. + fun unordered(vararg arrays: UnorderedArray) = + justified.copy( + declarations = + listOf(justified.declarations.single().copy(unorderedArrays = arrays.toList())) + ) + val declared = + FormMigration.capture( + repository, + "head", + pages, + unordered(UnorderedArray("/zipCodes", "the server builds it unordered")), + facts(), + ) + assertEquals( + listOf(UnorderedArray("/zipCodes", "the server builds it unordered")), + declared.overrides.single().unorderedArrays, + ) + listOf( + unordered(UnorderedArray("zipCodes", "unordered")) to "is not a pointer", + unordered(UnorderedArray("/zipCodes", " ")) to "needs a reason", + unordered(UnorderedArray("/a", "x"), UnorderedArray("/a", "y")) to "declared twice", + ) + .forEach { (review, problem) -> + val rejected = + assertThrows(IllegalArgumentException::class.java) { + FormMigration.capture(repository, "head", pages, review, facts()) + } + assertTrue(problem in rejected.message!!, rejected.message) + } } /** @@ -957,7 +989,7 @@ class FormMigrationTest { .map { it.fixture } .toSet(), ) - assertEquals(6, report.overrides.size) + assertEquals(4, report.overrides.size) assertEquals(96, report.unresolved.size) } diff --git a/audits/src/test/kotlin/dev/morphia/audits/offline/PrintedVectorsTest.kt b/audits/src/test/kotlin/dev/morphia/audits/offline/PrintedVectorsTest.kt index ca6e2785e5d..d98de8ca41b 100644 --- a/audits/src/test/kotlin/dev/morphia/audits/offline/PrintedVectorsTest.kt +++ b/audits/src/test/kotlin/dev/morphia/audits/offline/PrintedVectorsTest.kt @@ -52,6 +52,7 @@ class PrintedVectorsTest { constraints, vector.getArray("actual").map { it.asDocument() }, ResultOrder.valueOf(vector.getString("order").value), + unorderedArrays = StrictVectorsTest.unorderedArrays(vector), ) .state .name diff --git a/audits/src/test/kotlin/dev/morphia/audits/offline/StrictVectorsTest.kt b/audits/src/test/kotlin/dev/morphia/audits/offline/StrictVectorsTest.kt index afe3df428f2..32a315495ce 100644 --- a/audits/src/test/kotlin/dev/morphia/audits/offline/StrictVectorsTest.kt +++ b/audits/src/test/kotlin/dev/morphia/audits/offline/StrictVectorsTest.kt @@ -1,16 +1,28 @@ package dev.morphia.audits.offline import dev.morphia.audits.semantics.BsonComparison +import dev.morphia.audits.semantics.BsonComparisonPolicy import dev.morphia.audits.semantics.BsonComparisonState +import dev.morphia.audits.semantics.BsonPath import dev.morphia.audits.semantics.ResultOrder import java.nio.file.Files import java.nio.file.Path +import org.bson.BsonArray import org.bson.BsonDocument import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test /** Core's `StrictBson` runs the same vectors, so the two strict comparators agree. */ class StrictVectorsTest { + companion object { + /** A vector's declared unordered arrays, when it declares any. */ + fun unorderedArrays(vector: BsonDocument): Set = + vector + .getArray("unorderedArrays", BsonArray()) + .map { BsonPath(it.asString().value) } + .toSet() + } + @Test fun goldenVectorsMatchTheStrictComparator() { val root = @@ -48,6 +60,7 @@ class StrictVectorsTest { it.getArray("left").map { row -> row.asDocument() }, it.getArray("right").map { row -> row.asDocument() }, order, + BsonComparisonPolicy(unorderedArrays = unorderedArrays(it)), ) .state == BsonComparisonState.EQUAL, it.getString("name").value, diff --git a/core/src/test/java/dev/morphia/test/OperatorCaseRunner.java b/core/src/test/java/dev/morphia/test/OperatorCaseRunner.java index 1170246b2ad..e80fd9db8d2 100644 --- a/core/src/test/java/dev/morphia/test/OperatorCaseRunner.java +++ b/core/src/test/java/dev/morphia/test/OperatorCaseRunner.java @@ -49,7 +49,9 @@ * prove ({@link PrintedResults}). * * Serialization is compared after the scenario's declared form rules ({@link FormRules}) are applied to both sides. - * Fields named in {@code comparison.ignore} are removed from both results before the published comparison only, a + * Arrays named in {@code comparison.unorderedArrays}, by pointer within each result, are compared as multisets in the + * behavior and published checks. Fields named in {@code comparison.ignore} are removed from both results before the + * published comparison only, a * {@code requirements.minimumServer} skips the case on an older server, and a check the scenario lists under * {@code skipped}, with its reason, is not run. This runner supports aggregations with exact or printed expected results * and no tolerances, datasets or indexes; a scenario that needs any of them fails rather than being checked loosely. @@ -205,6 +207,9 @@ private void run(OperatorCase operatorCase, String kind, Shape shape, BsonDocument skipped = scenario.getDocument("skipped", new BsonDocument()); Set ignore = new TreeSet<>(); scenario.getDocument("comparison").getArray("ignore").forEach(field -> ignore.add(field.asString().getValue())); + Set unordered = new TreeSet<>(); + scenario.getDocument("comparison").getArray("unorderedArrays", new BsonArray()) + .forEach(path -> unordered.add(path.asString().getValue())); MongoDatabase morphia = test.getDatabase(); MongoDatabase reference = test.getDatabase(morphia.getName() + "_reference"); @@ -235,7 +240,7 @@ private void run(OperatorCase operatorCase, String kind, Shape shape, List referenceResults = execution.reference().apply(reference); List morphiaResults = execution.morphia().get(); - if (!StrictBson.equal(referenceResults, morphiaResults, ordered)) { + if (!StrictBson.equal(referenceResults, morphiaResults, ordered, unordered)) { fail(operatorCase.resource() + ": behavior differs\nreference: " + json(referenceResults) + "\nmorphia: " + json(morphiaResults)); } @@ -257,11 +262,11 @@ private void run(OperatorCase operatorCase, String kind, Shape shape, BsonDocument expected = scenario.getDocument("expected"); if (expected.containsKey("documents")) { List published = without(ignore, expected.getArray("documents").getValues()); - if (!StrictBson.equal(published, morphiaResults, ordered)) { + if (!StrictBson.equal(published, morphiaResults, ordered, unordered)) { fail(operatorCase.resource() + ": results differ from the documented results\ndocumented: " + json(published) + "\nmorphia: " + json(morphiaResults)); } - if (!StrictBson.equal(published, referenceResults, ordered)) { + if (!StrictBson.equal(published, referenceResults, ordered, unordered)) { fail(operatorCase.resource() + ": the reference results differ from the documented results\ndocumented: " + json(published) + "\nreference: " + json(referenceResults)); } @@ -270,12 +275,12 @@ private void run(OperatorCase operatorCase, String kind, Shape shape, for (BsonValue constraint : expected.getArray("printed")) { printed.add(PrintedResults.without(ignore, constraint)); } - String difference = PrintedResults.difference(printed, morphiaResults, ordered); + String difference = PrintedResults.difference(printed, morphiaResults, ordered, unordered); if (difference != null) { fail(operatorCase.resource() + ": results differ from the printed results at " + difference + "\nmorphia: " + json(morphiaResults)); } - difference = PrintedResults.difference(printed, referenceResults, ordered); + difference = PrintedResults.difference(printed, referenceResults, ordered, unordered); if (difference != null) { fail(operatorCase.resource() + ": the reference results differ from the printed results at " + difference + "\nreference: " + json(referenceResults)); @@ -305,6 +310,14 @@ private static void supported(OperatorCase operatorCase, BsonDocument scenario) unsupported.add("ignored field " + field); } } + for (BsonValue path : comparison.getArray("unorderedArrays", new BsonArray())) { + if (!path.isString() || !path.asString().getValue().startsWith("/")) { + unsupported.add("unordered array " + path); + } + } + if (!Set.of("order", "rules", "ignore", "unorderedArrays", "tolerance").containsAll(comparison.keySet())) { + unsupported.add("comparison fields " + comparison.keySet()); + } Set keys = Set.of("schemaVersion", "name", "title", "context", "source", "dataset", "collections", "indexes", "action", "expected", "comparison", "requirements", "skipped"); if (!keys.containsAll(scenario.keySet())) { diff --git a/core/src/test/java/dev/morphia/test/PrintedResults.java b/core/src/test/java/dev/morphia/test/PrintedResults.java index 57702df70e8..a1aa2456d1b 100644 --- a/core/src/test/java/dev/morphia/test/PrintedResults.java +++ b/core/src/test/java/dev/morphia/test/PrintedResults.java @@ -6,6 +6,7 @@ import java.util.HashSet; import java.util.List; import java.util.Set; +import java.util.function.BiPredicate; import org.bson.BsonArray; import org.bson.BsonBoolean; @@ -40,35 +41,55 @@ private PrintedResults() { * @throws IllegalArgumentException when the constraints are malformed */ public static String difference(List constraints, List actual, boolean ordered) { + return difference(constraints, actual, ordered, Set.of()); + } + + /** + * @param ordered whether position matters; if not, each result must match a distinct constraint + * @param unorderedArrays the pointers, relative to each result, of the arrays whose printed items each need a + * distinct matching item, in any order + * @return why {@code actual} does not satisfy {@code constraints}, or null when it does + * @throws IllegalArgumentException when the constraints are malformed + */ + public static String difference(List constraints, List actual, boolean ordered, + Set unorderedArrays) { constraints.forEach(PrintedResults::validate); if (constraints.size() != actual.size()) { return "result counts differ"; } if (ordered) { for (int i = 0; i < constraints.size(); i++) { - String difference = difference(constraints.get(i), actual.get(i), "/" + i); + // Paths are relative to the row, as the unordered arrays are, then placed in it. + String difference = difference(constraints.get(i), actual.get(i), "", unorderedArrays); if (difference != null) { - return difference; + return "/" + i + difference; } } return null; } // Constraints overlap: a constraint matching an Int32 or a Double must not take the only match of an exact // Double, so this finds a maximum matching rather than taking the first match. - boolean[][] matches = new boolean[constraints.size()][actual.size()]; - for (int left = 0; left < constraints.size(); left++) { - for (int right = 0; right < actual.size(); right++) { - matches[left][right] = difference(constraints.get(left), actual.get(right), "") == null; + int unmatched = unmatched(constraints.size(), actual.size(), + (left, right) -> difference(constraints.get(left), actual.get(right), "", unorderedArrays) == null); + return unmatched < 0 ? null : "/" + unmatched + ": no result matches this constraint"; + } + + /** @return the first left index a maximum bipartite matching leaves unmatched, or -1 when none is */ + private static int unmatched(int lefts, int rights, BiPredicate candidate) { + boolean[][] matches = new boolean[lefts][rights]; + for (int left = 0; left < lefts; left++) { + for (int right = 0; right < rights; right++) { + matches[left][right] = candidate.test(left, right); } } - int[] owners = new int[actual.size()]; + int[] owners = new int[rights]; Arrays.fill(owners, -1); - for (int left = 0; left < constraints.size(); left++) { - if (!assign(left, matches, owners, new boolean[actual.size()])) { - return "/" + left + ": no result matches this constraint"; + for (int left = 0; left < lefts; left++) { + if (!assign(left, matches, owners, new boolean[rights])) { + return left; } } - return null; + return -1; } /** @@ -156,7 +177,7 @@ private static void validate(BsonValue node) { } } - private static String difference(BsonValue node, BsonValue actual, String path) { + private static String difference(BsonValue node, BsonValue actual, String path, Set unordered) { BsonDocument constraint = node.asDocument(); String kind = constraint.getFirstKey(); BsonValue argument = constraint.get(kind); @@ -186,7 +207,7 @@ private static String difference(BsonValue node, BsonValue actual, String path) for (BsonValue value : argument.asArray()) { BsonDocument field = value.asDocument(); String name = field.getString("name").getValue(); - String difference = difference(field.get("value"), document.get(name), path + "/" + name); + String difference = difference(field.get("value"), document.get(name), child(path, name), unordered); if (difference != null) { return difference; } @@ -197,8 +218,17 @@ private static String difference(BsonValue node, BsonValue actual, String path) if (!(actual instanceof BsonArray array) || array.size() != argument.asArray().size()) { return mismatch; } + if (unordered.contains(path)) { + List items = argument.asArray().getValues(); + int unmatched = unmatched(items.size(), array.size(), + (left, right) -> difference(items.get(left), array.get(right), child(path, String.valueOf(left)), + unordered) == null); + return unmatched < 0 ? null + : child(path, String.valueOf(unmatched)) + ": no item of the unordered array satisfies this constraint"; + } for (int i = 0; i < array.size(); i++) { - String difference = difference(argument.asArray().get(i), array.get(i), path + "/" + i); + String difference = difference(argument.asArray().get(i), array.get(i), child(path, String.valueOf(i)), + unordered); if (difference != null) { return difference; } @@ -231,6 +261,10 @@ private static String difference(BsonValue node, BsonValue actual, String path) } } + private static String child(String path, String segment) { + return path + "/" + segment.replace("~", "~0").replace("/", "~1"); + } + /** JavaScript own-property order: array-index keys first, ascending, then the others in insertion order. */ private static List javaScriptOrder(List keys) { List result = new ArrayList<>(keys.stream().filter(key -> index(key) >= 0) diff --git a/core/src/test/java/dev/morphia/test/PrintedResultsTest.java b/core/src/test/java/dev/morphia/test/PrintedResultsTest.java index 0a7f2b35f6f..0bd28ffbd9f 100644 --- a/core/src/test/java/dev/morphia/test/PrintedResultsTest.java +++ b/core/src/test/java/dev/morphia/test/PrintedResultsTest.java @@ -24,7 +24,9 @@ public void goldenVectors() throws IOException { try { verdict = PrintedResults.difference(vector.getArray("constraints").getValues(), vector.getArray("actual").getValues(), - vector.getString("order").getValue().equals("ORDERED")) == null ? "EQUAL" : "DIFFERENT"; + vector.getString("order").getValue().equals("ORDERED"), StrictBsonTest.unorderedArrays(vector)) == null + ? "EQUAL" + : "DIFFERENT"; } catch (IllegalArgumentException | ClassCastException | org.bson.BsonInvalidOperationException e) { verdict = "INVALID"; } diff --git a/core/src/test/java/dev/morphia/test/StrictBson.java b/core/src/test/java/dev/morphia/test/StrictBson.java index a0c2b42cd64..82f3f1f72d8 100644 --- a/core/src/test/java/dev/morphia/test/StrictBson.java +++ b/core/src/test/java/dev/morphia/test/StrictBson.java @@ -2,6 +2,8 @@ import java.util.ArrayList; import java.util.List; +import java.util.Set; +import java.util.function.IntFunction; import org.bson.BsonArray; import org.bson.BsonDocument; @@ -10,27 +12,51 @@ /** * Strict BSON equality for operator cases: documents must have the same keys in the same order, and every value the - * same BSON type and value. {@link BsonDocument#equals} ignores key order, so it is not used for documents. The - * golden vectors in {@code generated/vectors/strict.json} pin this to the audits comparator's verdicts. + * same BSON type and value. {@link BsonDocument#equals} ignores key order, so it is not used for documents. Arrays + * keep their order unless a comparison names them as unordered, by RFC 6901 pointer relative to each result; an + * unordered array must hold the same items, as often, in any order. The golden vectors in + * {@code generated/vectors/strict.json} pin this to the audits comparator's verdicts. */ public final class StrictBson { private StrictBson() { } public static boolean equal(BsonValue left, BsonValue right) { + return equal(left, right, "", Set.of()); + } + + /** + * @param ordered whether position matters; if not, the lists must be equal as multisets + */ + public static boolean equal(List left, List right, boolean ordered) { + return equal(left, right, ordered, Set.of()); + } + + /** + * @param ordered whether position matters; if not, the lists must be equal as multisets + * @param unorderedArrays the pointers, relative to each result, of the arrays compared as multisets + */ + public static boolean equal(List left, List right, boolean ordered, + Set unorderedArrays) { + return equal(left, right, ordered, row -> "", unorderedArrays); + } + + /** {@code path} is the pointer of {@code left} and {@code right}, and items are addressed by their left index. */ + private static boolean equal(BsonValue left, BsonValue right, String path, Set unordered) { if (left instanceof BsonDocument a && right instanceof BsonDocument b) { if (!new ArrayList<>(a.keySet()).equals(new ArrayList<>(b.keySet()))) { return false; } for (String key : a.keySet()) { - if (!equal(a.get(key), b.get(key))) { + if (!equal(a.get(key), b.get(key), child(path, key), unordered)) { return false; } } return true; } if (left instanceof BsonArray a && right instanceof BsonArray b) { - return equal(a.getValues(), b.getValues(), true); + return equal(a.getValues(), b.getValues(), !unordered.contains(path), + item -> child(path, String.valueOf(item)), unordered); } if (left instanceof BsonDouble a && right instanceof BsonDouble b) { // Raw bits, as the audits comparator compares doubles: -0.0 is not 0.0, and NaN payloads differ. @@ -40,25 +66,27 @@ public static boolean equal(BsonValue left, BsonValue right) { } /** - * @param ordered whether position matters; if not, the lists must be equal as multisets + * {@code at} gives each left element's pointer: the row's own for results, the item's for an array. Strict + * equality is an equivalence, so taking the first match never rejects a valid pairing. */ - public static boolean equal(List left, List right, boolean ordered) { + private static boolean equal(List left, List right, boolean ordered, + IntFunction at, Set unordered) { if (left.size() != right.size()) { return false; } if (ordered) { for (int i = 0; i < left.size(); i++) { - if (!equal(left.get(i), right.get(i))) { + if (!equal(left.get(i), right.get(i), at.apply(i), unordered)) { return false; } } return true; } List remaining = new ArrayList<>(right); - for (BsonValue value : left) { + for (int index = 0; index < left.size(); index++) { int match = -1; for (int i = 0; i < remaining.size() && match < 0; i++) { - if (equal(value, remaining.get(i))) { + if (equal(left.get(index), remaining.get(i), at.apply(index), unordered)) { match = i; } } @@ -69,4 +97,8 @@ public static boolean equal(List left, List unorderedArrays(BsonDocument vector) { + Set paths = new TreeSet<>(); + vector.getArray("unorderedArrays", new BsonArray()).forEach(path -> paths.add(path.asString().getValue())); + return paths; + } + /** Extended JSON cannot spell a NaN payload, so this is not a vector; the audits comparator compares raw bits. */ @Test public void nanPayloadsDiffer() { diff --git a/core/src/test/java/dev/morphia/test/aggregation/stages/TestGraphLookup.java b/core/src/test/java/dev/morphia/test/aggregation/stages/TestGraphLookup.java index b73d0a4f88a..c06ba4b307f 100644 --- a/core/src/test/java/dev/morphia/test/aggregation/stages/TestGraphLookup.java +++ b/core/src/test/java/dev/morphia/test/aggregation/stages/TestGraphLookup.java @@ -20,7 +20,7 @@ public class TestGraphLookup extends TemplatedTestBase { @DisplayName("Within a Single Collection") public void testWithinASingleCollection() { testPipeline(new ActionTestOptions().removeIds(true).orderMatters(false), - (aggregation) -> aggregation.pipeline(graphLookup(EXAMPLE_TEST_COLLECTION).startWith("$reportsTo") + (aggregation) -> aggregation.pipeline(graphLookup("employees").startWith("$reportsTo") .connectFromField("reportsTo").connectToField("name").as("reportingHierarchy"))); } @@ -48,7 +48,7 @@ public void testAcrossMultipleCollections() { public void testWithAQueryFilter() { testPipeline(new ActionTestOptions().orderMatters(false), (aggregation) -> aggregation.pipeline( match(eq("name", "Tanya Jordan")), - graphLookup(EXAMPLE_TEST_COLLECTION).startWith("$friends").connectFromField("friends") + graphLookup("people").startWith("$friends").connectFromField("friends") .connectToField("name").as("golfers").restrict(eq("hobbies", "golf")), project().include("name").include("friends").include("connections who play golf", "$golfers.name") diff --git a/core/src/test/resources/dev/morphia/test/aggregation/stages/graphLookup/withAQueryFilter/action.json b/core/src/test/resources/dev/morphia/test/aggregation/stages/graphLookup/withAQueryFilter/action.json deleted file mode 100644 index ac87f4f13e8..00000000000 --- a/core/src/test/resources/dev/morphia/test/aggregation/stages/graphLookup/withAQueryFilter/action.json +++ /dev/null @@ -1,18 +0,0 @@ - [ - { $match: { "name": "Tanya Jordan" } }, - { $graphLookup: { - from: "example_test", - startWith: "$friends", - connectFromField: "friends", - connectToField: "name", - as: "golfers", - restrictSearchWithMatch: { "hobbies" : "golf" } - } - }, - { $project: { - "name": 1, - "friends": 1, - "connections who play golf": "$golfers.name" - } - } -] \ No newline at end of file diff --git a/core/src/test/resources/dev/morphia/test/aggregation/stages/graphLookup/withAQueryFilter/data.json b/core/src/test/resources/dev/morphia/test/aggregation/stages/graphLookup/withAQueryFilter/data.json deleted file mode 100644 index c186b3a55f2..00000000000 --- a/core/src/test/resources/dev/morphia/test/aggregation/stages/graphLookup/withAQueryFilter/data.json +++ /dev/null @@ -1,6 +0,0 @@ -{ "_id" : 1, "name" : "Tanya Jordan", "friends" : [ "Shirley Soto", "Terry Hawkins", "Carole Hale" ], "hobbies" : [ "tennis", "unicycling", "golf" ]} -{ "_id" : 2, "name" : "Carole Hale", "friends" : [ "Joseph Dennis", "Tanya Jordan", "Terry Hawkins" ], "hobbies" : [ "archery", "golf", "woodworking" ]} -{ "_id" : 3, "name" : "Terry Hawkins", "friends" : [ "Tanya Jordan", "Carole Hale", "Angelo Ward" ], "hobbies" : [ "knitting", "frisbee" ]} -{ "_id" : 4, "name" : "Joseph Dennis", "friends" : [ "Angelo Ward", "Carole Hale" ], "hobbies" : [ "tennis", "golf", "topiary" ]} -{ "_id" : 5, "name" : "Angelo Ward", "friends" : [ "Terry Hawkins", "Shirley Soto", "Joseph Dennis" ], "hobbies" : [ "travel", "ceramics", "golf" ]} -{ "_id" : 6, "name" : "Shirley Soto", "friends" : [ "Angelo Ward", "Tanya Jordan", "Carole Hale" ], "hobbies" : [ "frisbee", "set theory" ] } \ No newline at end of file diff --git a/core/src/test/resources/dev/morphia/test/aggregation/stages/graphLookup/withAQueryFilter/expected.json b/core/src/test/resources/dev/morphia/test/aggregation/stages/graphLookup/withAQueryFilter/expected.json deleted file mode 100644 index 90721d94005..00000000000 --- a/core/src/test/resources/dev/morphia/test/aggregation/stages/graphLookup/withAQueryFilter/expected.json +++ /dev/null @@ -1 +0,0 @@ -{ "_id" : 1, "name" : "Tanya Jordan", "friends" : [ "Shirley Soto", "Terry Hawkins", "Carole Hale" ], "connections who play golf" : [ "Joseph Dennis", "Tanya Jordan", "Angelo Ward", "Carole Hale" ]} \ No newline at end of file diff --git a/core/src/test/resources/dev/morphia/test/aggregation/stages/graphLookup/withAQueryFilter/name b/core/src/test/resources/dev/morphia/test/aggregation/stages/graphLookup/withAQueryFilter/name deleted file mode 100644 index 8e21f884b28..00000000000 --- a/core/src/test/resources/dev/morphia/test/aggregation/stages/graphLookup/withAQueryFilter/name +++ /dev/null @@ -1 +0,0 @@ -With a Query Filter \ No newline at end of file diff --git a/core/src/test/resources/dev/morphia/test/aggregation/stages/graphLookup/withAQueryFilter/scenario.json b/core/src/test/resources/dev/morphia/test/aggregation/stages/graphLookup/withAQueryFilter/scenario.json new file mode 100644 index 00000000000..3992a871179 --- /dev/null +++ b/core/src/test/resources/dev/morphia/test/aggregation/stages/graphLookup/withAQueryFilter/scenario.json @@ -0,0 +1,217 @@ +{ + "schemaVersion": { + "$numberInt": "1" + }, + "name": "aggregation/stages/graphLookup/withAQueryFilter", + "title": "With a Query Filter", + "context": "STAGE", + "source": { + "repository": "mongodb/docs", + "commit": "fbff8bd22e055259d67b394c854f128340571b1f", + "path": "source/reference/operator/aggregation/graphLookup.txt", + "blob": "d00d3c58699ec5ad0505fdcab3026e35f522ce87" + }, + "dataset": null, + "collections": { + "people": [ + { + "_id": { + "$numberInt": "1" + }, + "name": "Tanya Jordan", + "friends": [ + "Shirley Soto", + "Terry Hawkins", + "Carole Hale" + ], + "hobbies": [ + "tennis", + "unicycling", + "golf" + ] + }, + { + "_id": { + "$numberInt": "2" + }, + "name": "Carole Hale", + "friends": [ + "Joseph Dennis", + "Tanya Jordan", + "Terry Hawkins" + ], + "hobbies": [ + "archery", + "golf", + "woodworking" + ] + }, + { + "_id": { + "$numberInt": "3" + }, + "name": "Terry Hawkins", + "friends": [ + "Tanya Jordan", + "Carole Hale", + "Angelo Ward" + ], + "hobbies": [ + "knitting", + "frisbee" + ] + }, + { + "_id": { + "$numberInt": "4" + }, + "name": "Joseph Dennis", + "friends": [ + "Angelo Ward", + "Carole Hale" + ], + "hobbies": [ + "tennis", + "golf", + "topiary" + ] + }, + { + "_id": { + "$numberInt": "5" + }, + "name": "Angelo Ward", + "friends": [ + "Terry Hawkins", + "Shirley Soto", + "Joseph Dennis" + ], + "hobbies": [ + "travel", + "ceramics", + "golf" + ] + }, + { + "_id": { + "$numberInt": "6" + }, + "name": "Shirley Soto", + "friends": [ + "Angelo Ward", + "Tanya Jordan", + "Carole Hale" + ], + "hobbies": [ + "frisbee", + "set theory" + ] + } + ] + }, + "indexes": [], + "action": { + "kind": "aggregate", + "collection": "people", + "pipeline": [ + { + "$match": { + "name": "Tanya Jordan" + } + }, + { + "$graphLookup": { + "from": "people", + "startWith": "$friends", + "connectFromField": "friends", + "connectToField": "name", + "as": "golfers", + "restrictSearchWithMatch": { + "hobbies": "golf" + } + } + }, + { + "$project": { + "name": { + "$numberInt": "1" + }, + "friends": { + "$numberInt": "1" + }, + "connections who play golf": "$golfers.name" + } + } + ] + }, + "expected": { + "printed": [ + { + "document": [ + { + "name": "_id", + "value": { + "whole": { + "$numberInt": "1" + } + } + }, + { + "name": "name", + "value": { + "text": "Tanya Jordan" + } + }, + { + "name": "friends", + "value": { + "array": [ + { + "text": "Shirley Soto" + }, + { + "text": "Terry Hawkins" + }, + { + "text": "Carole Hale" + } + ] + } + }, + { + "name": "connections who play golf", + "value": { + "array": [ + { + "text": "Joseph Dennis" + }, + { + "text": "Tanya Jordan" + }, + { + "text": "Angelo Ward" + }, + { + "text": "Carole Hale" + } + ] + } + } + ] + } + ] + }, + "comparison": { + "order": "UNORDERED", + "rules": [], + "ignore": [], + "unorderedArrays": [ + "/connections who play golf" + ], + "tolerance": null + }, + "requirements": { + "minimumServer": null, + "topology": "STANDALONE" + } +} diff --git a/core/src/test/resources/dev/morphia/test/aggregation/stages/graphLookup/withinASingleCollection/action.json b/core/src/test/resources/dev/morphia/test/aggregation/stages/graphLookup/withinASingleCollection/action.json deleted file mode 100644 index f58cd658c8d..00000000000 --- a/core/src/test/resources/dev/morphia/test/aggregation/stages/graphLookup/withinASingleCollection/action.json +++ /dev/null @@ -1,11 +0,0 @@ - [ - { - $graphLookup: { - from: "example_test", - startWith: "$reportsTo", - connectFromField: "reportsTo", - connectToField: "name", - as: "reportingHierarchy" - } - } -] \ No newline at end of file diff --git a/core/src/test/resources/dev/morphia/test/aggregation/stages/graphLookup/withinASingleCollection/data.json b/core/src/test/resources/dev/morphia/test/aggregation/stages/graphLookup/withinASingleCollection/data.json deleted file mode 100644 index 17b661bb6c4..00000000000 --- a/core/src/test/resources/dev/morphia/test/aggregation/stages/graphLookup/withinASingleCollection/data.json +++ /dev/null @@ -1,6 +0,0 @@ -{ "_id" : 1, "name" : "Dev" }, -{ "_id" : 2, "name" : "Eliot", "reportsTo" : "Dev" }, -{ "_id" : 3, "name" : "Ron", "reportsTo" : "Eliot" }, -{ "_id" : 4, "name" : "Andrew", "reportsTo" : "Eliot" }, -{ "_id" : 5, "name" : "Asya", "reportsTo" : "Ron" }, -{ "_id" : 6, "name" : "Dan", "reportsTo" : "Andrew" } \ No newline at end of file diff --git a/core/src/test/resources/dev/morphia/test/aggregation/stages/graphLookup/withinASingleCollection/expected.json b/core/src/test/resources/dev/morphia/test/aggregation/stages/graphLookup/withinASingleCollection/expected.json deleted file mode 100644 index ede26931f6f..00000000000 --- a/core/src/test/resources/dev/morphia/test/aggregation/stages/graphLookup/withinASingleCollection/expected.json +++ /dev/null @@ -1,6 +0,0 @@ -{"_id" : 1, "name" : "Dev", "reportingHierarchy" : [ ]} -{"_id" : 2, "name" : "Eliot", "reportsTo" : "Dev", "reportingHierarchy" : [{ "_id" : 1, "name" : "Dev" }]} -{"_id" : 3, "name" : "Ron", "reportsTo" : "Eliot", "reportingHierarchy" : [{ "_id" : 1, "name" : "Dev" }, { "_id" : 2, "name" : "Eliot", "reportsTo" : "Dev" }]} -{"_id" : 4, "name" : "Andrew", "reportsTo" : "Eliot", "reportingHierarchy" : [{ "_id" : 1, "name" : "Dev" }, { "_id" : 2, "name" : "Eliot", "reportsTo" : "Dev" }]} -{"_id" : 5, "name" : "Asya", "reportsTo" : "Ron", "reportingHierarchy" : [{ "_id" : 1, "name" : "Dev" }, { "_id" : 2, "name" : "Eliot", "reportsTo" : "Dev" }, { "_id" : 3, "name" : "Ron", "reportsTo" : "Eliot" }]} -{"_id" : 6, "name" : "Dan", "reportsTo" : "Andrew", "reportingHierarchy" : [{ "_id" : 1, "name" : "Dev" }, { "_id" : 2, "name" : "Eliot", "reportsTo" : "Dev" }, { "_id" : 4, "name" : "Andrew", "reportsTo" : "Eliot" }]} \ No newline at end of file diff --git a/core/src/test/resources/dev/morphia/test/aggregation/stages/graphLookup/withinASingleCollection/name b/core/src/test/resources/dev/morphia/test/aggregation/stages/graphLookup/withinASingleCollection/name deleted file mode 100644 index c7a9f1b345b..00000000000 --- a/core/src/test/resources/dev/morphia/test/aggregation/stages/graphLookup/withinASingleCollection/name +++ /dev/null @@ -1 +0,0 @@ -Within a Single Collection \ No newline at end of file diff --git a/core/src/test/resources/dev/morphia/test/aggregation/stages/graphLookup/withinASingleCollection/scenario.json b/core/src/test/resources/dev/morphia/test/aggregation/stages/graphLookup/withinASingleCollection/scenario.json new file mode 100644 index 00000000000..fd76580e645 --- /dev/null +++ b/core/src/test/resources/dev/morphia/test/aggregation/stages/graphLookup/withinASingleCollection/scenario.json @@ -0,0 +1,508 @@ +{ + "schemaVersion": { + "$numberInt": "1" + }, + "name": "aggregation/stages/graphLookup/withinASingleCollection", + "title": "Within a Single Collection", + "context": "STAGE", + "source": { + "repository": "mongodb/docs", + "commit": "fbff8bd22e055259d67b394c854f128340571b1f", + "path": "source/reference/operator/aggregation/graphLookup.txt", + "blob": "d00d3c58699ec5ad0505fdcab3026e35f522ce87" + }, + "dataset": null, + "collections": { + "employees": [ + { + "_id": { + "$numberInt": "1" + }, + "name": "Dev" + }, + { + "_id": { + "$numberInt": "2" + }, + "name": "Eliot", + "reportsTo": "Dev" + }, + { + "_id": { + "$numberInt": "3" + }, + "name": "Ron", + "reportsTo": "Eliot" + }, + { + "_id": { + "$numberInt": "4" + }, + "name": "Andrew", + "reportsTo": "Eliot" + }, + { + "_id": { + "$numberInt": "5" + }, + "name": "Asya", + "reportsTo": "Ron" + }, + { + "_id": { + "$numberInt": "6" + }, + "name": "Dan", + "reportsTo": "Andrew" + } + ] + }, + "indexes": [], + "action": { + "kind": "aggregate", + "collection": "employees", + "pipeline": [ + { + "$graphLookup": { + "from": "employees", + "startWith": "$reportsTo", + "connectFromField": "reportsTo", + "connectToField": "name", + "as": "reportingHierarchy" + } + } + ] + }, + "expected": { + "printed": [ + { + "document": [ + { + "name": "_id", + "value": { + "whole": { + "$numberInt": "1" + } + } + }, + { + "name": "name", + "value": { + "text": "Dev" + } + }, + { + "name": "reportingHierarchy", + "value": { + "array": [] + } + } + ] + }, + { + "document": [ + { + "name": "_id", + "value": { + "whole": { + "$numberInt": "2" + } + } + }, + { + "name": "name", + "value": { + "text": "Eliot" + } + }, + { + "name": "reportsTo", + "value": { + "text": "Dev" + } + }, + { + "name": "reportingHierarchy", + "value": { + "array": [ + { + "document": [ + { + "name": "_id", + "value": { + "whole": { + "$numberInt": "1" + } + } + }, + { + "name": "name", + "value": { + "text": "Dev" + } + } + ] + } + ] + } + } + ] + }, + { + "document": [ + { + "name": "_id", + "value": { + "whole": { + "$numberInt": "3" + } + } + }, + { + "name": "name", + "value": { + "text": "Ron" + } + }, + { + "name": "reportsTo", + "value": { + "text": "Eliot" + } + }, + { + "name": "reportingHierarchy", + "value": { + "array": [ + { + "document": [ + { + "name": "_id", + "value": { + "whole": { + "$numberInt": "1" + } + } + }, + { + "name": "name", + "value": { + "text": "Dev" + } + } + ] + }, + { + "document": [ + { + "name": "_id", + "value": { + "whole": { + "$numberInt": "2" + } + } + }, + { + "name": "name", + "value": { + "text": "Eliot" + } + }, + { + "name": "reportsTo", + "value": { + "text": "Dev" + } + } + ] + } + ] + } + } + ] + }, + { + "document": [ + { + "name": "_id", + "value": { + "whole": { + "$numberInt": "4" + } + } + }, + { + "name": "name", + "value": { + "text": "Andrew" + } + }, + { + "name": "reportsTo", + "value": { + "text": "Eliot" + } + }, + { + "name": "reportingHierarchy", + "value": { + "array": [ + { + "document": [ + { + "name": "_id", + "value": { + "whole": { + "$numberInt": "1" + } + } + }, + { + "name": "name", + "value": { + "text": "Dev" + } + } + ] + }, + { + "document": [ + { + "name": "_id", + "value": { + "whole": { + "$numberInt": "2" + } + } + }, + { + "name": "name", + "value": { + "text": "Eliot" + } + }, + { + "name": "reportsTo", + "value": { + "text": "Dev" + } + } + ] + } + ] + } + } + ] + }, + { + "document": [ + { + "name": "_id", + "value": { + "whole": { + "$numberInt": "5" + } + } + }, + { + "name": "name", + "value": { + "text": "Asya" + } + }, + { + "name": "reportsTo", + "value": { + "text": "Ron" + } + }, + { + "name": "reportingHierarchy", + "value": { + "array": [ + { + "document": [ + { + "name": "_id", + "value": { + "whole": { + "$numberInt": "1" + } + } + }, + { + "name": "name", + "value": { + "text": "Dev" + } + } + ] + }, + { + "document": [ + { + "name": "_id", + "value": { + "whole": { + "$numberInt": "2" + } + } + }, + { + "name": "name", + "value": { + "text": "Eliot" + } + }, + { + "name": "reportsTo", + "value": { + "text": "Dev" + } + } + ] + }, + { + "document": [ + { + "name": "_id", + "value": { + "whole": { + "$numberInt": "3" + } + } + }, + { + "name": "name", + "value": { + "text": "Ron" + } + }, + { + "name": "reportsTo", + "value": { + "text": "Eliot" + } + } + ] + } + ] + } + } + ] + }, + { + "document": [ + { + "name": "_id", + "value": { + "whole": { + "$numberInt": "6" + } + } + }, + { + "name": "name", + "value": { + "text": "Dan" + } + }, + { + "name": "reportsTo", + "value": { + "text": "Andrew" + } + }, + { + "name": "reportingHierarchy", + "value": { + "array": [ + { + "document": [ + { + "name": "_id", + "value": { + "whole": { + "$numberInt": "1" + } + } + }, + { + "name": "name", + "value": { + "text": "Dev" + } + } + ] + }, + { + "document": [ + { + "name": "_id", + "value": { + "whole": { + "$numberInt": "2" + } + } + }, + { + "name": "name", + "value": { + "text": "Eliot" + } + }, + { + "name": "reportsTo", + "value": { + "text": "Dev" + } + } + ] + }, + { + "document": [ + { + "name": "_id", + "value": { + "whole": { + "$numberInt": "4" + } + } + }, + { + "name": "name", + "value": { + "text": "Andrew" + } + }, + { + "name": "reportsTo", + "value": { + "text": "Eliot" + } + } + ] + } + ] + } + } + ] + } + ] + }, + "comparison": { + "order": "UNORDERED", + "rules": [], + "ignore": [ + "_id" + ], + "unorderedArrays": [ + "/reportingHierarchy" + ], + "tolerance": null + }, + "requirements": { + "minimumServer": null, + "topology": "STANDALONE" + } +} diff --git a/core/src/test/resources/dev/morphia/test/generated/manifest.json b/core/src/test/resources/dev/morphia/test/generated/manifest.json index f89001ec63e..dd94ad31b0f 100644 --- a/core/src/test/resources/dev/morphia/test/generated/manifest.json +++ b/core/src/test/resources/dev/morphia/test/generated/manifest.json @@ -1169,6 +1169,16 @@ "name" : "aggregation/stages/fill/indicateIfAFieldWasPopulatedUsingFill", "scenario" : "/dev/morphia/test/aggregation/stages/fill/indicateIfAFieldWasPopulatedUsingFill/scenario.json", "test" : "dev.morphia.test.aggregation.stages.TestFill#testIndicateIfAFieldWasPopulatedUsingFill" + }, { + "kind" : "CONVERTED", + "name" : "aggregation/stages/graphLookup/withAQueryFilter", + "scenario" : "/dev/morphia/test/aggregation/stages/graphLookup/withAQueryFilter/scenario.json", + "test" : "dev.morphia.test.aggregation.stages.TestGraphLookup#testWithAQueryFilter" + }, { + "kind" : "CONVERTED", + "name" : "aggregation/stages/graphLookup/withinASingleCollection", + "scenario" : "/dev/morphia/test/aggregation/stages/graphLookup/withinASingleCollection/scenario.json", + "test" : "dev.morphia.test.aggregation.stages.TestGraphLookup#testWithinASingleCollection" }, { "kind" : "CONVERTED", "name" : "aggregation/stages/group/pivotData", @@ -2686,6 +2696,14 @@ "owner" : "GENERATED", "path" : "src/test/resources/dev/morphia/test/aggregation/stages/fill/indicateIfAFieldWasPopulatedUsingFill/scenario.json", "sha256" : "9fc2340e7a6542e49d906f0db3657c46fb4b65cf627837632b5c69e957eb6f53" + }, { + "owner" : "GENERATED", + "path" : "src/test/resources/dev/morphia/test/aggregation/stages/graphLookup/withAQueryFilter/scenario.json", + "sha256" : "386b91b708f76eac8a815bfe7b8742266d28c404d9553fdd0bfe5acca6bfd5e9" + }, { + "owner" : "GENERATED", + "path" : "src/test/resources/dev/morphia/test/aggregation/stages/graphLookup/withinASingleCollection/scenario.json", + "sha256" : "b27a28f73a06a6c9fd8f53eacfc6c7e9568056f56594cb72635c5c9e572998f7" }, { "owner" : "GENERATED", "path" : "src/test/resources/dev/morphia/test/aggregation/stages/group/pivotData/scenario.json", @@ -2889,7 +2907,7 @@ }, { "owner" : "PROTECTED", "path" : "src/test/resources/dev/morphia/test/generated/vectors/printed.json", - "sha256" : "5bc6d7520534154556af86805d35d1c5b4c1961f92b43b267b70b18f84f986a0" + "sha256" : "c885ad7dffa78942841c90f2f99fd885fb13d2799ab329e9f9c59331b5ffb01f" }, { "owner" : "PROTECTED", "path" : "src/test/resources/dev/morphia/test/generated/vectors/rules.json", @@ -2897,7 +2915,7 @@ }, { "owner" : "PROTECTED", "path" : "src/test/resources/dev/morphia/test/generated/vectors/strict.json", - "sha256" : "88907960a183757fef6f2793f6ce64057ce3fa5c28e8c4a65fb44f07f2047db8" + "sha256" : "3b16a4c4fb0633e0466290b6a157a2801fddd36019251f844512162a718ea331" }, { "owner" : "GENERATED", "path" : "src/test/resources/dev/morphia/test/query/filters/all/useAllToMatchValues/scenario.json", diff --git a/core/src/test/resources/dev/morphia/test/generated/vectors/printed.json b/core/src/test/resources/dev/morphia/test/generated/vectors/printed.json index 3b8d7f797bb..a564a7aa8d0 100644 --- a/core/src/test/resources/dev/morphia/test/generated/vectors/printed.json +++ b/core/src/test/resources/dev/morphia/test/generated/vectors/printed.json @@ -934,6 +934,316 @@ } ], "verdict": "INVALID" + }, + { + "name": "unordered array reordered", + "order": "ORDERED", + "unorderedArrays": [ + "/a" + ], + "constraints": [ + { + "document": [ + { + "name": "a", + "value": { + "array": [ + { + "document": [ + { + "name": "n", + "value": { + "whole": { + "$numberInt": "1" + } + } + } + ] + }, + { + "document": [ + { + "name": "n", + "value": { + "whole": { + "$numberInt": "2" + } + } + } + ] + } + ] + } + } + ] + } + ], + "actual": [ + { + "a": [ + { + "n": { + "$numberInt": "2" + } + }, + { + "n": { + "$numberInt": "1" + } + } + ] + } + ], + "verdict": "EQUAL" + }, + { + "name": "undeclared printed array reordered", + "order": "ORDERED", + "constraints": [ + { + "document": [ + { + "name": "a", + "value": { + "array": [ + { + "whole": { + "$numberInt": "1" + } + }, + { + "whole": { + "$numberInt": "2" + } + } + ] + } + } + ] + } + ], + "actual": [ + { + "a": [ + { + "$numberInt": "2" + }, + { + "$numberInt": "1" + } + ] + } + ], + "verdict": "DIFFERENT" + }, + { + "name": "unordered array multiplicity", + "order": "ORDERED", + "unorderedArrays": [ + "/a" + ], + "constraints": [ + { + "document": [ + { + "name": "a", + "value": { + "array": [ + { + "whole": { + "$numberInt": "1" + } + }, + { + "whole": { + "$numberInt": "1" + } + }, + { + "whole": { + "$numberInt": "2" + } + } + ] + } + } + ] + } + ], + "actual": [ + { + "a": [ + { + "$numberInt": "1" + }, + { + "$numberInt": "2" + }, + { + "$numberInt": "2" + } + ] + } + ], + "verdict": "DIFFERENT" + }, + { + "name": "unordered array item type", + "order": "ORDERED", + "unorderedArrays": [ + "/a" + ], + "constraints": [ + { + "document": [ + { + "name": "a", + "value": { + "array": [ + { + "text": "x" + }, + { + "whole": { + "$numberInt": "2" + } + } + ] + } + } + ] + } + ], + "actual": [ + { + "a": [ + { + "$numberLong": "2" + }, + "x" + ] + } + ], + "verdict": "DIFFERENT" + }, + { + "name": "unordered array matches overlapping constraints", + "order": "ORDERED", + "unorderedArrays": [ + "/a" + ], + "constraints": [ + { + "document": [ + { + "name": "a", + "value": { + "array": [ + { + "whole": { + "$numberInt": "4" + } + }, + { + "exact": { + "$numberDouble": "4.0" + } + } + ] + } + } + ] + } + ], + "actual": [ + { + "a": [ + { + "$numberDouble": "4.0" + }, + { + "$numberInt": "4" + } + ] + } + ], + "verdict": "EQUAL" + }, + { + "name": "unordered array path is per row", + "order": "UNORDERED", + "unorderedArrays": [ + "/a" + ], + "constraints": [ + { + "document": [ + { + "name": "_id", + "value": { + "whole": { + "$numberInt": "1" + } + } + }, + { + "name": "a", + "value": { + "array": [ + { + "text": "x" + }, + { + "text": "y" + } + ] + } + } + ] + }, + { + "document": [ + { + "name": "_id", + "value": { + "whole": { + "$numberInt": "2" + } + } + }, + { + "name": "a", + "value": { + "array": [ + { + "text": "z" + } + ] + } + } + ] + } + ], + "actual": [ + { + "_id": { + "$numberInt": "2" + }, + "a": [ + "z" + ] + }, + { + "_id": { + "$numberInt": "1" + }, + "a": [ + "y", + "x" + ] + } + ], + "verdict": "EQUAL" } ] } diff --git a/core/src/test/resources/dev/morphia/test/generated/vectors/strict.json b/core/src/test/resources/dev/morphia/test/generated/vectors/strict.json index cd3705bfb91..6ab21e3676d 100644 --- a/core/src/test/resources/dev/morphia/test/generated/vectors/strict.json +++ b/core/src/test/resources/dev/morphia/test/generated/vectors/strict.json @@ -34,6 +34,30 @@ "right": [ { "_id": { "$numberInt": "1" } }, { "_id": { "$numberInt": "2" } } ] }, { "name": "result count", "ordered": false, "equal": false, "left": [ { "_id": { "$numberInt": "1" } } ], - "right": [ { "_id": { "$numberInt": "1" } }, { "_id": { "$numberInt": "1" } } ] } + "right": [ { "_id": { "$numberInt": "1" } }, { "_id": { "$numberInt": "1" } } ] }, + { "name": "undeclared array reordered", "ordered": true, "equal": false, + "left": [ { "a": [ { "$numberInt": "1" }, { "$numberInt": "2" } ] } ], + "right": [ { "a": [ { "$numberInt": "2" }, { "$numberInt": "1" } ] } ] }, + { "name": "unordered array reordered", "ordered": true, "equal": true, "unorderedArrays": [ "/a" ], + "left": [ { "a": [ { "n": { "$numberInt": "1" } }, { "n": { "$numberInt": "2" } } ] } ], + "right": [ { "a": [ { "n": { "$numberInt": "2" } }, { "n": { "$numberInt": "1" } } ] } ] }, + { "name": "unordered array multiplicity", "ordered": true, "equal": false, "unorderedArrays": [ "/a" ], + "left": [ { "a": [ { "$numberInt": "1" }, { "$numberInt": "1" }, { "$numberInt": "2" } ] } ], + "right": [ { "a": [ { "$numberInt": "1" }, { "$numberInt": "2" }, { "$numberInt": "2" } ] } ] }, + { "name": "unordered array item type", "ordered": true, "equal": false, "unorderedArrays": [ "/a" ], + "left": [ { "a": [ { "n": { "$numberInt": "1" } }, { "n": { "$numberInt": "2" } } ] } ], + "right": [ { "a": [ { "n": { "$numberInt": "2" } }, { "n": { "$numberLong": "1" } } ] } ] }, + { "name": "unordered array keeps its items' arrays ordered", "ordered": true, "equal": false, "unorderedArrays": [ "/a" ], + "left": [ { "a": [ [ { "$numberInt": "1" }, { "$numberInt": "2" } ] ] } ], + "right": [ { "a": [ [ { "$numberInt": "2" }, { "$numberInt": "1" } ] ] } ] }, + { "name": "unordered array path is per row", "ordered": false, "equal": true, "unorderedArrays": [ "/a" ], + "left": [ { "_id": { "$numberInt": "1" }, "a": [ "x", "y" ] }, { "_id": { "$numberInt": "2" }, "a": [ "z" ] } ], + "right": [ { "_id": { "$numberInt": "2" }, "a": [ "z" ] }, { "_id": { "$numberInt": "1" }, "a": [ "y", "x" ] } ] }, + { "name": "unordered array path is exact", "ordered": true, "equal": false, "unorderedArrays": [ "/a" ], + "left": [ { "b": [ "x", "y" ] } ], + "right": [ { "b": [ "y", "x" ] } ] }, + { "name": "unordered array path escapes", "ordered": true, "equal": true, "unorderedArrays": [ "/a~1b" ], + "left": [ { "a/b": [ "x", "y" ] } ], + "right": [ { "a/b": [ "y", "x" ] } ] } ] } diff --git a/design/operator-audits-bson-comparison.md b/design/operator-audits-bson-comparison.md index 2d8b523ea27..bd16a25b585 100644 --- a/design/operator-audits-bson-comparison.md +++ b/design/operator-audits-bson-comparison.md @@ -47,11 +47,17 @@ There are no wildcards, recursive relaxations, or implicit omission rules. A zero tolerance explicitly allows equal finite numeric values with different representations (for example Decimal128 `1.0`/`1.00` or signed zero). It never permits INT32/INT64/DOUBLE/DECIMAL128 interchange. Policies on absent or inapplicable paths have no effect. +- `unorderedArrays` compares exactly the named arrays as multisets: the same items, as often, in + any order, matched by perfect bipartite matching. Items keep their own policies, addressed by + their expected position; arrays inside them stay ordered unless named too. Core's scenarios + declare them as `comparison.unorderedArrays`, for arrays the server builds in no defined order + (`$graphLookup`'s `as` field). - JavaScript-with-scope uses the synthetic `/$scope` child for its scope document; source text always matches exactly. `compareResults` accepts lists of result documents. ORDERED checks row position. UNORDERED -compares only the top-level result multiset, preserving duplicates and all nested array order. +compares only the top-level result multiset, preserving duplicates and nested array order except +where `unorderedArrays` names an array. Policy paths are relative to each row, independent of row position; reported ordered mismatches include their row index. Unordered mismatch pointers identify the expected row at which matching fails. @@ -73,7 +79,7 @@ MongoDB instance or the legacy helper's database/codec dependency. | INT32 1 vs DOUBLE 1.0 or INT64 1, relaxed JSON | strict accepts | TYPE difference | Preserve BSON type; any intentional compatibility needs explicit future policy. | | Reversed compound sort keys | strict accepts | KEY_ORDER difference | Keep order; changing it changes sort priority. | | Unexpected result field | lenient accepts | EXTRA_FIELD difference | Reject; expected output must describe the complete intended result. | -| Reordered nested array | lenient accepts | VALUE difference | Reject; top-level unordered result policy cannot relax nested arrays. | +| Reordered nested array | lenient accepts | VALUE difference | Reject, unless the scenario names the array in `unorderedArrays` with evidence that the server does not order it; top-level unordered result policy cannot relax nested arrays. | | Reordered pipeline stages | lenient accepts | difference | Reject; stage order is semantic. | | Reordered result rows | strict rejects; lenient accepts | ORDERED rejects; UNORDERED accepts | Choose result ordering from the scenario's sort/expectation evidence. | | Decimal scale; double signed zero | strict rejects decimal scale; accepts double signed zero | difference | Preserve by default; reviewed zero tolerance may permit finite equality. | diff --git a/design/operator-audits-design.md b/design/operator-audits-design.md index 84ce05a5065..5704fe35086 100644 --- a/design/operator-audits-design.md +++ b/design/operator-audits-design.md @@ -42,8 +42,8 @@ production baseline yet, so nothing runs it on a schedule. See [Capability cover the audits module, and never needs it. Core's tests read only committed files. The audits module joins the build only with `-Daudits`. - **Strict comparison by default.** BSON types, numeric representation, key order and array order - all count. Any leniency is declared per case with its reason: a form rule, an ignored field, or - an unordered result. + all count. Any leniency is declared per case with its reason: a form rule, an ignored field, an + unordered result, or an unordered array. - **Never loosen a case to make it pass.** When a documented example fails, it is either a Morphia bug to fix or an exclusion recorded with evidence (the page is wrong, or the server cannot run it). The generator never emits a weaker case. @@ -112,7 +112,7 @@ A case is one documented example, described entirely by a `scenario.json` (schem | `collections`, `indexes`, `dataset` | The seed data, in extended JSON with exact BSON types. | | `action` | The documented command: an aggregate pipeline, a find, or an update, with its collection. | | `expected` | The documented results, either exact BSON or `printed`: the constraints mongosh's printed output proves (see below). | -| `comparison` | Result order, declared form rules, ignored fields and tolerance. | +| `comparison` | Result order, declared form rules, ignored fields, unordered arrays and tolerance. | | `requirements` | The minimum server version and topology. | | `skipped` | Checks that do not run, each with its reason. | @@ -131,16 +131,21 @@ API: `aggregate`, `find` or `update`. It checks three things separately, against 3. **Published expectation.** Both results equal the documented results, or satisfy what the printed results prove. -Two kinds of leniency exist, and each is a declared, named rule rather than a loose comparison: +Three kinds of leniency exist, and each is declared per case rather than a loose comparison: - **Form rules** (`FormRules`) map spellings the server treats identically to one canonical spelling, such as `{$eq: x}` and `x`, or the array and document forms of `$cond`. A rule applies to both sides and needs a reason recorded in the form review. - **Printed results** (`PrintedResults`) cover output the page shows the way mongosh prints it. A printed `4` may be an Int32 or a Double, so it is a constraint, not a value. - -Both are Java ports of audits-module code (`FormEquivalence` and `PublishedComparison`). Golden -vectors under `generated/vectors/` hold the two implementations to the same verdicts. +- **Unordered arrays** (`comparison.unorderedArrays`) name result arrays, by pointer within each + result, that the server builds in no defined order, such as the array `$graphLookup` writes. + They must hold the same items, as often, in any order; every other array stays ordered. Each + is declared in the form review with its evidence. + +These are Java ports of audits-module code (`FormEquivalence`, `PublishedComparison` and +`BsonComparison`, whose strict checks `StrictBson` ports). Golden vectors under +`generated/vectors/` hold the two implementations to the same verdicts. ### Where cases live diff --git a/design/operator-audits-progress.md b/design/operator-audits-progress.md index f55c8f5a30c..841b9efc0f5 100644 --- a/design/operator-audits-progress.md +++ b/design/operator-audits-progress.md @@ -18,7 +18,7 @@ how the audits work updates it too; this file records what each PR delivered. Every step of the plan (0–7) has been started. What stands: -- **On the runner:** 349 legacy cases (348 converted, 1 migrated), plus 1 generated case. +- **On the runner:** 351 legacy cases (350 converted, 1 migrated), plus 1 generated case. Core gate: 662 tests under each mapper; audits: 452. - **Generation:** inventory of mongodb/docs `e4b0c153` (197 pages read; 300 examples owned, 32 unowned, 11 unnamed), reviewed DSL bindings checked against core's API, and the @@ -47,10 +47,9 @@ Step 5, generation and cutover: `$deserializeEJSON`, `$toObject`, `$reduce` `valueAs`). - **Find and update generation.** Only aggregation pipelines are generated. - **Reviewed names** for the 11 examples with generic titles. -- **The remaining legacy fixtures:** 207 directories. +- **The remaining legacy fixtures:** 205 directories. - 98 are locked; 96 are unresolved in `form-review.json`. - - 25 are legacy-only in `cutover.json`, the `$graphLookup` pair among them (#4562, an - unordered-array comparison). + - 23 are legacy-only in `cutover.json`. - 81 never-locked fixtures have no pinned reference. - **Deferred cutover features:** documented projections (`findOptions`), indexes, alternative commands. @@ -2556,3 +2555,22 @@ no product-documentation changes. Legacy operator AsciiDoc tables are intentiona pass under both mappers; removing the rule from the `$topN` scenario makes it fail with "serialization differs", so the check is live. - Totals: ledger 349 cases; 25 legacy-only; form report 6 overrides; 207 legacy directories. + +## Unordered result arrays (2026-11-23) + +- Branch audits-unordered-arrays, for #4562 (from #4554). A scenario's + `comparison.unorderedArrays` names result arrays, by RFC 6901 pointer within each result, that + match as multisets. `BsonComparisonPolicy.unorderedArrays` and `PublishedComparison` do it in + Kotlin, by bipartite matching shared through `Matching`; `StrictBson` and `PrintedResults` port + it, and 14 new golden vectors (reordered match, multiplicity and item-type mismatches, overlapping + printed constraints, per-row and escaped paths, ordered inner arrays) hold the two to the same + verdicts. +- A form-review declaration lists them as `unorderedArrays: [{path, reason}]`; capture rejects a + path that is not a result pointer, a blank reason or a repeat, and carries them to the override + and the scenario. Only a scenario that declares one carries the key. +- Both `$graphLookup` cases convert: `withinASingleCollection` (`/reportingHierarchy`) and + `withAQueryFilter` (`/connections who play golf`), citing the page's "Documents returned in the + as field are not guaranteed to be in any order". Their bodies look up `employees` and `people`, + recorded as reviewed body edits. +- Totals: ledger 351 cases; 23 legacy-only; form report 4 overrides; 205 legacy directories. Core + operator tests: 678 under each mapper; audits: 452. diff --git a/design/operator-audits-reference.md b/design/operator-audits-reference.md index 2642c980be2..fafdbb8727b 100644 --- a/design/operator-audits-reference.md +++ b/design/operator-audits-reference.md @@ -437,7 +437,10 @@ source dispositions and complete pinned external resources follow in subsequent `BsonValue` trees and lists of result documents. Defaults preserve BSON types, numeric representations, document keys, arrays, pipelines and duplicate results. Explicit RFC 6901 paths can relax document key order or finite numeric values of the same BSON type. -`ResultOrder.UNORDERED` relaxes only the top-level result multiset; nested arrays remain ordered. +`ResultOrder.UNORDERED` relaxes only the top-level result multiset; nested arrays remain ordered +unless the policy's `unorderedArrays` names them, by pointer within each row. Those match as +multisets, by bipartite matching, and so do the printed items of a named array in +`PublishedComparison`. Invalid/cyclic inputs or resource limits return `INVALID`, never a passing comparison. The [comparison contract](operator-audits-bson-comparison.md) documents the policies,