Skip to content

fix: retain concurrent receive continuations per context - #216

Merged
thomhurst merged 1 commit into
mainfrom
issue-203-async-receive
Nov 2, 2026
Merged

thomhurst merged 1 commit into
mainfrom
issue-203-async-receive

Conversation

@thomhurst

@thomhurst thomhurst commented Nov 2, 2026 •

Copy link
Copy Markdown
Owner

Concurrent receives allocate Relayer-owned async state-machine boxes when runtime caches miss. Keep continuation storage with each rented context and native receive state instead. Preserve execution context, fresh DI scopes, asynchronous disposal, failure handling and durable settlement order. Reserve native continuation storage until its ValueTask is consumed, clearing native references before completion.

Add a shared eight-handler cross-thread allocation fixture, MemoryDiagnoser coverage, execution-context/lifetime/cancellation regressions, Windows Native AOT coverage and matching receive/performance documentation. Batch dispatch and executable retry policies retain their existing implementations.

Closes #203

Validation

Performance evidence

Local diagnostic bracket: pinned main cf89c35 plus the identical attribution harness (a3ffe6d), candidate c54d4ca, then the same baseline again. SDK 10.0.403, runtime 10.0.14, BenchmarkDotNet 0.15.8, Windows x64. Sampling was fixed before this bracket at 15 measured iterations, 5 warmups and 1 launch; it is not the default adaptive job. Harness, project, SDK and package input hashes match. No gate threshold or CI workflow was changed.

Values below are baseline / candidate / baseline repeat. Times are ns/operation; allocation columns are inclusive bytes/operation. Concurrent cases normalize eight deliveries per invocation.

Case Time (ns) Allocated (B)
Concurrent direct scopes 761 / 837 / 1,082 128 / 128 / 128
Concurrent direct consumer 1,148 / 1,498 / 1,147 266 / 128 / 266
Concurrent native receive 1,399 / 2,061 / 1,606 502 / 128 / 501
Hosted synchronous round trip 3,319 / 3,350 / 2,764 536 / 536 / 536
Hosted concurrent round trip 1,949 / 1,933 / 1,844 818 / 691 / 820
Synchronous receive, text headers 163.5 / 166.7 / 158.2 128 / 128 / 128
Synchronous receive, UTF-8 headers 171.1 / 165.5 / 164.3 128 / 128 / 128
Build 100 handlers 24,040 / 22,630 / 32,100 131,224 / 141,720 / 127,448

Five timing rows are inconclusive under the existing confidence-bound rule, including the unfavorable dedicated-worker means. No row exceeds the 5% threshold against both baseline confidence bounds. The wide overlapping intervals and drift do not establish preserved throughput or latency, and none of these fixtures establishes the real-broker raw-client budget. Startup remains below 50 ms; startup allocation totals are informational.

A separately retained CPU probe uses 1.5 seconds of warmup per mode, fixed process affinity 0xF and 1.6 million measured messages per mode in baseline/candidate/baseline order. Receive CPU time is 1,123 / 596 / 771 ns/message, with inclusive allocations 498.736 / 128 / 493.357 B/message. Direct-scope CPU control is 547 / 264 / 313 ns/message, exposing substantial process/scheduler variation; these are diagnostic observations, not proof of a CPU budget. Earlier fixed-warmup explorations, including unfavorable results, remain archived. Their early candidate probe binaries were overwritten; the final controlled bracket has separately captured and verified binaries for all three executions.

Per-message cost: instance-owned continuation transitions and cached callbacks, with 0 B incremental composition allocation in the isolated concurrent fixture. Fresh DI scopes remain in every reported total; this does not claim zero total receive allocations.

The unfavorable historical #207 comparison remains retained: inclusive concurrent allocations 820 / 825 / 801 B/message. That earlier comparison did not meet the allocation rule and is not retroactively described as passing.

Retained evidence

C:/git/Relayer-evidence/pr-216/c54d4cadee8246891c52833c427cf6eaa96c977b/ contains raw reports/logs, the comparison with confidence intervals, probe sources, source snapshots, final loaded binaries, AOT output, TUnit reports and the independent historical attribution archive. inventory.json verifies 4,248 original/archive file pairs by length and SHA-256; its SHA-256 is EA9DCCB4A1595A216D3B40AB04FA2FC2D65A1CCDE3E07580520EAB867AF55685. Both originals and copies were rechecked after copying. Earlier exploratory records are preserved with their stated limitations; current final validation is the rebased run above.

@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: baf54106-695e-4855-b662-61e76a889926
  • 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-02T13:11:40.673611Z c54d4ca 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. Bravo.

Reviewed commit: c54d4cadee

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

I read CoreOperation against the ProcessCoreAsync code it replaces and found no blocking issues.

Checked and found correct

  • Failure and cancellation: a handler failure runs the failure delegate, then disposes the scope, then rethrows. A cancellation-triggered OperationCanceledException skips logging and failure handling, as before.
  • Late failures: an exception from the failure delegate, whether thrown synchronously or after an await, goes to _error. It is rethrown after the scope is disposed, like the old finally.
  • Order of operations: telemetry, activity disposal and EndProcessing run in the old nested-finally order. Finish runs them exactly once.
  • Suspension race: _suspended and _completion.Reset() are set before UnsafeOnCompleted registers the continuation. A continuation that runs inline, or on another thread before Start returns, is safe. The ValueTask version is read after builder.Start.
  • Context reuse: the context is returned to the pool only when the consumer calls Dispose() after awaiting. Dispose() throws if processing is still in flight. Clearing the per-run fields in Finish therefore cannot race with a second Start.
  • Execution context: it is captured at each suspension and restored with ExecutionContext.Run, so Activity and AsyncLocal flow matches the async method.
  • Per-message cost: the allocation is amortized by one CoreOperation and one cached Action per pooled context. Per-message work is one extra stage switch, with no LINQ, boxing or closures.
  • Scope: the benchmark, the shared fixture, the regression and execution-context tests, the AOT smoke test and the design.md note match the repo rules. The PR body does not commit benchmark output.

Non-blocking observations

  • The hand-rolled state machine (Runner, the Stage enum, goto case) is easy to get wrong later. Keep the failure-ordering tests as the safety net. A short comment listing the invariants would help future editors: the stage must be set before each call that can throw, and Finish must be the single exit.
  • ManualResetValueTaskSourceCore runs the consumer's continuation inline inside SetResult, which is the last statement of Finish. That is fine today. If a statement is ever added after it, the inline continuation could re-enter this CoreOperation.

@thomhurst

thomhurst commented Nov 2, 2026 •

Copy link
Copy Markdown
Owner Author

Both required reviewers now approve c54d4ca: Codex's head-bound summary is completed with no findings, and Claude's #216 (comment) ends CLEAR. All review surfaces have been read; there are no review threads or blocking findings.

Claude's observations are non-blocking:

  • The optional invariant-comment suggestion is declined as a standalone source-only push under the lifecycle's non-blocking feedback policy. The failure-ordering, execution-context and lifetime regressions remain the safety net.
  • The inline-completion warning is acknowledged. Completion publication remains the operation's last access; no code change is needed.

Implementation, local validation and the evidence archive are complete. The PR body records all timing/CPU rows, including inconclusive and unfavorable observations, and the independently retained #154 failure.

The successful manual Claude retry did not replace the original failed PR-associated receipt check. That check still gates promotion. Its failed job was rerun once, preserving the PR association, to recover review delivery; it is not a code-finding or test retry for green. #220 records this lifecycle gap. The PR remains draft until that original check is passing; no approval or passing check is manufactured.

@github-actions

github-actions Bot commented Nov 2, 2026

Copy link
Copy Markdown

Review of #216

I compared ConsumePipeline.CoreOperation and ReceivePipeline.State against the async methods they replace, stage by stage. I found nothing that should block merge.

Checked and sound

  • Failure paths: a handler failure runs the failure delegate. A cancellation or an exception from the failure delegate is stored, the scope is still disposed, and the error is rethrown after disposal. This matches the old try/finally behavior. A synchronous or asynchronous DisposeAsync fault goes through Finish, as before.
  • Ordering: settlement happens only after scope disposal, and EndProcessing runs in Finish. context.Dispose() happens in State.Cleanup, which runs after the inner ValueTask has been consumed through GetResult. The context can't be rented again while the CoreOperation source is still unconsumed.
  • Races: _asynchronous and _suspended are set before UnsafeOnCompleted. Start reads only those flags and the version after builder.Start. The consumer doesn't hold the ValueTask yet, so a continuation finishing on another thread can't corrupt Start. The State is returned to the pool only in GetResult (or on the synchronous path), as the PR describes.
  • ExecutionContext: it is captured at suspension and restored with ExecutionContext.Run. The synchronous path runs under AsyncTaskMethodBuilder.Start, which restores the caller's context.
  • Tests and docs: there are regression tests for execution context, lifetime and cancellation, a cross-thread allocation fixture, a MemoryDiagnoser benchmark and an AOT smoke test. docs/design.md and the site pages are updated.

Non-blocking notes

  • The hand-rolled Runner : IAsyncStateMachine with SetStateMachine => throw depends on AsyncTaskMethodBuilder.Start never boxing the runner. That holds today because the runner never awaits through the builder. A short comment saying so would stop a future edit from adding an await and hitting NotSupportedException.
  • GetResult assumes a single consumption of the ValueTask, which is standard. A Debug.Assert on _owner being non-null would make misuse fail loudly.
  • Per-message cost: ExecutionContext.Capture at each suspension. It allocates only when AsyncLocals are mutated, and the PR's allocation fixture covers the steady state. No benchmark is needed beyond what is already included.

@thomhurst

Copy link
Copy Markdown
Owner Author

Claude's PR-associated receipt run 41446807882/2 now succeeds and its current-head verdict is CLEAR: #216 (comment). Codex's completed, no-findings verdict remains bound to c54d4ca. All reviews, inline comments, conversation comments and review threads were rechecked; no blocking finding or unresolved thread remains.

Disposition of the latest Claude review's non-blocking notes:

  • Decline the optional Runner comment as a standalone source-only push. Both runners call AsyncTaskMethodBuilder.Start without using the builder's await methods; SetStateMachine is unreachable in this implementation.
  • Decline the optional Debug.Assert as a standalone source-only push. ReceivePipeline.State.GetResult retains its owner until the single permitted ValueTask consumption, then clears the owner and returns the state. Multiple consumption is outside the ValueTask contract.
  • The existing benchmark and allocation regressions already cover the reported per-message ExecutionContext work; no additional benchmark is requested.

Before promotion, all 4,248 archived files were rechecked by length and SHA-256 against the original archive inventory. All 1,072 surviving originals also match. The other 3,176 originals lived in removed worktrees; their independently archived files remain intact and match the hashes recorded when both originals and copies were verified. No retained evidence was lost or regenerated. Inventory SHA-256 remains EA9DCCB4A1595A216D3B40AB04FA2FC2D65A1CCDE3E07580520EAB867AF55685. Verification record: C:/git/Relayer-evidence/pr-216/promotion-evidence-verification.json. Archive location remains C:/git/Relayer-evidence/pr-216/c54d4cadee8246891c52833c427cf6eaa96c977b/.

@thomhurst
thomhurst marked this pull request as ready for review November 2, 2026 13:10
@thomhurst
thomhurst enabled auto-merge (squash) November 2, 2026 13:10
@thomhurst
thomhurst merged commit 7a1277f into main Nov 2, 2026
20 of 21 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.

Remove pooled async cache-miss allocations from concurrent core receive

1 participant