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
@@ -273,6 +273,29 @@ public sealed class HistorianClientIntegrationTests
Assert.False(string.IsNullOrWhiteSpace(value));
}
[Fact]
public async Task GetRuntimeParameterAsync_AgainstLocalHistorian_ReturnsHistorianVersion()
{
string? host = Environment.GetEnvironmentVariable("HISTORIAN_HOST");
if (string.IsNullOrWhiteSpace(host) || !string.Equals(host, "localhost", StringComparison.OrdinalIgnoreCase) || !OperatingSystem.IsWindows())
{
return;
}
HistorianClient client = new(new HistorianClientOptions
{
Host = host,
IntegratedSecurity = true,
Transport = HistorianTransport.LocalPipe
});
// GETRP rides the storage-session GUID as an uppercase string handle. HistorianVersion is
// a known-good runtime parameter returning the server version (e.g. "20,0,000,000").
string? value = await client.GetRuntimeParameterAsync("HistorianVersion", CancellationToken.None);
Assert.False(string.IsNullOrWhiteSpace(value));
}
[Fact]
public async Task GetConnectionStatusAsync_AgainstLocalHistorian_ReportsConnectedToServer()
{
@@ -0,0 +1,156 @@
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Text;
using System.Runtime.Versioning;
using AVEVA.Historian.Client.Wcf;
using AVEVA.Historian.Client.Wcf.Contracts;
using Xunit.Abstractions;
namespace AVEVA.Historian.Client.Tests;
/// <summary>
/// Diagnostic: retest the "string-handle wall" ops (GETHI / ExeC) using the Open2
/// storage-session GUID formatted UPPERCASE (the format the native client sends, and the
/// one that made GETRP punch through). Not an assertion test — it prints the server's
/// return code / buffer lengths so we can judge whether the wall is a handle-format issue.
/// </summary>
[SupportedOSPlatform("windows")]
public sealed class StringHandleProbeDiagnosticTests
{
private readonly ITestOutputHelper _output;
public StringHandleProbeDiagnosticTests(ITestOutputHelper output)
{
_output = output;
}
private static bool ShouldRun(out string host)
{
host = Environment.GetEnvironmentVariable("HISTORIAN_HOST") ?? string.Empty;
return !string.IsNullOrWhiteSpace(host)
&& string.Equals(host, "localhost", StringComparison.OrdinalIgnoreCase)
&& OperatingSystem.IsWindows();
}
[Fact]
public void GETHI_WithUppercaseStorageGuid_AgainstLocalHistorian()
{
if (!ShouldRun(out string host)) return;
HistorianClientOptions options = new()
{
Host = host,
IntegratedSecurity = true,
Transport = HistorianTransport.LocalPipe
};
// Native GETHI pRequestBuff: 53 67 02 00 (sig 0x6753 + version 2) + uint charCount + UTF-16 name.
const string name = "HistorianVersion";
using MemoryStream ms = new();
using (BinaryWriter w = new(ms, Encoding.Unicode, leaveOpen: true))
{
w.Write(new byte[] { 0x53, 0x67, 0x02, 0x00 });
w.Write((uint)name.Length);
w.Write(Encoding.Unicode.GetBytes(name));
}
byte[] requestBuffer = ms.ToArray();
ProbeOnStatusChannel(options, (channel, handle) =>
{
bool ok = channel.GetHistorianInfo(handle, requestBuffer, out byte[] resp, out byte[] err);
_output.WriteLine($"GETHI returned={ok} respLen={resp?.Length ?? 0} errLen={err?.Length ?? 0}");
if (resp is { Length: > 0 })
{
_output.WriteLine(" resp[0..64]=" + Convert.ToHexString(resp.AsSpan(0, Math.Min(64, resp.Length))));
}
});
}
[Fact]
public void ExeC_WithUppercaseStorageGuid_AgainstLocalHistorian()
{
if (!ShouldRun(out string host)) return;
HistorianClientOptions options = new()
{
Host = host,
IntegratedSecurity = true,
Transport = HistorianTransport.LocalPipe
};
Guid contextKey = Guid.NewGuid();
var (histBinding, histEndpoint, retrBinding, retrEndpoint) = HistorianWcfBindingFactory.CreateBindingPair(options);
HistorianWcfAuthChainHelper.OpenAuthenticatedConnection(
options, histBinding, histEndpoint, contextKey, CancellationToken.None,
additionalSetup: (_, context) =>
{
string handle = context.StorageSessionId.ToString("D").ToUpperInvariant();
ChannelFactory<IRetrievalServiceContract3> factory = new(retrBinding, retrEndpoint);
HistorianWcfClientCredentialsHelper.Configure(factory, options);
IRetrievalServiceContract3 channel = factory.CreateChannel();
ICommunicationObject co = (ICommunicationObject)channel;
try
{
// Prime the Retr service version handshake (Retr.GetV), as the native client does.
channel.GetInterfaceVersion(out uint retrVersion);
_output.WriteLine($"Retr.GetV version={retrVersion}");
uint queryHandle = 0;
bool execOk = channel.ExecuteSqlCommand(
handle, "SELECT 1 AS ProbeValue", 0u, ref queryHandle,
out int retValue, out uint errSize, out byte[] errBuf);
_output.WriteLine($"ExeC returned={execOk} retValue={retValue} queryHandle={queryHandle} errSize={errSize} errLen={errBuf?.Length ?? 0}");
if (execOk)
{
uint sequence = 0;
bool getrOk = channel.GetRecordSetByteStream(
handle, queryHandle, ref sequence,
out uint resultSize, out byte[] resultBuf, out uint gErrSize, out byte[] gErrBuf);
_output.WriteLine($"GetR returned={getrOk} resultSize={resultSize} resultLen={resultBuf?.Length ?? 0} sequence={sequence}");
if (resultBuf is { Length: > 0 })
{
_output.WriteLine(" result[0..96]=" + Convert.ToHexString(resultBuf.AsSpan(0, Math.Min(96, resultBuf.Length))));
}
}
}
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 void ProbeOnStatusChannel(HistorianClientOptions options, Action<IStatusServiceContract2, string> probe)
{
Guid contextKey = Guid.NewGuid();
var (histBinding, histEndpoint, _, _) = HistorianWcfBindingFactory.CreateBindingPair(options);
Binding statusBinding = HistorianWcfBindingFactory.CreateAuxiliaryBinding(options);
EndpointAddress statusEndpoint = HistorianWcfBindingFactory.CreateAuxiliaryEndpointAddress(options, HistorianWcfServiceNames.Status);
HistorianWcfAuthChainHelper.OpenAuthenticatedConnection(
options, histBinding, histEndpoint, contextKey, CancellationToken.None,
additionalSetup: (_, context) =>
{
string handle = context.StorageSessionId.ToString("D").ToUpperInvariant();
ChannelFactory<IStatusServiceContract2> factory = new(statusBinding, statusEndpoint);
IStatusServiceContract2 channel = factory.CreateChannel();
ICommunicationObject co = (ICommunicationObject)channel;
try
{
probe(channel, handle);
}
catch (Exception ex)
{
throw new InvalidOperationException($"probe raised: {ex.GetType().Name}: {ex.Message}", ex);
}
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 { } }
}
});
}
}
@@ -0,0 +1,58 @@
using AVEVA.Historian.Client.Protocol;
using AVEVA.Historian.Client.Wcf;
namespace AVEVA.Historian.Client.Tests;
public sealed class WcfRuntimeParameterProtocolTests
{
// GETRP pRequestBuff captured from the native client for GetRuntimeParameter("HistorianVersion")
// via scripts/Capture-RuntimeParam.ps1 + instrument-wcf-writemessage:
// 54 67 01 00 signature(0x6754) + version(1)
// 01 00 00 00 name count = 1
// 10 00 00 00 char count = 16
// UTF-16LE "HistorianVersion"
private const string CaptureRequestHex =
"54670100010000001000000048006900730074006F007200690061006E00560065007200730069006F006E00";
// GETRP pResponseBuff captured from the paired GETRPResponse (instrument-wcf-readmessage):
// 01 00 version = 1
// 01 00 00 00 result count = 1
// 43 CRetVariant type 0x43 (VT_BSTR)
// 1A 00 payload length = 26 (= charCount field + string bytes)
// 0C 00 char count = 12
// UTF-16LE "20,0,000,000"
private const string CaptureResponseHex =
"010001000000431A000C00320030002C0030002C003000300030002C00300030003000";
[Fact]
public void SerializeRequestMatchesInstrumentedNativeRequestBuffer()
{
byte[] actual = HistorianRuntimeParameterProtocol.SerializeRequest("HistorianVersion");
Assert.Equal(Convert.FromHexString(CaptureRequestHex), actual);
}
[Fact]
public void ParseSingleStringResultReadsTheCapturedResponseValue()
{
byte[] response = Convert.FromHexString(CaptureResponseHex);
string? value = HistorianRuntimeParameterProtocol.ParseSingleStringResult(response);
Assert.Equal("20,0,000,000", value);
}
[Fact]
public void ParseSingleStringResultReturnsNullForZeroResultCount()
{
// version(1) + result count(0)
byte[] empty = [0x01, 0x00, 0x00, 0x00, 0x00, 0x00];
Assert.Null(HistorianRuntimeParameterProtocol.ParseSingleStringResult(empty));
}
[Fact]
public void ParseSingleStringResultThrowsForUncapturedVariantType()
{
// version(1) + count(1) + a non-string variant marker (0x03, VT_I4 — not captured).
byte[] buffer = [0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x03, 0x04, 0x00, 0x00, 0x00, 0x00];
Assert.Throws<ProtocolEvidenceMissingException>(
() => HistorianRuntimeParameterProtocol.ParseSingleStringResult(buffer));
}
}