diff --git a/audits/catalog/documented-examples.json b/audits/catalog/documented-examples.json index e8bcecbe692..b439e96a9aa 100644 --- a/audits/catalog/documented-examples.json +++ b/audits/catalog/documented-examples.json @@ -8165,16 +8165,8 @@ "role" : "ACTION", "sha256" : "3e1b19c5bba77b08ea6a2736e8d91b31e58aa4ac5fea7a9fd981133791c93752", "text" : "db.movies.aggregate( [\n { $match: { metacritic: 100, rated: { $ne: null },\n year: { $lte: 1972 } } },\n { $group: { _id: { year: \"$year\", rated: \"$rated\" },\n count: { $sum: 1 } } },\n { $merge : { into: \"movieRatingSummary\", on: \"_id\",\n whenMatched: \"replace\", whenNotMatched: \"insert\" } }\n] )\n" - } ], - "detail" : null, - "name" : "Summarize Ratings into Another Collection", - "owner" : null, - "status" : "UNOWNED", - "stem" : "summarizeRatingsIntoAnotherCollection", - "title" : "On-Demand Materialized View: Initial Creation" - }, { - "blocks" : [ { - "role" : "ACTION", + }, { + "role" : "READ", "sha256" : "47ab092aeefcc156ab9ace5329c7c4961d1737909dcd41025c9e781720f3a91f", "text" : "db.movieRatingSummary.find().sort(\n { _id: 1 } )\n" }, { @@ -8182,25 +8174,19 @@ "sha256" : "f3b220cfc7ab8849badbfc2caf62650639cab6bb5c7b0d9e8772392f49e7912d", "text" : "[\n { _id: { year: 1939, rated: 'PASSED' }, count: 1 },\n { _id: { year: 1962, rated: 'PG' }, count: 1 },\n { _id: { year: 1963, rated: 'PG' }, count: 1 },\n { _id: { year: 1970, rated: 'R' }, count: 1 },\n { _id: { year: 1972, rated: 'R' }, count: 1 }\n]\n" } ], - "detail" : "AFTER_EARLIER_WRITE", + "detail" : null, + "name" : "Summarize Ratings into Another Collection", "owner" : null, - "status" : "UNSUPPORTED", - "stem" : "onDemandMaterializedViewInitialCreation", + "status" : "UNOWNED", + "stem" : "summarizeRatingsIntoAnotherCollection", "title" : "On-Demand Materialized View: Initial Creation" }, { "blocks" : [ { "role" : "ACTION", "sha256" : "facc7ecfbdaa80252905a3ae66c0813ca3e1f85e525c41bb756e96f122e1c449", "text" : "db.movies.aggregate( [\n { $match: { metacritic: 100, rated: { $ne: null },\n year: { $gte: 1963 } } },\n { $group: { _id: { year: \"$year\", rated: \"$rated\" },\n count: { $sum: 1 } } },\n { $merge : { into: \"movieRatingSummary\", on: \"_id\",\n whenMatched: \"replace\", whenNotMatched: \"insert\" } }\n] )\n" - } ], - "detail" : null, - "owner" : null, - "status" : "UNOWNED", - "stem" : "onDemandMaterializedViewUpdateReplaceData", - "title" : "On-Demand Materialized View: Update/Replace Data" - }, { - "blocks" : [ { - "role" : "ACTION", + }, { + "role" : "READ", "sha256" : "47ab092aeefcc156ab9ace5329c7c4961d1737909dcd41025c9e781720f3a91f", "text" : "db.movieRatingSummary.find().sort(\n { _id: 1 } )\n" }, { @@ -8208,9 +8194,9 @@ "sha256" : "84a4c1f0d92c84c82af7d6d803790d539bc1e53613d8b6efd7be540115465cc4", "text" : "[\n { _id: { year: 1939, rated: 'PASSED' }, count: 1 },\n { _id: { year: 1962, rated: 'PG' }, count: 1 },\n { _id: { year: 1963, rated: 'PG' }, count: 1 },\n { _id: { year: 1970, rated: 'R' }, count: 1 },\n { _id: { year: 1972, rated: 'R' }, count: 1 },\n { _id: { year: 1982, rated: 'R' }, count: 1 },\n { _id: { year: 2014, rated: 'R' }, count: 1 }\n]\n" } ], - "detail" : "AFTER_EARLIER_WRITE", + "detail" : null, "owner" : null, - "status" : "UNSUPPORTED", + "status" : "UNOWNED", "stem" : "onDemandMaterializedViewUpdateReplaceData", "title" : "On-Demand Materialized View: Update/Replace Data" }, { @@ -8233,15 +8219,8 @@ "role" : "ACTION", "sha256" : "c1340aae31ddfda0474e5ad95aebac468c415f59959d9893a8cc23b67ccca715", "text" : "db.movies.aggregate( [\n { $match: { metacritic: 100, rated: { $ne: null },\n year: { $gte: 1970, $lte: 1972 } } },\n { $group: { _id: \"$year\", movieCount: { $sum: 1 } } },\n { $merge : { into: \"yearlyStats\", on: \"_id\",\n whenMatched: \"merge\", whenNotMatched: \"insert\" } }\n])\n" - } ], - "detail" : null, - "owner" : null, - "status" : "UNOWNED", - "stem" : "mergeResultsFromMultipleCollections", - "title" : "Merge Results from Multiple Collections" - }, { - "blocks" : [ { - "role" : "ACTION", + }, { + "role" : "READ", "sha256" : "2f5d3a96ac6ad96f53765aef767cf7f978955e62abd6b00542b8139488b86fef", "text" : "db.yearlyStats.find().sort( { _id: 1 } )\n" }, { @@ -8249,9 +8228,9 @@ "sha256" : "1b642279507416bfc099eb7aa4970fba5b00107e259140c60ca471d8a54581de", "text" : "[\n { _id: 1970, movieCount: 1 },\n { _id: 1972, movieCount: 1 }\n]\n" } ], - "detail" : "AFTER_EARLIER_WRITE", + "detail" : null, "owner" : null, - "status" : "UNSUPPORTED", + "status" : "UNOWNED", "stem" : "mergeResultsFromMultipleCollections", "title" : "Merge Results from Multiple Collections" }, { @@ -8285,15 +8264,8 @@ "role" : "ACTION", "sha256" : "633643224f2d0b3e3d1d92dabf39742903db933372f4703f40be929871a69505", "text" : "db.comments.aggregate([\n { $match: { date: { $gte: new Date(\"1970-01-15\"),\n $lt: new Date(\"1970-01-16\") } } },\n { $group: { _id: { $dateToString: { format: \"%Y-%m\",\n date: \"$date\" } }, count: { $sum: 1 } } },\n { $merge: {\n into: \"monthlyCommentTotals\",\n on: \"_id\",\n whenMatched: [\n { $addFields: {\n count: { $add: [ \"$count\", \"$$new.count\" ] }\n } }\n ],\n whenNotMatched: \"insert\"\n } }\n])\n" - } ], - "detail" : null, - "owner" : null, - "status" : "UNOWNED", - "stem" : "useThePipelineToCustomizeTheMerge", - "title" : "Use the Pipeline to Customize the Merge" - }, { - "blocks" : [ { - "role" : "ACTION", + }, { + "role" : "READ", "sha256" : "8f9a466027791a0ef9e8d7339956ffdaac76019ff21bda623f45e1f308ef1106", "text" : "db.monthlyCommentTotals.find()\n" }, { @@ -8301,9 +8273,9 @@ "sha256" : "8e8576f2440a05fd0744443a297605e27be3e8f99d0dbf6f529f252e688d2338", "text" : "[ { _id: '1970-01', count: 71 } ]\n" } ], - "detail" : "AFTER_EARLIER_WRITE", + "detail" : null, "owner" : null, - "status" : "UNSUPPORTED", + "status" : "UNOWNED", "stem" : "useThePipelineToCustomizeTheMerge", "title" : "Use the Pipeline to Customize the Merge" }, { @@ -8445,15 +8417,8 @@ "role" : "ACTION", "sha256" : "ea3f05e954589b040a8b1f4ca2c77b4ddeb3d72a8ce50c374ec895deb2eb6f06", "text" : "db.movies.aggregate( [\n { $match : { runtime : { $gt : 1000 } } },\n { $group : { _id : \"$year\", movies: { $push: \"$title\" } } },\n { $out : \"movies_by_year\" }\n] )\n" - } ], - "detail" : null, - "owner" : null, - "status" : "UNOWNED", - "stem" : "outputToSameDatabase", - "title" : "Output to Same Database" - }, { - "blocks" : [ { - "role" : "ACTION", + }, { + "role" : "READ", "sha256" : "7a644059d2d56e403ffd6832aa28cbee59ad576f68cf6d6b0b968b9984f7082f", "text" : "db.movies_by_year.find().sort( { _id: 1 } )\n" }, { @@ -8461,9 +8426,9 @@ "sha256" : "cd9a71a57747a83d1c4272d2b67caf8e4dd9bd7739d314489dcfa4ac9ce4b216", "text" : "[\n { _id: 1978, movies: [ 'Centennial' ] },\n { _id: 1994, movies: [ 'Baseball' ] }\n]\n" } ], - "detail" : "AFTER_EARLIER_WRITE", + "detail" : null, "owner" : null, - "status" : "UNSUPPORTED", + "status" : "UNOWNED", "stem" : "outputToSameDatabase", "title" : "Output to Same Database" }, { @@ -8471,15 +8436,8 @@ "role" : "ACTION", "sha256" : "7b40fedff6bfd426a57c2d68ce525df638a354d5549b724976765ee8e0e3c7dd", "text" : "db.movies.aggregate( [\n { $match : { runtime : { $gt : 1000 } } },\n { $group : { _id : \"$year\", movies: { $push: \"$title\" } } },\n { $out : { db: \"reporting\", coll: \"movies_by_year\" } }\n] )\n" - } ], - "detail" : null, - "owner" : null, - "status" : "UNOWNED", - "stem" : "outputToADifferentDatabase", - "title" : "Output to a Different Database" - }, { - "blocks" : [ { - "role" : "ACTION", + }, { + "role" : "READ", "sha256" : "7a644059d2d56e403ffd6832aa28cbee59ad576f68cf6d6b0b968b9984f7082f", "text" : "db.movies_by_year.find().sort( { _id: 1 } )\n" }, { @@ -8487,9 +8445,9 @@ "sha256" : "cd9a71a57747a83d1c4272d2b67caf8e4dd9bd7739d314489dcfa4ac9ce4b216", "text" : "[\n { _id: 1978, movies: [ 'Centennial' ] },\n { _id: 1994, movies: [ 'Baseball' ] }\n]\n" } ], - "detail" : "AFTER_EARLIER_WRITE", + "detail" : null, "owner" : null, - "status" : "UNSUPPORTED", + "status" : "UNOWNED", "stem" : "outputToADifferentDatabase", "title" : "Output to a Different Database" } ], @@ -12329,19 +12287,8 @@ "role" : "ACTION", "sha256" : "218f2759e7c5ef1b81bfab1836e388a9dfa592278a1db738f18cc4ba431de5fa", "text" : "db.customers.updateOne(\n { _id: 1 },\n [\n { $set: { lastModified: \"$$NOW\", cancellation: {date: \"$$CLUSTER_TIME\", reason: \"user request\"}, status: \"D\" } }\n ]\n)" - } ], - "detail" : null, - "owner" : null, - "status" : "UNOWNED", - "stem" : "aggregationAlternativeToCurrentDate", - "title" : "Aggregation Alternative to $currentDate" - }, { - "blocks" : [ { - "role" : "DATA", - "sha256" : "52e44d3866738eb41ce921b867a3cc2506640124d3375616926c79dbf9c0a4d0", - "text" : "db.customers.insertOne(\n { _id: 1, status: \"a\", lastModified: ISODate(\"2013-10-02T01:11:18.965Z\") }\n)" }, { - "role" : "ACTION", + "role" : "READ", "sha256" : "115318d98733c31505a7ee115610a8e108749542a85f3972e2e2c52f6fc59ddb", "text" : "db.customers.find().pretty()" }, { @@ -12349,9 +12296,9 @@ "sha256" : "4506118e7b1dd3c633a7a37cf939b43cc45a606572a8523ee33c4d5e814e7212", "text" : "{\n \"_id\" : 1,\n \"status\" : \"D\",\n \"lastModified\" : ISODate(\"2020-01-22T21:02:18.994Z\"),\n \"cancellation\" : {\n \"date\" : Timestamp(1579726934, 2),\n \"reason\" : \"user request\"\n }\n}" } ], - "detail" : "AFTER_EARLIER_WRITE", + "detail" : null, "owner" : null, - "status" : "UNSUPPORTED", + "status" : "UNOWNED", "stem" : "aggregationAlternativeToCurrentDate", "title" : "Aggregation Alternative to $currentDate" } ], @@ -12661,25 +12608,6 @@ "status" : "OWNED", "stem" : null, "title" : "Update with Multiple Array Matches" - }, { - "blocks" : [ { - "role" : "DATA", - "sha256" : "093b214c82198a5913eed1a1aceeb8c9ca5eeed76b6c8d55230c7f7eb55f0b47", - "text" : "db.students_deans_list.insertMany( [\n {\n _id: 8,\n activity_ids: [ 1, 2 ],\n grades: [ 90, 95 ],\n deans_list: [ 2021, 2020 ]\n }\n] )" - }, { - "role" : "ACTION", - "sha256" : "a49e711e1e1887ef0aece764b95e4697555c7c7b8ef611cb166ddf80c03ce4de", - "text" : "db.students_deans_list.find( { _id: 8 } )" - }, { - "role" : "EXPECTED", - "sha256" : "c80922427104033dfb7c8a0d2280f14971504d881a73f60efee816da9a947bff", - "text" : "{\n _id: 8,\n activity_ids: [ 1, 2 ],\n grades: [ 90, 95 ],\n deans_list: [ 2021, 2022 ]\n}" - } ], - "detail" : "AFTER_EARLIER_WRITE", - "owner" : null, - "status" : "UNSUPPORTED", - "stem" : "updateWithMultipleArrayMatches", - "title" : "Update with Multiple Array Matches" } ], "includes" : [ ], "operator" : "positional", @@ -13334,7 +13262,7 @@ "examples.owned" : 307, "examples.unnamed" : 0, "examples.unowned" : 281, - "examples.unsupported" : 112, + "examples.unsupported" : 104, "pages" : 290, "pages.skipped" : 7, "reviews.stale" : 0 diff --git a/audits/catalog/generation-review.json b/audits/catalog/generation-review.json index dbc9e6d49f5..01a70e5f2b3 100644 --- a/audits/catalog/generation-review.json +++ b/audits/catalog/generation-review.json @@ -25,7 +25,7 @@ }, { "name": "query/updates/positional-all/updateArraysSpecifiedUsingANegationQueryOperator", - "reason": "The page prints the whole collection after the update; the runner's update results are the documents its filter still matches, as the legacy tests read them. Serialization and behavior pass." + "reason": "The page prints the whole collection after the update but shows no read, so the runner's update results are the documents its filter still matches, as the legacy tests read them. Serialization and behavior pass. Lift once the page shows its find, which the case then runs." } ], "sampleDatasets": { diff --git a/audits/src/main/kotlin/dev/morphia/audits/generate/DocumentedExamples.kt b/audits/src/main/kotlin/dev/morphia/audits/generate/DocumentedExamples.kt index f4e88fd2c48..5158f3e4cad 100644 --- a/audits/src/main/kotlin/dev/morphia/audits/generate/DocumentedExamples.kt +++ b/audits/src/main/kotlin/dev/morphia/audits/generate/DocumentedExamples.kt @@ -247,6 +247,8 @@ object DocumentedExamples { // Each declaration travels with the next block that runs, in page order: the insert or // action that reads it. val pending = mutableListOf() + // A second action is the find the page runs after the first, a write, to show its effect. + val action = scenario.blocks.firstOrNull { it.role == ProgramRole.ACTION } val blocks = scenario.blocks .filter { it.role != null } @@ -257,7 +259,8 @@ object DocumentedExamples { } val role = when (code.role) { - ProgramRole.ACTION -> BlockRole.ACTION + ProgramRole.ACTION -> + if (code === action) BlockRole.ACTION else BlockRole.READ ProgramRole.EXPECTED -> BlockRole.EXPECTED else -> if (code.format == null && ".createIndex" in code.source) @@ -271,14 +274,14 @@ object DocumentedExamples { else code.source SourceBlock(role, text, CaseManifests.sha256(text.toByteArray())) } - // Until an update's case runs the page's own read, generation keeps the legacy reading of - // what the page prints after it: an acknowledgement, or the documents the filter matches. + // Where the page shows no read after an update, generation keeps the legacy reading of + // what it prints: an acknowledgement, or the documents the filter matches. val printed = scenario.skipped .firstOrNull { it.reason == "UPDATE_RESULT" } ?.code ?.source - ?.takeIf { scenario.blocks.any { it.role == ProgramRole.ACTION } } + ?.takeIf { action != null && blocks.none { it.role == BlockRole.READ } } ?.let { SourceBlock(BlockRole.EXPECTED, it, CaseManifests.sha256(it.toByteArray())) } 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 6742b6cd138..8394c5f7b88 100644 --- a/audits/src/main/kotlin/dev/morphia/audits/repairs/FixtureMigration.kt +++ b/audits/src/main/kotlin/dev/morphia/audits/repairs/FixtureMigration.kt @@ -336,6 +336,17 @@ object FixtureMigration { action["multi"] = BsonBoolean(documented.many) } } + // The find the page runs after a write: both sides run it, and its result is the one the + // page printed. + documented.read?.let { read -> + action["read"] = + BsonDocument("collection", BsonString(read.collection)) + .append("filter", read.filter) + .also { spec -> + read.projection?.let { spec["projection"] = it } + read.sort?.let { spec["sort"] = it } + } + } // The page's other spellings of the action, each in the same shape as the action. if (documented.alternatives.isNotEmpty()) { action["alternatives"] = 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 64cd91df947..09a5ba2bd52 100644 --- a/audits/src/main/kotlin/dev/morphia/audits/repairs/FormMigration.kt +++ b/audits/src/main/kotlin/dev/morphia/audits/repairs/FormMigration.kt @@ -10,6 +10,7 @@ import dev.morphia.audits.shell.LegacyDocuments import dev.morphia.audits.shell.ProgramBlock import dev.morphia.audits.shell.ProgramFormat import dev.morphia.audits.shell.ProgramRole +import dev.morphia.audits.shell.QueryModifierKind import dev.morphia.audits.shell.ShellDialect import dev.morphia.audits.shell.ShellLiteralState import dev.morphia.audits.shell.ShellProgramRequest @@ -133,6 +134,8 @@ enum class BlockRole { DATA, EXPECTED, INDEX, + /** The find a page runs after a write to show its effect; its printed result is [EXPECTED]. */ + READ, } /** Source text as extracted from the page, so the claim can be rechecked without the page. */ @@ -168,6 +171,16 @@ data class DocumentedScenario( val indexes: List = emptyList(), /** The page's other spellings of the action, when it declares alternative commands. */ val alternatives: List> = emptyList(), + /** The find the page runs after a write, whose result is the printed one. */ + val read: DocumentedRead? = null, +) + +/** A find a page runs after a write: its collection, filter, projection and sort. */ +data class DocumentedRead( + val collection: String, + val filter: BsonDocument, + val projection: BsonDocument?, + val sort: BsonDocument?, ) data class FormOverride( @@ -324,11 +337,17 @@ object FormMigration { val action = if (alternatives) documented.alternatives.first() else documented.alternatives.single() require(shape == null || action.shape == shape) { "$label: action is ${action.shape}" } + val read = + when (val parsed = read(blocks)) { + is Examined.Gap -> throw IllegalArgumentException("$label: ${parsed.detail}") + else -> parsed as DocumentedRead? + } + require(read == null || action.shape != ActionShape.FIND) { "$label: a read after a find" } val expected = blocks.filter { it.role == BlockRole.EXPECTED } val printed = if (expected.isEmpty()) null else - when (val read = published(documented.collection, expected)) { + when (val read = published(read?.collection ?: documented.collection, expected)) { is Examined.Gap -> throw IllegalArgumentException("$label: ${read.detail}") else -> @Suppress("UNCHECKED_CAST") (read as List) } @@ -343,7 +362,81 @@ object FormMigration { listed.takeIf { it.isNotEmpty() && it.all { rows -> rows != null } }?.flatMap { it!! }, indexes = documented.indexes, alternatives = - if (alternatives) documented.alternatives.drop(1).map { it.values } else emptyList(), + if (alternatives) documented.alternatives.drop(1).map { it.values } + else emptyList(), + read = read, + ) + } + + /** + * The find a page runs after its write, when it shows one, or a gap. Only a filter, a + * projection and a sort are read; any other modifier would change what the page printed. + */ + private fun read(blocks: List): Any? { + val reads = blocks.filter { it.role == BlockRole.READ } + if (reads.isEmpty()) return null + val block = + reads.singleOrNull() + ?: return Examined.Gap(FormGap.SOURCE_UNSUPPORTED, "${reads.size} reads") + // The read runs after the example's other code, so it sees the bindings declared there. + val before = blocks.takeWhile { it !== block } + val program = + ShellPrograms.normalize( + ShellProgramRequest( + dialect = ShellDialect.MONGOSH, + blocks = + before + .filter { + it.role == BlockRole.INDEX || + it.role == BlockRole.ACTION || + it.role == BlockRole.DATA && + (".insertOne(" in it.text || ".insertMany(" in it.text) + } + .mapIndexed { index, it -> + ProgramBlock( + "before$index", + it.text, + if (it.role == BlockRole.ACTION) ProgramRole.ACTION + else ProgramRole.SETUP, + ) + } + ProgramBlock("read", block.text, ProgramRole.ACTION), + ) + ) + if (program.state != ShellLiteralState.NORMALIZED) { + return Examined.Gap( + FormGap.SOURCE_UNSUPPORTED, + "read: " + program.problems.joinToString { it.code }, + ) + } + val command = + program.commands.filter { it.id.block == "read" }.singleOrNull() + ?: return Examined.Gap(FormGap.SOURCE_UNSUPPORTED, "a read of several commands") + val find = + command.operation as? FindOperation + ?: return Examined.Gap( + FormGap.SOURCE_UNSUPPORTED, + "a ${command.operation.kind} read", + ) + if (command.namespace.database != null) { + return Examined.Gap(FormGap.SOURCE_UNSUPPORTED, "a read outside the current database") + } + find.modifiers + .firstOrNull { + it.kind != QueryModifierKind.SORT && it.kind != QueryModifierKind.PROJECT + } + ?.let { + return Examined.Gap(FormGap.SOURCE_UNSUPPORTED, "a read with ${it.kind}") + } + val projections = find.modifiers.filter { it.kind == QueryModifierKind.PROJECT } + val sorts = find.modifiers.filter { it.kind == QueryModifierKind.SORT } + if (projections.size + listOfNotNull(find.projection).size > 1 || sorts.size > 1) { + return Examined.Gap(FormGap.SOURCE_UNSUPPORTED, "a read with repeated modifiers") + } + return DocumentedRead( + command.namespace.collection, + find.filter.value().asDocument(), + (find.projection ?: projections.singleOrNull()?.value)?.value()?.asDocument(), + sorts.singleOrNull()?.value?.value()?.asDocument(), ) } diff --git a/audits/src/main/kotlin/dev/morphia/audits/scenarios/ScenarioExtraction.kt b/audits/src/main/kotlin/dev/morphia/audits/scenarios/ScenarioExtraction.kt index 97910f175f0..e59eb60838c 100644 --- a/audits/src/main/kotlin/dev/morphia/audits/scenarios/ScenarioExtraction.kt +++ b/audits/src/main/kotlin/dev/morphia/audits/scenarios/ScenarioExtraction.kt @@ -225,12 +225,27 @@ object ScenarioExtraction { } } + // Inserts and index builds: setup that changes what a later read sees. + private val setupCall = Regex("""\.(?:insert\w*|createIndex\w*)\s*\(""") + // Commands that change the data a later read sees. private val write = Regex( """\.(?:update|replace|delete|bulkWrite|findOneAnd|findAndModify)\w*\s*\(|[{,]\s*["']?\$(?:merge|out)["']?\s*:""" ) + /** + * Where a scenario sits for the writes before it: its section path, and the tab or + * selected-content branches it is in. A write reaches its own branch and the branches nested in + * it, never a sibling branch, which is a separate example. + */ + private data class Place(val section: List, val branches: List>) { + fun reaches(other: Place) = + section == other.section && + other.branches.size >= branches.size && + other.branches.take(branches.size) == branches + } + private class Run( val bundle: VerifiedSourceBundle, val document: DocumentReport, @@ -937,7 +952,7 @@ object ScenarioExtraction { .filter { it !in foundSections } .forEach { problem("MISSING_SECTION", rule, "Declared section $it is absent") } inheritSetup(rule, start, setupSources) - afterWrites(start) + afterWrites(rule, start) val emitted = scenarios.drop(start) val reference = emitted.count { it.variant == ScenarioVariant.REFERENCE } if (reference < rule.minimumReferenceGroups) @@ -1041,11 +1056,12 @@ object ScenarioExtraction { } /** - * A read that follows a write in the same section sees the write's effect, which its own - * program doesn't run, whether the write sits in its section's code or in another input/ - * output group. Such a read keeps its source and reports `AFTER_EARLIER_WRITE`. + * An action that follows a write in the same section sees the write's effect, which its own + * program doesn't run, whether the write sits in its section's code or in another + * input/output group. Such an action keeps its source and reports `AFTER_EARLIER_WRITE`, + * unless it is the find the page runs to show the write's effect: see [withRead]. */ - fun afterWrites(start: Int) { + fun afterWrites(rule: ScenarioPageRule, start: Int) { fun action(scenario: ExtractedScenario) = scenario.blocks.firstOrNull { it.role == ProgramRole.ACTION } fun writes(scenario: ExtractedScenario) = @@ -1062,24 +1078,40 @@ object ScenarioExtraction { a.zip(b).firstOrNull { (x, y) -> x != y }?.let { (x, y) -> x.compareTo(y) } ?: a.size.compareTo(b.size) } - val written = mutableSetOf>() + val written = mutableListOf() + // The scenario with an action just before this one in page order, and the reads + // folded into the write before them. + var previous: Int? = null + val folded = mutableListOf() (start until scenarios.size) .filter { scenarios[it].variant == ScenarioVariant.REFERENCE } .sortedWith(compareBy(order) { position(scenarios[it]) }) .forEach { index -> val scenario = scenarios[index] - val section = scenario.sections.map { it.anchor ?: it.title } + val section = section(scenario) + val paired = previous?.let { withRead(rule, scenarios[it], scenario) } + if (paired != null) { + scenarios[previous!!] = paired + folded += index + previous = null + return@forEach + } + if (action(scenario) != null) previous = index // A write the page shows but no scenario runs, such as a bulkWrite in a try - // block, still changes what the read after it sees. + // block, still changes what the read after it sees; a syntax template runs + // nothing. val skippedWrite = scenario.skipped.any { - write.containsMatchIn(it.code.source) && + it.reason != "SYNTAX_TEMPLATE" && + write.containsMatchIn(it.code.source) && order.compare(it.code.locator, position(scenario)) < 0 } + // A write after a write sees its effect too. A scenario that already can't + // run keeps its own problem. if ( - (section in written || skippedWrite) && - !writes(scenario) && - action(scenario) != null + (written.any { it.reaches(section) } || skippedWrite) && + action(scenario) != null && + scenario.normalizationProblem == null ) scenarios[index] = scenario.copy( @@ -1088,6 +1120,80 @@ object ScenarioExtraction { ) if (writes(scenario)) written += section } + folded.sortedDescending().forEach { scenarios.removeAt(it) } + } + + /** The [Place] of [scenario]. */ + fun section(scenario: ExtractedScenario) = + Place( + scenario.sections.map { it.anchor ?: it.title }, + scenario.containers + .filter { it.name in setOf("tab", "selected-content") } + .map { listOf(it.name, it.argument, it.options, it.attributes["selections"]) }, + ) + + /** + * [write] with [read] as the find the page runs after it, when [read] directly follows it + * in the same section: [write] runs one write and prints nothing of its own, and [read] is + * one find with its printed result. The pair is one scenario, whose published result is the + * find's; null when they aren't such a pair or don't normalize together. + */ + fun withRead( + rule: ScenarioPageRule, + write: ExtractedScenario, + read: ExtractedScenario, + ): ExtractedScenario? { + fun actions(scenario: ExtractedScenario) = + scenario.program + ?.takeIf { it.state == ShellLiteralState.NORMALIZED } + ?.commands + ?.filter { it.role == ProgramRole.ACTION } + if (!section(write).reaches(section(read))) return null + // Setup or a skipped write between them changes what the find sees, and the pair + // wouldn't run it. + val after = write.blocks.firstOrNull { it.role == ProgramRole.ACTION }?.locator + val before = read.blocks.firstOrNull { it.role == ProgramRole.ACTION }?.locator + if (after == null || before == null) return null + fun between(locator: List) = + locatorOrder.compare(locator, after) > 0 && + locatorOrder.compare(locator, before) < 0 + if ( + read.blocks.any { it.role == ProgramRole.SETUP && between(it.locator) } || + (write.skipped + read.skipped).any { + it.reason != "SYNTAX_TEMPLATE" && + between(it.code.locator) && + (ScenarioExtraction.write.containsMatchIn(it.code.source) || + setupCall.containsMatchIn(it.code.source)) + } + ) + return null + val writes = actions(write)?.singleOrNull() ?: return null + val finds = actions(read)?.singleOrNull() ?: return null + if (!writes(writes.operation) || finds.operation !is FindOperation) return null + if (write.blocks.any { it.role == ProgramRole.EXPECTED }) return null + val shown = + read.blocks.filter { it.role in setOf(ProgramRole.ACTION, ProgramRole.EXPECTED) } + if (shown.map { it.role } != listOf(ProgramRole.ACTION, ProgramRole.EXPECTED)) + return null + // The read's own setup, such as the earlier inserts into the collection it reads, + // runs before the write; the write's scenario may lack it. + fun key(code: ScenarioCode) = code.locator to code.sha256 + val known = write.blocks.map(::key).toSet() + val extra = read.blocks.filter { it.role == ProgramRole.SETUP && key(it) !in known } + // Setup in page order, so each declaration still comes before what reads it. + val setup = + (write.blocks.filter { it.role == ProgramRole.SETUP } + extra).sortedWith( + compareBy(locatorOrder) { it.locator } + ) + val blocks = setup + write.blocks.filter { it.role != ProgramRole.SETUP } + shown + val program = program(rule, blocks) + if (program.state != ShellLiteralState.NORMALIZED) return null + chargeSetup(extra) + programBytes += AuditJson.requireMaximumSize(program, limits.maximumReportBytes) + require(programBytes <= limits.maximumReportBytes) { + "Embedded programs exceed scenario report budget" + } + return write.copy(blocks = blocks, program = program) } fun program(rule: ScenarioPageRule, blocks: List) = @@ -1096,6 +1202,14 @@ object ScenarioExtraction { dialect = rule.dialect, blocks = blocks.mapIndexed { i, b -> + // With a write's read, a result belongs to the action just before it. + val owner = + (i - 1 downTo 0) + .firstOrNull { blocks[it].role == ProgramRole.ACTION } + ?.takeIf { + b.role == ProgramRole.EXPECTED && + blocks.count { c -> c.role == ProgramRole.ACTION } > 1 + } ProgramBlock( "block-$i", b.source, @@ -1106,6 +1220,7 @@ object ScenarioExtraction { ProgramFormat.SHELL_RESULTS else ProgramFormat.SHELL, namespace = b.namespace, + expectedFor = owner?.let { CommandSelector("block-$it", 0) }, ) }, resultOrder = rule.resultOrder, @@ -1162,7 +1277,7 @@ object ScenarioExtraction { } } val namespace = - program.commands.lastOrNull { it.role == ProgramRole.ACTION }?.namespace + program.commands.firstOrNull { it.role == ProgramRole.ACTION }?.namespace val inherited = namespace?.let { inserted[it] } if (namespace != null && namespace !in inserts && inherited != null) { // The copied setup counts against the budgets like any other. diff --git a/audits/src/main/kotlin/dev/morphia/audits/scenarios/SectionPrograms.kt b/audits/src/main/kotlin/dev/morphia/audits/scenarios/SectionPrograms.kt index f385c4b8a87..6ad11ad3d8e 100644 --- a/audits/src/main/kotlin/dev/morphia/audits/scenarios/SectionPrograms.kt +++ b/audits/src/main/kotlin/dev/morphia/audits/scenarios/SectionPrograms.kt @@ -30,14 +30,8 @@ internal object SectionPrograms { private sealed interface Kind { data class Setup(val inserts: Boolean) : Kind - /** - * [update] is an update command; [writes] also covers a pipeline that writes its output. - */ - data class Action( - val update: Boolean, - val namespace: LogicalNamespace, - val writes: Boolean = update, - ) : Kind + /** [update] is an update command. */ + data class Action(val update: Boolean, val namespace: LogicalNamespace) : Kind data object Document : Kind @@ -130,20 +124,15 @@ internal object SectionPrograms { own.getOrNull(action + 1) ?.takeIf { result(action + 1) && !updated(action + 1) } ?.copy(role = ProgramRole.EXPECTED) - // A read after an update in the same section sees the update's effect, which this - // scenario doesn't run; the update's own read will cover it. - val afterWrite = actions.any { it < action && (kinds[it] as Kind.Action).writes } val lostSetup = (0 until action).any { kinds[it] == Kind.Skip("UNSUPPORTED_SETUP") } Assignment( shared + setup + own[action].copy(role = ProgramRole.ACTION) + listOfNotNull(result), - when { - lostSetup -> "UNSUPPORTED_SETUP" - afterWrite -> "AFTER_EARLIER_WRITE" - else -> null - }, + // A read after a write in the same section is settled page-wide, with the reads + // in other input/output groups: it is the write's read, or AFTER_EARLIER_WRITE. + if (lostSetup) "UNSUPPORTED_SETUP" else null, skipped + listOfNotNull( own.getOrNull(action + 1) @@ -167,7 +156,8 @@ internal object SectionPrograms { if (seeds.isEmpty()) return blocks to emptyList() val program = blocks.filter { it.format == null && it.role != ProgramRole.EXPECTED } val inspection = inspect(program, dialect) - val action = program.indexOfLast { it.role == ProgramRole.ACTION } + // A write's read can name another collection; seeds belong to the write's. + val action = program.indexOfFirst { it.role == ProgramRole.ACTION } val namespace = inspection.namespaces.lastOrNull { it.first == "block-$action" }?.second if ( inspection.state != ShellLiteralState.NORMALIZED || @@ -221,7 +211,6 @@ internal object SectionPrograms { Kind.Action( update, inspection.namespaces.last { it.first == id }.second, - update || output.containsMatchIn(block.source), ) } } @@ -252,10 +241,6 @@ internal object SectionPrograms { .mapValues { (_, indexes) -> setup.take(indexes.max() + 1) } } - // A `$merge` or `$out` stage writes a pipeline's output for a later read; a `'$out'` string - // doesn't. - private val output = Regex("""[{,]\s*["']?\$(?:merge|out)["']?\s*:""") - /** A document or document list in a data or shell language: data, not program code. */ fun isDocument(block: ScenarioCode) = block.language in documentLanguages && diff --git a/audits/src/test/kotlin/dev/morphia/audits/offline/GeneratorTest.kt b/audits/src/test/kotlin/dev/morphia/audits/offline/GeneratorTest.kt index c36807453bd..bf909cdbd19 100644 --- a/audits/src/test/kotlin/dev/morphia/audits/offline/GeneratorTest.kt +++ b/audits/src/test/kotlin/dev/morphia/audits/offline/GeneratorTest.kt @@ -253,6 +253,86 @@ class GeneratorTest { ) } + @Test + fun anUpdatesReadTravelsWithItsCase() { + val root = directory.resolve("repository") + write( + root.resolve("audits/catalog/fixture-migration.json"), + AuditJson.write(FixtureMigrationLedger()), + ) + val seed = "db.inventory.insertMany( [ { _id: 1, qty: Int32(25) } ] )" + val update = "db.inventory.updateOne( { _id: 1 }, { \$inc: { qty: 2 } } )" + pages.operator("inc", "update", "update") { + listOf( + section( + "Examples", + code(seed), + section( + "Increment and Read", + code(update), + code("db.inventory.find( { _id: 1 } ).sort( { _id: 1 } )"), + code("[ { _id: 1, qty: 27 } ]"), + ), + section( + "Increment a Declared Id", + code("const id = 1"), + code("db.inventory.updateOne( { _id: id }, { \$inc: { qty: 2 } } )"), + code("db.inventory.find( { _id: id } )"), + code("[ { _id: 1, qty: 27 } ]"), + ), + section( + "Increment and Read One", + code(update), + code("db.inventory.find( { } ).limit( 1 )"), + code("[ { _id: 1, qty: 27 } ]"), + ), + ) + ) + } + val inventory = capture(root) + assertEquals( + listOf(BlockRole.DATA, BlockRole.ACTION, BlockRole.READ, BlockRole.EXPECTED), + inventory.pages.single().examples.first().blocks.map { it.role }, + ) + val repository = + generateSequence(Path.of("").toAbsolutePath()) { it.parent } + .first { Files.isDirectory(it.resolve("audits/catalog")) } + val generation = + CaseGenerator.generate( + inventory, + AuditJson.dslBindings(Files.readString(repository.resolve(DslBindings.PATH))), + GenerationReview(families = listOf("query/updates")), + emptySet(), + ) + fun scenario(name: String) = + BsonDocument.parse( + generation.files.getValue( + "core/src/test/resources" + + generation.cases + .single { it.manifest.name.endsWith(name) } + .manifest + .scenario + ) + ) + val scenario = scenario("incrementAndRead") + // A read sees the bindings the example declared before it. + assertEquals( + BsonDocument.parse("{collection: 'inventory', filter: {_id: 1}}"), + scenario("incrementADeclaredId").getDocument("action").getDocument("read"), + ) + // The page's find runs after the update on both sides; its result is the printed one. + assertEquals( + BsonDocument.parse("{collection: 'inventory', filter: {_id: 1}, sort: {_id: 1}}"), + scenario.getDocument("action").getDocument("read"), + ) + assertTrue(scenario.getDocument("expected").containsKey("printed"), scenario.toJson()) + // Any other modifier would change what the page printed. + assertEquals( + mapOf("Increment and Read One" to "a read with LIMIT"), + generation.gaps.associate { it.title to it.detail }, + ) + } + /** * A fixture named for an example owns it even when its title and action text have changed since * the fixture was written. diff --git a/audits/src/test/kotlin/dev/morphia/audits/offline/ScenarioExtractionTest.kt b/audits/src/test/kotlin/dev/morphia/audits/offline/ScenarioExtractionTest.kt index b6327dfc48c..b1e2d13b8a2 100644 --- a/audits/src/test/kotlin/dev/morphia/audits/offline/ScenarioExtractionTest.kt +++ b/audits/src/test/kotlin/dev/morphia/audits/offline/ScenarioExtractionTest.kt @@ -1309,43 +1309,196 @@ class ScenarioExtractionTest { ) assertEquals(2, charged(117).scenarios.size) assertThrows(IllegalArgumentException::class.java) { charged(116) } - // A read after an update in the same section depends on it, so it isn't run alone. - val reads = + fun updates(vararg blocks: String) = + extract(root(standalone("Update Items", "update", *blocks)), assembledRule()).scenarios + val insert = "db.items.insertOne({v:1});" + val update = "db.items.updateOne({}, {${'$'}set: {v: 2}});" + // The find a page runs right after an update is that update's read: one scenario, whose + // published result is the find's. + val paired = updates(insert, update, "db.items.find({});", "[{v:2}]").single() + assertEquals( + listOf(ProgramRole.SETUP, ProgramRole.ACTION, ProgramRole.ACTION, ProgramRole.EXPECTED), + paired.blocks.map { it.role }, + ) + val program = paired.program!! + assertEquals(ShellLiteralState.NORMALIZED, program.state) + val find = program.commands.last { it.role == ProgramRole.ACTION } + assertTrue(find.operation is FindOperation) + assertEquals(find.id, program.expectations.single().command) + // An acknowledgement printed between them is the update's, and skipped. + val acknowledged = + updates(insert, update, "{ acknowledged: true }", "db.items.find({});", "[{v:2}]") + .single() + assertEquals(4, acknowledged.blocks.size) + assertEquals(listOf("UPDATE_RESULT"), acknowledged.skipped.map { it.reason }) + // A second read sees the write too but isn't its read, and neither is a read with + // nothing printed after it. + val second = + updates( + insert, + update, + "db.items.find({});", + "[{v:2}]", + "db.items.find({v:2});", + "[{v:2}]", + ) + assertEquals( + setOf(null, "AFTER_EARLIER_WRITE"), + second.map { it.normalizationProblem }.toSet(), + ) + val unprinted = updates(insert, update, "db.items.find({});") + assertEquals( + setOf(null, "AFTER_EARLIER_WRITE"), + unprinted.map { it.normalizationProblem }.toSet(), + ) + // A write after a write sees its effect, so it isn't run alone either. + val twice = updates(insert, update, "db.items.updateOne({}, {${'$'}set: {v: 3}});") + assertEquals( + setOf(null, "AFTER_EARLIER_WRITE"), + twice.map { it.normalizationProblem }.toSet(), + ) + // Setup between them would change what the find sees without the pair running it. + val reseeded = + updates(insert, update, "db.items.insertOne({v:5});", "db.items.find({});", "[{v:2}]") + assertEquals( + setOf(null, "AFTER_EARLIER_WRITE"), + reseeded.map { it.normalizationProblem }.toSet(), + ) + // A write in one tab neither pairs with nor stales a read in another: tabs are separate + // examples under one section. + fun tab(id: String, vararg sources: String) = + node( + "directive", + name = "tab", + options = mapOf("tabid" to AuditJson.write(id).trim()), + arguments = listOf(node("text", text = id)), + children = sources.map { code(it) }, + ) + val tabbed = extract( root( + section( + "Update Items", + "update", + node( + "directive", + name = "tabs", + children = + listOf( + tab("first", insert, update), + tab("second", insert, "db.items.find({});", "[{v:1}]"), + ), + ), + ) + ), + assembledRule(tabs = listOf("first", "second")), + ) + .scenarios + assertEquals(2, tabbed.size) + assertTrue(tabbed.all { it.normalizationProblem == null }, tabbed.toString()) + assertTrue(tabbed.all { s -> s.blocks.count { it.role == ProgramRole.ACTION } == 1 }) + // A read on another collection keeps that collection's earlier inserts. + val merged = + extract( + root( + standalone("Seed Totals", "seed", "db.totals.insertOne({_id: 2, v: 10});"), standalone( + "Merge Items", + "merge-items", + insert, + "db.items.aggregate([{${'$'}merge: \"totals\"}]);", + "db.totals.find({});", + "[{_id: 2, v: 10}]", + ), + ), + assembledRule(), + ) + .scenarios + .single { it.program != null } + assertEquals( + setOf("items", "totals"), + merged.program!! + .commands + .filter { it.operation is InsertOperation } + .map { it.namespace.collection } + .toSet(), + ) + // A write outside a tab reaches the read inside it. + val nested = + extract( + root( + section( "Update Items", "update", - "db.items.insertOne({v:1});", - "db.items.updateOne({}, {${'$'}set: {v: 2}});", - "db.items.find({});", - "[{v:2}]", + code(insert), + code(update), + node( + "directive", + name = "tabs", + children = listOf(tab("nested", "db.items.find({});", "[{v:2}]")), + ), ) ), + assembledRule(tabs = listOf("nested")), + ) + .scenarios + assertEquals( + listOf( + listOf( + ProgramRole.SETUP, + ProgramRole.ACTION, + ProgramRole.ACTION, + ProgramRole.EXPECTED, + ) + ), + nested.map { s -> s.blocks.map { it.role } }, + ) + // Setup the two share keeps page order, so a declaration still comes first. + val declared = + extract( + root( + standalone( + "Seed Both", + "seed-both", + "const n = 1;", + "db.items.insertOne({v: n});", + "db.totals.insertOne({v: n});", + ), + standalone( + "Merge Declared", + "merge-declared", + "db.items.aggregate([{${'$'}merge: \"totals\"}]);", + "db.totals.find({});", + "[{v: 1}]", + ), + ), assembledRule(), ) .scenarios - val read = reads.single { it.blocks.any { b -> b.source == "db.items.find({});" } } - assertEquals("AFTER_EARLIER_WRITE", read.normalizationProblem) - assertNull(read.program) - // So does a read in another input/output group after a write in an earlier one. + .filter { it.program != null } + assertEquals(1, declared.size, declared.toString()) + assertEquals(ShellLiteralState.NORMALIZED, declared.single().program!!.state) + // A syntax template runs nothing, so it isn't a write before the action. + val templated = + updates("db.items.updateOne({ }, { });", insert, update).single() + assertNull(templated.normalizationProblem) + // A read in another input/output group after a pipeline that writes is that write's read, + // even on another collection. val groups = extract( root( section( "Merge Totals", "merge", - io("db.items.aggregate([{${'$'}merge: {into: \"totals\"}}]);", "[]"), + code("db.items.aggregate([{${'$'}merge: {into: \"totals\"}}]);"), io("db.totals.find({});", "[{v:1}]"), ) ), assembledRule(), ) .scenarios - assertEquals( - setOf(null, "AFTER_EARLIER_WRITE"), - groups.map { it.normalizationProblem }.toSet(), - ) + assertEquals(listOf(null), groups.map { it.normalizationProblem }) + assertEquals("totals", groups.single().program!!.commands.last().namespace.collection) } @Test diff --git a/core/src/test/java/dev/morphia/test/OperatorCaseRunner.java b/core/src/test/java/dev/morphia/test/OperatorCaseRunner.java index 66ea8943323..2c055ef8ef1 100644 --- a/core/src/test/java/dev/morphia/test/OperatorCaseRunner.java +++ b/core/src/test/java/dev/morphia/test/OperatorCaseRunner.java @@ -55,7 +55,10 @@ * {@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, and a dataset only when the scenario skips its results; a scenario that needs either fails rather - * than being checked loosely. Documented indexes are created on both databases after they are seeded. + * than being checked loosely. Documented indexes are created on both databases after they are seeded. A write (an + * update, or a pipeline that writes with {@code $merge} or {@code $out}) can carry {@code action.read}, the find the + * page runs afterwards to show its effect: both sides run that find after the write, and its results replace the + * action's own in the behavior and published checks. */ public class OperatorCaseRunner { // Canonical extended JSON, so a failure shows BSON types: relaxed JSON prints an Int64 like an Int32. @@ -143,8 +146,8 @@ public void update(OperatorCase operatorCase, ActionTestOptions options, Functio } /** - * Runs an update case: the results are the documents its filter matches after the update, and every collection is - * compared as well. + * Runs an update case: the results are what the page's own read returns after the update, when the scenario + * carries one, and otherwise the documents its filter matches afterwards. Every collection is compared as well. */ public void update(OperatorCase operatorCase, Function, Query> dsl, UpdateOperator... operators) { run(operatorCase, "update", Shape.UPDATE, (action, collection) -> { @@ -153,6 +156,8 @@ public void update(OperatorCase operatorCase, Function, Query) query).toDocument(), updates)), reference -> { var target = reference.getCollection(collection, BsonDocument.class); @@ -161,10 +166,13 @@ public void update(OperatorCase operatorCase, Function, Query(target.find(filter).into(new ArrayList<>())); + return read ? List.of() : new ArrayList<>(target.find(filter).into(new ArrayList<>())); }, () -> { query.update(new UpdateOptions().multi(multi), operators); + if (read) { + return List.of(); + } try (var cursor = query.iterator()) { return bson(cursor.toList()).getValues(); } @@ -172,6 +180,19 @@ public void update(OperatorCase operatorCase, Function, Query read(MongoDatabase database, BsonDocument read) { + var find = database.getCollection(read.getString("collection").getValue(), BsonDocument.class) + .find(read.getDocument("filter")); + if (read.containsKey("projection")) { + find = find.projection(read.getDocument("projection")); + } + if (read.containsKey("sort")) { + find = find.sort(read.getDocument("sort")); + } + return new ArrayList<>(find.into(new ArrayList<>())); + } + /** What one kind of action contributes to a run: Morphia's command, and each side's results. */ private record Execution(BsonArray emitted, Function> reference, Supplier> morphia) { @@ -294,6 +315,13 @@ private void run(OperatorCase operatorCase, String kind, Shape shape, List referenceResults = execution.reference().apply(reference); List morphiaResults = execution.morphia().get(); + // The page shows a write's effect with a find of its own; both sides run it after the write, and its + // results are the ones compared. + BsonDocument read = action.getDocument("read", null); + if (read != null) { + referenceResults = read(reference, read); + morphiaResults = read(morphia, read); + } if (!StrictBson.equal(referenceResults, morphiaResults, ordered, unordered)) { fail(operatorCase.resource() + ": behavior differs\nreference: " + json(referenceResults) + "\nmorphia: " + json(morphiaResults)); @@ -418,6 +446,14 @@ private static void supported(OperatorCase operatorCase, BsonDocument scenario) }; Set present = new TreeSet<>(action.keySet()); present.remove("alternatives"); + // Only a write has a read after it. + if (present.remove("read") && (action.getString("kind").getValue().equals("find") + || !action.get("read").isDocument() + || !Set.of("collection", "filter", "projection", "sort").containsAll(action.getDocument("read").keySet()) + || !action.getDocument("read").containsKey("collection") + || !action.getDocument("read").containsKey("filter"))) { + unsupported.add("read " + action.get("read")); + } if (!present.equals(fields)) { unsupported.add("action fields " + action.keySet()); } else if (action.getString("kind").getValue().equals("aggregate")) { diff --git a/core/src/test/java/dev/morphia/test/OperatorCaseRunnerTest.java b/core/src/test/java/dev/morphia/test/OperatorCaseRunnerTest.java index 3261ea44fc8..b99c5490d06 100644 --- a/core/src/test/java/dev/morphia/test/OperatorCaseRunnerTest.java +++ b/core/src/test/java/dev/morphia/test/OperatorCaseRunnerTest.java @@ -5,8 +5,14 @@ import org.junit.jupiter.api.Test; import org.opentest4j.AssertionFailedError; +import static dev.morphia.aggregation.expressions.ArrayExpressions.size; +import static dev.morphia.aggregation.expressions.ComparisonExpressions.gt; import static dev.morphia.aggregation.expressions.MathExpressions.round; import static dev.morphia.aggregation.stages.Projection.project; +import static dev.morphia.query.filters.Filters.expr; +import static dev.morphia.query.filters.Filters.ne; +import static dev.morphia.query.updates.UpdateOperators.inc; +import static dev.morphia.query.updates.UpdateOperators.unset; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -43,6 +49,29 @@ public void resultsMustSatisfyThePrintedResults() { assertTrue(failure.getMessage().contains("results differ from the printed results at /0/v"), failure.getMessage()); } + @Test + public void aWritesReadIsTheOneCompared() { + // The page prints the whole collection after the update; with its read, that is what both sides return. + runner.update(OperatorCase.of("/dev/morphia/test/generated/fixtures/runner/readAfterUpdate/scenario.json"), + (query) -> query.filter(ne("grades", 100)), inc("grades.$[]", 10)); + } + + @Test + public void aWritesReadReplacesTheFiltersQuery() { + // After the update the filter's $size has no array to read, so querying it again would fail; only the read runs. + runner.update(OperatorCase.of("/dev/morphia/test/generated/fixtures/runner/readAfterUnset/scenario.json"), + (query) -> query.filter(expr(gt(size("$tags"), 0))), unset("tags")); + } + + @Test + public void withoutAReadAnUpdateReturnsWhatItsFilterMatches() { + // The same update without its read: the filter no longer matches the document whose grades reached 100. + AssertionFailedError failure = assertThrows(AssertionFailedError.class, + () -> runner.update(OperatorCase.of("/dev/morphia/test/generated/fixtures/runner/filterAfterUpdate/scenario.json"), + (query) -> query.filter(ne("grades", 100)), inc("grades.$[]", 10))); + assertTrue(failure.getMessage().contains("results differ from the documented results"), failure.getMessage()); + } + @Test public void aConvertedCasesOptionsMustMatchItsScenario() { AssertionFailedError failure = assertThrows(AssertionFailedError.class, diff --git a/core/src/test/resources/dev/morphia/test/generated/fixtures/runner/filterAfterUpdate/scenario.json b/core/src/test/resources/dev/morphia/test/generated/fixtures/runner/filterAfterUpdate/scenario.json new file mode 100644 index 00000000000..599aef59afb --- /dev/null +++ b/core/src/test/resources/dev/morphia/test/generated/fixtures/runner/filterAfterUpdate/scenario.json @@ -0,0 +1,141 @@ +{ + "schemaVersion": 1, + "name": "runner/filterAfterUpdate", + "context": "UPDATE", + "source": null, + "dataset": null, + "collections": { + "results": [ + { + "_id": { + "$numberInt": "1" + }, + "grades": [ + { + "$numberInt": "85" + }, + { + "$numberInt": "82" + }, + { + "$numberInt": "80" + } + ] + }, + { + "_id": { + "$numberInt": "2" + }, + "grades": [ + { + "$numberInt": "88" + }, + { + "$numberInt": "90" + }, + { + "$numberInt": "92" + } + ] + }, + { + "_id": { + "$numberInt": "3" + }, + "grades": [ + { + "$numberInt": "85" + }, + { + "$numberInt": "100" + }, + { + "$numberInt": "90" + } + ] + } + ] + }, + "indexes": [], + "action": { + "kind": "update", + "collection": "results", + "filter": { + "grades": { + "$ne": { + "$numberInt": "100" + } + } + }, + "update": { + "$inc": { + "grades.$[]": { + "$numberInt": "10" + } + } + }, + "multi": true + }, + "expected": { + "documents": [ + { + "_id": { + "$numberInt": "1" + }, + "grades": [ + { + "$numberInt": "95" + }, + { + "$numberInt": "92" + }, + { + "$numberInt": "90" + } + ] + }, + { + "_id": { + "$numberInt": "2" + }, + "grades": [ + { + "$numberInt": "98" + }, + { + "$numberInt": "100" + }, + { + "$numberInt": "102" + } + ] + }, + { + "_id": { + "$numberInt": "3" + }, + "grades": [ + { + "$numberInt": "85" + }, + { + "$numberInt": "100" + }, + { + "$numberInt": "90" + } + ] + } + ] + }, + "comparison": { + "order": "ORDERED", + "rules": [], + "ignore": [], + "tolerance": null + }, + "requirements": { + "minimumServer": null, + "topology": "STANDALONE" + } +} diff --git a/core/src/test/resources/dev/morphia/test/generated/fixtures/runner/readAfterUnset/scenario.json b/core/src/test/resources/dev/morphia/test/generated/fixtures/runner/readAfterUnset/scenario.json new file mode 100644 index 00000000000..8859e693a5a --- /dev/null +++ b/core/src/test/resources/dev/morphia/test/generated/fixtures/runner/readAfterUnset/scenario.json @@ -0,0 +1,20 @@ +{ + "schemaVersion": 1, + "name": "runner/readAfterUnset", + "context": "UPDATE", + "source": null, + "dataset": null, + "collections": { "items": [ { "_id": { "$numberInt": "1" }, "tags": [ "a" ] } ] }, + "indexes": [], + "action": { + "kind": "update", + "collection": "items", + "filter": { "$expr": { "$gt": [ { "$size": "$tags" }, { "$numberInt": "0" } ] } }, + "update": { "$unset": { "tags": "" } }, + "multi": false, + "read": { "collection": "items", "filter": {} } + }, + "expected": { "documents": [ { "_id": { "$numberInt": "1" } } ] }, + "comparison": { "order": "ORDERED", "rules": [], "ignore": [], "tolerance": null }, + "requirements": { "minimumServer": null, "topology": "STANDALONE" } +} diff --git a/core/src/test/resources/dev/morphia/test/generated/fixtures/runner/readAfterUpdate/scenario.json b/core/src/test/resources/dev/morphia/test/generated/fixtures/runner/readAfterUpdate/scenario.json new file mode 100644 index 00000000000..82dea7e2566 --- /dev/null +++ b/core/src/test/resources/dev/morphia/test/generated/fixtures/runner/readAfterUpdate/scenario.json @@ -0,0 +1,150 @@ +{ + "schemaVersion": 1, + "name": "runner/readAfterUpdate", + "context": "UPDATE", + "source": null, + "dataset": null, + "collections": { + "results": [ + { + "_id": { + "$numberInt": "1" + }, + "grades": [ + { + "$numberInt": "85" + }, + { + "$numberInt": "82" + }, + { + "$numberInt": "80" + } + ] + }, + { + "_id": { + "$numberInt": "2" + }, + "grades": [ + { + "$numberInt": "88" + }, + { + "$numberInt": "90" + }, + { + "$numberInt": "92" + } + ] + }, + { + "_id": { + "$numberInt": "3" + }, + "grades": [ + { + "$numberInt": "85" + }, + { + "$numberInt": "100" + }, + { + "$numberInt": "90" + } + ] + } + ] + }, + "indexes": [], + "action": { + "kind": "update", + "collection": "results", + "filter": { + "grades": { + "$ne": { + "$numberInt": "100" + } + } + }, + "update": { + "$inc": { + "grades.$[]": { + "$numberInt": "10" + } + } + }, + "multi": true, + "read": { + "collection": "results", + "filter": {}, + "sort": { + "_id": { + "$numberInt": "1" + } + } + } + }, + "expected": { + "documents": [ + { + "_id": { + "$numberInt": "1" + }, + "grades": [ + { + "$numberInt": "95" + }, + { + "$numberInt": "92" + }, + { + "$numberInt": "90" + } + ] + }, + { + "_id": { + "$numberInt": "2" + }, + "grades": [ + { + "$numberInt": "98" + }, + { + "$numberInt": "100" + }, + { + "$numberInt": "102" + } + ] + }, + { + "_id": { + "$numberInt": "3" + }, + "grades": [ + { + "$numberInt": "85" + }, + { + "$numberInt": "100" + }, + { + "$numberInt": "90" + } + ] + } + ] + }, + "comparison": { + "order": "ORDERED", + "rules": [], + "ignore": [], + "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 f8f9b191aeb..54e8453e142 100644 --- a/core/src/test/resources/dev/morphia/test/generated/manifest.json +++ b/core/src/test/resources/dev/morphia/test/generated/manifest.json @@ -3620,10 +3620,22 @@ "owner" : "PROTECTED", "path" : "src/test/resources/dev/morphia/test/generated/fixtures/runner/crossDatabase/scenario.json", "sha256" : "cbee0e532d5860b826a27bbddda925f621fe69033d0220da7cbdb63acc2aec56" + }, { + "owner" : "PROTECTED", + "path" : "src/test/resources/dev/morphia/test/generated/fixtures/runner/filterAfterUpdate/scenario.json", + "sha256" : "2592cb3c9e8a42f20a3198e93ba81f408096ee296d2da08e44af35cb68367462" }, { "owner" : "PROTECTED", "path" : "src/test/resources/dev/morphia/test/generated/fixtures/runner/printedMismatch/scenario.json", "sha256" : "ccdec466a95e3325eecd8997cb852a14de71a815c6f6c5e4cd5b77332aab5296" + }, { + "owner" : "PROTECTED", + "path" : "src/test/resources/dev/morphia/test/generated/fixtures/runner/readAfterUnset/scenario.json", + "sha256" : "57ea07845bfdb6bc30c4018e61ab10ac45953d4aca30a19417b4a555d0fdbced" + }, { + "owner" : "PROTECTED", + "path" : "src/test/resources/dev/morphia/test/generated/fixtures/runner/readAfterUpdate/scenario.json", + "sha256" : "4ab0122b1d6ad999bc8438c2debfcb5d6b8677eb45c681fc0f7b1b1ba41d35d6" }, { "owner" : "GENERATED", "path" : "src/test/resources/dev/morphia/test/generated/fixtures/stages/group/groupByNull/scenario.json", diff --git a/design/operator-audits-design.md b/design/operator-audits-design.md index 2845920756a..551d778e9b8 100644 --- a/design/operator-audits-design.md +++ b/design/operator-audits-design.md @@ -254,9 +254,12 @@ snippets (`/code-examples/tested/...`) and include files are resolved through th with its blob. Many tested snippets query MongoDB's sample datasets (`db.movies`) and print elided results; they extract like any other example and then show up as generation gaps. -Until an update's case runs the read the page shows after it, what a page prints after an update -(an acknowledgement, or the documents its filter matches) goes to generation as that update's -printed result, the convention the converted cases use. +A write (an update, or a pipeline ending in `$merge` or `$out`) followed in its section by the find +the page runs to show its effect, with that find's printed result, is one example: the find is its +`READ` block, and the printed result is the find's. Both sides run the find after the write. Where +the page prints after an update without showing a read, what it prints (an acknowledgement, or the +documents its filter matches) goes to generation as that update's printed result, the convention +the converted cases use. ### Generation diff --git a/design/operator-audits-progress.md b/design/operator-audits-progress.md index aac8c6f7d8b..12b35334100 100644 --- a/design/operator-audits-progress.md +++ b/design/operator-audits-progress.md @@ -2776,3 +2776,12 @@ no product-documentation changes. Legacy operator AsciiDoc tables are intentiona `references`, `recheck-references`, `migrate`, `convert`) are deleted. Their catalogs stay frozen: `FormMigrationTest` checks the 136 migrated declarations and the 250 references offline, and that every referenced fixture is in the ledger. `FormMainKt` keeps `rescenario` and `manifest`. +- Update results, option (c): a write's read. A find directly after a write in its section (an + update, or a pipeline ending in `$merge`/`$out`), with its printed result, joins the write's + scenario as its read, across section code and input/output groups; the inventory records it as + a `READ` block and the scenario as `action.read`, which `OperatorCaseRunner` runs on both sides + after the write. At docs e4b0c153, 8 reads pair (six `$merge`/`$out` examples, `$currentDate`'s + aggregation alternative, and one owned `positional` example), and unsupported examples drop + from 112 to 104. None generates yet: `$merge`, `$out` and pipeline updates have no binding. + The page-wide pass now also marks a write after a write, and no longer counts a syntax template + as a write. diff --git a/design/operator-audits-section-assembly.md b/design/operator-audits-section-assembly.md index e94ab2dd148..96471412400 100644 --- a/design/operator-audits-section-assembly.md +++ b/design/operator-audits-section-assembly.md @@ -34,8 +34,9 @@ Skipped source stays visible on its scenario (`skipped`) or, for shared setup, o - `SYNTAX_TEMPLATE`: the block names operands in angle brackets, `{ $add: [ , ... ] }`; - `SAMPLE_DOCUMENT`: a displayed document where the scenario already inserts its data; - `OPERATOR_EXPRESSION`: a displayed expression such as `{ $regexMatch: { ... } }`, which is neither data nor a result; -- `UPDATE_RESULT`: the documents a page prints after an update, which come from a read it runs - next, not from the update; they wait for the update's own read; +- `UPDATE_RESULT`: what a page prints directly after an update, an acknowledgement or documents + from a read it doesn't show; it isn't the update's result (generation still reads it the legacy + way when the update has no read); - `UNREADABLE_RESULT`: a printed result the result grammar rejects, such as a truncated `...` listing; the scenario keeps its action and runs serialization-only; - `SEVERAL_COMMANDS`: a block holding more than one action; @@ -47,9 +48,8 @@ Skipped source stays visible on its scenario (`skipped`) or, for shared setup, o declared. Each action becomes its own scenario with the setup and candidate seeds before it; earlier actions -are other scenarios. A read that follows an update in the same section depends on that update, so it -reports `AFTER_EARLIER_WRITE` and has no program of its own; pairing an update with the read a -page runs after it is the next step for update examples. Seeds are settled per scenario against the setup it actually runs, shared and +are other scenarios. An action that follows a write in the same section depends on that write; the +page-wide pass below settles it (see **Reads after writes**). Seeds are settled per scenario against the setup it actually runs, shared and local, for section-owned and native input/output groups alike: where that setup inserts, the documents only illustrate (`SAMPLE_DOCUMENT`); otherwise they seed the action's collection. The language check ignores documents and printed results, so the action's own label always counts. An action without a result directly after it has no published expectation. A section @@ -91,7 +91,17 @@ scenarios are built, two page-wide passes run in page order: it. - **Reads after writes.** A read that follows a write in its section (an update, a pipeline with `$merge` or `$out`, or a write the page shows but no scenario runs, such as a `bulkWrite` in a - `try` block) reports `AFTER_EARLIER_WRITE` and has no program of its own. + `try` block) reports `AFTER_EARLIER_WRITE` and has no program of its own, and so does a write + after a write. A syntax template is not a write. The exception is the write's read: a find + directly after a write in its section, with its printed result, where the write runs one command + and prints nothing but, at most, an acknowledgement. The find and its result join the write's scenario, as a second + action whose result the expectation names (`expectedFor`), and the find has no scenario of its + own. That works across a section's code and its input/output groups, as on the `$merge` and + `$out` pages, and for a find on another collection. Only the first read after a write pairs. + Nothing may run between them: setup or a skipped write in between refuses the pair. The pair + keeps the setup either side needs, such as the earlier inserts into the collection the find + reads, in page order. A write reaches its own tab or `selected-content` branch and the + branches nested in it, never a sibling branch, which is a separate example. Tabs and `selected-content` branches start separate owners; a selection naming a reference tab reads as reference, one naming a foreign tab as foreign. A shared section with one branch per diff --git a/design/operator-audits-test-generation.md b/design/operator-audits-test-generation.md index 49b6a123a8c..ec1f908cb0a 100644 --- a/design/operator-audits-test-generation.md +++ b/design/operator-audits-test-generation.md @@ -121,6 +121,10 @@ canonical extended JSON (`$numberInt`, `$date`, …), so BSON types survive. `{kind: "update", collection, filter, update, multi}`. A find's results are the matching documents; an update's, as in the legacy harness, are the documents its filter matches afterwards, and every collection is compared too. +- **`action.read`:** on an update or an aggregate, `{collection, filter, projection?, sort?}`, the + find the page runs after the write to show its effect. Both sides run it after the write, and + its results replace the action's own in the behavior and published checks. A page that prints + after an update without showing a read has none, and keeps the reading above. - **`expected`:** either `documents` (exact), `printed` (the published constraints of [published expectations](operator-audits-published-expectations.md)), or `none` with a reason. Each printed constraint is a one-key document naming its kind, so no published field name or