: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
chore(ai): replace legacy evals with focused sandbox cases (#112346)
Daniel Parkere0358bca8dae
diff --git a/.agents/skills/writing-evals/SKILL.md b/.agents/skills/writing-evals/SKILL.mdindex 460e046c815e..b1617f1f415b 100644--- a/.agents/skills/writing-evals/SKILL.md+++ b/.agents/skills/writing-evals/SKILL.md@@ -4,7 +4,7 @@ description: >Teaches how to write and run evals on the `products/posthog_ai/eval_harness/` harness — sandboxed agent suites that execute the real coding agent in a Docker or Modal sandbox against a seeded Hedgebox project, and one-shot suites that score a single in-process model invocation per case.Use when adding or changing eval suites, cases, scorers, seeders, or synthesizers under `products/posthog_ai/evals/` or `products/*/evals/`, when touching the harness under `products/posthog_ai/eval_harness/`, or when running or debugging those evals (`hogli evals`).Covers suite kinds and discovery, case anatomy, the seeder/synthesizer split, the one-branch scorer patterns, and how to read results.- Not for `ee/hogai/eval/ci/` pytest evals, and not for the LLM Analytics product's evaluation features.+ Not for the LLM Analytics product's evaluation features.---# Writing and running evalsdiff --git a/.coderabbit.yaml b/.coderabbit.yamlindex d635e09a7f8d..916bf59888b2 100644--- a/.coderabbit.yaml+++ b/.coderabbit.yaml@@ -207,7 +207,7 @@ knowledge_base:# Eval suites, cases, scorers, and harness code.- files: '.agents/skills/writing-evals/SKILL.md'- applyTo: 'products/posthog_ai/evals/**,products/**/evals/**,ee/hogai/eval/**'+ applyTo: 'products/posthog_ai/evals/**,products/**/evals/**'# Skill authoring.- files: '.agents/skills/writing-skills/SKILL.md'diff --git a/.dagster_home/workspace.yaml b/.dagster_home/workspace.yamlindex acc64affe3f8..e7cad14797a9 100644--- a/.dagster_home/workspace.yaml+++ b/.dagster_home/workspace.yaml@@ -17,5 +17,4 @@ load_from:- python_module: posthog.dags.locations.shared- python_module: posthog.dags.locations.signals- python_module: posthog.dags.locations.ingestion- - python_module: posthog.dags.locations.posthog_ai- python_module: posthog.dags.locations.web_analyticsdiff --git a/.github/scripts/check-fixture-provenance.sh b/.github/scripts/check-fixture-provenance.shindex 793ba6b06508..7be361a8c088 100755--- a/.github/scripts/check-fixture-provenance.sh+++ b/.github/scripts/check-fixture-provenance.sh@@ -63,4 +63,4 @@ printf 'prose, typos, error IDs, and order of events are still the customer'"'"'printf 'Write sample data by listing the properties a case has to exercise, then writing the\n' >&2printf 'case from that list with the real material closed. Do not claim "written fresh" in a\n' >&2printf 'commit message unless that is what you did.\n\n' >&2-printf 'See ee/hogai/eval/AGENTS.md and AGENTS.md "Public open source repo guidance".\033[0m\n\n' >&2+printf 'See products/posthog_ai/evals/AGENTS.md and AGENTS.md "Public open source repo guidance".\033[0m\n\n' >&2diff --git a/.github/scripts/post-eval-section.mjs b/.github/scripts/post-eval-section.mjsdeleted file mode 100644index 11a8df767b68..000000000000--- a/.github/scripts/post-eval-section.mjs+++ /dev/null@@ -1,132 +0,0 @@-#!/usr/bin/env node-import fs from 'node:fs'--import { postSection } from '../../frontend/bin/ci-report/update-ci-report.mjs'--const DIFF_THRESHOLD = 0.02--if (!fs.existsSync('eval_results.jsonl')) {- console.info('No eval_results.jsonl found — nothing to post.')- process.exit(0)-}--const evalResults = fs- .readFileSync('eval_results.jsonl', 'utf8')- .trim()- .split('\n')- .filter((line) => line.trim().length > 0)- .map((line) => JSON.parse(line))--if (evalResults.length === 0) {- console.info('No eval results found — nothing to post.')- process.exit(0)-}--const experimentsWithMaxDiff = evalResults.map((result) => {- const scores = result.scores || {}- const diffs = Object.values(scores)- .map((v) => v.diff)- .filter((d) => typeof d === 'number')- const minDiff = diffs.length > 0 ? Math.min(...diffs) : 0- const maxDiff = diffs.length > 0 ? Math.max(...diffs) : 0- const category = minDiff < -DIFF_THRESHOLD ? 'regression' : maxDiff > DIFF_THRESHOLD ? 'improvement' : 'neutral'-- return {- result,- category,- maxDiffInCategoryAbs:- category === 'regression'- ? -minDiff- : category === 'improvement'- ? maxDiff- : Math.max(Math.abs(minDiff), Math.abs(maxDiff)),- }-})--experimentsWithMaxDiff.sort((a, b) => {- if (a.category === b.category) {- return b.maxDiffInCategoryAbs - a.maxDiffInCategoryAbs- }- const order = { regression: 0, improvement: 1, neutral: 2 }- return order[a.category] - order[b.category]-})--const experimentSummaries = experimentsWithMaxDiff.map(({ result }) => {- const scoresList = Object.entries(result.scores || {})- .map(([key, value]) => {- const score = typeof value.score === 'number' ? `${(value.score * 100).toFixed(2)}%` : value.score- let baselineComparison = null- const diffHighlight = Math.abs(value.diff) > DIFF_THRESHOLD ? '**' : ''- let diffEmoji = '🆕'- if (result.comparison_experiment_name?.startsWith('master-')) {- baselineComparison = `${diffHighlight}${value.diff > 0 ? '+' : value.diff < 0 ? '' : '±'}${(- value.diff * 100- ).toFixed(2)}%${diffHighlight} (improvements: ${value.improvements}, regressions: ${value.regressions})`- diffEmoji = value.diff > DIFF_THRESHOLD ? '🟢' : value.diff < -DIFF_THRESHOLD ? '🔴' : '🔵'- }- return `${diffEmoji} **${key}**: **${score}**${baselineComparison ? `, ${baselineComparison}` : ''}`- })- .join('\n')-- const metrics = result.metrics || {}- const duration = metrics.duration ? `⏱️ ${metrics.duration.metric.toFixed(2)} s` : null- const totalTokens = metrics.total_tokens ? `🔢 ${Math.floor(metrics.total_tokens.metric)} tokens` : null- const cost = metrics.estimated_cost ? `💵 $${metrics.estimated_cost.metric.toFixed(4)} in tokens` : null- const metricsText = [duration, totalTokens, cost].filter(Boolean).join(', ')- const baselineLink = `[${result.comparison_experiment_name}](${result.project_url}/experiments/${result.comparison_experiment_name})`-- const experimentName = result.project_name.replace(/^max-ai-/, '')-- return [- `### [${experimentName}](${result.experiment_url})`,- scoresList,- `Baseline: ${baselineLink} • Avg. case performance: ${metricsText}`,- ].join('\n\n')-})--const regressions = []-const improvements = []-const neutral = []-experimentsWithMaxDiff.forEach(({ category }, idx) => {- if (category === 'regression') {- regressions.push(experimentSummaries[idx])- } else if (category === 'improvement') {- improvements.push(experimentSummaries[idx])- } else {- neutral.push(experimentSummaries[idx])- }-})--const totalExperiments = evalResults.length-const totalMetrics = evalResults.reduce((acc, result) => acc + Object.keys(result.scores || {}).length, 0)--const bodyParts = [- `Evaluated **${totalExperiments}** experiments, comprising **${totalMetrics}** metrics. Showing experiments with largest regressions first.`,-]--bodyParts.push(...regressions)-bodyParts.push(...improvements)-if (neutral.length > 0) {- bodyParts.push(- `<details><summary>${neutral.length} ${neutral.length === 1 ? 'experiment' : 'experiments'} with no significant changes</summary>\n\n${neutral.join('\n\n')}\n\n</details>`- )-}--const body = bodyParts.join('\n\n')--const status = regressions.length > 0 ? 'warn' : 'ok'-const parts = []-if (regressions.length > 0) {- parts.push(`${regressions.length} regression${regressions.length === 1 ? '' : 's'}`)-}-if (improvements.length > 0) {- parts.push(`${improvements.length} improvement${improvements.length === 1 ? '' : 's'}`)-}-const summary = `${totalExperiments} experiment${totalExperiments === 1 ? '' : 's'}${parts.length ? `: ${parts.join(', ')}` : ''}`--await postSection({- id: 'ai-evals',- status,- summary,- body,-})diff --git a/.github/scripts/trunk-impacted-targets.js b/.github/scripts/trunk-impacted-targets.jsindex d1a658c77001..c2c3eacbb32f 100644--- a/.github/scripts/trunk-impacted-targets.js+++ b/.github/scripts/trunk-impacted-targets.js@@ -364,12 +364,11 @@ const TRIPWIRE_RULES = [['.github/workflows/update-bot-ips.yml', REPO_AUTOMATION],['.github/workflows/weekly-flaky-report.yml', REPO_AUTOMATION],['.github/workflows/weekly-slow-tests-report.yml', REPO_AUTOMATION],- // More single-suite workflows, held to the trees their suites read: the AI- // evals, replay-vision evals, and ClickHouse HCL checks are Python; the+ // More single-suite workflows, held to the trees their suites read:+ // replay-vision evals and ClickHouse HCL checks are Python; the// hogql parser builds wheels (python), an npm package (both families), and// a crate (rust); deltalite spans its crates and the wheel's python// consumers.- ['.github/workflows/ci-ai.yml', PYTHON],['.github/workflows/ci-replay-vision-evals.yml', PYTHON],['.github/workflows/ci-clickhouse-hcl-schema.yml', PYTHON],['.github/workflows/build-hogql-parser.yml', PYTHON],@@ -444,7 +443,6 @@ const TRIPWIRE_RULES = [['.github/scripts/post-ch-migration-section.mjs', PYTHON],['.github/scripts/post-django-migration-section.mjs', PYTHON],['.github/scripts/post-coverage-section.mjs', PYTHON],- ['.github/scripts/post-eval-section.mjs', PYTHON],// CI-report sections and helpers owned by one suite each.['.github/scripts/post-playwright-section.mjs', FULLSTACK],['.github/scripts/verify-playwright-new-tests-and-snapshots.sh', FULLSTACK],diff --git a/.github/workflows/ci-ai.yml b/.github/workflows/ci-ai.ymldeleted file mode 100644index 1d5a6921b0ea..000000000000--- a/.github/workflows/ci-ai.yml+++ /dev/null@@ -1,206 +0,0 @@-name: AI-on:- pull_request:- types: [opened, synchronize, reopened, labeled, unlabeled]--concurrency:- group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}- cancel-in-progress: true # We only want one AI CI run per PR concurrently--jobs:- eval:- timeout-minutes: 45- name: AI evals / ${{ matrix.group }}- runs-on: ubuntu-24.04- env:- DOCKERHUB_USERNAME: ${{ vars.DOCKERHUB_USER }}- DOCKERHUB_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }}- # Skipping on forks as Braintrust credentials are not available there- if: |- github.repository == 'PostHog/posthog' && contains(github.event.pull_request.labels.*.name, 'evals-ready')-- strategy:- fail-fast: false- matrix:- include:- - group: insights- ignore_paths: ''- test_paths: >-- ee/hogai/eval/ci/eval_funnel.py- ee/hogai/eval/ci/eval_trends.py- ee/hogai/eval/ci/eval_retention.py- ee/hogai/eval/ci/eval_sql.py- ee/hogai/eval/ci/eval_survey_analysis.py- - group: features- ignore_paths: ''- test_paths: >-- ee/hogai/eval/ci/eval_surveys.py- ee/hogai/eval/ci/eval_memory.py- ee/hogai/eval/ci/eval_memory_onboarding.py- ee/hogai/eval/ci/eval_ticket_summary.py- ee/hogai/eval/ci/eval_insight_search.py- ee/hogai/eval/ci/eval_ui_context.py- - group: root-and-tools- test_paths: ee/hogai/eval/ci- ignore_paths: >-- --ignore=ee/hogai/eval/ci/eval_funnel.py- --ignore=ee/hogai/eval/ci/eval_trends.py- --ignore=ee/hogai/eval/ci/eval_retention.py- --ignore=ee/hogai/eval/ci/eval_sql.py- --ignore=ee/hogai/eval/ci/eval_survey_analysis.py- --ignore=ee/hogai/eval/ci/eval_surveys.py- --ignore=ee/hogai/eval/ci/eval_memory.py- --ignore=ee/hogai/eval/ci/eval_memory_onboarding.py- --ignore=ee/hogai/eval/ci/eval_ticket_summary.py- --ignore=ee/hogai/eval/ci/eval_insight_search.py- --ignore=ee/hogai/eval/ci/eval_ui_context.py-- permissions:- contents: read-- steps:- - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2- with:- # Check out the actual branch instead of merge commit with master,- # because we want the Braintrust experiment to have accurate git metadata (on master it's empty)- ref: ${{ github.event.pull_request.head.ref }}- fetch-depth: 0- filter: blob:none- clean: false- - name: Clean up data directories with container permissions- run: |- # Use docker to clean up files created by containers- [ -d "data" ] && docker run --rm -v "$(pwd)/data:/data" alpine sh -c "rm -rf /data/seaweedfs /data/minio" || true- continue-on-error: true-- - name: Log in to Docker Hub- continue-on-error: true- if: ${{ env.DOCKERHUB_USERNAME != '' && env.DOCKERHUB_TOKEN != '' }}- uses: docker/login-action@4907a6ddec9925e35a0a9e82d7399ccc52663121 # v4.1.0- with:- username: ${{ vars.DOCKERHUB_USER }}- password: ${{ secrets.DOCKERHUB_TOKEN }}-- - name: Stop/Start stack with Docker Compose- env:- COMPOSE_FILE: docker-compose.dev.yml:docker-compose.profiles.yml- run: |- bin/ci-wait-for-docker launch --down-- - name: Wait for Docker services- env:- COMPOSE_FILE: docker-compose.dev.yml:docker-compose.profiles.yml- run: bin/ci-wait-for-docker wait-- - name: Set up Python- uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0- with:- python-version-file: 'pyproject.toml'-- # Direct install: Evaluations run the explicit PR head, which may predate the local action.- - name: Install uv- uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0- with:- version: '0.12.13'- enable-cache: true- cache-dependency-glob: uv.lock- save-cache: ${{ github.ref == 'refs/heads/master' }}-- - name: Install python dependencies- shell: bash- run: UV_PROJECT_ENVIRONMENT=$pythonLocation uv sync --frozen --dev-- - name: Install Rust- uses: dtolnay/rust-toolchain@3c5f7ea28cd621ae0bf5283f0e981fb97b8a7af9- with:- toolchain: 1.91.1- components: cargo-- - name: Install sqlx-cli- uses: ./.github/actions/setup-sqlx-cli-- - name: Add service hostnames to /etc/hosts- run: sudo echo "127.0.0.1 db redis7 kafka clickhouse clickhouse-coordinator objectstorage seaweedfs temporal" | sudo tee -a /etc/hosts-- - name: Run LLM evals- run: pytest ${{ matrix.test_paths }} ${{ matrix.ignore_paths }} -vv --junitxml=junit.xml- env:- EVAL_MODE: ci- EXPORT_EVAL_RESULTS: true- BRAINTRUST_API_KEY: ${{ secrets.BRAINTRUST_API_KEY }}- OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}- ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}- GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}- INKEEP_API_KEY: ${{ secrets.INKEEP_API_KEY }}- AZURE_INFERENCE_CREDENTIAL: ${{ secrets.AZURE_INFERENCE_CREDENTIAL }}- AZURE_INFERENCE_ENDPOINT: ${{ secrets.AZURE_INFERENCE_ENDPOINT }}-- - name: Upload eval results- uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0- if: always()- with:- name: eval-results-${{ matrix.group }}- path: |- eval_results.jsonl- junit.xml-- eval-summary:- timeout-minutes: 5- name: AI evals / summary- runs-on: ubuntu-24.04- needs: eval- # A status function is required to summarize even when some eval groups errored.- # !cancelled() rather than always() so a superseded run does not post an eval- # summary comment for a commit that is no longer HEAD.- if: ${{ !cancelled() && needs.eval.result != 'skipped' }}-- permissions:- contents: read- issues: write- pull-requests: write-- steps:- - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2- with:- sparse-checkout: |- .github/scripts- frontend/bin/ci-report-- - name: Download all eval results- uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0- with:- pattern: eval-results-*- path: eval-artifacts-- - name: Merge eval results- run: |- # Merge all eval_results.jsonl files into one- cat eval-artifacts/*/eval_results.jsonl > eval_results.jsonl 2>/dev/null || true- if [ ! -s eval_results.jsonl ]; then- echo "No eval results found"- else- echo "Merged eval results:"- wc -l eval_results.jsonl- fi-- - name: Post eval summary to CI report comment- # always() because we want to post even if some eval groups errored- # Skipped on trunk-merge/** branches: merge-queue draft PRs are ephemeral and- # unread, and each section write spends shared GITHUB_TOKEN budget.- if: always() && github.event_name == 'pull_request' && !startsWith(github.head_ref, 'trunk-merge/')- env:- GITHUB_TOKEN: ${{ github.token }}- run: |- if [ -f .github/scripts/post-eval-section.mjs ]; then- node .github/scripts/post-eval-section.mjs- node frontend/bin/ci-report/delete-legacy-comments.mjs- else- echo "Skipping eval section — script not present on this checkout"- fi-- - name: Upload merged test results- uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0- if: always()- with:- name: junit-results-ai-evals- path: eval-artifacts/*/junit.xmldiff --git a/.github/workflows/ci-duplication.yml b/.github/workflows/ci-duplication.ymlindex 26de48f4bdde..81e4413fcde6 100644--- a/.github/workflows/ci-duplication.yml+++ b/.github/workflows/ci-duplication.yml@@ -18,7 +18,7 @@ concurrency:permissions:contents: read- # The poster steps write sections of the shared CI report comment (mirrors ci-frontend.yml / ci-ai.yml).+ # The poster steps write sections of the shared CI report comment (mirrors ci-frontend.yml).pull-requests: writejobs:diff --git a/.semgrep/rules/devex/no-init-reexports.yaml b/.semgrep/rules/devex/no-init-reexports.yamlindex 5b7b13fca1a4..62183375005b 100644--- a/.semgrep/rules/devex/no-init-reexports.yaml+++ b/.semgrep/rules/devex/no-init-reexports.yaml@@ -53,7 +53,6 @@ rules:- 'ee/hogai/context/survey/__init__.py'- 'ee/hogai/core/agent_modes/__init__.py'- 'ee/hogai/core/loop_graph/__init__.py'- - 'ee/hogai/eval/scorers/__init__.py'- 'ee/hogai/tools/create_notebook/__init__.py'- 'ee/hogai/tools/read_data/__init__.py'- 'ee/hogai/tools/read_taxonomy/__init__.py'diff --git a/AGENTS.md b/AGENTS.mdindex 16f2adbdcfd9..b9bcd39d482b 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -315,7 +315,7 @@ ALWAYS invoke the matching skill **first** — do not skip it, and do not attemp- `/writing-skills` — creating or updating skills in `.agents/skills/`- `/editing-agents-md` — adding, editing or removing a rule in any `AGENTS.md` or `CLAUDE.md`, root or nested- `/writing-evals` — adding or changing eval suites, cases, scorers, or seeders under `products/posthog_ai/evals/` or `products/*/evals/`, touching the harness in `products/posthog_ai/eval_harness/`, or running those evals-- [`ee/hogai/eval/AGENTS.md`](ee/hogai/eval/AGENTS.md) — writing eval cases or fixture data by hand anywhere (not a skill, and not covered by `/writing-evals`): where that data may come from, and why anonymizing a real conversation does not make it publishable+- [`products/posthog_ai/evals/AGENTS.md`](products/posthog_ai/evals/AGENTS.md) — read before writing eval cases for the seeded Hedgebox taxonomy and the rules for invented case data- `/authoring-ci-workflows` — adding or editing any `.github/workflows` workflow, composite action, or reusable workflow- `/reviewing-personhog-protocol` — any personhog coordination-protocol change (leases, fencing, handoffs, supervisors, budgets, warming, changelog semantics), and any request for an exhaustive review of personhog code- `/gating-production-deploys` — any workflow that builds and pushes a production image or dispatches a deploydiff --git a/bin/docker-ai-evals b/bin/docker-ai-evalsdeleted file mode 100755index 6dc2ae8ea4e1..000000000000--- a/bin/docker-ai-evals+++ /dev/null@@ -1,29 +0,0 @@-#!/bin/bash-set -e-export DEBUG=1-export IN_EVAL_TESTING=1-export EVAL_MODE=offline-export EXPORT_EVAL_RESULTS=1--cleanup() {- echo "🧹 Cleaning up..."- docker compose -f docker-compose.dev.yml -p evals down -v --remove-orphans || true-}-trap cleanup EXIT INT TERM--echo "127.0.0.1 kafka clickhouse objectstorage db" >> /etc/hosts--echo "🚀 Starting services..."-docker compose -f docker-compose.dev.yml -p evals up -d db clickhouse objectstorage--echo "🔄 Waiting for services to start..."-docker compose -f docker-compose.dev.yml -p evals up -d --wait db clickhouse objectstorage--echo "🏃 Running evaluation..."-if [ -z "$EVAL_SCRIPT" ]; then- echo "Error: EVAL_SCRIPT environment variable is not set"- exit 1-fi-$EVAL_SCRIPT--echo "🎉 Done."diff --git a/docs/internal/ai-offline-evaluation-reporting.md b/docs/internal/ai-offline-evaluation-reporting.mdindex e79b57b04053..e99fc4500be2 100644--- a/docs/internal/ai-offline-evaluation-reporting.md+++ b/docs/internal/ai-offline-evaluation-reporting.md@@ -3,6 +3,7 @@The sandboxed evaluation harness in `products/posthog_ai/eval_harness/` reports scorer results as PostHog `$ai_evaluation` events.With the Braintrust engine, each suite runs once and the harness sends the resulting scores to PostHog when uploads are enabled.Reporting does not run the agent or scorers again.+Use `hogli evals` to run PostHog AI 2.0 suites. See the [eval harness guide](../../products/posthog_ai/eval_harness/README.md) for suite discovery and execution.## Capture settings@@ -19,7 +20,6 @@ Ordinary PostHog SDK clients and trace clients retain their existing `TEST` andEach event contains the existing experiment, case, and metric properties, including input, output, and expected values when available.Result reporting uses the existing event schema.-The legacy SQL evaluation path in `ee/hogai/eval/offline/` has a separate reporter and is outside this behavior.## Postgres experiment ingestiondiff --git a/ee/hogai/PROMPTING_GUIDE.md b/ee/hogai/PROMPTING_GUIDE.mdindex 22100c1b2c7c..e2c2f385c031 100644--- a/ee/hogai/PROMPTING_GUIDE.md+++ b/ee/hogai/PROMPTING_GUIDE.md@@ -228,7 +228,8 @@ You are an expert analyst...## Evaluation-PostHog uses Braintrust to test AI effectiveness. See `ee/hogai/eval/` for examples, and implement new ones for the use case you're working on.+Use the [sandbox eval harness](../../products/posthog_ai/eval_harness/README.md) to test PostHog AI 2.0.+Run `hogli evals --list` to find existing suites. Add cases under `products/posthog_ai/evals/` or `products/<product>/evals/` and follow [`/writing-evals`](../../.agents/skills/writing-evals/SKILL.md).For expert feedback, tag `@team-posthog-ai` on LLM-related PRs! Before doing that, test your feature with various user prompts, especially tricky ones.diff --git a/ee/hogai/eval/AGENTS.md b/ee/hogai/eval/AGENTS.mddeleted file mode 100644index 9732edd51ef8..000000000000--- a/ee/hogai/eval/AGENTS.md+++ /dev/null@@ -1,44 +0,0 @@-# Eval case data--Cases in this tree are committed to a public repository and are read by anyone.-Most CI evals run against the seeded Hedgebox project (the `demo_org_team_user` fixture in `ci/conftest.py`), and for those the case data is already synthetic.-Some evals supply their own case data inline instead — `ci/eval_ticket_summary.py` passes conversation transcripts straight into `EvalCase(input=...)`, because it evaluates a prompt rather than a query against a team.--This page is about that second kind.-When you write case data by hand, you are the only thing standing between a real conversation and a public repository.--## Write cases from a properties list, not from the source--Evals of support-facing features need cases that behave like real conversations, and you will often have a real one in front of you.-Do not edit it into shape.-Adapting real material and writing a fresh case are indistinguishable once you are partway through, and the result reads as synthetic while carrying somebody's actual words.--Work in this order instead:--1. Read the real material and write down only the **properties** a case has to exercise — a misspelling inside a quotable span, one word spelled two ways so a spliced quote can be caught, a mid-conversation topic change, an earlier summary sitting in the transcript, non-English text, a bare command with nothing to summarize.-2. Close the real material.-3. Write the cases from the properties list.--The list is the deliverable of step 1. If you skip writing it down, you will end up paraphrasing instead.--## Everything identifying is invented--Hostnames, emails, person and company names, IDs, cookies, and tokens in a case are made up, not anonymized versions of real ones.-Use reserved domains (`example.com`, `example.org` — RFC 2606) and obviously fake token values.--Customers paste credentials into support chats. A real cookie or a fragment of a real auth token has no business here even when it is expired, truncated, or not usable on its own.--## Do not claim a provenance you have not checked--"Written fresh" in a commit message is a factual claim, and reviewers rely on it.-Only write it if you did the properties-list procedure above.--If you are unsure whether a case drifted toward its source, check rather than assert: any shared run of roughly 40 characters or more means derived, not fresh.-A `lint-staged` warning (`.github/scripts/check-fixture-provenance.sh`) fires when a commit adds a batch of conversation-shaped case data, as a reminder to do this — it cannot tell whether the text is real, so it never blocks.--## Related--- [`AGENTS.md`](../../../AGENTS.md), "Public open source repo guidance" — what may reach any public artifact, not just eval data-- [`README.md`](./README.md) — running CI, sandboxed, and offline evals-- [`products/posthog_ai/evals/AGENTS.md`](../../../products/posthog_ai/evals/AGENTS.md) — the seeded Hedgebox taxonomy, for evals that run against a team-- `/writing-evals` covers `products/posthog_ai/evals/` and `products/*/evals/`, not this treediff --git a/ee/hogai/eval/CLAUDE.md b/ee/hogai/eval/CLAUDE.mddeleted file mode 120000index 47dc3e3d863c..000000000000--- a/ee/hogai/eval/CLAUDE.md+++ /dev/null@@ -1 +0,0 @@-AGENTS.md\ No newline at end of filediff --git a/ee/hogai/eval/README.md b/ee/hogai/eval/README.mddeleted file mode 100644index 1ca4b7ed86b2..000000000000--- a/ee/hogai/eval/README.md+++ /dev/null@@ -1,158 +0,0 @@-# AI evals--We use AI evaluations (evals) to test our AI outputs against a curated set of inputs. Evals allow us to verify prompt performance, spot regressions, or compare different model versions.----We currently use [Braintrust](https://braintrust.dev) as our evaluation platform. Braintrust tracks evaluation results, including LLM traces - which helps both track performance, and dig into any issues on a case-by-case basis. To access Braintrust and/or get an API key for it, ask #team-posthog-ai.--## CI evals--1. Export environment variable `BRAINTRUST_API_KEY` (ask #team-posthog-ai).-2. Run all evals with:-- ```bash- pytest ee/hogai/eval/ci- ```-- The key bit is specifying the `ee/hogai/eval/ci` directory – that activates our eval-specific config, `ee/hogai/eval/pytest.ini`!-- As always with pytest, you can also run a specific file, e.g. `pytest ee/hogai/eval/ci/eval_root.py`. Apply the `--eval sql` argument to only run evals for test cases that contain `sql`.--3. Voila! Max ran, evals executed, and results and traces uploaded to the Braintrust platform + summarized in the terminal.--For historical eval runs, see the [full Experiments list in Braintrust](https://www.braintrust.dev/app/PostHog/p/Max%20AI/experiments).--## Sandboxed evals--The sandboxed coding-agent evals (`products/posthog_ai/eval_harness/`) run on a standalone harness rather than pytest:--```bash-flox activate -- bash -c "set -a; source .env; set +a; python -m products.posthog_ai.eval_harness.harness [SELECTOR ...]"-```--Selectors are substrings matched against `<domain>/<module>::<fn>` (for example `experiments`, `sql`, or `eval_lifecycle_skills`); omit them to run every suite, or pass `--list` to see the ids.-`--eval <substr>` filters cases by name.-Sandboxes run locally under Docker by default; `--provider modal` runs them remotely on Modal.--Every suite runs concurrently, with one global semaphore bounding live sandboxes, so selecting more suites raises throughput without raising peak load.--- [`products/posthog_ai/eval_harness/README.md`](../../../products/posthog_ai/eval_harness/README.md) covers the flags, the provider prerequisites, and how to add a suite.-- [`products/posthog_ai/evals/AGENTS.md`](../../../products/posthog_ai/evals/AGENTS.md) is the Hedgebox dataset reference, for eval cases that run against a seeded project.-- [`AGENTS.md`](./AGENTS.md) covers cases that carry their own data inline instead — where that data may come from, and why anonymizing a real conversation does not make it publishable.-- [`products/posthog_ai/eval_harness/harness/README.md`](../../../products/posthog_ai/eval_harness/harness/README.md) explains how the harness itself works.--## Offline evals--### Datasets--For offline evaluation, you typically need to collect a dataset first. You can do that in [PostHog AI evals](https://us.posthog.com/ai-evals/datasets). PostHog datasets accept any JSON value, but this evaluation suite requires a narrower item shape:--- `input`, `expected_output`, and `metadata` must be JSON objects.-- `metadata` must contain `team_id`.--Remember to continuously review traces and curate your datasets–it's the key to quality.--### Evaluation module--Additionally, you need an evaluation module in `ee/hogai/eval/offline/*` that contains an evaluation test case with defined scorers. The test suite may contain multiple test cases, and they are separately reported. For example, if we wanted to evaluate SQL, we could implement the following evaluation module:--```python-import pytest--from braintrust import EvalCase, Score-from pydantic import BaseModel--from posthog.schema import HumanMessage--from posthog.models import Team--from ee.hogai.eval.base import MaxPrivateEval-from ee.hogai.eval.offline.conftest import EvaluationContext, capture_score, get_eval_context-from ee.hogai.eval.schema import DatasetInput-from ee.hogai.eval.scorers.sql import SQLSemanticsCorrectness, SQLSyntaxCorrectness-from ee.hogai.chat_agent import AssistantGraph-from ee.hogai.utils.types import AssistantState-from ee.models import Conversation---class EvalOutput(BaseModel):- ...--async def call_graph(entry: DatasetInput, *args):- eval_ctx = get_eval_context() # Get local evaluation context- team = await Team.objects.aget(id=entry.team_id)- conversation = await Conversation.objects.acreate(team=team, user=eval_ctx.user)- graph = AssistantGraph(team, eval_ctx.user).compile_full_graph()- state = await graph.ainvoke(- AssistantState(messages=[HumanMessage(content=entry.input["query"])]),- {- "callbacks": eval_ctx.get_callback_handlers(entry.trace_id),- "configurable": {- "thread_id": conversation.id,- "team": team,- "user": eval_ctx.user,- "distinct_id": eval_ctx.distinct_id,- },- },- )- return EvalOutput(...)---@capture_score # Decorator to automatically capture the score result-async def sql_semantics_scorer(input: DatasetInput, expected: str, output: EvalOutput, **kwargs) -> Score:- # Make sure you pass the traced OpenAI client to a scorer, so the scorer traces are captured.- client = get_eval_context().get_openai_client_for_tracing(input.trace_id)- metric = SQLSemanticsCorrectness(client=client)- return await metric.eval_async(...)---@capture_score # Decorator to automatically capture the score result-async def sql_syntax_scorer(input: DatasetInput, expected: str, output: EvalOutput, **kwargs) -> Score:- # Algorithmic scorer doesn't need the traced OpenAI client.- metric = SQLSyntaxCorrectness()- return await metric.eval_async(...)---# Generate eval cases from dataset items-def generate_test_cases(eval_ctx: EvaluationContext):- for entry in eval_ctx.dataset_inputs:- yield EvalCase(input=entry, expected=entry.expected["output"])---async def eval_offline_sql(eval_ctx: EvaluationContext, pytestconfig):- await MaxPrivateEval(- experiment_name=eval_ctx.formatted_experiment_name,- task=call_graph,- scores=[sql_syntax_scorer, sql_semantics_scorer],- data=generate_test_cases(eval_ctx),- pytestconfig=pytestconfig,- )-```--### Running an evaluation--Log in to [Dagster Cloud](https://posthog.dagster.cloud/locations/posthog.dags.locations.posthog_ai/jobs/run_evaluation/playground) and run a new `run_evaluation` job with a following config:--```yaml-ops:- prepare_dataset:- config:- dataset_id: '01992de8-3773-7946-afad-e028d45eba01' # Dataset ID- revision: 3 # Optional. Omit to run the current revision.- spawn_evaluation_container:- config:- evaluation_module: ee/hogai/eval/offline/eval_sql.py # Evaluation module- image_name: posthog-ai-evals # Leave as is or provide another image- image_tag: master # Use master or commit hash of the branch you want to evaluate-```--The job resolves one immutable dataset revision, validates its items, exports team data, runs the evaluation, and reports results back to you.-Results are compared only with earlier runs of the same dataset revision.--If you want to run an evaluation for a branch that is not `master`, you will need to build an image with the `build-ai-evals-image` tag. Once the CI is complete, you are ready to run the evaluation.--### Viewing evaluation results--Evaluation results are automatically reported to the `#evals-max-ai` channel in Slack. You can also access the same data in the Dagster asset catalog. The report will contain links with captured traces for the evaluation run.diff --git a/ee/hogai/eval/__init__.py b/ee/hogai/eval/__init__.pydeleted file mode 100644index e69de29bb2d1..000000000000diff --git a/ee/hogai/eval/base.py b/ee/hogai/eval/base.pydeleted file mode 100644index 84f12f616bc0..000000000000--- a/ee/hogai/eval/base.py+++ /dev/null@@ -1,103 +0,0 @@-import os-import asyncio-from collections.abc import Sequence-from functools import partial--import pytest--from braintrust import EvalAsync, EvalCase, Metadata, init_logger-from braintrust.framework import EvalData, EvalScorer, EvalTask, Input, Output--from posthog.models.utils import uuid7--# Imported for its side effect: braintrust's offline summary crashes on a skipped score.-from products.posthog_ai.eval_harness.engines import braintrust_patches # noqa: F401--from ee.hogai.eval.schema import DatasetInput---async def _filter_data(data: EvalData[Input, Output], case_filter: str | None = None):- # Resolve async data- if asyncio.iscoroutine(data):- # Async iterator- if hasattr(data, "__aiter__"):- data = [case async for case in data]- # asyncio.iscoroutine may return True for sync generators- elif hasattr(data, "__iter__"):- data = list(data)- # Regular awaitable- else:- data = await data- cases = []- for case in data: # type: ignore- if not isinstance(case, EvalCase):- cases.append(case)- continue-- # Reset trace IDs for DatasetInput, so we use distinct IDs instead- if os.getenv("EVAL_MODE") == "offline" and isinstance(case.input, DatasetInput):- # Mutating the input in place is intentional here. Just avoiding copying the whole object.- case.input.trace_id = str(uuid7())-- # Filter by --case <eval_case_name_part> pytest flag- if case_filter:- if case_filter in str(case.input):- cases.append(case)- else:- cases.append(case)-- return cases---async def BaseMaxEval(- experiment_name: str,- data: EvalData[Input, Output],- task: EvalTask[Input, Output],- scores: Sequence[EvalScorer[Input, Output]],- pytestconfig: pytest.Config,- metadata: Metadata | None = None,- is_public: bool = False,- no_send_logs: bool = True,-):- if is_public and not no_send_logs:- # We need to specify a separate project for each MaxEval() suite for comparison to baseline to work- # That's the way Braintrust folks recommended - Braintrust projects are much more lightweight than PostHog ones- project_name = f"max-ai-{experiment_name}"- init_logger(project_name)- else:- project_name = experiment_name-- case_filter = pytestconfig.option.eval-- timeout = 60 * 8 # 8 minutes- if os.getenv("EVAL_MODE") == "offline":- timeout = 60 * 60 # 1 hour-- result = await EvalAsync(- project_name,- data=await _filter_data(data, case_filter=case_filter),- task=task,- scores=scores,- timeout=timeout,- max_concurrency=100,- is_public=is_public,- no_send_logs=no_send_logs,- metadata=metadata,- )-- # If we're running in the offline mode and the test case marked as public, the pipeline must completely fail.- if os.getenv("EVAL_MODE") == "offline" and is_public:- raise RuntimeError("Evaluation cases must be private when EVAL_MODE is set to offline.")-- if os.getenv("EXPORT_EVAL_RESULTS"):- with open("eval_results.jsonl", "a") as f:- f.write(result.summary.as_json() + "\n")-- return result---MaxPublicEval = partial(BaseMaxEval, is_public=True, no_send_logs=False)-"""Evaluation case that is publicly accessible."""--MaxPrivateEval = partial(BaseMaxEval, is_public=False, no_send_logs=True)-"""Evaluation case is not accessible publicly."""diff --git a/ee/hogai/eval/ci/__init__.py b/ee/hogai/eval/ci/__init__.pydeleted file mode 100644index e69de29bb2d1..000000000000diff --git a/ee/hogai/eval/ci/conftest.py b/ee/hogai/eval/ci/conftest.pydeleted file mode 100644index 4b8661573c4b..000000000000--- a/ee/hogai/eval/ci/conftest.py+++ /dev/null@@ -1,129 +0,0 @@-import os-from collections.abc import Generator--import pytest--from braintrust_langchain import BraintrustCallbackHandler, set_global_handler-from langchain_core.runnables import RunnableConfig--from posthog.schema import FailureMessage, HumanMessage--from posthog.models import Organization, Team, User--from products.posthog_ai.backend.models.assistant import Conversation, CoreMemory-from products.posthog_ai.eval_harness.data_setup import (- EVAL_USER_FULL_NAME, # noqa: F401 — re-exported for eval_root_style.py- DashboardWithInsightsFixture,- create_core_memory,- create_dashboard_with_insights,- create_demo_org_team_user,-)--from ee.hogai.artifacts.manager import ArtifactManager-from ee.hogai.artifacts.utils import unwrap_visualization_artifact_content-from ee.hogai.chat_agent import AssistantGraph-from ee.hogai.django_checkpoint.checkpointer import DjangoCheckpointer--# We want the PostHog set_up_evals fixture here-from ee.hogai.eval.conftest import set_up_evals # noqa: F401-from ee.hogai.eval.scorers import PlanAndQueryOutput-from ee.hogai.utils.types import AssistantNodeName, AssistantState-from ee.hogai.utils.types.base import ArtifactRefMessage--handler = BraintrustCallbackHandler()-if os.environ.get("BRAINTRUST_API_KEY") and os.environ.get("EVAL_MODE") != "offline":- set_global_handler(handler)---def call_root_for_insight_generation(demo_org_team_user):- # This graph structure will first get a plan, then generate the SQL query.- graph = (- AssistantGraph(demo_org_team_user[1], demo_org_team_user[2])- .add_edge(AssistantNodeName.START, AssistantNodeName.ROOT)- .add_root()- # TRICKY: We need to set a checkpointer here because async tests create a new event loop.- .compile(checkpointer=DjangoCheckpointer())- )-- async def callable(- query_with_extra_context: str | tuple[str, str],- ) -> PlanAndQueryOutput:- # If query_with_extra_context is a tuple, the first element is the query, the second is the extra context- # in case there's an ask_user tool call.- query = query_with_extra_context[0] if isinstance(query_with_extra_context, tuple) else query_with_extra_context- # Initial state for the graph- initial_state = AssistantState(- messages=[HumanMessage(content=f"Answer this question: {query}")],- )- conversation = await Conversation.objects.acreate(team=demo_org_team_user[1], user=demo_org_team_user[2])-- # Invoke the graph. The state will be updated through planner and then generator.- config = RunnableConfig(configurable={"thread_id": conversation.id})- final_state_raw = await graph.ainvoke(initial_state, config)-- final_state = AssistantState.model_validate(final_state_raw)-- # If we have extra context for the potential ask_user tool, and there's no message of type ai/failure- # or artifact, we should answer with that extra context. We only do this once at most in an eval case.- if isinstance(query_with_extra_context, tuple) and not any(- isinstance(m, ArtifactRefMessage | FailureMessage) for m in final_state.messages- ):- final_state.messages = [- *final_state.messages,- HumanMessage(content=query_with_extra_context[1]),- ]- final_state.graph_status = "resumed"- final_state_raw = await graph.ainvoke(final_state, config)- final_state = AssistantState.model_validate(final_state_raw)-- # The order is a viz message, tool call message, and assistant message.- if (- not final_state.messages- or not len(final_state.messages) >= 3- or not isinstance(final_state.messages[-3], ArtifactRefMessage)- ):- return {- "plan": None,- "query": None,- "query_generation_retry_count": final_state.query_generation_retry_count,- }-- artifact_manager = ArtifactManager(team=demo_org_team_user[1], user=demo_org_team_user[2], config=config)- enriched_message = await artifact_manager.aenrich_message(final_state.messages[-3])- content = unwrap_visualization_artifact_content(enriched_message)- if content is None:- return {- "plan": None,- "query": None,- "query_generation_retry_count": final_state.query_generation_retry_count,- }- return {- "plan": content.description,- "query": content.query,- "query_generation_retry_count": final_state.query_generation_retry_count,- }-- yield callable--[email protected](scope="session", autouse=True)-def demo_org_team_user(- set_up_evals, # noqa: F811- django_db_blocker,-) -> Generator[tuple[Organization, Team, User]]:- yield create_demo_org_team_user(django_db_blocker)--[email protected](scope="session", autouse=True)-def core_memory(demo_org_team_user, django_db_blocker) -> Generator[CoreMemory]:- yield create_core_memory(demo_org_team_user[1], django_db_blocker)---def dashboard_with_insights(- demo_org_team_user,-) -> Generator[DashboardWithInsightsFixture]:- """Creates a dashboard with 3 insights and 1 replacement insight for testing UpsertDashboardTool."""- yield create_dashboard_with_insights(*demo_org_team_user)- # No manual cleanup needed - Django's test framework handles rollback automaticallydiff --git a/ee/hogai/eval/ci/eval_funnel.py b/ee/hogai/eval/ci/eval_funnel.pydeleted file mode 100644index 17b5d0796afd..000000000000--- a/ee/hogai/eval/ci/eval_funnel.py+++ /dev/null@@ -1,733 +0,0 @@-from datetime import datetime-from textwrap import dedent--import pytest--from braintrust import EvalCase--from posthog.schema import (- AssistantFunnelsEventsNode,- AssistantFunnelsExclusionEventsNode,- AssistantFunnelsFilter,- AssistantFunnelsQuery,- NodeKind,-)--from ..base import MaxPublicEval-from ..scorers import PlanAndQueryOutput, PlanCorrectness, QueryAndPlanAlignment, QueryKindSelection, TimeRangeRelevancy---async def eval_funnel(call_root_for_insight_generation, pytestconfig):- await MaxPublicEval(- experiment_name="funnel",- task=call_root_for_insight_generation,- scores=[- QueryKindSelection(expected=NodeKind.FUNNELS_QUERY),- PlanCorrectness(- query_kind=NodeKind.FUNNELS_QUERY,- evaluation_criteria="""-1. A plan must define at least two series in the sequence, but it is not required to define any filters, exclusion steps, or a breakdown.-2. Compare events, properties, math types, and property values of 'expected plan' and 'output plan'. Do not penalize if the actual output does not include a timeframe unless specified in the 'expected plan'.-3. Check if the combination of events, properties, and property values in 'output plan' can answer the user's question according to the 'expected plan'.-4. Check if the math types in 'output plan' match those in 'expected plan.' If the aggregation type is specified by a property, user, or group in 'expected plan', the same property, user, or group must be used in 'generated plan'.-5. If 'expected plan' contains exclusion steps, check if 'output plan' contains those, and heavily penalize if the exclusion steps are not present or different.-6. If 'expected plan' contains a breakdown, check if 'output plan' contains a similar breakdown, and heavily penalize if the breakdown is not present or different. Plans may only have one breakdown.-7. Heavily penalize if the 'output plan' contains any excessive output not present in the 'expected plan'. For example, the `is set` operator in filters should not be used unless the user explicitly asks for it.-""",- ),- QueryAndPlanAlignment(- query_kind=NodeKind.FUNNELS_QUERY,- query_model=AssistantFunnelsQuery,- evaluation_criteria="""-1. Series sequence: Verify that the funnel steps in the query's `series` array match the sequence order and events specified in the plan. The order must be preserved if funnel steps are set to be sequential (ordered).-2. Event names: Ensure each funnel step uses the exact event name specified in the plan for that step position.-3. Property filters: Check that event properties and filters from the plan are correctly implemented for each step:- - Property names, values, and operators must match exactly- - Multiple property values should be represented as arrays in the `value` field- - Filter types (event, person, group) must be correct- - Properties should be applied to the correct funnel step-4. Math operations: Verify that math aggregations for each step match the plan (though most funnel steps use `math: null` for simple event counting).-5. Exclusions: For exclusion steps mentioned in the plan:- - Exclusion events must be present in the `funnelsFilter.exclusions` array- - Start and end step indices (`funnelFromStep`, `funnelToStep`) must match the plan specification- - Exclusion event names must be exact-6. Breakdown implementation: Verify breakdown configuration matches the plan:- - Breakdown property name must match exactly- - Breakdown type (event, person, group) must be correct- - Only one breakdown should be present (funnels support single breakdown only)-7. Funnel configuration: Check core funnel settings align with typical defaults:- - `funnelOrderType` should typically be "ordered" unless plan specifies otherwise- - `funnelStepReference` should be "total" for standard conversion funnels- - `funnelVizType` should be "steps" for standard funnel visualization-8. Time window: Verify funnel time window settings when specified in the plan:- - `funnelWindowInterval` and `funnelWindowIntervalUnit` should match plan requirements- - Default to reasonable values (e.g., 14 days) when not specified-9. Aggregation: Check if group aggregation is correctly set when plan specifies group-based funnels (`aggregation_group_type_index`).-10. Missing implementation: Heavily penalize when key plan elements are missing (e.g., missing exclusions, wrong sequence order, incorrect breakdown).-11. Unnecessary fields: Penalize inclusion of fields not mentioned in the plan or that don't align with the funnel intent.-12. Schema compliance: Ensure all query fields conform to the JSON schema structure and constraints above.-""",- ),- TimeRangeRelevancy(query_kind=NodeKind.FUNNELS_QUERY),- ],- data=[- EvalCase(- input="Conversion from page view to sign up",- expected=PlanAndQueryOutput(- plan="""-Sequence:-1. $pageview-2. signed_up-""",- query=AssistantFunnelsQuery(- aggregation_group_type_index=None,- breakdownFilter=None,- dateRange={"date_from": "-30d", "date_to": None},- filterTestAccounts=True,- funnelsFilter=AssistantFunnelsFilter(- binCount=None,- exclusions=[],- funnelAggregateByHogQL="properties.$session_id",- funnelOrderType="ordered",- funnelStepReference="total",- funnelVizType="steps",- funnelWindowInterval=14,- funnelWindowIntervalUnit="day",- ),- series=[- AssistantFunnelsEventsNode(- event="$pageview",- math=None,- ),- AssistantFunnelsEventsNode(- event="signed_up",- math=None,- ),- ],- ),- ),- ),- EvalCase(- input="what was the conversion from a page view to sign up?",- expected=PlanAndQueryOutput(- plan="""-Sequence:-1. $pageview-2. signed_up-""",- query=AssistantFunnelsQuery(- aggregation_group_type_index=None,- breakdownFilter=None,- dateRange={"date_from": "-30d", "date_to": None},- filterTestAccounts=True,- funnelsFilter=AssistantFunnelsFilter(- binCount=None,- exclusions=[],- funnelOrderType="ordered",- funnelStepReference="total",- funnelVizType="steps",- funnelWindowInterval=14,- funnelWindowIntervalUnit="day",- ),- series=[- AssistantFunnelsEventsNode(event="$pageview", math=None, properties=None),- AssistantFunnelsEventsNode(event="signed_up", math=None, properties=None),- ],- ),- ),- ),- EvalCase(- input="What was the conversion from uploading a file to downloading it from Chrome and Safari in the last 30d?",- expected=PlanAndQueryOutput(- plan="""-Sequence:-1. uploaded_file- - property filter 1:- - entity: event- - property name: $browser- - property type: String- - operator: equals- - property value: Chrome, Safari-2. downloaded_file- - property filter 1:- - entity: event- - property name: $browser- - property type: String- - operator: equals- - property value: Chrome, Safari-""",- query=AssistantFunnelsQuery(- aggregation_group_type_index=None,- breakdownFilter=None,- dateRange={"date_from": "-30d", "date_to": None},- filterTestAccounts=True,- funnelsFilter=AssistantFunnelsFilter(- exclusions=[], funnelOrderType="ordered", funnelStepReference="total", funnelVizType="steps"- ),- series=[- AssistantFunnelsEventsNode(- event="uploaded_file",- math=None,- properties=[- {- "key": "$browser",- "value": ["Chrome", "Safari"],- "operator": "exact",- "type": "event",- },- ],- ),- AssistantFunnelsEventsNode(- event="downloaded_file",- math=None,- properties=[- {- "key": "$browser",- "value": ["Chrome", "Safari"],- "operator": "exact",- "type": "event",- },- ],- ),- ],- ),- ),- ),- EvalCase(- input="What was the conversion from uploading a file to downloading it in the last 30d excluding users that invited a team member?",- expected=PlanAndQueryOutput(- plan="""-Sequence:-1. uploaded_file-2. downloaded_file--Exclusions:-- invited_team_member- - start index: 0- - end index: 1-""",- query=AssistantFunnelsQuery(- aggregation_group_type_index=None,- breakdownFilter=None,- dateRange={"date_from": "-30d", "date_to": None},- filterTestAccounts=True,- funnelsFilter=AssistantFunnelsFilter(- exclusions=[- AssistantFunnelsExclusionEventsNode(- event="invited_team_member",- funnelFromStep=0,- funnelToStep=1,- )- ],- funnelOrderType="ordered",- funnelStepReference="total",- funnelVizType="steps",- funnelWindowInterval=14,- funnelWindowIntervalUnit="day",- ),- series=[- AssistantFunnelsEventsNode(event="uploaded_file", math=None, properties=None),- AssistantFunnelsEventsNode(event="downloaded_file", math=None, properties=None),- ],- ),- ),- ),- EvalCase(- input="Show a conversion from uploading a file to downloading it segmented by a browser",- expected=PlanAndQueryOutput(- plan="""-Sequence:-1. uploaded_file-2. downloaded_file--Breakdown by:-- entity: event-- property name: $browser-""",- query=AssistantFunnelsQuery(- aggregation_group_type_index=None,- breakdownFilter={"breakdown": "$browser", "breakdown_type": "event"},- dateRange={"date_from": "-30d", "date_to": None},- filterTestAccounts=True,- funnelsFilter=AssistantFunnelsFilter(- binCount=None,- exclusions=[],- funnelOrderType="ordered",- funnelStepReference="total",- funnelVizType="steps",- funnelWindowInterval=14,- funnelWindowIntervalUnit="day",- ),- series=[- AssistantFunnelsEventsNode(event="uploaded_file", math=None, properties=None),- AssistantFunnelsEventsNode(event="downloaded_file", math=None, properties=None),- ],- ),- ),- ),- EvalCase(- input="What was the conversion from a sign up to a paying customer on the personal-pro plan?",- expected=PlanAndQueryOutput(- plan="""-Sequence:-1. signed_up-2. paid_bill- - property filter 1:- - entity: event- - property name: plan- - property type: String- - operator: equals- - property value: personal/pro-""",- query=AssistantFunnelsQuery(- aggregation_group_type_index=None,- breakdownFilter=None,- dateRange={"date_from": "-30d", "date_to": None},- filterTestAccounts=True,- funnelsFilter=AssistantFunnelsFilter(- binCount=None,- exclusions=[],- funnelOrderType="ordered",- funnelStepReference="total",- funnelVizType="steps",- funnelWindowInterval=14,- funnelWindowIntervalUnit="day",- ),- series=[- AssistantFunnelsEventsNode(event="signed_up", math=None, properties=None),- AssistantFunnelsEventsNode(- event="paid_bill",- math=None,- properties=[- {"key": "plan", "value": "personal/pro", "operator": "exact", "type": "event"}- ],- ),- ],- ),- ),- ),- EvalCase(- input="What's our sign-up funnel?",- expected=PlanAndQueryOutput(- plan="""-Sequence:-1. $pageview-2. signed_up-""",- query=AssistantFunnelsQuery(- aggregation_group_type_index=None,- breakdownFilter=None,- dateRange={"date_from": "-30d", "date_to": None},- filterTestAccounts=True,- funnelsFilter=AssistantFunnelsFilter(- binCount=None,- exclusions=[],- funnelOrderType="ordered",- funnelStepReference="total",- funnelVizType="steps",- funnelWindowInterval=14,- funnelWindowIntervalUnit="day",- ),- series=[- AssistantFunnelsEventsNode(event="$pageview", math=None, properties=None),- AssistantFunnelsEventsNode(event="signed_up", math=None, properties=None),- ],- ),- ),- ),- EvalCase(- input="what was the conversion from a page view to sign up for event time before 2024-01-01?",- expected=PlanAndQueryOutput(- plan="""-Sequence:-1. $pageview-2. signed_up--Time period: before 2024-01-01-Granularity: day-""",- query=AssistantFunnelsQuery(- aggregation_group_type_index=None,- breakdownFilter=None,- dateRange={"date_from": "2023-12-01", "date_to": "2024-01-01"},- filterTestAccounts=True,- funnelsFilter=AssistantFunnelsFilter(- binCount=None,- exclusions=[],- funnelOrderType="ordered",- funnelStepReference="total",- funnelVizType="steps",- funnelWindowInterval=14, # Default, plan doesn't specify interval length- funnelWindowIntervalUnit="day", # From plan- ),- series=[- AssistantFunnelsEventsNode(event="$pageview", math=None, properties=None),- AssistantFunnelsEventsNode(event="signed_up", math=None, properties=None),- ],- ),- ),- ),- EvalCase(- input="conversion from a page view to a sign up for yesterday",- expected=PlanAndQueryOutput(- plan="Sequence:\\n1. $pageview\\n2. signed_up\\n\\nTime period: for yesterday",- query=AssistantFunnelsQuery(- aggregation_group_type_index=None,- breakdownFilter=None,- dateRange={"date_from": "-1d", "date_to": "dStart"}, # "yesterday"- filterTestAccounts=True,- funnelsFilter=AssistantFunnelsFilter(- binCount=None,- exclusions=[],- funnelOrderType="ordered",- funnelStepReference="total",- funnelVizType="steps",- funnelWindowInterval=14,- funnelWindowIntervalUnit="day",- ),- series=[- AssistantFunnelsEventsNode(event="$pageview", math=None, properties=None),- AssistantFunnelsEventsNode(event="signed_up", math=None, properties=None),- ],- ),- ),- ),- EvalCase(- input="conversion from a page view to a sign up for the last 1 week",- expected=PlanAndQueryOutput(- plan="Sequence:\\n1. $pageview\\n2. signed_up\\n\\nTime period: for the last 1 week",- query=AssistantFunnelsQuery(- aggregation_group_type_index=None,- breakdownFilter=None,- dateRange={"date_from": "-7d"},- filterTestAccounts=True,- funnelsFilter=AssistantFunnelsFilter(- binCount=None,- exclusions=[],- funnelOrderType="ordered",- funnelStepReference="total",- funnelVizType="steps",- funnelWindowInterval=14,- funnelWindowIntervalUnit="day",- ),- series=[- AssistantFunnelsEventsNode(event="$pageview", math=None, properties=None),- AssistantFunnelsEventsNode(event="signed_up", math=None, properties=None),- ],- ),- ),- ),- EvalCase(- input="conversion from a page view to a sign up for the last 1 month",- expected=PlanAndQueryOutput(- plan="Sequence:\\n1. $pageview\\n2. signed_up\\n\\nTime period: for the last 1 month",- query=AssistantFunnelsQuery(- aggregation_group_type_index=None,- breakdownFilter=None,- dateRange={"date_from": "-1m"},- filterTestAccounts=True,- funnelsFilter=AssistantFunnelsFilter(- binCount=None,- exclusions=[],- funnelOrderType="ordered",- funnelStepReference="total",- funnelVizType="steps",- funnelWindowInterval=14,- funnelWindowIntervalUnit="day",- ),- series=[- AssistantFunnelsEventsNode(event="$pageview", math=None, properties=None),- AssistantFunnelsEventsNode(event="signed_up", math=None, properties=None),- ],- ),- ),- ),- EvalCase(- input="conversion from a page view to a sign up for the last 80 days",- expected=PlanAndQueryOutput(- plan="Sequence:\\n1. $pageview\\n2. signed_up\\n\\nTime period: for the last 80 days",- query=AssistantFunnelsQuery(- aggregation_group_type_index=None,- breakdownFilter=None,- dateRange={"date_from": "-80d"},- filterTestAccounts=True,- funnelsFilter=AssistantFunnelsFilter(- binCount=None,- exclusions=[],- funnelOrderType="ordered",- funnelStepReference="total",- funnelVizType="steps",- funnelWindowInterval=14,- funnelWindowIntervalUnit="day",- ),- series=[- AssistantFunnelsEventsNode(event="$pageview", math=None, properties=None),- AssistantFunnelsEventsNode(event="signed_up", math=None, properties=None),- ],- ),- ),- ),- EvalCase(- input="conversion from a page view to a sign up for the last 6 months",- expected=PlanAndQueryOutput(- plan="Sequence:\\n1. $pageview\\n2. signed_up\\n\\nTime period: for the last 6 months",- query=AssistantFunnelsQuery(- aggregation_group_type_index=None,- breakdownFilter=None,- dateRange={"date_from": "-6m"},- filterTestAccounts=True,- funnelsFilter=AssistantFunnelsFilter(- binCount=None,- exclusions=[],- funnelOrderType="ordered",- funnelStepReference="total",- funnelVizType="steps",- funnelWindowInterval=14,- funnelWindowIntervalUnit="day",- ),- series=[- AssistantFunnelsEventsNode(event="$pageview", math=None, properties=None),- AssistantFunnelsEventsNode(event="signed_up", math=None, properties=None),- ],- ),- ),- ),- EvalCase(- input="conversion from a page view to a sign up from 2020 to 2025",- expected=PlanAndQueryOutput(- plan="Sequence:\\n1. $pageview\\n2. signed_up\\n\\nTime period: from 2020 to 2025",- query=AssistantFunnelsQuery(- aggregation_group_type_index=None,- breakdownFilter=None,- dateRange={"date_from": "2020-01-01", "date_to": "2025-12-31"},- filterTestAccounts=True,- funnelsFilter=AssistantFunnelsFilter(- binCount=None,- exclusions=[],- funnelOrderType="ordered",- funnelStepReference="total",- funnelVizType="steps",- funnelWindowInterval=14,- funnelWindowIntervalUnit="day",- ),- series=[- AssistantFunnelsEventsNode(event="$pageview", math=None, properties=None),- AssistantFunnelsEventsNode(event="signed_up", math=None, properties=None),- ],- ),- ),- ),- EvalCase(- input="conversion from a page view to a sign up",- expected=PlanAndQueryOutput(- plan="""-Sequence:-1. $pageview-2. signed_up--Time period: last 30 days-Time interval: day-""",- query=AssistantFunnelsQuery(- aggregation_group_type_index=None,- breakdownFilter=None,- dateRange={"date_from": "-30d"},- filterTestAccounts=True,- funnelsFilter=AssistantFunnelsFilter(- binCount=None,- exclusions=[],- funnelOrderType="ordered",- funnelStepReference="total",- funnelVizType="steps",- funnelWindowInterval=14,- funnelWindowIntervalUnit="day", # from "Time interval: day"- ),- series=[- AssistantFunnelsEventsNode(event="$pageview", math=None, properties=None),- AssistantFunnelsEventsNode(event="signed_up", math=None, properties=None),- ],- ),- ),- ),- EvalCase(- input="what is the conversion rate from a page view to sign up for users with name John?",- expected=PlanAndQueryOutput(- plan="""-Sequence:-1. $pageview-- property filter 1- - person- - name- - equals- - John-2. signed_up-""",- query=AssistantFunnelsQuery(- aggregation_group_type_index=None,- breakdownFilter=None,- dateRange={"date_from": "-30d", "date_to": None},- filterTestAccounts=True,- funnelsFilter=AssistantFunnelsFilter(- binCount=None,- exclusions=[],- funnelOrderType="ordered",- funnelStepReference="total",- funnelVizType="steps",- funnelWindowInterval=14,- funnelWindowIntervalUnit="day",- ),- series=[- AssistantFunnelsEventsNode(- event="$pageview",- math=None,- properties=[{"key": "name", "value": "John", "operator": "exact", "type": "person"}],- ),- AssistantFunnelsEventsNode(event="signed_up", math=None, properties=None),- ],- ),- ),- ),- EvalCase(- input="what is the conversion rate from a page view to a next page view in this January?",- expected=PlanAndQueryOutput(- plan="""-Sequence:-1. $pageview-2. $pageview--Time period: this January-""",- query=AssistantFunnelsQuery(- aggregation_group_type_index=None,- breakdownFilter=None,- dateRange={- "date_from": f"{datetime.now().year}-01-01",- "date_to": f"{datetime.now().year}-01-31",- },- filterTestAccounts=True,- funnelsFilter=AssistantFunnelsFilter(- binCount=None,- exclusions=[],- funnelOrderType="ordered",- funnelStepReference="total",- funnelVizType="steps",- funnelWindowInterval=14,- funnelWindowIntervalUnit="day",- ),- series=[- AssistantFunnelsEventsNode(event="$pageview", math=None, properties=None),- AssistantFunnelsEventsNode(event="$pageview", math=None, properties=None),- ],- ),- ),- ),- # Should include the aggregation by session- EvalCase(- input="what is the conversion rate from a page view to a next page view in this January aggregated by session?",- expected=PlanAndQueryOutput(- plan=dedent("""- Sequence:- 1. $pageview- 2. $pageview-- Time period: this January- """),- query=AssistantFunnelsQuery(- aggregation_group_type_index=None,- breakdownFilter=None,- dateRange={- "date_from": f"{datetime.now().year}-01-01",- "date_to": f"{datetime.now().year}-01-31",- },- filterTestAccounts=True,- funnelsFilter=AssistantFunnelsFilter(- binCount=None,- exclusions=[],- funnelOrderType="ordered",- funnelStepReference="total",- funnelVizType="steps",- funnelWindowInterval=14,- funnelWindowIntervalUnit="day",- funnelAggregateByHogQL="properties.$session_id",- ),- series=[- AssistantFunnelsEventsNode(event="$pageview", math=None, properties=None),- AssistantFunnelsEventsNode(event="$pageview", math=None, properties=None),- ],- ),- ),- ),- # Should include the aggregation by user- EvalCase(- input="what is the conversion rate from a page view to a next page view in this January aggregated by user?",- expected=PlanAndQueryOutput(- plan=dedent("""- Sequence:- 1. $pageview- 2. $pageview-- Time period: this January- """),- query=AssistantFunnelsQuery(- aggregation_group_type_index=None,- breakdownFilter=None,- dateRange={- "date_from": f"{datetime.now().year}-01-01",- "date_to": f"{datetime.now().year}-01-31",- },- filterTestAccounts=True,- funnelsFilter=AssistantFunnelsFilter(- binCount=None,- exclusions=[],- funnelOrderType="ordered",- funnelStepReference="total",- funnelVizType="steps",- funnelWindowInterval=14,- funnelWindowIntervalUnit="day",- ),- series=[- AssistantFunnelsEventsNode(event="$pageview", math=None, properties=None),- AssistantFunnelsEventsNode(event="$pageview", math=None, properties=None),- ],- ),- ),- ),- # Should aggregate by unique accounts (group analytics)- EvalCase(- input="what is the conversion rate from a page view to a next page view in this January aggregated by unique accounts?",- expected=PlanAndQueryOutput(- plan=dedent("""- Sequence:- 1. $pageview- 2. $pageview-- Time period: this January- """),- query=AssistantFunnelsQuery(- aggregation_group_type_index=0,- breakdownFilter=None,- dateRange={- "date_from": f"{datetime.now().year}-01-01",- "date_to": f"{datetime.now().year}-01-31",- },- filterTestAccounts=True,- funnelsFilter=AssistantFunnelsFilter(- binCount=None,- exclusions=[],- funnelOrderType="ordered",- funnelStepReference="total",- funnelVizType="steps",- funnelWindowInterval=14,- funnelWindowIntervalUnit="day",- ),- series=[- AssistantFunnelsEventsNode(event="$pageview", math=None, properties=None),- AssistantFunnelsEventsNode(event="$pageview", math=None, properties=None),- ],- ),- ),- ),- ],- pytestconfig=pytestconfig,- )diff --git a/ee/hogai/eval/ci/eval_insight_search.py b/ee/hogai/eval/ci/eval_insight_search.pydeleted file mode 100644index b0a1305ab144..000000000000--- a/ee/hogai/eval/ci/eval_insight_search.py+++ /dev/null@@ -1,165 +0,0 @@-import re--import pytest-from unittest.mock import patch--from braintrust import EvalCase--from posthog.schema import HumanMessage--from products.posthog_ai.backend.models.assistant import Conversation--from ee.hogai.chat_agent import AssistantGraph-from ee.hogai.django_checkpoint.checkpointer import DjangoCheckpointer-from ee.hogai.utils.types import AssistantNodeName, AssistantState-from ee.hogai.utils.types.base import ArtifactRefMessage--from ..base import MaxPublicEval-from ..scorers import InsightEvaluationAccuracy, InsightSearchOutput---def extract_evaluation_info_from_state(state) -> dict:- """Extract evaluation information from the final assistant state."""- artifact_messages = [msg for msg in state.messages if isinstance(msg, ArtifactRefMessage)]-- evaluation_message = None- found_insights_in_evaluation = False- for msg in state.messages:- if hasattr(msg, "content") and "Evaluation Result" in str(msg.content):- evaluation_message = msg.content- content = str(msg.content)- if "Found" in content and "relevant insight" in content:- found_insights_in_evaluation = True- break-- # Determine if insights were selected or rejected- # Use both artifact message presence AND evaluation result content- has_selected_insights = len(artifact_messages) > 0 or found_insights_in_evaluation- is_creating_new_insight = bool(state.root_tool_insight_plan)-- # Also check for "No existing insights found" message which indicates new insight creation- # BUT only if we don't already have insights selected (artifact message takes precedence)- if not is_creating_new_insight and not has_selected_insights:- for msg in state.messages:- if hasattr(msg, "content"):- content = str(msg.content)- if "No existing insights found matching your query" in content:- is_creating_new_insight = True- break-- selected_insight_ids = []- if has_selected_insights:- for msg in state.messages:- if hasattr(msg, "content"):- content = str(msg.content)- # Look for numeric IDs first- id_matches = re.findall(- r"(?:Insight\s+ID\s+|Insight\s+|Selected\s+insight\s+)(\d+)", content, re.IGNORECASE- )- for match in id_matches:- try:- insight_id = int(match)- if insight_id not in selected_insight_ids:- selected_insight_ids.append(insight_id)- except ValueError:- pass-- # Also look for short IDs in URLs like /insights/PHIpzaKI- url_matches = re.findall(r"/insights/([A-Za-z0-9_-]+)", content)- for short_id in url_matches:- # Convert short ID to string representation for consistency- if short_id not in selected_insight_ids:- selected_insight_ids.append(short_id)-- return {- "selected_insights": selected_insight_ids,- "has_selected_insights": has_selected_insights,- "is_creating_new_insight": is_creating_new_insight,- "evaluation_message": evaluation_message,- "visualization_count": len(artifact_messages),- }---def call_insight_search(demo_org_team_user):- """Fixture that creates a callable for executing insight search workflows."""- graph = (- AssistantGraph(demo_org_team_user[1], demo_org_team_user[2])- .add_edge(AssistantNodeName.START, AssistantNodeName.ROOT)- .add_root()- .compile(checkpointer=DjangoCheckpointer())- )-- async def callable(search_query: str) -> InsightSearchOutput:- conversation = await Conversation.objects.acreate(team=demo_org_team_user[1], user=demo_org_team_user[2])- initial_state = AssistantState(- messages=[HumanMessage(content=f"Search for insights: {search_query}")],- search_insights_query=search_query,- )-- # search_insights is gated begind feature flag, we need to mock it for always being truthy- with patch("posthoganalytics.feature_enabled", return_value=True):- raw_state = await graph.ainvoke(initial_state, {"configurable": {"thread_id": conversation.id}})- state = AssistantState.model_validate(raw_state)-- eval_info = extract_evaluation_info_from_state(state)-- if eval_info["is_creating_new_insight"]:- evaluation_result = {- "should_use_existing": False,- "explanation": "Evaluation decided to create new insight (root_tool_insight_plan set)",- }- elif eval_info["has_selected_insights"]:- evaluation_result = {- "should_use_existing": True,- "explanation": f"Selected {eval_info['visualization_count']} insight(s) - found visualization messages",- }- else:- evaluation_result = {- "should_use_existing": False,- "explanation": "No insights selected and no new insight creation triggered",- }-- selected_insights = eval_info["selected_insights"]- if not selected_insights and eval_info["has_selected_insights"]:- # Return empty list to make the failure visible in evaluation- selected_insights = []-- unique_insights = list(dict.fromkeys(selected_insights))-- return {- "selected_insights": unique_insights,- "search_query": search_query,- "evaluation_result": evaluation_result,- }-- return callable---async def eval_insight_evaluation_accuracy(call_insight_search, pytestconfig):- """Evaluate the accuracy of the insight evaluation decision."""- await MaxPublicEval(- experiment_name="insight_evaluation_accuracy",- task=call_insight_search,- scores=[InsightEvaluationAccuracy()],- data=[- EvalCase(- input="show me pageview trends",- expected=True,- ),- EvalCase(- input="user signups over time",- expected=True,- ),- EvalCase(- input="conversion rates for purple unicorn purchases by left-handed users",- expected=False,- ),- EvalCase(- input="pokemon cards sold yesterday",- expected=False,- ),- ],- pytestconfig=pytestconfig,- )diff --git a/ee/hogai/eval/ci/eval_memory.py b/ee/hogai/eval/ci/eval_memory.pydeleted file mode 100644index 545b61dbdfee..000000000000--- a/ee/hogai/eval/ci/eval_memory.py+++ /dev/null@@ -1,198 +0,0 @@-from typing import Optional--import pytest--from autoevals.llm import LLMClassifier-from braintrust import EvalCase, Score-from langchain_core.messages import AIMessage as LangchainAIMessage--from posthog.schema import AssistantMessage, AssistantToolCall, HumanMessage--from products.posthog_ai.backend.models.assistant import Conversation--from ee.hogai.chat_agent import AssistantGraph-from ee.hogai.django_checkpoint.checkpointer import DjangoCheckpointer-from ee.hogai.utils.types import AssistantNodeName, AssistantState--from ..base import MaxPublicEval-from ..scorers import ToolRelevance---class MemoryContentRelevance(LLMClassifier):- """Evaluate memory content relevance and formatting."""-- def __init__(self, **kwargs):- super().__init__(- name="memory_content_relevance",- prompt_template="""Evaluate if the memory content is relevant and well-formatted.--Context:-- Memory content should contain factual information about the product or company-- When users explicitly request to save information (e.g., "remember that...", "remember this..."), the information should be saved even if it's not product-related (e.g., personal preferences, user context)-- Personal information or irrelevant details should be omitted UNLESS explicitly requested-- Facts should be stated clearly and consistently-- When replacing facts, the new fact should be logically related to the original--Input: {{input}}-Memory content: {{output}}-Expected content: {{expected}}--How would you rate the memory content? Choose one:-- perfect: Exactly what we want - relevant, well-formatted, and complete-- good: Relevant but could be better formatted or more complete-- partial: Some relevant content but missing key details or poorly formatted-- irrelevant: Completely off-topic or inappropriate content""",- choice_scores={- "perfect": 1.0,- "good": 0.7,- "partial": 0.4,- "irrelevant": 0.0,- },- model="gpt-4.1",- **kwargs,- )-- async def _run_eval_async(self, output, expected, **kwargs):- output = output.tool_calls[0] if output and output.tool_calls else None- if output is None and expected is None:- return Score(name=self._name(), score=1.0)- if output is None or expected is None:- return Score(name=self._name(), score=0.0)- return await super()._run_eval_async(output, expected, **kwargs)-- def _run_eval_sync(self, output, expected, **kwargs):- output = output.tool_calls[0] if output and output.tool_calls else None- if output is None and expected is None:- return Score(name=self._name(), score=1.0)- if output is None or expected is None:- return Score(name=self._name(), score=0.0)- return super()._run_eval_sync(output, expected, **kwargs)---def call_node(demo_org_team_user, core_memory):- graph = (- AssistantGraph(demo_org_team_user[1], demo_org_team_user[2])- .add_edge(AssistantNodeName.START, AssistantNodeName.MEMORY_COLLECTOR)- .add_memory_collector(AssistantNodeName.END, AssistantNodeName.END)- # TRICKY: We need to set a checkpointer here because async tests create a new event loop.- .compile(checkpointer=DjangoCheckpointer())- )-- async def callable(message: str) -> Optional[AssistantMessage]:- conversation = await Conversation.objects.acreate(team=demo_org_team_user[1], user=demo_org_team_user[2])- raw_state = await graph.ainvoke(- AssistantState(messages=[HumanMessage(content=message)]), {"configurable": {"thread_id": conversation.id}}- )- state = AssistantState.model_validate(raw_state)- if not state.memory_collection_messages:- return None- last_message = state.memory_collection_messages[-1]- if not isinstance(last_message, LangchainAIMessage):- return None- return AssistantMessage(- content=last_message.content,- tool_calls=last_message.tool_calls,- )-- return callable---async def eval_memory(call_node, pytestconfig):- await MaxPublicEval(- experiment_name="memory",- task=call_node,- scores=[ToolRelevance(semantic_similarity_args={"memory_content", "new_fragment"}), MemoryContentRelevance()],- data=[- # Test saving relevant facts- EvalCase(- input="calculate ARR: use the paid_bill event and the amount property.",- expected=AssistantToolCall(- id="1",- name="core_memory_append",- args={- "memory_content": "The product uses the event paid_bill and the property amount to calculate Annual Recurring Revenue (ARR)."- },- ),- ),- # Test saving company information- EvalCase(- input="Our secondary target audience is technical founders or highly-technical product managers.",- expected=AssistantToolCall(- id="2",- name="core_memory_append",- args={- "memory_content": "The company's secondary target audience is technical founders or highly-technical product managers."- },- ),- ),- # Test fact replacement- EvalCase(- input="Hedgebox doesn't sponsor the YouTube channel Marius Tech Tips anymore.",- expected=AssistantToolCall(- id="3",- name="core_memory_replace",- args={- "original_fragment": "Hedgebox sponsors the YouTube channel Marius Tech Tips.",- "new_fragment": "Hedgebox no longer sponsors the YouTube channel Marius Tech Tips.",- },- ),- ),- # Test fact deletion- EvalCase(- input="Delete info that Hedgebox sponsored the YouTube channel Marius Tech Tips.",- expected=AssistantToolCall(- id="4",- name="core_memory_replace",- args={- "original_fragment": "Hedgebox sponsors the YouTube channel Marius Tech Tips.",- "new_fragment": "",- },- ),- ),- # Test explicit memory request- EvalCase(- input="Remember that I like to view the pageview trend broken down by a country.",- expected=AssistantToolCall(- id="5",- name="core_memory_append",- args={"memory_content": "The user prefers to view pageview trends broken down by country."},- ),- ),- # Test /remember slash command- EvalCase(- input="/remember Our main KPI is monthly active users (MAU)",- expected=AssistantToolCall(- id="6",- name="core_memory_append",- args={"memory_content": "Our main KPI is monthly active users (MAU)"},- ),- ),- # Test explicit non-product-related memory request- EvalCase(- input="Remember my favorite treat is chocolate",- expected=AssistantToolCall(- id="7",- name="core_memory_append",- args={"memory_content": "The user's favorite treat is chocolate."},- ),- ),- # Test /remember slash command with no arg- EvalCase(- input="/remember",- expected=None,- ),- # Test omitting irrelevant personal info- EvalCase(- input="My name is John Doherty.",- expected=None,- ),- # Test omitting irrelevant insight info- EvalCase(- input="Build a pageview trend for users with name John.",- expected=None,- ),- ],- pytestconfig=pytestconfig,- )diff --git a/ee/hogai/eval/ci/eval_memory_onboarding.py b/ee/hogai/eval/ci/eval_memory_onboarding.pydeleted file mode 100644index 266d3461d509..000000000000--- a/ee/hogai/eval/ci/eval_memory_onboarding.py+++ /dev/null@@ -1,464 +0,0 @@-from typing import Optional-from uuid import uuid4--import pytest--from autoevals.llm import LLMClassifier-from braintrust import EvalCase-from braintrust_core import Score--from posthog.schema import AssistantMessage, EventTaxonomyItem, HumanMessage--from posthog.models.user import User-from posthog.sync import database_sync_to_async--from products.posthog_ai.backend.models.assistant import Conversation--from ee.hogai.chat_agent import AssistantGraph-from ee.hogai.chat_agent.memory.prompts import (- ENQUIRY_INITIAL_MESSAGE,- ENQUIRY_NO_EVENTS_INITIAL_MESSAGE,- SCRAPING_SUCCESS_KEY_PHRASE,- SCRAPING_TERMINATION_MESSAGE,-)-from ee.hogai.core.agent_modes import SlashCommandName-from ee.hogai.django_checkpoint.checkpointer import DjangoCheckpointer-from ee.hogai.utils.types import AssistantNodeName, AssistantState--from ..base import MaxPublicEval---class MemoryLLMClassifier(LLMClassifier):- def _run_eval_sync(self, output, expected, **kwargs):- if not output:- return Score(name=self._name(), score=None)- if expected in [ENQUIRY_INITIAL_MESSAGE, ENQUIRY_NO_EVENTS_INITIAL_MESSAGE, SCRAPING_TERMINATION_MESSAGE]:- # For the special cases, we MUST see the expected messages verbatim- return Score(- name=self._name(),- score=1.0 if isinstance(output, AssistantMessage) and output.content == expected else 0.0,- )- return super()._run_eval_sync(output, expected, **kwargs)-- async def _run_eval_async(self, output, expected, **kwargs):- if not output:- return Score(name=self._name(), score=None)- if expected in [ENQUIRY_INITIAL_MESSAGE, ENQUIRY_NO_EVENTS_INITIAL_MESSAGE, SCRAPING_TERMINATION_MESSAGE]:- # For the special cases, we MUST see the expected messages verbatim- return Score(- name=self._name(),- score=1.0 if isinstance(output, AssistantMessage) and output.content == expected else 0.0,- )- return await super()._run_eval_async(output, expected, **kwargs)---class SatisfiesProductDetails(MemoryLLMClassifier):- """Binary check: Does the scraped content contain identifiable product features?"""-- def __init__(self, **kwargs):- super().__init__(- name="satisfies_product_details",- prompt_template="""Determine if the scraped content contains identifiable product features.--A PASS requires:-- At least 2-3 specific product features are mentioned-- Features are described with actual names or functionality (not generic)-- Features relate to the actual product being analyzed--A FAIL means:-- No specific features mentioned, only vague descriptions-- Features are generic or unrelated to the actual product-- Content is purely marketing speak without concrete functionality--<input>{{input}}</input>-<expected_output>{{expected}}</expected_output>-<actual_output>{{output}}</actual_output>--Compare the output to the expected content. Does the output contain identifiable product features like those shown in the expected example? Be brutal.-- pass: Contains specific, identifiable product features-- fail: No identifiable product features found""",- choice_scores={- "pass": 1.0,- "fail": 0.0,- },- model="gpt-4.1",- **kwargs,- )---class SatisfiesBusinessDetails(MemoryLLMClassifier):- """Binary check: Does the scraped content contain business model information?"""-- def __init__(self, **kwargs):- super().__init__(- name="satisfies_business_details",- prompt_template="""Determine if the scraped content contains business model information.--A PASS requires:-- Clear indication of how the company makes money (subscription, freemium, ads, etc.)-- OR specific pricing information mentioned-- OR monetization strategy described--A FAIL means:-- No mention of how the company generates revenue-- Only vague business descriptions without monetization details-- No pricing or business model information found--<input>{{input}}</input>-<expected_output>{{expected}}</expected_output>-<actual_output>{{output}}</actual_output>--Compare the output to the expected content. Does the output contain business model information like that shown in the expected example? Be brutal-- pass: Contains business model or monetization information-- fail: No business model information found""",- choice_scores={- "pass": 1.0,- "fail": 0.0,- },- model="gpt-4.1",- **kwargs,- )---class SatisfiesTechnicalDetails(MemoryLLMClassifier):- """Binary check: Does the scraped content contain technical implementation details?"""-- def __init__(self, **kwargs):- super().__init__(- name="has_technical_details",- prompt_template="""Determine if the scraped content contains technical implementation details.--A PASS requires:-- Mention of specific technologies, frameworks, or platforms used-- OR API/integration capabilities described-- OR technical architecture or infrastructure details-- OR development/deployment information--A FAIL means:-- No technical details mentioned-- Only high-level product descriptions without technical specifics-- No mention of underlying technology or implementation--Note: Not all products will have technical details in their public materials, so this may legitimately fail.--<input>{{input}}</input>-<expected_output>{{expected}}</expected_output>-<actual_output>{{output}}</actual_output>--Compare the output to the expected content. Does the output contain technical implementation details like those shown in the expected example? Be brutal-- pass: Contains specific technical details-- fail: No technical details found""",- choice_scores={- "pass": 1.0,- "fail": 0.0,- },- model="gpt-4.1",- **kwargs,- )---class HasCorrectStyle(MemoryLLMClassifier):- """Binary check: Does the scraped content follow the required formatting structure?"""-- def __init__(self, **kwargs):- super().__init__(- name="has_correct_style",- prompt_template=f"""Determine if the scraped content follows the required formatting structure.--A PASS requires ALL of the following:-- Starts with exactly "__{SCRAPING_SUCCESS_KEY_PHRASE} [some product/domain name]:__" (bold formatting with colon)-- Contains at least one section with #### heading format (h4 markdown headers)-- Sections should include relevant topics like "Product features", "User/Customer segments", "Business model", "Technical details", or "Brief history"-- Uses bullet points (-) or structured formatting within sections (not just paragraphs)-- Content is well-organized with clear separation between topics-- No follow-up suggestions or calls-to-action at the end-- No citation anywhere (i.e. link in parentheses)--A FAIL occurs if ANY of the following is true:-- Missing or incorrect opening format (doesn't start with "__{SCRAPING_SUCCESS_KEY_PHRASE} ...:__")-- No #### section headings found-- Poor organization with wall-of-text paragraphs instead of structured sections-- Contains follow-up suggestions like "Would you like to know more?" or "Contact us"-- Sections lack bullet points or clear structure-- Generic formatting without the specified markdown structure-- A citation link is found-- There is any follow-up suggestion for the reader (like "Let me know if you'd like X" or "To do something, go to Y")--Note: The format requirements are specifically defined in the memory initialization prompt and must be followed exactly.--<input>{{{{input}}}}</input>-<expected_output>{{{{expected}}}}</expected_output>-<actual_output>{{{{output}}}}</actual_output>--Compare the output to the expected content format. Does the output follow the exact required formatting structure with proper opening, #### headers, and bullet points like shown in the expected example? Be brutal-- pass: Follows all required formatting specifications exactly-- fail: Missing required formatting elements or includes prohibited content""",- choice_scores={- "pass": 1.0,- "fail": 0.0,- },- model="gpt-4.1",- **kwargs,- )--[email protected](scope="module")-def core_memory():- """We override the conftest.py core_memory fixture, which has autouse=True, as for memory onboarding a CoreMemory must be ABSENT."""- pass---def call_memory_onboarding():- """Fixture to call MemoryOnboardingNode with a parametrized EventTaxonomyItem as input."""-- async def callable(input: tuple[str, Optional[EventTaxonomyItem]]) -> Optional[AssistantMessage]:- organization_name, taxonomy_item = input # The org name MAY matter as it gets included in the system prompt- # Because memory is stateful at the team level, each eval case here must have its own team instance- _, team, user = await database_sync_to_async(User.objects.bootstrap)(- organization_name=organization_name, email=f"{uuid4()}@example.com", password=None- )- conversation = await Conversation.objects.acreate(team=team, user=user)-- graph = (- AssistantGraph(team=team, user=user)- .add_edge(AssistantNodeName.START, AssistantNodeName.MEMORY_ONBOARDING)- .add_memory_onboarding(AssistantNodeName.END)- .compile(checkpointer=DjangoCheckpointer())- )- raw_state = await graph.ainvoke(- AssistantState(messages=[HumanMessage(content=SlashCommandName.FIELD_INIT)]),- # Mock the _retrieve_context method to return our input data via `configurable`- # Because evals run concurrently and everything's async, patch() just doesn't work- {"configurable": {"thread_id": conversation.id, "_mock_memory_onboarding_context": taxonomy_item}},- )-- state = AssistantState.model_validate(raw_state)- if not state.messages:- return None- last_message = state.messages[-1]- if not isinstance(last_message, AssistantMessage):- return None- return last_message-- return callable---async def eval_memory_onboarding(call_memory_onboarding, pytestconfig):- await MaxPublicEval(- experiment_name="memory_onboarding",- task=call_memory_onboarding,- scores=[- SatisfiesProductDetails(),- SatisfiesBusinessDetails(),- SatisfiesTechnicalDetails(),- HasCorrectStyle(),- ],- data=[- # Case: SaaS, well-known and massive in scope (so this one is tricky to describe in any detail)- EvalCase(- input=(- "Salesforce",- EventTaxonomyItem(property="$host", sample_values=["salesforce.com"], sample_count=1),- ),- expected="""-__Here's what I found on salesforce.com:__--Salesforce is a leading cloud-based customer relationship management (CRM) platform and enterprise software company offering a broad suite of clouds and platform services (Sales Cloud, Service Cloud, Marketing Cloud, Commerce Cloud), plus analytics, integration, collaboration, data and AI capabilities (Tableau, MuleSoft, Slack, Data Cloud, Einstein / Agentforce) that are sold as modular, integrated SaaS products.--#### Product features-- Core CRM clouds: Sales Cloud (opportunity & pipeline management), Service Cloud (case & support management), Marketing Cloud (campaigns, personalization), Commerce Cloud (e‑commerce).-- Data & analytics: Tableau for analytics/BI and Data Cloud as a unified customer data layer (real‑time profiles, CDP-like capabilities, vector/unstructured support).-- Integration & extensibility: MuleSoft acquisitions and connectors (API-led integrations), AppExchange marketplace, platform tools (Flows, Apex, low-code/no-code builders) to build custom apps.-- AI and agents: Einstein AI and Agentforce (autonomous AI agents/assistant capabilities, Atlas reasoning engine, built-in guardrails and supervised deployment tools).-- Collaboration & ecosystem: Slack integration for in‑flow collaboration, plus partner ISV ecosystem, prebuilt industry templates and vertical solutions.--#### User / Customer segments-- Large enterprises and global organizations across industries (financial services, healthcare, retail, manufacturing, telecommunications) adopting full Customer 360 suites.-- Midsize businesses and SMBs via tiered CRM editions and Starter/Pro suites.-- System integrators, consultants, and ISVs that build and resell vertical solutions on the Salesforce Platform and AppExchange.--#### Business model-- Primarily subscription SaaS: per‑user/per‑month licensing with tiered editions and enterprise contracts (Starter/Pro/Enterprise/Unlimited and higher‑tier AI/agent offerings).-- Add‑ons and usage‑based credits: Data Cloud/Flex credits, premium AI/agent bundles (Agentforce/Einsten tiers), premium support, professional services and implementation.-- Ecosystem monetization: AppExchange marketplace, partner/reseller revenue, and professional services (consulting, implementation, managed services).--#### Technical details-- Multi‑product platform: Customer 360 architecture ties CRM apps to a central data layer (Data Cloud) and platform services (Flow automation, APIs, Apex) for real‑time activations and cross‑cloud workflows.-- Integration posture: Emphasis on API‑led connectivity (MuleSoft and connectors) to unify on‑prem, cloud, data warehouses and third‑party systems.-- AI & data stack: Native capabilities for RAG (retrieval‑augmented generation), vectorized unstructured data handling, governance/guardrails for enterprise AI, and tooling to build/manage autonomous agents.--#### Brief history-- Founded as a cloud CRM pioneer and public company in the early 2000s; growth strategy combined organic product development with major acquisitions to broaden capabilities. Major acquisitions include MuleSoft, Tableau and Slack (among others) to add integration, analytics and collaboration into the Salesforce portfolio.-""".strip(),- ),- # Case: SaaS, new- EvalCase(- input=(- "Artificial Societies",- EventTaxonomyItem(property="$host", sample_values=["app.societies.io"], sample_count=1),- ),- expected="""-__Here's what I found on societies.io (Artificial Societies):__--Artificial Societies (societies.io / app.societies.io) is a SaaS platform that builds AI-driven “artificial societies” (collections of AI personas and a social‑network model) so users can run rapid simulations to test content, messaging, product ideas and campaigns before launching them in the real world.--#### Product features-- Create Any Society: build target audiences in plain English or generate a personal society from your actual social media interactions.-- Rapid experiments: run multi-agent simulations in minutes to see reactions, spread, and engagement.-- Variant generation & automatic A/B testing: the product writes and tests multiple message variants (using your tone) alongside the original.-- Insights & forecasting: numeric scores, comments, summaries and a conversational intelligence ("Amos") for interpreting results.-- Persona & network modelling: a large persona database and social‑network graph used to model influence and information spread; simulations use many LLM calls and token budgets to represent individual and collective behavior.-- Contexts supported: social posts, emails, ads, headlines and other communication contexts.-(Primary source: product site).--#### User / customer segments-- Individual creators, founders and B2B marketers testing LinkedIn and other social content.-- Product and growth teams validating messaging, features and launches.-- PR, communications and content teams testing narratives and headlines.-- Agencies and market‑research buyers looking for faster/cheaper audience experiments.-- Enterprise customers requiring custom audiences, API and CRM/data integrations.-(Descriptions and customer examples from the site and launch pages).--#### Business model (pricing & monetization)-- Freemium + credits: a Free tier with starter simulation credits (three) to try the product.-- Pro subscription: listed at $55/month (monthly) or $40/month billed annually (site shows both monthly and annual pricing blocks). Pro unlocks unlimited societies and unlimited simulation credits.-- Enterprise: custom pricing for bespoke audience builds, API access, integrations and dedicated account management.-- Credits consumption: simulations and variant regenerations consume credits (Pro users have unlimited credits).-(Official pricing and FAQ on the site).--#### Technical details-- Primary domains / entry points: https://societies.io (marketing/docs) and https://app.societies.io (app / sign-up flow).-- API & integrations: enterprise offerings advertise API access and CRM/data integration capabilities.-- Underlying approach: persona creation from individual-level public data, social network graph construction, multi-agent LLM simulations (hundreds of LLM calls / millions of tokens per run are referenced).-- Product names / components referenced publicly: Reach (LinkedIn audience simulation), Amos (social intelligence engine).-(Information from the product site and related launch materials).--#### Brief history-- Founded in 2024 by James He and Patrick Sharpe; accepted to Y Combinator (W25 / Winter 2025).-- Early product launches included demos and "Reach" (simulating LinkedIn audiences); public launch activity appeared on Product Hunt in March 2025.-- Funding: reported combined pre‑seed and seed rounds (coverage cites roughly €4.5M / ~$5.3M total), with the seed led by Point72 Ventures and participation from Kindred Capital, Y Combinator and various angels / investors.-- Traction claims on the site and press: persona database size and platform usage metrics (persona database >1,000,000; thousands of users and many tens of thousands of simulations referenced on site and in press).-""".strip(),- ),- # Case: Mobile app, game- EvalCase(- input=(- "Supercell",- EventTaxonomyItem(- property="$app_namespace",- sample_values=["com.supercell.clashofclans"],- sample_count=1,- ),- ),- expected="""-__Here's what I found on Clash of Clans:__--Clash of Clans is a long-running, free-to-play mobile strategy game by Supercell where players build and upgrade a persistent village, train troops and Heroes, join/clash in Clans, and compete in multiplayer modes such as Clan Wars and seasonal competitive play.--#### Product features-- Core gameplay- - Village/base building (resource collectors, defenses, walls) and asymmetric base design.- - Attack phase where players assemble armies (troops, spells, siege machines) and deploy them against other players or single-player Goblin maps.-- Social & competitive systems- - Clans (up to 50 members), Clan Wars, Clan War Leagues, Clan Games, and Clan Capital content for coordinated play.- - Leaderboards, Legend League, friendly challenges, spectating and replays.-- Progression & meta features- - Town Hall progression unlocking new troops/buildings; Heroes (Barbarian King, Archer Queen, Grand Warden, Royal Champion, etc.) and Hero skins.- - Seasons and Battle Pass–style Gold Pass, special timed events, and periodic balance/feature updates.--#### User / Customer segments-- Mass market mobile players (casual to midcore) attracted to base-building and short-session competitive play.-- Social/competitive players who join clans, participate in Clan Wars and long-term progression.-- High-spending "whales" who purchase premium currency (gems), bundles and offers — a small share of users historically accounts for a large portion of revenue.--#### Business model-- Free-to-play with no mandatory ads; primary monetization via in-app purchases (gems, resource packs, Gold Pass, time-savers and timed offers). App Store listing shows multiple gem packs and Gold Pass options.-- Reliance on a small fraction of paying users (whales) plus recurring seasonal content and limited-time bundles to sustain high ARPU. Historical reporting places Clash of Clans among the highest-grossing mobile games with multi-billion cumulative revenue.--#### Technical details-- Primary bundle / package identifiers:- - iOS App Store ID: id529479190 (App Store listing shows pricing, requirements, and in‑app products).- - Android package name: com.supercell.clashofclans (widely referenced as the Play Store / APK package name).-- Official product pages / support paths:- - Supercell official game page: /en/games/clashofclans on supercell.com.- - App Store listing path: apps.apple.com/.../clash-of-clans/id529479190.- - Official support / help pages linked from the app and Supercell site (in‑game Help & Support and help.supercellsupport.com).--#### Brief history-- Launched on iOS August 2, 2012; Android release followed in October 2013. Rapid adoption and recurring updates turned it into one of Supercell’s flagship, decade-plus live-service titles.-- Long-term commercial success: sustained high grossing rank across app stores and cumulative revenues in the multi‑billion-dollar range; Supercell’s cell-based studio model and focus on persistent titles supported ongoing development and seasonal content.-""".strip(),- ),- # Case: No domain/bundle ID available (e.g. only localhost was present in the data)- EvalCase(- input=("Zapier", None), # No EventTaxonomyItem, but let's say the org name is well-known (Zapier)- expected=ENQUIRY_NO_EVENTS_INITIAL_MESSAGE, # Should fall back to enquiry flow INSTEAD OF scraping- ),- # Case: Non-existing product- EvalCase(- input=(- "Rotundify",- EventTaxonomyItem(property="$host", sample_values=["rotundify.xyz"], sample_count=1),- ),- expected=SCRAPING_TERMINATION_MESSAGE, # Should fall back to enquiry flow AFTER scraping- ),- # Case: Niche music app with multiple bundle IDs- EvalCase(- input=(- "Snare Music",- EventTaxonomyItem(- property="$app_namespace",- sample_values=["com.jackqcook.snare", "com.snaremusic.snare"],- sample_count=2,- ),- ),- expected="""-__Here's what I found on Snare (com.jackqcook.snare / com.snaremusic.snare):__--Snare (aka Snare Music) is a social music-discovery app that converts your listening habits into a feed, letting you follow others, react to their plays, post reviews, and engage over music.--#### Product features-- Connects with streaming platforms (Spotify / Apple Music) to import recent listening history.-- Live social feed: shows what friends are currently listening to (or recently listened) in a feed format.-- Reaction / engagement tools: users can react (likes, comments) to others' plays.-- Reviews / commentary: ability to write reviews on albums/tracks within the app.-- Discovery / recommendation features: suggestions (called “Snare Samples” or algorithmic picks) based on user activity.-- Social graph: following system (you follow friends / users) to tailor the feed.-- Basic version is free; updates indicate bug fixes, UI tweaks, algorithm improvements (e.g. “better algorithm for Snare Samples”)--#### User / customer segments-- Music enthusiasts who like to see what peers are listening to and discuss music.-- Early adopters of social / discovery tools in the music space.-- Playlist curators, tastemakers, influencers who want social reach or community feedback.-- Users dissatisfied with “cold” algorithmic recommendations and seeking more human-curated or socially filtered discovery.--#### Business model-- No public disclosures of paid features or pricing (as of available data).-- Likely freemium: core features free, with potential premium tier for enhanced discovery / analytics / filtering / no ads (though not confirmed).-- Monetization might include sponsorships, affiliate revenue (for streaming referrals), or future paid features for power users.-- No clear revenue metrics or public funding data found.--#### Technical details-- Website: snaremusic.app — “Discover, rate, and share your favorite albums. Connect with friends … join conversations about the tracks that move you.”-- App version history: latest version 1.1.0 for iOS at least; update notes mention bug fixes, minor improvements.-- Key flows / URL paths likely include:-- /login / connect (to Spotify / Apple Music)- - /feed (social feed of plays)- - /profile / settings- - /review / comment pages- - /discover / algorithmic suggestions-- Mobile first (iOS, possibly Android expectation in future).-- The app appears “new” / early stage (version numbering low, frequent iterative changes).--Brief history-- Developer / “Quentin Cook” is listed in app metadata.-- First public version around August 2025 (v1.0 in August).-- Update cycle is active (versions 1.0 → 1.0.6 → 1.1.0) with feature tweaks like better algorithms, UI changes.-- The domain / branding is “Snare — the app for music discovery.-""".strip(),- ),- ],- pytestconfig=pytestconfig,- )diff --git a/ee/hogai/eval/ci/eval_retention.py b/ee/hogai/eval/ci/eval_retention.pydeleted file mode 100644index 336901653782..000000000000--- a/ee/hogai/eval/ci/eval_retention.py+++ /dev/null@@ -1,203 +0,0 @@-import pytest--from braintrust import EvalCase--from posthog.schema import AssistantRetentionEventsNode, AssistantRetentionFilter, AssistantRetentionQuery, NodeKind--from ..base import MaxPublicEval-from ..scorers import PlanAndQueryOutput, PlanCorrectness, QueryAndPlanAlignment, QueryKindSelection, TimeRangeRelevancy---async def eval_retention(call_root_for_insight_generation, pytestconfig):- await MaxPublicEval(- experiment_name="retention",- task=call_root_for_insight_generation,- scores=[- QueryKindSelection(expected=NodeKind.RETENTION_QUERY),- PlanCorrectness(- query_kind=NodeKind.RETENTION_QUERY,- evaluation_criteria="""-1. A plan must define at least a returning event, and a target event, but it is not required to define any filters or breakdowns.-2. Compare returning events, target events, properties, and property values of 'expected plan' and 'output plan'. Do not penalize if the actual output does not include a timeframe unless specified in the 'expected plan'.-3. Check if the combination of events, properties, and property values in 'output plan' can answer the user's question according to the 'expected plan'.-4. If 'expected plan' contains a breakdown, check if 'output plan' contains a similar breakdown, and heavily penalize if the breakdown is not present or different.-5. If 'expected plan' contains specific period settings (e.g., daily, weekly, monthly), check if 'output plan' contains the same period settings, and penalize if different.-6. Heavily penalize if the 'output plan' contains any excessive output not present in the 'expected plan'. For example, the `is set` operator in filters should not be used unless the user explicitly asks for it.-""".strip(),- ),- QueryAndPlanAlignment(- query_kind=NodeKind.RETENTION_QUERY,- query_model=AssistantRetentionQuery,- evaluation_criteria="""-1. Returning event alignment: Verify that the returning event in `retentionFilter.returningEntity.name` exactly matches the returning event specified in the plan.-2. Target event alignment: Verify that the target event in `retentionFilter.targetEntity.name` exactly matches the target event specified in the plan.-3. Period configuration: Ensure the retention period in `retentionFilter.period` matches what's specified in the plan:- - "Day" for daily retention- - "Week" for weekly retention- - "Month" for monthly retention- - Default to "Week" when not specified in the plan-4. Total intervals: Verify that `retentionFilter.totalIntervals` is set appropriately based on the period:- - For daily: typically 14 intervals (14 days)- - For weekly: typically 11 intervals (11 weeks)- - For monthly: typically 11 intervals (11 months)- - Should align with date range when specified in the plan-5. Property filters on returning entity: Check that property filters from the plan are correctly implemented on the returning event:- - Property names, values, and operators must match exactly- - Filter types (event, person, group) must be correct- - Properties should be applied to `returningEntity.properties` when specified for the returning event-6. Property filters on target entity: Check that property filters from the plan are correctly implemented on the target event:- - Property names, values, and operators must match exactly- - Filter types (event, person, group) must be correct- - Properties should be applied to `targetEntity.properties` when specified for the target event-7. Date range alignment: Verify that the date range matches the period and intervals:- - Daily retention: date_from should be "-{totalIntervals}d"- - Weekly retention: date_from should be "-{totalIntervals}w"- - Monthly retention: date_from should be "-{totalIntervals}M"- - Custom time periods from plan should be respected-8. Breakdown limitations: Note that retention queries currently don't support breakdown filters in the schema, so breakdown mentions in the plan cannot be fully implemented (this should not be heavily penalized as it's a schema limitation).-9. Missing implementation: Heavily penalize when key plan elements are missing (e.g., wrong events, incorrect period, missing property filters on correct entities).-10. Unnecessary fields: Penalize inclusion of fields not mentioned in the plan or that don't align with the retention intent.-""".strip(),- ),- TimeRangeRelevancy(query_kind=NodeKind.RETENTION_QUERY),- ],- data=[- EvalCase(- input="Show user retention",- expected=PlanAndQueryOutput(- plan="""-Activation:-- event: $pageview--Retention:-- event: $pageview-""",- query=AssistantRetentionQuery(- dateRange={"date_from": "-11w", "date_to": None},- filterTestAccounts=True,- retentionFilter=AssistantRetentionFilter(- period="Week",- totalIntervals=11,- returningEntity=AssistantRetentionEventsNode(id="$pageview"),- targetEntity=AssistantRetentionEventsNode(id="$pageview"),- ),- ),- ),- ),- EvalCase(- input="Show monthly retention for users who sign up and then come back to view a dashboard",- expected=PlanAndQueryOutput(- plan="""-Activation:-- event: signed_up--Retention:-- event: viewed_dashboard-""",- query=AssistantRetentionQuery(- dateRange={"date_from": "-11M", "date_to": None},- filterTestAccounts=True,- retentionFilter=AssistantRetentionFilter(- period="Month",- totalIntervals=11,- returningEntity=AssistantRetentionEventsNode(id="signed_up"),- targetEntity=AssistantRetentionEventsNode(id="viewed_dashboard"),- ),- ),- ),- ),- EvalCase(- input="daily retention for Chrome users who sign up and then make a purchase",- expected=PlanAndQueryOutput(- plan="""-Activation:-- event: signed_up--Retention:-- event: purchased--Filters:- - property filter 1:- - entity: event- - property name: $browser- - property type: String- - operator: equals- - property value: Chrome-""",- query=AssistantRetentionQuery(- dateRange={"date_from": "-14d", "date_to": None},- filterTestAccounts=True,- retentionFilter=AssistantRetentionFilter(- period="Day",- totalIntervals=14,- returningEntity=AssistantRetentionEventsNode(- id="signed_up",- properties=[- {- "key": "$browser",- "value": "Chrome",- "operator": "exact",- "type": "event",- },- ],- ),- targetEntity=AssistantRetentionEventsNode(id="purchased"),- ),- ),- ),- ),- EvalCase(- input="weekly retention breakdown by browser for users who sign up and then make a purchase in the last 3 months",- # Tricky one, as AssistantRetentionQuery doesn't support `breakdownFilter` as of 2025-05-22!- expected=PlanAndQueryOutput(- plan="""-Activation:-- event: signed_up--Retention:-- event: purchased--Breakdown by:- - entity: event- - property name: $browser--Time period: last 3 months-""",- query=AssistantRetentionQuery(- dateRange={"date_from": "-3m", "date_to": None},- filterTestAccounts=True,- retentionFilter=AssistantRetentionFilter(- period="Week",- totalIntervals=12,- returningEntity=AssistantRetentionEventsNode(id="signed_up"),- targetEntity=AssistantRetentionEventsNode(id="purchased"),- ),- ),- ),- ),- EvalCase(- input="what's the retention for users who view the pricing page and then upgrade their plan?",- expected=PlanAndQueryOutput(- plan="""-Activation:-- event: viewed_pricing_page--Retention:-- event: upgraded_plan-""",- query=AssistantRetentionQuery(- dateRange={"date_from": "-11w", "date_to": None},- filterTestAccounts=True,- retentionFilter=AssistantRetentionFilter(- period="Week",- totalIntervals=11,- returningEntity=AssistantRetentionEventsNode(id="viewed_pricing_page"),- targetEntity=AssistantRetentionEventsNode(id="upgraded_plan"),- ),- ),- ),- ),- ],- pytestconfig=pytestconfig,- )diff --git a/ee/hogai/eval/ci/eval_root.py b/ee/hogai/eval/ci/eval_root.pydeleted file mode 100644index 123fc7fb4e61..000000000000--- a/ee/hogai/eval/ci/eval_root.py+++ /dev/null@@ -1,224 +0,0 @@-import json--import pytest--from braintrust import EvalCase--from posthog.schema import AssistantMessage, AssistantToolCall, AssistantToolCallMessage, HumanMessage--from products.posthog_ai.backend.models.assistant import Conversation--from ee.hogai.chat_agent import AssistantGraph-from ee.hogai.django_checkpoint.checkpointer import DjangoCheckpointer-from ee.hogai.utils.types import AssistantMessageUnion, AssistantNodeName, AssistantState--from ..base import MaxPublicEval-from ..scorers import ToolRelevance---def call_root(demo_org_team_user):- graph = (- AssistantGraph(demo_org_team_user[1], demo_org_team_user[2])- .add_edge(AssistantNodeName.START, AssistantNodeName.ROOT)- .add_root(lambda state: AssistantNodeName.END)- # TRICKY: We need to set a checkpointer here because async tests create a new event loop.- .compile(checkpointer=DjangoCheckpointer())- )-- async def callable(messages: str | list[AssistantMessageUnion]) -> AssistantMessage:- conversation = await Conversation.objects.acreate(team=demo_org_team_user[1], user=demo_org_team_user[2])- initial_state = AssistantState(- messages=[HumanMessage(content=messages)] if isinstance(messages, str) else messages- )- raw_state = await graph.ainvoke(initial_state, {"configurable": {"thread_id": conversation.id}})- state = AssistantState.model_validate(raw_state)- assert isinstance(state.messages[-1], AssistantMessage)- return state.messages[-1]-- return callable---async def eval_root(call_root, pytestconfig):- await MaxPublicEval(- experiment_name="root",- task=call_root,- scores=[ToolRelevance(semantic_similarity_args={"query_description"})],- data=[- EvalCase(- input="Create an SQL insight to calculate active users recently",- expected=AssistantToolCall(- id="1",- name="create_insight",- args={"query_description": "Calculate the number of active users recently"},- ),- ),- EvalCase(- input="Write SQL to calculate active users recently",- expected=AssistantToolCall(- id="2",- name="create_insight",- args={"query_description": "Calculate the number of active users recently"},- ),- ),- # Should propagate the dates from the previous insight request- EvalCase(- input=[- HumanMessage(content="what is the trend of pageviews ytd 2025"),- AssistantMessage(- content="",- tool_calls=[- AssistantToolCall(- id="call_vaTlpWMBgGyvYVIMfj1ecW8F",- name="create_insight",- args={- "query_description": "Trend of pageviews year-to-date 2025",- },- )- ],- ),- AssistantToolCallMessage(- tool_call_id="call_vaTlpWMBgGyvYVIMfj1ecW8F",- content=json.dumps(- {- "query_description": "Here is the results table of the TrendsQuery I created to answer your latest question: ``` Date|$pageview 2025-01-01|6982 2025-02-01|9953 2025-03-01|7507 2025-04-01|795 2025-05-01|3 ``` The current date and time is 2025-05-01 09:07:56 UTC, which is 2025-05-01 09:07:56 in this project's timezone (UTC). It's expected that the data point for the current period can have a drop in value, as data collection is still ongoing for it. Do not point this out.",- }- ),- ),- AssistantMessage(- content="Here's the trend of pageviews for the year-to-date 2025: - January: 6,982 pageviews - February: 9,953 pageviews - March: 7,507 pageviews - April: 795 pageviews - May (so far): 3 pageviews Looks like February was a busy month! If you have any more questions or need further insights, just let me know!"- ),- HumanMessage(content="list the users"),- ],- expected=AssistantToolCall(- id="2",- name="create_insight",- args={- "query_description": "List all users who have completed a page view in year-to-date 2025.",- },- ),- ),- # When the company name appears in the query results, it should NOT confuse the agent and it should still generate a new insight- EvalCase(- input=[- HumanMessage(content="List all user names who have completed a page view YTD"),- AssistantMessage(- content="",- tool_calls=[- AssistantToolCall(- id="call_XdLOyLrHbjoBBACDCZd8WyNS",- name="create_insight",- args={- "query_description": "List all user names who have completed a page view Year-To-Date (YTD).",- },- )- ],- ),- AssistantToolCallMessage(- tool_call_id="call_XdLOyLrHbjoBBACDCZd8WyNS",- content=json.dumps(- {- "query_description": 'You\'ll be given a JSON object with the results of a query.\n\nHere is the generated ClickHouse SQL query used to retrieve the results:\n\n```\nSELECT DISTINCT person.properties.name AS user_name\nFROM events\nWHERE event = \'$pageview\'\n AND toYear(timestamp) = toYear(now())\n```\n\nYou\'ll be given a JSON object with the results of a query.\n\nHere is the results table of the HogQLQuery I created to answer your latest question:\n\n```\n[[null],["Mario Bridges"],["Alexander Dickson"],["YCombinator"],["Andrea Dickson"]]\n```\n\nThe current date and time is 2025-05-01 10:12:06 UTC, which is 2025-05-01 10:12:06 in this project\'s timezone (UTC).\nIt\'s expected that the data point for the current period can have a drop in value, as data collection is still ongoing for it. Do not point this out.',- }- ),- ),- AssistantMessage(- content="Here's the list of user names who have completed a page view Year-To-Date (YTD):\n\n- Mario Bridges\n- Alexander Dickson\n- YCombinator\n- Andrea Dickson\n\nThat's quite a crowd! If you need anything else, just let me know!"- ),- HumanMessage(content="give me a list of the companies only associated with the users"),- ],- expected=AssistantToolCall(- id="2",- name="create_insight",- args={- "query_description": "List all companies who have completed a page view Year-To-Date (YTD).",- },- ),- ),- # Must reuse the previous data- EvalCase(- input=[- HumanMessage(content="List all user names who have completed a page view YTD"),- AssistantMessage(- content="",- tool_calls=[- AssistantToolCall(- id="call_XdLOyLrHbjoBBACDCZd8WyNS",- name="create_insight",- args={- "query_description": "List all user names who have completed a page view Year-To-Date (YTD).",- },- )- ],- ),- AssistantToolCallMessage(- tool_call_id="call_XdLOyLrHbjoBBACDCZd8WyNS",- content=json.dumps(- {- "query_description": 'You\'ll be given a JSON object with the results of a query.\n\nHere is the generated ClickHouse SQL query used to retrieve the results:\n\n```\nSELECT DISTINCT person.properties.name AS user_name\nFROM events\nWHERE event = \'$pageview\'\n AND toYear(timestamp) = toYear(now())\n```\n\nYou\'ll be given a JSON object with the results of a query.\n\nHere is the results table of the HogQLQuery I created to answer your latest question:\n\n```\n[[null],["Mario Bridges"],["Alexander Dickson"],["YCombinator"],["Andrea Dickson"]]\n```\n\nThe current date and time is 2025-05-01 10:12:06 UTC, which is 2025-05-01 10:12:06 in this project\'s timezone (UTC).\nIt\'s expected that the data point for the current period can have a drop in value, as data collection is still ongoing for it. Do not point this out.',- }- ),- ),- AssistantMessage(- content="Here's the list of user names who have completed a page view Year-To-Date (YTD):\n\n- Mario Bridges\n- Alexander Dickson\n- YCombinator\n- Andrea Dickson\n\nThat's quite a crowd! If you need anything else, just let me know!"- ),- HumanMessage(content="List all user names who have completed a page view YTD"),- ],- expected=None,- ),- # Ensure calls insights, not documentation- EvalCase(- input="Show me all events where the default $browser property equals Chrome",- expected=AssistantToolCall(- name="create_insight",- args={- "query_description": "Show all events where the $browser property equals Chrome",- },- id="call_insight_default_props_1",- ),- ),- EvalCase(- input="How many unique users have the default $device_type property as mobile?",- expected=AssistantToolCall(- name="create_insight",- args={- "query_description": "Count unique users who have the $device_type property set to mobile",- },- id="call_insight_default_props_2",- ),- ),- EvalCase(- input="Give me the signup to purchase conversion rate for the dates between 8 Jul and 9 Sep",- expected=AssistantToolCall(- name="create_insight",- args={- "query_description": "Calculate the signup to purchase conversion rate for dates between July 8 and September 9",- },- id="call_specific_conversion_rate",- ),- ),- EvalCase(- input="Show me daily active users for the past month",- expected=AssistantToolCall(- name="create_insight",- args={- "query_description": "Daily active users for the past month",- },- id="call_dau_past_month",- ),- ),- # Some models already know about PostHog's events, but they must not rely on this knowledge and use the read_taxonomy tool instead.- EvalCase(- input="create a pageview trends broken down by countries",- expected=AssistantToolCall(- name="read_taxonomy",- args={- "query": {"kind": "events"},- },- id="call_read_events",- ),- ),- ],- pytestconfig=pytestconfig,- )diff --git a/ee/hogai/eval/ci/eval_root_documentation.py b/ee/hogai/eval/ci/eval_root_documentation.pydeleted file mode 100644index 19f3ff60aaf9..000000000000--- a/ee/hogai/eval/ci/eval_root_documentation.py+++ /dev/null@@ -1,340 +0,0 @@-import pytest--from braintrust import EvalCase--from posthog.schema import AssistantMessage, AssistantToolCall, HumanMessage--from products.posthog_ai.backend.models.assistant import Conversation--from ee.hogai.chat_agent import AssistantGraph-from ee.hogai.django_checkpoint.checkpointer import DjangoCheckpointer-from ee.hogai.utils.types import AssistantNodeName, AssistantState--from ..base import MaxPublicEval-from ..scorers import ToolRelevance---def call_root(demo_org_team_user):- graph = (- AssistantGraph(demo_org_team_user[1], demo_org_team_user[2])- .add_edge(AssistantNodeName.START, AssistantNodeName.ROOT)- .add_root(router=lambda state: AssistantNodeName.END)- # TRICKY: We need to set a checkpointer here because async tests create a new event loop.- .compile(checkpointer=DjangoCheckpointer())- )-- async def callable(messages):- conversation = await Conversation.objects.acreate(team=demo_org_team_user[1], user=demo_org_team_user[2])- initial_state = AssistantState(- messages=[HumanMessage(content=messages)] if isinstance(messages, str) else messages- )- raw_state = await graph.ainvoke(initial_state, {"configurable": {"thread_id": conversation.id}})- state = AssistantState.model_validate(raw_state)- assert isinstance(state.messages[-1], AssistantMessage)- return state.messages[-1]-- return callable---async def eval_root_documentation(call_root, pytestconfig):- await MaxPublicEval(- experiment_name="root_documentation",- task=call_root,- scores=[ToolRelevance(semantic_similarity_args={"query"})],- data=[- # Documentation search when the user asks about SDK integration or instrumentation- EvalCase(- input="import posthog from 'posthog-js' posthog.captureException(error) in my react app i manually capture exceptions but i don't see them on the dashboard",- expected=AssistantToolCall(- name="search",- args={"kind": "docs", "query": "posthog-js captureException not showing exceptions on dashboard"},- id="call_oejkj9HpAcIVAqTjxaXaofyA",- ),- ),- # Basic PostHog product questions- EvalCase(- input="How do I set up event tracking in PostHog?",- expected=AssistantToolCall(- name="search",- args={"kind": "docs", "query": "set up event tracking"},- id="call_doc_search_1",- ),- ),- EvalCase(- input="What is a cohort in PostHog and how do I create one?",- expected=AssistantToolCall(- name="search",- args={"kind": "docs", "query": "cohort creation"},- id="call_doc_search_2",- ),- ),- EvalCase(- input="How does PostHog's session recording work?",- expected=AssistantToolCall(- name="search",- args={"kind": "docs", "query": "session recording"},- id="call_doc_search_3",- ),- ),- EvalCase(- input="Can you explain PostHog's feature flags functionality?",- expected=AssistantToolCall(- name="search",- args={"kind": "docs", "query": "feature flags functionality"},- id="call_doc_search_4",- ),- ),- # SDK and integration questions- EvalCase(- input="How do I install the PostHog SDK for Python?",- expected=AssistantToolCall(- name="search",- args={"kind": "docs", "query": "install PostHog SDK for Python"},- id="call_doc_search_5",- ),- ),- EvalCase(- input="posthog js sdk not working in my next.js app",- expected=AssistantToolCall(- name="search",- args={"kind": "docs", "query": "posthog js sdk next.js troubleshooting"},- id="call_doc_search_6",- ),- ),- EvalCase(- input="How to track custom events with posthog react library",- expected=AssistantToolCall(- name="search",- args={"kind": "docs", "query": "track custom events posthog react"},- id="call_doc_search_7",- ),- ),- EvalCase(- input="posthog.capture() vs posthog.track() whats the difference",- expected=AssistantToolCall(- name="search",- args={"kind": "docs", "query": "difference between capture and track"},- id="call_doc_search_8",- ),- ),- # Feature-specific questions- EvalCase(- input="How do I create a funnel analysis in PostHog?",- expected=AssistantToolCall(- name="search",- args={"kind": "docs", "query": "create funnel analysis"},- id="call_doc_search_9",- ),- ),- EvalCase(- input="What's the difference between trends and insights in PostHog?",- expected=AssistantToolCall(- name="search",- args={"kind": "docs", "query": "difference between trends and insights"},- id="call_doc_search_10",- ),- ),- EvalCase(- input="How do I set up A/B testing with PostHog feature flags?",- expected=AssistantToolCall(- name="search",- args={"kind": "docs", "query": "A/B testing with feature flags"},- id="call_doc_search_11",- ),- ),- EvalCase(- input="posthog dashboard widgets how to customize them",- expected=AssistantToolCall(- name="search",- args={"kind": "docs", "query": "customize dashboard widgets"},- id="call_doc_search_12",- ),- ),- # Terse/messy user input- EvalCase(- input="ph not tracking events???",- expected=AssistantToolCall(- name="search",- args={"kind": "docs", "query": "events not tracking troubleshooting"},- id="call_doc_search_13",- ),- ),- EvalCase(- input="help feature flag setup",- expected=AssistantToolCall(- name="search",- args={"kind": "docs", "query": "feature flag setup"},- id="call_doc_search_14",- ),- ),- EvalCase(- input="sdk integration issues react native",- expected=AssistantToolCall(- name="search",- args={"kind": "docs", "query": "react native SDK integration troubleshooting"},- id="call_doc_search_16",- ),- ),- EvalCase(- input="cant see recordings",- expected=AssistantToolCall(- name="search",- args={"kind": "docs", "query": "session recordings not visible troubleshooting"},- id="call_doc_search_17",- ),- ),- # Troubleshooting and debugging- EvalCase(- input="My PostHog events aren't showing up in the dashboard, what could be wrong?",- expected=AssistantToolCall(- name="search",- args={"kind": "docs", "query": "events not showing up in dashboard troubleshooting"},- id="call_doc_search_18",- ),- ),- EvalCase(- input="Session recordings are blank, how do I fix this?",- expected=AssistantToolCall(- name="search",- args={"kind": "docs", "query": "blank session recordings fix"},- id="call_doc_search_19",- ),- ),- EvalCase(- input="PostHog feature flags not working in production environment",- expected=AssistantToolCall(- name="search",- args={"kind": "docs", "query": "feature flags not working in production"},- id="call_doc_search_20",- ),- ),- EvalCase(- input="Why are my PostHog cohorts not updating automatically?",- expected=AssistantToolCall(- name="search",- args={"kind": "docs", "query": "cohorts not updating automatically"},- id="call_doc_search_21",- ),- ),- # Configuration and setup questions- EvalCase(- input="How do I configure PostHog for GDPR compliance?",- expected=AssistantToolCall(- name="search",- args={"kind": "docs", "query": "GDPR compliance configuration"},- id="call_doc_search_22",- ),- ),- EvalCase(- input="What are the different PostHog deployment options?",- expected=AssistantToolCall(- name="search",- args={"kind": "docs", "query": "deployment options"},- id="call_doc_search_23",- ),- ),- EvalCase(- input="posthog self hosted vs cloud which one should i choose",- expected=AssistantToolCall(- name="search",- args={"kind": "docs", "query": "self hosted vs cloud comparison"},- id="call_doc_search_24",- ),- ),- # API and integration questions- EvalCase(- input="How do I use PostHog's REST API to query events?",- expected=AssistantToolCall(- name="search",- args={"kind": "docs", "query": "REST API query events"},- id="call_doc_search_25",- ),- ),- EvalCase(- input="PostHog webhook integration with Slack how to set up",- expected=AssistantToolCall(- name="search",- args={"kind": "docs", "query": "webhook Slack integration setup"},- id="call_doc_search_26",- ),- ),- EvalCase(- input="can posthog integrate with segment?",- expected=AssistantToolCall(- name="search",- args={"kind": "docs", "query": "segment integration"},- id="call_doc_search_27",- ),- ),- # Performance and limits- EvalCase(- input="What are PostHog's rate limits for event ingestion?",- expected=AssistantToolCall(- name="search",- args={"kind": "docs", "query": "rate limits event ingestion"},- id="call_doc_search_28",- ),- ),- EvalCase(- input="my posthog is slow how to optimize performance",- expected=AssistantToolCall(- name="search",- args={"kind": "docs", "query": "optimize performance"},- id="call_doc_search_29",- ),- ),- # Mobile and platform-specific- EvalCase(- input="PostHog iOS SDK setup guide",- expected=AssistantToolCall(- name="search",- args={"kind": "docs", "query": "iOS SDK setup"},- id="call_doc_search_30",- ),- ),- EvalCase(- input="android posthog tracking not working",- expected=AssistantToolCall(- name="search",- args={"kind": "docs", "query": "android tracking not working troubleshooting"},- id="call_doc_search_31",- ),- ),- EvalCase(- input="flutter posthog plugin how to use",- expected=AssistantToolCall(- name="search",- args={"kind": "docs", "query": "flutter plugin usage"},- id="call_doc_search_32",- ),- ),- # Ensure calls docs, not insights- EvalCase(- input="Can I see which browser or device type a user is using from the default event properties?",- expected=AssistantToolCall(- name="search",- args={"kind": "docs", "query": "default event properties browser device type"},- id="call_doc_search_34",- ),- ),- EvalCase(- input="What geographic information does PostHog automatically capture about my users?",- expected=AssistantToolCall(- name="search",- args={"kind": "docs", "query": "automatic geographic information capture"},- id="call_doc_search_35",- ),- ),- EvalCase(- input="How do I delete events from PostHog?",- expected=AssistantToolCall(- name="search",- args={"kind": "docs", "query": "delete events from PostHog"},- id="call_doc_search_36",- ),- ),- ],- pytestconfig=pytestconfig,- )diff --git a/ee/hogai/eval/ci/eval_root_entity_search.py b/ee/hogai/eval/ci/eval_root_entity_search.pydeleted file mode 100644index bc02b07517d9..000000000000--- a/ee/hogai/eval/ci/eval_root_entity_search.py+++ /dev/null@@ -1,94 +0,0 @@-import pytest--from braintrust import EvalCase--from posthog.schema import AssistantMessage, AssistantToolCall, HumanMessage--from products.posthog_ai.backend.models.assistant import Conversation--from ee.hogai.chat_agent import AssistantGraph-from ee.hogai.django_checkpoint.checkpointer import DjangoCheckpointer-from ee.hogai.utils.types import AssistantNodeName, AssistantState--from ..base import MaxPublicEval-from ..scorers import ToolRelevance---def call_root(demo_org_team_user):- graph = (- AssistantGraph(demo_org_team_user[1], demo_org_team_user[2])- .add_edge(AssistantNodeName.START, AssistantNodeName.ROOT)- .add_root(router=lambda state: AssistantNodeName.END)- # TRICKY: We need to set a checkpointer here because async tests create a new event loop.- .compile(checkpointer=DjangoCheckpointer())- )-- async def callable(messages):- conversation = await Conversation.objects.acreate(team=demo_org_team_user[1], user=demo_org_team_user[2])- initial_state = AssistantState(- messages=[HumanMessage(content=messages)] if isinstance(messages, str) else messages- )- raw_state = await graph.ainvoke(initial_state, {"configurable": {"thread_id": conversation.id}})- state = AssistantState.model_validate(raw_state)- assert isinstance(state.messages[-1], AssistantMessage)- return state.messages[-1]-- return callable---async def eval_root_entity_search(call_root, pytestconfig):- await MaxPublicEval(- experiment_name="root_entity_search",- task=call_root,- scores=[ToolRelevance(semantic_similarity_args={"query"})],- data=[- # Entity search- EvalCase(- input="Search for my dashboards about user engagement",- expected=AssistantToolCall(- name="search",- args={- "kind": "dashboards",- "query": "user engagement",- },- id="call_search_1",- ),- ),- EvalCase(- input="Search for my cohorts about mobile users",- expected=AssistantToolCall(- name="search",- args={- "kind": "cohorts",- "query": "mobile users",- },- id="call_search_3",- ),- ),- EvalCase(- input="Find my feature flags related to the new feature about batch export",- expected=AssistantToolCall(- name="search",- args={- "kind": "feature_flags",- "query": "batch export",- },- id="call_search_4",- ),- ),- EvalCase(- input="Search for everything that might be related to `revenue`",- expected=AssistantToolCall(- name="search",- args={- "kind": "all",- "query": "revenue",- },- id="call_search_5",- ),- ),- ],- pytestconfig=pytestconfig,- )diff --git a/ee/hogai/eval/ci/eval_root_style.py b/ee/hogai/eval/ci/eval_root_style.pydeleted file mode 100644index 7ec1de1686cc..000000000000--- a/ee/hogai/eval/ci/eval_root_style.py+++ /dev/null@@ -1,173 +0,0 @@-import pytest--from autoevals.llm import LLMClassifier-from braintrust import EvalCase--from posthog.schema import AssistantMessage, HumanMessage--from products.posthog_ai.backend.models.assistant import Conversation--from ee.hogai.chat_agent import AssistantGraph-from ee.hogai.utils.types import AssistantMessageUnion, AssistantNodeName, AssistantState--from ..base import MaxPublicEval-from .conftest import EVAL_USER_FULL_NAME---class StyleChecker(LLMClassifier):- """LLM-as-judge scorer for evaluating communication style."""-- def __init__(self, **kwargs):- super().__init__(- name="style_checker",- prompt_template="""-You are evaluating the communication style of PostHog's AI assistant. The assistant should be friendly and direct without corporate fluff, professional but not whimsical.--The assistant will be talking with a user named {{{user_name}}}.--Based on PostHog's style preferences, evaluate if this response matches their target tone:--<user_message>-{{{input}}}-</user_message>--<assistant_response>-{{{output.content}}}-</assistant_response>--Evaluate this response's style quality. Choose one:-- perfectly-professional-but-approachable: Perfect PostHog tone - direct, helpful, friendly but not fluffy, gets straight to the point.-- visibly-corporate: Visibly formal, uses hedge words like "unfortunately", lacks warmth and personality, uses overly apologetic language like "no worries". Uses the em-dash (—). Doesn't use natural contractions (like "I'll").-- visibly-whimsical: Visibly flowery, overly enthusiastic, cutesy language, or cringey humor. Forces hedgehog puns/facts without user prompt.-- visibly-fluffy: Uses redundant casual commentary, filler phrases like "Great question!", verbose language that doesn't add value to helping the user, overly casual language that doesn't add value ("I hear you", "You're absolutely right!", "Let's get this sorted out", "Thanks for reaching out", etc.).-- empty: No response--Focus specifically on tone and writing style, not content accuracy. BE EXTREMELY HARSH.-""".strip(),- choice_scores={- "perfectly-professional-but-approachable": 1.0,- "visibly-corporate": 0.0,- "visibly-whimsical": 0.0,- "visibly-fluffy": 0.0,- "empty": None,- },- model="gpt-4.1",- **kwargs,- )---def call_root(demo_org_team_user):- graph = (- AssistantGraph(demo_org_team_user[1], demo_org_team_user[2])- .add_edge(AssistantNodeName.START, AssistantNodeName.ROOT)- .add_root(lambda state: AssistantNodeName.END)- .compile()- )-- async def callable(messages: str | list[AssistantMessageUnion]) -> AssistantMessage:- conversation = await Conversation.objects.acreate(team=demo_org_team_user[1], user=demo_org_team_user[2])- initial_state = AssistantState(- messages=[HumanMessage(content=messages)] if isinstance(messages, str) else messages- )- raw_state = await graph.ainvoke(initial_state, {"configurable": {"thread_id": conversation.id}})- state = AssistantState.model_validate(raw_state)- assert isinstance(state.messages[-1], AssistantMessage)- return state.messages[-1]-- return callable---async def eval_root_style(call_root, pytestconfig):- await MaxPublicEval(- experiment_name="root_style",- task=call_root,- scores=[StyleChecker(user_name=EVAL_USER_FULL_NAME)],- data=[- EvalCase(- input="My conversion funnel shows 45% from signup to activation. Is this good?",- expected="Response should be friendly and direct, acknowledge the number, provide context without being overly enthusiastic",- ),- EvalCase(- input="I'm getting an error when trying to create a cohort analysis",- expected="Response should be helpful and direct, ask for specific error details without flowery language",- ),- EvalCase(- input="Can you explain what retention analysis does?",- expected="Response should be clear and informative without being whimsical or overly technical",- ),- EvalCase(- input="My dashboard isn't showing any data",- expected="Response should troubleshoot systematically without unnecessary politeness markers",- ),- EvalCase(- input="How do I track custom events in PostHog?",- expected="Response should be instructional and direct, offering to help further with casual language",- ),- EvalCase(- input="What's the difference between events and actions?",- expected="Response should explain clearly with appropriate technical depth",- ),- EvalCase(- input="I need to create a report for my team showing user engagement",- expected="Response should offer practical solutions with friendly but professional tone",- ),- EvalCase(- input="The data in my trends analysis looks wrong",- expected="Response should investigate the issue systematically without hedge words",- ),- EvalCase(- input="Can you help me set up a new dashboard?",- expected="Response should offer help directly with casual, helpful language",- ),- EvalCase(- input="I'm new to PostHog and don't know where to start",- expected="Response should be welcoming and guide step-by-step without overwhelming enthusiasm",- ),- # Stereotype avoidance tests- EvalCase(- input="Tell me a joke about data analysis",- expected="Response should avoid stereotypes about gender, nationality, race, or other demographics in any humor",- ),- EvalCase(- input="Can you make this analytics meeting more fun with a joke?",- expected="Response should avoid stereotypical jokes about any demographic groups or cultures",- ),- # Critical: Test cases that previously triggered problematic responses- EvalCase(- input="my posthog is slow how to optimize performance",- expected="Response should be direct and helpful, addressing performance optimization without fluffy language like 'I hear you' or unnecessary commentary",- ),- EvalCase(- input="ph not tracking events???",- expected="Response should get straight to troubleshooting tracking issues without fluffy preambles or verbose explanations",- ),- EvalCase(- input="posthog broken",- expected="Response should immediately focus on systematic troubleshooting without unnecessary casual commentary",- ),- EvalCase(- input="cant see recordings",- expected="Response should directly address session recording issues without fluffy language or verbose explanations",- ),- EvalCase(- input="help feature flag setup",- expected="Response should provide concise setup assistance without verbose preambles or overly casual language",- ),- # Test cases for various communication styles that should get direct responses- EvalCase(- input="sdk integration issues react native",- expected="Response should provide direct technical help without verbose preambles or fluffy language",- ),- EvalCase(- input="Why are my PostHog cohorts not updating automatically?",- expected="Response should directly explain cohort behavior without unnecessary casual commentary or verbose explanations",- ),- EvalCase(- input="PostHog feature flags not working in production environment",- expected="Response should get straight to troubleshooting production issues without fluffy language or verbose setup",- ),- ],- pytestconfig=pytestconfig,- )diff --git a/ee/hogai/eval/ci/eval_sql.py b/ee/hogai/eval/ci/eval_sql.pydeleted file mode 100644index 749b23c8bb2b..000000000000--- a/ee/hogai/eval/ci/eval_sql.py+++ /dev/null@@ -1,530 +0,0 @@-import pytest--from asgiref.sync import sync_to_async-from braintrust import EvalCase, Score-from braintrust_core.score import Scorer-from langchain_core.runnables import RunnableConfig--from posthog.schema import AgentMode, AssistantMessage, HumanMessage--from posthog.models import Team--from products.posthog_ai.backend.models.assistant import Conversation--from ee.hogai.chat_agent import AssistantGraph-from ee.hogai.django_checkpoint.checkpointer import DjangoCheckpointer-from ee.hogai.eval.scorers.sql import SQLSemanticsCorrectness, evaluate_sql_query-from ee.hogai.utils.types import AssistantNodeName, AssistantState--from ..base import MaxPublicEval---def _has_execute_sql_call(state: AssistantState) -> bool:- for msg in state.messages:- if isinstance(msg, AssistantMessage) and msg.tool_calls:- for tool_call in msg.tool_calls:- if tool_call.name == "execute_sql":- return True- return False---def _extract_sql_result(state: AssistantState) -> dict:- result: dict = {"tool_called": False, "query": None}- for msg in state.messages:- if isinstance(msg, AssistantMessage) and msg.tool_calls:- for tool_call in msg.tool_calls:- if tool_call.name == "execute_sql":- result["tool_called"] = True- result["query"] = tool_call.args.get("query")- return result---class ExecuteSQLToolCalled(Scorer):- """Binary scorer: did the agent call execute_sql?"""-- def _name(self):- return "execute_sql_tool_called"-- async def _run_eval_async(self, output, expected=None, **kwargs):- return self._evaluate(output)-- def _run_eval_sync(self, output, expected=None, **kwargs):- return self._evaluate(output)-- def _evaluate(self, output) -> Score:- called = output.get("tool_called", False) if output else False- return Score(name=self._name(), score=1.0 if called else 0.0)---class HogQLQuerySyntaxCorrectness(Scorer):- def _name(self):- return "sql_syntax_correctness"-- async def _run_eval_async(self, output, *args, **kwargs):- return await sync_to_async(self._evaluate)(output)-- def _run_eval_sync(self, output, *args, **kwargs):- return self._evaluate(output)-- def _evaluate(self, output) -> Score:- team = Team.objects.latest("created_at")- query = output.get("query") if output else None- return evaluate_sql_query(self._name(), query, team)---class CISQLSemanticsCorrectness(SQLSemanticsCorrectness):- """Wraps the shared scorer to extract `query` from the CI eval output dict."""-- async def _run_eval_async(self, output, expected=None, database_schema=None, **kwargs):- query = output.get("query") if output else None- return await super()._run_eval_async(query, expected, database_schema=database_schema, **kwargs)-- def _run_eval_sync(self, output, expected=None, database_schema=None, **kwargs):- query = output.get("query") if output else None- return super()._run_eval_sync(query, expected, database_schema=database_schema, **kwargs)---def call_agent_for_sql(demo_org_team_user):- _, team, user = demo_org_team_user- graph = (- AssistantGraph(team, user)- .add_edge(AssistantNodeName.START, AssistantNodeName.ROOT)- .add_root()- .compile(checkpointer=DjangoCheckpointer())- )-- async def callable(query_with_extra_context: str | tuple[str, str]) -> dict:- query = query_with_extra_context[0] if isinstance(query_with_extra_context, tuple) else query_with_extra_context- conversation = await Conversation.objects.acreate(team=team, user=user)- initial_state = AssistantState(- messages=[HumanMessage(content=query)],- agent_mode=AgentMode.SQL,- )- config = RunnableConfig(configurable={"thread_id": conversation.id})- raw_state = await graph.ainvoke(initial_state, config)- state = AssistantState.model_validate(raw_state)-- if isinstance(query_with_extra_context, tuple) and not _has_execute_sql_call(state):- state.messages = [*state.messages, HumanMessage(content=query_with_extra_context[1])]- state.graph_status = "resumed"- raw_state = await graph.ainvoke(state, config)- state = AssistantState.model_validate(raw_state)-- return _extract_sql_result(state)-- yield callable---async def eval_sql(call_agent_for_sql, pytestconfig):- all_cases: list[EvalCase] = [- ### Straightforward breakdowns- EvalCase(- input="Count pageviews by browser",- expected="""-SELECT properties.$browser as browser, count(*) as pageview_count-FROM events-WHERE event = '$pageview'-GROUP BY browser-ORDER BY pageview_count DESC-LIMIT 100-""",- ),- EvalCase(- input="What are the top 10 countries by number of users in the last 7 days?",- expected="""-SELECT properties.$geoip_country_name as country, count(distinct person_id) as user_count-FROM events-WHERE timestamp >= now() - interval 7 day-GROUP BY country-ORDER BY user_count DESC-LIMIT 10-""",- ),- ### Session duration- EvalCase(- input="Show me the average session duration by day of week",- expected="""-SELECT toDayOfWeek(timestamp) as day_of_week,- avg(session.$session_duration) as avg_session_duration-FROM events-GROUP BY day_of_week-ORDER BY day_of_week-""",- ),- EvalCase(- input="What percentage of users who visited the pricing page made a purchase in this month?",- expected="""-WITH pricing_visitors AS (- SELECT distinct person_id- FROM events- WHERE event = 'viewed_pricing_page'- AND date_trunc('month', timestamp) = date_trunc('month', now())-),-purchasers AS (- SELECT distinct person_id- FROM events- WHERE event = 'purchase'- AND date_trunc('month', timestamp) = date_trunc('month', now())-)-SELECT- count(DISTINCT pv.person_id) AS pricing_visitors_count,- count(DISTINCT p.person_id) AS purchasers_count,- (count(DISTINCT p.person_id) * 100.0 / nullIf(count(DISTINCT pv.person_id), 0)) AS conversion_percentage-FROM pricing_visitors pv-LEFT JOIN purchasers p ON pv.person_id = p.person_id-""",- ),- ### Conversion- EvalCase(- input="How many users completed the onboarding flow (viewed welcome page, created profile, and completed tutorial) in sequence?",- expected="""-WITH occurences AS (- SELECT- person_id,- event,- timestamp,- ROW_NUMBER() OVER (PARTITION BY person_id, event ORDER BY timestamp) as occurrence- FROM events- WHERE event IN ('viewed_welcome_page', 'created_profile', 'completed_tutorial')-),-user_funnel AS (- SELECT- person_id,- maxIf(timestamp, event = 'viewed_welcome_page') as welcome_time,- maxIf(timestamp, event = 'created_profile') as profile_time,- maxIf(timestamp, event = 'completed_tutorial') as tutorial_time- FROM occurences- WHERE occurrence = 1- GROUP BY person_id- HAVING count(distinct event) = 3-)-SELECT count(*) as users_completed_onboarding-FROM user_funnel-WHERE welcome_time < profile_time AND profile_time < tutorial_time-""",- ),- EvalCase(- input="How many users completed the onboarding flow (viewed welcome page, created profile, and completed tutorial) regardless of sequence?",- expected="""-WITH occurences AS (- SELECT person_id, event- FROM events- WHERE event IN ('viewed_welcome_page', 'created_profile', 'completed_tutorial')-),-user_funnel AS (- SELECT- person_id,- count(distinct event) as event_count- FROM occurences- GROUP BY person_id-)-SELECT count(*) as users_completed_onboarding-FROM user_funnel-WHERE event_count = 3-""",- ),- ### Property math- EvalCase(- input="The number of distinct values of property $browser seen in each of the last 14 days",- expected="""-SELECT date_trunc('day', timestamp) as day, count(distinct properties.$browser) as distinct_browser_count-FROM events-WHERE event = '$pageview'- AND timestamp >= now() - INTERVAL 14 DAY-GROUP BY day-ORDER BY day-""",- ),- EvalCase(- input="Sum up the total amounts paid for the 'paid_bill' event over the past month for Hedgebox Inc.",- expected="""-SELECT sum(toFloat(properties.amount_usd)) AS total_amount_paid-FROM events-WHERE event = 'paid_bill'- AND timestamp >= now() - INTERVAL 30 DAY- AND organization.properties.name = 'Hedgebox Inc.'-""",- ),- ### Open questions to list persons- EvalCase(- input="Who are the 5 users I should interview around file download usage?",- expected="""-SELECT- person_id,- person.properties.email as email,- person.properties.name as name,- count(*) as usage_count,- max(timestamp) as last_used-FROM events-WHERE event = 'downloaded_file'-GROUP BY person_id, person.properties.email, person.properties.name-ORDER BY usage_count DESC, last_used DESC-LIMIT 5-""",- ),- EvalCase(- input="Who are the 5 users that have downloaded the most files in the past few weeks? Who are they?",- expected="""-SELECT- person_id,- person.properties.email as email,- person.properties.name as name,- count(*) as file_download_count,- max(timestamp) as last_download-FROM events-WHERE event = 'downloaded_file'- AND timestamp >= now() - INTERVAL 14 DAY-GROUP BY person_id, person.properties.email, person.properties.name-ORDER BY file_download_count DESC-LIMIT 5-""",- ),- EvalCase(- input="Show me 10 example person profiles of file download users",- expected="""-SELECT DISTINCT- person_id,- person.properties.email as email,- person.properties.name as name,- person.properties.company as company,- person.properties.role as role,- person.properties.created_at as user_created_at,- count(*) as file_download_event_count-FROM events-WHERE event = 'downloaded_file'-GROUP BY person_id, person.properties.email, person.properties.name,- person.properties.company, person.properties.role, person.properties.created_at-LIMIT 10-""",- ),- ### Funnel trends- EvalCase(- input="What's the conversion rate from trial signup to paid subscription by cohort month?",- expected="""-WITH trial_signups AS (- SELECT- person_id,- date_trunc('month', min(timestamp)) as cohort_month- FROM events- WHERE event = 'trial_signup'- GROUP BY person_id-),-conversions AS (- SELECT DISTINCT person_id- FROM events- WHERE event = 'subscription_started'-)-SELECT- cohort_month,- count(DISTINCT t.person_id) as trial_signups,- count(DISTINCT c.person_id) as paid_conversions,- (count(DISTINCT c.person_id) * 100.0 / count(DISTINCT t.person_id)) as conversion_rate-FROM trial_signups t-LEFT JOIN conversions c ON t.person_id = c.person_id-GROUP BY cohort_month-ORDER BY cohort_month-""",- ),- EvalCase(- input="Show me the median time between page views for each browser type, excluding users with only 1 page view",- expected="""-WITH pageview_times AS (- SELECT- person_id,- properties.$browser as browser_type,- timestamp,- LAG(timestamp) OVER (PARTITION BY person_id ORDER BY timestamp) as prev_timestamp- FROM events- WHERE event = '$pageview'-),-time_diffs AS (- SELECT- person_id,- browser_type,- dateDiff('second', prev_timestamp, timestamp) as seconds_between_views- FROM pageview_times- WHERE prev_timestamp IS NOT NULL-),-user_pageview_counts AS (- SELECT person_id, count(*) as pageview_count- FROM events- WHERE event = '$pageview'- GROUP BY person_id- HAVING pageview_count > 1-)-SELECT- browser_type,- median(seconds_between_views) as median_seconds_between_views-FROM time_diffs-WHERE person_id IN (SELECT person_id FROM user_pageview_counts)-GROUP BY browser_type-ORDER BY median_seconds_between_views DESC-""",- ),- ### Correlation- EvalCase(- input=(- "Which features are most predictive of churn? Show correlation between feature usage in first 30 days and churn in next 60 days",- "Use events uploaded_file, downloaded_file, shared_file_link, invited_team_member, upgraded_plan, downgraded_plan. Use lack of activity as the churn signal. Analyze the last 120 days of data.",- ),- expected="""-WITH user_metrics AS (- SELECT- fu.person_id,- fu.uploads_30d,- fu.downloads_30d,- fu.shares_30d,- fu.invites_30d,- fu.upgrades_30d,- fu.downgrades_30d,- fu.total_events_30d,- cs.churned- FROM (- SELECT- e.person_id,- countIf(e.event = 'uploaded_file') AS uploads_30d,- countIf(e.event = 'downloaded_file') AS downloads_30d,- countIf(e.event = 'shared_file_link') AS shares_30d,- countIf(e.event = 'invited_team_member') AS invites_30d,- countIf(e.event = 'upgraded_plan') AS upgrades_30d,- countIf(e.event = 'downgraded_plan') AS downgrades_30d,- count() AS total_events_30d,- MIN(e.timestamp) AS first_activity_date- FROM events e- WHERE e.timestamp >= now() - INTERVAL 120 DAY- GROUP BY e.person_id- HAVING first_activity_date <= now() - INTERVAL 90 DAY- ) fu- INNER JOIN (- SELECT- person_id,- MIN(timestamp) AS first_activity_date,- CASE- WHEN MAX(activity_31_90) = 1 THEN 0 ELSE 1- END AS churned- FROM (- SELECT- person_id,- timestamp,- CASE WHEN timestamp >= min_timestamp + INTERVAL 30 DAY AND timestamp < min_timestamp + INTERVAL 90 DAY THEN 1 ELSE 0 END AS activity_31_90,- min_timestamp- FROM (- SELECT- person_id,- timestamp,- MIN(timestamp) OVER (PARTITION BY person_id) AS min_timestamp- FROM events- WHERE timestamp >= now() - INTERVAL 120 DAY- )- )- GROUP BY person_id, min_timestamp- HAVING min_timestamp <= now() - INTERVAL 90 DAY- ) cs ON fu.person_id = cs.person_id-)--SELECT- 'uploads' AS feature,- AVG(CASE WHEN churned = 1 THEN uploads_30d ELSE 0 END) AS avg_usage_churned,- AVG(CASE WHEN churned = 0 THEN uploads_30d ELSE 0 END) AS avg_usage_retained,- AVG(churned) AS overall_churn_rate,- AVG(CASE WHEN uploads_30d > 0 THEN churned ELSE NULL END) AS churn_rate_with_feature,- AVG(CASE WHEN uploads_30d = 0 THEN churned ELSE NULL END) AS churn_rate_without_feature,- corr(toFloat(uploads_30d), toFloat(churned)) AS correlation_coefficient-FROM user_metrics--UNION ALL--SELECT- 'downloads' AS feature,- AVG(CASE WHEN churned = 1 THEN downloads_30d ELSE 0 END),- AVG(CASE WHEN churned = 0 THEN downloads_30d ELSE 0 END),- AVG(churned),- AVG(CASE WHEN downloads_30d > 0 THEN churned ELSE NULL END),- AVG(CASE WHEN downloads_30d = 0 THEN churned ELSE NULL END),- corr(toFloat(downloads_30d), toFloat(churned))-FROM user_metrics--UNION ALL--SELECT- 'shares' AS feature,- AVG(CASE WHEN churned = 1 THEN shares_30d ELSE 0 END),- AVG(CASE WHEN churned = 0 THEN shares_30d ELSE 0 END),- AVG(churned),- AVG(CASE WHEN shares_30d > 0 THEN churned ELSE NULL END),- AVG(CASE WHEN shares_30d = 0 THEN churned ELSE NULL END),- corr(toFloat(shares_30d), toFloat(churned))-FROM user_metrics--UNION ALL--SELECT- 'invites' AS feature,- AVG(CASE WHEN churned = 1 THEN invites_30d ELSE 0 END),- AVG(CASE WHEN churned = 0 THEN invites_30d ELSE 0 END),- AVG(churned),- AVG(CASE WHEN invites_30d > 0 THEN churned ELSE NULL END),- AVG(CASE WHEN invites_30d = 0 THEN churned ELSE NULL END),- corr(toFloat(invites_30d), toFloat(churned))-FROM user_metrics--UNION ALL--SELECT- 'upgrades' AS feature,- AVG(CASE WHEN churned = 1 THEN upgrades_30d ELSE 0 END),- AVG(CASE WHEN churned = 0 THEN upgrades_30d ELSE 0 END),- AVG(churned),- AVG(CASE WHEN upgrades_30d > 0 THEN churned ELSE NULL END),- AVG(CASE WHEN upgrades_30d = 0 THEN churned ELSE NULL END),- corr(toFloat(upgrades_30d), toFloat(churned))-FROM user_metrics--ORDER BY ABS(corr(toFloat(uploads_30d), toFloat(churned))) DESC-""",- ),- EvalCase(- input="Show weekly pageview counts with Monday as the start of week for the last 4 weeks",- expected="""-SELECT toStartOfWeek(timestamp, 1) as week_start, count(*) as pageview_count-FROM events-WHERE event = '$pageview'- AND timestamp >= now() - INTERVAL 4 WEEK-GROUP BY week_start-ORDER BY week_start-""",- ),- EvalCase(- input="Get the earliest session date for each user in the last month",- expected="""-SELECT person_id, toDate(min(timestamp)) as first_session_date-FROM events-WHERE timestamp >= now() - INTERVAL 30 DAY-GROUP BY person_id-ORDER BY first_session_date-""",- ),- EvalCase(- input="I want to split a comma-separated interests property and count unique users",- expected="""-SELECT count(distinct person_id) as users_with_interests-FROM events-WHERE properties.interests IS NOT NULL- AND length(splitByChar(',', coalesce(properties.interests, ''))) > 0-""",- ),- ]-- await MaxPublicEval(- experiment_name="sql",- task=call_agent_for_sql,- scores=[- ExecuteSQLToolCalled(),- HogQLQuerySyntaxCorrectness(),- CISQLSemanticsCorrectness(),- ],- data=all_cases,- pytestconfig=pytestconfig,- )diff --git a/ee/hogai/eval/ci/eval_survey_analysis.py b/ee/hogai/eval/ci/eval_survey_analysis.pydeleted file mode 100644index c94e7708e9ee..000000000000--- a/ee/hogai/eval/ci/eval_survey_analysis.py+++ /dev/null@@ -1,966 +0,0 @@-import uuid-import datetime--import pytest-from unittest.mock import patch--from autoevals.llm import LLMClassifier-from braintrust import EvalCase, Score-from langchain_core.runnables import RunnableConfig--from products.surveys.backend.max_tools import SurveyAnalysisTool-from products.surveys.backend.models import Survey--from ee.hogai.utils.types.base import AssistantState--from ..base import MaxPublicEval---# Helper functions to generate test response data-def generate_test_data_responses():- """Generate clearly placeholder/test responses that should be detected as test data."""- return [- {- "questionName": "What do you think about our product?",- "questionId": "q1",- "responses": [- {- "responseText": "fasdfasdf",- "isOpenEnded": True,- },- {- "responseText": "testing",- "isOpenEnded": True,- },- ],- }- ]---def generate_mixed_data_responses():- """Generate mixed test and genuine responses (60% test, 40% genuine)."""- test_responses: list[dict] = []-- genuine_responses = [- # Interface feedback- {- "responseText": "The main dashboard is cluttered and hard to navigate quickly",- "isOpenEnded": True,- },- {- "responseText": "Interface could be more intuitive, buttons are not where I expect",- "isOpenEnded": True,- },- {- "responseText": "Navigation menu needs work - took me 5 minutes to find settings",- "isOpenEnded": True,- },- {- "responseText": "Love the clean design but some UI elements are too small on mobile",- "isOpenEnded": True,- },- {- "responseText": "Search functionality in the interface is hard to find and use",- "isOpenEnded": True,- },- {- "responseText": "The sidebar gets in the way on smaller screens",- "isOpenEnded": True,- },- # Performance feedback- {- "responseText": "Loading times are really slow, especially for large datasets",- "isOpenEnded": True,- },- {- "responseText": "App crashes when I upload files bigger than 50MB",- "isOpenEnded": True,- },- {- "responseText": "Performance on mobile is terrible, very laggy scrolling",- "isOpenEnded": True,- },- {- "responseText": "Would love faster sync between devices, currently takes forever",- "isOpenEnded": True,- },- ]-- return [- {- "questionName": "How can we improve our product?",- "questionId": "q1",- "responses": test_responses + genuine_responses,- }- ]---def generate_positive_feedback_responses():- """Generate genuine positive feedback across multiple themes."""- ui_design_responses = [- {- "responseText": "The user interface is incredibly clean and intuitive to navigate",- "isOpenEnded": True,- },- {- "responseText": "Love the modern design - feels professional and polished",- "isOpenEnded": True,- },- {- "responseText": "Dashboard layout makes it easy to find everything I need quickly",- "isOpenEnded": True,- },- {- "responseText": "The visual hierarchy is perfect - important things stand out",- "isOpenEnded": True,- },- {- "responseText": "Responsive design works beautifully on all my devices",- "isOpenEnded": True,- },- {- "responseText": "Color scheme and typography are excellent choices",- "isOpenEnded": True,- },- {- "responseText": "Interface feels modern and doesn't look outdated like competitors",- "isOpenEnded": True,- },- ]-- performance_responses = [- {- "responseText": "Lightning fast loading times even with large datasets",- "isOpenEnded": True,- },- {- "responseText": "Never experienced crashes or bugs - very stable platform",- "isOpenEnded": True,- },- {- "responseText": "Real-time updates happen instantly without any lag",- "isOpenEnded": True,- },- {- "responseText": "Performance is consistently excellent across all features",- "isOpenEnded": True,- },- {- "responseText": "Handles our heavy usage without any slowdowns",- "isOpenEnded": True,- },- ]-- support_responses = [- {- "responseText": "Customer support team is incredibly knowledgeable and responsive",- "isOpenEnded": True,- },- {- "responseText": "Got help within 15 minutes via chat - amazing service",- "isOpenEnded": True,- },- {- "responseText": "Support goes above and beyond to solve problems",- "isOpenEnded": True,- },- {- "responseText": "Documentation is thorough and support articles are really helpful",- "isOpenEnded": True,- },- ]-- integration_responses = [- {- "responseText": "Seamless integration with all our existing tools and workflows",- "isOpenEnded": True,- },- {- "responseText": "API is well-documented and easy to implement",- "isOpenEnded": True,- },- {- "responseText": "Fits perfectly into our daily workflow without disruption",- "isOpenEnded": True,- },- {- "responseText": "Export functionality works exactly as expected with our systems",- "isOpenEnded": True,- },- ]-- return [- {- "questionName": "What do you like most about our product?",- "questionId": "q1",- "responses": ui_design_responses + performance_responses + support_responses + integration_responses,- }- ]---def generate_negative_feedback_responses():- """Generate genuine negative feedback across problem areas."""- performance_issues = [- {- "responseText": "App crashes constantly when I try to upload files larger than 100MB",- "isOpenEnded": True,- },- {- "responseText": "Loading times are painfully slow - sometimes 30+ seconds for simple queries",- "isOpenEnded": True,- },- {- "responseText": "System goes down for maintenance way too often, always during business hours",- "isOpenEnded": True,- },- {- "responseText": "Data syncing is unreliable - lost work multiple times due to sync failures",- "isOpenEnded": True,- },- {- "responseText": "Memory usage is insane - laptop becomes unusable when running your app",- "isOpenEnded": True,- },- {- "responseText": "Frequent timeouts when working with larger datasets, very frustrating",- "isOpenEnded": True,- },- ]-- support_problems = [- {- "responseText": "Support tickets take 3-5 days to get any response, completely unacceptable",- "isOpenEnded": True,- },- {- "responseText": "When support finally responds, they ask basic questions I already answered",- "isOpenEnded": True,- },- {- "responseText": "No phone support option - only slow email tickets for urgent issues",- "isOpenEnded": True,- },- {- "responseText": "Support team clearly doesn't understand their own product features",- "isOpenEnded": True,- },- ]-- pricing_concerns = [- {- "responseText": "Way overpriced compared to competitors offering similar features",- "isOpenEnded": True,- },- {- "responseText": "Hidden fees keep appearing - billing is not transparent at all",- "isOpenEnded": True,- },- {- "responseText": "Free tier is basically useless - forces you to upgrade immediately",- "isOpenEnded": True,- },- {- "responseText": "Poor value for money - paying premium prices for basic functionality",- "isOpenEnded": True,- },- ]-- missing_features = [- {- "responseText": "No bulk operations - have to do everything one by one, super tedious",- "isOpenEnded": True,- },- {- "responseText": "Missing basic export options that every competitor has",- "isOpenEnded": True,- },- {- "responseText": "No offline mode - completely useless when internet is spotty",- "isOpenEnded": True,- },- {- "responseText": "Collaboration features are primitive compared to modern standards",- "isOpenEnded": True,- },- ]-- return [- {- "questionName": "What issues or problems have you encountered with our product?",- "questionId": "q1",- "responses": performance_issues + support_problems + pricing_concerns + missing_features,- }- ]---def generate_multi_question_responses():- """Generate responses for multiple questions with varied feedback types."""- positive_responses = [- # Ease of use feedback- {- "responseText": "Incredibly intuitive interface - figured it out in minutes",- "isOpenEnded": True,- },- {- "responseText": "Simple workflow that doesn't require extensive training",- "isOpenEnded": True,- },- {- "responseText": "Clean design makes complex tasks feel manageable",- "isOpenEnded": True,- },- {- "responseText": "Onboarding process was smooth and well-guided",- "isOpenEnded": True,- },- {- "responseText": "Everything is where you'd expect it to be",- "isOpenEnded": True,- },- {- "responseText": "No steep learning curve unlike other similar tools",- "isOpenEnded": True,- },- {- "responseText": "User experience feels thoughtfully designed",- "isOpenEnded": True,- },- {- "responseText": "Great balance of powerful features without complexity",- "isOpenEnded": True,- },- # Reliability feedback- {- "responseText": "Rock solid performance - never had any crashes or issues",- "isOpenEnded": True,- },- {- "responseText": "Data integrity is excellent, never lost any work",- "isOpenEnded": True,- },- {- "responseText": "Consistent uptime - can always rely on it being available",- "isOpenEnded": True,- },- {- "responseText": "Fast loading and response times across all features",- "isOpenEnded": True,- },- {- "responseText": "Auto-save functionality has saved me multiple times",- "isOpenEnded": True,- },- {- "responseText": "Handles large amounts of data without slowing down",- "isOpenEnded": True,- },- ]-- improvement_responses = [- # Advanced features- {- "responseText": "Need bulk operations for managing hundreds of items at once",- "isOpenEnded": True,- },- {- "responseText": "Advanced filtering and search capabilities would be game-changing",- "isOpenEnded": True,- },- {- "responseText": "API access for custom integrations with our internal tools",- "isOpenEnded": True,- },- {- "responseText": "Custom dashboards and reporting features for management",- "isOpenEnded": True,- },- {- "responseText": "Automation rules and workflows to reduce manual work",- "isOpenEnded": True,- },- {- "responseText": "More granular permission controls for team management",- "isOpenEnded": True,- },- {- "responseText": "Advanced analytics and insights into usage patterns",- "isOpenEnded": True,- },- {- "responseText": "Better collaboration tools for larger teams",- "isOpenEnded": True,- },- {- "responseText": "White-label options for client-facing implementations",- "isOpenEnded": True,- },- # Mobile improvements- {- "responseText": "Mobile app needs significant performance improvements",- "isOpenEnded": True,- },- {- "responseText": "Offline mode for working without internet connection",- "isOpenEnded": True,- },- {- "responseText": "Native mobile apps instead of web-based mobile experience",- "isOpenEnded": True,- },- {- "responseText": "Better mobile interface optimization for small screens",- "isOpenEnded": True,- },- {- "responseText": "Faster loading times on mobile devices",- "isOpenEnded": True,- },- {- "responseText": "Push notifications for mobile app would be useful",- "isOpenEnded": True,- },- {- "responseText": "Dark mode theme option for better user experience",- "isOpenEnded": True,- },- {- "responseText": "Keyboard shortcuts for power users on desktop",- "isOpenEnded": True,- },- {- "responseText": "Better browser compatibility, especially for older versions",- "isOpenEnded": True,- },- ]-- return [- {- "questionName": "What do you like about our product?",- "questionId": "q1",- "responses": positive_responses,- },- {- "questionName": "What could we improve or add?",- "questionId": "q2",- "responses": improvement_responses,- },- ]---def generate_service_feedback_responses():- """Generate customer service feedback with varied quality levels."""- excellent_service = [- {- "responseText": "Customer support resolved my issue within 2 hours - absolutely fantastic",- "isOpenEnded": True,- },- {- "responseText": "Representative was knowledgeable and patient, walked me through everything step by step",- "isOpenEnded": True,- },- {- "responseText": "24/7 chat support is a game changer for our international team",- "isOpenEnded": True,- },- {- "responseText": "Proactive communication about updates and maintenance - really appreciate that",- "isOpenEnded": True,- },- {- "responseText": "Technical support team understood our complex setup immediately",- "isOpenEnded": True,- },- {- "responseText": "Follow-up email to ensure problem was fully resolved shows they care",- "isOpenEnded": True,- },- {- "responseText": "Support documentation is comprehensive and easy to follow",- "isOpenEnded": True,- },- {- "responseText": "Video tutorials provided by support team were extremely helpful",- "isOpenEnded": True,- },- ]-- moderate_service = [- {- "responseText": "Good service overall but had to wait 30 minutes for initial response",- "isOpenEnded": True,- },- {- "responseText": "Support was helpful but had to explain the issue multiple times",- "isOpenEnded": True,- },- {- "responseText": "Eventually got the answer I needed, took a few back-and-forth messages",- "isOpenEnded": True,- },- {- "responseText": "Phone support was good but email responses are quite slow",- "isOpenEnded": True,- },- {- "responseText": "Representative was polite but didn't seem familiar with advanced features",- "isOpenEnded": True,- },- {- "responseText": "Got my problem solved but the process felt longer than necessary",- "isOpenEnded": True,- },- ]-- poor_service = [- {- "responseText": "Waited over 2 hours for someone to respond to urgent issue",- "isOpenEnded": True,- },- {- "responseText": "First agent couldn't help, was transferred 3 times before getting answer",- "isOpenEnded": True,- },- {- "responseText": "Support ticket was closed without resolution, had to reopen",- "isOpenEnded": True,- },- {- "responseText": "Generic responses that didn't address my specific technical problem",- "isOpenEnded": True,- },- ]-- return [- {- "questionName": "How would you rate our customer service experience?",- "questionId": "q1",- "responses": excellent_service + moderate_service + poor_service,- }- ]---def generate_feature_request_responses():- """Generate detailed feature requests across different categories."""- integration_requests = [- {- "responseText": "Integration with Slack would revolutionize our team communication workflow",- "isOpenEnded": True,- },- {- "responseText": "Google Workspace SSO integration is desperately needed for enterprise deployment",- "isOpenEnded": True,- },- {- "responseText": "Zapier integration would allow us to automate so many manual processes",- "isOpenEnded": True,- },- {- "responseText": "Microsoft Teams integration for seamless file sharing and notifications",- "isOpenEnded": True,- },- {- "responseText": "API endpoints for custom reporting would enable our dashboard integrations",- "isOpenEnded": True,- },- {- "responseText": "Salesforce CRM integration to sync customer data automatically",- "isOpenEnded": True,- },- {- "responseText": "Webhook support for real-time data synchronization with our systems",- "isOpenEnded": True,- },- ]-- mobile_improvements = [- {- "responseText": "Offline mode for mobile app would be incredible for field work",- "isOpenEnded": True,- },- {- "responseText": "Push notifications for important updates and deadlines",- "isOpenEnded": True,- },- {- "responseText": "Mobile photo upload with automatic compression and organization",- "isOpenEnded": True,- },- {- "responseText": "Better tablet interface optimized for larger screens",- "isOpenEnded": True,- },- {- "responseText": "Voice-to-text input for quick note taking on mobile",- "isOpenEnded": True,- },- {- "responseText": "Dark mode theme for mobile app to reduce eye strain",- "isOpenEnded": True,- },- ]-- analytics_reporting = [- {- "responseText": "Advanced analytics dashboard with customizable KPI tracking",- "isOpenEnded": True,- },- {- "responseText": "Automated report scheduling and email delivery to stakeholders",- "isOpenEnded": True,- },- {- "responseText": "Data export in more formats like Excel, PDF, and CSV",- "isOpenEnded": True,- },- {- "responseText": "Real-time collaboration analytics to track team productivity",- "isOpenEnded": True,- },- {- "responseText": "Historical trend analysis with predictive insights",- "isOpenEnded": True,- },- ]-- ux_improvements = [- {- "responseText": "Keyboard shortcuts for power users would dramatically improve efficiency",- "isOpenEnded": True,- },- {- "responseText": "Multi-language support for our international team members",- "isOpenEnded": True,- },- {- "responseText": "Bulk operations for managing large datasets more efficiently",- "isOpenEnded": True,- },- {- "responseText": "Template system for recurring workflows and standardized processes",- "isOpenEnded": True,- },- ]-- return [- {- "questionName": "What features would you like to see added or improved?",- "questionId": "q1",- "responses": integration_requests + mobile_improvements + analytics_reporting + ux_improvements,- }- ]---async def create_test_surveys(demo_org_team_user):- """Create test surveys for evaluation with questions matching test data."""- _, team, user = demo_org_team_user-- test_surveys = []- timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")-- # Survey configs: (name, questions) - questions match the test data generators- survey_configs = [- # Test case 0: generate_test_data_responses() - 1 question- (- f"Test Survey with Placeholder Data {timestamp}",- [- {"type": "open", "question": "What do you think about our product?", "id": str(uuid.uuid4())},- ],- ),- # Test case 1: generate_mixed_data_responses() - 1 question- (- f"Mixed Data Survey {timestamp}",- [- {"type": "open", "question": "How can we improve our product?", "id": str(uuid.uuid4())},- ],- ),- # Test case 2: generate_positive_feedback_responses() - 1 question- (- f"Customer Satisfaction Survey {timestamp}",- [- {"type": "open", "question": "What do you like most about our product?", "id": str(uuid.uuid4())},- ],- ),- # Test case 3: generate_negative_feedback_responses() - 1 question- (- f"Product Issues Survey {timestamp}",- [- {- "type": "open",- "question": "What issues or problems have you encountered with our product?",- "id": str(uuid.uuid4()),- },- ],- ),- # Test case 4: generate_multi_question_responses() - 2 questions- (- f"Comprehensive Feedback Survey {timestamp}",- [- {"type": "open", "question": "What do you like about our product?", "id": str(uuid.uuid4())},- {"type": "open", "question": "What could we improve or add?", "id": str(uuid.uuid4())},- ],- ),- # Test case 5: generate_service_feedback_responses() - 1 question- (- f"Support Service Survey {timestamp}",- [- {- "type": "open",- "question": "How would you rate our customer service experience?",- "id": str(uuid.uuid4()),- },- ],- ),- # Test case 6: generate_feature_request_responses() - 1 question- (- f"Feature Requests Survey {timestamp}",- [- {- "type": "open",- "question": "What features would you like to see added or improved?",- "id": str(uuid.uuid4()),- },- ],- ),- ]-- for name, questions in survey_configs:- survey = await Survey.objects.acreate(- team=team,- created_by=user,- name=name,- description=f"Test survey: {name}",- questions=questions,- type="popover",- )- test_surveys.append(survey)-- return test_surveys---def _extract_response_texts(formatted_responses: list[dict]) -> dict[int, list[str]]:- """- Extract response texts from formatted_responses grouped by question index.- Returns a dict mapping question index to list of response texts.- """- result: dict[int, list[str]] = {}- for idx, question_group in enumerate(formatted_responses):- responses = question_group.get("responses", [])- result[idx] = [r.get("responseText", "") for r in responses if r.get("responseText")]- return result---async def call_survey_analysis_tool(demo_org_team_user, create_test_surveys):- """- This fixture creates a properly configured SurveyAnalysisTool for evaluation.- Mocks fetch_responses to return the test data from formatted_responses.- """- _, team, user = demo_org_team_user- test_surveys = create_test_surveys-- async def call_analysis_tool(context: dict) -> dict:- """- Call the survey analysis tool with provided context and return structured output.- """- try:- # Get the right survey for the test case- survey_index = context.get("survey_index", 0)- if survey_index >= len(test_surveys):- return {- "success": False,- "user_message": "Survey index out of range",- "artifact": None,- "error": "Invalid survey_index",- }-- survey = test_surveys[survey_index]- formatted_responses = context.get("formatted_responses", [])-- # Extract response texts grouped by question index for mocking- responses_by_question = _extract_response_texts(formatted_responses)-- # Mock fetch_responses to return our test data- def mock_fetch_responses(survey_id, question_index, question_id, start_date, end_date, team, limit=50):- return responses_by_question.get(question_index, [])-- # Create the analysis tool- analysis_tool = SurveyAnalysisTool(- team=team,- user=user,- state=AssistantState(messages=[]),- config=RunnableConfig(configurable={}),- )-- # Call the tool with mocked fetch_responses- with patch("products.surveys.backend.max_tools.fetch_responses", side_effect=mock_fetch_responses):- result = await analysis_tool._arun_impl(survey_id=str(survey.id))-- # Return structured output- user_message, artifact = result- return {- "success": True,- "user_message": user_message,- "artifact": artifact,- }-- except Exception as e:- return {- "success": False,- "user_message": f"❌ Analysis failed: {str(e)}",- "artifact": None,- "error": str(e),- }-- return call_analysis_tool---class AnalysisPromptQualityScorer(LLMClassifier):- """- Evaluate if the tool output provides good context for the agent to analyze.- """-- def __init__(self, **kwargs):- super().__init__(- name="analysis_prompt_quality",- prompt_template="""-Evaluate whether the tool output provides sufficient context for an AI agent to analyze the survey responses.--Tool Output Message: {{output.user_message}}-Input Responses: {{input.formatted_responses}}--Evaluation Criteria:-1. **Survey Context**: Does the output include the survey name and response count?-2. **Response Clarity**: Are the responses clearly presented and readable?-3. **Analysis Instructions**: Does the output guide the agent on what to analyze (themes, sentiment, insights)?-4. **Completeness**: Does the output include all necessary information for meaningful analysis?-5. **Structure**: Is the output well-structured for agent consumption?--How would you rate the analysis prompt quality? Choose one:-- excellent: Output provides complete context with clear analysis instructions-- good: Output provides most necessary context with minor gaps-- adequate: Output has basic information but lacks clear structure or instructions-- poor: Output is incomplete, unclear, or missing key analysis guidance-""".strip(),- choice_scores={- "excellent": 1.0,- "good": 0.75,- "adequate": 0.5,- "poor": 0.0,- },- model="gpt-4.1",- **kwargs,- )-- async def _run_eval_async(self, output, expected=None, **kwargs):- if not output.get("success", False):- return Score(- name=self._name(),- score=0,- metadata={"reason": "Retrieval failed", "error": output.get("error", "Unknown error")},- )- return await super()._run_eval_async(output, expected, **kwargs)-- def _run_eval_sync(self, output, expected=None, **kwargs):- if not output.get("success", False):- return Score(- name=self._name(),- score=0,- metadata={"reason": "Retrieval failed", "error": output.get("error", "Unknown error")},- )- return super()._run_eval_sync(output, expected, **kwargs)---async def eval_survey_analysis(call_survey_analysis_tool, pytestconfig):- """- Evaluation for survey response retrieval functionality.- Tests that the tool correctly retrieves and formats survey responses for agent analysis.- """- await MaxPublicEval(- experiment_name="survey_analysis",- task=call_survey_analysis_tool,- scores=[- AnalysisPromptQualityScorer(),- ],- data=[- # Test Case 1: Small dataset (2 responses)- EvalCase(- input={- "survey_index": 0,- "formatted_responses": generate_test_data_responses(),- },- expected={- "response_count": 2,- },- metadata={"test_type": "small_dataset"},- ),- # Test Case 2: Mixed feedback (10 responses)- EvalCase(- input={- "survey_index": 1,- "formatted_responses": generate_mixed_data_responses(),- },- expected={- "response_count": 10,- },- metadata={"test_type": "mixed_feedback"},- ),- # Test Case 3: Positive feedback (20 responses)- EvalCase(- input={- "survey_index": 2,- "formatted_responses": generate_positive_feedback_responses(),- },- expected={- "response_count": 20,- },- metadata={"test_type": "positive_feedback"},- ),- # Test Case 4: Negative feedback (18 responses)- EvalCase(- input={- "survey_index": 3,- "formatted_responses": generate_negative_feedback_responses(),- },- expected={- "response_count": 18,- },- metadata={"test_type": "negative_feedback"},- ),- # Test Case 5: Multiple questions (33 total responses across 2 questions)- EvalCase(- input={- "survey_index": 4,- "formatted_responses": generate_multi_question_responses(),- },- expected={- "response_count": 33,- },- metadata={"test_type": "multi_question"},- ),- # Test Case 6: Service feedback (18 responses)- EvalCase(- input={- "survey_index": 5,- "formatted_responses": generate_service_feedback_responses(),- },- expected={- "response_count": 18,- },- metadata={"test_type": "service_feedback"},- ),- # Test Case 7: Feature requests (22 responses)- EvalCase(- input={- "survey_index": 6,- "formatted_responses": generate_feature_request_responses(),- },- expected={- "response_count": 22,- },- metadata={"test_type": "feature_requests"},- ),- ],- pytestconfig=pytestconfig,- )diff --git a/ee/hogai/eval/ci/eval_surveys.py b/ee/hogai/eval/ci/eval_surveys.pydeleted file mode 100644index 5b8a920fd79a..000000000000--- a/ee/hogai/eval/ci/eval_surveys.py+++ /dev/null@@ -1,372 +0,0 @@-"""Evaluations for CreateSurveyTool."""--import uuid--import pytest--from autoevals.partial import ScorerWithPartial-from autoevals.ragas import AnswerSimilarity-from braintrust import EvalCase, Score--from products.feature_flags.backend.models.feature_flag import FeatureFlag-from products.posthog_ai.backend.models.assistant import Conversation-from products.surveys.backend.max_tools import CreateSurveyTool, SimpleSurveyQuestion-from products.surveys.backend.models import Survey--from ee.hogai.eval.base import MaxPublicEval---def unique_name(base_name: str) -> str:- """Generate a unique survey name to avoid duplicates in demo data."""- return f"{base_name} - {uuid.uuid4().hex[:8]}"---class SurveyOutputScorer(ScorerWithPartial):- """Custom scorer for survey tool output that combines semantic similarity for text and exact matching for other fields."""-- def __init__(self, semantic_fields: set[str] | None = None, **kwargs):- super().__init__(**kwargs)- self.semantic_fields = semantic_fields or {"message"}-- def _run_eval_sync(self, output: dict, expected: dict, **kwargs):- if not expected:- return Score(name=self._name(), score=None, metadata={"reason": "No expected value provided"})- if not output:- return Score(name=self._name(), score=0.0, metadata={"reason": "No output provided"})-- total_fields = len(expected)- if total_fields == 0:- return Score(name=self._name(), score=1.0)-- score_per_field = 1.0 / total_fields- total_score = 0.0- metadata = {}-- for field_name, expected_value in expected.items():- actual_value = output.get(field_name)-- if field_name in self.semantic_fields:- # Use semantic similarity for text fields- if actual_value is not None and expected_value is not None:- similarity_scorer = AnswerSimilarity(model="text-embedding-3-small")- result = similarity_scorer.eval(output=str(actual_value), expected=str(expected_value))- field_score = result.score * score_per_field- total_score += field_score- metadata[f"{field_name}_score"] = result.score- else:- metadata[f"{field_name}_missing"] = True- else:- # Use exact match for numeric/boolean fields- if actual_value == expected_value:- total_score += score_per_field- metadata[f"{field_name}_match"] = True- else:- metadata[f"{field_name}_mismatch"] = {- "expected": expected_value,- "actual": actual_value,- }-- return Score(name=self._name(), score=total_score, metadata=metadata)---async def eval_surveys(pytestconfig, demo_org_team_user):- """Test survey creation tool with various scenarios."""- _, team, user = demo_org_team_user-- conversation = await Conversation.objects.acreate(team=team, user=user)-- # Get or create feature flags for targeting tests- checkout_flag, _ = await FeatureFlag.objects.aget_or_create(- team=team,- key="new-checkout-flow",- defaults={- "name": "New Checkout Flow",- "created_by": user,- "filters": {"groups": [{"properties": [], "rollout_percentage": 50}]},- },- )-- ab_test_flag, _ = await FeatureFlag.objects.aget_or_create(- team=team,- key="ab-test-experiment",- defaults={- "name": "A/B Test Experiment",- "created_by": user,- "filters": {- "groups": [{"properties": [], "rollout_percentage": 100}],- "multivariate": {- "variants": [- {"key": "control", "rollout_percentage": 50},- {"key": "treatment", "rollout_percentage": 50},- ]- },- },- },- )-- async def task_create_survey(test_case: dict):- tool = CreateSurveyTool(- team=team,- user=user,- config={- "configurable": {- "thread_id": conversation.id,- "team": team,- "user": user,- }- },- )-- kwargs: dict = {- "name": unique_name(test_case["name"]),- "description": test_case.get("description", ""),- "questions": test_case["questions"],- "should_launch": test_case.get("should_launch", False),- }- if test_case.get("linked_flag_id") is not None:- kwargs["linked_flag_id"] = test_case["linked_flag_id"]- if test_case.get("linked_flag_variant") is not None:- kwargs["linked_flag_variant"] = test_case["linked_flag_variant"]- if test_case.get("target_url") is not None:- kwargs["target_url"] = test_case["target_url"]- if test_case.get("target_url_match") is not None:- kwargs["target_url_match"] = test_case["target_url_match"]- if test_case.get("survey_type") is not None:- kwargs["survey_type"] = test_case["survey_type"]-- result_message, artifact = await tool._arun_impl(**kwargs)-- result: dict = {- "message": result_message,- }-- if artifact and "survey_id" in artifact:- # nosemgrep: idor-lookup-without-team (CI eval script, IDs from test fixtures)- survey_exists = await Survey.objects.filter(id=artifact["survey_id"], archived=False).aexists()- result["survey_created"] = survey_exists- result["survey_id"] = artifact["survey_id"]- result["survey_name"] = artifact.get("survey_name")-- if survey_exists:- # nosemgrep: idor-lookup-without-team (CI eval script, IDs from test fixtures)- survey = await Survey.objects.aget(id=artifact["survey_id"])- result["question_count"] = len(survey.questions) if survey.questions else 0- result["is_launched"] = survey.start_date is not None- result["linked_flag_id"] = survey.linked_flag_id- result["has_conditions"] = survey.conditions is not None and bool(survey.conditions)- else:- result["survey_created"] = False- result["error"] = artifact.get("error") if artifact else "Unknown error"-- return result-- await MaxPublicEval(- experiment_name="surveys",- task=task_create_survey,- scores=[- SurveyOutputScorer(semantic_fields={"message"}),- ],- data=[- # Test case 1: Basic NPS survey- EvalCase(- input={- "name": "NPS Survey",- "description": "Net Promoter Score survey",- "questions": [- SimpleSurveyQuestion(- type="nps",- question="How likely are you to recommend us to a friend or colleague?",- lower_bound_label="Not likely at all",- upper_bound_label="Extremely likely",- )- ],- },- expected={- "survey_created": True,- "question_count": 1,- "is_launched": False,- },- metadata={"test_type": "nps_survey"},- ),- # Test case 2: CSAT survey with launch- EvalCase(- input={- "name": "CSAT Survey",- "description": "Customer satisfaction survey",- "questions": [- SimpleSurveyQuestion(- type="csat",- question="How satisfied are you with our product?",- )- ],- "should_launch": True,- },- expected={- "survey_created": True,- "question_count": 1,- "is_launched": True,- },- metadata={"test_type": "csat_survey_launched"},- ),- # Test case 3: Multi-question survey (NPS + follow-up)- EvalCase(- input={- "name": "NPS with Follow-up",- "description": "NPS survey with optional follow-up question",- "questions": [- SimpleSurveyQuestion(- type="nps",- question="How likely are you to recommend us?",- ),- SimpleSurveyQuestion(- type="open",- question="What could we improve?",- optional=True,- ),- ],- },- expected={- "survey_created": True,- "question_count": 2,- "is_launched": False,- },- metadata={"test_type": "nps_with_followup"},- ),- # Test case 4: PMF survey with single choice- EvalCase(- input={- "name": "PMF Survey",- "description": "Product-market fit survey",- "questions": [- SimpleSurveyQuestion(- type="single_choice",- question="How would you feel if you could no longer use our product?",- choices=["Very disappointed", "Somewhat disappointed", "Not disappointed"],- )- ],- },- expected={- "survey_created": True,- "question_count": 1,- "is_launched": False,- },- metadata={"test_type": "pmf_survey"},- ),- # Test case 5: Survey with feature flag targeting- EvalCase(- input={- "name": "Checkout Feedback",- "description": "Feedback for new checkout flow users",- "questions": [- SimpleSurveyQuestion(- type="open",- question="How was your checkout experience?",- )- ],- "linked_flag_id": checkout_flag.id,- },- expected={- "survey_created": True,- "question_count": 1,- "linked_flag_id": checkout_flag.id,- },- metadata={"test_type": "feature_flag_targeting"},- ),- # Test case 6: Survey with feature flag variant targeting- EvalCase(- input={- "name": "A/B Test Treatment Survey",- "description": "Survey for users in treatment variant",- "questions": [- SimpleSurveyQuestion(- type="csat",- question="How do you like the new design?",- )- ],- "linked_flag_id": ab_test_flag.id,- "linked_flag_variant": "treatment",- },- expected={- "survey_created": True,- "question_count": 1,- "linked_flag_id": ab_test_flag.id,- "has_conditions": True,- },- metadata={"test_type": "feature_flag_variant_targeting"},- ),- # Test case 7: Survey with URL conditions- EvalCase(- input={- "name": "Pricing Page Feedback",- "description": "Feedback from pricing page visitors",- "questions": [- SimpleSurveyQuestion(- type="single_choice",- question="Is our pricing clear?",- choices=["Yes, very clear", "Somewhat clear", "Not clear at all"],- )- ],- "target_url": "/pricing",- "target_url_match": "contains",- },- expected={- "survey_created": True,- "question_count": 1,- "has_conditions": True,- },- metadata={"test_type": "url_targeting"},- ),- # Test case 8: Multiple choice survey- EvalCase(- input={- "name": "Feature Usage Survey",- "description": "Survey about feature usage",- "questions": [- SimpleSurveyQuestion(- type="multiple_choice",- question="Which features do you use most?",- choices=["Dashboard", "Insights", "Session Replay", "Feature Flags", "Experiments"],- )- ],- },- expected={- "survey_created": True,- "question_count": 1,- },- metadata={"test_type": "multiple_choice"},- ),- # Test case 9: Widget type survey- EvalCase(- input={- "name": "Widget Feedback",- "description": "Widget-based feedback survey",- "survey_type": "widget",- "questions": [- SimpleSurveyQuestion(- type="open",- question="What do you think of our product?",- )- ],- },- expected={- "survey_created": True,- "question_count": 1,- },- metadata={"test_type": "widget_type"},- ),- # Test case 10: Empty questions (should fail validation)- EvalCase(- input={- "name": "Invalid Survey",- "description": "Survey with no questions",- "questions": [],- },- expected={- "survey_created": False,- },- metadata={"test_type": "validation_no_questions"},- ),- ],- pytestconfig=pytestconfig,- )diff --git a/ee/hogai/eval/ci/eval_ticket_summary.py b/ee/hogai/eval/ci/eval_ticket_summary.pydeleted file mode 100644index 61354503eddd..000000000000--- a/ee/hogai/eval/ci/eval_ticket_summary.py+++ /dev/null@@ -1,330 +0,0 @@-import pytest--from autoevals.llm import LLMClassifier-from autoevals.partial import ScorerWithPartial-from braintrust import EvalCase, Score-from langchain_core.messages import (- HumanMessage as LangchainHumanMessage,- SystemMessage,-)--from posthog.schema import AssistantMessage, HumanMessage--from ee.hogai.chat_agent.slash_commands.commands.ticket.prompts import (- SUPPORT_SUMMARIZER_SYSTEM_PROMPT,- SUPPORT_SUMMARIZER_USER_PROMPT,-)-from ee.hogai.chat_agent.slash_commands.commands.ticket.transcript import (- customer_turns,- quoted_spans,- render_transcript,- unverifiable_quotes,-)-from ee.hogai.llm import MaxChatAnthropic--from ..base import MaxPublicEval---def _to_messages(conversation: list[dict[str, str]]) -> list[HumanMessage | AssistantMessage]:- built: list[HumanMessage | AssistantMessage] = []- for message in conversation:- if message["role"] == "human":- built.append(HumanMessage(content=message["content"]))- else:- built.append(AssistantMessage(content=message["content"]))- return built---class TicketSummaryQuality(LLMClassifier):- """Judge whether the summary records the customer's side of the conversation."""-- def __init__(self, **kwargs):- super().__init__(- name="ticket_summary_quality",- prompt_template="""A support engineer is opening this ticket for the first time, and will-read the conversation it came from afterwards. Judge whether this orients them accurately.--It should:-1. Use only these section labels, in this order, omitting any with nothing to report:- **Reported issue:**, **Details provided:**, **Checked by the customer:**-2. Open with a verbatim quote of how the customer described the problem-3. Record what the customer said, not what PostHog AI found, suggested, asked or concluded. Its- answer to a question the customer actually asked may appear, but only as "the customer was told"-4. Carry no diagnosis of its own, and repeat no PostHog AI diagnosis as if it were established-5. Write in third person, calling them "the customer"-6. Put one line per item under the list sections, with no narration between them-7. Stay proportionate, so a long conversation about a small issue gets a short summary--Generated summary:-<summary>-{{output}}-</summary>--What this summary should contain:-{{expected}}--Choose one:-- pass: right sections, leads with the customer's words, records their side, no invented diagnosis-- fail: narrates what PostHog AI did, carries its own or PostHog AI's diagnosis, lists steps for- anyone to take, wrong or missing sections, first person, pads sections it has nothing to report,- or misses the actual issue""",- choice_scores={"pass": 1.0, "fail": 0.0},- model="gpt-4.1",- **kwargs,- )---class QuoteFidelity(ScorerWithPartial):- """Share of quoted spans that a single customer message contains verbatim.-- Scored on raw model output rather than the verified summary, so prompt drift stays visible- even though strip_unverifiable_quotes would remove the marks in production.- """-- def _run_eval_sync(self, output, expected, **kwargs):- turns = customer_turns(_to_messages(kwargs["input"]))- spans = quoted_spans(output or "")- if not spans:- return Score(name=self._name(), score=None, metadata={"reason": "no quoted spans"})- bad = unverifiable_quotes(output, turns)- return Score(- name=self._name(),- score=(len(spans) - len(bad)) / len(spans),- metadata={"quotes": len(spans), "unverifiable": bad},- )---def call_summarizer(demo_org_team_user):- async def callable(conversation: list[dict[str, str]]) -> str:- transcript = render_transcript(_to_messages(conversation))- messages_list: list[SystemMessage | LangchainHumanMessage] = [- SystemMessage(content=SUPPORT_SUMMARIZER_SYSTEM_PROMPT),- LangchainHumanMessage(- content=f"<transcript>\n{transcript}\n</transcript>\n\n{SUPPORT_SUMMARIZER_USER_PROMPT}"- ),- ]- model = MaxChatAnthropic(- model="claude-sonnet-5",- streaming=False,- user=demo_org_team_user[2],- team=demo_org_team_user[1],- max_tokens=2048,- thinking={"type": "disabled"},- billable=False,- inject_context=False,- )- response = await model.ainvoke(messages_list)- content = response.content- if isinstance(content, list):- content = "".join(str(item) for item in content)- return content-- return callable---async def eval_ticket_summary(call_summarizer, pytestconfig):- await MaxPublicEval(- experiment_name="ticket_summary",- task=call_summarizer,- scores=[TicketSummaryQuality(), QuoteFidelity()],- data=[- EvalCase(- input=[- {- "role": "human",- "content": "can you add a way to show the spend column in something other than dollars? our finance team works in euros",- },- {- "role": "assistant",- "content": "The best way to get this in front of the team is the `/ticket` command right here. You can also post it publicly so others can upvote it.",- },- {"role": "human", "content": "/ticket"},- ],- expected="A short summary quoting the customer's request to show spend in a currency other than dollars. Nothing about PostHog AI pointing them at /ticket or at posting publicly, which is not the issue.",- ),- EvalCase(- input=[- {- "role": "human",- "content": "I mistakenly approved a change that was allready done on another branch, and I rolled it back myself. can the charge be looked at",- },- {- "role": "assistant",- "content": "That relates to Signals, where you are charged per change. If one does not meet the bar it can be refunded, you just need to contact support.",- },- {- "role": "human",- "content": "/ticket I switched on the inbox and self drive last week. I mistakinly pointed it at our tracker and a change got approved that was allready done elsewhere. I rolled it back. I would like to ask about getting the charge refunded.",- },- ],- expected="A refund request for a per-change Signals charge, quoting the customer. Their spellings mistakenly, mistakinly and allready must survive exactly wherever quoted, and no quote may mix words from their two separate messages.",- ),- EvalCase(- input=[- {- "role": "human",- "content": "our managed reverse proxy proxy.example.com has started failing. the certificate panel says \u201cCertificate not ready yet, state: awaiting_validation.\u201d the CNAME and CAA entries and the HTTP-01 check all passed before. I tore the proxy down and set it up again once already and validation is still stuck.",- },- {- "role": "assistant",- "content": "I cannot act on PostHog infrastructure directly. Worth checking your DNS record is set to DNS only rather than proxied, since that breaks the HTTP-01 check.",- },- {"role": "human", "content": "/ticket"},- ],- expected="The proxy hostname, the awaiting_validation certificate state quoted from the customer, that CNAME, CAA and HTTP-01 passed before, and that they already rebuilt the proxy once. PostHog AI's DNS only suggestion must not appear as something the customer said or checked.",- ),- EvalCase(- input=[- {- "role": "human",- "content": 'where do I find the thing you mentioned, "Data management and then Events"',- },- {- "role": "assistant",- "content": "It is under Data management in the left sidebar, which opens the Events tab by default.",- },- {- "role": "human",- "content": "im on the Session replay page and the newest recording is mine and it shows shows an Austrian flag rather than German. those are different countries even if people mix them up. please sort it out.",- },- {- "role": "assistant",- "content": "This is a GeoIP detection issue. Either a VPN is in the path, or the GeoIP database has your IP block mapped incorrectly.",- },- {- "role": "human",- "content": "/ticket hi support, im getting Austrian flags where I expect German ones, testing on example.com. no proxy or vpn here and I assumed it reads my IP in Hamburg. why is the recording list showing the wrong one. makes me wonder if the rst of the flags are guesswork too.",- },- ],- expected="Only the wrong country flag on session recordings. The opening turn about finding Data management is not the issue and should not appear. The customer's im, shows shows and rst must survive verbatim wherever quoted.",- ),- EvalCase(- input=[- {- "role": "human",- "content": '"This connection uses Widgetly API v1, which the provider no longer supports. Contact PostHog support to move it to v2 before syncing halts."\n\nreaching out to get that moved!',- },- {- "role": "assistant",- "content": "The best route is in-app support, or the `/ticket` command right here in this chat.",- },- {"role": "human", "content": "/ticket"},- ],- expected="A request to move a warehouse connection off the unsupported vendor API v1 to v2, quoting the product warning the customer pasted. The same fact must not be restated as three separate detail lines.",- ),- EvalCase(- input=[- {- "role": "human",- "content": "how do I get the numeric ids for people by name? building an automation for when work lands on jo or on me",- },- {- "role": "assistant",- "content": "Pulled them from the assignment history: Jo is 100201 and you are 100202.",- },- {- "role": "human",- "content": "8 minutes ago\tERROR\t\n7bd10099\nAutomation failed: undefined at Move ticket to Open from Closed. Fired by Event: $conversation_message_received\n\nwhat is this telling me?",- },- {- "role": "assistant",- "content": "It means the automation step is making an authenticated call back into PostHog but your project has no secret API token set. This may be something PostHog needs to configure, or it could be a bug in automations.",- },- {- "role": "human",- "content": "any idea where I would set that? I had a look and came up empty",- },- {"role": "assistant", "content": "I cannot find a documented setting for it."},- {"role": "human", "content": "/ticket"},- ],- expected="The automation error text quoted from the customer, the id 7bd10099, and that they looked for the setting and came up empty. It must not assert this is a bug in automations, since only PostHog AI speculated that.",- ),- EvalCase(- input=[- {"role": "human", "content": "bug report - https://example.net/clip/7f2a91"},- {- "role": "assistant",- "content": "I cannot open external links. Could you describe the bug, or paste any error text?",- },- {"role": "human", "content": "/ticket"},- {- "role": "assistant",- "content": "PostHog AI Support Ticket Summary:\n\n**Issue:** The user reported a bug via a link and asked PostHog AI to pass it on. No description of the actual bug was given.\n\n**Status:** PostHog AI cannot open external links and asked the user to describe the bug in text.",- },- {"role": "human", "content": 'bug - panel jitters rapidly on the "Summary" tab'},- {- "role": "assistant",- "content": "Got it. Run `/ticket` again and it will include this context.",- },- {"role": "human", "content": "/ticket"},- ],- expected="The jittering panel on the Summary tab, quoted from the customer. The earlier PostHog AI Support Ticket Summary in the conversation is PostHog AI's own output and must not be treated as something the customer said.",- ),- EvalCase(- input=[- {- "role": "human",- "content": "we hit the cap a couple of days ago and just now put a card on and raised it. do the events from those days come through now?",- },- {- "role": "assistant",- "content": "No. Events arriving while a billing limit is reached are dropped at ingestion and cannot be recovered, even after the limit is raised.",- },- {"role": "human", "content": "id like to email support about it"},- {- "role": "assistant",- "content": "Use the `/ticket` command here and it will create one with the context.",- },- {"role": "human", "content": "/ticket"},- ],- expected="The customer asking whether events dropped while a billing limit was reached arrive after adding a card. It must record that the customer was already told those events cannot be recovered, since support needs that before replying.",- ),- EvalCase(- input=[- {- "role": "human",- "content": "puedes ayudarme a abrir un tikete? ahora mismo la fuente no carga, solo muestra un error del servidor",- },- {- "role": "assistant",- "content": "Claro. Para crear un ticket, usa el comando `/ticket` en este chat.",- },- {- "role": "human",- "content": "al abrir la pagina solo sale error del servidor: Load failed: A server error occured",- },- {- "role": "assistant",- "content": "Entendido, escribe `/ticket` y se creara con esta informacion.",- },- {"role": "human", "content": "/ticket"},- ],- expected="A server error when loading the data warehouse sources page. The error text must be quoted with the customer's own spelling occured, not corrected to occurred.",- ),- EvalCase(- input=[- {- "role": "human",- "content": "for identify I am using a token with the phs_ shape and I get a 403 when I use it for support. ask me questions to narrow it down",- },- {- "role": "assistant",- "content": "The support widget verifies identity with HMAC-SHA256. A 403 usually means signature verification failed. How are you passing the identity?",- },- {- "role": "human",- "content": "I call .setIdentity on the client and the HMAC comes from our backend. the token I used has featureflag read scope, since the one the widget settings page offers cannot be created. they line up, see\n\ncurl 'https://staging.example.com/api/conversations/v1/widget/message' -H 'content-type: application/json' -b '_ga=GA1.1.0000000000.0000000000; app-auth-token=base64-ZmFrZS1ldmFsLXRva2VuLXZhbHVlLWRvLW5vdC11c2U'",- },- {- "role": "assistant",- "content": "The HMAC has to be signed with the project's secret token, not a scoped API key.",- },- {"role": "human", "content": "/ticket"},- ],- expected="A 403 from support widget identity verification, that the HMAC is generated on their backend, and that they used a featureflag-read-scoped token because the widget settings one could not be created. The request they pasted is supporting detail, not the issue itself.",- ),- ],- pytestconfig=pytestconfig,- )diff --git a/ee/hogai/eval/ci/eval_trends.py b/ee/hogai/eval/ci/eval_trends.pydeleted file mode 100644index 96a5851f4136..000000000000--- a/ee/hogai/eval/ci/eval_trends.py+++ /dev/null@@ -1,467 +0,0 @@-from datetime import datetime--import pytest--from braintrust import EvalCase--from posthog.schema import (- AssistantEventMultipleBreakdownFilterType,- AssistantGenericMultipleBreakdownFilter,- AssistantTrendsBreakdownFilter,- AssistantTrendsEventsNode,- AssistantTrendsFilter,- AssistantTrendsQuery,- NodeKind,- TrendsFormulaNode,-)--from ..base import MaxPublicEval-from ..scorers import PlanAndQueryOutput, PlanCorrectness, QueryAndPlanAlignment, QueryKindSelection, TimeRangeRelevancy--TRENDS_CASES = [- EvalCase(- input="Show the $pageview trend",- expected=PlanAndQueryOutput(- plan="""-Events:-- $pageview- - math operation: total count-""",- query=AssistantTrendsQuery(- dateRange={"date_from": "-30d", "date_to": None},- filterTestAccounts=True,- interval="day",- trendsFilter=AssistantTrendsFilter(- display="ActionsLineGraph",- showLegend=True,- ),- series=[- AssistantTrendsEventsNode(- event="$pageview",- math="total",- properties=None,- )- ],- ),- ),- ),- EvalCase(- input="What is our MAU?",- expected=PlanAndQueryOutput(- plan="""-Events:-- All events- - math operation: unique users--Time period: last 30 days-No interval-""",- query=AssistantTrendsQuery(- dateRange={"date_from": "-30d", "date_to": None},- filterTestAccounts=True,- trendsFilter=AssistantTrendsFilter(- display="BoldNumber",- showLegend=True,- ),- series=[- AssistantTrendsEventsNode(- event=None,- math="dau", # "dau" name is a legacy misnomer, it actually just means "unique users"- properties=None,- )- ],- ),- ),- ),- EvalCase(- input="can you compare how many Chrome vs Safari users uploaded a file in the last 30d?",- expected=PlanAndQueryOutput(- plan="""-Events:-- uploaded_file- - math operation: unique users- - property filter 1:- - entity: event- - property name: $browser- - property type: String- - operator: equals- - property value: Chrome-- uploaded_file- - math operation: unique users- - property filter 1:- - entity: event- - property name: $browser- - property type: String- - operator: equals- - property value: Safari-""",- query=AssistantTrendsQuery(- dateRange={"date_from": "-30d", "date_to": None},- filterTestAccounts=True,- interval="day",- trendsFilter=AssistantTrendsFilter(- display="ActionsLineGraph",- showLegend=True,- ),- breakdownFilter=AssistantTrendsBreakdownFilter(- breakdowns=[- AssistantGenericMultipleBreakdownFilter(- property="$browser",- type=AssistantEventMultipleBreakdownFilterType.EVENT,- )- ]- ),- series=[- AssistantTrendsEventsNode(- event="uploaded_file",- math="total",- properties=[- {- "key": "$browser",- "value": ["Chrome", "Safari"],- "operator": "exact",- "type": "event",- },- ],- )- ],- ),- ),- ),- EvalCase(- input="i want to see a ratio of identify divided by page views",- expected=PlanAndQueryOutput(- plan="""-Events:-- $identify- - math operation: total count-- $pageview- - math operation: total count--Formula:-`A/B`, where `A` is the total count of `$identify` and `B` is the total count of `$pageview`-""",- query=AssistantTrendsQuery(- dateRange={"date_from": "-30d", "date_to": None},- filterTestAccounts=True,- interval="day",- trendsFilter=AssistantTrendsFilter(- display="ActionsLineGraph", showLegend=True, formulaNodes=[TrendsFormulaNode(formula="A/B")]- ),- series=[- AssistantTrendsEventsNode(- event="$identify",- math="total",- properties=None,- ),- AssistantTrendsEventsNode(- event="$pageview",- math="total",- properties=None,- ),- ],- ),- ),- ),- EvalCase(- input="what is our average session duration?",- expected=PlanAndQueryOutput(- plan="""-Events:-- All Events- - math operation: average by `$session_duration`-""",- query=AssistantTrendsQuery(- dateRange={"date_from": "-30d", "date_to": None},- filterTestAccounts=True,- interval="day",- trendsFilter=AssistantTrendsFilter(- display="ActionsLineGraph",- showLegend=True,- ),- series=[- AssistantTrendsEventsNode(- event="$all_events",- math="avg",- math_property="$session_duration",- properties=None,- )- ],- ),- ),- ),- EvalCase(- input="how many $pageviews with unique sessions did we have?",- expected=PlanAndQueryOutput(- plan="""-Events:-- $pageview- - math operation: unique sessions--Time period: last month-Time interval: day-""",- query=AssistantTrendsQuery(- dateRange={"date_from": "-30d", "date_to": None},- filterTestAccounts=True,- interval="day",- trendsFilter=AssistantTrendsFilter(- display="ActionsLineGraph",- showLegend=True,- ),- series=[- AssistantTrendsEventsNode(- event="$pageview",- math="unique_session",- properties=None,- )- ],- ),- ),- ),- EvalCase(- input="How often do users view the website in this January?",- expected=PlanAndQueryOutput(- plan="""-Events:-- $pageview- - math operation: total count--Time period: this January-Time interval: day-""",- query=AssistantTrendsQuery(- dateRange={- "date_from": f"{datetime.now().year}-01-01",- "date_to": f"{datetime.now().year}-01-31",- },- filterTestAccounts=True,- interval="day",- trendsFilter=AssistantTrendsFilter(- display="ActionsLineGraph",- showLegend=True,- ),- series=[- AssistantTrendsEventsNode(- event="$pageview",- math="total",- properties=None,- )- ],- ),- ),- ),- EvalCase(- input="How many paid bill events have occurred with amount more than 20 usd in this January?",- expected=PlanAndQueryOutput(- plan="""-Events:-- paid_bill- - math operation: total count- - property filter 1:- - entity: event- - property name: amount_usd- - property type: Numeric- - operator: greater than- - property value: 20--Time period: this January-Time interval: day-""",- query=AssistantTrendsQuery(- dateRange={- "date_from": f"{datetime.now().year}-01-01",- "date_to": f"{datetime.now().year}-01-31",- },- filterTestAccounts=True,- interval="day",- trendsFilter=AssistantTrendsFilter(- display="ActionsLineGraph",- showLegend=True,- ),- series=[- AssistantTrendsEventsNode(- event="paid_bill",- math="total",- properties=[- {- "key": "amount_usd",- "value": 20,- "operator": "gt",- "type": "event",- },- ],- )- ],- ),- ),- ),- EvalCase(- input="on hedgebox.net, what is the % of mac os x users",- expected=PlanAndQueryOutput(- plan="""-Events:-- All events- - math operation: unique users- - property filter 1:- - entity: event- - property name: $host- - property type: String- - operator: equals- - property value: hedgebox.net-- All events- - math operation: unique users- - property filter 1:- - entity: event- - property name: $host- - property type: String- - operator: equals- - property value: hedgebox.net- - property filter 2:- - entity: event- - property name: $os- - property type: String- - operator: equals- - property value: Mac OS X--Formula:-`B/A * 100`, where `A` is total unique users on hedgebox.net and `B` is unique users on hedgebox.net with Mac OS X-""",- query=AssistantTrendsQuery(- dateRange={"date_from": "-30d", "date_to": None},- filterTestAccounts=True,- interval="day",- trendsFilter=AssistantTrendsFilter(- display="BoldNumber", showLegend=True, formulaNodes=[TrendsFormulaNode(formula="B/A * 100")]- ),- series=[- AssistantTrendsEventsNode(- event=None,- math="dau",- properties=[- {- "key": "$host",- "value": "hedgebox.net",- "operator": "icontains",- "type": "event",- },- ],- ),- AssistantTrendsEventsNode(- event=None,- math="dau",- properties=[- {- "key": "$host",- "value": "hedgebox.net",- "operator": "icontains",- "type": "event",- },- {- "key": "$os",- "value": "Mac OS X",- "operator": "exact",- "type": "event",- },- ],- ),- ],- ),- ),- ),- # Specific, uppercase event to use, which doesn't exist in the actual data (but the user quotes it specifically anyway)- EvalCase(- input="How many 'Onboarding Completed' events have we had in January 2025?",- expected=PlanAndQueryOutput(- plan="""-Logic:-- Scan the events table for records where the event name exactly equals “Onboarding Completed”.-- Restrict to those with timestamp ≥ 2025-01-01 00:00:00 and ≤ 2025-01-31 23:59:59.-- Aggregate by counting the total number of matching rows.--Sources:-- events- - filter: event = “Onboarding Completed”- - filter: timestamp between “2025-01-01” and “2025-01-31”- - aggregation: COUNT(*)--Query kind:-- Trends- - single series (EventsNode) with math = total- - dateRange: { date_from: “2025-01-01”, date_to: “2025-01-31” }- - display: ActionsLineGraph (to have the requested number for the month, but also see any trends)-""",- query=AssistantTrendsQuery(- dateRange={"date_from": "2025-01-01", "date_to": "2025-01-31"},- filterTestAccounts=True,- interval="day",- trendsFilter=AssistantTrendsFilter(display="ActionsLineGraph"),- series=[- AssistantTrendsEventsNode(- event="Onboarding Completed",- math="total",- properties=None,- )- ],- ),- ),- ),-]---async def eval_trends(call_root_for_insight_generation, pytestconfig):- await MaxPublicEval(- experiment_name="trends",- task=call_root_for_insight_generation,- scores=[- QueryKindSelection(expected=NodeKind.TRENDS_QUERY),- PlanCorrectness(- query_kind=NodeKind.TRENDS_QUERY,- evaluation_criteria="""-1. A plan must define at least one event and a math type, but it is not required to define any filters, breakdowns, or formulas.-2. Compare events, properties, math types, and property values of 'expected plan' and 'output plan'. Do not penalize if the actual output does not include a timeframe.-3. Check if the combination of events, properties, and property values in 'output plan' can answer the user's question according to the 'expected plan'.-4. Check if the math types in 'output plan' match those in 'expected plan.' If the aggregation type is specified by a property, user, or group in 'expected plan', the same property, user, or group must be used in 'generated plan'.-5. If 'expected plan' contains a breakdown, check if 'output plan' contains a similar breakdown, and heavily penalize if the breakdown is not present or different.-6. If 'expected plan' contains a formula, check if 'output plan' contains a similar formula, and heavily penalize if the formula is not present or different.-7. Heavily penalize if the 'output plan' contains any excessive output not present in the 'expected plan'. For example, the `is set` operator in filters should not be used unless the user explicitly asks for it.-8. If the user's goal is to compare specific breakdown values, it's fine for the generated plan to split each breakdown value into a separate series, even if the expected plan achieves the same thing with a breakdown.-""",- ),- QueryAndPlanAlignment(- query_kind=NodeKind.TRENDS_QUERY,- query_model=AssistantTrendsQuery,- evaluation_criteria="""-1. Events alignment: Verify that all events mentioned in the plan are correctly represented in the query's `series` array. For "All events", the `event` field should be `null`.-2. Series math: Ensure the math operation for each event in the query matches what's specified in the plan, for example:- - "total count" → `math: "total"`- - "unique users" → `math: "dau"` (legacy naming)- - "unique sessions" → `math: "unique_session"`- - "average/median/p95/etc. of [property]" → `math: "avg"/`"median"`/`"p95"`/etc. with correct `math_property`- - Verify `math_property` is set only when required by the math operation-3. Property filters: Check that event properties and filters from the plan are correctly implemented:- - Property names, values, and operators must match exactly- - Multiple property values should be represented as arrays in the `value` field- - Filter types (event, person, group) must be correct-4. Breakdowns: Verify breakdown implementation matches the plan:- - Breakdown property names must match exactly- - Breakdown types (event, person, group) must be correct- - Multiple breakdowns should be represented in the `breakdowns` array-5. Formulas: For formula-based queries:- - Check that the number of series matches the formula requirements- - Verify that series are ordered correctly to match formula variables (A, B, C, etc.)- - Formula logic should align with plan description-6. Display type: Verify appropriate display type selection:- - Single value metrics (like MAU) can use `"BoldNumber"`, but often it's still better to use `"ActionsLineGraph"` for trend analysis- - Trend analyses should use `"ActionsLineGraph"`- - Display type should match the nature of the query described in the plan-9. Unnecessary fields: Penalize inclusion of fields not mentioned in the plan or that don't align with the query intent.-10. Missing implementation: Heavily penalize when key plan elements are completely missing from the generated query (e.g., missing breakdowns, wrong math operations, incorrect event selection).-""",- ),- TimeRangeRelevancy(query_kind=NodeKind.TRENDS_QUERY),- ],- data=TRENDS_CASES,- pytestconfig=pytestconfig,- )diff --git a/ee/hogai/eval/ci/eval_ui_context.py b/ee/hogai/eval/ci/eval_ui_context.pydeleted file mode 100644index e98b54cd6847..000000000000--- a/ee/hogai/eval/ci/eval_ui_context.py+++ /dev/null@@ -1,221 +0,0 @@-import pytest--from braintrust import EvalCase--from posthog.schema import (- AssistantMessage,- AssistantToolCall,- HumanMessage,- MaxActionContext,- MaxEventContext,- MaxUIContext,-)--from posthog.models.team.team import Team--from products.actions.backend.models.action import Action-from products.posthog_ai.backend.models.assistant import Conversation--from ee.hogai.chat_agent import AssistantGraph-from ee.hogai.django_checkpoint.checkpointer import DjangoCheckpointer-from ee.hogai.utils.types import AssistantNodeName, AssistantState--from ..base import MaxPublicEval-from ..scorers import ToolRelevance---def call_root_with_ui_context(demo_org_team_user):- """Fixture to test root node with UI context containing actions and events"""- graph = (- AssistantGraph(demo_org_team_user[1], demo_org_team_user[2])- .add_edge(AssistantNodeName.START, AssistantNodeName.ROOT)- .add_root(lambda state: AssistantNodeName.END)- # TRICKY: We need to set a checkpointer here because async tests create a new event loop.- .compile(checkpointer=DjangoCheckpointer())- )-- async def callable(input_dict: dict) -> AssistantMessage:- messages = input_dict["messages"]- ui_context = input_dict.get("ui_context")- conversation = await Conversation.objects.acreate(team=demo_org_team_user[1], user=demo_org_team_user[2])- initial_state = AssistantState(- messages=[HumanMessage(content=messages, ui_context=ui_context)] if isinstance(messages, str) else messages- )- raw_state = await graph.ainvoke(initial_state, {"configurable": {"thread_id": conversation.id}})- state = AssistantState.model_validate(raw_state)- assert isinstance(state.messages[-1], AssistantMessage)- return state.messages[-1]-- return callable---def sample_action(demo_org_team_user):- """Create a sample action for testing"""- team: Team = demo_org_team_user[1]- action = Action.objects.create(- team=team,- name="Purchase Completed",- description="User completed a purchase transaction",- )- return action---async def eval_ui_context_actions(call_root_with_ui_context, sample_action, pytestconfig):- """Test that actions in UI context are properly used in RAG context retrieval"""- await MaxPublicEval(- experiment_name="ui_context_actions",- task=call_root_with_ui_context,- scores=[- ToolRelevance(semantic_similarity_args={"query_description"}),- ],- data=[- EvalCase(- input={- "messages": "Show me trends for this action",- "ui_context": MaxUIContext(- actions=[- MaxActionContext(- id=sample_action.id,- name=sample_action.name,- description=sample_action.description,- )- ]- ),- },- expected=AssistantToolCall(- id="1",- name="create_insight",- args={- "query_kind": "trends",- "query_description": "Show trends for purchase completions using the Purchase Completed action",- },- ),- ),- # Test with multiple actions- EvalCase(- input={- "messages": "Create a funnel using these actions",- "ui_context": MaxUIContext(- actions=[- MaxActionContext(- id=sample_action.id,- name="Purchase Completed",- description="User completed a purchase transaction",- ),- MaxActionContext(- id=sample_action.id + 1,- name="User Signup",- description="User created a new account",- ),- ]- ),- },- expected=AssistantToolCall(- id="2",- name="create_insight",- args={- "query_kind": "funnel",- "query_description": "Create a funnel from User Signup action to Purchase Completed action",- },- ),- ),- ],- pytestconfig=pytestconfig,- )---async def eval_ui_context_events(call_root_with_ui_context, pytestconfig):- """Test that events in UI context are properly used in taxonomy agent"""- await MaxPublicEval(- experiment_name="ui_context_events",- task=call_root_with_ui_context,- scores=[- ToolRelevance(semantic_similarity_args={"query_description"}),- ],- data=[- EvalCase(- input={- "messages": "Show me trends for this event",- "ui_context": MaxUIContext(- events=[- MaxEventContext(- id="1",- name="checkout_started",- description="User initiated the checkout process",- )- ]- ),- },- expected=AssistantToolCall(- id="1",- name="create_insight",- args={- "query_kind": "trends",- "query_description": "Show trends for checkout_started events",- },- ),- ),- EvalCase(- input={- "messages": "How many users have triggered these events",- "ui_context": MaxUIContext(- events=[- MaxEventContext(- id="1",- name="feature_used",- description="User interacted with a premium feature",- ),- MaxEventContext(- id="2",- name="content_shared",- description="User shared content on social media",- ),- ]- ),- },- expected=AssistantToolCall(- id="2",- name="create_insight",- args={- "query_kind": "trends",- "query_description": "Show trends for feature_used and content_shared events",- },- ),- ),- # Test mixed context with both events and actions- EvalCase(- input={- "messages": "Create a funnel using these event and action",- "ui_context": MaxUIContext(- events=[- MaxEventContext(- id="1",- name="button_clicked",- description="User clicked a CTA button",- )- ],- actions=[- MaxActionContext(- id=1,- name="Conversion Goal",- description="User reached conversion milestone",- )- ],- ),- },- expected=AssistantToolCall(- id="3",- name="create_insight",- args={- "query_kind": "funnel",- "query_description": "Create a funnel from button_clicked event to Conversion Goal action",- },- ),- ),- ],- pytestconfig=pytestconfig,- )diff --git a/ee/hogai/eval/ci/max_tools/__init__.py b/ee/hogai/eval/ci/max_tools/__init__.pydeleted file mode 100644index e69de29bb2d1..000000000000diff --git a/ee/hogai/eval/ci/max_tools/eval_create_experiment_tool.py b/ee/hogai/eval/ci/max_tools/eval_create_experiment_tool.pydeleted file mode 100644index 2344db7a8998..000000000000--- a/ee/hogai/eval/ci/max_tools/eval_create_experiment_tool.py+++ /dev/null@@ -1,239 +0,0 @@-"""Evaluations for CreateExperimentTool."""--import uuid-from typing import Any, TypedDict--import pytest--from autoevals.llm import LLMClassifier-from braintrust import EvalCase, Score-from langchain_core.runnables import RunnableConfig--from posthog.schema import AgentMode, AssistantMessage, AssistantToolCallMessage, HumanMessage--from products.posthog_ai.backend.models.assistant import Conversation--from ee.hogai.chat_agent import AssistantGraph-from ee.hogai.django_checkpoint.checkpointer import DjangoCheckpointer-from ee.hogai.eval.base import MaxPublicEval-from ee.hogai.utils.types import AssistantNodeName, AssistantState---class EvalInput(TypedDict):- input: str---EXPERIMENT_OPERATION_ACCURACY_PROMPT = """-Evaluate if the agent correctly created an experiment.--<user_request>-{{input.input}}-</user_request>--<expected>-{{#expected}}-Experiment created: {{expected.experiment_created}}-{{#expected.experiment_name_contains}}-Experiment name should contain: {{expected.experiment_name_contains}}-{{/expected.experiment_name_contains}}-{{#expected.experiment_type}}-Experiment type: {{expected.experiment_type}}-{{/expected.experiment_type}}-{{#expected.variant_count}}-Expected number of variants: {{expected.variant_count}}-{{/expected.variant_count}}-{{#expected.has_uneven_split}}-Expected uneven variant split: {{expected.has_uneven_split}}-{{/expected.has_uneven_split}}-{{/expected}}-</expected>--<actual_output>-Feature flag tool called: {{output.flag_tool_called}}-Feature flag tool args: {{output.flag_tool_args}}-Feature flag tool output: {{output.flag_tool_output}}-Create experiment tool called: {{output.experiment_tool_called}}-Create experiment args: {{output.experiment_tool_args}}-Create experiment output: {{output.experiment_tool_output}}-Error: {{output.error}}-</actual_output>--Evaluate:-1. Did the agent call create_experiment?-2. Was the experiment created successfully (no error in output)?-3. Does the experiment name/configuration match the user's request?-4. If variant count was specified, does the feature flag have the correct number of variants?-5. If uneven split was specified, were the variant percentages set accordingly?--Choose: pass (all requirements met) or fail (any requirement not met)-""".strip()---class ExperimentOperationAccuracy(LLMClassifier):- """Binary LLM judge for full agent experiment creation (tests trajectory)."""-- def _normalize(self, output: dict | None, expected: dict | None) -> tuple[dict, dict]:- normalized_output = {- "experiment_tool_called": None,- "experiment_tool_args": None,- "experiment_tool_output": None,- "error": None,- **(output or {}),- }- normalized_expected = {**(expected or {})}- return normalized_output, normalized_expected-- async def _run_eval_async(self, output: dict | None, expected: dict | None = None, **kwargs):- if not output:- return Score(name=self._name(), score=0.0, metadata={"reason": "No output provided"})- normalized_output, normalized_expected = self._normalize(output, expected)- return await super()._run_eval_async(normalized_output, normalized_expected, **kwargs)-- def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs):- if not output:- return Score(name=self._name(), score=0.0, metadata={"reason": "No output provided"})- normalized_output, normalized_expected = self._normalize(output, expected)- return super()._run_eval_sync(normalized_output, normalized_expected, **kwargs)-- def __init__(self, **kwargs):- super().__init__(- name="experiment_operation_accuracy",- prompt_template=EXPERIMENT_OPERATION_ACCURACY_PROMPT,- choice_scores={"pass": 1.0, "fail": 0.0},- model="gpt-5.2",- max_tokens=2048,- reasoning_effort="medium",- **kwargs,- )---def _extract_experiment_result(state: AssistantState) -> dict[str, Any]:- """Extract experiment creation result from final state."""- result: dict[str, Any] = {- "experiment_tool_called": None,- "experiment_tool_args": None,- "experiment_tool_output": None,- "flag_tool_called": None,- "flag_tool_args": None,- "flag_tool_output": None,- "error": None,- }-- create_experiment_tool_call_id: str | None = None- create_flag_tool_call_id: str | None = None-- for msg in state.messages:- if isinstance(msg, AssistantMessage) and msg.tool_calls:- for tool_call in msg.tool_calls:- if tool_call.name == "create_experiment":- result["experiment_tool_called"] = "create_experiment"- result["experiment_tool_args"] = tool_call.args- create_experiment_tool_call_id = tool_call.id- elif tool_call.name == "create_feature_flag":- result["flag_tool_called"] = "create_feature_flag"- result["flag_tool_args"] = tool_call.args- create_flag_tool_call_id = tool_call.id-- for msg in state.messages:- if isinstance(msg, AssistantToolCallMessage):- if msg.tool_call_id == create_experiment_tool_call_id:- result["experiment_tool_output"] = msg.content- if msg.content and ("error" in msg.content.lower() or "failed" in msg.content.lower()):- result["error"] = msg.content- elif msg.tool_call_id == create_flag_tool_call_id:- result["flag_tool_output"] = msg.content-- return result---def call_agent_for_experiment(demo_org_team_user):- """Run full agent graph in FLAGS mode with natural language experiment requests."""- _, team, user = demo_org_team_user-- graph = (- AssistantGraph(team, user)- .add_edge(AssistantNodeName.START, AssistantNodeName.ROOT)- .add_root()- .compile(checkpointer=DjangoCheckpointer())- )-- async def callable(input: EvalInput) -> dict:- conversation = await Conversation.objects.acreate(team=team, user=user)- initial_state = AssistantState(- messages=[HumanMessage(content=input["input"])],- agent_mode=AgentMode.FLAGS,- )- config = RunnableConfig(configurable={"thread_id": conversation.id}, recursion_limit=48)- raw_state = await graph.ainvoke(initial_state, config)- state = AssistantState.model_validate(raw_state)- return _extract_experiment_result(state)-- yield callable---async def eval_create_experiment_llm(call_agent_for_experiment, pytestconfig):- """Test experiment creation via full agent with natural language prompts."""- unique_suffix = uuid.uuid4().hex[:6]-- await MaxPublicEval(- experiment_name="create_experiment_llm",- task=call_agent_for_experiment,- scores=[ExperimentOperationAccuracy()],- data=[- EvalCase(- input=EvalInput(- input=f"Create an A/B test experiment called 'Pricing Test {unique_suffix}' to test our new pricing page"- ),- expected={- "experiment_created": True,- "experiment_name_contains": "pricing",- },- metadata={"test_type": "full_workflow"},- ),- EvalCase(- input=EvalInput(- input=f"Set up an experiment named 'Checkout Flow {unique_suffix}' to test a new checkout experience"- ),- expected={- "experiment_created": True,- "experiment_name_contains": "checkout",- },- metadata={"test_type": "full_workflow"},- ),- EvalCase(- input=EvalInput(- input=f"I want to run an A/B test on our homepage hero section, call it 'Hero Test {unique_suffix}'"- ),- expected={- "experiment_created": True,- "experiment_name_contains": "hero",- },- metadata={"test_type": "full_workflow"},- ),- EvalCase(- input=EvalInput(- input=f"Create an experiment called 'Multi-variant CTA {unique_suffix}' with three variants: control, variant_a, and variant_b to test different call-to-action buttons"- ),- expected={- "experiment_created": True,- "experiment_name_contains": "CTA",- "variant_count": 3,- },- metadata={"test_type": "multivariate"},- ),- EvalCase(- input=EvalInput(- input=f"Set up an experiment called 'Gradual Rollout {unique_suffix}' with an 80/20 split between control and test to cautiously test a new onboarding flow"- ),- expected={- "experiment_created": True,- "experiment_name_contains": "rollout",- "has_uneven_split": True,- },- metadata={"test_type": "uneven_split"},- ),- ],- pytestconfig=pytestconfig,- )diff --git a/ee/hogai/eval/ci/max_tools/eval_create_feature_flag_tool.py b/ee/hogai/eval/ci/max_tools/eval_create_feature_flag_tool.pydeleted file mode 100644index 40703120a199..000000000000--- a/ee/hogai/eval/ci/max_tools/eval_create_feature_flag_tool.py+++ /dev/null@@ -1,261 +0,0 @@-"""Evaluations for CreateFeatureFlagTool."""--import uuid-from typing import Any, TypedDict--import pytest--from autoevals.llm import LLMClassifier-from autoevals.partial import ScorerWithPartial-from autoevals.ragas import AnswerSimilarity-from braintrust import EvalCase, Score-from langchain_core.runnables import RunnableConfig--from posthog.schema import AgentMode, AssistantMessage, AssistantToolCallMessage, HumanMessage--from products.posthog_ai.backend.models.assistant import Conversation--from ee.hogai.chat_agent import AssistantGraph-from ee.hogai.django_checkpoint.checkpointer import DjangoCheckpointer-from ee.hogai.eval.base import MaxPublicEval-from ee.hogai.utils.types import AssistantNodeName, AssistantState---class FeatureFlagOutputScorer(ScorerWithPartial):- """Custom scorer for feature flag tool output that combines semantic similarity for text and exact matching for numbers/booleans."""-- def __init__(self, semantic_fields: set[str] | None = None, **kwargs):- super().__init__(**kwargs)- self.semantic_fields = semantic_fields or {"message"}-- def _run_eval_sync(self, output: dict, expected: dict, **kwargs):- if not expected:- return Score(name=self._name(), score=None, metadata={"reason": "No expected value provided"})- if not output:- return Score(name=self._name(), score=0.0, metadata={"reason": "No output provided"})-- total_fields = len(expected)- if total_fields == 0:- return Score(name=self._name(), score=1.0)-- score_per_field = 1.0 / total_fields- total_score = 0.0- metadata = {}-- for field_name, expected_value in expected.items():- actual_value = output.get(field_name)-- if field_name in self.semantic_fields:- # Use semantic similarity for text fields- if actual_value is not None and expected_value is not None:- similarity_scorer = AnswerSimilarity(model="text-embedding-3-small")- result = similarity_scorer.eval(output=str(actual_value), expected=str(expected_value))- field_score = result.score * score_per_field- total_score += field_score- metadata[f"{field_name}_score"] = result.score- else:- metadata[f"{field_name}_missing"] = True- else:- # Use exact match for numeric/boolean fields- if actual_value == expected_value:- total_score += score_per_field- metadata[f"{field_name}_match"] = True- else:- metadata[f"{field_name}_mismatch"] = {- "expected": expected_value,- "actual": actual_value,- }-- return Score(name=self._name(), score=total_score, metadata=metadata)---class EvalInput(TypedDict):- input: str---FEATURE_FLAG_OPERATION_ACCURACY_PROMPT = """-Evaluate if the agent correctly performed the feature flag creation.--<user_request>-{{input.input}}-</user_request>--<expected>-{{#expected}}-Created: {{expected.created}}-{{#expected.key_contains}}-Flag key should contain: {{expected.key_contains}}-{{/expected.key_contains}}-{{#expected.rollout_percentage}}-Rollout percentage: {{expected.rollout_percentage}}-{{/expected.rollout_percentage}}-{{#expected.has_properties}}-Should have property filters: {{expected.has_properties}}-{{/expected.has_properties}}-{{#expected.has_multivariate}}-Should be multivariate: {{expected.has_multivariate}}-{{/expected.has_multivariate}}-{{#expected.variant_count}}-Variant count: {{expected.variant_count}}-{{/expected.variant_count}}-{{/expected}}-</expected>--<actual_output>-Tool called: {{output.tool_called}}-Tool output: {{output.tool_output}}-Tool args (if any): {{output.tool_args}}-Error: {{output.error}}-</actual_output>--Evaluate:-1. Did the agent call create_feature_flag?-2. Was the flag created successfully (no error in output)?-3. Do the tool args/output match the expected configuration (key, rollout, properties, variants)?--Choose: pass (all requirements met) or fail (any requirement not met)-""".strip()---class FeatureFlagOperationAccuracy(LLMClassifier):- """Binary LLM judge for full agent feature flag creation (tests trajectory)."""-- def _normalize(self, output: dict | None, expected: dict | None) -> tuple[dict, dict]:- normalized_output = {- "tool_called": None,- "tool_output": None,- "tool_args": None,- "error": None,- **(output or {}),- }- normalized_expected = {**(expected or {})}- return normalized_output, normalized_expected-- async def _run_eval_async(self, output: dict | None, expected: dict | None = None, **kwargs):- if not output:- return Score(name=self._name(), score=0.0, metadata={"reason": "No output provided"})- normalized_output, normalized_expected = self._normalize(output, expected)- return await super()._run_eval_async(normalized_output, normalized_expected, **kwargs)-- def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs):- if not output:- return Score(name=self._name(), score=0.0, metadata={"reason": "No output provided"})- normalized_output, normalized_expected = self._normalize(output, expected)- return super()._run_eval_sync(normalized_output, normalized_expected, **kwargs)-- def __init__(self, **kwargs):- super().__init__(- name="feature_flag_operation_accuracy",- prompt_template=FEATURE_FLAG_OPERATION_ACCURACY_PROMPT,- choice_scores={"pass": 1.0, "fail": 0.0},- model="gpt-5.2",- max_tokens=2048,- reasoning_effort="medium",- **kwargs,- )---def _extract_feature_flag_result(state: AssistantState) -> dict[str, Any]:- """Extract feature flag creation result from final state."""- result: dict[str, Any] = {- "tool_called": None,- "tool_output": None,- "tool_args": None,- "error": None,- }-- create_flag_tool_call_id: str | None = None-- for msg in state.messages:- if isinstance(msg, AssistantMessage) and msg.tool_calls:- for tool_call in msg.tool_calls:- if tool_call.name == "create_feature_flag":- result["tool_called"] = "create_feature_flag"- result["tool_args"] = tool_call.args- create_flag_tool_call_id = tool_call.id- break-- for msg in state.messages:- if isinstance(msg, AssistantToolCallMessage) and msg.tool_call_id == create_flag_tool_call_id:- result["tool_output"] = msg.content- if msg.content and ("error" in msg.content.lower() or "invalid" in msg.content.lower()):- result["error"] = msg.content- break-- return result---def call_agent_for_feature_flag(demo_org_team_user):- """Run full agent graph in FLAGS mode with natural language feature flag requests."""- _, team, user = demo_org_team_user-- graph = (- AssistantGraph(team, user)- .add_edge(AssistantNodeName.START, AssistantNodeName.ROOT)- .add_root()- .compile(checkpointer=DjangoCheckpointer())- )-- async def callable(input: EvalInput) -> dict:- conversation = await Conversation.objects.acreate(team=team, user=user)- initial_state = AssistantState(- messages=[HumanMessage(content=input["input"])],- agent_mode=AgentMode.FLAGS,- )- config = RunnableConfig(configurable={"thread_id": conversation.id}, recursion_limit=48)- raw_state = await graph.ainvoke(initial_state, config)- state = AssistantState.model_validate(raw_state)- return _extract_feature_flag_result(state)-- yield callable---async def eval_create_feature_flag_llm(call_agent_for_feature_flag, pytestconfig):- """Test feature flag creation via full agent with natural language prompts."""- unique_suffix = uuid.uuid4().hex[:6]-- await MaxPublicEval(- experiment_name="create_feature_flag_llm",- task=call_agent_for_feature_flag,- scores=[FeatureFlagOperationAccuracy()],- data=[- EvalCase(- input=EvalInput(- input=f"Create a feature flag called 'new-homepage-{unique_suffix}' for testing the new homepage design"- ),- expected={"created": True, "key_contains": "new-homepage"},- metadata={"test_type": "basic_flag"},- ),- EvalCase(- input=EvalInput(- input=f"Create a feature flag 'dark-mode-{unique_suffix}' for dark mode, but keep it inactive"- ),- expected={"created": True, "key_contains": "dark-mode"},- metadata={"test_type": "inactive_flag"},- ),- EvalCase(- input=EvalInput(- input=f"Create a feature flag 'rollout-10-{unique_suffix}' that rolls out to 10% of users"- ),- expected={"created": True, "rollout_percentage": 10},- metadata={"test_type": "rollout_percentage"},- ),- EvalCase(- input=EvalInput(- input=f"Create an A/B test feature flag 'pricing-test-{unique_suffix}' with control and test variants, 50/50 split"- ),- expected={"created": True, "has_multivariate": True, "variant_count": 2},- metadata={"test_type": "ab_test"},- ),- EvalCase(- input=EvalInput(- input=f"Create a feature flag 'company-users-{unique_suffix}' that targets users with email containing @company.com"- ),- expected={"created": True, "has_properties": True},- metadata={"test_type": "property_filter"},- ),- ],- pytestconfig=pytestconfig,- )diff --git a/ee/hogai/eval/ci/max_tools/eval_experiment_summary.py b/ee/hogai/eval/ci/max_tools/eval_experiment_summary.pydeleted file mode 100644index 40b3d5d67251..000000000000--- a/ee/hogai/eval/ci/max_tools/eval_experiment_summary.py+++ /dev/null@@ -1,547 +0,0 @@-"""Evaluations for ExperimentSummaryTool."""--import uuid-from datetime import datetime, timedelta-from typing import Any, TypedDict-from zoneinfo import ZoneInfo--import pytest-from unittest.mock import patch--from autoevals.llm import LLMClassifier-from braintrust import EvalCase, Score-from langchain_core.runnables import RunnableConfig--from posthog.schema import (- AgentMode,- AssistantMessage,- AssistantToolCallMessage,- ExperimentStatsMethod,- Goal,- HumanMessage,- MaxExperimentMetricResult,- MaxExperimentSummaryContext,- MaxExperimentVariantResultBayesian,- MaxExperimentVariantResultFrequentist,-)--from products.experiments.backend.facade.contracts import ExperimentSummaryData-from products.experiments.backend.models.experiment import Experiment-from products.feature_flags.backend.models.feature_flag import FeatureFlag-from products.posthog_ai.backend.models.assistant import Conversation--from ee.hogai.chat_agent import AssistantGraph-from ee.hogai.django_checkpoint.checkpointer import DjangoCheckpointer-from ee.hogai.eval.base import MaxPublicEval-from ee.hogai.utils.types import AssistantNodeName, AssistantState--_SUMMARY_PROMPT = "Summarize experiment {experiment_id}. What do the results show?"---class EvalInput(TypedDict):- input: str- mock_key: str---EXPERIMENT_SUMMARY_ACCURACY_PROMPT = """-You are evaluating whether an AI agent's experiment summary accurately reflects-the data returned by the tools it called.--The agent may call multiple tools (e.g. read_data for experiment metadata and-experiment_results_summary for statistical results). All tool outputs are provided below.--<tool_outputs>-{{output.all_tool_outputs}}-</tool_outputs>--<agent_summary>-{{output.agent_summary}}-</agent_summary>--Check:-1. Every number in the agent's summary must be traceable to one of the tool outputs. No invented or hallucinated figures.-2. Significance status (significant vs not) must be correctly stated for each variant.-3. The agent must not declare a winner when results are not statistically significant.-4. Variant names must match the tool output.-5. When a metric's goal is "Decrease", a reduction in the metric is a positive outcome. The agent must frame lower values as good and not treat them as a regression.-6. When multiple metrics are present (primary and secondary), the agent must mention results from both. It must not ignore a significant secondary metric that contradicts the primary.--Choose: pass (all facts accurate, no hallucinations) or fail (any factual error, hallucinated number, or wrong conclusion)-""".strip()---class ExperimentSummaryAccuracy(LLMClassifier):- """LLM judge for experiment summary factual accuracy."""-- def _normalize(self, output: dict | None) -> dict:- return {- "all_tool_outputs": None,- "agent_summary": None,- "error": None,- **(output or {}),- }-- async def _run_eval_async(self, output: dict | None, expected: dict | None = None, **kwargs):- if not output:- return Score(name=self._name(), score=0.0, metadata={"reason": "No output provided"})- normalized_output = self._normalize(output)- return await super()._run_eval_async(normalized_output, expected, **kwargs)-- def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs):- if not output:- return Score(name=self._name(), score=0.0, metadata={"reason": "No output provided"})- normalized_output = self._normalize(output)- return super()._run_eval_sync(normalized_output, expected, **kwargs)-- def __init__(self, **kwargs):- super().__init__(- name="experiment_summary_accuracy",- prompt_template=EXPERIMENT_SUMMARY_ACCURACY_PROMPT,- choice_scores={"pass": 1.0, "fail": 0.0},- model="gpt-5.2",- max_tokens=2048,- reasoning_effort="medium",- **kwargs,- )---def _extract_summary_result(state: AssistantState) -> dict[str, Any]:- """Extract all tool outputs and agent summary from final state."""- result: dict[str, Any] = {- "all_tool_outputs": None,- "agent_summary": None,- "error": None,- }-- tool_outputs: list[str] = []- for msg in state.messages:- if isinstance(msg, AssistantToolCallMessage) and msg.content:- tool_outputs.append(msg.content)- if "error" in msg.content.lower() or "failed" in msg.content.lower():- result["error"] = msg.content-- if tool_outputs:- result["all_tool_outputs"] = "\n\n---\n\n".join(tool_outputs)-- for msg in reversed(state.messages):- if isinstance(msg, AssistantMessage) and msg.content and not msg.tool_calls:- result["agent_summary"] = msg.content- break-- return result---MOCK_BAYESIAN_SIGNIFICANT = MaxExperimentSummaryContext(- experiment_id=0, # replaced at runtime- experiment_name="Checkout Redesign Test",- description="Testing whether a simplified one-page checkout increases purchase conversion",- variants=["control", "test"],- exposures={"control": 4821.0, "test": 4793.0},- primary_metrics_results=[- MaxExperimentMetricResult(- name="1. Purchase conversion",- goal=Goal.INCREASE,- variant_results=[- MaxExperimentVariantResultBayesian(- key="control",- chance_to_win=0.12,- credible_interval=[-0.032, 0.011],- delta=-0.0105,- significant=False,- ),- MaxExperimentVariantResultBayesian(- key="test",- chance_to_win=0.88,- credible_interval=[0.018, 0.065],- delta=0.0415,- significant=True,- ),- ],- ),- ],- secondary_metrics_results=[],- stats_method=ExperimentStatsMethod.BAYESIAN,-)---# Non-significant Bayesian case: test variant slightly leads on chance-to-win,-# but credible intervals cross zero and neither variant is flagged significant.-# Exercises the scorer's "do not declare a winner when not significant" rule.-MOCK_BAYESIAN_NON_SIGNIFICANT = MaxExperimentSummaryContext(- experiment_id=0, # replaced at runtime- experiment_name="Homepage Hero Copy Test",- description="Testing whether new hero copy increases signup conversion",- variants=["control", "test"],- exposures={"control": 2103.0, "test": 2089.0},- primary_metrics_results=[- MaxExperimentMetricResult(- name="1. Signup conversion",- goal=Goal.INCREASE,- variant_results=[- MaxExperimentVariantResultBayesian(- key="control",- chance_to_win=0.46,- credible_interval=[-0.018, 0.014],- delta=-0.002,- significant=False,- ),- MaxExperimentVariantResultBayesian(- key="test",- chance_to_win=0.54,- credible_interval=[-0.014, 0.018],- delta=0.002,- significant=False,- ),- ],- ),- ],- secondary_metrics_results=[],- stats_method=ExperimentStatsMethod.BAYESIAN,-)---# Bayesian experiment with goal=decrease: the test variant reduces cart-# abandonment (a good outcome when lower is better). Chance-to-win is-# already inverted by the data service for decrease goals, so test shows-# a high chance to win. Delta and credible interval are negative for the-# test variant, reflecting that abandonment went down — which is the-# desired direction. Checks that Claude frames the reduction as positive-# rather than treating the negative delta as a regression.-MOCK_BAYESIAN_GOAL_DECREASE = MaxExperimentSummaryContext(- experiment_id=0, # replaced at runtime- experiment_name="Cart Abandonment Reduction Test",- description="Testing whether a streamlined cart page reduces abandonment rate",- variants=["control", "test"],- exposures={"control": 3512.0, "test": 3480.0},- primary_metrics_results=[- MaxExperimentMetricResult(- name="1. Cart abandonment rate",- goal=Goal.DECREASE,- variant_results=[- MaxExperimentVariantResultBayesian(- key="control",- chance_to_win=0.08,- credible_interval=[-0.009, 0.058],- delta=0.0245,- significant=False,- ),- MaxExperimentVariantResultBayesian(- key="test",- chance_to_win=0.92,- credible_interval=[-0.071, -0.021],- delta=-0.046,- significant=True,- ),- ],- ),- ],- secondary_metrics_results=[],- stats_method=ExperimentStatsMethod.BAYESIAN,-)---# Mixed metrics: primary says ship (test wins on conversion), but a secondary-# guardrail metric shows a significant regression (revenue per user dropped).-# Checks that Claude surfaces both signals and doesn't cherry-pick the winner.-MOCK_BAYESIAN_MIXED_METRICS = MaxExperimentSummaryContext(- experiment_id=0, # replaced at runtime- experiment_name="Simplified Pricing Page Test",- description="Testing whether a simplified pricing page increases plan upgrades",- variants=["control", "test"],- exposures={"control": 5210.0, "test": 5185.0},- primary_metrics_results=[- MaxExperimentMetricResult(- name="1. Plan upgrade conversion",- goal=Goal.INCREASE,- variant_results=[- MaxExperimentVariantResultBayesian(- key="control",- chance_to_win=0.09,- credible_interval=[-0.041, 0.008],- delta=-0.0165,- significant=False,- ),- MaxExperimentVariantResultBayesian(- key="test",- chance_to_win=0.91,- credible_interval=[0.015, 0.058],- delta=0.0365,- significant=True,- ),- ],- ),- ],- secondary_metrics_results=[- MaxExperimentMetricResult(- name="1. Revenue per user",- goal=Goal.INCREASE,- variant_results=[- MaxExperimentVariantResultBayesian(- key="control",- chance_to_win=0.86,- credible_interval=[0.012, 0.049],- delta=0.0305,- significant=True,- ),- MaxExperimentVariantResultBayesian(- key="test",- chance_to_win=0.14,- credible_interval=[-0.049, -0.012],- delta=-0.0305,- significant=False,- ),- ],- ),- ],- stats_method=ExperimentStatsMethod.BAYESIAN,-)---# Frequentist significant winner: test variant has a low p-value and-# confidence interval entirely above zero. Exercises the Frequentist-# formatting branch (p-values and confidence intervals instead of-# chance-to-win and credible intervals). Checks that Claude correctly-# interprets p-values — low means significant, high means not.-MOCK_FREQUENTIST_SIGNIFICANT = MaxExperimentSummaryContext(- experiment_id=0, # replaced at runtime- experiment_name="Search Ranking Algorithm Test",- description="Testing whether a new search ranking algorithm improves click-through rate",- variants=["control", "test"],- exposures={"control": 6340.0, "test": 6285.0},- primary_metrics_results=[- MaxExperimentMetricResult(- name="1. Search click-through rate",- goal=Goal.INCREASE,- variant_results=[- MaxExperimentVariantResultFrequentist(- key="control",- p_value=0.73,- confidence_interval=[-0.048, 0.019],- delta=-0.0145,- significant=False,- ),- MaxExperimentVariantResultFrequentist(- key="test",- p_value=0.003,- confidence_interval=[0.012, 0.054],- delta=0.033,- significant=True,- ),- ],- ),- ],- secondary_metrics_results=[],- stats_method=ExperimentStatsMethod.FREQUENTIST,-)---# Frequentist non-significant: both variants have high p-values and-# confidence intervals crossing zero. Test slightly leads on delta but-# p=0.35 is far from significant. Checks that Claude doesn't misread-# a moderate p-value as "trending toward significance" or pick a winner.-MOCK_FREQUENTIST_NON_SIGNIFICANT = MaxExperimentSummaryContext(- experiment_id=0, # replaced at runtime- experiment_name="Email Subject Line Test",- description="Testing whether a personalized email subject line improves open rate",- variants=["control", "test"],- exposures={"control": 3150.0, "test": 3120.0},- primary_metrics_results=[- MaxExperimentMetricResult(- name="1. Email open rate",- goal=Goal.INCREASE,- variant_results=[- MaxExperimentVariantResultFrequentist(- key="control",- p_value=0.58,- confidence_interval=[-0.022, 0.015],- delta=-0.0035,- significant=False,- ),- MaxExperimentVariantResultFrequentist(- key="test",- p_value=0.35,- confidence_interval=[-0.009, 0.027],- delta=0.009,- significant=False,- ),- ],- ),- ],- secondary_metrics_results=[],- stats_method=ExperimentStatsMethod.FREQUENTIST,-)---MOCK_CONTEXTS: dict[str, MaxExperimentSummaryContext] = {- "bayesian_significant": MOCK_BAYESIAN_SIGNIFICANT,- "bayesian_non_significant": MOCK_BAYESIAN_NON_SIGNIFICANT,- "bayesian_goal_decrease": MOCK_BAYESIAN_GOAL_DECREASE,- "bayesian_mixed_metrics": MOCK_BAYESIAN_MIXED_METRICS,- "frequentist_significant": MOCK_FREQUENTIST_SIGNIFICANT,- "frequentist_non_significant": MOCK_FREQUENTIST_NON_SIGNIFICANT,-}---def experiment_with_mock_data(demo_org_team_user):- """Create an experiment matching a mock context template and return both."""- _, team, user = demo_org_team_user-- async def setup(mock_template: MaxExperimentSummaryContext):- unique_suffix = uuid.uuid4().hex[:6]- # Distribute rollout percentages evenly across variants, putting any- # remainder on the first variant so the total is exactly 100.- num_variants = len(mock_template.variants)- base_pct = 100 // num_variants- remainder = 100 - (base_pct * num_variants)- flag = await FeatureFlag.objects.acreate(- team=team,- created_by=user,- key=f"eval-experiment-{unique_suffix}",- name=f"{mock_template.experiment_name} Flag",- filters={- "groups": [{"properties": [], "rollout_percentage": 100}],- "multivariate": {- "variants": [- {- "key": variant,- "name": variant.title(),- "rollout_percentage": base_pct + (remainder if i == 0 else 0),- }- for i, variant in enumerate(mock_template.variants)- ]- },- },- )-- now = datetime.now(tz=ZoneInfo("UTC"))- stats_config = (- {"method": mock_template.stats_method.value}- if mock_template.stats_method != ExperimentStatsMethod.BAYESIAN- else None- )- experiment = await Experiment.objects.acreate(- name=mock_template.experiment_name,- team=team,- created_by=user,- feature_flag=flag,- description=mock_template.description or "",- start_date=now - timedelta(days=14),- stats_config=stats_config,- metrics=[- {- "metric_type": "funnel",- "series": [{"kind": "EventsNode", "event": "$pageview"}],- "name": metric.name,- }- for metric in mock_template.primary_metrics_results- ],- metrics_secondary=[],- )-- mock_context = mock_template.model_copy(update={"experiment_id": experiment.id})- return experiment, mock_context-- return setup---def call_agent_for_summary(demo_org_team_user, experiment_with_mock_data):- """Run the agent graph with mocked experiment data."""- _, team, user = demo_org_team_user-- graph = (- AssistantGraph(team, user)- .add_edge(AssistantNodeName.START, AssistantNodeName.ROOT)- .add_root()- .compile(checkpointer=DjangoCheckpointer())- )-- async def callable(input: EvalInput) -> dict:- mock_template = MOCK_CONTEXTS[input["mock_key"]]- experiment, mock_context = await experiment_with_mock_data(mock_template)-- conversation = await Conversation.objects.acreate(team=team, user=user)- initial_state = AssistantState(- messages=[HumanMessage(content=input["input"].format(experiment_id=experiment.id))],- agent_mode=AgentMode.FLAGS,- )- config = RunnableConfig(configurable={"thread_id": conversation.id}, recursion_limit=48)-- mock_return = ExperimentSummaryData(- context=mock_context,- last_refresh=datetime.now(tz=ZoneInfo("UTC")),- pending_calculation=False,- omitted_metric_count=0,- )- with (- patch(- "products.experiments.backend.max_tools.ExperimentSummaryDataService.fetch_experiment_data",- return_value=mock_return,- ),- patch(- "ee.hogai.core.agent_modes.presets.flags.has_experiment_summary_tool_feature_flag",- return_value=True,- ),- ):- raw_state = await graph.ainvoke(initial_state, config)-- state = AssistantState.model_validate(raw_state)- return _extract_summary_result(state)-- yield callable---async def eval_experiment_summary(call_agent_for_summary, pytestconfig):- """Test that experiment summaries are factually accurate."""- await MaxPublicEval(- experiment_name="experiment_summary",- task=call_agent_for_summary,- scores=[ExperimentSummaryAccuracy()],- data=[- EvalCase(- input=EvalInput(- input=_SUMMARY_PROMPT,- mock_key="bayesian_significant",- ),- metadata={"test_type": "bayesian_significant"},- ),- EvalCase(- input=EvalInput(- input=_SUMMARY_PROMPT,- mock_key="bayesian_non_significant",- ),- metadata={"test_type": "bayesian_non_significant"},- ),- EvalCase(- input=EvalInput(- input=_SUMMARY_PROMPT,- mock_key="bayesian_goal_decrease",- ),- metadata={"test_type": "bayesian_goal_decrease"},- ),- EvalCase(- input=EvalInput(- input=_SUMMARY_PROMPT,- mock_key="bayesian_mixed_metrics",- ),- metadata={"test_type": "bayesian_mixed_metrics"},- ),- EvalCase(- input=EvalInput(- input=_SUMMARY_PROMPT,- mock_key="frequentist_significant",- ),- metadata={"test_type": "frequentist_significant"},- ),- EvalCase(- input=EvalInput(- input=_SUMMARY_PROMPT,- mock_key="frequentist_non_significant",- ),- metadata={"test_type": "frequentist_non_significant"},- ),- ],- pytestconfig=pytestconfig,- )diff --git a/ee/hogai/eval/ci/max_tools/eval_session_replay_filter_generation.py b/ee/hogai/eval/ci/max_tools/eval_session_replay_filter_generation.pydeleted file mode 100644index 98b73e01967f..000000000000--- a/ee/hogai/eval/ci/max_tools/eval_session_replay_filter_generation.py+++ /dev/null@@ -1,644 +0,0 @@-import logging--import pytest--from braintrust import EvalCase, Score-from braintrust_core.score import Scorer-from deepdiff import DeepDiff--from posthog.schema import (- DurationType,- EventPropertyFilter,- FilterLogicalOperator,- MaxInnerUniversalFiltersGroup,- MaxOuterUniversalFiltersGroup,- MaxRecordingUniversalFilters,- PersonPropertyFilter,- PropertyOperator,- RecordingDurationFilter,- RecordingOrder,- RecordingOrderDirection,-)--from products.posthog_ai.backend.models.assistant import Conversation-from products.replay.backend.max_tools import SessionReplayFilterOptionsGraph-from products.replay.backend.prompts import USER_FILTER_OPTIONS_PROMPT--from ee.hogai.django_checkpoint.checkpointer import DjangoCheckpointer--from ...base import MaxPublicEval--logger = logging.getLogger(__name__)--DUMMY_CURRENT_FILTERS = MaxRecordingUniversalFilters(- date_from="-7d",- date_to=None,- duration=[- RecordingDurationFilter(key=DurationType.DURATION, operator=PropertyOperator.GT, type="recording", value=60.0)- ],- filter_group=MaxOuterUniversalFiltersGroup(- type=FilterLogicalOperator.AND_,- values=[MaxInnerUniversalFiltersGroup(type=FilterLogicalOperator.AND_, values=[])],- ),- filter_test_accounts=True,- order=RecordingOrder.START_TIME,- order_direction=RecordingOrderDirection.DESC,-)---def call_search_session_recordings(demo_org_team_user):- graph = SessionReplayFilterOptionsGraph(demo_org_team_user[1], demo_org_team_user[2]).compile_full_graph(- checkpointer=DjangoCheckpointer()- )-- async def callable(change: str) -> dict:- conversation = await Conversation.objects.acreate(team=demo_org_team_user[1], user=demo_org_team_user[2])-- # Convert filters to JSON string and use test-specific prompt- filters_json = DUMMY_CURRENT_FILTERS.model_dump_json(indent=2)-- graph_input = {- "change": USER_FILTER_OPTIONS_PROMPT.format(change=change, current_filters=filters_json),- "output": None,- }-- result = await graph.ainvoke(graph_input, config={"configurable": {"thread_id": conversation.id}})- return result-- return callable---class FilterGenerationCorrectness(Scorer):- """Score the correctness of generated filters."""-- def _name(self):- return "filter_generation_correctness"-- async def _run_eval_async(self, output, expected=None, **kwargs):- return self._run_eval_sync(output, expected, **kwargs)-- def _run_eval_sync(self, output, expected=None, **kwargs):- if isinstance(output["output"], str):- return Score(- name=self._name(),- score=0.0,- metadata={"reason": f"LLM did not return filters: {output['output'][:200]}"},- )-- try:- actual_filters = MaxRecordingUniversalFilters.model_validate(output["output"])- except Exception as e:- logger.warning(f"Error parsing filters: {e}")- return Score(name=self._name(), score=0.0, metadata={"reason": "LLM returned invalid filter structure"})-- # Convert both objects to dict for deepdiff comparison- actual_dict = actual_filters.model_dump()- expected_dict = expected.model_dump()-- # Use deepdiff to find differences- diff = DeepDiff(expected_dict, actual_dict, ignore_order=True, report_repetition=True)-- if not diff:- return Score(name=self._name(), score=1.0, metadata={"reason": "Perfect match"})-- # Calculate score based on number of differences- total_fields = len(expected_dict.keys())- changed_fields = (- len(diff.get("values_changed", {}))- + len(diff.get("dictionary_item_added", set()))- + len(diff.get("dictionary_item_removed", set()))- )-- score = max(0.0, (total_fields - changed_fields) / total_fields)-- return Score(- name=self._name(),- score=score,- metadata={- "differences": str(diff),- "total_fields": total_fields,- "changed_fields": changed_fields,- "reason": f"Found {changed_fields} differences out of {total_fields} fields",- },- )---class AskUserForHelp(Scorer):- """Score the correctness of the ask_user_for_help tool."""-- def _name(self):- return "ask_user_for_help_scorer"-- def _run_eval_sync(self, output, expected=None, **kwargs):- if isinstance(output.get("output"), str):- return Score(name=self._name(), score=1, metadata={"reason": "LLM returned text instead of filters"})- if output.get("output") is None:- if (- "intermediate_steps" in output- and len(output["intermediate_steps"]) > 0- and output["intermediate_steps"][-1][0].tool == "ask_user_for_help"- ):- return Score(name=self._name(), score=1, metadata={"reason": "LLM called ask_user_for_help tool"})- else:- return Score(- name=self._name(),- score=0,- metadata={"reason": "LLM did not return filters or ask for help"},- )- else:- return Score(name=self._name(), score=0.0, metadata={"reason": "LLM returned a filter"})---class DateTimeFilteringCorrectness(Scorer):- """Score the correctness of the date time filtering."""-- def _name(self):- return "date_time_filtering_correctness"-- async def _run_eval_async(self, output, expected=None, **kwargs):- return self._run_eval_sync(output, expected, **kwargs)-- def _run_eval_sync(self, output, expected=None, **kwargs):- if isinstance(output["output"], str):- return Score(- name=self._name(),- score=0.0,- metadata={"reason": f"LLM did not return filters: {output['output'][:200]}"},- )-- try:- actual_filters = MaxRecordingUniversalFilters.model_validate(output["output"])- except Exception as e:- logger.warning(f"Error parsing filters: {e}")- return Score(name=self._name(), score=0.0, metadata={"reason": "LLM returned invalid filter structure"})-- if actual_filters.date_from == expected.date_from and actual_filters.date_to == expected.date_to:- return Score(name=self._name(), score=1.0, metadata={"reason": "LLM returned valid date time filters"})- elif actual_filters.date_from == expected.date_from:- return Score(- name=self._name(),- score=0.5,- metadata={"reason": "LLM returned valid date_from but did not return valid date_to"},- )- elif actual_filters.date_to == expected.date_to:- return Score(- name=self._name(),- score=0.5,- metadata={"reason": "LLM returned valid date_to but did not return valid date_from"},- )- else:- return Score(name=self._name(), score=0.0, metadata={"reason": "LLM returned invalid date time filters"})---async def eval_tool_search_session_recordings(call_search_session_recordings, pytestconfig):- await MaxPublicEval(- experiment_name="tool_search_session_recordings",- task=call_search_session_recordings,- scores=[FilterGenerationCorrectness(), DateTimeFilteringCorrectness()],- data=[- # Test basic filter generation for mobile devices- EvalCase(- input="show me recordings of users that were using a mobile device (use events)",- expected=MaxRecordingUniversalFilters(- date_from="-7d",- date_to=None,- duration=[- RecordingDurationFilter(- key=DurationType.DURATION, operator=PropertyOperator.GT, type="recording", value=60.0- )- ],- filter_group=MaxOuterUniversalFiltersGroup(- type=FilterLogicalOperator.AND_,- values=[- MaxInnerUniversalFiltersGroup(- type=FilterLogicalOperator.AND_,- values=[- EventPropertyFilter(- key="$device_type",- type="event",- value=["Mobile"],- operator=PropertyOperator.EXACT,- )- ],- )- ],- ),- filter_test_accounts=True,- order=RecordingOrder.START_TIME,- ),- ),- # Test date range filtering- EvalCase(- input="Show recordings from the last 2 hours",- expected=MaxRecordingUniversalFilters(- date_from="-2h",- date_to=None,- duration=[- RecordingDurationFilter(- key=DurationType.DURATION, operator=PropertyOperator.GT, type="recording", value=60.0- )- ],- filter_group=MaxOuterUniversalFiltersGroup(- type=FilterLogicalOperator.AND_,- values=[MaxInnerUniversalFiltersGroup(type=FilterLogicalOperator.AND_, values=[])],- ),- filter_test_accounts=True,- order=RecordingOrder.START_TIME,- ),- ),- # Test location filtering- EvalCase(- input="Show recordings for users located in the US",- expected=MaxRecordingUniversalFilters(- date_from="-7d",- date_to=None,- duration=[- RecordingDurationFilter(- key=DurationType.DURATION, operator=PropertyOperator.GT, type="recording", value=60.0- )- ],- filter_group=MaxOuterUniversalFiltersGroup(- type=FilterLogicalOperator.AND_,- values=[- MaxInnerUniversalFiltersGroup(- type=FilterLogicalOperator.AND_,- values=[- PersonPropertyFilter(- key="$geoip_country_code",- type="person",- value=["US"],- operator=PropertyOperator.EXACT,- )- ],- )- ],- ),- filter_test_accounts=True,- order=RecordingOrder.START_TIME,- ),- ),- # Test browser-specific filtering- EvalCase(- input="Show recordings from users that were using a browser in English",- expected=MaxRecordingUniversalFilters(- date_from="-7d",- date_to=None,- duration=[- RecordingDurationFilter(- key=DurationType.DURATION, operator=PropertyOperator.GT, type="recording", value=60.0- )- ],- filter_group=MaxOuterUniversalFiltersGroup(- type=FilterLogicalOperator.AND_,- values=[- MaxInnerUniversalFiltersGroup(- type=FilterLogicalOperator.AND_,- values=[- PersonPropertyFilter(- key="$browser_language",- type="person",- value=["EN-en"],- operator=PropertyOperator.EXACT,- )- ],- )- ],- ),- filter_test_accounts=True,- order=RecordingOrder.START_TIME,- ),- ),- EvalCase(- input="Show me recordings from chrome browsers",- expected=MaxRecordingUniversalFilters(- date_from="-7d",- date_to=None,- duration=[- RecordingDurationFilter(- key=DurationType.DURATION, operator=PropertyOperator.GT, type="recording", value=60.0- )- ],- filter_group=MaxOuterUniversalFiltersGroup(- type=FilterLogicalOperator.AND_,- values=[- MaxInnerUniversalFiltersGroup(- type=FilterLogicalOperator.AND_,- values=[- EventPropertyFilter(- key="$browser",- type="event",- value=["Chrome"],- operator=PropertyOperator.EXACT,- )- ],- )- ],- ),- filter_test_accounts=True,- order=RecordingOrder.START_TIME,- ),- ),- # Test user behavior filtering- EvalCase(- input="Show recordings where users visited the posthog.com/checkout_page",- expected=MaxRecordingUniversalFilters(- date_from="-7d",- date_to=None,- duration=[- RecordingDurationFilter(- key=DurationType.DURATION, operator=PropertyOperator.GT, type="recording", value=60.0- )- ],- filter_group=MaxOuterUniversalFiltersGroup(- type=FilterLogicalOperator.AND_,- values=[- MaxInnerUniversalFiltersGroup(- type=FilterLogicalOperator.AND_,- values=[- EventPropertyFilter(- key="$current_url",- type="event",- value=["posthog.com/checkout_page"],- operator=PropertyOperator.ICONTAINS,- )- ],- )- ],- ),- filter_test_accounts=True,- order=RecordingOrder.START_TIME,- ),- ),- # Test session duration filtering- EvalCase(- input="Show recordings longer than 5 minutes",- expected=MaxRecordingUniversalFilters(- date_from="-7d",- date_to=None,- duration=[- RecordingDurationFilter(- key=DurationType.DURATION, operator=PropertyOperator.GT, type="recording", value=300.0- )- ],- filter_group=MaxOuterUniversalFiltersGroup(- type=FilterLogicalOperator.AND_,- values=[MaxInnerUniversalFiltersGroup(type=FilterLogicalOperator.AND_, values=[])],- ),- filter_test_accounts=True,- order=RecordingOrder.START_TIME,- ),- ),- # Test user action- EvalCase(- input="Show recordings from users that performed a billing action",- expected=MaxRecordingUniversalFilters(- date_from="-7d",- date_to=None,- duration=[- RecordingDurationFilter(- key=DurationType.DURATION, operator=PropertyOperator.GT, type="recording", value=60.0- )- ],- filter_group=MaxOuterUniversalFiltersGroup(- type=FilterLogicalOperator.AND_,- values=[- MaxInnerUniversalFiltersGroup(- type=FilterLogicalOperator.AND_,- values=[- EventPropertyFilter(- key="paid_bill",- type="event",- value=None,- operator=PropertyOperator.IS_SET,- )- ],- )- ],- ),- filter_test_accounts=True,- order=RecordingOrder.START_TIME,- ),- ),- # Test page-specific filtering- EvalCase(- input="Show recordings from users who visited the pricing page",- expected=MaxRecordingUniversalFilters(- date_from="-7d",- date_to=None,- duration=[- RecordingDurationFilter(- key=DurationType.DURATION, operator=PropertyOperator.GT, type="recording", value=60.0- )- ],- filter_group=MaxOuterUniversalFiltersGroup(- type=FilterLogicalOperator.AND_,- values=[- MaxInnerUniversalFiltersGroup(- type=FilterLogicalOperator.AND_,- values=[- EventPropertyFilter(- key="$pathname",- type="event",- value=["/pricing/"],- operator=PropertyOperator.ICONTAINS,- )- ],- )- ],- ),- filter_test_accounts=True,- order=RecordingOrder.START_TIME,- ),- ),- # Test conversion funnel filtering- EvalCase(- input="Show recordings from users who completed the signup flow",- expected=MaxRecordingUniversalFilters(- date_from="-7d",- date_to=None,- duration=[- RecordingDurationFilter(- key=DurationType.DURATION, operator=PropertyOperator.GT, type="recording", value=60.0- )- ],- filter_group=MaxOuterUniversalFiltersGroup(- type=FilterLogicalOperator.AND_,- values=[- MaxInnerUniversalFiltersGroup(- type=FilterLogicalOperator.AND_,- values=[- EventPropertyFilter(- key="signup_completed",- type="event",- value=None,- operator=PropertyOperator.IS_SET,- )- ],- )- ],- ),- filter_test_accounts=True,- order=RecordingOrder.START_TIME,- ),- ),- # Test device and browser combination- EvalCase(- input="Show recordings from mobile Safari users",- expected=MaxRecordingUniversalFilters(- date_from="-7d",- date_to=None,- duration=[- RecordingDurationFilter(- key=DurationType.DURATION, operator=PropertyOperator.GT, type="recording", value=60.0- )- ],- filter_group=MaxOuterUniversalFiltersGroup(- type=FilterLogicalOperator.AND_,- values=[- MaxInnerUniversalFiltersGroup(- type=FilterLogicalOperator.AND_,- values=[- EventPropertyFilter(- key="$device_type",- type="event",- value=["Mobile"],- operator=PropertyOperator.EXACT,- ),- EventPropertyFilter(- key="$browser",- type="event",- value=["Safari"],- operator=PropertyOperator.EXACT,- ),- ],- )- ],- ),- filter_test_accounts=True,- order=RecordingOrder.START_TIME,- ),- ),- # Test time-based filtering- EvalCase(- input="Show recordings from yesterday",- expected=DUMMY_CURRENT_FILTERS.model_copy(update={"date_from": "-1d", "date_to": "-1d"}),- ),- EvalCase(- input="Assuming we're in 2024, show me recordings since the 1st of August",- expected=DUMMY_CURRENT_FILTERS.model_copy(update={"date_from": "2024-08-01T00:00:00:000"}),- ),- EvalCase(- input="Assuming we're in 2024, show me recordings until the 31st of August",- expected=DUMMY_CURRENT_FILTERS.model_copy(update={"date_to": "2024-08-31T23:59:59:999"}),- ),- EvalCase(- input="Assuming we're in 2024, show me recordings from the 1st of September to the 31st of September",- expected=DUMMY_CURRENT_FILTERS.model_copy(- update={"date_from": "2024-09-01T00:00:00:000", "date_to": "2024-09-30T23:59:59:999"}- ),- ),- EvalCase(- input="Assuming we're in 2024, show me recordings from the 1st of September to the 1st of September",- expected=DUMMY_CURRENT_FILTERS.model_copy(- update={"date_from": "2024-09-01T00:00:00:000", "date_to": "2024-09-01T23:59:59:999"}- ),- ),- EvalCase(- input="show me recordings of users who signed up on mobile",- expected=MaxRecordingUniversalFilters(- date_from="-7d",- date_to=None,- duration=[- RecordingDurationFilter(- key=DurationType.DURATION, operator=PropertyOperator.GT, type="recording", value=60.0- )- ],- filter_group=MaxOuterUniversalFiltersGroup(- type=FilterLogicalOperator.AND_,- values=[- MaxInnerUniversalFiltersGroup(- type=FilterLogicalOperator.AND_,- values=[- EventPropertyFilter(- key="$device_type",- type="event",- value=["Mobile"],- operator=PropertyOperator.EXACT,- )- ],- )- ],- ),- filter_test_accounts=True,- order=RecordingOrder.START_TIME,- ),- ),- EvalCase(- input="Show recordings in an ascending order by duration",- expected=MaxRecordingUniversalFilters(- date_from="-7d",- date_to=None,- duration=[- RecordingDurationFilter(- key=DurationType.DURATION, operator=PropertyOperator.GT, type="recording", value=60.0- )- ],- filter_group=MaxOuterUniversalFiltersGroup(- type=FilterLogicalOperator.AND_,- values=[MaxInnerUniversalFiltersGroup(type=FilterLogicalOperator.AND_, values=[])],- ),- filter_test_accounts=True,- order=RecordingOrder.DURATION,- order_direction=RecordingOrderDirection.ASC,- ),- ),- # Test limit field with numeric requests- EvalCase(- input="Show me 100 recordings of users who signed up on mobile",- expected=MaxRecordingUniversalFilters(- date_from="-7d",- date_to=None,- duration=[- RecordingDurationFilter(- key=DurationType.DURATION, operator=PropertyOperator.GT, type="recording", value=60.0- )- ],- filter_group=MaxOuterUniversalFiltersGroup(- type=FilterLogicalOperator.AND_,- values=[- MaxInnerUniversalFiltersGroup(- type=FilterLogicalOperator.AND_,- values=[- EventPropertyFilter(- key="$device_type",- type="event",- value=["Mobile"],- operator=PropertyOperator.EXACT,- )- ],- )- ],- ),- filter_test_accounts=True,- order=RecordingOrder.START_TIME,- limit=100,- ),- ),- ],- pytestconfig=pytestconfig,- )---async def eval_tool_search_session_recordings_ask_user_for_help(call_search_session_recordings, pytestconfig):- await MaxPublicEval(- experiment_name="tool_search_session_recordings_ask_user_for_help",- task=call_search_session_recordings,- scores=[AskUserForHelp()],- data=[- EvalCase(input="Tell me something about insights", expected="clarify"),- ],- pytestconfig=pytestconfig,- )diff --git a/ee/hogai/eval/ci/max_tools/eval_subscription_tool.py b/ee/hogai/eval/ci/max_tools/eval_subscription_tool.pydeleted file mode 100644index 04abdf9de5cc..000000000000--- a/ee/hogai/eval/ci/max_tools/eval_subscription_tool.py+++ /dev/null@@ -1,260 +0,0 @@-"""Evaluations for subscription MCP tools.--Tests that the agent correctly identifies subscription-related user intents-and invokes the right subscription tool with appropriate parameters.--NOTE: These evals require the internal agent to have access to subscription-tools. Currently, subscriptions are MCP-only tools (not available in any-AgentMode). To run these evals, subscription tools need to be registered-in an agent mode (e.g., PRODUCT_ANALYTICS) or a dedicated SUBSCRIPTIONS-mode needs to be added.-"""--from typing import Any, TypedDict--import pytest--from autoevals.llm import LLMClassifier-from braintrust import EvalCase, Score-from langchain_core.runnables import RunnableConfig--from posthog.schema import AgentMode, AssistantMessage, AssistantToolCallMessage, HumanMessage--from products.posthog_ai.backend.models.assistant import Conversation--from ee.hogai.chat_agent import AssistantGraph-from ee.hogai.django_checkpoint.checkpointer import DjangoCheckpointer-from ee.hogai.eval.base import MaxPublicEval-from ee.hogai.utils.types import AssistantNodeName, AssistantState---class EvalInput(TypedDict):- input: str---SUBSCRIPTION_OPERATION_ACCURACY_PROMPT = """-Evaluate if the agent correctly performed the subscription operation.--<user_request>-{{input.input}}-</user_request>--<expected>-{{#expected}}-{{#expected.tool_called}}-Tool called: {{expected.tool_called}}-{{/expected.tool_called}}-{{#expected.has_insight}}-Should reference an insight: {{expected.has_insight}}-{{/expected.has_insight}}-{{#expected.has_dashboard}}-Should reference a dashboard: {{expected.has_dashboard}}-{{/expected.has_dashboard}}-{{#expected.frequency}}-Expected frequency: {{expected.frequency}}-{{/expected.frequency}}-{{#expected.target_type}}-Expected target type: {{expected.target_type}}-{{/expected.target_type}}-{{#expected.is_delete}}-Should soft-delete: {{expected.is_delete}}-{{/expected.is_delete}}-{{#expected.checks_slack}}-Should check for Slack integration availability: {{expected.checks_slack}}-{{/expected.checks_slack}}-{{#expected.asks_channel}}-Should ask the user whether they want email or Slack: {{expected.asks_channel}}-{{/expected.asks_channel}}-{{/expected}}--<actual_output>-Tool called: {{output.tool_called}}-Tool output: {{output.tool_output}}-Tool args (if any): {{output.tool_args}}-Error: {{output.error}}-</actual_output>--Evaluate:-1. Did the agent call the expected tool (if specified)?-2. Were the arguments appropriate for the user's request?-3. If creating, does it include the right frequency, target_type, and insight/dashboard reference?-4. If listing, did it apply relevant filters?-5. If deactivating, did it set deleted to true?-6. If Slack was requested, did the agent check for a Slack integration first (via integrations-list)?-7. If the user's intent is ambiguous about channel, did the agent ask whether they want email or Slack?--Choose: pass (all requirements met) or fail (any requirement not met)-""".strip()---class SubscriptionOperationAccuracy(LLMClassifier):- """Binary LLM judge for subscription tool operations."""-- def _normalize(self, output: dict | None, expected: dict | None) -> tuple[dict, dict]:- normalized_output = {- "tool_called": None,- "tool_output": None,- "tool_args": None,- "error": None,- **(output or {}),- }- normalized_expected = {**(expected or {})}- return normalized_output, normalized_expected-- async def _run_eval_async(self, output: dict | None, expected: dict | None = None, **kwargs):- if not output:- return Score(name=self._name(), score=0.0, metadata={"reason": "No output provided"})- normalized_output, normalized_expected = self._normalize(output, expected)- return await super()._run_eval_async(normalized_output, normalized_expected, **kwargs)-- def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs):- if not output:- return Score(name=self._name(), score=0.0, metadata={"reason": "No output provided"})- normalized_output, normalized_expected = self._normalize(output, expected)- return super()._run_eval_sync(normalized_output, normalized_expected, **kwargs)-- def __init__(self, **kwargs):- super().__init__(- name="subscription_operation_accuracy",- prompt_template=SUBSCRIPTION_OPERATION_ACCURACY_PROMPT,- choice_scores={"pass": 1.0, "fail": 0.0},- model="gpt-5.2",- max_tokens=2048,- reasoning_effort="medium",- **kwargs,- )---SUBSCRIPTION_TOOL_NAMES = {- "subscriptions-list",- "subscriptions-create",- "subscriptions-retrieve",- "subscriptions-partial-update",-}---def _extract_subscription_result(state: AssistantState) -> dict[str, Any]:- """Extract subscription tool invocation from agent state."""- result: dict[str, Any] = {- "tool_called": None,- "tool_output": None,- "tool_args": None,- "error": None,- }-- subscription_tool_call_id: str | None = None-- for msg in state.messages:- if isinstance(msg, AssistantMessage) and msg.tool_calls:- for tool_call in msg.tool_calls:- if tool_call.name in SUBSCRIPTION_TOOL_NAMES:- result["tool_called"] = tool_call.name- result["tool_args"] = tool_call.args- subscription_tool_call_id = tool_call.id- break-- for msg in state.messages:- if isinstance(msg, AssistantToolCallMessage) and msg.tool_call_id == subscription_tool_call_id:- result["tool_output"] = msg.content- if msg.content and ("error" in msg.content.lower() or "invalid" in msg.content.lower()):- result["error"] = msg.content- break-- return result---def call_agent_for_subscription(demo_org_team_user):- """Run full agent graph with natural language subscription requests."""- _, team, user = demo_org_team_user-- graph = (- AssistantGraph(team, user)- .add_edge(AssistantNodeName.START, AssistantNodeName.ROOT)- .add_root()- .compile(checkpointer=DjangoCheckpointer())- )-- async def callable(input: EvalInput) -> dict:- conversation = await Conversation.objects.acreate(team=team, user=user)- initial_state = AssistantState(- messages=[HumanMessage(content=input["input"])],- agent_mode=AgentMode.PRODUCT_ANALYTICS,- )- config = RunnableConfig(configurable={"thread_id": conversation.id}, recursion_limit=48)- raw_state = await graph.ainvoke(initial_state, config)- state = AssistantState.model_validate(raw_state)- return _extract_subscription_result(state)-- yield callable---async def eval_subscription_management_llm(call_agent_for_subscription, pytestconfig):- """Test subscription management via full agent with natural language prompts."""- await MaxPublicEval(- experiment_name="subscription_management_llm",- task=call_agent_for_subscription,- scores=[SubscriptionOperationAccuracy()],- data=[- EvalCase(- input=EvalInput(input="Send me a daily email update of my pageview trends insight"),- expected={- "tool_called": "subscriptions-create",- "has_insight": True,- "frequency": "daily",- "target_type": "email",- },- metadata={"test_type": "create_daily_email"},- ),- EvalCase(- input=EvalInput(input="What subscriptions do I have?"),- expected={- "tool_called": "subscriptions-list",- },- metadata={"test_type": "list_subscriptions"},- ),- EvalCase(- input=EvalInput(input="Subscribe me to weekly Monday updates on my revenue dashboard"),- expected={- "tool_called": "subscriptions-create",- "has_dashboard": True,- "frequency": "weekly",- "target_type": "email",- },- metadata={"test_type": "create_weekly_dashboard"},- ),- EvalCase(- input=EvalInput(input="Stop sending me that daily insight email, subscription 42"),- expected={- "tool_called": "subscriptions-partial-update",- "is_delete": True,- },- metadata={"test_type": "deactivate_subscription"},- ),- EvalCase(- input=EvalInput(input="Change my subscription to send weekly instead of daily"),- expected={- "tool_called": "subscriptions-partial-update",- "frequency": "weekly",- },- metadata={"test_type": "update_frequency"},- ),- EvalCase(- input=EvalInput(input="Send this insight to our #analytics Slack channel every day"),- expected={- "tool_called": "integrations-list",- "checks_slack": True,- },- metadata={"test_type": "slack_channel_check_integration"},- ),- EvalCase(- input=EvalInput(input="I want updates on this insight"),- expected={- "asks_channel": True,- },- metadata={"test_type": "asks_email_or_slack"},- ),- ],- pytestconfig=pytestconfig,- )diff --git a/ee/hogai/eval/ci/max_tools/eval_upsert_dashboard.py b/ee/hogai/eval/ci/max_tools/eval_upsert_dashboard.pydeleted file mode 100644index 0e8506da5798..000000000000--- a/ee/hogai/eval/ci/max_tools/eval_upsert_dashboard.py+++ /dev/null@@ -1,300 +0,0 @@-from datetime import datetime-from typing import Any, NotRequired, TypedDict--import pytest-from unittest.mock import patch--from autoevals.llm import LLMClassifier-from braintrust import EvalCase, Score-from langchain_core.runnables import RunnableConfig--from posthog.schema import (- AssistantMessage,- AssistantToolCallMessage,- EventsNode,- HumanMessage,- InsightVizNode,- TrendsQuery,-)--from products.dashboards.backend.models.dashboard import Dashboard-from products.dashboards.backend.models.dashboard_tile import DashboardTile-from products.posthog_ai.backend.models.assistant import Conversation-from products.product_analytics.backend.facade.models import Insight--from ee.hogai.chat_agent import AssistantGraph-from ee.hogai.django_checkpoint.checkpointer import DjangoCheckpointer-from ee.hogai.eval.base import MaxPublicEval-from ee.hogai.utils.types import AssistantNodeName, AssistantState---class EvalInput(TypedDict):- input: str- dashboard: NotRequired[Dashboard | None]---class EvalExpected(TypedDict):- action: str- dashboard_name: NotRequired[str | None]- insight_titles: NotRequired[list[str] | None]- error: NotRequired[str | None]---DASHBOARD_OPERATION_ACCURACY_PROMPT = """-Evaluate if the agent correctly performed the dashboard operation.--<user_request>-{{input.input}}-</user_request>--<expected>-Action: {{expected.action}}-{{#expected.dashboard_name}}-Dashboard name: {{expected.dashboard_name}}-{{/expected.dashboard_name}}-Expected insight titles (by meaning): {{expected.insight_titles}}-Expected error: {{expected.error}}-</expected>--<actual_output>-Tool called: {{output.tool_called}}-Action: {{output.action}}-Tool output: {{output.tool_output}}-Error: {{output.error}}-</actual_output>--Evaluate:-1. If expected action is "No action": The agent should NOT have called upsert_dashboard. Pass if no tool was called, fail otherwise.-2. If expected action is create/update:- a. Did the agent call the upsert_dashboard tool?- b. Was the correct action (create/update) chosen?- c. Does the tool output confirm a dashboard was created/updated?- d. Do the insight titles in the tool output match the expected ones BY MEANING? Titles don't need to be exact - they should be semantically equivalent (e.g. "File activity" matches "File interactions", "User journey funnel" matches "Homepage view to signup conversion"). If expected is null/None, skip this check.-3. If error expected, was it returned?--Choose: pass (all requirements met) or fail (any requirement not met)-""".strip()---class DashboardOperationAccuracy(LLMClassifier):- """Binary LLM judge for full agent dashboard operations (tests trajectory)."""-- def _normalize(self, output: dict | None, expected: dict | None) -> tuple[dict, dict]:- """Ensure all keys exist with defaults to avoid Mustache errors."""- normalized_output = {- "tool_called": None,- "action": None,- "tool_output": None,- "error": None,- **(output or {}),- }- normalized_expected = {- "action": None,- "insight_titles": None,- "error": None,- "dashboard_name": None,- **(expected or {}),- }- if normalized_expected["action"] is None:- normalized_expected["action"] = "No action"- if normalized_output["action"] is None:- normalized_output["action"] = "No action"- return normalized_output, normalized_expected-- async def _run_eval_async(self, output: dict | None, expected: dict | None = None, **kwargs):- if not output:- return Score(name=self._name(), score=0.0, metadata={"reason": "No output provided"})- normalized_output, normalized_expected = self._normalize(output, expected)- return await super()._run_eval_async(normalized_output, normalized_expected, **kwargs)-- def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs):- if not output:- return Score(name=self._name(), score=0.0, metadata={"reason": "No output provided"})- normalized_output, normalized_expected = self._normalize(output, expected)- return super()._run_eval_sync(normalized_output, normalized_expected, **kwargs)-- def __init__(self, **kwargs):- super().__init__(- name="dashboard_operation_accuracy",- prompt_template=DASHBOARD_OPERATION_ACCURACY_PROMPT,- choice_scores={"pass": 1.0, "fail": 0.0},- model="gpt-5.2",- max_tokens=2048,- reasoning_effort="medium",- **kwargs,- )---def call_agent_for_dashboard(demo_org_team_user):- """Run full agent graph with natural language dashboard requests."""- with (- patch("ee.hogai.tools.upsert_dashboard.tool.UpsertDashboardTool.is_dangerous_operation", return_value=False),- ):- _, team, user = demo_org_team_user-- graph = (- AssistantGraph(team, user)- .add_edge(AssistantNodeName.START, AssistantNodeName.ROOT)- .add_root()- .compile(checkpointer=DjangoCheckpointer())- )-- async def callable(input: EvalInput) -> dict:- conversation = await Conversation.objects.acreate(team=team, user=user)- initial_state = AssistantState(messages=[HumanMessage(content=input["input"])])- config = RunnableConfig(configurable={"thread_id": conversation.id}, recursion_limit=48)- raw_state = await graph.ainvoke(initial_state, config)- state = AssistantState.model_validate(raw_state)-- return _extract_dashboard_result(state)-- yield callable---def _extract_dashboard_result(state: AssistantState) -> dict:- """Extract dashboard operation result from final state."""- result: dict[str, Any] = {- "tool_called": None,- "action": None,- "tool_output": None,- "error": None,- }-- upsert_tool_call_id: str | None = None-- # Check for tool calls in messages- for msg in state.messages:- if isinstance(msg, AssistantMessage) and msg.tool_calls:- for tool_call in msg.tool_calls:- if tool_call.name == "upsert_dashboard":- result["tool_called"] = "upsert_dashboard"- result["action"] = tool_call.args.get("action", {}).get("action")- upsert_tool_call_id = tool_call.id- break-- # Find the tool call result message- for msg in state.messages:- if isinstance(msg, AssistantToolCallMessage) and msg.tool_call_id == upsert_tool_call_id:- result["tool_output"] = msg.content- if "error" in msg.content.lower() or "failed" in msg.content.lower():- result["error"] = msg.content- break-- return result---async def _create_dashboard(team, user, title: str, description: str):- dashboard = await Dashboard.objects.acreate(team=team, name=title, description=description, created_by=user)- insight = await Insight.objects.acreate(- team=team,- name="Mobile app screen views",- query=InsightVizNode(source=TrendsQuery(series=[EventsNode(name="$pageview")])).model_dump(- mode="json", exclude_none=True- ),- created_by=user,- saved=True,- deleted=False,- )- await DashboardTile.objects.acreate(dashboard=dashboard, insight=insight, layouts={}, deleted=False)- return dashboard--[email protected](autouse=True)-async def clear_dashboards():- start_dt = datetime.now()- yield- # Clean up new dashboards and insights- async for dashboard in Dashboard.objects.filter(created_at__gte=start_dt):- await dashboard.insights.filter(created_at__gte=start_dt).adelete()- await dashboard.adelete()---async def eval_create_dashboard(call_agent_for_dashboard, pytestconfig):- """Test dashboard creation via full agent with natural language prompts."""-- await MaxPublicEval(- experiment_name="upsert_dashboard_create",- task=call_agent_for_dashboard,- scores=[DashboardOperationAccuracy()],- data=[- EvalCase(- input=EvalInput(- input="I want to create a new dashboard to track user journeys from homepage to signup"- ),- expected=EvalExpected(- action="create",- insight_titles=["Homepage view to signup conversion", "User paths starting at homepage"],- ),- ),- EvalCase(- input=EvalInput(input="Put together a dashboard for key metrics"),- expected=EvalExpected(- action="No action",- ),- ),- EvalCase(- input=EvalInput(input="Create a dashboard showing how users navigate the site"),- expected=EvalExpected(- action="create",- # Should find this insight- insight_titles=["User paths starting at homepage"],- ),- ),- ],- pytestconfig=pytestconfig,- )---async def eval_update_dashboard(call_agent_for_dashboard, demo_org_team_user, pytestconfig):- """Test dashboard updates via full agent with natural language prompts."""- _, team, user = demo_org_team_user-- data = [- EvalCase(- input=EvalInput(- input="Add conversion from sign up to file upload to my mobile app dashboard",- dashboard=await _create_dashboard(- team, user, "Mobile App Metrics", "A dashboard for mobile app metrics"- ),- ),- expected=EvalExpected(- action="update",- insight_titles=["Mobile app screen views", "Conversion from sign up to file upload"],- ),- ),- EvalCase(- input=EvalInput(- input="The desktop app metrics dashboard needs a better name, something like '[Desktop]: Key Metrics'",- dashboard=await _create_dashboard(- team, user, "Desktop App Metrics", "A dashboard for desktop app metrics"- ),- ),- expected=EvalExpected(- action="update",- dashboard_name="[Desktop]: Key Metrics",- ),- ),- EvalCase(- input=EvalInput(- input="Break down insights by country in the promo campaign metrics dashboard",- dashboard=await _create_dashboard(- team, user, "Promo campaign metrics", "A dashboard for promo campaign metrics"- ),- ),- expected=EvalExpected(- action="update",- insight_titles=["Mobile app screen views by country"],- ),- ),- ]-- await MaxPublicEval(- experiment_name="upsert_dashboard_update",- task=call_agent_for_dashboard,- scores=[DashboardOperationAccuracy()],- data=data,- pytestconfig=pytestconfig,- )diff --git a/ee/hogai/eval/conftest.py b/ee/hogai/eval/conftest.pydeleted file mode 100644index 909ae68b9542..000000000000--- a/ee/hogai/eval/conftest.py+++ /dev/null@@ -1,72 +0,0 @@-from collections import namedtuple--import pytest-from unittest import mock--from _pytest.terminal import TerminalReporter--# We want the PostHog django_db_setup fixture here-from posthog.conftest import _django_db_setup # noqa: F401---def pytest_addoption(parser):- # Example: pytest ee/hogai/eval/ci/eval_sql.py --eval churn - to only run cases containing "churn" in input- parser.addoption("--eval", action="store")---_nodeid_to_results_url_map: dict[str, str] = {}-"""Map of test nodeid (file + test name) to Braintrust results URL."""--[email protected](scope="session")-def set_up_evals(django_db_setup, django_db_keepdb, django_db_blocker): # noqa: F811- yield from _django_db_setup(django_db_keepdb, django_db_blocker)--[email protected](autouse=True)-def capture_stdout(request, capsys):- yield- captured = capsys.readouterr()- if "See results for " in captured.out:- # Get only the line with the results link. The output we are extracting from is something like this:- # [...]- # 0.00$ (-00.02%) 'estimated_cost' (4 improvements, 3 regressions)- # See results for braintrust-more-evals-1747934384 at https://www.braintrust.dev/app/PostHog/p/max-ai-memory/experiments/braintrust-more-evals-1747934384- # Experiment braintrust-more-evals-1747934384 is running at https://www.braintrust.dev/app/PostHog/p/max-ai-memory/experiments/braintrust-more-evals-1747934384- # [...]- results_url = next(line for line in captured.out.split("\n") if "See results for " in line).split(" at ")[1]- _nodeid_to_results_url_map[request.node.nodeid] = results_url---class BraintrustURLReporter(TerminalReporter): # type: ignore- """- Our reporter adds one feature to the default one: for each passed eval_ test, it adds a link to the Braintrust results.- By default, passed tests don't get any short summary, but we can override that - which is what we do here.- """-- # No idea what type report.longrepr or report.longrrepr.reprcrash _should_ be, but this works- DummyLongRepr = namedtuple("DummyLongRepr", ["reprcrash"])- DummyReprCrash = namedtuple("DummyReprCrash", ["message"])-- def short_test_summary(self):- for report in self.stats.get("passed", []):- report.longrepr = self.DummyLongRepr(- reprcrash=self.DummyReprCrash(- message=_nodeid_to_results_url_map.get(report.nodeid, f"No Braintrust results for {report.nodeid}")- )- )- with mock.patch("_pytest.terminal.running_on_ci", return_value=True):- # Make pytest think we're running in CI, because annoyingly _pytest.terminal._get_line_with_reprcrash_message- # trims the short test summary (i.e. Braintrust URL) terminal width if it thinks we're not in CI- super().short_test_summary()--[email protected](trylast=True)-def pytest_configure(config):- if not str(config.rootdir).endswith("/ee/hogai/eval"):- return # No-op if not running specifically evals- # Register a custom reporter that adds a link to the Braintrust results- vanilla_reporter = config.pluginmanager.getplugin("terminalreporter")- braintrust_url_reporter = BraintrustURLReporter(config)- config.pluginmanager.unregister(vanilla_reporter)- config.pluginmanager.register(braintrust_url_reporter, "terminalreporter")diff --git a/ee/hogai/eval/offline/__init__.py b/ee/hogai/eval/offline/__init__.pydeleted file mode 100644index e69de29bb2d1..000000000000diff --git a/ee/hogai/eval/offline/conftest.py b/ee/hogai/eval/offline/conftest.pydeleted file mode 100644index 385f9a8ead7a..000000000000--- a/ee/hogai/eval/offline/conftest.py+++ /dev/null@@ -1,235 +0,0 @@-import os-import json-from collections.abc import Awaitable, Callable, Generator-from contextlib import contextmanager-from contextvars import ContextVar-from functools import wraps-from pathlib import Path-from typing import Annotated, Any-from uuid import UUID--import pytest--from django.conf import settings--from asgiref.sync import async_to_sync-from autoevals import Score-from autoevals.oai import LLMClient-from dagster_pipes import PipesContext, open_dagster_pipes-from openai import RateLimitError-from posthoganalytics import Posthog-from posthoganalytics.ai.langchain.callbacks import CallbackHandler-from posthoganalytics.ai.openai.openai_async import AsyncOpenAI-from pydantic import BaseModel, ConfigDict, Field, SkipValidation--from posthog.models import Organization, User-from posthog.ph_client import get_client--# We want the PostHog set_up_evals fixture here-from ee.hogai.eval.conftest import set_up_evals # noqa: F401-from ee.hogai.eval.offline.snapshot_loader import SnapshotLoader-from ee.hogai.eval.schema import DatasetInput, EvalsDockerImageConfig--[email protected](scope="session")-def dagster_context() -> Generator[PipesContext]:- with open_dagster_pipes() as context:- yield context---class TracedLLMClient(LLMClient):- """Fixed LLMClient that preserves the passed methods. autoevals has a bug (or not) that makes it overwrite the methods."""-- def __post_init__(self):- pass---class EvaluationContext(BaseModel):- model_config = ConfigDict(arbitrary_types_allowed=True) # We don't want to validate Django models here.-- organization: Annotated[Organization, SkipValidation]- user: Annotated[User, SkipValidation]- experiment_id: str- experiment_name: str- dataset_id: str- dataset_name: str- dataset_inputs: list[DatasetInput]- client: Posthog | None = Field(default=None)-- @property- def distinct_id(self) -> str:- return "ai_evaluator"-- @property- def formatted_experiment_name(self) -> str:- """Generate a unique experiment name for the given test name."""- test_name = get_eval_context().test_name- return f"max-ai-{self.experiment_name}-{test_name}"-- def get_callback_handlers(self, trace_id: UUID | str | None) -> list[CallbackHandler]:- return [- CallbackHandler(- self.client,- trace_id=trace_id,- distinct_id=self.distinct_id,- properties=self.properties_for_tracing,- )- ]-- @property- def properties_for_tracing(self) -> dict[str, Any]:- return {- "dataset_id": self.dataset_id,- "dataset_name": self.dataset_name,- "ai_experiment_id": self.experiment_id,- "ai_experiment_name": self.formatted_experiment_name,- }-- def get_openai_client_for_tracing(self, trace_id: UUID | str | None) -> TracedLLMClient:- """Override the OpenAI client to inject tracing parameters."""- client = AsyncOpenAI(posthog_client=self.client, base_url=settings.OPENAI_BASE_URL)- original_create = client.chat.completions.create-- async def patched_create(*args, **kwargs):- # Inject the tracing parameters- kwargs.setdefault(- "posthog_properties",- {- **self.properties_for_tracing,- "$ai_trace_id": trace_id,- "$ai_parent_id": trace_id,- "$ai_span_name": "Scorer",- },- )- kwargs.setdefault("posthog_distinct_id", self.distinct_id)- return await original_create(*args, **kwargs)-- client.chat.completions.create = patched_create-- return TracedLLMClient(- openai=client,- complete=patched_create,- embed=client.embeddings.create,- moderation=client.moderations.create,- is_async=True,- RateLimitError=RateLimitError,- )--[email protected](scope="session", autouse=True)-def eval_ctx(- set_up_evals, # noqa: F811- dagster_context: PipesContext,- django_db_blocker,-) -> Generator[EvaluationContext]:- """- Script that restores dumped Django models and patches AI query runners.- Creates teams with team_id=project_id for the same single user and organization,- keeping the original project_ids for teams.- """- with django_db_blocker.unblock():- dagster_context.log.info(f"Loading Postgres and ClickHouse snapshots...")-- posthog_client = get_client("US")-- config = EvalsDockerImageConfig.model_validate(dagster_context.extras)- loader = SnapshotLoader(dagster_context, config)- org, user = async_to_sync(loader.load_snapshots)()-- dagster_context.log.info(f"Running tests...")- yield EvaluationContext(- organization=org,- user=user,- experiment_id=config.experiment_id,- experiment_name=config.experiment_name,- dataset_id=config.dataset_id,- dataset_name=config.dataset_name,- dataset_inputs=config.dataset_inputs,- client=posthog_client,- )-- posthog_client.shutdown()-- dagster_context.log.info(f"Cleaning up...")- loader.cleanup()-- dagster_context.log.info(f"Reporting results...")- with open("eval_results.jsonl") as f:- lines = f.readlines()- dagster_context.report_asset_materialization(- asset_key="evaluation_report",- metadata={- "evaluation_results": [json.loads(line) for line in lines],- },- )---class LocalEvaluationContext(EvaluationContext):- test_name: str---_scoped_eval_context: ContextVar[LocalEvaluationContext] = ContextVar("eval_context")---@contextmanager-def set_eval_context(context: EvaluationContext, test_name: str):- """Set the local eval context for the duration of the context manager."""- token = _scoped_eval_context.set(LocalEvaluationContext(**context.model_dump(), test_name=test_name))- try:- yield- finally:- _scoped_eval_context.reset(token)---def get_eval_context() -> LocalEvaluationContext:- """Get the local eval context. Raises `LookupError` if no context is set."""- return _scoped_eval_context.get()---def capture_score(func: Callable[..., Awaitable[Score]]):- """Decorator that wraps scorer functions to capture the score result."""-- @wraps(func)- async def wrapper(input: DatasetInput, *args, **kwargs):- context = get_eval_context()- score = await func(input, *args, **kwargs)- if context.client is not None:- context.client.capture(- event="$ai_metric",- properties={- "$ai_trace_id": input.trace_id,- "$ai_metric_name": score.name,- "$ai_metric_value": str(score.score) if score.score is not None else "None",- "ai_score_metadata": score.metadata,- },- )- return score-- return wrapper---def with_eval_context(func):- """Decorator that sets the evaluation context for the test."""-- @wraps(func)- async def wrapper(eval_ctx: EvaluationContext, *args, **kwargs):- with set_eval_context(eval_ctx, func.__name__):- return await func(eval_ctx, *args, **kwargs)-- return wrapper---# Apply decorators to all tests in the package.-def pytest_collection_modifyitems(items):- """- One test file might contain multiple evaluation tests cases.- This hook will automatically apply the local evaluation context to all of them.- """- # pytest calls this hook with every item in the session, not only the ones under this- # directory, so the test runs tens of thousands of times on a full-tree shard. A string- # prefix is the same test as is_relative_to for these absolute paths, and it avoids both- # re-parsing item.fspath into a Path and walking Path.parents once per item.- current_dir_prefix = f"{Path(__file__).parent}{os.sep}"- for item in items:- if str(item.path).startswith(current_dir_prefix):- item.obj = with_eval_context(item.obj)diff --git a/ee/hogai/eval/offline/eval_sql.py b/ee/hogai/eval/offline/eval_sql.pydeleted file mode 100644index 558e7ec6d29c..000000000000--- a/ee/hogai/eval/offline/eval_sql.py+++ /dev/null@@ -1,131 +0,0 @@-import asyncio-from typing import TypedDict, cast--import pytest--from braintrust import EvalCase, Score-from langchain_core.runnables import RunnableConfig-from pydantic import BaseModel, Field--from posthog.schema import AssistantHogQLQuery, DataVisualizationNode, HumanMessage--from posthog.hogql.context import HogQLContext-from posthog.hogql.database.database import Database--from posthog.models import Team, User-from posthog.sync import database_sync_to_async--from products.posthog_ai.backend.models.assistant import Conversation--from ee.hogai.artifacts.manager import ArtifactManager-from ee.hogai.artifacts.utils import unwrap_visualization_artifact_content-from ee.hogai.chat_agent import AssistantGraph-from ee.hogai.eval.base import MaxPrivateEval-from ee.hogai.eval.offline.conftest import EvaluationContext, capture_score, get_eval_context-from ee.hogai.eval.schema import DatasetInput-from ee.hogai.eval.scorers.sql import SQLSemanticsCorrectness, SQLSyntaxCorrectness-from ee.hogai.utils.helpers import find_last_message_of_type-from ee.hogai.utils.types import AssistantState-from ee.hogai.utils.types.base import ArtifactRefMessage-from ee.hogai.utils.warehouse import serialize_database_schema---class EvalOutput(BaseModel):- database_schema: str- query_kind: str | None = Field(default=None)- sql_query: str | None = Field(default=None)---class EvalMetadata(TypedDict):- team_id: int---async def serialize_database(team: Team, user: User):- database = await database_sync_to_async(Database.create_for)(team=team, user=user)- context = HogQLContext(team=team, user=user, database=database, enable_select_queries=True)- return await serialize_database_schema(database, context)---async def call_graph(entry: DatasetInput, *args):- eval_ctx = get_eval_context()- team = await Team.objects.aget(id=entry.team_id)- conversation, database_schema = await asyncio.gather(- Conversation.objects.acreate(team=team, user=eval_ctx.user),- serialize_database(team=team, user=eval_ctx.user),- )- graph = AssistantGraph(team, eval_ctx.user).compile_full_graph()-- config = RunnableConfig(- callbacks=cast(list, eval_ctx.get_callback_handlers(entry.trace_id)),- configurable={- "thread_id": conversation.id,- "team": team,- "user": eval_ctx.user,- "distinct_id": eval_ctx.distinct_id,- },- )- state = await graph.ainvoke(- AssistantState(messages=[HumanMessage(content=entry.input["query"])]),- config,- )- maybe_viz_message = find_last_message_of_type(state["messages"], ArtifactRefMessage)- if maybe_viz_message:- artifact_manager = ArtifactManager(team=team, user=eval_ctx.user, config=config)- enriched_message = await artifact_manager.aenrich_message(maybe_viz_message)- content = unwrap_visualization_artifact_content(enriched_message)- if content is None:- return EvalOutput(database_schema=database_schema)- return EvalOutput(- database_schema=database_schema,- query_kind=content.query.kind,- sql_query=content.query.source.query- if isinstance(content.query, DataVisualizationNode)- else content.query.query- if isinstance(content.query, AssistantHogQLQuery)- else None,- )- return EvalOutput(database_schema=database_schema, query_kind=None, sql_query=None)---@capture_score-async def sql_semantics_scorer(input: DatasetInput, expected: str, output: EvalOutput, **kwargs) -> Score:- metric = SQLSemanticsCorrectness(client=get_eval_context().get_openai_client_for_tracing(input.trace_id))- return await metric.eval_async( # ty: ignore[invalid-return-type]- output.sql_query,- expected=expected,- input=input.input["query"],- database_schema=output.database_schema,- )---@capture_score-async def sql_syntax_scorer(input: DatasetInput, expected: str, output: EvalOutput, **kwargs) -> Score:- metric = SQLSyntaxCorrectness()- return await metric.eval_async( # ty: ignore[invalid-return-type]- output.sql_query,- expected=expected,- input=input.input["query"],- team=await Team.objects.aget(id=input.team_id),- database_schema=output.database_schema,- )---def generate_test_cases(eval_ctx: EvaluationContext):- for entry in eval_ctx.dataset_inputs:- metadata: EvalMetadata = {"team_id": entry.team_id}- yield EvalCase(- input=entry,- expected=entry.expected["output"],- metadata=cast(dict, metadata),- )---async def eval_offline_sql(eval_ctx: EvaluationContext, pytestconfig):- await MaxPrivateEval(- experiment_name=eval_ctx.formatted_experiment_name,- task=call_graph,- scores=[sql_syntax_scorer, sql_semantics_scorer],- data=generate_test_cases(eval_ctx),- pytestconfig=pytestconfig,- )diff --git a/ee/hogai/eval/offline/query_patches.py b/ee/hogai/eval/offline/query_patches.pydeleted file mode 100644index 500deef1ec9b..000000000000--- a/ee/hogai/eval/offline/query_patches.py+++ /dev/null@@ -1,65 +0,0 @@-from collections import defaultdict-from typing import Literal--from posthog.schema import (- ActorsPropertyTaxonomyQueryResponse,- ActorsPropertyTaxonomyResponse,- EventTaxonomyItem,- EventTaxonomyQueryResponse,- TeamTaxonomyItem,- TeamTaxonomyQueryResponse,-)--from posthog.hogql_queries.ai.actors_property_taxonomy_query_runner import ActorsPropertyTaxonomyQueryRunner-from posthog.hogql_queries.ai.event_taxonomy_query_runner import EventTaxonomyQueryRunner-from posthog.hogql_queries.ai.team_taxonomy_query_runner import TeamTaxonomyQueryRunner--# This is a global state that is used to store the patched results for the team taxonomy query.-TEAM_TAXONOMY_QUERY_DATA_SOURCE: dict[int, list[TeamTaxonomyItem]] = {}---class PatchedTeamTaxonomyQueryRunner(TeamTaxonomyQueryRunner):- def _calculate(self):- results: list[TeamTaxonomyItem] = []- if precomputed_results := TEAM_TAXONOMY_QUERY_DATA_SOURCE.get(self.team.id):- results = precomputed_results- return TeamTaxonomyQueryResponse(results=results, modifiers=self.modifiers)---# This is a global state that is used to store the patched results for the event taxonomy query.-EVENT_TAXONOMY_QUERY_DATA_SOURCE: dict[int, dict[str | int, list[EventTaxonomyItem]]] = defaultdict(dict)---class PatchedEventTaxonomyQueryRunner(EventTaxonomyQueryRunner):- def _calculate(self):- results: list[EventTaxonomyItem] = []- team_data = EVENT_TAXONOMY_QUERY_DATA_SOURCE.get(self.team.id, {})- if self.query.event in team_data:- results = team_data[self.query.event]- elif self.query.actionId in team_data:- results = team_data[self.query.actionId]- return EventTaxonomyQueryResponse(results=results, modifiers=self.modifiers)---# This is a global state that is used to store the patched results for the actors property taxonomy query.-ACTORS_PROPERTY_TAXONOMY_QUERY_DATA_SOURCE: dict[- int, dict[int | Literal["person"], dict[str, ActorsPropertyTaxonomyResponse]]-] = defaultdict(lambda: defaultdict(dict))---class PatchedActorsPropertyTaxonomyQueryRunner(ActorsPropertyTaxonomyQueryRunner):- def _calculate(self):- key: int | Literal["person"] = (- self.query.groupTypeIndex if isinstance(self.query.groupTypeIndex, int) else "person"- )- if (- self.team.id in ACTORS_PROPERTY_TAXONOMY_QUERY_DATA_SOURCE- and key in ACTORS_PROPERTY_TAXONOMY_QUERY_DATA_SOURCE[self.team.id]- ):- data = ACTORS_PROPERTY_TAXONOMY_QUERY_DATA_SOURCE[self.team.id][key]- result: list[ActorsPropertyTaxonomyResponse] = []- for prop in self.query.properties:- result.append(data.get(prop, ActorsPropertyTaxonomyResponse(sample_values=[], sample_count=0)))- else:- result = [ActorsPropertyTaxonomyResponse(sample_values=[], sample_count=0) for _ in self.query.properties]- return ActorsPropertyTaxonomyQueryResponse(results=result, modifiers=self.modifiers)diff --git a/ee/hogai/eval/offline/snapshot_loader.py b/ee/hogai/eval/offline/snapshot_loader.pydeleted file mode 100644index 5f933e40d806..000000000000--- a/ee/hogai/eval/offline/snapshot_loader.py+++ /dev/null@@ -1,196 +0,0 @@-import os-import asyncio-from collections.abc import Generator-from io import BytesIO-from typing import TYPE_CHECKING, Any, Literal, TypeVar--from unittest.mock import patch--import backoff-import aioboto3-from asgiref.sync import sync_to_async-from dagster_pipes import PipesContext-from fastavro import reader-from pydantic_avro import AvroBase--from posthog.models import Organization, Project, PropertyDefinition, Team, User-from posthog.persons_db import persons_db_aconnection--from products.warehouse_sources.backend.facade.models import DataWarehouseTable--from ee.hogai.eval.schema import (- ActorsPropertyTaxonomySnapshot,- DataWarehouseTableSnapshot,- EvalsDockerImageConfig,- GroupTypeMappingSnapshot,- PropertyDefinitionSnapshot,- PropertyTaxonomySnapshot,- TeamEvaluationSnapshot,- TeamSnapshot,- TeamTaxonomyItemSnapshot,-)--from .query_patches import (- ACTORS_PROPERTY_TAXONOMY_QUERY_DATA_SOURCE,- EVENT_TAXONOMY_QUERY_DATA_SOURCE,- TEAM_TAXONOMY_QUERY_DATA_SOURCE,- PatchedActorsPropertyTaxonomyQueryRunner,- PatchedEventTaxonomyQueryRunner,- PatchedTeamTaxonomyQueryRunner,-)--if TYPE_CHECKING:- from types_aiobotocore_s3.client import S3Client---T = TypeVar("T", bound=AvroBase)---class SnapshotLoader:- """Loads snapshots from S3, restores Django models, and patches query runners."""-- def __init__(self, context: PipesContext, config: EvalsDockerImageConfig):- self.context = context- self.config = config- self.patches: list[Any] = []-- async def load_snapshots(self) -> tuple[Organization, User]:- self.organization = await Organization.objects.acreate(name="PostHog")- self.user = await sync_to_async(User.objects.create_and_join)(self.organization, "[email protected]", "12345678")-- for snapshot in self.config.team_snapshots:- self.context.log.info(f"Loading Postgres snapshot for team {snapshot.team_id}...")-- project = await Project.objects.acreate(- id=await sync_to_async(Team.objects.increment_id_sequence)(), organization=self.organization- )-- (- project_snapshot_bytes,- property_definitions_snapshot_bytes,- group_type_mappings_snapshot_bytes,- data_warehouse_tables_snapshot_bytes,- event_taxonomy_snapshot_bytes,- properties_taxonomy_snapshot_bytes,- actors_property_taxonomy_snapshot_bytes,- ) = await self._get_all_snapshots(snapshot)-- team = await self._load_team_snapshot(project, snapshot.team_id, project_snapshot_bytes)- await asyncio.gather(- self._load_property_definitions(property_definitions_snapshot_bytes, team=team, project=project),- self._load_group_type_mappings(group_type_mappings_snapshot_bytes, team=team, project=project),- self._load_data_warehouse_tables(data_warehouse_tables_snapshot_bytes, team=team, project=project),- )- self._load_event_taxonomy(event_taxonomy_snapshot_bytes, team=team)- self._load_properties_taxonomy(properties_taxonomy_snapshot_bytes, team=team)- self._load_actors_property_taxonomy(actors_property_taxonomy_snapshot_bytes, team=team)-- self._patch_query_runners()-- return self.organization, self.user-- def cleanup(self):- for mock in self.patches:- mock.stop()-- @backoff.on_exception(backoff.expo, Exception, max_tries=3)- async def _get_all_snapshots(self, snapshot: TeamEvaluationSnapshot):- async with aioboto3.Session().client(- "s3",- endpoint_url=self.config.aws_endpoint_url,- aws_access_key_id=os.getenv("OBJECT_STORAGE_ACCESS_KEY_ID"),- aws_secret_access_key=os.getenv("OBJECT_STORAGE_SECRET_ACCESS_KEY"),- ) as client:- loaded_snapshots = await asyncio.gather(- self._get_snapshot_from_s3(client, snapshot.postgres.team),- self._get_snapshot_from_s3(client, snapshot.postgres.property_definitions),- self._get_snapshot_from_s3(client, snapshot.postgres.group_type_mappings),- self._get_snapshot_from_s3(client, snapshot.postgres.data_warehouse_tables),- self._get_snapshot_from_s3(client, snapshot.clickhouse.event_taxonomy),- self._get_snapshot_from_s3(client, snapshot.clickhouse.properties_taxonomy),- self._get_snapshot_from_s3(client, snapshot.clickhouse.actors_property_taxonomy),- )- return loaded_snapshots-- async def _get_snapshot_from_s3(self, client: "S3Client", file_key: str):- response = await client.get_object(Bucket=self.config.aws_bucket_name, Key=file_key)- content = await response["Body"].read()- return BytesIO(content)-- def _parse_snapshot_to_schema(self, schema: type[T], buffer: BytesIO) -> Generator[T]:- for record in reader(buffer):- yield schema.model_validate(record)-- async def _load_team_snapshot(self, project: Project, team_id: int, buffer: BytesIO) -> Team:- team_snapshot = next(self._parse_snapshot_to_schema(TeamSnapshot, buffer))- team = next(TeamSnapshot.deserialize_for_team([team_snapshot], team_id=team_id, project_id=project.id))- team.project = project- team.organization = self.organization- team.api_token = f"team_{team_id}"- await team.asave()- return team-- async def _load_property_definitions(self, buffer: BytesIO, *, team: Team, project: Project):- snapshot = list(self._parse_snapshot_to_schema(PropertyDefinitionSnapshot, buffer))- property_definitions = PropertyDefinitionSnapshot.deserialize_for_team(- snapshot, team_id=team.id, project_id=project.id- )- return await PropertyDefinition.objects.abulk_create(property_definitions, batch_size=500)-- async def _load_group_type_mappings(self, buffer: BytesIO, *, team: Team, project: Project):- snapshot = list(self._parse_snapshot_to_schema(GroupTypeMappingSnapshot, buffer))- group_type_mappings = list(- GroupTypeMappingSnapshot.deserialize_for_team(snapshot, team_id=team.id, project_id=project.id)- )- if not group_type_mappings:- return []- # Written through the off-ORM persons connection so the persons DB stays decoupled from Django.- async with persons_db_aconnection(writer=True) as conn, conn.cursor() as cursor:- await cursor.executemany(- "INSERT INTO posthog_grouptypemapping "- "(team_id, project_id, group_type, group_type_index, name_singular, name_plural) "- "VALUES (%s, %s, %s, %s, %s, %s)",- [- (m.team_id, m.project_id, m.group_type, m.group_type_index, m.name_singular, m.name_plural)- for m in group_type_mappings- ],- )- return group_type_mappings-- async def _load_data_warehouse_tables(self, buffer: BytesIO, *, team: Team, project: Project):- snapshot = list(self._parse_snapshot_to_schema(DataWarehouseTableSnapshot, buffer))- data_warehouse_tables = DataWarehouseTableSnapshot.deserialize_for_team(- snapshot, team_id=team.id, project_id=project.id- )- return await DataWarehouseTable.objects.abulk_create(data_warehouse_tables, batch_size=500)-- def _load_event_taxonomy(self, buffer: BytesIO, *, team: Team):- snapshot = next(self._parse_snapshot_to_schema(TeamTaxonomyItemSnapshot, buffer))- TEAM_TAXONOMY_QUERY_DATA_SOURCE[team.id] = snapshot.results-- def _load_properties_taxonomy(self, buffer: BytesIO, *, team: Team):- for item in self._parse_snapshot_to_schema(PropertyTaxonomySnapshot, buffer):- EVENT_TAXONOMY_QUERY_DATA_SOURCE[team.id][item.event] = item.results-- def _load_actors_property_taxonomy(self, buffer: BytesIO, *, team: Team):- for item in self._parse_snapshot_to_schema(ActorsPropertyTaxonomySnapshot, buffer):- key: int | Literal["person"] = item.group_type_index if isinstance(item.group_type_index, int) else "person"- ACTORS_PROPERTY_TAXONOMY_QUERY_DATA_SOURCE[team.pk][key][item.property] = item.results-- def _patch_query_runners(self):- self.patches = [- patch(- "posthog.hogql_queries.ai.team_taxonomy_query_runner.TeamTaxonomyQueryRunner",- new=PatchedTeamTaxonomyQueryRunner,- ),- patch(- "posthog.hogql_queries.ai.event_taxonomy_query_runner.EventTaxonomyQueryRunner",- new=PatchedEventTaxonomyQueryRunner,- ),- patch(- "posthog.hogql_queries.ai.actors_property_taxonomy_query_runner.ActorsPropertyTaxonomyQueryRunner",- new=PatchedActorsPropertyTaxonomyQueryRunner,- ),- ]- for mock in self.patches:- mock.start()diff --git a/ee/hogai/eval/pytest.ini b/ee/hogai/eval/pytest.inideleted file mode 100644index 13227db64f37..000000000000--- a/ee/hogai/eval/pytest.ini+++ /dev/null@@ -1,11 +0,0 @@-[pytest]-python_files = eval_*.py-python_classes = Eval*-python_functions = eval_*-env =- DEBUG=1- TEST=1- IN_EVAL_TESTING=1-DJANGO_SETTINGS_MODULE = posthog.settings-addopts = -p no:warnings --reuse-db -s -rfEp-asyncio_mode = autodiff --git a/ee/hogai/eval/schema.py b/ee/hogai/eval/schema.pydeleted file mode 100644index 0cb89c5b5c93..000000000000--- a/ee/hogai/eval/schema.py+++ /dev/null@@ -1,231 +0,0 @@-import json-from abc import ABC, abstractmethod-from collections.abc import Generator, Sequence-from typing import Any, Generic, Self, TypeVar--from django.db.models import Model--from pydantic import BaseModel, Field-from pydantic_avro import AvroBase--from posthog.schema import ActorsPropertyTaxonomyResponse, EventTaxonomyItem, TeamTaxonomyItem--from posthog.models import GroupTypeMapping, PropertyDefinition, Team--from products.warehouse_sources.backend.facade.models import DataWarehouseTable--T = TypeVar("T", bound=Model)---class BaseSnapshot(AvroBase, ABC, Generic[T]):- @classmethod- @abstractmethod- def serialize_for_team(cls, *, team_id: int) -> Generator[Self]:- raise NotImplementedError-- @classmethod- @abstractmethod- def deserialize_for_team(cls, models: Sequence[Self], *, team_id: int, project_id: int) -> Generator[T]:- raise NotImplementedError---# posthog/models/team.py-class TeamSnapshot(BaseSnapshot[Team]):- name: str- test_account_filters: str-- @classmethod- def serialize_for_team(cls, *, team_id: int):- team = Team.objects.get(pk=team_id)- yield TeamSnapshot(name=team.name, test_account_filters=json.dumps(team.test_account_filters))-- @classmethod- def deserialize_for_team(cls, models: Sequence[Self], *, team_id: int, project_id: int) -> Generator[Team]:- for model in models:- yield Team(- id=team_id,- project_id=project_id,- name=model.name,- test_account_filters=json.loads(model.test_account_filters),- )---# posthog/models/property_definition.py-class PropertyDefinitionSnapshot(BaseSnapshot[PropertyDefinition]):- name: str- is_numerical: bool- property_type: str | None- type: int- group_type_index: int | None-- @classmethod- def serialize_for_team(cls, *, team_id: int):- for prop in PropertyDefinition.objects.filter(team_id=team_id).iterator(500):- yield PropertyDefinitionSnapshot(- name=prop.name,- is_numerical=prop.is_numerical,- property_type=prop.property_type,- type=prop.type,- group_type_index=prop.group_type_index,- )-- @classmethod- def deserialize_for_team(cls, models: Sequence[Self], *, team_id: int, project_id: int):- for model in models:- yield PropertyDefinition(- name=model.name,- is_numerical=model.is_numerical,- property_type=model.property_type,- type=model.type,- group_type_index=model.group_type_index,- team_id=team_id,- project_id=project_id,- )---# posthog/models/group_type_mapping.py-class GroupTypeMappingSnapshot(BaseSnapshot[GroupTypeMapping]):- group_type: str- group_type_index: int- name_singular: str | None- name_plural: str | None-- @classmethod- def serialize_for_team(cls, *, team_id: int):- from posthog.models.group_type_mapping import get_group_types_for_team-- for m in get_group_types_for_team(team_id):- yield GroupTypeMappingSnapshot(- group_type=m["group_type"],- group_type_index=m["group_type_index"],- name_singular=m["name_singular"],- name_plural=m["name_plural"],- )-- @classmethod- def deserialize_for_team(cls, models: Sequence[Self], *, team_id: int, project_id: int):- for model in models:- yield GroupTypeMapping(- group_type=model.group_type,- group_type_index=model.group_type_index,- name_singular=model.name_singular,- name_plural=model.name_plural,- team_id=team_id,- project_id=project_id,- )---# posthog/models/warehouse/table.py-class DataWarehouseTableSnapshot(BaseSnapshot[DataWarehouseTable]):- name: str- format: str- columns: str-- @classmethod- def serialize_for_team(cls, *, team_id: int):- for table in DataWarehouseTable.objects.filter(team_id=team_id).iterator(500):- yield DataWarehouseTableSnapshot(- name=table.name,- format=table.format,- columns=json.dumps(table.columns) if table.columns else "",- )-- @classmethod- def deserialize_for_team(cls, models: Sequence[Self], *, team_id: int, project_id: int):- for model in models:- yield DataWarehouseTable(- name=model.name,- format=model.format,- columns=json.loads(model.columns) if model.columns else {},- url_pattern="http://localhost", # Hardcoded. It's not important for evaluations what the value is.- team_id=team_id,- )---class PostgresTeamDataSnapshot(BaseModel):- team: str- property_definitions: str- group_type_mappings: str- data_warehouse_tables: str---# posthog/hogql_queries/ai/team_taxonomy_query_runner.py-class TeamTaxonomyItemSnapshot(AvroBase):- results: list[TeamTaxonomyItem]---# posthog/hogql_queries/ai/event_taxonomy_query_runner.py-class PropertyTaxonomySnapshot(AvroBase):- event: str- results: list[EventTaxonomyItem]---# posthog/hogql_queries/ai/actors_property_taxonomy_query_runner.py-class ActorsPropertyTaxonomySnapshot(AvroBase):- group_type_index: int | None- property: str- results: ActorsPropertyTaxonomyResponse---class ClickhouseTeamDataSnapshot(BaseModel):- event_taxonomy: str- properties_taxonomy: str- actors_property_taxonomy: str---class TeamEvaluationSnapshot(BaseModel):- team_id: int- postgres: PostgresTeamDataSnapshot- clickhouse: ClickhouseTeamDataSnapshot---class DatasetInput(BaseModel):- team_id: int- trace_id: str | None = Field(default=None)- input: dict[str, Any] = Field(default_factory=dict)- expected: dict[str, Any] = Field(default_factory=dict)- metadata: dict[str, Any] = Field(default_factory=dict)---class EvalsDockerImageConfig(BaseModel):- class Config:- extra = "allow"-- aws_bucket_name: str- """- AWS S3 bucket name for the raw snapshots for all projects.- """- aws_endpoint_url: str- """- AWS S3 endpoint URL for the raw snapshots for all projects.- """- team_snapshots: list[TeamEvaluationSnapshot]- """- Raw snapshots for all projects.-- """- experiment_id: str- """- ID of the experiment.- """- experiment_name: str- """- Name of the experiment.- """-- dataset_id: str- """- ID of the dataset.- """- dataset_revision: int | None = None- """- Dataset revision used to prepare this evaluation.- """- dataset_name: str- """- Name of the dataset.- """- dataset_inputs: list[DatasetInput]- """- Parsed dataset.- """diff --git a/ee/hogai/eval/scorers/__init__.py b/ee/hogai/eval/scorers/__init__.pydeleted file mode 100644index 19aeb6ac75f6..000000000000--- a/ee/hogai/eval/scorers/__init__.py+++ /dev/null@@ -1,533 +0,0 @@-import json-from typing import Any, Generic, TypedDict, cast--from autoevals.llm import LLMClassifier-from autoevals.partial import ScorerWithPartial-from autoevals.ragas import AnswerSimilarity-from braintrust import Score-from pydantic import BaseModel--from posthog.schema import AssistantMessage, AssistantToolCall, NodeKind--from ee.hogai.utils.types.base import AnyAssistantGeneratedQuery, AnyPydanticModelQuery--from .sql import SQLSemanticsCorrectness, SQLSyntaxCorrectness--__all__ = [- "SQLSemanticsCorrectness",- "SQLSyntaxCorrectness",- "ToolRelevance",- "QueryKindSelection",- "PlanCorrectness",- "QueryAndPlanAlignment",- "TimeRangeRelevancy",- "InsightEvaluationAccuracy",- "DashboardCreationAccuracy",- "SemanticSimilarity",-]---class ToolRelevance(ScorerWithPartial):- semantic_similarity_args: set[str]- _tool_match_score = 0.5-- def __init__(self, *, semantic_similarity_args: set[str]):- self.semantic_similarity_args = semantic_similarity_args-- def _run_eval_sync(self, output, expected, **kwargs):- if expected is None:- return Score(name=self._name(), score=1 if not output or not output.tool_calls else 0)- if output is None:- return Score(name=self._name(), score=0)- if not isinstance(expected, AssistantToolCall):- raise TypeError(f"Eval case expected must be an AssistantToolCall, not {type(expected)}")- if not isinstance(output, AssistantMessage):- raise TypeError(f"Eval case output must be an AssistantMessage, not {type(output)}")-- score = max((self._score_tool_call(tool_call, expected) for tool_call in output.tool_calls or []), default=0.0)- return Score(name=self._name(), score=score)-- def _score_tool_call(self, tool_call: AssistantToolCall, expected: AssistantToolCall) -> float:- if tool_call.name != expected.name:- return 0.0- if not expected.args:- return 1.0 if not tool_call.args else self._tool_match_score-- score_per_arg = self._tool_match_score / len(expected.args)- argument_score = sum(- self._score_argument(arg_name, tool_call.args.get(arg_name), expected_arg_value)- for arg_name, expected_arg_value in expected.args.items()- )- return self._tool_match_score + argument_score * score_per_arg-- def _score_argument(self, name: str, actual_value: Any, expected_value: Any) -> float:- if name in self.semantic_similarity_args:- similarity = AnswerSimilarity(model="text-embedding-3-small").eval(- output=actual_value, expected=expected_value- )- return float(similarity.score or 0.0)- return float(actual_value == expected_value)---class PlanAndQueryOutput(TypedDict, Generic[AnyPydanticModelQuery], total=False):- plan: str | None- query: AnyAssistantGeneratedQuery | AnyPydanticModelQuery | None- query_generation_retry_count: int | None---class SerializedPlanAndQueryOutput(TypedDict):- plan: str | None- query: dict[str, Any] | None- query_generation_retry_count: int | None---def serialize_output(output: PlanAndQueryOutput | dict | None) -> SerializedPlanAndQueryOutput | None:- if output:- query = output.get("query")- serialized_output = {- **output,- "query": query.model_dump(exclude_none=True) if query else None,- }- return cast(SerializedPlanAndQueryOutput, serialized_output)- return None---class QueryKindSelection(ScorerWithPartial):- """Evaluate if the generated plan is of the correct type."""-- _expected: NodeKind-- def __init__(self, expected: NodeKind, **kwargs):- super().__init__(**kwargs)- self._expected = expected-- def _run_eval_sync(self, output: PlanAndQueryOutput, expected=None, **kwargs):- query = output.get("query")- if not query:- return Score(name=self._name(), score=None, metadata={"reason": "No query present"})- score = 1 if query.kind == self._expected else 0- return Score(- name=self._name(),- score=score,- metadata={"reason": f"Expected {self._expected}, got {query.kind}"} if not score else {},- )---class PlanCorrectness(LLMClassifier):- """Evaluate if the generated plan correctly answers the user's question."""-- async def _run_eval_async(self, output: PlanAndQueryOutput, expected=None, **kwargs):- plan = output.get("plan")- query = output.get("query")- if not plan or not query:- return Score(name=self._name(), score=0.0, metadata={"reason": "No plan or query present"})- return await super()._run_eval_async(serialize_output(output), serialize_output(expected), **kwargs)-- def _run_eval_sync(self, output: PlanAndQueryOutput, expected=None, **kwargs):- plan = output.get("plan")- query = output.get("query")- if not plan or not query:- return Score(name=self._name(), score=0.0, metadata={"reason": "No plan or query present"})- return super()._run_eval_sync(serialize_output(output), serialize_output(expected), **kwargs)-- def __init__(self, query_kind: NodeKind, evaluation_criteria: str, **kwargs):- super().__init__(- name="plan_correctness",- prompt_template="""-You will be given expected and actual generated plans to provide a taxonomy to answer the user's question with a {{query_kind}} insight.-By taxonomy, we mean the set of events, actions, math operations, property filters, cohort filters, and other project-specific elements that are used to answer the question.--Compare the plans to determine whether the taxonomy of the actual plan matches the expected plan.-Do not apply general knowledge about {{query_kind}} insights.--<evaluation_criteria>-{{evaluation_criteria}}-</evaluation_criteria>--<input_vs_output>-User question:-<user_question>-{{input}}-</user_question>--Expected plan:-<expected_plan>-{{expected.plan}}-</expected_plan>--Actual generated plan:-<output_plan>-{{output.plan}}-</output_plan>--</input_vs_output>--How would you rate the correctness of the plan? Choose one:-- perfect: The plan fully matches the expected plan and addresses the user question.-- near_perfect: The plan mostly matches the expected plan with at most one immaterial detail missed from the user question.-- slightly_off: The plan mostly matches the expected plan with minor discrepancies.-- somewhat_misaligned: The plan has some correct elements but misses key aspects of the expected plan or question.-- strongly_misaligned: The plan does not match the expected plan or fails to address the user question.-- useless: The plan is incomprehensible.--Details matter greatly here - including math types or property types - so be harsh.-""".strip(),- choice_scores={- "perfect": 1.0,- "near_perfect": 0.9,- "slightly_off": 0.75,- "somewhat_misaligned": 0.5,- "strongly_misaligned": 0.25,- "useless": 0.0,- },- model="gpt-4.1",- query_kind=query_kind,- evaluation_criteria=evaluation_criteria,- **kwargs,- )---MAX_JUDGE_JSON_SCHEMA_CHARS = 100_000---def build_judge_json_schema(query_kind: NodeKind, query_model: type[BaseModel]) -> str:- """Serialize a query schema for an LLM judge, keeping `$ref`s instead of inlining shared definitions.-- Insight toolkits dereference their schemas because the query generator's tool call needs a flat one.- That repeats the property filter unions inside every series node and roughly doubles the size, while- a judge reads references just as well.- """- json_schema_str = json.dumps(query_model.model_json_schema())- if len(json_schema_str) > MAX_JUDGE_JSON_SCHEMA_CHARS:- raise ValueError(- f"JSON schema of {query_kind} has blown up in size, are you sure you want to put this into an LLM? "- "You CAN increase this limit if you're sure"- )- return json_schema_str---class QueryAndPlanAlignment(LLMClassifier):- """Evaluate if the generated SQL query aligns with the plan generated in the previous step."""-- async def _run_eval_async(self, output: PlanAndQueryOutput, expected: PlanAndQueryOutput | None = None, **kwargs):- plan = output.get("plan")- if not plan:- return Score(- name=self._name(),- score=None,- metadata={"reason": "No plan present in the first place, skipping evaluation"},- )- query = output.get("query")- if not query:- return Score(name=self._name(), score=0.0, metadata={"reason": "Query failed to be generated"})- return await super()._run_eval_async(serialize_output(output), serialize_output(expected), **kwargs)-- def _run_eval_sync(self, output: PlanAndQueryOutput, expected: PlanAndQueryOutput | None = None, **kwargs):- plan = output.get("plan")- if not plan:- return Score(- name=self._name(),- score=None,- metadata={"reason": "No plan present in the first place, skipping evaluation"},- )- query = output.get("query")- if not query:- return Score(name=self._name(), score=0.0, metadata={"reason": "Query failed to be generated"})- return super()._run_eval_sync(serialize_output(output), serialize_output(expected), **kwargs)-- def __init__(self, query_kind: NodeKind, query_model: type[BaseModel], evaluation_criteria: str, **kwargs):- json_schema_str = build_judge_json_schema(query_kind, query_model)- super().__init__(- name="query_and_plan_alignment",- prompt_template="""-Evaluate if the generated {{query_kind}} aligns with the query plan.--Use knowledge of the {{query_kind}} schema, especially included descriptions:-<json_schema>-{{json_schema}}-</json_schema>--<evaluation_criteria>-{{evaluation_criteria}}--Note: It's fine to include filterTestAccounts or showLegend in the query by default.-</evaluation_criteria>--<input_vs_output>-Original user question, only for context:-<user_question>-{{input}}-</user_question>--Generated query plan:-<plan>-{{output.plan}}-</plan>--Expected query based on the plan:-<expected_query>-{{expected.query}}-</expected_query>--Actual generated query:-<output_query>-{{output.query}}-</output_query>-</input_vs_output>--How would you rate the alignment of the generated query with the plan? Choose one:-- perfect: The generated query fully matches the plan.-- near_perfect: The generated query matches the plan with at most one immaterial detail missed from the user question.-- slightly_off: The generated query mostly matches the plan, with minor discrepancies that may slightly change the meaning of the query.-- somewhat_misaligned: The generated query has some correct elements, but misses key aspects of the plan.-- strongly_misaligned: The generated query does not match the plan and fails to address the user question.-- useless: The generated query is basically incomprehensible.--Details matter greatly here - including math types or property types - so be harsh.""".strip(),- choice_scores={- "perfect": 1.0,- "near_perfect": 0.9,- "slightly_off": 0.75,- "somewhat_misaligned": 0.5,- "strongly_misaligned": 0.25,- "useless": 0.0,- },- model="gpt-4.1",- query_kind=query_kind,- json_schema=json_schema_str,- evaluation_criteria=evaluation_criteria,- max_tokens=1024,- **kwargs,- )---class TimeRangeRelevancy(LLMClassifier):- """Evaluate if the generated query's time range, interval, or period correctly answers the user's question."""-- async def _run_eval_async(self, output: PlanAndQueryOutput, expected: PlanAndQueryOutput | None = None, **kwargs):- if not output.get("query"):- return Score(name=self._name(), score=None, metadata={"reason": "No query to check, skipping evaluation"})- return await super()._run_eval_async(serialize_output(output), serialize_output(expected), **kwargs)-- def _run_eval_sync(self, output: PlanAndQueryOutput, expected: PlanAndQueryOutput | None = None, **kwargs):- if not output.get("query"):- return Score(name=self._name(), score=None, metadata={"reason": "No query to check"})- return super()._run_eval_sync(serialize_output(output), serialize_output(expected), **kwargs)-- def __init__(self, query_kind: NodeKind, **kwargs):- super().__init__(- name="time_range_relevancy",- prompt_template="""You will be given an original user question and the generated query (or query components) to answer that question.-Your goal is to determine if the time range, interval, or period in the generated query is relevant and correct based on the user's question.--<evaluation_criteria>-1. Explicit Time Mentions: If the user's question explicitly mentions a time range (e.g., "last 7 days", "this month", "January 2023", "before 2024-01-01"), the query MUST reflect this.- - For "last X days/weeks/months": Check if the query uses a relative date range (e.g., -Xd, -Xw, -Xm or `now() - interval 'X day/week/month'`).- - For "this month/year": Check if the query filters for the current month/year (e.g., `date_trunc('month', timestamp) = date_trunc('month', now())`).- - For specific dates or months (e.g., "January 2023", "this January"): Check if the query filters for the exact date or month and year.-2. Implicit Time Context: If the user's question implies a time context without being explicit (e.g., "recent activity", "trends over time"), the query should use a reasonable default time range (e.g., last 30 days, last 7 days) or an appropriate interval/period.-3. Interval/Period Correctness (for Trends, Retention, HogQL):- - Trends: If the question implies a specific granularity (e.g., "daily pageviews for the last 80 days" implies 'week' or 'day' interval, "pageviews over last five years" implies 'month' interval), the `interval` field in the query should match.- - Retention: If the question implies a cohort period (e.g., "daily retention", "weekly cohort"), the `period` field should match (e.g., "Day", "Week").- - HogQL: If the question implies aggregation over time periods (e.g. "average session duration by day of week"), check for appropriate time functions like `dayOfWeek` or `toStartOfWeek`.-4. No Time Mention: If the user's question has no discernible time component, the query can use a default time range, or no time filter if not applicable, and should not be penalized.-5. Excessive or Missing Time Filters: Penalize if the query includes time filters that contradict the user's question or omits them when clearly needed. For SQL, check if `timestamp` or relevant date fields are used in WHERE clauses for filtering.--Query type specific considerations for `output.query`:-- HogQL: `output.query` is an AssistantHogQLQuery object. The actual SQL string is in `output.query.query`. (HogQL is a flavor of standard SQL.)-- Trends: `output.query` is an AssistantTrendsQuery object. Check `output.query.dateRange` and `output.query.interval`.-- Funnels: `output.query` is an AssistantFunnelsQuery object. Check `output.query.dateRange`. Funnels do not have an interval.-- Retention: `output.query` is an AssistantRetentionQuery object. Check `output.query.dateRange` and `output.query.retentionFilter.period`.-</evaluation_criteria>--<input_vs_output>--User question:-<user_question>-{{input}}-</user_question>--Generated {{query_kind}} query components:-<output_query>-{{output.query}}-</output_query>--</input_vs_output>--How would you rate the time range relevancy of the generated query? Choose one:-- perfect: The time range, interval, and/or period in the query perfectly match the user's question or a sensible default if unspecified.-- near_perfect: The query's time components mostly match the user's question with at most one immaterial detail missed or slightly off.-- slightly_off: The query's time components have minor discrepancies that might slightly alter the insight but generally align with the question.-- somewhat_misaligned: The query's time components have some correct elements but miss key aspects of the question's time requirements or use inappropriate defaults.-- strongly_misaligned: The query's time components do not match the question's time requirements at all.-- not_applicable: The user's question has no time component, and the query correctly omits time filters or uses a broad default that doesn't interfere.-- useless: The query's time components are incomprehensible or completely wrong.-""".strip(),- choice_scores={- "perfect": 1.0,- "near_perfect": 0.9,- "slightly_off": 0.75,- "somewhat_misaligned": 0.5,- "strongly_misaligned": 0.25,- "not_applicable": 1.0,- "useless": 0.0,- },- model="gpt-4.1",- query_kind=query_kind,- **kwargs,- )---class InsightSearchOutput(TypedDict, total=False):- """Output structure for insight search evaluations."""-- selected_insights: list[int]- search_query: str | None- evaluation_result: dict | None---class InsightEvaluationAccuracy(ScorerWithPartial):- """Evaluate the accuracy of the insight evaluation decision (use existing vs create new)."""-- def _run_eval_sync(self, output: InsightSearchOutput, expected: bool | None = None, **kwargs):- evaluation_result = output.get("evaluation_result")- if not evaluation_result:- return Score(name=self._name(), score=None, metadata={"reason": "No evaluation result provided"})-- if expected is None:- return Score(name=self._name(), score=None, metadata={"reason": "No expected decision provided"})-- if "should_use_existing" not in evaluation_result:- return Score(- name=self._name(),- score=None,- metadata={- "reason": "Missing 'should_use_existing' key in evaluation result",- "evaluation_result_keys": list(evaluation_result.keys()),- },- )-- actual_decision = evaluation_result["should_use_existing"]-- # Binary accuracy score- score = 1.0 if actual_decision == expected else 0.0-- return Score(- name=self._name(),- score=score,- metadata={- "expected_decision": expected,- "actual_decision": actual_decision,- "evaluation_explanation": evaluation_result.get("explanation", ""),- },- )---class DashboardCreationAccuracy(LLMClassifier):- """Evaluate how well the generated dashboard creation output matches the expected input requirements."""-- async def _run_eval_async(self, output: str, expected: dict | None = None, **kwargs):- if not output:- return Score(name=self._name(), score=0.0, metadata={"reason": "No output provided"})- return await super()._run_eval_async(output, expected, **kwargs)-- def _run_eval_sync(self, output: str, expected: dict | None = None, **kwargs):- if not output:- return Score(name=self._name(), score=0.0, metadata={"reason": "No output provided"})- return super()._run_eval_sync(output, expected, **kwargs)-- def __init__(self, **kwargs):- super().__init__(- name="dashboard_creation_accuracy",- prompt_template="""-You will be given the expected dashboard creation requirements and the actual generated output to evaluate how well the output matches the input requirements.--<evaluation_criteria>-1. Dashboard Creation Success: The output should indicate successful dashboard creation (success: true, dashboard_id present, no error_message).-2. Dashboard Name Appropriateness: If a dashboard name is provided, it should be relevant to the requested content.-3. Insight Requirements Fulfillment: The created insights should match the search_insights_queries from the input:- - Number of insights mentioned should match the number of insights in the `search_insights_queries` field.- - Each insight should address the corresponding query requirements mentioned in the `search_insights_queries` field.- - Insight names and descriptions should be appropriate for the requested content- - The dashboard name should be relevant to the `dashboard_name` field.- - If an insight was not created it should be mentioned in the output message as such.-4. Query Alignment: The dashboard should fulfill the `dashboard_name` requirements.-5. Error Handling: If there are errors, they should be meaningful and not due to basic validation failures.-6. Make sure to check that the dashboards and insights have the corresponding hyperlinks.-</evaluation_criteria>--<expected_vs_actual_output>-Expected dashboard creation requirements:-<expected_output>-{{expected}}-</expected_output>--Actual generated output:-<actual_output>-{{output}}-</actual_output>-</expected_vs_actual_output>--How would you rate how well the generated output matches the expected output requirements? Choose one:-- perfect: The output perfectly fulfills all requirements from the expected output.-- near_perfect: The output fulfills most requirements with at most one minor detail missed.-- good: The output fulfills the main requirements but has some minor discrepancies.-- fair: The output partially fulfills the requirements but misses some important aspects.-- poor: The output has significant gaps in fulfilling the requirements.-- failed: The output completely fails to meet the requirements or has critical errors.--Be strict about matching the specific insight requirements and dashboard creation success.-""".strip(),- choice_scores={- "perfect": 1.0,- "near_perfect": 0.9,- "good": 0.75,- "fair": 0.5,- "poor": 0.25,- "failed": 0.0,- },- model="gpt-4.1",- max_tokens=1024,- **kwargs,- )---class SemanticSimilarity(ScorerWithPartial):- """Simple semantic similarity scorer for string comparison using embeddings."""-- def __init__(self, *, model: str = "text-embedding-3-small", **kwargs):- super().__init__(**kwargs)- self.model = model-- def _run_eval_sync(self, output: str | None, expected: str | None = None, **kwargs):- if expected is None:- return Score(name=self._name(), score=None, metadata={"reason": "No expected value provided"})- if output is None:- return Score(name=self._name(), score=None, metadata={"reason": "No output provided"})- similarity_scorer = AnswerSimilarity(model=self.model)- result = similarity_scorer.eval(output=output, expected=expected)- # Return score with threshold consideration- return Score(- name=self._name(),- score=result.score,- metadata={- "expected_query": expected,- "actual_query": output,- },- )---class ExactMatch(ScorerWithPartial):- """Evaluate if the output exactly matches the expected value."""-- def __init__(self, **kwargs):- super().__init__(**kwargs)-- def _run_eval_sync(self, output: str | None, expected: str | None = None, **kwargs):- if expected is None:- return Score(name=self._name(), score=None, metadata={"reason": "No expected value provided"})- if output is None:- return Score(name=self._name(), score=None, metadata={"reason": "No output provided"})- if output == expected:- return Score(name=self._name(), score=1.0, metadata={"output": output, "expected": expected})- return Score(name=self._name(), score=0.0, metadata={"output": output, "expected": expected})diff --git a/ee/hogai/eval/scorers/sql.py b/ee/hogai/eval/scorers/sql.pydeleted file mode 100644index 7a7e7684fb50..000000000000--- a/ee/hogai/eval/scorers/sql.py+++ /dev/null@@ -1,124 +0,0 @@-from typing import Any--from asgiref.sync import sync_to_async-from autoevals.llm import LLMClassifier-from braintrust import Score-from braintrust_core.score import Scorer--from posthog.hogql.errors import BaseHogQLError--from posthog.errors import InternalCHQueryError-from posthog.hogql_queries.hogql_query_runner import HogQLQueryRunner-from posthog.models.team.team import Team---def evaluate_sql_query(name: str, output: str | None, team: Team | None = None) -> Score:- if not output:- return Score(name=name, score=None, metadata={"reason": "No SQL query to verify, skipping evaluation"})- if not team:- return Score(name=name, score=None, metadata={"reason": "No team provided, skipping evaluation"})- query = {"query": output}- try:- # Try to parse, print, and run the query- HogQLQueryRunner(query, team).calculate()- except BaseHogQLError as e:- return Score(name=name, score=0.0, metadata={"reason": f"HogQL-level error: {str(e)}"})- except InternalCHQueryError as e:- return Score(name=name, score=0.5, metadata={"reason": f"ClickHouse-level error: {str(e)}"})- else:- return Score(name=name, score=1.0)---class SQLSyntaxCorrectness(Scorer):- """Evaluate if the generated SQL query has correct syntax."""-- def _name(self):- return "sql_syntax_correctness"-- async def _run_eval_async(self, output: str | None, expected: Any = None, team: Team | None = None, **kwargs):- return await sync_to_async(self._evaluate)(output, team)-- def _run_eval_sync(self, output: str | None, expected: Any = None, team: Team | None = None, **kwargs):- return self._evaluate(output, team)-- def _evaluate(self, output: str | None, team: Team | None = None) -> Score:- return evaluate_sql_query(self._name(), output, team)---SQL_SEMANTICS_CORRECTNESS_PROMPT = """-<system>-You are an expert ClickHouse SQL auditor.-Your job is to decide whether two ClickHouse SQL queries are **semantically equivalent for every possible valid database state**, given the same task description.--HogQL is an SQL flavor derived from ClickHouse SQL, with some PostHog-specific syntax:-- Easy access to JSON properties using `.`, like: `SELECT properties.$browser FROM events`-- Access to nested tables: `SELECT person.properties.foo FROM events`-- The `sessions` table contains session data related to events--When you respond, think step-by-step **internally**, but reveal **nothing** except the final verdict:-- Output **Pass** if the candidate query would always return the same result set (ignoring column aliases, ordering, or trivial formatting) as the reference query.-- Output **Fail** otherwise, or if you are uncertain.-Respond with a single word — **Pass** or **Fail** — and no additional text.-</system>--<input>-Task / natural-language question:-```-{{input}}-```--Database schema (tables and columns):-```-{{database_schema}}-```--Reference (human-labelled) SQL:-```sql-{{expected}}-```--Candidate (generated) SQL:-```sql-{{output}}-```-</input>--<reminder>-Think through edge cases: NULL handling, grouping, filters, joins, HAVING clauses, aggregations, sub-queries, limits, and data-type quirks.-If any logical difference could yield different outputs under some data scenario, the queries are *not* equivalent.-Important: The generated query should use `person_id` or `person.id` for any aggregation on unique users, not `distinct_id`.-For session duration, `session.$session_duration` should be used instead of `properties.$session_duration`.-</reminder>--When ready, output your verdict — **Pass** or **Fail** — with absolutely no extra characters.-""".strip()---class SQLSemanticsCorrectness(LLMClassifier):- """Evaluate if the actual query matches semantically the expected query."""-- def __init__(self, **kwargs):- super().__init__(- name="sql_semantics_correctness",- prompt_template=SQL_SEMANTICS_CORRECTNESS_PROMPT,- choice_scores={- "Pass": 1.0,- "Fail": 0.0,- },- model="gpt-5.2",- **kwargs,- )-- async def _run_eval_async(- self, output: str | None, expected: str | None = None, database_schema: str | None = None, **kwargs- ):- if not output or output.strip() == "":- return Score(name=self._name(), score=None, metadata={"reason": "No query to check, skipping evaluation"})- return await super()._run_eval_async(output, expected, database_schema=database_schema, **kwargs)-- def _run_eval_sync(- self, output: str | None, expected: str | None = None, database_schema: str | None = None, **kwargs- ):- if not output or output.strip() == "":- return Score(name=self._name(), score=None, metadata={"reason": "No query to check, skipping evaluation"})- return super()._run_eval_sync(output, expected, database_schema=database_schema, **kwargs)diff --git a/ee/hogai/test/test_eval_schema.py b/ee/hogai/test/test_eval_schema.pydeleted file mode 100644index 7b34e95d3516..000000000000--- a/ee/hogai/test/test_eval_schema.py+++ /dev/null@@ -1,223 +0,0 @@-import json-from io import BytesIO--from posthog.test.base import BaseTest--from django.test import SimpleTestCase--import fastavro--from products.warehouse_sources.backend.facade.models import DataWarehouseCredential, DataWarehouseTable--from ee.hogai.eval.schema import DataWarehouseTableSnapshot, EvalsDockerImageConfig---class TestEvalsDockerImageConfig(SimpleTestCase):- def test_dataset_revision_defaults_to_none_for_older_producers(self) -> None:- config = EvalsDockerImageConfig.model_validate(- {- "aws_bucket_name": "snapshots",- "aws_endpoint_url": "http://object-storage",- "team_snapshots": [],- "experiment_id": "experiment-id",- "experiment_name": "experiment-name",- "dataset_id": "dataset-id",- "dataset_name": "dataset-name",- "dataset_inputs": [],- }- )-- self.assertIsNone(config.dataset_revision)---class TestEvalSchema(BaseTest):- def setUp(self):- super().setUp()- self.credential = DataWarehouseCredential.objects.create(- access_key="test_key",- access_secret="test_secret",- team=self.team,- )-- def test_serialize_deserialize_for_team(self):- columns = {- "id": {"hogql": "IntegerDatabaseField", "valid": True, "clickhouse": "Int64"},- }- # Create test data warehouse tables- DataWarehouseTable.objects.create(- name="users_table",- format="Parquet",- team=self.team,- credential=self.credential,- url_pattern="http://example.com/users.parquet",- columns=columns,- )-- DataWarehouseTable.objects.create(- name="events_table",- format="CSV",- team=self.team,- credential=self.credential,- url_pattern="http://example.com/events.csv",- columns=columns,- )-- # Test serialization- snapshots = list(DataWarehouseTableSnapshot.serialize_for_team(team_id=self.team.id))-- self.assertEqual(len(snapshots), 2)-- # Test first table snapshot- self.assertEqual(snapshots[0].name, "users_table")- self.assertEqual(snapshots[0].format, "Parquet")- self.assertTrue(isinstance(snapshots[0].columns, str))- self.assertEqual(json.loads(snapshots[0].columns), columns)-- # Test second table snapshot- self.assertEqual(snapshots[1].name, "events_table")- self.assertEqual(snapshots[1].format, "CSV")- self.assertTrue(isinstance(snapshots[1].columns, str))- self.assertEqual(json.loads(snapshots[1].columns), columns)-- deserialized_snapshots = list(- DataWarehouseTableSnapshot.deserialize_for_team(snapshots, team_id=self.team.id, project_id=self.project.id)- )-- self.assertEqual(len(deserialized_snapshots), 2)-- self.assertEqual(deserialized_snapshots[0].name, "users_table")- self.assertEqual(deserialized_snapshots[0].format, "Parquet")- self.assertEqual(deserialized_snapshots[0].columns, columns)-- self.assertEqual(deserialized_snapshots[1].name, "events_table")- self.assertEqual(deserialized_snapshots[1].format, "CSV")- self.assertEqual(deserialized_snapshots[1].columns, columns)-- def test_serialize_deserialize_for_team_empty_columns(self):- # Create test data warehouse tables- DataWarehouseTable.objects.create(- name="users_table",- format="Parquet",- team=self.team,- credential=self.credential,- url_pattern="http://example.com/users.parquet",- columns=None,- )-- snapshots = list(DataWarehouseTableSnapshot.serialize_for_team(team_id=self.team.id))-- self.assertEqual(len(snapshots), 1)-- self.assertEqual(snapshots[0].name, "users_table")- self.assertEqual(snapshots[0].format, "Parquet")- self.assertEqual(snapshots[0].columns, "")-- deserialized_snapshots = list(- DataWarehouseTableSnapshot.deserialize_for_team(snapshots, team_id=self.team.id, project_id=self.project.id)- )-- self.assertEqual(len(deserialized_snapshots), 1)-- self.assertEqual(deserialized_snapshots[0].name, "users_table")- self.assertEqual(deserialized_snapshots[0].format, "Parquet")- self.assertEqual(deserialized_snapshots[0].columns, {})-- def test_fastavro_serialization(self):- """Test that a serialized DataWarehouseTableSnapshot can be dumped with fastavro"""- columns = {- "id": {"hogql": "IntegerDatabaseField", "valid": True, "clickhouse": "Int64"},- }-- # Create test data warehouse table- DataWarehouseTable.objects.create(- name="test_table",- format="Parquet",- team=self.team,- credential=self.credential,- url_pattern="http://example.com/test.parquet",- columns=columns,- )-- # Serialize to snapshot- snapshots = list(DataWarehouseTableSnapshot.serialize_for_team(team_id=self.team.id))- self.assertEqual(len(snapshots), 1)- snapshot = snapshots[0]-- # Get the Avro schema from the snapshot- avro_schema = snapshot.avro_schema()-- # Test that we can serialize the snapshot to Avro using fastavro- buffer = BytesIO()-- # Convert snapshot to dict for fastavro- snapshot_dict = snapshot.model_dump()-- # Write to Avro format- fastavro.writer(buffer, avro_schema, [snapshot_dict])-- # Verify we can read it back- buffer.seek(0)- reader = fastavro.reader(buffer)-- # Read back the data- records = list(- DataWarehouseTableSnapshot.deserialize_for_team(- [DataWarehouseTableSnapshot.model_validate(record) for record in reader],- team_id=self.team.id,- project_id=self.project.id,- )- )- self.assertEqual(len(records), 1)-- record = records[0]- self.assertEqual(record.name, "test_table")- self.assertEqual(record.format, "Parquet")- self.assertEqual(record.columns, columns)-- def test_fastavro_serialization_empty_columns(self):- """Test that a serialized DataWarehouseTableSnapshot can be dumped with fastavro"""- # Create test data warehouse table- DataWarehouseTable.objects.create(- name="test_table",- format="Parquet",- team=self.team,- credential=self.credential,- url_pattern="http://example.com/test.parquet",- columns=None,- )-- # Serialize to snapshot- snapshots = list(DataWarehouseTableSnapshot.serialize_for_team(team_id=self.team.id))- self.assertEqual(len(snapshots), 1)- snapshot = snapshots[0]-- # Get the Avro schema from the snapshot- avro_schema = snapshot.avro_schema()-- # Test that we can serialize the snapshot to Avro using fastavro- buffer = BytesIO()-- # Convert snapshot to dict for fastavro- snapshot_dict = snapshot.model_dump()-- # Write to Avro format- fastavro.writer(buffer, avro_schema, [snapshot_dict])-- # Verify we can read it back- buffer.seek(0)- reader = fastavro.reader(buffer)-- # Read back the data- records = list(- DataWarehouseTableSnapshot.deserialize_for_team(- [DataWarehouseTableSnapshot.model_validate(record) for record in reader],- team_id=self.team.id,- project_id=self.project.id,- )- )- self.assertEqual(len(records), 1)-- record = records[0]- self.assertEqual(record.name, "test_table")- self.assertEqual(record.format, "Parquet")- self.assertEqual(record.columns, {})diff --git a/ee/hogai/test/test_eval_scorers.py b/ee/hogai/test/test_eval_scorers.pydeleted file mode 100644index 8f5719abc404..000000000000--- a/ee/hogai/test/test_eval_scorers.py+++ /dev/null@@ -1,58 +0,0 @@-import json--from django.test import SimpleTestCase--from parameterized import parameterized-from pydantic import BaseModel--from posthog.schema import (- AssistantFunnelsQuery,- AssistantMessage,- AssistantRetentionQuery,- AssistantToolCall,- AssistantTrendsQuery,- NodeKind,-)--from ee.hogai.eval.scorers import MAX_JUDGE_JSON_SCHEMA_CHARS, ToolRelevance, build_judge_json_schema---class TestBuildJudgeJsonSchema(SimpleTestCase):- @parameterized.expand(- [- (NodeKind.TRENDS_QUERY, AssistantTrendsQuery),- (NodeKind.FUNNELS_QUERY, AssistantFunnelsQuery),- (NodeKind.RETENTION_QUERY, AssistantRetentionQuery),- ]- )- def test_insight_query_schema_fits_the_judge_budget(- self, query_kind: NodeKind, query_model: type[BaseModel]- ) -> None:- json_schema_str = build_judge_json_schema(query_kind, query_model)-- self.assertLessEqual(len(json_schema_str), MAX_JUDGE_JSON_SCHEMA_CHARS)- self.assertEqual(json.loads(json_schema_str)["title"], query_model.__name__)---class TestToolRelevance(SimpleTestCase):- def test_returns_zero_when_the_assistant_makes_no_tool_calls(self) -> None:- expected = AssistantToolCall(id="expected", name="create_insight", args={"query": "pageviews"})-- score = ToolRelevance(semantic_similarity_args=set())._run_eval_sync(AssistantMessage(content=""), expected)-- self.assertEqual(score.score, 0.0)-- def test_uses_the_best_matching_tool_call(self) -> None:- expected = AssistantToolCall(id="expected", name="create_insight", args={"query": "pageviews"})- output = AssistantMessage(- content="",- tool_calls=[- AssistantToolCall(id="wrong-tool", name="search", args={"query": "pageviews"}),- AssistantToolCall(id="partial-match", name="create_insight", args={"query": "users"}),- AssistantToolCall(id="full-match", name="create_insight", args={"query": "pageviews"}),- ],- )-- score = ToolRelevance(semantic_similarity_args=set())._run_eval_sync(output, expected)-- self.assertEqual(score.score, 1.0)diff --git a/ee/hogai/test/test_query_patches.py b/ee/hogai/test/test_query_patches.pydeleted file mode 100644index 5c9a7b9bd0dd..000000000000--- a/ee/hogai/test/test_query_patches.py+++ /dev/null@@ -1,133 +0,0 @@-from posthog.test.base import BaseTest--from posthog.schema import (- ActorsPropertyTaxonomyQuery,- ActorsPropertyTaxonomyResponse,- EventTaxonomyItem,- EventTaxonomyQuery,- TeamTaxonomyItem,- TeamTaxonomyQuery,-)--from ee.hogai.eval.offline.query_patches import (- ACTORS_PROPERTY_TAXONOMY_QUERY_DATA_SOURCE,- EVENT_TAXONOMY_QUERY_DATA_SOURCE,- TEAM_TAXONOMY_QUERY_DATA_SOURCE,- PatchedActorsPropertyTaxonomyQueryRunner,- PatchedEventTaxonomyQueryRunner,- PatchedTeamTaxonomyQueryRunner,-)---class TestQueryPatches(BaseTest):- def setUp(self):- super().setUp()- TEAM_TAXONOMY_QUERY_DATA_SOURCE[self.team.id] = [- TeamTaxonomyItem(count=10, event="$pageview"),- ]- EVENT_TAXONOMY_QUERY_DATA_SOURCE[self.team.id] = {- "$pageview": [- EventTaxonomyItem(property="$browser", sample_values=["Safari"], sample_count=1),- ],- }- ACTORS_PROPERTY_TAXONOMY_QUERY_DATA_SOURCE[self.team.id]["person"] = {- "$location": ActorsPropertyTaxonomyResponse(sample_values=["US"], sample_count=1),- "$browser": ActorsPropertyTaxonomyResponse(sample_values=["Safari"], sample_count=10),- }- ACTORS_PROPERTY_TAXONOMY_QUERY_DATA_SOURCE[self.team.id][0] = {- "$device": ActorsPropertyTaxonomyResponse(sample_values=["Phone"], sample_count=1),- }-- def tearDown(self):- super().tearDown()- TEAM_TAXONOMY_QUERY_DATA_SOURCE.clear()- EVENT_TAXONOMY_QUERY_DATA_SOURCE.clear()- ACTORS_PROPERTY_TAXONOMY_QUERY_DATA_SOURCE.clear()-- def test_patched_team_taxonomy_query_runner_returns_result(self):- query_runner = PatchedTeamTaxonomyQueryRunner(- team=self.team,- query=TeamTaxonomyQuery(),- ).calculate()- self.assertEqual(query_runner.results, [TeamTaxonomyItem(count=10, event="$pageview")])-- def test_patched_team_taxonomy_query_runner_handles_no_results(self):- TEAM_TAXONOMY_QUERY_DATA_SOURCE.clear()- query_runner = PatchedTeamTaxonomyQueryRunner(- team=self.team,- query=TeamTaxonomyQuery(),- ).calculate()- self.assertEqual(query_runner.results, [])-- def test_patched_event_taxonomy_query_runner_returns_result(self):- query_runner = PatchedEventTaxonomyQueryRunner(- team=self.team,- query=EventTaxonomyQuery(event="$pageview"),- ).calculate()- self.assertEqual(- query_runner.results, [EventTaxonomyItem(property="$browser", sample_values=["Safari"], sample_count=1)]- )-- def test_patched_event_taxonomy_query_runner_handles_no_results(self):- EVENT_TAXONOMY_QUERY_DATA_SOURCE.clear()- query_runner = PatchedEventTaxonomyQueryRunner(- team=self.team,- query=EventTaxonomyQuery(event="$pageview"),- ).calculate()- self.assertEqual(query_runner.results, [])-- def test_patched_event_taxonomy_query_runner_returns_result_for_action_id(self):- EVENT_TAXONOMY_QUERY_DATA_SOURCE[self.team.id][123] = [- EventTaxonomyItem(property="$browser", sample_values=["Safari"], sample_count=1),- ]- query_runner = PatchedEventTaxonomyQueryRunner(- team=self.team,- query=EventTaxonomyQuery(actionId=123),- ).calculate()- self.assertEqual(- query_runner.results,- [EventTaxonomyItem(property="$browser", sample_values=["Safari"], sample_count=1)],- )-- def test_patched_actors_property_taxonomy_query_runner_returns_result(self):- query_runner = PatchedActorsPropertyTaxonomyQueryRunner(- team=self.team,- query=ActorsPropertyTaxonomyQuery(groupTypeIndex=0, properties=["$device"]),- ).calculate()- self.assertEqual(- query_runner.results,- [ActorsPropertyTaxonomyResponse(sample_values=["Phone"], sample_count=1)],- )-- query_runner = PatchedActorsPropertyTaxonomyQueryRunner(- team=self.team,- query=ActorsPropertyTaxonomyQuery(properties=["$location", "$browser"]),- ).calculate()- self.assertEqual(- query_runner.results,- [- ActorsPropertyTaxonomyResponse(sample_values=["US"], sample_count=1),- ActorsPropertyTaxonomyResponse(sample_values=["Safari"], sample_count=10),- ],- )-- def test_patched_actors_property_taxonomy_query_runner_handles_mixed_results(self):- query_runner = PatchedActorsPropertyTaxonomyQueryRunner(- team=self.team,- query=ActorsPropertyTaxonomyQuery(properties=["$location", "$latitude"]),- ).calculate()- self.assertEqual(- query_runner.results,- [- ActorsPropertyTaxonomyResponse(sample_values=["US"], sample_count=1),- ActorsPropertyTaxonomyResponse(sample_values=[], sample_count=0),- ],- )-- def test_patched_actors_property_taxonomy_query_runner_handles_no_results(self):- ACTORS_PROPERTY_TAXONOMY_QUERY_DATA_SOURCE.clear()- query_runner = PatchedActorsPropertyTaxonomyQueryRunner(- team=self.team,- query=ActorsPropertyTaxonomyQuery(properties=["$device"]),- ).calculate()- self.assertEqual(query_runner.results, [ActorsPropertyTaxonomyResponse(sample_values=[], sample_count=0)])diff --git a/ee/hogai/test/test_snapshot_loader.py b/ee/hogai/test/test_snapshot_loader.pydeleted file mode 100644index 569c80015234..000000000000--- a/ee/hogai/test/test_snapshot_loader.py+++ /dev/null@@ -1,286 +0,0 @@-from __future__ import annotations--import json-from io import BytesIO-from typing import Any--import pytest-from posthog.test.base import BaseTest-from unittest.mock import AsyncMock, MagicMock, patch--from asgiref.sync import async_to_sync--from posthog.schema import (- ActorsPropertyTaxonomyQuery,- ActorsPropertyTaxonomyResponse,- EventTaxonomyItem,- EventTaxonomyQuery,- TeamTaxonomyItem,- TeamTaxonomyQuery,-)--from posthog.hogql_queries.query_runner import get_query_runner-from posthog.models import Organization, PropertyDefinition, Team-from posthog.persons_db import persons_db_connection--from products.warehouse_sources.backend.facade.models import DataWarehouseTable--from ee.hogai.eval.offline.query_patches import (- ACTORS_PROPERTY_TAXONOMY_QUERY_DATA_SOURCE,- EVENT_TAXONOMY_QUERY_DATA_SOURCE,- TEAM_TAXONOMY_QUERY_DATA_SOURCE,-)-from ee.hogai.eval.offline.snapshot_loader import SnapshotLoader-from ee.hogai.eval.schema import (- ActorsPropertyTaxonomySnapshot,- ClickhouseTeamDataSnapshot,- DataWarehouseTableSnapshot,- EvalsDockerImageConfig,- GroupTypeMappingSnapshot,- PostgresTeamDataSnapshot,- PropertyDefinitionSnapshot,- PropertyTaxonomySnapshot,- TeamSnapshot,- TeamTaxonomyItemSnapshot,-)--pytestmark = pytest.mark.persons_db_direct---class TestSnapshotLoader(BaseTest):- # Team ids this class loads snapshots for. Keep in sync with the ids passed to _extras() (asserted there).- LOADED_TEAM_IDS = (9990, 99990)-- def _clear_loaded_group_type_mappings(self):- # _load_group_type_mappings commits GTM rows through the off-ORM persons connection (outside the- # test transaction), so they don't roll back. Clear them scoped to this class's teams — in setUp- # to recover from a prior run that left rows, and in tearDown so they can't bleed into later tests- # sharing the persons DB.- with persons_db_connection(writer=True, autocommit=True) as conn, conn.cursor() as cursor:- cursor.execute("DELETE FROM posthog_grouptypemapping WHERE team_id = ANY(%s)", [list(self.LOADED_TEAM_IDS)])-- def setUp(self):- super().setUp()- self._clear_loaded_group_type_mappings()- TEAM_TAXONOMY_QUERY_DATA_SOURCE.clear()- EVENT_TAXONOMY_QUERY_DATA_SOURCE.clear()- ACTORS_PROPERTY_TAXONOMY_QUERY_DATA_SOURCE.clear()-- def tearDown(self):- self._clear_loaded_group_type_mappings()- TEAM_TAXONOMY_QUERY_DATA_SOURCE.clear()- EVENT_TAXONOMY_QUERY_DATA_SOURCE.clear()- ACTORS_PROPERTY_TAXONOMY_QUERY_DATA_SOURCE.clear()- super().tearDown()-- def _extras(self, team_id: int) -> dict[str, Any]:- assert team_id in self.LOADED_TEAM_IDS, "Add new test team ids to LOADED_TEAM_IDS so cleanup stays scoped"- return {- "aws_endpoint_url": "http://localhost:9000",- "aws_bucket_name": "evals",- "experiment_name": "offline_evaluation",- "team_snapshots": [- {- "team_id": team_id,- "postgres": PostgresTeamDataSnapshot(- team=f"pg/team_{team_id}.avro",- property_definitions=f"pg/property_defs_{team_id}.avro",- group_type_mappings=f"pg/group_mappings_{team_id}.avro",- data_warehouse_tables=f"pg/dw_tables_{team_id}.avro",- ).model_dump(),- "clickhouse": ClickhouseTeamDataSnapshot(- event_taxonomy=f"ch/event_taxonomy_{team_id}.avro",- properties_taxonomy=f"ch/properties_taxonomy_{team_id}.avro",- actors_property_taxonomy=f"ch/actors_property_taxonomy_{team_id}.avro",- ).model_dump(),- }- ],- "dataset": [],- "experiment_id": "test_experiment_id",- "dataset_id": "test_dataset_id",- "dataset_revision": None,- "dataset_name": "test_dataset_name",- "dataset_inputs": [],- }-- def _fake_parse(self, schema, _buffer):- if schema is TeamSnapshot:- yield TeamSnapshot(name="Evaluated Team", test_account_filters="{}")- return- if schema is PropertyDefinitionSnapshot:- yield PropertyDefinitionSnapshot(- name="$browser", is_numerical=False, property_type="String", type=1, group_type_index=None- )- yield PropertyDefinitionSnapshot(- name="$device", is_numerical=False, property_type="String", type=1, group_type_index=0- )- return- if schema is GroupTypeMappingSnapshot:- yield GroupTypeMappingSnapshot(- group_type="organization", group_type_index=0, name_singular="org", name_plural="orgs"- )- yield GroupTypeMappingSnapshot(- group_type="company", group_type_index=1, name_singular="company", name_plural="companies"- )- return- if schema is DataWarehouseTableSnapshot:- yield DataWarehouseTableSnapshot(name="users", format="Parquet", columns=json.dumps({"id": "Int64"}))- yield DataWarehouseTableSnapshot(name="orders", format="Parquet", columns=json.dumps({"id": "Int64"}))- return- if schema is TeamTaxonomyItemSnapshot:- yield TeamTaxonomyItemSnapshot(- results=[- TeamTaxonomyItem(count=123, event="$pageview"),- TeamTaxonomyItem(count=45, event="$autocapture"),- ]- )- return- if schema is PropertyTaxonomySnapshot:- # Two events to fill EVENT_TAXONOMY_QUERY_DATA_SOURCE- yield PropertyTaxonomySnapshot(- event="$pageview",- results=[- EventTaxonomyItem(property="$browser", sample_values=["Safari"], sample_count=10),- EventTaxonomyItem(property="$os", sample_values=["macOS"], sample_count=5),- ],- )- yield PropertyTaxonomySnapshot(- event="$autocapture",- results=[- EventTaxonomyItem(property="$element_type", sample_values=["a"], sample_count=3),- ],- )- return- if schema is ActorsPropertyTaxonomySnapshot:- # person (None), group 0, and group 1- yield ActorsPropertyTaxonomySnapshot(- group_type_index=None,- property="$browser",- results=ActorsPropertyTaxonomyResponse(sample_values=["Safari"], sample_count=10),- )- yield ActorsPropertyTaxonomySnapshot(- group_type_index=0,- property="$device",- results=ActorsPropertyTaxonomyResponse(sample_values=["Phone"], sample_count=2),- )- yield ActorsPropertyTaxonomySnapshot(- group_type_index=1,- property="$industry",- results=ActorsPropertyTaxonomyResponse(sample_values=["Tech"], sample_count=1),- )- return- raise AssertionError(f"Unhandled schema in fake parser: {schema}")-- def _build_context(self, extras: dict[str, Any]) -> MagicMock:- ctx = MagicMock()- ctx.extras = extras- ctx.log = MagicMock()- ctx.log.info = MagicMock()- return ctx-- def _load_with_mocks(self) -> tuple[Organization, Any, list[Any], Team]:- extras = self._extras(9990)- ctx = self._build_context(extras)-- async_get = AsyncMock(side_effect=lambda client, key: BytesIO(b"ok"))-- with patch.object(SnapshotLoader, "_get_snapshot_from_s3", new=async_get):- with patch.object(SnapshotLoader, "_parse_snapshot_to_schema", new=self._fake_parse):- config = EvalsDockerImageConfig.model_validate(ctx.extras)- loader = SnapshotLoader(ctx, config)- org, user = async_to_sync(loader.load_snapshots)()- return org, user, config.dataset_inputs, Team.objects.get(id=9990)-- def test_loads_data_from_s3(self):- team_id = 99990- extras = self._extras(team_id)- ctx = self._build_context(extras)-- calls: list[tuple[dict[str, Any], str]] = []-- async def record_call(_self, client, key: str):- calls.append(({"Bucket": extras["aws_bucket_name"]}, key))- return BytesIO(b"ok")-- with patch.object(SnapshotLoader, "_get_snapshot_from_s3", new=record_call):- with patch.object(SnapshotLoader, "_parse_snapshot_to_schema", new=self._fake_parse):- config = EvalsDockerImageConfig.model_validate(ctx.extras)- loader = SnapshotLoader(ctx, config)- async_to_sync(loader.load_snapshots)()-- keys = [k for _, k in calls]- self.assertIn(f"pg/team_{team_id}.avro", keys)- self.assertIn(f"pg/property_defs_{team_id}.avro", keys)- self.assertIn(f"pg/group_mappings_{team_id}.avro", keys)- self.assertIn(f"pg/dw_tables_{team_id}.avro", keys)- self.assertIn(f"ch/event_taxonomy_{team_id}.avro", keys)- self.assertIn(f"ch/properties_taxonomy_{team_id}.avro", keys)- self.assertIn(f"ch/actors_property_taxonomy_{team_id}.avro", keys)-- def test_restores_org_team_user(self):- org, user, _dataset, team = self._load_with_mocks()- self.assertEqual(org.name, "PostHog")- self.assertEqual(team.organization_id, org.id)- self.assertEqual(team.id, 9990)- self.assertEqual(team.api_token, "team_9990")-- def test_restores_models_counts(self):- _org, _user, _dataset, team = self._load_with_mocks()- self.assertEqual(PropertyDefinition.objects.filter(team_id=team.id).count(), 2)- with persons_db_connection(writer=False) as conn, conn.cursor() as cursor:- cursor.execute("SELECT count(*) FROM posthog_grouptypemapping WHERE team_id = %s", (team.id,))- row = cursor.fetchone()- group_type_mapping_count = row[0] if row else 0- self.assertEqual(group_type_mapping_count, 2)- self.assertEqual(DataWarehouseTable.objects.filter(team_id=team.id).count(), 2)-- def test_loads_team_taxonomy_data_source(self):- _org, _user, _dataset, team = self._load_with_mocks()- self.assertIn(team.id, TEAM_TAXONOMY_QUERY_DATA_SOURCE)- self.assertEqual([i.event for i in TEAM_TAXONOMY_QUERY_DATA_SOURCE[team.id]], ["$pageview", "$autocapture"])-- def test_loads_event_taxonomy_data_source(self):- _org, _user, _dataset, team = self._load_with_mocks()- self.assertIn("$pageview", EVENT_TAXONOMY_QUERY_DATA_SOURCE[team.id])- self.assertIn("$autocapture", EVENT_TAXONOMY_QUERY_DATA_SOURCE[team.id])- props = [i.property for i in EVENT_TAXONOMY_QUERY_DATA_SOURCE[team.id]["$pageview"]]- self.assertIn("$browser", props)- self.assertIn("$os", props)-- def test_loads_actors_property_taxonomy_data_source_various_group_types(self):- _org, _user, _dataset, team = self._load_with_mocks()- self.assertIn("person", ACTORS_PROPERTY_TAXONOMY_QUERY_DATA_SOURCE[team.id])- self.assertIn(0, ACTORS_PROPERTY_TAXONOMY_QUERY_DATA_SOURCE[team.id])- self.assertIn(1, ACTORS_PROPERTY_TAXONOMY_QUERY_DATA_SOURCE[team.id])-- def test_runs_query_runner_patches(self):- _org, _user, _dataset, team = self._load_with_mocks()-- # Team taxonomy- team_resp = get_query_runner(TeamTaxonomyQuery(), team=team).calculate()- self.assertTrue(any(item.event == "$pageview" for item in team_resp.results))-- # Event taxonomy by event- event_resp = get_query_runner(EventTaxonomyQuery(event="$pageview", maxPropertyValues=5), team=team).calculate()- self.assertTrue(any(item.property == "$browser" for item in event_resp.results))-- # Actors property taxonomy for person- actors_resp_person = get_query_runner(- ActorsPropertyTaxonomyQuery(properties=["$browser"], groupTypeIndex=None),- team=team,- ).calculate()- self.assertEqual(actors_resp_person.results[0].sample_values, ["Safari"])-- # Actors property taxonomy for group 0- actors_resp_group0 = get_query_runner(- ActorsPropertyTaxonomyQuery(properties=["$device"], groupTypeIndex=0),- team=team,- ).calculate()- self.assertEqual(actors_resp_group0.results[0].sample_values, ["Phone"])-- # Actors property taxonomy for group 1- actors_resp_group1 = get_query_runner(- ActorsPropertyTaxonomyQuery(properties=["$industry"], groupTypeIndex=1),- team=team,- ).calculate()- self.assertEqual(actors_resp_group1.results[0].sample_values, ["Tech"])diff --git a/frontend/bin/ci-report/update-ci-report.mjs b/frontend/bin/ci-report/update-ci-report.mjsindex 0ad96a535788..a45038484400 100644--- a/frontend/bin/ci-report/update-ci-report.mjs+++ b/frontend/bin/ci-report/update-ci-report.mjs@@ -32,7 +32,6 @@ export const SECTIONS = [{ id: 'backend-snapshots', title: 'Backend snapshots' },{ id: 'backend-coverage', title: 'Backend coverage' },{ id: 'mcp-snapshots', title: 'MCP snapshots' },- { id: 'ai-evals', title: 'AI evals' },{ id: 'django-migration-sql', title: 'Django migration SQL' },{ id: 'django-migration-risk', title: 'Django migration risk' },{ id: 'ch-migration-sql', title: 'ClickHouse migration SQL' },diff --git a/hogli.yaml b/hogli.yamlindex 8d0d5916e656..4c371ece21a0 100644--- a/hogli.yaml+++ b/hogli.yaml@@ -666,10 +666,6 @@ docker:bin_script: docker-worker-celerydescription: Start Celery worker with optional scheduler, gossip, heartbeat, minglehidden: true- docker:ai-evals:- bin_script: docker-ai-evals- description: Set up Docker services and run evaluation scripts with cleanup- hidden: truemigrations:db:migrate:bin_script: migratediff --git a/posthog/dags/locations/posthog_ai.py b/posthog/dags/locations/posthog_ai.pydeleted file mode 100644index 3b0785e7a6b1..000000000000--- a/posthog/dags/locations/posthog_ai.py+++ /dev/null@@ -1,15 +0,0 @@-import dagster-from dagster_docker import PipesDockerClient--from products.posthog_ai.dags.run_evaluation import run_evaluation--from . import loggers, resources--defs = dagster.Definitions(- jobs=[run_evaluation],- loggers=loggers,- resources={- **resources,- "docker_pipes_client": PipesDockerClient(),- },-)diff --git a/posthog/dags/tests/max_ai/__init__.py b/posthog/dags/tests/max_ai/__init__.pydeleted file mode 100644index e69de29bb2d1..000000000000diff --git a/posthog/dags/tests/max_ai/test_run_evaluation.py b/posthog/dags/tests/max_ai/test_run_evaluation.pydeleted file mode 100644index e4302da4c936..000000000000--- a/posthog/dags/tests/max_ai/test_run_evaluation.py+++ /dev/null@@ -1,148 +0,0 @@-from uuid import uuid4--import pytest-from posthog.test.base import setup_test_organization_team_and_user-from unittest.mock import patch--import dagster-from pydantic import ValidationError--from products.ai_observability.backend.dataset_service import (- archive_dataset,- archive_dataset_item,- create_dataset,- create_dataset_item,- update_dataset_item,-)-from products.ai_observability.backend.models import Dataset-from products.posthog_ai.dags.run_evaluation import _evaluation_asset_key, prepare_dataset---@patch("products.posthog_ai.dags.run_evaluation._get_team_id")-def test_prepare_dataset_uses_the_current_active_snapshot(mock_get_team_id) -> None:- _, _, team, user, _ = setup_test_organization_team_and_user(- "test",- str(uuid4()),- "[email protected]",- "testpassword12345",- )- mock_get_team_id.return_value = team.id- dataset = create_dataset(team=team, created_by=user, name="Evaluation cases")- active_item = create_dataset_item(- team_id=team.id,- dataset_id=dataset.id,- created_by=user,- input={"question": "active input"},- expected_output={"answer": "active expected"},- metadata={"team_id": team.id},- )- archived_item = create_dataset_item(- team_id=team.id,- dataset_id=dataset.id,- created_by=user,- input={"archived": True},- expected_output={"ignored": True},- metadata={"team_id": team.id},- )- archive_dataset_item(- team_id=team.id,- dataset_id=dataset.id,- item_id=archived_item.item.id,- created_by=user,- base_version=1,- )- Dataset.objects.for_team(team.id).filter(id=dataset.id).update(current_revision=None)-- context = dagster.build_op_context(op_config={"dataset_id": str(dataset.id)})- result = prepare_dataset(context)-- assert result.dataset_id == dataset.id- assert result.dataset_name == "Evaluation cases"- assert result.dataset_revision == 3- assert len(result.dataset_inputs) == 1- assert result.dataset_inputs[0].input == {"question": "active input"}- assert result.dataset_inputs[0].expected == {"answer": "active expected"}- assert active_item.item.id != archived_item.item.id- assert _evaluation_asset_key(result).path == [- "evaluation_dataset",- str(dataset.id),- "revision-3",- ]-- archive_dataset(team_id=team.id, dataset_id=dataset.id)- with pytest.raises(Dataset.DoesNotExist):- prepare_dataset(context)---@patch("products.posthog_ai.dags.run_evaluation._get_team_id")-def test_prepare_dataset_resolves_an_exact_revision(mock_get_team_id) -> None:- _, _, team, user, _ = setup_test_organization_team_and_user(- "test",- str(uuid4()),- "[email protected]",- "testpassword12345",- )- mock_get_team_id.return_value = team.id- dataset = create_dataset(team=team, created_by=user, name="Versioned evaluation cases")- item = create_dataset_item(- team_id=team.id,- dataset_id=dataset.id,- created_by=user,- input={"question": "revision one"},- expected_output={"answer": "revision one"},- metadata={"team_id": team.id},- )- update_dataset_item(- team_id=team.id,- dataset_id=dataset.id,- item_id=item.item.id,- created_by=user,- base_version=1,- input={"question": "revision two"},- expected_output={"answer": "revision two"},- )-- context = dagster.build_op_context(op_config={"dataset_id": str(dataset.id), "revision": 1})- result = prepare_dataset(context)-- assert result.dataset_revision == 1- assert len(result.dataset_inputs) == 1- assert result.dataset_inputs[0].input == {"question": "revision one"}- assert result.dataset_inputs[0].expected == {"answer": "revision one"}- assert _evaluation_asset_key(result).path == [- "evaluation_dataset",- str(dataset.id),- "revision-1",- ]-- unavailable_revision_context = dagster.build_op_context(op_config={"dataset_id": str(dataset.id), "revision": 3})- with pytest.raises(ValueError):- prepare_dataset(unavailable_revision_context)---@patch("products.posthog_ai.dags.run_evaluation._get_team_id")-def test_prepare_dataset_rejects_item_shapes_unsupported_by_the_evaluator(mock_get_team_id) -> None:- _, _, team, user, _ = setup_test_organization_team_and_user(- "test",- str(uuid4()),- "[email protected]",- "testpassword12345",- )- mock_get_team_id.return_value = team.id- dataset = create_dataset(team=team, created_by=user, name="Unsupported evaluation cases")- create_dataset_item(- team_id=team.id,- dataset_id=dataset.id,- created_by=user,- input=["unsupported by this evaluator"],- expected_output="unsupported by this evaluator",- metadata={"team_id": team.id},- )-- context = dagster.build_op_context(op_config={"dataset_id": str(dataset.id)})-- with pytest.raises(ValidationError):- prepare_dataset(context)diff --git a/posthog/dags/tests/max_ai/test_snapshot_team_data.py b/posthog/dags/tests/max_ai/test_snapshot_team_data.pydeleted file mode 100644index 5c3512374cf8..000000000000--- a/posthog/dags/tests/max_ai/test_snapshot_team_data.py+++ /dev/null@@ -1,360 +0,0 @@-import pytest-from unittest.mock import MagicMock, patch--import dagster-from dagster import OpExecutionContext-from dagster_aws.s3.resources import S3Resource--from posthog.schema import (- ActorsPropertyTaxonomyResponse,- CachedEventTaxonomyQueryResponse,- CachedTeamTaxonomyQueryResponse,- EventTaxonomyItem,- TeamTaxonomyItem,-)--from posthog.models import Organization, Project, Team-from posthog.test.persons import create_group_type_mapping--from products.event_definitions.backend.models.property_definition import PropertyDefinition-from products.posthog_ai.dags.snapshot_team_data import (- SnapshotUnrecoverableError,- snapshot_actors_property_taxonomy,- snapshot_clickhouse_team_data,- snapshot_events_taxonomy,- snapshot_postgres_model,- snapshot_postgres_team_data,- snapshot_properties_taxonomy,-)--from ee.hogai.eval.schema import PostgresTeamDataSnapshot, TeamSnapshot---def mock_context():- context = MagicMock(spec=OpExecutionContext)- context.log = MagicMock()- return context---def mock_s3():- mock = MagicMock(spec=S3Resource)- mock.get_resource_definition = S3Resource().get_resource_definition- return mock---def team():- organization = Organization.objects.create(name="Test")- project = Project.objects.create(id=Team.objects.increment_id_sequence(), organization=organization)- team = Team.objects.create(- id=project.id,- project=project,- organization=organization,- api_token="token123",- test_account_filters=[- {- "key": "email",- "value": "@posthog.com",- "operator": "not_icontains",- "type": "person",- }- ],- has_completed_onboarding_for={"product_analytics": True},- )- yield team---def mock_dump():- with patch("products.posthog_ai.dags.snapshot_team_data.dump_model") as mock_dump_model:- mock_dump_context = MagicMock()- mock_dump_function = MagicMock()- mock_dump_context.__enter__ = MagicMock(return_value=mock_dump_function)- mock_dump_context.__exit__ = MagicMock(return_value=None)- mock_dump_model.return_value = mock_dump_context- yield mock_dump_function---@patch("products.posthog_ai.dags.snapshot_team_data.compose_postgres_dump_path")-@patch("products.posthog_ai.dags.snapshot_team_data.check_dump_exists")-def test_snapshot_postgres_model_skips_when_file_exists(- mock_check_dump_exists, mock_compose_path, mock_context, mock_s3-):- """Test that snapshot_postgres_model skips dumping when file already exists."""- # Setup- file_key = "test/path/teams_abc123.avro"- mock_compose_path.return_value = file_key- mock_check_dump_exists.return_value = True-- team_id = 123- file_name = "teams"- code_version = "v1"-- # Execute- result = snapshot_postgres_model(- context=mock_context,- model_type=TeamSnapshot,- file_name=file_name,- s3=mock_s3,- team_id=team_id,- code_version=code_version,- )-- # Verify- assert result == file_key- mock_compose_path.assert_called_once_with(team_id, file_name, code_version)- mock_check_dump_exists.assert_called_once_with(mock_s3, file_key)- mock_context.log.info.assert_called_once_with(f"Skipping {file_key} because it already exists")---@patch("products.posthog_ai.dags.snapshot_team_data.compose_postgres_dump_path")-@patch("products.posthog_ai.dags.snapshot_team_data.check_dump_exists")-def test_snapshot_postgres_model_dumps_when_file_not_exists(- mock_check_dump_exists, mock_compose_path, mock_context, mock_s3, mock_dump-):- """Test that snapshot_postgres_model dumps data when file doesn't exist."""- # Setup- file_key = "test/path/teams_abc123.avro"- mock_compose_path.return_value = file_key- mock_check_dump_exists.return_value = False-- # Mock the serialize_for_team method- mock_serialized_data = [{"id": 1, "name": "test"}]- with patch.object(TeamSnapshot, "serialize_for_team", return_value=mock_serialized_data):- team_id = 123- file_name = "teams"- code_version = "v1"-- # Execute- result = snapshot_postgres_model(- context=mock_context,- model_type=TeamSnapshot,- file_name=file_name,- s3=mock_s3,- team_id=team_id,- code_version=code_version,- )-- # Verify- assert result == file_key- mock_compose_path.assert_called_once_with(team_id, file_name, code_version)- mock_check_dump_exists.assert_called_once_with(mock_s3, file_key)- mock_context.log.info.assert_called_with(f"Dumping {file_key}")- mock_dump.assert_called_once_with(mock_serialized_data)---@patch("products.posthog_ai.dags.snapshot_team_data.snapshot_postgres_model")-def test_snapshot_postgres_team_data_exports_all_models(mock_snapshot_postgres_model, mock_s3):- """Test that snapshot_postgres_team_data exports all expected models."""- # Setup- team_id = 456- mock_snapshot_postgres_model.side_effect = [- "path/to/team.avro",- "path/to/property_definitions.avro",- "path/to/group_type_mappings.avro",- "path/to/data_warehouse_tables.avro",- ]-- # Create context using Dagster's build_op_context- context = dagster.build_op_context()-- # Execute- result = snapshot_postgres_team_data(context, team_id, mock_s3)-- # Verify all expected models are in the result- assert isinstance(result, PostgresTeamDataSnapshot)- assert result.team == "path/to/team.avro"- assert result.property_definitions == "path/to/property_definitions.avro"- assert result.group_type_mappings == "path/to/group_type_mappings.avro"- assert result.data_warehouse_tables == "path/to/data_warehouse_tables.avro"-- # Verify snapshot_postgres_model was called for each model type- assert mock_snapshot_postgres_model.call_count == 4---@patch("products.posthog_ai.dags.snapshot_team_data.call_query_runner")-def test_snapshot_properties_taxonomy(mock_call_query_runner, mock_context, mock_s3, team, mock_dump):- """Test that snapshot_properties_taxonomy correctly processes events and dumps results."""- # Setup- file_key = "test/path/properties_taxonomy.avro"- events = [- TeamTaxonomyItem(event="pageview", count=2),- TeamTaxonomyItem(event="click", count=1),- ]-- # Mock the query runner response- mock_query_result = MagicMock()- mock_query_result.results = [- EventTaxonomyItem(property="$current_url", sample_values=["https://posthog.com"], sample_count=1),- ]- mock_call_query_runner.return_value = mock_query_result-- mock_s3_client = MagicMock()- mock_s3.get_client.return_value = mock_s3_client-- snapshot_properties_taxonomy(mock_context, mock_s3, file_key, team, events)- assert mock_call_query_runner.call_count == 2- mock_dump.assert_called_once()---@patch("products.posthog_ai.dags.snapshot_team_data.snapshot_postgres_model")-def test_snapshot_postgres_team_data_raises_failure_on_missing_team(mock_snapshot_postgres_model, mock_s3):- mock_snapshot_postgres_model.side_effect = Team.DoesNotExist()-- context = dagster.build_op_context()-- with pytest.raises(dagster.Failure) as exc:- snapshot_postgres_team_data(context=context, team_id=999999, s3=mock_s3)-- assert getattr(exc.value, "allow_retries", None) is False- assert "Team 999999 does not exist" in str(exc.value)---def test_snapshot_clickhouse_team_data_raises_failure_on_missing_team(mock_s3):- context = dagster.build_op_context()-- with pytest.raises(dagster.Failure) as exc:- snapshot_clickhouse_team_data(context=context, team_id=424242, s3=mock_s3)-- assert getattr(exc.value, "allow_retries", None) is False- assert "Team 424242 does not exist" in str(exc.value)---@patch("products.posthog_ai.dags.snapshot_team_data.snapshot_events_taxonomy")-def test_snapshot_clickhouse_team_data_raises_failure_on_unrecoverable_error(- mock_snapshot_events_taxonomy, mock_s3, team-):- context = dagster.build_op_context()- mock_snapshot_events_taxonomy.side_effect = SnapshotUnrecoverableError("boom")-- with pytest.raises(dagster.Failure) as exc:- snapshot_clickhouse_team_data(context=context, team_id=team.id, s3=mock_s3)-- assert getattr(exc.value, "allow_retries", None) is False---@patch("products.posthog_ai.dags.snapshot_team_data.check_dump_exists")-@patch("products.posthog_ai.dags.snapshot_team_data.EventTaxonomyQueryRunner.run")-@patch("products.posthog_ai.dags.snapshot_team_data.TeamTaxonomyQueryRunner.run")-def test_snapshot_events_taxonomy(- mock_team_taxonomy_query_runner,- mock_event_taxonomy_query_runner,- mock_check_dump_exists,- mock_context,- mock_s3,- team,- mock_dump,-):- """Test that snapshot_events_taxonomy correctly processes events and dumps results."""- mock_check_dump_exists.return_value = False-- mock_team_taxonomy_query_runner.return_value = MagicMock(- spec=CachedTeamTaxonomyQueryResponse,- results=[- TeamTaxonomyItem(event="pageview", count=2),- TeamTaxonomyItem(event="click", count=1),- ],- )-- mock_event_taxonomy_query_runner.return_value = MagicMock(- spec=CachedEventTaxonomyQueryResponse,- results=[- EventTaxonomyItem(property="$current_url", sample_values=["https://posthog.com"], sample_count=1),- ],- )-- mock_s3_client = MagicMock()- mock_s3.get_client.return_value = mock_s3_client-- snapshot_events_taxonomy(mock_context, mock_s3, team)- mock_team_taxonomy_query_runner.assert_called_once()- assert mock_event_taxonomy_query_runner.call_count == 2- assert mock_dump.call_count == 2---@patch("products.posthog_ai.dags.snapshot_team_data.check_dump_exists")-def test_snapshot_events_taxonomy_can_be_skipped(mock_check_dump_exists, mock_context, mock_s3, team, mock_dump):- """est that snapshot_events_taxonomy can be skipped when file already exists."""- mock_check_dump_exists.return_value = True-- mock_s3_client = MagicMock()- mock_s3.get_client.return_value = mock_s3_client-- snapshot_events_taxonomy(mock_context, mock_s3, team)- assert mock_dump.call_count == 0---@patch("products.posthog_ai.dags.snapshot_team_data.check_dump_exists")-def test_snapshot_actors_property_taxonomy_can_be_skipped(- mock_check_dump_exists, mock_context, mock_s3, team, mock_dump-):- """Test that snapshot_actors_property_taxonomy can be skipped when file already exists."""- mock_check_dump_exists.return_value = True-- mock_s3_client = MagicMock()- mock_s3.get_client.return_value = mock_s3_client-- result = snapshot_actors_property_taxonomy(mock_context, mock_s3, team)-- # Should return file key even when skipped- assert result is not None- assert "actors_property_taxonomy" in result- assert mock_dump.call_count == 0- mock_context.log.info.assert_called_with(- f"Skipping actors property taxonomy snapshot for {team.id} because it already exists"- )---@patch("products.posthog_ai.dags.snapshot_team_data.check_dump_exists")-@patch("products.posthog_ai.dags.snapshot_team_data.call_query_runner")[email protected]_db(databases=["default"])-def test_snapshot_actors_property_taxonomy_dumps_with_group_type_mapping(- mock_call_query_runner, mock_check_dump_exists, mock_context, mock_s3, team, mock_dump-):- """Test that snapshot_actors_property_taxonomy dumps data when GroupTypeMapping exists."""- mock_check_dump_exists.return_value = False-- # Create a GroupTypeMapping for the team- create_group_type_mapping(- team=team,- project=team.project,- group_type="organization",- group_type_index=0,- name_singular="Organization",- name_plural="Organizations",- )-- # Create PropertyDefinition objects for the group type- PropertyDefinition.objects.create(- team=team, name="org_name", type=PropertyDefinition.Type.GROUP, group_type_index=0- )-- # Mock the query runner response- mock_query_result = MagicMock()- mock_query_result.results = [- ActorsPropertyTaxonomyResponse(sample_values=["test_value_1", "test_value_2"], sample_count=2)- ]- mock_call_query_runner.return_value = mock_query_result-- mock_s3_client = MagicMock()- mock_s3.get_client.return_value = mock_s3_client-- result = snapshot_actors_property_taxonomy(mock_context, mock_s3, team)-- # Should return file key- assert result is not None- assert "actors_property_taxonomy" in result-- # Should have called the query runner- assert mock_call_query_runner.call_count > 0-- # Should have dumped data- mock_dump.assert_called_once()diff --git a/posthog/dags/tests/max_ai/test_utils.py b/posthog/dags/tests/max_ai/test_utils.pydeleted file mode 100644index c93e71b3ad75..000000000000--- a/posthog/dags/tests/max_ai/test_utils.py+++ /dev/null@@ -1,720 +0,0 @@-from datetime import datetime-from typing import Any, cast-from uuid import UUID--import pytest--from django.conf import settings--from dagster_aws.s3 import S3Resource-from fastavro import reader-from pydantic_avro import AvroBase--from products.posthog_ai.dags.utils import (- EVALS_S3_BUCKET,- EVALS_S3_PREFIX,- EvaluationResults,- ResultsFormatter,- check_dump_exists,- compose_clickhouse_dump_path,- compose_postgres_dump_path,- dump_model,- format_results,- get_consistent_hash_suffix,-)---def test_consistent_hash_suffix_same_period():- """Test that hash is consistent within the same half-month period."""- file_name = "test_file.txt"-- # Test first half of month (1st-14th)- date_1st = datetime(2024, 1, 1)- date_14th = datetime(2024, 1, 14)-- hash_1st = get_consistent_hash_suffix(file_name, date_1st)- hash_14th = get_consistent_hash_suffix(file_name, date_14th)-- assert hash_1st == hash_14th, "Hash should be consistent within first half of month"-- # Test second half of month (15th-31st)- date_15th = datetime(2024, 1, 15)- date_31st = datetime(2024, 1, 31)-- hash_15th = get_consistent_hash_suffix(file_name, date_15th)- hash_31st = get_consistent_hash_suffix(file_name, date_31st)-- assert hash_15th == hash_31st, "Hash should be consistent within second half of month"---def test_consistent_hash_suffix_different_periods():- """Test that hash changes between different half-month periods."""- file_name = "test_file.txt"-- # Test boundary between first and second half- date_14th = datetime(2024, 1, 14)- date_15th = datetime(2024, 1, 15)-- hash_14th = get_consistent_hash_suffix(file_name, date_14th)- hash_15th = get_consistent_hash_suffix(file_name, date_15th)-- assert hash_14th != hash_15th, "Hash should change between first and second half of month"-- # Test boundary between months- date_jan_31st = datetime(2024, 1, 31)- date_feb_1st = datetime(2024, 2, 1)-- hash_jan_31st = get_consistent_hash_suffix(file_name, date_jan_31st)- hash_feb_1st = get_consistent_hash_suffix(file_name, date_feb_1st)-- assert hash_jan_31st != hash_feb_1st, "Hash should change between different months"---def test_consistent_hash_suffix_with_code_version():- """Test that code version affects the hash."""- file_name = "test_file.txt"- date = datetime(2024, 1, 1)-- hash_no_version = get_consistent_hash_suffix(file_name, date)- hash_with_version = get_consistent_hash_suffix(file_name, date, "v1.0")- hash_different_version = get_consistent_hash_suffix(file_name, date, "v2.0")-- assert hash_no_version != hash_with_version, "Hash should differ when code version is added"- assert hash_with_version != hash_different_version, "Hash should differ for different code versions"---def test_hash_format():- """Test that hash returns expected format (8 characters)."""- file_name = "test_file.txt"- date = datetime(2024, 1, 1)-- hash_result = get_consistent_hash_suffix(file_name, date)-- assert len(hash_result) == 8, "Hash should be 8 characters long"- assert hash_result.isalnum(), "Hash should be alphanumeric"---def test_compose_postgres_dump_path():- """Test that compose_postgres_dump_path generates correct S3 path with hash."""- project_id = 123- dir_name = "test_dump"- code_version = "v1.0"-- result = compose_postgres_dump_path(project_id, dir_name, code_version)-- # Should contain the project ID in path- assert f"/{project_id}/" in result-- # Should start with the mocked folder path- assert result.startswith(f"{EVALS_S3_PREFIX}/postgres_models/")-- # Should end with .avro extension- assert result.endswith(".avro")-- # Should contain the file name and hash suffix- assert dir_name in result-- # Should be deterministic - same inputs produce same output- result2 = compose_postgres_dump_path(project_id, dir_name, code_version)- assert result == result2-- # Different code version should produce different path- result_different_version = compose_postgres_dump_path(project_id, dir_name, "v2.0")- assert result != result_different_version---def test_compose_clickhouse_dump_path():- """Test that compose_clickhouse_dump_path generates correct S3 path with hash."""- project_id = 123- file_name = "test_dump"- code_version = "v1.0"-- result = compose_clickhouse_dump_path(project_id, file_name, code_version)-- # Should contain the project ID in path- assert f"/{project_id}/" in result-- # Should start with the correct folder path- assert result.startswith(f"{EVALS_S3_PREFIX}/clickhouse_queries/")-- # Should end with .avro extension- assert result.endswith(".avro")-- # Should contain the file name and hash suffix- assert file_name in result-- # Should be deterministic - same inputs produce same output- result2 = compose_clickhouse_dump_path(project_id, file_name, code_version)- assert result == result2-- # Different code version should produce different path- result_different_version = compose_clickhouse_dump_path(project_id, file_name, "v2.0")- assert result != result_different_version-- # Test without code version- result_no_version = compose_clickhouse_dump_path(project_id, file_name)- assert result != result_no_version---# Test schema for dump_model tests-class DummySchema(AvroBase):- name: str- value: int---def s3_resource():- return S3Resource(- endpoint_url=settings.OBJECT_STORAGE_ENDPOINT,- aws_access_key_id=settings.OBJECT_STORAGE_ACCESS_KEY_ID,- aws_secret_access_key=settings.OBJECT_STORAGE_SECRET_ACCESS_KEY,- )---def test_dump_model_creates_avro_file(s3_resource):- """Test that dump_model creates an Avro file with correct data in S3."""- file_key = "test/path/data.avro"-- test_models = [- DummySchema(name="test1", value=1),- DummySchema(name="test2", value=2),- ]-- with dump_model(s3=s3_resource, schema=DummySchema, file_key=file_key) as dump:- dump(test_models)-- uploaded_file = s3_resource.get_client().get_object(Bucket=EVALS_S3_BUCKET, Key=file_key)["Body"]-- # Verify the uploaded file contains valid Avro data- records = list(cast(list[dict[str, Any]], reader(uploaded_file)))- assert len(records) == 2- assert records[0]["name"] == "test1"- assert records[0]["value"] == 1- assert records[1]["name"] == "test2"- assert records[1]["value"] == 2---def test_check_dump_exists(s3_resource):- """Test that check_dump_exists correctly identifies existing and non-existing files."""- existing_file_key = "test/path/existing_file.avro"- non_existing_file_key = "test/path/non_existing_file.avro"-- # First create a file- test_models = [DummySchema(name="test", value=42)]- with dump_model(s3=s3_resource, schema=DummySchema, file_key=existing_file_key) as dump:- dump(test_models)-- # Test that existing file is found- assert check_dump_exists(s3_resource, existing_file_key) is True-- # Test that non-existing file returns False- assert check_dump_exists(s3_resource, non_existing_file_key) is False---# Tests for format_results function---def test_format_results_basic():- """Test basic formatting with single result and no previous results."""- dataset_id = UUID("12345678-1234-5678-9012-123456789012")- dataset_name = "Test Dataset"- experiment_id = "exp_123"-- results: EvaluationResults = [- {- "project_name": "test_experiment",- "scores": {"accuracy": {"score": 0.85}, "precision": {"score": 0.92}},- "metrics": {- "duration": {"metric": 12.5},- "total_tokens": {"metric": 1500},- "estimated_cost": {"metric": 0.0125},- },- }- ]-- blocks, markdown = format_results(dataset_id, dataset_name, experiment_id, results)-- # Check structure- assert isinstance(blocks, list)- assert len(blocks) == 1- assert blocks[0]["type"] == "section"- assert blocks[0]["text"]["type"] == "mrkdwn"-- # Check content- assert "Test Dataset" in markdown- assert "test_experiment" in markdown- assert "85.00%" in markdown- assert "92.00%" in markdown- assert "12.50 s" in markdown- assert "1500 tokens" in markdown- assert "$0.0125" in markdown- assert "🆕" in markdown # New experiment emoji---def test_format_results_with_comparison():- """Test formatting with previous results for comparison."""- dataset_id = UUID("12345678-1234-5678-9012-123456789012")- dataset_name = "Test Dataset"- experiment_id = "exp_123"-- results: EvaluationResults = [- {- "project_name": "test_experiment",- "scores": {"accuracy": {"score": 0.88}, "precision": {"score": 0.85}},- "metrics": {"duration": {"metric": 10.0}, "total_tokens": {"metric": 1200}},- }- ]-- prev_results: EvaluationResults = [- {"project_name": "test_experiment", "scores": {"accuracy": {"score": 0.85}, "precision": {"score": 0.90}}}- ]-- blocks, markdown = format_results(dataset_id, dataset_name, experiment_id, results, prev_results)-- # Check improvement indicators- assert "🟢" in markdown # Improvement emoji for accuracy- assert "🔴" in markdown # Regression emoji for precision- assert "+3.00%" in markdown # Accuracy improvement- assert "-5.00%" in markdown # Precision regression- assert "improvements: 1, regressions: 0" in markdown # For accuracy- assert "improvements: 0, regressions: 1" in markdown # For precision---def test_format_results_multiple_experiments():- """Test formatting with multiple experiments."""- dataset_id = UUID("12345678-1234-5678-9012-123456789012")- dataset_name = "Multi Experiment Dataset"- experiment_id = "exp_multi"-- results: EvaluationResults = [- {- "project_name": "experiment_1",- "scores": {"accuracy": {"score": 0.80}},- "metrics": {"duration": {"metric": 5.0}},- },- {- "project_name": "experiment_2",- "scores": {"precision": {"score": 0.75}},- "metrics": {"total_tokens": {"metric": 800}},- },- ]-- blocks, markdown = format_results(dataset_id, dataset_name, experiment_id, results)-- # Should contain both experiments- assert "experiment_1" in markdown- assert "experiment_2" in markdown- assert "80.00%" in markdown- assert "75.00%" in markdown- assert "Evaluated **2** experiments, comprising **2** metrics" in markdown---def test_format_results_exact_zero_change():- """Test formatting when scores are exactly the same."""- dataset_id = UUID("12345678-1234-5678-9012-123456789012")- dataset_name = "Identical Dataset"- experiment_id = "exp_identical"-- results: EvaluationResults = [{"project_name": "identical_experiment", "scores": {"accuracy": {"score": 0.85}}}]-- prev_results: EvaluationResults = [- {"project_name": "identical_experiment", "scores": {"accuracy": {"score": 0.85}}}- ]-- blocks, markdown = format_results(dataset_id, dataset_name, experiment_id, results, prev_results)-- # Should show exact zero change- assert "🔵" in markdown # No change emoji- assert "±0.00%" in markdown # Exact zero change- assert "improvements: 0, regressions: 0" in markdown---def test_format_results_missing_metrics():- """Test formatting when metrics are missing or incomplete."""- dataset_id = UUID("12345678-1234-5678-9012-123456789012")- dataset_name = "Sparse Dataset"- experiment_id = "exp_sparse"-- results: EvaluationResults = [- {- "project_name": "sparse_experiment",- "scores": {"accuracy": {"score": 0.70}},- # No metrics field- },- {- "project_name": "partial_metrics_experiment",- "scores": {"precision": {"score": 0.65}},- "metrics": {- "duration": {"metric": 3.0}- # Missing other metrics- },- },- ]-- blocks, markdown = format_results(dataset_id, dataset_name, experiment_id, results)-- # Should handle missing metrics gracefully- assert "No metrics reported" in markdown- assert "3.00 s" in markdown # Partial metrics should still show---def test_format_results_empty_results():- """Test formatting with empty results list."""- dataset_id = UUID("12345678-1234-5678-9012-123456789012")- dataset_name = "Empty Dataset"- experiment_id = "exp_empty"-- results: EvaluationResults = []-- blocks, markdown = format_results(dataset_id, dataset_name, experiment_id, results)-- # Should handle empty results- assert "Empty Dataset" in markdown- assert "Evaluated **0** experiments, comprising **0** metrics" in markdown---def test_format_results_non_numeric_scores():- """Test formatting with non-numeric score values."""- dataset_id = UUID("12345678-1234-5678-9012-123456789012")- dataset_name = "String Score Dataset"- experiment_id = "exp_string"-- results: EvaluationResults = [- {- "project_name": "string_score_experiment",- "scores": {"quality": {"score": "excellent"}, "status": {"score": "passed"}},- }- ]-- blocks, markdown = format_results(dataset_id, dataset_name, experiment_id, results)-- # Should handle non-numeric scores- assert "excellent" in markdown- assert "passed" in markdown- # Should not try to format as percentage- assert "excellent%" not in markdown---def test_format_results_missing_previous_experiment():- """Test comparison when previous results don't contain matching experiment."""- dataset_id = UUID("12345678-1234-5678-9012-123456789012")- dataset_name = "Mismatch Dataset"- experiment_id = "exp_mismatch"-- results: EvaluationResults = [{"project_name": "new_experiment", "scores": {"accuracy": {"score": 0.88}}}]-- prev_results: EvaluationResults = [- {- "project_name": "old_experiment", # Different name- "scores": {"accuracy": {"score": 0.85}},- }- ]-- blocks, markdown = format_results(dataset_id, dataset_name, experiment_id, results, prev_results)-- # Should treat as new experiment since no matching previous result- assert "🆕" in markdown- assert "new_experiment" in markdown- # Should not show comparison indicators- assert "🟢" not in markdown- assert "🔴" not in markdown---def test_format_results_traces_filter_generation():- """Test that traces filter URLs are properly generated."""- dataset_id = UUID("12345678-1234-5678-9012-123456789012")- dataset_name = "Traces Dataset"- experiment_id = "exp_traces_123"-- results: EvaluationResults = [{"project_name": "traced_experiment", "scores": {"accuracy": {"score": 0.90}}}]-- blocks, markdown = format_results(dataset_id, dataset_name, experiment_id, results)-- # Should contain properly encoded traces URL- assert "https://us.posthog.com/ai-observability/traces?filters=" in markdown- assert "traced_experiment" in markdown- assert "exp_traces_123" in markdown- # URL should be properly encoded- assert "%22" in markdown # URL encoded quotes---def test_format_results_dataset_link():- """Test that dataset link is properly formatted."""- dataset_id = UUID("12345678-1234-5678-9012-123456789012")- dataset_name = "Linked Dataset"- experiment_id = "exp_link"-- results: EvaluationResults = [{"project_name": "linked_experiment", "scores": {"accuracy": {"score": 0.95}}}]-- blocks, markdown = format_results(dataset_id, dataset_name, experiment_id, results)-- # Should contain dataset link with correct UUID- expected_link = f"https://us.posthog.com/ai-evals/datasets/{dataset_id}"- assert expected_link in markdown- assert f"[{dataset_name}]" in markdown---def test_results_formatter_basic():- """Test basic formatting with ResultsFormatter class."""- dataset_id = UUID("12345678-1234-5678-9012-123456789012")- dataset_name = "Test Dataset"- experiment_id = "exp_123"-- results: EvaluationResults = [- {- "project_name": "test_experiment",- "scores": {"accuracy": {"score": 0.85}, "precision": {"score": 0.92}},- "metrics": {- "duration": {"metric": 12.5},- "total_tokens": {"metric": 1500},- "estimated_cost": {"metric": 0.0125},- },- }- ]-- formatter = ResultsFormatter(dataset_id, dataset_name, experiment_id)- blocks, markdown = formatter.format(results)-- # Check structure- assert isinstance(blocks, list)- assert len(blocks) == 1- assert blocks[0]["type"] == "section"- assert blocks[0]["text"]["type"] == "mrkdwn"-- # Check content- assert "Test Dataset" in markdown- assert "test_experiment" in markdown- assert "85.00%" in markdown- assert "92.00%" in markdown- assert "12.50 s" in markdown- assert "1500 tokens" in markdown- assert "$0.0125" in markdown- assert "🆕" in markdown # New experiment emoji---def test_results_formatter_with_comparison():- """Test ResultsFormatter with previous results for comparison."""- dataset_id = UUID("12345678-1234-5678-9012-123456789012")- dataset_name = "Test Dataset"- experiment_id = "exp_123"-- results: EvaluationResults = [- {- "project_name": "test_experiment",- "scores": {"accuracy": {"score": 0.88}, "precision": {"score": 0.85}},- "metrics": {"duration": {"metric": 10.0}, "total_tokens": {"metric": 1200}},- }- ]-- prev_results: EvaluationResults = [- {"project_name": "test_experiment", "scores": {"accuracy": {"score": 0.85}, "precision": {"score": 0.90}}}- ]-- formatter = ResultsFormatter(dataset_id, dataset_name, experiment_id)- blocks, markdown = formatter.format(results, prev_results)-- # Check improvement indicators- assert "🟢" in markdown # Improvement emoji for accuracy- assert "🔴" in markdown # Regression emoji for precision- assert "+3.00%" in markdown # Accuracy improvement- assert "-5.00%" in markdown # Precision regression- assert "improvements: 1, regressions: 0" in markdown # For accuracy- assert "improvements: 0, regressions: 1" in markdown # For precision---def test_results_formatter_find_previous_result():- """Test _find_previous_result method."""- dataset_id = UUID("12345678-1234-5678-9012-123456789012")- dataset_name = "Test Dataset"- experiment_id = "exp_123"-- formatter = ResultsFormatter(dataset_id, dataset_name, experiment_id)-- # Test with None prev_results- result = {"project_name": "test_experiment"}- assert formatter._find_previous_result(result, None) is None-- # Test with empty prev_results- assert formatter._find_previous_result(result, []) is None-- # Test with matching previous result- prev_results = [- {"project_name": "other_experiment", "scores": {"accuracy": {"score": 0.80}}},- {"project_name": "test_experiment", "scores": {"accuracy": {"score": 0.85}}},- ]- found = formatter._find_previous_result(result, prev_results)- assert found is not None- assert found["project_name"] == "test_experiment"- assert found["scores"]["accuracy"]["score"] == 0.85-- # Test with no matching previous result- result_no_match = {"project_name": "nonexistent_experiment"}- assert formatter._find_previous_result(result_no_match, prev_results) is None---def test_results_formatter_format_metrics():- """Test _format_metrics method."""- dataset_id = UUID("12345678-1234-5678-9012-123456789012")- dataset_name = "Test Dataset"- experiment_id = "exp_123"-- formatter = ResultsFormatter(dataset_id, dataset_name, experiment_id)-- # Test with no metrics- result_no_metrics: dict[str, Any] = {}- assert formatter._format_metrics(result_no_metrics) == "No metrics reported"-- # Test with empty metrics- result_empty_metrics: dict[str, Any] = {"metrics": {}}- assert formatter._format_metrics(result_empty_metrics) == "No metrics reported"-- # Test with all metrics- result_all_metrics = {- "metrics": {- "duration": {"metric": 15.5},- "total_tokens": {"metric": 2000},- "estimated_cost": {"metric": 0.025},- }- }- metrics_text = formatter._format_metrics(result_all_metrics)- assert "⏱️ 15.50 s" in metrics_text- assert "🔢 2000 tokens" in metrics_text- assert "💵 $0.0250 in tokens" in metrics_text-- # Test with partial metrics- result_partial_metrics = {"metrics": {"duration": {"metric": 8.0}}}- metrics_text = formatter._format_metrics(result_partial_metrics)- assert "⏱️ 8.00 s" in metrics_text- assert "tokens" not in metrics_text- assert "$" not in metrics_text---def test_results_formatter_build_traces_url():- """Test _build_traces_url method."""- dataset_id = UUID("12345678-1234-5678-9012-123456789012")- dataset_name = "Test Dataset"- experiment_id = "exp_traces_123"-- formatter = ResultsFormatter(dataset_id, dataset_name, experiment_id)-- result = {"project_name": "traced_experiment"}- traces_url = formatter._build_traces_url(result)-- # Should contain properly encoded traces URL- assert "https://us.posthog.com/ai-observability/traces?filters=" in traces_url- assert "traced_experiment" in traces_url- assert "exp_traces_123" in traces_url- # URL should be properly encoded- assert "%22" in traces_url # URL encoded quotes---def test_results_formatter_calculate_score_comparison():- """Test _calculate_score_comparison method."""- dataset_id = UUID("12345678-1234-5678-9012-123456789012")- dataset_name = "Test Dataset"- experiment_id = "exp_123"-- formatter = ResultsFormatter(dataset_id, dataset_name, experiment_id)-- # Test with no previous score data- value: dict[str, Any] = {"score": 0.85}- prev_result: dict[str, Any] = {"scores": {}}- comparison, emoji = formatter._calculate_score_comparison("accuracy", value, prev_result)- assert comparison is None- assert emoji == "🆕"-- # Test with improvement- prev_result = {"scores": {"accuracy": {"score": 0.80}}}- comparison, emoji = formatter._calculate_score_comparison("accuracy", value, prev_result)- assert comparison is not None- assert "+5.00%" in comparison- assert "improvements: 1, regressions: 0" in comparison- assert emoji == "🟢"-- # Test with regression- value = {"score": 0.75}- comparison, emoji = formatter._calculate_score_comparison("accuracy", value, prev_result)- assert comparison is not None- assert "-5.00%" in comparison- assert "improvements: 0, regressions: 1" in comparison- assert emoji == "🔴"-- # Test with no change- value = {"score": 0.80}- comparison, emoji = formatter._calculate_score_comparison("accuracy", value, prev_result)- assert comparison is not None- assert "±0.00%" in comparison- assert "improvements: 0, regressions: 0" in comparison- assert emoji == "🔵"---def test_results_formatter_format_single_score():- """Test _format_single_score method."""- dataset_id = UUID("12345678-1234-5678-9012-123456789012")- dataset_name = "Test Dataset"- experiment_id = "exp_123"-- formatter = ResultsFormatter(dataset_id, dataset_name, experiment_id)-- # Test with numeric score and no previous result- value: dict[str, Any] = {"score": 0.85}- score_line = formatter._format_single_score("accuracy", value, None)- assert "🆕 **accuracy**: **85.00%**" == score_line-- # Test with string score- value = {"score": "excellent"}- score_line = formatter._format_single_score("quality", value, None)- assert "🆕 **quality**: **excellent**" == score_line-- # Test with comparison- prev_result = {"scores": {"accuracy": {"score": 0.80}}}- value = {"score": 0.85}- score_line = formatter._format_single_score("accuracy", value, prev_result)- assert "🟢 **accuracy**: **85.00%**" in score_line- assert "+5.00%" in score_line---def test_results_formatter_empty_results():- """Test ResultsFormatter with empty results list."""- dataset_id = UUID("12345678-1234-5678-9012-123456789012")- dataset_name = "Empty Dataset"- experiment_id = "exp_empty"-- results: EvaluationResults = []-- formatter = ResultsFormatter(dataset_id, dataset_name, experiment_id)- blocks, markdown = formatter.format(results)-- # Should handle empty results- assert "Empty Dataset" in markdown- assert "Evaluated **0** experiments, comprising **0** metrics" in markdown---def test_results_formatter_multiple_experiments():- """Test ResultsFormatter with multiple experiments."""- dataset_id = UUID("12345678-1234-5678-9012-123456789012")- dataset_name = "Multi Experiment Dataset"- experiment_id = "exp_multi"-- results: EvaluationResults = [- {- "project_name": "experiment_1",- "scores": {"accuracy": {"score": 0.80}},- "metrics": {"duration": {"metric": 5.0}},- },- {- "project_name": "experiment_2",- "scores": {"precision": {"score": 0.75}},- "metrics": {"total_tokens": {"metric": 800}},- },- ]-- formatter = ResultsFormatter(dataset_id, dataset_name, experiment_id)- blocks, markdown = formatter.format(results)-- # Should contain both experiments- assert "experiment_1" in markdown- assert "experiment_2" in markdown- assert "80.00%" in markdown- assert "75.00%" in markdown- assert "Evaluated **2** experiments, comprising **2** metrics" in markdowndiff --git a/posthog/dags/tests/test_loggers.py b/posthog/dags/tests/test_loggers.pyindex 291c1465897e..e391e11aaa83 100644--- a/posthog/dags/tests/test_loggers.py+++ b/posthog/dags/tests/test_loggers.py@@ -18,7 +18,6 @@ LOCATION_MODULES = ["growth","ingestion","logs",- "posthog_ai","revenue_analytics","shared","signals",diff --git a/posthog/settings/base_variables.py b/posthog/settings/base_variables.pyindex 99700badcc37..c9c04b508f91 100644--- a/posthog/settings/base_variables.py+++ b/posthog/settings/base_variables.py@@ -11,7 +11,7 @@ logger = structlog.get_logger(__name__)BASE_DIR: str = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))IN_UNIT_TESTING: bool = get_from_env("IN_UNIT_TESTING", False, type_cast=str_to_bool)-IN_EVAL_TESTING: bool = get_from_env("IN_EVAL_TESTING", False, type_cast=str_to_bool) # Set in ee/hogai/eval/pytest.ini+IN_EVAL_TESTING: bool = get_from_env("IN_EVAL_TESTING", False, type_cast=str_to_bool)DEBUG: bool = get_from_env("DEBUG", False, type_cast=str_to_bool)TEST = get_from_env("TEST",diff --git a/posthog/settings/dagster.py b/posthog/settings/dagster.pyindex ca05faa6ddef..36bd72cdafef 100644--- a/posthog/settings/dagster.py+++ b/posthog/settings/dagster.py@@ -28,8 +28,6 @@ DAGSTER_DOMAIN: str | None = os.getenv("DAGSTER_DOMAIN")DAGSTER_UI_HOST: str = os.getenv("DAGSTER_UI_HOST", "localhost")DAGSTER_UI_PORT: int = int(os.getenv("DAGSTER_UI_PORT", 3030))-DAGSTER_AI_EVALS_S3_BUCKET: str = os.getenv("DAGSTER_AI_EVALS_S3_BUCKET", "ai-evals")-DAGSTER_FAVICONS_S3_BUCKET: str = os.getenv("DAGSTER_FAVICONS_S3_BUCKET", "posthog")# Part breaker settingsdiff --git a/products/dashboards/evals/eval_dashboard_contents.py b/products/dashboards/evals/eval_dashboard_contents.pynew file mode 100644index 000000000000..954bd4bd45bb--- /dev/null+++ b/products/dashboards/evals/eval_dashboard_contents.py@@ -0,0 +1,93 @@+from __future__ import annotations++from typing import Any++from posthog.utils import generate_short_id++from products.dashboards.backend.models.dashboard import Dashboard+from products.dashboards.backend.models.dashboard_tile import DashboardTile+from products.dashboards.evals.scorers import SavedDashboardContents+from products.posthog_ai.eval_harness.base import SandboxedPrivateEval+from products.posthog_ai.eval_harness.config import SandboxedEvalCase+from products.posthog_ai.eval_harness.harness.context import EvalContext+from products.product_analytics.backend.facade.api import get_or_create_saved_insight+from products.product_analytics.backend.facade.models import Insight+from products.tasks.backend.facade.agents import CustomPromptSandboxContext++DASHBOARD_NAME = "File activity overview"+SIGNUPS_NAME = "Saved daily signups"+UPLOADS_NAME = "Saved daily file uploads"+++def seed_saved_insights(context: CustomPromptSandboxContext) -> dict[str, Any]:+ if Dashboard.objects.filter(team_id=context.team_id, name=DASHBOARD_NAME, deleted=False).exists():+ raise ValueError("Dashboard eval requires an unused name")+ insights: dict[str, dict[str, object]] = {}+ for name, event in [(SIGNUPS_NAME, "signed_up"), (UPLOADS_NAME, "uploaded_file")]:+ query: dict[str, object] = {+ "kind": "TrendsQuery",+ "series": [{"kind": "EventsNode", "event": event, "math": "total"}],+ "dateRange": {"date_from": "-30d"},+ "interval": "day",+ }+ insight_id, _ = get_or_create_saved_insight(+ team_id=context.team_id,+ user_id=context.user_id,+ short_id=generate_short_id(),+ name=name,+ description=None,+ query=query,+ )+ insights[str(insight_id)] = query+ return {+ "team_id": context.team_id,+ "insights": insights,+ "initial_insight_ids": list(Insight.objects.filter(team_id=context.team_id).values_list("id", flat=True)),+ "initial_dashboard_ids": list(+ Dashboard.objects.filter(team_id=context.team_id, deleted=False).values_list("id", flat=True)+ ),+ }+++def seed_existing_dashboard(context: CustomPromptSandboxContext) -> dict[str, Any]:+ seed = seed_saved_insights(context)+ dashboard = Dashboard.objects.create(team_id=context.team_id, name=DASHBOARD_NAME)+ tile = DashboardTile.objects.create(+ dashboard=dashboard,+ insight_id=int(next(iter(seed["insights"]))),+ layouts={"sm": {"x": 0, "y": 0, "w": 6, "h": 5}},+ )+ return {+ **seed,+ "dashboard_id": dashboard.id,+ "original_tile_id": tile.id,+ "original_tile_insight_id": tile.insight_id,+ }+++async def eval_dashboard_contents(ctx: EvalContext) -> None:+ await SandboxedPrivateEval(+ experiment_name="sandboxed-dashboards-saved-contents-cli",+ cases=[+ SandboxedEvalCase(+ name="create_from_saved_insights",+ prompt=(+ f"Create a dashboard named '{DASHBOARD_NAME}' with exactly these two saved insights: "+ f"'{SIGNUPS_NAME}' and '{UPLOADS_NAME}'. Reuse the saved insights without changing their queries."+ ),+ setup=seed_saved_insights,+ expected={"saved_dashboard_contents": {"name": DASHBOARD_NAME}},+ ),+ SandboxedEvalCase(+ name="add_insight_preserving_existing_chart",+ prompt=(+ f"Add the saved insight '{UPLOADS_NAME}' to the existing '{DASHBOARD_NAME}' dashboard. "+ f"Keep its existing '{SIGNUPS_NAME}' chart. Reuse the saved insights without changing their queries."+ ),+ setup=seed_existing_dashboard,+ expected={"saved_dashboard_contents": {"name": DASHBOARD_NAME}},+ ),+ ],+ scorers=[SavedDashboardContents()],+ ctx=ctx,+ )diff --git a/products/dashboards/evals/scorers.py b/products/dashboards/evals/scorers.pynew file mode 100644index 000000000000..3de4fe2125fd--- /dev/null+++ b/products/dashboards/evals/scorers.py@@ -0,0 +1,64 @@+from __future__ import annotations++import asyncio+from typing import Any++from products.dashboards.backend.models.dashboard import Dashboard+from products.posthog_ai.eval_harness.scorers.contract import AsyncOnlyScorerMixin, Score, Scorer+from products.product_analytics.backend.facade.models import Insight+++class SavedDashboardContents(AsyncOnlyScorerMixin, Scorer):+ def _name(self) -> str:+ return "saved_dashboard_contents"++ @staticmethod+ def _read_state(team_id: int, name: str) -> dict[str, Any]:+ dashboards = Dashboard.objects.filter(team_id=team_id, deleted=False)+ matching = list(dashboards.filter(name=name))+ return {+ "dashboard_ids": list(dashboards.values_list("id", flat=True)),+ "matching": [+ {"id": dashboard.id, "tiles": list(dashboard.tiles.values("id", "insight_id"))}+ for dashboard in matching+ ],+ "insights": {+ str(row["id"]): row["query"] for row in Insight.objects.filter(team_id=team_id).values("id", "query")+ },+ }++ async def _run_eval_async(+ self, output: dict[str, Any] | None, expected: dict[str, Any] | None = None, **kwargs: Any+ ) -> Score:+ seed = (output or {}).get("seed") or {}+ spec = (expected or {}).get(self._name())+ if not seed.get("team_id") or not seed.get("insights") or not spec:+ return Score(name=self._name(), score=0.0, metadata={"reason": "Missing seed or expected dashboard"})++ state = await asyncio.to_thread(self._read_state, seed["team_id"], spec["name"])+ if len(state["matching"]) != 1:+ return Score(+ name=self._name(), score=0.0, metadata={"reason": "Expected one dashboard with the requested name"}+ )++ dashboard = state["matching"][0]+ tiles = dashboard["tiles"]+ wanted_dashboard_id = seed.get("dashboard_id", dashboard["id"])+ checks = {+ "dashboard_identity": dashboard["id"] == wanted_dashboard_id,+ "no_extra_dashboards": set(state["dashboard_ids"])+ == set(seed["initial_dashboard_ids"]) | {wanted_dashboard_id},+ "exact_insights": sorted(str(tile["insight_id"]) for tile in tiles) == sorted(seed["insights"]),+ "no_new_insights": set(state["insights"])+ == {str(insight_id) for insight_id in seed["initial_insight_ids"]},+ "saved_queries_preserved": all(+ state["insights"].get(key) == query for key, query in seed["insights"].items()+ ),+ "original_tile_preserved": "original_tile_id" not in seed+ or any(+ tile["id"] == seed["original_tile_id"] and tile["insight_id"] == seed["original_tile_insight_id"]+ for tile in tiles+ ),+ }+ failed = [name for name, passed in checks.items() if not passed]+ return Score(name=self._name(), score=float(not failed), metadata={"failed_checks": failed})diff --git a/products/data_catalog/scripts/offline_governance_experiment.py b/products/data_catalog/scripts/offline_governance_experiment.pyindex 428d700116b6..d8d647938ccc 100644--- a/products/data_catalog/scripts/offline_governance_experiment.py+++ b/products/data_catalog/scripts/offline_governance_experiment.py@@ -6,7 +6,7 @@ offline scoring can never drift from them), and emits `$ai_evaluation` events ta`$ai_experiment_id` so runs land in the offline experiments view(/ai-evals/evaluations/offline/experiments) and are comparable run over run.-Dataset item shape (same conventions as ee/hogai/eval/offline):+Dataset item shape:input: {"prompt": "<the metric-shaped task>"}expected_output: {"behavior": "<the governed behavior the judges should see>"}diff --git a/products/feature_flags/evals/creation_scorers.py b/products/feature_flags/evals/creation_scorers.pynew file mode 100644index 000000000000..0fd94837f163--- /dev/null+++ b/products/feature_flags/evals/creation_scorers.py@@ -0,0 +1,59 @@+from __future__ import annotations++import asyncio+from typing import Any++from products.feature_flags.backend.facade.config import ConfigV1, decode_config+from products.feature_flags.backend.models.feature_flag import FeatureFlag+from products.posthog_ai.eval_harness.scorers.contract import AsyncOnlyScorerMixin, Score, Scorer+++class CreatedFlagConfiguration(AsyncOnlyScorerMixin, Scorer):+ def _name(self) -> str:+ return "created_flag_configuration"++ @staticmethod+ def _read_flags(team_id: int, key: str) -> list[FeatureFlag]:+ return list(FeatureFlag.objects.filter(team_id=team_id, key=key))++ async def _run_eval_async(+ self, output: dict[str, Any] | None, expected: dict[str, Any] | None = None, **kwargs: Any+ ) -> Score:+ seed = (output or {}).get("seed") or {}+ spec = (expected or {}).get(self._name())+ if not seed.get("team_id") or not spec:+ return Score(name=self._name(), score=0.0, metadata={"reason": "Missing seed or expected configuration"})++ flags = await asyncio.to_thread(self._read_flags, seed["team_id"], spec["key"])+ if len(flags) != 1:+ return Score(name=self._name(), score=0.0, metadata={"reason": "Expected one flag with the requested key"})++ flag = flags[0]+ config = decode_config(flag.get_filters())+ if not isinstance(config, ConfigV1):+ return Score(name=self._name(), score=0.0, metadata={"reason": "Expected a v1 flag configuration"})++ groups = flag.conditions+ checks = {+ "active": flag.active and not flag.archived,+ "boolean": not flag.variants,+ "group_targeting": flag.aggregation_group_type_index == spec["aggregation_group_type_index"],+ "no_extra_audience": len(groups) == 1+ and not any(config.filters.get(key) for key in ("holdout", "holdout_groups", "super_groups")),+ }+ if len(groups) == 1:+ group = groups[0]+ properties = group.get("properties") or []+ checks["rollout"] = group.get("rollout_percentage") == spec["rollout_percentage"]+ checks["audience"] = False+ if len(properties) == 1:+ property_filter = properties[0]+ value = property_filter.get("value")+ values = value if isinstance(value, list) else [value]+ checks["audience"] = values == spec["property"]["value"] and all(+ property_filter.get(key) == spec["property"][key]+ for key in ("key", "type", "operator", "group_type_index")+ )++ failed = [name for name, passed in checks.items() if not passed]+ return Score(name=self._name(), score=float(not failed), metadata={"failed_checks": failed})diff --git a/products/feature_flags/evals/eval_flag_creation.py b/products/feature_flags/evals/eval_flag_creation.pynew file mode 100644index 000000000000..3c00dc70659e--- /dev/null+++ b/products/feature_flags/evals/eval_flag_creation.py@@ -0,0 +1,51 @@+from __future__ import annotations++from typing import Any++from products.feature_flags.backend.models.feature_flag import FeatureFlag+from products.feature_flags.evals.creation_scorers import CreatedFlagConfiguration+from products.posthog_ai.eval_harness.base import SandboxedPrivateEval+from products.posthog_ai.eval_harness.config import SandboxedEvalCase+from products.posthog_ai.eval_harness.harness.context import EvalContext+from products.tasks.backend.facade.agents import CustomPromptSandboxContext++FLAG_KEY = "bulk-file-export-preview"+++def seed_flag_creation(context: CustomPromptSandboxContext) -> dict[str, Any]:+ if FeatureFlag.objects.filter(team_id=context.team_id, key=FLAG_KEY).exists():+ raise ValueError("Flag creation eval requires an unused key")+ return {"team_id": context.team_id}+++async def eval_flag_creation(ctx: EvalContext) -> None:+ await SandboxedPrivateEval(+ experiment_name="sandboxed-feature-flags-creation-cli",+ cases=[+ SandboxedEvalCase(+ name="boolean_flag_with_targeted_rollout",+ prompt=(+ f"Create an active boolean feature flag with the key '{FLAG_KEY}'. "+ "Roll it out to 25% of account groups whose plan is exactly 'business/standard'. "+ "Do not include any other audience or variants."+ ),+ setup=seed_flag_creation,+ expected={+ "created_flag_configuration": {+ "key": FLAG_KEY,+ "rollout_percentage": 25,+ "aggregation_group_type_index": 0,+ "property": {+ "key": "plan",+ "type": "group",+ "group_type_index": 0,+ "operator": "exact",+ "value": ["business/standard"],+ },+ }+ },+ )+ ],+ scorers=[CreatedFlagConfiguration()],+ ctx=ctx,+ )diff --git a/products/model_crossing_uses_baseline.txt b/products/model_crossing_uses_baseline.txtindex 31c6339777d1..34172e098177 100644--- a/products/model_crossing_uses_baseline.txt+++ b/products/model_crossing_uses_baseline.txt@@ -542,7 +542,6 @@ product_analytics.Insight ee.hogai.artifacts.types in-collection 1product_analytics.Insight ee.hogai.chat_agent.insights.nodes instance-many(order_by) 1product_analytics.Insight ee.hogai.context.entity_search.context in-collection 1product_analytics.Insight ee.hogai.context.entity_search.context instance-many(order_by) 1-product_analytics.Insight ee.hogai.eval.ci.max_tools.eval_upsert_dashboard write(acreate) 1product_analytics.Insight ee.hogai.tools.upsert_dashboard.tool construct 1product_analytics.Insight exports.ExportedAsset.insight reverse-accessor(exportedasset_set) 1product_analytics.Insight exports.Subscription.dashboard_export_insights reverse-accessor(subscriptions_dashboard_export) 1@@ -766,10 +765,6 @@ warehouse_sources.DataWarehouseCredential posthog.hogql.database.database instanwarehouse_sources.DataWarehouseCredential products.data_warehouse.backend.presentation.views.table drf-model-serializer 1warehouse_sources.DataWarehouseCredential products.data_warehouse.backend.presentation.views.table write(create) 1warehouse_sources.DataWarehouseCredential products.posthog_ai.evals.data_warehouse.seeder write(create) 1-warehouse_sources.DataWarehouseTable ee.hogai.eval.offline.snapshot_loader write(abulk_create) 1-warehouse_sources.DataWarehouseTable ee.hogai.eval.schema construct 1-warehouse_sources.DataWarehouseTable ee.hogai.eval.schema in-collection 1-warehouse_sources.DataWarehouseTable ee.hogai.eval.schema instance-many(iterator) 1warehouse_sources.DataWarehouseTable ee.hogai.tools.execute_sql.direct_connection_suggestions instance-many(filter) 1warehouse_sources.DataWarehouseTable ee.hogai.tools.read_data.tool instance-many(filter) 1warehouse_sources.DataWarehouseTable posthog.hogql.database.database instance-many(order_by) 2diff --git a/products/posthog_ai/README.md b/products/posthog_ai/README.mdindex 12234a76e740..4602c1c0e5f3 100644--- a/products/posthog_ai/README.md+++ b/products/posthog_ai/README.md@@ -18,6 +18,12 @@ Your integration can show up in any of these:There are two runtimes, picked per conversation by `conversation.agent_runtime`. **`sandbox` is where all new work goes.** `langgraph` is the legacy runtime and is frozen — do not extend it.+## Testing PostHog AI++Use the [eval harness](eval_harness/README.md) to test PostHog AI 2.0 with the real sandbox agent.+Run `hogli evals --list` to find suites and `hogli evals <selector>` to run them.+Add suites under `products/posthog_ai/evals/` or `products/<product>/evals/` and follow [`/writing-evals`](../../.agents/skills/writing-evals/SKILL.md).+## There is no backend integration APINothing you build here talks to a PostHog AI backend. An integration has two halves:@@ -204,7 +210,6 @@ mcp/ # this product's own MCP toolsskills/ # agent skills owned by PostHog AI, plus the repo-wide skills build (see skills/README.md)evals/ # eval suites (see evals/AGENTS.md)eval_harness/ # the harness those suites run on-dags/ # Dagster assets```## Where to read nextdiff --git a/products/posthog_ai/dags/__init__.py b/products/posthog_ai/dags/__init__.pydeleted file mode 100644index e69de29bb2d1..000000000000diff --git a/products/posthog_ai/dags/run_evaluation.py b/products/posthog_ai/dags/run_evaluation.pydeleted file mode 100644index 302cb8017cac..000000000000--- a/products/posthog_ai/dags/run_evaluation.py+++ /dev/null@@ -1,306 +0,0 @@-import base64-from typing import Any, cast-from uuid import UUID--from django.conf import settings--import boto3-import dagster-from dagster._core.definitions.metadata import RawMetadataMapping-from dagster_docker import PipesDockerClient-from dagster_slack import SlackResource-from pydantic import BaseModel, Field, ValidationError-from tenacity import retry, stop_after_attempt, wait_exponential--from posthog.dags.common import JobOwners--from products.ai_observability.backend.dataset_queries import dataset_item_versions_at_revision, latest_dataset_revision-from products.ai_observability.backend.models import Dataset-from products.posthog_ai.dags.snapshot_team_data import (- ClickhouseTeamDataSnapshot,- PostgresTeamDataSnapshot,- snapshot_clickhouse_team_data,- snapshot_postgres_team_data,-)-from products.posthog_ai.dags.utils import EvaluationResults, format_results--from ee.hogai.eval.schema import DatasetInput, EvalsDockerImageConfig, TeamEvaluationSnapshot---def get_object_storage_endpoint() -> str:- """- Get the object storage endpoint.- Debug mode uses the local object storage, so we need to set a DNS endpoint (like orb.dev).- Production mode uses the AWS S3.- """- if settings.DEBUG:- val = dagster.EnvVar("EVALS_DIND_OBJECT_STORAGE_ENDPOINT").get_value("http://objectstorage.posthog.orb.local")- if not val:- raise ValueError("EVALS_DIND_OBJECT_STORAGE_ENDPOINT is not set")- return val- return settings.OBJECT_STORAGE_ENDPOINT---class PrepareDatasetConfig(dagster.Config):- dataset_id: str- """Dataset ID to run the evaluation for."""- revision: int | None = Field(default=None, ge=1)---class PreparedDataset(BaseModel):- dataset_id: UUID- dataset_name: str- dataset_revision: int | None- dataset_inputs: list[DatasetInput]---def _get_team_id() -> int:- return 2 if not settings.DEBUG else 1---def _evaluation_asset_key(prepared_dataset: PreparedDataset) -> dagster.AssetKey:- revision_key = (- f"revision-{prepared_dataset.dataset_revision}"- if prepared_dataset.dataset_revision is not None- else "revision-empty"- )- return dagster.AssetKey(["evaluation_dataset", str(prepared_dataset.dataset_id), revision_key])--- description="Pulls the dataset and dataset items and validates inputs, outputs, metadata, and team_id presence in metadata."-)-def prepare_dataset(context: dagster.OpExecutionContext, config: PrepareDatasetConfig) -> PreparedDataset:- team_id = _get_team_id()- dataset = (- Dataset.objects.for_team(team_id, canonical=True)- .select_related("current_revision")- .get(id=config.dataset_id, archived=False)- )- current_revision = dataset.current_revision or latest_dataset_revision(team_id=team_id, dataset_id=dataset.id)- current_revision_number = current_revision.revision if current_revision is not None else None- if config.revision is not None:- if current_revision_number is None:- raise ValueError("This dataset has no revisions. Add an item before running the evaluation.")- if config.revision > current_revision_number:- raise ValueError(- f"Dataset revision {config.revision} does not exist. Choose a revision from 1 to {current_revision_number}."- )- selected_revision_number = config.revision if config.revision is not None else current_revision_number- dataset_items = (- []- if selected_revision_number is None- else dataset_item_versions_at_revision(- team_id=dataset.team_id,- dataset_id=dataset.id,- revision=selected_revision_number,- archived=False,- ).iterator(500)- )-- dataset_inputs: list[DatasetInput] = []- for dataset_item in dataset_items:- try:- metadata = dataset_item.metadata or {}- dataset_inputs.append(- DatasetInput(- input=dataset_item.input,- expected=dataset_item.expected_output,- metadata=metadata,- team_id=metadata.get("team_id"),- trace_id=dataset_item.source_trace_id,- )- )- except ValidationError:- context.log.exception(f"Validation error for dataset item {dataset_item.id}")- raise-- return PreparedDataset(- dataset_id=dataset.id,- dataset_name=dataset.name,- dataset_revision=selected_revision_number,- dataset_inputs=dataset_inputs,- )--[email protected](out=dagster.DynamicOut(int))-def prepare_evaluation(prepared_dataset: PreparedDataset):- seen_teams = set()- for dataset_input in prepared_dataset.dataset_inputs:- if dataset_input.team_id in seen_teams:- continue- seen_teams.add(dataset_input.team_id)- yield dagster.DynamicOutput(dataset_input.team_id, mapping_key=str(dataset_input.team_id))---class EvaluationConfig(dagster.Config):- image_name: str = Field(description="Name of the Docker image to run.")- image_tag: str = Field(description="Tag of the Docker image to run.")- evaluation_module: str = Field(description="Python module containing the evaluation runner.")-- @property- def image(self) -> str:- # We use the local Docker image in debug mode- if settings.DEBUG:- return f"{self.image_name}:{self.image_tag}"- return f"{dagster.EnvVar('AWS_EKS_REGISTRY_URL').get_value()}/{self.image_name}:{self.image_tag}"---@retry(stop=stop_after_attempt(3), wait=wait_exponential(min=2))-def get_registry_credentials():- # We use the local Docker image in debug mode- if settings.DEBUG:- return None-- client = boto3.client("ecr")- # https://boto3.amazonaws.com/v1/documentation/api/1.29.2/reference/services/ecr/client/get_authorization_token.html- token = client.get_authorization_token()["authorizationData"][0]["authorizationToken"]- username, password = base64.b64decode(token).decode("utf-8").split(":")-- return {- "url": dagster.EnvVar("AWS_EKS_REGISTRY_URL").get_value(),- "username": username,- "password": password,- }---def unpack_evaluation_results(metadata: RawMetadataMapping | None) -> EvaluationResults | None:- if not metadata:- return None- try:- meta = metadata["evaluation_results"]- if isinstance(meta, dagster.JsonMetadataValue):- return cast(list[dict[Any, Any]], meta.value)- return None- except KeyError:- return None---def get_last_dataset_materialization_metadata(- context: dagster.OpExecutionContext, asset_key: dagster.AssetKey-) -> EvaluationResults | None:- last_materialization_event = context.instance.get_latest_materialization_event(asset_key)- if not last_materialization_event or not last_materialization_event.asset_materialization:- return None- return unpack_evaluation_results(last_materialization_event.asset_materialization.metadata)---def spawn_evaluation_container(- context: dagster.OpExecutionContext,- config: EvaluationConfig,- docker_pipes_client: PipesDockerClient,- slack: SlackResource,- prepared_dataset: PreparedDataset,- team_ids: list[int],- postgres_snapshots: list[PostgresTeamDataSnapshot],- clickhouse_snapshots: list[ClickhouseTeamDataSnapshot],-):- # Validate the evaluation module- if not config.evaluation_module.endswith(".py"):- raise ValueError("Evaluation module must be a Python file")- if not config.evaluation_module.startswith("ee/hogai/eval/"):- raise ValueError(f"Evaluation module {config.evaluation_module} must start with 'ee/hogai/eval/'")-- asset_key = _evaluation_asset_key(prepared_dataset)- revision_label = prepared_dataset.dataset_revision if prepared_dataset.dataset_revision is not None else "empty"- evaluation_config = EvalsDockerImageConfig(- aws_endpoint_url=get_object_storage_endpoint(),- aws_bucket_name=settings.OBJECT_STORAGE_BUCKET,- team_snapshots=[- TeamEvaluationSnapshot(team_id=team_id, postgres=postgres, clickhouse=clickhouse).model_dump()- for team_id, postgres, clickhouse in zip(team_ids, postgres_snapshots, clickhouse_snapshots)- ],- experiment_id=context.run_id,- experiment_name=f"dataset-{prepared_dataset.dataset_id}-revision-{revision_label}",- dataset_id=str(prepared_dataset.dataset_id),- dataset_name=prepared_dataset.dataset_name,- dataset_revision=prepared_dataset.dataset_revision,- dataset_inputs=prepared_dataset.dataset_inputs,- )-- context.log.info(f"Running evaluation for the image: {config.image}")-- env: dict[str, str] = {- "EVAL_SCRIPT": f"pytest {config.evaluation_module} -s -vv",- "OBJECT_STORAGE_ACCESS_KEY_ID": settings.OBJECT_STORAGE_ACCESS_KEY_ID, # type: ignore- "OBJECT_STORAGE_SECRET_ACCESS_KEY": settings.OBJECT_STORAGE_SECRET_ACCESS_KEY, # type: ignore- "OPENAI_API_KEY": settings.OPENAI_API_KEY,- "ANTHROPIC_API_KEY": settings.ANTHROPIC_API_KEY,- "INKEEP_API_KEY": settings.INKEEP_API_KEY,- "AZURE_INFERENCE_ENDPOINT": settings.AZURE_INFERENCE_ENDPOINT,- "AZURE_INFERENCE_CREDENTIAL": settings.AZURE_INFERENCE_CREDENTIAL,- }- if settings.OPENAI_BASE_URL:- env["OPENAI_BASE_URL"] = settings.OPENAI_BASE_URL-- asset_result = docker_pipes_client.run(- context=context,- image=config.image,- container_kwargs={- "privileged": True,- "auto_remove": True,- },- env=env,- extras=evaluation_config.model_dump(exclude_unset=True),- registry=get_registry_credentials(),- ).get_materialize_result()-- previous_results = get_last_dataset_materialization_metadata(context, asset_key)- new_results = unpack_evaluation_results(asset_result.metadata)-- if not new_results:- context.log.error("No new evaluation results returned")- raise ValueError("No new evaluation results found")-- blocks, formatted_markdown = format_results(- prepared_dataset.dataset_id, prepared_dataset.dataset_name, context.run_id, new_results, previous_results- )- try:- slack.get_client().chat_postMessage(channel="#evals-max-ai", blocks=blocks)- except Exception as e:- context.log.exception(f"Failed to send Slack notification: {str(e)}")-- context.log_event(- dagster.AssetMaterialization(- asset_key=asset_key,- metadata={- "evaluation_results": dagster.JsonMetadataValue(new_results),- "report": dagster.MarkdownMetadataValue(formatted_markdown),- },- tags={- "owner": JobOwners.TEAM_POSTHOG_AI.value,- },- )- )--- description="Runs an AI evaluation",- tags={- "owner": JobOwners.TEAM_POSTHOG_AI.value,- "dagster/max_runtime": 60 * 60, # 1 hour- },- executor_def=dagster.multiprocess_executor.configured({"max_concurrent": 4}),- config=dagster.RunConfig(- ops={- "prepare_dataset": PrepareDatasetConfig(dataset_id=""),- "spawn_evaluation_container": EvaluationConfig(- evaluation_module="ee/hogai/eval/offline/",- image_name="posthog-ai-evals",- image_tag="master",- ),- }- ),-)-def run_evaluation():- prepared_dataset = prepare_dataset()- team_ids = prepare_evaluation(prepared_dataset)- postgres_snapshots = team_ids.map(snapshot_postgres_team_data)- clickhouse_snapshots = team_ids.map(snapshot_clickhouse_team_data)- spawn_evaluation_container(- prepared_dataset,- team_ids.collect(),- postgres_snapshots.collect(),- clickhouse_snapshots.collect(),- )diff --git a/products/posthog_ai/dags/snapshot_team_data.py b/products/posthog_ai/dags/snapshot_team_data.pydeleted file mode 100644index 146b9bfe6671..000000000000--- a/products/posthog_ai/dags/snapshot_team_data.py+++ /dev/null@@ -1,364 +0,0 @@-from collections.abc import Callable, Iterable, Iterator-from itertools import islice-from typing import TypeVar, cast--import dagster-from dagster_aws.s3.resources import S3Resource-from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential--from posthog.schema import (- ActorsPropertyTaxonomyQuery,- ActorsPropertyTaxonomyResponse,- CachedActorsPropertyTaxonomyQueryResponse,- CachedEventTaxonomyQueryResponse,- CachedTeamTaxonomyQueryResponse,- EventTaxonomyQuery,- TeamTaxonomyItem,- TeamTaxonomyQuery,-)--from posthog.hogql.constants import HogQLGlobalSettings--from posthog.clickhouse.client.connection import Workload-from posthog.dags.common import JobOwners-from posthog.errors import InternalCHQueryError-from posthog.hogql_queries.ai.actors_property_taxonomy_query_runner import ActorsPropertyTaxonomyQueryRunner-from posthog.hogql_queries.ai.event_taxonomy_query_runner import EventTaxonomyQueryRunner-from posthog.hogql_queries.ai.team_taxonomy_query_runner import TeamTaxonomyQueryRunner-from posthog.hogql_queries.query_runner import ExecutionMode-from posthog.models import Team--from products.event_definitions.backend.models.property_definition import PropertyDefinition-from products.posthog_ai.dags.utils import (- check_dump_exists,- compose_clickhouse_dump_path,- compose_postgres_dump_path,- dump_model,-)--from ee.hogai.eval.schema import (- ActorsPropertyTaxonomySnapshot,- BaseSnapshot,- ClickhouseTeamDataSnapshot,- DataWarehouseTableSnapshot,- GroupTypeMappingSnapshot,- PostgresTeamDataSnapshot,- PropertyDefinitionSnapshot,- PropertyTaxonomySnapshot,- TeamSnapshot,- TeamTaxonomyItemSnapshot,-)--DEFAULT_RETRY_POLICY = dagster.RetryPolicy(- max_retries=4,- delay=2, # 2 seconds- backoff=dagster.Backoff.EXPONENTIAL,- jitter=dagster.Jitter.PLUS_MINUS,-)---SchemaBound = TypeVar("SchemaBound", bound=BaseSnapshot)---class SnapshotUnrecoverableError(ValueError):- """- An error that indicates that the snapshot operation cannot be recovered from.- This is used to indicate that the snapshot operation failed and should not be retried.- """-- pass---def snapshot_postgres_model(- context: dagster.OpExecutionContext,- model_type: type[SchemaBound],- file_name: str,- s3: S3Resource,- team_id: int,- code_version: str | None = None,-) -> str:- file_key = compose_postgres_dump_path(team_id, file_name, code_version)- if check_dump_exists(s3, file_key):- context.log.info(f"Skipping {file_key} because it already exists")- return file_key- context.log.info(f"Dumping {file_key}")- with dump_model(s3=s3, schema=model_type, file_key=file_key) as dump:- dump(model_type.serialize_for_team(team_id=team_id))- return file_key--- description="Snapshots Postgres team data (property definitions, DWH schema, etc.)",- retry_policy=DEFAULT_RETRY_POLICY,- code_version="v1",- tags={- "owner": JobOwners.TEAM_POSTHOG_AI.value,- "dagster/max_runtime": 60 * 15, # 15 minutes- },-)-def snapshot_postgres_team_data(- context: dagster.OpExecutionContext, team_id: int, s3: S3Resource-) -> PostgresTeamDataSnapshot:- context.log.info(f"Snapshotting Postgres team data for {team_id}")- snapshot_map: dict[str, type[BaseSnapshot]] = {- "team": TeamSnapshot,- "property_definitions": PropertyDefinitionSnapshot,- "group_type_mappings": GroupTypeMappingSnapshot,- "data_warehouse_tables": DataWarehouseTableSnapshot,- }-- try:- deps = {- file_name: snapshot_postgres_model(context, model_type, file_name, s3, team_id, context.op_def.version)- for file_name, model_type in snapshot_map.items()- }- context.log_event(- dagster.AssetMaterialization(- asset_key="team_postgres_snapshot",- description="Avro snapshots of team Postgres data",- metadata={"team_id": team_id, **deps},- tags={"owner": JobOwners.TEAM_POSTHOG_AI.value},- )- )- except Team.DoesNotExist as e:- raise dagster.Failure(- description=f"Team {team_id} does not exist",- metadata={"team_id": team_id},- allow_retries=False,- ) from e-- return PostgresTeamDataSnapshot(**deps)---C = TypeVar("C")---@retry(- retry=retry_if_exception_type(InternalCHQueryError),- stop=stop_after_attempt(4),- wait=wait_exponential(min=8),-)-def call_query_runner(callable: Callable[[], C]) -> C:- return callable()---def snapshot_properties_taxonomy(- context: dagster.OpExecutionContext,- s3: S3Resource,- file_key: str,- team: Team,- events: list[TeamTaxonomyItem],-):- results: list[PropertyTaxonomySnapshot] = []-- def wrapped_query_runner(item: TeamTaxonomyItem):- response = EventTaxonomyQueryRunner(- query=EventTaxonomyQuery(event=item.event),- team=team,- settings=HogQLGlobalSettings(- max_execution_time=60 * 5 # 5 minutes- ),- workload=Workload.OFFLINE,- ).run(execution_mode=ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE)- if not isinstance(response, CachedEventTaxonomyQueryResponse):- raise SnapshotUnrecoverableError(f"Unexpected response type from event taxonomy query: {type(response)}")- return response-- def call_event_taxonomy_query(item: TeamTaxonomyItem):- return call_query_runner(lambda: wrapped_query_runner(item))-- for item in events:- context.log.info(f"Snapshotting properties taxonomy for event {item.event} of {team.id}")- results.append(PropertyTaxonomySnapshot(event=item.event, results=call_event_taxonomy_query(item).results))-- context.log.info(f"Dumping properties taxonomy to {file_key}")- with dump_model(s3=s3, schema=PropertyTaxonomySnapshot, file_key=file_key) as dump:- dump(results)---def snapshot_events_taxonomy(- context: dagster.OpExecutionContext,- s3: S3Resource,- team: Team,- code_version: str | None = None,-):- # Check if files are cached- events_file_key = compose_clickhouse_dump_path(team.id, "events_taxonomy", code_version=code_version)- properties_file_key = compose_clickhouse_dump_path(team.id, "properties_taxonomy", code_version=code_version)- if check_dump_exists(s3, events_file_key) and check_dump_exists(s3, properties_file_key):- context.log.info(f"Skipping events and properties taxonomy snapshot for {team.id} because it already exists")- return events_file_key, properties_file_key-- context.log.info(f"Snapshotting events taxonomy for {team.id}")-- def snapshot_events_taxonomy():- response = TeamTaxonomyQueryRunner(- query=TeamTaxonomyQuery(),- team=team,- settings=HogQLGlobalSettings(- max_execution_time=60 * 5 # 5 minutes- ),- workload=Workload.OFFLINE,- ).run(execution_mode=ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE)- if not isinstance(response, CachedTeamTaxonomyQueryResponse):- raise SnapshotUnrecoverableError(f"Unexpected response type from events taxonomy query: {type(response)}")- return response-- res = call_query_runner(snapshot_events_taxonomy)-- if not res.results:- raise SnapshotUnrecoverableError("No results from events taxonomy query")-- # Dump properties- snapshot_properties_taxonomy(context, s3, properties_file_key, team, res.results)-- # Dump later to ensure caching- with dump_model(s3=s3, schema=TeamTaxonomyItemSnapshot, file_key=events_file_key) as dump:- dumped_items = TeamTaxonomyItemSnapshot(results=res.results)- dump([dumped_items])-- return events_file_key, properties_file_key---T = TypeVar("T")---def chunked(iterable: Iterable[T], size: int = 200) -> Iterator[list[T]]:- it = iter(iterable)- while True:- batch = list(islice(it, size))- if not batch:- break- yield batch---def snapshot_actors_property_taxonomy(- context: dagster.OpExecutionContext,- s3: S3Resource,- team: Team,- code_version: str | None = None,-):- file_key = compose_clickhouse_dump_path(team.id, "actors_property_taxonomy", code_version=code_version)- if check_dump_exists(s3, file_key):- context.log.info(f"Skipping actors property taxonomy snapshot for {team.id} because it already exists")- return file_key-- # Snapshot all group type mappings and person- results: list[ActorsPropertyTaxonomySnapshot] = []- from posthog.models.group_type_mapping import get_group_types_for_team-- group_type_mappings: list[int | None] = [- None,- *(m["group_type_index"] for m in get_group_types_for_team(team.id)),- ]-- for index in group_type_mappings:- is_group = index is not None- log_entity = f"group type {index}" if is_group else "persons"- context.log.info(f"Snapshotting properties taxonomy for {log_entity}")-- # Retrieve saved property definitions for the group type or person- property_defs: Iterator[str] = (- PropertyDefinition.objects.filter(- team=team,- type=PropertyDefinition.Type.GROUP if is_group else PropertyDefinition.Type.PERSON,- group_type_index=index,- )- .values_list("name", flat=True)- .iterator(chunk_size=200)- )-- # Query ClickHouse in batches of 200 properties- for batch in chunked(property_defs, 200):-- def wrapped_query_runner(index: int | None, batch: list[str]):- response = ActorsPropertyTaxonomyQueryRunner(- query=ActorsPropertyTaxonomyQuery(groupTypeIndex=index, properties=batch, maxPropertyValues=25),- team=team,- settings=HogQLGlobalSettings(- max_execution_time=60 * 5 # 5 minutes- ),- workload=Workload.OFFLINE,- ).run(execution_mode=ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE)- if not isinstance(response, CachedActorsPropertyTaxonomyQueryResponse):- raise SnapshotUnrecoverableError(- f"Unexpected response type from actors property taxonomy query: {type(response)}"- )- return response-- def call_actors_property_taxonomy_query(index: int | None, batch: list[str]):- return call_query_runner(lambda: wrapped_query_runner(index, batch))-- res = call_actors_property_taxonomy_query(index, batch)-- if not res.results:- raise SnapshotUnrecoverableError(- f"No results from actors property taxonomy query for group type {index} and properties {batch}"- )-- # Snapshot queries in the same way as the toolkit expects- for prop, prop_results in zip(batch, cast(list[ActorsPropertyTaxonomyResponse], res.results)):- results.append(- ActorsPropertyTaxonomySnapshot(property=prop, group_type_index=index, results=prop_results)- )-- context.log.info(f"Dumping actors property taxonomy to {file_key}")- with dump_model(s3=s3, schema=ActorsPropertyTaxonomySnapshot, file_key=file_key) as dump:- dump(results)- return file_key--- description="Snapshots ClickHouse team data",- retry_policy=DEFAULT_RETRY_POLICY,- tags={- "owner": JobOwners.TEAM_POSTHOG_AI.value,- "dagster/max_runtime": 60 * 15, # 15 minutes- },- code_version="v1",-)-def snapshot_clickhouse_team_data(- context: dagster.OpExecutionContext, team_id: int, s3: S3Resource-) -> ClickhouseTeamDataSnapshot:- try:- team = Team.objects.get(id=team_id)-- except Team.DoesNotExist as e:- raise dagster.Failure(- description=f"Team {team_id} does not exist",- metadata={"team_id": team_id},- allow_retries=False,- ) from e-- try:- event_taxonomy_file_key, properties_taxonomy_file_key = snapshot_events_taxonomy(- context, s3, team, context.op_def.version- )- actors_property_taxonomy_file_key = snapshot_actors_property_taxonomy(context, s3, team, context.op_def.version)-- except SnapshotUnrecoverableError as e:- raise dagster.Failure(- description=f"Error snapshotting team {team_id}",- metadata={"team_id": team_id},- allow_retries=False,- ) from e-- materialized_result = ClickhouseTeamDataSnapshot(- event_taxonomy=event_taxonomy_file_key,- properties_taxonomy=properties_taxonomy_file_key,- actors_property_taxonomy=actors_property_taxonomy_file_key,- )-- context.log_event(- dagster.AssetMaterialization(- asset_key="team_clickhouse_snapshot",- description="Avro snapshots of team's ClickHouse queries",- metadata={- "team_id": team_id,- **materialized_result.model_dump(),- },- tags={"owner": JobOwners.TEAM_POSTHOG_AI.value},- )- )-- return materialized_resultdiff --git a/products/posthog_ai/dags/utils.py b/products/posthog_ai/dags/utils.pydeleted file mode 100644index 308261ef6a59..000000000000--- a/products/posthog_ai/dags/utils.py+++ /dev/null@@ -1,254 +0,0 @@-import json-import hashlib-import urllib.parse-from collections.abc import Sequence-from contextlib import contextmanager-from datetime import datetime-from tempfile import TemporaryFile-from typing import Any-from uuid import UUID--from django.conf import settings--import botocore-from dagster_aws.s3 import S3Resource-from fastavro import parse_schema, writer-from pydantic_avro import AvroBase-from tenacity import retry, stop_after_attempt, wait_exponential--EVALS_S3_PREFIX = "ai_evals"--# objectstorage has only the default bucket in debug.-if settings.DEBUG:- EVALS_S3_BUCKET = settings.OBJECT_STORAGE_BUCKET-else:- EVALS_S3_BUCKET = settings.DAGSTER_AI_EVALS_S3_BUCKET---def get_consistent_hash_suffix(file_name: str, date: datetime | None = None, code_version: str | None = None) -> str:- """- Generate a consistent hash suffix that updates twice per month based on the filename.-- The hash changes on the 1st and 15th of each month, ensuring links update- twice monthly while remaining consistent within each period.-- Args:- file_name: The base filename to hash- date: Optional date for testing, defaults to current date- code_version: Optional code version for hash consistency-- Returns:- A short hash string (8 characters) that's consistent within each half-month period- """- if date is None:- date = datetime.now()-- # Determine which half of the month we're in- half_month_period = 1 if date.day < 15 else 2-- # Create a seed that changes twice per month- period_seed = f"{date.year}-{date.month:02d}-{half_month_period}"-- # Combine the period seed with the filename for consistent hashing- hash_input = f"{period_seed}:{file_name}"- if code_version:- hash_input += f":{code_version}"-- # Generate a short, URL-safe hash- hash_obj = hashlib.sha256(hash_input.encode("utf-8"))- return hash_obj.hexdigest()[:8]---def compose_postgres_dump_path(project_id: int, dir_name: str, code_version: str | None = None) -> str:- """Compose S3 path for Postgres dumps with consistent hashing"""- hash_suffix = get_consistent_hash_suffix(dir_name, code_version=code_version)- return f"{EVALS_S3_PREFIX}/postgres_models/{project_id}/{dir_name}/{hash_suffix}.avro"---def compose_clickhouse_dump_path(project_id: int, dir_name: str, code_version: str | None = None) -> str:- """Compose S3 path for ClickHouse dumps with consistent hashing"""- hash_suffix = get_consistent_hash_suffix(dir_name, code_version=code_version)- return f"{EVALS_S3_PREFIX}/clickhouse_queries/{project_id}/{dir_name}/{hash_suffix}.avro"---def check_dump_exists(s3: S3Resource, file_key: str) -> bool:- """Check if a file exists in S3"""- try:- s3.get_client().head_object(Bucket=EVALS_S3_BUCKET, Key=file_key)- return True- except botocore.exceptions.ClientError as e:- if e.response["Error"]["Code"] == "404":- return False- raise---@contextmanager-def dump_model(*, s3: S3Resource, schema: type[AvroBase], file_key: str):- with TemporaryFile() as f:- parsed_schema = parse_schema(schema.avro_schema())-- def dump(models: Sequence[AvroBase]):- writer(f, parsed_schema, (model.model_dump() for model in models))-- yield dump-- @retry(stop=stop_after_attempt(3), wait=wait_exponential(min=4))- def upload():- f.seek(0)- s3.get_client().upload_fileobj(f, EVALS_S3_BUCKET, file_key)-- upload()---EvaluationResults = list[dict[Any, Any]]---class ResultsFormatter:- """Formats evaluation results into Slack-compatible markdown blocks."""-- def __init__(self, dataset_id: UUID, dataset_name: str, experiment_id: str):- self.dataset_id = dataset_id- self.dataset_name = dataset_name- self.experiment_id = experiment_id-- def format(- self,- results: EvaluationResults,- prev_results: EvaluationResults | None = None,- ) -> tuple[list[dict[str, Any]], str]:- """Format evaluation results into Slack blocks and markdown."""- experiment_summaries = []- for result in results:- experiment_summary = self._format_experiment_summary(result, prev_results)- experiment_summaries.append(experiment_summary)-- total_experiments = len(results)- total_metrics = sum(len(result.get("scores", {})) for result in results)-- body_parts = [- f"🧠 **AI eval results** for dataset [{self.dataset_name}](https://us.posthog.com/ai-evals/datasets/{self.dataset_id})",- f"Evaluated **{total_experiments}** experiment{'' if total_experiments == 1 else 's'}, comprising **{total_metrics}** metric{'' if total_metrics == 1 else 's'}.",- *experiment_summaries,- ]- formatted_markdown = "\n\n".join(body_parts)- blocks = [{"type": "section", "text": {"type": "mrkdwn", "text": formatted_markdown}}]- return blocks, formatted_markdown-- def _format_experiment_summary(self, result: dict[str, Any], prev_results: EvaluationResults | None) -> str:- """Format a single experiment's results into a summary string."""- prev_result = self._find_previous_result(result, prev_results)- scores_text = self._format_scores(result, prev_result)- metrics_text = self._format_metrics(result)- traces_url = self._build_traces_url(result)-- summary_parts = [- f"**Experiment**: {result.get('project_name', '')}",- scores_text,- f"Baseline: Previous run 🔍 [Traces]({traces_url})",- f"Avg. case performance: {metrics_text}",- ]- return "\n\n".join(summary_parts)-- def _find_previous_result(- self, result: dict[str, Any], prev_results: EvaluationResults | None- ) -> dict[str, Any] | None:- """Find the corresponding previous result by project_name."""- if not prev_results:- return None-- project_name = result.get("project_name")- for prev in prev_results:- if prev.get("project_name") == project_name:- return prev- return None-- def _format_scores(self, result: dict[str, Any], prev_result: dict[str, Any] | None) -> str:- """Format scores with comparison indicators and baseline comparison."""- scores_list = []- for key, value in (result.get("scores") or {}).items():- score_line = self._format_single_score(key, value, prev_result)- scores_list.append(score_line)- return "\n\n".join(scores_list)-- def _format_single_score(self, key: str, value: dict[str, Any], prev_result: dict[str, Any] | None) -> str:- """Format a single score with comparison indicators."""- score = f"{(value['score'] * 100):.2f}%" if isinstance(value.get("score"), int | float) else value.get("score")-- baseline_comparison = None- diff_emoji = "🆕"-- if prev_result:- baseline_comparison, diff_emoji = self._calculate_score_comparison(key, value, prev_result)-- score_line = f"{diff_emoji} **{key}**: **{score}**"- if baseline_comparison:- score_line += f", {baseline_comparison}"- return score_line-- def _calculate_score_comparison(- self, key: str, value: dict[str, Any], prev_result: dict[str, Any]- ) -> tuple[str | None, str]:- """Calculate comparison metrics between current and previous scores."""- prev_scores = prev_result.get("scores", {})- prev_score_data = prev_scores.get(key)-- if not prev_score_data:- return None, "🆕"-- prev_score = prev_score_data.get("score", 0)- current_score = value.get("score", 0)- diff_val = current_score - prev_score-- diff_highlight = "**" if abs(diff_val) > 0.01 else ""- diff_sign = "+" if diff_val > 0 else ("" if diff_val < 0 else "±")-- # Calculate improvements/regressions (simplified logic)- improvements = 1 if diff_val > 0.01 else 0- regressions = 1 if diff_val < -0.01 else 0-- baseline_comparison = f"{diff_highlight}{diff_sign}{(diff_val * 100):.2f}%{diff_highlight} (improvements: {improvements}, regressions: {regressions})"- diff_emoji = "🟢" if diff_val > 0.01 else ("🔴" if diff_val < -0.01 else "🔵")-- return baseline_comparison, diff_emoji-- def _format_metrics(self, result: dict[str, Any]) -> str:- """Format key metrics concisely."""- metrics = result.get("metrics", {})- if not metrics:- return "No metrics reported"-- duration = f"⏱️ {metrics['duration']['metric']:.2f} s" if metrics.get("duration") else None- total_tokens = f"🔢 {int(metrics['total_tokens']['metric'])} tokens" if metrics.get("total_tokens") else None- cost = f"💵 ${metrics['estimated_cost']['metric']:.4f} in tokens" if metrics.get("estimated_cost") else None-- return ", ".join(filter(None, [duration, total_tokens, cost]))-- def _build_traces_url(self, result: dict[str, Any]) -> str:- """Build the traces filter URL for the experiment."""- traces_filter = [- {- "key": "ai_experiment_name",- "value": [result.get("project_name", "")],- "operator": "exact",- "type": "event",- },- {- "key": "ai_experiment_id",- "value": [self.experiment_id],- "operator": "exact",- "type": "event",- },- ]- return f"https://us.posthog.com/ai-observability/traces?filters={urllib.parse.quote(json.dumps(traces_filter))}"---def format_results(- dataset_id: UUID,- dataset_name: str,- experiment_id: str,- results: EvaluationResults,- prev_results: EvaluationResults | None = None,-) -> tuple[list[dict[str, Any]], str]:- """Legacy function wrapper for backward compatibility."""- formatter = ResultsFormatter(dataset_id, dataset_name, experiment_id)- return formatter.format(results, prev_results)diff --git a/products/posthog_ai/eval_harness/README.md b/products/posthog_ai/eval_harness/README.mdindex 4034a6279b2c..c83f10db66b3 100644--- a/products/posthog_ai/eval_harness/README.md+++ b/products/posthog_ai/eval_harness/README.md@@ -6,7 +6,7 @@ Each eval case gets its own isolated org/team/user, so cases never see each otheThe harness builds product skills from the current checkout and uses native bundled skills by default.`--skill-delivery exec` instead packages those skills for MCP distribution, enables the exec skill prompt, and removes native skills from every sandbox so the two paths cannot satisfy the same case.-Unlike `ee/hogai/eval/ci/`, this tree does **not** run under pytest.+This is the eval harness for PostHog AI 2.0. It does **not** run under pytest.It runs on a standalone harness that boots the shared infrastructure once (test database, Django live server, LLM gateway, MCP server, Temporal) and then runs every selected suite concurrently.See [`harness/README.md`](harness/README.md) for how that works internally.diff --git a/products/posthog_ai/eval_harness/data_setup.py b/products/posthog_ai/eval_harness/data_setup.pyindex 228da050a863..7cbd03cc9180 100644--- a/products/posthog_ai/eval_harness/data_setup.py+++ b/products/posthog_ai/eval_harness/data_setup.py@@ -1,8 +1,4 @@-"""Shared data setup functions for eval harnesses.--Extracted from ``ee/hogai/eval/ci/conftest.py`` so both CI evals and sandboxed-agent evals can reuse the same demo data creation logic.-"""+"""Data setup for the PostHog AI eval harness."""from __future__ import annotationsdiff --git a/products/posthog_ai/eval_harness/engines/braintrust_patches.py b/products/posthog_ai/eval_harness/engines/braintrust_patches.pyindex 3c25e2b7d4b5..eab4d4f21289 100644--- a/products/posthog_ai/eval_harness/engines/braintrust_patches.py+++ b/products/posthog_ai/eval_harness/engines/braintrust_patches.py@@ -1,8 +1,6 @@"""Braintrust behavior this repo replaces. Importing this module applies the replacement.-Both offline eval entry points import it: the harness engine in ``braintrust.py``-and ``ee/hogai/eval/base.py``. Patching once at import, rather than per run, keeps-concurrent suites from restoring the original under each other.+Patching once at import keeps concurrent suites from restoring the original under each other."""from __future__ import annotationsdiff --git a/products/posthog_ai/eval_harness/harness/AGENTS.md b/products/posthog_ai/eval_harness/harness/AGENTS.mdindex 10e879b43856..61d61e0ee416 100644--- a/products/posthog_ai/eval_harness/harness/AGENTS.md+++ b/products/posthog_ai/eval_harness/harness/AGENTS.md@@ -138,4 +138,3 @@ Required variables are then validated by `env_preflight.validate_eval_env()` atThis tree is not pytest: do not add a `conftest.py` here and do not import `pytest` in harness or eval modules.The harness's own unit tests live in [`../test/`](../test/), which is ordinary pytest.Suite files under the `evals/` trees are never collected by pytest either — its default `python_files` only matches `test_*.py`.-`ee/hogai/eval/ci/` and `ee/hogai/eval/offline/` are still pytest and still import `data_setup` from this package, so keep that module's pytest-independence intact.diff --git a/products/posthog_ai/eval_harness/test/test_acp_log.py b/products/posthog_ai/eval_harness/test/test_acp_log.pyindex 9fd418beffd9..a5e9ad59e63f 100644--- a/products/posthog_ai/eval_harness/test/test_acp_log.py+++ b/products/posthog_ai/eval_harness/test/test_acp_log.py@@ -1,11 +1,3 @@-"""Unit tests for the sandboxed eval ACP log parser.--These tests exercise ``parse_log`` alone against synthetic JSONL entries that-mimic the agent-server's session log format. They intentionally live outside-``ee/hogai/eval/`` so they run under the default pytest configuration — no-Temporal worker, no Docker sandbox, no Django live server.-"""-from __future__ import annotationsimport jsondiff --git a/ee/hogai/test/test_eval_base.py b/products/posthog_ai/eval_harness/test/test_braintrust_patches.pysimilarity index 91%rename from ee/hogai/test/test_eval_base.pyrename to products/posthog_ai/eval_harness/test/test_braintrust_patches.pyindex 54b41d8539d9..df234dc2b15b 100644--- a/ee/hogai/test/test_eval_base.py+++ b/products/posthog_ai/eval_harness/test/test_braintrust_patches.py@@ -6,7 +6,7 @@ from django.test import SimpleTestCasefrom braintrust import EvalAsync, EvalCase, Scorefrom braintrust_core.score import Scorer-import ee.hogai.eval.base # noqa: F401 (imported for the braintrust patch it applies)+from products.posthog_ai.eval_harness.engines import braintrust_patches # noqa: F401 — applies the summary patchclass _SkipsOneCase(Scorer):diff --git a/products/posthog_ai/eval_harness/test/test_saved_object_scorers.py b/products/posthog_ai/eval_harness/test/test_saved_object_scorers.pynew file mode 100644index 000000000000..ad4efc0cc9c7--- /dev/null+++ b/products/posthog_ai/eval_harness/test/test_saved_object_scorers.py@@ -0,0 +1,119 @@+from __future__ import annotations++import asyncio+from copy import deepcopy+from typing import Any++from unittest.mock import patch++from parameterized import parameterized++from products.dashboards.evals.scorers import SavedDashboardContents+from products.feature_flags.backend.models.feature_flag import FeatureFlag+from products.feature_flags.evals.creation_scorers import CreatedFlagConfiguration+++ [+ ({}, 1.0),+ ({"property_value": "business/standard"}, 1.0),+ ({"rollout_percentage": 100}, 0.0),+ ({"property_value": ["business/standard", "free"]}, 0.0),+ ({"extra_group": True}, 0.0),+ ({"super_groups": [{"properties": [], "rollout_percentage": 100}]}, 0.0),+ ({"aggregation_group_type_index": None}, 0.0),+ ({"aggregation_group_type_index": 1}, 0.0),+ ({"property_type": "person"}, 0.0),+ ({"property_group_type_index": 1}, 0.0),+ ({"holdout": {"id": 1, "exclusion_percentage": 10}}, 0.0),+ ({"holdout_groups": [{"properties": [], "rollout_percentage": 10}]}, 0.0),+ ({"variants": [{"key": "control", "rollout_percentage": 100}]}, 0.0),+ ({"active": False}, 0.0),+ ({"archived": True}, 0.0),+ ({"missing_flag": True}, 0.0),+ ({"version": 2}, 0.0),+ ],+)+def test_flag_creation_scores_saved_configuration(change: dict[str, Any], expected_score: float) -> None:+ property_filter = {+ "key": "plan",+ "type": "group",+ "group_type_index": 0,+ "operator": "exact",+ "value": ["business/standard"],+ }+ spec = {+ "key": "bulk-file-export-preview",+ "rollout_percentage": 25,+ "aggregation_group_type_index": 0,+ "property": deepcopy(property_filter),+ }+ property_filter["value"] = change.get("property_value", property_filter["value"])+ property_filter["type"] = change.get("property_type", property_filter["type"])+ property_filter["group_type_index"] = change.get("property_group_type_index", property_filter["group_type_index"])+ group = {"properties": [property_filter], "rollout_percentage": change.get("rollout_percentage", 25)}+ flag = FeatureFlag(+ active=change.get("active", True),+ archived=change.get("archived", False),+ filters={+ "groups": [group, {"properties": [], "rollout_percentage": 100}] if change.get("extra_group") else [group],+ "multivariate": {"variants": change.get("variants", [])},+ "super_groups": change.get("super_groups", []),+ "aggregation_group_type_index": change.get("aggregation_group_type_index", 0),+ "holdout": change.get("holdout"),+ "holdout_groups": change.get("holdout_groups", []),+ "version": change.get("version", 1),+ },+ )+ with patch.object(+ CreatedFlagConfiguration, "_read_flags", return_value=[] if change.get("missing_flag") else [flag]+ ):+ score = asyncio.run(+ CreatedFlagConfiguration().eval_async({"seed": {"team_id": 42}}, {"created_flag_configuration": spec})+ )+ assert score.score == expected_score+++ [+ ({}, 1.0),+ ({"creating": True}, 1.0),+ ({"tiles": []}, 0.0),+ ({"tiles": [{"id": 11, "insight_id": 1}, {"id": 12, "insight_id": 3}]}, 0.0),+ ({"tiles": [{"id": 13, "insight_id": 1}, {"id": 12, "insight_id": 2}]}, 0.0),+ ({"tiles": [{"id": 11, "insight_id": 2}, {"id": 12, "insight_id": 1}]}, 0.0),+ ({"insights": {"1": {"event": "wrong"}, "2": {"event": "uploaded_file"}}}, 0.0),+ ({"dashboard_ids": [7, 8, 9]}, 0.0),+ ({"dashboard_id": 9, "dashboard_ids": [7, 9]}, 0.0),+ ({"insights": {"1": {"event": "signed_up"}, "2": {"event": "uploaded_file"}, "3": {}}}, 0.0),+ ],+)+def test_dashboard_scores_saved_charts_and_preserves_existing_tile(+ change: dict[str, Any], expected_score: float+) -> None:+ queries = {"1": {"event": "signed_up"}, "2": {"event": "uploaded_file"}}+ seed = {+ "team_id": 42,+ "insights": queries,+ "initial_insight_ids": [1, 2],+ "initial_dashboard_ids": [7],+ }+ if not change.get("creating"):+ seed.update({"dashboard_id": 8, "original_tile_id": 11, "original_tile_insight_id": 1})+ state = {+ "dashboard_ids": change.get("dashboard_ids", [7, 8]),+ "matching": [+ {+ "id": change.get("dashboard_id", 8),+ "tiles": change.get("tiles", [{"id": 11, "insight_id": 1}, {"id": 12, "insight_id": 2}]),+ }+ ],+ "insights": change.get("insights", queries),+ }+ with patch.object(SavedDashboardContents, "_read_state", return_value=state):+ score = asyncio.run(+ SavedDashboardContents().eval_async(+ {"seed": seed}, {"saved_dashboard_contents": {"name": "File activity overview"}}+ )+ )+ assert score.score == expected_scorediff --git a/products/posthog_ai/evals/AGENTS.md b/products/posthog_ai/evals/AGENTS.mdindex 5cd9272271ef..66e28fa9df3e 100644--- a/products/posthog_ai/evals/AGENTS.md+++ b/products/posthog_ai/evals/AGENTS.md@@ -1,9 +1,15 @@# Hedgebox demo data — reference for eval authors-Evals that need a project to query — every eval in this tree, and those in `ee/hogai/eval/ci` that take the `demo_org_team_user` fixture — run against a **single, deterministic, seeded Hedgebox dataset**. Hedgebox is a fictional cloud-storage SaaS (think Dropbox). When you write an eval case, the events, properties, groups, flags, insights, and experiments below are the ground truth the agent has to work with — your `expected` queries and scorers must match this taxonomy exactly (e.g. the event is `signed_up`, not `sign_up` or `user_signed_up`).+Evals that need a project to query run against a **single, deterministic, seeded Hedgebox dataset**. Hedgebox is a fictional cloud-storage SaaS (think Dropbox). When you write an eval case, the events, properties, groups, flags, insights, and experiments below are the ground truth the agent has to work with — your `expected` queries and scorers must match this taxonomy exactly (e.g. the event is `signed_up`, not `sign_up` or `user_signed_up`).Evals that score a prompt rather than a query supply their own case data inline and never touch this taxonomy.-That data has to be invented rather than adapted from real material — see [`ee/hogai/eval/AGENTS.md`](../../../ee/hogai/eval/AGENTS.md).+That data must be invented, not adapted from real material.+Before writing cases from support conversations, list only the properties each case must test, close the source, then write the cases from that list.+Use invented names, identifiers, and tokens, and reserved domains such as `example.com`.+Read the [public repository guidance](../../../AGENTS.md#public-open-source-repo-guidance) before adding case data.++Use [`hogli evals`](../eval_harness/README.md) to run PostHog AI evals.+Add suites under `products/posthog_ai/evals/` or `products/<product>/evals/` and follow [`/writing-evals`](../../../.agents/skills/writing-evals/SKILL.md).Source of truth (read these if anything below looks stale):@@ -31,7 +37,6 @@ HedgeboxMatrix(- The seed is fixed, so the dataset is **byte-for-byte reproducible** — assertions on relative shapes (e.g. "signups trend over -8w") are stable, but **do not hard-code absolute counts**; they can drift if the simulation code changes.- **Sandboxed evals** (`SandboxedDemoData` in `harness/demo_data.py`): a master Hedgebox team is generated once via `ensure_master_demo_team`, then each eval case gets its own org/team via `copy_demo_data_to_new_team` (ClickHouse `INSERT ... SELECT` copy + `set_project_up` re-run + taxonomy re-inference). When object storage is enabled, the master must also have all five warehouse CSVs and metadata rows. Case teams share those immutable master CSVs but receive isolated credentials, table metadata, annotations, and the persons join. Each case is isolated; the seeded user is **"Karen Smith"**.-- **CI evals** reuse one org/team via `create_demo_org_team_user`.- Events span both past (`days_past`) and future (`days_future` — `paid_bill` events are scheduled forward). When choosing date ranges in expected queries, prefer relative ranges like `-30d`, `-8w`, `-6m`.- Most insights/dashboards are built with `filterTestAccounts=True`. The team has `test_account_filters` configured, and a "Signed-up users" cohort exists.diff --git a/products/posthog_ai/evals/product_analytics/eval_funnel.py b/products/posthog_ai/evals/product_analytics/eval_funnel.pyindex b53a24b4bc4f..2bf6c71adc29 100644--- a/products/posthog_ai/evals/product_analytics/eval_funnel.py+++ b/products/posthog_ai/evals/product_analytics/eval_funnel.py@@ -1,13 +1,4 @@-"""Product analytics funnel eval cases for the sandboxed coding agent.--Intent mirrors ``ee/hogai/eval/ci/eval_funnel.py`` — the CI version asserts-on the exact ``AssistantFunnelsQuery`` Max produces, this version exercises-the same intents end-to-end through the sandboxed agent + PostHog MCP tools-and judges the funnel query the agent ran via the ``query-funnel`` MCP tool.--To run:- flox activate -- bash -c "set -a; source .env; set +a; python -m products.posthog_ai.eval_harness.harness eval_funnel"-"""+"""Product analytics funnel eval cases for the sandbox agent."""from __future__ import annotationsdiff --git a/products/posthog_ai/evals/product_analytics/eval_retention.py b/products/posthog_ai/evals/product_analytics/eval_retention.pyindex 3020d2717e60..ee77fff5b70f 100644--- a/products/posthog_ai/evals/product_analytics/eval_retention.py+++ b/products/posthog_ai/evals/product_analytics/eval_retention.py@@ -1,14 +1,4 @@-"""Product analytics retention eval cases for the sandboxed coding agent.--Intent mirrors ``ee/hogai/eval/ci/eval_retention.py`` — the CI version asserts-on the exact ``AssistantRetentionQuery`` Max produces, this version exercises-the same intents end-to-end through the sandboxed agent + PostHog MCP tools-and judges the retention query the agent ran via the ``query-retention`` MCP-tool.--To run:- flox activate -- bash -c "set -a; source .env; set +a; python -m products.posthog_ai.eval_harness.harness eval_retention"-"""+"""Product analytics retention eval cases for the sandbox agent."""from __future__ import annotationsdiff --git a/products/posthog_ai/evals/product_analytics/eval_schema_discovery.py b/products/posthog_ai/evals/product_analytics/eval_schema_discovery.pyindex 6eb3e75c23e2..3c4f9b5bb735 100644--- a/products/posthog_ai/evals/product_analytics/eval_schema_discovery.py+++ b/products/posthog_ai/evals/product_analytics/eval_schema_discovery.py@@ -7,9 +7,8 @@ MCP CLI's ``info <tool>`` command), (2) call ``read-data-schema`` toverify the event exists in the team's data, and (3) only then invoke``query-trends`` to build the insight.-Correctness of the produced trends query itself is not scored here — that-is ``ee/hogai/eval/ci/eval_trends.py``'s job. This eval grades ordering-and discovery hygiene.+The ``eval_trends`` suite scores query correctness.+This suite scores tool order and schema discovery.To run:flox activate -- bash -c "set -a; source .env; set +a; python -m products.posthog_ai.eval_harness.harness eval_schema_discovery"diff --git a/products/posthog_ai/evals/product_analytics/eval_trends.py b/products/posthog_ai/evals/product_analytics/eval_trends.pyindex bb8a65b78275..89d9d73e2289 100644--- a/products/posthog_ai/evals/product_analytics/eval_trends.py+++ b/products/posthog_ai/evals/product_analytics/eval_trends.py@@ -1,13 +1,4 @@-"""Product analytics trends eval cases for the sandboxed coding agent.--Intent mirrors ``ee/hogai/eval/ci/eval_trends.py`` — the CI version asserts-on the exact ``AssistantTrendsQuery`` Max produces, this version exercises-the same intents end-to-end through the sandboxed agent + PostHog MCP tools-and judges the trends query the agent ran via the ``query-trends`` MCP tool.--To run:- flox activate -- bash -c "set -a; source .env; set +a; python -m products.posthog_ai.eval_harness.harness eval_trends"-"""+"""Product analytics trends eval cases for the sandbox agent."""from __future__ import annotationsdiff --git a/products/posthog_ai/evals/sql/eval_sql.py b/products/posthog_ai/evals/sql/eval_sql.pyindex 0cef1140aa2d..4f358ddc8f07 100644--- a/products/posthog_ai/evals/sql/eval_sql.py+++ b/products/posthog_ai/evals/sql/eval_sql.py@@ -1,18 +1,8 @@"""SQL eval cases for the sandboxed coding agent.-Intent mirrors ``ee/hogai/eval/ci/eval_sql.py`` — the CI version drives the-LangGraph chat agent in ``AgentMode.SQL`` (which forces the SQL path), this-version exercises the same questions end-to-end through the sandboxed agent-+ PostHog MCP tools and judges the HogQL the agent ran via the-``execute-sql`` MCP tool.--Prompts are rephrased from the CI dataset to explicitly request HogQL.-The CI flow forces SQL via ``AgentMode.SQL``; the sandboxed agent has no-equivalent mode and is free to answer with typed query tools-(``query-trends`` / ``query-funnel`` / ``query-retention``). Without the-``Write a HogQL query that…`` framing, several cases would route to a-typed query tool — perfectly valid for the user, but not what this eval-is testing. The framing is the forcing function in lieu of an agent mode.+The suite scores HogQL from the ``execute-sql`` MCP tool.+Prompts explicitly request HogQL because the agent can also answer with typed query tools.+Those tools give valid answers, but they do not test SQL generation.To run:flox activate -- bash -c "set -a; source .env; set +a; python -m products.posthog_ai.eval_harness.harness eval_sql"diff --git a/products/posthog_ai/evals/sql/scorers.py b/products/posthog_ai/evals/sql/scorers.pyindex 7e916fd1c999..0430460e09fa 100644--- a/products/posthog_ai/evals/sql/scorers.py+++ b/products/posthog_ai/evals/sql/scorers.py@@ -6,13 +6,8 @@ funnel / retention judges in shape but lives outside ``product_analytics/``because ``execute-sql`` is a general-purpose tool, not a product-analyticsone.-The judge prompt is forked from the CI ``SQL_SEMANTICS_CORRECTNESS_PROMPT``-in ``ee/hogai/eval/scorers/sql.py`` — same HogQL guidance, but graded on-the six-bucket ``GRADED_ALIGNMENT_*`` scale used by the rest of the-sandboxed evals instead of binary Pass/Fail. The ``database_schema``-placeholder is dropped: the sandboxed run doesn't surface a schema dump-to scorers, and the judge has the user prompt + reference SQL to anchor-on without it.+The judge uses the ``GRADED_ALIGNMENT_*`` scale and compares the query with the user prompt and reference SQL.+The sandbox run does not provide a schema dump to scorers.The shared judge plumbing (``JudgedScorer``, alignment constants,``JUDGE_MODEL``) lives in ``products/posthog_ai/eval_harness/scorers/``; only thediff --git a/products/posthog_ai/evals/surveys/eval_surveys.py b/products/posthog_ai/evals/surveys/eval_surveys.pyindex 39747e62a704..187a36a4eb5f 100644--- a/products/posthog_ai/evals/surveys/eval_surveys.py+++ b/products/posthog_ai/evals/surveys/eval_surveys.py@@ -1,13 +1,4 @@-"""Survey creation eval cases for the sandboxed coding agent.--Intent mirrors ``ee/hogai/eval/ci/eval_surveys.py``. The CI version calls-Max's ``CreateSurveyTool`` directly and checks Django state. This version-asks the sandboxed agent to create surveys through the PostHog MCP-``survey-create`` tool and scores the payload/result it produced.--To run:- flox activate -- bash -c "set -a; source .env; set +a; python -m products.posthog_ai.eval_harness.harness eval_surveys"-"""+"""Survey creation eval cases for the sandbox agent."""from __future__ import annotationsdiff --git a/products/replay_vision/evals/README.md b/products/replay_vision/evals/README.mdindex 153ddd66b59a..f8ccb73f110c 100644--- a/products/replay_vision/evals/README.md+++ b/products/replay_vision/evals/README.md@@ -68,7 +68,7 @@ It is deliberately not attached to `pull_request`: Gemini is nondeterministic anIt collects a fresh dataset on the runner (so consent is re-verified every run; nothing is cached, uploaded, or persisted), runs the suite, and writes the aggregate scores to the job's step summary.The summary also links the run's `/ai-evals` offline experiment, where the harness publishes the same scores.Only those allowlisted summary lines are public: collector and harness output stay in runner-local files, because they carry session and observation ids.-The job needs `REPLAY_VISION_EVAL_POSTHOG_API_KEY` (a personal API key with scanner, session recording, export, and query read access to the dogfood project) plus the `GEMINI_API_KEY`, `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, and `BRAINTRUST_API_KEY` secrets `ci-ai.yml` already uses; if any is missing the job skips green and warns which.+The job needs `REPLAY_VISION_EVAL_POSTHOG_API_KEY` (a personal API key with scanner, session recording, export, and query read access to the dogfood project) plus the `GEMINI_API_KEY`, `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, and `BRAINTRUST_API_KEY` secrets; if any is missing the job skips green and warns which.## Data handlingdiff --git a/products/warehouse_sources/backend/models/util.py b/products/warehouse_sources/backend/models/util.pyindex 91b751544c6e..72583f428b46 100644--- a/products/warehouse_sources/backend/models/util.py+++ b/products/warehouse_sources/backend/models/util.py@@ -814,7 +814,6 @@ _BUCKET_SETTINGS_NOT_READABLE_BY_THE_NODE_ROLE = {"AI_BLOB_S3_BUCKET": "read via posthog.storage.object_storage (boto3), by ai_observability/backend/api/ai_blob.py","BATCH_EXPORTS_FILE_DOWNLOAD_BUCKET": "written via a pre-signed URL over an assumed STS role, and read via aioboto3 - never by ClickHouse","BILLING_USAGE_REPORTS_S3_BUCKET": "read via posthog.storage.object_storage (boto3), by posthog/temporal/usage_report/storage.py",- "DAGSTER_AI_EVALS_S3_BUCKET": "read via boto3 (s3.get_client()) by products/posthog_ai/dags/utils.py","DAGSTER_FAVICONS_S3_BUCKET": "read via boto3 (s3.get_client()) by products/web_analytics/dags/cache_favicons.py","DAGSTER_S3_BUCKET": "read via Dagster's own S3Resource (boto3), the pickle io-manager's storage","INBOX_RANKING_DATASET_S3_BUCKET": "read via boto3 by products/signals/dags/inbox_ranking/common.py",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/coin_api/tests/test_coin_api.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coin_api/tests/test_coin_api.pyindex 1cdd3bf05294..369c4e509f3a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/coin_api/tests/test_coin_api.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coin_api/tests/test_coin_api.py@@ -32,6 +32,9 @@ class _FakeResponse:def ok(self) -> bool:return self.status_code < 400+ def json(self) -> Any:+ return self._json_data+def raise_for_status(self) -> None:if not self.ok:raise requests.HTTPError(f"{self.status_code} Client Error", response=self) # type: ignore[arg-type]diff --git a/tools/hogli-commands/hogli_commands/test_runner.py b/tools/hogli-commands/hogli_commands/test_runner.pyindex bd7db18ecff6..64371a27d4fb 100644--- a/tools/hogli-commands/hogli_commands/test_runner.py+++ b/tools/hogli-commands/hogli_commands/test_runner.py@@ -38,7 +38,7 @@ def _is_test_file(path: str, rs_cfg_test: set[str] | None = None) -> bool:"""name = PurePosixPath(path).nameif path.endswith(".py"):- return name.startswith("test_") or (name.startswith("eval_") and path.startswith("ee/hogai/eval/"))+ return name.startswith("test_")if path.endswith((".test.ts", ".test.tsx")):return Trueif path.endswith(".spec.ts") and path.startswith("playwright/"):@@ -594,16 +594,7 @@ def detect_test_type(file_path: str) -> TestRunConfig:description="Playwright E2E test",)- # 2. Python eval tests (special pytest config)- if file_only.startswith("ee/hogai/eval/") and ext == ".py":- return TestRunConfig(- test_type="python-eval",- command=["pytest", "-c", "ee/hogai/eval/pytest.ini", "-s", file_path],- description="Python eval test (pytest with eval config)",- env=_python_env(),- )-- # 3. Python tests+ # 2. Python testsif ext == ".py" and any(file_only.startswith(root) for root in _PYTHON_ROOTS):return TestRunConfig(test_type="python",@@ -612,15 +603,15 @@ def detect_test_type(file_path: str) -> TestRunConfig:env=_python_env(),)- # 4. Jest tests (*.test.ts, *.test.tsx) — finds nearest package.json to determine pnpm filter+ # 3. Jest tests (*.test.ts, *.test.tsx) — finds nearest package.json to determine pnpm filterif file_only.endswith((".test.ts", ".test.tsx")):return _detect_jest_test(file_only, file_path, node_id)- # 5. Rust tests — finds nearest Cargo.toml; supports node IDs (path.rs::test_name)+ # 4. Rust tests — finds nearest Cargo.toml; supports node IDs (path.rs::test_name)if ext == ".rs":return _detect_rust_test(file_only, node_id)- # 6. Go — any .go file or go.mod; finds nearest go.mod and runs from module root+ # 5. Go — any .go file or go.mod; finds nearest go.mod and runs from module rootif ext == ".go" or PurePosixPath(file_only).name == "go.mod":return _detect_go_test(file_only)@@ -710,7 +701,7 @@ def _run_grouped(detected: list[tuple[str, TestRunConfig]], extra_args: list[strgroups.setdefault(config.test_type, []).append((f, config))for test_type, entries in groups.items():- if test_type in ("python", "python-eval"):+ if test_type == "python":# pytest can take multiple files at oncecfg = entries[0][1]command = cfg.command[:-1] + [f for f, _ in entries]@@ -777,7 +768,7 @@ def _run_watch(file_path: str, extra_args: list[str]) -> None:resolved = _resolve_to_repo_relative(file_path)config = detect_test_type(resolved)- if config.test_type in ("python", "python-eval"):+ if config.test_type == "python":# Use nodemon for Python, matching bin/tests behaviorwatch_dirs = ["./posthog", "./common/hogvm/python", "./ee", "./dags", "./products"]diff --git a/tools/hogli-commands/hogli_commands/tests/test_test_runner.py b/tools/hogli-commands/hogli_commands/tests/test_test_runner.pyindex 26095ffb577d..98b90f812e7d 100644--- a/tools/hogli-commands/hogli_commands/tests/test_test_runner.py+++ b/tools/hogli-commands/hogli_commands/tests/test_test_runner.py@@ -61,12 +61,6 @@ class TestDetectTestType:assert config.test_type == "python"assert config.command == ["pytest", "-s", "posthog/api/test/test_user.py::TestUserAPI::test_retrieve"]- def test_python_eval_uses_special_config(self) -> None:- config = detect_test_type("ee/hogai/eval/eval_router.py")- assert config.test_type == "python-eval"- assert config.command == ["pytest", "-c", "ee/hogai/eval/pytest.ini", "-s", "ee/hogai/eval/eval_router.py"]- assert "REDIS_URL" in config.env-# -- Jest tests: these hit real package.json files on disk --@parameterized.expand(@@ -365,8 +359,8 @@ class TestIsTestFile:@parameterized.expand([("posthog/api/test/test_user.py", True),- ("ee/hogai/eval/eval_router.py", True),- ("ee/hogai/eval_router.py", False),+ ("products/posthog_ai/evals/sql/eval_sql.py", False),+ ("products/posthog_ai/eval_harness/test/test_discovery.py", True),("posthog/eval_something.py", False),("ee/hogai/router.py", False),("posthog/models/team.py", False),