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(signals): skip no-op scheduled scout runs with a pre-check query (#114355)

posthog[bot]2f1d03a58db3
diff --git a/posthog/temporal/tests/ai/test_module_integrity.py b/posthog/temporal/tests/ai/test_module_integrity.py
index 4ae464b2fbef..6aafedf736da 100644
--- a/posthog/temporal/tests/ai/test_module_integrity.py
+++ b/posthog/temporal/tests/ai/test_module_integrity.py
@@ -177,6 +177,7 @@ class TestSignalsProductModuleIntegrity:
"fetch_enabled_signals_scout_runs_activity",
"stamp_dispatched_signals_scout_runs_activity",
"run_due_signal_report_checks_activity",
+ "evaluate_signals_scout_precheck_activity",
"run_signals_scout_activity",
"load_scout_trial_evaluation_activity",
"dispatch_scout_trial_comparison_activity",
diff --git a/products/signals/backend/migrations/0165_scout_config_precheck.py b/products/signals/backend/migrations/0165_scout_config_precheck.py
new file mode 100644
index 000000000000..cdfd6f757b58
--- /dev/null
+++ b/products/signals/backend/migrations/0165_scout_config_precheck.py
@@ -0,0 +1,17 @@
+# Generated by Django 5.2.18 on 2026-10-09 08:41
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("signals", "0164_report_monitoring_foundation"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="signalscoutconfig",
+ name="precheck_query",
+ field=models.TextField(blank=True, null=True),
+ ),
+ ]
diff --git a/products/signals/backend/migrations/max_migration.txt b/products/signals/backend/migrations/max_migration.txt
index 2dec3a487f33..4497d66df879 100644
--- a/products/signals/backend/migrations/max_migration.txt
+++ b/products/signals/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0164_report_monitoring_foundation
+0165_scout_config_precheck
diff --git a/products/signals/backend/models.py b/products/signals/backend/models.py
index 01337114823a..aaf8ee54afc9 100644
--- a/products/signals/backend/models.py
+++ b/products/signals/backend/models.py
@@ -2727,6 +2727,11 @@ class SignalScoutConfig(ModelActivityMixin, TeamScopedRootMixin, UUIDModel):
# defer an already-overdue scheduled run. Null on rows whose schedule was never edited —
# `created_at` anchors those.
schedule_changed_at = models.DateTimeField(null=True, blank=True)
+ # Optional HogQL query a scheduled run evaluates before it starts (`scout_harness/precheck.py`).
+ # No rows, or a single false value, skips the run, so a scout that watches something rare can
+ # run often and pay for a sandbox only when there is something new. `{since}` and `{now}` are
+ # bound as HogQL placeholders. Null turns the pre-check off.
+ precheck_query = models.TextField(null=True, blank=True)
# Stamped by the coordinator after each dispatch; drives the due-check. Written every
# run, so it is excluded from activity logging (see field_exclusions below).
last_run_at = models.DateTimeField(null=True, blank=True)
diff --git a/products/signals/backend/scout_harness/precheck.py b/products/signals/backend/scout_harness/precheck.py
new file mode 100644
index 000000000000..c449ccd4430c
--- /dev/null
+++ b/products/signals/backend/scout_harness/precheck.py
@@ -0,0 +1,219 @@
+"""Pre-check for scheduled scout runs.
+
+A scout config can carry a HogQL query that a scheduled run evaluates before it starts. When the
+query returns no rows, or one row with one false value (`false`, `0`, null or empty), there is
+nothing new to look at, so the run is skipped before it creates a run row, a sandbox, or an LLM
+call. Any other result starts the run. The single-value rule lets a `SELECT count() ...` gate work
+as written, because a count always returns one row. Only the coordinator's scheduled dispatch
+evaluates it: a manual, workflow, or check run already has a reason to run.
+
+A skip writes nothing. The coordinator stamped `last_run_at` (the dispatch anchor) when it
+dispatched the run, so the next tick does not dispatch it again at once. `{since}` reads the last
+run row, so the next run that starts still sees everything since the last run that actually ran.
+The failure breaker and the inactivity sweep read run rows, so a quiet scout is never paused for
+being quiet.
+
+A query error never turns the scout off: the run continues as if there were no pre-check.
+"""
+
+from __future__ import annotations
+
+import json
+import time
+from datetime import datetime
+from typing import Any, Literal
+
+from django.utils import timezone
+
+import structlog
+import posthoganalytics
+
+from posthog.hogql import ast
+from posthog.hogql.constants import HogQLGlobalSettings
+from posthog.hogql.parser import parse_select
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.clickhouse.query_tagging import Feature, Product, tags_context
+from posthog.clickhouse.workload import Workload
+from posthog.dataclasses import frozen
+from posthog.event_usage import groups
+from posthog.models import Team
+
+from products.signals.backend.models import SignalScoutConfig, SignalScoutRun
+from products.signals.backend.scout_harness.limits import SCOUT_TRIAL_METADATA_KEY
+
+logger = structlog.get_logger(__name__)
+
+PRECHECK_TIMEOUT_S = 10
+PRECHECK_MAX_ROWS = 50
+PRECHECK_MAX_TEXT_BYTES = 8 * 1024
+
+PrecheckOutcome = Literal["run", "skip", "error"]
+# `rows`: the query found rows. `no_rows`: it found none. `false_value`: it returned one false
+# value. `query_error`: the query failed and the run continues.
+PrecheckReason = Literal["rows", "no_rows", "false_value", "query_error"]
+
+
+@frozen
+class PrecheckResult:
+ outcome: PrecheckOutcome
+ reason: PrecheckReason
+ row_count: int = 0
+ # The capped rows, one JSON object per line, for a later prompt block.
+ rows_text: str | None = None
+
+ @property
+ def should_run(self) -> bool:
+ return self.outcome != "skip"
+
+
+@frozen
+class _PrecheckRows:
+ columns: list[Any]
+ rows: list[Any]
+
+ @property
+ def is_single_false_value(self) -> bool:
+ return len(self.rows) == 1 and len(self.rows[0]) == 1 and self.rows[0][0] in (None, False, 0, "")
+
+
+def evaluate_scout_precheck(team_id: int, skill_name: str, now: datetime | None = None) -> PrecheckResult | None:
+ """Evaluate the pre-check of one scout. Return None when the scout has no pre-check.
+
+ Never raises for a query problem: a failed query returns an `error` outcome that runs the scout.
+ """
+ config = (
+ SignalScoutConfig.objects.for_team(team_id)
+ .filter(skill_name=skill_name)
+ .only("id", "team_id", "skill_name", "created_at", "status", "precheck_query")
+ .first()
+ )
+ # A paused lane only runs as a breaker probe, which exists to find out whether the lane can
+ # succeed. A skip would hold the lane paused for as long as it stays quiet.
+ if config is None or not config.precheck_query or config.status not in SignalScoutConfig.RUNNABLE_STATUSES:
+ return None
+
+ now = now or timezone.now()
+ since = _last_real_run_at(team_id, skill_name) or config.created_at
+ team = Team.objects.select_related("organization").get(pk=team_id)
+ started = time.monotonic()
+ error_type: str | None = None
+
+ try:
+ found = _run_query(team, config.precheck_query, since=since, now=now)
+ except Exception as error:
+ error_type = type(error).__name__
+ logger.warning(
+ "signals_scout: pre-check query failed, running the scout",
+ team_id=team_id,
+ skill_name=skill_name,
+ error_type=error_type,
+ exc_info=True,
+ )
+ result = PrecheckResult(outcome="error", reason="query_error")
+ else:
+ result = _result_from_rows(found)
+
+ _capture_precheck_evaluated(
+ team=team,
+ config=config,
+ result=result,
+ duration_ms=round((time.monotonic() - started) * 1000),
+ error_type=error_type,
+ )
+ return result
+
+
+def _last_real_run_at(team_id: int, skill_name: str) -> datetime | None:
+ return (
+ SignalScoutRun.objects.for_team(team_id)
+ .filter(skill_name=skill_name)
+ .exclude(metadata__has_key=SCOUT_TRIAL_METADATA_KEY)
+ .order_by("-created_at")
+ .values_list("created_at", flat=True)
+ .first()
+ )
+
+
+def _result_from_rows(found: _PrecheckRows) -> PrecheckResult:
+ if not found.rows:
+ return PrecheckResult(outcome="skip", reason="no_rows")
+ if found.is_single_false_value:
+ return PrecheckResult(outcome="skip", reason="false_value", row_count=1)
+ return PrecheckResult(outcome="run", reason="rows", row_count=len(found.rows), rows_text=_render_rows(found))
+
+
+def _run_query(team: Team, query: str, *, since: datetime, now: datetime) -> _PrecheckRows:
+ parsed = parse_select(query, placeholders={"since": ast.Constant(value=since), "now": ast.Constant(value=now)})
+ capped = _cap_rows(parsed)
+ with tags_context(product=Product.SIGNALS, feature=Feature.ENRICHMENT, team_id=team.pk):
+ response = execute_hogql_query(
+ query_type="scout_precheck",
+ query=capped,
+ team=team,
+ workload=Workload.OFFLINE,
+ settings=HogQLGlobalSettings(max_execution_time=PRECHECK_TIMEOUT_S),
+ )
+ return _PrecheckRows(columns=response.columns or [], rows=(response.results or [])[:PRECHECK_MAX_ROWS])
+
+
+def _cap_rows(parsed: ast.SelectQuery | ast.SelectSetQuery) -> ast.SelectQuery:
+ """Cap the rows whatever the owner wrote, including a union or no LIMIT at all."""
+ if isinstance(parsed, ast.SelectQuery):
+ # Set the limit in place. `SELECT *` over a subquery loses unaliased columns, so a wrapper
+ # would turn `SELECT false` into an unnamed `1`.
+ current = parsed.limit
+ if not (
+ isinstance(current, ast.Constant) and isinstance(current.value, int) and current.value <= PRECHECK_MAX_ROWS
+ ):
+ parsed.limit = ast.Constant(value=PRECHECK_MAX_ROWS)
+ return parsed
+ return ast.SelectQuery(
+ select=[ast.Field(chain=["*"])],
+ select_from=ast.JoinExpr(table=parsed),
+ limit=ast.Constant(value=PRECHECK_MAX_ROWS),
+ )
+
+
+def _render_rows(found: _PrecheckRows) -> str:
+ """Render rows one JSON object per line, and stop before the text passes the size cap."""
+ lines: list[str] = []
+ size = 0
+ for row in found.rows:
+ line = json.dumps(dict(zip(found.columns, row)), default=str, ensure_ascii=False)
+ size += len(line.encode("utf-8")) + 1
+ if size > PRECHECK_MAX_TEXT_BYTES:
+ break
+ lines.append(line)
+ return "\n".join(lines)
+
+
+def _capture_precheck_evaluated(
+ *,
+ team: Team,
+ config: SignalScoutConfig,
+ result: PrecheckResult,
+ duration_ms: int,
+ error_type: str | None,
+) -> None:
+ try:
+ posthoganalytics.capture(
+ event="scout_precheck_evaluated",
+ distinct_id=str(team.uuid),
+ properties={
+ "skill_name": config.skill_name,
+ "scout_config_id": str(config.id),
+ "outcome": result.outcome,
+ "reason": result.reason,
+ "row_count": result.row_count,
+ "duration_ms": duration_ms,
+ "error_type": error_type,
+ },
+ groups=groups(team.organization, team),
+ )
+ except Exception:
+ logger.warning(
+ "signals_scout: failed to capture pre-check analytics event",
+ team_id=team.pk,
+ skill_name=config.skill_name,
+ )
diff --git a/products/signals/backend/temporal/__init__.py b/products/signals/backend/temporal/__init__.py
index 2b86e38875cc..1f9a2d49cd26 100644
--- a/products/signals/backend/temporal/__init__.py
+++ b/products/signals/backend/temporal/__init__.py
@@ -13,6 +13,7 @@ from products.signals.backend.temporal.agentic.scout_rubrics import (
)
from products.signals.backend.temporal.agentic.scout_scheduler import (
RunSignalsScoutWorkflow,
+ evaluate_signals_scout_precheck_activity,
resume_signals_scout_workflow_step,
run_signals_scout_activity,
)
@@ -189,6 +190,7 @@ ACTIVITIES = [
run_custom_signal_agent_activity,
run_signal_semantic_search_activity,
run_signals_scout_activity,
+ evaluate_signals_scout_precheck_activity,
plan_scout_suggestion_runs_activity,
resume_signals_scout_workflow_step,
run_scout_suggestions_activity,
diff --git a/products/signals/backend/temporal/agentic/scout_scheduler.py b/products/signals/backend/temporal/agentic/scout_scheduler.py
index 17477f717aa5..3cb86803d0d7 100644
--- a/products/signals/backend/temporal/agentic/scout_scheduler.py
+++ b/products/signals/backend/temporal/agentic/scout_scheduler.py
@@ -37,6 +37,7 @@ from products.signals.backend.scout_harness.limits import (
TRIGGERED_BY_WORKFLOW,
WORKFLOW_HARD_CEILING_S,
)
+from products.signals.backend.scout_harness.precheck import PRECHECK_TIMEOUT_S, evaluate_scout_precheck
from products.signals.backend.temporal import metrics
if TYPE_CHECKING:
@@ -120,6 +121,21 @@ def resume_signals_scout_workflow_step(input: RunSignalsScoutInput, output: RunS
_resume_workflow_step(input, output, raise_on_error=True)
+@frozen
+class EvaluateScoutPrecheckOutput:
+ should_run: bool
+
+
+@close_db_connections
+async def evaluate_signals_scout_precheck_activity(input: RunSignalsScoutInput) -> EvaluateScoutPrecheckOutput:
+ """Evaluate the scout's pre-check query. A scout without one always runs."""
+ result = await database_sync_to_async(evaluate_scout_precheck, thread_sensitive=False)(
+ input.team_id, input.skill_name
+ )
+ return EvaluateScoutPrecheckOutput(should_run=result is None or result.should_run)
+
+
@temporalio.activity.defn
@close_db_connections
async def run_signals_scout_activity(input: RunSignalsScoutInput) -> RunSignalsScoutOutput:
@@ -260,6 +276,19 @@ class RunSignalsScoutWorkflow:
managed_resume = bool(input.workflow_origin_key) and temporalio.workflow.patched("scout-workflow-step-resume")
if managed_resume:
input = replace(input, workflow_managed_resume=True)
+ if input.triggered_by == TRIGGERED_BY_SCHEDULE and temporalio.workflow.patched("scout-precheck"):
+ precheck = await self._evaluate_precheck(input)
+ if not precheck.should_run:
+ # No run row exists for a skipped run. The coordinator already advanced `last_run_at`.
+ return RunSignalsScoutOutput(
+ run_id=None,
+ task_run_id=None,
+ status=None,
+ runtime_s=0.0,
+ skill_name=input.skill_name,
+ skill_version=input.skill_version or 0,
+ skip_reason="precheck_skipped",
+ )
try:
output = await temporalio.workflow.execute_activity(
run_signals_scout_activity,
@@ -287,6 +316,22 @@ class RunSignalsScoutWorkflow:
await self._resume_step(input, output)
return output
+ async def _evaluate_precheck(self, input: RunSignalsScoutInput) -> EvaluateScoutPrecheckOutput:
+ try:
+ return await temporalio.workflow.execute_activity(
+ evaluate_signals_scout_precheck_activity,
+ input,
+ start_to_close_timeout=timedelta(seconds=PRECHECK_TIMEOUT_S + 20),
+ retry_policy=RetryPolicy(maximum_attempts=1),
+ )
+ except ActivityError:
+ # A pre-check that cannot finish must not turn the scout off.
+ temporalio.workflow.logger.warning(
+ "signals_scout: pre-check activity failed, running the scout",
+ extra={"team_id": input.team_id, "skill_name": input.skill_name},
+ )
+ return EvaluateScoutPrecheckOutput(should_run=True)
+
async def _resume_step(self, input: RunSignalsScoutInput, output: RunSignalsScoutOutput) -> None:
await temporalio.workflow.execute_activity(
resume_signals_scout_workflow_step,
diff --git a/products/signals/backend/test/test_scout_harness.py b/products/signals/backend/test/test_scout_harness.py
index 66998828d969..ad0fda3cb6c3 100644
--- a/products/signals/backend/test/test_scout_harness.py
+++ b/products/signals/backend/test/test_scout_harness.py
@@ -101,9 +101,11 @@ from products.signals.backend.scout_harness.trial_launch import (
)
from products.signals.backend.scout_harness.trial_result import get_trial_workflow_status
from products.signals.backend.temporal.agentic.scout_scheduler import (
+ EvaluateScoutPrecheckOutput,
RunSignalsScoutInput,
RunSignalsScoutOutput,
RunSignalsScoutWorkflow,
+ evaluate_signals_scout_precheck_activity,
run_signals_scout_activity,
start_trial_signals_scout_run,
)
@@ -3608,6 +3610,8 @@ async def test_workflow_delivers_scout_outcomes_even_when_the_run_activity_canno
)
async def execute_activity(activity_function, input=None, **kwargs):
+ if activity_function is evaluate_signals_scout_precheck_activity:
+ return EvaluateScoutPrecheckOutput(should_run=True)
if activity_function is run_signals_scout_activity:
assert kwargs["start_to_close_timeout"] == timedelta(minutes=timeout_minutes)
if outcome == "cancelled":
@@ -3649,6 +3653,63 @@ async def test_workflow_delivers_scout_outcomes_even_when_the_run_activity_canno
assert resume.call_args.kwargs["raise_on_error"] is True
+ "triggered_by,precheck,runs",
+ [
+ ("schedule", "skip", False),
+ ("schedule", "run", True),
+ ("schedule", "activity_error", True),
+ ("manual", "skip", True),
+ ("workflow", "skip", True),
+ ("check", "skip", True),
+ ],
+)
+async def test_workflow_skips_only_scheduled_runs_the_precheck_rejects(triggered_by, precheck, runs):
+ output = RunSignalsScoutOutput(
+ run_id="abc", task_run_id="def", status="completed", runtime_s=1.0, skill_name="s", skill_version=1
+ )
+ called: list[object] = []
+
+ async def execute_activity(activity_function, input=None, **kwargs):
+ called.append(activity_function)
+ if activity_function is evaluate_signals_scout_precheck_activity:
+ if precheck == "activity_error":
+ raise ActivityError(
+ "Pre-check failed",
+ scheduled_event_id=1,
+ started_event_id=2,
+ identity="worker",
+ activity_type="evaluate_signals_scout_precheck_activity",
+ activity_id="precheck",
+ retry_state=None,
+ )
+ return EvaluateScoutPrecheckOutput(should_run=precheck == "run")
+ return output
+
+ with (
+ patch(
+ "products.signals.backend.temporal.agentic.scout_scheduler.temporalio.workflow.patched", return_value=True
+ ),
+ patch(
+ "products.signals.backend.temporal.agentic.scout_scheduler.temporalio.workflow.execute_activity",
+ side_effect=execute_activity,
+ ),
+ patch("products.signals.backend.temporal.agentic.scout_scheduler.temporalio.workflow.logger"),
+ ):
+ result = await RunSignalsScoutWorkflow().run(
+ RunSignalsScoutInput(team_id=7, skill_name="s", triggered_by=triggered_by)
+ )
+
+ assert (run_signals_scout_activity in called) is runs
+ assert (evaluate_signals_scout_precheck_activity in called) is (triggered_by == "schedule")
+ if runs:
+ assert result == output
+ else:
+ assert result.run_id is None
+ assert result.skip_reason == "precheck_skipped"
+
+
class TestScoutCosts(BaseTest):
def setUp(self) -> None:
super().setUp()
diff --git a/products/signals/backend/test/test_scout_precheck.py b/products/signals/backend/test/test_scout_precheck.py
new file mode 100644
index 000000000000..14ee9fcc506a
--- /dev/null
+++ b/products/signals/backend/test/test_scout_precheck.py
@@ -0,0 +1,135 @@
+from datetime import UTC, datetime, timedelta
+
+import time_machine
+from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
+from unittest.mock import patch
+
+from django.apps import apps
+
+from parameterized import parameterized
+
+from products.signals.backend.models import SignalScoutConfig, SignalScoutRun
+from products.signals.backend.scout_harness.precheck import PRECHECK_MAX_ROWS, evaluate_scout_precheck
+
+NOW = datetime(2026, 10, 9, 12, 0, 0, tzinfo=UTC)
+SKILL = "signals-scout-errors"
+NEW_EVENTS_QUERY = "SELECT event FROM events WHERE event = 'boom' AND timestamp > {since} AND timestamp <= {now}"
+
+
+@time_machine.travel(NOW, tick=False)
+class TestEvaluateScoutPrecheck(ClickhouseTestMixin, BaseTest):
+ def _config(self, query: str | None) -> SignalScoutConfig:
+ config = SignalScoutConfig.all_teams.create(team=self.team, skill_name=SKILL, precheck_query=query)
+ SignalScoutConfig.all_teams.filter(pk=config.pk).update(created_at=NOW - timedelta(days=7))
+ return config
+
+ def _last_run(self, hours_ago: float, *, trial: bool = False) -> None:
+ Task = apps.get_model("tasks", "Task")
+ TaskRun = apps.get_model("tasks", "TaskRun")
+ task = Task.objects.create(
+ team=self.team, title="scout run", description="", origin_product=Task.OriginProduct.SIGNALS_SCOUT
+ )
+ run = SignalScoutRun.all_teams.create(
+ team=self.team,
+ task_run=TaskRun.objects.create(task=task, team=self.team),
+ skill_name=SKILL,
+ skill_version=1,
+ metadata={"scout_trial": {}} if trial else {},
+ )
+ SignalScoutRun.all_teams.filter(pk=run.pk).update(created_at=NOW - timedelta(hours=hours_ago))
+
+ def _event(self, hours_ago: float) -> None:
+ _create_event(team=self.team, event="boom", distinct_id="d1", timestamp=NOW - timedelta(hours=hours_ago))
+
+ def _evaluate(self):
+ with patch("products.signals.backend.scout_harness.precheck.posthoganalytics.capture") as capture:
+ result = evaluate_scout_precheck(self.team.pk, SKILL)
+ return result, capture
+
+ @parameterized.expand(
+ [
+ # The only event is older than the last run that ran, so `{since}` hides it.
+ ("nothing_since_last_run", [5], "skip", "no_rows", 0),
+ ("new_event_since_last_run", [5, 1], "run", "rows", 1),
+ ]
+ )
+ def test_since_is_the_last_run_that_ran(self, _name, event_hours_ago, outcome, reason, row_count) -> None:
+ self._config(NEW_EVENTS_QUERY)
+ self._last_run(hours_ago=2)
+ # A trial run does not move `{since}`.
+ self._last_run(hours_ago=0.5, trial=True)
+ for hours_ago in event_hours_ago:
+ self._event(hours_ago)
+ flush_persons_and_events()
+
+ result, capture = self._evaluate()
+
+ assert result is not None
+ assert (result.outcome, result.reason, result.row_count) == (outcome, reason, row_count)
+ properties = capture.call_args.kwargs["properties"]
+ assert capture.call_args.kwargs["event"] == "scout_precheck_evaluated"
+ assert (properties["outcome"], properties["row_count"]) == (outcome, row_count)
+
+ @parameterized.expand(
+ [
+ ("no_limit", "SELECT number FROM numbers(1000)"),
+ ("larger_limit", "SELECT number FROM numbers(1000) LIMIT 500"),
+ ("union", "SELECT number FROM numbers(40) UNION ALL SELECT number FROM numbers(40)"),
+ ]
+ )
+ def test_rows_are_capped(self, _name, query) -> None:
+ self._config(query)
+
+ result, _ = self._evaluate()
+
+ assert result is not None
+ assert result.row_count == PRECHECK_MAX_ROWS
+ assert result.rows_text is not None and len(result.rows_text.splitlines()) == PRECHECK_MAX_ROWS
+
+ def test_query_error_runs_the_scout(self) -> None:
+ self._config("SELECT nope FROM not_a_table WHERE timestamp > {since}")
+
+ result, capture = self._evaluate()
+
+ assert result is not None
+ assert (result.outcome, result.should_run) == ("error", True)
+ assert capture.call_args.kwargs["properties"]["error_type"] is not None
+
+ @parameterized.expand(
+ [
+ ("zero_count", "SELECT count() FROM numbers(0)", "skip", "false_value"),
+ ("false", "SELECT false", "skip", "false_value"),
+ ("null", "SELECT NULL", "skip", "false_value"),
+ ("empty_string", "SELECT ''", "skip", "false_value"),
+ ("nonzero_count", "SELECT count() FROM numbers(3)", "run", "rows"),
+ ("true", "SELECT true", "run", "rows"),
+ ("zero_with_a_second_column", "SELECT 0, 'x'", "run", "rows"),
+ ("two_zero_rows", "SELECT 0 FROM numbers(2)", "run", "rows"),
+ ]
+ )
+ def test_single_false_value_skips(self, _name, query, outcome, reason) -> None:
+ self._config(query)
+
+ result, _ = self._evaluate()
+
+ assert result is not None
+ assert (result.outcome, result.reason) == (outcome, reason)
+
+ @parameterized.expand(
+ [
+ ("no_query", None, SignalScoutConfig.Status.ACTIVE),
+ ("breaker_probe", "SELECT 1 WHERE 0", SignalScoutConfig.Status.PAUSED_BY_SYSTEM),
+ ]
+ )
+ def test_no_precheck(self, _name, query, status) -> None:
+ config = self._config(query)
+ SignalScoutConfig.all_teams.filter(pk=config.pk).update(
+ status=status,
+ enabled=status in SignalScoutConfig.RUNNABLE_STATUSES,
+ pause_reason=None if status == SignalScoutConfig.Status.ACTIVE else "repeated_failures",
+ )
+
+ result, capture = self._evaluate()
+
+ assert result is None
+ capture.assert_not_called()