Skip to content

Commit 5ce3244

Browse files
mkirshadclaude
andcommitted
fix: warn when multi-repo projects resolve to different state connections or gateways
A multi-repo context resolves the state connection and each gateway name from the first project's config only, so projects that disagree on them were silently ignored: `run` evaluated only the first project's models while reporting success. Warn at state-sync creation instead, so the mismatch is visible where it happens. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Signed-off-by: Muhammad Kashif Irshad <2148913+mkirshad@users.noreply.github.com>
1 parent cfde8eb commit 5ce3244

3 files changed

Lines changed: 133 additions & 0 deletions

File tree

‎docs/guides/multi_repo.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,10 @@ Although mono repos are convenient and easy to use, sometimes your organization
44
SQLMesh provides native support for multiple repos and makes it easy to maintain data consistency and correctness even with multiple repos.
55
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).
66

7+
!!! note
8+
9+
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.
10+
711
## Bootstrapping multiple projects
812
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).
913

‎sqlmesh/core/context.py‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@
6060
from sqlmesh.core.config import (
6161
CategorizerConfig,
6262
Config,
63+
GatewayConfig,
6364
load_configs,
6465
)
6566
from sqlmesh.core.config.connection import ConnectionConfig
@@ -421,6 +422,7 @@ def __init__(
421422
self._linters: t.Dict[str, Linter] = {}
422423
self._loaded: bool = False
423424
self._materializations_loaded: bool = False
425+
self._multi_repo_connections_validated: bool = False
424426
self._load_state: bool = load_state
425427
self._uncached_model_names: t.Set[str] = set()
426428
self._selector_cls = selector or NativeSelector
@@ -3364,7 +3366,58 @@ def _print_state_versions(
33643366
version = f"{getattr(previous_versions, attribute)} -> {version}"
33653367
self.console.log_status_update(f"{label}: {version}")
33663368

3369+
def _validate_multi_repo_connections(self) -> None:
3370+
"""Validates that the projects of a multi-repo context can share this context's state.
3371+
3372+
Global concerns like the state connection and engine adapters are resolved once for
3373+
the entire context, so projects that disagree on them would be silently ignored.
3374+
"""
3375+
if self._multi_repo_connections_validated or len(self.configs) < 2:
3376+
return
3377+
self._multi_repo_connections_validated = True
3378+
3379+
state_connection_source: t.Optional[t.Tuple[Path, ConnectionConfig]] = None
3380+
gateway_sources: t.Dict[str, t.Tuple[Path, GatewayConfig]] = {}
3381+
3382+
for path, config in self.configs.items():
3383+
gateway_name = self.gateway or config.default_gateway_name
3384+
try:
3385+
state_connection = config.get_state_connection(
3386+
gateway_name
3387+
) or config.get_connection(gateway_name)
3388+
except ConfigError:
3389+
state_connection = None
3390+
3391+
if state_connection is not None:
3392+
if state_connection_source is None:
3393+
state_connection_source = (path, state_connection)
3394+
elif state_connection != state_connection_source[1]:
3395+
self.console.log_warning(
3396+
f"Project '{path}' resolves to a different state connection than project "
3397+
f"'{state_connection_source[0]}', whose state connection is used for all "
3398+
"projects. SQLMesh reads environment state from a single state connection, "
3399+
"so environments planned against the other projects' own state connections "
3400+
"are not visible here and their models may never be evaluated by `plan` "
3401+
"or `run`. Configure the same `state_connection` in every project."
3402+
)
3403+
3404+
gateways = config.gateways
3405+
if not isinstance(gateways, dict):
3406+
continue
3407+
for name, gateway in gateways.items():
3408+
gateway_source = gateway_sources.get(name)
3409+
if gateway_source is None:
3410+
gateway_sources[name] = (path, gateway)
3411+
elif gateway != gateway_source[1]:
3412+
self.console.log_warning(
3413+
f"Gateway '{name}' is defined differently in project '{path}' than in "
3414+
f"project '{gateway_source[0]}'; the definition from "
3415+
f"'{gateway_source[0]}' is used for all projects."
3416+
)
3417+
33673418
def _new_state_sync(self) -> StateSync:
3419+
if self._provided_state_sync is None:
3420+
self._validate_multi_repo_connections()
33683421
return self._provided_state_sync or self._scheduler.create_state_sync(self)
33693422

33703423
def _new_selector(

‎tests/core/test_context.py‎

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4680,3 +4680,79 @@ def test_grants_through_plan_apply(sushi_context, mocker):
46804680
# plan for prod
46814681
sushi_context.plan(no_prompts=True, auto_apply=True)
46824682
assert sync_grants_mock.call_count == 2
4683+
4684+
4685+
def test_multi_repo_mismatched_state_connections_warn(tmp_path: Path) -> None:
4686+
"""Multi-repo state should be shared: with differing state connections, the first
4687+
project's state connection is used and the other projects' environments are not
4688+
visible, so a warning points this out instead of leaving the run silent."""
4689+
repo_one = tmp_path / "repo_one"
4690+
repo_two = tmp_path / "repo_two"
4691+
(repo_one / "models").mkdir(parents=True)
4692+
(repo_two / "models").mkdir(parents=True)
4693+
4694+
def make_config(database: str) -> Config:
4695+
return Config(
4696+
gateways={
4697+
"local": GatewayConfig(
4698+
connection=DuckDBConnectionConfig(database=str(tmp_path / database))
4699+
)
4700+
},
4701+
default_gateway="local",
4702+
model_defaults=ModelDefaultsConfig(dialect="duckdb"),
4703+
)
4704+
4705+
context = Context(
4706+
paths=[repo_one, repo_two],
4707+
config={
4708+
repo_one: make_config("one.duckdb"),
4709+
repo_two: make_config("two.duckdb"),
4710+
},
4711+
)
4712+
4713+
with patch.object(get_console(), "log_warning") as mock_warning:
4714+
assert context.state_sync is not None
4715+
4716+
warnings = [call_args[0][0] for call_args in mock_warning.call_args_list]
4717+
assert any("resolves to a different state connection" in warning for warning in warnings), (
4718+
warnings
4719+
)
4720+
4721+
4722+
def test_multi_repo_conflicting_gateway_definitions_warn(tmp_path: Path) -> None:
4723+
"""A shared state connection is accepted, but same-named gateways that differ
4724+
across projects log a warning because the first definition wins."""
4725+
repo_one = tmp_path / "repo_one"
4726+
repo_two = tmp_path / "repo_two"
4727+
(repo_one / "models").mkdir(parents=True)
4728+
(repo_two / "models").mkdir(parents=True)
4729+
4730+
state_connection = DuckDBConnectionConfig(database=str(tmp_path / "state.duckdb"))
4731+
4732+
def make_config(database: str) -> Config:
4733+
return Config(
4734+
gateways={
4735+
"local": GatewayConfig(
4736+
connection=DuckDBConnectionConfig(database=str(tmp_path / database)),
4737+
state_connection=state_connection,
4738+
)
4739+
},
4740+
default_gateway="local",
4741+
model_defaults=ModelDefaultsConfig(dialect="duckdb"),
4742+
)
4743+
4744+
context = Context(
4745+
paths=[repo_one, repo_two],
4746+
config={
4747+
repo_one: make_config("one.duckdb"),
4748+
repo_two: make_config("two.duckdb"),
4749+
},
4750+
)
4751+
4752+
with patch.object(get_console(), "log_warning") as mock_warning:
4753+
assert context.state_sync is not None
4754+
4755+
warnings = [call_args[0][0] for call_args in mock_warning.call_args_list]
4756+
assert any("Gateway 'local' is defined differently" in warning for warning in warnings), (
4757+
warnings
4758+
)

0 commit comments

Comments
 (0)