: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
fix(ci): cap schema artifact listing pagination (#81639)
Raúl Negrón-Oterod569c3c1555a
diff --git a/.depot/workflows/ci-backend.yml b/.depot/workflows/ci-backend.ymlindex 7577308f9fe9..4df65d9c01f7 100644--- a/.depot/workflows/ci-backend.yml+++ b/.depot/workflows/ci-backend.yml@@ -46,6 +46,8 @@# The shadow strips artifact uploads (above) and routes every cache write to Depot Cache# (below), so it has neither the artifact to download nor a GitHub cache to fill: the job,# and the check-migrations mig_schema_key output that feeds it, are depot-exempt.+# - migrated-schema upload settings: canonical tunes the upload (e.g. retention-days);+# the shadow strips artifact uploads (above), so those tunings are depot-exempt.# - OpenAPI types: the check-openapi-types job is folded into check-migrations as a# check-only step (drift still fails the run); only its auto-commit side effect is dropped# - events_json variants: the shadow never doubles the matrix (no RUN_NEW_EVENTS_SCHEMAdiff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.ymlindex f465b2b92ab6..48955bf74289 100644--- a/.github/workflows/ci-backend.yml+++ b/.github/workflows/ci-backend.yml@@ -1864,7 +1864,9 @@ jobs:with:name: migrated-schemapath: schema.sql.gz- retention-days: 90+ # Consumers only ever take the newest artifact, so a longer window just+ # adds pages to the artifacts listing that db:download-schema walks.+ retention-days: 7- name: Save schema to Actions cache for PR shards# Kept as the exact merge-base key that every consumer's restore-keys falls back to.diff --git a/.github/workflows/ci-clickhouse-multinode-migrations.yml b/.github/workflows/ci-clickhouse-multinode-migrations.ymlindex e2fe6232bf0d..9ba6cadf1de2 100644--- a/.github/workflows/ci-clickhouse-multinode-migrations.yml+++ b/.github/workflows/ci-clickhouse-multinode-migrations.yml@@ -90,11 +90,13 @@ jobs:GH_TOKEN: ${{ github.token }}run: |# ci-backend.yml's "Validate migrations" job uploads the post-migrate- # schema as the migrated-schema artifact on every master push- # (90-day retention). The Actions cache also holds it, but the repo's- # 10 GB LRU pool evicts the dump within minutes, so the artifact is- # the reliable source. Any recent master schema works — the smoke- # only needs Postgres bootable, migrate_clickhouse doesn't touch it.+ # schema as the migrated-schema artifact on every master push, held+ # for the retention-days set on that upload step. The scan below stays+ # well inside that window because master pushes are far more frequent.+ # The Actions cache also holds it, but the repo's 10 GB LRU pool evicts+ # the dump within minutes, so the artifact is the reliable source. Any+ # recent master schema works, because the smoke only needs Postgres+ # bootable and migrate_clickhouse doesn't touch it.# Resolve the artifact through successful master runs of# ci-backend.yml rather than the repo-wide artifact list, so only# that workflow's uploads are ever trusted. Paths-filtered masterdiff --git a/.github/workflows/ci-nodejs.yml b/.github/workflows/ci-nodejs.ymlindex a620ee6c57af..d42c6964a12c 100644--- a/.github/workflows/ci-nodejs.yml+++ b/.github/workflows/ci-nodejs.yml@@ -416,7 +416,8 @@ jobs:SECRET_KEY: 'abcdef' # unsafe - for testing onlyDATABASE_URL: 'postgres://posthog:posthog@localhost:5432/posthog'BEHAVIORAL_COHORTS_DATABASE_URL: 'postgres://posthog:posthog@localhost:5432/test_behavioral_cohorts'- GH_TOKEN: ${{ github.token }}+ # Schema artifact lookup pages the artifacts API; keep it off the shared per-repo bucket+ GH_TOKEN: ${{ steps.setup-gh-token.outputs.token || github.token }}run: |# Download pre-migrated schema from CI./bin/hogli db:download-schema@@ -688,7 +689,8 @@ jobs:SECRET_KEY: 'abcdef' # unsafe - for testing onlyDATABASE_URL: 'postgres://posthog:posthog@localhost:5432/posthog'BEHAVIORAL_COHORTS_DATABASE_URL: 'postgres://posthog:posthog@localhost:5432/test_behavioral_cohorts'- GH_TOKEN: ${{ github.token }}+ # Schema artifact lookup pages the artifacts API; keep it off the shared per-repo bucket+ GH_TOKEN: ${{ steps.setup-gh-token.outputs.token || github.token }}run: |# Download pre-migrated schema from CI./bin/hogli db:download-schemadiff --git a/tools/hogli-commands/hogli_commands/db_schema.py b/tools/hogli-commands/hogli_commands/db_schema.pyindex 3a27702d9dd9..bbc24faf10e7 100644--- a/tools/hogli-commands/hogli_commands/db_schema.py+++ b/tools/hogli-commands/hogli_commands/db_schema.py@@ -27,6 +27,7 @@ SCHEMA_ARTIFACT_NAME = "migrated-schema"SCHEMA_DUMP_NAME = "schema.sql.gz"LOCAL_SCHEMA_PATH = Path(".postgres-backups/schema-latest.sql.gz")MIN_SCHEMA_ARTIFACT_BYTES = 10_000+MAX_ARTIFACT_PAGES = 10DEFAULT_BASE_BRANCH = "master"DIAGNOSTIC_CANDIDATE_LIMIT = 3DOCKER_COMPOSE = ["docker", "compose", "-f", "docker-compose.dev.yml"]@@ -262,12 +263,20 @@ def select_newest_compatible_artifact(return candidates[0] if candidates else None-def fetch_schema_artifacts(*, token: str | None, session: requests.Session | None = None) -> list[SchemaArtifact]:+def find_newest_compatible_artifact(+ *,+ token: str | None,+ session: requests.Session | None = None,+ base_branch: str = DEFAULT_BASE_BRANCH,+ max_pages: int = MAX_ARTIFACT_PAGES,+) -> SchemaArtifact | None:+ # The listing is newest-first, so the first page holding a candidate holds the+ # newest one and the walk stops there. max_pages caps the miss case at a fixed+ # number of requests instead of paging through the whole retention window.http = session or requests.Session()- artifacts: list[SchemaArtifact] = []- page = 1+ fetched: list[SchemaArtifact] = []- while True:+ for page in range(1, max_pages + 1):response = http.get(f"https://api.github.com/repos/{GITHUB_REPOSITORY}/actions/artifacts",params={"name": SCHEMA_ARTIFACT_NAME, "per_page": 100, "page": page},@@ -287,13 +296,17 @@ def fetch_schema_artifacts(*, token: str | None, session: requests.Session | Nonif isinstance(raw_artifact, Mapping):artifact = _artifact_from_api(raw_artifact)if artifact is not None:- artifacts.append(artifact)+ fetched.append(artifact)++ selected = select_newest_compatible_artifact(fetched, base_branch=base_branch)+ if selected is not None:+ return selectedif "next" not in response.links:break- page += 1- return artifacts+ _emit_selection_diagnostics(fetched, base_branch=base_branch)+ return Nonedef download_schema_artifact(@@ -371,10 +384,8 @@ def download_latest_compatible_schema(session: requests.Session | None = None,) -> SchemaArtifact:token = github_token()- artifacts = fetch_schema_artifacts(token=token, session=session)- artifact = select_newest_compatible_artifact(artifacts, base_branch=base_branch)+ artifact = find_newest_compatible_artifact(token=token, session=session, base_branch=base_branch)if artifact is None:- _emit_selection_diagnostics(artifacts, base_branch=base_branch)raise SchemaRestoreUnavailable(f"no compatible {SCHEMA_ARTIFACT_NAME} artifact found for base_branch={base_branch}")diff --git a/tools/hogli-commands/hogli_commands/tests/test_db_schema.py b/tools/hogli-commands/hogli_commands/tests/test_db_schema.pyindex 86a2e730b39f..182e2fd4646e 100644--- a/tools/hogli-commands/hogli_commands/tests/test_db_schema.py+++ b/tools/hogli-commands/hogli_commands/tests/test_db_schema.py@@ -87,6 +87,61 @@ def test_select_ignores_invalid_artifacts(artifact: db_schema.SchemaArtifact) ->assert db_schema.select_newest_compatible_artifact([artifact]) is None+class _FakeArtifactPage:+ def __init__(self, artifacts: list[dict[str, Any]], *, has_next: bool) -> None:+ self._artifacts = artifacts+ self.links = {"next": {"url": "next"}} if has_next else {}++ def raise_for_status(self) -> None:+ pass++ def json(self) -> dict[str, Any]:+ return {"artifacts": self._artifacts}+++class _FakeArtifactPagesSession:+ def __init__(self, pages: list[list[dict[str, Any]]]) -> None:+ self._pages = pages+ self.get_count = 0++ def get(self, url: str, *, params: dict[str, Any], headers: dict[str, str], timeout: int) -> _FakeArtifactPage:+ self.get_count += 1+ page = params["page"]+ return _FakeArtifactPage(+ self._pages[page - 1] if page <= len(self._pages) else [],+ has_next=page < len(self._pages),+ )+++def _raw_artifact(artifact_id: int, head_branch: str) -> dict[str, Any]:+ return {+ "id": artifact_id,+ "name": db_schema.SCHEMA_ARTIFACT_NAME,+ "expired": False,+ "size_in_bytes": db_schema.MIN_SCHEMA_ARTIFACT_BYTES + 1,+ "archive_download_url": f"https://api.github.com/artifacts/{artifact_id}/zip",+ "created_at": "2026-01-01T00:00:00Z",+ "workflow_run": {"head_sha": "sha", "head_branch": head_branch},+ }+++def test_find_stops_at_first_page_with_compatible_candidate() -> None:+ session = _FakeArtifactPagesSession([[_raw_artifact(1, "master")], [_raw_artifact(2, "master")]])++ artifact = db_schema.find_newest_compatible_artifact(token="t", session=session, base_branch="master") # type: ignore[arg-type]++ assert session.get_count == 1+ assert artifact is not None and artifact.id == 1+++def test_find_caps_pages_when_no_candidate_matches() -> None:+ pages = [[_raw_artifact(page, "some-pr-branch")] for page in range(1, 31)]+ session = _FakeArtifactPagesSession(pages)++ assert db_schema.find_newest_compatible_artifact(token="t", session=session, base_branch="master") is None # type: ignore[arg-type]+ assert session.get_count == db_schema.MAX_ARTIFACT_PAGES++def test_select_honors_custom_base_branch() -> None:master_artifact = _artifact(1, "sha-a", "2026-01-01T00:00:00Z", head_branch="master")release_artifact = _artifact(2, "sha-b", "2026-01-02T00:00:00Z", head_branch="release-26.1")@@ -99,20 +154,23 @@ def test_select_honors_custom_base_branch() -> None:assert selected == release_artifact-def test_download_diagnostics_on_no_compatible_artifact(monkeypatch: pytest.MonkeyPatch) -> None:- artifacts = [- _artifact(10, "pr-sha", "2026-01-01T00:00:00Z", head_branch="some-pr"),- _artifact(11, "master-sha", "2026-01-02T00:00:00Z", head_branch="some-other-pr"),- ]+def test_find_emits_diagnostics_on_no_compatible_artifact(capsys: pytest.CaptureFixture[str]) -> None:+ session = _FakeArtifactPagesSession([[_raw_artifact(10, "some-pr"), _raw_artifact(11, "some-other-pr")]])++ assert db_schema.find_newest_compatible_artifact(token="t", session=session, base_branch="master") is None # type: ignore[arg-type]++ stderr = capsys.readouterr().err+ assert "Fetched 2 migrated-schema artifact(s)" in stderr+ assert "After name/expiry/size/branch filters: 0 candidate(s)" in stderr+++def test_download_fails_when_no_compatible_artifact(monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setattr(db_schema, "github_token", lambda: "token")- monkeypatch.setattr(db_schema, "fetch_schema_artifacts", lambda **kwargs: artifacts)+ monkeypatch.setattr(db_schema, "find_newest_compatible_artifact", lambda **kwargs: None)- split_runner = CliRunner(mix_stderr=False)- result = split_runner.invoke(db_schema.db_download_schema, [])+ result = runner.invoke(db_schema.db_download_schema, [])assert result.exit_code != 0- assert "Fetched 2 migrated-schema artifact(s)" in result.stderr- assert "After name/expiry/size/branch filters: 0 candidate(s)" in result.stderrdef test_effective_base_branch_prefers_env(monkeypatch: pytest.MonkeyPatch) -> None: