Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
180 changes: 180 additions & 0 deletions CosmosDBShell.Tests/CommandTests/ThroughputReplacementStatusTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
// ------------------------------------------------------------
// 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.States;
using Azure.ResourceManager;
using Azure.ResourceManager.CosmosDB;
using Azure.ResourceManager.CosmosDB.Models;
using Microsoft.Azure.Cosmos;
using ModelContextProtocol.Protocol;
using NSubstitute;
using ModelReaderWriter = System.ClientModel.Primitives.ModelReaderWriter;

public class ThroughputReplacementStatusTests
{
[Theory]
[InlineData(false, "show", "True", true)]
[InlineData(true, "show", "false", false)]
[InlineData(false, "show", null, null)]
[InlineData(false, "show", "", null)]
[InlineData(true, "set", "true", true)]
[InlineData(false, "set", "False", false)]
[InlineData(true, "set", null, null)]
[InlineData(true, "set", "unknown", null)]
[InlineData(true, "dry-run", "true", true)]
public async Task DataPlane_ReportsObservedStatus(bool isContainer, string operation, string? pending, bool? expected)
{
var client = Substitute.For<CosmosClient>();
var database = Substitute.For<Database>();
var container = Substitute.For<Container>();
client.GetDatabase("db").Returns(database);
database.GetContainer("items").Returns(container);
var databaseRead = Substitute.For<DatabaseResponse>();
var containerRead = Substitute.For<ContainerResponse>();
databaseRead.StatusCode.Returns(HttpStatusCode.OK);
containerRead.StatusCode.Returns(HttpStatusCode.OK);
database.ReadAsync(cancellationToken: Arg.Any<CancellationToken>()).Returns(databaseRead);
container.ReadContainerAsync(cancellationToken: Arg.Any<CancellationToken>()).Returns(containerRead);

var read = CreateDataPlaneResponse(operation == "set" ? (expected == true ? "false" : "true") : pending);
var write = CreateDataPlaneResponse(pending);
database.ReadThroughputAsync(Arg.Any<RequestOptions>(), Arg.Any<CancellationToken>()).Returns(read);
container.ReadThroughputAsync(Arg.Any<RequestOptions>(), Arg.Any<CancellationToken>()).Returns(read);
database.ReplaceThroughputAsync(Arg.Any<ThroughputProperties>(), cancellationToken: Arg.Any<CancellationToken>()).Returns(write);
container.ReplaceThroughputAsync(Arg.Any<ThroughputProperties>(), cancellationToken: Arg.Any<CancellationToken>()).Returns(write);

await AssertOutputAsync(new ConnectedState(client), isContainer, operation, expected);
}

[Theory]
[InlineData(false, "show", "True", true)]
[InlineData(true, "show", "false", false)]
[InlineData(false, "show", null, null)]
[InlineData(true, "show", "unknown", null)]
[InlineData(true, "set", "true", true)]
[InlineData(false, "set", "False", false)]
[InlineData(true, "set", null, null)]
public async Task Arm_ReportsObservedStatus(bool isContainer, string operation, string? pending, bool? expected)
{
var account = Substitute.For<CosmosDBAccountResource>();
account.Data.Returns(ModelReaderWriter.Read<CosmosDBAccountData>(BinaryData.FromString("""{"location":"westus"}"""))!);
var databases = Substitute.For<CosmosDBSqlDatabaseCollection>();
var database = Substitute.For<CosmosDBSqlDatabaseResource>();
account.GetCosmosDBSqlDatabases().Returns(databases);
databases.GetIfExistsAsync("db", Arg.Any<CancellationToken>())
.Returns((NullableResponse<CosmosDBSqlDatabaseResource>)Response.FromValue(database, Substitute.For<Response>()));
var containers = Substitute.For<CosmosDBSqlContainerCollection>();
var container = Substitute.For<CosmosDBSqlContainerResource>();
database.GetCosmosDBSqlContainers().Returns(containers);
containers.GetIfExistsAsync("items", Arg.Any<CancellationToken>())
.Returns((NullableResponse<CosmosDBSqlContainerResource>)Response.FromValue(container, Substitute.For<Response>()));

var databaseSetting = Substitute.For<CosmosDBSqlDatabaseThroughputSettingResource>();
var containerSetting = Substitute.For<CosmosDBSqlContainerThroughputSettingResource>();
database.GetCosmosDBSqlDatabaseThroughputSetting().Returns(databaseSetting);
container.GetCosmosDBSqlContainerThroughputSetting().Returns(containerSetting);
var read = CreateArmData(operation == "set" ? (expected == true ? "false" : "true") : pending);
databaseSetting.Data.Returns(read);
containerSetting.Data.Returns(read);
databaseSetting.GetAsync(Arg.Any<CancellationToken>()).Returns(Response.FromValue(databaseSetting, Substitute.For<Response>()));
containerSetting.GetAsync(Arg.Any<CancellationToken>()).Returns(Response.FromValue(containerSetting, Substitute.For<Response>()));

var write = CreateArmData(pending);
var updatedDatabase = Substitute.For<CosmosDBSqlDatabaseThroughputSettingResource>();
var updatedContainer = Substitute.For<CosmosDBSqlContainerThroughputSettingResource>();
updatedDatabase.Data.Returns(write);
updatedContainer.Data.Returns(write);
var databaseOperation = Substitute.For<ArmOperation<CosmosDBSqlDatabaseThroughputSettingResource>>();
var containerOperation = Substitute.For<ArmOperation<CosmosDBSqlContainerThroughputSettingResource>>();
databaseOperation.Value.Returns(updatedDatabase);
containerOperation.Value.Returns(updatedContainer);
databaseSetting.CreateOrUpdateAsync(WaitUntil.Completed, Arg.Any<ThroughputSettingsUpdateData>(), Arg.Any<CancellationToken>()).Returns(databaseOperation);
containerSetting.CreateOrUpdateAsync(WaitUntil.Completed, Arg.Any<ThroughputSettingsUpdateData>(), Arg.Any<CancellationToken>()).Returns(containerOperation);

var id = new ResourceIdentifier("/subscriptions/s/resourceGroups/rg/providers/Microsoft.DocumentDB/databaseAccounts/a");
var context = new ArmCosmosContext(Substitute.For<ArmClient>(), id, "s", "rg", "a", new Uri("https://a.documents.azure.com"), account);
await AssertOutputAsync(new ConnectedState(Substitute.For<CosmosClient>(), context), isContainer, operation, expected);
}

private static ThroughputResponse CreateDataPlaneResponse(string? pending)
{
var response = Substitute.For<ThroughputResponse>();
var headers = new Headers();
if (pending is not null)
{
headers.Add("x-ms-offer-replace-pending", pending);
}

response.Headers.Returns(headers);
response.Resource.Returns(ThroughputProperties.CreateManualThroughput(4000));
return response;
}

private static ThroughputSettingData CreateArmData(string? pending)
{
var resource = pending is null ? new { throughput = 4000 } : (object)new { throughput = 4000, offerReplacePending = pending };
var json = JsonSerializer.Serialize(new { properties = new { resource } });
return ModelReaderWriter.Read<ThroughputSettingData>(BinaryData.FromString(json))!;
}

private static async Task AssertOutputAsync(ConnectedState connection, bool isContainer, string operation, bool? expected)
{
using var shell = ShellInterpreter.CreateInstance();
shell.State = connection;
var dryRun = operation == "dry-run";
var command = new ThroughputCommand
{
Subcommand = operation == "show" ? "show" : "set",
Ru = operation == "show" ? null : 4000,
Database = "db",
Container = isContainer ? "items" : null,
DryRun = dryRun,
Yes = true,
};
var result = await command.ExecuteAsync(shell, new CommandState(), "throughput", TestContext.Current.CancellationToken);

result.OutputFormat = OutputFormat.JSon;
using var cli = JsonDocument.Parse(result.GenerateOutputText());
var mcpResult = McpResponseFactory.CreateSuccess(result, shell.State);
using var mcp = JsonDocument.Parse(Assert.IsType<TextContentBlock>(Assert.Single(mcpResult.Content)).Text);
AssertStatus(cli.RootElement);
AssertStatus(mcp.RootElement.GetProperty("result"));

void AssertStatus(JsonElement payload)
{
Assert.Equal(isContainer ? "container" : "database", payload.GetProperty("scope").GetString());
if (dryRun)
{
Assert.False(payload.GetProperty("planned").TryGetProperty("isReplacePending", out _));
payload = payload.GetProperty("current");
}

var value = payload.GetProperty("isReplacePending");
JsonValueKind expectedKind;
if (expected == true)
{
expectedKind = JsonValueKind.True;
}
else if (expected == false)
{
expectedKind = JsonValueKind.False;
}
else
{
expectedKind = JsonValueKind.Null;
}

Assert.Equal(expectedKind, value.ValueKind);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ private static CommandState BuildResult(ThroughputView view)
["throughput"] = view.Throughput,
["autoscaleMaxThroughput"] = view.AutoscaleMaxThroughput,
["minThroughput"] = view.MinThroughput,
["isReplacePending"] = view.IsReplacePending,
};

using var jsonDoc = JsonDocument.Parse(root.ToJsonString(new JsonSerializerOptions { WriteIndented = true }));
Expand Down Expand Up @@ -182,6 +183,7 @@ private static CommandState BuildDryRunResult(ThroughputView current, bool plann
["throughput"] = current.Throughput,
["autoscaleMaxThroughput"] = current.AutoscaleMaxThroughput,
["minThroughput"] = current.MinThroughput,
["isReplacePending"] = current.IsReplacePending,
},
["planned"] = new JsonObject
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -406,7 +406,8 @@ private static ThroughputView BuildThroughputView(string scope, string resourceN
autoscaleMax,
min,
ThroughputAvailability.Available,
null);
null,
bool.TryParse(info.OfferReplacePending, out var pending) ? pending : null);
}

private async Task<ThroughputBucketsView> UpdateBucketsAsync(string databaseName, string containerName, int bucketId, int? maxThroughputPercentage, CancellationToken token)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,9 @@ private static ThroughputView BuildThroughputView(string scope, string resourceN
var resource = response.Resource;
int? autoscaleMax = resource?.AutoscaleMaxThroughput;
bool isAutoscale = autoscaleMax.HasValue;

// The SDK's IsReplacePending getter throws on unrecognized header values.
bool? isReplacePending = bool.TryParse(response.Headers?["x-ms-offer-replace-pending"], out var pending) ? pending : null;
return new ThroughputView(
scope,
resourceName,
Expand All @@ -412,7 +415,8 @@ private static ThroughputView BuildThroughputView(string scope, string resourceN
autoscaleMax,
response.MinThroughput,
ThroughputAvailability.Available,
null);
null,
isReplacePending);
}

private static ContainerProperties GetContainerPropertiesOrThrow(ContainerResponse response)
Expand Down
3 changes: 2 additions & 1 deletion CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ThroughputView.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,5 @@ internal sealed record ThroughputView(
int? AutoscaleMaxThroughput,
int? MinThroughput,
ThroughputAvailability Availability,
string? ErrorMessage);
string? ErrorMessage,
bool? IsReplacePending = null);
4 changes: 3 additions & 1 deletion docs/commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -1334,6 +1334,8 @@ By default the command targets the current scope: the container when in a contai
|`manual <RUs>`|Switches to manual provisioning at the given RU/s.|
|`autoscale <maxRUs>`|Switches to autoscale with the given maximum RU/s.|

Structured results for `show` and throughput changes include `isReplacePending`: `true` means the service reports a replacement is pending, `false` means it explicitly reports no pending replacement, and `null` means the service omitted the status or returned an unrecognized value. The field is supported on both data-plane and Azure Resource Manager connections. A successful write or a matching RU/s value alone does not establish that a replacement is complete; use `throughput show` to check the latest reported state.

Throughput changes apply to the resource's own provisioned throughput. Containers inside a shared-throughput database, and serverless accounts, have no dedicated throughput to change.

Throughput values are validated before the request is sent: manual RU/s must be at least 400 and a multiple of 100, and autoscale maximum RU/s must be at least 1000 and a multiple of 1000.
Expand All @@ -1342,7 +1344,7 @@ Switching between `manual` and `autoscale` is a mode migration. Over an Azure AD

Write operations (`set`, `manual`, `autoscale`) ask for confirmation before applying, because throughput changes can affect your bill. Pass `--yes` (`-y`/`--force`) to skip the prompt. The prompt is also skipped automatically in non-interactive contexts (MCP, script execution, or piped input).

Pass `--dry-run` with a write subcommand to preview the change without applying it. The command reads the current throughput and reports the current vs. planned mode and RU/s as JSON (and a table interactively); no write is performed and no confirmation is required.
Pass `--dry-run` with a write subcommand to preview the change without applying it. The command reads the current throughput and reports the current vs. planned mode and RU/s as JSON (and a table interactively); no write is performed and no confirmation is required. Only the `current` object includes `isReplacePending`, because the plan has not been submitted.

#### Examples

Expand Down
2 changes: 2 additions & 0 deletions docs/mcp.md
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,8 @@ Database and container resource actions are executed through Azure Resource Mana

On serverless accounts, `mkdb`, `mkcon`, and their `create` aliases omit throughput when neither `--scale` nor `--ru` is supplied. Explicit throughput options are rejected on serverless accounts for both ARM and data-plane connections. See [database and container creation](commands.md#mkdb).

The `throughput` tool reports `isReplacePending` in read and write results: `true` for a pending replacement, `false` when the service reports none pending, and `null` when the status is unavailable. A successful write does not by itself confirm completion. See [throughput](commands.md#throughput).

For deterministic ARM routing in multi-subscription environments, start the shell with `--connect-subscription` and `--connect-resource-group`.

MCP `import` uses the same bounded concurrency as the CLI: up to 16 writes in flight by default, configurable with the `concurrency` argument. Its schema requires a positive integer (`minimum: 1`). Use `concurrency: 1` for sequential, file-order writes. In-flight writes may complete after an error; imports are not transactional. See [import](commands.md#import) for error and cancellation behavior.
Expand Down