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(alerts): add typed synthetic demand discovery (#101535)

Jon McCallumd1a665af5b03
diff --git a/docs/internal/alerts-product-temporal.md b/docs/internal/alerts-product-temporal.md
index bd27df842bc9..0990fbf3f06a 100644
--- a/docs/internal/alerts-product-temporal.md
+++ b/docs/internal/alerts-product-temporal.md
@@ -9,8 +9,8 @@ The Alerts product registers three queues through `products/alerts/backend/facad
| `ALERTS_PRODUCT_DELIVERY_TASK_QUEUE` | `alerts-product-delivery-task-queue` | `alerts-product-deliver` |
These queue names are hardcoded and stay separate even with `DEBUG=True`.
-Shared orchestration registers only the orchestration workflow, with no activities.
-Each schedule tick starts orchestration, which awaits an evaluation child on the evaluation queue.
+Shared orchestration registers the orchestration workflow and a synthetic demand-discovery activity.
+Each schedule tick starts orchestration, which discovers demand before awaiting an evaluation child on the evaluation queue.
Evaluation runs the probe and starts its independent delivery child on the delivery queue.
Start one worker for each queue:
@@ -86,7 +86,7 @@ All three workflows accept an empty `AlertsProductInputs` dataclass.
Orchestration awaits one evaluation child, with a 40-second execution timeout and one workflow attempt.
The evaluation child ID includes the orchestration run ID, so each tick starts a distinct evaluation.
Evaluation runs a Postgres connectivity probe; delivery runs an empty activity with no I/O.
-Each activity has a 10-second start-to-close timeout and a 30-second schedule-to-close timeout.
+Evaluation and delivery activities each have a 10-second start-to-close timeout and a 30-second schedule-to-close timeout.
Evaluation has one attempt; delivery retains at most three attempts.
Evaluation starts one delivery child on the delivery queue and waits for confirmation that it started, without waiting for completion.
The child ID includes the evaluation run ID, so repeated runs of the same evaluation workflow ID start different children.
@@ -94,6 +94,22 @@ The child ID includes the evaluation run ID, so repeated runs of the same evalua
Delivery has a one-minute execution timeout for the noop.
Real notification delivery guarantees remain undecided.
+## Synthetic demand discovery
+
+The first orchestration activity, `alerts_product_discover_demand_activity`, accepts a timezone-aware ISO-8601 cutoff.
+Scheduled runs use `TemporalScheduledStartTime`; manual runs use the workflow start time.
+Activity retries retain the same cutoff rather than reading the activity's clock.
+The activity returns an `AlertDemand` containing configuration IDs grouped by the shared `SourceKind` enum (`logs` and `insight`).
+Only nonempty groups are returned. Discovery does not reserve or claim IDs.
+
+For now, `logic/demand.py` supplies deterministic synthetic configurations relative to that cutoff:
+two eligible logs configurations and one eligible insight configuration, plus future and disabled configurations that are excluded.
+There are no configuration-table reads, new database entities, or real evaluations of these IDs.
+The result is visible in the activity history; orchestration still runs the existing independent probe/delivery smoke path without passing it synthetic IDs.
+Source-specific child workflows, batching, TTL claims, and continuation are not implemented here.
+The discovery command is patch-gated so existing workflow histories still replay without it.
+Discovery has a five-second start-to-close timeout, a ten-second schedule-to-close timeout, and at most three attempts.
+
## Postgres connectivity probe
Each evaluation activity issues one explicit `SELECT 1` and checks for `(1,)` through Django's `default` main writer connection.
@@ -132,7 +148,8 @@ Worker registration does not deploy workers. The dev schedule sets the orchestra
## Activity logs
-Both Alerts queues use an activity-only interceptor that emits `alerts_product_activity_started` and `alerts_product_activity_finished` through the shared write-only logger.
+The evaluation and delivery queues use an activity-only interceptor that emits `alerts_product_activity_started` and `alerts_product_activity_finished` through the shared write-only logger.
+Discovery has SDK metrics and traces but does not use this logging interceptor.
The shared logger's async methods keep log processing and writes off the activity event loop.
Each retry emits its own start and finish events.
The shared logger supplies `activity_id`, `activity_type`, `attempt`, `task_queue`, `workflow_id`, `workflow_namespace`, `workflow_run_id`, and `workflow_type`.
diff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.py
index 5a4e91d12a28..1f640041c1d8 100644
--- a/posthog/management/commands/start_temporal_worker.py
+++ b/posthog/management/commands/start_temporal_worker.py
@@ -156,6 +156,7 @@ from products.alerts.backend.facade.temporal import (
DELIVERY_WORKFLOWS as ALERTS_PRODUCT_DELIVERY_WORKFLOWS,
EVALUATION_ACTIVITIES as ALERTS_PRODUCT_EVALUATION_ACTIVITIES,
EVALUATION_WORKFLOWS as ALERTS_PRODUCT_EVALUATION_WORKFLOWS,
+ SHARED_ORCHESTRATION_ACTIVITIES as ALERTS_PRODUCT_SHARED_ORCHESTRATION_ACTIVITIES,
SHARED_ORCHESTRATION_WORKFLOWS as ALERTS_PRODUCT_SHARED_ORCHESTRATION_WORKFLOWS,
)
from products.batch_exports.backend.temporal import (
@@ -553,7 +554,7 @@ _task_queue_specs = [
(
settings.ALERTS_PRODUCT_SHARED_ORCHESTRATION_TASK_QUEUE,
ALERTS_PRODUCT_SHARED_ORCHESTRATION_WORKFLOWS,
- [],
+ ALERTS_PRODUCT_SHARED_ORCHESTRATION_ACTIVITIES,
),
(
settings.ALERTS_PRODUCT_EVALUATION_TASK_QUEUE,
diff --git a/posthog/management/commands/test/test_start_temporal_worker.py b/posthog/management/commands/test/test_start_temporal_worker.py
index e4ecb88c2aa3..8c145cdb1ce6 100644
--- a/posthog/management/commands/test/test_start_temporal_worker.py
+++ b/posthog/management/commands/test/test_start_temporal_worker.py
@@ -20,6 +20,7 @@ from products.alerts.backend.facade.temporal import (
DELIVERY_WORKFLOWS,
EVALUATION_ACTIVITIES,
EVALUATION_WORKFLOWS,
+ SHARED_ORCHESTRATION_ACTIVITIES,
SHARED_ORCHESTRATION_WORKFLOWS,
)
from products.wizard.backend.facade.temporal import (
@@ -36,7 +37,11 @@ class _NotADataSyncWorkflow:
"task_queue,expected_workflows,expected_activities",
[
(settings.WIZARD_TASK_QUEUE, WIZARD_WORKFLOWS, WIZARD_ACTIVITIES),
- ("alerts-product-shared-orchestration-task-queue", SHARED_ORCHESTRATION_WORKFLOWS, []),
+ (
+ "alerts-product-shared-orchestration-task-queue",
+ SHARED_ORCHESTRATION_WORKFLOWS,
+ SHARED_ORCHESTRATION_ACTIVITIES,
+ ),
("alerts-product-evaluation-task-queue", EVALUATION_WORKFLOWS, EVALUATION_ACTIVITIES),
("alerts-product-delivery-task-queue", DELIVERY_WORKFLOWS, DELIVERY_ACTIVITIES),
],
@@ -46,13 +51,11 @@ def test_queue_registers_workflows_and_activities(
) -> None:
assert expected_workflows
assert set(expected_workflows) <= WORKFLOWS_DICT[task_queue]
+ assert expected_activities
+ assert set(expected_activities) <= ACTIVITIES_DICT[task_queue]
if task_queue == settings.ALERTS_PRODUCT_SHARED_ORCHESTRATION_TASK_QUEUE:
assert WORKFLOWS_DICT[task_queue] == set(expected_workflows)
- assert not expected_activities
- assert not ACTIVITIES_DICT[task_queue]
- else:
- assert expected_activities
- assert set(expected_activities) <= ACTIVITIES_DICT[task_queue]
+ assert ACTIVITIES_DICT[task_queue] == set(expected_activities)
# Data-import sources import vendor SDKs (google-ads, etc.) that register protobuf descriptors into a
diff --git a/products/alerts/backend/facade/contracts.py b/products/alerts/backend/facade/contracts.py
index 72c01e878adf..082f8f339aee 100644
--- a/products/alerts/backend/facade/contracts.py
+++ b/products/alerts/backend/facade/contracts.py
@@ -14,6 +14,21 @@ from uuid import UUID
from posthog.dataclasses import frozen
+class SourceKind(StrEnum):
+ LOGS = "logs"
+ INSIGHT = "insight"
+
+
+@frozen
+class DemandDiscoveryInputs:
+ cutoff: str
+
+
+@frozen
+class AlertDemand:
+ configuration_ids_by_source: dict[SourceKind, list[str]]
+
+
class DestinationType(StrEnum):
SLACK = "slack"
DISCORD = "discord"
diff --git a/products/alerts/backend/facade/temporal.py b/products/alerts/backend/facade/temporal.py
index 360d48ce2cbe..538783bbae04 100644
--- a/products/alerts/backend/facade/temporal.py
+++ b/products/alerts/backend/facade/temporal.py
@@ -5,6 +5,7 @@ from products.alerts.backend.temporal.workflows import (
DELIVERY_WORKFLOWS,
EVALUATION_ACTIVITIES,
EVALUATION_WORKFLOWS,
+ SHARED_ORCHESTRATION_ACTIVITIES,
SHARED_ORCHESTRATION_WORKFLOWS,
)
@@ -13,6 +14,7 @@ __all__ = [
"DELIVERY_WORKFLOWS",
"EVALUATION_ACTIVITIES",
"EVALUATION_WORKFLOWS",
+ "SHARED_ORCHESTRATION_ACTIVITIES",
"SHARED_ORCHESTRATION_WORKFLOWS",
"AlertsProductTelemetryInterceptor",
"create_alerts_product_check_due_schedule",
diff --git a/products/alerts/backend/logic/demand.py b/products/alerts/backend/logic/demand.py
new file mode 100644
index 000000000000..13c9d1d74989
--- /dev/null
+++ b/products/alerts/backend/logic/demand.py
@@ -0,0 +1,56 @@
+import datetime as dt
+
+from posthog.dataclasses import frozen
+
+from products.alerts.backend.facade.contracts import AlertDemand, SourceKind
+
+
+@frozen
+class _SyntheticConfiguration:
+ id: str
+ source_kind: SourceKind
+ next_check_at: dt.datetime
+ enabled: bool = True
+
+
+def _synthetic_configurations(cutoff: dt.datetime) -> tuple[_SyntheticConfiguration, ...]:
+ return (
+ _SyntheticConfiguration(
+ id="00000000-0000-4000-8000-000000000001",
+ source_kind=SourceKind.LOGS,
+ next_check_at=cutoff - dt.timedelta(minutes=1),
+ ),
+ _SyntheticConfiguration(
+ id="00000000-0000-4000-8000-000000000002",
+ source_kind=SourceKind.LOGS,
+ next_check_at=cutoff,
+ ),
+ _SyntheticConfiguration(
+ id="00000000-0000-4000-8000-000000000003",
+ source_kind=SourceKind.INSIGHT,
+ next_check_at=cutoff,
+ ),
+ _SyntheticConfiguration(
+ id="00000000-0000-4000-8000-000000000004",
+ source_kind=SourceKind.INSIGHT,
+ next_check_at=cutoff + dt.timedelta(minutes=1),
+ ),
+ _SyntheticConfiguration(
+ id="00000000-0000-4000-8000-000000000005",
+ source_kind=SourceKind.LOGS,
+ next_check_at=cutoff - dt.timedelta(minutes=1),
+ enabled=False,
+ ),
+ )
+
+
+def discover_synthetic_demand(cutoff: str) -> AlertDemand:
+ cutoff_time = dt.datetime.fromisoformat(cutoff)
+ if cutoff_time.utcoffset() is None:
+ raise ValueError("Demand discovery cutoff must include a timezone")
+
+ configuration_ids_by_source: dict[SourceKind, list[str]] = {}
+ for configuration in _synthetic_configurations(cutoff_time):
+ if configuration.enabled and configuration.next_check_at <= cutoff_time:
+ configuration_ids_by_source.setdefault(configuration.source_kind, []).append(configuration.id)
+ return AlertDemand(configuration_ids_by_source=configuration_ids_by_source)
diff --git a/products/alerts/backend/temporal/workflows.py b/products/alerts/backend/temporal/workflows.py
index d5ad87039c0d..b27381073304 100644
--- a/products/alerts/backend/temporal/workflows.py
+++ b/products/alerts/backend/temporal/workflows.py
@@ -1,7 +1,7 @@
import datetime as dt
from temporalio import activity, workflow
-from temporalio.common import RetryPolicy
+from temporalio.common import RetryPolicy, SearchAttributeKey
from temporalio.exceptions import ActivityError, ApplicationError, TimeoutError, TimeoutType
from posthog.dataclasses import frozen
@@ -13,6 +13,8 @@ with workflow.unsafe.imports_passed_through():
from asgiref.sync import sync_to_async
+ from products.alerts.backend.facade.contracts import AlertDemand, DemandDiscoveryInputs
+ from products.alerts.backend.logic.demand import discover_synthetic_demand
from products.alerts.backend.temporal.postgres import check_postgres_connection
@@ -24,6 +26,11 @@ class AlertsProductInputs:
pass
+async def alerts_product_discover_demand_activity(inputs: DemandDiscoveryInputs) -> AlertDemand:
+ return discover_synthetic_demand(inputs.cutoff)
+
+
@activity.defn
async def alerts_product_check_due_activity() -> None:
try:
@@ -92,6 +99,18 @@ class AlertsProductOrchestrateWorkflow(PostHogWorkflow):
@workflow.run
async def run(self, inputs: AlertsProductInputs) -> None:
+ if workflow.patched("alerts-product-discover-demand-v1"):
+ info = workflow.info()
+ cutoff = info.typed_search_attributes.get(
+ SearchAttributeKey.for_datetime("TemporalScheduledStartTime"), info.workflow_start_time
+ )
+ await workflow.execute_activity(
+ alerts_product_discover_demand_activity,
+ DemandDiscoveryInputs(cutoff=cutoff.isoformat()),
+ start_to_close_timeout=dt.timedelta(seconds=5),
+ schedule_to_close_timeout=dt.timedelta(seconds=10),
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ )
await workflow.execute_child_workflow(
AlertsProductCheckDueWorkflow.run,
inputs,
@@ -103,6 +122,7 @@ class AlertsProductOrchestrateWorkflow(PostHogWorkflow):
SHARED_ORCHESTRATION_WORKFLOWS = [AlertsProductOrchestrateWorkflow]
+SHARED_ORCHESTRATION_ACTIVITIES = [alerts_product_discover_demand_activity]
EVALUATION_WORKFLOWS = [AlertsProductCheckDueWorkflow]
EVALUATION_ACTIVITIES = [alerts_product_check_due_activity]
DELIVERY_WORKFLOWS = [AlertsProductDeliverWorkflow]
diff --git a/products/alerts/backend/tests/test_temporal_workflows.py b/products/alerts/backend/tests/test_temporal_workflows.py
index 4f24304ffeeb..8cf2912363fb 100644
--- a/products/alerts/backend/tests/test_temporal_workflows.py
+++ b/products/alerts/backend/tests/test_temporal_workflows.py
@@ -3,6 +3,7 @@ import asyncio
import logging
import datetime as dt
from collections.abc import AsyncIterator, Iterator
+from contextlib import nullcontext
from typing import Literal
import pytest
@@ -17,6 +18,7 @@ from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanE
from temporalio import activity, workflow
from temporalio.api.enums.v1 import EventType
from temporalio.client import WorkflowExecutionStatus, WorkflowFailureError
+from temporalio.common import SearchAttributeKey, SearchAttributePair, TypedSearchAttributes
from temporalio.contrib.opentelemetry import OpenTelemetryPlugin
from temporalio.exceptions import (
ActivityError,
@@ -30,16 +32,23 @@ from temporalio.runtime import MetricBuffer, Runtime, TelemetryConfig
from temporalio.testing import WorkflowEnvironment
from temporalio.worker import Replayer, UnsandboxedWorkflowRunner, Worker
+from products.alerts.backend.facade.contracts import AlertDemand, DemandDiscoveryInputs, SourceKind
from products.alerts.backend.facade.temporal import (
DELIVERY_ACTIVITIES,
DELIVERY_WORKFLOWS,
EVALUATION_ACTIVITIES,
EVALUATION_WORKFLOWS,
+ SHARED_ORCHESTRATION_ACTIVITIES,
SHARED_ORCHESTRATION_WORKFLOWS,
AlertsProductTelemetryInterceptor,
)
+from products.alerts.backend.logic import demand
from products.alerts.backend.temporal import postgres
-from products.alerts.backend.temporal.workflows import AlertsProductCheckDueWorkflow, AlertsProductInputs
+from products.alerts.backend.temporal.workflows import (
+ AlertsProductCheckDueWorkflow,
+ AlertsProductInputs,
+ AlertsProductOrchestrateWorkflow,
+)
@workflow.defn(name="test-alerts-product-close-after-child-start")
@@ -80,10 +89,11 @@ def postgres_cursor() -> Iterator[MagicMock]:
@pytest.mark.asyncio
@pytest.mark.parametrize("database_error", [False, True])
@pytest.mark.parametrize(
- "tick_workflow, tick_queue",
+ "tick_workflow, tick_queue, demand_enabled",
[
- ("alerts-product-check-due", settings.ALERTS_PRODUCT_EVALUATION_TASK_QUEUE),
- ("alerts-product-orchestrate", settings.ALERTS_PRODUCT_SHARED_ORCHESTRATION_TASK_QUEUE),
+ ("alerts-product-check-due", settings.ALERTS_PRODUCT_EVALUATION_TASK_QUEUE, False),
+ ("alerts-product-orchestrate", settings.ALERTS_PRODUCT_SHARED_ORCHESTRATION_TASK_QUEUE, True),
+ ("alerts-product-orchestrate", settings.ALERTS_PRODUCT_SHARED_ORCHESTRATION_TASK_QUEUE, False),
],
)
async def test_each_tick_starts_independent_delivery(
@@ -96,6 +106,7 @@ async def test_each_tick_starts_independent_delivery(
database_error: bool,
tick_workflow: str,
tick_queue: str,
+ demand_enabled: bool,
) -> None:
if database_error:
postgres_cursor.execute.side_effect = OperationalError("sensitive connection details")
@@ -117,6 +128,7 @@ async def test_each_tick_starts_independent_delivery(
client,
task_queue=settings.ALERTS_PRODUCT_SHARED_ORCHESTRATION_TASK_QUEUE,
workflows=SHARED_ORCHESTRATION_WORKFLOWS,
+ activities=SHARED_ORCHESTRATION_ACTIVITIES,
workflow_runner=UnsandboxedWorkflowRunner(),
),
Worker(
@@ -129,20 +141,45 @@ async def test_each_tick_starts_independent_delivery(
),
):
for _ in range(2):
- parent = await client.start_workflow(
- tick_workflow,
- AlertsProductInputs(),
- id=workflow_id,
- task_queue=tick_queue,
- execution_timeout=dt.timedelta(seconds=10),
- )
- assert await parent.result() is None
+ with nullcontext() if demand_enabled else patch.object(workflow, "patched", return_value=False):
+ parent = await client.start_workflow(
+ tick_workflow,
+ AlertsProductInputs(),
+ id=workflow_id,
+ task_queue=tick_queue,
+ execution_timeout=dt.timedelta(seconds=10),
+ )
+ assert await parent.result() is None
history = await parent.fetch_history()
evaluation_run_id = parent.first_execution_run_id
if tick_workflow == "alerts-product-orchestrate":
- assert not any(
- event.event_type == EventType.EVENT_TYPE_ACTIVITY_TASK_SCHEDULED for event in history.events
- )
+ discovery_events = [
+ event.activity_task_scheduled_event_attributes
+ for event in history.events
+ if event.event_type == EventType.EVENT_TYPE_ACTIVITY_TASK_SCHEDULED
+ ]
+ assert len(discovery_events) == int(demand_enabled)
+ if demand_enabled:
+ assert discovery_events[0].activity_type.name == "alerts_product_discover_demand_activity"
+ assert (
+ discovery_events[0].task_queue.name == settings.ALERTS_PRODUCT_SHARED_ORCHESTRATION_TASK_QUEUE
+ )
+ discovery_inputs = await client.data_converter.decode(
+ discovery_events[0].input.payloads, [DemandDiscoveryInputs]
+ )
+ assert dt.datetime.fromisoformat(discovery_inputs[0].cutoff) == history.events[
+ 0
+ ].event_time.ToDatetime(tzinfo=dt.UTC)
+ completed_discovery = next(
+ event.activity_task_completed_event_attributes
+ for event in history.events
+ if event.event_type == EventType.EVENT_TYPE_ACTIVITY_TASK_COMPLETED
+ )
+ discovered = await client.data_converter.decode(completed_discovery.result.payloads, [AlertDemand])
+ assert discovered[0] == demand.discover_synthetic_demand(discovery_inputs[0].cutoff)
+ await Replayer(
+ workflows=SHARED_ORCHESTRATION_WORKFLOWS, workflow_runner=UnsandboxedWorkflowRunner()
+ ).replay_workflow(history)
evaluations = [
event.start_child_workflow_execution_initiated_event_attributes
for event in history.events
@@ -216,6 +253,7 @@ async def test_each_tick_starts_independent_delivery(
updates = sdk_metrics.retrieve_updates()
for metric_name in ("temporal_activity_schedule_to_start_latency", "temporal_activity_execution_latency"):
for task_queue, expected_attempts in (
+ (settings.ALERTS_PRODUCT_SHARED_ORCHESTRATION_TASK_QUEUE, 2 if demand_enabled else 0),
(settings.ALERTS_PRODUCT_EVALUATION_TASK_QUEUE, 2),
(settings.ALERTS_PRODUCT_DELIVERY_TASK_QUEUE, 4),
):
@@ -233,7 +271,7 @@ async def test_each_tick_starts_independent_delivery(
workflow_spans = [span for span in spans if span.name.startswith("RunWorkflow:")]
activity_spans = [span for span in spans if span.name.startswith("RunActivity:")]
assert len(workflow_spans) == (6 if tick_workflow == "alerts-product-orchestrate" else 4)
- assert len(activity_spans) == 6
+ assert len(activity_spans) == (8 if demand_enabled else 6)
for delivery in (span for span in workflow_spans if span.name == "RunWorkflow:alerts-product-deliver"):
assert delivery.parent is not None
child_start = spans_by_id[delivery.parent.span_id]
@@ -267,6 +305,9 @@ async def test_each_tick_starts_independent_delivery(
for entry in activity_logs
if entry.get("span_id") == trace.format_span_id(attempt_span.context.span_id)
]
+ if attempt_span.name == "RunActivity:alerts_product_discover_demand_activity":
+ assert entries == []
+ continue
assert [entry["event"] for entry in entries] == [
"alerts_product_activity_started",
"alerts_product_activity_finished",
@@ -442,3 +483,62 @@ async def test_probe_workflow_cancellation_does_not_start_delivery() -> None:
):
await AlertsProductCheckDueWorkflow().run(AlertsProductInputs())
start_delivery.assert_not_awaited()
+
+
+ "cutoff_offset, expected_ids",
+ [
+ (-2, {}),
+ (-1, {SourceKind.LOGS: ["00000000-0000-4000-8000-000000000001"]}),
+ (
+ 0,
+ {
+ SourceKind.LOGS: ["00000000-0000-4000-8000-000000000001", "00000000-0000-4000-8000-000000000002"],
+ SourceKind.INSIGHT: ["00000000-0000-4000-8000-000000000003"],
+ },
+ ),
+ ],
+)
+def test_discovery_filters_and_groups_due_configurations(
+ cutoff_offset: int, expected_ids: dict[SourceKind, list[str]]
+) -> None:
+ tick_time = dt.datetime(2026, 9, 16, 10, tzinfo=dt.UTC)
+ configurations = demand._synthetic_configurations(tick_time)
+ cutoff = (tick_time + dt.timedelta(minutes=cutoff_offset)).isoformat()
+ with patch.object(demand, "_synthetic_configurations", return_value=configurations):
+ for _ in range(2):
+ assert demand.discover_synthetic_demand(cutoff).configuration_ids_by_source == expected_ids
+
+
[email protected]("cutoff", ["invalid", "2026-09-16T10:00:00"])
+def test_discovery_rejects_invalid_cutoff(cutoff: str) -> None:
+ with pytest.raises(ValueError):
+ demand.discover_synthetic_demand(cutoff)
+
+
[email protected]("scheduled", [False, True])
+async def test_discovery_uses_scheduled_cutoff_or_manual_start(scheduled: bool) -> None:
+ tick_time = dt.datetime(2026, 9, 16, 10, tzinfo=dt.UTC)
+ actual_start = tick_time + dt.timedelta(seconds=20)
+ attributes = TypedSearchAttributes(
+ [SearchAttributePair(SearchAttributeKey.for_datetime("TemporalScheduledStartTime"), tick_time)]
+ if scheduled
+ else []
+ )
+ with (
+ patch.object(
+ workflow,
+ "info",
+ return_value=MagicMock(workflow_start_time=actual_start, typed_search_attributes=attributes),
+ ),
+ patch.object(workflow, "patched", return_value=True),
+ patch.object(workflow, "execute_activity", AsyncMock()) as discover,
+ patch.object(workflow, "execute_child_workflow", AsyncMock()) as evaluate,
+ ):
+ await AlertsProductOrchestrateWorkflow().run(AlertsProductInputs())
+ assert discover.await_args is not None
+ assert discover.await_args.args[1] == DemandDiscoveryInputs(
+ cutoff=(tick_time if scheduled else actual_start).isoformat()
+ )
+ assert evaluate.await_args is not None
+ assert evaluate.await_args.args[1] == AlertsProductInputs()