Skip to content

impl(028): the sink, acknowledgement, loss, context and sampling - #159

Merged
bartekus merged 1 commit into
mainfrom
impl/028-c-sink
Oct 22, 2026
Merged

bartekus merged 1 commit into
mainfrom
impl/028-c-sink

Conversation

@bartekus

@bartekus bartekus commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

Part 3 of 4 of spec 028, split from the single PR #151 because its AI review timed out at 15 minutes three times. Merge in order: #151 (increments 1 and 2), #158 (increment 3), #159 (increment 4), #160 (increments 5 to 7). Each part is one signed commit; later parts are stacked on the branch below and are rebased onto main after each merge.

  • Increment 4, the sink (3.6 to 3.9.4): OtelSink and TeeSink; synchronous projection and redaction, metrics never sampled, sampling, whole-tree queueing, otel:accepted: / otel:exported: / otel:sampled_out: receipts; a worker exporting each batch as its own task under the timeout so failures, hangs and panics are counted; conservation per signal; W3C trace context, plan registration and the exchange join buffer. Tested through the runtime under every spec 003 sink policy, including the equivalence of 3.8.6.

Owner decisions:

  • SDK workarounds: metrics go through an SDK meter provider with a periodic reader (interval one year) driven by flush_metrics, because ResourceMetrics can only be filled by an SDK reader and the manual reader's collect needs experimental_metrics_custom_reader, which 3.2.3 does not enable; the SDK's final export on drop is skipped so metrics leave only through flush_metrics, where they are counted. Log records are exported with LogBatch::new, which the SDK documents as public but not meant for direct use, so an SDK upgrade may need to revisit it.

Local verification on this head: make gate and spec-spine couple pass; bash scripts/check-authored-content.sh passes. The combined tree of all four parts is identical to the squashed #151 head 5c44374, whose CI run passed every job except the timed-out AI review (code, verify, boundaries, bindings, release-checks).

Review responses (round on 43ceaa9):

  • logs_of no longer indexes p.lines[0] or p.lines[a.line]: it returns no records without a root line and skips an attempt whose line is out of range.
  • AttrSet::with now checks the dimension class (enum, plan metadata, model identity) at run time in every build instead of a debug_assert!; a unit test grants allow to every grantable class and shows only the enum field becomes an attribute.

Size: about 3,100 added lines, over the 2,000-line guideline, all authored: src/sink.rs is one 1,256-line module (the sink, its queue and its export worker) and tests/sink.rs its 990 lines of tests; context.rs, config.rs and metrics.rs make up the rest. The only cut available would still leave a part of about 2,300 lines, and the AI review of this content has finished within its time limit on every run, so it stays one PR (coordinator decision).

Head 856d1d6 failed cargo fmt (the new metrics unit test); fixed by formatting only, no content change.

@github-actions

Copy link
Copy Markdown

AI review (no-findings)

I reviewed all changed files. Here is my analysis:

config.rs — Validation is consistent with the ranges module. check_usize correctly avoids the Into<u64> bound that usize doesn't satisfy on all platforms. All defaults fall within the validated ranges. The schema check accepts only 1, consistent with the spec's claim that no version 2 yet exists.

context.rs — hex_bytes accepts only lowercase hex, which matches the W3C traceparent specification (the test confirms uppercase is rejected). The version-00 extra-field check is correct. JoinBuffer remembers max.max(EXPORTED_MEMORY) = at least 4 096 attempt ids in the exported set, matching the spec claim. ContextTable::insert allows re-registration of an existing key without counting against the cap, which is intentional.

sink.rs — Lock ordering: deliver_record holds queue then stats simultaneously; the worker takes stats alone, then queue alone (never simultaneously). No deadlock is possible. The notified future is created before each queue check in both the worker loop and shutdown's wait loop, so no notification can be missed. The enqueued atomic with SeqCst ordering correctly lets TeeSink know whether the item entered the queue before a timeout, ensuring a decision is never counted under two loss reasons. The sampled_out path returns before queuing, maintaining the conservation invariant (accepted = exported + lost + in_flight). The ratio sampler uses u128 intermediate arithmetic to avoid overflow and matches the spec formula exactly.

metrics.rs — AttrSet::with only adds a dimension when the policy action is Allow, correctly excluding digest/truncated values from metric dimensions. Histogram bucket indexing is safe (BOUNDARIES.len() is a valid index into the len+1 bucket vec).

sink.rs / worker — After an export finishes, exporting = false is set before idle.notify_waiters(), so shutdown's guard condition is checked correctly. The worker drains the queue fully before exiting on closed.

Spec update vs implementation — All eight validated ranges match between config.rs constants and the spec text. The JSONL exporter refusing logs: on at construction, schema 1 only, and the ratio rule description all agree with the code.

No concrete defects are supported by the evidence.

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

Subject: 5fa408a...dacad91, diff digest c238cf5cbc777957000875a156bf00de12c04b581617beed487e9fb65532bf42, 1 call(s). An AI comment is not an approval.

@github-actions

Copy link
Copy Markdown

AI review (findings)

Reading the diff carefully for bugs, security problems, and inconsistencies.

config.rs — validation logic and range constants are consistent with each other and with the spec text additions. Default values fall within stated ranges. The dual check / check_usize helpers exist because usize does not implement Into<u64> on 32-bit targets; this is correct.

context.rs — hex_bytes accepts only lowercase ASCII hex, rejecting uppercase. The W3C traceparent spec requires lowercase, and the test explicitly asserts uppercase is refused. Correct. ContextTable::expire and JoinBuffer::expire use saturating_sub consistently. JoinBuffer::take maintains exported / exported_set in sync: an id is pushed to the deque only on first insertion, and removal from deque always removes from the set.

metrics.rs — Histogram allocates BOUNDARIES.len() + 1 buckets (16), and record indexes 0..=15 (0..14 from position, 15 from unwrap_or). Correct.

sink.rs

ratio_sampled — implements OTel's integer-form rule: rnd = last_8_bytes >> 1, bound = per_million * 2^63 / 10^6. At per_million = 1_000_000, bound = 2^63, rnd ≤ 2^63 – 1, so always sampled. At 0, bound = 0, never sampled. Correct.

Liveness bug in shutdown: idle.notified() returns a future but does not register the task as a waiter until the future is first polled. notify_waiters() notifies only currently-registered waiters and, unlike notify_one(), does not store a permit for future polls. The following race is reachable on a multi-threaded runtime:

  1. Worker finishes its last export batch, sets q.exporting = false.
  2. shutdown creates let notified = s.idle.notified() (not yet polled, not registered).
  3. Worker calls s.idle.notify_waiters() — no registered waiters, notification is lost.
  4. Worker calls next_batch → Next::Exit, calls s.idle.notify_waiters() again — lost.
  5. Worker task exits.
  6. shutdown checks condition: q.items.is_empty() && !q.exporting evaluates false because it was true in step 1 but the check is evaluated after creating the notified future (i.e., the condition check happens between steps 2 and 6 — but only if step 1 completes before the check).

Actually, the race materialises when the condition check at step 6 evaluates true before notified.await is reached (which would return immediately) but the condition was false at the check — that is, when exporting transitions false between the creation of notified (step 2) and the condition check. Then:

  • condition check (step 6) sees exporting = true → does not return
  • drops the lock
  • worker sets exporting = false and calls notify_waiters (lost)
  • worker exits
  • notified.await blocks forever; no one will call notify_waiters again

The fix is to call notified.enable() immediately after creating the future and before the condition check, which registers the waiter before any concurrent notify_waiters can fire. Tokio's documentation describes this pattern explicitly as the motivation for enable().

The consequence is not correctness of the final stat counters — the drained queue is empty at that point — but shutdown blocks for the full timeout_ms rather than returning early.

Conservation accounting — accepted = exported + lost + in_flight is correctly maintained across all paths (deliver, queue-full, worker success/failure/panic/timeout, shutdown drain). TeeSink avoids double-counting via the enqueued atomic, which is stored while holding the queue lock (a synchronous section with no .await points), so the Tokio executor cannot preempt between the store and the return.

logs_of — indexes p.lines[0] unconditionally. No evidence in the diff that project can return zero lines, so not reported.

Spec additions — range constants in prose match ranges::* exactly. Acknowledgement-mode descriptions, conservation invariant, metric-attribute restrictions, and sampling rule are accurate to the implementation.

{"head": "43ceaa9db02718336074fc8dbafea4c308b78567", "verdict": "findings", "findings": [{"path": "integrations/rustev-otel/src/sink.rs", "line": null, "summary": "In `OtelSink::shutdown`, `idle.notified()` is created before the queue condition check without calling `enable()`, so if the worker finishes and calls `idle.notify_waiters()` in the window between future creation and `notified.await`, the notification is lost (notify_waiters does not store a permit) and shutdown blocks for the full timeout even though the queue is already drained."}]}

Subject: b571dc5...43ceaa9, diff digest dcb1c36b665ee28ee14a151f6fd6ec6a6aac8c47effd97479942dfca9e819948, 1 call(s). An AI comment is not an approval.

@bartekus
bartekus had a problem deploying to statecraft-review-exception October 22, 2026 01:35 — with GitHub Actions Error
@github-actions

Copy link
Copy Markdown

AI review (findings)

Reviewing the diff for bugs, security issues, and inconsistencies in the new OtelSink implementation (spec 028, increment 4).

Config and range validation (config.rs): All stated ranges match the spec text in the diff. The check/check_usize split is sound; u32 as u64 and usize as u64 are widening casts.

Traceparent parsing (context.rs): Correctly rejects version 0xff, all-zero trace/parent ids, uppercase hex, and extra fields on version 00. Tests are thorough.

JoinBuffer: The pointer-identity distinct-count in distinct() and expire() correctly counts ExchangeRecords (not attempt slots). EXPORTED_MEMORY lower bound on the eviction ring is wired correctly.

Conservation invariant: accepted = exported + lost + in_flight per signal is maintained. The simultaneous hold of queue and stats in deliver_record creates a lock-ordering that differs from the worker (which acquires each separately), but no path currently acquires stats while waiting for queue, so no deadlock today.

ratio_sampled: The integer-form OTel rule is correct; the test vectors are consistent with the spec formula.

AttrSet::with: The guard that only Enum | PlanMetadata | ModelIdentity field classes reach metric dimensions is a debug_assert!, invisible in release builds. A caller that passes FieldClass::Id or FieldClass::FreeText would bypass it; the policy's Action::Allow check provides a second layer, but the assertion is the stated first guard.

logs_of (sink.rs): Two unchecked index accesses constitute latent panics:

  1. let root = &p.lines[0]; — if project() ever returns a Projected with an empty lines vector (e.g., for an edge-case record schema), this panics with no local guard.
  2. let l = &p.lines[a.line]; — a.line is a raw usize index originating in project(). If any Facts::attempts entry carries an index ≥ p.lines.len(), this panics. Neither bound is checked locally.

Both are in production code called for every sampled delivery when logs: true.

{"head": "43ceaa9db02718336074fc8dbafea4c308b78567", "verdict": "findings", "findings": [{"path": "integrations/rustev-otel/src/sink.rs", "line": null, "summary": "logs_of indexes p.lines[0] and p.lines[a.line] without bounds checks; either panics if project() returns an empty lines vector or an out-of-range attempt line index."}, {"path": "integrations/rustev-otel/src/metrics.rs", "line": null, "summary": "AttrSet::with enforces the Enum|PlanMetadata|ModelIdentity field-class restriction only with debug_assert!, which is a no-op in release builds, leaving the guard ineffective in production."}]}

Subject: b571dc5...43ceaa9, diff digest dcb1c36b665ee28ee14a151f6fd6ec6a6aac8c47effd97479942dfca9e819948, 1 call(s). An AI comment is not an approval.

@bartekus
bartekus had a problem deploying to statecraft-review-exception October 22, 2026 01:36 — with GitHub Actions Error
@github-actions

Copy link
Copy Markdown

AI review (no-findings)

I reviewed all changed files for bugs, security issues, and spec inconsistencies. Here is what I examined:

config.rs — Range checks are correct and exhaustive; check/check_usize split is necessary because usize lacks Into<u64> unconditionally. validate() covers all ranges named in the spec text. No issues.

context.rs — parse_traceparent correctly enforces lowercase-only hex (the W3C spec mandates lowercase; the test cases confirm this is intentional). The zero trace-id and zero parent-id rejections match the spec. JoinBuffer::distinct() is O(n) and called from insert(), but the buffer is bounded to 65,536, so this is not a security or correctness issue. The expire logic uses saturating_sub correctly.

sink.rs — I traced lock ordering throughout. The only place two mutexes are held simultaneously is deliver_record, which takes queue then stats. The worker takes stats (releases), then separately queue — no cycle. I verified the conservation invariant (accepted == exported + lost + in_flight) holds through every code path: enqueue, export success, export failure, queue-full, shutdown drain, and post-shutdown delivery. The ratio_sampled function implements rnd < per_million × 2⁶³ / 10⁶ correctly in u128 arithmetic; the edge cases per_million=0 (always false) and per_million=1_000_000 (always true, since max rnd is 2⁶³−1 < 2⁶³) are correct. The TeeSink enqueued flag correctly distinguishes "timed out before enqueue" from "timed out after enqueue" — in the latter case the worker will count the item under its own reason, so tee_failed is not double-counted. Cancellation safety holds because the queue lock is a synchronous std::sync::Mutex (no .await inside the lock).

metrics.rs — AttrSet::with correctly gates on both the policy action and the field class (Enum | PlanMetadata | ModelIdentity); the guard is compile-time unconditional so no policy override can make an ID or text field a dimension.

spec.md increment — The spec text matches the implementation: receipt prefixes, conservation invariants (I-2), the ratio formula, the EXPORTED_MEMORY = 4096 lower bound, and the decision.duration having no attributes are all consistent with the code.

Cargo changes — rustev-runtime and tokio are added to integrations/rustev-otel, which is within integrations/*, satisfying the boundary rule.

No concrete defects found.

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

Subject: b571dc5...9510bef, diff digest 02f05b499ad4545c655a9e503de4850025f072821bfd72fed5a68421a314ef6a, 1 call(s). An AI comment is not an approval.

bartekus added a commit that referenced this pull request Oct 22, 2026
…y and trace line (#151)

Part 1 of 4 of spec 028, split from the single PR #151 because its AI
review timed out at 15 minutes three times. Merge in order: #151
(increments 1 and 2), #158 (increment 3), #159 (increment 4), #160
(increments 5 to 7). Each part is one signed commit; later parts are
stacked on the branch below and are rebased onto `main` after each
merge.

- Increment 1, `tools/rustev-boundaries` (3.12): the telemetry exporter
family (every `opentelemetry*` package and `tracing-opentelemetry`). A
crate outside `integrations/` that declares one as a normal or build
dependency (optional included) or reaches one through its resolved
normal and build graph is `TelemetryOutsideIntegrations`, naming the
path. Rule 3.4.1 for the pure crates is unchanged. The pinned facts of
3.2.1 were re-confirmed on 2026-10-21; the v1.41.1 pin stands.
- Increment 2, `rustev-contract` (3.3, 3.4, 3.10.1): `redaction` (field
classes and defaults, the lineage rule, the `rustev.redaction/1`
document and `RedactionPolicyId`, validation naming the entry for every
refusal of 3.4.2, the effective action, the keyed HMAC-SHA256 digest
through `hmac` 0.12, `DigestKey` that is never serialized and whose
`Debug` shows only the `key_id`, and `Redactor`); `trace_fields` (the
closed catalogue and the pinned schema URL); `trace` (the
`rustev.trace/1` line under the new `TRACE_V1` limits). Tests include
RFC 4231 vectors and independently computed Rustev vectors. No existing
document, schema string, limit, canonical byte or identity changes.

Owner decisions:
- 028 takes an `extends` edge on `tools/rustev-release/`: its new
contract source files and `crates/rustev-cli/src/trace.rs` join the
reviewed archive lists, and `rustev-otel` is listed as excluded in
`release-set.json` (as 027 and 033 took).
- JSON Schemas for `rustev.redaction/1` and `rustev.trace/1`: the owner
decided on 2026-10-21 that they join spec 027's emitter. That is out of
scope here (it regenerates the committed binding declarations under
`integrations/rustev-wasm/` and `integrations/rustev-node/`) and lands
in a follow-up PR after the 028 series merges, recorded as R-46.

Local verification on this head: `make gate` and `spec-spine couple`
pass; `bash scripts/check-authored-content.sh` passes. The combined tree
of all four parts is identical to the squashed #151 head 5c44374, whose
CI run passed every job except the timed-out AI review (code, verify,
boundaries, bindings, release-checks).

Review responses (round on 14b8c82):
- `TraceLine::check` now refuses a `schema_version` other than
`SPAN_SCHEMA_VERSION` (1), on read and on write; tested in
`bad_lines_are_refused`.
- `DigestKey` key bytes: overwritten on drop (`fill(0)` then
`std::hint::black_box`). This is best effort by design: spec 028 3.1.1
gives `rustev-contract` exactly one new dependency, `hmac` (quoted:
"with one new dependency, `hmac` (3.4.5), beside its existing `sha2`"),
so `zeroize` would need a spec amendment, and the crate has
`#![forbid(unsafe_code)]`, so no volatile write. The per-call HMAC state
derived from the key is not covered. The implementation record says so.
@bartekus
bartekus force-pushed the impl/028-b-projection branch from b571dc5 to 4be133f Compare October 22, 2026 02:40
Base automatically changed from impl/028-b-projection to main October 22, 2026 03:21
bartekus added a commit that referenced this pull request Oct 22, 2026
Part 2 of 4 of spec 028, split from the single PR #151 because its AI
review timed out at 15 minutes three times. Merge in order: #151
(increments 1 and 2), #158 (increment 3), #159 (increment 4), #160
(increments 5 to 7). Each part is one signed commit; later parts are
stacked on the branch below and are rebased onto `main` after each
merge.

- Increment 3, `integrations/rustev-otel` (3.5, 3.10.2): the projection
of a delivered `rustev.run/1` record to a span tree, every value through
`Redactor`; the append-only `0600` JSONL exporter bounded by
`max_bytes`; goldens for both reference plans and the scripted remote
exchange, under the default and an all-allow policy, reproduced byte for
byte. `publish = false`, listed as excluded in `release-set.json`.

Owner decisions:
- Readings chosen where the spec left room, each recorded in the spec's
implementation record: the projection knows only the `rustev.run/1`,
`rustev.evidence/1` and `rustev.judgment/1` versions and anything later
is `projection_unknown`; outcome parameter kinds are preserved (decimals
as exact strings, composites as canonical JSON); a reader without a
`fields` override applies the most withholding action a lineage-rule
field could take; conservation is per signal in items while
`rustev.telemetry.lost{reason}` counts decisions under exactly one
reason; metric dimensions only for `allow` fields; `logs: on` with the
JSONL exporter is refused; `schema` accepts `1` alone; the configuration
ranges; the trace-id ratio in integer form; `trace tail` completeness
(root plus policy span) and polling in 200 ms steps with no clock; an
`OTEL_*` endpoint variable outside the list refuses construction.

Local verification on this head: `make gate` and `spec-spine couple`
pass; `bash scripts/check-authored-content.sh` passes. The combined tree
of all four parts is identical to the squashed #151 head 5c44374, whose
CI run passed every job except the timed-out AI review (code, verify,
boundaries, bindings, release-checks).
@github-actions

Copy link
Copy Markdown

AI review (no-findings)

I reviewed the diff carefully: new config.rs, context.rs, metrics.rs, sink.rs, updated lib.rs, test helpers, fixtures, and the spec update for spec 028 increment 4.

Lock ordering / deadlock: In deliver_record the queue and stats mutexes are taken simultaneously; in the worker, next_batch takes queue alone then releases before stats is taken; in flush_metrics only stats is taken; in metrics() only metrics then stats sequentially. All acquisition orders are consistent — no deadlock possible.

Conservation invariants: accepted = exported + lost + in_flight is maintained per signal. sampled_out decisions are returned Ok(…) before the queue section, so their spans are never counted in accepted; that is consistent with stats.sampled_out being a separate counter. The TeeSink's counted flag ensures decisions_lost increments exactly once per lost decision.

ratio_sampled arithmetic: (u128::from(per_million) << 63) / 1_000_000 stays in u128; the cast to u64 is safe because the result is at most 2^63 (when per_million = 1_000_000). The right-shift of the last 8 bytes produces at most 2^63 − 1, so ratio 1_000_000 always samples and ratio 0 never samples. ✓

Tokio Notify usage: wake.notified() is created before next_batch checks the queue; any notify_one() sent by deliver_record after that point is captured. notify_one() stores a permit if no waiter is present, so the worker does not miss wakeups between iterations. ✓

JoinBuffer exported-memory bound: self.max.max(EXPORTED_MEMORY) ensures at least 4 096 attempt IDs are remembered even when join_buffer = 1 (the minimum). ✓

run_export abort: the AbortHandle is obtained before the JoinHandle is moved into tokio::time::timeout; on timeout the handle aborts the spawned task. ✓

Boundary compliance: rustev-otel is under integrations/, so depending on rustev-runtime and tokio is permitted by the governance rules.

parse_traceparent: correctly rejects uppercase hex, version ff, all-zero IDs, and extra fields for version 00; permits extra fields for later versions per the W3C spec.

Minor corner case (not reported as a finding): if record_digest() returns an error (counted = false) inside a TeeSink with require_telemetry = true, decisions_lost is not incremented. In practice record_digest() cannot fail for a well-formed RunRecord, and the scenario is unreachable in normal operation.

No concrete, evidence-supported defects found.

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

Subject: 70b99ea...856d1d6, diff digest 02f05b499ad4545c655a9e503de4850025f072821bfd72fed5a68421a314ef6a, 1 call(s). An AI comment is not an approval.

@github-actions

Copy link
Copy Markdown

AI review (no-findings)

Reading the diff: new OtelSink implementation across config.rs, context.rs, metrics.rs, sink.rs, a comprehensive test suite, and a spec increment for spec 028.

Boundary / governance check

rustev-otel is under integrations/, so the new production dependency on rustev-runtime (and tokio) is within the tier the AGENTS.md boundary rule allows. rustev-contract and rustev-core are unchanged and still hold no async runtime dependency. No managed workflow files are touched. ✓

Lock ordering / deadlock

deliver_record acquires queue then stats simultaneously. Every other caller acquires them alone or in the same order: worker → next_batch acquires queue (releases), then stats (releases), then queue again; shutdown → queue drain (releases), then stats; begin / record_exchange → tables (releases), then stats. No reverse-order acquisition exists; no deadlock cycle. ✓

Conservation invariants

accepted = exported + lost + in_flight per signal. The queue-full and closed paths increment accepted and lost atomically under the same pair of locks, never touching in_flight. The Exported-mode waiter chain and shutdown drain correctly adjust in_flight before lost. TeeSink ensures a decision is counted under exactly one reason: f.counted suppresses tee_failed when another reason already owns it. ✓

ratio_sampled arithmetic

per_million × 2^63 / 10^6 computed in u128 (max ≈ 9.2×10²¹, well below 2¹²⁸). The cast to u64 is safe because the result is ≤ 2^63. At per_million = 1 000 000 the bound is exactly 2^63, and rnd (top bit cleared by the right-shift) is at most 2^63−1, so all IDs are sampled. At 0 the bound is 0 and nothing is sampled. ✓

Traceparent parsing

Only lowercase hex is accepted, matching the W3C header specification that mandates lowercase. Upper-case rejection is explicitly tested. Version ff and all-zero IDs are refused per spec 3.7.1. ✓

JoinBuffer / ContextTable correctness

insert in JoinBuffer checks distinct() (pointer-identity count of live Arc records) before mutating, correctly counting logical records. take records all attempt IDs as exported whether or not they were buffered, so a late exchange record for an already-exported decision is immediately exchange_unjoined. expire in both tables uses saturating_sub to avoid underflow. ✓

Metric attribute safety

AttrSet::with hard-gates on FieldClass::Enum | PlanMetadata | ModelIdentity in every build before consulting the policy, so ids, digests, and free-text values can never become dimensions regardless of redaction configuration. ✓

Log records

logs_of skips a missing root or attempt line with continue rather than indexing, preventing panics in the sink when projection produces fewer lines than expected. Log bodies use only fixed templates and enum-valued fields already present in the projection; no raw user-supplied text leaks through (confirmed by the CANARY test). ✓

Shutdown / task lifecycle

The shutdown wait correctly pre-subscribes idle.notified() before checking q.items.is_empty() && !q.exporting, so notifications fired between subscription and the check are not missed. Drained items have their in_flight adjusted before lost is incremented, keeping conservation. ✓

No concrete defects found.

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

Subject: 70b99ea...25e0194, diff digest 461dccd727872ac033c3c1562dd470762b83f2862ff239767307b0e86d3f3b76, 1 call(s). An AI comment is not an approval.

@github-actions

Copy link
Copy Markdown

AI review (no-findings)

Reviewing this PR, which adds Increment 4 (the OtelSink implementation) to integrations/rustev-otel.

Dependency and boundary check: rustev-runtime is added as a production dependency (not just dev). The crate is under integrations/, which the governance permits to take an async runtime. rustev-backend-rules is correctly dev-only. No boundary violation.

Lock ordering (sink.rs): Three mutexes — tables, queue, stats. The code consistently acquires tables alone, then drops it; later acquires queue + stats together (queue first); the worker acquires stats alone, then queue alone. No inversion exists.

Conservation invariant: accepted is incremented before the queue-full check, and if full, lose() is called in the same locked block. For sampled-out decisions no span counters are touched at all. Both paths are consistent with conserved().

ratio_sampled: The integer arithmetic uses u128 to avoid overflow and matches the stated formula per_million × 2⁶³ / 10⁶. Edge cases (0 and 1 000 000) are correct.

Shutdown liveness: shutdown uses idle.notify_waiters() (not notify_one()), which only wakes already-polled futures. If the queue drains between the notified() creation and await, the notification can be missed. This is benign because the outer tokio::time::timeout bounds the wait.

JoinBuffer::distinct() is O(n) and called on every insert. At the configured maximum of 65 536 records this can be slow, but it is not a correctness defect.

PreDrawn id fallback: The [1; 16] fallback in the None/ctx branch of deliver_record is structurally unreachable (the pre-drawn trace id is always populated before reaching that arm).

Traceparent parsing: Lowercase-only hex is enforced; the W3C spec mandates lowercase, and the test suite covers uppercase rejection explicitly.

Log record safety: Log bodies are constructed from projection-owned redacted attributes; the literal detail string from AttemptEnd::Failed is never included (only the failure_class attribute from the redacted line). The test canary assertion confirms this.

TeeSink::accepts: Delegates to OtelSink::accepts, which uses the default EvidenceSink implementation. Unknown schemas are accepted and produce a PROJECTION_UNKNOWN loss rather than a delivery refusal, which is the intended behavior.

Spec consistency: Range constants in config.rs::ranges match the spec text exactly. Receipt prefixes (otel:accepted:, otel:exported:, otel:sampled_out:), loss reasons, and the conservation invariant are all faithfully implemented.

No concrete defects found.

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

Subject: 68f40c0...4dab2ca, diff digest 461dccd727872ac033c3c1562dd470762b83f2862ff239767307b0e86d3f3b76, 1 call(s). An AI comment is not an approval.

@bartekus
bartekus enabled auto-merge (squash) October 22, 2026 04:06
@bartekus
bartekus merged commit 1b0ce68 into main Oct 22, 2026
26 checks passed
@bartekus
bartekus deleted the impl/028-c-sink branch October 22, 2026 04:26
bartekus added a commit that referenced this pull request Oct 22, 2026
Spec 010, increment 2: the `rustev-aicortex` adapter, a non-released
integration. Follows #156 (spec 021 3.4, R-49, merged), which makes the
`rustev-aicortex` binding record's item 1 pass; rebased onto `main`
after it. Nothing here authorizes a release, publication, live service
call, spend or real-user data.

## Changes

- `integrations/rustev-aicortex/`: `AicortexContext`, a bounded read of
one claim-history page per bound subject under an explicit transaction
bound, mapped through a declared projection of 1 to 64 field bindings
into attributed snapshot entries (values, conflicts, refusals and
missing fields named; no partial history read as complete), and
`stage_observation`, an observation proposal with its Rustev lineage
staged into the host's `TxnBuilder` and never committed. Aicortex is
pinned at the record's revision
`6415b765e5267188b4ecf302a93869352e28cccc`, with Rahi `=0.6.0`, which
that revision pins. Tests: unit tests of the projection, kind mapping,
identities and refusals, and integration tests against a single-voter
Rahi 0.6.0 store with Aicortex's schema on loopback. The code is the
adapter kept on `wip/010-rustev-aicortex-adapter` (`c776546`),
unchanged.
- `specs/010-integrations/spec.md`: the `rustev-aicortex` record's item
1 passes under R-49 (its Git dependency is outside the release closure;
every release member still resolves from crates.io only), so the record
passes every row; `planned: true` is removed from its `establishes`
entry; the Verification block runs its tests, clippy and build and the
authorization-type grep; the implementation record describes increment
2.
- `tools/rustev-release/release-set.json`: `rustev-aicortex` is excluded
from the release family. `docs/backlog.md` RUSTEV-015 state.
- `tools/rustev-release/tests/manifests.rs`: #156's
`a_git_source_only_an_excluded_package_reaches_is_not_judged` asserted
exactly one violation when the resolve graph is absent, which held only
while no workspace package had a Git source. With `rustev-aicortex` its
real Aicortex packages are judged too (`code` failed on `b988788`), so
that case now asserts the added package is among the violations and
every violation is a source violation.
- `Cargo.lock`: regenerated by Cargo for the Aicortex revision and Rahi
0.6.0's graph (Rahi 0.7.1's entries stay; Cargo now names the two Rahi
versions explicitly in dependency lists).

## Limitation

The adapter pins Rahi 0.6.0 and `rustev-rahi` pins 0.7.1, so one host
cell cannot link both until Aicortex adopts Rahi 0.7.1 (record item 1).
`rustev-serve` stays unimplemented (its record refuses).

## Review history

Round 1 on `374a86b` (stacked on #156): no findings. Rebased onto `main`
at `3a238a1` after #156 merged (no conflict, derived shards unchanged).
Round 2 on `b988788`: no findings, but the `code` job failed on the
manifest test above; fixed in this head.

Round 3 on `413c222` (1 finding, rejected with evidence): it read
`serde_core` in `uuid`'s dependency list as an unrecognized crate.
`serde_core` is serde's own core crate, which `serde` 1.0.220 and later
depend on; `main` at `3a238a1` already locks it (`Cargo.lock`: `name =
"serde_core"`, `version = "1.0.229"`, crates.io, checksum
`67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48`), and
`serde` 1.0.229's entry lists it. This PR adds no `serde_core` package
entry; only the `uuid` edge is new, because Aicortex enables `uuid`'s
`serde` feature.
Round 3 rerun on `413c222` (the `code` job had a timing flake in
`rustev-remote-http`'s `runtime_batch`, untouched here; run re-run): no
findings. Rebased onto `main` at `fd19273` (#155, no conflict).
Round 4 on `2a80b7b`: no findings. Rebased onto `main` at `70a6424`
(#154, no conflict).
Round 5 on `199b201`: no findings; held for the coordinator's merge
hold. Rebased onto `main` at `cf6665c` (#151, no conflict; `Cargo.lock`
still resolves with `--locked`).
Round 6 on `0024f6c`: no findings; held for the coordinator's merge
hold. Rebased onto `main` at `70b99ea` (#158): `release-set.json` kept
both the new `rustev-otel` exclusion and this one; the manifest tests
pass locally (18 of 18).
Round 7 on `0550224`: no findings. Rebased onto `main` at `68f40c0`
(#161, no conflict).
Round 8 on `2ccb9f9` (1 finding, the same `serde_core` question as round
3): the `rustev-aicortex` record's item 1 now states the new `uuid ->
serde_core` edge and where `serde_core` comes from, so the evidence is
inside the diff.
Round 9 on `242c75f`: no findings. Rebased onto `main` at `1b0ce68`
(#159, no conflict).
bartekus added a commit that referenced this pull request Oct 22, 2026
Spec 028, split from the single PR #151 (its AI review timed out at 15
minutes three times) into #151, #158 and #159 (merging in that order),
then #160 (increment 5), #164 (increment 6) and #165 (increment 7). Each
part is one signed commit and builds on its own; later parts are stacked
on the branch below and rebased onto `main` after each merge.

- Increment 5, `rustev trace tail` (3.11, amends spec 006): `--file`,
`--trace-id`, `--redaction`, `--follow`, `--timeout-ms`, `--text`, with
`rustev-contract` alone and no new CLI dependency; the reader's policy
applies on top of the line's, and keys outside the catalogue are
counted, never echoed. End-to-end tests through the binary over the
goldens.

Review responses (from the earlier #160 round on 6bf3bcd): `node`
recursed with no cycle or depth bound; a span reached twice or deeper
than 64 levels is now `invalid_input` naming the line, tested in
`a_cyclic_or_too_deep_span_tree_is_invalid_input_not_a_crash`.

Local verification on this head: `make gate`, `spec-spine couple` and
`bash scripts/check-authored-content.sh` pass. CI runs code, verify and
boundaries.

Review response (round on 01146e8): the resource's withheld and
uncatalogued attributes were counted into locals and dropped; the
resource object now carries its own `withheld_by_reader` and
`not_in_catalogue`, tested in
`a_key_outside_the_catalogue_is_withheld_with_a_notice`.
bartekus added a commit that referenced this pull request Oct 22, 2026
Spec 029 increment 3: repeat sets and `rustev.repeat-report/1` (3.1,
3.2.5, 3.5, 3.6). Library only; no CLI, ledger, baseline or gate yet; no
live run, provider call or spend. `implementation` stays `in-progress`.

- `rustev-eval/src/repeat.rs` (new): `repeat(RepeatInputs)` over N
reconciled runs. Refuses the `live` source (`live-source-unavailable`),
  N outside 1 to 64, unreconciled case measures (`reconcile`), runs that
  differ in dataset, split, evaluator configuration, plan or metric list
  or do not list the split's cases in manifest order (`mixed-runs`), a
  `replay` set whose runs are not identical (`not-reproducible`), an
  unreported stability metric or override, and a cohort over the
  bootstrap bound (`bootstrap-too-large`). The report names the source,
  configurations, dataset, split and fixed role (3.7.1), provenance,
  adapter rules, plan, each run's document digests and run seed, the
  stable cohort, and per cohort (`all`, then each slice) every metric's
per-run values, `mean`, `sd`, `min`, `max`, `pooled`, interval and band
  with its basis. Slices below their minimum are unknown throughout; a
metric without a per-case measure (cost totals, `brier`) has across-run
  statistics in `all` only. Latency, queue and cost metrics state their
observation (`historical` for candidate runs, 3.11.2). A held-out report
  records `held_out` as unknown until increment 4 adds the ledger.
- `rustev-eval/src/report.rs`, `eval_cases.rs`: `cost_per_1000/observed`
  and `/estimated` case measures (3.2.5), unknown unless cost units are
  declared comparable, the observed series unknown for a case with
  liability or an unknown charge; none for a candidate.
- `rustev-eval/src/repeat_stats.rs`: `across_runs`, factored out of
  `run_stats` unchanged, for metrics stated only by the run reports.
- Tests (`tests/reports.rs`): replay set (zero `deterministic_replay`
  band, pooled equal to the report, distinct run seeds, stable cohort,
  totals and `brier`, observations, unknown `cost_per_1000`, a reported
  slice and one below its minimum, round trip and byte determinism);
  captured set with a case losing its bundle (stable cohort, positive
  `k_sd` band); one captured run (unknown band); differing replays, the
  live source and N of 0 and 65 refused; mixed baseline and candidate
runs, unreconciled measures and an unreported stability metric refused;
  a candidate set with historical observations and `interval_width`
  bands.
- `tools/rustev-release/archive-policy.json`: `src/repeat.rs`.
- Spec 029: increment 3 record and engineering choices.

Still open from increment 2: owner decision D-029-1 (Brier per-case
measures), recorded in spec 029's implementation record.

Local verification (macOS arm64): `make gate` passes with spec-spine
0.31.0; `cargo clippy -p rustev-eval --all-targets -- -D warnings`,
`cargo test -p rustev-eval` and `cargo test -p rustev-fp-corpus` pass.

Review round 1 (1 finding, not a defect, evidence added): the finding
says
a candidate's cases get a known `cost_per_1000/observed` when costs are
comparable and known. The cost measures sit inside `case_measures_of`'s
`if inputs.candidate.is_none()` block (opened above the latency loop,
outside the reviewed hunk), so a candidate's cases carry none. A comment
now says so in the hunk, and a new test,
`cost_per_1000_is_measured_for_a_baseline_and_never_for_a_candidate`,
declares cost units comparable and checks that the baseline's cases
carry
cost per 1000 while the candidate's carry none and its repeat report's
`cost_per_1000/observed` is historical and unknown.

Review round 2: no findings. Rebased onto `main` after #159 (no
conflict).
`make code` passes locally on this head, except two failures caused by
other worktrees sharing the build target (a test binary removed by a
concurrent `cargo clean`, and `rustev-jev`'s `lodging_swap` finding its
output directory already created by a concurrent run); each passes when
rerun alone.

Review round 3 (1 finding, fixed by making the rule explicit): the
finding
says `cost_unknown_attempts` should carry no observation. It is one of
the
four cost series a spec 004 candidate report replaces with "the
candidate
was not executed; latency and cost are the baseline's", so it is an
observation of the runs and historical for a candidate, as 3.12.4 needs.
`observation` now lists latency, queue, the four cost series and
`cost_per_1000/*` by name instead of a `cost_` prefix, with that reason
in
its comment; the candidate test checks the cost series are historical
and
a quality metric has no observation.

Local on this head: `make gate` passes; `cargo test --workspace
--no-fail-fast` passes except `rustev-release --test manifests`, which
reports a `rustev-aicortex` member that exists only in another lane's
worktree sharing the build target, and passes when run alone; clippy,
fmt and boundaries pass.
Rebased onto `main` after #157 (no conflict); `rustev-eval` and
`rustev-release` tests (including `manifests`, now that
`rustev-aicortex` is on `main`) and `rustev-eval` clippy pass on the
rebased head.
Review round 4: no findings. Rebased onto `main` after #162 (no
conflict).
Review round 5: no findings. Rebased onto `main` after #160 (no
conflict); `make code` and `make gate` pass locally on this head.
Review round 6: no findings. Its `code` run failed in
`rustev-remote-http --test runtime_batch`

(`a_deadline_or_a_cancellation_after_send_ends_every_member_as_independent_calls_do`),
a timing test in a crate this PR does not touch. Rebased onto `main`
after
#167, which changes no Rust source, so the previous head's local `make
code`
still covers the Rust tree; `make gate` passes.
bartekus added a commit that referenced this pull request Oct 22, 2026
Spec 028, split from the single PR #151 (its AI review timed out at 15
minutes three times) into #151, #158 and #159 (merging in that order),
then #160 (increment 5), #164 (increment 6) and #165 (increment 7). Each
part is one signed commit and builds on its own; later parts are stacked
on the branch below and rebased onto `main` after each merge.

- Increment 6, OTLP (3.2.3, 3.9.1 to 3.9.3): `opentelemetry`,
`opentelemetry_sdk` and `opentelemetry-otlp` 0.33 with `default-features
= false`, used only by `rustev-otel` behind `otlp-grpc` and `otlp-http`;
no `reqwest`, no `internal-logs`, default features empty. `endpoint`
refuses, before anything is built or dialed, an origin not exactly in
the list, an empty list, user information, wildcards, plaintext to
anything but a loopback IP literal, and an `OTEL_*` endpoint variable
naming an origin outside the list. Redirects are never followed.
Loopback fake collectors on h2 and hyper.

Owner decisions:
- TLS paths (gRPC with the host's `ca_pem`, HTTP with given roots or the
Web PKI roots) are compiled and type-checked but not exercised by a
test: the workspace has no certificate generator. The tests run
plaintext to loopback only. The spec record says so.

Local verification on this head: `make gate`, `spec-spine couple` and
`bash scripts/check-authored-content.sh` pass. CI runs code, verify and
boundaries.

Review response (round on be6f412): an unbracketed IPv6 literal
(`http://::1:4318`) parsed, its last colon read as the port separator; a
colon left in the host outside brackets is now `Malformed` ("an IPv6
literal outside brackets"), tested in `endpoint::tests::refusals`.
Bracketed literals (`http://[::1]:4317`) are unchanged.

Review responses (round on 230e1eb):
- Duplicate header names: both builders validated every entry but HTTP
collected them into a map (and gRPC's `HeaderMap::insert` overwrote), so
one value was silently dropped. A name given twice, compared
case-insensitively, is now `OtlpError::DuplicateHeader` before anything
is built; tested in `header_values_never_appear_in_errors_or_debug`.
- Log severity: `export_logs` set `Severity::Warn` regardless of the
record. It now maps the record's own `severity_number` (1 to 24) to the
OpenTelemetry severity, leaving an out-of-range number unspecified;
unit-tested in `otlp::tests`. The sink writes only `WARN`/13 today, so
exported bytes are unchanged.

Review response (round on 0b09035): the finding read "3.12" in the
workspace `Cargo.toml` comment as a typo. It is not: spec 028 3.12 is
"Dependency boundary", the amendment of spec 001 3.5 that forbids every
`opentelemetry*` package outside `integrations/` (the rule `make
boundaries` enforces). The comment now names both cited sections by
title so the citation is checkable from the diff.
bartekus added a commit that referenced this pull request Oct 22, 2026
…on (#165)

Spec 028, split from the single PR #151 (its AI review timed out at 15
minutes three times) into #151, #158 and #159 (merging in that order),
then #160 (increment 5), #164 (increment 6) and #165 (increment 7). Each
part is one signed commit and builds on its own; later parts are stacked
on the branch below and rebased onto `main` after each merge.

- Increment 7 (3.14, Acceptance): the redaction property test (200
seeded decisions, canaries in every text and identifier slot, generated
policies; no canary of a `drop` field in any exported byte, raw or cut,
and no raw canary of a `digest` field), the overhead benchmark
`examples/overhead.rs` with its 100-decision smoke test, and the
`verify:cli` block.

Benchmark (`cargo run -p rustev-otel --release --all-features --example
overhead`), 10 000 decisions per configuration alternating the two
reference plans after 1 000 warm-up, concurrency 4 under `backpressure`
(64 pending). CPU and RSS are the whole process, which also hosts the
fake collector. No threshold is asserted (3.14.3).

| Configuration | Decision p50 / p95 / p99 ms | `deliver` p50 / p99 ms |
CPU ms per decision | Exported bytes per decision | Peak RSS KiB | Loss
|
|---|---|---|---|---|---|---|
| (a) in-memory sink | 0.197 / 0.254 / 0.276 | 0.0001 / 0.0001 | 0.153 |
0 | 12 704 | 0 |
| (b) no-op exporter | 0.180 / 0.234 / 0.250 | 0.603 / 0.846 | 0.722 | 0
| 14 672 | 0 |
| (c) JSONL file | 0.206 / 0.427 / 0.536 | 0.730 / 1.595 | 1.336 | 22
657 | 28 784 | 0 |
| (d) OTLP/gRPC, loopback | 0.187 / 0.249 / 0.266 | 0.633 / 0.885 |
0.874 | 13 566 | 31 008 | 0 |
| (e) OTLP/HTTP, loopback | 0.188 / 0.252 / 0.279 | 0.623 / 0.904 |
0.834 | 13 561 | 32 464 | 0 |

Loss is zero everywhere: no decision failure, no runtime sink failure,
timeout or drop, no telemetry lost and none in flight at the end.

Local verification on this head: `make gate`, `spec-spine couple` and
`bash scripts/check-authored-content.sh` pass. CI runs code, verify and
boundaries.

Review response (round on b1ad15f): the finding read
`exported_bytes_per_decision` as dividing warm-up-inclusive bytes by the
wrong count. It does not: `bytes_start` is read before the warm-up, so
the bytes cover all 11 000 decisions and dividing by 11 000 is right.
The real inconsistency was the CPU figure: `cpu_start` is also read
before the warm-up, but CPU time was divided by the 10 000 measured
decisions. Both now divide by every decision run (a comment in
`overhead.rs` says so). The CPU column above is the earlier run's CPU
time divided by 11 000 instead of 10 000 (each value times 10/11), not a
new run; bytes, latency and RSS are unchanged.
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