packages feed

shibuya-redis-adapter (empty) → 0.1.0.0

raw patch · 40 files changed

+3690/−0 lines, 40 filesdep +asyncdep +basedep +bytestring

Dependencies added: async, base, bytestring, containers, directory, effectful-core, entropy, filepath, hedis, hs-opentelemetry-api, hs-opentelemetry-exporter-in-memory, hs-opentelemetry-sdk, process, shibuya-core, shibuya-redis-adapter, stm, streamly-core, temporary, text, unordered-containers

Files

+ CHANGELOG.md view
@@ -0,0 +1,16 @@+# Changelog++## Unreleased++## 0.1.0.0 — 2027-01-06++### New Features++- Add independent Redis Streams readers with ordered checkpoints and consumer-group workers with fenced recovery.+- Support delayed retries and idempotent dead-letter records, including exhausted retries and consumer trace context.+- Propagate W3C trace context to Shibuya’s OpenTelemetry consumer spans, with configurable reader and worker correlation policies.++### Other Changes++- Provide optional reader and worker examples. The compatibility matrix covers Redis 7.2.17 and 8.10.1 on GHC 9.12.4.+- Include integration guides and a capability catalog in the source distribution.
+ LICENSE view
@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Nadeem Bitar++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.
+ README.md view
@@ -0,0 +1,56 @@+# Shibuya Redis Streams adapter++This Haskell library connects Shibuya processors to one Redis Stream per adapter on a single primary.++| Use case | Constructor | Progress |+|---|---|---|+| A projection or live subscriber needs its own ordered copy | `newReader` and `readerProcessor` | Completed cursor with optional application-managed checkpoint |+| Workers share jobs and recover abandoned assignments | `newGroupWorker` and `groupProcessor` | Redis group position, pending entries and fenced attempt state |++Both constructors accept a raw binary entry or a typed decoder. They preserve field order and duplicate names. The envelope's stable message ID is an application idempotency key. Commit external effects with that key in durable application storage when they must survive replay.++See the [adapter guides and reference](docs/user/index.md) for integration details and the [capability catalog](docs/capabilities/index.md) for the behavior and limits of each feature.++## Run both examples++The package builds its library by default. The repository's `cabal.project` and Nix build enable the `examples` flag. Use `-fexamples` when building from the source archive.++Start the project-local Redis service in one terminal. Stop it with Ctrl-C after the demo.++```sh+nix develop+process-compose -U up -t=false+```++In another terminal, start from the repository root. Use a fresh stream and checkpoint file.++```sh+nix develop+stream="shibuya-demo-$(date +%s)"+checkpoint=".dev/${stream}.cursor"+redis-cli -s "$REDIS_SOCKET" XADD "$stream" 1-0 item first+cabal run reader-example -- "$REDIS_SOCKET" "$stream" "$checkpoint" 1+cabal run worker-example -- "$REDIS_SOCKET" "$stream" thumbnails earliest 1++redis-cli -s "$REDIS_SOCKET" XADD "$stream" 2-0 item second+cabal run reader-example -- "$REDIS_SOCKET" "$stream" "$checkpoint" 1+cabal run worker-example -- "$REDIS_SOCKET" "$stream" thumbnails attach 1+```++Both examples print entry `1-0` on their first invocation and `2-0` on their second, followed by the stable message ID. Each exits after processing the requested number of entries. The reader replaces its checkpoint file atomically and expects a single owner. The worker generates a new consumer name each time it starts. Use `tail` to create a missing group at the current end of its stream.++## Integrate with an application++Use `withRedisRuntime` around processor construction, `runApp`, and the complete shutdown. Each runtime reserves one dedicated read connection alongside an owned or caller-borrowed command pool. Keep the borrowed pool open until finalizers drain.++Readers can start at `Earliest`, `After checkpoint`, or `Live`. A saved checkpoint takes precedence. Store the completed ID and any producer continuity evidence together under the reader's logical name and source identity. When attaching after a snapshot, pass the snapshot cursor and evidence to `After`, then check the next entry's generation or predecessor with `checkContinuity`. Use `onReaderGap` to stop, request a resnapshot, or accept the discontinuity explicitly.++Workers use explicit group creation or attachment and unique per-instance consumer names. Call the optional message lease's `leaseExtend` before a long-running handler becomes eligible for recovery. A worker can reclaim its own retried entry after the requested delay. A stale finalizer cannot acknowledge or modify a newer attempt. A stale handler may still finish an external effect, so transactionally deduplicate effects that must apply once.++On retry exhaustion, either mode writes a `MaxRetriesExceeded` record and advances when a dead-letter hash is configured. Without a hash, the processor stops with the reader checkpoint before the entry or the worker entry still pending.++The processor helpers set compatible Shibuya policies. Readers use strict serial processing, and workers use unordered processing up to the configured group capacity. A reader cannot supply a batch that waits for several unfinalized entries. Attach each processor to its own runtime. A second attachment fails with `RuntimeAlreadyAttached`. Import adapter constructors and configuration from `Shibuya.Adapter.Redis`. The `Internal` module exposes implementation helpers without a compatibility guarantee.++For OpenTelemetry correlation, producers can write W3C `traceparent` and optional `tracestate` as stream fields. Readers default to `LinkOnly`, which starts a linked trace for each delivery. Group workers default to `ParentAndLink`, which joins the producer trace and also links to its span. Set the mode configuration’s `telemetry` field to override the policy or use its trace-context extractor to read a custom field convention. Rejections from a traced finalizer retain the consumer span’s W3C context.++See [compatibility and operations](docs/compatibility.md) for tested versions, Redis permissions and recovery behavior.
+ docs/capabilities/binary-entries.md view
@@ -0,0 +1,30 @@+---+type: Capability+title: "Binary entries and stable message identity"+description: "Decode ordered binary field pairs while retaining a source-scoped message ID across redelivery."+capabilityId: CAP-4+provider: mori://shinzui/shibuya-redis-adapter+status: shipped+stability: experimental+since: unreleased+packages: [shibuya-redis-adapter]+interface: ["SourceIdentity", "RedisEntry", "readerDecode", "groupDecode"]+generated:+  by: codex-cli/0.172.0+  at: "2026-11-25T14:35:53Z"+evidence:+  - kind: test+    resource: test/Main.hs+    proves: "Checks binary delivery, identity framing, absent versus empty generation, and decoder failure identity."+  - kind: module+    resource: src/Shibuya/Adapter/Redis/Types.hs+    proves: "Defines the envelope cursor, message identity and field-preserving conversion."+---++# Binary entries and stable message identity++Both delivery modes expose the native entry ID and original field/value sequence, including duplicate field names. A typed decoder changes the payload while preserving the envelope identity. The message ID incorporates namespace, optional generation, stream key and native entry ID.++## Limits++Recreating a stream can reuse native IDs. Supply a distinct generation when old and new entries must remain distinguishable. The application owns durable deduplication of external writes.
+ docs/capabilities/dead-letter-records.md view
@@ -0,0 +1,30 @@+---+type: Capability+title: "Idempotent dead-letter records"+description: "Record rejected or retry-exhausted entries in a Redis hash before committing progress."+capabilityId: CAP-5+provider: mori://shinzui/shibuya-redis-adapter+status: shipped+stability: experimental+since: unreleased+packages: [shibuya-redis-adapter]+interface: ["readerDeadLetters", "groupDeadLetters", "rejectionRecord"]+generated:+  by: codex-cli/0.172.0+  at: "2026-11-25T14:35:53Z"+evidence:+  - kind: test+    resource: test/ReaderSpec.hs+    proves: "Checks ordered rejection, reconnect and retry exhaustion."+  - kind: test+    resource: test/ReleaseSpec.hs+    proves: "Exercises replay after the rejection write succeeds and XACK fails."+---++# Idempotent dead-letter records++Configure a rejection hash for either delivery mode. A permanent rejection stores the reason and original field pairs under a key scoped to the reader or group and message identity. Retry exhaustion uses MaxRetriesExceeded. Repeating the write keeps the first record. A reader then commits its checkpoint and a worker acknowledges its pending entry.++## Limits++Without a destination, rejection stops processing with the entry outstanding. Retain the hash through the replay horizon. Redrive is an application operation.
+ docs/capabilities/index.md view
@@ -0,0 +1,16 @@+---+okf_version: "0.2"+---++# Files++- [profile.dhall](profile.dhall)++# Capability++- [Binary entries and stable message identity](binary-entries.md) - Decode ordered binary field pairs while retaining a source-scoped message ID across redelivery.+- [Idempotent dead-letter records](dead-letter-records.md) - Record rejected or retry-exhausted entries in a Redis hash before committing progress.+- [Independent ordered readers](ordered-readers.md) - Run multiple projections over a stream with separate identities and ordered checkpoint commits.+- [Recoverable consumer-group workers](recoverable-worker-pools.md) - Share work across consumers and reclaim pending entries with attempt-fenced finalization.+- [Snapshot handover and gap detection](snapshot-continuity.md) - Resume after a snapshot and inspect evidence of a stream rollback or producer discontinuity.+- [Producer and consumer trace correlation](trace-correlation.md) - Correlate Shibuya consumer spans with W3C context carried by Redis stream fields.
+ docs/capabilities/log.md view
@@ -0,0 +1,4 @@+# Bundle Update Log++## 2026-11-25+* **Adoption**: Adopted the `coordination.capabilities` export of `mori://shinzui/okf-profiles` (v0.25.0). Added CAP-1 through CAP-6 with implementation and test evidence for each consumer-facing contract.
+ docs/capabilities/ordered-readers.md view
@@ -0,0 +1,30 @@+---+type: Capability+title: "Independent ordered readers"+description: "Run multiple projections over a stream with separate identities and ordered checkpoint commits."+capabilityId: CAP-1+provider: mori://shinzui/shibuya-redis-adapter+status: shipped+stability: experimental+since: unreleased+packages: [shibuya-redis-adapter]+interface: ["newReader", "readerProcessor", "CheckpointStore"]+generated:+  by: codex-cli/0.172.0+  at: "2026-11-25T14:35:53Z"+evidence:+  - kind: test+    resource: test/ReaderSpec.hs+    proves: "Exercises independent readers, restart, retry ordering and replay after a crash."+  - kind: example+    resource: examples/Reader.hs+    proves: "Runs a reader with a single-owner file checkpoint."+---++# Independent ordered readers++Each reader uses XREAD and tracks its own completed cursor. A saved checkpoint takes precedence over the configured earliest, live or snapshot start. Fetching ahead does not advance progress past an unfinished entry.++## Limits++The default checkpoint is in memory. A durable projection supplies its own store and handles replay between committing an effect and saving its cursor. A handler that waits for multiple unfinished entries can block this serial processor.
+ docs/capabilities/profile.dhall view
@@ -0,0 +1,14 @@+-- OKF profile descriptor written by `okf profile init`.+--+-- Profile: coordination.capabilities+-- Source:  https://raw.githubusercontent.com/shinzui/okf-profiles/v0.25.0/package.dhall+--+-- Existing hashes are preserved and unhashed remote value imports are frozen.+-- Local and environment inputs remain live; this is not a portable snapshot.+-- To update remote imports, remove their hashes and run `dhall freeze profile.dhall`.+-- Never hand-write a sha256 value.+let registry =+      https://raw.githubusercontent.com/shinzui/okf-profiles/v0.25.0/package.dhall+        sha256:ec74cc6f7b8ee1a5af81ee7fc8804f35cf2c9ba4010671d9e881da72eb6719d3++in  registry.coordination.capabilities
+ docs/capabilities/recoverable-worker-pools.md view
@@ -0,0 +1,30 @@+---+type: Capability+title: "Recoverable consumer-group workers"+description: "Share work across consumers and reclaim pending entries with attempt-fenced finalization."+capabilityId: CAP-3+provider: mori://shinzui/shibuya-redis-adapter+status: shipped+stability: experimental+since: unreleased+packages: [shibuya-redis-adapter]+interface: ["newGroupWorker", "groupProcessor", "minimumIdleMillis", "groupInFlight"]+generated:+  by: codex-cli/0.172.0+  at: "2026-11-25T14:35:53Z"+evidence:+  - kind: test+    resource: test/GroupSpec.hs+    proves: "Exercises competing consumers, takeover back to an earlier owner, stale callbacks, lease renewal, delayed retry and bounded pending scans."+  - kind: example+    resource: examples/Worker.hs+    proves: "Creates or attaches to a group with a fresh consumer name."+---++# Recoverable consumer-group workers++Workers sharing one group divide entries among themselves. The adapter alternates new work with bounded scans of pending work. An explicit retry releases capacity until its deadline. Abandoned deliveries become eligible after the idle interval and any lease deadline. The worker checks attempt ownership before extending, retrying, rejecting or acknowledging.++## Limits++Workers may finish out of order. A stale handler can still perform external effects. Retain pending payloads until completion and use the missing-payload callback to record losses when retention removes an entry.
+ docs/capabilities/snapshot-continuity.md view
@@ -0,0 +1,28 @@+---+type: Capability+title: "Snapshot handover and gap detection"+description: "Resume after a snapshot and inspect evidence of a stream rollback or producer discontinuity."+capabilityId: CAP-2+provider: mori://shinzui/shibuya-redis-adapter+status: shipped+stability: experimental+since: unreleased+packages: [shibuya-redis-adapter]+interface: ["After", "checkContinuity", "onReaderGap"]+generated:+  by: codex-cli/0.172.0+  at: "2026-11-25T14:35:53Z"+requires: [CAP-1]+evidence:+  - kind: test+    resource: test/ReaderSpec.hs+    proves: "The handover scenario exercises snapshot readers, predecessor and generation checks, and gap disposition."+---++# Snapshot handover and gap detection++Start an [ordered reader](ordered-readers.md) after the snapshot checkpoint. Persist opaque continuity evidence with each completed ID. The reader checks for Redis tail rollback and passes the candidate entry to the application continuity check. The application can stop, resnapshot or explicitly accept a discontinuity.++## Limits++Redis IDs alone cannot reveal all trimmed history. The producer must supply evidence such as a predecessor when the application needs to detect missing entries. Snapshot creation and rebuilding belong to the application.
+ docs/capabilities/trace-correlation.md view
@@ -0,0 +1,27 @@+---+type: Capability+title: "Producer and consumer trace correlation"+description: "Correlate Shibuya consumer spans with W3C context carried by Redis stream fields."+capabilityId: CAP-6+provider: mori://shinzui/shibuya-redis-adapter+status: shipped+stability: experimental+since: unreleased+packages: [shibuya-redis-adapter]+interface: ["defaultTraceContext", "traceCorrelation", "readerTraceContext", "groupTraceContext"]+generated:+  by: codex-cli/0.172.0+  at: "2026-11-25T14:35:53Z"+evidence:+  - kind: test+    resource: test/TelemetrySpec.hs+    proves: "Inspects exported consumer spans, producer parent and links, Redis attributes and context in rejection records."+---++# Producer and consumer trace correlation++Readers link a new trace to the producer by default. Workers make the producer span their parent and also link to it. Both support a custom extractor and correlation policy. Redis span attributes include the native entry ID. A traced finalizer can carry its consumer context into the rejection record.++## Limits++Producer correlation needs valid incoming context. Applications configure their tracing interpreter, provider and export destination.
+ docs/compatibility.md view
@@ -0,0 +1,79 @@+# Compatibility and operations++The adapter uses one Redis primary and one stream per instance. The public runtime supports both an owned command pool and a caller-borrowed command pool. Reserve capacity for finalization, recovery and shutdown independently of the blocking read connection.++## Qualified builds++The qualification target is GHC 9.12.4 on Apple Silicon with hedis 0.16.4, shibuya-core 0.13.0.1, streamly-core 0.3.3, effectful-core 2.7.1.2, entropy 0.4.1.11 and OpenTelemetry 1.0.0.0 (API, SDK and exporters). The release candidate passed all five suites on both Redis builds on 2026-11-25.++| Redis | Source revision | Build ID | Suites passed |+|---|---|---|---|+| 7.2.17 | `83937c51afb53e1c69661c8e1533e0e19b896fe1` | `68e86d123dada851` | 5 of 5 |+| 8.10.1 | `3399357e7c17b668289386b8a15a3037bc4527b1` | `63b009e75218a69d` | 5 of 5 |++Redis 7.2.17 was built from the upstream release tarball on Apple Silicon. The tarball SHA-256 was `07c679c013fd82513299733bddf91999bbbc830351ec9ea985a533b09a595d76`. Redis 8.10.1 came from the pinned Nix development shell. The version commands report `sha=00000000:0` for both source snapshots. The table lists the upstream tag revisions.++```sh+curl -fLO https://download.redis.io/releases/redis-7.2.17.tar.gz+tar -xzf redis-7.2.17.tar.gz+make -C redis-7.2.17 -j6 MALLOC=libc redis-server+redis-7.2.17/src/redis-server --version+nix develop -c redis-server --version+```++The group protocol uses exclusive `XPENDING` ranges, `XCLAIM` with `JUSTID`, Redis server time and server-side scripting. The qualified builds support these primitives without requiring server modules. Test another server executable by setting an absolute path in `REDIS_SERVER`.++```sh+nix develop -c cabal build all+nix develop -c cabal test all --test-show-details=direct+nix develop -c env REDIS_SERVER=/path/to/redis-server cabal test all --test-show-details=direct+nix flake check+```++On the same host, `cabal check` reported no errors or warnings. The unpacked source archive built with the default library-only configuration and with `-fexamples`. Haddock generated the public facade with 47 of 47 items documented. Both examples processed two entries across restarts. `nix flake check` passed, and the default Nix package built both examples and ran all five suites. An OTLP smoke test also retrieved both consumer spans from Jaeger.++## Scenario evidence++The suites launch private Redis servers through the selected executable and run the public processors through the Shibuya runner. Handler and finalization barriers coordinate competing connections. The release suite restarts its own AOF-enabled server and inspects progress over a fresh connection.++| Initial-spec scenario | Automated evidence |+|---|---|+| Independent projections | `reader-integration`, independent readers and checkpoint restart |+| Work pool and separate group | `group-integration`, concurrent creators, competing workers and another group |+| Worker takeover | `group-integration`, A→B→A ownership with stale success, retry, lease and rejection callbacks |+| Retry and permanent failure | `group-integration` covers same-worker retry, Redis-time deadlines, exception retry and exhausted retries. `reader-integration` covers exhaustion, rejection reconnect and ordered checkpointing. `release-integration` denies XACK after the failure record is written and verifies replay. |+| Script cache and lease loss | `group-integration` covers script cache flush recovery, skipping locally active rows, and stale lease status. |+| OpenTelemetry | `telemetry-integration` checks reader links, worker parent and link, Redis tags, and consumer context in dead letters. |+| Projection crash | `reader-integration`, forced stop after the effect and before checkpoint save |+| Snapshot handover | `reader-integration`, two readers after a shared cursor, predecessor and generation checks, and resnapshot |+| Retention and wire fidelity | `reader-integration` and `group-integration`, missing history and pending payloads. `runner-fixture` verifies ordered duplicate binary fields. |+| Bounded lifecycle | `release-integration`, blocked reads, stalled handler, Redis restart with AOF, borrow and drain, sibling halt, and finite reconnect exhaustion. The mode suites verify bounded pending scans, prefetch ordering and recovery. |++## Redis permissions++The connection requires `PING`. Configure authentication and database selection as needed. Grant key permissions only for the relevant stream, optional rejection hash and adapter state. Typical Redis ACL key patterns are `~stream-key`, `~failure-hash` and, for workers, `~shibuya:group:v1:*`.++| Capability | Commands |+|---|---|+| Reader | `XREAD`, `XINFO STREAM` |+| Optional reader rejection | `HSETNX` |+| Worker | `XREADGROUP`, `XPENDING`, `SCRIPT LOAD`, `EVALSHA`, `EVAL`, `XRANGE`, `XCLAIM`, `TIME`, `EXISTS`, `HGET`, `HSET`, `HDEL`, `XACK`, `DEL` |+| Optional worker group creation | `XGROUP CREATE` |+| Optional worker rejection | `HSETNX` executed in the finalizer script |+| Optional worker pending depth and age | `XPENDING`, including the summary form on scan wrap |++The restricted-credential test grants stream subcommands individually and exercises the Lua command permissions. Every worker in a group must use the same source identity, metadata protocol and rejection destination. Reserve the group state namespace for the adapter.++## Runtime and recovery++An empty blocking poll keeps the processor live. Socket loss, I/O failure or timeout consumes a finite reconnect budget. Exhausted polling retries, Redis command rejection and a missing group are processor failures. A reader detects cursor rollback from Redis metadata and checks application-provided producer evidence before admission. Redis ID distance cannot prove that an event was trimmed. Supply a revision, predecessor or generation when the application needs continuity across trim or stream recreation.++Reader retry holds subsequent entries behind the current one. Group retry stores a deadline on Redis and releases the local processing slot. Any worker, including the one that scheduled the retry, can reclaim the entry after that deadline. The group counts deliveries and claims toward the retry limit. On exhaustion either mode writes a `MaxRetriesExceeded` dead-letter record when a destination is configured. The reader commits afterward and the group acknowledges the entry. Without a destination, the processor stops with the checkpoint before the entry or with the entry still pending in the group. Recovery alternates new and pending work and caps pending detail pages. Abandoned work must meet the minimum idle interval and any lease deadline, while an explicit retry needs only its retry deadline. Optional pending telemetry reports total depth and the highest idle time in the sampled page. Redis summary work grows with the number of consumers, so enable it selectively for large groups.++A stale callback leaves current work untouched. Permanent failure writes an idempotent hash record before committing progress. With no destination, permanent failure stops the processor with the cursor or pending entry intact. An explicit halt also preserves that progress boundary. Missing pending payloads call the application loss observer before acknowledging the unrecoverable row. The application owns any replay from the failure destination.++Use persistence that can retain stream, group, attempt and rejection state together. If Redis rolls back acknowledged or pending state during restore or failover, applications may observe redelivery or lost work. Prevent eviction of all those keys and retain unread and pending payloads until they can be processed. Keep a failure record through its replay horizon and give a recreated stream a new source generation when identities span lifetimes. Maintain group positions and live consumer ownership through the adapter protocol. When retention removes a payload, preserve the pending reference so the adapter can report the loss. Operations that delete pending references can leave attempt hashes for operator cleanup. Unused Redis consumer records can be removed independently when an operator has confirmed that they own no pending entries.++Checkpoint callbacks own durable write consistency. Use one writer per checkpoint or a conditional write that accepts an already-committed identical value after reply loss. Shibuya owns runner scheduling and graceful shutdown deadlines. Adapter counters and pending samples carry no stream keys, values or credentials. The application owns its telemetry callbacks and tracing resources and should keep callbacks prompt and successful.++OpenTelemetry uses `traceparent` and optional `tracestate` stream fields by default. Set `telemetry` on the mode configuration to override the reader’s `LinkOnly` or the group worker’s `ParentAndLink` policy. Consumer spans identify Redis as the messaging system and use the native entry ID in the message ID tag. Rejection values written by a traced finalizer retain that consumer’s W3C context.
+ docs/initial-spec.md view
@@ -0,0 +1,84 @@+---+title: "Shibuya Redis Streams Adapter — Initial Specification"+type: library-spec+status: proposed+canonical: mori://shinzui/shibuya-redis-adapter/docs/initial-spec+---++# Shibuya Redis Streams Adapter++## Purpose++A Haskell application should be able to attach a Shibuya processor to a Redis Stream and choose who receives each entry. A search indexer and a reporting projection may each need every event. A pool of thumbnail workers should share jobs and recover work when a worker disappears. A live view may need only the changes after a snapshot. The adapter must support all three uses with ordinary Shibuya handlers.++The proposed package is `shibuya-redis-adapter`, released independently of Shibuya. Its first-release contract covers independent readers and consumer groups against a single Redis primary. One adapter instance reads one stream. Applications can compose instances through Shibuya. Redis Cluster, cross-stream ordering, producer transactions and queue administration are outside the initial release. Package bounds and the supported Redis version range will be established against released dependencies and tested Redis servers.++## Delivery modes++| Contract | Independent reader | Consumer-group worker |+|---|---|---|+| Who receives an entry? | Every interested reader whose starting position includes it. | One member receives the initial assignment in each group. Another member may take over pending work. |+| Typical use | Rebuild a projection, tail changes, feed subscribers on multiple replicas. | Distribute jobs across processes or run several competing workers for one projection. |+| Where is progress kept? | A reader-local completed cursor, optionally persisted through an application checkpoint. | Redis holds the group's delivery position and pending entries. Successful finalization acknowledges each entry. |+| What order is promised? | Serial processing preserves stream order, including retries. | Redis assigns new entries in stream order. Concurrent execution, retries and claims can change completion order. |+| What survives a crash? | A replacement reader resumes after the last saved checkpoint, while entries are retained. | A replacement worker recovers unacknowledged, retained entries through pending-entry recovery. |++### Independent readers++Use `XREAD` with an exclusive position. Expose three explicit starts: earliest retained, after a supplied stream ID, and live tail. Resolve live tail to a concrete position once at startup, including for an empty stream. Reuse the concrete position on later polls and reconnects so an append between polls remains visible. Reading or finalizing on one reader leaves every other reader's position and the source entry intact. [Redis XREAD](https://redis.io/docs/latest/commands/xread/)++Expose the **completed cursor** separately from the last fetched ID. Prefetch may read B while A is running. A crash at that point must allow A to be delivered again. For restartable projections, provide a way to load and save a checkpoint under a caller-supplied reader identity and stream identity. A failed save leaves progress retryable. The application must arrange exclusive ownership or conditional writes if two processes can update the same durable checkpoint. An ephemeral subscriber can keep its cursor in memory.++A Redis ID orders entries within a stream. It cannot establish that every intervening event still exists. Preserve stream identity, entry ID and raw fields so consumers can check a producer revision, predecessor or generation. Expose detected loss of history or stream replacement as a distinct outcome. Document what is unknowable after deletion, trimming or recreation without producer evidence. A strict projection can stop and rebuild. A live view can resnapshot. A best-effort tailer can explicitly elect to continue.++### Consumer groups++Use `XREADGROUP` with acknowledgements enabled. Require an explicit group and a consumer identity unique to the running worker instance. Support attaching to an existing group and an opt-in create-if-absent policy with an explicit initial position. Concurrent creation must preserve the existing group's position. Acquisition and reconnect must never reset an existing group. [Redis XGROUP CREATE](https://redis.io/docs/latest/commands/xgroup-create/) and [XREADGROUP](https://redis.io/docs/latest/commands/xreadgroup/)++A delivered entry stays in the group's pending entries list until finalization or an explicit recovery action. Bound recovery work per poll and share capacity between new and abandoned work so both make progress. Reclaim entries after a configurable minimum idle interval. Long-running handlers need an ownership-checked extension of that interval or a documented handling-time limit. If retention removes a pending payload, surface a loss diagnostic with its identity and the chosen recovery action. A missing payload cannot yield a successful handler result. [Redis XPENDING](https://redis.io/docs/latest/commands/xpending/) and [XAUTOCLAIM](https://redis.io/docs/latest/commands/xautoclaim/)++Fence late callbacks after a claim. For example, worker A stalls, B claims the entry, then A returns success. Redis `XACK` identifies the stream, group and entry, so an unguarded call from A could clear B's pending work. Verify ownership and delivery generation atomically with acknowledgement, retry scheduling, lease extension and dead-letter finalization. This must hold even if ownership moves away and back. A stale callback leaves the current attempt untouched. Application effects may still occur twice across a crash or claim. Handlers that send mail, charge an account or write another database need their own idempotency key. [Redis XACK](https://redis.io/docs/latest/commands/xack/)++## Shibuya interface and message identity++Provide public constructors in `Shibuya.Adapter.Redis` with distinct configuration types for each mode. Each constructs a standard `Adapter es msg` with an effectful source, shutdown action, adapter name and configurable Shibuya telemetry. Use hedis for Redis access. A caller may supply a connection pool. Document which connections the adapter acquires and releases. The interface and envelope contract belong to `mori://shinzui/shibuya/packages/shibuya-core`. The Redis client is `mori://informatikr/hedis/packages/hedis`.++The default payload preserves the stream key, Redis entry ID and ordered binary field/value pairs, including duplicate field names. Consumers can opt into a typed decoder or header convention. Decoding errors must retain the source identity and follow the configured permanent-failure policy. Build a stable Shibuya message ID from the stream identity and entry ID with unambiguous encoding. A reclaimed or retried entry keeps its ID. Applications that recreate stream keys must include a source generation if deduplication spans those lifetimes. Expose a zero-based attempt count only where the backend or adapter can support it. Keep producer event time distinct from Redis entry ID time.++Shibuya owns scheduling, supervision and the call to finalize each decision. The adapter owns Redis progress, reader-local retry and recovery of pending group entries. Admission can suppress a known superseded delivery. Because ownership can change while the handler runs, the finalizer still needs its own fence. The relevant architecture is `mori://shinzui/shibuya/docs/architecture`.++## Handler decisions++| Shibuya decision | Independent reader | Consumer-group worker |+|---|---|---|+| `AckOk` | Advance the completed cursor through the contiguous successful prefix and persist it when configured. | Acknowledge the current owned attempt. Leave the source entry available to other groups and readers. |+| `AckRetry delay` | Retry the same entry after the delay. In serial mode hold later entries behind it. | Keep the work recoverable and honor the retry due time across workers and process restarts. Other jobs can proceed. |+| `AckDeadLetter reason` | With a configured destination, record source identity and reason, then advance. Without one, halt at the rejected entry. | With a configured destination, record the failure and acknowledge the owned attempt as one recoverable operation. Without one, halt and leave the entry pending. |+| `AckHalt reason` | Stop this processor with its completed cursor before the halted entry. | Stop this processor and leave the entry available for pending recovery. Sibling processors continue under their configured supervision. |++A repeated finalizer after a lost Redis reply must yield the same logical result. Preserve Shibuya's structured reason code and bounded detail in a dead-letter record. Use an idempotency identity scoped to the logical reader or group and source entry, so two groups can independently reject the same input. A checkpoint failure after a successful dead-letter write must allow a retry without creating a second logical record. Document the recovery of each partially completed operation and the retention window of any deduplication metadata. Applications own replay from a dead-letter destination.++## Operations and compatibility++Bound blocking-read duration, prefetch, in-flight work, retries and pending-recovery scans. Reserve connection capacity for acknowledgement, recovery and shutdown while reads block. Reject unsupported ordering or concurrency combinations before admitting work. Document which failures are transient, which stop a processor, and how to distinguish an idle stream from a lost Redis connection. Shutdown stops new polls, permits admitted finalizers to drain within the Shibuya deadline, and releases adapter-owned resources. Repeated shutdown is safe.++Use Shibuya's telemetry options. Report delivered, acknowledged, retried, reclaimed, superseded and dead-lettered counts, checkpoint failures and detected retention gaps. Expose pending backlog and age where available. Keep labels bounded and payloads, credentials and application-specific stream keys out of default telemetry.++The project follows `mori://shinzui/haskell-jitsurei/docs/core-standards` and uses `mori://shinzui/seihou-modules/seihou/modules/nix-haskell-flake` for development and real-Redis tests. Publish the tested Redis capabilities, server versions, and the minimum commands or ACL permissions for each mode. State the persistence, eviction and retention assumptions behind recovery guarantees. A Redis restore that rolls back group state or a stream that trims outstanding jobs can invalidate those guarantees.++## Acceptance scenarios++Run these cases with a real Redis server and the Shibuya processor runner. Use independent connections for competing actors and synchronize at delivery, claim and finalization boundaries so timing alone does not determine success.++| Scenario | Observable result |+|---|---|+| Independent projections | An indexer and a reporting projection read the same three IDs. Pause one, append another entry and restart it from its saved cursor. Both finish with the same ordered IDs and independent checkpoints. |+| Work pool and separate group | Two workers in one group divide jobs under normal operation. A worker in another group can process the entire input. Successful acknowledgements in either group leave the other group's progress intact. |+| Worker takeover | Stop A after delivery and let B claim its pending job. Release A's delayed finalizer. B still owns the job and completes it. Repeat with ownership moving back to A under a new attempt. |+| Retry and permanent failure | Request a delayed retry, restart a worker, then permanently reject the retried entry. It cannot run early. Drop the finalizer reply and retry: one logical dead-letter record exists with the original source identity. |+| Projection crash | Commit an application effect, then crash before saving its checkpoint. The same message ID is redelivered and an idempotent handler produces one logical effect. |+| Snapshot handover | Capture a roster and cursor, then append a change before attaching two independent Kehai readers. Both receive the change or the application detects lost continuity and resnapshots. Kehai owns lease updates, viewer authorization and SSE. Its contract is `mori://shinzui/kehai/docs/initial-spec`. |+| Retention and wire fidelity | Trim an unread change and a pending job. Observe the defined gap evidence or missing-payload outcome. A separate binary entry with repeated field names round-trips unchanged. |+| Bounded lifecycle | Hold a read open on an idle stream, stall a handler and disconnect Redis. Verify bounded intake and shutdown, intact completed progress, recoverable pending work, and continued service for an independent reader after reconnection. |++Initial release evidence includes a buildable consumer example for each delivery mode and the compatibility matrix used to run these scenarios. Redis deployment automation, domain-specific stream schemas, SSE, recurring job scheduling and a general producer API belong to their respective applications or follow-up specifications.
+ docs/user/delivery-outcomes.md view
@@ -0,0 +1,25 @@+---+type: Reference+title: "Delivery outcomes and trace context"+description: "Look up progress, dead-letter and tracing behavior for a reader or worker delivery."+generated:+  by: codex-cli/0.172.0+  at: "2026-11-25T14:35:06Z"+docId: DOC-4+tags: ["acknowledgement", "dead-letter", "opentelemetry"]+---++# Delivery outcomes and trace context++| Handler outcome | Independent reader | Group worker |+|---|---|---|+| `AckOk` | Saves the completed cursor. | Acknowledges the current attempt. |+| `AckRetry` | Holds the current entry until retry. | Leaves it pending until the retry deadline. |+| `AckDeadLetter` | Writes the rejection before advancing. | Writes the rejection before acknowledging the current attempt. |+| `AckHalt` | Stops with the checkpoint before the entry. | Stops with the entry pending. |++Set `readerDeadLetters` or `groupDeadLetters` to a Redis hash key to enable rejection storage. A permanent decode failure also takes the rejection path. Exhaustion of `readerRetryLimit` or `groupRetryLimit` uses reason `MaxRetriesExceeded`. Without a destination, rejection or exhaustion stops the processor at the current progress boundary.++`rejectionRecord` describes the binary field and value. The field scopes an entry to its reader or group. Redis keeps the first record on a repeated write. The value carries the reason, original ordered field pairs and any consumer trace context available at finalization. Applications own retention and replay.++Put a W3C `traceparent` and optional `tracestate` in the producer's stream fields. With tracing enabled, readers default to `LinkOnly` and start a new trace linked to the producer. Group workers default to `ParentAndLink` and join the producer trace. Override `telemetry.traceCorrelation` on the configuration or supply `readerTraceContext` / `groupTraceContext` for another field convention. Consumer spans use the native Redis entry ID for `messaging.message.id`. The envelope's idempotency key also incorporates source identity.
+ docs/user/index.md view
@@ -0,0 +1,17 @@+---+okf_version: "0.2"+---++# Files++- [profile.dhall](profile.dhall)++# Guide++- [Resume an ordered projection](resume-a-projection.md) - Persist a reader checkpoint and decide how to handle gaps after a restart or snapshot.+- [Run a recoverable worker pool](run-a-worker-pool.md) - Configure group position, concurrency and lease renewal for competing workers.+- [Connect a Redis stream to a processor](start-a-processor.md) - Choose a delivery mode and run its processor for the lifetime of a Redis runtime.++# Reference++- [Delivery outcomes and trace context](delivery-outcomes.md) - Look up progress, dead-letter and tracing behavior for a reader or worker delivery.
+ docs/user/log.md view
@@ -0,0 +1,4 @@+# Bundle Update Log++## 2026-11-25+* **Adoption**: Adopted the `documentation.userDocumentation` export of `mori://shinzui/okf-profiles` (v0.25.0). Added DOC-1 through DOC-4 covering runtime setup, ordered checkpoints, worker recovery, delivery outcomes and trace context.
+ docs/user/profile.dhall view
@@ -0,0 +1,14 @@+-- OKF profile descriptor written by `okf profile init`.+--+-- Profile: documentation.userDocumentation+-- Source:  https://raw.githubusercontent.com/shinzui/okf-profiles/v0.25.0/package.dhall+--+-- Existing hashes are preserved and unhashed remote value imports are frozen.+-- Local and environment inputs remain live; this is not a portable snapshot.+-- To update remote imports, remove their hashes and run `dhall freeze profile.dhall`.+-- Never hand-write a sha256 value.+let registry =+      https://raw.githubusercontent.com/shinzui/okf-profiles/v0.25.0/package.dhall+        sha256:ec74cc6f7b8ee1a5af81ee7fc8804f35cf2c9ba4010671d9e881da72eb6719d3++in  registry.documentation.userDocumentation
+ docs/user/resume-a-projection.md view
@@ -0,0 +1,24 @@+---+type: Guide+title: "Resume an ordered projection"+description: "Persist a reader checkpoint and decide how to handle gaps after a restart or snapshot."+generated:+  by: codex-cli/0.172.0+  at: "2026-11-25T14:35:06Z"+docId: DOC-2+tags: ["reader", "checkpoint", "snapshot"]+---++# Resume an ordered projection++Start with `rawReaderConfig`. Set `checkpointStore = Just store` for a projection that survives process restarts. A stored checkpoint wins over every start policy. With an empty store, choose `Earliest` for retained history, `Live` for future entries, or `After checkpoint` for the suffix following a snapshot.++1. Key the store by the logical reader name and full source identity. Persist the completed entry ID and its continuity evidence together.+2. Give the store a single writer, or condition each save on the expected previous checkpoint. Accept an identical already-saved value so a lost write reply can be retried.+3. Return `AckOk` after the projection effect commits. A crash between that commit and the checkpoint save can replay the entry. Record the message ID with the effect in the same transaction when duplicates matter.++`readerProcessor` finalizes entries in order. A delayed retry holds later entries even when they have already been fetched. Use a handler that can complete one entry at a time.++For snapshot handover, have the producer supply a predecessor, revision or generation that the projection can check. Return the next evidence and any gap description from `checkContinuity`. Redis IDs may legitimately skip values. The adapter also checks for a stream tail behind the checkpoint. `onReaderGap` defaults to `StopAndRebuild`. Return `Resnapshot` to stop for application-managed snapshot replacement, or `BestEffort` when the projection can accept the gap.++The single-owner file store in `examples/Reader.hs` demonstrates cursor persistence. It stores no producer continuity evidence.
+ docs/user/run-a-worker-pool.md view
@@ -0,0 +1,26 @@+---+type: Guide+title: "Run a recoverable worker pool"+description: "Configure group position, concurrency and lease renewal for competing workers."+generated:+  by: codex-cli/0.172.0+  at: "2026-11-25T14:35:06Z"+docId: DOC-3+tags: ["consumer-group", "lease", "recovery"]+---++# Run a recoverable worker pool++Build a worker with `newGroupWorker rt (rawGroupConfig name source group consumer start)`, then pass `groupProcessor worker handler` to the runner. Use the same source identity, group and dead-letter destination for all instances. Generate a unique consumer name on each launch as in `examples/Worker.hs`.++| Start policy | When to use it |+|---|---|+| `CreateIfAbsent (EntryId 0 0)` | Create a missing group to process retained history. |+| `CreateAtTailIfAbsent` | Create a missing group for future entries. |+| `AttachExisting` | Require an already provisioned group. |++Creation preserves an existing group's position. Set `groupInFlight` to the maximum outstanding deliveries per instance (default 1). Workers can complete different entries out of order. A separate group has its own position and pending list.++For a long-running handler, extend the message lease before the minimum idle interval expires (default 30 seconds). Abandoned work becomes reclaimable after the idle interval and any extended deadline. An explicit retry releases the local slot and uses its own Redis-time deadline. Any worker, including the original worker, can pick it up. Delivery and claim attempts count toward the retry budget.++A callback from an older attempt cannot acknowledge, retry or reject a newer attempt, even if ownership has returned to the original consumer. Deduplicate external effects independently because an old handler can still finish. Retain pending payloads through the recovery window and install `onMissingPending` to record a missing payload before the pending reference is acknowledged.
+ docs/user/start-a-processor.md view
@@ -0,0 +1,41 @@+---+type: Guide+title: "Connect a Redis stream to a processor"+description: "Choose a delivery mode and run its processor for the lifetime of a Redis runtime."+generated:+  by: codex-cli/0.172.0+  at: "2026-11-25T14:35:06Z"+docId: DOC-1+tags: ["redis-streams", "integration", "shutdown"]+---++# Connect a Redis stream to a processor++Choose a reader when every projection needs every retained entry. Give each projection its own checkpoint identity. Choose a consumer group when several instances should share the jobs in a stream. Give those instances the same group name and a distinct consumer name on each start.++Import `Shibuya.Adapter.Redis` for the adapter and `Shibuya` for the runner. Set `SourceIdentity` to an application namespace, an optional generation, and the binary stream key. Change the generation if a rebuilt stream can reuse old IDs.++For example, this reader processes every retained entry and acknowledges it. It uses the no-op tracing interpreter.++```haskell+{-# LANGUAGE OverloadedStrings #-}++import Effectful (liftIO, runEff)+import Shibuya+import Shibuya.Adapter.Redis++runProjection connection =+  withRedisRuntime (OwnPools connection) defaultRuntimeOptions $ \rt -> do+    let source = SourceIdentity "inventory" Nothing "stock-events"+    reader <- newReader rt (rawReaderConfig "stock" "projection" source Earliest)+    runEff $ runTracingNoop $ do+      result <- runApp defaultAppConfig+        [(ProcessorId "stock", readerProcessor reader (const (pure AckOk)))]+      either (liftIO . fail . show) waitApp result+```++To process application data, replace the handler and set `readerDecode` or `groupDecode` on the raw configuration. The decoder receives field/value pairs in Redis order, including duplicate names and non-text bytes. Use the envelope's stable message ID as the idempotency key when recording an effect that must survive a crash.++Allocate one runtime per processor. `BorrowCommands` lets the application supply a command pool for the same primary and database. Both connection modes reserve a separate read connection. Run graceful shutdown inside the runtime bracket so acknowledgements and checkpoint saves can finish.++The repository README walks through running both executables against the local Redis socket. To configure durable progress, follow [Resume an ordered projection](resume-a-projection.md) or [Run a recoverable worker pool](run-a-worker-pool.md).
+ examples/Example.hs view
@@ -0,0 +1,62 @@+module Example (Effects, connection, source, runExample, parseCount, bytes) where++import Control.Concurrent (newEmptyMVar, putMVar, readMVar)+import Control.Monad (unless, void, when)+import Data.ByteString (ByteString)+import Data.IORef+import Data.Set qualified as Set+import Data.Text qualified as Text+import Data.Text.Encoding qualified as Text+import Database.Redis qualified as Redis+import Effectful (IOE, liftIO, runEff)+import Effectful.Exception qualified as E+import Shibuya+import Shibuya.Adapter.Redis+import System.Timeout (timeout)+import Text.Read (readMaybe)++type Effects = '[Tracing, IOE]++bytes :: String -> ByteString+bytes = Text.encodeUtf8 . Text.pack++connection :: FilePath -> ConnectionSource+connection socket = OwnPools (Redis.defaultConnectInfo {Redis.connectAddr = Redis.ConnectAddrUnixSocket socket})++source :: String -> SourceIdentity+source stream = SourceIdentity "shibuya-example" Nothing (bytes stream)++parseCount :: String -> IO Int+parseCount input = case readMaybe input of+  Just value | value > 0 -> pure value+  _ -> fail "COUNT must be a positive integer"++runExample :: Int -> IO () -> (Handler Effects RedisEntry -> QueueProcessor Effects) -> IO ()+runExample count stop processor = do+  finished <- newEmptyMVar+  seen <- newIORef Set.empty+  let handle message = liftIO $ do+        let envelope = message.envelope+            -- The stable ID is an application idempotency key. Use durable+            -- storage for an external effect that must survive restarts.+            MessageId effectKey = envelope.messageId+        effectCount <- atomicModifyIORef' seen $ \keys ->+          if Set.member effectKey keys+            then (keys, Nothing)+            else let updated = Set.insert effectKey keys in (updated, Just (Set.size updated))+        case effectCount of+          Nothing -> pure ()+          Just completed -> do+            putStrLn (showEntry envelope.payload.entryId <> " " <> Text.unpack effectKey)+            when (completed == count) (stop >> putMVar finished ())+        pure AckOk+  runEff $ runTracingNoop $ do+    result <- runApp defaultAppConfig [(ProcessorId "example", processor handle)]+    app <- either (liftIO . fail . show) pure result+    flip E.finally (void (stopAppGracefully (ShutdownConfig 1 2) app)) $ do+      ready <- liftIO (timeout 30000000 (readMVar finished))+      unless (ready == Just ()) (liftIO (fail "timed out waiting for entries"))+      stopAppGracefully (ShutdownConfig 2 4) app >>= \drained ->+        unless drained (liftIO (fail "processor did not drain"))+  where+    showEntry = Text.unpack . Text.decodeUtf8 . renderEntryId
+ examples/Reader.hs view
@@ -0,0 +1,55 @@+module Main (main) where++import Data.ByteString qualified as BS+import Data.ByteString.Char8 qualified as C8+import Example+import Shibuya.Adapter.Redis+import System.Directory (doesFileExist, renameFile)+import System.Environment (getArgs)+import System.FilePath (takeDirectory)+import System.IO (hClose)+import System.IO.Temp (withTempFile)++usage :: String+usage = "reader-example SOCKET STREAM CHECKPOINT_FILE COUNT"++main :: IO ()+main =+  getArgs >>= \case+    ["--help"] -> putStrLn usage+    [socket, stream, file, countArg] -> do+      count <- parseCount countArg+      let src = Example.source stream+          config =+            (rawReaderConfig "reader-example" "projection" src Earliest)+              { checkpointStore = Just (fileStore file)+              }+      withRedisRuntime (connection socket) defaultRuntimeOptions {prefetchLimit = 1} $ \runtime -> do+        reader <- newReader runtime config+        runExample count (stopIntake runtime) (readerProcessor reader)+    _ -> fail usage++-- One process owns this file. Atomically replacing it keeps the cursor usable+-- after an interrupted write. The demo uses no producer continuity evidence.+fileStore :: FilePath -> CheckpointStore+fileStore file = CheckpointStore load save+  where+    scope name identity = C8.pack (show (name, identity))+    load name identity = do+      exists <- doesFileExist file+      if exists+        then do+          content <- C8.lines <$> BS.readFile file+          case content of+            [version, savedScope, rawId]+              | version == "shibuya-example-v1",+                savedScope == scope name identity,+                Just position <- parseEntryId rawId ->+                  pure (Just (Checkpoint position Nothing))+            _ -> fail "checkpoint file is malformed or belongs to a different reader"+        else pure Nothing+    save name identity _ checkpoint =+      withTempFile (takeDirectory file) ".checkpoint" $ \temporary handle -> do+        BS.hPut handle (C8.unlines ["shibuya-example-v1", scope name identity, renderEntryId checkpoint.position])+        hClose handle+        renameFile temporary file
+ examples/Worker.hs view
@@ -0,0 +1,29 @@+module Main (main) where++import Data.ByteString.Builder qualified as Builder+import Data.ByteString.Lazy qualified as LBS+import Example+import Shibuya.Adapter.Redis+import System.Entropy (getEntropy)+import System.Environment (getArgs)++usage :: String+usage = "worker-example SOCKET STREAM GROUP (attach|earliest|tail) COUNT"++main :: IO ()+main =+  getArgs >>= \case+    ["--help"] -> putStrLn usage+    [socket, stream, group, positioning, countArg] -> do+      count <- parseCount countArg+      start <- case positioning of+        "attach" -> pure AttachExisting+        "earliest" -> pure (CreateIfAbsent (EntryId 0 0))+        "tail" -> pure CreateAtTailIfAbsent+        _ -> fail usage+      instanceId <- LBS.toStrict . Builder.toLazyByteString . Builder.byteStringHex <$> getEntropy 16+      let config = rawGroupConfig "worker-example" (Example.source stream) (bytes group) instanceId start+      withRedisRuntime (connection socket) defaultRuntimeOptions {prefetchLimit = 1} $ \runtime -> do+        worker <- newGroupWorker runtime config+        runExample count (stopIntake runtime) (groupProcessor worker)+    _ -> fail usage
+ shibuya-redis-adapter.cabal view
@@ -0,0 +1,169 @@+cabal-version: 3.12+name: shibuya-redis-adapter+version: 0.1.0.0+synopsis: Redis Streams adapter for Shibuya+description:+  Connect Shibuya processors to Redis Streams using either an independent+  ordered reader with checkpoints or a consumer-group worker with fenced+  pending-entry recovery. Both modes support dead-lettering and OpenTelemetry+  trace correlation.++category: Concurrency, Database+author: Nadeem Bitar+maintainer: nadeem@gmail.com+copyright: 2026 Nadeem Bitar+homepage: https://github.com/shinzui/shibuya-redis-adapter+bug-reports: https://github.com/shinzui/shibuya-redis-adapter/issues+license: MIT+license-file: LICENSE+tested-with: ghc ==9.12.4+build-type: Simple+extra-doc-files:+  CHANGELOG.md+  README.md+  docs/capabilities/*.md+  docs/user/*.md++extra-source-files:+  docs/capabilities/profile.dhall+  docs/compatibility.md+  docs/initial-spec.md+  docs/user/profile.dhall++source-repository head+  type: git+  location: https://github.com/shinzui/shibuya-redis-adapter.git++flag examples+  description: Build the reader and worker example programs.+  default: False+  manual: True++common shared+  default-language: GHC2024+  default-extensions:+    DeriveAnyClass+    DuplicateRecordFields+    OverloadedLabels+    OverloadedRecordDot+    OverloadedStrings++  ghc-options:+    -Wall+    -Wcompat+    -Widentities+    -Wincomplete-uni-patterns+    -Wincomplete-record-updates+    -Wredundant-constraints+    -Wmissing-export-lists+    -Wpartial-fields+    -Wmissing-deriving-strategies++  build-depends:+    base ^>=4.21,+    bytestring ^>=0.12,+    hedis ^>=0.16.4,+    shibuya-core ^>=0.13.0.1,+    text ^>=2.1,++library+  import: shared+  hs-source-dirs: src+  exposed-modules:+    Shibuya.Adapter.Redis+    Shibuya.Adapter.Redis.Internal++  other-modules:+    Shibuya.Adapter.Redis.Adapter+    Shibuya.Adapter.Redis.Connection+    Shibuya.Adapter.Redis.DeadLetter+    Shibuya.Adapter.Redis.Group+    Shibuya.Adapter.Redis.Group.Scripts+    Shibuya.Adapter.Redis.Reader+    Shibuya.Adapter.Redis.Types++  build-depends:+    async ^>=2.2,+    containers ^>=0.7,+    effectful-core (>=2.6.1 && <2.7) || (>=2.7.1.1 && <2.8),+    entropy ^>=0.4.1,+    hs-opentelemetry-api ^>=1.0,+    stm ^>=2.5,+    streamly-core ^>=0.3,+    unordered-containers ^>=0.2,++common redis-integration+  import: shared+  other-modules: Fixture+  hs-source-dirs: test+  ghc-options: -threaded+  build-depends:+    async ^>=2.2,+    directory ^>=1.3,+    effectful-core (>=2.6.1 && <2.7) || (>=2.7.1.1 && <2.8),+    filepath ^>=1.5,+    process ^>=1.6,+    shibuya-redis-adapter,+    streamly-core ^>=0.3,+    temporary ^>=1.3,++test-suite runner-fixture+  import: redis-integration+  type: exitcode-stdio-1.0+  main-is: Main.hs+  build-depends:+    hs-opentelemetry-api ^>=1.0,+    unordered-containers ^>=0.2,++test-suite reader-integration+  import: redis-integration+  type: exitcode-stdio-1.0+  main-is: ReaderSpec.hs++test-suite group-integration+  import: redis-integration+  type: exitcode-stdio-1.0+  main-is: GroupSpec.hs++test-suite release-integration+  import: redis-integration+  type: exitcode-stdio-1.0+  main-is: ReleaseSpec.hs++test-suite telemetry-integration+  import: redis-integration+  type: exitcode-stdio-1.0+  main-is: TelemetrySpec.hs+  build-depends:+    hs-opentelemetry-api ^>=1.0,+    hs-opentelemetry-exporter-in-memory ^>=1.0,+    hs-opentelemetry-sdk ^>=1.0,++common example+  import: shared+  other-modules: Example+  hs-source-dirs: examples+  ghc-options: -threaded+  build-depends:+    containers ^>=0.7,+    effectful-core (>=2.6.1 && <2.7) || (>=2.7.1.1 && <2.8),+    shibuya-redis-adapter,++executable reader-example+  import: example+  main-is: Reader.hs++  if !flag(examples)+    buildable: False+  build-depends:+    directory ^>=1.3,+    filepath ^>=1.5,+    temporary ^>=1.3,++executable worker-example+  import: example+  main-is: Worker.hs++  if !flag(examples)+    buildable: False+  build-depends: entropy ^>=0.4.1
+ src/Shibuya/Adapter/Redis.hs view
@@ -0,0 +1,107 @@+-- | Redis Streams readers and consumer-group workers for Shibuya.+--+-- Keep 'withRedisRuntime' around construction, processing and graceful+-- shutdown. Attach one reader or worker per runtime. Each runtime uses a+-- dedicated Redis read connection and an owned or borrowed command pool.+--+-- @+-- {-# LANGUAGE OverloadedStrings #-}+--+-- import Effectful (liftIO, runEff)+-- import Shibuya+-- import Shibuya.Adapter.Redis+--+-- runReader connection = withRedisRuntime (OwnPools connection) defaultRuntimeOptions $ \rt -> do+--   let source = SourceIdentity "inventory" Nothing "inventory-events"+--   reader <- newReader rt (rawReaderConfig "projection" "search-index" source Earliest)+--   run (readerProcessor reader (const (pure AckOk)))+--+-- runWorker connection consumer = withRedisRuntime (OwnPools connection) defaultRuntimeOptions $ \rt -> do+--   let source = SourceIdentity "images" Nothing "image-jobs"+--   worker <- newGroupWorker rt (rawGroupConfig "worker" source "thumbnails" consumer (CreateIfAbsent (EntryId 0 0)))+--   run (groupProcessor worker (const (pure AckOk)))+--+-- run processor = runEff $ runTracingNoop $ do+--   result <- runApp defaultAppConfig [(ProcessorId "redis", processor)]+--   either (liftIO . fail . show) waitApp result+-- @+--+-- The reader resumes after its completed checkpoint and commits in stream+-- order. A worker uses Redis group state and its pending entries list. Give+-- each running worker a unique consumer name. Extend its lease before a+-- long-running handler reaches the recovery deadline.+--+-- * 'Shibuya.AckOk' commits the reader checkpoint or acknowledges the pending worker entry.+-- * 'Shibuya.AckRetry' delays the current reader entry or makes a pending worker entry eligible at the retry deadline. A thrown handler exception requests an immediate retry.+-- * 'Shibuya.AckDeadLetter' writes the failure to the configured hash before committing or acknowledging.+-- * 'Shibuya.AckHalt' stops intake and leaves the current entry at its existing progress boundary.+--+-- On retry exhaustion, a configured hash receives 'Shibuya.MaxRetriesExceeded'+-- and the processor continues. Without a hash, exhaustion or rejection stops+-- the processor with the checkpoint before the entry or the entry still pending.+--+-- Producers can write W3C @traceparent@ and optional @tracestate@ fields.+-- Readers use 'LinkOnly' and group workers use 'ParentAndLink' by default.+-- Set the mode configuration’s @telemetry@ field to override correlation.+module Shibuya.Adapter.Redis+  ( -- * Runtime+    withRedisRuntime,+    ConnectionSource (..),+    RuntimeOptions (..),+    defaultRuntimeOptions,+    RedisRuntime,+    stopIntake,++    -- * Sources and entries+    SourceIdentity (..),+    EntryId (..),+    renderEntryId,+    parseEntryId,+    RedisEntry (..),++    -- * Independent readers+    ReaderConfig (..),+    ReaderStart (..),+    Checkpoint (..),+    CheckpointStore (..),+    GapEvidence (..),+    ReaderGap (..),+    GapAction (..),+    Reader (..),+    rawReaderConfig,+    newReader,+    readerProcessor,++    -- * Consumer groups+    GroupConfig (..),+    GroupStart (..),+    Group (..),+    MissingPending (..),+    rawGroupConfig,+    newGroupWorker,+    groupProcessor,++    -- * Events and errors+    AdapterEvent (..),+    AdapterError (..),+    ReaderError (..),+    GroupError (..),++    -- * Dead-letter records+    RejectionOwner (..),+    rejectionRecord,++    -- * Telemetry+    AdapterTelemetry (traceCorrelation),+    defaultAdapterTelemetry,+    TraceCorrelation (..),+    defaultTraceContext,+  )+where++import Shibuya (AdapterTelemetry (traceCorrelation), TraceCorrelation (..), defaultAdapterTelemetry)+import Shibuya.Adapter.Redis.Connection+import Shibuya.Adapter.Redis.DeadLetter+import Shibuya.Adapter.Redis.Group+import Shibuya.Adapter.Redis.Reader+import Shibuya.Adapter.Redis.Types
+ src/Shibuya/Adapter/Redis/Adapter.hs view
@@ -0,0 +1,18 @@+module Shibuya.Adapter.Redis.Adapter (mkRedisAdapter) where++import Data.Text (Text)+import Effectful (Eff, IOE, liftIO, (:>))+import Shibuya (Adapter (..), AdapterTelemetry, Ingested)+import Shibuya.Adapter.Redis.Connection+import Streamly.Data.Stream (Stream)++-- | Attach a mode's delivery stream to the runner. Keep the runtime bracket+-- around the application until all finalizers have drained.+mkRedisAdapter :: (IOE :> es) => RedisRuntime -> Text -> AdapterTelemetry -> Stream (Eff es) (Ingested es a) -> Adapter es a+mkRedisAdapter runtime name settings deliveries =+  Adapter+    { adapterName = name,+      source = deliveries,+      shutdown = liftIO (stopIntake runtime),+      telemetry = settings+    }
+ src/Shibuya/Adapter/Redis/Connection.hs view
@@ -0,0 +1,214 @@+module Shibuya.Adapter.Redis.Connection+  ( ConnectionSource (..),+    RuntimeOptions (..),+    defaultRuntimeOptions,+    RedisRuntime (options, stopped),+    AdapterError (..),+    withRedisRuntime,+    withRuntimeAttachment,+    stopIntake,+    runCommand,+    DeliveryMode (..),+    validateDeliveryPolicy,+    readBatchOptions,+    pollStream,+    retryConnection,+    streamEntries,+    streamRecord,+  )+where++import Control.Concurrent (threadDelay)+import Control.Concurrent.Async (race)+import Control.Concurrent.STM (TVar, atomically, check, newTVarIO, readTVar, readTVarIO, writeTVar)+import Control.Exception (Exception, Handler (..), IOException, bracket, catches, evaluate, mask, onException, throwIO)+import Control.Monad (unless)+import Database.Redis qualified as Redis+import GHC.Generics (Generic)+import Shibuya (Concurrency, OrderingPolicy (..), PolicyError (..), validatePolicy)+import Shibuya.Adapter.Redis.Types+import System.Timeout (timeout)++-- | Create a dedicated read pool in both cases. A borrowed command pool must+-- address the same primary/database and stay live until the bracket returns.+data ConnectionSource+  = -- | Open and close both pools using the supplied connection details.+    OwnPools Redis.ConnectInfo+  | -- | Open the read pool and borrow the supplied command pool.+    BorrowCommands Redis.ConnectInfo Redis.Connection++-- | Bounds for a runtime and a callback for adapter events.+data RuntimeOptions = RuntimeOptions+  { -- | Timeout per Redis command in microseconds. Defaults to 2,000,000.+    commandTimeoutMicros :: !Int,+    -- | Blocking read time in milliseconds. Defaults to 250 and must be below the command timeout.+    pollMillis :: !Int,+    -- | Maximum entries per new read. Defaults to 32.+    prefetchLimit :: !Int,+    -- | Connection retries after the initial attempt. Defaults to 5.+    reconnectAttempts :: !Int,+    -- | Delay between connection attempts in microseconds. Defaults to 100,000.+    reconnectDelayMicros :: !Int,+    -- | Handle an adapter event promptly. Defaults to discarding events.+    observe :: AdapterEvent -> IO ()+  }+  deriving stock (Generic)++-- | Standard connection limits and a no-op observer.+defaultRuntimeOptions :: RuntimeOptions+defaultRuntimeOptions =+  RuntimeOptions+    { commandTimeoutMicros = 2000000,+      pollMillis = 250,+      prefetchLimit = 32,+      reconnectAttempts = 5,+      reconnectDelayMicros = 100000,+      observe = const (pure ())+    }++-- | Connection pools and intake state for one reader or worker.+data RedisRuntime = RedisRuntime+  { readPool :: !Redis.Connection,+    commandPool :: !Redis.Connection,+    stopped :: !(TVar Bool),+    attached :: !(TVar Bool),+    options :: !RuntimeOptions+  }++-- | Configuration, attachment, and Redis command errors.+data AdapterError+  = -- | Configuration fails the adapter's option checks.+    InvalidOptions+  | -- | Redis returned a reply the adapter cannot interpret.+    InvalidStreamReply+  | -- | The command exceeded its configured timeout.+    CommandTimedOut+  | -- | Redis rejected the command. Inspect the raw reply programmatically.+    CommandRejected Redis.Reply+  | -- | A reader or group worker already reserved this runtime.+    RuntimeAlreadyAttached++-- Redis errors can quote keys or requests. Keep the raw reply available for+-- programmatic inspection without including it in runner failure telemetry.+instance Show AdapterError where+  show RuntimeAlreadyAttached = "RuntimeAlreadyAttached"+  show InvalidOptions = "InvalidOptions"+  show InvalidStreamReply = "InvalidStreamReply"+  show CommandTimedOut = "CommandTimedOut"+  show (CommandRejected _) = "CommandRejected"++instance Exception AdapterError++-- | Bracket connection ownership around construction, processing, and finalizer drain.+-- The runtime holds one dedicated blocking read connection.+withRedisRuntime :: ConnectionSource -> RuntimeOptions -> (RedisRuntime -> IO a) -> IO a+withRedisRuntime source opts use = do+  let info = case source of+        OwnPools c -> c+        BorrowCommands c _ -> c+  unless+    ( opts.commandTimeoutMicros > 0+        && opts.pollMillis > 0+        && toInteger opts.pollMillis * 1000 < toInteger opts.commandTimeoutMicros+        && opts.prefetchLimit > 0+        && opts.reconnectAttempts >= 0+        && opts.reconnectDelayMicros > 0+        && Redis.connectMaxConnections info >= 1+    )+    (throwIO InvalidOptions)+  let owned config = bracket (Redis.connect config) Redis.disconnect+      withCommands = case source of+        OwnPools _ -> owned info+        BorrowCommands _ pool -> (\f -> f pool)+  owned (info {Redis.connectMaxConnections = 1, Redis.connectNumStripes = Just 1}) $ \readerPool ->+    withCommands $ \commands -> do+      closing <- newTVarIO False+      attachment <- newTVarIO False+      let runtime = RedisRuntime readerPool commands closing attachment opts+      _ <- boundedRequest opts readerPool Redis.ping+      _ <- runCommand runtime Redis.ping+      use runtime++-- Reserve a runtime before any constructor side effects. Failed initialization+-- releases the reservation, including when the constructing thread is canceled.+withRuntimeAttachment :: RedisRuntime -> IO a -> IO a+withRuntimeAttachment runtime initialize = mask $ \restore -> do+  acquired <- atomically $ do+    alreadyAttached <- readTVar runtime.attached+    if alreadyAttached+      then pure False+      else writeTVar runtime.attached True >> pure True+  unless acquired (throwIO RuntimeAlreadyAttached)+  restore initialize `onException` atomically (writeTVar runtime.attached False)++-- | Stop accepting deliveries and wake a blocked read. Run graceful shutdown+-- before exiting the runtime bracket so outstanding finalizers can finish.+stopIntake :: RedisRuntime -> IO ()+stopIntake runtime = atomically $ writeTVar runtime.stopped True++boundedRequest :: RuntimeOptions -> Redis.Connection -> Redis.Redis (Either Redis.Reply a) -> IO a+boundedRequest opts pool action = do+  result <-+    timeout opts.commandTimeoutMicros $+      Redis.runRedis pool action >>= either (throwIO . CommandRejected) evaluate+  maybe (throwIO CommandTimedOut) pure result++runCommand :: RedisRuntime -> Redis.Redis (Either Redis.Reply a) -> IO a+runCommand runtime = boundedRequest runtime.options runtime.commandPool++-- | Independent readers admit one outstanding entry. Groups share work across+-- processes, so the runner cannot impose source order on their side effects.+data DeliveryMode = IndependentReader | GroupWorker deriving stock (Eq, Show)++validateDeliveryPolicy :: DeliveryMode -> OrderingPolicy -> Concurrency -> Either PolicyError ()+validateDeliveryPolicy IndependentReader StrictInOrder concurrency = validatePolicy StrictInOrder concurrency+validateDeliveryPolicy GroupWorker Unordered concurrency = validatePolicy Unordered concurrency+validateDeliveryPolicy _ _ _ = Left (InvalidPolicyCombo "readers require strict order and groups require unordered execution")++readBatchOptions :: RedisRuntime -> Redis.XReadOpts+readBatchOptions runtime = Redis.XReadOpts (Just (toInteger runtime.options.pollMillis)) (Just (toInteger runtime.options.prefetchLimit))++-- | Nothing denotes shutdown. Redis blocking-read timeouts remain a successful+-- empty reply inside Just. A disconnect or command timeout propagates.+pollStream :: forall a. RedisRuntime -> Redis.Redis (Either Redis.Reply a) -> IO (Maybe a)+pollStream runtime action = do+  closed <- readTVarIO runtime.stopped+  if closed+    then pure Nothing+    else do+      outcome <-+        race+          (atomically (readTVar runtime.stopped >>= check))+          (retryConnection runtime (boundedRequest runtime.options runtime.readPool action))+      pure (either (const Nothing) Just outcome)++-- Only use this for operations that can be repeated after a lost reply.+retryConnection :: forall a. RedisRuntime -> IO a -> IO a+retryConnection runtime action = attempt runtime.options.reconnectAttempts+  where+    attempt remaining =+      action+        `catches` [ Handler (retry @Redis.ConnectionLostException remaining),+                    Handler (retry @Redis.ConnectTimeout remaining),+                    Handler (retry @IOException remaining),+                    Handler+                      ( \err -> case err of+                          CommandTimedOut -> retry remaining err+                          _ -> throwIO err+                      )+                  ]+    retry :: forall e. (Exception e) => Int -> e -> IO a+    retry remaining err+      | remaining == 0 = throwIO err+      | otherwise = threadDelay runtime.options.reconnectDelayMicros >> attempt (remaining - 1)++streamEntries :: SourceIdentity -> Maybe [Redis.XReadResponse] -> IO [RedisEntry]+streamEntries src rows = concat <$> traverse parseStream (maybe [] id rows)+  where+    parseStream (Redis.XReadResponse key records)+      | key == src.streamKey = traverse (streamRecord src) records+      | otherwise = throwIO InvalidStreamReply++streamRecord :: SourceIdentity -> Redis.StreamsRecord -> IO RedisEntry+streamRecord src (Redis.StreamsRecord rawId fields) =+  maybe (throwIO InvalidStreamReply) (\position -> pure (RedisEntry src position fields)) (parseEntryId rawId)
+ src/Shibuya/Adapter/Redis/DeadLetter.hs view
@@ -0,0 +1,49 @@+module Shibuya.Adapter.Redis.DeadLetter+  ( RejectionOwner (..),+    rejectionRecord,+    storeRejection,+  )+where++import Data.ByteString (ByteString)+import Data.Maybe (fromMaybe)+import Data.Text qualified as Text+import Data.Text.Encoding qualified as Text+import Database.Redis qualified as Redis+import Shibuya (DeadLetterReason, TraceHeaders, deadLetterCodeText, deadLetterReasonCode, deadLetterReasonDetail)+import Shibuya.Adapter.Redis.Types++-- | Namespace for the dead-letter hash field.+data RejectionOwner+  = -- | The reader’s logical checkpoint identity.+    LogicalReader !ByteString+  | -- | The Redis consumer group name shared by its workers.+    ConsumerGroup !ByteString+  deriving stock (Eq, Show)++-- | Encode the field and value for an idempotent Redis @HSETNX@.+--+-- Components have unsigned 64-bit big-endian byte lengths. The field+-- contains @redis-rejection-v1@, owner kind and name, then the framed message+-- identity. The value contains @redis-rejection-v1@, reason code, a detail+-- marker and optional UTF-8 detail of at most 512 characters, a trace marker+-- and optional W3C traceparent/tracestate, then alternating entry field names+-- and values. Pass no trace headers for rejections outside a consumer span.+rejectionRecord :: RejectionOwner -> RedisEntry -> DeadLetterReason -> Maybe TraceHeaders -> (ByteString, ByteString)+rejectionRecord owner entry reason headers = (key, value)+  where+    scope = case owner of+      LogicalReader name -> ["reader", name]+      ConsumerGroup name -> ["group", name]+    key = frame (["redis-rejection-v1"] <> scope <> [entryIdentity entry])+    code = Text.encodeUtf8 (deadLetterCodeText (deadLetterReasonCode reason))+    detail = maybe ["absent"] (\s -> ["present", Text.encodeUtf8 (Text.take 512 s)]) (deadLetterReasonDetail reason)+    trace = case headers >>= lookup "traceparent" of+      Nothing -> ["absent"]+      Just parent -> ["present", parent, fromMaybe "" (headers >>= lookup "tracestate")]+    value = frame (["redis-rejection-v1", code] <> detail <> trace <> concatMap (\(k, v) -> [k, v]) entry.fields)++storeRejection :: ByteString -> RejectionOwner -> RedisEntry -> DeadLetterReason -> Maybe TraceHeaders -> Redis.Redis (Either Redis.Reply Bool)+storeRejection destination owner entry reason headers =+  let (key, value) = rejectionRecord owner entry reason headers+   in Redis.hsetnx destination key value
+ src/Shibuya/Adapter/Redis/Group.hs view
@@ -0,0 +1,391 @@+module Shibuya.Adapter.Redis.Group+  ( GroupStart (..),+    MissingPending (..),+    GroupError (..),+    GroupConfig (..),+    rawGroupConfig,+    Group (..),+    groupProcessor,+    groupAttemptKey,+    newGroupWorker,+  )+where++import Control.Concurrent.STM+import Control.Exception (Exception, catch, mask, throwIO)+import Control.Monad (unless, void, when)+import Data.ByteString (ByteString)+import Data.ByteString.Char8 qualified as C8+import Data.HashMap.Strict qualified as HashMap+import Data.Map.Strict qualified as Map+import Data.Text (Text)+import Data.Text.Encoding (decodeUtf8')+import Database.Redis qualified as Redis+import Effectful (IOE, liftIO, (:>))+import OpenTelemetry.Attributes (toAttribute)+import Shibuya+import Shibuya.Adapter.Redis.Adapter+import Shibuya.Adapter.Redis.Connection+import Shibuya.Adapter.Redis.DeadLetter+import Shibuya.Adapter.Redis.Group.Scripts+import Shibuya.Adapter.Redis.Types+import Shibuya.Telemetry.Propagation (currentTraceHeaders)+import Streamly.Data.Stream qualified as Stream+import System.Entropy (getEntropy)++-- | How to attach a worker to a Redis consumer group.+data GroupStart+  = -- | Require a group that already exists.+    AttachExisting+  | -- | Create a missing group at the supplied position.+    CreateIfAbsent !EntryId+  | -- | Create a missing group at the stream’s current tail.+    CreateAtTailIfAbsent+  deriving stock (Eq, Show)++-- | A pending ID whose source payload no longer exists.+data MissingPending = MissingPending+  { -- | Source associated with the missing payload.+    missingSource :: !SourceIdentity,+    -- | Group with the lost pending payload.+    missingGroup :: !ByteString,+    -- | ID of the unavailable entry.+    missingEntry :: !EntryId+  }+  deriving stock (Eq, Show)++-- | Terminal failures specific to consumer-group workers.+data GroupError+  = -- | The Redis consumer group is missing.+    GroupUnavailable+  | -- | The entry requires rejection but no destination is configured.+    GroupRejectionWithoutDestination !EntryId+  | -- | The entry exhausted its retries without a dead-letter destination.+    GroupRetryLimit !EntryId+  deriving stock (Show)+  deriving anyclass (Exception)++-- | Configuration of a consumer-group worker. 'rawGroupConfig' supplies+-- defaults for a raw payload.+data GroupConfig a = GroupConfig+  { -- | Display name passed to Shibuya. Supplied by the caller.+    groupAdapterName :: !Text,+    -- | Namespace, generation and Redis key. Supplied by the caller.+    groupSource :: !SourceIdentity,+    -- | Redis consumer group name. Supplied by the caller.+    groupName :: !ByteString,+    -- | Consumer name unique to the running instance, including across restarts.+    -- Supplied by the caller.+    consumerName :: !ByteString,+    -- | Attach or create the group. Supplied by the caller.+    groupStart :: !GroupStart,+    -- | Maximum outstanding deliveries per worker. Defaults to 1.+    groupInFlight :: !Int,+    -- | Maximum pending rows per recovery page. Defaults to 32.+    groupScanLimit :: !Int,+    -- | Idle time in milliseconds before abandoned work is eligible for recovery.+    -- Defaults to 30,000. Explicit retries use their own deadline.+    minimumIdleMillis :: !Int,+    -- | Maximum retries, counting prior deliveries and claims. Defaults to 10.+    groupRetryLimit :: !Int,+    -- | Redis hash for rejected entries. Defaults to no destination.+    groupDeadLetters :: !(Maybe ByteString),+    -- | Decode the entry or return a permanent failure. Defaults to the raw entry.+    groupDecode :: RedisEntry -> Either DeadLetterReason a,+    -- | Extract application headers. Defaults to no application headers.+    groupHeaders :: RedisEntry -> Maybe Headers,+    -- | Extract incoming W3C context. Defaults to 'defaultTraceContext'.+    groupTraceContext :: RedisEntry -> Maybe TraceHeaders,+    -- | Shibuya tracing settings. Defaults to 'ParentAndLink' correlation.+    telemetry :: !AdapterTelemetry,+    -- | Called before acknowledging a pending ID whose payload has disappeared.+    -- Defaults to a no-op.+    onMissingPending :: MissingPending -> IO (),+    -- | Sample total pending depth on scan wrap and the highest idle time per page.+    -- Defaults to disabled.+    samplePending :: !Bool+  }++-- | Configure a worker that delivers raw entries. Arguments are the adapter+-- name, source identity, group name, consumer name, and start policy.+rawGroupConfig :: Text -> SourceIdentity -> ByteString -> ByteString -> GroupStart -> GroupConfig RedisEntry+rawGroupConfig name src group worker start =+  GroupConfig+    { groupAdapterName = name,+      groupSource = src,+      groupName = group,+      consumerName = worker,+      groupStart = start,+      groupInFlight = 1,+      groupScanLimit = 32,+      minimumIdleMillis = 30000,+      groupRetryLimit = 10,+      groupDeadLetters = Nothing,+      groupDecode = Right,+      groupHeaders = const Nothing,+      groupTraceContext = defaultTraceContext,+      telemetry = defaultAdapterTelemetry,+      onMissingPending = const (pure ()),+      samplePending = False+    }++-- | An attached consumer-group worker.+data Group es a = Group+  { -- | Shibuya adapter for advanced runner integration.+    groupAdapter :: !(Adapter es a),+    -- | Shibuya concurrency selected from the configured outstanding limit.+    configuredConcurrency :: !Concurrency+  }++-- | Process deliveries without an ordering guarantee, using the worker’s+-- configured concurrency.+groupProcessor :: Group es a -> Handler es a -> QueueProcessor es+groupProcessor group handler = QueueProcessor group.groupAdapter handler Unordered group.configuredConcurrency++data Pending = Pending !EntryId !ByteString !Integer++data GroupPull+  = Buffered ![RedisEntry] !EntryId !Bool+  | Poll !EntryId !Bool++data Active = Active !EntryId !(TVar Bool)++-- | Versioned, length-framed state for one pending ID. Keep this namespace+-- reserved for the adapter and consistent across every worker in the group.+groupAttemptKey :: SourceIdentity -> ByteString -> EntryId -> ByteString+groupAttemptKey src group position =+  groupStatePrefix <> frame [group, entryIdentity (RedisEntry src position [])]++-- | Attach one consumer-group worker to a runtime and load the fencing script.+-- Keep the runtime open until all finalizers have drained.+newGroupWorker :: (IOE :> es, Tracing :> es) => RedisRuntime -> GroupConfig a -> IO (Group es a)+newGroupWorker runtime cfg = do+  let concurrency = if cfg.groupInFlight == 1 then Serial else Async cfg.groupInFlight+  unless+    ( cfg.groupScanLimit > 0+        && cfg.minimumIdleMillis > 0+        && cfg.groupRetryLimit >= 0+        && not (C8.null cfg.groupName || C8.null cfg.consumerName)+        && Just src.streamKey /= cfg.groupDeadLetters+        && not (groupStatePrefix `C8.isPrefixOf` src.streamKey)+        && not (any (groupStatePrefix `C8.isPrefixOf`) cfg.groupDeadLetters)+        && either (const False) (const True) (validateDeliveryPolicy GroupWorker Unordered concurrency)+    )+    (throwIO InvalidOptions)+  withRuntimeAttachment runtime $ do+    attachGroup runtime cfg+    scriptHash <- groupCommand runtime (Redis.scriptLoad attemptScript)+    active <- newTVarIO Map.empty+    let freeCapacity =+          atomically $+            ( do+                closed <- readTVar runtime.stopped+                check closed+                pure 0+            )+              `orElse` ( do+                           count <- Map.size <$> readTVar active+                           let available = cfg.groupInFlight - count+                           check (available > 0)+                           pure available+                       )++        pull state = do+          capacity <- freeCapacity+          if capacity == 0+            then pure Nothing+            else case state of+              Buffered [] cursor recoverNext -> pull (Poll cursor recoverNext)+              Buffered (entry : rest) cursor recoverNext -> do+                token <- getEntropy 24+                result <- attempt "register" entry.entryId token []+                case result of+                  [Redis.Bulk (Just "ok")] -> deliver entry (Just 0) token (Buffered rest cursor recoverNext)+                  _ | superseded result -> emit Superseded >> pull (Buffered rest cursor recoverNext)+                  _ -> throwIO InvalidStreamReply+              Poll cursor True -> do+                let from = if cursor == origin then "-" else "(" <> renderEntryId cursor+                reply <- groupCommand runtime $ Redis.sendRequest ["XPENDING", src.streamKey, cfg.groupName, from, "+", number cfg.groupScanLimit]+                pending <- traverse pendingRow reply+                when (cfg.samplePending && cursor == origin) (sample pending)+                recover origin pending+              Poll cursor False -> do+                let opts =+                      Redis.XReadGroupOpts+                        (Just (toInteger runtime.options.pollMillis))+                        (Just (toInteger (min capacity runtime.options.prefetchLimit)))+                        False+                    readNew = Redis.xreadGroupOpts cfg.groupName cfg.consumerName [(src.streamKey, ">")] opts+                fetched <- groupFailure (pollStream runtime readNew)+                case fetched of+                  Nothing -> pure Nothing+                  Just rows -> streamEntries src rows >>= \entries -> pull (Buffered entries cursor True)++        recover nextCursor [] = pull (Poll nextCursor False)+        recover _ (Pending entryId owner _ : remaining) = do+          held <-+            if owner == cfg.consumerName+              then any (\(Active position _) -> position == entryId) <$> readTVarIO active+              else pure False+          if held then recover entryId remaining else claim entryId remaining++        claim entryId remaining = do+          let arguments = [number cfg.minimumIdleMillis, ""]+          token <- getEntropy 24+          result <- attempt "claim" entryId token arguments+          case result of+            [Redis.Bulk (Just "claimed"), raw, Redis.Integer count] -> do+              record <- either (const (throwIO InvalidStreamReply)) pure (Redis.decode raw)+              entry <- streamRecord src record+              emit Reclaimed+              let countKnown = count > 0 && count < 9007199254740992 && count - 1 <= toInteger (maxBound :: Word)+              deliver entry (if countKnown then Just (Attempt (fromInteger (count - 1))) else Nothing) token (Poll entryId False)+            [Redis.Bulk (Just "missing")] -> do+              cfg.onMissingPending (MissingPending src cfg.groupName entryId)+              emit PendingPayloadMissing+              void (attempt "drop-missing" entryId token arguments)+              recover entryId remaining+            [Redis.Bulk (Just "skip")] -> recover entryId remaining+            _ | superseded result -> recover entryId remaining+            _ -> throwIO InvalidStreamReply++        deliver entry count token next = do+          valid <- newTVarIO True+          atomically $ do+            deliveries <- readTVar active+            let updated = Map.filter (\(Active position _) -> position /= entry.entryId) deliveries+            mapM_ (\(Active position status) -> when (position == entry.entryId) (writeTVar status False)) deliveries+            writeTVar active (Map.insert token (Active entry.entryId valid) updated)+          let retire = atomically $ do+                writeTVar valid False+                modifyTVar' active (Map.delete token)+              transition operation args event = do+                result <- attempt operation entry.entryId token args+                transitionEvent result event+              transitionEvent result event =+                case result of+                  [Redis.Bulk (Just "ok")] -> pure (Just event)+                  [Redis.Bulk (Just "repeat")] -> pure Nothing+                  [Redis.Bulk (Just "absent")] -> pure Nothing+                  [Redis.Bulk (Just "stale")] -> pure (Just Superseded)+                  _ -> throwIO InvalidStreamReply+              reject reason headers = do+                let (field, value) = rejectionRecord (ConsumerGroup cfg.groupName) entry reason headers+                transition "reject" [field, value] DeadLettered+              scheduleRetry delay headers = do+                let args = [milliseconds delay, number cfg.groupRetryLimit]+                result <- attempt "retry" entry.entryId token args+                case result of+                  [Redis.Bulk (Just "retry-limit")] -> case cfg.groupDeadLetters of+                    Nothing -> throwIO (GroupRetryLimit entry.entryId)+                    Just _ -> reject MaxRetriesExceeded headers+                  _ -> transitionEvent result Retried+              finalize headers decision = mask $ \restore -> do+                event <- restore $ case decision of+                  AckOk -> transition "ack" [] Acknowledged+                  AckRetry (RetryDelay delay) -> scheduleRetry delay headers+                  AckDeadLetter reason -> case cfg.groupDeadLetters of+                    Nothing -> throwIO (GroupRejectionWithoutDestination entry.entryId)+                    Just _ -> reject reason headers+                  AckHalt _ -> stopIntake runtime >> pure Nothing+                retire+                mapM_ emit event+              renew duration = do+                result <- attempt "renew" entry.entryId token [milliseconds duration]+                if superseded result+                  then atomically (writeTVar valid False) >> emit Superseded+                  else unless (result == [Redis.Bulk (Just "ok")]) (throwIO InvalidStreamReply)+          case decodeEnvelope cfg.groupDecode cfg.groupHeaders cfg.groupTraceContext entry of+            Left (DecodeFailure _ reason) -> finalize Nothing (AckDeadLetter reason) >> pull next+            Right envelope -> do+              emit Delivered+              let redisAttributes = case decodeUtf8' cfg.groupName of+                    Left _ -> envelope.attributes+                    Right group -> HashMap.insert "messaging.consumer.group.name" (toAttribute group) envelope.attributes+                  finish decision = do+                    headers <- case decision of+                      AckDeadLetter _ -> currentTraceHeaders+                      AckRetry _ | maybe True (>= Attempt (fromIntegral cfg.groupRetryLimit)) count -> currentTraceHeaders+                      _ -> pure Nothing+                    liftIO (finalize headers decision)+                  delivery = mkIngested (envelope {attempt = count, attributes = redisAttributes}) (AckHandle finish)+              pure $+                Just+                  ( delivery+                      { lease = Just (Lease envelope.messageId.unMessageId (liftIO . renew)),+                        deliveryStatus = liftIO $ do+                          current <- readTVarIO valid+                          pure (if current then DeliveryCurrent else DeliverySuperseded)+                      },+                    next+                  )++        attempt operation position token args = do+          let keys = [src.streamKey, groupAttemptKey src cfg.groupName position] <> maybe [] pure cfg.groupDeadLetters+              arguments = [operation, cfg.groupName, cfg.consumerName, renderEntryId position, token] <> args+          groupCommand runtime (Redis.evalsha scriptHash keys arguments)+            `catch` \err -> case err of+              CommandRejected (Redis.Error message)+                | "NOSCRIPT " `C8.isPrefixOf` message ->+                    groupCommand runtime (Redis.eval attemptScript keys arguments)+              _ -> throwIO err++        sample pending = do+          reply <- groupCommand runtime $ Redis.sendRequest ["XPENDING", src.streamKey, cfg.groupName]+          case reply of+            Redis.Integer depth : _ ->+              let age = case [idle | Pending _ _ idle <- pending] of+                    [] -> Nothing+                    ages -> Just (maximum ages)+               in emit (PendingSample depth age)+            _ -> throwIO InvalidStreamReply++    let source = Stream.unfoldrM (liftIO . pull) (Poll origin True)+    pure (Group (mkRedisAdapter runtime cfg.groupAdapterName cfg.telemetry source) concurrency)+  where+    src = cfg.groupSource+    emit = runtime.options.observe+    origin = EntryId 0 0++attachGroup :: RedisRuntime -> GroupConfig a -> IO ()+attachGroup runtime cfg =+  case cfg.groupStart of+    AttachExisting -> void $ groupCommand runtime pendingProbe+    CreateIfAbsent position -> create (renderEntryId position)+    CreateAtTailIfAbsent -> create "$"+  where+    key = cfg.groupSource.streamKey+    pendingProbe :: Redis.Redis (Either Redis.Reply [Redis.Reply])+    pendingProbe = Redis.sendRequest ["XPENDING", key, cfg.groupName, "-", "+", "1"]+    create position = do+      result <- retryConnection runtime $ runCommand runtime $ Redis.sendRequest ["XGROUP", "CREATE", key, cfg.groupName, position, "MKSTREAM"]+      case result of+        Redis.SingleLine "OK" -> pure ()+        Redis.Error message | "BUSYGROUP " `C8.isPrefixOf` message -> pure ()+        Redis.Error message -> throwIO (CommandRejected (Redis.Error message))+        _ -> throwIO InvalidStreamReply++groupCommand :: RedisRuntime -> Redis.Redis (Either Redis.Reply a) -> IO a+groupCommand runtime = groupFailure . retryConnection runtime . runCommand runtime++groupFailure :: IO a -> IO a+groupFailure action =+  action `catch` \err ->+    case err of+      CommandRejected (Redis.Error message) | "NOGROUP " `C8.isPrefixOf` message -> throwIO GroupUnavailable+      _ -> throwIO err++pendingRow :: [Redis.Reply] -> IO Pending+pendingRow [Redis.Bulk (Just rawId), Redis.Bulk (Just owner), Redis.Integer idle, Redis.Integer _]+  | Just position <- parseEntryId rawId = pure (Pending position owner idle)+pendingRow _ = throwIO InvalidStreamReply++superseded :: [Redis.Reply] -> Bool+superseded result = result == [Redis.Bulk (Just "stale")] || result == [Redis.Bulk (Just "absent")]++number :: (Show a) => a -> ByteString+number = C8.pack . show++-- Keep durations and absolute server time within Lua's exact integer range.+milliseconds :: (RealFrac a) => a -> ByteString+milliseconds duration = number (max 0 (min 315360000000 (ceiling (duration * 1000))) :: Integer)
+ src/Shibuya/Adapter/Redis/Group/Scripts.hs view
@@ -0,0 +1,91 @@+module Shibuya.Adapter.Redis.Group.Scripts (attemptScript) where++import Data.ByteString (ByteString)+import Data.ByteString.Char8 qualified as C8++-- KEYS: stream, per-entry attempt state, optional rejection hash.+-- ARGV: operation, group, consumer, entry ID, token, operation arguments.+--+-- An attempt token is meaningful only while its consumer still owns the PEL+-- row. Pending metadata has no expiry. Completion removes it after XACK.+attemptScript :: ByteString+attemptScript =+  C8.unlines+    [ "local op, grp, consumer, id, token = unpack(ARGV)",+      "local stream, state, failures = unpack(KEYS)",+      "local row = redis.call('XPENDING', stream, grp, id, id, 1)[1]",+      "if not row then",+      "  if op == 'ack' or op == 'reject' or op == 'drop-missing' then",+      "    redis.call('DEL', state)",+      "  end",+      "  return {'absent'}",+      "end",+      "if row[4] >= 9007199254740991 then return redis.error_reply('ERR attempt count exhausted') end",+      "local generation = string.format('%.0f', row[4])",+      "local registered = redis.call('HGET', state, 'generation') == generation",+      "local current = redis.call('HGET', state, 'token')",+      "local owner = row[2] == consumer",+      "local function now()",+      "  local t = redis.call('TIME')",+      "  return tonumber(t[1]) * 1000 + math.floor(tonumber(t[2]) / 1000)",+      "end",+      -- XREADGROUP and registration are separate. A later claim always consumes+      -- the first delivery generation, even if the consumer name returns.+      "if op == 'register' then",+      "  if owner and registered and current == token then return {'ok'} end",+      "  if not owner or row[4] ~= 1 or redis.call('EXISTS', state) ~= 0 then",+      "    return {'stale'}",+      "  end",+      "  redis.call('HSET', state, 'token', token, 'generation', generation)",+      "  return {'ok'}",+      "end",+      "if op == 'claim' or op == 'drop-missing' then",+      "  if op == 'claim' and owner and registered and current == token then",+      "    local record = redis.call('XRANGE', stream, id, id)[1]",+      "    if record then return {'claimed', record, row[4]} end",+      "  end",+      "  local eligibleAt = tonumber(redis.call('HGET', state, 'until') or '0')",+      "  local retried = registered and redis.call('HGET', state, 'retried')",+      "  if eligibleAt > now() or (not retried and row[3] < tonumber(ARGV[6])) then return {'skip'} end",+      "  if owner and current and current ~= '' and current == ARGV[7] then return {'skip'} end",+      "  local record = redis.call('XRANGE', stream, id, id)[1]",+      "  if not record then",+      "    if op == 'claim' then return {'missing'} end",+      "    redis.call('XACK', stream, grp, id)",+      "    redis.call('DEL', state)",+      "    return {'ok'}",+      "  end",+      "  if op == 'drop-missing' then return {'skip'} end",+      "  local claimed = redis.call('XCLAIM', stream, grp, consumer, 0, id)",+      "  if not claimed[1] then return {'skip'} end",+      "  redis.call('HSET', state, 'token', token, 'generation', string.format('%.0f', row[4] + 1))",+      "  redis.call('HDEL', state, 'until', 'retried')",+      "  return {'claimed', claimed[1], row[4] + 1}",+      "end",+      -- Repeating a committed retry must leave its original due time alone.+      "if op == 'retry' and owner and registered and redis.call('HGET', state, 'retried') == token then",+      "  return {'repeat'}",+      "end",+      "if not owner or not registered or current ~= token then return {'stale'} end",+      "if op == 'retry' then",+      "  if row[4] - 1 >= tonumber(ARGV[7]) then return {'retry-limit'} end",+      "  redis.call('HSET', state, 'until', now() + tonumber(ARGV[6]), 'retried', token, 'token', '')",+      "  return {'ok'}",+      "end",+      "if op == 'renew' then",+      "  if not redis.call('XRANGE', stream, id, id)[1] then return {'stale'} end",+      "  local duration = tonumber(ARGV[6])",+      "  local previous = tonumber(redis.call('HGET', state, 'until') or '0')",+      "  redis.call('XCLAIM', stream, grp, consumer, 0, id, 'JUSTID')",+      "  redis.call('HSET', state, 'until', math.max(previous, now() + duration))",+      "  return {'ok'}",+      "end",+      "if op == 'reject' then",+      -- HSETNX validates the destination type before progress changes. If it+      -- succeeds and XACK errors, the next call can repeat the same write.+      "  redis.call('HSETNX', failures, ARGV[6], ARGV[7])",+      "end",+      "redis.call('XACK', stream, grp, id)",+      "redis.call('DEL', state)",+      "return {'ok'}"+    ]
+ src/Shibuya/Adapter/Redis/Internal.hs view
@@ -0,0 +1,30 @@+-- | __Internal module.__ This module exposes implementation details for tests+-- and advanced use. Its exports may change or disappear in any release.+module Shibuya.Adapter.Redis.Internal+  ( runCommand,+    pollStream,+    readBatchOptions,+    retryConnection,+    streamEntries,+    streamRecord,+    mkRedisAdapter,+    DeliveryMode (..),+    validateDeliveryPolicy,+    storeRejection,+    entryEnvelope,+    decodeEnvelope,+    DecodeFailure (..),+    frame,+    entryIdentity,+    groupAttemptKey,+    groupStatePrefix,+    attemptScript,+  )+where++import Shibuya.Adapter.Redis.Adapter+import Shibuya.Adapter.Redis.Connection+import Shibuya.Adapter.Redis.DeadLetter+import Shibuya.Adapter.Redis.Group+import Shibuya.Adapter.Redis.Group.Scripts+import Shibuya.Adapter.Redis.Types
+ src/Shibuya/Adapter/Redis/Reader.hs view
@@ -0,0 +1,327 @@+module Shibuya.Adapter.Redis.Reader+  ( Checkpoint (..),+    CheckpointStore (..),+    ReaderStart (..),+    GapEvidence (..),+    ReaderGap (..),+    GapAction (..),+    ReaderError (..),+    ReaderConfig (..),+    rawReaderConfig,+    Reader (..),+    readerProcessor,+    newReader,+  )+where++import Control.Concurrent (threadDelay)+import Control.Concurrent.Async (race)+import Control.Concurrent.STM+import Control.Exception (Exception, mask, onException, throwIO, tryJust)+import Control.Monad (unless, when)+import Data.ByteString (ByteString)+import Data.ByteString qualified as BS+import Data.IORef+import Data.Text (Text)+import Database.Redis qualified as Redis+import Effectful (IOE, liftIO, (:>))+import Shibuya+import Shibuya.Adapter.Redis.Adapter+import Shibuya.Adapter.Redis.Connection+import Shibuya.Adapter.Redis.DeadLetter+import Shibuya.Adapter.Redis.Types+import Shibuya.Telemetry.Propagation (currentTraceHeaders)+import Streamly.Data.Stream qualified as Stream++-- | Last completed entry and optional producer-supplied continuity evidence.+data Checkpoint = Checkpoint+  { -- | Cursor used to resume strictly after this entry.+    position :: !EntryId,+    -- | Opaque producer evidence persisted with the cursor.+    continuity :: !(Maybe ByteString)+  }+  deriving stock (Eq, Show)++-- | Application-owned checkpoint persistence. A conditional save must accept+-- an identical already-committed update. Both callbacks receive the same+-- logical reader name and source identity.+data CheckpointStore = CheckpointStore+  { -- | Load the reader’s durable completed cursor, if present.+    loadCheckpoint :: ByteString -> SourceIdentity -> IO (Maybe Checkpoint),+    -- | Save the next completed cursor given the expected previous value.+    -- The previous value is absent when writing the start boundary.+    saveCheckpoint :: ByteString -> SourceIdentity -> Maybe Checkpoint -> Checkpoint -> IO ()+  }++-- | Initial position when the checkpoint store has no saved cursor.+data ReaderStart+  = -- | Deliver every retained entry starting at the first.+    Earliest+  | -- | Deliver entries strictly after the supplied checkpoint.+    After !Checkpoint+  | -- | Start after the stream’s current tail.+    Live+  deriving stock (Eq, Show)++-- | Evidence that previously completed history may no longer match the stream.+data GapEvidence+  = -- | Redis’s tail moved behind the checkpoint. A missing tail denotes an absent stream.+    StreamRolledBack !(Maybe EntryId)+  | -- | The application’s continuity callback reported a discontinuity.+    ProducerDiscontinuity !Text+  deriving stock (Eq, Show)++-- | Information passed to the application when the reader detects a gap.+data ReaderGap = ReaderGap+  { -- | Logical source whose history changed.+    gapSource :: !SourceIdentity,+    -- | Completed checkpoint before the gap.+    lastCheckpoint :: !Checkpoint,+    -- | Candidate next entry when the gap was detected during delivery.+    nextEntry :: !(Maybe EntryId),+    -- | Evidence that triggered the gap callback.+    gapEvidence :: !GapEvidence+  }+  deriving stock (Eq, Show)++-- | Choose how a reader responds to a detected history gap.+data GapAction+  = -- | Stop and leave reconstruction to the application.+    StopAndRebuild+  | -- | Stop so the application can resnapshot and construct a fresh reader.+    Resnapshot+  | -- | Accept the discontinuity and keep reading.+    BestEffort+  deriving stock (Eq, Show)++-- | Terminal failures specific to an independent reader.+data ReaderError+  = -- | A detected gap and the application's terminal disposition.+    ReaderHistoryLost !ReaderGap !GapAction+  | -- | The entry requires rejection but no destination is configured.+    ReaderRejectionWithoutDestination !EntryId+  | -- | The entry exhausted its retries without a dead-letter destination.+    ReaderRetryLimit !EntryId+  deriving anyclass (Exception)++instance Show ReaderError where+  show (ReaderHistoryLost _ disposition) = "ReaderHistoryLost " <> show disposition+  show (ReaderRejectionWithoutDestination position) = "ReaderRejectionWithoutDestination " <> show position+  show (ReaderRetryLimit position) = "ReaderRetryLimit " <> show position++-- | Configuration of one ordered independent reader. 'rawReaderConfig'+-- supplies the defaults for a raw payload.+data ReaderConfig a = ReaderConfig+  { -- | Display name passed to Shibuya. Supplied by the caller.+    readerAdapterName :: !Text,+    -- | Logical name for checkpoints and dead-letter records. Supplied by the caller.+    readerIdentity :: !ByteString,+    -- | Namespace, generation and Redis key. Supplied by the caller.+    readerSource :: !SourceIdentity,+    -- | Position when no checkpoint is saved. Supplied by the caller.+    readerStart :: !ReaderStart,+    -- | Optional durable checkpoint storage. Defaults to an in-memory checkpoint.+    checkpointStore :: !(Maybe CheckpointStore),+    -- | Decode the entry or return a permanent failure. Defaults to the raw entry.+    readerDecode :: RedisEntry -> Either DeadLetterReason a,+    -- | Extract application headers. Defaults to no application headers.+    readerHeaders :: RedisEntry -> Maybe Headers,+    -- | Extract incoming W3C context. Defaults to 'defaultTraceContext'.+    readerTraceContext :: RedisEntry -> Maybe TraceHeaders,+    -- | Shibuya tracing settings. Defaults to 'LinkOnly' correlation.+    telemetry :: !AdapterTelemetry,+    -- | Evidence to save with this entry and an optional discontinuity message.+    -- Defaults to neither. 'BestEffort' accepts the evidence even on a gap.+    checkContinuity :: Checkpoint -> RedisEntry -> (Maybe ByteString, Maybe Text),+    -- | Respond to a history gap. Defaults to 'StopAndRebuild'.+    onReaderGap :: ReaderGap -> IO GapAction,+    -- | Redis hash for rejected entries. Defaults to no destination.+    readerDeadLetters :: !(Maybe ByteString),+    -- | Maximum retries after the first delivery. Defaults to 10.+    readerRetryLimit :: !Int+  }++-- | Configure a reader that delivers raw entries. Arguments are the adapter+-- name, logical reader name, source identity, and start position.+rawReaderConfig :: Text -> ByteString -> SourceIdentity -> ReaderStart -> ReaderConfig RedisEntry+rawReaderConfig name identity src start =+  ReaderConfig+    { readerAdapterName = name,+      readerIdentity = identity,+      readerSource = src,+      readerStart = start,+      checkpointStore = Nothing,+      readerDecode = Right,+      readerHeaders = const Nothing,+      readerTraceContext = defaultTraceContext,+      telemetry = defaultAdapterTelemetry {traceCorrelation = LinkOnly},+      checkContinuity = \_ _ -> (Nothing, Nothing),+      onReaderGap = const (pure StopAndRebuild),+      readerDeadLetters = Nothing,+      readerRetryLimit = 10+    }++-- | An attached reader and access to its progress.+data Reader es a = Reader+  { -- | Shibuya adapter for advanced runner integration.+    readerAdapter :: !(Adapter es a),+    -- | Read the latest completed checkpoint.+    completedCheckpoint :: IO Checkpoint+  }++-- | Run one delivery at a time in stream order. Batches that wait for several+-- outstanding entries cannot use the single-entry reader.+readerProcessor :: Reader es a -> Handler es a -> QueueProcessor es+readerProcessor reader handler = QueueProcessor reader.readerAdapter handler StrictInOrder Serial++data HeadResult = Advance | RepeatAfter !Int++data ReaderPull+  = Ready ![RedisEntry]+  | Await !(TMVar HeadResult) !RedisEntry !Checkpoint !Int ![RedisEntry]++-- | Create one reader per runtime. Keep the runtime open through runner drain.+newReader :: (IOE :> es, Tracing :> es) => RedisRuntime -> ReaderConfig a -> IO (Reader es a)+newReader runtime cfg = do+  when+    ( cfg.readerRetryLimit < 0+        || Just src.streamKey == cfg.readerDeadLetters+        || groupStatePrefix `BS.isPrefixOf` src.streamKey+        || any (groupStatePrefix `BS.isPrefixOf`) cfg.readerDeadLetters+    )+    (throwIO InvalidOptions)+  withRuntimeAttachment runtime $ do+    loaded <- maybe (pure Nothing) (\store -> store.loadCheckpoint cfg.readerIdentity src) cfg.checkpointStore+    initial <- case loaded of+      Just saved -> pure saved+      Nothing -> do+        boundary <- case cfg.readerStart of+          Earliest -> pure origin+          After checkpoint -> pure checkpoint+          Live -> do+            tailId <- streamTail runtime src+            pure (Checkpoint (maybe origin.position id tailId) Nothing)+        save Nothing boundary+        pure boundary+    completed <- newIORef initial+    let commit previous next = do+          save (Just previous) next+          writeIORef completed next++        reportGap previous entry evidence = do+          let gap = ReaderGap src previous entry evidence+          emit HistoryGap+          disposition <- cfg.onReaderGap gap+          unless (disposition == BestEffort) (throwIO (ReaderHistoryLost gap disposition))++        pull state = do+          stopped <- readTVarIO runtime.stopped+          if stopped+            then pure Nothing+            else case state of+              Ready [] -> do+                previous <- readIORef completed+                tailId <- streamTail runtime src+                boundary <-+                  if maybe origin.position id tailId < previous.position+                    then do+                      reportGap previous Nothing (StreamRolledBack tailId)+                      commit previous origin+                      pure origin+                    else pure previous+                batch <- pollStream runtime (Redis.xreadOpts [(src.streamKey, renderEntryId boundary.position)] (readBatchOptions runtime))+                case batch of+                  Nothing -> pure Nothing+                  Just rows -> streamEntries src rows >>= pull . Ready+              Ready (entry : rest) -> do+                previous <- readIORef completed+                let (evidence, problem) = cfg.checkContinuity previous entry+                    next = Checkpoint entry.entryId evidence+                mapM_ (reportGap previous (Just entry.entryId) . ProducerDiscontinuity) problem+                deliver previous next entry 0 rest+              Await result entry next attempt rest -> do+                outcome <- atomically $ (Just <$> readTMVar result) `orElse` (readTVar runtime.stopped >>= check >> pure Nothing)+                case outcome of+                  Nothing -> pure Nothing+                  Just Advance -> pull (Ready rest)+                  Just (RepeatAfter micros) -> do+                    waited <- race (atomically (readTVar runtime.stopped >>= check)) (threadDelay micros)+                    case waited of+                      Left () -> pure Nothing+                      Right () -> do+                        previous <- readIORef completed+                        deliver previous next entry (attempt + 1) rest++        deliver previous next entry attempt rest = do+          gate <- newEmptyTMVarIO+          let complete = commit previous next+              reject reason headers = case cfg.readerDeadLetters of+                Nothing -> throwIO (ReaderRejectionWithoutDestination entry.entryId)+                Just key -> do+                  _ <- retryConnection runtime $ runCommand runtime $ storeRejection key (LogicalReader cfg.readerIdentity) entry reason headers+                  emit DeadLettered+                  complete+              finalize headers decision = mask $ \restore -> do+                unfinalized <- atomically (isEmptyTMVar gate)+                when unfinalized $ case decision of+                  AckOk -> do+                    restore complete+                    atomically (putTMVar gate Advance)+                    emit Acknowledged+                  AckDeadLetter reason -> do+                    restore (reject reason headers)+                    atomically (putTMVar gate Advance)+                  AckRetry (RetryDelay delay)+                    | attempt == cfg.readerRetryLimit -> case cfg.readerDeadLetters of+                        Nothing -> throwIO (ReaderRetryLimit entry.entryId)+                        Just _ -> do+                          restore (reject MaxRetriesExceeded headers)+                          atomically (putTMVar gate Advance)+                    | otherwise -> do+                        let micros = max 0 (min (toInteger (maxBound :: Int)) (ceiling (delay * 1000000)))+                        atomically (putTMVar gate (RepeatAfter (fromInteger micros)))+                        emit Retried+                  AckHalt _ -> stopIntake runtime+          case decodeEnvelope cfg.readerDecode cfg.readerHeaders cfg.readerTraceContext entry of+            Left (DecodeFailure _ reason) -> reject reason Nothing >> pull (Ready rest)+            Right envelope -> do+              emit Delivered+              let finish decision = do+                    headers <- case decision of+                      AckDeadLetter _ -> currentTraceHeaders+                      AckRetry _ | attempt == cfg.readerRetryLimit -> currentTraceHeaders+                      _ -> pure Nothing+                    liftIO (finalize headers decision)+                  delivery = mkIngested (envelope {attempt = Just (Attempt (fromIntegral attempt))}) (AckHandle finish)+              pure (Just (delivery, Await gate entry next attempt rest))++    let deliveries = Stream.unfoldrM (liftIO . pull) (Ready [])+    pure (Reader (mkRedisAdapter runtime cfg.readerAdapterName cfg.telemetry deliveries) (readIORef completed))+  where+    src = cfg.readerSource+    origin = Checkpoint (EntryId 0 0) Nothing+    emit = runtime.options.observe+    save previous next = mapM_ persist cfg.checkpointStore+      where+        persist store =+          store.saveCheckpoint cfg.readerIdentity src previous next+            `onException` emit CheckpointFailed++streamTail :: RedisRuntime -> SourceIdentity -> IO (Maybe EntryId)+streamTail runtime src = do+  result <- tryJust missing $ retryConnection runtime $ runCommand runtime $ Redis.sendRequest ["XINFO", "STREAM", src.streamKey]+  case result of+    Left () -> pure Nothing+    Right (Redis.Error "ERR no such key") -> pure Nothing+    Right err@(Redis.Error _) -> throwIO (CommandRejected err)+    Right (Redis.MultiBulk (Just properties)) ->+      case lookup "last-generated-id" (pairs properties) >>= parseEntryId of+        Just position -> pure (Just position)+        Nothing -> throwIO InvalidStreamReply+    Right _ -> throwIO InvalidStreamReply+  where+    missing (CommandRejected (Redis.Error "ERR no such key")) = Just ()+    missing _ = Nothing+    pairs (Redis.Bulk (Just key) : Redis.Bulk (Just value) : rest) = (key, value) : pairs rest+    pairs (_ : _ : rest) = pairs rest+    pairs _ = []
+ src/Shibuya/Adapter/Redis/Types.hs view
@@ -0,0 +1,145 @@+-- | Binary stream entries and their Shibuya envelope representation.+module Shibuya.Adapter.Redis.Types+  ( EntryId (..),+    renderEntryId,+    parseEntryId,+    SourceIdentity (..),+    RedisEntry (..),+    frame,+    entryIdentity,+    entryEnvelope,+    defaultTraceContext,+    DecodeFailure (..),+    decodeEnvelope,+    AdapterEvent (..),+    groupStatePrefix,+  )+where++import Data.ByteString (ByteString)+import Data.ByteString qualified as BS+import Data.ByteString.Builder qualified as Builder+import Data.ByteString.Char8 qualified as C8+import Data.ByteString.Lazy qualified as LBS+import Data.HashMap.Strict qualified as HashMap+import Data.Text (Text)+import Data.Text.Encoding qualified as Text+import Data.Word (Word64)+import GHC.Generics (Generic)+import OpenTelemetry.Attributes (toAttribute)+import Shibuya (Cursor (..), DeadLetterReason, Envelope (..), Headers, MessageId (..), TraceHeaders, mkEnvelope)++-- | A Redis stream position ordered by milliseconds and sequence number.+data EntryId+  = -- | Milliseconds component followed by the sequence component.+    EntryId !Word64 !Word64+  deriving stock (Eq, Ord, Show, Generic)++-- | Render an entry ID as canonical Redis decimal milliseconds-sequence bytes.+renderEntryId :: EntryId -> ByteString+renderEntryId (EntryId ms seqNo) = C8.pack (show ms <> "-" <> show seqNo)++-- | Parse a canonical Redis ID with two unsigned 64-bit components.+parseEntryId :: ByteString -> Maybe EntryId+parseEntryId input = case C8.split '-' input of+  [ms, seqNo] -> EntryId <$> component ms <*> component seqNo+  _ -> Nothing+  where+    component s = do+      (n, rest) <- C8.readInteger s+      if BS.null rest && n >= 0 && n <= toInteger (maxBound :: Word64) && C8.pack (show n) == s+        then Just (fromInteger n)+        else Nothing++-- | Identify a logical stream across its deliveries.+data SourceIdentity = SourceIdentity+  { -- | Application scope that distinguishes streams with otherwise identical identities.+    namespace :: !ByteString,+    -- | Optional producer generation. Change it when a recreated stream has a new identity.+    generation :: !(Maybe ByteString),+    -- | Binary Redis key of the stream.+    streamKey :: !ByteString+  }+  deriving stock (Eq, Show, Generic)++-- | A Redis stream entry with its original binary data.+data RedisEntry = RedisEntry+  { -- | Logical source of the entry.+    sourceIdentity :: !SourceIdentity,+    -- | Redis position and backend-native entry ID.+    entryId :: !EntryId,+    -- | Field/value pairs in stream order, including duplicate names.+    fields :: ![(ByteString, ByteString)]+  }+  deriving stock (Eq, Show, Generic)++-- | Components have unsigned 64-bit big-endian byte lengths.+frame :: [ByteString] -> ByteString+frame = LBS.toStrict . Builder.toLazyByteString . foldMap component+  where+    component bytes = Builder.word64BE (fromIntegral (BS.length bytes)) <> Builder.byteString bytes++entryIdentity :: RedisEntry -> ByteString+entryIdentity entry =+  frame $+    ["redis-stream-v1", src.namespace]+      <> maybe ["absent"] (\g -> ["present", g]) src.generation+      <> [src.streamKey, renderEntryId entry.entryId]+  where+    src = entry.sourceIdentity++entryEnvelope :: RedisEntry -> Envelope RedisEntry+entryEnvelope entry =+  (mkEnvelope (MessageId (Text.decodeUtf8 hexId)) entry)+    { cursor = Just (CursorText position),+      attributes =+        HashMap.fromList+          [ ("messaging.system", toAttribute ("redis" :: Text)),+            ("messaging.message.id", toAttribute position),+            ("shibuya.redis.entry_id", toAttribute position)+          ]+    }+  where+    position = Text.decodeUtf8 (renderEntryId entry.entryId)+    hexId = LBS.toStrict (Builder.toLazyByteString (Builder.byteStringHex (entryIdentity entry)))++-- | Extract W3C headers from the first field with each standard name.+-- Shibuya validates the headers when it creates the consumer span.+defaultTraceContext :: RedisEntry -> Maybe TraceHeaders+defaultTraceContext entry = do+  parent <- lookup "traceparent" entry.fields+  pure (("traceparent", parent) : [("tracestate", state) | Just state <- [lookup "tracestate" entry.fields]])++data DecodeFailure = DecodeFailure !RedisEntry !DeadLetterReason deriving stock (Eq, Show)++decodeEnvelope :: (RedisEntry -> Either DeadLetterReason a) -> (RedisEntry -> Maybe Headers) -> (RedisEntry -> Maybe TraceHeaders) -> RedisEntry -> Either DecodeFailure (Envelope a)+decodeEnvelope decode selectHeaders selectTrace entry = case decode entry of+  Left reason -> Left (DecodeFailure entry reason)+  Right value -> Right ((value <$ entryEnvelope entry) {headers = selectHeaders entry, traceContext = selectTrace entry})++-- | Observations emitted during reads, finalization and recovery.+data AdapterEvent+  = -- | An entry was admitted to the runner.+    Delivered+  | -- | A successful decision advanced the cursor or acknowledged the entry.+    Acknowledged+  | -- | A later attempt was scheduled.+    Retried+  | -- | A worker claimed a pending entry.+    Reclaimed+  | -- | An attempt lost its Redis ownership fence.+    Superseded+  | -- | The dead-letter write completed, including an idempotent replay.+    DeadLettered+  | -- | An application checkpoint save failed.+    CheckpointFailed+  | -- | A reader detected a discontinuity in history.+    HistoryGap+  | -- | A pending entry no longer has a stream payload.+    PendingPayloadMissing+  | -- | Total pending entries and the optional maximum idle age of the page in milliseconds.+    PendingSample !Integer !(Maybe Integer)+  deriving stock (Eq, Show)++groupStatePrefix :: ByteString+groupStatePrefix = "shibuya:group:v1:"
+ test/Fixture.hs view
@@ -0,0 +1,41 @@+module Fixture (withRedis, withRedisRestarts) where++import Control.Concurrent (threadDelay)+import Control.Exception (bracket)+import Control.Monad (unless, void, when)+import Database.Redis qualified as R+import System.Directory (doesPathExist)+import System.Environment (lookupEnv)+import System.FilePath ((</>))+import System.IO.Temp (withTempDirectory)+import System.Process++withRedis :: (R.ConnectInfo -> IO a) -> IO a+withRedis use = withRedisDirectory [] (\start -> start (\info _ -> use info))++-- | Start another server on the same socket and data after stopping the+-- preceding child. The caller can keep adapter connections across restarts.+withRedisRestarts :: ((forall b. (R.ConnectInfo -> IO () -> IO b) -> IO b) -> IO a) -> IO a+withRedisRestarts = withRedisDirectory ["--appendonly", "yes", "--appendfsync", "always"]++withRedisDirectory :: [String] -> ((forall b. (R.ConnectInfo -> IO () -> IO b) -> IO b) -> IO a) -> IO a+withRedisDirectory persistence use = withTempDirectory "/tmp" "shibuya-redis" $ \dir -> do+  executable <- maybe "redis-server" id <$> lookupEnv "REDIS_SERVER"+  let socket = dir </> "redis.sock"+      info = R.defaultConnectInfo {R.connectAddr = R.ConnectAddrUnixSocket socket}+      args = ["--port", "0", "--unixsocket", socket, "--dir", dir, "--save", "", "--logfile", dir </> "redis.log"] <> persistence+      launch = do+        (_, _, _, child) <- createProcess (proc executable args)+        pure child+      ready child = do+        getProcessExitCode child >>= mapM_ (fail . ("redis-server exited: " <>) . show)+        exists <- doesPathExist socket+        unless exists (threadDelay 10000 >> ready child)+      stop child = do+        status <- getProcessExitCode child+        when (status == Nothing) (terminateProcess child >> void (waitForProcess child))+      start :: (R.ConnectInfo -> IO () -> IO b) -> IO b+      start action = bracket launch stop $ \child -> do+        ready child+        action info (stop child)+  use start
+ test/GroupSpec.hs view
@@ -0,0 +1,458 @@+module Main (main) where++import Control.Concurrent+import Control.Concurrent.Async (async, concurrently, wait, withAsync)+import Control.Exception (bracket)+import Control.Monad (forM_, unless, void)+import Data.ByteString (ByteString)+import Data.ByteString.Char8 qualified as C8+import Data.IORef+import Data.List (sort)+import Data.List.NonEmpty (NonEmpty (..))+import Data.Text qualified as T+import Database.Redis qualified as R+import Effectful (Eff, IOE, liftIO, runEff)+import Effectful.Exception qualified as E+import Fixture+import Shibuya+import Shibuya.Adapter.Redis+import Streamly.Data.Stream qualified as Stream+import System.Timeout (timeout)++type Effects = '[Tracing, IOE]++assert :: String -> Bool -> IO ()+assert label condition = unless condition (fail label)++within :: String -> IO a -> IO a+within label action = timeout 12000000 action >>= maybe (fail (label <> " timed out")) pure++main :: IO ()+main = withRedis $ \info ->+  bracket (R.connect info) R.disconnect $ \admin -> do+    within "same-consumer retry" $ sameConsumerRetry info admin "solo-retry" 1 (Just (RetryDelay 0.2))+    within "creation and distribution" $ distribution info admin+    forM_ [AckOk, AckRetry (RetryDelay 40), AckDeadLetter rejection] $ \decision ->+      within ("takeover and late " <> show decision) $ takeover info admin decision+    within "long-handler renewal" $ leaseRenewal info admin+    within "retry deadline" $ sameConsumerRetry info admin "retry-deadline" 5000 (Just (RetryDelay 0.3))+    within "handler exception retry" $ sameConsumerRetry info admin "retry-exception" 5000 Nothing+    within "retry exhaustion" $ retryExhaustion info admin+    within "script cache and active recovery" $ scriptCache info admin+    within "retry and rejection" $ retryAndReject info admin+    within "pending loss and failed destination" $ payloadLoss info admin+    within "rotating pending scan" $ boundedScan info admin+    putStrLn "Group creation, distribution, takeover, fencing, solo retry, retry exhaustion, script caching, rejection, pending loss and scan fairness passed"++command :: (R.RedisResult a) => R.Connection -> [ByteString] -> IO a+command connection request = R.runRedis connection (R.sendRequest request) >>= either (fail . show) pure++append :: R.Connection -> ByteString -> ByteString -> IO ()+append connection key identifier =+  void $ R.runRedis connection (R.xadd key identifier [("data", "job")]) >>= either (fail . show) pure++pending :: R.Connection -> ByteString -> ByteString -> IO [[R.Reply]]+pending admin key group = command admin ["XPENDING", key, group, "-", "+", "100"]++ownerIs :: ByteString -> [[R.Reply]] -> Bool+ownerIs worker [[_, R.Bulk (Just who), _, _]] = who == worker+ownerIs _ _ = False++age :: R.Connection -> ByteString -> ByteString -> ByteString -> ByteString -> IO ()+age admin key group owner identifier =+  void $ command @([ByteString]) admin ["XCLAIM", key, group, owner, "0", identifier, "IDLE", "10000", "JUSTID"]++await :: IO Bool -> IO ()+await action = do+  satisfied <- action+  unless satisfied (threadDelay 10000 >> await action)++withGroup :: R.ConnectInfo -> GroupConfig a -> (Group Effects a -> IO b) -> IO b+withGroup info config use =+  withRedisRuntime (OwnPools info) defaultRuntimeOptions $ \runtime ->+    newGroupWorker runtime config >>= use++runWorker :: Group Effects a -> Handler Effects a -> (AppHandle Effects -> Eff Effects b) -> IO b+runWorker group handler use = runEff $ runTracingNoop $ do+  result <- runApp defaultAppConfig [(ProcessorId "worker", groupProcessor group handler)]+  app <- either (liftIO . fail . show) pure result+  use app `E.finally` void (stopAppGracefully (ShutdownConfig 0.1 1) app)++drain :: AppHandle Effects -> Eff Effects ()+drain app = stopAppGracefully (ShutdownConfig 1 2) app >>= liftIO . assert "group drain"++configuration :: ByteString -> ByteString -> ByteString -> GroupStart -> GroupConfig RedisEntry+configuration key group worker start =+  (rawGroupConfig "worker" (SourceIdentity "tests" Nothing key) group worker start)+    { minimumIdleMillis = 5000+    }++record :: Chan (ByteString, EntryId) -> ByteString -> Handler Effects RedisEntry+record channel name message = liftIO $ do+  writeChan channel (name, message.envelope.payload.entryId)+  pure AckOk++distribution :: R.ConnectInfo -> R.Connection -> IO ()+distribution info admin = do+  let key = "distribution"+      cfg = configuration key "jobs"+      use owner start = withGroup info (cfg owner start)+  append admin key "1-0"+  void $+    concurrently+      (use "creator-a" (CreateIfAbsent (EntryId 0 0)) (const (pure ())))+      (use "creator-b" CreateAtTailIfAbsent (const (pure ())))+  -- Read the actual winning position before deliberately requesting other starts.+  details <- command @[R.Reply] admin ["XINFO", "GROUPS", key]+  use "creator-c" CreateAtTailIfAbsent (const (pure ()))+  use "creator-d" (CreateIfAbsent (EntryId 0 0)) (const (pure ()))+  command @[R.Reply] admin ["XINFO", "GROUPS", key] >>= assert "concurrent creation preserves winning position" . (== details)+  append admin key "2-0"+  append admin key "3-0"+  claimedA <- newEmptyMVar+  releaseA <- newEmptyMVar+  seen <- newChan+  allSeen <- newChan+  withAsync+    ( use "a" AttachExisting $ \worker ->+        runWorker+          worker+          ( \message -> liftIO $ do+              putMVar claimedA message.envelope.payload.entryId+              readMVar releaseA+              pure AckOk+          )+          $ \app -> liftIO (readMVar releaseA) >> drain app+    )+    $ \a -> do+      first <- readMVar claimedA+      use "b" AttachExisting $ \worker ->+        runWorker worker (record seen "b") $ \app -> do+          (_, second) <- liftIO (readChan seen)+          liftIO $ assert "other worker receives a distinct job" (first /= second)+          liftIO (putMVar releaseA ())+          drain app+      wait a+  withGroup info (configuration key "separate" "c" (CreateIfAbsent (EntryId 0 0))) $ \worker ->+    runWorker worker (record allSeen "c") $ \app -> do+      ids <- liftIO (mapM (const (snd <$> readChan allSeen)) [1 :: Int, 2, 3])+      liftIO (assert "separate group sees all original jobs" (sort ids == map (`EntryId` 0) [1, 2, 3]))+      drain app+  command @Integer admin ["XLEN", key] >>= assert "group ack leaves source intact" . (== 3)++takeover :: R.ConnectInfo -> R.Connection -> AckDecision -> IO ()+takeover info admin oldDecision = do+  let key = C8.pack (show oldDecision)+      config worker = (configuration key "jobs" worker (CreateIfAbsent (EntryId 0 0))) {groupDeadLetters = Just (key <> ":rejects")}+      gid = "jobs"+      release m = liftIO (readMVar m)+  append admin key "1-0"+  second <- newEmptyMVar+  third <- newEmptyMVar+  unpause <- newEmptyMVar+  allowB <- newEmptyMVar+  done <- newEmptyMVar+  bReturned <- newEmptyMVar+  -- Keep the first callback outside the runner to replay every stale operation+  -- after A→B→A. A and B's subsequent deliveries use the public processors.+  withGroup info ((config "a") {groupInFlight = 2}) $ \a ->+    runEff $ runTracingNoop $ do+      item <- Stream.uncons a.groupAdapter.source >>= maybe (liftIO (fail "first delivery missing")) (pure . fst)+      liftIO $ assert "initial attempt" (item.envelope.attempt == Just 0)+      run <- liftIO $ runAsyncWorker info (config "b") second allowB bReturned+      E.finally+        ( do+            liftIO $ age admin key gid "a" "1-0"+            liftIO $ readMVar second >>= assert "B claims first generation" . (== Just 1)+            liftIO $ pending admin key gid >>= assert "B owns pending work" . ownerIs "b"+            extend item+            status <- item.deliveryStatus+            case status of+              DeliverySuperseded -> pure ()+              _ -> liftIO (fail "stale lease did not supersede the delivery")+            acknowledge item oldDecision+            liftIO $ pending admin key gid >>= assert "stale callback cannot touch B" . ownerIs "b"+            output <-+              runApp+                defaultAppConfig+                [ ( ProcessorId "worker",+                    groupProcessor+                      a+                      ( \message -> do+                          liftIO $ putMVar third message.envelope.attempt+                          release unpause+                          pure AckOk+                      )+                  )+                ]+            app <- either (liftIO . fail . show) pure output+            flip E.finally (drain app) $ do+              liftIO $ do+                age admin key gid "b" "1-0"+                readMVar third >>= assert "A claims with new generation" . (== Just 2)+              extend item+              acknowledge item oldDecision+              liftIO $ do+                pending admin key gid >>= assert "stale callback cannot touch new A" . ownerIs "a"+                putMVar allowB ()+                readMVar bReturned+                putMVar unpause ()+              drain app+              liftIO $ putMVar done ()+        )+        (liftIO run)+  readMVar done+  pending admin key gid >>= assert "new A acknowledged" . null+  command @Integer admin ["HLEN", key <> ":rejects"] >>= assert "stale rejection writes nothing" . (== 0)+  where+    acknowledge item decision = let AckHandle finish = item.ack in finish decision+    extend item = mapM_ (\lease -> lease.leaseExtend 60) item.lease++runAsyncWorker :: R.ConnectInfo -> GroupConfig RedisEntry -> MVar (Maybe Attempt) -> MVar () -> MVar () -> IO (IO ())+runAsyncWorker info config started proceed returned = do+  let use = withGroup info config $ \worker ->+        runWorker+          worker+          ( \message -> liftIO $ do+              putMVar started message.envelope.attempt+              readMVar proceed+              pure AckOk+          )+          $ \app -> do+            liftIO (readMVar proceed)+            drain app+            liftIO (putMVar returned ())+  -- Return a join action. The caller must release proceed before joining.+  job <- async use+  pure (void (tryPutMVar proceed ()) >> wait job)++rejection :: DeadLetterReason+rejection = InvalidPayload (T.replicate 600 "x")++retryAndReject :: R.ConnectInfo -> R.Connection -> IO ()+retryAndReject info admin = do+  let key = "retry-group"+      cfg owner =+        (configuration key "jobs" owner (CreateIfAbsent (EntryId 0 0)))+          { minimumIdleMillis = 1,+            groupDeadLetters = Just "retry-rejections"+          }+  append admin key "1-0"+  initial <- newEmptyMVar+  withGroup info (cfg "a") $ \worker ->+    runWorker+      worker+      ( \message -> liftIO $ do+          now <- redisMillis admin+          putMVar initial (message.envelope.messageId, now)+          pure (AckRetry (RetryDelay 1))+      )+      $ \app -> do+        _ <- liftIO (readMVar initial)+        drain app+  (original, issued) <- readMVar initial+  calls <- newIORef (0 :: Int)+  finalized <- newEmptyMVar+  withGroup info (cfg "b") $ \worker -> do+    let base = worker.groupAdapter+        hideReply delivery =+          let AckHandle finish = delivery.ack+           in delivery+                { ack = AckHandle $ \decision -> do+                    finish decision+                    first <- liftIO $ atomicModifyIORef' calls (\n -> (n + 1, n == 0))+                    liftIO $ if first then fail "fixture hid the committed rejection reply" else putMVar finalized ()+                }+        instrumented = worker {groupAdapter = base {source = Stream.mapM (pure . hideReply) base.source}}+        handle message = liftIO $ do+          now <- redisMillis admin+          assert "retry did not run before due time" (now >= issued + 1000)+          assert "retry preserves message identity" (message.envelope.messageId == original && message.envelope.attempt == Just 1)+          pure (AckDeadLetter rejection)+    runWorker instrumented handle $ \app -> liftIO (readMVar finalized) >> drain app+  readIORef calls >>= assert "runner repeated the finalizer after an uncertain reply" . (== 2)+  pending admin key "jobs" >>= assert "rejected ID acknowledged" . null+  command @Integer admin ["HLEN", "retry-rejections"] >>= assert "one logical rejection after replay" . (== 1)+  let other = (cfg "c") {groupName = "another-group"}+  withGroup info other $ \worker ->+    runEff $ runTracingNoop $ do+      (delivery, _) <- Stream.uncons worker.groupAdapter.source >>= maybe (liftIO (fail "second group's input is missing")) pure+      let AckHandle finish = delivery.ack+      finish (AckDeadLetter rejection)+  command @Integer admin ["HLEN", "retry-rejections"] >>= assert "rejection scoped to group" . (== 2)++sameConsumerRetry :: R.ConnectInfo -> R.Connection -> ByteString -> Int -> Maybe RetryDelay -> IO ()+sameConsumerRetry info admin key idle delay = do+  let cfg = (configuration key "jobs" "solo" (CreateIfAbsent (EntryId 0 0))) {minimumIdleMillis = idle}+  seen <- newChan+  let handler message = liftIO $ do+        now <- redisMillis admin+        let envelope = message.envelope+        writeChan seen (envelope.messageId, envelope.attempt, now)+        case envelope.attempt of+          Just 0 -> maybe (fail "handler failed on the first attempt") (pure . AckRetry) delay+          _ -> pure AckOk+  append admin key "1-0"+  withGroup info cfg $ \worker ->+    runWorker worker handler $ \app -> do+      liftIO $ do+        (original, first, issued) <- readChan seen+        later <- timeout 2000000 (readChan seen)+        (retried, next, delivered) <- maybe (fail "solo worker did not retry within two seconds") pure later+        assert "retry preserves the identity and increments the attempt" (original == retried && first == Just 0 && next == Just 1)+        forM_ delay $ \(RetryDelay duration) ->+          assert "retry respects Redis server deadline" (delivered >= issued + floor (duration * 1000))+      drain app+  pending admin key "jobs" >>= assert "solo retry was acknowledged" . null++redisMillis :: R.Connection -> IO Integer+redisMillis admin = do+  serverTime <- command @[ByteString] admin ["TIME"]+  case serverTime of+    [seconds, micros] -> pure (read (C8.unpack seconds) * 1000 + read (C8.unpack micros) `div` 1000)+    _ -> fail "invalid server TIME reply"++retryExhaustion :: R.ConnectInfo -> R.Connection -> IO ()+retryExhaustion info admin = do+  let cfg key = (configuration key "jobs" "solo" (CreateIfAbsent (EntryId 0 0))) {groupRetryLimit = 1}+      retry = const (pure (AckRetry (RetryDelay 0)))+  append admin "limited-pending" "1-0"+  withGroup info (cfg "limited-pending") $ \worker -> runWorker worker retry waitApp+  pending admin "limited-pending" "jobs" >>= assert "exhaustion preserves pending work without a destination" . ownerIs "solo"+  seen <- newChan+  let key = "limited-group"+      dest = "limited-rejections"+      handler message+        | message.envelope.payload.entryId == EntryId 1 0 = retry message+        | otherwise = record seen "solo" message+  append admin key "1-0"+  withGroup info ((cfg key) {groupDeadLetters = Just dest}) $ \worker ->+    runWorker worker handler $ \app -> do+      liftIO $ do+        await ((== 1) <$> command @Integer admin ["HLEN", dest])+        command @[ByteString] admin ["HVALS", dest] >>= \records ->+          assert+            "one rejection with the exhaustion reason"+            ( case records of+                [value] -> "max_retries_exceeded" `C8.isInfixOf` value+                _ -> False+            )+        append admin key "2-0"+        readChan seen >>= assert "same worker processes the next job" . (== ("solo", EntryId 2 0))+      drain app+  pending admin key "jobs" >>= assert "no pending work after dead-lettering" . null++scriptCache :: R.ConnectInfo -> R.Connection -> IO ()+scriptCache info admin = do+  let key = "script-cache"+      cfg = (configuration key "jobs" "solo" (CreateIfAbsent (EntryId 0 0))) {groupInFlight = 2}+      stats = command @ByteString admin ["INFO", "commandstats"]+      count prefix = map (C8.takeWhile (/= ',')) . filter (prefix `C8.isPrefixOf`) . C8.lines+  started <- newEmptyMVar+  release <- newEmptyMVar+  seen <- newChan+  let handler message+        | message.envelope.payload.entryId == EntryId 1 0 = liftIO $ do+            putMVar started ()+            readMVar release+            pure AckOk+        | otherwise = record seen "solo" message+  append admin key "1-0"+  withGroup info cfg $ \worker ->+    runWorker worker handler $ \app -> do+      liftIO $ do+        readMVar started+        before <- stats+        threadDelay 1100000+        after <- stats+        assert "active row is scanned without a Lua call" $+          count "cmdstat_xpending:" after /= count "cmdstat_xpending:" before+            && count "cmdstat_evalsha:" after == count "cmdstat_evalsha:" before+            && count "cmdstat_eval:" after == count "cmdstat_eval:" before+        putMVar release ()+        await (null <$> pending admin key "jobs")+        void $ command @R.Status admin ["SCRIPT", "FLUSH"]+        append admin key "2-0"+        readChan seen >>= assert "worker reloads the flushed script" . (== ("solo", EntryId 2 0))+      drain app+  pending admin key "jobs" >>= assert "flushed script recovered through finalization" . null++payloadLoss :: R.ConnectInfo -> R.Connection -> IO ()+payloadLoss info admin = do+  let key = "loss"+      cfg worker = (configuration key "jobs" worker (CreateIfAbsent (EntryId 0 0))) {groupDeadLetters = Just "wrong-type"}+  append admin key "1-0"+  void $ command @R.Status admin ["SET", "wrong-type", "string"]+  withGroup info (cfg "a") $ \worker ->+    runWorker worker (const (pure (AckDeadLetter rejection))) waitApp+  pending admin key "jobs" >>= assert "invalid hash preserved pending entry" . ownerIs "a"+  age admin key "jobs" "a" "1-0"+  void $ R.runRedis admin (R.xdel key ("1-0" :| [])) >>= either (fail . show) pure+  observed <- newEmptyMVar+  withGroup info ((cfg "b") {onMissingPending = putMVar observed}) $ \worker ->+    runWorker worker (const (liftIO (fail "missing payload reached handler"))) $ \app -> do+      liftIO $ do+        loss <- readMVar observed+        assert "diagnostic carries source and ID" (loss.missingEntry == EntryId 1 0 && loss.missingSource.streamKey == key)+        await (null <$> pending admin key "jobs")+      drain app+  append admin key "2-0"+  withGroup info ((cfg "c") {groupDeadLetters = Nothing}) $ \worker ->+    runWorker worker (const (pure (AckDeadLetter rejection))) waitApp+  pending admin key "jobs" >>= assert "rejection without destination preserves work" . ownerIs "c"+  age admin key "jobs" "c" "2-0"+  withGroup info ((cfg "d") {groupDeadLetters = Nothing}) $ \worker ->+    runWorker worker (const (pure (AckHalt (HaltFatal "planned halt")))) waitApp+  pending admin key "jobs" >>= assert "halt preserves work" . ownerIs "d"++boundedScan :: R.ConnectInfo -> R.Connection -> IO ()+boundedScan info admin = do+  let key = "scan"+      cfg =+        (configuration key "jobs" "scan-worker" AttachExisting)+          { groupInFlight = 1,+            groupScanLimit = 1,+            samplePending = True+          }+  mapM_ (append admin key) ["1-0", "2-0", "3-0", "4-0", "5-0"]+  void $ command @R.Status admin ["XGROUP", "CREATE", key, "jobs", "0-0"]+  void $ command @[R.Reply] admin ["XREADGROUP", "GROUP", "jobs", "parked", "COUNT", "3", "STREAMS", key, ">"]+  age admin key "jobs" "parked" "3-0"+  channel <- newChan+  events <- newIORef []+  let options = defaultRuntimeOptions {observe = \event -> atomicModifyIORef' events (\seen -> (event : seen, ()))}+  withRedisRuntime (OwnPools info) options $ \runtime -> do+    worker <- newGroupWorker runtime cfg+    runWorker worker (record channel "scan-worker") $ \app -> do+      observed <- liftIO $ mapM (const (snd <$> readChan channel)) [1 :: Int, 2, 3]+      liftIO $ assert "later pending page and new work both progress" (sort observed == map (`EntryId` 0) [3, 4, 5])+      drain app+  readIORef events >>= assert "group emits counts and bounded backlog sample" . (\seen -> all (`elem` seen) [Delivered, Acknowledged, Reclaimed] && any isSample seen)+  where+    isSample (PendingSample depth (Just ageMillis)) = depth > 0 && ageMillis >= 0+    isSample _ = False++leaseRenewal :: R.ConnectInfo -> R.Connection -> IO ()+leaseRenewal info admin = do+  let key = "lease"+      cfg worker = configuration key "jobs" worker (CreateIfAbsent (EntryId 0 0))+  append admin key "1-0"+  append admin key "2-0"+  withGroup info (cfg "holder") $ \a ->+    runEff $ runTracingNoop $ do+      delivery <- Stream.uncons a.groupAdapter.source >>= maybe (liftIO (fail "no lease to renew")) (pure . fst)+      case delivery.lease of+        Nothing -> liftIO (fail "group has no lease")+        Just lease -> lease.leaseExtend 60+      liftIO $ do+        age admin key "jobs" "holder" "1-0"+        withGroup info (cfg "peer") $ \b -> do+          seen <- newChan+          runWorker b (record seen "peer") $ \app -> do+            (_, identifier) <- liftIO (readChan seen)+            liftIO (assert "renewed lease withstands reclamation while new work proceeds" (identifier == EntryId 2 0))+            drain app+        pending admin key "jobs" >>= assert "renewal retained original owner" . ownerIs "holder"+      let AckHandle finish = delivery.ack+      finish AckOk+  pending admin key "jobs" >>= assert "renewal did not rotate the finalizer fence" . null
+ test/Main.hs view
@@ -0,0 +1,153 @@+module Main (main) where++import Control.Concurrent+import Control.Concurrent.Async (wait, withAsync)+import Control.Exception (bracket, try)+import Control.Monad (unless, void)+import Data.ByteString qualified as BS+import Data.HashMap.Strict qualified as HashMap+import Data.IORef+import Data.Text qualified as T+import Database.Redis qualified as R+import Effectful (IOE, liftIO, runEff)+import Effectful.Exception qualified as E+import Fixture+import OpenTelemetry.Attributes (toAttribute)+import Shibuya+import Shibuya.Adapter.Redis+import Shibuya.Adapter.Redis qualified as ReaderFields (ReaderConfig (telemetry))+import Shibuya.Adapter.Redis.Internal+import Streamly.Data.Stream qualified as Stream+import System.Timeout (timeout)++check :: String -> Bool -> IO ()+check label ok = unless ok (fail label)++main :: IO ()+main = do+  completed <- timeout 15000000 $ withRedis $ \info ->+    bracket (R.connect info) R.disconnect $ \borrowed -> do+      let pools = BorrowCommands info borrowed+      bad <- try @AdapterError (withRedisRuntime pools (defaultRuntimeOptions {pollMillis = 0}) (const (pure ())))+      check "invalid poll limit" (case bad of Left InvalidOptions -> True; _ -> False)+      -- Fail the second PING after acquiring the dedicated read pool.+      let countClients =+            R.runRedis borrowed (R.sendRequest ["CLIENT", "LIST"])+              >>= either (fail . show) (pure . length . BS.split 10)+      before <- countClients+      bracket (R.connect (info {R.connectDatabase = -1})) R.disconnect $ \unusable -> do+        failed <- try @R.ConnectError (withRedisRuntime (BorrowCommands info unusable) defaultRuntimeOptions (const (pure ())))+        check "second pool failed to acquire" (either (const True) (const False) failed)+      after <- countClients+      check "partial acquisition released read connection" (before == after)+      check "reader rejects concurrent handlers" (either (const True) (const False) (validateDeliveryPolicy IndependentReader StrictInOrder (Async 2)))+      withRedisRuntime pools defaultRuntimeOptions roundTrip+      withRedisRuntime pools defaultRuntimeOptions checkTelemetryDefaults+      withRedisRuntime pools defaultRuntimeOptions checkGroupTelemetryDefault+      withRedisRuntime pools defaultRuntimeOptions checkSingleAttachment+      withRedisRuntime pools defaultRuntimeOptions $ \runtime ->+        withAsync (pollStream runtime (R.xreadOpts [("idle", "0-0")] (R.XReadOpts (Just 1200) (Just 1)))) $ \reader -> do+          -- Wait for Redis to confirm that the dedicated connection is blocked.+          let awaitRead = do+                clients <- runCommand runtime (R.sendRequest ["INFO", "clients"])+                unless ("blocked_clients:1" `BS.isInfixOf` clients) (threadDelay 1000 >> awaitRead)+          awaitRead+          stopIntake runtime+          stopIntake runtime+          wait reader >>= check "poll cancelled on shutdown" . (== Nothing)+      R.runRedis borrowed R.ping >>= check "borrowed pool still usable" . (== Right R.Pong)+  check "runner fixture deadline" (completed == Just ())+  putStrLn "PONG; binary delivery, rejection replay, cancelled poll and finalizer drain passed"++roundTrip :: RedisRuntime -> IO ()+roundTrip runtime = do+  let key = "orders"+      identity = SourceIdentity "demo" Nothing key+      pairs = [("item", "a"), ("item", BS.pack [0, 255])]+      expected = RedisEntry identity (EntryId 7 2) pairs+      expectedId = (entryEnvelope expected).messageId+      alternate = RedisEntry (SourceIdentity "dem" Nothing "oorders") (EntryId 7 2) pairs+      reason = InvalidPayload (T.replicate 600 "x")+      owner = LogicalReader "index"+  let headers = [("traceparent", "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01"), ("tracestate", "acme=opaque")]+      traced = expected {fields = pairs <> headers}+      convert = decodeEnvelope Right (const Nothing)+  check "default extractor reads both W3C fields" (((.traceContext) <$> convert defaultTraceContext traced) == Right (Just headers))+  check "tracestate by itself does not propagate" (defaultTraceContext (traced {fields = drop 1 headers}) == Nothing)+  check "untraced entries have no context" (((.traceContext) <$> convert defaultTraceContext expected) == Right Nothing)+  check "custom extractor overrides W3C fields" (((.traceContext) <$> convert (const Nothing) traced) == Right Nothing)+  check+    "Redis attributes omit the stream key"+    ((entryEnvelope traced).attributes == HashMap.fromList [("messaging.system", toAttribute ("redis" :: T.Text)), ("messaging.message.id", toAttribute ("7-2" :: T.Text)), ("shibuya.redis.entry_id", toAttribute ("7-2" :: T.Text))])+  check "length-framed message ID" (expectedId /= (entryEnvelope alternate).messageId)+  check "missing generation distinct from empty" (expectedId /= (entryEnvelope (expected {sourceIdentity = identity {generation = Just ""}})).messageId)+  check "reject invalid stream ID" (parseEntryId "18446744073709551616-1" == Nothing)+  check "decoder failure retains identity" (decodeEnvelope (const (Left reason)) (const Nothing) defaultTraceContext expected == Left @DecodeFailure @(Envelope ()) (DecodeFailure expected reason))+  void $ runCommand runtime (R.xadd key "7-2" pairs)+  started <- newEmptyMVar+  intakeClosed <- newEmptyMVar+  finalized <- newEmptyMVar+  firstReply <- newIORef True+  let sourceAction = do+        rows <- liftIO $ pollStream runtime (R.xreadOpts [(key, "0-0")] (readBatchOptions runtime))+        entry <- liftIO $ case rows of+          Just (Just [R.XReadResponse k [R.StreamsRecord rawId fs]])+            | k == key,+              Just i <- parseEntryId rawId ->+                pure (RedisEntry identity i fs)+          _ -> fail "expected one stream record"+        let finish decision = liftIO $ do+              check "runner decision" (decision == AckDeadLetter reason)+              readMVar intakeClosed+              inserted <- runCommand runtime (storeRejection "failures" owner entry reason Nothing)+              loseReply <- atomicModifyIORef' firstReply (\first -> (False, first))+              if loseReply && inserted then fail "fixture hid successful Redis reply" else pure ()+              count <- runCommand runtime (R.hlen "failures")+              check "one logical rejection" (not loseReply && not inserted && count == 1)+              putMVar finalized ()+        pure $ mkIngested (entryEnvelope entry) (AckHandle finish)+      baseAdapter = mkRedisAdapter runtime "redis-fixture" (defaultAdapterTelemetry {traceCorrelation = LinkOnly}) (Stream.fromEffect sourceAction)+      adapter = baseAdapter {shutdown = baseAdapter.shutdown >> liftIO (void (tryPutMVar intakeClosed ()))}+      handler message = liftIO $ do+        check "wire fidelity and stable ID" (message.envelope.payload == expected && message.envelope.messageId == expectedId)+        check "producer time and attempt absent" (message.envelope.enqueuedAt == Nothing && message.envelope.attempt == Nothing)+        putMVar started ()+        pure (AckDeadLetter reason)+  check "configured telemetry" (adapter.telemetry.traceCorrelation == LinkOnly)+  runEff $ runTracingNoop $ do+    result <- runApp defaultAppConfig [(ProcessorId "fixture", mkProcessor adapter handler)]+    app <- either (liftIO . fail . show) pure result+    flip E.finally (stopApp app) $ do+      liftIO $ takeMVar started+      drained <- stopAppGracefully (ShutdownConfig 2 4) app+      liftIO $ check "graceful app drain" drained+  takeMVar finalized++checkTelemetryDefaults :: RedisRuntime -> IO ()+checkTelemetryDefaults runtime = do+  let config = rawReaderConfig "reader" "index" (SourceIdentity "test" Nothing "defaults") Earliest+  check "reader defaults to linked roots" (config.telemetry.traceCorrelation == LinkOnly)+  reader <- newReader @'[Tracing, IOE] runtime (config {ReaderFields.telemetry = defaultAdapterTelemetry})+  check "reader applies telemetry override" (reader.readerAdapter.telemetry.traceCorrelation == ParentAndLink)++checkGroupTelemetryDefault :: RedisRuntime -> IO ()+checkGroupTelemetryDefault runtime = do+  let config = rawGroupConfig "worker" (SourceIdentity "test" Nothing "defaults") "jobs" "solo" (CreateIfAbsent (EntryId 0 0))+  worker <- newGroupWorker @'[Tracing, IOE] runtime config+  check "group defaults to parent and link" (worker.groupAdapter.telemetry.traceCorrelation == ParentAndLink)++checkSingleAttachment :: RedisRuntime -> IO ()+checkSingleAttachment runtime = do+  let source = SourceIdentity "test" Nothing "attach-once"+      readerConfig = rawReaderConfig "reader" "index" source Earliest+      groupConfig = rawGroupConfig "worker" source "missing" "solo" AttachExisting+      newProjection = void (newReader @'[Tracing, IOE] runtime readerConfig)+      newWorker = void (newGroupWorker @'[Tracing, IOE] runtime groupConfig)+      assertAttached label action = do+        result <- try @AdapterError action+        check label (case result of Left RuntimeAlreadyAttached -> True; _ -> False)+  missing <- try @GroupError newWorker+  check "failed group initialization is reported" (case missing of Left GroupUnavailable -> True; _ -> False)+  newProjection+  assertAttached "runtime rejects a second independent reader" newProjection+  assertAttached "runtime rejects a group worker after a reader" newWorker
+ test/ReaderSpec.hs view
@@ -0,0 +1,321 @@+module Main (main) where++import Control.Concurrent+import Control.Concurrent.Async (wait, withAsync)+import Control.Exception (bracket)+import Control.Monad (unless, void)+import Data.ByteString (ByteString)+import Data.ByteString.Char8 qualified as C8+import Data.IORef+import Data.List.NonEmpty (NonEmpty (..))+import Database.Redis qualified as R+import Effectful (Eff, IOE, liftIO, runEff, (:>))+import Effectful.Exception qualified as E+import Fixture+import Shibuya+import Shibuya.Adapter.Redis+import System.IO.Unsafe (unsafePerformIO)+import System.Timeout (timeout)++main :: IO ()+main = do+  result <- timeout 20000000 $ withRedis $ \info ->+    bracket (R.connect info) R.disconnect $ \producer -> do+      let pools = OwnPools info+          append key i fields = R.runRedis producer (R.xadd key i fields) >>= either (fail . show) pure+      putStrLn "Reader scenario independent"+      independent pools append+      putStrLn "Reader scenario retries"+      retries pools append+      rejectionReconnect info producer append+      retryExhaustion pools producer append+      putStrLn "Reader scenario rejection"+      rejection pools producer append+      putStrLn "Reader scenario handover"+      handover pools producer append+  assert "reader integration timeout" (result == Just ())+  putStrLn "Reader order, durable restart, retry, crash, rejection and continuity passed"++type Append = ByteString -> ByteString -> [(ByteString, ByteString)] -> IO ByteString++assert :: String -> Bool -> IO ()+assert message ok = unless ok (fail message)++storeIn :: IORef (Maybe Checkpoint) -> CheckpointStore+storeIn cell = CheckpointStore (\_ _ -> readIORef cell) $ \_ _ old new -> do+  updated <- atomicModifyIORef' cell $ \current ->+    if current == old || current == Just new then (Just new, True) else (current, False)+  assert "checkpoint compare-and-set" updated++withReader :: (IOE :> es, Tracing :> es) => ConnectionSource -> ReaderConfig a -> (Reader es a -> IO b) -> IO b+withReader pools config use = withRedisRuntime pools defaultRuntimeOptions $ \runtime ->+  newReader runtime config >>= use++runReader :: Reader '[Tracing, IOE] a -> Handler '[Tracing, IOE] a -> (AppHandle '[Tracing, IOE] -> Eff '[Tracing, IOE] b) -> IO b+runReader reader handle use = runEff $ runTracingNoop $ do+  result <- runApp defaultAppConfig [(ProcessorId "reader", readerProcessor reader handle)]+  app <- either (liftIO . fail . show) pure result+  use app `E.finally` void (stopAppGracefully (ShutdownConfig 0.1 1) app)++recording :: (IOE :> es) => Chan EntryId -> Handler es RedisEntry+recording channel message = liftIO $ do+  writeChan channel message.envelope.payload.entryId+  pure AckOk++expectIds :: Chan EntryId -> [EntryId] -> IO ()+expectIds channel = mapM_ $ \expected ->+  readChan channel >>= assert ("expected reader entry " <> show expected) . (== expected)++independent :: ConnectionSource -> Append -> IO ()+independent pools append = do+  let src = SourceIdentity "test" Nothing "projections"+      config name cell = (rawReaderConfig "projection" name src Earliest) {checkpointStore = Just (storeIn cell)}+      appendAt i = void (append src.streamKey (renderEntryId (EntryId i 0)) [("value", "x")])+      first = map (`EntryId` 0) [1, 2, 3]+  mapM_ appendAt [1, 2, 3]+  aStore <- newIORef Nothing+  bStore <- newIORef Nothing+  a <- newChan+  b <- newChan+  bReady <- newEmptyMVar+  finishB <- newEmptyMVar+  withAsync+    ( withReader pools (config "reporting" bStore) $ \reader ->+        runReader reader (recording b) $ \app -> do+          liftIO (putMVar bReady () >> takeMVar finishB)+          stopAppGracefully (ShutdownConfig 2 4) app >>= liftIO . assert "projection B drains"+    )+    $ \worker -> do+      takeMVar bReady+      withReader pools (config "index" aStore) $ \reader ->+        runReader reader (recording a) $ \app -> do+          liftIO (expectIds a first >> expectIds b first)+          stopAppGracefully (ShutdownConfig 2 4) app >>= liftIO . assert "projection A drains"+      appendAt 4+      withReader pools ((config "index" aStore) {readerStart = Live}) $ \reader ->+        runReader reader (recording a) $ \app -> do+          liftIO (expectIds a [EntryId 4 0] >> expectIds b [EntryId 4 0])+          stopAppGracefully (ShutdownConfig 2 4) app >>= liftIO . assert "projection A resumes"+      putMVar finishB ()+      wait worker+  forStores aStore bStore+  where+    forStores a b = mapM_ (\store -> readIORef store >>= assert "independent saved cursor" . (== Just (Checkpoint (EntryId 4 0) Nothing))) [a, b]++retries :: ConnectionSource -> Append -> IO ()+retries pools append = do+  let src = SourceIdentity "test" Nothing "retry"+      config = rawReaderConfig "retry" "index" src Earliest+  void (append src.streamKey "1-0" [("value", "A")])+  void (append src.streamKey "2-0" [("value", "B")])+  deliveries <- newChan+  withReader pools config $ \reader -> do+    let handle message = liftIO $ do+          let envelope = message.envelope+          writeChan deliveries (envelope.payload.entryId, envelope.attempt)+          pure $ if envelope.payload.entryId == EntryId 1 0 && envelope.attempt == Just 0 then AckRetry (RetryDelay 0) else AckOk+    runReader reader handle $ \app -> do+      liftIO $+        mapM_+          (\expected -> readChan deliveries >>= assert "retry holds the next prefetched entry" . (== expected))+          [(EntryId 1 0, Just 0), (EntryId 1 0, Just 1), (EntryId 2 0, Just 0)]+      stopAppGracefully (ShutdownConfig 2 4) app >>= liftIO . assert "retry processor drains"+  let crashSource = src {streamKey = "crash"}+  void (append crashSource.streamKey "1-0" [("value", "effect")])+  store <- newIORef Nothing+  effects <- newIORef []+  committed <- newEmptyMVar+  parked <- newEmptyMVar+  let crashConfig = config {readerSource = crashSource, checkpointStore = Just (storeIn store)}+      applyEffect identifier = atomicModifyIORef' effects $ \seen ->+        (if identifier `elem` seen then seen else identifier : seen, ())+  withReader pools crashConfig $ \reader ->+    runReader+      reader+      ( \message -> liftIO $ do+          applyEffect message.envelope.messageId+          putMVar committed message.envelope.messageId+          () <- takeMVar parked+          pure AckOk+      )+      $ \_ -> liftIO (readMVar committed >> pure ())+  readIORef store >>= assert "forced stop preserves initial checkpoint" . (== Just (Checkpoint (EntryId 0 0) Nothing))+  replayed <- newEmptyMVar+  withReader pools crashConfig $ \reader ->+    runReader+      reader+      ( \message -> liftIO $ do+          applyEffect message.envelope.messageId+          putMVar replayed message.envelope.messageId+          pure AckOk+      )+      $ \app -> do+        liftIO $ do+          first <- readMVar committed+          readMVar replayed >>= assert "same ID after forced stop" . (== first)+        stopAppGracefully (ShutdownConfig 2 4) app >>= liftIO . assert "replayed reader drains"+  readIORef effects >>= assert "one logical external effect" . (== 1) . length++retryExhaustion :: ConnectionSource -> R.Connection -> Append -> IO ()+retryExhaustion pools producer append = do+  let src = SourceIdentity "test" Nothing "retry-exhaustion"+      dest = "exhausted-reader"+      cfg = (rawReaderConfig "retry-exhaustion" "index" src Earliest) {readerRetryLimit = 1}+      retryEntry = AckRetry (RetryDelay 0)+  void (append src.streamKey "1-0" [("value", "poison")])+  withReader pools cfg $ \reader -> do+    runReader reader (const (pure retryEntry)) waitApp+    reader.completedCheckpoint >>= assert "exhaustion without a destination preserves the checkpoint" . (== Checkpoint (EntryId 0 0) Nothing)+  void (append src.streamKey "2-0" [("value", "healthy")])+  seen <- newChan+  withReader pools (cfg {readerDeadLetters = Just dest}) $ \reader -> do+    let handle message = liftIO $ do+          let envelope = message.envelope+          writeChan seen (envelope.payload.entryId, envelope.attempt)+          pure $ if envelope.payload.entryId == EntryId 1 0 then retryEntry else AckOk+    runReader reader handle $ \app -> do+      liftIO $+        mapM_+          (\expected -> readChan seen >>= assert "exhausted retries release the next entry in order" . (== expected))+          [(EntryId 1 0, Just 0), (EntryId 1 0, Just 1), (EntryId 2 0, Just 0)]+      stopAppGracefully (ShutdownConfig 2 4) app >>= liftIO . assert "exhausted retry processor drains"+    reader.completedCheckpoint >>= assert "checkpoint reaches the next accepted entry" . (== Checkpoint (EntryId 2 0) Nothing)+  records <- R.runRedis producer (R.sendRequest ["HVALS", dest]) >>= either (fail . show) pure+  assert+    "one exhaustion record"+    ( case records of+        [value] -> "max_retries_exceeded" `C8.isInfixOf` value+        _ -> False+    )++rejectionReconnect :: R.ConnectInfo -> R.Connection -> Append -> IO ()+rejectionReconnect info admin append = do+  let src = SourceIdentity "test" Nothing "reject-disconnect"+      dest = "reconnect-failures"+      send :: (R.RedisResult a) => R.Connection -> [ByteString] -> IO a+      send connection request = R.runRedis connection (R.sendRequest request) >>= either (fail . show) pure+      commandInfo = info {R.connectMaxConnections = 1, R.connectNumStripes = Just 1}+  void (append src.streamKey "1-0" [("value", "bad")])+  void (append src.streamKey "2-0" [("value", "good")])+  bracket (R.connect commandInfo) R.disconnect $ \commands -> do+    client <- send @Integer commands ["CLIENT", "ID"]+    let disconnect =+          send @Integer admin ["CLIENT", "KILL", "ID", C8.pack (show client)]+            >>= assert "fixture disconnects the borrowed command socket" . (== 1)+        cfg =+          (rawReaderConfig "reject-disconnect" "index" src Earliest)+            { readerDecode = disconnectingDecoder disconnect,+              readerDeadLetters = Just dest+            }+    withReader (BorrowCommands info commands) cfg $ \reader -> do+      seen <- newChan+      runReader reader (recording seen) $ \app -> do+        liftIO (timeout 3000000 (expectIds seen [EntryId 2 0]) >>= assert "decode rejection recovers the connection" . (== Just ()))+        stopAppGracefully (ShutdownConfig 2 4) app >>= liftIO . assert "rejection processor drains"+      reader.completedCheckpoint >>= assert "checkpoint advances after reconnect" . (== Checkpoint (EntryId 2 0) Nothing)+    send @Integer admin ["HLEN", dest] >>= assert "rejection written once after reconnect" . (== 1)++-- Test-only fault injection at the boundary immediately before the rejection write.+{-# NOINLINE disconnectingDecoder #-}+disconnectingDecoder :: IO () -> RedisEntry -> Either DeadLetterReason RedisEntry+disconnectingDecoder disconnect entry+  | entry.entryId == EntryId 1 0 = unsafePerformIO (disconnect >> pure (Left (InvalidPayload "malformed")))+  | otherwise = Right entry++rejection :: ConnectionSource -> R.Connection -> Append -> IO ()+rejection pools producer append = do+  let src = SourceIdentity "test" Nothing "reject"+      reason = InvalidPayload "malformed"+      raw = rawReaderConfig "reject" "index" src Earliest+  void (append src.streamKey "1-0" [("value", "invalid")])+  saved <- newIORef Nothing+  let store = storeIn saved+      rejecting = raw {readerDecode = const (Left reason), checkpointStore = Just store, readerDeadLetters = Just "failures"}+      failing =+        store+          { saveCheckpoint = \name identity old new ->+              if new.position == EntryId 1 0 then fail "checkpoint store unavailable" else store.saveCheckpoint name identity old new+          }+      noHandler _ = liftIO (fail "decode failure reached the handler")+      failureCount = R.runRedis producer (R.hlen "failures")+  withReader pools (rejecting {checkpointStore = Just failing}) $ \reader ->+    runReader reader noHandler waitApp+  failureCount >>= assert "reject written before failed checkpoint" . (== Right 1)+  readIORef saved >>= assert "failed checkpoint remains at boundary" . (== Just (Checkpoint (EntryId 0 0) Nothing))+  withReader pools rejecting $ \reader ->+    runReader reader noHandler $ \app -> do+      let awaitSave = do+            cursor <- reader.completedCheckpoint+            unless (cursor.position == EntryId 1 0) (threadDelay 1000 >> awaitSave)+      liftIO awaitSave+      void (stopAppGracefully (ShutdownConfig 2 4) app)+  failureCount >>= assert "replayed rejection stored once" . (== Right 1)+  let assertOrigin reader = reader.completedCheckpoint >>= assert "terminal decision leaves cursor intact" . (== Checkpoint (EntryId 0 0) Nothing)+  withReader pools (rejecting {checkpointStore = Nothing, readerDeadLetters = Nothing}) $ \reader -> do+    runReader reader noHandler waitApp+    assertOrigin reader+  withReader pools raw $ \reader -> do+    runReader reader (const (pure (AckHalt (HaltFatal "planned halt")))) waitApp+    assertOrigin reader++handover :: ConnectionSource -> R.Connection -> Append -> IO ()+handover pools producer append = do+  let src = SourceIdentity "test" (Just "generation-1") "handover"+      previous = Checkpoint (EntryId 1 0) (Just "A")+      liveSource = src {streamKey = "empty-live"}+  withReader pools (rawReaderConfig "live" "viewer" liveSource Live) $ \reader -> do+    reader.completedCheckpoint >>= assert "missing stream live boundary" . (== Checkpoint (EntryId 0 0) Nothing)+    void (append liveSource.streamKey "1-0" [("value", "new")])+    seen <- newChan+    runReader reader (recording seen) $ \app -> do+      liftIO $ do+        expectIds seen [EntryId 1 0]+        let blockedRead = do+              clients <- R.runRedis producer (R.sendRequest ["CLIENT", "LIST"]) >>= either (fail . show) pure+              case [ identifier+                   | row <- C8.lines clients,+                     "cmd=xread" `elem` C8.words row,+                     field <- C8.words row,+                     Just identifier <- [C8.stripPrefix "id=" field]+                   ] of+                [identifier] -> pure identifier+                _ -> threadDelay 10000 >> blockedRead+        client <- blockedRead+        killed <- R.runRedis producer (R.sendRequest ["CLIENT", "KILL", "ID", client]) >>= either (fail . show) pure+        assert "disconnect the one dedicated reader socket" (killed == (1 :: Integer))+        void (append liveSource.streamKey "2-0" [("value", "after disconnect")])+        expectIds seen [EntryId 2 0]+      void (stopAppGracefully (ShutdownConfig 2 4) app)+  void (append src.streamKey "1-0" [("revision", "A")])+  void (append src.streamKey "2-0" [("revision", "B"), ("previous", "A"), ("generation", "generation-1")])+  let configs = rawReaderConfig "snapshot" "viewer" src (After previous)+      observeContinuity checkpoint entry =+        let revision = lookup "revision" entry.fields+            valid = lookup "previous" entry.fields == checkpoint.continuity && lookup "generation" entry.fields == src.generation+         in (revision, if valid then Nothing else Just "producer generation or predecessor changed")+      checked = configs {checkContinuity = observeContinuity}+      attach = withReader pools checked $ \reader -> do+        seen <- newChan+        runReader reader (recording seen) $ \app -> do+          liftIO (expectIds seen [EntryId 2 0])+          void (stopAppGracefully (ShutdownConfig 2 4) app)+  withAsync attach $ \other -> attach >> wait other+  void $ R.runRedis producer (R.xdel src.streamKey ("2-0" :| []))+  void (append src.streamKey "3-0" [("revision", "C"), ("previous", "B"), ("generation", "generation-1")])+  gap <- newEmptyMVar+  let strict = checked {onReaderGap = \evidence -> putMVar gap evidence >> pure Resnapshot}+      testGap expected = withReader pools strict $ \reader ->+        runReader reader (const (liftIO (fail "known gap reached the handler"))) $ \app -> do+          liftIO $ takeMVar gap >>= assert "detected continuity evidence" . (== expected) . (.gapEvidence)+          waitApp app+  testGap (ProducerDiscontinuity "producer generation or predecessor changed")+  withReader pools (checked {onReaderGap = const (pure BestEffort)}) $ \reader -> do+    seen <- newChan+    runReader reader (recording seen) $ \app -> do+      liftIO (expectIds seen [EntryId 3 0])+      void (stopAppGracefully (ShutdownConfig 2 4) app)+  void $ R.runRedis producer (R.del (src.streamKey :| []))+  testGap (StreamRolledBack Nothing)++  void (append src.streamKey "4-0" [("revision", "B"), ("previous", "A"), ("generation", "generation-2")])+  testGap (ProducerDiscontinuity "producer generation or predecessor changed")
+ test/ReleaseSpec.hs view
@@ -0,0 +1,244 @@+module Main (main) where++import Control.Concurrent+import Control.Concurrent.Async (withAsync)+import Control.Exception (bracket, displayException, try)+import Control.Monad (unless, void)+import Data.ByteString (ByteString)+import Data.ByteString.Char8 qualified as C8+import Data.IORef+import Database.Redis qualified as R+import Effectful (Eff, IOE, Limit (..), Persistence (..), UnliftStrategy (..), liftIO, runEff, withEffToIO)+import Effectful.Exception qualified as E+import Fixture+import Shibuya+import Shibuya.Adapter.Redis+import Shibuya.Adapter.Redis.Internal+import Streamly.Data.Stream qualified as Stream+import System.Timeout (timeout)++type Effects = '[Tracing, IOE]++main :: IO ()+main = do+  within "combined modes and persistent restart" lifecycle+  within "restricted Redis command and key permissions" $ withRedis permissions+  within "bounded reconnect exhaustion" $ withRedisRestarts reconnectLimit+  putStrLn "Both modes passed persistent restart, independent supervision, ACLs and finite reconnect checks"++within :: String -> IO a -> IO a+within label action = timeout 15000000 action >>= maybe (fail (label <> " timed out")) pure++assert :: String -> Bool -> IO ()+assert label ok = unless ok (fail label)++send :: (R.RedisResult a) => R.Connection -> [ByteString] -> IO a+send conn args = R.runRedis conn (R.sendRequest args) >>= either (fail . show) pure++append :: R.Connection -> ByteString -> ByteString -> IO ()+append conn key identifier = void $ send @ByteString conn ["XADD", key, identifier, "field", "private-payload"]++withConnection :: R.ConnectInfo -> (R.Connection -> IO a) -> IO a+withConnection info = bracket (R.connect info) R.disconnect++runProcessors :: [(ProcessorId, QueueProcessor Effects)] -> (AppHandle Effects -> Eff Effects b) -> IO b+runProcessors processors use = runEff $ runTracingNoop $ do+  result <- runApp defaultAppConfig processors+  app <- either (liftIO . fail . show) pure result+  use app `E.finally` void (stopAppGracefully (ShutdownConfig 0.1 1) app)++lifecycle :: IO ()+lifecycle = withRedisRestarts $ \start ->+  start $ \info stop -> withConnection info $ \admin -> do+    let src = SourceIdentity "release" Nothing "private-source"+        key = src.streamKey+        worker consumer = rawGroupConfig "worker" src "jobs" consumer (CreateIfAbsent (EntryId 0 0))+        options = defaultRuntimeOptions {reconnectAttempts = 30, prefetchLimit = 2}+    append admin key "1-0"+    checkpoint <- newIORef Nothing+    entered <- newEmptyMVar+    parked <- newEmptyMVar+    requestStop <- newEmptyMVar+    aStopped <- newEmptyMVar+    projected <- newChan+    consumed <- newChan+    events <- newIORef []+    let store = CheckpointStore (\_ _ -> readIORef checkpoint) (\_ _ _ new -> writeIORef checkpoint (Just new))+        projection = (rawReaderConfig "projection" "reports" src Earliest) {checkpointStore = Just store}+        observeEvent event = atomicModifyIORef' events (\seen -> (event : seen, ()))+        track channel message = liftIO $ do+          writeChan channel message.envelope.payload.entryId+          pure AckOk+        runA = withRedisRuntime (OwnPools info) options $ \runtime -> do+          a <- newGroupWorker runtime (worker "a")+          let blocked message = liftIO $ do+                putMVar entered message.envelope.payload.entryId+                () <- readMVar parked+                pure AckOk+          runProcessors [(ProcessorId "a", groupProcessor a blocked)] $ \app -> do+            liftIO (readMVar requestStop)+            graceful <- stopAppGracefully (ShutdownConfig 0.1 1) app+            repeated <- stopAppGracefully (ShutdownConfig 0.1 1) app+            liftIO $ do+              assert "forced shutdown result is repeatable" (not graceful && not repeated)+              putMVar aStopped ()+    withAsync runA $ \_ -> do+      readMVar entered >>= assert "A receives first pending job" . (== EntryId 1 0)+      withConnection info $ \borrowed ->+        withRedisRuntime (BorrowCommands info borrowed) (options {observe = observeEvent}) $ \readerRuntime ->+          withRedisRuntime (OwnPools info) (options {observe = observeEvent}) $ \groupRuntime -> do+            reader <- newReader readerRuntime projection+            b <- newGroupWorker groupRuntime (worker "b")+            runProcessors+              [ (ProcessorId "reader", readerProcessor reader (track projected)),+                ( ProcessorId "b",+                  groupProcessor+                    b+                    ( \message -> do+                        _ <- track consumed message+                        pure $+                          if message.envelope.payload.entryId == EntryId 3 0+                            then AckHalt (HaltFatal "planned worker halt")+                            else AckOk+                    )+                )+              ]+              $ \app -> do+                liftIO $ do+                  readChan projected >>= assert "projection sees same input as A" . (== EntryId 1 0)+                  await $ (== Just (Checkpoint (EntryId 1 0) Nothing)) <$> readIORef checkpoint+                  await $ C8.isInfixOf "blocked_clients:2" <$> send @ByteString admin ["INFO", "clients"]+                  stop+                  putMVar requestStop ()+                  readMVar aStopped+                  readIORef checkpoint >>= assert "forced stop across outage does not move cursor" . (== Just (Checkpoint (EntryId 1 0) Nothing))+                startOnSameServer start key app projected consumed borrowed+            stopped <- readIORef events+            assert+              "bounded adapter event vocabulary"+              ( all (`elem` stopped) [Delivered, Acknowledged, Reclaimed]+                  && not ("private" `C8.isInfixOf` C8.pack (show stopped))+              )+  where+    startOnSameServer start key app projected consumed borrowed = do+      -- Run adapter callbacks in the surrounding Eff scope and hold the+      -- restarted child open with a barrier until the shutdown completes.+      ready <- liftIO newEmptyMVar+      done <- liftIO newEmptyMVar+      withEffToIO (ConcUnlift Persistent Unlimited) $ \unlift ->+        withAsync (start (\info _ -> withConnection info (\fresh -> putMVar ready fresh >> readMVar done))) $ \_ ->+          unlift $ flip E.finally (liftIO (putMVar done ())) $ do+            fresh <- liftIO (readMVar ready)+            liftIO $ do+              rows <- send @[[R.Reply]] fresh ["XPENDING", key, "jobs", "-", "+", "2"]+              assert "Redis restart retained A's pending row" $ case rows of+                [[R.Bulk (Just "1-0"), R.Bulk (Just "a"), _, _]] -> True+                _ -> False+              void $ send @[ByteString] fresh ["XCLAIM", key, "jobs", "a", "0", "1-0", "IDLE", "60000", "JUSTID"]+              append fresh key "2-0"+              readChan projected >>= assert "independent reader continues after reconnection" . (== EntryId 2 0)+              jobs <- sequence [readChan consumed, readChan consumed]+              assert "replacement worker resumes new and abandoned work" (EntryId 1 0 `elem` jobs && EntryId 2 0 `elem` jobs)+              await (null <$> send @[[R.Reply]] fresh ["XPENDING", key, "jobs", "-", "+", "2"])+              append fresh key "3-0"+              readChan consumed >>= assert "worker receives its halt job" . (== EntryId 3 0)+              append fresh key "4-0"+              sequence [readChan projected, readChan projected] >>= assert "reader progresses after sibling halt" . (== [EntryId 3 0, EntryId 4 0])+            drained <- stopAppGracefully (ShutdownConfig 1 2) app+            liftIO $ do+              assert "surviving processors drain" drained+              jobs <- send @[[R.Reply]] fresh ["XPENDING", key, "jobs", "-", "+", "2"]+              assert "only the deliberately halted job remains pending" $ case jobs of+                [[R.Bulk (Just "3-0"), R.Bulk (Just "b"), _, _]] -> True+                _ -> False+              R.runRedis borrowed R.ping >>= assert "borrowed commands remain live through drain" . (== Right R.Pong)++await :: IO Bool -> IO ()+await predicate = do+  result <- predicate+  unless result (threadDelay 10000 >> await predicate)++permissions :: R.ConnectInfo -> IO ()+permissions info = withConnection info $ \admin -> do+  let identifier = SourceIdentity "acl" Nothing "acl-input"+      key = identifier.streamKey+      passwords = [">test-password", "on", "~acl-input", "~acl-rejections", "+ping"]+      user role privileges = send @R.Status admin (["ACL", "SETUSER", role, "reset"] <> passwords <> privileges)+      login role = info {R.connectUsername = Just role, R.connectAuth = Just "test-password"}+      readerCommands = ["+xread", "+xinfo|stream", "+hsetnx"]+      workerCommands =+        [ "~shibuya:group:v1:*",+          "+xreadgroup",+          "+xgroup|create",+          "+xpending",+          "+script|load",+          "+evalsha",+          "+eval",+          "+xrange",+          "+xclaim",+          "+time",+          "+exists",+          "+hget",+          "+hset",+          "+hdel",+          "+del",+          "+hsetnx"+        ]+      reason = InvalidPayload "bad job"+  let gap = ReaderGap identifier (Checkpoint (EntryId 0 0) Nothing) Nothing (ProducerDiscontinuity "private-payload")+      failures = [displayException (ReaderHistoryLost gap Resnapshot), displayException (CommandRejected (R.Error "acl-input"))]+  assert+    "runner failure text redacts keys and producer details"+    ( all+        ( \failure ->+            not ("acl-input" `C8.isInfixOf` C8.pack failure)+              && not ("private-payload" `C8.isInfixOf` C8.pack failure)+        )+        failures+    )+  _ <- user "projection" readerCommands+  -- Omit XACK for the first finalizer. The script writes the rejection before+  -- encountering the ACL error, and the exact callback can finish after grant.+  _ <- user "worker" workerCommands+  append admin key "1-0"+  let readerCfg = (rawReaderConfig "projection" "acl" identifier Earliest) {readerDeadLetters = Just "acl-rejections"}+  withRedisRuntime (OwnPools (login "projection")) defaultRuntimeOptions $ \runtime -> do+    reader <- newReader runtime readerCfg+    processed <- newEmptyMVar+    runProcessors [(ProcessorId "projection", readerProcessor reader (\_ -> liftIO (putMVar processed ()) >> pure (AckDeadLetter reason)))] $ \app -> do+      liftIO (readMVar processed)+      stopAppGracefully (ShutdownConfig 1 2) app >>= liftIO . assert "restricted reader drains"+    denied <- try @AdapterError (runCommand runtime (R.get "alien-key"))+    assert "reader credentials deny unrelated commands and keys" (either (const True) (const False) denied)+  withRedisRuntime (OwnPools (login "worker")) defaultRuntimeOptions $ \runtime -> do+    let cfg =+          (rawGroupConfig "worker" identifier "acl-group" "worker-one" (CreateIfAbsent (EntryId 0 0)))+            { groupDeadLetters = Just "acl-rejections"+            }+    invalid <- try @AdapterError (newGroupWorker @Effects runtime cfg {groupInFlight = 0})+    assert "invalid group capacity rejected before creating a group" (case invalid of Left InvalidOptions -> True; _ -> False)+    send @[R.Reply] admin ["XINFO", "GROUPS", key] >>= assert "invalid worker left no group" . null+    worker <- newGroupWorker runtime cfg+    runEff $ runTracingNoop $ do+      (item, _) <- Stream.uncons worker.groupAdapter.source >>= maybe (liftIO (fail "restricted delivery missing")) pure+      let AckHandle finish = item.ack+      failed <- E.try @AdapterError (finish (AckDeadLetter reason))+      liftIO $ do+        assert "partial Redis script failed as intended" (either (const True) (const False) failed)+        send @Integer admin ["HLEN", "acl-rejections"] >>= assert "both failure records exist before group ack" . (== 2)+        send @[[R.Reply]] admin ["XPENDING", key, "acl-group", "-", "+", "2"] >>= assert "partial write leaves the PEL row" . ((== 1) . length)+        void $ send @R.Status admin ["ACL", "SETUSER", "worker", "+xack"]+      finish (AckDeadLetter reason)+      finish (AckDeadLetter reason)+  send @Integer admin ["HLEN", "acl-rejections"] >>= assert "same failure record after partial replay" . (== 2)+  send @[[R.Reply]] admin ["XPENDING", key, "acl-group", "-", "+", "2"] >>= assert "proper worker ACL lets replay acknowledge" . null++reconnectLimit :: (forall b. (R.ConnectInfo -> IO () -> IO b) -> IO b) -> IO ()+reconnectLimit start = start $ \info stop -> do+  let options = defaultRuntimeOptions {reconnectAttempts = 1, reconnectDelayMicros = 20000, pollMillis = 20, commandTimeoutMicros = 300000}+  withRedisRuntime (OwnPools info) options $ \runtime -> do+    stop+    exhausted <- try @E.SomeException (timeout 2000000 (pollStream runtime (R.xreadOpts [("idle", "0-0")] (readBatchOptions runtime))))+    assert "connection failure differs from a quiet poll and exhausts finite budget" $ case exhausted of+      Left _ -> True+      _ -> False
+ test/TelemetrySpec.hs view
@@ -0,0 +1,170 @@+module Main (main) where++import Control.Concurrent (newEmptyMVar, putMVar, readMVar)+import Control.Exception (bracket)+import Control.Monad (unless, void)+import Data.ByteString (ByteString)+import Data.ByteString.Char8 qualified as C8+import Data.Foldable (toList)+import Data.IORef (readIORef)+import Data.Maybe (isNothing)+import Data.Text (Text)+import Data.Text.Encoding (decodeUtf8)+import Data.Text.IO qualified as Text+import Database.Redis qualified as Redis+import Effectful (IOE, liftIO, runEff)+import Effectful.Exception qualified as Exception+import Fixture (withRedis)+import OpenTelemetry.Attributes (emptyAttributes, lookupAttribute, toAttribute)+import OpenTelemetry.Exporter.InMemory (inMemoryListExporter)+import OpenTelemetry.Trace qualified as SDK+import OpenTelemetry.Trace.Core qualified as OTel+import OpenTelemetry.Trace.Id (Base (Base16), spanIdBaseEncodedText, traceIdBaseEncodedText)+import OpenTelemetry.Trace.Id.Generator (IdGenerator (DefaultIdGenerator))+import OpenTelemetry.Util (appendOnlyBoundedCollectionValues)+import Shibuya+import Shibuya.Adapter.Redis+import Shibuya.Telemetry.Propagation (injectTraceContext)+import Shibuya.Telemetry.Semantic (processSpanName)+import System.Environment (getArgs)+import System.Timeout (timeout)++type Effects = '[Tracing, IOE]++assert :: String -> Bool -> IO ()+assert label condition = unless condition (fail label)++main :: IO ()+main = do+  arguments <- getArgs+  completed <- timeout 15000000 $ withRedis $ \info ->+    bracket (Redis.connect info) Redis.disconnect $ \admin ->+      case arguments of+        [] -> verifyInMemory info admin+        ["--jaeger"] -> exportToJaeger info admin+        _ -> fail "expected no arguments or --jaeger"+  assert "telemetry integration timed out" (completed == Just ())++verifyInMemory :: Redis.ConnectInfo -> Redis.Connection -> IO ()+verifyInMemory info admin = do+  let fields = [("traceparent", "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01"), ("tracestate", "acme=test")]+  (processor, spansRef) <- inMemoryListExporter+  bracket+    (OTel.createTracerProvider [processor] OTel.emptyTracerProviderOptions {OTel.tracerProviderOptionsIdGenerator = DefaultIdGenerator})+    shutdown+    $ \provider -> do+      let tracer = makeTracer provider+      processEntry info admin (Just tracer) "reader" fields reader (AckDeadLetter MaxRetriesExceeded)+      processEntry info admin (Just tracer) "worker" fields worker (AckRetry (RetryDelay 0))+      processEntry info admin (Just tracer) "untraced" [] reader AckOk+      processEntry info admin Nothing "noop" fields reader (AckDeadLetter MaxRetriesExceeded)+  spans <- readIORef spansRef+  let producer = ("0af7651916cd43dd8448eb211c80319c", "b7ad6b7169203331")+      inspect name = do+        named <- traverse (\sp -> (sp,) <$> readIORef (OTel.spanHot sp)) [sp | sp <- spans, OTel.spanKind sp == OTel.Consumer]+        case [(sp, hot) | (sp, hot) <- named, OTel.hotName hot == processSpanName name] of+          [(sp, hot)] -> pure (sp, hot)+          _ -> fail ("expected one consumer span for " <> show name)+      links hot = map (contextIds . OTel.frozenLinkContext) (toList (appendOnlyBoundedCollectionValues (OTel.hotLinks hot)))+      attr key hot = lookupAttribute (OTel.hotAttributes hot) key+      redisAttributes processorName hot = do+        assert "span names Redis as the messaging system" (attr "messaging.system" hot == Just (toAttribute ("redis" :: Text)))+        assert "messaging ID uses the native Redis ID without the stream key" (attr "messaging.message.id" hot == Just (toAttribute ("1-0" :: Text)))+        assert "span carries the Redis entry ID" (attr "shibuya.redis.entry_id" hot == Just (toAttribute ("1-0" :: Text)))+        assert "span destination stays the processor name" (attr "messaging.destination.name" hot == Just (toAttribute (processorName :: Text)))+  (readerSpan, readerHot) <- inspect "reader"+  assert "reader starts a linked root" $+    fst (contextIds (OTel.spanContext readerSpan)) /= fst producer+      && isNothing (OTel.spanParent readerSpan)+      && links readerHot == [producer]+  redisAttributes "reader" readerHot+  assertRejectionTrace admin "reader" readerSpan+  (workerSpan, workerHot) <- inspect "worker"+  parent <- traverse OTel.getSpanContext (OTel.spanParent workerSpan)+  assert "worker uses the producer as parent and link" $+    fst (contextIds (OTel.spanContext workerSpan)) == fst producer+      && fmap contextIds parent == Just producer+      && links workerHot == [producer]+  redisAttributes "worker" workerHot+  assertRejectionTrace admin "worker" workerSpan+  assert "worker span identifies the UTF-8 group" (attr "messaging.consumer.group.name" workerHot == Just (toAttribute ("jobs" :: Text)))+  (_, untracedHot) <- inspect "untraced"+  assert "untraced entries have no link" (null (links untracedHot))+  noopValue <- rejectionValue admin "noop"+  let noopEntry = RedisEntry (SourceIdentity "telemetry" Nothing (streamKeyFor "noop")) (EntryId 1 0) (("value", "test") : fields)+  assert+    "disabled tracing stores the rejection without a consumer context"+    (noopValue == snd (rejectionRecord (LogicalReader "projection") noopEntry MaxRetriesExceeded Nothing))+  putStrLn "Redis telemetry correlation, span attributes and dead-letter context passed"++rejectionValue :: Redis.Connection -> ByteString -> IO ByteString+rejectionValue admin name = do+  result <- Redis.runRedis admin (Redis.sendRequest ["HVALS", name <> "-rejections"])+  case result of+    Right [value] -> pure value+    _ -> fail ("expected one rejection for " <> show name)++assertRejectionTrace :: Redis.Connection -> ByteString -> OTel.ImmutableSpan -> IO ()+assertRejectionTrace admin name sp = do+  value <- rejectionValue admin name+  headers <- injectTraceContext (OTel.wrapSpanContext (OTel.spanContext sp))+  assert "dead letter carries the consumer traceparent" $+    maybe False (`C8.isInfixOf` value) (lookup "traceparent" headers)++exportToJaeger :: Redis.ConnectInfo -> Redis.Connection -> IO ()+exportToJaeger info admin = bracket SDK.initializeGlobalTracerProvider shutdown $ \provider -> do+  let tracer = makeTracer provider+  (headers, trace, parent) <- OTel.inSpan' tracer "redis qualification producer" OTel.defaultSpanArguments {OTel.kind = OTel.Producer} $ \producerSpan -> do+    headers <- injectTraceContext producerSpan+    (trace, parent) <- contextIds <$> OTel.getSpanContext producerSpan+    pure (headers, trace, parent)+  assert "OTLP smoke test generated a sampled producer context" (not (null headers))+  processEntry info admin (Just tracer) "jaeger-worker" headers worker AckOk+  processEntry info admin (Just tracer) "jaeger-reader" headers reader AckOk+  flushed <- OTel.forceFlushTracerProvider provider (Just 5_000_000)+  case flushed of+    OTel.FlushSuccess -> pure ()+    _ -> fail "OTLP trace flush failed"+  Text.putStrLn ("Jaeger producer trace " <> trace <> " span " <> parent)++shutdown :: OTel.TracerProvider -> IO ()+shutdown provider = void (OTel.shutdownTracerProvider provider (Just 5_000_000))++makeTracer :: OTel.TracerProvider -> OTel.Tracer+makeTracer provider = OTel.makeTracer provider (OTel.InstrumentationLibrary "shibuya-redis-qualification" "" "" emptyAttributes) OTel.tracerOptions++contextIds :: OTel.SpanContext -> (Text, Text)+contextIds ctx = (traceIdBaseEncodedText Base16 ctx.traceId, spanIdBaseEncodedText Base16 ctx.spanId)++reader :: ByteString -> RedisRuntime -> Handler Effects RedisEntry -> IO (QueueProcessor Effects)+reader key runtime handler = do+  source <- newReader runtime ((rawReaderConfig "reader" "projection" (SourceIdentity "telemetry" Nothing (streamKeyFor key)) Earliest) {readerDeadLetters = Just (key <> "-rejections")})+  pure (readerProcessor source handler)++worker :: ByteString -> RedisRuntime -> Handler Effects RedisEntry -> IO (QueueProcessor Effects)+worker key runtime handler = do+  group <- newGroupWorker runtime ((rawGroupConfig "worker" (SourceIdentity "telemetry" Nothing (streamKeyFor key)) "jobs" "solo" (CreateIfAbsent (EntryId 0 0))) {groupDeadLetters = Just (key <> "-rejections"), groupRetryLimit = 0})+  pure (groupProcessor group handler)++processEntry ::+  Redis.ConnectInfo ->+  Redis.Connection ->+  Maybe OTel.Tracer ->+  ByteString ->+  TraceHeaders ->+  (ByteString -> RedisRuntime -> Handler Effects RedisEntry -> IO (QueueProcessor Effects)) ->+  AckDecision ->+  IO ()+processEntry info admin tracer name headers create decision = do+  _ <- Redis.runRedis admin (Redis.xadd (streamKeyFor name) "1-0" (("value", "test") : headers)) >>= either (fail . show) pure+  handled <- newEmptyMVar+  withRedisRuntime (OwnPools info) defaultRuntimeOptions $ \runtime -> do+    processor <- create name runtime (const (liftIO (putMVar handled ()) >> pure decision))+    runEff $ maybe runTracingNoop runTracing tracer $ do+      app <- runApp defaultAppConfig [(ProcessorId (decodeUtf8 name), processor)] >>= either (liftIO . fail . show) pure+      flip Exception.finally (stopApp app) $ do+        liftIO (readMVar handled)+        stopAppGracefully (ShutdownConfig 1 2) app >>= liftIO . assert "telemetry processor drains"++streamKeyFor :: ByteString -> ByteString+streamKeyFor name = "telemetry-input:" <> name