mainspring-session-redis 0.1.0__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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 mainspring contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,71 @@
1
+ Metadata-Version: 2.4
2
+ Name: mainspring-session-redis
3
+ Version: 0.1.0
4
+ Summary: Redis session store and run checkpoint for mainspring.
5
+ Author: mainspring contributors
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Classifier: Development Status :: 4 - Beta
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python :: 3 :: Only
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Programming Language :: Python :: 3.14
16
+ Classifier: Typing :: Typed
17
+ Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
18
+ Requires-Dist: mainspring-agent
19
+ Requires-Dist: redis>=5.0,<7
20
+ Requires-Python: >=3.11
21
+ Project-URL: Homepage, https://github.com/chyong/mainspring
22
+ Project-URL: Documentation, https://github.com/chyong/mainspring/tree/main/docs
23
+ Project-URL: Repository, https://github.com/chyong/mainspring
24
+ Project-URL: Issues, https://github.com/chyong/mainspring/issues
25
+ Description-Content-Type: text/markdown
26
+
27
+ # mainspring-session-redis
28
+
29
+ Redis 会话后端 + RunCheckpoint 实现(T4-3)。实现 core 的两个 Protocol,与 SQLite 外挂共用
30
+ 同一套接口契约测试(`tests/test_session_backends.py`),换后端只改 yaml。
31
+
32
+ ## 用法
33
+
34
+ ```python
35
+ from mainspring_session_redis import open_redis, backend_factory
36
+
37
+ store, checkpoint = open_redis("redis://:mainspring@127.0.0.1:6379/0")
38
+ await store.append("s1", [Message(id="m1", role="user", content="你好")])
39
+ ```
40
+
41
+ yaml 装配(core 不反向依赖外挂:工厂由调用方注入):
42
+
43
+ ```yaml
44
+ session:
45
+ backend: redis
46
+ url: redis://:mainspring@127.0.0.1:6379/0
47
+ ```
48
+
49
+ ```python
50
+ runner = build_runner(config, backends={"redis": backend_factory}, checkpoint=checkpoint)
51
+ ```
52
+
53
+ `url` 缺省取 `MAINSPRING_SESSION_REDIS_URL`,再缺省用 compose 默认地址。
54
+
55
+ ## 设计要点
56
+
57
+ 1. **幂等 append 用 Lua 脚本原子收口**:一次往返内完成「查 Message.id 是否已存在 + 追加」,
58
+ 多 worker 并发写同一 session 不会出现检查与写入之间的竞态;`Message.id` 为 NULL 时照写不去重。
59
+ 2. **快照存 hash**:`payload / status / saved_at` 三字段,`save_step` 整包覆盖。
60
+ 3. **条件写 `save_step_if`**:带期望状态的 CAS,approve / deny 跨进程竞态下只有一方能把挂起
61
+ run 从 `pending` 推进(RunCheckpoint 契约之外的扩展能力,SQLite / Postgres 同样提供)。
62
+ 4. **key 带 hash tag** `{session_id}` / `{run_id}`:同一会话/运行的多把 key 落同一 slot,
63
+ Redis Cluster 下 Lua 脚本仍合法。
64
+ 5. **客户端懒连接**:yaml 装配阶段不依赖 Redis 在线;`aclose()` 关闭共享客户端。
65
+
66
+ ## 验收
67
+
68
+ - `docker compose up -d redis` 后跑 `pytest tests/test_session_backends.py -k redis`;
69
+ - 覆盖:append 幂等 / NULL 不去重 / 会话隔离与删除 / 快照八要素 roundtrip / 覆盖写 /
70
+ 并发双写 / 条件写单赢家;
71
+ - core 零反向依赖由 import-linter 守护。
@@ -0,0 +1,45 @@
1
+ # mainspring-session-redis
2
+
3
+ Redis 会话后端 + RunCheckpoint 实现(T4-3)。实现 core 的两个 Protocol,与 SQLite 外挂共用
4
+ 同一套接口契约测试(`tests/test_session_backends.py`),换后端只改 yaml。
5
+
6
+ ## 用法
7
+
8
+ ```python
9
+ from mainspring_session_redis import open_redis, backend_factory
10
+
11
+ store, checkpoint = open_redis("redis://:mainspring@127.0.0.1:6379/0")
12
+ await store.append("s1", [Message(id="m1", role="user", content="你好")])
13
+ ```
14
+
15
+ yaml 装配(core 不反向依赖外挂:工厂由调用方注入):
16
+
17
+ ```yaml
18
+ session:
19
+ backend: redis
20
+ url: redis://:mainspring@127.0.0.1:6379/0
21
+ ```
22
+
23
+ ```python
24
+ runner = build_runner(config, backends={"redis": backend_factory}, checkpoint=checkpoint)
25
+ ```
26
+
27
+ `url` 缺省取 `MAINSPRING_SESSION_REDIS_URL`,再缺省用 compose 默认地址。
28
+
29
+ ## 设计要点
30
+
31
+ 1. **幂等 append 用 Lua 脚本原子收口**:一次往返内完成「查 Message.id 是否已存在 + 追加」,
32
+ 多 worker 并发写同一 session 不会出现检查与写入之间的竞态;`Message.id` 为 NULL 时照写不去重。
33
+ 2. **快照存 hash**:`payload / status / saved_at` 三字段,`save_step` 整包覆盖。
34
+ 3. **条件写 `save_step_if`**:带期望状态的 CAS,approve / deny 跨进程竞态下只有一方能把挂起
35
+ run 从 `pending` 推进(RunCheckpoint 契约之外的扩展能力,SQLite / Postgres 同样提供)。
36
+ 4. **key 带 hash tag** `{session_id}` / `{run_id}`:同一会话/运行的多把 key 落同一 slot,
37
+ Redis Cluster 下 Lua 脚本仍合法。
38
+ 5. **客户端懒连接**:yaml 装配阶段不依赖 Redis 在线;`aclose()` 关闭共享客户端。
39
+
40
+ ## 验收
41
+
42
+ - `docker compose up -d redis` 后跑 `pytest tests/test_session_backends.py -k redis`;
43
+ - 覆盖:append 幂等 / NULL 不去重 / 会话隔离与删除 / 快照八要素 roundtrip / 覆盖写 /
44
+ 并发双写 / 条件写单赢家;
45
+ - core 零反向依赖由 import-linter 守护。
@@ -0,0 +1,182 @@
1
+ """mainspring-session-redis:Redis 会话后端 + RunCheckpoint 实现(T4-3)。
2
+
3
+ 与 SQLite 外挂共用同一套接口契约测试(tests/test_session_backends.py),接口不变即可平滑替换
4
+ (§2.6 / §2.9):
5
+
6
+ RedisSessionStore SessionStore:load / append / delete,append 按 Message.id 幂等去重
7
+ RedisCheckpoint RunCheckpoint:load_run / save_step,快照整包存 hash
8
+ open_redis(url) 便捷工厂:一次拿到同源的 store + checkpoint(§2.9 store 同源规则)
9
+ backend_factory 供 core.config 注入的后端工厂(session.backend: redis)
10
+
11
+ 设计要点:
12
+
13
+ - **幂等 append 用 Lua 脚本原子收口**:一次往返内完成「查 Message.id 是否已存在 + 追加」,
14
+ 多 worker 并发写同一 session 时不会出现检查与写入之间的竞态(与 SQLite 唯一索引等价);
15
+ Message.id 为 NULL 时照写不去重(与 MemoryStore 语义一致,§2.9);
16
+ - **run 快照存 hash**:payload / status / saved_at 三字段,`save_step` 整包覆盖;
17
+ - **条件写 `save_step_if`**:带期望状态的 CAS(比较当前 status 再覆盖),用于 approve / deny
18
+ 跨进程竞态收口(T4-3 验收;RunCheckpoint 契约之外的扩展能力,SQLite / Postgres 同样提供);
19
+ - **key 结构带 hash tag** `{session_id}` / `{run_id}`:同一会话/运行的多把 key 落同一 slot,
20
+ Redis Cluster 下 Lua 脚本仍然合法;
21
+ - **客户端懒连接**:`open_redis` 只构造客户端,首次读写才建连——yaml 装配阶段不依赖 Redis 在线;
22
+ - 后端不自带信号处理:停机快照由 Runner.shutdown() 统一驱动(§2.6)。
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import os
28
+ from collections.abc import Sequence
29
+ from typing import Any
30
+
31
+ from mainspring.session import SessionStore
32
+ from mainspring.types import Message, RunSnapshot
33
+ from redis.asyncio import Redis, from_url
34
+
35
+ __all__ = [
36
+ "DEFAULT_URL",
37
+ "RedisCheckpoint",
38
+ "RedisSessionStore",
39
+ "backend_factory",
40
+ "open_redis",
41
+ ]
42
+
43
+ DEFAULT_URL = "redis://:mainspring@127.0.0.1:6379/0"
44
+ ENV_URL = "MAINSPRING_SESSION_REDIS_URL"
45
+
46
+ # 原子幂等追加:ARGV 按 (flag, payload) 成对传入;flag = "0" 表示 Message.id 为 NULL,
47
+ # 否则为 "1" + id。SADD 返回值 1 表示首次出现——只有首次出现才 RPUSH。
48
+ _APPEND_SCRIPT = """
49
+ local list_key = KEYS[1]
50
+ local ids_key = KEYS[2]
51
+ local count = #ARGV / 2
52
+ for i = 1, count do
53
+ local flag = ARGV[2 * i - 1]
54
+ local payload = ARGV[2 * i]
55
+ if flag == '0' then
56
+ redis.call('RPUSH', list_key, payload)
57
+ elseif redis.call('SADD', ids_key, flag) == 1 then
58
+ redis.call('RPUSH', list_key, payload)
59
+ end
60
+ end
61
+ return 1
62
+ """
63
+
64
+ # 条件写:当前 status 必须等于期望值才覆盖;run 不存在(HGET 返回 false)同样不覆盖。
65
+ _CAS_SCRIPT = """
66
+ if redis.call('HGET', KEYS[1], 'status') ~= ARGV[1] then
67
+ return 0
68
+ end
69
+ redis.call('HSET', KEYS[1], 'status', ARGV[2], 'saved_at', ARGV[3], 'payload', ARGV[4])
70
+ return 1
71
+ """
72
+
73
+
74
+ def _text(value: Any) -> str:
75
+ """统一 bytes / str 客户端差异(调用方可能自带 decode_responses=False 的客户端)。"""
76
+ return value.decode("utf-8") if isinstance(value, bytes) else str(value)
77
+
78
+
79
+ def _messages_key(prefix: str, session_id: str) -> str:
80
+ return f"{prefix}:session:{{{session_id}}}:messages"
81
+
82
+
83
+ def _ids_key(prefix: str, session_id: str) -> str:
84
+ return f"{prefix}:session:{{{session_id}}}:ids"
85
+
86
+
87
+ def _run_key(prefix: str, run_id: str) -> str:
88
+ return f"{prefix}:run:{{{run_id}}}"
89
+
90
+
91
+ class RedisSessionStore:
92
+ """SessionStore 的 Redis 实现:append 由 Lua 脚本原子去重。"""
93
+
94
+ def __init__(self, client: Redis, *, prefix: str = "mainspring") -> None:
95
+ self._client = client
96
+ self._prefix = prefix
97
+
98
+ async def load(self, session_id: str) -> list[Message]:
99
+ payloads = await self._client.lrange(_messages_key(self._prefix, session_id), 0, -1)
100
+ return [Message.model_validate_json(_text(payload)) for payload in payloads]
101
+
102
+ async def append(self, session_id: str, messages: Sequence[Message]) -> None:
103
+ if not messages:
104
+ return
105
+ arguments: list[str] = []
106
+ for message in messages:
107
+ flag = "0" if message.id is None else f"1{message.id}"
108
+ arguments.extend((flag, message.model_dump_json()))
109
+ await self._client.eval(
110
+ _APPEND_SCRIPT,
111
+ 2,
112
+ _messages_key(self._prefix, session_id),
113
+ _ids_key(self._prefix, session_id),
114
+ *arguments,
115
+ )
116
+
117
+ async def delete(self, session_id: str) -> None:
118
+ await self._client.delete(
119
+ _messages_key(self._prefix, session_id),
120
+ _ids_key(self._prefix, session_id),
121
+ )
122
+
123
+ async def aclose(self) -> None:
124
+ """关闭共享客户端(store 与 checkpoint 同源时调用任一即可)。"""
125
+ await self._client.aclose()
126
+
127
+
128
+ class RedisCheckpoint:
129
+ """RunCheckpoint 的 Redis 实现:快照整包存 hash,支持带期望状态的条件写。"""
130
+
131
+ def __init__(self, client: Redis, *, prefix: str = "mainspring") -> None:
132
+ self._client = client
133
+ self._prefix = prefix
134
+
135
+ async def load_run(self, run_id: str) -> RunSnapshot | None:
136
+ data = await self._client.hgetall(_run_key(self._prefix, run_id))
137
+ if not data:
138
+ return None
139
+ # 兼容 decode_responses=False 的外部客户端:hash 键可能是 bytes 而非 str
140
+ payload = _text(data.get("payload", data.get(b"payload", b"")))
141
+ return RunSnapshot.model_validate_json(payload)
142
+
143
+ async def save_step(self, run_id: str, step: RunSnapshot) -> None:
144
+ await self._client.hset(
145
+ _run_key(self._prefix, run_id),
146
+ mapping={
147
+ "status": step.status,
148
+ "saved_at": str(step.saved_at),
149
+ "payload": step.model_dump_json(),
150
+ },
151
+ )
152
+
153
+ async def save_step_if(self, run_id: str, step: RunSnapshot, *, expected_status: str) -> bool:
154
+ """条件写(CAS):仅当已存的 status 等于 expected_status 时覆盖,返回是否写入。"""
155
+ applied = await self._client.eval(
156
+ _CAS_SCRIPT,
157
+ 1,
158
+ _run_key(self._prefix, run_id),
159
+ expected_status,
160
+ step.status,
161
+ str(step.saved_at),
162
+ step.model_dump_json(),
163
+ )
164
+ return bool(applied)
165
+
166
+ async def aclose(self) -> None:
167
+ await self._client.aclose()
168
+
169
+
170
+ def open_redis(
171
+ url: str | None = None, *, prefix: str = "mainspring"
172
+ ) -> tuple[RedisSessionStore, RedisCheckpoint]:
173
+ """同源工厂:store 与 checkpoint 共享一个客户端(§2.9 store 同源规则)。"""
174
+ client = from_url(url or DEFAULT_URL, decode_responses=True)
175
+ return RedisSessionStore(client, prefix=prefix), RedisCheckpoint(client, prefix=prefix)
176
+
177
+
178
+ def backend_factory(config: object) -> SessionStore:
179
+ """供 core.config 注入的后端工厂:读 session.url,缺省取环境变量或 compose 默认地址。"""
180
+ url = getattr(config, "url", None) or os.environ.get(ENV_URL) or DEFAULT_URL
181
+ store, _ = open_redis(url)
182
+ return store
@@ -0,0 +1,44 @@
1
+ [project]
2
+ name = "mainspring-session-redis"
3
+ version = "0.1.0"
4
+ description = "Redis session store and run checkpoint for mainspring."
5
+ license = "MIT"
6
+ license-files = ["LICENSE"]
7
+ readme = "README.md"
8
+ classifiers = [
9
+ "Development Status :: 4 - Beta",
10
+ "Intended Audience :: Developers",
11
+ "Operating System :: OS Independent",
12
+ "Programming Language :: Python :: 3 :: Only",
13
+ "Programming Language :: Python :: 3.11",
14
+ "Programming Language :: Python :: 3.12",
15
+ "Programming Language :: Python :: 3.13",
16
+ "Programming Language :: Python :: 3.14",
17
+ "Typing :: Typed",
18
+ "Topic :: Software Development :: Libraries :: Application Frameworks",
19
+ ]
20
+ requires-python = ">=3.11"
21
+ dependencies = [
22
+ "mainspring-agent",
23
+ "redis>=5.0,<7",
24
+ ]
25
+
26
+ [[project.authors]]
27
+ name = "mainspring contributors"
28
+
29
+ [project.urls]
30
+ Homepage = "https://github.com/chyong/mainspring"
31
+ Documentation = "https://github.com/chyong/mainspring/tree/main/docs"
32
+ Repository = "https://github.com/chyong/mainspring"
33
+ Issues = "https://github.com/chyong/mainspring/issues"
34
+
35
+ [tool.uv.sources.mainspring-agent]
36
+ workspace = true
37
+
38
+ [tool.uv.build-backend]
39
+ module-name = "mainspring_session_redis"
40
+ module-root = ""
41
+
42
+ [build-system]
43
+ requires = ["uv_build>=0.8,<2"]
44
+ build-backend = "uv_build"
@@ -0,0 +1,42 @@
1
+ [project]
2
+ name = "mainspring-session-redis"
3
+ version = "0.1.0"
4
+ description = "Redis session store and run checkpoint for mainspring."
5
+ license = "MIT"
6
+ license-files = ["LICENSE"]
7
+ readme = "README.md"
8
+ authors = [{ name = "mainspring contributors" }]
9
+ classifiers = [
10
+ "Development Status :: 4 - Beta",
11
+ "Intended Audience :: Developers",
12
+ "Operating System :: OS Independent",
13
+ "Programming Language :: Python :: 3 :: Only",
14
+ "Programming Language :: Python :: 3.11",
15
+ "Programming Language :: Python :: 3.12",
16
+ "Programming Language :: Python :: 3.13",
17
+ "Programming Language :: Python :: 3.14",
18
+ "Typing :: Typed",
19
+ "Topic :: Software Development :: Libraries :: Application Frameworks",
20
+ ]
21
+ requires-python = ">=3.11"
22
+ dependencies = [
23
+ "mainspring-agent",
24
+ "redis>=5.0,<7",
25
+ ]
26
+
27
+ [project.urls]
28
+ Homepage = "https://github.com/chyong/mainspring"
29
+ Documentation = "https://github.com/chyong/mainspring/tree/main/docs"
30
+ Repository = "https://github.com/chyong/mainspring"
31
+ Issues = "https://github.com/chyong/mainspring/issues"
32
+
33
+ [tool.uv.sources]
34
+ mainspring-agent = { workspace = true }
35
+
36
+ [build-system]
37
+ requires = ["uv_build>=0.8,<2"]
38
+ build-backend = "uv_build"
39
+
40
+ [tool.uv.build-backend]
41
+ module-name = "mainspring_session_redis"
42
+ module-root = ""