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,410 @@
1
+ """Agent persistence — CRUD on AgentORM / AgentVersionORM.
2
+
3
+ Ownership: every read / write helper takes the actor's ``user_id``
4
+ (plus an ``is_admin`` flag for the cross-user admin path). Non-admins
5
+ only see their own rows; an attempt to mutate someone else's row
6
+ raises ``NotFoundError`` (anti-enumeration — same rule the API layer
7
+ already applies for cross-user DELETE on api-tokens).
8
+
9
+ Also hosts ``pipelines_using_agent`` / ``count_pipelines_using_agents``:
10
+ those are agent-facing queries (rendered on agent endpoints) but
11
+ operate on pipeline data, so they reuse the private
12
+ ``_current_pipeline_versions`` helper from
13
+ :mod:`dap_engine.persistence.pipelines`.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import uuid
19
+ from collections.abc import Iterable, Sequence
20
+
21
+ from dap_types import Agent
22
+ from sqlalchemy import ColumnElement, func, select
23
+ from sqlalchemy.orm import Session
24
+
25
+ from dap_engine.auth.audit import record_audit_event
26
+ from dap_engine.contracts import AgentCreate, AgentUpdate
27
+ from dap_engine.persistence._common import NotFoundError, _new_id, _now
28
+ from dap_engine.persistence.models import AgentORM, AgentVersionORM, PipelineORM
29
+ from dap_engine.persistence.pipelines import _current_pipeline_versions
30
+
31
+
32
+ def _ownership_filter(
33
+ actor_id: uuid.UUID,
34
+ is_admin: bool,
35
+ ) -> list[ColumnElement[bool]]:
36
+ """Return ``[]`` for admins, else a single-clause filter for the actor.
37
+
38
+ Centralised so every list query gets the rule without copy-paste.
39
+ Admins see all rows (including legacy NULL ``user_id`` rows from
40
+ the pre-v0.3 backfill); non-admins only see rows they own.
41
+ """
42
+ if is_admin:
43
+ return []
44
+ return [AgentORM.user_id == actor_id]
45
+
46
+
47
+ def _agent_from_orm(
48
+ agent: AgentORM,
49
+ version: AgentVersionORM,
50
+ *,
51
+ is_current: bool,
52
+ ) -> Agent:
53
+ return Agent(
54
+ id=agent.id,
55
+ name=agent.name if is_current else version.name,
56
+ role=agent.role,
57
+ version=version.version,
58
+ runtime_id=version.runtime_id,
59
+ runtime_config=version.runtime_config,
60
+ prompt_template=version.prompt_template,
61
+ input_schema=version.input_schema,
62
+ output_schema=version.output_schema,
63
+ constraints=version.constraints,
64
+ budget_limit_usd=version.budget_limit_usd,
65
+ timeout_ms=version.timeout_ms,
66
+ created_at=agent.created_at,
67
+ updated_at=agent.updated_at if is_current else version.created_at,
68
+ is_active=agent.archived_at is None,
69
+ )
70
+
71
+
72
+ def create_agent(
73
+ session: Session,
74
+ payload: AgentCreate,
75
+ *,
76
+ user_id: uuid.UUID,
77
+ ) -> Agent:
78
+ """Create a new agent owned by ``user_id`` and write an audit row."""
79
+ now = _now()
80
+ agent = AgentORM(
81
+ id=_new_id(),
82
+ user_id=user_id,
83
+ name=payload.name,
84
+ role=payload.role,
85
+ current_version=1,
86
+ created_at=now,
87
+ updated_at=now,
88
+ archived_at=None,
89
+ )
90
+ version = AgentVersionORM(
91
+ id=_new_id(),
92
+ agent_id=agent.id,
93
+ version=1,
94
+ name=payload.name,
95
+ runtime_id=payload.runtime_id,
96
+ runtime_config=payload.runtime_config,
97
+ prompt_template=payload.prompt_template,
98
+ input_schema=payload.input_schema,
99
+ output_schema=payload.output_schema,
100
+ constraints=payload.constraints,
101
+ budget_limit_usd=payload.budget_limit_usd,
102
+ timeout_ms=payload.timeout_ms,
103
+ created_at=now,
104
+ )
105
+ session.add(agent)
106
+ session.add(version)
107
+ session.flush()
108
+ record_audit_event(
109
+ session,
110
+ user_id=user_id,
111
+ event_type="agent.created",
112
+ event_data={"agent_id": agent.id, "name": payload.name, "role": payload.role},
113
+ )
114
+ return _agent_from_orm(agent, version, is_current=True)
115
+
116
+
117
+ def update_agent(
118
+ session: Session,
119
+ agent_id: str,
120
+ payload: AgentUpdate,
121
+ *,
122
+ actor_id: uuid.UUID,
123
+ is_admin: bool,
124
+ ) -> Agent:
125
+ """Update an agent. Non-admins can only touch their own rows."""
126
+ agent = session.get(AgentORM, agent_id)
127
+ if agent is None or agent.archived_at is not None:
128
+ raise NotFoundError(f"Agent not found: {agent_id}")
129
+ if not is_admin and agent.user_id != actor_id:
130
+ # Anti-enumeration: cross-user lookup looks indistinguishable
131
+ # from "doesn't exist".
132
+ raise NotFoundError(f"Agent not found: {agent_id}")
133
+
134
+ now = _now()
135
+ new_version_number = agent.current_version + 1
136
+
137
+ if payload.name is not None:
138
+ agent.name = payload.name
139
+ agent.current_version = new_version_number
140
+ agent.updated_at = now
141
+
142
+ version = AgentVersionORM(
143
+ id=_new_id(),
144
+ agent_id=agent.id,
145
+ version=new_version_number,
146
+ name=agent.name,
147
+ runtime_id=payload.runtime_id,
148
+ runtime_config=payload.runtime_config,
149
+ prompt_template=payload.prompt_template,
150
+ input_schema=payload.input_schema,
151
+ output_schema=payload.output_schema,
152
+ constraints=payload.constraints,
153
+ budget_limit_usd=payload.budget_limit_usd,
154
+ timeout_ms=payload.timeout_ms,
155
+ created_at=now,
156
+ )
157
+ session.add(version)
158
+ session.flush()
159
+ record_audit_event(
160
+ session,
161
+ user_id=actor_id,
162
+ event_type="agent.updated",
163
+ event_data={"agent_id": agent.id, "version": new_version_number},
164
+ )
165
+ return _agent_from_orm(agent, version, is_current=True)
166
+
167
+
168
+ def archive_agent(
169
+ session: Session,
170
+ agent_id: str,
171
+ *,
172
+ actor_id: uuid.UUID,
173
+ is_admin: bool,
174
+ ) -> None:
175
+ """Archive an agent. Non-admins can only archive their own rows."""
176
+ agent = session.get(AgentORM, agent_id)
177
+ if agent is None:
178
+ raise NotFoundError(f"Agent not found: {agent_id}")
179
+ if not is_admin and agent.user_id != actor_id:
180
+ raise NotFoundError(f"Agent not found: {agent_id}")
181
+ if agent.archived_at is not None:
182
+ return # idempotent
183
+ agent.archived_at = _now()
184
+ session.flush()
185
+ record_audit_event(
186
+ session,
187
+ user_id=actor_id,
188
+ event_type="agent.archived",
189
+ event_data={"agent_id": agent.id},
190
+ )
191
+
192
+
193
+ def pipelines_using_agent(session: Session, agent_id: str) -> list[tuple[str, str]]:
194
+ """Return (id, name) of non-archived pipelines whose current version references the agent.
195
+
196
+ Read-only / informational — used by the "is this agent in use?"
197
+ UI hint. Doesn't filter by pipeline ownership: an admin viewing an
198
+ agent that other users embed in their pipelines should see the
199
+ full impact.
200
+
201
+ **Caller contract** — this function leaks pipeline ids/names by
202
+ design (admins need them; the UI hint needs them). Every caller
203
+ MUST gate the request on agent-level ownership *before* calling
204
+ this, otherwise a non-admin can probe foreign agent ids and get
205
+ back a structured 409 with names instead of the intended 404.
206
+ The two callers today (``GET /agents/{id}/usage`` via list
207
+ enrichment, and the ``DELETE /agents/{id}`` precheck) both call
208
+ ``get_agent(...)``/``list_agents(...)`` first to establish that
209
+ gate — sub-A4b2a wired the DELETE gate explicitly.
210
+ """
211
+ out: list[tuple[str, str]] = []
212
+ pipeline_names = {
213
+ p.id: p.name
214
+ for p in session.scalars(select(PipelineORM).where(PipelineORM.archived_at.is_(None))).all()
215
+ }
216
+ for version in _current_pipeline_versions(session):
217
+ for node in version.nodes or []:
218
+ if node.get("agent_id") == agent_id:
219
+ out.append((version.pipeline_id, pipeline_names[version.pipeline_id]))
220
+ break
221
+ return out
222
+
223
+
224
+ def count_pipelines_using_agents(
225
+ session: Session,
226
+ agent_ids: Iterable[str],
227
+ ) -> dict[str, int]:
228
+ """Batch counterpart of ``pipelines_using_agent`` for the agent list endpoint."""
229
+ target = set(agent_ids)
230
+ counts: dict[str, int] = dict.fromkeys(target, 0)
231
+ if not target:
232
+ return counts
233
+ for version in _current_pipeline_versions(session):
234
+ seen: set[str] = set()
235
+ for node in version.nodes or []:
236
+ aid = node.get("agent_id")
237
+ if aid in target and aid not in seen:
238
+ seen.add(aid)
239
+ counts[aid] += 1
240
+ return counts
241
+
242
+
243
+ def get_agent(
244
+ session: Session,
245
+ agent_id: str,
246
+ *,
247
+ actor_id: uuid.UUID,
248
+ is_admin: bool,
249
+ ) -> Agent:
250
+ """Fetch an agent. Non-admins only see their own."""
251
+ agent = session.get(AgentORM, agent_id)
252
+ if agent is None:
253
+ raise NotFoundError(f"Agent not found: {agent_id}")
254
+ if not is_admin and agent.user_id != actor_id:
255
+ raise NotFoundError(f"Agent not found: {agent_id}")
256
+ version = _get_agent_version_orm(session, agent_id, agent.current_version)
257
+ return _agent_from_orm(agent, version, is_current=True)
258
+
259
+
260
+ def get_agents_by_ids(
261
+ session: Session,
262
+ agent_ids: Iterable[str],
263
+ *,
264
+ actor_id: uuid.UUID,
265
+ is_admin: bool,
266
+ ) -> dict[str, Agent]:
267
+ """Fetch multiple agents (current version) in 2 queries total (#126).
268
+
269
+ Used by the pipeline bundle exporter, where a pipeline can
270
+ reference N agents and per-id ``get_agent`` calls would cost
271
+ ``2N`` round-trips. ``WHERE id IN (...)`` for the agent rows,
272
+ then ``WHERE agent_id IN (...)`` for the matching version rows
273
+ indexed by ``(agent_id, current_version)`` to pick each agent's
274
+ head version.
275
+
276
+ Missing ids are silently absent from the returned dict — callers
277
+ handle them however they want (404 vs skip). Non-admin actors get
278
+ only their own rows in the result; an out-of-scope id behaves like
279
+ "id doesn't exist" (anti-enumeration).
280
+ """
281
+ ids = list(agent_ids)
282
+ if not ids:
283
+ return {}
284
+ agent_query = select(AgentORM).where(AgentORM.id.in_(ids))
285
+ if not is_admin:
286
+ agent_query = agent_query.where(AgentORM.user_id == actor_id)
287
+ agent_rows = session.scalars(agent_query).all()
288
+ if not agent_rows:
289
+ return {}
290
+ version_rows = session.scalars(
291
+ select(AgentVersionORM).where(
292
+ AgentVersionORM.agent_id.in_(a.id for a in agent_rows),
293
+ ),
294
+ ).all()
295
+ versions_by_key = {(v.agent_id, v.version): v for v in version_rows}
296
+ out: dict[str, Agent] = {}
297
+ for agent in agent_rows:
298
+ version = versions_by_key.get((agent.id, agent.current_version))
299
+ if version is None:
300
+ continue
301
+ out[agent.id] = _agent_from_orm(agent, version, is_current=True)
302
+ return out
303
+
304
+
305
+ def get_agent_version(
306
+ session: Session,
307
+ agent_id: str,
308
+ version: int,
309
+ *,
310
+ actor_id: uuid.UUID,
311
+ is_admin: bool,
312
+ ) -> Agent:
313
+ agent = session.get(AgentORM, agent_id)
314
+ if agent is None:
315
+ raise NotFoundError(f"Agent not found: {agent_id}")
316
+ if not is_admin and agent.user_id != actor_id:
317
+ raise NotFoundError(f"Agent not found: {agent_id}")
318
+ version_orm = _get_agent_version_orm(session, agent_id, version)
319
+ return _agent_from_orm(agent, version_orm, is_current=version == agent.current_version)
320
+
321
+
322
+ def get_agent_template(
323
+ session: Session,
324
+ agent_id: str,
325
+ version: int | None = None,
326
+ *,
327
+ actor_id: uuid.UUID,
328
+ is_admin: bool,
329
+ ) -> str:
330
+ """Fetch the prompt_template string for an agent (current or specific version)."""
331
+ agent = session.get(AgentORM, agent_id)
332
+ if agent is None:
333
+ raise NotFoundError(f"Agent not found: {agent_id}")
334
+ if not is_admin and agent.user_id != actor_id:
335
+ raise NotFoundError(f"Agent not found: {agent_id}")
336
+ target_version = version if version is not None else agent.current_version
337
+ version_orm = _get_agent_version_orm(session, agent_id, target_version)
338
+ return version_orm.prompt_template
339
+
340
+
341
+ def list_agent_versions(
342
+ session: Session,
343
+ agent_id: str,
344
+ *,
345
+ actor_id: uuid.UUID,
346
+ is_admin: bool,
347
+ ) -> list[Agent]:
348
+ agent = session.get(AgentORM, agent_id)
349
+ if agent is None:
350
+ raise NotFoundError(f"Agent not found: {agent_id}")
351
+ if not is_admin and agent.user_id != actor_id:
352
+ raise NotFoundError(f"Agent not found: {agent_id}")
353
+ versions = session.scalars(
354
+ select(AgentVersionORM)
355
+ .where(AgentVersionORM.agent_id == agent_id)
356
+ .order_by(AgentVersionORM.version)
357
+ ).all()
358
+ return [
359
+ _agent_from_orm(agent, v, is_current=v.version == agent.current_version) for v in versions
360
+ ]
361
+
362
+
363
+ def list_agents(
364
+ session: Session,
365
+ *,
366
+ actor_id: uuid.UUID,
367
+ is_admin: bool,
368
+ role: str | None = None,
369
+ archived: bool = False,
370
+ offset: int = 0,
371
+ limit: int = 50,
372
+ ) -> tuple[Sequence[Agent], int]:
373
+ where_clauses: list[ColumnElement[bool]] = []
374
+ where_clauses.extend(_ownership_filter(actor_id, is_admin))
375
+ if not archived:
376
+ where_clauses.append(AgentORM.archived_at.is_(None))
377
+ if role is not None:
378
+ where_clauses.append(AgentORM.role == role)
379
+
380
+ total = session.scalar(select(func.count()).select_from(AgentORM).where(*where_clauses)) or 0
381
+
382
+ # JOIN on (agent_id, current_version) folds the per-row version
383
+ # lookup into the same query — single round trip, and nothing scales
384
+ # with `limit` in bind-parameter count (which a tuple-IN would).
385
+ rows = session.execute(
386
+ select(AgentORM, AgentVersionORM)
387
+ .join(
388
+ AgentVersionORM,
389
+ (AgentVersionORM.agent_id == AgentORM.id)
390
+ & (AgentVersionORM.version == AgentORM.current_version),
391
+ )
392
+ .where(*where_clauses)
393
+ .order_by(AgentORM.created_at.desc())
394
+ .offset(offset)
395
+ .limit(limit)
396
+ ).all()
397
+
398
+ items = [_agent_from_orm(agent, version, is_current=True) for agent, version in rows]
399
+ return items, total
400
+
401
+
402
+ def _get_agent_version_orm(session: Session, agent_id: str, version: int) -> AgentVersionORM:
403
+ version_orm = session.scalar(
404
+ select(AgentVersionORM)
405
+ .where(AgentVersionORM.agent_id == agent_id)
406
+ .where(AgentVersionORM.version == version)
407
+ )
408
+ if version_orm is None:
409
+ raise NotFoundError(f"Agent version not found: {agent_id}@v{version}")
410
+ return version_orm
@@ -0,0 +1,179 @@
1
+ """SQLAlchemy engine factory — SQLite (WAL mode) and PostgreSQL.
2
+
3
+ Dialect selection is driven by the ``DAP_DATABASE_URL`` env var (see
4
+ ``__main__.py``). The URL prefix determines which path is taken:
5
+
6
+ * ``sqlite://`` (or bare file path via DAP_DB_PATH) → SQLite + WAL pragmas.
7
+ Default for local dev; no extra dependencies needed.
8
+ * ``postgresql+asyncpg://`` → PostgreSQL via psycopg (sync engine). Requires
9
+ ``psycopg[binary]`` and ``langgraph-checkpoint-postgres`` (declared as
10
+ deps in pyproject.toml). The ``+asyncpg`` driver suffix is accepted for
11
+ legacy compatibility but rewritten to ``+psycopg`` before SQLAlchemy use;
12
+ the asyncpg package is not actually imported.
13
+
14
+ The rest of the engine (ORM models, repository, migrations) is dialect-agnostic
15
+ and works unchanged against both backends.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ from collections.abc import Iterator
21
+ from contextlib import contextmanager
22
+ from pathlib import Path
23
+ from typing import Literal
24
+
25
+ from sqlalchemy import Engine, create_engine, event
26
+ from sqlalchemy.orm import Session, sessionmaker
27
+
28
+ from dap_engine.persistence.migrations import apply_migrations
29
+ from dap_engine.persistence.models import Base
30
+
31
+ # ---------------------------------------------------------------------------
32
+ # Dialect helpers
33
+ # ---------------------------------------------------------------------------
34
+
35
+
36
+ def detect_dialect(url: str) -> Literal["sqlite", "postgresql"]:
37
+ """Return ``"postgresql"`` for postgres-family URLs, else ``"sqlite"``.
38
+
39
+ Accepts ``postgresql+asyncpg://``, ``postgresql+psycopg://``, bare
40
+ ``postgresql://``, and heroku-style ``postgres://`` — all routed to the
41
+ PostgreSQL branch.
42
+ """
43
+ return "postgresql" if url.startswith(("postgresql", "postgres://")) else "sqlite"
44
+
45
+
46
+ def _normalize_pg_prefix(url: str) -> str:
47
+ """Rewrite heroku-style ``postgres://`` to ``postgresql://`` for SQLAlchemy.
48
+
49
+ SQLAlchemy 1.4+ rejects the bare ``postgres://`` scheme; normalize at
50
+ consumption time so callers can pass either form.
51
+ """
52
+ if url.startswith("postgres://"):
53
+ return "postgresql://" + url[len("postgres://") :]
54
+ return url
55
+
56
+
57
+ def _pg_sync_url(database_url: str) -> str:
58
+ """Return a SQLAlchemy URL guaranteed to use psycopg v3 as the sync driver.
59
+
60
+ Normalizes ``postgres://`` to ``postgresql://``, rewrites ``+asyncpg`` to
61
+ ``+psycopg``, and forces ``+psycopg`` on bare ``postgresql://`` URLs.
62
+ The bare scheme is critical: SQLAlchemy defaults bare ``postgresql://``
63
+ to psycopg2, which is not a project dependency, so create_engine would
64
+ fail at runtime without this rewrite.
65
+ """
66
+ url = _normalize_pg_prefix(database_url)
67
+ url = url.replace("postgresql+asyncpg://", "postgresql+psycopg://", 1)
68
+ if url.startswith("postgresql://"):
69
+ url = "postgresql+psycopg://" + url[len("postgresql://") :]
70
+ return url
71
+
72
+
73
+ def pg_conn_string(database_url: str) -> str:
74
+ """Return a bare ``postgresql://`` conn string for psycopg (e.g. AsyncPostgresSaver)."""
75
+ url = _normalize_pg_prefix(database_url)
76
+ return url.replace("postgresql+asyncpg://", "postgresql://", 1).replace(
77
+ "postgresql+psycopg://", "postgresql://", 1
78
+ )
79
+
80
+
81
+ # ---------------------------------------------------------------------------
82
+ # SQLite
83
+ # ---------------------------------------------------------------------------
84
+
85
+
86
+ def _enable_sqlite_pragmas(dbapi_connection, _connection_record) -> None: # type: ignore[no-untyped-def]
87
+ cursor = dbapi_connection.cursor()
88
+ cursor.execute("PRAGMA journal_mode = WAL")
89
+ cursor.execute("PRAGMA synchronous = NORMAL")
90
+ cursor.execute("PRAGMA foreign_keys = ON")
91
+ # Allow up to 5 s of retry before raising "database is locked". Needed
92
+ # when the node executor opens a short-lived log session concurrently
93
+ # with the long-lived background session (#162).
94
+ cursor.execute("PRAGMA busy_timeout = 5000")
95
+ cursor.close()
96
+
97
+
98
+ def create_engine_for_sqlite(db_path: str) -> Engine:
99
+ absolute = Path(db_path).resolve()
100
+ absolute.parent.mkdir(parents=True, exist_ok=True)
101
+
102
+ engine = create_engine(
103
+ f"sqlite:///{absolute}",
104
+ echo=False,
105
+ future=True,
106
+ # Allow up to 10 s of busy-wait when another connection holds a write
107
+ # lock. Needed when node_executor opens a short-lived log session
108
+ # concurrently with the long-lived background session (#162).
109
+ connect_args={"timeout": 10},
110
+ )
111
+ event.listen(engine, "connect", _enable_sqlite_pragmas)
112
+
113
+ # Order matters: ``create_all`` creates any missing tables (no-op
114
+ # for existing ones, *including ones that lack columns the current
115
+ # model defines*). Then ``apply_migrations`` runs the in-code
116
+ # ALTERs (#109) that catch up older schemas to today's shape. New
117
+ # DBs see all current columns from ``create_all`` and the
118
+ # migrations are recorded as applied no-ops.
119
+ Base.metadata.create_all(engine)
120
+ apply_migrations(engine)
121
+
122
+ return engine
123
+
124
+
125
+ # ---------------------------------------------------------------------------
126
+ # PostgreSQL
127
+ # ---------------------------------------------------------------------------
128
+
129
+
130
+ def create_engine_for_postgresql(database_url: str) -> Engine:
131
+ """Create a synchronous SQLAlchemy engine for PostgreSQL.
132
+
133
+ Uses ``psycopg`` (v3) as the sync DBAPI driver. The caller supplies a URL
134
+ with the ``postgresql+asyncpg://`` scheme (used as the canonical DAP URL);
135
+ this function rewrites it to ``postgresql+psycopg://`` for the sync engine.
136
+
137
+ Pool settings for a single long-running process:
138
+ - ``pool_size=5`` — modest default.
139
+ - ``max_overflow=10`` — burst headroom.
140
+ - ``pool_pre_ping=True`` — validate connections after idle periods
141
+ (k8s NodePort is behind NAT that drops idle TCP).
142
+ """
143
+ sync_url = _pg_sync_url(database_url)
144
+
145
+ engine = create_engine(
146
+ sync_url,
147
+ echo=False,
148
+ future=True,
149
+ pool_size=5,
150
+ max_overflow=10,
151
+ pool_pre_ping=True,
152
+ )
153
+
154
+ Base.metadata.create_all(engine)
155
+ apply_migrations(engine)
156
+
157
+ return engine
158
+
159
+
160
+ # ---------------------------------------------------------------------------
161
+ # Shared helpers
162
+ # ---------------------------------------------------------------------------
163
+
164
+
165
+ def make_session_factory(engine: Engine) -> sessionmaker[Session]:
166
+ return sessionmaker(bind=engine, expire_on_commit=False, autoflush=False)
167
+
168
+
169
+ @contextmanager
170
+ def session_scope(factory: sessionmaker[Session]) -> Iterator[Session]:
171
+ session = factory()
172
+ try:
173
+ yield session
174
+ session.commit()
175
+ except Exception:
176
+ session.rollback()
177
+ raise
178
+ finally:
179
+ session.close()