Failed lookback interval runs create data holes
Core Problem
When an INCREMENTAL_BY_TIME_RANGE model with lookback configured fails during a lookback interval run, it creates a data hole (empty interval) rather than preserving the existing stale data. This occurs because the default materialization strategy for most engines is DELETE + INSERT, which is not atomic. You can find the materialization strategy documentation in docs/concepts/models/model_kinds.md.
Materialization Strategy
The DELETE + INSERT strategy works in two steps:
- DELETE existing data for the time interval
- INSERT new data for that interval
If step 1 succeeds but step 2 fails, the interval is left empty. This is fundamentally different from atomic operations like INSERT OVERWRITE (used by Spark/Databricks) which either fully succeed or fully fail. The strategy table is documented in docs/concepts/models/model_kinds.md.
Lookback Mechanism
The lookback parameter is designed to handle late-arriving data by reprocessing recent intervals on each run. The lookback parameter is documented in docs/concepts/models/overview.md.
For example, with lookback=2 and daily intervals:
- On January 5th, SQLMesh processes January 5th, 4th, and 3rd
- On January 6th, SQLMesh processes January 6th, 5th, and 4th
The lookback_start method calculates the effective start date by moving back lookback intervals. This method is implemented in sqlmesh/core/model/meta.py.
Interval Computation Logic
The compute_missing_intervals function determines which intervals need processing. This function is implemented in sqlmesh/core/snapshot/definition.py.
Key logic:
- Expands the time range into individual interval boundaries
- Compares against already-processed intervals
- If
lookback > 0, adds additional intervals to the missing set based on parent interval availability
The critical section for lookback handling checks if parent intervals are missing and adds current intervals to the missing set accordingly. However, this doesn't create a mechanism for retrying failed lookback intervals specifically.
Scheduler Behavior
The scheduler's merged_missing_intervals function computes missing intervals across all snapshots. This function is implemented in sqlmesh/core/scheduler.py.
This function:
- Takes a collection of snapshots
- Calls
compute_interval_paramsfor each - Returns a mapping of snapshots to their missing intervals
Crucially, it treats all missing intervals equally - there's no distinction between:
- Current intervals that failed
- Lookback intervals that failed
- Intervals that were never processed
The Gap
The gap exists because:
-
No Atomicity Guarantee: DELETE + INSERT is not atomic, so failures after DELETE leave data holes. This is documented in
docs/concepts/models/model_kinds.md. -
No Special Retry Logic: The scheduler doesn't distinguish between failed lookback intervals and other missing intervals. The scheduler logic is in
sqlmesh/core/scheduler.py. -
Assumption of Success: The lookback mechanism assumes intervals will either succeed or be naturally retried on the next scheduled run. However, if the failure is transient (e.g., network issue), the next scheduled run may have moved past the lookback window.
-
Interval Tracking: While failed intervals should theoretically be included in missing intervals (since they're never added to the processed intervals list), there's no explicit mechanism to prioritize retrying them. The interval tracking logic is in
sqlmesh/core/snapshot/definition.py.
Test Case Evidence
The test cases in tests/core/test_snapshot.py show the expected behavior of lookback. Specifically, the test_missing_intervals_past_end_date_with_lookback function demonstrates that lookback intervals ARE included in missing intervals when they're removed.
However, this doesn't address the case where a DELETE succeeded but INSERT failed - the interval would be missing from the processed list, but the data would also be gone from the target table.
Gap Detection Logic
SQLMesh does have gap detection logic in _ensure_no_gaps, but this is only used during plan application for version changes, not for runtime retry of failed intervals. This function is implemented in sqlmesh/core/state_sync/db/facade.py.
This prevents gaps during version changes but doesn't help with runtime failures.
Summary
The issue is a gap because:
- The materialization strategy is non-atomic for most engines (documented in
docs/concepts/models/model_kinds.md) - Lookback intervals that fail mid-execution leave data holes
- There's no special retry mechanism for failed lookback intervals (scheduler logic in
sqlmesh/core/scheduler.py) - The system assumes lookback intervals will succeed or be naturally retried, which may not happen for transient failures
- Gap detection only applies to plan application, not runtime failures (logic in
sqlmesh/core/state_sync/db/facade.py)
Notes
The end_bounded parameter in missing_intervals can be used to limit intervals to the target end date, but this doesn't address the retry issue for failed lookback intervals. This parameter is documented in the missing_intervals method in sqlmesh/core/snapshot/definition.py.
Relevant Files
docs/concepts/models/model_kinds.md- Materialization strategy documentationdocs/concepts/models/overview.md- Lookback parameter documentationsqlmesh/core/model/meta.py- lookback_start method implementationsqlmesh/core/snapshot/definition.py- compute_missing_intervals and missing_intervals implementationsqlmesh/core/scheduler.py- merged_missing_intervals implementationtests/core/test_snapshot.py- Test cases for lookback behaviorsqlmesh/core/state_sync/db/facade.py- Gap detection logic in _ensure_no_gaps
Wiki pages you might want to explore:
- Incremental Models (SQLMesh/sqlmesh)
Confirmed with a standalone reproduction on official SQLMesh 0.236.4, Python 3.11.15 and DuckDB 1.5.6. The failing operation is an ordinary Context.run with lookback. No restatement arguments or manual interval invalidation are used.
One correction to the original report: the failed lookback interval retains its previous successful coverage. It is not recorded as missing after the replacement fails.
The reproduction bootstraps five daily rows, then runs through November 6:
- The November 5 lookback batch deletes its old row and fails before INSERT. The November 6 batch succeeds. Upstream retains continuous November 1–7 coverage, despite the missing November 5 row. Downstream is skipped in the failed run.
- After removing the injected failure, a same-cutoff retry returns
SUCCESS. It skips upstream repair and copies the missing row into downstream. - The following day's run also returns
SUCCESS. With upstream lookback one, November 5 is outside the new window and stays missing in both models. Both advertise continuous November 1–8 coverage.
The failed batch had one attempt. A separate lookback-five control repaired the row the next day, but the same-cutoff retry still propagated the gap. Explicit bounded restatement repaired both models.
#5285 acknowledges inconsistent state after failed restatements. Is retaining old coverage after a failed ordinary lookback run also intentional? What supported recovery prevents a successful retry from propagating missing data?
This is a local DuckDB DELETE_INSERT reproduction, not evidence for other engines. The only fault injection raises after the actual DELETE and before INSERT; it does not alter scheduler or interval-state behavior. The script below passed with all assertions.
Standalone reproduction
Install into a private Python 3.11 environment:
pip install 'sqlmesh[duckdb]==0.236.4' 'duckdb==1.5.6' pytest time-machine
python reproduce.py
"""Run with sqlmesh[duckdb]==0.236.4, pytest and time-machine installed."""
import os
os.environ["MAX_FORK_WORKERS"] = "1"
from datetime import datetime, timezone
from pathlib import Path
from tempfile import TemporaryDirectory
import pytest
import time_machine
from sqlglot import exp
from sqlmesh.core.config import Config, DuckDBConnectionConfig, GatewayConfig
from sqlmesh.core.config.model import ModelDefaultsConfig
from sqlmesh.core.context import Context
from sqlmesh.core.state_sync.db.facade import EngineAdapterStateSync
def day(n):
return datetime(2026, 11, n, tzinfo=timezone.utc)
with TemporaryDirectory() as directory:
root = Path(directory)
(root / "models").mkdir()
values = ",".join(f"('2026-11-{n:02}',{n})" for n in range(1, 8))
(root / "models/upstream.sql").write_text(
"MODEL (name repro.upstream, kind INCREMENTAL_BY_TIME_RANGE "
"(time_column ds, batch_size 1, lookback 1), start '2026-11-01', cron '@daily'); "
"SELECT CAST(ds AS DATE) AS ds, CAST(id AS INT) AS id "
f"FROM (VALUES {values}) AS src(ds,id) "
"WHERE CAST(ds AS DATE) BETWEEN @start_ds AND @end_ds;"
)
(root / "models/downstream.sql").write_text(
"MODEL (name repro.downstream, kind INCREMENTAL_BY_TIME_RANGE "
"(time_column ds, batch_size 2, lookback 5), start '2026-11-01', cron '@daily'); "
"SELECT ds,id FROM repro.upstream WHERE ds BETWEEN @start_ds AND @end_ds;"
)
config = Config(
gateways={"local": GatewayConfig(
connection=DuckDBConnectionConfig(database=str(root / "warehouse.db"), concurrent_tasks=1),
state_connection=DuckDBConnectionConfig(database=str(root / "state.db"), concurrent_tasks=1),
)},
default_gateway="local",
model_defaults=ModelDefaultsConfig(dialect="duckdb"),
disable_anonymized_analytics=True,
)
ctx = Context(paths=[str(root)], config=config)
def checkpoint(label):
adapter = DuckDBConnectionConfig(database=str(root / "state.db"), concurrent_tasks=1).create_engine_adapter()
state = EngineAdapterStateSync(adapter, schema="sqlmesh")
try:
env = state.get_environment("prod")
snapshots = state.get_snapshots(env.snapshots)
state.refresh_snapshot_intervals(snapshots.values())
result = {}
for snapshot in snapshots.values():
ids = [row[0] for row in ctx.engine_adapter.fetchall(f"SELECT id FROM {snapshot.table_name()} ORDER BY id")]
name = snapshot.model.name.split(".")[-1].strip('"')
result[name] = ids
print(label, name, "ids=", ids, "coverage=", snapshot.intervals)
return result
finally:
adapter.close()
def run(cutoff):
with time_machine.travel(day(cutoff), tick=False):
return ctx.run("prod", start=day(1), end=day(cutoff), execution_time=day(cutoff), skip_janitor=True)
try:
with time_machine.travel(day(6), tick=False):
ctx.apply(ctx.plan_builder("prod", execution_time=day(6), skip_tests=True).build())
upstream = ctx.get_snapshot("repro.upstream", raise_if_missing=True)
physical_name = exp.to_table(upstream.table_name()).name
adapter_type = type(ctx.snapshot_evaluator.adapter)
original_insert = adapter_type._insert_append_query
attempts = []
def fail_after_delete(self, table_name, query, *args, **kwargs):
if exp.to_table(table_name).name == physical_name:
replacement = self.fetchall(query)
if any(row[1] == 5 for row in replacement):
assert 5 not in [row[0] for row in self.fetchall(f"SELECT id FROM {upstream.table_name()}")]
attempts.append("November 5")
raise RuntimeError("Synthetic INSERT failure after actual DELETE")
return original_insert(self, table_name, query, *args, **kwargs)
with pytest.MonkeyPatch.context() as patch:
patch.setattr(adapter_type, "_insert_append_query", fail_after_delete)
assert str(run(7)).endswith("FAILURE")
assert len(attempts) == 1
failed = checkpoint("failed run")
assert failed == {"upstream": [1, 2, 3, 4, 6], "downstream": [1, 2, 3, 4, 5]}
assert str(run(7)).endswith("SUCCESS")
assert all(ids == [1, 2, 3, 4, 6] for ids in checkpoint("same-cutoff retry").values())
assert str(run(8)).endswith("SUCCESS")
assert all(ids == [1, 2, 3, 4, 6, 7] for ids in checkpoint("next day").values())
finally:
ctx.close()