Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
132 changes: 122 additions & 10 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,118 @@ on:
type: boolean

permissions:
checks: read
contents: read

concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: true

jobs:
# On pushes to main, check whether a green merge_group run of this workflow
# targeting main already verified every required job on this exact commit.
# Skipped immediately on pull_request, merge_group, and workflow_dispatch with
# no runner startup cost. Fails open: if precheck errors or skips, full CI
# still runs. Keep the required job list in step with DEFAULT_REQUIRED_CHECKS
# in scripts/verify-release-ci.ts.
precheck:
name: Check if commit already passed CI
if: github.event_name == 'push'
runs-on: ubuntu-latest
timeout-minutes: 5
outputs:
skip_ci: ${{ steps.check.outputs.skip_ci }}
warm_cache: ${{ steps.check.outputs.warm_cache }}
steps:
- id: check
name: Check prior merge_group verdict on this commit
env:
GH_TOKEN: ${{ github.token }}
BEFORE: ${{ github.event.before }}
run: |
set -euo pipefail
required_json='[
"Checks and Build",
"Unit Test",
"Server Test (1/4)",
"Server Test (2/4)",
"Server Test (3/4)",
"Server Test (4/4)",
"Browser Test (1/2)",
"Browser Test (2/2)",
"Release Smoke"
]'

# Find the newest successful merge_group run of ci.yml for main on this exact SHA.
merge_run_id="$(
gh api "repos/${GITHUB_REPOSITORY}/actions/workflows/ci.yml/runs?event=merge_group&head_sha=${GITHUB_SHA}&status=success&per_page=20" \
--jq '[.workflow_runs[] | select(.conclusion == "success" and (.head_branch | startswith("gh-readonly-queue/main/")))] | sort_by(.run_started_at // .created_at) | last | .id // empty'
)"

already_passed="false"
if [[ -n "$merge_run_id" ]]; then
already_passed="$(
gh api --paginate "repos/${GITHUB_REPOSITORY}/actions/runs/${merge_run_id}/jobs?per_page=100" --jq '.jobs[]' \
| jq -s --argjson required "$required_json" '
. as $jobs |
$required | all(. as $name |
any($jobs[]; .name == $name and .status == "completed" and .conclusion == "success")
)
'
)"
fi

if [[ "$already_passed" != "true" ]]; then
echo "Commit ${GITHUB_SHA} has no passing main merge_group CI run covering all required checks; running full CI."
echo "skip_ci=false" >> "$GITHUB_OUTPUT"
echo "warm_cache=false" >> "$GITHUB_OUTPUT"
exit 0
fi

echo "merge_group run ${merge_run_id} already passed every required check on ${GITHUB_SHA}; skipping duplicate push CI."
echo "skip_ci=true" >> "$GITHUB_OUTPUT"

# Keep the main-scoped pnpm store cache warm when pnpm-lock.yaml changed
# (caches saved on merge_group branches are not visible to future PRs).
# Compare the lockfile blob SHA directly so large diffs (>300 files) never
# miss a lockfile change, and warm conservatively if the lookup fails.
warm_cache="true"
if [[ -n "$BEFORE" && "$BEFORE" != "0000000000000000000000000000000000000000" ]]; then
before_blob="$(gh api "repos/${GITHUB_REPOSITORY}/contents/pnpm-lock.yaml?ref=${BEFORE}" --jq '.sha' 2>/dev/null || true)"
after_blob="$(gh api "repos/${GITHUB_REPOSITORY}/contents/pnpm-lock.yaml?ref=${GITHUB_SHA}" --jq '.sha' 2>/dev/null || true)"
if [[ -n "$before_blob" && -n "$after_blob" && "$before_blob" == "$after_blob" ]]; then
warm_cache="false"
fi
fi
echo "warm_cache=${warm_cache}" >> "$GITHUB_OUTPUT"

warm_cache:
name: Warm main dependency cache
needs: [precheck]
if: ${{ github.event_name == 'push' && needs.precheck.result == 'success' && needs.precheck.outputs.skip_ci == 'true' && needs.precheck.outputs.warm_cache == 'true' }}
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- name: Checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1

- name: Setup Vite+
uses: voidzero-dev/setup-vp@cab1ab9eaff52d4857875f4f2c016e36af8f2c76 # v1.22.0
with:
node-version: "24"
cache: true
run-install: false

- name: Install dependencies
env:
ELECTRON_SKIP_BINARY_DOWNLOAD: "1"
run: vp install --frozen-lockfile

# scripts/verify-release-ci.ts requires this job by name.
quality:
name: Checks and Build
needs: [precheck]
if: ${{ !cancelled() && !(github.event_name == 'push' && needs.precheck.result == 'success' && needs.precheck.outputs.skip_ci == 'true') }}
runs-on: ubuntu-latest
# 20 minutes starves dependency-bump branches: a lockfile change cold-starts
# every cache and slow runners then hit the cap mid-pipeline.
Expand Down Expand Up @@ -84,6 +186,8 @@ jobs:
# scripts/verify-release-ci.ts requires this job by name.
unit_test:
name: Unit Test
needs: [precheck]
if: ${{ !cancelled() && !(github.event_name == 'push' && needs.precheck.result == 'success' && needs.precheck.outputs.skip_ci == 'true') }}
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
Expand Down Expand Up @@ -116,13 +220,15 @@ jobs:
# update DEFAULT_REQUIRED_CHECKS in scripts/verify-release-ci.ts.
server_test:
name: Server Test (${{ matrix.shard }}/${{ strategy.job-total }})
needs: [precheck]
if: ${{ !cancelled() && !(github.event_name == 'push' && needs.precheck.result == 'success' && needs.precheck.outputs.skip_ci == 'true') }}
runs-on: ubuntu-latest
timeout-minutes: 20
strategy:
# One failing shard still lets the others report their own failures.
fail-fast: false
matrix:
shard: [1, 2, 3]
shard: [1, 2, 3, 4]
steps:
- name: Checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
Expand Down Expand Up @@ -161,17 +267,17 @@ jobs:
# verification (scripts/verify-release-ci.ts) checks the jobs themselves.
quality_gate:
name: Format, Lint, Typecheck, Test, Build
if: ${{ always() }}
needs: [quality, unit_test, server_test]
if: ${{ always() && !(github.event_name == 'push' && needs.precheck.result == 'success' && needs.precheck.outputs.skip_ci == 'true') }}
needs: [precheck, quality, unit_test, server_test]
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- name: Require every job to pass
env:
RESULTS: ${{ toJSON(needs) }}
run: |
echo "$RESULTS" | jq -r 'to_entries[] | "\(.key): \(.value.result)"'
echo "$RESULTS" | jq -e 'all(.[]; .result == "success")' > /dev/null
echo "$RESULTS" | jq -r 'del(.precheck) | to_entries[] | "\(.key): \(.value.result)"'
echo "$RESULTS" | jq -e 'del(.precheck) | all(.[]; .result == "success")' > /dev/null

# The browser suite is CPU-bound (every spec renders the whole app), so one
# 4-core runner tops out at about two tabs' worth of work. Two shards on two
Expand All @@ -180,6 +286,8 @@ jobs:
# updates DEFAULT_REQUIRED_CHECKS in scripts/verify-release-ci.ts too.
browser:
name: Browser Test (${{ matrix.shard }}/${{ strategy.job-total }})
needs: [precheck]
if: ${{ !cancelled() && !(github.event_name == 'push' && needs.precheck.result == 'success' && needs.precheck.outputs.skip_ci == 'true') }}
runs-on: ubuntu-latest
timeout-minutes: 30
strategy:
Expand Down Expand Up @@ -265,20 +373,22 @@ jobs:
# name: it passes only when every browser shard passed.
browser_gate:
name: Browser Test
if: ${{ always() }}
needs: [browser]
if: ${{ always() && !(github.event_name == 'push' && needs.precheck.result == 'success' && needs.precheck.outputs.skip_ci == 'true') }}
needs: [precheck, browser]
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- name: Require every shard to pass
env:
RESULTS: ${{ toJSON(needs) }}
run: |
echo "$RESULTS" | jq -r 'to_entries[] | "\(.key): \(.value.result)"'
echo "$RESULTS" | jq -e 'all(.[]; .result == "success")' > /dev/null
echo "$RESULTS" | jq -r 'del(.precheck) | to_entries[] | "\(.key): \(.value.result)"'
echo "$RESULTS" | jq -e 'del(.precheck) | all(.[]; .result == "success")' > /dev/null

release_smoke:
name: Release Smoke
needs: [precheck]
if: ${{ !cancelled() && !(github.event_name == 'push' && needs.precheck.result == 'success' && needs.precheck.outputs.skip_ci == 'true') }}
runs-on: ubuntu-latest
# A lockfile change cold-starts the Vite+ cache: setup alone took ~8 minutes
# on #950 and the old 10-minute cap cut the job off while saving the cache.
Expand Down Expand Up @@ -306,6 +416,8 @@ jobs:
- quality_gate
- browser_gate
- release_smoke
if: github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main' && inputs.deploy == true
# Explicit status checks are required because `precheck` is a skipped
# transitive ancestor on workflow_dispatch (implicit success() would skip).
if: ${{ !cancelled() && needs.quality_gate.result == 'success' && needs.browser_gate.result == 'success' && needs.release_smoke.result == 'success' && github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main' && inputs.deploy == true }}
uses: ./.github/workflows/deploy-web.yml
secrets: inherit
95 changes: 78 additions & 17 deletions scripts/update-test-shard-weights.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,41 +38,96 @@ const repoRoot = NodeURL.fileURLToPath(new URL("..", import.meta.url));
const gh = (args: ReadonlyArray<string>): string =>
NodeChildProcess.execFileSync("gh", args, { cwd: repoRoot, encoding: "utf8" }).trim();

const CANDIDATE_RUNS_PER_EVENT = 15;

type ListedRun = {
readonly databaseId: number;
readonly createdAt: string;
readonly headSha: string;
readonly headBranch: string;
};

const isOnOriginMain = (sha: string): boolean => {
const result = NodeChildProcess.spawnSync(
"git",
["merge-base", "--is-ancestor", sha, "origin/main"],
{
cwd: repoRoot,
stdio: "ignore",
},
);
return result.status === 0;
};

const givenRunIds = process.argv.slice(3);
const runIds =
givenRunIds.length > 0
? givenRunIds
: gh([
let candidates: ReadonlyArray<{ readonly runId: string; readonly headSha?: string }>;
if (givenRunIds.length > 0) {
candidates = givenRunIds.map((runId) => ({ runId }));
} else {
// Fetch origin/main so we only sample merge_group runs whose commit actually
// landed on main (ignoring green queue runs that were later dequeued).
NodeChildProcess.execFileSync("git", ["fetch", "--quiet", "origin", "main"], { cwd: repoRoot });

const listRuns = (extraArgs: ReadonlyArray<string>): ReadonlyArray<ListedRun> =>
JSON.parse(
gh([
"run",
"list",
"--workflow=ci.yml",
"--branch=main",
"--event=push",
"--status=success",
`--limit=${RUNS_TO_READ}`,
"--json=databaseId",
"--jq=.[].databaseId",
])
.split("\n")
.filter(Boolean);
if (runIds.length === 0) {
throw new Error("Found no green CI run on main to read test timings from.");
`--limit=${CANDIDATE_RUNS_PER_EVENT}`,
"--json=databaseId,createdAt,headSha,headBranch",
...extraArgs,
]),
) as ReadonlyArray<ListedRun>;

// Query merge_group and main push separately so PR runs never crowd them out.
candidates = [
...listRuns(["--event=merge_group"]).filter(
(run) => run.headBranch.startsWith("gh-readonly-queue/main/") && isOnOriginMain(run.headSha),
),
...listRuns(["--branch=main", "--event=push"]),
]
.toSorted((a, b) => Date.parse(b.createdAt) - Date.parse(a.createdAt))
.map((run) => ({ runId: String(run.databaseId), headSha: run.headSha }));
}
if (candidates.length === 0) {
throw new Error("Found no green CI run on main or landed merge_group to read test timings from.");
}

const downloadDir = NodeFS.mkdtempSync(
NodePath.join(NodeOS.tmpdir(), "threadlines-shard-weights-"),
);
// One map of file -> seconds per run, newest run first.
const runs: Array<Map<string, number>> = [];
const sampledShas = new Set<string>();
try {
for (const runId of runIds) {
for (const { runId, headSha } of candidates) {
if (givenRunIds.length === 0 && runs.length >= RUNS_TO_READ) {
break;
}
if (headSha && sampledShas.has(headSha)) {
continue;
}
const runDir = NodePath.join(downloadDir, runId);
gh(["run", "download", runId, `--pattern=${suite.artifacts}`, `--dir=${runDir}`]);
try {
gh(["run", "download", runId, `--pattern=${suite.artifacts}`, `--dir=${runDir}`]);
} catch (error) {
// Skipped push runs on main upload no timings artifacts; keep scanning
// unless the caller explicitly asked for this run id.
if (givenRunIds.length > 0) {
throw error;
}
continue;
}
const reports = NodeFS.readdirSync(runDir, { recursive: true, encoding: "utf8" }).filter(
(entry) => NodePath.basename(entry) === TIMINGS_FILE,
);
if (reports.length === 0) {
throw new Error(`CI run ${runId} has no ${suiteName} test timings.`);
if (givenRunIds.length > 0) {
throw new Error(`CI run ${runId} has no ${suiteName} test timings.`);
}
continue;
}
const timings = new Map<string, number>();
for (const entry of reports) {
Expand All @@ -82,11 +137,17 @@ try {
for (const [file, seconds] of Object.entries(report)) timings.set(file, seconds);
}
runs.push(timings);
if (headSha) {
sampledShas.add(headSha);
}
console.log(`Read ${reports.length} shard reports from CI run ${runId}.`);
}
} finally {
NodeFS.rmSync(downloadDir, { recursive: true, force: true });
}
if (runs.length === 0) {
throw new Error(`Found no green CI run with ${suiteName} test timings.`);
}

const median = (values: ReadonlyArray<number>): number => {
const ordered = values.toSorted((a, b) => a - b);
Expand Down
Loading
Loading