fix(grpc-data): size projected unary reservations from the node's shape (#960); per-item status for projected items refused at create (#961)
#960: a projected read reserves 16 KiB for a fixed-size scalar (16 KiB + 256 B/element for a fixed-length fixed-size array) instead of the whole MaxPendingBytes, so the default 1 MiB admits 64 concurrent scalar reads; String/Bytes/variable arrays keep the whole cap, and a waiting whole-cap read holds back smaller ones for 100 ms (anti-starvation). Writes reserve 16 KiB + identifiers + 3 x the value bound (what the origin's DataWriteExecutor admits the batch against). Monitored-item renewals reserve 256 KiB. Measured: 4 x 250 ms maxAge=0 reads 1016 ms / 1 in flight -> 285 ms / 4 in flight. #961: TryAcquireProjectedItem reports BadResourceUnavailable for a stream-capacity refusal; the node manager's CreateMonitoredItem override turns the item manager's ServiceResultException into that item's status (was a whole-request fault), and an authority race is re-classified outside Lock like the per-item probe.
This commit is contained in:
+6
-1
@@ -189,7 +189,12 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
|
||||
response.Results.ToArray()!.ShouldHaveSingleItem().ShouldBe(outcome == DataWriteState.DriverConfirmedSuccess
|
||||
? StatusCodes.Good : StatusCodes.UncertainLastUsableValue);
|
||||
writes.Calls.ShouldBe(1, "neither a success nor an ambiguous outcome may be replayed");
|
||||
writes.Value.ShouldBe(77); writes.Budget.ShouldNotBeNull().MaxBytes.ShouldBe(1024 * 1024);
|
||||
writes.Value.ShouldBe(77);
|
||||
// #960: within the default 1 MiB budget a scalar write reserves (and carries) what it needs, not all of it — enough for
|
||||
// the origin's write accounting (3 × the 288 B scalar estimate + 512 + identifiers).
|
||||
var budget = writes.Budget.ShouldNotBeNull().MaxBytes;
|
||||
budget.ShouldBeLessThan(64 * 1024);
|
||||
budget.ShouldBeGreaterThan(ProjectedDataAccess.ProjectedEnvelopeBytes + 3 * 288);
|
||||
}, maxUnaryBytes: 1024 * 1024, allowWrite: true);
|
||||
}
|
||||
|
||||
|
||||
+18
-3
@@ -221,10 +221,14 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
|
||||
/// <summary>Like <c>FakeConnections</c>, counting browse, metadata and read calls separately.</summary>
|
||||
private sealed class CountingConnections(LocalDataFixture peer) : IGrpcDataAdapterConnectionSource
|
||||
{
|
||||
private int _browse, _metadata, _read;
|
||||
private int _browse, _metadata, _read, _readsInFlight, _maxReadsInFlight;
|
||||
public int BrowseCalls => Volatile.Read(ref _browse);
|
||||
public int MetadataCalls => Volatile.Read(ref _metadata);
|
||||
public int ReadCalls => Volatile.Read(ref _read);
|
||||
/// <summary>#960: the most origin reads ever in flight at once.</summary>
|
||||
public int MaxConcurrentReads => Volatile.Read(ref _maxReadsInFlight);
|
||||
/// <summary>#960: how long each origin read takes (real time), so concurrent reads overlap measurably.</summary>
|
||||
public TimeSpan ReadDelay { get; set; }
|
||||
public ValueTask<IGrpcDataAdapterConnectionLease?> AcquireAsync(string connectionId, CancellationToken cancellationToken) =>
|
||||
ValueTask.FromResult<IGrpcDataAdapterConnectionLease?>(connectionId == "link" ? new Lease(new Connection(peer.Connection(), this)) : null);
|
||||
private sealed class Lease(IDataConnection connection) : IGrpcDataAdapterConnectionLease
|
||||
@@ -242,8 +246,19 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
|
||||
{ Interlocked.Increment(ref owner._browse); return inner.BrowseAsync(request, cancellationToken); }
|
||||
public Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken)
|
||||
{ Interlocked.Increment(ref owner._metadata); return inner.GetMetadataAsync(request, cancellationToken); }
|
||||
public Task<IReadOnlyList<DataReadResult>> ReadAsync(DataReadRequest request, CancellationToken cancellationToken)
|
||||
{ Interlocked.Increment(ref owner._read); return inner.ReadAsync(request, cancellationToken); }
|
||||
public async Task<IReadOnlyList<DataReadResult>> ReadAsync(DataReadRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
Interlocked.Increment(ref owner._read);
|
||||
var now = Interlocked.Increment(ref owner._readsInFlight);
|
||||
for (var seen = Volatile.Read(ref owner._maxReadsInFlight); now > seen; seen = Volatile.Read(ref owner._maxReadsInFlight))
|
||||
if (Interlocked.CompareExchange(ref owner._maxReadsInFlight, now, seen) == seen) break;
|
||||
try
|
||||
{
|
||||
if (owner.ReadDelay > TimeSpan.Zero) await Task.Delay(owner.ReadDelay, cancellationToken);
|
||||
return await inner.ReadAsync(request, cancellationToken);
|
||||
}
|
||||
finally { Interlocked.Decrement(ref owner._readsInFlight); }
|
||||
}
|
||||
public Task<IReadOnlyList<WriteItemResult>> WriteAsync(WriteBatch request, CancellationToken cancellationToken) => inner.WriteAsync(request, cancellationToken);
|
||||
public Task<IDataSubscription> SubscribeAsync(CancellationToken cancellationToken) => inner.SubscribeAsync(cancellationToken);
|
||||
public ValueTask DisposeAsync() => inner.DisposeAsync();
|
||||
|
||||
+150
-8
@@ -175,32 +175,115 @@ public sealed partial class GrpcDataProjectedAccessTests
|
||||
access.ScheduleRead(demand!, sdkBudget, fixture.Clock.GetTimestamp()).ShouldBeTrue();
|
||||
var update = await fixture.Published.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||||
update.Snapshot.Value.ShouldBe(42);
|
||||
fixture.ReadBudget.ShouldNotBeNull().MaxBytes.ShouldBe(1024 * 1024);
|
||||
// #960: a scalar read reserves (and may decode) only what its declared shape can answer, within the configured limit.
|
||||
fixture.ReadBudget.ShouldNotBeNull().MaxBytes.ShouldBe(ProjectedDataAccess.ProjectedEnvelopeBytes);
|
||||
await fixture.ConnectionDisposed.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||||
}
|
||||
|
||||
[Fact(Timeout = 30000), Trait("Phase", "P10")]
|
||||
public async Task Clamped_read_reserves_the_full_configured_budget_until_physical_completion()
|
||||
[Fact(Timeout = 30000), Trait("Phase", "P10"), Trait("Issue", "960")]
|
||||
public async Task Variable_size_read_reserves_the_full_configured_budget_until_physical_completion()
|
||||
{
|
||||
// A String value has no declared bound, so its read keeps the whole per-read cap (#960 sizes only bounded shapes).
|
||||
using var fixture = new AccessFixture(readOnly: true) { BlockAcquire = true }; using var access = fixture.Create(maxBytes: 1024 * 1024);
|
||||
fixture.Publish(42);
|
||||
UseValueKind(fixture, DataValueKind.String);
|
||||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var first).ShouldBeTrue();
|
||||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var second).ShouldBeTrue();
|
||||
var sdkBudget = new DataBudget(TimeSpan.FromSeconds(5), 1, 4 * 1024 * 1024);
|
||||
try
|
||||
{
|
||||
access.ScheduleRead(first!, sdkBudget, fixture.Clock.GetTimestamp()).ShouldBeTrue();
|
||||
first = null; // admitted work owns the lease
|
||||
await fixture.AcquireEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||||
access.ScheduleRead(second!, sdkBudget, fixture.Clock.GetTimestamp()).ShouldBeFalse();
|
||||
second!.IsValid.ShouldBeTrue("a rejected admission leaves ownership with the caller");
|
||||
fixture.ReleaseAcquire.TrySetResult();
|
||||
await fixture.Published.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||||
SpinWait.SpinUntil(() => access.ScheduleRead(second, sdkBudget, fixture.Clock.GetTimestamp()), TimeSpan.FromSeconds(5)).ShouldBeTrue();
|
||||
second = null; // admitted work owns the lease
|
||||
second = null;
|
||||
fixture.ReadBudget.ShouldNotBeNull().MaxBytes.ShouldBe(1024 * 1024);
|
||||
}
|
||||
finally { fixture.ReleaseAcquire.TrySetResult(); first?.Dispose(); second?.Dispose(); }
|
||||
}
|
||||
|
||||
[Fact(Timeout = 30000), Trait("Phase", "P10"), Trait("Issue", "960")]
|
||||
public async Task Scalar_reads_reserve_their_shape_bound_so_concurrent_reads_share_the_default_budget()
|
||||
{
|
||||
// The production default: DataConnections:MaxPendingBytes = 1 MiB. Before #960 every read reserved all of it, so only
|
||||
// ONE projected read (or write) could be in flight per node. The operation-count limit (4 here) is the bound now.
|
||||
using var fixture = new AccessFixture(readOnly: true) { BlockAcquire = true }; using var access = fixture.Create(maxDemands: 8, maxBytes: 1024 * 1024);
|
||||
fixture.Publish(42);
|
||||
var sdkBudget = new DataBudget(TimeSpan.FromSeconds(5), 1, 4 * 1024 * 1024);
|
||||
var demands = new List<IProjectedDemandLease?>();
|
||||
try
|
||||
{
|
||||
for (var i = 0; i < 5; i++)
|
||||
{
|
||||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var demand).ShouldBeTrue();
|
||||
demands.Add(demand);
|
||||
}
|
||||
var admitted = 0;
|
||||
for (var i = 0; i < 4; i++)
|
||||
if (access.ScheduleRead(demands[i]!, sdkBudget, fixture.Clock.GetTimestamp())) { admitted++; demands[i] = null; }
|
||||
admitted.ShouldBe(4, "four scalar reads fit the 1 MiB budget at once");
|
||||
access.ScheduleRead(demands[4]!, sdkBudget, fixture.Clock.GetTimestamp()).ShouldBeFalse("the operation-count limit still bounds them");
|
||||
fixture.ReleaseAcquire.TrySetResult();
|
||||
SpinWait.SpinUntil(() => access.ScheduleRead(demands[4]!, sdkBudget, fixture.Clock.GetTimestamp()), TimeSpan.FromSeconds(5)).ShouldBeTrue();
|
||||
demands[4] = null;
|
||||
await fixture.Published.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||||
}
|
||||
finally { fixture.ReleaseAcquire.TrySetResult(); foreach (var demand in demands) demand?.Dispose(); }
|
||||
}
|
||||
|
||||
[Fact(Timeout = 30000), Trait("Phase", "P10"), Trait("Issue", "960")]
|
||||
public async Task A_waiting_whole_cap_read_holds_back_smaller_reads_until_it_is_admitted()
|
||||
{
|
||||
// Scalar reads now share the budget; a whole-cap (String) read that waits for capacity must not be starved by them.
|
||||
using var fixture = new AccessFixture(readOnly: true, streams: true) { BlockAcquire = true };
|
||||
using var access = fixture.Create(maxDemands: 8, maxBytes: 1024 * 1024);
|
||||
var stringMetadata = fixture.SecondProof!.Metadata with { ValueKind = DataValueKind.String };
|
||||
fixture.SecondProof = fixture.SecondProof with { Metadata = stringMetadata, OriginMetadata = fixture.SecondProof.OriginMetadata with { ValueKind = DataValueKind.String } };
|
||||
fixture.SecondDefinition = fixture.SecondDefinition! with { Metadata = stringMetadata };
|
||||
fixture.Publish(42);
|
||||
var sdkBudget = new DataBudget(TimeSpan.FromSeconds(5), 1, 4 * 1024 * 1024);
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var first).ShouldBeTrue();
|
||||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var second).ShouldBeTrue();
|
||||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var third).ShouldBeTrue();
|
||||
access.TryAcquire(fixture.SecondNodeId, fixture.Caller, DataOperations.Read, out var large).ShouldBeTrue();
|
||||
try
|
||||
{
|
||||
access.ScheduleRead(first!, sdkBudget, fixture.Clock.GetTimestamp()).ShouldBeTrue();
|
||||
first = null;
|
||||
(await access.ReadNowAsync(large!, sdkBudget, fixture.Clock.GetTimestamp(), ct)).Status.ShouldBe(ProjectedOriginReadStatus.NotAdmitted);
|
||||
access.ScheduleRead(second!, sdkBudget, fixture.Clock.GetTimestamp()).ShouldBeFalse("a waiting whole-cap read holds back smaller ones");
|
||||
// A waiter that gives up stops holding them back once the window lapses.
|
||||
fixture.Advance(ProjectedDataAccess.ReadDrainWindow + TimeSpan.FromMilliseconds(1));
|
||||
access.ScheduleRead(second!, sdkBudget, fixture.Clock.GetTimestamp()).ShouldBeTrue();
|
||||
second = null;
|
||||
// It waits again; the scalar reads in flight finish and it is admitted ahead of the third.
|
||||
(await access.ReadNowAsync(large!, sdkBudget, fixture.Clock.GetTimestamp(), ct)).Status.ShouldBe(ProjectedOriginReadStatus.NotAdmitted);
|
||||
access.ScheduleRead(third!, sdkBudget, fixture.Clock.GetTimestamp()).ShouldBeFalse();
|
||||
fixture.ReleaseAcquire.TrySetResult();
|
||||
Task<ProjectedOriginRead>? read = null;
|
||||
SpinWait.SpinUntil(() =>
|
||||
{
|
||||
var attempt = access.ReadNowAsync(large!, sdkBudget, fixture.Clock.GetTimestamp(), ct);
|
||||
if (attempt.IsCompletedSuccessfully && attempt.Result.Status == ProjectedOriginReadStatus.NotAdmitted) return false;
|
||||
read = attempt; return true;
|
||||
}, TimeSpan.FromSeconds(5)).ShouldBeTrue("the waiting read is admitted once the scalar reads finish");
|
||||
await read!.WaitAsync(TimeSpan.FromSeconds(5), ct);
|
||||
SpinWait.SpinUntil(() => access.ScheduleRead(third!, sdkBudget, fixture.Clock.GetTimestamp()), TimeSpan.FromSeconds(5)).ShouldBeTrue();
|
||||
third = null;
|
||||
}
|
||||
finally { fixture.ReleaseAcquire.TrySetResult(); first?.Dispose(); second?.Dispose(); third?.Dispose(); large?.Dispose(); }
|
||||
}
|
||||
|
||||
private static void UseValueKind(AccessFixture fixture, DataValueKind kind)
|
||||
{
|
||||
var metadata = fixture.Proof.Metadata with { ValueKind = kind };
|
||||
fixture.Proof = fixture.Proof with { Metadata = metadata, OriginMetadata = fixture.Proof.OriginMetadata with { ValueKind = kind } };
|
||||
fixture.Definition = fixture.Definition with { Metadata = metadata };
|
||||
}
|
||||
|
||||
[Fact(Timeout = 30000)]
|
||||
public async Task Read_without_subscribe_permission_preserves_origin_age_timestamps_and_source_proof()
|
||||
{
|
||||
@@ -250,12 +333,70 @@ public sealed partial class GrpcDataProjectedAccessTests
|
||||
var budget = new DataBudget(TimeSpan.FromSeconds(5), 1, 4 * 1024 * 1024);
|
||||
var result = await access.WriteAsync(demand!, 42, budget, fixture.Clock.GetTimestamp(), TestContext.Current.CancellationToken);
|
||||
result.State.ShouldBe(DataWriteState.OutcomeUnknown);
|
||||
fixture.SentWrite.ShouldNotBeNull().Budget.MaxBytes.ShouldBe(1024 * 1024);
|
||||
// #960: a scalar write reserves what it needs (envelope + the origin's write accounting), not the whole configured limit.
|
||||
var sent = fixture.SentWrite.ShouldNotBeNull();
|
||||
sent.Budget.MaxBytes.ShouldBeLessThan(ScalarWriteBytesBound);
|
||||
sent.Budget.MaxBytes.ShouldBeGreaterThanOrEqualTo(OriginWriteAccounting(sent, 288));
|
||||
fixture.WriteCalls.ShouldBe(1);
|
||||
}
|
||||
finally { demand?.Dispose(); }
|
||||
}
|
||||
|
||||
/// <summary>#960: more than one scalar write's reservation (envelope + identifiers + 3 × 288), less than two.</summary>
|
||||
private const long ScalarWriteBytesBound = 30 * 1024;
|
||||
|
||||
/// <summary>What the origin's DataWriteExecutor admits a one-item write batch against (3 × retained estimate + 512 + identifiers).</summary>
|
||||
private static long OriginWriteAccounting(WriteBatch sent, long valueEstimate)
|
||||
{
|
||||
var item = sent.Items.ShouldHaveSingleItem();
|
||||
return 3 * valueEstimate + 512 + 2L * ((item.CorrelationId?.Length ?? 0) + (item.OperationId?.Length ?? 0) +
|
||||
(item.View.Subject?.Length ?? 0) + (item.View.MappingId?.Length ?? 0) + (item.View.Address.OriginClusterId?.Length ?? 0) +
|
||||
(item.View.Address.NamespaceUri?.Length ?? 0) + (item.View.Address.IdentifierKind?.Length ?? 0) +
|
||||
(item.View.Address.Identifier?.Length ?? 0) + (item.ExpectedServingIncarnation?.Length ?? 0));
|
||||
}
|
||||
|
||||
[Fact(Timeout = 30000), Trait("Phase", "P10"), Trait("Issue", "960")]
|
||||
public async Task A_large_string_write_reserves_what_the_origin_admits_it_against()
|
||||
{
|
||||
// Sized below the cap, a write must still carry the budget the ORIGIN checks it against, or a long string that the
|
||||
// whole-cap reservation used to carry is refused there ("Write batch exceeds its byte limit").
|
||||
using var fixture = new AccessFixture(writable: true); using var access = fixture.Create(maxBytes: 1024 * 1024);
|
||||
UseValueKind(fixture, DataValueKind.String);
|
||||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Write, out var demand).ShouldBeTrue();
|
||||
try
|
||||
{
|
||||
var text = new string('x', 20_000);
|
||||
var budget = new DataBudget(TimeSpan.FromSeconds(5), 1, 4 * 1024 * 1024);
|
||||
(await access.WriteAsync(demand!, text, budget, fixture.Clock.GetTimestamp(), TestContext.Current.CancellationToken)).State
|
||||
.ShouldBe(DataWriteState.OutcomeUnknown);
|
||||
var sent = fixture.SentWrite.ShouldNotBeNull();
|
||||
sent.Budget.MaxBytes.ShouldBeGreaterThanOrEqualTo(OriginWriteAccounting(sent, 288 + 2L * text.Length));
|
||||
sent.Budget.MaxBytes.ShouldBeLessThan(1024 * 1024);
|
||||
}
|
||||
finally { demand?.Dispose(); }
|
||||
}
|
||||
|
||||
[Fact(Timeout = 30000), Trait("Phase", "P10"), Trait("Issue", "960")]
|
||||
public async Task Scalar_writes_are_dispatched_concurrently_within_the_default_budget()
|
||||
{
|
||||
using var fixture = new AccessFixture(writable: true) { BlockWrite = true }; using var access = fixture.Create(maxBytes: 1024 * 1024);
|
||||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Write, out var first).ShouldBeTrue();
|
||||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Write, out var second).ShouldBeTrue();
|
||||
try
|
||||
{
|
||||
var budget = new DataBudget(TimeSpan.FromSeconds(5), 1, 4 * 1024 * 1024);
|
||||
var one = access.WriteAsync(first!, 42, budget, fixture.Clock.GetTimestamp(), TestContext.Current.CancellationToken);
|
||||
await fixture.WriteEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||||
var two = access.WriteAsync(second!, 43, budget, fixture.Clock.GetTimestamp(), TestContext.Current.CancellationToken);
|
||||
SpinWait.SpinUntil(() => Volatile.Read(ref fixture.WriteCalls) == 2 || two.IsCompleted, TimeSpan.FromSeconds(5));
|
||||
fixture.WriteCalls.ShouldBe(2, "a second write is dispatched while the first is in flight, not rejected for capacity");
|
||||
fixture.ReleaseWrite.TrySetResult();
|
||||
(await one.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).State.ShouldBe(DataWriteState.OutcomeUnknown);
|
||||
(await two.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).State.ShouldBe(DataWriteState.OutcomeUnknown);
|
||||
}
|
||||
finally { fixture.ReleaseWrite.TrySetResult(); first?.Dispose(); second?.Dispose(); }
|
||||
}
|
||||
|
||||
[Fact(Timeout = 30000), Trait("Phase", "P10")]
|
||||
public async Task Clamped_write_rejects_oversized_value_before_dispatch()
|
||||
{
|
||||
@@ -276,7 +417,8 @@ public sealed partial class GrpcDataProjectedAccessTests
|
||||
[Fact(Timeout = 30000), Trait("Phase", "P10")]
|
||||
public async Task Cancelled_clamped_write_keeps_capacity_until_the_physical_send_finishes()
|
||||
{
|
||||
using var fixture = new AccessFixture(writable: true) { BlockWrite = true }; using var access = fixture.Create(maxBytes: 1024 * 1024);
|
||||
// A budget that holds one scalar write's reservation but not two (#960), so the held one leaves no room for another.
|
||||
using var fixture = new AccessFixture(writable: true) { BlockWrite = true }; using var access = fixture.Create(maxBytes: ScalarWriteBytesBound);
|
||||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Write, out var first).ShouldBeTrue();
|
||||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Write, out var second).ShouldBeTrue();
|
||||
using var cancel = new CancellationTokenSource();
|
||||
|
||||
+107
-1
@@ -79,7 +79,7 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
|
||||
using var origin = new LocalDataFixture(additionalRawNodes: 3, servingGeneration: 1);
|
||||
origin.Publish(42);
|
||||
var connections = new CountingConnections(origin);
|
||||
// 1 MiB unary budget = ONE read in flight at a time (each reserves it all), as in production by default.
|
||||
// A unary budget of exactly one scalar read's reservation (#960) = ONE read in flight at a time.
|
||||
await WithComposedServer(origin, origin.Root, async (session, _, _, _, _, _, anchor) =>
|
||||
{
|
||||
var client = (SessionClient)session;
|
||||
@@ -90,6 +90,36 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
|
||||
var results = read.Results.ToArray()!;
|
||||
results.ShouldAllBe(r => StatusCode.IsGood(r.StatusCode), string.Join(", ", results.Select(r => r.StatusCode.ToString())));
|
||||
connections.ReadCalls.ShouldBe(4);
|
||||
connections.MaxConcurrentReads.ShouldBe(1);
|
||||
}, connectionSource: connections, maxUnaryBytes: ProjectedDataAccess.ProjectedEnvelopeBytes);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- #960
|
||||
|
||||
[Fact(Timeout = 90000), Trait("Issue", "960")]
|
||||
public async Task A_max_age_zero_batch_of_scalar_nodes_reads_the_origin_concurrently_within_the_default_budget()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
using var origin = new LocalDataFixture(additionalRawNodes: 3, servingGeneration: 1);
|
||||
origin.Publish(42);
|
||||
var connections = new CountingConnections(origin) { ReadDelay = TimeSpan.FromMilliseconds(250) };
|
||||
// The production default DataConnections:MaxPendingBytes (1 MiB). Before #960 each read reserved all of it, so the four
|
||||
// origin reads ran one after another (~4 x 250 ms); the harness's operation limit (4) is now the only bound.
|
||||
await WithComposedServer(origin, origin.Root, async (session, _, _, _, _, _, anchor) =>
|
||||
{
|
||||
var client = (SessionClient)session;
|
||||
var children = (await BrowseAll(client, anchor, 10)).Select(r => ExpandedNodeId.ToNodeId(r.NodeId, session.NamespaceUris)).ToArray();
|
||||
children.Length.ShouldBe(4);
|
||||
var timer = System.Diagnostics.Stopwatch.StartNew();
|
||||
var read = await client.ReadAsync(new RequestHeader(), 0, TimestampsToReturn.Both,
|
||||
children.Select(c => new ReadValueId { NodeId = c, AttributeId = Attributes.Value }).ToArray(), ct);
|
||||
timer.Stop();
|
||||
var results = read.Results.ToArray()!;
|
||||
TestContext.Current.TestOutputHelper?.WriteLine(
|
||||
$"#960: 4 maxAge=0 scalar reads, 250 ms origin each: {timer.ElapsedMilliseconds} ms, max {connections.MaxConcurrentReads} in flight");
|
||||
results.ShouldAllBe(r => StatusCode.IsGood(r.StatusCode), string.Join(", ", results.Select(r => r.StatusCode.ToString())));
|
||||
connections.ReadCalls.ShouldBe(4);
|
||||
connections.MaxConcurrentReads.ShouldBe(4, "the four origin reads run concurrently, not one at a time");
|
||||
}, connectionSource: connections, maxUnaryBytes: 1024 * 1024);
|
||||
}
|
||||
|
||||
@@ -343,6 +373,82 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
|
||||
}, connectionSource: connections, staleTimeoutMilliseconds: LongStale);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- #961
|
||||
|
||||
private static MonitoredItemCreateRequest ItemRequest(NodeId node, uint handle) => new()
|
||||
{
|
||||
ItemToMonitor = new ReadValueId { NodeId = node, AttributeId = Attributes.Value },
|
||||
MonitoringMode = MonitoringMode.Reporting,
|
||||
RequestedParameters = new MonitoringParameters { ClientHandle = handle, SamplingInterval = 100, QueueSize = 1, DiscardOldest = true },
|
||||
};
|
||||
|
||||
[Fact(Timeout = 90000), Trait("Issue", "961")]
|
||||
public async Task A_projected_item_refused_for_stream_capacity_at_create_fails_only_that_item()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
LocalDataFixture? peer = null;
|
||||
var subscriptions = new FakeSubscriptions(() => peer!.Serving);
|
||||
using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions);
|
||||
peer = origin; subscriptions.SampleClock = origin.Clock;
|
||||
var connections = new RefusingConnections(origin);
|
||||
// The harness allows 2 origin streams; one stream (cohort) is opened per publishing interval.
|
||||
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
|
||||
{
|
||||
var client = (SessionClient)session;
|
||||
await BrowseAll(client, anchor, 1);
|
||||
foreach (var interval in new double[] { 500, 1000 })
|
||||
{
|
||||
var sub = (await client.CreateSubscriptionAsync(new RequestHeader(), interval, 300, 1, 0, true, 0, ct)).SubscriptionId;
|
||||
(await CreateItem(client, sub, anchor, 1, ct)).ShouldBe(StatusCodes.Good);
|
||||
}
|
||||
var third = (await client.CreateSubscriptionAsync(new RequestHeader(), 2000, 300, 1, 0, true, 0, ct)).SubscriptionId;
|
||||
var response = await client.CreateMonitoredItemsAsync(new RequestHeader(), third, TimestampsToReturn.Both,
|
||||
[ItemRequest(anchor, 1), ItemRequest(VariableIds.Server_ServerStatus_State, 2)], ct);
|
||||
var results = response.Results.ToArray()!;
|
||||
results[0].StatusCode.ShouldBe(StatusCodes.BadResourceUnavailable, "no origin stream can take it: retryable, for this item only");
|
||||
results[1].StatusCode.ShouldBe(StatusCodes.Good, "the rest of the batch is created");
|
||||
}, connectionSource: connections);
|
||||
}
|
||||
|
||||
[Fact(Timeout = 90000), Trait("Issue", "961")]
|
||||
public async Task A_projected_item_whose_lease_lapses_between_the_probe_and_the_create_is_retryable_for_that_item_only()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
LocalDataFixture? peer = null;
|
||||
var subscriptions = new FakeSubscriptions(() => peer!.Serving);
|
||||
using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions);
|
||||
peer = origin; subscriptions.SampleClock = origin.Clock;
|
||||
var connections = new RefusingConnections(origin);
|
||||
ZB.MOM.WW.OtOpcUa.OpcUaServer.OtOpcUaNodeManager? manager = null;
|
||||
await WithComposedServer(origin, origin.Raw, async (session, _, resolver, _, _, _, anchor) =>
|
||||
{
|
||||
var client = (SessionClient)session;
|
||||
await BrowseAll(client, anchor, 1);
|
||||
var lapsed = 0;
|
||||
// The authority changes after CreateMonitoredItems' per-item probe admitted the item, under the create's Lock.
|
||||
manager.ShouldNotBeNull().BeforeProjectedItemAcquireForTests = _ =>
|
||||
{
|
||||
if (Interlocked.Exchange(ref lapsed, 1) == 0) origin.Clock.Advance(TimeSpan.FromSeconds(16));
|
||||
};
|
||||
var sub = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId;
|
||||
var response = await client.CreateMonitoredItemsAsync(new RequestHeader(), sub, TimestampsToReturn.Both,
|
||||
[ItemRequest(anchor, 1), ItemRequest(VariableIds.Server_ServerStatus_State, 2)], ct);
|
||||
manager.BeforeProjectedItemAcquireForTests = null;
|
||||
var results = response.Results.ToArray()!;
|
||||
lapsed.ShouldBe(1, "precondition: the create ran after the probe");
|
||||
results[0].StatusCode.ShouldBe(StatusCodes.BadResourceUnavailable, "a lapse the caller is granted is retryable, not an access denial");
|
||||
results[1].StatusCode.ShouldBe(StatusCodes.Good, "the rest of the batch is created");
|
||||
// ...and the retry succeeds once the on-demand renewal the classification started has committed.
|
||||
var created = false;
|
||||
for (var i = 0; i < 100 && !created; i++)
|
||||
{
|
||||
created = await CreateItem(client, sub, anchor, 3, ct) == StatusCodes.Good;
|
||||
if (!created) await Task.Delay(50, ct);
|
||||
}
|
||||
created.ShouldBeTrue();
|
||||
}, connectionSource: connections, staleTimeoutMilliseconds: LongStale, onHistory: (_, m) => manager = m);
|
||||
}
|
||||
|
||||
private static async Task<StatusCode> Write(SessionClient client, NodeId node, int value, CancellationToken ct) =>
|
||||
(await client.WriteAsync(new RequestHeader(),
|
||||
[new WriteValue { NodeId = node, AttributeId = Attributes.Value, Value = new Opc.Ua.DataValue(new Variant(value), StatusCodes.Good) }], ct))
|
||||
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
using DataValue = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue;
|
||||
using ReadResult = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadResult;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
||||
|
||||
/// <summary>
|
||||
/// #960: a projected read reserves only what its node's declared shape can answer, and that reservation is the read's
|
||||
/// decode limit. These pin the constants against the REAL wire codec: a response carrying the widest value of each bounded
|
||||
/// shape, with long serving identifiers, must decode within its reservation.
|
||||
/// </summary>
|
||||
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Issue", "960")]
|
||||
public sealed class GrpcDataProjectedReadReservationTests
|
||||
{
|
||||
private static readonly ServingIdentity Serving = new(new string('n', 128), Guid.NewGuid().ToString("D") + new string('i', 92),
|
||||
"Primary", long.MaxValue, long.MaxValue, long.MaxValue);
|
||||
|
||||
private static DataMetadata Metadata(DataValueKind kind, int length = 0, DataValueKind? element = null) =>
|
||||
new(new DataView(new DataAddress("cluster", "https://zb.com/otopcua/raw", "s", "Plant/Speed"), DataRealm.Raw, null, 0, "Plant/Speed"),
|
||||
"Speed", "Variable", kind, kind == DataValueKind.Array ? 1 : -1, kind == DataValueKind.Array ? [length] : [], false,
|
||||
DataOperations.Read, 1, null, null, false, element, Serving);
|
||||
|
||||
public static TheoryData<string> BoundedShapes => new() { "Int64", "Double", "Timestamp", "Guid", "Int32[1000]", "Double[64]", "Guid[64]", "Timestamp[64]" };
|
||||
|
||||
private static (DataMetadata Metadata, DataValue Value) Widest(string shape)
|
||||
{
|
||||
var timestamp = DateTimeOffset.MaxValue.AddTicks(-1).ToUniversalTime();
|
||||
return shape switch
|
||||
{
|
||||
"Int64" => (Metadata(DataValueKind.Int64), DataValue.FromScalar(DataValueKind.Int64, long.MinValue)),
|
||||
"Double" => (Metadata(DataValueKind.Double), DataValue.FromScalar(DataValueKind.Double, double.MinValue)),
|
||||
"Timestamp" => (Metadata(DataValueKind.Timestamp), DataValue.FromScalar(DataValueKind.Timestamp, timestamp)),
|
||||
"Guid" => (Metadata(DataValueKind.Guid), DataValue.FromScalar(DataValueKind.Guid, Guid.NewGuid())),
|
||||
"Int32[1000]" => (Metadata(DataValueKind.Array, 1000, DataValueKind.Int32),
|
||||
DataValue.FromArray(DataValueKind.Int32, Enumerable.Repeat((object)int.MinValue, 1000).ToArray(), [1000])),
|
||||
"Double[64]" => (Metadata(DataValueKind.Array, 64, DataValueKind.Double),
|
||||
DataValue.FromArray(DataValueKind.Double, Enumerable.Repeat((object)double.MinValue, 64).ToArray(), [64])),
|
||||
"Guid[64]" => (Metadata(DataValueKind.Array, 64, DataValueKind.Guid),
|
||||
DataValue.FromArray(DataValueKind.Guid, Enumerable.Range(0, 64).Select(_ => (object)Guid.NewGuid()).ToArray(), [64])),
|
||||
"Timestamp[64]" => (Metadata(DataValueKind.Array, 64, DataValueKind.Timestamp),
|
||||
DataValue.FromArray(DataValueKind.Timestamp, Enumerable.Repeat((object)timestamp, 64).ToArray(), [64])),
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(shape)),
|
||||
};
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(BoundedShapes))]
|
||||
public void The_widest_value_of_a_bounded_shape_decodes_within_its_read_reservation(string shape)
|
||||
{
|
||||
var (metadata, value) = Widest(shape);
|
||||
var reservation = ProjectedDataAccess.ReadReservationBytes(metadata, 4 * 1024 * 1024);
|
||||
reservation.ShouldBeLessThan(4 * 1024 * 1024L, "a bounded shape is never charged the whole cap");
|
||||
var sample = new DataSample(value, 0x80000000u, DateTimeOffset.UtcNow, DateTimeOffset.UtcNow, Serving, long.MaxValue);
|
||||
var wire = DataProtoMapper.EncodeReadResponse([new ReadResult("0", DataItemStatus.Good, DataReadiness.Ready, TimeSpan.MaxValue, sample,
|
||||
new string('d', 256), AgeBounds: new(TimeSpan.Zero, TimeSpan.FromDays(1)))]);
|
||||
wire.Serving = DataProtoMapper.EncodeServing(Serving);
|
||||
var decoded = DataProtoMapper.DecodeReadResponse(wire, new DataDecodeLimits(1, (int)reservation));
|
||||
try { decoded.ShouldHaveSingleItem().Sample.ShouldNotBeNull(); }
|
||||
finally { foreach (var item in decoded) item.Dispose(); }
|
||||
// The origin's own admission of the same answer (LocalDataServices.ReadAsync: retained estimate + 256).
|
||||
(value.EstimatedRetainedBytes + 256).ShouldBeLessThanOrEqualTo(reservation);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(DataValueKind.String)]
|
||||
[InlineData(DataValueKind.Bytes)]
|
||||
[InlineData(DataValueKind.Unspecified)]
|
||||
public void An_unbounded_shape_keeps_the_whole_per_read_cap(DataValueKind kind) =>
|
||||
ProjectedDataAccess.ReadReservationBytes(Metadata(kind), 1024 * 1024).ShouldBe(1024 * 1024);
|
||||
|
||||
[Fact]
|
||||
public void A_variable_length_or_string_array_keeps_the_whole_per_read_cap()
|
||||
{
|
||||
ProjectedDataAccess.ReadReservationBytes(Metadata(DataValueKind.Array, 0, DataValueKind.Int32), 1024 * 1024).ShouldBe(1024 * 1024);
|
||||
ProjectedDataAccess.ReadReservationBytes(Metadata(DataValueKind.Array, 8, DataValueKind.String), 1024 * 1024).ShouldBe(1024 * 1024);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_reservation_never_exceeds_the_configured_cap()
|
||||
{
|
||||
ProjectedDataAccess.ReadReservationBytes(Metadata(DataValueKind.Int32), 1100).ShouldBe(1100);
|
||||
ProjectedDataAccess.ReadReservationBytes(Metadata(DataValueKind.Array, 100_000, DataValueKind.Double), 1024 * 1024).ShouldBe(1024 * 1024);
|
||||
}
|
||||
}
|
||||
+3
-1
@@ -19,7 +19,9 @@ public sealed partial class GrpcDataProjectedAccessTests
|
||||
var large = new int[20_000];
|
||||
try
|
||||
{
|
||||
var pending = access.WriteAsync(first!, new[] { 1, 2, 3 }, budget, fixture.Clock.GetTimestamp(), TestContext.Current.CancellationToken);
|
||||
// #960: a write reserves what its value needs, so the held write is itself large enough (~2 MiB of the 4 MiB) that the
|
||||
// second (~2.5 MiB) no longer fits beside it.
|
||||
var pending = access.WriteAsync(first!, new int[16_000], budget, fixture.Clock.GetTimestamp(), TestContext.Current.CancellationToken);
|
||||
await fixture.WriteEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||||
var before = GC.GetAllocatedBytesForCurrentThread();
|
||||
var rejected = access.WriteAsync(second!, large, budget, fixture.Clock.GetTimestamp(), TestContext.Current.CancellationToken);
|
||||
|
||||
Reference in New Issue
Block a user