: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(signals): track customer spend for signals and scout runs (#110924)
Oliver Brownef9280fed517a
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yamlindex e32500e52308..bbbf3e6de363 100644--- a/.semgrep/rules/security/idor-team-scoped-models.yaml+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml@@ -401,6 +401,7 @@ rules:|SignalScoutStructuredOutput|SignalScoutSuggestionSet|SignalScoutBackgroundBand+ |SignalSpend|SignalScratchpad|SignalProjectProfile|SingleSessionSummary@@ -861,6 +862,7 @@ rules:|SignalScoutStructuredOutput|SignalScoutSuggestionSet|SignalScoutBackgroundBand+ |SignalSpend|SignalScratchpad|SignalProjectProfile|SingleSessionSummarydiff --git a/posthog/llm/gateway_usage.py b/posthog/llm/gateway_usage.pynew file mode 100644index 000000000000..5ba71c110d14--- /dev/null+++ b/posthog/llm/gateway_usage.py@@ -0,0 +1,57 @@+import re+from decimal import Decimal++import structlog++from posthog.dataclasses import frozen++logger = structlog.get_logger(__name__)+_REQUEST_ID = re.compile(r"[a-zA-Z0-9_-]{1,255}\Z")+_USD_AMOUNT = re.compile(r"[0-9]{1,12}(?:\.[0-9]{1,6})?\Z")+++@frozen+class GatewayRequestCost:+ model: str+ provider: str+ cost_microusd: int+++async def fetch_gateway_cost(request_id: str, *, base_url: str, api_key: str) -> GatewayRequestCost | None:+ import aiohttp # noqa: PLC0415 - keeps aiohttp off Django's startup path++ base_url = base_url.rstrip("/").removesuffix("/v1")+ if not base_url or not api_key or not _REQUEST_ID.fullmatch(request_id):+ return None+ try:+ async with (+ # nosemgrep: aiohttp-missing-trust-env — the internal gateway must bypass the external egress proxy+ aiohttp.ClientSession(trust_env=False) as session,+ session.get(+ f"{base_url}/v1/usage/{request_id}",+ headers={"Authorization": f"Bearer {api_key}"},+ timeout=aiohttp.ClientTimeout(total=15, connect=2, sock_read=3),+ allow_redirects=False,+ ) as response,+ ):+ if response.status != 200:+ logger.warning("gateway_usage.cost_pending", status_code=response.status)+ return None+ body = await response.json()+ if not isinstance(body, dict) or body.get("request_id") != request_id:+ return None+ amount = body.get("cost_usd")+ model, provider = body.get("model") or "unknown", body.get("provider") or "unknown"+ if (+ not isinstance(amount, str)+ or not _USD_AMOUNT.fullmatch(amount)+ or not isinstance(model, str)+ or len(model) > 255+ or not isinstance(provider, str)+ or len(provider) > 255+ ):+ return None+ return GatewayRequestCost(model=model, provider=provider, cost_microusd=int(Decimal(amount) * 1_000_000))+ except (aiohttp.ClientError, TimeoutError, ValueError, TypeError):+ logger.warning("gateway_usage.lookup_failed")+ return Nonediff --git a/posthog/temporal/tests/ai/test_module_integrity.py b/posthog/temporal/tests/ai/test_module_integrity.pyindex 6e54180684eb..df98918167e0 100644--- a/posthog/temporal/tests/ai/test_module_integrity.py+++ b/posthog/temporal/tests/ai/test_module_integrity.py@@ -91,6 +91,7 @@ class TestSignalsProductModuleIntegrity:def test_workflows_remain_unchanged(self):"""Ensure all expected signals product workflows are present."""expected_workflows = [+ "UpdateSignalSpendWorkflow","GenerateScoutRubricsWorkflow","BackfillErrorTrackingWorkflow","TeamSignalGroupingWorkflow",@@ -125,6 +126,9 @@ class TestSignalsProductModuleIntegrity:def test_activities_remain_unchanged(self):"""Ensure all expected signals product activities are present."""expected_activities = [+ "update_signal_spend_activity",+ "confirm_signal_spend_activity",+ "publish_report_spend_activity","generate_scout_rubrics_activity","fail_scout_rubrics_activity","dispatch_inbox_slack_notifications_activity",diff --git a/posthog/test/repo_invariants/setup_receivers_baseline.txt b/posthog/test/repo_invariants/setup_receivers_baseline.txtindex 9847e76dad43..934bef67c410 100644--- a/posthog/test/repo_invariants/setup_receivers_baseline.txt+++ b/posthog/test/repo_invariants/setup_receivers_baseline.txt@@ -246,6 +246,8 @@ post_save:products.signals.backend.receivers.sync_report_latest_actionability_onpost_save:products.signals.backend.receivers.sync_suggested_reviewer_index_on_savepost_save:products.signals.backend.receivers.sync_task_run_pr_to_assignmentspost_save:products.signals.backend.receivers.tombstone_report_embedding_on_delete+post_save:products.signals.backend.spend_receivers.scout_run_created+post_save:products.signals.backend.spend_receivers.task_run_createdpost_save:products.slack_app.backend.signals.invalidate_repo_list_on_user_github_changepost_save:products.slack_app.backend.signals.onboard_slack_inbox_on_installpost_save:products.surveys.backend.models.survey_changeddiff --git a/products/signals/backend/apps.py b/products/signals/backend/apps.pyindex b69a6065b290..d4d111d4f50a 100644--- a/products/signals/backend/apps.py+++ b/products/signals/backend/apps.py@@ -20,9 +20,11 @@ class SignalsConfig(AppConfig):from . import (activity_logging, # noqa: F401receivers, # noqa: F401+ spend_receivers,)receivers.connect_task_run_assignment_sync()+ spend_receivers.connect_spend_receivers()self._register_signal_emission_gate()self._register_scout_skill_archive_guard()self._register_scout_skill_rename_hook()diff --git a/products/signals/backend/emission/direct_gate.py b/products/signals/backend/emission/direct_gate.pyindex 5b7282f7d6f7..3a2c051e7159 100644--- a/products/signals/backend/emission/direct_gate.py+++ b/products/signals/backend/emission/direct_gate.py@@ -78,6 +78,7 @@ async def steering_filters_signal(description: str,weight: float,extra: dict[str, Any],+ signal_id: str | None = None,) -> bool:"""Whether this team's steering says to drop the signal.@@ -102,6 +103,7 @@ async def steering_filters_signal()output = SignalEmitterOutput(+ signal_id=signal_id,source_product=source_product,source_type=source_type,source_id=source_id,diff --git a/products/signals/backend/emission/pipeline.py b/products/signals/backend/emission/pipeline.pyindex afa911a0dca8..4d148c11edb0 100644--- a/products/signals/backend/emission/pipeline.py+++ b/products/signals/backend/emission/pipeline.py@@ -5,6 +5,7 @@ import asyncioimport dataclassesfrom datetime import datetimefrom typing import Any+from uuid import uuid4from django.utils import timezone@@ -29,7 +30,9 @@ from products.signals.backend.emission.registry import ()from products.signals.backend.emission.steering import SourceSteering, apply_steering, steering_from_configfrom products.signals.backend.facade.api import emit_signal+from products.signals.backend.llm_spend import generate_with_spendfrom products.signals.backend.models import SignalEmissionRecord+from products.signals.backend.spend import signal_id_forfrom products.signals.backend.system_one_decision import run_model_decisionfrom products.signals.backend.system_one_prompts import SystemOnePrompt, bundled_prompt, current_promptfrom products.signals.backend.temporal import metrics@@ -186,7 +189,7 @@ def build_emitter_outputs(output,extra={k: v.isoformat() if isinstance(v, datetime) else v for k, v in output.extra.items()},)- outputs.append(output)+ outputs.append(dataclasses.replace(output, signal_id=output.signal_id or str(uuid4())))return outputs, error_count@@ -198,8 +201,12 @@ async def _summarize_description(threshold: int,gateway_mode: bool | None = None,) -> SignalEmitterOutput:+ gateway = resolve_ai_gateway_config() if gateway_mode is not False else Nonemessages: list[MessageParam] = [- {"role": "user", "content": summarization_prompt.format(description=output.description, max_length=threshold)}+ {+ "role": "user",+ "content": summarization_prompt.format(description=output.description, max_length=threshold),+ }]extra_headers = _signals_extra_headers(output, stage="summarization", gateway_mode=gateway_mode, team_id=team_id)for attempt in range(LLM_MAX_ATTEMPTS):@@ -207,7 +214,7 @@ async def _summarize_description(await asyncio.sleep(LLM_RETRY_INITIAL_DELAY_SECONDS * (LLM_RETRY_BACKOFF_COEFFICIENT ** (attempt - 1)))summary = ""try:- response = await asyncio.wait_for(+ generation = asyncio.wait_for(client.messages.create(model=LLM_MODEL,messages=messages,@@ -218,6 +225,10 @@ async def _summarize_description(),timeout=LLM_CALL_TIMEOUT_SECONDS,)+ priced = await generate_with_spend(+ generation, gateway=gateway, team_id=team_id, signal_id=output.signal_id, stage="summarization"+ )+ response = priced.responsesummary = _extract_text(response).strip()if response.stop_reason == "max_tokens":raise ValueError("LLM summary response was truncated due to token limit")@@ -337,6 +348,7 @@ async def check_actionability(Shared with the direct-source gate in `direct_gate.py`, which judges a single signal that neverentered this batch pipeline."""+ gateway = resolve_ai_gateway_config() if gateway_mode is not False else Nonedescription = output.description# Steering rules often reference metadata (labels, state, priority) that emitters keep in `extra`# rather than in the description, so the steered gate sees all of it. An unsteered gate sees only@@ -372,7 +384,7 @@ async def check_actionability(if attempt > 0:await asyncio.sleep(LLM_RETRY_INITIAL_DELAY_SECONDS * (LLM_RETRY_BACKOFF_COEFFICIENT ** (attempt - 1)))try:- response = await asyncio.wait_for(+ generation = asyncio.wait_for(client.messages.create(model=LLM_MODEL,messages=[{"role": "user", "content": prompt}],@@ -383,6 +395,10 @@ async def check_actionability(),timeout=LLM_CALL_TIMEOUT_SECONDS,)+ priced = await generate_with_spend(+ generation, gateway=gateway, team_id=team_id, signal_id=output.signal_id, stage="actionability"+ )+ response = priced.responseresponse_text = _extract_text(response).strip().upper()return "NOT_ACTION" not in response_textexcept Exception as e:@@ -556,6 +572,7 @@ async def _emit_signals()output = without_extraawait emit_signal(+ signal_id=output.signal_id,team=team,source_product=output.source_product,source_type=output.source_type,@@ -624,6 +641,22 @@ async def run_signal_pipeline(emitter=config.emitter,unloggable_fields=config.unloggable_fields,)+ emission_run_id = activity.info().workflow_run_id if activity.in_activity() else None+ if config.record_processed_outputs or emission_run_id is not None:+ outputs = [+ dataclasses.replace(+ output,+ signal_id=signal_id_for(+ team_id=team.id,+ source_product=output.source_product,+ source_type=output.source_type,+ idempotency_key=output.source_id+ if config.record_processed_outputs+ else f"{emission_run_id}:{activity.info().activity_id}:{output.source_id}",+ ),+ )+ for output in outputs+ ]# Only fail if every record raised — emitters may return None as a benign skip,# so a mix of skips and errors should fall through to the no_actionable_records path.if error_count == len(records):diff --git a/products/signals/backend/emission/registry.py b/products/signals/backend/emission/registry.pyindex 9e87737f109c..9cd8a2278b6b 100644--- a/products/signals/backend/emission/registry.py+++ b/products/signals/backend/emission/registry.py@@ -25,6 +25,7 @@ class SignalEmitterOutput:description: strweight: floatextra: dict[str, Any]+ signal_id: str | None = None# Type for signal emitter functions (None if the source has not enough meaningful data)diff --git a/products/signals/backend/emission/tests/test_direct_gate.py b/products/signals/backend/emission/tests/test_direct_gate.pyindex e2e02e167d7a..4b2e5b8f7f42 100644--- a/products/signals/backend/emission/tests/test_direct_gate.py+++ b/products/signals/backend/emission/tests/test_direct_gate.py@@ -21,6 +21,7 @@ def _make_llm_response(verdict: str) -> MagicMock:response = MagicMock()response.content = [block]response.stop_reason = "end_turn"+ response._request_id = Nonereturn responsediff --git a/products/signals/backend/emission/tests/test_emit_signals.py b/products/signals/backend/emission/tests/test_emit_signals.pyindex 65949ecf362d..805b5e192209 100644--- a/products/signals/backend/emission/tests/test_emit_signals.py+++ b/products/signals/backend/emission/tests/test_emit_signals.py@@ -1,6 +1,7 @@import jsonimport uuidfrom collections.abc import Sequence+from dataclasses import replacefrom datetime import UTC, datetimefrom typing import Any@@ -72,6 +73,7 @@ def _make_llm_response(content: str | None, stop_reason: str = "end_turn") -> Mablock.text = contentresponse.content = [block]response.stop_reason = stop_reason+ response._request_id = Nonereturn response@@ -365,6 +367,33 @@ class TestRunSignalPipelineEmitterFailures:assert result == {"status": "success", "reason": "no_actionable_records", "signals_emitted": 0}+class TestEmissionRetryIdentity:+ @pytest.mark.asyncio+ async def test_activity_retries_keep_signal_id_but_later_imports_do_not(self):+ config = _make_config(record_processed_outputs=False)+ team = MagicMock(id=1)+ with (+ patch(f"{PIPELINE_MODULE_PATH}.activity") as temporal_activity,+ patch(f"{PIPELINE_MODULE_PATH}.emit_signal", new_callable=AsyncMock) as emit,+ patch(f"{PIPELINE_MODULE_PATH}.posthoganalytics.capture"),+ ):+ temporal_activity.in_activity.return_value = True+ info = temporal_activity.info.return_value+ info.workflow_run_id = "first-import"+ info.activity_id = "emit-1"+ emit.side_effect = RuntimeError("dispatch failed")+ with pytest.raises(RuntimeError, match="All 1 signal emissions failed"):+ await run_signal_pipeline(team=team, config=config, records=[{"id": "record-1"}], extra={})+ first = emit.call_args.kwargs["signal_id"]+ emit.side_effect = None+ info.attempt = 2+ await run_signal_pipeline(team=team, config=config, records=[{"id": "record-1"}], extra={})+ assert emit.call_args.kwargs["signal_id"] == first+ info.workflow_run_id = "next-import"+ await run_signal_pipeline(team=team, config=config, records=[{"id": "record-1"}], extra={})+ assert emit.call_args.kwargs["signal_id"] != first++class TestCheckActionability:@pytest.mark.asyncio@pytest.mark.parametrize(@@ -674,7 +703,7 @@ class TestSummarizeLongDescriptions:class TestEmitSignals:@pytest.mark.asyncioasync def test_passes_correct_args_to_emit_signal(self):- output = _make_output(source_id="42", description="bug report")+ output = replace(_make_output(source_id="42", description="bug report"), signal_id=str(uuid.uuid4()))team = MagicMock()with (@@ -693,6 +722,7 @@ class TestEmitSignals:weight=0.5,extra={},idempotency_key=None,+ signal_id=output.signal_id,)@pytest.mark.asynciodiff --git a/products/signals/backend/emission/tests/test_google_search_console_opportunities.py b/products/signals/backend/emission/tests/test_google_search_console_opportunities.pyindex 5a4c99bb15ee..d52655faf883 100644--- a/products/signals/backend/emission/tests/test_google_search_console_opportunities.py+++ b/products/signals/backend/emission/tests/test_google_search_console_opportunities.py@@ -125,7 +125,9 @@ class TestGoogleSearchConsoleEmitter:variant = SIGNAL_VARIANT_LOOKUP.get((output.source_product, output.source_type))assert variant is not None# extra="forbid" + strict types on the contract catches any drift between emitter and schema.- variant.model_validate(dataclasses.asdict(output))+ data = dataclasses.asdict(output)+ data.pop("signal_id")+ variant.model_validate(data)class TestGoogleSearchConsoleConfig:diff --git a/products/signals/backend/emission/tests/test_schema_validation.py b/products/signals/backend/emission/tests/test_schema_validation.pyindex dc2f38aa4695..715f1d634bd3 100644--- a/products/signals/backend/emission/tests/test_schema_validation.py+++ b/products/signals/backend/emission/tests/test_schema_validation.py@@ -22,6 +22,7 @@ def _load_fixture(filename: str) -> list[dict]:def _validate_output(output):data = dataclasses.asdict(output)+ data.pop("signal_id")variant_type = SIGNAL_VARIANT_LOOKUP.get((output.source_product, output.source_type))if variant_type is None:raise ValueError(f"No SignalInput variant for ({output.source_product}, {output.source_type})")diff --git a/products/signals/backend/facade/api.py b/products/signals/backend/facade/api.pyindex c1c790ca1220..ca7465ba77d1 100644--- a/products/signals/backend/facade/api.py+++ b/products/signals/backend/facade/api.py@@ -102,6 +102,7 @@ from products.signals.backend.scout_harness.workflow_runs import (start_workflow_scout_run as start_workflow_scout_run,)from products.signals.backend.signal_metadata import SourceSliceSignalStats, fetch_signal_stats_for_source_slice+from products.signals.backend.spend import signal_id_for# Re-exported for external products (tasks presentation catches it around facade create_task).from products.signals.backend.task_run_artefacts import ReportTaskCapExceeded as ReportTaskCapExceeded@@ -748,6 +749,7 @@ async def emit_signal(extra: dict | None = None,remediation: SignalRemediation | None = None,idempotency_key: str | None = None,+ signal_id: str | None = None,) -> None:"""Emit a signal for grouping and potential report generation, fire-and-forget.@@ -862,6 +864,10 @@ async def emit_signal(source_id=source_id,)+ signal_id = signal_id or signal_id_for(+ team_id=team.id, source_product=source_product, source_type=source_type, idempotency_key=idempotency_key+ )+# Below the started event on purpose: a filtered signal then has a top-of-funnel event to be# counted against, so a steering drop reads apart from a dispatch failure rather than as one.if (source_product, source_type) in DIRECT_STEERABLE_SOURCES:@@ -870,6 +876,7 @@ async def emit_signal(from products.signals.backend.emission.direct_gate import steering_filters_signal # noqa: PLC0415if await steering_filters_signal(+ signal_id=signal_id,team=team,organization=organization,source_product=source_product,@@ -884,6 +891,7 @@ async def emit_signal(client = await async_connect()signal_input = EmitSignalInputs(+ signal_id=signal_id,team_id=team.id,source_product=source_product,source_type=source_type,diff --git a/products/signals/backend/facade/spend.py b/products/signals/backend/facade/spend.pynew file mode 100644index 000000000000..714766d22d31--- /dev/null+++ b/products/signals/backend/facade/spend.py@@ -0,0 +1 @@+from products.signals.backend.spend import complete_task_spend as complete_task_spenddiff --git a/products/signals/backend/llm_spend.py b/products/signals/backend/llm_spend.pynew file mode 100644index 000000000000..390b15db9149--- /dev/null+++ b/products/signals/backend/llm_spend.py@@ -0,0 +1,120 @@+import asyncio+from collections.abc import Awaitable+from datetime import UTC, datetime+from decimal import Decimal++import structlog+from anthropic import APIResponseValidationError+from anthropic.types import Message+from temporalio import activity++from posthog.dataclasses import frozen+from posthog.llm.gateway_client import AIGatewayConfig+from posthog.llm.gateway_usage import GatewayRequestCost, fetch_gateway_cost+from posthog.sync import database_sync_to_async++from products.signals.backend.pricing import cost_to_spend+from products.signals.backend.spend import record_llm_spend++logger = structlog.get_logger(__name__)+USAGE_WAIT_SECONDS = 10.0+++@frozen+class PricedGeneration:+ response: Message+ spend: Decimal | None+++def _usage_wait_seconds() -> float:+ budget = USAGE_WAIT_SECONDS+ if activity.in_activity():+ info = activity.info()+ now = datetime.now(UTC)+ for started, timeout in (+ (info.started_time, info.start_to_close_timeout),+ (info.scheduled_time, info.schedule_to_close_timeout),+ ):+ if timeout is not None:+ budget = min(budget, (started + timeout - now).total_seconds() - 1)+ return max(0, budget)+++async def _wait_for_gateway_cost(request_id: str, gateway: AIGatewayConfig) -> GatewayRequestCost:+ delay = 0.01+ while True:+ cost = await fetch_gateway_cost(request_id, base_url=gateway.url, api_key=gateway.api_key)+ if cost is not None:+ return cost+ if activity.in_activity():+ activity.heartbeat()+ await asyncio.sleep(delay)+ delay = min(delay * 2, 1.0)+++async def _settle_generation(+ request_id: str | None,+ *,+ gateway: AIGatewayConfig | None,+ team_id: int | None,+ signal_id: str | None,+ stage: str,+) -> Decimal | None:+ cost_microusd = None+ try:+ if gateway is None or not request_id or team_id is None or signal_id is None:+ return None+ cost = await asyncio.wait_for(_wait_for_gateway_cost(request_id, gateway), timeout=_usage_wait_seconds())+ cost_microusd = cost.cost_microusd+ return cost_to_spend(cost_microusd)+ except TimeoutError:+ logger.warning("signals.spend.usage_wait_expired", stage=stage, team_id=team_id, signal_id=signal_id)+ return None+ except Exception:+ logger.exception("signals.spend.accounting_failed", stage=stage, team_id=team_id, signal_id=signal_id)+ return None+ finally:+ await database_sync_to_async(record_llm_spend)(+ request_id,+ token_cost_microusd=cost_microusd,+ team_id=team_id,+ signal_id=signal_id,+ stage=stage,+ )+++async def generate_with_spend(+ generation: Awaitable[Message],+ *,+ gateway: AIGatewayConfig | None,+ team_id: int | None,+ signal_id: str | None,+ stage: str,+) -> PricedGeneration:+ """Generate once, then wait for its gateway usage. Spend is in USD cents.++ Accounting waits up to ten seconds within the calling activity, leaving time+ to return before its deadline. Missing usage preserves the completed response+ and marks the stage unaccounted.+ """+ try:+ response = await generation+ except (Exception, asyncio.CancelledError) as error:+ request_id = (+ error.response.headers.get("x-request-id") if isinstance(error, APIResponseValidationError) else None+ )+ if gateway is not None and request_id:+ await _settle_generation(request_id, gateway=gateway, team_id=team_id, signal_id=signal_id, stage=stage)+ else:+ await database_sync_to_async(record_llm_spend)(+ None, token_cost_microusd=None, team_id=team_id, signal_id=signal_id, stage=stage+ )+ raise+ spend = await _settle_generation(+ getattr(response, "_request_id", None) if gateway is not None else None,+ gateway=gateway,+ team_id=team_id,+ signal_id=signal_id,+ stage=stage,+ )+ return PricedGeneration(response=response, spend=spend)diff --git a/products/signals/backend/migrations/0182_spend_tracking.py b/products/signals/backend/migrations/0182_spend_tracking.pynew file mode 100644index 000000000000..293bf4a26fec--- /dev/null+++ b/products/signals/backend/migrations/0182_spend_tracking.py@@ -0,0 +1,104 @@+# Generated by Django 5.2.17 on 2026-10-02 14:32++import django.db.models.deletion+from django.db import migrations, models++import posthog.uuidt+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1391_organization_provisioning"),+ ("signals", "0181_signalreportpullrequest_participant_logins"),+ ]++ operations = [+ migrations.AddField(+ model_name="signalreport",+ name="pending_triggering_signal_id",+ field=models.UUIDField(blank=True, null=True),+ ),+ migrations.AddField(+ model_name="signalreport",+ name="researching_signal_count",+ field=models.IntegerField(blank=True, null=True),+ ),+ migrations.AddField(+ model_name="signalreport",+ name="triggering_signal_id",+ field=models.UUIDField(blank=True, null=True),+ ),+ migrations.AddField(+ model_name="signalscoutrun",+ name="total_spend",+ field=models.DecimalField(blank=True, decimal_places=4, max_digits=20, null=True),+ ),+ migrations.CreateModel(+ name="SignalSpend",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.uuidt.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("signal_id", models.UUIDField(blank=True, null=True)),+ ("task_id", models.UUIDField(blank=True, db_index=True, null=True)),+ ("source_id", models.CharField(max_length=255)),+ ("is_task", models.BooleanField(default=False)),+ ("token_cost_microusd", models.BigIntegerField(blank=True, null=True)),+ ("updated_at", models.DateTimeField(auto_now=True)),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ (+ "scout_run",+ models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.CASCADE,+ to="signals.signalscoutrun",+ ),+ ),+ (+ "team",+ models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="+",+ to="posthog.team",+ ),+ ),+ ],+ options={+ "indexes": [+ models.Index(fields=["team", "signal_id"], name="signals_spend_signal_idx"),+ ],+ "constraints": [+ models.UniqueConstraint(+ fields=("team", "source_id", "is_task"),+ name="signals_spend_source_unique",+ ),+ models.CheckConstraint(+ condition=models.Q(+ models.Q(+ ("scout_run__isnull", True),+ ("signal_id__isnull", False),+ ),+ models.Q(+ ("scout_run__isnull", False),+ ("signal_id__isnull", True),+ ),+ _connector="OR",+ ),+ name="signals_spend_one_owner",+ ),+ models.CheckConstraint(+ condition=models.Q(("token_cost_microusd__gte", 0)),+ name="signals_spend_nonnegative",+ ),+ ],+ },+ ),+ ]diff --git a/products/signals/backend/migrations/0183_spend_accounting_failures.py b/products/signals/backend/migrations/0183_spend_accounting_failures.pynew file mode 100644index 000000000000..cd8a23b6490f--- /dev/null+++ b/products/signals/backend/migrations/0183_spend_accounting_failures.py@@ -0,0 +1,20 @@+# Generated by Django 5.2.17 on 2026-10-06 15:02++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [("signals", "0182_spend_tracking")]++ operations = [+ migrations.AddField(+ model_name="signalspend",+ name="accounting_failed",+ field=models.BooleanField(default=False),+ ),+ migrations.AddField(+ model_name="signalspend",+ name="stage",+ field=models.CharField(default="unknown", max_length=100),+ ),+ ]diff --git a/products/signals/backend/migrations/max_migration.txt b/products/signals/backend/migrations/max_migration.txtindex a985165169dc..0c0d24b36c9d 100644--- a/products/signals/backend/migrations/max_migration.txt+++ b/products/signals/backend/migrations/max_migration.txt@@ -1 +1 @@-0181_signalreportpullrequest_participant_logins+0183_spend_accounting_failuresdiff --git a/products/signals/backend/models.py b/products/signals/backend/models.pyindex 233ddd2a0a29..f4ce7aeb470b 100644--- a/products/signals/backend/models.py+++ b/products/signals/backend/models.py@@ -324,6 +324,9 @@ class SignalReport(UUIDModel):POSTHOG_SYSTEM = "posthog_system", "PostHog system"team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+")+ triggering_signal_id = models.UUIDField(null=True, blank=True)+ pending_triggering_signal_id = models.UUIDField(null=True, blank=True)+ researching_signal_count = models.IntegerField(null=True, blank=True)status = models.CharField(max_length=20, choices=Status, default=Status.POTENTIAL)# System billing exemption: non-null means this report's implementation PRs must never be# charged (PostHog-system origins, e.g. health-check scout findings). Prospective-only —@@ -3196,6 +3199,7 @@ class SignalScoutRun(TeamScopedRootMixin, UUIDModel):# the note a person typed when triggering the run by hand, so read it as prose, not a dimension.# Nullable with a `{}` db_default so the AddField stays non-blocking on the populated table.metadata = models.JSONField(null=True, blank=True, default=dict, db_default={})+ total_spend = models.DecimalField(max_digits=20, decimal_places=4, null=True, blank=True)# Keep private trial documents separate from metadata inspected by ordinary scout history queries.trial_state = models.JSONField(null=True, blank=True)created_at = models.DateTimeField(auto_now_add=True)@@ -3666,3 +3670,35 @@ class SignalScoutBackgroundBand(TeamScopedRootMixin, UUIDModel):verbose_name = "Signal scout background band"verbose_name_plural = "Signal scout background bands"default_manager_name = "all_teams"+++class SignalSpend(TeamScopedRootMixin, UUIDModel):+ """One absolute cost observation per gateway request or task run."""++ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False, related_name="+")+ signal_id = models.UUIDField(null=True, blank=True)+ scout_run = models.ForeignKey(SignalScoutRun, on_delete=models.CASCADE, null=True, blank=True)+ task_id = models.UUIDField(null=True, blank=True, db_index=True)+ source_id = models.CharField(max_length=255)+ stage = models.CharField(max_length=100, default="unknown")+ accounting_failed = models.BooleanField(default=False)+ is_task = models.BooleanField(default=False)+ token_cost_microusd = models.BigIntegerField(null=True, blank=True)+ updated_at = models.DateTimeField(auto_now=True)+ created_at = models.DateTimeField(auto_now_add=True)++ class Meta:+ constraints = [+ models.UniqueConstraint(fields=["team", "source_id", "is_task"], name="signals_spend_source_unique"),+ models.CheckConstraint(+ condition=(+ models.Q(signal_id__isnull=False, scout_run__isnull=True)+ | models.Q(signal_id__isnull=True, scout_run__isnull=False)+ ),+ name="signals_spend_one_owner",+ ),+ models.CheckConstraint(condition=models.Q(token_cost_microusd__gte=0), name="signals_spend_nonnegative"),+ ]+ indexes = [+ models.Index(fields=["team", "signal_id"], name="signals_spend_signal_idx"),+ ]diff --git a/products/signals/backend/pricing.py b/products/signals/backend/pricing.pynew file mode 100644index 000000000000..6f764a69133f--- /dev/null+++ b/products/signals/backend/pricing.py@@ -0,0 +1,8 @@+from decimal import Decimal+++def cost_to_spend(token_cost_microusd: int, *, task_count: int = 0) -> Decimal:+ """Customer spend in USD cents: token cost plus four cents per task run."""+ if token_cost_microusd < 0 or task_count < 0:+ raise ValueError("Cost and task count must be nonnegative")+ return Decimal(token_cost_microusd) / 10_000 + Decimal(4) * task_countdiff --git a/products/signals/backend/scout_harness/serializers.py b/products/signals/backend/scout_harness/serializers.pyindex a739c1799dd1..5f6a7ccfa415 100644--- a/products/signals/backend/scout_harness/serializers.py+++ b/products/signals/backend/scout_harness/serializers.py@@ -187,6 +187,11 @@ class SignalScoutRunSummarySerializer(serializers.Serializer):Status and timestamps flow from the linked `tasks.TaskRun`."""+ total_spend = serializers.FloatField(+ read_only=True,+ allow_null=True,+ help_text="Accounted customer spend in USD cents, including fractional cents. May be partial; null for untracked runs.",+ )run_id = serializers.CharField(help_text="UUID of the bridge row.")skill_name = serializers.CharField(help_text="Canonical skill name the run executed (e.g. `signals-scout-general`)."diff --git a/products/signals/backend/scout_harness/tools/runs.py b/products/signals/backend/scout_harness/tools/runs.pyindex f51afa8cedd0..d397b92badb2 100644--- a/products/signals/backend/scout_harness/tools/runs.py+++ b/products/signals/backend/scout_harness/tools/runs.py@@ -58,6 +58,7 @@ RUN_SUMMARY_FIELDS = ("emitted_report_ids","edited_report_ids","metadata",+ "total_spend","task_run__id","task_run__task_id","task_run__status",@@ -86,7 +87,7 @@ CRON_GAP_SAMPLES = 4# Part of every `runs_version`. Bump it when `_to_summary` changes its output, so a client that# holds a body in the old shape fetches the new one.-RUNS_VERSION_SCHEMA = 1+RUNS_VERSION_SCHEMA = 2# Runaway guard on the fan-out of the per-scout probe. Deliberately a limit on *scouts* rather than# on rows: capping rows after the per-scout ranking would drop the slowest scouts' history, which is@@ -159,6 +160,7 @@ class RunSummary:# harness-computed run flags written at finalize. Empty for default-model runs that never# finalized, and for rows predating the column.metadata: dict[str, Any] = field(default_factory=dict)+ total_spend: float | None = Nonedef as_dict(self) -> dict[str, Any]:return asdict(self)@@ -203,6 +205,7 @@ class RunDetail:# harness-computed run flags written at finalize. Empty for default-model runs that never# finalized, and for rows predating the column.metadata: dict[str, Any] = field(default_factory=dict)+ total_spend: float | None = Nonedef as_dict(self) -> dict[str, Any]:return asdict(self)@@ -657,6 +660,7 @@ def _to_summary(row: SignalScoutRun, *, team_id: int) -> RunSummary:error=error,failure_reason=failure_reason,metadata=metadata,+ total_spend=float(row.total_spend) if row.total_spend is not None else None,)diff --git a/products/signals/backend/scout_report/persistence.py b/products/signals/backend/scout_report/persistence.pyindex 415050ddbe7b..2c548bb7d810 100644--- a/products/signals/backend/scout_report/persistence.py+++ b/products/signals/backend/scout_report/persistence.py@@ -36,6 +36,7 @@ from django.db import IntegrityError, transactionfrom django.db.models import Ffrom django.utils import timezone+from asgiref.sync import async_to_syncfrom pydantic import JsonValue, TypeAdapter, ValidationErrorfrom rest_framework.renderers import JSONRenderer@@ -78,6 +79,7 @@ from products.signals.backend.report_generation.select_repo import RepoSelectionfrom products.signals.backend.report_metrics import ReportMetric, metric_batch_errorfrom products.signals.backend.report_prompts import normalize_suggested_prompts, suggested_prompts_batch_errorfrom products.signals.backend.scout_harness.tools.emit import SCOUT_SIGNAL_WEIGHT, SOURCE_PRODUCT, SOURCE_TYPE+from products.signals.backend.spend import SignalMetadataChange, submit_signal_metadata_updatesfrom products.signals.backend.supersession import NO_IMPLEMENTATION_CONTEXT, research_implementation_contextif TYPE_CHECKING:@@ -248,6 +250,7 @@ def create_scout_report(title=title,summary=summary,scout_idempotency_key=idempotency_key,+ triggering_signal_id=document_ids[0],signal_count=len(signals),total_weight=total_weight,charts=[chart.model_dump(mode="json") for chart in charts],@@ -1424,18 +1427,10 @@ def soft_delete_scout_signal(_validate_report_id(report_id)if not SignalReport.objects.filter(team_id=team_id, id=report_id).exists():raise InvalidScoutReportError(f"report {report_id} not found for team {team_id}")- metadata = _signal_metadata(report_id=report_id, source_id=source_id, weight=weight, extra=extra)- metadata["deleted"] = True- emit_embedding_request(- content=description,+ async_to_sync(submit_signal_metadata_updates)(team_id=team_id,- product=_EMBEDDING_PRODUCT,- document_type=_EMBEDDING_DOCUMENT_TYPE,- rendering=_EMBEDDING_RENDERING,- document_id=document_id,- models=[m.value for m in EmbeddingModelName],- timestamp=timestamp,- metadata=metadata,+ signal_ids=[document_id],+ change=SignalMetadataChange(deleted=True, expected_report_id=report_id),)diff --git a/products/signals/backend/serializers.py b/products/signals/backend/serializers.pyindex 6d52f1c28048..f0e2e2a59266 100644--- a/products/signals/backend/serializers.py+++ b/products/signals/backend/serializers.py@@ -2109,6 +2109,17 @@ class SignalMatchMetadataField(serializers.JSONField):class SignalNodeSerializer(serializers.Serializer):+ total_spend = serializers.FloatField(+ read_only=True,+ allow_null=True,+ help_text="Accounted customer spend in USD cents, including fractional cents. May be partial; null for untracked signals.",+ )+ spend_accounting_failed_stages = serializers.ListField(+ child=serializers.CharField(),+ read_only=True,+ default=list,+ help_text="Pipeline stages with generations whose spend could not be accounted for. Cleared when accounting recovers.",+ )signal_id = serializers.CharField(help_text="ClickHouse document id of the signal.")content = serializers.CharField(help_text="The signal's human-readable description.")source_product = serializers.ChoiceField(diff --git a/products/signals/backend/signal_metadata.py b/products/signals/backend/signal_metadata.pyindex a30850d2cbc5..9ea263a2172d 100644--- a/products/signals/backend/signal_metadata.py+++ b/products/signals/backend/signal_metadata.py@@ -505,6 +505,8 @@ def fetch_signals_for_report_sync(team: Team, report_id: str, newest: int | None"timestamp": timestamp,"extra": metadata.get("extra", {}),"match_metadata": metadata.get("match_metadata"),+ "total_spend": metadata.get("total_spend"),+ "spend_accounting_failed_stages": metadata.get("spend_accounting_failed_stages", []),})diff --git a/products/signals/backend/spend.py b/products/signals/backend/spend.pynew file mode 100644index 000000000000..5482fe8410db--- /dev/null+++ b/products/signals/backend/spend.py@@ -0,0 +1,349 @@+import asyncio+from dataclasses import field+from datetime import timedelta+from uuid import NAMESPACE_URL, UUID, uuid4, uuid5++from django.conf import settings+from django.contrib.postgres.aggregates import ArrayAgg+from django.db import transaction+from django.db.models import Count, Q, Sum+from django.utils import timezone++import structlog+from asgiref.sync import async_to_sync++from posthog.dataclasses import frozen+from posthog.sync import database_sync_to_async++from products.signals.backend.models import (+ SignalReport,+ SignalReportArtefact,+ SignalReportTask,+ SignalScoutRun,+ SignalSpend,+)+from products.signals.backend.pricing import cost_to_spend++logger = structlog.get_logger(__name__)+++@frozen+class SignalSpendSummary:+ total_spend: float+ failed_stages: list[str]+++def signal_id_for(*, team_id: int, source_product: str, source_type: str, idempotency_key: str | None = None) -> str:+ return (+ str(uuid5(NAMESPACE_URL, f"signals:{team_id}:{source_product}:{source_type}:{idempotency_key}"))+ if idempotency_key+ else str(uuid4())+ )+++def report_triggering_signal(*, team_id: int, report_id: str) -> str | None:+ with transaction.atomic():+ report = (+ SignalReport.objects.filter(team_id=team_id, id=report_id).only("triggering_signal_id", "team_id").first()+ )+ if report is None:+ return None+ if report.triggering_signal_id is not None:+ return str(report.triggering_signal_id)++ from products.signals.backend.signal_metadata import (+ fetch_signals_for_report_sync, # noqa: PLC0415 — keeps HogQL off Django startup+ )++ signals = fetch_signals_for_report_sync(report.team, report_id, newest=1)+ if not signals:+ return None+ with transaction.atomic():+ reports = SignalReport.objects.filter(team_id=team_id, id=report_id)+ reports.filter(triggering_signal_id__isnull=True).update(triggering_signal_id=signals[0]["signal_id"])+ signal_id = reports.values_list("triggering_signal_id", flat=True).get()+ return str(signal_id)+++@frozen+class SignalMetadataChange:+ report_id: str | None = None+ deleted: bool = False+ clear_content: bool = False+ expected_report_id: str | None = None+++@frozen+class SignalSpendUpdate:+ team_id: int+ signal_id: str+ changes: list[SignalMetadataChange] = field(default_factory=list)+++@frozen+class SignalSpendPublication:+ signal: SignalSpendUpdate+ summary: SignalSpendSummary+ versions: dict[str, int]+++async def submit_signal_metadata_updates(+ *,+ team_id: int,+ signal_ids: list[str],+ change: SignalMetadataChange | None = None,+ wait_for_completion: bool = False,+) -> None:+ from temporalio.common import WorkflowIDReusePolicy # noqa: PLC0415 — keeps Temporal off Django startup++ from posthog.temporal.common.client import async_connect # noqa: PLC0415 — keeps Temporal off Django startup++ if not signal_ids:+ return+ client = await asyncio.wait_for(async_connect(), timeout=5)+ for start in range(0, len(signal_ids), 20):+ handles = await asyncio.gather(+ *(+ client.start_workflow(+ "update-signal-spend",+ SignalSpendUpdate(team_id=team_id, signal_id=signal_id),+ id=f"signal-spend-{team_id}-{signal_id}",+ task_queue=settings.VIDEO_EXPORT_TASK_QUEUE,+ id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,+ start_signal="update_metadata" if change else "refresh",+ start_signal_args=[change] if change else [],+ execution_timeout=timedelta(minutes=15),+ rpc_timeout=timedelta(seconds=5),+ )+ for signal_id in signal_ids[start : start + 20]+ )+ )+ if wait_for_completion:+ await asyncio.gather(*(handle.result() for handle in handles))+++async def publish_signal_spend(*, team_id: int, signal_id: str) -> None:+ try:+ await submit_signal_metadata_updates(team_id=team_id, signal_ids=[signal_id], wait_for_completion=True)+ except Exception:+ logger.exception(+ "signals.spend.accounting_failed", stage="persist_metadata", team_id=team_id, signal_id=signal_id+ )+++def record_llm_spend(+ request_id: str | None,+ *,+ token_cost_microusd: int | None,+ team_id: int | None,+ stage: str,+ signal_id: str | None = None,+) -> None:+ if team_id is None or signal_id is None:+ return+ try:+ with transaction.atomic():+ spend, created = SignalSpend.objects.for_team(team_id).get_or_create(+ team_id=team_id,+ source_id=request_id or f"unknown-{uuid4()}",+ is_task=False,+ defaults={+ "signal_id": signal_id,+ "stage": stage,+ "token_cost_microusd": token_cost_microusd,+ "accounting_failed": token_cost_microusd is None,+ },+ )+ if not created and token_cost_microusd is not None:+ SignalSpend.objects.for_team(team_id).filter(id=spend.id).update(+ token_cost_microusd=token_cost_microusd,+ accounting_failed=False,+ updated_at=timezone.now(),+ )+ if token_cost_microusd is None:+ logger.warning("signals.spend.generation_unaccounted", stage=stage, team_id=team_id, signal_id=signal_id)+ except Exception:+ logger.exception(+ "signals.spend.accounting_failed", stage=stage, team_id=team_id, signal_id=signal_id, request_id=request_id+ )+++def signal_spend_summaries(*, team_id: int, signal_ids: list[str]) -> dict[str, SignalSpendSummary]:+ valid_ids = []+ for signal_id in signal_ids:+ try:+ valid_ids.append(UUID(signal_id))+ except ValueError:+ continue+ if not valid_ids:+ return {}+ try:+ with transaction.atomic():+ rows = (+ SignalSpend.objects.for_team(team_id)+ .filter(signal_id__in=valid_ids)+ .values("signal_id")+ .annotate(+ cost=Sum("token_cost_microusd"),+ tasks=Count("id", filter=Q(is_task=True)),+ failed_stages=ArrayAgg("stage", distinct=True, filter=Q(accounting_failed=True)),+ )+ )+ return {+ str(row["signal_id"]): SignalSpendSummary(+ total_spend=float(cost_to_spend(row["cost"] or 0, task_count=row["tasks"])),+ failed_stages=sorted(row["failed_stages"] or []),+ )+ for row in rows+ }+ except Exception:+ logger.exception("signals.spend.accounting_failed", stage="read_spend", team_id=team_id, signal_ids=signal_ids)+ return {}+++def signal_spend_totals(*, team_id: int, signal_ids: list[str]) -> dict[str, float]:+ return {+ signal_id: summary.total_spend+ for signal_id, summary in signal_spend_summaries(team_id=team_id, signal_ids=signal_ids).items()+ }+++def refresh_task_spend(*, spend_id: UUID, team_id: int) -> None:+ try:+ from products.tasks.backend.facade.billing import (+ get_task_run_token_usage, # noqa: PLC0415 — keeps task cost services off startup+ )++ with transaction.atomic():+ spend = SignalSpend.objects.for_team(team_id).select_for_update().get(id=spend_id)+ usage = get_task_run_token_usage(team_id=team_id, run_id=UUID(spend.source_id))+ if usage.cost_microusd is not None:+ spend.token_cost_microusd = usage.cost_microusd+ spend.accounting_failed = not usage.complete+ spend.save(update_fields=["token_cost_microusd", "accounting_failed", "updated_at"])+ if not usage.complete:+ logger.warning(+ "signals.spend.generation_unaccounted",+ stage=spend.stage,+ team_id=team_id,+ signal_id=str(spend.signal_id) if spend.signal_id else None,+ scout_run_id=str(spend.scout_run_id) if spend.scout_run_id else None,+ request_id=spend.source_id,+ )+ if spend.scout_run_id:+ scout_run = SignalScoutRun.objects.for_team(team_id).select_for_update().get(id=spend.scout_run_id)+ scout_run.total_spend = cost_to_spend(spend.token_cost_microusd or 0, task_count=1)+ scout_run.metadata = {+ **(scout_run.metadata or {}),+ "spend_accounting_failed_stages": [spend.stage] if spend.accounting_failed else [],+ }+ scout_run.save(update_fields=["total_spend", "metadata"])+ except Exception:+ logger.exception(+ "signals.spend.accounting_failed", stage="task_cost_update", team_id=team_id, spend_id=str(spend_id)+ )+++def record_task_spend(+ *,+ team_id: int,+ run_id: str,+ stage: str,+ signal_id: str | None = None,+ scout_run_id: str | None = None,+ task_id: str | None = None,+) -> None:+ if signal_id is None and scout_run_id is None:+ return+ if (signal_id is None) == (scout_run_id is None):+ raise ValueError("A task's spend must have exactly one owner")+ spend, _ = SignalSpend.objects.for_team(team_id).get_or_create(+ team_id=team_id,+ source_id=run_id,+ is_task=True,+ defaults={"signal_id": signal_id, "scout_run_id": scout_run_id, "task_id": task_id, "stage": stage},+ )+ refresh_task_spend(spend_id=spend.id, team_id=team_id)+++def _settle_task_spend(spend: SignalSpend) -> None:+ from products.tasks.backend.facade.billing import ( # noqa: PLC0415 — keeps task services off startup+ process_pending_gateway_usage,+ )++ try:+ process_pending_gateway_usage(run_id=UUID(spend.source_id), team_id=spend.team_id, limit=1000)+ refresh_task_spend(spend_id=spend.id, team_id=spend.team_id)+ except Exception:+ with transaction.atomic():+ SignalSpend.objects.for_team(spend.team_id).filter(id=spend.id).update(accounting_failed=True)+ logger.exception(+ "signals.spend.accounting_failed", stage=spend.stage, team_id=spend.team_id, source_id=spend.source_id+ )+++def settle_signal_task_spend(*, team_id: int, signal_id: str) -> None:+ for spend in SignalSpend.objects.for_team(team_id).filter(signal_id=signal_id, is_task=True):+ _settle_task_spend(spend)+++def _report_spend_signal_ids(*, team_id: int, report_id: str) -> list[str]:+ from products.tasks.backend.facade.api import ( # noqa: PLC0415 — keeps the task facade off startup+ TaskRunStatus,+ get_signal_report_implementation_runs,+ )++ report = SignalReport.objects.filter(team_id=team_id, id=report_id).first()+ if report is None or report.status == SignalReport.Status.IN_PROGRESS:+ return []+ task_ids = list(+ SignalReportTask.objects.filter(+ team_id=team_id, report_id=report_id, relationship="implementation"+ ).values_list("task_id", flat=True)+ )+ runs = get_signal_report_implementation_runs(team_id, report_id, task_ids)+ if any(run.status not in {TaskRunStatus.COMPLETED, TaskRunStatus.FAILED, TaskRunStatus.CANCELLED} for run in runs):+ return []+ task_ids.extend(+ SignalReportArtefact.objects.filter(team_id=team_id, report_id=report_id, task_id__isnull=False).values_list(+ "task_id", flat=True+ )+ )+ owners = set(+ SignalSpend.objects.for_team(team_id)+ .filter(task_id__in=task_ids, signal_id__isnull=False)+ .values_list("signal_id", flat=True)+ )+ if report.triggering_signal_id:+ owners.add(report.triggering_signal_id)+ return sorted(str(owner) for owner in owners)+++async def publish_report_spend(*, team_id: int, report_id: str) -> None:+ try:+ signal_ids = await database_sync_to_async(_report_spend_signal_ids)(team_id=team_id, report_id=report_id)+ for signal_id in signal_ids:+ await publish_signal_spend(team_id=team_id, signal_id=signal_id)+ except Exception:+ logger.exception(+ "signals.spend.accounting_failed", stage="report_completion", team_id=team_id, report_id=report_id+ )+++def complete_task_spend(*, team_id: int, run_id: str) -> None:+ try:+ spend = SignalSpend.objects.for_team(team_id).filter(source_id=run_id, is_task=True).first()+ if spend is None:+ return+ if spend.scout_run_id:+ _settle_task_spend(spend)+ else:+ refresh_task_spend(spend_id=spend.id, team_id=team_id)+ if spend.stage == "implementation" and spend.task_id:+ report_ids = SignalReportTask.objects.filter(+ team_id=team_id, task_id=spend.task_id, relationship="implementation"+ ).values_list("report_id", flat=True)+ for report_id in report_ids:+ async_to_sync(publish_report_spend)(team_id=team_id, report_id=str(report_id))+ except Exception:+ logger.exception("signals.spend.accounting_failed", stage="task_completion", team_id=team_id, run_id=run_id)diff --git a/products/signals/backend/spend_metadata.py b/products/signals/backend/spend_metadata.pynew file mode 100644index 000000000000..57375ff0ec7a--- /dev/null+++ b/products/signals/backend/spend_metadata.py@@ -0,0 +1,154 @@+import json+from dataclasses import replace+from datetime import UTC, datetime++from django.utils import timezone++from pydantic import JsonValue++from posthog.schema import EmbeddingModelName++from posthog.hogql import ast+from posthog.hogql.query import execute_hogql_query++from posthog.clickhouse.query_tagging import Feature, Product, tag_queries+from posthog.dataclasses import frozen+from posthog.kafka_client.routing import producer_scope+from posthog.kafka_client.topics import KAFKA_DOCUMENT_EMBEDDINGS_TOPIC+from posthog.models import Team++from products.signals.backend.models import SignalSpend+from products.signals.backend.signal_metadata import (+ SIGNAL_DOCUMENT_PRODUCT,+ SIGNAL_DOCUMENT_RENDERING,+ SIGNAL_DOCUMENT_TYPE,+ _signals_query_context,+)+from products.signals.backend.spend import (+ SignalMetadataChange,+ SignalSpendPublication,+ SignalSpendSummary,+ SignalSpendUpdate,+ signal_spend_summaries,+)+++@frozen+class _SignalEmbedding:+ model: EmbeddingModelName+ content: str+ metadata: dict[str, JsonValue]+ timestamp: datetime+ embedding: list[float]+ inserted_at: datetime++ def with_updates(self, summary: SignalSpendSummary, changes: list[SignalMetadataChange]) -> "_SignalEmbedding":+ metadata: dict[str, JsonValue] = {+ **self.metadata,+ "total_spend": summary.total_spend,+ "spend_accounting_failed_stages": [*summary.failed_stages],+ }+ clear_content = False+ for change in changes:+ if change.expected_report_id is not None and metadata.get("report_id") != change.expected_report_id:+ continue+ if change.report_id is not None and not metadata.get("deleted"):+ metadata["report_id"] = change.report_id+ if change.deleted:+ metadata["deleted"] = True+ clear_content |= change.clear_content+ return replace(+ self,+ metadata=metadata,+ content="" if clear_content else self.content,+ embedding=[0.0] * len(self.embedding) if clear_content else self.embedding,+ )+++def _read_embedding(team: Team, signal_id: str, model: EmbeddingModelName) -> _SignalEmbedding | None:+ result = execute_hogql_query(+ query_type="SignalsRefreshSpendMetadata",+ query="""+ SELECT document_id, argMax(tuple(content, metadata, timestamp, embedding, inserted_at), inserted_at)+ FROM document_embeddings+ WHERE model_name = {model_name}+ AND product = 'signals' AND document_type = 'signal' AND rendering = 'plain'+ AND document_id = {signal_id}+ GROUP BY document_id+ """,+ team=team,+ context=_signals_query_context(team),+ placeholders={"model_name": ast.Constant(value=model.value), "signal_id": ast.Constant(value=signal_id)},+ )+ if not result.results:+ return None+ content, metadata_json, timestamp, embedding, inserted_at = result.results[0][1]+ return _SignalEmbedding(+ model=model,+ content=content,+ metadata=json.loads(metadata_json),+ timestamp=timestamp.replace(tzinfo=UTC),+ embedding=embedding,+ inserted_at=inserted_at.replace(tzinfo=UTC),+ )+++def publish_signal_spend_metadata(signal: SignalSpendUpdate) -> SignalSpendPublication:+ team = Team.objects.get(id=signal.team_id)+ summary = signal_spend_summaries(team_id=signal.team_id, signal_ids=[signal.signal_id]).get(signal.signal_id)+ if summary is None:+ if SignalSpend.objects.for_team(signal.team_id).filter(signal_id=signal.signal_id).exists():+ raise RuntimeError("Could not read signal spend")+ summary = SignalSpendSummary(total_spend=0, failed_stages=[])+ tag_queries(product=Product.SIGNALS, feature=Feature.QUERY)+ rows = []+ version = int(timezone.now().timestamp())+ for model in EmbeddingModelName:+ row = _read_embedding(team, signal.signal_id, model)+ if row is None:+ raise RuntimeError("Signal embedding is not yet visible in ClickHouse")+ # Kafka's second-resolution timestamp is the replacement version in ClickHouse.+ if row.with_updates(summary, signal.changes) != row and int(row.inserted_at.timestamp()) >= version:+ raise RuntimeError("Waiting for a strictly newer embedding replacement version")+ rows.append(row)+ versions = {}+ for row in rows:+ updated = row.with_updates(summary, signal.changes)+ if updated == row:+ versions[row.model.value] = int(row.inserted_at.timestamp())+ continue+ payload = {+ "team_id": signal.team_id,+ "product": SIGNAL_DOCUMENT_PRODUCT,+ "document_type": SIGNAL_DOCUMENT_TYPE,+ "rendering": SIGNAL_DOCUMENT_RENDERING,+ "document_id": signal.signal_id,+ "model_name": row.model.value,+ "timestamp": row.timestamp.strftime("%Y-%m-%d %H:%M:%S.%f")[:-3],+ "content": updated.content,+ "metadata": json.dumps(updated.metadata),+ "embedding": updated.embedding,+ }+ with producer_scope(topic=KAFKA_DOCUMENT_EMBEDDINGS_TOPIC, flush_timeout=5) as producer:+ delivery = producer.produce(+ topic=KAFKA_DOCUMENT_EMBEDDINGS_TOPIC,+ data=payload,+ key=f"signals:{signal.team_id}:{signal.signal_id}:{row.model.value}",+ )+ delivery.get(timeout=0)+ versions[row.model.value] = version+ return SignalSpendPublication(signal=signal, summary=summary, versions=versions)+++def confirm_signal_spend_metadata(publication: SignalSpendPublication) -> bool:+ team = Team.objects.get(id=publication.signal.team_id)+ tag_queries(product=Product.SIGNALS, feature=Feature.QUERY)+ for model in EmbeddingModelName:+ row = _read_embedding(team, publication.signal.signal_id, model)+ if (+ row is None+ or row.with_updates(publication.summary, publication.signal.changes) != row+ or int(row.inserted_at.timestamp()) < publication.versions[model.value]+ ):+ return False+ return Truediff --git a/products/signals/backend/spend_receivers.py b/products/signals/backend/spend_receivers.pynew file mode 100644index 000000000000..2054a9ec6c88--- /dev/null+++ b/products/signals/backend/spend_receivers.py@@ -0,0 +1,104 @@+from typing import TYPE_CHECKING+from uuid import UUID++from django.db import transaction+from django.db.models.signals import post_save++import structlog++from products.signals.backend.models import SignalReportTask, SignalScoutRun, SignalSpend+from products.signals.backend.spend import record_task_spend, refresh_task_spend, report_triggering_signal+from products.tasks.backend.facade.task_run_signals import (+ TaskOriginProduct,+ connect_task_run_cost_updated,+ connect_task_run_post_save,+)++logger = structlog.get_logger(__name__)+++if TYPE_CHECKING:+ from products.tasks.backend.facade.task_run_signals import TaskRun+++def task_run_created(*, instance: "TaskRun", created: bool, **kwargs: object) -> None:+ if not created:+ return+ stage = (instance.state or {}).get("ai_stage") or "implementation"+ try:+ with transaction.atomic():+ task = instance.task+ if task.origin_product != TaskOriginProduct.SIGNAL_REPORT or not task.signal_report_id:+ return+ previous = SignalSpend.objects.for_team(instance.team_id).filter(task_id=task.id, is_task=True).first()+ if (+ previous is None+ and (instance.state or {}).get("ai_stage")+ not in {+ "research",+ "implementation",+ "repo_selection",+ }+ and not SignalReportTask.objects.filter(+ team_id=instance.team_id, task_id=task.id, relationship="implementation"+ ).exists()+ ):+ return+ stage = (instance.state or {}).get("ai_stage") or (previous.stage if previous else "implementation")+ signal_id = (+ str(previous.signal_id)+ if previous and previous.signal_id+ else report_triggering_signal(team_id=instance.team_id, report_id=str(task.signal_report_id))+ )+ record_task_spend(+ team_id=instance.team_id,+ run_id=str(instance.id),+ stage=stage,+ signal_id=signal_id,+ task_id=str(task.id),+ )+ except Exception:+ logger.exception(+ "signals.spend.accounting_failed", stage=stage, team_id=instance.team_id, run_id=str(instance.id)+ )+++def scout_run_created(*, instance: SignalScoutRun, created: bool, **kwargs: object) -> None:+ if not created:+ return+ try:+ with transaction.atomic():+ record_task_spend(+ team_id=instance.team_id,+ run_id=str(instance.task_run_id),+ stage="scout",+ scout_run_id=str(instance.id),+ task_id=str(instance.task_run.task_id),+ )+ except Exception:+ logger.exception(+ "signals.spend.accounting_failed", stage="scout", team_id=instance.team_id, scout_run_id=str(instance.id)+ )+++def task_cost_updated(*, run_id: UUID, team_id: int, **kwargs: object) -> None:+ try:+ with transaction.atomic():+ spend_id = (+ SignalSpend.objects.for_team(team_id)+ .filter(source_id=str(run_id), is_task=True)+ .values_list("id", flat=True)+ .first()+ )+ if spend_id is not None:+ refresh_task_spend(spend_id=spend_id, team_id=team_id)+ except Exception:+ logger.exception(+ "signals.spend.accounting_failed", stage="task_cost_update", team_id=team_id, run_id=str(run_id)+ )+++def connect_spend_receivers() -> None:+ connect_task_run_cost_updated(task_cost_updated, dispatch_uid="signals.task_cost_updated")+ connect_task_run_post_save(task_run_created, dispatch_uid="signals.spend_task_created")+ post_save.connect(scout_run_created, sender=SignalScoutRun, dispatch_uid="signals.spend_scout_created")diff --git a/products/signals/backend/stack_plan.py b/products/signals/backend/stack_plan.pyindex 17ee53b72b9a..6d2ef48efaa6 100644--- a/products/signals/backend/stack_plan.py+++ b/products/signals/backend/stack_plan.py@@ -114,6 +114,7 @@ def create_layer_reports(for index, layer in enumerate(layers):child = SignalReport.objects.create(team_id=team_id,+ triggering_signal_id=parent.triggering_signal_id,status=SignalReport.Status.READY,title=layer.title,summary=_layer_summary(parent=parent, layer=layer, index=index, total=len(layers)),diff --git a/products/signals/backend/temporal/__init__.py b/products/signals/backend/temporal/__init__.pyindex dd257bfc4c71..93ffccb0f8b1 100644--- a/products/signals/backend/temporal/__init__.py+++ b/products/signals/backend/temporal/__init__.py@@ -95,6 +95,11 @@ from products.signals.backend.temporal.signal_queries import (run_signal_semantic_search_activity,wait_for_signal_in_clickhouse_activity,)+from products.signals.backend.temporal.spend import (+ UpdateSignalSpendWorkflow,+ confirm_signal_spend_activity,+ update_signal_spend_activity,+)from products.signals.backend.temporal.summary import (SignalReportSummaryWorkflow,check_report_quota_gate_activity,@@ -106,6 +111,7 @@ from products.signals.backend.temporal.summary import (mark_report_ready_activity,maybe_autostart_implementation_activity,publish_report_completed_activity,+ publish_report_spend_activity,report_has_assigned_signals_activity,report_is_candidate_activity,reset_report_to_potential_activity,@@ -113,6 +119,7 @@ from products.signals.backend.temporal.summary import ()WORKFLOWS = [+ UpdateSignalSpendWorkflow,GenerateScoutRubricsWorkflow,BackfillErrorTrackingWorkflow,TeamSignalGroupingWorkflow,@@ -136,6 +143,8 @@ WORKFLOWS = []ACTIVITIES = [+ update_signal_spend_activity,+ confirm_signal_spend_activity,load_scout_trial_evaluation_activity,dispatch_scout_trial_comparison_activity,fail_scout_trial_comparison_activity,@@ -179,6 +188,7 @@ ACTIVITIES = [implementation_buffer_seconds_activity,report_is_candidate_activity,publish_report_completed_activity,+ publish_report_spend_activity,report_has_assigned_signals_activity,revert_report_to_candidate_activity,delete_team_reports_activity,diff --git a/products/signals/backend/temporal/buffer.py b/products/signals/backend/temporal/buffer.pyindex 7bd1d0721378..74a6546688b6 100644--- a/products/signals/backend/temporal/buffer.py+++ b/products/signals/backend/temporal/buffer.py@@ -279,6 +279,7 @@ class BufferSignalsWorkflow:workflow.execute_activity(safety_filter_activity,SafetyFilterInput(+ signal_id=s.signal_id,team_id=s.team_id,description=s.description,source_product=s.source_product,diff --git a/products/signals/backend/temporal/grouping.py b/products/signals/backend/temporal/grouping.pyindex fa4c3c4ac5c2..c4781f4ad6d8 100644--- a/products/signals/backend/temporal/grouping.py+++ b/products/signals/backend/temporal/grouping.py@@ -41,6 +41,7 @@ from products.signals.backend.receivers import _is_safety_suppressedfrom products.signals.backend.recurrence import fixed_dismissal_atfrom products.signals.backend.report_merge import signal_target_reportfrom products.signals.backend.signal_metadata import EMBEDDING_MODEL+from products.signals.backend.spend import signal_spend_summariesfrom products.signals.backend.temporal import metricsfrom products.signals.backend.temporal.drop_telemetry import capture_signal_droppedfrom products.signals.backend.temporal.llm import MAX_QUERY_TOKENS, call_llm, truncate_query_to_token_limit@@ -179,6 +180,7 @@ class GenerateSearchQueriesInput:# Optional with a default so workflows mid-flight across a deploy (whose activity input was# serialized before this field existed) still deserialize; missing => gateway key owner's team.team_id: int | None = None+ signal_id: str | None = Nonesignal: EmitSignalInputs | None = None@@ -201,6 +203,7 @@ async def generate_search_queries(input: GenerateSearchQueriesInput) -> list[strreturn await call_llm(team_id=input.team_id,+ signal_id=input.signal_id,system_prompt=system_prompt,user_prompt=user_prompt,validate=validate,@@ -458,6 +461,7 @@ class MatchSignalToReportInput:report_contexts: dict[str, ReportContext]# Optional with a default for deploy-time backward compatibility (see GenerateSearchQueriesInput).team_id: int | None = None+ signal_id: str | None = Noneasync def match_signal_to_report(input: MatchSignalToReportInput) -> MatchResult:@@ -511,6 +515,7 @@ async def match_signal_to_report(input: MatchSignalToReportInput) -> MatchResultreturn await call_llm(team_id=input.team_id,+ signal_id=input.signal_id,system_prompt=MATCHING_SYSTEM_PROMPT,user_prompt=user_prompt,validate=validate,@@ -596,7 +601,7 @@ async def fetch_report_contexts_activity(input: FetchReportContextsInput) -> Fetraise-@dataclass+@dataclass(frozen=False)class VerifyMatchSpecificityInput:team_id: intreport_id: str@@ -605,6 +610,7 @@ class VerifyMatchSpecificityInput:new_signal_source_product: strnew_signal_source_type: strgroup_signals: list[SignalData]+ signal_id: str | None = None@dataclass@@ -621,6 +627,7 @@ async def verify_match_specificity(new_signal_source_type: str,report_title: str,group_signals: list[SignalData],+ signal_id: str | None = None,researched_summary: str | None = None,) -> VerifyMatchSpecificityOutput:"""Verify that adding a signal to a group produces a specific-enough PR title."""@@ -635,6 +642,7 @@ async def verify_match_specificity(specificity = await call_llm(team_id=team_id,+ signal_id=signal_id,system_prompt=SPECIFICITY_CHECK_SYSTEM_PROMPT,user_prompt=specificity_prompt,validate=lambda text: SpecificityResult.model_validate_json(text),@@ -696,6 +704,7 @@ async def verify_match_specificity_activity(input: VerifyMatchSpecificityInput)new_signal_source_type=input.new_signal_source_type,report_title=input.report_title,group_signals=input.group_signals,+ signal_id=input.signal_id,researched_summary=researched_summary,)@@ -806,6 +815,7 @@ async def assign_and_emit_signal_activity(input: AssignAndEmitSignalInput) -> Asmatch_result = input.match_resultdef do_assign_and_emit(suppress_promotion: bool) -> AssignAndEmitDbResult:+ spend = signal_spend_summaries(team_id=input.team_id, signal_ids=[input.signal_id]).get(input.signal_id)with transaction.atomic():promoted = Falsepromotion_suppressed = False@@ -834,6 +844,8 @@ async def assign_and_emit_signal_activity(input: AssignAndEmitSignalInput) -> As"extra": input.extra,"remediation": input.remediation,"deleted": True,+ "total_spend": spend.total_spend if spend else 0,+ "spend_accounting_failed_stages": spend.failed_stages if spend else [],}metadata["match_metadata"] = asdict(match_result.match_metadata)emit_embedding_request(@@ -955,11 +967,22 @@ async def assign_and_emit_signal_activity(input: AssignAndEmitSignalInput) -> As# (e.g. CH wait raised before start_child_workflow)elif report.status != SignalReport.Status.CANDIDATE:updated_fields = report.transition_to(SignalReport.Status.CANDIDATE)- report.save(update_fields=updated_fields)+ report.triggering_signal_id = input.signal_id+ report.save(update_fields=[*updated_fields, "triggering_signal_id"])promoted = Trueelse:promoted = True+ pending_bucket = next_research_bucket(report.researching_signal_count or 0)+ if (+ report.status == SignalReport.Status.IN_PROGRESS+ and report.pending_triggering_signal_id is None+ and pending_bucket is not None+ and report.signal_count >= pending_bucket+ ):+ report.pending_triggering_signal_id = input.signal_id+ report.save(update_fields=["pending_triggering_signal_id"])+report_id = str(report.id)_link_check_follow_up(team_id=input.team_id,@@ -974,6 +997,8 @@ async def assign_and_emit_signal_activity(input: AssignAndEmitSignalInput) -> As"source_id": input.source_id,"weight": input.weight,"report_id": report_id,+ "total_spend": spend.total_spend if spend else 0,+ "spend_accounting_failed_stages": spend.failed_stages if spend else [],"extra": input.extra,"remediation": input.remediation,}@@ -1287,6 +1312,7 @@ async def _process_signal_batch(workflow.execute_activity(generate_search_queries_activity,GenerateSearchQueriesInput(+ signal_id=s.signal_id,team_id=team_id,description=s.description,source_product=s.source_product,@@ -1412,7 +1438,7 @@ async def _process_signal_batch(emitted_signals = _par.emitted_signalsfor i, signal in enumerate(batch if not _use_parallel_sequential else []):- signal_id = str(uuid.uuid4())+ signal_id = signal.signal_id or str(uuid.uuid4())try:# Augment CH candidates with earlier-in-batch signalsaugmented_results = _augment_candidates_with_batch(@@ -1426,6 +1452,7 @@ async def _process_signal_batch(match_result = await workflow.execute_activity(match_signal_to_report_activity,MatchSignalToReportInput(+ signal_id=signal_id,team_id=team_id,description=signal.description,source_product=signal.source_product,@@ -1461,6 +1488,7 @@ async def _process_signal_batch(specificity_result: VerifyMatchSpecificityOutput = await workflow.execute_activity(verify_match_specificity_activity,VerifyMatchSpecificityInput(+ signal_id=signal_id,team_id=team_id,report_id=match_result.report_id,report_title=report_title,diff --git a/products/signals/backend/temporal/llm.py b/products/signals/backend/temporal/llm.pyindex fab9a7300387..1d28adfa5cb7 100644--- a/products/signals/backend/temporal/llm.py+++ b/products/signals/backend/temporal/llm.py@@ -15,6 +15,7 @@ from posthog.llm.gateway_client import (resolve_ai_gateway_config,)+from products.signals.backend.llm_spend import generate_with_spendfrom products.signals.backend.temporal import metricslogger = structlog.get_logger(__name__)@@ -158,6 +159,7 @@ async def call_llm(cache_system_prompt: bool = False,trace_id: str | None = None,properties: Mapping[str, str] | None = None,+ signal_id: str | None = None,) -> T:model = model or MATCHING_MODEL# Native Anthropic Messages endpoint so prefilling and extended thinking carry over unchanged.@@ -215,8 +217,8 @@ async def call_llm(# lands there: an un-opted call site, or an opted one before the gateway env is set. Skip it# only when an opted call site actually reaches the Go gateway, which reads ai_stage from the# X-PostHog-Properties blob instead.- on_go_gateway = ai_product is not None and resolve_ai_gateway_config() is not None- if stage and not on_go_gateway:+ gateway = resolve_ai_gateway_config() if ai_product is not None else None+ if stage and gateway is None:create_kwargs["extra_headers"] = {"x-posthog-property-ai_stage": stage}# Later, we'll want to tune how many tokens we give over to thinking vs. producing output. Hard-coded for now.@@ -235,7 +237,11 @@ async def call_llm(# NOTE - we explicitly don't want to retry if we fail to call the llm, or fail to extract text content,# only if we fail to validate the response. A transport/extraction failure is a hot-path LLM error.try:- response = await client.messages.create(**create_kwargs)+ generation = client.messages.create(**create_kwargs)+ priced = await generate_with_spend(+ generation, gateway=gateway, team_id=team_id, signal_id=signal_id, stage=stage_label+ )+ response = priced.responsetext_content = _extract_text_content(response)except Exception:metrics.increment_llm_call(stage_label, metrics.LLM_STATUS_ERROR)diff --git a/products/signals/backend/temporal/parallel_grouping.py b/products/signals/backend/temporal/parallel_grouping.pyindex 3dc95c64af58..2bf260e879f3 100644--- a/products/signals/backend/temporal/parallel_grouping.py+++ b/products/signals/backend/temporal/parallel_grouping.py@@ -168,6 +168,7 @@ async def _process_signal(match_result = await workflow.execute_activity(match_signal_to_report_activity,MatchSignalToReportInput(+ signal_id=signal_id,team_id=team_id,description=signal.description,source_product=signal.source_product,@@ -197,6 +198,7 @@ async def _process_signal(specificity_result: VerifyMatchSpecificityOutput = await workflow.execute_activity(verify_match_specificity_activity,VerifyMatchSpecificityInput(+ signal_id=signal_id,team_id=team_id,report_id=match_result.report_id,report_title=report_title,@@ -328,7 +330,7 @@ async def _process_parallel_batch(coroutines = []for idx in batch_indices:signal = batch[idx]- signal_id = str(uuid.uuid4())+ signal_id = signal.signal_id or str(uuid.uuid4())# Augment CH candidates with all previously processed signals (from earlier batches)augmented_results = _augment_candidates_with_batch(diff --git a/products/signals/backend/temporal/refusal_review.py b/products/signals/backend/temporal/refusal_review.pyindex 3094557bbb61..bf70ddbac614 100644--- a/products/signals/backend/temporal/refusal_review.py+++ b/products/signals/backend/temporal/refusal_review.py@@ -18,7 +18,9 @@ MAX_REFUSAL_ATTEMPTS = 3def refusal_review_key(signal: EmitSignalInputs) -> str:- fingerprint = hashlib.sha256(json.dumps(asdict(signal), sort_keys=True).encode()).hexdigest()+ payload = asdict(signal)+ payload.pop("signal_id", None)+ fingerprint = hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest()return f"signals/refusal_review/{signal.team_id}/{fingerprint}.json"diff --git a/products/signals/backend/temporal/reingestion.py b/products/signals/backend/temporal/reingestion.pyindex 83ee31b48cc0..0ad3e8bb3e35 100644--- a/products/signals/backend/temporal/reingestion.py+++ b/products/signals/backend/temporal/reingestion.py@@ -9,11 +9,8 @@ from asgiref.sync import sync_to_asyncfrom temporalio import workflowfrom temporalio.common import RetryPolicy-from posthog.schema import EmbeddingModelName-from posthog.hogql import ast-from posthog.api.embedding_worker import emit_embedding_requestfrom posthog.models import Teamfrom posthog.sync import database_sync_to_asyncfrom posthog.temporal.common.scoped import scoped_temporal@@ -22,13 +19,11 @@ from posthog.temporal.common.utils import close_db_connectionsfrom products.signals.backend.facade.api import emit_signalfrom products.signals.backend.models import SignalReport, SignalReportArtefactfrom products.signals.backend.signal_metadata import EMBEDDING_MODEL+from products.signals.backend.spend import SignalMetadataChange, submit_signal_metadata_updatesfrom products.signals.backend.temporal.clickhouse import execute_hogql_query_with_retryfrom products.signals.backend.temporal.grouping_v2 import TeamSignalGroupingV2Workflowfrom products.signals.backend.temporal.signal_queries import (_DEDUPED_SIGNALS_SUBQUERY,- SIGNAL_DOCUMENT_PRODUCT,- SIGNAL_DOCUMENT_RENDERING,- SIGNAL_DOCUMENT_TYPE,FetchSignalsForReportInput,FetchSignalsForReportOutput,WaitForClickHouseInput,@@ -224,19 +219,10 @@ async def process_team_signals_batch_activity(input: ProcessTeamSignalsBatchInpufor signal in signals:temporalio.activity.heartbeat()- metadata = dict(signal.metadata)- metadata["deleted"] = True-- await sync_to_async(emit_embedding_request, thread_sensitive=False)(- content=signal.content,+ await submit_signal_metadata_updates(team_id=input.team_id,- product=SIGNAL_DOCUMENT_PRODUCT,- document_type=SIGNAL_DOCUMENT_TYPE,- rendering=SIGNAL_DOCUMENT_RENDERING,- document_id=signal.signal_id,- models=[m.value for m in EmbeddingModelName],- timestamp=signal.timestamp,- metadata=metadata,+ signal_ids=[signal.signal_id],+ change=SignalMetadataChange(deleted=True),)if not input.delete_only:@@ -262,9 +248,7 @@ async def process_team_signals_batch_activity(input: ProcessTeamSignalsBatchInpufor signal in signals],max_wait_time_seconds=3600,- # Bulk reprocessing is non-interactive: let the store gate the polling, but- # confirm in ClickHouse before the next batch re-reads these rows.- mode=WaitForClickHouseMode.CH_CONFIRMED,+ mode=WaitForClickHouseMode.METADATA_UPDATE,))@@ -407,7 +391,7 @@ class SignalReportReingestionWorkflow:for s in fetch_result.signals],max_wait_time_seconds=3600,- mode=WaitForClickHouseMode.CH_CONFIRMED,+ mode=WaitForClickHouseMode.METADATA_UPDATE,),start_to_close_timeout=timedelta(hours=1, minutes=5),heartbeat_timeout=timedelta(minutes=5),diff --git a/products/signals/backend/temporal/report_safety_judge.py b/products/signals/backend/temporal/report_safety_judge.pyindex 6f41edfc55ee..cce8e65db872 100644--- a/products/signals/backend/temporal/report_safety_judge.py+++ b/products/signals/backend/temporal/report_safety_judge.py@@ -17,6 +17,7 @@ from posthog.temporal.common.utils import close_db_connectionsfrom products.ml_inference.backend.facade.contracts import JsonValuefrom products.signals.backend.artefact_schemas import SafetyJudgmentfrom products.signals.backend.models import ArtefactAttribution, SignalReportArtefact+from products.signals.backend.spend import report_triggering_signalfrom products.signals.backend.system_one_decision import SAFETY_CATEGORIES, ModelMode, model_mode, run_model_decisionfrom products.signals.backend.system_one_prompts import bundled_prompt, current_promptfrom products.signals.backend.temporal.llm import SAFETY_MODEL, call_llm@@ -146,6 +147,7 @@ async def judge_report_safety(team_id: int,signals: list[SignalData],report_id: str | None = None,+ signal_id: str | None = None,) -> SafetyJudgeResponse:"""Assess whether a signal report contains prompt injection or manipulation attempts.@@ -169,6 +171,7 @@ async def judge_report_safety(async def sonnet_verdict(trace_id: str | None) -> SafetyJudgeResponse:return await call_llm(team_id=team_id,+ signal_id=signal_id,system_prompt=system_one_prompt.policy,user_prompt=user_prompt,validate=validate,@@ -253,11 +256,24 @@ class SafetyJudgeOutput:@close_db_connectionsasync def report_safety_judge_activity(input: SafetyJudgeInput) -> SafetyJudgeOutput:"""Assess report for prompt injection attacks and store result as artefact."""+ try:+ signal_id = await database_sync_to_async(report_triggering_signal)(+ team_id=input.team_id, report_id=input.report_id+ )+ except Exception:+ logger.exception(+ "signals.spend.accounting_failed",+ stage="report_safety_judge",+ team_id=input.team_id,+ report_id=input.report_id,+ )+ signal_id = Nonetry:result = await judge_report_safety(team_id=input.team_id,signals=input.signals,report_id=input.report_id,+ signal_id=signal_id,)# Append-only: each safety assessment is a point-in-time entry in the report log. Thediff --git a/products/signals/backend/temporal/safety_filter.py b/products/signals/backend/temporal/safety_filter.pyindex 1dbef6e2b399..bc504c7f0dcb 100644--- a/products/signals/backend/temporal/safety_filter.py+++ b/products/signals/backend/temporal/safety_filter.py@@ -157,7 +157,7 @@ def _safe_verdict_cache_key(team_id: int, mode: ModelMode, signal_prompt: str, preturn f"signals:safety:safe:v1:{team_id}:{hashlib.sha256(payload.encode()).hexdigest()}"-@dataclass+@dataclass(frozen=False)class SafetyFilterInput:description: str# Optional with a default for deploy-time backward compatibility: a batch scheduled before this@@ -171,6 +171,7 @@ class SafetyFilterInput:source_id: str | None = Noneweight: float | None = Noneextra: dict = field(default_factory=dict)+ signal_id: str | None = None@dataclass@@ -186,6 +187,7 @@ async def safety_filter(source_product: str | None = None,source_type: str | None = None,source_id: str | None = None,+ signal_id: str | None = None,) -> SafetyFilterJudgeResponse:def validate(text: str) -> SafetyFilterJudgeResponse:data = json.loads(text)@@ -216,6 +218,7 @@ async def safety_filter(try:return await call_llm(team_id=team_id,+ signal_id=signal_id,system_prompt=system_one_prompt.policy,user_prompt=signal_prompt,validate=validate,@@ -343,7 +346,12 @@ async def safety_filter_activity(input: SafetyFilterInput) -> SafetyFilterOutput"""Filter out unsafe signals before passing them through the pipeline."""try:result = await safety_filter(- input.team_id, input.description, input.source_product, input.source_type, input.source_id+ input.team_id,+ input.description,+ input.source_product,+ input.source_type,+ input.source_id,+ signal_id=input.signal_id,)except Exception:logger.exception("Failed to run safety filter")diff --git a/products/signals/backend/temporal/signal_queries.py b/products/signals/backend/temporal/signal_queries.pyindex 2c96f128728e..cf0fba39e9b1 100644--- a/products/signals/backend/temporal/signal_queries.py+++ b/products/signals/backend/temporal/signal_queries.py@@ -7,15 +7,15 @@ from typing import Unionimport structlogimport temporalio--from posthog.schema import EmbeddingModelName+from asgiref.sync import async_to_syncfrom posthog.hogql import astfrom posthog.hogql.query import execute_hogql_query-from posthog.api.embedding_worker import DocumentKey, async_get_recently_seen_documents, emit_embedding_request+from posthog.api.embedding_worker import DocumentKey, async_get_recently_seen_documentsfrom posthog.clickhouse.query_tagging import Feature, Product, tag_queriesfrom posthog.models import Team+from posthog.temporal.common.client import async_connectfrom posthog.temporal.common.scoped import scoped_temporalfrom posthog.temporal.common.utils import close_db_connections@@ -29,6 +29,7 @@ from products.signals.backend.signal_metadata import (_report_placeholders,_signals_for_report_query,)+from products.signals.backend.spend import SignalMetadataChange, submit_signal_metadata_updatesfrom products.signals.backend.temporal import metricsfrom products.signals.backend.temporal.clickhouse import execute_hogql_query_with_retryfrom products.signals.backend.temporal.types import SignalCandidate, SignalData, SignalTypeExample@@ -109,22 +110,11 @@ def soft_delete_report_signals(report_id: str, team_id: int, team: Team) -> Noneplaceholders=_report_placeholders(report_id),)- for row in result.results or []:- document_id, content, metadata_str, timestamp_raw, _inserted_at_raw = row- metadata = json.loads(metadata_str)- metadata["deleted"] = True-- emit_embedding_request(- content=content,- team_id=team_id,- product=SIGNAL_DOCUMENT_PRODUCT,- document_type=SIGNAL_DOCUMENT_TYPE,- rendering=SIGNAL_DOCUMENT_RENDERING,- document_id=document_id,- models=[m.value for m in EmbeddingModelName],- timestamp=_ensure_tz_aware(timestamp_raw),- metadata=metadata,- )+ async_to_sync(submit_signal_metadata_updates)(+ team_id=team_id,+ signal_ids=[row[0] for row in result.results or []],+ change=SignalMetadataChange(deleted=True, expected_report_id=report_id),+ )_RETRACT_PAGE_SIZE = 500@@ -169,22 +159,12 @@ def retract_source_signals(*, team: Team, source_product: str, source_type: str,},)rows = result.results or []- for row in rows:- document_id, _content, metadata_str, timestamp_raw = row- metadata = json.loads(metadata_str) if isinstance(metadata_str, str) else dict(metadata_str or {})- metadata["deleted"] = True- emit_embedding_request(- content="",- team_id=team.id,- product=SIGNAL_DOCUMENT_PRODUCT,- document_type=SIGNAL_DOCUMENT_TYPE,- rendering=SIGNAL_DOCUMENT_RENDERING,- document_id=document_id,- models=[model.value for model in EmbeddingModelName],- timestamp=_ensure_tz_aware(timestamp_raw),- metadata=metadata,- )- retracted += 1+ async_to_sync(submit_signal_metadata_updates)(+ team_id=team.id,+ signal_ids=[row[0] for row in rows],+ change=SignalMetadataChange(deleted=True, clear_content=True),+ )+ retracted += len(rows)if len(rows) < _RETRACT_PAGE_SIZE:return retractedafter = rows[-1][0]@@ -205,24 +185,13 @@ def reassign_report_signals(*, source_report_id: str, survivor_report_id: str, tplaceholders=_report_placeholders(source_report_id),)- moved = 0- for row in result.results or []:- document_id, content, metadata_str, timestamp_raw, _inserted_at_raw = row- metadata = json.loads(metadata_str)- metadata["report_id"] = survivor_report_id-- emit_embedding_request(- content=content,- team_id=team_id,- product=SIGNAL_DOCUMENT_PRODUCT,- document_type=SIGNAL_DOCUMENT_TYPE,- rendering=SIGNAL_DOCUMENT_RENDERING,- document_id=document_id,- models=[m.value for m in EmbeddingModelName],- timestamp=_ensure_tz_aware(timestamp_raw),- metadata=metadata,- )- moved += 1+ signal_ids = [row[0] for row in result.results or []]+ async_to_sync(submit_signal_metadata_updates)(+ team_id=team_id,+ signal_ids=signal_ids,+ change=SignalMetadataChange(report_id=survivor_report_id, expected_report_id=source_report_id),+ )+ moved = len(signal_ids)if moved >= REASSIGN_SIGNAL_ROW_CAP:logger.warning("signals_reassign_hit_row_cap",@@ -419,10 +388,13 @@ class WaitForClickHouseMode(StrEnum):CH_CONFIRMED: a store confirmation triggers an immediate ClickHouse confirm, andClickHouse stays authoritative — the store only decides when to start querying.+ METADATA_UPDATE: wait for the per-signal writer, which confirms its own replacement+ version in ClickHouse without passing through the embedding worker."""OPTIMISTIC = "optimistic"CH_CONFIRMED = "ch_confirmed"+ METADATA_UPDATE = "metadata_update"@dataclass@@ -501,6 +473,18 @@ async def wait_for_signal_in_clickhouse_activity(input: WaitForClickHouseInput)if not input.signals:return+ if input.mode == WaitForClickHouseMode.METADATA_UPDATE:+ client = await async_connect()+ for start in range(0, len(input.signals), 20):+ temporalio.activity.heartbeat()+ await asyncio.gather(+ *(+ client.get_workflow_handle(f"signal-spend-{input.team_id}-{signal.signal_id}").result()+ for signal in input.signals[start : start + 20]+ )+ )+ return+from django.utils import timezoneteam = await Team.objects.aget(pk=input.team_id)diff --git a/products/signals/backend/temporal/spend.py b/products/signals/backend/temporal/spend.pynew file mode 100644index 000000000000..a221e85ea292--- /dev/null+++ b/products/signals/backend/temporal/spend.py@@ -0,0 +1,78 @@+from dataclasses import replace+from datetime import timedelta++from temporalio import activity, workflow+from temporalio.common import RetryPolicy+from temporalio.exceptions import ApplicationError++from posthog.temporal.common.base import PostHogWorkflow++with workflow.unsafe.imports_passed_through():+ from posthog.temporal.common.utils import asyncify++ from products.signals.backend.spend import (+ SignalMetadataChange,+ SignalSpendPublication,+ SignalSpendUpdate,+ settle_signal_task_spend,+ )+ from products.signals.backend.spend_metadata import confirm_signal_spend_metadata, publish_signal_spend_metadata+++@asyncify+def update_signal_spend_activity(input: SignalSpendUpdate) -> SignalSpendPublication:+ settle_signal_task_spend(team_id=input.team_id, signal_id=input.signal_id)+ return publish_signal_spend_metadata(input)+++@asyncify+def confirm_signal_spend_activity(input: SignalSpendPublication) -> None:+ if not confirm_signal_spend_metadata(input):+ raise ApplicationError("Signal spend metadata is not yet visible in ClickHouse", type="SignalSpendNotVisible")++[email protected](name="update-signal-spend")+class UpdateSignalSpendWorkflow(PostHogWorkflow):+ inputs_cls = SignalSpendUpdate++ def __init__(self) -> None:+ self._updates = 0+ self._changes: list[SignalMetadataChange] = []++ @workflow.signal+ def refresh(self) -> None:+ self._updates += 1++ @workflow.signal+ def update_metadata(self, change: SignalMetadataChange) -> None:+ self._changes.append(change)+ self._updates += 1++ @workflow.run+ async def run(self, input: SignalSpendUpdate) -> None:+ self._changes = input.changes + self._changes+ while True:+ # Separate replacements into Kafka timestamp seconds, and coalesce queued notifications.+ await workflow.sleep(1)+ updates = self._updates+ changes, self._changes = self._changes, []+ publication = await workflow.execute_activity(+ update_signal_spend_activity,+ replace(input, changes=changes),+ start_to_close_timeout=timedelta(minutes=1),+ schedule_to_close_timeout=timedelta(minutes=10),+ retry_policy=RetryPolicy(initial_interval=timedelta(seconds=1), maximum_interval=timedelta(seconds=10)),+ )+ await workflow.execute_activity(+ confirm_signal_spend_activity,+ publication,+ start_to_close_timeout=timedelta(minutes=1),+ schedule_to_close_timeout=timedelta(minutes=10),+ retry_policy=RetryPolicy(initial_interval=timedelta(seconds=1), maximum_interval=timedelta(seconds=10)),+ )+ if updates == self._updates:+ return+ if workflow.info().is_continue_as_new_suggested():+ workflow.continue_as_new(replace(input, changes=self._changes))diff --git a/products/signals/backend/temporal/summary.py b/products/signals/backend/temporal/summary.pyindex f86305f2de38..b00edd296997 100644--- a/products/signals/backend/temporal/summary.py+++ b/products/signals/backend/temporal/summary.py@@ -51,6 +51,7 @@ from products.signals.backend.report_generation.research import ActionabilityChofrom products.signals.backend.report_generation.select_repo import RepoSelectionResultfrom products.signals.backend.report_metric_query_access import query_filter_shape_allows_readfrom products.signals.backend.report_metrics import REPORT_METRIC_GOAL_FIELDS+from products.signals.backend.spend import publish_report_spendfrom products.signals.backend.stack_plan import create_layer_reports, start_unblocked_layers_of_planfrom products.signals.backend.temporal import metricsfrom products.signals.backend.temporal.agentic.report import (@@ -222,7 +223,19 @@ class SignalReportSummaryWorkflow:posthoganalytics.tag("team_id", inputs.team_id)posthoganalytics.tag("report_id", inputs.report_id)posthoganalytics.tag("product", "signals")- await self._run_impl(inputs)+ try:+ await self._run_impl(inputs)+ finally:+ if workflow.patched("signals-publish-spend-on-completion"):+ try:+ await workflow.execute_activity(+ publish_report_spend_activity,+ inputs,+ start_to_close_timeout=timedelta(minutes=20),+ retry_policy=RetryPolicy(maximum_attempts=1),+ )+ except Exception:+ workflow.logger.exception("Failed to publish completed report spend")async def _run_impl(self, inputs: SignalReportSummaryWorkflowInputs) -> None:# Bind team_id + report_id so all logs flow to the log_entries sink (the Temporal@@ -809,7 +822,9 @@ async def mark_report_in_progress_activity(input: MarkReportInProgressInput) ->updated_fields = report.transition_to(SignalReport.Status.IN_PROGRESS, signals_at_run_increment=SIGNALS_AT_RUN_INCREMENT)- report.save(update_fields=updated_fields)+ report.pending_triggering_signal_id = None+ report.researching_signal_count = input.signal_count+ report.save(update_fields=[*updated_fields, "pending_triggering_signal_id", "researching_signal_count"])return report.run_count, Falserun_count, was_already_in_progress = await database_sync_to_async(do_update, thread_sensitive=False)()@@ -1013,7 +1028,9 @@ async def mark_report_ready_activity(input: MarkReportReadyInput) -> bool:# If more signals arrived while the report was being processed, we want to# re-promote it back to candidate and loop to also process new signalscandidate_fields = report.transition_to(SignalReport.Status.CANDIDATE)- report.save(update_fields=candidate_fields)+ if report.pending_triggering_signal_id is not None:+ report.triggering_signal_id = report.pending_triggering_signal_id+ report.save(update_fields=[*candidate_fields, "triggering_signal_id"])else:# Only a pass that settles writes its checks. A pass about to be re-researched is# an intermediate one, and its checks would describe prose the next pass replaces.@@ -1458,3 +1475,9 @@ async def publish_report_completed_activity(input: PublishReportCompletedInput)team_id=input.team_id,)raise+++@scoped_temporal()+async def publish_report_spend_activity(input: SignalReportSummaryWorkflowInputs) -> None:+ await publish_report_spend(team_id=input.team_id, report_id=input.report_id)diff --git a/products/signals/backend/temporal/types.py b/products/signals/backend/temporal/types.pyindex 405089b1c4d9..6231c7c9c9f9 100644--- a/products/signals/backend/temporal/types.py+++ b/products/signals/backend/temporal/types.py@@ -60,7 +60,7 @@ IMPLEMENTATION_DEBOUNCE_SECONDS = int(os.getenv("SIGNAL_IMPLEMENTATION_DEBOUNCE_NEW_SELF_DRIVING_GRACE = timedelta(hours=24)-@dataclass+@dataclass(frozen=False)class EmitSignalInputs:team_id: intsource_product: str@@ -74,6 +74,7 @@ class EmitSignalInputs:# the Temporal/S3 JSON round-trip. Surfaced to the research agent as authoritative direction when# present; not required by any source.remediation: Optional[dict] = None+ signal_id: str | None = None@dataclassdiff --git a/products/signals/backend/test/test_agentic_report_activity.py b/products/signals/backend/test/test_agentic_report_activity.pyindex ad1a5b0e8b6f..ae69c9b6fe00 100644--- a/products/signals/backend/test/test_agentic_report_activity.py+++ b/products/signals/backend/test/test_agentic_report_activity.py@@ -3,7 +3,7 @@ import randomimport asynciofrom collections.abc import Callablefrom datetime import UTC, datetime, timedelta-from uuid import UUID+from uuid import UUID, uuid4import pytestfrom unittest.mock import AsyncMock, Mock, patch@@ -602,7 +602,7 @@ async def test_select_repository_activity_returns_repo(monkeypatch, ateam):with patch("products.signals.backend.temporal.agentic.select_repository.Heartbeater"):result = await select_repository_activity(- SelectRepositoryInput(team_id=ateam.id, report_id="test-report-id", signals=_build_signals())+ SelectRepositoryInput(team_id=ateam.id, report_id=str(uuid4()), signals=_build_signals()))assert result.repository == "posthog/posthog"@@ -633,7 +633,7 @@ async def test_select_repository_activity_reuses_previous_selection(monkeypatch,with patch("products.signals.backend.temporal.agentic.select_repository.Heartbeater"):result = await select_repository_activity(- SelectRepositoryInput(team_id=ateam.id, report_id="test-report-id", signals=_build_signals())+ SelectRepositoryInput(team_id=ateam.id, report_id=str(uuid4()), signals=_build_signals()))assert result is previous@@ -662,7 +662,7 @@ async def test_select_repository_activity_retries_transient_db_drop(monkeypatch,with patch("products.signals.backend.temporal.agentic.select_repository.Heartbeater"):result = await select_repository_activity(- SelectRepositoryInput(team_id=ateam.id, report_id="test-report-id", signals=_build_signals())+ SelectRepositoryInput(team_id=ateam.id, report_id=str(uuid4()), signals=_build_signals()))assert result is previous@@ -691,7 +691,7 @@ async def test_select_repository_activity_no_repo(monkeypatch, ateam):with patch("products.signals.backend.temporal.agentic.select_repository.Heartbeater"):result = await select_repository_activity(- SelectRepositoryInput(team_id=ateam.id, report_id="test-report-id", signals=_build_signals())+ SelectRepositoryInput(team_id=ateam.id, report_id=str(uuid4()), signals=_build_signals()))assert result.repository is None@@ -734,7 +734,7 @@ async def test_select_repository_activity_does_not_raise_with_only_user_integratwith patch("products.signals.backend.temporal.agentic.select_repository.Heartbeater"):result = await select_repository_activity(- SelectRepositoryInput(team_id=ateam.id, report_id="test-report-id", signals=_build_signals())+ SelectRepositoryInput(team_id=ateam.id, report_id=str(uuid4()), signals=_build_signals()))assert result.repository == "posthog/posthog"diff --git a/products/signals/backend/test/test_assign_and_emit_signal.py b/products/signals/backend/test/test_assign_and_emit_signal.pyindex df2a2eba36e8..e7389c847f6a 100644--- a/products/signals/backend/test/test_assign_and_emit_signal.py+++ b/products/signals/backend/test/test_assign_and_emit_signal.py@@ -20,6 +20,7 @@ from products.signals.backend.enums import ReportLinkKindfrom products.signals.backend.models import SignalReport, SignalReportArtefactfrom products.signals.backend.quota import SelfDrivingQuotaGatefrom products.signals.backend.report_merge import MERGE_DISMISSAL_REASON+from products.signals.backend.spend import record_llm_spendfrom products.signals.backend.temporal.grouping import (WEIGHT_THRESHOLD,AssignAndEmitSignalInput,@@ -65,11 +66,17 @@ def patch_side_effects():"""Mock only the external side effects (Kafka, analytics, ClickHouse). The Postgres statemachine is the SUT and is exercised against a real DB."""with (+ patch("posthog.temporal.common.client.async_connect", new=AsyncMock(return_value=AsyncMock())) as connect_mock,patch(f"{GROUPING_MODULE_PATH}.emit_embedding_request") as emit_mock,patch(f"{GROUPING_MODULE_PATH}.posthoganalytics.capture") as capture_mock,patch(f"{GROUPING_MODULE_PATH}.soft_delete_report_signals") as soft_delete_mock,):- yield {"emit": emit_mock, "capture": capture_mock, "soft_delete": soft_delete_mock}+ yield {+ "emit": emit_mock,+ "capture": capture_mock,+ "soft_delete": soft_delete_mock,+ "temporal": connect_mock.return_value,+ }def _existing_match(report_id: str) -> ExistingReportMatch:@@ -118,11 +125,21 @@ def _build_input(@pytest.mark.asyncio@pytest.mark.django_db-async def test_new_match_creates_potential_report_below_threshold(ateam):+async def test_new_match_creates_potential_report_below_threshold(ateam, patch_side_effects):"""A first signal below weight threshold creates a POTENTIAL report, not promoted yet."""input_ = _build_input(ateam.id, _new_match(), weight=WEIGHT_THRESHOLD * 0.5)+ await database_sync_to_async(record_llm_spend)(+ "example-generation",+ token_cost_microusd=123_456,+ team_id=ateam.id,+ signal_id=input_.signal_id,+ stage="actionability",+ )result = await assign_and_emit_signal_activity(input_)+ assert patch_side_effects["emit"].call_args.kwargs["metadata"]["total_spend"] == 12.3456+ assert patch_side_effects["emit"].call_args.kwargs["metadata"]["spend_accounting_failed_stages"] == []+ patch_side_effects["temporal"].start_workflow.assert_not_called()assert result.promoted is Falsereport = await database_sync_to_async(SignalReport.objects.get)(id=result.report_id)@@ -216,6 +233,7 @@ async def test_potential_promotes_when_weight_crosses_threshold(ateam):assert refreshed.total_weight == pytest.approx(WEIGHT_THRESHOLD * 1.2)assert refreshed.signal_count == 2assert refreshed.promoted_at is not None+ assert str(refreshed.triggering_signal_id) == input_.signal_id@pytest.mark.asyncio@@ -271,8 +289,10 @@ async def test_candidate_returns_promoted_true_without_changing_status(ateam):- leave status at CANDIDATE- increment weight + signal_count atomically"""+ original_driver = uuid.uuid4()report = await database_sync_to_async(SignalReport.objects.create)(team=ateam,+ triggering_signal_id=original_driver,status=SignalReport.Status.CANDIDATE,total_weight=2.0,signal_count=3,@@ -287,6 +307,8 @@ async def test_candidate_returns_promoted_true_without_changing_status(ateam):assert refreshed.total_weight == pytest.approx(2.5)assert refreshed.signal_count == 4+ assert refreshed.triggering_signal_id == original_driver+@pytest.mark.asyncio@pytest.mark.django_db@@ -1159,7 +1181,17 @@ async def test_deleted_report_skips_counter_updates_and_marks_signal_deleted(ate)input_ = _build_input(ateam.id, _existing_match(str(report.id)), weight=0.5)+ await database_sync_to_async(record_llm_spend)(+ "example-generation",+ token_cost_microusd=123_456,+ team_id=ateam.id,+ signal_id=input_.signal_id,+ stage="actionability",+ )result = await assign_and_emit_signal_activity(input_)+ assert patch_side_effects["emit"].call_args.kwargs["metadata"]["total_spend"] == 12.3456+ assert patch_side_effects["emit"].call_args.kwargs["metadata"]["spend_accounting_failed_stages"] == []+ patch_side_effects["temporal"].start_workflow.assert_not_called()assert result.promoted is Falserefreshed = await database_sync_to_async(SignalReport.objects.get)(id=report.id)@@ -1323,3 +1355,29 @@ async def test_daily_limit_gate_emits_no_event_when_signal_would_not_promote(ateevents = [call.kwargs.get("event") for call in patch_side_effects["capture"].call_args_list]assert "signal_report_daily_limit_paused" not in events+++async def test_signal_crossing_next_bucket_owns_next_research_pass(ateam):+ original_driver = uuid.uuid4()+ report = await database_sync_to_async(SignalReport.objects.create)(+ team=ateam,+ status=SignalReport.Status.IN_PROGRESS,+ signal_count=2,+ total_weight=2,+ researching_signal_count=2,+ triggering_signal_id=original_driver,+ )+ for _ in range(3):+ signal = _build_input(ateam.id, _existing_match(str(report.id)))+ await assign_and_emit_signal_activity(signal)+ await database_sync_to_async(report.refresh_from_db)()+ assert report.triggering_signal_id == original_driver+ if report.signal_count == 3:+ assert report.pending_triggering_signal_id is None+ elif report.signal_count == 4:+ next_driver = signal.signal_id+ assert str(report.pending_triggering_signal_id) == next_driver+ else:+ assert str(report.pending_triggering_signal_id) == next_driverdiff --git a/products/signals/backend/test/test_generate_search_queries.py b/products/signals/backend/test/test_generate_search_queries.pyindex 6e78af3153c6..d6c2d8b50f03 100644--- a/products/signals/backend/test/test_generate_search_queries.py+++ b/products/signals/backend/test/test_generate_search_queries.py@@ -32,11 +32,13 @@ async def test_generate_search_queries_keeps_the_first_three_without_a_retry(retsource_product="zendesk",source_type="ticket",signal_type_examples=[],+ signal_id="driver-signal",))assert result == queries[:MAX_SEARCH_QUERIES]assert call_llm.call_count == 1+ assert call_llm.call_args.kwargs["signal_id"] == "driver-signal"@pytest.mark.asynciodiff --git a/products/signals/backend/test/test_refusal_review.py b/products/signals/backend/test/test_refusal_review.pyindex a097768a054b..92e41f98baf4 100644--- a/products/signals/backend/test/test_refusal_review.py+++ b/products/signals/backend/test/test_refusal_review.py@@ -1,5 +1,7 @@import json+import hashlibfrom collections.abc import Generator+from dataclasses import asdict, replaceimport pytestfrom unittest.mock import AsyncMock, patch@@ -46,17 +48,33 @@ async def test_noisy_refusal_can_recover_before_review(stored_records: dict[str,@pytest.mark.asyncio-async def test_three_refusals_preserve_the_signal_and_skip_batch_retries(stored_records: dict[str, str]) -> None:[email protected]("legacy", [False, True])+async def test_three_refusals_preserve_the_signal_and_skip_batch_retries(+ stored_records: dict[str, str], legacy: bool+) -> None:signal = make_signal()generate = AsyncMock(side_effect=llm.LLMRefusalError())+ if legacy:+ payload = asdict(signal)+ del payload["signal_id"]+ fingerprint = hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest()+ stored_records[f"signals/refusal_review/{signal.team_id}/{fingerprint}.json"] = json.dumps(+ {"signal": payload, "attempts": 3, "status": "needs_review"}+ )+assert await generate_queries_or_preserve_refusal(signal, generate) is Nonerecord = json.loads(stored_records[refusal_review_key(signal)])assert record["status"] == "needs_review"assert record["attempts"] == 3assert EmitSignalInputs(**record["signal"]) == signal- assert await generate_queries_or_preserve_refusal(signal, generate) is None- assert generate.await_count == 3+ assert (+ await generate_queries_or_preserve_refusal(+ replace(signal, signal_id="00000000-0000-0000-0000-000000000001"), generate+ )+ is None+ )+ assert generate.await_count == (0 if legacy else 3)@pytest.mark.asynciodiff --git a/products/signals/backend/test/test_report_safety_judge.py b/products/signals/backend/test/test_report_safety_judge.pyindex 4470e3b000c8..ed5239758e72 100644--- a/products/signals/backend/test/test_report_safety_judge.py+++ b/products/signals/backend/test/test_report_safety_judge.py@@ -36,9 +36,10 @@ async def test_report_judge_runs_on_the_safety_model() -> None:cache_flags: list[bool] = []async def fake_call_llm(- *, model: str | None = None, cache_system_prompt: bool = False, **_kwargs: object+ *, model: str | None = None, cache_system_prompt: bool = False, signal_id: str | None = None, **_kwargs: object) -> SafetyJudgeResponse:captured["model"] = model+ captured["signal_id"] = signal_idcache_flags.append(cache_system_prompt)return SafetyJudgeResponse(choice=True)@@ -53,9 +54,10 @@ async def test_report_judge_runs_on_the_safety_model() -> None:)with patch(f"{MODULE_PATH}.call_llm", new=fake_call_llm):- result = await judge_report_safety(team_id=1, signals=[signal])+ result = await judge_report_safety(team_id=1, signals=[signal], signal_id="driver-signal")assert result.choice is True+ assert captured["signal_id"] == "driver-signal"assert captured["model"] == SAFETY_MODELassert cache_flags == [True]diff --git a/products/signals/backend/test/test_report_telemetry.py b/products/signals/backend/test/test_report_telemetry.pyindex 5dfe6c887dcd..ddade984b5d4 100644--- a/products/signals/backend/test/test_report_telemetry.py+++ b/products/signals/backend/test/test_report_telemetry.py@@ -1,3 +1,5 @@+from uuid import uuid4+import pytestfrom unittest.mock import patch@@ -36,11 +38,13 @@ CHART_PAYLOAD = {[(True, [CHART_PAYLOAD], 1), (False, None, 0)],)async def test_started_and_ready_fire_expected_captures(ateam, charts_enabled, charts, expected_chart_count):+ driver = uuid4()report = await database_sync_to_async(SignalReport.objects.create)(team=ateam,status=SignalReport.Status.CANDIDATE,signal_count=2,total_weight=1.2,+ triggering_signal_id=driver,)report_id = str(report.id)source_products = ["conversations", "zendesk"]@@ -87,6 +91,9 @@ async def test_started_and_ready_fire_expected_captures(ateam, charts_enabled, c# chart, so the count only reads as a rate next to the rollout state the run saw.assert events[1]["properties"]["charts_enabled"] is charts_enabledassert "charts_enabled" not in events[0]["properties"]+ await database_sync_to_async(report.refresh_from_db)()+ assert report.triggering_signal_id == driver+ assert report.researching_signal_count == 2@pytest.mark.asyncio@@ -156,6 +163,7 @@ async def test_failed_is_idempotent_when_already_failed(ateam):@pytest.mark.asyncio@pytest.mark.django_dbasync def test_in_progress_is_idempotent_when_already_in_progress(ateam):+ pending_driver = uuid4()report = await database_sync_to_async(SignalReport.objects.create)(team=ateam,status=SignalReport.Status.IN_PROGRESS,@@ -163,6 +171,8 @@ async def test_in_progress_is_idempotent_when_already_in_progress(ateam):total_weight=1.0,run_count=4,signals_at_run=5,+ researching_signal_count=1,+ pending_triggering_signal_id=pending_driver,)report_id = str(report.id)@@ -182,6 +192,8 @@ async def test_in_progress_is_idempotent_when_already_in_progress(ateam):# Run count and signals_at_run must not be advanced again on retry.assert refreshed.run_count == 4assert refreshed.signals_at_run == 5+ assert refreshed.researching_signal_count == 1+ assert refreshed.pending_triggering_signal_id == pending_driver@pytest.mark.asyncio@@ -394,27 +406,34 @@ def _seed_check_lane(team: Team) -> None:@pytest.mark.asyncio@pytest.mark.django_db@pytest.mark.parametrize(- ("run_count", "processed_signal_count", "signal_count", "expected_loop"),+ ("run_count", "processed_signal_count", "signal_count", "expected_loop", "has_pending_driver"),[# Signals landed mid-run and carried the report to its next bucket: loop rather than make# them wait for a signal that arrives after the run.- (1, 1, 2, True),- (1, 1, 9, True),+ (1, 1, 2, True, True),+ (1, 1, 9, True, True),+ (1, 1, 2, True, False),# Signals landed but the report is still short of its next bucket, so the run settles.- (2, 2, 3, False),- (3, 4, 9, False),+ (2, 2, 3, False, False),+ (3, 4, 9, False, False),# No new signals at all.- (2, 2, 2, False),+ (2, 2, 2, False, False),# This pass covered the last bucket: the report stays READY however far past it grew.- (4, 10, 15, False),+ (4, 10, 15, False, False),# Attempts are not passes: a report whose run_count was spent on runs that paused before# researching still loops when this pass leaves it at a bucket.- (9, 1, 2, True),+ (9, 1, 2, True, True),],)async def test_ready_loops_only_when_the_run_reached_the_next_bucket(- ateam, run_count: int, processed_signal_count: int, signal_count: int, expected_loop: bool-):+ ateam: Team,+ run_count: int,+ processed_signal_count: int,+ signal_count: int,+ expected_loop: bool,+ has_pending_driver: bool,+) -> None:+ driver, pending_driver = uuid4(), uuid4()await database_sync_to_async(_seed_check_lane)(ateam)report = await database_sync_to_async(SignalReport.objects.create)(team=ateam,@@ -422,6 +441,8 @@ async def test_ready_loops_only_when_the_run_reached_the_next_bucket(signal_count=signal_count,run_count=run_count,total_weight=2.0,+ triggering_signal_id=driver,+ pending_triggering_signal_id=pending_driver if has_pending_driver else None,)report_id = str(report.id)@@ -454,6 +475,7 @@ async def test_ready_loops_only_when_the_run_reached_the_next_bucket(refreshed = await database_sync_to_async(SignalReport.objects.get)(id=report_id)expected_status = SignalReport.Status.CANDIDATE if expected_loop else SignalReport.Status.READYassert refreshed.status == expected_status+ assert refreshed.triggering_signal_id == (pending_driver if has_pending_driver else driver)# Stamped by the pass that just completed, so the next bucket is measured against what this run# actually covered rather than against how many times the workflow has started.assert refreshed.signals_researched == processed_signal_countdiff --git a/products/signals/backend/test/test_safety_filter.py b/products/signals/backend/test/test_safety_filter.pyindex 91eaeaf1f826..76c931873e6d 100644--- a/products/signals/backend/test/test_safety_filter.py+++ b/products/signals/backend/test/test_safety_filter.py@@ -50,16 +50,22 @@ async def test_safety_filter_wires_prompt_source_and_model(ai_product: str,model: str,cache_system_prompt: bool,+ signal_id: str | None = None,**_kwargs: object,) -> SafetyFilterJudgeResponse:captured.update(system_prompt=system_prompt, user_prompt=user_prompt, ai_product=ai_product, model=model)+ assert signal_id is not None+ captured["signal_id"] = signal_idcache_flags.append(cache_system_prompt)return SafetyFilterJudgeResponse(safe=True)with patch(f"{MODULE_PATH}.call_llm", new=fake_call_llm), time_machine.travel("2026-09-10", tick=False):- result = await safety_filter(1, "a finding", source_product=source_product, source_type=source_type)+ result = await safety_filter(+ 1, "a finding", source_product=source_product, source_type=source_type, signal_id="driver-signal"+ )assert result.safe is True+ assert captured["signal_id"] == "driver-signal"assert captured["system_prompt"] == SAFETY_FILTER_PROMPTassert captured["model"] == SAFETY_MODELassert captured["ai_product"] == "signals_safety"diff --git a/products/signals/backend/test/test_scout_harness_api.py b/products/signals/backend/test/test_scout_harness_api.pyindex a48f7eb85896..b0e2bab7ca92 100644--- a/products/signals/backend/test/test_scout_harness_api.py+++ b/products/signals/backend/test/test_scout_harness_api.py@@ -781,7 +781,7 @@ class TestScoutHarnessRecentPerScoutAPI(APIBaseTest):response = self.client.get(self._url(), HTTP_IF_MATCH='"stale"')assert response.status_code == status.HTTP_412_PRECONDITION_FAILED- @parameterized.expand(["emit_tally", "task_run_settles", "report_deleted", "new_run"])+ @parameterized.expand(["emit_tally", "task_run_settles", "total_spend", "report_deleted", "new_run"])def test_a_change_the_summary_shows_moves_the_etag(self, change: str) -> None:report = SignalReport.objects.create(team=self.team, status=SignalReport.Status.READY)run = _make_run(self.team, emitted_report_ids=[str(report.id)])@@ -794,6 +794,9 @@ class TestScoutHarnessRecentPerScoutAPI(APIBaseTest):elif change == "task_run_settles":run.task_run.status = run.task_run.Status.COMPLETEDrun.task_run.save(update_fields=["status"])+ elif change == "total_spend":+ run.total_spend = Decimal("16.3456")+ run.save(update_fields=["total_spend"])elif change == "report_deleted":SignalReport.objects.filter(id=report.id).update(status=SignalReport.Status.DELETED)else:@@ -802,6 +805,8 @@ class TestScoutHarnessRecentPerScoutAPI(APIBaseTest):second = self.client.get(self._url(), HTTP_IF_NONE_MATCH=first["ETag"])assert second.status_code == status.HTTP_200_OKassert second["ETag"] != first["ETag"]+ if change == "total_spend":+ assert second.json()[0]["total_spend"] == 16.3456class TestScoutHarnessFindingsSummaryAPI(APIBaseTest):diff --git a/products/signals/backend/test/test_scout_harness_tools.py b/products/signals/backend/test/test_scout_harness_tools.pyindex 952004753a82..95c81b1e76d5 100644--- a/products/signals/backend/test/test_scout_harness_tools.py+++ b/products/signals/backend/test/test_scout_harness_tools.py@@ -202,14 +202,18 @@ class TestSearchRecentRuns(BaseTest):assert len(hits) == MAX_RUN_SEARCH_LIMITdef test_summary_surfaces_run_metadata(self) -> None:- # `metadata` carries the routed model triple stamped at run creation; a pre-column row- # (NULL) and a default-model run ({}) must both project as an empty dict, not None/crash.+ # New runs also carry accounting metadata; legacy NULL rows must still project as {}.routed = _create_run(self.team, metadata={"model": "@cf/zai-org/glm-5.2", "runtime_adapter": "claude"})legacy = _create_run(self.team, metadata=None)+ SignalScoutRun.objects.for_team(self.team.id).filter(pk=legacy.pk).update(metadata=None)by_run_id = {hit.run_id: hit for hit in search_recent_runs(team_id=self.team.id)}- assert by_run_id[str(routed.id)].metadata == {"model": "@cf/zai-org/glm-5.2", "runtime_adapter": "claude"}+ assert by_run_id[str(routed.id)].metadata == {+ "model": "@cf/zai-org/glm-5.2",+ "runtime_adapter": "claude",+ "spend_accounting_failed_stages": ["scout"],+ }assert by_run_id[str(legacy.id)].metadata == {}def test_summary_surfaces_status_from_linked_task_run(self) -> None:@@ -536,6 +540,7 @@ class TestRunReadsSkipTaskRunPayload(BaseTest):task_run_queries = [q["sql"] for q in captured.captured_queries if '"posthog_task_run"' in q["sql"]]assert len(task_run_queries) == 1+ assert '"total_spend"' in task_run_queries[0]for column in ("output", "artifacts", "state"):assert f'"posthog_task_run"."{column}"' not in task_run_queries[0]failed = next(hit for hit in hits if hit.run_id == str(runs[1].id))diff --git a/products/signals/backend/test/test_scout_report_persistence.py b/products/signals/backend/test/test_scout_report_persistence.pyindex 178da7322919..4d913baf59cf 100644--- a/products/signals/backend/test/test_scout_report_persistence.py+++ b/products/signals/backend/test/test_scout_report_persistence.py@@ -4,10 +4,11 @@ from datetime import UTC, datetimeimport pytestfrom posthog.test.base import BaseTest-from unittest.mock import patch+from unittest.mock import AsyncMock, Mock, patchfrom django.apps import appsfrom django.db import DatabaseError+from django.utils import timezonefrom parameterized import parameterized@@ -54,6 +55,8 @@ from products.signals.backend.scout_report import ()from products.signals.backend.scout_report.judge import resolve_authored_report_statusfrom products.signals.backend.scout_report.persistence import _report_metrics_unchanged+from products.signals.backend.spend import signal_spend_totals+from products.tasks.backend.models import Task, TaskRunPERSISTENCE_MODULE = "products.signals.backend.scout_report.persistence"@@ -147,7 +150,8 @@ class TestScoutReportPersistence(BaseTest):assert raised.value.existing.status == SignalReport.Status.READYassert SignalReport.objects.filter(team=self.team).count() == 1- def test_create_writes_report_with_bound_signals_metadata(self) -> None:+ @parameterized.expand([(False,), (True,)])+ def test_create_writes_report_with_bound_signals_metadata(self, legacy: bool) -> None:# The load-bearing contract (decision #5): each backing signal is written to the embeddings# pipeline with report_id pre-set, as a signals/signal row, so every read-side consumer# (source filter/chips, /signals/ tab, inbox-validation) resolves it like a pipeline signal.@@ -188,6 +192,38 @@ class TestScoutReportPersistence(BaseTest):doc_ids = [call.kwargs["document_id"] for call in self.emit_mock.call_args_list]assert len(set(doc_ids)) == 2assert result.signal_document_ids == doc_ids+ assert str(report.triggering_signal_id) == doc_ids[0]+ if legacy:+ report.triggering_signal_id = None+ report.save(update_fields=["triggering_signal_id"])+ task = Task.objects.create(+ team=self.team,+ title="Implement finding",+ signal_report=report,+ origin_product=Task.OriginProduct.SIGNAL_REPORT,+ )+ now = timezone.now()+ with (+ patch(+ "products.signals.backend.signal_metadata.execute_hogql_query",+ return_value=Mock(results=[(doc_ids[0], "Example observation", "{}", now, now)]),+ ),+ patch("posthog.temporal.common.client.async_connect", new=AsyncMock()),+ self.captureOnCommitCallbacks(execute=True),+ ):+ TaskRun.objects.create(+ team=self.team,+ task=task,+ environment=TaskRun.Environment.CLOUD,+ state={+ "ai_stage": "implementation",+ "unprocessed_request_ids": [],+ "token_cost": {"model": {"provider": {"cost_microusd": 10_001}}},+ },+ )+ assert signal_spend_totals(team_id=self.team.id, signal_ids=doc_ids) == {doc_ids[0]: 5.0001}+ report.refresh_from_db()+ assert str(report.triggering_signal_id) == doc_ids[0]# Provenance: a note artefact marks the report scout-authored and is attributed to the task.note = SignalReportArtefact.objects.get(report_id=result.report_id, type=SignalReportArtefact.ArtefactType.NOTE)@@ -505,7 +541,8 @@ class TestScoutReportPersistence(BaseTest):assert SignalReportArtefact.ArtefactType.SAFETY_JUDGMENT in typesassert SignalReportArtefact.ArtefactType.ACTIONABILITY_JUDGMENT in types- def test_soft_delete_re_emits_tombstone_preserving_id_and_timestamp(self) -> None:+ @patch("posthog.temporal.common.client.async_connect")+ def test_soft_delete_preserves_signal_identity(self, connect: AsyncMock) -> None:# Soft-delete is a re-emit of the same document_id with metadata.deleted=True; the original# timestamp must be preserved so the tombstone lands in the same ReplacingMergeTree partition# and supersedes the live row rather than adding a sibling. The target report must be one the@@ -529,11 +566,13 @@ class TestScoutReportPersistence(BaseTest):timestamp=ts,source_id="obs-1",)- kwargs = self.emit_mock.call_args.kwargs- assert kwargs["document_id"] == document_id- assert kwargs["timestamp"] == ts- assert kwargs["metadata"]["deleted"] is True- assert kwargs["metadata"]["report_id"] == report.report_id+ call = connect.return_value.start_workflow.call_args+ assert call.args[1].signal_id == document_id+ assert call.args[1].team_id == self.team.id+ change = call.kwargs["start_signal_args"][0]+ assert change.deleted is True+ assert change.expected_report_id == report.report_id+ self.emit_mock.assert_not_called()def test_create_rejects_duplicate_supplied_document_ids(self) -> None:# Two backing signals sharing a document_id would collapse in the ReplacingMergeTree, leavingdiff --git a/products/signals/backend/test/test_scout_trial_state.py b/products/signals/backend/test/test_scout_trial_state.pyindex 22229e82498a..d40980964e76 100644--- a/products/signals/backend/test/test_scout_trial_state.py+++ b/products/signals/backend/test/test_scout_trial_state.py@@ -861,6 +861,7 @@ class TestScoutTrialReportCapture(APIBaseTest):evidence = self.client.get(f"{base}{report_id}/signals/")assert evidence.status_code == 200assert evidence.json()["signals"][0]["source_id"] == "synthetic-observation"+ assert evidence.json()["signals"][0]["spend_accounting_failed_stages"] == []artefacts = self.client.get(f"{base}{report_id}/artefacts/")assert artefacts.status_code == 200assert artefacts.json()["count"] == detail.json()["artefact_count"]diff --git a/products/signals/backend/test/test_signal_queries.py b/products/signals/backend/test/test_signal_queries.pyindex 1933282fd794..929a3b4510c3 100644--- a/products/signals/backend/test/test_signal_queries.py+++ b/products/signals/backend/test/test_signal_queries.py@@ -4,11 +4,16 @@ import jsonimport uuidfrom datetime import UTC, datetime, timedelta+import time_machinefrom posthog.test.base import APIBaseTest, ClickhouseTestMixin, FuzzyInt-from unittest.mock import MagicMock, patch+from unittest.mock import AsyncMock, MagicMock, patch++from django.utils import timezonefrom parameterized import parameterized+from posthog.schema import EmbeddingModelName+from posthog.clickhouse.client import sync_executefrom products.signals.backend.facade.api import (@@ -27,6 +32,8 @@ from products.signals.backend.signal_metadata import (fetch_source_products_for_reports,fetch_source_references_for_report,)+from products.signals.backend.spend import SignalMetadataChange, SignalSpendUpdate, record_llm_spend+from products.signals.backend.spend_metadata import confirm_signal_spend_metadata, publish_signal_spend_metadatafrom products.signals.backend.temporal.signal_queries import (fetch_report_ids_for_scout_names,fetch_report_ids_for_scout_prefix,@@ -34,7 +41,6 @@ from products.signals.backend.temporal.signal_queries import ()_MODEL_TABLE = f"distributed_posthog_document_embeddings_{EMBEDDING_MODEL.value.replace('-', '_')}"-_EMBEDDING = [0.0] * 1536class _SignalEmbeddingsTestBase(ClickhouseTestMixin, APIBaseTest):@@ -51,6 +57,9 @@ class _SignalEmbeddingsTestBase(ClickhouseTestMixin, APIBaseTest):skill_name: str | None = None,extra: dict | None = None,source_id: str | None = None,+ model: EmbeddingModelName = EMBEDDING_MODEL,+ spend_metadata: dict | None = None,+ embedding: list[float] | None = None,) -> None:"""Write one version of a signal document straight to the model-specific embeddings table.@@ -66,9 +75,11 @@ class _SignalEmbeddingsTestBase(ClickhouseTestMixin, APIBaseTest):}if skill_name is not None or extra is not None:metadata["extra"] = {**(extra or {}), **({"skill_name": skill_name} if skill_name is not None else {})}+ metadata.update(spend_metadata or {})+ table = f"distributed_posthog_document_embeddings_{model.value.replace('-', '_')}"sync_execute(f"""- INSERT INTO {_MODEL_TABLE} (+ INSERT INTO {table} (team_id, product, document_type, rendering, document_id,timestamp, inserted_at, content, metadata, embedding,_timestamp, _offset, _partition@@ -85,7 +96,7 @@ class _SignalEmbeddingsTestBase(ClickhouseTestMixin, APIBaseTest):inserted_at,content,json.dumps(metadata),- _EMBEDDING,+ embedding if embedding is not None else [0.0] * int(model.value.rsplit("-", 1)[1]),inserted_at,0,0,@@ -449,6 +460,96 @@ class TestFetchSignalsForReportSync(_SignalEmbeddingsTestBase):assert [s["content"] for s in signals] == ["new text"]+class TestSpendPublicationVersions(_SignalEmbeddingsTestBase):+ @parameterized.expand(+ [+ ("spend", SignalMetadataChange()),+ ("move", SignalMetadataChange(report_id="new-report", expected_report_id="example-report")),+ ("delete", SignalMetadataChange(deleted=True, expected_report_id="example-report")),+ ("retract", SignalMetadataChange(deleted=True, clear_content=True)),+ ]+ )+ def test_delayed_spend_preserves_latest_total_and_metadata(self, _name: str, change: SignalMetadataChange) -> None:+ driver = str(uuid.uuid4())+ signal = SignalSpendUpdate(team_id=self.team.id, signal_id=driver)+ now = timezone.now().replace(microsecond=0)+ for model in EmbeddingModelName:+ self._emit_version(+ document_id=driver,+ report_id="example-report",+ source_product="errors",+ inserted_at=now - timedelta(seconds=2),+ model=model,+ embedding=[0.125] * int(model.value.rsplit("-", 1)[1]),+ )+ producer = MagicMock()++ def deliver(payload: dict, version: int) -> None:+ self._emit_version(+ document_id=driver,+ report_id="example-report",+ source_product="errors",+ inserted_at=datetime.fromtimestamp(version, UTC),+ model=EmbeddingModelName(payload["model_name"]),+ spend_metadata=json.loads(payload["metadata"]),+ content=payload["content"],+ embedding=payload["embedding"],+ )++ with (+ time_machine.travel(now, tick=False) as clock,+ patch("products.signals.backend.spend_metadata.producer_scope", return_value=producer),+ ):+ record_llm_spend(+ "first", token_cost_microusd=100, team_id=self.team.id, signal_id=driver, stage="actionability"+ )+ first = publish_signal_spend_metadata(signal)+ first_payloads = [call.kwargs["data"] for call in producer.__enter__.return_value.produce.call_args_list]+ for payload in first_payloads:+ deliver(payload, first.versions[payload["model_name"]])+ assert confirm_signal_spend_metadata(first)+ producer.__enter__.return_value.produce.reset_mock()+ clock.shift(timedelta(seconds=2))+ record_llm_spend(+ "second", token_cost_microusd=200, team_id=self.team.id, signal_id=driver, stage="summarization"+ )+ second = publish_signal_spend_metadata(+ SignalSpendUpdate(team_id=self.team.id, signal_id=driver, changes=[change])+ )+ assert all(second.versions[key] > version for key, version in first.versions.items())+ for call in producer.__enter__.return_value.produce.call_args_list:+ payload = call.kwargs["data"]+ deliver(payload, second.versions[payload["model_name"]])+ assert confirm_signal_spend_metadata(second)+ for payload in first_payloads:+ deliver(payload, first.versions[payload["model_name"]])+ assert confirm_signal_spend_metadata(second)+ producer.__enter__.return_value.produce.reset_mock()+ clock.shift(timedelta(seconds=2))+ record_llm_spend("third", token_cost_microusd=300, team_id=self.team.id, signal_id=driver, stage="research")+ third = publish_signal_spend_metadata(+ SignalSpendUpdate(+ team_id=self.team.id,+ signal_id=driver,+ changes=[+ SignalMetadataChange(deleted=True, expected_report_id="example-report")+ if change.report_id+ else SignalMetadataChange(report_id="must-not-move", expected_report_id="stale-report")+ ],+ )+ )+ for call in producer.__enter__.return_value.produce.call_args_list:+ payload = call.kwargs["data"]+ metadata = json.loads(payload["metadata"])+ assert metadata["total_spend"] == 0.06+ assert metadata["report_id"] == (change.report_id or "example-report")+ assert metadata["deleted"] is change.deleted+ assert payload["content"] == ("" if change.clear_content else "the signal content")+ assert set(payload["embedding"]) == ({0.0} if change.clear_content else {0.125})+ deliver(payload, third.versions[payload["model_name"]])+ assert confirm_signal_spend_metadata(third)++class TestFetchSignalStatsForSourceSlice(_SignalEmbeddingsTestBase):def test_counts_only_the_slice_and_skips_deleted_latest_versions(self) -> None:# Guards the extra_equals pushdown and the argMax dedup: a broken JSON path would leak other@@ -579,8 +680,10 @@ class TestGetOutcomesForSignalSourceSlice(_SignalEmbeddingsTestBase):class TestRetractSourceSignals(_SignalEmbeddingsTestBase):@patch("products.signals.backend.temporal.signal_queries._RETRACT_PAGE_SIZE", 2)- @patch("products.signals.backend.temporal.signal_queries.emit_embedding_request")- def test_retracts_every_page_of_the_source(self, emit: MagicMock) -> None:+ @patch("posthog.temporal.common.client.async_connect")+ def test_retracts_every_page_of_the_source(self, connect: AsyncMock) -> None:+ client = connect.return_value+ client.start_workflow = AsyncMock()for document_id in ("a", "b", "c"):self._emit_version(document_id=document_id,@@ -604,6 +707,9 @@ class TestRetractSourceSignals(_SignalEmbeddingsTestBase):)assert retracted == 3- assert sorted(call.kwargs["document_id"] for call in emit.call_args_list) == ["a", "b", "c"]- assert all(call.kwargs["content"] == "" for call in emit.call_args_list)- assert all(call.kwargs["metadata"]["deleted"] is True for call in emit.call_args_list)+ calls = client.start_workflow.call_args_list+ assert sorted(call.args[1].signal_id for call in calls) == ["a", "b", "c"]+ assert all(+ call.kwargs["start_signal_args"] == [SignalMetadataChange(deleted=True, clear_content=True)]+ for call in calls+ )diff --git a/products/signals/backend/test/test_spend.py b/products/signals/backend/test/test_spend.pynew file mode 100644index 000000000000..f651fdf0d202--- /dev/null+++ b/products/signals/backend/test/test_spend.py@@ -0,0 +1,728 @@+import json+import asyncio+from collections.abc import Callable+from datetime import timedelta+from decimal import Decimal+from types import SimpleNamespace+from uuid import uuid4++import time_machine+from posthog.test.base import BaseTest+from unittest.mock import AsyncMock, MagicMock, Mock, patch++from django.db import connection, transaction+from django.test import SimpleTestCase, override_settings+from django.utils import timezone++import httpx+from anthropic import APIResponseValidationError, AsyncAnthropic+from asgiref.sync import async_to_sync+from fakeredis import FakeRedis+from parameterized import parameterized+from structlog.testing import capture_logs++from posthog.schema import EmbeddingModelName++from posthog.llm.gateway_client import AIGatewayConfig+from posthog.llm.gateway_usage import GatewayRequestCost+from posthog.models import Team+from posthog.sync import database_sync_to_async+from posthog.token_bucket import TEST_reset_scripts++from products.ml_inference.backend.facade.contracts import DecisionResult, NoulAnswer+from products.signals.backend.emission.pipeline import check_actionability+from products.signals.backend.emission.registry import SignalEmitterOutput+from products.signals.backend.llm_spend import generate_with_spend+from products.signals.backend.models import SignalReport, SignalReportTask, SignalScoutRun, SignalSpend+from products.signals.backend.pricing import cost_to_spend+from products.signals.backend.signal_metadata import fetch_signals_for_report_sync+from products.signals.backend.spend import (+ SignalSpendUpdate,+ complete_task_spend,+ publish_report_spend,+ record_llm_spend,+ settle_signal_task_spend,+ signal_spend_summaries,+ signal_spend_totals,+)+from products.signals.backend.spend_metadata import confirm_signal_spend_metadata, publish_signal_spend_metadata+from products.signals.backend.system_one_prompts import bundled_prompt+from products.signals.backend.temporal.llm import call_llm+from products.tasks.backend.facade.task_run_signals import task_run_cost_updated+from products.tasks.backend.models import Task, TaskRun+++class TestSpendPricing(SimpleTestCase):+ @parameterized.expand([(1, 0, "0.0001"), (10_001, 1, "5.0001"), (0, 1, "4"), (123_456, 2, "20.3456")])+ def test_price_in_cents(self, cost: int, tasks: int, expected: str) -> None:+ assert cost_to_spend(cost, task_count=tasks) == Decimal(expected)+++class TestSignalSpend(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.temporal = AsyncMock()+ self.connect = patch("posthog.temporal.common.client.async_connect", new=AsyncMock(return_value=self.temporal))+ self.connect.start()+ self.addCleanup(self.connect.stop)++ @parameterized.expand([("generation",), ("task",)])+ def test_clickhouse_spend_retries_until_visible_and_tracks_later_costs(self, source: str) -> None:+ driver = str(uuid4())+ signal = SignalSpendUpdate(team_id=self.team.id, signal_id=driver)+ record_llm_spend(+ "first", token_cost_microusd=123, team_id=self.team.id, signal_id=driver, stage="actionability"+ )+ now = timezone.now()+ metadata = {"report_id": "moved-report", "deleted": True, "extra": {"example": 1}, "total_spend": 0}+ rows: dict[str, list] = {}+ producer = Mock()+ scope = MagicMock()+ scope.__enter__.return_value = producer+ with (+ time_machine.travel(now + timedelta(seconds=2), tick=False) as clock,+ patch("products.signals.backend.spend_metadata.producer_scope", return_value=scope) as produce_scope,+ patch(+ "products.signals.backend.spend_metadata.execute_hogql_query",+ side_effect=lambda **kwargs: Mock(results=rows.get(kwargs["placeholders"]["model_name"].value, [])),+ ),+ ):+ with self.assertRaisesRegex(RuntimeError, "not yet visible"):+ publish_signal_spend_metadata(signal)+ for model in EmbeddingModelName:+ rows[model.value] = [(driver, ("Example finding", json.dumps(metadata), now, [0.5], now))]+ produce_scope.side_effect = RuntimeError("Kafka unavailable")+ with self.assertRaises(RuntimeError):+ publish_signal_spend_metadata(signal)+ produce_scope.side_effect = None+ publication = publish_signal_spend_metadata(signal)+ assert producer.produce.call_count == len(EmbeddingModelName)+ for _ in range(5):+ assert not confirm_signal_spend_metadata(publication)+ assert producer.produce.call_count == len(EmbeddingModelName)+ for call in producer.produce.call_args_list:+ payload = call.kwargs["data"]+ assert call.kwargs["key"] == f"signals:{self.team.id}:{driver}:{payload['model_name']}"+ assert json.loads(payload["metadata"]) == {+ **metadata,+ "total_spend": 0.0123,+ "spend_accounting_failed_stages": [],+ }+ assert payload["content"] == "Example finding"+ assert payload["embedding"] == [0.5]+ assert payload["timestamp"] == now.strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]+ rows[payload["model_name"]] = [+ (driver, (payload["content"], payload["metadata"], now, [0.5], timezone.now()))+ ]+ producer.reset_mock()+ assert confirm_signal_spend_metadata(publication)+ assert publish_signal_spend_metadata(signal) == publication+ producer.produce.assert_not_called()+ if source == "generation":+ record_llm_spend(+ "later",+ token_cost_microusd=123,+ team_id=self.team.id,+ signal_id=driver,+ stage="report_safety_judge",+ )+ expected = 0.0246+ else:+ report = SignalReport.objects.create(team=self.team, triggering_signal_id=driver)+ run = self._run(report=report)+ self._set_task_cost(run, 123)+ expected = 4.0246+ with self.assertRaisesRegex(RuntimeError, "strictly newer"):+ publish_signal_spend_metadata(signal)+ producer.produce.assert_not_called()+ clock.shift(2)+ newer = publish_signal_spend_metadata(signal)+ assert all(newer.versions[model] > version for model, version in publication.versions.items())+ assert producer.produce.call_count == len(EmbeddingModelName)+ for call in producer.produce.call_args_list:+ payload = call.kwargs["data"]+ assert json.loads(payload["metadata"])["total_spend"] == expected+ rows[payload["model_name"]] = [+ (driver, (payload["content"], payload["metadata"], now, [0.5], timezone.now()))+ ]+ assert confirm_signal_spend_metadata(newer)+ record_llm_spend(+ None, token_cost_microusd=None, team_id=self.team.id, signal_id=driver, stage="summarization"+ )+ producer.reset_mock()+ clock.shift(2)+ publish_signal_spend_metadata(signal)+ assert producer.produce.call_count == len(EmbeddingModelName)+ assert all(+ json.loads(call.kwargs["data"]["metadata"])["spend_accounting_failed_stages"] == ["summarization"]+ for call in producer.produce.call_args_list+ )+ with patch(+ "products.signals.backend.signal_metadata.execute_hogql_query",+ return_value=Mock(results=[(driver, "Example finding", json.dumps(metadata), now, now)]),+ ):+ signal_row = fetch_signals_for_report_sync(self.team, str(uuid4()))[0]+ assert signal_row["total_spend"] == metadata["total_spend"]++ @parameterized.expand([("priced", 12_345), ("free", 0), ("cancelled", None), ("missing_id", None)])+ async def test_generation_waits_for_spend_without_regenerating(self, outcome: str, cost: int | None) -> None:+ driver = str(uuid4())+ response = Mock(_request_id=None if outcome == "missing_id" else "generation-1")+ generate = AsyncMock(return_value=response)+ with (+ patch(+ "products.signals.backend.llm_spend.fetch_gateway_cost",+ new=AsyncMock(+ side_effect=[None, None, GatewayRequestCost(model="model", provider="provider", cost_microusd=cost)]+ if cost is not None+ else [None]+ ),+ ) as lookup,+ patch(+ "products.signals.backend.llm_spend.asyncio.sleep",+ new=AsyncMock(side_effect=asyncio.CancelledError if outcome == "cancelled" else None),+ ),+ ):+ generation = generate_with_spend(+ generate(),+ gateway=AIGatewayConfig(url="https://gateway.example.com/v1", api_key="test-key"),+ team_id=self.team.id,+ signal_id=driver,+ stage="summarization",+ )+ if outcome == "cancelled":+ with self.assertRaises(asyncio.CancelledError):+ await generation+ elif outcome == "missing_id":+ priced = await generation+ assert priced.response is response+ assert priced.spend is None+ lookup.assert_not_awaited()+ else:+ priced = await generation+ assert priced.response is response+ assert cost is not None+ assert priced.spend == Decimal(cost) / 10_000+ assert lookup.await_count == 3+ generate.assert_awaited_once()+ spend = await database_sync_to_async(lambda: SignalSpend.objects.for_team(self.team.id).get(signal_id=driver))()+ assert spend.token_cost_microusd == cost+ assert spend.accounting_failed is (cost is None)+ assert spend.stage == "summarization"++ @parameterized.expand([("unavailable",), ("hung",), ("activity_deadline",)])+ async def test_usage_timeout_preserves_completed_generation(self, outcome: str) -> None:+ driver = str(uuid4())+ response = Mock(_request_id="generation-1")+ generate = AsyncMock(return_value=response)++ async def lookup(*args: object, **kwargs: object) -> None:+ if outcome == "hung":+ await asyncio.Event().wait()+ return None++ now = timezone.now()+ info = SimpleNamespace(+ started_time=now - timedelta(seconds=5),+ scheduled_time=now - timedelta(seconds=5),+ start_to_close_timeout=timedelta(seconds=5),+ schedule_to_close_timeout=timedelta(seconds=60),+ )+ with (+ patch("products.signals.backend.llm_spend.USAGE_WAIT_SECONDS", 0.01),+ patch(+ "products.signals.backend.llm_spend.activity.in_activity", return_value=outcome == "activity_deadline"+ ),+ patch("products.signals.backend.llm_spend.activity.info", return_value=info),+ patch("products.signals.backend.llm_spend.fetch_gateway_cost", new=AsyncMock(side_effect=lookup)),+ ):+ priced = await generate_with_spend(+ generate(),+ gateway=AIGatewayConfig(url="https://gateway.example.com/v1", api_key="test-key"),+ team_id=self.team.id,+ signal_id=driver,+ stage="actionability",+ )+ assert priced.response is response+ assert priced.spend is None+ generate.assert_awaited_once()+ receipt = await database_sync_to_async(+ lambda: SignalSpend.objects.for_team(self.team.id).get(signal_id=driver)+ )()+ assert receipt.source_id == "generation-1"+ assert receipt.accounting_failed is True+ assert receipt.stage == "actionability"++ @parameterized.expand(+ [(gateway, failure) for gateway in (True, False) for failure in ("timeout", "transport", "cancelled")]+ )+ async def test_failed_generation_records_stage_before_propagating(self, use_gateway: bool, failure: str) -> None:+ driver = str(uuid4())+ error = {+ "timeout": TimeoutError(),+ "transport": httpx.ReadError("connection lost"),+ "cancelled": asyncio.CancelledError(),+ }[failure]+ generate = AsyncMock(side_effect=error)+ with self.assertRaises(type(error)):+ await generate_with_spend(+ generate(),+ gateway=AIGatewayConfig(url="https://gateway.example.com/v1", api_key="test-key")+ if use_gateway+ else None,+ team_id=self.team.id,+ signal_id=driver,+ stage="actionability",+ )+ spend = await database_sync_to_async(lambda: SignalSpend.objects.for_team(self.team.id).get(signal_id=driver))()+ assert spend.accounting_failed is True+ assert spend.stage == "actionability"+ generate.assert_awaited_once()++ @parameterized.expand([("invalid_json",), ("invalid_message",)])+ @override_settings(AI_GATEWAY_URL="https://gateway.example.com/v1", AI_GATEWAY_API_KEY="phs_test")+ async def test_unreadable_generation_preserves_request_id_or_records_failed_stage(self, failure: str) -> None:+ driver = str(uuid4())+ transport = httpx.MockTransport(+ lambda _request: httpx.Response(+ 200,+ headers={+ "x-request-id": "generation-1",+ "request-id": "generation-1",+ "content-type": "application/json",+ },+ content=b"not-json" if failure == "invalid_json" else b"{}",+ )+ )+ async with AsyncAnthropic(+ api_key="test-key",+ http_client=httpx.AsyncClient(transport=transport),+ _strict_response_validation=True,+ ) as client:+ with (+ patch("products.signals.backend.temporal.llm.build_async_anthropic_client", return_value=client),+ patch(+ "products.signals.backend.llm_spend.fetch_gateway_cost",+ new=AsyncMock(+ return_value=GatewayRequestCost(model="model", provider="provider", cost_microusd=123)+ ),+ ),+ self.assertRaises(json.JSONDecodeError if failure == "invalid_json" else APIResponseValidationError),+ ):+ await call_llm(+ team_id=self.team.id,+ signal_id=driver,+ system_prompt="Example prompt",+ user_prompt="Example finding",+ validate=lambda text: text,+ stage="safety",+ ai_product="signals",+ )+ spend = await database_sync_to_async(lambda: SignalSpend.objects.for_team(self.team.id).get(signal_id=driver))()+ assert spend.stage == "safety"+ assert spend.accounting_failed is (failure == "invalid_json")+ if failure == "invalid_json":+ assert spend.source_id.startswith("unknown-")+ else:+ assert spend.source_id == "generation-1"++ @parameterized.expand([("gateway",), ("legacy",)])+ async def test_parallel_generations_record_every_attempt_for_the_explicit_owner(self, mode: str) -> None:+ drivers = [str(uuid4()), str(uuid4())]+ attempts: dict[str, int] = {}++ async def respond(request: httpx.Request) -> httpx.Response:+ key = json.loads(request.content)["messages"][0]["content"]+ attempts[key] = attempts.get(key, 0) + 1+ return httpx.Response(+ 200,+ headers={"x-request-id": f"{key}-{attempts[key]}", "request-id": f"{key}-{attempts[key]}"},+ json={+ "id": "msg_example",+ "type": "message",+ "role": "assistant",+ "model": "claude-sonnet-5",+ "content": [+ {"type": "text", "text": "invalid" if key == "request-a" and attempts[key] == 1 else "ok"}+ ],+ "stop_reason": "end_turn",+ "usage": {"input_tokens": 10, "output_tokens": 1},+ },+ )++ def validate(text: str) -> str:+ if text != "ok":+ raise ValueError("Invalid generation")+ return text++ async def call(driver: str | None, request_id: str) -> str:+ return await call_llm(+ team_id=self.team.id,+ signal_id=driver,+ system_prompt="Example prompt",+ user_prompt=request_id,+ validate=validate,+ stage="actionability",+ ai_product="signals",+ model="claude-sonnet-5",+ )++ with (+ override_settings(+ AI_GATEWAY_URL="" if mode == "legacy" else "https://gateway.example.com/v1",+ AI_GATEWAY_API_KEY="" if mode == "legacy" else "phs_test",+ LLM_GATEWAY_URL="https://legacy.example.com",+ LLM_GATEWAY_API_KEY="test-key",+ ),+ patch("httpx.AsyncHTTPTransport.handle_async_request", new=AsyncMock(side_effect=respond)),+ patch(+ "products.signals.backend.llm_spend.fetch_gateway_cost",+ new=AsyncMock(return_value=GatewayRequestCost(model="model", provider="provider", cost_microusd=123)),+ ),+ ):+ results = await asyncio.gather(call(drivers[0], "request-a"), call(drivers[1], "request-b"))+ assert list(results) == ["ok", "ok"]+ assert await call(None, "unattributed") == "ok"+ rows = await database_sync_to_async(+ lambda: list(+ SignalSpend.objects.for_team(self.team.id).values(+ "source_id", "signal_id", "stage", "accounting_failed"+ )+ )+ )()+ assert await database_sync_to_async(+ lambda: signal_spend_totals(team_id=self.team.id, signal_ids=drivers)+ )() == {drivers[0]: 0.0246 if mode == "gateway" else 0, drivers[1]: 0.0123 if mode == "gateway" else 0}+ assert len(rows) == 3+ assert sorted(str(row["signal_id"]) for row in rows) == sorted([drivers[0], drivers[0], drivers[1]])+ assert all(row["stage"] == "actionability" for row in rows)+ if mode == "gateway":+ assert {row["source_id"]: str(row["signal_id"]) for row in rows} == {+ "request-a-1": drivers[0],+ "request-a-2": drivers[0],+ "request-b-1": drivers[1],+ }+ assert not any(row["accounting_failed"] for row in rows)+ else:+ assert all(row["accounting_failed"] for row in rows)+ assert all(row["source_id"].startswith("unknown-") for row in rows)++ @parameterized.expand(+ [+ ("system-one-only", True),+ ("system-one-shadow", True),+ ("traditional-shadow", True),+ ("traditional-only", False),+ ]+ )+ @override_settings(AI_GATEWAY_URL="https://gateway.example.com/v1", AI_GATEWAY_API_KEY="phs_test")+ async def test_system_one_is_excluded_from_spend_while_traditional_calls_are_accounted(+ self, mode: str, request_id_available: bool+ ) -> None:+ driver = str(uuid4())+ output = SignalEmitterOutput(+ signal_id=driver,+ source_id="issue-1",+ source_product="linear",+ source_type="issue",+ description="An example finding",+ weight=1.0,+ extra={},+ )+ result = DecisionResult(+ model="jevk5-fp8-0.2",+ answers={"actionable": NoulAnswer(probability=0.98)},+ input_tokens=10,+ )+ client = Mock()+ client.messages.create = AsyncMock(+ return_value=Mock(+ content=[Mock(type="text", text="ACTIONABLE" if request_id_available else "NOT_ACTIONABLE")],+ _request_id="traditional-request" if request_id_available else None,+ )+ )+ TEST_reset_scripts()+ try:+ with (+ patch(+ "products.signals.backend.llm_spend.fetch_gateway_cost",+ new=AsyncMock(+ return_value=GatewayRequestCost(model="model", provider="provider", cost_microusd=123)+ ),+ ),+ patch("products.signals.backend.system_one_decision.get_client", return_value=FakeRedis()),+ patch("products.signals.backend.system_one_decision.model_mode", new=AsyncMock(return_value=mode)),+ patch("products.signals.backend.system_one_decision.posthoganalytics.capture"),+ patch(+ "products.signals.backend.system_one_decision.decision_api.decide_when_available",+ return_value=result,+ ),+ ):+ assert (+ await check_actionability(+ client,+ self.team.id,+ output,+ "Is this actionable? {description}",+ gateway_mode=True,+ system_one_prompt=bundled_prompt("example-prompt", "policy", "Actionable?", 0.9),+ )+ is request_id_available+ )+ finally:+ TEST_reset_scripts()+ rows = await database_sync_to_async(+ lambda: list(+ SignalSpend.objects.for_team(self.team.id).values(+ "source_id", "signal_id", "stage", "accounting_failed"+ )+ )+ )()+ if mode == "system-one-only":+ assert rows == []+ else:+ assert len(rows) == 1+ assert str(rows[0]["signal_id"]) == driver+ if request_id_available:+ assert rows[0]["source_id"] == "traditional-request"+ else:+ assert rows[0]["source_id"].startswith("unknown-")+ assert rows[0]["stage"] == "actionability"+ assert rows[0]["accounting_failed"] is (not request_id_available)+ client.messages.create.assert_awaited_once()++ def _run(self, *, report: SignalReport | None = None, task: Task | None = None, stage: str = "research") -> TaskRun:+ task = task or Task.objects.create(+ team=self.team,+ title="Example research",+ description="",+ origin_product=Task.OriginProduct.SIGNAL_REPORT,+ signal_report=report,+ )+ return TaskRun.objects.create(+ team=self.team,+ task=task,+ environment=TaskRun.Environment.CLOUD,+ status=TaskRun.Status.IN_PROGRESS,+ state={"ai_stage": stage, "unprocessed_request_ids": [], "token_cost": {}},+ )++ def _set_task_cost(self, run: TaskRun, cost: int | None, *, pending: bool = False) -> None:+ run.refresh_from_db()+ state = dict(run.state or {})+ state["unprocessed_request_ids"] = ["pending-request"] if cost is None or pending else []+ if cost is not None:+ state["token_cost"] = {"model-a": {"provider-a": {"cost_microusd": cost}}}+ run.state = state+ run.save(update_fields=["state"])+ with self.captureOnCommitCallbacks(execute=True):+ task_run_cost_updated.send(sender=TaskRun, run_id=run.id, team_id=self.team.id)++ @parameterized.expand([("research",), ("repo_selection",), ("implementation",)])+ def test_late_task_cost_updates_charge_driver_once_and_preserve_fractional_cents(self, resumed_stage: str) -> None:+ driver, other = str(uuid4()), str(uuid4())+ report = SignalReport.objects.create(team=self.team, triggering_signal_id=driver)+ research = self._run(report=report, stage=resumed_stage)+ implementation = self._run(report=report, stage="implementation")+ self._set_task_cost(research, 10_001)+ self._set_task_cost(implementation, 25_002)+ assert signal_spend_totals(team_id=self.team.id, signal_ids=[driver, other]) == {driver: 11.5003}++ report.triggering_signal_id = other+ report.save(update_fields=["triggering_signal_id"])+ self._set_task_cost(research, 10_004)+ assert signal_spend_totals(team_id=self.team.id, signal_ids=[driver, other]) == {driver: 11.5006}+ assert SignalSpend.objects.for_team(self.team.id).count() == 2+ self.temporal.reset_mock()+ with self.captureOnCommitCallbacks(execute=True):+ try:+ with transaction.atomic():+ task_run_cost_updated.send(sender=TaskRun, run_id=research.id, team_id=self.team.id)+ raise RuntimeError("roll back task cost")+ except RuntimeError:+ pass+ self.temporal.start_workflow.assert_not_called()++ rerun = self._run(task=research.task, stage="")+ self._set_task_cost(rerun, 1)+ assert signal_spend_totals(team_id=self.team.id, signal_ids=[driver, other]) == {driver: 15.5007}+ assert SignalSpend.objects.for_team(self.team.id).get(source_id=str(rerun.id)).stage == resumed_stage++ def test_task_cost_callback_updates_spend_synchronously_without_publishing(self) -> None:+ driver = str(uuid4())+ report = SignalReport.objects.create(team=self.team, triggering_signal_id=driver)+ run = self._run(report=report)+ with transaction.atomic():+ self._set_task_cost(run, 10_001)+ assert signal_spend_totals(team_id=self.team.id, signal_ids=[driver]) == {driver: 5.0001}+ self.temporal.start_workflow.assert_not_called()+ try:+ with transaction.atomic():+ self._set_task_cost(run, 20_002)+ assert signal_spend_totals(team_id=self.team.id, signal_ids=[driver]) == {driver: 6.0002}+ raise RuntimeError("roll back task cost")+ except RuntimeError:+ pass+ assert signal_spend_totals(team_id=self.team.id, signal_ids=[driver]) == {driver: 5.0001}+ self.temporal.start_workflow.assert_not_called()++ @parameterized.expand(+ [+ (SignalReport.Status.CANDIDATE, None),+ (SignalReport.Status.READY, None),+ (SignalReport.Status.READY, TaskRun.Status.COMPLETED),+ (SignalReport.Status.READY, TaskRun.Status.FAILED),+ (SignalReport.Status.READY, TaskRun.Status.CANCELLED),+ ]+ )+ def test_report_publishes_at_research_or_implementation_completion(+ self, report_status: str, implementation_status: str | None+ ) -> None:+ driver = str(uuid4())+ report = SignalReport.objects.create(team=self.team, triggering_signal_id=driver, status=report_status)+ research = self._run(report=report)+ self._set_task_cost(research, 10_001)+ implementation = None+ if implementation_status:+ implementation = self._run(report=report, stage="implementation")+ SignalReportTask.objects.create(+ team=self.team, report=report, task_id=implementation.task_id, relationship="implementation"+ )+ self._set_task_cost(implementation, 20_002)+ async_to_sync(publish_report_spend)(team_id=self.team.id, report_id=str(report.id))+ if implementation is not None:+ self.temporal.start_workflow.assert_not_called()+ assert implementation_status is not None+ implementation.status = implementation_status+ implementation.save(update_fields=["status"])+ complete_task_spend(team_id=self.team.id, run_id=str(implementation.id))+ self.temporal.start_workflow.assert_awaited_once()+ assert self.temporal.start_workflow.call_args.args[1] == SignalSpendUpdate(+ team_id=self.team.id, signal_id=driver+ )+ self.temporal.start_workflow.return_value.result.assert_awaited_once()+ assert signal_spend_totals(team_id=self.team.id, signal_ids=[driver]) == {+ driver: 11.0003 if implementation else 5.0001+ }++ @parameterized.expand([(False,), (True,)])+ @override_settings(SANDBOX_AI_GATEWAY_URL="https://gateway.example", SANDBOX_AI_GATEWAY_MINT_KEY="test-key")+ def test_completion_settles_pending_task_usage_inline(self, is_scout: bool) -> None:+ driver = str(uuid4())+ report = SignalReport.objects.create(team=self.team, triggering_signal_id=driver)+ run = self._run(report=None if is_scout else report)+ scout = (+ SignalScoutRun.objects.for_team(self.team.id).create(+ team=self.team, task_run=run, skill_name="example-scout", skill_version=1+ )+ if is_scout+ else None+ )+ run.state = {"ai_stage": "research", "unprocessed_request_ids": ["pending-request"], "token_cost": {}}+ run.status = TaskRun.Status.COMPLETED+ run.save(update_fields=["state", "status"])+ with patch(+ "products.tasks.backend.logic.services.gateway_usage._fetch_gateway_cost",+ new=AsyncMock(return_value=GatewayRequestCost(model="example", provider="example", cost_microusd=123_456)),+ ) as fetch:+ if scout:+ complete_task_spend(team_id=self.team.id, run_id=str(run.id))+ else:+ settle_signal_task_spend(team_id=self.team.id, signal_id=driver)+ fetch.assert_awaited_once_with("pending-request")+ if scout:+ scout.refresh_from_db()+ assert scout.total_spend == Decimal("16.3456")+ assert scout.metadata is not None+ assert scout.metadata["spend_accounting_failed_stages"] == []+ else:+ summary = signal_spend_summaries(team_id=self.team.id, signal_ids=[driver])[driver]+ assert summary.total_spend == 16.3456+ assert summary.failed_stages == []+ self.temporal.start_workflow.assert_not_called()++ def test_one_shot_receipts_preserve_known_spend_and_record_failed_stage(self) -> None:+ driver = str(uuid4())+ for request_id, cost in [("one-shot-1", None), ("one-shot-2", 9), ("one-shot-2", None)]:+ record_llm_spend(+ request_id, token_cost_microusd=cost, team_id=self.team.id, signal_id=driver, stage="actionability"+ )+ summary = signal_spend_summaries(team_id=self.team.id, signal_ids=[driver])[driver]+ assert summary.total_spend == 0.0009+ assert summary.failed_stages == ["actionability"]+ for _ in range(2):+ record_llm_spend(+ "one-shot-1", token_cost_microusd=1, team_id=self.team.id, signal_id=driver, stage="actionability"+ )+ assert SignalSpend.objects.for_team(self.team.id).count() == 2+ assert signal_spend_totals(team_id=self.team.id, signal_ids=[driver]) == {driver: 0.001}+ assert signal_spend_summaries(team_id=self.team.id, signal_ids=[driver])[driver].failed_stages == []+ record_llm_spend(None, token_cost_microusd=None, team_id=self.team.id, signal_id=driver, stage="summarization")+ other_team = Team.objects.create(organization=self.organization, name="Other project")+ assert signal_spend_totals(team_id=other_team.id, signal_ids=[driver]) == {}++ @parameterized.expand([(False,), (True,)])+ def test_scout_persists_spend_in_cents_after_failed_run_settles(self, settled_before_owner: bool) -> None:+ task_run = self._run()+ if settled_before_owner:+ self._set_task_cost(task_run, 123_456, pending=True)+ with self.captureOnCommitCallbacks(execute=True):+ scout = SignalScoutRun.objects.for_team(self.team.id).create(+ team=self.team,+ task_run=task_run,+ skill_name="example-scout",+ skill_version=1,+ )+ assert scout.total_spend is None+ scout.refresh_from_db()+ assert scout.total_spend == (Decimal("16.3456") if settled_before_owner else Decimal("4"))+ assert scout.metadata is not None+ assert scout.metadata["spend_accounting_failed_stages"] == (["scout"] if settled_before_owner else [])+ task_run.status = TaskRun.Status.FAILED+ task_run.save(update_fields=["status"])+ self._set_task_cost(task_run, 123_456)+ scout.refresh_from_db()+ assert scout.total_spend == Decimal("16.3456")+ self._set_task_cost(task_run, None)+ scout.refresh_from_db()+ assert scout.total_spend == Decimal("16.3456")+ assert scout.metadata is not None+ assert scout.metadata["spend_accounting_failed_stages"] == ["scout"]+ self._set_task_cost(task_run, 123_457)+ scout.refresh_from_db()+ assert scout.total_spend == Decimal("16.3457")+ assert scout.metadata is not None+ assert scout.metadata["spend_accounting_failed_stages"] == []++ @parameterized.expand([("generation", "actionability"), ("task", "research"), ("task_cost", "task_cost_update")])+ def test_accounting_database_failure_does_not_abort_pipeline_transaction(self, source: str, stage: str) -> None:+ driver = str(uuid4())+ report = SignalReport.objects.create(team=self.team, triggering_signal_id=driver)+ existing_run = self._run(report=report) if source == "task_cost" else None++ def fail_spend_query(+ execute: Callable[..., object], sql: str, params: object, many: bool, context: object+ ) -> object:+ if sql.startswith('INSERT INTO "signals_signalspend"') or (+ source == "task_cost" and sql.startswith("SELECT") and '"signals_signalspend"' in sql+ ):+ return execute("SELECT 1 / 0", (), False, context)+ return execute(sql, params, many, context)++ with capture_logs() as logs, connection.execute_wrapper(fail_spend_query):+ if existing_run is not None:+ with self.captureOnCommitCallbacks(execute=True):+ task_run_cost_updated.send(sender=TaskRun, run_id=existing_run.id, team_id=self.team.id)+ elif source == "task":+ run = self._run(report=report)+ assert TaskRun.objects.filter(id=run.id).exists()+ else:+ record_llm_spend(+ "example-request",+ token_cost_microusd=123,+ team_id=self.team.id,+ signal_id=driver,+ stage="actionability",+ )+ assert SignalReport.objects.filter(id=report.id).exists()+ assert any(log["event"] == "signals.spend.accounting_failed" and log["stage"] == stage for log in logs)diff --git a/products/signals/backend/test/test_spend_workflow.py b/products/signals/backend/test/test_spend_workflow.pynew file mode 100644index 000000000000..5f583fb27aa1--- /dev/null+++ b/products/signals/backend/test/test_spend_workflow.py@@ -0,0 +1,89 @@+import asyncio+from uuid import uuid4++import pytest+from unittest.mock import AsyncMock, patch++from django.test import override_settings++from temporalio import activity+from temporalio.exceptions import ApplicationError+from temporalio.testing import WorkflowEnvironment+from temporalio.worker import UnsandboxedWorkflowRunner, Worker++from products.signals.backend.spend import (+ SignalMetadataChange,+ SignalSpendPublication,+ SignalSpendSummary,+ SignalSpendUpdate,+ publish_signal_spend,+ submit_signal_metadata_updates,+)+from products.signals.backend.temporal.spend import UpdateSignalSpendWorkflow+++async def test_spend_updates_retry_and_serialize_updates_arriving_during_and_after_a_write() -> None:+ queue = f"spend-test-{uuid4()}"+ driver = str(uuid4())+ write_started, release_write = asyncio.Event(), asyncio.Event()+ latest_spend = 1+ stored: list[int] = []+ changes: list[SignalMetadataChange] = []+ attempts = 0++ @activity.defn(name="update_signal_spend_activity")+ async def write_metadata(input: SignalSpendUpdate) -> SignalSpendPublication:+ nonlocal attempts+ assert (input.team_id, input.signal_id) == (1, driver)+ attempts += 1+ if attempts == 1:+ raise ApplicationError("ClickHouse row not visible yet", type="SignalSpendNotVisible")+ spend = latest_spend+ if attempts == 2:+ write_started.set()+ await release_write.wait()+ stored.append(spend)+ changes.extend(input.changes)+ return SignalSpendPublication(+ signal=input, summary=SignalSpendSummary(total_spend=spend, failed_stages=[]), versions={}+ )++ confirmation_attempts = 0++ @activity.defn(name="confirm_signal_spend_activity")+ async def confirm_metadata(input: SignalSpendPublication) -> None:+ nonlocal confirmation_attempts+ confirmation_attempts += 1+ if confirmation_attempts == 1:+ raise ApplicationError("ClickHouse ingestion delayed", type="SignalSpendNotVisible")++ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with Worker(+ env.client,+ task_queue=queue,+ workflows=[UpdateSignalSpendWorkflow],+ activities=[write_metadata, confirm_metadata],+ workflow_runner=UnsandboxedWorkflowRunner(),+ ):+ with (+ override_settings(VIDEO_EXPORT_TASK_QUEUE=queue),+ patch("posthog.temporal.common.client.async_connect", new=AsyncMock(return_value=env.client)),+ ):+ publication = asyncio.create_task(publish_signal_spend(team_id=1, signal_id=driver))+ await asyncio.wait_for(write_started.wait(), timeout=20)+ assert not publication.done()+ latest_spend = 2+ change = SignalMetadataChange(report_id="new-report", expected_report_id="old-report")+ await submit_signal_metadata_updates(team_id=1, signal_ids=[driver], change=change)+ handle = env.client.get_workflow_handle(f"signal-spend-1-{driver}")+ await handle.signal("refresh")+ release_write.set()+ await asyncio.wait_for(publication, timeout=20)+ assert stored == [1, 2]+ assert changes == [change]++ latest_spend = 3+ await publish_signal_spend(team_id=1, signal_id=driver)+ assert stored == [1, 2, 3]+ assert confirmation_attempts == 4diff --git a/products/signals/backend/test/test_summary_workflow.py b/products/signals/backend/test/test_summary_workflow.pyindex b77fa40eb8da..1d5b4805c81f 100644--- a/products/signals/backend/test/test_summary_workflow.py+++ b/products/signals/backend/test/test_summary_workflow.py@@ -200,6 +200,7 @@ class _Recorder:self.safety_checks = 0self.repo_selections = 0self.researches = 0+ self.spend_publications = 0self.reverts = 0self.resets = 0self.failures = 0@@ -298,6 +299,10 @@ async def _run_summary_workflow(recorder: _Recorder) -> None:async def fake_publish(input: PublishReportCompletedInput) -> None:return None+ @activity.defn(name="publish_report_spend_activity")+ async def fake_publish_spend(input: SignalReportSummaryWorkflowInputs) -> None:+ recorder.spend_publications += 1+@activity.defn(name="revert_report_to_candidate_activity")async def fake_revert(input: RevertReportToCandidateInput) -> None:recorder.reverts += 1@@ -330,6 +335,7 @@ async def _run_summary_workflow(recorder: _Recorder) -> None:fake_mark_pending,fake_mark_ready,fake_publish,+ fake_publish_spend,fake_revert,fake_reset,fake_failed,@@ -378,6 +384,7 @@ async def test_open_gates_let_the_run_flow_through():await _run_summary_workflow(recorder)assert recorder.gate_checks == ["summary_entry", "pre_repo_selection", "pre_research"]assert recorder.researches == 1+ assert recorder.spend_publications == 1assert recorder.reverts == 0assert recorder.failures == 0@@ -433,6 +440,7 @@ async def test_empty_first_fetch_is_retried_and_run_proceeds():await _run_summary_workflow(recorder)assert recorder.fetches == 3assert recorder.researches == 1+ assert recorder.spend_publications == 1assert recorder.failures == 0assert recorder.assigned_signal_checks == 0diff --git a/products/signals/backend/test/test_wait_for_signal_in_clickhouse.py b/products/signals/backend/test/test_wait_for_signal_in_clickhouse.pyindex 35e4db4c3707..ea74872b3606 100644--- a/products/signals/backend/test/test_wait_for_signal_in_clickhouse.py+++ b/products/signals/backend/test/test_wait_for_signal_in_clickhouse.py@@ -78,15 +78,19 @@ async def _run([pytest.param(WaitForClickHouseMode.OPTIMISTIC, 0, id="optimistic_trusts_store_and_skips_clickhouse"),pytest.param(WaitForClickHouseMode.CH_CONFIRMED, 1, id="ch_confirmed_runs_single_confirm"),+ pytest.param(WaitForClickHouseMode.METADATA_UPDATE, 0, id="metadata_writer_confirms_its_own_version"),],)async def test_store_confirmation_short_circuits(mode, expected_ch_queries):signals = _signals(2)+ client = MagicMock()+ client.get_workflow_handle.return_value.result = AsyncMock()with (patch(f"{MODULE}.Team", _team_model_mock()),patch(f"{MODULE}.async_get_recently_seen_documents", side_effect=_store_returning(timedelta(0))) as store,patch(f"{MODULE}.execute_hogql_query_with_retry", AsyncMock(return_value=_ch_result(2))) as ch,patch(f"{MODULE}.asyncio.sleep", AsyncMock()) as sleep,+ patch(f"{MODULE}.async_connect", AsyncMock(return_value=client)),):await _run(signals, mode=mode)@@ -94,8 +98,10 @@ async def test_store_confirmation_short_circuits(mode, expected_ch_queries):# touching ClickHouse at all, ch_confirmed with exactly one confirm query — and# neither should sleep through a poll interval.assert ch.await_count == expected_ch_queries- assert store.call_count == 1+ assert store.call_count == (0 if mode == WaitForClickHouseMode.METADATA_UPDATE else 1)assert sleep.await_count == 0+ if mode == WaitForClickHouseMode.METADATA_UPDATE:+ assert client.get_workflow_handle.return_value.result.await_count == len(signals)@pytest.mark.asynciodiff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.tsindex 63b063db1305..06059a05f6bb 100644--- a/products/signals/frontend/generated/api.schemas.ts+++ b/products/signals/frontend/generated/api.schemas.ts@@ -2531,6 +2531,13 @@ export interface NoMatchMetadataApi {export type SignalMatchMetadataApi = MatchedMetadataApi | NoMatchMetadataApiexport interface SignalNodeApi {+ /**+ * Accounted customer spend in USD cents, including fractional cents. May be partial; null for untracked signals.+ * @nullable+ */+ readonly total_spend: number | null+ /** Pipeline stages with generations whose spend could not be accounted for. Cleared when accounting recovers. */+ readonly spend_accounting_failed_stages: readonly string[]/** ClickHouse document id of the signal. */signal_id: string/** The signal's human-readable description. */@@ -6213,6 +6220,11 @@ export const RunStatusEnumApi = {* Status and timestamps flow from the linked `tasks.TaskRun`.*/export interface SignalScoutRunSummaryApi {+ /**+ * Accounted customer spend in USD cents, including fractional cents. May be partial; null for untracked runs.+ * @nullable+ */+ readonly total_spend: number | null/** UUID of the bridge row. */run_id: string/** Canonical skill name the run executed (e.g. `signals-scout-general`). */@@ -6313,6 +6325,11 @@ export type SignalScoutRunDetailApiMetadata = {* LLMA token-cost join) can land here without bloating the list response.*/export interface SignalScoutRunDetailApi {+ /**+ * Accounted customer spend in USD cents, including fractional cents. May be partial; null for untracked runs.+ * @nullable+ */+ readonly total_spend: number | null/** UUID of the bridge row. */run_id: string/** Canonical skill name the run executed (e.g. `signals-scout-general`). */diff --git a/products/signals/frontend/inbox/__mocks__/inboxMocks.ts b/products/signals/frontend/inbox/__mocks__/inboxMocks.tsindex 268242c0896f..71de6dbf3274 100644--- a/products/signals/frontend/inbox/__mocks__/inboxMocks.ts+++ b/products/signals/frontend/inbox/__mocks__/inboxMocks.ts@@ -291,6 +291,8 @@ export function mockSourceMetadata(export function mockSignals(reportId: string, count = 4): SignalNode[] {return Array.from({ length: count }).map((_, i) => ({signal_id: `${reportId}-sig-${i}`,+ total_spend: null,+ spend_accounting_failed_stages: [],content: ['User clicked **Submit** with an empty recipient row; the request returned `500` from `/api/invites`.','Session shows three retries of the same failing checkout call before the user gave up.',diff --git a/products/signals/frontend/inbox/__mocks__/scoutConfigs.ts b/products/signals/frontend/inbox/__mocks__/scoutConfigs.tsindex 5df251c6e5d4..c0935cf5256f 100644--- a/products/signals/frontend/inbox/__mocks__/scoutConfigs.ts+++ b/products/signals/frontend/inbox/__mocks__/scoutConfigs.ts@@ -103,6 +103,7 @@ export function mockScoutRuns(configs: SignalScoutConfigApi[]): SignalScoutRunSuconst startedAt = MOCK_NOW_MS - (runIndex + 1) * HOUR_MSreturn {run_id: `${config.skill_name}-run-${runIndex}`,+ total_spend: null,skill_name: config.skill_name,skill_version: 1,status: failed ? ('failed' as const) : ('completed' as const),@@ -132,6 +133,7 @@ export function mockDailyQuietRuns(config: SignalScoutConfigApi): SignalScoutRunconst startedAt = MOCK_NOW_MS - (runIndex + 2) * 24 * HOUR_MSreturn {run_id: `${config.skill_name}-daily-run-${runIndex}`,+ total_spend: null,skill_name: config.skill_name,skill_version: 1,status: 'completed' as const,diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutRunBoxes.test.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutRunBoxes.test.tsxindex b15753e25df1..2ecfda3530a2 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutRunBoxes.test.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutRunBoxes.test.tsx@@ -8,6 +8,7 @@ import { ScoutRunBoxes } from './ScoutRunBoxes'function makeRun(overrides: Partial<SignalScoutRunSummary> = {}): SignalScoutRunSummary {return {run_id: 'run-1',+ total_spend: null,skill_name: 'signals-scout-general',skill_version: 1,status: 'completed',diff --git a/products/signals/frontend/inbox/components/signalCards/ConversationsTicketSignalCard.test.tsx b/products/signals/frontend/inbox/components/signalCards/ConversationsTicketSignalCard.test.tsxindex b75f72fdfd18..643b4601570a 100644--- a/products/signals/frontend/inbox/components/signalCards/ConversationsTicketSignalCard.test.tsx+++ b/products/signals/frontend/inbox/components/signalCards/ConversationsTicketSignalCard.test.tsx@@ -13,6 +13,8 @@ jest.mock('lib/components/TZLabel', () => ({function makeSignal(extra: Record<string, unknown>): SignalNode {return {signal_id: 'signal-1',+ total_spend: null,+ spend_accounting_failed_stages: [],content: 'The upload progress bar reaches 100% but the file never appears.',source_product: 'conversations',source_type: 'ticket',diff --git a/products/signals/frontend/inbox/components/signalCards/HealthCheckSignalCard.test.tsx b/products/signals/frontend/inbox/components/signalCards/HealthCheckSignalCard.test.tsxindex 0f4ac218e1ef..e51ec2d946dd 100644--- a/products/signals/frontend/inbox/components/signalCards/HealthCheckSignalCard.test.tsx+++ b/products/signals/frontend/inbox/components/signalCards/HealthCheckSignalCard.test.tsx@@ -13,6 +13,8 @@ jest.mock('lib/components/TZLabel', () => ({function makeSignal(payload: Record<string, unknown>, title: string, content: string): SignalNode {return {signal_id: 'signal-1',+ total_spend: null,+ spend_accounting_failed_stages: [],content,source_product: 'health_checks',source_type: 'health_issue',diff --git a/products/signals/frontend/inbox/components/signalCards/SignalCards.stories.tsx b/products/signals/frontend/inbox/components/signalCards/SignalCards.stories.tsxindex 9c733e118032..938602e80a31 100644--- a/products/signals/frontend/inbox/components/signalCards/SignalCards.stories.tsx+++ b/products/signals/frontend/inbox/components/signalCards/SignalCards.stories.tsx@@ -33,6 +33,8 @@ function makeSignal(): SignalNode {return {signal_id: `sig-${overrides.source_product}`,+ total_spend: null,+ spend_accounting_failed_stages: [],content: 'The user retried the upload three times before leaving the page.',source_type: 'issue',source_id: 'src-1',diff --git a/products/signals/frontend/inbox/components/signalCards/SignalsScoutSignalCard.test.tsx b/products/signals/frontend/inbox/components/signalCards/SignalsScoutSignalCard.test.tsxindex a00d4035c35c..248ca6d9941b 100644--- a/products/signals/frontend/inbox/components/signalCards/SignalsScoutSignalCard.test.tsx+++ b/products/signals/frontend/inbox/components/signalCards/SignalsScoutSignalCard.test.tsx@@ -13,6 +13,8 @@ jest.mock('lib/components/TZLabel', () => ({function makeSignal(extra: Record<string, unknown>): SignalNode {return {signal_id: 'signal-1',+ total_spend: null,+ spend_accounting_failed_stages: [],content: 'Checkout 500s spike after the payment flag rollout',source_product: 'signals_scout',source_type: 'cross_source_issue',diff --git a/products/signals/frontend/inbox/inboxSceneLogic.test.ts b/products/signals/frontend/inbox/inboxSceneLogic.test.tsindex 54a807b9657c..f73d549b560e 100644--- a/products/signals/frontend/inbox/inboxSceneLogic.test.ts+++ b/products/signals/frontend/inbox/inboxSceneLogic.test.ts@@ -36,6 +36,7 @@ function waitForOpenRankRetry(): Promise<void> {function scoutRun(overrides: Partial<SignalScoutRunSummary> = {}): SignalScoutRunSummary {return {run_id: 'run-1',+ total_spend: null,skill_name: 'signals-scout-error-tracking',skill_version: 1,status: 'completed',diff --git a/products/signals/frontend/inbox/logics/scoutFleetLogic.test.ts b/products/signals/frontend/inbox/logics/scoutFleetLogic.test.tsindex 988cf0718a20..def32ef521fd 100644--- a/products/signals/frontend/inbox/logics/scoutFleetLogic.test.ts+++ b/products/signals/frontend/inbox/logics/scoutFleetLogic.test.ts@@ -118,6 +118,7 @@ const OWNED_CONFIG: SignalScoutConfigApi = { ...BASE_CONFIG, scout_origin: 'custfunction makeRun(overrides: Partial<SignalScoutRunSummary> = {}): SignalScoutRunSummary {return {run_id: 'run-1',+ total_spend: null,skill_name: BASE_CONFIG.skill_name,skill_version: 1,status: 'completed',diff --git a/products/signals/frontend/inbox/utils/scoutGroups.test.ts b/products/signals/frontend/inbox/utils/scoutGroups.test.tsindex d88626da0718..e1989968b572 100644--- a/products/signals/frontend/inbox/utils/scoutGroups.test.ts+++ b/products/signals/frontend/inbox/utils/scoutGroups.test.ts@@ -44,6 +44,7 @@ function makeConfig(overrides: Partial<SignalScoutConfig> = {}): SignalScoutConffunction makeRun(overrides: Partial<SignalScoutRunSummary> = {}): SignalScoutRunSummary {return {run_id: 'run-1',+ total_spend: null,skill_name: 'signals-scout-apm',skill_version: 1,status: 'completed',diff --git a/products/signals/frontend/inbox/utils/scoutRunsWindow.test.ts b/products/signals/frontend/inbox/utils/scoutRunsWindow.test.tsindex a548c1599184..ca217d243d8f 100644--- a/products/signals/frontend/inbox/utils/scoutRunsWindow.test.ts+++ b/products/signals/frontend/inbox/utils/scoutRunsWindow.test.ts@@ -35,6 +35,7 @@ const NOW = new Date('2026-06-27T22:00:00Z')function makeRun(overrides: Partial<SignalScoutRunSummary> = {}): SignalScoutRunSummary {return {run_id: 'run-1',+ total_spend: null,skill_name: 'signals-scout-dev-report-probe',skill_version: 1,status: 'completed',diff --git a/products/tasks/backend/facade/billing.py b/products/tasks/backend/facade/billing.pyindex ffbea082b6f1..cbbc8ac8824b 100644--- a/products/tasks/backend/facade/billing.py+++ b/products/tasks/backend/facade/billing.py@@ -4,8 +4,14 @@ The usage reporter (posthog/tasks/usage_report.py) lives in the ``posthog`` moduwhich may only import ``products.tasks`` through the facade (see tach.toml)."""-from products.tasks.backend.facade.contracts import TaskRunCost-from products.tasks.backend.logic.services.gateway_usage import get_task_cost, get_task_run_cost+from products.tasks.backend.facade.contracts import TaskRunCost, TaskRunTokenUsage+from products.tasks.backend.logic.services.gateway_usage import (+ get_task_cost,+ get_task_run_cost,+ get_task_run_token_cost_microusd,+ get_task_run_token_usage,+ process_pending_gateway_usage,+)from products.tasks.backend.logic.services.sandbox_pricing import ComputeRateCardConfigurationErrorfrom products.tasks.backend.logic.services.sandbox_usage import (SandboxComputeUsageByTeam,@@ -26,6 +32,7 @@ from products.tasks.backend.logic.services.task_usage import (__all__ = ["ComputeRateCardConfigurationError","TaskRunCost",+ "TaskRunTokenUsage","SandboxComputeUsageByTeam","SandboxUsageByTeam","TaskUsage",@@ -39,4 +46,7 @@ __all__ = ["get_task_usage","get_task_run_cost","get_task_cost",+ "get_task_run_token_cost_microusd",+ "get_task_run_token_usage",+ "process_pending_gateway_usage",]diff --git a/products/tasks/backend/facade/contracts.py b/products/tasks/backend/facade/contracts.pyindex 155bb5aa3202..9cfc10848d7b 100644--- a/products/tasks/backend/facade/contracts.py+++ b/products/tasks/backend/facade/contracts.py@@ -130,6 +130,14 @@ class WizardCloudRunDTO:started_at: datetime | None = None+@dataclass(frozen=True)+class TaskRunTokenUsage:+ """Settled token subtotal in micro-USD and whether every request is accounted for."""++ cost_microusd: int | None+ complete: bool++@dataclass(frozen=True)class TaskRunCost:"""Provider costs in integer USD cents, or None while a source is unavailable or incomplete."""diff --git a/products/tasks/backend/facade/task_run_signals.py b/products/tasks/backend/facade/task_run_signals.pyindex c3749957be46..8c96728725bc 100644--- a/products/tasks/backend/facade/task_run_signals.py+++ b/products/tasks/backend/facade/task_run_signals.py@@ -55,3 +55,10 @@ def register_task_read_exclusion(exclusion: TaskReadExclusion, *, name: str) ->def hidden_task_ids(team_id: int, user_id: int | None) -> set[UUID]:"""Every registered product's task ids to hide from this user."""return {task_id for exclusion in _task_read_exclusions.values() for task_id in exclusion(team_id, user_id)}+++task_run_cost_updated = Signal()+++def connect_task_run_cost_updated(receiver: Callable[..., None], *, dispatch_uid: str) -> None:+ task_run_cost_updated.connect(receiver, sender=TaskRun, dispatch_uid=dispatch_uid)diff --git a/products/tasks/backend/logic/services/gateway_usage.py b/products/tasks/backend/logic/services/gateway_usage.pyindex 0dabe4ba4896..70d40434930e 100644--- a/products/tasks/backend/logic/services/gateway_usage.py+++ b/products/tasks/backend/logic/services/gateway_usage.py@@ -16,8 +16,10 @@ import structlogfrom asgiref.sync import async_to_syncfrom posthog.dataclasses import frozen+from posthog.llm.gateway_usage import GatewayRequestCost, fetch_gateway_cost-from products.tasks.backend.facade.contracts import TaskRunCost+from products.tasks.backend.facade.contracts import TaskRunCost, TaskRunTokenUsage+from products.tasks.backend.facade.task_run_signals import task_run_cost_updatedfrom products.tasks.backend.logic.services.sandbox_pricing import COMPUTE_RATE_CARDS, calculate_sandbox_compute_costfrom products.tasks.backend.models import SandboxSession, TaskRun@@ -26,17 +28,9 @@ if TYPE_CHECKING:logger = structlog.get_logger(__name__)_REQUEST_ID = re.compile(r"[a-zA-Z0-9_-]{1,255}\Z")-_USD_AMOUNT = re.compile(r"[0-9]{1,12}(?:\.[0-9]{1,6})?\Z")_PROCESSING_SECONDS = 10-@frozen-class GatewayRequestCost:- model: str- provider: str- cost_microusd: int--@frozenclass _CostSources:token_cost_microusd: int | None@@ -68,6 +62,7 @@ def _save_accounting_state(run: TaskRun) -> None:# Accounting can finish after completion; it must not emit completion signals again.# It also leaves `updated_at` alone, because recency gauges and stale-run sweeps read it.TaskRun.objects.filter(id=run.id, team_id=run.team_id).update(state=run.state)+ task_run_cost_updated.send(sender=TaskRun, run_id=run.id, team_id=run.team_id)def record_gateway_routing(*, run_id: UUID | str, team_id: int, uses_gateway: bool) -> None:@@ -207,52 +202,39 @@ def get_task_cost(*, team_id: int, task_id: UUID) -> TaskRunCost:async def _fetch_gateway_cost(request_id: str) -> GatewayRequestCost | None:- import aiohttp # noqa: PLC0415 - keeps aiohttp off Django's startup path+ return await fetch_gateway_cost(+ request_id, base_url=settings.SANDBOX_AI_GATEWAY_URL or "", api_key=settings.SANDBOX_AI_GATEWAY_MINT_KEY or ""+ )+++def get_task_run_token_cost_microusd(*, run_id: UUID, team_id: int) -> int | None:+ return _token_cost_microusd(TaskRun.objects.get(id=run_id, team_id=team_id))- base_url = (settings.SANDBOX_AI_GATEWAY_URL or "").rstrip("/").removesuffix("/v1")- mint_key = settings.SANDBOX_AI_GATEWAY_MINT_KEY- if not base_url or not mint_key:- return None- try:- async with (- aiohttp.ClientSession(trust_env=True) as session,- session.get(- f"{base_url}/v1/usage/{request_id}",- headers={"Authorization": f"Bearer {mint_key}"},- timeout=aiohttp.ClientTimeout(total=15, connect=2, sock_read=3),- allow_redirects=False,- ) as response,- ):- if response.status != 200:- logger.warning("task_gateway_usage.cost_pending", status_code=response.status)- return None- body = await response.json()- if not isinstance(body, dict) or body.get("request_id") != request_id:- return None- amount = body.get("cost_usd")- model, provider = body.get("model") or "unknown", body.get("provider") or "unknown"- if (- not isinstance(amount, str)- or not _USD_AMOUNT.fullmatch(amount)- or not isinstance(model, str)- or len(model) > 255- or not isinstance(provider, str)- or len(provider) > 255- ):- return None- return GatewayRequestCost(model=model, provider=provider, cost_microusd=int(Decimal(amount) * 1_000_000))- except (aiohttp.ClientError, TimeoutError, ValueError, TypeError):- logger.warning("task_gateway_usage.lookup_failed")- return None++def _token_usage(run: TaskRun) -> TaskRunTokenUsage:+ state = run.state or {}+ return TaskRunTokenUsage(+ cost_microusd=sum(bucket.get("cost_microusd", 0) for bucket in _cost_buckets(state))+ if isinstance(state.get("token_cost"), dict)+ else None,+ complete=gateway_usage_enabled(run)+ and not state.get("token_cost_incomplete", False)+ and not bool(state.get("unprocessed_request_ids")),+ )+++def get_task_run_token_usage(*, run_id: UUID, team_id: int) -> TaskRunTokenUsage:+ return _token_usage(TaskRun.objects.get(id=run_id, team_id=team_id))+++def _token_cost_microusd(run: TaskRun) -> int | None:+ usage = _token_usage(run)+ return usage.cost_microusd if usage.complete else Nonedef _cost_sources(run: TaskRun, *, sessions: list[SandboxSession] | None = None) -> _CostSources:return _CostSources(- token_cost_microusd=sum(bucket.get("cost_microusd", 0) for bucket in _cost_buckets(run.state or {}))- if gateway_usage_enabled(run)- and not (run.state or {}).get("token_cost_incomplete")- and not (run.state or {}).get("unprocessed_request_ids")- else None,+ token_cost_microusd=_token_cost_microusd(run),compute_cost_usd=_compute_cost_source(run, sessions=sessions),)diff --git a/products/tasks/backend/temporal/__init__.py b/products/tasks/backend/temporal/__init__.pyindex 6efbc563cb48..c743c4dec9c3 100644--- a/products/tasks/backend/temporal/__init__.py+++ b/products/tasks/backend/temporal/__init__.py@@ -20,6 +20,7 @@ from .process_task.activities import (clone_repository_in_sandbox,collect_agent_shadow_result,complete_run_stream,+ complete_signal_spend,create_resume_snapshot,create_sandbox_for_repository,emit_progress_activity,@@ -120,6 +121,7 @@ ACTIVITIES = [start_dev_stack_preview,wait_dev_stack_preview,update_task_run_status,+ complete_signal_spend,get_pr_context,get_pr_babysit_snapshot,mark_pr_ready,diff --git a/products/tasks/backend/temporal/process_task/activities/__init__.py b/products/tasks/backend/temporal/process_task/activities/__init__.pyindex 8078b38c5922..4a234640e733 100644--- a/products/tasks/backend/temporal/process_task/activities/__init__.py+++ b/products/tasks/backend/temporal/process_task/activities/__init__.py@@ -83,7 +83,7 @@ from .start_dev_stack_preview import (wait_dev_stack_preview,)from .track_workflow_event import TrackWorkflowEventInput, track_workflow_event-from .update_task_run_status import UpdateTaskRunStatusInput, update_task_run_status+from .update_task_run_status import UpdateTaskRunStatusInput, complete_signal_spend, update_task_run_status__all__ = ["CleanupSandboxInput",@@ -168,6 +168,7 @@ __all__ = ["mark_repo_ready","track_workflow_event","update_task_run_status",+ "complete_signal_spend","clone_repository_in_sandbox","materialize_context_layer_in_sandbox","MaterializeContextLayerInput",diff --git a/products/tasks/backend/temporal/process_task/activities/update_task_run_status.py b/products/tasks/backend/temporal/process_task/activities/update_task_run_status.pyindex 13d62398a982..16f3ff103ed8 100644--- a/products/tasks/backend/temporal/process_task/activities/update_task_run_status.py+++ b/products/tasks/backend/temporal/process_task/activities/update_task_run_status.py@@ -10,6 +10,7 @@ from temporalio.exceptions import ApplicationErrorfrom posthog.temporal.common.utils import asyncify+from products.signals.backend.facade.spend import complete_task_spendfrom products.tasks.backend.constants import TIMED_OUT_INACTIVITY_STATE_KEYfrom products.tasks.backend.error_telemetry import truncate_error_messagefrom products.tasks.backend.logic.services.gateway_usage import refresh_task_run_cost@@ -165,6 +166,14 @@ def update_task_run_status(input: UpdateTaskRunStatusInput) -> None:)+@asyncify+def complete_signal_spend(run_id: str) -> None:+ run = TaskRun.objects.only("team_id", "status").get(id=run_id)+ if run.status in _TERMINAL_STATUSES:+ complete_task_spend(team_id=run.team_id, run_id=run_id)++def _capture_posthog_ai_chat_analytics(task_run: TaskRun, input: UpdateTaskRunStatusInput, *, termination_reason: Optional[str]) -> None:diff --git a/products/tasks/backend/temporal/process_task/tests/test_workflow.py b/products/tasks/backend/temporal/process_task/tests/test_workflow.pyindex 55f528639b69..9c4452ebc26b 100644--- a/products/tasks/backend/temporal/process_task/tests/test_workflow.py+++ b/products/tasks/backend/temporal/process_task/tests/test_workflow.py@@ -2627,6 +2627,8 @@ class TestProcessTaskWorkflowUnit:(None, False, 1, False, "completed"),("slack", False, 1, False, "completed"),("user_created", False, 1, None, "completed"),+ ("signal_report", False, 1, None, "completed"),+ ("signals_scout", False, 1, None, "completed"),# Onboarding runs are one-shot, so a vanished sandbox is a failed setup rather than a# resumable snapshot.("onboarding", False, 1, None, "failed"),@@ -2699,7 +2701,15 @@ class TestProcessTaskWorkflowUnit:monkeypatch.setattr(process_task_workflow_module.workflow, "wait_condition", fake_wait_condition)+ async def finish_spend(activity_fn, run_id, **kwargs):+ assert activity_fn is process_task_workflow_module.complete_signal_spend+ assert run_id == "run-id"+ cleanup_sandbox_mock.assert_awaited_once()++ finish_spend_mock = AsyncMock(side_effect=finish_spend)+ monkeypatch.setattr(process_task_workflow_module.workflow, "execute_activity", finish_spend_mock)result = await workflow.run(ProcessTaskInput(run_id="run-id"))+ assert finish_spend_mock.await_count == (1 if origin_product in {"signal_report", "signals_scout"} else 0)assert result.success is Trueassert workflow._completion_status == expected_statusdiff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.pyindex e2668239f110..3c1835939c5b 100644--- a/products/tasks/backend/temporal/process_task/workflow.py+++ b/products/tasks/backend/temporal/process_task/workflow.py@@ -149,6 +149,7 @@ from .activities.update_task_run_status import (SANDBOX_GONE_STATE_KEY,TIMED_OUT_WALL_CLOCK_STATE_KEY,UpdateTaskRunStatusInput,+ complete_signal_spend,update_task_run_status,)from .credential_refresh import CredentialRefreshExitReason, run_credential_refresh_loop, sandbox_gone_error_message@@ -1866,6 +1867,21 @@ class ProcessTaskWorkflow(PostHogWorkflow):if sandbox_cleaned and self._slack_thread_context and self._context:await self._post_slack_update(sandbox_cleaned=True)+ if (+ self._context+ and self.context.origin_product in {_ORIGIN_PRODUCT_SIGNAL_REPORT, "signals_scout"}+ and workflow.patched("signals-publish-spend-on-completion")+ ):+ try:+ await workflow.execute_activity(+ complete_signal_spend,+ run_id,+ start_to_close_timeout=timedelta(minutes=20),+ retry_policy=RetryPolicy(maximum_attempts=1),+ )+ except Exception:+ workflow.logger.exception("Failed to finalize signal spend", extra={"run_id": run_id})+async def _provision_and_start_agent(self, input: ProcessTaskInput, run_id: str) -> tuple[str, str, str | None]:"""Initial-run setup: resolve agent-design, provision the sandbox, start the agentserver. Returns (sandbox_id, sandbox_url, connect_token). Skipped on continue_as_new."""diff --git a/products/tasks/backend/tests/test_gateway_usage.py b/products/tasks/backend/tests/test_gateway_usage.pyindex f213d750ce46..887ea141cd4b 100644--- a/products/tasks/backend/tests/test_gateway_usage.py+++ b/products/tasks/backend/tests/test_gateway_usage.py@@ -1,5 +1,6 @@from datetime import timedeltafrom decimal import Decimal+from uuid import UUIDfrom posthog.test.base import BaseTestfrom unittest.mock import AsyncMock, MagicMock, Mock, patch@@ -10,7 +11,14 @@ from django.utils import timezonefrom asgiref.sync import sync_to_asyncfrom parameterized import parameterized-from products.tasks.backend.facade.billing import TaskRunCost, get_task_cost, get_task_run_cost+from products.tasks.backend.facade.billing import (+ TaskRunCost,+ get_task_cost,+ get_task_run_cost,+ get_task_run_token_cost_microusd,+ get_task_run_token_usage,+)+from products.tasks.backend.facade.task_run_signals import task_run_cost_updatedfrom products.tasks.backend.logic.services.gateway_usage import (process_pending_gateway_usage,record_gateway_routing,@@ -52,9 +60,18 @@ class TestGatewayUsage(BaseTest):def _process(self, run: TaskRun, *, limit: int = 20) -> TaskRunCost:return process_pending_gateway_usage(run_id=run.id, team_id=self.team.id, limit=limit)- @patch("aiohttp.ClientSession._request")+ @patch.dict("os.environ", {"HTTPS_PROXY": "http://proxy.example.com:8080"})+ @patch("aiohttp.ClientSession._request", autospec=True)def test_records_cost_by_model_and_provider_and_removes_processed_ids(self, get: Mock) -> None:run = self._run()+ observed_costs: dict[UUID, int | None] = {}++ def cost_updated(*, run_id: UUID, team_id: int, **kwargs: object) -> None:+ assert team_id == self.team.id+ observed_costs[run_id] = get_task_run_token_cost_microusd(team_id=team_id, run_id=run_id)++ task_run_cost_updated.connect(cost_updated, sender=TaskRun)+ self.addCleanup(task_run_cost_updated.disconnect, cost_updated, sender=TaskRun)self._report(run, ["parent", "subagent", "other-model", "second-turn", "parent"])get.side_effect = [self._response("parent", "0.005"),@@ -63,8 +80,10 @@ class TestGatewayUsage(BaseTest):self._response("second-turn", "0.005"),]assert self._process(run).token_cost == 2+ assert observed_costs == {run.id: 20_010}assert get.call_count == 4assert get.call_args.kwargs["timeout"].total == 15+ assert get.call_args.args[0].trust_env is Falserun.refresh_from_db()assert run.state == {"unprocessed_request_ids": [],@@ -138,6 +157,9 @@ class TestGatewayUsage(BaseTest):assert get_task_run_cost(run_id=run.id, team_id=self.team.id).token_cost is Noneassert get_task_cost(team_id=self.team.id, task_id=run.task_id).token_cost is Noneassert get.call_args.args[1].endswith("/v1/usage/priced")+ usage = get_task_run_token_usage(run_id=run.id, team_id=self.team.id)+ assert usage.cost_microusd == 100_000+ assert not usage.completerun.refresh_from_db()assert run.state["unprocessed_request_ids"] == ["missing"]diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 2e5246b553cc..48c3b40fae55 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -96050,6 +96050,13 @@ export namespace Schemas {export type SignalMatchMetadata = MatchedMetadata | NoMatchMetadata;export interface SignalNode {+ /**+ * Accounted customer spend in USD cents, including fractional cents. May be partial; null for untracked signals.+ * @nullable+ */+ readonly total_spend: number | null;+ /** Pipeline stages with generations whose spend could not be accounted for. Cleared when accounting recovers. */+ readonly spend_accounting_failed_stages: readonly string[];/** ClickHouse document id of the signal. */signal_id: string;/** The signal's human-readable description. */@@ -102310,6 +102317,11 @@ export namespace Schemas {* LLMA token-cost join) can land here without bloating the list response.*/export interface SignalScoutRunDetail {+ /**+ * Accounted customer spend in USD cents, including fractional cents. May be partial; null for untracked runs.+ * @nullable+ */+ readonly total_spend: number | null;/** UUID of the bridge row. */run_id: string;/** Canonical skill name the run executed (e.g. `signals-scout-general`). */@@ -102410,6 +102422,11 @@ export namespace Schemas {* Status and timestamps flow from the linked `tasks.TaskRun`.*/export interface SignalScoutRunSummary {+ /**+ * Accounted customer spend in USD cents, including fractional cents. May be partial; null for untracked runs.+ * @nullable+ */+ readonly total_spend: number | null;/** UUID of the bridge row. */run_id: string;/** Canonical skill name the run executed (e.g. `signals-scout-general`). */