dap-engine 0.3.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.
- dap_engine/__init__.py +3 -0
- dap_engine/__main__.py +80 -0
- dap_engine/api/__init__.py +0 -0
- dap_engine/api/agents.py +546 -0
- dap_engine/api/deps.py +60 -0
- dap_engine/api/health.py +20 -0
- dap_engine/api/pipelines.py +428 -0
- dap_engine/api/projects.py +191 -0
- dap_engine/api/runs.py +694 -0
- dap_engine/api/runtimes.py +29 -0
- dap_engine/api/schemas.py +331 -0
- dap_engine/api/settings.py +288 -0
- dap_engine/app.py +438 -0
- dap_engine/auth/__init__.py +23 -0
- dap_engine/auth/admin_users_routes.py +134 -0
- dap_engine/auth/api_token_routes.py +345 -0
- dap_engine/auth/api_tokens.py +147 -0
- dap_engine/auth/audit.py +91 -0
- dap_engine/auth/audit_routes.py +125 -0
- dap_engine/auth/db.py +135 -0
- dap_engine/auth/oauth.py +41 -0
- dap_engine/auth/policies.py +64 -0
- dap_engine/auth/schemas.py +37 -0
- dap_engine/auth/users.py +400 -0
- dap_engine/contracts.py +205 -0
- dap_engine/execution/__init__.py +30 -0
- dap_engine/execution/conditions.py +87 -0
- dap_engine/execution/node_executor.py +363 -0
- dap_engine/execution/output_parser.py +162 -0
- dap_engine/execution/run_orchestrator.py +213 -0
- dap_engine/execution/run_registry.py +158 -0
- dap_engine/execution/runner.py +422 -0
- dap_engine/execution/validator.py +580 -0
- dap_engine/persistence/__init__.py +0 -0
- dap_engine/persistence/_common.py +24 -0
- dap_engine/persistence/agents.py +410 -0
- dap_engine/persistence/db.py +179 -0
- dap_engine/persistence/migrations.py +739 -0
- dap_engine/persistence/models.py +569 -0
- dap_engine/persistence/pipelines.py +328 -0
- dap_engine/persistence/projects.py +256 -0
- dap_engine/persistence/repository.py +101 -0
- dap_engine/persistence/runs.py +482 -0
- dap_engine/py.typed +0 -0
- dap_engine-0.3.0.dist-info/METADATA +49 -0
- dap_engine-0.3.0.dist-info/RECORD +48 -0
- dap_engine-0.3.0.dist-info/WHEEL +4 -0
- dap_engine-0.3.0.dist-info/entry_points.txt +2 -0
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
"""Background orchestration of pipeline runs (#254).
|
|
2
|
+
|
|
3
|
+
Lifted out of ``api/runs.py``: the two coroutines below are pure
|
|
4
|
+
runner-orchestration with session handling, not HTTP routing. The
|
|
5
|
+
router endpoints (``POST /runs``, ``POST /runs/{id}/resume``,
|
|
6
|
+
``POST /runs/{id}/nodes/{n}/{retry,skip,approve}``) wrap calls to
|
|
7
|
+
these functions in ``asyncio.create_task`` and register the resulting
|
|
8
|
+
task with :class:`RunRegistry`.
|
|
9
|
+
|
|
10
|
+
Each coroutine opens its own DB session via ``session_factory`` so
|
|
11
|
+
the request-scoped session that handled the original POST stays
|
|
12
|
+
short-lived.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import asyncio
|
|
18
|
+
import logging
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
from dap_runtimes import RuntimeRegistry
|
|
22
|
+
from dap_types import PipelineState
|
|
23
|
+
from langgraph.checkpoint.base import BaseCheckpointSaver
|
|
24
|
+
from sqlalchemy import select
|
|
25
|
+
from sqlalchemy.orm import Session, sessionmaker
|
|
26
|
+
|
|
27
|
+
from dap_engine.execution.run_registry import RunRegistry
|
|
28
|
+
from dap_engine.execution.runner import (
|
|
29
|
+
CheckpointNotFoundError,
|
|
30
|
+
PipelineRunner,
|
|
31
|
+
RunnerError,
|
|
32
|
+
RunnerInterrupt,
|
|
33
|
+
)
|
|
34
|
+
from dap_engine.persistence import repository as repo
|
|
35
|
+
from dap_engine.persistence.models import PipelineORM, PipelineVersionORM
|
|
36
|
+
|
|
37
|
+
logger = logging.getLogger("dap.engine.execution.orchestrator")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
async def execute_run_background(
|
|
41
|
+
*,
|
|
42
|
+
run_id: str,
|
|
43
|
+
pipeline_id: str,
|
|
44
|
+
pipeline_version: int,
|
|
45
|
+
initial_state: PipelineState | None,
|
|
46
|
+
session_factory: sessionmaker[Session],
|
|
47
|
+
registry: RuntimeRegistry,
|
|
48
|
+
run_registry: RunRegistry,
|
|
49
|
+
checkpointer: BaseCheckpointSaver[Any],
|
|
50
|
+
resume: bool,
|
|
51
|
+
) -> None:
|
|
52
|
+
"""Run the pipeline in a fresh DB session and finalize the Run row."""
|
|
53
|
+
try:
|
|
54
|
+
with session_factory() as bg_session:
|
|
55
|
+
pipeline_orm = bg_session.get(PipelineORM, pipeline_id)
|
|
56
|
+
version_orm = bg_session.scalar(
|
|
57
|
+
select(PipelineVersionORM)
|
|
58
|
+
.where(PipelineVersionORM.pipeline_id == pipeline_id)
|
|
59
|
+
.where(PipelineVersionORM.version == pipeline_version)
|
|
60
|
+
)
|
|
61
|
+
if pipeline_orm is None or version_orm is None:
|
|
62
|
+
logger.error(
|
|
63
|
+
"background run %s: pipeline %s@v%s vanished",
|
|
64
|
+
run_id,
|
|
65
|
+
pipeline_id,
|
|
66
|
+
pipeline_version,
|
|
67
|
+
)
|
|
68
|
+
repo.finalize_run(bg_session, run_id, final_status="failed")
|
|
69
|
+
bg_session.commit()
|
|
70
|
+
return
|
|
71
|
+
|
|
72
|
+
runner = PipelineRunner(
|
|
73
|
+
session=bg_session,
|
|
74
|
+
registry=registry,
|
|
75
|
+
checkpointer=checkpointer,
|
|
76
|
+
)
|
|
77
|
+
try:
|
|
78
|
+
final_state = await runner.run(
|
|
79
|
+
run_id=run_id,
|
|
80
|
+
pipeline_orm=pipeline_orm,
|
|
81
|
+
pipeline_version_orm=version_orm,
|
|
82
|
+
initial_state=initial_state,
|
|
83
|
+
resume=resume,
|
|
84
|
+
)
|
|
85
|
+
except RunnerInterrupt:
|
|
86
|
+
# Graph paused at an approval-required node (interrupt_before).
|
|
87
|
+
# This is a normal stop — mark run as paused so the operator
|
|
88
|
+
# can resume via POST /runs/{id}/resume or approve via
|
|
89
|
+
# POST /runs/{id}/nodes/{node_id}/approve (#164).
|
|
90
|
+
repo.pause_run(bg_session, run_id)
|
|
91
|
+
bg_session.commit()
|
|
92
|
+
return
|
|
93
|
+
except RunnerError as exc:
|
|
94
|
+
logger.exception("run %s failed: %s", run_id, exc)
|
|
95
|
+
repo.finalize_run(bg_session, run_id, final_status="failed")
|
|
96
|
+
bg_session.commit()
|
|
97
|
+
return
|
|
98
|
+
|
|
99
|
+
final_status = final_state.final_status
|
|
100
|
+
if final_status not in {"success", "failed", "aborted"}:
|
|
101
|
+
final_status = "success"
|
|
102
|
+
repo.finalize_run(bg_session, run_id, final_status=final_status)
|
|
103
|
+
bg_session.commit()
|
|
104
|
+
except asyncio.CancelledError:
|
|
105
|
+
# Cancelled via pause() or abort(). Distinguish via was_paused() flag —
|
|
106
|
+
# paused runs keep their checkpoint and can be resumed (no ended_at);
|
|
107
|
+
# aborted runs are terminal.
|
|
108
|
+
was_paused = run_registry.was_paused(run_id)
|
|
109
|
+
try:
|
|
110
|
+
with session_factory() as cancel_session:
|
|
111
|
+
if was_paused:
|
|
112
|
+
repo.pause_run(cancel_session, run_id)
|
|
113
|
+
else:
|
|
114
|
+
repo.finalize_run(cancel_session, run_id, final_status="aborted")
|
|
115
|
+
cancel_session.commit()
|
|
116
|
+
except Exception:
|
|
117
|
+
logger.exception("failed to finalize cancelled run %s", run_id)
|
|
118
|
+
raise # propagate so the registry sees the cancellation
|
|
119
|
+
except Exception:
|
|
120
|
+
logger.exception("background run %s crashed", run_id)
|
|
121
|
+
try:
|
|
122
|
+
with session_factory() as crash_session:
|
|
123
|
+
repo.finalize_run(crash_session, run_id, final_status="failed")
|
|
124
|
+
crash_session.commit()
|
|
125
|
+
except Exception:
|
|
126
|
+
logger.exception("failed to finalize crashed run %s", run_id)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
async def execute_rewind_background(
|
|
130
|
+
*,
|
|
131
|
+
run_id: str,
|
|
132
|
+
pipeline_id: str,
|
|
133
|
+
pipeline_version: int,
|
|
134
|
+
target_node: str,
|
|
135
|
+
mode: str,
|
|
136
|
+
session_factory: sessionmaker[Session],
|
|
137
|
+
registry: RuntimeRegistry,
|
|
138
|
+
run_registry: RunRegistry,
|
|
139
|
+
checkpointer: BaseCheckpointSaver[Any],
|
|
140
|
+
) -> None:
|
|
141
|
+
"""Run a retry/skip rewind in a fresh DB session and finalize the Run row."""
|
|
142
|
+
try:
|
|
143
|
+
with session_factory() as bg_session:
|
|
144
|
+
pipeline_orm = bg_session.get(PipelineORM, pipeline_id)
|
|
145
|
+
version_orm = bg_session.scalar(
|
|
146
|
+
select(PipelineVersionORM)
|
|
147
|
+
.where(PipelineVersionORM.pipeline_id == pipeline_id)
|
|
148
|
+
.where(PipelineVersionORM.version == pipeline_version)
|
|
149
|
+
)
|
|
150
|
+
if pipeline_orm is None or version_orm is None:
|
|
151
|
+
logger.error(
|
|
152
|
+
"rewind run %s: pipeline %s@v%s vanished",
|
|
153
|
+
run_id,
|
|
154
|
+
pipeline_id,
|
|
155
|
+
pipeline_version,
|
|
156
|
+
)
|
|
157
|
+
repo.finalize_run(bg_session, run_id, final_status="failed")
|
|
158
|
+
bg_session.commit()
|
|
159
|
+
return
|
|
160
|
+
|
|
161
|
+
runner = PipelineRunner(
|
|
162
|
+
session=bg_session,
|
|
163
|
+
registry=registry,
|
|
164
|
+
checkpointer=checkpointer,
|
|
165
|
+
)
|
|
166
|
+
try:
|
|
167
|
+
final_state = await runner.rewind_and_run(
|
|
168
|
+
run_id=run_id,
|
|
169
|
+
pipeline_orm=pipeline_orm,
|
|
170
|
+
pipeline_version_orm=version_orm,
|
|
171
|
+
target_node=target_node,
|
|
172
|
+
mode=mode,
|
|
173
|
+
)
|
|
174
|
+
except RunnerInterrupt:
|
|
175
|
+
repo.pause_run(bg_session, run_id)
|
|
176
|
+
bg_session.commit()
|
|
177
|
+
return
|
|
178
|
+
except CheckpointNotFoundError as exc:
|
|
179
|
+
logger.warning("rewind run %s: %s", run_id, exc)
|
|
180
|
+
repo.finalize_run(bg_session, run_id, final_status="failed")
|
|
181
|
+
bg_session.commit()
|
|
182
|
+
return
|
|
183
|
+
except RunnerError as exc:
|
|
184
|
+
logger.exception("rewind run %s failed: %s", run_id, exc)
|
|
185
|
+
repo.finalize_run(bg_session, run_id, final_status="failed")
|
|
186
|
+
bg_session.commit()
|
|
187
|
+
return
|
|
188
|
+
|
|
189
|
+
final_status = final_state.final_status
|
|
190
|
+
if final_status not in {"success", "failed", "aborted"}:
|
|
191
|
+
final_status = "success"
|
|
192
|
+
repo.finalize_run(bg_session, run_id, final_status=final_status)
|
|
193
|
+
bg_session.commit()
|
|
194
|
+
except asyncio.CancelledError:
|
|
195
|
+
was_paused = run_registry.was_paused(run_id)
|
|
196
|
+
try:
|
|
197
|
+
with session_factory() as cancel_session:
|
|
198
|
+
if was_paused:
|
|
199
|
+
repo.pause_run(cancel_session, run_id)
|
|
200
|
+
else:
|
|
201
|
+
repo.finalize_run(cancel_session, run_id, final_status="aborted")
|
|
202
|
+
cancel_session.commit()
|
|
203
|
+
except Exception:
|
|
204
|
+
logger.exception("failed to finalize cancelled rewind run %s", run_id)
|
|
205
|
+
raise
|
|
206
|
+
except Exception:
|
|
207
|
+
logger.exception("background rewind run %s crashed", run_id)
|
|
208
|
+
try:
|
|
209
|
+
with session_factory() as crash_session:
|
|
210
|
+
repo.finalize_run(crash_session, run_id, final_status="failed")
|
|
211
|
+
crash_session.commit()
|
|
212
|
+
except Exception:
|
|
213
|
+
logger.exception("failed to finalize crashed rewind run %s", run_id)
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
"""In-memory tracker of running asyncio tasks per run_id.
|
|
2
|
+
|
|
3
|
+
Required for abort + graceful shutdown. Process-local — restarting the
|
|
4
|
+
engine forgets the registry; persistent state lives in the DB (Run rows).
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import asyncio
|
|
10
|
+
import logging
|
|
11
|
+
import threading
|
|
12
|
+
|
|
13
|
+
logger = logging.getLogger("dap.engine.execution.registry")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class RunRegistry:
|
|
17
|
+
"""Maps run_id → asyncio.Task.
|
|
18
|
+
|
|
19
|
+
Mutations of the underlying ``_tasks`` / ``_paused`` collections are
|
|
20
|
+
serialised under a ``threading.Lock`` (#258). In normal single-loop
|
|
21
|
+
operation the lock is uncontended — Python bytecode for the
|
|
22
|
+
check-then-set in ``register`` already runs without yielding the
|
|
23
|
+
event loop — but the explicit lock makes the registry correct under
|
|
24
|
+
multi-thread access (e.g. shutdown handlers running off the loop)
|
|
25
|
+
without relying on that implicit single-thread invariant.
|
|
26
|
+
|
|
27
|
+
The DB-side TOCTOU guard for resume / revive lives in
|
|
28
|
+
:func:`dap_engine.persistence.runs.try_claim_resume` (#185); this
|
|
29
|
+
registry only protects its own in-memory state.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
def __init__(self) -> None:
|
|
33
|
+
self._tasks: dict[str, asyncio.Task[None]] = {}
|
|
34
|
+
self._paused: set[str] = set()
|
|
35
|
+
# Sync mutex (not asyncio.Lock) so callers don't have to be async
|
|
36
|
+
# — register is invoked from sync code paths (e.g. POST handlers'
|
|
37
|
+
# post-claim block) and the critical section is a few dict ops.
|
|
38
|
+
self._lock = threading.Lock()
|
|
39
|
+
|
|
40
|
+
def register(self, run_id: str, task: asyncio.Task[None]) -> None:
|
|
41
|
+
with self._lock:
|
|
42
|
+
existing = self._tasks.get(run_id)
|
|
43
|
+
if existing is not None and not existing.done():
|
|
44
|
+
raise ValueError(f"Run already registered: {run_id}")
|
|
45
|
+
# Replace stale done-task slot (e.g. resume after pause where the
|
|
46
|
+
# done-callback has not been dispatched yet by the loop).
|
|
47
|
+
self._tasks[run_id] = task
|
|
48
|
+
self._paused.discard(run_id)
|
|
49
|
+
|
|
50
|
+
def _cleanup(_t: asyncio.Task[None]) -> None:
|
|
51
|
+
# Only clear the slot if it still points at *this* task —
|
|
52
|
+
# a fast resume may have replaced it with a fresh task.
|
|
53
|
+
with self._lock:
|
|
54
|
+
if self._tasks.get(run_id) is task:
|
|
55
|
+
self._tasks.pop(run_id, None)
|
|
56
|
+
self._paused.discard(run_id)
|
|
57
|
+
|
|
58
|
+
task.add_done_callback(_cleanup)
|
|
59
|
+
|
|
60
|
+
def get(self, run_id: str) -> asyncio.Task[None] | None:
|
|
61
|
+
with self._lock:
|
|
62
|
+
return self._tasks.get(run_id)
|
|
63
|
+
|
|
64
|
+
def is_running(self, run_id: str) -> bool:
|
|
65
|
+
with self._lock:
|
|
66
|
+
task = self._tasks.get(run_id)
|
|
67
|
+
return task is not None and not task.done()
|
|
68
|
+
|
|
69
|
+
def list_running(self) -> list[str]:
|
|
70
|
+
# Snapshot the items under lock so a concurrent register / cleanup
|
|
71
|
+
# can't mutate the dict mid-iteration. Done-state check happens
|
|
72
|
+
# after release: a task transitioning to done while we evaluate
|
|
73
|
+
# is harmless, the next call observes the new state.
|
|
74
|
+
with self._lock:
|
|
75
|
+
items = list(self._tasks.items())
|
|
76
|
+
return [run_id for run_id, t in items if not t.done()]
|
|
77
|
+
|
|
78
|
+
async def abort(self, run_id: str) -> bool:
|
|
79
|
+
"""Cancel the task for `run_id`. Returns True if a running task was found.
|
|
80
|
+
|
|
81
|
+
Caller is responsible for updating the Run row's final_status.
|
|
82
|
+
"""
|
|
83
|
+
with self._lock:
|
|
84
|
+
task = self._tasks.get(run_id)
|
|
85
|
+
if task is None or task.done():
|
|
86
|
+
return False
|
|
87
|
+
# Lock released before await — the cleanup callback that fires when
|
|
88
|
+
# the cancelled task transitions to done re-acquires the same lock,
|
|
89
|
+
# so holding it across the await would deadlock.
|
|
90
|
+
task.cancel()
|
|
91
|
+
try:
|
|
92
|
+
await task
|
|
93
|
+
except asyncio.CancelledError:
|
|
94
|
+
pass
|
|
95
|
+
except Exception:
|
|
96
|
+
logger.exception("task for run %s raised during cancellation", run_id)
|
|
97
|
+
return True
|
|
98
|
+
|
|
99
|
+
async def pause(self, run_id: str) -> bool:
|
|
100
|
+
"""Mark a run as paused and cancel its task.
|
|
101
|
+
|
|
102
|
+
Pausing relies on LangGraph's checkpointer: the task is cancelled
|
|
103
|
+
between node boundaries, but the checkpointed state remains, so
|
|
104
|
+
a later resume() can pick up where it left off.
|
|
105
|
+
|
|
106
|
+
Returns True if a running task was found and cancelled.
|
|
107
|
+
"""
|
|
108
|
+
# Lookup-and-mark under lock so the ``_paused`` flip and the
|
|
109
|
+
# task-found check appear atomic to other registry callers.
|
|
110
|
+
with self._lock:
|
|
111
|
+
task = self._tasks.get(run_id)
|
|
112
|
+
if task is None or task.done():
|
|
113
|
+
return False
|
|
114
|
+
self._paused.add(run_id)
|
|
115
|
+
task.cancel()
|
|
116
|
+
try:
|
|
117
|
+
await task
|
|
118
|
+
except asyncio.CancelledError:
|
|
119
|
+
pass
|
|
120
|
+
except Exception:
|
|
121
|
+
logger.exception("task for run %s raised during pause", run_id)
|
|
122
|
+
return True
|
|
123
|
+
|
|
124
|
+
def was_paused(self, run_id: str) -> bool:
|
|
125
|
+
"""Whether the (now-cancelled) task was cancelled via pause(), not abort()."""
|
|
126
|
+
with self._lock:
|
|
127
|
+
return run_id in self._paused
|
|
128
|
+
|
|
129
|
+
async def shutdown(self, *, timeout: float = 5.0) -> list[str]:
|
|
130
|
+
"""Cancel all running tasks. Returns list of run_ids that were cancelled.
|
|
131
|
+
|
|
132
|
+
Used at engine teardown to ensure no orphan tasks leak.
|
|
133
|
+
"""
|
|
134
|
+
# Snapshot the (run_id, task) pairs under lock — we need both to
|
|
135
|
+
# cancel and await without iterating ``_tasks`` while cleanup
|
|
136
|
+
# callbacks pop entries.
|
|
137
|
+
with self._lock:
|
|
138
|
+
running = [(rid, t) for rid, t in self._tasks.items() if not t.done()]
|
|
139
|
+
if not running:
|
|
140
|
+
return []
|
|
141
|
+
|
|
142
|
+
for _run_id, task in running:
|
|
143
|
+
if not task.done():
|
|
144
|
+
task.cancel()
|
|
145
|
+
|
|
146
|
+
tasks = [t for _rid, t in running]
|
|
147
|
+
if tasks:
|
|
148
|
+
try:
|
|
149
|
+
await asyncio.wait_for(
|
|
150
|
+
asyncio.gather(*tasks, return_exceptions=True),
|
|
151
|
+
timeout=timeout,
|
|
152
|
+
)
|
|
153
|
+
except TimeoutError:
|
|
154
|
+
logger.warning(
|
|
155
|
+
"shutdown timeout (%.1fs) — some run tasks may not have finalized",
|
|
156
|
+
timeout,
|
|
157
|
+
)
|
|
158
|
+
return [rid for rid, _t in running]
|