R1.2 GetRuntimeParameter + string-handle wall RESOLVED (handle-format bug)

Execute HCAL roadmap R1.2 (GetRuntimeParameterAsync) end-to-end, and in doing so
discover that the "string-handle wall" blocking R1.1/R1.4/R1.5/R1.6 was a handle
FORMAT bug, not a missing native session/filter registration.

R1.2 (shipped, live-verified):
- Captured native GetRuntimeParameter -> WCF op aa/Stat/GETRP (string-handle op,
  GETHI's shape), via scripts/Capture-RuntimeParam.ps1 + instrument-wcf-{write,read}message.
- HistorianRuntimeParameterProtocol serializes pRequestBuff (54 67 01 00 + uint
  nameCount + per-name uint charCount + UTF-16) and parses pResponseBuff (version +
  uint resultCount + CRetVariant 0x43 VT_BSTR + uint16 len + uint16 charCount + UTF-16).
- IStatusServiceContract2.GetRuntimeParameter (GETRP) op; HistorianWcfStatusClient
  passes the Open2 storage-session GUID as the string handle, UPPERCASE.
- Public HistorianClient.GetRuntimeParameterAsync(name) via the dialect.
- Golden WcfRuntimeParameterProtocolTests + gated live test; returns HistorianVersion.

String-handle wall RESOLVED (proven, public APIs deferred):
- The Open2 storage GUID works as the string handle when sent UPPERCASE
  (ToString("D").ToUpperInvariant()); earlier "blocked" probes used lowercase.
- Live-probed GETHI (R1.4) -> returns data; ExeC (R1.1) -> Retr.GetV prime -> ExeC ->
  GetR returns a BinaryFormatter-serialized .NET DataTable. Gated
  StringHandleProbeDiagnosticTests + scripts/Capture-ExecSql.ps1 + exec-sql harness scenario.
- Docs flipped: wcf-string-handle-wall.md RESOLVED banner; roadmap R1.1/R1.4 reachable,
  R1.5/R1.6 likely; wcf-status-localhost.md GETRP section.
- R1.1/R1.4 public APIs NOT shipped: ExeC needs a GetR paging loop + a BinaryFormatter-
  stream parser (BinaryFormatter is removed from .NET 10); GETHI full-info struct needs
  its own capture.

223 unit tests pass; gated live tests green against the local 2020 Historian.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B6mcaT2PjRFKcogzp9UkfC
This commit is contained in:
Joseph Doherty
2026-06-20 22:10:31 -04:00
parent 6d470eab4a
commit 4da5287d01
15 changed files with 953 additions and 16 deletions
@@ -154,6 +154,18 @@ public sealed class HistorianClient : IAsyncDisposable
return _protocol.GetSystemParameterAsync(name, cancellationToken);
}
/// <summary>
/// Reads a named Historian <em>runtime</em> parameter (the live server state surface,
/// distinct from the configuration <see cref="GetSystemParameterAsync"/>). Returns the
/// string value, or null when the server reports no value. Single string-valued parameters
/// only (the evidence-backed surface); see <c>HistorianRuntimeParameterProtocol</c>.
/// </summary>
public Task<string?> GetRuntimeParameterAsync(string name, CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(name);
return _protocol.GetRuntimeParameterAsync(name, cancellationToken);
}
/// <summary>
/// Creates or updates the named tag in the Historian Runtime database via
/// <c>EnsureTags2</c>. Currently only <see cref="HistorianDataType.Float"/> is
@@ -67,6 +67,13 @@ internal sealed class Historian2020ProtocolDialect
return Wcf.HistorianWcfStatusClient.GetSystemParameterAsync(_options, name, cancellationToken);
}
public Task<string?> GetRuntimeParameterAsync(string name, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
ArgumentException.ThrowIfNullOrWhiteSpace(name);
return Wcf.HistorianWcfStatusClient.GetRuntimeParameterAsync(_options, name, cancellationToken);
}
private static async IAsyncEnumerable<T> Missing<T>(
string operation,
[System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken)
@@ -29,6 +29,14 @@ internal interface IStatusServiceContract2 : IStatusServiceContract
[MessageParameter(Name = "pResponseBuff")] out byte[] responseBuffer,
out byte[] errorBuffer);
[OperationContract(Name = "GETRP")]
[return: MarshalAs(UnmanagedType.U1)]
bool GetRuntimeParameter(
string handle,
[MessageParameter(Name = "pRequestBuff")] byte[] requestBuffer,
[MessageParameter(Name = "pResponseBuff")] out byte[] responseBuffer,
out byte[] errorBuffer);
[OperationContract(Name = "PNGS")]
[return: MarshalAs(UnmanagedType.U1)]
bool PingServer(string handle, string pipeName, uint timeout, ref byte[] errorBuffer);
@@ -0,0 +1,104 @@
using System.Buffers.Binary;
using System.Text;
using AVEVA.Historian.Client.Protocol;
namespace AVEVA.Historian.Client.Wcf;
/// <summary>
/// Serializes the <c>GETRP</c> (GetRuntimeParameter) request buffer and parses its response
/// buffer for AVEVA Historian 2020 over WCF/MDAS.
/// </summary>
/// <remarks>
/// Wire format captured from the native client (<c>scripts/Capture-RuntimeParam.ps1</c> +
/// instrument-wcf-{write,read}message; golden-pinned in <c>WcfRuntimeParameterProtocolTests</c>).
/// The op is <c>aa/Stat/GETRP(string handle, byte[] pRequestBuff) -&gt; (bool, byte[]
/// pResponseBuff, byte[] errorBuffer)</c> — the same string-handle + request/response-buffer
/// shape as <c>GETHI</c>.
///
/// <para><b>pRequestBuff</b> (44 bytes for one name "HistorianVersion"):
/// <c>54 67</c> signature · <c>01 00</c> version(1) · uint32 nameCount · then per name:
/// uint32 charCount + UTF-16LE chars.</para>
///
/// <para><b>pResponseBuff</b>: <c>01 00</c> version(1) · uint32 resultCount · then per result a
/// CRetVariant: <c>0x43</c> (VT_BSTR) + uint16 payloadLength + uint16 charCount + UTF-16LE chars.
/// Only the string variant (0x43) is evidence-backed; other variant types throw.</para>
///
/// <para>Only a single string-valued parameter is exercised against the live server; the
/// multi-name framing is inferred from the count field and not yet captured.</para>
/// </remarks>
internal static class HistorianRuntimeParameterProtocol
{
// Captured constant prefix of pRequestBuff: signature 0x6754 + version 0x0001.
private static ReadOnlySpan<byte> RequestHeader => [0x54, 0x67, 0x01, 0x00];
private const byte VariantTypeBStr = 0x43;
public static byte[] SerializeRequest(string parameterName)
{
ArgumentException.ThrowIfNullOrEmpty(parameterName);
using MemoryStream stream = new();
using BinaryWriter writer = new(stream, Encoding.Unicode, leaveOpen: true);
writer.Write(RequestHeader); // 54 67 01 00
writer.Write(1u); // name count = 1
WriteName(writer, parameterName);
writer.Flush();
return stream.ToArray();
}
private static void WriteName(BinaryWriter writer, string name)
{
writer.Write((uint)name.Length); // char count
writer.Write(Encoding.Unicode.GetBytes(name));
}
/// <summary>
/// Parses the first string-valued result out of the GETRP response buffer, or null when the
/// buffer carries no result. Throws <see cref="ProtocolEvidenceMissingException"/> for any
/// non-string variant type (not yet captured).
/// </summary>
public static string? ParseSingleStringResult(ReadOnlySpan<byte> responseBuffer)
{
if (responseBuffer.Length < 6)
{
return null;
}
// [0..2) version, [2..6) result count.
uint resultCount = BinaryPrimitives.ReadUInt32LittleEndian(responseBuffer.Slice(2, 4));
if (resultCount == 0)
{
return null;
}
ReadOnlySpan<byte> cursor = responseBuffer[6..];
if (cursor.Length < 1)
{
return null;
}
byte variantType = cursor[0];
if (variantType != VariantTypeBStr)
{
throw new ProtocolEvidenceMissingException(
$"GETRP response variant type 0x{variantType:X2} is not the evidence-backed string variant (0x43).");
}
if (cursor.Length < 5)
{
return null;
}
ushort charCount = BinaryPrimitives.ReadUInt16LittleEndian(cursor.Slice(3, 2));
int byteCount = charCount * 2;
ReadOnlySpan<byte> valueBytes = cursor.Slice(5);
if (valueBytes.Length < byteCount)
{
byteCount = valueBytes.Length - (valueBytes.Length % 2);
}
return Encoding.Unicode.GetString(valueBytes[..byteCount]);
}
}
@@ -17,6 +17,19 @@ internal static class HistorianWcfStatusClient
return Task.Run(() => GetSystemParameter(options, parameterName), cancellationToken);
}
/// <summary>Diagnostic: the GETRP return code / error description from the last
/// <see cref="GetRuntimeParameterAsync"/> call (set only when the server rejects it).</summary>
public static string? LastRuntimeParameterError { get; private set; }
public static Task<string?> GetRuntimeParameterAsync(
HistorianClientOptions options,
string parameterName,
CancellationToken cancellationToken)
{
ArgumentException.ThrowIfNullOrWhiteSpace(parameterName);
return Task.Run(() => GetRuntimeParameter(options, parameterName), cancellationToken);
}
public static Task<HistorianConnectionStatus> GetConnectionStatusAsync(
HistorianClientOptions options,
CancellationToken cancellationToken)
@@ -45,6 +58,49 @@ internal static class HistorianWcfStatusClient
return value;
}
private static string? GetRuntimeParameter(HistorianClientOptions options, string parameterName)
{
Guid contextKey = Guid.NewGuid();
var (histBinding, histEndpoint, _, _) = HistorianWcfBindingFactory.CreateBindingPair(options);
Binding statusBinding = HistorianWcfBindingFactory.CreateAuxiliaryBinding(options);
EndpointAddress statusEndpoint = HistorianWcfBindingFactory.CreateAuxiliaryEndpointAddress(options, HistorianWcfServiceNames.Status);
string? value = null;
LastRuntimeParameterError = null;
HistorianWcfAuthChainHelper.OpenAuthenticatedConnection(
options, histBinding, histEndpoint, contextKey, CancellationToken.None,
additionalSetup: (_, context) => value = QueryRuntimeParameter(statusBinding, statusEndpoint, context.StorageSessionId, parameterName));
return value;
}
private static string? QueryRuntimeParameter(Binding statusBinding, EndpointAddress statusEndpoint, Guid storageSessionId, string parameterName)
{
// GETRP takes the storage-session GUID as a string handle, formatted exactly as the
// native client sends it: uppercase, dash-separated, no braces.
string handle = storageSessionId.ToString("D").ToUpperInvariant();
byte[] requestBuffer = HistorianRuntimeParameterProtocol.SerializeRequest(parameterName);
ChannelFactory<IStatusServiceContract2> factory = new(statusBinding, statusEndpoint);
IStatusServiceContract2 channel = factory.CreateChannel();
ICommunicationObject co = (ICommunicationObject)channel;
try
{
bool ok = channel.GetRuntimeParameter(handle, requestBuffer, out byte[] responseBuffer, out byte[] errorBuffer);
if (!ok)
{
LastRuntimeParameterError = $"GETRP returned false (responseLen={responseBuffer?.Length ?? 0}, errorLen={errorBuffer?.Length ?? 0}).";
return null;
}
return HistorianRuntimeParameterProtocol.ParseSingleStringResult(responseBuffer ?? []);
}
finally
{
try { if (co.State == CommunicationState.Faulted) co.Abort(); else co.Close(); } catch { try { co.Abort(); } catch { } }
try { if (factory.State == CommunicationState.Faulted) factory.Abort(); else factory.Close(); } catch { try { factory.Abort(); } catch { } }
}
}
private static string? QuerySystemParameter(Binding statusBinding, EndpointAddress statusEndpoint, uint clientHandle, string parameterName)
{
ChannelFactory<IStatusServiceContract2> factory = new(statusBinding, statusEndpoint);