From 9f9c18d1b562b55b4e296e25b7b98bdabcea31f2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mike=20Kr=C3=BCger?= Date: Mon, 30 Nov 2026 13:03:09 +0100 Subject: [PATCH] Preserve full-text policy metadata in info (#313) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../FullTextPolicyReadbackTests.cs | 191 ++++++++++++++++++ .../InfoCommand.cs | 6 + .../ArmCosmosResourceOperations.cs | 10 +- docs/commands.md | 13 ++ 4 files changed, 219 insertions(+), 1 deletion(-) create mode 100644 CosmosDBShell.Tests/CommandTests/FullTextPolicyReadbackTests.cs diff --git a/CosmosDBShell.Tests/CommandTests/FullTextPolicyReadbackTests.cs b/CosmosDBShell.Tests/CommandTests/FullTextPolicyReadbackTests.cs new file mode 100644 index 00000000..62963159 --- /dev/null +++ b/CosmosDBShell.Tests/CommandTests/FullTextPolicyReadbackTests.cs @@ -0,0 +1,191 @@ +// ------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +// ------------------------------------------------------------ + +namespace CosmosShell.Tests.CommandTests; + +using System.Net; +using System.Text.Json; +using Azure; +using Azure.Core; +using Azure.Data.Cosmos.Shell.Commands; +using Azure.Data.Cosmos.Shell.Core; +using Azure.Data.Cosmos.Shell.Mcp; +using Azure.Data.Cosmos.Shell.Parser; +using Azure.Data.Cosmos.Shell.States; +using Azure.ResourceManager; +using Azure.ResourceManager.CosmosDB; +using Microsoft.Azure.Cosmos; +using ModelContextProtocol.Protocol; +using Newtonsoft.Json; +using NSubstitute; + +public class FullTextPolicyReadbackTests +{ + public static IEnumerable PolicyCases() + { + string?[] policies = + [ + """{"defaultLanguage":"en-US","fullTextPaths":[{"path":"/description","language":"en-US"},{"path":"/title","language":"de-DE"},{"path":"/notes"}]}""", + """{"defaultLanguage":"fr-FR","fullTextPaths":[]}""", + """{"defaultLanguage":"en-US"}""", + """{"fullTextPaths":[{"path":"/description","language":"en-US"}]}""", + "null", + null, + ]; + foreach (var arm in new[] { false, true }) + { + foreach (var mcp in new[] { false, true }) + { + foreach (var policy in policies) + { + yield return [arm, mcp, policy]; + } + } + } + } + + [Theory] + [MemberData(nameof(PolicyCases))] + public async Task Info_PreservesCompletePolicyAndLegacyPathsAcrossBackends(bool arm, bool mcp, string? policy) + { + using var shell = ShellInterpreter.CreateInstance(); + shell.State = CreateState(arm, policy); + shell.IsMcpInvocation = mcp; + var command = new InfoCommand + { + Database = "db", + Container = "Items", + Format = "json", + }; + + var result = await command.ExecuteAsync(shell, new CommandState(), "info", TestContext.Current.CancellationToken); + + var root = Assert.IsType(result.Result).Value; + if (mcp) + { + var response = McpResponseFactory.CreateSuccess(result, shell.State); + Assert.False(response.IsError); + using var envelope = JsonDocument.Parse(Assert.IsType(Assert.Single(response.Content)).Text); + Assert.Equal(root.GetRawText(), envelope.RootElement.GetProperty("result").GetRawText()); + } + + var details = root.GetProperty("fullTextPolicyDetails"); + if (policy is null || policy == "null") + { + Assert.Equal(JsonValueKind.Null, details.ValueKind); + Assert.False(root.TryGetProperty("fullTextPolicy", out _)); + return; + } + + using var expected = JsonDocument.Parse(policy); + var expectedLanguage = expected.RootElement.TryGetProperty("defaultLanguage", out var language) + ? language.GetString() + : null; + Assert.Equal(expectedLanguage, details.GetProperty("defaultLanguage").GetString()); + var expectedPaths = expected.RootElement.TryGetProperty("fullTextPaths", out var expectedPathArray) + ? expectedPathArray.EnumerateArray().ToArray() + : []; + var paths = details.GetProperty("fullTextPaths").EnumerateArray().ToArray(); + Assert.Equal(expectedPaths.Length, paths.Length); + for (var i = 0; i < paths.Length; i++) + { + Assert.Equal(expectedPaths[i].GetProperty("path").GetString(), paths[i].GetProperty("path").GetString()); + var expectedPathLanguage = expectedPaths[i].TryGetProperty("language", out var pathLanguage) + ? pathLanguage.GetString() + : null; + Assert.Equal(expectedPathLanguage, paths[i].GetProperty("language").GetString()); + } + + Assert.Equal(details.GetProperty("fullTextPaths").GetRawText(), root.GetProperty("fullTextPolicy").GetRawText()); + } + + [Theory] + [InlineData(false, 403)] + [InlineData(true, 403)] + [InlineData(false, 501)] + [InlineData(true, 501)] + public async Task Info_MetadataReadFailureIsNotReportedAsAbsentPolicy(bool arm, int status) + { + using var shell = ShellInterpreter.CreateInstance(); + shell.State = CreateState(arm, null, status); + var command = new InfoCommand { Database = "db", Container = "Items", Format = "json" }; + var state = new CommandState(); + + var error = await Assert.ThrowsAsync( + () => command.ExecuteAsync(shell, state, "info", TestContext.Current.CancellationToken)); + + Assert.Contains("metadata unavailable", error.Message, StringComparison.Ordinal); + Assert.Null(state.Result); + } + + private static ConnectedState CreateState(bool arm, string? policy, int? failureStatus = null) + { + var resourceJson = $$""" + {"id":"Items","partitionKey":{"paths":["/id"],"kind":"Hash"}{{(policy is null ? string.Empty : ",\"fullTextPolicy\":" + policy)}}} + """; + var client = Substitute.For(); + var database = Substitute.For(); + var container = Substitute.For(); + client.GetDatabase("db").Returns(database); + database.GetContainer("Items").Returns(container); + var databaseResponse = Substitute.For(); + databaseResponse.StatusCode.Returns(HttpStatusCode.OK); + database.ReadAsync(Arg.Any(), Arg.Any()).Returns(databaseResponse); + var metadata = Substitute.For(); + metadata.Resource.Returns(JsonConvert.DeserializeObject(resourceJson)!); + metadata.Headers.Returns(new Headers()); + metadata.StatusCode.Returns(HttpStatusCode.OK); + if (!arm && failureStatus.HasValue) + { + container.ReadContainerAsync(Arg.Any(), Arg.Any()) + .Returns( + _ => Task.FromResult(metadata), + _ => Task.FromException(new CosmosException("metadata unavailable", (HttpStatusCode)failureStatus.Value, 0, "test", 0))); + } + else + { + container.ReadContainerAsync(Arg.Any(), Arg.Any()).Returns(metadata); + } + + container.ReadThroughputAsync(Arg.Any(), Arg.Any()) + .Returns>(_ => throw new CosmosException("not configured", HttpStatusCode.NotFound, 0, "test", 0)); + if (!arm) + { + return new ConnectedState(client); + } + + var account = Substitute.For(); + var databases = Substitute.For(); + var armDatabase = Substitute.For(); + var containers = Substitute.For(); + var armContainer = Substitute.For(); + account.GetCosmosDBSqlDatabases().Returns(databases); + armDatabase.GetCosmosDBSqlContainers().Returns(containers); + databases.GetIfExistsAsync("db", Arg.Any()) + .Returns(Task.FromResult>(Response.FromValue(armDatabase, Substitute.For()))); + armContainer.Data.Returns(CosmosArmResourceProvider.ReadArmModel( + """{"properties":{"resource":""" + resourceJson + "}}")); + NullableResponse containerResponse = Response.FromValue(armContainer, Substitute.For()); + if (failureStatus.HasValue) + { + containers.GetIfExistsAsync("Items", Arg.Any()) + .Returns( + _ => Task.FromResult(containerResponse), + _ => Task.FromException>(new RequestFailedException(failureStatus.Value, "metadata unavailable"))); + } + else + { + containers.GetIfExistsAsync("Items", Arg.Any()) + .Returns(Task.FromResult(containerResponse)); + } + + var throughput = Substitute.For(); + armContainer.GetCosmosDBSqlContainerThroughputSetting().Returns(throughput); + throughput.GetAsync(Arg.Any()) + .Returns>>(_ => throw new RequestFailedException(404, "not configured")); + var id = new ResourceIdentifier("/subscriptions/s/resourceGroups/rg/providers/Microsoft.DocumentDB/databaseAccounts/a"); + var context = new ArmCosmosContext(Substitute.For(), id, "s", "rg", "a", new Uri("https://a.documents.azure.com"), account); + return new ConnectedState(client, context); + } +} diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/InfoCommand.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/InfoCommand.cs index 7493feab..d65d43b8 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/InfoCommand.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/InfoCommand.cs @@ -836,6 +836,7 @@ private async Task ShowContainerSettingsAsync(ShellInterpreter she ShellInterpreter.Instance.Output.MarkupLine(ShellMessageKind.Result, Theme.FormatSectionHeader(MessageService.GetString("command-settings-fulltext-title"))); } + mcpTable["fullTextPolicyDetails"] = null; if (view.FullTextPolicy is { } fullText) { Table? fullTextTable = null; @@ -869,6 +870,11 @@ private async Task ShowContainerSettingsAsync(ShellInterpreter she } mcpTable["fullTextPolicy"] = mcpPaths; + mcpTable["fullTextPolicyDetails"] = new Dictionary + { + { "defaultLanguage", fullText.DefaultLanguage }, + { "fullTextPaths", mcpPaths }, + }; if (fullTextTable is not null) { fullTextTable.HideHeaders(); diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ArmCosmosResourceOperations.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ArmCosmosResourceOperations.cs index 988125cf..51310142 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ArmCosmosResourceOperations.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ArmCosmosResourceOperations.cs @@ -134,6 +134,14 @@ public async Task GetContainerSettingsAsync(string databa } var armResource = resource.Data.Resource; + ContainerFullTextPolicyView? fullTextView = null; + if (armResource.FullTextPolicy is { } fullTextPolicy) + { + fullTextView = new ContainerFullTextPolicyView( + fullTextPolicy.DefaultLanguage, + fullTextPolicy.FullTextPaths.Select(p => new ContainerFullTextPathView(p.Path, p.Language)).ToArray()); + } + ContainerIndexingPolicyView? indexingView = null; if (armResource.IndexingPolicy is { } indexingPolicy) { @@ -156,7 +164,7 @@ public async Task GetContainerSettingsAsync(string databa throughputAvailability, throughputError, GeospatialType: null, - FullTextPolicy: null, + FullTextPolicy: fullTextView, IndexingPolicy: indexingView); } diff --git a/docs/commands.md b/docs/commands.md index 7c10ac44..1d045dd5 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -1890,6 +1890,19 @@ Manager control-plane operations do not consume Cosmos DB request units. When `$sessionRequestChargeWarningThreshold` is positive, `session.requestChargeWarningThreshold` reports the configured warning threshold. This command is read-only. +Container JSON and MCP results include `fullTextPolicyDetails`, containing the +observed `defaultLanguage` and `fullTextPaths` entries (`path` and `language`). +This is available on both data-plane and Azure Resource Manager connections. +An observed absent policy is represented by `fullTextPolicyDetails: null`; a +failed or unsupported container-metadata read returns an error, not an absent +policy. A configured policy with no paths still returns an object with an empty +`fullTextPaths` array. + +For compatibility, `fullTextPolicy` retains its existing path-array shape and +is omitted when no policy is present. Consumers needing the complete policy +should use the additive `fullTextPolicyDetails` field; consumers requiring an +exact set of JSON fields must accept this new field. + ### help Show help for commands.