Files
Marc Schier b2b4dbb13f [Server] Part 13 Aggregates compliance fixes, full test coverage and docs (#3863)
# Description

Brings the server-side **OPC UA Part 13 (Aggregates) v1.05.07** support
to full conformance: fixes the three genuine non-compliances found by a
spec review, completes value-validated test coverage for **all 37
standard aggregate functions**, and adds documentation. The existing
aggregate engine is a faithful port and was already largely compliant;
this PR closes the remaining gaps.

## Compliance fixes

- **`TreatUncertainAsBad` default (§4.2.1.2).** The server-default
`AggregateConfiguration` (used when a `ReadProcessedDetails` request
sets `UseServerCapabilitiesDefaults = true`) now defaults
`TreatUncertainAsBad` to **`True`** as the spec mandates, in both
`AggregateManager.GetDefaultConfiguration` and the `HistorianDispatcher`
fallback. Behavior change noted in `MigrationGuide.md`.
- **`AnnotationCount` (§5.4.3.20).** Previously counted raw data values.
It now counts **Annotations** per interval, computed in
`HistorianDispatcher.DispatchProcessedReadAsync` from
`IHistorianAnnotationProvider` (endTime-exclusive bucketing;
reverse-time and `ProcessingInterval == 0` handled). Returns
`Bad_AggregateNotSupported` when the provider has no annotation history.
- **StandardDeviation/Variance use all n Good raw values
(§5.4.3.37/.39).** `ComputeStdDev` previously computed over the N−1
sub-regions returned by `GetRegionsInValueSet`, silently dropping the
last raw value. It now computes the mean/variance directly over all Good
raw values in the interval (UseBounds = None), differing only by the
divisor (sample n−1, population n). The population spec-example tests
that used to add a duplicate trailing value as a workaround were updated
to the natural 5-value datasets matching §A.35/.37.

## Tests

- **Calculator coverage is complete for all 37 aggregates** — added
`StatusAggregateCalculatorTests` (DurationGood/Bad, PercentGood/Bad,
WorstQuality/WorstQuality2), the Min/Max `*2` simple-bound variants
(`Minimum2`/`Maximum2`/`Range2`/`MinimumActualTime2`/`MaximumActualTime2`),
and `Interpolative`.
- **End-to-end integration** in `HistoryClientIntegrationTests` over the
live in-process ReferenceServer: value-validated
`Average`/`Minimum`/`Maximum` processed reads and an **AnnotationCount**
write→read round-trip.
- **Dispatcher-level** `AnnotationCount` tests (counts per interval;
`Bad_AggregateNotSupported` without an annotation provider).
- **Tightened `AggregateBaseTests`**: dropped `allowAnyResult` from
`StandardDeviationSample`/`StandardDeviationPopulation`/`NumberOfTransitions`
basecases (now deterministic on seeded data after the D3 fix).
- **Validation tests** for `AggregateConfiguration` per §4.2.1.2:
`PercentDataBad`/`PercentDataGood > 100` and the invalid relationship
`PercentDataGood < (100 - PercentDataBad)`.
- **Cross-cutting**: reversed time-range test (start > end).

## Verification

- Builds: **0 warnings / 0 errors**.
- Aggregate + historian dispatcher + History integration suites green on
**.NET 10** and **.NET Framework 4.8** (cross-TFM).
- Black-box (MCP) check against a standalone `ConsoleReferenceServer`:
both `Server.ServerCapabilities.AggregateFunctions` and
`HistoryServerCapabilities.AggregateFunctions` advertise all 37
functions (§4.2.2.1).

## Notes / out of scope

- AnnotationCount advertisement remains the full standard set with
per-node `Bad_AggregateNotSupported`. This is spec-acceptable: §4.2.2.1
lists what the server *can* support; per-node refinement is the optional
`HistoricalConfiguration.AggregateFunctions`. Conditional advertisement
could be added later as a quality refinement.
- A native-vs-framework-fallback parity test would be useful once a
third-party `IHistorianProcessedProvider` implementation exists; the
bundled `InMemoryHistorianProvider` uses only the framework fallback
today.

## Related Issues

_No existing tracking issue; this addresses OPC 10000-13 (Part 13,
Aggregates) v1.05.07 conformance gaps. Maintainers: please link or open
a tracking issue if one is required._

## Checklist

- [ ] I have signed the
[CLA](https://opcfoundation.org/license/cla/ContributorLicenseAgreementv1.0.pdf)
and read the
[CONTRIBUTING](https://github.com/OPCFoundation/UA-.NETStandard/blob/master/CONTRIBUTING.md)
doc.
- [x] I have added tests that prove my fix is effective or that my
feature works and increased code coverage.
- [x] I have added all necessary documentation.
- [x] I have verified that my changes do not introduce (new) build or
analyzer warnings.
- [ ] I ran **all** tests locally using the **UA.slnx** solution against
at least .net **framework** and .net **10**, and all passed. _(Ran the
aggregate/historian/integration suites on net48 + net10; full-solution
run pending CI.)_
- [ ] I fixed **all** failing and flaky tests in the CI pipelines and
**all** CodeQL warnings.
- [ ] I have addressed **all** PR feedback received.
2026-06-10 08:34:09 +02:00

232 lines
7.8 KiB
C#

/* ========================================================================
* Copyright (c) 2005-2025 The OPC Foundation, Inc. All rights reserved.
*
* OPC Foundation MIT License 1.00
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* The complete license agreement can be found here:
* http://opcfoundation.org/License/MIT/1.00/
* ======================================================================*/
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Opc.Ua.Server
{
/// <summary>
/// An object that manages aggregate factories supported by the server.
/// </summary>
public class AggregateManager : IDisposable
{
/// <summary>
/// Initilizes the manager.
/// </summary>
public AggregateManager(IServerInternal server)
{
m_server = server;
m_factories = [];
m_minimumProcessingInterval = 1000;
}
/// <summary>
/// Frees any unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// An overrideable version of the Dispose.
/// </summary>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// TBD
}
}
/// <summary>
/// Checks if the aggregate is supported by the server.
/// </summary>
/// <param name="aggregateId">The id of the aggregate function.</param>
/// <returns>True if the aggregate is supported.</returns>
public bool IsSupported(NodeId aggregateId)
{
if (aggregateId.IsNull)
{
return false;
}
lock (m_lock)
{
return m_factories.ContainsKey(aggregateId);
}
}
/// <summary>
/// The minimum processing interval for any aggregate calculation.
/// </summary>
public double MinimumProcessingInterval
{
get
{
lock (m_lock)
{
return m_minimumProcessingInterval;
}
}
set
{
lock (m_lock)
{
m_minimumProcessingInterval = value;
}
}
}
/// <summary>
/// Returns the default configuration for the specified variable id.
/// </summary>
/// <param name="variableId">The id of history data node.</param>
/// <returns>The configuration.</returns>
public AggregateConfiguration GetDefaultConfiguration(NodeId variableId)
{
lock (m_lock)
{
m_defaultConfiguration ??= new AggregateConfiguration
{
PercentDataBad = 100,
PercentDataGood = 100,
// Part 13 v1.05.07 §4.2.1.2: the TreatUncertainAsBad default is True.
TreatUncertainAsBad = true,
UseSlopedExtrapolation = false,
UseServerCapabilitiesDefaults = false
};
return m_defaultConfiguration;
}
}
/// <summary>
/// Sets the default aggregate configuration.
/// </summary>
/// <param name="configuration">The default aggregate configuration..</param>
public void SetDefaultConfiguration(AggregateConfiguration configuration)
{
lock (m_lock)
{
m_defaultConfiguration = configuration;
}
}
/// <summary>
/// Creates a new aggregate calculator.
/// </summary>
/// <param name="aggregateId">The id of the aggregate function.</param>
/// <param name="startTime">When to start processing.</param>
/// <param name="endTime">When to stop processing.</param>
/// <param name="processingInterval">The processing interval.</param>
/// <param name="stepped">Whether stepped interpolation should be used.</param>
/// <param name="configuration">The configuration to use.</param>
public IAggregateCalculator? CreateCalculator(
NodeId aggregateId,
DateTimeUtc startTime,
DateTimeUtc endTime,
double processingInterval,
bool stepped,
AggregateConfiguration configuration)
{
if (aggregateId.IsNull)
{
return null;
}
AggregatorFactory? factory;
lock (m_lock)
{
if (!m_factories.TryGetValue(aggregateId, out factory))
{
return null;
}
}
if (configuration.UseServerCapabilitiesDefaults)
{
// ensure the configuration is initialized
configuration = GetDefaultConfiguration(default);
}
return factory!(
aggregateId,
startTime,
endTime,
processingInterval,
stepped,
configuration,
m_server.Telemetry);
}
/// <summary>
/// Registers an aggregate factory.
/// </summary>
/// <param name="aggregateId">The id of the aggregate function.</param>
/// <param name="aggregateName">The id of the aggregate name.</param>
/// <param name="factory">The factory used to create calculators.</param>
/// <param name="cancellationToken">A cancellation token.</param>
public async ValueTask RegisterFactoryAsync(
NodeId aggregateId,
string aggregateName,
AggregatorFactory factory,
CancellationToken cancellationToken = default)
{
lock (m_lock)
{
m_factories[aggregateId] = factory;
}
await m_server.DiagnosticsNodeManager.AddAggregateFunctionAsync(aggregateId, aggregateName, true, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Unregisters an aggregate factory.
/// </summary>
/// <param name="aggregateId">The id of the aggregate function.</param>
public void RegisterFactory(NodeId aggregateId)
{
lock (m_lock)
{
m_factories.Remove(aggregateId);
}
}
private readonly Lock m_lock = new();
private readonly IServerInternal m_server;
private AggregateConfiguration? m_defaultConfiguration;
private readonly NodeIdDictionary<AggregatorFactory> m_factories;
private double m_minimumProcessingInterval;
}
}