LLM-Driven Extraction of Unstructured Data — Built for API Deployments & ETL Pipeline Workflows
Python ai-agentsdata-engineeringdocument-aigenerative-aiidpjson-extractionllmmcp-serverocrpdf-extractionprompt-engineeringstructured-output
UN-3056 [FEAT] Per-window batched notifications + "notify on failures only" (#1936)
Kirtiman Mishrae8afcfa88c81
diff --git a/backend/api_v2/notification.py b/backend/api_v2/notification.pyindex 733084c63..ec1d2ca47 100644--- a/backend/api_v2/notification.py+++ b/backend/api_v2/notification.py@@ -1,6 +1,6 @@import logging-from notification_v2.helper import NotificationHelper+from notification_v2.helper import dispatch_notifications, is_failure_runfrom notification_v2.models import Notificationfrom pipeline_v2.dto import PipelineStatusPayloadfrom workflow_manager.workflow_v2.models.execution import WorkflowExecution@@ -16,11 +16,30 @@ class APINotification:self.api = apiself.workflow_execution = workflow_execution- def send(self):- if not self.notifications.count():- logger.info(f"No notifications found for api {self.api}")+ def send(self) -> None:+ # Shared failure rule (status ∈ {ERROR, STOPPED} OR any file errored) —+ # see notification_v2.helper.is_failure_run.+ failed_files = self.workflow_execution.failed_files or 0+ is_failure = is_failure_run(self.workflow_execution.status, failed_files)+ if not is_failure:+ # Success path: skip rows that opted into failure-only alerts.+ self.notifications = self.notifications.filter(notify_on_failures=False)++ if not self.notifications.exists():+ logger.info(+ "No notifications to dispatch for api %s (status=%s, failed_files=%s)",+ self.api,+ self.workflow_execution.status,+ failed_files,+ )return- logger.info(f"Sending api status notification for api {self.api}")+ logger.info(+ "Sending api status notification for api %s (status=%s, successful=%s, failed=%s)",+ self.api,+ self.workflow_execution.status,+ self.workflow_execution.successful_files or 0,+ failed_files,+ )payload_dto = PipelineStatusPayload(type="API",@@ -29,8 +48,17 @@ class APINotification:status=self.workflow_execution.status,execution_id=self.workflow_execution.id,error_message=self.workflow_execution.error_message,+ total_files=self.workflow_execution.total_files,+ successful_files=self.workflow_execution.successful_files,+ failed_files=failed_files,+ # status is already ExecutionStatus vocab here, so the renderer would+ # classify correctly anyway; carry the explicit verdict so both+ # backend dispatch paths are uniform and vocab-independent.+ is_failure=is_failure,)- NotificationHelper.send_notification(- notifications=self.notifications, payload=payload_dto.to_dict()+ dispatch_notifications(+ list(self.notifications),+ payload_dto.to_dict(),+ error_context=f"api={self.api.id}",)diff --git a/backend/backend/settings/base.py b/backend/backend/settings/base.pyindex 479cb5476..7593305fd 100644--- a/backend/backend/settings/base.py+++ b/backend/backend/settings/base.py@@ -223,6 +223,33 @@ CELERY_RESULT_CHORD_RETRY_INTERVAL = float(INDEXING_FLAG_TTL = int(get_required_setting("INDEXING_FLAG_TTL"))NOTIFICATION_TIMEOUT = int(get_required_setting("NOTIFICATION_TIMEOUT", "5"))+# Default batching window (seconds) for clubbing BATCHED notifications — also the+# flush cadence. Default 300 (5 min). This is only the fallback default; each org+# can override it from Platform Settings (Configuration key+# NOTIFICATION_CLUB_INTERVAL), read per-org at enqueue time. Buffer rows+# precompute flush_after at enqueue, so changes only affect rows enqueued after.+NOTIFICATION_CLUB_INTERVAL = int(os.environ.get("NOTIFICATION_CLUB_INTERVAL", "300"))+# Retention for terminal NotificationBuffer rows (DISPATCHED / DEAD_LETTER).+# PENDING rows are never GC'd regardless of age.+NOTIFICATION_BUFFER_RETENTION_DAYS = int(+ os.environ.get("NOTIFICATION_BUFFER_RETENTION_DAYS", "7")+)+# Lease (seconds) for a buffer row claimed for dispatch (status=SENDING). If a row+# stays SENDING longer than this — e.g. the backend crashed between committing the+# claim and publishing the Celery task — the flush reaper returns it to PENDING for+# re-dispatch. Must exceed the worst-case retry duration (max_retries * retry_delay)+# so in-flight dispatches are never reclaimed mid-flight. Default 900 (15 min).+NOTIFICATION_DISPATCH_LEASE_SECONDS = int(+ os.environ.get("NOTIFICATION_DISPATCH_LEASE_SECONDS", "900")+)+# Hard ceiling on how many times a buffer row may be claimed for dispatch. Each+# SENDING claim increments NotificationBuffer.dispatch_attempts; once it reaches+# this cap the row is dead-lettered instead of re-dispatched. Bounds the reaper+# reclaim loop so a row whose terminal callback never fires (e.g. a crash that+# recurs in the dispatch->callback window) cannot be redelivered forever.+NOTIFICATION_MAX_DISPATCH_ATTEMPTS = int(+ os.environ.get("NOTIFICATION_MAX_DISPATCH_ATTEMPTS", "5")+)ATOMIC_REQUESTS = CommonUtils.str_to_bool(os.environ.get("DJANGO_ATOMIC_REQUESTS", "False"))diff --git a/backend/configuration/enums.py b/backend/configuration/enums.pyindex f35033a9f..78bbeb7df 100644--- a/backend/configuration/enums.py+++ b/backend/configuration/enums.py@@ -61,6 +61,14 @@ class ConfigKey(Enum):max_value=settings.MAX_PARALLEL_FILE_BATCHES_MAX_VALUE,)+ NOTIFICATION_CLUB_INTERVAL = ConfigSpec(+ default=settings.NOTIFICATION_CLUB_INTERVAL,+ value_type=ConfigType.INT,+ help_text="Window (seconds) for clubbing BATCHED notifications.",+ min_value=60,+ max_value=7200,+ )+def cast_value(self, raw_value: Any):converters = {ConfigType.INT: int,diff --git a/backend/notification_v2/clubbed_renderer.py b/backend/notification_v2/clubbed_renderer.pynew file mode 100644index 000000000..b94667c19--- /dev/null+++ b/backend/notification_v2/clubbed_renderer.py@@ -0,0 +1,55 @@+"""Backend dispatch entry for clubbed-notification rendering.++Delegates the canonical envelope + Slack body to+``unstract.core.notification_clubbed_renderer`` so backend and worker+callbacks emit byte-identical receiver-visible payloads. This thin shim+keeps the ``render_clubbed_message`` platform dispatcher (uses+``PlatformType`` enum) backend-side; everything else lives in the shared+module.+"""++from __future__ import annotations++import logging+from typing import Any++from notification_v2.enums import PlatformType+from unstract.core.notification_clubbed_renderer import (+ MAX_BATCH_SIZE,+ build_envelope,+ render_slack_text,+)++logger = logging.getLogger(__name__)++# build_envelope is imported for internal use below; it is intentionally not+# re-exported — callers import it straight from unstract.core.+__all__ = ["MAX_BATCH_SIZE", "render_clubbed_message"]+++def _render_for_slack(envelope: dict[str, Any]) -> dict[str, Any]:+ """Wrap the rendered Slack mrkdwn body in the dict shape Slack expects."""+ return {"text": render_slack_text(envelope)}+++def render_clubbed_message(+ payloads: list[dict[str, Any]],+ platform: str,+) -> dict[str, Any]:+ """Top-level entry — returns the dispatch body for ``platform``.++ Used by every dispatch site so the receiver-visible payload is+ identical regardless of caller.+ """+ envelope = build_envelope(payloads)+ if platform == PlatformType.SLACK.value:+ return _render_for_slack(envelope)+ if platform == PlatformType.API.value:+ return envelope+ # Unknown platform — fall back to the raw envelope and warn so misrouted+ # rows don't drop silently.+ logger.warning(+ "Unknown platform %s for clubbed dispatch; returning raw envelope",+ platform,+ )+ return envelopediff --git a/backend/notification_v2/enums.py b/backend/notification_v2/enums.pyindex 991b08cac..3c4dd32b6 100644--- a/backend/notification_v2/enums.py+++ b/backend/notification_v2/enums.py@@ -36,3 +36,26 @@ class PlatformType(Enum):@classmethoddef choices(cls):return [(e.value, e.name.replace("_", " ").capitalize()) for e in cls]+++class BufferStatus(Enum):+ """Lifecycle states for a NotificationBuffer row.++ PENDING — waiting for the next flush tick.+ SENDING — claimed by a flush and handed to the dispatch task; awaiting+ its success/failure callback. Reclaimed to PENDING by the+ reaper if it stays here past the dispatch lease (crash window).+ DISPATCHED — delivery succeeded.+ DEAD_LETTER — Celery exhausted retries, or the row hit+ NOTIFICATION_MAX_DISPATCH_ATTEMPTS reclaim attempts; terminal,+ never re-picked.+ """++ PENDING = "PENDING"+ SENDING = "SENDING"+ DISPATCHED = "DISPATCHED"+ DEAD_LETTER = "DEAD_LETTER"++ @classmethod+ def choices(cls):+ return [(e.value, e.name.replace("_", " ").capitalize()) for e in cls]diff --git a/backend/notification_v2/helper.py b/backend/notification_v2/helper.pyindex a454b9d82..c50159def 100644--- a/backend/notification_v2/helper.py+++ b/backend/notification_v2/helper.py@@ -1,48 +1,206 @@+import hashlib+import jsonimport logging+from collections.abc import Iterable+from datetime import timedeltafrom typing import Any-from notification_v2.enums import NotificationType, PlatformType-from notification_v2.models import Notification-from notification_v2.provider.notification_provider import NotificationProvider-from notification_v2.provider.registry import get_notification_provider+from account_v2.models import Organization+from django.utils import timezone++from notification_v2.enums import (+ AuthorizationType,+ BufferStatus,+ PlatformType,+)+from notification_v2.models import Notification, NotificationBuffer+from unstract.core.data_models import is_failure_run as _core_is_failure_runlogger = logging.getLogger(__name__)-class NotificationHelper:- @classmethod- def send_notification(cls, notifications: list[Notification], payload: Any) -> None:- """Send notification Sends notifications using the appropriate provider- based on the notification type and platform.-- This method iterates through a list of `Notification` objects, determines the- appropriate notification provider based on the notification's type and- platform, and sends the notification with the provided payload. If an error- occurs due to an invalid notification type or platform, it logs the error.-- Args:- notifications (list[Notification]): A list of `Notification` instances to- be processed and sent.- payload (Any): The data to be sent with the notification. This can be any- format expected by the provider-- Returns:- None- """- for notification in notifications:- notification_type = NotificationType(notification.notification_type)- platform_type = PlatformType(notification.platform)- try:- notification_provider = get_notification_provider(- notification_type, platform_type- )- notifier: NotificationProvider = notification_provider(- notification=notification, payload=payload- )- notifier.send()- logger.info(f"Sending notification to {notification}")- except ValueError as e:- logger.error(- f"Error in notification type {notification_type} and platform "- f"{platform_type} for notification {notification}: {e}"- )+def is_failure_run(execution_status: str | None, failed_files: int | None) -> bool:+ """Backend entry point for the "did this run fail?" rule.++ Delegates to the canonical predicate in ``unstract.core`` (which lives beside+ ``ExecutionStatus`` and is shared with the clubbed renderer) so the dispatch+ filter and the rendered summary can't drift. Kept as the public name here for+ the backend paths: api_v2/notification.py, pipeline_v2/notification.py and+ internal_api_views._apply_failure_filter. The pipeline path ORs an extra+ last_run_status==FAILURE backstop on top for the case where no+ WorkflowExecution can be loaded.+ """+ return _core_is_failure_run(execution_status, failed_files)+++# Used as a stable salt-free input for SHA-256 grouping; collisions are+# vanishingly improbable and the digest is never used as a security primitive.+_AUTH_SIG_NONE = ""+++def compute_auth_sig(notification: Notification) -> str:+ """SHA-256 hex of (auth_type, auth_key, auth_header) — never raw creds.++ Identical auth configs produce the same sig (so grouping clubs them);+ differing configs split into separate groups. The tuple is JSON-encoded+ before hashing so a literal delimiter byte inside auth_key/header cannot+ cause two distinct tuples to collapse to the same digest.+ """+ raw = json.dumps(+ [+ notification.authorization_type or _AUTH_SIG_NONE,+ notification.authorization_key or _AUTH_SIG_NONE,+ notification.authorization_header or _AUTH_SIG_NONE,+ ],+ separators=(",", ":"),+ )+ return hashlib.sha256(raw.encode("utf-8")).hexdigest()+++def webhook_url_hash(url: str | None) -> str:+ """Short, log-safe fingerprint of a webhook URL (first 8 chars of SHA-256)."""+ if not url:+ return "none"+ return hashlib.sha256(url.encode("utf-8")).hexdigest()[:8]+++def get_org_club_interval_seconds(organization: Organization) -> int:+ """Per-org override of NOTIFICATION_CLUB_INTERVAL, falling back to env default.++ Reads from the generic configuration KV table; returns the env-derived+ default when the org has no override. The value is read at enqueue time+ and baked into the row's flush_after, so changing the override only affects+ rows enqueued after the change.+ """+ # Local import: configuration depends on Django settings at import time+ # and notification_v2.helper is imported during app boot.+ from configuration.enums import ConfigKey+ from configuration.models import Configuration++ return int(+ Configuration.get_value_by_organization(+ ConfigKey.NOTIFICATION_CLUB_INTERVAL, organization+ )+ )+++def build_webhook_headers(notification: Notification) -> dict[str, str]:+ """Build HTTP headers for a webhook dispatch from the notification's auth.++ Used by the buffer flush in ``internal_api_views._dispatch_group`` to+ pass live auth headers through to the Celery task.+ """+ headers = {"Content-Type": "application/json"}+ auth_type_raw = (notification.authorization_type or "").upper()+ auth_key = notification.authorization_key+ auth_header = notification.authorization_header+ if auth_type_raw == AuthorizationType.BEARER.value and auth_key:+ headers["Authorization"] = f"Bearer {auth_key}"+ elif auth_type_raw == AuthorizationType.API_KEY.value and auth_key:+ headers["Authorization"] = auth_key+ elif (+ auth_type_raw == AuthorizationType.CUSTOM_HEADER.value+ and auth_header+ and auth_key+ ):+ headers[auth_header] = auth_key+ return headers+++def _resolve_organization(notification: Notification) -> Organization | None:+ """Walk pipeline/api FK to find the owning org. Notification has no direct FK."""+ pipeline = notification.pipeline+ if pipeline and pipeline.organization_id:+ return pipeline.organization+ api = notification.api+ if api and api.organization_id:+ return api.organization+ return None+++def dispatch_notifications(+ notifications: "Iterable[Notification]",+ payload: dict[str, Any],+ *,+ error_context: str = "",+) -> None:+ """Enqueue every active notification into ``NotificationBuffer``.++ Single dispatch path: each notification produces a buffer row that the+ periodic flush ships as part of a clubbed message. An enqueue failure+ on one row is logged but does not abort the loop — sibling notifications+ still get their chance.++ ``error_context`` lets callers tag failures with their dispatch source+ (pipeline id, api id) for easier triage.+ """+ for notification in notifications:+ try:+ enqueue(notification, payload)+ except Exception:+ # A dropped enqueue means a failure alert may never be delivered —+ # the exact event this feature exists to surface. Emit a metric so+ # the drop is observable, not just buried in a stack trace.+ logger.exception(+ "metric=notification_enqueue_failed_total notification_id=%s "+ "webhook_url_hash=%s%s",+ notification.id,+ webhook_url_hash(notification.url),+ f" context={error_context}" if error_context else "",+ )+++def enqueue(notification: Notification, payload: dict[str, Any]) -> NotificationBuffer:+ """Buffer a single execution event for a notification.++ Computes auth_sig and flush_after at write time so existing PENDING rows+ keep their original cadence even if NOTIFICATION_CLUB_INTERVAL or the+ notification's auth changes mid-window. Returns the persisted row.++ Raises ValueError if the notification has no resolvable organization+ (defensive — the FK chain via pipeline/api always provides one in practice).+ """+ organization = _resolve_organization(notification)+ if organization is None:+ raise ValueError(+ f"Notification {notification.id} has no resolvable organization "+ "(neither pipeline nor api FK populated)"+ )++ interval_seconds = get_org_club_interval_seconds(organization)+ flush_after = timezone.now() + timedelta(seconds=interval_seconds)+ auth_sig = compute_auth_sig(notification)+ platform = notification.platform or PlatformType.API.value++ # Stamp a buffered-at timestamp so renderers always have one to humanize.+ # Worker callers already supply one; backend dispatchers+ # (PipelineStatusPayload.to_dict) don't, so default here.+ payload = {+ **payload,+ "timestamp": payload.get("timestamp") or timezone.now().isoformat(),+ }++ buffer_row = NotificationBuffer.objects.create(+ notification=notification,+ organization=organization,+ webhook_url=notification.url,+ payload=payload,+ platform=platform,+ auth_sig=auth_sig,+ flush_after=flush_after,+ status=BufferStatus.PENDING.value,+ )++ # Structured log: org + URL fingerprint only — never the raw URL or any+ # part of the auth tuple. Downstream metrics consumers grep on metric=.+ logger.info(+ "metric=notification_buffer_enqueued_total platform=%s org_id=%s "+ "webhook_url_hash=%s notification_id=%s buffer_id=%s flush_after=%s",+ platform,+ organization.organization_id,+ webhook_url_hash(notification.url),+ notification.id,+ buffer_row.id,+ flush_after.isoformat(),+ )+ return buffer_rowdiff --git a/backend/notification_v2/internal_api_views.py b/backend/notification_v2/internal_api_views.pyindex 6843d5a50..be2bbe57e 100644--- a/backend/notification_v2/internal_api_views.py+++ b/backend/notification_v2/internal_api_views.py@@ -9,17 +9,34 @@ Security Note:- These endpoints are not accessible from browsers and don't use session cookies"""+import jsonimport logging+from datetime import timedelta+from typing import Any, castfrom api_v2.models import APIDeployment-from django.http import JsonResponse+from django.conf import settings+from django.db import transaction+from django.db.models import F, Min, QuerySet+from django.http import HttpRequest, JsonResponsefrom django.shortcuts import get_object_or_404+from django.utils import timezonefrom django.views.decorators.csrf import csrf_exemptfrom django.views.decorators.http import require_http_methodsfrom pipeline_v2.models import Pipelinefrom utils.organization_utils import filter_queryset_by_organization--from notification_v2.models import Notification+from workflow_manager.workflow_v2.models.execution import WorkflowExecution++from backend.celery_service import app as celery_app+from notification_v2.clubbed_renderer import MAX_BATCH_SIZE, render_clubbed_message+from notification_v2.enums import BufferStatus+from notification_v2.helper import (+ build_webhook_headers,+ enqueue,+ is_failure_run,+ webhook_url_hash,+)+from notification_v2.models import Notification, NotificationBufferlogger = logging.getLogger(__name__)@@ -27,9 +44,92 @@ logger = logging.getLogger(__name__)INTERNAL_SERVER_ERROR_MSG = "Internal server error"+def _load_execution(execution_id: str | None) -> WorkflowExecution | None:+ """Best-effort lookup; returns None on missing id or unknown row."""+ if not execution_id:+ return None+ try:+ return cast(WorkflowExecution, WorkflowExecution.objects.get(id=execution_id))+ except WorkflowExecution.DoesNotExist:+ # Catch ONLY DoesNotExist: a missing row is the fail-closed case+ # (_apply_failure_filter then drops notify_on_failures rows). A malformed+ # id raises ValueError/ValidationError and must keep propagating to the+ # handler's 500 — do not widen this except, or the two paths collapse.+ # Strip CR/LF from the query-param id before logging (log-forging guard).+ logger.warning(+ "WorkflowExecution %s not found",+ execution_id.replace("\r", "").replace("\n", ""),+ )+ return None+++def _apply_failure_filter(+ notifications_qs: QuerySet[Notification],+ execution: WorkflowExecution | None,+ execution_id: str | None = None,+) -> QuerySet[Notification]:+ """Drop notify_on_failures=True rows on success (or unconfirmable) runs.++ Uses the shared rule in notification_v2.helper.is_failure_run (status ∈+ {ERROR, STOPPED} OR any file errored), the same rule applied by+ backend/api_v2/notification.py. The pipeline backend path+ (backend/pipeline_v2/notification.py) ORs an additional last_run_status+ backstop on top for the case where no WorkflowExecution exists.++ Three lookup outcomes:+ - No execution_id requested → no filter, preserving legacy "return every+ active row" behavior for callers that don't pass execution_id.+ - execution_id requested but the row is missing (replication lag / a race+ between the status write and this fetch) → fail CLOSED: drop+ notify_on_failures rows so a run we cannot confirm as a failure never+ sends a success alert to a failure-only subscriber. Emits a metric so the+ rare miss is observable. notify_on_failures=False rows are unaffected.+ - execution found → apply is_failure_run.+ """+ if execution is None:+ if execution_id:+ # Strip CR/LF from the query-param id before logging (log-forging+ # guard, SonarCloud S5145); it is UUID-validated upstream.+ logger.warning(+ "metric=notification_failure_filter_fail_closed_total execution_id=%s",+ execution_id.replace("\r", "").replace("\n", ""),+ )+ return notifications_qs.filter(notify_on_failures=False)+ return notifications_qs+ if not is_failure_run(execution.status, execution.failed_files):+ notifications_qs = notifications_qs.filter(notify_on_failures=False)+ return notifications_qs+++def _execution_counts(execution: WorkflowExecution | None) -> dict[str, int]:+ """File counts surfaced into webhook payloads. Empty dict on no execution."""+ if execution is None:+ return {}+ return {+ "total_files": execution.total_files or 0,+ "successful_files": execution.successful_files or 0,+ "failed_files": execution.failed_files or 0,+ }+++def _serialize_notification(n: Notification) -> dict[str, Any]:+ return {+ "id": str(n.id),+ "notification_type": n.notification_type,+ "platform": n.platform,+ "url": n.url,+ "authorization_type": n.authorization_type,+ "authorization_key": n.authorization_key,+ "authorization_header": n.authorization_header,+ "max_retries": n.max_retries,+ "is_active": n.is_active,+ "notify_on_failures": n.notify_on_failures,+ }++@csrf_exempt # Safe: Internal API with Bearer token auth, service-to-service only@require_http_methods(["GET"])-def get_pipeline_notifications(request, pipeline_id):+def get_pipeline_notifications(request: HttpRequest, pipeline_id: str) -> JsonResponse:"""Get active notifications for a pipeline or API deployment.Used by callback worker to fetch notification configuration.@@ -41,83 +141,54 @@ def get_pipeline_notifications(request, pipeline_id):pipeline_queryset, request, "organization")+ execution_id = request.GET.get("execution_id")+ execution = _load_execution(execution_id)+ counts = _execution_counts(execution)+if pipeline_queryset.exists():pipeline = pipeline_queryset.first()-- # Get active notifications for this pipelinenotifications = Notification.objects.filter(pipeline=pipeline, is_active=True)-- notifications_data = []- for notification in notifications:- notifications_data.append(- {- "id": str(notification.id),- "notification_type": notification.notification_type,- "platform": notification.platform,- "url": notification.url,- "authorization_type": notification.authorization_type,- "authorization_key": notification.authorization_key,- "authorization_header": notification.authorization_header,- "max_retries": notification.max_retries,- "is_active": notification.is_active,- }- )-+ notifications = _apply_failure_filter(notifications, execution, execution_id)+ serialized = [_serialize_notification(n) for n in notifications]return JsonResponse({"status": "success","pipeline_id": str(pipeline.id),"pipeline_name": pipeline.pipeline_name,"pipeline_type": pipeline.pipeline_type,- "notifications": notifications_data,+ "notifications": serialized,+ "execution_counts": counts,})- else:- # If not found in Pipeline, try APIDeployment model- api_queryset = APIDeployment.objects.filter(id=pipeline_id)- api_queryset = filter_queryset_by_organization(- api_queryset, request, "organization"++ # If not found in Pipeline, try APIDeployment model+ api_queryset = APIDeployment.objects.filter(id=pipeline_id)+ api_queryset = filter_queryset_by_organization(+ api_queryset, request, "organization"+ )+ if api_queryset.exists():+ api = api_queryset.first()+ notifications = Notification.objects.filter(api=api, is_active=True)+ notifications = _apply_failure_filter(notifications, execution, execution_id)+ serialized = [_serialize_notification(n) for n in notifications]+ return JsonResponse(+ {+ "status": "success",+ "pipeline_id": str(api.id),+ "pipeline_name": api.api_name,+ "pipeline_type": "API",+ "notifications": serialized,+ "execution_counts": counts,+ })- if api_queryset.exists():- api = api_queryset.first()-- # Get active notifications for this API deployment- notifications = Notification.objects.filter(api=api, is_active=True)-- notifications_data = []- for notification in notifications:- notifications_data.append(- {- "id": str(notification.id),- "notification_type": notification.notification_type,- "platform": notification.platform,- "url": notification.url,- "authorization_type": notification.authorization_type,- "authorization_key": notification.authorization_key,- "authorization_header": notification.authorization_header,- "max_retries": notification.max_retries,- "is_active": notification.is_active,- }- )-- return JsonResponse(- {- "status": "success",- "pipeline_id": str(api.id),- "pipeline_name": api.api_name,- "pipeline_type": "API",- "notifications": notifications_data,- }- )- else:- return JsonResponse(- {- "status": "error",- "message": "Pipeline or API deployment not found",- },- status=404,- )+ return JsonResponse(+ {+ "status": "error",+ "message": "Pipeline or API deployment not found",+ },+ status=404,+ )except Exception as e:logger.error(f"Error getting pipeline notifications for {pipeline_id}: {e}")return JsonResponse(@@ -127,7 +198,7 @@ def get_pipeline_notifications(request, pipeline_id):@csrf_exempt # Safe: Internal API with Bearer token auth, service-to-service only@require_http_methods(["GET"])-def get_api_notifications(request, api_id):+def get_api_notifications(request: HttpRequest, api_id: str) -> JsonResponse:"""Get active notifications for an API deployment.Used by callback worker to fetch notification configuration.@@ -140,24 +211,10 @@ def get_api_notifications(request, api_id):)api = get_object_or_404(api_queryset)- # Get active notifications for this API+ execution_id = request.GET.get("execution_id")+ execution = _load_execution(execution_id)notifications = Notification.objects.filter(api=api, is_active=True)-- notifications_data = []- for notification in notifications:- notifications_data.append(- {- "id": str(notification.id),- "notification_type": notification.notification_type,- "platform": notification.platform,- "url": notification.url,- "authorization_type": notification.authorization_type,- "authorization_key": notification.authorization_key,- "authorization_header": notification.authorization_header,- "max_retries": notification.max_retries,- "is_active": notification.is_active,- }- )+ notifications = _apply_failure_filter(notifications, execution, execution_id)return JsonResponse({@@ -165,7 +222,8 @@ def get_api_notifications(request, api_id):"api_id": str(api.id),"api_name": api.api_name,"display_name": api.display_name,- "notifications": notifications_data,+ "notifications": [_serialize_notification(n) for n in notifications],+ "execution_counts": _execution_counts(execution),})@@ -182,7 +240,7 @@ def get_api_notifications(request, api_id):@csrf_exempt # Safe: Internal API with Bearer token auth, service-to-service only@require_http_methods(["GET"])-def get_pipeline_data(request, pipeline_id):+def get_pipeline_data(request: HttpRequest, pipeline_id: str) -> JsonResponse:"""Get basic pipeline data for notification purposes.Used by callback worker to determine pipeline type and name.@@ -218,7 +276,7 @@ def get_pipeline_data(request, pipeline_id):@csrf_exempt # Safe: Internal API with Bearer token auth, service-to-service only@require_http_methods(["GET"])-def get_api_data(request, api_id):+def get_api_data(request: HttpRequest, api_id: str) -> JsonResponse:"""Get basic API deployment data for notification purposes.Used by callback worker to determine API name and details.@@ -250,3 +308,475 @@ def get_api_data(request, api_id):return JsonResponse({"status": "error", "message": INTERNAL_SERVER_ERROR_MSG}, status=500)+++# `execution_id` is required except for INPROGRESS, which fires from the+# scheduler before the WorkflowExecution exists. INPROGRESS rows therefore+# store execution_id=null — receivers cannot correlate with execution logs+# until the producer ordering is changed.+_ENQUEUE_REQUIRED_FIELDS = (+ "notification_id",+ "pipeline_id",+ "pipeline_name",+ "status",+ "platform",+ "execution_id",+)+++@csrf_exempt # Safe: Internal API with Bearer token auth, service-to-service only+@require_http_methods(["POST"])+def enqueue_notification_buffer(request: HttpRequest) -> JsonResponse:+ """Buffer one execution event from a callback worker.++ Worker code is model-free: it forwards a notification_id + structured+ payload here and lets the backend write the NotificationBuffer row.+ Required fields are validated up front; an INPROGRESS event for a+ failure-only notification is dropped here, since the GET-side filter+ cannot see it (no WorkflowExecution exists yet at run start).+ """+ try:+ body = json.loads(request.body.decode("utf-8") or "{}")+ except json.JSONDecodeError:+ return JsonResponse(+ {"status": "error", "message": "Invalid JSON body"}, status=400+ )++ missing_fields = [f for f in _ENQUEUE_REQUIRED_FIELDS if not body.get(f)]+ # INPROGRESS is the one status legitimately allowed to omit execution_id+ # (see comment on _ENQUEUE_REQUIRED_FIELDS).+ if (+ body.get("status") == Pipeline.PipelineStatus.INPROGRESS+ and "execution_id" in missing_fields+ ):+ missing_fields.remove("execution_id")+ if missing_fields:+ return JsonResponse(+ {+ "status": "error",+ "message": f"Missing required fields: {', '.join(missing_fields)}",+ },+ status=400,+ )++ try:+ notification = Notification.objects.get(id=body["notification_id"])+ except Notification.DoesNotExist:+ return JsonResponse(+ {"status": "error", "message": "Notification not found"}, status=404+ )++ # INPROGRESS fires from the scheduler before a WorkflowExecution exists,+ # so the GET-side `_apply_failure_filter` cannot run (no execution → no+ # filter applied) and returns notify_on_failures=True rows too. Drop the+ # event here so failure-only subscribers never receive a run-start.+ if (+ notification.notify_on_failures+ and body.get("status") == Pipeline.PipelineStatus.INPROGRESS+ ):+ return JsonResponse({"status": "ok", "buffer_row_id": None})++ # type / timestamp / additional_data stay optional during rollout — older+ # worker builds that don't forward them still produce a usable row; the+ # single-line clubbed renderer simply omits the missing fields.+ payload = {+ "type": body.get("type", ""),+ "execution_id": body.get("execution_id"),+ "pipeline_id": body["pipeline_id"],+ "pipeline_name": body["pipeline_name"],+ "status": body["status"],+ "error_message": body.get("error_message"),+ "platform": body["platform"],+ "timestamp": body.get("timestamp"),+ "additional_data": body.get("additional_data") or {},+ }+ try:+ buffer_row = enqueue(notification, payload)+ except ValueError as e:+ return JsonResponse({"status": "error", "message": str(e)}, status=400)++ return JsonResponse(+ {"status": "success", "buffer_row_id": str(buffer_row.id)}, status=201+ )+++def _mark_buffer_rows(+ request: HttpRequest, *, target_status: str, metric_result: str+) -> JsonResponse:+ """Flip a clubbed dispatch's buffer rows to a terminal state.++ Replaces the old Celery ``link``/``link_error`` callbacks: the notification+ worker POSTs here on delivery success / retry exhaustion instead of relying+ on a backend Celery task being registered on the ``celery`` queue (the+ unified ``-A worker`` that also drains that queue does not register those+ tasks, so half the callbacks were silently dropped). Only rows still in+ SENDING and owned by ``organization_id`` are transitioned — a reaper-+ reclaimed/re-dispatched row or a cross-tenant id must never be clobbered.+ """+ try:+ body = json.loads(request.body.decode("utf-8") or "{}")+ except json.JSONDecodeError:+ return JsonResponse(+ {"status": "error", "message": "Invalid JSON body"}, status=400+ )++ ids = body.get("buffer_row_ids") or []+ org_id = body.get("organization_id")+ if not ids or not org_id:+ return JsonResponse(+ {+ "status": "error",+ "message": "buffer_row_ids and organization_id are required",+ },+ status=400,+ )++ updated: int = NotificationBuffer.objects.filter(+ id__in=ids,+ organization_id=org_id,+ status=BufferStatus.SENDING.value,+ ).update(status=target_status)+ logger.info(+ "metric=notification_batch_dispatched_total result=%s rows=%d",+ metric_result,+ updated,+ )+ return JsonResponse({"status": "success", "updated": int(updated)})+++@csrf_exempt # Safe: Internal API with Bearer token auth, service-to-service only+@require_http_methods(["POST"])+def mark_buffer_dispatched(request: HttpRequest) -> JsonResponse:+ """Worker reports a clubbed webhook delivered: SENDING -> DISPATCHED."""+ return _mark_buffer_rows(+ request, target_status=BufferStatus.DISPATCHED.value, metric_result="delivered"+ )+++@csrf_exempt # Safe: Internal API with Bearer token auth, service-to-service only+@require_http_methods(["POST"])+def mark_buffer_dead_letter(request: HttpRequest) -> JsonResponse:+ """Worker reports a clubbed webhook exhausted retries: SENDING -> DEAD_LETTER."""+ return _mark_buffer_rows(+ request,+ target_status=BufferStatus.DEAD_LETTER.value,+ metric_result="dead_letter",+ )+++def _gc_terminal_rows() -> int:+ """Delete buffer rows past the retention window.++ Two sweeps:+ - Terminal rows (DISPATCHED / DEAD_LETTER) older than the retention+ window: hygiene for completed work.+ - PENDING rows whose source notification has been deactivated and+ whose ``flush_after`` has aged past the same window: ``_dispatch_group``+ filters ``notification__is_active=True``, so without this sweep+ these rows are unreachable from both dispatch and GC and would+ accumulate forever in the partial PENDING index.++ PENDING rows attached to active notifications are intentionally+ untouched regardless of age — they represent live work the flush+ job still owns.+ """+ cutoff = timezone.now() - timedelta(days=settings.NOTIFICATION_BUFFER_RETENTION_DAYS)+ terminal_deleted, _ = NotificationBuffer.objects.filter(+ status__in=[BufferStatus.DISPATCHED.value, BufferStatus.DEAD_LETTER.value],+ created_at__lt=cutoff,+ ).delete()+ inactive_deleted, _ = NotificationBuffer.objects.filter(+ status=BufferStatus.PENDING.value,+ notification__is_active=False,+ flush_after__lt=cutoff,+ ).delete()+ return int(terminal_deleted) + int(inactive_deleted)+++def _reclaim_stale_sending() -> int:+ """Return rows stuck in SENDING past the dispatch lease to PENDING.++ Covers the crash window where a flush committed the SENDING claim but no+ terminal callback ever ran (e.g. the backend died before the on_commit+ publish, or the worker vanished). The lease must exceed the worst-case retry+ duration so genuinely in-flight dispatches are never reclaimed mid-flight.+ """+ cutoff = timezone.now() - timedelta(+ seconds=settings.NOTIFICATION_DISPATCH_LEASE_SECONDS+ )+ reclaimed = NotificationBuffer.objects.filter(+ status=BufferStatus.SENDING.value,+ dispatched_at__lt=cutoff,+ ).update(status=BufferStatus.PENDING.value, dispatched_at=None)+ if reclaimed:+ logger.warning("metric=notification_buffer_reclaimed_total rows=%d", reclaimed)+ return int(reclaimed)+++def _send_clubbed(+ *,+ url: str,+ body: Any,+ headers: dict[str, str],+ platform: str,+ max_retries: int,+ buffer_ids: list[str],+ org_id: Any,+) -> None:+ """Send the clubbed Celery task after the DB transition has committed.++ Runs as a ``transaction.on_commit`` callback so a rolled-back UPDATE can+ never leave a broker-queued message orphaned (the prior order — send+ then update — risked duplicate delivery if the UPDATE failed). On broker+ failure we revert rows back to PENDING in a separate transaction so the+ next flush tick retries cleanly.++ The buffer rows' terminal transition is reported back by the notification+ worker over the internal API (``buffer/mark/dispatched`` /+ ``buffer/mark/dead-letter``), not via Celery ``link``/``link_error``: those+ callbacks routed to the ``celery`` queue, which the unified ``-A worker``+ also drains without the backend tasks registered, so ~half were dropped as+ "unregistered task" and the rows stuck in SENDING. We therefore pass+ ``buffer_row_ids`` + ``organization_id`` to the worker so it can mark them.+ """+ try:+ celery_app.send_task(+ "send_webhook_notification",+ args=[url, body, headers, settings.NOTIFICATION_TIMEOUT],+ kwargs={+ "max_retries": max_retries,+ "retry_delay": 10,+ "platform": platform,+ # Re-raise on retry exhaustion so the task ends in FAILURE for+ # monitoring; the worker marks the rows DEAD_LETTER over the+ # internal API before raising (see send_webhook_notification).+ "raise_on_final_failure": True,+ # Worker marks these rows DISPATCHED/DEAD_LETTER via the internal+ # mark endpoints (replaces Celery link/link_error).+ "buffer_row_ids": buffer_ids,+ "organization_id": org_id,+ },+ queue="notifications",+ )+ logger.info(+ "metric=notification_batch_dispatched_total platform=%s result=success "+ "org_id=%s webhook_url_hash=%s rows=%d",+ platform,+ org_id,+ webhook_url_hash(url),+ len(buffer_ids),+ )+ except Exception:+ logger.exception(+ "metric=notification_batch_dispatched_total platform=%s "+ "result=broker_failure org_id=%s webhook_url_hash=%s rows=%d",+ platform,+ org_id,+ webhook_url_hash(url),+ len(buffer_ids),+ )+ # Revert to PENDING (outside the committed txn) so a transient broker+ # outage retries next tick; refund the SENDING-claim attempt since nothing+ # was queued or sent. Guard on SENDING so a row the worker already marked+ # terminal (broker raised post-delivery) isn't resurrected into a duplicate.+ NotificationBuffer.objects.filter(+ id__in=buffer_ids,+ status=BufferStatus.SENDING.value,+ ).update(+ status=BufferStatus.PENDING.value,+ dispatched_at=None,+ dispatch_attempts=F("dispatch_attempts") - 1,+ )+++def _penalize_render_failure(buffer_ids: list[str], org_id: Any, platform: str) -> None:+ """Charge a dispatch attempt to a group whose payloads failed to render.++ The SENDING-claim increment never runs on a render failure, so count it here+ to let the cap dead-letter an un-renderable group instead of re-rendering it+ every flush tick (which also blocks every event clubbed with it).+ """+ NotificationBuffer.objects.filter(id__in=buffer_ids).update(+ dispatch_attempts=F("dispatch_attempts") + 1,+ )+ # logger.exception keeps the render traceback the caller used to log.+ logger.exception(+ "metric=notification_buffer_render_failed_total rows=%d org_id=%s platform=%s",+ len(buffer_ids),+ org_id,+ platform,+ )+++def _dispatch_group(+ org_id: Any,+ webhook_url: str,+ auth_sig: str,+ platform: str,+) -> int:+ """Dispatch a single (org, url, auth_sig, platform) group; returns the number of rows dispatched.++ Caller already filtered groups to MIN(flush_after) <= now. Locks rows+ with SKIP LOCKED so a sibling replica skips them rather than blocking.+ Re-fetches the source Notification each time for live auth (record may+ have been edited between enqueue and flush).+ """+ with transaction.atomic():+ rows = list(+ # of=("self",): lock only the buffer rows, not the joined Notification+ # row — else SKIP LOCKED skips the group when an unrelated txn (e.g. an+ # admin edit) holds the Notification.+ NotificationBuffer.objects.select_for_update(skip_locked=True, of=("self",))+ .select_related("notification")+ .filter(+ status=BufferStatus.PENDING.value,+ organization_id=org_id,+ webhook_url=webhook_url,+ auth_sig=auth_sig,+ platform=platform,+ notification__is_active=True,+ )+ .order_by("created_at")[:_PROCESS_BUFFER_CAP]+ )+ if not rows:+ # Either another replica claimed the rows (SKIP LOCKED) or they+ # transitioned out of PENDING between the GROUP BY scan and the+ # row-level lock. Either way: nothing to do here.+ return 0++ # Bound the reaper reclaim loop: a row reclaimed past its dispatch budget+ # (e.g. a crash that recurs in the dispatch->callback window keeps+ # returning it to PENDING) is dead-lettered here rather than re-dispatched+ # forever. Attempts are charged at the SENDING claim below (refunded on a+ # clean broker-publish failure) and on a render failure+ # (_penalize_render_failure).+ cap = settings.NOTIFICATION_MAX_DISPATCH_ATTEMPTS+ exhausted_ids = [str(r.id) for r in rows if r.dispatch_attempts >= cap]+ if exhausted_ids:+ NotificationBuffer.objects.filter(id__in=exhausted_ids).update(+ status=BufferStatus.DEAD_LETTER.value,+ )+ logger.warning(+ "metric=notification_buffer_dispatch_exhausted_total rows=%d "+ "org_id=%s platform=%s cap=%d",+ len(exhausted_ids),+ org_id,+ platform,+ cap,+ )+ rows = [r for r in rows if r.dispatch_attempts < cap]+ if not rows:+ return 0++ # Live auth — read from the FIRST row's notification. If multiple+ # notifications collide on (url, auth_sig, platform) we have, by+ # definition, identical auth + format, so this is safe. Retry budget+ # is the MAX across rows: there's a single HTTP call per batch, so+ # the most retry-tolerant subscriber's intent wins; using the first+ # row's value would silently truncate everyone else's retry budget.+ first_notification = rows[0].notification+ payloads = [r.payload for r in rows]+ buffer_ids = [str(r.id) for r in rows]+ try:+ body = render_clubbed_message(payloads, platform)+ headers = build_webhook_headers(first_notification)+ max_retries = max(r.notification.max_retries for r in rows)+ except Exception:+ # Poison payload: charge an attempt so the cap dead-letters the group+ # instead of re-rendering it forever (the caller swallows this error).+ _penalize_render_failure(buffer_ids, org_id, platform)+ return 0++ # Claim the rows as SENDING (the lease starts at dispatched_at) inside+ # the transaction; the on_commit hook then publishes the broker task. If+ # the commit fails, rows stay PENDING and nothing is published —+ # eliminating the broker-vs-DB duplicate-send race. SENDING rows are+ # excluded from the flush query, so they are not re-claimed until the+ # dispatch task's success/failure callback resolves them to+ # DISPATCHED / DEAD_LETTER (or the reaper reclaims a stale lease).+ now = timezone.now()+ NotificationBuffer.objects.filter(id__in=buffer_ids).update(+ status=BufferStatus.SENDING.value,+ dispatched_at=now,+ dispatch_attempts=F("dispatch_attempts") + 1,+ )+ transaction.on_commit(+ lambda: _send_clubbed(+ url=first_notification.url,+ body=body,+ headers=headers,+ platform=platform,+ max_retries=max_retries,+ buffer_ids=buffer_ids,+ org_id=org_id,+ )+ )+ return len(rows)+++# Per-group cap, bound to the renderer's MAX_BATCH_SIZE so the rendered events+# list and the dispatched row set stay in lock-step by construction (raising one+# can no longer silently mark un-rendered rows DISPATCHED). Anything beyond this+# rolls into the next flush tick.+_PROCESS_BUFFER_CAP = MAX_BATCH_SIZE+++@csrf_exempt # Safe: Internal API with Bearer token auth, service-to-service only+@require_http_methods(["POST"])+def process_notification_buffer(request: HttpRequest) -> JsonResponse:+ """Flush PENDING groups that have hit their flush_after; then GC.++ Algorithm:+ 1. GROUP BY (org, url, auth_sig, platform), HAVING MIN(flush_after) <= NOW()+ 2. For each group, in its own transaction: lock-skip-locked rows, render,+ mark rows SENDING, on_commit-dispatch a single Celery task whose success /+ failure callbacks move the rows to DISPATCHED / DEAD_LETTER.+ 3. Reclaim rows stuck in SENDING past the dispatch lease back to PENDING.+ 4. Sweep terminal rows older than NOTIFICATION_BUFFER_RETENTION_DAYS.++ Concurrency: SELECT FOR UPDATE SKIP LOCKED makes parallel calls safe —+ each replica skips groups another worker is already dispatching.+ """+ now = timezone.now()+ groups = list(+ NotificationBuffer.objects.filter(status=BufferStatus.PENDING.value)+ .values("organization_id", "webhook_url", "auth_sig", "platform")+ .annotate(earliest_flush=Min("flush_after"))+ .filter(earliest_flush__lte=now)+ )++ dispatched_groups = 0+ dispatched_rows = 0+ for group in groups:+ try:+ rows = _dispatch_group(+ org_id=group["organization_id"],+ webhook_url=group["webhook_url"],+ auth_sig=group["auth_sig"],+ platform=group["platform"],+ )+ except Exception:+ logger.exception(+ "Failed dispatching group org=%s url_hash=%s",+ group["organization_id"],+ webhook_url_hash(group["webhook_url"]),+ )+ continue+ if rows > 0:+ dispatched_groups += 1+ dispatched_rows += rows++ reclaimed_rows = _reclaim_stale_sending()+ gc_deleted = _gc_terminal_rows()+ return JsonResponse(+ {+ "status": "success",+ "dispatched_groups": dispatched_groups,+ "dispatched_rows": dispatched_rows,+ # DISPATCHED / DEAD_LETTER transitions are async (Celery success /+ # link_error callbacks) and are not reflected in this response.+ "dead_letter_rows": 0,+ "reclaimed_rows": reclaimed_rows,+ "gc_deleted_rows": gc_deleted,+ }+ )diff --git a/backend/notification_v2/internal_urls.py b/backend/notification_v2/internal_urls.pyindex 041476108..90da468fb 100644--- a/backend/notification_v2/internal_urls.py+++ b/backend/notification_v2/internal_urls.py@@ -21,6 +21,29 @@ router = DefaultRouter()router.register(r"", WebhookInternalViewSet, basename="webhook-internal")urlpatterns = [+ # Buffered (clubbed) notification dispatch endpoints+ path(+ "buffer/enqueue/",+ internal_api_views.enqueue_notification_buffer,+ name="enqueue_notification_buffer",+ ),+ path(+ "buffer/process/",+ internal_api_views.process_notification_buffer,+ name="process_notification_buffer",+ ),+ # Terminal-state marks posted by the notification worker after delivery+ # (replaces the old Celery link/link_error callbacks).+ path(+ "buffer/mark/dispatched/",+ internal_api_views.mark_buffer_dispatched,+ name="mark_buffer_dispatched",+ ),+ path(+ "buffer/mark/dead-letter/",+ internal_api_views.mark_buffer_dead_letter,+ name="mark_buffer_dead_letter",+ ),# Notification data endpoints for workerspath("pipeline/<str:pipeline_id>/notifications/",diff --git a/backend/notification_v2/migrations/0002_notification_batching.py b/backend/notification_v2/migrations/0002_notification_batching.pynew file mode 100644index 000000000..db0f862b3--- /dev/null+++ b/backend/notification_v2/migrations/0002_notification_batching.py@@ -0,0 +1,135 @@+import uuid++import django.db.models.deletion+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("account_v2", "0001_initial"),+ ("notification_v2", "0001_initial"),+ ]++ operations = [+ migrations.AddField(+ model_name="notification",+ name="notify_on_failures",+ field=models.BooleanField(+ default=False,+ db_comment=(+ "When True, fire only on failed runs — terminal status "+ "ERROR/STOPPED or any file in the run errored (partial "+ "failure). When False (default), fire on every terminal "+ "completion."+ ),+ ),+ ),+ migrations.CreateModel(+ name="NotificationBuffer",+ fields=[+ (+ "id",+ models.UUIDField(+ default=uuid.uuid4,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("modified_at", models.DateTimeField(auto_now=True)),+ (+ "webhook_url",+ models.URLField(+ db_comment="Denormalized destination URL; grouping key."+ ),+ ),+ (+ "payload",+ models.JSONField(+ db_comment="Pre-structured execution data (type, pipeline_id, pipeline_name, status, additional_data; optional execution_id, error_message, is_failure, timestamp) — NOT a final rendered message. The renderer formats this at dispatch time."+ ),+ ),+ (+ "platform",+ models.CharField(+ choices=[("SLACK", "Slack"), ("API", "Api")],+ db_comment="SLACK / API — drives renderer selection at flush time.",+ max_length=50,+ ),+ ),+ (+ "auth_sig",+ models.CharField(+ db_comment="SHA-256 hex of (auth_type + auth_key + auth_header), computed at enqueue time. Grouping key — never store raw credentials here.",+ max_length=64,+ ),+ ),+ (+ "flush_after",+ models.DateTimeField(+ db_comment="now() at enqueue + the org's effective club interval (per-org Configuration override, else the NOTIFICATION_CLUB_INTERVAL default), precomputed at enqueue. Read-at-enqueue contract: changing the interval only affects rows enqueued afterward."+ ),+ ),+ ("dispatched_at", models.DateTimeField(blank=True, null=True)),+ (+ "dispatch_attempts",+ models.PositiveIntegerField(+ db_comment="Count of times this row has been claimed for dispatch (incremented on each PENDING -> SENDING transition). Bounds the reaper reclaim loop: at NOTIFICATION_MAX_DISPATCH_ATTEMPTS the row is dead-lettered instead of re-dispatched, so a lost terminal callback cannot redeliver forever.",+ default=0,+ ),+ ),+ (+ "status",+ models.CharField(+ choices=[+ ("PENDING", "Pending"),+ ("SENDING", "Sending"),+ ("DISPATCHED", "Dispatched"),+ ("DEAD_LETTER", "Dead letter"),+ ],+ db_comment="Lifecycle: PENDING -> SENDING (claimed by a flush tick) -> DISPATCHED on success / DEAD_LETTER on retry exhaustion or once dispatch_attempts hits NOTIFICATION_MAX_DISPATCH_ATTEMPTS. A SENDING row whose lease expires is reclaimed back to PENDING by the reaper.",+ default="PENDING",+ max_length=16,+ ),+ ),+ (+ "notification",+ models.ForeignKey(+ db_comment="Source Notification. Cascade-delete is intentional: removing a Notification expresses intent to stop all future deliveries, including buffered ones.",+ on_delete=django.db.models.deletion.CASCADE,+ related_name="buffer_rows",+ to="notification_v2.notification",+ ),+ ),+ (+ "organization",+ models.ForeignKey(+ db_comment="Tenant scope. Mandatory grouping key — prevents cross-tenant leakage at flush time.",+ on_delete=django.db.models.deletion.CASCADE,+ related_name="notification_buffer_rows",+ to="account_v2.organization",+ ),+ ),+ ],+ options={+ "verbose_name": "Notification Buffer",+ "verbose_name_plural": "Notification Buffers",+ "db_table": "notification_buffer",+ },+ ),+ migrations.AddIndex(+ model_name="notificationbuffer",+ index=models.Index(+ condition=models.Q(("status", "PENDING")),+ fields=[+ "organization",+ "webhook_url",+ "auth_sig",+ "platform",+ "flush_after",+ ],+ name="idx_notif_buffer_pending",+ ),+ ),+ ]diff --git a/backend/notification_v2/models.py b/backend/notification_v2/models.pyindex 489a8c827..74a891232 100644--- a/backend/notification_v2/models.py+++ b/backend/notification_v2/models.py@@ -1,13 +1,20 @@import uuid+from account_v2.models import Organizationfrom api_v2.models import APIDeploymentfrom django.db import modelsfrom pipeline_v2.models import Pipelinefrom utils.models.base_model import BaseModel-from .enums import AuthorizationType, NotificationType, PlatformType+from .enums import (+ AuthorizationType,+ BufferStatus,+ NotificationType,+ PlatformType,+)NOTIFICATION_NAME_MAX_LENGTH = 255+AUTH_SIG_LENGTH = 64 # SHA-256 hex digestclass Notification(BaseModel):@@ -47,6 +54,14 @@ class Notification(BaseModel):default=True,db_comment="Flag indicating whether the notification is active or not.",)+ notify_on_failures = models.BooleanField(+ default=False,+ db_comment=(+ "When True, fire only on failed runs — terminal status ERROR/STOPPED "+ "or any file in the run errored (partial failure). When False "+ "(default), fire on every terminal completion."+ ),+ )# Foreign keys to specific modelspipeline = models.ForeignKey(Pipeline,@@ -92,3 +107,117 @@ class Notification(BaseModel):f"Notification {self.id}: (Type: {self.notification_type}, "f"Platform: {self.platform}, Url: {self.url}))")+++class NotificationBuffer(BaseModel):+ """Per-execution event buffered for clubbed (batched) dispatch.++ One row is written per workflow completion. The flush job groups rows by+ (organization, webhook_url, auth_sig, platform), renders one clubbed message+ per group, and dispatches via the existing send_webhook_notification Celery+ task. Group key includes auth_sig because two notifications may share the+ same URL but use different credentials — they must dispatch separately; it+ includes platform so SLACK and API rows never share a rendered batch.+ """++ id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)+ notification = models.ForeignKey(+ Notification,+ on_delete=models.CASCADE,+ related_name="buffer_rows",+ db_comment=(+ "Source Notification. Cascade-delete is intentional: removing a "+ "Notification expresses intent to stop all future deliveries, "+ "including buffered ones."+ ),+ )+ organization = models.ForeignKey(+ Organization,+ on_delete=models.CASCADE,+ related_name="notification_buffer_rows",+ db_comment=(+ "Tenant scope. Mandatory grouping key — prevents cross-tenant "+ "leakage at flush time."+ ),+ )+ webhook_url = models.URLField(+ db_comment="Denormalized destination URL; grouping key.",+ )+ payload = models.JSONField(+ db_comment=(+ "Pre-structured execution data (type, pipeline_id, pipeline_name, "+ "status, additional_data; optional execution_id, error_message, "+ "is_failure, timestamp) — NOT a final rendered message. The renderer "+ "formats this at dispatch time."+ ),+ )+ platform = models.CharField(+ max_length=50,+ choices=PlatformType.choices(),+ db_comment="SLACK / API — drives renderer selection at flush time.",+ )+ auth_sig = models.CharField(+ max_length=AUTH_SIG_LENGTH,+ db_comment=(+ "SHA-256 hex of (auth_type + auth_key + auth_header), computed at "+ "enqueue time. Grouping key — never store raw credentials here."+ ),+ )+ flush_after = models.DateTimeField(+ db_comment=(+ "now() at enqueue + the org's effective club interval (per-org "+ "Configuration override, else the NOTIFICATION_CLUB_INTERVAL "+ "default), precomputed at enqueue. Read-at-enqueue contract: "+ "changing the interval only affects rows enqueued afterward."+ ),+ )+ dispatched_at = models.DateTimeField(null=True, blank=True)+ dispatch_attempts = models.PositiveIntegerField(+ default=0,+ db_comment=(+ "Count of times this row has been claimed for dispatch (incremented "+ "on each PENDING -> SENDING transition). Bounds the reaper reclaim "+ "loop: at NOTIFICATION_MAX_DISPATCH_ATTEMPTS the row is dead-lettered "+ "instead of re-dispatched, so a lost terminal callback cannot redeliver "+ "forever."+ ),+ )+ status = models.CharField(+ max_length=16,+ choices=BufferStatus.choices(),+ default=BufferStatus.PENDING.value,+ db_comment=(+ "Lifecycle: PENDING -> SENDING (claimed by a flush tick) -> "+ "DISPATCHED on success / DEAD_LETTER on retry exhaustion or once "+ "dispatch_attempts hits NOTIFICATION_MAX_DISPATCH_ATTEMPTS. A SENDING "+ "row whose lease expires is reclaimed back to PENDING by the reaper."+ ),+ )++ class Meta:+ verbose_name = "Notification Buffer"+ verbose_name_plural = "Notification Buffers"+ db_table = "notification_buffer"+ indexes = [+ # Partial covering index — supports Index Only Scans on the flush+ # GROUP BY query and bounds index size to live PENDING backlog.+ # `platform` is part of the grouping key so SLACK and API rows on+ # the same (org, url, auth) split into separate dispatches.+ models.Index(+ fields=[+ "organization",+ "webhook_url",+ "auth_sig",+ "platform",+ "flush_after",+ ],+ name="idx_notif_buffer_pending",+ condition=models.Q(status=BufferStatus.PENDING.value),+ ),+ ]++ def __str__(self) -> str:+ return (+ f"NotificationBuffer {self.id}: status={self.status} "+ f"flush_after={self.flush_after.isoformat() if self.flush_after else 'n/a'}"+ )diff --git a/backend/notification_v2/provider/__init__.py b/backend/notification_v2/provider/__init__.pydeleted file mode 100644index e69de29bb..000000000diff --git a/backend/notification_v2/provider/notification_provider.py b/backend/notification_v2/provider/notification_provider.pydeleted file mode 100644index 10492aaf3..000000000--- a/backend/notification_v2/provider/notification_provider.py+++ /dev/null@@ -1,30 +0,0 @@-from abc import ABC, abstractmethod--from django.conf import settings--from notification_v2.models import Notification---class NotificationProvider(ABC):- NOTIFICATION_TIMEOUT = settings.NOTIFICATION_TIMEOUT- RETRY_DELAY = 10 # Seconds-- def __init__(self, notification: Notification, payload):- self.payload = payload- self.notification = notification-- @abstractmethod- def send(self):- """Method to be overridden in child classes for sending the- notification.- """- raise NotImplementedError("Subclasses should implement this method.")-- def validate(self):- """Method to validate the notification data."""- pass-- @abstractmethod- def get_headers(self):- """Method to get the headers for the notification."""- raise NotImplementedError("Subclasses should implement this method.")diff --git a/backend/notification_v2/provider/registry.py b/backend/notification_v2/provider/registry.pydeleted file mode 100644index 909ad58b4..000000000--- a/backend/notification_v2/provider/registry.py+++ /dev/null@@ -1,54 +0,0 @@-from notification_v2.enums import NotificationType, PlatformType-from notification_v2.provider.notification_provider import NotificationProvider-from notification_v2.provider.webhook.api_webhook import APIWebhook-from notification_v2.provider.webhook.slack_webhook import SlackWebhook--REGISTRY = {- NotificationType.WEBHOOK: {- PlatformType.SLACK: SlackWebhook,- PlatformType.API: APIWebhook,- # Add other platform-specific classes here- },- # Add other notification types and classes here-}---def get_notification_provider(- notification_type: NotificationType, platform_type: PlatformType-) -> NotificationProvider:- """Get Notification provider based on notification type and platform type- It uses the REGISTRY to map the combination of notification type and- platform type to the corresponding NotificationProvider class.-- If the provided combination is not found in the REGISTRY, a ValueError is raised.-- Note:- This function assumes that the REGISTRY dictionary is correctly populated- with the appropriate NotificationProvider classes for each combination of- notification type and platform type.-- See Also:- - NotificationType- - PlatformType- - NotificationProvider- - REGISTRY-- Parameters:- notification_type (NotificationType): The type of notification.- platform_type (PlatformType): The platform/provider type for the notification.-- Returns:- NotificationProvider: The appropriate NotificationProvider class for- the given combination.-- Raises:- ValueError: If the provided combination is not found in the REGISTRY.- """- if notification_type not in REGISTRY:- raise ValueError(f"Unsupported notification type: {notification_type}")-- platform_registry = REGISTRY[notification_type]- if platform_type not in platform_registry:- raise ValueError(f"Unsupported platform type: {platform_type}")-- return platform_registry[platform_type]diff --git a/backend/notification_v2/provider/webhook/__init__.py b/backend/notification_v2/provider/webhook/__init__.pydeleted file mode 100644index e69de29bb..000000000diff --git a/backend/notification_v2/provider/webhook/api_webhook.py b/backend/notification_v2/provider/webhook/api_webhook.pydeleted file mode 100644index 9f1264b9e..000000000--- a/backend/notification_v2/provider/webhook/api_webhook.py+++ /dev/null@@ -1,13 +0,0 @@-from notification_v2.provider.webhook.webhook import Webhook---class APIWebhook(Webhook):- def send(self):- """Send the API webhook notification."""- super().send()-- def get_headers(self):- """API-specific headers."""- headers = super().get_headers()- headers["Content-Type"] = "application/json"- return headersdiff --git a/backend/notification_v2/provider/webhook/slack_webhook.py b/backend/notification_v2/provider/webhook/slack_webhook.pydeleted file mode 100644index 45e260b68..000000000--- a/backend/notification_v2/provider/webhook/slack_webhook.py+++ /dev/null@@ -1,60 +0,0 @@-import logging--from notification_v2.provider.webhook.webhook import Webhook--logger = logging.getLogger(__name__)---class SlackWebhook(Webhook):- def send(self):- """Send the Slack webhook notification."""- formatted_payload = self.format_payload()- self.payload = formatted_payload- super().send()-- def get_headers(self):- """Slack-specific headers."""- headers = super().get_headers()- headers["Content-Type"] = "application/json"- return headers-- def format_payload(self) -> dict:- """Format the payload to match Slack's expected structure."""- if "text" not in self.payload:- # Construct a basic Slack message with 'text' field- formatted_payload = {- "text": "Notification",- "blocks": self.create_blocks_from_payload(),- }- else:- # If 'text' is already present, format accordingly- formatted_payload = {- "text": self.payload.pop("text"),- "blocks": self.create_blocks_from_payload(),- }- return formatted_payload-- def create_blocks_from_payload(self) -> list:- """Create Slack blocks from the given payload."""- blocks = []- # Header- blocks.append(- {- "type": "section",- "text": {"type": "mrkdwn", "text": "*Unstract Update:*"},- }- )- # Add a divider for separation- blocks.append({"type": "divider"})- # Add each key-value pair to the blocks- for key, value in self.payload.items():- formatted_key = key.replace("_", " ").title()- blocks.append(- {- "type": "section",- "text": {"type": "mrkdwn", "text": f"*{formatted_key}:* {value}"},- }- )- # Footer- blocks.append({"type": "section", "text": {"type": "mrkdwn", "text": "*---*"}})- return blocksdiff --git a/backend/notification_v2/provider/webhook/webhook.py b/backend/notification_v2/provider/webhook/webhook.pydeleted file mode 100644index 549336a5f..000000000--- a/backend/notification_v2/provider/webhook/webhook.py+++ /dev/null@@ -1,103 +0,0 @@-import logging--from backend.celery_service import app as celery_app-from notification_v2.enums import AuthorizationType-from notification_v2.provider.notification_provider import NotificationProvider--logger = logging.getLogger(__name__)---class WebhookNotificationArg:- MAX_RETRIES = "max_retries"- RETRY_DELAY = "retry_delay"---class HeaderConstants:- APPLICATION_JSON = "application/json"---class Webhook(NotificationProvider):- def send(self):- """Send the webhook notification."""- try:- headers = self.get_headers()- self.validate()- except ValueError as e:- logger.error(f"Error validating notification {self.notification} :: {e}")- return- celery_app.send_task(- "send_webhook_notification",- args=[- self.notification.url,- self.payload,- headers,- self.NOTIFICATION_TIMEOUT,- ],- kwargs={- WebhookNotificationArg.MAX_RETRIES: self.notification.max_retries,- WebhookNotificationArg.RETRY_DELAY: self.RETRY_DELAY,- },- )-- def validate(self):- """Validate notification.-- Returns:- _type_: None- """- if not self.notification.url:- raise ValueError("Webhook URL is required.")- if not self.payload:- raise ValueError("Payload is required.")- return super().validate()-- def get_headers(self):- """Get the headers for the notification based on the authorization type and key.-- Raises:- ValueError: _description_-- Returns:- dict[str, str]: A dictionary containing the headers.- """- headers = {}- try:- authorization_type = AuthorizationType(- self.notification.authorization_type.upper()- )- except ValueError:- raise ValueError(- "Unsupported authorization type: "- f"{self.notification.authorization_type}"- )- authorization_key = self.notification.authorization_key- authorization_header = self.notification.authorization_header-- header_formats = {- AuthorizationType.BEARER: lambda key: {- "Authorization": f"Bearer {key}",- "Content-Type": HeaderConstants.APPLICATION_JSON,- },- AuthorizationType.API_KEY: lambda key: {- "Authorization": key,- "Content-Type": HeaderConstants.APPLICATION_JSON,- },- AuthorizationType.CUSTOM_HEADER: lambda key: {- authorization_header: key,- "Content-Type": HeaderConstants.APPLICATION_JSON,- },- AuthorizationType.NONE: lambda _: {- "Content-Type": HeaderConstants.APPLICATION_JSON,- },- }-- if authorization_type not in header_formats:- raise ValueError(f"Unsupported authorization type: {authorization_type}")-- headers = header_formats[authorization_type](authorization_key)-- # Check if custom header type has required details- if authorization_type == AuthorizationType.CUSTOM_HEADER:- if not authorization_header or not authorization_key:- raise ValueError("Custom header or key missing for custom authorization.")- return headersdiff --git a/backend/notification_v2/serializers.py b/backend/notification_v2/serializers.pyindex 115487c48..54a65a08d 100644--- a/backend/notification_v2/serializers.py+++ b/backend/notification_v2/serializers.py@@ -5,6 +5,14 @@ from .enums import AuthorizationType, NotificationType, PlatformTypefrom .models import Notification+class NotificationSettingsSerializer(serializers.Serializer):+ """Org-scoped notification batching settings."""++ # Bounds (1 min – 2 h) mirror ConfigKey.NOTIFICATION_CLUB_INTERVAL so DRF+ # returns a structured 400 before ConfigKey.cast_value re-raises.+ club_interval_seconds = serializers.IntegerField(min_value=60, max_value=7200)++class NotificationSerializer(serializers.ModelSerializer):notification_type = serializers.ChoiceField(choices=NotificationType.choices())authorization_type = serializers.ChoiceField(choices=AuthorizationType.choices())@@ -12,6 +20,7 @@ class NotificationSerializer(serializers.ModelSerializer):max_retries = serializers.IntegerField(max_value=4, min_value=0, default=0, required=False)+ notify_on_failures = serializers.BooleanField(default=False, required=False)class Meta:model = Notificationdiff --git a/backend/notification_v2/tasks.py b/backend/notification_v2/tasks.pynew file mode 100644index 000000000..fc98cbb0d--- /dev/null+++ b/backend/notification_v2/tasks.py@@ -0,0 +1,94 @@+"""Celery tasks owned by notification_v2.++DEPRECATED — retained only to drain any in-flight Celery messages during+rollout. The clubbed dispatch no longer wires these as ``link``/``link_error``:+they routed to the ``celery`` queue, which the unified ``-A worker`` also drains+without these backend tasks registered, so ~half the callbacks were silently+dropped ("Received unregistered task") and the buffer rows stuck in SENDING.+The notification worker now reports the terminal state over the internal API+(``buffer/mark/dispatched`` / ``buffer/mark/dead-letter`` →+``notification_v2.internal_api_views``) instead. Safe to remove once no+pre-upgrade messages remain in the broker.++Both tasks only transition rows still in ``SENDING`` — on success to+``DISPATCHED``, on terminal failure to ``DEAD_LETTER`` — so the flush job will+not re-pick them.+"""++from __future__ import annotations++import logging+from collections.abc import Iterable+from typing import Any++from backend.celery_service import app as celery_app+from notification_v2.enums import BufferStatus+from notification_v2.models import NotificationBuffer++logger = logging.getLogger(__name__)+++@celery_app.task(name="notification_v2.mark_buffer_dead_letter")+def mark_buffer_dead_letter(+ request: Any,+ exc: Any = None,+ traceback: Any = None,+ *,+ buffer_row_ids: Iterable[str] | None = None,+) -> int:+ """Mark a clubbed dispatch's rows as DEAD_LETTER on terminal failure.++ Celery's ``link_error`` signature passes ``(request, exc, traceback)`` to+ the callback; the actual buffer ids are bound at dispatch time via task+ kwargs. Returns the row count for visibility in flower.+ """+ if not buffer_row_ids:+ logger.warning(+ "mark_buffer_dead_letter invoked without buffer_row_ids — nothing to do"+ )+ return 0+ ids = list(buffer_row_ids)+ # Only transition rows still in SENDING — a row the reaper has already+ # reclaimed (back to PENDING / re-dispatched) must not be clobbered by a+ # stale callback from a superseded attempt.+ updated: int = NotificationBuffer.objects.filter(+ id__in=ids, status=BufferStatus.SENDING.value+ ).update(status=BufferStatus.DEAD_LETTER.value)+ # A dead-lettered batch is a delivered-never event — include a row-id sample+ # so it is traceable back to specific buffer rows (and their org/url) without+ # grepping the whole batch.+ logger.warning(+ "metric=notification_batch_dispatched_total result=dead_letter rows=%d "+ "exc=%r sample=%s",+ updated,+ exc,+ ids[0] if ids else "none",+ )+ return updated+++@celery_app.task(name="notification_v2.mark_buffer_dispatched")+def mark_buffer_dispatched(+ result: Any = None,+ *,+ buffer_row_ids: Iterable[str] | None = None,+) -> int:+ """Mark a clubbed dispatch's rows DISPATCHED on delivery success.++ Wired as the Celery ``link`` (success callback) of+ ``send_webhook_notification``. Celery passes the parent task's return value+ as the first positional arg, hence ``result``; the buffer ids are bound at+ dispatch time via task kwargs. Only flips rows still in SENDING so a+ reaper-reclaimed / re-dispatched row is not clobbered by a stale callback.+ """+ if not buffer_row_ids:+ return 0+ ids = list(buffer_row_ids)+ updated: int = NotificationBuffer.objects.filter(+ id__in=ids, status=BufferStatus.SENDING.value+ ).update(status=BufferStatus.DISPATCHED.value)+ logger.info(+ "metric=notification_batch_dispatched_total result=delivered rows=%d",+ updated,+ )+ return updateddiff --git a/backend/notification_v2/urls.py b/backend/notification_v2/urls.pyindex 2e356b400..a6ea59107 100644--- a/backend/notification_v2/urls.py+++ b/backend/notification_v2/urls.py@@ -1,7 +1,7 @@from django.urls import pathfrom rest_framework.urlpatterns import format_suffix_patterns-from .views import NotificationViewSet+from .views import NotificationSettingsView, NotificationViewSetnotification_list = NotificationViewSet.as_view({"get": "list", "post": "create"})notification_detail = NotificationViewSet.as_view(@@ -16,6 +16,13 @@ notification_detail = NotificationViewSet.as_view(urlpatterns = format_suffix_patterns([path("", notification_list, name="notification-list"),+ # Org-scoped notification batching settings. Mounted before the+ # <uuid:pk> route so "settings" is not interpreted as a UUID.+ path(+ "settings/",+ NotificationSettingsView.as_view(),+ name="notification-settings",+ ),path("<uuid:pk>/", notification_detail, name="notification-detail"),path("pipeline/<uuid:pipeline_uuid>/",diff --git a/backend/notification_v2/views.py b/backend/notification_v2/views.pyindex 1410256ab..ce23c73f2 100644--- a/backend/notification_v2/views.py+++ b/backend/notification_v2/views.py@@ -1,14 +1,26 @@+import logging+from api_v2.deployment_helper import DeploymentHelperfrom api_v2.exceptions import APINotFound+from configuration.enums import ConfigKey+from configuration.models import Configurationfrom pipeline_v2.exceptions import PipelineNotFoundfrom pipeline_v2.models import Pipelinefrom pipeline_v2.pipeline_processor import PipelineProcessor-from rest_framework import viewsets+from platform_api.permissions import IsOrganizationAdmin+from rest_framework import status, viewsets+from rest_framework.permissions import IsAuthenticated+from rest_framework.request import Request+from rest_framework.response import Response+from rest_framework.views import APIView+from utils.user_context import UserContextfrom notification_v2.constants import NotificationUrlConstantfrom .models import Notification-from .serializers import NotificationSerializer+from .serializers import NotificationSerializer, NotificationSettingsSerializer++logger = logging.getLogger(__name__)class NotificationViewSet(viewsets.ModelViewSet):@@ -39,3 +51,47 @@ class NotificationViewSet(viewsets.ModelViewSet):queryset = queryset.filter(api=api)return queryset+++class NotificationSettingsView(APIView):+ """Org-scoped notification batching settings — currently just the club interval.++ GET returns the org's effective interval (override or env-derived default).+ PATCH writes/updates the override via the generic configuration KV table.++ Read-at-enqueue contract: updates take effect for notifications enqueued+ after the change. Existing PENDING buffer rows keep their original+ flush_after.+ """++ permission_classes = [IsAuthenticated, IsOrganizationAdmin]++ def get(self, request: Request) -> Response:+ organization = UserContext.get_organization()+ value = Configuration.get_value_by_organization(+ ConfigKey.NOTIFICATION_CLUB_INTERVAL, organization+ )+ return Response({"club_interval_seconds": int(value)})++ def patch(self, request: Request) -> Response:+ serializer = NotificationSettingsSerializer(data=request.data, partial=True)+ serializer.is_valid(raise_exception=True)+ organization = UserContext.get_organization()+ new_value = serializer.validated_data.get("club_interval_seconds")+ if new_value is None:+ return Response(+ {"detail": "club_interval_seconds is required."},+ status=status.HTTP_400_BAD_REQUEST,+ )+ # ConfigKey.cast_value enforces type + any future bounds; bubble its+ # ValueError up as a 400 instead of letting it 500.+ try:+ ConfigKey.NOTIFICATION_CLUB_INTERVAL.cast_value(new_value)+ except ValueError as exc:+ return Response({"detail": str(exc)}, status=status.HTTP_400_BAD_REQUEST)+ Configuration.objects.update_or_create(+ organization=organization,+ key=ConfigKey.NOTIFICATION_CLUB_INTERVAL.name,+ defaults={"value": str(new_value), "enabled": True},+ )+ return Response({"club_interval_seconds": int(new_value)})diff --git a/backend/pipeline_v2/dto.py b/backend/pipeline_v2/dto.pyindex 5a87ba082..d3e2e1443 100644--- a/backend/pipeline_v2/dto.py+++ b/backend/pipeline_v2/dto.py@@ -10,6 +10,10 @@ class PipelineStatusPayload:status: str,execution_id: str | None = None,error_message: str | None = None,+ total_files: int | None = None,+ successful_files: int | None = None,+ failed_files: int | None = None,+ is_failure: bool | None = None,):self.type = typeself.pipeline_id = pipeline_id@@ -17,17 +21,39 @@ class PipelineStatusPayload:self.status = statusself.execution_id = execution_idself.error_message = error_message+ self.total_files = total_files+ self.successful_files = successful_files+ self.failed_files = failed_files+ # Authoritative failure verdict computed at dispatch (see+ # is_failure_run + the pipeline last_run_status backstop). Lets the+ # clubbed renderer classify the run without re-deriving it from the+ # `status` string, whose vocabulary differs per dispatch path+ # (PipelineStatus on the pipeline path vs ExecutionStatus elsewhere).+ self.is_failure = is_failuredef to_dict(self) -> dict[str, Any]:- """Convert the payload DTO to a dictionary."""- payload = {+ """Convert the payload DTO to a dictionary.++ File counts are nested in `additional_data` to match the worker-path+ payload shape (NotificationPayload.from_execution_status).+ """+ payload: dict[str, Any] = {"type": self.type,"pipeline_id": str(self.pipeline_id),"pipeline_name": self.pipeline_name,"status": self.status,+ "additional_data": {+ "total_files": self.total_files or 0,+ "successful_files": self.successful_files or 0,+ "failed_files": self.failed_files or 0,+ },}if self.execution_id:payload["execution_id"] = str(self.execution_id)if self.error_message:payload["error_message"] = self.error_message+ # Only emit when explicitly set so worker/legacy payloads (which never+ # carry it) stay byte-identical and the renderer falls back to status.+ if self.is_failure is not None:+ payload["is_failure"] = self.is_failurereturn payloaddiff --git a/backend/pipeline_v2/notification.py b/backend/pipeline_v2/notification.pyindex dbfc0dea5..9e1a4f668 100644--- a/backend/pipeline_v2/notification.py+++ b/backend/pipeline_v2/notification.py@@ -1,7 +1,8 @@import logging-from notification_v2.helper import NotificationHelper+from notification_v2.helper import dispatch_notifications, is_failure_runfrom notification_v2.models import Notification+from workflow_manager.workflow_v2.models.execution import WorkflowExecutionfrom pipeline_v2.dto import PipelineStatusPayloadfrom pipeline_v2.models import Pipeline@@ -23,11 +24,60 @@ class PipelineNotification:self.error_message = error_messageself.execution_id = execution_id- def send(self):- if not self.notifications.count():- logger.info(f"No notifications found for pipeline {self.pipeline}")+ def _load_execution(self) -> WorkflowExecution | None:+ """Load the WorkflowExecution row for this dispatch, if available.++ Falls back to None when no execution_id was supplied (e.g. legacy+ callers); callers must handle the None case.+ """+ if not self.execution_id:+ return None+ try:+ return WorkflowExecution.objects.get(id=self.execution_id)+ except WorkflowExecution.DoesNotExist:+ logger.warning(+ "WorkflowExecution %s not found for pipeline notification",+ self.execution_id,+ )+ return None++ def send(self) -> None:+ execution = self._load_execution()+ # Source of truth for partial-failure detection is the per-run aggregate+ # written by the worker callback. Pipeline.last_run_status is a coarse+ # collapse (ERROR/STOPPED → FAILURE) that hides per-file errors when+ # at least one file succeeded.+ failed_files = (execution.failed_files or 0) if execution else 0+ execution_status = execution.status if execution else None+ # Shared rule (see notification_v2.helper.is_failure_run), plus a+ # pipeline-only backstop: when the WorkflowExecution can't be loaded+ # (legacy caller / missing execution_id) the per-run aggregate is+ # unavailable, so fall back to the pipeline's collapsed last_run_status.+ is_failure = (+ is_failure_run(execution_status, failed_files)+ or self.pipeline.last_run_status == Pipeline.PipelineStatus.FAILURE+ )+ if not is_failure:+ self.notifications = self.notifications.filter(notify_on_failures=False)++ if not self.notifications.exists():+ logger.info(+ "No notifications to dispatch for pipeline %s (status=%s, failed_files=%s)",+ self.pipeline,+ self.pipeline.last_run_status,+ failed_files,+ )return- logger.info(f"Sending pipeline status notification for pipeline {self.pipeline}")+ successful_files = (execution.successful_files or 0) if execution else 0+ total_files = execution.total_files if execution else None+ logger.info(+ "Sending pipeline status notification for pipeline %s "+ "(status=%s, successful=%s, failed=%s)",+ self.pipeline,+ self.pipeline.last_run_status,+ successful_files,+ failed_files,+ )payload_dto = PipelineStatusPayload(type=self.pipeline.pipeline_type,pipeline_id=str(self.pipeline.id),@@ -35,8 +85,16 @@ class PipelineNotification:status=self.pipeline.last_run_status,execution_id=self.execution_id,error_message=self.error_message,+ total_files=total_files,+ successful_files=successful_files,+ failed_files=failed_files,+ # Carry the verdict the routing filter used so the rendered outcome+ # can't disagree with it — last_run_status is PipelineStatus vocab+ # (SUCCESS/FAILURE) the renderer's is_failure_run can't classify.+ is_failure=is_failure,)-- NotificationHelper.send_notification(- notifications=self.notifications, payload=payload_dto.to_dict()+ dispatch_notifications(+ list(self.notifications),+ payload_dto.to_dict(),+ error_context=f"pipeline={self.pipeline.id}",)diff --git a/backend/workflow_manager/internal_serializers.py b/backend/workflow_manager/internal_serializers.pyindex bed98c685..8c156d345 100644--- a/backend/workflow_manager/internal_serializers.py+++ b/backend/workflow_manager/internal_serializers.py@@ -178,9 +178,47 @@ class WorkflowExecutionStatusUpdateSerializer(serializers.Serializer):total_files = serializers.IntegerField(required=False, min_value=0) # Allow 0 but backend will only update if > 0+ successful_files = serializers.IntegerField(required=False, min_value=0)+ failed_files = serializers.IntegerField(required=False, min_value=0)attempts = serializers.IntegerField(required=False, min_value=0)execution_time = serializers.FloatField(required=False, min_value=0)+ def validate(self, attrs):+ """Reject impossible file-count aggregates.++ Per-field min_value=0 catches negatives, but successful + failed >+ total or either component > total slips through and skews the+ outcome-based notification filter downstream.+ """+ total = attrs.get("total_files")+ successful = attrs.get("successful_files")+ failed = attrs.get("failed_files")++ if total is None:+ if successful is not None or failed is not None:+ raise serializers.ValidationError(+ {+ "total_files": "total_files is required when file aggregates are provided."+ }+ )+ else:+ if successful is not None and successful > total:+ raise serializers.ValidationError(+ {"successful_files": "successful_files cannot exceed total_files."}+ )+ if failed is not None and failed > total:+ raise serializers.ValidationError(+ {"failed_files": "failed_files cannot exceed total_files."}+ )+ if (+ successful is not None+ and failed is not None+ and successful + failed > total+ ):+ msg = "successful_files + failed_files cannot exceed total_files."+ raise serializers.ValidationError({"non_field_errors": msg})+ return attrs+class OrganizationContextSerializer(serializers.Serializer):"""Serializer for organization context information."""diff --git a/backend/workflow_manager/internal_views.py b/backend/workflow_manager/internal_views.pyindex c822e5e7b..88a083707 100644--- a/backend/workflow_manager/internal_views.py+++ b/backend/workflow_manager/internal_views.py@@ -478,59 +478,51 @@ class WorkflowExecutionInternalViewSet(viewsets.ReadOnlyModelViewSet):execution = self.get_object()serializer = WorkflowExecutionStatusUpdateSerializer(data=request.data)- if serializer.is_valid():- validated_data = serializer.validated_data-- # FIXED: Use update_execution() method for proper wall-clock time calculation- # This replaces manual field setting which bypassed execution time logic-- # Handle error message truncation before calling update_execution- error_message = None- if validated_data.get("error_message"):- error_msg = validated_data["error_message"]- if len(error_msg) > 256:- error_message = error_msg[:253] + "..."- logger.warning(- f"Error message truncated for execution {id} (original length: {len(error_msg)})"- )- else:- error_message = error_msg+ if not serializer.is_valid():+ return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)- # Handle attempts increment- increment_attempt = (- validated_data.get("attempts") is not None- and validated_data.get("attempts") > execution.attempts- )+ validated_data = serializer.validated_data++ # Use update_execution() for proper wall-clock time calculation rather+ # than manual field setting, which bypassed the execution time logic.+ error_message = self._truncate_error_message(+ validated_data.get("error_message"), id+ )++ increment_attempt = (+ validated_data.get("attempts") is not None+ and validated_data.get("attempts") > execution.attempts+ )- # Use the model's update_execution method for proper wall-clock calculation- from workflow_manager.workflow_v2.enums import ExecutionStatus+ from workflow_manager.workflow_v2.enums import ExecutionStatus- status_enum = ExecutionStatus(validated_data["status"])- logger.info(f"Updating status for execution {id} to {status_enum}")+ status_enum = ExecutionStatus(validated_data["status"])+ logger.info(f"Updating status for execution {id} to {status_enum}")+ # Status and file-count aggregates must commit together. Otherwise a+ # failure between the two writes can leave the row at a terminal status+ # with failed_files=None, which is_failure_run() reads as a success and+ # silently bypasses notify_on_failures subscribers.+ with transaction.atomic():execution.update_execution(status=status_enum,error=error_message,increment_attempt=increment_attempt,)- # Update total_files separately (not handled by update_execution)- if validated_data.get("total_files") is not None:- execution.total_files = validated_data["total_files"]- execution.save()-- logger.info(- f"Updated workflow execution {id} status to {validated_data['status']}"- )+ # File aggregates are not handled by update_execution; persist separately.+ self._update_file_aggregates(execution, validated_data)- return Response(- {- "status": "updated",- "execution_id": str(execution.id),- "new_status": execution.status,- }- )+ logger.info(+ f"Updated workflow execution {id} status to {validated_data['status']}"+ )- return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)+ return Response(+ {+ "status": "updated",+ "execution_id": str(execution.id),+ "new_status": execution.status,+ }+ )except Exception as e:logger.error(f"Failed to update workflow execution status {id}: {str(e)}")@@ -539,6 +531,30 @@ class WorkflowExecutionInternalViewSet(viewsets.ReadOnlyModelViewSet):status=status.HTTP_500_INTERNAL_SERVER_ERROR,)+ @staticmethod+ def _truncate_error_message(error_msg: str | None, execution_id) -> str | None:+ """Truncate an error message to the 256-char column limit (with ellipsis)."""+ if not error_msg:+ return None+ if len(error_msg) > 256:+ logger.warning(+ f"Error message truncated for execution {execution_id} "+ f"(original length: {len(error_msg)})"+ )+ return error_msg[:253] + "..."+ return error_msg++ @staticmethod+ def _update_file_aggregates(execution, validated_data) -> None:+ """Persist total / successful / failed file counts when present."""+ update_fields: list[str] = []+ for field in ("total_files", "successful_files", "failed_files"):+ if validated_data.get(field) is not None:+ setattr(execution, field, validated_data[field])+ update_fields.append(field)+ if update_fields:+ execution.save(update_fields=update_fields)+class FileBatchCreateAPIView(APIView):"""Internal API endpoint for creating file batches for workflow execution."""diff --git a/backend/workflow_manager/workflow_v2/migrations/0020_workflowexecution_file_counts.py b/backend/workflow_manager/workflow_v2/migrations/0020_workflowexecution_file_counts.pynew file mode 100644index 000000000..6dba25f5b--- /dev/null+++ b/backend/workflow_manager/workflow_v2/migrations/0020_workflowexecution_file_counts.py@@ -0,0 +1,36 @@+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("workflow_v2", "0019_remove_filehistory_trigram_index"),+ ]++ operations = [+ migrations.AddField(+ model_name="workflowexecution",+ name="successful_files",+ field=models.PositiveIntegerField(+ blank=True,+ null=True,+ db_comment=(+ "Per-run aggregate of files that completed successfully. "+ "Written by the worker callback at terminal state. Null on "+ "rows created before this column was added."+ ),+ ),+ ),+ migrations.AddField(+ model_name="workflowexecution",+ name="failed_files",+ field=models.PositiveIntegerField(+ blank=True,+ null=True,+ db_comment=(+ "Per-run aggregate of files that errored. Written by the "+ "worker callback at terminal state. Null on rows created "+ "before this column was added."+ ),+ ),+ ),+ ]diff --git a/backend/workflow_manager/workflow_v2/models/execution.py b/backend/workflow_manager/workflow_v2/models/execution.pyindex 262b191a2..e59e8faeb 100644--- a/backend/workflow_manager/workflow_v2/models/execution.py+++ b/backend/workflow_manager/workflow_v2/models/execution.py@@ -18,7 +18,6 @@ from utils.user_context import UserContextfrom workflow_manager.execution.dto import ExecutionCachefrom workflow_manager.execution.execution_cache_utils import ExecutionCacheUtils-from workflow_manager.file_execution.models import WorkflowFileExecutionfrom workflow_manager.workflow_v2.enums import ExecutionStatusfrom workflow_manager.workflow_v2.models import Workflow@@ -180,6 +179,24 @@ class WorkflowExecution(BaseModel):total_files = models.PositiveIntegerField(default=0, verbose_name="Total files", db_comment="Number of files to process")+ successful_files = models.PositiveIntegerField(+ null=True,+ blank=True,+ db_comment=(+ "Per-run aggregate of files that completed successfully. Written by "+ "the worker callback at terminal state. Null on rows created before "+ "this column was added."+ ),+ )+ failed_files = models.PositiveIntegerField(+ null=True,+ blank=True,+ db_comment=(+ "Per-run aggregate of files that errored. Written by the worker "+ "callback at terminal state. Null on rows created before this "+ "column was added."+ ),+ )error_message = models.CharField(max_length=EXECUTION_ERROR_LENGTH,blank=True,@@ -426,16 +443,8 @@ class WorkflowExecution(BaseModel):result = []for e in executions:- # TODO: Optimize by storing successful/failed counts directly in- # WorkflowExecution model. Current approach causes N+1 queries- # (2 queries per execution). Denormalized counts would eliminate- # these queries entirely.- successful = WorkflowFileExecution.objects.filter(- workflow_execution_id=e.id, status="COMPLETED"- ).count()- failed = WorkflowFileExecution.objects.filter(- workflow_execution_id=e.id, status="ERROR"- ).count()+ successful = e.successful_files or 0+ failed = e.failed_files or 0# Compute display_status: PARTIAL_SUCCESS if completed with mixed resultsdisplay_status = e.statusdiff --git a/frontend/src/components/pipelines-or-deployments/notification-modal/CreateNotification.jsx b/frontend/src/components/pipelines-or-deployments/notification-modal/CreateNotification.jsxindex 9c207bd1a..21d274687 100644--- a/frontend/src/components/pipelines-or-deployments/notification-modal/CreateNotification.jsx+++ b/frontend/src/components/pipelines-or-deployments/notification-modal/CreateNotification.jsx@@ -1,4 +1,4 @@-import { Button, Form, Input, Select, Space } from "antd";+import { Button, Checkbox, Form, Input, Select, Space } from "antd";import PropTypes from "prop-types";import { useEffect, useState } from "react";import { getBackendErrorDetail } from "../../../helpers/GetStaticData";@@ -12,6 +12,7 @@ const DEFAULT_FORM_DETAILS = {authorization_key: "",is_active: false,max_retries: 0,+ notify_on_failures: false,pipeline: "",api: "",url: "",@@ -83,7 +84,8 @@ function CreateNotification({}, [formDetails]);const handleInputChange = (changedValues, allValues) => {- setFormDetails({ ...formDetails, ...allValues });+ const nextValues = { ...formDetails, ...allValues };+ setFormDetails(nextValues);const changedFieldName = Object.keys(changedValues)[0];form.setFields([{@@ -220,6 +222,13 @@ function CreateNotification({</Form.Item>),)}+ <Form.Item+ name="notify_on_failures"+ valuePropName="checked"+ extra="Notification interval can be configured in Platform settings."+ >+ <Checkbox>Notify on failures only</Checkbox>+ </Form.Item><Form.Item className="display-flex-right"><Space><Button onClick={() => setIsForm(false)}>Cancel</Button>diff --git a/frontend/src/components/pipelines-or-deployments/notification-modal/DisplayNotifications.jsx b/frontend/src/components/pipelines-or-deployments/notification-modal/DisplayNotifications.jsxindex 9754dd20a..d504f5563 100644--- a/frontend/src/components/pipelines-or-deployments/notification-modal/DisplayNotifications.jsx+++ b/frontend/src/components/pipelines-or-deployments/notification-modal/DisplayNotifications.jsx@@ -42,28 +42,24 @@ function DisplayNotifications({key: "pipeline_id",align: "center",render: (_, record) => (- <>- <Space className="actions">- <Tooltip title="edit" className="cursorPointer">- <Button- type="text"- size="small"- icon={<EditOutlined />}- onClick={() => handleEdit(record)}- />- </Tooltip>- </Space>- <Space className="actions">- <Tooltip title="delete" className="cursorPointer">- <ConfirmModal- handleConfirm={() => handleDelete(record?.id, record?.name)}- content="Are you sure you want to delete?"- >- <Button type="text" size="small" icon={<DeleteOutlined />} />- </ConfirmModal>- </Tooltip>- </Space>- </>+ <Space>+ <Tooltip title="edit" className="cursorPointer">+ <Button+ type="text"+ size="small"+ icon={<EditOutlined />}+ onClick={() => handleEdit(record)}+ />+ </Tooltip>+ <Tooltip title="delete" className="cursorPointer">+ <ConfirmModal+ handleConfirm={() => handleDelete(record?.id, record?.name)}+ content="Are you sure you want to delete?"+ >+ <Button type="text" size="small" icon={<DeleteOutlined />} />+ </ConfirmModal>+ </Tooltip>+ </Space>),},];@@ -91,7 +87,7 @@ function DisplayNotifications({indicator: <SpinnerLoader />,spinning: isLoading,}}- pagination={{ pageSize: 5 }}+ pagination={false}/></SpaceWrapper>);diff --git a/frontend/src/components/settings/platform/PlatformSettings.css b/frontend/src/components/settings/platform/PlatformSettings.cssindex 4ad6f4bf8..da0da7931 100644--- a/frontend/src/components/settings/platform/PlatformSettings.css+++ b/frontend/src/components/settings/platform/PlatformSettings.css@@ -2,7 +2,7 @@.plt-set-layout {height: calc(100vh - 60px);- background-color: #ffffff;+ background-color: var(--page-bg-3);}.plt-set-layout-2 {@@ -10,9 +10,10 @@}.plt-set-head {- background-color: #f5f7f9;+ background-color: var(--white);padding: 14px;height: 60px;+ border-bottom: 1px solid var(--border-color-1);}.plt-set-head-typo {@@ -20,14 +21,56 @@font-weight: 600;}+.plt-set-section {+ margin-bottom: 16px;+}++.plt-set-section > .ant-typography {+ margin-top: 0;+}++.plt-set-section-subtitle {+ display: block;+ margin-bottom: 8px;+ font-size: 12px;+}++.plt-set-inner-card {+ background-color: #f5f7f9;+ border: 1px solid #e5e7eb;+ border-radius: 8px;+ padding: 16px;+}+.plt-set-key-head {+ display: flex;+ align-items: center;+ gap: 8px;margin-bottom: 8px;}-.plt-set-key-head-col-1 {- padding-right: 16px;+.plt-set-key-pill-clickable {+ cursor: pointer;}.plt-set-key-display {width: 300px;}++.plt-set-notif-field-label {+ display: block;+ margin-bottom: 8px;+ font-size: 13px;+}++.plt-set-notif-field-row {+ display: flex;+ align-items: center;+ gap: 8px;+}++.plt-set-notif-helper {+ display: block;+ margin-top: 6px;+ font-size: 12px;+}diff --git a/frontend/src/components/settings/platform/PlatformSettings.jsx b/frontend/src/components/settings/platform/PlatformSettings.jsxindex f255da6a7..e62b48a91 100644--- a/frontend/src/components/settings/platform/PlatformSettings.jsx+++ b/frontend/src/components/settings/platform/PlatformSettings.jsx@@ -3,7 +3,17 @@ import {CopyOutlined,DeleteOutlined,} from "@ant-design/icons";-import { Button, Col, Divider, Input, Radio, Row, Typography } from "antd";+import {+ Button,+ Col,+ Divider,+ Input,+ InputNumber,+ Row,+ Tag,+ Typography,+} from "antd";+import PropTypes from "prop-types";import { useEffect, useState } from "react";import { useNavigate } from "react-router-dom";@@ -33,11 +43,48 @@ const defaultKeys = [},];+// Keyboard-accessible "Inactive" pill. Split out of the key-row render so the+// activation control's conditional handlers don't inflate the row's complexity.+function InactivePlatformKeyTag({ keyName, canActivate, onActivate }) {+ if (!canActivate) {+ return <Tag tabIndex={-1}>Inactive</Tag>;+ }++ const handleKeyDown = (e) => {+ if (e.key === "Enter" || e.key === " ") {+ e.preventDefault();+ onActivate();+ }+ };++ return (+ <Tag+ className="plt-set-key-pill-clickable"+ role="button"+ tabIndex={0}+ aria-label={`Activate ${keyName}`}+ onClick={onActivate}+ onKeyDown={handleKeyDown}+ >+ Inactive+ </Tag>+ );+}++InactivePlatformKeyTag.propTypes = {+ keyName: PropTypes.string,+ canActivate: PropTypes.bool,+ onActivate: PropTypes.func.isRequired,+};+function PlatformSettings() {const [activeKey, setActiveKey] = useState(null);const [keys, setKeys] = useState(defaultKeys);const [isLoadingIndex, setLoadingIndex] = useState(null);const [isDeletingIndex, setDeletingIndex] = useState(null);+ // UI shows minutes; wire format (and ConfigSpec.value) is seconds.+ const [batchIntervalMinutes, setBatchIntervalMinutes] = useState(null);+ const [isSavingInterval, setIsSavingInterval] = useState(false);const { sessionDetails } = useSessionStore();const { setAlertDetails } = useAlertStore();const axiosPrivate = useAxiosPrivate();@@ -45,6 +92,71 @@ function PlatformSettings() {const handleException = useExceptionHandler();const { setPostHogCustomEvent } = usePostHogEvents();+ useEffect(() => {+ // Wait for session hydration — without this guard the first render+ // fires GET against /api/v1/unstract/undefined/... and silently 404s.+ if (!sessionDetails?.orgId) {+ return;+ }+ // Load org-scoped batch interval. Falls back to null on failure (logged+ // in the catch below) so the rest of the page still renders.+ axiosPrivate({+ method: "GET",+ url: `/api/v1/unstract/${sessionDetails?.orgId}/notifications/settings/`,+ })+ .then((res) => {+ const seconds = res?.data?.club_interval_seconds;+ if (typeof seconds === "number" && seconds > 0) {+ setBatchIntervalMinutes(Math.round(seconds / 60));+ }+ })+ .catch((err) => {+ // Non-fatal for page render, but log it: a failed load otherwise+ // looks identical to "no override set" (the field stays blank), so+ // the admin could edit from a wrong baseline and overwrite the real+ // value on save.+ console.warn("Failed to load notification batch interval", err);+ });+ }, [sessionDetails?.orgId]);++ const handleSaveInterval = () => {+ if (+ !batchIntervalMinutes ||+ batchIntervalMinutes < 1 ||+ batchIntervalMinutes > 120+ ) {+ setAlertDetails({+ type: "error",+ content: "Notification interval must be between 1 and 120 minutes.",+ });+ return;+ }+ setIsSavingInterval(true);+ axiosPrivate({+ method: "PATCH",+ url: `/api/v1/unstract/${sessionDetails?.orgId}/notifications/settings/`,+ headers: {+ "X-CSRFToken": sessionDetails?.csrfToken,+ "Content-Type": "application/json",+ },+ data: { club_interval_seconds: batchIntervalMinutes * 60 },+ })+ .then(() => {+ setAlertDetails({+ type: "success",+ content: "Notification batch interval updated.",+ });+ })+ .catch((err) => {+ setAlertDetails(+ handleException(err, "Failed to update batch interval"),+ );+ })+ .finally(() => {+ setIsSavingInterval(false);+ });+ };+useEffect(() => {const requestOptions = {method: "GET",@@ -252,84 +364,124 @@ function PlatformSettings() {<div className="plt-set-layout"><IslandLayout><div className="plt-set-layout-2">- <div>- {keys.map((keyDetails, keyIndex) => {- return (- <div key={keyDetails?.keyName}>- <div>- <div className="plt-set-key-head">- <Row>- <Col>- <div className="plt-set-key-head-col-1">- <Typography.Text>- {keyDetails?.keyName}- </Typography.Text>- </div>- </Col>- <Col>- <div className="plt-set-key-head-col-2">- <Radio- checked={- keyDetails?.id && activeKey === keyIndex- }- disabled={keyDetails?.id === null}- onClick={() => handleToggle(keyIndex)}- >- Active Key- </Radio>- </div>- </Col>- </Row>- </div>+ <div className="plt-set-section">+ <Typography.Title level={5}>Internal API Keys</Typography.Title>+ <Typography.Text+ type="secondary"+ className="plt-set-section-subtitle"+ >+ Authenticate platform-to-platform requests. Keep these values+ secret.+ </Typography.Text>+ <div className="plt-set-inner-card">+ {keys.map((keyDetails, keyIndex) => {+ const isActive =+ Boolean(keyDetails?.id) && activeKey === keyIndex;+ const canActivate = keyDetails?.id !== null;+ return (+ <div key={keyDetails?.keyName}><div>- <Row gutter={10}>- <Col>- <div className="plt-set-key-display">- <Input- size="small"- value={keys[keyIndex].key}- suffix={- <CopyOutlined- onClick={() =>- copyText(keys[keyIndex].key)- }- />- }- />- </div>- </Col>- <Col>- <Button- size="small"- loading={isLoadingIndex === keyIndex}- onClick={() => handleGenerate(keyIndex)}- >- {keyDetails?.id?.length > 0- ? "Refresh"- : "Generate"}- </Button>- </Col>- <Col>- <ConfirmModal- handleConfirm={() => handleDelete(keyIndex)}- content="Want to delete this platform key? This action cannot be undone."- okText="Delete"- >+ <div className="plt-set-key-head">+ <Typography.Text>+ {keyDetails?.keyName}+ </Typography.Text>+ {isActive ? (+ <Tag color="success">Active</Tag>+ ) : (+ <InactivePlatformKeyTag+ keyName={keyDetails?.keyName}+ canActivate={canActivate}+ onActivate={() => handleToggle(keyIndex)}+ />+ )}+ </div>+ <div>+ <Row gutter={10}>+ <Col>+ <div className="plt-set-key-display">+ <Input+ size="small"+ value={keys[keyIndex].key}+ suffix={+ <CopyOutlined+ onClick={() =>+ copyText(keys[keyIndex].key)+ }+ />+ }+ />+ </div>+ </Col>+ <Col><Buttonsize="small"- icon={<DeleteOutlined />}- disabled={keyDetails?.id === null}- loading={isDeletingIndex === keyIndex}- />- </ConfirmModal>- </Col>- </Row>+ loading={isLoadingIndex === keyIndex}+ onClick={() => handleGenerate(keyIndex)}+ >+ {keyDetails?.id?.length > 0+ ? "Refresh"+ : "Generate"}+ </Button>+ </Col>+ <Col>+ <ConfirmModal+ handleConfirm={() => handleDelete(keyIndex)}+ content="Want to delete this platform key? This action cannot be undone."+ okText="Delete"+ >+ <Button+ size="small"+ icon={<DeleteOutlined />}+ disabled={keyDetails?.id === null}+ loading={isDeletingIndex === keyIndex}+ />+ </ConfirmModal>+ </Col>+ </Row>+ </div></div>+ {keyIndex < keys?.length - 1 && <Divider />}</div>- {keyIndex < keys?.length - 1 && <Divider />}- </div>- );- })}+ );+ })}+ </div>+ </div>+ <div className="plt-set-section">+ <Typography.Title level={5}>Notifications</Typography.Title>+ <Typography.Text+ type="secondary"+ className="plt-set-section-subtitle"+ >+ Control how often the platform notifies you about activity.+ </Typography.Text>+ <div className="plt-set-inner-card">+ <Typography.Text className="plt-set-notif-field-label">+ Notification interval+ </Typography.Text>+ <div className="plt-set-notif-field-row">+ <InputNumber+ min={1}+ max={120}+ step={1}+ precision={0}+ value={batchIntervalMinutes}+ onChange={(v) => setBatchIntervalMinutes(v)}+ />+ <Button+ type="primary"+ onClick={handleSaveInterval}+ loading={isSavingInterval}+ >+ Save+ </Button>+ </div>+ <Typography.Text+ type="secondary"+ className="plt-set-notif-helper"+ >+ Allowed: 1 to 120 minutes. Default: 5 minutes.+ </Typography.Text>+ </div></div></div></IslandLayout>diff --git a/unstract/core/src/unstract/core/data_models.py b/unstract/core/src/unstract/core/data_models.pyindex 7e8e984a0..b56d0487f 100644--- a/unstract/core/src/unstract/core/data_models.py+++ b/unstract/core/src/unstract/core/data_models.py@@ -388,6 +388,40 @@ def _is_completed(cls, status: str) -> bool:ExecutionStatus.is_completed = classmethod(_is_completed)+# Terminal statuses treated as a failed run for notification routing.+# STOPPED counts alongside ERROR (a stopped run is not a success).+def _failure_statuses(cls) -> frozenset["ExecutionStatus"]:+ """Return the set of statuses that represent a failed run."""+ return frozenset({cls.ERROR, cls.STOPPED})+++def _is_failure(cls, status: str) -> bool:+ """Check if the given status is a terminal failure state."""+ try:+ return cls(status) in cls.failure_statuses()+ except ValueError:+ return False+++ExecutionStatus.failure_statuses = classmethod(_failure_statuses)+ExecutionStatus.is_failure = classmethod(_is_failure)+++def is_failure_run(execution_status: str | None, failed_files: int | None) -> bool:+ """Canonical "did this run fail?" rule, shared across every dispatch path.++ A run counts as a failure if it reached a terminal failure state+ (ERROR/STOPPED) OR any file errored. Partial-success runs land as+ status=COMPLETED with failed_files>0, so the status check alone misses them.++ Lives here, beside ``ExecutionStatus``, as the single source of truth: the+ backend ``notification_v2.helper.is_failure_run`` re-exports it and the+ clubbed renderer derives its success/failure counts from it, so the routing+ filter and the rendered summary can never drift apart.+ """+ return ExecutionStatus.is_failure(execution_status) or (failed_files or 0) > 0++# Add the get_skip_processing_statuses method as a class methoddef _get_skip_processing_statuses(cls) -> list["ExecutionStatus"]:"""Get list of statuses that should skip file processing.@@ -512,6 +546,8 @@ class NotificationPayload:# Metadatatimestamp: datetime = field(default_factory=lambda: datetime.now(UTC))+ # Per-run file aggregates (total/successful/failed) are nested here+ # so receivers see them grouped rather than as top-level keys.additional_data: dict[str, Any] = field(default_factory=dict)# Internal tracking (not sent to external webhooks)@@ -565,6 +601,9 @@ class NotificationPayload:error_message: str | None = None,organization_id: str | None = None,additional_data: dict[str, Any] | None = None,+ total_files: int = 0,+ successful_files: int = 0,+ failed_files: int = 0,) -> "NotificationPayload":"""Create notification payload from execution status.@@ -599,6 +638,18 @@ class NotificationPayload:f"Cannot create notification for non-final status: {execution_status}")+ # File counts are bundled inside additional_data so receivers see them+ # grouped; the clubbed renderer surfaces them as an inline "N/M files"+ # field on each Slack event line.+ # Caller-supplied additional_data takes precedence on key conflict.+ merged_additional = {+ "total_files": total_files,+ "successful_files": successful_files,+ "failed_files": failed_files,+ }+ if additional_data:+ merged_additional.update(additional_data)+return cls(type=workflow_type,pipeline_id=pipeline_id,@@ -607,7 +658,7 @@ class NotificationPayload:execution_id=execution_id,error_message=error_message,organization_id=organization_id,- additional_data=additional_data or {},+ additional_data=merged_additional,_source=source,)diff --git a/unstract/core/src/unstract/core/notification_clubbed_renderer.py b/unstract/core/src/unstract/core/notification_clubbed_renderer.pynew file mode 100644index 000000000..184a81a83--- /dev/null+++ b/unstract/core/src/unstract/core/notification_clubbed_renderer.py@@ -0,0 +1,244 @@+"""Shared clubbed-notification envelope + Slack renderer.++Imported by both `backend/notification_v2/clubbed_renderer.py` and the+worker `notification/providers/*_webhook.py` so the receiver-visible+payload (envelope JSON for API, mrkdwn string for Slack) is byte-identical+regardless of which side rendered it.++Envelope shape:++ {+ "summary": {"total": N, "succeeded": S, "failed": F},+ "events": [+ {+ "type": "ETL" | "TASK" | "API",+ "pipeline_name": "...",+ "status": "ERROR" | "SUCCESS" | ...,+ "is_failure": bool, # optional; authoritative verdict the+ # renderer prefers over status+counts+ "execution_id": "...",+ "timestamp": "2026 May 5 5:03:34 PM",+ "additional_data": {+ "total_files": int,+ "successful_files": int,+ "failed_files": int,+ },+ "error_message": "...", # only on failure+ },+ ...+ ]+ }++`pipeline_id` is intentionally absent — neither channel surfaces it.+"""++from __future__ import annotations++import datetime+from typing import Any++from unstract.core.data_models import is_failure_run++# Hard cap on events per dispatch; the rest roll into the next flush tick.+MAX_BATCH_SIZE = 500+# Slack inlines this many events before collapsing the rest under an+# "_… and K more_" footer. Slack tolerates much larger payloads, but+# readability tanks past ~25 lines.+SLACK_MAX_DISPLAY_EVENTS = 25++# Legacy single-run webhook keys (pre-clubbing flat shape). Spread onto a+# single-event envelope for backward compatibility — see build_envelope.+# Covers both pre-clubbing wire shapes: the backend dispatch DTO+# (pipeline_v2.dto.PipelineStatusPayload.to_dict) and the worker callback path+# (core.data_models.NotificationPayload.to_webhook_payload). Both always emit+# ``additional_data``; only the worker path additionally emits a top-level+# ``timestamp``. The spread covers the union — keys absent on a given row are+# skipped.+_LEGACY_FLAT_KEYS = (+ "type",+ "pipeline_id",+ "pipeline_name",+ "status",+ "execution_id",+ "error_message",+ "timestamp",+ "additional_data",+)++# Middle dot (U+00B7) padded by single spaces — the per-event field separator.+_SEPARATOR = " · "+_MISSING = "—" # em-dash placeholder for missing fields+_DIVIDER = "———" # triple em-dash divider between header and events++# Slack emoji shortcodes — render the same as the literal unicode glyphs and+# stay readable in source.+_EMOJI_SUCCESS = ":white_check_mark:"+_EMOJI_FAILURE = ":x:"+++def _is_effective_failure(event: dict[str, Any]) -> bool:+ """Did this event fail? Single-sourced with the dispatch filter.++ Prefers the authoritative ``is_failure`` verdict the dispatch site computed+ and carried on the payload, so classification does not depend on the+ ``status`` string — whose vocabulary differs per dispatch path+ (``PipelineStatus`` on the backend pipeline path vs ``ExecutionStatus``+ elsewhere) and which core ``is_failure_run`` only understands as+ ``ExecutionStatus``. Falls back to ``is_failure_run(status, failed_files)``+ when the flag is absent (worker / legacy flat payloads), so the rendered+ outcome can never disagree with the reason the alert fired.+ """+ explicit = event.get("is_failure")+ if explicit is not None:+ return bool(explicit)+ counts = event.get("additional_data") or {}+ return is_failure_run(event.get("status"), counts.get("failed_files"))+++def _humanize_timestamp(iso: str | None) -> str:+ """Render an ISO timestamp as `2026 May 11 11:38:31 AM`.++ Falls back to the missing placeholder on falsy / unparseable input so a+ partial row still renders without raising. The day is interpolated from+ ``dt.day`` rather than a ``%-d`` directive: ``%-d`` is a glibc extension+ that raises ``ValueError`` on macOS/Windows, and this call sits in the+ flush render path where an unhandled raise drops the whole batch.+ """+ if not iso:+ return _MISSING+ try:+ dt = datetime.datetime.fromisoformat(iso)+ except (TypeError, ValueError):+ return _MISSING+ return f"{dt.strftime('%Y %b')} {dt.day} {dt.strftime('%I:%M:%S %p')}"+++def _format_file_count(event: dict[str, Any]) -> str:+ """Render the file-count summary; empty string when no totals available.++ A COMPLETED run with file failures short-circuits to the failure shape so+ the rendered line matches why a failures-only notification fired.+ """+ counts = event.get("additional_data") or {}+ total = counts.get("total_files")+ if total is None:+ return ""+ if _is_effective_failure(event):+ failed = counts.get("failed_files", 0)+ return f"{_EMOJI_FAILURE} {failed}/{total} files"+ successful = counts.get("successful_files", 0)+ return f"{_EMOJI_SUCCESS} {successful}/{total} files"+++def _format_event_line(event: dict[str, Any]) -> str:+ """Format one event as a single Slack mrkdwn line.++ Fields are middle-dot separated; the file-count column is omitted when+ `additional_data` is empty so the line collapses to 5 fields, not 6. A+ trailing italic ``error_message`` field is appended when present so the+ failures-only audience sees *why* the run failed — the pre-clubbing Slack+ body surfaced it and the clubbed renderer must not regress that.+ """+ parts = [+ event.get("timestamp") or _MISSING,+ f"*{event.get('execution_id') or _MISSING}*",+ event.get("type") or _MISSING,+ event.get("pipeline_name") or _MISSING,+ event.get("status") or _MISSING,+ ]+ file_count = _format_file_count(event)+ if file_count:+ parts.append(file_count)+ error_message = event.get("error_message")+ if error_message:+ # Collapse whitespace so a multi-line traceback stays on one line; the+ # raw-API channel still carries the full untruncated text.+ parts.append(f"_{' '.join(str(error_message).split())}_")+ return _SEPARATOR.join(parts)+++def _event_from_payload(payload: dict[str, Any]) -> dict[str, Any]:+ """Project a buffered payload into the canonical per-event dict.++ Unified shape across Slack/API and every dispatch path. `pipeline_id`+ is intentionally dropped — neither channel surfaces it. Timestamps are+ humanized once at projection so Slack and API consumers see the same+ string (implicit UTC, no timezone suffix).+ """+ event: dict[str, Any] = {+ "type": payload.get("type") or "",+ "pipeline_name": payload.get("pipeline_name") or "",+ "status": payload.get("status") or "",+ "execution_id": payload.get("execution_id") or "",+ "timestamp": _humanize_timestamp(payload.get("timestamp")),+ "additional_data": payload.get("additional_data") or {},+ }+ error_message = payload.get("error_message")+ if error_message:+ event["error_message"] = error_message+ # Authoritative failure verdict from the dispatch site; carried only when+ # set so worker / legacy event dicts (which fall back to status+counts)+ # stay byte-identical.+ is_failure = payload.get("is_failure")+ if is_failure is not None:+ event["is_failure"] = is_failure+ return event+++def build_envelope(payloads: list[dict[str, Any]]) -> dict[str, Any]:+ """Build the canonical envelope used by every dispatch path.++ Summary carries `{total, succeeded, failed}`; `events` is the per-run list.++ Backward compatibility: when the batch holds exactly one event, the legacy+ flat top-level fields (the pre-clubbing single-run shape) are also spread+ onto the envelope alongside `summary`/`events`. This reproduces both legacy+ wire shapes — the backend DTO (`type, pipeline_id, pipeline_name, status,+ execution_id?, error_message?`) and the worker callback body, which also+ carried top-level `timestamp` and `additional_data`. Receivers written+ against either old body keep working; new receivers read `events`.+ Multi-event batches are envelope-only (there was never a flat shape for+ them). Removable once all receivers have migrated to `events`.+ """+ capped = payloads[:MAX_BATCH_SIZE]+ failed = sum(1 for p in capped if _is_effective_failure(p))+ envelope: dict[str, Any] = {+ "summary": {+ "total": len(capped),+ "succeeded": len(capped) - failed,+ "failed": failed,+ },+ "events": [_event_from_payload(p) for p in capped],+ }+ if len(capped) == 1:+ single = capped[0]+ for key in _LEGACY_FLAT_KEYS:+ if single.get(key) is not None:+ envelope[key] = single[key]+ return envelope+++def render_slack_text(envelope: dict[str, Any]) -> str:+ """Render the envelope as Slack mrkdwn body text.++ Header + divider are emitted for every dispatch — single-event and+ multi-event batches share the same shape. Visible events are capped at+ ``SLACK_MAX_DISPLAY_EVENTS`` with an `_… and K more_` overflow footer.+ """+ summary = envelope["summary"]+ events: list[dict[str, Any]] = envelope["events"]+ total = summary["total"]+ noun = "execution" if total == 1 else "executions"+ header = (+ f"*{total} {noun}* "+ f"({_EMOJI_SUCCESS} {summary['succeeded']} succeeded "+ f"{_EMOJI_FAILURE} {summary['failed']} failed)"+ )+ visible = events[:SLACK_MAX_DISPLAY_EVENTS]+ sections: list[str] = [header, _DIVIDER]+ sections.extend(_format_event_line(e) for e in visible)+ overflow = len(events) - len(visible)+ if overflow > 0:+ sections.append(_DIVIDER)+ sections.append(f"_… and {overflow} more executions_")+ return "\n".join(sections)diff --git a/unstract/core/tests/test_data_models_is_failure_run.py b/unstract/core/tests/test_data_models_is_failure_run.pynew file mode 100644index 000000000..a708c2e1d--- /dev/null+++ b/unstract/core/tests/test_data_models_is_failure_run.py@@ -0,0 +1,46 @@+"""Unit tests for ``is_failure_run`` — the single notification-routing predicate.++``is_failure_run`` is the one rule that decides whether a failure-only+notification fires and how the clubbed renderer tallies succeeded/failed, so+its truth table is pinned here (pure function — no DB / Django needed).+"""++import unittest++from unstract.core.data_models import ExecutionStatus, is_failure_run+++class IsFailureRunTests(unittest.TestCase):+ def test_terminal_failure_statuses_are_failures(self):+ self.assertTrue(is_failure_run(ExecutionStatus.ERROR.value, 0))+ self.assertTrue(is_failure_run(ExecutionStatus.STOPPED.value, 0))++ def test_completed_with_no_failed_files_is_success(self):+ self.assertFalse(is_failure_run(ExecutionStatus.COMPLETED.value, 0))++ def test_completed_with_failed_files_is_partial_failure(self):+ # Partial-success runs land COMPLETED with failed_files > 0 — the status+ # check alone would miss them.+ self.assertTrue(is_failure_run(ExecutionStatus.COMPLETED.value, 2))++ def test_failed_files_none_defaults_to_zero(self):+ self.assertFalse(is_failure_run(ExecutionStatus.COMPLETED.value, None))++ def test_failure_status_overrides_zero_failed_files(self):+ self.assertTrue(is_failure_run(ExecutionStatus.ERROR.value, None))++ def test_both_predicates_true(self):+ # STOPPED status AND failed files — both legs true (or short-circuits).+ self.assertTrue(is_failure_run(ExecutionStatus.STOPPED.value, 3))++ def test_unknown_or_missing_status_is_not_a_failure(self):+ self.assertFalse(is_failure_run("NOT_A_STATUS", 0))+ self.assertFalse(is_failure_run(None, 0))++ def test_unknown_status_with_failed_files_is_still_a_failure(self):+ # Even if the status string is unrecognised, a failed file fails the run.+ self.assertTrue(is_failure_run("NOT_A_STATUS", 1))+++if __name__ == "__main__":+ unittest.main()diff --git a/unstract/core/tests/test_notification_clubbed_renderer.py b/unstract/core/tests/test_notification_clubbed_renderer.pynew file mode 100644index 000000000..2603cccb3--- /dev/null+++ b/unstract/core/tests/test_notification_clubbed_renderer.py@@ -0,0 +1,234 @@+"""Unit tests for the shared clubbed-notification renderer.++``build_envelope`` / ``render_slack_text`` produce the receiver-visible payload+for both the backend and the worker, so the envelope shape, the single-event+legacy-compat spread, the batch cap, and the Slack overflow footer are pinned+here (pure functions — no DB / Django needed).+"""++import unittest++from unstract.core.notification_clubbed_renderer import (+ _MISSING,+ MAX_BATCH_SIZE,+ SLACK_MAX_DISPLAY_EVENTS,+ build_envelope,+ render_slack_text,+)+++def _payload(status="COMPLETED", failed_files=0, total_files=3, **overrides):+ """A buffered per-event payload dict (the shape build_envelope consumes)."""+ payload = {+ "type": "API",+ "pipeline_id": "pipe-1",+ "pipeline_name": "demo",+ "status": status,+ "execution_id": "exec-1",+ "error_message": None,+ "timestamp": "2026-05-11T11:38:31",+ "additional_data": {+ "total_files": total_files,+ "successful_files": total_files - failed_files,+ "failed_files": failed_files,+ },+ }+ payload.update(overrides)+ return payload+++class BuildEnvelopeTests(unittest.TestCase):+ def test_summary_counts_use_failure_predicate(self):+ env = build_envelope(+ [+ _payload(status="ERROR", failed_files=0, total_files=0), # status fail+ _payload(status="COMPLETED", failed_files=2, total_files=5), # partial+ _payload(status="COMPLETED", failed_files=0, total_files=5), # success+ ]+ )+ self.assertEqual(env["summary"], {"total": 3, "succeeded": 1, "failed": 2})++ def test_single_event_spreads_legacy_flat_keys(self):+ env = build_envelope(+ [+ _payload(+ status="ERROR",+ failed_files=1,+ total_files=2,+ error_message="boom",+ )+ ]+ )+ # Canonical envelope still present alongside the legacy flat keys.+ self.assertIn("summary", env)+ self.assertIn("events", env)+ self.assertEqual(env["type"], "API")+ self.assertEqual(env["pipeline_id"], "pipe-1")+ self.assertEqual(env["pipeline_name"], "demo")+ self.assertEqual(env["status"], "ERROR")+ self.assertEqual(env["execution_id"], "exec-1")+ self.assertEqual(env["error_message"], "boom")+ # The two worker-callback-only legacy keys (raw values, not humanized).+ self.assertEqual(env["timestamp"], "2026-05-11T11:38:31")+ self.assertEqual(+ env["additional_data"],+ {"total_files": 2, "successful_files": 1, "failed_files": 1},+ )++ def test_multi_event_is_envelope_only(self):+ env = build_envelope([_payload(), _payload(execution_id="exec-2")])+ self.assertEqual(set(env), {"summary", "events"})++ def test_batch_is_capped_at_max_batch_size(self):+ env = build_envelope(+ [_payload(execution_id=f"e{i}") for i in range(MAX_BATCH_SIZE + 5)]+ )+ self.assertEqual(env["summary"]["total"], MAX_BATCH_SIZE)+ self.assertEqual(len(env["events"]), MAX_BATCH_SIZE)++ def test_event_timestamp_is_humanized(self):+ # _humanize_timestamp interpolates dt.day rather than the %-d directive+ # (which raises on macOS/Windows) — pin the receiver-visible string.+ env = build_envelope([_payload()])+ self.assertEqual(env["events"][0]["timestamp"], "2026 May 11 11:38:31 AM")++ def test_unparseable_timestamp_falls_back_without_raising(self):+ env = build_envelope([_payload(timestamp="not-a-timestamp")])+ self.assertEqual(env["events"][0]["timestamp"], _MISSING)++ def test_error_message_absent_from_success_event(self):+ # _event_from_payload sets error_message only when truthy.+ env = build_envelope([_payload(status="COMPLETED", failed_files=0)])+ self.assertNotIn("error_message", env["events"][0])++ def test_empty_batch_is_envelope_only(self):+ env = build_envelope([])+ self.assertEqual(env["summary"], {"total": 0, "succeeded": 0, "failed": 0})+ self.assertEqual(env["events"], [])+ self.assertEqual(set(env), {"summary", "events"})++ def test_explicit_is_failure_overrides_unclassifiable_status(self):+ # The regression: the backend pipeline path sends PipelineStatus vocab+ # ("FAILURE") that is_failure_run can't classify, with failed_files=0+ # (deploy/setup error before any file ran). The explicit verdict the+ # dispatch site carries must still count it as a failure.+ env = build_envelope(+ [_payload(status="FAILURE", failed_files=0, total_files=0, is_failure=True)]+ )+ self.assertEqual(env["summary"], {"total": 1, "succeeded": 0, "failed": 1})+ self.assertIs(env["events"][0]["is_failure"], True)++ def test_explicit_is_failure_false_is_authoritative(self):+ # A False verdict wins even when the status string looks like a failure.+ env = build_envelope(+ [_payload(status="ERROR", failed_files=0, is_failure=False)]+ )+ self.assertEqual(env["summary"], {"total": 1, "succeeded": 1, "failed": 0})++ def test_absent_flag_falls_back_to_predicate_and_omits_key(self):+ # Worker / legacy payloads carry no flag: classification falls back to+ # is_failure_run(status, failed_files) and the event dict stays free of+ # the key (byte-identical to pre-change output).+ env = build_envelope([_payload(status="ERROR", failed_files=0)])+ self.assertEqual(env["summary"]["failed"], 1)+ self.assertNotIn("is_failure", env["events"][0])+++class RenderSlackTextTests(unittest.TestCase):+ def test_single_event_header_is_singular(self):+ text = render_slack_text(+ build_envelope([_payload(status="ERROR", failed_files=1, total_files=2)])+ )+ self.assertIn("*1 execution*", text)+ self.assertIn("1 failed", text)++ def test_explicit_failure_flag_drives_header_and_event_emoji(self):+ # End-to-end of the regression on the Slack side: a FAILURE-vocab run+ # with 0 failed files renders as failed (header + per-event glyph),+ # not the success ✅ it showed before the explicit verdict was carried.+ text = render_slack_text(+ build_envelope(+ [+ _payload(+ status="FAILURE",+ failed_files=0,+ total_files=0,+ is_failure=True,+ )+ ]+ )+ )+ self.assertIn("1 failed", text)+ self.assertIn(":x: 0/0 files", text)++ def test_overflow_footer_collapses_extra_events(self):+ payloads = [+ _payload(execution_id=f"e{i}") for i in range(SLACK_MAX_DISPLAY_EVENTS + 1)+ ]+ text = render_slack_text(build_envelope(payloads))+ # 26 events, 25 shown → exactly 1 collapsed under the footer.+ self.assertIn("and 1 more executions", text)++ def test_empty_batch_header_renders(self):+ text = render_slack_text(build_envelope([]))+ self.assertIn("*0 executions*", text)++ def test_failure_error_message_is_surfaced(self):+ # A failures-only Slack subscriber (the UN-3056 audience) must see the+ # failure reason, not just the status + file-count. error_message is+ # carried on the per-event dict; the line renderer surfaces it.+ text = render_slack_text(+ build_envelope(+ [+ _payload(+ status="ERROR",+ failed_files=1,+ total_files=2,+ error_message="Connector auth failed",+ )+ ]+ )+ )+ self.assertIn("Connector auth failed", text)++ def test_multiline_error_message_collapses_to_single_line(self):+ # A traceback must not break the one-line-per-event contract.+ text = render_slack_text(+ build_envelope(+ [+ _payload(+ status="ERROR",+ failed_files=1,+ total_files=2,+ error_message="line1\nline2\n line3",+ )+ ]+ )+ )+ event_line = text.split("\n")[-1]+ self.assertIn("line1 line2 line3", event_line)++ def test_success_event_line_omits_error_segment(self):+ # success payloads carry error_message=None → no trailing field appended+ # (line stays 6 fields: timestamp · *exec* · type · pipeline · status · files).+ text = render_slack_text(+ build_envelope([_payload(status="COMPLETED", failed_files=0, total_files=3)])+ )+ event_line = text.split("\n")[-1]+ self.assertEqual(len(event_line.split(" · ")), 6)++ def test_file_count_column_omitted_when_no_totals(self):+ # The "N/M files" column appears only when additional_data has totals;+ # an empty additional_data collapses the line (5 fields, not 6).+ with_counts = render_slack_text(+ build_envelope([_payload(total_files=3, failed_files=1)])+ )+ self.assertIn("files", with_counts)+ without_counts = render_slack_text(+ build_envelope([_payload(additional_data={})])+ )+ self.assertNotIn("files", without_counts)+++if __name__ == "__main__":+ unittest.main()diff --git a/workers/callback/tasks.py b/workers/callback/tasks.pyindex 80ba1f054..0532fb177 100644--- a/workers/callback/tasks.py+++ b/workers/callback/tasks.py@@ -380,12 +380,16 @@ def _update_execution_status_unified(try:# Consistent workflow execution status update across all callback typestotal_files = aggregated_results.get("total_files", 0)+ successful_files = aggregated_results.get("successful_files", 0)+ failed_files = aggregated_results.get("failed_files", 0)# Make the unified API callapi_client.update_workflow_execution_status(execution_id=execution_id,status=final_status,total_files=total_files,+ successful_files=successful_files,+ failed_files=failed_files,organization_id=organization_id,error_message=error_message,)diff --git a/workers/general/tasks.py b/workers/general/tasks.pyindex edceacdb7..38d363173 100644--- a/workers/general/tasks.py+++ b/workers/general/tasks.py@@ -34,6 +34,7 @@ from shared.models.execution_models import (WorkflowContextData,create_organization_context,)+from shared.patterns.notification.helper import notify_execution_failurefrom shared.patterns.retry.utils import circuit_breakerfrom shared.processing.files import FileProcessingUtilsfrom shared.processing.types import FileDataValidator, TypeConverter@@ -339,6 +340,29 @@ def async_execute_bin_general(f"[exec:{execution_id}] [pipeline:{pipeline_id}] Failed to update pipeline status to FAILED: {pipeline_error}")+ # Notify failure subscribers for runs that died before the+ # file-processing callback (missing tool / tool-validation /+ # source-setup errors). That callback is the only other ETL+ # dispatch point and never runs for these, so without this+ # the failure is silent. Fire only once retries are+ # exhausted so autoretry_for doesn't enqueue a duplicate per+ # attempt; mutually exclusive with the callback (a run that+ # reaches file processing returns normally above).+ if self.request.retries >= self.max_retries:+ try:+ notify_execution_failure(+ api_client=api_client,+ pipeline_id=pipeline_id,+ execution_id=execution_id,+ organization_id=schema_name,+ error_message=str(e),+ )+ except Exception as notify_error:+ logger.warning(+ f"[exec:{execution_id}] [pipeline:{pipeline_id}] "+ f"Early-failure notification dispatch failed: {notify_error}"+ )+except Exception as update_error:logger.error(f"Failed to update execution status: {update_error}")diff --git a/workers/log_consumer/process_notification_buffer.py b/workers/log_consumer/process_notification_buffer.pynew file mode 100755index 000000000..3d6d403f3--- /dev/null+++ b/workers/log_consumer/process_notification_buffer.py@@ -0,0 +1,91 @@+#!/usr/bin/env python3+"""Trigger backend processing of the notification buffer.++Mirrors process_log_history.py: a thin wrapper around an internal API call+that the log_consumer scheduler.sh fires on every tick. The backend owns the+actual GROUP BY / SKIP LOCKED / dispatch logic. Idempotent — safe to run+under multiple replicas (the backend's row-level lock prevents duplicate+dispatch).++Usage:+ python process_notification_buffer.py+"""++import logging+import os+import sys++import httpx++logger = logging.getLogger(__name__)++# Endpoint must match the URL registered in+# backend/notification_v2/internal_urls.py + backend/backend/internal_base_urls.py+PROCESS_BUFFER_ENDPOINT = "v1/webhook/buffer/process/"+++def process_notification_buffer() -> bool:+ """Hit the backend's process-buffer endpoint; return True on success.++ Returns False on auth/network failure so the calling scheduler can log+ the failure and proceed to the next tick. Never raises — the scheduler+ is supposed to keep ticking.+ """+ internal_api_base_url = os.getenv("INTERNAL_API_BASE_URL")+ internal_api_key = os.getenv("INTERNAL_SERVICE_API_KEY")++ if not internal_api_base_url:+ logger.error("INTERNAL_API_BASE_URL environment variable not set")+ return False+ if not internal_api_key:+ logger.error("INTERNAL_SERVICE_API_KEY environment variable not set")+ return False++ url = f"{internal_api_base_url.rstrip('/')}/{PROCESS_BUFFER_ENDPOINT}"+ # Longer timeout than process_log_history (60s vs 30s): a flush tick can+ # involve multiple Celery dispatches, GC, and per-group rendering.+ transport = httpx.HTTPTransport(retries=3)+ try:+ with httpx.Client(transport=transport) as client:+ response = client.post(+ url,+ headers={"Authorization": f"Bearer {internal_api_key}"},+ timeout=60.0,+ )+ except httpx.HTTPError:+ logger.exception("HTTP error calling process-buffer")+ return False+ except Exception:+ logger.exception("Unexpected error calling process-buffer")+ return False++ if response.status_code != 200:+ logger.error(+ "Backend returned status %s on process-buffer: %s",+ response.status_code,+ response.text[:500],+ )+ return False++ # A 200 with a non-JSON body (proxy/error page) would raise here; keep the+ # "never raises" contract so the scheduler keeps ticking.+ try:+ result = response.json()+ except ValueError:+ logger.error("Non-JSON 200 response from process-buffer: %s", response.text[:500])+ return False++ if result.get("dispatched_groups", 0) > 0 or result.get("gc_deleted_rows", 0) > 0:+ logger.info(+ "Notification buffer flush: groups=%s rows=%s reclaimed=%s gc=%s",+ result.get("dispatched_groups", 0),+ result.get("dispatched_rows", 0),+ result.get("reclaimed_rows", 0),+ result.get("gc_deleted_rows", 0),+ )+ return True+++if __name__ == "__main__":+ success = process_notification_buffer()+ sys.exit(0 if success else 1)diff --git a/workers/log_consumer/scheduler.sh b/workers/log_consumer/scheduler.shindex a5572b21e..e09a82dbd 100755--- a/workers/log_consumer/scheduler.sh+++ b/workers/log_consumer/scheduler.sh@@ -1,19 +1,38 @@#!/usr/bin/env bash-set -euo pipefail+set -uo pipefail+# Note: pipefail without -e — one task's failure must not abort the loop.-INTERVAL="${LOG_HISTORY_CONSUMER_INTERVAL:-5}"-TASK_NAME="process_log_history"+# Task 1: log history consumer (existing).+LOG_HISTORY_INTERVAL="${LOG_HISTORY_CONSUMER_INTERVAL:-5}"+DEFAULT_LOG_HISTORY_CMD="/app/.venv/bin/python /app/log_consumer/process_log_history.py"+LOG_HISTORY_CMD="${TASK_TRIGGER_COMMAND:-$DEFAULT_LOG_HISTORY_CMD}"-# Task trigger command - can be overridden via environment variable-DEFAULT_TRIGGER_CMD="/app/.venv/bin/python /app/log_consumer/process_log_history.py"-TRIGGER_CMD="${TASK_TRIGGER_COMMAND:-$DEFAULT_TRIGGER_CMD}"+# Task 2: notification buffer flush (clubbed dispatch).+# Polls on its OWN cadence (NOTIFICATION_BUFFER_POLL_INTERVAL), decoupled from+# the log-history consumer so one env knob doesn't silently govern both tasks.+# The endpoint short-circuits on an empty PENDING set, so frequent polling is+# cheap; the real dispatch cadence is gated by NOTIFICATION_CLUB_INTERVAL on the+# backend (rows precompute flush_after at enqueue time), so this only bounds how+# soon a due group is picked up.+NOTIFICATION_BUFFER_INTERVAL="${NOTIFICATION_BUFFER_POLL_INTERVAL:-10}"+DEFAULT_BUFFER_FLUSH_CMD="/app/.venv/bin/python /app/log_consumer/process_notification_buffer.py"+BUFFER_FLUSH_CMD="${NOTIFICATION_BUFFER_TASK_COMMAND:-$DEFAULT_BUFFER_FLUSH_CMD}"++# Loop wakes at the finer of the two cadences (min, floored at 1s); each task+# fires independently once its own interval has elapsed.+if [[ "${LOG_HISTORY_INTERVAL}" -lt "${NOTIFICATION_BUFFER_INTERVAL}" ]]; then+ BASE_INTERVAL="${LOG_HISTORY_INTERVAL}"+else+ BASE_INTERVAL="${NOTIFICATION_BUFFER_INTERVAL}"+fi+[[ "${BASE_INTERVAL}" -lt 1 ]] && BASE_INTERVAL=1echo "=========================================="-echo "Log History Scheduler Starting"+echo "Log Consumer Scheduler Starting"echo "=========================================="-echo "Task: ${TASK_NAME}"-echo "Interval: ${INTERVAL} seconds"-echo "Trigger Command: ${TRIGGER_CMD}"+echo "Log history interval: ${LOG_HISTORY_INTERVAL}s | Buffer flush interval: ${NOTIFICATION_BUFFER_INTERVAL}s"+echo "Task 1 (log history): ${LOG_HISTORY_CMD}"+echo "Task 2 (notification buffer flush): ${BUFFER_FLUSH_CMD}"echo "=========================================="cleanup() {@@ -22,29 +41,52 @@ cleanup() {echo "Scheduler received shutdown signal"echo "Exiting gracefully..."echo "=========================================="- exit 0+ return 0}-trap cleanup SIGTERM SIGINT+# The trap exits after cleanup runs; cleanup itself returns so the function+# has an explicit terminal return (no unreachable code after exit).+trap 'cleanup; exit 0' SIGTERM SIGINT++run_task() {+ # $1 = display name, $2 = command, $3 = run number. Returns the command's+ # exit code but never propagates failure — the caller logs it and moves on.+ local task_name="$1"+ local cmd="$2"+ local run_num="$3"+ local exit_code=0+ echo "[$(date '+%Y-%m-%d %H:%M:%S')] [Run #${run_num}] Triggering ${task_name}..."+ if eval "${cmd}" 2>&1; then+ echo "[$(date '+%Y-%m-%d %H:%M:%S')] [Run #${run_num}] ✓ ${task_name} OK"+ else+ exit_code=$?+ echo "[$(date '+%Y-%m-%d %H:%M:%S')] [Run #${run_num}] ✗ ${task_name} failed with exit code ${exit_code}"+ fi+ return "${exit_code}"+}run_count=0+# Seed both at 0 so each task fires on the first loop iteration (now ≫ interval).+last_log_run=0+last_buffer_run=0while true; do- run_count=$((run_count + 1))+ now=$(date '+%s')- echo "[$(date '+%Y-%m-%d %H:%M:%S')] [Run #${run_count}] Triggering ${TASK_NAME}..."-- if eval "${TRIGGER_CMD}" 2>&1; then- echo "[$(date '+%Y-%m-%d %H:%M:%S')] [Run #${run_count}] ✓ Task completed successfully"- else- exit_code=$?- echo "[$(date '+%Y-%m-%d %H:%M:%S')] [Run #${run_count}] ✗ Task failed with exit code ${exit_code}"- echo "[$(date '+%Y-%m-%d %H:%M:%S')] [Run #${run_count}] Will retry after ${INTERVAL} seconds"+ if [[ $((now - last_log_run)) -ge "${LOG_HISTORY_INTERVAL}" ]]; then+ run_count=$((run_count + 1))+ run_task "process_log_history" "${LOG_HISTORY_CMD}" "${run_count}"+ last_log_run="${now}"fi- echo "[$(date '+%Y-%m-%d %H:%M:%S')] Sleeping for ${INTERVAL} seconds..."- echo ""+ if [[ $((now - last_buffer_run)) -ge "${NOTIFICATION_BUFFER_INTERVAL}" ]]; then+ run_count=$((run_count + 1))+ run_task "process_notification_buffer" "${BUFFER_FLUSH_CMD}" "${run_count}"+ last_buffer_run="${now}"+ fi- sleep "${INTERVAL}" &+ # Background sleep + wait so a SIGTERM/SIGINT interrupts promptly (the trap+ # fires, cleanup runs, the script exits) instead of blocking the full tick.+ sleep "${BASE_INTERVAL}" &wait $!donediff --git a/workers/notification/providers/api_webhook.py b/workers/notification/providers/api_webhook.pyindex 8c54d2d19..3acee31fa 100644--- a/workers/notification/providers/api_webhook.py+++ b/workers/notification/providers/api_webhook.py@@ -1,6 +1,10 @@"""API Webhook Notification Provider-Standard API webhook provider for generic webhook endpoints.+Wraps single-event payloads (flat per-event dict) in the canonical envelope so+API webhook receivers always see the same ``{"summary": {...}, "events": [...]}``+shape. The decision is purely shape-based: a payload already in envelope shape+(it contains ``events`` — e.g. a backend buffer-rendered batch) passes through+unchanged; only a flat per-event dict is wrapped here."""from typing import Any@@ -8,17 +12,20 @@ from typing import Anyfrom notification.providers.webhook_provider import WebhookProviderfrom shared.infrastructure.logging import WorkerLogger+from unstract.core.notification_clubbed_renderer import build_envelope+logger = WorkerLogger.get_logger(__name__)class APIWebhook(WebhookProvider):"""Standard API webhook provider.- Handles generic webhook notifications without platform-specific formatting.- Sends the payload as-is in JSON format.+ Normalises the payload to the canonical envelope before POSTing so+ programmatic consumers parse one schema regardless of how the+ notification was produced."""- def __init__(self):+ def __init__(self) -> None:"""Initialize API webhook provider."""super().__init__()self.provider_name = "APIWebhook"@@ -26,16 +33,15 @@ class APIWebhook(WebhookProvider):def prepare_data(self, notification_data: dict[str, Any]) -> dict[str, Any]:"""Prepare API webhook data.- For standard API webhooks, we send the payload as-is without- any special formatting.+ Wraps a flat per-event payload in the canonical envelope; payloads+ already in envelope shape (backend buffer-rendered) pass through.+ """+ prepared_data = super().prepare_data(notification_data)- Args:- notification_data: Raw notification data+ if "payload" in prepared_data:+ payload = prepared_data["payload"]+ if isinstance(payload, dict) and "events" not in payload:+ prepared_data["payload"] = build_envelope(payloads=[payload])- Returns:- Prepared notification data- """- logger.debug(- f"Preparing standard API webhook data for {notification_data.get('url')}"- )- return super().prepare_data(notification_data)+ logger.debug(f"Prepared API webhook data for {notification_data.get('url')}")+ return prepared_datadiff --git a/workers/notification/providers/slack_webhook.py b/workers/notification/providers/slack_webhook.pyindex 89206646a..6c97cde02 100644--- a/workers/notification/providers/slack_webhook.py+++ b/workers/notification/providers/slack_webhook.py@@ -1,7 +1,10 @@"""Slack Webhook Notification Provider-This provider handles Slack-specific webhook notifications with proper-payload formatting for Slack's Block Kit API.+Renders single-event payloads (flat per-event dict) into the same Slack mrkdwn+body the backend produces via ``clubbed_renderer``. The decision is+purely shape-based: a payload already rendered to ``{"text": "<mrkdwn>"}``+(e.g. a backend buffer-rendered batch) passes through unchanged; only a flat+per-event dict is wrapped and rendered here."""from typing import Any@@ -9,17 +12,23 @@ from typing import Anyfrom notification.providers.webhook_provider import WebhookProviderfrom shared.infrastructure.logging import WorkerLogger+from unstract.core.notification_clubbed_renderer import (+ build_envelope,+ render_slack_text,+)+logger = WorkerLogger.get_logger(__name__)class SlackWebhook(WebhookProvider):"""Slack-specific webhook provider.- Formats payloads according to Slack's expected structure,- including support for Block Kit formatting.+ Renders flat single-event payloads via the worker-side mirror of the+ backend clubbed renderer, then sends them as Slack-native ``text``+ mrkdwn."""- def __init__(self):+ def __init__(self) -> None:"""Initialize Slack webhook provider."""super().__init__()self.provider_name = "SlackWebhook"@@ -27,9 +36,6 @@ class SlackWebhook(WebhookProvider):def prepare_data(self, notification_data: dict[str, Any]) -> dict[str, Any]:"""Prepare Slack-specific webhook data.- Formats the payload to match Slack's expected structure- with 'text' field and optional Block Kit blocks.-Args:notification_data: Raw notification data@@ -38,7 +44,6 @@ class SlackWebhook(WebhookProvider):"""prepared_data = super().prepare_data(notification_data)- # Format payload for Slackif "payload" in prepared_data:prepared_data["payload"] = self.format_payload(prepared_data["payload"])@@ -47,171 +52,18 @@ class SlackWebhook(WebhookProvider):def format_payload(self, payload: dict[str, Any]) -> dict[str, Any]:"""Format the payload to match Slack's expected structure.- Args:- payload: Original payload-- Returns:- Slack-formatted payload with 'text' field and optional blocks- """- # If payload already has 'text' field, enhance it with blocks- if "text" in payload:- formatted_payload = {- "text": payload.pop("text"),- "blocks": self.create_blocks_from_payload(payload),- }- else:- # Construct a Slack message from the payload- formatted_payload = {- "text": self._get_summary_text(payload),- "blocks": self.create_blocks_from_payload(payload),- }-- return formatted_payload-- def create_blocks_from_payload(self, payload: dict[str, Any]) -> list[dict[str, Any]]:- """Create Slack Block Kit blocks from the payload.-- Args:- payload: Payload to convert to blocks-- Returns:- List of Slack Block Kit blocks- """- blocks = []-- # Header block- blocks.append(- {- "type": "section",- "text": {"type": "mrkdwn", "text": "*Unstract Notification*"},- }- )-- # Add divider for visual separation- blocks.append({"type": "divider"})-- # Add each key-value pair as a section- for key, value in payload.items():- if value is None or value == "":- continue-- # Format key for display- formatted_key = self._format_key(key)-- # Format value based on type- formatted_value = self._format_value(value)-- # Create section block with inline format- blocks.append(- {- "type": "section",- "text": {- "type": "mrkdwn",- "text": f"*{formatted_key}:* {formatted_value}",- },- }- )-- # Add timestamp footer if not already present- if not any("timestamp" in str(block).lower() for block in blocks):- from datetime import datetime-- blocks.append({"type": "divider"})- blocks.append(- {- "type": "context",- "elements": [- {- "type": "mrkdwn",- "text": f"_Sent at {datetime.now().strftime('%Y-%m-%d %H:%M:%S UTC')}_",- }- ],- }- )-- return blocks-- def _get_summary_text(self, payload: dict[str, Any]) -> str:- """Generate summary text from payload.-- Args:- payload: Payload to summarize-- Returns:- Summary text for Slack notification- """- # Priority order for summary fields- summary_fields = [- "message",- "status",- "pipeline_name",- "workflow_name",- "api_name",- "error",- "result",- "summary",- ]-- for field in summary_fields:- if field in payload and payload[field]:- return str(payload[field])-- # Default summary- return "Unstract Notification"-- def _format_key(self, key: str) -> str:- """Format dictionary key for display.-- Args:- key: Raw key name-- Returns:- Formatted key for display+ Two input shapes are accepted:+ - Backend-rendered ``{"text": "<mrkdwn>"}`` (any backend dispatch+ through ``clubbed_renderer``) — passed through.+ - Flat per-event dict from the generic internal webhook-send endpoints —+ wrapped in a single-event envelope and rendered to the canonical+ Slack mrkdwn body."""- # Replace underscores with spaces and capitalize- formatted = key.replace("_", " ").title()-- # Special formatting for known keys- key_mapping = {- "Pipeline Name": "Pipeline Name",- "Api Name": "API Name",- "Workflow Name": "Workflow Name",- "Status": "Status",- "Error": "Error",- "Success": "Success",- "Execution Id": "Execution Id",- "Organization Id": "Organization Id",- }-- return key_mapping.get(formatted, formatted)-- def _format_value(self, value: Any) -> str:- """Format value for Slack display.-- Args:- value: Value to format+ if "text" in payload and "events" not in payload:+ return {"text": payload["text"]}- Returns:- Formatted value string- """- if isinstance(value, bool):- return "✅ Yes" if value else "❌ No"- elif isinstance(value, (list, tuple)):- return "\n• " + "\n• ".join(str(item) for item in value)- elif isinstance(value, dict):- # Format nested dictionary- items = []- for k, v in value.items():- items.append(f" • {self._format_key(k)}: {v}")- return "\n" + "\n".join(items)- elif value is None:- return "_Not specified_"- else:- # Format long strings- value_str = str(value)- if len(value_str) > 500:- return value_str[:497] + "..."- return value_str+ envelope = build_envelope(payloads=[payload])+ return {"text": render_slack_text(envelope)}def get_destination(self, notification_data: dict[str, Any]) -> str:"""Extract webhook URL from notification data with masking for security."""@@ -230,4 +82,4 @@ class SlackWebhook(WebhookProvider):# Mask long URLs that might contain tokensreturn url[:30] + "..." + url[-10:]- return url+ return str(url)diff --git a/workers/notification/tasks.py b/workers/notification/tasks.pyindex c092fbc05..41d76f5cf 100644--- a/workers/notification/tasks.py+++ b/workers/notification/tasks.py@@ -8,6 +8,7 @@ while maintaining backward compatibility.import osfrom typing import Any+import httpxfrom notification.enums import PlatformTypefrom notification.providers.base_provider import (DeliveryError,@@ -164,6 +165,64 @@ def process_notification(}+def _mark_buffer_outcome(+ buffer_row_ids: list[str] | None,+ organization_id: Any,+ *,+ dispatched: bool,+) -> None:+ """Report a clubbed dispatch's buffer rows as DISPATCHED / DEAD_LETTER.++ Replaces the old Celery ``link``/``link_error`` callbacks with an internal+ HTTP POST, so marking no longer depends on a backend task being registered+ on whichever worker happens to drain the ``celery`` queue. Bearer-authed+ with org scoping carried in the body (matches the ``buffer/process`` flush+ call style — ``organization_id`` is the numeric org pk, not a header).+ Best-effort: if this POST fails the rows stay SENDING and the backend reaper+ reclaims them after the lease — the same safety net as before.+ """+ if not buffer_row_ids or organization_id is None:+ return+ base_url = os.getenv("INTERNAL_API_BASE_URL")+ api_key = os.getenv("INTERNAL_SERVICE_API_KEY")+ if not base_url or not api_key:+ logger.warning(+ "Cannot mark buffer rows: INTERNAL_API_BASE_URL / "+ "INTERNAL_SERVICE_API_KEY not set"+ )+ return+ suffix = "dispatched" if dispatched else "dead-letter"+ url = f"{base_url.rstrip('/')}/v1/webhook/buffer/mark/{suffix}/"+ try:+ with httpx.Client(transport=httpx.HTTPTransport(retries=2)) as client:+ response = client.post(+ url,+ headers={"Authorization": f"Bearer {api_key}"},+ json={+ "buffer_row_ids": buffer_row_ids,+ "organization_id": organization_id,+ },+ timeout=10.0,+ )+ if response.status_code != 200:+ logger.warning(+ "metric=notification_buffer_mark_failed_total result=%s "+ "reason=http_%s rows=%d body=%s; reaper will reclaim",+ suffix,+ response.status_code,+ len(buffer_row_ids),+ response.text[:200],+ )+ except Exception as e: # noqa: BLE001+ logger.warning(+ "metric=notification_buffer_mark_failed_total result=%s "+ "reason=exception rows=%d exc=%r; reaper will reclaim",+ suffix,+ len(buffer_row_ids),+ e,+ )++@worker_task(bind=True, name="send_webhook_notification")def send_webhook_notification(self,@@ -174,6 +233,9 @@ def send_webhook_notification(max_retries: int | None = None,retry_delay: int = 10,platform: str | None = None,+ raise_on_final_failure: bool = False,+ buffer_row_ids: list[str] | None = None,+ organization_id: str | None = None,) -> None:"""Backward compatible webhook notification task.@@ -189,12 +251,17 @@ def send_webhook_notification(max_retries: The maximum number of retries allowedretry_delay: The delay between retries in secondsplatform: Platform type from notification config (SLACK, API, etc.)+ raise_on_final_failure: When True, re-raise on retry exhaustion so the+ task ends in FAILURE and any Celery ``link_error`` callback runs+ (used by the clubbed/buffered dispatch to dead-letter the rows).+ When False (default), preserve the legacy "return None" behavior.Returns:None (matches original behavior)Raises:- Exception: If webhook delivery fails (for Celery retry mechanism)+ Exception: If webhook delivery fails (for Celery retry mechanism), or on+ final failure when ``raise_on_final_failure`` is set."""try:logger.debug(@@ -235,6 +302,7 @@ def send_webhook_notification(f"Webhook delivered successfully to {url} "f"(status: {result.get('details', {}).get('status_code', 'unknown')})")+ _mark_buffer_outcome(buffer_row_ids, organization_id, dispatched=True)return None # Success - matches original behaviorelse:# Failed delivery - raise exception for retry handling@@ -256,9 +324,15 @@ def send_webhook_notification(f"Failed to send webhook to {url} after {max_retries} attempts. "f"Error: {e}")+ _mark_buffer_outcome(buffer_row_ids, organization_id, dispatched=False)+ if raise_on_final_failure:+ raisereturn None # Final failure - matches original behaviorelse:logger.error(f"Webhook request to {url} failed with error: {e}")+ _mark_buffer_outcome(buffer_row_ids, organization_id, dispatched=False)+ if raise_on_final_failure:+ raisereturn None # No retries configured - matches original behaviorexcept Exception as e:@@ -275,9 +349,15 @@ def send_webhook_notification(f"Failed to send webhook to {url} after {max_retries} attempts. "f"Error: {e}")+ _mark_buffer_outcome(buffer_row_ids, organization_id, dispatched=False)+ if raise_on_final_failure:+ raisereturn Noneelse:logger.error(f"Webhook request to {url} failed with error: {e}")+ _mark_buffer_outcome(buffer_row_ids, organization_id, dispatched=False)+ if raise_on_final_failure:+ raisereturn Nonediff --git a/workers/scheduler/tasks.py b/workers/scheduler/tasks.pyindex a152b98ae..b0bd0ec9f 100644--- a/workers/scheduler/tasks.py+++ b/workers/scheduler/tasks.py@@ -82,6 +82,7 @@ def _send_pipeline_status_notification(pipeline_id=pipeline_id,pipeline_name=pipeline_name,notification_payload=notification,+ execution_id=execution_id,)logger.info(f"Notification sent successfully for {pipeline_type} {pipeline_id}")except Exception as notification_error:diff --git a/workers/shared/api/internal_client.py b/workers/shared/api/internal_client.pyindex def90bd86..4964a2b37 100644--- a/workers/shared/api/internal_client.py+++ b/workers/shared/api/internal_client.py@@ -603,6 +603,8 @@ class InternalAPIClient(CachedAPIClientMixin):status: str,error_message: str | None = None,total_files: int | None = None,+ successful_files: int | None = None,+ failed_files: int | None = None,attempts: int | None = None,execution_time: float | None = None,organization_id: str | None = None,@@ -613,6 +615,8 @@ class InternalAPIClient(CachedAPIClientMixin):status,error_message,total_files,+ successful_files,+ failed_files,attempts,execution_time,organization_id,diff --git a/workers/shared/clients/execution_client.py b/workers/shared/clients/execution_client.pyindex 80e9ca656..e1373eb9f 100644--- a/workers/shared/clients/execution_client.py+++ b/workers/shared/clients/execution_client.py@@ -265,6 +265,8 @@ class ExecutionAPIClient(BaseAPIClient):status: str | TaskStatus,error_message: str | None = None,total_files: int | None = None,+ successful_files: int | None = None,+ failed_files: int | None = None,attempts: int | None = None,execution_time: float | None = None,organization_id: str | None = None,@@ -276,6 +278,8 @@ class ExecutionAPIClient(BaseAPIClient):status: New status (TaskStatus enum or string)error_message: Optional error messagetotal_files: Optional total files count+ successful_files: Optional count of files that completed successfully+ failed_files: Optional count of files that erroredattempts: Optional attempts countexecution_time: Optional execution timeorganization_id: Optional organization ID override@@ -292,6 +296,10 @@ class ExecutionAPIClient(BaseAPIClient):data["error_message"] = error_messageif total_files is not None:data["total_files"] = total_files+ if successful_files is not None:+ data["successful_files"] = successful_files+ if failed_files is not None:+ data["failed_files"] = failed_filesif attempts is not None:data["attempts"] = attemptsif execution_time is not None:diff --git a/workers/shared/patterns/notification/helper.py b/workers/shared/patterns/notification/helper.pyindex 199a5b8de..ae7ac39be 100644--- a/workers/shared/patterns/notification/helper.py+++ b/workers/shared/patterns/notification/helper.py@@ -5,8 +5,7 @@ No Django dependencies, works in pure worker environment."""import logging--from queue_backend import dispatch+from typing import Any# Import shared data models from @unstract/corefrom unstract.core.data_models import (@@ -18,86 +17,93 @@ from unstract.core.data_models import (logger = logging.getLogger(__name__)--def get_webhook_headers(- auth_type: str, auth_key: str | None, auth_header: str | None-) -> dict[str, str]:- """Generate webhook headers based on authorization configuration."""- headers = {"Content-Type": "application/json"}-- try:- if auth_type and auth_key:- auth_type_upper = auth_type.upper()-- if auth_type_upper == "BEARER":- headers["Authorization"] = f"Bearer {auth_key}"- elif auth_type_upper == "API_KEY":- headers["Authorization"] = auth_key- elif auth_type_upper == "CUSTOM_HEADER" and auth_header:- headers[auth_header] = auth_key- # NONE type just uses Content-Type header- except Exception as e:- logger.warning(f"Error generating webhook headers: {e}")- # Use default headers if auth config is invalid-- return headers+ENQUEUE_BUFFER_ENDPOINT = "v1/webhook/buffer/enqueue/"-def send_notification_to_worker(- url: str,+def _enqueue_to_buffer(+ api_client: Any,+ notification: dict[str, Any],payload: NotificationPayload,- auth_type: str,- auth_key: str | None,- auth_header: str | None,- max_retries: int = 0,- platform: str | None = None,-) -> bool:- """Send a single notification to the notification worker queue.+) -> None:+ """POST a single execution event to the backend's buffer endpoint.- Args:- url: Webhook URL to send notification to- payload: Structured notification payload- auth_type: Authorization type (NONE, BEARER, API_KEY, CUSTOM_HEADER)- auth_key: Authorization key/token- auth_header: Custom header name for CUSTOM_HEADER auth type- max_retries: Maximum number of retry attempts- platform: Platform type from notification config (SLACK, API, etc.)-- Returns:- True if task was successfully queued, False otherwise+ Worker writes nothing to the DB itself — the backend owns NotificationBuffer+ rows. Raises on any failure so the outer trigger_* caller's except block+ logs the drop instead of silently treating BATCHED delivery as successful."""+ # Forward the full per-event shape so the backend can buffer it and the+ # shared clubbed renderer can format each event consistently. Older backend+ # builds that ignore the extra fields stay unaffected.+ payload_type = payload.type.value if hasattr(payload.type, "value") else payload.type+ payload_status = (+ payload.status.value if hasattr(payload.status, "value") else payload.status+ )+ payload_timestamp = payload.timestamp.isoformat() if payload.timestamp else Nonetry:- headers = get_webhook_headers(auth_type, auth_key, auth_header)-- # Convert payload to webhook format (excludes internal fields)- payload_dict = payload.to_webhook_payload()-- # Send task to notification worker- dispatch(- "send_webhook_notification",- args=[- url,- payload_dict,- headers,- 10, # timeout- ],- kwargs={- "max_retries": max_retries,- "retry_delay": 10,- "platform": platform,+ api_client._make_request(+ method="POST",+ endpoint=ENQUEUE_BUFFER_ENDPOINT,+ data={+ "notification_id": notification["id"],+ "type": payload_type,+ "execution_id": payload.execution_id,+ "pipeline_id": payload.pipeline_id,+ "pipeline_name": payload.pipeline_name,+ "status": payload_status,+ "error_message": payload.error_message,+ "platform": notification.get("platform"),+ "timestamp": payload_timestamp,+ "additional_data": payload.additional_data or {},},- queue="notifications",- fairness=None, # not a workflow-execution dispatch+ timeout=10,)+ # Propagate any failure; caller decides whether to continue iteration.+ except Exception: # noqa: BLE001+ logger.exception(+ "Failed to enqueue BATCHED notification %s for pipeline %s",+ notification["id"],+ payload.pipeline_id,+ )+ raise+ logger.info(+ "Enqueued BATCHED notification %s for pipeline %s execution %s",+ notification["id"],+ payload.pipeline_id,+ payload.execution_id,+ )+++def _route_notification(+ api_client: Any,+ notification: dict[str, Any],+ payload: NotificationPayload,+) -> None:+ """Forward webhook notifications to the backend buffer-enqueue endpoint.- logger.info(- f"Sent webhook notification to worker queue for {url} (pipeline: {payload.pipeline_id})"+ Single dispatch path: the backend owns the buffer and the periodic+ flush ships clubbed messages. Non-webhook notification types are+ skipped at this layer. An enqueue failure is logged but doesn't abort+ the outer trigger_* loop so sibling notifications still get their+ chance.+ """+ if notification.get("notification_type") != "WEBHOOK":+ logger.debug(+ "Skipping non-webhook notification type: %s",+ notification.get("notification_type"),)- return True+ return- except Exception as e:- logger.error(f"Failed to send notification to {url}: {e}")- return False+ try:+ _enqueue_to_buffer(api_client, notification, payload)+ # Already logged with stack inside _enqueue_to_buffer; broad catch keeps+ # sibling notifications going. Emit a metric so a dropped failure alert is+ # observable here (this is the path's final swallow point).+ except Exception: # noqa: BLE001+ logger.warning(+ "metric=notification_dropped_total notification_id=%s; "+ "buffer enqueue failed, continuing with others",+ notification.get("id"),+ )def trigger_notification(@@ -105,6 +111,7 @@ def trigger_notification(pipeline_id: str,pipeline_name: str,notification_payload: NotificationPayload,+ execution_id: str | None = None,) -> None:"""Trigger notifications for pipeline status updates.@@ -112,10 +119,13 @@ def trigger_notification(Uses API client to fetch notification configuration."""try:- # Fetch pipeline notifications via API+ # Pass execution_id so the backend filter respects notify_on_failures+ # (see trigger_pipeline_notifications for the rationale).+ params = {"execution_id": execution_id} if execution_id else Noneresponse_data = api_client._make_request(method="GET",endpoint=f"v1/webhook/pipeline/{pipeline_id}/notifications/",+ params=params,timeout=10,)@@ -136,20 +146,7 @@ def trigger_notification(# Send each notificationfor notification in active_notifications:- if notification.get("notification_type") == "WEBHOOK":- send_notification_to_worker(- url=notification["url"],- payload=notification_payload,- auth_type=notification.get("authorization_type", "NONE"),- auth_key=notification.get("authorization_key"),- auth_header=notification.get("authorization_header"),- max_retries=notification.get("max_retries", 0),- platform=notification.get("platform"),- )- else:- logger.debug(- f"Skipping non-webhook notification type: {notification.get('notification_type')}"- )+ _route_notification(api_client, notification, notification_payload)except Exception as e:logger.error(f"Error triggering pipeline notifications for {pipeline_id}: {e}")@@ -177,10 +174,14 @@ def trigger_pipeline_notifications(returntry:- # Fetch pipeline notifications via API+ # Pass execution_id so the backend can drop notify_on_failures=True rows+ # on success runs. Without it the endpoint is a no-op and we'd fire on+ # every active row regardless of trigger preference.+ params = {"execution_id": execution_id} if execution_id else Noneresponse_data = api_client._make_request(method="GET",endpoint=f"v1/webhook/pipeline/{pipeline_id}/notifications/",+ params=params,timeout=10,)@@ -205,7 +206,9 @@ def trigger_pipeline_notifications(else:workflow_type = WorkflowType.ETL # Default fallback- # Create notification payload using dataclass+ # File counts come from WorkflowExecution via the same endpoint so+ # webhook receivers (Slack, raw API) see partial-success breakdowns.+ counts = response_data.get("execution_counts") or {}payload = NotificationPayload.from_execution_status(pipeline_id=pipeline_id,pipeline_name=pipeline_name,@@ -214,6 +217,9 @@ def trigger_pipeline_notifications(source=NotificationSource.CALLBACK_WORKER,execution_id=execution_id,error_message=error_message,+ total_files=counts.get("total_files", 0),+ successful_files=counts.get("successful_files", 0),+ failed_files=counts.get("failed_files", 0),)logger.info(@@ -222,20 +228,7 @@ def trigger_pipeline_notifications(# Send each notificationfor notification in active_notifications:- if notification.get("notification_type") == "WEBHOOK":- send_notification_to_worker(- url=notification["url"],- payload=payload,- auth_type=notification.get("authorization_type", "NONE"),- auth_key=notification.get("authorization_key"),- auth_header=notification.get("authorization_header"),- max_retries=notification.get("max_retries", 0),- platform=notification.get("platform"),- )- else:- logger.debug(- f"Skipping non-webhook notification type: {notification.get('notification_type')}"- )+ _route_notification(api_client, notification, payload)except Exception as e:logger.error(f"Error triggering pipeline notifications for {pipeline_id}: {e}")@@ -262,9 +255,14 @@ def trigger_api_notifications(returntry:- # Fetch API notifications via API+ # See trigger_pipeline_notifications: execution_id powers the backend+ # filter that respects notify_on_failures.+ params = {"execution_id": execution_id} if execution_id else Noneresponse_data = api_client._make_request(- method="GET", endpoint=f"v1/webhook/api/{api_id}/notifications/", timeout=10+ method="GET",+ endpoint=f"v1/webhook/api/{api_id}/notifications/",+ params=params,+ timeout=10,)# _make_request already handles status codes and returns parsed data@@ -278,7 +276,7 @@ def trigger_api_notifications(logger.info(f"No active notifications found for API {api_id}")return- # Create notification payload using dataclass+ counts = response_data.get("execution_counts") or {}payload = NotificationPayload.from_execution_status(pipeline_id=api_id,pipeline_name=api_name,@@ -287,6 +285,9 @@ def trigger_api_notifications(source=NotificationSource.CALLBACK_WORKER,execution_id=execution_id,error_message=error_message,+ total_files=counts.get("total_files", 0),+ successful_files=counts.get("successful_files", 0),+ failed_files=counts.get("failed_files", 0),)logger.info(@@ -295,27 +296,14 @@ def trigger_api_notifications(# Send each notificationfor notification in active_notifications:- if notification.get("notification_type") == "WEBHOOK":- send_notification_to_worker(- url=notification["url"],- payload=payload,- auth_type=notification.get("authorization_type", "NONE"),- auth_key=notification.get("authorization_key"),- auth_header=notification.get("authorization_header"),- max_retries=notification.get("max_retries", 0),- platform=notification.get("platform"),- )- else:- logger.debug(- f"Skipping non-webhook notification type: {notification.get('notification_type')}"- )+ _route_notification(api_client, notification, payload)except Exception as e:logger.error(f"Error triggering API notifications for {api_id}: {e}")def handle_status_notifications(- api_client,+ api_client: Any,pipeline_id: str,status: str,execution_id: str | None = None,@@ -445,3 +433,63 @@ def handle_status_notifications(import tracebacktraceback.print_exc()+++def notify_execution_failure(+ api_client: Any,+ pipeline_id: str,+ execution_id: str,+ organization_id: str,+ error_message: str | None = None,+) -> None:+ """Dispatch a failure notification for a run that errored *before* the+ file-processing callback ran.++ ETL/Task notifications normally fire from the callback worker's+ ``handle_status_notifications`` once files finish processing. Build/setup+ failures — missing-tool / tool-registry errors, tool validation, source+ connector errors — halt the run before any file is processed, so that+ callback never runs and a "notify on failures" subscriber hears nothing.+ This resolves the pipeline's name/type from the backend and reuses the+ standard dispatch with a terminal ERROR status, so the failure-filter and+ the clubbed payload are identical to the normal path.++ Mutually exclusive with the callback: a run that reaches file processing+ returns normally from the worker and is notified by the callback instead.+ API deployments are intentionally not handled here — they already dispatch+ early failures through the backend ``update_pipeline_status`` path.+ """+ try:+ api_client.set_organization_context(organization_id)+ response = api_client.get_pipeline_data(+ pipeline_id=pipeline_id, check_active=False+ )+ if not (getattr(response, "success", False) and response.data):+ logger.warning(+ "Skipping early-failure notification for %s: pipeline data unavailable",+ pipeline_id,+ )+ return+ # Unified endpoint nests the record under "pipeline"; fall back to the+ # flat shape for older builds.+ pdata = response.data.get("pipeline", response.data)+ pipeline_name = pdata.get("pipeline_name") or pdata.get("api_name")+ pipeline_type = pdata.get("pipeline_type", WorkflowType.ETL.value)+ except Exception as e: # noqa: BLE001+ logger.warning(+ "Could not resolve pipeline %s for early-failure notification: %s",+ pipeline_id,+ e,+ )+ return++ handle_status_notifications(+ api_client=api_client,+ pipeline_id=pipeline_id,+ status=ExecutionStatus.ERROR.value,+ execution_id=execution_id,+ error_message=error_message,+ pipeline_name=pipeline_name,+ pipeline_type=pipeline_type,+ organization_id=organization_id,+ )diff --git a/workers/tests/test_dispatch_sites_characterisation.py b/workers/tests/test_dispatch_sites_characterisation.pyindex d07721bdb..7900503b0 100644--- a/workers/tests/test_dispatch_sites_characterisation.py+++ b/workers/tests/test_dispatch_sites_characterisation.py@@ -1,157 +1,157 @@-"""Behavioural tests for the two dispatch sites — now routed through the-``queue_backend.dispatch()`` seam.--Both sites used to call ``current_app.send_task(...)`` directly with a-string task name. They now go through ``queue_backend.dispatch(...)``-instead. The dispatch contract — task name, positional args, keyword-args, and target queue — is unchanged by the migration; ``dispatch()``-is a transparent pass-through to ``current_app.send_task`` today.--This suite locks down the contract at each call site so a future change-that quietly drops a kwarg or rewires a queue will fail loudly.--Sites:-1. ``shared/patterns/notification/helper.py:send_notification_to_worker``-2. ``scheduler/tasks.py:_execute_scheduled_workflow``+"""Behavioural tests for the worker dispatch sites.++Two independent contracts are pinned here so a future change that quietly+drops a field, rewires a queue, or changes an endpoint fails loudly:++1. ``shared/patterns/notification/helper.py`` — status-callback notifications.+ UN-3056 replaced the old ``send_notification_to_worker`` ->+ ``queue_backend.dispatch`` path with a model-free HTTP enqueue:+ ``_route_notification`` -> ``_enqueue_to_buffer`` POSTs each event to the+ backend buffer endpoint, which owns batching + send. These tests+ characterise that HTTP enqueue contract.+2. ``scheduler/tasks.py:_execute_scheduled_workflow`` — still routed through+ the ``queue_backend.dispatch()`` seam (unchanged)."""from unittest.mock import MagicMock, patchimport pytest+from shared.patterns.notification.helper import (+ ENQUEUE_BUFFER_ENDPOINT,+ _enqueue_to_buffer,+ _route_notification,+)-# --- Site 1: shared/patterns/notification/helper.py ------class TestNotificationDispatchSite:- """Pin ``send_notification_to_worker`` -> ``queue_backend.dispatch``."""-- def _make_payload(self):- """Build a minimal NotificationPayload-shaped mock.+from unstract.core.data_models import (+ ExecutionStatus,+ NotificationPayload,+ NotificationSource,+ WorkflowType,+)- The function under test only invokes ``payload.to_webhook_payload()``- and reads ``payload.pipeline_id`` (for log output). Anything else- about the payload object is irrelevant to dispatch behaviour.- """- payload = MagicMock()- payload.to_webhook_payload.return_value = {"event": "test_event", "id": 42}- payload.pipeline_id = "pipe-001"- return payload-- def test_dispatch_task_name_and_queue(self):- from shared.patterns.notification.helper import send_notification_to_worker-- with patch("shared.patterns.notification.helper.dispatch") as mock_dispatch:- send_notification_to_worker(- url="https://example.com/hook",- payload=self._make_payload(),- auth_type="NONE",- auth_key=None,- auth_header=None,- )+# --- Site 1: shared/patterns/notification/helper.py (HTTP buffer enqueue) ---- mock_dispatch.assert_called_once()- call = mock_dispatch.call_args- assert call.args[0] == "send_webhook_notification"- assert call.kwargs["queue"] == "notifications"-- def test_dispatch_positional_args_layout(self):- """Positional args MUST be [url, payload_dict, headers, timeout]."""- from shared.patterns.notification.helper import send_notification_to_worker-- with patch("shared.patterns.notification.helper.dispatch") as mock_dispatch:- send_notification_to_worker(- url="https://example.com/hook",- payload=self._make_payload(),- auth_type="BEARER",- auth_key="token-abc",- auth_header=None,- )- args = mock_dispatch.call_args.kwargs["args"]- assert len(args) == 4- assert args[0] == "https://example.com/hook" # url- assert args[1] == {"event": "test_event", "id": 42} # payload_dict- assert args[2]["Authorization"] == "Bearer token-abc" # headers- assert args[3] == 10 # timeout (hard-coded)+class TestNotificationDispatchSite:+ """Pin the worker notification path -> backend buffer-enqueue HTTP contract.- def test_dispatch_kwargs_layout(self):- """Kwargs MUST contain max_retries, retry_delay, platform."""- from shared.patterns.notification.helper import send_notification_to_worker-- with patch("shared.patterns.notification.helper.dispatch") as mock_dispatch:- send_notification_to_worker(- url="https://example.com/hook",- payload=self._make_payload(),- auth_type="NONE",- auth_key=None,- auth_header=None,- max_retries=5,- platform="SLACK",- )+ UN-3056 made the callback worker model-free: instead of dispatching a+ Celery task, ``_route_notification`` -> ``_enqueue_to_buffer`` POSTs each+ event to the backend, which owns the NotificationBuffer + clubbed send.+ """- kwargs = mock_dispatch.call_args.kwargs["kwargs"]- assert kwargs == {- "max_retries": 5,- "retry_delay": 10,- "platform": "SLACK",+ def _make_notification(self, notification_type="WEBHOOK", platform="API"):+ return {+ "id": "notif-001",+ "notification_type": notification_type,+ "platform": platform,}- def test_dispatch_returns_true_on_success(self):- from shared.patterns.notification.helper import send_notification_to_worker+ def _make_payload(self):+ """A real NotificationPayload so enum -> value coercion is exercised."""+ return NotificationPayload.from_execution_status(+ pipeline_id="pipe-001",+ pipeline_name="char-test-pipeline",+ execution_status=ExecutionStatus.ERROR,+ workflow_type=WorkflowType.API,+ source=NotificationSource.CALLBACK_WORKER,+ execution_id="exec-123",+ error_message="boom",+ total_files=3,+ successful_files=1,+ failed_files=2,+ )- with patch("shared.patterns.notification.helper.dispatch"):- result = send_notification_to_worker(- url="https://example.com/hook",- payload=self._make_payload(),- auth_type="NONE",- auth_key=None,- auth_header=None,+ def test_enqueue_posts_to_buffer_endpoint(self):+ """``_enqueue_to_buffer`` MUST POST to the buffer endpoint, timeout=10."""+ api_client = MagicMock()+ _enqueue_to_buffer(api_client, self._make_notification(), self._make_payload())++ api_client._make_request.assert_called_once()+ call = api_client._make_request.call_args+ assert call.kwargs["method"] == "POST"+ assert call.kwargs["endpoint"] == ENQUEUE_BUFFER_ENDPOINT+ assert call.kwargs["timeout"] == 10++ def test_enqueue_payload_shape(self):+ """The enqueued ``data`` MUST carry the full per-event contract the+ backend buffer + clubbed renderer rely on."""+ api_client = MagicMock()+ _enqueue_to_buffer(api_client, self._make_notification(), self._make_payload())++ data = api_client._make_request.call_args.kwargs["data"]+ assert set(data) == {+ "notification_id",+ "type",+ "execution_id",+ "pipeline_id",+ "pipeline_name",+ "status",+ "error_message",+ "platform",+ "timestamp",+ "additional_data",+ }+ assert data["notification_id"] == "notif-001"+ assert data["pipeline_id"] == "pipe-001"+ assert data["pipeline_name"] == "char-test-pipeline"+ assert data["execution_id"] == "exec-123"+ assert data["platform"] == "API"+ # Enums are coerced to their string values, not passed as objects.+ assert data["type"] == WorkflowType.API.value+ assert isinstance(data["status"], str)+ assert isinstance(data["additional_data"], dict)++ def test_enqueue_raises_on_request_failure(self):+ """A transport failure MUST propagate out of ``_enqueue_to_buffer`` so+ the router can count the drop (it is the only failure signal)."""+ api_client = MagicMock()+ api_client._make_request.side_effect = RuntimeError("backend down")++ with pytest.raises(RuntimeError):+ _enqueue_to_buffer(+ api_client, self._make_notification(), self._make_payload())- assert result is True-- def test_helper_swallows_dispatch_exception(self):- """The helper's try/except contract: any exception from ``dispatch``- is caught and surfaced as ``False``. Patches the helper-side seam,- so this is purely a Python-level error-handling assertion."""- from shared.patterns.notification.helper import send_notification_to_worker-- with patch("shared.patterns.notification.helper.dispatch") as mock_dispatch:- mock_dispatch.side_effect = RuntimeError("broker down")- result = send_notification_to_worker(- url="https://example.com/hook",- payload=self._make_payload(),- auth_type="NONE",- auth_key=None,- auth_header=None,- )+ def test_route_skips_non_webhook(self):+ """Non-WEBHOOK notifications MUST NOT be enqueued."""+ api_client = MagicMock()+ _route_notification(+ api_client,+ self._make_notification(notification_type="EMAIL"),+ self._make_payload(),+ )+ api_client._make_request.assert_not_called()++ def test_route_skips_missing_notification_type(self):+ """A malformed notification with no notification_type key is skipped —+ ``.get()`` returns None, which fails the WEBHOOK check (no KeyError)."""+ api_client = MagicMock()+ notification = {"id": "notif-001", "platform": "API"} # no notification_type+ _route_notification(api_client, notification, self._make_payload())+ api_client._make_request.assert_not_called()++ def test_route_enqueues_webhook(self):+ """WEBHOOK notifications MUST reach the buffer endpoint."""+ api_client = MagicMock()+ _route_notification(api_client, self._make_notification(), self._make_payload())++ api_client._make_request.assert_called_once()+ assert (+ api_client._make_request.call_args.kwargs["endpoint"]+ == ENQUEUE_BUFFER_ENDPOINT+ )- assert result is False-- def test_substrate_failure_surfaces_as_false(self):- """End-to-end seam → substrate failure path.-- Leaves ``dispatch`` itself unpatched and patches the substrate- boundary (``queue_backend.dispatch.current_app``). Models a real- broker outage: ``send_task`` raises ``ConnectionError``,- ``dispatch`` propagates, the helper's ``except`` catches it,- return value is ``False``. Complements the helper-side test- above — together they exercise the full failure path without- either side being trivially mocked."""- from shared.patterns.notification.helper import send_notification_to_worker-- with patch("queue_backend.dispatch.current_app") as mock_app:- mock_app.send_task.side_effect = ConnectionError("broker down")- result = send_notification_to_worker(- url="https://example.com/hook",- payload=self._make_payload(),- auth_type="NONE",- auth_key=None,- auth_header=None,- )+ def test_route_swallows_enqueue_failure(self):+ """An enqueue failure MUST NOT abort the caller's loop — sibling+ notifications still get their turn. ``_route_notification`` is the+ path's final swallow point."""+ api_client = MagicMock()+ api_client._make_request.side_effect = RuntimeError("backend down")- assert result is False- mock_app.send_task.assert_called_once()+ # Must not raise.+ _route_notification(api_client, self._make_notification(), self._make_payload())+ api_client._make_request.assert_called_once()# --- Site 2: scheduler/tasks.py ---@@ -367,5 +367,108 @@ class TestDispatchSiteInventory:assert seam.exists(), f"Canonical dispatch seam missing: {seam}"+# --- Site 1b: early-failure dispatch (notify_execution_failure) ---+++class TestEarlyFailureNotification:+ """Pin the early-failure notification path (UN-3056).++ Runs that fail before file processing (missing-tool / tool-validation /+ source-setup errors) never reach the callback's+ ``handle_status_notifications``, so the general worker calls+ ``notify_execution_failure`` on its failure branch. It must resolve the+ pipeline name/type from the backend and dispatch a terminal ERROR status;+ if pipeline data can't be fetched it must skip rather than raise.+ """++ def _api_client(self, *, success=True, data="default"):+ api_client = MagicMock()+ resp = MagicMock()+ resp.success = success+ resp.data = (+ {"pipeline": {"pipeline_name": "etl-early-fail", "pipeline_type": "ETL"}}+ if data == "default"+ else data+ )+ api_client.get_pipeline_data.return_value = resp+ return api_client++ def test_dispatches_terminal_error_with_resolved_identity(self):+ from shared.patterns.notification import helper as notif_helper++ api_client = self._api_client()+ with patch.object(notif_helper, "handle_status_notifications") as mock_dispatch:+ notif_helper.notify_execution_failure(+ api_client=api_client,+ pipeline_id="pipe-1",+ execution_id="exec-1",+ organization_id="org-1",+ error_message="Tool does not exist in registry: text_extractor",+ )++ api_client.get_pipeline_data.assert_called_once_with(+ pipeline_id="pipe-1", check_active=False+ )+ mock_dispatch.assert_called_once()+ kwargs = mock_dispatch.call_args.kwargs+ assert kwargs["pipeline_id"] == "pipe-1"+ assert kwargs["status"] == ExecutionStatus.ERROR.value+ assert kwargs["pipeline_name"] == "etl-early-fail"+ assert kwargs["pipeline_type"] == "ETL"+ assert kwargs["execution_id"] == "exec-1"+ assert kwargs["organization_id"] == "org-1"+ assert "text_extractor" in kwargs["error_message"]++ def test_skips_when_pipeline_data_unavailable(self):+ from shared.patterns.notification import helper as notif_helper++ api_client = self._api_client(success=False, data=None)+ with patch.object(notif_helper, "handle_status_notifications") as mock_dispatch:+ notif_helper.notify_execution_failure(+ api_client=api_client,+ pipeline_id="pipe-1",+ execution_id="exec-1",+ organization_id="org-1",+ )++ mock_dispatch.assert_not_called()++ def test_resolves_flat_pipeline_shape(self):+ # Older backend builds return the record flat (no "pipeline" envelope).+ from shared.patterns.notification import helper as notif_helper++ api_client = self._api_client(+ data={"pipeline_name": "flat-etl", "pipeline_type": "TASK"}+ )+ with patch.object(notif_helper, "handle_status_notifications") as mock_dispatch:+ notif_helper.notify_execution_failure(+ api_client=api_client,+ pipeline_id="pipe-1",+ execution_id="exec-1",+ organization_id="org-1",+ )++ kwargs = mock_dispatch.call_args.kwargs+ assert kwargs["pipeline_name"] == "flat-etl"+ assert kwargs["pipeline_type"] == "TASK"++ def test_does_not_raise_when_resolution_errors(self):+ # A backend hiccup while resolving identity must not bubble out of the+ # worker's failure handler (it is best-effort, post-status-update).+ from shared.patterns.notification import helper as notif_helper++ api_client = MagicMock()+ api_client.get_pipeline_data.side_effect = RuntimeError("backend down")+ with patch.object(notif_helper, "handle_status_notifications") as mock_dispatch:+ notif_helper.notify_execution_failure(+ api_client=api_client,+ pipeline_id="pipe-1",+ execution_id="exec-1",+ organization_id="org-1",+ )++ mock_dispatch.assert_not_called()++if __name__ == "__main__":pytest.main([__file__, "-v"])diff --git a/workers/tests/test_queue_backend_seam.py b/workers/tests/test_queue_backend_seam.pyindex 8cd827cc1..86b73fe0a 100644--- a/workers/tests/test_queue_backend_seam.py+++ b/workers/tests/test_queue_backend_seam.py@@ -7,9 +7,9 @@ proved to preserve the Celery default path.Two layers:1. **dispatch()** must produce the same ``current_app.send_task`` call- as the raw idiom used at the two existing dispatch sites:- ``shared/patterns/notification/helper.py::send_notification_to_worker``- and ``scheduler/tasks.py::_execute_scheduled_workflow``.+ as the raw Celery idiom — checked against representative+ ``send_webhook_notification`` and ``async_execute_bin``+ (``scheduler/tasks.py::_execute_scheduled_workflow``) shapes.2. **@worker_task** must register a task with the Celery app so thatfunctions decorated with it behave identically to ones decorated@@ -100,9 +100,13 @@ class TestDispatchEquivalence:assert result is sentineldef test_matches_notification_helper_shape(self):- """Output mirrors the raw send_task at ``send_notification_to_worker``.+ """Output mirrors the raw ``send_task`` shape for a notification task.- Reference call from helper (paraphrased):+ The callback notification path itself migrated to an HTTP+ buffer-enqueue in UN-3056; this keeps a representative+ ``send_webhook_notification`` call as a seam-equivalence reference.++ Reference call shape (paraphrased):current_app.send_task("send_webhook_notification",