Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(cdp): add a command to unstick runs left on running (#86537)

Harley Alexanderd2556e17c75f
diff --git a/posthog/kafka_client/routing.py b/posthog/kafka_client/routing.py
index 3334f7c9102d..6fbcad0968b0 100644
--- a/posthog/kafka_client/routing.py
+++ b/posthog/kafka_client/routing.py
@@ -42,6 +42,7 @@ from posthog.kafka_client.topics import (
KAFKA_EVENTS_JSON,
KAFKA_FLAGS_CACHE_INVALIDATION,
KAFKA_GROUPS,
+ KAFKA_HOG_INVOCATION_RESULTS,
KAFKA_LOG_ENTRIES,
KAFKA_METRICS_TIME_TO_SEE_DATA,
KAFKA_NOTIFICATION_EVENTS,
@@ -95,6 +96,10 @@ _DEFAULT_TOPIC_ROUTING: dict[str, KafkaClusterProfile] = {
# --- CYCLOTRON (Warpstream cyclotron) ---
KAFKA_CDP_INTERNAL_EVENTS: KafkaClusterProfile.CYCLOTRON,
KAFKA_DWH_CDP_RAW_TABLE: KafkaClusterProfile.CYCLOTRON,
+ # The ClickHouse Kafka engine table for this topic reads from the
+ # warpstream-cyclotron named collection, so a Django producer has to target
+ # the same cluster the CDP workers produce to or the rows never arrive.
+ KAFKA_HOG_INVOCATION_RESULTS: KafkaClusterProfile.CYCLOTRON,
# --- CALCULATED_EVENTS (Warpstream calculated-events) ---
KAFKA_COHORT_MEMBERSHIP_CHANGED: KafkaClusterProfile.CALCULATED_EVENTS,
# --- REPLAY (Session replay) ---
diff --git a/products/cdp/backend/management/commands/unstick_hog_invocations.py b/products/cdp/backend/management/commands/unstick_hog_invocations.py
new file mode 100644
index 000000000000..89165ea294ee
--- /dev/null
+++ b/products/cdp/backend/management/commands/unstick_hog_invocations.py
@@ -0,0 +1,94 @@
+"""Mark CDP runs that are stuck on `running` as failed so they can be re-run.
+
+A run gets stuck when its invocation was dropped without a terminal lifecycle
+row ever being produced. The known cause was re-running an invocation of a
+disabled destination, fixed at the source, but the rows written before that fix
+stay stuck for the 30 days the ClickHouse table retains them, and any future
+drop path with the same gap would land here too.
+
+Runs against one team at a time. Start with a dry run, which prints what it
+would touch and writes nothing.
+"""
+
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+from django.core.management.base import BaseCommand, CommandError
+
+from products.cdp.backend.services.stuck_invocations import MAX_WINDOW_DAYS, StuckInvocationScope, unstick_invocations
+
+FUNCTION_KINDS = ["hog_function", "hog_flow"]
+
+# A hog flow legitimately sits on `running` for as long as its longest delay
+# step, and nothing in the stored row says how long that is. An operator has to
+# pick an age past it, so flows are opt-in rather than reachable by default.
+DEFAULT_MIN_AGE_HOURS = 24
+MIN_AGE_FLOOR_HOURS = 1
+
+
+class Command(BaseCommand):
+ help = (
+ "Mark hog invocations stuck on 'running' as failed so the Runs tab stops "
+ "showing them in flight and they become re-runnable. Dry run by default."
+ )
+
+ def add_arguments(self, parser: Any) -> None:
+ parser.add_argument("--team-id", type=int, required=True, help="Team to scan.")
+ parser.add_argument(
+ "--function-kind",
+ choices=FUNCTION_KINDS,
+ default="hog_function",
+ help="Default: hog_function. Read the --min-age-hours help before using hog_flow.",
+ )
+ parser.add_argument("--function-id", default=None, help="Restrict to one destination or workflow.")
+ parser.add_argument(
+ "--invocation-id",
+ action="append",
+ default=None,
+ dest="invocation_ids",
+ help="Repeatable. Restrict to specific invocations.",
+ )
+ parser.add_argument(
+ "--min-age-hours",
+ type=int,
+ default=DEFAULT_MIN_AGE_HOURS,
+ help=(
+ f"Only touch runs last scheduled at least this long ago (default {DEFAULT_MIN_AGE_HOURS}, "
+ f"minimum {MIN_AGE_FLOOR_HOURS}). A hog flow waiting on a delay step is genuinely running, "
+ "so set this past the longest delay in the flow."
+ ),
+ )
+ parser.add_argument("--limit", type=int, default=1000, help="Cap on invocations touched per run.")
+ parser.add_argument("--commit", action="store_true", help="Write the terminal rows. Omit for a dry run.")
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ min_age_hours = options["min_age_hours"]
+ if min_age_hours < MIN_AGE_FLOOR_HOURS:
+ raise CommandError(f"--min-age-hours must be at least {MIN_AGE_FLOOR_HOURS}")
+ if min_age_hours >= MAX_WINDOW_DAYS * 24:
+ raise CommandError(
+ f"--min-age-hours must be under {MAX_WINDOW_DAYS * 24}, the ClickHouse retention on these rows"
+ )
+
+ scope = StuckInvocationScope(
+ team_id=options["team_id"],
+ function_kind=options["function_kind"],
+ function_id=options["function_id"],
+ invocation_ids=tuple(options["invocation_ids"] or ()),
+ min_age=timedelta(hours=min_age_hours),
+ limit=options["limit"],
+ )
+ dry_run = not options["commit"]
+
+ stuck = unstick_invocations(scope, now=datetime.now(tz=UTC), dry_run=dry_run)
+
+ for invocation in stuck:
+ self.stdout.write(
+ f"{invocation.invocation_id} function={invocation.function_id} "
+ f"scheduled_at={invocation.scheduled_at.isoformat()}"
+ )
+
+ verb = "would mark" if dry_run else "marked"
+ self.stdout.write(f"{verb} {len(stuck)} invocation(s) failed for team {scope.team_id}")
+ if dry_run and stuck:
+ self.stdout.write("Re-run with --commit to write the terminal rows.")
diff --git a/products/cdp/backend/services/stuck_invocations.py b/products/cdp/backend/services/stuck_invocations.py
new file mode 100644
index 000000000000..176fe68ae89a
--- /dev/null
+++ b/products/cdp/backend/services/stuck_invocations.py
@@ -0,0 +1,229 @@
+"""Recover CDP invocations whose lifecycle rows never reached a terminal status.
+
+`hog_invocation_results` resolves a run's status with `argMax(status, version)`
+over its lifecycle rows. An invocation whose terminal row was never produced
+therefore reads `running` forever: the Runs tab shows it in flight, and the
+rerun paginator's in-flight guard refuses to replay it. Nothing reconciles that
+after the fact, because the cyclotron job the row described is already gone.
+
+The only way to move such a run is to produce a terminal row carrying a higher
+`version`, so this writes one to the same Kafka topic the CDP workers produce
+to. Every other column is copied from the stored row, `invocation_globals`
+included, because the rerun paginator rehydrates the replayed invocation from
+that column.
+"""
+
+from dataclasses import field
+from datetime import UTC, datetime, timedelta
+from typing import Any, Optional
+
+from posthog.clickhouse.client.execute import sync_execute
+from posthog.dataclasses import frozen
+from posthog.kafka_client.routing import producer_scope
+from posthog.kafka_client.topics import KAFKA_HOG_INVOCATION_RESULTS
+
+# Stable, low-cardinality `error_kind` stamped on every row this writes, so the
+# runs UI and the rerun filters can target exactly these recoveries and tell
+# them apart from failures the destination itself produced.
+STUCK_INVOCATION_ERROR_KIND = "stuck_invocation"
+
+STUCK_INVOCATION_ERROR_MESSAGE = "This run never reported a result, so it was marked failed. Re-run it to try again."
+
+# Matches the ClickHouse TTL on hog_invocation_results. Rows older than this are
+# gone, so scanning further back only reads partitions that cannot match.
+MAX_WINDOW_DAYS = 30
+
+DELIVERY_TIMEOUT_SECONDS = 30.0
+
+# Aliases are deliberately not named after their source columns: ClickHouse's
+# analyzer resolves a name in WHERE to a same-named SELECT alias, which would
+# turn `WHERE scheduled_at >= …` into an aggregate-in-WHERE error. Same reason
+# the runs listing query aliases its aggregates `latest_*`.
+#
+# The age check sits in HAVING rather than WHERE because `scheduled_at` moves
+# per lifecycle row (cyclotron rewrites it on every retry). Filtering rows by it
+# could hide an invocation's terminal row while keeping its `running` one, which
+# would report a finished run as stuck.
+_STUCK_INVOCATIONS_QUERY = """
+SELECT
+ invocation_id,
+ argMax(function_id, version) AS latest_function_id,
+ argMax(parent_run_id, version) AS latest_parent_run_id,
+ argMax(attempts, version) AS latest_attempts,
+ argMax(is_retry, version) AS latest_is_retry,
+ max(scheduled_at) AS latest_scheduled_at,
+ argMax(first_scheduled_at, version) AS latest_first_scheduled_at,
+ argMax(started_at, version) AS latest_started_at,
+ argMax(event_uuid, version) AS latest_event_uuid,
+ argMax(distinct_id, version) AS latest_distinct_id,
+ argMax(person_id, version) AS latest_person_id,
+ argMax(invocation_globals, version) AS latest_invocation_globals,
+ max(version) AS latest_version
+FROM hog_invocation_results
+WHERE team_id = %(team_id)s
+ AND function_kind = %(function_kind)s
+ AND scheduled_at >= %(window_start)s
+ {function_id_clause}
+ {invocation_ids_clause}
+GROUP BY invocation_id
+HAVING argMax(status, version) = 'running'
+ AND argMax(is_deleted, version) = 0
+ AND max(scheduled_at) < %(cutoff)s
+ORDER BY latest_scheduled_at ASC
+LIMIT %(limit)s
+"""
+
+
+@frozen
+class StuckInvocationScope:
+ team_id: int
+ function_kind: str
+ # Both optional filters narrow the scan; omitting them covers every function
+ # of this kind in the team.
+ function_id: Optional[str]
+ invocation_ids: tuple[str, ...]
+ min_age: timedelta
+ limit: int
+
+
+@frozen
+class StuckInvocation:
+ invocation_id: str
+ function_id: str
+ parent_run_id: str
+ attempts: int
+ is_retry: int
+ scheduled_at: datetime
+ first_scheduled_at: datetime
+ started_at: Optional[datetime]
+ event_uuid: str
+ distinct_id: str
+ person_id: str
+ # The triggering payload, still gzip+base64 encoded as the producer wrote
+ # it. Kept out of `repr` so a customer payload cannot reach a traceback or a
+ # log line just because this object was printed.
+ invocation_globals: str = field(repr=False)
+ version: int
+
+
+def _iso_microseconds(value: datetime) -> str:
+ # ClickHouse DateTime64(6) accepts 'YYYY-MM-DD HH:MM:SS.ffffff'. The Node
+ # producer writes the same format onto this topic.
+ return value.astimezone(UTC).strftime("%Y-%m-%d %H:%M:%S.%f")
+
+
+def _as_utc(value: datetime) -> datetime:
+ # The ClickHouse driver returns naive datetimes for DateTime64 columns.
+ return value if value.tzinfo else value.replace(tzinfo=UTC)
+
+
+def find_stuck_invocations(scope: StuckInvocationScope, *, now: datetime) -> list[StuckInvocation]:
+ params: dict[str, Any] = {
+ "team_id": scope.team_id,
+ "function_kind": scope.function_kind,
+ "window_start": now - timedelta(days=MAX_WINDOW_DAYS),
+ "cutoff": now - scope.min_age,
+ "limit": scope.limit,
+ }
+
+ function_id_clause = ""
+ if scope.function_id:
+ function_id_clause = "AND function_id = %(function_id)s"
+ params["function_id"] = scope.function_id
+
+ invocation_ids_clause = ""
+ if scope.invocation_ids:
+ invocation_ids_clause = "AND invocation_id IN %(invocation_ids)s"
+ params["invocation_ids"] = list(scope.invocation_ids)
+
+ rows = sync_execute(
+ _STUCK_INVOCATIONS_QUERY.format(
+ function_id_clause=function_id_clause,
+ invocation_ids_clause=invocation_ids_clause,
+ ),
+ params,
+ )
+
+ return [
+ StuckInvocation(
+ invocation_id=row[0],
+ function_id=row[1],
+ parent_run_id=row[2],
+ attempts=row[3],
+ is_retry=row[4],
+ scheduled_at=_as_utc(row[5]),
+ first_scheduled_at=_as_utc(row[6]),
+ started_at=_as_utc(row[7]) if row[7] else None,
+ event_uuid=row[8],
+ distinct_id=row[9],
+ person_id=row[10],
+ invocation_globals=row[11],
+ version=row[12],
+ )
+ for row in rows
+ ]
+
+
+def build_terminal_row(invocation: StuckInvocation, *, scope: StuckInvocationScope, now: datetime) -> dict[str, Any]:
+ started_at = invocation.started_at
+ duration_ms = max(0, int((now - started_at).total_seconds() * 1000)) if started_at else None
+
+ # ReplacingMergeTree keeps the highest `version` per invocation, so a row
+ # that does not beat the stored one is written and then silently ignored.
+ # The producers stamp `version` from a wall clock in microseconds, which a
+ # clock skew or a replayed row can push ahead of this process's clock.
+ version = max(int(now.timestamp() * 1_000_000), invocation.version + 1)
+
+ return {
+ "team_id": scope.team_id,
+ "function_kind": scope.function_kind,
+ "function_id": invocation.function_id,
+ "invocation_id": invocation.invocation_id,
+ "parent_run_id": invocation.parent_run_id,
+ "status": "failed",
+ "attempts": invocation.attempts,
+ "is_retry": invocation.is_retry,
+ # Carried verbatim so the new row lands in the same daily partition as
+ # the rows it collapses with, and keeps the run's original timing.
+ "scheduled_at": _iso_microseconds(invocation.scheduled_at),
+ "first_scheduled_at": _iso_microseconds(invocation.first_scheduled_at),
+ "started_at": _iso_microseconds(started_at) if started_at else None,
+ "finished_at": _iso_microseconds(now),
+ "duration_ms": duration_ms,
+ "error_kind": STUCK_INVOCATION_ERROR_KIND,
+ "error_message": STUCK_INVOCATION_ERROR_MESSAGE,
+ "event_uuid": invocation.event_uuid,
+ "distinct_id": invocation.distinct_id,
+ "person_id": invocation.person_id,
+ "invocation_globals": invocation.invocation_globals,
+ "version": str(version),
+ "is_deleted": 0,
+ }
+
+
+def unstick_invocations(scope: StuckInvocationScope, *, now: datetime, dry_run: bool) -> list[StuckInvocation]:
+ """Mark every stuck invocation in `scope` as failed, returning the ones matched.
+
+ A dry run resolves the matches and writes nothing.
+ """
+ stuck = find_stuck_invocations(scope, now=now)
+ if dry_run or not stuck:
+ return stuck
+
+ with producer_scope(topic=KAFKA_HOG_INVOCATION_RESULTS) as producer:
+ deliveries = [
+ producer.produce(
+ topic=KAFKA_HOG_INVOCATION_RESULTS,
+ data=build_terminal_row(invocation, scope=scope, now=now),
+ # Same partitioning key the CDP producers use, so every row for
+ # one invocation stays on one partition.
+ key=invocation.invocation_id,
+ log_key_on_delivery_failure=True,
+ )
+ for invocation in stuck
+ ]
+
+ for delivery in deliveries:
+ delivery.get(timeout=DELIVERY_TIMEOUT_SECONDS)
+
+ return stuck
diff --git a/products/cdp/backend/test/test_stuck_invocations.py b/products/cdp/backend/test/test_stuck_invocations.py
new file mode 100644
index 000000000000..a17bea65fbdf
--- /dev/null
+++ b/products/cdp/backend/test/test_stuck_invocations.py
@@ -0,0 +1,242 @@
+from datetime import UTC, datetime, timedelta
+from typing import Any, Optional
+
+from posthog.test.base import BaseTest, ClickhouseTestMixin
+from unittest.mock import MagicMock, patch
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from posthog.clickhouse.client.execute import sync_execute
+from posthog.models.hog_invocation_results.sql import INSERT_HOG_INVOCATION_RESULT_SQL
+
+from products.cdp.backend.services.stuck_invocations import (
+ STUCK_INVOCATION_ERROR_KIND,
+ StuckInvocation,
+ StuckInvocationScope,
+ build_terminal_row,
+ unstick_invocations,
+)
+
+NOW = datetime(2026, 8, 20, 12, 0, 0, tzinfo=UTC)
+TEAM_ID = 1
+FUNCTION_ID = "018f0000-0000-0000-0000-00000000f00d"
+INVOCATION_ID = "018f0000-0000-0000-0000-0000000000a1"
+
+
+def _insert_row(
+ *,
+ team_id: int,
+ invocation_id: str,
+ status: str,
+ version: int,
+ scheduled_at: datetime,
+ is_deleted: int = 0,
+ invocation_globals: str = "{}",
+ started_at: Optional[datetime] = None,
+) -> None:
+ params: dict[str, Any] = {
+ "team_id": team_id,
+ "function_kind": "hog_function",
+ "function_id": FUNCTION_ID,
+ "invocation_id": invocation_id,
+ "parent_run_id": "",
+ "status": status,
+ "attempts": 0,
+ "is_retry": 0,
+ "scheduled_at": scheduled_at,
+ "first_scheduled_at": scheduled_at,
+ "started_at": started_at,
+ "finished_at": None,
+ "duration_ms": None,
+ "error_kind": "",
+ "error_message": "",
+ "event_uuid": "",
+ "distinct_id": "user-1",
+ "person_id": "person-1",
+ "invocation_globals": invocation_globals,
+ "version": version,
+ "is_deleted": is_deleted,
+ }
+ sync_execute(INSERT_HOG_INVOCATION_RESULT_SQL, params)
+
+
+def _scope(
+ team_id: int,
+ *,
+ min_age_hours: int = 24,
+ function_id: Optional[str] = None,
+ invocation_ids: tuple[str, ...] = (),
+) -> StuckInvocationScope:
+ return StuckInvocationScope(
+ team_id=team_id,
+ function_kind="hog_function",
+ function_id=function_id,
+ invocation_ids=invocation_ids,
+ min_age=timedelta(hours=min_age_hours),
+ limit=100,
+ )
+
+
+class TestStuckInvocations(ClickhouseTestMixin, BaseTest):
+ @parameterized.expand(
+ [
+ # A run whose terminal row was never produced, old enough to be
+ # certain no worker is still holding it.
+ ("only_running", "01", [("running", 1, -48)], True),
+ ("running_then_succeeded", "02", [("running", 1, -48), ("succeeded", 2, -48)], False),
+ # The terminal row carries the retry's scheduled_at, which is inside
+ # the age cutoff while the running row sits outside it. Filtering
+ # rows by scheduled_at instead of the aggregate would hide the
+ # terminal row here and report a finished run as stuck.
+ ("terminal_row_scheduled_after_cutoff", "03", [("running", 1, -48), ("succeeded", 2, -1)], False),
+ ("running_but_too_recent", "04", [("running", 1, -2)], False),
+ # A lower version does not win the argMax, so the run still reads
+ # as running and is still stuck. This is the re-run case that
+ # produced the stuck rows in the first place.
+ ("terminal_row_superseded_by_running", "05", [("succeeded", 1, -48), ("running", 2, -48)], True),
+ ]
+ )
+ def test_selects_only_invocations_left_on_running(
+ self, _name: str, suffix: str, rows: list[tuple[str, int, int]], expected_stuck: bool
+ ) -> None:
+ invocation_id = f"{INVOCATION_ID[:-2]}{suffix}"
+ for status, version, hours_ago in rows:
+ _insert_row(
+ team_id=self.team.pk,
+ invocation_id=invocation_id,
+ status=status,
+ version=version,
+ scheduled_at=NOW + timedelta(hours=hours_ago),
+ )
+
+ with patch("products.cdp.backend.services.stuck_invocations.producer_scope"):
+ stuck = unstick_invocations(_scope(self.team.pk), now=NOW, dry_run=False)
+
+ assert [invocation.invocation_id for invocation in stuck] == ([invocation_id] if expected_stuck else [])
+
+ def test_deleted_invocations_are_left_alone(self) -> None:
+ _insert_row(
+ team_id=self.team.pk,
+ invocation_id=INVOCATION_ID,
+ status="running",
+ version=1,
+ scheduled_at=NOW - timedelta(hours=48),
+ )
+ _insert_row(
+ team_id=self.team.pk,
+ invocation_id=INVOCATION_ID,
+ status="running",
+ version=2,
+ scheduled_at=NOW - timedelta(hours=48),
+ is_deleted=1,
+ )
+
+ with patch("products.cdp.backend.services.stuck_invocations.producer_scope"):
+ stuck = unstick_invocations(_scope(self.team.pk), now=NOW, dry_run=False)
+
+ assert stuck == []
+
+ def test_invocation_id_filter_leaves_the_other_stuck_runs_alone(self) -> None:
+ # Unsticking one reported run is the common case, and the filter is the
+ # only thing standing between that and marking every stuck run in the
+ # team failed.
+ other_invocation_id = f"{INVOCATION_ID[:-2]}99"
+ for invocation_id in (INVOCATION_ID, other_invocation_id):
+ _insert_row(
+ team_id=self.team.pk,
+ invocation_id=invocation_id,
+ status="running",
+ version=1,
+ scheduled_at=NOW - timedelta(hours=48),
+ )
+
+ with patch("products.cdp.backend.services.stuck_invocations.producer_scope"):
+ stuck = unstick_invocations(
+ _scope(self.team.pk, function_id=FUNCTION_ID, invocation_ids=(INVOCATION_ID,)),
+ now=NOW,
+ dry_run=False,
+ )
+
+ assert [invocation.invocation_id for invocation in stuck] == [INVOCATION_ID]
+
+ def test_dry_run_reports_matches_without_producing(self) -> None:
+ _insert_row(
+ team_id=self.team.pk,
+ invocation_id=INVOCATION_ID,
+ status="running",
+ version=1,
+ scheduled_at=NOW - timedelta(hours=48),
+ )
+
+ with patch("products.cdp.backend.services.stuck_invocations.producer_scope") as mock_scope:
+ stuck = unstick_invocations(_scope(self.team.pk), now=NOW, dry_run=True)
+
+ assert [invocation.invocation_id for invocation in stuck] == [INVOCATION_ID]
+ mock_scope.assert_not_called()
+
+ def test_commit_produces_one_terminal_row_per_invocation(self) -> None:
+ _insert_row(
+ team_id=self.team.pk,
+ invocation_id=INVOCATION_ID,
+ status="running",
+ version=1,
+ scheduled_at=NOW - timedelta(hours=48),
+ )
+ producer = MagicMock()
+
+ with patch("products.cdp.backend.services.stuck_invocations.producer_scope") as mock_scope:
+ mock_scope.return_value.__enter__.return_value = producer
+ unstick_invocations(_scope(self.team.pk), now=NOW, dry_run=False)
+
+ producer.produce.assert_called_once()
+ kwargs = producer.produce.call_args.kwargs
+ assert kwargs["key"] == INVOCATION_ID
+ assert kwargs["data"]["status"] == "failed"
+ assert kwargs["data"]["error_kind"] == STUCK_INVOCATION_ERROR_KIND
+
+
+class TestBuildTerminalRow(SimpleTestCase):
+ def _invocation(self, *, version: int, invocation_globals: str = "H4sIAAAA") -> StuckInvocation:
+ return StuckInvocation(
+ invocation_id=INVOCATION_ID,
+ function_id=FUNCTION_ID,
+ parent_run_id="",
+ attempts=0,
+ is_retry=0,
+ scheduled_at=NOW - timedelta(hours=48),
+ first_scheduled_at=NOW - timedelta(hours=48),
+ started_at=NOW - timedelta(hours=48),
+ event_uuid="",
+ distinct_id="user-1",
+ person_id="person-1",
+ invocation_globals=invocation_globals,
+ version=version,
+ )
+
+ def test_carries_the_stored_invocation_globals_through_untouched(self) -> None:
+ # The rerun paginator rehydrates a replayed invocation from this column,
+ # so dropping or re-encoding it here would leave the run un-rerunnable,
+ # which is the state this command exists to fix.
+ row = build_terminal_row(self._invocation(version=1), scope=_scope(TEAM_ID), now=NOW)
+
+ assert row["invocation_globals"] == "H4sIAAAA"
+
+ def test_version_beats_a_stored_version_ahead_of_the_clock(self) -> None:
+ # ReplacingMergeTree keeps the highest version, so a row that does not
+ # beat the stored one is accepted by Kafka and then silently ignored.
+ ahead = int((NOW + timedelta(days=1)).timestamp() * 1_000_000)
+
+ row = build_terminal_row(self._invocation(version=ahead), scope=_scope(TEAM_ID), now=NOW)
+
+ assert int(row["version"]) == ahead + 1
+
+ def test_keeps_the_original_scheduled_at_so_the_row_lands_in_the_same_partition(self) -> None:
+ # PARTITION BY toYYYYMMDD(scheduled_at): stamping "now" instead would
+ # scatter an invocation's rows across partitions, so they would never
+ # collapse and the row would outlive the retention of the rows it fixes.
+ row = build_terminal_row(self._invocation(version=1), scope=_scope(TEAM_ID), now=NOW)
+
+ assert row["scheduled_at"] == "2026-08-18 12:00:00.000000"
+ assert row["finished_at"] == "2026-08-20 12:00:00.000000"