glyff 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.
Files changed (36) hide show
  1. glyff-0.1.0/.gitignore +210 -0
  2. glyff-0.1.0/LICENSE +21 -0
  3. glyff-0.1.0/PKG-INFO +91 -0
  4. glyff-0.1.0/README.md +53 -0
  5. glyff-0.1.0/pyproject.toml +38 -0
  6. glyff-0.1.0/src/glyff/__init__.py +15 -0
  7. glyff-0.1.0/src/glyff/context.py +174 -0
  8. glyff-0.1.0/src/glyff/decorators.py +51 -0
  9. glyff-0.1.0/src/glyff/exceptions.py +16 -0
  10. glyff-0.1.0/src/glyff/executor.py +60 -0
  11. glyff-0.1.0/src/glyff/interfaces.py +92 -0
  12. glyff-0.1.0/src/glyff/models.py +47 -0
  13. glyff-0.1.0/src/glyff/sequencer.py +40 -0
  14. glyff-0.1.0/src/glyff/serialization/__init__.py +6 -0
  15. glyff-0.1.0/src/glyff/serialization/json.py +48 -0
  16. glyff-0.1.0/src/glyff/session.py +52 -0
  17. glyff-0.1.0/src/glyff/stores/__init__.py +7 -0
  18. glyff-0.1.0/src/glyff/stores/memory.py +91 -0
  19. glyff-0.1.0/src/glyff/stores/memory_client.py +41 -0
  20. glyff-0.1.0/src/glyff/tests/__init__.py +0 -0
  21. glyff-0.1.0/src/glyff/tests/conftest.py +68 -0
  22. glyff-0.1.0/src/glyff/tests/scenarios/__init__.py +0 -0
  23. glyff-0.1.0/src/glyff/tests/scenarios/test_basic_execution.py +102 -0
  24. glyff-0.1.0/src/glyff/tests/scenarios/test_interruption_resumption.py +80 -0
  25. glyff-0.1.0/src/glyff/tests/scenarios/test_parallel_execution.py +81 -0
  26. glyff-0.1.0/src/glyff/tests/stubs/__init__.py +0 -0
  27. glyff-0.1.0/src/glyff/tests/stubs/store.py +74 -0
  28. glyff-0.1.0/src/glyff/tests/types.py +5 -0
  29. glyff-0.1.0/src/glyff/tests/units/__init__.py +0 -0
  30. glyff-0.1.0/src/glyff/tests/units/test_decorators.py +53 -0
  31. glyff-0.1.0/src/glyff/tests/units/test_decorators_no_future.py +25 -0
  32. glyff-0.1.0/src/glyff/tests/units/test_execution_id.py +15 -0
  33. glyff-0.1.0/src/glyff/tests/units/test_executor.py +202 -0
  34. glyff-0.1.0/src/glyff/tests/units/test_json_serializer.py +60 -0
  35. glyff-0.1.0/src/glyff/tests/units/test_sequencer.py +49 -0
  36. glyff-0.1.0/src/glyff/tests/units/test_stores.py +71 -0
glyff-0.1.0/.gitignore ADDED
@@ -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/
glyff-0.1.0/LICENSE ADDED
@@ -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.
glyff-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,91 @@
1
+ Metadata-Version: 2.4
2
+ Name: glyff
3
+ Version: 0.1.0
4
+ Summary: Guaranteed Lightweight Yieldable Function Foundation for checkpointed and resumable task execution.
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
+ Description-Content-Type: text/markdown
38
+
39
+ # glyff
40
+
41
+ **G**uaranteed **L**ightweight **Y**ieldable **F**unction **F**oundation.
42
+
43
+ A primitive for pausing async functions across process and request boundaries,
44
+ and resuming them later from the same point.
45
+
46
+ ## Install
47
+
48
+ ```bash
49
+ pip install glyff
50
+ ```
51
+
52
+ `glyff` has no dependencies beyond the Python standard library.
53
+
54
+ ## Behavior
55
+
56
+ - Marked function calls are recorded in a session-scoped store, keyed by
57
+ function identity, arguments, and call position.
58
+ - Re-invoking the same call within the same session returns the recorded
59
+ result instead of re-executing.
60
+ - A call's outcome — success or failure — is permanent once recorded.
61
+ - `YieldException` suspends execution at a function boundary; the session
62
+ can be resumed later by entering it again with the same session id.
63
+
64
+ ## Public API
65
+
66
+ | Name | Description |
67
+ | ----------------- | --------------------------------------------------------------- |
68
+ | `engrave` | Decorator that marks an async function for recording. |
69
+ | `Session` | Async context manager that scopes a sequence of engraved calls. |
70
+ | `ExecutionId` | Identifier for a recorded function execution. |
71
+ | `ExecutionRecord` | Persisted execution state and result. |
72
+ | `ExecutionStatus` | Enum: `STARTED`, `COMPLETED`, `FAILED`. |
73
+ | `SessionStore` | Protocol for storage backends. |
74
+ | `Serializer` | Protocol for value serialization. |
75
+ | `ArgsHasher` | Protocol for argument hashing. |
76
+ | `YieldException` | Raised to suspend a session. |
77
+
78
+ ## Extending
79
+
80
+ - For persistent storage, see [`glyff-file-store`](https://pypi.org/project/glyff-file-store/).
81
+ - For Pydantic-typed serialization, see [`glyff-pydantic`](https://pypi.org/project/glyff-pydantic/).
82
+ - Custom backends can be written by implementing the `SessionStore`,
83
+ `Serializer`, and `ArgsHasher` protocols.
84
+
85
+ ## Status
86
+
87
+ Early development. APIs may change before v1.0.
88
+
89
+ ## License
90
+
91
+ MIT
glyff-0.1.0/README.md ADDED
@@ -0,0 +1,53 @@
1
+ # glyff
2
+
3
+ **G**uaranteed **L**ightweight **Y**ieldable **F**unction **F**oundation.
4
+
5
+ A primitive for pausing async functions across process and request boundaries,
6
+ and resuming them later from the same point.
7
+
8
+ ## Install
9
+
10
+ ```bash
11
+ pip install glyff
12
+ ```
13
+
14
+ `glyff` has no dependencies beyond the Python standard library.
15
+
16
+ ## Behavior
17
+
18
+ - Marked function calls are recorded in a session-scoped store, keyed by
19
+ function identity, arguments, and call position.
20
+ - Re-invoking the same call within the same session returns the recorded
21
+ result instead of re-executing.
22
+ - A call's outcome — success or failure — is permanent once recorded.
23
+ - `YieldException` suspends execution at a function boundary; the session
24
+ can be resumed later by entering it again with the same session id.
25
+
26
+ ## Public API
27
+
28
+ | Name | Description |
29
+ | ----------------- | --------------------------------------------------------------- |
30
+ | `engrave` | Decorator that marks an async function for recording. |
31
+ | `Session` | Async context manager that scopes a sequence of engraved calls. |
32
+ | `ExecutionId` | Identifier for a recorded function execution. |
33
+ | `ExecutionRecord` | Persisted execution state and result. |
34
+ | `ExecutionStatus` | Enum: `STARTED`, `COMPLETED`, `FAILED`. |
35
+ | `SessionStore` | Protocol for storage backends. |
36
+ | `Serializer` | Protocol for value serialization. |
37
+ | `ArgsHasher` | Protocol for argument hashing. |
38
+ | `YieldException` | Raised to suspend a session. |
39
+
40
+ ## Extending
41
+
42
+ - For persistent storage, see [`glyff-file-store`](https://pypi.org/project/glyff-file-store/).
43
+ - For Pydantic-typed serialization, see [`glyff-pydantic`](https://pypi.org/project/glyff-pydantic/).
44
+ - Custom backends can be written by implementing the `SessionStore`,
45
+ `Serializer`, and `ArgsHasher` protocols.
46
+
47
+ ## Status
48
+
49
+ Early development. APIs may change before v1.0.
50
+
51
+ ## License
52
+
53
+ MIT
@@ -0,0 +1,38 @@
1
+ [project]
2
+ name = "glyff"
3
+ description = "Guaranteed Lightweight Yieldable Function Foundation for checkpointed and resumable task execution."
4
+ readme = "README.md"
5
+ license = { file = "LICENSE" }
6
+ requires-python = ">=3.11"
7
+ dependencies = []
8
+ dynamic = ["version"]
9
+ classifiers = [
10
+ "Programming Language :: Python :: 3",
11
+ "Programming Language :: Python :: 3.11",
12
+ "Programming Language :: Python :: 3.12",
13
+ "Programming Language :: Python :: 3.13",
14
+ "License :: OSI Approved :: MIT License",
15
+ "Operating System :: OS Independent",
16
+ "Development Status :: 3 - Alpha",
17
+ "Framework :: AsyncIO",
18
+ "Typing :: Typed",
19
+ ]
20
+
21
+ [build-system]
22
+ requires = ["hatchling", "hatch-vcs"]
23
+ build-backend = "hatchling.build"
24
+
25
+ [tool.hatch.build.targets.wheel]
26
+ packages = ["src/glyff"]
27
+ exclude = ["src/glyff/tests"]
28
+
29
+ [tool.hatch.version]
30
+ source = "vcs"
31
+ raw-options = { root = "../.." }
32
+
33
+ [tool.pytest.ini_options]
34
+ asyncio_mode = "auto"
35
+ testpaths = ["src/glyff/tests"]
36
+
37
+ [dependency-groups]
38
+ dev = ["pytest>=8.0", "pytest-asyncio>=0.23", "pytest-mock>=3.12.0"]
@@ -0,0 +1,15 @@
1
+ from .decorators import engrave
2
+ from .interfaces import ArgsHasher, Serializer, SessionStore
3
+ from .models import ExecutionId, ExecutionRecord, ExecutionStatus
4
+ from .session import Session
5
+
6
+ __all__ = [
7
+ "engrave",
8
+ "Session",
9
+ "ExecutionId",
10
+ "ExecutionRecord",
11
+ "ExecutionStatus",
12
+ "ArgsHasher",
13
+ "Serializer",
14
+ "SessionStore",
15
+ ]
@@ -0,0 +1,174 @@
1
+ from __future__ import annotations
2
+
3
+ import contextvars
4
+ from collections.abc import Iterator, Sequence
5
+ from typing import Callable, overload
6
+
7
+ from .exceptions import ExecutionFailedError, YieldException
8
+ from .interfaces import ArgsHasher, SessionStore, Transaction
9
+ from .models import ExecutionId
10
+ from .sequencer import Sequencer
11
+
12
+
13
+ class Context:
14
+ """Holds the execution context for a workflow session."""
15
+
16
+ def __init__(
17
+ self,
18
+ session_id: str,
19
+ store: SessionStore,
20
+ sequencer: Sequencer,
21
+ hasher: ArgsHasher,
22
+ transaction_scope_factory: Callable[[], TransactionScope],
23
+ ) -> None:
24
+ self._session_id = session_id
25
+ self._store = store
26
+ self._sequencer = sequencer
27
+ self._hasher = hasher
28
+ self._transaction_scope_factory = transaction_scope_factory
29
+ self._tracer = ExecutionTracer()
30
+ self._current_transaction_scope: TransactionScope | None = None
31
+
32
+ @property
33
+ def store(self) -> SessionStore:
34
+ return self._store
35
+
36
+ @property
37
+ def sequencer(self) -> Sequencer:
38
+ return self._sequencer
39
+
40
+ @property
41
+ def hasher(self) -> ArgsHasher:
42
+ return self._hasher
43
+
44
+ @property
45
+ def tracer(self) -> ExecutionTracer:
46
+ return self._tracer
47
+
48
+ @property
49
+ def call_stack(self) -> CallStack:
50
+ return self._tracer.call_stack
51
+
52
+ @property
53
+ def current_execution_id(self) -> ExecutionId | None:
54
+ return self._tracer.current
55
+
56
+ @property
57
+ def in_transaction(self) -> bool:
58
+ """Returns True if currently within a transaction scope."""
59
+ ts = self._current_transaction_scope
60
+ return ts is not None and ts.in_transaction
61
+
62
+ def get_transaction_scope(self) -> TransactionScope:
63
+ if self._current_transaction_scope is None:
64
+ self._current_transaction_scope = self._transaction_scope_factory()
65
+ return self._current_transaction_scope
66
+
67
+
68
+ class CallStack(Sequence[ExecutionId]):
69
+ """Read-only view of the execution call stack. No allocation on access."""
70
+
71
+ __slots__ = ("_data",)
72
+
73
+ def __init__(self, data: list[ExecutionId]) -> None:
74
+ self._data = data
75
+
76
+ @overload
77
+ def __getitem__(self, index: int) -> ExecutionId: ...
78
+ @overload
79
+ def __getitem__(self, index: slice) -> list[ExecutionId]: ...
80
+
81
+ def __getitem__(self, index):
82
+ return self._data[index]
83
+
84
+ def __len__(self) -> int:
85
+ return len(self._data)
86
+
87
+ def __contains__(self, item: object) -> bool:
88
+ return item in self._data
89
+
90
+ def __iter__(self) -> Iterator[ExecutionId]:
91
+ return iter(self._data)
92
+
93
+ def __repr__(self) -> str:
94
+ return f"CallStack({self._data!r})"
95
+
96
+
97
+ class ExecutionTracer:
98
+ """Records the active call stack during workflow execution."""
99
+
100
+ def __init__(self) -> None:
101
+ self._stack: list[ExecutionId] = []
102
+ self._view = CallStack(self._stack)
103
+
104
+ @property
105
+ def call_stack(self) -> CallStack:
106
+ return self._view
107
+
108
+ @property
109
+ def current(self) -> ExecutionId | None:
110
+ return self._stack[-1] if self._stack else None
111
+
112
+ def start(self, execution_id: ExecutionId) -> None:
113
+ self._stack.append(execution_id)
114
+
115
+ def end(self) -> None:
116
+ self._stack.pop()
117
+
118
+
119
+ class TransactionScope:
120
+ """
121
+ Manages a transaction across a SessionStore, supporting nesting.
122
+ The actual commit/rollback only happens at the outermost scope.
123
+ """
124
+
125
+ def __init__(self, store: SessionStore):
126
+ self._store = store
127
+ self._level = 0
128
+ self._transaction: Transaction | None = None
129
+
130
+ @property
131
+ def in_transaction(self) -> bool:
132
+ """Returns True if currently within a transaction scope."""
133
+ return self._level > 0
134
+
135
+ async def __aenter__(self):
136
+ if self._level == 0:
137
+ self._transaction = await self._store.begin_transaction()
138
+ self._level += 1
139
+ return self
140
+
141
+ async def __aexit__(self, exc_type, exc_val, exc_tb):
142
+ self._level -= 1
143
+ if self._level == 0 and self._transaction:
144
+ if exc_type is None or isinstance(
145
+ exc_val, (YieldException, ExecutionFailedError)
146
+ ):
147
+ # On YieldException or ExecutionFailedError we still commit so that
148
+ # state (completed subtasks or the failure record) is durably saved.
149
+ await self._transaction.commit()
150
+ else:
151
+ await self._transaction.rollback()
152
+
153
+
154
+ _context_var: contextvars.ContextVar[Context] = contextvars.ContextVar("glyff_context")
155
+
156
+
157
+ def get_context() -> Context:
158
+ """Retrieves the current workflow context."""
159
+ try:
160
+ return _context_var.get()
161
+ except LookupError:
162
+ raise RuntimeError(
163
+ "Workflow context is not set. Are you running outside a Session?"
164
+ )
165
+
166
+
167
+ def set_context(ctx: Context) -> contextvars.Token:
168
+ """Sets the current workflow context. Returns a token that can be used to reset it."""
169
+ return _context_var.set(ctx)
170
+
171
+
172
+ def reset_context(token: contextvars.Token) -> None:
173
+ """Resets the workflow context to a previous state using the provided token."""
174
+ _context_var.reset(token)
@@ -0,0 +1,51 @@
1
+ import functools
2
+ import inspect
3
+ from typing import Any, Callable, ParamSpec, TypeVar, cast
4
+
5
+ from .context import get_context
6
+ from .executor import execute
7
+ from .models import ExecutionId
8
+
9
+ P = ParamSpec("P")
10
+ R = TypeVar("R")
11
+
12
+
13
+ def engrave(func: Callable[P, R]) -> Callable[P, R]:
14
+ """
15
+ Decorator that makes an async method engraveable and resumable.
16
+ Its main responsibilities are ExecutionId creation and delegation to the
17
+ `executor` module.
18
+ """
19
+ sig = inspect.signature(func)
20
+ task_name = getattr(func, "__qualname__", func.__name__)
21
+
22
+ try:
23
+ type_hints = inspect.get_annotations(func, eval_str=True)
24
+ return_type = type_hints.get("return", Any)
25
+ except Exception as e:
26
+ raise TypeError(
27
+ f"Could not resolve type hints for {task_name}. "
28
+ f"Please ensure all types are correctly defined and imported. Error: {e}"
29
+ ) from e
30
+
31
+ @functools.wraps(func)
32
+ async def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
33
+ ctx = get_context()
34
+ parent_id = ctx.current_execution_id
35
+ seq = await ctx.sequencer.next(parent_id, task_name)
36
+ args_hash = ctx.hasher.hash_args(func, sig, args, kwargs)
37
+ execution_id = ExecutionId(
38
+ parent_id=parent_id, name=task_name, sequence=seq, args_hash=args_hash
39
+ )
40
+
41
+ result = await execute(
42
+ ctx=ctx,
43
+ execution_id=execution_id,
44
+ func=func,
45
+ args=args,
46
+ kwargs=kwargs,
47
+ return_type=return_type,
48
+ )
49
+ return cast(R, result)
50
+
51
+ return cast(Callable[P, R], wrapper)
@@ -0,0 +1,16 @@
1
+ class YieldException(Exception):
2
+ """
3
+ A special exception to signal that the session should be interrupted gracefully.
4
+ This is not an error, but a signal to stop processing and engrave the state.
5
+ """
6
+
7
+ pass
8
+
9
+
10
+ class ExecutionFailedError(Exception):
11
+ """
12
+ Raised when attempting to execute a task that has previously failed
13
+ and its failure state is engraved.
14
+ """
15
+
16
+ pass