glyff-file-store 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.
- glyff_file_store-0.1.0/.gitignore +210 -0
- glyff_file_store-0.1.0/LICENSE +21 -0
- glyff_file_store-0.1.0/PKG-INFO +77 -0
- glyff_file_store-0.1.0/README.md +38 -0
- glyff_file_store-0.1.0/pyproject.toml +43 -0
- glyff_file_store-0.1.0/src/glyff_file_store/__init__.py +4 -0
- glyff_file_store-0.1.0/src/glyff_file_store/file.py +261 -0
- glyff_file_store-0.1.0/src/glyff_file_store/file_client.py +103 -0
- glyff_file_store-0.1.0/src/glyff_file_store/tests/__init__.py +0 -0
- glyff_file_store-0.1.0/src/glyff_file_store/tests/conftest.py +38 -0
- glyff_file_store-0.1.0/src/glyff_file_store/tests/test_crash_recovery.py +57 -0
- glyff_file_store-0.1.0/src/glyff_file_store/tests/test_stores.py +59 -0
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
# Byte-compiled / optimized / DLL files
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[codz]
|
|
4
|
+
*$py.class
|
|
5
|
+
|
|
6
|
+
# C extensions
|
|
7
|
+
*.so
|
|
8
|
+
|
|
9
|
+
# Distribution / packaging
|
|
10
|
+
.Python
|
|
11
|
+
build/
|
|
12
|
+
develop-eggs/
|
|
13
|
+
dist/
|
|
14
|
+
downloads/
|
|
15
|
+
eggs/
|
|
16
|
+
.eggs/
|
|
17
|
+
lib/
|
|
18
|
+
lib64/
|
|
19
|
+
parts/
|
|
20
|
+
sdist/
|
|
21
|
+
var/
|
|
22
|
+
wheels/
|
|
23
|
+
share/python-wheels/
|
|
24
|
+
*.egg-info/
|
|
25
|
+
.installed.cfg
|
|
26
|
+
*.egg
|
|
27
|
+
MANIFEST
|
|
28
|
+
|
|
29
|
+
# PyInstaller
|
|
30
|
+
# Usually these files are written by a python script from a template
|
|
31
|
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
|
32
|
+
*.manifest
|
|
33
|
+
*.spec
|
|
34
|
+
|
|
35
|
+
# Installer logs
|
|
36
|
+
pip-log.txt
|
|
37
|
+
pip-delete-this-directory.txt
|
|
38
|
+
|
|
39
|
+
# Unit test / coverage reports
|
|
40
|
+
htmlcov/
|
|
41
|
+
.tox/
|
|
42
|
+
.nox/
|
|
43
|
+
.coverage
|
|
44
|
+
.coverage.*
|
|
45
|
+
.cache
|
|
46
|
+
nosetests.xml
|
|
47
|
+
coverage.xml
|
|
48
|
+
*.cover
|
|
49
|
+
*.py.cover
|
|
50
|
+
.hypothesis/
|
|
51
|
+
.pytest_cache/
|
|
52
|
+
cover/
|
|
53
|
+
|
|
54
|
+
# Translations
|
|
55
|
+
*.mo
|
|
56
|
+
*.pot
|
|
57
|
+
|
|
58
|
+
# Django stuff:
|
|
59
|
+
*.log
|
|
60
|
+
local_settings.py
|
|
61
|
+
db.sqlite3
|
|
62
|
+
db.sqlite3-journal
|
|
63
|
+
|
|
64
|
+
# Flask stuff:
|
|
65
|
+
instance/
|
|
66
|
+
.webassets-cache
|
|
67
|
+
|
|
68
|
+
# Scrapy stuff:
|
|
69
|
+
.scrapy
|
|
70
|
+
|
|
71
|
+
# Sphinx documentation
|
|
72
|
+
docs/_build/
|
|
73
|
+
|
|
74
|
+
# PyBuilder
|
|
75
|
+
.pybuilder/
|
|
76
|
+
target/
|
|
77
|
+
|
|
78
|
+
# Jupyter Notebook
|
|
79
|
+
.ipynb_checkpoints
|
|
80
|
+
|
|
81
|
+
# IPython
|
|
82
|
+
profile_default/
|
|
83
|
+
ipython_config.py
|
|
84
|
+
|
|
85
|
+
# pyenv
|
|
86
|
+
# For a library or package, you might want to ignore these files since the code is
|
|
87
|
+
# intended to run in multiple environments; otherwise, check them in:
|
|
88
|
+
# .python-version
|
|
89
|
+
|
|
90
|
+
# pipenv
|
|
91
|
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
|
92
|
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
|
93
|
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
|
94
|
+
# install all needed dependencies.
|
|
95
|
+
#Pipfile.lock
|
|
96
|
+
|
|
97
|
+
# UV
|
|
98
|
+
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
|
|
99
|
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
|
100
|
+
# commonly ignored for libraries.
|
|
101
|
+
#uv.lock
|
|
102
|
+
|
|
103
|
+
# poetry
|
|
104
|
+
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
|
105
|
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
|
106
|
+
# commonly ignored for libraries.
|
|
107
|
+
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
|
108
|
+
#poetry.lock
|
|
109
|
+
#poetry.toml
|
|
110
|
+
|
|
111
|
+
# pdm
|
|
112
|
+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
|
113
|
+
# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
|
|
114
|
+
# https://pdm-project.org/en/latest/usage/project/#working-with-version-control
|
|
115
|
+
#pdm.lock
|
|
116
|
+
#pdm.toml
|
|
117
|
+
.pdm-python
|
|
118
|
+
.pdm-build/
|
|
119
|
+
|
|
120
|
+
# pixi
|
|
121
|
+
# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
|
|
122
|
+
#pixi.lock
|
|
123
|
+
# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
|
|
124
|
+
# in the .venv directory. It is recommended not to include this directory in version control.
|
|
125
|
+
.pixi
|
|
126
|
+
|
|
127
|
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
|
128
|
+
__pypackages__/
|
|
129
|
+
|
|
130
|
+
# Celery stuff
|
|
131
|
+
celerybeat-schedule
|
|
132
|
+
celerybeat.pid
|
|
133
|
+
|
|
134
|
+
# SageMath parsed files
|
|
135
|
+
*.sage.py
|
|
136
|
+
|
|
137
|
+
# Environments
|
|
138
|
+
.env
|
|
139
|
+
.envrc
|
|
140
|
+
.venv
|
|
141
|
+
env/
|
|
142
|
+
venv/
|
|
143
|
+
ENV/
|
|
144
|
+
env.bak/
|
|
145
|
+
venv.bak/
|
|
146
|
+
|
|
147
|
+
# Spyder project settings
|
|
148
|
+
.spyderproject
|
|
149
|
+
.spyproject
|
|
150
|
+
|
|
151
|
+
# Rope project settings
|
|
152
|
+
.ropeproject
|
|
153
|
+
|
|
154
|
+
# mkdocs documentation
|
|
155
|
+
/site
|
|
156
|
+
|
|
157
|
+
# mypy
|
|
158
|
+
.mypy_cache/
|
|
159
|
+
.dmypy.json
|
|
160
|
+
dmypy.json
|
|
161
|
+
|
|
162
|
+
# Pyre type checker
|
|
163
|
+
.pyre/
|
|
164
|
+
|
|
165
|
+
# pytype static type analyzer
|
|
166
|
+
.pytype/
|
|
167
|
+
|
|
168
|
+
# Cython debug symbols
|
|
169
|
+
cython_debug/
|
|
170
|
+
|
|
171
|
+
# PyCharm
|
|
172
|
+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
|
173
|
+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
|
174
|
+
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
|
175
|
+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
|
176
|
+
#.idea/
|
|
177
|
+
|
|
178
|
+
# Abstra
|
|
179
|
+
# Abstra is an AI-powered process automation framework.
|
|
180
|
+
# Ignore directories containing user credentials, local state, and settings.
|
|
181
|
+
# Learn more at https://abstra.io/docs
|
|
182
|
+
.abstra/
|
|
183
|
+
|
|
184
|
+
# Visual Studio Code
|
|
185
|
+
# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
|
|
186
|
+
# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
|
|
187
|
+
# and can be added to the global gitignore or merged into this file. However, if you prefer,
|
|
188
|
+
# you could uncomment the following to ignore the entire vscode folder
|
|
189
|
+
# .vscode/
|
|
190
|
+
|
|
191
|
+
# Ruff stuff:
|
|
192
|
+
.ruff_cache/
|
|
193
|
+
|
|
194
|
+
# PyPI configuration file
|
|
195
|
+
.pypirc
|
|
196
|
+
|
|
197
|
+
# Cursor
|
|
198
|
+
# Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to
|
|
199
|
+
# exclude from AI features like autocomplete and code analysis. Recommended for sensitive data
|
|
200
|
+
# refer to https://docs.cursor.com/context/ignore-files
|
|
201
|
+
.cursorignore
|
|
202
|
+
.cursorindexingignore
|
|
203
|
+
|
|
204
|
+
# Marimo
|
|
205
|
+
marimo/_static/
|
|
206
|
+
marimo/_lsp/
|
|
207
|
+
__marimo__/
|
|
208
|
+
|
|
209
|
+
/out/
|
|
210
|
+
/.local/
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 nueruyu
|
|
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,77 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: glyff-file-store
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: File-based SessionStore implementation for glyff.
|
|
5
|
+
License: MIT License
|
|
6
|
+
|
|
7
|
+
Copyright (c) 2026 nueruyu
|
|
8
|
+
|
|
9
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
10
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
11
|
+
in the Software without restriction, including without limitation the rights
|
|
12
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
13
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
14
|
+
furnished to do so, subject to the following conditions:
|
|
15
|
+
|
|
16
|
+
The above copyright notice and this permission notice shall be included in all
|
|
17
|
+
copies or substantial portions of the Software.
|
|
18
|
+
|
|
19
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
20
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
21
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
22
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
23
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
24
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
25
|
+
SOFTWARE.
|
|
26
|
+
License-File: LICENSE
|
|
27
|
+
Classifier: Development Status :: 3 - Alpha
|
|
28
|
+
Classifier: Framework :: AsyncIO
|
|
29
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
30
|
+
Classifier: Operating System :: OS Independent
|
|
31
|
+
Classifier: Programming Language :: Python :: 3
|
|
32
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
33
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
34
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
35
|
+
Classifier: Typing :: Typed
|
|
36
|
+
Requires-Python: >=3.11
|
|
37
|
+
Requires-Dist: glyff>=0.1.0
|
|
38
|
+
Description-Content-Type: text/markdown
|
|
39
|
+
|
|
40
|
+
# glyff-file-store
|
|
41
|
+
|
|
42
|
+
A file-based `SessionStore` implementation for
|
|
43
|
+
[glyff](https://pypi.org/project/glyff/).
|
|
44
|
+
|
|
45
|
+
Sessions are persisted to disk as append-only JSON event logs, with separate
|
|
46
|
+
files for large execution results. Designed to survive process restarts
|
|
47
|
+
without requiring a database.
|
|
48
|
+
|
|
49
|
+
## Install
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
pip install glyff-file-store
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
This package depends on `glyff>=0.1.0`.
|
|
56
|
+
|
|
57
|
+
## Public API
|
|
58
|
+
|
|
59
|
+
| Name | Description |
|
|
60
|
+
| ------------------ | ----------------------------------------------------- |
|
|
61
|
+
| `FileClient` | Low-level file I/O for a session directory. |
|
|
62
|
+
| `FileSessionStore` | `SessionStore` implementation backed by `FileClient`. |
|
|
63
|
+
|
|
64
|
+
## Format
|
|
65
|
+
|
|
66
|
+
Sessions are stored as event log files under the configured base directory.
|
|
67
|
+
Each event is a single JSON line; the format is append-only and
|
|
68
|
+
forward-compatible. Large execution results are written to separate files
|
|
69
|
+
referenced by the event log.
|
|
70
|
+
|
|
71
|
+
## Status
|
|
72
|
+
|
|
73
|
+
Early development. APIs may change before v1.0.
|
|
74
|
+
|
|
75
|
+
## License
|
|
76
|
+
|
|
77
|
+
MIT
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
# glyff-file-store
|
|
2
|
+
|
|
3
|
+
A file-based `SessionStore` implementation for
|
|
4
|
+
[glyff](https://pypi.org/project/glyff/).
|
|
5
|
+
|
|
6
|
+
Sessions are persisted to disk as append-only JSON event logs, with separate
|
|
7
|
+
files for large execution results. Designed to survive process restarts
|
|
8
|
+
without requiring a database.
|
|
9
|
+
|
|
10
|
+
## Install
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
pip install glyff-file-store
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
This package depends on `glyff>=0.1.0`.
|
|
17
|
+
|
|
18
|
+
## Public API
|
|
19
|
+
|
|
20
|
+
| Name | Description |
|
|
21
|
+
| ------------------ | ----------------------------------------------------- |
|
|
22
|
+
| `FileClient` | Low-level file I/O for a session directory. |
|
|
23
|
+
| `FileSessionStore` | `SessionStore` implementation backed by `FileClient`. |
|
|
24
|
+
|
|
25
|
+
## Format
|
|
26
|
+
|
|
27
|
+
Sessions are stored as event log files under the configured base directory.
|
|
28
|
+
Each event is a single JSON line; the format is append-only and
|
|
29
|
+
forward-compatible. Large execution results are written to separate files
|
|
30
|
+
referenced by the event log.
|
|
31
|
+
|
|
32
|
+
## Status
|
|
33
|
+
|
|
34
|
+
Early development. APIs may change before v1.0.
|
|
35
|
+
|
|
36
|
+
## License
|
|
37
|
+
|
|
38
|
+
MIT
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "glyff-file-store"
|
|
3
|
+
description = "File-based SessionStore implementation for glyff."
|
|
4
|
+
readme = "README.md"
|
|
5
|
+
license = { file = "LICENSE" }
|
|
6
|
+
requires-python = ">=3.11"
|
|
7
|
+
dependencies = [
|
|
8
|
+
"glyff>=0.1.0",
|
|
9
|
+
]
|
|
10
|
+
dynamic = ["version"]
|
|
11
|
+
classifiers = [
|
|
12
|
+
"Programming Language :: Python :: 3",
|
|
13
|
+
"Programming Language :: Python :: 3.11",
|
|
14
|
+
"Programming Language :: Python :: 3.12",
|
|
15
|
+
"Programming Language :: Python :: 3.13",
|
|
16
|
+
"License :: OSI Approved :: MIT License",
|
|
17
|
+
"Operating System :: OS Independent",
|
|
18
|
+
"Development Status :: 3 - Alpha",
|
|
19
|
+
"Framework :: AsyncIO",
|
|
20
|
+
"Typing :: Typed",
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
[tool.uv.sources]
|
|
24
|
+
glyff = { workspace = true }
|
|
25
|
+
|
|
26
|
+
[build-system]
|
|
27
|
+
requires = ["hatchling", "hatch-vcs"]
|
|
28
|
+
build-backend = "hatchling.build"
|
|
29
|
+
|
|
30
|
+
[tool.hatch.build.targets.wheel]
|
|
31
|
+
packages = ["src/glyff_file_store"]
|
|
32
|
+
exclude = ["src/glyff_file_store/tests"]
|
|
33
|
+
|
|
34
|
+
[tool.hatch.version]
|
|
35
|
+
source = "vcs"
|
|
36
|
+
raw-options = { root = "../.." }
|
|
37
|
+
|
|
38
|
+
[tool.pytest.ini_options]
|
|
39
|
+
asyncio_mode = "auto"
|
|
40
|
+
testpaths = ["src/glyff_file_store/tests"]
|
|
41
|
+
|
|
42
|
+
[dependency-groups]
|
|
43
|
+
dev = ["pytest>=8.0", "pytest-asyncio>=0.23"]
|
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import json
|
|
5
|
+
from datetime import datetime, timezone
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any, TypedDict
|
|
8
|
+
|
|
9
|
+
from glyff.interfaces import Execution, Serializer, SessionStore, Transaction
|
|
10
|
+
from glyff.models import ExecutionId, ExecutionRecord, ExecutionStatus
|
|
11
|
+
|
|
12
|
+
from .file_client import FileClient
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class LogEntry(TypedDict):
|
|
16
|
+
timestamp: str
|
|
17
|
+
event_type: str # "start", "complete", "fail"
|
|
18
|
+
call_stack: list[str] # outermost → innermost, each "name#sequence:args_hash"
|
|
19
|
+
result: Any | None # JSON-compatible object
|
|
20
|
+
error: str | None
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
_STATUS_TO_EVENT_TYPE = {
|
|
24
|
+
ExecutionStatus.STARTED: "start",
|
|
25
|
+
ExecutionStatus.COMPLETED: "complete",
|
|
26
|
+
ExecutionStatus.FAILED: "fail",
|
|
27
|
+
}
|
|
28
|
+
_EVENT_TYPE_TO_STATUS = {v: k for k, v in _STATUS_TO_EVENT_TYPE.items()}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class _FileTransaction(Transaction):
|
|
32
|
+
def __init__(self, client: FileClient):
|
|
33
|
+
self._client = client
|
|
34
|
+
|
|
35
|
+
async def commit(self) -> None:
|
|
36
|
+
await self._client.commit_staged()
|
|
37
|
+
|
|
38
|
+
async def rollback(self) -> None:
|
|
39
|
+
await self._client.clear_staged()
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class _FileExecution(Execution):
|
|
43
|
+
def __init__(self, store: FileSessionStore, execution_id: ExecutionId):
|
|
44
|
+
self._store = store
|
|
45
|
+
self._id = execution_id
|
|
46
|
+
|
|
47
|
+
def _create_log_entry(self, status: ExecutionStatus, **kwargs) -> LogEntry:
|
|
48
|
+
return LogEntry(
|
|
49
|
+
timestamp=datetime.now(timezone.utc).isoformat(),
|
|
50
|
+
event_type=_STATUS_TO_EVENT_TYPE[status],
|
|
51
|
+
call_stack=self._store._id_to_callstack(self._id),
|
|
52
|
+
result=kwargs.get("result"),
|
|
53
|
+
error=kwargs.get("error"),
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
async def complete(self, value: Any, return_type: type) -> None:
|
|
57
|
+
serialized_bytes = self._store._serializer.serialize(value, return_type)
|
|
58
|
+
persistable_result = json.loads(serialized_bytes)
|
|
59
|
+
entry = self._create_log_entry(
|
|
60
|
+
ExecutionStatus.COMPLETED, result=persistable_result
|
|
61
|
+
)
|
|
62
|
+
await self._store._add_log_entry(entry)
|
|
63
|
+
|
|
64
|
+
async def fail(self, error: str) -> None:
|
|
65
|
+
entry = self._create_log_entry(ExecutionStatus.FAILED, error=error)
|
|
66
|
+
await self._store._add_log_entry(entry)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class FileSessionStore(SessionStore):
|
|
70
|
+
"""
|
|
71
|
+
A file-based implementation of SessionStore that logs all execution events
|
|
72
|
+
to a file in either JSONL or pretty-printed JSON format.
|
|
73
|
+
"""
|
|
74
|
+
|
|
75
|
+
def __init__(
|
|
76
|
+
self,
|
|
77
|
+
client: FileClient,
|
|
78
|
+
serializer: Serializer,
|
|
79
|
+
format: str = "jsonl",
|
|
80
|
+
**kwargs,
|
|
81
|
+
):
|
|
82
|
+
if format not in ("json", "jsonl"):
|
|
83
|
+
raise ValueError("format must be either 'json' or 'jsonl'")
|
|
84
|
+
self._client = client
|
|
85
|
+
self._serializer = serializer
|
|
86
|
+
self._format = format
|
|
87
|
+
self._executions_path = Path(f"executions.{format}")
|
|
88
|
+
|
|
89
|
+
self._states: dict[str, ExecutionStatus] = {}
|
|
90
|
+
self._results: dict[str, Any] = {} # Caches JSON-compatible objects
|
|
91
|
+
self._errors: dict[str, str] = {}
|
|
92
|
+
|
|
93
|
+
self._staged_log_entries: list[LogEntry] = []
|
|
94
|
+
self._lock = asyncio.Lock()
|
|
95
|
+
|
|
96
|
+
self._load_executions()
|
|
97
|
+
|
|
98
|
+
@property
|
|
99
|
+
def executions_path(self) -> Path:
|
|
100
|
+
return self._executions_path
|
|
101
|
+
|
|
102
|
+
def _id_to_callstack(self, execution_id: ExecutionId) -> list[str]:
|
|
103
|
+
"""Converts an ExecutionId to a call stack list (outermost → innermost)."""
|
|
104
|
+
frames: list[str] = []
|
|
105
|
+
current: ExecutionId | None = execution_id
|
|
106
|
+
while current is not None:
|
|
107
|
+
frames.append(f"{current.name}#{current.sequence}:{current.args_hash}")
|
|
108
|
+
current = current.parent_id
|
|
109
|
+
frames.reverse()
|
|
110
|
+
return frames
|
|
111
|
+
|
|
112
|
+
def _id_to_key(self, execution_id: ExecutionId) -> str:
|
|
113
|
+
"""Converts an ExecutionId to a stable, unique string key."""
|
|
114
|
+
parent_path = (
|
|
115
|
+
f"{self._id_to_key(execution_id.parent_id)}/"
|
|
116
|
+
if execution_id.parent_id
|
|
117
|
+
else ""
|
|
118
|
+
)
|
|
119
|
+
return f"{parent_path}{execution_id.name}#{execution_id.sequence}:{execution_id.args_hash}"
|
|
120
|
+
|
|
121
|
+
@staticmethod
|
|
122
|
+
def _callstack_to_key(call_stack: list[str]) -> str:
|
|
123
|
+
"""Converts a call stack list back to the stable string key."""
|
|
124
|
+
return "/".join(call_stack)
|
|
125
|
+
|
|
126
|
+
def _load_executions(self) -> None:
|
|
127
|
+
"""Parses the executions file to build the in-memory state."""
|
|
128
|
+
abs_path = self._client.resolve(self._executions_path)
|
|
129
|
+
if not abs_path.exists():
|
|
130
|
+
return
|
|
131
|
+
|
|
132
|
+
lines_to_process: list[str] = []
|
|
133
|
+
with open(abs_path, "r", encoding="utf-8") as f:
|
|
134
|
+
if self._format == "jsonl":
|
|
135
|
+
lines_to_process.extend(f.readlines())
|
|
136
|
+
else: # json
|
|
137
|
+
content = f.read()
|
|
138
|
+
if not content.strip():
|
|
139
|
+
return
|
|
140
|
+
try:
|
|
141
|
+
entries = json.loads(content)
|
|
142
|
+
lines_to_process.extend([json.dumps(e) for e in entries])
|
|
143
|
+
except json.JSONDecodeError:
|
|
144
|
+
return # Ignore corrupted file
|
|
145
|
+
|
|
146
|
+
for line in lines_to_process:
|
|
147
|
+
if not line.strip():
|
|
148
|
+
continue
|
|
149
|
+
try:
|
|
150
|
+
entry: LogEntry = json.loads(line)
|
|
151
|
+
key = self._callstack_to_key(entry["call_stack"])
|
|
152
|
+
event_type = entry["event_type"]
|
|
153
|
+
|
|
154
|
+
status = _EVENT_TYPE_TO_STATUS.get(event_type)
|
|
155
|
+
|
|
156
|
+
if status is ExecutionStatus.STARTED:
|
|
157
|
+
self._states[key] = ExecutionStatus.STARTED
|
|
158
|
+
elif status is ExecutionStatus.COMPLETED:
|
|
159
|
+
self._states[key] = ExecutionStatus.COMPLETED
|
|
160
|
+
self._results[key] = entry["result"]
|
|
161
|
+
if key in self._errors:
|
|
162
|
+
del self._errors[key]
|
|
163
|
+
elif status is ExecutionStatus.FAILED:
|
|
164
|
+
self._states[key] = ExecutionStatus.FAILED
|
|
165
|
+
self._errors[key] = entry["error"] or ""
|
|
166
|
+
if key in self._results:
|
|
167
|
+
del self._results[key]
|
|
168
|
+
except (json.JSONDecodeError, KeyError):
|
|
169
|
+
pass
|
|
170
|
+
|
|
171
|
+
async def _on_write(self) -> bytes:
|
|
172
|
+
staged_entries = self._staged_log_entries
|
|
173
|
+
existing_content = await self._client.read(self._executions_path) or b""
|
|
174
|
+
|
|
175
|
+
if self._format == "jsonl":
|
|
176
|
+
content_to_append = ""
|
|
177
|
+
for entry in staged_entries:
|
|
178
|
+
content_to_append += json.dumps(entry, sort_keys=True) + "\n"
|
|
179
|
+
|
|
180
|
+
self._update_in_memory_state(staged_entries)
|
|
181
|
+
return existing_content + content_to_append.encode("utf-8")
|
|
182
|
+
else: # json
|
|
183
|
+
all_entries: list[LogEntry] = []
|
|
184
|
+
if existing_content:
|
|
185
|
+
try:
|
|
186
|
+
all_entries = json.loads(existing_content.decode("utf-8"))
|
|
187
|
+
except json.JSONDecodeError:
|
|
188
|
+
pass
|
|
189
|
+
all_entries.extend(staged_entries)
|
|
190
|
+
new_content = json.dumps(all_entries, indent=2, sort_keys=True)
|
|
191
|
+
|
|
192
|
+
self._update_in_memory_state(staged_entries)
|
|
193
|
+
return new_content.encode("utf-8")
|
|
194
|
+
|
|
195
|
+
async def _on_clear(self) -> None:
|
|
196
|
+
self._staged_log_entries.clear()
|
|
197
|
+
|
|
198
|
+
def _update_in_memory_state(self, entries: list[LogEntry]):
|
|
199
|
+
for entry in entries:
|
|
200
|
+
key = self._callstack_to_key(entry["call_stack"])
|
|
201
|
+
status = _EVENT_TYPE_TO_STATUS.get(entry["event_type"])
|
|
202
|
+
if status is ExecutionStatus.STARTED:
|
|
203
|
+
self._states[key] = ExecutionStatus.STARTED
|
|
204
|
+
elif status is ExecutionStatus.COMPLETED:
|
|
205
|
+
self._states[key] = ExecutionStatus.COMPLETED
|
|
206
|
+
self._results[key] = entry["result"]
|
|
207
|
+
elif status is ExecutionStatus.FAILED:
|
|
208
|
+
self._states[key] = ExecutionStatus.FAILED
|
|
209
|
+
self._errors[key] = entry["error"] or ""
|
|
210
|
+
|
|
211
|
+
async def _add_log_entry(self, entry: LogEntry):
|
|
212
|
+
async with self._lock:
|
|
213
|
+
# If this is the first entry in the transaction, stage the write operation.
|
|
214
|
+
if not self._staged_log_entries:
|
|
215
|
+
await self._client.stage_write(
|
|
216
|
+
self._executions_path,
|
|
217
|
+
self._on_write,
|
|
218
|
+
self._on_clear,
|
|
219
|
+
)
|
|
220
|
+
|
|
221
|
+
self._staged_log_entries.append(entry)
|
|
222
|
+
|
|
223
|
+
async def begin_transaction(self) -> Transaction:
|
|
224
|
+
self._staged_log_entries.clear()
|
|
225
|
+
return _FileTransaction(self._client)
|
|
226
|
+
|
|
227
|
+
async def start_execution(self, execution_id: ExecutionId) -> Execution:
|
|
228
|
+
key = self._id_to_key(execution_id)
|
|
229
|
+
if self._states.get(key) is None:
|
|
230
|
+
entry = LogEntry(
|
|
231
|
+
timestamp=datetime.now(timezone.utc).isoformat(),
|
|
232
|
+
event_type=_STATUS_TO_EVENT_TYPE[ExecutionStatus.STARTED],
|
|
233
|
+
call_stack=self._id_to_callstack(execution_id),
|
|
234
|
+
result=None,
|
|
235
|
+
error=None,
|
|
236
|
+
)
|
|
237
|
+
await self._add_log_entry(entry)
|
|
238
|
+
return _FileExecution(self, execution_id)
|
|
239
|
+
|
|
240
|
+
async def get_execution_record(
|
|
241
|
+
self, execution_id: ExecutionId, return_type: type
|
|
242
|
+
) -> ExecutionRecord | None:
|
|
243
|
+
key = self._id_to_key(execution_id)
|
|
244
|
+
status = self._states.get(key)
|
|
245
|
+
if not status:
|
|
246
|
+
return None
|
|
247
|
+
|
|
248
|
+
result = None
|
|
249
|
+
error = None
|
|
250
|
+
|
|
251
|
+
if status == ExecutionStatus.COMPLETED:
|
|
252
|
+
persistable_result = self._results.get(key)
|
|
253
|
+
if persistable_result is not None:
|
|
254
|
+
serialized_bytes = json.dumps(
|
|
255
|
+
persistable_result, sort_keys=True
|
|
256
|
+
).encode("utf-8")
|
|
257
|
+
result = self._serializer.deserialize(serialized_bytes, return_type)
|
|
258
|
+
elif status == ExecutionStatus.FAILED:
|
|
259
|
+
error = self._errors.get(key)
|
|
260
|
+
|
|
261
|
+
return ExecutionRecord(status=status, result=result, error=error)
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import os
|
|
5
|
+
import tempfile
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any, Awaitable, Callable, Coroutine, NamedTuple
|
|
8
|
+
|
|
9
|
+
WriteCallback = Callable[[], Awaitable[bytes]]
|
|
10
|
+
ClearCallback = Callable[[], Coroutine[Any, Any, None]]
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class StagedWrite(NamedTuple):
|
|
14
|
+
write: WriteCallback
|
|
15
|
+
clear: ClearCallback | None
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class FileClient:
|
|
19
|
+
"""A low-level file-based data store with transactional capabilities."""
|
|
20
|
+
|
|
21
|
+
def __init__(self, base_dir: str | Path, session_id: str):
|
|
22
|
+
self._session_path = Path(base_dir) / session_id
|
|
23
|
+
self._session_path.mkdir(parents=True, exist_ok=True)
|
|
24
|
+
self._staged_writes: dict[str, StagedWrite] = {}
|
|
25
|
+
self._staged_deletes: set[str] = set()
|
|
26
|
+
self._lock = asyncio.Lock()
|
|
27
|
+
|
|
28
|
+
def resolve(self, path: str | Path) -> Path:
|
|
29
|
+
return self._session_path / path
|
|
30
|
+
|
|
31
|
+
async def clear_staged(self) -> None:
|
|
32
|
+
clear_tasks = [
|
|
33
|
+
staged.clear() for staged in self._staged_writes.values() if staged.clear
|
|
34
|
+
]
|
|
35
|
+
if clear_tasks:
|
|
36
|
+
await asyncio.gather(*clear_tasks)
|
|
37
|
+
|
|
38
|
+
self._staged_writes.clear()
|
|
39
|
+
self._staged_deletes.clear()
|
|
40
|
+
|
|
41
|
+
async def commit_staged(self) -> None:
|
|
42
|
+
def _write_temp_file(content: bytes, target_dir: Path) -> str:
|
|
43
|
+
with tempfile.NamedTemporaryFile(
|
|
44
|
+
mode="wb", dir=target_dir, delete=False
|
|
45
|
+
) as f:
|
|
46
|
+
f.write(content)
|
|
47
|
+
return f.name
|
|
48
|
+
|
|
49
|
+
async with self._lock:
|
|
50
|
+
temp_paths: dict[str, str] = {}
|
|
51
|
+
try:
|
|
52
|
+
for rel_path_str, staged_write in self._staged_writes.items():
|
|
53
|
+
target_path = self.resolve(rel_path_str)
|
|
54
|
+
target_path.parent.mkdir(parents=True, exist_ok=True)
|
|
55
|
+
content = await staged_write.write()
|
|
56
|
+
temp_paths[rel_path_str] = await asyncio.to_thread(
|
|
57
|
+
_write_temp_file, content, target_path.parent
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
for rel_path_str, temp_path in temp_paths.items():
|
|
61
|
+
target_path = self.resolve(rel_path_str)
|
|
62
|
+
await asyncio.to_thread(os.replace, temp_path, str(target_path))
|
|
63
|
+
|
|
64
|
+
for rel_path_str in self._staged_deletes:
|
|
65
|
+
target_path = self.resolve(rel_path_str)
|
|
66
|
+
await asyncio.to_thread(
|
|
67
|
+
lambda p=target_path: p.unlink(missing_ok=True)
|
|
68
|
+
)
|
|
69
|
+
finally:
|
|
70
|
+
unlink_tasks = [
|
|
71
|
+
asyncio.to_thread(os.unlink, temp_path)
|
|
72
|
+
for temp_path in temp_paths.values()
|
|
73
|
+
if os.path.exists(temp_path)
|
|
74
|
+
]
|
|
75
|
+
if unlink_tasks:
|
|
76
|
+
await asyncio.gather(*unlink_tasks)
|
|
77
|
+
|
|
78
|
+
await self.clear_staged()
|
|
79
|
+
|
|
80
|
+
async def read(self, path: str | Path) -> bytes | None:
|
|
81
|
+
try:
|
|
82
|
+
return await asyncio.to_thread(self.resolve(path).read_bytes)
|
|
83
|
+
except FileNotFoundError:
|
|
84
|
+
return None
|
|
85
|
+
|
|
86
|
+
async def stage_write(
|
|
87
|
+
self,
|
|
88
|
+
path: str | Path,
|
|
89
|
+
write_callback: WriteCallback,
|
|
90
|
+
clear_callback: ClearCallback | None = None,
|
|
91
|
+
) -> None:
|
|
92
|
+
rel_str = str(path)
|
|
93
|
+
self._staged_writes[rel_str] = StagedWrite(
|
|
94
|
+
write=write_callback, clear=clear_callback
|
|
95
|
+
)
|
|
96
|
+
if rel_str in self._staged_deletes:
|
|
97
|
+
self._staged_deletes.remove(rel_str)
|
|
98
|
+
|
|
99
|
+
async def stage_delete(self, path: str | Path) -> None:
|
|
100
|
+
rel_str = str(path)
|
|
101
|
+
self._staged_deletes.add(rel_str)
|
|
102
|
+
if rel_str in self._staged_writes:
|
|
103
|
+
del self._staged_writes[rel_str]
|
|
File without changes
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
|
|
3
|
+
import pytest
|
|
4
|
+
from glyff import ExecutionId
|
|
5
|
+
from glyff.interfaces import ArgsHasher, Serializer, SessionStore
|
|
6
|
+
from glyff.serialization import JsonArgsHasher, JsonSerializer
|
|
7
|
+
from pytest import FixtureRequest
|
|
8
|
+
|
|
9
|
+
from glyff_file_store import FileClient, FileSessionStore
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@pytest.fixture
|
|
13
|
+
def base_execution_id() -> ExecutionId:
|
|
14
|
+
return ExecutionId(
|
|
15
|
+
parent_id=None, name="test_func", sequence=0, args_hash="abcde123"
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@pytest.fixture
|
|
20
|
+
def serializer() -> Serializer:
|
|
21
|
+
return JsonSerializer()
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@pytest.fixture
|
|
25
|
+
def hasher() -> ArgsHasher:
|
|
26
|
+
return JsonArgsHasher()
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@pytest.fixture(params=["file_jsonl", "file_json"])
|
|
30
|
+
def store_factory(request: FixtureRequest, tmp_path: Path, serializer: Serializer):
|
|
31
|
+
param = request.param
|
|
32
|
+
|
|
33
|
+
def factory(session_id: str) -> SessionStore:
|
|
34
|
+
client = FileClient(base_dir=tmp_path, session_id=session_id)
|
|
35
|
+
fmt = "json" if param == "file_json" else "jsonl"
|
|
36
|
+
return FileSessionStore(client=client, serializer=serializer, format=fmt)
|
|
37
|
+
|
|
38
|
+
return factory
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import json
|
|
2
|
+
|
|
3
|
+
from glyff import Session, engrave
|
|
4
|
+
from glyff.interfaces import ArgsHasher, Serializer
|
|
5
|
+
|
|
6
|
+
from glyff_file_store import FileClient, FileSessionStore
|
|
7
|
+
|
|
8
|
+
_call_count = 0
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def reset_count():
|
|
12
|
+
global _call_count
|
|
13
|
+
_call_count = 0
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@engrave
|
|
17
|
+
async def crash_func() -> str:
|
|
18
|
+
global _call_count
|
|
19
|
+
_call_count += 1
|
|
20
|
+
return "done"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
async def test_started_task_is_rerun_on_next_session(
|
|
24
|
+
tmp_path, serializer: Serializer, hasher: ArgsHasher
|
|
25
|
+
):
|
|
26
|
+
"""Simulates a crash after record_start but before commit by manually
|
|
27
|
+
editing the executions log file to remove the completion record."""
|
|
28
|
+
global _call_count
|
|
29
|
+
_call_count = 0
|
|
30
|
+
|
|
31
|
+
session_id = "crash-recovery"
|
|
32
|
+
client = FileClient(base_dir=tmp_path, session_id=session_id)
|
|
33
|
+
store = FileSessionStore(client=client, serializer=serializer, format="jsonl")
|
|
34
|
+
log_file = client.resolve(store.executions_path)
|
|
35
|
+
|
|
36
|
+
async with Session(id=session_id, store=store, hasher=hasher):
|
|
37
|
+
await crash_func()
|
|
38
|
+
assert _call_count == 1
|
|
39
|
+
|
|
40
|
+
with open(log_file, "r", encoding="utf-8") as f:
|
|
41
|
+
lines = f.readlines()
|
|
42
|
+
|
|
43
|
+
start_lines = [line for line in lines if json.loads(line)["event_type"] == "start"]
|
|
44
|
+
|
|
45
|
+
with open(log_file, "w", encoding="utf-8") as f:
|
|
46
|
+
f.writelines(start_lines)
|
|
47
|
+
|
|
48
|
+
_call_count = 0
|
|
49
|
+
client_after_crash = FileClient(base_dir=tmp_path, session_id=session_id)
|
|
50
|
+
store_after_crash = FileSessionStore(
|
|
51
|
+
client=client_after_crash, serializer=serializer, format="jsonl"
|
|
52
|
+
)
|
|
53
|
+
async with Session(id=session_id, store=store_after_crash, hasher=hasher):
|
|
54
|
+
result = await crash_func()
|
|
55
|
+
|
|
56
|
+
assert result == "done"
|
|
57
|
+
assert _call_count == 1
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
from glyff import ExecutionId
|
|
2
|
+
from glyff.interfaces import SessionStore
|
|
3
|
+
from glyff.models import ExecutionStatus
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
async def test_initial_state_is_none(store_factory, base_execution_id: ExecutionId):
|
|
7
|
+
store: SessionStore = store_factory("test-initial")
|
|
8
|
+
assert await store.get_execution_record(base_execution_id, dict) is None
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
async def test_start_execution_stages_start_event(
|
|
12
|
+
store_factory, base_execution_id: ExecutionId
|
|
13
|
+
):
|
|
14
|
+
store: SessionStore = store_factory("test-start")
|
|
15
|
+
tx = await store.begin_transaction()
|
|
16
|
+
await store.start_execution(base_execution_id)
|
|
17
|
+
assert await store.get_execution_record(base_execution_id, dict) is None
|
|
18
|
+
await tx.commit()
|
|
19
|
+
state = await store.get_execution_record(base_execution_id, dict)
|
|
20
|
+
assert state is not None
|
|
21
|
+
assert state.status == ExecutionStatus.STARTED
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
async def test_commit_completion(store_factory, base_execution_id: ExecutionId):
|
|
25
|
+
store: SessionStore = store_factory("test-commit-ok")
|
|
26
|
+
result_obj = {"result": 42}
|
|
27
|
+
|
|
28
|
+
tx = await store.begin_transaction()
|
|
29
|
+
execution = await store.start_execution(base_execution_id)
|
|
30
|
+
await execution.complete(result_obj, dict)
|
|
31
|
+
assert await store.get_execution_record(base_execution_id, dict) is None
|
|
32
|
+
await tx.commit()
|
|
33
|
+
|
|
34
|
+
state = await store.get_execution_record(base_execution_id, dict)
|
|
35
|
+
assert state is not None
|
|
36
|
+
assert state.status == ExecutionStatus.COMPLETED
|
|
37
|
+
assert state.result == result_obj
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
async def test_commit_failure(store_factory, base_execution_id: ExecutionId):
|
|
41
|
+
store: SessionStore = store_factory("test-commit-fail")
|
|
42
|
+
tx = await store.begin_transaction()
|
|
43
|
+
execution = await store.start_execution(base_execution_id)
|
|
44
|
+
await execution.fail("something went wrong")
|
|
45
|
+
await tx.commit()
|
|
46
|
+
|
|
47
|
+
state = await store.get_execution_record(base_execution_id, str)
|
|
48
|
+
assert state is not None
|
|
49
|
+
assert state.status == ExecutionStatus.FAILED
|
|
50
|
+
assert state.error == "something went wrong"
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
async def test_rollback_discards_staged(store_factory, base_execution_id: ExecutionId):
|
|
54
|
+
store: SessionStore = store_factory("test-rollback")
|
|
55
|
+
tx = await store.begin_transaction()
|
|
56
|
+
execution = await store.start_execution(base_execution_id)
|
|
57
|
+
await execution.complete({"result": 1}, dict)
|
|
58
|
+
await tx.rollback()
|
|
59
|
+
assert await store.get_execution_record(base_execution_id, dict) is None
|