:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(ci): shadow merge-commit change detection (#89454)
Raúl Negrón-Oterofb839fe24774
diff --git a/.depot/actions/paths-filter/README.md b/.depot/actions/paths-filter/README.mdindex 9ff00783cfa6..cb2b746d89a6 100644--- a/.depot/actions/paths-filter/README.md+++ b/.depot/actions/paths-filter/README.md@@ -65,6 +65,22 @@ changed:- added|modified: ['src/**', '!src/vendor/**']```+## Shadow comparison (opt-in)++Set `PATHS_FILTER_SHADOW_POSTHOG_TOKEN` on a step to have that run compare the API's+changed-file list against the same list derived from the pull request's merge commit,+and send the verdict to PostHog. The comparison never changes what the filter answers.++```yaml+- uses: ./.github/actions/paths-filter+ env:+ PATHS_FILTER_SHADOW_POSTHOG_TOKEN: ${{ secrets.POSTHOG_DEVEX_PROJECT_API_TOKEN }}+```++Without the variable the action does no extra work. Set it in one workflow that runs on+every pull request; that keeps the merge-ref fetch off the critical path of the other+gating jobs. This is temporary, and goes away with the decision it exists to inform.+## Rebuilding after source changesThe action runs the committed `dist/index.js` bundle. After editing anything under `src/`,diff --git a/.depot/actions/paths-filter/__tests__/shadow.test.ts b/.depot/actions/paths-filter/__tests__/shadow.test.tsnew file mode 100644index 000000000000..257a62d706fe--- /dev/null+++ b/.depot/actions/paths-filter/__tests__/shadow.test.ts@@ -0,0 +1,101 @@+import {PullRequest} from '@octokit/webhooks-types'++import {ChangeStatus} from '../src/file'+import {compareWithMergeCommit} from '../src/shadow'++const cp = jest.requireMock('child_process') as {execFile: jest.Mock}++jest.mock('child_process', () => ({execFile: jest.fn()}))+jest.mock('@actions/core', () => ({info: jest.fn(), startGroup: jest.fn(), endGroup: jest.fn()}))++const HEAD = 'a'.repeat(40)+const OTHER_SHA = 'b'.repeat(40)+const GIT_DIR = '/tmp/runner/paths-filter-shadow.git'+const PAST_ANY_BUDGET_MS = 120000++type ExecFileArgs = [+ string,+ string[],+ {signal: AbortSignal},+ (error: Error | null, stdout: string, stderr: string) => void+]++const pullRequest = {number: 42, head: {sha: HEAD}} as PullRequest++function stubGit(...stdouts: string[]): void {+ for (const stdout of stdouts) {+ cp.execFile.mockImplementationOnce((...args: ExecFileArgs) => args[3](null, stdout, ''))+ }+}++function argvOf(call: number): string[] {+ return cp.execFile.mock.calls[call][1] as string[]+}++describe('shadow merge-commit comparison', () => {+ beforeEach(() => {+ process.env.RUNNER_TEMP = '/tmp/runner'+ process.env.GITHUB_SERVER_URL = 'https://github.com'+ process.env.GITHUB_REPOSITORY = 'PostHog/posthog'+ cp.execFile.mockReset()+ })++ // A git call that forgets the scratch dir runs against the job workspace, where a+ // --depth or --filter fetch drops the schema cache of every later step in the job.+ test('never runs git against the job workspace', async () => {+ stubGit('', '', HEAD, 'a.ts\0')++ const result = await compareWithMergeCommit([{filename: 'a.ts', status: ChangeStatus.Modified}], pullRequest)++ expect(result.verdict).toBe('match')+ expect(argvOf(0)).toContain(GIT_DIR)+ for (let call = 1; call < cp.execFile.mock.calls.length; call++) {+ expect(argvOf(call).slice(0, 2)).toEqual(['--git-dir', GIT_DIR])+ }+ })++ // Losing this guard scores a merge ref from an earlier push as this pull request's+ // changes, which fills the measurement with mismatches that mean nothing.+ test('refuses a stale merge ref instead of comparing against it', async () => {+ stubGit('', '', OTHER_SHA)++ const result = await compareWithMergeCommit([{filename: 'a.ts', status: ChangeStatus.Modified}], pullRequest)++ expect(result.verdict).toBe('unavailable')+ expect(result.reason).toBe('stale-merge-ref')+ })++ // Losing --no-renames reports one path where the API path reports two, so every+ // rename reads as a mismatch.+ test('matches a rename that the API reported as two entries', async () => {+ stubGit('', '', HEAD, 'old.ts\0new.ts\0')++ const result = await compareWithMergeCommit(+ [+ {filename: 'new.ts', status: ChangeStatus.Added},+ {filename: 'old.ts', status: ChangeStatus.Deleted}+ ],+ pullRequest+ )++ expect(result.verdict).toBe('match')+ expect(cp.execFile.mock.calls.map(c => c[1])).toContainEqual(expect.arrayContaining(['--no-renames']))+ })++ // An exec with no handle on the child leaves the fetch running after the budget gives+ // up, and the action's process stays open until git exits.+ test('stops git when the budget expires', async () => {+ cp.execFile.mockImplementation(() => undefined)+ jest.useFakeTimers()++ const pending = compareWithMergeCommit([], pullRequest)+ await jest.advanceTimersByTimeAsync(PAST_ANY_BUDGET_MS)+ const result = await pending++ expect(result.verdict).toBe('unavailable')+ expect(result.reason).toBe('budget-exceeded')+ const [, , options] = cp.execFile.mock.calls[0] as ExecFileArgs+ expect(options.signal.aborted).toBe(true)+ jest.useRealTimers()+ })+})diff --git a/.depot/actions/paths-filter/dist/index.js b/.depot/actions/paths-filter/dist/index.jsindex 00836501b899..1115cb186a4f 100644--- a/.depot/actions/paths-filter/dist/index.js+++ b/.depot/actions/paths-filter/dist/index.js@@ -42687,6 +42687,7 @@ const github = __importStar(__nccwpck_require__(3228));const filter_1 = __nccwpck_require__(9037);const file_1 = __nccwpck_require__(3765);const git = __importStar(__nccwpck_require__(1243));+const shadow = __importStar(__nccwpck_require__(5763));const shell_escape_1 = __nccwpck_require__(6880);const csv_escape_1 = __nccwpck_require__(6146);async function run() {@@ -42753,7 +42754,9 @@ async function getChangedFiles(token, base, ref, initialFetchDepth) {}const pr = github.context.payload.pull_request;if (token) {- return await getChangedFilesFromApi(token, pr);+ const apiFiles = await getChangedFilesFromApi(token, pr);+ await shadow.report(apiFiles, pr);+ return apiFiles;}if (github.context.eventName === 'pull_request_target') {// pull_request_target is executed in context of base branch and GITHUB_SHA points to last commit in base branch@@ -42926,6 +42929,326 @@ function getErrorMessage(error) {run();+/***/ }),++/***/ 5763:+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {++"use strict";++var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {+ if (k2 === undefined) k2 = k;+ var desc = Object.getOwnPropertyDescriptor(m, k);+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {+ desc = { enumerable: true, get: function() { return m[k]; } };+ }+ Object.defineProperty(o, k2, desc);+}) : (function(o, m, k, k2) {+ if (k2 === undefined) k2 = k;+ o[k2] = m[k];+}));+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {+ Object.defineProperty(o, "default", { enumerable: true, value: v });+}) : function(o, v) {+ o["default"] = v;+});+var __importStar = (this && this.__importStar) || (function () {+ var ownKeys = function(o) {+ ownKeys = Object.getOwnPropertyNames || function (o) {+ var ar = [];+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;+ return ar;+ };+ return ownKeys(o);+ };+ return function (mod) {+ if (mod && mod.__esModule) return mod;+ var result = {};+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);+ __setModuleDefault(result, mod);+ return result;+ };+})();+Object.defineProperty(exports, "__esModule", ({ value: true }));+exports.compareWithMergeCommit = compareWithMergeCommit;+exports.report = report;+const child_process_1 = __nccwpck_require__(5317);+const os = __importStar(__nccwpck_require__(857));+const path = __importStar(__nccwpck_require__(6928));+const core = __importStar(__nccwpck_require__(7484));+// Compares the API's changed-file list against the same list derived locally from+// the pull request's merge commit, and reports disagreement without acting on it.+// The API result stays authoritative, so a wrong local answer can only produce a+// log line. Removing the API call later is only safe once this has run quiet+// across the shapes no offline sample can reach: very large diffs, and ones GitHub+// has not finished computing a merge ref for.+//+// Detecting changes from `base.sha..HEAD` instead reports every commit the branch+// picked up when the base was merged into it as the pull request's own work, which+// is wrong by thousands of files on a branch that has taken master in. The merge+// commit's first parent is the base GitHub actually merged against, so+// `HEAD^1..HEAD` is the pull request's own changes and matches the API.+const MERGE_REF_FETCH_DEPTH = 2;+const POSTHOG_HOST = 'https://us.i.posthog.com';+const EVENT_NAME = 'paths_filter_shadow_compared';+// A change-detection job is on the critical path of every workflow, so the comparison+// and the capture that follows it share one wall-clock budget, and give up rather than+// holding the job to its timeout-minutes. The git-level low-speed settings cover a+// stalled transfer; the budget covers everything else.+const BUDGET_MS = 20000;+const CAPTURE_FLOOR_MS = 500;+const LIST_CAP = 50;+// A queue branch carries the cumulative batch diff, so the path list can be far larger+// than a human pull request's. execFile's 1 MB default would fail those as a diff error,+// which drops the population the comparison most needs to measure.+const MAX_GIT_OUTPUT_BYTES = 64 * 1024 * 1024;+const DETAIL_CAP = 200;+// The API caps pulls/{n}/files at this many entries and says nothing when it truncates.+const API_FILE_CAP = 3000;+class Unavailable extends Error {+ constructor(reason, detail) {+ super(`${reason}: ${detail}`);+ this.reason = reason;+ this.detail = detail;+ }+}+// Every git call that reads or writes history names the scratch repository. `--depth`+// and `--filter` rewrite `.git/shallow` and the promisor config of whatever repository+// they run in, and steps later in the same job read history from the workspace checkout:+// ci-dagster and ci-e2e-playwright resolve `git merge-base HEAD^2 origin/<base>` after+// this action returns, and an empty merge base there silently drops their schema cache.+async function git(gitDir, args, signal) {+ return run(['--git-dir', gitDir, ...args], signal);+}+// The signal is what makes the wall-clock budget real. `@actions/exec` gives no handle+// on the child process, so a fetch the budget gave up on keeps running and holds the+// action's process open until it finishes, past the budget it was supposed to obey.+//+// stdout is returned raw. A caller that reads a path list must not trim it, because a+// tracked path can begin with a space, and that path sorts first in the -z output.+async function run(args, signal) {+ return new Promise(resolve => {+ (0, child_process_1.execFile)('git', args, { signal, maxBuffer: MAX_GIT_OUTPUT_BYTES }, (error, stdout, stderr) => {+ resolve({ code: error ? 1 : 0, out: stdout, err: stderr.trim() });+ });+ });+}+function firstLine(stderr) {+ return stderr.slice(0, DETAIL_CAP).split('\n')[0] || 'no stderr';+}+function messageOf(error) {+ return error instanceof Error ? error.message : String(error);+}+async function scratchRepo(signal) {+ const gitDir = path.join(process.env.RUNNER_TEMP || os.tmpdir(), 'paths-filter-shadow.git');+ const init = await run(['init', '--bare', '--quiet', gitDir], signal);+ if (init.code !== 0) {+ throw new Unavailable('no-scratch-repo', firstLine(init.err));+ }+ return gitDir;+}+// The workspace remote carries no credentials of its own: actions/checkout keeps the+// token in an http.extraheader the scratch repository does not inherit. A private+// remote therefore reports unavailable rather than comparing against a partial fetch.+function originUrl() {+ const server = process.env.GITHUB_SERVER_URL;+ const repo = process.env.GITHUB_REPOSITORY;+ if (!server || !repo) {+ throw new Unavailable('no-origin-url', 'GITHUB_SERVER_URL or GITHUB_REPOSITORY is unset');+ }+ return `${server}/${repo}`;+}+// The merge ref is not guaranteed to be present or current: GitHub recomputes it+// asynchronously after a push. Requiring the second parent to equal the head SHA+// rejects a stale ref rather than reading it as this pull request's changes.+async function localChangedFiles(pr, signal) {+ const gitDir = await scratchRepo(signal);+ const fetched = await git(gitDir, [+ '-c',+ 'http.lowSpeedLimit=1000',+ '-c',+ 'http.lowSpeedTime=10',+ 'fetch',+ '--no-tags',+ '--filter=blob:none',+ `--depth=${MERGE_REF_FETCH_DEPTH}`,+ originUrl(),+ `refs/pull/${pr.number}/merge`+ ], signal);+ if (fetched.code !== 0) {+ throw new Unavailable('no-merge-ref', firstLine(fetched.err));+ }+ const head = await git(gitDir, ['rev-parse', 'FETCH_HEAD^2'], signal);+ if (head.code !== 0) {+ throw new Unavailable('no-second-parent', firstLine(head.err));+ }+ const headSha = head.out.trim();+ if (headSha !== pr.head.sha) {+ throw new Unavailable('stale-merge-ref', `^2=${headSha.slice(0, 8)}, head=${pr.head.sha.slice(0, 8)}`);+ }+ // --no-renames so a rename arrives as a delete plus an add, which is the shape+ // the API path builds by hand from `previous_filename`. -z because git quotes a+ // path holding a newline or a non-ASCII byte in the default format.+ const diff = await git(gitDir, ['diff', '--no-renames', '--name-only', '-z', 'FETCH_HEAD^1', 'FETCH_HEAD'], signal);+ if (diff.code !== 0) {+ throw new Unavailable('diff-failed', firstLine(diff.err));+ }+ return diff.out.split('\0').filter(Boolean);+}+// A queue branch can differ by thousands of paths, which is neither readable in a log+// line nor worth carrying as an event property. The count answers how far apart the two+// answers are, and the sample answers what kind of path is involved.+function difference(from, against) {+ const sample = [];+ let count = 0;+ for (const filename of from) {+ if (against.has(filename)) {+ continue;+ }+ count++;+ if (sample.length < LIST_CAP) {+ sample.push(filename);+ }+ }+ return { count, sample };+}+function compare(api, local) {+ const onlyInApi = difference(api, local);+ const onlyInGit = difference(local, api);+ return {+ verdict: onlyInApi.count === 0 && onlyInGit.count === 0 ? 'match' : 'mismatch',+ reason: null,+ detail: null,+ apiCount: api.size,+ gitCount: local.size,+ onlyInApi,+ onlyInGit+ };+}+async function budgeted(work, ms) {+ const controller = new AbortController();+ let timer;+ const expiry = new Promise((_, reject) => {+ timer = setTimeout(() => {+ controller.abort();+ reject(new Unavailable('budget-exceeded', `${ms}ms`));+ }, ms);+ });+ return Promise.race([work(controller.signal), expiry]).finally(() => clearTimeout(timer));+}+async function compareWithMergeCommit(apiFiles, pr) {+ const api = new Set(apiFiles.map(f => f.filename));+ try {+ const gitFiles = await budgeted(async (signal) => localChangedFiles(pr, signal), BUDGET_MS);+ return compare(api, new Set(gitFiles));+ }+ catch (error) {+ return {+ verdict: 'unavailable',+ reason: error instanceof Unavailable ? error.reason : 'unknown',+ detail: error instanceof Unavailable ? error.detail : messageOf(error),+ apiCount: api.size,+ gitCount: null,+ onlyInApi: { count: 0, sample: [] },+ onlyInGit: { count: 0, sample: [] }+ };+ }+}+// Without this the only record of a divergence is a log line in one job of one run,+// which is unreadable at the volume that makes the comparison worth running.+async function capture(apiKey, result, pr, durationMs) {+ var _a;+ const repo = process.env.GITHUB_REPOSITORY || null;+ const properties = {+ repo,+ verdict: result.verdict,+ reason: result.reason,+ detail: result.detail,+ api_count: result.apiCount,+ git_count: result.gitCount,+ only_in_api: result.onlyInApi.sample,+ only_in_api_count: result.onlyInApi.count,+ only_in_git: result.onlyInGit.sample,+ only_in_git_count: result.onlyInGit.count,+ // pulls/{n}/files truncates silently, so record both sides of the tell: what the+ // API returned, and what the pull request payload says it should have been. The+ // count has to come from the payload, because `api_count` counts a rename twice:+ // the API path expands each renamed row into an add plus a delete.+ api_truncated: pr.changed_files >= API_FILE_CAP,+ pr_changed_files: pr.changed_files,+ pr_number: pr.number,+ head_sha: pr.head.sha,+ head_ref: pr.head.ref,+ base_ref: pr.base.ref,+ // Queue branches carry the cumulative batch diff and page far more than a human+ // pull request, so they are the population worth reading separately.+ branch_class: pr.head.ref.startsWith('trunk-merge/') ? 'trunk-merge' : 'pull-request',+ is_fork: ((_a = pr.head.repo) === null || _a === void 0 ? void 0 : _a.full_name) !== repo,+ duration_ms: durationMs,+ workflow: process.env.GITHUB_WORKFLOW || null,+ job: process.env.GITHUB_JOB || null,+ run_id: process.env.GITHUB_RUN_ID || null,+ run_attempt: process.env.GITHUB_RUN_ATTEMPT || null+ };+ const res = await fetch(`${POSTHOG_HOST}/capture/`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ api_key: apiKey,+ event: EVENT_NAME,+ distinct_id: repo || 'paths-filter-shadow',+ properties+ }),+ // Whatever the comparison did not spend, so the step's ceiling stays the budget.+ signal: AbortSignal.timeout(Math.max(CAPTURE_FLOOR_MS, BUDGET_MS - durationMs))+ });+ if (!res.ok) {+ throw new Error(`capture ${res.status}`);+ }+}+function summarize(result) {+ if (result.verdict === 'unavailable') {+ return `unavailable (${result.reason}: ${result.detail})`;+ }+ if (result.verdict === 'mismatch') {+ return (`MISMATCH api=${result.apiCount} git=${result.gitCount} ` ++ `onlyInApi=${JSON.stringify(result.onlyInApi.sample)} onlyInGit=${JSON.stringify(result.onlyInGit.sample)}`);+ }+ return `match (${result.apiCount} files)`;+}+// Never throws: the filter's real answer is already computed by the time this runs,+// so nothing here is worth failing a CI job over.+//+// The token gates the comparison itself, not just the capture. Every workflow that+// detects changes runs this action, so a comparison whose result cannot be recorded+// is a merge-ref fetch on the critical path of a gate job in exchange for a log line+// nobody reads. Fork pull requests get no secrets, so they take this path too.+async function report(apiFiles, pr) {+ const apiKey = process.env.PATHS_FILTER_SHADOW_POSTHOG_TOKEN;+ if (!apiKey) {+ return;+ }+ try {+ core.startGroup('Shadow: merge-commit change detection');+ const startedAt = Date.now();+ const result = await compareWithMergeCommit(apiFiles, pr);+ const durationMs = Date.now() - startedAt;+ // core.info even for a mismatch: a warning becomes an annotation on the run summary+ // and the checks page, which reads as a problem with the pull request.+ core.info(`shadow: ${summarize(result)} in ${durationMs}ms`);+ await capture(apiKey, result, pr, durationMs).catch(error => {+ core.info(`shadow: capture skipped (${messageOf(error)})`);+ });+ }+ catch (error) {+ core.info(`shadow: skipped (${messageOf(error)})`);+ }+ finally {+ core.endGroup();+ }+}++/***/ }),/***/ 2613:diff --git a/.depot/actions/paths-filter/src/main.ts b/.depot/actions/paths-filter/src/main.tsindex 2254fef3a32a..cec7f6628895 100644--- a/.depot/actions/paths-filter/src/main.ts+++ b/.depot/actions/paths-filter/src/main.ts@@ -7,6 +7,7 @@ import {PullRequest, PushEvent} from '@octokit/webhooks-types'import {Filter, FilterResults} from './filter'import {File, ChangeStatus} from './file'import * as git from './git'+import * as shadow from './shadow'import {backslashEscape, shellEscape} from './list-format/shell-escape'import {csvEscape} from './list-format/csv-escape'@@ -83,7 +84,9 @@ async function getChangedFiles(token: string, base: string, ref: string, initial}const pr = github.context.payload.pull_request as PullRequestif (token) {- return await getChangedFilesFromApi(token, pr)+ const apiFiles = await getChangedFilesFromApi(token, pr)+ await shadow.report(apiFiles, pr)+ return apiFiles}if (github.context.eventName === 'pull_request_target') {// pull_request_target is executed in context of base branch and GITHUB_SHA points to last commit in base branchdiff --git a/.depot/actions/paths-filter/src/shadow.ts b/.depot/actions/paths-filter/src/shadow.tsnew file mode 100644index 000000000000..abcfcb3b975e--- /dev/null+++ b/.depot/actions/paths-filter/src/shadow.ts@@ -0,0 +1,339 @@+import {execFile} from 'child_process'+import * as os from 'os'+import * as path from 'path'++import * as core from '@actions/core'+import {PullRequest} from '@octokit/webhooks-types'++import {File} from './file'++// Compares the API's changed-file list against the same list derived locally from+// the pull request's merge commit, and reports disagreement without acting on it.+// The API result stays authoritative, so a wrong local answer can only produce a+// log line. Removing the API call later is only safe once this has run quiet+// across the shapes no offline sample can reach: very large diffs, and ones GitHub+// has not finished computing a merge ref for.+//+// Detecting changes from `base.sha..HEAD` instead reports every commit the branch+// picked up when the base was merged into it as the pull request's own work, which+// is wrong by thousands of files on a branch that has taken master in. The merge+// commit's first parent is the base GitHub actually merged against, so+// `HEAD^1..HEAD` is the pull request's own changes and matches the API.++const MERGE_REF_FETCH_DEPTH = 2+const POSTHOG_HOST = 'https://us.i.posthog.com'+const EVENT_NAME = 'paths_filter_shadow_compared'++// A change-detection job is on the critical path of every workflow, so the comparison+// and the capture that follows it share one wall-clock budget, and give up rather than+// holding the job to its timeout-minutes. The git-level low-speed settings cover a+// stalled transfer; the budget covers everything else.+const BUDGET_MS = 20000+const CAPTURE_FLOOR_MS = 500+const LIST_CAP = 50++// A queue branch carries the cumulative batch diff, so the path list can be far larger+// than a human pull request's. execFile's 1 MB default would fail those as a diff error,+// which drops the population the comparison most needs to measure.+const MAX_GIT_OUTPUT_BYTES = 64 * 1024 * 1024+const DETAIL_CAP = 200++// The API caps pulls/{n}/files at this many entries and says nothing when it truncates.+const API_FILE_CAP = 3000++type Verdict = 'match' | 'mismatch' | 'unavailable'++// A closed set, because this is the field the comparison is grouped by once the events+// land. Git's own words go in `detail`, which is free text and unbounded.+type Reason =+ | 'no-scratch-repo'+ | 'no-origin-url'+ | 'no-merge-ref'+ | 'no-second-parent'+ | 'stale-merge-ref'+ | 'diff-failed'+ | 'budget-exceeded'+ | 'unknown'++class Unavailable extends Error {+ constructor(readonly reason: Reason, readonly detail: string) {+ super(`${reason}: ${detail}`)+ }+}++interface Difference {+ count: number+ sample: string[]+}++interface ShadowResult {+ verdict: Verdict+ reason: Reason | null+ detail: string | null+ apiCount: number+ gitCount: number | null+ onlyInApi: Difference+ onlyInGit: Difference+}++interface GitResult {+ code: number+ out: string+ err: string+}++// Every git call that reads or writes history names the scratch repository. `--depth`+// and `--filter` rewrite `.git/shallow` and the promisor config of whatever repository+// they run in, and steps later in the same job read history from the workspace checkout:+// ci-dagster and ci-e2e-playwright resolve `git merge-base HEAD^2 origin/<base>` after+// this action returns, and an empty merge base there silently drops their schema cache.+async function git(gitDir: string, args: string[], signal: AbortSignal): Promise<GitResult> {+ return run(['--git-dir', gitDir, ...args], signal)+}++// The signal is what makes the wall-clock budget real. `@actions/exec` gives no handle+// on the child process, so a fetch the budget gave up on keeps running and holds the+// action's process open until it finishes, past the budget it was supposed to obey.+//+// stdout is returned raw. A caller that reads a path list must not trim it, because a+// tracked path can begin with a space, and that path sorts first in the -z output.+async function run(args: string[], signal: AbortSignal): Promise<GitResult> {+ return new Promise(resolve => {+ execFile('git', args, {signal, maxBuffer: MAX_GIT_OUTPUT_BYTES}, (error, stdout, stderr) => {+ resolve({code: error ? 1 : 0, out: stdout, err: stderr.trim()})+ })+ })+}++function firstLine(stderr: string): string {+ return stderr.slice(0, DETAIL_CAP).split('\n')[0] || 'no stderr'+}++function messageOf(error: unknown): string {+ return error instanceof Error ? error.message : String(error)+}++async function scratchRepo(signal: AbortSignal): Promise<string> {+ const gitDir = path.join(process.env.RUNNER_TEMP || os.tmpdir(), 'paths-filter-shadow.git')+ const init = await run(['init', '--bare', '--quiet', gitDir], signal)+ if (init.code !== 0) {+ throw new Unavailable('no-scratch-repo', firstLine(init.err))+ }+ return gitDir+}++// The workspace remote carries no credentials of its own: actions/checkout keeps the+// token in an http.extraheader the scratch repository does not inherit. A private+// remote therefore reports unavailable rather than comparing against a partial fetch.+function originUrl(): string {+ const server = process.env.GITHUB_SERVER_URL+ const repo = process.env.GITHUB_REPOSITORY+ if (!server || !repo) {+ throw new Unavailable('no-origin-url', 'GITHUB_SERVER_URL or GITHUB_REPOSITORY is unset')+ }+ return `${server}/${repo}`+}++// The merge ref is not guaranteed to be present or current: GitHub recomputes it+// asynchronously after a push. Requiring the second parent to equal the head SHA+// rejects a stale ref rather than reading it as this pull request's changes.+async function localChangedFiles(pr: PullRequest, signal: AbortSignal): Promise<string[]> {+ const gitDir = await scratchRepo(signal)++ const fetched = await git(+ gitDir,+ [+ '-c',+ 'http.lowSpeedLimit=1000',+ '-c',+ 'http.lowSpeedTime=10',+ 'fetch',+ '--no-tags',+ '--filter=blob:none',+ `--depth=${MERGE_REF_FETCH_DEPTH}`,+ originUrl(),+ `refs/pull/${pr.number}/merge`+ ],+ signal+ )+ if (fetched.code !== 0) {+ throw new Unavailable('no-merge-ref', firstLine(fetched.err))+ }++ const head = await git(gitDir, ['rev-parse', 'FETCH_HEAD^2'], signal)+ if (head.code !== 0) {+ throw new Unavailable('no-second-parent', firstLine(head.err))+ }+ const headSha = head.out.trim()+ if (headSha !== pr.head.sha) {+ throw new Unavailable('stale-merge-ref', `^2=${headSha.slice(0, 8)}, head=${pr.head.sha.slice(0, 8)}`)+ }++ // --no-renames so a rename arrives as a delete plus an add, which is the shape+ // the API path builds by hand from `previous_filename`. -z because git quotes a+ // path holding a newline or a non-ASCII byte in the default format.+ const diff = await git(gitDir, ['diff', '--no-renames', '--name-only', '-z', 'FETCH_HEAD^1', 'FETCH_HEAD'], signal)+ if (diff.code !== 0) {+ throw new Unavailable('diff-failed', firstLine(diff.err))+ }+ return diff.out.split('\0').filter(Boolean)+}++// A queue branch can differ by thousands of paths, which is neither readable in a log+// line nor worth carrying as an event property. The count answers how far apart the two+// answers are, and the sample answers what kind of path is involved.+function difference(from: Set<string>, against: Set<string>): Difference {+ const sample: string[] = []+ let count = 0+ for (const filename of from) {+ if (against.has(filename)) {+ continue+ }+ count+++ if (sample.length < LIST_CAP) {+ sample.push(filename)+ }+ }+ return {count, sample}+}++function compare(api: Set<string>, local: Set<string>): ShadowResult {+ const onlyInApi = difference(api, local)+ const onlyInGit = difference(local, api)+ return {+ verdict: onlyInApi.count === 0 && onlyInGit.count === 0 ? 'match' : 'mismatch',+ reason: null,+ detail: null,+ apiCount: api.size,+ gitCount: local.size,+ onlyInApi,+ onlyInGit+ }+}++async function budgeted<T>(work: (signal: AbortSignal) => Promise<T>, ms: number): Promise<T> {+ const controller = new AbortController()+ let timer: NodeJS.Timeout+ const expiry = new Promise<never>((_, reject) => {+ timer = setTimeout(() => {+ controller.abort()+ reject(new Unavailable('budget-exceeded', `${ms}ms`))+ }, ms)+ })+ return Promise.race([work(controller.signal), expiry]).finally(() => clearTimeout(timer))+}++export async function compareWithMergeCommit(apiFiles: File[], pr: PullRequest): Promise<ShadowResult> {+ const api = new Set(apiFiles.map(f => f.filename))+ try {+ const gitFiles = await budgeted(async signal => localChangedFiles(pr, signal), BUDGET_MS)+ return compare(api, new Set(gitFiles))+ } catch (error) {+ return {+ verdict: 'unavailable',+ reason: error instanceof Unavailable ? error.reason : 'unknown',+ detail: error instanceof Unavailable ? error.detail : messageOf(error),+ apiCount: api.size,+ gitCount: null,+ onlyInApi: {count: 0, sample: []},+ onlyInGit: {count: 0, sample: []}+ }+ }+}++// Without this the only record of a divergence is a log line in one job of one run,+// which is unreadable at the volume that makes the comparison worth running.+async function capture(apiKey: string, result: ShadowResult, pr: PullRequest, durationMs: number): Promise<void> {+ const repo = process.env.GITHUB_REPOSITORY || null+ const properties = {+ repo,+ verdict: result.verdict,+ reason: result.reason,+ detail: result.detail,+ api_count: result.apiCount,+ git_count: result.gitCount,+ only_in_api: result.onlyInApi.sample,+ only_in_api_count: result.onlyInApi.count,+ only_in_git: result.onlyInGit.sample,+ only_in_git_count: result.onlyInGit.count,+ // pulls/{n}/files truncates silently, so record both sides of the tell: what the+ // API returned, and what the pull request payload says it should have been. The+ // count has to come from the payload, because `api_count` counts a rename twice:+ // the API path expands each renamed row into an add plus a delete.+ api_truncated: pr.changed_files >= API_FILE_CAP,+ pr_changed_files: pr.changed_files,+ pr_number: pr.number,+ head_sha: pr.head.sha,+ head_ref: pr.head.ref,+ base_ref: pr.base.ref,+ // Queue branches carry the cumulative batch diff and page far more than a human+ // pull request, so they are the population worth reading separately.+ branch_class: pr.head.ref.startsWith('trunk-merge/') ? 'trunk-merge' : 'pull-request',+ is_fork: pr.head.repo?.full_name !== repo,+ duration_ms: durationMs,+ workflow: process.env.GITHUB_WORKFLOW || null,+ job: process.env.GITHUB_JOB || null,+ run_id: process.env.GITHUB_RUN_ID || null,+ run_attempt: process.env.GITHUB_RUN_ATTEMPT || null+ }+ const res = await fetch(`${POSTHOG_HOST}/capture/`, {+ method: 'POST',+ headers: {'Content-Type': 'application/json'},+ body: JSON.stringify({+ api_key: apiKey,+ event: EVENT_NAME,+ distinct_id: repo || 'paths-filter-shadow',+ properties+ }),+ // Whatever the comparison did not spend, so the step's ceiling stays the budget.+ signal: AbortSignal.timeout(Math.max(CAPTURE_FLOOR_MS, BUDGET_MS - durationMs))+ })+ if (!res.ok) {+ throw new Error(`capture ${res.status}`)+ }+}++function summarize(result: ShadowResult): string {+ if (result.verdict === 'unavailable') {+ return `unavailable (${result.reason}: ${result.detail})`+ }+ if (result.verdict === 'mismatch') {+ return (+ `MISMATCH api=${result.apiCount} git=${result.gitCount} ` ++ `onlyInApi=${JSON.stringify(result.onlyInApi.sample)} onlyInGit=${JSON.stringify(result.onlyInGit.sample)}`+ )+ }+ return `match (${result.apiCount} files)`+}++// Never throws: the filter's real answer is already computed by the time this runs,+// so nothing here is worth failing a CI job over.+//+// The token gates the comparison itself, not just the capture. Every workflow that+// detects changes runs this action, so a comparison whose result cannot be recorded+// is a merge-ref fetch on the critical path of a gate job in exchange for a log line+// nobody reads. Fork pull requests get no secrets, so they take this path too.+export async function report(apiFiles: File[], pr: PullRequest): Promise<void> {+ const apiKey = process.env.PATHS_FILTER_SHADOW_POSTHOG_TOKEN+ if (!apiKey) {+ return+ }+ try {+ core.startGroup('Shadow: merge-commit change detection')+ const startedAt = Date.now()+ const result = await compareWithMergeCommit(apiFiles, pr)+ const durationMs = Date.now() - startedAt++ // core.info even for a mismatch: a warning becomes an annotation on the run summary+ // and the checks page, which reads as a problem with the pull request.+ core.info(`shadow: ${summarize(result)} in ${durationMs}ms`)++ await capture(apiKey, result, pr, durationMs).catch(error => {+ core.info(`shadow: capture skipped (${messageOf(error)})`)+ })+ } catch (error) {+ core.info(`shadow: skipped (${messageOf(error)})`)+ } finally {+ core.endGroup()+ }+}diff --git a/.github/actions/paths-filter/README.md b/.github/actions/paths-filter/README.mdindex 9ff00783cfa6..cb2b746d89a6 100644--- a/.github/actions/paths-filter/README.md+++ b/.github/actions/paths-filter/README.md@@ -65,6 +65,22 @@ changed:- added|modified: ['src/**', '!src/vendor/**']```+## Shadow comparison (opt-in)++Set `PATHS_FILTER_SHADOW_POSTHOG_TOKEN` on a step to have that run compare the API's+changed-file list against the same list derived from the pull request's merge commit,+and send the verdict to PostHog. The comparison never changes what the filter answers.++```yaml+- uses: ./.github/actions/paths-filter+ env:+ PATHS_FILTER_SHADOW_POSTHOG_TOKEN: ${{ secrets.POSTHOG_DEVEX_PROJECT_API_TOKEN }}+```++Without the variable the action does no extra work. Set it in one workflow that runs on+every pull request; that keeps the merge-ref fetch off the critical path of the other+gating jobs. This is temporary, and goes away with the decision it exists to inform.+## Rebuilding after source changesThe action runs the committed `dist/index.js` bundle. After editing anything under `src/`,diff --git a/.github/actions/paths-filter/__tests__/shadow.test.ts b/.github/actions/paths-filter/__tests__/shadow.test.tsnew file mode 100644index 000000000000..257a62d706fe--- /dev/null+++ b/.github/actions/paths-filter/__tests__/shadow.test.ts@@ -0,0 +1,101 @@+import {PullRequest} from '@octokit/webhooks-types'++import {ChangeStatus} from '../src/file'+import {compareWithMergeCommit} from '../src/shadow'++const cp = jest.requireMock('child_process') as {execFile: jest.Mock}++jest.mock('child_process', () => ({execFile: jest.fn()}))+jest.mock('@actions/core', () => ({info: jest.fn(), startGroup: jest.fn(), endGroup: jest.fn()}))++const HEAD = 'a'.repeat(40)+const OTHER_SHA = 'b'.repeat(40)+const GIT_DIR = '/tmp/runner/paths-filter-shadow.git'+const PAST_ANY_BUDGET_MS = 120000++type ExecFileArgs = [+ string,+ string[],+ {signal: AbortSignal},+ (error: Error | null, stdout: string, stderr: string) => void+]++const pullRequest = {number: 42, head: {sha: HEAD}} as PullRequest++function stubGit(...stdouts: string[]): void {+ for (const stdout of stdouts) {+ cp.execFile.mockImplementationOnce((...args: ExecFileArgs) => args[3](null, stdout, ''))+ }+}++function argvOf(call: number): string[] {+ return cp.execFile.mock.calls[call][1] as string[]+}++describe('shadow merge-commit comparison', () => {+ beforeEach(() => {+ process.env.RUNNER_TEMP = '/tmp/runner'+ process.env.GITHUB_SERVER_URL = 'https://github.com'+ process.env.GITHUB_REPOSITORY = 'PostHog/posthog'+ cp.execFile.mockReset()+ })++ // A git call that forgets the scratch dir runs against the job workspace, where a+ // --depth or --filter fetch drops the schema cache of every later step in the job.+ test('never runs git against the job workspace', async () => {+ stubGit('', '', HEAD, 'a.ts\0')++ const result = await compareWithMergeCommit([{filename: 'a.ts', status: ChangeStatus.Modified}], pullRequest)++ expect(result.verdict).toBe('match')+ expect(argvOf(0)).toContain(GIT_DIR)+ for (let call = 1; call < cp.execFile.mock.calls.length; call++) {+ expect(argvOf(call).slice(0, 2)).toEqual(['--git-dir', GIT_DIR])+ }+ })++ // Losing this guard scores a merge ref from an earlier push as this pull request's+ // changes, which fills the measurement with mismatches that mean nothing.+ test('refuses a stale merge ref instead of comparing against it', async () => {+ stubGit('', '', OTHER_SHA)++ const result = await compareWithMergeCommit([{filename: 'a.ts', status: ChangeStatus.Modified}], pullRequest)++ expect(result.verdict).toBe('unavailable')+ expect(result.reason).toBe('stale-merge-ref')+ })++ // Losing --no-renames reports one path where the API path reports two, so every+ // rename reads as a mismatch.+ test('matches a rename that the API reported as two entries', async () => {+ stubGit('', '', HEAD, 'old.ts\0new.ts\0')++ const result = await compareWithMergeCommit(+ [+ {filename: 'new.ts', status: ChangeStatus.Added},+ {filename: 'old.ts', status: ChangeStatus.Deleted}+ ],+ pullRequest+ )++ expect(result.verdict).toBe('match')+ expect(cp.execFile.mock.calls.map(c => c[1])).toContainEqual(expect.arrayContaining(['--no-renames']))+ })++ // An exec with no handle on the child leaves the fetch running after the budget gives+ // up, and the action's process stays open until git exits.+ test('stops git when the budget expires', async () => {+ cp.execFile.mockImplementation(() => undefined)+ jest.useFakeTimers()++ const pending = compareWithMergeCommit([], pullRequest)+ await jest.advanceTimersByTimeAsync(PAST_ANY_BUDGET_MS)+ const result = await pending++ expect(result.verdict).toBe('unavailable')+ expect(result.reason).toBe('budget-exceeded')+ const [, , options] = cp.execFile.mock.calls[0] as ExecFileArgs+ expect(options.signal.aborted).toBe(true)+ jest.useRealTimers()+ })+})diff --git a/.github/actions/paths-filter/dist/index.js b/.github/actions/paths-filter/dist/index.jsindex 00836501b899..1115cb186a4f 100644--- a/.github/actions/paths-filter/dist/index.js+++ b/.github/actions/paths-filter/dist/index.js@@ -42687,6 +42687,7 @@ const github = __importStar(__nccwpck_require__(3228));const filter_1 = __nccwpck_require__(9037);const file_1 = __nccwpck_require__(3765);const git = __importStar(__nccwpck_require__(1243));+const shadow = __importStar(__nccwpck_require__(5763));const shell_escape_1 = __nccwpck_require__(6880);const csv_escape_1 = __nccwpck_require__(6146);async function run() {@@ -42753,7 +42754,9 @@ async function getChangedFiles(token, base, ref, initialFetchDepth) {}const pr = github.context.payload.pull_request;if (token) {- return await getChangedFilesFromApi(token, pr);+ const apiFiles = await getChangedFilesFromApi(token, pr);+ await shadow.report(apiFiles, pr);+ return apiFiles;}if (github.context.eventName === 'pull_request_target') {// pull_request_target is executed in context of base branch and GITHUB_SHA points to last commit in base branch@@ -42926,6 +42929,326 @@ function getErrorMessage(error) {run();+/***/ }),++/***/ 5763:+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {++"use strict";++var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {+ if (k2 === undefined) k2 = k;+ var desc = Object.getOwnPropertyDescriptor(m, k);+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {+ desc = { enumerable: true, get: function() { return m[k]; } };+ }+ Object.defineProperty(o, k2, desc);+}) : (function(o, m, k, k2) {+ if (k2 === undefined) k2 = k;+ o[k2] = m[k];+}));+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {+ Object.defineProperty(o, "default", { enumerable: true, value: v });+}) : function(o, v) {+ o["default"] = v;+});+var __importStar = (this && this.__importStar) || (function () {+ var ownKeys = function(o) {+ ownKeys = Object.getOwnPropertyNames || function (o) {+ var ar = [];+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;+ return ar;+ };+ return ownKeys(o);+ };+ return function (mod) {+ if (mod && mod.__esModule) return mod;+ var result = {};+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);+ __setModuleDefault(result, mod);+ return result;+ };+})();+Object.defineProperty(exports, "__esModule", ({ value: true }));+exports.compareWithMergeCommit = compareWithMergeCommit;+exports.report = report;+const child_process_1 = __nccwpck_require__(5317);+const os = __importStar(__nccwpck_require__(857));+const path = __importStar(__nccwpck_require__(6928));+const core = __importStar(__nccwpck_require__(7484));+// Compares the API's changed-file list against the same list derived locally from+// the pull request's merge commit, and reports disagreement without acting on it.+// The API result stays authoritative, so a wrong local answer can only produce a+// log line. Removing the API call later is only safe once this has run quiet+// across the shapes no offline sample can reach: very large diffs, and ones GitHub+// has not finished computing a merge ref for.+//+// Detecting changes from `base.sha..HEAD` instead reports every commit the branch+// picked up when the base was merged into it as the pull request's own work, which+// is wrong by thousands of files on a branch that has taken master in. The merge+// commit's first parent is the base GitHub actually merged against, so+// `HEAD^1..HEAD` is the pull request's own changes and matches the API.+const MERGE_REF_FETCH_DEPTH = 2;+const POSTHOG_HOST = 'https://us.i.posthog.com';+const EVENT_NAME = 'paths_filter_shadow_compared';+// A change-detection job is on the critical path of every workflow, so the comparison+// and the capture that follows it share one wall-clock budget, and give up rather than+// holding the job to its timeout-minutes. The git-level low-speed settings cover a+// stalled transfer; the budget covers everything else.+const BUDGET_MS = 20000;+const CAPTURE_FLOOR_MS = 500;+const LIST_CAP = 50;+// A queue branch carries the cumulative batch diff, so the path list can be far larger+// than a human pull request's. execFile's 1 MB default would fail those as a diff error,+// which drops the population the comparison most needs to measure.+const MAX_GIT_OUTPUT_BYTES = 64 * 1024 * 1024;+const DETAIL_CAP = 200;+// The API caps pulls/{n}/files at this many entries and says nothing when it truncates.+const API_FILE_CAP = 3000;+class Unavailable extends Error {+ constructor(reason, detail) {+ super(`${reason}: ${detail}`);+ this.reason = reason;+ this.detail = detail;+ }+}+// Every git call that reads or writes history names the scratch repository. `--depth`+// and `--filter` rewrite `.git/shallow` and the promisor config of whatever repository+// they run in, and steps later in the same job read history from the workspace checkout:+// ci-dagster and ci-e2e-playwright resolve `git merge-base HEAD^2 origin/<base>` after+// this action returns, and an empty merge base there silently drops their schema cache.+async function git(gitDir, args, signal) {+ return run(['--git-dir', gitDir, ...args], signal);+}+// The signal is what makes the wall-clock budget real. `@actions/exec` gives no handle+// on the child process, so a fetch the budget gave up on keeps running and holds the+// action's process open until it finishes, past the budget it was supposed to obey.+//+// stdout is returned raw. A caller that reads a path list must not trim it, because a+// tracked path can begin with a space, and that path sorts first in the -z output.+async function run(args, signal) {+ return new Promise(resolve => {+ (0, child_process_1.execFile)('git', args, { signal, maxBuffer: MAX_GIT_OUTPUT_BYTES }, (error, stdout, stderr) => {+ resolve({ code: error ? 1 : 0, out: stdout, err: stderr.trim() });+ });+ });+}+function firstLine(stderr) {+ return stderr.slice(0, DETAIL_CAP).split('\n')[0] || 'no stderr';+}+function messageOf(error) {+ return error instanceof Error ? error.message : String(error);+}+async function scratchRepo(signal) {+ const gitDir = path.join(process.env.RUNNER_TEMP || os.tmpdir(), 'paths-filter-shadow.git');+ const init = await run(['init', '--bare', '--quiet', gitDir], signal);+ if (init.code !== 0) {+ throw new Unavailable('no-scratch-repo', firstLine(init.err));+ }+ return gitDir;+}+// The workspace remote carries no credentials of its own: actions/checkout keeps the+// token in an http.extraheader the scratch repository does not inherit. A private+// remote therefore reports unavailable rather than comparing against a partial fetch.+function originUrl() {+ const server = process.env.GITHUB_SERVER_URL;+ const repo = process.env.GITHUB_REPOSITORY;+ if (!server || !repo) {+ throw new Unavailable('no-origin-url', 'GITHUB_SERVER_URL or GITHUB_REPOSITORY is unset');+ }+ return `${server}/${repo}`;+}+// The merge ref is not guaranteed to be present or current: GitHub recomputes it+// asynchronously after a push. Requiring the second parent to equal the head SHA+// rejects a stale ref rather than reading it as this pull request's changes.+async function localChangedFiles(pr, signal) {+ const gitDir = await scratchRepo(signal);+ const fetched = await git(gitDir, [+ '-c',+ 'http.lowSpeedLimit=1000',+ '-c',+ 'http.lowSpeedTime=10',+ 'fetch',+ '--no-tags',+ '--filter=blob:none',+ `--depth=${MERGE_REF_FETCH_DEPTH}`,+ originUrl(),+ `refs/pull/${pr.number}/merge`+ ], signal);+ if (fetched.code !== 0) {+ throw new Unavailable('no-merge-ref', firstLine(fetched.err));+ }+ const head = await git(gitDir, ['rev-parse', 'FETCH_HEAD^2'], signal);+ if (head.code !== 0) {+ throw new Unavailable('no-second-parent', firstLine(head.err));+ }+ const headSha = head.out.trim();+ if (headSha !== pr.head.sha) {+ throw new Unavailable('stale-merge-ref', `^2=${headSha.slice(0, 8)}, head=${pr.head.sha.slice(0, 8)}`);+ }+ // --no-renames so a rename arrives as a delete plus an add, which is the shape+ // the API path builds by hand from `previous_filename`. -z because git quotes a+ // path holding a newline or a non-ASCII byte in the default format.+ const diff = await git(gitDir, ['diff', '--no-renames', '--name-only', '-z', 'FETCH_HEAD^1', 'FETCH_HEAD'], signal);+ if (diff.code !== 0) {+ throw new Unavailable('diff-failed', firstLine(diff.err));+ }+ return diff.out.split('\0').filter(Boolean);+}+// A queue branch can differ by thousands of paths, which is neither readable in a log+// line nor worth carrying as an event property. The count answers how far apart the two+// answers are, and the sample answers what kind of path is involved.+function difference(from, against) {+ const sample = [];+ let count = 0;+ for (const filename of from) {+ if (against.has(filename)) {+ continue;+ }+ count++;+ if (sample.length < LIST_CAP) {+ sample.push(filename);+ }+ }+ return { count, sample };+}+function compare(api, local) {+ const onlyInApi = difference(api, local);+ const onlyInGit = difference(local, api);+ return {+ verdict: onlyInApi.count === 0 && onlyInGit.count === 0 ? 'match' : 'mismatch',+ reason: null,+ detail: null,+ apiCount: api.size,+ gitCount: local.size,+ onlyInApi,+ onlyInGit+ };+}+async function budgeted(work, ms) {+ const controller = new AbortController();+ let timer;+ const expiry = new Promise((_, reject) => {+ timer = setTimeout(() => {+ controller.abort();+ reject(new Unavailable('budget-exceeded', `${ms}ms`));+ }, ms);+ });+ return Promise.race([work(controller.signal), expiry]).finally(() => clearTimeout(timer));+}+async function compareWithMergeCommit(apiFiles, pr) {+ const api = new Set(apiFiles.map(f => f.filename));+ try {+ const gitFiles = await budgeted(async (signal) => localChangedFiles(pr, signal), BUDGET_MS);+ return compare(api, new Set(gitFiles));+ }+ catch (error) {+ return {+ verdict: 'unavailable',+ reason: error instanceof Unavailable ? error.reason : 'unknown',+ detail: error instanceof Unavailable ? error.detail : messageOf(error),+ apiCount: api.size,+ gitCount: null,+ onlyInApi: { count: 0, sample: [] },+ onlyInGit: { count: 0, sample: [] }+ };+ }+}+// Without this the only record of a divergence is a log line in one job of one run,+// which is unreadable at the volume that makes the comparison worth running.+async function capture(apiKey, result, pr, durationMs) {+ var _a;+ const repo = process.env.GITHUB_REPOSITORY || null;+ const properties = {+ repo,+ verdict: result.verdict,+ reason: result.reason,+ detail: result.detail,+ api_count: result.apiCount,+ git_count: result.gitCount,+ only_in_api: result.onlyInApi.sample,+ only_in_api_count: result.onlyInApi.count,+ only_in_git: result.onlyInGit.sample,+ only_in_git_count: result.onlyInGit.count,+ // pulls/{n}/files truncates silently, so record both sides of the tell: what the+ // API returned, and what the pull request payload says it should have been. The+ // count has to come from the payload, because `api_count` counts a rename twice:+ // the API path expands each renamed row into an add plus a delete.+ api_truncated: pr.changed_files >= API_FILE_CAP,+ pr_changed_files: pr.changed_files,+ pr_number: pr.number,+ head_sha: pr.head.sha,+ head_ref: pr.head.ref,+ base_ref: pr.base.ref,+ // Queue branches carry the cumulative batch diff and page far more than a human+ // pull request, so they are the population worth reading separately.+ branch_class: pr.head.ref.startsWith('trunk-merge/') ? 'trunk-merge' : 'pull-request',+ is_fork: ((_a = pr.head.repo) === null || _a === void 0 ? void 0 : _a.full_name) !== repo,+ duration_ms: durationMs,+ workflow: process.env.GITHUB_WORKFLOW || null,+ job: process.env.GITHUB_JOB || null,+ run_id: process.env.GITHUB_RUN_ID || null,+ run_attempt: process.env.GITHUB_RUN_ATTEMPT || null+ };+ const res = await fetch(`${POSTHOG_HOST}/capture/`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ api_key: apiKey,+ event: EVENT_NAME,+ distinct_id: repo || 'paths-filter-shadow',+ properties+ }),+ // Whatever the comparison did not spend, so the step's ceiling stays the budget.+ signal: AbortSignal.timeout(Math.max(CAPTURE_FLOOR_MS, BUDGET_MS - durationMs))+ });+ if (!res.ok) {+ throw new Error(`capture ${res.status}`);+ }+}+function summarize(result) {+ if (result.verdict === 'unavailable') {+ return `unavailable (${result.reason}: ${result.detail})`;+ }+ if (result.verdict === 'mismatch') {+ return (`MISMATCH api=${result.apiCount} git=${result.gitCount} ` ++ `onlyInApi=${JSON.stringify(result.onlyInApi.sample)} onlyInGit=${JSON.stringify(result.onlyInGit.sample)}`);+ }+ return `match (${result.apiCount} files)`;+}+// Never throws: the filter's real answer is already computed by the time this runs,+// so nothing here is worth failing a CI job over.+//+// The token gates the comparison itself, not just the capture. Every workflow that+// detects changes runs this action, so a comparison whose result cannot be recorded+// is a merge-ref fetch on the critical path of a gate job in exchange for a log line+// nobody reads. Fork pull requests get no secrets, so they take this path too.+async function report(apiFiles, pr) {+ const apiKey = process.env.PATHS_FILTER_SHADOW_POSTHOG_TOKEN;+ if (!apiKey) {+ return;+ }+ try {+ core.startGroup('Shadow: merge-commit change detection');+ const startedAt = Date.now();+ const result = await compareWithMergeCommit(apiFiles, pr);+ const durationMs = Date.now() - startedAt;+ // core.info even for a mismatch: a warning becomes an annotation on the run summary+ // and the checks page, which reads as a problem with the pull request.+ core.info(`shadow: ${summarize(result)} in ${durationMs}ms`);+ await capture(apiKey, result, pr, durationMs).catch(error => {+ core.info(`shadow: capture skipped (${messageOf(error)})`);+ });+ }+ catch (error) {+ core.info(`shadow: skipped (${messageOf(error)})`);+ }+ finally {+ core.endGroup();+ }+}++/***/ }),/***/ 2613:diff --git a/.github/actions/paths-filter/src/main.ts b/.github/actions/paths-filter/src/main.tsindex 2254fef3a32a..cec7f6628895 100644--- a/.github/actions/paths-filter/src/main.ts+++ b/.github/actions/paths-filter/src/main.ts@@ -7,6 +7,7 @@ import {PullRequest, PushEvent} from '@octokit/webhooks-types'import {Filter, FilterResults} from './filter'import {File, ChangeStatus} from './file'import * as git from './git'+import * as shadow from './shadow'import {backslashEscape, shellEscape} from './list-format/shell-escape'import {csvEscape} from './list-format/csv-escape'@@ -83,7 +84,9 @@ async function getChangedFiles(token: string, base: string, ref: string, initial}const pr = github.context.payload.pull_request as PullRequestif (token) {- return await getChangedFilesFromApi(token, pr)+ const apiFiles = await getChangedFilesFromApi(token, pr)+ await shadow.report(apiFiles, pr)+ return apiFiles}if (github.context.eventName === 'pull_request_target') {// pull_request_target is executed in context of base branch and GITHUB_SHA points to last commit in base branchdiff --git a/.github/actions/paths-filter/src/shadow.ts b/.github/actions/paths-filter/src/shadow.tsnew file mode 100644index 000000000000..abcfcb3b975e--- /dev/null+++ b/.github/actions/paths-filter/src/shadow.ts@@ -0,0 +1,339 @@+import {execFile} from 'child_process'+import * as os from 'os'+import * as path from 'path'++import * as core from '@actions/core'+import {PullRequest} from '@octokit/webhooks-types'++import {File} from './file'++// Compares the API's changed-file list against the same list derived locally from+// the pull request's merge commit, and reports disagreement without acting on it.+// The API result stays authoritative, so a wrong local answer can only produce a+// log line. Removing the API call later is only safe once this has run quiet+// across the shapes no offline sample can reach: very large diffs, and ones GitHub+// has not finished computing a merge ref for.+//+// Detecting changes from `base.sha..HEAD` instead reports every commit the branch+// picked up when the base was merged into it as the pull request's own work, which+// is wrong by thousands of files on a branch that has taken master in. The merge+// commit's first parent is the base GitHub actually merged against, so+// `HEAD^1..HEAD` is the pull request's own changes and matches the API.++const MERGE_REF_FETCH_DEPTH = 2+const POSTHOG_HOST = 'https://us.i.posthog.com'+const EVENT_NAME = 'paths_filter_shadow_compared'++// A change-detection job is on the critical path of every workflow, so the comparison+// and the capture that follows it share one wall-clock budget, and give up rather than+// holding the job to its timeout-minutes. The git-level low-speed settings cover a+// stalled transfer; the budget covers everything else.+const BUDGET_MS = 20000+const CAPTURE_FLOOR_MS = 500+const LIST_CAP = 50++// A queue branch carries the cumulative batch diff, so the path list can be far larger+// than a human pull request's. execFile's 1 MB default would fail those as a diff error,+// which drops the population the comparison most needs to measure.+const MAX_GIT_OUTPUT_BYTES = 64 * 1024 * 1024+const DETAIL_CAP = 200++// The API caps pulls/{n}/files at this many entries and says nothing when it truncates.+const API_FILE_CAP = 3000++type Verdict = 'match' | 'mismatch' | 'unavailable'++// A closed set, because this is the field the comparison is grouped by once the events+// land. Git's own words go in `detail`, which is free text and unbounded.+type Reason =+ | 'no-scratch-repo'+ | 'no-origin-url'+ | 'no-merge-ref'+ | 'no-second-parent'+ | 'stale-merge-ref'+ | 'diff-failed'+ | 'budget-exceeded'+ | 'unknown'++class Unavailable extends Error {+ constructor(readonly reason: Reason, readonly detail: string) {+ super(`${reason}: ${detail}`)+ }+}++interface Difference {+ count: number+ sample: string[]+}++interface ShadowResult {+ verdict: Verdict+ reason: Reason | null+ detail: string | null+ apiCount: number+ gitCount: number | null+ onlyInApi: Difference+ onlyInGit: Difference+}++interface GitResult {+ code: number+ out: string+ err: string+}++// Every git call that reads or writes history names the scratch repository. `--depth`+// and `--filter` rewrite `.git/shallow` and the promisor config of whatever repository+// they run in, and steps later in the same job read history from the workspace checkout:+// ci-dagster and ci-e2e-playwright resolve `git merge-base HEAD^2 origin/<base>` after+// this action returns, and an empty merge base there silently drops their schema cache.+async function git(gitDir: string, args: string[], signal: AbortSignal): Promise<GitResult> {+ return run(['--git-dir', gitDir, ...args], signal)+}++// The signal is what makes the wall-clock budget real. `@actions/exec` gives no handle+// on the child process, so a fetch the budget gave up on keeps running and holds the+// action's process open until it finishes, past the budget it was supposed to obey.+//+// stdout is returned raw. A caller that reads a path list must not trim it, because a+// tracked path can begin with a space, and that path sorts first in the -z output.+async function run(args: string[], signal: AbortSignal): Promise<GitResult> {+ return new Promise(resolve => {+ execFile('git', args, {signal, maxBuffer: MAX_GIT_OUTPUT_BYTES}, (error, stdout, stderr) => {+ resolve({code: error ? 1 : 0, out: stdout, err: stderr.trim()})+ })+ })+}++function firstLine(stderr: string): string {+ return stderr.slice(0, DETAIL_CAP).split('\n')[0] || 'no stderr'+}++function messageOf(error: unknown): string {+ return error instanceof Error ? error.message : String(error)+}++async function scratchRepo(signal: AbortSignal): Promise<string> {+ const gitDir = path.join(process.env.RUNNER_TEMP || os.tmpdir(), 'paths-filter-shadow.git')+ const init = await run(['init', '--bare', '--quiet', gitDir], signal)+ if (init.code !== 0) {+ throw new Unavailable('no-scratch-repo', firstLine(init.err))+ }+ return gitDir+}++// The workspace remote carries no credentials of its own: actions/checkout keeps the+// token in an http.extraheader the scratch repository does not inherit. A private+// remote therefore reports unavailable rather than comparing against a partial fetch.+function originUrl(): string {+ const server = process.env.GITHUB_SERVER_URL+ const repo = process.env.GITHUB_REPOSITORY+ if (!server || !repo) {+ throw new Unavailable('no-origin-url', 'GITHUB_SERVER_URL or GITHUB_REPOSITORY is unset')+ }+ return `${server}/${repo}`+}++// The merge ref is not guaranteed to be present or current: GitHub recomputes it+// asynchronously after a push. Requiring the second parent to equal the head SHA+// rejects a stale ref rather than reading it as this pull request's changes.+async function localChangedFiles(pr: PullRequest, signal: AbortSignal): Promise<string[]> {+ const gitDir = await scratchRepo(signal)++ const fetched = await git(+ gitDir,+ [+ '-c',+ 'http.lowSpeedLimit=1000',+ '-c',+ 'http.lowSpeedTime=10',+ 'fetch',+ '--no-tags',+ '--filter=blob:none',+ `--depth=${MERGE_REF_FETCH_DEPTH}`,+ originUrl(),+ `refs/pull/${pr.number}/merge`+ ],+ signal+ )+ if (fetched.code !== 0) {+ throw new Unavailable('no-merge-ref', firstLine(fetched.err))+ }++ const head = await git(gitDir, ['rev-parse', 'FETCH_HEAD^2'], signal)+ if (head.code !== 0) {+ throw new Unavailable('no-second-parent', firstLine(head.err))+ }+ const headSha = head.out.trim()+ if (headSha !== pr.head.sha) {+ throw new Unavailable('stale-merge-ref', `^2=${headSha.slice(0, 8)}, head=${pr.head.sha.slice(0, 8)}`)+ }++ // --no-renames so a rename arrives as a delete plus an add, which is the shape+ // the API path builds by hand from `previous_filename`. -z because git quotes a+ // path holding a newline or a non-ASCII byte in the default format.+ const diff = await git(gitDir, ['diff', '--no-renames', '--name-only', '-z', 'FETCH_HEAD^1', 'FETCH_HEAD'], signal)+ if (diff.code !== 0) {+ throw new Unavailable('diff-failed', firstLine(diff.err))+ }+ return diff.out.split('\0').filter(Boolean)+}++// A queue branch can differ by thousands of paths, which is neither readable in a log+// line nor worth carrying as an event property. The count answers how far apart the two+// answers are, and the sample answers what kind of path is involved.+function difference(from: Set<string>, against: Set<string>): Difference {+ const sample: string[] = []+ let count = 0+ for (const filename of from) {+ if (against.has(filename)) {+ continue+ }+ count+++ if (sample.length < LIST_CAP) {+ sample.push(filename)+ }+ }+ return {count, sample}+}++function compare(api: Set<string>, local: Set<string>): ShadowResult {+ const onlyInApi = difference(api, local)+ const onlyInGit = difference(local, api)+ return {+ verdict: onlyInApi.count === 0 && onlyInGit.count === 0 ? 'match' : 'mismatch',+ reason: null,+ detail: null,+ apiCount: api.size,+ gitCount: local.size,+ onlyInApi,+ onlyInGit+ }+}++async function budgeted<T>(work: (signal: AbortSignal) => Promise<T>, ms: number): Promise<T> {+ const controller = new AbortController()+ let timer: NodeJS.Timeout+ const expiry = new Promise<never>((_, reject) => {+ timer = setTimeout(() => {+ controller.abort()+ reject(new Unavailable('budget-exceeded', `${ms}ms`))+ }, ms)+ })+ return Promise.race([work(controller.signal), expiry]).finally(() => clearTimeout(timer))+}++export async function compareWithMergeCommit(apiFiles: File[], pr: PullRequest): Promise<ShadowResult> {+ const api = new Set(apiFiles.map(f => f.filename))+ try {+ const gitFiles = await budgeted(async signal => localChangedFiles(pr, signal), BUDGET_MS)+ return compare(api, new Set(gitFiles))+ } catch (error) {+ return {+ verdict: 'unavailable',+ reason: error instanceof Unavailable ? error.reason : 'unknown',+ detail: error instanceof Unavailable ? error.detail : messageOf(error),+ apiCount: api.size,+ gitCount: null,+ onlyInApi: {count: 0, sample: []},+ onlyInGit: {count: 0, sample: []}+ }+ }+}++// Without this the only record of a divergence is a log line in one job of one run,+// which is unreadable at the volume that makes the comparison worth running.+async function capture(apiKey: string, result: ShadowResult, pr: PullRequest, durationMs: number): Promise<void> {+ const repo = process.env.GITHUB_REPOSITORY || null+ const properties = {+ repo,+ verdict: result.verdict,+ reason: result.reason,+ detail: result.detail,+ api_count: result.apiCount,+ git_count: result.gitCount,+ only_in_api: result.onlyInApi.sample,+ only_in_api_count: result.onlyInApi.count,+ only_in_git: result.onlyInGit.sample,+ only_in_git_count: result.onlyInGit.count,+ // pulls/{n}/files truncates silently, so record both sides of the tell: what the+ // API returned, and what the pull request payload says it should have been. The+ // count has to come from the payload, because `api_count` counts a rename twice:+ // the API path expands each renamed row into an add plus a delete.+ api_truncated: pr.changed_files >= API_FILE_CAP,+ pr_changed_files: pr.changed_files,+ pr_number: pr.number,+ head_sha: pr.head.sha,+ head_ref: pr.head.ref,+ base_ref: pr.base.ref,+ // Queue branches carry the cumulative batch diff and page far more than a human+ // pull request, so they are the population worth reading separately.+ branch_class: pr.head.ref.startsWith('trunk-merge/') ? 'trunk-merge' : 'pull-request',+ is_fork: pr.head.repo?.full_name !== repo,+ duration_ms: durationMs,+ workflow: process.env.GITHUB_WORKFLOW || null,+ job: process.env.GITHUB_JOB || null,+ run_id: process.env.GITHUB_RUN_ID || null,+ run_attempt: process.env.GITHUB_RUN_ATTEMPT || null+ }+ const res = await fetch(`${POSTHOG_HOST}/capture/`, {+ method: 'POST',+ headers: {'Content-Type': 'application/json'},+ body: JSON.stringify({+ api_key: apiKey,+ event: EVENT_NAME,+ distinct_id: repo || 'paths-filter-shadow',+ properties+ }),+ // Whatever the comparison did not spend, so the step's ceiling stays the budget.+ signal: AbortSignal.timeout(Math.max(CAPTURE_FLOOR_MS, BUDGET_MS - durationMs))+ })+ if (!res.ok) {+ throw new Error(`capture ${res.status}`)+ }+}++function summarize(result: ShadowResult): string {+ if (result.verdict === 'unavailable') {+ return `unavailable (${result.reason}: ${result.detail})`+ }+ if (result.verdict === 'mismatch') {+ return (+ `MISMATCH api=${result.apiCount} git=${result.gitCount} ` ++ `onlyInApi=${JSON.stringify(result.onlyInApi.sample)} onlyInGit=${JSON.stringify(result.onlyInGit.sample)}`+ )+ }+ return `match (${result.apiCount} files)`+}++// Never throws: the filter's real answer is already computed by the time this runs,+// so nothing here is worth failing a CI job over.+//+// The token gates the comparison itself, not just the capture. Every workflow that+// detects changes runs this action, so a comparison whose result cannot be recorded+// is a merge-ref fetch on the critical path of a gate job in exchange for a log line+// nobody reads. Fork pull requests get no secrets, so they take this path too.+export async function report(apiFiles: File[], pr: PullRequest): Promise<void> {+ const apiKey = process.env.PATHS_FILTER_SHADOW_POSTHOG_TOKEN+ if (!apiKey) {+ return+ }+ try {+ core.startGroup('Shadow: merge-commit change detection')+ const startedAt = Date.now()+ const result = await compareWithMergeCommit(apiFiles, pr)+ const durationMs = Date.now() - startedAt++ // core.info even for a mismatch: a warning becomes an annotation on the run summary+ // and the checks page, which reads as a problem with the pull request.+ core.info(`shadow: ${summarize(result)} in ${durationMs}ms`)++ await capture(apiKey, result, pr, durationMs).catch(error => {+ core.info(`shadow: capture skipped (${messageOf(error)})`)+ })+ } catch (error) {+ core.info(`shadow: skipped (${messageOf(error)})`)+ } finally {+ core.endGroup()+ }+}diff --git a/.github/workflows/ci-python.yml b/.github/workflows/ci-python.ymlindex 1e80ffa00b73..d3a82c8a0624 100644--- a/.github/workflows/ci-python.yml+++ b/.github/workflows/ci-python.yml@@ -40,6 +40,10 @@ jobs:private-key: ${{ secrets.GH_APP_POSTHOG_PATHS_FILTER_PRIVATE_KEY }}- uses: ./.github/actions/paths-filterid: filter+ env:+ # This workflow opts in for the whole repository. It runs on every pull+ # request, so one wiring covers every shape the comparison needs to see.+ PATHS_FILTER_SHADOW_POSTHOG_TOKEN: ${{ secrets.POSTHOG_DEVEX_PROJECT_API_TOKEN }}if: github.event_name != 'push' # Run all tests on master pushwith:token: ${{ steps.app-token.outputs.token || github.token }}