Merge #916/#917: stop sending stable_source_id (field 10 deprecated, never encoded/decoded); alarm-bearing raw tags are unsupported value nodes hidden from browse; review fixes

This commit is contained in:
Joseph Doherty
2026-11-28 10:43:51 -05:00
16 changed files with 548 additions and 21 deletions
+28 -4
View File
@@ -170,11 +170,35 @@ advertisement and a per-call request header, `x-otopcua-data-features`, whose va
- The new RPCs (`HistoryRead`, `CallConditionMethod`) answer `FailedPrecondition("feature not negotiated")`. A
history-only call is also refused `CallConditionMethod`.
- Header-less goldens (`*Goldens.cs`) and the recorded-v1-client gates (`GrpcDataV1CompatibilityTests`,
`GrpcDataV1RealOriginCompatibilityTests`) pin the v1 bytes. Every phase ran them with an empty goldens diff.
`GrpcDataV1RealOriginCompatibilityTests`) pin the v1 bytes. Every phase ran them with an empty goldens diff. The two
pre-deploy corrections below are the only deliberate differences. The real-origin gate applies them to the recorded
goldens in `GrpcDataV1RealOriginCorrections`; the goldens are never re-recorded.
Fix two v1 defects before any v1 deploy. #916: `stable_source_id` leaks the driver id and RawPath to UNS-only peers.
#917: v1 exports alarm-bearing raw tags as variables that never get a value. G0, the v1 deploy and soak (#915), is still
open; see the plan's §1.1.
### What an origin exports (v1 corrections #916, #917)
v1 was merged but not deployed (#915), so two defects were fixed in v1 itself. Header-less callers get the fix too.
Neither change alters the wire shape: one drops an optional field, the other drops a page item. Evidence: `docs/plans/evidence/grpc-data-ext/V1-916-917.md`.
- **No `Metadata.stable_source_id` (#916).** The origin never sends field 10. It used to carry the internal acquisition key,
which for a driver tag is `<len>:<driverInstanceId><RawPath>`. That disclosed driver ids and RawPaths to peers holding
only a UNS export.
- No consumer used the field except for byte accounting, so it was dropped rather than replaced by an opaque id. A
stable opaque id would only let a peer correlate Raw and UNS nodes.
- The field is `optional`. Old consumers decode its absence as null, so every version mix works.
- Conditions dedupe on the keyed `condition_key` instead.
- Internally the origin still keys acquisition on the unchanged `BackingSourceKey`.
- **Alarm-bearing raw tags are not exported as values (#917).** A tag with an alarm config never gets a value: the driver
host keeps it out of the value fan-out, and #896 gives it no UNS variable.
- The origin compiles it as an unsupported value node. GetMetadata, Read, Subscribe and HistoryRead on it answer
`Unsupported`, and writes are refused.
- **Browse does not list it**, and the same holds for any unsupported value node, such as a data type v1 cannot carry.
Every consumer build applies a browse page all or nothing and cannot materialise an `UnsupportedVariable`. Listing one
made the whole folder unbrowsable on the consumer (`BadNoCommunication`); the live gate found this.
- The node stays in the catalog, so an export rooted at it still compiles. Such a root grants nothing: the values are unsupported, and the condition sits under the tag's folder, not under the tag.
- The alarm itself is forwarded as a **condition** (A1–A4, see "Condition forwarding end to end"). Condition placements
do not depend on the value node.
G0, the v1 deploy and soak (#915), is still open; see the plan's §1.1.
## Remote history (runtime consumers)
@@ -647,7 +647,9 @@ per-origin-cluster `${secret:}` of at least 32 UTF-8 bytes, identical on both pa
- It cannot be dictionary-reversed from guessable paths. An unkeyed hash was rejected for that reason.
- If the secret is absent, the origin advertises no `conditions` capability (fail closed, with a diagnostic).
> **Pre-existing v1 findings (not fixed here; filed as #916 and #917):**
> **Pre-existing v1 findings (not fixed here; filed as #916 and #917).** *Update 2026-11-28: both are fixed in v1 before
> deploy. `stable_source_id` is no longer sent, and alarm-bearing raw tags are no longer value nodes (not listed by Browse, `Unsupported` on every value operation). See
> `docs/plans/evidence/grpc-data-ext/V1-916-917.md`.*
> 1. #916 — `type:review-finding`, security: v1 already sends `stable_source_id` = driver id + RawPath on **UNS reference variables**
> to UNS-only principals (same code path).
> 2. #917 — `type:bug`: v1 exports alarm-bearing raw tags as `Variable` (`LocalExportCatalog.Compilation.cs:120-130` has no Alarm
@@ -0,0 +1,180 @@
# v1 pre-deploy corrections: #916 and #917
Two defects in gRPC data connections v1 (merged `95c5e484`, never deployed, #915), found while planning remote history and
alarm forwarding (plan §5.2, "Pre-existing v1 findings"; N3). Both are fixed in the v1 origin catalog
(`LocalExportCatalog.Compilation.cs`), so header-less v1 callers get the fix too. Neither changes the wire shape.
## #916: `Metadata.stable_source_id` disclosed driver ids and RawPaths
**Defect.** `Compile` put `BackingSourceKey.StableSourceId` into `Metadata.stable_source_id` (proto field 10) on every value
node, in every realm. For a driver source that key is `SourceKey.ForDriver`'s `<len>:<driverInstanceId><driver reference>`,
and the reference is the RawPath. So a peer holding only a UNS export learned the origin's driver instance ids and RawPaths.
The recorded real-origin golden shows the leak: `Browse/uns` carries `8:driver-1Plant/Modbus/dev1/Speed` on the UNS Speed
reference.
**Consumer-side uses of the field (all of them).** Every read of `DataMetadata.StableSourceId` / `Metadata.stable_source_id`
in `src/`:
| Site | Use |
|---|---|
| `DataProtoMapper.EncodeMetadata` / `DecodeMetadata` | Copies it when present. Decodes absence as `null` (`HasStableSourceId`). |
| `ProjectedProofSize.cs:21` | Byte accounting of a proof. |
| `OtOpcUaNodeManager.cs:4439` | Byte accounting of a projected definition. |
Nothing dedupes on it, compares it, keys on it, or exposes it to the consumer's own OPC UA clients. It is not an OPC UA
property, not shown in the AdminUI and not logged. `DataSourceIdentity.StableSourceId` (Core.Abstractions) has no users.
A1–A4 dedupe conditions by the keyed `condition_key` (`ConditionKeys`), never by this field.
**Decision: omit the field on every export, in every realm.** We considered two alternatives:
- *A keyed opaque id* (HMAC like `condition_key`). Rejected. No consumer uses the field, so an opaque value would only be a
stable cross-realm correlator: it would tell a peer holding both a Raw and a UNS export that two nodes share a source.
It would also depend on `DataConnections:ConditionKeySecret`, which is optional, so the field would come and go with an
unrelated setting.
- *Omit only where the realm differs.* Rejected. A Raw export also does not need the internal key, and keeping one rule
is simpler to audit.
**Mixed versions.** Field 10 is `optional`. An old consumer decodes its absence as `null` and uses it for nothing but size
accounting, so an upgraded origin works with old consumers, and a new consumer works with an old origin (it ignores
the value).
One effect to know about: consumers compare whole `DataMetadata` records, field 10 included, when they renew a
projection (`ProjectedCatalogCache.SameMetadata`, `OtOpcUaNodeManager` projected-variable reuse). An origin pair running a
pre-fix build on one member and this build on the other would therefore look like a metadata change at failover, and the
node would be re-projected once. No pre-fix build was ever deployed (#915), so this cannot happen in the field.
The internal `BackingSourceKey` (on `LocalDataNode.Source`) is unchanged: acquisition, sample routing,
partitioning, write routes and `SourceKey.TryDriver` still use it.
## #917: alarm-bearing raw tags were exported as Variables that never get a value
**Defect.** `Compile` added every raw tag plan as a `Variable` with Read/Subscribe/HistoryRead. An alarm-bearing tag
(`RawTagPlan.Alarm != null`) never receives a value, because `DriverHostActor` keeps it out of the value fan-out and #896
gives it no UNS variable. So a consumer that imported one read `BadWaitingForInitialData` forever.
**Are these tags now forwarded as conditions?** Yes. Since A1–A4, every alarm-bearing raw tag gets a native condition
placement at its RawPath in Raw (parented at its device or group folder). Every UNS reference to one gets a placement at
the reserved `Area/Line/Equipment/EffectiveName` id, parented at the equipment. Both are listed through root-scoped
condition items and keyed by `condition_key`, and the consumer materialises them in its `mapped/conditions` namespace.
The alarm is therefore served as a condition, never as a value.
**Decision: compile the tag as an unsupported value node, and do not list it in Browse.** The rule is
`supported = plan.Alarm is null && …` in `Compile`. In `LocalDataServices.BrowseAsync`, a child with a `Source` and
`!Supported` is skipped.
- **Value operations.** Every value gate already keys on `LocalDataNode.Supported`: GetMetadata, Read and Subscribe
answer `Unsupported`, history requires `Supported`, and `DataWriteDispatchGate` refuses writes.
- **The node stays in the catalog.** Removing it would turn a deployable `DataExport` rooted at that tag
(`RootKind = RawTag` is valid) into a catalog compile failure ("Export has no valid origin root") for the whole cluster.
- **Browse hides it. The live gate forced this.** The first attempt listed the tag as the existing v1
`UnsupportedVariable` kind, on the assumption that consumers skip that kind. They do not. `ProjectedNamespaceApplier`
hands a whole page to `IProjectedNamespacePageSink.TryApply`, and `OtOpcUaNodeManager.TryEnsureProjectedVariable`
rejects anything that is not a Folder, Variable or Tag (`OtOpcUaNodeManager.cs:4988`). So **one** `UnsupportedVariable`
child failed the whole page.
- On run `fu916-1`, browsing the consumer's `remote-opc` branch (the A4 Raw mapping of the opc-plc device, which holds
the alarm tag `EastTankYellow`) answered `BadNoCommunication`.
- The rig's `resolve` walk hit the same status, and `deploy` timed out on "deployed catalog and OPC UA namespace
identity".
- Every consumer build behaves this way, including the merged v1 consumers. Listing the node would therefore break any
mixed-version consumer. Not listing it works for all of them, because a page simply has one item fewer.
- **The same holds for any unsupported value node**, for example a data type v1 cannot carry. A pre-existing v1 origin
already broke consumer browse of a folder holding one, and the browse filter fixes that too.
Condition placements are independent of the value node. They need only their parent folder or equipment, so condition
forwarding is unchanged. The live gate below re-proves it on the alarm tag itself.
## The v1 gate: goldens not re-recorded
`GrpcDataV1RealOriginGoldens` (recorded on `1086593a`) captured both defects. The goldens stay as recorded. The new
`GrpcDataV1RealOriginCorrections.Expected(scenario)` applies exactly two edits to the parsed golden message and
re-serialises it:
- it clears `stable_source_id` on every Metadata;
- it removes HighTemp from the device Browse page, and makes its GetMetadata item `status = Unsupported` with no value
and no lease.
The test then compares the real origin's header-less bytes with the result. Only Browse, Browse/uns and GetMetadata are
corrected. GetCapabilities, Read, Write, Write/no-write-grant and Subscribe are compared with the raw goldens, unchanged.
`V1_corrections_916_917_are_exact_and_the_recorded_leak_was_real` pins the method:
- an unedited golden re-serialises byte-identically, so an edit is the only possible difference;
- the corrected scenarios really differ from the goldens, and the others really do not;
- the recorded UNS browse really contains the leaked `driver-1Plant/Modbus/dev1/`, and no corrected scenario does;
- HighTemp is the single Unsupported item in GetMetadata, and the only item dropped from the recorded device page.
The fake-origin gate `GrpcDataV1CompatibilityTests` is untouched and green.
Before the fix, the decoded diff of real-origin output against the goldens was exactly these edits: field 10 on every
value node of Browse, Browse/uns and GetMetadata, plus the HighTemp entries.
## Red/green
| Test | Before the fix (master behaviour) | After |
|---|---|---|
| `GrpcDataConditionPlacementTests.No_exported_metadata_carries_the_internal_source_key_916` (60 generated topologies; encoded metadata of every node; UNS bytes searched for every driver id and RawPath; positive control: the internal key still contains them) | **Failed**: `node.Metadata.StableSourceId should be null` | Pass |
| `GrpcDataConditionPlacementTests.An_alarm_bearing_raw_tag_is_an_UnsupportedVariable_and_keeps_its_condition_placements_917` (positive controls: a plain tag, and the same tag without its alarm config, stay supported `Variable`s; 3 placements and the Raw listing intact; an export rooted at the alarm tag compiles) | **Failed**: alarm tag `Supported` was true | Pass |
| `GrpcDataV1RealOriginCompatibilityTests` header-less + feature-header Browse, Browse/uns, GetMetadata vs the raw goldens | Pass on master; fail with the fix | Compared with `Expected(...)`: pass |
Control run: with master's `src` restored over this branch's tests, the full Runtime.Tests `Feature=GrpcData` run failed
exactly the two new tests (#916, #917). All other tests passed (1021/1023).
The browse filter has its own red/green. With the `LocalDataServices` skip commented out, the real-origin Browse scenario
fails, both header-less and with the feature header (2 failures). With the skip restored, it passes.
## Gate runs (Release, on `70539999` + docs)
- Runtime.Tests `Feature=GrpcData`: **1023/1023 passed in 3 of 3 consecutive full runs.**
- Two earlier full runs each failed one test,
`GrpcDataConfiguredDiscoveryWireTests.Bad_null_sdk_notification_cannot_borrow_unproven_sample_evidence(different_timestamp)`:
it expected `BadUserAccessDenied` and got `BadNoCommunication`.
- This is the pre-existing intermittent **#920**, which reproduces on master and is being fixed separately. It passed
40/40 in isolation here.
- It is not touched by this change. Its fixture's nodes are all `Supported`, so the browse skip is a no-op there, and
the test exercises SDK notification queueing, not catalog metadata.
- The new 60-seed property test takes about 125 ms, the same order as the existing 60-seed UNS-only property test, so
it is not a load source.
- Host.Tests `Feature=GrpcData`: 210/210 passed. This includes `GrpcDataV1CompatibilityTests` (fake origin, untouched),
`GrpcDataV1RealOriginCompatibilityTests` and `GrpcDataHistoryWireTests`.
- `dotnet build -c Release` (whole solution): 0 warnings, 0 errors.
## Live gate (local grpc-data rig, `--conditions` profile, under the shared rig lock)
| Run | Build | Result |
|---|---|---|
| `fu916-1` | `b7ca71f1`: alarm tag listed as `UnsupportedVariable` | **Failed**, which is how the browse defect above was found. `deploy` timed out on "deployed catalog and OPC UA namespace identity". The seeder `resolve` got `BadNoCommunication`. The consumer's `remote-opc` folder answered `BadNoCommunication` to a Client.CLI browse, while the SOURCE leaves read Good on both pair members |
| `fu916-2` | interim | Discarded. The image was built while the source tree was being edited, so `verify_candidate` refused it ("running manifest does not match current image build inputs") |
| `fu916-3` | `70539999`: Browse skips unsupported value nodes | **PASS**, details below |
`fu916-3` ran `up --conditions` → `seed` → 85 s → `deploy --timeout 300` (ready) → `conditions_a3_smoke.py` → `conditions_scenarios.py` → `down`:
- `deploy --timeout 300` reached ready;
- `conditions_a3_smoke.py` reported `passed: true` (origin and consumer subscribers each saw Active/Unacknowledged → Active/Acknowledged);
- `conditions_scenarios.py` passed **A01–A08, 8/8**, `source_revision` `70539999`. A04 is the three placements of the alarm tag `EastTankYellow` (Raw `map-opc`, UNS `map-pumpa`/`map-pumpb`) and the UNS-only principal's records;
- `down` left 0 run containers.
A Client.CLI browse of consumer-1 then showed `remote-opc` → `FastUInt1` only, with the alarm tag not listed. Evidence is in
`artifacts/grpc-data/runs/fu916-3/evidence/` (`A4S-results.{json,md}`).
The live run does not separately probe `stable_source_id` over gRPC. #916 is pinned by the wire-level real-origin gate and
the 60-seed property test above.
## Review round 1 (2026-11-28)
| Finding | Fix | Red/green |
|---|---|---|
| #916 defence in depth: the mapper still encoded field 10 if anything set it | `DataProtoMapper.EncodeMetadata` never writes field 10. `DecodeMetadata` drops it, so a consumer of a pre-fix origin never retains it in `OriginMetadata`. The proto marks field 10 deprecated in a comment (not renumbered or removed) | `GrpcDataCodecTests.Stable_source_id_is_never_encoded_and_is_dropped_on_decode_916`: red with master's mapper, green with the fix. Engineering units (field 11) are the positive control |
| The fake-origin gate's goldens carry field 10 from its fake metadata, so the mapper change moves them | `GrpcDataV1Corrections.Expected` clears field 10 on the parsed Browse/GetMetadata goldens. That is the only edit, and the goldens are not re-recorded | `V1_correction_916_clears_only_stable_source_id`: the recording really carried field 10, an unedited golden re-serialises identically, and the other RPCs compare raw |
| Browse page boundaries | A skipped unsupported node no longer counts against the page's scan bound. The budget timeout still bounds the call. The skip therefore never yields an empty `Complete=false` page | `GrpcDataLocalConnectionTests.Browse_skips_unsupported_value_nodes_across_page_boundaries_917`, page size 2 over `[Speed, u, u, u, v, u, v]`. Red before the fix (an empty first-continuation page). Green after: `Speed, c3, c5` each exactly once, 2 non-empty pages, completes. Positive control: the skipped nodes are addressable (`Unsupported`) |
| Internal metadata still said an unsupported node was writable | `Add` compiles `writable &= supported` (raw tags, UNS references, virtual tags) | The #917 test fixture's alarm tag is now `ReadWrite`. `alarm.Metadata.Writable.ShouldBeFalse()` was red before the change and green after. Positive control: the same tag without its alarm is writable |
| Stale "browsable" test doc; "an export may still be rooted at it" | Both reworded. Such a root compiles, but grants nothing: the values are unsupported, and the condition placement sits under the tag's folder, not under the tag | — |
A consumer receiving an empty `Complete=false` page is no longer produced by this change. It can still come from the
pre-existing name filter. Whether the consumer resolver tolerates one was not tested end to end; it is suggested as a
follow-up.
Gates after the review, Release:
- Commons.Tests: 513/513.
- Runtime.Tests `Feature=GrpcData`: 1024/1024.
- Host.Tests `Feature=GrpcData`: 211/211. This includes both v1 gates.
- `dotnet build -c Release`: 0 warnings, 0 errors.
+4
View File
@@ -220,6 +220,10 @@ pre-H2 master `1086593a`.
2. Still expect these exact bytes **without** the header.
3. Expect them **with** the header too, until the server advertises the feature in `SupportedFeatures`.
4. Never re-record.
- **Pre-deploy corrections (#916, #917; 2026-11-28).** Two deliberate v1 fixes change real-origin Browse, Browse/uns and
GetMetadata. `GrpcDataV1RealOriginCorrections.Expected` applies exactly those edits to the parsed, unre-recorded golden:
it clears `stable_source_id`, drops the alarm-bearing HighTemp from the device Browse page, and makes its GetMetadata
item `Unsupported`. A test pins that the edits are the only difference. See `V1-916-917.md`.
## 3. Gate runs
@@ -258,8 +258,8 @@ public static class DataProtoMapper
v.Dimensions.AddRange(x.Dimensions);
if (x.ArrayElementKind is { } elementKind)
v.ArrayElementKind = (W.ValueKind)elementKind;
if (x.StableSourceId is not null)
v.StableSourceId = x.StableSourceId;
// #916: field 10 (stable_source_id) is never encoded, whatever the caller set. It carried the origin's internal
// acquisition key (driver instance id + RawPath), and no consumer needs it.
if (x.EngineeringUnits is not null)
v.EngineeringUnits = x.EngineeringUnits;
// H2: the service strips this (and the HistoryRead bit) from every response of a call that did not negotiate history.
@@ -288,7 +288,8 @@ public static class DataProtoMapper
// A2b method bits are condition grants, never node operations, so a metadata item carrying them is masked too.
(DataOperations)(x.AllowedOperations & (uint)DataOperationSets.Understood & ~(uint)DataOperationSets.ConditionGrants),
x.CatalogRevision,
x.HasStableSourceId ? x.StableSourceId : null,
// #916: dropped on decode too, so a consumer of a pre-fix origin never retains it in OriginMetadata.
null,
x.HasEngineeringUnits ? x.EngineeringUnits : null,
x.IsStale,
x.HasArrayElementKind ? (DataValueKind)x.ArrayElementKind : null,
@@ -161,6 +161,8 @@ message Metadata {
bool writable = 7;
uint32 allowed_operations = 8;
int64 catalog_revision = 9;
// DEPRECATED (#916): never sent and ignored on receipt. It carried the origin's internal acquisition key (driver
// instance id + RawPath). Kept so the field number is never reused.
optional string stable_source_id = 10;
optional string engineering_units = 11;
bool is_stale = 12;
@@ -19,7 +19,7 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// failover and re-deploys, identical on both pair members (the secret is a per-cluster <c>${secret:}</c>), and
/// equal across every listing and principal (m-T6), so a consumer dedupes a condition's Raw and UNS placements.
/// Being keyed, it cannot be dictionary-reversed from guessable RawPaths, and it carries no RawPath or driver id
/// (unlike <c>Metadata.stable_source_id</c>, #916).
/// (the v1 <c>Metadata.stable_source_id</c> did, and is no longer sent, #916).
/// </para>
/// <para>
/// Without a secret the origin advertises no <c>conditions</c> capability (fail closed): <see cref="IsAvailable"/>
@@ -394,11 +394,19 @@ public sealed partial class LocalDataServices : IDataConnectionFactory
long bytes = 256;
var maximum = Math.Min(request.Budget.MaxItems, limits.MaxPageItems);
var scanned = 0;
while (offset < children.Count && page.Count < maximum && scanned++ < maximum)
while (offset < children.Count && page.Count < maximum && scanned < maximum)
{
cancellationToken.ThrowIfCancellationRequested();
if (Expired(start, request.Budget)) return Task.FromResult(Empty(DataItemStatus.Unavailable));
var child = children[offset++];
// #917: an unsupported value node (an alarm-bearing tag, or a data type v1 cannot carry) is never listed. Every
// consumer build applies a browse page all-or-nothing and cannot materialise one, so listing it made the whole
// folder unbrowsable on the consumer (BadNoCommunication). It stays addressable (GetMetadata/Read/Subscribe on it
// answer Unsupported). An export rooted at it still compiles but grants nothing. A skipped node is not counted
// against the scan bound (it costs one check; the budget timeout above still bounds the call), so the skip never
// yields an empty Complete=false page.
if (child.Source is not null && !child.Supported) continue;
scanned++;
if ((request.Filter is { Length: > 0 } filter && !child.Metadata.BrowseName.Contains(filter, StringComparison.Ordinal))
|| !Allowed(catalog, context, child, DataOperations.Browse)) continue;
var metadata = Metadata(catalog, context, target, child);
@@ -92,11 +92,16 @@ public sealed partial class LocalExportCatalog
BackingSourceKey? source = null, DataValueKind valueKind = DataValueKind.Null, bool writable = false,
bool array = false, uint? length = null, bool supported = true, bool enabled = true)
{
writable &= supported; // #917 review: an unsupported value node is never writable, not even in internal metadata
var operations = source is null ? navigation : data | (writable ? DataOperations.Write : DataOperations.None);
var metadata = new DataMetadata(view, name, source is null ? "Folder" : supported ? "Variable" : "UnsupportedVariable",
array && supported ? DataValueKind.Array : valueKind, array && supported ? 1 : -1,
array && supported ? Array.AsReadOnly(new[] { length is { } n ? checked((int)n) : 0 }) : [],
writable, operations, serving.CatalogEpoch, source?.StableSourceId, null, false,
// #916: Metadata.stable_source_id is never sent. The internal key of a driver source is
// "<len>:<driverInstanceId><RawPath>" (SourceKey.ForDriver), which told a UNS-only peer the origin's driver ids
// and RawPaths; no consumer uses the field (it is optional on the wire and old consumers decode its absence as
// null). Acquisition keys on the LocalDataNode.Source BackingSourceKey, which is unchanged.
writable, operations, serving.CatalogEpoch, null, null, false,
array && supported ? valueKind : null);
nodes.Add(new(kind, id, metadata, scope, parent, source, supported, enabled));
views.Add((view.Realm, kind, id.ToUpperInvariant()), view);
@@ -131,7 +136,13 @@ public sealed partial class LocalExportCatalog
var enabled = deviceById[tagById[plan.TagId].DeviceId].Enabled && driverById[plan.DriverInstanceId].Enabled;
rawSources.Add(plan.NodeId, (source, enabled));
var kind = ValueKind(plan.DataType);
var supported = kind != DataValueKind.Unspecified && (!plan.IsArray || DataValue.IsSupportedArrayElementKind(kind));
// #917: an alarm-bearing tag never gets a value (DriverHostActor keeps it out of the value fan-out; #896 gives it
// no UNS variable), so it is an unsupported value node: Browse does not list it (LocalDataServices) and every
// value operation answers Unsupported, instead of a Variable a consumer would wait on forever. The node is KEPT so
// an export rooted at it still compiles, but such a root grants nothing: its values are unsupported and its
// condition placement sits under its folder, not under the tag. The alarm is forwarded as a condition (A1–A4).
var supported = plan.Alarm is null && kind != DataValueKind.Unspecified
&& (!plan.IsArray || DataValue.IsSupportedArrayElementKind(kind));
var rawView = View(DataRealm.Raw, plan.NodeId, scope);
Add("RawTag", plan.TagId, plan.Name, rawView, scope, RawParent(scope), source,
supported ? kind : DataValueKind.Null, plan.Writable && (!plan.IsArray || plan.ArrayWritable),
@@ -148,6 +148,31 @@ public sealed class GrpcDataCodecTests
}
}
/// <summary>
/// #916 defence in depth: the mapper never encodes <c>stable_source_id</c> (field 10), whatever a caller sets, and
/// drops it on decode so a consumer of a pre-fix origin never retains it. Engineering units (field 11) are the
/// positive control: an optional string in the same message still round-trips.
/// </summary>
[Fact]
public void Stable_source_id_is_never_encoded_and_is_dropped_on_decode_916()
{
var view = new DataView(new DataAddress("c", "urn:test", "string", "x"), DataRealm.Uns, null, 0, "subject");
var metadata = new DataMetadata(view, "x", "Variable", DataValueKind.Int32, -1, [], false, DataOperations.Read, 1,
"8:driver-1Plant/Modbus/dev1/Speed", "rpm", false);
var wire = DataProtoMapper.EncodeMetadata(metadata);
wire.HasStableSourceId.ShouldBeFalse();
ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1.Metadata.Parser.ParseFrom(wire.ToByteArray()).HasStableSourceId.ShouldBeFalse();
wire.EngineeringUnits.ShouldBe("rpm");
// A pre-fix origin's bytes: field 10 present on the wire.
var legacy = wire.Clone();
legacy.StableSourceId = "8:driver-1Plant/Modbus/dev1/Speed";
var decoded = DataProtoMapper.DecodeMetadata(legacy);
decoded.StableSourceId.ShouldBeNull();
decoded.EngineeringUnits.ShouldBe("rpm");
}
[Fact]
public void Array_metadata_rejects_missing_and_invalid_element_kind()
{
@@ -69,7 +69,7 @@ public sealed class GrpcDataHistoryWireTests
byId["Plant/Modbus/dev1/Speed"].History.Historizing.ShouldBeFalse();
(byId["Plant/Modbus/dev1/Speed"].AllowedOperations & 32u).ShouldBe(0u);
// Header-less: the golden (no Metadata.history, no bit 32).
(await origin.DriveAsync("GetMetadata", new Metadata())).ShouldBe(GrpcDataV1RealOriginGoldens.Responses["GetMetadata"]);
(await origin.DriveAsync("GetMetadata", new Metadata())).ShouldBe(GrpcDataV1RealOriginCorrections.Expected("GetMetadata"));
// A caller whose ACL lacks HistoryRead sees historizing=false on Flow: the same as an unhistorized node.
await using var denied = new RealOrigin(permissions: NodePermissions.Operator & ~NodePermissions.HistoryRead);
var deniedMeta = W.MetadataResponse.Parser.ParseFrom(Convert.FromHexString(await denied.DriveAsync("GetMetadata", History)));
@@ -64,12 +64,30 @@ public sealed class GrpcDataV1CompatibilityTests
Hex(V1Requests.Bytes(rpc)).ShouldBe(GrpcDataV1Goldens.Requests[rpc], $"recorded {rpc} request");
}
/// <summary>#916: the only correction of the fake-origin goldens is field 10, and the recording really carried it.</summary>
[Fact]
public void V1_correction_916_clears_only_stable_source_id()
{
foreach (var rpc in RpcNames.Where(r => r != "Subscribe"))
{
var golden = GrpcDataV1Goldens.Responses[rpc];
if (GrpcDataV1Corrections.Corrected.Contains(rpc))
{
GrpcDataV1Corrections.Expected(rpc).ShouldNotBe(golden, $"{rpc}: the recorded fake metadata carried field 10");
IMessage parsed = rpc == "Browse" ? W.BrowseResponse.Parser.ParseFrom(Convert.FromHexString(golden))
: W.MetadataResponse.Parser.ParseFrom(Convert.FromHexString(golden));
Hex(parsed.ToByteArray()).ShouldBe(golden, $"{rpc}: re-serialising a golden is byte-identical");
}
else GrpcDataV1Corrections.Expected(rpc).ShouldBe(golden);
}
}
[Theory]
[MemberData(nameof(Rpcs))]
public async Task V1_client_without_feature_header_gets_the_recorded_v1_response_bytes(string rpc)
{
var actual = await V1CompatibilityHarness.DriveAsync(rpc, new Metadata());
actual.ShouldBe(GrpcDataV1Goldens.Responses[rpc], $"{rpc} response diverged from the recorded v1 bytes");
actual.ShouldBe(GrpcDataV1Corrections.Expected(rpc), $"{rpc} response diverged from the recorded v1 bytes");
}
[Theory]
@@ -79,9 +97,9 @@ public sealed class GrpcDataV1CompatibilityTests
// H2 supports history, but this origin advertises none (and conditions are A2): the effective set is empty.
var headers = new Metadata { { "x-otopcua-data-features", "history,conditions" } };
var actual = await V1CompatibilityHarness.DriveAsync(rpc, headers, history: false, conditions: false);
actual.ShouldBe(GrpcDataV1Goldens.Responses[rpc], $"{rpc} response must not change when nothing requested is servable");
actual.ShouldBe(GrpcDataV1Corrections.Expected(rpc), $"{rpc} response must not change when nothing requested is servable");
(await V1CompatibilityHarness.DriveAsync(rpc, new Metadata { { "x-otopcua-data-features", "conditions" } }, conditions: false))
.ShouldBe(GrpcDataV1Goldens.Responses[rpc], $"{rpc}: conditions on an origin that cannot serve them change nothing");
.ShouldBe(GrpcDataV1Corrections.Expected(rpc), $"{rpc}: conditions on an origin that cannot serve them change nothing");
}
[Fact]
@@ -254,6 +272,39 @@ public sealed class GrpcDataV1CompatibilityTests
internal static IMessage Normalise(IMessage message) => message;
}
/// <summary>
/// #916 (pre-deploy, never re-recorded): <c>DataProtoMapper</c> no longer encodes <c>Metadata.stable_source_id</c>
/// (field 10), so the fake origin's metadata loses it on the wire. The expected bytes are the recorded golden with field 10
/// cleared on every Metadata of Browse and GetMetadata. That is the only edit. The real-origin variant has its own corrections
/// (<see cref="GrpcDataV1RealOriginCorrections"/>).
/// </summary>
internal static class GrpcDataV1Corrections
{
internal static readonly string[] Corrected = ["Browse", "GetMetadata"];
internal static string Expected(string rpc)
{
var golden = GrpcDataV1Goldens.Responses[rpc];
if (!Corrected.Contains(rpc)) return golden;
var bytes = Convert.FromHexString(golden);
IMessage corrected;
if (rpc == "Browse")
{
var response = W.BrowseResponse.Parser.ParseFrom(bytes);
foreach (var item in response.Items) item.ClearStableSourceId();
corrected = response;
}
else
{
var response = W.MetadataResponse.Parser.ParseFrom(bytes);
foreach (var item in response.Items) item.Value?.ClearStableSourceId();
corrected = response;
}
return Convert.ToHexString(corrected.ToByteArray());
}
}
/// <summary>The recorded v1 client requests. Changing any value here invalidates the goldens.</summary>
internal static class V1Requests
{
@@ -66,13 +66,53 @@ public sealed class GrpcDataV1RealOriginCompatibilityTests
Hex(RealOriginRequests.Bytes(scenario)).ShouldBe(GrpcDataV1RealOriginGoldens.Requests[scenario], $"recorded {scenario} request");
}
/// <summary>
/// #916/#917: the corrections are exact and not vacuous — an unedited golden re-serialises byte-identically, the
/// uncorrected scenarios are the raw goldens, the recorded UNS browse really leaked the driver id + RawPath, and the
/// corrected bytes carry neither the leak nor a value-bearing HighTemp.
/// </summary>
[Fact]
public void V1_corrections_916_917_are_exact_and_the_recorded_leak_was_real()
{
foreach (var scenario in RealOriginRequests.Scenarios.Where(s => s != "Subscribe"))
{
var golden = GrpcDataV1RealOriginGoldens.Responses[scenario];
IMessage parsed = scenario.Split('/')[0] switch
{
"GetCapabilities" => W.CapabilitiesResponse.Parser.ParseFrom(Convert.FromHexString(golden)),
"Browse" => W.BrowseResponse.Parser.ParseFrom(Convert.FromHexString(golden)),
"GetMetadata" => W.MetadataResponse.Parser.ParseFrom(Convert.FromHexString(golden)),
"Read" => W.ReadResponse.Parser.ParseFrom(Convert.FromHexString(golden)),
_ => W.WriteResponse.Parser.ParseFrom(Convert.FromHexString(golden)),
};
Hex(parsed.ToByteArray()).ShouldBe(golden, $"{scenario}: re-serialising a golden is byte-identical");
if (GrpcDataV1RealOriginCorrections.Corrected.Contains(scenario))
GrpcDataV1RealOriginCorrections.Expected(scenario).ShouldNotBe(golden, $"{scenario} carries a corrected field");
else
GrpcDataV1RealOriginCorrections.Expected(scenario).ShouldBe(golden);
}
var leak = Hex(System.Text.Encoding.UTF8.GetBytes("driver-1Plant/Modbus/dev1/"));
GrpcDataV1RealOriginGoldens.Responses["Browse/uns"].ShouldContain(leak, Case.Sensitive, "the recorded v1 UNS browse leaked it (#916)");
foreach (var scenario in GrpcDataV1RealOriginCorrections.Corrected)
GrpcDataV1RealOriginCorrections.Expected(scenario).ShouldNotContain(leak, Case.Sensitive);
var metadata = W.MetadataResponse.Parser.ParseFrom(Convert.FromHexString(GrpcDataV1RealOriginCorrections.Expected("GetMetadata")));
metadata.Items.Count(x => x.Status == (int)DataItemStatus.Unsupported).ShouldBe(1);
metadata.Items.ShouldNotContain(x => x.Value != null && x.Value.View.Address.Identifier == RealOriginRequests.HighTemp.Address.Identifier);
// HighTemp was in the recorded device page and is the only item the correction drops (positive control).
var recorded = W.BrowseResponse.Parser.ParseFrom(Convert.FromHexString(GrpcDataV1RealOriginGoldens.Responses["Browse"]));
var corrected = W.BrowseResponse.Parser.ParseFrom(Convert.FromHexString(GrpcDataV1RealOriginCorrections.Expected("Browse")));
recorded.Items.Select(x => x.View.Address.Identifier).Except(corrected.Items.Select(x => x.View.Address.Identifier))
.ShouldBe([RealOriginRequests.HighTemp.Address.Identifier]);
corrected.Items.Count.ShouldBe(recorded.Items.Count - 1);
}
[Theory]
[MemberData(nameof(Scenarios))]
public async Task V1_client_without_feature_header_gets_the_recorded_v1_response_bytes(string scenario)
{
await using var origin = new RealOrigin();
var actual = await origin.DriveAsync(scenario, new Metadata());
actual.ShouldBe(GrpcDataV1RealOriginGoldens.Responses[scenario], $"{scenario} response diverged from the recorded v1 bytes");
actual.ShouldBe(GrpcDataV1RealOriginCorrections.Expected(scenario), $"{scenario} response diverged from the recorded v1 bytes");
}
[Theory]
@@ -83,10 +123,10 @@ public sealed class GrpcDataV1RealOriginCompatibilityTests
// effective set is empty and the bytes are v1.
await using var origin = new RealOrigin(historian: false, conditions: false);
var actual = await origin.DriveAsync(scenario, new Metadata { { "x-otopcua-data-features", "history,conditions" } });
actual.ShouldBe(GrpcDataV1RealOriginGoldens.Responses[scenario], $"{scenario} response must not change when nothing requested is servable");
actual.ShouldBe(GrpcDataV1RealOriginCorrections.Expected(scenario), $"{scenario} response must not change when nothing requested is servable");
await using var conditionsOnly = new RealOrigin(conditions: false);
(await conditionsOnly.DriveAsync(scenario, new Metadata { { "x-otopcua-data-features", "conditions" } }))
.ShouldBe(GrpcDataV1RealOriginGoldens.Responses[scenario], $"{scenario}: conditions on an origin that cannot serve them change nothing");
.ShouldBe(GrpcDataV1RealOriginCorrections.Expected(scenario), $"{scenario}: conditions on an origin that cannot serve them change nothing");
}
[Fact]
@@ -219,6 +259,56 @@ public sealed class GrpcDataV1RealOriginCompatibilityTests
internal static IMessage Normalise(IMessage message) => message;
}
/// <summary>
/// The deliberate pre-deploy v1 corrections (#916, #917; v1 was merged but never deployed, #915). The goldens in
/// <see cref="GrpcDataV1RealOriginGoldens"/> are NOT re-recorded: the expected bytes are the recorded golden with exactly
/// these edits applied to its parsed message, and every other byte must still match. Re-serialising an unedited golden is
/// byte-identical (asserted), so the edit is the only difference. Nothing here changes the wire SHAPE — both corrections
/// use fields and values a v1 client already handles (an absent optional field; one item fewer in a page; the existing
/// per-item Unsupported status).
/// <list type="bullet">
/// <item><b>#916</b> — <c>Metadata.stable_source_id</c> is never sent (it was <c>&lt;len&gt;:&lt;driverInstanceId&gt;&lt;RawPath&gt;</c>, even on
/// UNS exports). Cleared on every Metadata of every Browse/GetMetadata response.</item>
/// <item><b>#917</b> — the alarm-bearing raw tag (HighTemp) is an unsupported value node: a Browse page no longer lists it
/// (every consumer build applies a page all-or-nothing and cannot materialise one), and a GetMetadata item for it is
/// <c>status = Unsupported</c> with no value and no lease.</item>
/// </list>
/// </summary>
internal static class GrpcDataV1RealOriginCorrections
{
internal static readonly string[] Corrected = ["Browse", "Browse/uns", "GetMetadata"];
internal static string Expected(string scenario)
{
var golden = GrpcDataV1RealOriginGoldens.Responses[scenario];
if (!Corrected.Contains(scenario)) return golden;
var bytes = Convert.FromHexString(golden);
var alarm = RealOriginRequests.HighTemp.Address.Identifier;
IMessage corrected;
if (scenario == "GetMetadata")
{
var response = W.MetadataResponse.Parser.ParseFrom(bytes);
foreach (var item in response.Items)
{
if (item.Value is null) continue;
if (item.Value.View.Address.Identifier == alarm && item.Value.View.Realm == (int)DataRealm.Raw)
{ item.Status = (int)DataItemStatus.Unsupported; item.Value = null; item.Lease = null; continue; }
item.Value.ClearStableSourceId();
}
corrected = response;
}
else
{
var response = W.BrowseResponse.Parser.ParseFrom(bytes);
var hidden = response.Items.Where(item => item.View.Address.Identifier == alarm && item.View.Realm == (int)DataRealm.Raw).ToArray();
foreach (var item in hidden) response.Items.Remove(item);
foreach (var item in response.Items) item.ClearStableSourceId();
corrected = response;
}
return GrpcDataV1RealOriginCompatibilityTests.Hex(corrected.ToByteArray());
}
}
/// <summary>The recorded v1 client requests against <see cref="RealOrigin"/>'s catalog. Changing any value invalidates the goldens.</summary>
internal static class RealOriginRequests
{
@@ -6,6 +6,8 @@ namespace ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections;
/// NEVER re-record these to make a later phase (H2, A2, A3, ...) pass: a difference is a v1 wire regression of the
/// real origin, not a stale golden. A later phase extends <see cref="RealOrigin"/>'s snapshot with its new-shape data
/// and must still produce these exact bytes for a headerless (and, while unsupported, a feature-requesting) v1 call.
/// The only sanctioned differences are the pre-deploy corrections #916/#917, applied to these bytes (not re-recorded) by
/// <see cref="GrpcDataV1RealOriginCorrections"/>.
/// </summary>
internal static class GrpcDataV1RealOriginGoldens
{
@@ -2,6 +2,7 @@ using System.Security.Cryptography;
using System.Text.Json;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.DataConnections;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
@@ -45,7 +46,7 @@ public sealed class GrpcDataConditionPlacementTests
Devices = [new() { DeviceId = "device", DriverInstanceId = "driver-id-7f3", Name = "Device", DeviceConfig = "{}" }],
TagGroups = [new() { TagGroupId = "group", DeviceId = "device", Name = "Group" }],
Tags = [new() { TagId = "tag", DeviceId = "device", Name = "Speed", DataType = "Int32", AccessLevel = TagAccessLevel.ReadWrite, TagConfig = "{}" },
new() { TagId = "alarm-tag", DeviceId = "device", TagGroupId = "group", Name = "OverTemp", DataType = "Boolean", AccessLevel = TagAccessLevel.Read,
new() { TagId = "alarm-tag", DeviceId = "device", TagGroupId = "group", Name = "OverTemp", DataType = "Boolean", AccessLevel = TagAccessLevel.ReadWrite,
TagConfig = withAlarms ? AlarmConfig : "{}" }],
UnsAreas = [new() { UnsAreaId = "area-id", ClusterId = "cluster", Name = "Area" }],
UnsLines = [new() { UnsLineId = "line-id", UnsAreaId = "area-id", Name = "Line" }],
@@ -306,6 +307,83 @@ public sealed class GrpcDataConditionPlacementTests
listedNative.ShouldBeGreaterThan(20); // the generator really exercised native UNS placements
}
/// <summary>
/// #916: no exported metadata carries <c>stable_source_id</c> — a driver source's internal key is
/// <c>&lt;len&gt;:&lt;driverInstanceId&gt;&lt;RawPath&gt;</c>, so sending it told a UNS-only peer the origin's driver ids and
/// RawPaths. The internal <see cref="BackingSourceKey"/> is unchanged (positive control: it still holds both, so the
/// search below would see a leak). Checked on the encoded wire bytes of every node, every realm, 60 seeds.
/// </summary>
[Fact]
public void No_exported_metadata_carries_the_internal_source_key_916()
{
var checkedSources = 0;
for (var seed = 1; seed <= 60; seed++)
{
var (snapshot, rawPaths, driverIds, _) = Generate(seed);
using var fixture = new LocalDataFixture();
var catalog = LocalExportCatalog.Compile(snapshot, fixture.Serving, fixture.Activation.CaptureAuthority());
foreach (var node in catalog.Nodes)
{
node.Metadata.StableSourceId.ShouldBeNull($"seed {seed} {node.EntityKind} {node.EntityId}");
var wire = DataProtoMapper.EncodeMetadata(node.Metadata);
wire.HasStableSourceId.ShouldBeFalse();
if (node.Metadata.View.Realm != DataRealm.Uns) continue;
var text = wire.ToString();
foreach (var rawPath in rawPaths) text.ShouldNotContain(rawPath, Case.Sensitive, $"seed {seed}");
foreach (var driverId in driverIds) text.ShouldNotContain(driverId, Case.Sensitive, $"seed {seed}");
// Positive control: the internal key of a driver-backed UNS reference still names its driver and RawPath.
if (node.Source is { SourceKind: "driver" } source)
{
driverIds.ShouldContain(d => source.StableSourceId.Contains(d, StringComparison.Ordinal));
rawPaths.ShouldContain(r => source.StableSourceId.EndsWith(r, StringComparison.Ordinal));
checkedSources++;
}
}
}
checkedSources.ShouldBeGreaterThan(20); // the generator really produced driver-backed UNS references
}
/// <summary>
/// #917: an alarm-bearing raw tag gets no value (DriverHostActor keeps it out of the value fan-out, and #896 gives it
/// no UNS variable), so v1 compiles it as an unsupported value node: kind <c>UnsupportedVariable</c>, never writable
/// (the fixture tag is ReadWrite), Unsupported on every value operation, and NOT listed by Browse — never a Variable
/// that waits forever. Its condition placements (A1) are untouched. An export rooted at it still compiles (the
/// deploy is not broken) but grants nothing: its values are unsupported and its condition is not under the root.
/// </summary>
[Fact]
public void An_alarm_bearing_raw_tag_is_an_UnsupportedVariable_and_keeps_its_condition_placements_917()
{
using var fixture = new LocalDataFixture();
var catalog = LocalExportCatalog.Compile(Fixed(), fixture.Serving, fixture.Activation.CaptureAuthority());
var alarm = catalog.Nodes.Single(n => n.EntityKind == "RawTag" && n.EntityId == "alarm-tag");
alarm.Supported.ShouldBeFalse();
alarm.Metadata.NodeKind.ShouldBe("UnsupportedVariable");
alarm.Metadata.ValueKind.ShouldBe(DataValueKind.Null);
alarm.Metadata.Writable.ShouldBeFalse();
// (Every value gate keys on Supported; the operations a caller sees are masked to Browse by LocalDataServices —
// pinned on the wire by GrpcDataV1RealOriginCompatibilityTests.)
// Positive controls: a plain tag is still a Variable, and the same tag without its alarm config is one too.
var speed = catalog.Nodes.Single(n => n.EntityKind == "RawTag" && n.EntityId == "tag");
speed.Supported.ShouldBeTrue();
speed.Metadata.NodeKind.ShouldBe("Variable");
var plain = LocalExportCatalog.Compile(Fixed(withAlarms: false), fixture.Serving, fixture.Activation.CaptureAuthority())
.Nodes.Single(n => n.EntityKind == "RawTag" && n.EntityId == "alarm-tag");
plain.Supported.ShouldBeTrue();
plain.Metadata.NodeKind.ShouldBe("Variable");
plain.Metadata.ValueKind.ShouldBe(DataValueKind.Boolean);
plain.Metadata.Writable.ShouldBeTrue(); // the same ReadWrite tag without its alarm IS writable
// Condition forwarding is unaffected: the Raw placement at its RawPath and both UNS placements remain.
catalog.PlacementsOf(new(AddressSpaceRealm.Raw, "Plant/Driver/Device/Group/OverTemp")).Count.ShouldBe(3);
catalog.ListConditions("raw-peer", LocalExportCatalog.RealmRoot("cluster", DataRealm.Raw), DataOperations.Subscribe,
ConditionKeys.FromSecret(Secret)).ShouldHaveSingleItem();
// A deployable export rooted at the alarm-bearing tag still compiles (the node is kept, not removed).
var b = Fixed();
Should.NotThrow(() => LocalExportCatalog.Compile(With(b, exports: [.. b.DataExports,
Export("tag-root", DataRealm.Raw, "tag-peer", rootKind: "RawTag", rootId: "alarm-tag")]), fixture.Serving, fixture.Activation.CaptureAuthority()));
}
private static (DraftSnapshot Snapshot, string[] RawPaths, string[] DriverIds, int ExpectedUnsNative) Generate(int seed)
{
var random = new Random(seed);
@@ -33,6 +33,43 @@ public sealed class GrpcDataLocalConnectionTests
expired.Items.ShouldBeEmpty();
}
/// <summary>
/// #917 review: Browse skips unsupported value nodes across page boundaries. With a page size of 2 and children
/// <c>[Speed, u, u, u, v, u, v]</c>, every supported child appears exactly once, no unsupported one appears, the walk
/// completes, and no page is empty: a skipped node does not count against the page's scan bound, so the skip
/// never produces an empty <c>Complete = false</c> page.
/// </summary>
[Fact]
public async Task Browse_skips_unsupported_value_nodes_across_page_boundaries_917()
{
using var fixture = new LocalDataFixture(siblingPattern: "uuuvuv");
await using var connection = fixture.Connection();
var budget = LocalDataFixture.Budget with { MaxItems = 2 };
var seen = new List<string>();
var pages = 0;
string? continuation = null;
while (true)
{
var page = await connection.BrowseAsync(new(fixture.Root, null, continuation, budget), TestContext.Current.CancellationToken);
page.Status.ShouldBe(DataItemStatus.Good);
page.Items.ShouldNotBeEmpty($"page {pages}");
page.Items.Count.ShouldBeLessThanOrEqualTo(2);
seen.AddRange(page.Items.Select(x => x.BrowseName));
pages++;
if (page.Complete) { page.Continuation.ShouldBeNull(); break; }
page.Continuation.ShouldNotBeNull();
continuation = page.Continuation;
pages.ShouldBeLessThan(10);
}
seen.ShouldBe(["Speed", "c3", "c5"]);
pages.ShouldBe(2);
// Positive control: the unsupported siblings are in the catalog and addressable (Unsupported, not NotFound).
fixture.Catalog.Nodes.Count(n => !n.Supported).ShouldBe(4);
var metadata = await connection.GetMetadataAsync(new([fixture.Root with { Address = fixture.Root.Address with { Identifier = "Plant/c0" },
Subject = "Plant/c0" }], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
metadata.ShouldHaveSingleItem().Status.ShouldBe(DataItemStatus.Unsupported);
}
[Fact]
public async Task Metadata_bootstrap_resolves_address_and_never_uses_the_claimed_subject_as_authority()
{
@@ -136,7 +173,8 @@ internal sealed class LocalDataFixture : IDisposable
bool advanceAuthority = false, string role = "Primary", long servingGeneration = 0, bool nestedCatalog = false, bool nestedUnsCatalog = false,
Func<DataAuthenticatedContext, IDataWriteService>? writes = null, bool denyReadExport = false,
ManualTimeProvider? clock = null, string servingNode = "node-a", string servingIncarnation = "serving-1",
IOriginHistoryPort? history = null, DataValueKind rawValueKind = DataValueKind.Int32, int maxBatchItems = 100)
IOriginHistoryPort? history = null, DataValueKind rawValueKind = DataValueKind.Int32, int maxBatchItems = 100,
string? siblingPattern = null)
{
if (clock is not null) Clock = clock;
Serving = Serving with { NodeId = servingNode, Incarnation = servingIncarnation, Role = role, ServingGeneration = servingGeneration };
@@ -191,6 +229,17 @@ internal sealed class LocalDataFixture : IDisposable
nodes.Add(new("RawTag", "extra-" + i, rawMetadata with { View = view, BrowseName = "Speed" + i },
new() { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw, Segments = ["Plant", "Driver", "Device", "Speed" + i] }, Root, Ticket.Key));
}
// #917: "u" = an unsupported value node (as an alarm-bearing tag compiles), "v" = a supported one, named c0, c1, ...
// in order (they sort after "Speed"), all under Root.
for (var i = 0; i < (siblingPattern?.Length ?? 0); i++)
{
var name = "c" + i.ToString(System.Globalization.CultureInfo.InvariantCulture);
var view = Raw with { Address = Raw.Address with { Identifier = "Plant/" + name }, Subject = "Plant/" + name };
var supported = siblingPattern![i] == 'v';
nodes.Add(new("RawTag", "sibling-" + name, supported ? rawMetadata with { View = view, BrowseName = name }
: rawMetadata with { View = view, BrowseName = name, NodeKind = "UnsupportedVariable", ValueKind = DataValueKind.Null, Writable = false },
new() { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw, Segments = ["Plant", name] }, Root, Ticket.Key, Supported: supported));
}
Catalog = new LocalExportCatalog("cluster", Serving, Activation.CaptureAuthority(), nodes,
[new() { DataExportId = "raw-export", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Raw, RootKind = "RawFolder", RootEntityId = "folder", PrincipalId = "peer", AllowedOperations = operations },
new() { DataExportId = "uns-export", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Uns, RootKind = nestedUnsCatalog ? "UnsArea" : "UnsTagReference", RootEntityId = nestedUnsCatalog ? "area" : "reference", PrincipalId = "peer", AllowedOperations = operations }]);