Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .env.test
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ MYSQL__IMAGE=mysql:8.4.13
OTEL_COLLECTOR__IMAGE=otel/opentelemetry-collector-contrib:0.165.0
POSTGRES__IMAGE=postgres:18.7-alpine
PUSHGATEWAY__IMAGE=prom/pushgateway:v1.11.5
REDIS__IMAGE=redis:8.10.3-alpine
REDIS__IMAGE=ghcr.io/redis/docker-library-redis:8.12.0-alpine
SCYLLADB__IMAGE=scylladb/scylla:2026.3.6
STARROCKS__IMAGE=starrocks/allin1-ubuntu:4.1.8
TEMPORAL__IMAGE=temporalio/temporal:1.10.1
Expand Down
6 changes: 5 additions & 1 deletion .github/workflows/link-check.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,5 +22,9 @@ jobs:

- uses: lycheeverse/lychee-action@v2
with:
args: --no-progress --max-retries 2 --accept 200,429 --exclude 'localhost' --exclude '127\.0\.0\.1' 'README.md' 'docs/**/*.md'
args: >-
--no-progress --max-retries 2 --accept 200,429
--exclude 'localhost' --exclude '127\.0\.0\.1'
--remap '^https://github\.com/SyntaxArc/ArchiPy/blob/master/ file://${{ github.workspace }}/'
'README.md' 'docs/**/*.md'
fail: true
21 changes: 19 additions & 2 deletions archipy/configs/sections/redis.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,11 @@ class RedisClusterConfig(BaseModel):

NODES: list[str] = Field(default=[], description="List of cluster node addresses (host:port)")
REQUIRE_FULL_COVERAGE: bool = Field(default=True, description="Require full cluster coverage")
TOPOLOGY_REFRESH_MIN_INTERVAL: float | None = Field(
default=None,
ge=0,
description="Minimum seconds between error-triggered topology refreshes; None uses the client default",
)
READ_FROM_REPLICAS: bool = Field(default=True, description="Allow reading from replica nodes")


Expand Down Expand Up @@ -79,6 +84,7 @@ class RedisRetryConfig(BaseModel):
)
BACKOFF_BASE: float = Field(default=0.008, gt=0, description="Exponential backoff base delay in seconds")
BACKOFF_CAP: float = Field(default=0.512, gt=0, description="Exponential backoff maximum delay in seconds")
FAIL_FAST_MISSING_SOCKET: bool = Field(default=False, description="Skip retries when the Unix socket is missing")
ON_TIMEOUT: bool = Field(default=False, description="Also retry commands that hit a socket timeout")


Expand All @@ -91,12 +97,13 @@ class RedisConfig(BaseModel):
MODE: RedisMode = Field(default=RedisMode.STANDALONE, description="Redis deployment mode")
MASTER_HOST: str | None = Field(default="localhost", description="Redis master host (standalone/sentinel)")
SLAVE_HOST: str | None = Field(default=None, description="Redis slave host (standalone)")
UNIX_SOCKET_PATH: str | None = Field(default=None, min_length=1, description="Standalone Redis Unix socket path")
PORT: int = Field(default=6379, description="Default Redis server port")
DATABASE: int = Field(default=0, description="Redis database number (standalone and sentinel; ignored in cluster)")
USERNAME: str | None = Field(default=None, description="Redis ACL username (Redis 6+); None uses the default user")
PASSWORD: SecretStr | None = Field(default=None, description="Redis password")
DECODE_RESPONSES: Literal[True] = Field(default=True, description="Whether to decode responses")
PROTOCOL: Literal[2, 3] = Field(default=3, description="RESP protocol version (2 or 3)")
PROTOCOL: Literal[2, 3] | None = Field(default=3, description="RESP protocol version; None enables negotiation")
HEALTH_CHECK_INTERVAL: int = Field(default=10, description="Health check interval in seconds")
SOCKET_KEEPALIVE: bool | None = Field(
default=None,
Expand Down Expand Up @@ -136,11 +143,21 @@ def validate_mode_configuration(self) -> Self:
for node in self.SENTINEL.NODES:
self._validate_node_address(node, port_required=True)

elif self.MODE == RedisMode.STANDALONE and not self.MASTER_HOST:
elif not (self.MASTER_HOST or self.UNIX_SOCKET_PATH):
raise ConfigurationError(operation="redis", reason="master_host_required")

return self

@model_validator(mode="after")
def validate_unix_socket(self) -> Self:
"""Validate options for a standalone Unix socket connection."""
if self.UNIX_SOCKET_PATH and (self.MODE != RedisMode.STANDALONE or self.TLS.IS_ENABLED or self.SLAVE_HOST):
raise ConfigurationError(operation="redis", reason="unix_socket_requires_standalone_without_tls_or_replica")
if self.RETRY.FAIL_FAST_MISSING_SOCKET and self.UNIX_SOCKET_PATH is None:
raise ConfigurationError(operation="redis", reason="missing_socket_fast_fail_requires_unix_socket")

return self

@model_validator(mode="after")
def warn_insecure_tls(self) -> Self:
"""Warn when credentials travel without TLS or the server identity is not verified."""
Expand Down
12 changes: 8 additions & 4 deletions archipy/models/dtos/redis/search/aggregation_dto.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
"""DTOs for Redis Search aggregations."""

from typing import Literal
from typing import Annotated, Literal

from pydantic import field_validator
from pydantic import Field, field_validator

from archipy.models.dtos.base_dtos import BaseDTO
from archipy.models.dtos.redis.search.escaping import SearchIdentifier
Expand All @@ -18,12 +18,16 @@ class AggregationDTO(BaseDTO):
query: str = "*"
group_by: list[SearchIdentifier] | None = None
reduce_field: SearchIdentifier | None = None
reduce_function: SearchIdentifier | None = None
reduce_function: Literal["COUNT", "COLLECT"] | None = None
collect_fields: list[SearchIdentifier] = Field(default_factory=list)
collect_sort_by: SearchIdentifier | None = None
collect_sort_direction: Literal["ASC", "DESC"] = "ASC"
collect_limit: tuple[Annotated[int, Field(ge=0)], Annotated[int, Field(ge=0)]] | None = None
sort_by: SearchIdentifier | None = None
sort_direction: Literal["ASC", "DESC"] = "ASC"
limit: int | None = None

@field_validator("sort_direction", mode="before")
@field_validator("sort_direction", "collect_sort_direction", mode="before")
@classmethod
def _normalize_sort_direction(cls, value: object) -> object:
"""Accept any casing of ASC/DESC, as before."""
Expand Down
123 changes: 122 additions & 1 deletion docs/tutorials/adapters/redis.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,16 @@ REDIS__SENTINEL__USERNAME=sentinel-user # sentinel ACL user, used with SENTINEL
`SSL` or when `SSL_CHECK_HOSTNAME` is disabled. `SENTINEL_NODES` entries must be `host:port` and `CLUSTER_NODES` ports
must be numeric; malformed entries raise `ConfigurationError`.

### Protocol negotiation, Unix sockets, and cluster refresh

Set `RedisConfig(PROTOCOL=None)` to negotiate RESP3 and allow redis-py to fall back to RESP2 when a
server rejects `HELLO`. The default is explicit RESP3.

Use `REDIS__UNIX_SOCKET_PATH` for a standalone Unix socket connection. Set
`REDIS__RETRY__FAIL_FAST_MISSING_SOCKET=true` to skip backoff for a missing socket.
Set `REDIS__CLUSTER__TOPOLOGY_REFRESH_MIN_INTERVAL` in seconds to control the minimum time between
error-triggered cluster topology refreshes. The redis-py default applies when the option is unset.

## Basic Usage

=== "Sync"
Expand Down Expand Up @@ -179,13 +189,41 @@ async def run() -> None:
await redis.set("key", "value")
```

Sentinel adapters close their data clients and Sentinel discovery pools when the adapter closes. Async standalone
and cluster clients use redis-py’s automatic RESP3 maintenance notifications on supported deployments.
The Redis Open Source test image lacks this server capability. See [Redis smart client handoffs](https://redis.io/docs/latest/develop/clients/sch/).

### Async iteration

On the async adapter, `scan_iter()` and `sscan_iter()` can be iterated directly with `async for key in
redis.scan_iter(match="user:*")`. The older `async for key in await redis.scan_iter(...)` form still works.

## Caching Patterns

### Server-assisted client-side caching

The sync standalone and cluster adapters accept redis-py's `CacheConfig`. Use explicit RESP3 and
Redis 7.4 or newer. The tracking mode controls which reads Redis tracks, and a predicate can
further limit cache eligibility.

```python
from redis.cache import CacheConfig, TrackingMode

from archipy.adapters.redis.adapters import RedisAdapter

with RedisAdapter(
cache_config=CacheConfig(
tracking_mode=TrackingMode.OPTIN,
cache_predicate=lambda command, keys: command == "GET" and keys[0].startswith("products:"),
),
) as redis:
product = redis.get("products:42")
```

`TrackingMode.OPTOUT` also tracks eligible cached reads. `TrackingMode.PLAIN` is the default.
The sync adapter accepts a `MetadataResolver` to customize command eligibility and cluster
routing. The async cluster adapter accepts an `AsyncMetadataResolver` for routing.

### Function Result Caching

```python
Expand Down Expand Up @@ -266,8 +304,68 @@ logger.info(f"Second call (cached): {result2}")

## Advanced Redis Features

### List batches, set cardinality, and streams

These operations require Redis 8.10+. They are available on both adapters. Use the same hash tag
for keys in a multi-key list, set, or stream operation on Redis Cluster.

```python
redis_adapter.rpush("{tasks}:ready", "a", "b", "c")
redis_adapter.lmovem("{tasks}:ready", "{tasks}:running", count=2, ordering="BULK")
redis_adapter.blmovem("{tasks}:ready", "{tasks}:running", timeout_seconds=1)
redis_adapter.sunioncard(["{tasks}:pending", "{tasks}:active"], limit=100)
redis_adapter.sdiffcard(["{tasks}:pending", "{tasks}:active"])

redis_adapter.xread({"{events}:new": "0-0"}, max_count=100, max_size=65536)
redis_adapter.xreadgroup("workers", "worker-1", {"{events}:new": ">"}, max_count=100)
```

`MAXCOUNT` and `MAXSIZE` apply to the whole stream reply. `MAXSIZE` still permits one oversized entry.
Create the consumer group before calling `xreadgroup`. Stream reply shapes follow the configured RESP version.

The stream-limit and RediSearch integration scenarios run against real Redis.

### Member expiration, sorted set moves, and maintenance

Both adapters expose the redis-py 8.2 command families. The Redis server must support the
command you call. The ArchiPy container suite uses Redis 8.12.

| Capability | Adapter methods |
| --- | --- |
| Set-member expiration | `saddex`, `sexpire`, `spexpire`, `sexpireat`, `spexpireat`, `sttl`, `spttl`, `sexpiretime`, `spexpiretime`, `spersist` |
| Sorted-set moves | `zmove`, `bzmove`, `zmovemember` |
| Bitmap positions and key eviction flags | `bitrangeintarray`, `bless_get`, `bless_set`, `bless_clear`, `bless_scan` |
| Client list | `client_list_iter`, with optional type or client IDs |
| Count-Min Sketch counter widths | `cms_initbydim`, `cms_initbyprob` with `cell_size` in bytes |
| Server backup | `backup_start`, `backup_status`, `backup_list`, `backup_seal`, `backup_abort`, `backup_cleanup` |

Use a shared cluster hash tag for the source and destination of a sorted-set move. Set-member expiration
methods return one status per requested member. An async call to `client_list_iter` is awaited once and
returns an ordinary iterator.

Backups are managed per Redis node. Connect directly to the node you intend to back up. Start the
backup, check `backup_status` for the `incrementing` state, then seal and copy the files returned by
`backup_list` before cleanup.

### Experimental hash fieldsets

redis-py 8.1.0 exposes experimental `HIMPORT` fieldsets on Redis 8.10+. The upstream API can change.
Use the same adapter client to prepare the fieldset, write values in field order, and discard the fieldset.
Await these calls when using the async adapter.

```python
client = redis_adapter.client
client.himport_prepare("profile", ["name", "region"])
try:
client.himport_set("profile:42", "profile", ["Avery", "west"])
finally:
client.himport_discard("profile")
```

### Publish/Subscribe

For shard channels in Redis Cluster, call `spublish` on the adapter and `ssubscribe` on its Pub/Sub handle.

The `publish` and `pubsub` methods are available through the port interface:

```python
Expand Down Expand Up @@ -819,6 +917,10 @@ logger.info(f"Text hits: {text_result.total}, hybrid hits: {len(hybrid_result.hi
Set `text_scorer` (for example `"BM25"` or `"TFIDF"`) on `SearchQueryDTO` or `from_hybrid()` to choose the full-text
scoring function; it is sent to RediSearch as `SCORER`, and an unknown name is rejected by the server.

Use `handle.hybrid_search(query, explain_score=True)` with a redis-py `HybridQuery` when you need
the native `FT.HYBRID` score explanation. The returned `HybridResult` contains score details using
Redis's response shape for the selected protocol. The async Search handle exposes the same method.

### Aggregations

Group and count documents with `AggregationDTO`:
Expand Down Expand Up @@ -846,6 +948,23 @@ agg = handle.aggregate(
logger.info(f"Aggregation rows: {agg['rows']}")
```

Use `COLLECT` to return field values for each group on Redis 8.10+. `collect_fields` selects which fields to collect.
Omit it to collect all fields. `collect_sort_by`, `collect_sort_direction`, and `collect_limit` select and order entries
within each group. `COLLECT` is a preview feature and can require `search-enable-unstable-features` on the server.

```python
by_category = handle.aggregate(
AggregationDTO(
group_by=["category"],
reduce_function="COLLECT",
reduce_field="titles",
collect_fields=["title"],
collect_sort_by="title",
collect_limit=(0, 10),
),
)
```

### Schema Changes, Aliases, and Index Lifecycle

```python
Expand All @@ -870,6 +989,8 @@ handle.drop_index(delete_documents=True)
handle.delete_alias("products-view")
```

Call `handle.list_aliases()` to list the aliases assigned to that index on Redis 8.10+.

### Untrusted Input and Escaping

`SearchQueryDTO.query`, `filter_expr` and `AggregationDTO.query` are raw RediSearch syntax and are **not** escaped. Never
Expand All @@ -885,7 +1006,7 @@ hybrid = SearchQueryDTO.from_hybrid(quote_phrase(user_text), [0.1, 0.2, 0.3])
```

Identifier-like fields (`vector_field`, `score_field`, `return_fields`, `group_by`, `sort_by`, `reduce_field`,
`reduce_function`) are validated to letters, digits, `_`, `.`, `$` and `-` (with an optional leading `@`), and
`collect_fields`) are validated to letters, digits, `_`, `.`, `$` and `-` (with an optional leading `@`), and
`sort_direction` must be `ASC` or `DESC`; anything else raises a Pydantic `ValidationError`.

### Asynchronous RediSearch
Expand Down
Loading
Loading