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.

fix(legal-documents): decouple signature from PDF archival (#82337)

posthog[bot]6d30e85877ab
diff --git a/posthog/settings/celery.py b/posthog/settings/celery.py
index bdec526944b0..2a3b8f440c1f 100644
--- a/posthog/settings/celery.py
+++ b/posthog/settings/celery.py
@@ -26,6 +26,7 @@ CELERY_IMPORTS: list[str] = [
# Not a `<app>/tasks.py`, so autodiscovery walks past it — the app package holds a `tasks/`
# namespace package instead, and importing that doesn't reach the module inside.
"products.tasks.backend.tasks.tasks",
+ "products.legal_documents.backend.tasks.tasks",
]
CELERY_BROKER_URL = REDIS_URL # celery connects to redis
CELERY_BEAT_MAX_LOOP_INTERVAL = 30 # sleep max 30sec before checking for new periodic events
diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.py
index 6e2c6e111403..af5151356fc1 100644
--- a/posthog/tasks/scheduled.py
+++ b/posthog/tasks/scheduled.py
@@ -94,6 +94,7 @@ from products.feature_flags.backend.tasks import (
refresh_expiring_flags_cache_entries,
sync_cross_region_flags_task,
)
+from products.legal_documents.backend.facade.tasks import reconcile_pending_legal_documents
from products.logs.backend.facade.tasks import logs_alert_events_cleanup_task
from products.pulse.backend.tasks import mark_stale_pulse_briefs_failed
from products.reminders.backend.tasks import process_due_reminders
@@ -700,6 +701,16 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:
name="process due reminders",
)
+ # Poll PandaDoc for legal documents we still think are unsigned and archive
+ # any signed PDFs that missed their webhook — the safety net that recovers
+ # dropped completion webhooks and the current signed-but-stuck backlog.
+ add_periodic_task_with_expiry(
+ sender,
+ crontab(minute="*/15"),
+ reconcile_pending_legal_documents.s(),
+ name="reconcile pending legal documents",
+ )
+
# Reconcile pulse briefs stranded in GENERATING by an externally-terminated workflow.
add_periodic_task_with_expiry(
sender,
diff --git a/products/legal_documents/backend/admin.py b/products/legal_documents/backend/admin.py
index 57560541949f..cae4bfd5ad74 100644
--- a/products/legal_documents/backend/admin.py
+++ b/products/legal_documents/backend/admin.py
@@ -208,8 +208,10 @@ class LegalDocumentAdmin(admin.ModelAdmin):
return
# Add path: row + S3 upload happen together so we never leave a row
- # pointing at a missing PDF (and never leave a PDF without a row).
+ # pointing at a missing PDF (and never leave a PDF without a row). The
+ # PDF is written synchronously below, so it's archived from the start.
obj.status = LegalDocument.Status.SIGNED
+ obj.signed_pdf_stored = True
obj.created_by = request.user if request.user.is_authenticated else None
try:
with transaction.atomic():
@@ -316,10 +318,10 @@ class LegalDocumentAdmin(admin.ModelAdmin):
@admin.display(description="Signed PDF")
def download_link(self, document: LegalDocument) -> str | SafeString:
- # The PDF only exists once the row is signed (PandaDoc-signed rows get
- # the file via the completion webhook; admin-uploaded rows write it
- # synchronously on save). Hide the link until there's something to fetch.
- if document.status != LegalDocument.Status.SIGNED:
+ # The PDF only exists once the archive job has stored it. A row can be
+ # `signed` a beat before that lands, so gate on the stored flag, not on
+ # status, or the link would 404.
+ if not document.signed_pdf_stored:
return "—"
url = f"/api/organizations/{document.organization_id}/legal_documents/{document.id}/download"
return format_html('<a href="{}" target="_blank" rel="noopener">Download PDF</a>', url)
@@ -355,7 +357,9 @@ class LegalDocumentInline(admin.TabularInline):
@admin.display(description="Signed PDF")
def download_link(self, document: LegalDocument) -> str | SafeString:
- if document.status != LegalDocument.Status.SIGNED:
+ # Gate on the stored flag: a row can be `signed` before the archive job
+ # lands the PDF, and the link would 404 until then.
+ if not document.signed_pdf_stored:
return "—"
url = f"/api/organizations/{document.organization_id}/legal_documents/{document.id}/download"
return format_html('<a href="{}" target="_blank" rel="noopener">Download PDF</a>', url)
diff --git a/products/legal_documents/backend/facade/api.py b/products/legal_documents/backend/facade/api.py
index 55539b15ad14..510188e0f3ee 100644
--- a/products/legal_documents/backend/facade/api.py
+++ b/products/legal_documents/backend/facade/api.py
@@ -8,11 +8,16 @@ output, and never leaks ORM instances or QuerySets across the boundary.
from __future__ import annotations
+from collections.abc import Callable
from uuid import UUID
from django.db import transaction
+import structlog
+
+from posthog.exceptions_capture import capture_exception
from posthog.models.organization import Organization
+from posthog.ph_client import ph_scoped_capture
from .. import logic
from ..logic.pandadoc import (
@@ -23,13 +28,15 @@ from ..models import LegalDocument
from . import contracts
from .enums import LegalDocumentStatus
+logger = structlog.get_logger(__name__)
+
-class LegalDocumentDownloadFailed(Exception):
+class LegalDocumentPdfArchiveFailed(Exception):
"""
- Raised when we own a row but couldn't pull the signed PDF from PandaDoc /
- stash it in object storage. The webhook handler surfaces this as a 5xx so
- PandaDoc retries; the underlying exception has already been logged +
- captured at the source.
+ Raised by the background archive task when it can't pull the signed PDF from
+ PandaDoc or write it to object storage. The row is already `signed` — only
+ the download copy is missing — so the task retries and the reconciliation
+ sweep re-enqueues it if every retry is exhausted.
"""
@@ -41,6 +48,7 @@ def _to_dto(doc: LegalDocument) -> contracts.LegalDocumentDTO:
company_name=doc.company_name,
representative_email=doc.representative_email,
status=doc.status,
+ signed_pdf_stored=doc.signed_pdf_stored,
created_by=(
contracts.LegalDocumentCreator(first_name=creator.first_name or "", email=creator.email)
if creator is not None
@@ -66,7 +74,7 @@ def get_signed_pdf_download_url(document_id: UUID, organization_id: UUID) -> str
storage (upload failed, storage disabled).
"""
document = logic.get_for_organization(document_id, organization_id)
- if document is None or document.status != LegalDocumentStatus.SIGNED:
+ if document is None or document.status != LegalDocumentStatus.SIGNED or not document.signed_pdf_stored:
return None
return logic.get_signed_pdf_presigned_url(document)
@@ -209,19 +217,19 @@ def mark_signed_by_pandadoc_document_id(
template_id: str,
) -> contracts.LegalDocumentDTO | None:
"""
- Entry point from the PandaDoc webhook. The caller must have already
- verified the HMAC signature on the raw body; this function:
+ Entry point from the PandaDoc `document.completed` webhook. The caller must
+ have already verified the HMAC signature on the raw body; this function:
- Looks up the row by the PandaDoc document uuid (no IDOR surface: unknown ids 404).
- Double-checks the template matches the stored document variant, to guard
against misconfigured PandaDoc templates flipping the wrong row.
- - Downloads the signed PDF from PandaDoc and stashes it in object storage.
- - Flips status to signed, fires analytics.
+ - Flips status to signed, fires analytics and BAA side effects, and schedules
+ the signed-PDF archive as a retried background job.
- Idempotent: if the row is already signed we return the existing DTO
- without re-downloading or re-firing analytics. If the download or
- upload fails we leave the row unsigned and return None so the webhook
- handler can surface 5xx; PandaDoc will retry.
+ The signature is recorded as soon as the webhook lands — it is never gated
+ on the PDF archival, which used to leave the row stuck when a download or
+ upload failed. Idempotent: an already-signed row returns its DTO without
+ re-firing side effects.
"""
document = logic.get_by_pandadoc_document_id(pandadoc_document_id)
if document is None:
@@ -230,9 +238,125 @@ def mark_signed_by_pandadoc_document_id(
return None
if document.status == LegalDocumentStatus.SIGNED:
return _to_dto(document)
- if not logic.download_and_store_signed_pdf(document):
- raise LegalDocumentDownloadFailed(f"Failed to retrieve signed PDF for legal_document {document.id}")
+ return _to_dto(_mark_signed_and_schedule_archive(document))
+
+
+def _mark_signed_and_schedule_archive(document: LegalDocument) -> LegalDocument:
document = logic.mark_document_signed(document)
logic.apply_baa_signed_side_effects(document)
logic.fire_legal_document_signed_event(document)
- return _to_dto(document)
+ _schedule_pdf_archive(document)
+ return document
+
+
+def _try_mark_signed_and_schedule_archive(
+ document: LegalDocument, capture: Callable[..., None] | None = None, delay_seconds: int = 0
+) -> bool:
+ """
+ Reconcile-only variant of `_mark_signed_and_schedule_archive`. The sweep's
+ queryset snapshot can be stale by the time this runs, so it uses the
+ conditional-update helper instead of an unconditional save. A document a
+ concurrent webhook already signed loses the race and its side effects are
+ skipped rather than re-fired.
+ """
+ if not logic.try_mark_signed_if_pending(document):
+ return False
+ logic.apply_baa_signed_side_effects(document)
+ logic.fire_legal_document_signed_event(document, capture=capture)
+ _schedule_pdf_archive(document, delay_seconds=delay_seconds)
+ return True
+
+
+def _schedule_pdf_archive(document: LegalDocument, delay_seconds: int = 0) -> None:
+ # Local import breaks the facade ⇄ tasks import cycle (tasks import the facade).
+ from ..tasks.tasks import archive_signed_legal_document_pdf # noqa: PLC0415
+
+ document_id = str(document.id)
+ transaction.on_commit(
+ lambda: archive_signed_legal_document_pdf.apply_async(args=[document_id], countdown=delay_seconds)
+ )
+
+
+def archive_signed_pdf(document_id: UUID) -> None:
+ """
+ Pull the signed PDF from PandaDoc and write it to object storage, then mark
+ the row archived. Called from the background task. Raises
+ LegalDocumentPdfArchiveFailed on any download/upload failure so the task
+ retries; a no-op if the row is gone or already archived.
+ """
+ document = logic.get_by_id(document_id)
+ if document is None or document.signed_pdf_stored:
+ return
+ if not logic.download_and_store_signed_pdf(document):
+ raise LegalDocumentPdfArchiveFailed(f"Failed to archive signed PDF for legal_document {document_id}")
+ logic.mark_signed_pdf_stored(document)
+
+
+def reconcile_pending_signatures() -> contracts.LegalDocumentReconcileResult:
+ """
+ Safety net for the whole completion path. Polls PandaDoc for every row we
+ still think is out for signature and marks the completed ones — recovering
+ dropped, throttled, or 204'd `document.completed` webhooks and clearing the
+ backlog. Also re-enqueues the archive for signed rows whose PDF never landed.
+
+ Each row is processed independently: `list_pending_signature_documents` is
+ ordered oldest-first, so one row that deterministically errors (a bad
+ PandaDoc response, a DB hiccup) must not block every row behind it on every
+ 15-minute tick.
+ """
+ newly_signed = 0
+ errors = 0
+ pending_seen = 0
+ # PandaDoc allows 100 downloads a minute across the whole account, shared with
+ # live signings. Staggering one archive per second keeps a backlog drain from
+ # starving a customer signing right now, and holds regardless of worker count.
+ scheduled_archives = 0
+ signed_this_run: set[UUID] = set()
+ # One scoped client for the whole loop, not one per row: this runs in a Celery
+ # worker, where the global client's background flush may never run before the
+ # process exits, and the scoped client blocks for seconds on setup and flush.
+ # Losing these events would hide whether the sweep is recovering anything.
+ with ph_scoped_capture() as capture:
+ for document in logic.list_pending_signature_documents():
+ pending_seen += 1
+ try:
+ if logic.get_pandadoc_document_status(document) == logic.PANDADOC_COMPLETED_STATUS:
+ if _try_mark_signed_and_schedule_archive(
+ document, capture=capture, delay_seconds=scheduled_archives
+ ):
+ newly_signed += 1
+ scheduled_archives += 1
+ signed_this_run.add(document.id)
+ except Exception as exc:
+ errors += 1
+ logger.exception("legal_document_reconcile_pending_row_failed", document_id=str(document.id))
+ capture_exception(exc, additional_properties={"legal_document_id": str(document.id)})
+
+ # The pending query is oldest-first and capped per run. When it fills the cap,
+ # newer rows fall off this run's tail and wait for a later tick — surface the
+ # binding cap instead of truncating silently, so a real backlog is visible.
+ if pending_seen >= logic.RECONCILE_MAX_PER_RUN:
+ logger.warning(
+ "legal_document_reconcile_pending_cap_reached",
+ processed=pending_seen,
+ cap=logic.RECONCILE_MAX_PER_RUN,
+ )
+
+ # Rows this run just signed and already scheduled an archive for above.
+ # excluding them here is what keeps the archive from being `.delay()`'d twice.
+ archives_requeued = 0
+ for document in logic.list_signed_documents_missing_pdf(exclude_ids=signed_this_run):
+ try:
+ _schedule_pdf_archive(document, delay_seconds=scheduled_archives)
+ archives_requeued += 1
+ scheduled_archives += 1
+ except Exception as exc:
+ errors += 1
+ logger.exception("legal_document_reconcile_archive_row_failed", document_id=str(document.id))
+ capture_exception(exc, additional_properties={"legal_document_id": str(document.id)})
+
+ return contracts.LegalDocumentReconcileResult(
+ newly_signed=newly_signed,
+ archives_requeued=archives_requeued,
+ errors=errors,
+ )
diff --git a/products/legal_documents/backend/facade/contracts.py b/products/legal_documents/backend/facade/contracts.py
index 13a4b5403710..f92530e900f3 100644
--- a/products/legal_documents/backend/facade/contracts.py
+++ b/products/legal_documents/backend/facade/contracts.py
@@ -23,10 +23,23 @@ class LegalDocumentDTO:
company_name: str
representative_email: str
status: str
+ # True once the signed PDF is in object storage. A signed row can still have
+ # this False for a short window while the archive job runs, so the UI knows
+ # to hold the download link back until the file lands.
+ signed_pdf_stored: bool
created_by: LegalDocumentCreator | None
created_at: datetime
+@dataclass(frozen=True)
+class LegalDocumentReconcileResult:
+ """Outcome of one reconciliation sweep, for logging and tests."""
+
+ newly_signed: int
+ archives_requeued: int
+ errors: int
+
+
@dataclass(frozen=True)
class CreateLegalDocumentInput:
"""Input for creating a new legal document. organization/user are injected by the view."""
diff --git a/products/legal_documents/backend/facade/tasks.py b/products/legal_documents/backend/facade/tasks.py
new file mode 100644
index 000000000000..ed91d59c41b4
--- /dev/null
+++ b/products/legal_documents/backend/facade/tasks.py
@@ -0,0 +1,12 @@
+"""Facade re-export for the legal_documents Celery tasks.
+
+Core's beat schedule (``posthog/tasks/scheduled.py``) imports the reconciliation
+task object and calls ``.s()`` on it, so the wiring crosses the boundary as an
+object, not data. Re-exporting the tasks keeps that coupling at the facade
+boundary. Each ``name=`` is pinned in ``tasks/tasks.py``, so the registered task
+identity is independent of the import path.
+"""
+
+from ..tasks.tasks import archive_signed_legal_document_pdf, reconcile_pending_legal_documents
+
+__all__ = ["archive_signed_legal_document_pdf", "reconcile_pending_legal_documents"]
diff --git a/products/legal_documents/backend/logic/__init__.py b/products/legal_documents/backend/logic/__init__.py
index f7f313c2afa0..86c9d596d1fd 100644
--- a/products/legal_documents/backend/logic/__init__.py
+++ b/products/legal_documents/backend/logic/__init__.py
@@ -7,10 +7,13 @@ Called by facade/api.py — do not call from outside this module.
from __future__ import annotations
+from collections.abc import Callable, Iterable
+from datetime import timedelta
from uuid import UUID
from django.conf import settings
from django.db.models import QuerySet
+from django.utils import timezone
import structlog
import posthoganalytics
@@ -97,6 +100,16 @@ def get_for_organization(document_id: UUID, organization_id: UUID) -> LegalDocum
return None
+def get_by_id(document_id: UUID) -> LegalDocument | None:
+ try:
+ # Internal background-task lookup by primary key (the archive/reconcile jobs
+ # pass an id we generated) — no request user and no org to scope by.
+ # nosemgrep: idor-lookup-without-org
+ return LegalDocument.objects.get(id=document_id)
+ except LegalDocument.DoesNotExist:
+ return None
+
+
def get_by_pandadoc_document_id(pandadoc_document_id: str) -> LegalDocument | None:
if not pandadoc_document_id:
return None
@@ -130,6 +143,96 @@ def mark_document_signed(document: LegalDocument) -> LegalDocument:
return document
+def try_mark_signed_if_pending(document: LegalDocument) -> bool:
+ """
+ Conditional UPDATE that re-asserts the row was still `submitted_for_signature`
+ before flipping it to `signed`. The reconciliation sweep holds a queryset
+ snapshot that can go stale between the PandaDoc poll and this call. A
+ concurrent `document.completed` webhook may have already signed the row.
+ Losing that race must skip the caller's side effects (BAA opt-out email)
+ rather than re-fire them, so the caller only proceeds when this returns True.
+ """
+ updated = LegalDocument.objects.filter(id=document.id, status=LegalDocument.Status.SUBMITTED_FOR_SIGNATURE).update(
+ status=LegalDocument.Status.SIGNED, updated_at=timezone.now()
+ )
+ return updated == 1
+
+
+def mark_signed_pdf_stored(document: LegalDocument) -> LegalDocument:
+ document.signed_pdf_stored = True
+ document.save(update_fields=["signed_pdf_stored", "updated_at"])
+ return document
+
+
+# PandaDoc status string for a fully-signed envelope. Mirrors the webhook layer.
+PANDADOC_COMPLETED_STATUS = "document.completed"
+
+# The reconciliation sweep polls PandaDoc once per pending row every 15 minutes, so
+# bound the set: only rows created inside this window, capped per run. Two weeks is
+# where the returns stop. Of the pending envelopes older than that, 2 of 162 ever
+# completed, so a longer window mostly re-asks about drafts nobody will ever sign.
+_RECONCILE_LOOKBACK = timedelta(days=14)
+RECONCILE_MAX_PER_RUN = 500
+
+
+def list_pending_signature_documents() -> QuerySet[LegalDocument]:
+ """
+ Rows we still think are out for signature but that have a PandaDoc envelope
+ to ask about. The reconciliation task polls each one so a dropped or 204'd
+ `document.completed` webhook can't strand a signature forever.
+ """
+ cutoff = timezone.now() - _RECONCILE_LOOKBACK
+ return (
+ LegalDocument.objects.filter(
+ status=LegalDocument.Status.SUBMITTED_FOR_SIGNATURE,
+ created_at__gte=cutoff,
+ )
+ .exclude(pandadoc_document_id="")
+ .order_by("created_at")[:RECONCILE_MAX_PER_RUN]
+ )
+
+
+def list_signed_documents_missing_pdf(exclude_ids: Iterable[UUID] = ()) -> QuerySet[LegalDocument]:
+ """
+ Signed rows whose PDF never made it to object storage — the background
+ archive job failed every retry. The reconciliation task re-enqueues these.
+ Capped like `list_pending_signature_documents` so a large backlog can't make
+ one sweep run long enough to overlap the next tick. `exclude_ids` lets the
+ caller skip rows it just signed and already scheduled an archive for in the
+ same sweep, so the same document doesn't get `.delay()`'d twice.
+ """
+ return (
+ LegalDocument.objects.filter(
+ status=LegalDocument.Status.SIGNED,
+ signed_pdf_stored=False,
+ )
+ .exclude(pandadoc_document_id="")
+ .exclude(id__in=list(exclude_ids))
+ .order_by("created_at")[:RECONCILE_MAX_PER_RUN]
+ )
+
+
+def get_pandadoc_document_status(document: LegalDocument) -> str | None:
+ """
+ Ask PandaDoc for the envelope's current status. Returns None when we can't
+ reach PandaDoc or the envelope is gone — the caller skips the row this round
+ and retries on the next tick.
+ """
+ if not document.pandadoc_document_id:
+ return None
+ client = pandadoc_client.PandaDocClient()
+ try:
+ return client.get_document_status(document_id=document.pandadoc_document_id)
+ except pandadoc_client.PandaDocError as exc:
+ logger.warning(
+ "legal_document_pandadoc_status_poll_failed",
+ document_id=str(document.id),
+ pandadoc_document_id=document.pandadoc_document_id,
+ error=str(exc),
+ )
+ return None
+
+
def delete_document(document: LegalDocument, *, strict_pandadoc: bool = False) -> None:
"""
Remove a legal document end-to-end.
@@ -471,14 +574,25 @@ def fire_legal_document_submitted_event(document: LegalDocument, distinct_id: st
_capture_lifecycle_event(document, SUBMITTED_EVENT, distinct_id)
-def fire_legal_document_signed_event(document: LegalDocument, distinct_id: str | None = None) -> None:
- """Capture the signed milestone to PostHog for the same analytics funnel."""
- _capture_lifecycle_event(document, SIGNED_EVENT, distinct_id)
+def fire_legal_document_signed_event(
+ document: LegalDocument, distinct_id: str | None = None, capture: Callable[..., None] | None = None
+) -> None:
+ """
+ Capture the signed milestone to PostHog for the same analytics funnel.
+
+ `capture` overrides the global client. The reconciliation sweep runs in a
+ Celery worker, where the global client's background flush may never run
+ before the process exits, so it passes a scoped client instead.
+ """
+ _capture_lifecycle_event(document, SIGNED_EVENT, distinct_id, capture)
-def _capture_lifecycle_event(document: LegalDocument, event_name: str, distinct_id: str | None) -> None:
+def _capture_lifecycle_event(
+ document: LegalDocument, event_name: str, distinct_id: str | None, capture: Callable[..., None] | None = None
+) -> None:
+ capture_event = capture or posthoganalytics.capture
try:
- posthoganalytics.capture(
+ capture_event(
event=event_name,
distinct_id=distinct_id or f"legal_document:{document.id}",
properties={
diff --git a/products/legal_documents/backend/logic/pandadoc.py b/products/legal_documents/backend/logic/pandadoc.py
index 0d17ca0be05a..cb2e3f3096d4 100644
--- a/products/legal_documents/backend/logic/pandadoc.py
+++ b/products/legal_documents/backend/logic/pandadoc.py
@@ -164,6 +164,14 @@ class PandaDocClient:
url = f"{self._base_url}{path}"
try:
with requests.get(url, headers=self._headers(), stream=True, timeout=self._timeout) as response:
+ if response.status_code == 202:
+ # PandaDoc's spec documents 202 + empty body + Retry-After for "signed
+ # assets not produced yet", exactly the race this file exists to survive.
+ # Treating it as success would stream an empty body into storage and mark
+ # the row permanently archived with no PDF behind it.
+ retry_after = response.headers.get("Retry-After")
+ suffix = f", retry after {retry_after}s" if retry_after else ""
+ raise PandaDocError(f"PandaDoc {path} returned 202: assets not ready yet{suffix}")
if response.status_code >= 400:
raise PandaDocError(f"PandaDoc {path} returned {response.status_code}: {response.text[:500]}")
# Transparently handle gzip/deflate on the wire so consumers
diff --git a/products/legal_documents/backend/migrations/0005_legaldocument_signed_pdf_stored.py b/products/legal_documents/backend/migrations/0005_legaldocument_signed_pdf_stored.py
new file mode 100644
index 000000000000..2ad822cd1ea9
--- /dev/null
+++ b/products/legal_documents/backend/migrations/0005_legaldocument_signed_pdf_stored.py
@@ -0,0 +1,15 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("legal_documents", "0004_alter_legaldocument_document_type"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="legaldocument",
+ name="signed_pdf_stored",
+ field=models.BooleanField(default=False, db_default=False),
+ ),
+ ]
diff --git a/products/legal_documents/backend/migrations/0006_backfill_signed_pdf_stored.py b/products/legal_documents/backend/migrations/0006_backfill_signed_pdf_stored.py
new file mode 100644
index 000000000000..7c8949693585
--- /dev/null
+++ b/products/legal_documents/backend/migrations/0006_backfill_signed_pdf_stored.py
@@ -0,0 +1,22 @@
+from django.db import migrations
+
+
+def backfill_signed_pdf_stored(apps, schema_editor):
+ # Every already-signed row got its PDF under the old flow, which only
+ # flipped status to `signed` after the archive succeeded (PandaDoc webhook)
+ # or wrote the PDF synchronously (admin upload). Mark those as stored so the
+ # download link keeps working and the reconciliation task ignores them.
+ # legal_documents is a small table (hundreds of rows), so a single UPDATE is
+ # fine — no batching needed.
+ LegalDocument = apps.get_model("legal_documents", "LegalDocument")
+ LegalDocument.objects.filter(status="signed").update(signed_pdf_stored=True)
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("legal_documents", "0005_legaldocument_signed_pdf_stored"),
+ ]
+
+ operations = [
+ migrations.RunPython(backfill_signed_pdf_stored, migrations.RunPython.noop),
+ ]
diff --git a/products/legal_documents/backend/migrations/max_migration.txt b/products/legal_documents/backend/migrations/max_migration.txt
index 12ab0aec871e..2343cc70c489 100644
--- a/products/legal_documents/backend/migrations/max_migration.txt
+++ b/products/legal_documents/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0004_alter_legaldocument_document_type
+0006_backfill_signed_pdf_stored
diff --git a/products/legal_documents/backend/models.py b/products/legal_documents/backend/models.py
index a458a4161175..5a396d919edb 100644
--- a/products/legal_documents/backend/models.py
+++ b/products/legal_documents/backend/models.py
@@ -39,6 +39,13 @@ class LegalDocument(ModelActivityMixin, CreatedMetaFields, UpdatedMetaFields, UU
# join key for inbound PandaDoc webhooks.
pandadoc_document_id = models.CharField(max_length=64, blank=True, db_index=True)
+ # True once the signed PDF has been pulled from PandaDoc and written to
+ # object storage. A row can be `signed` before this flips: the signature is
+ # recorded the moment the completion webhook lands, and the PDF is archived
+ # in a retried background job. The download link stays hidden until the file
+ # is actually there.
+ signed_pdf_stored = models.BooleanField(default=False, db_default=False)
+
class Meta:
ordering = ["-created_at"]
# An org has at most one BAA and at most one DPA. If they need a new one (e.g.,
diff --git a/products/legal_documents/backend/presentation/webhook.py b/products/legal_documents/backend/presentation/webhook.py
index 1523ea18c74c..03133dffa494 100644
--- a/products/legal_documents/backend/presentation/webhook.py
+++ b/products/legal_documents/backend/presentation/webhook.py
@@ -5,29 +5,18 @@ from django.conf import settings
import structlog
from drf_spectacular.utils import OpenApiTypes, extend_schema
from rest_framework import status
-from rest_framework.decorators import api_view, authentication_classes, permission_classes, throttle_classes
+from rest_framework.decorators import api_view, authentication_classes, permission_classes
from rest_framework.request import Request
from rest_framework.response import Response
from posthog.cloud_utils import is_cloud, is_dev_mode
from posthog.exceptions_capture import capture_exception
-from posthog.rate_limit import IPThrottle
from ..facade import api
logger = structlog.get_logger(__name__)
-class PandaDocWebhookBurstThrottle(IPThrottle):
- scope = "legal_document_pandadoc_webhook_burst"
- rate = "5/minute"
-
-
-class PandaDocWebhookSustainedThrottle(IPThrottle):
- scope = "legal_document_pandadoc_webhook_sustained"
- rate = "30/hour"
-
-
# PandaDoc state-change events we care about. Everything else is ignored.
_PANDADOC_STATE_CHANGED_EVENT = "document_state_changed"
@@ -47,20 +36,20 @@ _PANDADOC_COMPLETED_STATUS = "document.completed"
description=(
"PandaDoc webhook receiver. Authenticates via HMAC-SHA256 over the raw "
"body. Handles two `document_state_changed` events: `document.draft` "
- "dispatches the signing email, and `document.completed` pulls the "
- "signed PDF and stores it in object storage. Returns 200 "
- "when an event applied, 204 when the request is valid but the "
- "document doesn't live on this cloud instance (PandaDoc fans the "
+ "dispatches the signing email, and `document.completed` records the "
+ "signature and schedules the signed-PDF archive as a background job. "
+ "Returns 200 when an event applied, 204 when the request is valid but "
+ "the document doesn't live on this cloud instance (PandaDoc fans the "
"webhook out to every instance, only one of which owns the row), "
- "404 on a bad signature, 400 on an unparseable body. A transient "
- "failure fetching/storing the signed PDF surfaces as 5xx so PandaDoc "
- "retries."
+ "404 on a bad signature, 400 on an unparseable body. No per-IP throttle: "
+ "PandaDoc delivers from a small shared pool of egress IPs, so keying on "
+ "them drops legitimate deliveries; the HMAC check already proves "
+ "provenance."
),
)
@api_view(["POST"])
@authentication_classes([])
@permission_classes([])
-@throttle_classes([PandaDocWebhookBurstThrottle, PandaDocWebhookSustainedThrottle])
def legal_document_pandadoc_webhook(request: Request) -> Response:
if not (is_cloud() or is_dev_mode()):
# Self-hosted deployments don't run the PandaDoc integration — never
@@ -88,13 +77,6 @@ def legal_document_pandadoc_webhook(request: Request) -> Response:
events = [events]
processed_any = False
- # Set when a completed event raises a retriable failure. We finish
- # iterating the rest of the batch first — every facade method is
- # idempotent, so whatever else applies now is a no-op on the replay —
- # and surface the 503 at the end. Short-circuiting mid-batch would
- # silently drop trailing events until PandaDoc's retry replayed the
- # whole payload.
- deferred_retry = False
for event in events:
if not isinstance(event, dict):
@@ -128,23 +110,12 @@ def legal_document_pandadoc_webhook(request: Request) -> Response:
continue
if event_status == _PANDADOC_COMPLETED_STATUS:
- # PandaDoc's completed payload does not carry a signed-PDF URL;
- # the facade pulls the PDF via the public API and stashes it in
- # object storage. A transient download/upload failure surfaces as
- # 503 so PandaDoc retries the delivery.
- try:
- dto = api.mark_signed_by_pandadoc_document_id(
- pandadoc_document_id=pandadoc_document_id,
- template_id=template_id or "",
- )
- except api.LegalDocumentDownloadFailed as exc:
- logger.warning(
- "pandadoc_webhook_signed_pdf_unavailable",
- pandadoc_document_id=pandadoc_document_id,
- error=str(exc),
- )
- deferred_retry = True
- continue
+ # Record the signature and schedule the PDF archive as a background
+ # job — the signature is never gated on the download succeeding.
+ dto = api.mark_signed_by_pandadoc_document_id(
+ pandadoc_document_id=pandadoc_document_id,
+ template_id=template_id or "",
+ )
if dto is None:
logger.info("pandadoc_webhook_no_matching_document", pandadoc_document_id=pandadoc_document_id)
continue
@@ -153,12 +124,6 @@ def legal_document_pandadoc_webhook(request: Request) -> Response:
# Other states (document.sent, document.viewed, …) — nothing to do.
- if deferred_retry:
- return Response(
- {"detail": "Signed document unavailable; please retry."},
- status=status.HTTP_503_SERVICE_UNAVAILABLE,
- )
-
if processed_any:
return Response({"status": "ok"}, status=status.HTTP_200_OK)
diff --git a/products/legal_documents/backend/tasks/tasks.py b/products/legal_documents/backend/tasks/tasks.py
index ed7a12948303..c060093a21e7 100644
--- a/products/legal_documents/backend/tasks/tasks.py
+++ b/products/legal_documents/backend/tasks/tasks.py
@@ -2,7 +2,48 @@
Celery tasks for legal_documents.
Async entrypoints that call the facade (facade/api.py).
-Keep task functions thin - only call facade methods.
+Keep task functions thin — only call facade methods.
"""
-# from celery import shared_task
-# from ..facade import api
+
+from __future__ import annotations
+
+from uuid import UUID
+
+import structlog
+from celery import shared_task
+
+from ..facade import api
+
+logger = structlog.get_logger(__name__)
+
+
+# Task names are pinned so the registered identity is independent of the import
+# path — core re-exports these through facade/tasks.py to call `.s()`.
+@shared_task(
+ name="products.legal_documents.backend.tasks.archive_signed_legal_document_pdf",
+ ignore_result=True,
+ autoretry_for=(api.LegalDocumentPdfArchiveFailed,),
+ retry_backoff=30,
+ retry_backoff_max=600,
+ retry_jitter=True,
+ max_retries=8,
+)
+def archive_signed_legal_document_pdf(document_id: str) -> None:
+ api.archive_signed_pdf(UUID(document_id))
+
+
+@shared_task(
+ name="products.legal_documents.backend.tasks.reconcile_pending_legal_documents",
+ ignore_result=True,
+ # Runs every 15 minutes; limits stay well under that so a slow run can't overlap the next tick.
+ soft_time_limit=180,
+ time_limit=300,
+)
+def reconcile_pending_legal_documents() -> None:
+ result = api.reconcile_pending_signatures()
+ logger.info(
+ "legal_documents.reconcile_swept",
+ newly_signed=result.newly_signed,
+ archives_requeued=result.archives_requeued,
+ errors=result.errors,
+ )
diff --git a/products/legal_documents/backend/tests/test_api.py b/products/legal_documents/backend/tests/test_api.py
index abf833332223..8675a0fe35ad 100644
--- a/products/legal_documents/backend/tests/test_api.py
+++ b/products/legal_documents/backend/tests/test_api.py
@@ -2,6 +2,7 @@ import hmac
import json
import hashlib
from contextlib import contextmanager
+from datetime import timedelta
from typing import Any
from posthog.test.base import APIBaseTest
@@ -9,13 +10,16 @@ from unittest.mock import patch
from django.db import IntegrityError
from django.test import override_settings
+from django.utils import timezone
+from celery.exceptions import Retry
from parameterized import parameterized
from rest_framework import status
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.organization import Organization, OrganizationMembership
+from products.legal_documents.backend.facade import api as legal_api
from products.legal_documents.backend.models import LegalDocument
BAA_PAYLOAD = {
@@ -266,6 +270,7 @@ class TestLegalDocumentDownloadEndpoint(APIBaseTest):
company_address="1 Analytics Way",
representative_email="[email protected]",
status=LegalDocument.Status.SIGNED,
+ signed_pdf_stored=True,
pandadoc_document_id="doc_123",
created_by=self.user,
)
@@ -292,6 +297,16 @@ class TestLegalDocumentDownloadEndpoint(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
presign_mock.assert_not_called()
+ def test_signed_but_unarchived_document_returns_404(self) -> None:
+ # The signature lands before the PDF archive job runs. Until the file is
+ # stored, the download must 404 instead of redirecting to a missing S3 key.
+ self.document.signed_pdf_stored = False
+ self.document.save(update_fields=["signed_pdf_stored"])
+ with patch("products.legal_documents.backend.logic.object_storage.get_presigned_url") as presign_mock:
+ response = self.client.get(self.url)
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+ presign_mock.assert_not_called()
+
def test_unknown_document_returns_404(self) -> None:
bogus_url = (
f"/api/organizations/{self.organization.id}/legal_documents/00000000-0000-0000-0000-000000000000/download"
@@ -537,9 +552,9 @@ class TestLegalDocumentPandaDocWebhook(APIBaseTest):
PANDADOC_DPA_TEMPLATE_ID=self.DPA_TEMPLATE_ID,
)
- def test_valid_signature_streams_pdf_to_object_storage_and_flips_status(self) -> None:
- # The streaming handle is opaque to the webhook layer; we just need to
- # confirm it's threaded from PandaDoc into object storage.
+ def test_valid_signature_flips_status_and_archives_pdf_in_background(self) -> None:
+ # The signature is recorded synchronously; the PDF archive runs from the
+ # scheduled background task (fired here via captureOnCommitCallbacks).
fake_stream = object()
@contextmanager
@@ -555,10 +570,12 @@ class TestLegalDocumentPandaDocWebhook(APIBaseTest):
) as stream_mock,
patch("products.legal_documents.backend.logic.object_storage.write_stream") as write_mock,
):
- response = self._post_raw(body, self._sign(body))
+ with self.captureOnCommitCallbacks(execute=True):
+ response = self._post_raw(body, self._sign(body))
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.document.refresh_from_db()
self.assertEqual(self.document.status, "signed")
+ self.assertTrue(self.document.signed_pdf_stored)
stream_mock.assert_called_once_with(document_id="doc_123")
write_mock.assert_called_once()
args, kwargs = write_mock.call_args
@@ -567,7 +584,10 @@ class TestLegalDocumentPandaDocWebhook(APIBaseTest):
self.assertIs(args[1], fake_stream)
self.assertEqual(kwargs["extras"], {"ContentType": "application/pdf"})
- def test_download_failure_returns_503_and_leaves_row_unsigned(self) -> None:
+ def test_archive_failure_leaves_row_signed_but_unarchived(self) -> None:
+ # The whole point of the decoupling: a PDF download failure no longer
+ # blocks the signature. The row is signed and the webhook returns 200;
+ # only signed_pdf_stored stays False for the reconciliation sweep to fix.
from products.legal_documents.backend.logic import pandadoc as pandadoc_module
body = json.dumps(self._completed_payload()).encode("utf-8")
@@ -576,16 +596,20 @@ class TestLegalDocumentPandaDocWebhook(APIBaseTest):
patch(
"products.legal_documents.backend.logic.pandadoc_client.PandaDocClient.stream_document",
side_effect=pandadoc_module.PandaDocError("network boom"),
- ),
+ ) as stream_mock,
patch("products.legal_documents.backend.logic.object_storage.write_stream") as write_mock,
):
- response = self._post_raw(body, self._sign(body))
+ # Celery runs eagerly in tests, and autoretry_for re-raises as Retry once
+ # every attempt is exhausted, the same pattern as the task's real retry behavior.
+ with self.assertRaises(Retry), self.captureOnCommitCallbacks(execute=True):
+ response = self._post_raw(body, self._sign(body))
- # 503 surfaces so PandaDoc retries the delivery.
- self.assertEqual(response.status_code, status.HTTP_503_SERVICE_UNAVAILABLE)
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ stream_mock.assert_called_once_with(document_id="doc_123")
write_mock.assert_not_called()
self.document.refresh_from_db()
- self.assertEqual(self.document.status, "submitted_for_signature")
+ self.assertEqual(self.document.status, "signed")
+ self.assertFalse(self.document.signed_pdf_stored)
def test_invalid_signature_returns_404(self) -> None:
body = json.dumps(self._completed_payload()).encode("utf-8")
@@ -800,6 +824,265 @@ class TestLegalDocumentPandaDocWebhook(APIBaseTest):
self.assertFalse(self.organization.is_ai_data_processing_approved)
+@override_settings(CLOUD_DEPLOYMENT="US")
+class TestLegalDocumentReconciliation(APIBaseTest):
+ """
+ The reconciliation sweep and the background archive task — the safety net
+ that recovers signatures whose completion webhook was dropped, throttled, or
+ 204'd, and re-archives signed rows whose PDF never landed.
+ """
+
+ def setUp(self) -> None:
+ super().setUp()
+ self.document = LegalDocument.objects.create(
+ organization=self.organization,
+ document_type="DPA",
+ company_name="Acme, Inc.",
+ company_address="1 Analytics Way",
+ representative_email="[email protected]",
+ pandadoc_document_id="doc_123",
+ created_by=self.user,
+ )
+
+ @contextmanager
+ def _fake_pdf_pipeline(self):
+ @contextmanager
+ def fake_stream_cm(*, document_id): # noqa: ARG001
+ yield object()
+
+ with (
+ patch(
+ "products.legal_documents.backend.logic.pandadoc_client.PandaDocClient.stream_document",
+ side_effect=fake_stream_cm,
+ ),
+ patch("products.legal_documents.backend.logic.object_storage.write_stream"),
+ ):
+ yield
+
+ @patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient.get_document_status")
+ def test_reconcile_marks_completed_pending_document_signed(self, status_mock) -> None:
+ status_mock.return_value = "document.completed"
+ with self._fake_pdf_pipeline(), self.captureOnCommitCallbacks(execute=True):
+ result = legal_api.reconcile_pending_signatures()
+
+ self.assertEqual(result.newly_signed, 1)
+ self.document.refresh_from_db()
+ self.assertEqual(self.document.status, "signed")
+ self.assertTrue(self.document.signed_pdf_stored)
+
+ @patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient.get_document_status")
+ def test_reconcile_captures_the_signed_event_through_a_scoped_client(self, status_mock) -> None:
+ # The sweep runs in a Celery worker, where the global analytics client's
+ # background flush may never run before the process exits. Losing the signed
+ # event here would leave a working sweep indistinguishable from a broken one,
+ # since that event is what the outage was detected on.
+ status_mock.return_value = "document.completed"
+ with (
+ patch("products.legal_documents.backend.facade.api.ph_scoped_capture") as scoped_mock,
+ patch("products.legal_documents.backend.logic.posthoganalytics.capture") as global_mock,
+ ):
+ capture = scoped_mock.return_value.__enter__.return_value
+ with self._fake_pdf_pipeline(), self.captureOnCommitCallbacks(execute=True):
+ legal_api.reconcile_pending_signatures()
+
+ capture.assert_called_once()
+ self.assertEqual(capture.call_args.kwargs["event"], "legal document signed")
+ global_mock.assert_not_called()
+
+ @patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient.get_document_status")
+ def test_reconcile_skips_documents_older_than_lookback_window(self, status_mock) -> None:
+ # Abandoned envelopes must not be polled forever, or the sweep re-asks PandaDoc
+ # about them every 15 minutes. 30 days is deliberately inside the window this
+ # started with, so widening it back would fail here rather than pass quietly.
+ status_mock.return_value = "document.completed"
+ LegalDocument.objects.filter(id=self.document.id).update(created_at=timezone.now() - timedelta(days=30))
+
+ result = legal_api.reconcile_pending_signatures()
+
+ self.assertEqual(result.newly_signed, 0)
+ status_mock.assert_not_called()
+ self.document.refresh_from_db()
+ self.assertEqual(self.document.status, "submitted_for_signature")
+
+ @patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient.get_document_status")
+ def test_reconcile_leaves_still_pending_document_alone(self, status_mock) -> None:
+ status_mock.return_value = "document.sent"
+ result = legal_api.reconcile_pending_signatures()
+
+ self.assertEqual(result.newly_signed, 0)
+ self.document.refresh_from_db()
+ self.assertEqual(self.document.status, "submitted_for_signature")
+
+ @patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient.get_document_status")
+ def test_reconcile_continues_past_a_row_that_raises(self, status_mock) -> None:
+ # Each org can only hold one DPA (unique constraint), so the extra pending
+ # rows live in separate orgs. list_pending_signature_documents orders
+ # oldest-first, so pin created_at explicitly to make the middle row deterministic.
+ middle_org = Organization.objects.create(name="Middle Co")
+ last_org = Organization.objects.create(name="Last Co")
+ middle = LegalDocument.objects.create(
+ organization=middle_org,
+ document_type="DPA",
+ company_name="Middle Co",
+ company_address="Elsewhere",
+ representative_email="[email protected]",
+ pandadoc_document_id="doc_middle",
+ created_by=self.user,
+ )
+ last = LegalDocument.objects.create(
+ organization=last_org,
+ document_type="DPA",
+ company_name="Last Co",
+ company_address="Elsewhere",
+ representative_email="[email protected]",
+ pandadoc_document_id="doc_last",
+ created_by=self.user,
+ )
+ now = timezone.now()
+ LegalDocument.objects.filter(id=self.document.id).update(created_at=now - timedelta(minutes=2))
+ LegalDocument.objects.filter(id=middle.id).update(created_at=now - timedelta(minutes=1))
+ LegalDocument.objects.filter(id=last.id).update(created_at=now)
+
+ def status_side_effect(*, document_id):
+ if document_id == "doc_middle":
+ raise RuntimeError("unexpected PandaDoc client bug")
+ return "document.completed"
+
+ status_mock.side_effect = status_side_effect
+
+ with self._fake_pdf_pipeline(), self.captureOnCommitCallbacks(execute=True):
+ result = legal_api.reconcile_pending_signatures()
+
+ self.assertEqual(result.newly_signed, 2)
+ self.assertEqual(result.errors, 1)
+ self.document.refresh_from_db()
+ middle.refresh_from_db()
+ last.refresh_from_db()
+ self.assertEqual(self.document.status, "signed")
+ self.assertEqual(middle.status, "submitted_for_signature")
+ self.assertEqual(last.status, "signed")
+
+ @patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient.get_document_status")
+ def test_reconcile_schedules_archive_once_for_newly_signed_row(self, status_mock) -> None:
+ status_mock.return_value = "document.completed"
+ with (
+ patch(
+ "products.legal_documents.backend.tasks.tasks.archive_signed_legal_document_pdf.apply_async"
+ ) as enqueue_mock,
+ self.captureOnCommitCallbacks(execute=True),
+ ):
+ result = legal_api.reconcile_pending_signatures()
+
+ self.assertEqual(result.newly_signed, 1)
+ self.assertEqual(result.archives_requeued, 0)
+ enqueue_mock.assert_called_once_with(args=[str(self.document.id)], countdown=0)
+
+ @patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient.get_document_status")
+ def test_reconcile_staggers_archives_one_per_second(self, status_mock) -> None:
+ # PandaDoc caps downloads per account, shared with live signings, so a backlog
+ # drain has to spread out rather than enqueue every archive at once.
+ for i in (1, 2):
+ org = self.create_organization_with_features([])
+ LegalDocument.objects.create(
+ organization=org,
+ document_type="DPA",
+ company_name=f"Later Co {i}",
+ company_address="2 Analytics Way",
+ representative_email=f"later{i}@other.example",
+ pandadoc_document_id=f"doc_later_{i}",
+ created_by=self.user,
+ )
+ status_mock.return_value = "document.completed"
+
+ with (
+ patch(
+ "products.legal_documents.backend.tasks.tasks.archive_signed_legal_document_pdf.apply_async"
+ ) as enqueue_mock,
+ self.captureOnCommitCallbacks(execute=True),
+ ):
+ result = legal_api.reconcile_pending_signatures()
+
+ self.assertEqual(result.newly_signed, 3)
+ countdowns = [call.kwargs["countdown"] for call in enqueue_mock.call_args_list]
+ self.assertEqual(countdowns, [0, 1, 2])
+
+ def test_reconcile_skips_side_effects_for_concurrently_signed_row(self) -> None:
+ # A webhook can sign the row between the reconcile loop reading its queryset
+ # snapshot and processing it. BAA side effects include emailing org owners,
+ # so re-running them here would send a second email for a signature the
+ # webhook already handled.
+ self.document.document_type = "BAA"
+ self.document.save(update_fields=["document_type"])
+ self.organization.is_ai_data_processing_approved = True
+ self.organization.save(update_fields=["is_ai_data_processing_approved"])
+
+ def status_side_effect(*, document_id): # noqa: ARG001
+ LegalDocument.objects.filter(id=self.document.id).update(status=LegalDocument.Status.SIGNED)
+ return "document.completed"
+
+ with patch(
+ "products.legal_documents.backend.logic.pandadoc_client.PandaDocClient.get_document_status",
+ side_effect=status_side_effect,
+ ):
+ result = legal_api.reconcile_pending_signatures()
+
+ self.assertEqual(result.newly_signed, 0)
+ self.assertEqual(result.errors, 0)
+ self.organization.refresh_from_db()
+ self.assertTrue(self.organization.is_ai_data_processing_approved)
+
+ def test_reconcile_leaves_pending_document_alone_when_pandadoc_unreachable(self) -> None:
+ from products.legal_documents.backend.logic import pandadoc as pandadoc_module
+
+ with patch(
+ "products.legal_documents.backend.logic.pandadoc_client.PandaDocClient.get_document_status",
+ side_effect=pandadoc_module.PandaDocError("network boom"),
+ ):
+ result = legal_api.reconcile_pending_signatures()
+
+ self.assertEqual(result.newly_signed, 0)
+ self.assertEqual(result.errors, 0)
+ self.document.refresh_from_db()
+ self.assertEqual(self.document.status, "submitted_for_signature")
+
+ def test_reconcile_requeues_archive_for_signed_row_missing_pdf(self) -> None:
+ self.document.status = LegalDocument.Status.SIGNED
+ self.document.save(update_fields=["status"])
+
+ with self._fake_pdf_pipeline(), self.captureOnCommitCallbacks(execute=True):
+ result = legal_api.reconcile_pending_signatures()
+
+ self.assertEqual(result.archives_requeued, 1)
+ self.document.refresh_from_db()
+ self.assertTrue(self.document.signed_pdf_stored)
+
+ def test_archive_is_noop_when_already_stored(self) -> None:
+ self.document.status = LegalDocument.Status.SIGNED
+ self.document.signed_pdf_stored = True
+ self.document.save(update_fields=["status", "signed_pdf_stored"])
+
+ with patch(
+ "products.legal_documents.backend.logic.pandadoc_client.PandaDocClient.stream_document"
+ ) as stream_mock:
+ legal_api.archive_signed_pdf(self.document.id)
+ stream_mock.assert_not_called()
+
+ def test_archive_failure_raises_for_task_retry(self) -> None:
+ from products.legal_documents.backend.logic import pandadoc as pandadoc_module
+
+ self.document.status = LegalDocument.Status.SIGNED
+ self.document.save(update_fields=["status"])
+
+ with patch(
+ "products.legal_documents.backend.logic.pandadoc_client.PandaDocClient.stream_document",
+ side_effect=pandadoc_module.PandaDocError("boom"),
+ ):
+ with self.assertRaises(legal_api.LegalDocumentPdfArchiveFailed):
+ legal_api.archive_signed_pdf(self.document.id)
+ self.document.refresh_from_db()
+ self.assertFalse(self.document.signed_pdf_stored)
+
+
@override_settings(CLOUD_DEPLOYMENT=None, DEBUG=False)
class TestLegalDocumentsSelfHostedGate(APIBaseTest):
"""
diff --git a/products/legal_documents/backend/tests/test_pandadoc.py b/products/legal_documents/backend/tests/test_pandadoc.py
index f80c31dd62b8..74ac24326085 100644
--- a/products/legal_documents/backend/tests/test_pandadoc.py
+++ b/products/legal_documents/backend/tests/test_pandadoc.py
@@ -120,6 +120,26 @@ class TestPandaDocClient(TestCase):
with client.stream_document(document_id="doc_123"):
pass
+ @override_settings(PANDADOC_API_KEY="key")
+ def test_stream_document_treats_202_as_not_ready(self) -> None:
+ # PandaDoc answers 202 with an empty body while the signed asset is still
+ # being produced. It has to raise: a 202 that streamed through would store a
+ # zero-byte PDF and mark the document archived, which nothing ever revisits.
+ fake_response = MagicMock()
+ fake_response.status_code = 202
+ fake_response.headers = {"Retry-After": "30"}
+ fake_response.__enter__ = MagicMock(return_value=fake_response)
+ fake_response.__exit__ = MagicMock(return_value=False)
+
+ with patch("products.legal_documents.backend.logic.pandadoc.requests.get", return_value=fake_response):
+ client = pandadoc.PandaDocClient()
+ with self.assertRaises(pandadoc.PandaDocError) as ctx:
+ with client.stream_document(document_id="doc_123"):
+ pass
+
+ self.assertIn("not ready yet", str(ctx.exception))
+ self.assertIn("30", str(ctx.exception))
+
@override_settings(PANDADOC_API_KEY="key", PANDADOC_API_BASE_URL="https://api.pandadoc.com")
def test_send_document_includes_sender_when_provided(self) -> None:
# PandaDoc only honors the configured sender identity if `sender` is on
diff --git a/products/legal_documents/backend/tests/test_reconcile_tasks.py b/products/legal_documents/backend/tests/test_reconcile_tasks.py
new file mode 100644
index 000000000000..007ee25eb342
--- /dev/null
+++ b/products/legal_documents/backend/tests/test_reconcile_tasks.py
@@ -0,0 +1,74 @@
+from typing import Any
+
+from posthog.test.base import NonAtomicTestMigrations
+
+from django.test import SimpleTestCase
+
+from posthog.celery import app
+
+from products.legal_documents.backend.facade import api as legal_api
+from products.legal_documents.backend.tasks.tasks import archive_signed_legal_document_pdf
+
+
+class TestArchiveSignedLegalDocumentPdfRetryConfig(SimpleTestCase):
+ def test_registered_under_pinned_name(self) -> None:
+ # facade/tasks.py re-exports this task by name rather than import path, so a
+ # rename that drops registration under the pinned name would silently break
+ # that lookup. Suffix match tolerates the pinned name's prefix changing.
+ assert archive_signed_legal_document_pdf.name.endswith("archive_signed_legal_document_pdf")
+ assert archive_signed_legal_document_pdf.name in app.tasks
+
+ def test_retry_config_is_not_inert(self) -> None:
+ # Bare max_retries without autoretry_for is silently inert; assert the wiring
+ # this task's whole purpose depends on is actually there.
+ assert archive_signed_legal_document_pdf.autoretry_for == (legal_api.LegalDocumentPdfArchiveFailed,)
+ assert archive_signed_legal_document_pdf.max_retries == 8
+ assert archive_signed_legal_document_pdf.retry_backoff == 30
+ assert archive_signed_legal_document_pdf.retry_backoff_max == 600
+ assert archive_signed_legal_document_pdf.retry_jitter is True
+
+
+class BackfillSignedPdfStoredMigrationTest(NonAtomicTestMigrations):
+ """0006 marks pre-existing signed rows as archived. The old flow only flipped
+ status to `signed` after the PDF was already written to object storage, so every
+ row signed before this migration has its PDF sitting in storage already. The
+ reconciliation sweep only looks at signed_pdf_stored=False rows, so an unmarked
+ signed row would get silently re-swept and would hide its download link.
+ """
+
+ migrate_from = "0005_legaldocument_signed_pdf_stored"
+ migrate_to = "0006_backfill_signed_pdf_stored"
+
+ CLASS_DATA_LEVEL_SETUP = False
+
+ @property
+ def app(self) -> str:
+ return "legal_documents"
+
+ def setUpBeforeMigration(self, apps: Any) -> None:
+ Organization = apps.get_model("posthog", "Organization")
+ LegalDocument = apps.get_model("legal_documents", "LegalDocument")
+
+ org = Organization.objects.create(name="Acme, Inc.")
+ self.signed_id = LegalDocument.objects.create(
+ organization=org,
+ document_type="BAA",
+ company_name="Acme, Inc.",
+ company_address="1 Analytics Way",
+ representative_email="[email protected]",
+ status="signed",
+ ).id
+ self.pending_id = LegalDocument.objects.create(
+ organization=org,
+ document_type="DPA",
+ company_name="Acme, Inc.",
+ company_address="1 Analytics Way",
+ representative_email="[email protected]",
+ status="submitted_for_signature",
+ ).id
+
+ def test_backfills_signed_rows_only(self) -> None:
+ LegalDocument = self.apps.get_model("legal_documents", "LegalDocument") # type: ignore[union-attr]
+
+ assert LegalDocument.objects.get(id=self.signed_id).signed_pdf_stored is True
+ assert LegalDocument.objects.get(id=self.pending_id).signed_pdf_stored is False
diff --git a/products/legal_documents/frontend/generated/api.schemas.ts b/products/legal_documents/frontend/generated/api.schemas.ts
index a92168a8e0b7..e65dffadc39a 100644
--- a/products/legal_documents/frontend/generated/api.schemas.ts
+++ b/products/legal_documents/frontend/generated/api.schemas.ts
@@ -21,6 +21,7 @@ export interface LegalDocumentDTOApi {
company_name: string
representative_email: string
status: string
+ signed_pdf_stored: boolean
created_by: LegalDocumentCreatorApi | null
created_at: string
}
diff --git a/products/legal_documents/frontend/scenes/LegalDocuments.stories.tsx b/products/legal_documents/frontend/scenes/LegalDocuments.stories.tsx
index 678ad6b6dc5a..e89dd63feada 100644
--- a/products/legal_documents/frontend/scenes/LegalDocuments.stories.tsx
+++ b/products/legal_documents/frontend/scenes/LegalDocuments.stories.tsx
@@ -19,6 +19,7 @@ const LEGAL_DOCUMENT_LIST = [
company_name: 'Acme Health, Inc.',
representative_email: '[email protected]',
status: 'signed',
+ signed_pdf_stored: true,
created_by: SUBMITTER,
created_at: '2026-04-10T12:00:00Z',
},
@@ -28,6 +29,7 @@ const LEGAL_DOCUMENT_LIST = [
company_name: 'Acme Health, Inc.',
representative_email: '[email protected]',
status: 'submitted_for_signature',
+ signed_pdf_stored: false,
created_by: SUBMITTER,
created_at: '2026-04-20T15:30:00Z',
},
diff --git a/products/legal_documents/frontend/scenes/LegalDocumentsScene.tsx b/products/legal_documents/frontend/scenes/LegalDocumentsScene.tsx
index 775f6369bef8..3792ec34850a 100644
--- a/products/legal_documents/frontend/scenes/LegalDocumentsScene.tsx
+++ b/products/legal_documents/frontend/scenes/LegalDocumentsScene.tsx
@@ -169,7 +169,7 @@ export function LegalDocumentsScene(): JSX.Element {
title: 'Signed copy',
width: 140,
render: (_: any, row: LegalDocument) =>
- row.status === 'signed' && currentOrganizationId ? (
+ row.status === 'signed' && row.signed_pdf_stored && currentOrganizationId ? (
<Link
to={getLegalDocumentsDownloadRetrieveUrl(currentOrganizationId, row.id)}
target="_blank"
diff --git a/products/legal_documents/frontend/scenes/legalDocumentsLogic.ts b/products/legal_documents/frontend/scenes/legalDocumentsLogic.ts
index 2cb3528a71dc..7d198e9de7e7 100644
--- a/products/legal_documents/frontend/scenes/legalDocumentsLogic.ts
+++ b/products/legal_documents/frontend/scenes/legalDocumentsLogic.ts
@@ -30,6 +30,9 @@ export interface LegalDocument {
company_name: string
representative_email: string
status: LegalDocumentStatus
+ // False for the short window between the signature landing and the archive
+ // job storing the PDF — the download link stays hidden until it's true.
+ signed_pdf_stored: boolean
created_by: LegalDocumentCreator | null
created_at: string
}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 65937782b1b5..ed81ece9b87e 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -42558,6 +42558,7 @@ export namespace Schemas {
company_name: string;
representative_email: string;
status: string;
+ signed_pdf_stored: boolean;
created_by: LegalDocumentCreator | null;
created_at: string;
}