Skip to content

Commit bb9f590

Browse files
authored
fix: adding in run_id injection (#5893)
Signed-off-by: Cortland Goffena <30168413+cmgoffena13@users.noreply.github.com>
1 parent 28cbd20 commit bb9f590

4 files changed

Lines changed: 109 additions & 3 deletions

File tree

‎sqlmesh/core/context.py‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,7 @@
118118
filter_tests_by_patterns,
119119
)
120120
from sqlmesh.core.user import User
121-
from sqlmesh.utils import UniqueKeyDict, Verbosity
121+
from sqlmesh.utils import CorrelationId, UniqueKeyDict, Verbosity
122122
from sqlmesh.utils.concurrency import concurrent_apply_to_values
123123
from sqlmesh.utils.dag import DAG
124124
from sqlmesh.utils.date import (
@@ -811,6 +811,9 @@ def run(
811811
engine_type=self.snapshot_evaluator.adapter.dialect,
812812
state_sync_type=self.state_sync.state_type(),
813813
)
814+
snapshot_evaluator = self.snapshot_evaluator.set_correlation_id(
815+
CorrelationId.from_run_id(analytics_run_id)
816+
)
814817
self._load_materializations()
815818

816819
env_check_attempts_num = max(
@@ -863,6 +866,7 @@ def _has_environment_changed() -> bool:
863866
select_models=select_models,
864867
circuit_breaker=_has_environment_changed,
865868
no_auto_upstream=no_auto_upstream,
869+
snapshot_evaluator=snapshot_evaluator,
866870
)
867871
done = True
868872
except CircuitBreakerError:
@@ -2605,8 +2609,9 @@ def _run(
26052609
select_models: t.Optional[t.Collection[str]],
26062610
circuit_breaker: t.Optional[t.Callable[[], bool]],
26072611
no_auto_upstream: bool,
2612+
snapshot_evaluator: t.Optional[SnapshotEvaluator] = None,
26082613
) -> CompletionStatus:
2609-
scheduler = self.scheduler(environment=environment)
2614+
scheduler = self.scheduler(environment=environment, snapshot_evaluator=snapshot_evaluator)
26102615
snapshots = scheduler.snapshots
26112616

26122617
if select_models is not None:

‎sqlmesh/utils/__init__.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -409,6 +409,10 @@ def __str__(self) -> str:
409409
def from_plan_id(cls, plan_id: str) -> CorrelationId:
410410
return CorrelationId(JobType.PLAN, plan_id)
411411

412+
@classmethod
413+
def from_run_id(cls, run_id: str) -> CorrelationId:
414+
return CorrelationId(JobType.RUN, run_id)
415+
412416

413417
def get_source_columns_to_types(
414418
columns_to_types: t.Dict[str, exp.DataType],

‎tests/core/engine_adapter/integration/test_integration_bigquery.py‎

Lines changed: 56 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
import typing as t
2+
from unittest import mock
3+
24
import pytest
5+
import time_machine
36
from pathlib import Path
47
from sqlglot import exp
58
from sqlglot.optimizer.qualify_columns import quote_identifiers
@@ -441,7 +444,7 @@ def test_table_diff_table_name_matches_column_name(ctx: TestContext):
441444
assert row_diff.full_match_count == 1
442445

443446

444-
def test_correlation_id_in_job_labels(ctx: TestContext):
447+
def test_plan_correlation_id_in_job_labels(ctx: TestContext):
445448
model_name = ctx.table("test")
446449

447450
sqlmesh = ctx.create_context()
@@ -469,3 +472,55 @@ def test_correlation_id_in_job_labels(ctx: TestContext):
469472
labels = adapter._job_params.get("labels")
470473
correlation_id = CorrelationId.from_plan_id(plan.plan_id)
471474
assert labels == {correlation_id.job_type.value.lower(): correlation_id.job_id}
475+
476+
477+
@time_machine.travel("2023-01-08 15:00:00 UTC")
478+
def test_run_correlation_id_in_job_labels(ctx: TestContext):
479+
run_id = "test_run_id"
480+
model_name = ctx.table("run_test")
481+
482+
sqlmesh = ctx.create_context()
483+
sqlmesh.upsert_model(
484+
load_sql_based_model(
485+
d.parse(
486+
f"""
487+
MODEL (
488+
name {model_name},
489+
kind INCREMENTAL_BY_TIME_RANGE (
490+
time_column event_ts
491+
),
492+
cron '@daily',
493+
start '2023-01-07'
494+
);
495+
SELECT 1 AS col, '2023-01-07' AS event_ts
496+
"""
497+
)
498+
)
499+
)
500+
sqlmesh.plan(auto_apply=True, no_prompts=True)
501+
502+
captured_evaluators: t.List = []
503+
original_scheduler = sqlmesh.scheduler
504+
505+
def scheduler_wrapper(
506+
environment: t.Optional[str] = None,
507+
snapshot_evaluator: t.Optional[t.Any] = None,
508+
):
509+
if snapshot_evaluator is not None:
510+
captured_evaluators.append(snapshot_evaluator)
511+
return original_scheduler(environment=environment, snapshot_evaluator=snapshot_evaluator)
512+
513+
with time_machine.travel("2023-01-09 00:00:00 UTC"):
514+
with mock.patch(
515+
"sqlmesh.core.context.analytics.collector.on_run_start", return_value=run_id
516+
):
517+
with mock.patch.object(sqlmesh, "scheduler", scheduler_wrapper):
518+
sqlmesh.run()
519+
520+
assert captured_evaluators
521+
adapter = t.cast(BigQueryEngineAdapter, captured_evaluators[-1].adapter)
522+
523+
assert adapter.correlation_id is not None
524+
labels = adapter._job_params.get("labels")
525+
correlation_id = CorrelationId.from_run_id(run_id)
526+
assert labels == {correlation_id.job_type.value.lower(): correlation_id.job_id}

‎tests/core/integration/test_model_kinds.py‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2332,6 +2332,48 @@ def _correlation_id_in_sqls(correlation_id: CorrelationId, mock_logger):
23322332
assert _correlation_id_in_sqls(correlation_id, mock_logger)
23332333

23342334

2335+
@time_machine.travel("2023-01-08 15:00:00 UTC")
2336+
def test_run_correlation_id(tmp_path: Path):
2337+
def _correlation_id_in_sqls(correlation_id: CorrelationId, mock_logger):
2338+
sqls = [call[0][0] for call in mock_logger.call_args_list]
2339+
return any(f"/* {correlation_id} */" in sql for sql in sqls)
2340+
2341+
run_id = "test_run_id"
2342+
ctx = Context(paths=[tmp_path], config=Config())
2343+
2344+
create_temp_file(
2345+
tmp_path,
2346+
Path("models", "test.sql"),
2347+
"""
2348+
MODEL (
2349+
name test.a,
2350+
kind INCREMENTAL_BY_TIME_RANGE (
2351+
time_column event_ts
2352+
),
2353+
cron '@daily',
2354+
start '2023-01-07'
2355+
);
2356+
SELECT 1 AS col, '2023-01-07' AS event_ts
2357+
""",
2358+
)
2359+
2360+
ctx.load()
2361+
ctx.plan(auto_apply=True, no_prompts=True)
2362+
2363+
with time_machine.travel("2023-01-09 00:00:00 UTC"):
2364+
with mock.patch(
2365+
"sqlmesh.core.context.analytics.collector.on_run_start", return_value=run_id
2366+
):
2367+
with mock.patch(
2368+
"sqlmesh.core.engine_adapter.base.EngineAdapter._log_sql"
2369+
) as mock_logger:
2370+
ctx.run()
2371+
2372+
correlation_id = CorrelationId.from_run_id(run_id)
2373+
assert str(correlation_id) == f"SQLMESH_RUN: {run_id}"
2374+
assert _correlation_id_in_sqls(correlation_id, mock_logger)
2375+
2376+
23352377
@time_machine.travel("2023-01-08 15:00:00 UTC")
23362378
def test_scd_type_2_regular_run_with_offset(init_and_plan_context: t.Callable):
23372379
context, plan = init_and_plan_context("examples/sushi")

0 commit comments

Comments
 (0)