Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(ci): file-granularity backend sharding with per-segment durations (#64783)

Julian Bezfc4cfaf013ba
diff --git a/.github/scripts/optimize_test_durations.py b/.github/scripts/optimize_test_durations.py
index 96b274898484..027615387e8e 100644
--- a/.github/scripts/optimize_test_durations.py
+++ b/.github/scripts/optimize_test_durations.py
@@ -517,6 +517,19 @@ def main():
action="store_true",
help="Filter to only tests that exist in the codebase (runs pytest --collect-only)",
)
+ parser.add_argument(
+ "--scope-to-junit",
+ action="store_true",
+ help=(
+ "Filter the output to exactly the nodeids the JUnit artifacts saw run "
+ "(requires --junit-dir). The shared .test_durations is a union across all "
+ "CI jobs, so a segment's artifacts still carry stale cross-segment nodeids "
+ "(other segments' param variants, product-routed files). This scopes a "
+ "per-segment file to what THAT segment actually ran -- the run-set is already "
+ "in the JUnit, so no extra collection is needed. Used to emit "
+ ".test_durations.<segment> for --split-granularity=file."
+ ),
+ )
parser.add_argument(
"--merge-files",
type=Path,
@@ -577,6 +590,26 @@ def main():
result.migration_tax_seconds / 60,
)
+ # Scope to exactly what this segment's JUnit saw run. The shared timing
+ # artifacts each carry the full union (every shard restores the merged file
+ # then refreshes its own slice), so a per-segment merge still contains other
+ # segments' nodeids -- their param variants and product-routed files -- which
+ # would poison a file-granularity plan (it budgets weight for tests that never
+ # collect in this segment). The JUnit call_times map is the segment's real
+ # run-set at nodeid granularity, already loaded above, so this costs nothing.
+ if args.scope_to_junit:
+ if not junit_shards:
+ logger.error("--scope-to-junit requires --junit-dir with matching artifacts")
+ sys.exit(1)
+ ran = set().union(*(s.call_times.keys() for s in junit_shards))
+ before_count = len(durations)
+ durations = {k: v for k, v in durations.items() if k in ran}
+ logger.info(
+ " Scoped to %d nodeids the JUnit saw run (dropped %d cross-segment/stale)",
+ len(durations),
+ before_count - len(durations),
+ )
+
# Filter to only existing tests if requested
if args.filter_existing:
logger.info("Collecting existing tests from codebase...")
diff --git a/.github/workflows/ci-backend-update-test-timing.yml b/.github/workflows/ci-backend-update-test-timing.yml
index 547cfe17e4b2..a361c5e55263 100644
--- a/.github/workflows/ci-backend-update-test-timing.yml
+++ b/.github/workflows/ci-backend-update-test-timing.yml
@@ -197,6 +197,27 @@ jobs:
# to the script — see test_optimize_test_durations.py.
uv run .github/scripts/optimize_test_durations.py .test_durations \
--merge-files /tmp/core_durations /tmp/temporal_durations /tmp/products_durations /tmp/dagster_durations
+
+ # Additionally emit nodeid-clean per-segment files for
+ # --split-granularity=file. The shared .test_durations above is a union
+ # across every CI job, so a Core file-mode plan scoped to it budgets weight
+ # for tests that never run in Core (other segments' param variants,
+ # product-routed files) — that mis-scoping is the imbalance file-mode hit.
+ # --scope-to-junit trims each file to exactly the nodeids that segment's
+ # JUnit saw run; the run-set is already in the artifacts, so this adds no
+ # collection. The union above is untouched (item-mode + turbo-discover still
+ # read it); these are purely additive, cached per-segment below.
+ # Non-fatal: --scope-to-junit hard-exits if a segment's JUnit is missing,
+ # but the union .test_durations above is already built and MUST still be
+ # cached/committed below. A JUnit miss just skips that segment's per-segment
+ # file for the day; ci-backend then falls back to scoping the union.
+ uv run .github/scripts/optimize_test_durations.py timing_artifacts .test_durations.core \
+ --segment Core --junit-dir junit_artifacts --scope-to-junit \
+ || echo "::warning::Core per-segment durations skipped (no JUnit?) — file-mode falls back to union scoping"
+ uv run .github/scripts/optimize_test_durations.py timing_artifacts .test_durations.temporal \
+ --segment Temporal --junit-dir junit_artifacts --scope-to-junit \
+ || echo "::warning::Temporal per-segment durations skipped (no JUnit?) — file-mode falls back to union scoping"
+
# Also drop junit_artifacts — ghcommit-action defaults file_pattern
# to "." and chokes on leftover download dirs ("read junit_artifacts/:
# is a directory"). The commit steps below also pin file_pattern as a
@@ -214,7 +235,9 @@ jobs:
# ever touch the newest entry, so each prior day's entry ages out 7 days after
# it stops being newest: up to ~7 daily entries (~1 MB zstd each, ~7 MB total)
# coexist before eviction. Tiny, self-pruning, no shared-budget pressure.
- echo "cache_key=posthog-test-durations-$(date -u +%F)" >> "$GITHUB_OUTPUT"
+ TODAY=$(date -u +%F)
+ echo "date=$TODAY" >> "$GITHUB_OUTPUT"
+ echo "cache_key=posthog-test-durations-$TODAY" >> "$GITHUB_OUTPUT"
# Every run refreshes the cache; only the monthly cron (or a manual dispatch)
# also commits the repo fallback, so the daily runs don't churn the 11 MB file.
# SCHEDULE is the cron that triggered the run — keep it in sync with the monthly
@@ -238,6 +261,22 @@ jobs:
path: .test_durations
key: ${{ steps.durations-meta.outputs.cache_key }}
+ - name: Save per-segment durations to Actions cache
+ # Nodeid-clean per-segment files for --split-granularity=file, restored by
+ # ci-backend via the posthog-segment-durations- prefix. The prefix MUST NOT
+ # start with posthog-test-durations- : the union restores match that prefix and
+ # take the newest entry, so a shared prefix would shadow the union .test_durations
+ # across every backend + dagster shard. Same per-day key shape as the union; a
+ # miss makes file-mode fall back to scoping the union (still correct, just the
+ # pre-fix balance). continue-on-error so a cache hiccup never fails the merge.
+ uses: actions/cache/save@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3
+ continue-on-error: true
+ with:
+ path: |
+ .test_durations.core
+ .test_durations.temporal
+ key: posthog-segment-durations-${{ steps.durations-meta.outputs.date }}
+
- name: Check for changes
id: check-changes
run: |
diff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.yml
index d347c6b9da46..c9e59588571c 100644
--- a/.github/workflows/ci-backend.yml
+++ b/.github/workflows/ci-backend.yml
@@ -2232,6 +2232,24 @@ jobs:
restore-keys: |
posthog-test-durations-
+ - name: Restore per-segment test durations from cache
+ # File-granularity sharding plans from a per-segment file (.test_durations.core /
+ # .test_durations.temporal) scoped to exactly what the segment runs, avoiding the
+ # union file's cross-segment contamination. These are cache-only (NOT committed),
+ # written by the daily timing-update job on master so PR runs can restore them.
+ # On a miss the file is simply absent and the "Run … tests" step omits
+ # --split-plan-path, falling back to scoping the union (still correct, pre-fix
+ # balance). The posthog-segment-durations- prefix is deliberately distinct from
+ # the union's posthog-test-durations- so the two never shadow each other.
+ uses: actions/cache/restore@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3
+ with:
+ path: |
+ .test_durations.core
+ .test_durations.temporal
+ key: posthog-segment-durations-${{ github.run_id }}
+ restore-keys: |
+ posthog-segment-durations-
+
- name: Determine if --snapshot-update should be on
# UPDATE mode: human commits - update snapshots
# CHECK mode: bot commits (after snapshot update) - verify snapshots match exactly
@@ -2291,13 +2309,26 @@ jobs:
shell: 'signal-fanout bash --noprofile --norc -eo pipefail {0}'
run: | # async_migrations covered in ci-async-migrations.yml
set +e
- # Pick the split algorithm at runtime: optimal_chunks only when the
- # installed pytest-split offers it, else duration_based_chunks. A workflow
- # edit runs merged with master, so an unrebased PR on older pytest-split
- # must not hit an unknown --splitting-algorithm. See AGENTS.md (CI).
+ # Pick the split algorithm and granularity at runtime: optimal_chunks +
+ # file granularity only when the installed pytest-split offers them, else
+ # duration_based_chunks / item. A workflow edit runs merged with master, so
+ # an unrebased PR on older pytest-split must not hit an unknown
+ # --splitting-algorithm / --split-granularity. See AGENTS.md (CI).
SPLITTING_ALGORITHM=duration_based_chunks
- if python -c "from pytest_split.algorithms import Algorithms; raise SystemExit(0 if 'optimal_chunks' in Algorithms.names() else 1)" 2>/dev/null; then
+ SPLIT_GRANULARITY=()
+ if python -c "from pytest_split.algorithms import Algorithms; from pytest_split.plugin import PytestSplitFilePlugin; raise SystemExit(0 if 'optimal_chunks' in Algorithms.names() else 1)" 2>/dev/null; then
SPLITTING_ALGORITHM=optimal_chunks
+ SPLIT_GRANULARITY=(--split-granularity=file)
+ # Scope the file-mode plan to Core's clean per-segment durations
+ # (restored from the daily master cache) when the pinned pytest-split
+ # supports it, so the plan isn't poisoned by the union .test_durations's
+ # cross-segment tests — see AGENTS.md (CI). Only persons-on-events-off,
+ # non-compat Core matches the .core run-set; POE-on and compat run a
+ # different/narrower scope, and a cache miss with no committed file all
+ # fall back to scoping the union.
+ if [ -f .test_durations.core ] && [[ "${{ matrix.person-on-events }}" != "true" ]] && [[ "${{ matrix.compat }}" != "true" ]] && python -c "from pytest_split.plugin import SUPPORTS_SPLIT_PLAN_PATH" 2>/dev/null; then
+ SPLIT_GRANULARITY+=(--split-plan-path .test_durations.core)
+ fi
fi
if [[ "$MODE" == "selected" ]]; then
# Selected mode: run only the test files chosen by the snob shadow selector.
@@ -2333,6 +2364,7 @@ jobs:
--durations=1000 --durations-min=1.0 --store-durations \
--pytest-durations=100 \
--splitting-algorithm="$SPLITTING_ALGORITHM" \
+ "${SPLIT_GRANULARITY[@]}" \
--reruns 2 --reruns-delay 1 \
-r fEsxX \
--junitxml=junit-core.xml \
@@ -2387,13 +2419,24 @@ jobs:
TEMPORAL_FILES: ${{ needs.select-tests.outputs.temporal_files }}
run: |
set +e
- # Pick the split algorithm at runtime: optimal_chunks only when the
- # installed pytest-split offers it, else duration_based_chunks. A workflow
- # edit runs merged with master, so an unrebased PR on older pytest-split
- # must not hit an unknown --splitting-algorithm. See AGENTS.md (CI).
+ # Pick the split algorithm and granularity at runtime: optimal_chunks +
+ # file granularity only when the installed pytest-split offers them, else
+ # duration_based_chunks / item. A workflow edit runs merged with master, so
+ # an unrebased PR on older pytest-split must not hit an unknown
+ # --splitting-algorithm / --split-granularity. See AGENTS.md (CI).
SPLITTING_ALGORITHM=duration_based_chunks
- if python -c "from pytest_split.algorithms import Algorithms; raise SystemExit(0 if 'optimal_chunks' in Algorithms.names() else 1)" 2>/dev/null; then
+ SPLIT_GRANULARITY=()
+ if python -c "from pytest_split.algorithms import Algorithms; from pytest_split.plugin import PytestSplitFilePlugin; raise SystemExit(0 if 'optimal_chunks' in Algorithms.names() else 1)" 2>/dev/null; then
SPLITTING_ALGORITHM=optimal_chunks
+ SPLIT_GRANULARITY=(--split-granularity=file)
+ # Scope the file-mode plan to this segment's clean per-segment durations
+ # (restored from the daily master cache) when the pinned pytest-split
+ # supports it, so the plan isn't poisoned by the union .test_durations —
+ # see AGENTS.md (CI). A missing file (cache miss, no fallback) is omitted
+ # and the plugin falls back to scoping the union.
+ if [ -f .test_durations.temporal ] && python -c "from pytest_split.plugin import SUPPORTS_SPLIT_PLAN_PATH" 2>/dev/null; then
+ SPLIT_GRANULARITY+=(--split-plan-path .test_durations.temporal)
+ fi
fi
if [[ "$MODE" == "selected" ]]; then
# Selected mode: no sharding, no --store-durations (don't pollute
@@ -2416,6 +2459,7 @@ jobs:
--durations=100 --durations-min=1.0 --store-durations \
--pytest-durations=100 \
--splitting-algorithm="$SPLITTING_ALGORITHM" \
+ "${SPLIT_GRANULARITY[@]}" \
--reruns 2 --reruns-delay 1 \
-r fEsxX \
--junitxml=junit-temporal.xml \
diff --git a/.github/workflows/ci-dagster.yml b/.github/workflows/ci-dagster.yml
index 0fa903ddd87d..6cd419ebe7e0 100644
--- a/.github/workflows/ci-dagster.yml
+++ b/.github/workflows/ci-dagster.yml
@@ -395,19 +395,23 @@ jobs:
- name: Run Dagster tests
run: |
- # Pick the split algorithm at runtime: optimal_chunks only when the
- # installed pytest-split offers it, else duration_based_chunks. A workflow
- # edit runs merged with master, so an unrebased PR on older pytest-split
- # must not hit an unknown --splitting-algorithm. See AGENTS.md (CI).
+ # Pick the split algorithm and granularity at runtime: optimal_chunks +
+ # file granularity only when the installed pytest-split offers them, else
+ # duration_based_chunks / item. A workflow edit runs merged with master, so
+ # an unrebased PR on older pytest-split must not hit an unknown
+ # --splitting-algorithm / --split-granularity. See AGENTS.md (CI).
SPLITTING_ALGORITHM=duration_based_chunks
- if python -c "from pytest_split.algorithms import Algorithms; raise SystemExit(0 if 'optimal_chunks' in Algorithms.names() else 1)" 2>/dev/null; then
+ SPLIT_GRANULARITY=()
+ if python -c "from pytest_split.algorithms import Algorithms; from pytest_split.plugin import PytestSplitFilePlugin; raise SystemExit(0 if 'optimal_chunks' in Algorithms.names() else 1)" 2>/dev/null; then
SPLITTING_ALGORITHM=optimal_chunks
+ SPLIT_GRANULARITY=(--split-granularity=file)
fi
pytest posthog/dags products/**/dags \
--reuse-db \
--splits ${{ matrix.concurrency }} --group ${{ matrix.group }} \
--durations=100 --durations-min=1.0 --store-durations \
--splitting-algorithm="$SPLITTING_ALGORITHM" \
+ "${SPLIT_GRANULARITY[@]}" \
--reruns 2 --reruns-delay 1 \
-r fEsxX \
--junitxml=junit-dagster-${{ matrix.group }}.xml
diff --git a/ee/hogai/chat_agent/query_planner/test/test_toolkit.py b/ee/hogai/chat_agent/query_planner/test/test_toolkit.py
index 5df5d8a96e5b..a4e6fe161947 100644
--- a/ee/hogai/chat_agent/query_planner/test/test_toolkit.py
+++ b/ee/hogai/chat_agent/query_planner/test/test_toolkit.py
@@ -197,7 +197,24 @@ class TestTaxonomyAgentToolkit(ClickhouseTestMixin, APIBaseTest):
)
self.assertEqual(toolkit.retrieve_entity_property_values("org", "test"), '"7"')
- def test_retrieve_entity_property_values_virtual_person_property_with_examples(self):
+ @patch("ee.hogai.chat_agent.query_planner.toolkit.ActorsPropertyTaxonomyQueryRunner")
+ def test_retrieve_entity_property_values_virtual_person_property_with_examples(self, mock_runner_class):
+ # A virtual property has no stored actor values, so the toolkit falls back to
+ # the taxonomy's hardcoded examples. The real runner reads ClickHouse actor
+ # data, which sibling tests on the same shard can pollute (file-level sharding
+ # runs the whole file together and ClickHouse writes are not rolled back per
+ # test), making it return a stray "Unknown" instead of nothing. Mock an empty
+ # result so this asserts the fallback deterministically; the real-runner path
+ # is covered by the property-value tests that seed actual actor data.
+ now = datetime(2024, 1, 1, tzinfo=UTC)
+ mock_runner_class.return_value.run.return_value = CachedActorsPropertyTaxonomyQueryResponse(
+ cache_key="test",
+ is_cached=True,
+ last_refresh=now,
+ next_allowed_client_refresh=now,
+ results=[],
+ timezone="UTC",
+ )
toolkit = DummyToolkit(self.team, self.user)
self.assertEqual(
toolkit.retrieve_entity_property_values("person", "$virt_initial_channel_type"),
diff --git a/posthog/api/test/test_data_color_theme.py b/posthog/api/test/test_data_color_theme.py
index b07126d9132b..33c118a1dedb 100644
--- a/posthog/api/test/test_data_color_theme.py
+++ b/posthog/api/test/test_data_color_theme.py
@@ -9,6 +9,40 @@ from posthog.models.team.team import Team
class TestDataColorTheme(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ # The global "Default Theme" is seeded by migration 0537, but a
+ # TransactionTestCase flush earlier on the same shard truncates migration
+ # data and nothing restores it (ensure_migration_defaults is a manual
+ # command, not a test hook). Recreate it idempotently so these tests don't
+ # silently depend on what ran before them. The guard matches the migration
+ # so a non-flushed run still sees exactly one global theme.
+ if not DataColorTheme.objects.filter(team__isnull=True, name="Default Theme").exists():
+ DataColorTheme.objects.create(
+ name="Default Theme",
+ # Mirror migration 0537 so the recreated theme is identical to the
+ # seeded one — otherwise its `colors` would be order/shard-dependent
+ # (real palette when not flushed, empty when recreated).
+ colors=[
+ "#1d4aff",
+ "#621da6",
+ "#42827e",
+ "#ce0e74",
+ "#f14f58",
+ "#7c440e",
+ "#529a0a",
+ "#0476fb",
+ "#fe729e",
+ "#35416b",
+ "#41cbc4",
+ "#b64b02",
+ "#e4a604",
+ "#a56eff",
+ "#30d5c8",
+ ],
+ team=None,
+ )
+
def test_can_fetch_public_themes(self) -> None:
response = self.client.get(f"/api/environments/{self.team.pk}/data_color_themes")
diff --git a/posthog/clickhouse/test/test_cluster.py b/posthog/clickhouse/test/test_cluster.py
index d71de9ea91f2..f9a6d0ee485b 100644
--- a/posthog/clickhouse/test/test_cluster.py
+++ b/posthog/clickhouse/test/test_cluster.py
@@ -138,6 +138,14 @@ def test_alter_mutation_single_command(cluster: ClickhouseCluster) -> None:
table = EVENTS_DATA_TABLE()
count = 100
+ # Start from a clean table. This table is shared and ClickHouse writes are not
+ # rolled back per test, so sibling tests on the same shard leave rows behind.
+ # The mutation below updates every row (WHERE 1 = 1), so leftover rows would
+ # inflate the post-mutation count and break the exact-count assertion. Normally
+ # masked because these tests scatter across shards; file-level sharding runs the
+ # whole file together.
+ cluster.map_all_hosts(Query(f"TRUNCATE TABLE {table}")).result()
+
# make sure there is some data to play with first
cluster.map_one_host_per_shard(Query(f"INSERT INTO {table} SELECT * FROM generateRandom() LIMIT {count}")).result()
diff --git a/posthog/session_recordings/test/test_session_recording_personhog.py b/posthog/session_recordings/test/test_session_recording_personhog.py
index c6bcd08af52d..d6baec87564b 100644
--- a/posthog/session_recordings/test/test_session_recording_personhog.py
+++ b/posthog/session_recordings/test/test_session_recording_personhog.py
@@ -5,7 +5,7 @@ TestLoadPersonIntegration — parameterized integration test (ORM + personhog).
"""
from posthog.test.base import BaseTest
-from unittest.mock import MagicMock, patch
+from unittest.mock import MagicMock, PropertyMock, patch
from django.test import SimpleTestCase
@@ -87,15 +87,16 @@ class TestLoadPersonRouting(SimpleTestCase):
recording = SessionRecording()
recording.distinct_id = "test-distinct-id"
recording.team_id = 1
- # Use a real-looking mock for the team FK — bypass Django's descriptor
+ # Use a real-looking mock for the team FK — bypass Django's descriptor.
mock_team = MagicMock()
mock_team.pk = 1
- recording.__dict__["_team_cache"] = mock_team
- object.__setattr__(recording, "_team_cache", mock_team)
- # Patch the property access used in load_person
- type(recording).team = property(lambda self: mock_team) # type: ignore[assignment]
- recording.load_person()
+ # Patch `team` at the class level via patch.object so the original FK
+ # descriptor is restored afterwards. A bare `type(recording).team = ...`
+ # leaks a setter-less property into every later SessionRecording test in
+ # the same process (only visible when those tests run on the same shard).
+ with patch.object(type(recording), "team", new_callable=PropertyMock, return_value=mock_team):
+ recording.load_person()
mock_routing_counter.labels.assert_called_with(
operation="load_person", source=expected_source, client_name="posthog-django"
diff --git a/posthog/settings/celery.py b/posthog/settings/celery.py
index cb5328f4ad0c..fe1a67cbc1c7 100644
--- a/posthog/settings/celery.py
+++ b/posthog/settings/celery.py
@@ -8,7 +8,21 @@ from posthog.settings.data_stores import REDIS_URL
# Only listen to the default queue "celery", unless overridden via the CLI
CELERY_QUEUES = (Queue("celery", Exchange("celery"), "celery"),)
CELERY_DEFAULT_QUEUE = "celery"
-CELERY_IMPORTS: list[str] = []
+# Tasks defined OUTSIDE the autodiscovered `<app>/tasks.py` convention only register
+# when their module happens to get imported. That's fine under the normal worker (the
+# app loads them transitively) and under item-level test sharding (every shard imports
+# the whole tree), but NOT under --split-granularity=file, where a shard imports only
+# its own files — so e.g. test_all_posthog_tasks_registered saw an incomplete registry.
+# List them here so Celery's import_default_modules() registers them deterministically
+# (worker + tests), independent of what else got imported.
+CELERY_IMPORTS: list[str] = [
+ "posthog.api.oauth.cimd",
+ "posthog.caching.warming",
+ "posthog.email",
+ "posthog.models.product_intent.product_intent",
+ "posthog.models.scoping",
+ "posthog.scoping_audit",
+]
CELERY_BROKER_URL = REDIS_URL # celery connects to redis
CELERY_BEAT_MAX_LOOP_INTERVAL = 30 # sleep max 30sec before checking for new periodic events
CELERY_RESULT_BACKEND = REDIS_URL # stores results for lookup when processing
diff --git a/posthog/tasks/test/test_task_registration.py b/posthog/tasks/test/test_task_registration.py
index 0283ebbe13af..a874180362bd 100644
--- a/posthog/tasks/test/test_task_registration.py
+++ b/posthog/tasks/test/test_task_registration.py
@@ -12,6 +12,14 @@ class TestAllTasksRegistered(TestCase):
snapshot: Any
def test_all_posthog_tasks_registered_snapshot(self) -> None:
+ # Load the full task set the way a worker does (autodiscover + CELERY_IMPORTS)
+ # rather than relying on whatever else this shard happened to import. Without
+ # this the registry is complete only because item-level sharding imports the
+ # whole tree; under --split-granularity=file a shard imports just its own files,
+ # so non-tasks.py tasks (see CELERY_IMPORTS) would be missing and the snapshot
+ # would silently lose entries.
+ app.loader.import_default_modules()
+
all_tasks = sorted([name for name in app.tasks.keys() if name.startswith("posthog.")])
self.assertGreater(len(all_tasks), 0, "No PostHog tasks found. This likely indicates a registration problem.")
diff --git a/posthog/temporal/tests/conftest.py b/posthog/temporal/tests/conftest.py
index f3905a226653..39b562aaa31d 100644
--- a/posthog/temporal/tests/conftest.py
+++ b/posthog/temporal/tests/conftest.py
@@ -1,4 +1,5 @@
import random
+import signal
import asyncio
import pytest
@@ -19,6 +20,23 @@ from posthog.temporal.common.client import connect
from posthog.temporal.common.logger import configure_logger
[email protected](autouse=True)
+def _ignore_sigpipe():
+ """Keep SIGPIPE non-fatal for temporal tests.
+
+ Importing temporalio pulls in grpc, whose C core can leave SIGPIPE on its
+ default (process-killing) disposition. Some tests here run real HTTP servers
+ whose client disconnects mid-response (e.g. test_handles_temporal_timeout),
+ producing a broken-pipe write — which then kills the whole shard with exit
+ 141 instead of raising a catchable BrokenPipeError. This is normally masked
+ because the offending tests are scattered across shards; file-level sharding
+ runs them together. Restore Python's default SIG_IGN so the broken pipe is a
+ normal error, not a process-killer.
+ """
+ signal.signal(signal.SIGPIPE, signal.SIG_IGN)
+ yield
+
+
@pytest.fixture
def organization():
"""A test organization."""
diff --git a/pyproject.toml b/pyproject.toml
index 21c64aed93f4..de42a64ae7c0 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -302,7 +302,7 @@ infi-clickhouse-orm = { git = "https://github.com/PostHog/infi.clickhouse_orm",
# optimal_chunks split. Fork: PostHog/pytest-split (of jerry-git/pytest-split).
# To pull upstream fixes: rebase the fork's feat branch onto upstream, cut the next
# v0.11.0-posthog.N tag, and bump this pin.
-pytest-split = { git = "https://github.com/PostHog/pytest-split", tag = "v0.11.0-posthog.1" }
+pytest-split = { git = "https://github.com/PostHog/pytest-split", tag = "v0.11.0-posthog.6" }
[tool.isort]
diff --git a/uv.lock b/uv.lock
index 9b6a96822d0b..0a587af42857 100644
--- a/uv.lock
+++ b/uv.lock
@@ -11,7 +11,7 @@ resolution-markers = [
]
[options]
-exclude-newer = "0001-01-01T00:00:00Z" # This has no effect and is included for backwards compatibility when using relative exclude-newer values.
+exclude-newer = "2026-06-15T10:42:02.393902Z"
exclude-newer-span = "P7D"
[options.exclude-newer-package]
@@ -6015,7 +6015,7 @@ dev = [
{ name = "pytest-icdiff", specifier = "~=0.9" },
{ name = "pytest-mock", specifier = "~=3.15.1" },
{ name = "pytest-rerunfailures", specifier = "~=16.1" },
- { name = "pytest-split", git = "https://github.com/PostHog/pytest-split?tag=v0.11.0-posthog.1" },
+ { name = "pytest-split", git = "https://github.com/PostHog/pytest-split?tag=v0.11.0-posthog.6" },
{ name = "pytest-timeout", specifier = "~=2.4.0" },
{ name = "pytest-xdist", specifier = "~=3.8.0" },
{ name = "python-dateutil", specifier = "~=2.9.0" },
@@ -6819,7 +6819,7 @@ wheels = [
[[package]]
name = "pytest-split"
version = "0.11.0"
-source = { git = "https://github.com/PostHog/pytest-split?tag=v0.11.0-posthog.1#83365ed14512bb854d51c917389d3359be360c5c" }
+source = { git = "https://github.com/PostHog/pytest-split?tag=v0.11.0-posthog.6#8fc59b2e1ca13b9421f6e7828105d8635437c912" }
dependencies = [
{ name = "pytest" },
]