sandloom-redis 0.7.0a14__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (27) hide show
  1. sandloom_redis-0.7.0a14/.gitignore +4 -0
  2. sandloom_redis-0.7.0a14/CHANGELOG.md +34 -0
  3. sandloom_redis-0.7.0a14/LICENSE +202 -0
  4. sandloom_redis-0.7.0a14/NOTICE +8 -0
  5. sandloom_redis-0.7.0a14/PKG-INFO +54 -0
  6. sandloom_redis-0.7.0a14/README.md +38 -0
  7. sandloom_redis-0.7.0a14/pyproject.toml +40 -0
  8. sandloom_redis-0.7.0a14/src/sandloom_redis/__init__.py +6 -0
  9. sandloom_redis-0.7.0a14/src/sandloom_redis/_errors.py +218 -0
  10. sandloom_redis-0.7.0a14/src/sandloom_redis/_eviction_guard.py +174 -0
  11. sandloom_redis-0.7.0a14/src/sandloom_redis/_url.py +51 -0
  12. sandloom_redis-0.7.0a14/src/sandloom_redis/atomic_store.py +734 -0
  13. sandloom_redis-0.7.0a14/src/sandloom_redis/broadcast.py +547 -0
  14. sandloom_redis-0.7.0a14/src/sandloom_redis/cache.py +831 -0
  15. sandloom_redis-0.7.0a14/src/sandloom_redis/eventbus/__init__.py +9 -0
  16. sandloom_redis-0.7.0a14/src/sandloom_redis/eventbus/driver.py +320 -0
  17. sandloom_redis-0.7.0a14/src/sandloom_redis/eventbus/streams_consume.py +655 -0
  18. sandloom_redis-0.7.0a14/src/sandloom_redis/eventbus/streams_groups.py +473 -0
  19. sandloom_redis-0.7.0a14/src/sandloom_redis/eventbus/streams_transport.py +312 -0
  20. sandloom_redis-0.7.0a14/src/sandloom_redis/eventbus/streams_transport_base.py +308 -0
  21. sandloom_redis-0.7.0a14/src/sandloom_redis/lease.py +464 -0
  22. sandloom_redis-0.7.0a14/src/sandloom_redis/testing/__init__.py +19 -0
  23. sandloom_redis-0.7.0a14/src/sandloom_redis/testing/family.py +155 -0
  24. sandloom_redis-0.7.0a14/src/sandloom_redis/testing/isolation.py +193 -0
  25. sandloom_redis-0.7.0a14/src/sandloom_redis/testing/ownership.py +108 -0
  26. sandloom_redis-0.7.0a14/src/sandloom_redis/testing/resources.py +405 -0
  27. sandloom_redis-0.7.0a14/src/sandloom_redis/testing/urls.py +79 -0
@@ -0,0 +1,4 @@
1
+ # Build artifacts from `uv build` — not committed.
2
+ dist/
3
+ build/
4
+ *.egg-info/
@@ -0,0 +1,34 @@
1
+ # Changelog — sandloom-redis
2
+
3
+ ## [Unreleased]
4
+
5
+ ## [0.7.0a14] — 2026-11-16
6
+
7
+ ### Breaking changes
8
+
9
+ - **The Redis drivers take no url and no client bound from a setting, and no instance follows the url of another** (idk-flat-urls-z, idk-flat-urls-no-follows). The `redis` cache, `atomic_store`, `lease` and `broadcast` drivers and the `streams` event bus read their `url` and their bounds from the options of their instance, and an instance with no `url` is refused (`MissingUrlError`). `CACHE_URL` and the `CACHE_*` bounds no longer exist as settings (the kernel refuses them), and the drivers' `settings_fill` is empty. A `broadcast` and the synthesized development `atomic_store` no longer take the url of `cache.default` either: each states its own. The bounds keep the defaults the settings had. The `redis` harness family no longer rewrites a flat variable: it moves the database index of each instance `url`, and of the Celery `broker` through the kernel layout. Upgrade: state the `url` of every Redis instance in `INFRA` ([Upgrading to 0.7.0a14](https://sandloom.dev/docs/operate/upgrade/#upgrading-to-070a14-the-flat-redis-settings)). Two cases need care. An environment whose `INFRA` `cache.default` url differs from the old `CACHE_URL` (a staging setup) must state `atomic_store.security.url` as the old `CACHE_URL` before upgrading, or revocations and blocks written earlier are not seen. A rolling deploy with a declared `broadcast` must state `broadcast.<instance>.url` first, or old and new processes publish on different Redis servers.
10
+
11
+ ### Added
12
+
13
+ - **A startup warning when a persistent instance shares the cache's Redis database** (idk-flat-urls-no-follows). A `redis` `atomic_store`, a `redis` `lease` or a `streams` event bus whose `host:port/db` is the one of `cache.default` logs one WARNING naming both instances and the endpoint (never a password): a cache that evicts can drop the keys they must keep. It refuses nothing and does not depend on the order the instances start in. An instance the kernel synthesized (not written in `INFRA`: the development `atomic_store` and the default `streams` bus the kernel builds without one) is logged at INFO instead, so the warning keeps its meaning. The drivers register their endpoints in `sandloom.driverkit.shared_endpoints`, drop them when they close, and a path that still holds an `@` (an unencoded password) is never echoed.
14
+ - **The `redis` atomic store moves per xdist worker** (idk-flat-urls-z). `RedisAtomicStoreProvider.test_isolation` rewrites the store `url` to the worker's own Redis database through the same driverkit helper the cache uses, so the security store of a worker stays on the worker's cache database (the testing fixtures write revocation and block marks through the cache, the app reads them from the store). A test app whose security store shares its cache url keeps them equal under `-n`.
15
+ - **`hiredis` is an optional extra** (idk-low5-product). `pip install 'sandloom-redis[hiredis]'` adds the hiredis parser of the Redis client (`redis[hiredis]>=5.2.1,<6`); the plain install is unchanged.
16
+
17
+ ### Changed
18
+
19
+ - **An unknown Redis reply is no longer an outage: the five drivers now share one classifier (`sandloom_redis._errors`).** A connection error, a socket `OSError` and the transient replies `LOADING`, `READONLY`, `MASTERDOWN`, `TRYAGAIN`, `CLUSTERDOWN`, `BUSY`, `OOM`, `MISCONF` (the server stops writes after a failed save), `NOREPLICAS` (`min-replicas-to-write` unmet), `MOVED` / `ASK` (a single-node URL pointed at a cluster node) and `UNBLOCKED` (a read cut by a failover) map to `Unavailable` (the reply word is read through the client's `Command # n (...) of pipeline caused error:` annotation too); a timeout to `Timeout`; `AuthenticationError`, `NoPermissionError` and `NOAUTH` / `WRONGPASS` / `NOPERM` to `PermissionDenied`; any other `ResponseError` (an unknown `ERR ...`: an oversized value, a script error) and a client `DataError` to `InvalidArgument`, which is not retryable. Before, the cache, atomic store, lease and broadcast drivers mapped every such reply to `Unavailable`, so the outbox relay (which trusts the mapped class) parked the row for ever as an outage instead of spending an attempt and dead-lettering it. An exception that is not a Redis failure (a `TypeError` of a bug) is no longer mapped at all: it propagates as itself, so it cannot park relay rows as an outage. The lease and the atomic store no longer read a transient reply to `CONFIG GET` as the server refusing the read. The message names the error type only.
20
+ - The Streams batch publish chains its `PartialPublish` from the MAPPED error, with the raw Redis error as that error's `__cause__` (it chained the raw error), so the relay judges the batch path like the per-row path: a `PermissionDenied` batch is an outage, an unknown `ERR` reply is not.
21
+ - Add the Redis drivers `atomic_store.redis`, `lease.redis` and `broadcast.redis` as an optional package. They left the kernel wheel; `sandloom[redis]` installs this package.
22
+ - Add the Streams event bus driver `eventbus.streams` (`sandloom_redis.eventbus.driver`, with its transport in `sandloom_redis.eventbus.streams_*`), moved from the kernel wheel. Its `isolation_identity()` is `streams:<run_id>` of the reached server.
23
+ - Add the Redis cache driver `cache.redis` (`sandloom_redis.cache`), moved from the kernel wheel. Its `health()` also runs a no-op script, so a server that refuses scripting reports `fail`.
24
+ - **A `redis` instance with no url is refused at startup, and the message names the INFRA option** (idk-flat-urls-s0a). Opening any of the five Redis drivers (`cache`, `atomic_store`, `broadcast`, `lease` and the `streams` event bus; `aopen`, run by the registry at startup) raises `MissingUrlError` (a `ValueError`, `fatal_at_startup`, so startup aborts in every environment, development included) saying `redis atomic_store instance 'security' has no url: set the INFRA option atomic_store.security.url, e.g. INFRA='{...}'`. A `streams` bus with no url of its own still runs on the default cache client and is refused only when that client has no url either. One helper (`sandloom_redis._url.require_url`) does the check for all five. Building a provider and a provider built by hand (`create_redis_cache`, a client or client factory passed in) are unchanged.
25
+ - **The Redis test family isolates `INFRA` urls per worker** (idk-flat-urls-s0b). It moves the `url`, `broker` and `backend` of every `INFRA` instance per xdist worker (the Celery task queue's `broker` included), and claims and allocates the indexes of those urls.
26
+ - **A `MOVED` / `ASK` reply maps to an `Unavailable` that carries a hint** (idk-low-batch-4). The error has `hint` "cluster redirect: is the client cluster-aware?" (the sentence only, never the address or slot), which the outbox relay prints in its outage warning. The class and `retryable` are unchanged. The hint is set as an attribute after the error is built.
27
+
28
+ ### Fixed
29
+
30
+ - **The `redis` atomic_store and lease judge `maxmemory-policy` on every new connection, before its first command** (idk-atomic-store-conn-check). A flag cannot judge a socket it did not see: the retrying client and the pool's liveness probe reconnect a dropped socket without raising, and a growing pool opens new ones, after a failover or a DNS repoint possibly to a server that came back evicting. The command that caused the reconnect used to run unchecked on the new socket. Now the pool's connect function sends `CONFIG GET maxmemory-policy` on THAT connection on every connect (the first included); an evicting policy is `InvalidArgument` and a refused read follows `never_evicts_check` (`PermissionDenied` under `verify`), raised before any command is sent. The price is one round trip per new socket. The lease pool, which had no such hook, gets it (an evicted fence key would repeat a fence). A transient failure of the read itself stays `Unavailable` and is no verdict.
31
+ - **A client rebuilt for another loop reopens the atomic_store's check**, as the lease's does (idk-atomic-store-conn-check). The check-in-flight race of the old flag (a check that started before a reconnect set the flag after it) no longer matters: each socket is judged by its own connect.
32
+ - **A lease health probe on a socket the pool refused answers the policy's reason** (`evicting_policy`, `noeviction_unverifiable` or `eviction_check_refused`), as the atomic_store's does, not the error type of the refusal; the eviction verdict and the policy reader are one shared implementation of both drivers, and a refusal is no `ConnectionError`, so the client's retry never dials and checks again for it (idk-atomic-store-conn-check).
33
+ - **The `redis` atomic_store checks `maxmemory-policy` on its first operation, not only in `aopen`** (idk-review-a-fixes). A worker or CLI process never runs `aopen`, so it wrote revocation marks, blocks and idempotency reservations into an evicting Redis without a refusal. The check follows the lease's: `never_evicts_check` `verify` or `assume` behave as in `aopen`, a refusal repeats on every operation and is judged again each time, and a transient failure while reading the policy is `Unavailable` and never counts as a passed check.
34
+ - **A `noeviction` lost at runtime refuses the next operation** (idk-review-a-fixes). A `health` probe that finds the policy lost or unreadable (the lease and the atomic_store; also when the probe itself fails with a connection error), and a pooled connection that reconnects (the atomic_store, through the pool's `redis_connect_func`: the retrying client reconnects without raising), open the check again. `health` of the atomic_store no longer repeats a recorded refusal without reading the server: it re-reads every time.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,8 @@
1
+ Sandloom
2
+ Copyright 2026 Vasyl Cherniavskyi
3
+
4
+ The original Sandloom framework code, documentation and examples are licensed
5
+ under the Apache License, Version 2.0. See LICENSE for the full terms.
6
+
7
+ Third-party components and assets retain their own copyright notices and
8
+ licenses. This notice does not replace or modify those terms.
@@ -0,0 +1,54 @@
1
+ Metadata-Version: 2.5
2
+ Name: sandloom-redis
3
+ Version: 0.7.0a14
4
+ Summary: Redis drivers for Sandloom: atomic store, lease, broadcast, cache and the Streams event bus
5
+ License-Expression: Apache-2.0
6
+ License-File: LICENSE
7
+ License-File: NOTICE
8
+ Requires-Python: >=3.11
9
+ Requires-Dist: orjson<4,>=3.13.0
10
+ Requires-Dist: pydantic<3,>=2
11
+ Requires-Dist: redis<6,>=5.2.1
12
+ Requires-Dist: sandloom<0.8,>=0.7.0a14
13
+ Provides-Extra: hiredis
14
+ Requires-Dist: redis[hiredis]<6,>=5.2.1; extra == 'hiredis'
15
+ Description-Content-Type: text/markdown
16
+
17
+ # Sandloom Redis drivers
18
+
19
+ Install this package alongside the matching Sandloom release: `pip install
20
+ 'sandloom[redis]'` brings it in, and a checkout runs `uv pip install -e
21
+ packages/sandloom -e packages/sandloom-redis` from the repository root. Sandloom
22
+ discovers the drivers through the `sandloom.drivers` entry-point group.
23
+
24
+ | Entry point | Capability | Provider |
25
+ | --- | --- | --- |
26
+ | `atomic_store.redis` | `atomic_store` | `sandloom_redis.atomic_store:RedisAtomicStoreProvider` |
27
+ | `lease.redis` | `lease` | `sandloom_redis.lease:RedisLeaseProvider` |
28
+ | `broadcast.redis` | `broadcast` | `sandloom_redis.broadcast:RedisBroadcastProvider` |
29
+ | `cache.redis` | `cache` | `sandloom_redis.cache:RedisCacheProvider` |
30
+ | `eventbus.streams` | `eventbus` | `sandloom_redis.eventbus.driver:StreamsEventBusProvider` |
31
+
32
+ Each driver declares the tier `beta`. The `redis-drivers` job of `ci.yml`
33
+ (required by the aggregate check "CI required") runs the conformance kits
34
+ (`AtomicStoreConformance`, `LeaseConformance`, `BroadcastConformance`,
35
+ `CacheConformance`, `EventTransportConformance`) against
36
+ a real Redis, and this package's tests and types (`mypy` strict).
37
+
38
+ ```sh
39
+ INFRA='{"lease":{"beat":{"driver":"redis"}},"atomic_store":{"security":{"driver":"redis","url":"redis://cache:6379/0"}}}'
40
+ ```
41
+
42
+ The `atomic_store` and `lease` drivers refuse a Redis whose `maxmemory-policy`
43
+ is not `noeviction`. Where a managed service refuses `CONFIG GET`, the option
44
+ `never_evicts_check` set to `assume` lets the operator vouch for the policy; in
45
+ production that needs the accepted risk `unverified_noeviction`.
46
+
47
+ Run the package tests from the repository root against a Redis with enough
48
+ databases for the xdist workers (`redis-server --databases 256`):
49
+
50
+ ```sh
51
+ SANDLOOM_TEST_CACHE_URL=redis://127.0.0.1:6380/0 \
52
+ SANDLOOM_TEST_BROKER_URL=redis://127.0.0.1:6380/1 \
53
+ uv run pytest -n 2 --dist loadfile packages/sandloom-redis/tests
54
+ ```
@@ -0,0 +1,38 @@
1
+ # Sandloom Redis drivers
2
+
3
+ Install this package alongside the matching Sandloom release: `pip install
4
+ 'sandloom[redis]'` brings it in, and a checkout runs `uv pip install -e
5
+ packages/sandloom -e packages/sandloom-redis` from the repository root. Sandloom
6
+ discovers the drivers through the `sandloom.drivers` entry-point group.
7
+
8
+ | Entry point | Capability | Provider |
9
+ | --- | --- | --- |
10
+ | `atomic_store.redis` | `atomic_store` | `sandloom_redis.atomic_store:RedisAtomicStoreProvider` |
11
+ | `lease.redis` | `lease` | `sandloom_redis.lease:RedisLeaseProvider` |
12
+ | `broadcast.redis` | `broadcast` | `sandloom_redis.broadcast:RedisBroadcastProvider` |
13
+ | `cache.redis` | `cache` | `sandloom_redis.cache:RedisCacheProvider` |
14
+ | `eventbus.streams` | `eventbus` | `sandloom_redis.eventbus.driver:StreamsEventBusProvider` |
15
+
16
+ Each driver declares the tier `beta`. The `redis-drivers` job of `ci.yml`
17
+ (required by the aggregate check "CI required") runs the conformance kits
18
+ (`AtomicStoreConformance`, `LeaseConformance`, `BroadcastConformance`,
19
+ `CacheConformance`, `EventTransportConformance`) against
20
+ a real Redis, and this package's tests and types (`mypy` strict).
21
+
22
+ ```sh
23
+ INFRA='{"lease":{"beat":{"driver":"redis"}},"atomic_store":{"security":{"driver":"redis","url":"redis://cache:6379/0"}}}'
24
+ ```
25
+
26
+ The `atomic_store` and `lease` drivers refuse a Redis whose `maxmemory-policy`
27
+ is not `noeviction`. Where a managed service refuses `CONFIG GET`, the option
28
+ `never_evicts_check` set to `assume` lets the operator vouch for the policy; in
29
+ production that needs the accepted risk `unverified_noeviction`.
30
+
31
+ Run the package tests from the repository root against a Redis with enough
32
+ databases for the xdist workers (`redis-server --databases 256`):
33
+
34
+ ```sh
35
+ SANDLOOM_TEST_CACHE_URL=redis://127.0.0.1:6380/0 \
36
+ SANDLOOM_TEST_BROKER_URL=redis://127.0.0.1:6380/1 \
37
+ uv run pytest -n 2 --dist loadfile packages/sandloom-redis/tests
38
+ ```
@@ -0,0 +1,40 @@
1
+ [project]
2
+ name = "sandloom-redis"
3
+ version = "0.7.0a14"
4
+ description = "Redis drivers for Sandloom: atomic store, lease, broadcast, cache and the Streams event bus"
5
+ readme = "README.md"
6
+ requires-python = ">=3.11"
7
+ license = "Apache-2.0"
8
+ license-files = ["LICENSE", "NOTICE"]
9
+ dependencies = [
10
+ "sandloom>=0.7.0a14,<0.8",
11
+ "orjson>=3.13.0,<4",
12
+ "pydantic>=2,<3",
13
+ "redis>=5.2.1,<6",
14
+ ]
15
+
16
+ [project.optional-dependencies]
17
+ # The hiredis parser of the Redis client (faster reply parsing); optional.
18
+ hiredis = ["redis[hiredis]>=5.2.1,<6"]
19
+
20
+ [project.entry-points."sandloom.drivers"]
21
+ "atomic_store.redis" = "sandloom_redis.atomic_store:RedisAtomicStoreProvider"
22
+ "lease.redis" = "sandloom_redis.lease:RedisLeaseProvider"
23
+ "broadcast.redis" = "sandloom_redis.broadcast:RedisBroadcastProvider"
24
+ "cache.redis" = "sandloom_redis.cache:RedisCacheProvider"
25
+ "eventbus.streams" = "sandloom_redis.eventbus.driver:StreamsEventBusProvider"
26
+
27
+ # The Redis half of the test harness (sandloom.driverkit.testing_family),
28
+ # loaded by the kernel's test harness.
29
+ [project.entry-points."sandloom.testing"]
30
+ redis = "sandloom_redis.testing.family:FAMILY"
31
+
32
+ [build-system]
33
+ requires = ["hatchling>=1.27"]
34
+ build-backend = "hatchling.build"
35
+
36
+ [tool.hatch.build.targets.wheel]
37
+ packages = ["src/sandloom_redis"]
38
+
39
+ [tool.hatch.build.targets.sdist]
40
+ include = ["/src", "/LICENSE", "/NOTICE", "/README.md", "/CHANGELOG.md", "/pyproject.toml"]
@@ -0,0 +1,6 @@
1
+ """Redis drivers for Sandloom.
2
+
3
+ One module per capability: ``atomic_store``, ``lease`` and ``broadcast``. Each
4
+ registers through the ``sandloom.drivers`` entry-point group and imports only
5
+ ``sandloom.driverkit``; redis-py loads when a driver runs, not at import.
6
+ """
@@ -0,0 +1,218 @@
1
+ """The one Redis error -> ``InfraError`` classifier of the package (spec 2.1).
2
+
3
+ Which Redis errors mean what is Redis knowledge, so it lives here and not in
4
+ ``driverkit``. The cache, atomic store, lease, broadcast and Streams drivers
5
+ all map through :func:`map_redis_error`; a parity test pins the table.
6
+
7
+ ============================================= ====================
8
+ what Redis (or the socket) raised the ``InfraError``
9
+ ============================================= ====================
10
+ a connection error, ``OSError``, a bad reply ``Unavailable``
11
+ ``LOADING`` ``READONLY`` ``MASTERDOWN``
12
+ ``TRYAGAIN`` ``CLUSTERDOWN`` ``BUSY`` ``OOM``
13
+ ``MISCONF`` ``NOREPLICAS`` ``MOVED`` ``ASK``
14
+ ``UNBLOCKED`` ``Unavailable``
15
+ a timeout (the client's or the socket's) ``Timeout``
16
+ ``AuthenticationError``, ``NoPermissionError``,
17
+ ``NOAUTH`` / ``WRONGPASS`` / ``NOPERM`` ``PermissionDenied``
18
+ ``DataError`` (a value the client cannot send) ``InvalidArgument``
19
+ any OTHER ``ResponseError`` (an unknown
20
+ ``ERR ...``: a refused value, a script error) ``InvalidArgument``
21
+ anything that is not a Redis failure (a re-raised as itself,
22
+ ``TypeError`` of a bug) never mapped
23
+ ============================================= ====================
24
+
25
+ The last row is the one that matters: the outbox relay trusts the mapped class,
26
+ so an error mapped to the retryable ``Unavailable`` is an outage that never
27
+ spends an attempt of the row and never dead-letters it. A reply the server
28
+ sends for THIS request (it will answer the same again) is not an outage: it is
29
+ not retryable, so the relay counts an attempt and dead-letters a poison row.
30
+
31
+ The message carries the error's type name only, never its text: a Redis error
32
+ names the host, the port or a key. A ``MOVED`` / ``ASK`` reply also sets the
33
+ error's ``hint`` (:data:`CLUSTER_REDIRECT_HINT`, a fixed sentence) so the relay's
34
+ outage warning says why; the hint labels a line and decides nothing.
35
+
36
+ Chaining (``raise ... from``) stays with each call site, which knows who reads
37
+ the chain. The relay walks ``__cause__`` through the Streams transport and the
38
+ pub/sub broadcast, so those raise ``from exc``; the cache and the atomic store
39
+ answer a request unit that branches on the class only, so they raise
40
+ ``from None`` and the raw error (its text names the host) never reaches a log.
41
+ """
42
+
43
+ from __future__ import annotations
44
+
45
+ import importlib
46
+ import re
47
+ from functools import cache
48
+ from types import ModuleType
49
+
50
+ from sandloom.driverkit import (
51
+ InfraError,
52
+ InvalidArgument,
53
+ PermissionDenied,
54
+ Timeout,
55
+ Unavailable,
56
+ )
57
+
58
+ #: Replies of a server that is loading, failing over, overloaded, full, unable
59
+ #: to persist (``MISCONF``: the last background save failed and the server stops
60
+ #: writes; ``NOREPLICAS``: ``min-replicas-to-write`` is unmet) or that is not the
61
+ #: node that owns the key (``MOVED`` / ``ASK``: a single-node URL pointed at a
62
+ #: cluster node; ``UNBLOCKED``: a blocked read cut by a failover). The same
63
+ #: command may succeed later, or against the right broker: none of it is the
64
+ #: request's fault. Matched on the reply's first word, for the errors the client
65
+ #: does not turn into its own class.
66
+ TRANSIENT_REPLIES = frozenset(
67
+ {
68
+ "LOADING",
69
+ "READONLY",
70
+ "MASTERDOWN",
71
+ "TRYAGAIN",
72
+ "CLUSTERDOWN",
73
+ "BUSY",
74
+ "OOM",
75
+ "MISCONF",
76
+ "NOREPLICAS",
77
+ "MOVED",
78
+ "ASK",
79
+ "UNBLOCKED",
80
+ }
81
+ )
82
+
83
+ #: Replies that refuse the credentials or the command for this user.
84
+ REFUSED_REPLIES = frozenset({"NOAUTH", "WRONGPASS", "NOPERM"})
85
+
86
+
87
+ def _redis_exceptions() -> ModuleType:
88
+ """``redis.exceptions``, imported when an error is classified."""
89
+ return importlib.import_module("redis.exceptions")
90
+
91
+
92
+ @cache
93
+ def _transient_types() -> tuple[type[BaseException], ...]:
94
+ """The client's own classes for a transient reply (``MasterDownError`` is a
95
+ ``ClusterDownError``)."""
96
+ exceptions = _redis_exceptions()
97
+ return (
98
+ exceptions.ReadOnlyError,
99
+ exceptions.OutOfMemoryError,
100
+ exceptions.ClusterDownError,
101
+ exceptions.TryAgainError,
102
+ exceptions.MovedError, # the cluster client's classes: the text lost the word
103
+ exceptions.AskError,
104
+ )
105
+
106
+
107
+ @cache
108
+ def _backend_types() -> tuple[type[BaseException], ...]:
109
+ """What a Redis backend raises: the client's own errors, a socket's
110
+ ``OSError``, a timeout and an undecodable stored value (the cache and the
111
+ atomic store name it a backend failure)."""
112
+ return (
113
+ _redis_exceptions().RedisError,
114
+ OSError,
115
+ TimeoutError,
116
+ UnicodeDecodeError,
117
+ )
118
+
119
+
120
+ #: What redis-py puts before the reply of a command rejected inside a pipeline
121
+ #: (``Command # 1 (XADD ...) of pipeline caused error: ('MASTERDOWN ...',)``).
122
+ _PIPELINE_NOTE_START = "Command # "
123
+ _PIPELINE_NOTE_END = ") of pipeline caused error: "
124
+ _WORD = re.compile(r"\w+")
125
+
126
+
127
+ def _reply_word(exc: BaseException) -> str:
128
+ """The first word of the reply text (``"BUSY"`` of ``"BUSY script ..."``).
129
+
130
+ A command rejected at queue time inside ``MULTI`` carries the client's
131
+ annotation before the reply: the word is the reply's, taken after the LAST
132
+ ``... of pipeline caused error: `` (the command, whose arguments can hold
133
+ any payload, comes before it; the reply comes after and is the server's).
134
+ """
135
+ text = str(exc)
136
+ if text.startswith(_PIPELINE_NOTE_START) and _PIPELINE_NOTE_END in text:
137
+ reply = text.rpartition(_PIPELINE_NOTE_END)[2].lstrip("('\"")
138
+ found = _WORD.match(reply)
139
+ return found.group() if found else ""
140
+ return text.split(" ", 1)[0]
141
+
142
+
143
+ #: The log hint of a reply from a cluster node that does not own the key (a plain
144
+ #: client pointed at a Redis Cluster gets ``MOVED`` / ``ASK`` for most keys and
145
+ #: retries for ever). A fixed sentence: the ``host:port`` of the reply stays out.
146
+ CLUSTER_REDIRECT_HINT = "cluster redirect: is the client cluster-aware?"
147
+ _CLUSTER_REDIRECT_WORDS = frozenset({"MOVED", "ASK"})
148
+
149
+
150
+ def _is_cluster_redirect(exc: BaseException) -> bool:
151
+ """Whether ``exc`` is a ``MOVED`` / ``ASK`` reply, by its text or, for the
152
+ cluster client's classes (their text lost the word), by its class."""
153
+ exceptions = _redis_exceptions()
154
+ if not isinstance(exc, exceptions.ResponseError):
155
+ return False
156
+ return _reply_word(exc) in _CLUSTER_REDIRECT_WORDS or isinstance(
157
+ exc, exceptions.MovedError | exceptions.AskError
158
+ )
159
+
160
+
161
+ def redis_error_kind(exc: BaseException) -> type[InfraError]:
162
+ """The ``InfraError`` class of a Redis or socket failure (the table above).
163
+
164
+ An allow-list for the retryable answer: only a connection fault, a timeout
165
+ and the transient replies are outages; any other ``ResponseError`` is the
166
+ server refusing this request and is not retryable. An exception that is not
167
+ a backend failure at all (``RedisError``, ``OSError``, ``TimeoutError``,
168
+ ``UnicodeDecodeError``) is re-raised as itself, unmapped.
169
+ """
170
+ exceptions = _redis_exceptions()
171
+ if isinstance(
172
+ exc,
173
+ exceptions.AuthenticationError
174
+ | exceptions.AuthorizationError
175
+ | exceptions.NoPermissionError,
176
+ ):
177
+ return PermissionDenied
178
+ if isinstance(exc, exceptions.TimeoutError | TimeoutError):
179
+ return Timeout
180
+ if isinstance(exc, exceptions.ResponseError):
181
+ word = _reply_word(exc)
182
+ if word in REFUSED_REPLIES:
183
+ return PermissionDenied
184
+ if word in TRANSIENT_REPLIES or isinstance(exc, _transient_types()):
185
+ return Unavailable
186
+ return InvalidArgument
187
+ if isinstance(exc, exceptions.DataError):
188
+ return InvalidArgument
189
+ if isinstance(exc, _backend_types()):
190
+ # ConnectionError (also BusyLoadingError), a socket OSError, a bad reply,
191
+ # a cluster or pub/sub fault: the same call may succeed later.
192
+ return Unavailable
193
+ # Not a Redis failure (a TypeError of a bug): never an outage, which the
194
+ # relay retries for ever. The caller's own ``raise`` of the result never runs.
195
+ raise exc
196
+
197
+
198
+ def map_redis_error(
199
+ exc: BaseException, *, capability: str, instance: str | None, what: str
200
+ ) -> InfraError:
201
+ """``exc`` as an ``InfraError`` named ``"<what>: <type of exc>"``.
202
+
203
+ ``what`` says what was being done (``"cache 'default' get"``). The caller
204
+ raises the result (``from exc`` or ``from None``, see the module docstring).
205
+ A non-backend ``exc`` is re-raised as itself (see :func:`redis_error_kind`).
206
+ """
207
+ kind = redis_error_kind(exc)
208
+ error = kind(
209
+ f"{what}: {type(exc).__name__}", capability=capability, instance=instance
210
+ )
211
+ if _is_cluster_redirect(exc):
212
+ # An attribute, not a ``hint=`` keyword, from when this package also
213
+ # supported ``sandloom>=0.7.0a13``, whose ``InfraError`` has no such
214
+ # keyword. The floor is ``>=0.7.0a14``, which has ``hint``, so the
215
+ # fallback is dead now and ``hint=`` would do; it stays until a release
216
+ # that changes this code on purpose.
217
+ error.hint = CLUSTER_REDIRECT_HINT
218
+ return error