Skip to content

impl(020): remote protocol refinements - #152

Merged
bartekus merged 8 commits into
mainfrom
impl/020-remote-protocol-refinements
Oct 21, 2026
Merged

bartekus merged 8 commits into
mainfrom
impl/020-remote-protocol-refinements

Conversation

@bartekus

@bartekus bartekus commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Spec 020: remote protocol refinements, increments 1 to 6 (phase ceilings, the host-endpoint principal reference and rustev.remote/2, bounded connection reuse, rustev.run/2, runtime-planned remote batches, Jev and verification). Every refinement is disabled by default, and a binding with every refinement disabled keeps its spec 009 bytes, artifact and PlanId.

Awaiting the owner. Spec 020 stays implementation: pending, and so stays out of make verify, because two acceptance items are not verifiable as written (recorded in the spec's implementation record):

  1. Multiplex cancellation (pool acceptance). The HTTP binding speaks HTTP/1.1 only, so a pool policy must declare one stream per connection; nothing is multiplexed and there is no multiplexed cancellation to test. Covering it needs an HTTP/2 binding, a new dependency that spec 021's audit would have to admit.
  2. "New qualification evidence for every enabled refinement" (Jev). No refinement is enabled on the Jev adapter, so there is none to produce; enabling one would need a new mapping version and a newly authorized qualification, which this spec does not authorize (3.7).

The ruling on these two decides whether 020 can be marked implemented.

Per increment

  • 1, phase ceilings (3.4, 3.1). rustev-remote-http/src/phases.rs (new): PhasePolicy (a positive ceiling per phase; zero refused at construction), TransportPhases (disabled by default), PhaseClock (each phase's allowance is the lesser of its ceiling and the budget left when it starts; phases only move forward) and phased. HttpTransport::with_phases enters resolution, connect, TLS handshake, request write, first response byte and response body on the real connection; TransportError::PhaseExpired. An expiry before request bytes is transport_unsent, after them transport_interrupted; no retry is added. The cancellation acknowledgement ceiling bounds every cancel exchange. rustev.remote-exchange/1 gains an optional phase_expiry; AdapterBinding::transport_phases is not written when disabled.
  • 2, principal reference and rustev.remote/2 (3.6, 3.7). rustev-contract: PROTOCOL_V2, InferRequest::principal (WirePrincipal, omitted when absent, refused in version 1 or when not canonical) and its domain-separated evidence digest; the exchange record's optional principal holds only that digest. rustev-remote-http/src/principal.rs (new): EndpointOperator, PrincipalSource, HandleAsReference, PrincipalPosture, PrincipalWire. The client negotiates exactly protocol_major (1 by default) and refuses a principal for a third-party endpoint, over version 1, or with a bad label. The server serves ServerConfig::versions ([1] by default) and includes the principal in idempotency content. Redirects stay unfollowed.
  • 3, bounded connection reuse (3.5). rustev-remote-http/src/pool.rs (new): PoolPolicy, host-owned ConnectionPool, KeyMaterial (every isolation member; credential and principal only as digests; unknown material never reuses). HttpTransport::post_observed swaps stream hooks per exchange, so the tracker and phase clock are always the current exchange's. A stale connection is never replaced mid-exchange; exhaustion is transport_unsent with observed{0}. The exchange record gains an optional connection; the binding gains connection_pool, not written when disabled.
  • 4, rustev.run/2 (3.2, I-4). rustev-contract: RUN_V2, RunRecord::remote_evidence and remote_evidence_truncated (absent in every other version, so version 1 and 3 bytes are unchanged), bounded RemoteEvidence, check_version_members, project_v1. rustev-core: EvidenceSink::run_schema and DecisionBackend::take_remote_evidence, both defaulted. rustev-runtime: version 2 exactly when the sink selects it; one entry per remote attempt in order; a rejected version 2 record is never retried as version 1. rustev-remote-http: ClientConfig::run_evidence, ExchangeSink::deliver_located, and Exchanges::deliver now returns the record digest and delivery result. rustev-eval: bundles hold the version 1 projection, so replay is unchanged and offline; remote_evidence::availability checks references against a host store, apart from judgment parity.
  • 5, runtime-planned remote batches (3.3). RemoteClient offers spec 017's batch_capability only when ClientConfig::batch_dispatch and the negotiated terms both allow shared-state batching (bound is the lesser). infer_batch refuses an oversized or mixed batch before any byte, checks each member as an independent attempt, sends one exchange in the runtime's order bounded by the earliest member budget, and answers each member from its own answer. New exchange attribution runtime_planned.
  • 6, Jev, drift, verification. A negotiated endpoint answering another protocol version is identity_mismatch. rustev-jev/tests/refinements.rs: Jev offers no general batch seam, its adapter-scoped batch stays shared-state, and no spec 020 member or remote evidence appears; its binding and mapping are unchanged. Spec 020: acceptance mapped item by item and a declared verify:cli block.

Amended specs whose shared APIs change: 003 (runtime run/2 delivery), 004 (eval bundles and availability), 009 (binding members, exchange record, TransportError, Exchanges::deliver), 012 (Jev), 017 (the batch seam's remote side). Their verify passes.

Interpretations recorded in the implementation record

  • 3.1's explicit disabled values are explicit in the configuration types but not written into the binding document, so every existing adapter's artifact and PlanId stay byte-identical (section 2).
  • The request-write phase ends at the first completed flush after the connection took the request body; the response-body phase includes the response head.
  • The cancellation acknowledgement ceiling bounds the whole cancel exchange, whose own transport phases also apply.
  • rustev.remote/2 keeps the HTTP paths /rustev/remote/1/... and the schema strings; the version member distinguishes it. A version 1 server refuses a version 2 describe with 400, reported at construction as a negotiation failure.
  • The isolation key's authority is the configured scheme, host and port, not the resolved address.
  • Replay never consults an exchange store; "without a transport or store call" is read as that, and availability is a separate, explicit check.
  • A plan 3 decision's record stays rustev.run/3 without remote evidence even for a sink that selected version 2.
  • Spec 017's batch report has one cancellation answer and one remote state, so one possibly continuing member makes every member of its batch possibly continuing with charge unknown: never understated, possibly overstated until the host reconciles.
  • A host-operated server hands a version 2 request's reference to the hosted backend as CallContext::principal_handle; version 1 keeps spec 009's empty handle.

Local verification (macOS arm64)

Rebased onto main at df053f6 (4cecab0 dropped as already applied as #146), then onto 2d6a1f2 after #143 and #144 merged, then onto c58c52e after #150 (spec 026) merged; no conflicts and no call sites to fix. .bin/spec-spine verify 026 also passes. make gate, make code (build, test, clippy -D warnings, fmt, boundaries), .bin/spec-spine verify for 020, 003, 004, 009, 012 and 017 (spec-spine 0.31.0), bash scripts/check-authored-content.sh.

Review round 1 (1 finding, reported by two groups, fixed): the RustevRun1 and RustevRun3 declarations (both packages) carried remote_evidence and remote_evidence_truncated, which spec 020 says are rustev.run/2 only. The declarations were faithful to the schemas, and the schemas to the parser: the run record's parser read every version with one type and did not refuse those members outside version 2. Fixed at the source: versioned_document! takes an optional check = f rule, and the run record's parser applies check_version_members (refusing either member in version 1 or 3, and a version 2 record without the list or beyond its bounds, as ParseError::Schema). The run schemas now state that rule: rustev.run-1 and rustev.run-3 drop both members and their now-unreferenced $defs (byte-identical to main again), and rustev.run-2 requires a non-null list. Declarations regenerated with gen-types.mjs. crates/rustev-contract/tests/run_v2.rs (the_parser_and_the_schemas_hold_the_version_rule) checks parser and schemas agree for each case; the implementation record says so.

Review round 2 (1 finding, fixed): an attempt that passed prepare (which records its evidence as pending) and was then withdrawn from a coalescing exchange before it sent kept pending: finish completes only the members in the exchange record, and note_unexchanged leaves an existing entry alone. Both "stopped before sending" paths of cancel_member (withdrawn while collecting, and a lone member that stops the send) now go through stopped_unsent, which turns a still-pending entry into no_exchange with code cancelled and charge provenance nothing_sent. tests/batching.rs (a_member_withdrawn_before_sending_has_no_exchange_in_its_evidence) fails without the fix and passes with it; the implementation record says so. Round 2's review job reached its 15-minute limit right after posting its comment, so that run recorded no evidence artifact; this push runs a fresh review.

Review round 3 (0 findings), after the rebase onto #150. The first attempt of this round reached the review job's 15-minute limit without a verdict; the rerun returned no findings in both groups.

@github-actions

Copy link
Copy Markdown

AI review (findings)

Group 1 of 3

Reviewing the diff for group 1 (schema files and rustev-contract/src/{lib,remote,run,schema_emit}.rs, tests/documents.rs).

Schema files: The new/updated schemas carry the descriptive $comment that the parser is the authority. The rustev.run-2 schema correctly changes "const":"rustev.run/2" while the rustev.run-1 and rustev.run-3 schemas properly absorb the new $defs (additive only). The optional remote_evidence/remote_evidence_truncated fields are absent from the required array, consistent with the Rust serde attributes.

remote.rs:

  • WirePrincipal::Debug redacts the reference field, and the test confirms format!("{p:?}") contains no reference bytes.
  • reference_bytes() accepts only lowercase hex; encode() always emits lowercase via format!("{b:02x}") — consistent.
  • Length checks: r.len() > MAX_PRINCIPAL_BYTES * 2 correctly bounds the original bytes at MAX_PRINCIPAL_BYTES (128). Boundary test at [1; 128] and [1; 129] confirms this.
  • evidence() uses length-prefixed encoding over [mapping_version, scope, reference_hex] before tagged_digest, preventing collisions across fields.
  • bounded() for ExchangeRecord cuts principal.digest to MAX_TEXT_BYTES via cut_flag and principal.mapping_version to MAX_PRINCIPAL_LABEL_BYTES — matching is_bounded()'s checks.
  • Attribution::RuntimePlanned addition is additive and backward-compatible.

run.rs:

  • check_version_members() match arms are logically correct: arm 3 (_ if truncated && !v2) is only reachable when (None && !v2) or (Some && v2), and the !v2 guard filters to the None && !v2 && truncated case only.
  • project_v1() calls check_version_members() before projecting — no partial projection possible.
  • RemoteEvidence::bounded() two-pass approach (cut to MAX_TEXT_BYTES, fall back to 32 if canonical bytes still exceed MAX_REMOTE_EVIDENCE_ENTRY_BYTES) is deterministic and correct.
  • ExchangeReference serde with rename_all = "snake_case" on an externally-tagged enum produces {"retained":{…}}/{"unavailable":{…}} matching the schema.
  • RemoteEvidence.code is always serialized (as null); batch and principal_digest are skipped when absent — minor asymmetry but consistent with the schema allowing all three as optional.

schema_emit.rs: emit::<RunRecord>(schema::RUN_V2, None) correctly adds the v2 schema emission.

tests/documents.rs: The added remote_evidence: None, remote_evidence_truncated: false fields are correct for a rustev.run/1 record; check_version_members() would accept this (None && !v2).

No concrete defects found.

{"head": "eb97ed4c284634786aa33f3e45854dec1fdea313", "verdict": "no-findings", "findings": []}

Group 2 of 3

Reviewing the changed files in this group for bugs, security problems, and inconsistencies.

integrations/rustev-node/types/rustev-documents.d.ts

The new RustevRun3.RustevRun3 interface (and the modified RustevRun1.RustevRun1) both include remote_evidence and remote_evidence_truncated fields whose JSDoc explicitly states:

"rustev.run/2 only (spec 020, 3.2) … Absent in every other version, so their bytes are unchanged."

Yet these fields appear inside the RustevRun3 interface with discriminant schema: "rustev.run/3". The runtime code confirms the exclusivity: run_2 = !plan_3 && i.sink.run_schema() == schema::RUN_V2 — plan-3 decisions produce rustev.run/3 records and are explicitly excluded from the run_2 path, so remote_evidence is always None/absent in run-3 records. Including the fields in the RustevRun3 TypeScript interface with comments that call them absent contradicts the stated invariant and will mislead type consumers. The same copy-paste error affects RustevRun1.RustevRun1.

No other concrete defects found in the remaining files of this group (seams, assemble, remote_evidence module, runtime lib, pool, phases, principal, server, wire, exchange, and the new test files all look internally consistent with the spec intent).

{"head": "eb97ed4c284634786aa33f3e45854dec1fdea313", "verdict": "findings", "findings": [{"path": "integrations/rustev-node/types/rustev-documents.d.ts", "line": null, "summary": "The RustevRun3.RustevRun3 interface (schema: \"rustev.run/3\") includes remote_evidence and remote_evidence_truncated fields whose JSDoc states they are \"rustev.run/2 only\" and \"Absent in every other version, so their bytes are unchanged\" — directly contradicting their presence in the run-3 interface; the same copy-paste error is present in RustevRun1.RustevRun1."}]}

Group 3 of 3

Review: group 3 of 3


integrations/rustev-wasm/types/rustev-documents.d.ts

Finding — remote_evidence and remote_evidence_truncated present in RustevRun1.RustevRun1 and RustevRun3.RustevRun3

The diff adds these two fields to RustevRun1.RustevRun1 (hunk @@ -8501,6 +8501,16 @@, ≈ line 8507 in the new file):

remote_evidence?: RemoteEvidence[] | null;
remote_evidence_truncated?: boolean;

The inline doc comment on both fields says "rustev.run/2 only… Absent in every other version, so their bytes are unchanged." The same two fields appear again in the newly-added RustevRun3.RustevRun3 interface (hunk @@ -9659,6 +9968,1182 @@, the RustevRun3 interface block within the new namespace).

The spec's own implementation record (increment 4) states: "remote_evidence (exactly in version 2) and remote_evidence_truncated (version 2 only, omitted when false), both absent in every other version", and the engineering-choices note reads: "A plan 3 decision's record stays rustev.run/3 without remote evidence even for a sink that selected version 2: this spec defines the list for version 2 only."

Including these fields (even as optional T | null) in the v1 and v3 TypeScript interfaces is incorrect: a consumer writing against these types can emit a version-1 or version-3 record carrying remote_evidence, which violates the wire-contract invariant the spec sets, and defeats the stated goal that existing golden outputs stay byte-identical. RustevRun2.RustevRun2 is the only interface that should carry these members.


specs/020-remote-protocol-refinements/spec.md and tools/rustev-release/archive-policy.json

No defects found. The archive-policy additions (three new rustev-remote-http source files plus rustev-eval/src/remote_evidence.rs) match what the implementation record prescribes for increments 1–4. The spec's extends additions and verification block are internally consistent, and the implementation: pending retention for the two owner-ruled acceptance items is the correct state per the contract lifecycle table.


{"head": "eb97ed4c284634786aa33f3e45854dec1fdea313", "verdict": "findings", "findings": [{"path": "integrations/rustev-wasm/types/rustev-documents.d.ts", "line": 8507, "summary": "remote_evidence and remote_evidence_truncated are added to RustevRun1.RustevRun1 and to the new RustevRun3.RustevRun3 interface, but the spec explicitly requires these fields to be absent in versions 1 and 3, contradicting the inline comment that calls them 'rustev.run/2 only… Absent in every other version'."}]}

Subject: df053f6...eb97ed4, diff digest a7458ccfd47c0c6794c87c8f9e409070450441f6559aacf009458fee0f1a4fa6, 3 call(s). An AI comment is not an approval.

@github-actions

Copy link
Copy Markdown

AI review (findings)

Group 1 of 2

Reviewing the diff for group 1.

Contract and schema changes look internally consistent. The versioned_document! macro extension is correct, run_members/prune_defs schema emission is sound, and WirePrincipal::evidence() uses proper length-prefixed domain separation. The backward-compatibility invariant (disabled refinements not written) is tested and enforced via skip_serializing_if.

Schema version enforcement in check_version_members / parsed_members_fit is correct: each match arm is reachable, remote_evidence_truncated without remote_evidence in a non-v2 record is caught, and the schema emitter adds the list to required only for v2.

phased() race handling is correct: changed.as_mut().enable() before reading the current phase prevents notification loss, and the biased select with a generation check on the sleep branch handles the change-then-sleep race.

Concrete bug – stale Pending evidence for a withdrawn coalesced attempt. The flow is:

  1. prepare() succeeds → inserts an EvidenceUnavailable::Pending entry into EvidenceStore (end of prepare).
  2. The attempt joins a coalescing exchange and its budget expires or its cancel signal fires while waiting.
  3. cancel_member() marks it Withdrawn; run_exchange() removes all Withdrawn members from st.members before sending.
  4. The exchange fires for other members and finish() runs, but it only iterates record.members – which is built from the non-withdrawn members – so the withdrawn attempt's entry is never updated.
  5. After attempt() returns, note_unexchanged() is called. It finds the Pending entry already in the store (store.map.contains_key(attempt_id) is true) and returns early without correcting it to NoExchange.
  6. The runtime's take_remote_evidence() returns a RemoteEvidence with exchange: Unavailable { reason: Pending }, i.e., "the exchange had not ended when the record was built" – which is wrong, because the withdrawn attempt never had any bytes sent on its behalf. The correct value is NoExchange ("nothing was exchanged: the attempt was refused before any request").

This makes rustev.run/2 records semantically incorrect for cancelled-mid-wait attempts in coalescing exchanges, violating the spec's "stated, never reconstructed" contract for EvidenceUnavailable.

{"head": "c0ae98091213a831f4c84b0a9e1be8204a922e86", "verdict": "findings", "findings": [{"path": "integrations/rustev-remote-http/src/client.rs", "line": null, "summary": "An attempt that passes `prepare()` (inserting a Pending entry in EvidenceStore) but is then withdrawn before the exchange fires gets stale EvidenceUnavailable::Pending evidence: `finish()` only iterates non-withdrawn members so it never updates the entry, and `note_unexchanged` returns early on finding the existing entry, leaving the run/2 record claiming the exchange was pending rather than never started (NoExchange)."}]}

Group 2 of 2

Looking at the changed files in group 2: the new pool.rs, principal.rs, server changes in server.rs, wire.rs changes, the test files, the WASM type declarations, the spec update, and the archive-policy update.

pool.rs (new file): The accounting logic in try_acquire is sound. When both per_origin and total bounds are simultaneously at their limits, the per-origin eviction reduces st.open by 1, making the total-bound check trivially false afterward, so double-eviction cannot occur. The Lease Drop correctly handles abandoned leases (meta taken by release, so Drop is a no-op after a proper release). The room.notify_waiters() is called after forget, ensuring freed slots are visible to waiters. The credential_identity function hashes credentials before inclusion in the key material. Key isolation correctly uses None digest for unknown/noncanonical material.

principal.rs (new file): Construction correctly refuses principal forwarding to third-party endpoints or over protocol v1. for_attempt maps a missing or oversized reference to Err(()), which the caller treats as a pre-send refusal. WirePrincipal's Debug impl intentionally redacts the reference (verified by test). The HandleAsReference impl rejects empty handles.

server.rs: Version negotiation picks the maximum common version via filter + max, which is correct. The content_key function uses the principal's evidence digest (not the raw reference) as the idempotency key component — different principals under the same attempt ID produce different content keys, triggering attempt_id_conflict. The version-check paths for describe, infer, and cancel are consistently updated to use state.config.versions.contains(...) rather than hardcoded PROTOCOL_MAJOR.

wire.rs: hooks_of acquires the Mutex and clones the Arc-backed SentTracker and PhaseClock handles on every poll. Cloning an Arc-backed tracker is cheap and the atomic operations through the clone are correct. The pool enforces max_streams = 1, so only one exchange uses a connection at a time; hooks are swapped between exchanges, never during one, ruling out the tracker-swap race.

Test files: Coverage is comprehensive — phases, pool evictions, principal isolation, run-evidence references, and batch differentials all tested. The tests/principal.rs case that a returned principal member in a response fails the answer closed, and that authorization extras don't change the record principal, correctly tests the "proposals, never grants" principle.

Spec update: The implementation frontmatter stays pending (as stated in the body text), consistent with the lifecycle table (approved + pending = work order). The new extends entries claim ownership over tools/rustev-release/, integrations/rustev-node/, and integrations/rustev-wasm/ with additive nature, which matches the code changes (new archive entries, regenerated declarations). No claims of completion for unresolved acceptance items.

archive-policy.json: Adds src/remote_evidence.rs, src/phases.rs, src/pool.rs, and src/principal.rs — the new source files introduced in this PR — consistent with the requirement that new source files of release members join the archive list.

No concrete defects found.

{"head": "c0ae98091213a831f4c84b0a9e1be8204a922e86", "verdict": "no-findings", "findings": []}

Subject: 2d6a1f2...c0ae980, diff digest ac86260f73a8bb898a8e56604e134cca8c63278f078877e4b8a64a5a8d4a62d0, 2 call(s). An AI comment is not an approval.

@bartekus
bartekus temporarily deployed to statecraft-review-exception October 21, 2026 20:14 — with GitHub Actions Inactive
Spec 020, increment 1 of 6: phase-specific time ceilings (3.4) and the
binding's phase member (3.1). Plan in the spec's new implementation record.

- `rustev-remote-http/src/phases.rs` (new): `PhasePolicy` (a positive
  ceiling per phase, zero refused at construction), `TransportPhases`
  (disabled by default), `PhaseClock` (each phase's allowance is the lesser
  of its ceiling and the budget left when it starts; phases only move
  forward) and `phased`, which ends an exchange whose phase ran out.
- `http.rs`: `HttpTransport::with_phases` enters resolution, connect, TLS
  handshake, request write, first response byte and response body on the
  real connection; `TransportError::PhaseExpired`. `wire.rs`: `TrackedIo`
  reports completed flushes and response bytes to the clock.
- `client.rs`: `ClientConfig::phases`; an expiry maps to
  `transport_unsent` before request bytes and `transport_interrupted`
  after; the cancellation acknowledgement ceiling cuts every cancel
  exchange's budget; no retry is added.
- `rustev-contract`: `rustev.remote-exchange/1` gains an optional
  `phase_expiry`, omitted when absent (existing records keep their bytes);
  schemas and the generated declarations regenerated.
- `AdapterBinding::transport_phases`, not written when disabled, so every
  existing binding keeps its bytes and artifact; enabled changes it.
- Jev compiles the new module and maps the new error; its policy stays
  disabled.
- Tests: `tests/phases.rs` (deterministic fake transport on a paused
  clock for every phase boundary, exact exhaustion, slow chunks and
  cancellation races; loopback first-byte and body expiry and the
  acknowledgement ceiling), contract and binding byte pins.
- `src/phases.rs` joins the reviewed archive list.
…tev.remote/2

Spec 020, increment 2 of 6: the principal reference (3.6) and exact
version negotiation (2, 3.7).

- `rustev-contract`: `rustev.remote/2` (`PROTOCOL_V2`, `protocol_name`);
  `InferRequest::principal` (`WirePrincipal`: lowercase hex of at most 128
  bytes, mapping version, scope), omitted when absent so version 1 bytes
  are unchanged, refused in a version 1 request or when not canonical;
  `WirePrincipal::evidence`, a domain-separated digest with the mapping
  version; the exchange record's optional `principal` holds only that.
  Schemas and generated declarations regenerated.
- `rustev-remote-http/src/principal.rs` (new): `EndpointOperator` (third
  party by default), `PrincipalSource`, `HandleAsReference`,
  `PrincipalPosture` (omitted by default), `PrincipalWire`.
- Client: negotiates exactly `protocol_major` (1 by default); refuses at
  construction a principal for a third-party endpoint, over version 1, or
  with a bad label; refuses an attempt before any byte when the reference
  is missing or oversized; sends it only in the request field; record and
  retained bytes carry its digest instead. The binding's `principal_wire`
  is not written when omitted; rotation keeps the binding.
- Server: `ServerConfig::versions` (`[1]` by default); refuses a principal
  in version 1; idempotency content includes the principal; the hosted
  backend receives the reference as its opaque handle.
- Jev compiles the new module; no Jev behavior changes.
- Tests: `tests/principal.rs` (omission, host-only construction, exact
  negotiation, redaction, rotation, bounds, conflict, no authority from a
  returned claim, no redirect), unit tests.
Spec 020, increment 3 of 6: bounded connection reuse (3.5).

- `rustev-remote-http/src/pool.rs` (new): `PoolPolicy` (every bound of
  3.5, positive and consistent; one stream per connection on HTTP/1.1;
  refuse or queue on exhaustion), `ConnectionPool` (host-owned, shareable
  by clients), `KeyMaterial` (every isolation member; credential and
  principal only as digests; unknown material never reuses), sweeps and
  evictions with reasons.
- `http.rs`: `HttpConn`, `HttpPool`, `with_pool`, `post_observed`: an
  exchange on a pooled connection whose stream hooks (tracker, phase
  clock) are swapped per exchange; reuse skips resolution, connect and
  handshake without carrying their ceilings; a stale connection fails as
  its bytes say and is never replaced mid-exchange. `wire.rs`: `IoHooks`.
- Client: `ClientConfig::pool` and `tls_label`; the binding gains
  `connection_pool`, not written when disabled; exhaustion is
  `transport_unsent` with `observed{0}`.
- `rustev-contract`: the exchange record's optional `connection`
  (fresh or reused, instance id, age bucket, use count, multiplex posture,
  key digest, eviction reason). Schemas and declarations regenerated.
- Jev compiles the new module; its transport keeps no pool.
- Tests: pool unit tests on a paused clock; `tests/pool.rs` over loopback
  behind a counting TCP front (reuse, use bound, credential, privacy,
  endpoint-class and principal isolation, stale connections, exhaustion).
…lability

Spec 020, increment 4 of 6: `rustev.run/2` (3.2, I-4).

- `rustev-contract`: `RUN_V2`; `RunRecord::remote_evidence` (exactly in
  version 2) and `remote_evidence_truncated`, absent in every other
  version so version 1 and 3 bytes are unchanged; `RemoteEvidence`
  (exchange digest, schema, retention and opaque locator, or an explicit
  unavailable reason; identities, binding, protocol, endpoint class, code,
  final remote state, charge provenance, batch membership, principal
  digest), bounded per string, per entry and per list;
  `check_version_members`; `project_v1`, exact and never partial. Schemas
  (new `rustev.run-2`) and declarations regenerated.
- `rustev-core`: `EvidenceSink::run_schema` (version 1 by default) and
  `DecisionBackend::take_remote_evidence` (none by default).
- `rustev-runtime`: a plan 2 record is version 2 exactly when the sink
  selected it; one entry per remote attempt in attempt order; entries
  leave from the end until the record fits its bounds; a rejected version
  2 record is never retried as version 1.
- `rustev-remote-http`: `ClientConfig::run_evidence` (binding member
  `run_record_schema`, not written when off); entries completed before
  members are answered; `no_exchange` for a refused attempt;
  `ExchangeSink::deliver_located`; `Exchanges::deliver` returns a note.
- `rustev-eval`: bundles hold the version 1 projection, so replay is
  unchanged and offline; `remote_evidence::availability` against a host
  store, apart from judgment parity.
- Tests: contract, runtime, eval and loopback suites for every case.
Spec 020, increment 5 of 6: the remote side of spec 017's general batch
seam (3.3).

- `RemoteClient` implements `batch_capability` only when
  `ClientConfig::batch_dispatch` (off by default; binding member
  `batch_dispatch_max_members`, not written when off) and the negotiated
  terms declare shared-state batching; the bound is the lesser of both.
  Compatibility is the binding plus the shared state.
- `infer_batch`: refuses an oversized batch or one mixing principals or
  decisions before any byte; checks each member as an independent attempt
  (removed and reported unsent when already cancelled or out of budget);
  one exchange in the runtime's order, bounded by the earliest member
  budget; each member answered from its own answer, never a sibling's.
  The report sums the members' charges and is possibly continuing when
  any member is.
- `attempt` split into `prepare` and `wait_member`, shared by both paths;
  a runtime batch keeps its order; exchange attribution
  `runtime_planned` (new); remote evidence names the runtime batch id.
- Tests: `tests/runtime_batch.rs` differential batched vs independent
  (values, a member failure, deadline and cancellation after send, cost),
  ineligible steps and disabled bindings, a missing member answer.
Spec 020, increment 6 of 6.

- A negotiated endpoint answering another protocol version is
  `identity_mismatch` (3.7), never an upgrade or downgrade; loopback test.
- `integrations/rustev-jev/tests/refinements.rs`: the Jev adapter offers
  no general batch seam, its default batch dispatch refuses without a
  call, its own adapter-scoped batch stays shared-state, and no spec 020
  member or remote evidence appears; no refinement is enabled on it, so
  its binding and mapping are unchanged.
- Spec 020: acceptance mapped item by item, a declared `verify:cli`
  block (`spec-spine verify 020` passes), and two acceptance items left
  for the owner's ruling (multiplex cancellation on an HTTP/1.1-only
  binding; Jev qualification evidence when nothing is enabled).
  `implementation` stays `pending` until then, so 020 does not join
  `make verify` yet.
Review round 1: the run/1 and run/3 schemas and declarations carried
remote_evidence. The parser now refuses either member outside
rustev.run/2 and requires the list in version 2, within its bounds; the
run/1 and run/3 schemas are byte-identical to main again and the run/2
schema requires a non-null list. Declarations regenerated.
…vidence

Review round 2: a member withdrawn from a coalescing exchange (or a lone
member that stopped the send) is in no exchange record, so its entry,
prepared as pending, stayed pending. Both stopped-before-sending paths
now mark it no_exchange, cancelled, nothing sent.
@bartekus
bartekus force-pushed the impl/020-remote-protocol-refinements branch from f46b317 to dcaee27 Compare October 21, 2026 20:42
@github-actions

Copy link
Copy Markdown

AI review (no-findings)

Group 1 of 2

I reviewed all files in group 1 for bugs, security problems, and inconsistencies. Here is my analysis of the key areas:

Schema and version enforcement (run.rs, document.rs, schema_emit.rs):
RunRecord::check_version_members / parsed_members_fit is wired correctly through the versioned_document! macro's new check = arm. The parser refuses a v2 record without remote_evidence, and refuses v1/v3 records that carry it. The schema emitter correctly adds remote_evidence to required for v2 and prunes unreachable $defs entries for v1/v3. The prune_defs BFS correctly handles transitive $ref chains and cycles via the reached set.

Principal reference confidentiality (remote.rs, client.rs):
WirePrincipal::Debug redacts the reference; evidence() hashes the wire form with a domain tag so no log, record, or retained byte carries the raw reference. The retained-request substitution in run_exchange replaces the reference with its evidence digest before storage. All correct.

Phase clock (phases.rs):
phased() correctly races fut, change-notification, and a per-phase timer. enable() before clock.current() prevents missing a notification; the generation check prevents stale expiry after a concurrent phase transition. Phases only advance forward, and the validate gate rejects zero ceilings. No infinite-loop risk: 7 phases are finite and each fires at most once.

Evidence store (client.rs):
EvidenceStore::put / take keep map and order in sync. stopped_unsent is only called after dropping the exchange-state lock, avoiding deadlock. Evidence is fully updated before reports are sent through channels. note_unexchanged correctly skips entries already populated, including those updated by finish() or stopped_unsent.

fit_remote_evidence (runtime/lib.rs):
Pops from the end until the record fits. An empty list terminates the loop even if theoretically large (impossible in practice since the base record fits). No unbounded loop.

Backward compatibility (identity.rs):
All new AdapterBinding fields are skip_serializing_if their disabled/absent default, so existing binding artifacts are unchanged.

assemble.rs:
project_v1() is called only for schema == RUN_V2, the result stored in a pre-declared projected binding, borrowed for the rest of the function. Lifetime is correct.

remote_evidence.rs (eval):
catch_unwind(AssertUnwindSafe(...)) on store lookups is appropriate here. The double check (record_digest + record_canonical == bytes) is a strong idempotency requirement. Correct.

After full review I found no concrete defects.

{"head": "dcaee273ff481112e36d03587ee69b0f761470e7", "verdict": "no-findings", "findings": []}

Group 2 of 2

Reviewing the assigned files for bugs, security issues, and inconsistencies.

pool.rs

  • Pool counting invariant: open always equals sum of per_origin values. Tracing through try_acquire: the per-origin eviction decrements both open and per_origin[origin], the global eviction decrements open and the evicted connection's per-origin entry, then the single open += 1 and per-origin increment restore the balance. No double-count.
  • release: the evicted-idle path calls forget (decrementing open) and then pushes the returning connection without incrementing open (it was already counted as checked-out). Net: open goes from k to k-1, which is correct—one eviction, one return.
  • Lease::drop takes meta out; release also takes meta out first, making the Drop impl a no-op. No double-free of the pool slot.
  • credential_identity returns "none" for None (no credential). Tagged digests have the form sha256:…, which cannot equal "none". No collision risk.
  • queue exhaustion: Notify::notified() + enable() before the select! correctly catches notifications that arrive between the failed try_acquire and entering the wait. No wakeup can be missed.
  • Instant::now() in observation is tokio::time::Instant, so paused-clock tests work correctly.

principal.rs

  • PrincipalPosture::Sent Debug impl uses finish_non_exhaustive(), omitting the source field. Test confirms the reference bytes are not printed.
  • HandleAsReference returns None for an empty handle, causing refusal before send. Correct.
  • validate blocks a third-party endpoint and enforces protocol_major == PROTOCOL_V2 before any reference is sent. Correct.

server.rs

  • Version negotiation in describe picks the max common version via filter + max. A v1-only server with a v2-only client correctly returns 400.
  • members_fit_version() is checked before version validation; both checks happen before any backend call, so order has no security consequence.
  • content_key includes principal_digest (length-prefixed). unwrap_or_default() maps no-principal to "", which length-prefixes to an 8-byte zero length prefix, structurally distinct from any real digest. Idempotency with a different principal under the same attempt id correctly produces a conflict.
  • principal_handle passed to the hosted backend is extracted from the already-validated WirePrincipal; if decoding returns None unexpectedly, the empty-default follows spec 009's empty-handle engineering choice.
  • Cancel and infer responses echo req.version, not the constant. Correct.

wire.rs

  • hooks_of clones IoHooks under lock on each I/O call. SentTracker and PhaseClock are Arc-backed, so cloning shares state. Correct.
  • Swap-per-exchange: HTTP/1.1 carries one request at a time, so hooks are only swapped between exchanges, never during a write. No mid-write confusion.

Tests

  • phases.rs: paused clock, current_thread flavor—deterministic. biased select correctly prioritizes the signal over the phase expiry.
  • pool.rs: counting TCP front accurately distinguishes reuse. The drop_next test verifies no transparent reconnect on mid-request failure.
  • principal.rs: redirect test verifies elsewhere.hits == 0. Authorization-in-response test verifies the evidence digest matches the sent reference, not the returned value. Both cover the no-laundering requirement.
  • run_evidence.rs: hex-encoding check (SYNTHETIC-tenant and its hex form absent from the record) is thorough.

spec.md

  • implementation: pending with "all six increments delivered" is a coherent, documented state per the contract table (approved + pending = work order).
  • The three new extends entries (031, 027×2) with additive nature correctly justify changes to archive-policy.json and the TypeScript declarations.

archive-policy.json / rustev-documents.d.ts

  • New entries match the new source files. TypeScript union extensions are additive and backward-compatible. remote_evidence is required in RustevRun2, matching the spec's "the schema requires the list."

No concrete defects found.

{"head": "dcaee273ff481112e36d03587ee69b0f761470e7", "verdict": "no-findings", "findings": []}

Subject: c58c52e...dcaee27, diff digest be7682adb44e6156b4362d5fe6b790e01dee863edb58a1f60809bab5a9f08489, 2 call(s). An AI comment is not an approval.

@bartekus
bartekus merged commit 0d67a8f into main Oct 21, 2026
12 of 14 checks passed
@bartekus
bartekus deleted the impl/020-remote-protocol-refinements branch October 21, 2026 21:23
bartekus added a commit that referenced this pull request Oct 21, 2026
Spec 019, increments 1 and 2: dynamic questions as a narrow evaluated
class. The documents, pure validation and identity, `ask_dynamic`,
offline reproduction and the dynamic evaluation report. Scripted
backends only; nothing here selects a backend, authorizes live inference
or spend, or claims accuracy or calibration.

- `crates/rustev-contract/` (`src/dynamic.rs`, `ids.rs`, `limits.rs`):
`rustev.dynamic-question/1`, `rustev.dynamic-capability/1` (identified
by `DynamicCapabilityId`) and `rustev.dynamic-outcome/1` (`RECORD_V1`);
`DynamicRequestId`, `TemplateId`; the `DYNAMIC_QUESTION_V1` scan limits.
Parsing scans the bytes first, then checks the structural bounds of 3.2
(sizes, counts, byte-exact uniqueness of labels and context names, 64
KiB of context values, 128 KiB canonical); unknown members are refused.
The canonical request identity covers what a backend computes from,
including label order, template and preprocessing; the backend receives
a projection under fixed member names only.
- `crates/rustev-core/` (`src/dynamic.rs`, `seams.rs`): `validate`
builds the only `ValidatedQuestion`; `admit` (capability fit, no
truncation, `bounded` cost model only), `admit_cost` (enforceable bound
at or below the hard cap), `judge` (exact support, non-answer material
is invalid, pinned served identity, named abstention rules), `proposal`
(`model-derived`, with lineage). `DynamicBackend` and
`DynamicEvidenceSink` seams, separate from `DecisionBackend`, with no
tool, function or retrieval surface. Compile-fail tests with a compiling
control keep dynamic outcomes, raw outputs and proposals out of
`Supplied`, `Evaluation::supply` and `Judgment`, and keep
`ValidatedQuestion` unforgeable.
- `crates/rustev-runtime/` (`src/dynamic.rs`): `ask_dynamic`, one
attempt under a fresh hard ledger at the request's cap (and the optional
host ledger), deadline over every phase, spec 003/013 cancellation
evidence, optional sink whose delivery never changes the outcome. No
retry, fallback, batching or cache on this path.
- `crates/rustev-eval/` (`src/dynamic.rs`): `reproduce` takes no
backend; a changed canonical identity is `incomparable{request_changed}`
(section 5's last row: reordered labels), another declaration
`capability_changed`, a missing raw response `raw_response_unavailable`,
a different judgment `diverged`. `rustev.dynamic-dataset/1` and
`rustev.dynamic-evaluator-config/1` bind task family, exact question
schema, artifact and template; the dataset requires an
injection-adversarial case and refuses leakage across splits.
`rustev.dynamic-eval-report/1`: coverage, abstention by reason, accepted
error, uncalibrated Brier and log loss or mean level distance, overall
and over adversarial cases; `uncalibrated`, `mechanics_only` on
synthetic data, every gate `unknown`.
- Tests: `rustev-contract/tests/dynamic_wire.rs`,
`rustev-core/tests/dynamic.rs` (including adversarial text in every
caller-controlled field), `rustev-runtime/tests/dynamic.rs` (section 5
rows 1 to 7 with a dispatch counter), `rustev-eval/tests/dynamic.rs`.
- `tools/rustev-release/archive-policy.json`: the four new source files
join the reviewed archive lists; 019 now `extends`
`tools/rustev-release/` (additive) for it.
- `tools/rustev-conformance/fp-corpus` (spec 027, 3.11.3): the dynamic
log loss's `rustev_core::math::ln` call joins the differential corpus as
`eval.dynamic_log_loss.ln` (probability domain, as the existing log-loss
site), with its digests committed in `expected.json`; 019 `extends`
`tools/rustev-conformance/` (additive) and its verification runs the
corpus test.
- `Makefile`: 019 joins `VERIFIED_SPECS`.
- Spec 019: `implementation: complete`, Verification declares the
acceptance commands, implementation record. No existing document,
golden, plan id or test changed.

What remains: nothing in 019's acceptance. Calibration of a dynamic task
family needs a separately fitted artifact with its own binding; none
exists and none is claimed.

Owner decisions:
1. Whether the dynamic documents join spec 027's JSON Schema emitter
(3.2.2, "every public document type"). They are not emitted here: doing
so adds schema files under `crates/rustev-contract/schema/` and changes
the generated binding types under `integrations/rustev-wasm/types/` that
spec 027 owns, and neither spec says whether dynamic documents belong in
the binding surface.
2. Defaults chosen where the spec is silent, recorded in the
implementation record:
- `DISTRIBUTION_TOLERANCE` is 0.000001, equal to the reference plans'
tolerance.
- `min_margin` is top mass minus the second mass; ties go to the earlier
declared label.
- Free-text backend output retained in an outcome is cut to 256 bytes.
- Every evaluation gate is reported `unknown`: over synthetic data a
gate would claim quality from mechanics, and real data needs separately
governed admission (spec 023) that no dynamic dataset binds yet.

Local verification (macOS arm64): `make gate`, `make code` (build, test,
clippy `-D warnings`, fmt, boundaries), `.bin/spec-spine verify 019` (12
commands, passed), `rustev-fp-corpus check` (5 sites agree natively).
The WebAssembly corpus runs (`make bindings`) were not run locally: this
toolchain lacks the `wasm32-unknown-unknown` target. Rebased onto `main`
after #146, again after #143 to #145 merged (#145's corpus test required
the new site), and again after #150 (`VERIFIED_SPECS` and the contract's
schema constants unioned); derived shards regenerated each time.

Review round 1 (1 finding, fixed): `bounded_raw` kept NaN and infinite
distribution masses, so the outcome for that invalid output could not be
serialized and the evidence was lost. Such a distribution is now
recorded, and judged, as `Unrecognized { shape: non_finite_mass }` with
the masses as text (a new `ResponseShape` variant), so the outcome stays
a writable record and offline reproduction judges exactly what was
recorded.
`adapter_failures_and_malformed_outputs_are_named_and_never_retried` now
includes a NaN and an infinite distribution, asserts the recorded shape
and round-trips both outcomes. The implementation record says so.

Review round 1 (1 finding, fixed): `bounded_raw` kept NaN and infinite
distribution masses, so the outcome for that invalid output could not be
serialized and the evidence was lost. Such a distribution is now
recorded, and judged, as `Unrecognized { shape: non_finite_mass }` with
the masses as text (a new `ResponseShape` variant), so the outcome stays
a writable record and offline reproduction judges exactly what was
recorded.
`adapter_failures_and_malformed_outputs_are_named_and_never_retried` now
includes a NaN and an infinite distribution, asserts the recorded shape
and round-trips both outcomes. The implementation record says so.

Review round 2 (0 findings) on the rebased head 48c6c15.

Review round 3 (1 finding, fixed in the docs, behavior kept):
"`proposal()` omits `abstention` from `exact_processing` for label
answers, contradicting its doc comment and the implementation record."
The behavior is intended: under the explicit `label_only` posture no
abstention rule runs (`judge` returns `AbstentionDecision::LabelOnly`),
so listing `abstention` would claim an exact step that never ran. The
doc comment and the implementation record were wrong and now say
`validate` always, `abstention` only when thresholds were applied. The
core test for label output now builds the proposal and asserts its
lineage is exactly `["validate"]`.

Review round 4 (0 findings) on f9c4045. Rebased onto `main` after #152
(no conflicts, shards current).

Review round 5 (0 findings) on 54587eb; ci-gate passed.
bartekus added a commit that referenced this pull request Oct 21, 2026
…153)

Registers the two remaining required CI jobs: spec 027's `bindings`
(3.12.5) and spec 031's `release-checks` (3.5, 3.6.7, 3.8, 3.12).

- `.github/workflows/bindings.yml` (owned by spec 027): `make bindings`
on the reference runner (`ubuntu-24.04` x64, Node 22), the native suite
under Node 20 and 24, and the seven-platform native matrix. On each
platform the matrix builds the addon, runs the differential corpus, and
installs both packages from their tarballs into a fresh project.
- `.github/workflows/release-checks.yml` (owned by spec 031):
`adoption`, one job per partial-adoption subset (the five subsets whose
crate is absent are reported as skipped, never passed); `msrv` at the
toolchain the members' `rust-version` declares; `semver` with the pinned
`cargo-semver-checks` 0.51.0, where `no-baseline` is recorded as not
applicable.
- Both are registered by adding them to `ci.extra_required_jobs` in
`project.setup.parameters` of `.statecraft/environment.json`, then
re-rendering with the revision-17 renderer (statecraft-cli commit
`2f366913240ab9c6a13e4da46d057b165574bd71`, profile identity
`fe0e763c8f21`): `init plan . --profile github-actions-rust` produced
plan `df5491a7507d9a49ad1df28ec2bfc1e69f63f0af47557c3f22076fc511009bcd`,
which `init apply` applied, reporting every rendered path at its
intended digest. The renderer changed only `statecraft-ci.yml` (the two
`uses:` jobs and `ci-gate`'s `needs`) and the two setup documents.
`specs/000-bootstrap/spec.md` and `standards/spec/constitution.md` were
withheld as owner-edited and are unchanged.
- Specs 027 and 031: implementation-record paragraphs (027 increment 7,
fourth change; 031 increment 4).

This PR changes the authority set, so it needs the owner's approval of
the `statecraft-review-exception` Environment once. Once the
seven-platform matrix passes, specs 046 and 027 can be marked complete
in a follow-up.

Local verification (macOS arm64): `make gate` passes with spec-spine
0.31.0. The new jobs themselves run only in CI.

Round 1 CI (win32-x64-msvc): all 34 conformance cases failed their
pinned fixture digests, because the Windows runner checks out with
`core.autocrlf=true`. The `native` job now disables it before checkout;
spec 027 records why.

Review round 2 (1 finding, fixed): the WebAssembly tools cache key did
not name the tool pins, and its `restore-keys` prefix could restore an
older cache whose tools then passed the `test -x` check. The key now
carries `wasm-bindgen-cli` 0.2.129 and `wasm-opt` 0.116.1, and each tool
is installed under a root named by its version, so a restored older
cache never supplies a stale tool. (Round 2 first failed on reviewer
infrastructure, "claude native binary not installed", and was rerun.)

Review round 3 (0 findings). Rebased onto `main` after #150, #152 and
#148 (no conflict; none touched a managed or workflow file); `make
gate`, `couple` and the authored-content check pass again.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant