Coverage for apps / backend / src / orcheo_backend / app / repository_postgres / _persistence.py: 99%
156 statements
« prev ^ index » next coverage.py v7.13.0, created at 2026-11-16 14:04 +0000
« prev ^ index » next coverage.py v7.13.0, created at 2026-11-16 14:04 +0000
1"""Low-level PostgreSQL persistence helpers."""
3from __future__ import annotations
4import json
5from collections.abc import Mapping
6from typing import Any
7from uuid import UUID
8from starlette.concurrency import run_in_threadpool
9from orcheo.models import Workflow, WorkflowRun, WorkflowRunStatus, WorkflowVersion
10from orcheo.models.workflow_refs import workflow_ref_is_uuid
11from orcheo.runtime.runnable_config import merge_runnable_configs
12from orcheo_backend.app.repository import (
13 WorkflowHandleConflictError,
14 WorkflowNotFoundError,
15 WorkflowRunNotFoundError,
16 WorkflowVersionNotFoundError,
17)
18from orcheo_backend.app.repository_postgres._base import (
19 _RUN_QUOTA_LOCK_NAMESPACE,
20 PostgresRepositoryBase,
21)
22from orcheo_backend.app.workspace import get_workspace_repository
23from orcheo_backend.app.workspace_governance import ensure_concurrent_run_capacity
26_ACTIVE_RUN_STATUSES = (
27 WorkflowRunStatus.PENDING.value,
28 WorkflowRunStatus.RUNNING.value,
29)
32class PostgresPersistenceMixin(PostgresRepositoryBase):
33 """Expose fetch helpers shared across mixins."""
35 @staticmethod
36 def _deserialize_workflow(
37 payload: dict[str, Any] | str,
38 *,
39 workspace_id: str | None = None,
40 team_id: str | None = None,
41 ) -> Workflow:
42 """Return a Workflow instance from serialized JSON."""
43 data: dict[str, Any]
44 if isinstance(payload, str): 2F a G p H tbE I J K L M N O t P u Q R S T U V v w ubvbW X Y Z 0 1 q 2 3 4 5 r 6 7 wbrbsbxbyb] 8 9 ! c # $ % ' ( ) * s f + g d m i , - . b / x : y z A ; B C = D ? @ [
45 data = json.loads(payload) 2xb
46 else:
47 data = payload 2F a G p H tbE I J K L M N O t P u Q R S T U V v w ubvbW X Y Z 0 1 q 2 3 4 5 r 6 7 wbrbsbyb] 8 9 ! c # $ % ' ( ) * s f + g d m i , - . b / x : y z A ; B C = D ? @ [
48 if workspace_id is not None: 2F a G p H tbE I J K L M N O t P u Q R S T U V v w ubvbW X Y Z 0 1 q 2 3 4 5 r 6 7 wbrbsbxbyb] 8 9 ! c # $ % ' ( ) * s f + g d m i , - . b / x : y z A ; B C = D ? @ [
49 data["workspace_id"] = workspace_id 2sb]
50 if team_id is not None: 2F a G p H tbE I J K L M N O t P u Q R S T U V v w ubvbW X Y Z 0 1 q 2 3 4 5 r 6 7 wbrbsbxbyb] 8 9 ! c # $ % ' ( ) * s f + g d m i , - . b / x : y z A ; B C = D ? @ [
51 data["team_id"] = team_id 2rb
52 return Workflow.model_validate(data) 2F a G p H tbE I J K L M N O t P u Q R S T U V v w ubvbW X Y Z 0 1 q 2 3 4 5 r 6 7 wbrbsbxbyb] 8 9 ! c # $ % ' ( ) * s f + g d m i , - . b / x : y z A ; B C = D ? @ [
54 @staticmethod
55 def _deserialize_workflow_version(
56 payload: dict[str, Any] | str, *, workspace_id: str | None = None
57 ) -> WorkflowVersion:
58 """Return a WorkflowVersion instance from serialized JSON."""
59 data: dict[str, Any]
60 if isinstance(payload, str): 2a h t u v w e k l ^ j o zb} ~ c f g d m i b x y z A B abC D Ib
61 data = json.loads(payload) 1uv}~yBD
62 else:
63 data = payload 2a h t w e k l ^ j o zbc f g d m i b x z A abC Ib
64 if workspace_id is not None: 2a h t u v w e k l ^ j o zb} ~ c f g d m i b x y z A B abC D Ib
65 data["workspace_id"] = workspace_id 2zb
66 return WorkflowVersion.model_validate(data) 2a h t u v w e k l ^ j o zb} ~ c f g d m i b x y z A B abC D Ib
68 async def _get_workflow_locked(self, workflow_id: UUID) -> Workflow:
69 async with self._connection() as conn: 2F a G p H E I J K L M N O t P u Q R S T U V v w W X Y Z 0 1 q 2 3 4 5 r 6 7 Ab] 8 9 ! c # $ % ' ( ) * Bbs f + g d m i , - . b / x : y z A ; B C = D ? @ [
70 cursor = await conn.execute( 2F a G p H E I J K L M N O t P u Q R S T U V v w W X Y Z 0 1 q 2 3 4 5 r 6 7 Ab] 8 9 ! c # $ % ' ( ) * Bbs f + g d m i , - . b / x : y z A ; B C = D ? @ [
71 "SELECT payload, workspace_id, team_id FROM workflows WHERE id = %s",
72 (str(workflow_id),),
73 )
74 row = await cursor.fetchone() 2F a G p H E I J K L M N O t P u Q R S T U V v w W X Y Z 0 1 q 2 3 4 5 r 6 7 Ab] 8 9 ! c # $ % ' ( ) * Bbs f + g d m i , - . b / x : y z A ; B C = D ? @ [
75 if row is None: 2F a G p H E I J K L M N O t P u Q R S T U V v w W X Y Z 0 1 q 2 3 4 5 r 6 7 Ab] 8 9 ! c # $ % ' ( ) * Bbs f + g d m i , - . b / x : y z A ; B C = D ? @ [
76 raise WorkflowNotFoundError(str(workflow_id)) 2AbBb
77 try: 1FaGpHEIJKLMNOtPuQRSTUVvwWXYZ01q2345r67]89!c#$%'()*sf+gdmi,-.b/x:yzA;BC=D?@[
78 workspace_id = row["workspace_id"] 1FaGpHEIJKLMNOtPuQRSTUVvwWXYZ01q2345r67]89!c#$%'()*sf+gdmi,-.b/x:yzA;BC=D?@[
79 except (KeyError, IndexError, TypeError): 1FaGpHEIJKLMNOtPuQRSTUVvwWXYZ01q2345r6789!c#$%'()*sf+gdmi,-.b/x:yzA;BC=D?@[
80 workspace_id = None 1FaGpHEIJKLMNOtPuQRSTUVvwWXYZ01q2345r6789!c#$%'()*sf+gdmi,-.b/x:yzA;BC=D?@[
81 try: 1FaGpHEIJKLMNOtPuQRSTUVvwWXYZ01q2345r67]89!c#$%'()*sf+gdmi,-.b/x:yzA;BC=D?@[
82 team_id = row["team_id"] 1FaGpHEIJKLMNOtPuQRSTUVvwWXYZ01q2345r67]89!c#$%'()*sf+gdmi,-.b/x:yzA;BC=D?@[
83 except (KeyError, IndexError, TypeError): 1FaGpHEIJKLMNOtPuQRSTUVvwWXYZ01q2345r67]89!c#$%'()*sf+gdmi,-.b/x:yzA;BC=D?@[
84 team_id = None 1FaGpHEIJKLMNOtPuQRSTUVvwWXYZ01q2345r67]89!c#$%'()*sf+gdmi,-.b/x:yzA;BC=D?@[
85 return self._deserialize_workflow( 1FaGpHEIJKLMNOtPuQRSTUVvwWXYZ01q2345r67]89!c#$%'()*sf+gdmi,-.b/x:yzA;BC=D?@[
86 row["payload"], workspace_id=workspace_id, team_id=team_id
87 )
89 async def _ensure_handle_available_locked(
90 self,
91 handle: str | None,
92 *,
93 workflow_id: UUID | None,
94 is_archived: bool,
95 workspace_id: str | None = None,
96 team_id: str | None = None,
97 ) -> None:
98 """Ensure the provided handle can be assigned within the team scope."""
99 if handle is None: 2E Mbr gbhbibjbbbNbkblb
100 return 2E MbNb
102 async with self._connection() as conn: 2r gbhbibjbbbkblb
103 if workspace_id is None: 2r gbhbibjbbbkblb
104 if workflow_id is None: 2r gbhbibjbbb
105 cursor = await conn.execute( 2gbhbibbb
106 """
107 SELECT id, is_archived
108 FROM workflows
109 WHERE handle = %s
110 AND workspace_id IS NULL
111 """,
112 (handle,),
113 )
114 else:
115 cursor = await conn.execute( 2r jb
116 """
117 SELECT id, is_archived
118 FROM workflows
119 WHERE handle = %s
120 AND workspace_id IS NULL
121 AND id != %s::uuid
122 """,
123 (handle, str(workflow_id)),
124 )
125 elif workflow_id is None: 2kblb
126 cursor = await conn.execute( 2kb
127 """
128 SELECT id, is_archived
129 FROM workflows
130 WHERE handle = %s
131 AND workspace_id = %s
132 AND COALESCE(team_id, '') = COALESCE(%s, '')
133 """,
134 (handle, workspace_id, team_id),
135 )
136 else:
137 cursor = await conn.execute( 2lb
138 """
139 SELECT id, is_archived
140 FROM workflows
141 WHERE handle = %s
142 AND workspace_id = %s
143 AND COALESCE(team_id, '') = COALESCE(%s, '')
144 AND id != %s::uuid
145 """,
146 (handle, workspace_id, team_id, str(workflow_id)),
147 )
148 rows = await cursor.fetchall() 2r gbhbibjbbbkblb
150 for row in rows: 2r gbhbibjbbbkblb
151 if not row["is_archived"]: 2gbhbbb
152 msg = f"Workflow handle '{handle}' is already in use." 2bb
153 raise WorkflowHandleConflictError(msg) 2bb
155 async def _resolve_workflow_ref_in_team_locked(
156 self,
157 normalized_ref: str,
158 *,
159 include_archived: bool,
160 workspace_id: str,
161 team_id: str,
162 ) -> UUID:
163 """Resolve a handle strictly within a single team (onboarding path)."""
164 async with self._connection() as conn: 2CbDbfb
165 cursor = await conn.execute( 2CbDbfb
166 """
167 SELECT id
168 FROM workflows
169 WHERE handle = %s
170 AND workspace_id = %s
171 AND COALESCE(team_id, '') = COALESCE(%s, '')
172 AND (%s OR is_archived = FALSE)
173 ORDER BY is_archived ASC, updated_at DESC
174 LIMIT 1
175 """,
176 (normalized_ref, workspace_id, team_id, include_archived),
177 )
178 row = await cursor.fetchone() 2CbDbfb
179 if row is not None: 2CbDbfb
180 return UUID(row["id"]) 2Cbfb
181 raise WorkflowNotFoundError(normalized_ref) 2Db
183 async def _resolve_workflow_ref_locked(
184 self,
185 workflow_ref: str,
186 *,
187 include_archived: bool = True,
188 workspace_id: str | None = None,
189 team_id: str | None = None,
190 ) -> UUID:
191 """Resolve a workflow ref using handle-first semantics."""
192 normalized_ref = workflow_ref.strip().lower() 2Jbcbfbdb_ ` eb{ |
193 if not normalized_ref: 2Jbcbfbdb_ ` eb{ |
194 raise WorkflowNotFoundError("workflow ref is empty") 2Jb
196 # Onboarding scopes resolution to one team; no global / UUID fallback.
197 if team_id is not None and workspace_id is not None: 2cbfbdb_ ` eb{ |
198 return await self._resolve_workflow_ref_in_team_locked( 2fb
199 normalized_ref,
200 include_archived=include_archived,
201 workspace_id=workspace_id,
202 team_id=team_id,
203 )
205 should_match_uuid = workflow_ref_is_uuid(normalized_ref) 2cbdb_ ` eb{ |
206 async with self._connection() as conn: 2cbdb_ ` eb{ |
207 if workspace_id is not None: 2cbdb_ ` eb{ |
208 for scope_workspace_id in (workspace_id, None): 1_`{|
209 if scope_workspace_id is None: 1_`{|
210 cursor = await conn.execute( 1_`
211 """
212 SELECT id
213 FROM workflows
214 WHERE (
215 handle = %s
216 AND workspace_id IS NULL
217 AND (%s OR is_archived = FALSE)
218 )
219 OR (
220 %s AND id = %s
221 AND workspace_id IS NULL
222 )
223 ORDER BY
224 CASE
225 WHEN handle = %s AND is_archived = FALSE THEN 0
226 WHEN handle = %s AND is_archived = TRUE THEN 1
227 ELSE 2
228 END,
229 updated_at DESC
230 LIMIT 1
231 """,
232 (
233 normalized_ref,
234 include_archived,
235 should_match_uuid,
236 normalized_ref,
237 normalized_ref,
238 normalized_ref,
239 ),
240 )
241 else:
242 cursor = await conn.execute( 1_`{|
243 """
244 SELECT w.id
245 FROM workflows w
246 LEFT JOIN teams t ON t.id = w.team_id
247 WHERE (
248 w.handle = %s
249 AND w.workspace_id = %s
250 AND (%s OR w.is_archived = FALSE)
251 )
252 OR (
253 %s AND w.id = %s
254 AND w.workspace_id = %s
255 )
256 ORDER BY
257 CASE
258 WHEN w.handle = %s
259 AND w.is_archived = FALSE THEN 0
260 WHEN w.handle = %s
261 AND w.is_archived = TRUE THEN 1
262 ELSE 2
263 END,
264 COALESCE(t.is_default, FALSE) DESC,
265 w.updated_at DESC
266 LIMIT 1
267 """,
268 (
269 normalized_ref,
270 scope_workspace_id,
271 include_archived,
272 should_match_uuid,
273 normalized_ref,
274 scope_workspace_id,
275 normalized_ref,
276 normalized_ref,
277 ),
278 )
279 row = await cursor.fetchone() 1_`{|
280 if row is not None: 1_`{|
281 return UUID(row["id"]) 1_{|
282 else:
283 cursor = await conn.execute( 2cbdbeb
284 """
285 SELECT id
286 FROM workflows
287 WHERE (
288 handle = %s
289 AND (%s OR is_archived = FALSE)
290 )
291 OR (%s AND id = %s)
292 ORDER BY
293 CASE
294 WHEN handle = %s AND is_archived = FALSE THEN 0
295 WHEN handle = %s AND is_archived = TRUE THEN 1
296 ELSE 2
297 END,
298 updated_at DESC
299 LIMIT 1
300 """,
301 (
302 normalized_ref,
303 include_archived,
304 should_match_uuid,
305 normalized_ref,
306 normalized_ref,
307 normalized_ref,
308 ),
309 )
310 row = await cursor.fetchone() 2cbdbeb
311 if row is not None: 2cbdbeb
312 return UUID(row["id"]) 2dbeb
314 raise WorkflowNotFoundError(normalized_ref) 2cb`
316 async def _get_version_locked(
317 self, version_id: UUID, *, connection: Any | None = None
318 ) -> WorkflowVersion:
319 async with self._connection(connection) as conn: 2a h e k l ^ j o Eb~ c f g d i b ab
320 cursor = await conn.execute( 2a h e k l ^ j o Eb~ c f g d i b ab
321 "SELECT payload FROM workflow_versions WHERE id = %s",
322 (str(version_id),),
323 )
324 row = await cursor.fetchone() 2a h e k l ^ j o Eb~ c f g d i b ab
325 if row is None: 2a h e k l ^ j o Eb~ c f g d i b ab
326 raise WorkflowVersionNotFoundError(str(version_id)) 2Ebi
327 payload = row["payload"] 2a h e k l ^ j o ~ c f g d b ab
328 return self._deserialize_workflow_version(payload) 2a h e k l ^ j o ~ c f g d b ab
330 async def _get_latest_version_locked(self, workflow_id: UUID) -> WorkflowVersion:
331 async with self._connection() as conn: 2a Fb} s f g d m i b
332 cursor = await conn.execute( 2a Fb} s f g d m i b
333 """
334 SELECT payload
335 FROM workflow_versions
336 WHERE workflow_id = %s
337 ORDER BY version DESC
338 LIMIT 1
339 """,
340 (str(workflow_id),),
341 )
342 row = await cursor.fetchone() 2a Fb} s f g d m i b
343 if row is None: 2a Fb} s f g d m i b
344 raise WorkflowVersionNotFoundError("latest") 2Fbs
345 payload = row["payload"] 1a}fgdmib
346 return self._deserialize_workflow_version(payload) 1a}fgdmib
348 async def _get_run_locked(self, run_id: UUID) -> WorkflowRun:
349 async with self._connection() as conn: 2p q GbmbnbobpbqbHb
350 cursor = await conn.execute( 2p q GbmbnbobpbqbHb
351 (
352 "SELECT payload, workflow_id, triggered_by, status "
353 "FROM workflow_runs WHERE id = %s"
354 ),
355 (str(run_id),),
356 )
357 row = await cursor.fetchone() 2p q GbmbnbobpbqbHb
358 if row is None: 2p q GbmbnbobpbqbHb
359 raise WorkflowRunNotFoundError(str(run_id)) 2GbHb
360 payload = row["payload"] 2p q mbnbobpbqb
361 if isinstance(payload, str): 2p q mbnbobpbqb
362 return WorkflowRun.model_validate_json(payload) 2mb
363 return WorkflowRun.model_validate(payload) 2p q nbobpbqb
365 async def _create_run_locked(
366 self,
367 *,
368 workflow_id: UUID,
369 workflow_version_id: UUID,
370 triggered_by: str,
371 input_payload: Mapping[str, Any],
372 actor: str | None,
373 runnable_config: Mapping[str, Any] | None = None,
374 workspace_id: str | None = None,
375 dispatch_requested: bool = False,
376 connection: Any | None = None,
377 ) -> WorkflowRun:
378 version = await self._get_version_locked( 1ahekl^jocb
379 workflow_version_id, connection=connection
380 )
381 if version.workflow_id != workflow_id: 1ahekl^jocb
382 raise WorkflowVersionNotFoundError(str(workflow_version_id)) 1^
383 workspace_record = None 1ahekljocb
384 if workspace_id is not None: 1ahekljocb
385 workspace_record = await run_in_threadpool( 1ek
386 lambda: get_workspace_repository().get_workspace(UUID(workspace_id))
387 )
389 config_payload: dict[str, Any] | None = None 1ahekljocb
390 if runnable_config: 1ahekljocb
391 if hasattr(runnable_config, "model_dump"): 1j
392 config_payload = runnable_config.model_dump(mode="json") # type: ignore[arg-type] 1j
393 elif isinstance(runnable_config, Mapping): # pragma: no branch
394 config_payload = dict(runnable_config)
395 merged_config = merge_runnable_configs(version.runnable_config, config_payload) 1ahekljocb
396 config_payload = merged_config.model_dump( 1ahekljocb
397 mode="json",
398 exclude_defaults=True,
399 exclude_none=True,
400 )
401 tags = ( 1ahekljocb
402 list(config_payload.get("tags", []))
403 if isinstance(config_payload, dict)
404 else []
405 )
406 callbacks = ( 1ahekljocb
407 list(config_payload.get("callbacks", []))
408 if isinstance(config_payload, dict)
409 else []
410 )
411 metadata = ( 1ahekljocb
412 dict(config_payload.get("metadata", {}))
413 if isinstance(config_payload, Mapping)
414 else {}
415 )
416 run_name = ( 1ahekljocb
417 config_payload.get("run_name")
418 if isinstance(config_payload, Mapping)
419 else None
420 )
421 run = WorkflowRun( 1ahekljocb
422 workspace_id=workspace_id,
423 workflow_id=workflow_id,
424 workflow_version_id=workflow_version_id,
425 triggered_by=triggered_by,
426 input_payload=dict(input_payload),
427 runnable_config=config_payload if isinstance(config_payload, dict) else {},
428 tags=tags,
429 callbacks=callbacks,
430 metadata=metadata,
431 run_name=run_name,
432 )
433 run.record_event(actor=actor or triggered_by, action="run_created") 1ahekljocb
435 async with self._connection(connection) as conn: 1ahekljocb
436 if workspace_id is not None and workspace_record is not None: 1ahekljocb
437 await self._ensure_run_capacity_locked( 1ek
438 conn,
439 workspace_id,
440 limit=workspace_record.quotas.max_concurrent_runs,
441 )
442 await conn.execute( 1aheljocb
443 """
444 INSERT INTO workflow_runs (
445 id,
446 workflow_id,
447 workflow_version_id,
448 status,
449 triggered_by,
450 payload,
451 created_at,
452 updated_at,
453 workspace_id,
454 dispatch_requested
455 )
456 VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
457 """,
458 (
459 str(run.id),
460 str(workflow_id),
461 str(workflow_version_id),
462 run.status.value,
463 run.triggered_by,
464 self._dump_model(run),
465 run.created_at,
466 run.updated_at,
467 workspace_id,
468 dispatch_requested,
469 ),
470 )
472 # Caller-owned transactions must finish before updating process-local state.
473 if connection is None: 473 ↛ 477line 473 didn't jump to line 477 because the condition on line 473 was always true1aheljocb
474 self._trigger_layer.track_run(workflow_id, run.id) 1aheljocb
475 if triggered_by == "cron": 1aheljcb
476 self._trigger_layer.register_cron_run(run.id) 1l
477 return run 1aheljcb
479 async def mark_run_enqueued(self, run_id: UUID) -> None:
480 """Record broker acceptance so queued work is not published again."""
481 await self._ensure_initialized() 2a h KbLbd m b
482 async with self._connection() as conn: 2a h KbLbd m b
483 await conn.execute( 2a h KbLbd m b
484 "UPDATE workflow_runs SET enqueue_confirmed = TRUE WHERE id = %s",
485 (str(run_id),),
486 )
488 async def _ensure_run_capacity_locked(
489 self, conn: Any, workspace_id: str, *, limit: int
490 ) -> None:
491 """Refuse a run when the workspace already has ``limit`` active runs.
493 Takes a transaction-scoped advisory lock first, so two processes
494 cannot both count the same free slot before either inserts.
495 """
496 await conn.execute( 1ek
497 "SELECT pg_advisory_xact_lock(%s, hashtext(%s))",
498 (_RUN_QUOTA_LOCK_NAMESPACE, workspace_id),
499 )
500 cursor = await conn.execute( 1ek
501 """
502 SELECT COUNT(*) AS active
503 FROM workflow_runs
504 WHERE workspace_id = %s
505 AND status = ANY(%s)
506 """,
507 (workspace_id, list(_ACTIVE_RUN_STATUSES)),
508 )
509 row = await cursor.fetchone() 1ek
510 ensure_concurrent_run_capacity( 1ek
511 workspace_id, active_runs=int(row["active"]), limit=limit
512 )
515__all__ = ["PostgresPersistenceMixin"]