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
adops/__init__.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
File without changes
@@ -0,0 +1,192 @@
1
+ from collections.abc import Iterable, Mapping
2
+ from dataclasses import dataclass
3
+ from datetime import UTC, datetime
4
+
5
+ from adops.application.ports import ResolvedWarehouse, SchemaSnapshotStore, Sync
6
+ from adops.application.run_pipeline import StepError, pick_environment, relax_dropped_columns
7
+ from adops.application.secrets import (
8
+ resolve_connection,
9
+ resolve_secret_references,
10
+ resolve_warehouse,
11
+ secret_references,
12
+ )
13
+ from adops.domain.accepted_change_record import AcceptedChangeRecord, cover
14
+ from adops.domain.errors import PipelineValidationError
15
+ from adops.domain.loader import ensure_sources_defined, load_pipeline, load_project_settings
16
+ from adops.domain.pipeline import Pipeline, SyncStep
17
+ from adops.domain.run_log import TIMESTAMP_FORMAT, is_plain_name
18
+ from adops.domain.schema_snapshot import BreakingChange, TableShape, find_breaking_changes
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class AcceptedSchema:
23
+ pipeline: str
24
+ environment: str
25
+ step: str
26
+ table: str
27
+ shape: TableShape
28
+ nullable_columns: tuple[str, ...] = ()
29
+ changes: tuple[BreakingChange, ...] = ()
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class FoundSchemaChanges:
34
+ pipeline: str
35
+ environment: str
36
+ step: SyncStep
37
+ source: str
38
+ table: str
39
+ shape: TableShape
40
+ warehouse: ResolvedWarehouse
41
+ had_previous_snapshot: bool
42
+ changes: tuple[BreakingChange, ...]
43
+
44
+
45
+ @dataclass(frozen=True)
46
+ class NothingToRecord:
47
+ pass
48
+
49
+
50
+ @dataclass(frozen=True)
51
+ class AlreadyCovered:
52
+ record_ids: tuple[str, ...]
53
+
54
+
55
+ @dataclass(frozen=True)
56
+ class NewRecord:
57
+ record: AcceptedChangeRecord
58
+
59
+
60
+ RecordPlan = NothingToRecord | AlreadyCovered | NewRecord
61
+
62
+
63
+ def find_schema_changes(
64
+ pipeline_text: str,
65
+ settings_text: str,
66
+ settings_environment_name: str,
67
+ table: str,
68
+ env: Mapping[str, str],
69
+ sync: Sync,
70
+ snapshot_store: SchemaSnapshotStore,
71
+ environment_name: str | None = None,
72
+ ) -> FoundSchemaChanges:
73
+ """Compare a table's current Source shape with its snapshot, changing nothing.
74
+
75
+ Sources and secrets come from the settings Environment; the result is reported under
76
+ environment_name, so a Branch can use stage's settings under its own name.
77
+ """
78
+ pipeline = load_pipeline(pipeline_text)
79
+ settings = load_project_settings(settings_text)
80
+ environment = pick_environment(settings.environments, settings_environment_name)
81
+ ensure_sources_defined(pipeline, environment)
82
+ step = _only_step_with(pipeline, table)
83
+
84
+ source_connection = environment.sources[step.source]
85
+ secrets = resolve_secret_references(
86
+ env, secret_references(environment.warehouse, [source_connection])
87
+ )
88
+ facts = sync.preflight(step, resolve_connection(source_connection, secrets))[table]
89
+ if not facts.table_exists:
90
+ raise StepError(
91
+ f"Step {step.name}: {table} not found in Source {step.source}; nothing accepted"
92
+ )
93
+
94
+ shape = TableShape(facts.column_types)
95
+ warehouse = resolve_warehouse(environment.warehouse, secrets)
96
+ previous = snapshot_store.load(warehouse, pipeline.name, step.source, table)
97
+ changes = () if previous is None else find_breaking_changes(previous, shape)
98
+ return FoundSchemaChanges(
99
+ pipeline.name,
100
+ environment_name or settings_environment_name,
101
+ step,
102
+ step.source,
103
+ table,
104
+ shape,
105
+ warehouse,
106
+ previous is not None,
107
+ changes,
108
+ )
109
+
110
+
111
+ def apply_schema_acceptance(
112
+ found: FoundSchemaChanges, sync: Sync, snapshot_store: SchemaSnapshotStore
113
+ ) -> AcceptedSchema:
114
+ """Relax dropped columns' NOT NULL and save the found shape as the new snapshot."""
115
+ dropped = relax_dropped_columns(
116
+ sync, found.step, found.step.tables[0], found.warehouse, found.changes
117
+ )
118
+ snapshot_store.save(found.warehouse, found.pipeline, found.source, found.table, found.shape)
119
+ return AcceptedSchema(
120
+ found.pipeline,
121
+ found.environment,
122
+ found.step.name,
123
+ found.table,
124
+ found.shape,
125
+ dropped,
126
+ found.changes,
127
+ )
128
+
129
+
130
+ def accept_schema(
131
+ pipeline_text: str,
132
+ settings_text: str,
133
+ settings_environment_name: str,
134
+ table: str,
135
+ env: Mapping[str, str],
136
+ sync: Sync,
137
+ snapshot_store: SchemaSnapshotStore,
138
+ environment_name: str | None = None,
139
+ ) -> AcceptedSchema:
140
+ """Record a table's current Source shape as its accepted snapshot in one Environment."""
141
+ found = find_schema_changes(
142
+ pipeline_text,
143
+ settings_text,
144
+ settings_environment_name,
145
+ table,
146
+ env,
147
+ sync,
148
+ snapshot_store,
149
+ environment_name,
150
+ )
151
+ return apply_schema_acceptance(found, sync, snapshot_store)
152
+
153
+
154
+ def plan_accepted_record(
155
+ pipeline_name: str,
156
+ table: str,
157
+ changes: tuple[BreakingChange, ...],
158
+ existing_records: Iterable[AcceptedChangeRecord],
159
+ now: datetime,
160
+ ) -> RecordPlan:
161
+ """Decide whether found changes need a new accepted-change record."""
162
+ if not changes:
163
+ return NothingToRecord()
164
+ same_table = [
165
+ record
166
+ for record in existing_records
167
+ if record.pipeline == pipeline_name and record.table == table
168
+ ]
169
+ coverage = cover(changes, same_table, applied_ids=())
170
+ if not coverage.uncovered:
171
+ return AlreadyCovered(coverage.used_ids)
172
+ if not is_plain_name(table):
173
+ raise PipelineValidationError(
174
+ [f"{table}: an accepted-change record needs a plain table name (a-z, 0-9, _)"]
175
+ )
176
+ record_id = f"{now.astimezone(UTC).strftime(TIMESTAMP_FORMAT)}-{pipeline_name}-{table}"
177
+ return NewRecord(AcceptedChangeRecord(record_id, pipeline_name, table, changes))
178
+
179
+
180
+ def _only_step_with(pipeline: Pipeline, table: str) -> SyncStep:
181
+ steps = [
182
+ step
183
+ for step in pipeline.steps
184
+ if isinstance(step, SyncStep) and any(t.name == table for t in step.tables)
185
+ ]
186
+ if not steps:
187
+ raise PipelineValidationError([f"{table}: no Step in Pipeline {pipeline.name} copies it"])
188
+ if len(steps) > 1:
189
+ names = ", ".join(step.name for step in steps)
190
+ raise PipelineValidationError([f"{table}: copied by more than one Step ({names})"])
191
+ [step] = steps
192
+ return step.model_copy(update={"tables": [t for t in step.tables if t.name == table]})
@@ -0,0 +1,59 @@
1
+ """Alerts the Server sends: names, fixed text and the sanitized Step error only."""
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Protocol
5
+
6
+ from adops.application.ports import SUCCEEDED, RunResult
7
+
8
+
9
+ @dataclass(frozen=True)
10
+ class FailureAlert:
11
+ pipeline: str
12
+ environment: str
13
+ step: str
14
+ message: str
15
+
16
+
17
+ STALE_RUN_MESSAGE = "a run left running by a Server crash was marked failed"
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class StaleRunAlert:
22
+ pipeline: str
23
+ environment: str
24
+ message: str = STALE_RUN_MESSAGE
25
+
26
+
27
+ Alert = FailureAlert | StaleRunAlert
28
+
29
+
30
+ class AlertSender(Protocol):
31
+ def send(self, alert: Alert) -> None: ...
32
+
33
+
34
+ def failure_alert(result: RunResult) -> FailureAlert:
35
+ failed = next(step for step in result.steps if step.status not in SUCCEEDED)
36
+ return FailureAlert(
37
+ pipeline=result.pipeline,
38
+ environment=result.environment,
39
+ step=failed.name,
40
+ message=failed.error or str(failed.status),
41
+ )
42
+
43
+
44
+ def notify_failure(result: RunResult, sender: AlertSender) -> str | None:
45
+ return _notify(failure_alert(result), sender)
46
+
47
+
48
+ def notify_stale_run(pipeline: str, environment: str, sender: AlertSender) -> str | None:
49
+ return _notify(StaleRunAlert(pipeline, environment), sender)
50
+
51
+
52
+ def _notify(alert: Alert, sender: AlertSender) -> str | None:
53
+ """Returns a sanitized problem line instead of raising: a failing alert never changes a run."""
54
+ try:
55
+ sender.send(alert)
56
+ except Exception as error:
57
+ # Only the type: the error may carry the webhook URL, which is itself a secret.
58
+ return f"alert could not be sent ({type(error).__name__})"
59
+ return None
@@ -0,0 +1,103 @@
1
+ from collections.abc import Iterable, Mapping
2
+ from dataclasses import dataclass
3
+ from enum import StrEnum
4
+ from typing import Protocol
5
+
6
+ from adops.application.ports import ResolvedConnection
7
+ from adops.application.secrets import (
8
+ MissingSecretError,
9
+ resolve_connection,
10
+ resolve_secret_references,
11
+ )
12
+ from adops.domain.environment import DuckDbConnection, Environment, PostgresConnection
13
+
14
+ WAREHOUSE = "warehouse"
15
+ WAREHOUSE_UNREACHABLE = "Warehouse is unreachable"
16
+
17
+
18
+ def source_unreachable(name: str) -> str:
19
+ return f"Source {name} is unreachable"
20
+
21
+
22
+ def target_unreachable(name: str) -> str:
23
+ return f"Target {name} is unreachable"
24
+
25
+
26
+ class ConnectionKind(StrEnum):
27
+ WAREHOUSE = "warehouse"
28
+ SOURCE = "source"
29
+ TARGET = "target"
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class ConnectionResult:
34
+ kind: ConnectionKind
35
+ name: str
36
+ ok: bool
37
+ message: str | None = None
38
+
39
+
40
+ class ConnectionProbe(Protocol):
41
+ """Connects and disconnects only; answers whether it could, never with driver text."""
42
+
43
+ def postgres(self, connection: ResolvedConnection) -> bool: ...
44
+
45
+ def duckdb(self, path: str) -> bool: ...
46
+
47
+
48
+ def check_connections(
49
+ environment: Environment,
50
+ source_names: Iterable[str],
51
+ env_values: Mapping[str, str],
52
+ probe: ConnectionProbe,
53
+ ) -> list[ConnectionResult]:
54
+ """One result per Warehouse, Source used and Reverse Sync target, in that order."""
55
+ results = [_check_warehouse(environment.warehouse, env_values, probe)]
56
+ for name in sorted(set(source_names)):
57
+ source = environment.sources.get(name)
58
+ unreachable = source_unreachable(name)
59
+ if source is None:
60
+ results.append(ConnectionResult(ConnectionKind.SOURCE, name, False, unreachable))
61
+ else:
62
+ results.append(
63
+ _check_postgres(ConnectionKind.SOURCE, name, source, unreachable, env_values, probe)
64
+ )
65
+ for name, target in environment.targets.items():
66
+ results.append(
67
+ _check_postgres(
68
+ ConnectionKind.TARGET, name, target, target_unreachable(name), env_values, probe
69
+ )
70
+ )
71
+ return results
72
+
73
+
74
+ def _check_warehouse(
75
+ warehouse: PostgresConnection | DuckDbConnection,
76
+ env_values: Mapping[str, str],
77
+ probe: ConnectionProbe,
78
+ ) -> ConnectionResult:
79
+ if isinstance(warehouse, DuckDbConnection):
80
+ ok = probe.duckdb(warehouse.path)
81
+ return _result(ConnectionKind.WAREHOUSE, WAREHOUSE, ok, WAREHOUSE_UNREACHABLE)
82
+ return _check_postgres(
83
+ ConnectionKind.WAREHOUSE, WAREHOUSE, warehouse, WAREHOUSE_UNREACHABLE, env_values, probe
84
+ )
85
+
86
+
87
+ def _check_postgres(
88
+ kind: ConnectionKind,
89
+ name: str,
90
+ connection: PostgresConnection,
91
+ unreachable: str,
92
+ env_values: Mapping[str, str],
93
+ probe: ConnectionProbe,
94
+ ) -> ConnectionResult:
95
+ try:
96
+ secrets = resolve_secret_references(env_values, [connection.password_env])
97
+ except MissingSecretError as missing:
98
+ return ConnectionResult(kind, name, False, str(missing))
99
+ return _result(kind, name, probe.postgres(resolve_connection(connection, secrets)), unreachable)
100
+
101
+
102
+ def _result(kind: ConnectionKind, name: str, ok: bool, unreachable: str) -> ConnectionResult:
103
+ return ConnectionResult(kind, name, ok, None if ok else unreachable)
@@ -0,0 +1,64 @@
1
+ from collections.abc import Mapping, Sequence
2
+ from dataclasses import dataclass
3
+ from typing import Protocol, runtime_checkable
4
+
5
+ from adops.application.ports import ResolvedWarehouse
6
+ from adops.application.run_pipeline import stage_branch_name, stage_environment
7
+ from adops.application.secrets import (
8
+ resolve_secret_references,
9
+ resolve_warehouse,
10
+ secret_references,
11
+ )
12
+ from adops.domain.branch_environment import drop_prefix
13
+ from adops.domain.loader import load_project_settings
14
+
15
+
16
+ @runtime_checkable
17
+ class WarehouseSchemas(Protocol):
18
+ """Lists and drops whole schemas in a Warehouse."""
19
+
20
+ def list_schemas(self, warehouse: ResolvedWarehouse) -> Sequence[str]: ...
21
+
22
+ def drop(self, warehouse: ResolvedWarehouse, schema: str) -> None:
23
+ """Drop the schema and everything in it; a schema that is already gone is fine."""
24
+ ...
25
+
26
+
27
+ @runtime_checkable
28
+ class BranchState(Protocol):
29
+ """The local state a Branch Environment's runs keep outside the Warehouse."""
30
+
31
+ def delete(self, environment: str) -> None: ...
32
+
33
+
34
+ @dataclass(frozen=True)
35
+ class DroppedBranch:
36
+ environment: str
37
+ schemas: tuple[str, ...]
38
+
39
+
40
+ def drop_branch(
41
+ settings_text: str,
42
+ branch: str,
43
+ env: Mapping[str, str],
44
+ schemas: WarehouseSchemas,
45
+ state: BranchState,
46
+ ) -> DroppedBranch:
47
+ """Drop a Branch Environment's schemas from stage's Warehouse, then its local state.
48
+
49
+ Only schemas whose names start with the Branch's exact prefix are dropped, so stage's
50
+ schemas and other Branches' schemas are never touched. The local state goes last, so a
51
+ Warehouse failure leaves it for a re-run.
52
+ """
53
+ stage = stage_environment(load_project_settings(settings_text).environments)
54
+ environment = stage_branch_name(stage, branch)
55
+ secrets = resolve_secret_references(env, secret_references(stage.warehouse, ()))
56
+ warehouse = resolve_warehouse(stage.warehouse, secrets)
57
+ prefix = drop_prefix(environment)
58
+ dropped = tuple(
59
+ sorted(name for name in schemas.list_schemas(warehouse) if name.startswith(prefix))
60
+ )
61
+ for name in dropped:
62
+ schemas.drop(warehouse, name)
63
+ state.delete(environment)
64
+ return DroppedBranch(environment, dropped)
@@ -0,0 +1,274 @@
1
+ from collections.abc import Collection, Mapping, Sequence
2
+ from dataclasses import dataclass, field
3
+ from datetime import datetime
4
+ from enum import StrEnum
5
+ from typing import Protocol, runtime_checkable
6
+
7
+ from adops.domain.checks import CheckResult, LoadFacts, SourceFacts
8
+ from adops.domain.pipeline import SyncStep, SyncTable
9
+ from adops.domain.reverse_sync import ReverseSyncStep
10
+ from adops.domain.reverse_sync_diff import Diff, PreviewSample, Row
11
+ from adops.domain.schema_snapshot import TableShape
12
+ from adops.domain.transform import DbtTestFacts, TransformStep
13
+
14
+ MASK = "***"
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class ResolvedConnection:
19
+ """A Postgres connection with its Secret Reference resolved; the password never prints."""
20
+
21
+ host: str
22
+ port: int
23
+ database: str
24
+ user: str
25
+ password: str = field(repr=False)
26
+
27
+ def __repr__(self) -> str:
28
+ return (
29
+ f"ResolvedConnection(host={self.host!r}, port={self.port!r}, "
30
+ f"database={self.database!r}, user={self.user!r}, password={MASK!r})"
31
+ )
32
+
33
+
34
+ @dataclass(frozen=True)
35
+ class ResolvedDuckDb:
36
+ """A DuckDB Warehouse file, with the path exactly as the Project settings wrote it."""
37
+
38
+ path: str
39
+
40
+
41
+ type ResolvedWarehouse = ResolvedConnection | ResolvedDuckDb
42
+
43
+
44
+ class SourceUnreachable(Exception):
45
+ """A Sync could not connect to the Source; it names the table and holds no driver text."""
46
+
47
+ def __init__(self, table: str) -> None:
48
+ super().__init__(table)
49
+ self.table = table
50
+
51
+
52
+ class WarehouseUnreachable(Exception):
53
+ """An adapter could not connect to the Warehouse; it holds no driver text."""
54
+
55
+
56
+ class WarehouseLocked(Exception):
57
+ """Another run kept the Warehouse locked for the whole wait; names no DSN or file path."""
58
+
59
+ def __init__(self, environment: str, waited_seconds: float) -> None:
60
+ minutes = waited_seconds // 60
61
+ super().__init__(
62
+ f"Another run is using the {environment} Warehouse; "
63
+ f"gave up after {minutes:.0f} minutes."
64
+ )
65
+ self.environment = environment
66
+
67
+
68
+ class TargetUnreachable(Exception):
69
+ """A Reverse Sync could not connect to its Target; it holds no driver text."""
70
+
71
+
72
+ class WriteFailed(Exception):
73
+ """A Reverse Sync write was rolled back and left the Target unchanged; no driver text."""
74
+
75
+
76
+ @dataclass(frozen=True)
77
+ class SyncResult:
78
+ rows_loaded: Mapping[str, int]
79
+ load_facts: Mapping[str, LoadFacts]
80
+
81
+
82
+ @runtime_checkable
83
+ class Sync(Protocol):
84
+ """Copies a Step's allowlisted tables from a Source into the Warehouse and measures them."""
85
+
86
+ def preflight(self, step: SyncStep, source: ResolvedConnection) -> Mapping[str, SourceFacts]:
87
+ ...
88
+
89
+ def sync(
90
+ self, step: SyncStep, source: ResolvedConnection, warehouse: ResolvedWarehouse
91
+ ) -> SyncResult:
92
+ ...
93
+
94
+ def make_columns_nullable(
95
+ self,
96
+ step: SyncStep,
97
+ table: SyncTable,
98
+ warehouse: ResolvedWarehouse,
99
+ columns: Collection[str],
100
+ ) -> None:
101
+ """Let loaded columns that the Source no longer has hold NULL in the Warehouse."""
102
+ ...
103
+
104
+
105
+ @dataclass(frozen=True)
106
+ class TransformResult:
107
+ """What one dbt build measured; it carries model and test names only, never dbt's text."""
108
+
109
+ tests: tuple[DbtTestFacts, ...]
110
+ crashed: bool
111
+ failed_models: tuple[str, ...]
112
+
113
+
114
+ @runtime_checkable
115
+ class Transform(Protocol):
116
+ """Runs a Transform Step's dbt models and tests in the Warehouse and reports what happened."""
117
+
118
+ def run(self, step: TransformStep, warehouse: ResolvedWarehouse) -> TransformResult: ...
119
+
120
+
121
+ @dataclass(frozen=True)
122
+ class ReverseSyncRead:
123
+ """The dbt result rows (dbt column names), the Target's rows (Target column names), measured.
124
+
125
+ `duplicate_keys` and `null_keys` count rows of the dbt result.
126
+ """
127
+
128
+ result_rows: tuple[Row, ...]
129
+ target_rows: tuple[Row, ...]
130
+ target_table_exists: bool
131
+ missing_target_columns: tuple[str, ...]
132
+ duplicate_keys: int
133
+ null_keys: int
134
+
135
+
136
+ @runtime_checkable
137
+ class ReverseSync(Protocol):
138
+ """Reads a dbt result from the Warehouse and applies a computed Diff to a Target table."""
139
+
140
+ def read(
141
+ self, step: ReverseSyncStep, warehouse: ResolvedWarehouse, target: ResolvedConnection
142
+ ) -> ReverseSyncRead: ...
143
+
144
+ def apply(self, step: ReverseSyncStep, target: ResolvedConnection, diff: Diff) -> None:
145
+ """Apply exactly `diff` in one transaction."""
146
+ ...
147
+
148
+
149
+ @runtime_checkable
150
+ class SchemaSnapshotStore(Protocol):
151
+ """Keeps each Source table's last accepted shape in the Warehouse, and the ids of the
152
+ accepted-change records the Environment has applied; it never judges a change."""
153
+
154
+ def load(
155
+ self, warehouse: ResolvedWarehouse, pipeline: str, source: str, table: str
156
+ ) -> TableShape | None: ...
157
+
158
+ def applied_record_ids(self, warehouse: ResolvedWarehouse) -> frozenset[str]: ...
159
+
160
+ def save(
161
+ self,
162
+ warehouse: ResolvedWarehouse,
163
+ pipeline: str,
164
+ source: str,
165
+ table: str,
166
+ shape: TableShape,
167
+ *,
168
+ applied_record_ids: Sequence[str] = (),
169
+ ) -> None:
170
+ """Store the shape and the record ids atomically: both are saved, or neither is."""
171
+ ...
172
+
173
+
174
+ @runtime_checkable
175
+ class StepFingerprintStore(Protocol):
176
+ """Keeps each Step's Step Fingerprint from stage's last successful run, in Step order."""
177
+
178
+ def load(self, pipeline: str) -> Mapping[str, str]: ...
179
+
180
+ def save(self, pipeline: str, step: str, fingerprint: str) -> None: ...
181
+
182
+
183
+ @runtime_checkable
184
+ class ProjectFiles(Protocol):
185
+ def read_tree(self, relative_dir: str) -> Mapping[str, bytes]:
186
+ """Every file under a Project folder, keyed by its POSIX path relative to that folder."""
187
+ ...
188
+
189
+
190
+ @runtime_checkable
191
+ class Clock(Protocol):
192
+ def now(self) -> datetime:
193
+ """The current moment, timezone-aware."""
194
+ ...
195
+
196
+
197
+ class StepStatus(StrEnum):
198
+ PASSED = "passed"
199
+ FAILED = "failed"
200
+ CHECK_FAILED = "check_failed"
201
+ SKIPPED = "skipped"
202
+ DEFERRED = "deferred"
203
+
204
+
205
+ SUCCEEDED = frozenset({StepStatus.PASSED, StepStatus.DEFERRED})
206
+
207
+
208
+ @dataclass(frozen=True)
209
+ class ReverseSyncPreview:
210
+ """How many Target rows a Reverse Sync changes, with a key-only sample; never row values."""
211
+
212
+ inserts: int
213
+ updates: int
214
+ deletes: int
215
+ kept: int
216
+ sample: PreviewSample
217
+ written: bool
218
+
219
+
220
+ @dataclass(frozen=True)
221
+ class StepReport:
222
+ name: str
223
+ status: StepStatus
224
+ checks: tuple[CheckResult, ...] = ()
225
+ rows_loaded: Mapping[str, int] = field(default_factory=dict)
226
+ error: str | None = None
227
+ preview: ReverseSyncPreview | None = None
228
+ retryable: bool = False
229
+ notes: tuple[str, ...] = ()
230
+
231
+
232
+ @dataclass(frozen=True)
233
+ class StepOutcome:
234
+ checks: tuple[CheckResult, ...]
235
+ rows_loaded: Mapping[str, int]
236
+ preview: ReverseSyncPreview | None = None
237
+ notes: tuple[str, ...] = ()
238
+
239
+
240
+ class StepTask(Protocol):
241
+ """One Step, ready to run, with everything it needs bound in. Raises StepError on failure."""
242
+
243
+ @property
244
+ def name(self) -> str: ...
245
+
246
+ def __call__(self, sync: Sync) -> StepOutcome: ...
247
+
248
+
249
+ @dataclass(frozen=True)
250
+ class RunPlan:
251
+ pipeline: str
252
+ environment: str
253
+ steps: tuple[StepTask, ...]
254
+
255
+
256
+ @dataclass(frozen=True)
257
+ class RunResult:
258
+ pipeline: str
259
+ environment: str
260
+ steps: tuple[StepReport, ...]
261
+
262
+ @property
263
+ def succeeded(self) -> bool:
264
+ return all(step.status in SUCCEEDED for step in self.steps)
265
+
266
+ @property
267
+ def retryable(self) -> bool:
268
+ first_failure = next((s for s in self.steps if s.status not in SUCCEEDED), None)
269
+ return first_failure is not None and first_failure.retryable
270
+
271
+
272
+ @runtime_checkable
273
+ class Orchestrator(Protocol):
274
+ def execute(self, plan: RunPlan, sync: Sync) -> RunResult: ...