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(self-driving): frozen dataclass returns and renames (#76131)

Arno Hillencc2e6e26f76c
diff --git a/posthog/api/github_callback/state.py b/posthog/api/github_callback/state.py
index 7337c97f2b22..07ca40eb5c53 100644
--- a/posthog/api/github_callback/state.py
+++ b/posthog/api/github_callback/state.py
@@ -14,6 +14,7 @@ from posthog.api.github_callback.types import (
GitHubAuthorizeState,
team_id_from_next_url,
)
+from posthog.dataclasses import frozen
from posthog.models import Team, User
from posthog.models.organization import OrganizationMembership
from posthog.user_permissions import UserPermissions
@@ -150,6 +151,13 @@ def consume_authorize_state(token: str, *, user_id: int | None = None) -> GitHub
return state
+@frozen
+class ConsumedAuthorizeState:
+ state_token: str
+ next_url: str
+ team_id: int | None
+
+
def consume_github_authorize_state(
request: Request,
state_raw: str | None,
@@ -157,7 +165,7 @@ def consume_github_authorize_state(
setup_action: str = "",
code: str | None = None,
installation_id: str | None = None,
-) -> tuple[str, str, int | None]:
+) -> ConsumedAuthorizeState:
user_id = authenticated_user_id(request)
pending_token = cache.get(unified_authorize_pending_cache_key(user_id))
cached = cache.get(unified_authorize_cache_key(str(pending_token))) if pending_token else None
@@ -192,4 +200,4 @@ def consume_github_authorize_state(
cache.delete(unified_authorize_cache_key(expected_token))
cache.delete(unified_authorize_pending_cache_key(user_id))
- return expected_token, param_next or cached_next, team_id
+ return ConsumedAuthorizeState(state_token=expected_token, next_url=param_next or cached_next, team_id=team_id)
diff --git a/posthog/api/github_callback/team_services.py b/posthog/api/github_callback/team_services.py
index 3141666ce644..032db0c25e99 100644
--- a/posthog/api/github_callback/team_services.py
+++ b/posthog/api/github_callback/team_services.py
@@ -269,9 +269,9 @@ def finish_team_github_setup_update(
next_url = fallback_next_url or ""
if cache.get(github_callback_state.unified_authorize_pending_cache_key(user.id)) is not None:
- _, next_url, _ = github_callback_state.consume_github_authorize_state(
+ next_url = github_callback_state.consume_github_authorize_state(
request, state_raw, setup_action="update", code=None, installation_id=installation_id_str
- )
+ ).next_url
refreshed = refresh_team_github_integration(user, team_id, installation_id_str, existing=existing)
return TeamGitHubFinishSetupResult(
@@ -296,9 +296,9 @@ def execute_team_github_finish_setup(
installation_id_str = str(installation_id)
- _state_token, next_url, _team_id = github_callback_state.consume_github_authorize_state(
+ next_url = github_callback_state.consume_github_authorize_state(
request, state_raw, setup_action=setup_action, code=code, installation_id=installation_id_str
- )
+ ).next_url
is_already_installed = setup_action == "update" or not code
connect_from = _connect_from_for_next(next_url)
diff --git a/posthog/test/dataclass_frozen_baseline.txt b/posthog/test/dataclass_frozen_baseline.txt
index 24cdd090ae39..f3b805adfed3 100644
--- a/posthog/test/dataclass_frozen_baseline.txt
+++ b/posthog/test/dataclass_frozen_baseline.txt
@@ -194,7 +194,6 @@
1 products/streamlit_apps/backend/logic/zip_validator.py
1 products/surveys/backend/summarization/llm/gemini.py
1 products/tasks/backend/logic/services/agent_command.py
-1 products/tasks/backend/logic/services/custom_prompt_multi_turn_runner.py
1 products/tasks/backend/logic/services/modal_provision_diagnostics.py
1 products/tasks/backend/logic/services/sandbox.py
1 products/tasks/backend/logic/services/warm.py
diff --git a/products/mcp_store/backend/facade/api.py b/products/mcp_store/backend/facade/api.py
index 59b5b947df1a..1713f3c5a724 100644
--- a/products/mcp_store/backend/facade/api.py
+++ b/products/mcp_store/backend/facade/api.py
@@ -19,7 +19,7 @@ from products.mcp_store.backend.agents import (
get_built_in_agent,
is_builtin_agent_enforcement_enabled,
)
-from products.mcp_store.backend.facade.contracts import ActiveInstallationInfo
+from products.mcp_store.backend.facade.contracts import ActiveInstallation
from products.mcp_store.backend.gateway import (
agent_grant_owner_label,
agent_grant_proxy_path,
@@ -127,8 +127,8 @@ def _is_oauth_ready(installation: MCPServerInstallation) -> bool:
return True
-def _to_info(installation: MCPServerInstallation, team_id: int) -> ActiveInstallationInfo:
- return ActiveInstallationInfo(
+def _to_info(installation: MCPServerInstallation, team_id: int) -> ActiveInstallation:
+ return ActiveInstallation(
id=str(installation.id),
name=_resolve_name(installation),
proxy_path=f"/api/environments/{team_id}/mcp_server_installations/{installation.id}/proxy/",
@@ -210,13 +210,13 @@ def _agent_installation_infos(
agent_account: MCPServiceAccount,
mounts: list[tuple[MCPServiceAccountServerAccess, MCPServerInstallation]],
credential_owner_id: int | None,
-) -> list[ActiveInstallationInfo]:
+) -> list[ActiveInstallation]:
if not mounts:
return []
proxy_token = create_gateway_agent_token(agent_account, credential_owner_id=credential_owner_id)
mounts_per_server = Counter(access.gateway_server_id for access, _installation in mounts)
- infos: list[ActiveInstallationInfo] = []
+ infos: list[ActiveInstallation] = []
for access, installation in mounts:
name = _resolve_name(installation)
if mounts_per_server[access.gateway_server_id] > 1:
@@ -224,7 +224,7 @@ def _agent_installation_infos(
# the same server need distinct ones.
name = f"{name} ({agent_grant_owner_label(access)})"
infos.append(
- ActiveInstallationInfo(
+ ActiveInstallation(
id=str(installation.id),
name=name,
proxy_path=agent_grant_proxy_path(access),
@@ -235,7 +235,7 @@ def _agent_installation_infos(
return infos
-def get_active_installations(team_id: int, user_id: int) -> list[ActiveInstallationInfo]:
+def get_active_installations(team_id: int, user_id: int) -> list[ActiveInstallation]:
"""Return active, ready-to-use personal MCP installations for a user.
Filters out disabled installations and OAuth installations that
@@ -253,7 +253,7 @@ def get_active_installations(team_id: int, user_id: int) -> list[ActiveInstallat
logger.warning("Error fetching MCP installations", error=str(e), team_id=team_id)
return []
- results: list[ActiveInstallationInfo] = []
+ results: list[ActiveInstallation] = []
for installation in installations:
if not _is_oauth_ready(installation):
logger.debug(
@@ -276,7 +276,7 @@ def get_installations_for_sandbox(
task_agent_key: str | None = None,
credential_owner_id: int | None = None,
allowed_gateway_server_ids: list[str] | None = None,
-) -> list[ActiveInstallationInfo]:
+) -> list[ActiveInstallation]:
"""Return MCP installations for sandbox agent use.
Generic tasks retain the legacy team-shared installation behavior. A
@@ -362,7 +362,7 @@ def get_installations_for_sandbox(
logger.warning("Error fetching MCP installations for sandbox", error=str(e), team_id=team_id)
return []
- results: list[ActiveInstallationInfo]
+ results: list[ActiveInstallation]
if agent_key is not None:
results = (
_agent_installation_infos(agent_account, agent_mounts, credential_owner_id)
diff --git a/products/mcp_store/backend/facade/contracts.py b/products/mcp_store/backend/facade/contracts.py
index 1e5120a27d6e..c02aa9b0cc3e 100644
--- a/products/mcp_store/backend/facade/contracts.py
+++ b/products/mcp_store/backend/facade/contracts.py
@@ -9,7 +9,7 @@ from dataclasses import dataclass, field
@dataclass(frozen=True)
-class ActiveInstallationInfo:
+class ActiveInstallation:
"""An MCP server installation that is active and ready to use."""
id: str
diff --git a/products/mcp_store/backend/test/test_facade.py b/products/mcp_store/backend/test/test_facade.py
index af803f6978f9..b6030a182f3d 100644
--- a/products/mcp_store/backend/test/test_facade.py
+++ b/products/mcp_store/backend/test/test_facade.py
@@ -12,7 +12,7 @@ from products.mcp_store.backend.agents import (
resolve_gateway_agent_token,
)
from products.mcp_store.backend.facade.api import get_active_installations, get_installations_for_sandbox
-from products.mcp_store.backend.facade.contracts import ActiveInstallationInfo
+from products.mcp_store.backend.facade.contracts import ActiveInstallation
from products.mcp_store.backend.models import (
MCPGatewayServer,
MCPMemberServerRevocation,
@@ -42,7 +42,7 @@ class TestGetActiveInstallations(BaseTest):
results = get_active_installations(self.team.id, self.user.id)
assert results == [
- ActiveInstallationInfo(
+ ActiveInstallation(
id=str(installation.id),
name="Linear",
proxy_path=f"/api/environments/{self.team.id}/mcp_server_installations/{installation.id}/proxy/",
@@ -359,7 +359,7 @@ class TestGetInstallationsForSandbox(BaseTest):
granted_by=self.user,
)
- def resolve(credential_owner_id: int | None) -> list[ActiveInstallationInfo]:
+ def resolve(credential_owner_id: int | None) -> list[ActiveInstallation]:
return get_installations_for_sandbox(
self.team.id,
task_origin="support_reply",
@@ -392,7 +392,7 @@ class TestGetInstallationsForSandbox(BaseTest):
granted_by=self.user,
)
- def resolve() -> list[ActiveInstallationInfo]:
+ def resolve() -> list[ActiveInstallation]:
return get_installations_for_sandbox(
self.team.id,
task_origin="support_reply",
@@ -437,7 +437,7 @@ class TestGetInstallationsForSandbox(BaseTest):
scope=scope,
)
- def _agent_results(self, credential_owner_id: int | None) -> list[ActiveInstallationInfo]:
+ def _agent_results(self, credential_owner_id: int | None) -> list[ActiveInstallation]:
return get_installations_for_sandbox(
self.team.id,
task_origin="support_reply",
diff --git a/products/posthog_ai/eval_harness/runner.py b/products/posthog_ai/eval_harness/runner.py
index cb6a8952463e..8b4658e7b32d 100644
--- a/products/posthog_ai/eval_harness/runner.py
+++ b/products/posthog_ai/eval_harness/runner.py
@@ -111,10 +111,8 @@ async def run_eval_case(
workflow_id = task_run.get_workflow_id(task.id, task_run.id)
client = await async_connect()
handle = client.get_workflow_handle(workflow_id)
- last_message, full_log_opt, _, _ = await poll_for_turn(
- task_run, verbose=True, output_fn=lambda msg: logger.info("agent: %s", msg)
- )
- full_log = full_log_opt or ""
+ turn = await poll_for_turn(task_run, verbose=True, output_fn=lambda msg: logger.info("agent: %s", msg))
+ full_log = turn.full_log or ""
duration = time.monotonic() - start
logger.info(
@@ -122,7 +120,7 @@ async def run_eval_case(
case.name,
duration,
len(full_log),
- last_message or "(none)",
+ turn.last_message or "(none)",
)
artifacts = _parse_artifacts_from_log(full_log, duration, agent_finished=True)
completion_task = asyncio.create_task(_finish_workflow(handle, status="completed", reason=None))
diff --git a/products/posthog_ai/eval_harness/test/test_sandboxed_harness.py b/products/posthog_ai/eval_harness/test/test_sandboxed_harness.py
index 4e94244513ed..6b22b81bbdb8 100644
--- a/products/posthog_ai/eval_harness/test/test_sandboxed_harness.py
+++ b/products/posthog_ai/eval_harness/test/test_sandboxed_harness.py
@@ -18,6 +18,7 @@ from products.posthog_ai.eval_harness.config import SandboxedEvalCase
from products.posthog_ai.eval_harness.harness.cli import parse_args
from products.posthog_ai.eval_harness.harness.live_server import EvalLiveServer
from products.posthog_ai.eval_harness.harness.providers import ModalProviderStrategy, SandboxProviderStrategy
+from products.tasks.backend.facade.agents import TurnPollResult
class _FakeWorkflowHandle:
@@ -149,7 +150,11 @@ async def test_success_waits_for_workflow_cleanup_before_returning(monkeypatch:
_patch_runner_boundaries(
monkeypatch,
handle,
- AsyncMock(return_value=("done", '{"notification": {}}', None, None)),
+ AsyncMock(
+ return_value=TurnPollResult(
+ last_message="done", full_log='{"notification": {}}', total_lines=0, printed_lines=0
+ )
+ ),
)
case_task = asyncio.create_task(
@@ -223,7 +228,11 @@ async def test_unconfirmed_success_is_an_infrastructure_error(monkeypatch: pytes
_patch_runner_boundaries(
monkeypatch,
handle,
- AsyncMock(return_value=("done", '{"notification": {}}', None, None)),
+ AsyncMock(
+ return_value=TurnPollResult(
+ last_message="done", full_log='{"notification": {}}', total_lines=0, printed_lines=0
+ )
+ ),
)
monkeypatch.setattr(runner, "WORKFLOW_COMPLETION_GRACE_SECONDS", 0.01)
monkeypatch.setattr(runner, "WORKFLOW_CANCELLATION_GRACE_SECONDS", 0.01)
diff --git a/products/tasks/backend/facade/agents.py b/products/tasks/backend/facade/agents.py
index 2fa03cf136e3..296b75c42cc5 100644
--- a/products/tasks/backend/facade/agents.py
+++ b/products/tasks/backend/facade/agents.py
@@ -12,6 +12,7 @@ from products.tasks.backend.logic.services.custom_prompt_internals import (
CustomPromptSandboxContext,
EmptyAgentTurnError,
OutputFn,
+ TurnPollResult,
TurnPollTimeout,
create_task_and_trigger,
extract_json_from_text,
@@ -28,6 +29,7 @@ __all__ = [
"LocalSkillsCache",
"MultiTurnSession",
"OutputFn",
+ "TurnPollResult",
"TurnPollTimeout",
"create_task_and_trigger",
"extract_json_from_text",
diff --git a/products/tasks/backend/logic/services/custom_prompt_internals.py b/products/tasks/backend/logic/services/custom_prompt_internals.py
index 40e5899e9dd7..f00216f8a832 100644
--- a/products/tasks/backend/logic/services/custom_prompt_internals.py
+++ b/products/tasks/backend/logic/services/custom_prompt_internals.py
@@ -13,6 +13,7 @@ from django.db import InterfaceError, OperationalError, close_old_connections
from asgiref.sync import sync_to_async
+from posthog.dataclasses import frozen
from posthog.models.team.team import Team
from posthog.storage import object_storage
from posthog.storage.object_storage import ObjectStorageError
@@ -285,6 +286,14 @@ async def _refresh_task_run(task_run_id) -> TaskRun:
return await sync_to_async(_read)()
+@frozen
+class TurnPollResult:
+ last_message: str
+ full_log: str | None
+ total_lines: int
+ printed_lines: int
+
+
async def poll_for_turn(
task_run,
*,
@@ -294,7 +303,7 @@ async def poll_for_turn(
output_fn: OutputFn = None,
workflow_handle: WorkflowHandle | None = None,
max_poll_seconds: int | None = None,
-) -> tuple[str, str | None, int, int]:
+) -> TurnPollResult:
"""Poll S3 logs until the agent finishes a turn.
`max_poll_seconds` overrides the default poll budget for callers whose activity
@@ -331,7 +340,7 @@ async def poll_for_turn(
logger.warning("custom_prompt - poll_for_turn: failed to send workflow heartbeat", exc_info=True)
try:
# Poll the logs.
- finished, last_message, full_log, total_lines, empty_end_turn, refused = await sync_to_async(
+ log_state = await sync_to_async(
# thread_sensitive=False because of pure I/O (object_storage.read + JSON parsing) and doesn't touch the ORM
_check_logs,
thread_sensitive=False,
@@ -354,9 +363,9 @@ async def poll_for_turn(
# never clear, starving the dropped-finalization salvage of the silence window it needs. This
# mirrors the side-channel discounting the tail check already does in
# _ended_on_pending_finalization.
- if total_lines > skip_lines:
- new_lines = (full_log or "").strip().split("\n")[skip_lines:]
- relevant_growth = (total_lines - skip_lines) - _transient_growth(new_lines)
+ if log_state.total_lines > skip_lines:
+ new_lines = (log_state.full_log or "").strip().split("\n")[skip_lines:]
+ relevant_growth = (log_state.total_lines - skip_lines) - _transient_growth(new_lines)
if relevant_growth > 0:
turn_relevant_lines += relevant_growth
last_new_lines_at = elapsed
@@ -367,50 +376,60 @@ async def poll_for_turn(
"custom_prompt - poll_for_turn: no new S3 log lines for %ds, run=%s, total_lines=%d",
stale_seconds,
task_run.id,
- total_lines,
+ log_state.total_lines,
)
# Detect how many lines were printed in this poll
- printed_lines = _stream_new_lines(full_log, printed_lines, verbose=verbose, output_fn=output_fn)
+ printed_lines = _stream_new_lines(log_state.full_log, printed_lines, verbose=verbose, output_fn=output_fn)
# Fail the turn immediately on a provider refusal — the EmptyAgentTurnError channel gives
# it the in-session nudge retry, then the caller's activity retry, instead of a dead poll.
- if refused:
+ if log_state.refused:
logger.warning(
"custom_prompt - poll_for_turn: agent refused the turn (stopReason=refusal), run=%s total_lines=%d",
task_run.id,
- total_lines,
+ log_state.total_lines,
)
raise EmptyAgentTurnError(
f"Agent refused the turn (stopReason=refusal) for run={task_run.id}",
- total_lines=total_lines,
+ total_lines=log_state.total_lines,
printed_lines=printed_lines,
)
- if last_message:
- latest_assistant_text = last_message
+ if log_state.last_message:
+ latest_assistant_text = log_state.last_message
# If success
- if finished and last_message:
- return last_message, full_log, total_lines, printed_lines
+ if log_state.agent_finished and log_state.last_message:
+ return TurnPollResult(
+ last_message=log_state.last_message,
+ full_log=log_state.full_log,
+ total_lines=log_state.total_lines,
+ printed_lines=printed_lines,
+ )
# Surface empty end_turn to the multi-turn session, so it can retry
# the prompt instead of us polling until MAX_POLL_SECONDS.
- if empty_end_turn:
+ if log_state.empty_end_turn:
# If the agent emitted text in an earlier poll of this same turn, the turn
# is genuinely complete — end_turn just landed in a later slice.
if latest_assistant_text is not None:
- return latest_assistant_text, full_log, total_lines, printed_lines
+ return TurnPollResult(
+ last_message=latest_assistant_text,
+ full_log=log_state.full_log,
+ total_lines=log_state.total_lines,
+ printed_lines=printed_lines,
+ )
logger.warning(
"custom_prompt - poll_for_turn: empty end_turn detected (no agent_message), run=%s total_lines=%d",
task_run.id,
- total_lines,
+ log_state.total_lines,
)
# Actual end_turn with no message, need to retry the step
raise EmptyAgentTurnError(
f"Agent emitted end_turn with no agent_message for run={task_run.id}",
- total_lines=total_lines,
+ total_lines=log_state.total_lines,
printed_lines=printed_lines,
)
# Keep the cursor monotonic — S3 eventual-consistency can briefly return fewer lines than the
# prior poll; without the clamp we'd re-parse old lines. Doubles as the line-count high-water
# mark handed to salvage: every line up to here was seen (and watched go quiet) during polling.
- skip_lines = max(skip_lines, total_lines)
+ skip_lines = max(skip_lines, log_state.total_lines)
refreshed = await _refresh_task_run(task_run.id)
if refreshed.status in {
TaskRun.Status.COMPLETED,
@@ -425,7 +444,7 @@ async def poll_for_turn(
task_run.id,
elapsed,
elapsed - last_new_lines_at,
- total_lines,
+ log_state.total_lines,
)
return await _drain_final_log(
task_run,
@@ -497,9 +516,7 @@ async def poll_for_turn(
)
-async def _read_turn_log_with_retry(
- task_run, *, skip_lines: int, context: str
-) -> tuple[bool, str | None, str | None, int, bool, bool]:
+async def _read_turn_log_with_retry(task_run, *, skip_lines: int, context: str) -> TurnLogState:
"""Read the turn log via _check_logs, retrying transient ObjectStorageError up to
MAX_CONSECUTIVE_STORAGE_ERRORS times (one POLL_INTERVAL_SECONDS apart). Re-raises the error
if every attempt fails, so a single S3 blip doesn't fail an otherwise-recoverable turn.
@@ -537,7 +554,7 @@ async def _salvage_dropped_finalization(
stale_seconds: int,
verbose: bool,
output_fn: OutputFn,
-) -> tuple[str, str | None, int, int] | None:
+) -> TurnPollResult | None:
"""Recover a turn whose closing end_turn was dropped (final message + null-cost usage_update,
then silence). Re-reads from the start-of-turn cursor so a chunked response is recovered in full.
@@ -551,20 +568,25 @@ async def _salvage_dropped_finalization(
Declining falls back to the caller's timeout failure. A storage outage on the reread propagates
(like the poll loop and terminal drain) rather than masquerading as a timeout."""
- finished, last_message, full_log, total_lines, _, _ = await _read_turn_log_with_retry(
+ log_state = await _read_turn_log_with_retry(
task_run, skip_lines=original_skip_lines, context="salvage_dropped_finalization"
)
- if finished and last_message is not None:
- printed_lines = _stream_new_lines(full_log, printed_lines, verbose=verbose, output_fn=output_fn)
+ if log_state.agent_finished and log_state.last_message is not None:
+ printed_lines = _stream_new_lines(log_state.full_log, printed_lines, verbose=verbose, output_fn=output_fn)
logger.warning(
"custom_prompt - salvage_dropped_finalization: end_turn recovered on reread at poll timeout "
"(%ds) — completing, run=%s total_lines=%d",
elapsed,
task_run.id,
- total_lines,
+ log_state.total_lines,
)
- return last_message, full_log, total_lines, printed_lines
- if last_message is None or not _ended_on_pending_finalization(full_log):
+ return TurnPollResult(
+ last_message=log_state.last_message,
+ full_log=log_state.full_log,
+ total_lines=log_state.total_lines,
+ printed_lines=printed_lines,
+ )
+ if log_state.last_message is None or not _ended_on_pending_finalization(log_state.full_log):
return None
# The fingerprint also matches a mid-turn pause between chunks. The log is append-only, so the only
# benign turn-relevant growth since polling is the finalization usage_update itself landing late
@@ -574,8 +596,8 @@ async def _salvage_dropped_finalization(
# in this post-poll window; they carry no turn-state and must be discounted, or one arriving
# alongside the late usage_update would push raw growth past the threshold and wrongly decline the
# very dropped-finalization case this path recovers.
- new_lines = (full_log or "").strip().split("\n")[max_total_lines_seen:]
- relevant_growth = (total_lines - max_total_lines_seen) - _transient_growth(new_lines)
+ new_lines = (log_state.full_log or "").strip().split("\n")[max_total_lines_seen:]
+ relevant_growth = (log_state.total_lines - max_total_lines_seen) - _transient_growth(new_lines)
if relevant_growth > 1:
logger.warning(
"custom_prompt - salvage_dropped_finalization: reread grew %d turn-relevant line(s) past "
@@ -585,16 +607,21 @@ async def _salvage_dropped_finalization(
task_run.id,
)
return None
- printed_lines = _stream_new_lines(full_log, printed_lines, verbose=verbose, output_fn=output_fn)
+ printed_lines = _stream_new_lines(log_state.full_log, printed_lines, verbose=verbose, output_fn=output_fn)
logger.warning(
"custom_prompt - salvage_dropped_finalization: end_turn missing, turn-accounting tail present, "
"stale %ds at poll timeout (%ds) — salvaging last message, run=%s total_lines=%d",
stale_seconds,
elapsed,
task_run.id,
- total_lines,
+ log_state.total_lines,
+ )
+ return TurnPollResult(
+ last_message=log_state.last_message,
+ full_log=log_state.full_log,
+ total_lines=log_state.total_lines,
+ printed_lines=printed_lines,
)
- return last_message, full_log, total_lines, printed_lines
async def _drain_final_log(
@@ -606,7 +633,7 @@ async def _drain_final_log(
original_skip_lines: int,
verbose: bool,
output_fn: OutputFn,
-) -> tuple[str, str | None, int, int]:
+) -> TurnPollResult:
"""
Drain one last S3 read after the TaskRun hit a terminal status. S3 may not have flushed the final agent_message
before Temporal marked the run done, so we retry the read. Raises RuntimeError if no message is recoverable.
@@ -618,17 +645,20 @@ async def _drain_final_log(
stale earlier-turn response in multi-turn sessions). For single-turn callers `original_skip_lines == 0`, so
the scan covers the full log as before. The walk is idempotent and only runs once at terminal status.
"""
- _, final_message, final_log, final_lines, final_empty_end_turn, _ = await _read_turn_log_with_retry(
- task_run, skip_lines=original_skip_lines, context="drain_final_log"
- )
- printed_lines = _stream_new_lines(final_log, printed_lines, verbose=verbose, output_fn=output_fn)
- if final_message:
- return final_message, final_log, final_lines, printed_lines
+ final_state = await _read_turn_log_with_retry(task_run, skip_lines=original_skip_lines, context="drain_final_log")
+ printed_lines = _stream_new_lines(final_state.full_log, printed_lines, verbose=verbose, output_fn=output_fn)
+ if final_state.last_message:
+ return TurnPollResult(
+ last_message=final_state.last_message,
+ full_log=final_state.full_log,
+ total_lines=final_state.total_lines,
+ printed_lines=printed_lines,
+ )
# Prefer the agent's own classified error over the generic terminal-status message
# (Temporal's "Activity task failed"). Only on FAILED — CANCELLED is a user action and
# COMPLETED-with-no-message is the empty-turn path, neither of which we want to relabel.
if refreshed_status == TaskRun.Status.FAILED:
- agent_error = _extract_agent_error(final_log, skip_lines=original_skip_lines)
+ agent_error = _extract_agent_error(final_state.full_log, skip_lines=original_skip_lines)
if agent_error is not None:
cause_text = agent_error.describe()
# Persist the real cause so the TaskRun stops showing "Activity task failed".
@@ -637,7 +667,7 @@ async def _drain_final_log(
f"custom_prompt - drain_final_log: TaskRun reached terminal status={refreshed_status} "
f"(cause: {cause_text})"
)
- reason = "end_turn with empty response" if final_empty_end_turn else "no agent message"
+ reason = "end_turn with empty response" if final_state.empty_end_turn else "no agent message"
cause = f" (cause: {error_message})" if error_message else ""
raise RuntimeError(
f"custom_prompt - drain_final_log: TaskRun reached terminal status={refreshed_status}{cause} — {reason}"
@@ -731,21 +761,45 @@ def _stream_new_lines(
return max(printed_lines, len(lines))
-def _check_logs(task_run, skip_lines: int = 0) -> tuple[bool, str | None, str | None, int, bool, bool]:
+@frozen
+class TurnLogState:
+ agent_finished: bool
+ last_message: str | None
+ full_log: str | None
+ total_lines: int
+ empty_end_turn: bool
+ refused: bool
+
+
+def _check_logs(task_run, skip_lines: int = 0) -> TurnLogState:
"""
Parse S3 logs. When skip_lines > 0, only lines after that offset are inspected for end_turn
and agent messages. This avoids re-parsing the entire log on every poll cycle.
- The final tuple element flags a provider refusal (stopReason "refusal") — a terminal turn
+ `refused` flags a provider refusal (stopReason "refusal") — a terminal turn
state: without it the poll loop would wait out its whole budget on a turn that already died.
"""
log_content = object_storage.read(task_run.log_url, missing_ok=True) or ""
if not log_content.strip():
- return False, None, None, 0, False, False
+ return TurnLogState(
+ agent_finished=False,
+ last_message=None,
+ full_log=None,
+ total_lines=0,
+ empty_end_turn=False,
+ refused=False,
+ )
all_lines = log_content.strip().split("\n")
total_lines = len(all_lines)
# Eventual consistency: if S3 returns fewer lines than expected, no new data
if total_lines <= skip_lines:
- return False, None, log_content, total_lines, False, False
+ return TurnLogState(
+ agent_finished=False,
+ last_message=None,
+ full_log=log_content,
+ total_lines=total_lines,
+ empty_end_turn=False,
+ refused=False,
+ )
lines_to_parse = all_lines[skip_lines:]
agent_finished = False
refused = False
@@ -802,11 +856,32 @@ def _check_logs(task_run, skip_lines: int = 0) -> tuple[bool, str | None, str |
# A refused turn must not surface its partial text — the caller would mistake it for the
# turn's real response.
if refused:
- return False, None, log_content, total_lines, False, True
+ return TurnLogState(
+ agent_finished=False,
+ last_message=None,
+ full_log=log_content,
+ total_lines=total_lines,
+ empty_end_turn=False,
+ refused=True,
+ )
# If we found end_turn but no agent message in the new lines, flag it as an empty turn.
if agent_finished and latest_text is None:
- return False, None, log_content, total_lines, True, False
- return agent_finished, latest_text, log_content, total_lines, False, False
+ return TurnLogState(
+ agent_finished=False,
+ last_message=None,
+ full_log=log_content,
+ total_lines=total_lines,
+ empty_end_turn=True,
+ refused=False,
+ )
+ return TurnLogState(
+ agent_finished=agent_finished,
+ last_message=latest_text,
+ full_log=log_content,
+ total_lines=total_lines,
+ empty_end_turn=False,
+ refused=False,
+ )
def _is_failed_progress(notification: dict) -> bool:
diff --git a/products/tasks/backend/logic/services/custom_prompt_multi_turn_runner.py b/products/tasks/backend/logic/services/custom_prompt_multi_turn_runner.py
index d288a5d7ad28..3b31114bd34f 100644
--- a/products/tasks/backend/logic/services/custom_prompt_multi_turn_runner.py
+++ b/products/tasks/backend/logic/services/custom_prompt_multi_turn_runner.py
@@ -34,7 +34,8 @@ _EMPTY_TURN_RETRY_NUDGE = "\n\nPlease respond now with the JSON object matching
_ModelT = TypeVar("_ModelT", bound=BaseModel)
-@dataclass
+# Mutable: per-turn log offsets (`log_lines_seen`, `printed_lines`) are updated in place.
+@dataclass(frozen=False)
class MultiTurnSession:
task: Task
task_run: TaskRun
@@ -222,13 +223,15 @@ class MultiTurnSession:
raise
started_at = time.monotonic()
try:
- last_message, _, session.log_lines_seen, session.printed_lines = await poll_for_turn(
+ turn = await poll_for_turn(
task_run,
verbose=verbose,
output_fn=output_fn,
workflow_handle=workflow_handle,
max_poll_seconds=max_poll_seconds,
)
+ session.log_lines_seen = turn.total_lines
+ session.printed_lines = turn.printed_lines
logger.info(
"multi_turn: initial turn completed run=%s duration=%.2fs",
task_run.id,
@@ -242,7 +245,7 @@ class MultiTurnSession:
# Shield so the failure signal still lands if the cancel re-fires mid-cleanup.
await asyncio.shield(session.end(status="failed", error=str(e)))
raise
- return session, last_message
+ return session, turn.last_message
async def send_followup(
self,
@@ -297,7 +300,7 @@ class MultiTurnSession:
attempt,
)
try:
- last_message, _, self.log_lines_seen, self.printed_lines = await poll_for_turn(
+ turn = await poll_for_turn(
self.task_run,
skip_lines=self.log_lines_seen,
printed_lines=self.printed_lines,
@@ -306,7 +309,9 @@ class MultiTurnSession:
workflow_handle=self._workflow_handle,
max_poll_seconds=self.max_poll_seconds,
)
- return last_message
+ self.log_lines_seen = turn.total_lines
+ self.printed_lines = turn.printed_lines
+ return turn.last_message
# Catch empty turns, raise everything else
except EmptyAgentTurnError as e:
# Advance log offsets to read from the current tail instead of re-reading the empty-turn lines
diff --git a/products/tasks/backend/temporal/process_task/tests/test_utils.py b/products/tasks/backend/temporal/process_task/tests/test_utils.py
index 3dc4bf90176c..394a961507ed 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_utils.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_utils.py
@@ -4,7 +4,7 @@ from django.test import SimpleTestCase, TestCase, override_settings
from parameterized import parameterized
-from products.mcp_store.backend.facade.contracts import ActiveInstallationInfo
+from products.mcp_store.backend.facade.contracts import ActiveInstallation
from products.tasks.backend.constants import (
DEFAULT_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATH,
DEFAULT_SANDBOX_WORKING_DIR,
@@ -342,14 +342,14 @@ class TestFetchUserMcpServerConfigs(TestCase):
MOCK_FACADE = "products.tasks.backend.temporal.process_task.utils.get_installations_for_sandbox"
MOCK_API_URL = "products.tasks.backend.temporal.process_task.utils.get_sandbox_api_url"
- def _make_installation(self, **kwargs) -> ActiveInstallationInfo:
+ def _make_installation(self, **kwargs) -> ActiveInstallation:
defaults = {
"id": "abc-123",
"name": "Linear",
"proxy_path": f"/api/environments/{self.TEAM_ID}/mcp_server_installations/abc-123/proxy/",
}
defaults.update(kwargs)
- return ActiveInstallationInfo(**defaults)
+ return ActiveInstallation(**defaults)
def _expected_user_headers(self, *, consumer: str = "posthog-code") -> list[dict[str, str]]:
return [
diff --git a/products/tasks/backend/tests/test_check_logs.py b/products/tasks/backend/tests/test_check_logs.py
index a83e22986633..87d9d25ae128 100644
--- a/products/tasks/backend/tests/test_check_logs.py
+++ b/products/tasks/backend/tests/test_check_logs.py
@@ -16,10 +16,10 @@ class TestCheckLogs:
def test_returns_agent_message_when_both_present(self):
log = "\n".join([_agent_message_line("hello"), _end_turn_line()])
with patch("posthog.storage.object_storage.read", return_value=log):
- finished, text, _, _, empty_end_turn, _ = _check_logs(FakeTaskRun())
- assert finished is True
- assert text == "hello"
- assert empty_end_turn is False
+ state = _check_logs(FakeTaskRun())
+ assert state.agent_finished is True
+ assert state.last_message == "hello"
+ assert state.empty_end_turn is False
def test_end_turn_without_agent_message_flags_empty_end_turn(self):
"""Regression: when skip_lines puts us past the agent_message but end_turn
@@ -35,12 +35,12 @@ class TestCheckLogs:
skip = len(turn_1) + len(turn_2_prompt)
with patch("posthog.storage.object_storage.read", return_value=log):
- finished, text, _, total, empty_end_turn, _ = _check_logs(FakeTaskRun(), skip_lines=skip)
+ state = _check_logs(FakeTaskRun(), skip_lines=skip)
- assert finished is False
- assert text is None
- assert empty_end_turn is True
- assert total == len(turn_1) + len(turn_2_prompt) + len(turn_2_partial)
+ assert state.agent_finished is False
+ assert state.last_message is None
+ assert state.empty_end_turn is True
+ assert state.total_lines == len(turn_1) + len(turn_2_prompt) + len(turn_2_partial)
def test_skip_lines_returns_only_new_agent_message(self):
turn_1 = [_agent_message_line("old"), _end_turn_line()]
@@ -50,37 +50,51 @@ class TestCheckLogs:
skip = len(turn_1)
with patch("posthog.storage.object_storage.read", return_value=log):
- finished, text, _, _, empty_end_turn, _ = _check_logs(FakeTaskRun(), skip_lines=skip)
+ state = _check_logs(FakeTaskRun(), skip_lines=skip)
- assert finished is True
- assert text == "new"
- assert empty_end_turn is False
+ assert state.agent_finished is True
+ assert state.last_message == "new"
+ assert state.empty_end_turn is False
def test_empty_log_returns_all_defaults(self):
with patch("posthog.storage.object_storage.read", return_value=""):
- finished, text, full_log, total, empty_end_turn, refused = _check_logs(FakeTaskRun())
- assert (finished, text, full_log, total, empty_end_turn, refused) == (False, None, None, 0, False, False)
+ state = _check_logs(FakeTaskRun())
+ assert (
+ state.agent_finished,
+ state.last_message,
+ state.full_log,
+ state.total_lines,
+ state.empty_end_turn,
+ state.refused,
+ ) == (
+ False,
+ None,
+ None,
+ 0,
+ False,
+ False,
+ )
def test_no_new_lines_since_skip_does_not_flag_empty(self):
"""Eventual-consistency case: S3 hasn't caught up yet, no new data to parse."""
turn_1 = [_agent_message_line("x"), _end_turn_line()]
log = "\n".join(turn_1)
with patch("posthog.storage.object_storage.read", return_value=log):
- finished, text, _, total, empty_end_turn, _ = _check_logs(FakeTaskRun(), skip_lines=len(turn_1))
- assert finished is False
- assert text is None
- assert empty_end_turn is False
- assert total == len(turn_1)
+ state = _check_logs(FakeTaskRun(), skip_lines=len(turn_1))
+ assert state.agent_finished is False
+ assert state.last_message is None
+ assert state.empty_end_turn is False
+ assert state.total_lines == len(turn_1)
def test_empty_end_turn_flagged_on_first_turn_too(self):
"""SDK short-circuit on the very first turn must surface as empty_end_turn too.
Otherwise MultiTurnSession.start silently polls until timeout."""
log = "\n".join([_end_turn_line()])
with patch("posthog.storage.object_storage.read", return_value=log):
- finished, text, _, _, empty_end_turn, _ = _check_logs(FakeTaskRun(), skip_lines=0)
- assert finished is False
- assert text is None
- assert empty_end_turn is True
+ state = _check_logs(FakeTaskRun(), skip_lines=0)
+ assert state.agent_finished is False
+ assert state.last_message is None
+ assert state.empty_end_turn is True
def test_usage_updates_alone_between_prompt_and_end_turn_flags_empty(self):
"""This is the exact pattern seen in the production incident:
@@ -95,11 +109,11 @@ class TestCheckLogs:
log = "\n".join(turn_1 + turn_2_empty)
with patch("posthog.storage.object_storage.read", return_value=log):
- finished, text, _, _, empty_end_turn, _ = _check_logs(FakeTaskRun(), skip_lines=len(turn_1))
+ state = _check_logs(FakeTaskRun(), skip_lines=len(turn_1))
- assert finished is False
- assert text is None
- assert empty_end_turn is True
+ assert state.agent_finished is False
+ assert state.last_message is None
+ assert state.empty_end_turn is True
def test_refusal_flags_refused_and_suppresses_partial_text(self):
"""Regression: a provider refusal used to look like a still-running turn, so every
@@ -107,11 +121,11 @@ class TestCheckLogs:
pre-refusal partial text must not be mistaken for the turn's response."""
log = "\n".join([_agent_message_line("partial reasoning"), _refusal_line()])
with patch("posthog.storage.object_storage.read", return_value=log):
- finished, text, _, _, empty_end_turn, refused = _check_logs(FakeTaskRun())
- assert refused is True
- assert finished is False
- assert text is None
- assert empty_end_turn is False
+ state = _check_logs(FakeTaskRun())
+ assert state.refused is True
+ assert state.agent_finished is False
+ assert state.last_message is None
+ assert state.empty_end_turn is False
@pytest.mark.parametrize(
"lines,expected_text",
@@ -133,11 +147,11 @@ class TestCheckLogs:
failing a finished turn as refused would discard a good response."""
log = "\n".join(lines)
with patch("posthog.storage.object_storage.read", return_value=log):
- finished, text, _, _, empty_end_turn, refused = _check_logs(FakeTaskRun())
- assert refused is False
- assert finished is True
- assert text == expected_text
- assert empty_end_turn is False
+ state = _check_logs(FakeTaskRun())
+ assert state.refused is False
+ assert state.agent_finished is True
+ assert state.last_message == expected_text
+ assert state.empty_end_turn is False
class TestStreamNewLinesMonotonic:
diff --git a/products/tasks/backend/tests/test_multi_turn_session.py b/products/tasks/backend/tests/test_multi_turn_session.py
index 9b546071fd12..c22fffa8bcc0 100644
--- a/products/tasks/backend/tests/test_multi_turn_session.py
+++ b/products/tasks/backend/tests/test_multi_turn_session.py
@@ -19,6 +19,7 @@ from products.tasks.backend.logic.services.custom_prompt_internals import (
AgentError,
CustomPromptSandboxContext,
EmptyAgentTurnError,
+ TurnPollResult,
TurnPollTimeout,
_extract_agent_error,
create_task_and_trigger,
@@ -107,9 +108,9 @@ class TestPollForTurnEmptyEndTurn:
patch("products.tasks.backend.logic.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 0),
patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake_task_run),
):
- last_message, _, total_lines, _ = await poll_for_turn(fake_task_run, skip_lines=skip)
- assert last_message == "current-turn-text"
- assert total_lines == len(turn_1) + len(turn_2_with_text) + len(turn_2_end_turn)
+ turn = await poll_for_turn(fake_task_run, skip_lines=skip)
+ assert turn.last_message == "current-turn-text"
+ assert turn.total_lines == len(turn_1) + len(turn_2_with_text) + len(turn_2_end_turn)
@pytest.mark.asyncio
async def test_poll_handles_s3_shrink_then_recovery_without_duplicates(self):
@@ -136,16 +137,14 @@ class TestPollForTurnEmptyEndTurn:
patch("products.tasks.backend.logic.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 0),
patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake_task_run),
):
- last_message, _, total_lines, printed_lines = await poll_for_turn(
- fake_task_run, skip_lines=0, output_fn=captured.append, verbose=True
- )
+ turn = await poll_for_turn(fake_task_run, skip_lines=0, output_fn=captured.append, verbose=True)
- assert last_message == "final-answer"
+ assert turn.last_message == "final-answer"
# Every raw line streamed exactly once, in log order — no re-emission after the shrink.
assert captured == poll_3_lines
# Cursors settled on the final (recovered) line count, not the truncated one.
- assert total_lines == len(poll_3_lines)
- assert printed_lines == len(poll_3_lines)
+ assert turn.total_lines == len(poll_3_lines)
+ assert turn.printed_lines == len(poll_3_lines)
class TestPollForTurnStaleSalvage:
@@ -167,10 +166,10 @@ class TestPollForTurnStaleSalvage:
patch("products.tasks.backend.logic.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 15),
patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake),
):
- last_message, _, total_lines, _ = await poll_for_turn(fake, skip_lines=0)
+ turn = await poll_for_turn(fake, skip_lines=0)
- assert last_message == "close-out summary"
- assert total_lines == 2
+ assert turn.last_message == "close-out summary"
+ assert turn.total_lines == 2
@pytest.mark.asyncio
async def test_salvages_dropped_finalization_after_active_work(self):
@@ -197,10 +196,10 @@ class TestPollForTurnStaleSalvage:
# STALE_TURN_SALVAGE_SECONDS intentionally NOT patched — exercise the production floor.
patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake),
):
- last_message, _, total_lines, _ = await poll_for_turn(fake, skip_lines=0)
+ turn = await poll_for_turn(fake, skip_lines=0)
- assert last_message == "close-out summary"
- assert total_lines == len(done)
+ assert turn.last_message == "close-out summary"
+ assert turn.total_lines == len(done)
@parameterized.expand(
[
@@ -228,10 +227,10 @@ class TestPollForTurnStaleSalvage:
patch("products.tasks.backend.logic.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 15),
patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake),
):
- last_message, _, total_lines, _ = await poll_for_turn(fake, skip_lines=0)
+ turn = await poll_for_turn(fake, skip_lines=0)
- assert last_message == "close-out summary"
- assert total_lines == 2 + len(trailing)
+ assert turn.last_message == "close-out summary"
+ assert turn.total_lines == 2 + len(trailing)
@pytest.mark.asyncio
async def test_salvages_dropped_finalization_despite_side_channels_arriving_every_poll(self):
@@ -259,9 +258,9 @@ class TestPollForTurnStaleSalvage:
patch("products.tasks.backend.logic.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 15),
patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake),
):
- last_message, _, _, _ = await poll_for_turn(fake, skip_lines=0)
+ turn = await poll_for_turn(fake, skip_lines=0)
- assert last_message == "close-out summary"
+ assert turn.last_message == "close-out summary"
@pytest.mark.asyncio
async def test_does_not_salvage_when_console_lines_follow_a_live_tail(self):
@@ -318,9 +317,9 @@ class TestPollForTurnStaleSalvage:
patch("products.tasks.backend.logic.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 15),
patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake),
):
- last_message, _, _, _ = await poll_for_turn(fake, skip_lines=0)
+ turn = await poll_for_turn(fake, skip_lines=0)
- assert last_message == "Part-one.Part-two.Part-three."
+ assert turn.last_message == "Part-one.Part-two.Part-three."
@pytest.mark.asyncio
async def test_does_not_salvage_turn_active_near_deadline(self):
@@ -397,9 +396,9 @@ class TestPollForTurnStaleSalvage:
patch("products.tasks.backend.logic.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 15),
patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake),
):
- last_message, _, _, _ = await poll_for_turn(fake, skip_lines=0)
+ turn = await poll_for_turn(fake, skip_lines=0)
- assert last_message == "final answer"
+ assert turn.last_message == "final answer"
@pytest.mark.asyncio
async def test_salvages_despite_eventually_consistent_short_final_poll(self):
@@ -430,9 +429,9 @@ class TestPollForTurnStaleSalvage:
patch("products.tasks.backend.logic.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 15),
patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake),
):
- last_message, _, _, _ = await poll_for_turn(fake, skip_lines=0)
+ turn = await poll_for_turn(fake, skip_lines=0)
- assert last_message == "close-out summary"
+ assert turn.last_message == "close-out summary"
@pytest.mark.asyncio
async def test_salvages_when_finalization_fingerprint_lands_on_reread(self):
@@ -457,9 +456,9 @@ class TestPollForTurnStaleSalvage:
patch("products.tasks.backend.logic.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 15),
patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake),
):
- last_message, _, _, _ = await poll_for_turn(fake, skip_lines=0)
+ turn = await poll_for_turn(fake, skip_lines=0)
- assert last_message == "close-out summary"
+ assert turn.last_message == "close-out summary"
@pytest.mark.asyncio
async def test_declines_salvage_when_reread_shows_new_chunk_after_final_poll(self):
@@ -553,9 +552,9 @@ class TestPollForTurnStaleSalvage:
patch("products.tasks.backend.logic.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 15),
patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake),
):
- last_message, _, _, _ = await poll_for_turn(fake, skip_lines=0)
+ turn = await poll_for_turn(fake, skip_lines=0)
- assert last_message == "Part-one.Part-two.Part-three."
+ assert turn.last_message == "Part-one.Part-two.Part-three."
@pytest.mark.asyncio
async def test_salvage_propagates_exhausted_storage_error(self):
@@ -604,9 +603,9 @@ class TestPollForTurnStaleSalvage:
patch("products.tasks.backend.logic.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 15),
patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake),
):
- last_message, _, _, _ = await poll_for_turn(fake, skip_lines=0)
+ turn = await poll_for_turn(fake, skip_lines=0)
- assert last_message == "close-out summary"
+ assert turn.last_message == "close-out summary"
@pytest.mark.asyncio
async def test_terminal_status_at_timeout_drains_instead_of_salvaging(self):
@@ -649,10 +648,10 @@ class TestPollForTurnStaleSalvage:
patch("products.tasks.backend.logic.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 10),
patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake),
):
- last_message, _, total_lines, _ = await poll_for_turn(fake, skip_lines=0)
+ turn = await poll_for_turn(fake, skip_lines=0)
- assert last_message == "final answer"
- assert total_lines == len(final)
+ assert turn.last_message == "final answer"
+ assert turn.total_lines == len(final)
@parameterized.expand(
[
@@ -712,9 +711,9 @@ class TestPollForTurnStaleSalvage:
patch("products.tasks.backend.logic.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 15),
patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake),
):
- last_message, _, _, _ = await poll_for_turn(fake, skip_lines=0)
+ turn = await poll_for_turn(fake, skip_lines=0)
- assert last_message == "close-out summary"
+ assert turn.last_message == "close-out summary"
@pytest.mark.asyncio
async def test_failed_progress_after_fingerprint_declines_salvage(self):
@@ -755,9 +754,9 @@ class TestPollForTurnStaleSalvage:
patch("products.tasks.backend.logic.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 15),
patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake),
):
- last_message, _, _, _ = await poll_for_turn(fake, skip_lines=0)
+ turn = await poll_for_turn(fake, skip_lines=0)
- assert last_message == "close-out summary"
+ assert turn.last_message == "close-out summary"
class TestPollForTurnTimeoutDiagnosis:
@@ -882,9 +881,9 @@ class TestPollForTurnTerminalDrain:
patch("products.tasks.backend.logic.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 0),
patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake_task_run),
):
- last_message, _, _, _ = await poll_for_turn(fake_task_run, skip_lines=skip)
+ turn = await poll_for_turn(fake_task_run, skip_lines=skip)
- assert last_message == "turn-2-partial-answer"
+ assert turn.last_message == "turn-2-partial-answer"
@pytest.mark.asyncio
async def test_terminal_status_first_turn_still_scans_full_log(self):
@@ -904,9 +903,9 @@ class TestPollForTurnTerminalDrain:
patch("products.tasks.backend.logic.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 0),
patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake_task_run),
):
- last_message, _, _, _ = await poll_for_turn(fake_task_run, skip_lines=0)
+ turn = await poll_for_turn(fake_task_run, skip_lines=0)
- assert last_message == "partial-before-death"
+ assert turn.last_message == "partial-before-death"
class TestExtractAgentError:
@@ -1130,7 +1129,9 @@ class TestMultiTurnSessionRetry:
with patch(
"products.tasks.backend.logic.services.custom_prompt_multi_turn_runner.poll_for_turn",
- new=AsyncMock(return_value=(agent_response, None, 10, 5)),
+ new=AsyncMock(
+ return_value=TurnPollResult(last_message=agent_response, full_log=None, total_lines=10, printed_lines=5)
+ ),
):
result = await session.send_followup("hello", _Resp, label="unit")
@@ -1146,7 +1147,7 @@ class TestMultiTurnSessionRetry:
poll_mock = AsyncMock(
side_effect=[
EmptyAgentTurnError("empty", total_lines=12, printed_lines=7),
- (agent_response, None, 20, 10),
+ TurnPollResult(last_message=agent_response, full_log=None, total_lines=20, printed_lines=10),
]
)
with patch(
@@ -1254,7 +1255,7 @@ class TestMultiTurnSessionRetry:
captured_skip_lines.append(skip_lines)
if len(captured_skip_lines) == 1:
raise EmptyAgentTurnError("empty", total_lines=99, printed_lines=50)
- return (agent_response, None, 120, 60)
+ return TurnPollResult(last_message=agent_response, full_log=None, total_lines=120, printed_lines=60)
with patch(
"products.tasks.backend.logic.services.custom_prompt_multi_turn_runner.poll_for_turn",
@@ -1295,7 +1296,11 @@ class TestMultiTurnSessionStartBranch:
),
patch(
"products.tasks.backend.logic.services.custom_prompt_multi_turn_runner.poll_for_turn",
- new=AsyncMock(return_value=(agent_response, None, 1, 1)),
+ new=AsyncMock(
+ return_value=TurnPollResult(
+ last_message=agent_response, full_log=None, total_lines=1, printed_lines=1
+ )
+ ),
),
):
kwargs = {"branch": branch} if branch is not None else {}
@@ -1577,9 +1582,9 @@ class TestPollForTurnConnectionDrop:
patch("products.tasks.backend.logic.services.custom_prompt_internals.close_old_connections") as close_conns,
patch("products.tasks.backend.models.TaskRun.objects.get", new=get_mock),
):
- last_message, _, _, _ = await poll_for_turn(FakeTaskRun(), skip_lines=0)
+ turn = await poll_for_turn(FakeTaskRun(), skip_lines=0)
- assert last_message == "connection-drop summary"
+ assert turn.last_message == "connection-drop summary"
# Read was retried after the drop, and the staleness guard ran before each attempt.
assert get_mock.call_count == 2
assert close_conns.call_count == 2