feat: define validated grpc data contracts and codecs

This commit is contained in:
Joseph Doherty
2026-11-15 21:52:49 -05:00
parent 28aabaf82d
commit 9cda2dd8d0
17 changed files with 3639 additions and 3 deletions
@@ -10,7 +10,7 @@
---
Status: Astra reviewed; approved for user implementation-plan review after revision. Awaiting user review. This task prepares a plan only; it does not authorize implementation, builds, running fixtures or deployment.
Status: Astra-reviewed plan; user has authorized implementation with the specified subagents and gates. Execution is in progress on `codex/grpc-data-connections`; see [execution ledger](evidence/grpc-data/README.md). Remote deployment/push/merge remains outside this implementation request.
Design: [reviewed design](2026-11-15-grpc-data-connections-design.md). Design review: [Astra design findings](2026-11-15-grpc-data-connections-astra-review.md). Plan review: [Astra implementation-plan review](2026-11-15-grpc-data-connections-plan-astra-review.md).
+12 -2
View File
@@ -16,8 +16,8 @@ The [implementation plan](../../2026-11-15-grpc-data-connections-implementation-
| Phase | Scope | Status | Evidence |
|---|---|---|---|
| P00 | Unit discovery isolation and execution controls | Passed | 22 Python runner units after Astra correction; 2 C# guard units, zero failures/skips; clean phase run `20261116T020813.843515Z-2ebe0fbcb7d2` |
| P01 | Domain/protobuf contracts | In progress | Domain-contract worker next; codec follows frozen types |
| P02 | Schema/artifact/consumer projection | Pending | |
| P01 | Domain/protobuf contracts | Passed; Astra freeze approved | 15 domain + 36 wire tests, zero failures/skips; run `20261116T024814.318745Z-3a06bbb5af5e` |
| P02 | Schema/artifact/consumer projection | In progress | Schema/validator worker next; artifact projection follows entity freeze |
| P03 | Shared authorization and leases | Pending | |
| P04 | Immutable publication, hub and local ports | Pending | |
| P05 | Mutation tickets/outcomes | Pending | |
@@ -58,3 +58,13 @@ Runtime artifacts belong under ignored `artifacts/grpc-data/`; this tracked ledg
## P00 verification
The runner tests first failed as expected while `run-unit-phase.py` was absent. After initial implementation, 18 fake-subprocess Python units passed. Astra found required existing regression classes were not enforced as strictly as new classes; four added regression tests failed before the correction. The final 22 Python tests passed, with red/green logs in `artifacts/grpc-data/p00-runner-regressions/`. The real P00 discovery/execution runner passed both counting-probe/reaper C# tests with no skips; the starting production graph compiled successfully. No solution test run or Docker mutation occurred. Raw TRX/commands/discovery identities remain in ignored artifacts. The runner validates discovery AND executed results for every required new class, retains parameterized class filters, and sanitizes both child environments. Astra approved P00 after the required-existing-class correction; see [checkpoint review](p00-astra-review.md).
## P03 preparation obligations
Read-only security preparation confirmed that caller-supplied `DataView.Subject` is a claim, never an ACL authority. P03 resolves subject/provenance against the active deployed catalog before either Raw/UNS fallback or cache lookup, and strictly caller-bound facades carry authenticated principal/key/version/original expiry. Revalidate the current key principal and credential version as well as expiry even without an authority-generation change. Deep-copy mutable authority inputs before publishing security snapshots. Failed desired-authority staging must close new mapped/data access rather than retain stale permissions. These obligations supplement the planned spoofed-subject, queued expiry, same-ID credential replacement, deep-copy mutation, and failed/empty apply tests; they are not yet implemented.
## P01 verification and frozen contracts
Test-first domain/protocol changes and targeted review regressions produced recorded failures before correction. Final P01 run `20261116T024814.318745Z-3a06bbb5af5e` passed 15 Core.Abstractions and 36 Commons tests, including named existing protocol regressions, with no failures or skips. No broad unit or integration suite was run. [Astra checkpoint](p01-astra-review.md) approves P01 freeze only after cluster identity, original credential identity, array metadata, receiver-owned aggregate decoding, per-value element limits, pinned stream provenance, additive negotiation and structural/descriptor corrections.
The frozen facade is caller-bound through `IDataConnectionFactory` and `DataAuthenticatedContext`; no authenticated identity comes from protobuf claims. `DataWriteAdmission` retains original key/version/expiry. Capabilities carry cluster identity and independently advertised array-element limits. Compact and fallback stream decoding require expected serving identity. Array/byte storage uses defensive managed copies and separate disposable leases; pooling is deferred. Post-parse budget checks do not substitute for the P07 transport parse/decompression or P11 measured-memory gates.
@@ -0,0 +1,108 @@
# 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. Candidate file digests are recorded in phase runs `20261116T022304.446452Z-4dfc62e5c9c2` and `20261116T023911.320464Z-fa7c2928e3f6`.
**Disposition after follow-up: revisions required; H2 and M5 remain open, and final green evidence is pending.** H1, H3, M1, M2, and M3 are resolved in the corrected candidate. M4's source correction is sound, with its test-name casing fix awaiting passing evidence. 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](../../2026-11-15-grpc-data-connections-implementation-plan.md), [design](../../2026-11-15-grpc-data-connections-design.md), 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 | Partially resolved: receiver-owned `DataDecodeLimits`, aggregate typed-value accounting, collection-count checks, and read/write/metadata response helpers are present. `DecodeMetadata` checks the fixed 16-dimension ceiling before `ToArray`. Remaining gaps and evidence requests are 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 | Source correction complete: stable explicit domain values, full existing-field descriptor assertions, service signatures, and hash invariance/change tests are present. The second run failed only because the generated wire enum uses `Uint8` while the test parsed `UInt8` case-sensitively. The reviewed `ignoreCase: true` correction needs successful execution before closing this evidence item. |
| M5 | Partially 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 residual cases below still pass through the decode boundary. |
### H2 residual work
`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.
### M5 residual work
- `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.
## 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: open.** `DecodeWriteRequest` checks aggregate encoded size, then independently decodes every value with the entire `maxBytes` allowance (`DataProtoMapper.cs:559–585`). It never sums decoded storage, so several individually small values can collectively exceed the batch's decoded budget. For example, two byte values each accepted by the per-value decoded limit can fit the encoded envelope while their combined copies exceed 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: source corrected; final passing evidence pending.** 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: open.** Required enum validation is present in several paths, but the domain constructors/decoders otherwise accept structurally invalid state. Examples include 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` accepts nonfinite deadband values without defining their meaning; `DecodeBrowseResponse` constructs a nonpositive lease without validating it. `DataView.Validate` also permits a positive mapping revision with no mapping ID. These values should 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 follow-up 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. The casing correction was read in source but has no passing result in this review's evidence yet.
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.
The residual H2/M5 work and final focused green evidence are required before the P01 freeze is approved. Later runtime policy, queue ordering, revocation, ingress authentication, Docker, scaling, and final-suite gates remain outstanding.