diff --git a/docs/decisions.md b/docs/decisions.md index e8a4784a2..4ead5bae1 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -33,7 +33,7 @@ To change a decision, add a new entry that supersedes it rather than editing his | [D20](#d20-sagas-are-out-of-scope-for-v1) | Sagas are out of scope for v1 | Accepted | | [D21](#d21-repository-conventions) | Repository conventions | Accepted | | [D22](#d22-the-kafka-transport-wraps-dekaf) | The Kafka transport wraps Dekaf | Accepted | -| [D23](#d23-a-generic-transport-spi-owned-by-the-core) | A generic transport SPI owned by the core | Accepted | +| [D23](#d23-a-generic-transport-spi-owned-by-the-core) | A generic transport SPI owned by the core | Accepted; core-first log scheduling superseded by [D40](#d40-log-transports-reuse-native-processing-runtimes) | | [D24](#d24-capabilities-are-valued-and-declared-per-endpoint) | Capabilities are valued and declared per endpoint | Accepted | | [D25](#d25-telemetry-follows-the-opentelemetry-messaging-span-model) | Telemetry follows the OpenTelemetry messaging span model | Accepted | | [D26](#d26-generate-default-json-metadata-with-the-official-systemtextjson-generator) | Generate default JSON metadata with the official System.Text.Json generator | Accepted | @@ -50,6 +50,7 @@ To change a decision, add a new entry that supersedes it rather than editing his | [D37](#d37-ordered-dispatch-bounds-validated-endpoint-retention) | Ordered dispatch bounds validated endpoint retention | Accepted | | [D38](#d38-postgresql-maintenance-leases-recover-unordered-rows-and-bound-retention) | PostgreSQL maintenance leases recover unordered rows and bound retention | Accepted | | [D39](#d39-named-transports-capture-startup-prepared-serializers) | Named transports capture startup-prepared serializers | Accepted | +| [D40](#d40-log-transports-reuse-native-processing-runtimes) | Log transports reuse native processing runtimes | Accepted | --- @@ -202,6 +203,8 @@ To change a decision, add a new entry that supersedes it rather than editing his ## D13. Kafka gets its own consumption model +Implementation ownership is clarified by [D40](#d40-log-transports-reuse-native-processing-runtimes): the planned parallel path uses Dekaf's native runtime. The consumption requirements below remain in force. + **Decision.** - Key-ordered parallelism within a partition. - Offsets are committed at the contiguous-completed watermark. @@ -309,6 +312,8 @@ Superseded by [D24](#d24-capabilities-are-valued-and-declared-per-endpoint). ## D23. A generic transport SPI owned by the core +The core-first log scheduling rule below is superseded by [D40](#d40-log-transports-reuse-native-processing-runtimes). The remaining SPI decisions stay in force. + **Context.** - D1 splits the work correctly: the core owns cross-cutting concerns and each transport owns native behaviour. But `ITransport` only declared a lifecycle. The core had no way to hand a message to a transport, a transport had no way to feed the consume pipeline, and the failure pipeline (D10) had no way to ask a transport to settle. - Without that seam, every transport would reimplement serialization, the CloudEvents envelope, trace propagation, retries, the dead-letter and delay fallbacks, outbox dispatch and telemetry, each slightly differently. Adding a technology would mean rewriting the basics. @@ -753,3 +758,22 @@ fetches or per-message discovery. Other schema versions require explicit wire ty errors fail startup. Registry IDs remain local to each serializer and never replace stable CloudEvents message identity. Dynamic discovery, registry rules/validation, latest-version selection, header/GUID identities, Avro and Protobuf schema registry adapters remain planned. No broker send, receive or settlement semantics change. + +## D40. Log transports reuse native processing runtimes + +Supersedes D23's core-first log scheduling rule and clarifies implementation ownership for D13, following #239. The rest of D23's generic SPI remains in force. + +**Context.** D23 put key ordering, completion watermarks, backpressure and ownership drain in the core to avoid rebuilding them for each log transport. Kafka is currently the only production log transport, and the pinned Dekaf 1.25.0 already provides these mechanisms in [`RunPartitionedAsync`](https://github.com/thomhurst/Dekaf/blob/v1.25.0/src/Dekaf/Consumer/PartitionedProcessing.cs) and its [key-ordered dispatcher](https://github.com/thomhurst/Dekaf/blob/v1.25.0/src/Dekaf/Consumer/KeyOrderedPartitionDispatcher.cs). Driving the core scheduler from Kafka, as proposed in #221, duplicates the native runtime and conflicts with D1 and D22. + +**Decision.** +- Inspect the pinned native client's source before selecting a log processing model. Reuse its scheduling, completion tracking, backpressure and ownership drain. File missing native capabilities upstream and wrap what exists. A parallel implementation needs a recorded decision naming the native feature and why it cannot be used. +- Kafka's planned parallel adapter wraps Dekaf's `RunPartitionedAsync` and maps configuration onto `PartitionedProcessingOptions`. Use native key ordering, per-partition handler/buffer limits, pause/resume, stop policy/timeout and commit policy/interval. Relayer retains its receive/failure pipeline, durable disposition before native completion, commit tracing and health integration. It does not use the core scheduler for Kafka. +- `PartitionScheduler` remains a fallback only for log transports whose native client has no equivalent. Its existing single-owner, bounded-storage and ownership-fencing contracts remain unchanged; see the [transport-author contract](../website/docs/transports/partition-scheduler.md). +- No production transport currently uses that fallback. Retain its public SPI and tests while the next log transport is designed, then inspect that client's runtime first. If no planned transport needs it, remove the public scheduler instead of maintaining unused public code. This decision makes no public API removal. + +**Consequences.** The current serial Kafka adapter remains the shipped path. #182 owns the native parallel adapter rework; this policy change does not complete it or permit #221's duplicated runtime to merge. Consumer-wide limits, oldest outstanding record health and runtime-aware replay must preserve their contracts; the native gaps and implementation status are recorded in [design §7](design.md#7-kafka-done-properly) and the [Kafka guide](../website/docs/transports/kafka.md). Missing native support is not permission to silently weaken those contracts or rebuild the runtime. D22's native reuse rule still applies; #240 separately tightens its exception wording. + +**Alternatives rejected.** +- Require every log transport to use the core scheduler: duplicates clients that already own processing and adds a second ownership protocol. +- Remove the scheduler immediately: preempts the next log transport's native-client assessment; #239 explicitly retains that decision for its design. +- Keep the Kafka duplication until native gaps close: makes an unrecorded exception to D1/D22 and creates a second runtime to retire later. diff --git a/docs/design.md b/docs/design.md index 6abeef0b4..2206496e0 100644 --- a/docs/design.md +++ b/docs/design.md @@ -168,7 +168,9 @@ public static ConsumerBuilder Group(this ConsumerBuilder`: key-ordered parallelism within a partition, commits at the contiguous-completed watermark, backpressure, drain on revoke, and pause tracking per partition (§7). The transport feeds records in and implements three calls: +**Log-based transports.** Kafka, Event Hubs, Kinesis, Pulsar, RabbitMQ Streams and JetStream share ordering and durable-checkpoint requirements (§7), but their native clients may already implement scheduling, backpressure and ownership drain. Search the pinned client's source first and wrap those mechanisms (D1, D22, D23). Kafka's planned parallel receive path wraps Dekaf's `RunPartitionedAsync`; it does not use the core scheduler. + +The core's `PartitionScheduler` is a fallback only for a log transport whose native client has no equivalent. A missing piece in an existing native runtime belongs upstream; it does not justify replacing that runtime. Record any exception and its native-feature gap in the decisions record before building a parallel implementation. When that fallback is justified, the transport feeds records in and implements three calls: ```csharp public interface IPartitionSource @@ -181,7 +183,7 @@ public interface IPartitionSource `TPosition` is whatever the broker uses: a `long` offset for Kafka, a sequence-number string for Kinesis, a `MessageId` for Pulsar. The scheduler never compares positions; it tracks them in arrival order. -The implemented [partition scheduler](../website/docs/transports/partition-scheduler.md) uses `IPartitionMessageBinding` for native key equality and lease release, and the [completion-window primitive](../website/docs/transports/partition-completion.md) for bounded arrival-order checkpoints. One transport-owned pump serializes admission, dispatch, completion observation and native calls without per-delivery tasks or continuations. Assignment tokens fence stale completions; configurable global/per-assignment limits include retained work, and global limits include late handlers after ownership ends. Revoke stops dispatch and drains active work up to a monotonic deadline; loss fences immediately. Native Kafka integration remains planned. +The implemented fallback [partition scheduler](../website/docs/transports/partition-scheduler.md) uses `IPartitionMessageBinding` for native key equality and lease release, and the [completion-window primitive](../website/docs/transports/partition-completion.md) for bounded arrival-order checkpoints. One transport-owned pump serializes admission, dispatch, completion observation and native calls without per-delivery tasks or continuations. Assignment tokens fence stale completions; configurable global/per-assignment limits include retained work, and global limits include late handlers after ownership ends. Revoke stops dispatch and drains active work up to a monotonic deadline; loss fences immediately. No production transport in `src/` currently uses this scheduler. When designing the next log transport, check its native client before choosing the fallback; remove the public scheduler if no planned transport needs it (D23). Every transport proves the SPI contract by passing the transport conformance suite (§15). The in-memory transport is the first implementation, in phase 0. @@ -556,11 +558,11 @@ See [consumer configuration and failure boundaries](https://relayer.tomlonghurst Kafka gets its own consumption model instead of being forced into a queue shape (Wolverine #3134). -The transport wraps **[Dekaf](https://github.com/thomhurst/Dekaf)**, a pure C# Kafka client (decision D22). Dekaf has no native dependencies, supports Native AOT, and is built for zero-allocation hot paths, which matches Relayer's own goals. Dekaf already ships features such as retry and dead-letter topics, an outbox, and OpenTelemetry instrumentation. Following principle 1, the Kafka transport reuses Dekaf's mechanisms where they fit Relayer's uniform pipeline, rather than re-implementing them. Relayer's outbox remains the cross-transport outbox. +The transport wraps **[Dekaf](https://github.com/thomhurst/Dekaf)**, a pure C# Kafka client (decision D22). Dekaf has no native dependencies, supports Native AOT, and is built for zero-allocation hot paths, which matches Relayer's own goals. Dekaf already ships features such as partitioned processing, retry and dead-letter topics, an outbox, and OpenTelemetry instrumentation. Following principle 1, search the pinned client's source and reuse its mechanisms. A feature that cannot be used needs a recorded reason and an upstream issue; a parallel implementation needs an explicit decision. Relayer's outbox remains the cross-transport outbox. -- **Key-ordered parallelism:** within a partition, messages with different keys are processed concurrently (`Concurrency(perPartition: n, orderBy: OrderBy.Key)`), while messages with the same key stay ordered. This, the watermark commits and the rebalance handling below live in the core's partition scheduler (§2.4), so other log-based transports reuse them. -- **Offset commits by watermark:** Relayer commits the highest *contiguous* completed offset per partition, asynchronously and batched, and flushes on rebalance and shutdown (Brighter #2269). -- **Rebalance safety:** `cooperative-sticky` is supported. On revoke, Relayer stops dispatching for the revoked partitions, drains in-flight work up to a timeout, then commits. Pause and resume are tracked per partition, so a rebalance while paused cannot deadlock (KafkaFlow #456, #681). +- **Key-ordered parallelism (planned):** wrap Dekaf's `RunPartitionedAsync` with `Ordering = PartitionedProcessingOrder.Key` and `MaxConcurrentHandlersPerPartition`. Dekaf compares byte-array keys by content and owns the ordered lanes; Relayer invokes its receive/failure pipeline within the native processor. Kafka does not use the fallback core scheduler (§2.4). +- **Offset commits by watermark (planned for parallel receive):** Dekaf tracks the highest *contiguous* completed offset per partition and batches asynchronous commits through `PartitionCommitPolicy.CommitCompletedPeriodically`, including flush on revoke and shutdown (Brighter #2269). Relayer allows native processing completion only after `Complete` or `SettledByHandler` means the work is durable. Relayer supplies its commit span without a second checkpoint tracker. +- **Rebalance safety (planned for parallel receive):** use Dekaf's native cooperative assignment, `PartitionStopPolicy.Drain`, `StopTimeout` and `PartitionBackpressureMode.PauseResume`. The native runtime owns revoked lanes, drain and pause tracking, including rebalances while paused (KafkaFlow #456, #681). Preserve the configured native rebalance listeners. - **Consume-transform-produce:** - *Kafka → database → anything:* the inbox, business data, and outbox are written in one database transaction. The offset is committed only after that transaction commits. Redelivery after a crash is deduplicated by the inbox. - *Kafka → Kafka:* optional native Kafka transactions (Dekaf's `SendOffsetsToTransactionAsync`) give exactly-once processing. @@ -570,6 +572,8 @@ The transport wraps **[Dekaf](https://github.com/thomhurst/Dekaf)**, a pure C# K - **Schema registry:** works with multiple clusters, each with its own registry (KafkaFlow #558). - **Logging:** Dekaf logs through `ILoggerFactory` (`WithLoggerFactory`), so Kafka client logs land in the app's logging pipeline with no native log bridge. +The shipped adapter still uses serial native fetch batches; see the [Kafka guide](../website/docs/transports/kafka.md) for the current API. [#182](https://github.com/thomhurst/Relayer/issues/182) owns the parallel adapter implementation. Dekaf 1.25.0 lacks consumer-wide handler/buffer limits ([Dekaf#4054](https://github.com/thomhurst/Dekaf/issues/4054)), oldest outstanding record time ([Dekaf#4055](https://github.com/thomhurst/Dekaf/issues/4055)), and runtime-aware seek ([Dekaf#4056](https://github.com/thomhurst/Dekaf/issues/4056)). Keep these contracts explicit while the native gaps are resolved; neither silently weaken them nor recreate the runtime in Relayer. + --- ## 8. Observability diff --git a/website/docs/roadmap.md b/website/docs/roadmap.md index d8dbe69db..90c385927 100644 --- a/website/docs/roadmap.md +++ b/website/docs/roadmap.md @@ -23,7 +23,7 @@ Relayer is in early development. Track progress in [GitHub issues](https://githu - [PostgreSQL ADO.NET and Dapper transactions](reference/postgres-outbox.md): scoped enlistment, owned message copies and one atomic batched insert on commit. - [Unordered PostgreSQL direct dispatch](reference/direct-dispatch.md): background sends immediately after EF commit, fenced claims, native transport batches and fenced batch deletion. Register [leased recovery and cleanup](reference/postgres-maintenance.md) for unordered crash recovery and bounded dead/inbox retention. Poison-row handling remains planned. - The consume pipeline and the native receive SPI. -- [Bounded partition completion watermarks](transports/partition-completion.md) and the core [partition scheduler](transports/partition-scheduler.md) for transport authors, with native key ordering, bounded concurrency, backpressure and ownership-fenced drain. Native Kafka integration remains planned. +- [Bounded partition completion watermarks](transports/partition-completion.md) and the core [fallback partition scheduler](transports/partition-scheduler.md) for transport authors whose clients have no equivalent native runtime, with key ordering, bounded concurrency, backpressure and ownership-fenced drain. Kafka parallel receive remains planned and will wrap Dekaf's `RunPartitionedAsync`. - Explicit [message upcaster chains](guides/messages.md#versioning-and-unknown-types), composed at startup for single-message and batch handlers. - [Service Bus native sending and topology](transports/service-bus.md): named registration, owned/caller-owned clients, queues/topics, byte-limited native batches, scheduling, native callbacks, explicit session verification and non-destructive provisioning. [Receive primitives](transports/service-bus-receive.md) are available separately; hosted receiver composition remains planned. - Generated batch handler execution, durable partial-failure decisions, and validated native/client-side receive executors for transport authors. diff --git a/website/docs/transports/kafka.md b/website/docs/transports/kafka.md index ede963722..85e98be84 100644 --- a/website/docs/transports/kafka.md +++ b/website/docs/transports/kafka.md @@ -69,7 +69,9 @@ Register the handler and its message with source generation. Create both topics `KafkaTransportOptions.ConfigureConsumer` receives Dekaf's `ConsumerBuilder`. Native security, offset-reset, fetch and group settings remain available. Keep the raw byte deserializers. After that callback, Relayer sets the declared group and source subscription, disables automatic offset storage and commits, and adds its rebalance listener. These ownership settings ensure polling never acknowledges unfinished work. Dekaf's native offset-reset default still applies; set `WithAutoOffsetReset(AutoOffsetReset.Earliest)` explicitly when a new group must read existing records. -One declaration currently processes records serially, with `Concurrency(1)` and single-message handlers. Other values fail at startup with an actionable error. The adapter consumes native fetch batches and commits their native next-offset checkpoints only after every delivered record completes. It abandons an invalidated batch on rebalance. If the partition remains assigned, it seeks to the batch's first delivered offset and replays the uncommitted batch; a revoked partition resumes through native reassignment. Successful records in that batch may therefore run again. Native batch checkpoints preserve offset gaps and leader epochs. Key-parallel processing, contiguous watermark tracking across parallel work, and bounded drain-on-revoke belong to the planned partition scheduler. Shutdown stops fetching and drains the current batch; its cancellation deadline aborts unfinished handling without committing it. Each hosted service starts once; recreate the host to restart Kafka consumers, including after a failed or aborted receive. A fresh native consumer resumes at the broker's committed offsets. Partial startup failure disposes the transport and all consumers already created. +One declaration currently processes records serially, with `Concurrency(1)` and single-message handlers. Other values fail at startup with an actionable error. The adapter consumes native fetch batches and commits their native next-offset checkpoints only after every delivered record completes. It abandons an invalidated batch on rebalance. If the partition remains assigned, it seeks to the batch's first delivered offset and replays the uncommitted batch; a revoked partition resumes through native reassignment. Successful records in that batch may therefore run again. Native batch checkpoints preserve offset gaps and leader epochs. Shutdown stops fetching and drains the current batch; its cancellation deadline aborts unfinished handling without committing it. Each hosted service starts once; recreate the host to restart Kafka consumers, including after a failed or aborted receive. A fresh native consumer resumes at the broker's committed offsets. Partial startup failure disposes the transport and all consumers already created. + +Parallel receive is planned in [#182](https://github.com/thomhurst/Relayer/issues/182). It will wrap Dekaf's `RunPartitionedAsync` for key ordering, contiguous completion tracking, backpressure and bounded drain; it will not use Relayer's [fallback partition scheduler](partition-scheduler.md). Relayer will retain its receive/failure pipeline, durable completion rule, commit spans and health reporting. Integration must preserve consumer-wide limits, oldest outstanding record health and safe replay. Native gaps are tracked in [Dekaf#4054](https://github.com/thomhurst/Dekaf/issues/4054), [Dekaf#4055](https://github.com/thomhurst/Dekaf/issues/4055) and [Dekaf#4056](https://github.com/thomhurst/Dekaf/issues/4056); this plan does not make parallel receive available today. Inside a handler, `context.Kafka().ConsumeResult` exposes Dekaf's original record. Durable dead-letter copies retain native null values and nullable application headers. The struct view wraps a pooled `NativeMessage` feature and is valid only during processing. It provides native headers, key, partition, offset and timestamp without allocating a feature for each record. Null-value records receive the tombstone telemetry attribute and dispatch to `IHandler>`. Non-null records, including empty values, dispatch to `IHandler`. Missing handlers or malformed non-null bodies follow the core failure policy. diff --git a/website/docs/transports/partition-completion.md b/website/docs/transports/partition-completion.md index 2323a4cf4..7629307c5 100644 --- a/website/docs/transports/partition-completion.md +++ b/website/docs/transports/partition-completion.md @@ -5,7 +5,7 @@ description: "Bounded arrival-order completion tracking for log transport author `PartitionCompletionWindow` is a core building block for log transports. It tracks deliveries in native arrival order and releases only the contiguous completed prefix. Positions are opaque: the window never compares, sorts or increments them. A position can include a native next offset and leader epoch, or be a string checkpoint. -The window does not dispatch handlers, commit to a broker, pause fetching or drain workers. The core [partition scheduler](partition-scheduler.md) composes those mechanisms. [Kafka integration](kafka.md#register-a-consumer) remains planned under [#182](https://github.com/thomhurst/Relayer/issues/182); Kafka consumers still require `Concurrency(1)`. +The window does not dispatch handlers, commit to a broker, pause fetching or drain workers. The core [fallback partition scheduler](partition-scheduler.md) composes those mechanisms for clients without an equivalent native runtime. Reuse native completion tracking when it exists. [Kafka parallel receive](kafka.md#register-a-consumer) remains planned under [#182](https://github.com/thomhurst/Relayer/issues/182) and will use Dekaf's `RunPartitionedAsync`, not this window or the fallback scheduler. Kafka consumers still require `Concurrency(1)`. ## Tracking and completion diff --git a/website/docs/transports/partition-scheduler.md b/website/docs/transports/partition-scheduler.md index 897dd0af4..b27897368 100644 --- a/website/docs/transports/partition-scheduler.md +++ b/website/docs/transports/partition-scheduler.md @@ -1,9 +1,17 @@ --- title: Partition scheduler -description: "Key-ordered scheduling, native backpressure and bounded drain for log transport authors." +description: "Fallback key-ordered scheduling for log transports without a native processing runtime." --- -`PartitionScheduler` runs an existing receive/failure pipeline with key ordering and bounded concurrency. It builds on [partition completion watermarks](partition-completion.md). This is a transport-author SPI; [Kafka consumer integration](kafka.md#register-a-consumer) remains planned in [#182](https://github.com/thomhurst/Relayer/issues/182). Kafka registration still requires `Concurrency(1)`. +`PartitionScheduler` runs an existing receive/failure pipeline with key ordering and bounded concurrency. It builds on [partition completion watermarks](partition-completion.md). This is a fallback transport-author SPI for clients without an equivalent native processing runtime. No production transport currently uses it. + +## Choose the native runtime first + +Before using this scheduler, inspect the native client's source at the pinned version for ordering, completion tracking, backpressure and ownership drain. Wrap those features when they exist. File missing capabilities upstream; do not replace an existing native runtime to fill a gap without a recorded design decision explaining why its feature cannot be used. + +Kafka's planned parallel adapter wraps Dekaf's `RunPartitionedAsync`, which already owns key ordering, completion tracking, pause/resume and bounded drain. Kafka will not use this fallback scheduler. [Kafka parallel receive](kafka.md#register-a-consumer) remains planned in [#182](https://github.com/thomhurst/Relayer/issues/182); registration still requires `Concurrency(1)`. + +The fallback SPI and its tests remain available while the next log transport is designed. Check that client's runtime first. If no planned transport needs the fallback, remove the public scheduler instead of maintaining unused public code. This policy does not remove or change the existing SPI. ## Compose once, pump on the native owner diff --git a/website/src/pages/index.js b/website/src/pages/index.js index 098878b6c..1e6631d32 100644 --- a/website/src/pages/index.js +++ b/website/src/pages/index.js @@ -291,8 +291,8 @@ const status = [ ['CI performance regression gate and in-memory benchmarks', 'Implemented; raw broker cases planned', true], ['Kafka producers, serial consumers, typed tombstones, dead-letter copies and offset/timestamp replay', 'Implemented', true], ['Named transport serializers and independent Kafka JSON schema registries', 'Implemented; explicit startup contracts', true], - ['Partition watermarks, key scheduling, backpressure and bounded drain', 'Implemented core SPI', true], - ['Kafka parallel scheduling, Service Bus receiver composition, SQS/SNS and RabbitMQ transports', 'In progress', false], + ['Fallback partition watermarks, key scheduling, backpressure and bounded drain', 'Implemented core SPI; native runtime first', true], + ['Kafka parallel receive via Dekaf, Service Bus receiver composition, SQS/SNS and RabbitMQ transports', 'In progress', false], ['Health checks with application-provided adapters', 'Implemented', true], ['Durable outbox contracts and keyed health adapter', 'Implemented core seam', true], ['PostgreSQL schema scripts, CLI and EF migration path', 'Implemented schema tooling', true],