Skip to content

fix: record native Kafka and Service Bus send durations - #301

Merged
thomhurst merged 3 commits into
mainfrom
issue-296-send-durations
Nov 2, 2026
Merged

thomhurst merged 3 commits into
mainfrom
issue-296-send-durations

Conversation

@thomhurst

@thomhurst thomhurst commented Nov 2, 2026 •

Copy link
Copy Markdown
Owner

Kafka and Service Bus sends now record one messaging.client.operation.duration measurement per actual native send call, including acknowledgement, native retries, failure and cancellation. Timing lives inside the adapter, so logical batching, pipeline tracing and outbox dispatch do not duplicate measurements; enqueue and preparation failures emit none.

  • Reuse the existing SendTracing endpoint recorder with an allocation-free native-operation timer. Disabled instruments avoid clock reads; concurrent Kafka tombstone sends also avoid a completion wrapper when disabled.
  • Measure each Service Bus batch after native size/session/partition splitting and each Kafka native operation, preserving synchronous admission failures and draining admitted calls before returning borrowed storage.
  • Use bounded error.type = "_OTHER", precomputed dimensions and the native Service Bus namespace. Document the boundary and extend native-comparison benchmarks with metrics enabled/disabled.

Native-first review: this builds on Dekaf 1.25.0 ProduceAsync, ForTopic().ProduceAsync, ProduceAllAsync and its existing acknowledgement/retry/instrumentation paths (source), and Azure.Messaging.ServiceBus 7.21.0 SendMessageAsync, CreateMessageBatchAsync, TryAddMessage and SendMessagesAsync (source). It reuses Relayer's RelayerInstrumentation, EndpointTelemetry.RecordDuration, batch grouping and send pools. Native metrics remain intact; the missing measurement is on Relayer's existing instrument. No new meter, span, retry, batching or acknowledgement implementation is introduced, and no decision exception is needed.

Validation:

  • 70 focused core/Service Bus tests, including real Service Bus emulator sends, pass.
  • 25 Kafka tests pass, including Kafka 4.0.2 sends/tombstones/conformance, native completion failures and inline state reuse. A deterministic 128-concurrent-completion test verifies 0 B after warmup.
  • All 117 tracing tests pass. Additional duration tests cover pending completion, bounded errors, cancellation, mixed batches, dispatch, enqueue exclusion and the typed pipeline with/without activity listeners. The timer allocates 0 B after warmup with metrics enabled and disabled.
  • npm ci and the documentation production build pass on Node.js 24.14.1. The existing 22 low/moderate audit findings are unchanged and already recorded in Address documentation dependency audit vulnerabilities #101.
  • dotnet build -c Release passes with 0 warnings/errors. Both native comparison suites completed 24 Dry and 24 Short cases. After refinement, an additional 8-case Kafka batch comparison ran with 64 invocations/iteration, 3 warmups and 3 measurements. The measured tombstone batch allocation fell from 342 to 51 B/message after replacing the pooled async wrapper with retained completion state; these broker figures include native/serializer allocations. The isolated retained completion test is 0 B at 128 concurrent operations. Wide ShortRun confidence intervals prevent a throughput-budget claim; these local numbers are diagnostic and the PR carries performance for the advisory CI gate.

Per native operation: one additional Kafka endpoint lookup and an instrument-enabled check, with two clock reads and one existing histogram record when enabled, 0 B from the timer. Concurrent Kafka tombstone completions use a retained IValueTaskSource only when measurement is enabled, avoiding pooled async builder retention-cap allocations. Native synchronous admission failure behavior is preserved. The native-comparison benchmarks include native client and serializer allocations.

Unrelated finding: filed #302 for the existing sent counter incrementing before validation/preparation and pre-counting unattempted batch tails. This PR fixes duration accounting only.

Evidence: raw reports, test logs, fixture/harness sources, repository inputs and loaded benchmark binaries are archived outside the removable worktree at C:/git/Relayer-evidence/pr-301/9bf8b14b320247d5a98de26d1556cda84aaea442/. index.txt distinguishes the initial and final measurements; sha256.json records the verified inventory. Binary/report copies were checked against their originals. Local retention lasts while this PR is open; repository cleanup may remove it after closure.

Documentation: updated the telemetry guide and clarified the design record's native-call versus logical-span boundary.

Closes #296

Maintenance validation on d092a17f1eb6eef3c4626f73eddfea4f7d5c4d60: rebased onto main 34f00f7 after #300, preserving its default JSON benchmarks and sharing the existing instrumentation instance so the Metrics parameter covers them. Release solution build passed with 0 warnings/errors; 31 focused core/Service Bus tests (including the real emulator) and 10 Kafka duration tests (including real Kafka) passed. Production per-message code is unchanged by this rebase; the extra singleton registration runs only during benchmark setup. No docs impact from this maintenance change.

Current-head source, logs, reports and binaries are archived in C:/git/Relayer-evidence/pr-301/d092a17f1eb6eef3c4626f73eddfea4f7d5c4d60/ with a verified 550-file SHA-256 inventory. The 542 copied binary files match their worktree originals. Historical benchmark measurements above remain tied to 9bf8b14 and its separately reverified 933-file archive; no new throughput-budget claim is made. Both archives follow the retention policy stated above. The previous CI run 41511589444 passed, but this new head needs fresh draft reviews before promotion.

@thomhurst thomhurst added the performance Run the advisory benchmark regression gate on this PR label Nov 2, 2026
@coderabbitai

coderabbitai Bot commented Nov 2, 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: ebed50d8-c928-4146-ae5e-1ff5cffd0326
  • 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

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 2, 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-02T19:54:42.418654Z d092a17 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. Can't wait for the next one!

Reviewed commit: 14ef62ccbc

ℹ️ 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 2, 2026

Copy link
Copy Markdown

Review of #301

I read the diff and checked it against AGENTS.md. I found nothing that should block merge. I did not build the code or run the tests.

Correctness

  • Duration is recorded once per native call and only on the send side. A grep of src shows RecordDuration is otherwise used only by the consume pipeline, so there is no double count with logical spans or outbox dispatch.
  • The timer is a default struct when there is no endpoint tracing, so those paths cost nothing. When the instrument is disabled it skips the clock reads.
  • Complete(failed) sits in a finally, so success, failure and cancellation each record exactly one measurement. Enqueue and message-preparation failures sit outside the timed region, as the PR description says.
  • The Kafka null/tombstone batch keeps its synchronous-admission behavior. ProduceAsync closes the timer in catch if the native call throws synchronously. SendNullBatchAsync still drains the pending entries before returning the borrowed storage.
  • The pooled CompleteProduceAsync wrapper is used only when metrics are enabled, so the disabled path adds no allocation.
  • Adding ServerAddress = client.FullyQualifiedNamespace for Service Bus matches the semantic-convention server.address attribute. The tests assert it.

Native-first and performance

  • It builds on the existing SendTracing/EndpointTelemetry and the native Dekaf and Service Bus send calls, and adds no parallel implementation. The PR description names the native features it uses, and it gives the per-message cost (two clock reads and one histogram record when enabled, 0 B).
  • It adds Metrics enabled/disabled parameters to the existing native-comparison benchmarks. That is enough under AGENTS.md; the benchmark results the description says are still being finalized would only be diagnostic.

Tests and docs

  • The tests cover pending completion, failure tagging with _OTHER, cancellation, split and mixed batches, outbox dispatch, enqueue exclusion, and 0 B allocation of the warm timer.
  • The telemetry guide and docs/design.md are updated, so the docs match the change.

Minor, non-blocking

  • In the benchmark files, the new using Microsoft.Extensions.Options; and using System.Diagnostics.Metrics; lines sit above the existing System.Text using. Sorting them is optional.
  • In the Kafka transport, Endpoint(...) is looked up once for the tracing wrapper and again for the timer. It is a dictionary lookup, so the cost is negligible.

@thomhurst

Copy link
Copy Markdown
Owner Author

Disposition of Claude's review of 14ef62c: both suggestions are non-blocking. Import ordering is cosmetic, so I left it unchanged. The repeated endpoint lookup is constant-time, preserves the explicit native-call boundary, and its cost is now stated in the PR; a signature refactor is unnecessary for this fix.

Local native comparison then exposed allocations from the pooled async completion wrapper at batch concurrency. Commit 9bf8b14b320247d5a98de26d1556cda84aaea442 replaces that wrapper with retained per-send completion state, preserves synchronous admission failures, and adds deterministic 128-concurrent-completion (0 B), failure and inline-reuse tests. Final native tombstone batch allocation is 51 B/message including native/serializer costs, versus 342 B with the old wrapper in the same diagnostic job. The confidence intervals remain too wide for a throughput-budget claim.

The earlier CLEAR verdicts cover 14ef62c only. This new head needs fresh reviews and remains a draft. Sent-counter accounting found during validation is tracked separately in #302.

@thomhurst

Copy link
Copy Markdown
Owner Author

@codex review

@github-actions

github-actions Bot commented Nov 2, 2026

Copy link
Copy Markdown

Review

I read the source changes in Kafka, Service Bus and SendTracing, and skimmed the tests. I did not run the build or tests.

  • Correctness: Each native call records one duration, and nothing else records it. NativeSendOperation.Complete is called once on every path, including failure and cancellation, and a default timer records nothing. The failed = true / finally pattern handles cancellation correctly.
  • Kafka tombstone batch: KafkaSendCompletion clears the native awaiter before it publishes completion, so a continuation that runs inline can't see stale state. It is only built when the duration instrument is enabled. A synchronous throw in ProduceAsync completes the timer as failed and rethrows, so the existing drain behavior is kept.
  • Per-message cost: With metrics disabled the cost is one dictionary lookup and one bool check per message, at 0 B. With metrics enabled the pooled completion keeps allocations at 0 B in steady state. The native-comparison benchmarks cover both cases, which is enough for this change.
  • Native-first: The PR builds on the native ProduceAsync, ProduceAllAsync, SendMessageAsync and SendMessagesAsync calls and the existing EndpointTelemetry. It adds no parallel implementation of a native feature.
  • Docs: docs/design.md and the telemetry guide are updated.
  • Minor, non-blocking: In the Kafka single-send path Endpoint(destination) is looked up twice per message, once in SendAsync and once in SendCoreAsync. This is trivial.

No actionable findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: 9bf8b14b32

ℹ️ 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

Both required reviewers have positive verdicts for 9bf8b14b320247d5a98de26d1556cda84aaea442: Claude's current-head CLEAR review and the completed Codex summary. All review surfaces have been checked; there are no inline reviews or review threads.

The repeated Kafka endpoint lookup remains non-blocking: this constant-time lookup is already disclosed in the per-operation cost and covered by the native-comparison benchmarks. The earlier disposition still applies; no code change is needed.

Before promotion, I rechecked all 933 files in C:/git/Relayer-evidence/pr-301/9bf8b14b320247d5a98de26d1556cda84aaea442/ against sha256.json; every file matches, with no missing or additional inventory entries. The original worktree has been removed; the prior archival verification against original binaries and reports is preserved in the PR body and archive index. The retained build and focused test logs confirm the stated passing results. This is verification of retained evidence, not a new test or benchmark run. The archive remains available while this PR is open, subject to the documented cleanup policy after closure.

@thomhurst
thomhurst marked this pull request as ready for review November 2, 2026 19:36
@thomhurst
thomhurst enabled auto-merge (squash) November 2, 2026 19:37
@thomhurst
thomhurst disabled auto-merge November 2, 2026 19:48
@thomhurst
thomhurst marked this pull request as draft November 2, 2026 19:48
@thomhurst
thomhurst force-pushed the issue-296-send-durations branch from 9bf8b14 to d092a17 Compare November 2, 2026 19:50
@thomhurst

Copy link
Copy Markdown
Owner Author

Run 41511589444 completed successfully, so the previous CI wait ended. Main then added the Service Bus JSON benchmark in #300, creating an import conflict. I disabled auto-merge, restored the draft and rebased onto 34f00f7, preserving both benchmark scenarios and both import sets.

Head d092a17f1eb6eef3c4626f73eddfea4f7d5c4d60 also registers the existing instrumentation instance with the benchmark's service provider. This makes the Metrics parameter apply to the new JSON path as well as the direct transport path. The registration is setup-only; production per-message code is unchanged by this rebase. No new native feature or duplicate implementation is introduced. No docs impact from this maintenance change; the existing telemetry documentation remains in this PR.

Validation on this head: Release solution build passed with 0 warnings/errors; 31 focused core/Service Bus tests passed, including the real emulator; all 10 Kafka duration tests passed, including real Kafka. Reviewed the combined diff for reuse, correctness and efficiency. No new performance measurements or throughput-budget claim.

The 550-file source, log, report and binary archive is at C:/git/Relayer-evidence/pr-301/d092a17f1eb6eef3c4626f73eddfea4f7d5c4d60/. All 542 copied binary files were SHA-256 verified against their originals; the complete archive inventory was rechecked. The historical 933-file archive for 9bf8b14 also still verifies. Its measurements remain evidence for that earlier head, not fresh measurements. Local retention lasts while this PR is open and cleanup may remove these archives after closure.

Earlier approvals cover the previous head only. This head remains a draft and needs fresh Claude and Codex reviews before promotion.

@thomhurst

Copy link
Copy Markdown
Owner Author

@codex review

@github-actions

github-actions Bot commented Nov 2, 2026

Copy link
Copy Markdown

Review of #301: native send duration for Kafka and Service Bus

I read the full diff and checked the Kafka tombstone-batch drain path in pr-head. I did not run the build or tests.

Design. This follows the project rules.

  • It reuses the existing EndpointTelemetry.RecordDuration and SendTracing recorder, and adds no new meter, retry or batching code.
  • Timing sits inside the adapters, around the actual native call. Logical batches, pipeline tracing and outbox dispatch therefore don't record twice, and enqueue and preparation failures record nothing.
  • When the instrument is disabled, the timer is a default struct and does no clock read. Kafka tombstone sends skip the completion wrapper in that case.
  • error.type is the bounded _OTHER. Service Bus now sets server.address from the native namespace.

Correctness.

  • KafkaSendCompletion releases _pending and the timer before it publishes the result. The result is read via GetResult with a reset in finally. This is safe for the inline-continuation reuse case, which Awaiting_batch_can_reuse_completion_state_from_an_inline_continuation covers.
  • SendNullBatchAsync awaits every admitted Pending[i] before it rethrows. Each pooled completion is therefore consumed and reset before its state returns to the pool. A synchronous admission failure stops admission and still drains earlier calls.
  • Service Bus records one measurement per native SendMessagesAsync call, after the size, session and partition split.

Tests. Coverage is thorough. It includes success, failure and cancellation, split batches, outbox dispatch, no recording for empty or preparation failures, and zero-allocation checks. The benchmarks add a metrics on/off parameter.

Non-blocking notes.

  1. In KafkaSendCompletion.Complete, an exception thrown by duration.Complete (for example from a metrics listener callback) replaces a successful send result with a failure. The message was already acknowledged, so a caller retrying on that exception would produce a duplicate. Telemetry failure shouldn't change the send outcome, so consider swallowing it there. The finally { duration.Complete(failed); } blocks elsewhere have the same weakness, but MeterListener callbacks rarely throw.
  2. Batch sends via ProduceAllAsync record one measurement for the whole native batch, not one per message. The telemetry docs describe the boundary, so this looks intentional. Check that the docs say plainly that the duration is per native call.
  3. KafkaSendBenchmarks.cs adds its using lines out of order. This is a nit.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: d092a17f1e

ℹ️ 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 Claude's current-head review, for d092a17f1eb6eef3c4626f73eddfea4f7d5c4d60:

  1. Non-blocking defensive suggestion: the exception scenario requires a custom MeterListener callback that throws. EndpointTelemetry.RecordDuration directly calls the BCL histogram, as the existing recorder methods do; no listener-isolation contract or failing exporter was identified. Keep the existing propagation behavior rather than introduce exception suppression only in this completion wrapper. The wrapper still publishes a terminal result and lets the batch drain/reset its retained state if recording throws. No change for this theoretical callback failure.
  2. Already documented: website/docs/guides/telemetry.md says “for each actual native send call” and explicitly says a homogeneous Kafka batch records one duration for ProduceAllAsync, whereas tombstones record individual native completions. This matches Record client operation durations for Kafka and Service Bus sends #296's native-operation boundary.
  3. Non-blocking import-order nit: cosmetic; no push needed.

Claude's CLEAR receipt and Codex's completed, finding-free summary both name this exact head. REST reviews, inline comments and GraphQL review threads are empty; all conversation comments were checked. There are three Claude review rounds and one force-push, below the rework limits.

Before promotion, reverified the retained SHA-256 inventories: 550 files for this head and 933 historical files for 9bf8b14b320247d5a98de26d1556cda84aaea442, with no missing, altered or additional inventory entries. Locations remain C:/git/Relayer-evidence/pr-301/<full-SHA>/; original binary/report comparisons are recorded in the archive index and prior archival report. The original worktree is gone. This verifies retained evidence, not a new test or benchmark run. Historical measurements remain tied to their measured head. Retention lasts while the PR is open; cleanup may remove archives after closure.

The old wait on run 41511589444 ended successfully. No unresolved prerequisite or superseding PR was identified; #301 delivers and already closes #296. Proceeding through the protected promotion/auto-merge script on the approved head.

@thomhurst
thomhurst marked this pull request as ready for review November 2, 2026 19:53
@thomhurst
thomhurst enabled auto-merge (squash) November 2, 2026 19:53
@thomhurst

Copy link
Copy Markdown
Owner Author

The protected Enable-AutoMerge.ps1 -Pr 301 -MarkReady promotion succeeded on reviewed head d092a17f1eb6eef3c4626f73eddfea4f7d5c4d60; auto-merge is armed. Fresh ready CI is run 41514146110, with advisory performance in run 41514146225. GitHub must wait for required CI Passed before merging. No push or new review cycle was needed for these dispositions. Releasing the PR lock for the driver to revisit after CI completes.

@thomhurst
thomhurst merged commit 991fee8 into main Nov 2, 2026
18 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

performance Run the advisory benchmark regression gate on this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Record client operation durations for Kafka and Service Bus sends

1 participant