diff --git a/docs/guides/multi_repo.md b/docs/guides/multi_repo.md index 4dae4de57e..9641fa711e 100644 --- a/docs/guides/multi_repo.md +++ b/docs/guides/multi_repo.md @@ -4,6 +4,10 @@ Although mono repos are convenient and easy to use, sometimes your organization SQLMesh provides native support for multiple repos and makes it easy to maintain data consistency and correctness even with multiple repos. If you are wanting to separate your systems/data and provide isolation, checkout the [isolated systems guide](https://sqlmesh.readthedocs.io/en/stable/guides/isolated_systems/?h=isolated). +!!! note + + All projects of a multi-repo setup should share the same [state connection](../reference/configuration.md#connections): SQLMesh reads environment state from a single state connection, so if the projects resolve to different ones, the first project's state connection is used for all of them and commands like `plan` and `run` log a warning, because environments planned against the other projects' own state connections are not visible. Gateways that share a name across projects should also be defined identically — otherwise the definition from the first project wins, with a warning. + ## Bootstrapping multiple projects Setting up SQLMesh with multiple repos is quite simple. Copy the contents of this example [multi-repo project](https://github.com/SQLMesh/sqlmesh/tree/main/examples/multi). diff --git a/sqlmesh/core/context.py b/sqlmesh/core/context.py index a8ff8719ac..27637ffc23 100644 --- a/sqlmesh/core/context.py +++ b/sqlmesh/core/context.py @@ -60,6 +60,7 @@ from sqlmesh.core.config import ( CategorizerConfig, Config, + GatewayConfig, load_configs, ) from sqlmesh.core.config.connection import ConnectionConfig @@ -421,6 +422,7 @@ def __init__( self._linters: t.Dict[str, Linter] = {} self._loaded: bool = False self._materializations_loaded: bool = False + self._multi_repo_connections_validated: bool = False self._load_state: bool = load_state self._uncached_model_names: t.Set[str] = set() self._selector_cls = selector or NativeSelector @@ -3364,7 +3366,58 @@ def _print_state_versions( version = f"{getattr(previous_versions, attribute)} -> {version}" self.console.log_status_update(f"{label}: {version}") + def _validate_multi_repo_connections(self) -> None: + """Validates that the projects of a multi-repo context can share this context's state. + + Global concerns like the state connection and engine adapters are resolved once for + the entire context, so projects that disagree on them would be silently ignored. + """ + if self._multi_repo_connections_validated or len(self.configs) < 2: + return + self._multi_repo_connections_validated = True + + state_connection_source: t.Optional[t.Tuple[Path, ConnectionConfig]] = None + gateway_sources: t.Dict[str, t.Tuple[Path, GatewayConfig]] = {} + + for path, config in self.configs.items(): + gateway_name = self.gateway or config.default_gateway_name + try: + state_connection = config.get_state_connection( + gateway_name + ) or config.get_connection(gateway_name) + except ConfigError: + state_connection = None + + if state_connection is not None: + if state_connection_source is None: + state_connection_source = (path, state_connection) + elif state_connection != state_connection_source[1]: + self.console.log_warning( + f"Project '{path}' resolves to a different state connection than project " + f"'{state_connection_source[0]}', whose state connection is used for all " + "projects. SQLMesh reads environment state from a single state connection, " + "so environments planned against the other projects' own state connections " + "are not visible here and their models may never be evaluated by `plan` " + "or `run`. Configure the same `state_connection` in every project." + ) + + gateways = config.gateways + if not isinstance(gateways, dict): + continue + for name, gateway in gateways.items(): + gateway_source = gateway_sources.get(name) + if gateway_source is None: + gateway_sources[name] = (path, gateway) + elif gateway != gateway_source[1]: + self.console.log_warning( + f"Gateway '{name}' is defined differently in project '{path}' than in " + f"project '{gateway_source[0]}'; the definition from " + f"'{gateway_source[0]}' is used for all projects." + ) + def _new_state_sync(self) -> StateSync: + if self._provided_state_sync is None: + self._validate_multi_repo_connections() return self._provided_state_sync or self._scheduler.create_state_sync(self) def _new_selector( diff --git a/tests/core/test_context.py b/tests/core/test_context.py index 71276b7396..82b499022a 100644 --- a/tests/core/test_context.py +++ b/tests/core/test_context.py @@ -4680,3 +4680,79 @@ def test_grants_through_plan_apply(sushi_context, mocker): # plan for prod sushi_context.plan(no_prompts=True, auto_apply=True) assert sync_grants_mock.call_count == 2 + + +def test_multi_repo_mismatched_state_connections_warn(tmp_path: Path) -> None: + """Multi-repo state should be shared: with differing state connections, the first + project's state connection is used and the other projects' environments are not + visible, so a warning points this out instead of leaving the run silent.""" + repo_one = tmp_path / "repo_one" + repo_two = tmp_path / "repo_two" + (repo_one / "models").mkdir(parents=True) + (repo_two / "models").mkdir(parents=True) + + def make_config(database: str) -> Config: + return Config( + gateways={ + "local": GatewayConfig( + connection=DuckDBConnectionConfig(database=str(tmp_path / database)) + ) + }, + default_gateway="local", + model_defaults=ModelDefaultsConfig(dialect="duckdb"), + ) + + context = Context( + paths=[repo_one, repo_two], + config={ + repo_one: make_config("one.duckdb"), + repo_two: make_config("two.duckdb"), + }, + ) + + with patch.object(get_console(), "log_warning") as mock_warning: + assert context.state_sync is not None + + warnings = [call_args[0][0] for call_args in mock_warning.call_args_list] + assert any("resolves to a different state connection" in warning for warning in warnings), ( + warnings + ) + + +def test_multi_repo_conflicting_gateway_definitions_warn(tmp_path: Path) -> None: + """A shared state connection is accepted, but same-named gateways that differ + across projects log a warning because the first definition wins.""" + repo_one = tmp_path / "repo_one" + repo_two = tmp_path / "repo_two" + (repo_one / "models").mkdir(parents=True) + (repo_two / "models").mkdir(parents=True) + + state_connection = DuckDBConnectionConfig(database=str(tmp_path / "state.duckdb")) + + def make_config(database: str) -> Config: + return Config( + gateways={ + "local": GatewayConfig( + connection=DuckDBConnectionConfig(database=str(tmp_path / database)), + state_connection=state_connection, + ) + }, + default_gateway="local", + model_defaults=ModelDefaultsConfig(dialect="duckdb"), + ) + + context = Context( + paths=[repo_one, repo_two], + config={ + repo_one: make_config("one.duckdb"), + repo_two: make_config("two.duckdb"), + }, + ) + + with patch.object(get_console(), "log_warning") as mock_warning: + assert context.state_sync is not None + + warnings = [call_args[0][0] for call_args in mock_warning.call_args_list] + assert any("Gateway 'local' is defined differently" in warning for warning in warnings), ( + warnings + )