mainspring-session-sqlite 0.1.0__py3-none-any.whl

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,199 @@
1
+ """mainspring-session-sqlite:SQLite 会话后端 + RunCheckpoint 实现(T2-6)。
2
+
3
+ 实现 core 的两个 Protocol,接口不变即可平滑替换 Redis / Postgres(§2.6 / §2.9):
4
+
5
+ SQLiteSessionStore SessionStore:load / append / delete,append 按 Message.id 幂等去重
6
+ SQLiteCheckpoint RunCheckpoint:load_run / save_step,快照整包落库
7
+ open_sqlite(path) 便捷工厂:一次拿到同源的 store + checkpoint(§2.9 store 同源规则)
8
+ backend_factory 供 core.config 注入的后端工厂(session.backend: sqlite)
9
+
10
+ 设计要点:
11
+
12
+ - 单文件 SQLite + WAL:进程被 kill 后数据完整,重启 resume 同一 run 从最后快照继续;
13
+ - 幂等去重靠唯一索引 `(session_id, message_id)`:Message.id 为 NULL 时照写不去重
14
+ (SQLite 唯一索引允许多个 NULL),与 MemoryStore 语义一致(§2.9);
15
+ - 快照整包 JSON 落库:契约只要求 load_run 返回全量快照,增量存储是可选优化;
16
+ - 所有 sqlite3 调用走 `asyncio.to_thread` 串行执行,不阻塞事件循环、不跨线程并发用连接;
17
+ - 后端不自带信号处理:停机快照由 Runner.shutdown() 统一驱动(§2.6)。
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import asyncio
23
+ import contextlib
24
+ import sqlite3
25
+ from collections.abc import Callable, Sequence
26
+ from pathlib import Path
27
+ from typing import TypeVar
28
+
29
+ from mainspring.session import SessionStore
30
+ from mainspring.types import Message, RunSnapshot
31
+
32
+ __all__ = ["SQLiteCheckpoint", "SQLiteSessionStore", "backend_factory", "open_sqlite"]
33
+
34
+ T = TypeVar("T")
35
+
36
+ DEFAULT_PATH = "mainspring-session.db"
37
+
38
+ _SCHEMA = """
39
+ CREATE TABLE IF NOT EXISTS messages (
40
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
41
+ session_id TEXT NOT NULL,
42
+ message_id TEXT,
43
+ payload TEXT NOT NULL
44
+ );
45
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_messages_dedupe
46
+ ON messages (session_id, message_id);
47
+ CREATE INDEX IF NOT EXISTS idx_messages_session
48
+ ON messages (session_id, seq);
49
+ CREATE TABLE IF NOT EXISTS runs (
50
+ run_id TEXT PRIMARY KEY,
51
+ status TEXT NOT NULL,
52
+ saved_at REAL NOT NULL,
53
+ payload TEXT NOT NULL
54
+ );
55
+ """
56
+
57
+
58
+ class _Database:
59
+ """最小异步 SQLite 封装:单连接 + 全程串行,pragma / 建表在首次使用时完成。
60
+
61
+ 单连接配 `check_same_thread=False`:连接在事件循环线程创建,实际操作经 to_thread
62
+ 落到任意工作线程,线程归属检查必须关掉;安全完全靠 `_lock` 串行化——同一时刻至多
63
+ 一个线程持有连接,这是下方取消不变量的前提。
64
+ """
65
+
66
+ def __init__(self, path: str | Path) -> None:
67
+ self.path = Path(path)
68
+ self.path.parent.mkdir(parents=True, exist_ok=True)
69
+ self._connection: sqlite3.Connection | None = None
70
+ self._lock = asyncio.Lock()
71
+
72
+ async def run(self, operation: Callable[[sqlite3.Connection], T]) -> T:
73
+ async with self._lock: # 串行不变量:单连接同一时刻只被一个线程使用
74
+ task = asyncio.create_task(asyncio.to_thread(self._execute, operation))
75
+ try:
76
+ return await asyncio.shield(task)
77
+ except asyncio.CancelledError:
78
+ # 快照串行写入不变量:取消打在落库途中,必须等在途写收尾再放锁。
79
+ # 提前放锁的后果:工作线程仍在写,下一个操作(取消收口要落的 cancelled
80
+ # 快照)挤上同一连接,提交顺序未定义——先前 in-flight 的 running 快照可能
81
+ # 反过来覆盖 cancelled 快照,恢复时「复活」一个实际已取消的 run
82
+ # (T2-6 崩溃恢复竞态,回归用例见 tests/test_resume.py)。
83
+ while not task.done():
84
+ with contextlib.suppress(asyncio.CancelledError):
85
+ await task
86
+ raise
87
+
88
+ def _execute(self, operation: Callable[[sqlite3.Connection], T]) -> T:
89
+ connection = self._connect()
90
+ # `with connection:` 让单次操作成为独立事务:成功提交、异常回滚,整包快照写
91
+ # 不会留半截;配合 WAL,进程被 kill 后已提交数据仍然完整
92
+ with connection:
93
+ return operation(connection)
94
+
95
+ def _connect(self) -> sqlite3.Connection:
96
+ if self._connection is None:
97
+ connection = sqlite3.connect(self.path, check_same_thread=False)
98
+ connection.execute("PRAGMA journal_mode=WAL")
99
+ connection.executescript(_SCHEMA)
100
+ self._connection = connection
101
+ return self._connection
102
+
103
+
104
+ class SQLiteSessionStore:
105
+ """SessionStore 的 SQLite 实现:append 幂等(靠 Message.id 唯一索引)。"""
106
+
107
+ def __init__(self, path: str | Path) -> None:
108
+ self._db = _Database(path)
109
+
110
+ async def load(self, session_id: str) -> list[Message]:
111
+ def operation(connection: sqlite3.Connection) -> list[Message]:
112
+ rows = connection.execute(
113
+ "SELECT payload FROM messages WHERE session_id = ? ORDER BY seq",
114
+ (session_id,),
115
+ ).fetchall()
116
+ return [Message.model_validate_json(row[0]) for row in rows]
117
+
118
+ return await self._db.run(operation)
119
+
120
+ async def append(self, session_id: str, messages: Sequence[Message]) -> None:
121
+ rows = [(session_id, message.id, message.model_dump_json()) for message in messages]
122
+ if not rows:
123
+ return
124
+
125
+ def operation(connection: sqlite3.Connection) -> None:
126
+ # INSERT OR IGNORE + 唯一索引 = 幂等去重(message_id 为 NULL 时不去重)
127
+ connection.executemany(
128
+ "INSERT OR IGNORE INTO messages (session_id, message_id, payload) VALUES (?, ?, ?)",
129
+ rows,
130
+ )
131
+
132
+ await self._db.run(operation)
133
+
134
+ async def delete(self, session_id: str) -> None:
135
+ def operation(connection: sqlite3.Connection) -> None:
136
+ connection.execute("DELETE FROM messages WHERE session_id = ?", (session_id,))
137
+
138
+ await self._db.run(operation)
139
+
140
+
141
+ class SQLiteCheckpoint:
142
+ """RunCheckpoint 的 SQLite 实现:快照整包落库,save_step 覆盖式写入。"""
143
+
144
+ def __init__(self, path: str | Path) -> None:
145
+ self._db = _Database(path)
146
+
147
+ async def load_run(self, run_id: str) -> RunSnapshot | None:
148
+ def operation(connection: sqlite3.Connection) -> RunSnapshot | None:
149
+ row = connection.execute(
150
+ "SELECT payload FROM runs WHERE run_id = ?", (run_id,)
151
+ ).fetchone()
152
+ return None if row is None else RunSnapshot.model_validate_json(row[0])
153
+
154
+ return await self._db.run(operation)
155
+
156
+ async def save_step(self, run_id: str, step: RunSnapshot) -> None:
157
+ """整包覆盖写,后写者胜;写入经 `_Database.run` 串行化,永不与取消收口交错
158
+ (不变量见 `_Database.run`)。跨进程竞态用 save_step_if 的 CAS 收口。
159
+ """
160
+ payload = step.model_dump_json()
161
+
162
+ def operation(connection: sqlite3.Connection) -> None:
163
+ connection.execute(
164
+ "INSERT INTO runs (run_id, status, saved_at, payload) VALUES (?, ?, ?, ?) "
165
+ "ON CONFLICT(run_id) DO UPDATE SET "
166
+ "status = excluded.status, saved_at = excluded.saved_at, "
167
+ "payload = excluded.payload",
168
+ (run_id, step.status, step.saved_at, payload),
169
+ )
170
+
171
+ await self._db.run(operation)
172
+
173
+ async def save_step_if(self, run_id: str, step: RunSnapshot, *, expected_status: str) -> bool:
174
+ """条件写(CAS):仅当已存的 status 等于 expected_status 时覆盖,返回是否写入。
175
+
176
+ T4-3 并发契约的扩展能力(Redis / Postgres 同样提供):approve / deny 跨进程竞态的
177
+ 收口点——两个进程同时裁决同一挂起 run 时,只有一方能把快照从 pending 推进。
178
+ """
179
+
180
+ def operation(connection: sqlite3.Connection) -> bool:
181
+ cursor = connection.execute(
182
+ "UPDATE runs SET status = ?, saved_at = ?, payload = ? "
183
+ "WHERE run_id = ? AND status = ?",
184
+ (step.status, step.saved_at, step.model_dump_json(), run_id, expected_status),
185
+ )
186
+ return cursor.rowcount == 1
187
+
188
+ return await self._db.run(operation)
189
+
190
+
191
+ def open_sqlite(path: str | Path) -> tuple[SQLiteSessionStore, SQLiteCheckpoint]:
192
+ """同源工厂:store 与 checkpoint 指向同一文件(§2.9 store 同源规则的落库形态)。"""
193
+ return SQLiteSessionStore(path), SQLiteCheckpoint(path)
194
+
195
+
196
+ def backend_factory(config: object) -> SessionStore:
197
+ """供 core.config 注入的后端工厂:读取 session.path(缺省 ./mainspring-session.db)。"""
198
+ path = getattr(config, "path", None) or DEFAULT_PATH
199
+ return SQLiteSessionStore(path)
File without changes
@@ -0,0 +1,53 @@
1
+ Metadata-Version: 2.4
2
+ Name: mainspring-session-sqlite
3
+ Version: 0.1.0
4
+ Summary: SQLite 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-Python: >=3.11
20
+ Project-URL: Homepage, https://github.com/chyong/mainspring
21
+ Project-URL: Documentation, https://github.com/chyong/mainspring/tree/main/docs
22
+ Project-URL: Repository, https://github.com/chyong/mainspring
23
+ Project-URL: Issues, https://github.com/chyong/mainspring/issues
24
+ Description-Content-Type: text/markdown
25
+
26
+ # mainspring-session-sqlite
27
+
28
+ SQLite 会话后端 + RunCheckpoint 实现(T2-6):单文件、WAL、崩溃恢复、零额外依赖。
29
+
30
+ ## 安装
31
+
32
+ ```bash
33
+ pip install mainspring-session-sqlite
34
+ ```
35
+
36
+ ## 用法
37
+
38
+ ```python
39
+ from mainspring_session_sqlite import open_sqlite
40
+
41
+ store, checkpoint = open_sqlite(".mainspring/session.db")
42
+
43
+ await store.append("session-1", [message]) # 按 Message.id 幂等去重
44
+ history = await store.load("session-1")
45
+
46
+ runner = Runner(store=store, checkpoint=checkpoint)
47
+ ```
48
+
49
+ `append` 靠唯一索引 `(session_id, message_id)` 去重;快照整包落库,进程被 kill 后可从最后
50
+ 一次提交恢复。把 `backend_factory` 注入 `mainspring.config.build_store`,即可在 YAML 里用
51
+ `session.backend: sqlite` 选中它。
52
+
53
+ mainspring 工作区成员,与 [core](https://github.com/chyong/mainspring) 同源。MIT。
@@ -0,0 +1,6 @@
1
+ mainspring_session_sqlite/__init__.py,sha256=tRNx0-VgWDp0RC3u6UczHgKbOvjEVaV88BOqJYhg-3M,8737
2
+ mainspring_session_sqlite/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ mainspring_session_sqlite-0.1.0.dist-info/licenses/LICENSE,sha256=wRDF_w9CNQSolm8Pjiu3W13uQJ7Iw2K00IrirvJepqY,1080
4
+ mainspring_session_sqlite-0.1.0.dist-info/WHEEL,sha256=wfHFB5CQ4yOA68LQ_ISeFjKJGxj2GfVzMH9QxkYgrCw,81
5
+ mainspring_session_sqlite-0.1.0.dist-info/METADATA,sha256=ZUqmxRh-TDwc5AjtvQvlmcoOkn6ko9RREEo0j-YMMI8,1921
6
+ mainspring_session_sqlite-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.13.13
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -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.