diff --git a/audits/src/main/kotlin/dev/morphia/audits/coverage/AuditJson.kt b/audits/src/main/kotlin/dev/morphia/audits/coverage/AuditJson.kt index 14cf7ff9e00..f6ab908dc7e 100644 --- a/audits/src/main/kotlin/dev/morphia/audits/coverage/AuditJson.kt +++ b/audits/src/main/kotlin/dev/morphia/audits/coverage/AuditJson.kt @@ -222,6 +222,13 @@ object AuditJson { /** Canonical JSON attribute strings stay typed at the adapter boundary. */ fun textValue(json: String): String = requireNotNull(mapper.readValue(json, String::class.java)) + /** The values of a JSON object's members, null where a value isn't text. */ + fun textValues(json: String): List = + mapper.readTree(json).let { tree -> + require(tree.isObject) { "Expected a JSON object" } + tree.properties().map { (_, value) -> value.textValue() } + } + private fun read(json: String, type: Class): T { val tree = requireNotNull(mapper.readTree(json)) { "Empty JSON input" } require( diff --git a/audits/src/main/kotlin/dev/morphia/audits/scenarios/ScenarioContracts.kt b/audits/src/main/kotlin/dev/morphia/audits/scenarios/ScenarioContracts.kt index 5b3b59a1114..294242f5581 100644 --- a/audits/src/main/kotlin/dev/morphia/audits/scenarios/ScenarioContracts.kt +++ b/audits/src/main/kotlin/dev/morphia/audits/scenarios/ScenarioContracts.kt @@ -36,6 +36,8 @@ data class SectionAssemblyPolicy( val scenarioTabs: List = emptyList(), /** Explicit legacy highlighting aliases, still parsed with the closed shell grammar. */ val additionalShellLanguages: List = emptyList(), + /** The reviewed language of code the page leaves unlabeled, when the page has such code. */ + val unlabeledLanguage: String? = null, ) enum class SectionLayout { @@ -82,6 +84,10 @@ data class ScenarioCode( val role: ProgramRole?, val containers: List, val snippets: List, + /** How the program reads this block, when not by its role: a sample document seeds data. */ + val format: ProgramFormat? = null, + /** The collection a sample document seeds. */ + val namespace: LogicalNamespace? = null, ) enum class ScenarioVariant { @@ -104,8 +110,13 @@ data class ExtractedScenario( val program: ShellProgramResult?, val normalizationProblem: String?, val naming: NamingScenario?, + /** Selected source the program leaves out, each with the reason. */ + val skipped: List = emptyList(), ) +/** Source a section shows that no program role fits, such as a syntax template. */ +data class SkippedCode(val code: ScenarioCode, val reason: String) + data class ScenarioExtractionProblem( val code: String, val rule: String, @@ -133,6 +144,8 @@ data class ExtractedScenarioPage( val namingComplete: Boolean, /** Declared setup is retained even if all consumers disappear. */ val sharedSetup: List = emptyList(), + /** Source in the shared setup sections that isn't setup, each with the reason. */ + val sharedSetupSkipped: List = emptyList(), ) enum class ScenarioExtractionState { 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 4b96a24db18..3f43fd285d5 100644 --- a/audits/src/main/kotlin/dev/morphia/audits/scenarios/ScenarioExtraction.kt +++ b/audits/src/main/kotlin/dev/morphia/audits/scenarios/ScenarioExtraction.kt @@ -210,6 +210,10 @@ object ScenarioExtraction { } ) require(policy.additionalShellLanguages.all { it in setOf("bash", "sh") }) + require( + policy.unlabeledLanguage == null || + policy.unlabeledLanguage in p.referenceLanguages + ) require(policy.scenarioTabs.all { it.matches(Regex("[A-Za-z0-9][A-Za-z0-9_.-]*")) }) require( policy.scenarioTabs @@ -373,6 +377,16 @@ object ScenarioExtraction { return report } + /** The language (or other) choices a selected-content block is shown for. */ + fun selections(container: ScenarioContainer): List = + container.attributes["selections"]?.let { + try { + AuditJson.textValues(it).ifEmpty { listOf(null) } + } catch (_: Exception) { + listOf(null) + } + } ?: listOf(null) + fun value(values: Map, key: String): String? = values[key]?.let { try { @@ -496,7 +510,16 @@ object ScenarioExtraction { "step", "steps", "list-table", + "composable-tutorial", + "selected-content", + // Shared content a page pulls in from an include. + "extract", ) + // A composable tutorial's selected content names its selection the way a tab does. + val selections = + containers + .filter { it.kind == "directive" && it.name == "selected-content" } + .flatMap { selections(it) } val tabs = containers .filter { @@ -504,7 +527,7 @@ object ScenarioExtraction { it.name == "tab" && it.domain in setOf(null, "", "mongodb", "std") } - .map { value(it.options, "tabid") } + .map { value(it.options, "tabid") } + selections if (tabs.any { it in rule.foreignTabs }) return ScenarioVariant.FOREIGN if ( containers.any { @@ -525,7 +548,12 @@ object ScenarioExtraction { val languages = code .filter { it.role in setOf(ProgramRole.ACTION, ProgramRole.SETUP) } - .map { it.language } + // JSON is data a page shows or seeds; `none` turns highlighting off. + .filter { it.language != "json" } + .map { + it.language?.takeUnless { l -> l == "none" } + ?: rule.sectionAssembly?.unlabeledLanguage + } if (languages.isEmpty() || languages.any { it == null }) return ScenarioVariant.UNRESOLVED if ( @@ -611,7 +639,9 @@ object ScenarioExtraction { locator, source, sha(source), - value(node.attributes, "lang"), + // The parser leaves code-block options after the language: `javascript\n:copyable: + // true`. + value(node.attributes, "lang")?.lineSequence()?.first()?.trim()?.ifEmpty { null }, node.attributes, node.origin, roles.singleOrNull(), @@ -653,6 +683,7 @@ object ScenarioExtraction { val owners = linkedMapOf, Owner>() val pendingIo = mutableListOf<() -> Unit>() var sharedSetup = emptyList() + var sharedSetupSkipped = emptyList() var setupProblem: String? = null val ownedResources = (listOf(prefix + page.id) + @@ -680,7 +711,11 @@ object ScenarioExtraction { if (node.kind !in setOf("root", "section", "code")) containers + container(node) else containers val nextOwner = - if (node.kind == "section" || (node.kind == "directive" && node.name == "tab")) + if ( + node.kind == "section" || + (node.kind == "directive" && + node.name in setOf("tab", "selected-content")) + ) locator else owner if ( @@ -756,9 +791,17 @@ object ScenarioExtraction { val selectedSetup = mutableSetOf() val rawSetup = mutableListOf() policy.sharedSetupSections.forEach { anchor -> + val all = owners.values.filter { it.sections.lastOrNull()?.anchor == anchor } + // A section with one selected-content branch per language shares its shell + // one; when only other languages show code, it shares nothing. val matches = - owners.values.filter { it.sections.lastOrNull()?.anchor == anchor } - if (matches.size != 1) { + all.filter { + ownVariant(rule, it.blocks, it.containers, true) != + ScenarioVariant.FOREIGN + } + if (all.isNotEmpty() && matches.isEmpty()) { + // The foreign branches stay ordinary foreign groups. + } else if (matches.size != 1) { setupProblem = "MISSING_OR_AMBIGUOUS_SHARED_SETUP" problem( requireNotNull(setupProblem), @@ -772,14 +815,18 @@ object ScenarioExtraction { } if (rawSetup.isNotEmpty()) { val assignment = SectionPrograms.shared(rawSetup, rule.dialect) + sharedSetupSkipped = assignment.skipped + // Sample documents that seed data are data, whatever their highlighting. val knownReference = - rawSetup.all { - variant( - rule, - listOf(it.copy(role = ProgramRole.ACTION)), - it.containers, - ) == ScenarioVariant.REFERENCE - } + assignment.blocks + .filter { it.format == null } + .all { + variant( + rule, + listOf(it.copy(role = ProgramRole.ACTION)), + it.containers, + ) == ScenarioVariant.REFERENCE + } if (assignment.problem != null || !knownReference) { setupProblem = assignment.problem ?: "UNRESOLVED_SHARED_SETUP_LANGUAGE" problem( @@ -793,43 +840,53 @@ object ScenarioExtraction { owners.values .filter { it !in selectedSetup } .forEach { owner -> - require(++groups <= limits.maximumGroups) { - "Scenario group budget exceeded" - } val ownVariant = ownVariant(rule, owner.blocks, owner.containers, true) val setup = if (ownVariant == ScenarioVariant.REFERENCE) sharedSetup else emptyList() - chargeSetup(setup) - val assignment = + val assignments = when { policy.layout == SectionLayout.SOURCE_ONLY -> - SectionPrograms.Assignment( - setup + owner.blocks, - "SOURCE_ONLY_SECTION", + listOf( + SectionPrograms.Assignment( + setup + owner.blocks, + "SOURCE_ONLY_SECTION", + ) ) ownVariant == ScenarioVariant.FOREIGN -> - SectionPrograms.Assignment(owner.blocks, "FOREIGN_SECTION") + listOf( + SectionPrograms.Assignment(owner.blocks, "FOREIGN_SECTION") + ) ownVariant == ScenarioVariant.UNRESOLVED -> - SectionPrograms.Assignment( - owner.blocks, - "UNRESOLVED_SECTION_LANGUAGE", + listOf( + SectionPrograms.Assignment( + owner.blocks, + "UNRESOLVED_SECTION_LANGUAGE", + ) ) else -> SectionPrograms.assign(setup, owner.blocks, rule.dialect) } - emit( - rule, - page, - owner.sections, - owner.containers, - owner.source, - emptyList(), - assignment.blocks, - false, - setupProblem ?: assignment.problem, - sectionOwned = true, - sharedSetupBlocks = setup.size, - ) + assignments.forEach { assignment -> + // Each action a section splits into is a group of its own. + require(++groups <= limits.maximumGroups) { + "Scenario group budget exceeded" + } + chargeSetup(setup) + emit( + rule, + page, + owner.sections, + owner.containers, + owner.source, + emptyList(), + assignment.blocks, + false, + setupProblem ?: assignment.problem, + sectionOwned = true, + sharedSetupBlocks = setup.size, + skipped = assignment.skipped, + ) + } } pendingIo.forEach { it() } } @@ -893,6 +950,7 @@ object ScenarioExtraction { sourceDiagnostics, complete, sharedSetup, + sharedSetupSkipped, ) } @@ -955,14 +1013,17 @@ object ScenarioExtraction { containers: List, sectionOwned: Boolean, ): ScenarioVariant { - // The reviewed layout declares its output tail independently of input semantics. + // Documents are data: the code around them decides the language, wherever they sit. val inputs = if ( sectionOwned && - rule.sectionAssembly?.layout == SectionLayout.COMMANDS_THEN_RESULT && - blocks.size >= 2 + rule.sectionAssembly?.layout == SectionLayout.COMMANDS_THEN_RESULT ) - blocks.dropLast(1) + blocks + .filter { + it.role != ProgramRole.EXPECTED && !SectionPrograms.isDocument(it) + } + .ifEmpty { blocks } else blocks return variant( rule, @@ -984,6 +1045,7 @@ object ScenarioExtraction { ownershipProblem: String?, sectionOwned: Boolean = false, sharedSetupBlocks: Int = 0, + skipped: List = emptyList(), ) { val scenarioTabs = containers.filter { @@ -1008,7 +1070,13 @@ object ScenarioExtraction { .takeIf { it.isNotBlank() } val ownBlocks = assembledBlocks.drop(sharedSetupBlocks) val variant = ownVariant(rule, ownBlocks, containers, sectionOwned) - val blocks = if (variant == ScenarioVariant.REFERENCE) assembledBlocks else ownBlocks + var blocks = if (variant == ScenarioVariant.REFERENCE) assembledBlocks else ownBlocks + var skippedCode = skipped + if (variant == ScenarioVariant.REFERENCE) { + val (seeded, unused) = SectionPrograms.resolveSeeds(blocks, rule.dialect) + blocks = seeded + skippedCode = skippedCode + unused + } if (!sectionOwned && variant == ScenarioVariant.REFERENCE) chargeSetup(assembledBlocks.take(sharedSetupBlocks)) val id = @@ -1018,7 +1086,15 @@ object ScenarioExtraction { rule.id, sections.map { listOf(it.anchor, it.explicitLabels) }, attachedLabels, - containers.map { listOf(it.name, it.argument, it.options) }, + // Selections tell apart branches that show the same code. + containers.map { + listOf( + it.name, + it.argument, + it.options, + it.attributes["selections"], + ) + }, blocks.map { listOf(it.role, it.sha256, it.snippets.map { s -> s.identity }) }, @@ -1072,31 +1148,50 @@ object ScenarioExtraction { blocks .filter { it.role == ProgramRole.EXPECTED } .all { + // Pages label printed results as JSON, or not at all. it.language in rule.referenceLanguages + - rule.sectionAssembly?.additionalShellLanguages.orEmpty() + rule.sectionAssembly?.additionalShellLanguages.orEmpty() + + listOf(null, "json", "none") } - val program = - if (canNormalize) - ShellPrograms.normalize( - ShellProgramRequest( - dialect = rule.dialect, - blocks = - blocks.mapIndexed { i, b -> - ProgramBlock( - "block-$i", - b.source, - requireNotNull(b.role), - format = - if (b.role == ProgramRole.EXPECTED) + fun normalize(blocks: List) = + ShellPrograms.normalize( + ShellProgramRequest( + dialect = rule.dialect, + blocks = + blocks.mapIndexed { i, b -> + ProgramBlock( + "block-$i", + b.source, + requireNotNull(b.role), + format = + b.format + ?: if (b.role == ProgramRole.EXPECTED) ProgramFormat.SHELL_RESULTS else ProgramFormat.SHELL, - ) - }, - resultOrder = rule.resultOrder, - ) + namespace = b.namespace, + ) + }, + resultOrder = rule.resultOrder, ) - else null + ) + var program = if (canNormalize) normalize(blocks) else null + // A printed result the grammar can't read (a truncated `...` listing) leaves the + // example serialization-only rather than losing it. + val result = blocks.lastOrNull()?.takeIf { it.role == ProgramRole.EXPECTED } + if ( + sectionOwned && + result != null && + program != null && + program.state != ShellLiteralState.NORMALIZED + ) { + val without = normalize(blocks.dropLast(1)) + if (without.state == ShellLiteralState.NORMALIZED) { + program = without + blocks = blocks.dropLast(1) + skippedCode = skippedCode + SkippedCode(result, "UNREADABLE_RESULT") + } + } program?.let { programBytes += AuditJson.requireMaximumSize(it, limits.maximumReportBytes) require(programBytes <= limits.maximumReportBytes) { @@ -1145,6 +1240,7 @@ object ScenarioExtraction { "UNSUPPORTED_IO_OR_OUTPUT_LANGUAGE" else null, naming, + skippedCode, ) } 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 559e9a68874..b3afd129634 100644 --- a/audits/src/main/kotlin/dev/morphia/audits/scenarios/SectionPrograms.kt +++ b/audits/src/main/kotlin/dev/morphia/audits/scenarios/SectionPrograms.kt @@ -4,59 +4,219 @@ import dev.morphia.audits.shell.* /** * A reviewed commands-then-result layout plus closed parsing establishes roles, never proximity - * alone. + * alone. Each block is classified by what the shell grammar makes of it in the context of the + * blocks accepted before it: setup (inserts, indexes and declarations), an action, the published + * result directly after an action, a sample document, or source the program skips (a syntax + * template, a second command in one block), recorded with its reason. + * + * A sample document seeds the collection of the action that follows it only where nothing the + * scenario runs inserts data; otherwise it illustrates and is skipped. */ internal object SectionPrograms { private val setupKinds = setOf(ShellOperationKind.INSERT, ShellOperationKind.INDEX) + // Syntax templates name their operands in angle brackets: `{ $add: [ , ... ] }`. + private val placeholder = Regex("<[A-Za-z][^<>\n]*>") + private val quoted = Regex("""'(?:[^'\\\n]|\\.)*'|"(?:[^"\\\n]|\\.)*"""") - data class Assignment(val blocks: List, val problem: String?) + // Only source the grammar rejects is a template, and a quoted `''` is a string. + private fun template(source: String) = placeholder.containsMatchIn(source.replace(quoted, "")) + data class Assignment( + val blocks: List, + val problem: String?, + val skipped: List = emptyList(), + ) + + private sealed interface Kind { + data class Setup(val inserts: Boolean) : Kind + + data class Action(val update: Boolean, val namespace: LogicalNamespace) : Kind + + data object Document : Kind + + data class Skip(val reason: String) : Kind + } + + /** + * The setup an examples section shares; its commands and anything unreadable are skipped, with + * reasons. Its documents are candidate seeds; [resolveSeeds] decides per scenario. + */ fun shared(blocks: List, dialect: ShellDialect): Assignment { if (blocks.isEmpty()) return Assignment(blocks, "EMPTY_SHARED_SETUP") - val inspection = inspect(blocks, dialect) - if ( - inspection.state != ShellLiteralState.NORMALIZED || - inspection.operations.any { it.second !in setupKinds } - ) - return Assignment(blocks, "UNSUPPORTED_SHARED_SETUP") - return Assignment(blocks.map { it.copy(role = ProgramRole.SETUP) }, null) + val kinds = classify(emptyList(), blocks, dialect) + val setup = + blocks.mapIndexedNotNull { i, block -> + when (kinds[i]) { + is Kind.Setup -> block.copy(role = ProgramRole.SETUP) + Kind.Document -> seed(block) + else -> null + } + } + val skipped = + blocks.mapIndexedNotNull { i, block -> + when (val kind = kinds[i]) { + is Kind.Skip -> SkippedCode(block, kind.reason) + is Kind.Action -> SkippedCode(block, "SHARED_SECTION_COMMAND") + else -> null + } + } + return Assignment(setup, null, skipped) } + /** + * One assignment per action the section owns. An action's result is the document-shaped block + * directly after it; without one the scenario has no published result. The documents before an + * action are its candidate seeds. + */ fun assign( shared: List, own: List, dialect: ShellDialect, - ): Assignment { - val all = shared + own - if (own.size < 2) return Assignment(all, "MISSING_COMMAND_OR_RESULT") - // The selected policy declares a single trailing published result. No parser fallback - // chooses it. - val input = all.dropLast(1) - val inspection = inspect(input, dialect) - if (inspection.state != ShellLiteralState.NORMALIZED) - return Assignment(all, "UNSUPPORTED_SECTION_INPUT") - val byBlock = inspection.operations.groupBy({ it.first }, { it.second }) - val actionIds = inspection.operations.filter { it.second !in setupKinds }.map { it.first } - if (actionIds.size != 1) return Assignment(all, "AMBIGUOUS_SECTION_ACTION") - val action = actionIds.single() - val actionIndex = input.indices.single { "block-$it" == action } - if (byBlock.getValue(action).any { it in setupKinds } || actionIndex != input.lastIndex) - return Assignment(all, "MIXED_SECTION_ROLES") - return Assignment( - all.mapIndexed { i, block -> - block.copy( - role = + ): List { + val kinds = classify(shared.filter { it.format == null }, own, dialect) + val actions = own.indices.filter { kinds[it] is Kind.Action } + // What a page prints after an update is the read it runs next, not the update's result. + fun updated(i: Int) = (kinds.getOrNull(i - 1) as? Kind.Action)?.update == true + fun result(i: Int) = kinds[i] == Kind.Document && kinds.getOrNull(i - 1) is Kind.Action + // Setup and seeds only reach the actions after them. + fun trailing(i: Int) = actions.none { it > i } + val skipped = + own.mapIndexedNotNull { i, block -> + when (val kind = kinds[i]) { + is Kind.Skip -> SkippedCode(block, kind.reason) + Kind.Document -> + when { + updated(i) -> SkippedCode(block, "UPDATE_RESULT") + result(i) -> null + trailing(i) -> SkippedCode(block, "SAMPLE_DOCUMENT") + else -> null + } + is Kind.Setup -> + if (actions.isNotEmpty() && trailing(i)) + SkippedCode(block, "TRAILING_SETUP") + else null + is Kind.Action -> null + } + } + if (actions.isEmpty()) + return listOf(Assignment(shared + own, "MISSING_COMMAND_OR_RESULT", skipped)) + return actions.map { action -> + // Setup the section shows before this action; earlier actions are other scenarios. + val setup = + own.indices + .filter { it < action } + .mapNotNull { i -> when { - i == all.lastIndex -> ProgramRole.EXPECTED - i == actionIndex -> ProgramRole.ACTION - else -> ProgramRole.SETUP + kinds[i] is Kind.Setup -> own[i].copy(role = ProgramRole.SETUP) + kinds[i] == Kind.Document && !result(i) -> seed(own[i]) + else -> null } - ) - }, - null, + } + val result = + 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).update } + Assignment( + shared + + setup + + own[action].copy(role = ProgramRole.ACTION) + + listOfNotNull(result), + if (afterWrite) "AFTER_EARLIER_WRITE" else null, + skipped, + ) + } + } + + /** + * Settles a scenario's candidate seeds against the setup it actually runs. Where that setup + * inserts, the documents only illustrate and are skipped; otherwise they seed the action's + * collection. + */ + fun resolveSeeds( + blocks: List, + dialect: ShellDialect, + ): Pair, List> { + val seeds = blocks.filter { it.format != null && it.namespace == null } + 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 } + val namespace = inspection.namespaces.lastOrNull { it.first == "block-$action" }?.second + if ( + inspection.state != ShellLiteralState.NORMALIZED || + namespace == null || + inspection.operations.any { it.second == ShellOperationKind.INSERT } ) + return blocks.filterNot { it in seeds } to + seeds.map { SkippedCode(it, "SAMPLE_DOCUMENT") } + return blocks.map { if (it in seeds) it.copy(namespace = namespace) else it } to emptyList() } + private fun seed(block: ScenarioCode) = + block.copy(role = ProgramRole.SETUP, format = ProgramFormat.LEGACY_DOCUMENTS) + + private fun classify( + shared: List, + blocks: List, + dialect: ShellDialect, + ): List { + val accepted = shared.toMutableList() + return blocks.map { block -> + val inspection = inspect(accepted + block, dialect) + val id = "block-${accepted.size}" + val own = inspection.operations.filter { it.first == id } + when { + inspection.state != ShellLiteralState.NORMALIZED -> + when { + template(block.source) -> Kind.Skip("SYNTAX_TEMPLATE") + expression(block) -> Kind.Skip("OPERATOR_EXPRESSION") + isDocument(block) -> Kind.Document + else -> Kind.Skip("UNSUPPORTED_SOURCE") + } + own.isEmpty() -> + if (expression(block)) Kind.Skip("OPERATOR_EXPRESSION") + else if (isDocument(block)) Kind.Document + else Kind.Setup(false).also { accepted += block } + own.all { it.second in setupKinds } -> + Kind.Setup(own.any { it.second == ShellOperationKind.INSERT }).also { + accepted += block + } + own.count { it.second !in setupKinds } > 1 -> Kind.Skip("SEVERAL_COMMANDS") + // One role per block: setup beside an action would be read as part of it. + own.any { it.second in setupKinds } -> Kind.Skip("MIXED_SECTION_ROLES") + // An action isn't setup for the actions after it, which are other scenarios. + else -> + Kind.Action( + own.any { it.second == ShellOperationKind.UPDATE }, + inspection.namespaces.last { it.first == id }.second, + ) + } + } + } + + // Another language's code can open with a bracket too: a C# `[BsonIgnoreExtraElements]`. + private val documentLanguages = + setOf(null, "none", "json", "javascript", "js", "shell", "mongosh", "bash", "sh") + + /** A document or document list in a data or shell language: data, not program code. */ + fun isDocument(block: ScenarioCode) = + block.language in documentLanguages && + block.source.replace(leadingComments, "").let { + it.startsWith("{") || it.startsWith("[") + } + + // `{ $regexMatch: { ... } }` shows an expression; data and results don't lead with an operator. + private val operatorKey = Regex("""^\[?\s*\{\s*["']?\$[A-Za-z]""") + + private fun expression(block: ScenarioCode) = + isDocument(block) && operatorKey.containsMatchIn(block.source.replace(leadingComments, "")) + + // Pages caption printed results with a comment: `// The result` above the documents. + private val leadingComments = Regex("""^(?:\s|//[^\n]*(?:\n|$)|/\*[\s\S]*?\*/)*""") + private fun inspect(blocks: List, dialect: ShellDialect) = ShellPrograms.inspect( ShellProgramRequest( diff --git a/audits/src/main/kotlin/dev/morphia/audits/shell/ShellPrograms.kt b/audits/src/main/kotlin/dev/morphia/audits/shell/ShellPrograms.kt index 5f9007d8767..d98330af644 100644 --- a/audits/src/main/kotlin/dev/morphia/audits/shell/ShellPrograms.kt +++ b/audits/src/main/kotlin/dev/morphia/audits/shell/ShellPrograms.kt @@ -44,6 +44,7 @@ object ShellPrograms { result.state, result.commands.map { it.id.block to it.operation.kind }, result.problems, + result.commands.map { it.id.block to it.namespace }, ) } @@ -51,6 +52,7 @@ object ShellPrograms { val state: ShellLiteralState, val operations: List>, val problems: List, + val namespaces: List> = emptyList(), ) private class Stop( @@ -948,22 +950,42 @@ object ShellPrograms { unit.namespace ?: stop("FRAGMENT_NAMESPACE", "Legacy setup/action needs an explicit namespace") val parsed = LegacyDocuments.parse(unit.source, limits.values) - if (parsed.state != ShellLiteralState.NORMALIZED) - stop( - "LEGACY_DOCUMENTS", - parsed.problems.joinToString { "${it.code}: ${it.message}" }, - ) + val documents = + if (parsed.state == ShellLiteralState.NORMALIZED) parsed.documents + else + shellDocuments(unit.source) + ?: stop( + "LEGACY_DOCUMENTS", + parsed.problems.joinToString { "${it.code}: ${it.message}" }, + ) val op = if (unit.role == ProgramRole.SETUP) - InsertOperation("seed", true, parsed.documents.map { snapshot(it) }, null) + InsertOperation("seed", true, documents.map { snapshot(it) }, null) else AggregateOperation( - snapshot(pipeline(BsonArray(parsed.documents), EmptyExpression())), + snapshot(pipeline(BsonArray(documents), EmptyExpression())), null, ) add(Planned(namespace, op, emptyList())) } + /** + * A comma-separated document list in the shell's own value grammar, which also reads the + * printed constructors (`Decimal128(...)`) the extended JSON reader rejects. + */ + fun shellDocuments(source: String): List? { + val value = + ShellLiterals.normalize("[" + source + "\n]", request.dialect, limits.values) + .takeIf { it.state == ShellLiteralState.NORMALIZED } + ?.value as? BsonArray ?: return null + val documents = + value.values.singleOrNull()?.takeIf { it is BsonArray }?.asArray()?.values + ?: value.values + return documents + .takeIf { it.isNotEmpty() && it.all { d -> d is BsonDocument } } + ?.map { it.asDocument() } + } + fun expected(unit: ProgramBlock) { if (unit.role == ProgramRole.EXPECTED_ERROR) { val error = requireNotNull(unit.expectedError) 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 434231235bd..1f8ee71fb6e 100644 --- a/audits/src/test/kotlin/dev/morphia/audits/offline/ScenarioExtractionTest.kt +++ b/audits/src/test/kotlin/dev/morphia/audits/offline/ScenarioExtractionTest.kt @@ -910,10 +910,7 @@ class ScenarioExtractionTest { node( "directive", name = "input", - children = - listOf( - code("db.items.find({});", "javascript\n:broken-option:") - ), + children = listOf(code("db.items.find({});", "pseudocode")), ) ) ) @@ -951,7 +948,7 @@ class ScenarioExtractionTest { children = io().children.map { if (it.name == "output") - it.copy(children = listOf(code("[{v:1}]", "json"))) + it.copy(children = listOf(code("[{v:1}]", "python"))) else it } ) @@ -1124,21 +1121,27 @@ class ScenarioExtractionTest { } @Test - fun sharedSetupCannotBeAnActionOrAnUnresolvedLanguage() { - for (setup in - listOf(code("db.items.find({});"), code("db.items.insertOne({v:1});", "bash"))) { - val report = - extract( - root( - section("Shared", "shared", setup), - standalone("Read Items", "read", "db.items.find({});", "[]"), - ), - assembledRule(shared = listOf("shared")), - ) - assertEquals(ScenarioExtractionState.PARTIAL, report.state) - assertTrue(report.pages.single().unassigned.isNotEmpty()) - assertTrue(report.scenarios.all { it.naming == null && it.program == null }) - } + fun sharedSetupSkipsCommandsAndRejectsAnUnresolvedLanguage() { + fun shared(setup: DocumentNode) = + extract( + root( + section("Shared", "shared", setup), + standalone("Read Items", "read", "db.items.find({});", "[]"), + ), + assembledRule(shared = listOf("shared")), + ) + // A command the shared section shows is skipped, with its reason; the consumer still runs. + val command = shared(code("db.items.find({});")) + assertEquals(ScenarioExtractionState.READY, command.state, command.problems.toString()) + assertEquals( + listOf("SHARED_SECTION_COMMAND"), + command.pages.single().sharedSetupSkipped.map { it.reason }, + ) + assertNotNull(command.scenarios.single().program) + val unresolved = shared(code("db.items.insertOne({v:1});", "bash")) + assertEquals(ScenarioExtractionState.PARTIAL, unresolved.state) + assertTrue(unresolved.pages.single().unassigned.isNotEmpty()) + assertTrue(unresolved.scenarios.all { it.naming == null && it.program == null }) val missing = extract( root(standalone("Read Items", "read", "db.items.find({});", "[]")), @@ -1244,27 +1247,311 @@ class ScenarioExtractionTest { } @Test - fun ambiguousCommandsAndPrintedSamplesRemainOwnedWithoutExecutablePlans() { - val sources = - listOf( - listOf("{v:1}", "db.items.find({});", "[{v:1}]"), - listOf("db.items.find({});", "db.items.find({v:1});", "[]"), - listOf("db.items.insertOne({v:1}); db.items.find({});", "[]"), - listOf("db.items.find({});", "const n=1;", "[]"), + fun splittingASectionKeepsEachActionIndependentAndCharged() { + // Setup beside an action in one block is skipped rather than read as the action. + val mixed = + extract( + root( + standalone( + "Read Items", + "read", + "db.items.insertOne({v:1}); db.items.find({});", + "[{v:1}]", + ) + ), + assembledRule(), + ) + .scenarios + .single() + assertNull(mixed.program) + assertEquals( + listOf("MIXED_SECTION_ROLES", "SAMPLE_DOCUMENT"), + mixed.skipped.map { it.reason }, + ) + // Earlier actions don't count toward a later one's program limits. + val finds = (1..70).map { "db.items.find({v:$it});" }.toTypedArray() + val many = extract(root(standalone("Read Items", "read", *finds)), assembledRule()) + assertEquals(70, many.scenarios.count { it.program?.state == ShellLiteralState.NORMALIZED }) + // Each scenario a section splits into is charged against the group budget. + val (bundle, document) = + fixture( + root( + standalone("Read Items", "read", "db.items.find({});", "db.items.find({v:1});") + ) ) - for (blocks in sources) { - val report = - extract( - root(standalone("Read Items", "read", *blocks.toTypedArray())), + assertThrows(IllegalArgumentException::class.java) { + ScenarioExtraction.extract( + bundle, + document, + plan(assembledRule()), + ScenarioExtractionLimits(maximumGroups = 1), + ) + } + // So is the shared setup each of them repeats: 26 + 18 + 21 selected, plus 26 twice. + val seed = "db.items.insertOne({v:1});" + val (sharedBundle, sharedDocument) = + fixture( + root( + standalone("Shared", "shared", seed), + standalone("Read Items", "read", "db.items.find({});", "db.items.find({v:1});"), + ) + ) + fun charged(budget: Int) = + ScenarioExtraction.extract( + sharedBundle, + sharedDocument, + plan(assembledRule(shared = listOf("shared"))), + ScenarioExtractionLimits(maximumCodeCharacters = budget), + ) + 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 = + extract( + root( + standalone( + "Update Items", + "update", + "db.items.insertOne({v:1});", + "db.items.updateOne({}, {${'$'}set: {v: 2}});", + "db.items.find({});", + "[{v:2}]", + ) + ), assembledRule(), ) - assertEquals(ScenarioExtractionState.READY, report.state, report.problems.toString()) - val scenario = report.scenarios.single() - assertNull(scenario.program) - assertNotNull(scenario.normalizationProblem) - assertNotNull(scenario.naming) - assertEquals(blocks, scenario.blocks.map { it.source }) + .scenarios + val read = reads.single { it.blocks.any { b -> b.source == "db.items.find({});" } } + assertEquals("AFTER_EARLIER_WRITE", read.normalizationProblem) + assertNull(read.program) + } + + @Test + fun seedsFollowTheSetupEachScenarioRuns() { + fun extracted(vararg nodes: DocumentNode, shared: List = emptyList()) = + extract(root(*nodes), assembledRule(shared = shared)) + fun seeds(scenario: ExtractedScenario) = + scenario.blocks.filter { it.format == ProgramFormat.LEGACY_DOCUMENTS } + + // Shared declarations don't insert, so the section's sample still seeds. + val declared = + extracted( + standalone("Shared", "shared", "const n=1;"), + standalone("Read Items", "read", "{v:1}", "db.items.find({});", "[{v:1}]"), + shared = listOf("shared"), + ) + .scenarios + .single() + assertEquals("items", seeds(declared).single().namespace!!.collection) + assertEquals(ShellLiteralState.NORMALIZED, declared.program!!.state) + // An insert after an action is another scenario's setup, not this one's. + val first = + extracted( + standalone( + "Read Items", + "read", + "{v:1}", + "db.items.find({});", + "db.items.insertOne({v:2});", + "db.items.find({v:2});", + ) + ) + .scenarios + .single { it.blocks.any { b -> b.source == "db.items.find({});" } } + assertEquals(1, seeds(first).size) + // A shared sample beside a section's own insert only illustrates. + val inserted = + extracted( + standalone("Shared", "shared", "{v:9}"), + standalone( + "Read Items", + "read", + "db.items.insertOne({v:1});", + "db.items.find({});", + ), + shared = listOf("shared"), + ) + .scenarios + .single() + assertTrue(seeds(inserted).isEmpty()) + assertEquals(listOf("SAMPLE_DOCUMENT"), inserted.skipped.map { it.reason }) + // A shared sample seeds a native input/output group's collection too. + val native = + extracted( + standalone("Shared", "shared", "{v:1}"), + section("Match Values", "values", io()), + shared = listOf("shared"), + ) + .scenarios + .single() + assertEquals("items", seeds(native).single().namespace!!.collection) + assertEquals(ShellLiteralState.NORMALIZED, native.program!!.state) + } + + @Test + fun languagesAndTemplatesAreReadFromTheCodeNotItsPosition() { + fun scenarios(vararg blocks: DocumentNode) = + extract(root(section("Read Items", "read", *blocks)), assembledRule()).scenarios + // The action's own language counts, even with no result after it. + assertEquals( + ScenarioVariant.UNRESOLVED, + scenarios(code("db.items.insertOne({v:1});"), code("db.items.find({});", "pseudocode")) + .single() + .variant, + ) + // A JSON sample before the action doesn't decide the language. + assertEquals( + ScenarioVariant.REFERENCE, + scenarios(code("{\"v\": 1}", "json"), code("db.items.find({});")).single().variant, + ) + // Angle brackets inside a string are a value, not a template. + val quoted = scenarios(code("db.items.find({v:''});")).single() + assertEquals(listOf(ProgramRole.ACTION), quoted.blocks.map { it.role }) + assertTrue(quoted.skipped.isEmpty()) + // Sibling selections are separate examples. + fun selected(tab: String) = + node( + "directive", + name = "selected-content", + attributes = mapOf("selections" to "{\"language\":\"$tab\"}"), + children = listOf(code("db.items.find({});")), + ) + assertEquals( + setOf(ScenarioVariant.REFERENCE, ScenarioVariant.FOREIGN), + scenarios(selected("shell"), selected("nodejs")).map { it.variant }.toSet(), + ) + // Branches that show the same code are still separate examples. + val same = + extract( + root(section("Read Items", "read", selected("nodejs"), selected("csharp"))), + assembledRule(), + ) + assertEquals(2, same.scenarios.map { it.id }.distinct().size) + assertTrue(same.problems.none { it.code == "AMBIGUOUS_GROUP" }) + // A displayed operator expression is neither data nor a result. + val shown = + scenarios( + code("// Specify i\n{ ${'$'}regexMatch: { input: 'a', regex: /a/i } }"), + code("db.items.find({});"), + ) + .single() + assertEquals(listOf("OPERATOR_EXPRESSION"), shown.skipped.map { it.reason }) + // A caption comment above printed results doesn't hide them. + val captioned = + scenarios(code("db.items.find({});"), code("// The result\n[{v:1}]")).single() + assertEquals( + listOf(ProgramRole.ACTION, ProgramRole.EXPECTED), + captioned.blocks.map { it.role }, + ) + // A selection that names nothing stays unresolved. + for (selections in listOf("{}", "[]")) { + val empty = + node( + "directive", + name = "selected-content", + attributes = mapOf("selections" to selections), + children = listOf(code("db.items.find({});")), + ) + assertEquals(ScenarioVariant.UNRESOLVED, scenarios(empty).single().variant) } + // A shared section that shows code only in other languages shares nothing. + val foreignOnly = + extract( + root( + section("Shared", "shared", selected("nodejs"), selected("csharp")), + standalone("Read Items", "read", "db.items.find({});", "[]"), + ), + assembledRule(shared = listOf("shared")), + ) + assertTrue(foreignOnly.problems.none { it.code == "MISSING_OR_AMBIGUOUS_SHARED_SETUP" }) + assertNotNull( + foreignOnly.scenarios.single { it.variant == ScenarioVariant.REFERENCE }.program + ) + } + + @Test + fun sectionAssemblyReadsHowPagesPrintAndLabelTheirCode() { + fun scenario(vararg blocks: DocumentNode, policy: SectionAssemblyPolicy? = null) = + extract( + root(section("Read Items", "read", *blocks)), + policy?.let { rule().copy(sectionAssembly = it) } ?: assembledRule(), + ) + .scenarios + .single() + // A seed may use the printed constructors the extended JSON reader rejects. + val decimal = scenario(code("{ v: Decimal128(\"1.5\") }"), code("db.items.find({});")) + assertEquals(ShellLiteralState.NORMALIZED, decimal.program!!.state) + // A truncated listing leaves the example serialization-only. + val truncated = scenario(code("db.items.find({});"), code("[ {v:1} ]\n...")) + assertEquals(ShellLiteralState.NORMALIZED, truncated.program!!.state) + assertEquals(listOf(ProgramRole.ACTION), truncated.blocks.map { it.role }) + assertEquals(listOf("UNREADABLE_RESULT"), truncated.skipped.map { it.reason }) + // Code the page leaves unhighlighted takes the reviewed language, when there is one. + val unlabeled = code("db.items.find({});", "none") + assertEquals(ScenarioVariant.UNRESOLVED, scenario(unlabeled).variant) + val reviewed = + SectionAssemblyPolicy( + SectionLayout.COMMANDS_THEN_RESULT, + unlabeledLanguage = "javascript", + ) + assertEquals(ScenarioVariant.REFERENCE, scenario(unlabeled, policy = reviewed).variant) + // A composable tutorial's selected content is classified like a tab. + fun selected(tab: String) = + node( + "directive", + name = "selected-content", + attributes = mapOf("selections" to "{\"language\":\"$tab\"}"), + children = listOf(code("db.items.find({});")), + ) + assertEquals(ScenarioVariant.REFERENCE, scenario(selected("shell")).variant) + assertEquals(ScenarioVariant.FOREIGN, scenario(selected("nodejs")).variant) + } + + @Test + fun sectionBlocksTakeTheirRolesFromTheShellGrammar() { + fun scenarios(vararg blocks: String) = + extract(root(standalone("Read Items", "read", *blocks)), assembledRule()).scenarios + fun roles(scenario: ExtractedScenario) = scenario.blocks.map { it.role } + val read = listOf(ProgramRole.SETUP, ProgramRole.ACTION, ProgramRole.EXPECTED) + + // A sample document seeds the collection where nothing inserts. + val seeded = scenarios("{v:1}", "db.items.find({});", "[{v:1}]").single() + assertEquals(ShellLiteralState.NORMALIZED, seeded.program!!.state) + assertEquals(read, roles(seeded)) + assertEquals(ProgramFormat.LEGACY_DOCUMENTS, seeded.blocks.first().format) + assertEquals("items", seeded.blocks.first().namespace!!.collection) + // Where the section inserts, a sample document only illustrates. + val inserted = + scenarios("db.items.insertOne({v:1});", "{v:2}", "db.items.find({});", "[{v:1}]") + .single() + assertEquals(read, roles(inserted)) + assertEquals(listOf("SAMPLE_DOCUMENT"), inserted.skipped.map { it.reason }) + // Each action is its own scenario, with the result printed right after it, if any. + val two = scenarios("db.items.find({});", "db.items.find({v:1});", "[]") + assertEquals( + setOf(listOf(ProgramRole.ACTION), listOf(ProgramRole.ACTION, ProgramRole.EXPECTED)), + two.map(::roles).toSet(), + ) + // A syntax template is skipped, and so is setup no action follows. + val template = + scenarios("{ ${'$'}match: { } }", "db.items.find({});", "const n=1;").single() + assertEquals(listOf(ProgramRole.ACTION), roles(template)) + assertEquals( + listOf("SYNTAX_TEMPLATE", "TRAILING_SETUP"), + template.skipped.map { it.reason }, + ) + // What a page prints after an update is a later read's result, kept for that read. + val update = + scenarios( + "db.items.insertOne({v:1});", + "db.items.updateOne({}, {${'$'}set: {v: 2}});", + "[{v:2}]", + ) + .single() + assertEquals(listOf(ProgramRole.SETUP, ProgramRole.ACTION), roles(update)) + assertEquals(listOf("UPDATE_RESULT"), update.skipped.map { it.reason }) + // A section without a command has nothing to run. + assertEquals("MISSING_COMMAND_OR_RESULT", scenarios("{v:1}").single().normalizationProblem) } @Test @@ -1413,8 +1700,11 @@ class ScenarioExtractionTest { root(first, second, consumer), assembledRule(shared = listOf("a-second", "z-first")), ) - assertEquals(ScenarioExtractionState.PARTIAL, reversed.state) - assertTrue(reversed.problems.any { it.code == "UNSUPPORTED_SHARED_SETUP" }) + // In the other order the insert reads a binding not yet declared, so it isn't setup. + assertEquals( + listOf("db.items.insertOne({v:n});" to "UNSUPPORTED_SOURCE"), + reversed.pages.single().sharedSetupSkipped.map { it.code.source to it.reason }, + ) } @Test diff --git a/design/operator-audits-design.md b/design/operator-audits-design.md index f27fbf7e9a4..c981bbcc3cf 100644 --- a/design/operator-audits-design.md +++ b/design/operator-audits-design.md @@ -185,7 +185,7 @@ methods or fixture directories disagree with it. | `naming` | Descriptive example names, and the name registry reconciler. | Names: yes. Reconciler: not yet. | | `rst`, `model` | The legacy line-based RST extractor. | Yes, until the structured parser replaces it | | `sources`, `documents`, `discovery` | Pinned Git source bundles, the Snooty parser adapter, capability discovery. | Yes, weekly | -| `scenarios` | Structured scenario extraction. | Not yet | +| `scenarios` | Structured scenario extraction: native input/output groups, and section assembly, which gives each block a role by what the shell grammar makes of it. | Not yet; it replaces `rst` next | | `coverage` | Capability catalog and plan contracts, coverage comparison, and `AuditJson`, the strict JSON codec every package uses. | Yes, weekly | Each package with a command has a `*Main.kt` entry point, run through the exec plugin with diff --git a/design/operator-audits-progress.md b/design/operator-audits-progress.md index cae0abb1f4a..92b630ff1a4 100644 --- a/design/operator-audits-progress.md +++ b/design/operator-audits-progress.md @@ -2761,3 +2761,8 @@ no product-documentation changes. Legacy operator AsciiDoc tables are intentiona - Per the user: the Atlas Search and hybrid-search stages, the diagnostic and administration stages, and the Queryable Encryption operators are excluded with their reasons (32 exclusions with facets); 14 missing APIs remain, all new server expressions. +- Parser retirement, step 1 (section roles): section assembly classifies each block by the shell + grammar instead of accepting one trailing command and result. Sample documents seed where nothing + inserts, each action is its own scenario, and skipped source is recorded with a reason. Over all + 297 operator pages (docs e4b0c153) with a draft plan, 605 scenarios normalize, against 582 + examples in the legacy inventory; 508 of those match by title. diff --git a/design/operator-audits-section-assembly.md b/design/operator-audits-section-assembly.md index b588812469b..d3db15a5aa7 100644 --- a/design/operator-audits-section-assembly.md +++ b/design/operator-audits-section-assembly.md @@ -15,23 +15,55 @@ parents keep their explicit ownership; their code is never duplicated into a sta All source text, report-local locators, attributes, ancestors, snippet receipts and physical origins remain visible. Locators and block indexes do not establish persistent identity. -`COMMANDS_THEN_RESULT` declares a single trailing published result. The preceding blocks must -parse together with the existing closed shell processor. The processor's internal inspection +`COMMANDS_THEN_RESULT` classifies each block a section owns by what the closed shell processor +makes of it, read together with the setup accepted before it. The processor's internal inspection mode permits declaration-only input and returns operation classifications, not an executable -artifact. The public normalizer still rejects programs with no action. No JavaScript is evaluated, -no fake query is appended, and no source is rewritten. - -Under this contract, insert/index operations and pure declarations are setup. Exactly one -find/aggregate/update command must follow setup, in its own final input block. Mixed setup/action -blocks, multiple actions, unsupported input and missing command/result pairs retain their owned -source and a normalization reason. The final result uses the explicit `SHELL_RESULTS` grammar; -a malformed or unrepresentable published result remains unsupported in the program report. -No last-action heuristic assigns an ambiguous expectation. +artifact. No JavaScript is evaluated, no fake query is appended, and no source is rewritten. + +| Block | Role | +|---|---| +| Inserts, index builds and pure declarations | Setup for the actions after it | +| One find, aggregate or update command | An action: its own scenario | +| A document or document list directly after a read action | That action's published result | +| A document or document list where nothing the scenario runs inserts data | A seed for the next action's collection (`LEGACY_DOCUMENTS` setup in that namespace) | +| Anything else | Skipped, with a reason | + +Skipped source stays visible on its scenario (`skipped`) or, for shared setup, on the page +(`sharedSetupSkipped`). The reasons are: + +- `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; +- `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; +- `MIXED_SECTION_ROLES`: a block holding setup and an action together, which one role can't describe; +- `TRAILING_SETUP`: setup or a seed no action follows; +- `UNSUPPORTED_SOURCE`: anything else the processor can't read, such as a binding used before it is + 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 +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 +with no action reports `MISSING_COMMAND_OR_RESULT`. The final result uses the explicit +`SHELL_RESULTS` grammar; JSON-labeled and unlabeled results are accepted, since that is how pages +print them. Code in another programming language never reads as a document, even when it opens with +a bracket (a C# `[BsonIgnoreExtraElements]`). + +These rules replaced a stricter contract that accepted only one trailing command and one trailing +result per section and refused to seed from displayed documents. That contract left most operator +pages without a runnable scenario; the rules above recover them while recording every block they +leave out. `SOURCE_ONLY` owns source for descriptive naming while leaving local roles unassigned and the program absent. It is useful for pages that display a sample document, an expression or a dataset -without defining executable setup. A displayed sample never becomes an insert with an inferred -namespace or input BSON type. Source-only and unsupported semantic states remain visible separately +without defining executable setup. Under `SOURCE_ONLY` a displayed sample never becomes an insert. Source-only and unsupported semantic states remain visible separately from source grouping completeness. `READY` means complete source grouping for naming, not execution, serialization parity, setup sufficiency or API coverage. @@ -43,7 +75,10 @@ example selection; it does not implicitly select that section's descendants. Set not be excluded. Missing/duplicate ownership, unresolved languages/selectors and non-setup commands block promotion and complete naming. Selected raw source remains visible when validation fails. -The combined shared source must parse as a closed declaration/insert/index program. Verified setup +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 +language shares its reference branch, and shares nothing when only other languages show code. +The shared source contributes only its setup blocks, classified as above; its commands, templates and unreadable blocks are skipped with their reasons. Where it inserts nothing, its documents seed the collection of each action that consumes them. Verified setup is retained in the page's `sharedSetup` field even if every consumer disappears. It is prepended, in the declared order, to standalone and native IO reference candidates. The module never borrows state from the first sibling or treats section ancestry as proof of a shared dependency. @@ -84,7 +119,7 @@ parse. It verifies that the three `$abs` blocks acquire setup/action/expected ro with the same source digests and physical origins as the preceding reviewed raw-source experiment. Its program retains two commands and four published rows. The two `$acos` scenario tabs retain three raw blocks each, obtain authored descriptive names, and remain explicitly source-only: -those docs show a sample triangle document without inserting it. +those docs show a sample triangle document without inserting it. (The probe records the earlier, stricter contract; under the current rules that sample seeds the `trigonometry` collection.) The probe repeats extraction byte-for-byte, proposes three names in synthetic fixture destinations, and verifies source/runtime inputs before and after replay. The earlier native IO probe verifies