Skip to content

Commit 6fcfcc5

Browse files
committed
fix(location): keep a build's heartbeat running while it waits on a resume claim
A build waited on open claims before it started its heartbeat. With a grace shorter than the wait, its own hold looked expired, so another resumer could resume the model and close the hold; the build then suspended the model again and, holding nothing, never resumed it. The heartbeat now starts before the wait. The docs list the remaining gap: a resume that outlasts its 2-minute claim.
1 parent 157b75f commit 6fcfcc5

6 files changed

Lines changed: 158 additions & 26 deletions

File tree

‎src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/models/dynamic.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,5 +85,6 @@ whether it succeeds or fails.
8585

8686
## Limitations
8787

88+
- A resume that takes longer than its 2-minute claim can still start a model a build has just paused: the last `ALTER` of a sync killed at the limit, or a build's resume of another model on a queued warehouse.
8889
- Unit tests and scenarios treat a dynamic model as a table.
8990
- On a target with `schema = "preserve"`, builds see each other's pauses only when their dynamic models share a schema.

‎src/sqlbuild/executor/dynamic_pauses/classes/dynamic_hold.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,8 @@ def acquire(self, *, connection: Any, on_progress: Callable[[str], None] | None)
142142
self._yield_to_rivals(
143143
connection=connection, location=location, names=tuple(self._paused), window=window
144144
)
145+
self._heartbeat = self._new_heartbeat(self._write_heartbeat)
146+
self._heartbeat.start()
145147
claimed: frozenset[_RelationKey] = self._await_claims(
146148
connection=connection, location=location, names=tuple(self._paused)
147149
)
@@ -153,8 +155,6 @@ def acquire(self, *, connection: Any, on_progress: Callable[[str], None] | None)
153155
}
154156
)
155157
self._suspend_active(connection=connection, names=tuple(self._paused), states=states)
156-
self._heartbeat = self._new_heartbeat(self._write_heartbeat)
157-
self._heartbeat.start()
158158

159159
def after_create(self, *, connection: Any, name: str) -> None:
160160
"""Suspend a model CREATE OR REPLACE made active; check its new hold as acquire does."""

‎tests/integration/src/sqlbuild/executor/dynamic_pauses/_test_types.py‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,16 @@ class AbandonedClaimTestCase:
160160
expected_states: dict[str, str]
161161

162162

163+
@dataclass(frozen=True)
164+
class LongClaimWaitTestCase:
165+
description: str
166+
grace_seconds: int
167+
waited_seconds: int
168+
expected_open_holds: tuple[str, ...]
169+
expected_states: dict[str, str]
170+
expected_released_states: dict[str, str]
171+
172+
163173
@dataclass(frozen=True)
164174
class TwoBuildsTestCase:
165175
description: str

‎tests/integration/src/sqlbuild/executor/dynamic_pauses/helpers.py‎

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from __future__ import annotations
44

5+
import time
56
from collections.abc import Callable
67
from dataclasses import replace
78
from pathlib import Path
@@ -26,6 +27,7 @@
2627
from sqlbuild.executor.dynamic_pauses.classes.dynamic_hold import DynamicHold
2728
from sqlbuild.executor.dynamic_pauses.constants import CLAIM_RUN_MARKER
2829
from sqlbuild.executor.dynamic_pauses.main.hold_dynamic_models import hold_dynamic_models
30+
from sqlbuild.executor.dynamic_pauses.main.resume_expired_holds import resume_expired_holds
2931
from sqlbuild.executor.dynamic_pauses.models import DynamicPauseEvent
3032
from sqlbuild.executor.dynamic_pauses.types import DynamicPauseEventType, StateLocation
3133
from tests.integration.src.sqlbuild.compiler.planner.main._test_types import (
@@ -367,6 +369,84 @@ def held_by_dead_run(
367369
return plan
368370

369371

372+
def expired_hold_plan(
373+
*, adapter: PausingDuckDbAdapter, connection: Any, database_path: Path
374+
) -> PlanOutput:
375+
"""Build once, seed `dead_run`'s hold on `daily_totals` an hour silent; the rebuild's plan."""
376+
377+
_ = build_lease_project(
378+
adapter=adapter,
379+
connection=connection,
380+
case=lease_project_case(
381+
orders_query="SELECT 1 AS order_id", report_locations={}, refresh_on_build=False
382+
),
383+
runtime=BuildRuntimeParams(run_id="first_run"),
384+
database_path=database_path,
385+
)
386+
plan: PlanOutput = plan_lease_project(
387+
adapter=adapter,
388+
connection=connection,
389+
case=lease_project_case(
390+
orders_query="SELECT 1 AS order_id UNION ALL SELECT 2",
391+
report_locations={},
392+
refresh_on_build=False,
393+
),
394+
)
395+
seed_hold(
396+
adapter=adapter,
397+
connection=connection,
398+
run_id="dead_run",
399+
name="daily_totals",
400+
idle_seconds=3600,
401+
)
402+
return plan
403+
404+
405+
def age_beat_and_sync(
406+
*,
407+
adapter: PausingDuckDbAdapter,
408+
connection: Any,
409+
waiting: tuple[str, int],
410+
sync: tuple[str, float, str],
411+
) -> None:
412+
"""Age the waiting run as a long wait would, let it beat, run a sync, then close the claim."""
413+
414+
run_id, age_seconds = waiting
415+
recorded_by, grace_seconds, claim_run = sync
416+
connection.execute(
417+
"UPDATE staging._sqlbuild_dynamic_pauses "
418+
f"SET recorded_at = recorded_at - INTERVAL {age_seconds} SECOND WHERE run_id = '{run_id}'"
419+
)
420+
aged: int = heartbeat_count(connection=connection, run_id=run_id)
421+
deadline: float = time.monotonic() + 2
422+
while heartbeat_count(connection=connection, run_id=run_id) <= aged and (
423+
time.monotonic() < deadline
424+
):
425+
time.sleep(0.02)
426+
_ = resume_expired_holds(
427+
adapter=adapter,
428+
connection=connection,
429+
location=(None, "staging"),
430+
grace_seconds=grace_seconds,
431+
recorded_by=recorded_by,
432+
quiet_token=None,
433+
)
434+
connection.execute(
435+
insert_sql(
436+
adapter=adapter,
437+
location=(None, "staging"),
438+
events=(
439+
DynamicPauseEvent(
440+
event_type=DynamicPauseEventType.RESUMED,
441+
run_id=claim_run,
442+
recorded_by=recorded_by,
443+
relation=_daily_totals(),
444+
),
445+
),
446+
)
447+
)
448+
449+
370450
def other_model_hold(*, adapter: PausingDuckDbAdapter, database_path: Path) -> DynamicHold:
371451
"""`other_run`'s unacquired hold on `weekly_totals`, beside `daily_totals`' pause table."""
372452

‎tests/integration/src/sqlbuild/executor/dynamic_pauses/test_dynamic_sync_resume.py‎

Lines changed: 64 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
ClaimRaceTestCase,
2929
ClaimWaitTestCase,
3030
DoubleCloseTestCase,
31+
LongClaimWaitTestCase,
3132
QuietTokenTestCase,
3233
RefusedResumeTestCase,
3334
StaleSyncResumeTestCase,
@@ -43,8 +44,10 @@
4344
RefusingResumeAdapter,
4445
SyncDuringTakeoverAdapter,
4546
TokenPausingDuckDbAdapter,
47+
age_beat_and_sync,
4648
build_lease_project,
4749
claim_events,
50+
expired_hold_plan,
4851
finish_claimed_resume,
4952
heartbeat_count,
5053
held_by_dead_run,
@@ -736,30 +739,8 @@ def test_given_two_builds_taking_over_one_expired_hold_when_one_holds_the_model_
736739
adapter: ClaimHookAdapter = ClaimHookAdapter()
737740
connection: Any = adapter.connect({"database": str(database_path)})
738741
connection.execute("CREATE SCHEMA staging")
739-
_ = build_lease_project(
740-
adapter=adapter,
741-
connection=connection,
742-
case=lease_project_case(
743-
orders_query="SELECT 1 AS order_id", report_locations={}, refresh_on_build=False
744-
),
745-
runtime=BuildRuntimeParams(run_id="first_run"),
746-
database_path=database_path,
747-
)
748-
plan: PlanOutput = plan_lease_project(
749-
adapter=adapter,
750-
connection=connection,
751-
case=lease_project_case(
752-
orders_query="SELECT 1 AS order_id UNION ALL SELECT 2",
753-
report_locations={},
754-
refresh_on_build=False,
755-
),
756-
)
757-
seed_hold(
758-
adapter=adapter,
759-
connection=connection,
760-
run_id="dead_run",
761-
name="daily_totals",
762-
idle_seconds=3600,
742+
plan: PlanOutput = expired_hold_plan(
743+
adapter=adapter, connection=connection, database_path=database_path
763744
)
764745
holder: DynamicHold | None = hold_dynamic_models(
765746
plan=plan,
@@ -787,3 +768,62 @@ def test_given_two_builds_taking_over_one_expired_hold_when_one_holds_the_model_
787768
assert states == test_case.expected_states
788769
assert tuple(sorted(hold.run_id for hold in holds)) == test_case.expected_open_holds
789770
assert claims == list(test_case.expected_claims)
771+
772+
773+
@pytest.mark.parametrize(
774+
"test_case",
775+
[
776+
LongClaimWaitTestCase(
777+
description="a build waiting past its grace on a claim still beats, so it keeps its hold",
778+
grace_seconds=61,
779+
waited_seconds=62,
780+
expected_open_holds=("second_run",),
781+
expected_states={"daily_totals": "SUSPENDED"},
782+
expected_released_states={"daily_totals": "ACTIVE"},
783+
),
784+
],
785+
ids=lambda case: case.description,
786+
)
787+
def test_given_a_build_waiting_on_a_claim_past_its_grace_when_another_sync_passes_then_its_hold_stays_live(
788+
test_case: LongClaimWaitTestCase, database_path: Path
789+
) -> None:
790+
adapter: ClaimHookAdapter = ClaimHookAdapter()
791+
connection: Any = adapter.connect({"database": str(database_path)})
792+
connection.execute("CREATE SCHEMA staging")
793+
plan: PlanOutput = expired_hold_plan(
794+
adapter=adapter, connection=connection, database_path=database_path
795+
)
796+
claim_run: str = f"{_SYNC}/claim/slow"
797+
seed_claim(adapter=adapter, connection=connection, claim_run=claim_run, age_seconds=0)
798+
adapter.after_claim_read.append(
799+
lambda read: age_beat_and_sync(
800+
adapter=adapter,
801+
connection=read,
802+
waiting=("second_run", test_case.waited_seconds),
803+
sync=("location-sync:other", float(test_case.grace_seconds), claim_run),
804+
)
805+
)
806+
building: DynamicHold | None = hold_dynamic_models(
807+
plan=plan,
808+
adapter=adapter,
809+
runtime=BuildRuntimeParams(
810+
run_id="second_run", dynamic_heartbeat_grace_seconds=test_case.grace_seconds
811+
),
812+
connection_config={"database": str(database_path)},
813+
heartbeat_seconds=0.05,
814+
claim_wait=(60.0, 0.02),
815+
)
816+
assert building is not None
817+
818+
building.acquire(connection=connection, on_progress=None)
819+
820+
holds: tuple[OpenHold, ...] = read_open_holds(
821+
adapter=adapter, connection=connection, location=(None, "staging")
822+
)
823+
states: dict[str, str] = dict(adapter.states)
824+
building.release(connection=connection)
825+
released: dict[str, str] = dict(adapter.states)
826+
adapter.close(connection)
827+
assert tuple(sorted(hold.run_id for hold in holds)) == test_case.expected_open_holds
828+
assert states == test_case.expected_states
829+
assert released == test_case.expected_released_states

‎website/src/content/docs/docs/concepts/models/dynamic.mdx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,5 +82,6 @@ whether it succeeds or fails.
8282

8383
## Limitations
8484

85+
- A resume that takes longer than its 2-minute claim can still start a model a build has just paused: the last `ALTER` of a sync killed at the limit, or a build's resume of another model on a queued warehouse.
8586
- Unit tests and scenarios treat a dynamic model as a table.
8687
- On a target with `schema = "preserve"`, builds see each other's pauses only when their dynamic models share a schema.

0 commit comments

Comments
 (0)