From 96acaaff5340d69b823d09f3c3c82201139e7f94 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 1/3] Preserve full-text policy metadata in info (#313) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> (cherry picked from commit 9f9c18d1b562b55b4e296e25b7b98bdabcea31f2) --- .../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 8a55b8fa..61879bcb 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 AnsiConsole.MarkupLine(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 7801721c..0abefd5b 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -1886,6 +1886,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. From 607c3fcccbd534c5135dcd96f5e7bfd6410f084f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mike=20Kr=C3=BCger?= Date: Mon, 30 Nov 2026 14:21:14 +0100 Subject: [PATCH 2/3] Address test findings in PR #315 (cherry picked from commit cf1d0571975df5d9ae8ba60848065fcd7a7f0a86) --- CosmosDBShell.Tests/CommandTests/BulkCommandTests.cs | 2 +- .../CommandTests/FullTextPolicyReadbackTests.cs | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/CosmosDBShell.Tests/CommandTests/BulkCommandTests.cs b/CosmosDBShell.Tests/CommandTests/BulkCommandTests.cs index 2f06e108..dc5d37c4 100644 --- a/CosmosDBShell.Tests/CommandTests/BulkCommandTests.cs +++ b/CosmosDBShell.Tests/CommandTests/BulkCommandTests.cs @@ -999,7 +999,7 @@ public async Task JournalFailureDuringSettlementStillDrainsEveryStartedWrite() var actual = await Assert.ThrowsAsync(async () => await run.WaitAsync(timeout.Token)); Assert.Same(expected, actual); - Assert.Equal([0L, 1L], settled); + Assert.Equal([0L, 1L], settled.Order()); Assert.Equal(2, summary.Succeeded); } diff --git a/CosmosDBShell.Tests/CommandTests/FullTextPolicyReadbackTests.cs b/CosmosDBShell.Tests/CommandTests/FullTextPolicyReadbackTests.cs index 62963159..a96f93b3 100644 --- a/CosmosDBShell.Tests/CommandTests/FullTextPolicyReadbackTests.cs +++ b/CosmosDBShell.Tests/CommandTests/FullTextPolicyReadbackTests.cs @@ -136,12 +136,12 @@ private static ConnectedState CreateState(bool arm, string? policy, int? failure metadata.Resource.Returns(JsonConvert.DeserializeObject(resourceJson)!); metadata.Headers.Returns(new Headers()); metadata.StatusCode.Returns(HttpStatusCode.OK); - if (!arm && failureStatus.HasValue) + if (!arm && failureStatus is int dataPlaneStatusCode) { container.ReadContainerAsync(Arg.Any(), Arg.Any()) .Returns( _ => Task.FromResult(metadata), - _ => Task.FromException(new CosmosException("metadata unavailable", (HttpStatusCode)failureStatus.Value, 0, "test", 0))); + _ => Task.FromException(new CosmosException("metadata unavailable", (HttpStatusCode)dataPlaneStatusCode, 0, "test", 0))); } else { @@ -167,12 +167,12 @@ private static ConnectedState CreateState(bool arm, string? policy, int? failure armContainer.Data.Returns(CosmosArmResourceProvider.ReadArmModel( """{"properties":{"resource":""" + resourceJson + "}}")); NullableResponse containerResponse = Response.FromValue(armContainer, Substitute.For()); - if (failureStatus.HasValue) + if (failureStatus is int armStatusCode) { containers.GetIfExistsAsync("Items", Arg.Any()) .Returns( _ => Task.FromResult(containerResponse), - _ => Task.FromException>(new RequestFailedException(failureStatus.Value, "metadata unavailable"))); + _ => Task.FromException>(new RequestFailedException(armStatusCode, "metadata unavailable"))); } else { From a44fcfa70222da2097acdcce535fe04c208e88c3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mike=20Kr=C3=BCger?= Date: Tue, 1 Dec 2026 11:18:28 +0100 Subject: [PATCH 3/3] Consolidate full-text metadata in fullTextPolicy (#313) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../CommandTests/FullTextPolicyReadbackTests.cs | 10 +++++----- .../Azure.Data.Cosmos.Shell.Commands/InfoCommand.cs | 5 ++--- docs/commands.md | 10 ++++------ 3 files changed, 11 insertions(+), 14 deletions(-) diff --git a/CosmosDBShell.Tests/CommandTests/FullTextPolicyReadbackTests.cs b/CosmosDBShell.Tests/CommandTests/FullTextPolicyReadbackTests.cs index a96f93b3..628c908e 100644 --- a/CosmosDBShell.Tests/CommandTests/FullTextPolicyReadbackTests.cs +++ b/CosmosDBShell.Tests/CommandTests/FullTextPolicyReadbackTests.cs @@ -47,7 +47,7 @@ public class FullTextPolicyReadbackTests [Theory] [MemberData(nameof(PolicyCases))] - public async Task Info_PreservesCompletePolicyAndLegacyPathsAcrossBackends(bool arm, bool mcp, string? policy) + public async Task Info_PreservesCompletePolicyAcrossBackends(bool arm, bool mcp, string? policy) { using var shell = ShellInterpreter.CreateInstance(); shell.State = CreateState(arm, policy); @@ -70,14 +70,16 @@ public async Task Info_PreservesCompletePolicyAndLegacyPathsAcrossBackends(bool Assert.Equal(root.GetRawText(), envelope.RootElement.GetProperty("result").GetRawText()); } - var details = root.GetProperty("fullTextPolicyDetails"); + Assert.False(root.TryGetProperty("fullTextPolicyDetails", out _)); + var details = root.GetProperty("fullTextPolicy"); if (policy is null || policy == "null") { Assert.Equal(JsonValueKind.Null, details.ValueKind); - Assert.False(root.TryGetProperty("fullTextPolicy", out _)); return; } + Assert.Equal(JsonValueKind.Object, details.ValueKind); + Assert.Equal(2, details.EnumerateObject().Count()); using var expected = JsonDocument.Parse(policy); var expectedLanguage = expected.RootElement.TryGetProperty("defaultLanguage", out var language) ? language.GetString() @@ -96,8 +98,6 @@ public async Task Info_PreservesCompletePolicyAndLegacyPathsAcrossBackends(bool : null; Assert.Equal(expectedPathLanguage, paths[i].GetProperty("language").GetString()); } - - Assert.Equal(details.GetProperty("fullTextPaths").GetRawText(), root.GetProperty("fullTextPolicy").GetRawText()); } [Theory] diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/InfoCommand.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/InfoCommand.cs index 61879bcb..5eff2640 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/InfoCommand.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/InfoCommand.cs @@ -836,7 +836,7 @@ private async Task ShowContainerSettingsAsync(ShellInterpreter she AnsiConsole.MarkupLine(Theme.FormatSectionHeader(MessageService.GetString("command-settings-fulltext-title"))); } - mcpTable["fullTextPolicyDetails"] = null; + mcpTable["fullTextPolicy"] = null; if (view.FullTextPolicy is { } fullText) { Table? fullTextTable = null; @@ -869,8 +869,7 @@ private async Task ShowContainerSettingsAsync(ShellInterpreter she }); } - mcpTable["fullTextPolicy"] = mcpPaths; - mcpTable["fullTextPolicyDetails"] = new Dictionary + mcpTable["fullTextPolicy"] = new Dictionary { { "defaultLanguage", fullText.DefaultLanguage }, { "fullTextPaths", mcpPaths }, diff --git a/docs/commands.md b/docs/commands.md index 0abefd5b..c3171af8 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -1886,18 +1886,16 @@ 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 +Container JSON and MCP results include a `fullTextPolicy` object, 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 +An observed absent policy is represented by `fullTextPolicy: 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. +`fullTextPolicy` replaces the previous path-array shape. Consumers that iterated +over `fullTextPolicy` directly should now use `fullTextPolicy.fullTextPaths`. ### help