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
@@ -0,0 +1,580 @@
1
+ """Pipeline DAG validator — pure + DB-aware checks before save.
2
+
3
+ Two layers:
4
+ 1. Pydantic-level — handled by FastAPI on request parse (correct types,
5
+ edge condition union, etc.)
6
+ 2. Semantic — this module: agent existence, entry point, reachability,
7
+ ambiguous routing, per-agent input/output cohesion (#59).
8
+
9
+ Run via `validate_pipeline_dag(payload, session)`. Used by Pipeline Designer
10
+ (F7) to surface errors before save.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import dataclasses
16
+ from collections import deque
17
+ from graphlib import CycleError, TopologicalSorter
18
+ from typing import Any, Final
19
+
20
+ from dap_types import PipelineState
21
+ from dap_types.pipeline import (
22
+ ComparisonCondition,
23
+ EdgeCondition,
24
+ LogicalCondition,
25
+ PipelineEdge,
26
+ PipelineNode,
27
+ )
28
+ from pydantic import BaseModel, ConfigDict, Field
29
+ from sqlalchemy import select
30
+ from sqlalchemy.orm import Session
31
+
32
+ from dap_engine.contracts import PipelineCreate
33
+ from dap_engine.persistence.models import AgentORM, AgentVersionORM
34
+
35
+ START_SENTINEL: Final = "__start__"
36
+ END_SENTINEL: Final = "__end__"
37
+ SENTINEL_NODES: Final = frozenset({START_SENTINEL, END_SENTINEL})
38
+
39
+
40
+ def _load_referenced_agents(payload: PipelineCreate, session: Session) -> dict[str, AgentORM]:
41
+ """One SELECT for every agent the pipeline references (#120 hot-path).
42
+
43
+ ``validate_pipeline_dag`` runs on every save now, so per-agent
44
+ ``session.get`` calls turned into N+1 round-trips on pipelines
45
+ with many nodes. Single ``WHERE id IN (...)`` keeps the cost
46
+ flat regardless of node count.
47
+ """
48
+ referenced = {n.agent_id for n in payload.nodes}
49
+ if not referenced:
50
+ return {}
51
+ rows = session.scalars(
52
+ select(AgentORM).where(AgentORM.id.in_(referenced)),
53
+ ).all()
54
+ return {agent.id: agent for agent in rows}
55
+
56
+
57
+ class ValidationResult(BaseModel):
58
+ """Outcome of pipeline DAG validation."""
59
+
60
+ model_config = ConfigDict(extra="forbid")
61
+
62
+ valid: bool
63
+ errors: list[str] = Field(default_factory=list)
64
+ warnings: list[str] = Field(default_factory=list)
65
+
66
+
67
+ def validate_pipeline_dag(payload: PipelineCreate, session: Session) -> ValidationResult:
68
+ """Validate pipeline structure + references. Returns ValidationResult.
69
+
70
+ Errors block save; warnings inform but allow save.
71
+ """
72
+ errors: list[str] = []
73
+ warnings: list[str] = []
74
+
75
+ node_id_set = {n.id for n in payload.nodes}
76
+
77
+ errors.extend(_check_duplicate_ids(payload))
78
+ errors.extend(_check_entry_point(payload, node_id_set))
79
+ errors.extend(_check_edge_references(payload, node_id_set))
80
+ errors.extend(_check_agents(payload, session))
81
+
82
+ # If structural errors, skip reachability — graph is bogus.
83
+ if errors:
84
+ return ValidationResult(valid=False, errors=errors, warnings=warnings)
85
+
86
+ errors.extend(_check_ambiguous_routing(payload))
87
+ errors.extend(_check_reachability(payload))
88
+ warnings.extend(_check_condition_fields(payload))
89
+
90
+ # Cohesion checks (#59) need the structural graph + agent contracts.
91
+ # Skipped silently when a structural problem already broke the run.
92
+ if not errors:
93
+ contracts = _load_agent_contracts(payload, session)
94
+ errors.extend(_check_input_contracts(payload, contracts))
95
+ warnings.extend(_check_unused_outputs(payload, contracts))
96
+ warnings.extend(_check_conflicting_writers(payload, contracts))
97
+
98
+ return ValidationResult(valid=not errors, errors=errors, warnings=warnings)
99
+
100
+
101
+ def _check_duplicate_ids(payload: PipelineCreate) -> list[str]:
102
+ out: list[str] = []
103
+ node_ids = [n.id for n in payload.nodes]
104
+ if len(node_ids) != len(set(node_ids)):
105
+ dups = sorted({nid for nid in node_ids if node_ids.count(nid) > 1})
106
+ out.append(f"Duplicate node ids: {dups}")
107
+ edge_ids = [e.id for e in payload.edges]
108
+ if len(edge_ids) != len(set(edge_ids)):
109
+ dups = sorted({eid for eid in edge_ids if edge_ids.count(eid) > 1})
110
+ out.append(f"Duplicate edge ids: {dups}")
111
+ return out
112
+
113
+
114
+ def _check_entry_point(payload: PipelineCreate, node_id_set: set[str]) -> list[str]:
115
+ if payload.entry_point in node_id_set:
116
+ return []
117
+ return [
118
+ f"entry_point '{payload.entry_point}' does not match any node.id "
119
+ f"(known: {sorted(node_id_set)})",
120
+ ]
121
+
122
+
123
+ def _check_edge_references(payload: PipelineCreate, node_id_set: set[str]) -> list[str]:
124
+ out: list[str] = []
125
+ valid_refs = node_id_set | SENTINEL_NODES
126
+ for edge in payload.edges:
127
+ if edge.source not in valid_refs:
128
+ out.append(f"Edge '{edge.id}' source '{edge.source}' is not a known node")
129
+ if edge.target not in valid_refs:
130
+ out.append(f"Edge '{edge.id}' target '{edge.target}' is not a known node")
131
+ return out
132
+
133
+
134
+ def _check_agents(payload: PipelineCreate, session: Session) -> list[str]:
135
+ out: list[str] = []
136
+ referenced = {n.agent_id for n in payload.nodes}
137
+ agents = _load_referenced_agents(payload, session)
138
+ for agent_id in sorted(referenced):
139
+ agent = agents.get(agent_id)
140
+ if agent is None:
141
+ out.append(f"Agent not found: '{agent_id}'")
142
+ elif agent.archived_at is not None:
143
+ out.append(f"Agent is archived: '{agent_id}'")
144
+ return out
145
+
146
+
147
+ def _check_ambiguous_routing(payload: PipelineCreate) -> list[str]:
148
+ out: list[str] = []
149
+ edges_by_source: dict[str, list[PipelineEdge]] = {}
150
+ for edge in payload.edges:
151
+ edges_by_source.setdefault(edge.source, []).append(edge)
152
+ for source, edges in edges_by_source.items():
153
+ unconditional = [e for e in edges if e.condition is None]
154
+ if len(unconditional) > 1:
155
+ out.append(
156
+ f"Source '{source}' has {len(unconditional)} unconditional edges — "
157
+ f"ambiguous routing. Use exactly one unconditional edge or all conditional."
158
+ )
159
+ return out
160
+
161
+
162
+ def _check_reachability(payload: PipelineCreate) -> list[str]:
163
+ out: list[str] = []
164
+ forward_adj: dict[str, set[str]] = {}
165
+ reverse_adj: dict[str, set[str]] = {}
166
+ for edge in payload.edges:
167
+ forward_adj.setdefault(edge.source, set()).add(edge.target)
168
+ reverse_adj.setdefault(edge.target, set()).add(edge.source)
169
+
170
+ # Implicit edge START → entry_point
171
+ forward_adj.setdefault(START_SENTINEL, set()).add(payload.entry_point)
172
+ reverse_adj.setdefault(payload.entry_point, set()).add(START_SENTINEL)
173
+
174
+ reachable_from_start = _bfs(forward_adj, START_SENTINEL)
175
+ reaches_end = _bfs(reverse_adj, END_SENTINEL)
176
+
177
+ for node in payload.nodes:
178
+ if node.id not in reachable_from_start:
179
+ out.append(f"Node '{node.id}' is unreachable from START")
180
+ if node.id not in reaches_end:
181
+ out.append(f"Node '{node.id}' has no path to END")
182
+ return out
183
+
184
+
185
+ def _check_condition_fields(payload: PipelineCreate) -> list[str]:
186
+ out: list[str] = []
187
+ state_fields = set(PipelineState.model_fields.keys())
188
+ for edge in payload.edges:
189
+ if edge.condition is not None:
190
+ unknown = _collect_unknown_fields(edge.condition, state_fields)
191
+ for field in sorted(unknown):
192
+ out.append(
193
+ f"Edge '{edge.id}' references unknown PipelineState field: '{field}'",
194
+ )
195
+ return out
196
+
197
+
198
+ def _bfs(adjacency: dict[str, set[str]], start: str) -> set[str]:
199
+ """Return set of nodes reachable from `start` in the given adjacency map."""
200
+ visited = {start}
201
+ queue: deque[str] = deque([start])
202
+ while queue:
203
+ current = queue.popleft()
204
+ for neighbor in adjacency.get(current, set()):
205
+ if neighbor not in visited:
206
+ visited.add(neighbor)
207
+ queue.append(neighbor)
208
+ return visited
209
+
210
+
211
+ def _collect_unknown_fields(
212
+ condition: EdgeCondition,
213
+ known_fields: set[str],
214
+ ) -> set[str]:
215
+ """Walk the condition tree and return field names not in known_fields."""
216
+ unknown: set[str] = set()
217
+ if isinstance(condition, ComparisonCondition):
218
+ if condition.field not in known_fields:
219
+ unknown.add(condition.field)
220
+ elif isinstance(condition, LogicalCondition):
221
+ for child in condition.children:
222
+ unknown |= _collect_unknown_fields(child, known_fields)
223
+ return unknown
224
+
225
+
226
+ # ---------------------------------------------------------------------------
227
+ # Cohesion checks (#59) — verify per-agent input/output contracts hang together
228
+ # across the pipeline graph.
229
+ # ---------------------------------------------------------------------------
230
+
231
+
232
+ @dataclasses.dataclass(frozen=True)
233
+ class _AgentContract:
234
+ """Per-agent input/output schemas, normalised for cohesion analysis."""
235
+
236
+ input_schema: tuple[str, ...]
237
+ output_schema: tuple[str, ...]
238
+
239
+
240
+ def _load_agent_contracts(
241
+ payload: PipelineCreate,
242
+ session: Session,
243
+ ) -> dict[str, _AgentContract]:
244
+ """Build ``agent_id → contract`` for every agent referenced in the pipeline.
245
+
246
+ Reads the *current* version of each agent. Agents that don't exist or
247
+ are archived are skipped silently — those cases are reported by
248
+ :func:`_check_agents` and we don't want to double-flag them here.
249
+
250
+ Legacy dict-shaped schemas (pre-#58 rows) collapse to ``()`` so they
251
+ contribute no constraint either way (matches the runtime fallback).
252
+
253
+ Two batched SELECTs total (#120 hot-path): one for the agent rows,
254
+ one for the matching version rows. Pipelines with N nodes used to
255
+ cost ``N + 1`` round-trips; now it's a flat 2 regardless of N.
256
+ """
257
+ agents = _load_referenced_agents(payload, session)
258
+ active_agents = {aid: agent for aid, agent in agents.items() if agent.archived_at is None}
259
+ if not active_agents:
260
+ return {}
261
+
262
+ # Pull every candidate version row for the active agents in one
263
+ # query, then index by ``(agent_id, version)`` so we can pick the
264
+ # row matching each agent's ``current_version`` without another
265
+ # round-trip. ``in_(active_agents)`` is fine even with one element.
266
+ version_rows = session.scalars(
267
+ select(AgentVersionORM).where(
268
+ AgentVersionORM.agent_id.in_(active_agents),
269
+ ),
270
+ ).all()
271
+ versions_by_key = {(v.agent_id, v.version): v for v in version_rows}
272
+
273
+ out: dict[str, _AgentContract] = {}
274
+ for agent_id, agent in active_agents.items():
275
+ version = versions_by_key.get((agent_id, agent.current_version))
276
+ if version is None:
277
+ continue
278
+ ins = version.input_schema if isinstance(version.input_schema, list) else []
279
+ outs = version.output_schema if isinstance(version.output_schema, list) else []
280
+ out[agent_id] = _AgentContract(
281
+ input_schema=tuple(ins),
282
+ output_schema=tuple(outs),
283
+ )
284
+ return out
285
+
286
+
287
+ # Sentinel "empty" values — a default of one of these means "field hasn't
288
+ # been populated yet", not "field has a meaningful initial value".
289
+ _TRIVIAL_DEFAULTS: Final[tuple[Any, ...]] = (None, False, 0, 0.0, "", [], {})
290
+
291
+
292
+ def _field_is_born_satisfied(field_name: str) -> bool:
293
+ """A PipelineState field that doesn't need an upstream writer.
294
+
295
+ Two ways a field is satisfied without any node writing it:
296
+
297
+ 1. **Required field** — no default at all → engine guarantees it
298
+ comes from ``initial_state`` at run-time (or the run fails to
299
+ create). ``run_id``, ``repo``, ``branch`` are the obvious
300
+ examples.
301
+ 2. **Non-trivial default** — a meaningful initial value like
302
+ ``max_attempts: int = 3`` or ``verification_status: "pending"``.
303
+
304
+ Trivial defaults (``[]``, ``""``, ``False``, ``None``) are treated
305
+ as "not yet populated" sentinels — those fields *do* need a writer.
306
+ ``default_factory`` always means an empty container, also a sentinel.
307
+ """
308
+ info = PipelineState.model_fields.get(field_name)
309
+ if info is None:
310
+ return False # unknown — caller already rejected it via field validators
311
+ if info.is_required():
312
+ return True
313
+ if info.default_factory is not None:
314
+ return False
315
+ return info.default not in _TRIVIAL_DEFAULTS
316
+
317
+
318
+ def _build_dag_adjacency(
319
+ payload: PipelineCreate,
320
+ node_ids: set[str],
321
+ ) -> tuple[dict[str, set[str]], dict[str, set[str]]]:
322
+ """Forward + reverse adjacency over real (non-sentinel) nodes only."""
323
+ adj: dict[str, set[str]] = {nid: set() for nid in node_ids}
324
+ rev_adj: dict[str, set[str]] = {nid: set() for nid in node_ids}
325
+ for edge in payload.edges:
326
+ if edge.source in node_ids and edge.target in node_ids:
327
+ adj[edge.source].add(edge.target)
328
+ rev_adj[edge.target].add(edge.source)
329
+ return adj, rev_adj
330
+
331
+
332
+ def _compute_dominators(
333
+ payload: PipelineCreate,
334
+ node_ids: set[str],
335
+ ) -> dict[str, frozenset[str]] | None:
336
+ """Compute the dominator set of every reachable node, or ``None`` on cycle.
337
+
338
+ A node ``M`` *dominates* ``N`` iff every path from ``entry_point``
339
+ to ``N`` passes through ``M``. Dominator analysis is the right tool
340
+ for cohesion: a writer satisfies a reader iff the writer is on
341
+ every path that reaches the reader (covers conditional branches
342
+ conservatively — if only one branch writes the field, it doesn't
343
+ dominate the merge).
344
+
345
+ Returns ``None`` for cyclic graphs — strict dominator semantics
346
+ don't translate cleanly, so the caller skips cohesion entirely
347
+ rather than emit false positives on retry-loop pipelines.
348
+ """
349
+ _, rev_adj = _build_dag_adjacency(payload, node_ids)
350
+ try:
351
+ topo_order = list(TopologicalSorter(rev_adj).static_order())
352
+ except CycleError:
353
+ return None
354
+
355
+ dom: dict[str, frozenset[str]] = {}
356
+ for node in topo_order:
357
+ preds = [p for p in rev_adj.get(node, set()) if p in dom]
358
+ if not preds:
359
+ dom[node] = frozenset({node})
360
+ else:
361
+ dom[node] = frozenset({node}) | frozenset.intersection(*(dom[p] for p in preds))
362
+ return dom
363
+
364
+
365
+ def _compute_descendants(
366
+ payload: PipelineCreate,
367
+ node_ids: set[str],
368
+ ) -> dict[str, set[str]]:
369
+ """For each node, the set of nodes reachable from it (excluding itself)."""
370
+ adj, _ = _build_dag_adjacency(payload, node_ids)
371
+ out: dict[str, set[str]] = {}
372
+ for nid in node_ids:
373
+ visited: set[str] = set()
374
+ queue: deque[str] = deque([nid])
375
+ while queue:
376
+ cur = queue.popleft()
377
+ for nxt in adj.get(cur, set()):
378
+ if nxt != nid and nxt not in visited:
379
+ visited.add(nxt)
380
+ queue.append(nxt)
381
+ out[nid] = visited
382
+ return out
383
+
384
+
385
+ def _check_input_contracts(
386
+ payload: PipelineCreate,
387
+ contracts: dict[str, _AgentContract],
388
+ ) -> list[str]:
389
+ """Every declared input must be covered by writers on every path, or born satisfied.
390
+
391
+ Semantics: a reader N is satisfied iff every path from
392
+ ``entry_point`` to N passes through at least one node M with the
393
+ field in ``output_schema``. Different writers on different paths
394
+ are fine — as long as each path has *some* writer (covers diamond
395
+ cases where parallel branches all happen to write the field).
396
+
397
+ Strict dominator semantics ("one writer must be on every path")
398
+ was too strict — it falsely flagged diamond merges as unsatisfied
399
+ even when both branches wrote the field.
400
+ """
401
+ out: list[str] = []
402
+ node_ids = {n.id for n in payload.nodes}
403
+ if _compute_dominators(payload, node_ids) is None:
404
+ return out # cyclic graph — skip cohesion entirely
405
+
406
+ adj, _ = _build_dag_adjacency(payload, node_ids)
407
+ nodes_by_id = {n.id: n for n in payload.nodes}
408
+
409
+ for node_id in sorted(node_ids):
410
+ contract = contracts.get(nodes_by_id[node_id].agent_id)
411
+ if contract is None:
412
+ continue
413
+ for field in contract.input_schema:
414
+ if _field_is_born_satisfied(field):
415
+ continue
416
+ writers = _writer_ids_for(field, contracts, nodes_by_id, node_ids) - {node_id}
417
+ if not _every_path_passes_writer(
418
+ payload.entry_point,
419
+ target=node_id,
420
+ writers=writers,
421
+ adj=adj,
422
+ ):
423
+ out.append(
424
+ f"Node '{node_id}' requires '{field}' but no upstream node writes it.",
425
+ )
426
+ return out
427
+
428
+
429
+ def _writer_ids_for(
430
+ field: str,
431
+ contracts: dict[str, _AgentContract],
432
+ nodes_by_id: dict[str, PipelineNode],
433
+ node_ids: set[str],
434
+ ) -> frozenset[str]:
435
+ """Return the set of node ids whose agent declares ``field`` as an output."""
436
+ return frozenset(
437
+ nid
438
+ for nid in node_ids
439
+ if (c := contracts.get(nodes_by_id[nid].agent_id)) is not None and field in c.output_schema
440
+ )
441
+
442
+
443
+ def _every_path_passes_writer(
444
+ entry: str,
445
+ *,
446
+ target: str,
447
+ writers: frozenset[str],
448
+ adj: dict[str, set[str]],
449
+ ) -> bool:
450
+ """True iff every path from ``entry`` to ``target`` includes a writer.
451
+
452
+ Implementation: BFS from ``entry`` treating writer nodes as walls
453
+ (we don't traverse INTO them — going through one means the field
454
+ is set, so the path is covered). If ``target`` is reached without
455
+ crossing a writer, that path is *uncovered* → return False.
456
+ """
457
+ if entry == target:
458
+ # Reader is the entry point — no upstream writer can save it.
459
+ return False
460
+ if entry in writers:
461
+ # Entry writes the field; every path from entry through its
462
+ # successors carries the write forward.
463
+ return True
464
+
465
+ visited: set[str] = {entry}
466
+ queue: deque[str] = deque([entry])
467
+ while queue:
468
+ cur = queue.popleft()
469
+ for nxt in adj.get(cur, set()):
470
+ if nxt == target:
471
+ # Reached target via a path that didn't cross a writer.
472
+ return False
473
+ if nxt in writers:
474
+ continue # wall — paths through here are covered
475
+ if nxt not in visited:
476
+ visited.add(nxt)
477
+ queue.append(nxt)
478
+ return True
479
+
480
+
481
+ def _check_unused_outputs(
482
+ payload: PipelineCreate,
483
+ contracts: dict[str, _AgentContract],
484
+ ) -> list[str]:
485
+ """Warn when a declared output isn't read by any descendant — likely a wiring bug.
486
+
487
+ Terminal nodes (no descendants in the real-node graph — their only
488
+ successor is ``__end__`` or none) are skipped: their outputs are by
489
+ design consumed only by the final PipelineState snapshot or external
490
+ callers reading via ``/runs/{id}/state``. Warning on them produces
491
+ noise on legitimate final-reporter agents (e.g. ``finalize``,
492
+ ``pr_creator``) and trains operators to ignore the warning class. (#204)
493
+ """
494
+ out: list[str] = []
495
+ node_ids = {n.id for n in payload.nodes}
496
+ descendants = _compute_descendants(payload, node_ids)
497
+ nodes_by_id = {n.id: n for n in payload.nodes}
498
+
499
+ for node_id in sorted(node_ids):
500
+ # Terminal node — no real-node descendants → nothing in-pipeline can
501
+ # read its outputs, but that's by design for end-of-pipeline writers.
502
+ if not descendants[node_id]:
503
+ continue
504
+ node = nodes_by_id[node_id]
505
+ contract = contracts.get(node.agent_id)
506
+ if contract is None:
507
+ continue
508
+ for field in contract.output_schema:
509
+ if not _has_downstream_reader(field, descendants[node_id], nodes_by_id, contracts):
510
+ out.append(
511
+ f"Node '{node_id}' writes '{field}' but no downstream node reads it.",
512
+ )
513
+ return out
514
+
515
+
516
+ def _has_downstream_reader(
517
+ field: str,
518
+ descendant_ids: set[str],
519
+ nodes_by_id: dict[str, PipelineNode],
520
+ contracts: dict[str, _AgentContract],
521
+ ) -> bool:
522
+ for desc_id in descendant_ids:
523
+ node = nodes_by_id.get(desc_id)
524
+ if node is None:
525
+ continue
526
+ contract = contracts.get(node.agent_id)
527
+ if contract is None:
528
+ continue
529
+ if field in contract.input_schema:
530
+ return True
531
+ return False
532
+
533
+
534
+ def _check_conflicting_writers(
535
+ payload: PipelineCreate,
536
+ contracts: dict[str, _AgentContract],
537
+ ) -> list[str]:
538
+ """Warn when two parallel-branch nodes both declare the same output field.
539
+
540
+ "Parallel" = neither node dominates the other, so at runtime LangGraph
541
+ has to merge concurrent state diffs with no declared strategy —
542
+ almost always a bug.
543
+ """
544
+ out: list[str] = []
545
+ node_ids = {n.id for n in payload.nodes}
546
+ dominators = _compute_dominators(payload, node_ids)
547
+ if dominators is None:
548
+ return out
549
+
550
+ nodes_by_id = {n.id: n for n in payload.nodes}
551
+ writers_by_field: dict[str, list[str]] = {}
552
+ for node_id in node_ids:
553
+ contract = contracts.get(nodes_by_id[node_id].agent_id)
554
+ if contract is None:
555
+ continue
556
+ for field in contract.output_schema:
557
+ writers_by_field.setdefault(field, []).append(node_id)
558
+
559
+ for field in sorted(writers_by_field):
560
+ writers = sorted(writers_by_field[field])
561
+ # Need at least two writers to have a conflict.
562
+ if len(writers) < 2: # noqa: PLR2004 — "two" is a structural threshold, not a magic constant
563
+ continue
564
+ for i, a in enumerate(writers):
565
+ conflict = next(
566
+ (
567
+ b
568
+ for b in writers[i + 1 :]
569
+ if a not in dominators.get(b, frozenset())
570
+ and b not in dominators.get(a, frozenset())
571
+ ),
572
+ None,
573
+ )
574
+ if conflict is not None:
575
+ out.append(
576
+ f"Field '{field}' is written by both '{a}' and '{conflict}' on parallel "
577
+ f"branches; merge order is undefined.",
578
+ )
579
+ break # one warning per field is enough
580
+ return out
File without changes
@@ -0,0 +1,24 @@
1
+ """Shared persistence-layer primitives.
2
+
3
+ These helpers and the ``NotFoundError`` exception are imported by every
4
+ per-entity module (agents, pipelines, projects, runs) and re-exported
5
+ from :mod:`dap_engine.persistence.repository` for backward compat with
6
+ existing callers.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import uuid
12
+ from datetime import UTC, datetime
13
+
14
+
15
+ class NotFoundError(Exception):
16
+ """Raised when an entity is not found by id/version."""
17
+
18
+
19
+ def _now() -> datetime:
20
+ return datetime.now(UTC)
21
+
22
+
23
+ def _new_id() -> str:
24
+ return str(uuid.uuid4())