feat: preserve grpc write admission and uncertain outcomes

This commit is contained in:
Joseph Doherty
2026-11-16 03:56:13 -05:00
parent 8f28a0eabf
commit 862dbc8e90
37 changed files with 3686 additions and 70 deletions
+25 -3
View File
@@ -20,7 +20,7 @@ The [implementation plan](../../2026-11-15-grpc-data-connections-implementation-
| P02 | Schema/artifact/consumer projection | Passed; Astra approved | 72 F + 31 P + 106 R, no failures/skips; final run `20261116T034337.311145Z-cd97a339f340` |
| P03 | Shared authorization and leases | Passed; Astra approved | 77 K + 89 O + 53 R + 19 H, no failures/skips; final run `20261116T034150.797719Z-8f107e03d8d5` |
| P04 | Immutable publication, hub and local ports | Passed; Astra approved | 185 R + 16 A + 16 C + 77 O + 74 ScriptWorker + 88 MTConnect + 40 OpcUaClient = 496, no failures/skips; final run `20261116T060538.590404Z-b8ef1894731e` |
| P05 | Mutation tickets/outcomes | Pending | |
| P05 | Mutation tickets/outcomes | Passed; Astra approved | Complete gate 910/910 passed `20261116T084759.594405Z-42a294fc7f4f` after three Astra regression corrections; source and candidate reconciliation approved |
| P06 | Streams/sharing/fair delivery | Pending | |
| P07 | TLS/provisioning/node+cluster clients | Pending | |
| P08 | Raw/UNS projection and adapter | Pending | |
@@ -67,6 +67,28 @@ Final [Astra P02/P03 review](p02-p03-astra-review.md) closes all five findings a
Independent Python helpers for local-context validation, fixture endpoint/manifest isolation, ownership-only cleanup, atomic secret files, bounded/redacted processes, deployment outcome polling and CLI result validation have test-first preparation evidence: initial discovery failed on missing modules; the focused combined run subsequently passed 44 tests. This is not the P10 gate. Concrete Compose, SQL/device/seeder, TLS/provisioning, runtime observation, CLI/probe scenarios and actual Docker integration remain pending. No containers or databases have been modified.
## P05 execution notes
Runtime and SDK missing-API RED evidence is `20261116T062437.578601Z-6e2b4f1b2274` and `20261116T062507.986231Z-c09214fa8087`. The real DI composition test failed on the missing shared fence in `20261116T064939.908320Z-4dd869b001d4`; runtime registration now supplies one singleton without replacing an explicit registration. Rich actor creation initially failed all 19 startup checks because Akka constructor-based Props could not use the private rich constructor. An explicit indirect producer fixed creation, verified by one narrowly filtered positive test in `20261116T071454.486118Z-e187323e8fe5`; this was a diagnostic selection through the same discovery/TRX/source-identity guards, not a complete phase gate.
| Boundary | Observed RED | Correction / focused evidence |
|---|---|---|
| Original credential, authority, route and role admission | Missing API above | First 12 admission checks passed `20261116T065544.493707Z-3eb41ed1767c`; actual composed catalog/policy/actor checks are included in the driver cases |
| Stop/restart retirement, injected-clock gateway deadline, snapshot-role callback order | 15 passed / 4 failed `20261116T071731.988476Z-ab7eaaea4c9b` | All original 19 cases subsequently passed inside the physical-overlap RED run below |
| Rich physical same-target exclusion | 19 passed / 2 failed `20261116T072907.706321Z-c0a3b2178516` | Shared keyed permit now survives actor replacement, ID case variation, caller timeout and observation expiry; verified in the 910-test gate |
| Principal duplicate identity | 5 passed / 1 failed `20261116T070925.834679Z-03e9d268979d` | Principal uses OrdinalIgnoreCase; operation ID remains Ordinal |
| Late confirmation retention | 3 passed / 1 failed `20261116T072347.015611Z-61960f01d936` | Accepted definitive refinement refreshes result retention before physical release |
| Expired observer result authority | 12 passed / 1 failed `20261116T074826.305696Z-f170f189f3b8` | Physical observer is the sole definitive publisher; the expiry case passed in the later 15-case hash RED |
| Membership-event callback ordering | 8 passed / 1 failed `20261116T080834.575675Z-a81b507a518b` | Primary publication moved ahead of independent history callbacks; verified in the 910-test gate |
| Authoritative SDK value and timestamp | 3 passed / 4 failed `20261116T065427.180129Z-23fa1d306a25` | All 7 passed `20261116T073441.203032Z-e27a76f907e9`; uncertainty restores last authoritative value/time and marks uncertain |
| Concrete Modbus rich outcome / no resend | Capability absent, `20261116T065504.810035Z-1d3c011bd4e3` | All 20 passed `20261116T074539.497522Z-2b59ad2f16cd`, including real TCP dropped reply after effect and unsupported injected transport |
| Allocation-bounded exact value fingerprint | Missing internal method, `20261116T080329.365239Z-f4c6626ad391` | All 8 passed `20261116T081444.424298Z-0adf33e9701f`; no large GetBytes/GetArray copies during hashing |
| Resolved address and exact string operation semantics | 13 passed / 2 failed `20261116T082102.902677Z-dd7a6a847714` | Canonical catalog view and lossless UTF-16 metadata hashing verified in the 910-test gate |
The first complete P05 gate passed 906 tests in `20261116T082435.847137Z-41e436e72d95`. [Astra's final source review](p05-astra-review.md) then identified three uncovered cases. Real TCP FC23 wrong-function exception fallback produced the expected failure in `20261116T083756.925253Z-ac0395f545eb` (21 passed/one failed); its no-replay correction passed all 22 focused cases in `20261116T084606.160092Z-73c1868a8b65`. The current-key-expiry fence-wait test failed in `20261116T084157.535508Z-509aba58e961` (22 passed/one failed), and the actual coordinator-backed source callback blocked in `20261116T084419.395301Z-6c55e8767242` (19 passed/one failed). Current immutable key expiry is now checked with original expiry under the final dispatch fence; role-wrapper cache refresh uses nonblocking fence acquisition and provisional process provenance on contention. The final complete gate passed **910** tests (195 Runtime, 70 SDK, 29 Core, 593 Modbus, 23 Abstractions), no failures/skips, in `20261116T084759.594405Z-42a294fc7f4f`. Astra verified the final candidate hashes and approved P05.
The [physical lifetime review](p05-physical-lifetime-astra-review.md) requires keyed rich-to-rich exclusion for known pending raw tasks. It does not promise universal device ordering against the unchanged legacy abandonment path, fire-and-forget application, different logical references or another process. Both factory-supported Modbus modes provide an explicit no-resend transport path; legacy transport recovery is preserved. The rich SDK hook remains unbound until the complete authorized P08 mapping route exists. No Docker or database apply has run.
## P04 execution notes
Hub and source-feed expected missing-API RED runs: `20261116T035138.678709Z-921224df1e45` and `20261116T035253.701549Z-3677798d45ff`. The coordinated production graph then compiled while the Task10 test failed on the missing local catalog/facade APIs in `20261116T040451.917499Z-9fc5a1cf55f8`. [Publication review](p04-publication-astra-review.md) identified producer blocking, lifecycle, binding recovery and virtual freshness issues; correction candidates remain unapproved until their behavioral gate and rereview finish.
@@ -79,9 +101,9 @@ The P04 selector manifest adds only affected virtual/restart, timestamp/worker/h
## Later-phase integration obligations
P05 read-only preparation located the actual device invocation inside the resilience delegate, after actor dispatch and `Task.Yield`; final ticket validation must occur there. Capture the actual driver task for bounded late observation, because the resilience wrapper can time out first. Legacy Good acknowledgments without established device-application guarantees remain unconfirmed.
P05 read-only preparation located the actual device invocation inside the resilience delegate, after actor dispatch and `Task.Yield`; final ticket validation must occur there. Capture the actual driver task for bounded late observation, because the resilience wrapper can time out first. Legacy Good acknowledgments without established device-application guarantees remain unconfirmed. The agreed rich path shares a short dispatch/publication fence across actual authority, catalog, primary-verdict, route and driver-lifetime pointer changes; permission evaluation, callbacks and arbitrary driver code remain outside it. The dispatch mark is the documented linearization point immediately before the driver call on the same delegate path. Dispatched Unknown claims and physical-call/payload permits remain pinned until the actual task ends, even after observer retention expires. Real per-item endpoint switching belongs to the P07 connection-client gate, with mapped integration in P08; P05 must prove ordered partial executor outcomes without a fabricated failover client.
P06 must prove retained snapshot acquisition age survives transport/reconnect independently of optional wall-clock timestamps. Current unary `ReadResult` carries age, while subscription values do not yet carry an explicit age field; resolve this at the stream contract checkpoint rather than infer freshness from receipt. P07 should construct remote realm roots using the canonical cluster identity from validated capabilities, and compose source publishers with real atomic process/role provenance shared with the catalog coordinator.
The [Astra P06 contract checkpoint](p06-contract-astra-review.md) approves additive age/readiness with explicit domain age uncertainty, successful delivery receipts, finite session expiry and real acknowledged acquisition demand. It approves no implementation yet. P06 must prove retained snapshot acquisition age survives transport/reconnect independently of optional wall-clock timestamps. Current unary `ReadResult` carries age, while subscription values do not yet carry an explicit age field; resolve this at the stream contract checkpoint rather than infer freshness from receipt. P07 should construct remote realm roots using the canonical cluster identity from validated capabilities, and compose source publishers with real atomic process/role provenance shared with the catalog coordinator.
## P00 verification
@@ -0,0 +1,58 @@
# P05 Astra implementation review
**Disposition: approved for P05 source freeze.** All three findings below are resolved in the reviewed correction candidate and complete applicable gate. The final gate passed **910 tests with zero failures/skips**. This is a P05 checkpoint, not approval of the complete data-connection feature.
The review is read-only except this evidence document. No reviewer builds, tests, production changes, migration execution or Docker work were performed. Scope covers Task 11/12 admission, actual actor invocation, publication fencing, operation retention, physical resource lifetime, SDK rich completion, Modbus rich no-resend handling and exact value/metadata fingerprints. The plan, design obligations and execution ledger informed the review.
## Candidate and verification evidence
Final complete gate `artifacts/grpc-data/20261116T084759.594405Z-42a294fc7f4f/unit/P05/run.json` reports **910 passed, zero failures/skips**: Runtime 195, SDK 70, Core 29, Modbus 593 and Core.Abstractions 23. Every new and required existing class is represented in execution; this gate has no platform exclusions. Before this final review-document edit, the reviewed checkout matched its recorded baseline `70f50201e9140aa51b64b289e608c3bea4061003`, tracked binary-diff SHA-256 `5c12ff3d22f130314af6e84055bb94200682167f6decfe841c0fd57ca77fcd5a` and all 19 recorded untracked file hashes. That includes 16 source/test files and three review documents. This document's disposition update is the sole reviewer change after reconciliation.
The preceding complete gate `20261116T082435.847137Z-41e436e72d95` passed 906 tests but did not cover the three issues found during source review. Its tracked diff SHA-256 was `8f3d9145aeff119443b6b9d9028e6ee897f1c0be8455962f235a968631f6968a`; its 18 recorded untracked hashes also matched the then-reviewed checkout. The additional correction regressions are included in the final 910-test gate.
The execution ledger records the actual failing tests preceding the existing corrections. Relevant evidence includes physical same-target RED `20261116T072907.706321Z-c0a3b2178516`, late-retention RED `20261116T072347.015611Z-61960f01d936`, observer-expiry RED `20261116T074826.305696Z-f170f189f3b8`, real actor ordering RED `20261116T071731.988476Z-ab7eaaea4c9b`, membership callback ordering RED `20261116T080834.575675Z-a81b507a518b`, SDK RED `20261116T065427.180129Z-23fa1d306a25`, and canonical metadata hashing RED `20261116T082102.902677Z-dd7a6a847714`. The complete gate covers their corrected candidates.
## H1 — Mismatched Modbus exception can trigger a second mutation
**Severity: High. Status: resolved.** In the initially reviewed `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusDriver.cs:1568`, `SingleSendWriteTransport` correctly declined to classify a mismatched exception function as a definitive refusal, but rethrew the original `ModbusException`. `TryWriteViaFc23Async` at line 1830 caught every exception with code `0x01`, without matching the requested function, and returned false. `WriteOneAsync` then sent FC16 as its fallback.
Consequently an FC23 request followed by a matching transaction/unit but mismatched exception function, for example FC6/code1, can issue a second mutation after an ambiguous first response. Transport-level retry is disabled, but this driver-level fallback still violates the rich no-replay boundary. The existing wrong-function test mutates a normal FC23 response and does not exercise the exception catch.
Reject a mismatched exception function as an invalid/ambiguous response before the rich path reaches the legacy fallback, or constrain that fallback to the exact requested FC23 function. Preserve fallback after a valid FC23 Illegal Function response, which proves that request did not perform the write. Add a regression with an exact physical send/effect count: malformed exception response must yield Unknown and one send; valid FC23 Illegal Function may still lead to the safe FC16 fallback. A real TCP fixture is preferred because this crosses the response parser and fallback together.
**Resolution:** the rich wrapper now converts a mismatched write exception function to `InvalidDataException` before the FC23 fallback catch. Its definitive-refusal flag remains false and the outcome is Unknown. Actual RED `20261116T083756.925253Z-ac0395f545eb` passed 21 tests and failed this new case by incorrectly reporting confirmed success. Focused gate `20261116T084606.160092Z-73c1868a8b65` then passed all 22. The real TCP regression verifies an FC23 effect followed by `0x86/0x01` produces one request, one effect and Unknown; its positive counterpart verifies exact `0x97/0x01` permits two requests but one effect through FC16. Both pass in the complete final gate. The change is confined to the rich wrapper and preserves legacy behavior.
## H2 — Current key expiry is not rechecked at dispatch commitment
**Severity: High. Status: resolved.** The initially reviewed `src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataWriteDispatchGate.cs:36` checked current key usability before acquiring the publication fence. The final fenced check at line 49 checked only the ticket's original `CredentialExpiresUtc`. Current key expiry can be earlier than that original timestamp, or the original timestamp can be absent: changing a deployed key's expiry does not change its secret-derived credential version.
A context authenticated under a nonexpiring/later-expiring key can remain usable after its key's expiry has been shortened. If the current key is still valid during policy evaluation but expires while this invocation waits for the fence, authority/catalog references remain unchanged and the final check can commit dispatch after current key expiry. The existing expiry regression advances time before policy evaluation and uses the caller expiry, so does not establish this boundary.
Inside the final short fence, recheck the already captured immutable authority's key binding and expiry against the current time, as well as the original context expiry. Keep permission evaluation and callbacks outside the fence; expose a bounded immutable credential check rather than invoking the evaluator there. A deterministic regression should hold the fence after policy succeeds, advance UTC across the current key expiry while original expiry is null/later, release it, and verify a terminal undispatched rejection with zero backend calls.
**Resolution:** the gate captures current enabled key facts and verifies principal/credential version from its captured immutable authority before policy evaluation. It keeps the current key expiry as a local value. After acquiring the fence it checks both this expiry and the original context expiry against one fresh UTC sample, while the authority identity check ensures those captured facts remain authoritative. Hashing, key copying and permission evaluation remain outside the fence. Actual RED `20261116T084157.535508Z-509aba58e961` passed 22 tests and failed the real actor/current-key-expiry case by confirming the write. That regression holds the fence, waits for the last successful policy UTC read, advances time beyond current key expiry with a null original expiry, and verifies rejection/zero device calls; it passes in the final complete gate. Taking the UTC sample at the start of this short fenced block is acceptable: the remaining checks are bounded immutable reads with no await, permission evaluator or driver callback. The correction closes the demonstrated fence-wait expiry gap without promising an atomic wall-clock-and-CAS instruction.
## M1 — Role-wrapper refresh makes acquisition callbacks block again
**Severity: Medium. Status: resolved.** The initially reviewed `src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalCatalogCoordinator.cs:61` called blocking `DispatchFence.Enter()` when `Current` had to replace its cached serving-role wrapper. P04 approved that accessor as a bounded lock-free read/CAS path. `SourceSamplePublisher.TryPublish` calls its supplied serving provider at `SourceSamplePublisher.cs:338` while in the producer callback and per-source gate; the coordinator-backed provider traverses `Serving` and `Current`.
A role mismatch while another thread holds the dispatch fence therefore makes the new ingress wait, despite the surrounding source and hub gates using nonblocking acquisition. The scope is the production coordinator-backed source provider; it does not depend on an arbitrary malicious callback.
Use a nonblocking fence acquisition for read-side wrapper refresh and return an appropriate unavailable/provisional identity on contention, or arrange control-side publication with lock-free reads. Preserve current producer identity and actual acquisition timestamps; dropping a contended acquisition must not replay it later as fresh. Add the composed regression: coordinator-backed publisher, cached role mismatch, another thread holding the dispatch fence, and a producer callback that completes without waiting for that holder.
**Resolution:** `DataWriteDispatchFence.TryEnter` uses `Monitor.TryEnter` with no wait. The bounded `Current` refresh returns null on contention; `Serving` then provides actual process identity/current role with provisional zero epochs, as permitted by the P04 acquisition boundary. Source publisher and hub remain unchanged. Actual RED `20261116T084419.395301Z-6c55e8767242` passed 19 tests and failed the new callback case because it waited for the fence. The composed publisher/coordinator regression now completes before the held fence is released, preserves the active producer, and verifies a subsequent real acquisition's value and original source timestamp. It passes in the final complete gate. Public serving still requires the established catalog/authority validation; provisional raw retention does not make a public catalog ready.
## Resolved earlier findings and reviewed behavior
- The [earlier physical-lifetime review](p05-physical-lifetime-astra-review.md) is superseded for its two findings: `LateWriteObserver` now reserves the global slot and `(driver ID, reference)` key together, using driver `OrdinalIgnoreCase` and reference `Ordinal`. Release follows actual raw invocation completion, including synchronous blocking before a task is returned. Caller timeout, observer expiry and actor replacement do not release that target. Real actor regressions use capacity two, prove another target progresses, and cover replacement driver ID case variation. Local actor slots can still be abandoned as in the legacy path.
- Accepted definitive `LateRefine` updates the retained-result timestamp before physical completion becomes visible. The one-minute registry/five-minute observer regression confirms a result arriving after two minutes remains Existing for its new result-retention window. Previously completed Unknown waiter tasks stay immutable; current retained outcome supplies the refinement.
- The actual rich driver call is inside the non-idempotent resilience invoker delegate. Ticket validation runs there immediately before the dispatch CAS. Driver code, permission evaluation and authority notifications run outside the short publication fence. Authority/catalog/route/lifetime and primary-generation publications share the fence; remap-away-and-back and demote/promote do not revive old proofs. H2 now also checks current-key expiry after fence acquisition.
- Dispatch and proven no-call rejection compete through the claim transition. Released queued tickets cannot later invoke the driver. The raw-task observer alone publishes definitive dispatched results; outer Ask/invoker replies can establish no-call rejection or Unknown but cannot refine beyond observer retention. Payload and physical capacity remain charged until the actual invocation exits.
- Executor admission uses authenticated context, resolved catalog view and trusted route, enforces authorization/export/write/type readiness before dispatch, retains its own value lease, joins duplicate operation IDs without tying shared work to a waiter's cancellation, and preserves per-item input order. Registry principal comparison matches case-insensitive principal identity while operation IDs remain ordinal. Internal canonical fingerprints preserve typed shape, ordinal UTF-16 including unpaired surrogates and floating-point bits without a payload-sized hashing copy.
- SDK rich completion is asynchronous and uses the exact node/write stamp. Rejection/confirmed failure restores prior authoritative value, status and source timestamp. Unknown/AcceptedUnconfirmed restores the prior value/time with `UncertainLastUsableValue`. Equal-valued fresh source updates, newer writes and recreated nodes cannot be overwritten by stale completions. No optimistic value is published to the sample hub by this seam.
- Modbus rich TCP and RTU-over-TCP calls disable transport resend after ambiguous loss and keep legacy recovery behavior. Valid normal echoes/readback shape are checked, and real TCP dropped-reply-after-effect evidence exists. H1's mismatched-exception fallback hole is resolved by the rich wrapper and actual TCP regression.
- Runtime DI supplies one shared dispatch fence without overriding an explicit registration. Production data service wiring belongs to P07; the SDK hook remains unbound until the authorized P08 mapping route exists. Real endpoint failover belongs to P07/P08, not a fabricated P05 client.
The target exclusion guarantee is limited to rich-to-rich known pending raw tasks in this process. It does not promise universal device ordering against legacy abandoned operations, different references naming the same device storage, fire-and-forget application after a task returns, or another process. Those limitations do not excuse replay of a known ambiguous mutation or dispatch using expired current credentials.
The focused correction rereview and reconciled complete applicable gate satisfy the P05 checkpoint. No P05 findings remain open; dependent implementation may proceed subject to its own planned gates and review.
@@ -0,0 +1,28 @@
# P05 Astra physical-lifetime checkpoint
**Disposition: a rich-write target-lifetime guard is required before approving this boundary.** This narrow source review inspected `RunRichWriteAsync`, actor queue completion, `LateWriteObserver` and `WriteOperationRegistry` at baseline `70f50201e` plus the current P05 candidate. No source edits, builds or tests were performed. This is not a whole-P05 review.
## Confirmed overlap after abandonment
`DriverInstanceActor.RunRichWriteAsync` around lines 1338–1351 waits for the invoker outcome only through its bounded timeout/abandonment window, then unconditionally sends `WriteCompleted`. `OnWriteCompleted` around lines 1499–1505 removes `_tagsInFlight` and drains the queue. The separately retained `LateWriteReservation` correctly keeps the payload and global physical permit until the raw invocation actually exits, including synchronous blocking before it returns a task. However, that permit is only a node-wide count.
With at least two global physical permits, a token-ignoring rich write A can remain physically pending after its caller receives Unknown and its actor tag slot is released. A **different operation ID** B for the same trusted driver/reference can then pass the ordinary tag check, reserve the second permit and dispatch. A's later completion may occur after B. Duplicate-operation protection does not help because these are intentionally different operations. The current physical-capacity regression uses a limit of one, which hides this per-target gap.
Task 11 requires per-tag serialization and bounded physical work. Its compatibility requirement preserves the established legacy timeout behavior; it does not justify representing a known-pending rich invocation as physically finished. For the additive rich path, preserve the per-target physical exclusion while retaining bounded caller response and actor-slot release.
## Minimal guard
- Reserve a process-shared rich physical-target key together with the existing global permit. Use the trusted stable driver ID plus the resolved driver reference, with the same identity comparison semantics as the route. Do not key by client view/alias, operation ID or actor/driver incarnation: replacement actors must still see the known pending invocation. Include an owner/cluster discriminator only if stable driver IDs are not already process-unique.
- Hold that key, physical permit and value lifetime until the actual raw invocation exits. Caller timeout, outer Ask failure, observer-retention expiry, registry retention, actor stop/restart and driver reincarnation must not release it. Every proven pre-dispatch rejection releases its unused reservation exactly once.
- Reject a conflicting new rich operation before dispatch, or keep it only within the existing bounded queue/expiry policy. A per-key busy check must not block unrelated references. Bound the key registry by the active physical-permit limit; clean entries at actual completion.
- Keep legacy admission behavior unchanged in this correction. Consequently the guarantee is **rich-to-rich known-task exclusion**, not universal device ordering against legacy abandoned writes, another process, or later device application behind a fire-and-forget API. Once an underlying task returns AcceptedUnconfirmed, no known pending task remains to guard; do not manufacture device confirmation.
The decisive regression uses `maxOutstanding >= 2`: A on target X ignores cancellation and remains live after its Unknown response; B with a new operation ID on X must not invoke the backend; C on another reference must progress. After A actually completes, a newly admitted write on X may run. Repeat the protected-key case through actor/driver replacement using the same shared observer. Verify exact raw call count and release once on both success and rejection.
## Known registry retention correction
The coordinator had already identified the `WriteClaim.LateRefine` timestamp issue; this is not a new finding. The inspected implementation replaces `_outcome` with a definitive late result but leaves `_completedTimestamp` at the earlier Unknown/AcceptedUnconfirmed response. `CanRetire` can then prune the newly refined result immediately after `PhysicalFinished`, allowing a same-ID claim to become Owner instead of returning the retained outcome.
Refresh the retained-result timestamp when a definitive late refinement is accepted, before publishing physical completion. The stated regression is appropriate: one-minute registry retention, five-minute observer retention, definitive raw completion at two minutes, then the duplicate must remain Existing with the definitive current outcome. Keep the already-completed waiter task immutable; late refinement is queried through the retained current outcome. This checkpoint does not assert the queued correction has passed.
Host-stop publication ordering, injected-clock Ask behavior, primary verdict ordering, SDK correction and Modbus transport behavior were explicitly outside this narrow review and are not newly reported here.
@@ -0,0 +1,48 @@
# P06 Astra contract checkpoint
**Disposition: approve the minimal contract direction below, subject to the required semantics and tests. This is not implementation or P06 phase approval.** This read-only checkpoint inspected Tasks 13/14, the approved design, the subscription/domain/protobuf contracts, snapshot cursor behavior and the existing driver desired-subscription boundary at baseline `70f50201e` plus active P05 work. No source was changed and no build/tests were run. Actor changes must remain serialized after the P05 owner finishes.
## 1. Preserve acquisition age without inventing network freshness
`SnapshotItem` currently retains a sample/version but not its source's monotonic received timestamp. `DataSubscriptionValue`, `ValueUpdate` and `CompactUpdate` currently carry no acquisition age or readiness. Required additions:
- Capture the **actual existing `SourceState.Received`** with the immutable snapshot item under the same partition capture lock. Retained snapshots, status-only changes, role/header overlays and reconnects must not replace it with snapshot/send/receive time. The timestamp remains process-local; never serialize an absolute monotonic counter.
- Add per-update optional `origin_age_ticks` and presence-bearing readiness to both fallback and compact forms, using new field numbers. Compute the elapsed origin age from the retained acquisition timestamp as late as practical at encoding/emission. A delayed encoded age is still a lower bound, never an exact receiver age. Preserve independently absent original source/server wall timestamps; do not infer age from them.
- Decode age with explicit uncertainty. A small domain `DataAgeBounds` value with nullable lower and upper durations is sufficient: absent age means unknown, not zero; a supplied nonnegative origin age gives a lower bound at receipt and **no finite stream upper bound**. Accumulate receiver-local monotonic elapsed time afterward. Validate negative values, overflow and inconsistent bounds. Age zero is valid only when explicitly present. An absent readiness field must not silently become Ready; negotiate support or expose unknown/unavailable readiness while preserving original sample quality separately.
- A receiver may certify a finite maximum-age requirement only from a known upper bound. `lower > maximum` proves stale; `lower <= maximum` with unknown upper proves neither fresh nor stale. Origin readiness, transport liveness and freshness are separate facts. A fresh authorized snapshot does not imply newly acquired device data.
**Decision:** additive wire age/readiness plus explicit domain age bounds/unknown freshness is sufficient for the current design. No stream probe/control extension is required now. Do not expose a plain lower-bound `TimeSpan` as though it were an exact age. A unary response can conservatively bound age above by its origin age plus elapsed time since that request began, provided the origin age was sampled within that causal request/response window. An unsolicited stream frame has no such finite upper bound. A later correlated probe may establish one only when its response is demonstrably ordered with the relevant sample/version; a heartbeat or metadata renewal alone cannot do so. Do not assume a finite one-way network delay or synchronized wall clocks.
Add codec parity/absence/invalid-duration tests and fake-time tests for a stalled snapshot, queued encoding, reconnect and status-only updates. Verify that absent wall timestamps do not prevent correct monotonic age, and that unknown stream freshness never satisfies a finite maximum-age predicate.
## 2. Commit delivery state at the actual adapter boundary
`ReadAllAsync` yielding a frame is not evidence of successful socket write. Use one serialized internal delivery sink/receipt boundary per stream. A prepared delivery owns bounded retained samples, authorization/publication gates, item/stream revisions and the expected committed baseline. The P07 transport adapter must await its actual `WriteAsync`; only successful completion acknowledges that delivery and commits the baseline/cursor. Failure, cancellation or ambiguous completion leaves no delivered baseline and resets/closes that epoch. This is transport acceptance, not a claim that the remote application consumed bytes.
The final authority/lease/revision check precedes handing bytes to the transport. Do not hold an actor/partition lock or a shared authority mutation lock through a potentially stalled socket write. Bytes already handed to the transport cannot be recalled; queued unsent payloads remain subject to the final gate. Removal acknowledgment is emitted only after earlier in-flight delivery is settled and every queued old-revision segment is canceled or rejected, so no old revision follows the acknowledgment.
Define the direct in-process adapter separately: enforce one consumer and choose an explicit successful bounded handoff/acceptance point. Commit there, or expose an acceptance receipt. Do not route the network adapter through an API that auto-commits merely on enumeration. Requesting the next item or disposing a frame must not accidentally stand in for an unobserved network result.
`SnapshotLease.TryReadDelta` currently mutates `_versions` and `_positions` before downstream delivery. P06 must replace or wrap that use with prepare/commit semantics. Keep **last considered version**, **pending retained candidate** and **last successfully delivered baseline** separate. Filtering/coalescing may advance considered work without claiming delivery; a failed candidate cannot advance the committed baseline or conceal a snapshot catch-up gap. Re-evaluate a candidate if its expected baseline changed while encoding. A receipt must be idempotent and scoped to the exact stream epoch/item revision so a late completion cannot commit into a replacement.
## 3. Use bounded session expiry and existing Open semantics
`OpenSubscription.SessionLifetime` already exists. Require a positive finite admitted duration, capped by server limits and current credential/authority lifetime. Expiry is measured monotonically and enforced even on a quiet control-only stream. At expiry, reject further commands/delivery, release demand and leases, and require a new Open/new stream epoch and snapshot. In v1, renewal can mean replacement with a newly authenticated Open; do not silently invent a renewal command or extend expiry on ordinary values/heartbeats.
If a requested duration cannot be admitted, reject it or report the effective duration explicitly; do not silently promise the requested lifetime while using an undisclosed revision. A duration is an upper lifetime limit, not a guarantee against earlier credential revocation. Separate command acknowledgment deadlines from session lifetime. An acknowledgment timeout after admission has an uncertain outcome and requires reconciliation through a fresh epoch/snapshot, not a fabricated rejection.
## 4. Acknowledge actual upstream demand, not mux interest
The current DriverHost sends a complete reference set with one publishing interval, and DriverInstance stores it then self-sends Subscribe. `SubscriptionEstablished` currently reports only diagnostic ID/reference count and is swallowed on ordinary self-resubscription; it proves neither a requested demand revision nor an effective sampling cadence. DependencyMux interest changes do not configure physical acquisition.
Required implementation boundary:
- Maintain a versioned demand registry merged with the existing legacy references/alarm behavior. Removing the final gRPC consumer must never remove a legacy interest. Preserve principal, export, target-mode/pinned-node, consistency and serving-generation isolation in sharing keys; shared physical samples do not share authorization.
- Carry a desired revision and current producer incarnation to the actual driver subscription operation; return an acknowledged applied revision with effective supported settings or a rejection. Ignore late acknowledgment from a superseded desired revision/producer. Completion of the current driver's real Subscribe operation is a minimum requirement; do not claim arbitrary sampling/filter support merely because the generic method accepted an interval argument.
- Compute the fastest admitted cadence and union of required triggers, with no upstream value deadband by default. Keep sampling and downstream publishing distinct. The current single driver-level interval may force a common faster cadence; revise/reject unsupported per-item demands honestly. An adapter whose physical cadence cannot change must report its known supported behavior instead of inventing acknowledgment.
- A stronger add/modify remains pending until the actual origin establishment is acknowledged. Then take the registration/snapshot/version boundary and emit revised settings plus acknowledgment in order. Failure or timeout releases the tentative interest and does not send a success snapshot. Only safe relaxation may debounce; churn must coalesce bounded desired revisions without losing the latest stronger request.
- Atomically install partition interest and capture its immutable state/watermark under the same owner boundary. Updates between physical acknowledgment and snapshot capture must be represented by the snapshot or later dirty generation. Multi-partition capture remains a vector, with bounded catch-up/reset; it does not imply cross-item atomicity. Keep steady interest ownership distinct from the finite snapshot payload lease so disposing sent snapshot chunks does not silently remove demand or lose the catch-up boundary.
Essential regressions are actual driver acknowledgment/revision ordering; faster-demand failure and revised settings; legacy-plus-gRPC union and last-interest removal; quiet source/revocation/expiry; source changes during registration/capture; old prepared candidate versus changed baseline; failed/ambiguous writer; remove acknowledgment versus a blocked prior send; and bounded snapshot cancellation/reconnect pressure. Existing fake hub or mux registration tests alone cannot prove physical cadence.
These contracts permit P06 implementation to proceed without adding an unneeded network freshness probe. The implementation checkpoint must still demonstrate the acknowledged origin boundary, actual writer receipt and bounded resource ownership before P06 approval.