Skip to content

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

chore(ci): run the backend master push on depot (#116512)

Raúl Negrón-Otero78df66113b90
diff --git a/.depot/workflows/ci-backend.yml b/.depot/workflows/ci-backend.yml
index 58a635ac1e17..b177394778d4 100644
--- a/.depot/workflows/ci-backend.yml
+++ b/.depot/workflows/ci-backend.yml
@@ -9,8 +9,9 @@
#
# Intentional deltas vs canonical (everything else is kept apples-to-apples):
# - Every pull request event runs here. Canonical runs no backend tests on pull requests;
-# its `Django Tests Pass` job only points at this workflow. Depot's own checks carry no
-# output, so the gate posts a `Test results` check with the failure summary.
+# its `Django Tests Pass` job only points at this workflow, and it has no push trigger.
+# Depot's own checks carry no output, so the gate posts a `Test results` check with the
+# failure summary.
# - runs-on: depot-* labels instead of GitHub-hosted ubuntu-24.04
# - turbo-discover adds the `origin` remote before its history fetch when it is missing.
# Depot CI serves an input-less actions/checkout from a fast clone that has no remote.
@@ -40,11 +41,9 @@
# here is depot-only: the paths-filter skip, the `!= 'schedule'` gates on the per-commit
# checks, the events_json cron in build_django_matrix, the events schema recording and
# its upload, and POSTHOG_PYTEST_HARD_EXIT.
-# - mirror-schema-cache: canonical's master run copies the migrated schema dump out of the
-# migrated-schema artifact into GitHub Actions Cache, so fork PRs (which run without
-# secrets and cannot authenticate to Depot Cache) prime instead of migrating from scratch.
-# The shadow routes cache writes to Depot Cache, so it must not fill the GitHub
-# cache. This job and the mig_schema_key output that feeds it remain depot-exempt.
+# - The master run's schema dump lands in Depot artifacts and Depot Cache, which GitHub-hosted
+# runners and fork PRs cannot read. .github/workflows/ci-backend-schema-mirror.yml copies it
+# into a GitHub artifact and GitHub Actions cache; canonical has no mirror job.
# - Superseded-run cancel: Depot's concurrency policy can keep an older event, so each event gets
# its own group and `cancel-superseded-runs` cancels older runs. See "Superseded runs" in
# .agents/skills/depot-ci/references/posthog-check-run-semantics.md.
@@ -115,10 +114,8 @@
# .github/workflows/ci-backend-update-test-timing.yml runs on Depot runners and writes
# that same cache, so shard counts match GitHub Actions. Committed .test_durations is the
# fallback.
-# - No push trigger: canonical primes the shared schema cache on master, and Depot Cache
-# serves both engines. The `github.event_name != 'push'` guards stay to mirror canonical.
-# - Fresh-master cache waiting is canonical-only: it waits on the GitHub Actions
-# warmer, which cannot signal readiness for Depot's separate cache channel.
+# - The master push runs here, so the per-commit checks and the schema dump have no
+# `github.event_name != 'push'` guard; the matrices keep theirs, as in canonical.
# This workflow runs all of our backend django tests.
#
@@ -127,11 +124,13 @@
name: Backend CI on Depot
# Depot CI copy of canonical Backend CI. Branch protection requires this workflow's gate,
# `Backend CI on Depot / Django Tests Pass on Depot`, posted by the Depot Code Access app.
-# Pull requests, manual runs and the hourly master run start here on their own; canonical
-# keeps the master push.
+# Pull requests, master pushes, manual runs and the hourly master run all start here.
# The drift check (.github/workflows/ci-backend-shadow-drift.yml) keeps this file in sync
# with canonical; it runs whenever either file changes.
on:
+ push:
+ branches:
+ - master
schedule:
# Hourly full-matrix run against the newest master state. The merge queue's
# trunk-merge/** run already gated every commit before it landed, so this is where
@@ -1528,7 +1527,7 @@ jobs:
# bots rewrite manifests across majors, so this is the block. Stdlib only, no venv.
sdk-major-guard:
needs: [changes]
- if: needs.changes.outputs.sdk_manifests == 'true' && github.event_name != 'push' && github.event_name != 'schedule'
+ if: needs.changes.outputs.sdk_manifests == 'true' && github.event_name != 'schedule'
timeout-minutes: 5
permissions: {}
name: SDK major-version guard (depot-ubuntu-24.04)
@@ -1541,7 +1540,7 @@ jobs:
repo-checks:
needs: [changes]
# product_yamls: ownership-only PRs still need the owners.yaml lint below.
- if: (needs.changes.outputs.backend == 'true' || needs.changes.outputs.product_yamls == 'true' || needs.changes.outputs.repo_invariants == 'true') && github.event_name != 'push' && github.event_name != 'schedule'
+ if: (needs.changes.outputs.backend == 'true' || needs.changes.outputs.product_yamls == 'true' || needs.changes.outputs.repo_invariants == 'true') && github.event_name != 'schedule'
timeout-minutes: 10
outputs:
deterministic_failure: ${{ steps.deterministic-failure.outputs.deterministic_failure || 'false' }}
@@ -1808,7 +1807,10 @@ jobs:
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
repository: PostHog/posthog
- ref: master
+ # The schema dump takes its cache key from the pushed commit, so a push
+ # migrates from that commit. A newer master can carry migrations that the
+ # pushed commit does not have.
+ ref: ${{ github.event_name == 'push' && github.sha || 'master' }}
path: upstream-master
- name: Install python dependencies for master
working-directory: upstream-master
@@ -1898,7 +1900,7 @@ jobs:
# For same-repo PRs, checkout the actual branch (not the merge commit)
# so upstream/master..HEAD reflects PR files. Fork PRs fall back
# to the default merge commit.
- ref: ${{ (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == 'PostHog/posthog') && github.event.pull_request.head.ref || github.ref }}
+ ref: ${{ (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == 'PostHog/posthog') && github.event.pull_request.head.ref || github.event_name == 'push' && github.sha || github.ref }}
clean: false
- name: Install python dependencies for this PR
run: |
@@ -2278,22 +2280,6 @@ jobs:
# Verify the dump is valid
gunzip -t schema.sql.gz
- - name: Upload migrated schema artifact
- if: ${{ github.event_name == 'push' }}
- uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
- with:
- name: migrated-schema
- path: schema.sql.gz
- # 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 PR-base key that every consumer's restore-keys falls back to.
- if: github.event_name == 'push'
- uses: actions/cache/save@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3
- with:
- path: schema.sql.gz
- key: posthog-schema-master-${{ github.sha }}
- name: Compute migration-set schema key
# Must match the PR-base computation in turbo-discover and the
# master restore key above (inputs, hash, and key prefix).
@@ -2308,13 +2294,35 @@ jobs:
DB_ROUTING=$(git ls-tree -r --format='%(objectname) %(path)' HEAD -- products/db_routing.yaml posthog/product_db_config.py posthog/product_db_router.py)
PG_IMAGE=$(git show "HEAD:docker-compose.base.yml" 2>/dev/null \
| grep -m1 -E '^[[:space:]]*image:[[:space:]]*postgres:' | tr -d '[:space:]')
+ KEY=""
if [ -z "$MIG_FILES" ]; then
- echo "key=" >> $GITHUB_OUTPUT
echo "::notice::no migration files matched — skipping migration-set schema save"
else
MIG_HASH=$(printf '%s\n%s\n%s' "$MIG_FILES" "$PG_IMAGE" "$DB_ROUTING" | sha256sum | cut -c1-40)
- echo "key=posthog-schema-mig-${SCHEMA_CACHE_EPOCH}-${MIG_HASH}" >> $GITHUB_OUTPUT
+ KEY="posthog-schema-mig-${SCHEMA_CACHE_EPOCH}-${MIG_HASH}"
fi
+ echo "key=$KEY" >> $GITHUB_OUTPUT
+ printf '%s' "$KEY" > schema-cache-key
+ - name: Upload migrated schema artifact
+ if: ${{ github.event_name == 'push' }}
+ uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
+ with:
+ name: migrated-schema
+ # .github/workflows/ci-backend-schema-mirror.yml copies the dump into GitHub
+ # artifacts and cache; the key file tells it the migration-set cache key.
+ path: |
+ schema.sql.gz
+ schema-cache-key
+ # 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 PR-base key that every consumer's restore-keys falls back to.
+ if: github.event_name == 'push'
+ uses: actions/cache/save@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3
+ with:
+ path: schema.sql.gz
+ key: posthog-schema-master-${{ github.sha }}
- name: Save schema to Actions cache (migration-set key)
if: github.event_name == 'push' && steps.mig-schema-key.outputs.key != ''
uses: actions/cache/save@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3
@@ -2450,8 +2458,7 @@ jobs:
check-openapi-types:
needs: [changes]
- # Not on master push: master only primes the schema cache.
- if: (needs.changes.outputs.backend == 'true' || needs.changes.outputs.openapi_types == 'true') && github.event_name != 'push' && github.event_name != 'schedule'
+ if: (needs.changes.outputs.backend == 'true' || needs.changes.outputs.openapi_types == 'true') && github.event_name != 'schedule'
timeout-minutes: 20
outputs:
deterministic_failure: ${{ steps.deterministic-failure.outputs.deterministic_failure || 'false' }}
@@ -2460,7 +2467,7 @@ jobs:
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
- ref: ${{ (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == 'PostHog/posthog') && github.event.pull_request.head.ref || github.ref }}
+ ref: ${{ (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == 'PostHog/posthog') && github.event.pull_request.head.ref || github.event_name == 'push' && github.sha || github.ref }}
clean: false
- name: Clean up data directories with container permissions
run: |
diff --git a/.github/scripts/ci-alerts-devex.js b/.github/scripts/ci-alerts-devex.js
index e23b3fe78660..55513fd4f3d8 100644
--- a/.github/scripts/ci-alerts-devex.js
+++ b/.github/scripts/ci-alerts-devex.js
@@ -99,37 +99,6 @@ function buildLanes(env) {
countNeedsActivity: false,
}))
const scheduled = list(env.SCHEDULED_GATING_WORKFLOWS).map((workflowFile) => ({ workflowFile }))
- // The workflow whose cron runs on Depot CI has no GitHub runs to list. Its lane reads the file
- // that .github/scripts/depot_scheduled_runs.py wrote, which holds the runs in GitHub's shape.
- // A missing or unparseable file throws, so the lane reads as unreadable, never green.
- if (env.DEPOT_SCHEDULED_GATING_WORKFLOW) {
- scheduled.push({
- workflowFile: env.DEPOT_SCHEDULED_GATING_WORKFLOW,
- listRuns: (page) => {
- if (page !== 1) {
- return []
- }
- const runs = JSON.parse(fs.readFileSync(env.DEPOT_SCHEDULED_RUNS_FILE, 'utf8'))
- if (
- !Array.isArray(runs) ||
- runs.length === 0 ||
- runs.some(
- (run) =>
- !run ||
- !['completed', 'in_progress'].includes(run.status) ||
- !Number.isFinite(Date.parse(run.created_at)) ||
- (run.status === 'completed' &&
- !['success', 'failure', 'cancelled'].includes(run.conclusion))
- )
- ) {
- throw new Error('Depot scheduled runs file contains invalid run data')
- }
- return runs
- },
- // GitHub has no run history for this lane, so the alert links its failing run.
- linkFailingRun: true,
- })
- }
for (const source of scheduled) {
lanes.push({
...source,
@@ -146,7 +115,43 @@ function buildLanes(env) {
countNeedsActivity: true,
})
}
- return lanes
+ // A workflow that runs on Depot CI has no GitHub runs to list. Each of its lanes reads the
+ // file that .github/scripts/depot_backend_runs.py wrote for that trigger, which holds the runs
+ // in GitHub's shape. A missing or unparseable file throws, so the lane reads as unreadable,
+ // never green.
+ const depotWorkflows = new Set(list(env.DEPOT_WORKFLOWS))
+ return lanes.map((lane) =>
+ depotWorkflows.has(lane.workflowFile)
+ ? { ...lane, ...depotRunSource(`${env.DEPOT_RUNS_DIR}/${lane.workflowFile}-${lane.event}.json`) }
+ : lane
+ )
+}
+
+function depotRunSource(file) {
+ return {
+ listRuns: (page) => {
+ if (page !== 1) {
+ return []
+ }
+ const runs = JSON.parse(fs.readFileSync(file, 'utf8'))
+ if (
+ !Array.isArray(runs) ||
+ runs.length === 0 ||
+ runs.some(
+ (run) =>
+ !run ||
+ !['completed', 'in_progress'].includes(run.status) ||
+ !Number.isFinite(Date.parse(run.created_at)) ||
+ (run.status === 'completed' && !['success', 'failure', 'cancelled'].includes(run.conclusion))
+ )
+ ) {
+ throw new Error('Depot runs file contains invalid run data')
+ }
+ return runs
+ },
+ // GitHub has no run history for this lane, so the alert links its failing run.
+ linkFailingRun: true,
+ }
}
// ---------------------------------------------------------------------------
diff --git a/.github/scripts/ci-alerts-devex.test.js b/.github/scripts/ci-alerts-devex.test.js
index badb6eee3cb4..44aebe2892a9 100644
--- a/.github/scripts/ci-alerts-devex.test.js
+++ b/.github/scripts/ci-alerts-devex.test.js
@@ -170,6 +170,8 @@ function run(github, { history = [], now = minutes(0), env = {}, fetch: fetchImp
ACTIVITY_WINDOW_MINUTES: '120',
COMMIT_FAILURE_STREAK_THRESHOLD: '10',
DIAGNOSIS_WEBHOOK_URL: '',
+ DEPOT_WORKFLOWS: '',
+ DEPOT_RUNS_DIR: '',
...env,
})
return ciAlertsDevex(
@@ -860,19 +862,19 @@ describe('ci-alerts-devex', () => {
it(`scheduled lane read from Depot CI: ${scenario}`, async (t) => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'depot-runs-'))
t.after(() => fs.rmSync(dir, { recursive: true, force: true }))
- const runsFile = path.join(dir, 'runs.json')
if (depotRuns) {
- fs.writeFileSync(runsFile, JSON.stringify(depotRuns))
+ fs.writeFileSync(path.join(dir, 'ci-backend.yml-schedule.json'), JSON.stringify(depotRuns))
}
const github = laneGithub(
- { 'ci-backend.yml:push': runs('Backend CI', ['success']) },
+ { 'ci-frontend.yml:push': runs('Frontend CI', ['success']) },
pushAt(minutes(-3).toISOString())
)
const { slack, outputs } = await run(github, {
env: {
- GATING_WORKFLOWS: 'ci-backend.yml',
- DEPOT_SCHEDULED_GATING_WORKFLOW: 'ci-backend.yml',
- DEPOT_SCHEDULED_RUNS_FILE: runsFile,
+ GATING_WORKFLOWS: 'ci-frontend.yml',
+ SCHEDULED_GATING_WORKFLOWS: 'ci-backend.yml',
+ DEPOT_WORKFLOWS: 'ci-backend.yml',
+ DEPOT_RUNS_DIR: dir,
},
history: expected.action === 'hold' ? [activeAnchor({ workflows: ['Backend CI (scheduled)'] })] : [],
})
@@ -882,6 +884,34 @@ describe('ci-alerts-devex', () => {
})
}
+ for (const [scenario, depotRuns, expected] of [
+ ['pages on a failure streak', runs('Backend CI', Array(5).fill('failure')), { action: 'create', blocking: '1' }],
+ ['stays quiet while green', runs('Backend CI', ['success']), { action: 'none', blocking: '0' }],
+ ['holds an open incident when the file is missing', null, { action: 'hold', blocking: '0' }],
+ ]) {
+ it(`push lane read from Depot CI: ${scenario}`, async (t) => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'depot-runs-'))
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }))
+ if (depotRuns) {
+ fs.writeFileSync(path.join(dir, 'ci-backend.yml-push.json'), JSON.stringify(depotRuns))
+ }
+ const github = laneGithub(
+ { 'ci-frontend.yml:push': runs('Frontend CI', ['success']) },
+ pushAt(minutes(-3).toISOString())
+ )
+ const { outputs } = await run(github, {
+ env: {
+ GATING_WORKFLOWS: 'ci-frontend.yml,ci-backend.yml',
+ DEPOT_WORKFLOWS: 'ci-backend.yml',
+ DEPOT_RUNS_DIR: dir,
+ },
+ history: expected.action === 'hold' ? [activeAnchor({ workflows: ['Backend CI'] })] : [],
+ })
+ assert.equal(outputs.action, expected.action)
+ assert.equal(outputs.blocking_count, expected.blocking)
+ })
+ }
+
it('a red scheduled lane stays quiet while nobody is pushing (weekend gate)', async () => {
// A cron keeps producing runs through a quiet weekend, so unlike a push lane its run
// streak alone must not open an incident.
diff --git a/.github/scripts/depot_scheduled_runs.py b/.github/scripts/depot_backend_runs.py
similarity index 62%
rename from .github/scripts/depot_scheduled_runs.py
rename to .github/scripts/depot_backend_runs.py
index f10476c9cf54..f83ebfef64e9 100644
--- a/.github/scripts/depot_scheduled_runs.py
+++ b/.github/scripts/depot_backend_runs.py
@@ -1,18 +1,20 @@
#!/usr/bin/env python3
-"""Read the hourly Backend CI runs on Depot CI: their verdicts and their artifacts.
-
-The hourly master run of Backend CI lives on Depot CI, which keeps its runs and artifacts
-apart from GitHub Actions. This is the Depot counterpart of listing workflow runs with
-`gh api` and fetching artifacts with `gh run download`.
-
- depot_scheduled_runs.py find --prefix timing_data- --min-artifacts 38 --limit 5
- depot_scheduled_runs.py download <run-id> --pattern 'timing_data-Core-*' --dir timing
- depot_scheduled_runs.py gate-runs
-
-`find` prints one `<run-id> <sha>` line per successful run, newest first. `download` unpacks
-each matching artifact into `<dir>/<artifact name>/`, the layout `gh run download` produces.
-`gate-runs` prints the newest runs as JSON, each with the conclusion of its gate job, in the
-shape .github/scripts/ci-alerts-devex.js reads GitHub workflow runs in.
+"""Read the master Backend CI runs on Depot CI: their verdicts and their artifacts.
+
+The master push and the hourly run of Backend CI live on Depot CI, which keeps its runs and
+artifacts apart from GitHub Actions. This is the Depot counterpart of listing workflow runs
+with `gh api` and fetching artifacts with `gh run download`.
+
+ depot_backend_runs.py find --trigger schedule --prefix timing_data- --min-artifacts 38 --limit 5
+ depot_backend_runs.py download <run-id> --pattern 'timing_data-Core-*' --dir timing
+ depot_backend_runs.py gate-runs --trigger push --limit 40 --out runs.json
+
+`find` prints one `<run-id> <sha>` line per run of the trigger with the artifacts, newest first;
+it lists successful runs unless `--status` says otherwise.
+`download` unpacks each matching artifact into `<dir>/<artifact name>/`, the layout
+`gh run download` produces. `gate-runs` writes the newest runs of one trigger as JSON, each
+with the conclusion of its gate job, in the shape .github/scripts/ci-alerts-devex.js reads
+GitHub workflow runs in.
Needs the `depot` CLI and DEPOT_TOKEN.
"""
@@ -37,15 +39,14 @@ WORKFLOW_NAME = "Backend CI on Depot"
GATE_JOB_KEY = "ci-backend.yml:django_tests"
GATE_CONCLUSIONS = {"finished": "success", "failed": "failure", "cancelled": "cancelled"}
ENDED = frozenset(GATE_CONCLUSIONS)
-# Short enough that the alerter's read of GATE_RUNS_LISTED runs ends inside its step timeout.
+# Short enough that the alerter's lane reads end inside their step timeout.
CLI_TIMEOUT_SECONDS = 10
DOWNLOAD_TIMEOUT_SECONDS = 120
PARALLEL_CLI_CALLS = 8
# The Depot CLI returns at most 200 workflows, which is 8 days of hourly runs.
MAX_LISTED = 200
-# The alerter resolves an incident when no listed run is a settled failure, so the window has
-# to outlast a stretch of hung or cancelled runs.
-GATE_RUNS_LISTED = 12
+TRIGGERS = ("push", "schedule")
+MASTER_REF = "refs/heads/master"
class ListedWorkflow(TypedDict):
@@ -68,8 +69,14 @@ class Job(TypedDict, total=False):
finished_at: str
+class ShownRun(TypedDict):
+ trigger: str
+ ref: str
+
+
class ShownWorkflow(TypedDict):
org_id: str
+ run: ShownRun
jobs: list[Job]
@@ -90,9 +97,9 @@ def depot(*args: str, timeout: int = CLI_TIMEOUT_SECONDS) -> str:
return result.stdout
-def scheduled_workflows(statuses: list[str], limit: int, *, repo: str = REPO) -> list[ListedWorkflow]:
- """The hourly Backend CI workflows in the given states, newest first."""
- args = ["workflow", "list", "--repo", repo, "--name", WORKFLOW_NAME, "--trigger", "schedule", "-n", str(limit)]
+def master_workflows(statuses: list[str], limit: int, *, trigger: str, repo: str = REPO) -> list[ListedWorkflow]:
+ """The master Backend CI workflows of one trigger in the given states, newest first."""
+ args = ["workflow", "list", "--repo", repo, "--name", WORKFLOW_NAME, "--trigger", trigger, "-n", str(limit)]
for status in statuses:
args += ["--status", status]
# The CLI prints `null` when nothing matches.
@@ -104,6 +111,10 @@ def scheduled_workflows(statuses: list[str], limit: int, *, repo: str = REPO) ->
return sorted(workflows, key=lambda w: w["created_at"], reverse=True)
+def show(workflow_id: str) -> ShownWorkflow:
+ return cast(ShownWorkflow, json.loads(depot("workflow", "show", workflow_id, "--output", "json")))
+
+
def artifacts(run_id: str) -> list[Artifact]:
listed = json.loads(depot("artifacts", "list", run_id, "--output", "json") or "null") or {}
return cast(list[Artifact], listed.get("artifacts") or [])
@@ -117,18 +128,24 @@ def newest_per_name(run_artifacts: list[Artifact]) -> list[Artifact]:
return list(newest.values())
-def find(prefix: str, min_artifacts: int, limit: int, max_age_days: int) -> list[ListedWorkflow]:
+def find(
+ prefix: str, min_artifacts: int, limit: int, max_age_days: int, *, trigger: str, statuses: list[str]
+) -> list[ListedWorkflow]:
cutoff = (datetime.now(UTC) - timedelta(days=max_age_days)).strftime("%Y-%m-%dT%H:%M:%SZ")
found: list[ListedWorkflow] = []
- for workflow in scheduled_workflows(["finished"], MAX_LISTED):
+ for workflow in master_workflows(statuses, MAX_LISTED, trigger=trigger):
if workflow["created_at"] < cutoff:
break
try:
names = {a["name"] for a in artifacts(workflow["run_id"]) if a["name"].startswith(prefix)}
+ sys.stderr.write(f"Run {workflow['run_id']} has {len(names)} {prefix}* artifacts\n")
+ # Only a candidate push run pays for the extra CLI call that reads its ref.
+ if len(names) >= min_artifacts and trigger == "push" and not ran_on_master(show(workflow["workflow_id"])):
+ sys.stderr.write(f"Run {workflow['run_id']} did not run on master, skipping it\n")
+ continue
except (subprocess.SubprocessError, json.JSONDecodeError) as error:
- sys.stderr.write(f"Run {workflow['run_id']}: could not list artifacts, skipping it: {error!r}\n")
+ sys.stderr.write(f"Run {workflow['run_id']}: could not read it, skipping it: {error!r}\n")
continue
- sys.stderr.write(f"Run {workflow['run_id']} has {len(names)} {prefix}* artifacts\n")
if len(names) >= min_artifacts:
found.append(workflow)
if len(found) >= limit:
@@ -173,16 +190,28 @@ def download(run_id: str, patterns: list[str], directory: Path) -> int:
return len(matching)
-def gate_run(listed: ListedWorkflow) -> GateRun:
+def ran_on_master(shown: ShownWorkflow) -> bool:
+ """A branch can add itself to the push trigger in its own copy of the workflow.
+
+ Depot leaves a scheduled run's ref empty, and the schedule fires only on the default branch.
+ Any other run counts as master only when its ref says so, so a payload without a ref fails closed.
+ """
+ run = shown.get("run") or {}
+ return run.get("trigger") == "schedule" or run.get("ref") == MASTER_REF
+
+
+def gate_run(listed: ListedWorkflow) -> GateRun | None:
"""One workflow as a GitHub-shaped run. A workflow whose gate job has not ended is not completed."""
- shown = cast(ShownWorkflow, json.loads(depot("workflow", "show", listed["workflow_id"], "--output", "json")))
+ shown = show(listed["workflow_id"])
+ if not ran_on_master(shown):
+ return None
gate = next((job for job in shown.get("jobs") or [] if job.get("job_key") == GATE_JOB_KEY), None)
conclusion: str | None = None
if gate and gate.get("status") in GATE_CONCLUSIONS:
conclusion = GATE_CONCLUSIONS[gate["status"]]
elif listed["status"] in ENDED:
- # An hourly run that ended without a gate verdict ran no tests. The alerter drops
- # skipped runs, so reporting one as skipped would hide a lane that tests nothing.
+ # A run that ended without a gate verdict ran no checks. The alerter drops skipped
+ # runs, so reporting one as skipped would hide a lane that tests nothing.
conclusion = "cancelled" if listed["status"] == "cancelled" else "failure"
return {
"id": listed["run_id"],
@@ -196,15 +225,15 @@ def gate_run(listed: ListedWorkflow) -> GateRun:
}
-def gate_runs() -> list[GateRun]:
- listed = scheduled_workflows(["queued", "running", *sorted(ENDED)], GATE_RUNS_LISTED)
+def gate_runs(trigger: str, limit: int) -> list[GateRun]:
+ listed = master_workflows(["queued", "running", *sorted(ENDED)], limit, trigger=trigger)
with ThreadPoolExecutor(max_workers=PARALLEL_CLI_CALLS) as pool:
- runs = list(pool.map(gate_run, listed))
+ runs = [run for run in pool.map(gate_run, listed) if run is not None]
# An empty or inconclusive window must not resolve an existing CI incident.
if not any(
run["status"] == "completed" and run["conclusion"] not in (None, "cancelled", "skipped") for run in runs
):
- raise ValueError("No settled Backend CI verdict in the scheduled run window")
+ raise ValueError(f"No settled Backend CI verdict in the {trigger} run window")
return runs
@@ -212,23 +241,39 @@ def main() -> int:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
commands = parser.add_subparsers(dest="command", required=True)
find_parser = commands.add_parser("find")
+ find_parser.add_argument("--trigger", choices=TRIGGERS, required=True)
find_parser.add_argument("--prefix", required=True)
find_parser.add_argument("--min-artifacts", type=int, default=1)
find_parser.add_argument("--limit", type=int, default=1)
find_parser.add_argument("--max-age-days", type=int, default=14)
+ # A run whose unrelated job failed after the upload still carries the artifact.
+ find_parser.add_argument("--status", action="append", choices=sorted(ENDED), default=None)
download_parser = commands.add_parser("download")
download_parser.add_argument("run_id")
download_parser.add_argument("--pattern", action="append", required=True)
download_parser.add_argument("--dir", type=Path, required=True)
- commands.add_parser("gate-runs")
+ gate_parser = commands.add_parser("gate-runs")
+ gate_parser.add_argument("--trigger", choices=TRIGGERS, required=True)
+ gate_parser.add_argument("--limit", type=int, required=True)
+ gate_parser.add_argument("--out", type=Path, required=True)
args = parser.parse_args()
if args.command == "find":
- for workflow in find(args.prefix, args.min_artifacts, args.limit, args.max_age_days):
+ for workflow in find(
+ args.prefix,
+ args.min_artifacts,
+ args.limit,
+ args.max_age_days,
+ trigger=args.trigger,
+ statuses=args.status or ["finished"],
+ ):
sys.stdout.write(f"{workflow['run_id']} {workflow['sha']}\n")
return 0
if args.command == "gate-runs":
- json.dump(gate_runs(), sys.stdout)
+ # Written whole, so a reader never sees a half-written file.
+ partial = args.out.with_suffix(".partial")
+ partial.write_text(json.dumps(gate_runs(args.trigger, args.limit)))
+ partial.replace(args.out)
return 0
count = download(args.run_id, args.pattern, args.dir)
sys.stderr.write(f"Downloaded {count} artifacts matching {args.pattern} from run {args.run_id}\n")
diff --git a/.github/scripts/report_workflow_run_traces.py b/.github/scripts/report_workflow_run_traces.py
index 79f5da04fc74..90e9febe2a08 100644
--- a/.github/scripts/report_workflow_run_traces.py
+++ b/.github/scripts/report_workflow_run_traces.py
@@ -55,11 +55,12 @@ import urllib.error
import urllib.parse
import urllib.request
from collections.abc import Iterator, Mapping, Sequence
+from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass, replace
from datetime import UTC, datetime, timedelta
from typing import Any, TypedDict, cast
-import depot_scheduled_runs
+import depot_backend_runs
from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.resources import Resource
@@ -284,7 +285,7 @@ def watermark(repo: str, token: str, *, lookback_hours: float, now: datetime, op
def scan_runs(repo: str, token: str, since: datetime, *, opener: Any = None) -> list[dict]:
"""Completed master runs whose completion lands at or after `since`, newest first.
- GitHub supplies master pushes; scheduled Backend CI runs are read from Depot separately.
+ GitHub supplies master pushes; Backend CI runs are read from Depot separately.
The API can only filter on `created`, so widen the window by a day and narrow
on `updated_at` — which for a completed run is when it finished.
@@ -527,7 +528,7 @@ def parse_depot_run(shown: DepotShownWorkflow) -> WorkflowRun | None:
"id": job["job_id"],
"name": job.get("job_display_name") or job["job_key"],
"status": "completed",
- "conclusion": depot_scheduled_runs.GATE_CONCLUSIONS.get(job["status"], job["status"]),
+ "conclusion": depot_backend_runs.GATE_CONCLUSIONS.get(job["status"], job["status"]),
"html_url": f"{url}?job={job['job_id']}",
"created_at": job.get("started_at"),
"started_at": job.get("started_at"),
@@ -546,7 +547,7 @@ def parse_depot_run(shown: DepotShownWorkflow) -> WorkflowRun | None:
"workflow_id": workflow["workflow_id"],
"event": context["trigger"],
"status": "completed",
- "conclusion": depot_scheduled_runs.GATE_CONCLUSIONS[workflow["status"]],
+ "conclusion": depot_backend_runs.GATE_CONCLUSIONS[workflow["status"]],
"head_sha": context["sha"],
"head_branch": "master",
"repository": {"full_name": context["repo"]},
@@ -565,33 +566,76 @@ def parse_depot_run(shown: DepotShownWorkflow) -> WorkflowRun | None:
return replace(run, provider="depot", end=max(run.end, finished))
-def collect_depot_runs(repo: str, since: datetime) -> Collection:
- runs: list[WorkflowRun] = []
- complete = True
- created_floor = since - timedelta(days=1)
- listed = depot_scheduled_runs.scheduled_workflows(sorted(depot_scheduled_runs.ENDED), 200, repo=repo)
+# How far behind `since` a listing walks. A run created before this bound is not listed, so a push
+# run created more than 3 hours before `since` that finishes after it gets no trace. Across 1,000
+# Backend CI master push runs on GitHub Actions from 2026-10-12 to 2026-10-15, the slowest went
+# from creation to completion in 2,264 seconds. The hourly listing keeps the one-day slack the
+# GitHub scan uses. The Depot CLI lists at most 200 workflows, and a master push burst can exceed
+# that inside a long window, which marks every tick incomplete, so the push bound stays short.
+DEPOT_LISTING_SLACK = {"push": timedelta(hours=3), "schedule": timedelta(days=1)}
+
+
+def _depot_workflows_since(
+ repo: str, trigger: str, created_floor: datetime
+) -> tuple[list[depot_backend_runs.ListedWorkflow], bool]:
+ """The workflows created since the floor, and whether the listing reached the floor at all."""
+ kept: list[depot_backend_runs.ListedWorkflow] = []
+ listed = depot_backend_runs.master_workflows(
+ sorted(depot_backend_runs.ENDED), depot_backend_runs.MAX_LISTED, repo=repo, trigger=trigger
+ )
for workflow in listed:
created = parse_iso_utc(workflow["created_at"])
if created is not None and created < created_floor:
- break
+ return kept, True
+ kept.append(workflow)
+ # The CLI caps a listing, so a window that fills it may continue past what was listed.
+ return kept, len(listed) < depot_backend_runs.MAX_LISTED
+
+
+def _read_depot_run(workflow: depot_backend_runs.ListedWorkflow, since: datetime) -> WorkflowRun | None:
+ shown = cast(
+ DepotShownWorkflow,
+ json.loads(depot_backend_runs.depot("workflow", "show", workflow["workflow_id"], "--output", "json")),
+ )
+ if not depot_backend_runs.ran_on_master(cast(depot_backend_runs.ShownWorkflow, shown)):
+ return None
+ finished = parse_iso_utc(shown["workflow"]["finished_at"])
+ if finished is None:
+ raise ValueError("Completed Depot workflow has no finish timestamp")
+ if finished < since:
+ return None
+ run = parse_depot_run(shown)
+ if run is None:
+ raise ValueError("Completed Depot workflow has no start timestamp")
+ return run
+
+
+def collect_depot_runs(repo: str, since: datetime) -> Collection:
+ # Each listing is newest first, so the floor ends one trigger's walk without hiding the other's.
+ listed: list[depot_backend_runs.ListedWorkflow] = []
+ complete = True
+ for trigger, slack in DEPOT_LISTING_SLACK.items():
try:
- shown = cast(
- DepotShownWorkflow,
- json.loads(depot_scheduled_runs.depot("workflow", "show", workflow["workflow_id"], "--output", "json")),
- )
- finished = parse_iso_utc(shown["workflow"]["finished_at"])
- if finished is None:
- raise ValueError("Completed Depot workflow has no finish timestamp")
- if finished < since:
- continue
- run = parse_depot_run(shown)
- if run is None:
- raise ValueError("Completed Depot workflow has no start timestamp")
- runs.append(run)
+ workflows, reached_floor = _depot_workflows_since(repo, trigger, since - slack)
except Exception:
- logger.exception("could not read Depot workflow %s", workflow["workflow_id"])
+ # One unreadable trigger holds the watermark; the other's runs still get their traces.
+ logger.exception("could not list Depot %s workflows", trigger)
complete = False
- return Collection(runs=tuple(runs), complete=complete)
+ continue
+ listed += workflows
+ complete = complete and reached_floor
+
+ def read(workflow: depot_backend_runs.ListedWorkflow) -> tuple[WorkflowRun | None, bool]:
+ try:
+ return _read_depot_run(workflow, since), True
+ except Exception:
+ logger.exception("could not read Depot workflow %s", workflow["workflow_id"])
+ return None, False
+
+ with ThreadPoolExecutor(max_workers=depot_backend_runs.PARALLEL_CLI_CALLS) as pool:
+ results = list(pool.map(read, listed))
+ runs = tuple(run for run, _ in results if run is not None)
+ return Collection(runs=runs, complete=complete and all(ok for _, ok in results))
# ---------- OTLP export ----------
diff --git a/.github/scripts/test_depot_scheduled_runs.py b/.github/scripts/test_depot_backend_runs.py
similarity index 63%
rename from .github/scripts/test_depot_scheduled_runs.py
rename to .github/scripts/test_depot_backend_runs.py
index 594e0b02d4b4..62ca2d800245 100644
--- a/.github/scripts/test_depot_scheduled_runs.py
+++ b/.github/scripts/test_depot_backend_runs.py
@@ -7,7 +7,9 @@ from typing import Any
import pytest
import ci_backend_relay
-import depot_scheduled_runs as script
+import depot_backend_runs as script
+
+SCHEDULED_RUN = {"trigger": "schedule", "ref": ""}
@pytest.mark.parametrize(
@@ -30,7 +32,7 @@ def test_gate_run_reports_the_gate_verdict(
jobs: list[dict[str, Any]] = [{"job_key": "ci-backend.yml:report-test-timings", "status": "failed"}]
if gate_status:
jobs.append({"job_key": script.GATE_JOB_KEY, "status": gate_status, "finished_at": "2026-10-05T13:00:00Z"})
- shown = {"org_id": "org", "jobs": jobs}
+ shown = {"org_id": "org", "run": SCHEDULED_RUN, "jobs": jobs}
monkeypatch.setattr(script, "depot", lambda *args: json.dumps(shown))
listed = {
"workflow_id": "wf",
@@ -51,6 +53,49 @@ def test_names_the_workflow_and_gate_job_the_relay_reads() -> None:
assert script.GATE_JOB_KEY == ci_backend_relay.GATE_JOB_KEY
+ "run,kept",
+ [
+ ({"trigger": "push", "ref": "refs/heads/master"}, 1),
+ ({"trigger": "push", "ref": "refs/heads/feature"}, 0),
+ (SCHEDULED_RUN, 1),
+ ({}, 0),
+ ],
+ ids=["master", "branch", "schedule", "no-ref"],
+)
+def test_gate_runs_drop_runs_from_other_branches(
+ monkeypatch: pytest.MonkeyPatch, run: dict[str, str], kept: int
+) -> None:
+ def depot_response(*args: str) -> str:
+ if args[:2] == ("workflow", "list"):
+ return json.dumps(
+ [
+ {
+ "workflow_id": "wf",
+ "run_id": "run",
+ "sha": "abc",
+ "status": "finished",
+ "created_at": "2026-10-05T12:23:00Z",
+ }
+ ]
+ )
+ return json.dumps(
+ {
+ "org_id": "org",
+ "run": run,
+ "jobs": [{"job_key": script.GATE_JOB_KEY, "status": "finished"}],
+ }
+ )
+
+ monkeypatch.setattr(script, "depot", depot_response)
+
+ if kept:
+ assert len(script.gate_runs("push", 40)) == 1
+ else:
+ with pytest.raises(ValueError, match="No settled Backend CI verdict"):
+ script.gate_runs("push", 40)
+
+
def test_retries_a_workflow_listing_timeout_once(monkeypatch: pytest.MonkeyPatch) -> None:
calls = 0
@@ -63,7 +108,7 @@ def test_retries_a_workflow_listing_timeout_once(monkeypatch: pytest.MonkeyPatch
monkeypatch.setattr(script, "depot", depot_response)
- assert script.scheduled_workflows(["finished"], 5) == []
+ assert script.master_workflows(["finished"], 5, trigger="schedule") == []
assert calls == 2
@@ -84,15 +129,17 @@ def test_gate_window_requires_a_settled_verdict(monkeypatch: pytest.MonkeyPatch,
if status
else []
)
- return json.dumps({"org_id": "org", "jobs": [{"job_key": script.GATE_JOB_KEY, "status": status}]})
+ return json.dumps(
+ {"org_id": "org", "run": SCHEDULED_RUN, "jobs": [{"job_key": script.GATE_JOB_KEY, "status": status}]}
+ )
monkeypatch.setattr(script, "depot", depot_response)
if status in ("finished", "failed"):
- assert script.gate_runs()[0]["conclusion"] == script.GATE_CONCLUSIONS[status]
+ assert script.gate_runs("schedule", 12)[0]["conclusion"] == script.GATE_CONCLUSIONS[status]
else:
with pytest.raises(ValueError, match="No settled Backend CI verdict"):
- script.gate_runs()
+ script.gate_runs("schedule", 12)
def test_gate_window_keeps_in_progress_runs_alongside_a_settled_verdict(monkeypatch: pytest.MonkeyPatch) -> None:
@@ -110,11 +157,43 @@ def test_gate_window_keeps_in_progress_runs_alongside_a_settled_verdict(monkeypa
for status in ("finished", "running")
]
)
- return json.dumps({"org_id": "org", "jobs": [{"job_key": script.GATE_JOB_KEY, "status": args[2]}]})
+ return json.dumps(
+ {"org_id": "org", "run": SCHEDULED_RUN, "jobs": [{"job_key": script.GATE_JOB_KEY, "status": args[2]}]}
+ )
monkeypatch.setattr(script, "depot", depot_response)
- assert [run["status"] for run in script.gate_runs()] == ["completed", "in_progress"]
+ assert [run["status"] for run in script.gate_runs("schedule", 12)] == ["completed", "in_progress"]
+
+
+ "ref,found", [("refs/heads/master", ["run-master"]), ("refs/heads/feature", [])], ids=["master", "branch"]
+)
+def test_find_trusts_only_push_runs_on_master(monkeypatch: pytest.MonkeyPatch, ref: str, found: list[str]) -> None:
+ def depot_response(*args: str, **kwargs: object) -> str:
+ if args[:2] == ("workflow", "list"):
+ return json.dumps(
+ [
+ {
+ "workflow_id": "wf",
+ "run_id": "run-master",
+ "sha": "abc",
+ "status": "finished",
+ "created_at": "2099-01-01T00:00:00Z",
+ }
+ ]
+ )
+ if args[:2] == ("workflow", "show"):
+ return json.dumps({"org_id": "org", "run": {"trigger": "push", "ref": ref}, "jobs": []})
+ if args[:2] == ("artifacts", "list"):
+ return json.dumps({"artifacts": [{"artifact_id": "a", "name": "migrated-schema", "created_at": "x"}]})
+ raise AssertionError(args)
+
+ monkeypatch.setattr(script, "depot", depot_response)
+
+ workflows = script.find("migrated-schema", 1, 1, 2, trigger="push", statuses=["finished"])
+
+ assert [workflow["run_id"] for workflow in workflows] == found
def test_download_keeps_the_newest_artifact_per_name() -> None:
diff --git a/.github/scripts/test_report_workflow_run_traces.py b/.github/scripts/test_report_workflow_run_traces.py
index 1e4bd44ec236..f4535cc75d90 100644
--- a/.github/scripts/test_report_workflow_run_traces.py
+++ b/.github/scripts/test_report_workflow_run_traces.py
@@ -444,26 +444,30 @@ class TestDepotTraces:
}
],
}
- monkeypatch.setattr(
- reporter.depot_scheduled_runs,
- "scheduled_workflows",
- lambda *args, **kwargs: [
+ listed_triggers: list[str] = []
+
+ def list_workflows(*args: object, **kwargs: object) -> list[dict[str, str]]:
+ listed_triggers.append(str(kwargs["trigger"]))
+ # Newest first, as the CLI lists them; the old one must end this trigger's walk only.
+ return [
{"workflow_id": "wf", "created_at": _iso(0)},
- {"workflow_id": "old", "created_at": _iso(-100)},
- ],
- )
+ {"workflow_id": "old", "created_at": _iso(-100000)},
+ ]
+
+ monkeypatch.setattr(reporter.depot_backend_runs, "master_workflows", list_workflows)
def depot_response(*args: str) -> str:
if args[2] == "old":
return json.dumps({**shown, "workflow": {**shown["workflow"], "finished_at": _iso(-1)}})
return json.dumps(shown)
- monkeypatch.setattr(reporter.depot_scheduled_runs, "depot", depot_response)
+ monkeypatch.setattr(reporter.depot_backend_runs, "depot", depot_response)
collection = reporter.collect_depot_runs("PostHog/posthog", RUN_START)
assert collection.complete
- assert len(collection.runs) == 1
+ assert sorted(listed_triggers) == ["push", "schedule"]
+ assert len(collection.runs) == 2
run = collection.runs[0]
assert (run.id, run.attempt, run.provider, run.conclusion) == ("depot:run", 2, "depot", conclusion)
assert run.path == ".depot/workflows/ci-backend.yml"
diff --git a/.github/workflows/ci-alerts-devex.yml b/.github/workflows/ci-alerts-devex.yml
index f85cfd45d10f..d1c65a6fb451 100644
--- a/.github/workflows/ci-alerts-devex.yml
+++ b/.github/workflows/ci-alerts-devex.yml
@@ -10,7 +10,7 @@ name: Master CI Alerts
# A workflow is read as one lane per trigger event, each with its own streak and thresholds.
# Backend CI has two: master push (the per-commit checks) and the hourly scheduled run (the test
# matrices). Without the second lane a broken matrix never pages, because the push lane it shares
-# a workflow with stays green.
+# a workflow with stays green. Both Backend CI lanes run on Depot CI and are read from there.
#
# The script owns the whole flow: it recomputes master health from the GitHub
# API every tick and reconciles a single Slack incident (Slack is the source of
@@ -18,12 +18,13 @@ name: Master CI Alerts
# state to race or lose). See .github/scripts/ci-alerts-devex.js.
on:
- # Reconcile ~a minute after master CI finishes; GitHub throttles the cron below to ~hourly under
- # load. A reconcile reads all gating workflows anyway, so one hook on Backend CI (the long-pole on
- # ~every push) suffices.
+ # Reconcile soon after master CI finishes; GitHub throttles the cron below to ~hourly under load.
+ # A reconcile reads all gating workflows anyway, so one hook on the long pole suffices. Backend CI
+ # runs on Depot CI and has no GitHub run to hook, so the hook is on Security, the slowest GitHub
+ # workflow that runs on every master push.
# branches:[master] skips PR completions; cron stays a backstop.
workflow_run:
- workflows: ['Backend CI']
+ workflows: ['Security']
types: [completed]
branches: [master]
schedule:
@@ -66,10 +67,10 @@ env:
# Frontend CI is split the same way: jest runs hourly, while typecheck, format and bundle size
# run on every push. For Node.js, Dagster, Python and MCP the whole suite is on the cron, so
# their push lane only proves the run dispatched and the scheduled lane carries the coverage.
- SCHEDULED_GATING_WORKFLOWS: 'ci-frontend.yml,ci-nodejs.yml,ci-dagster.yml,ci-python.yml,ci-mcp.yml'
- # Backend CI's hourly run is on Depot CI (.depot/workflows/ci-backend.yml), so GitHub has no
- # runs for that lane. The reconcile job writes its runs to DEPOT_SCHEDULED_RUNS_FILE first.
- DEPOT_SCHEDULED_GATING_WORKFLOW: 'ci-backend.yml'
+ SCHEDULED_GATING_WORKFLOWS: 'ci-backend.yml,ci-frontend.yml,ci-nodejs.yml,ci-dagster.yml,ci-python.yml,ci-mcp.yml'
+ # Workflows that run on Depot CI, so GitHub has no runs for their lanes. The reconcile job
+ # writes each of their lanes to DEPOT_RUNS_DIR first, as <workflow file>-<event>.json.
+ DEPOT_WORKFLOWS: 'ci-backend.yml'
# A scheduled lane produces one run an hour, so it needs its own arms: the push streak of 5
# would take 5 hours to trip, while the push wall-clock arm of 60 minutes pages on a single
# flaky run held for one tick. Two red ticks in a row, or red across two ticks, is the honest
@@ -80,11 +81,7 @@ env:
jobs:
check-master:
- # Only reconcile on the master run completions the alerter reads
- # (branches:[master] already scopes the trigger to master).
- if: >-
- github.event_name != 'workflow_run' ||
- github.event.workflow_run.event == 'push'
+ if: github.event_name != 'workflow_run' || github.event.workflow_run.event == 'push'
runs-on: ubuntu-24.04
timeout-minutes: 5
steps:
@@ -93,7 +90,7 @@ jobs:
persist-credentials: false
sparse-checkout: |
.github/scripts/ci-alerts-devex.js
- .github/scripts/depot_scheduled_runs.py
+ .github/scripts/depot_backend_runs.py
sparse-checkout-cone-mode: false
# Both Depot steps are capped, so a slow Depot API cannot use up the job's
@@ -102,16 +99,23 @@ jobs:
continue-on-error: true
timeout-minutes: 1
- # A failed read leaves no file, and the script then treats the lane as unreadable.
- - name: Read the hourly Backend CI runs from Depot CI
+ # A failed read leaves no file, and the script then treats that lane as unreadable.
+ # A merge-queue burst can start a dozen master push runs inside one run's duration, so
+ # the push window is wider than the hourly one.
+ - name: Read the Backend CI lanes from Depot CI
id: depot-runs
continue-on-error: true
- timeout-minutes: 1
+ timeout-minutes: 2
env:
DEPOT_TOKEN: ${{ secrets.DEPOT_TOKEN }}
+ RUNS_DIR: ${{ runner.temp }}/depot-runs
run: |
- python3 .github/scripts/depot_scheduled_runs.py gate-runs > "$RUNNER_TEMP/runs.json"
- mv "$RUNNER_TEMP/runs.json" "$RUNNER_TEMP/depot-backend-scheduled-runs.json"
+ mkdir -p "$RUNS_DIR"
+ # Each lane is read on its own, so one unreadable lane does not hide the other.
+ status=0
+ python3 .github/scripts/depot_backend_runs.py gate-runs --trigger push --limit 40 --out "$RUNS_DIR/ci-backend.yml-push.json" || status=1
+ python3 .github/scripts/depot_backend_runs.py gate-runs --trigger schedule --limit 12 --out "$RUNS_DIR/ci-backend.yml-schedule.json" || status=1
+ exit "$status"
# Ticks list runs for every gating workflow (dozens of calls at worst)
# exactly when master push volume peaks, so read through the posthog-tests App
@@ -136,7 +140,7 @@ jobs:
# variable rather than a secret, because this repo sits two under GitHub's cap of
# 100 secrets; the script masks the value so a public log cannot leak it.
DIAGNOSIS_WEBHOOK_URL: ${{ vars.MASTER_RED_DIAGNOSIS_WEBHOOK_URL }}
- DEPOT_SCHEDULED_RUNS_FILE: ${{ runner.temp }}/depot-backend-scheduled-runs.json
+ DEPOT_RUNS_DIR: ${{ runner.temp }}/depot-runs
with:
github-token: ${{ steps.app-token.outputs.token || github.token }}
script: |
@@ -147,5 +151,5 @@ jobs:
- name: Report a failed Depot read
if: always() && steps.depot-runs.outcome == 'failure'
run: |
- echo "::error::The scheduled Backend CI lane could not be read from Depot CI"
+ echo "::error::A Backend CI lane could not be read from Depot CI"
exit 1
diff --git a/.github/workflows/ci-backend-schema-mirror.yml b/.github/workflows/ci-backend-schema-mirror.yml
new file mode 100644
index 000000000000..503a47fc8aed
--- /dev/null
+++ b/.github/workflows/ci-backend-schema-mirror.yml
@@ -0,0 +1,138 @@
+name: Backend schema mirror
+
+# Backend CI runs on Depot CI, which keeps its artifacts and its cache apart from GitHub
+# Actions. Its master run dumps the migrated Postgres schema. This workflow copies the newest
+# dump into a GitHub artifact, for `hogli db:download-schema` and the ClickHouse multinode
+# smoke, and into GitHub Actions cache, for jobs on GitHub-hosted runners and for fork pull
+# requests, which cannot read Depot Cache. A cron rather than a hook on the push: Depot cannot
+# dispatch a GitHub workflow without a token that writes to Actions, and a runner that waits
+# for the dump idles for the length of the migration replay.
+
+on:
+ schedule:
+ - cron: '*/10 * * * *'
+ workflow_dispatch:
+
+concurrency:
+ group: ${{ github.workflow }}
+ cancel-in-progress: false
+
+permissions:
+ contents: read
+ actions: read # the artifact and cache listings that say whether a dump is already mirrored
+
+jobs:
+ mirror:
+ name: Mirror the newest master schema dump
+ # Master only: a dispatch from another branch would save caches no master run can read.
+ if: github.repository == 'PostHog/posthog' && github.ref == 'refs/heads/master'
+ runs-on: ubuntu-24.04
+ timeout-minutes: 10
+ steps:
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ with:
+ persist-credentials: false
+ sparse-checkout: .github/scripts/depot_backend_runs.py
+ sparse-checkout-cone-mode: false
+
+ - uses: depot/setup-action@15c09a5f77a0840ad4bce955686522a257853461 # v1.7.1
+
+ - name: Find the newest Depot master run with a dump
+ id: source
+ env:
+ DEPOT_TOKEN: ${{ secrets.DEPOT_TOKEN }}
+ GH_TOKEN: ${{ github.token }}
+ run: |
+ # A failed listing must fail the tick; only an empty one is "nothing to mirror".
+ python3 .github/scripts/depot_backend_runs.py find --trigger push --status finished --status failed \
+ --prefix migrated-schema --max-age-days 2 > "$RUNNER_TEMP/source"
+ read -r run_id sha < "$RUNNER_TEMP/source" || true
+ if [ -z "${run_id:-}" ]; then
+ echo "::warning::No Depot master run with a schema dump in the last two days"
+ exit 0
+ fi
+ if ! [[ "$run_id" =~ ^[a-z0-9]{1,32}$ && "$sha" =~ ^[0-9a-f]{40}$ ]]; then
+ echo "::error::Unexpected run id or sha from the Depot listing"
+ exit 1
+ fi
+ # A marker artifact, uploaded last, records a dump that reached every destination.
+ # A cache key cannot serve as the record: the repo's LRU pool evicts it within minutes.
+ # Only a same-repo master run can have written the marker; any run can upload an artifact of that name.
+ mirrored=$(gh api "repos/$GITHUB_REPOSITORY/actions/artifacts?name=migrated-schema-mirrored-$sha&per_page=20" \
+ --jq '[.artifacts[] | select(.workflow_run.head_branch == "master" and .workflow_run.head_repository_id == .workflow_run.repository_id)] | length')
+ if [ "$mirrored" != "0" ]; then
+ echo "Dump of $sha is already mirrored"
+ exit 0
+ fi
+ echo "run_id=$run_id" >> "$GITHUB_OUTPUT"
+ echo "sha=$sha" >> "$GITHUB_OUTPUT"
+
+ - name: Download the dump from Depot
+ id: dump
+ if: steps.source.outputs.run_id != ''
+ env:
+ DEPOT_TOKEN: ${{ secrets.DEPOT_TOKEN }}
+ RUN_ID: ${{ steps.source.outputs.run_id }}
+ run: |
+ python3 .github/scripts/depot_backend_runs.py download "$RUN_ID" --pattern migrated-schema --dir .
+ # actions/cache keys an entry by its path too, so save the file where every consumer restores it.
+ mv migrated-schema/schema.sql.gz schema.sql.gz
+ gunzip -t schema.sql.gz
+ key=$(cat migrated-schema/schema-cache-key)
+ if [ -n "$key" ] && ! [[ "$key" =~ ^posthog-schema-mig-[A-Za-z0-9._-]+$ ]]; then
+ echo "::error::Unexpected migration-set cache key in the dump"
+ exit 1
+ fi
+ echo "migration_key=$key" >> "$GITHUB_OUTPUT"
+
+ - name: Upload migrated schema artifact
+ if: steps.source.outputs.run_id != ''
+ uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
+ with:
+ name: migrated-schema
+ path: schema.sql.gz
+ # 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 GitHub cache (master key)
+ if: steps.source.outputs.run_id != ''
+ uses: actions/cache/save@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3
+ with:
+ path: schema.sql.gz
+ key: posthog-schema-master-${{ steps.source.outputs.sha }}
+
+ - name: Save schema to GitHub cache (migration-set key)
+ if: steps.source.outputs.run_id != '' && steps.dump.outputs.migration_key != ''
+ uses: actions/cache/save@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3
+ with:
+ path: schema.sql.gz
+ key: ${{ steps.dump.outputs.migration_key }}
+
+ - name: Record the mirrored dump
+ id: record
+ if: steps.source.outputs.run_id != ''
+ env:
+ GH_TOKEN: ${{ github.token }}
+ SHA: ${{ steps.source.outputs.sha }}
+ MIGRATION_KEY: ${{ steps.dump.outputs.migration_key }}
+ run: |
+ # actions/cache/save only warns when a save fails, so a dump is recorded only once
+ # both entries exist. An unrecorded dump is retried on the next tick.
+ for key in "posthog-schema-master-$SHA" ${MIGRATION_KEY:+"$MIGRATION_KEY"}; do
+ saved=$(gh api "repos/$GITHUB_REPOSITORY/actions/caches?key=$key&ref=refs/heads/master" \
+ --jq "[.actions_caches[] | select(.key == \"$key\")] | length")
+ if [ "$saved" = "0" ]; then
+ echo "::warning::Cache entry $key is missing, so the next tick retries this dump"
+ exit 0
+ fi
+ done
+ echo "$SHA" > mirrored
+ echo "recorded=true" >> "$GITHUB_OUTPUT"
+
+ - uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
+ if: steps.record.outputs.recorded == 'true'
+ with:
+ name: migrated-schema-mirrored-${{ steps.source.outputs.sha }}
+ path: mirrored
+ retention-days: 7
diff --git a/.github/workflows/ci-backend-update-test-timing.yml b/.github/workflows/ci-backend-update-test-timing.yml
index 6f1fd22c2c7d..f3d68a9bf93d 100644
--- a/.github/workflows/ci-backend-update-test-timing.yml
+++ b/.github/workflows/ci-backend-update-test-timing.yml
@@ -82,7 +82,7 @@ jobs:
# Newest first: successful hourly runs on Depot CI that uploaded a full set of
# timing artifacts (>=38), up to N.
- run_ids=$(python3 .github/scripts/depot_scheduled_runs.py find \
+ run_ids=$(python3 .github/scripts/depot_backend_runs.py find --trigger schedule \
--prefix timing_data- --min-artifacts 38 --limit "$N" | cut -d' ' -f1)
primary=$(echo "$run_ids" | head -1)
@@ -175,7 +175,7 @@ jobs:
DAGSTER_RUN_ID: ${{ steps.find-dagster-run.outputs.run_id }}
run: |
# Backend runs live on Depot CI, Dagster runs on GitHub Actions.
- depot_download() { python3 .github/scripts/depot_scheduled_runs.py download "$@"; }
+ depot_download() { python3 .github/scripts/depot_backend_runs.py download "$@"; }
# Download backend timing artifacts. Use segment-specific patterns
# so we don't accidentally pull Dagster artifacts here when the same
@@ -445,11 +445,11 @@ jobs:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
path: depot-reader
- sparse-checkout: .github/scripts/depot_scheduled_runs.py
+ sparse-checkout: .github/scripts/depot_backend_runs.py
sparse-checkout-cone-mode: false
- name: Keep the Depot run reader
- run: cp depot-reader/.github/scripts/depot_scheduled_runs.py "$RUNNER_TEMP/depot_scheduled_runs.py"
+ run: cp depot-reader/.github/scripts/depot_backend_runs.py "$RUNNER_TEMP/depot_backend_runs.py"
- uses: depot/setup-action@15c09a5f77a0840ad4bce955686522a257853461 # v1.7.1
@@ -461,7 +461,7 @@ jobs:
# Only the hourly runs on Depot CI that take the events_json rows record. A
# successful one carries every shard's recording, because a shard that wrote
# none fails.
- read -r id sha < <(python3 "$RUNNER_TEMP/depot_scheduled_runs.py" find \
+ read -r id sha < <(python3 "$RUNNER_TEMP/depot_backend_runs.py" find --trigger schedule \
--prefix events-schema-record- --max-age-days 2) || true
if [ -n "${id:-}" ]; then
echo "Using run $id at $sha"
@@ -500,7 +500,7 @@ jobs:
env:
DEPOT_TOKEN: ${{ secrets.DEPOT_TOKEN }}
RUN_ID: ${{ steps.find-run.outputs.run_id }}
- run: python3 "$RUNNER_TEMP/depot_scheduled_runs.py" download "$RUN_ID" --pattern 'events-schema-record-*' --dir events-schema-records
+ run: python3 "$RUNNER_TEMP/depot_backend_runs.py" download "$RUN_ID" --pattern 'events-schema-record-*' --dir events-schema-records
- name: Build the manifest
if: steps.cached.outputs.cache-hit != 'true'
diff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.yml
index 4a8713239c73..6bffbd9c0949 100644
--- a/.github/workflows/ci-backend.yml
+++ b/.github/workflows/ci-backend.yml
@@ -4,11 +4,8 @@
# .github/workflows/ci-backend-update-test-timing.yml action
name: Backend CI
on:
- push:
- branches:
- - master
- # No schedule trigger: the hourly full-matrix master run is on Depot CI, from the schedule
- # trigger of .depot/workflows/ci-backend.yml.
+ # No push or schedule trigger: the master push and the hourly full-matrix master run are on
+ # Depot CI, from .depot/workflows/ci-backend.yml.
workflow_dispatch:
inputs:
clickhouseServerVersion:
@@ -1648,8 +1645,6 @@ jobs:
# over two of them: it is there to cancel a hang, not to cap how long the
# history takes.
timeout-minutes: 60
- outputs:
- mig_schema_key: ${{ steps.mig-schema-key.outputs.key }}
# The "Publish Migration risk check" step posts the check via the
# posthog-tests app token, which carries its own checks:write
# installation permission — so the check lands in that app's own
@@ -2182,65 +2177,6 @@ jobs:
exit 1
fi
- - name: Dump migrated schema
- if: github.event_name == 'push'
- run: |
- set -e
- set -o pipefail
- # Dump schema + django_migrations data so Django knows which migrations are applied
- # Run pg_dump inside container to ensure version match (host has pg_dump 16, container has 15)
- (docker compose -f docker-compose.dev.yml exec -T db pg_dump --schema-only --clean --if-exists -U posthog posthog && \
- docker compose -f docker-compose.dev.yml exec -T db pg_dump --data-only --table=django_migrations -U posthog posthog) | gzip > schema.sql.gz
- # Verify the dump is valid
- gunzip -t schema.sql.gz
-
- - name: Upload migrated schema artifact
- if: github.event_name == 'push'
- uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
- with:
- name: migrated-schema
- path: schema.sql.gz
- # 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.
- if: github.event_name == 'push'
- uses: actions/cache/save@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3
- with:
- path: schema.sql.gz
- key: posthog-schema-master-${{ github.sha }}
-
- - name: Compute migration-set schema key
- # Must match the merge-base computation in turbo-discover and the
- # master restore key above (inputs, hash, and key prefix).
- if: github.event_name == 'push'
- id: mig-schema-key
- run: |
- MIG_FILES=$(git ls-tree -r --format='%(objectname) %(path)' HEAD \
- | grep -E '/migrations/[^/]+\.py$|^[0-9a-f]+ uv\.lock$' \
- | grep -vE '/(clickhouse|async_migrations)/migrations/' \
- | LC_ALL=C sort) || true
- # Routing decides which app labels are in the dump, so these inputs belong in the key.
- DB_ROUTING=$(git ls-tree -r --format='%(objectname) %(path)' HEAD -- products/db_routing.yaml posthog/product_db_config.py posthog/product_db_router.py)
- PG_IMAGE=$(git show "HEAD:docker-compose.base.yml" 2>/dev/null \
- | grep -m1 -E '^[[:space:]]*image:[[:space:]]*postgres:' | tr -d '[:space:]')
- if [ -z "$MIG_FILES" ]; then
- echo "key=" >> $GITHUB_OUTPUT
- echo "::notice::no migration files matched — skipping migration-set schema save"
- else
- MIG_HASH=$(printf '%s\n%s\n%s' "$MIG_FILES" "$PG_IMAGE" "$DB_ROUTING" | sha256sum | cut -c1-40)
- echo "key=posthog-schema-mig-${SCHEMA_CACHE_EPOCH}-${MIG_HASH}" >> $GITHUB_OUTPUT
- fi
-
- - name: Save schema to Actions cache (migration-set key)
- if: github.event_name == 'push' && steps.mig-schema-key.outputs.key != ''
- uses: actions/cache/save@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3
- with:
- path: schema.sql.gz
- key: ${{ steps.mig-schema-key.outputs.key }}
-
- name: Check migrations
# Skip migration safety check on master push (no migration_files from path filter)
if: github.event_name != 'push'
@@ -2364,37 +2300,6 @@ jobs:
echo "Skipping CH migration section — script not present on this checkout"
fi
- mirror-schema-cache:
- needs: [check-migrations]
- # Fork PRs run without secrets, so they aren't authenticated to Depot Cache and
- # read only GitHub's own cache, where check-migrations' Depot-runner saves never land.
- # Mirror the dump there so fork PRs prime instead of migrating from scratch.
- if: github.event_name == 'push' && github.ref == 'refs/heads/master'
- name: Mirror schema cache to GitHub cache
- runs-on: ubuntu-24.04
- timeout-minutes: 5
- permissions:
- contents: read
- steps:
- - name: Download migrated schema artifact
- uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0
- with:
- name: migrated-schema
-
- - name: Save schema to GitHub cache (merge-base key)
- if: github.ref == 'refs/heads/master'
- uses: actions/cache/save@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3
- with:
- path: schema.sql.gz
- key: posthog-schema-master-${{ github.sha }}
-
- - name: Save schema to GitHub cache (migration-set key)
- if: github.ref == 'refs/heads/master' && needs.check-migrations.outputs.mig_schema_key != ''
- uses: actions/cache/save@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3
- with:
- path: schema.sql.gz
- key: ${{ needs.check-migrations.outputs.mig_schema_key }}
-
check-openapi-types:
needs: [changes]
if: (needs.changes.outputs.backend == 'true' || needs.changes.outputs.openapi_types == 'true')
diff --git a/.github/workflows/ci-clickhouse-multinode-migrations.yml b/.github/workflows/ci-clickhouse-multinode-migrations.yml
index ea39d2b32281..f70190799e16 100644
--- a/.github/workflows/ci-clickhouse-multinode-migrations.yml
+++ b/.github/workflows/ci-clickhouse-multinode-migrations.yml
@@ -28,7 +28,8 @@ permissions:
contents: read
# Pull the pinned hclexp image from ghcr for the live-schema convergence gate.
packages: read
- # Download the migrated-schema artifact produced by ci-backend.yml on master.
+ # Download the migrated-schema artifact that ci-backend-schema-mirror.yml copies from the
+ # Backend CI master run on Depot CI.
actions: read
jobs:
@@ -88,35 +89,25 @@ jobs:
env:
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, 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 master
- # pushes can succeed without producing the artifact, hence the scan.
+ # ci-backend-schema-mirror.yml uploads the newest post-migrate schema of the
+ # Depot master run as the migrated-schema artifact, held for the retention-days
+ # set on that upload step. 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.
+ # The repo-wide artifact list is newest first and spans the whole retention
+ # window, however many mirror ticks uploaded nothing. A pull request run from
+ # a fork can upload an artifact of the same name, and the fork's branch can be
+ # called master too, so only a run on this repository's own master counts.
# Any failure here degrades to the full-migrate fallback in the
# smoke script (PRIME_POSTGRES_FROM stays absent).
- RUN_IDS=$(gh api "repos/${GITHUB_REPOSITORY}/actions/workflows/ci-backend.yml/runs?branch=master&event=push&status=success&per_page=10" \
- --jq '.workflow_runs[].id' || true)
- ARTIFACT_ID=""
- for RUN_ID in $RUN_IDS; do
- ARTIFACT_ID=$(gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${RUN_ID}/artifacts?name=migrated-schema" \
- --jq '[.artifacts[] | select(.expired | not)][0].id // empty' || true)
- if [ -n "$ARTIFACT_ID" ]; then
- echo "using migrated-schema artifact ${ARTIFACT_ID} from master run ${RUN_ID}"
- break
- fi
- done
+ ARTIFACT_ID=$(gh api "repos/${GITHUB_REPOSITORY}/actions/artifacts?name=migrated-schema&per_page=100" \
+ --jq '[.artifacts[] | select((.expired | not) and .workflow_run.head_branch == "master" and .workflow_run.head_repository_id == .workflow_run.repository_id)][0].id // empty' || true)
if [ -z "$ARTIFACT_ID" ]; then
- echo "::warning::no migrated-schema artifact in recent successful master ci-backend runs; falling back to full migrate"
+ echo "::warning::no migrated-schema artifact from a master run; falling back to full migrate"
exit 0
fi
+ echo "using migrated-schema artifact ${ARTIFACT_ID}"
if ! { gh api "repos/${GITHUB_REPOSITORY}/actions/artifacts/${ARTIFACT_ID}/zip" > migrated-schema.zip \
&& unzip -o migrated-schema.zip schema.sql.gz \
&& gunzip -t schema.sql.gz; }; then
diff --git a/.github/workflows/ci-master-run-traces.yml b/.github/workflows/ci-master-run-traces.yml
index e4a5314deab2..e5614785e8f6 100644
--- a/.github/workflows/ci-master-run-traces.yml
+++ b/.github/workflows/ci-master-run-traces.yml
@@ -4,7 +4,7 @@ name: Master run traces
# a span per job beneath it, a span per step beneath those. Covers every workflow,
# including the ones with no telemetry of their own (Container Images CD, the
# container CD lane, the Rust image builds). Master pushes are scanned repo-wide;
-# Backend CI's scheduled runs are read from Depot. Depot exposes workflow and job
+# Backend CI's push and scheduled runs are read from Depot. Depot exposes workflow and job
# timestamps, but not step or job-queue timestamps, so those traces stop at jobs.
#
# Complements .github/scripts/report_test_timings.py, which emits per-test traces
@@ -58,7 +58,7 @@ jobs:
persist-credentials: false
sparse-checkout: |
.github/scripts/report_workflow_run_traces.py
- .github/scripts/depot_scheduled_runs.py
+ .github/scripts/depot_backend_runs.py
.github/actions/setup-uv
sparse-checkout-cone-mode: false
diff --git a/tools/hogli-commands/hogli_commands/db_schema.py b/tools/hogli-commands/hogli_commands/db_schema.py
index 52164b2da745..3245f95b1c98 100644
--- a/tools/hogli-commands/hogli_commands/db_schema.py
+++ b/tools/hogli-commands/hogli_commands/db_schema.py
@@ -283,6 +283,13 @@ def _artifact_from_api(raw: Mapping[str, object]) -> SchemaArtifact | None:
if not isinstance(workflow_run, Mapping):
return None
try:
+ # A pull request run from a fork uploads its artifacts to this repository, and the
+ # fork's branch can also be named master. Only a run on this repository's own
+ # branch can supply the schema that is loaded into the database.
+ if _require_type(workflow_run.get("head_repository_id"), int) != _require_type(
+ workflow_run.get("repository_id"), int
+ ):
+ return None
return SchemaArtifact(
id=_require_type(raw.get("id"), int),
name=_require_type(raw.get("name"), str),
diff --git a/tools/hogli-commands/hogli_commands/tests/test_db_schema.py b/tools/hogli-commands/hogli_commands/tests/test_db_schema.py
index 72f9aef1eb7b..fbbd1355537a 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_db_schema.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_db_schema.py
@@ -116,7 +116,7 @@ class _FakeArtifactPagesSession:
)
-def _raw_artifact(artifact_id: int, head_branch: str) -> dict[str, Any]:
+def _raw_artifact(artifact_id: int, head_branch: str, *, head_repository_id: int | None = 1) -> dict[str, Any]:
return {
"id": artifact_id,
"name": db_schema.SCHEMA_ARTIFACT_NAME,
@@ -124,10 +124,26 @@ def _raw_artifact(artifact_id: int, head_branch: str) -> dict[str, Any]:
"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},
+ "workflow_run": {
+ "head_sha": "sha",
+ "head_branch": head_branch,
+ "repository_id": 1,
+ "head_repository_id": head_repository_id,
+ },
}
[email protected]("head_repository_id", [2, None])
+def test_find_skips_artifacts_from_another_repository(head_repository_id: int | None) -> None:
+ session = _FakeArtifactPagesSession(
+ [[_raw_artifact(2, "master", head_repository_id=head_repository_id), _raw_artifact(1, "master")]]
+ )
+
+ artifact = db_schema.find_newest_compatible_artifact(token="t", session=session, base_branch="master") # type: ignore[arg-type]
+
+ assert artifact is not None and artifact.id == 1
+
+
def test_find_stops_at_first_page_with_compatible_candidate() -> None:
session = _FakeArtifactPagesSession([[_raw_artifact(1, "master")], [_raw_artifact(2, "master")]])
diff --git a/tools/workflow-plan/tests/workflows.test.ts b/tools/workflow-plan/tests/workflows.test.ts
index eb0a959b39d4..e04d34358e1f 100644
--- a/tools/workflow-plan/tests/workflows.test.ts
+++ b/tools/workflow-plan/tests/workflows.test.ts
@@ -182,7 +182,8 @@ const EXPECTATIONS: Expectation[] = [
}
)
),
- backend(
+ // The master push runs on Depot CI: the per-commit checks and the schema dump, no matrices.
+ depotBackend(
{ name: 'master push', github: push() },
{
runs: [
@@ -190,12 +191,14 @@ const EXPECTATIONS: Expectation[] = [
'repo-checks',
'sdk-major-guard',
'check-migrations',
- 'mirror-schema-cache',
+ 'check-openapi-types',
'django_tests',
],
skipped: [
- 'dynamic-ci-filter',
+ 'cancel-superseded-runs',
'detect-snapshot-mode',
+ 'turbo-discover',
+ 'prime-schema-cache',
'turbo-tests',
'django',
'get_clickhouse_versions',