dap-engine 0.3.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- dap_engine/__init__.py +3 -0
- dap_engine/__main__.py +80 -0
- dap_engine/api/__init__.py +0 -0
- dap_engine/api/agents.py +546 -0
- dap_engine/api/deps.py +60 -0
- dap_engine/api/health.py +20 -0
- dap_engine/api/pipelines.py +428 -0
- dap_engine/api/projects.py +191 -0
- dap_engine/api/runs.py +694 -0
- dap_engine/api/runtimes.py +29 -0
- dap_engine/api/schemas.py +331 -0
- dap_engine/api/settings.py +288 -0
- dap_engine/app.py +438 -0
- dap_engine/auth/__init__.py +23 -0
- dap_engine/auth/admin_users_routes.py +134 -0
- dap_engine/auth/api_token_routes.py +345 -0
- dap_engine/auth/api_tokens.py +147 -0
- dap_engine/auth/audit.py +91 -0
- dap_engine/auth/audit_routes.py +125 -0
- dap_engine/auth/db.py +135 -0
- dap_engine/auth/oauth.py +41 -0
- dap_engine/auth/policies.py +64 -0
- dap_engine/auth/schemas.py +37 -0
- dap_engine/auth/users.py +400 -0
- dap_engine/contracts.py +205 -0
- dap_engine/execution/__init__.py +30 -0
- dap_engine/execution/conditions.py +87 -0
- dap_engine/execution/node_executor.py +363 -0
- dap_engine/execution/output_parser.py +162 -0
- dap_engine/execution/run_orchestrator.py +213 -0
- dap_engine/execution/run_registry.py +158 -0
- dap_engine/execution/runner.py +422 -0
- dap_engine/execution/validator.py +580 -0
- dap_engine/persistence/__init__.py +0 -0
- dap_engine/persistence/_common.py +24 -0
- dap_engine/persistence/agents.py +410 -0
- dap_engine/persistence/db.py +179 -0
- dap_engine/persistence/migrations.py +739 -0
- dap_engine/persistence/models.py +569 -0
- dap_engine/persistence/pipelines.py +328 -0
- dap_engine/persistence/projects.py +256 -0
- dap_engine/persistence/repository.py +101 -0
- dap_engine/persistence/runs.py +482 -0
- dap_engine/py.typed +0 -0
- dap_engine-0.3.0.dist-info/METADATA +49 -0
- dap_engine-0.3.0.dist-info/RECORD +48 -0
- dap_engine-0.3.0.dist-info/WHEEL +4 -0
- dap_engine-0.3.0.dist-info/entry_points.txt +2 -0
|
@@ -0,0 +1,739 @@
|
|
|
1
|
+
"""In-code schema migrations (#109).
|
|
2
|
+
|
|
3
|
+
Run **after** ``Base.metadata.create_all`` in the engine lifespan.
|
|
4
|
+
|
|
5
|
+
Why this exists:
|
|
6
|
+
SQLAlchemy's ``create_all`` only creates *new* tables. It doesn't
|
|
7
|
+
ALTER existing ones, so any column added in a later release is
|
|
8
|
+
invisible on a pre-existing dev DB. We hit this with
|
|
9
|
+
``runs.project_id`` (#64); the ORM then crashed every list-runs
|
|
10
|
+
call until the operator hand-applied the ALTER.
|
|
11
|
+
|
|
12
|
+
Why not Alembic (yet):
|
|
13
|
+
At v0.x scale (single-user, SQLite, dev-grade) the few schema
|
|
14
|
+
changes per release fit comfortably in a hand-written list. The
|
|
15
|
+
intent is to switch to Alembic once schema stabilises and we get
|
|
16
|
+
a second deployment that needs migrations applied independently
|
|
17
|
+
— see #109 for the rationale.
|
|
18
|
+
|
|
19
|
+
Contract for new migrations:
|
|
20
|
+
- Pure SQL, idempotent. ``ALTER TABLE … IF NOT EXISTS`` doesn't
|
|
21
|
+
exist in SQLite — guard with ``_column_exists`` (which uses
|
|
22
|
+
SQLAlchemy's ``Inspector``, not f-string PRAGMA) before the
|
|
23
|
+
ALTER instead.
|
|
24
|
+
- Forward-only. We don't track down-migrations.
|
|
25
|
+
- Append to :data:`MIGRATIONS` in order. Names are stable string
|
|
26
|
+
keys recorded in ``schema_migrations``; never rename a name once
|
|
27
|
+
it ships, or operators will re-run the migration on next start.
|
|
28
|
+
- Each migration runs in its own transaction with an atomic
|
|
29
|
+
INSERT OR IGNORE claim on its name, so concurrent engine
|
|
30
|
+
instances racing the same SQLite file don't double-apply.
|
|
31
|
+
A failure rolls the transaction back (including the claim)
|
|
32
|
+
and stops lifespan startup loudly.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
from __future__ import annotations
|
|
36
|
+
|
|
37
|
+
import logging
|
|
38
|
+
from collections.abc import Callable
|
|
39
|
+
from dataclasses import dataclass
|
|
40
|
+
from datetime import UTC, datetime
|
|
41
|
+
|
|
42
|
+
from sqlalchemy import Connection, Engine, inspect, text
|
|
43
|
+
|
|
44
|
+
logger = logging.getLogger("dap.engine.migrations")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass(frozen=True)
|
|
48
|
+
class Migration:
|
|
49
|
+
"""One named, idempotent schema change."""
|
|
50
|
+
|
|
51
|
+
name: str
|
|
52
|
+
apply: Callable[[Connection], None]
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _column_exists(conn: Connection, table: str, column: str) -> bool:
|
|
56
|
+
"""Whether ``column`` exists on ``table`` according to the live schema.
|
|
57
|
+
|
|
58
|
+
Uses SQLAlchemy's ``Inspector`` rather than f-string interpolating
|
|
59
|
+
a ``PRAGMA table_info(<table>)`` — table/column names landing in
|
|
60
|
+
SQL via string formatting are an identifier-injection footgun and
|
|
61
|
+
don't survive reserved words / special chars. ``Inspector`` also
|
|
62
|
+
abstracts the dialect so the helper can be reused if we ever
|
|
63
|
+
target Postgres. Returns ``False`` when the table doesn't exist
|
|
64
|
+
(rather than raising) so a migration can guard "ADD COLUMN" with
|
|
65
|
+
a single check.
|
|
66
|
+
"""
|
|
67
|
+
inspector = inspect(conn)
|
|
68
|
+
if not inspector.has_table(table):
|
|
69
|
+
return False
|
|
70
|
+
return any(col["name"].lower() == column.lower() for col in inspector.get_columns(table))
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
# ---------------------------------------------------------------------------
|
|
74
|
+
# Migration list — append-only. Don't rename existing names.
|
|
75
|
+
# ---------------------------------------------------------------------------
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _001_runs_add_project_id(conn: Connection) -> None:
|
|
79
|
+
"""Backfill #64 — add ``runs.project_id`` on pre-v0.6 dev DBs.
|
|
80
|
+
|
|
81
|
+
The column was introduced in #64 but the engine relied on
|
|
82
|
+
``create_all`` to apply it, which silently no-ops on an existing
|
|
83
|
+
table. Operators saw ``OperationalError: no such column:
|
|
84
|
+
runs.project_id`` until they ran a manual ALTER. This migration
|
|
85
|
+
makes that automatic on next startup.
|
|
86
|
+
|
|
87
|
+
Fresh DBs already have the column from ``create_all`` — guard
|
|
88
|
+
keeps this migration a no-op there. The recorded ``applied_at``
|
|
89
|
+
in ``schema_migrations`` is still useful as a paper trail.
|
|
90
|
+
"""
|
|
91
|
+
if _column_exists(conn, "runs", "project_id"):
|
|
92
|
+
return
|
|
93
|
+
# SQLite ALTER TABLE … ADD COLUMN can't include REFERENCES on
|
|
94
|
+
# an existing table — the FK constraint would only apply if
|
|
95
|
+
# declared at table creation. We accept that for the backfill;
|
|
96
|
+
# project_id existence is validated by the API layer
|
|
97
|
+
# (api/runs.py — POST /runs returns 422 when the project
|
|
98
|
+
# doesn't exist or is archived) before the row ever reaches
|
|
99
|
+
# the repository.
|
|
100
|
+
conn.execute(text("ALTER TABLE runs ADD COLUMN project_id TEXT"))
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _002_node_execution_logs_add_extra_data(conn: Connection) -> None:
|
|
104
|
+
"""#145 — add ``node_execution_logs.extra_data`` for python-func audit payloads."""
|
|
105
|
+
if _column_exists(conn, "node_execution_logs", "extra_data"):
|
|
106
|
+
return
|
|
107
|
+
conn.execute(text("ALTER TABLE node_execution_logs ADD COLUMN extra_data TEXT"))
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _003_pipeline_versions_add_ui_metadata(conn: Connection) -> None:
|
|
111
|
+
"""#226 — add ``pipeline_versions.ui_metadata`` for dashboard node positions.
|
|
112
|
+
|
|
113
|
+
SQLite stores JSON as TEXT (the JSON ORM type is a thin wrapper around
|
|
114
|
+
TEXT on SQLite). PostgreSQL has a native JSON/JSONB type; use JSONB so
|
|
115
|
+
the column type matches the ORM mapping and enables native JSON queries.
|
|
116
|
+
"""
|
|
117
|
+
if _column_exists(conn, "pipeline_versions", "ui_metadata"):
|
|
118
|
+
return
|
|
119
|
+
dialect = conn.dialect.name
|
|
120
|
+
col_type = "JSONB" if dialect == "postgresql" else "TEXT"
|
|
121
|
+
conn.execute(text(f"ALTER TABLE pipeline_versions ADD COLUMN ui_metadata {col_type}"))
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _004_runs_index_started_at(conn: Connection) -> None:
|
|
125
|
+
"""#251 — index for ``list_runs`` ORDER BY ``started_at DESC``.
|
|
126
|
+
|
|
127
|
+
The list endpoint sorts the runs table on every page and currently
|
|
128
|
+
forces a full scan + sort. Both SQLite and PostgreSQL can walk the
|
|
129
|
+
index backward, so an ASC index is sufficient and dialect-portable.
|
|
130
|
+
"""
|
|
131
|
+
conn.execute(text("CREATE INDEX IF NOT EXISTS ix_runs_started_at ON runs (started_at)"))
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _005_runs_index_project_started(conn: Connection) -> None:
|
|
135
|
+
"""#251 — composite index for the project-scoped runs view.
|
|
136
|
+
|
|
137
|
+
``WHERE project_id = ? ORDER BY started_at DESC`` is the most
|
|
138
|
+
common shape (project detail page). Leading with ``project_id``
|
|
139
|
+
lets SQLite — which can't bitmap-intersect single-column indexes —
|
|
140
|
+
satisfy filter and sort in one index walk.
|
|
141
|
+
"""
|
|
142
|
+
conn.execute(
|
|
143
|
+
text("CREATE INDEX IF NOT EXISTS ix_runs_project_started ON runs (project_id, started_at)")
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _006_node_execution_logs_index_run_started(conn: Connection) -> None:
|
|
148
|
+
"""#251 — composite index for ``get_run`` log fan-out.
|
|
149
|
+
|
|
150
|
+
``GET /runs/{id}`` joins ``node_execution_logs`` on every call to
|
|
151
|
+
populate per-node statuses (#233). High-frequency polling hammers
|
|
152
|
+
this table; the composite supports both the ``WHERE run_id = ?``
|
|
153
|
+
lookup and the ``ORDER BY started_at`` in one index.
|
|
154
|
+
"""
|
|
155
|
+
conn.execute(
|
|
156
|
+
text(
|
|
157
|
+
"CREATE INDEX IF NOT EXISTS ix_node_execution_logs_run_started "
|
|
158
|
+
"ON node_execution_logs (run_id, started_at)"
|
|
159
|
+
)
|
|
160
|
+
)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _007_runs_index_pipeline_started(conn: Connection) -> None:
|
|
164
|
+
"""#251 — composite index for the per-pipeline runs view.
|
|
165
|
+
|
|
166
|
+
Mirror of ``_005_runs_index_project_started`` for the pipeline-
|
|
167
|
+
scoped query (``WHERE pipeline_id = ? ORDER BY started_at DESC``)
|
|
168
|
+
rendered by the pipeline detail page.
|
|
169
|
+
"""
|
|
170
|
+
conn.execute(
|
|
171
|
+
text(
|
|
172
|
+
"CREATE INDEX IF NOT EXISTS ix_runs_pipeline_started ON runs (pipeline_id, started_at)"
|
|
173
|
+
)
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _008_runs_add_failure_reason(conn: Connection) -> None:
|
|
178
|
+
"""#260 — add ``runs.failure_reason`` for stale-recovery diagnostics.
|
|
179
|
+
|
|
180
|
+
Replaces the synthetic ``__shutdown__`` snapshot pattern with a
|
|
181
|
+
dedicated nullable column. Existing dev DBs need the ALTER on
|
|
182
|
+
next startup; fresh DBs already have the column from
|
|
183
|
+
``create_all``, so the guard keeps this a no-op there.
|
|
184
|
+
"""
|
|
185
|
+
if _column_exists(conn, "runs", "failure_reason"):
|
|
186
|
+
return
|
|
187
|
+
conn.execute(text("ALTER TABLE runs ADD COLUMN failure_reason TEXT"))
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _009_create_users_table(conn: Connection) -> None:
|
|
191
|
+
"""v0.3 / #299 — create the ``users`` table for fastapi-users.
|
|
192
|
+
|
|
193
|
+
Fresh DBs already have this table from ``Base.metadata.create_all``
|
|
194
|
+
(the ORM mapping landed in this release alongside the migration).
|
|
195
|
+
The migration backstops upgrades from pre-v0.3 dev DBs and records
|
|
196
|
+
the schema version for paper trail.
|
|
197
|
+
|
|
198
|
+
Columns mirror ``SQLAlchemyBaseUserTableUUID`` (id, email,
|
|
199
|
+
hashed_password, is_active, is_superuser, is_verified) plus the
|
|
200
|
+
extensions defined on ``UserORM`` (created_at, updated_at,
|
|
201
|
+
deleted_at, last_login_at). The unique-email index is created
|
|
202
|
+
explicitly because SQLite's CREATE TABLE … UNIQUE inline doesn't
|
|
203
|
+
produce a named index that we can grep for in operations.
|
|
204
|
+
"""
|
|
205
|
+
inspector = inspect(conn)
|
|
206
|
+
if inspector.has_table("users"):
|
|
207
|
+
return
|
|
208
|
+
|
|
209
|
+
# Dialect-aware DDL: PostgreSQL gets a real UUID column and TIMESTAMPTZ
|
|
210
|
+
# so the type matches the ``DateTime(timezone=True)`` ORM mapping; SQLite
|
|
211
|
+
# uses CHAR(36) + TIMESTAMP because it lacks both native types and
|
|
212
|
+
# treats them as TEXT internally either way.
|
|
213
|
+
dialect = conn.dialect.name
|
|
214
|
+
if dialect == "postgresql":
|
|
215
|
+
id_type = "UUID"
|
|
216
|
+
ts_type = "TIMESTAMPTZ"
|
|
217
|
+
else:
|
|
218
|
+
id_type = "CHAR(36)"
|
|
219
|
+
ts_type = "TIMESTAMP"
|
|
220
|
+
|
|
221
|
+
conn.execute(
|
|
222
|
+
text(
|
|
223
|
+
f"""
|
|
224
|
+
CREATE TABLE users (
|
|
225
|
+
id {id_type} NOT NULL PRIMARY KEY,
|
|
226
|
+
email VARCHAR(320) NOT NULL,
|
|
227
|
+
hashed_password VARCHAR(1024) NOT NULL,
|
|
228
|
+
is_active BOOLEAN NOT NULL,
|
|
229
|
+
is_superuser BOOLEAN NOT NULL,
|
|
230
|
+
is_verified BOOLEAN NOT NULL,
|
|
231
|
+
created_at {ts_type} NOT NULL,
|
|
232
|
+
updated_at {ts_type} NOT NULL,
|
|
233
|
+
deleted_at {ts_type} NULL,
|
|
234
|
+
last_login_at {ts_type} NULL
|
|
235
|
+
)
|
|
236
|
+
"""
|
|
237
|
+
)
|
|
238
|
+
)
|
|
239
|
+
conn.execute(text("CREATE UNIQUE INDEX ix_users_email ON users (email)"))
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def _010_create_oauth_accounts_table(conn: Connection) -> None:
|
|
243
|
+
"""v0.3 / #299 — create the ``oauth_accounts`` table for fastapi-users.
|
|
244
|
+
|
|
245
|
+
Mirrors the ORM mapping in ``OAuthAccountORM``. As with migration 9,
|
|
246
|
+
fresh DBs already have the table from ``Base.metadata.create_all``;
|
|
247
|
+
this migration backstops upgrades from pre-OAuth dev DBs.
|
|
248
|
+
|
|
249
|
+
Indexes are created unconditionally with ``IF NOT EXISTS`` —
|
|
250
|
+
``create_all`` runs first but only creates indexes for *new* tables,
|
|
251
|
+
so a DB that was upgraded incrementally could end up with the table
|
|
252
|
+
but no indexes. The ``IF NOT EXISTS`` guards make the index creates
|
|
253
|
+
a cheap no-op on fresh DBs that already have them from the ORM.
|
|
254
|
+
"""
|
|
255
|
+
inspector = inspect(conn)
|
|
256
|
+
if not inspector.has_table("oauth_accounts"):
|
|
257
|
+
dialect = conn.dialect.name
|
|
258
|
+
id_type = "UUID" if dialect == "postgresql" else "CHAR(36)"
|
|
259
|
+
conn.execute(
|
|
260
|
+
text(
|
|
261
|
+
f"""
|
|
262
|
+
CREATE TABLE oauth_accounts (
|
|
263
|
+
id {id_type} NOT NULL PRIMARY KEY,
|
|
264
|
+
user_id {id_type} NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
265
|
+
oauth_name VARCHAR(100) NOT NULL,
|
|
266
|
+
access_token VARCHAR(1024) NOT NULL,
|
|
267
|
+
expires_at INTEGER NULL,
|
|
268
|
+
refresh_token VARCHAR(1024) NULL,
|
|
269
|
+
account_id VARCHAR(320) NOT NULL,
|
|
270
|
+
account_email VARCHAR(320) NOT NULL
|
|
271
|
+
)
|
|
272
|
+
"""
|
|
273
|
+
)
|
|
274
|
+
)
|
|
275
|
+
|
|
276
|
+
conn.execute(
|
|
277
|
+
text("CREATE INDEX IF NOT EXISTS ix_oauth_accounts_user_id ON oauth_accounts (user_id)")
|
|
278
|
+
)
|
|
279
|
+
conn.execute(
|
|
280
|
+
text(
|
|
281
|
+
"CREATE INDEX IF NOT EXISTS ix_oauth_accounts_provider_account "
|
|
282
|
+
"ON oauth_accounts (oauth_name, account_id)"
|
|
283
|
+
)
|
|
284
|
+
)
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def _012_add_user_id_to_resources(conn: Connection) -> None:
|
|
288
|
+
"""v0.3 / #299 (sub-A4a) — add nullable ``user_id`` to resource tables.
|
|
289
|
+
|
|
290
|
+
Adds the column on ``agents``, ``pipelines``, ``projects``, ``runs``
|
|
291
|
+
so the schema is ready for the ownership enforcement that lands in
|
|
292
|
+
sub-A4b. The column is nullable here because:
|
|
293
|
+
1. SQLite ``ALTER TABLE … ADD COLUMN`` can't add a NOT NULL
|
|
294
|
+
column without a DEFAULT, and we don't have a system-user UUID
|
|
295
|
+
to default to until #13 runs.
|
|
296
|
+
2. The backfill (#13) populates *existing* rows; the
|
|
297
|
+
application-layer contract that "every new row sets user_id"
|
|
298
|
+
is enforced by the route handlers (sub-A4b), not the schema.
|
|
299
|
+
|
|
300
|
+
PostgreSQL gets the same nullable shape so the two backends match.
|
|
301
|
+
The follow-up sub-PR can ALTER COLUMN SET NOT NULL on PG once the
|
|
302
|
+
contract is wired through; SQLite leaves it nullable forever
|
|
303
|
+
because that dialect has no equivalent ALTER.
|
|
304
|
+
|
|
305
|
+
Index creation runs **unconditionally** with ``IF NOT EXISTS``,
|
|
306
|
+
separately from the ADD COLUMN guard. Otherwise on a fresh DB —
|
|
307
|
+
where ``Base.metadata.create_all`` already created the column — the
|
|
308
|
+
early-skip branch would also skip the indexes, leaving fresh
|
|
309
|
+
installs without ``ix_*_user_id`` (the ORM only declares those
|
|
310
|
+
indexes on three of the four tables; ``RunORM`` deliberately does
|
|
311
|
+
not, so the index would be missing entirely otherwise).
|
|
312
|
+
|
|
313
|
+
PostgreSQL upgrades additionally need an explicit FK constraint:
|
|
314
|
+
``ALTER TABLE ADD COLUMN`` (without REFERENCES) leaves the column
|
|
315
|
+
integrity-checkless even though the ORM declares a ForeignKey.
|
|
316
|
+
SQLite ignores trailing FK clauses, but to keep the migration
|
|
317
|
+
dialect-correct we only emit the ALTER on PostgreSQL.
|
|
318
|
+
"""
|
|
319
|
+
dialect = conn.dialect.name
|
|
320
|
+
id_type = "UUID" if dialect == "postgresql" else "CHAR(36)"
|
|
321
|
+
|
|
322
|
+
for table in ("agents", "pipelines", "projects", "runs"):
|
|
323
|
+
if not _column_exists(conn, table, "user_id"):
|
|
324
|
+
conn.execute(text(f"ALTER TABLE {table} ADD COLUMN user_id {id_type} NULL"))
|
|
325
|
+
if dialect == "postgresql":
|
|
326
|
+
# SQLite can't add an FK to an existing column; on PG we
|
|
327
|
+
# tighten the constraint to match the ORM mapping
|
|
328
|
+
# (ondelete=CASCADE). Constraint naming is explicit so
|
|
329
|
+
# operators can drop / recreate it without guessing the
|
|
330
|
+
# generated identifier.
|
|
331
|
+
conn.execute(
|
|
332
|
+
text(
|
|
333
|
+
f"ALTER TABLE {table} ADD CONSTRAINT fk_{table}_user_id "
|
|
334
|
+
"FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE"
|
|
335
|
+
)
|
|
336
|
+
)
|
|
337
|
+
# Indexes always — IF NOT EXISTS makes this a cheap no-op when
|
|
338
|
+
# create_all already produced them on a fresh DB, and a real
|
|
339
|
+
# backstop for older dev DBs upgrading through this migration.
|
|
340
|
+
conn.execute(text(f"CREATE INDEX IF NOT EXISTS ix_{table}_user_id ON {table} (user_id)"))
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def _013_backfill_user_id_via_system_user(conn: Connection) -> None:
|
|
344
|
+
"""v0.3 / #299 (sub-A4a) — backfill resource ownership.
|
|
345
|
+
|
|
346
|
+
For each resource table with NULL ``user_id`` rows (i.e. data that
|
|
347
|
+
pre-dates v0.3), set ``user_id`` to a synthetic ``system@local``
|
|
348
|
+
user that's created on-the-fly if missing. The user is flagged
|
|
349
|
+
``is_superuser=True`` so admins listing resources see the legacy
|
|
350
|
+
rows, plus ``is_active=False`` and a random unrecoverable password
|
|
351
|
+
so **nobody can log in as system@local directly**. To re-assign
|
|
352
|
+
ownership, an admin signs in with their own real account
|
|
353
|
+
(after Phase B's dashboard auth flow ships) and reassigns the
|
|
354
|
+
legacy resources via the admin panel (Phase C).
|
|
355
|
+
|
|
356
|
+
Skipped entirely on a fresh DB where every resource table is
|
|
357
|
+
empty — the system user only materialises when something actually
|
|
358
|
+
needs claiming.
|
|
359
|
+
"""
|
|
360
|
+
# Detect whether any backfill is needed.
|
|
361
|
+
has_orphans = False
|
|
362
|
+
for table in ("agents", "pipelines", "projects", "runs"):
|
|
363
|
+
if not _column_exists(conn, table, "user_id"):
|
|
364
|
+
continue
|
|
365
|
+
result = conn.execute(text(f"SELECT 1 FROM {table} WHERE user_id IS NULL LIMIT 1"))
|
|
366
|
+
if result.first() is not None:
|
|
367
|
+
has_orphans = True
|
|
368
|
+
break
|
|
369
|
+
if not has_orphans:
|
|
370
|
+
return
|
|
371
|
+
|
|
372
|
+
# Find or create the system user. We can't use the ORM here (the
|
|
373
|
+
# in-code migration runs against a raw SQLAlchemy Connection), so
|
|
374
|
+
# SELECT-then-INSERT with the email as a uniqueness key.
|
|
375
|
+
import secrets # noqa: PLC0415 — local; migrations import lazily
|
|
376
|
+
|
|
377
|
+
SYSTEM_EMAIL = "system@local"
|
|
378
|
+
existing = conn.execute(
|
|
379
|
+
text("SELECT id FROM users WHERE email = :email"),
|
|
380
|
+
{"email": SYSTEM_EMAIL},
|
|
381
|
+
).first()
|
|
382
|
+
if existing is None:
|
|
383
|
+
# Hash a random throwaway password — fastapi-users uses pwdlib
|
|
384
|
+
# / argon2 by default, but the migration has no easy access to
|
|
385
|
+
# that. Storing a plain-random sha256 keeps the column non-NULL
|
|
386
|
+
# without ever being a valid login (no UserManager will accept
|
|
387
|
+
# it since the row is also is_active=False).
|
|
388
|
+
import hashlib # noqa: PLC0415
|
|
389
|
+
import uuid as _uuid # noqa: PLC0415
|
|
390
|
+
|
|
391
|
+
system_id = str(_uuid.uuid4())
|
|
392
|
+
random_secret = secrets.token_urlsafe(32)
|
|
393
|
+
random_hash = hashlib.sha256(random_secret.encode()).hexdigest()
|
|
394
|
+
now = datetime.now(UTC).isoformat()
|
|
395
|
+
conn.execute(
|
|
396
|
+
text(
|
|
397
|
+
"""
|
|
398
|
+
INSERT INTO users (
|
|
399
|
+
id, email, hashed_password,
|
|
400
|
+
is_active, is_superuser, is_verified,
|
|
401
|
+
created_at, updated_at, deleted_at, last_login_at
|
|
402
|
+
) VALUES (
|
|
403
|
+
:id, :email, :pw,
|
|
404
|
+
:is_active, :is_superuser, :is_verified,
|
|
405
|
+
:created_at, :updated_at, NULL, NULL
|
|
406
|
+
)
|
|
407
|
+
"""
|
|
408
|
+
),
|
|
409
|
+
{
|
|
410
|
+
"id": system_id,
|
|
411
|
+
"email": SYSTEM_EMAIL,
|
|
412
|
+
"pw": random_hash,
|
|
413
|
+
"is_active": False,
|
|
414
|
+
"is_superuser": True,
|
|
415
|
+
"is_verified": True,
|
|
416
|
+
"created_at": now,
|
|
417
|
+
"updated_at": now,
|
|
418
|
+
},
|
|
419
|
+
)
|
|
420
|
+
logger.warning(
|
|
421
|
+
"Backfilled %s for legacy ownership claims on pre-v0.3 resources. "
|
|
422
|
+
"Password is unrecoverable — sign in as an admin and re-assign "
|
|
423
|
+
"ownership via /admin/users (Phase C) or hard-delete the row.",
|
|
424
|
+
SYSTEM_EMAIL,
|
|
425
|
+
)
|
|
426
|
+
else:
|
|
427
|
+
system_id = str(existing[0])
|
|
428
|
+
|
|
429
|
+
for table in ("agents", "pipelines", "projects", "runs"):
|
|
430
|
+
if not _column_exists(conn, table, "user_id"):
|
|
431
|
+
continue
|
|
432
|
+
conn.execute(
|
|
433
|
+
text(f"UPDATE {table} SET user_id = :uid WHERE user_id IS NULL"),
|
|
434
|
+
{"uid": system_id},
|
|
435
|
+
)
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
def _014_create_audit_log_table(conn: Connection) -> None:
|
|
439
|
+
"""v0.3 / #299 (sub-A4a) — create the ``audit_log`` table.
|
|
440
|
+
|
|
441
|
+
Matches ``AuditLogORM``. Append-only; no FK to ``users`` so an audit
|
|
442
|
+
row survives hard-deletion of the actor (audit integrity > referential
|
|
443
|
+
cleanliness — see ORM docstring).
|
|
444
|
+
|
|
445
|
+
Same idempotent IF-NOT-EXISTS index pattern as migrations 10 + 11.
|
|
446
|
+
"""
|
|
447
|
+
inspector = inspect(conn)
|
|
448
|
+
if not inspector.has_table("audit_log"):
|
|
449
|
+
dialect = conn.dialect.name
|
|
450
|
+
id_type = "UUID" if dialect == "postgresql" else "CHAR(36)"
|
|
451
|
+
ts_type = "TIMESTAMPTZ" if dialect == "postgresql" else "TIMESTAMP"
|
|
452
|
+
json_type = "JSONB" if dialect == "postgresql" else "TEXT"
|
|
453
|
+
conn.execute(
|
|
454
|
+
text(
|
|
455
|
+
f"""
|
|
456
|
+
CREATE TABLE audit_log (
|
|
457
|
+
id {id_type} NOT NULL PRIMARY KEY,
|
|
458
|
+
user_id {id_type} NULL,
|
|
459
|
+
event_type VARCHAR(100) NOT NULL,
|
|
460
|
+
event_data {json_type} NULL,
|
|
461
|
+
created_at {ts_type} NOT NULL
|
|
462
|
+
)
|
|
463
|
+
"""
|
|
464
|
+
)
|
|
465
|
+
)
|
|
466
|
+
conn.execute(
|
|
467
|
+
text(
|
|
468
|
+
"CREATE INDEX IF NOT EXISTS ix_audit_log_user_event ON audit_log (user_id, event_type)"
|
|
469
|
+
)
|
|
470
|
+
)
|
|
471
|
+
conn.execute(
|
|
472
|
+
text("CREATE INDEX IF NOT EXISTS ix_audit_log_created_at ON audit_log (created_at)")
|
|
473
|
+
)
|
|
474
|
+
|
|
475
|
+
|
|
476
|
+
def _011_create_api_tokens_table(conn: Connection) -> None:
|
|
477
|
+
"""v0.3 / #299 — create the ``api_tokens`` table for CLI / script auth.
|
|
478
|
+
|
|
479
|
+
Mirrors the ORM mapping in ``ApiTokenORM``. The token-prefix index
|
|
480
|
+
is the hot path: every authenticated CLI call looks up by prefix
|
|
481
|
+
first, then SHA-256-verifies the candidate hash. The user_id index
|
|
482
|
+
supports the ``GET /auth/api-tokens`` listing endpoint (admin view
|
|
483
|
+
or per-user).
|
|
484
|
+
|
|
485
|
+
Same idempotency pattern as migration 10 — fresh DBs already have
|
|
486
|
+
the table from ``create_all``; this migration backstops upgrades
|
|
487
|
+
and ensures indexes exist either way.
|
|
488
|
+
"""
|
|
489
|
+
inspector = inspect(conn)
|
|
490
|
+
if not inspector.has_table("api_tokens"):
|
|
491
|
+
dialect = conn.dialect.name
|
|
492
|
+
id_type = "UUID" if dialect == "postgresql" else "CHAR(36)"
|
|
493
|
+
ts_type = "TIMESTAMPTZ" if dialect == "postgresql" else "TIMESTAMP"
|
|
494
|
+
conn.execute(
|
|
495
|
+
text(
|
|
496
|
+
f"""
|
|
497
|
+
CREATE TABLE api_tokens (
|
|
498
|
+
id {id_type} NOT NULL PRIMARY KEY,
|
|
499
|
+
user_id {id_type} NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
500
|
+
name VARCHAR(255) NOT NULL,
|
|
501
|
+
token_prefix VARCHAR(8) NOT NULL,
|
|
502
|
+
token_hash VARCHAR(64) NOT NULL,
|
|
503
|
+
created_at {ts_type} NOT NULL,
|
|
504
|
+
expires_at {ts_type} NULL,
|
|
505
|
+
last_used_at {ts_type} NULL,
|
|
506
|
+
revoked_at {ts_type} NULL
|
|
507
|
+
)
|
|
508
|
+
"""
|
|
509
|
+
)
|
|
510
|
+
)
|
|
511
|
+
|
|
512
|
+
conn.execute(
|
|
513
|
+
text("CREATE INDEX IF NOT EXISTS ix_api_tokens_token_prefix ON api_tokens (token_prefix)")
|
|
514
|
+
)
|
|
515
|
+
conn.execute(text("CREATE INDEX IF NOT EXISTS ix_api_tokens_user_id ON api_tokens (user_id)"))
|
|
516
|
+
|
|
517
|
+
|
|
518
|
+
def _015_promote_system_user_to_legacy_admin(conn: Connection) -> None:
|
|
519
|
+
"""v0.3 / #343 (sub-E1) — finish the pre-v0.3 upgrade story.
|
|
520
|
+
|
|
521
|
+
Migration ``013`` created a synthetic ``system@local`` user as a
|
|
522
|
+
*backfill anchor* — inactive, unrecoverable password, just enough
|
|
523
|
+
to satisfy the application-layer ownership contract (the
|
|
524
|
+
``user_id`` column itself is nullable on the SQL side — SQLite
|
|
525
|
+
can't ALTER COLUMN to NOT NULL — but the route handlers refuse
|
|
526
|
+
to insert NULL going forward; see migration 012). That left
|
|
527
|
+
operators upgrading from 0.0.1 with no way to actually log in to
|
|
528
|
+
the multi-user instance — every resource was owned by an
|
|
529
|
+
unreachable account.
|
|
530
|
+
|
|
531
|
+
This migration finishes the job: promote ``system@local`` to
|
|
532
|
+
``legacy-admin@local`` with a freshly-generated, *usable*
|
|
533
|
+
Argon2id-hashed password and set the row active. Resource
|
|
534
|
+
ownership stays linked through the same user id — no second
|
|
535
|
+
UPDATE pass on the resource tables.
|
|
536
|
+
|
|
537
|
+
Output split (Copilot review of sub-E1):
|
|
538
|
+
- ``print()`` writes the password to **stdout** — captured once
|
|
539
|
+
by an interactive operator.
|
|
540
|
+
- ``logger.warning()`` writes a follow-up note *without* the
|
|
541
|
+
password to the engine's normal log channel — long-lived log
|
|
542
|
+
aggregation never contains the secret, but oncall still gets
|
|
543
|
+
a heads-up to look at stdout.
|
|
544
|
+
|
|
545
|
+
Idempotent: if the row was already promoted (e.g. re-running
|
|
546
|
+
migrations), or if ``legacy-admin@local`` already exists from a
|
|
547
|
+
fresh ``dap init``, this migration skips.
|
|
548
|
+
|
|
549
|
+
Fresh installs (no orphan resources → no ``system@local`` was ever
|
|
550
|
+
created by 013) also skip — they get their admin from
|
|
551
|
+
``dap init`` instead.
|
|
552
|
+
"""
|
|
553
|
+
import secrets # noqa: PLC0415 — lazy, like 013
|
|
554
|
+
|
|
555
|
+
from fastapi_users.password import PasswordHelper # noqa: PLC0415
|
|
556
|
+
|
|
557
|
+
legacy_email = "legacy-admin@local"
|
|
558
|
+
system_email = "system@local"
|
|
559
|
+
|
|
560
|
+
# If a legacy admin already exists (re-run, or someone ran
|
|
561
|
+
# ``dap init --admin-email=legacy-admin@local``), bow out.
|
|
562
|
+
legacy = conn.execute(
|
|
563
|
+
text("SELECT id FROM users WHERE email = :email"),
|
|
564
|
+
{"email": legacy_email},
|
|
565
|
+
).first()
|
|
566
|
+
if legacy is not None:
|
|
567
|
+
return
|
|
568
|
+
|
|
569
|
+
# No system user → either fresh install, or someone already
|
|
570
|
+
# promoted the row. Either way, nothing to do.
|
|
571
|
+
system_user = conn.execute(
|
|
572
|
+
text("SELECT id FROM users WHERE email = :email"),
|
|
573
|
+
{"email": system_email},
|
|
574
|
+
).first()
|
|
575
|
+
if system_user is None:
|
|
576
|
+
return
|
|
577
|
+
|
|
578
|
+
# Generate a usable password. 22 base64url chars = ~132 bits of
|
|
579
|
+
# entropy, same as ``dap init`` uses for its generated path.
|
|
580
|
+
password = secrets.token_urlsafe(22)
|
|
581
|
+
hashed = PasswordHelper().hash(password)
|
|
582
|
+
now = datetime.now(UTC).isoformat()
|
|
583
|
+
|
|
584
|
+
# ``is_superuser = TRUE`` belt-and-suspenders: 013 already set it
|
|
585
|
+
# when it created the row, but an operator could in principle have
|
|
586
|
+
# toggled it off (e.g. via a manual SQL fix-up) between then and
|
|
587
|
+
# now. Re-asserting here guarantees the row promotion lands as an
|
|
588
|
+
# actual admin no matter what intermediate state preceded it.
|
|
589
|
+
conn.execute(
|
|
590
|
+
text(
|
|
591
|
+
"""
|
|
592
|
+
UPDATE users
|
|
593
|
+
SET email = :legacy_email,
|
|
594
|
+
hashed_password = :hashed,
|
|
595
|
+
is_active = :is_active,
|
|
596
|
+
is_superuser = :is_superuser,
|
|
597
|
+
is_verified = :is_verified,
|
|
598
|
+
deleted_at = NULL,
|
|
599
|
+
updated_at = :updated_at
|
|
600
|
+
WHERE email = :system_email
|
|
601
|
+
"""
|
|
602
|
+
),
|
|
603
|
+
{
|
|
604
|
+
"legacy_email": legacy_email,
|
|
605
|
+
"hashed": hashed,
|
|
606
|
+
"is_active": True,
|
|
607
|
+
"is_superuser": True,
|
|
608
|
+
"is_verified": True,
|
|
609
|
+
"updated_at": now,
|
|
610
|
+
"system_email": system_email,
|
|
611
|
+
},
|
|
612
|
+
)
|
|
613
|
+
|
|
614
|
+
# Password to stdout (operator's terminal); separate WARN log
|
|
615
|
+
# without the password (long-term log aggregation never sees the
|
|
616
|
+
# secret). Both reference the same email so it's clear they
|
|
617
|
+
# describe the same event.
|
|
618
|
+
print(
|
|
619
|
+
f"Migrated single-user install. Bootstrap admin: {legacy_email} "
|
|
620
|
+
f"with password={password}. Change immediately at /admin/users.",
|
|
621
|
+
flush=True,
|
|
622
|
+
)
|
|
623
|
+
logger.warning(
|
|
624
|
+
"Promoted system@local → %s during pre-v0.3 upgrade. "
|
|
625
|
+
"The generated password was printed to stdout exactly once — "
|
|
626
|
+
"capture it now and rotate at /admin/users.",
|
|
627
|
+
legacy_email,
|
|
628
|
+
)
|
|
629
|
+
|
|
630
|
+
|
|
631
|
+
MIGRATIONS: list[Migration] = [
|
|
632
|
+
Migration(name="001_runs_add_project_id", apply=_001_runs_add_project_id),
|
|
633
|
+
Migration(
|
|
634
|
+
name="002_node_execution_logs_add_extra_data",
|
|
635
|
+
apply=_002_node_execution_logs_add_extra_data,
|
|
636
|
+
),
|
|
637
|
+
Migration(
|
|
638
|
+
name="003_pipeline_versions_add_ui_metadata",
|
|
639
|
+
apply=_003_pipeline_versions_add_ui_metadata,
|
|
640
|
+
),
|
|
641
|
+
Migration(name="004_runs_index_started_at", apply=_004_runs_index_started_at),
|
|
642
|
+
Migration(name="005_runs_index_project_started", apply=_005_runs_index_project_started),
|
|
643
|
+
Migration(
|
|
644
|
+
name="006_node_execution_logs_index_run_started",
|
|
645
|
+
apply=_006_node_execution_logs_index_run_started,
|
|
646
|
+
),
|
|
647
|
+
Migration(name="007_runs_index_pipeline_started", apply=_007_runs_index_pipeline_started),
|
|
648
|
+
Migration(name="008_runs_add_failure_reason", apply=_008_runs_add_failure_reason),
|
|
649
|
+
Migration(name="009_create_users_table", apply=_009_create_users_table),
|
|
650
|
+
Migration(name="010_create_oauth_accounts_table", apply=_010_create_oauth_accounts_table),
|
|
651
|
+
Migration(name="011_create_api_tokens_table", apply=_011_create_api_tokens_table),
|
|
652
|
+
Migration(name="012_add_user_id_to_resources", apply=_012_add_user_id_to_resources),
|
|
653
|
+
Migration(
|
|
654
|
+
name="013_backfill_user_id_via_system_user",
|
|
655
|
+
apply=_013_backfill_user_id_via_system_user,
|
|
656
|
+
),
|
|
657
|
+
Migration(name="014_create_audit_log_table", apply=_014_create_audit_log_table),
|
|
658
|
+
Migration(
|
|
659
|
+
name="015_promote_system_user_to_legacy_admin",
|
|
660
|
+
apply=_015_promote_system_user_to_legacy_admin,
|
|
661
|
+
),
|
|
662
|
+
]
|
|
663
|
+
|
|
664
|
+
|
|
665
|
+
# ---------------------------------------------------------------------------
|
|
666
|
+
# Runner
|
|
667
|
+
# ---------------------------------------------------------------------------
|
|
668
|
+
|
|
669
|
+
|
|
670
|
+
_CREATE_TABLE_SQL = text(
|
|
671
|
+
"""
|
|
672
|
+
CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
673
|
+
name TEXT PRIMARY KEY,
|
|
674
|
+
applied_at TEXT NOT NULL
|
|
675
|
+
)
|
|
676
|
+
""",
|
|
677
|
+
)
|
|
678
|
+
|
|
679
|
+
|
|
680
|
+
def _ensure_table(conn: Connection) -> None:
|
|
681
|
+
conn.execute(_CREATE_TABLE_SQL)
|
|
682
|
+
|
|
683
|
+
|
|
684
|
+
def apply_migrations(engine: Engine) -> list[str]:
|
|
685
|
+
"""Run pending migrations in order. Returns the names of the ones applied.
|
|
686
|
+
|
|
687
|
+
Each migration runs in its own transaction with an "INSERT OR
|
|
688
|
+
IGNORE" claim on the migration name *before* the schema change.
|
|
689
|
+
The claim is atomic: if two engine processes start against the
|
|
690
|
+
same SQLite file, only one wins the row insert (rowcount == 1)
|
|
691
|
+
and runs the migration body; the other sees rowcount == 0 and
|
|
692
|
+
skips. If the migration body raises after the claim, the whole
|
|
693
|
+
transaction rolls back — including the row insert — so the
|
|
694
|
+
name doesn't get marked applied for a migration that didn't
|
|
695
|
+
actually run.
|
|
696
|
+
|
|
697
|
+
A failure is fatal: the engine refuses to soldier on against a
|
|
698
|
+
half-migrated schema. The operator inspects the error, fixes
|
|
699
|
+
the underlying problem, and restarts.
|
|
700
|
+
"""
|
|
701
|
+
# PostgreSQL uses "ON CONFLICT DO NOTHING"; SQLite uses "INSERT OR IGNORE".
|
|
702
|
+
# Both are semantically equivalent here — claim the migration name atomically
|
|
703
|
+
# before running the body so concurrent processes don't double-apply.
|
|
704
|
+
dialect = engine.dialect.name # "sqlite" | "postgresql"
|
|
705
|
+
if dialect == "postgresql":
|
|
706
|
+
_claim_sql = text(
|
|
707
|
+
"INSERT INTO schema_migrations (name, applied_at) "
|
|
708
|
+
"VALUES (:name, :applied_at) ON CONFLICT (name) DO NOTHING"
|
|
709
|
+
)
|
|
710
|
+
else:
|
|
711
|
+
_claim_sql = text(
|
|
712
|
+
"INSERT OR IGNORE INTO schema_migrations (name, applied_at) VALUES (:name, :applied_at)"
|
|
713
|
+
)
|
|
714
|
+
|
|
715
|
+
applied: list[str] = []
|
|
716
|
+
with engine.begin() as conn:
|
|
717
|
+
_ensure_table(conn)
|
|
718
|
+
|
|
719
|
+
for migration in MIGRATIONS:
|
|
720
|
+
with engine.begin() as conn:
|
|
721
|
+
claim = conn.execute(
|
|
722
|
+
_claim_sql,
|
|
723
|
+
{
|
|
724
|
+
"name": migration.name,
|
|
725
|
+
"applied_at": datetime.now(UTC).isoformat(),
|
|
726
|
+
},
|
|
727
|
+
)
|
|
728
|
+
if claim.rowcount == 0:
|
|
729
|
+
# Already applied by us (previous startup) or by a
|
|
730
|
+
# concurrent instance racing the same DB — either
|
|
731
|
+
# way, nothing more to do.
|
|
732
|
+
continue
|
|
733
|
+
logger.info("applying schema migration: %s", migration.name)
|
|
734
|
+
migration.apply(conn)
|
|
735
|
+
applied.append(migration.name)
|
|
736
|
+
|
|
737
|
+
if applied:
|
|
738
|
+
logger.info("applied %d schema migration(s): %s", len(applied), applied)
|
|
739
|
+
return applied
|