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.
Files changed (48) hide show
  1. dap_engine/__init__.py +3 -0
  2. dap_engine/__main__.py +80 -0
  3. dap_engine/api/__init__.py +0 -0
  4. dap_engine/api/agents.py +546 -0
  5. dap_engine/api/deps.py +60 -0
  6. dap_engine/api/health.py +20 -0
  7. dap_engine/api/pipelines.py +428 -0
  8. dap_engine/api/projects.py +191 -0
  9. dap_engine/api/runs.py +694 -0
  10. dap_engine/api/runtimes.py +29 -0
  11. dap_engine/api/schemas.py +331 -0
  12. dap_engine/api/settings.py +288 -0
  13. dap_engine/app.py +438 -0
  14. dap_engine/auth/__init__.py +23 -0
  15. dap_engine/auth/admin_users_routes.py +134 -0
  16. dap_engine/auth/api_token_routes.py +345 -0
  17. dap_engine/auth/api_tokens.py +147 -0
  18. dap_engine/auth/audit.py +91 -0
  19. dap_engine/auth/audit_routes.py +125 -0
  20. dap_engine/auth/db.py +135 -0
  21. dap_engine/auth/oauth.py +41 -0
  22. dap_engine/auth/policies.py +64 -0
  23. dap_engine/auth/schemas.py +37 -0
  24. dap_engine/auth/users.py +400 -0
  25. dap_engine/contracts.py +205 -0
  26. dap_engine/execution/__init__.py +30 -0
  27. dap_engine/execution/conditions.py +87 -0
  28. dap_engine/execution/node_executor.py +363 -0
  29. dap_engine/execution/output_parser.py +162 -0
  30. dap_engine/execution/run_orchestrator.py +213 -0
  31. dap_engine/execution/run_registry.py +158 -0
  32. dap_engine/execution/runner.py +422 -0
  33. dap_engine/execution/validator.py +580 -0
  34. dap_engine/persistence/__init__.py +0 -0
  35. dap_engine/persistence/_common.py +24 -0
  36. dap_engine/persistence/agents.py +410 -0
  37. dap_engine/persistence/db.py +179 -0
  38. dap_engine/persistence/migrations.py +739 -0
  39. dap_engine/persistence/models.py +569 -0
  40. dap_engine/persistence/pipelines.py +328 -0
  41. dap_engine/persistence/projects.py +256 -0
  42. dap_engine/persistence/repository.py +101 -0
  43. dap_engine/persistence/runs.py +482 -0
  44. dap_engine/py.typed +0 -0
  45. dap_engine-0.3.0.dist-info/METADATA +49 -0
  46. dap_engine-0.3.0.dist-info/RECORD +48 -0
  47. dap_engine-0.3.0.dist-info/WHEEL +4 -0
  48. dap_engine-0.3.0.dist-info/entry_points.txt +2 -0
dap_engine/api/runs.py ADDED
@@ -0,0 +1,694 @@
1
+ """REST endpoints for runs.
2
+
3
+ POST /runs (F5+) triggers asynchronous pipeline execution via LangGraph.
4
+ Returns 201 with Run immediately; pipeline runs in a background asyncio.Task
5
+ tracked by the engine's RunRegistry. Use POST /runs/{id}/abort to cancel,
6
+ POST /runs/{id}/pause to suspend (LangGraph checkpoint preserved),
7
+ POST /runs/{id}/resume to continue from the last checkpoint, and
8
+ POST /runs/{id}/nodes/{node_id}/retry|skip to recover from a per-node
9
+ failure on a paused or failed run.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import asyncio
15
+ import logging
16
+ from typing import Any
17
+
18
+ from dap_runtimes import RuntimeRegistry
19
+ from dap_types import NodeExecutionLog, PipelineDefaults, PipelineState, Run, StateSnapshot
20
+ from fastapi import APIRouter, Depends, HTTPException, Query, status
21
+ from langgraph.checkpoint.base import BaseCheckpointSaver
22
+ from pydantic import ValidationError
23
+ from sqlalchemy import select
24
+ from sqlalchemy.orm import Session, sessionmaker
25
+
26
+ from dap_engine.api.deps import (
27
+ get_checkpointer,
28
+ get_registry,
29
+ get_run_registry,
30
+ get_session,
31
+ get_session_factory,
32
+ )
33
+ from dap_engine.auth.users import current_active_user
34
+ from dap_engine.contracts import RunCreateRequest
35
+ from dap_engine.execution import (
36
+ REWIND_RETRY,
37
+ REWIND_SKIP,
38
+ RunRegistry,
39
+ execute_rewind_background,
40
+ execute_run_background,
41
+ )
42
+ from dap_engine.persistence import repository as repo
43
+ from dap_engine.persistence.models import PipelineVersionORM, UserORM
44
+
45
+ logger = logging.getLogger("dap.engine.api.runs")
46
+
47
+ router = APIRouter(prefix="/runs", tags=["runs"])
48
+
49
+
50
+ @router.post("", status_code=status.HTTP_201_CREATED, response_model=Run)
51
+ async def trigger_run(
52
+ payload: RunCreateRequest,
53
+ session: Session = Depends(get_session),
54
+ registry: RuntimeRegistry = Depends(get_registry),
55
+ run_registry: RunRegistry = Depends(get_run_registry),
56
+ session_factory: sessionmaker[Session] = Depends(get_session_factory),
57
+ checkpointer: BaseCheckpointSaver[Any] = Depends(get_checkpointer),
58
+ user: UserORM = Depends(current_active_user),
59
+ ) -> Run:
60
+ """Trigger asynchronous pipeline execution.
61
+
62
+ Returns immediately with the Run row in `running` state. The actual
63
+ execution happens in a background asyncio.Task. Poll the GET endpoints
64
+ for progress, or POST /runs/{id}/abort to cancel.
65
+
66
+ Ownership: the caller must own the referenced pipeline (and project,
67
+ when set). Both gates surface a 404 / 422 with anti-enumeration
68
+ wording — a foreign pipeline_id looks exactly like a missing id.
69
+ The new run row is stamped with the acting ``user_id``.
70
+ """
71
+ try:
72
+ pipeline = repo.get_pipeline(
73
+ session, payload.pipeline_id, actor_id=user.id, is_admin=user.is_superuser
74
+ )
75
+ except repo.NotFoundError as exc:
76
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
77
+ if not pipeline.is_active:
78
+ # Archived pipeline — 404, same wording as "doesn't exist", so a
79
+ # caller can't tell archived apart from missing.
80
+ raise HTTPException(
81
+ status_code=status.HTTP_404_NOT_FOUND,
82
+ detail=f"Pipeline not found: {payload.pipeline_id}",
83
+ )
84
+
85
+ # When a project is bound, it must exist (and be owned by the caller)
86
+ # and be active. Archived projects fail loudly here so users notice
87
+ # instead of getting a half-stamped run that the dashboard can't
88
+ # group cleanly.
89
+ project = None
90
+ if payload.project_id is not None:
91
+ try:
92
+ project = repo.get_project(
93
+ session, payload.project_id, actor_id=user.id, is_admin=user.is_superuser
94
+ )
95
+ except repo.NotFoundError as exc:
96
+ raise HTTPException(
97
+ status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
98
+ detail=str(exc),
99
+ ) from exc
100
+ if project.archived_at is not None:
101
+ raise HTTPException(
102
+ status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
103
+ detail=f"Project is archived: {payload.project_id}",
104
+ )
105
+
106
+ # ``is not None`` rather than ``or`` — the latter coerces ``0`` to
107
+ # the current version, but ``0`` is a malformed user-supplied
108
+ # version we want to surface as 404 below, not silently rewrite.
109
+ # ``RunCreateRequest.pipeline_version`` has no ge=1 validator, so
110
+ # this is the only gate that catches the malformed case
111
+ # (Copilot review on PR #313).
112
+ target_version = (
113
+ payload.pipeline_version if payload.pipeline_version is not None else pipeline.version
114
+ )
115
+ pipeline_version = session.scalar(
116
+ select(PipelineVersionORM)
117
+ .where(PipelineVersionORM.pipeline_id == payload.pipeline_id)
118
+ .where(PipelineVersionORM.version == target_version)
119
+ )
120
+ if pipeline_version is None:
121
+ raise HTTPException(
122
+ status_code=status.HTTP_404_NOT_FOUND,
123
+ detail=f"Pipeline version not found: {payload.pipeline_id}@v{target_version}",
124
+ )
125
+
126
+ # Build initial state — defaults < project context (#65) < caller's
127
+ # initial_state (caller wins). Project supplies ``repo`` from
128
+ # ``repo_url`` and ``branch`` from ``default_branch`` so a project
129
+ # owner doesn't have to repeat them on every trigger.
130
+ project_defaults: dict[str, Any] = {}
131
+ if project is not None:
132
+ if project.repo_url:
133
+ project_defaults["repo"] = project.repo_url
134
+ project_defaults["branch"] = project.default_branch
135
+
136
+ state_dict: dict[str, Any] = {
137
+ "run_id": "pending",
138
+ "repo": "",
139
+ "branch": "",
140
+ **project_defaults,
141
+ **payload.initial_state,
142
+ }
143
+ try:
144
+ initial_state = PipelineState.model_validate(state_dict)
145
+ except ValidationError as exc:
146
+ raise HTTPException(
147
+ status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
148
+ detail=f"Invalid initial_state: {exc.errors()}",
149
+ ) from exc
150
+
151
+ run_orm = repo.create_run(
152
+ session,
153
+ user_id=user.id,
154
+ pipeline_id=payload.pipeline_id,
155
+ pipeline_version=target_version,
156
+ trigger_source="api",
157
+ initial_state=initial_state,
158
+ project_id=payload.project_id,
159
+ )
160
+ # Commit so the background task can see the row in its own session.
161
+ session.commit()
162
+ run_id = run_orm.id
163
+
164
+ initial_state_with_run_id = initial_state.model_copy(update={"run_id": run_id})
165
+
166
+ # Spawn background task — runs pipeline in its own DB session.
167
+ task = asyncio.create_task(
168
+ execute_run_background(
169
+ run_id=run_id,
170
+ pipeline_id=payload.pipeline_id,
171
+ pipeline_version=target_version,
172
+ initial_state=initial_state_with_run_id,
173
+ session_factory=session_factory,
174
+ registry=registry,
175
+ run_registry=run_registry,
176
+ checkpointer=checkpointer,
177
+ resume=False,
178
+ )
179
+ )
180
+ run_registry.register(run_id, task)
181
+
182
+ # Re-fetch run to return current state (running)
183
+ return repo.get_run(session, run_id, actor_id=user.id, is_admin=user.is_superuser)
184
+
185
+
186
+ @router.post("/{run_id}/abort", response_model=Run)
187
+ async def abort_run(
188
+ run_id: str,
189
+ session: Session = Depends(get_session),
190
+ run_registry: RunRegistry = Depends(get_run_registry),
191
+ user: UserORM = Depends(current_active_user),
192
+ ) -> Run:
193
+ """Cancel a running pipeline.
194
+
195
+ 409 if the run is already finalized (success/failed/aborted) or no
196
+ background task is registered for it. Paused runs can also be aborted.
197
+ """
198
+ try:
199
+ run = repo.get_run(session, run_id, actor_id=user.id, is_admin=user.is_superuser)
200
+ except repo.NotFoundError as exc:
201
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
202
+
203
+ if run.final_status not in {"running", "paused"}:
204
+ raise HTTPException(
205
+ status_code=status.HTTP_409_CONFLICT,
206
+ detail=f"Run is not running or paused (final_status={run.final_status})",
207
+ )
208
+
209
+ cancelled = await run_registry.abort(run_id)
210
+ if not cancelled:
211
+ # Background task already finished or run is paused with no live task.
212
+ # Mark the run as aborted defensively.
213
+ repo.finalize_run(session, run_id, final_status="aborted")
214
+
215
+ # The background task's CancelledError handler finalizes status in a
216
+ # *separate* session. With expire_on_commit=False, our request session
217
+ # still has the stale RunORM cached — expire it so we read fresh state.
218
+ session.expire_all()
219
+ return repo.get_run(session, run_id, actor_id=user.id, is_admin=user.is_superuser)
220
+
221
+
222
+ @router.post("/{run_id}/pause", response_model=Run)
223
+ async def pause_run_endpoint(
224
+ run_id: str,
225
+ session: Session = Depends(get_session),
226
+ run_registry: RunRegistry = Depends(get_run_registry),
227
+ user: UserORM = Depends(current_active_user),
228
+ ) -> Run:
229
+ """Pause a running pipeline.
230
+
231
+ Cancels the background task between node boundaries; the LangGraph
232
+ checkpoint preserves state so the run can be resumed via
233
+ POST /runs/{id}/resume. 409 if the run is not currently running.
234
+ """
235
+ try:
236
+ run = repo.get_run(session, run_id, actor_id=user.id, is_admin=user.is_superuser)
237
+ except repo.NotFoundError as exc:
238
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
239
+
240
+ if run.final_status != "running":
241
+ raise HTTPException(
242
+ status_code=status.HTTP_409_CONFLICT,
243
+ detail=f"Run is not running (final_status={run.final_status})",
244
+ )
245
+
246
+ paused = await run_registry.pause(run_id)
247
+ if not paused:
248
+ # Race window: task finished between status check and pause request.
249
+ raise HTTPException(
250
+ status_code=status.HTTP_409_CONFLICT,
251
+ detail="No active background task for this run",
252
+ )
253
+
254
+ # Pause finalization runs in the background task's session — expire
255
+ # this session's cached RunORM so the response reflects final_status="paused".
256
+ session.expire_all()
257
+ return repo.get_run(session, run_id, actor_id=user.id, is_admin=user.is_superuser)
258
+
259
+
260
+ @router.post("/{run_id}/resume", response_model=Run)
261
+ async def resume_run_endpoint(
262
+ run_id: str,
263
+ session: Session = Depends(get_session),
264
+ registry: RuntimeRegistry = Depends(get_registry),
265
+ run_registry: RunRegistry = Depends(get_run_registry),
266
+ session_factory: sessionmaker[Session] = Depends(get_session_factory),
267
+ checkpointer: BaseCheckpointSaver[Any] = Depends(get_checkpointer),
268
+ user: UserORM = Depends(current_active_user),
269
+ ) -> Run:
270
+ """Resume a paused run from its last LangGraph checkpoint.
271
+
272
+ 409 if the run is not paused. Spawns a fresh background task using
273
+ the same run_id (= LangGraph thread_id), so execution picks up from
274
+ the last checkpointed node.
275
+
276
+ **Human gate behaviour**: when the run is paused via ``interrupt_before``
277
+ (pipeline has ``approval_required_nodes`` set), calling ``/resume``
278
+ correctly skips the interrupt and continues execution — no infinite loop.
279
+ Use ``POST /runs/{id}/nodes/{node_id}/approve`` for a semantically
280
+ clearer alternative that also validates the gate node is actually staged.
281
+
282
+ .. deprecated-warning::
283
+ If the run was paused by a *python-func* node that called
284
+ ``POST /runs/{id}/pause`` internally (the old ``human_gate`` pattern),
285
+ ``/resume`` re-executes that node and triggers a new pause. Use
286
+ ``POST /runs/{id}/nodes/{node_id}/skip`` in that case. The preferred
287
+ approach is ``approval_required_nodes`` + ``interrupt_before``
288
+ (this engine version) which makes ``/resume`` work correctly (#164).
289
+ """
290
+ try:
291
+ run = repo.get_run(session, run_id, actor_id=user.id, is_admin=user.is_superuser)
292
+ except repo.NotFoundError as exc:
293
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
294
+
295
+ # Fast-fail with informative current status; the atomic claim below is the
296
+ # actual source of truth for the paused→running transition (#185).
297
+ if run.final_status != "paused":
298
+ raise HTTPException(
299
+ status_code=status.HTTP_409_CONFLICT,
300
+ detail=f"Run is not paused (final_status={run.final_status})",
301
+ )
302
+
303
+ if run_registry.is_running(run_id):
304
+ raise HTTPException(
305
+ status_code=status.HTTP_409_CONFLICT,
306
+ detail="Run already has an active background task",
307
+ )
308
+
309
+ # Atomic paused→running transition. Two concurrent /resume requests would
310
+ # otherwise both pass the checks above, both spawn background tasks, and
311
+ # the second run_registry.register would raise with an orphan task in
312
+ # flight. Only one row update wins; the loser sees rowcount==0 → 409. (#185)
313
+ if not repo.try_claim_resume(session, run_id):
314
+ raise HTTPException(
315
+ status_code=status.HTTP_409_CONFLICT,
316
+ detail=(
317
+ "Run is no longer paused — another request may have resumed it, "
318
+ "or the run was aborted/finalized between validation and here"
319
+ ),
320
+ )
321
+ session.commit()
322
+
323
+ task = asyncio.create_task(
324
+ execute_run_background(
325
+ run_id=run_id,
326
+ pipeline_id=run.pipeline_id,
327
+ pipeline_version=run.pipeline_version,
328
+ initial_state=None,
329
+ session_factory=session_factory,
330
+ registry=registry,
331
+ run_registry=run_registry,
332
+ checkpointer=checkpointer,
333
+ resume=True,
334
+ )
335
+ )
336
+ run_registry.register(run_id, task)
337
+
338
+ return repo.get_run(session, run_id, actor_id=user.id, is_admin=user.is_superuser)
339
+
340
+
341
+ @router.post("/{run_id}/nodes/{node_id}/approve", response_model=Run)
342
+ async def approve_gate_endpoint(
343
+ run_id: str,
344
+ node_id: str,
345
+ session: Session = Depends(get_session),
346
+ registry: RuntimeRegistry = Depends(get_registry),
347
+ run_registry: RunRegistry = Depends(get_run_registry),
348
+ session_factory: sessionmaker[Session] = Depends(get_session_factory),
349
+ checkpointer: BaseCheckpointSaver[Any] = Depends(get_checkpointer),
350
+ user: UserORM = Depends(current_active_user),
351
+ ) -> Run:
352
+ """Approve a human gate and continue pipeline execution (#164).
353
+
354
+ Semantically equivalent to ``POST /runs/{id}/resume`` but communicates
355
+ operator intent explicitly — "I reviewed the gate and approve". The
356
+ ``node_id`` path parameter documents *which* gate was reviewed; the engine
357
+ validates it exists in the pipeline version that produced this run.
358
+
359
+ Works correctly with pipelines that use ``approval_required_nodes`` +
360
+ ``interrupt_before``: ``/resume`` and ``/approve`` both call
361
+ ``ainvoke(None, ...)`` which skips the pending interrupt and continues.
362
+
363
+ Status codes:
364
+
365
+ * **404** — run not found, pipeline version vanished, or ``node_id`` does
366
+ not exist in the pipeline version that produced this run.
367
+ * **409** — run is not paused, run already has an active background task,
368
+ or ``node_id`` exists in the pipeline but is not declared as an
369
+ approval gate (``defaults.approval_required_nodes``). The last case
370
+ prevents audit-log spoofing: previously the path parameter was
371
+ decorative and any node could be approved against any gate (#184).
372
+
373
+ .. note::
374
+ For the legacy python-func ``human_gate`` pattern (where the gate node
375
+ itself calls ``POST /runs/{id}/pause``), use
376
+ ``POST /runs/{id}/nodes/{node_id}/skip`` instead — ``/approve`` and
377
+ ``/resume`` would re-execute the gate node and pause again.
378
+ """
379
+ try:
380
+ run = repo.get_run(session, run_id, actor_id=user.id, is_admin=user.is_superuser)
381
+ except repo.NotFoundError as exc:
382
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
383
+
384
+ if run.final_status != "paused":
385
+ raise HTTPException(
386
+ status_code=status.HTTP_409_CONFLICT,
387
+ detail=f"Run is not paused (final_status={run.final_status})",
388
+ )
389
+
390
+ if run_registry.is_running(run_id):
391
+ raise HTTPException(
392
+ status_code=status.HTTP_409_CONFLICT,
393
+ detail="Run already has an active background task",
394
+ )
395
+
396
+ # Validate node_id exists in the pipeline version that produced this run.
397
+ version_orm = session.scalar(
398
+ select(PipelineVersionORM)
399
+ .where(PipelineVersionORM.pipeline_id == run.pipeline_id)
400
+ .where(PipelineVersionORM.version == run.pipeline_version)
401
+ )
402
+ if version_orm is None:
403
+ raise HTTPException(
404
+ status_code=status.HTTP_404_NOT_FOUND,
405
+ detail=f"Pipeline version not found: {run.pipeline_id}@v{run.pipeline_version}",
406
+ )
407
+ node_ids = {n["id"] for n in version_orm.nodes}
408
+ if node_id not in node_ids:
409
+ raise HTTPException(
410
+ status_code=status.HTTP_404_NOT_FOUND,
411
+ detail=f"Node '{node_id}' not in pipeline {run.pipeline_id}@v{run.pipeline_version}",
412
+ )
413
+
414
+ # Reject approval against a non-gate node. Without this check, the path
415
+ # parameter was decorative — any existing node could "approve" any gate,
416
+ # so the audit log would record approved=<wrong_node> while the run
417
+ # actually advances at whatever LangGraph's interrupt_before paused on (#184).
418
+ pipeline_defaults = PipelineDefaults.model_validate(version_orm.defaults)
419
+ approval_nodes = set(pipeline_defaults.approval_required_nodes)
420
+ if node_id not in approval_nodes:
421
+ raise HTTPException(
422
+ status_code=status.HTTP_409_CONFLICT,
423
+ detail=(
424
+ f"Node '{node_id}' is not an approval gate in this pipeline "
425
+ f"(defaults.approval_required_nodes={sorted(approval_nodes)})"
426
+ ),
427
+ )
428
+
429
+ # Atomic paused→running transition (#185); see /resume for rationale.
430
+ if not repo.try_claim_resume(session, run_id):
431
+ raise HTTPException(
432
+ status_code=status.HTTP_409_CONFLICT,
433
+ detail=(
434
+ "Run is no longer paused — another request may have resumed it, "
435
+ "or the run was aborted/finalized between validation and here"
436
+ ),
437
+ )
438
+ session.commit()
439
+
440
+ task = asyncio.create_task(
441
+ execute_run_background(
442
+ run_id=run_id,
443
+ pipeline_id=run.pipeline_id,
444
+ pipeline_version=run.pipeline_version,
445
+ initial_state=None,
446
+ session_factory=session_factory,
447
+ registry=registry,
448
+ run_registry=run_registry,
449
+ checkpointer=checkpointer,
450
+ resume=True,
451
+ )
452
+ )
453
+ run_registry.register(run_id, task)
454
+ return repo.get_run(session, run_id, actor_id=user.id, is_admin=user.is_superuser)
455
+
456
+
457
+ @router.post("/{run_id}/nodes/{node_id}/retry", response_model=Run)
458
+ async def retry_node(
459
+ run_id: str,
460
+ node_id: str,
461
+ session: Session = Depends(get_session),
462
+ registry: RuntimeRegistry = Depends(get_registry),
463
+ run_registry: RunRegistry = Depends(get_run_registry),
464
+ session_factory: sessionmaker[Session] = Depends(get_session_factory),
465
+ checkpointer: BaseCheckpointSaver[Any] = Depends(get_checkpointer),
466
+ user: UserORM = Depends(current_active_user),
467
+ ) -> Run:
468
+ """Re-execute a single node and continue forward.
469
+
470
+ Rewinds to the LangGraph checkpoint where `node_id` was staged as next,
471
+ branches a new tip from there, and resumes — the named node runs again.
472
+ Useful when a transient failure (rate limit, flake) caused a node to
473
+ fail; the rest of the run can complete without re-running everything.
474
+ """
475
+ return await _do_node_intervention(
476
+ run_id=run_id,
477
+ node_id=node_id,
478
+ mode=REWIND_RETRY,
479
+ session=session,
480
+ registry=registry,
481
+ run_registry=run_registry,
482
+ session_factory=session_factory,
483
+ checkpointer=checkpointer,
484
+ user=user,
485
+ )
486
+
487
+
488
+ @router.post("/{run_id}/nodes/{node_id}/skip", response_model=Run)
489
+ async def skip_node(
490
+ run_id: str,
491
+ node_id: str,
492
+ session: Session = Depends(get_session),
493
+ registry: RuntimeRegistry = Depends(get_registry),
494
+ run_registry: RunRegistry = Depends(get_run_registry),
495
+ session_factory: sessionmaker[Session] = Depends(get_session_factory),
496
+ checkpointer: BaseCheckpointSaver[Any] = Depends(get_checkpointer),
497
+ user: UserORM = Depends(current_active_user),
498
+ ) -> Run:
499
+ """Bypass a node and continue with its downstream successors.
500
+
501
+ Rewinds to the LangGraph checkpoint where `node_id` was staged as next,
502
+ fakes a no-op completion of that node, and resumes — downstream nodes
503
+ proceed using whatever state existed before the skipped node would have
504
+ run. Useful when a node is broken and the rest of the pipeline can
505
+ still produce a useful outcome.
506
+ """
507
+ return await _do_node_intervention(
508
+ run_id=run_id,
509
+ node_id=node_id,
510
+ mode=REWIND_SKIP,
511
+ session=session,
512
+ registry=registry,
513
+ run_registry=run_registry,
514
+ session_factory=session_factory,
515
+ checkpointer=checkpointer,
516
+ user=user,
517
+ )
518
+
519
+
520
+ async def _do_node_intervention(
521
+ *,
522
+ run_id: str,
523
+ node_id: str,
524
+ mode: str,
525
+ session: Session,
526
+ registry: RuntimeRegistry,
527
+ run_registry: RunRegistry,
528
+ session_factory: sessionmaker[Session],
529
+ checkpointer: BaseCheckpointSaver[Any],
530
+ user: UserORM,
531
+ ) -> Run:
532
+ """Shared validation + dispatch path for retry-node and skip-node."""
533
+ try:
534
+ run = repo.get_run(session, run_id, actor_id=user.id, is_admin=user.is_superuser)
535
+ except repo.NotFoundError as exc:
536
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
537
+
538
+ if run.final_status not in {"paused", "failed"}:
539
+ raise HTTPException(
540
+ status_code=status.HTTP_409_CONFLICT,
541
+ detail=(
542
+ f"Run is not paused or failed (final_status={run.final_status}); "
543
+ "retry/skip require a stopped run."
544
+ ),
545
+ )
546
+
547
+ if run_registry.is_running(run_id):
548
+ raise HTTPException(
549
+ status_code=status.HTTP_409_CONFLICT,
550
+ detail="Run already has an active background task",
551
+ )
552
+
553
+ # Validate node exists in the pipeline version that produced this run.
554
+ version_orm = session.scalar(
555
+ select(PipelineVersionORM)
556
+ .where(PipelineVersionORM.pipeline_id == run.pipeline_id)
557
+ .where(PipelineVersionORM.version == run.pipeline_version)
558
+ )
559
+ if version_orm is None:
560
+ raise HTTPException(
561
+ status_code=status.HTTP_404_NOT_FOUND,
562
+ detail=(f"Pipeline version not found: {run.pipeline_id}@v{run.pipeline_version}"),
563
+ )
564
+ node_ids = {n["id"] for n in version_orm.nodes}
565
+ if node_id not in node_ids:
566
+ raise HTTPException(
567
+ status_code=status.HTTP_404_NOT_FOUND,
568
+ detail=(
569
+ f"Node '{node_id}' not found in pipeline {run.pipeline_id}@v{run.pipeline_version}"
570
+ ),
571
+ )
572
+
573
+ # Atomic (paused|failed)→running transition (#185); same TOCTOU class as
574
+ # /resume and /approve, just a wider starting state to allow node-level
575
+ # recovery from a terminated run.
576
+ if not repo.try_claim_revive(session, run_id):
577
+ raise HTTPException(
578
+ status_code=status.HTTP_409_CONFLICT,
579
+ detail=(
580
+ "Run is no longer paused or failed — another request may have "
581
+ "retried/skipped/resumed it, or the run was aborted/finalized "
582
+ "between validation and here"
583
+ ),
584
+ )
585
+ session.commit()
586
+
587
+ task = asyncio.create_task(
588
+ execute_rewind_background(
589
+ run_id=run_id,
590
+ pipeline_id=run.pipeline_id,
591
+ pipeline_version=run.pipeline_version,
592
+ target_node=node_id,
593
+ mode=mode,
594
+ session_factory=session_factory,
595
+ registry=registry,
596
+ run_registry=run_registry,
597
+ checkpointer=checkpointer,
598
+ )
599
+ )
600
+ run_registry.register(run_id, task)
601
+
602
+ session.expire_all()
603
+ return repo.get_run(session, run_id, actor_id=user.id, is_admin=user.is_superuser)
604
+
605
+
606
+ @router.get("")
607
+ def list_runs(
608
+ session: Session = Depends(get_session),
609
+ user: UserORM = Depends(current_active_user),
610
+ pipeline_id: str | None = Query(default=None),
611
+ final_status: str | None = Query(default=None),
612
+ project_id: str | None = Query(
613
+ default=None,
614
+ description=(
615
+ "Filter by project: omit for all runs, supply a project id "
616
+ 'for that project only, or pass the literal "null" to return '
617
+ "only ad-hoc / legacy runs without a project."
618
+ ),
619
+ ),
620
+ offset: int = Query(default=0, ge=0),
621
+ limit: int = Query(default=50, ge=1, le=500),
622
+ ) -> dict[str, Any]:
623
+ only_unscoped = project_id == "null"
624
+ effective_project_id = None if only_unscoped else project_id
625
+ items, total = repo.list_runs(
626
+ session,
627
+ actor_id=user.id,
628
+ is_admin=user.is_superuser,
629
+ pipeline_id=pipeline_id,
630
+ final_status=final_status,
631
+ project_id=effective_project_id,
632
+ only_unscoped=only_unscoped,
633
+ offset=offset,
634
+ limit=limit,
635
+ )
636
+ return {
637
+ "items": [r.model_dump(mode="json") for r in items],
638
+ "total": total,
639
+ "offset": offset,
640
+ "limit": limit,
641
+ }
642
+
643
+
644
+ @router.get("/{run_id}", response_model=Run)
645
+ def get_run(
646
+ run_id: str,
647
+ session: Session = Depends(get_session),
648
+ user: UserORM = Depends(current_active_user),
649
+ ) -> Run:
650
+ try:
651
+ return repo.get_run(session, run_id, actor_id=user.id, is_admin=user.is_superuser)
652
+ except repo.NotFoundError as exc:
653
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
654
+
655
+
656
+ @router.get("/{run_id}/state", response_model=PipelineState)
657
+ def get_run_state(
658
+ run_id: str,
659
+ session: Session = Depends(get_session),
660
+ user: UserORM = Depends(current_active_user),
661
+ ) -> PipelineState:
662
+ try:
663
+ return repo.get_run_state(session, run_id, actor_id=user.id, is_admin=user.is_superuser)
664
+ except repo.NotFoundError as exc:
665
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
666
+
667
+
668
+ @router.get("/{run_id}/state/history", response_model=list[StateSnapshot])
669
+ def list_run_state_history(
670
+ run_id: str,
671
+ session: Session = Depends(get_session),
672
+ user: UserORM = Depends(current_active_user),
673
+ ) -> list[StateSnapshot]:
674
+ try:
675
+ return repo.list_run_state_history(
676
+ session, run_id, actor_id=user.id, is_admin=user.is_superuser
677
+ )
678
+ except repo.NotFoundError as exc:
679
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
680
+
681
+
682
+ @router.get("/{run_id}/nodes/{node_id}", response_model=NodeExecutionLog)
683
+ def get_run_node_log(
684
+ run_id: str,
685
+ node_id: str,
686
+ session: Session = Depends(get_session),
687
+ user: UserORM = Depends(current_active_user),
688
+ ) -> NodeExecutionLog:
689
+ try:
690
+ return repo.get_run_node_log(
691
+ session, run_id, node_id, actor_id=user.id, is_admin=user.is_superuser
692
+ )
693
+ except repo.NotFoundError as exc:
694
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc