Skip to content

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

feat(weekly-digest): add a command to resend a digest to chosen organizations (#127259)

Harley Alexander7d0dd856053c
diff --git a/posthog/management/commands/resend_weekly_digest.py b/posthog/management/commands/resend_weekly_digest.py
new file mode 100644
index 000000000000..fa98bc300522
--- /dev/null
+++ b/posthog/management/commands/resend_weekly_digest.py
@@ -0,0 +1,87 @@
+"""Resend a weekly digest to chosen organizations from the data the scheduled run already generated.
+
+The digest data stays in the digest Redis for three days after the scheduled run, so resend within that window.
+
+Usage:
+ # Resend to organizations a failed send skipped. Members who already got it get a second copy.
+ python manage.py resend_weekly_digest --digest-key weekly-digest-2026-45 --org <uuid> --org <uuid>
+
+ # Send only to members the routing flag sends through Workflows, for example to test the workflow with staff
+ python manage.py resend_weekly_digest --digest-key weekly-digest-2026-45 --org <uuid> --workflows-only
+
+ # Log who would get the digest, without sending
+ python manage.py resend_weekly_digest --digest-key weekly-digest-2026-45 --org <uuid> --dry-run
+"""
+
+import asyncio
+from datetime import UTC, datetime
+from typing import Any
+from uuid import UUID, uuid4
+
+from django.conf import settings
+from django.core.management.base import BaseCommand, CommandError
+
+from posthog.temporal.common.client import async_connect
+from posthog.temporal.weekly_digest.types import WeeklyDigestInput
+
+DIGEST_KEY_PREFIX = "weekly-digest-"
+
+
+def period_end_for_digest_key(digest_key: str) -> datetime:
+ # The scheduled run names its key after the ISO week of its Monday, and its period ends at that Monday's midnight.
+ try:
+ year, week = (int(part) for part in digest_key.removeprefix(DIGEST_KEY_PREFIX).split("-"))
+ monday = datetime.fromisocalendar(year, week, 1)
+ except ValueError as err:
+ raise CommandError(f"Expected a digest key like {DIGEST_KEY_PREFIX}2026-45, got {digest_key!r}") from err
+ return monday.replace(tzinfo=UTC)
+
+
+class Command(BaseCommand):
+ help = "Resend a weekly digest to chosen organizations from the data the scheduled run already generated."
+
+ def add_arguments(self, parser: Any) -> None:
+ parser.add_argument(
+ "--digest-key", required=True, help="Key of the scheduled run to resend, such as weekly-digest-2026-45."
+ )
+ parser.add_argument(
+ "--org",
+ dest="organization_ids",
+ action="append",
+ required=True,
+ type=UUID,
+ help="Organization (UUID) to resend to. Repeat the option for more organizations.",
+ )
+ parser.add_argument(
+ "--workflows-only",
+ action="store_true",
+ help="Send only to members the routing flag sends through Workflows. Nobody gets a second Customer.io email.",
+ )
+ parser.add_argument("--dry-run", action="store_true", help="Log who would get the digest without sending it.")
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ digest_key: str = options["digest_key"]
+ organization_ids = [str(organization_id) for organization_id in options["organization_ids"]]
+ workflow_input = WeeklyDigestInput(
+ dry_run=options["dry_run"],
+ skip_generate=True,
+ digest_key_override=digest_key,
+ # The scheduled run marks every organization it reached as sent, including ones a failure cut short.
+ allow_already_sent=True,
+ organization_ids=organization_ids,
+ workflows_only=options["workflows_only"],
+ period_end_override=period_end_for_digest_key(digest_key),
+ )
+ workflow_id = f"weekly-digest-resend-{digest_key}-{uuid4()}"
+ asyncio.run(self._start(workflow_input, workflow_id))
+ self.stdout.write(
+ self.style.SUCCESS(
+ f"Started {workflow_id} for {len(organization_ids)} organization(s). Follow it in the Temporal UI."
+ )
+ )
+
+ async def _start(self, workflow_input: WeeklyDigestInput, workflow_id: str) -> None:
+ client = await async_connect()
+ await client.start_workflow(
+ "weekly-digest", workflow_input, id=workflow_id, task_queue=settings.WEEKLY_DIGEST_TASK_QUEUE
+ )
diff --git a/posthog/management/commands/test/test_resend_weekly_digest.py b/posthog/management/commands/test/test_resend_weekly_digest.py
new file mode 100644
index 000000000000..3256996ed226
--- /dev/null
+++ b/posthog/management/commands/test/test_resend_weekly_digest.py
@@ -0,0 +1,25 @@
+from datetime import UTC, datetime
+
+import pytest
+
+from django.core.management.base import CommandError
+
+from posthog.management.commands.resend_weekly_digest import period_end_for_digest_key
+
+
+ "digest_key,expected",
+ [
+ ("weekly-digest-2026-45", datetime(2026, 11, 2, tzinfo=UTC)),
+ # ISO week 1 of 2026 starts in December 2025.
+ ("weekly-digest-2026-1", datetime(2025, 12, 29, tzinfo=UTC)),
+ ],
+)
+def test_period_end_for_digest_key_is_the_monday_of_the_iso_week(digest_key, expected):
+ assert period_end_for_digest_key(digest_key) == expected
+
+
[email protected]("digest_key", ["weekly-digest-2026", "weekly-digest-2026-54", "my-custom-key"])
+def test_period_end_for_digest_key_rejects_keys_it_cannot_date(digest_key):
+ with pytest.raises(CommandError):
+ period_end_for_digest_key(digest_key)
diff --git a/posthog/temporal/tests/weekly_digest/test_activities.py b/posthog/temporal/tests/weekly_digest/test_activities.py
index 962462ef5960..d0f1fcda2e95 100644
--- a/posthog/temporal/tests/weekly_digest/test_activities.py
+++ b/posthog/temporal/tests/weekly_digest/test_activities.py
@@ -786,6 +786,53 @@ def test_send_weekly_digest_batch_emails_subscribed_members_once(
}
+ "listed,workflows_only,flag_answers,expected_route",
+ [
+ (True, False, [False], "customer_io"),
+ (True, True, [True], "workflows"),
+ # A Workflows-only resend must not send a second Customer.io copy.
+ (True, True, [False], None),
+ # The flag can answer differently on a second check, so one answer must decide the route.
+ (True, True, [True, False], "workflows"),
+ (False, False, [True], None),
+ ],
+)
+def test_send_weekly_digest_batch_resend_reaches_only_listed_organizations(
+ listed, workflows_only, flag_answers, expected_route, organization, team, redis_servers, common_input, digest
+):
+ subscribed = create_user(organization, "[email protected]")
+ redis_servers.digest.set(org_digest_key(digest.key, organization.id), _org_digest_json(organization, team))
+ redis_servers.digest.sadd(user_data_key(digest.key, UserDataKey.NOTIFY_TEAMS, subscribed.id), team.id)
+ record, _ = MessagingRecord.objects.get_or_create(raw_email=f"org_{organization.id}", campaign_key=digest.key)
+ record.sent_at = timezone.now()
+ record.save()
+ ph_client = MagicMock()
+ session = MagicMock()
+ session.post.return_value.status_code = 201
+ resend_input = _send_input(organization, digest, common_input, dry_run=False).model_copy(
+ update={
+ # A resend batches over the listed organizations only.
+ "batch": (0, 1),
+ "allow_already_sent": True,
+ "organization_ids": [str(organization.id) if listed else str(uuid4())],
+ "workflows_only": workflows_only,
+ }
+ )
+
+ with (
+ override_settings(**WEBHOOK_SETTINGS),
+ patch("posthog.temporal.weekly_digest.activities.get_ph_client", return_value=ph_client),
+ patch("posthog.temporal.weekly_digest.activities.posthoganalytics.feature_enabled", side_effect=flag_answers),
+ patch("posthog.temporal.weekly_digest.activities.requests.Session", return_value=session),
+ ):
+ run_sync(send_weekly_digest_batch, resend_input)
+
+ assert ph_client.capture.call_count == (expected_route == "customer_io")
+ assert session.post.call_count == (expected_route == "workflows")
+
+
@pytest.mark.parametrize(
"first_answer",
[
diff --git a/posthog/temporal/weekly_digest/README.md b/posthog/temporal/weekly_digest/README.md
index b2a42fff2f78..eee2b0ccb576 100644
--- a/posthog/temporal/weekly_digest/README.md
+++ b/posthog/temporal/weekly_digest/README.md
@@ -34,6 +34,15 @@ All send batches share one token bucket in the digest Redis that keeps posts to
The webhook refuses a body above 512,000 bytes, and a project can create thousands of events in a week. The Workflows payload carries the first six new event definitions and their total in `new_event_definitions_count`, which is what the email shows.
The workflow paces the emails themselves with its own sending rate limit.
+### Resending
+
+`python manage.py resend_weekly_digest --digest-key <key> --org <uuid>` resends a digest to the listed organizations, in the region where it runs.
+It skips generation and reads the data the scheduled run left in the digest Redis, so it works only within `redis_ttl` (3 days) of that run.
+It sends to the listed organizations even when they are marked sent, so members who already got the digest get a second copy.
+`--workflows-only` sends only to members the routing flag sends through Workflows, so nobody gets a second Customer.io email.
+`--dry-run` logs who would get the digest.
+The period in the email comes from the digest key, not from the day of the resend.
+
## Redis Storage Structure
Data is stored with keys prefixed by `{digest_key}` (e.g., `weekly-digest-2024-01`).
diff --git a/posthog/temporal/weekly_digest/activities.py b/posthog/temporal/weekly_digest/activities.py
index f2b064f27542..3b0281611c3f 100644
--- a/posthog/temporal/weekly_digest/activities.py
+++ b/posthog/temporal/weekly_digest/activities.py
@@ -869,11 +869,16 @@ def generate_product_suggestion_lookup(input: GenerateDigestDataBatchInput) -> N
_generate_product_suggestion_lookup(input)
+def _organizations_to_send(organization_ids: list[str] | None) -> QuerySet:
+ organizations = query_orgs_for_digest()
+ return organizations if organization_ids is None else organizations.filter(id__in=organization_ids)
+
+
@activity.defn(name="count-organizations")
@asyncify
-def count_organizations() -> int:
+def count_organizations(organization_ids: list[str] | None = None) -> int:
with HeartbeaterSync(logger=LOGGER):
- return query_orgs_for_digest().count()
+ return _organizations_to_send(organization_ids).count()
def _cut_team_id_ranges(team_ids: list[int], batch_size: int) -> list[TeamIdRange]:
@@ -1195,7 +1200,7 @@ def _send_weekly_digest_batch(input: SendWeeklyDigestBatchInput) -> None:
try:
with _digest_redis(input.common) as r:
batch_start, batch_end = input.batch
- for organization in query_orgs_for_digest()[batch_start:batch_end]:
+ for organization in _organizations_to_send(input.organization_ids)[batch_start:batch_end]:
_raise_if_cancelled()
partial = False
try:
@@ -1262,6 +1267,13 @@ def _send_weekly_digest_batch(input: SendWeeklyDigestBatchInput) -> None:
empty_user_digest_count += 1
continue
+ # One evaluation decides the route. A second one could disagree and send a Workflows-only
+ # resend to Customer.io.
+ routes_to_workflows = _routes_to_workflows(user)
+ # A Workflows-only resend never captures for Customer.io, so nobody there gets a second copy.
+ if input.workflows_only and not routes_to_workflows:
+ continue
+
payload = digest_for_user.render_payload(input.digest)
if input.dry_run:
@@ -1270,7 +1282,7 @@ def _send_weekly_digest_batch(input: SendWeeklyDigestBatchInput) -> None:
digest=payload,
user_email=user.email,
)
- elif _routes_to_workflows(user):
+ elif routes_to_workflows:
workflows_payload = digest_for_user.render_payload(
input.digest, event_definitions_limit=WORKFLOWS_EVENT_DEFINITIONS_LIMIT
)
diff --git a/posthog/temporal/weekly_digest/types.py b/posthog/temporal/weekly_digest/types.py
index a6f93ed11cff..7f56346b3dfd 100644
--- a/posthog/temporal/weekly_digest/types.py
+++ b/posthog/temporal/weekly_digest/types.py
@@ -34,6 +34,10 @@ class WeeklyDigestInput(BaseModel):
digest_key_override: str | None = None
allow_already_sent: bool = False
common: CommonInput = CommonInput()
+ # A resend sets these. None sends to every organization.
+ organization_ids: list[str] | None = None
+ workflows_only: bool = False
+ period_end_override: datetime | None = None
class GenerateDigestDataInput(BaseModel):
@@ -65,6 +69,8 @@ class SendWeeklyDigestInput(BaseModel):
allow_already_sent: bool
digest: Digest
common: CommonInput
+ organization_ids: list[str] | None = None
+ workflows_only: bool = False
class SendWeeklyDigestBatchInput(BaseModel):
@@ -73,6 +79,8 @@ class SendWeeklyDigestBatchInput(BaseModel):
allow_already_sent: bool
digest: Digest
common: CommonInput
+ organization_ids: list[str] | None = None
+ workflows_only: bool = False
class DigestDashboard(BaseModel):
diff --git a/posthog/temporal/weekly_digest/workflows.py b/posthog/temporal/weekly_digest/workflows.py
index 953c6d0dfd0e..e5feae7900a9 100644
--- a/posthog/temporal/weekly_digest/workflows.py
+++ b/posthog/temporal/weekly_digest/workflows.py
@@ -82,7 +82,7 @@ class WeeklyDigestWorkflow(PostHogWorkflow):
input.common.django_redis_url = settings.REDIS_URL
year, week, _ = datetime.now().isocalendar()
- period_end = datetime.now(UTC).replace(hour=0, minute=0, second=0, microsecond=0)
+ period_end = input.period_end_override or datetime.now(UTC).replace(hour=0, minute=0, second=0, microsecond=0)
period_start = period_end - timedelta(days=7)
digest = Digest(
@@ -114,6 +114,8 @@ class WeeklyDigestWorkflow(PostHogWorkflow):
allow_already_sent=input.allow_already_sent,
digest=digest,
common=input.common,
+ organization_ids=input.organization_ids,
+ workflows_only=input.workflows_only,
),
parent_close_policy=workflow.ParentClosePolicy.REQUEST_CANCEL,
execution_timeout=timedelta(hours=15),
@@ -236,8 +238,10 @@ class SendWeeklyDigestWorkflow(PostHogWorkflow):
@workflow.run
async def run(self, input: SendWeeklyDigestInput) -> None:
+ # Only a resend passes its organizations, so the scheduled run calls the activity exactly as before.
organization_count = await workflow.execute_activity(
count_organizations,
+ args=[input.organization_ids] if input.organization_ids is not None else [],
start_to_close_timeout=timedelta(minutes=5),
retry_policy=common.RetryPolicy(
maximum_attempts=2,
@@ -259,6 +263,8 @@ class SendWeeklyDigestWorkflow(PostHogWorkflow):
allow_already_sent=input.allow_already_sent,
digest=input.digest,
common=input.common,
+ organization_ids=input.organization_ids,
+ workflows_only=input.workflows_only,
),
# Batches share the pace of the captures for Workflows, so a batch can wait well past 30 minutes.
start_to_close_timeout=timedelta(hours=2),