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(tasks): close TaskRun startup race causing TaskNotFoundError (#65948)

posthog[bot]23287d93d07c
diff --git a/products/tasks/backend/exceptions.py b/products/tasks/backend/exceptions.py
index 8c81cac11e5b..7f3671934505 100644
--- a/products/tasks/backend/exceptions.py
+++ b/products/tasks/backend/exceptions.py
@@ -39,6 +39,22 @@ class TaskNotFoundError(ProcessTaskFatalError):
pass
+class TaskRunNotReadyError(ProcessTaskTransientError):
+ """The TaskRun row is not yet visible to this activity.
+
+ Typically the creating transaction has not committed by the time the activity's
+ first read runs (the run was created inside an enclosing transaction.atomic block).
+ Retryable so the activity's existing retry policy recovers once the row is visible.
+ Intentionally does not capture to error tracking — this is an expected transient
+ window the retry absorbs, not a fault worth an issue.
+ """
+
+ def __init__(self, message: str, context: dict[str, Any]):
+ # Bypass ProcessTaskTransientError.__init__ to pass cause=None, which skips the
+ # capture_exception() call in ProcessTaskError — avoiding error-tracking noise.
+ ProcessTaskError.__init__(self, message, context, None, non_retryable=False)
+
+
class TaskInvalidStateError(ProcessTaskFatalError):
pass
diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.py
index 31b7224c783e..712f14bb14d8 100644
--- a/products/tasks/backend/models.py
+++ b/products/tasks/backend/models.py
@@ -574,14 +574,24 @@ class Task(FileSystemSyncMixin, DeletedMetaFields, models.Model):
task_run = task.create_run(mode=mode, extra_state=extra_state or None, branch=branch)
if start_workflow:
- execute_task_processing_workflow(
- task_id=str(task.id),
- run_id=str(task_run.id),
- team_id=task.team.id,
- user_id=user_id,
- create_pr=create_pr,
- slack_thread_context=slack_thread_context,
- posthog_mcp_scopes=posthog_mcp_scopes,
+ # Defer the fire-and-forget workflow start until the creating transaction commits.
+ # Otherwise, when create_and_run runs inside a transaction.atomic() block, the
+ # workflow's first activity can read the TaskRun before its row is visible and fail.
+ # on_commit runs the callback immediately in autocommit mode, so non-atomic callers
+ # are unaffected.
+ run_id = str(task_run.id)
+ team_id = task.team.id
+ task_id = str(task.id)
+ transaction.on_commit(
+ lambda: execute_task_processing_workflow(
+ task_id=task_id,
+ run_id=run_id,
+ team_id=team_id,
+ user_id=user_id,
+ create_pr=create_pr,
+ slack_thread_context=slack_thread_context,
+ posthog_mcp_scopes=posthog_mcp_scopes,
+ )
)
return task
diff --git a/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py b/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py
index 84dc0196c822..e6d6715367b1 100644
--- a/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py
+++ b/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py
@@ -17,7 +17,7 @@ from products.tasks.backend.constants import (
MODAL_VM_SANDBOX_FEATURE_FLAG,
SANDBOX_EVENT_INGEST_FEATURE_FLAG,
)
-from products.tasks.backend.exceptions import TaskInvalidStateError, TaskNotFoundError
+from products.tasks.backend.exceptions import TaskInvalidStateError, TaskRunNotReadyError
from products.tasks.backend.logic.services.sandbox_config import (
MAX_SANDBOX_CPU_CORES,
MAX_SANDBOX_MEMORY_GB,
@@ -406,8 +406,10 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskPro
"task__github_integration",
"task__github_user_integration",
).get(id=run_id)
- except ObjectDoesNotExist as e:
- raise TaskNotFoundError(f"TaskRun {run_id} not found", {"run_id": run_id}, cause=e)
+ except ObjectDoesNotExist:
+ # The row may simply not be visible yet (creating transaction not committed) or
+ # be mid-cancel/delete. Retry rather than fail fatally so the transient window recovers.
+ raise TaskRunNotReadyError(f"TaskRun {run_id} not found", {"run_id": run_id})
emit_agent_log(run_id, "debug", "Fetching task details")
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py b/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py
index d6f98a718caa..3a09ad970eca 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py
@@ -13,7 +13,7 @@ from products.tasks.backend.constants import (
MODAL_VM_SANDBOX_FEATURE_FLAG,
SANDBOX_EVENT_INGEST_FEATURE_FLAG,
)
-from products.tasks.backend.exceptions import TaskInvalidStateError, TaskNotFoundError
+from products.tasks.backend.exceptions import TaskInvalidStateError, TaskRunNotReadyError
from products.tasks.backend.models import SandboxEnvironment, Task
from products.tasks.backend.temporal.process_task.activities.get_task_processing_context import (
GetTaskProcessingContextInput,
@@ -58,13 +58,17 @@ class TestGetTaskProcessingContextActivity:
assert result.create_pr is True
@pytest.mark.django_db(transaction=True)
- def test_get_task_processing_context_task_not_found(self, activity_environment):
+ def test_get_task_processing_context_task_not_found_is_retryable(self, activity_environment):
+ # A missing TaskRun is treated as a transient (retryable) condition, not a fatal error,
+ # so the activity's retry policy can recover once a just-created row becomes visible.
non_existent_run_id = "550e8400-e29b-41d4-a716-446655440000"
input_data = GetTaskProcessingContextInput(run_id=non_existent_run_id)
- with pytest.raises(TaskNotFoundError):
+ with pytest.raises(TaskRunNotReadyError) as exc_info:
async_to_sync(activity_environment.run)(get_task_processing_context, input_data)
+ assert exc_info.value.non_retryable is False
+
@pytest.mark.django_db(transaction=True)
def test_get_task_processing_context_invalid_uuid(self, activity_environment):
invalid_run_id = "not-a-uuid"
diff --git a/products/tasks/backend/tests/test_models.py b/products/tasks/backend/tests/test_models.py
index e21c85b2a1f4..9e6c0495a9b1 100644
--- a/products/tasks/backend/tests/test_models.py
+++ b/products/tasks/backend/tests/test_models.py
@@ -56,14 +56,15 @@ class TestTask(TestCase):
user = User.objects.create(email="[email protected]")
Integration.objects.create(team=self.team, kind="github", config={})
- task = Task.create_and_run(
- team=self.team,
- title="Test Create and Run",
- description="Test Description",
- origin_product=Task.OriginProduct.USER_CREATED,
- user_id=user.id,
- repository="posthog/posthog",
- )
+ with self.captureOnCommitCallbacks(execute=True):
+ task = Task.create_and_run(
+ team=self.team,
+ title="Test Create and Run",
+ description="Test Description",
+ origin_product=Task.OriginProduct.USER_CREATED,
+ user_id=user.id,
+ repository="posthog/posthog",
+ )
self.assertIsNotNone(task.id)
self.assertEqual(task.title, "Test Create and Run")
@@ -88,15 +89,16 @@ class TestTask(TestCase):
user = User.objects.create(email="[email protected]")
Integration.objects.create(team=self.team, kind="github", config={})
- task = Task.create_and_run(
- team=self.team,
- title="Slack Task",
- description="Slack Description",
- origin_product=Task.OriginProduct.SLACK,
- user_id=user.id,
- repository="posthog/posthog",
- initial_permission_mode="bypassPermissions",
- )
+ with self.captureOnCommitCallbacks(execute=True):
+ task = Task.create_and_run(
+ team=self.team,
+ title="Slack Task",
+ description="Slack Description",
+ origin_product=Task.OriginProduct.SLACK,
+ user_id=user.id,
+ repository="posthog/posthog",
+ initial_permission_mode="bypassPermissions",
+ )
run_id = mock_execute_workflow.call_args.kwargs["run_id"]
task_run = TaskRun.objects.get(id=run_id)
@@ -108,15 +110,16 @@ class TestTask(TestCase):
user = User.objects.create(email="[email protected]")
Integration.objects.create(team=self.team, kind="github", config={})
- Task.create_and_run(
- team=self.team,
- title="Signal Task",
- description="Signal Description",
- origin_product=Task.OriginProduct.SIGNAL_REPORT,
- user_id=user.id,
- repository="posthog/posthog",
- ai_stage="research",
- )
+ with self.captureOnCommitCallbacks(execute=True):
+ Task.create_and_run(
+ team=self.team,
+ title="Signal Task",
+ description="Signal Description",
+ origin_product=Task.OriginProduct.SIGNAL_REPORT,
+ user_id=user.id,
+ repository="posthog/posthog",
+ ai_stage="research",
+ )
run_id = mock_execute_workflow.call_args.kwargs["run_id"]
task_run = TaskRun.objects.get(id=run_id)
@@ -127,14 +130,15 @@ class TestTask(TestCase):
user = User.objects.create(email="[email protected]")
Integration.objects.create(team=self.team, kind="github", config={})
- Task.create_and_run(
- team=self.team,
- title="Plain Task",
- description="Plain Description",
- origin_product=Task.OriginProduct.USER_CREATED,
- user_id=user.id,
- repository="posthog/posthog",
- )
+ with self.captureOnCommitCallbacks(execute=True):
+ Task.create_and_run(
+ team=self.team,
+ title="Plain Task",
+ description="Plain Description",
+ origin_product=Task.OriginProduct.USER_CREATED,
+ user_id=user.id,
+ repository="posthog/posthog",
+ )
run_id = mock_execute_workflow.call_args.kwargs["run_id"]
task_run = TaskRun.objects.get(id=run_id)
@@ -145,14 +149,15 @@ class TestTask(TestCase):
user = User.objects.create(email="[email protected]")
Integration.objects.create(team=self.team, kind="github", config={})
- Task.create_and_run(
- team=self.team,
- title="Plain Task",
- description="Plain Description",
- origin_product=Task.OriginProduct.USER_CREATED,
- user_id=user.id,
- repository="posthog/posthog",
- )
+ with self.captureOnCommitCallbacks(execute=True):
+ Task.create_and_run(
+ team=self.team,
+ title="Plain Task",
+ description="Plain Description",
+ origin_product=Task.OriginProduct.USER_CREATED,
+ user_id=user.id,
+ repository="posthog/posthog",
+ )
run_id = mock_execute_workflow.call_args.kwargs["run_id"]
task_run = TaskRun.objects.get(id=run_id)
@@ -163,14 +168,15 @@ class TestTask(TestCase):
user = User.objects.create(email="[email protected]")
Integration.objects.create(team=self.team, kind="github", config={})
- task = Task.create_and_run(
- team=self.team,
- title="Test Task",
- description="Test Description",
- origin_product=Task.OriginProduct.USER_CREATED,
- user_id=user.id,
- repository="posthog/posthog-js",
- )
+ with self.captureOnCommitCallbacks(execute=True):
+ task = Task.create_and_run(
+ team=self.team,
+ title="Test Task",
+ description="Test Description",
+ origin_product=Task.OriginProduct.USER_CREATED,
+ user_id=user.id,
+ repository="posthog/posthog-js",
+ )
self.assertEqual(task.repository, "posthog/posthog-js")
@@ -198,14 +204,15 @@ class TestTask(TestCase):
def test_create_and_run_public_repo_without_integration(self, mock_execute_workflow):
user = User.objects.create(email="[email protected]")
- task = Task.create_and_run(
- team=self.team,
- title="Test Task",
- description="Test Description",
- origin_product=Task.OriginProduct.USER_CREATED,
- user_id=user.id,
- repository="posthog/hedgebox",
- )
+ with self.captureOnCommitCallbacks(execute=True):
+ task = Task.create_and_run(
+ team=self.team,
+ title="Test Task",
+ description="Test Description",
+ origin_product=Task.OriginProduct.USER_CREATED,
+ user_id=user.id,
+ repository="posthog/hedgebox",
+ )
self.assertEqual(task.repository, "posthog/hedgebox")
self.assertIsNone(task.github_integration)
@@ -233,14 +240,15 @@ class TestTask(TestCase):
user = User.objects.create(email="[email protected]")
integration = Integration.objects.create(team=self.team, kind="github", config={})
- task = Task.create_and_run(
- team=self.team,
- title="Test Task",
- description="Test Description",
- origin_product=Task.OriginProduct.USER_CREATED,
- user_id=user.id,
- repository="posthog/posthog",
- )
+ with self.captureOnCommitCallbacks(execute=True):
+ task = Task.create_and_run(
+ team=self.team,
+ title="Test Task",
+ description="Test Description",
+ origin_product=Task.OriginProduct.USER_CREATED,
+ user_id=user.id,
+ repository="posthog/posthog",
+ )
self.assertEqual(task.github_integration, integration)
mock_execute_workflow.assert_called_once()
@@ -261,14 +269,15 @@ class TestTask(TestCase):
repository_cache=[{"full_name": "posthog/posthog", "id": 1}],
)
- task = Task.create_and_run(
- team=self.team,
- title="Signal Report",
- description="Research",
- origin_product=Task.OriginProduct.SIGNAL_REPORT,
- user_id=user.id,
- repository="posthog/posthog",
- )
+ with self.captureOnCommitCallbacks(execute=True):
+ task = Task.create_and_run(
+ team=self.team,
+ title="Signal Report",
+ description="Research",
+ origin_product=Task.OriginProduct.SIGNAL_REPORT,
+ user_id=user.id,
+ repository="posthog/posthog",
+ )
self.assertIsNone(task.github_integration)
self.assertEqual(task.github_user_integration, user_integration)