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,482 @@
|
|
|
1
|
+
"""Run persistence — Run lifecycle, state snapshots, node-execution logs.
|
|
2
|
+
|
|
3
|
+
Ownership: read / list helpers (``get_run``, ``list_runs``,
|
|
4
|
+
``get_run_state``, ``list_run_state_history``, ``get_run_node_log``)
|
|
5
|
+
take the actor's ``user_id`` plus an ``is_admin`` flag. Cross-user
|
|
6
|
+
lookups raise ``NotFoundError`` (anti-enumeration — same rule
|
|
7
|
+
``agents.py`` / ``pipelines.py`` / ``projects.py`` apply).
|
|
8
|
+
|
|
9
|
+
Lifecycle primitives (``finalize_run``, ``pause_run``,
|
|
10
|
+
``try_claim_resume``, ``try_claim_revive``,
|
|
11
|
+
``mark_stale_running_runs_as_failed``) **deliberately** take no
|
|
12
|
+
ownership args — they're called from background asyncio tasks and the
|
|
13
|
+
engine-startup hook, neither of which has a user context. The
|
|
14
|
+
ownership boundary is established by the API route, which gates
|
|
15
|
+
``get_run(actor_id, is_admin)`` before invoking any primitive.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import uuid
|
|
21
|
+
from collections.abc import Sequence
|
|
22
|
+
from typing import Final
|
|
23
|
+
|
|
24
|
+
from dap_types import (
|
|
25
|
+
NodeExecutionLog,
|
|
26
|
+
PipelineState,
|
|
27
|
+
Run,
|
|
28
|
+
StateSnapshot,
|
|
29
|
+
)
|
|
30
|
+
from sqlalchemy import ColumnElement, func, select, update
|
|
31
|
+
from sqlalchemy.orm import Session
|
|
32
|
+
|
|
33
|
+
from dap_engine.auth.audit import record_audit_event
|
|
34
|
+
from dap_engine.persistence._common import NotFoundError, _new_id, _now
|
|
35
|
+
from dap_engine.persistence.models import (
|
|
36
|
+
NodeExecutionLogORM,
|
|
37
|
+
RunORM,
|
|
38
|
+
StateSnapshotORM,
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _ownership_filter(
|
|
43
|
+
actor_id: uuid.UUID,
|
|
44
|
+
is_admin: bool,
|
|
45
|
+
) -> list[ColumnElement[bool]]:
|
|
46
|
+
"""Return ``[]`` for admins, else a single-clause filter for the actor.
|
|
47
|
+
|
|
48
|
+
Admins see all rows (including legacy NULL ``user_id`` rows from
|
|
49
|
+
the pre-v0.3 backfill); non-admins only see runs they triggered.
|
|
50
|
+
"""
|
|
51
|
+
if is_admin:
|
|
52
|
+
return []
|
|
53
|
+
return [RunORM.user_id == actor_id]
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
# Statuses considered terminal — once a run lands in any of these,
|
|
57
|
+
# ``finalize_run`` / ``pause_run`` short-circuit so a stray late cancel
|
|
58
|
+
# can't overwrite the run's recorded outcome (#257).
|
|
59
|
+
_TERMINAL_STATUSES: Final = frozenset({"success", "failed", "aborted"})
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _run_from_orm(
|
|
63
|
+
run: RunORM,
|
|
64
|
+
*,
|
|
65
|
+
node_statuses_override: dict[str, str] | None = None,
|
|
66
|
+
) -> Run:
|
|
67
|
+
return Run(
|
|
68
|
+
id=run.id,
|
|
69
|
+
project_id=run.project_id,
|
|
70
|
+
pipeline_id=run.pipeline_id,
|
|
71
|
+
pipeline_version=run.pipeline_version,
|
|
72
|
+
trigger_source=run.trigger_source, # type: ignore[arg-type]
|
|
73
|
+
initial_state=PipelineState.model_validate(run.initial_state),
|
|
74
|
+
current_node=run.current_node,
|
|
75
|
+
node_statuses=(
|
|
76
|
+
node_statuses_override # type: ignore[arg-type]
|
|
77
|
+
if node_statuses_override is not None
|
|
78
|
+
else run.node_statuses
|
|
79
|
+
),
|
|
80
|
+
final_status=run.final_status, # type: ignore[arg-type]
|
|
81
|
+
failure_reason=run.failure_reason,
|
|
82
|
+
started_at=run.started_at,
|
|
83
|
+
ended_at=run.ended_at,
|
|
84
|
+
tokens_used=run.tokens_used,
|
|
85
|
+
cost_usd=run.cost_usd,
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _state_snapshot_from_orm(snapshot: StateSnapshotORM) -> StateSnapshot:
|
|
90
|
+
return StateSnapshot(
|
|
91
|
+
id=snapshot.id,
|
|
92
|
+
run_id=snapshot.run_id,
|
|
93
|
+
node_id=snapshot.node_id,
|
|
94
|
+
timestamp=snapshot.timestamp,
|
|
95
|
+
state=PipelineState.model_validate(snapshot.state),
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _node_log_from_orm(log: NodeExecutionLogORM) -> NodeExecutionLog:
|
|
100
|
+
return NodeExecutionLog(
|
|
101
|
+
id=log.id,
|
|
102
|
+
run_id=log.run_id,
|
|
103
|
+
node_id=log.node_id,
|
|
104
|
+
agent_id=log.agent_id,
|
|
105
|
+
runtime_id=log.runtime_id,
|
|
106
|
+
started_at=log.started_at,
|
|
107
|
+
ended_at=log.ended_at,
|
|
108
|
+
prompt_xml=log.prompt_xml,
|
|
109
|
+
stdout=log.stdout,
|
|
110
|
+
stderr=log.stderr,
|
|
111
|
+
output_json=log.output_json,
|
|
112
|
+
tokens_used=log.tokens_used,
|
|
113
|
+
cost_usd=log.cost_usd,
|
|
114
|
+
duration_ms=log.duration_ms,
|
|
115
|
+
status=log.status, # type: ignore[arg-type]
|
|
116
|
+
error_message=log.error_message,
|
|
117
|
+
extra_data=log.extra_data,
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def list_runs(
|
|
122
|
+
session: Session,
|
|
123
|
+
*,
|
|
124
|
+
actor_id: uuid.UUID,
|
|
125
|
+
is_admin: bool,
|
|
126
|
+
pipeline_id: str | None = None,
|
|
127
|
+
final_status: str | None = None,
|
|
128
|
+
project_id: str | None = None,
|
|
129
|
+
only_unscoped: bool = False,
|
|
130
|
+
offset: int = 0,
|
|
131
|
+
limit: int = 50,
|
|
132
|
+
) -> tuple[Sequence[Run], int]:
|
|
133
|
+
"""List runs with optional filters; non-admins only see their own.
|
|
134
|
+
|
|
135
|
+
``project_id``: filter to a specific project's runs.
|
|
136
|
+
``only_unscoped``: when True, return only runs without a project
|
|
137
|
+
(ad-hoc / legacy). Mutually exclusive with ``project_id``; the
|
|
138
|
+
router enforces the mapping from query string to one of these.
|
|
139
|
+
"""
|
|
140
|
+
where_clauses: list[ColumnElement[bool]] = []
|
|
141
|
+
where_clauses.extend(_ownership_filter(actor_id, is_admin))
|
|
142
|
+
if pipeline_id is not None:
|
|
143
|
+
where_clauses.append(RunORM.pipeline_id == pipeline_id)
|
|
144
|
+
if final_status is not None:
|
|
145
|
+
where_clauses.append(RunORM.final_status == final_status)
|
|
146
|
+
if only_unscoped:
|
|
147
|
+
where_clauses.append(RunORM.project_id.is_(None))
|
|
148
|
+
elif project_id is not None:
|
|
149
|
+
where_clauses.append(RunORM.project_id == project_id)
|
|
150
|
+
|
|
151
|
+
total = session.scalar(select(func.count()).select_from(RunORM).where(*where_clauses)) or 0
|
|
152
|
+
|
|
153
|
+
runs_orm = session.scalars(
|
|
154
|
+
select(RunORM)
|
|
155
|
+
.where(*where_clauses)
|
|
156
|
+
.order_by(RunORM.started_at.desc())
|
|
157
|
+
.offset(offset)
|
|
158
|
+
.limit(limit)
|
|
159
|
+
).all()
|
|
160
|
+
return [_run_from_orm(r) for r in runs_orm], total
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def get_run(
|
|
164
|
+
session: Session,
|
|
165
|
+
run_id: str,
|
|
166
|
+
*,
|
|
167
|
+
actor_id: uuid.UUID,
|
|
168
|
+
is_admin: bool,
|
|
169
|
+
) -> Run:
|
|
170
|
+
run = session.get(RunORM, run_id)
|
|
171
|
+
if run is None:
|
|
172
|
+
raise NotFoundError(f"Run not found: {run_id}")
|
|
173
|
+
if not is_admin and run.user_id != actor_id:
|
|
174
|
+
# Anti-enumeration: cross-user lookup looks indistinguishable
|
|
175
|
+
# from "doesn't exist".
|
|
176
|
+
raise NotFoundError(f"Run not found: {run_id}")
|
|
177
|
+
# Populate node_statuses from execution logs on every detail fetch (#233).
|
|
178
|
+
#
|
|
179
|
+
# The runs.node_statuses column is only ever written at row creation
|
|
180
|
+
# (initialised to {} by create_run) — no runner path writes back to
|
|
181
|
+
# it. Per-node status truth lives in node_execution_logs instead, so
|
|
182
|
+
# we join that table here to derive an up-to-date dict for the
|
|
183
|
+
# detail view. list_runs intentionally skips this join: the per-run
|
|
184
|
+
# overhead is too expensive for bulk queries and node-level detail
|
|
185
|
+
# isn't shown in the list view anyway.
|
|
186
|
+
logs = session.scalars(
|
|
187
|
+
select(NodeExecutionLogORM)
|
|
188
|
+
.where(NodeExecutionLogORM.run_id == run_id)
|
|
189
|
+
.order_by(NodeExecutionLogORM.started_at)
|
|
190
|
+
).all()
|
|
191
|
+
# Compute into a local dict — do NOT mutate run.node_statuses.
|
|
192
|
+
# The session is committed on success in get_session() so any ORM
|
|
193
|
+
# attribute write would turn this read endpoint into a DB write,
|
|
194
|
+
# causing unexpected churn during polling.
|
|
195
|
+
node_statuses_override = {log.node_id: log.status for log in logs} if logs else None
|
|
196
|
+
return _run_from_orm(run, node_statuses_override=node_statuses_override)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def get_run_state(
|
|
200
|
+
session: Session,
|
|
201
|
+
run_id: str,
|
|
202
|
+
*,
|
|
203
|
+
actor_id: uuid.UUID,
|
|
204
|
+
is_admin: bool,
|
|
205
|
+
) -> PipelineState:
|
|
206
|
+
"""Return the latest state snapshot, or initial_state if no snapshots yet."""
|
|
207
|
+
run = session.get(RunORM, run_id)
|
|
208
|
+
if run is None:
|
|
209
|
+
raise NotFoundError(f"Run not found: {run_id}")
|
|
210
|
+
if not is_admin and run.user_id != actor_id:
|
|
211
|
+
raise NotFoundError(f"Run not found: {run_id}")
|
|
212
|
+
|
|
213
|
+
latest = session.scalar(
|
|
214
|
+
select(StateSnapshotORM)
|
|
215
|
+
.where(StateSnapshotORM.run_id == run_id)
|
|
216
|
+
.order_by(StateSnapshotORM.timestamp.desc())
|
|
217
|
+
.limit(1)
|
|
218
|
+
)
|
|
219
|
+
if latest is None:
|
|
220
|
+
return PipelineState.model_validate(run.initial_state)
|
|
221
|
+
return PipelineState.model_validate(latest.state)
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def list_run_state_history(
|
|
225
|
+
session: Session,
|
|
226
|
+
run_id: str,
|
|
227
|
+
*,
|
|
228
|
+
actor_id: uuid.UUID,
|
|
229
|
+
is_admin: bool,
|
|
230
|
+
) -> list[StateSnapshot]:
|
|
231
|
+
run = session.get(RunORM, run_id)
|
|
232
|
+
if run is None:
|
|
233
|
+
raise NotFoundError(f"Run not found: {run_id}")
|
|
234
|
+
if not is_admin and run.user_id != actor_id:
|
|
235
|
+
raise NotFoundError(f"Run not found: {run_id}")
|
|
236
|
+
snapshots = session.scalars(
|
|
237
|
+
select(StateSnapshotORM)
|
|
238
|
+
.where(StateSnapshotORM.run_id == run_id)
|
|
239
|
+
.order_by(StateSnapshotORM.timestamp)
|
|
240
|
+
).all()
|
|
241
|
+
return [_state_snapshot_from_orm(s) for s in snapshots]
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def create_run(
|
|
245
|
+
session: Session,
|
|
246
|
+
*,
|
|
247
|
+
user_id: uuid.UUID,
|
|
248
|
+
pipeline_id: str,
|
|
249
|
+
pipeline_version: int,
|
|
250
|
+
trigger_source: str,
|
|
251
|
+
initial_state: PipelineState,
|
|
252
|
+
project_id: str | None = None,
|
|
253
|
+
) -> RunORM:
|
|
254
|
+
"""Insert a Run row in 'running' state. Caller commits.
|
|
255
|
+
|
|
256
|
+
The acting ``user_id`` is required; routes resolve it from the
|
|
257
|
+
authenticated request, tests pass an explicit owner. Writes a
|
|
258
|
+
``run.triggered`` audit row.
|
|
259
|
+
"""
|
|
260
|
+
now = _now()
|
|
261
|
+
run = RunORM(
|
|
262
|
+
id=_new_id(),
|
|
263
|
+
user_id=user_id,
|
|
264
|
+
project_id=project_id,
|
|
265
|
+
pipeline_id=pipeline_id,
|
|
266
|
+
pipeline_version=pipeline_version,
|
|
267
|
+
trigger_source=trigger_source,
|
|
268
|
+
initial_state=initial_state.model_dump(mode="json"),
|
|
269
|
+
current_node=None,
|
|
270
|
+
node_statuses={},
|
|
271
|
+
final_status="running",
|
|
272
|
+
started_at=now,
|
|
273
|
+
ended_at=None,
|
|
274
|
+
tokens_used=0,
|
|
275
|
+
cost_usd=0.0,
|
|
276
|
+
)
|
|
277
|
+
session.add(run)
|
|
278
|
+
session.flush()
|
|
279
|
+
record_audit_event(
|
|
280
|
+
session,
|
|
281
|
+
user_id=user_id,
|
|
282
|
+
event_type="run.triggered",
|
|
283
|
+
event_data={
|
|
284
|
+
"run_id": run.id,
|
|
285
|
+
"pipeline_id": pipeline_id,
|
|
286
|
+
"pipeline_version": pipeline_version,
|
|
287
|
+
"project_id": project_id,
|
|
288
|
+
"trigger_source": trigger_source,
|
|
289
|
+
},
|
|
290
|
+
)
|
|
291
|
+
return run
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def _compute_run_totals(session: Session, run_id: str) -> tuple[int, float]:
|
|
295
|
+
"""Sum ``tokens_used`` + ``cost_usd`` from a run's node-execution logs.
|
|
296
|
+
|
|
297
|
+
Uses SQL aggregation so we don't materialise every log row in memory —
|
|
298
|
+
runs with many nodes can have a lot of logs. Returns ``(tokens, cost)``.
|
|
299
|
+
"""
|
|
300
|
+
totals = session.execute(
|
|
301
|
+
select(
|
|
302
|
+
func.coalesce(func.sum(NodeExecutionLogORM.tokens_used), 0),
|
|
303
|
+
func.coalesce(func.sum(NodeExecutionLogORM.cost_usd), 0.0),
|
|
304
|
+
).where(NodeExecutionLogORM.run_id == run_id)
|
|
305
|
+
).one()
|
|
306
|
+
return int(totals[0]), float(totals[1])
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def finalize_run(
|
|
310
|
+
session: Session,
|
|
311
|
+
run_id: str,
|
|
312
|
+
*,
|
|
313
|
+
final_status: str,
|
|
314
|
+
) -> None:
|
|
315
|
+
"""Mark a run as completed (success/failed/aborted) and aggregate metrics.
|
|
316
|
+
|
|
317
|
+
Idempotent and race-safe (#257): the status transition is an atomic
|
|
318
|
+
``UPDATE ... WHERE final_status NOT IN <terminal>`` and the rowcount
|
|
319
|
+
decides whether the caller won the claim. A late finaliser whose
|
|
320
|
+
session still holds a stale ``"running"`` cached ORM instance will
|
|
321
|
+
see ``rowcount=0`` because the predicate runs at the database, not
|
|
322
|
+
against the session's identity map — first writer wins.
|
|
323
|
+
|
|
324
|
+
Cancel-during-runner-error scenario: the inner ``except RunnerError``
|
|
325
|
+
commits ``finalize_run("failed")`` and the outer ``except
|
|
326
|
+
CancelledError`` handler then calls ``finalize_run("aborted")`` from
|
|
327
|
+
a fresh session; the second call no-ops.
|
|
328
|
+
"""
|
|
329
|
+
tokens, cost = _compute_run_totals(session, run_id)
|
|
330
|
+
stmt = (
|
|
331
|
+
update(RunORM)
|
|
332
|
+
.where(
|
|
333
|
+
RunORM.id == run_id,
|
|
334
|
+
RunORM.final_status.notin_(_TERMINAL_STATUSES),
|
|
335
|
+
)
|
|
336
|
+
.values(
|
|
337
|
+
final_status=final_status,
|
|
338
|
+
ended_at=_now(),
|
|
339
|
+
tokens_used=tokens,
|
|
340
|
+
cost_usd=cost,
|
|
341
|
+
)
|
|
342
|
+
)
|
|
343
|
+
result = session.execute(stmt)
|
|
344
|
+
# ``CursorResult.rowcount`` exposed only at runtime; static type is
|
|
345
|
+
# ``Result[Any]`` which doesn't have it — same pattern as
|
|
346
|
+
# ``try_claim_resume`` below.
|
|
347
|
+
if result.rowcount == 0: # type: ignore[attr-defined]
|
|
348
|
+
# Either the run doesn't exist or it's already terminal —
|
|
349
|
+
# distinguish for the caller. NotFoundError is a programmer
|
|
350
|
+
# error; the no-op return is the expected race outcome.
|
|
351
|
+
if session.get(RunORM, run_id) is None:
|
|
352
|
+
raise NotFoundError(f"Run not found: {run_id}")
|
|
353
|
+
return
|
|
354
|
+
session.flush()
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
def pause_run(session: Session, run_id: str) -> None:
|
|
358
|
+
"""Mark a run as paused without setting ended_at (resumable).
|
|
359
|
+
|
|
360
|
+
Idempotent and race-safe (#257), same atomic-UPDATE pattern as
|
|
361
|
+
``finalize_run``. A late pause attempt on an already-terminal run
|
|
362
|
+
no-ops at the database level so it can't reset ``ended_at`` to
|
|
363
|
+
``None`` and erase the recorded outcome.
|
|
364
|
+
"""
|
|
365
|
+
tokens, cost = _compute_run_totals(session, run_id)
|
|
366
|
+
stmt = (
|
|
367
|
+
update(RunORM)
|
|
368
|
+
.where(
|
|
369
|
+
RunORM.id == run_id,
|
|
370
|
+
RunORM.final_status.notin_(_TERMINAL_STATUSES),
|
|
371
|
+
)
|
|
372
|
+
.values(
|
|
373
|
+
final_status="paused",
|
|
374
|
+
tokens_used=tokens,
|
|
375
|
+
cost_usd=cost,
|
|
376
|
+
)
|
|
377
|
+
)
|
|
378
|
+
result = session.execute(stmt)
|
|
379
|
+
if result.rowcount == 0: # type: ignore[attr-defined]
|
|
380
|
+
if session.get(RunORM, run_id) is None:
|
|
381
|
+
raise NotFoundError(f"Run not found: {run_id}")
|
|
382
|
+
return
|
|
383
|
+
session.flush()
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
def try_claim_resume(session: Session, run_id: str) -> bool:
|
|
387
|
+
"""Atomically transition a paused run to running. Returns True on success.
|
|
388
|
+
|
|
389
|
+
Used by ``/runs/{id}/resume`` and ``/runs/{id}/nodes/{n}/approve`` to
|
|
390
|
+
prevent the TOCTOU race where two concurrent requests both pass a
|
|
391
|
+
Python-side ``final_status == "paused"`` check, both spawn background
|
|
392
|
+
tasks, and the second ``run_registry.register`` raises with an orphan
|
|
393
|
+
asyncio.Task already in flight. (#185)
|
|
394
|
+
|
|
395
|
+
Returns ``False`` if no row matched — either the run id doesn't exist or
|
|
396
|
+
its ``final_status`` is no longer ``"paused"`` (a concurrent caller won
|
|
397
|
+
the claim, or the run was finalized between request validation and here).
|
|
398
|
+
The caller distinguishes those cases with a separate existence check
|
|
399
|
+
when it matters; for the resume path, both produce a 409 response.
|
|
400
|
+
"""
|
|
401
|
+
stmt = (
|
|
402
|
+
update(RunORM)
|
|
403
|
+
.where(RunORM.id == run_id, RunORM.final_status == "paused")
|
|
404
|
+
.values(final_status="running", ended_at=None, failure_reason=None)
|
|
405
|
+
)
|
|
406
|
+
# session.execute(update(...)) returns CursorResult at runtime — only
|
|
407
|
+
# CursorResult exposes .rowcount, which the static Result[Any] type does not.
|
|
408
|
+
result = session.execute(stmt)
|
|
409
|
+
return bool(result.rowcount == 1) # type: ignore[attr-defined]
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
def try_claim_revive(session: Session, run_id: str) -> bool:
|
|
413
|
+
"""Atomically transition a paused-or-failed run to running. Returns True on success.
|
|
414
|
+
|
|
415
|
+
Used by ``/runs/{id}/nodes/{n}/retry`` and ``.../skip`` — same TOCTOU
|
|
416
|
+
safety as ``try_claim_resume`` (#185), but accepts ``failed`` as a
|
|
417
|
+
starting state so a node-level intervention can put a terminated run
|
|
418
|
+
back into motion.
|
|
419
|
+
|
|
420
|
+
Clears ``failure_reason`` (#260): a revived run has left the failed
|
|
421
|
+
state, so a stale "engine restarted mid-run" diagnostic from the
|
|
422
|
+
previous lifecycle should not stay attached.
|
|
423
|
+
"""
|
|
424
|
+
stmt = (
|
|
425
|
+
update(RunORM)
|
|
426
|
+
.where(RunORM.id == run_id, RunORM.final_status.in_(("paused", "failed")))
|
|
427
|
+
.values(final_status="running", ended_at=None, failure_reason=None)
|
|
428
|
+
)
|
|
429
|
+
# session.execute(update(...)) returns CursorResult at runtime — only
|
|
430
|
+
# CursorResult exposes .rowcount, which the static Result[Any] type does not.
|
|
431
|
+
result = session.execute(stmt)
|
|
432
|
+
return bool(result.rowcount == 1) # type: ignore[attr-defined]
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
def mark_stale_running_runs_as_failed(session: Session, *, reason: str) -> int:
|
|
436
|
+
"""Find Run rows still in 'running' state and mark them as failed.
|
|
437
|
+
|
|
438
|
+
Called on engine startup to clean up orphans left by crashes / kills.
|
|
439
|
+
Returns the count of runs updated. The diagnostic ``reason`` lands
|
|
440
|
+
in ``runs.failure_reason`` (#260) — earlier code wrote a synthetic
|
|
441
|
+
snapshot with ``node_id="__shutdown__"`` and a ``verification_reason``
|
|
442
|
+
state field, which polluted ``get_run_state_history`` consumers
|
|
443
|
+
that scanned for real node ids.
|
|
444
|
+
"""
|
|
445
|
+
runs = session.scalars(
|
|
446
|
+
select(RunORM).where(RunORM.final_status == "running"),
|
|
447
|
+
).all()
|
|
448
|
+
count = 0
|
|
449
|
+
now = _now()
|
|
450
|
+
for run in runs:
|
|
451
|
+
run.final_status = "failed"
|
|
452
|
+
run.ended_at = now
|
|
453
|
+
run.failure_reason = reason
|
|
454
|
+
count += 1
|
|
455
|
+
session.flush()
|
|
456
|
+
return count
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
def get_run_node_log(
|
|
460
|
+
session: Session,
|
|
461
|
+
run_id: str,
|
|
462
|
+
node_id: str,
|
|
463
|
+
*,
|
|
464
|
+
actor_id: uuid.UUID,
|
|
465
|
+
is_admin: bool,
|
|
466
|
+
) -> NodeExecutionLog:
|
|
467
|
+
run = session.get(RunORM, run_id)
|
|
468
|
+
if run is None:
|
|
469
|
+
raise NotFoundError(f"Run not found: {run_id}")
|
|
470
|
+
if not is_admin and run.user_id != actor_id:
|
|
471
|
+
raise NotFoundError(f"Run not found: {run_id}")
|
|
472
|
+
|
|
473
|
+
log = session.scalar(
|
|
474
|
+
select(NodeExecutionLogORM)
|
|
475
|
+
.where(NodeExecutionLogORM.run_id == run_id)
|
|
476
|
+
.where(NodeExecutionLogORM.node_id == node_id)
|
|
477
|
+
.order_by(NodeExecutionLogORM.started_at.desc())
|
|
478
|
+
.limit(1)
|
|
479
|
+
)
|
|
480
|
+
if log is None:
|
|
481
|
+
raise NotFoundError(f"Node log not found: {run_id}/{node_id}")
|
|
482
|
+
return _node_log_from_orm(log)
|
dap_engine/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: dap-engine
|
|
3
|
+
Version: 0.3.0
|
|
4
|
+
Summary: DAP engine — FastAPI + LangGraph + SQLAlchemy + SQLite / PostgreSQL
|
|
5
|
+
Requires-Python: >=3.13
|
|
6
|
+
Requires-Dist: alembic>=1.13.3
|
|
7
|
+
Requires-Dist: anyio>=4.6.0
|
|
8
|
+
Requires-Dist: dap-prompt-dsl
|
|
9
|
+
Requires-Dist: dap-runtimes
|
|
10
|
+
Requires-Dist: dap-schemas
|
|
11
|
+
Requires-Dist: fastapi-users[oauth,sqlalchemy]>=15.0.5
|
|
12
|
+
Requires-Dist: fastapi>=0.115.0
|
|
13
|
+
Requires-Dist: langgraph-checkpoint-postgres>=2.0
|
|
14
|
+
Requires-Dist: langgraph-checkpoint-sqlite>=2.0.0
|
|
15
|
+
Requires-Dist: langgraph>=0.2.50
|
|
16
|
+
Requires-Dist: psycopg[binary,pool]>=3.2
|
|
17
|
+
Requires-Dist: pydantic>=2.9.2
|
|
18
|
+
Requires-Dist: sqlalchemy>=2.0.36
|
|
19
|
+
Requires-Dist: uvicorn[standard]>=0.32.0
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
|
|
22
|
+
# dap-engine
|
|
23
|
+
|
|
24
|
+
FastAPI + SQLAlchemy 2.0 + SQLite (WAL mode). LangGraph integration w F5.
|
|
25
|
+
|
|
26
|
+
## Endpoints (F0)
|
|
27
|
+
|
|
28
|
+
```
|
|
29
|
+
GET /health → service status
|
|
30
|
+
GET /runtimes → list of registered adapters
|
|
31
|
+
GET /runtimes/{id}/health → per-adapter healthcheck
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Run standalone
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
uv run dap-engine
|
|
38
|
+
# default: 127.0.0.1:7333, db: ./.dap/state.db
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Migrations
|
|
42
|
+
|
|
43
|
+
W F0 schema jest tworzona automatycznie przy starcie engine'u przez
|
|
44
|
+
`Base.metadata.create_all(engine)` (dev mode).
|
|
45
|
+
|
|
46
|
+
Pełne Alembic-based migrations są **planowane na późniejszą iterację**. Repo nie
|
|
47
|
+
zawiera jeszcze scaffoldu Alembic (`alembic.ini`, `alembic/env.py`), więc
|
|
48
|
+
komendy `alembic revision` / `alembic upgrade` nie będą działać dopóki ten
|
|
49
|
+
config nie zostanie dodany.
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
dap_engine/__init__.py,sha256=sccxZFin4GFIE77mvkQ-D-Vz1iAUwMWZu82F1_2bSfU,64
|
|
2
|
+
dap_engine/__main__.py,sha256=ffy3Sm6gjXRsPtsHZhijsXvijAxFj72ed32bh-Azla8,3662
|
|
3
|
+
dap_engine/app.py,sha256=wZTJAhXLK4MtPqtz7fNV-EyuiMUzRsLSkls8-muofz8,19682
|
|
4
|
+
dap_engine/contracts.py,sha256=S9XXyjBUz-30-WMeO6IHPv5jqQ4bKSh1eBvay7QbM9Y,7034
|
|
5
|
+
dap_engine/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
+
dap_engine/api/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
7
|
+
dap_engine/api/agents.py,sha256=-NlQrg-veJc9uPCBLWY7-PG6hx5PAM-FabgDQkiWd6s,20124
|
|
8
|
+
dap_engine/api/deps.py,sha256=qft_Kn3Y9vAbUoqbReq-Soj1p7VAEK82zMe2pVCRwvU,1956
|
|
9
|
+
dap_engine/api/health.py,sha256=Cyf83qze-fKCjdvq17s3na0tmiYAA7weSpSjs2cqGa4,492
|
|
10
|
+
dap_engine/api/pipelines.py,sha256=ylogPqcNC7wJN3G3wwW3X3AEQ4lu7n4pyc8_O19Uvcg,17415
|
|
11
|
+
dap_engine/api/projects.py,sha256=Z1l-U2J2e21KBOC5nxplYxqe4UwZ6Ki1FOD_kWZf5Ek,6990
|
|
12
|
+
dap_engine/api/runs.py,sha256=o3gkYDdc7DBeeulgFBSRqPqmErf9TAOLE07m8osImqc,27292
|
|
13
|
+
dap_engine/api/runtimes.py,sha256=pQpgQZ1-csNosJ04STbIgc7v0Ca_6gviRrQaJjDxQUk,897
|
|
14
|
+
dap_engine/api/schemas.py,sha256=EEIWcbz76DyXikWzvuE1r1iiKdgaat7NUT5hMXCjM_E,11777
|
|
15
|
+
dap_engine/api/settings.py,sha256=doefsj0FG-zKfnNF2H358xMLsgh4rGclQKvWDGb_F5A,10785
|
|
16
|
+
dap_engine/auth/__init__.py,sha256=uTD29R6WlhC3Iz_gAT2Zfe9YE3GfMc94z09IJ7Lry3A,842
|
|
17
|
+
dap_engine/auth/admin_users_routes.py,sha256=sO7dt9HeNaq7VF6KRPna6IcodW0QnQzjuH3uFuXJu6Q,4339
|
|
18
|
+
dap_engine/auth/api_token_routes.py,sha256=55g_GCCaQLhl3ggwEqoGfrEjMHsXsh4yqhOswEd4yW4,11748
|
|
19
|
+
dap_engine/auth/api_tokens.py,sha256=Wba1a34IyGyAoPW0Sg8_A7RI4nOnWPWSMmQzeLCnVSs,5768
|
|
20
|
+
dap_engine/auth/audit.py,sha256=u4hvTBI1iKWURtd631aJPatLrxJp1qS2eozTPkN8aQM,3114
|
|
21
|
+
dap_engine/auth/audit_routes.py,sha256=-57PoTf0lCxhUmz_8XhGlVVgCFT5lGTMCi5PVF1ccmA,3765
|
|
22
|
+
dap_engine/auth/db.py,sha256=HWN_T6844C_Jv-c3ubfDdSOj5ri3elAdAev5TClvXbo,5144
|
|
23
|
+
dap_engine/auth/oauth.py,sha256=phKOYWu8qwxKzxBb3cGXiBkYVU_ztpZtCyMehjdD4Uw,1675
|
|
24
|
+
dap_engine/auth/policies.py,sha256=VbWDCAzOyqzIvm9tZwgwvMSJMkZ63ftpqDEdpsO1_T0,2162
|
|
25
|
+
dap_engine/auth/schemas.py,sha256=juhGPc6lSUZfaPAFTBe3306dnldFFc-Qg4YxZSKDBjI,1279
|
|
26
|
+
dap_engine/auth/users.py,sha256=6sIMznFjZinpgm10G5tXgo6IDUmq8-E-M4_MtdIjMck,15010
|
|
27
|
+
dap_engine/execution/__init__.py,sha256=yZ94gqQ5AIUBNXdD1A5O6jcHfDJQ2l_LUQwrUUCI6w4,793
|
|
28
|
+
dap_engine/execution/conditions.py,sha256=1yKq55UY8sSF4rLZnvOXspDe5Jq-G9vxSKW2s6LjZZI,2630
|
|
29
|
+
dap_engine/execution/node_executor.py,sha256=zR-aWh5WtBYXpzQ5h1otaaiiOXCu5eBMXFKNs3cEc2Y,13963
|
|
30
|
+
dap_engine/execution/output_parser.py,sha256=tl8Z97Dtu_FGlZ183d20DuRC-MzwcUgvCrKhf6gBn_g,5817
|
|
31
|
+
dap_engine/execution/run_orchestrator.py,sha256=JyvoSnpZ_K5XTq9x209StMRAJT8ojN2RRcOY8tT31Rs,8437
|
|
32
|
+
dap_engine/execution/run_registry.py,sha256=o1QAVcdp4xw5DhjoxMpgN2KtsiVG88hVJWRm_lyv50E,6238
|
|
33
|
+
dap_engine/execution/runner.py,sha256=lk7LfqSqVOccjV_OD0SF_HueEYpDNe4AWeVQnDG7WRE,16717
|
|
34
|
+
dap_engine/execution/validator.py,sha256=UrYXFcKyeXnO7t69iOQU3oCJShJsewreKDuUrmuH0R4,21749
|
|
35
|
+
dap_engine/persistence/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
36
|
+
dap_engine/persistence/_common.py,sha256=DIePb9m8K3n5VrCIByiAul4Zh3bF675rAmdTEG-qb7g,562
|
|
37
|
+
dap_engine/persistence/agents.py,sha256=lSvyBbxrKZCe9lJhGmwl2gItgW3ZXHtjOV54XfnI3I4,13950
|
|
38
|
+
dap_engine/persistence/db.py,sha256=UigwYofxRyecMlXIv7cUokbD_n6qeHUNfSVvDsaVKLU,6684
|
|
39
|
+
dap_engine/persistence/migrations.py,sha256=NOOQULQfVFuYc5NwlzHCBI_dLiH4z8MRN-YO--1sqbw,30611
|
|
40
|
+
dap_engine/persistence/models.py,sha256=psWLctP98pR0Il-Pry5Uf_7cdNwupgm-UtJFLcKFAE8,26333
|
|
41
|
+
dap_engine/persistence/pipelines.py,sha256=lL_w_UQByezjHTOa3NG8JKlOr17J6Og9xtB_vg_HHT4,11363
|
|
42
|
+
dap_engine/persistence/projects.py,sha256=dK1V3zUOn1-1y3hyvR_awDCai98MhpH4ucbL3YPlEVA,8886
|
|
43
|
+
dap_engine/persistence/repository.py,sha256=ghdl8NYk8Jktq59-7sphwSmoTEXqSR7cpx7oWCp998Q,2456
|
|
44
|
+
dap_engine/persistence/runs.py,sha256=Tax7xDrn8SXBTZNoqd0wT9jEDhNBI2oK_G1g6BonW34,17038
|
|
45
|
+
dap_engine-0.3.0.dist-info/METADATA,sha256=iRk1a9B2MmudjSuH6-DtW8u2WlEDRZDg5tpxGYIJu3I,1505
|
|
46
|
+
dap_engine-0.3.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
|
|
47
|
+
dap_engine-0.3.0.dist-info/entry_points.txt,sha256=Z_r2R-gYIyNjhFXosA-Sv2OnfPU-19bSyeLeLI4uWU4,56
|
|
48
|
+
dap_engine-0.3.0.dist-info/RECORD,,
|