Skip to content

Add key-ordered Kafka scheduling and bounded rebalance drains - #221

Closed
thomhurst wants to merge 3 commits into
mainfrom
issue-182-kafka-scheduler
Closed

thomhurst wants to merge 3 commits into
mainfrom
issue-182-kafka-scheduler

Conversation

@thomhurst

@thomhurst thomhurst commented Nov 2, 2026 •

Copy link
Copy Markdown
Owner

Current scope and external gate

This draft tracks #22, which consolidates former child #182. It is incomplete and must not be promoted in its current form. The branch's core-scheduler runtime is rejected; replace it with Dekaf's RunPartitionedAsync while preserving reusable tests and Relayer pipeline integration.

The original external release gate is satisfied: Dekaf 1.26.0 and merged #339 supply consumer-wide limits, oldest outstanding health and runtime-aware replay. The separate remaining native gap is Dekaf#4100: observing runtime-managed commits with duration, errors and actual completed-record count. OnCommit runs only after success; decorating the consumer hides the internal rebalance event source used by RunPartitionedAsync. See the maintained disposition comment below for source evidence.

on-hold now means only that commit-observation API or a demonstrated supported workaround is needed to preserve design §8.2 while retaining native runtime ownership. Remove it once that condition is met, then implement the adapter and validate the new head. #239/#241 and #240 are merged. The duplicated runtime remains rejected. Historical validation below applies only to its explicitly named historical heads.


Kafka consumers now use the core partition scheduler for bounded concurrency and same-key ordering, instead of rejecting Concurrency values above one. The adapter retains native byte arrays and materializes Dekaf header snapshots before their borrowed fetch windows expire, then commits only contiguous durable next-offset checkpoints.

Closes #22

Changes

  • Add typed partition concurrency, buffer limits and drain timeout options; size receive pools for total concurrency and advertise implemented pause/replay capabilities.
  • Serialize admission, native operations and rebalance commands on one pump. Native callback execution scopes survive the handoff, preserving configured listeners and allowing safe revoke commits. Retained partitions continue; revoked/lost epochs fence queued work, stale completions and pending commits.
  • Batch native commits across partitions with one CLIENT settle span per request, including message counts. Track the oldest outstanding delivery for consumer health.
  • Preserve graceful transport restart for conformance; aborted receivers restart through a fresh host/native consumer. Fix iterator cleanup so a pending poll cannot mask the original receive failure.
  • Update Kafka, scheduler, roadmap and status documentation. D13 now names Dekaf's native KIP-848 sticky uniform assignor, Kafka's migration equivalent of classic CooperativeStickyAssignor.

Validation

  • Release solution build: zero warnings/errors.
  • Kafka suite: 51 passed, including real-broker rebalance under load, paused revoke, drain timeout, worker crash/restart, aborted-transaction offset gaps/leader epochs and all five conformance scenarios.
  • Core suite: 625 passed, including completion notifications, oldest outstanding health and allocation checks.
  • Windows x64 Native AOT publish and smoke execution passed with trimming warnings treated as errors.
  • npm ci and production documentation build passed. Existing dependency audit findings remain tracked in Address documentation dependency audit vulnerabilities #101.
  • Kafka receive MemoryDiagnoser: all eight ShortRun cases completed (raw Dekaf versus production scheduler, concurrency 1/4, health off/on). ShortRun mean ratios were 0.99–1.01 on the final head; confidence intervals are wide and these local numbers do not establish the 5% budget. Inclusive allocations contain native header snapshots and JSON work; no zero-allocation end-to-end claim is made. A focused warm snapshot/key-comparison check allocates 0 B from Relayer.

Performance impact: adds bounded scheduler bookkeeping, native header snapshot capture and cached completion notification for asynchronous handlers; synchronous handlers stay on the pump. The performance label enables the advisory CI gate.

Validation evidence for 1079a11 is retained outside the removable worktree under C:/git/Relayer-evidence/pr-221/1079a116525710628bb2771d2bbe403ae6dc55d3/. It includes raw logs/reports, source inputs, benchmark/test assemblies and dependencies, broker configuration and the Native AOT executable. The generated BenchmarkDotNet runner is reproducible from these inputs; BenchmarkDotNet removed that generated runner during cleanup.

Review fix: replay shutdown

Commit aaadd04 fixes the Codex shutdown finding. When stop interrupts a replay drain, the consumer leaves that drain and enters its existing bounded shutdown path. Pending seeks cancel; active handlers receive cancellation at DrainTimeout, and late handlers remain retained safely until disposal.

A deterministic regression keeps one handler pending and supplies an explicit peer-completion wake after entering the accepted-work drain. It times out before the fix and passes afterward. The host-level seek test now requires shutdown to finish without releasing its blocked handler.

Validation for this fix: Release solution build passed with zero warnings/errors; all 52 Kafka tests passed, including real-broker scheduling and transport conformance; npm ci and the production documentation build passed. Existing npm audit findings remain tracked in #101. Core, AOT and benchmark results above belong to the preceding 1079a11 head and were not rerun for this shutdown-only fix.

Per-message cost of this fix: one stop check per replay-drain iteration, 0 B; no change to normal message admission or dispatch. No additional benchmark is required for this shutdown path.

Evidence is retained at C:/git/Relayer-evidence/pr-221/aaadd04c1e4e463909bb657f53e364da9fe18130/. The archive contains raw validation logs, the failing-before-fix regression log, test reports, the full Kafka test binary/dependency set, source inputs, and a SHA-256 inventory. All 218 copied files were checked against their originals; source.zip is also hashed.

Review clarification: admission performs one failure scan across assigned partitions after each record, O(assigned partitions) time and 0 B per message. This preserves immediate failure detection before the next admission; changing that timing or adding a scheduler failure flag is deferred as an optional optimization, with no performance trade-off introduced in this review cycle.

Archive revalidation before promotion: all 39 manifest entries for 1079a11 and all 219 entries for aaadd04 match their retained file lengths and SHA-256 hashes. The six surviving original shutdown-validation logs also match their archived copies. Prior worktrees have been released; the original archive-time comparisons recorded above remain the provenance for removed originals.

Current review fix and rebase: 3691828

Ready CI run 41454717372 passed, including build/test, documentation, package validation and Linux Native AOT. The later ready-event Codex review found a health-state defect, so the PR was converted back to draft before this push.

The worker now becomes active before batch processing, including entirely synchronous handlers, and stays active through the native commit. An already active worker preserves its age. A real-broker regression covers both initial states and native commit entry/completion with an injected clock; it fails before the fix. Kafka health documentation now describes this behavior and removes an outdated statement that parallel handling is planned.

Rebased cleanly onto origin/main 0c7ec42, including #216's concurrent receive continuation fix and #200's dependency patch. Range-diff confirms the existing Kafka changes were retained; only the AOT smoke insertion moved around main's new smoke code. No code simplification beyond this focused fix was needed.

Validation of this exact head:

  • Release solution build: zero warnings/errors.
  • Kafka suite: 55 passed, including both new health regression cases, real-broker rebalance/shutdown tests and all conformance cases.
  • Core suite: 632 passed.
  • npm ci and production documentation build passed. Audit reports 19 moderate and 3 low findings, matching the existing advisory dispositions in website/README.md from fix: patch documentation tooling dependencies #200; no high/critical findings.
  • git diff --check passed. Native AOT publish and benchmarks were not rerun locally for this head. Earlier AOT/benchmark results above retain their explicitly named historical heads.

Per-message cost of this health fix: one optional-health condition per native batch and one volatile read when enabled; the clock is read only when leaving idle/unavailable, 0 B. No new loop, copy, lock, await or allocation; no additional benchmark required for this constant-time health correction.

The advisory Performance run 41454717223 failed on ScopeAndHandlerResolution(ScopedHandler: False) throughput (-9.77%) and ConcurrentRoundTrip allocations (946/946 baseline versus 948 candidate B/op). It measured the previous aaadd04 head against 5e40e01. The affected call paths do not invoke Kafka or PartitionScheduler, but containing build inputs differ, so these results do not establish unchanged performance. Attribution and preserved raw reports are tracked in #237. No run was retried and no threshold was changed.

Evidence for this exact head is retained outside the removable worktree at C:/git/Relayer-evidence/pr-221/36918284655c958844efb958c825592887ad1edb/. All 450 entries were verified by length and SHA-256 against originals (source.zip is generated from git HEAD and separately hashed), then rechecked against inventory.json. It contains raw build/test/install/docs/audit logs, failing-before-fix diagnostics, test reports, complete Kafka/core test binaries and dependencies, and source inputs. Inventory SHA-256: 95F5FC34F1876E35183119F96C85F40F2A52A5581B71E15FD471E1A56DD134A6. Local retention lasts while this PR is open; cleanup removes it after closure. Performance evidence also has an independent copy under issue-237 so it survives this PR's closure.

Fresh head-bound Claude and Codex reviews are required before promotion. Auto-merge remains disarmed.

Current blocking runtime review

Head 5272301 is not approved for promotion. The maintainer requires #22 (consolidating former #182) to wrap Dekaf's RunPartitionedAsync and remove the duplicated runtime. #239 / merged #241 (fe1d7af) completed the independent policy prerequisite; #240's D22 clarification is merged. Those upstream gaps are resolved in released Dekaf 1.26.0, already pinned on main; the native adapter rework remains outstanding. Historical CI run 41454717372 passed on its historical head and does not approve this head. See the maintained blocker/disposition comment: #221 (comment). Advisory investigation #237 is complete through merged #243 (8a01bf0); its historical uncertainty remains recorded there and is not a promotion prerequisite.

Release check (2026-11-13): Dekaf 1.27.0 is now released, but its runtime commit calls still have no commit-observer boundary. Dekaf#4100 remains open without a response. The hold is the missing supported commit observation contract, not adoption of the current package pin. No new adapter or validation result is claimed.

@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

Draft PR not reviewed

Draft PRs are not automatically reviewed by default.

  • Trigger a manual review

To automatically review draft PRs, update your CodeRabbit configuration:

reviews:
  auto_review:
    drafts: true
  • 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 #221: key-ordered Kafka scheduling and bounded rebalance drains

I found no actionable issues. I read KafkaConsumer.cs in full and checked the PR's file list and description against AGENTS.md. I did not build or run the tests, and I did not read the full diff of every other file, including the PartitionScheduler changes and the tests.

What I checked

  • Single-owner pump. Admission, native operations, rebalance commands and commits all run on one pump. Handler continuations only call Signal, so the scheduler is never touched concurrently and there are no locks on the per-message path.
  • Rebalance fencing. Revoked and lost assignments are fenced by token, and ThrowFailures and FlushAsync skip partitions that are revoking or no longer assigned.
  • Commits. Commits use the contiguous Durable watermark. Revoke commits run inside the callback's captured ExecutionContext.
  • Receive-failure handling. The new cleanup waits for the outstanding MoveNextAsync before disposing the iterator, and swallows its exception so the original receive error still surfaces.
  • Conventions. All awaits in src/ use ConfigureAwait(false). There is no .Result or .Wait() on a task. The one Task.Run is at start-up, with execution-context flow suppressed. The .Result hits in KafkaDelivery are Dekaf's ConsumeResult property.
  • Docs. Docs, decisions and roadmap are updated in the same PR.

Non-blocking notes

  • The PR's own benchmark numbers (ratios 0.99–1.01 with wide confidence intervals) show no regression but do not demonstrate the 5% budget. The performance label and the advisory CI gate are the right place to confirm it.
  • KafkaDelivery.Snapshot copies headers on every message. The PR states this allocates and that no zero-allocation claim is made for it. That is fair, but consider a follow-up to pool or lazily materialise the header snapshot, since D18 targets 0 B from Relayer's own pipeline.

@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-02T14:15:54.094915Z 3691828 Manual request
ℹ️ 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.

@thomhurst

Copy link
Copy Markdown
Owner Author

Disposition of the Claude review on 1079a11:

  • Benchmark confidence: agreed. The PR explicitly treats ShortRun results as diagnostic and does not claim the 5% budget has passed. The advisory performance workflow remains enabled.
  • Header pooling/lazy materialization: non-blocking optional optimization; retain the native snapshot mechanism here under D1/D22. Dekaf already materializes header values lazily. Admission must materialize them before advancing the borrowed fetch window, since independent handlers can outlive that window. The snapshot arrays belong to the native client and are excluded by D18; Relayer reuses the original key/body arrays and adds no snapshot object. The focused warm snapshot/key-comparison allocation test passes at 0 B for caller-owned native headers. Replacing native snapshot ownership requires a separate measured design rather than a review-only refactor.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1079a11652

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

Comment thread src/Relayer.Kafka/KafkaConsumer.cs Resolved
@thomhurst

Copy link
Copy Markdown
Owner Author

@codex review

The shutdown finding from the previous review is fixed and dispositioned in aaadd04. Release build, all 52 Kafka tests, and the documentation build pass. The PR remains a draft for fresh head-bound reviews.

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: aaadd04c1e

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

Copy link
Copy Markdown
Owner Author

Resolved: run https://github.com/thomhurst/Relayer/actions/runs/41451920361 attempt 2 succeeded and posted a receipt-verified CLEAR verdict for aaadd04. Codex also completed its review of this head with no findings. The original review-delivery failure tracked in #220 no longer blocks this PR.

@github-actions

github-actions Bot commented Nov 2, 2026

Copy link
Copy Markdown

Review of #221 (Kafka partition scheduling, bounded rebalance drains)

I read KafkaConsumer.cs in full, checked the file list and PR description against AGENTS.md, and compared the result with the earlier Claude and Codex review threads. The earlier findings, including the shutdown one fixed in aaadd04, are dispositioned. I found no correctness or security problems that should block merge.

What looks sound:

  • One pump owns the scheduler, native operations and rebalance commands, and handler continuations only signal it. That keeps the design simple and the ordering reasoning local.
  • Commits go through contiguous durable checkpoints. Revoked and lost epochs fence queued work.
  • The iterator-cleanup fix keeps the original receive failure instead of masking it with the pending poll.
  • Docs, the roadmap and the AOT smoke test are updated in the same PR.

Non-blocking suggestion (per-message cost):

  • AdmitBatchAsync calls ThrowFailures() after every record. That loops over all of _source.Assignments and calls IsAssigned and GetFailure for each one. The cost is O(assigned partitions) per message, not O(1), which sits against the per-message-path rules in AGENTS.md. It stays at 0 B but grows with partition count.
  • A cheaper approach is a scheduler-level failure flag or counter, such as an Interlocked volatile int set when a partition faults. Check that per message and walk the assignments only when it is set. PumpAsync already runs ThrowFailures once per cycle, so the per-record call could also move to per-batch. Failures would then surface at most one batch later.
  • This is not a benchmark request. State the per-message cost in the PR description.

@thomhurst

Copy link
Copy Markdown
Owner Author

Disposition of the Claude review on aaadd04: the per-record assignment scan is an optional optimization, as the review states. Retain immediate failure detection before admitting the next record. Moving the scan to a batch boundary changes failure timing, and a scheduler failure flag needs separate measured design and validation; neither is required to fix a demonstrated correctness or regression defect here. No code push for this non-blocking suggestion. The PR description now explicitly states O(assigned partitions) time and 0 B per record for the scan.

Both required reviewers approve this head. The shutdown thread remains resolved with no newer reviewer reply. Archive inventories and SHA-256 hashes have been revalidated (39 and 219 entries), including comparisons against all six surviving original shutdown-validation logs.

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

thomhurst commented Nov 2, 2026 •

Copy link
Copy Markdown
Owner Author

Resolved: ready CI run https://github.com/thomhurst/Relayer/actions/runs/41454717372 passed on aaadd04. Its wait no longer blocks this PR.

A later ready-event Codex review found a receiver health-state defect. The PR is back in draft and 3691828 fixes it, with fresh Kafka/core/documentation validation and retained evidence. Both required reviewers must review the new head before promotion. Advisory performance findings from run 41454717223 are tracked in #237.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: aaadd04c1e

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

Comment thread src/Relayer.Kafka/KafkaConsumer.cs Resolved
@thomhurst

Copy link
Copy Markdown
Owner Author

@codex review

The blocking health finding from review 5737430086 is fixed and dispositioned in 3691828. The worker becomes active before synchronous handlers/native commits and preserves an already active worker's age. Both real-broker regression cases, all 55 Kafka tests and 632 core tests pass; Release build and documentation build pass. The PR is rebased onto current main and remains draft for fresh head-bound reviews. The advisory benchmark signal is tracked separately in #237, with its raw artifact preserved.

@thomhurst thomhurst left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This PR re-implements Dekaf's partitioned processing runtime

Relayer already references Dekaf 1.25.0, and that release ships RunPartitionedAsync (src/Dekaf/Consumer/PartitionedProcessing.cs, KeyOrderedPartitionDispatcher.cs). Most of what this PR adds is already there:

This PR Dekaf 1.25.0
ConcurrencyPerPartition + KafkaMessageBinding.KeysEqual (byte comparison, null keys in their own lane) Ordering = PartitionedProcessingOrder.Key, MaxConcurrentHandlersPerPartition; byte-array keys compare by content, null keys share a separate lane
MaxBufferedPerPartition + KafkaPartitionSource.Pause/Resume MaxBufferedRecordsPerPartition, BackpressureMode = PauseResume
DrainTimeout, bounded revoke drain, fencing StopPolicy = Drain, StopTimeout; thomhurst/Dekaf#3854 holds revocation until revoked lanes drain and commit; #3805 bounds stop cancellation callbacks
Contiguous watermark commits, flush on revoke and shutdown MarkProcessed tracking, CommitPolicy = CommitCompletedOnRevoke, CommitInterval
KafkaOwnership command queue, KafkaPumpSignal, assignment epochs, ~300 lines of pump logic in KafkaConsumer The runtime's own rebalance handling and lanes

This conflicts with:

  • D1 and D22, and AGENTS.md: "reuse features the native client already ships where they fit".
  • Issue #182 itself: "Reuse Dekaf native mechanisms and core scheduling; do not implement another scheduler inside the Kafka adapter."

The PR description does not mention RunPartitionedAsync or explain why it does not fit.

Root cause: #181 / D23

Core PartitionScheduler is a log-consumption scheduler, and Kafka is Relayer's only log transport. The core scheduler therefore duplicates Dekaf for its only user, and this PR is the glue that makes that work. D23 should be revisited: either remove the core scheduler, or keep it only for a future log transport whose native client has no equivalent.

Real gaps, filed in Dekaf

These are gaps to close in Dekaf, not reasons to build a second runtime in Relayer:

  • thomhurst/Dekaf#4054: consumer-wide limits for concurrent handlers and buffered records. Relayer's Concurrency and this PR's MaxBufferedDeliveries are totals, and Dekaf only limits per partition.
  • thomhurst/Dekaf#4055: oldest outstanding record time, for consumer health.
  • thomhurst/Dekaf#4056: seek and replay while RunPartitionedAsync is running, needed by KafkaReplay / SeekAsync.

Requested change

Do not merge in this form. Rework #182 so KafkaConsumer wraps RunPartitionedAsync with key ordering and maps Relayer options onto PartitionedProcessingOptions. Keep in Relayer only what is Relayer-specific: the receive pipeline call, the rule that settlement is durable (Complete/SettledByHandler) before MarkProcessed, the commit span, and health reporting. Block on, or work around, the three Dekaf issues above. Record the decision in docs/decisions.md (D22/D23).

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 3691828465

ℹ️ 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 #221 (Kafka partition scheduler)

I found no blocking issues. I read KafkaConsumer.cs and KafkaPartitionSource.cs in full and skimmed the file list. I did not run the build or tests, and I did not read the rest of the diff (ownership, hosted service, scheduler changes, tests) line by line.

Correctness

  • Commit in KafkaPartitionSource only runs from _scheduler.Pump() on the receive pump. Durable, Safe, Pending and Committed are therefore single-threaded, and the Committed = Durable assignment after the commit await in FlushAsync cannot overstate what was committed. This matches the comment on the class.
  • Rebalance callbacks go through the command queue, so revoke and lost handling cannot race commits. The revoke path flushes only the revoked partitions and removes them after the commit.
  • The iterator cleanup waits for the outstanding MoveNextAsync and swallows its error, so the original receive failure is preserved.

Performance

  • The per-message path in AdmitBatchAsync has no LINQ, no capturing lambdas and no reflection. It uses pooled async builders and static callbacks with explicit state. Please keep the PR description's one-line per-message cost statement, and add the performance label since the receive path changed.

Docs and tests

  • The site (Kafka, scheduler and completion pages), the roadmap, the status page, and D13 in the decisions record are all updated. Tests cover rebalance under load, drain timeout, worker crash and restart, and conformance, and the AOT smoke test is extended.

Non-blocking

  • HandleCommand and FlushAsync use ExecutionContext.Run per rebalance. That is fine because rebalances are not per-message, but a short comment saying so would stop it being flagged later.

thomhurst added a commit that referenced this pull request Nov 2, 2026
Remove the 'where they fit' escape hatch from the wrap-don't-replace rule,
add a 'Search before you build' rule, require PR descriptions to list the
native and Relayer features a change builds on, and add the search step to
the issue/PR loop. Prompted by PR #221 re-implementing Dekaf's
RunPartitionedAsync.
@thomhurst

thomhurst commented Nov 2, 2026 •

Copy link
Copy Markdown
Owner Author

The original three upstream gates are resolved by released Dekaf 1.26.0 and merged #339. The policy prerequisites #240/#241 are merged. This audit found a separate native integration gap, now filed as Dekaf#4100: RunPartitionedAsync has no supported observation boundary around runtime-managed commits.

Design §8.2 and #22 require one Relayer CLIENT settle span per native commit, outside process spans, with actual message count and duration/error reporting. Source evidence at the pinned release:

  • Runtime-owned commit has no observer.
  • OnCommit fires only after success; it cannot measure a pending/failed commit or supply a completed-record count across offset gaps.
  • CommitAsync and the coordinator start no commit activity. Dekaf's ActivitySource currently supplies send/process/poll instrumentation, so an ActivityListener cannot recover a missing commit boundary; native transport details also do not replace Relayer's spans under §8.2.
  • Wrapping IKafkaConsumer to intercept CommitAsync hides internal IConsumerRebalanceEventSource, which the runtime uses to drain and commit before revocation releases ownership. Such a decorator is unsafe. Building our own drain/commit tracker would repeat the rejected runtime.

Checked current upstream main a40d9a3dc456f1340de1df628730ae15b9039198 and release notes; no observer is present. Searched open/closed commit and tracing issues before filing #4100. The original key ordering, limits, health and replay APIs are available; they are not the current blocker.

Current gate is [upstream]: #4100, or demonstrated supported instrumentation that preserves the existing contract and native rebalance ownership. Both #22 and this PR carry on-hold only for that condition. Remove it when the contract-preserving native API/workaround is available. No internal CI/review wait is being parked. The native adapter, its chaos/conformance tests, benchmarks/AOT and docs remain implementation work; adding an unused adapter or shipping it without the specified commit spans would not be a complete independently shippable change.

Read all review bodies, conversation comments and resolved threads; neither resolved thread has a newer reviewer reply. The maintainer/Claude runtime findings remain blocking. The branch and useful tests are preserved unchanged at 5272301; an attempted rebase was aborted and the checkout restored. No source push or new validation is claimed, and historical results apply only to their named heads. Local source-audit inputs are retained under /Users/tom/git/Relayer-evidence/pr-221/ while this PR is open.

2026-11-13 triage: Release check (2026-11-13): Dekaf 1.27.0 is now released, but its runtime commit calls still have no commit-observer boundary. Dekaf#4100 remains open without a response. The hold is the missing supported commit observation contract, not adoption of the current package pin. No new adapter or validation result is claimed. Rechecked review bodies, inline comments and both resolved threads: no newer reviewer replies; the rejected-runtime finding still requires adapter rework. Draft stays unarmed.

@thomhurst
thomhurst force-pushed the issue-182-kafka-scheduler branch from 3691828 to e071605 Compare November 2, 2026 14:18
@github-actions

github-actions Bot commented Nov 2, 2026

Copy link
Copy Markdown

Review of #221 (Kafka partition scheduler integration)

Scope. I read KafkaConsumer.cs (the pump, admission, rebalance handling, flush/commit and shutdown paths) and KafkaPartitionSource.cs. I did not read every file in the diff. I also did not run the build or tests, and I did not read the docs, tests or benchmark changes in detail.

What I checked, with no defects found

  • Single pump. Admission, native operations, rebalance commands and commits all run on one pump. HandleCommand is only called from PumpAsync and AdmitBatchAsync, so Assignments and the checkpoint state are never touched across an await by another actor. The _source.Assignments[...] lookup after the commit in FlushAsync is therefore safe.
  • Stale completions. Revoked and lost partitions are fenced through the assignment tokens, Revoking and IsAssigned. Revokes commit only the revoked partitions' offsets, and the normal flush skips partitions that are revoking.
  • Failure paths. When the receive loop fails with an outstanding MoveNextAsync, it waits for that call to finish before rethrowing, so the original error is not masked. The restart path re-seeds from broker commits, or from the first admitted offset, when the previous run dropped queued records.
  • Project rules.
    • Every await in src/ uses ConfigureAwait(false).
    • There is no .Result or .Wait().
    • Pump methods use pooled async builders.
    • The 5 ms periodic deadline timer runs only during revoke or stop, not per message.
    • Native Pause, Resume and commit are used rather than re-implemented.
    • The scheduler is the existing core component.
    • The PR touches docs, roadmap, design and decisions (D13) in the same change.

Non-blocking notes

  • The PR title says per-message cost is covered by KafkaReceiveBenchmarks. Please also state the 0 B per-message result for KafkaDelivery.Snapshot in the PR description. It copies header data, which is the one place this path could allocate.
  • Rebalance and commit behaviour is covered by real-broker tests according to the description, but I did not check the CI results. Make sure CI Passed is green on this exact head before the draft is marked ready.

No actionable findings from what I read.

@thomhurst
thomhurst force-pushed the issue-182-kafka-scheduler branch from e071605 to 5272301 Compare November 2, 2026 14:26
@github-actions

github-actions Bot commented Nov 2, 2026

Copy link
Copy Markdown

Review of PR #221 (head 3691828)

I could not read Dekaf's source from this environment (network access to its repository needed approval), so the blocking finding below rests on an earlier review comment on this PR plus a grep of pr-head/docs. I did not review the full ~2000-line diff line by line.

Blocking: no recorded decision for building a parallel partitioned runtime (AGENTS.md 'Search before you build', D1, D22)

An earlier review comment on this PR says Dekaf 1.25.0 (the version in Directory.Packages.props) already ships RunPartitionedAsync, PartitionedProcessingOrder.Key, MaxConcurrentHandlersPerPartition and a KeyOrderedPartitionDispatcher. That would cover key-ordered per-partition concurrency, bounded buffering, and rebalance and revoke handling. This PR adds each of those again in PartitionScheduler, KafkaConsumer, KafkaOwnership and KafkaPartitionSource.

AGENTS.md says that building a parallel implementation needs a recorded decision in docs/decisions.md naming the native feature and why it cannot be used. The decision text added by this PR is the nearest thing to that. It says Dekaf's hosted retry and dead-letter helpers would bypass the portable classifier and durable-copy contract. That covers retry and dead-lettering. It does not name RunPartitionedAsync or the key-ordered dispatcher, and it does not say why their scheduling, ordering and revoke-drain parts cannot be wrapped. A grep for RunPartitioned across pr-head/docs finds nothing.

Requested change, either of:

  1. Add a decision to docs/decisions.md that names Dekaf's partitioned-processing API. It should state precisely which gaps block using it, for example commit control, replay on drain timeout, native-header snapshot lifetime, or core failure-pipeline integration. It should also link a Dekaf issue for each gap, as AGENTS.md requires for a client that falls short.
  2. If the gaps are small, file them on Dekaf and wrap the native runtime.

Reuse would remove most of the new concurrency, ordering and rebalance code. That code is the highest-risk part of this PR and has already drawn two rounds of correctness findings (shutdown during replay drain, health state).

Non-blocking

Positives

  • The tests cover real-broker rebalance under load, paused revoke, drain timeout, worker crash and restart, and aborted-transaction offset gaps.
  • Documentation and the roadmap are updated in the same PR.
  • The PR description states the per-message cost of each fix.

@thomhurst

Copy link
Copy Markdown
Owner Author

Removed the external hold: Dekaf 1.26.0 includes all three requested contracts, and #339 merged the pin. #22 already reflects this release. Keep this PR draft/unarmed while replacing its rejected duplicated runtime with the native adapter; historical reviews do not approve that future rework.

@thomhurst

Copy link
Copy Markdown
Owner Author

Superseded by #795, which wraps Dekaf's RunPartitionedAsync instead of the core scheduler. Some of the broker tests from here were carried over.

@thomhurst

Copy link
Copy Markdown
Owner Author

Closing as superseded by #795 (merged as 4f2835e), which wraps Dekaf's RunPartitionedAsync and closed #22. The branch stays for history.

@thomhurst thomhurst closed this Nov 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

on-hold Waiting for an external dependency or gate performance Run the advisory benchmark regression gate on this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Kafka: key-ordered parallelism, watermark commits and rebalance safety

1 participant