fix(historian): refuse aggregates not valid for the node's DataType up front (#897)
v2-ci / unit-tests (push) Has been cancelled

TimeAverage / Total on a Boolean node over the Gateway backend (AVEVA discrete tag, live
SysPulse) went to the gateway since native TimeAverage/Total became default-on (#694). AVEVA
refuses both modes at StartQuery; the gateway reports that only as Internal /
HistorianServerOperationException (the same answer as a historian storage fault), so the
node answered BadHistoryOperationUnsupported and the read counted as a backend failure.

HistoryRead-Processed now checks the node's scalar DataType before calling any backend and
answers BadAggregateNotSupported (Part 11 6.5.4: "If the Aggregate is not valid for the Node
then the StatusCode shall be Bad_AggregateNotSupported"). Nothing is sent, nothing is counted.
- Shared, every backend: HistoryAggregateDataTypes (Core.Abstractions) applies Part 13
  5.4.2.3 Table 50: the numeric-only aggregates (Average, TimeAverage(2), Total(2), Min/Max,
  ActualTime, Range, Delta, DeltaBounds, Interpolative, stddev/variance) on a String or
  DateTime node are refused. Client-visible: the SQL backends used to answer every interval
  BadAggregateInvalidInputs.
- Per backend: IHistorianDataSource.SupportsAggregateFor(aggregate, TypeCode?) (default true;
  every production backend declares it, guard-tested). Gateway: false for native
  TimeAverage/Total on a Boolean node. SqlServer/QuestDb: true, since they serve Boolean as
  0/1 (stepped), so Boolean stays served there, as do the Gateway's raw-evaluated aggregates.

The residual case (a node declared numeric whose AVEVA tag is discrete) cannot be told apart
from a historian fault on the wire and still counts; that needs the gateway to surface
AVEVA's native error code as a deterministic status.

Tests: HistoryAggregateDataTypesTests, guard test, node-manager String/DateTime and per-type
refusals, Gateway capability matrix, DiscreteTagTimeWeightedWireTests (production Gateway
backend over an AVEVA-shaped fake: unsent, 0 health failures, positive controls). Each
mutation (no check, no shared rule, no backend hint, Gateway hint true, shared rule always
true, SQL inheriting the default) fails at least one. Live gate re-run read-only against
AVEVA 2023 R2 via a private HistorianGateway fa9cf31 container: SysPulse TimeAverage on the
wire = BadAggregateNotSupported, health failures unchanged; #801 gate 244 cases pass.

Claude-Session: https://claude.ai/code/session_01GT67ACmpMR7b9LGRPLijMi
This commit is contained in:
Joseph Doherty
2026-11-13 00:41:32 -05:00
parent 2e537dc6ca
commit ee39c169df
17 changed files with 506 additions and 6 deletions
@@ -979,6 +979,103 @@ public sealed class NodeManagerHistoryReadTests : IDisposable
finally { await host.DisposeAsync(); }
}
private static ReadProcessedDetails ProcessedDetails(NodeId aggregate) => new()
{
StartTime = DateTime.UtcNow.AddHours(-1),
EndTime = DateTime.UtcNow,
ProcessingInterval = 10_000.0,
AggregateConfiguration = new AggregateConfiguration { UseServerCapabilitiesDefaults = true },
AggregateType = new List<NodeId> { aggregate },
};
/// <summary>
/// lmxopcua#897 — Part 11 §6.5.4 ("If the Aggregate is not valid for the Node then the StatusCode shall be
/// Bad_AggregateNotSupported") with Part 13 Table 50 (TimeAverage, Total, Average, … are numeric only): a String or
/// DateTime node asked for a numeric aggregate is refused up front on EVERY backend, without a backend call, while
/// an all-types aggregate (Count) on the same node and the numeric one on a numeric node still reach the backend.
/// </summary>
[Theory]
[InlineData("String", "TimeAverage")]
[InlineData("String", "Total")]
[InlineData("String", "Average")]
[InlineData("String", "Maximum")]
[InlineData("DateTime", "TimeAverage")]
[InlineData("DateTime", "Delta")]
public async Task A_numeric_aggregate_on_a_non_numeric_node_is_refused_unsent(string dataType, string aggregate)
{
var (host, server) = await BootAsync();
try
{
var nm = server.NodeManager!;
var fake = new RecordingHistorianDataSource { ProcessedResult = Empty() };
nm.HistorianDataSource = fake;
nm.EnsureVariable("eq/text", null, "Text", dataType, false, historianTagname: "T.Text", realm: AddressSpaceRealm.Uns);
nm.EnsureVariable("eq/num", null, "Num", "Double", false, historianTagname: "T.Num", realm: AddressSpaceRealm.Uns);
var aggregateId = aggregate switch
{
"TimeAverage" => ObjectIds.AggregateFunction_TimeAverage,
"Total" => ObjectIds.AggregateFunction_Total,
"Average" => ObjectIds.AggregateFunction_Average,
"Maximum" => ObjectIds.AggregateFunction_Maximum,
_ => ObjectIds.AggregateFunction_Delta,
};
var (_, errors) = InvokeHistoryRead(server, nm, ProcessedDetails(aggregateId), nm.TryGetVariable("eq/text")!.NodeId);
errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadAggregateNotSupported.Code);
fake.LastCall.ShouldBeNull("the refusal is decided before any backend read");
// Positive controls: an all-types aggregate on the same node, and the same aggregate on a numeric node.
InvokeHistoryRead(server, nm, ProcessedDetails(ObjectIds.AggregateFunction_Count), nm.TryGetVariable("eq/text")!.NodeId)
.Item2[0].StatusCode.Code.ShouldBe(StatusCodes.Good.Code);
fake.LastCall.ShouldBe("Processed");
fake.LastAggregate.ShouldBe(HistoryAggregateType.Count);
InvokeHistoryRead(server, nm, ProcessedDetails(aggregateId), nm.TryGetVariable("eq/num")!.NodeId)
.Item2[0].StatusCode.Code.ShouldBe(StatusCodes.Good.Code);
fake.LastTagname.ShouldBe("T.Num");
}
finally { await host.DisposeAsync(); }
}
/// <summary>
/// lmxopcua#897: a backend's own per-type limit (<see cref="IHistorianDataSource.SupportsAggregateFor"/> — the
/// Gateway refuses native TimeAverage / Total on a Boolean node) is consulted with the node's scalar type and answers
/// <c>BadAggregateNotSupported</c> without a backend read; the same aggregate on another type, and another aggregate
/// on the Boolean node, are served.
/// </summary>
[Fact]
public async Task A_backend_per_type_refusal_answers_BadAggregateNotSupported_unsent()
{
var (host, server) = await BootAsync();
try
{
var nm = server.NodeManager!;
var fake = new RecordingHistorianDataSource
{
ProcessedResult = Empty(),
SupportsFor = (a, t) => !(t == TypeCode.Boolean && a == HistoryAggregateType.TimeAverage),
};
nm.HistorianDataSource = fake;
nm.EnsureVariable("eq/pulse", null, "Pulse", "Boolean", false, historianTagname: "SysPulse", realm: AddressSpaceRealm.Uns);
nm.EnsureVariable("eq/sec", null, "Sec", "Int32", false, historianTagname: "SysTimeSec", realm: AddressSpaceRealm.Uns);
var pulse = nm.TryGetVariable("eq/pulse")!.NodeId;
var (_, errors) = InvokeHistoryRead(server, nm, ProcessedDetails(ObjectIds.AggregateFunction_TimeAverage), pulse);
errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadAggregateNotSupported.Code);
fake.LastCall.ShouldBeNull();
fake.SupportsForCalls.ShouldContain((HistoryAggregateType.TimeAverage, (TypeCode?)TypeCode.Boolean),
"the node's scalar type is what the backend is asked about");
InvokeHistoryRead(server, nm, ProcessedDetails(ObjectIds.AggregateFunction_Average), pulse)
.Item2[0].StatusCode.Code.ShouldBe(StatusCodes.Good.Code);
fake.LastAggregate.ShouldBe(HistoryAggregateType.Average);
InvokeHistoryRead(server, nm, ProcessedDetails(ObjectIds.AggregateFunction_TimeAverage), nm.TryGetVariable("eq/sec")!.NodeId)
.Item2[0].StatusCode.Code.ShouldBe(StatusCodes.Good.Code);
fake.LastTagname.ShouldBe("SysTimeSec");
fake.LastAggregate.ShouldBe(HistoryAggregateType.TimeAverage);
}
finally { await host.DisposeAsync(); }
}
private static HistorianRead Empty() => new(Array.Empty<DataValueSnapshot>(), null);
/// <summary>A recording fake historian source — captures the last call's kind + arguments and returns
@@ -992,6 +1089,13 @@ public sealed class NodeManagerHistoryReadTests : IDisposable
public bool LimitExceeded { get; init; }
public IReadOnlySet<HistoryAggregateType>? Supported { get; init; } = HistoryAggregateTypes.All;
public IReadOnlySet<HistoryAggregateType> SupportedAggregates => Supported!;
public Func<HistoryAggregateType, TypeCode?, bool>? SupportsFor { get; init; }
public List<(HistoryAggregateType Aggregate, TypeCode? Type)> SupportsForCalls { get; } = [];
public bool SupportsAggregateFor(HistoryAggregateType aggregate, TypeCode? valueType)
{
lock (SupportsForCalls) SupportsForCalls.Add((aggregate, valueType));
return SupportsFor?.Invoke(aggregate, valueType) ?? true;
}
public HistorianRead RawResult { get; set; } = new(Array.Empty<DataValueSnapshot>(), null);
public HistorianRead ProcessedResult { get; set; } = new(Array.Empty<DataValueSnapshot>(), null);
public HistorianRead AtTimeResult { get; set; } = new(Array.Empty<DataValueSnapshot>(), null);