Files
lmxopcua/docs/plans/evidence/grpc-data/p01-astra-review.md
T
2026-11-23 09:55:03 -05:00

23 KiB
Raw Blame History

P01 Astra contract-freeze review

Date: 2026-11-15 (America/Indiana/Indianapolis)
Scope: initial and corrected frozen P01 Task 2/3 working candidates based on c3abd468211bf1c8202708447e84df9a2d90bd3f; the five Core.Abstractions data-connection files, the new protobuf/service registration, mapper and value codec, and the four new test classes. Final candidate file digests are recorded in phase run 20261116T024814.318745Z-3a06bbb5af5e; earlier runs are retained below for traceability.

Final disposition: approved for P01 contract freeze after correction. All eight findings are resolved for this checkpoint. The final focused phase gate passed 51 tests with zero failures/skips, and the reviewed source/test digests match that run. Dependent phases may proceed against these contracts. This review does not approve later phases or the completed feature. The reviewer inspected source and existing run evidence only; no build or test was executed, and only this review document was edited.

The review uses the implementation plan, design, and preceding design/plan findings. Source line numbers below refer to the reviewed candidate, before corrective edits.

Follow-up assessment

The complete corrected source and tests were reread. The following table supersedes the original finding statuses where stated; original explanations remain below for traceability.

Finding Follow-up assessment
H1 Resolved: required DataCapabilities.ClusterId is encoded/decoded and validated; capability round-trip and empty cluster identity tests cover it. Configured expected-cluster comparison remains a P07 selector obligation.
H2 Resolved: receiver-owned DataDecodeLimits, aggregate typed-value accounting, collection-count checks, and read/write/metadata response helpers are present. Browse requests now use the same preflight. DecodeMetadata checks the fixed 16-dimension ceiling before ToArray; final tests cover oversized browse input and valid/oversized/over-rank nested metadata. The accounting and runtime limits of this approval are stated below.
H3 Resolved: both compact/fallback value decoders require validated expectedServing, compare every sample/batch against it, and check ack-handle stream/epoch consistency. Regression cases cover changed incarnation, fallback node mismatch, and another ack epoch. Runtime control/reset transitions must supply the correctly updated context; they are not implicitly accepted by the codec.
M1 Resolved: array element kind is preserved and validated in both directions; positive and malformed array metadata tests passed in the follow-up run.
M2 Resolved: framing/write item counts and value-element counts are separate parameters. A positive MaxValueElements is advertised with an explicit backward default. One-item/100-element write and compact/fallback cases passed.
M3 Resolved: known value kinds/operation bits are intersected, unknown compact version falls back, and major mismatch still rejects. The corresponding capability test passed.
M4 Resolved: stable explicit domain values, full existing-field descriptor assertions, service signatures, and hash invariance/change tests are present. The generated wire enum name-casing fix passed in the final gate.
M5 Resolved: identities, ready epochs, samples, settings, negotiated limits, top-level command/frame generations, and lease duration are checked; sub-tick timestamp precision is rejected explicitly. The final correction also rejects orphan mapping revisions, invalid write identity/preconditions/budget, negative control/watermark fields, and cross-stream removal handles.

Final H2 assessment and runtime boundary

The final DecodeBrowseRequest accepts receiver-owned limits and runs preflight before returning the domain request. Nested metadata has a fixed graph of view/address/type fields and at most 16 copied dimensions; top-level repeated collections are checked before domain list/array construction. Variable string content is charged through encoded size, per-item domain structure through the fixed allowance, and typed-value/array content through additional aggregate cost. The resulting accounting rule bounds accepted work and retained domain shape for this schema. It is not an exact measurement of managed heap usage, allocation churn, pooled-buffer release, protobuf parser memory, or decompression expansion. P07 must enforce transport/parser/decompression limits, and P04/P06/P11 must verify their actual retained-memory and load budgets. A later schema or representation change must revisit the fixed accounting allowance.

The final nested-metadata regression accepts the maximum supported rank, rejects an over-rank shape before dimension copying, and rejects a strict receiver budget. Together with the aggregate-write/count tests and the source review of collection entry points, this closes the concrete P01 gaps without claiming the later workload gates have run.

Earlier H2 residual request — resolved

DataProtoMapper.DecodeBrowseRequest still has no receiver limits or preflight, unlike the other operation envelopes (corrected source lines 743–749). An arbitrarily large filter/continuation/view within the transport's separate ceiling can therefore bypass a stricter receiver decode budget. Add the same receiver-owned boundary to this entry point.

The generic preflight now estimates decoded cost as encoded * 2 + count * 256 + 128 plus typed-value cost (lines 25–47). This is meaningfully stronger than the initial code, but its constants and the assumption that nested object graphs fit inside the per-item allowance are not documented or pinned by boundary tests. Do not treat it as a measured heap bound. The fixed dimension check prevents unbounded metadata-dimension copies, but the suite still needs valid maximal-rank metadata nested in browse/metadata-result envelopes, strict-budget/over-count response cases, and an oversized browse request. Establish and document the accounting invariant for nested view/address/metadata/ID/list overhead and test both sides of its rejection threshold. Transport parsing/decompression remains explicitly outside this post-parse accounting.

Earlier M5 residual request — resolved

  • DataView.Validate still permits MappingId = null with a positive MappingRevision.
  • DecodeWriteRequest still admits empty operation ID/expected serving incarnation and nonpositive catalog revision/remaining budget without structural validation. Validate these before allocating/returning owned values.
  • DecodeControlOrAck still copies negative control catalog/authority epochs, negative partition IDs, and negative watermark versions into domain controls. Define permitted zero values explicitly, then reject negative/illegal values.
  • Remove-command handles are individually validated but are not checked against their enclosing command's subscription ID and stream epoch. Apply the same cross-envelope consistency already added for acknowledgments.

These are transport/domain structure checks. They do not replace P03 authorization or P05 live role/catalog/deadline revalidation. Likewise, DataView.Subject remains a caller-supplied claim copied by the mapper. P03 must resolve the authoritative subject from the active catalog and authenticated principal/key, and reject a spoofed claim; no P01 type or codec makes that string authoritative. Carry this explicit negative test into P03.

The final domain correction documents DataView.Subject as untrusted. IDataConnectionFactory now explicitly creates caller-bound facades from host-established DataAuthenticatedContext, which separates principal, public key identity, non-secret credential version, original expiry, and authority epoch. DataWriteAdmission also retains the credential version and original expiry. The context/admission tests passed. The factory implementation and P03/P05 policy must enforce these contracts: request payloads cannot create trusted contexts, key replacement cannot relabel an admitted operation or extend its original expiry, and an authoritative subject must come from the active catalog.

H1 — Preserve the expected cluster identity through capabilities

Severity: High. Status: resolved in follow-up. Originally, CapabilitiesResponse.cluster_id existed at wire field 10, but DataCapabilities had no cluster identity (DataContracts.cs:113–114). DataProtoMapper.EncodeCapabilities never wrote that field and DecodeCapabilities discarded it (DataProtoMapper.cs:743–803). ServingIdentity supplies node/incarnation, not cluster. Thus the normal domain-to-wire-to-domain capabilities path could not supply the information required to verify DataTarget.ExpectedClusterId before node/cluster selection. An identity check added only to raw gRPC messages would also leave the transport-neutral path inconsistent.

Correction: Add required serving-cluster identity to the domain capabilities contract, preserve and structurally validate it in both directions, and require the later connection selector to compare it with the configured target. Add round-trip, empty-identity, and wrong-target identity tests at the responsible boundary. Keep origin ownership and serving-node/incarnation distinct.

H2 — Enforce receiver-owned aggregate decode budgets before collection allocation

Severity: High. Status: resolved after final follow-up. Originally, DecodeWriteRequest checked aggregate encoded size, then independently decoded every value with the entire maxBytes allowance (DataProtoMapper.cs:559–585). It never summed decoded storage, so several individually small values could collectively exceed the batch's decoded budget. For example, two byte values each accepted by the per-value decoded limit could fit the encoded envelope while their combined copies exceeded that limit.

Other exposed collection decoders have no receiver-owned count/byte parameters and allocate with ToArray/List directly: read requests (529–538), metadata requests (617–618), subscription commands (270–308), browse responses (642–659), and control/ack frames (858–901). Payload-supplied Budget is validated only for positivity and is not an independent receiver limit. Compact/fallback value-frame accounting covers typed values but does not account for their per-item domain samples/list entries or other decoded frame state. A wire-byte ceiling alone does not establish the decoded resource bound required by P01 and the design.

Correction: Define a receiver-supplied decode-limit context and preflight each collection/envelope against its item, dimension/element, encoded-byte, and aggregate decoded-byte limits before constructing domain collections or owned values. Include surrounding per-item/envelope storage in the accounting. Apply it consistently to request, response, command, ack/control, and both value encodings; handle partial decode cleanup consistently. Transport parsing/decompression ceilings remain separate P07 ingress obligations and must not be claimed as covered by these post-parse helpers.

Regression evidence required: A multi-value write whose encoded envelope fits but aggregate decoded storage does not; over-count read/metadata/add/control/ack envelopes; compact and fallback envelopes that exceed decoded storage while fitting wire bytes; and boundary-sized valid messages. Tests should demonstrate rejection at preflight, not after creating every domain item.

H3 — Bind decoded stream handles to the serving incarnation

Severity: High. Status: resolved in follow-up. Originally, compact decoding verified the handle's stream ID, epoch, and item revision but accepted whatever Serving the incoming batch claimed (DataProtoMapper.cs:336–364). The handle context had no expected serving node/incarnation. Fallback decoding likewise accepted each sample's independent serving identity, including a frame mixing different nodes (454–509). The encoder's compact-only mixed-provenance check did not protect a consumer from an invalid peer frame. Consequently, the same valid handle/epoch could accept samples from another node or restarted incarnation, contrary to design §6's pinned stream and fresh-epoch requirement.

Correction: Carry expected serving-node/incarnation identity in the stream decode context or handle bindings and enforce it in compact and fallback paths. Check handle/frame epoch consistency for acknowledgments as well. Permit catalog/authority transitions only through the specified control/reset behavior; do not equate arbitrary epoch changes with a new serving incarnation. Add tests for a different node, a changed incarnation, mixed fallback provenance, and mismatched ack handles, alongside valid compact/fallback equivalence.

M1 — Complete the array metadata mapper correction

Severity: Medium. Status: resolved in follow-up; initially reproduced by the phase gate. The earlier Task 2 finding added DataMetadata.ArrayElementKind and protobuf field 13, but EncodeMetadata did not assign it and DecodeMetadata did not read it or call DataMetadata.Validate (DataProtoMapper.cs:178–218). Empty integer and string arrays therefore lost their distinct type metadata. The new Array_metadata_preserves_element_kind_even_for_empty_arrays test failed at its element-kind assertion.

Correction: Preserve field presence and element kind in both directions and validate the completed metadata. Retain the existing positive regression and add missing/unknown element kind, nested/unsupported element kind, and scalar-with-array-kind rejection cases. Validate rank/dimension structure together with the type information rather than allowing contradictory metadata into the projection layer.

M2 — Separate frame item limits from typed-array element limits

Severity: Medium. Status: resolved in follow-up. Originally, DecodeCompact passed frame maxItems into TypedValueCodec.Decode as maxElements (line 357); fallback did the same through DecodeSample (line 494), and writes repeated it at line 572. These are distinct quantities. A permitted one-item batch carrying a 100-element array failed with maxItems = 1, even when the array was supported and fit its element/byte limits. The original standalone array codec test did not exercise the framing paths.

Correction: Give value array elements their own receiver limit and pass it independently from the count of read/write/stream items. Advertise the limit where peers need it for admission. Add successful one-item/multi-element round trips for writes, compact, and fallback, plus independent rejection at each limit.

M3 — Negotiate additive capabilities without rejecting a compatible peer

Severity: Medium. Status: resolved in follow-up. Originally, DecodeCapabilities called DataContractValidation.Required on every advertised value kind (DataProtoMapper.cs:780–782). A newer peer on the same protocol major advertising an additional unknown kind alongside supported kinds therefore failed the entire handshake. The design requires unsupported capabilities to become unavailable individually while supported operations remain usable. Unknown values in an actual typed payload should still reject; capability advertisement is a different boundary.

Correction: Define explicit same-major intersection/fallback behavior for unknown advertised value kinds, operation bits, and compact versions. Preserve major-version rejection and do not silently accept an unknown actual payload. Add old/new peer capability tests with both known and unknown kinds, an unsupported compact version falling back, and a major mismatch. The current unknown-protobuf-field preservation test does not cover this negotiation behavior.

M4 — Freeze all wire decisions and compatibility-sensitive descriptors

Severity: Medium. Status: resolved after final follow-up. Originally, most wire decisions were bare int32 fields populated by casts from implicitly numbered C# enums (DataContracts.cs:3–8). Inserting a status/write/control enum member could silently renumber deployed meanings. DataConnectionProtoContract.Validate pinned only three field numbers and the zero ValueKind; the test added one compact timestamp field. Most field numbers, wire types, oneofs, enum values, operation bits, and service request/response signatures were consequently outside the promised contract lock.

Correction: Assign explicit stable values to every wire-visible decision and pin the complete message/service/enum contract with a descriptor snapshot or equivalent comprehensive assertions. Protobuf enums are preferable for self-describing decisions; explicit domain-number assertions are required if int32 remains deliberate. Reserve removed numbers/names. Keep evolution tests additive: adding fields/capabilities must not authorize renumbering existing ones. Add write-payload-hash tests proving correlation/remaining-budget independence and changes for value/address/semantic preconditions; those critical hash invariants currently have no test despite WritePayloadHash being implemented.

M5 — Define and enforce malformed envelope invariants at decode boundaries

Severity: Medium. Status: resolved after final follow-up. Originally, required enum validation was present in several paths, but the domain constructors/decoders otherwise accepted structurally invalid state. Examples included empty node/incarnation and arbitrary epochs from DecodeServing (70–74), negative negotiated capacity values from DecodeCapabilities (790–800), and command/frame IDs, epochs, timeouts, and sequence values copied without validation. DecodeSettings accepted nonfinite deadband values without defining their meaning; DecodeBrowseResponse constructed a nonpositive lease without validating it. DataView.Validate also permitted a positive mapping revision with no mapping ID. These values must not become apparently valid domain envelopes on which later admission and ordering code depends.

Correction: Define shared structural validation for identities, generations, settings, limits, leases, and required command/frame fields, then invoke it consistently on both mapping paths. Document any deliberately allowed sentinel values such as zero sampling before enforcing them; distinguish such protocol semantics from unsupported policy requests. Reject malformed known decisions and illegal combinations before later services consume them. Add focused negative cases for the examples above and full request/response/command round trips for all six services. Timestamp tests should cover nonzero subsecond precision and establish the policy for protobuf precision finer than the domain's ticks.

Evidence and coverage limits

The completed phase run 20261116T022304.446452Z-4dfc62e5c9c2 records the candidate SHA, tracked diff hash, and per-untracked-file hashes. Core.Abstractions executed 9 tests, all passed, with zero skips; its expected new and existing classes were verified. Commons executed 21 tests: 20 passed, 1 failed, zero skipped. The failure is the array metadata regression above; run.json correctly reports the phase as failed. No whole-solution or integration result is inferred.

The intermediate phase run 20261116T023911.320464Z-fa7c2928e3f6 also records the candidate digests and correctly reports failure. Core.Abstractions executed 13 tests, all passed, zero skipped. Commons executed 33 tests: 32 passed, one failed, zero skipped. The only failure was the generated UInt8/Uint8 enum-name casing in the new contract-number test; the new metadata, aggregate-write/count, serving-context, independent-array-limit, capability, timestamp, and hash cases passed. The reviewer inspected run.json and the failure log directly.

Final phase evidence: 20261116T024814.318745Z-3a06bbb5af5e passed. Core.Abstractions executed 15 tests and Commons executed 36, with zero failures/skips in either project. The runner verified GrpcDataContractsTests, GrpcDataProtoContractTests, GrpcDataCodecTests, GrpcDataCompactCodecTests and all required existing selectors (DataChangeBatchContractTests, DeploymentArtifactProtoTests, MeshTransportProtoContractTests, TelemetryProtoContractTests). The reviewer inspected run.json and compared every recorded new source/test file digest with the final files on disk; all matched. This was evidence inspection, not a reviewer test execution.

The initial candidate's new tests cover enum validation examples, explicit write-outcome classification, optional timestamps, copied input bytes, request-start lease timing, handle revisions, scalar/array codec examples, one compact absence override, one stale handle, one mixed compact encoding case, control/ack round trips, and a small golden/unknown-field payload. They do not yet establish the aggregate budgets, complete service envelope mappings, expected serving provenance, operation hash, or additive negotiation required by this checkpoint.

Reviewed strengths and earlier findings

  • The direct API composes browse/metadata/read/write/subscription without actor, OPC UA SDK, generated gRPC, or channel types. The service descriptor defines the six planned methods, with bidirectional subscription streaming. Existing mesh/telemetry proto registrations are unchanged.
  • The Task 2 admission correction now separates stable principal from authenticated ApiKeyId and optional credential expiry. The contract explicitly requires checking the original credential at dispatch even when the authority epoch is unchanged. Actual P03/P05 revalidation and expiry behavior remain later gates.
  • DataValue copies input bytes, array elements, and dimensions; supported scalar elements are immutable. Retain creates a separate disposal state, and getters do not expose the private mutable byte/array storage. This is a managed-copy implementation, not evidence of pooled payload release or bounded retained memory under hub/stream load. Add independent-lease disposal tests as ownership behavior develops.
  • Full unsigned status codes, UInt64 values, null versus empty byte/array values, original optional timestamps, and explicit uncertain/unconfirmed write outcomes are represented. Compact timestamp override messages can express inherited, explicitly absent, and explicitly present values. The compact encoder refuses mixed provenance within a batch, and both decoders reject unknown/removed handle revisions.
  • The hash implementation omits transport correlation and remaining budget and includes the value/view and incarnation/catalog preconditions. Its missing regression coverage is called out in M4. No automatic retry or transport behavior is introduced by these contract files.

No unresolved P01 contract-freeze finding remains. Later runtime policy, queue ordering, revocation, ingress authentication, Docker, scaling, and final-suite gates remain outstanding.