Skip to content

fix: count sends at native admission boundaries - #308

Merged
thomhurst merged 1 commit into
mainfrom
issue-302-native-send-count
Nov 2, 2026
Merged

thomhurst merged 1 commit into
mainfrom
issue-302-native-send-count

Conversation

@thomhurst

@thomhurst thomhurst commented Nov 2, 2026 •

Copy link
Copy Markdown
Owner

Count messaging.client.sent.messages immediately before native sends, after validation and preparation. Failed native calls count; rejected calls and unattempted Service Bus split tails do not. Outbox enqueue stays excluded, and dispatch retries count at each native attempt. Custom adapters call SendTracing.RecordNativeSend(count) at their native boundary.

Build on Dekaf 1.25.0 ProduceAsync/topic ProduceAsync/ProduceAllAsync, Azure.Messaging.ServiceBus 7.21.0 CreateMessageBatchAsync/TryAddMessage/SendMessageAsync/SendMessagesAsync, and Relayer's endpoint recorder, pools, existing grouping and native-duration timers. Native source was inspected at the pinned versions during implementation. No native batching, retry, ordering or acknowledgement behavior is replaced or duplicated; no decision exception is needed.

Update Kafka, Service Bus and in-memory sends, the telemetry guide (including custom-adapter migration), listener tests and metrics-enabled benchmarks. Rebase onto b57353c (#310), preserving its retained cross-thread send continuations, native send duration timing, Kafka's synchronous admission/drain behavior, the default JSON benchmarks, both metrics callbacks and shared DI instrumentation. Resolve duplicate setup/disposal introduced by overlapping changes. The Service Bus emulator test now checks counts and durations together.

Per-message cost: move the existing counter to native admission, 0 B from recording. In-memory sends add an endpoint lookup; Kafka singles reuse the validated endpoint for both counter and timer, ordinary batches reuse the duration endpoint lookup, and tombstone batches add one endpoint lookup per homogeneous batch. Service Bus records per admitted batch. The performance label enables the advisory gate; no throughput-budget claim is made.

Validation on 4349c1e6d6c8d2fb3da359a41737eae1fc82e7ad: Release solution build (0 warnings/errors), 63 core/send/duration/allocation/emulator tests, all 137 tracing tests (including retained cross-thread continuations), 21 real Kafka send/duration/conformance tests, 18 PostgreSQL outbox telemetry tests, npm ci and documentation production build pass. The earlier head's 28 BenchmarkDotNet Dry smoke cases remain execution checks only; they were not rerun for this conflict resolution. The same 22 low/moderate documentation dependency audit findings remain tracked in #101; no dependency manifests changed.

Evidence for 4349c1e6d6c8d2fb3da359a41737eae1fc82e7ad: C:/git/Relayer-evidence/pr-308/4349c1e6d6c8d2fb3da359a41737eae1fc82e7ad/continuation-validation/ contains logs, reports, loaded test binaries, the exact source snapshot and rebase range-diff. All 819 inventoried files were SHA-256 verified, with copies checked against their originals. Earlier validation remains in the SHA-specific archives described in the PR history; those results are not measurements of this rebased head. Local evidence is retained while the PR is open and may be removed after closure.

Closes #302

@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: 3520a618-0cd1-462e-aa0b-c6fb4a8a7069
  • 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

@github-actions

github-actions Bot commented Nov 2, 2026

Copy link
Copy Markdown

Review of #308: count sends at native admission boundaries

I read the Kafka, Service Bus and in-memory changes in pr-head/ against AGENTS.md and found no blocking problems.

What I checked

  • Kafka single send: RecordNativeSend() comes after Validate and Prepare, directly before ProduceAsync. Cancelled and preparation-failed calls count zero, and a call that fails natively still counts once.
  • Kafka batches: the non-tombstone path counts messages.Length once, right before ProduceAllAsync. The tombstone path counts per message as each ProduceAsync is issued. This matches "counts what was actually handed to the native client", and a failure partway through the loop leaves the unattempted tail uncounted.
  • Service Bus splits: admitted.Count is recorded after the batch is filled and before SendMessagesAsync. The count is at least 1 there, because the first iteration either adds a message or throws. Oversize, create-batch and later-preparation failures never reach the count, and unattempted splits and mixed-destination groups are excluded.
  • In-memory: the count sits after ValidateSend, right before EnqueueAsync.
  • API: SendTracing.RecordNativeSend(long count = 1) is a simple public hook for custom adapters. Removing the count from SendAsync/SendBatchAsync avoids double counting.
  • Tests: they cover the boundaries well: pre-native failures, each split reason, mixed destinations, partial in-memory batches, Kafka against a real broker, the Service Bus emulator, and a zero-allocation check with the listener on and off.
  • Docs and benchmarks: the telemetry guide is updated and the benchmarks gain a metrics-enabled variant.

Non-blocking notes

  1. The PR description has no per-message cost line, which AGENTS.md asks for when a benchmark is not the justification. The change adds one dictionary-backed GetSendTracing/Endpoint lookup per message in the in-memory single-send path, plus a counter add. The 0 B check in Native_counter_adds_zero_allocations_after_warmup covers the counter but not that lookup. Consider resolving the SendTracing once per call and passing it down, as the Kafka single-send path already does through Validate.
  2. website/docs/guides/telemetry.md says Kafka's ProduceAllAsync "counts its supplied batch once". Batches containing tombstones go through per-message ProduceAsync, and each is counted individually. A short qualifier would make the doc exact.
  3. Because SendTracing.SendAsync no longer counts, any external ITransportSendTracing implementation silently stops emitting messaging.client.sent.messages until it calls RecordNativeSend. The telemetry guide does document the migration. Consider also adding a release note, since this is a silent behavior change for custom adapters.
  4. Add the performance label, since the change touches the per-message send path.

@thomhurst

Copy link
Copy Markdown
Owner Author

Disposition of Claude's review of 51d3810, which reported no blocking findings:

  1. Non-blocking performance suggestion: added the exact per-message cost and benchmark limitations to the PR description. Keep endpoint lookup refactoring out of this accounting fix; Kafka batches and in-memory sends add an endpoint lookup, and counter recording allocates 0 B. Metrics-enabled benchmarks and the performance label cover the changed paths.
  2. Documentation wording fixed in 7892b459d031aab02d6f23030678c14b7b87143b: Kafka batches containing tombstones count each invoked ProduceAsync; other batches count messages supplied to ProduceAllAsync.
  3. Non-blocking release-note suggestion: the telemetry guide already documents the custom-adapter migration to RecordNativeSend. Keep that guidance with the API documentation, without introducing a separate release-note mechanism for this fix.
  4. The performance label is present.

Rebased onto 34f00f7 and preserved both the default JSON benchmark setup/cleanup and metrics cases. Share instrumentation with the JSON DI path so its metrics parameter takes effect. Release build, 66 focused tests (including Kafka, Service Bus emulator and PostgreSQL), and docs installation/build pass. The PR description names the SHA-specific, hash-verified evidence archive. Remote head is 7892b459d031aab02d6f23030678c14b7b87143b; the PR stays draft for fresh reviews.

@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 src/ changes in full and skimmed the tests, benchmarks and docs.

What the change does: RecordSent moves out of SendTracing.SendAsync and SendBatchAsync. It now runs as RecordNativeSend(count) at each adapter's native call, after validation and preparation.

Checked and correct:

  • Kafka single send: counted after Prepare, once per call. Validate now returns the tracing instance, so there is no second dictionary lookup.
  • Kafka batch: counted once with messages.Length before ProduceAllAsync. In the tombstone path it is counted per message just before each produce, so an unattempted tail is not counted.
  • Kafka mixed batch: falls through SendAsync, so each message is counted once and nothing is double counted.
  • Service Bus single send: counted after Prepare.
  • Service Bus batch: counted with admitted.Count right before SendMessagesAsync. Messages rejected by TryAddMessage or left pending for the next native batch are not counted.
  • Service Bus mixed destinations: this splits into per-destination batches, so there is no double count.
  • In-memory: counted after ValidateSend. Batches go through SendCoreAsync per message, so each message is counted once.
  • Other implementers: the only ITransportSendTracing implementers in src/ are in-memory, Kafka, Service Bus and the Testing harness wrapper, which delegates. Moving the count out of SendTracing therefore drops no counts elsewhere.
  • Per-message cost: a null check plus one Counter.Add, 0 B, the same work as before at a different place. The metrics-enabled benchmarks were extended, which is more than the rules require.
  • Public API: RecordNativeSend is a small, documented extension point for custom adapters.
  • Tests and docs: the counter tests cover failed native calls, rejected calls and split tails, and the telemetry guide documents the boundary.

I found no correctness, security or performance issues.

@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-02T21:09:54.334108Z 4349c1e 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. 🚀

Reviewed commit: 7892b459d0

ℹ️ 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 approve current head 7892b459d031aab02d6f23030678c14b7b87143b: Claude's receipt-verified run 41513392082/1 is successful and CLEAR, and Codex's completed summary reports no findings for the same full SHA. All review surfaces were checked; there are no unresolved threads or outstanding findings.

Before promotion, rechecked both evidence inventories and every SHA-256 hash: 661 files in C:/git/Relayer-evidence/pr-308/7892b459d031aab02d6f23030678c14b7b87143b/rebase-validation/, and 132 files in the earlier head's implementation-validation/ archive. All 27 available original files also match. Removed worktrees' originals are unavailable; the retained archives and manifests remain intact. Verification is recorded in C:/git/Relayer-evidence/pr-308/promotion-evidence-verification.json. These local archives are retained while the PR remains open and may be removed after closure.

Promoting through scripts/Enable-AutoMerge.ps1 -Pr 308 -MarkReady; required ready CI must pass before merge.

@thomhurst
thomhurst marked this pull request as ready for review November 2, 2026 19:55
@thomhurst
thomhurst enabled auto-merge (squash) November 2, 2026 19:56
@thomhurst
thomhurst marked this pull request as draft November 2, 2026 20:22
auto-merge was automatically disabled November 2, 2026 20:22

Pull request was converted to draft

@thomhurst
thomhurst force-pushed the issue-302-native-send-count branch from 7892b45 to 51a6c7f Compare November 2, 2026 20:26
@thomhurst

Copy link
Copy Markdown
Owner Author

Run 41514498885 completed successfully, so the previous wait has ended. The PR subsequently conflicted with native-duration changes merged in #301. Rebased onto 991fee8 and pushed 51a6c7fc875b670a3ec83c2796922dd4931928f5.

The resolution preserves native-duration timing and Kafka's synchronous admission/drain behavior while adding counters immediately before native attempts. It preserves both benchmark metrics callbacks and the JSON DI instrumentation, removes overlapping duplicate setup/disposal, and keeps Service Bus emulator assertions for both counts and durations. Simplification review found no further changes needed.

Release build, 102 focused tests (including real Kafka, Service Bus emulator and PostgreSQL), documentation installation/build and 28 BenchmarkDotNet Dry cases pass. The PR body identifies the hash-verified archive, exact validation source and final whitespace-only cleanup. The previous head's approvals do not carry over: restored draft before pushing and requesting fresh review. No merge or protection bypass was attempted.

@thomhurst

Copy link
Copy Markdown
Owner Author

@codex review

@github-actions

github-actions Bot commented Nov 2, 2026

Copy link
Copy Markdown

Review of #308

I traced the counter move from SendTracing.SendAsync/SendBatchAsync to the native-send boundary in each adapter. I found nothing that should block merge.

Correctness

  • Kafka: Validate now returns the endpoint, so single sends count once and reuse the same lookup for the duration timer. Counting happens after Prepare and before ProduceAsync. Ordinary batches count messages.Length once per ProduceAllAsync, and the tombstone path counts per ProduceAsync.
  • Service Bus: single sends count after Prepare. Batches count admitted.Count per split just before the native send. A split that is never attempted is not counted, and a failed split is.
  • In-memory: counting happens after ValidateSend and before enqueue. Every path goes through SendCoreAsync, including the tracing path and the mixed-destination batch path. Messages are therefore not double-counted, and cancelled or failed preparation counts nothing.
  • Custom adapters have to call RecordNativeSend now. The telemetry guide documents the migration, and the benchmark sink and the Postgres FailingTransport test double are updated.

Tests
Coverage is good. It includes pre-native failures, split boundaries with and without failure, mixed destinations, a Kafka broker test, an emulator assertion, and a zero-allocation check with the listener on and off.

Performance and conventions
The PR states the per-message cost. RecordNativeSend is a single Add with precomputed tags, so it allocates 0 B. The change reuses the native batching and the existing grouping, and it adds no parallel implementation. The docs are updated in the same PR.

Minor, non-blocking
In InMemoryTransport.SendCoreAsync the endpoint's SendTracing is looked up again per message after Endpoint(...). If that dictionary lookup ever shows up in profiles, it could be hoisted into the endpoint object.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

Reviewed commit: 51a6c7fc87

ℹ️ 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
thomhurst force-pushed the issue-302-native-send-count branch from 51a6c7f to 4349c1e Compare November 2, 2026 20:32
@thomhurst

Copy link
Copy Markdown
Owner Author

Run 41514498885 passed; that wait no longer blocks this PR. Main subsequently merged #310, which caused a new conflict in SendTracing.SendBatchAsync. Rebased onto b57353c and pushed 4349c1e6d6c8d2fb3da359a41737eae1fc82e7ad.

The resolution preserves #310's retained continuation and execution-context implementation exactly, except removing the tracing-level counter as intended by #302. SendBatchAsync still enters Start; each adapter records its native attempts. The range-diff confirms every other PR change is unchanged. Code-simplifier review found no further changes needed.

Disposition of Claude's latest review: the endpoint lookup suggestion is non-blocking and remains outside this accounting fix. The PR already states its endpoint lookup cost and records 0 B for counter recording; keep the existing benchmark coverage without refactoring endpoint ownership here.

Release build, 239 tests (including all tracing tests, real Kafka, Service Bus emulator and PostgreSQL), documentation installation/build pass. The PR body names the exact-head archive; all 819 inventory hashes and originals were verified before citation. Previous head approvals do not carry over. The PR stays draft for fresh Claude and Codex reviews.

@thomhurst

Copy link
Copy Markdown
Owner Author

@codex review

@github-actions

github-actions Bot commented Nov 2, 2026

Copy link
Copy Markdown

Review of #308: count sends at native admission boundaries

I read the full diff and checked the Kafka batch path in pr-head. I found no blocking issues, and I did not run the build or tests.

Correctness

  • RecordNativeSend is called after validation, Prepare and batch assembly in every adapter, and immediately before the native call. That matches the documented contract.
  • Kafka batches without tombstones count messages.Length once per ProduceAllAsync call.
  • Kafka batches with tombstones count once per ProduceAsync inside the admission loop. Messages never reached after a synchronous admission failure are not counted.
  • Service Bus counts admitted.Count per split after the batch is built, so unattempted tails and preparation failures count zero.
  • Removing the counts from SendAsync and SendBatchAsync in SendTracing avoids double counting. The doc and the RecordNativeSend remarks both say custom adapters must now call it. The telemetry guide covers the migration, which is a behaviour change for out-of-tree adapters.

Performance and AGENTS.md

  • The recording path is a null-conditional call plus an existing RecordSent. The new allocation test, Native_counter_adds_zero_allocations_after_warmup, confirms 0 B.
  • The PR states the per-message cost, reuses the existing endpoint lookups and adds no reflection or LINQ in src/.
  • The PR description names the native features it builds on and says no decision exception is needed.

Tests and docs

  • Coverage is broad: pre-native failures, size/session/partition/transaction splits, mixed destinations, partial in-memory batches, the Kafka tombstone path, the emulator counts and the allocation check.
  • The telemetry guide is updated in the same PR.

Non-blocking nit

  • SendNullBatchAsync calls Endpoint(...) once per batch, and ProduceAsync looks the endpoint up again per message for the timer. You could pass the resolved SendTracing into ProduceAsync to drop the per-message lookup. This is not required.

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 4349c1e6d6

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

The earlier wait ended: run 41514498885 succeeded. Current head is 4349c1e and is mergeable. Claude's PR-associated run 41520121060/1 succeeded with CLEAR for this head; Codex's completed summary names the same full SHA and reports no findings. All review bodies, inline comments, conversation comments and review threads were checked; there are no unresolved threads or blocking findings.

Disposition of Claude's current review: passing the resolved endpoint through the Kafka tombstone helper is a non-blocking optimization. Keep it outside this accounting fix: the PR already records the endpoint lookup cost and includes metrics-enabled benchmarks. No code push is needed for this suggestion.

Reverified all four retained evidence inventories and SHA-256 hashes: 819 files for the current head, plus 764, 132 and 661 files from earlier heads. All 49 available original files also match; originals in removed worktrees are unavailable, while the archived binaries, sources and reports remain intact. Verification is recorded at C:/git/Relayer-evidence/pr-308/promotion-20261102-2106-verification.json. The current-head archive remains C:/git/Relayer-evidence/pr-308/4349c1e6d6c8d2fb3da359a41737eae1fc82e7ad/continuation-validation/. These local archives remain while the PR is open and may be removed after closure. No validation was rerun or attributed to a different head.

No prerequisite, superseding PR, unfinished parent, stale scope or reversible design decision blocks promotion. #308 already closes #302. Promoting and arming through scripts/Enable-AutoMerge.ps1 -Pr 308 -MarkReady; required ready CI must pass before merge.

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

Copy link
Copy Markdown
Owner Author

scripts/Enable-AutoMerge.ps1 -Pr 308 -MarkReady passed and armed auto-merge for approved head 4349c1e. Required ready CI is now running: https://github.com/thomhurst/Relayer/actions/runs/41525641258. No check was bypassed. This single unit releases pr-308 without waiting for CI completion.

@thomhurst
thomhurst merged commit ecae503 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.

Count broker sends only after native admission begins

1 participant