: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(signals): build stacked report plans from research layers (#107675)
posthog[bot]99b3a775461d
diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.pyindex 3845d8fa6ac8..eba6ea3b1ba7 100644--- a/posthog/api/test/test_integration.py+++ b/posthog/api/test/test_integration.py@@ -3167,7 +3167,7 @@ class TestGitHubIntegrationStateValidation:@patch("posthog.models.github_integration_base.GitHubIntegrationBase.verify_user_installation_access")@patch("posthog.models.integration.github.GitHubIntegration.github_user_from_code")@patch("posthog.models.integration.github.GitHubIntegration.integration_from_installation_id")- @patch("posthog.models.user_integration.user_github_integration_from_installation")+ @patch("posthog.api.github_callback.team_services.user_github_integration_from_installation")def test_create_github_integration_with_valid_state_succeeds(self, mock_user_integration, mock_from_install, mock_from_code, mock_verify, client: HttpClient):@@ -3283,7 +3283,7 @@ class TestGitHubIntegrationStateValidation:@patch("posthog.models.github_integration_base.GitHubIntegrationBase.verify_user_installation_access")@patch("posthog.models.integration.github.GitHubIntegration.github_user_from_code")@patch("posthog.models.integration.github.GitHubIntegration.integration_from_installation_id")- @patch("posthog.models.user_integration.user_github_integration_from_installation")+ @patch("posthog.api.github_callback.team_services.user_github_integration_from_installation")def test_create_github_integration_state_token_single_use(self, mock_user_integration, mock_from_install, mock_from_code, mock_verify, client: HttpClient):@@ -3726,7 +3726,7 @@ class TestGitHubTeamIntegrationComplete:@patch("posthog.models.github_integration_base.GitHubIntegrationBase.verify_user_installation_access")@patch("posthog.models.integration.github.GitHubIntegration.github_user_from_code")@patch("posthog.models.integration.github.GitHubIntegration.integration_from_installation_id")- @patch("posthog.models.user_integration.user_github_integration_from_installation")+ @patch("posthog.api.github_callback.team_services.user_github_integration_from_installation")def test_success_redirects_to_next_with_integration_id(self, mock_user_integration, mock_from_install, mock_from_code, mock_verify, client: HttpClient):@@ -3794,7 +3794,7 @@ class TestGitHubTeamIntegrationComplete:@patch("posthog.models.github_integration_base.GitHubIntegrationBase.verify_user_installation_access")@patch("posthog.models.integration.github.GitHubIntegration.github_user_from_code")@patch("posthog.models.integration.github.GitHubIntegration.integration_from_installation_id")- @patch("posthog.models.user_integration.user_github_integration_from_installation")+ @patch("posthog.api.github_callback.team_services.user_github_integration_from_installation")def test_member_can_complete_fresh_team_install(self, mock_user_integration, mock_from_install, mock_from_code, mock_verify, client: HttpClient):@@ -3860,7 +3860,7 @@ class TestGitHubTeamIntegrationComplete:@patch("posthog.models.github_integration_base.GitHubIntegrationBase.verify_user_installation_access")@patch("posthog.models.integration.github.GitHubIntegration.github_user_from_code")@patch("posthog.models.integration.github.GitHubIntegration.integration_from_installation_id")- @patch("posthog.models.user_integration.user_github_integration_from_installation")+ @patch("posthog.api.github_callback.team_services.user_github_integration_from_installation")def test_environment_integrations_flow_uses_team_id_from_authorize_cache(self, mock_user_integration, mock_from_install, mock_from_code, mock_verify, client: HttpClient):diff --git a/products/signals/ARCHITECTURE.md b/products/signals/ARCHITECTURE.mdindex 308e16bbb307..dab09c0a24e4 100644--- a/products/signals/ARCHITECTURE.md+++ b/products/signals/ARCHITECTURE.md@@ -1457,10 +1457,12 @@ Rows that no longer parse name no edge, the same tolerance every other read of t| `blocked_by_dependency` | Some outgoing `depends_on` target carries no pull request, or only ones known to be closed || `plan_parent` | The report has incoming `part_of` edges, so it is the plan and the steps do the work |-The implementation path checks these gates again under the report lock before task creation. A gate returns `AutostartOutcome(status="blocked")`, writes an `autostart_skip` artefact naming the deciding report, and fires `signals_autostart_skipped`. The artefact exists only for the link gates: every other skip is a property of the report a reader can already see, while a link gate's reason lives on a different report. The gates hold the automatic path only, so pressing Implement in the inbox still starts a run. Nothing re-evaluates a blocked report when its dependency's pull request opens: a blocked child starts on the next pipeline evaluation of that report, or by hand.+The implementation path checks these gates again under the report lock before task creation. A gate returns `AutostartOutcome(status="blocked")`, writes an `autostart_skip` artefact naming the deciding report, and fires `signals_autostart_skipped`. The artefact exists only for the link gates: every other skip is a property of the report a reader can already see, while a link gate's reason lives on a different report. The gates hold the automatic path only, so pressing Implement in the inbox still starts a run. When a report's pull request syncs from its run, `start_dependent_stack_layers` re-evaluates the reports that depend on it (see Stacked plans).**Plan roll-up** (`backend/plan_rollup.py`). A `part_of` child carries the work and closes on its own pull request; the plan usually carries nothing of its own, so without the roll-up it sits in the inbox forever after the last step lands. When every live step of a plan is closed, the plan takes their verdict: resolved when at least one resolved, suppressed when they all were, untouched while any step is open. A deleted step is not a verdict and is dropped. Deleting a step also triggers the check. A plan that becomes ready checks its own steps, so completion can follow a failed attempt during research. Each plan is locked before the check reads and updates its state. The walk continues through plans that are already closed. Archiving a resolved plan is refused, for the same reason `_apply_pr_report_state` refuses it. The walk continues up a plan of plans, bounded by `MAX_PLAN_ROLLUP_LEVELS`, which tracks the `MAX_REPORT_LINK_GRAPH_LEVELS` depth `validated_report_link_write` accepts: a hierarchy the write path allows but the walk stops short of would leave its top plan open, with every step that could retrigger the walk already closed. A plan with a pending replacement is skipped like any other report, and that read, like the pull request read beside it, is pinned to the writer because a replacement written moments earlier must not read as absent. A plan a person pressed Implement on does carry its own pull request, and while that pull request is open, draft, or unknown the steps decide nothing: resolving on their verdict would hide a plan whose own work is still in flight, and archiving on it would send the dismissal receiver to close that pull request. It is hooked on `SignalReport`'s status change (`receivers.roll_up_plan_parents_when_report_closes`) rather than on the pull request webhook, so a merged pull request, a manual resolve, a bulk state change and an MCP state write all reach it. Plenty of steps close with no pull request at all. A `part_of` row written on a step that already closed runs the check too, from the link write path, because that write announces no status change of its own.+**Stacked plans** (`backend/stack_plan.py`). Research can return an optional `layers` plan on `ReportPresentationOutput`: two to six layers, each with a title, a scope, and the index of an earlier layer it depends on. A forward reference falls back to the previous layer, so the order is always acyclic. When the pass settles ready, `mark_report_ready_activity` creates one ready child report per layer in the same transaction. Each child gets the scope as its summary, the plan's latest safety, actionability, priority, repository and reviewer judgments, a `part_of` link to the plan, and a `depends_on` link to its dependency. A plan that already has children keeps them on a re-research. The plan itself is held by the `plan_parent` gate, and its settle-point auto-start then starts the layers whose dependencies already have a pull request. After that, each pull request sync on a report queues `start_dependent_stack_layers`, which starts the waiting layers. A layer whose dependency has an open or draft pull request starts on that dependency's automation branch, and the run state carries `stack_base_branch`, so the task launch protects that branch as the PR base instead of the base of the dependency's PR. A merged dependency leaves the layer on the default base. Replacing a whole stack after a lower layer is superseded, a server-side GitHub stack link, and a collapsed inbox list are not built yet.+**The recurrence chain** (`backend/recurrence.py`) reads incoming `recurrence_of` edges to follow a forked report to its current live successor.The inbox renders both types in the work log: a `report_link` row shows its kind, reason, and a link to the other report, and an `autostart_skip` row says in plain words why nothing started and links the deciding report.diff --git a/products/signals/backend/auto_start.py b/products/signals/backend/auto_start.pyindex fd467a124283..350ddc603d2b 100644--- a/products/signals/backend/auto_start.py+++ b/products/signals/backend/auto_start.py@@ -67,6 +67,7 @@ from products.signals.backend.signal_metadata import (fetch_source_products_for_reports,fetch_source_references_for_report,)+from products.signals.backend.stack_plan import dependency_head_branchfrom products.signals.backend.supersession import (TargetVerificationUnavailable,decision_is_current,@@ -312,6 +313,17 @@ def _head_branch_instruction(head_branch: str) -> str:)+def _stack_base_instruction(stack_base_branch: str | None) -> str:+ if not stack_base_branch:+ return ""+ return (+ f"\n\nThis report is one layer of a stack of dependent pull requests. The run starts on "+ f"`{stack_base_branch}`, the head branch of the pull request this layer builds on. Open your PR "+ f"with `{stack_base_branch}` as its base, and do not push to that branch. Change only what this "+ "layer's summary asks for, because the layer below already carries the rest."+ )++def _superseded_pr_instruction(supersede: SupersedeDecision) -> str:"""Tell the agent which pull request it is replacing, and to say so in its own description.@@ -692,6 +704,7 @@ def _create_implementation_task_if_absent(user_id: int,repository: str,base_branch: str | None,+ stack_base_branch: str | None = None,billing_exempt_reason: str | None = None,steering: ReportSteering = NO_STEERING,free_trial_enabled: bool | None = None,@@ -844,6 +857,7 @@ def _create_implementation_task_if_absent(# The pre-generated branch the description instructs the agent to push to; stamped# into protected run state so the review carve-out can verify the PR is this run's.self_driving_head_branch=head_branch,+ stack_base_branch=stack_base_branch,# Internal so the run stays out of the default task list; the report surfaces it by id.internal=True,runtime_adapter=agent_runtime.runtime_adapter,@@ -1488,6 +1502,11 @@ async def maybe_autostart_implementation_task(return AutostartOutcome(status="blocked", reason="Organization is on a free trial")base_branch = team_config.base_branch_for(repository) if team_config else None+ stack_base_branch = await database_sync_to_async(dependency_head_branch, thread_sensitive=False)(+ team_id=team_id, report_id=report_id, repository=repository+ )+ if stack_base_branch:+ base_branch = stack_base_branchsource_references = await database_sync_to_async(_fetch_source_references, thread_sensitive=False)(team_id, report_id@@ -1511,10 +1530,12 @@ async def maybe_autostart_implementation_task(source_references=source_references,steering=steering,supersede=supersede,- ),+ )+ + _stack_base_instruction(stack_base_branch),user_id=task_user.id,repository=repository,base_branch=base_branch,+ stack_base_branch=stack_base_branch,billing_exempt_reason=billing_exempt_reason,steering=steering,# The verdict resolved above, so the create-time gate re-reads no flag while it holds thediff --git a/products/signals/backend/receivers.py b/products/signals/backend/receivers.pyindex eb53c1a81551..1e0b7c13338f 100644--- a/products/signals/backend/receivers.py+++ b/products/signals/backend/receivers.py@@ -116,6 +116,7 @@ def sync_task_run_pr_to_assignments(sender: type, instance: Any, created: bool,# the signals contracts, both forbidden at django.setup() by the startup-import-budget test.from products.signals.backend.pull_requests import apply_report_completionfrom products.signals.backend.report_assignments import sync_task_pull_request_to_assignments # noqa: PLC0415+ from products.signals.backend.stack_plan import schedule_dependent_layers # noqa: PLC0415from products.signals.backend.tasks import link_report_tracker_issues # noqa: PLC0415from products.tasks.backend.facade.api import read_pr_urls@@ -153,6 +154,7 @@ def sync_task_run_pr_to_assignments(sender: type, instance: Any, created: bool,)for report in reports:apply_report_completion(report)+ schedule_dependent_layers(team_id=instance.team_id, report_ids=[str(report.id) for report in reports])except Exception:logger.exception("signals.task_run_pr_assignment_sync_failed", task_run_id=str(instance.id))diff --git a/products/signals/backend/report_generation/research.py b/products/signals/backend/report_generation/research.pyindex 16665909eb6a..9a10bd48471a 100644--- a/products/signals/backend/report_generation/research.py+++ b/products/signals/backend/report_generation/research.py@@ -62,6 +62,7 @@ __all__ = ["ImplementationDecision","Priority","PriorityAssessment",+ "ReportLayer","ReportPresentationOutput","ReportResearchOutput","ResearchArtefactContent",@@ -82,6 +83,35 @@ def _rejection_reason(error: Exception) -> str:)+MIN_REPORT_LAYERS = 2+MAX_REPORT_LAYERS = 6+MAX_REPORT_LAYER_TITLE_LENGTH = 96+MAX_REPORT_LAYER_SCOPE_LENGTH = 2_000+++class ReportLayer(BaseModel):+ """One pull request in a stack of dependent pull requests. Each layer becomes a child report."""++ title: str = Field(+ description="A PR-style title for this layer alone, in the same Conventional Commits style as the report title.",+ max_length=MAX_REPORT_LAYER_TITLE_LENGTH,+ )+ scope: str = Field(+ description=(+ "What this layer changes and what it leaves to the other layers, in two to five plain sentences. "+ "This becomes the layer's own summary, so it must stand alone for the engineer who implements it."+ ),+ max_length=MAX_REPORT_LAYER_SCOPE_LENGTH,+ )+ depends_on: int | None = Field(+ default=None,+ description=(+ "Zero-based index of the earlier layer whose pull request this layer builds on, or null when "+ "the layer can land on the default branch by itself."+ ),+ )++class ReportPresentationOutput(BaseModel):title: str = Field(description="""@@ -142,6 +172,57 @@ Hard rules:"EventsNode or ActionsNode sources. Its value/value_at snapshot is an optional cached fallback."),)+ layers: list[ReportLayer] = Field(+ default_factory=list,+ description=(+ "An optional plan of dependent pull requests. Leave empty unless the work is too large for one "+ "reviewable PR and splits into layers that a reviewer can review one at a time. When the source "+ "issue has a `## Stack`, `## Phases` or landing plan section, follow its layers. Otherwise decide "+ f"yourself, and use between {MIN_REPORT_LAYERS} and {MAX_REPORT_LAYERS} layers in landing order. "+ "When you fill this, the report title and summary describe the whole plan, and each layer "+ "becomes its own report with its own pull request."+ ),+ )++ @field_validator("layers", mode="before")+ @classmethod+ def drop_a_plan_with_a_layer_that_does_not_validate(cls, v: object) -> object:+ # Pydantic checks each layer's own fields (a missing scope, a title over the length cap, a+ # non-integer dependency) before `layers_form_a_plan` runs, and the presentation turn has no+ # retry. So a malformed layer drops the whole plan here, and the report continues as a single+ # pull request with its title and summary, the same as a plan with a blank layer.+ if not isinstance(v, list):+ return v+ for index, entry in enumerate(v):+ try:+ ReportLayer.model_validate(entry)+ except ValidationError as e:+ logger.warning(+ "presentation: dropped layer plan, layer at index %d did not validate (%s)",+ index,+ _rejection_reason(e),+ )+ return []+ return v++ @field_validator("layers")+ @classmethod+ def layers_form_a_plan(cls, layers: list[ReportLayer]) -> list[ReportLayer]:+ # A plan outside the bounds, or with a layer that has no title or scope, keeps the report a+ # single pull request instead of failing the whole presentation turn. A dependency must point+ # at an earlier layer, which keeps the order acyclic. A forward or self reference falls back+ # to the previous layer, the usual shape of a stack, and the first layer falls back to no+ # dependency.+ if not MIN_REPORT_LAYERS <= len(layers) <= MAX_REPORT_LAYERS:+ return []+ if any(not layer.title.strip() or not layer.scope.strip() for layer in layers):+ return []+ return [+ layer+ if layer.depends_on is None or 0 <= layer.depends_on < index+ else layer.model_copy(update={"depends_on": index - 1 if index else None})+ for index, layer in enumerate(layers)+ ]@field_validator("charts", mode="before")@classmethod@@ -298,6 +379,11 @@ class ReportResearchOutput(BaseModel):"Every entry has a bounded live EventsNode/ActionsNode Trends query; its snapshot is optional."),)+ layers: list[ReportLayer] = Field(+ default_factory=list,+ description="The plan of dependent pull requests, when research split the work. Each layer becomes "+ "a child report when the report settles ready.",+ )research_task_id: str | None = Field(default=None,description="UUID of the sandbox task that performed the research; artefacts persisted from "@@ -1462,6 +1548,7 @@ async def run_multi_turn_research(summary=presentation_result.summary,charts=presentation_result.charts,metrics=presentation_result.metrics if metrics_enabled else [],+ layers=presentation_result.layers,research_task_id=str(session.task.id),verification_note=verification_note,checks=checks,diff --git a/products/signals/backend/stack_plan.py b/products/signals/backend/stack_plan.pynew file mode 100644index 000000000000..98c55ad8b802--- /dev/null+++ b/products/signals/backend/stack_plan.py@@ -0,0 +1,278 @@+"""A research plan of dependent pull requests, stored as one child report per layer.++One report still means one pull request. When research splits the work into layers, the report it+researched becomes the plan: its summary describes the whole change, and it never starts its own+run (the `plan_parent` gate). Each layer becomes a child report that is `part_of` the plan and+`depends_on` the layer it builds on, so every rule about claims, pull requests, completion, billing+and checks stays per report.++Postgres holds the order. A layer starts when every layer it depends on has a pull request, and its+run checks out the head branch of that pull request, so the pull request it opens stacks on it.+"""++from functools import partial+from typing import cast++from django.db import transaction+from django.utils import timezone++import structlog+from asgiref.sync import async_to_sync+from pydantic import ValidationError++from posthog.models.github_integration_base import GitHubIntegrationBase++from products.signals.backend.artefact_attribution import ArtefactAttribution+from products.signals.backend.artefact_schemas import (+ ARTEFACT_CONTENT_SCHEMAS,+ ReportLink,+ StatusArtefactContent,+ TaskRunArtefact,+)+from products.signals.backend.billing import system_billing_exempt_reason+from products.signals.backend.enums import ReportLinkKind+from products.signals.backend.implementation_pr import fetch_implementation_prs_for_reports+from products.signals.backend.models import SignalReport, SignalReportArtefact, SignalReportPullRequest+from products.signals.backend.report_generation.research import ReportLayer+from products.signals.backend.task_run_artefacts import SIGNALS_PRODUCT, TASK_RUN_TYPE_IMPLEMENTATION+from products.signals.backend.typed_report_links import has_open_or_merged_pull_request, incoming_links, outgoing_links++logger = structlog.get_logger(__name__)++# The judgments a layer takes from its plan. A layer is born ready without its own research pass,+# so auto-start reads these to decide whether, where, and as whom the layer starts.+_INHERITED_STATUS_TYPES = (+ SignalReportArtefact.ArtefactType.SAFETY_JUDGMENT,+ SignalReportArtefact.ArtefactType.ACTIONABILITY_JUDGMENT,+ SignalReportArtefact.ArtefactType.PRIORITY_JUDGMENT,+ SignalReportArtefact.ArtefactType.REPO_SELECTION,+ SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS,+)++# A dependency whose pull request is in one of these states still has its head branch on GitHub. A+# merged dependency is already on the default branch, so its layer bases there instead.+# `unknown` counts too, like in the link gates: an attach keeps it when the GitHub lookup fails, and+# the gate already lets the layer start on it, so leaving it out would start the layer off the stack.+_STACKABLE_PR_STATES = (+ SignalReportPullRequest.State.OPEN,+ SignalReportPullRequest.State.DRAFT,+ SignalReportPullRequest.State.UNKNOWN,+)+++def _layer_summary(*, parent: SignalReport, layer: ReportLayer, index: int, total: int) -> str:+ return f"{layer.scope}\n\n## Plan\n\nThis is layer {index + 1} of {total} of the plan '{parent.title}'."+++def _inherited_judgments(parent: SignalReport) -> list[StatusArtefactContent]:+ judgments: list[StatusArtefactContent] = []+ for artefact_type in _INHERITED_STATUS_TYPES:+ latest = (+ SignalReportArtefact.objects.filter(team_id=parent.team_id, report_id=parent.id, type=artefact_type)+ .order_by("-created_at", "-id")+ .values_list("content", "created_by_id")+ .first()+ )+ if latest is None:+ continue+ content, editor_user_id = latest+ # Auto-start runs a user-edited reviewer list as the editing user. A copy written under the+ # plan's attribution would read as pipeline-chosen and could run as a named colleague.+ if artefact_type == SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS and editor_user_id is not None:+ continue+ judgments.append(+ cast(StatusArtefactContent, ARTEFACT_CONTENT_SCHEMAS[artefact_type].model_validate_json(content))+ )+ return judgments+++def create_layer_reports(+ *, parent: SignalReport, layers: list[ReportLayer], attribution: ArtefactAttribution+) -> list[str]:+ """Create one ready child report per layer, linked to the plan, and return their ids in order.++ Call inside the transaction that makes the plan ready, so the plan and its layers land together+ or not at all. A plan that already has layers keeps them: a re-research can rewrite the plan's+ summary, but replacing layers that may already carry pull requests is a separate decision.+ A report that already has its own pull request stays on that one pull request, so the layers+ do not repeat its work beside it.+ """+ if not layers:+ return []+ team_id = parent.team_id+ if incoming_links(team_id=team_id, report_id=parent.id, kinds=(ReportLinkKind.PART_OF,)):+ return []+ if has_open_or_merged_pull_request(team_id=team_id, report_ids=[str(parent.id)]):+ logger.info("signals.stack_plan.layers_skipped_for_own_pull_request", report_id=str(parent.id), team_id=team_id)+ return []+ judgments = _inherited_judgments(parent)+ # A layer does the plan's work, so it keeps the plan's exemption. The scout policy matches only+ # the report the scout emitted, and a layer's id is never in that list.+ billing_exempt_reason = parent.billing_exempt_reason or system_billing_exempt_reason(team_id, parent.id)+ now = timezone.now()+ child_ids: list[str] = []+ for index, layer in enumerate(layers):+ child = SignalReport.objects.create(+ team_id=team_id,+ status=SignalReport.Status.READY,+ title=layer.title,+ summary=_layer_summary(parent=parent, layer=layer, index=index, total=len(layers)),+ promoted_at=now,+ # Born directly in a visible status without `transition_to`, which stamps this for+ # pipeline reports, so the daily report limit counts the layer from creation.+ first_visible_at=now,+ billing_exempt_reason=billing_exempt_reason,+ )+ child_id = str(child.id)+ for judgment in judgments:+ SignalReportArtefact.append_status(+ team_id=team_id,+ report_id=child_id,+ content=judgment,+ attribution=attribution,+ reevaluate_autostart=False,+ )+ SignalReportArtefact.add_log(+ team_id=team_id,+ report_id=child_id,+ content=ReportLink(+ kind=ReportLinkKind.PART_OF,+ report_id=str(parent.id),+ reason=f"Layer {index + 1} of {len(layers)} of the research plan.",+ ),+ attribution=attribution,+ )+ if layer.depends_on is not None:+ SignalReportArtefact.add_log(+ team_id=team_id,+ report_id=child_id,+ content=ReportLink(+ kind=ReportLinkKind.DEPENDS_ON,+ report_id=child_ids[layer.depends_on],+ reason=f"Layer {index + 1} stacks on layer {layer.depends_on + 1}.",+ ),+ attribution=attribution,+ )+ child_ids.append(child_id)+ logger.info("signals.stack_plan.layers_created", report_id=str(parent.id), team_id=team_id, layers=len(child_ids))+ return child_ids+++def _pull_request_repository(url: str) -> str | None:+ parsed = GitHubIntegrationBase.parse_pull_request_url(url)+ return parsed.repository.lower() if parsed else None+++def dependency_head_branch(*, team_id: int, report_id: str, repository: str) -> str | None:+ """The head branch this report's pull request stacks on, or None to use the default base.++ A layer stacks on its oldest `depends_on` target. The branch is the one auto-start generated+ for that target's run, which is also the head of the pull request the run opened. A target with+ no open pull request has no branch to stack on: a merged one is already on the default branch.+ A target whose pull request is in another repository has no branch in `repository` either.+ """+ edges = outgoing_links(team_id=team_id, report_id=report_id, kinds=(ReportLinkKind.DEPENDS_ON,))+ if not edges:+ return None+ target_id = edges[0].target_id++ prs = fetch_implementation_prs_for_reports([target_id], team_id=team_id, using="default").get(target_id, [])+ if not any(+ pr.state in _STACKABLE_PR_STATES and _pull_request_repository(pr.url) == repository.lower() for pr in prs+ ):+ return None+ # Read from the `task_run` rows directly: the unified task view prefers the older gate row for+ # the same task, and that row carries no branch.+ rows = (+ SignalReportArtefact.objects.using("default")+ .filter(team_id=team_id, report_id=target_id, type=SignalReportArtefact.ArtefactType.TASK_RUN)+ .order_by("-created_at", "-id")+ .values_list("content", flat=True)+ )+ for content in rows:+ try:+ run = TaskRunArtefact.model_validate_json(content)+ except ValidationError:+ continue+ if run.product == SIGNALS_PRODUCT and run.type == TASK_RUN_TYPE_IMPLEMENTATION and run.automation_branch:+ return run.automation_branch+ return None+++def _dependencies_have_pull_requests(*, team_id: int, report_id: str) -> bool:+ dependency_ids = [+ edge.target_id+ for edge in outgoing_links(team_id=team_id, report_id=report_id, kinds=(ReportLinkKind.DEPENDS_ON,))+ ]+ if not dependency_ids:+ return True+ return set(dependency_ids) <= has_open_or_merged_pull_request(team_id=team_id, report_ids=dependency_ids)+++def start_unblocked_layers(*, team_id: int, report_ids: list[str]) -> list[str]:+ """Run auto-start for each layer whose dependencies all have a pull request. Returns those ids.++ A layer that is still blocked is not evaluated, so waiting writes no `autostart_skip` row on+ every pull request event. Auto-start stays the one place that decides and is idempotent, so a+ layer that already started, or that a person started by hand, starts nothing new.+ """+ from products.signals.backend.auto_start import maybe_autostart_from_report_artefacts # noqa: PLC0415++ # Only a layer still in the inbox can start. A person who archived or resolved it decided.+ ready_ids = {+ str(pk)+ for pk in SignalReport.objects.using("default")+ .filter(team_id=team_id, id__in=report_ids, status=SignalReport.Status.READY)+ .values_list("id", flat=True)+ }+ evaluated: list[str] = []+ failed: list[str] = []+ for report_id in report_ids:+ if report_id not in ready_ids:+ continue+ if SignalReport.associated_task_runs(+ report_id=report_id, team_id=team_id, product=SIGNALS_PRODUCT, type=TASK_RUN_TYPE_IMPLEMENTATION+ ):+ continue+ if not _dependencies_have_pull_requests(team_id=team_id, report_id=report_id):+ continue+ evaluated.append(report_id)+ try:+ async_to_sync(maybe_autostart_from_report_artefacts)(team_id=team_id, report_id=report_id)+ except Exception:+ # One layer that fails to start must not hold back its siblings.+ logger.exception("signals.stack_plan.layer_autostart_failed", report_id=report_id, team_id=team_id)+ failed.append(report_id)+ if failed:+ # Raise only after every sibling was tried, so the caller's retry runs. A retry skips the+ # layers that already started.+ raise RuntimeError(f"Stack layers failed to start: {', '.join(failed)}")+ return evaluated+++def start_unblocked_layers_of_plan(*, team_id: int, parent_report_id: str) -> list[str]:+ """Start the layers of a plan that can start now. A report with no layers starts nothing."""+ child_ids = [+ edge.source_id+ for edge in incoming_links(team_id=team_id, report_id=parent_report_id, kinds=(ReportLinkKind.PART_OF,))+ ]+ return start_unblocked_layers(team_id=team_id, report_ids=child_ids)+++def start_dependent_layers(*, team_id: int, report_id: str) -> list[str]:+ """Start the layers that wait on this report, now that it has a pull request."""+ dependent_ids = [+ edge.source_id+ for edge in incoming_links(team_id=team_id, report_id=report_id, kinds=(ReportLinkKind.DEPENDS_ON,))+ ]+ return start_unblocked_layers(team_id=team_id, report_ids=dependent_ids)+++def schedule_dependent_layers(*, team_id: int, report_ids: list[str]) -> None:+ """After commit, queue a start of the layers that wait on these reports."""+ from products.signals.backend.tasks import start_dependent_stack_layers # noqa: PLC0415++ for report_id in report_ids:+ transaction.on_commit(+ partial(start_dependent_stack_layers.delay, team_id=team_id, report_id=report_id), robust=True+ )diff --git a/products/signals/backend/tasks.py b/products/signals/backend/tasks.pyindex edfa9255fc50..8ca9be32ddd3 100644--- a/products/signals/backend/tasks.py+++ b/products/signals/backend/tasks.py@@ -646,6 +646,29 @@ def assign_reviewers_on_implementation_pr(team_id: int, report_id: str, pr_url:assign_reviewers_to_pull_request(team_id=team_id, report_id=report_id, pr_url=pr_url)+@shared_task(+ name="products.signals.backend.tasks.start_dependent_stack_layers",+ ignore_result=True,+ max_retries=3,+ autoretry_for=(Exception,),+ retry_backoff=True,+ soft_time_limit=210,+ time_limit=240,+)+@with_team_scope()+def start_dependent_stack_layers(team_id: int, report_id: str) -> None:+ """Start the stack layers that wait on this report, now that it has a pull request.++ Runs on a worker because auto-start creates tasks and must not hold up the pull request sync+ that queued it. A failed layer start retries with backoff, because the next pull request event+ on the report may come only at merge, when the layer can no longer stack. A retry skips the+ layers that already started.+ """+ from products.signals.backend.stack_plan import start_dependent_layers # noqa: PLC0415++ start_dependent_layers(team_id=team_id, report_id=report_id)++@shared_task(name="products.signals.backend.tasks.open_implementation_pr_for_review",ignore_result=True,diff --git a/products/signals/backend/temporal/agentic/report.py b/products/signals/backend/temporal/agentic/report.pyindex b3324961c7b0..8b35c85a7471 100644--- a/products/signals/backend/temporal/agentic/report.py+++ b/products/signals/backend/temporal/agentic/report.py@@ -107,6 +107,9 @@ class RunAgenticReportOutput:# writes the metrics they reference — a check naming a metric the report never got is dropped# there rather than stored pointing at nothing. `None` predates the field and writes none.checks: list[dict[str, Any]] | None = None+ # The plan of dependent pull requests, as `ReportLayer` dicts. The ready transition turns each+ # one into a child report. `None` predates the field and creates none.+ layers: list[dict[str, Any]] | None = None# The research sandbox task the check rows are attributed to, so the report's log names what# decided the fix was worth re-measuring. `None` for saved fixtures and pre-existing outputs.research_task_id: str | None = None@@ -982,6 +985,7 @@ async def run_agentic_report_activity(input: RunAgenticReportInput) -> RunAgenticharts=charts_payload,metrics=metrics_payload,checks=[check.model_dump(mode="json") for check in result.checks],+ layers=[layer.model_dump(mode="json") for layer in result.layers],research_task_id=result.research_task_id,charts_enabled=True,)diff --git a/products/signals/backend/temporal/summary.py b/products/signals/backend/temporal/summary.pyindex cd99a8115dec..fe9e2ae6b22e 100644--- a/products/signals/backend/temporal/summary.py+++ b/products/signals/backend/temporal/summary.py@@ -40,8 +40,9 @@ from products.signals.backend.quota import (record_quota_check_failed_open,self_driving_quota_gate,)-from products.signals.backend.report_generation.research import ActionabilityChoice+from products.signals.backend.report_generation.research import ActionabilityChoice, ReportLayerfrom products.signals.backend.report_generation.select_repo import RepoSelectionResult+from products.signals.backend.stack_plan import create_layer_reports, start_unblocked_layers_of_planfrom products.signals.backend.temporal import metricsfrom products.signals.backend.temporal.agentic.report import (RunAgenticReportInput,@@ -151,6 +152,7 @@ class ReportDecision:# Check specs the research run's verification turn authored, and the research task they are# attributed to. Empty for the no-repo branch, which does no research.checks: list[dict[str, Any]] = field(default_factory=list)+ layers: list[dict[str, Any]] = field(default_factory=list)research_task_id: str | None = None# The chart rollout state the research run saw (see `RunAgenticReportOutput.charts_enabled`).# `None` for the no-repo branch, which does no research and so never asks.@@ -458,6 +460,7 @@ class SignalReportSummaryWorkflow:charts=agentic_result.charts,metrics=agentic_result.metrics,checks=agentic_result.checks or [],+ layers=agentic_result.layers or [],research_task_id=agentic_result.research_task_id,charts_enabled=agentic_result.charts_enabled,pending_reason="agent_requested",@@ -522,6 +525,7 @@ class SignalReportSummaryWorkflow:metrics=decision.metrics,checks=decision.checks,checks_task_id=decision.research_task_id,+ layers=decision.layers,suggested_prompts=decision.suggested_prompts,charts_enabled=decision.charts_enabled,),@@ -834,6 +838,10 @@ class MarkReportReadyInput:checks: list[dict[str, Any]] | None = None# Task the check rows are attributed to: the research sandbox that authored the specs.checks_task_id: str | None = None+ # The research plan of dependent pull requests, as `ReportLayer` dicts. Each becomes a child+ # report in the same transaction. Empty or `None` creates none, which is also what an older+ # workflow history replays as.+ layers: list[dict[str, Any]] | None = None# Suggested prompts to write alongside title/summary, same three states and same replay-safe# default. The research pipeline passes `[]`: it doesn't author prompts yet, and the ones a# scout wrote were written against the summary this transition is replacing.@@ -873,6 +881,25 @@ def _write_research_checks(report: SignalReport, input: MarkReportReadyInput) ->)+def _write_stack_layers(report: SignalReport, input: MarkReportReadyInput) -> None:+ """Create one child report per layer of the research plan, inside the ready transaction.++ Unlike the checks, a layer the pipeline cannot store fails the transition: a plan with a missing+ layer would start the layers above it on a base that does not exist.+ """+ if not input.layers:+ return+ create_layer_reports(+ parent=report,+ layers=[ReportLayer.model_validate(raw) for raw in input.layers],+ attribution=(+ ArtefactAttribution.from_task(input.checks_task_id)+ if input.checks_task_id+ else ArtefactAttribution.system()+ ),+ )++@temporalio.activity.defn@scoped_temporal()@close_db_connections@@ -926,6 +953,7 @@ async def mark_report_ready_activity(input: MarkReportReadyInput) -> bool:# just stored: written earlier it would name a metric the report does not have yet,# and written later it could survive a rollback that took the metric with it._write_research_checks(report, input)+ _write_stack_layers(report, input)return _ReportTransition(run_count=report.run_count,chart_count=len(report.charts or []),@@ -1054,6 +1082,10 @@ async def maybe_autostart_implementation_activity(input: MaybeAutostartImplement)else:await maybe_autostart_from_report_artefacts(team_id=input.team_id, report_id=input.report_id)+ # A plan never starts its own run, so its first layers start here, at the same settle point.+ await database_sync_to_async(start_unblocked_layers_of_plan, thread_sensitive=False)(+ team_id=input.team_id, parent_report_id=input.report_id+ )@dataclassdiff --git a/products/signals/backend/test/test_auto_start.py b/products/signals/backend/test/test_auto_start.pyindex 78d11b4dee93..64650211a64c 100644--- a/products/signals/backend/test/test_auto_start.py+++ b/products/signals/backend/test/test_auto_start.py@@ -18,7 +18,7 @@ from posthog.models.scoping import team_scopefrom posthog.temporal.oauth import grants_scratchpad_writefrom products.signals.backend.agent_runtime import AgentRuntime-from products.signals.backend.artefact_schemas import PullRequestLink, ReportLink+from products.signals.backend.artefact_schemas import PullRequestLink, ReportLink, TaskRunArtefactfrom products.signals.backend.auto_start import (NO_SUPERSEDE,ImplementationReportContent,@@ -999,6 +999,20 @@ async def test_typed_links_hold_back_autostart(link, expect_skip_reason, link_beelif link == "depends_on_with_open_pr":dependency = _report()_attach_open_pr(dependency, 22)+ dependency_task = Task.objects.create(+ team_id=team.id, title="dependency", description="d", origin_product=Task.OriginProduct.SIGNAL_REPORT+ )+ SignalReportArtefact.add_log(+ team_id=team.id,+ report_id=str(dependency.id),+ content=TaskRunArtefact(+ product="signals",+ type="implementation",+ task_id=str(dependency_task.id),+ automation_branch="posthog-self-driving/dependency-abc123",+ ),+ attribution=ArtefactAttribution.from_task(str(dependency_task.id)),+ )_link(team.id, report, dependency, ReportLinkKind.DEPENDS_ON)elif link == "incoming_part_of":_link(team.id, _report(), report, ReportLinkKind.PART_OF)@@ -1056,6 +1070,12 @@ async def test_typed_links_hold_back_autostart(link, expect_skip_reason, link_beassert mock_create.call_count == 1assert skips == []assert skipped_events == []+ if link == "depends_on_with_open_pr" and not link_before_lock:+ # The stacked run starts on the dependency's head branch and keeps it as the PR base.+ created = mock_create.call_args.kwargs+ assert created["branch"] == "posthog-self-driving/dependency-abc123"+ assert created["stack_base_branch"] == "posthog-self-driving/dependency-abc123"+ assert "with `posthog-self-driving/dependency-abc123` as its base" in created["description"]else:assert outcome.status == "blocked"assert mock_create.call_count == 0diff --git a/products/signals/backend/test/test_stack_plan.py b/products/signals/backend/test/test_stack_plan.pynew file mode 100644index 000000000000..d4e6d7020b90--- /dev/null+++ b/products/signals/backend/test/test_stack_plan.py@@ -0,0 +1,352 @@+from posthog.test.base import BaseTest+from unittest.mock import AsyncMock, patch++from django.db import transaction+from django.test import SimpleTestCase++from parameterized import parameterized++from products.signals.backend.artefact_attribution import ArtefactAttribution+from products.signals.backend.artefact_schemas import (+ PullRequestLink,+ SafetyJudgment,+ SuggestedReviewerEntry,+ SuggestedReviewers,+)+from products.signals.backend.enums import ReportLinkKind+from products.signals.backend.models import SignalReport, SignalReportArtefact, SignalReportPullRequest, SignalScoutRun+from products.signals.backend.report_generation.research import (+ MAX_REPORT_LAYER_TITLE_LENGTH,+ ActionabilityAssessment,+ ActionabilityChoice,+ Priority,+ PriorityAssessment,+ ReportLayer,+ ReportPresentationOutput,+)+from products.signals.backend.report_generation.select_repo import RepoSelectionResult+from products.signals.backend.stack_plan import (+ create_layer_reports,+ dependency_head_branch,+ start_dependent_layers,+ start_unblocked_layers_of_plan,+)+from products.signals.backend.task_run_artefacts import record_implementation_task+from products.signals.backend.test.test_billing import _seed_canonical_scout_skill+from products.signals.backend.typed_report_links import outgoing_links+from products.tasks.backend.models import Task, TaskRun++AUTOSTART = "products.signals.backend.auto_start.maybe_autostart_from_report_artefacts"+++class TestReportLayersValidation(SimpleTestCase):+ @parameterized.expand(+ [+ ("single_layer_is_no_plan", [None], []),+ ("too_many_layers_is_no_plan", [None] * 7, []),+ ("stack_keeps_its_order", [None, 0, 1], [None, 0, 1]),+ ("forward_reference_falls_back_to_previous", [2, 5, 1], [None, 0, 1]),+ ]+ )+ def test_layers_form_an_acyclic_plan(self, _name: str, depends_on: list[int | None], expected: list[int | None]):+ output = ReportPresentationOutput.model_validate(+ {+ "title": "feat(x): plan",+ "summary": "s",+ "layers": [+ {"title": f"layer {index}", "scope": "scope", "depends_on": dep}+ for index, dep in enumerate(depends_on)+ ],+ }+ )+ assert [layer.depends_on for layer in output.layers] == expected++ @parameterized.expand(+ [+ ("empty_title", {"title": "", "scope": "scope", "depends_on": 0}),+ ("whitespace_title", {"title": " \n", "scope": "scope", "depends_on": 0}),+ ("empty_scope", {"title": "layer 1", "scope": "", "depends_on": 0}),+ ("whitespace_scope", {"title": "layer 1", "scope": " \t", "depends_on": 0}),+ ("missing_scope", {"title": "layer 1", "depends_on": 0}),+ ("title_too_long", {"title": "x" * (MAX_REPORT_LAYER_TITLE_LENGTH + 1), "scope": "scope"}),+ ("list_depends_on", {"title": "layer 1", "scope": "scope", "depends_on": [0]}),+ ]+ )+ def test_malformed_layer_is_no_plan(self, _name: str, layer: dict[str, object]):+ output = ReportPresentationOutput.model_validate(+ {+ "title": "feat(x): plan",+ "summary": "s",+ "layers": [{"title": "layer 0", "scope": "scope"}, layer],+ }+ )+ assert output.title == "feat(x): plan"+ assert output.layers == []+++class TestStackPlan(BaseTest):+ def setUp(self):+ super().setUp()+ self.parent = SignalReport.objects.create(+ team=self.team, status=SignalReport.Status.READY, title="feat(x): the plan", summary="plan"+ )+ for content in (+ SafetyJudgment(choice=True),+ ActionabilityAssessment(+ explanation="clear", actionability=ActionabilityChoice.IMMEDIATELY_ACTIONABLE, already_addressed=False+ ),+ PriorityAssessment(explanation="important", priority=Priority.P2),+ RepoSelectionResult(repository="example/repo", reason="selected"),+ ):+ SignalReportArtefact.append_status(+ team_id=self.team.id,+ report_id=str(self.parent.id),+ content=content,+ attribution=ArtefactAttribution.system(),+ )++ def _layers(self) -> list[ReportLayer]:+ return [+ ReportLayer(title="feat(x): schema", scope="Add the schema."),+ ReportLayer(title="feat(x): api", scope="Add the API.", depends_on=0),+ ReportLayer(title="feat(x): ui", scope="Add the UI.", depends_on=1),+ ]++ def _create_layers(self) -> list[str]:+ with transaction.atomic():+ return create_layer_reports(+ parent=self.parent, layers=self._layers(), attribution=ArtefactAttribution.system()+ )++ def _start_run(self, report_id: str, branch: str) -> None:+ task = Task.objects.create(+ team=self.team,+ signal_report_id=report_id,+ origin_product=Task.OriginProduct.SIGNAL_REPORT,+ title="Implementation",+ repository="example/repo",+ internal=True,+ )+ with transaction.atomic():+ record_implementation_task(+ team_id=self.team.id, report_id=report_id, task_id=str(task.id), automation_branch=branch+ )++ def _attach_pull_request(self, report_id: str, number: int, state: str, repository: str = "example/repo") -> None:+ pr = SignalReportPullRequest.objects.create(+ team_id=self.team.id,+ repository=repository,+ number=number,+ url=f"https://github.com/{repository}/pull/{number}",+ state=state,+ )+ link = SignalReportArtefact.add_log(+ team_id=self.team.id,+ report_id=report_id,+ content=PullRequestLink(url=pr.url),+ attribution=ArtefactAttribution.system(),+ )+ link.pull_request = pr+ link.save(update_fields=["pull_request"])++ def test_each_layer_becomes_a_ready_report_linked_into_the_stack(self):+ child_ids = self._create_layers()++ children = {str(r.id): r for r in SignalReport.objects.filter(id__in=child_ids)}+ assert [children[child_id].title for child_id in child_ids] == [+ "feat(x): schema",+ "feat(x): api",+ "feat(x): ui",+ ]+ assert all(child.status == SignalReport.Status.READY for child in children.values())+ for index, child_id in enumerate(child_ids):+ links = outgoing_links(team_id=self.team.id, report_id=child_id)+ assert [(edge.kind, edge.target_id) for edge in links if edge.kind == ReportLinkKind.PART_OF] == [+ (ReportLinkKind.PART_OF, str(self.parent.id))+ ]+ expected_dependency = [child_ids[index - 1]] if index else []+ assert [edge.target_id for edge in links if edge.kind == ReportLinkKind.DEPENDS_ON] == expected_dependency+ # Auto-start reads these on the layer, so the layer can start without its own research.+ assert set(SignalReportArtefact.objects.filter(report_id=child_id).values_list("type", flat=True)) >= {+ "safety_judgment",+ "actionability_judgment",+ "priority_judgment",+ "repo_selection",+ }++ @parameterized.expand(+ [+ ("pipeline_list_is_inherited", False, 3),+ ("user_edited_list_is_not_inherited", True, 0),+ ]+ )+ def test_layers_inherit_only_a_pipeline_reviewer_list(self, _name: str, edited_by_user: bool, expected: int):+ SignalReportArtefact.append_status(+ team_id=self.team.id,+ report_id=str(self.parent.id),+ content=SuggestedReviewers(root=[SuggestedReviewerEntry(github_login="octocat")]),+ attribution=ArtefactAttribution.from_user(self.user.id) if edited_by_user else ArtefactAttribution.system(),+ reevaluate_autostart=False,+ )++ child_ids = self._create_layers()++ inherited = SignalReportArtefact.objects.filter(+ report_id__in=child_ids, type=SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS+ )+ assert inherited.count() == expected+ assert not inherited.filter(created_by__isnull=False).exists()++ @parameterized.expand(+ [+ ("billable_plan", None, False, None),+ (+ "stored_exemption",+ SignalReport.BillingExemptReason.POSTHOG_SYSTEM,+ False,+ SignalReport.BillingExemptReason.POSTHOG_SYSTEM,+ ),+ ("exempt_scout_origin", None, True, SignalReport.BillingExemptReason.POSTHOG_HEALTH_CHECK),+ ]+ )+ def test_layers_keep_the_plan_billing_exemption(+ self, _name: str, stored_reason: str | None, emitted_by_exempt_scout: bool, expected: str | None+ ):+ self.parent.billing_exempt_reason = stored_reason+ self.parent.save(update_fields=["billing_exempt_reason"])+ if emitted_by_exempt_scout:+ _seed_canonical_scout_skill(self.team, "signals-scout-health-checks")+ task = Task.objects.create(team=self.team, title="scout", description="d")+ SignalScoutRun.objects.create(+ team=self.team,+ task_run=TaskRun.objects.create(team=self.team, task=task),+ skill_name="signals-scout-health-checks",+ skill_version=1,+ emitted_report_ids=[str(self.parent.id)],+ )++ child_ids = self._create_layers()++ assert set(SignalReport.objects.filter(id__in=child_ids).values_list("billing_exempt_reason", flat=True)) == {+ expected+ }++ @parameterized.expand(+ [+ ("open_pull_request_keeps_the_single_pr_path", SignalReportPullRequest.State.OPEN, 0),+ ("merged_pull_request_keeps_the_single_pr_path", SignalReportPullRequest.State.MERGED, 0),+ ("closed_pull_request_allows_layers", SignalReportPullRequest.State.CLOSED, 3),+ ]+ )+ def test_a_report_with_its_own_pull_request_gets_no_layers(self, _name: str, state: str, expected: int):+ self._attach_pull_request(str(self.parent.id), 1, state)++ child_ids = self._create_layers()++ assert len(child_ids) == expected+ assert SignalReport.objects.filter(team=self.team).count() == 1 + expected++ def test_a_plan_that_already_has_layers_keeps_them(self):+ first = self._create_layers()+ second = self._create_layers()++ assert len(first) == 3+ assert second == []+ assert SignalReport.objects.filter(team=self.team).count() == 4++ def test_only_the_first_layer_starts_with_the_plan(self):+ child_ids = self._create_layers()++ with patch(AUTOSTART, new_callable=AsyncMock) as autostart:+ started = start_unblocked_layers_of_plan(team_id=self.team.id, parent_report_id=str(self.parent.id))++ assert started == [child_ids[0]]+ autostart.assert_awaited_once_with(team_id=self.team.id, report_id=child_ids[0])++ def test_a_failed_layer_start_raises_after_its_siblings_are_tried(self):+ with transaction.atomic():+ child_ids = create_layer_reports(+ parent=self.parent,+ layers=[+ ReportLayer(title="feat(x): api", scope="Add the API."),+ ReportLayer(title="feat(x): docs", scope="Add the docs."),+ ],+ attribution=ArtefactAttribution.system(),+ )++ with patch(AUTOSTART, new_callable=AsyncMock, side_effect=[RuntimeError("temporal down"), None]) as autostart:+ with self.assertRaises(RuntimeError):+ start_unblocked_layers_of_plan(team_id=self.team.id, parent_report_id=str(self.parent.id))++ assert sorted(call.kwargs["report_id"] for call in autostart.await_args_list) == sorted(child_ids)++ def test_the_next_layer_starts_when_its_dependency_opens_a_pull_request(self):+ child_ids = self._create_layers()++ with patch(AUTOSTART, new_callable=AsyncMock) as autostart:+ assert start_dependent_layers(team_id=self.team.id, report_id=child_ids[0]) == []+ self._attach_pull_request(child_ids[0], 1, SignalReportPullRequest.State.OPEN)+ assert start_dependent_layers(team_id=self.team.id, report_id=child_ids[0]) == [child_ids[1]]++ autostart.assert_awaited_once_with(team_id=self.team.id, report_id=child_ids[1])++ def test_an_archived_layer_does_not_start_when_its_dependency_opens_a_pull_request(self):+ child_ids = self._create_layers()+ self._attach_pull_request(child_ids[0], 1, SignalReportPullRequest.State.OPEN)+ SignalReport.objects.filter(id=child_ids[1]).update(status=SignalReport.Status.SUPPRESSED)++ with patch(AUTOSTART, new_callable=AsyncMock) as autostart:+ assert start_dependent_layers(team_id=self.team.id, report_id=child_ids[0]) == []++ autostart.assert_not_awaited()++ def test_a_layer_that_already_started_is_not_started_again(self):+ child_ids = self._create_layers()+ self._attach_pull_request(child_ids[0], 1, SignalReportPullRequest.State.OPEN)+ self._start_run(child_ids[1], "posthog-self-driving/api-abc123")++ with patch(AUTOSTART, new_callable=AsyncMock) as autostart:+ assert start_dependent_layers(team_id=self.team.id, report_id=child_ids[0]) == []++ autostart.assert_not_awaited()++ @parameterized.expand(+ [+ (+ "open_dependency_is_the_base",+ SignalReportPullRequest.State.OPEN,+ "example/repo",+ "posthog-self-driving/schema-abc123",+ ),+ (+ "draft_dependency_is_the_base",+ SignalReportPullRequest.State.DRAFT,+ "example/repo",+ "posthog-self-driving/schema-abc123",+ ),+ ("merged_dependency_uses_the_default_base", SignalReportPullRequest.State.MERGED, "example/repo", None),+ (+ "dependency_in_another_repository_uses_the_default_base",+ SignalReportPullRequest.State.OPEN,+ "other/repo",+ None,+ ),+ (+ "unknown_dependency_is_the_base",+ SignalReportPullRequest.State.UNKNOWN,+ "example/repo",+ "posthog-self-driving/schema-abc123",+ ),+ ]+ )+ def test_a_layer_stacks_on_its_dependency_head_branch(+ self, _name: str, state: str, pr_repository: str, expected: str | None+ ):+ child_ids = self._create_layers()+ self._start_run(child_ids[0], "posthog-self-driving/schema-abc123")+ self._attach_pull_request(child_ids[0], 1, state, repository=pr_repository)++ assert (+ dependency_head_branch(team_id=self.team.id, report_id=child_ids[1], repository="Example/Repo") == expected+ )+ assert dependency_head_branch(team_id=self.team.id, report_id=child_ids[0], repository="example/repo") is Nonediff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 787158824d3e..2ac7cc54a838 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -2600,6 +2600,7 @@ _PROTECTED_RUN_STATE_KEYS = frozenset({"run_source","pr_base_branch",+ "stack_base_branch","github_credential_source",TASK_OWNERSHIP_VERSION_STATE_KEY,"pr_authorship_mode",@@ -8370,7 +8371,7 @@ def warm_task_resume_sandbox("custom_image_id": custom_image_id,}extra_state.update(_github_credential_source_extra_state(resolved_pr_authorship_mode, None))- for protected_key in ("wizard_head_branch", "self_driving_head_branch", "github_read_access"):+ for protected_key in ("wizard_head_branch", "self_driving_head_branch", "stack_base_branch", "github_read_access"):if protected_key in (previous_run.state or {}):extra_state[protected_key] = (previous_run.state or {})[protected_key]if "imported_from" in (previous_run.state or {}):@@ -8760,6 +8761,11 @@ def run_task(prev_self_driving_head_branch = (previous_run.state or {}).get("self_driving_head_branch")if prev_self_driving_head_branch:extra_state["self_driving_head_branch"] = prev_self_driving_head_branch+ # The launch protects the stacked base only while the run is still on that exact branch, so+ # carrying the marker is safe once the run moved to its own head branch.+ prev_stack_base_branch = (previous_run.state or {}).get("stack_base_branch")+ if prev_stack_base_branch:+ extra_state["stack_base_branch"] = prev_stack_base_branchif pipeline_rerun and task.internal and is_implementation:extra_state["ai_stage"] = "implementation"diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.pyindex e8283b7c189c..ea169530f0d3 100644--- a/products/tasks/backend/models.py+++ b/products/tasks/backend/models.py@@ -1090,6 +1090,7 @@ class Task(DeletedMetaFields, models.Model):wizard_config: dict | None = None,wizard_head_branch: str | None = None,self_driving_head_branch: str | None = None,+ stack_base_branch: str | None = None,pending_user_message: str | None = None,custom_image_builder_id: str | None = None,custom_image_id: str | None = None,@@ -1352,6 +1353,12 @@ class Task(DeletedMetaFields, models.Model):if self_driving_head_branch:extra_state["self_driving_head_branch"] = self_driving_head_branch+ # A stacked run checks out the head branch of the pull request it builds on. That branch+ # heads an open PR, so without this marker the launch would protect that PR's base instead+ # and let the run push into the lower layer.+ if stack_base_branch:+ extra_state["stack_base_branch"] = stack_base_branch+# The first message handed to the agent once its server is ready (forward_pending_user_message# reads it from run state). Without it a background run boots the agent idle — it never gets a# prompt and just sits there while relay_sandbox_events waits for events that never come.@@ -1466,6 +1473,7 @@ class Task(DeletedMetaFields, models.Model):wizard_config: dict | None = None,wizard_head_branch: str | None = None,self_driving_head_branch: str | None = None,+ stack_base_branch: str | None = None,pending_user_message: str | None = None,workflow_id_prefix: str | None = None,scheduled_at: datetime | None = None,@@ -1527,6 +1535,7 @@ class Task(DeletedMetaFields, models.Model):wizard_config=wizard_config,wizard_head_branch=wizard_head_branch,self_driving_head_branch=self_driving_head_branch,+ stack_base_branch=stack_base_branch,pending_user_message=pending_user_message,custom_image_builder_id=custom_image_builder_id,custom_image_id=custom_image_id,diff --git a/products/tasks/backend/temporal/process_task/activities/start_agent_server.py b/products/tasks/backend/temporal/process_task/activities/start_agent_server.pyindex 24923f30a844..3802d2da6087 100644--- a/products/tasks/backend/temporal/process_task/activities/start_agent_server.py+++ b/products/tasks/backend/temporal/process_task/activities/start_agent_server.py@@ -130,6 +130,12 @@ def _resolve_protected_base_branch(ctx: TaskProcessingContext) -> str | None:if not ctx.has_github_credentials:return branch+ # A stacked run starts on the head branch of the pull request it builds on, and that branch is+ # its PR base. Only the exact branch the run was created for counts, so a resume that moved to+ # the run's own head branch takes the lookup below.+ if (ctx.state or {}).get("stack_base_branch") == branch:+ return branch+try:integration: GitHubIntegration | UserGitHubIntegrationif ctx.github_integration_id:diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py b/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.pyindex f9baecff55ad..b0a0af3c1ce5 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py@@ -668,6 +668,26 @@ def test_resolve_protected_base_branch(mocker, pr_base, branch, expected) -> Nonassert _resolve_protected_base_branch(context) == expected+ "stack_base_branch,expected",+ [+ # A stacked run starts on the lower layer's head: protect that head as the PR base.+ ("posthog-self-driving/layer-one-abc123", "posthog-self-driving/layer-one-abc123"),+ # The marker names another branch, so the run moved on and the open PR lookup decides.+ ("posthog-self-driving/other-def456", "master"),+ ],+)+def test_resolve_protected_base_branch_for_stacked_run(mocker, stack_base_branch, expected) -> None:+ _mock_github_integration(mocker, pr_base="master")+ context = _context(+ github_integration_id=42,+ repository="PostHog/posthog",+ branch="posthog-self-driving/layer-one-abc123",+ state={"stack_base_branch": stack_base_branch},+ )+ assert _resolve_protected_base_branch(context) == expected++def test_resolve_protected_base_skips_lookup_without_repository(mocker) -> None:get = mocker.patch("products.tasks.backend.temporal.process_task.activities.start_agent_server.Integration.objects.get",diff --git a/products/tasks/backend/tests/test_facade.py b/products/tasks/backend/tests/test_facade.pyindex e1f66562564d..aa76c0e2b2b7 100644--- a/products/tasks/backend/tests/test_facade.py+++ b/products/tasks/backend/tests/test_facade.py@@ -1207,7 +1207,13 @@ class TestFacadeReadsAndMappers(TestCase):else:self.assertNotIn("custom_image_id", new_run.state)- def test_run_task_resume_carries_self_driving_head_branch(self):+ @parameterized.expand(+ [+ ("self_driving_head_branch", "posthog-self-driving/fix-abc123"),+ ("stack_base_branch", "posthog-self-driving/schema-abc123"),+ ]+ )+ def test_run_task_resume_carries_self_driving_branch_stamp(self, state_key: str, branch: str):# The signals review carve-out binds a PR to its run by matching the PR head ref against the# PATCH-protected state.self_driving_head_branch stamp. A resume mints a new run, so the# stamp must be copied forward or the carve-out stops matching the successor — the receiver@@ -1219,7 +1225,7 @@ class TestFacadeReadsAndMappers(TestCase):task=task,team=self.team,status=TaskRun.Status.COMPLETED,- state={"self_driving_head_branch": "posthog-self-driving/fix-abc123"},+ state={state_key: branch},)with patch("products.tasks.backend.facade.api._trigger_task_processing_workflow", return_value=None):@@ -1232,7 +1238,7 @@ class TestFacadeReadsAndMappers(TestCase):assert result is not None and result.error is Nonenew_run = task.runs.exclude(id=previous_run.id).get()- self.assertEqual(new_run.state.get("self_driving_head_branch"), "posthog-self-driving/fix-abc123")+ self.assertEqual(new_run.state.get(state_key), branch)@parameterized.expand([diff --git a/products/tasks/backend/tests/test_warm_facade.py b/products/tasks/backend/tests/test_warm_facade.pyindex f81beb5b4f74..b7398cecae81 100644--- a/products/tasks/backend/tests/test_warm_facade.py+++ b/products/tasks/backend/tests/test_warm_facade.py@@ -1665,6 +1665,7 @@ class TestWarmTaskResumeSandbox(APIBaseTest):extra_state={"snapshot_external_id": "snapshot-1","pr_base_branch": base_branch,+ "stack_base_branch": "release","auto_publish": True,"runtime_adapter": "claude","model": "claude-sonnet-5",@@ -1696,6 +1697,7 @@ class TestWarmTaskResumeSandbox(APIBaseTest):assert warm_run.state["pr_base_branch"] == base_branchassert warm_run.state["resume_from_run_id"] == str(terminal.id)assert warm_run.state["snapshot_external_id"] == "snapshot-1"+ assert warm_run.state["stack_base_branch"] == "release"assert warm_run.state["await_user_message"] is Trueassert warm_run.state["auto_publish"] is Trueassert warm_run.state["pr_authorship_mode"] == "bot"