From fe6aa118556e870e467d361d1453eaee05be43b8 Mon Sep 17 00:00:00 2001 From: mokashang Date: Sat, 14 Nov 2026 09:34:58 -0800 Subject: [PATCH 1/2] fix(cli): let `plan --restate-model` run without local model files `sqlmesh run` can refresh an environment that has no local model definitions, but `sqlmesh plan --restate-model` on the same project errored out with "doesn't seem to have any models". A restatement is supposed to operate against state alone (local changes are deliberately ignored, see `plan_builder.force_no_diff`), so it should not require the model files to be present. Two changes: * `sqlmesh/cli/main.py`: when `plan` is invoked with `--restate-model` or `-r`, skip the local load and the "no models" guard, mirroring how `run` is handled via `SKIP_LOAD_COMMANDS`. * `sqlmesh/core/context.py`: when expanding `restate_models` selections, pull snapshots from the target environment in addition to local models. `select_models` already combines environment and local models this way; restatement selections should too, so a model that exists only in state can still be named. Fixes #3260 Signed-off-by: mokashang --- sqlmesh/cli/main.py | 10 ++++++++++ sqlmesh/core/context.py | 12 +++++++++++- tests/cli/test_cli.py | 37 +++++++++++++++++++++++++++++++++++++ 3 files changed, 58 insertions(+), 1 deletion(-) diff --git a/sqlmesh/cli/main.py b/sqlmesh/cli/main.py index 896b47abd7..6b30d570e6 100644 --- a/sqlmesh/cli/main.py +++ b/sqlmesh/cli/main.py @@ -44,6 +44,9 @@ LOCAL_ONLY_COMMANDS = ("format",) # Commands that are local-only when they're passed --local. OPTIONAL_LOCAL_COMMANDS = ("lint", "test") +# Flags that, when passed to `plan`, make the command restatement-only and allow +# running without local model definitions, since restatements operate against state. +_RESTATE_ONLY_PLAN_FLAGS = ("--restate-model", "-r") class _SQLMeshGroup(click.Group): @@ -151,6 +154,13 @@ def cli( if ctx.invoked_subcommand == "lint": load = False + # `plan --restate-model` works entirely against state, so missing local model + # files shouldn't block it (parity with `run`). + if ctx.invoked_subcommand == "plan" and any( + arg in _RESTATE_ONLY_PLAN_FLAGS for arg in ctx.meta["subcommand_args"] + ): + load = False + configs = load_configs(config, Context.CONFIG_TYPE, paths, dotenv_path=dotenv) log_limit = list(configs.values())[0].log_limit diff --git a/sqlmesh/core/context.py b/sqlmesh/core/context.py index fd7f8ad071..9c742c2d4c 100644 --- a/sqlmesh/core/context.py +++ b/sqlmesh/core/context.py @@ -1771,7 +1771,17 @@ def plan_builder( expanded_restate_models = None if restate_models is not None: - expanded_restate_models = model_selector.expand_model_selections(restate_models) + # Restatements operate entirely against state, so the selector must be + # able to find models that exist only in the target environment (for + # example when local model files are absent). + env_models_for_restate = model_selector._load_env_models( + environment, + fallback_env_name=create_from or c.PROD, + ensure_finalized_snapshots=self.config.plan.use_finalized_state, + ) + expanded_restate_models = model_selector.expand_model_selections( + restate_models, models={**env_models_for_restate, **self._models} + ) if (restate_models is not None and not expanded_restate_models) or ( backfill_models is not None and not backfill_models and not selected_deletion_fqns diff --git a/tests/cli/test_cli.py b/tests/cli/test_cli.py index 1602dc3b11..59954aa37d 100644 --- a/tests/cli/test_cli.py +++ b/tests/cli/test_cli.py @@ -370,6 +370,43 @@ def test_plan_restate_model(runner, tmp_path): assert "Virtual layer updated" not in result.output +def test_plan_restate_model_without_local_definitions(runner, tmp_path): + """`plan --restate-model` should work against state alone, like `run`. + + Reproduces https://github.com/SQLMesh/sqlmesh/issues/3260. + """ + create_example_project(tmp_path) + init_prod_and_backfill(runner, tmp_path) + + # Wipe every local project directory, keeping only config.yaml + db.db. + for subdir in ("models", "seeds", "tests", "audits", "macros", ".cache"): + rmtree(tmp_path / subdir, ignore_errors=True) + assert not (tmp_path / "models").exists() + + result = runner.invoke( + cli, + [ + "--log-file-dir", + tmp_path, + "--paths", + tmp_path, + "plan", + "--restate-model", + "sqlmesh_example.full_model", + "--start", + "", + "--end", + "", + "--auto-apply", + ], + ) + assert result.exit_code == 0, result.output + assert "doesn't seem to have any models" not in result.output + assert "Models selected for restatement" in result.output + assert "sqlmesh_example.full_model" in result.output + assert_model_batches_executed(result) + + @pytest.mark.parametrize("flag", ["--skip-backfill", "--dry-run"]) def test_plan_skip_backfill(runner, tmp_path, flag): create_example_project(tmp_path) From c5d680a7d3f05864cfbb9373a2684ec3cc42875c Mon Sep 17 00:00:00 2001 From: mokashang Date: Tue, 24 Nov 2026 11:28:47 -0800 Subject: [PATCH 2/2] fix(cli): keep local loading on for restate plans, bypass empty-project guard Previous revision disabled local loading entirely for `plan --restate-model`, which broke three cases that work on main: `-r X --backfill-model 'Y.*'` (backfill selector sees no local models), `-r '+X'` (upstream selector DAG is empty), and unit tests tied to a restate plan. Address the maintainer review on #6219: * `sqlmesh/cli/main.py`: keep `load = True` for restate plans and only skip the `doesn't seem to have any models` guard via `not restating`. New `_is_restate_arg` helper recognises `--restate-model`, `--restate-model=X`, `-r` and `-rX` (all four Click spellings). * `sqlmesh/core/context.py`: build a dedicated selector for restate expansion over the union of local and environment models, with a matching DAG, so `-r '+X'` can still reach upstream dependencies that only exist in the target environment. New regression tests parametrise all four `--restate-model` spellings, cover `-r '+full_model'` upstream expansion against state alone, pin the `--skip-linter -r X --backfill-model 'Y.*'` combination with local models present, and keep the ordinary `plan` empty-project error path. Signed-off-by: mokashang --- sqlmesh/cli/main.py | 31 ++++++++---- sqlmesh/core/context.py | 18 ++++--- tests/cli/test_cli.py | 104 ++++++++++++++++++++++++++++++++++++++-- 3 files changed, 134 insertions(+), 19 deletions(-) diff --git a/sqlmesh/cli/main.py b/sqlmesh/cli/main.py index 6b30d570e6..296f33a8d1 100644 --- a/sqlmesh/cli/main.py +++ b/sqlmesh/cli/main.py @@ -44,9 +44,19 @@ LOCAL_ONLY_COMMANDS = ("format",) # Commands that are local-only when they're passed --local. OPTIONAL_LOCAL_COMMANDS = ("lint", "test") -# Flags that, when passed to `plan`, make the command restatement-only and allow -# running without local model definitions, since restatements operate against state. -_RESTATE_ONLY_PLAN_FLAGS = ("--restate-model", "-r") + + +def _is_restate_arg(arg: str) -> bool: + """Whether ``arg`` is a ``--restate-model`` / ``-r`` option token. + + Covers the four spellings Click accepts: ``--restate-model VALUE``, + ``--restate-model=VALUE``, ``-r VALUE`` and ``-rVALUE``. + """ + if arg == "--restate-model" or arg.startswith("--restate-model="): + return True + if arg == "-r" or (arg.startswith("-r") and not arg.startswith("--")): + return True + return False class _SQLMeshGroup(click.Group): @@ -154,12 +164,13 @@ def cli( if ctx.invoked_subcommand == "lint": load = False - # `plan --restate-model` works entirely against state, so missing local model - # files shouldn't block it (parity with `run`). - if ctx.invoked_subcommand == "plan" and any( - arg in _RESTATE_ONLY_PLAN_FLAGS for arg in ctx.meta["subcommand_args"] - ): - load = False + # `plan --restate-model` operates entirely against state, so a project with no + # local model definitions should still be allowed to run (parity with `run`). + # Local loading itself stays on so that backfill expansion, unit tests, and the + # linter continue to work when model files are present. + restating = ctx.invoked_subcommand == "plan" and any( + _is_restate_arg(arg) for arg in ctx.meta["subcommand_args"] + ) configs = load_configs(config, Context.CONFIG_TYPE, paths, dotenv_path=dotenv) log_limit = list(configs.values())[0].log_limit @@ -179,7 +190,7 @@ def cli( logger.exception("Failed to initialize SQLMesh context") raise - if load and not context.models: + if load and not context.models and not restating: raise click.ClickException( f"`{paths}` doesn't seem to have any models... cd into the proper directory or specify the path(s) with -p." ) diff --git a/sqlmesh/core/context.py b/sqlmesh/core/context.py index 9c742c2d4c..a8ff8719ac 100644 --- a/sqlmesh/core/context.py +++ b/sqlmesh/core/context.py @@ -1771,17 +1771,23 @@ def plan_builder( expanded_restate_models = None if restate_models is not None: - # Restatements operate entirely against state, so the selector must be - # able to find models that exist only in the target environment (for - # example when local model files are absent). + # Restatements operate entirely against state. Build a dedicated + # selector over the union of local and environment models so that + # both name lookup and upstream expansion (e.g. ``-r '+model'``) + # reach dependencies that only exist in the target environment. env_models_for_restate = model_selector._load_env_models( environment, fallback_env_name=create_from or c.PROD, ensure_finalized_snapshots=self.config.plan.use_finalized_state, ) - expanded_restate_models = model_selector.expand_model_selections( - restate_models, models={**env_models_for_restate, **self._models} - ) + restate_models_combined: UniqueKeyDict[str, Model] = UniqueKeyDict("models") + for fqn, model in {**env_models_for_restate, **self._models}.items(): + restate_models_combined[fqn] = model + restate_dag: DAG[str] = DAG() + for fqn, model in restate_models_combined.items(): + restate_dag.add(fqn, model.depends_on) + restate_selector = self._new_selector(models=restate_models_combined, dag=restate_dag) + expanded_restate_models = restate_selector.expand_model_selections(restate_models) if (restate_models is not None and not expanded_restate_models) or ( backfill_models is not None and not backfill_models and not selected_deletion_fqns diff --git a/tests/cli/test_cli.py b/tests/cli/test_cli.py index 59954aa37d..790e98afa6 100644 --- a/tests/cli/test_cli.py +++ b/tests/cli/test_cli.py @@ -370,10 +370,21 @@ def test_plan_restate_model(runner, tmp_path): assert "Virtual layer updated" not in result.output -def test_plan_restate_model_without_local_definitions(runner, tmp_path): +@pytest.mark.parametrize( + "restate_args", + [ + pytest.param(["--restate-model", "sqlmesh_example.full_model"], id="long-space"), + pytest.param(["--restate-model=sqlmesh_example.full_model"], id="long-equals"), + pytest.param(["-r", "sqlmesh_example.full_model"], id="short-space"), + pytest.param(["-rsqlmesh_example.full_model"], id="short-attached"), + ], +) +def test_plan_restate_model_without_local_definitions(runner, tmp_path, restate_args): """`plan --restate-model` should work against state alone, like `run`. - Reproduces https://github.com/SQLMesh/sqlmesh/issues/3260. + Reproduces https://github.com/SQLMesh/sqlmesh/issues/3260. Each + parametrization covers one of the spellings Click accepts for the + option so the empty-project bypass tracks whatever form the user types. """ create_example_project(tmp_path) init_prod_and_backfill(runner, tmp_path) @@ -383,6 +394,53 @@ def test_plan_restate_model_without_local_definitions(runner, tmp_path): rmtree(tmp_path / subdir, ignore_errors=True) assert not (tmp_path / "models").exists() + result = runner.invoke( + cli, + [ + "--log-file-dir", + tmp_path, + "--paths", + tmp_path, + "plan", + *restate_args, + "--start", + "", + "--end", + "", + "--auto-apply", + ], + ) + assert result.exit_code == 0, result.output + assert "doesn't seem to have any models" not in result.output + assert "Models selected for restatement" in result.output + assert "sqlmesh_example.full_model" in result.output + assert_model_batches_executed(result) + + +def test_plan_without_restate_and_no_local_models_still_errors(runner, tmp_path): + """A non-restatement plan against an empty project must still error out.""" + create_example_project(tmp_path) + init_prod_and_backfill(runner, tmp_path) + + for subdir in ("models", "seeds", "tests", "audits", "macros", ".cache"): + rmtree(tmp_path / subdir, ignore_errors=True) + + result = runner.invoke( + cli, + ["--log-file-dir", tmp_path, "--paths", tmp_path, "plan"], + ) + assert result.exit_code == 1 + assert "doesn't seem to have any models" in result.output + + +def test_plan_restate_upstream_models_without_local_definitions(runner, tmp_path): + """``-r '+'`` should restate upstream deployed models even without local files.""" + create_example_project(tmp_path) + init_prod_and_backfill(runner, tmp_path) + + for subdir in ("models", "seeds", "tests", "audits", "macros", ".cache"): + rmtree(tmp_path / subdir, ignore_errors=True) + result = runner.invoke( cli, [ @@ -392,7 +450,47 @@ def test_plan_restate_model_without_local_definitions(runner, tmp_path): tmp_path, "plan", "--restate-model", + "+sqlmesh_example.full_model", + "--start", + "", + "--end", + "", + "--auto-apply", + ], + ) + assert result.exit_code == 0, result.output + assert "Models selected for restatement" in result.output + # full_model depends on incremental_model, which depends on seed_model; + # a `+` selector must pick both upstream dependencies from state. + assert "sqlmesh_example.full_model" in result.output + assert "sqlmesh_example.incremental_model" in result.output + assert_model_batches_executed(result) + + +def test_plan_restate_model_with_backfill_model_and_skip_linter(runner, tmp_path): + """Restatements with local models and ``--backfill-model`` must still expand selectors. + + With local model files present, ``plan --skip-linter --restate-model X + --backfill-model Y`` has to run both selector expansions against the + local project. Keeping local loading enabled for restate plans is what + makes this case work. + """ + create_example_project(tmp_path) + init_prod_and_backfill(runner, tmp_path) + + result = runner.invoke( + cli, + [ + "--log-file-dir", + tmp_path, + "--paths", + tmp_path, + "plan", + "--skip-linter", + "--restate-model", "sqlmesh_example.full_model", + "--backfill-model", + "sqlmesh_example.*", "--start", "", "--end", @@ -401,7 +499,7 @@ def test_plan_restate_model_without_local_definitions(runner, tmp_path): ], ) assert result.exit_code == 0, result.output - assert "doesn't seem to have any models" not in result.output + assert "Selector did not return any models" not in result.output assert "Models selected for restatement" in result.output assert "sqlmesh_example.full_model" in result.output assert_model_batches_executed(result)