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(notebooks): add example data-analysis notebook evals (#93127)

Sinan Kucukkoseler1a24c289e89a
diff --git a/products/notebooks/evals/eval_notebook_analysis.py b/products/notebooks/evals/eval_notebook_analysis.py
new file mode 100644
index 000000000000..826020797bb8
--- /dev/null
+++ b/products/notebooks/evals/eval_notebook_analysis.py
@@ -0,0 +1,137 @@
+"""Open-ended eval cases for churn analysis in a notebook over MCP.
+
+Unlike ``eval_notebook_cells``, these cases name only the question, not the cells. They
+check that the agent turns a churn-prediction request into a notebook that pulls behavioural
+signals with SQL, carries the analysis into Python, and lands on a conclusion — the shape of
+a real analysis, graded qualitatively rather than by matching an exact query.
+
+Each case is seeded by ``seed_churn_signal``, which plants a small cohort of accounts that
+were power users early in the demo window and then went completely silent — the textbook
+churn shape. That gives the run a synthetic ground truth to grade the prediction against.
+
+Four layers grade each case:
+
+- ``NotebookCreated`` / ``CellRunsCompleted`` — the outcome, read from the database: a markdown
+ notebook exists, and both a SQL (``hogql``) and a Python cell reached a completed run. This is
+ what proves the agent used *both* lanes rather than doing everything in one.
+- ``NotebookApproachQuality`` — the approach, an LLM judge over the cells the agent authored:
+ did it pull the right behavioural signals and reason its way to a churn conclusion.
+- ``ChurnCohortSurfaced`` — the prediction itself: what fraction of the planted silent accounts
+ the notebook actually named as at-risk.
+
+Because these cases need a completed Python run, run them on docker:
+ hogli evals eval_notebook_analysis --provider docker
+ hogli evals eval_notebook_analysis --eval churn_from_file_sharing --provider docker
+"""
+
+from __future__ import annotations
+
+from products.notebooks.evals.scorers import (
+ CellRunsCompleted,
+ ChurnCohortSurfaced,
+ NotebookApproachQuality,
+ NotebookCreated,
+)
+from products.notebooks.evals.seeders import seed_churn_signal
+from products.posthog_ai.eval_harness.base import SandboxedPublicEval
+from products.posthog_ai.eval_harness.config import SandboxedEvalCase
+from products.posthog_ai.eval_harness.harness.context import EvalContext
+from products.posthog_ai.eval_harness.scorers import RequiredToolCall
+
+# Both lanes must complete: the SQL cell pulls the behavioural signals, the Python cell does the
+# churn analysis over them. Naming both is what separates "wrote a python cell" from "the kernel
+# ran it", and it is how these cases assert the agent used SQL *and* Python.
+_SQL_AND_PYTHON = {"node_types": ["hogql", "python"]}
+
+
+async def eval_notebook_analysis(ctx: EvalContext) -> None:
+ cases: list[SandboxedEvalCase] = [
+ SandboxedEvalCase(
+ name="churn_from_file_sharing",
+ prompt=(
+ "I want to predict churn for our file-sharing feature based on how people use it. "
+ "Create a notebook that pulls each account's file-sharing and download behaviour "
+ "with SQL, then works out in Python which accounts look most likely to churn and "
+ "why. Finish with a short summary of the signals that matter most."
+ ),
+ expected={
+ "notebook_created": {},
+ "cell_runs_completed": _SQL_AND_PYTHON,
+ "churn_cohort_surfaced": {},
+ "notebook_approach_quality": {
+ "approach": (
+ "Uses SQL to pull per-account file-sharing engagement from behavioural events "
+ "such as shared_file_link, downloaded_file, and uploaded_file, with enough "
+ "history to show a trend (for example weekly counts or recent vs earlier "
+ "activity). Carries those dataframes into Python to derive a churn signal — for "
+ "instance flagging accounts whose sharing or downloading has fallen off, or "
+ "scoring/ranking accounts by risk — rather than eyeballing raw rows. Ends with a "
+ "conclusion that names which behavioural signals point to churn."
+ )
+ },
+ },
+ setup=seed_churn_signal,
+ ),
+ SandboxedEvalCase(
+ name="churn_from_upload_activity",
+ prompt=(
+ "Create a notebook to predict which users are likely to churn based on their "
+ "file-upload behaviour over time. Use SQL to get weekly upload activity per user, "
+ "then use Python to spot the accounts whose usage is trailing off and rank them by "
+ "churn risk. Wrap up with a markdown summary of what you found."
+ ),
+ expected={
+ "notebook_created": {},
+ "cell_runs_completed": _SQL_AND_PYTHON,
+ "churn_cohort_surfaced": {},
+ "notebook_approach_quality": {
+ "approach": (
+ "Uses SQL to pull weekly uploaded_file activity per account or user across "
+ "several weeks, so a trend is visible. Uses Python over that dataframe to detect "
+ "declining usage — comparing recent weeks against earlier ones, or fitting a "
+ "slope — and ranks or flags the accounts most at risk. Ends with a summary that "
+ "explains which accounts look most likely to churn and on what basis."
+ )
+ },
+ },
+ setup=seed_churn_signal,
+ ),
+ SandboxedEvalCase(
+ name="churn_open_ended",
+ prompt=(
+ "I want to predict churn based on user behaviour. Build a notebook that figures out "
+ "which behavioural signals separate users who stick around from users who leave, and "
+ "use them to flag the accounts most at risk. Explain your approach as you go."
+ ),
+ expected={
+ "notebook_created": {},
+ "cell_runs_completed": _SQL_AND_PYTHON,
+ "churn_cohort_surfaced": {},
+ "notebook_approach_quality": {
+ "approach": (
+ "Chooses sensible behavioural churn signals for a file-storage product on its own "
+ "— activity frequency (logged_in, uploaded_file, downloaded_file, shared_file_link) "
+ "and negative signals (downgraded_plan, activity dropping to zero) — and pulls them "
+ "with SQL. Uses Python to compare retained versus lapsed users on those signals, or "
+ "to build a risk score, rather than asserting a churn definition without deriving it. "
+ "Explains the reasoning and flags the most at-risk accounts with a conclusion a "
+ "reader can act on."
+ )
+ },
+ },
+ setup=seed_churn_signal,
+ ),
+ ]
+
+ await SandboxedPublicEval(
+ experiment_name="sandboxed-notebook-analysis-cli",
+ cases=cases,
+ scorers=[
+ RequiredToolCall({"notebooks-add-cell"}),
+ NotebookCreated(),
+ CellRunsCompleted(),
+ ChurnCohortSurfaced(),
+ NotebookApproachQuality(),
+ ],
+ ctx=ctx,
+ )
diff --git a/products/notebooks/evals/scorers.py b/products/notebooks/evals/scorers.py
index af3dd9b6c97b..4bde2c9e7458 100644
--- a/products/notebooks/evals/scorers.py
+++ b/products/notebooks/evals/scorers.py
@@ -1,26 +1,41 @@
"""Scorers for the notebook evals.
-These grade the notebook the agent left behind, not the transcript that describes it.
-A cell run that is dispatched and one that finishes look nearly identical in the log —
-the tool returns ``status: running`` either way — and it is the finished run whose
-result the notebook renders, so the run rows are the honest source.
+``NotebookCreated`` and ``CellRunsCompleted`` grade the notebook the agent left behind,
+not the transcript that describes it. A cell run that is dispatched and one that finishes
+look nearly identical in the log — the tool returns ``status: running`` either way — and it
+is the finished run whose result the notebook renders, so the run rows are the honest source.
Reading the ORM means running async: the engine dispatches every scorer through
``eval_async``, and the base class's sync branch would execute Django ORM calls on the
event loop, which Django's async-safety guard rejects.
+
+``NotebookApproachQuality`` is the qualitative layer. It reads the cells the agent authored
+from the tool-call transcript rather than the database, because the question it asks is about
+the *approach* the agent took — the SQL it wrote, the Python it wrote, the story it told —
+which is exactly what the ``notebooks-add-cell`` calls carry. Whether those cells actually
+ran is a different question, and ``CellRunsCompleted`` already answers it from the run rows.
"""
from __future__ import annotations
+import re
import asyncio
from typing import Any
+from posthog.dataclasses import frozen
+
from products.notebooks.backend.markdown_conversion import MARKDOWN_NOTEBOOK_NODE_TYPE
from products.notebooks.backend.models import Notebook, NotebookNodeRun
-from products.posthog_ai.eval_harness.scorers import AsyncOnlyScorerMixin
+from products.posthog_ai.eval_harness.log_parser import LogParser, ToolCall
+from products.posthog_ai.eval_harness.scorers import (
+ GRADED_ALIGNMENT_CHOICE_SCORES,
+ JUDGE_MODEL,
+ AsyncOnlyScorerMixin,
+ JudgedScorer,
+)
from products.posthog_ai.eval_harness.scorers.contract import Score, Scorer
-__all__ = ["CellRunsCompleted", "NotebookCreated"]
+__all__ = ["CellRunsCompleted", "ChurnCohortSurfaced", "NotebookApproachQuality", "NotebookCreated"]
def _seeded_team_id(output: dict | None) -> int | None:
@@ -53,6 +68,46 @@ def _markdown_body(content: Any) -> str | None:
return markdown if isinstance(markdown, str) and markdown else None
+_CELL_TAG_START = re.compile(r"^<([A-Z][A-Za-z0-9]*)(?=[\s/>])")
+
+
+def _cell_block_end(lines: list[str], start: int, tag_name: str) -> int | None:
+ """Index of the line that closes the cell block opened at ``start``, or None if unclosed."""
+ block: list[str] = []
+ cursor = start
+ while cursor < len(lines) and (cursor == start or lines[cursor].strip()):
+ block.append(lines[cursor])
+ scanned = "\n".join(block).strip()
+ if scanned.endswith("/>") or f"</{tag_name}>" in scanned:
+ return cursor
+ cursor += 1
+ return None
+
+
+def _notebook_prose(markdown: str) -> str:
+ """The notebook markdown with every component cell block removed.
+
+ A finished run writes its result back into the cell tag, so the stored document also
+ carries the query's first page of rows and the run's stdout. The prose around the
+ cells is what the agent chose to say, which is where a conclusion lives.
+
+ Mirrors the block scan in ``services/mcp/src/tools/notebooks/cellTags.ts``: a block
+ opens on a line that starts a component tag and closes on the line that ends it.
+ """
+ lines = markdown.split("\n")
+ kept: list[str] = []
+ index = 0
+ while index < len(lines):
+ opening = _CELL_TAG_START.match(lines[index].strip())
+ end = _cell_block_end(lines, index, opening.group(1)) if opening else None
+ if end is None:
+ kept.append(lines[index])
+ index += 1
+ continue
+ index = end + 1
+ return "\n".join(kept)
+
+
class NotebookCreated(AsyncOnlyScorerMixin, Scorer):
"""Binary: does the case's team hold a markdown notebook the agent created?
@@ -106,6 +161,12 @@ class CellRunsCompleted(AsyncOnlyScorerMixin, Scorer):
``duckdb`` runs go out to the notebook kernel. Naming both is what separates "the
agent wrote a python cell" from "the kernel actually ran it", and the observed
statuses land in the metadata so a failure says which of the two happened.
+
+ The required types must all complete in a *single* notebook. Grading the team's
+ runs in aggregate would let a scratch or retry notebook's SQL run and another
+ notebook's Python run satisfy the requirement together, with neither notebook
+ holding the whole analysis. Deleting a notebook is a soft delete, so its runs
+ outlive it — they are skipped for the same reason.
"""
def _name(self) -> str:
@@ -123,15 +184,20 @@ class CellRunsCompleted(AsyncOnlyScorerMixin, Scorer):
return Score(name=self._name(), score=0.0, metadata={"reason": "No seed.team_id — case needs a seeder"})
runs = await asyncio.to_thread(self._read_runs, team_id)
- completed = {run["node_type"] for run in runs if run["status"] == NotebookNodeRun.Status.DONE}
- missing = [node_type for node_type in required if node_type not in completed]
- if missing:
+ completed_by_notebook: dict[str, set[str]] = {}
+ for run in runs:
+ if run["status"] == NotebookNodeRun.Status.DONE:
+ completed_by_notebook.setdefault(run["notebook_short_id"], set()).add(run["node_type"])
+
+ required_set = set(required)
+ if not any(required_set <= completed for completed in completed_by_notebook.values()):
return Score(
name=self._name(),
score=0.0,
metadata={
- "reason": "No completed run for every required cell type",
- "missing_node_types": missing,
+ "reason": "No single notebook has a completed run for every required cell type",
+ "required": required,
+ "completed_by_notebook": {nb: sorted(types) for nb, types in completed_by_notebook.items()},
"runs": runs,
},
)
@@ -140,8 +206,241 @@ class CellRunsCompleted(AsyncOnlyScorerMixin, Scorer):
@staticmethod
def _read_runs(team_id: int) -> list[dict[str, Any]]:
return [
- {"node_type": node_type, "status": status, "error": error}
- for node_type, status, error in NotebookNodeRun.objects.for_team(team_id)
+ {"notebook_short_id": notebook_short_id, "node_type": node_type, "status": status, "error": error}
+ for notebook_short_id, node_type, status, error in NotebookNodeRun.objects.for_team(team_id)
+ .filter(notebook__deleted=False)
.order_by("created_at")
- .values_list("node_type", "status", "error")
+ .values_list("notebook__short_id", "node_type", "status", "error")
+ ]
+
+
+@frozen
+class _CohortMatch:
+ """Which planted accounts one notebook named, and which it missed."""
+
+ surfaced: list[str]
+ missing: list[str]
+
+
+class ChurnCohortSurfaced(AsyncOnlyScorerMixin, Scorer):
+ """Fractional: how many planted churn accounts did the notebook name?
+
+ Opt in with ``expected = {"churn_cohort_surfaced": {}}`` on a case seeded by
+ ``seed_churn_signal``. Reads the planted cohort from ``seed["churn_needle"]`` and
+ looks for each account's identifiers — email, name, distinct id, account key — in the
+ prose of the notebook the agent left behind and its final message. The planted accounts
+ are power users who went silent, so a sound churn prediction should list them; the
+ score is the fraction it surfaced, a synthetic ground truth for the prediction itself.
+
+ Only prose counts. A completed cell run writes its rows and stdout back into the cell
+ tag, so an account the SQL merely returned sits in the stored document beside one the
+ analysis picked out. Grading the whole document would hand full recall to a notebook
+ that selected every account and concluded nothing.
+
+ Each notebook is graded on its own and the best one wins. Concatenating every
+ notebook's markdown would let accounts named across separate scratch or retry
+ notebooks combine into a score no single delivered notebook earns.
+
+ Self-skips (``None``) only when the case does not opt in. A case that opts in but
+ arrives without a cohort scores ``0.0``: a timed-out run loses its seed, and skipping
+ it would drop the case from the average while every sibling scorer records a failure,
+ so timeouts would lift this metric.
+ """
+
+ def _name(self) -> str:
+ return "churn_cohort_surfaced"
+
+ async def _run_eval_async(self, output: Any, expected: Any = None, **kwargs: Any) -> Score:
+ if _spec(expected, self._name()) is None:
+ return Score(name=self._name(), score=None, metadata={"reason": "not requested"})
+ needle = ((output or {}).get("seed") or {}).get("churn_needle")
+ accounts = needle.get("accounts") if isinstance(needle, dict) else None
+ if not isinstance(accounts, list) or not accounts:
+ return Score(name=self._name(), score=0.0, metadata={"reason": "Opted in but the seed carries no cohort"})
+ team_id = _seeded_team_id(output)
+ if team_id is None:
+ return Score(name=self._name(), score=0.0, metadata={"reason": "No seed.team_id — case needs a seeder"})
+
+ bodies = await asyncio.to_thread(self._read_markdown_bodies, team_id)
+ final_message = _final_message(output)
+ # Grade the final message alongside each notebook, and when no notebook exists
+ # grade it alone — a conclusion named only in chat still counts for something.
+ candidates = bodies or [""]
+
+ best = max(
+ (self._grade(f"{_notebook_prose(body)}\n{final_message}".lower(), accounts) for body in candidates),
+ key=lambda graded: len(graded.surfaced),
+ )
+ return Score(
+ name=self._name(),
+ score=len(best.surfaced) / len(accounts),
+ metadata={
+ "surfaced": best.surfaced,
+ "missing": best.missing,
+ "total": len(accounts),
+ "notebooks": len(bodies),
+ },
+ )
+
+ @staticmethod
+ def _grade(haystack: str, accounts: list[dict[str, Any]]) -> _CohortMatch:
+ surfaced: list[str] = []
+ missing: list[str] = []
+ for account in accounts:
+ identifiers = [
+ str(account.get(key, "")).lower()
+ for key in ("email", "name", "distinct_id", "account_key")
+ if account.get(key)
+ ]
+ label = account.get("email") or account.get("distinct_id") or str(account.get("index"))
+ if any(identifier and identifier in haystack for identifier in identifiers):
+ surfaced.append(label)
+ else:
+ missing.append(label)
+ return _CohortMatch(surfaced=surfaced, missing=missing)
+
+ @staticmethod
+ def _read_markdown_bodies(team_id: int) -> list[str]:
+ return [
+ body
+ for notebook in Notebook.objects.filter(team_id=team_id, deleted=False)
+ if (body := _markdown_body(notebook.content))
]
+
+
+_ADD_CELL_TOOL = "notebooks-add-cell"
+
+
+def _parser_for(output: dict | None) -> LogParser | None:
+ if not output:
+ return None
+ raw_log = output.get("raw_log")
+ if not raw_log:
+ return None
+ return LogParser.cached(raw_log, initial_prompt=output.get("prompt", "") or "")
+
+
+def _final_message(output: dict | None) -> str:
+ message = (output or {}).get("last_message") or ""
+ return message if isinstance(message, str) else str(message)
+
+
+def _authored_cells(parser: LogParser) -> list[ToolCall]:
+ """Every cell the agent successfully added, in the order it added them.
+
+ Grades what the agent authored, so a rejected call (``is_error``) is left out —
+ the recovery is graded by whether a later, successful call took its place.
+ """
+ calls = [c for c in parser.get_tool_calls(_ADD_CELL_TOOL) if not c.is_error]
+ return sorted(calls, key=lambda c: c.position)
+
+
+def _render_cells(cells: list[ToolCall]) -> str:
+ """Render the authored cells as a readable notebook outline for the judge."""
+ blocks: list[str] = []
+ for index, call in enumerate(cells, start=1):
+ payload = call.input if isinstance(call.input, dict) else {}
+ cell_type = payload.get("cell_type") or "?"
+ title = payload.get("title")
+ header = f"Cell {index} [{cell_type}]" + (f" — {title}" if title else "")
+ body = payload.get("code") or payload.get("markdown") or "(empty)"
+ blocks.append(f"{header}\n{body}")
+ return "\n\n".join(blocks)
+
+
+NOTEBOOK_APPROACH_PROMPT = """
+You are an expert data analyst judging whether an agent built a notebook that follows a sound
+analytical approach for the user's request. You are grading the *approach*, not whether the
+numbers are exactly right — a separate check confirms the cells actually ran.
+
+The agent works in a PostHog notebook. It writes `sql` cells (HogQL against product data) and
+`python` cells (pandas over the dataframes those SQL cells produce), and `markdown` cells for
+prose. Judge the cells it authored, in order, against the expected approach.
+
+Reward a notebook that:
+- pulls the behavioural signals the question needs with SQL, using real events and properties,
+- carries the analysis into Python over those dataframes when the question calls for it,
+- explains its reasoning and lands on a conclusion a reader can act on.
+
+Penalize a notebook that skips a step the expected approach names, hard-codes an answer instead
+of deriving it from the data, or answers a different question than the one asked.
+
+User request:
+<user_request>
+{{output.prompt}}
+</user_request>
+
+Expected approach:
+<expected_approach>
+{{expected.approach}}
+</expected_approach>
+
+Cells the agent authored, in order:
+<authored_cells>
+{{output.authored_cells}}
+</authored_cells>
+
+Final assistant message:
+<final_message>
+{{output.final_message}}
+</final_message>
+""".strip()
+
+
+NOTEBOOK_APPROACH_RUBRIC = """
+How well does the notebook's approach match the expected approach? Choose one:
+- perfect: Follows every step of the expected approach — the right signals in SQL, the analysis carried into Python, a clear conclusion.
+- near_perfect: Follows the expected approach with at most one immaterial gap.
+- slightly_off: Mostly follows it, with a minor step done weakly or skipped.
+- somewhat_misaligned: Some of the right pieces, but misses a load-bearing step (e.g. no Python analysis when the question needs it, or SQL that ignores the behavioural signals).
+- strongly_misaligned: Does not follow the expected approach or answers a different question.
+- useless: No meaningful analysis, or a hard-coded answer not derived from the data.
+""".strip()
+
+
+class NotebookApproachQuality(JudgedScorer):
+ """Graded LLM judge: did the notebook follow the expected analytical approach?
+
+ Opt in per case with ``expected = {"notebook_approach_quality": {"approach": "..."}}``,
+ where ``approach`` is a plain-language rubric of what a good notebook for this prompt
+ does. Reads the authored cells from the transcript, so it grades the same whether or not
+ a cell's run finished; pair it with ``CellRunsCompleted`` to also require execution.
+
+ Self-skips (``None``) when the case does not opt in. Scores ``0.0`` when it opts in but
+ the agent authored no cells — a run that built nothing is a failure, not a skip.
+ """
+
+ def __init__(self, **kwargs: Any) -> None:
+ super().__init__(
+ name="notebook_approach_quality",
+ prompt_template=NOTEBOOK_APPROACH_PROMPT + "\n\n" + NOTEBOOK_APPROACH_RUBRIC,
+ choice_scores=GRADED_ALIGNMENT_CHOICE_SCORES,
+ model=JUDGE_MODEL,
+ max_completion_tokens=1024,
+ **kwargs,
+ )
+
+ def _prepare(self, output: Any, expected: Any) -> dict[str, Any] | Score:
+ spec = _spec(expected, self._name())
+ if spec is None:
+ return Score(name=self._name(), score=None, metadata={"reason": "not requested"})
+ approach = spec.get("approach")
+ if not isinstance(approach, str) or not approach.strip():
+ return Score(name=self._name(), score=None, metadata={"reason": "no approach rubric configured"})
+
+ parser = _parser_for(output)
+ if parser is None:
+ return Score(name=self._name(), score=0.0, metadata={"reason": "No raw log to read cells from"})
+ cells = _authored_cells(parser)
+ if not cells:
+ return Score(name=self._name(), score=0.0, metadata={"reason": "Agent authored no cells"})
+
+ prompt = parser.get_user_prompt() or (output or {}).get("prompt", "")
+ return {
+ "output": {
+ "prompt": prompt,
+ "authored_cells": _render_cells(cells),
+ "final_message": _final_message(output),
+ },
+ "expected": {"approach": approach},
+ }
diff --git a/products/notebooks/evals/seeders.py b/products/notebooks/evals/seeders.py
index b9822feeb8a2..0efa727e80fe 100644
--- a/products/notebooks/evals/seeders.py
+++ b/products/notebooks/evals/seeders.py
@@ -4,13 +4,104 @@ The seeder contract takes no per-case parameters, so each seeded state gets its
function. Every one of them returns ``team_id``: it is the only channel a scorer has
for reaching the case's own team, and the notebook scorers grade the documents and run
rows the agent left there rather than what the transcript claims.
+
+Seeders run synchronously in the case's freshly cloned team, so they can write straight
+to ClickHouse with the same ``TEST=1`` helpers the pytest suites use, and mirror what they
+plant into the persons database the way cloning the team mirrors the demo's own persons.
"""
from __future__ import annotations
+import uuid
+from datetime import datetime, timedelta
from typing import Any
+from django.utils import timezone
+
+from posthog.models import Team
+from posthog.models.event.util import bulk_create_events
+from posthog.models.filters.utils import GroupTypeIndex
+from posthog.models.group.util import raw_create_group_ch
+from posthog.models.person.util import create_person, create_person_distinct_id
+from posthog.persons_db import persons_db_connection
+from posthog.persons_seed import insert_seed_distinct_id, insert_seed_person
+
+from products.notebooks.evals.synthesizer import CHURN_TOKEN, SIGNUP_EVENT, ChurnAccount, build_churn_needle
from products.tasks.backend.facade.agents import CustomPromptSandboxContext
+from products.warehouse_sources.backend.facade.api import soft_delete_tables
+
+# Realistic props for the planted file events, so a churn query that groups or filters on
+# file properties still sees well-formed rows. Fixed values keep the seed deterministic.
+_FILE_EVENT_PROPS: dict[str, dict[str, Any]] = {
+ "uploaded_file": {"file_type": "application/pdf", "file_size_b": 5_242_880, "used_mb": 5_242_880},
+ "downloaded_file": {"file_type": "application/pdf", "file_size_b": 5_242_880, "file_name": "quarterly-report"},
+ "shared_file_link": {"file_type": "application/pdf", "file_size_b": 5_242_880},
+}
+
+# Hedgebox registers its "account" group type at index 0, which is what ``$group_0`` on the
+# planted events points at.
+_ACCOUNT_GROUP_TYPE_INDEX: GroupTypeIndex = 0
+_MB_PER_PLANTED_FILE = 5
+
+
+def _workspace_name(account: ChurnAccount) -> str:
+ return f"{account.name} workspace"
+
+
+def _person_uuid(team_id: int, account: ChurnAccount) -> uuid.UUID:
+ return uuid.uuid5(uuid.NAMESPACE_URL, f"{team_id}:{account.distinct_id}")
+
+
+def _person_properties(account: ChurnAccount) -> dict[str, Any]:
+ return {"email": account.email, "name": account.name}
+
+
+def _seed_persons_db(
+ team_id: int,
+ accounts: tuple[ChurnAccount, ...],
+ *,
+ created_at: datetime,
+ last_seen_at: datetime,
+) -> None:
+ """Mirror the planted persons into the persons database.
+
+ Cloning a team syncs the demo's own persons there, and personhog serves exact person
+ lookups from it, so a person planted only in ClickHouse would be the one account in
+ the team that a lookup by id or distinct id cannot hydrate.
+ """
+ with persons_db_connection(writer=True, autocommit=True) as conn:
+ for account in accounts:
+ person_id = insert_seed_person(
+ conn,
+ team_id=team_id,
+ properties=_person_properties(account),
+ is_identified=True,
+ uuid=_person_uuid(team_id, account),
+ version=0,
+ created_at=created_at,
+ last_seen_at=last_seen_at,
+ )
+ insert_seed_distinct_id(conn, team_id=team_id, person_id=person_id, distinct_id=account.distinct_id)
+
+
+def _group_properties(account: ChurnAccount, uploads: int) -> dict[str, Any]:
+ """The account group as the demo writes it: name, industry, storage, plan, team size."""
+ return {
+ "name": _workspace_name(account),
+ "industry": None,
+ "used_mb": uploads * _MB_PER_PLANTED_FILE,
+ "file_count": uploads,
+ "plan": "personal/free",
+ "team_size": 1,
+ }
+
+
+# Hedgebox also exposes its uploads as a warehouse table, derived once from the master
+# simulation into a CSV every case team shares. The planted cohort only reaches ClickHouse
+# ``events``, so that table would show an upload history without the churners in it: an
+# agent that queried it would build a sound analysis and still miss the needle. Hide it so
+# every source the agent can reach agrees on who uploaded what.
+_STALE_WAREHOUSE_TABLES = ("uploaded_files",)
def seed_case_team(context: CustomPromptSandboxContext) -> dict[str, Any]:
@@ -20,3 +111,111 @@ def seed_case_team(context: CustomPromptSandboxContext) -> dict[str, Any]:
whole fixture.
"""
return {"team_id": context.team_id}
+
+
+def _event_properties(event: str, account: ChurnAccount) -> dict[str, Any]:
+ # The simulation captures the signup before it links the person to an account, so a
+ # real signed_up carries from_invite and no group. Planting a group on it would make
+ # the event less like the ones around it, not more.
+ if event == SIGNUP_EVENT:
+ return {"from_invite": False}
+ props: dict[str, Any] = {"$group_0": account.account_key}
+ props.update(_FILE_EVENT_PROPS.get(event, {}))
+ return props
+
+
+def _hide_stale_warehouse_tables(team_id: int) -> None:
+ soft_delete_tables(team_id, _STALE_WAREHOUSE_TABLES)
+
+
+def seed_churn_signal(context: CustomPromptSandboxContext) -> dict[str, Any]:
+ """Plant a cohort of accounts with an unmistakable activity drop-off.
+
+ Each planted account is a power user across the demo's early window, then goes
+ completely silent — the textbook churn shape. A sound churn analysis should rank
+ them near the top of its at-risk list, which is the synthetic ground truth
+ ``ChurnCohortSurfaced`` grades against.
+ """
+ team = Team.objects.get(id=context.team_id)
+ needle = build_churn_needle()
+ now = timezone.now()
+ # Spread events within their day so ordering and per-day counts stay stable. Every
+ # account repeats the same schedule, so the timestamps are worked out once.
+ planted_at = [
+ now - timedelta(days=planted.days_before_now, minutes=slot) for slot, planted in enumerate(needle.schedule)
+ ]
+ newest_planted_at = max(planted_at)
+ # The signup opens the account, so the group starts there.
+ account_created_at = min(planted_at)
+ # Persons exist before their first event, so the account looks real to the analysis.
+ person_created_at = now - timedelta(days=needle.active_window_days[0] + 5)
+ uploads = sum(1 for planted in needle.schedule if planted.event == "uploaded_file")
+
+ _seed_persons_db(team.id, needle.accounts, created_at=person_created_at, last_seen_at=newest_planted_at)
+
+ events: list[dict[str, Any]] = []
+ for account in needle.accounts:
+ person_uuid = _person_uuid(team.id, account)
+ person_properties = _person_properties(account)
+ create_person(
+ team_id=team.id,
+ version=0,
+ uuid=str(person_uuid),
+ properties=person_properties,
+ is_identified=True,
+ created_at=person_created_at,
+ # HogQL reads persons.last_seen_at as the person's most recent event, and the
+ # writer defaults it to the time of the write. Left alone, the planted cohort
+ # would read as the most recently active people in the team — the opposite of
+ # the churn shape these events describe.
+ last_seen_at=newest_planted_at,
+ )
+ create_person_distinct_id(team_id=team.id, distinct_id=account.distinct_id, person_id=str(person_uuid))
+ # HogQL reads account.key and account.properties through the groups table, so an
+ # analysis that starts from the account list only sees accounts with a group row.
+ # ClickHouse only, like the demo generator, so a planted account reads the same as
+ # a simulated one.
+ raw_create_group_ch(
+ team_id=team.id,
+ group_type_index=_ACCOUNT_GROUP_TYPE_INDEX,
+ group_key=account.account_key,
+ properties=_group_properties(account, uploads),
+ created_at=account_created_at,
+ )
+ for planted, timestamp in zip(needle.schedule, planted_at):
+ properties = _event_properties(planted.event, account)
+ group_columns = (
+ {"group0_properties": {"name": _workspace_name(account)}} if "$group_0" in properties else {}
+ )
+ events.append(
+ {
+ "event": planted.event,
+ "team": team,
+ "distinct_id": account.distinct_id,
+ "timestamp": timestamp,
+ "properties": properties,
+ "person_id": person_uuid,
+ "person_properties": person_properties,
+ **group_columns,
+ }
+ )
+ bulk_create_events(events)
+ _hide_stale_warehouse_tables(team.id)
+
+ return {
+ "team_id": team.id,
+ "churn_needle": {
+ "token": CHURN_TOKEN,
+ "silent_after_days": needle.silent_after_days,
+ "accounts": [
+ {
+ "index": account.index,
+ "email": account.email,
+ "name": account.name,
+ "distinct_id": account.distinct_id,
+ "account_key": account.account_key,
+ }
+ for account in needle.accounts
+ ],
+ },
+ }
diff --git a/products/notebooks/evals/synthesizer.py b/products/notebooks/evals/synthesizer.py
new file mode 100644
index 000000000000..df3e4006558b
--- /dev/null
+++ b/products/notebooks/evals/synthesizer.py
@@ -0,0 +1,99 @@
+"""Deterministic churn-needle definition for the notebook analysis evals.
+
+Pure and Django-free, so it stays unit-testable outside the app: it only names the
+accounts to plant and the shape of their activity. The seeder turns this into
+ClickHouse persons and events, and the scorer checks the notebook surfaces them.
+
+Every identifier carries ``CHURN_TOKEN``, so an analysis that lists at-risk accounts
+by email, by name, by distinct id, or by account key all surface the same searchable
+marker — which is what lets the scorer grade the prediction without knowing how the
+agent chose to group.
+"""
+
+from __future__ import annotations
+
+from posthog.dataclasses import frozen
+
+CHURN_TOKEN = "hollowbrook"
+
+# First names keep the planted accounts distinguishable from one another; the shared
+# CHURN_TOKEN in the surname, domain, and account key is what the scorer matches on.
+_FIRST_NAMES = ("ada", "bianca", "caleb", "dara", "elias", "farah", "gideon", "hana")
+
+# One "active session" the planted power users repeat until they go silent. The mix spans
+# the signals the cases ask about — logins, uploads, downloads, and sharing — so the same
+# cohort reads as churn whichever behaviour an analysis keys on.
+_SESSION_EVENTS = ("logged_in", "uploaded_file", "uploaded_file", "downloaded_file", "shared_file_link")
+
+SIGNUP_EVENT = "signed_up"
+
+
+@frozen
+class ChurnAccount:
+ index: int
+ distinct_id: str
+ account_key: str
+ email: str
+ name: str
+
+
+@frozen
+class PlantedEvent:
+ event: str
+ days_before_now: int
+
+
+@frozen
+class ChurnNeedle:
+ accounts: tuple[ChurnAccount, ...]
+ schedule: tuple[PlantedEvent, ...]
+ silent_after_days: int
+ active_window_days: tuple[int, int]
+
+
+def build_churn_needle(
+ count: int = 6,
+ *,
+ oldest_active_day: int = 120,
+ newest_active_day: int = 70,
+ session_stride_days: int = 4,
+) -> ChurnNeedle:
+ """Build the planted cohort: ``count`` accounts, each signing up
+ ``oldest_active_day`` days ago, very active until ``newest_active_day``, then silent.
+
+ The gap between ``newest_active_day`` and today is the churn signal — power users
+ who stopped — so keep it wide relative to the demo's ~120-day window.
+ """
+ if not 1 <= count <= len(_FIRST_NAMES):
+ raise ValueError(f"count must be between 1 and {len(_FIRST_NAMES)}")
+ if oldest_active_day <= newest_active_day:
+ raise ValueError("oldest_active_day must be greater than newest_active_day")
+
+ accounts = tuple(
+ ChurnAccount(
+ index=i,
+ distinct_id=f"{CHURN_TOKEN}-user-{i}",
+ account_key=f"{CHURN_TOKEN}-{i}",
+ email=f"{name}.{CHURN_TOKEN}@example.com",
+ name=f"{name.capitalize()} {CHURN_TOKEN.capitalize()}",
+ )
+ for i, name in enumerate(_FIRST_NAMES[:count])
+ )
+ # The signup comes first: every simulated account emits ``signed_up`` before anything
+ # else, and the simulation makes it a precondition for logging in, uploading, and
+ # sharing. A cohort without one is a shape the fixture never holds, so an analysis
+ # that builds its customer base from signups would drop every planted account.
+ schedule = (
+ PlantedEvent(event=SIGNUP_EVENT, days_before_now=oldest_active_day),
+ *(
+ PlantedEvent(event=event, days_before_now=day)
+ for day in range(oldest_active_day - 1, newest_active_day - 1, -session_stride_days)
+ for event in _SESSION_EVENTS
+ ),
+ )
+ return ChurnNeedle(
+ accounts=accounts,
+ schedule=schedule,
+ silent_after_days=newest_active_day,
+ active_window_days=(oldest_active_day, newest_active_day),
+ )
diff --git a/products/notebooks/evals/test/__init__.py b/products/notebooks/evals/test/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/notebooks/evals/test/test_scorers.py b/products/notebooks/evals/test/test_scorers.py
new file mode 100644
index 000000000000..5a2ab1eb802b
--- /dev/null
+++ b/products/notebooks/evals/test/test_scorers.py
@@ -0,0 +1,187 @@
+"""Unit tests for the notebook eval scorers.
+
+Builds notebook documents in the shape the collab save stores — cell tags with their run
+result written back — plus a synthetic churn needle, then asserts the score.
+"""
+
+from __future__ import annotations
+
+import json
+from typing import Any
+
+import pytest
+from unittest.mock import patch
+
+from posthog.models import Team
+from posthog.models.scoping import team_scope
+
+from products.notebooks.backend.models import Notebook, NotebookNodeRun
+from products.notebooks.evals.scorers import CellRunsCompleted, ChurnCohortSurfaced
+from products.notebooks.evals.seeders import seed_churn_signal
+from products.notebooks.evals.synthesizer import CHURN_TOKEN, SIGNUP_EVENT, build_churn_needle
+from products.tasks.backend.facade.agents import CustomPromptSandboxContext
+
+_ACCOUNTS: list[dict[str, Any]] = [
+ {
+ "index": account.index,
+ "email": account.email,
+ "name": account.name,
+ "distinct_id": account.distinct_id,
+ "account_key": account.account_key,
+ }
+ for account in build_churn_needle(count=3).accounts
+]
+
+
+def _sql_cell_listing(accounts: list[dict[str, Any]]) -> str:
+ result = {
+ "columns": ["email", "events"],
+ "types": ["String", "UInt64"],
+ "row_count": len(accounts),
+ "first_page": [[account["email"], 120] for account in accounts],
+ "has_more": False,
+ "stdout": "",
+ "stderr": "",
+ "media": [],
+ }
+ code = json.dumps("SELECT properties.$email AS email, count() FROM events GROUP BY email")
+ return (
+ f'<SQLV2 nodeId="cell-1" title="Events per account" code={code} returnVariable="sql_df" '
+ f'runId="run-1" result={{{json.dumps(result)}}} />'
+ )
+
+
+ "bodies,final_message,expected_score",
+ [
+ pytest.param([_sql_cell_listing(_ACCOUNTS)], "The analysis is in the notebook.", 0.0, id="run_rows_only"),
+ pytest.param(
+ [
+ f"{_sql_cell_listing(_ACCOUNTS)}\n\n\n## Most at risk\n\n- {_ACCOUNTS[0]['email']}\n- {_ACCOUNTS[1]['name']}"
+ ],
+ "",
+ 2 / 3,
+ id="prose_names_two",
+ ),
+ pytest.param([], f"Most at risk: {_ACCOUNTS[2]['distinct_id']}", 1 / 3, id="final_message_names_one"),
+ ],
+)
+async def test_churn_cohort_surfaced_counts_prose_only(
+ monkeypatch: pytest.MonkeyPatch, bodies: list[str], final_message: str, expected_score: float
+) -> None:
+ monkeypatch.setattr(ChurnCohortSurfaced, "_read_markdown_bodies", staticmethod(lambda team_id: bodies))
+ output = {
+ "seed": {"team_id": 1, "churn_needle": {"token": CHURN_TOKEN, "accounts": _ACCOUNTS}},
+ "last_message": final_message,
+ }
+
+ score = await ChurnCohortSurfaced().eval_async(output, {"churn_cohort_surfaced": {}})
+
+ assert score.score == pytest.approx(expected_score)
+
+
+def test_read_runs_skips_soft_deleted_notebooks(team: Team) -> None:
+ delivered = Notebook.objects.create(team=team, short_id="delivered")
+ scratch = Notebook.objects.create(team=team, short_id="scratch", deleted=True)
+ with team_scope(team.id):
+ for notebook, node_type in (
+ (scratch, NotebookNodeRun.NodeType.HOGQL),
+ (scratch, NotebookNodeRun.NodeType.PYTHON),
+ (delivered, NotebookNodeRun.NodeType.HOGQL),
+ ):
+ NotebookNodeRun.objects.create(
+ team=team,
+ notebook=notebook,
+ node_id=f"{notebook.short_id}-{node_type}",
+ node_type=node_type,
+ status=NotebookNodeRun.Status.DONE,
+ )
+
+ runs = CellRunsCompleted._read_runs(team.id)
+
+ assert [(run["notebook_short_id"], run["node_type"]) for run in runs] == [("delivered", "hogql")]
+
+
+def test_churn_needle_plants_one_signup_before_every_session() -> None:
+ signup, *sessions = build_churn_needle().schedule
+
+ assert signup.event == SIGNUP_EVENT
+ assert all(planted.days_before_now < signup.days_before_now for planted in sessions)
+ assert all(planted.event != SIGNUP_EVENT for planted in sessions)
+
+
+def test_planted_persons_are_last_seen_at_their_newest_event(team: Team) -> None:
+ with (
+ patch("products.notebooks.evals.seeders.create_person") as create_person,
+ patch("products.notebooks.evals.seeders.create_person_distinct_id"),
+ patch("products.notebooks.evals.seeders.bulk_create_events") as bulk_create_events,
+ patch("products.notebooks.evals.seeders.raw_create_group_ch"),
+ patch("products.notebooks.evals.seeders._seed_persons_db"),
+ ):
+ seed_churn_signal(CustomPromptSandboxContext(team_id=team.id, user_id=1))
+
+ newest_event = max(event["timestamp"] for event in bulk_create_events.call_args.args[0])
+ assert create_person.call_args_list
+ assert all(call.kwargs["last_seen_at"] == newest_event for call in create_person.call_args_list)
+
+
+ "expected,expected_score",
+ [
+ pytest.param({"churn_cohort_surfaced": {}}, 0.0, id="opted_in_without_a_seed"),
+ pytest.param({}, None, id="not_requested"),
+ ],
+)
+async def test_churn_cohort_surfaced_on_a_timed_out_case(
+ expected: dict[str, Any], expected_score: float | None
+) -> None:
+ timed_out = {"exit_code": 1, "stderr": "case timeout after 900s"}
+
+ score = await ChurnCohortSurfaced().eval_async(timed_out, expected)
+
+ assert score.score == expected_score
+
+
+def test_every_planted_account_key_gets_a_group_row(team: Team) -> None:
+ with (
+ patch("products.notebooks.evals.seeders.create_person"),
+ patch("products.notebooks.evals.seeders.create_person_distinct_id"),
+ patch("products.notebooks.evals.seeders.bulk_create_events") as bulk_create_events,
+ patch("products.notebooks.evals.seeders.raw_create_group_ch") as raw_create_group_ch,
+ patch("products.notebooks.evals.seeders._seed_persons_db"),
+ ):
+ seed_churn_signal(CustomPromptSandboxContext(team_id=team.id, user_id=1))
+
+ event_keys = {
+ event["properties"]["$group_0"]
+ for event in bulk_create_events.call_args.args[0]
+ if "$group_0" in event["properties"]
+ }
+ planted = {call.kwargs["group_key"]: call.kwargs["properties"] for call in raw_create_group_ch.call_args_list}
+
+ assert event_keys and event_keys == set(planted)
+ assert all(CHURN_TOKEN in properties["name"].lower() for properties in planted.values())
+
+
+def test_planted_persons_reach_the_persons_database(team: Team) -> None:
+ with (
+ patch("products.notebooks.evals.seeders.create_person"),
+ patch("products.notebooks.evals.seeders.create_person_distinct_id"),
+ patch("products.notebooks.evals.seeders.bulk_create_events") as bulk_create_events,
+ patch("products.notebooks.evals.seeders.raw_create_group_ch"),
+ patch("products.notebooks.evals.seeders.persons_db_connection"),
+ patch("products.notebooks.evals.seeders.insert_seed_person", return_value=1) as insert_seed_person,
+ patch("products.notebooks.evals.seeders.insert_seed_distinct_id") as insert_seed_distinct_id,
+ ):
+ seed_churn_signal(CustomPromptSandboxContext(team_id=team.id, user_id=1))
+
+ event_distinct_ids = {event["distinct_id"] for event in bulk_create_events.call_args.args[0]}
+ seeded_distinct_ids = {call.kwargs["distinct_id"] for call in insert_seed_distinct_id.call_args_list}
+ newest_event = max(event["timestamp"] for event in bulk_create_events.call_args.args[0])
+
+ assert event_distinct_ids and seeded_distinct_ids == event_distinct_ids
+ assert all(call.kwargs["last_seen_at"] == newest_event for call in insert_seed_person.call_args_list)
diff --git a/products/notebooks/package.json b/products/notebooks/package.json
index 8d305c904eec..840a112ebf5c 100644
--- a/products/notebooks/package.json
+++ b/products/notebooks/package.json
@@ -1,7 +1,7 @@
{
"name": "@posthog/products-notebooks",
"scripts": {
- "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/ -v --tb=short"
+ "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/ evals/test/ -v --tb=short"
},
"dependencies": {
"kea": "catalog:",
diff --git a/products/warehouse_sources/backend/facade/api.py b/products/warehouse_sources/backend/facade/api.py
index 028fc6ab7fef..d2c7802a57d8 100644
--- a/products/warehouse_sources/backend/facade/api.py
+++ b/products/warehouse_sources/backend/facade/api.py
@@ -13,7 +13,9 @@ don't drag heavy imports onto the ``django.setup()`` path.
Write paths (create/update of sources, schemas, tables, jobs) remain inside
``products/data_warehouse`` for now — a legacy-leak swept in Phase 2 — so this
-first facade serves the read consumers and the framework-free helpers.
+first facade serves the read consumers and the framework-free helpers. The one
+exception is ``soft_delete_tables``: consumers may not iterate the model to call
+``soft_delete()`` themselves, so the facade does it for them.
"""
from collections.abc import Collection
@@ -378,6 +380,21 @@ def list_tables_for_source(source_id: UUID, team_id: int) -> list[contracts.Data
return [_to_table(t) for t in qs]
+def soft_delete_tables(team_id: int, names: Collection[str]) -> int:
+ """Soft-delete the team's tables with these names and return how many were deleted.
+
+ Goes through ``DataWarehouseTable.soft_delete`` so the joins that reference a table
+ are retired with it, instead of leaving a dangling join behind a hidden table.
+ Already-deleted tables are skipped, so calling this twice is safe.
+ """
+ tables = _DataWarehouseTable.objects.filter(team_id=team_id, name__in=names).exclude(deleted=True)
+ deleted = 0
+ for table in tables:
+ table.soft_delete()
+ deleted += 1
+ return deleted
+
+
def list_jobs_for_source(source_id: UUID, team_id: int) -> list[contracts.ExternalDataJob]:
qs = (
_ExternalDataJob.objects.select_related("schema", "pipeline")