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.

chore(workflows): delete the finished conversion window migration command (#109385)

Daniel Marchukec7ddbaf61fe
diff --git a/products/workflows/backend/management/commands/migrate_conversion_window_to_duration.py b/products/workflows/backend/management/commands/migrate_conversion_window_to_duration.py
deleted file mode 100644
index e3d4ed9a5793..000000000000
--- a/products/workflows/backend/management/commands/migrate_conversion_window_to_duration.py
+++ /dev/null
@@ -1,444 +0,0 @@
-import uuid
-from typing import Any
-
-from django.core.management.base import BaseCommand
-from django.db import transaction
-
-from posthog.dataclasses import frozen
-
-from products.workflows.backend.models.hog_flow.hog_flow import HogFlow
-from products.workflows.backend.models.hog_flow.hog_flow_template import HogFlowTemplate
-from products.workflows.backend.models.hog_flow_revision import HogFlowRevision
-from products.workflows.backend.services.timing_reschedule import parse_delay_duration_seconds
-from products.workflows.backend.utils.durations import duration_minutes
-
-MINUTES_PER_DAY = 1440
-# The ceiling the matcher clamped a legacy value to, kept here because nothing else needs it now.
-MAX_LEGACY_WINDOW_MINUTES = 90 * 24 * 60
-
-
-@frozen
-class RewrittenWindow:
- """A conversion whose window_minutes has been respelled as a duration string."""
-
- conversion: dict[str, Any]
- window: str
- minutes: int
-
-
-@frozen
-class ConvertedFlow:
- """What one locked row's conversion turned into, and whether its draft moved with it."""
-
- window: str
- minutes: int
- draft_converted: bool
-
-
-class Command(BaseCommand):
- help = (
- "Move conversion.window_minutes onto conversion.window, the duration-string form. "
- "Only converts values the matcher already honors in full (at or under the legacy ceiling of "
- f"{MAX_LEGACY_WINDOW_MINUTES} minutes), which is a representation change with no effect on any "
- "conversion rate. A larger value is reported and left alone: it can be a real minute count or a "
- "seconds count in a minutes field, and either reading changes what the workflow measures, so "
- "which one is right needs a person. Default dry-run; pass --live-run to apply."
- )
-
- def add_arguments(self, parser: Any) -> None:
- parser.add_argument("--team-id", default=None, type=int, help="Limit to a specific team ID")
- parser.add_argument("--live-run", action="store_true", help="Apply changes (default is dry-run)")
- parser.add_argument(
- "--strip-inert",
- action="store_true",
- help=(
- "Delete window_minutes wherever it cannot change what a workflow measures: null, zero, a "
- "row that already carries window, or a value above the legacy ceiling the matcher clamped "
- "anyway. Refuses to touch a row the convert pass would still convert, so run without this "
- "flag first."
- ),
- )
-
- def handle(self, *args: Any, **options: Any) -> None:
- live_run = options.get("live_run", False)
- team_id = options.get("team_id")
- strip_inert = options.get("strip_inert", False)
- mode = "LIVE RUN" if live_run else "DRY RUN"
- self.stdout.write(f"Starting migrate_conversion_window_to_duration ({mode})")
-
- if strip_inert:
- self.strip_inert(live_run, team_id, mode)
- return
-
- flows = HogFlow.objects.filter(conversion__isnull=False)
- if team_id:
- flows = flows.filter(team_id=team_id)
- self.stdout.write(f"Filtering to team_id={team_id}")
-
- converted = 0
- drafts_with_rows = 0
- needs_review = []
- for flow in flows.iterator():
- conversion = flow.conversion or {}
- minutes = conversion.get("window_minutes")
- # A row that already carries a usable window was written by a client that knows the new
- # field. Anything the worker cannot read leaves the legacy value as what it measures.
- if has_usable_window(conversion):
- continue
- if not isinstance(minutes, int) or isinstance(minutes, bool) or minutes <= 0:
- continue
-
- if minutes > MAX_LEGACY_WINDOW_MINUTES:
- needs_review.append((flow, minutes))
- continue
-
- if not live_run:
- self.stdout.write(
- f" Would convert flow id={flow.id} team_id={flow.team_id} status={flow.status}: "
- f"window_minutes={minutes} -> window={duration_string(minutes)}"
- )
- converted += 1
- continue
-
- result = self.convert_locked(flow.pk)
- if result is None:
- self.stdout.write(
- f" Skipped flow id={flow.id} team_id={flow.team_id}: conversion changed since the "
- "scan, leaving it for a rerun"
- )
- continue
-
- drafts_with_rows += 1 if result.draft_converted else 0
- self.stdout.write(
- f" Converting flow id={flow.id} team_id={flow.team_id} status={flow.status}: "
- f"window_minutes={result.minutes} -> window={result.window}"
- )
- converted += 1
-
- drafts = drafts_with_rows + self.convert_drafts(live_run, team_id)
- revisions = self.convert_revisions(live_run, team_id)
- templates = self.convert_templates(live_run, team_id)
-
- self.report_needs_review(needs_review)
-
- verb = "converted" if live_run else "to convert"
- self.stdout.write(self.style.SUCCESS(f"Completed ({mode}): {converted} flow(s) {verb}"))
- self.stdout.write(
- self.style.SUCCESS(
- f" plus {drafts} draft(s), {revisions} revision snapshot(s) and {templates} template(s)"
- )
- )
-
- def strip_inert(self, live_run: bool, team_id: int | None, mode: str) -> None:
- """Delete the key everywhere it is dead weight, so nothing is left to read or restore."""
- flows = HogFlow.objects.filter(conversion__isnull=False)
- drafted = HogFlow.objects.filter(draft__isnull=False)
- if team_id:
- flows = flows.filter(team_id=team_id)
- drafted = drafted.filter(team_id=team_id)
- self.stdout.write(f"Filtering to team_id={team_id}")
-
- verb = "Stripping" if live_run else "Would strip"
- still_convertible = 0
- flows_stripped = 0
- for flow in flows.iterator():
- if converted_conversion(flow.conversion) is not None:
- still_convertible += 1
- continue
- if stripped_conversion(flow.conversion) is None:
- continue
- value = (flow.conversion or {}).get("window_minutes")
- self.stdout.write(f" {verb} flow id={flow.id} team_id={flow.team_id}: window_minutes={value!r}")
- if live_run:
- with transaction.atomic():
- locked = HogFlow.objects.select_for_update().get(pk=flow.pk)
- fresh = stripped_conversion(locked.conversion)
- if fresh is None:
- continue
- HogFlow.objects.filter(pk=flow.pk).update(conversion=fresh)
- flows_stripped += 1
-
- drafts_stripped = 0
- for flow in drafted.iterator():
- draft = flow.draft
- if not isinstance(draft, dict):
- continue
- if converted_conversion(draft.get("conversion")) is not None:
- # Publishing this draft later would drop a window the convert pass could still save.
- still_convertible += 1
- continue
- if stripped_conversion(draft.get("conversion")) is None:
- continue
- self.stdout.write(f" {verb} draft on flow id={flow.id} team_id={flow.team_id}")
- if live_run:
- with transaction.atomic():
- locked = HogFlow.objects.select_for_update().get(pk=flow.pk)
- locked_draft = locked.draft
- if not isinstance(locked_draft, dict):
- continue
- fresh = stripped_conversion(locked_draft.get("conversion"))
- if fresh is None:
- continue
- HogFlow.objects.filter(pk=flow.pk).update(draft={**locked_draft, "conversion": fresh})
- drafts_stripped += 1
-
- revisions = HogFlowRevision.objects.for_team(team_id) if team_id else HogFlowRevision.objects.unscoped().all()
- revisions_stripped = 0
- for revision in revisions.iterator():
- content = revision.content
- if not isinstance(content, dict):
- continue
- if converted_conversion(content.get("conversion")) is not None:
- # Restoring this snapshot later would drop a window the convert pass could still save.
- still_convertible += 1
- continue
- fresh = stripped_conversion(content.get("conversion"))
- if fresh is None:
- continue
- self.stdout.write(f" {verb} revision id={revision.id} flow={revision.hog_flow_id} v{revision.version}")
- if live_run:
- HogFlowRevision.objects.for_team(revision.team_id).filter(pk=revision.pk).update(
- content={**content, "conversion": fresh}
- )
- revisions_stripped += 1
-
- templates = HogFlowTemplate.objects.filter(conversion__isnull=False)
- if team_id:
- templates = templates.filter(team_id=team_id)
- templates_stripped = 0
- for template in templates.iterator():
- if converted_conversion(template.conversion) is not None:
- # A workflow created from this template would get the default window instead of its own.
- still_convertible += 1
- continue
- if stripped_conversion(template.conversion) is None:
- continue
- self.stdout.write(f" {verb} template id={template.id} team_id={template.team_id}")
- if live_run:
- with transaction.atomic():
- locked_template = HogFlowTemplate.objects.select_for_update().get(pk=template.pk)
- fresh = stripped_conversion(locked_template.conversion)
- if fresh is None:
- continue
- HogFlowTemplate.objects.filter(pk=template.pk).update(conversion=fresh)
- templates_stripped += 1
-
- if still_convertible:
- self.stdout.write(
- self.style.WARNING(
- f" {still_convertible} flow(s), draft(s), snapshot(s) or template(s) still carry a "
- "convertible value and were left alone. Run the command without --strip-inert first, "
- "then repeat this pass."
- )
- )
- done = "stripped" if live_run else "to strip"
- self.stdout.write(self.style.SUCCESS(f"Completed ({mode}): {flows_stripped} flow(s) {done}"))
- self.stdout.write(
- self.style.SUCCESS(
- f" plus {drafts_stripped} draft(s), {revisions_stripped} revision snapshot(s) and "
- f"{templates_stripped} template(s)"
- )
- )
-
- def convert_drafts(self, live_run: bool, team_id: int | None) -> int:
- """Drafts whose live conversion needed no change of its own. The pass above already rewrote a
- draft alongside its row; this catches the rest, where only the draft carries the old field."""
- flows = HogFlow.objects.filter(draft__isnull=False)
- if team_id:
- flows = flows.filter(team_id=team_id)
-
- count = 0
- for flow in flows.iterator():
- draft = flow.draft
- if not isinstance(draft, dict):
- continue
- rewritten = converted_conversion(draft.get("conversion"))
- if rewritten is None:
- continue
- self.stdout.write(
- f" {'Converting' if live_run else 'Would convert'} draft on flow id={flow.id} "
- f"team_id={flow.team_id}: window={rewritten.window}"
- )
- if live_run:
- with transaction.atomic():
- locked = HogFlow.objects.select_for_update().get(pk=flow.pk)
- locked_draft = locked.draft
- if not isinstance(locked_draft, dict):
- continue
- fresh = converted_conversion(locked_draft.get("conversion"))
- if fresh is None:
- continue
- HogFlow.objects.filter(pk=flow.pk).update(draft={**locked_draft, "conversion": fresh.conversion})
- count += 1
- return count
-
- def convert_revisions(self, live_run: bool, team_id: int | None) -> int:
- """Snapshots a rollback copies back into the draft. Rewriting one keeps a restore from putting
- the deprecated field back. The value is unchanged, only how it is spelled, so the snapshot still
- records the same window it always did."""
- # Fail-closed manager: one team goes through for_team, and a whole-instance backfill is the
- # cross-team access unscoped() exists for.
- revisions = HogFlowRevision.objects.for_team(team_id) if team_id else HogFlowRevision.objects.unscoped().all()
-
- count = 0
- for revision in revisions.iterator():
- content = revision.content
- if not isinstance(content, dict):
- continue
- rewritten = converted_conversion(content.get("conversion"))
- if rewritten is None:
- continue
- self.stdout.write(
- f" {'Converting' if live_run else 'Would convert'} revision id={revision.id} "
- f"flow={revision.hog_flow_id} v{revision.version}: window={rewritten.window}"
- )
- if live_run:
- # Append-only in practice — nothing edits a published snapshot — so no lock is needed.
- HogFlowRevision.objects.for_team(revision.team_id).filter(pk=revision.pk).update(
- content={**content, "conversion": rewritten.conversion}
- )
- count += 1
- return count
-
- def convert_templates(self, live_run: bool, team_id: int | None) -> int:
- """Templates a new workflow copies its conversion from. The flow API drops window_minutes, so a
- template left on the old field gives every workflow created from it the default window instead."""
- templates = HogFlowTemplate.objects.filter(conversion__isnull=False)
- if team_id:
- templates = templates.filter(team_id=team_id)
-
- count = 0
- for template in templates.iterator():
- rewritten = converted_conversion(template.conversion)
- if rewritten is None:
- continue
- self.stdout.write(
- f" {'Converting' if live_run else 'Would convert'} template id={template.id} "
- f"team_id={template.team_id}: window={rewritten.window}"
- )
- if live_run:
- with transaction.atomic():
- locked = HogFlowTemplate.objects.select_for_update().get(pk=template.pk)
- fresh = converted_conversion(locked.conversion)
- if fresh is None:
- continue
- HogFlowTemplate.objects.filter(pk=template.pk).update(conversion=fresh.conversion)
- count += 1
- return count
-
- def convert_locked(self, pk: uuid.UUID) -> ConvertedFlow | None:
- # Re-read the row under a lock and convert the value it holds now, not the one the scan read.
- # A customer saving the workflow between the scan and this write would otherwise lose that edit
- # to the stale conversion this command is holding, the lost write the API save path and the
- # sibling backfills guard against. A locked row that no longer qualifies (a save added a window
- # or pushed the value above the ceiling) is left for a rerun. .update() keeps updated_at
- # untouched: this is a representation change, not a user edit, so it must not fail an open
- # editor's next save or re-sort untouched flows to the top. The cost is that an editor which loaded
- # the workflow before the run and saves after it writes its stale conversion back, returning that
- # one row to window_minutes. The value it restores is under the ceiling and still honored, and a
- # rerun converts it again, so this is the cheaper side of the trade.
- with transaction.atomic():
- locked = HogFlow.objects.select_for_update().get(pk=pk)
- rewritten = converted_conversion(locked.conversion or {})
- if rewritten is None:
- return None
- fields: dict[str, object] = {"conversion": rewritten.conversion}
- draft_converted = False
- # The draft holds its own copy of conversion, so leaving it behind would put the
- # deprecated field back on the live row the moment the draft is published.
- draft = locked.draft
- if isinstance(draft, dict):
- draft_conversion = converted_conversion(draft.get("conversion"))
- if draft_conversion is not None:
- fields["draft"] = {**draft, "conversion": draft_conversion.conversion}
- draft_converted = True
- HogFlow.objects.filter(pk=pk).update(**fields)
- return ConvertedFlow(window=rewritten.window, minutes=rewritten.minutes, draft_converted=draft_converted)
-
- def report_needs_review(self, needs_review: list[tuple[HogFlow, int]]) -> None:
- if not needs_review:
- return
- self.stdout.write("")
- self.stdout.write(self.style.WARNING(f"{len(needs_review)} flow(s) left alone, each needs a person:"))
- self.stdout.write(f" {'id':<36} team_id window_minutes as minutes as seconds own delay steps name")
- for flow, minutes in sorted(needs_review, key=lambda pair: pair[0].team_id):
- span = flow_span_days(flow)
- span_label = f"{span:.1f}d" if span else "none"
- self.stdout.write(
- f" {str(flow.id):<36} {flow.team_id:<7} {minutes:<14} {minutes / MINUTES_PER_DAY:>7.1f}d "
- f"{minutes / (MINUTES_PER_DAY * 60):>8.1f}d {span_label:>15} {flow.name}"
- )
- self.stdout.write(
- " Read it as whichever column sits closest to the workflow's own delay steps. A value that "
- "only makes sense as seconds was written by someone who meant that many days."
- )
-
-
-def stripped_conversion(conversion: object) -> dict[str, Any] | None:
- """The same conversion without window_minutes, or None when the key must stay or is already gone.
-
- A row the convert pass would still rewrite is left alone: dropping its value there would move the
- window it measures, which is the one thing this whole change must not do."""
- if not isinstance(conversion, dict) or "window_minutes" not in conversion:
- return None
- if converted_conversion(conversion) is not None:
- return None
- return {k: v for k, v in conversion.items() if k != "window_minutes"}
-
-
-def has_usable_window(conversion: dict[str, Any]) -> bool:
- """True when conversion.window holds a window the matcher can actually read.
-
- One rule for both passes, and the matcher's own: it honors `window` only when the shared duration
- grammar parses it to a positive value (nodejs/src/cdp/services/hogflows/conversion-watcher.ts), so
- a missing, non-string, unparseable or non-positive one leaves the legacy value as what the row
- measures. Treating any of those as migrated would let the strip pass delete the only readable
- window, which is the one outcome this change must not produce."""
- window = conversion.get("window")
- if not isinstance(window, str):
- return False
- minutes = duration_minutes(window)
- return minutes is not None and minutes > 0
-
-
-def converted_conversion(conversion: object) -> RewrittenWindow | None:
- """The same conversion with window_minutes spelled as a duration string, or None when it must not
- be touched: already migrated, no usable value, or above the ceiling where the reading is in doubt."""
- if not isinstance(conversion, dict):
- return None
- minutes = conversion.get("window_minutes")
- if has_usable_window(conversion):
- return None
- if not isinstance(minutes, int) or isinstance(minutes, bool) or minutes <= 0:
- return None
- if minutes > MAX_LEGACY_WINDOW_MINUTES:
- return None
- window = duration_string(minutes)
- rewritten = {k: v for k, v in conversion.items() if k != "window_minutes"}
- rewritten["window"] = window
- return RewrittenWindow(conversion=rewritten, window=window, minutes=minutes)
-
-
-def duration_string(minutes: int) -> str:
- """The shortest exact duration string for a whole number of minutes."""
- if minutes % MINUTES_PER_DAY == 0:
- return f"{minutes // MINUTES_PER_DAY}d"
- if minutes % 60 == 0:
- return f"{minutes // 60}h"
- return f"{minutes}m"
-
-
-def flow_span_days(flow: HogFlow) -> float:
- """Rough timescale of the workflow's fixed delay steps, each clamped per unit the way the worker
- clamps a delay before it waits, so a step written 90d counts the 30 days it actually waits. This
- is only a sanity signal for the review table. It sums fixed delays without following branches, so
- mutually exclusive delays are added together, and it counts neither date-based delays nor
- condition-wait deadlines. Treat it as approximate, not the exact span any one run follows."""
- total_seconds = 0.0
- for action in flow.actions or []:
- if not isinstance(action, dict):
- continue
- seconds = parse_delay_duration_seconds((action.get("config") or {}).get("delay_duration"))
- if seconds is not None:
- total_seconds += seconds
- return total_seconds / (MINUTES_PER_DAY * 60)
diff --git a/products/workflows/backend/test/test_migrate_conversion_window_to_duration.py b/products/workflows/backend/test/test_migrate_conversion_window_to_duration.py
deleted file mode 100644
index 342da82304f4..000000000000
--- a/products/workflows/backend/test/test_migrate_conversion_window_to_duration.py
+++ /dev/null
@@ -1,267 +0,0 @@
-from io import StringIO
-from typing import Any
-
-from posthog.test.base import BaseTest
-
-from django.core.management import call_command
-
-from parameterized import parameterized
-
-from posthog.models import Team
-from posthog.models.scoping import team_scope
-
-from products.workflows.backend.models.hog_flow.hog_flow import HogFlow
-from products.workflows.backend.models.hog_flow.hog_flow_template import HogFlowTemplate
-from products.workflows.backend.models.hog_flow_revision import HogFlowRevision
-
-
-def _flow(team: Team, name: str, conversion: dict[str, Any]) -> HogFlow:
- return HogFlow.objects.create(
- team=team,
- name=name,
- status="active",
- trigger={"type": "event", "filters": {}},
- exit_condition="exit_only_at_end",
- conversion=conversion,
- actions=[],
- edges=[],
- )
-
-
-def _template(team: Team, conversion: dict[str, Any]) -> HogFlowTemplate:
- return HogFlowTemplate.objects.create(team=team, name="template", scope="team", conversion=conversion)
-
-
-class TestMigrateConversionWindowToDuration(BaseTest):
- @parameterized.expand(
- [
- ("a whole number of days", 129600, "90d"),
- ("a whole number of hours", 60, "1h"),
- ("neither", 90, "90m"),
- ]
- )
- def test_converts_a_window_the_matcher_already_honors(self, _name: str, minutes: int, expected: str) -> None:
- flow = _flow(self.team, "convertible", {"filters": [], "window_minutes": minutes})
-
- call_command("migrate_conversion_window_to_duration", team_id=self.team.pk, live_run=True)
-
- flow.refresh_from_db()
- assert flow.conversion == {"filters": [], "window": expected}
-
- @parameterized.expand([("seven days in seconds", 604800), ("thirty days in seconds", 2592000)])
- def test_leaves_a_window_above_the_legacy_ceiling_alone(self, _name: str, minutes: int) -> None:
- # Converting one of these either way changes what the workflow measures, and which reading is
- # right needs a person. Touching it silently is the failure this guards.
- flow = _flow(self.team, "ambiguous", {"filters": [], "window_minutes": minutes})
-
- call_command("migrate_conversion_window_to_duration", team_id=self.team.pk, live_run=True)
-
- flow.refresh_from_db()
- assert flow.conversion == {"filters": [], "window_minutes": minutes}
-
- @parameterized.expand(
- [
- ("a number", 7),
- ("null", None),
- ("an empty string", ""),
- ("a string the duration grammar rejects", "1 week"),
- ("an ISO-8601 duration", "P7D"),
- ("a duration of zero", "0d"),
- ]
- )
- def test_converts_over_a_window_that_is_not_a_usable_duration(self, _name: str, window: object) -> None:
- # The matcher honors `window` only when the shared grammar parses it to a positive value, so
- # each of these already falls through to the legacy value. Skipping the row here would let the
- # strip pass delete the only readable window.
- flow = _flow(self.team, "junk window", {"filters": [], "window": window, "window_minutes": 60})
-
- call_command("migrate_conversion_window_to_duration", team_id=self.team.pk, live_run=True)
-
- flow.refresh_from_db()
- assert flow.conversion == {"filters": [], "window": "1h"}
-
- def test_dry_run_writes_nothing(self) -> None:
- flow = _flow(self.team, "untouched", {"filters": [], "window_minutes": 60})
-
- call_command("migrate_conversion_window_to_duration", team_id=self.team.pk)
-
- flow.refresh_from_db()
- assert flow.conversion == {"filters": [], "window_minutes": 60}
-
- def test_leaves_a_flow_that_already_has_a_window_alone(self) -> None:
- flow = _flow(self.team, "already migrated", {"filters": [], "window": "7d"})
-
- call_command("migrate_conversion_window_to_duration", team_id=self.team.pk, live_run=True)
-
- flow.refresh_from_db()
- assert flow.conversion == {"filters": [], "window": "7d"}
-
- def test_converts_the_draft_copy_of_a_conversion(self) -> None:
- # A draft carries its own conversion, so leaving it behind puts the deprecated field back on
- # the live row the moment someone publishes.
- flow = _flow(self.team, "with draft", {"filters": [], "window_minutes": 60})
- flow.draft = {"conversion": {"filters": [], "window_minutes": 1440}}
- flow.save()
-
- call_command("migrate_conversion_window_to_duration", team_id=self.team.pk, live_run=True)
-
- flow.refresh_from_db()
- assert flow.conversion == {"filters": [], "window": "1h"}
- assert flow.draft == {"conversion": {"filters": [], "window": "1d"}}
-
- def test_converts_a_revision_snapshot(self) -> None:
- # Restoring a snapshot copies it back into the draft, so an unmigrated one reintroduces the field.
- flow = _flow(self.team, "with revision", {"filters": [], "window": "7d"})
- with team_scope(self.team.id):
- revision = HogFlowRevision.objects.create(
- team=self.team,
- hog_flow=flow,
- version=1,
- content={"conversion": {"filters": [], "window_minutes": 1440}},
- )
-
- call_command("migrate_conversion_window_to_duration", team_id=self.team.pk, live_run=True)
-
- with team_scope(self.team.id):
- revision.refresh_from_db()
- assert revision.content == {"conversion": {"filters": [], "window": "1d"}}
-
- def test_converts_a_template(self) -> None:
- # A new workflow copies the template's conversion, and the flow API drops window_minutes, so an
- # unmigrated template hands every workflow built from it the default window instead of its own.
- template = _template(self.team, {"filters": [], "window_minutes": 2880})
-
- call_command("migrate_conversion_window_to_duration", team_id=self.team.pk, live_run=True)
-
- template.refresh_from_db()
- assert template.conversion == {"filters": [], "window": "2d"}
-
- def test_leaves_an_ambiguous_revision_snapshot_alone(self) -> None:
- flow = _flow(self.team, "ambiguous revision", {"filters": [], "window": "7d"})
- with team_scope(self.team.id):
- revision = HogFlowRevision.objects.create(
- team=self.team,
- hog_flow=flow,
- version=1,
- content={"conversion": {"filters": [], "window_minutes": 604800}},
- )
-
- call_command("migrate_conversion_window_to_duration", team_id=self.team.pk, live_run=True)
-
- with team_scope(self.team.id):
- revision.refresh_from_db()
- assert revision.content == {"conversion": {"filters": [], "window_minutes": 604800}}
-
-
-class TestStripInert(BaseTest):
- @parameterized.expand(
- [
- ("null", None),
- ("zero", 0),
- ("above the legacy ceiling, which the matcher clamped anyway", 604800),
- ]
- )
- def test_strips_a_value_that_cannot_change_what_the_workflow_measures(
- self, _name: str, minutes: int | None
- ) -> None:
- flow = _flow(self.team, "inert", {"filters": [], "window_minutes": minutes})
-
- call_command("migrate_conversion_window_to_duration", team_id=self.team.pk, live_run=True, strip_inert=True)
-
- flow.refresh_from_db()
- assert flow.conversion == {"filters": []}
-
- def test_refuses_a_row_the_convert_pass_would_still_convert(self) -> None:
- # Stripping here would move the window from two days to the default, which is the one outcome
- # this whole change must not produce. The operator is told to run the convert pass first.
- flow = _flow(self.team, "convertible", {"filters": [], "window_minutes": 2880})
-
- call_command("migrate_conversion_window_to_duration", team_id=self.team.pk, live_run=True, strip_inert=True)
-
- flow.refresh_from_db()
- assert flow.conversion == {"filters": [], "window_minutes": 2880}
-
- def test_strips_alongside_an_existing_window_without_touching_it(self) -> None:
- flow = _flow(self.team, "both", {"filters": [], "window": "7d", "window_minutes": 60})
-
- call_command("migrate_conversion_window_to_duration", team_id=self.team.pk, live_run=True, strip_inert=True)
-
- flow.refresh_from_db()
- assert flow.conversion == {"filters": [], "window": "7d"}
-
- @parameterized.expand([("a string the grammar rejects", "1 week"), ("a duration of zero", "0d")])
- def test_refuses_a_row_whose_window_the_matcher_cannot_read(self, _name: str, window: str) -> None:
- # A window the shared grammar cannot parse to a positive value is not a window: the legacy
- # value is what the row measures today, so the convert pass still owns this row.
- flow = _flow(self.team, "unreadable window", {"filters": [], "window": window, "window_minutes": 2880})
-
- call_command("migrate_conversion_window_to_duration", team_id=self.team.pk, live_run=True, strip_inert=True)
-
- flow.refresh_from_db()
- assert flow.conversion == {"filters": [], "window": window, "window_minutes": 2880}
-
- def test_refuses_a_convertible_draft_snapshot_or_template_and_says_so(self) -> None:
- # A convertible value hiding in a draft, a snapshot or a template is not inert: publishing,
- # restoring or building from it after the field is gone drops the window. Skipping it silently
- # would report a clean sweep.
- flow = _flow(self.team, "clean live row", {"filters": []})
- flow.draft = {"conversion": {"filters": [], "window_minutes": 2880}}
- flow.save()
- with team_scope(self.team.pk):
- revision = HogFlowRevision.objects.create(
- team=self.team,
- hog_flow=flow,
- version=1,
- content={"conversion": {"filters": [], "window_minutes": 1440}},
- )
- template = _template(self.team, {"filters": [], "window_minutes": 60})
-
- out = StringIO()
- call_command(
- "migrate_conversion_window_to_duration",
- team_id=self.team.pk,
- live_run=True,
- strip_inert=True,
- stdout=out,
- )
-
- flow.refresh_from_db()
- revision.refresh_from_db()
- template.refresh_from_db()
- assert flow.draft == {"conversion": {"filters": [], "window_minutes": 2880}}
- assert revision.content == {"conversion": {"filters": [], "window_minutes": 1440}}
- assert template.conversion == {"filters": [], "window_minutes": 60}
- assert "3 flow(s), draft(s), snapshot(s) or template(s) still carry a convertible value" in out.getvalue()
-
- def test_strips_drafts_revision_snapshots_and_templates(self) -> None:
- # A snapshot or a template that keeps the key puts it back the moment someone restores that
- # version or builds a workflow from it.
- flow = _flow(self.team, "with draft", {"filters": [], "window_minutes": 0})
- flow.draft = {"conversion": {"filters": [], "window_minutes": None}}
- flow.save()
- with team_scope(self.team.pk):
- revision = HogFlowRevision.objects.create(
- team=self.team,
- hog_flow=flow,
- version=1,
- content={"conversion": {"filters": [], "window_minutes": 0}},
- )
- template = _template(self.team, {"filters": [], "window_minutes": None})
-
- call_command("migrate_conversion_window_to_duration", team_id=self.team.pk, live_run=True, strip_inert=True)
-
- flow.refresh_from_db()
- revision.refresh_from_db()
- template.refresh_from_db()
- assert flow.conversion == {"filters": []}
- assert flow.draft == {"conversion": {"filters": []}}
- assert revision.content == {"conversion": {"filters": []}}
- assert template.conversion == {"filters": []}
-
- def test_dry_run_writes_nothing(self) -> None:
- flow = _flow(self.team, "inert", {"filters": [], "window_minutes": 0})
-
- call_command("migrate_conversion_window_to_duration", team_id=self.team.pk, strip_inert=True)
-
- flow.refresh_from_db()
- assert flow.conversion == {"filters": [], "window_minutes": 0}