adops 0.1.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 (103) hide show
  1. adops/__init__.py +1 -0
  2. adops/application/__init__.py +0 -0
  3. adops/application/accept_schema.py +192 -0
  4. adops/application/alerts.py +59 -0
  5. adops/application/connection_check.py +103 -0
  6. adops/application/drop_branch.py +64 -0
  7. adops/application/ports.py +274 -0
  8. adops/application/run_pipeline.py +742 -0
  9. adops/application/secrets.py +78 -0
  10. adops/domain/__init__.py +0 -0
  11. adops/domain/accepted_change_record.py +122 -0
  12. adops/domain/assistant_access.py +133 -0
  13. adops/domain/branch_environment.py +150 -0
  14. adops/domain/checks.py +384 -0
  15. adops/domain/environment.py +116 -0
  16. adops/domain/errors.py +19 -0
  17. adops/domain/loader.py +115 -0
  18. adops/domain/names.py +1 -0
  19. adops/domain/pipeline.py +218 -0
  20. adops/domain/reverse_sync.py +71 -0
  21. adops/domain/reverse_sync_diff.py +117 -0
  22. adops/domain/run_log.py +19 -0
  23. adops/domain/schedule.py +134 -0
  24. adops/domain/schema_snapshot.py +97 -0
  25. adops/domain/secret_reference.py +25 -0
  26. adops/domain/transform.py +80 -0
  27. adops/infrastructure/__init__.py +0 -0
  28. adops/infrastructure/clock.py +6 -0
  29. adops/infrastructure/connection_probe.py +40 -0
  30. adops/infrastructure/dagster_orchestrator.py +123 -0
  31. adops/infrastructure/dagster_server.py +161 -0
  32. adops/infrastructure/dbt_transform.py +194 -0
  33. adops/infrastructure/dlt_sync.py +454 -0
  34. adops/infrastructure/git_start.py +37 -0
  35. adops/infrastructure/postgres_reverse_sync.py +209 -0
  36. adops/infrastructure/release_folders.py +158 -0
  37. adops/infrastructure/run_log_store.py +51 -0
  38. adops/infrastructure/schema_snapshot_store.py +201 -0
  39. adops/infrastructure/step_fingerprint_store.py +128 -0
  40. adops/infrastructure/warehouse_lock.py +142 -0
  41. adops/infrastructure/warehouse_schemas.py +79 -0
  42. adops/infrastructure/webhook_alerts.py +45 -0
  43. adops/interface/__init__.py +0 -0
  44. adops/interface/accept_schema_command.py +217 -0
  45. adops/interface/assistant_files.py +122 -0
  46. adops/interface/cli.py +48 -0
  47. adops/interface/drop_branch_command.py +71 -0
  48. adops/interface/init_command.py +85 -0
  49. adops/interface/mcp_server.py +719 -0
  50. adops/interface/project_secrets.py +20 -0
  51. adops/interface/recover_command.py +56 -0
  52. adops/interface/release_command.py +107 -0
  53. adops/interface/run_command.py +667 -0
  54. adops/interface/server.py +124 -0
  55. adops/interface/validate_command.py +199 -0
  56. adops/templates/__init__.py +0 -0
  57. adops/templates/demo/.claude/skills/adops-breaking-change/SKILL.md +109 -0
  58. adops/templates/demo/.claude/skills/adops-build/SKILL.md +81 -0
  59. adops/templates/demo/.claude/skills/adops-promote/SKILL.md +70 -0
  60. adops/templates/demo/.claude/skills/adops-setup/SKILL.md +104 -0
  61. adops/templates/demo/.claude/skills/adops-share/SKILL.md +141 -0
  62. adops/templates/demo/.claude/skills/adops-test-in-dev/SKILL.md +72 -0
  63. adops/templates/demo/.env.example +20 -0
  64. adops/templates/demo/.mcp.json +8 -0
  65. adops/templates/demo/adops.yaml +92 -0
  66. adops/templates/demo/dagster.yaml +25 -0
  67. adops/templates/demo/dbt/dbt_project.yml +9 -0
  68. adops/templates/demo/dbt/models/customer_orders.sql +9 -0
  69. adops/templates/demo/dbt/models/customer_stats.sql +8 -0
  70. adops/templates/demo/dbt/models/customers.sql +2 -0
  71. adops/templates/demo/dbt/models/orders.sql +2 -0
  72. adops/templates/demo/dbt/models/schema.yml +17 -0
  73. adops/templates/demo/dbt/models/sources.yml +8 -0
  74. adops/templates/demo/docker-compose.yml +79 -0
  75. adops/templates/demo/gitignore +4 -0
  76. adops/templates/demo/pipelines/shop_sync.yaml +30 -0
  77. adops/templates/demo/seed/01_shop.sql +34 -0
  78. adops/templates/demo/seed/02_shop_dev.sql +11 -0
  79. adops/templates/demo/seed/03_shop_prod.sql +11 -0
  80. adops/templates/demo/warehouse_init/01_stage.sql +2 -0
  81. adops/templates/demo/warehouse_init/02_prod.sql +2 -0
  82. adops/templates/github/workflows/adops-prod.yml +71 -0
  83. adops/templates/github/workflows/adops-pull-request.yml +88 -0
  84. adops/templates/github/workflows/adops-stage.yml +65 -0
  85. adops/templates/plain/.claude/skills/adops-breaking-change/SKILL.md +109 -0
  86. adops/templates/plain/.claude/skills/adops-build/SKILL.md +81 -0
  87. adops/templates/plain/.claude/skills/adops-promote/SKILL.md +70 -0
  88. adops/templates/plain/.claude/skills/adops-setup/SKILL.md +104 -0
  89. adops/templates/plain/.claude/skills/adops-share/SKILL.md +141 -0
  90. adops/templates/plain/.claude/skills/adops-test-in-dev/SKILL.md +72 -0
  91. adops/templates/plain/.env.example +16 -0
  92. adops/templates/plain/.mcp.json +8 -0
  93. adops/templates/plain/adops.yaml +24 -0
  94. adops/templates/plain/docker-compose.yml +50 -0
  95. adops/templates/plain/gitignore +2 -0
  96. adops/templates/server/Dockerfile +8 -0
  97. adops/templates/server/dagster.yaml +39 -0
  98. adops/templates/server/workspace.yaml +5 -0
  99. adops-0.1.0.dist-info/METADATA +256 -0
  100. adops-0.1.0.dist-info/RECORD +103 -0
  101. adops-0.1.0.dist-info/WHEEL +4 -0
  102. adops-0.1.0.dist-info/entry_points.txt +2 -0
  103. adops-0.1.0.dist-info/licenses/LICENSE +203 -0
@@ -0,0 +1,742 @@
1
+ import re
2
+ from collections.abc import Callable, Iterable, Mapping, Sequence
3
+ from dataclasses import dataclass
4
+ from typing import assert_never
5
+
6
+ from adops.application.ports import (
7
+ MASK,
8
+ Clock,
9
+ Orchestrator,
10
+ ProjectFiles,
11
+ ResolvedConnection,
12
+ ResolvedWarehouse,
13
+ ReverseSync,
14
+ ReverseSyncPreview,
15
+ ReverseSyncRead,
16
+ RunPlan,
17
+ RunResult,
18
+ SchemaSnapshotStore,
19
+ SourceUnreachable,
20
+ StepFingerprintStore,
21
+ StepOutcome,
22
+ StepReport,
23
+ StepStatus,
24
+ StepTask,
25
+ Sync,
26
+ TargetUnreachable,
27
+ Transform,
28
+ TransformResult,
29
+ WarehouseUnreachable,
30
+ WriteFailed,
31
+ )
32
+ from adops.application.secrets import (
33
+ resolve_connection,
34
+ resolve_secret_references,
35
+ resolve_warehouse,
36
+ secret_references,
37
+ )
38
+ from adops.domain.accepted_change_record import AcceptedChangeRecord, Coverage, cover
39
+ from adops.domain.assistant_access import DEV
40
+ from adops.domain.branch_environment import (
41
+ STAGE,
42
+ SchemaLayout,
43
+ branch_environment_name,
44
+ canonical_step_json,
45
+ first_changed_step,
46
+ raw_schema_var,
47
+ saves_stage_fingerprint,
48
+ step_fingerprint,
49
+ uses_raw_schema_var,
50
+ )
51
+ from adops.domain.checks import (
52
+ CheckName,
53
+ CheckResult,
54
+ CheckStatus,
55
+ ReverseSyncFacts,
56
+ SourceFacts,
57
+ evaluate_declared_checks,
58
+ evaluate_load_checks,
59
+ evaluate_preflight_checks,
60
+ evaluate_reverse_sync,
61
+ )
62
+ from adops.domain.environment import Environment
63
+ from adops.domain.errors import PipelineValidationError
64
+ from adops.domain.loader import (
65
+ ensure_sources_defined,
66
+ ensure_targets_defined,
67
+ format_path,
68
+ load_pipeline,
69
+ load_project_settings,
70
+ )
71
+ from adops.domain.pipeline import Pipeline, Step, SyncStep, SyncTable
72
+ from adops.domain.reverse_sync import ReverseSyncStep
73
+ from adops.domain.reverse_sync_diff import Diff, compute_diff, preview_sample, writes_allowed
74
+ from adops.domain.schema_snapshot import (
75
+ BreakingChange,
76
+ BreakingChangeKind,
77
+ TableShape,
78
+ find_breaking_changes,
79
+ )
80
+ from adops.domain.transform import TransformStep, evaluate_dbt_tests
81
+
82
+ NOT_IN_SOURCE = SourceFacts(table_exists=False, columns=frozenset())
83
+ URL_PATTERN = re.compile(r"[a-z][a-z0-9+.-]*://\S+", re.IGNORECASE)
84
+ SNAPSHOT_STORE = "schema snapshot store"
85
+ CRASHED = TransformResult(tests=(), crashed=True, failed_models=())
86
+ _RECORD_HINT = " — add an accepted-change record for {table} to the PR"
87
+
88
+
89
+ class StepError(Exception):
90
+ """A Step that did not pass; its message never contains a secret value."""
91
+
92
+
93
+ class CheckFailedError(StepError):
94
+ def __init__(
95
+ self, step: str, checks: Sequence[CheckResult], rows_loaded: Mapping[str, int]
96
+ ) -> None:
97
+ self.checks = tuple(checks)
98
+ self.rows_loaded = dict(rows_loaded)
99
+ failed = [check.message for check in self.checks if check.status is CheckStatus.FAIL]
100
+ super().__init__(f"Step {step}: Checks failed: " + "; ".join(failed))
101
+
102
+
103
+ class EmptySourceTableError(CheckFailedError):
104
+ def __init__(self, pipeline: str, step: str, table: str, checks: Sequence[CheckResult]) -> None:
105
+ super().__init__(step, checks, {})
106
+ self.table = table
107
+ self.args = (f"Pipeline {pipeline}, Step {step}, table {table}: Source table is empty",)
108
+
109
+
110
+ class SyncFailedError(StepError):
111
+ pass
112
+
113
+
114
+ class SourceUnreachableError(StepError):
115
+ def __init__(self, pipeline: str, step: str, table: str) -> None:
116
+ self.table = table
117
+ super().__init__(f"Pipeline {pipeline}, Step {step}, table {table}: Source is unreachable")
118
+
119
+
120
+ class WarehouseUnreachableError(StepError):
121
+ def __init__(self, pipeline: str, step: str) -> None:
122
+ super().__init__(f"Pipeline {pipeline}, Step {step}: Warehouse is unreachable")
123
+
124
+
125
+ # The Server retries only an unreachable Source or Warehouse (ADR-0014). An unreachable Reverse
126
+ # Sync Target is deliberately not retried. Matched by exact type, so a new subclass is not retried
127
+ # until it is added here.
128
+ RETRYABLE_ERRORS = (SourceUnreachableError, WarehouseUnreachableError)
129
+
130
+
131
+ class ReverseSyncTargetUnreachableError(StepError):
132
+ def __init__(self, pipeline: str, step: str, target: str) -> None:
133
+ self.target = target
134
+ super().__init__(f"Pipeline {pipeline}, Step {step}: Target {target} is unreachable")
135
+
136
+
137
+ class ReverseSyncWriteFailedError(StepError):
138
+ def __init__(self, pipeline: str, step: str, target: str) -> None:
139
+ self.target = target
140
+ super().__init__(
141
+ f"Pipeline {pipeline}, Step {step}: the write to Target {target} failed "
142
+ "and was rolled back; the Target was left unchanged"
143
+ )
144
+
145
+
146
+ class TransformFailedError(StepError):
147
+ def __init__(self, pipeline: str, step: str, failed_models: Sequence[str]) -> None:
148
+ self.failed_models = tuple(failed_models)
149
+ models = f" (models: {', '.join(self.failed_models)})" if self.failed_models else ""
150
+ super().__init__(f"Pipeline {pipeline}, Step {step}: dbt run failed{models}")
151
+
152
+
153
+ class BreakingChangeError(StepError):
154
+ def __init__(
155
+ self,
156
+ step: str,
157
+ changes: Mapping[str, Sequence[BreakingChange]],
158
+ *,
159
+ ask_for_record: bool = False,
160
+ ) -> None:
161
+ self.changes = {table: tuple(found) for table, found in changes.items()}
162
+ super().__init__(
163
+ f"Step {step}: "
164
+ + "; ".join(
165
+ f"Breaking Change in {table}: "
166
+ + ", ".join(change.message for change in found)
167
+ + (_RECORD_HINT.format(table=table) if ask_for_record else "")
168
+ for table, found in self.changes.items()
169
+ )
170
+ )
171
+
172
+
173
+ class StageNotRunError(Exception):
174
+ def __init__(self, pipeline: str) -> None:
175
+ super().__init__(
176
+ f"Pipeline {pipeline}: stage has no Step Fingerprints; run the Pipeline in stage first"
177
+ )
178
+
179
+
180
+ class BranchSourcesNotParameterizedError(PipelineValidationError):
181
+ def __init__(self, transform_step: str, source: str) -> None:
182
+ self.source = source
183
+ variable = raw_schema_var(source)
184
+ schema = f"{{{{ var('{variable}', '{SchemaLayout.default().raw(source)}') }}}}"
185
+ super().__init__(
186
+ [
187
+ f"Step {transform_step}: the Branch rebuilds Source {source}, but the dbt sources "
188
+ f"do not read {variable}, so dbt would read stage's tables; set the schema of "
189
+ f'Source {source} in sources.yml to "{schema}"'
190
+ ]
191
+ )
192
+
193
+
194
+ @dataclass(frozen=True)
195
+ class StepFingerprinting:
196
+ store: StepFingerprintStore
197
+ files: ProjectFiles
198
+
199
+
200
+ @dataclass(frozen=True)
201
+ class BranchRun:
202
+ """A Branch Environment's run: Steps before `first_changed` are deferred to stage.
203
+
204
+ `first_changed` is None when every Step matches stage, so nothing needs to run.
205
+ """
206
+
207
+ environment: str
208
+ stage_fingerprints: Mapping[str, str]
209
+ first_changed: int | None
210
+
211
+
212
+ @dataclass(frozen=True)
213
+ class FingerprintSavingStep:
214
+ """Saves the Step's fingerprint once the Step, Checks included, has passed."""
215
+
216
+ task: StepTask
217
+ pipeline: str
218
+ fingerprint: str
219
+ store: StepFingerprintStore
220
+
221
+ @property
222
+ def name(self) -> str:
223
+ return self.task.name
224
+
225
+ def __call__(self, sync: Sync) -> StepOutcome:
226
+ outcome = self.task(sync)
227
+ try:
228
+ self.store.save(self.pipeline, self.name, self.fingerprint)
229
+ return outcome
230
+ except Exception as error:
231
+ # Only the type: the store's error text may hold a Warehouse secret.
232
+ failure = SyncFailedError(
233
+ f"Step {self.name}: step fingerprint store: {type(error).__name__}"
234
+ )
235
+ raise failure
236
+
237
+
238
+ @dataclass(frozen=True)
239
+ class AcceptedChanges:
240
+ changes: tuple[BreakingChange, ...]
241
+ record_ids: tuple[str, ...]
242
+
243
+
244
+ @dataclass(frozen=True)
245
+ class PlannedStep:
246
+ step: SyncStep
247
+ source: ResolvedConnection
248
+ warehouse: ResolvedWarehouse
249
+ pipeline: str
250
+ snapshot_store: SchemaSnapshotStore
251
+ clock: Clock
252
+ environment: str = DEV
253
+ records: tuple[AcceptedChangeRecord, ...] = ()
254
+
255
+ @property
256
+ def name(self) -> str:
257
+ return self.step.name
258
+
259
+ def __call__(self, sync: Sync) -> StepOutcome:
260
+ source_facts = self._guard(lambda: sync.preflight(self.step, self.source))
261
+ checks: list[CheckResult] = []
262
+ for table in self.step.tables:
263
+ checks += evaluate_preflight_checks(table, source_facts.get(table.name, NOT_IN_SOURCE))
264
+ _raise_if_only_empty_tables(self.pipeline, self.name, checks)
265
+ _raise_if_failed(self.name, checks, {})
266
+ shapes = {
267
+ table.name: TableShape(source_facts[table.name].column_types)
268
+ for table in self.step.tables
269
+ }
270
+ accepted = self._accept_breaking(shapes)
271
+ self._relax_dropped(sync, accepted)
272
+
273
+ result = self._guard(lambda: sync.sync(self.step, self.source, self.warehouse))
274
+ now = self.clock.now()
275
+ for table in self.step.tables:
276
+ load_facts = result.load_facts.get(table.name)
277
+ if load_facts is None:
278
+ raise SyncFailedError(f"Step {self.name}: no load facts reported for {table.name}")
279
+ checks += evaluate_load_checks(table, load_facts)
280
+ checks += evaluate_declared_checks(table, load_facts, now)
281
+ _raise_if_failed(self.name, checks, result.rows_loaded)
282
+ self._save_shapes(shapes, accepted)
283
+ applied = tuple(
284
+ f"Applied accepted-change record {record_id} in {self.environment}"
285
+ for found in accepted.values()
286
+ for record_id in found.record_ids
287
+ )
288
+ return StepOutcome(tuple(checks), dict(result.rows_loaded), notes=applied)
289
+
290
+ def _accept_breaking(self, shapes: Mapping[str, TableShape]) -> dict[str, AcceptedChanges]:
291
+ """The changes records accept, per table; raises if any change is still breaking."""
292
+ breaking: dict[str, tuple[BreakingChange, ...]] = {}
293
+ accepted: dict[str, AcceptedChanges] = {}
294
+ for table, current in shapes.items():
295
+ previous = self._guard(
296
+ lambda table=table: self.snapshot_store.load(
297
+ self.warehouse, self.pipeline, self.step.source, table
298
+ ),
299
+ SNAPSHOT_STORE,
300
+ )
301
+ if previous is None:
302
+ continue
303
+ changes = find_breaking_changes(previous, current)
304
+ if not changes:
305
+ continue
306
+ coverage = self._cover(table, changes)
307
+ if coverage.uncovered:
308
+ breaking[table] = coverage.uncovered
309
+ else:
310
+ accepted[table] = AcceptedChanges(changes, coverage.used_ids)
311
+ if breaking:
312
+ raise BreakingChangeError(self.name, breaking, ask_for_record=self.environment != DEV)
313
+ return accepted
314
+
315
+ def _cover(self, table: str, changes: tuple[BreakingChange, ...]) -> Coverage:
316
+ records = [record for record in self.records if record.table == table]
317
+ if not records:
318
+ return Coverage(changes, ())
319
+ applied = self._guard(
320
+ lambda: self.snapshot_store.applied_record_ids(self.warehouse), SNAPSHOT_STORE
321
+ )
322
+ return cover(changes, records, applied)
323
+
324
+ def _relax_dropped(self, sync: Sync, accepted: Mapping[str, AcceptedChanges]) -> None:
325
+ tables = {table.name: table for table in self.step.tables}
326
+ for name, found in accepted.items():
327
+ self._guard(
328
+ lambda name=name, found=found: relax_dropped_columns(
329
+ sync, self.step, tables[name], self.warehouse, found.changes
330
+ )
331
+ )
332
+
333
+ def _save_shapes(
334
+ self, shapes: Mapping[str, TableShape], accepted: Mapping[str, AcceptedChanges]
335
+ ) -> None:
336
+ for table, shape in shapes.items():
337
+ found = accepted.get(table)
338
+ self._guard(
339
+ lambda table=table, shape=shape, found=found: self._save_shape(table, shape, found),
340
+ SNAPSHOT_STORE,
341
+ )
342
+
343
+ def _save_shape(self, table: str, shape: TableShape, found: AcceptedChanges | None) -> None:
344
+ if found is None:
345
+ self.snapshot_store.save(self.warehouse, self.pipeline, self.step.source, table, shape)
346
+ else:
347
+ self.snapshot_store.save(
348
+ self.warehouse,
349
+ self.pipeline,
350
+ self.step.source,
351
+ table,
352
+ shape,
353
+ applied_record_ids=found.record_ids,
354
+ )
355
+
356
+ def _guard[T](self, call: Callable[[], T], component: str | None = None) -> T:
357
+ try:
358
+ return call()
359
+ except SourceUnreachable as marker:
360
+ failure: StepError = SourceUnreachableError(self.pipeline, self.name, marker.table)
361
+ except WarehouseUnreachable:
362
+ failure = WarehouseUnreachableError(self.pipeline, self.name)
363
+ except StepError as error:
364
+ failure = error
365
+ except Exception as error:
366
+ where = f"{component}: " if component else ""
367
+ message = self._redact(f"{type(error).__name__}: {error}")
368
+ failure = SyncFailedError(f"Step {self.name}: {where}{message}")
369
+ # Raised outside `except` so the original error, which may hold a secret, is not chained.
370
+ raise failure
371
+
372
+ def _redact(self, text: str) -> str:
373
+ return _redact(text, (self.source, self.warehouse))
374
+
375
+
376
+ @dataclass(frozen=True)
377
+ class PlannedTransformStep:
378
+ step: TransformStep
379
+ warehouse: ResolvedWarehouse
380
+ pipeline: str
381
+ transform: Transform
382
+
383
+ @property
384
+ def name(self) -> str:
385
+ return self.step.name
386
+
387
+ def __call__(self, sync: Sync) -> StepOutcome:
388
+ result = self._run()
389
+ if result.crashed or result.failed_models:
390
+ raise TransformFailedError(self.pipeline, self.name, result.failed_models)
391
+ checks = evaluate_dbt_tests(result.tests)
392
+ _raise_if_failed(self.name, checks, {})
393
+ return StepOutcome(checks, {})
394
+
395
+ def _run(self) -> TransformResult:
396
+ try:
397
+ return self.transform.run(self.step, self.warehouse)
398
+ except Exception:
399
+ # dbt's own error text may hold the Warehouse password, so none of it is kept.
400
+ return CRASHED
401
+
402
+
403
+ @dataclass(frozen=True)
404
+ class PlannedReverseSyncStep:
405
+ step: ReverseSyncStep
406
+ warehouse: ResolvedWarehouse
407
+ target: ResolvedConnection
408
+ environment: str
409
+ pipeline: str
410
+ reverse_sync: ReverseSync
411
+
412
+ @property
413
+ def name(self) -> str:
414
+ return self.step.name
415
+
416
+ def __call__(self, sync: Sync) -> StepOutcome:
417
+ read = self._guard(lambda: self.reverse_sync.read(self.step, self.warehouse, self.target))
418
+ diff = compute_diff(
419
+ read.result_rows,
420
+ read.target_rows,
421
+ self.step.key,
422
+ self.step.mapping,
423
+ self.step.delete_missing,
424
+ )
425
+ checks = evaluate_reverse_sync(self.step, _reverse_sync_facts(read, diff))
426
+ _raise_if_failed(self.name, checks, {})
427
+ written = writes_allowed(self.environment)
428
+ if written:
429
+ self._guard(lambda: self.reverse_sync.apply(self.step, self.target, diff))
430
+ return StepOutcome(checks, {}, _preview(diff, written))
431
+
432
+ def _guard[T](self, call: Callable[[], T]) -> T:
433
+ try:
434
+ return call()
435
+ except TargetUnreachable:
436
+ failure: StepError = ReverseSyncTargetUnreachableError(
437
+ self.pipeline, self.name, self.step.target
438
+ )
439
+ except WriteFailed:
440
+ failure = ReverseSyncWriteFailedError(self.pipeline, self.name, self.step.target)
441
+ except WarehouseUnreachable:
442
+ failure = WarehouseUnreachableError(self.pipeline, self.name)
443
+ except Exception as error:
444
+ message = _redact(f"{type(error).__name__}: {error}", (self.target, self.warehouse))
445
+ failure = SyncFailedError(f"Step {self.name}: {message}")
446
+ # Raised outside `except` so the original error, which may hold a secret, is not chained.
447
+ raise failure
448
+
449
+
450
+ def relax_dropped_columns(
451
+ sync: Sync,
452
+ step: SyncStep,
453
+ table: SyncTable,
454
+ warehouse: ResolvedWarehouse,
455
+ changes: Iterable[BreakingChange],
456
+ ) -> tuple[str, ...]:
457
+ """Drop NOT NULL from the accepted changes' dropped columns; returns those columns."""
458
+ dropped = tuple(
459
+ change.column for change in changes if change.kind is BreakingChangeKind.DROPPED
460
+ )
461
+ if dropped:
462
+ # Loaded rows no longer carry these columns, so a NOT NULL copied from the Source would
463
+ # reject every new row.
464
+ sync.make_columns_nullable(step, table, warehouse, dropped)
465
+ return dropped
466
+
467
+
468
+ def _reverse_sync_facts(read: ReverseSyncRead, diff: Diff) -> ReverseSyncFacts:
469
+ return ReverseSyncFacts(
470
+ target_table_exists=read.target_table_exists,
471
+ missing_target_columns=read.missing_target_columns,
472
+ result_rows=len(read.result_rows),
473
+ duplicate_keys=read.duplicate_keys,
474
+ null_keys=read.null_keys,
475
+ target_rows=len(read.target_rows),
476
+ diff_updates=len(diff.updates),
477
+ diff_deletes=len(diff.deletes) + len(diff.kept),
478
+ )
479
+
480
+
481
+ def _preview(diff: Diff, written: bool) -> ReverseSyncPreview:
482
+ return ReverseSyncPreview(
483
+ inserts=len(diff.inserts),
484
+ updates=len(diff.updates),
485
+ deletes=len(diff.deletes),
486
+ kept=len(diff.kept),
487
+ sample=preview_sample(diff),
488
+ written=written,
489
+ )
490
+
491
+
492
+ def _redact(text: str, connections: Iterable[ResolvedWarehouse]) -> str:
493
+ for connection in connections:
494
+ if isinstance(connection, ResolvedConnection):
495
+ text = text.replace(connection.password, MASK)
496
+ return URL_PATTERN.sub(MASK, text)
497
+
498
+
499
+ def _raise_if_only_empty_tables(pipeline: str, step: str, checks: Sequence[CheckResult]) -> None:
500
+ failed = [check for check in checks if check.status is CheckStatus.FAIL]
501
+ if failed and all(check.check == CheckName.SOURCE_NOT_EMPTY for check in failed):
502
+ raise EmptySourceTableError(pipeline, step, failed[0].table, checks)
503
+
504
+
505
+ def _raise_if_failed(
506
+ step: str, checks: Sequence[CheckResult], rows_loaded: Mapping[str, int]
507
+ ) -> None:
508
+ if any(check.status is CheckStatus.FAIL for check in checks):
509
+ raise CheckFailedError(step, checks, rows_loaded)
510
+
511
+
512
+ class InOrderOrchestrator:
513
+ """Runs Steps in Pipeline order; after the first failure every later Step is skipped."""
514
+
515
+ def execute(self, plan: RunPlan, sync: Sync) -> RunResult:
516
+ reports: list[StepReport] = []
517
+ for task in plan.steps:
518
+ if reports and reports[-1].status is not StepStatus.PASSED:
519
+ reports.append(StepReport(task.name, StepStatus.SKIPPED))
520
+ else:
521
+ reports.append(run_step(task, sync))
522
+ return RunResult(plan.pipeline, plan.environment, tuple(reports))
523
+
524
+
525
+ def run_step(task: StepTask, sync: Sync) -> StepReport:
526
+ try:
527
+ outcome = task(sync)
528
+ except CheckFailedError as error:
529
+ return StepReport(
530
+ task.name, StepStatus.CHECK_FAILED, error.checks, error.rows_loaded, str(error)
531
+ )
532
+ except StepError as error:
533
+ return StepReport(
534
+ task.name,
535
+ StepStatus.FAILED,
536
+ error=str(error),
537
+ retryable=type(error) in RETRYABLE_ERRORS,
538
+ )
539
+ return StepReport(
540
+ task.name,
541
+ StepStatus.PASSED,
542
+ outcome.checks,
543
+ outcome.rows_loaded,
544
+ preview=outcome.preview,
545
+ notes=outcome.notes,
546
+ )
547
+
548
+
549
+ def run_pipeline(
550
+ pipeline_text: str,
551
+ settings_text: str,
552
+ environment_name: str,
553
+ env: Mapping[str, str],
554
+ sync: Sync,
555
+ snapshot_store: SchemaSnapshotStore,
556
+ clock: Clock,
557
+ orchestrator: Orchestrator | None = None,
558
+ transform: Transform | None = None,
559
+ reverse_sync: ReverseSync | None = None,
560
+ fingerprinting: StepFingerprinting | None = None,
561
+ branch: BranchRun | None = None,
562
+ *,
563
+ records: Sequence[AcceptedChangeRecord] = (),
564
+ ) -> RunResult:
565
+ """Run a Pipeline; a Branch run uses stage's settings under the Branch Environment's name.
566
+
567
+ Outside dev, the Pipeline's accepted-change records let Sync Steps past the Breaking Changes
568
+ they cover; dev accepts by hand with accept-schema.
569
+ """
570
+ pipeline = load_pipeline(pipeline_text)
571
+ settings = load_project_settings(settings_text)
572
+ if branch is None:
573
+ environment = pick_environment(settings.environments, environment_name)
574
+ first: int | None = 0
575
+ else:
576
+ if branch.environment != environment_name:
577
+ raise ValueError("a Branch run must run under its Branch Environment's name")
578
+ environment = stage_environment(settings.environments)
579
+ first = branch.first_changed
580
+ ensure_sources_defined(pipeline, environment)
581
+ ensure_targets_defined(pipeline, environment)
582
+ if first is None:
583
+ return RunResult(pipeline.name, environment_name, _deferred(pipeline.steps))
584
+ plan = _build_plan(
585
+ pipeline,
586
+ environment_name,
587
+ environment,
588
+ env,
589
+ snapshot_store,
590
+ clock,
591
+ transform,
592
+ reverse_sync,
593
+ first,
594
+ () if environment_name == DEV else [r for r in records if r.pipeline == pipeline.name],
595
+ )
596
+ if fingerprinting is not None and saves_stage_fingerprint(environment_name):
597
+ plan = _saving_fingerprints(plan, pipeline, fingerprinting)
598
+ result = (orchestrator or InOrderOrchestrator()).execute(plan, sync)
599
+ deferred = _deferred(pipeline.steps[:first])
600
+ return RunResult(result.pipeline, result.environment, deferred + result.steps)
601
+
602
+
603
+ def plan_branch_run(
604
+ pipeline_text: str, environment: str, fingerprinting: StepFingerprinting
605
+ ) -> BranchRun:
606
+ pipeline = load_pipeline(pipeline_text)
607
+ stage = fingerprinting.store.load(pipeline.name)
608
+ if not stage:
609
+ raise StageNotRunError(pipeline.name)
610
+ current = current_fingerprints(pipeline.steps, fingerprinting.files)
611
+ first = first_changed_step(current, stage)
612
+ if first is not None:
613
+ _ensure_sources_parameterized(pipeline.steps[first:], fingerprinting.files)
614
+ return BranchRun(environment, stage, first)
615
+
616
+
617
+ def current_fingerprints(
618
+ steps: Sequence[Step], project_files: ProjectFiles
619
+ ) -> tuple[tuple[str, str], ...]:
620
+ """Each Step's name and fingerprint in Step order; a Transform's covers its dbt project."""
621
+ return tuple(
622
+ (step.name, step_fingerprint(canonical_step_json(step), _step_files(step, project_files)))
623
+ for step in steps
624
+ )
625
+
626
+
627
+ def _step_files(step: Step, project_files: ProjectFiles) -> Mapping[str, bytes]:
628
+ if isinstance(step, TransformStep):
629
+ return project_files.read_tree(step.project)
630
+ return {}
631
+
632
+
633
+ def _ensure_sources_parameterized(running: Sequence[Step], project_files: ProjectFiles) -> None:
634
+ rebuilt: dict[str, None] = {}
635
+ for step in running:
636
+ if isinstance(step, SyncStep):
637
+ rebuilt[step.source] = None
638
+ elif isinstance(step, TransformStep):
639
+ files = project_files.read_tree(step.project)
640
+ for source in rebuilt:
641
+ if not uses_raw_schema_var(files, source):
642
+ raise BranchSourcesNotParameterizedError(step.name, source)
643
+
644
+
645
+ def _saving_fingerprints(
646
+ plan: RunPlan, pipeline: Pipeline, fingerprinting: StepFingerprinting
647
+ ) -> RunPlan:
648
+ fingerprints = dict(current_fingerprints(pipeline.steps, fingerprinting.files))
649
+ steps = tuple(
650
+ FingerprintSavingStep(task, pipeline.name, fingerprints[task.name], fingerprinting.store)
651
+ for task in plan.steps
652
+ )
653
+ return RunPlan(plan.pipeline, plan.environment, steps)
654
+
655
+
656
+ def _deferred(steps: Sequence[Step]) -> tuple[StepReport, ...]:
657
+ return tuple(StepReport(step.name, StepStatus.DEFERRED) for step in steps)
658
+
659
+
660
+ def stage_environment(environments: Mapping[str, Environment]) -> Environment:
661
+ if STAGE not in environments:
662
+ location = format_path(("environments", STAGE))
663
+ raise PipelineValidationError(
664
+ [f"{location}: a Branch run needs a stage Environment in adops.yaml, and none is set"]
665
+ )
666
+ return environments[STAGE]
667
+
668
+
669
+ def stage_branch_name(stage: Environment, branch: str) -> str:
670
+ """The Branch Environment a Git branch gets, sized to fit stage's longest Source name."""
671
+ longest_source = max(stage.sources, key=lambda name: len(name.encode()), default="")
672
+ return branch_environment_name(branch, longest_source)
673
+
674
+
675
+ def pick_environment(environments: Mapping[str, Environment], name: str) -> Environment:
676
+ if name not in environments:
677
+ available = ", ".join(sorted(environments))
678
+ location = format_path(("environments", name))
679
+ raise PipelineValidationError(
680
+ [f"{location}: no Environment with this name (available: {available})"]
681
+ )
682
+ return environments[name]
683
+
684
+
685
+ def _build_plan(
686
+ pipeline: Pipeline,
687
+ environment_name: str,
688
+ environment: Environment,
689
+ env: Mapping[str, str],
690
+ snapshot_store: SchemaSnapshotStore,
691
+ clock: Clock,
692
+ transform: Transform | None,
693
+ reverse_sync: ReverseSync | None,
694
+ first: int = 0,
695
+ records: Sequence[AcceptedChangeRecord] = (),
696
+ ) -> RunPlan:
697
+ running = pipeline.steps[first:]
698
+ sources = [environment.sources[step.source] for step in running if isinstance(step, SyncStep)]
699
+ targets = [
700
+ environment.targets[step.target] for step in running if isinstance(step, ReverseSyncStep)
701
+ ]
702
+ secrets = resolve_secret_references(
703
+ env, secret_references(environment.warehouse, sources, targets)
704
+ )
705
+ warehouse = resolve_warehouse(environment.warehouse, secrets)
706
+ steps: list[StepTask] = []
707
+ for index, step in enumerate(running, start=first):
708
+ if isinstance(step, SyncStep):
709
+ source = resolve_connection(environment.sources[step.source], secrets)
710
+ tables = {table.name for table in step.tables}
711
+ steps.append(
712
+ PlannedStep(
713
+ step,
714
+ source,
715
+ warehouse,
716
+ pipeline.name,
717
+ snapshot_store,
718
+ clock,
719
+ environment_name,
720
+ tuple(record for record in records if record.table in tables),
721
+ )
722
+ )
723
+ elif isinstance(step, TransformStep):
724
+ if transform is None:
725
+ raise _missing_engine(index, "a Transform Step needs a Transform engine")
726
+ steps.append(PlannedTransformStep(step, warehouse, pipeline.name, transform))
727
+ elif isinstance(step, ReverseSyncStep):
728
+ if reverse_sync is None:
729
+ raise _missing_engine(index, "a Reverse Sync Step needs a Reverse Sync engine")
730
+ target = resolve_connection(environment.targets[step.target], secrets)
731
+ steps.append(
732
+ PlannedReverseSyncStep(
733
+ step, warehouse, target, environment_name, pipeline.name, reverse_sync
734
+ )
735
+ )
736
+ else:
737
+ assert_never(step)
738
+ return RunPlan(pipeline.name, environment_name, tuple(steps))
739
+
740
+
741
+ def _missing_engine(index: int, need: str) -> PipelineValidationError:
742
+ return PipelineValidationError([f"{format_path(('steps', index))}: {need}, and none is set"])