Skip to content

Add endpoint tracing primitives and immutable creation-context helpers - #94

Merged
thomhurst merged 3 commits into
mainfrom
issue-91-tracing
Nov 1, 2026
Merged

thomhurst merged 3 commits into
mainfrom
issue-91-tracing

Conversation

@thomhurst

@thomhurst thomhurst commented Nov 1, 2026 •

Copy link
Copy Markdown
Owner

Adds the shared tracing foundation for #13: a provider-owned Relayer ActivitySource with schema 1.37.0, precomputed endpoint operations, parent/link rules, recorded-only enrichment, and immutable W3C creation-context helpers. Reuses the existing envelope formatter. Includes listener tests, MemoryDiagnoser benchmarks, documentation, and Native AOT smoke coverage.

Batch validation runs independently of listeners and existing creation contexts. Missing error types use _OTHER. Enricher failures cannot interrupt delivery or leave an undisposed current activity; later enrichers still run. Telemetry() documents provider ownership and recommends one production provider.

Sampling receives the design §8.3 attributes, partition ID, and all creation links. Constant tags are passed directly; per-operation scratch storage reuses partition tags and links, with references cleared after StartActivity consumes them. Other message attributes are added only when all activity data is requested. UTF-8 traceparent parsing uses stack storage and immutable SearchValues validation while preserving the framework parser's version, flag, validation and remote-context behavior. Headers remain unchanged. The small no-listener entry point stays separate from enabled tracing.

Automatic send instrumentation remains in #92; process and settlement integration remains in #93. Outbox integration remains in #36. The parent issue stays open. The allocation follow-up from #96 is included here.

Validation for 085698951b5461e09f4f3b2b102cb12fe236f95a:

  • Release build passed with 0 warnings and 0 errors; all 339 tests passed, including 43 dedicated tracing cases.
  • Three new allocation regression cases failed before these fixes. Added sampler-visible partition/link checks, concurrent and reentrant starts, borrowed-buffer reuse, and UTF-8/UTF-16 parser equivalence cases.
  • Native AOT win-x64 publish and executable smoke run passed, including UTF-8 parsing and reused sampling storage.
  • BenchmarkDotNet Dry validation passed. Side-by-side baseline/candidate diagnostics use MemoryDiagnoser; raw reports and harness sources are archived.
  • Final default-job no-listener Send: 6.59 to 1.53 ns, 0 B. Dropped Send/single/batch preparation: 0 B; final Short means fell approximately 49–62%.
  • Recorded allocations fell from 840/1216/1320 B to 648/848/872 B for Send/single/batch. Recorded-send timing was unchanged within Short-run noise (ratio 1.01, RatioSD 0.09); single/batch means improved. These diagnostic figures are not native-broker throughput or end-to-end acceptance measurements.
  • Final default-job UTF-8 reads: 67.9 to 66.0 ns without tracestate, 90.9 to 82.2 ns with tracestate; allocations fell from 280 to 144 B and 328 to 192 B. The remaining 144 B stores the framework's trace/span IDs; UTF-8 tracestate adds 48 B. No claim that ActivityContext itself allocates nothing.
  • Per-message cost: inactive tracing remains constant-time checks, 0 B; enabled tracing reuses sampling state through Interlocked operations and copies links into reused storage, with no steady-state preparation allocation in the measured cases. Framework activity/context allocations are measured separately.
  • Final diff reviewed for correctness, reuse, quality and efficiency under code-simplifier guidance.

Validation evidence is outside removable worktrees at C:/git/Relayer-evidence/pr-94/085698951b5461e09f4f3b2b102cb12fe236f95a/ (local 7-day retention). Its 809 inventoried files were SHA-256 verified against originals and rechecked against sha256-inventory.json. It includes raw build/test/AOT logs, test reports and loaded test binaries, Native AOT binaries, baseline/candidate benchmark sources, reports and binaries, framework inspection evidence, and the committed source archive. comparison/PROVENANCE.md distinguishes the rejected intermediate scalar parser from final measurements and records the pre-commit build metadata.

Closes #91
Closes #96

@coderabbitai

coderabbitai Bot commented Nov 1, 2026 •

Copy link
Copy Markdown

Important

  • Trigger review

This repository does not receive automatic reviews because it has fewer than 10 stars.

Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 050b3fac-4dae-43a6-9421-01fc6b80a7ff
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@thomhurst

Copy link
Copy Markdown
Owner Author

@codex review

@github-actions

github-actions Bot commented Nov 1, 2026

Copy link
Copy Markdown

Review of PR 94 (tracing primitives)

The design follows D15/D25 well: one ActivitySource named Relayer, a startup-precomputed span name and constant tags, and a no-op when no listener is attached. I checked the diff against AGENTS.md. My concerns are below.

Blocking

  1. Argument validation in MessageOperationTracing.Start only runs when a listener is attached. The HasListeners() early return comes before the BatchCount < 1 check and the "Create describes one message, never a batch" check. A caller bug is invisible in tests and local runs without tracing. It throws in production once an exporter is enabled, from inside the send/process path, so tracing would break message handling. This conflicts with fail-early (D16/D24). Either make these checks unconditional and place them before the listener check (two integer/enum comparisons, 0 B per message), or drop the throws and ignore bad input, because telemetry should not take down delivery. Fail has the same problem: ThrowIfNullOrWhiteSpace(errorType) runs on the error path, and a throw there masks the original exception. Prefer Debug.Assert or a fallback value.

Should fix (per-message cost with a listener)

  1. Start allocates on every call once any listener is attached, even if the sampler drops the span: a copied ActivityTagsCollection, data.Links.ToArray(), and a one-element link array, all before the sampler decides. Options: pass the precomputed _tags array directly when there are no per-message tags; cache the single-context link array or call AddLink only once IsAllDataRequested is known; move per-message tags (MessageId, EventType and so on) to SetTag after creation, guarded by IsAllDataRequested, keeping only sampling-relevant tags at start. The added TracingBenchmarks with Listener = true should show this, and AGENTS.md zero-allocation budget covers Relayer own work in that case too.

  2. MessageCreationContext.Read calls ToString() on the traceparent span for every message, and again for tracestate. That is a 55-char string per message on the receive path. Parse the fixed-width W3C traceparent from the span (MessageEnvelope already writes the same format) and only build a string for tracestate when present. The remark says "only when tracing needs it", but nothing enforces that, so please guard call sites with HasListeners when they are added.

Minor

  • MessageTracing creates its own ActivitySource per instance, all named Relayer. That is fine for D17 test isolation, but two instances in one process both emit under that name. Add a doc note on Telemetry() that it is one per container.
  • Enrich runs user enrichers without try/catch. The contract says "must not throw", but a throwing enricher would break send/process. A try/catch costs nothing on the non-throwing path.

Tests and benchmark are present, and the WriteCreationContext refactor keeps the existing envelope behavior. Please address item 1, and fix items 2 and 3 or record them as follow-up issues in the PR, per AGENTS.md.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 1, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-01T13:16:14.180216Z 0856989 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Breezy!

Reviewed commit: 002f1ab50a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@github-actions

github-actions Bot commented Nov 1, 2026

Copy link
Copy Markdown

Review of PR 94 at head e44ba4c (tracing primitives)

Earlier findings are partly addressed. The argument checks in Start now run before the HasListeners check, Fail no longer throws, and Enrich swallows enricher exceptions. The design otherwise fits D15/D25 and the tests cover it.

Blocking: allocations that AGENTS.md forbids (still unaddressed from the prior review)

  1. MessageOperationTracing.Start allocates in Relayer's own code on every call once any listener exists, including when the sampler drops the span. It builds a new ActivityTagsCollection(_tags), calls data.Links.ToArray(), and creates new[] { new ActivityLink(...) }. All of that happens before the sampler decides. The PR text attributes these allocations to System.Diagnostics, but these particular ones are Relayer's. Better approach:

    • Pass only the sampling-relevant tags at start, using the precomputed constant array directly as IEnumerable<KeyValuePair<string, object?>> when there are no per-message sampling tags (the partition id is the only one).
    • Set the per-message tags (message id, event type, source, conversation id, body size) with SetTag only after IsAllDataRequested is true.
    • Add links with AddLink after the same check. For a single creation context this removes the array allocation.
      This makes a sampled-out span cost 0 B from Relayer, which is what the budget asks for.
  2. MessageCreationContext.Read calls traceParent.ToString() for every message, plus a ToString() for tracestate. That is a 55-char string on the receive path, and nothing guards it by listener or propagation need. MessageEnvelope already writes the fixed-width format. Parse the 55 chars from the span directly (version, trace id, span id and flags with ActivityTraceId.CreateFromString and ActivitySpanId.CreateFromString over ReadOnlySpan<char> or UTF-8), and allocate a string only when tracestate is present. Alternatively, keep it as is but require call sites to guard it with HasListeners, and document that. Parsing without a string is the better fix because it also covers propagation-only use.

Non-blocking

  • Telemetry() registers one MessageTracing per provider, and every instance uses the source name Relayer. That is fine for D17 isolation, but add a short doc note that production code should keep a single container.

Per AGENTS.md, a benchmark with Listener = true and a sampled-out variant should show 0 B once items 1 and 2 are fixed.

@thomhurst

Copy link
Copy Markdown
Owner Author

Disposition of Claude's review, addressed in e44ba4c:

  1. Blocking, fixed. Batch validation now precedes both the listener check and the existing-creation-context shortcut. Invalid counts and create-with-batch metadata fail consistently with or without a listener. Fail uses _OTHER for null, empty, or whitespace error types instead of throwing over the original failure.
  2. Non-blocking optimization, tracked in Reduce tracing allocations before sampling and during UTF-8 context parsing #96. The pre-sampling copies are real. D25 and design §8.5/§12 explicitly measure the zero-allocation budget with no listener and measure enabled tracing separately. Moving tags/links after sampling would change what samplers can observe; Reduce tracing allocations before sampling and during UTF-8 context parsing #96 requires benchmark evidence while preserving those contracts and borrowed-buffer lifetimes. This PR retains its required no-listener allocation test and primitive benchmarks.
  3. Non-blocking optimization, tracked in Reduce tracing allocations before sampling and during UTF-8 context parsing #96. WireString.ToString() reuses existing UTF-16 strings; the traceparent allocation applies to UTF-8 values. A span parser must preserve the framework parser's W3C validation/version handling. There are no automatic send/receive callers of Read in this PR; integration belongs to Integrate tracing into direct single and batch sends #92/Integrate process and settlement tracing into delivery pipelines #93. Reduce tracing allocations before sampling and during UTF-8 context parsing #96 also records on-demand reads without gating required propagation solely on listeners.
  4. Minor ownership documentation, fixed. Telemetry() and the guide now state one shared source per provider and separate sources for separate providers.
  5. Enricher failure isolation, fixed. Each recorded-span enricher has its own exception boundary. A throwing enricher cannot abort Start, leak the created activity, or prevent later enrichers from running. The regression test verifies activity disposal restores the ambient activity and the next enricher executes.

Validation: Release build passed with zero warnings; 332 tests passed, including 36 tracing cases; win-x64 Native AOT publish and smoke execution passed. Nine of the 12 new regression cases failed before the fixes. Per-message cost of this revision: constant-time batch validation, 0 B; fallback/error isolation adds no successful-path allocation. The no-listener allocation regression still reports 0 B. Current evidence and SHA-256 inventory are linked in the PR body. The draft stays in review for this new head.

@thomhurst

Copy link
Copy Markdown
Owner Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

Reviewed commit: e44ba4c355

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@github-actions

github-actions Bot commented Nov 1, 2026

Copy link
Copy Markdown

Review of PR 94 (tracing primitives)

I read the tracing code against AGENTS.md and found nothing that should block merge.

  • Design: It matches D15/D25. There is one Relayer ActivitySource per provider. The span name and constant tags are precomputed once per endpoint. Start returns null before any tag work when no listener is attached. Pooled sampling state is handed out and returned with Interlocked, with no locks. The pool is returned in a finally.
  • Per-message cost: The batch metadata checks run before HasListeners, as constant-time checks. The PR states 0 B with no listener and backs it with a regression test, so no benchmark is needed.
  • Correctness:
    • The parent, link and kind rules for Create, Send and Process look consistent.
    • An existing creation context skips Create and makes Send a client span.
    • WriteIfAbsent never overwrites an existing traceparent.
    • Fail falls back to _OTHER.
    • Enricher exceptions are isolated, so a throwing enricher cannot leave an undisposed Activity.Current.
  • Tests and docs: The PR adds 36 listener tests, an AOT smoke test and design/tracing docs. The earlier Codex review of the previous head found no major issues. The recorded-only allocation follow-ups are tracked in Reduce tracing allocations before sampling and during UTF-8 context parsing #96.

Non-blocking suggestions:

  1. MessageTracing.Enrich swallows enricher exceptions silently. Logging them through a LoggerMessage source-generated method, rate-limited, would make a broken enricher diagnosable. This is on an error path, so it costs nothing in steady state.
  2. Because AGENTS.md prefers explicit APIs, a one-line note on Telemetry() about where AddSource("Relayer") must be called would help. The remarks already cover the provider ownership contract.

@thomhurst

Copy link
Copy Markdown
Owner Author

Disposition of Claude's current-head review, addressed in 0856989:

  1. Blocking, fixed. Constant tags now pass directly to ActivitySource. Partition and creation links use reused per-operation storage, including sliced borrowed batch buffers. All design §8.3 sampling attributes and creation links remain visible to samplers; other message attributes and numeric boxing wait for IsAllDataRequested. Storage is cleared and returned after synchronous sampling/copying. Reentrant, concurrent, borrowed-buffer and dropped-span allocation tests pass. Warmed dropped cases allocate 0 B in the measurements. Framework root-ID allocation is explicitly separated in the test and documentation.
  2. Blocking, fixed. UTF-8 traceparent no longer becomes a whole-header string. Stack storage and immutable SearchValues validation preserve ActivityContext.TryParse behavior, including future versions and flags. UTF-16 retains the framework path. Equivalence tests cover valid/invalid UTF-8 and UTF-16 values. Native context ID strings still cost 144 B on this runtime; the removed header costs 136 B. Default-job diagnostics show reduced allocations without a parsing slowdown. The slower intermediate scalar parser was rejected rather than trading CPU for allocations.
  3. Non-blocking documentation, fixed alongside blocking changes. Telemetry() now recommends one production service provider while retaining provider-owned sources and test isolation.

Release build: 0 warnings/errors. Tests: 339 passed, including 43 tracing cases. Native AOT publish and smoke passed. Final benchmark comparisons, raw evidence, provenance and the verified 809-file SHA-256 inventory are linked in the PR body. #96 is now included in this draft and will close on merge. Fresh reviews are required for this head; the draft remains in review.

@thomhurst

Copy link
Copy Markdown
Owner Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: 085698951b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@thomhurst

Copy link
Copy Markdown
Owner Author

Disposition of the optional suggestions in Claude's CLEAR review for 0856989:

  1. Non-blocking diagnostic enhancement, declined for this PR. Rate-limited enricher logging adds a diagnostic policy beyond these primitives. Exception isolation and subsequent-enricher execution are covered by the regression tests. No correctness fix remains here, so this does not justify another review-fix push.
  2. Non-blocking documentation suggestion, declined as redundant. MessageTracing.Source already documents that it is the source to enable with AddSource("Relayer"). Telemetry() documents registration and provider ownership. No code change is needed for this optional extra note.

The PR remains a draft while the requested Codex review completes for this head.

@thomhurst

Copy link
Copy Markdown
Owner Author

Both required reviewers approve head 0856989: Claude's CLEAR verdict is in #94 (comment) and Codex's completed summary is in #94 (comment). All review surfaces have been checked; there are no review threads, and the optional suggestions already have dispositions.

Before promotion, I reverified all 809 files in C:/git/Relayer-evidence/pr-94/085698951b5461e09f4f3b2b102cb12fe236f95a/ against sha256-inventory.json. All 142 surviving originals also match; the remaining worktree originals were removed after their previously verified archival. A regenerated source archive matches the reviewed commit. The archived reports and binaries remain intact under the documented local 7-day retention. The verification record is C:/git/Relayer-evidence/pr-94/promotion-verification.txt.

Promoting and arming this reviewed head with scripts/Enable-AutoMerge.ps1 -Pr 94 -MarkReady; GitHub will wait for required CI.

@thomhurst
thomhurst marked this pull request as ready for review November 1, 2026 13:14
@thomhurst
thomhurst enabled auto-merge (squash) November 1, 2026 13:15
@thomhurst
thomhurst merged commit 0d98a84 into main Nov 1, 2026
14 checks passed
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.

Reduce tracing allocations before sampling and during UTF-8 context parsing Add endpoint tracing primitives and creation-context helpers

1 participant