Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(workflows): route the proposal lifecycle through the facade (#110630)

Harley Alexanderffab59e58d4c
diff --git a/products/workflows/backend/facade/contracts.py b/products/workflows/backend/facade/contracts.py
index 2410f4d53a26..708eb3bcb6cc 100644
--- a/products/workflows/backend/facade/contracts.py
+++ b/products/workflows/backend/facade/contracts.py
@@ -11,6 +11,7 @@ from products.workflows.backend.facade.enums import (
HogFlowScheduleStatus,
HogFlowTemplateExitCondition,
HogFlowTemplateScope,
+ WorkflowProposalStatus,
)
if TYPE_CHECKING:
@@ -382,6 +383,32 @@ class ProposalChanges:
conflicts: list[str]
+@frozen
+class WorkflowProposalRecord:
+ """A change to a workflow that an agent proposed, and how a human resolved it."""
+
+ id: UUID
+ title: str
+ rationale: str
+ content: dict[str, Any]
+ evidence: dict[str, Any]
+ step_id: str | None
+ base_version: int
+ status: WorkflowProposalStatus
+ source_id: str | None
+ created_at: datetime
+ resolved_at: datetime | None
+ resolved_by: "User | None"
+ applied_version: int | None
+
+
+@frozen
+class CreatedWorkflowProposal:
+ proposal: WorkflowProposalRecord
+ # False when a retry with the same source_id returned the proposal it already made.
+ created: bool
+
+
@frozen
class EditedEmailDesign:
design: dict[str, Any]
diff --git a/products/workflows/backend/facade/enums.py b/products/workflows/backend/facade/enums.py
index af215e1a8520..a31a0b1f5b2f 100644
--- a/products/workflows/backend/facade/enums.py
+++ b/products/workflows/backend/facade/enums.py
@@ -47,3 +47,10 @@ class HogFlowScheduleStatus(LabeledStrEnum):
ACTIVE = "active"
PAUSED = "paused"
COMPLETED = "completed" # RRULE exhausted (COUNT/UNTIL reached)
+
+
+class WorkflowProposalStatus(LabeledStrEnum):
+ SUGGESTED = "suggested", "Suggested"
+ APPROVED = "approved", "Approved"
+ REJECTED = "rejected", "Rejected"
+ APPLIED = "applied", "Applied"
diff --git a/products/workflows/backend/facade/proposals.py b/products/workflows/backend/facade/proposals.py
index 0a1d718e9a4e..d2e1131a382a 100644
--- a/products/workflows/backend/facade/proposals.py
+++ b/products/workflows/backend/facade/proposals.py
@@ -4,10 +4,17 @@ from products.workflows.backend.metrics import HOG_FLOW_VERSION_APP_SOURCE
from products.workflows.backend.services.workflow_proposals import (
PROPOSAL_MERGE_BY_ID_FIELDS,
as_the_serializer_stores_it,
+ count_proposals,
+ create_proposal,
+ get_proposal,
+ get_proposal_by_source_id,
is_optimization_enabled,
+ list_proposals,
+ lock_proposal,
merge_proposal_content,
proposal_conflicts,
proposal_outcome,
+ resolve_proposal,
set_optimization_enabled,
staged_proposal_changes,
target_metric_in,
@@ -19,10 +26,17 @@ __all__ = [
"HOG_FLOW_VERSION_APP_SOURCE",
"PROPOSAL_MERGE_BY_ID_FIELDS",
"as_the_serializer_stores_it",
+ "count_proposals",
+ "create_proposal",
+ "get_proposal",
+ "get_proposal_by_source_id",
"is_optimization_enabled",
+ "list_proposals",
+ "lock_proposal",
"merge_proposal_content",
"proposal_conflicts",
"proposal_outcome",
+ "resolve_proposal",
"set_optimization_enabled",
"staged_proposal_changes",
"target_metric_in",
diff --git a/products/workflows/backend/models/workflow_proposal.py b/products/workflows/backend/models/workflow_proposal.py
index 83a79cb18fbb..71dc6ad1c417 100644
--- a/products/workflows/backend/models/workflow_proposal.py
+++ b/products/workflows/backend/models/workflow_proposal.py
@@ -5,6 +5,8 @@ from django.db import models
from posthog.models.scoping.root_mixin import TeamScopedRootMixin
from posthog.models.utils import UUIDModel
+from products.workflows.backend.facade.enums import WorkflowProposalStatus
+
class WorkflowProposal(TeamScopedRootMixin, UUIDModel):
"""A change to a workflow that an agent proposes and a human resolves.
@@ -17,11 +19,7 @@ class WorkflowProposal(TeamScopedRootMixin, UUIDModel):
row it already made.
"""
- class Status(models.TextChoices):
- SUGGESTED = "suggested", "Suggested"
- APPROVED = "approved", "Approved"
- REJECTED = "rejected", "Rejected"
- APPLIED = "applied", "Applied"
+ Status = WorkflowProposalStatus
OPEN_STATUSES = (Status.SUGGESTED,)
@@ -80,7 +78,7 @@ class WorkflowProposal(TeamScopedRootMixin, UUIDModel):
),
)
- status = models.CharField(max_length=20, choices=Status, default=Status.SUGGESTED)
+ status = models.CharField(max_length=20, choices=Status.choices, default=Status.SUGGESTED.value)
source_id = models.CharField(
max_length=200,
null=True,
diff --git a/products/workflows/backend/presentation/views/hog_flow.py b/products/workflows/backend/presentation/views/hog_flow.py
index 4aa40b09c371..5093e1a12acb 100644
--- a/products/workflows/backend/presentation/views/hog_flow.py
+++ b/products/workflows/backend/presentation/views/hog_flow.py
@@ -13,7 +13,7 @@ from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
from django.conf import settings
from django.core.cache import cache
from django.core.signing import BadSignature, SignatureExpired, TimestampSigner
-from django.db import IntegrityError, models, transaction
+from django.db import models, transaction
from django.db.models import Count, F, OuterRef, Q, QuerySet, Subquery, Value
from django.db.models.expressions import RawSQL
from django.db.models.functions import Coalesce
@@ -140,6 +140,7 @@ from products.workflows.backend.facade.contracts import (
WorkflowBatchJobNotFound,
WorkflowDraftChanged,
WorkflowDraftExists,
+ WorkflowProposalRecord,
WorkflowRevisionNotFound,
WorkflowRevisionSummary,
WorkflowScheduleNotFound,
@@ -159,16 +160,23 @@ from products.workflows.backend.facade.email_health import (
resume_email_sending,
team_email_sending_allowance,
)
-from products.workflows.backend.facade.enums import HogFlowBatchJobState, HogFlowScheduleStatus
+from products.workflows.backend.facade.enums import HogFlowBatchJobState, HogFlowScheduleStatus, WorkflowProposalStatus
from products.workflows.backend.facade.message_assets import fetch_message_asset_html, fetch_message_assets
from products.workflows.backend.facade.proposals import (
HOG_FLOW_VERSION_APP_SOURCE,
PROPOSAL_MERGE_BY_ID_FIELDS,
as_the_serializer_stores_it,
+ count_proposals,
+ create_proposal,
+ get_proposal,
+ get_proposal_by_source_id,
is_optimization_enabled,
+ list_proposals,
+ lock_proposal,
merge_proposal_content,
proposal_conflicts,
proposal_outcome,
+ resolve_proposal,
set_optimization_enabled,
staged_proposal_changes,
target_metric_in,
@@ -3594,10 +3602,29 @@ class HogFlowOptimizationSerializer(serializers.Serializer):
enabled = serializers.BooleanField(help_text="Whether PostHog may suggest changes to this workflow.")
-class WorkflowProposalSerializer(serializers.ModelSerializer):
- resolved_by = UserBasicSerializer(read_only=True, allow_null=True)
+class WorkflowProposalSerializer(serializers.Serializer):
+ id = serializers.UUIDField(read_only=True)
+ title = serializers.CharField(read_only=True, help_text="Short summary of the proposed change.")
+ rationale = serializers.CharField(read_only=True, help_text="Why the producer thinks this change is worth making.")
content = WorkflowProposalContentField(read_only=True)
evidence = WorkflowProposalEvidenceField(read_only=True)
+ step_id = serializers.CharField(
+ read_only=True,
+ allow_null=True,
+ help_text=(
+ "The workflow step this is about. Set for a change to one step: the evidence and the "
+ "outcome then read that step's metrics, so a change to one email in a sequence is not "
+ "measured against the rest. Null only for a change that spans the workflow, such as its "
+ "exit condition or a step being taken out, which is measured on the workflow's own numbers."
+ ),
+ )
+ base_version = serializers.IntegerField(
+ read_only=True,
+ help_text=(
+ "Live workflow version this was authored against. Approving compares the steps and fields "
+ "this changes against that version to tell whether somebody else already changed them."
+ ),
+ )
is_stale = serializers.SerializerMethodField(
help_text=(
"Whether approving this would undo an edit made since it was proposed. False while the "
@@ -3605,37 +3632,29 @@ class WorkflowProposalSerializer(serializers.ModelSerializer):
)
)
- class Meta:
- model = WorkflowProposal
- fields = [
- "id",
- "title",
- "rationale",
- "content",
- "evidence",
- "step_id",
- "base_version",
- "is_stale",
- "status",
- "source_id",
- "created_at",
- "resolved_at",
- "resolved_by",
- "applied_version",
- ]
- read_only_fields = fields
+ status = serializers.ChoiceField(choices=WorkflowProposalStatus.choices, read_only=True)
+ source_id = serializers.CharField(
+ read_only=True,
+ allow_null=True,
+ help_text="Stable id of the producing agent run or finding, e.g. 'run:<run id>:finding:<finding id>'.",
+ )
+ created_at = serializers.DateTimeField(read_only=True)
+ resolved_at = serializers.DateTimeField(read_only=True, allow_null=True)
+ resolved_by = UserBasicSerializer(read_only=True, allow_null=True)
+ applied_version = serializers.IntegerField(
+ read_only=True, allow_null=True, help_text="Workflow version the approved change went live as."
+ )
@extend_schema_field(serializers.BooleanField)
- def get_is_stale(self, proposal: WorkflowProposal) -> bool:
- if (proposal.hog_flow.version or 0) <= proposal.base_version:
+ def get_is_stale(self, proposal: WorkflowProposalRecord) -> bool:
+ hog_flow = self.context["hog_flow"]
+ if (hog_flow.version or 0) <= proposal.base_version:
return False
# One revision read per base version, shared across the page.
cache = self.context.setdefault("proposal_conflicts", {})
- key = (proposal.hog_flow_id, proposal.base_version, json.dumps(proposal.content, sort_keys=True))
+ key = (hog_flow.pk, proposal.base_version, json.dumps(proposal.content, sort_keys=True))
if key not in cache:
- cache[key] = proposal_conflicts(
- team_id=proposal.team_id, hog_flow_id=proposal.hog_flow_id, proposal_id=proposal.id
- )
+ cache[key] = proposal_conflicts(team_id=hog_flow.team_id, hog_flow_id=hog_flow.pk, proposal_id=proposal.id)
return bool(cache[key])
@@ -4034,6 +4053,19 @@ class _RevisionPages:
return list_revisions(self.hog_flow_id, offset=page.start or 0, limit=page.stop - (page.start or 0))
+class _ProposalPages:
+ def __init__(self, hog_flow_id: uuid_mod.UUID, status: str | None) -> None:
+ self.hog_flow_id = hog_flow_id
+ self.status = status
+
+ def count(self) -> int:
+ return count_proposals(hog_flow_id=self.hog_flow_id, status=self.status)
+
+ def __getitem__(self, page: slice) -> list[WorkflowProposalRecord]:
+ offset = page.start or 0
+ return list_proposals(hog_flow_id=self.hog_flow_id, status=self.status, offset=offset, limit=page.stop - offset)
+
+
class HogFlowPagination(LimitOffsetPagination):
default_limit = 100
max_limit = 500
@@ -5429,7 +5461,7 @@ class HogFlowViewSet(
"status",
OpenApiTypes.STR,
description="Only return proposals in this status (suggested, approved, rejected, applied).",
- enum=[choice.value for choice in WorkflowProposal.Status],
+ enum=[choice.value for choice in WorkflowProposalStatus],
)
],
responses={200: WorkflowProposalSerializer(many=True)},
@@ -5450,19 +5482,14 @@ class HogFlowViewSet(
# DRF routes HEAD to the GET handler, and the scope gate reads it as a read.
if request.method in ("GET", "HEAD"):
requested_status = request.query_params.get("status")
- if requested_status and requested_status not in WorkflowProposal.Status.values:
+ if requested_status and requested_status not in WorkflowProposalStatus.values:
raise exceptions.ValidationError(
- {"status": f"Must be one of: {', '.join(WorkflowProposal.Status.values)}."}
+ {"status": f"Must be one of: {', '.join(WorkflowProposalStatus.values)}."}
)
- # Applied ones order by the version that shipped them; the rest read as a queue, newest first.
- applied_only = requested_status == WorkflowProposal.Status.APPLIED
- ordering = ("-applied_version", "-created_at") if applied_only else ("-created_at",)
- queryset = WorkflowProposal.objects.filter(hog_flow=instance).order_by(*ordering)
- if requested_status:
- queryset = queryset.filter(status=requested_status)
- queryset = queryset.select_related("resolved_by", "hog_flow")
- page = self.paginate_queryset(queryset)
- return self.get_paginated_response(WorkflowProposalSerializer(page, many=True).data)
+ page = self.paginate_queryset(cast(Sequence[Any], _ProposalPages(instance.pk, requested_status or None)))
+ return self.get_paginated_response(
+ WorkflowProposalSerializer(page, many=True, context={"hog_flow": instance}).data
+ )
param_serializer = WorkflowProposalCreateSerializer(data=request.data)
param_serializer.is_valid(raise_exception=True)
@@ -5471,11 +5498,11 @@ class HogFlowViewSet(
source_id = params.get("source_id") or None
# A retry names the suggestion it already made, which is still in someone's queue whatever the switch says now.
- retry_of = (
- WorkflowProposal.objects.filter(hog_flow=instance, source_id=source_id).first() if source_id else None
- )
+ retry_of = get_proposal_by_source_id(hog_flow_id=instance.pk, source_id=source_id) if source_id else None
if retry_of:
- return Response(WorkflowProposalSerializer(retry_of).data, status=status.HTTP_200_OK)
+ return Response(
+ WorkflowProposalSerializer(retry_of, context={"hog_flow": instance}).data, status=status.HTTP_200_OK
+ )
# A version the workflow has not reached names nothing, and the outcome read spans versions.
if params["base_version"] > instance.version:
@@ -5542,8 +5569,8 @@ class HogFlowViewSet(
if measured is not None:
evidence["measured"] = measured
- proposal = WorkflowProposal(
- hog_flow=instance,
+ created = create_proposal(
+ hog_flow_id=instance.pk,
title=params["title"],
rationale=params["rationale"],
content=content,
@@ -5552,23 +5579,19 @@ class HogFlowViewSet(
base_version=params["base_version"],
source_id=source_id,
)
- try:
- with transaction.atomic():
- proposal.save()
- except IntegrityError:
- # A concurrent create with the same source_id landed between the read and this save.
- existing = (
- WorkflowProposal.objects.filter(hog_flow=instance, source_id=source_id).first() if source_id else None
+ proposal = created.proposal
+ if not created.created:
+ return Response(
+ WorkflowProposalSerializer(proposal, context={"hog_flow": instance}).data, status=status.HTTP_200_OK
)
- if existing is None:
- raise
- return Response(WorkflowProposalSerializer(existing).data, status=status.HTTP_200_OK)
self._report_workflow_action(
"hog_flow_proposal_created",
instance,
{"proposal_id": str(proposal.id)},
)
- return Response(WorkflowProposalSerializer(proposal).data, status=status.HTTP_201_CREATED)
+ return Response(
+ WorkflowProposalSerializer(proposal, context={"hog_flow": instance}).data, status=status.HTTP_201_CREATED
+ )
@extend_schema(
parameters=[
@@ -5581,18 +5604,16 @@ class HogFlowViewSet(
self._require_self_optimising_enabled()
instance = self.get_object()
proposal = self._get_proposal_or_404(instance, proposal_id)
- return Response(WorkflowProposalSerializer(proposal).data)
+ return Response(WorkflowProposalSerializer(proposal, context={"hog_flow": instance}).data)
- def _get_proposal_or_404(self, hog_flow: HogFlow, proposal_id: Optional[str]) -> WorkflowProposal:
+ def _get_proposal_or_404(self, hog_flow: HogFlow, proposal_id: Optional[str]) -> WorkflowProposalRecord:
parsed = _parse_uuid_or_none(proposal_id)
if parsed is None:
raise exceptions.NotFound("No such suggestion for this workflow.")
- try:
- return WorkflowProposal.objects.select_related("resolved_by", "hog_flow").get(
- team_id=self.team_id, hog_flow_id=hog_flow.pk, id=parsed
- )
- except WorkflowProposal.DoesNotExist:
+ proposal = get_proposal(team_id=self.team_id, hog_flow_id=hog_flow.pk, proposal_id=parsed)
+ if proposal is None:
raise exceptions.NotFound("No such suggestion for this workflow.")
+ return proposal
@extend_schema(
parameters=[
@@ -5621,13 +5642,13 @@ class HogFlowViewSet(
locked = HogFlow.objects.select_for_update().get(pk=instance.pk)
proposal = self._get_proposal_or_404(locked, proposal_id)
# The row lock serializes concurrent approvals; the second sees what the first wrote.
- locked_proposal = WorkflowProposal.objects.select_for_update().get(pk=proposal.pk)
- if locked_proposal.status != WorkflowProposal.Status.SUGGESTED:
+ locked_proposal = lock_proposal(team_id=self.team_id, proposal_id=proposal.id)
+ if locked_proposal.status != WorkflowProposalStatus.SUGGESTED:
raise ProposalAlreadyResolvedError()
if locked.draft and not param_serializer.validated_data["overwrite"]:
raise DraftExistsError()
staged = staged_proposal_changes(
- team_id=locked.team_id, hog_flow_id=locked.pk, proposal_id=locked_proposal.pk
+ team_id=locked.team_id, hog_flow_id=locked.pk, proposal_id=locked_proposal.id
)
if staged.conflicts:
raise ProposalOutOfDateError(staged.conflicts)
@@ -5658,15 +5679,17 @@ class HogFlowViewSet(
# The new draft replaces what was staged; an earlier approval stays only if the draft still carries it.
unstage_workflow_proposals(team_id=locked.team_id, hog_flow_id=locked.pk)
- locked_proposal.status = WorkflowProposal.Status.APPROVED
- locked_proposal.resolved_at = timezone.now()
- locked_proposal.resolved_by = request.user if request.user.is_authenticated else None
- locked_proposal.save(update_fields=["status", "resolved_at", "resolved_by"])
+ locked_proposal = resolve_proposal(
+ team_id=self.team_id,
+ proposal_id=locked_proposal.id,
+ status=WorkflowProposalStatus.APPROVED,
+ resolved_by_id=request.user.pk if request.user.is_authenticated else None,
+ )
log_activity_from_viewset(self, locked, activity="proposal_approved", name=locked.name, previous=before_update)
self._emit_resource_edited(locked)
self._report_workflow_action("hog_flow_proposal_approved", locked, {"proposal_id": str(locked_proposal.id)})
- return Response(WorkflowProposalSerializer(locked_proposal).data)
+ return Response(WorkflowProposalSerializer(locked_proposal, context={"hog_flow": locked}).data)
@extend_schema(
parameters=[
@@ -5698,7 +5721,7 @@ class HogFlowViewSet(
tag_queries(product=ProductKey.WORKFLOWS, feature=Feature.QUERY)
return Response(
WorkflowProposalOutcomeSerializer(
- proposal_outcome(team_id=self.team_id, hog_flow_id=instance.pk, proposal_id=proposal.pk)
+ proposal_outcome(team_id=self.team_id, hog_flow_id=instance.pk, proposal_id=proposal.id)
).data
)
@@ -5752,17 +5775,19 @@ class HogFlowViewSet(
instance = self.get_object()
with transaction.atomic():
proposal = self._get_proposal_or_404(instance, proposal_id)
- locked_proposal = WorkflowProposal.objects.select_for_update().get(pk=proposal.pk)
- if locked_proposal.status != WorkflowProposal.Status.SUGGESTED:
+ locked_proposal = lock_proposal(team_id=self.team_id, proposal_id=proposal.id)
+ if locked_proposal.status != WorkflowProposalStatus.SUGGESTED:
raise ProposalAlreadyResolvedError()
- locked_proposal.status = WorkflowProposal.Status.REJECTED
- locked_proposal.resolved_at = timezone.now()
- locked_proposal.resolved_by = request.user if request.user.is_authenticated else None
- locked_proposal.save(update_fields=["status", "resolved_at", "resolved_by"])
+ locked_proposal = resolve_proposal(
+ team_id=self.team_id,
+ proposal_id=locked_proposal.id,
+ status=WorkflowProposalStatus.REJECTED,
+ resolved_by_id=request.user.pk if request.user.is_authenticated else None,
+ )
log_activity_from_viewset(self, instance, activity="proposal_rejected", name=instance.name)
self._report_workflow_action("hog_flow_proposal_rejected", instance, {"proposal_id": str(locked_proposal.id)})
- return Response(WorkflowProposalSerializer(locked_proposal).data)
+ return Response(WorkflowProposalSerializer(locked_proposal, context={"hog_flow": instance}).data)
@extend_schema(request=HogFlowOptimizationSerializer, responses={200: HogFlowOptimizationSerializer})
@action(detail=True, methods=["GET", "POST"], url_path="optimization", filter_backends=[])
diff --git a/products/workflows/backend/services/workflow_proposals.py b/products/workflows/backend/services/workflow_proposals.py
index 7ad76b76046e..2e3d616ff503 100644
--- a/products/workflows/backend/services/workflow_proposals.py
+++ b/products/workflows/backend/services/workflow_proposals.py
@@ -6,9 +6,14 @@ from datetime import datetime
from typing import Any, Optional
from uuid import UUID
+from django.db import IntegrityError, transaction
+from django.db.models import QuerySet
+from django.utils import timezone
+
from posthog.api.app_metrics2 import fetch_app_metric_totals
-from products.workflows.backend.facade.contracts import ProposalChanges
+from products.workflows.backend.facade.contracts import CreatedWorkflowProposal, ProposalChanges, WorkflowProposalRecord
+from products.workflows.backend.facade.enums import WorkflowProposalStatus
from products.workflows.backend.metrics import (
GUARDRAIL_LABELS,
GUARDRAIL_METRICS,
@@ -35,6 +40,105 @@ PROPOSAL_WHOLE_LIST_FIELDS = ("edges", "variables")
PROPOSAL_MERGE_BY_ID_FIELDS = ("actions",)
+def _to_record(proposal: WorkflowProposal) -> WorkflowProposalRecord:
+ return WorkflowProposalRecord(
+ id=proposal.id,
+ title=proposal.title,
+ rationale=proposal.rationale,
+ content=proposal.content,
+ evidence=proposal.evidence,
+ step_id=proposal.step_id,
+ base_version=proposal.base_version,
+ status=WorkflowProposalStatus(proposal.status),
+ source_id=proposal.source_id,
+ created_at=proposal.created_at,
+ resolved_at=proposal.resolved_at,
+ resolved_by=proposal.resolved_by,
+ applied_version=proposal.applied_version,
+ )
+
+
+def _proposals(hog_flow_id: UUID, status: str | None) -> QuerySet[WorkflowProposal]:
+ applied_only = status == WorkflowProposal.Status.APPLIED
+ ordering = ("-applied_version", "-created_at", "-pk") if applied_only else ("-created_at", "-pk")
+ queryset = WorkflowProposal.objects.filter(hog_flow_id=hog_flow_id).order_by(*ordering)
+ if status:
+ queryset = queryset.filter(status=status)
+ return queryset
+
+
+def count_proposals(*, hog_flow_id: UUID, status: str | None) -> int:
+ return _proposals(hog_flow_id, status).count()
+
+
+def list_proposals(*, hog_flow_id: UUID, status: str | None, offset: int, limit: int) -> list[WorkflowProposalRecord]:
+ queryset = _proposals(hog_flow_id, status).select_related("resolved_by")
+ return [_to_record(proposal) for proposal in queryset[offset : offset + limit]]
+
+
+def get_proposal(*, team_id: int, hog_flow_id: UUID, proposal_id: UUID) -> WorkflowProposalRecord | None:
+ proposal = (
+ WorkflowProposal.objects.select_related("resolved_by")
+ .filter(team_id=team_id, hog_flow_id=hog_flow_id, id=proposal_id)
+ .first()
+ )
+ return _to_record(proposal) if proposal is not None else None
+
+
+def get_proposal_by_source_id(*, hog_flow_id: UUID, source_id: str) -> WorkflowProposalRecord | None:
+ proposal = WorkflowProposal.objects.filter(hog_flow_id=hog_flow_id, source_id=source_id).first()
+ return _to_record(proposal) if proposal is not None else None
+
+
+def create_proposal(
+ *,
+ hog_flow_id: UUID,
+ title: str,
+ rationale: str,
+ content: dict[str, Any],
+ evidence: dict[str, Any],
+ step_id: str | None,
+ base_version: int,
+ source_id: str | None,
+) -> CreatedWorkflowProposal:
+ proposal = WorkflowProposal(
+ hog_flow_id=hog_flow_id,
+ title=title,
+ rationale=rationale,
+ content=content,
+ evidence=evidence,
+ step_id=step_id,
+ base_version=base_version,
+ source_id=source_id,
+ )
+ try:
+ with transaction.atomic():
+ proposal.save()
+ except IntegrityError:
+ existing = (
+ WorkflowProposal.objects.filter(hog_flow_id=hog_flow_id, source_id=source_id).first() if source_id else None
+ )
+ if existing is None:
+ raise
+ return CreatedWorkflowProposal(proposal=_to_record(existing), created=False)
+ return CreatedWorkflowProposal(proposal=_to_record(proposal), created=True)
+
+
+def lock_proposal(*, team_id: int, proposal_id: UUID) -> WorkflowProposalRecord:
+ return _to_record(WorkflowProposal.objects.select_for_update().get(team_id=team_id, id=proposal_id))
+
+
+def resolve_proposal(
+ *, team_id: int, proposal_id: UUID, status: WorkflowProposalStatus, resolved_by_id: int | None
+) -> WorkflowProposalRecord:
+ proposal = WorkflowProposal.objects.get(team_id=team_id, id=proposal_id)
+ proposal.status = status
+ proposal.resolved_at = timezone.now()
+ proposal.resolved_by_id = resolved_by_id
+ proposal.save(update_fields=["status", "resolved_at", "resolved_by"])
+ return _to_record(proposal)
+
+
# How far past the applied version the after side will look for versions that kept the change.
OUTCOME_VERSION_LIMIT = 20