ci(gates): merge job 셋이 의존성 캐시에서 설치를 시작하고 main만 저장한다

문제: merge job 셋은 runner의 새 컨테이너에서 매번 Node(GitHub
다운로드), corepack의 pnpm, 패키지 404개를 내려받고, pnpm 11은 lockfile
542개 항목의 공급망 정책을 레지스트리에 물어 검증한다. run 169에서 job마다
setup-node 11~18초, 설치 12~29초였고 설치 시간의 대부분은 정책 검증의
메타데이터 요청이었다(10.1~27.9초). FE-GATE-013의 시스템 컨테이너는 같은
설치를 한 번 더 한다. merge 25분 목표에 0.8분 모자랐다.

고친 것(권하는 안으로 정함 2026-11-13, 총괄):
- job 단계 `dependency-cache`를 더한다. setup-node 앞에서 Node toolcache와
  `/tmp/fe-dependency-cache`(corepack, pnpm store, pnpm 메타데이터 캐시)를
  `.nvmrc`·`pnpm-lock.yaml` 해시 키로 복원한다. main run은 actions/cache로
  복원·저장하고, 그 밖의 ref는 actions/cache/restore로 복원만 한다. pin은
  짝 백엔드의 JDK·Gradle·Trivy 캐시와 같다(v4.3.0).
- 생성기가 그 job에 `COREPACK_HOME`·`PNPM_CONFIG_STORE_DIR`·
  `PNPM_CONFIG_CACHE_DIR`를 주어 job의 모든 pnpm 호출이 같은 곳을 본다.
  frozen install 단계는 그대로이고 캐시와 관계없이 돈다.
- PR run은 main이 저장한 항목을 같은 키로 읽기만 한다. 저장할 수 있는
  actions/cache 단계는 `refs/heads/main` 조건 아래에만 있고, 그 밖의 ref가
  타는 actions/cache/restore에는 저장하는 post 단계가 없다(시험으로 고정).
- 계약: merge job 셋만 이 단계를 가진다(release·promotion·provider·main
  job은 거절, 단계 순서 고정에 반영). 그 env를 job이 따로 묶으면 거절한다.
  키 입력은 `config/repository-layout.json`의 새 집합
  `dependency-cache-key`(`.nvmrc`, `pnpm-lock.yaml`)에서 고른다.
- `scripts/run-in-system-container.sh`가 그 env가 있으면 store와 메타데이터
  캐시를 같은 경로로 컨테이너에 넘긴다. 없으면(desktop) 지금과 같다.
- 결정 색인, ci-quality-gates.md, O1 출처 문구를 총괄이 정한 말로 맞춘다.

버린 대안:
- CI 이미지에 의존성 굽기: 레지스트리 쓰기 토큰이 든다.
- 브랜치 run도 저장하기: 캐시 항목은 다음 run이 믿는 입력이다. pnpm은
  같은 lockfile의 공급망 검증 기록이 캐시에 있으면 다시 검증하지 않으므로,
  브랜치가 쓴 항목이 main의 검증을 건너뛰게 할 수 있다.
- `cache-hit`일 때 설치를 건너뛰기: 결과가 캐시 상태에 달린다.
- apt 글꼴 캐시: 캐시가 없을 때 새 패키지 버전이 깔려 시각 결과가 달라질
  수 있다.

위험·한계:
- PR run은 main이 같은 키(또는 restore-keys로 앞 항목)를 저장한 뒤에야
  hit한다. 이 PR 자신의 run은 비어서 시작한다.
- runner 캐시 저장소(5GB)는 짝 백엔드와 같이 쓴다. 항목 하나는 Node·store·
  메타데이터로 압축 전 약 0.7GB다. lockfile이 바뀔 때마다 새 항목이 생긴다.
- Node toolcache 경로(`/opt/hostedtoolcache`)가 job 이미지와 다르면 그
  부분만 효과가 없고 setup-node가 내려받는다.

검증(desktop):
- 설치 실험(같은 lockfile, 새 폴더): 빈 캐시 13.9·17.2초, 캐시 있음 1.6초,
  store 파일 40개·메타데이터 40개를 망가뜨린 캐시 3.6초(27개만 다시 받음).
  다섯 번 모두 node_modules 트리 해시가 같다. pnpm 11은 대문자
  `PNPM_CONFIG_STORE_DIR`·`PNPM_CONFIG_CACHE_DIR`를 읽는다.
- FE-GATE-013 흐름을 캐시 env로 재현: 빈 캐시 설치 13.7초, 캐시 설치
  2.6초, 시스템 컨테이너 안 설치 1.5초(`Recreating node_modules` 없음, 지금은
  31.3초). 그 실행의 FE-GATE-013은 provider 묶음 시험 하나가 손 timeout
  30초에 걸려 실패했다(캐시와 무관, PR #39가 고치는 문제).
- RED: 계약·생성기를 둔 채 gates.json에서 캐시 단계를 빼면 새 시험 6개
  실패. 키 입력을 코드에 직접 적은 첫 판은 repository-layout R2 시험이
  잡았다. GREEN: repository-layout·ci-workflow-generation 456개 통과,
  check:ci·check:types·eslint rc=0, verify:documentation rc=0, 노트북
  `scripts/verify.sh docs` OK.
This commit is contained in:
DongHyeonka
2026-11-13 08:26:13 +09:00
parent 574212225d
commit 7ed0af3d29
13 changed files with 390 additions and 15 deletions
+61 -4
View File
@@ -4,6 +4,7 @@ import path from "node:path";
import { z } from "zod";
import { DEPENDENCY_ADVISORIES_RECORD_PATH } from "../lib/dependency-advisories.ts";
import { selectRepositoryPaths } from "../lib/repository-layout.ts";
import { PROMOTION_FORMULA } from "../lib/promotion-readiness.ts";
import {
RELEASE_CANDIDATE_EVIDENCE_PATHS,
@@ -39,6 +40,7 @@ const ciActionRegistrySchema = z
setupNode: ciActionRegistrationSchema,
uploadArtifact: ciActionRegistrationSchema,
downloadArtifact: ciActionRegistrationSchema,
cache: ciActionRegistrationSchema,
})
.strict()
.readonly();
@@ -78,6 +80,12 @@ export const CI_ACTION_REGISTRY = parseCiActionRegistry({
revision: "75635f32b4c1c41c4b3d64e8f85210112ed4c9c7",
version: "v4 branch",
},
// The same pin as the paired backend's JDK, Gradle and Trivy caches.
cache: {
repository: "https://github.com/actions/cache",
revision: "0057852bfaa89a56745cba8c7296529d2fc39830",
version: "v4.3.0",
},
});
const actionIdByStepKind = Object.freeze({
@@ -85,6 +93,7 @@ const actionIdByStepKind = Object.freeze({
"setup-node": "setupNode",
upload: "uploadArtifact",
download: "downloadArtifact",
"dependency-cache": "cache",
} as const satisfies Readonly<Record<string, CiActionId>>);
export function resolveCiActionUses(actionId: CiActionId): string {
@@ -93,6 +102,42 @@ export function resolveCiActionUses(actionId: CiActionId): string {
return `${action.repository}@${action.revision}`;
}
/** An action a registered repository holds below its root (`actions/cache/restore`), at the same pin. */
export function resolveCiSubActionUses(actionId: CiActionId, subpath: "restore"): string {
const action = CI_ACTION_REGISTRY[actionId];
if (!action) throw new TypeError(`unknown CI action: ${String(actionId)}`);
return `${action.repository}/${subpath}@${action.revision}`;
}
/**
* Decision (2026-11-13, lead): the dependency cache is for the merge jobs
* only; the jobs that produce supply-chain evidence install fresh every time
* (docs/work/reference/decisions.md). A merge job restores the Node toolcache, the corepack
* download and pnpm's store and metadata cache (with its record of the
* lockfile's supply-chain verification) before setup-node, keyed by
* `.nvmrc` and the lockfile. Only a run on main saves an entry, the paired
* backend's rule for its caches: an entry is trusted input to the next run
* (the verification record lets pnpm skip the check), so a branch must not
* write one. The frozen install always runs after it: a missing or damaged
* entry only makes pnpm download what it lacks, and node_modules is the same
* (desktop, 2026-11-13: cold 13.9 s, warm 1.6 s, 40 broken store and 40
* broken metadata files 3.6 s with 27 packages fetched again; the same tree
* hash in all five installs).
*/
export const DEPENDENCY_CACHE = Object.freeze({
keyPrefix: "fe-dependencies-${{ runner.os }}-${{ runner.arch }}-",
// `.nvmrc` and `pnpm-lock.yaml` (config/repository-layout.json).
keyInputs: selectRepositoryPaths("dependency-cache-key"),
paths: Object.freeze(["/opt/hostedtoolcache/node", "/tmp/fe-dependency-cache"] as const),
environment: Object.freeze([
Object.freeze({ name: "COREPACK_HOME", value: "/tmp/fe-dependency-cache/corepack" }),
Object.freeze({ name: "PNPM_CONFIG_STORE_DIR", value: "/tmp/fe-dependency-cache/pnpm-store" }),
Object.freeze({ name: "PNPM_CONFIG_CACHE_DIR", value: "/tmp/fe-dependency-cache/pnpm-cache" }),
]),
/** The jobs that may hold the step: the three merge jobs. */
jobIds: Object.freeze(["merge_static", "merge_test", "merge_browser"] as const),
});
export function resolveCiStepActionUses(stepKind: string): string | null {
const actionId = actionIdByStepKind[stepKind as keyof typeof actionIdByStepKind];
return actionId ? resolveCiActionUses(actionId) : null;
@@ -333,6 +378,7 @@ const environmentBindingSchema = z
const checkoutStep = z.object({ kind: z.literal("checkout") }).strict();
const setupNodeStep = z.object({ kind: z.literal("setup-node") }).strict();
const frozenInstallStep = z.object({ kind: z.literal("frozen-install") }).strict();
const dependencyCacheStep = z.object({ kind: z.literal("dependency-cache") }).strict();
/**
* `image`: the job runs in Playwright's own image for the pinned
* @playwright/test version, which already holds the browsers and their OS
@@ -405,6 +451,7 @@ const deployStep = z
const jobStepSchema = z.discriminatedUnion("kind", [
checkoutStep,
dependencyCacheStep,
setupNodeStep,
frozenInstallStep,
browserInstallStep,
@@ -817,6 +864,16 @@ function validateContractSemantics(
}
}
validateJobStepKinds(job, issue);
if (job.steps.some(({ kind }) => kind === "dependency-cache")) {
if (!(DEPENDENCY_CACHE.jobIds as readonly string[]).includes(job.id)) {
issue(`the dependency cache is for the merge jobs only: ${job.id}`);
}
for (const { name } of DEPENDENCY_CACHE.environment) {
if (job.environment.some((binding) => binding.name === name)) {
issue(`job ${job.id} binds ${name}, which its dependency cache sets`);
}
}
}
for (const step of job.steps) {
const uses = resolveCiStepActionUses(step.kind);
if (uses && !/^https:\/\/github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+@[0-9a-f]{40}$/u.test(uses)) {
@@ -910,9 +967,9 @@ function validateContractSemantics(
}
}
const expectedStepKinds: Readonly<Record<string, readonly CiWorkflowStep["kind"][]>> = {
merge_static: ["checkout", "setup-node", "frozen-install", "run-gate", "upload"],
merge_test: ["checkout", "setup-node", "frozen-install", "run-gate", "upload"],
merge_browser: ["checkout", "setup-node", "frozen-install", "browser-install", "run-gate", "upload"],
merge_static: ["checkout", "dependency-cache", "setup-node", "frozen-install", "run-gate", "upload"],
merge_test: ["checkout", "dependency-cache", "setup-node", "frozen-install", "run-gate", "upload"],
merge_browser: ["checkout", "dependency-cache", "setup-node", "frozen-install", "browser-install", "run-gate", "upload"],
release_gate: ["checkout", "setup-node", "frozen-install", "browser-install", "run-gate", "upload"],
immutable_build: ["checkout", "setup-node", "frozen-install", "run-gate", "archive-candidate", "upload", "upload"],
vulnerability_provider: ["checkout", "setup-node", "frozen-install", "download", "run-provider", "validate-provider-evidence", "upload"],
@@ -1324,7 +1381,7 @@ function validateJobStepKinds(
): void {
const allowed: Readonly<Record<z.infer<typeof jobSchema>["kind"], ReadonlySet<string>>> = {
"gate-matrix": new Set(["checkout", "setup-node", "frozen-install", "browser-install", "download", "extract", "run-gate", "upload"]),
"gate-sequence": new Set(["checkout", "setup-node", "frozen-install", "browser-install", "run-gate", "upload"]),
"gate-sequence": new Set(["checkout", "dependency-cache", "setup-node", "frozen-install", "browser-install", "run-gate", "upload"]),
"gate-single": new Set(["checkout", "setup-node", "frozen-install", "run-gate", "upload"]),
immutable: new Set(["checkout", "setup-node", "frozen-install", "run-gate", "archive-candidate", "upload"]),
provider: new Set(["checkout", "setup-node", "frozen-install", "download", "extract", "run-provider", "validate-provider-evidence", "upload"]),
+33 -1
View File
@@ -11,9 +11,11 @@ import { fileURLToPath } from "node:url";
import path from "node:path";
import {
DEPENDENCY_CACHE,
indexCiGateContract,
loadCiGateContract,
resolveCiStepActionUses,
resolveCiSubActionUses,
type CiGateContract,
type CiWorkflowJob,
type CiWorkflowStep,
@@ -234,9 +236,16 @@ function renderJob(
const jobEnvironment = job.environment.filter((binding) => !isStepScopedSecret(job, binding));
// The build records the image it ran in (scripts/lib/build-environment.ts):
// a job in its own image names that one, not the runner label's.
// Every pnpm and corepack call of the job reads the cached directories, the
// install and the system container's own install alike.
const cacheEnvironment = job.steps.some(({ kind }) => kind === "dependency-cache")
? DEPENDENCY_CACHE.environment
: [];
const environmentLines = [
...(image ? [` CI_RUNNER_IMAGE: ${yamlScalar(image)}`] : []),
...jobEnvironment.map((binding) => ` ${binding.name}: ${yamlScalar(binding.value)}`),
...[...cacheEnvironment, ...jobEnvironment].map(
(binding) => ` ${binding.name}: ${yamlScalar(binding.value)}`,
),
];
if (environmentLines.length > 0) lines.push(" env:", ...environmentLines);
if (job.kind === "gate-matrix") {
@@ -316,6 +325,29 @@ function renderStep(
" with:",
" node-version-file: .nvmrc",
];
case "dependency-cache": {
// DEPENDENCY_CACHE: main restores and saves, every other ref restores.
// The frozen install after it runs either way.
const inputs = DEPENDENCY_CACHE.keyInputs.map((file) => `'${file}'`).join(", ");
const cache = [
" with:",
" path: |",
...DEPENDENCY_CACHE.paths.map((cachePath) => ` ${cachePath}`),
` key: ${DEPENDENCY_CACHE.keyPrefix}\${{ hashFiles(${inputs}) }}`,
" restore-keys: |",
` ${DEPENDENCY_CACHE.keyPrefix}`,
];
return [
" - name: Restore and save the dependency cache",
" if: ${{ gitea.ref == 'refs/heads/main' }}",
` uses: ${requiredStepActionUses(step.kind)}`,
...cache,
" - name: Restore the dependency cache",
" if: ${{ gitea.ref != 'refs/heads/main' }}",
` uses: ${resolveCiSubActionUses("cache", "restore")}`,
...cache,
];
}
case "frozen-install":
return [
" - name: Frozen install",
+1
View File
@@ -32,6 +32,7 @@ export const REPOSITORY_LAYOUT_SETS = Object.freeze([
"feature-typecheck",
"product-typecheck",
"app-typecheck",
"dependency-cache-key",
] as const);
export type RepositoryLayoutSet = (typeof REPOSITORY_LAYOUT_SETS)[number];
+13
View File
@@ -25,6 +25,15 @@ node_root=$(dirname "$(dirname "$(command -v node)")")
corepack_home=${COREPACK_HOME:-$HOME/.cache/node/corepack}
# The environment the gate reads (scripts/verify.sh ci_env, the workflow's global env).
pass_env=(CI VITE_BUILD_ID VITE_COMMIT_SHA RELEASE_ID CI_RUNNER_IMAGE SOURCE_DATE_EPOCH APP_PROFILE RELEASE_TARGET)
# A merge job's dependency cache (scripts/contracts/ci-gates.ts DEPENDENCY_CACHE): pnpm's store and metadata
# cache go in at the same paths, so the install in here reuses what the job's install fetched.
pnpm_dirs=()
for name in PNPM_CONFIG_STORE_DIR PNPM_CONFIG_CACHE_DIR; do
if [ -n "${!name:-}" ] && [ -d "${!name}" ]; then
pass_env+=("$name")
pnpm_dirs+=("${!name}")
fi
done
say() { echo "system-container: $*" >&2; }
fail() { say "$*"; exit 3; }
@@ -68,6 +77,10 @@ else
fi
tar -C "$node_root" -cf - . | $docker exec -i "$cid" sh -c 'mkdir -p /opt/node && tar -C /opt/node --no-same-owner -xf -' \
|| fail "copying node failed"
for dir in "${pnpm_dirs[@]}"; do
tar -C "$dir" -cf - . | $docker exec -i "$cid" sh -c "mkdir -p '$dir' && tar -C '$dir' --no-same-owner -xf -" \
|| fail "copying $dir failed"
done
if [ -d "$corepack_home" ]; then
tar -C "$corepack_home" -cf - . | $docker exec -i "$cid" sh -c 'mkdir -p /opt/corepack && tar -C /opt/corepack --no-same-owner -xf -' \
|| fail "copying the corepack cache failed"