From 46dfe23f699a756efed2ca40ee91b3b4a8fec85a Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 20:22:27 +0900 Subject: [PATCH 01/12] =?UTF-8?q?fix(bundle):=20=EC=98=88=EC=82=B0?= =?UTF-8?q?=EC=9D=84=20=EB=84=98=EC=9C=BC=EB=A9=B4=20=EB=84=98=EC=9D=80=20?= =?UTF-8?q?=ED=95=9C=EB=8F=84=EC=99=80=20=EC=B4=88=EA=B3=BC=EB=9F=89?= =?UTF-8?q?=EC=9D=84=20=EC=B6=9C=EB=A0=A5=ED=95=98=EA=B3=A0=20=EC=B4=88?= =?UTF-8?q?=EA=B8=B0=20=ED=8C=8C=EC=9D=BC=20=EC=88=98=EB=A5=BC=20=EB=A7=89?= =?UTF-8?q?=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 초기 JS가 예산을 넘으면 check:bundle은 "Bundle budget or manifest integrity failed: " 한 줄만 쓰고 콜론 뒤가 비어 있었다. 측정값과 한도는 artifacts/performance/bundle.json에만 있어 예산 실패인지 manifest 무결성 실패인지, 몇 바이트 넘었는지 알 수 없었다. 또 초기 JS 파일 수에는 상한이 없어 08-08처럼 파일을 16개에서 25개로 늘리는 변경도 모든 게이트를 통과했다. 템플릿은 HTTP/2를 전제로 초기 청크를 나눠 두었는데, 파일 수를 늘리는 결정이 어디에도 드러나지 않았다. 고른 방법: 예산 실패와 무결성 실패를 다른 문장으로 쓴다. 예산 실패는 넘은 한도마다 측정값·한도·초과량을 한 줄로 쓴다 (describeBundleBudgetFailures). config/performance/budgets.json에 initialJsFiles(지금 25)를 두고 check:bundle이 entry를 포함한 초기 파일 수를 센다. bundle.json 스키마는 측정값·한도·결과와 자가 검사 fixture를 하나씩 더 가진다. 두 변경은 같은 함수와 스키마를 고치므로 한 커밋에 넣었다. 버린 대안: 파일 수를 문서에만 적기. 08-08이 그 상태에서 파일을 늘렸다. 위험·한계: 초기 파일을 하나라도 늘리는 변경은 이제 budgets.json을 같이 고쳐야 통과한다. 그것이 목적이다. HTTP/2 확인 자체는 이 커밋에 없다 (13-02에서 probe에 넣는다). 검증: tests/unit/check-bundle-output.test.ts가 손으로 만든 빌드 출력에 check-bundle.ts를 돌려 통과·초기 바이트 초과·lazy 초과·파일 수 초과· 무결성 실패의 출력을 본다(고치기 전 4건 실패). bundle-artifact-contract, performance-budgets 통과. 실제 빌드에서 check:bundle PASS(25 / 25 files). Refs: docs/reviews/2026-11-03-maturity-review/15-performance.md 15-03, 15-05 --- config/performance/budgets.json | 1 + docs/operations/performance-evidence.md | 8 +- scripts/check-bundle.ts | 57 +++++++-- scripts/contracts/release-artifacts.ts | 16 ++- scripts/lib/performance-budgets.ts | 38 +++++- tests/unit/bundle-artifact-contract.test.ts | 9 +- tests/unit/check-bundle-output.test.ts | 128 ++++++++++++++++++++ tests/unit/performance-budgets.test.ts | 10 +- 8 files changed, 251 insertions(+), 16 deletions(-) create mode 100644 tests/unit/check-bundle-output.test.ts diff --git a/config/performance/budgets.json b/config/performance/budgets.json index adf9cc73..495e8a98 100644 --- a/config/performance/budgets.json +++ b/config/performance/budgets.json @@ -2,6 +2,7 @@ "schemaVersion": 1, "bundle": { "initialJsGzipBytes": 204800, + "initialJsFiles": 25, "lazyChunkGzipBytes": 122880 }, "lab": { diff --git a/docs/operations/performance-evidence.md b/docs/operations/performance-evidence.md index 6bf1c888..16e5cc36 100644 --- a/docs/operations/performance-evidence.md +++ b/docs/operations/performance-evidence.md @@ -3,7 +3,9 @@ Performance evidence is deliberately split by measurement context: - `bundle.json` records production build output and enforces initial JavaScript - at 200 KiB gzip and every lazy chunk at 120 KiB gzip. + at 200 KiB gzip, the number of initial JavaScript files (`initialJsFiles`), + and every lazy chunk at 120 KiB gzip. A failure names each exceeded limit, + the measured value and the excess (1103/15-03). - `lab.json` records Chromium/runner/viewport/network/CPU/cache/build context and enforces LCP 2.5 s, CLS 0.10, and the named route interaction at 200 ms. - `field-web-vitals.json` records consent-filtered, route-ID aggregated, @@ -154,6 +156,8 @@ the example can never serve as production evidence. 버렸다. - HTTP/2에서는 (나)도 Fast 3G 85 ms, Fast 4G 22 ms 차이다(위 둘째 표). -그래서 템플릿은 HTTP/2 이상으로 서빙한다고 본다. HTTP/1.1로만 서빙해야 하는 +그래서 템플릿은 HTTP/2 이상으로 서빙한다고 본다. 초기 파일 수는 +`config/performance/budgets.json`의 `initialJsFiles`가 막는다(1103/15-05). 초기 +파일을 늘리는 변경은 그 값을 같이 고치고, 이유를 같은 변경에 적는다. HTTP/1.1로만 서빙해야 하는 제품은 (나)처럼 초기 청크를 묶는 그룹을 `vite.config.ts`에 넣는다. 그 목록은 셸을 바꿀 때마다 위 방법으로 다시 잰다. diff --git a/scripts/check-bundle.ts b/scripts/check-bundle.ts index 64223b20..bbd9fb9e 100644 --- a/scripts/check-bundle.ts +++ b/scripts/check-bundle.ts @@ -1,6 +1,9 @@ import { readFile } from "node:fs/promises"; -import { evaluateBundleBudget } from "./lib/performance-budgets.ts"; +import { + describeBundleBudgetFailures, + evaluateBundleBudget, +} from "./lib/performance-budgets.ts"; import { bundleOutputInventoryArtifactSchema, bundlePerformanceArtifactSchema, @@ -14,6 +17,7 @@ type ViteManifest = Record< >; type BundleBudgets = { initialJsGzipBytes: number; + initialJsFiles: number; lazyChunkGzipBytes: number; }; @@ -43,7 +47,11 @@ const missingOutputs = [ ...classification.initialFiles, ...classification.lazyFiles, ].filter((file) => !outputByPath.has(file)); -const measurements = { initialJsGzipBytes, lazyChunks }; +const measurements = { + initialJsGzipBytes, + initialJsFiles: classification.initialFiles.length, + lazyChunks, +}; const result = evaluateBundleBudget(measurements, budgets); const fixtures = [ { @@ -52,6 +60,7 @@ const fixtures = [ !evaluateBundleBudget( { initialJsGzipBytes: budgets.initialJsGzipBytes + 1, + initialJsFiles: 0, lazyChunks: [], }, budgets, @@ -63,6 +72,7 @@ const fixtures = [ !evaluateBundleBudget( { initialJsGzipBytes: 0, + initialJsFiles: 0, lazyChunks: [ { path: "fixture.js", @@ -73,6 +83,18 @@ const fixtures = [ budgets, ).passed, }, + { + name: "initial-files-over-budget", + passed: + !evaluateBundleBudget( + { + initialJsGzipBytes: 0, + initialJsFiles: budgets.initialJsFiles + 1, + lazyChunks: [], + }, + budgets, + ).passed, + }, ]; const passed = result.passed && @@ -95,15 +117,32 @@ await writeValidatedJsonArtifact({ schema: bundlePerformanceArtifactSchema, value: completedReport, }); +// 1103/15-03. The budget and the manifest integrity fail for different +// reasons, so each says what failed and by how much. if (!passed) { - process.stderr.write( - `Bundle budget or manifest integrity failed: ${[ - ...classification.missingImports, - ...missingOutputs, - ].join(", ")}\n`, - ); + const budgetFailures = describeBundleBudgetFailures(measurements, budgets); + if (budgetFailures.length > 0) { + process.stderr.write( + `Bundle budget failed (config/performance/budgets.json):\n${budgetFailures + .map((line) => ` ${line}\n`) + .join("")}`, + ); + } + const integrityFailures = [ + ...classification.missingImports.map((key) => `manifest import without an entry: ${key}`), + ...missingOutputs.map((file) => `output missing from the inventory: ${file}`), + ...fixtures + .filter((fixture) => !fixture.passed) + .map((fixture) => `budget self-check did not fail: ${fixture.name}`), + ]; + if (integrityFailures.length > 0) { + process.stderr.write( + `Bundle manifest integrity failed:\n${integrityFailures.map((line) => ` ${line}\n`).join("")}`, + ); + } process.exit(1); } process.stdout.write( - `Bundle budget: PASS (initial JS ${initialJsGzipBytes} / ${budgets.initialJsGzipBytes} gzip bytes)\n`, + `Bundle budget: PASS (initial JS ${initialJsGzipBytes} / ${budgets.initialJsGzipBytes} gzip bytes, ` + + `${measurements.initialJsFiles} / ${budgets.initialJsFiles} files)\n`, ); diff --git a/scripts/contracts/release-artifacts.ts b/scripts/contracts/release-artifacts.ts index d70ed79a..7891ff28 100644 --- a/scripts/contracts/release-artifacts.ts +++ b/scripts/contracts/release-artifacts.ts @@ -364,12 +364,14 @@ const bundleClassificationSchema = z const bundleThresholdsSchema = z .object({ initialJsGzipBytes: z.int().positive(), + initialJsFiles: z.int().positive(), lazyChunkGzipBytes: z.int().positive(), }) .strict(); const bundleBudgetResultSchema = z .object({ initialPassed: z.boolean(), + initialFilesPassed: z.boolean(), lazyResults: z.array( bundleMeasurementSchema.extend({ threshold: z.int().positive(), @@ -386,6 +388,7 @@ export const bundlePerformanceArtifactSchema = z measurements: z .object({ initialJsGzipBytes: z.int().nonnegative(), + initialJsFiles: z.int().nonnegative(), lazyChunks: z.array(bundleMeasurementSchema), }) .strict(), @@ -396,6 +399,7 @@ export const bundlePerformanceArtifactSchema = z fixtures: z.tuple([ z.object({ name: z.literal("initial-js-over-budget"), passed: z.boolean() }).strict(), z.object({ name: z.literal("lazy-chunk-over-budget"), passed: z.boolean() }).strict(), + z.object({ name: z.literal("initial-files-over-budget"), passed: z.boolean() }).strict(), ]), passed: z.boolean(), }) @@ -441,6 +445,9 @@ export const bundlePerformanceArtifactSchema = z if (artifact.measurements.initialJsGzipBytes !== expectedInitialBytes) { issue(["measurements", "initialJsGzipBytes"], "must equal classified initial output bytes"); } + if (artifact.measurements.initialJsFiles !== artifact.classification.initialFiles.length) { + issue(["measurements", "initialJsFiles"], "must equal the classified initial file count"); + } const expectedLazyChunks = artifact.classification.lazyFiles.map((file) => ({ path: file, gzipBytes: outputs.get(file)?.gzipBytes ?? 0, @@ -453,6 +460,11 @@ export const bundlePerformanceArtifactSchema = z if (artifact.results.initialPassed !== expectedInitialPassed) { issue(["results", "initialPassed"], "must agree with initial threshold"); } + const expectedInitialFilesPassed = + artifact.measurements.initialJsFiles <= artifact.thresholds.initialJsFiles; + if (artifact.results.initialFilesPassed !== expectedInitialFilesPassed) { + issue(["results", "initialFilesPassed"], "must agree with the initial file threshold"); + } const expectedLazyResults = artifact.measurements.lazyChunks.map((chunk) => ({ ...chunk, threshold: artifact.thresholds.lazyChunkGzipBytes, @@ -462,7 +474,9 @@ export const bundlePerformanceArtifactSchema = z issue(["results", "lazyResults"], "must agree with lazy measurements and threshold"); } const expectedBudgetPassed = - expectedInitialPassed && expectedLazyResults.every(({ passed }) => passed); + expectedInitialPassed && + expectedInitialFilesPassed && + expectedLazyResults.every(({ passed }) => passed); if (artifact.results.passed !== expectedBudgetPassed) { issue(["results", "passed"], "must agree with budget results"); } diff --git a/scripts/lib/performance-budgets.ts b/scripts/lib/performance-budgets.ts index d6caac34..b2bf26b1 100644 --- a/scripts/lib/performance-budgets.ts +++ b/scripts/lib/performance-budgets.ts @@ -1,10 +1,18 @@ export type BundleMeasurements = Readonly<{ initialJsGzipBytes: number; + initialJsFiles: number; lazyChunks: readonly Readonly<{ path: string; gzipBytes: number }>[]; }>; +/** + * 1103/15-05. `initialJsFiles` bounds the number of initial JavaScript files + * (entry included). The entry preloads them in parallel, which costs no round + * trip over HTTP/2 and queues them six at a time over HTTP/1.1 + * (docs/operations/performance-evidence.md, "초기 청크 수와 HTTP/1.1"). + */ export type BundleThresholds = Readonly<{ initialJsGzipBytes: number; + initialJsFiles: number; lazyChunkGzipBytes: number; }>; @@ -14,6 +22,7 @@ export function evaluateBundleBudget( ) { const initialPassed = measurements.initialJsGzipBytes <= thresholds.initialJsGzipBytes; + const initialFilesPassed = measurements.initialJsFiles <= thresholds.initialJsFiles; const lazyResults = measurements.lazyChunks.map((chunk) => ({ ...chunk, threshold: thresholds.lazyChunkGzipBytes, @@ -21,11 +30,38 @@ export function evaluateBundleBudget( })); return Object.freeze({ initialPassed, + initialFilesPassed, lazyResults: Object.freeze(lazyResults), - passed: initialPassed && lazyResults.every((chunk) => chunk.passed), + passed: initialPassed && initialFilesPassed && lazyResults.every((chunk) => chunk.passed), }); } +/** + * 1103/15-03. One line per exceeded limit with the measured value, the limit + * and the excess, so a failed check:bundle says what to cut without opening + * artifacts/performance/bundle.json. + */ +export function describeBundleBudgetFailures( + measurements: BundleMeasurements, + thresholds: BundleThresholds, +): string[] { + const over = (label: string, measured: number, limit: number, unit = " gzip bytes") => + `${label} ${measured}${unit} > budget ${limit} (over by ${measured - limit})`; + const lines: string[] = []; + if (measurements.initialJsGzipBytes > thresholds.initialJsGzipBytes) { + lines.push(over("initial JavaScript", measurements.initialJsGzipBytes, thresholds.initialJsGzipBytes)); + } + if (measurements.initialJsFiles > thresholds.initialJsFiles) { + lines.push(over("initial JavaScript files", measurements.initialJsFiles, thresholds.initialJsFiles, "")); + } + for (const chunk of measurements.lazyChunks) { + if (chunk.gzipBytes > thresholds.lazyChunkGzipBytes) { + lines.push(over(`lazy chunk ${chunk.path}`, chunk.gzipBytes, thresholds.lazyChunkGzipBytes)); + } + } + return lines; +} + export type LabMetrics = Readonly<{ lcpMs: number; cls: number; diff --git a/tests/unit/bundle-artifact-contract.test.ts b/tests/unit/bundle-artifact-contract.test.ts index 478c2a70..cb42caf9 100644 --- a/tests/unit/bundle-artifact-contract.test.ts +++ b/tests/unit/bundle-artifact-contract.test.ts @@ -28,6 +28,7 @@ const completed = { ...inventory, measurements: { initialJsGzipBytes: 50, + initialJsFiles: 1, lazyChunks: [{ path: "assets/lazy.js", gzipBytes: 40 }], }, classification: { @@ -36,9 +37,10 @@ const completed = { missingImports: [], }, missingOutputs: [], - thresholds: { initialJsGzipBytes: 60, lazyChunkGzipBytes: 45 }, + thresholds: { initialJsGzipBytes: 60, initialJsFiles: 1, lazyChunkGzipBytes: 45 }, results: { initialPassed: true, + initialFilesPassed: true, lazyResults: [ { path: "assets/lazy.js", gzipBytes: 40, threshold: 45, passed: true }, ], @@ -47,6 +49,7 @@ const completed = { fixtures: [ { name: "initial-js-over-budget", passed: true }, { name: "lazy-chunk-over-budget", passed: true }, + { name: "initial-files-over-budget", passed: true }, ], passed: true, } as const; @@ -64,8 +67,10 @@ describe("bundle artifact contracts", () => { ["lazy classification", { classification: { ...completed.classification, lazyFiles: [] } }], ["missing output", { missingOutputs: ["assets/missing.js"], passed: true }], ["threshold result", { results: { ...completed.results, initialPassed: false } }], + ["initial file count", { measurements: { ...completed.measurements, initialJsFiles: 2 } }], + ["initial file result", { results: { ...completed.results, initialFilesPassed: false } }], ["lazy result", { results: { ...completed.results, lazyResults: [] } }], - ["fixture identity", { fixtures: [{ name: "other", passed: true }, completed.fixtures[1]] }], + ["fixture identity", { fixtures: [{ name: "other", passed: true }, completed.fixtures[1], completed.fixtures[2]] }], ["overall result", { passed: false }], ] as const)("rejects inconsistent %s evidence", (_name, mutation) => { expect(() => diff --git a/tests/unit/check-bundle-output.test.ts b/tests/unit/check-bundle-output.test.ts new file mode 100644 index 00000000..f5dd42ee --- /dev/null +++ b/tests/unit/check-bundle-output.test.ts @@ -0,0 +1,128 @@ +import { spawnSync } from "node:child_process"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +import { afterEach, describe, expect, it } from "vitest"; + +/** + * 1103/15-03. An over-budget build printed only + * "Bundle budget or manifest integrity failed: " with nothing after the + * colon, so the first budget failure a project meets named neither the limit + * nor the excess. check-bundle runs here on a hand-made build output. + */ +const roots: string[] = []; + +afterEach(async () => { + await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))); +}); + +type Output = Readonly<{ path: string; gzipBytes: number }>; + +async function checkBundle( + options: Readonly<{ + outputs: readonly Output[]; + manifest: Record; + budgets: Record; + }>, +) { + const root = await mkdtemp(path.join(tmpdir(), "check-bundle-output-")); + roots.push(root); + const write = async (file: string, value: unknown) => { + await mkdir(path.dirname(path.join(root, file)), { recursive: true }); + await writeFile(path.join(root, file), `${JSON.stringify(value, null, 2)}\n`); + }; + await write("config/performance/budgets.json", { schemaVersion: 1, bundle: options.budgets }); + await write("dist/.vite/manifest.json", options.manifest); + await write("artifacts/performance/bundle.json", { + schemaVersion: 1, + generatedAt: "2026-11-04T00:00:00.000Z", + context: { nodeVersion: "v24.14.0", packageManager: "pnpm@11.17.0", runnerImage: "fixture" }, + outputs: options.outputs.map((output) => ({ + path: `dist/${output.path}`, + bytes: output.gzipBytes * 3, + gzipBytes: output.gzipBytes, + sha256: "a".repeat(64), + })), + }); + const result = spawnSync(process.execPath, [path.resolve("scripts/check-bundle.ts")], { + cwd: root, + encoding: "utf8", + }); + return { status: result.status, stdout: result.stdout, stderr: result.stderr }; +} + +const MANIFEST = { + "index.html": { + file: "assets/index-A.js", + isEntry: true, + imports: ["_boot"], + }, + // The entry's own dynamic imports are initial (09-03); a route's are lazy. + _boot: { file: "assets/boot-B.js", dynamicImports: ["src/lazy.tsx"] }, + "src/lazy.tsx": { file: "assets/lazy-C.js" }, +}; +const OUTPUTS = [ + { path: "assets/index-A.js", gzipBytes: 400 }, + { path: "assets/boot-B.js", gzipBytes: 500 }, + { path: "assets/lazy-C.js", gzipBytes: 300 }, +]; +const BUDGETS = { initialJsGzipBytes: 1_000, initialJsFiles: 2, lazyChunkGzipBytes: 400 }; + +describe("check:bundle failure output (1103/15-03)", () => { + it("passes and prints the total within budget", async () => { + const result = await checkBundle({ outputs: OUTPUTS, manifest: MANIFEST, budgets: BUDGETS }); + expect(result.stderr).toBe(""); + expect(result.status).toBe(0); + expect(result.stdout).toContain("initial JS 900 / 1000 gzip bytes"); + }); + + it("names the measured initial total, the budget and the excess", async () => { + const result = await checkBundle({ + outputs: OUTPUTS, + manifest: MANIFEST, + budgets: { ...BUDGETS, initialJsGzipBytes: 899 }, + }); + expect(result.status).toBe(1); + expect(result.stderr).toContain("Bundle budget failed (config/performance/budgets.json):"); + expect(result.stderr).toContain("initial JavaScript 900 gzip bytes > budget 899 (over by 1)"); + expect(result.stderr).not.toContain("manifest integrity"); + }); + + it("names each lazy chunk over its budget", async () => { + const result = await checkBundle({ + outputs: OUTPUTS, + manifest: MANIFEST, + budgets: { ...BUDGETS, lazyChunkGzipBytes: 250 }, + }); + expect(result.status).toBe(1); + expect(result.stderr).toContain( + "lazy chunk assets/lazy-C.js 300 gzip bytes > budget 250 (over by 50)", + ); + }); + + // 1103/15-05. The entry preloads every initial file at once; over HTTP/1.1 + // they queue for six connections. A change that adds an initial file is a + // decision recorded in the budget, not a side effect. + it("fails when the initial JavaScript has more files than the budget", async () => { + const result = await checkBundle({ + outputs: OUTPUTS, + manifest: MANIFEST, + budgets: { ...BUDGETS, initialJsFiles: 1 }, + }); + expect(result.status).toBe(1); + expect(result.stderr).toContain("initial JavaScript files 2 > budget 1 (over by 1)"); + }); + + it("reports a manifest integrity failure apart from the budget", async () => { + const result = await checkBundle({ + outputs: OUTPUTS.filter(({ path: file }) => file !== "assets/boot-B.js"), + manifest: MANIFEST, + budgets: BUDGETS, + }); + expect(result.status).toBe(1); + expect(result.stderr).toContain("Bundle manifest integrity failed:"); + expect(result.stderr).toContain("output missing from the inventory: assets/boot-B.js"); + expect(result.stderr).not.toContain("Bundle budget failed"); + }); +}); diff --git a/tests/unit/performance-budgets.test.ts b/tests/unit/performance-budgets.test.ts index 8d33d5d8..7cff0612 100644 --- a/tests/unit/performance-budgets.test.ts +++ b/tests/unit/performance-budgets.test.ts @@ -11,11 +11,12 @@ describe("performance budgets", () => { it("rejects initial and lazy JavaScript above their named limits", () => { const thresholds = { initialJsGzipBytes: 200, + initialJsFiles: 2, lazyChunkGzipBytes: 120, }; expect( evaluateBundleBudget( - { initialJsGzipBytes: 201, lazyChunks: [] }, + { initialJsGzipBytes: 201, initialJsFiles: 1, lazyChunks: [] }, thresholds, ).passed, ).toBe(false); @@ -23,11 +24,18 @@ describe("performance budgets", () => { evaluateBundleBudget( { initialJsGzipBytes: 100, + initialJsFiles: 1, lazyChunks: [{ path: "lazy.js", gzipBytes: 121 }], }, thresholds, ).passed, ).toBe(false); + expect( + evaluateBundleBudget( + { initialJsGzipBytes: 100, initialJsFiles: 3, lazyChunks: [] }, + thresholds, + ), + ).toMatchObject({ initialPassed: true, initialFilesPassed: false, passed: false }); }); it("fails lab evidence when context is absent or a metric is over budget", () => { From af6d0a9f013ffadf5b360428ae0d4d4ecbb6214e Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 20:23:54 +0900 Subject: [PATCH 02/12] =?UTF-8?q?perf(build):=20react-dom=EC=9D=84=20?= =?UTF-8?q?=EC=9E=90=EA=B8=B0=20=EC=B2=AD=ED=81=AC=EB=A1=9C=20=EB=B9=BC=20?= =?UTF-8?q?build=20id=EB=A7=8C=20=EB=B0=94=EB=80=90=20release=EC=9D=98=20?= =?UTF-8?q?=EC=BA=90=EC=8B=9C=20=EC=86=90=EC=8B=A4=EC=9D=84=20=EC=A4=84?= =?UTF-8?q?=EC=9D=B8=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: build id는 부트 실패 화면이 보여 주므로 render-boot-failure 청크에 들어간다. react-dom과 scheduler(약 56 KB gzip)가 같은 청크에 있어서 build id만 다른 두 빌드에서 boot·index·render-boot-failure 세 파일의 이름이 바뀌었다. 합계 99,785 B로 초기 JS의 49.4%다. 해시 자산은 1년 immutable로 캐시되는데, 재방문 사용자는 코드가 같아도 release마다 이만큼 다시 받았다. 1101 O1이 같은 것을 재고 채택을 권했지만 결정 기록이 없었다. 고른 방법: codeSplitting.groups에 react-dom·scheduler 그룹을 더한다 (includeDependenciesRecursively: false라 라이브러리 모듈만 묶는다). 같은 비교에서 바뀐 초기 JS가 44,297 B(22.0%)로 준다. 초기 JS는 201,857 → 201,552 B, 초기 파일 수는 25개 그대로다(react-dom 진입 모듈 1.3 KB 청크가 합쳐졌다). 버린 대안: build id를 JS에 넣지 않고 release-manifest.json에서만 읽기. boot까지 바뀌지 않아 더 줄지만, 부트 실패 화면이 build id를 보여 주는 계약을 바꿔야 한다. 위험·한계: boot(39 KB)는 build id로 설정을 대조하므로 계속 바뀐다. 그룹 정규식은 pnpm의 node_modules 배치를 가정한다. 배치가 바뀌어 그룹이 비면 새 테스트가 실패한다. 검증: tests/unit/build-environment-bundle.test.ts가 build id만 다른 두 빌드에서 react-dom이 든 청크의 이름이 같고 그 청크가 render-boot-failure가 아님을 본다(고치기 전 실패). 부트 실패 화면 e2e(tests/e2e/boot-module-failure.spec.ts, chromium) 통과. feature-shape-growth·design-system-initial-chunk·bundle-classification 통과. 두 빌드 비교는 docs/operations/performance-evidence.md에 기록했다. Refs: docs/reviews/2026-11-03-maturity-review/15-performance.md 15-06 --- docs/operations/performance-evidence.md | 26 +++++++++++++++++++++ tests/unit/build-environment-bundle.test.ts | 12 ++++++++++ vite.config.ts | 14 +++++++++++ 3 files changed, 52 insertions(+) diff --git a/docs/operations/performance-evidence.md b/docs/operations/performance-evidence.md index 16e5cc36..41016f98 100644 --- a/docs/operations/performance-evidence.md +++ b/docs/operations/performance-evidence.md @@ -161,3 +161,29 @@ the example can never serve as production evidence. 파일을 늘리는 변경은 그 값을 같이 고치고, 이유를 같은 변경에 적는다. HTTP/1.1로만 서빙해야 하는 제품은 (나)처럼 초기 청크를 묶는 그룹을 `vite.config.ts`에 넣는다. 그 목록은 셸을 바꿀 때마다 위 방법으로 다시 잰다. + +## build id와 재방문 캐시 + +리뷰 1103/15-06(1101 O1, 0929/13-03). build id는 부트 실패 화면이 보여 주므로 +그 청크에 들어간다. 해시 자산은 1년 `immutable`로 캐시되지만, build id가 든 +청크와 그 청크를 import하는 청크는 release마다 이름이 바뀐다. react-dom이 그 +청크 안에 있을 때는 코드가 같아도 release마다 초기 JS의 절반을 다시 받았다. + +판단: react-dom과 scheduler를 자기 청크(`vite.config.ts`의 `react-dom` 그룹)로 +뺀다. 2026-11-04 `VITE_BUILD_ID`만 다른 두 빌드(`gitea-101-1`, `gitea-102-1`)를 +비교했다. + +| 빌드 | 이름이 바뀐 초기 파일 | 바뀐 초기 JS gzip(B) | 초기 JS gzip(B) | 초기 파일 | +|---|---|---:|---:|---:| +| 분리 전 | `boot`, `index`, `render-boot-failure` | 99,785 (49.4%) | 201,857 | 25 | +| 분리 뒤 | `boot`, `index`, `render-boot-failure` | 44,297 (22.0%) | 201,552 | 25 | + +- lazy 파일은 두 경우 모두 0 B 바뀐다. +- 초기 파일 수는 그대로다. react-dom의 작은 진입 모듈(1.3 KB)이 같은 청크로 + 합쳐졌다. +- `boot`는 build id로 설정 문서를 대조하므로 계속 바뀐다. build id를 JS에 넣지 + 않고 `release-manifest.json`에서만 읽으면 더 줄지만, 부트 실패 화면이 build + id를 보여 주는 계약을 바꿔야 해서 하지 않았다. +- 부트 실패 화면은 여전히 앱 그래프의 모듈 없이 그려진다(09-03, + `tests/e2e/boot-module-failure.spec.ts`). 이름이 유지되는지는 + `tests/unit/build-environment-bundle.test.ts`가 본다. diff --git a/tests/unit/build-environment-bundle.test.ts b/tests/unit/build-environment-bundle.test.ts index 6fde8f02..16abbc6d 100644 --- a/tests/unit/build-environment-bundle.test.ts +++ b/tests/unit/build-environment-bundle.test.ts @@ -78,6 +78,18 @@ describe("build variables in the bundle (13-06)", () => { const firstChunks = designSystem(first); expect(firstChunks).toHaveLength(1); expect(designSystem(second)).toEqual(firstChunks); + + // 1103/15-06. react-dom is about 56 KB of the initial JavaScript. It sat + // in the boot-failure chunk with the build id, so every release renamed + // it and returning visitors downloaded it again. Its own chunk keeps the + // name while only the build id changes. + const reactDom = ({ contents }: Awaited>) => + contents + .filter(({ file, text }) => file.endsWith(".js") && text.includes("__reactContainer$")) + .map(({ file }) => path.basename(file)); + expect(reactDom(first)).toHaveLength(1); + expect(reactDom(first)[0]).not.toMatch(/render-boot-failure/u); + expect(reactDom(second)).toEqual(reactDom(first)); }, 120_000); it("refuses a VITE_* variable the build does not declare", async () => { diff --git a/vite.config.ts b/vite.config.ts index 86bdfe88..1c411f1a 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -182,6 +182,20 @@ export default defineConfig(({ mode }) => { // chunk would import the entry, whose hash changes with each // build id. { name: "preload-helper", test: /vite[\\/]preload-helper/ }, + // 1103/15-06. react-dom and scheduler (about 56 KB gzip) shared + // the boot-failure chunk with the build id, so a release that + // only changed the build id renamed half of the initial + // JavaScript (99,785 of 201,857 B) and returning visitors + // downloaded it again. In a chunk of their own they keep their + // name: the same change renames 44,297 B (boot, entry and the + // boot-failure screen, which hold or import the build id). + // The boot-failure screen still needs no module of the + // application graph (09-03): this chunk is a library leaf. + { + name: "react-dom", + test: /[\\/]node_modules[\\/](?:\.pnpm[\\/][^\\/]+[\\/]node_modules[\\/])?(?:react-dom|scheduler)[\\/]/, + includeDependenciesRecursively: false, + }, // 1101/07-03. Every feature's schemas and runtime half import // the shared zod adapter. Alone it becomes a chunk of its own // once two features share it, and every route and runtime From 9f9e459c4d916862c7cad22da46bc14791b2f0f4 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 20:25:48 +0900 Subject: [PATCH 03/12] =?UTF-8?q?perf(build):=20=EC=9A=B4=EC=98=81=20?= =?UTF-8?q?=EB=B9=8C=EB=93=9C=EA=B0=80=20react-router=EC=9D=98=20=EC=9A=B4?= =?UTF-8?q?=EC=98=81=20=EB=B9=8C=EB=93=9C=EB=A5=BC=20=EC=8B=A3=EB=8A=94?= =?UTF-8?q?=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: react-router 7.18.1의 exports는 모든 조건에서 dist/development/*를 가리킨다. 그 파일은 ENABLE_DEV_WARNINGS = true라 운영 번들의 초기 청크에 라우터 개발 경고 문구("You rendered descendant …")가 들어 있었다. 운영 콘솔에 개발 경고가 뜨고, 초기 JS가 약 600 B 크다. 고른 방법: vite build일 때만 react-router-dom이 import하는 두 진입점 (react-router, react-router/dom)을 같은 패키지의 dist/production 파일로 alias한다. 경로는 react-router-dom에서 react-router를 resolve한 개발 진입점 옆에서 찾고, 파일이 없으면 빌드를 멈춘다. 개발 서버와 테스트는 개발 빌드를 그대로 써서 경고를 받는다. 버린 대안: 고정 경로 alias(리뷰 실험). 업그레이드로 배치가 바뀌면 조용히 깨진다. react-router에 production 조건을 요청하기는 시점을 정할 수 없어 이 alias를 지울 조건으로만 적었다. 위험·한계: exports 밖 경로를 쓴다. 업그레이드 때 배치가 바뀌면 빌드가 실패한다(조용히 개발 빌드로 돌아가지 않는다). Firefox·WebKit e2e는 돌리지 않았다. 검증: tests/unit/build-environment-bundle.test.ts가 빌드한 JS에 개발 경고 문구가 없음을 본다(고치기 전 chunk-KS7C4IRE 1개에서 실패). 같은 빌드(local-build) 초기 JS 201,552 → 200,939 B(−613 B), 파일 25개. 라우터를 쓰는 e2e 5개 spec 14건(app-shell, reference-route, reference-save, scroll-restoration, platform-overview, chromium) 통과. Refs: docs/reviews/2026-11-03-maturity-review/15-performance.md 15-07 --- tests/unit/build-environment-bundle.test.ts | 8 +++++ vite.config.ts | 35 ++++++++++++++++++++- 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/tests/unit/build-environment-bundle.test.ts b/tests/unit/build-environment-bundle.test.ts index 16abbc6d..b3a13f37 100644 --- a/tests/unit/build-environment-bundle.test.ts +++ b/tests/unit/build-environment-bundle.test.ts @@ -90,6 +90,14 @@ describe("build variables in the bundle (13-06)", () => { expect(reactDom(first)).toHaveLength(1); expect(reactDom(first)[0]).not.toMatch(/render-boot-failure/u); expect(reactDom(second)).toEqual(reactDom(first)); + + // 1103/15-07. react-router's exports map resolves every condition to its + // development build; a production build must carry the production one, + // without the router's development warnings. + const developmentWarnings = first.contents + .filter(({ file, text }) => file.endsWith(".js") && text.includes("You rendered descendant")) + .map(({ file }) => path.basename(file)); + expect(developmentWarnings).toEqual([]); }, 120_000); it("refuses a VITE_* variable the build does not declare", async () => { diff --git a/vite.config.ts b/vite.config.ts index 1c411f1a..c2e205a3 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -1,3 +1,5 @@ +import { existsSync } from "node:fs"; +import { createRequire } from "node:module"; import path from "node:path"; import { defineConfig, loadEnv } from "vite"; @@ -138,13 +140,44 @@ function createFeatureChunkGroups(root: string) { }; } -export default defineConfig(({ mode }) => { +/** + * 1103/15-07. react-router publishes its production build under + * dist/production, but its exports map points every condition at + * dist/development. A production bundle carried the router's development + * warnings (ENABLE_DEV_WARNINGS): 604 gzip bytes of initial JavaScript at + * 15-07 and warnings in the production console. A build resolves the two + * entries react-router-dom imports to the production files next to the + * development entry. If an upgrade moves them, the build stops here rather + * than silently shipping the development build again; + * tests/unit/build-environment-bundle.test.ts checks the bundle. Remove this + * when the package exports a production condition. + */ +function reactRouterProductionAliases(root: string) { + const projectRequire = createRequire(path.join(root, "package.json")); + const routerRequire = createRequire(projectRequire.resolve("react-router-dom")); + const production = path.join(path.dirname(routerRequire.resolve("react-router")), "..", "production"); + const aliases = [ + { find: /^react-router$/u, replacement: path.join(production, "index.mjs") }, + { find: /^react-router\/dom$/u, replacement: path.join(production, "dom-export.mjs") }, + ]; + const missing = aliases.filter(({ replacement }) => !existsSync(replacement)); + if (missing.length > 0) { + throw new Error( + `react-router production build not found: ${missing.map(({ replacement }) => replacement).join(", ")}`, + ); + } + return aliases; +} + +export default defineConfig(({ command, mode }) => { assertDeclaredBuildVariables(mode); const base = routerBasePath(process.env); assertRuntimeConfigUnderBase(process.env, base); return { base, plugins: [react(), tailwindcss(), viteModuleInventoryPlugin()], + // Development keeps the router's warnings. + resolve: command === "build" ? { alias: reactRouterProductionAliases(process.cwd()) } : {}, build: { manifest: true, sourcemap: false, From e440ece9fe85371b69799ae802053ffd7fcc7180 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 20:28:52 +0900 Subject: [PATCH 04/12] =?UTF-8?q?build(vite):=20=ED=8F=90=EA=B8=B0=20?= =?UTF-8?q?=EC=98=88=EC=A0=95=20build.rollupOptions=EB=A5=BC=20rolldownOpt?= =?UTF-8?q?ions=EB=A1=9C=20=EB=B0=94=EA=BE=BC=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 앱·Service Worker·선택 레시피 번들의 청크 설정이 Vite 8에서 @deprecated인 build.rollupOptions 별칭에 있었다(0929/13-07, 세 라운드 남음). 별칭이 지워지는 Vite 버전으로 올리면 청크 그룹과 treeshake 설정이 조용히 빠질 수 있다. 고른 방법: 세 곳의 키 이름만 rolldownOptions로 바꾼다. 내용은 그대로다. 위험·한계: 없음에 가깝다. 같은 설정의 정식 이름이다. 검증: 바꾸기 전후 빌드의 dist/assets 파일 이름이 모두 같다(해시가 같아 출력이 같다). service-worker-build-output 7건 통과, check:optional-recipes PASS(레시피 예산 4개 그대로). Refs: docs/reviews/2026-11-03-maturity-review/13-build-release-supply-chain.md 0929/13-07 --- scripts/lib/optional-recipe-bundle.ts | 2 +- vite.config.ts | 2 +- vite.service-worker.config.ts | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/scripts/lib/optional-recipe-bundle.ts b/scripts/lib/optional-recipe-bundle.ts index 915b287c..0794cf5e 100644 --- a/scripts/lib/optional-recipe-bundle.ts +++ b/scripts/lib/optional-recipe-bundle.ts @@ -127,7 +127,7 @@ export async function measureOptionalRecipeBundle(input: Readonly<{ copyPublicDir: false, cssCodeSplit: false, reportCompressedSize: false, - rollupOptions: { + rolldownOptions: { input: virtualEntry, // Budget the complete selected runtime, including internal fail-closed // guards that a synthetic consumer cannot predict it will exercise. diff --git a/vite.config.ts b/vite.config.ts index c2e205a3..60053a34 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -181,7 +181,7 @@ export default defineConfig(({ command, mode }) => { build: { manifest: true, sourcemap: false, - rollupOptions: { + rolldownOptions: { /** * 1101/08-08. The design-system modules have no top-level effects: * they declare components, icons and token lists. Declared so, a diff --git a/vite.service-worker.config.ts b/vite.service-worker.config.ts index aee34b9e..156732ef 100644 --- a/vite.service-worker.config.ts +++ b/vite.service-worker.config.ts @@ -76,7 +76,7 @@ export default defineConfig({ // §17.2.2: exactly one input, exactly one output, no additional chunk. emptyOutDir: false, sourcemap: false, - rollupOptions: { + rolldownOptions: { input: "src/adapters/service-worker/service-worker-entry.ts", output: { format: "es", From c9e7bab2d75653818880f7ab5b41124298b802cb Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 20:34:39 +0900 Subject: [PATCH 05/12] =?UTF-8?q?test(scale):=20=EA=B8=B0=EB=8A=A5=C2=B7co?= =?UTF-8?q?ntext=20=EB=B9=84=EC=9A=A9=EC=9D=84=20=EB=94=B0=EB=A1=9C=20?= =?UTF-8?q?=EC=9E=AC=EA=B3=A0=20=EC=B4=88=EA=B8=B0=20JS=20=EA=B8=B0?= =?UTF-8?q?=EC=A4=80=EC=84=A0=EC=9D=84=20=EB=B9=8C=EB=93=9C=EC=99=80=20?= =?UTF-8?q?=EB=8C=80=EC=A1=B0=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: (1) 기능당 1 KiB 상한 테스트는 복사본 0개와 1개만 쟀다. 첫 복사본은 새 context(shape-context-0)도 만들어서, 잰 값에 context 비용이 섞였고 상한까지 40 B만 남았다. 넘으면 기능이 커졌는지 context가 비싸졌는지 알 수 없었다. (2) 성능 기준선 숫자는 performance-evidence.md, static-delivery.md, feature-shape-ceilings.json에 손으로 적혀 있었고 현재 빌드와도, 같은 파일 안에서도 서로 달랐다(1101/15-02 재발). (3) 이 테스트는 vitest 안에서 돌아 NODE_ENV=test를 물려받았다. 그래서 픽스처 vite build가 React 개발 빌드를 묶었고, 잰 합계가 운영 빌드 (약 201 KB)가 아니라 약 264 KB였다. 고른 방법: 복사본 0·1·2개를 잰다. 둘째 복사본은 같은 context에 들어가 기능 하나의 비용이고, 첫 복사본에서 그것을 뺀 나머지가 context 하나의 비용이다. 기능은 1 KiB, context는 512 B로 따로 막고 실패 메시지에 잰 값을 넣는다. 기준선은 feature-shape-ceilings.json의 initialJavascript 한 곳에 기계가 읽는 칸으로 두고, 같은 테스트가 빌드와 대조한다(합계 1%, 파일 수 정확히, 기능·context 비용 10%). 기록은 `measure-feature-shape-growth.ts --initial-baseline --write`로 다시 쓴다. 문서는 숫자 대신 그 칸을 가리킨다. 픽스처 명령은 NODE_ENV를 지우고 돈다. 버린 대안: 문서 숫자를 다시 손으로 고치기(두 번 낡았다), 문서에서 숫자를 지우고 bundle.json만 가리키기(예산을 정할 숫자를 보려면 빌드가 필요하다). 위험·한계: unit에 빌드가 하나 늘었다(약 3초). 초기 JS를 움직이는 변경은 기록도 다시 써야 test:unit이 통과한다. 그것이 목적이다. `298201f` 출처별 크기 표와 `ec7435c` HTTP/1.1 측정 표는 날짜가 붙은 측정 기록으로 남겼다. 검증: 기록을 쓰기 전 새 테스트가 실패했다. 기록 gzipBytes를 2% 바꾸면 실패하고 되돌리면 통과한다. 지금 기록: 200,939 B, 파일 25개, 기능 +765 B, context +214 B. feature-shape-growth 7건 통과, verify:documentation PASS_SCOPED. Refs: docs/reviews/2026-11-03-maturity-review/15-performance.md 15-02, 15-04 --- config/scale/feature-shape-ceilings.json | 12 ++- docs/architecture/static-delivery.md | 6 +- docs/operations/performance-evidence.md | 47 +++++---- scripts/scale/measure-feature-shape-growth.ts | 96 +++++++++++++++++-- tests/unit/feature-shape-growth.test.ts | 64 +++++++++++-- 5 files changed, 184 insertions(+), 41 deletions(-) diff --git a/config/scale/feature-shape-ceilings.json b/config/scale/feature-shape-ceilings.json index 35f02ca1..18003b6b 100644 --- a/config/scale/feature-shape-ceilings.json +++ b/config/scale/feature-shape-ceilings.json @@ -21,9 +21,9 @@ }, { "axis": "Initial JavaScript", - "verified": "15-01: only each feature's declaration (route table, messages, invalidation identities) loads at boot; its runtime half loads with its routes. Baseline: 203,816 B with no copy, about 610-630 B and no extra file per copy (219,508 B at 25, 264,841 B at 100; before 15-01: +3,922 B per copy). tests/unit/feature-shape-growth.test.ts keeps one copy at or under 1 KiB", + "verified": "15-01: only each feature's declaration (route table, messages, invalidation identities) loads at boot; its runtime half loads with its routes, and a copy adds no initial file. initialJavascript below is the current template build, what one more feature in an existing context adds (perFeatureGzipBytes) and what a new context adds (perContextGzipBytes); tests/unit/feature-shape-growth.test.ts measures them on every unit run, bounds a feature at 1 KiB and a context at 512 B, and fails when the record no longer matches the build. The 25- and 100-copy runs are in the baseline at its source commit (before 15-01: +3,922 B per copy)", "condition": "Same; the feature-declarations and feature-platform chunk groups in vite.config.ts", - "notVerified": "The initial budget (204,800 B, config/performance/budgets.json) leaves 2,291 B over the baseline's 202,509 B, so about three more reference-shaped features fit at about 610 B each: the platform itself is 98.9% of it" + "notVerified": "How many more features fit: the initial budget (config/performance/budgets.json) minus initialJavascript.gzipBytes, divided by perFeatureGzipBytes (plus perContextGzipBytes per new context). The platform itself takes most of the budget" }, { "axis": "Lazy JavaScript", @@ -37,5 +37,11 @@ "condition": "Same", "notVerified": "Router matching cost at runtime" } - ] + ], + "initialJavascript": { + "gzipBytes": 200939, + "files": 25, + "perFeatureGzipBytes": 765, + "perContextGzipBytes": 214 + } } diff --git a/docs/architecture/static-delivery.md b/docs/architecture/static-delivery.md index 44e0b685..7cda8166 100644 --- a/docs/architecture/static-delivery.md +++ b/docs/architecture/static-delivery.md @@ -40,8 +40,10 @@ that the host serves that release; while the slot is empty FE-GATE-019 is Rollback changes the active pointer only after confirming that the prior immutable release has a coherent HTML/assets/config/API/manifest tuple. -Serve the app over HTTP/2 or later. The entry preloads about 26 initial -JavaScript files in parallel. Over HTTP/1.1 they queue for six connections per +Serve the app over HTTP/2 or later. The entry preloads every initial +JavaScript file in parallel (`initialJsFiles` in +`config/performance/budgets.json` bounds how many; the current count is +`initialJavascript.files` in `config/scale/feature-shape-ceilings.json`). Over HTTP/1.1 they queue for six connections per host, and the first screen on Fast 3G came about one second later than with the initial chunks grouped (2026-11-03). Over HTTP/2 the difference was under 100 ms, so the template keeps the chunks split. A product that can only serve diff --git a/docs/operations/performance-evidence.md b/docs/operations/performance-evidence.md index 41016f98..65e63552 100644 --- a/docs/operations/performance-evidence.md +++ b/docs/operations/performance-evidence.md @@ -14,23 +14,33 @@ Performance evidence is deliberately split by measurement context: ## 번들 예산의 기준선과 여유 -리뷰 0925/13-14, 1101/15-02. 예산은 `config/performance/budgets.json`에 있고 -`scripts/check-bundle.ts`(FE-GATE-012, merge 단계)가 강제한다. 템플릿 기본 -화면만으로 초기 JS 예산의 98.9%를 쓴다. 첫 기능을 추가하기 전에 아래 숫자를 +리뷰 0925/13-14, 1101/15-02, 1103/15-02. 예산은 `config/performance/budgets.json`에 +있고 `scripts/check-bundle.ts`(FE-GATE-012, merge 단계)가 강제한다. 템플릿 기본 +화면만으로 초기 JS 예산의 대부분을 쓴다. 첫 기능을 추가하기 전에 아래 기록을 보고 예산을 정한다. -| 항목 | 값 | +기준선 숫자는 이 문서에 적지 않는다. 손으로 적은 숫자는 두 번 낡았다. 기록은 +`config/scale/feature-shape-ceilings.json`의 `initialJavascript` 한 곳이다. + +| 칸 | 뜻 | |---|---| -| 초기 JS 예산 | 204,800 gzip bytes(200 KiB) | -| 템플릿 기준선(2026-11-01, 커밋 `298201f`) | 202,509~202,522 gzip bytes, 16개 파일. local 프로필, `VITE_BUILD_ID`가 `local-build`일 때와 CI 모양(`gitea--`)일 때다. 빌드 ID가 번들에 들어가므로 빌드마다 수십~수백 바이트 다르다 | -| 여유 | 약 2,280 bytes(1.1%) | -| 기능 하나를 더할 때 | 참조 기능 모양 복사본 하나에 약 +650~750 bytes(`298201f` 측정, 상한은 `tests/unit/feature-shape-growth.test.ts`의 1 KiB). 기능 실행부(`feature-runtime.ts`)는 라우트에 들어갈 때 받는 lazy chunk다 | -| lazy chunk 예산 | 파일마다 122,880 gzip bytes(120 KiB). 기준선의 lazy JS는 17개, 합계 28,204 bytes이고 가장 큰 것은 `use-reference-feature` 8,386 bytes다 | +| `gzipBytes`, `files` | 템플릿 그대로의 초기 JS gzip bytes와 파일 수(entry 포함) | +| `perFeatureGzipBytes` | 있는 context에 참조 기능 모양 기능을 하나 더할 때 느는 초기 JS. 상한 1 KiB | +| `perContextGzipBytes` | 새 context를 하나 더할 때 느는 초기 JS. 상한 512 B | + +- `tests/unit/feature-shape-growth.test.ts`(unit, merge 단계)가 매번 빌드해 이 + 값을 재고, 상한을 넘거나 기록과 다르면(합계 1% 초과, 파일 수 불일치, 기능· + context 비용 10% 초과) 실패한다. 실패 메시지에 잰 값이 나온다. +- 기록을 고칠 때는 `node scripts/scale/measure-feature-shape-growth.ts + --initial-baseline --write`를 돌리고 같은 변경에 넣는다. +- 여유는 예산에서 `gzipBytes`를 뺀 값이다. 그것을 `perFeatureGzipBytes`로 나누면 + 더 넣을 수 있는 기능 수다. 새 context마다 `perContextGzipBytes`가 더 든다. +- 기능 실행부(`feature-runtime.ts`)는 라우트에 들어갈 때 받는 lazy chunk다. + lazy chunk 예산은 파일마다 120 KiB(`lazyChunkGzipBytes`)다. 청크 이름으로 크기를 판단하지 않는다. rolldown은 공용 청크에 안에 든 모듈 -하나의 이름을 붙인다. 예를 들어 `render-boot-failure` 청크(58.6 KB)의 대부분은 -react-dom이고, `design-system` 청크(48.2 KB)에는 react-router가 들어 있다. -아래는 출처별 크기다. sourcemap 빌드에서 minify된 바이트를 원래 모듈에 나눠 +하나의 이름을 붙인다. 아래는 2026-11-01(`298201f`)에 잰 출처별 크기다. 지금 +빌드와는 조금 다르다. sourcemap 빌드에서 minify된 바이트를 원래 모듈에 나눠 붙이고 묶음마다 따로 gzip했다. 따로 압축하므로 합은 실제 합계와 조금 다르다. | 출처 | minify bytes | 단독 gzip bytes | @@ -54,8 +64,7 @@ react-dom이고, `design-system` 청크(48.2 KB)에는 react-router가 들어 (`scripts/lib/classify-vite-bundle.ts`). entry는 앱 그래프의 평가 실패를 보고하려고 그 둘을 dynamic import로 읽을 뿐이고, 첫 화면에 항상 필요하다 (0925/09-03). 그 밖의 dynamic import chunk는 lazy다. -- 합계는 JavaScript만 센다. CSS(`index-*.css`, 8.6 KB gzip)는 예산에 들어가지 - 않는다. +- 합계는 JavaScript만 센다. CSS(`index-*.css`)는 예산에 들어가지 않는다. - gzip은 Node `zlib.gzipSync` 기본 수준(6)으로 잰다 (`scripts/lib/release-candidate.ts`). 호스팅이 brotli로 보내면 전송 크기는 더 작다. 예산은 gzip 기준 그대로 둔다. @@ -104,12 +113,12 @@ the example can never serve as production evidence. 리뷰 1101/14.4. 08-08은 초기 JS 바이트를 줄이는 대신 초기 파일 수를 늘렸다 (`vite.config.ts`의 `moduleSideEffects` 주석). HTTP/1.1에서 브라우저는 한 호스트에 연결을 6개까지만 연다. 파일이 많으면 요청이 줄을 서서 왕복이 는다. -그래서 지금 빌드와 작은 초기 청크를 하나로 묶은 빌드를 쟀다(2026-11-03, -커밋 `ec7435c`). +그래서 그때 빌드와 작은 초기 청크를 하나로 묶은 빌드를 쟀다(2026-11-03, +커밋 `ec7435c`). 아래 두 표의 파일 수와 바이트는 그 커밋의 값이다. | 빌드 | 초기 JS 파일(entry 포함) | 초기 JS gzip(B) | 첫 화면까지 JS 요청 | Fast 3G 첫 화면 | Fast 4G 첫 화면 | |---|---:|---:|---:|---:|---:| -| 지금 | 26 | 202,782 | 27 | 5,887 ms | 1,874 ms | +| `ec7435c` | 26 | 202,782 | 27 | 5,887 ms | 1,874 ms | | (가) 08-08이 나눈 초기 primitive 청크 4개(`field`·`button`·`select`·`page-templates`)를 하나로 | 23 | 201,818 | 24 | 5,426 ms | 1,764 ms | | (나) 묶을 수 있는 초기 청크 14개를 하나로 | 13 | 198,673 | 14 | 4,930 ms | 1,535 ms | @@ -118,7 +127,7 @@ the example can never serve as production evidence. | 빌드 | Fast 3G 첫 화면 | Fast 4G 첫 화면 | |---|---:|---:| -| 지금 | 4,793 ms | 1,444 ms | +| `ec7435c` | 4,793 ms | 1,444 ms | | (가) | 4,769 ms | 1,440 ms | | (나) | 4,708 ms | 1,422 ms | @@ -130,7 +139,7 @@ the example can never serve as production evidence. - 매번 새 browser context에서 캐시 없이 `/`를 연다. 첫 화면은 boot 셸이 사라지고 `#main-content h1[data-route-heading]`가 DOM에 들어온 시각이다 (`performance.now()`). -- 세 빌드를 번갈아 7번씩 재고 중앙값을 적었다. 7번의 범위는 지금 5,866~6,077 ms, +- 세 빌드를 번갈아 7번씩 재고 중앙값을 적었다. 7번의 범위는 `ec7435c` 5,866~6,077 ms, (가) 5,384~5,652 ms, (나) 4,891~5,032 ms다(Fast 3G). loadavg는 HTTP/1.1 측정 때 6~20, HTTP/2 측정 때 3~6이었다. 그래서 두 표끼리는 비교하지 않는다. - CDP 지연은 요청마다 붙는다. 연결 수립(TCP·TLS) 비용은 따로 재지 않았다. diff --git a/scripts/scale/measure-feature-shape-growth.ts b/scripts/scale/measure-feature-shape-growth.ts index 6ff8b8b3..94b6e6b5 100644 --- a/scripts/scale/measure-feature-shape-growth.ts +++ b/scripts/scale/measure-feature-shape-growth.ts @@ -25,8 +25,11 @@ import { parseTscExtendedDiagnostics, type TscDiagnostics } from "./collect-tsc- * to represent) is recorded as a result with its first error. * * node scripts/scale/measure-feature-shape-growth.ts [--sizes=0,25,100] [--repeats=2] [--write] + * node scripts/scale/measure-feature-shape-growth.ts --initial-baseline [--write] * - * `--write` stores the result as config/scale/feature-shape-growth.json. + * `--write` stores the result as config/scale/feature-shape-growth.json, or + * with `--initial-baseline` the initial JavaScript record in + * config/scale/feature-shape-ceilings.json. */ export const FEATURE_SHAPE_BASELINE_PATH = "config/scale/feature-shape-growth.json"; /** What the declared ceilings rest on, derived by hand from the baseline. */ @@ -143,10 +146,15 @@ function run( cwd: string, options: Readonly<{ allowFailure?: boolean }> = {}, ) { + // 1103/15-02. Vitest sets NODE_ENV=test, and a vite build that inherits it + // bundles React's development build: the unit test measured 264 KB where + // the production build is 201 KB. Every command here measures production. + const { NODE_ENV: _inherited, ...environment } = process.env; const started = performance.now(); const result = spawnSync(command, args, { cwd, encoding: "utf8", + env: environment, maxBuffer: 64 * 1024 * 1024, }); const ms = Math.round(performance.now() - started); @@ -167,23 +175,77 @@ async function javascriptGzipBytes(root: string, files: readonly string[]) { } /** - * 15-01. Initial JavaScript gzip bytes of the app with `features` reference - * copies added: the generator and `vite build` only, no typecheck. The unit - * suite (merge stage) bounds what one more feature adds to the initial chunk - * with it, so the growth is caught on the PR instead of at the next release. + * 15-01. Initial JavaScript of the app with `features` reference copies + * added: the generator and `vite build` only, no typecheck. The unit suite + * (merge stage) bounds what one more feature adds to the initial chunk with + * it, so the growth is caught on the PR instead of at the next release. */ -export async function measureInitialJavascriptGzipBytes(features: number): Promise { +async function measureInitialJavascript( + features: number, +): Promise> { const root = await createFixture(features); try { run(process.execPath, [path.resolve("scripts/generate-product-feature-index.ts"), `--root=${root}`], root); run(path.resolve("node_modules/.bin/vite"), ["build", "--logLevel", "error"], root); const manifest = JSON.parse(await readFile(path.join(root, "dist/.vite/manifest.json"), "utf8")); - return await javascriptGzipBytes(root, classifyViteJavascript(manifest).initialFiles); + const { initialFiles } = classifyViteJavascript(manifest); + return { gzipBytes: await javascriptGzipBytes(root, initialFiles), files: initialFiles.length }; } finally { await rm(root, { recursive: true, force: true }); } } +/** + * 1103/15-02, 15-04. The template's initial JavaScript and what one more + * feature and one more context add to it. The first copy lands in a new + * context (shape-context-0) and the second in the same one, so the second + * copy is a feature alone and the rest of the first is the context. + * `initialJavascript` in config/scale/feature-shape-ceilings.json records + * these numbers; tests/unit/feature-shape-growth.test.ts compares them with + * the build on every unit run. + */ +export type InitialJavascriptCosts = Readonly<{ + gzipBytes: number; + files: number; + perFeatureGzipBytes: number; + perContextGzipBytes: number; +}>; + +export async function measureInitialJavascriptCosts(): Promise { + const none = await measureInitialJavascript(0); + const one = await measureInitialJavascript(1); + const two = await measureInitialJavascript(2); + const perFeatureGzipBytes = two.gzipBytes - one.gzipBytes; + return { + gzipBytes: none.gzipBytes, + files: none.files, + perFeatureGzipBytes, + perContextGzipBytes: one.gzipBytes - none.gzipBytes - perFeatureGzipBytes, + }; +} + +/** + * Fields of the record that no longer describe the build. The total moves + * by tens of bytes with the build id (CI and local builds differ), so it may + * be 1% off; the per-feature and per-context costs are differences of builds + * with the same id but only a few hundred bytes, so 10%; the file count is + * exact. + */ +export function initialJavascriptRecordDrift( + measured: InitialJavascriptCosts, + record: InitialJavascriptCosts, +): string[] { + const tolerance: Readonly> = { + gzipBytes: 0.01, + files: 0, + perFeatureGzipBytes: 0.1, + perContextGzipBytes: 0.1, + }; + return (Object.keys(tolerance) as (keyof InitialJavascriptCosts)[]) + .filter((field) => Math.abs(record[field] - measured[field]) > Math.abs(measured[field]) * tolerance[field]) + .map((field) => `${field}: record ${record[field]}, build ${measured[field]}`); +} + async function measureOnce(root: string, features: number) { const loadBefore = load(); run(process.execPath, [path.resolve("scripts/generate-product-feature-index.ts"), `--root=${root}`], root); @@ -262,7 +324,27 @@ function version(bin: string): string { return (result.stdout ?? "").trim(); } +/** + * 1103/15-02. `--initial-baseline` measures the record the documents cite and, + * with `--write`, stores it as `initialJavascript` in + * config/scale/feature-shape-ceilings.json. Run it in the change that moves + * the initial JavaScript. + */ +async function writeInitialBaseline(): Promise { + const measured = await measureInitialJavascriptCosts(); + process.stdout.write(`initial JavaScript: ${JSON.stringify(measured)}\n`); + if (!process.argv.includes("--write")) return; + const ceilings = JSON.parse(await readFile(FEATURE_SHAPE_CEILINGS_PATH, "utf8")) as Record; + ceilings["initialJavascript"] = measured; + await writeFile(FEATURE_SHAPE_CEILINGS_PATH, `${JSON.stringify(ceilings, null, 2)}\n`); + process.stdout.write(`feature-shape initial baseline: ${FEATURE_SHAPE_CEILINGS_PATH}\n`); +} + async function main(): Promise { + if (process.argv.includes("--initial-baseline")) { + await writeInitialBaseline(); + return; + } const argument = (name: string) => process.argv.find((entry) => entry.startsWith(`--${name}=`))?.slice(name.length + 3); const sizes = (argument("sizes") ?? "0,25,100").split(",").map(Number); diff --git a/tests/unit/feature-shape-growth.test.ts b/tests/unit/feature-shape-growth.test.ts index c97d6422..fb267f0c 100644 --- a/tests/unit/feature-shape-growth.test.ts +++ b/tests/unit/feature-shape-growth.test.ts @@ -5,8 +5,10 @@ import { describe, expect, it } from "vitest"; import { FEATURE_SHAPE_BASELINE_PATH, FEATURE_SHAPE_CEILINGS_PATH, - measureInitialJavascriptGzipBytes, + initialJavascriptRecordDrift, + measureInitialJavascriptCosts, renameReferenceFeature, + type InitialJavascriptCosts, } from "../../scripts/scale/measure-feature-shape-growth.ts"; import { APP_MAX_CONTEXTS } from "../../src/apps/template-app/app-module.ts"; import { CONTEXT_MAX_FEATURES } from "../../src/contexts/reference-context/context-module.ts"; @@ -131,17 +133,59 @@ describe("feature-shape growth measurement (11-04)", () => { * contracts, schemas, mappers, HTTP gateway and API loaded at boot: +3,922 B * per copy, and the first added feature exceeded the budget. Only what the * shell needs before a feature route is entered may load at boot (route - * table, navigation and page messages, invalidation identities: 741 B when - * 15-01 landed); the rest loads with the feature's routes. The bound also - * fails if the feature-declarations chunk group in vite.config.ts stops - * matching. + * table, navigation and page messages, invalidation identities); the rest + * loads with the feature's routes. The bound also fails if the + * feature-declarations chunk group in vite.config.ts stops matching. + * + * 1103/15-04. The first copy also adds a context (shape-context-0), so one + * number mixed a context's cost with a feature's and had 40 B left under + * the bound. A second copy in the same context is one more feature alone; + * the rest of the first copy is the context. Each has its own bound and + * the failure names which one grew. + * + * 1103/15-02. The record in config/scale/feature-shape-ceilings.json is the + * one place the documents take the template's baseline from. Written by + * hand, it went stale twice; it now has to match this build. */ - it("adds at most 1 KiB of initial JavaScript per reference-shaped feature (15-01)", async () => { - const withoutCopies = await measureInitialJavascriptGzipBytes(0); - const withOneCopy = await measureInitialJavascriptGzipBytes(1); + it("bounds what one more feature and one more context add, and matches the record (15-01)", async () => { + const measured = await measureInitialJavascriptCosts(); + const { initialJavascript: record } = JSON.parse( + await readFile(FEATURE_SHAPE_CEILINGS_PATH, "utf8"), + ) as { initialJavascript: InitialJavascriptCosts }; + const observed = `measured ${JSON.stringify(measured)}`; - expect(withOneCopy - withoutCopies).toBeLessThanOrEqual(1_024); - }, 120_000); + expect(measured.perFeatureGzipBytes, `one more feature in an existing context: ${observed}`) + .toBeLessThanOrEqual(1_024); + expect(measured.perContextGzipBytes, `one more context: ${observed}`) + .toBeLessThanOrEqual(512); + expect( + initialJavascriptRecordDrift(measured, record), + `${FEATURE_SHAPE_CEILINGS_PATH} initialJavascript is stale (${observed}); ` + + "rewrite it with node scripts/scale/measure-feature-shape-growth.ts --initial-baseline --write", + ).toEqual([]); + }, 180_000); + + it("reports a record more than 1% off the build, or a different file count", () => { + const measured = { + gzipBytes: 200_000, + files: 25, + perFeatureGzipBytes: 700, + perContextGzipBytes: 250, + }; + expect(initialJavascriptRecordDrift(measured, measured)).toEqual([]); + expect( + initialJavascriptRecordDrift(measured, { ...measured, gzipBytes: 201_500 }), + ).toEqual([]); + expect( + initialJavascriptRecordDrift(measured, { ...measured, gzipBytes: 204_000 }), + ).toEqual(["gzipBytes: record 204000, build 200000"]); + expect(initialJavascriptRecordDrift(measured, { ...measured, files: 26 })).toEqual([ + "files: record 26, build 25", + ]); + expect( + initialJavascriptRecordDrift(measured, { ...measured, perFeatureGzipBytes: 800 }), + ).toEqual(["perFeatureGzipBytes: record 800, build 700"]); + }); it("states in the committed rationale what the ceilings rest on", async () => { // The rationale lives next to the baseline, not in a review document: the From 4bce8bf379051e224b8037c0f30b5f6b84ee8296 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 20:40:37 +0900 Subject: [PATCH 06/12] =?UTF-8?q?fix(hosting):=20FE-GATE-019=EA=B0=80=20?= =?UTF-8?q?=ED=9B=84=EB=B3=B4=EC=9D=98=20=EC=84=A4=EC=A0=95=C2=B7entry?= =?UTF-8?q?=EC=99=80=20HTTP/2=C2=B7=EC=95=95=EC=B6=95=20=EC=A0=84=EC=A0=9C?= =?UTF-8?q?=EB=A5=BC=20=EB=8C=80=EC=A1=B0=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: (1) live probe는 배포된 release-manifest.json의 buildId·releaseId만 후보와 비교했다. 두 값은 CI run 번호로 만든 이름이라, 같은 run에서 로컬 프로필로 다시 빌드한 release(APP_ENV=local, AUTH_MODE=demo, loopback API)를 올려도 PASS(live)였다(리뷰 실험 E-2c). 공개 대상 승인 (FE-GATE-027)을 받은 것은 후보의 config.json인데, 호스트가 내주는 config.json은 헤더만 보았다. entry script도 호스트의 두 응답끼리만 비교했다. (2) 템플릿은 HTTP/2와 압축을 전제로 초기 청크를 나누고 gzip 바이트로 예산을 재는데, 그 전제가 호스팅 계약에 없고 probe도 보지 않았다. 템플릿 nginx 예시는 http2도 gzip도 켜지 않았다. 고른 방법: - 받은 /config.json을 후보 dist/config.json과 비교한다. 비상 스위치 두 개(CAPABILITY_OVERRIDES, FEATURE_OVERRIDES) 밖의 필드가 다르거나 읽을 수 없으면 FAIL. 규칙은 check-release-admission과 같은 함수 (scripts/lib/runtime-config-switches.ts)로 옮겨 같이 쓴다. - 받은 index.html의 entry script를 후보 index.html의 것과 비교한다. - cache-policy.json에 transport.alpnProtocols(["h2"])와 hashedAsset.contentEncodings(br, gzip, zstd)를 선언한다. probe는 TLS handshake의 ALPN(node:tls, h2와 http/1.1을 제안)과 entry script 응답의 Content-Encoding을 본다. Node fetch는 h2를 지원하는 서버에도 HTTP/1.1로 붙어서 프로토콜은 따로 확인해야 한다. - nginx 예시에 http2 on과 gzip·gzip_types를 넣고, static-delivery.md와 release-cache-rollback.md에 두 전제와 실패 조건을 적었다. 두 수정은 같은 probe 함수와 테스트를 고쳐 한 커밋에 넣었다. 버린 대안: archive SHA를 호스트에 올려 대조하기(호스트에 새 파일 규약이 생기고 일부 파일만 다른 배포는 못 잡는다). HTTP/2를 기록만 하기 (아무도 읽지 않는 경고는 청크를 묶는 결정을 부르지 못한다. 선언을 바꾸면 제품이 끌 수 있다). 위험·한계: HTTP/1.1만 되는 호스트는 이제 FE-GATE-019에서 FAIL한다. 그 제품은 cache-policy.json 선언을 바꾸고 초기 청크를 묶는다. 실제 nginx와 Gitea runner에서는 돌리지 않았다. 슬롯이 후보를 받도록 강제하는 계약 규칙은 다음 커밋(제품 overlay)에 있다. 검증: hosting-probe.test.ts에 같은 이름·다른 config.json → FAIL, 비상 스위치만 다름 → PASS, 읽을 수 없는 config.json → FAIL, 다른 entry → FAIL, ALPN http/1.1·없음 → FAIL, 압축 없는 entry → FAIL, 정책 선언 확인을 더했다(고치기 전 실패). 33건 통과. 로컬 자체 서명 TLS 서버 실험: http2.createSecureServer → "h2", https.createServer → "http/1.1", 인증서 이름 불일치 → ERR_TLS_CERT_ALTNAME_INVALID. verify:hosting-headers(fixture) UNVERIFIED exit 3, deployment-admission 통과. Refs: docs/reviews/2026-11-03-maturity-review/13-build-release-supply-chain.md 13-01, 13-02 --- config/hosting/cache-policy.json | 4 + config/hosting/response-headers.fixture.json | 3 +- docs/architecture/static-delivery.md | 9 ++ docs/operations/ci-quality-gates.md | 5 +- docs/operations/release-cache-rollback.md | 27 ++++ scripts/check-release-admission.ts | 30 +---- scripts/lib/hosting-probe.ts | 106 +++++++++++++++- scripts/lib/runtime-config-switches.ts | 27 ++++ scripts/verify-hosting-headers.ts | 28 ++++- tests/unit/hosting-probe.test.ts | 122 ++++++++++++++++++- 10 files changed, 325 insertions(+), 36 deletions(-) create mode 100644 scripts/lib/runtime-config-switches.ts diff --git a/config/hosting/cache-policy.json b/config/hosting/cache-policy.json index 7fcc3936..46e786d5 100644 --- a/config/hosting/cache-policy.json +++ b/config/hosting/cache-policy.json @@ -1,5 +1,8 @@ { "schemaVersion": 1, + "transport": { + "alpnProtocols": ["h2"] + }, "surfaces": { "index": { "path": "/", @@ -23,6 +26,7 @@ "pathPattern": "/assets/*", "cacheControl": "public, max-age=31536000, immutable", "contentTypes": ["text/javascript", "application/javascript"], + "contentEncodings": ["br", "gzip", "zstd"], "securityHeaders": false }, "sourceMap": { diff --git a/config/hosting/response-headers.fixture.json b/config/hosting/response-headers.fixture.json index 504b10e5..6d301ac4 100644 --- a/config/hosting/response-headers.fixture.json +++ b/config/hosting/response-headers.fixture.json @@ -33,7 +33,8 @@ }, "hashedAsset": { "cache-control": "public, max-age=31536000, immutable", - "content-type": "text/javascript; charset=utf-8" + "content-type": "text/javascript; charset=utf-8", + "content-encoding": "gzip" }, "appRoute": { "cache-control": "no-cache", diff --git a/docs/architecture/static-delivery.md b/docs/architecture/static-delivery.md index 7cda8166..85e002e8 100644 --- a/docs/architecture/static-delivery.md +++ b/docs/architecture/static-delivery.md @@ -51,3 +51,12 @@ HTTP/1.1 groups its initial chunks in `vite.config.ts` and measures again whenever the shell changes ("초기 청크 수와 HTTP/1.1" in [`performance-evidence.md`](../operations/performance-evidence.md), review 1101/14.4). + +Serve JavaScript compressed (gzip, brotli or zstd). The bundle budget counts +gzip bytes; uncompressed, the initial JavaScript is about three times larger. +Both premises are declared in `config/hosting/cache-policy.json` +(`transport.alpnProtocols`, `hashedAsset.contentEncodings`), and the live probe +of FE-GATE-019 fails a host that does not meet them (review 1103/13-02). The +nginx example in +[`release-cache-rollback.md`](../operations/release-cache-rollback.md) turns +both on. diff --git a/docs/operations/ci-quality-gates.md b/docs/operations/ci-quality-gates.md index 6e24b5de..7b7d4a6f 100644 --- a/docs/operations/ci-quality-gates.md +++ b/docs/operations/ci-quality-gates.md @@ -335,7 +335,10 @@ contract rejects a production gate command that builds or omits the release root The hosting gate FE-GATE-019 also reads `.release/promoted-release`: it checks that archive's `dist` and requires the live host to serve a `release-manifest.json` with the candidate's `buildId` and `releaseId`, so a -host still serving an earlier release fails (1101/13-01). The workflow deploys +host still serving an earlier release fails (1101/13-01). Because a rebuild in +the same run shares those names, the served `config.json` must also equal the +candidate's outside the two emergency switches and the served `index.html` must +name the candidate's entry script (1103/13-01). The workflow deploys nothing itself. Between `promotion` and `production_gate` sits the `deployment` job, the project's deployment slot. It is empty by default: it reports `deployed=false`, FE-GATE-019 does not probe the host and ends `UNVERIFIED` diff --git a/docs/operations/release-cache-rollback.md b/docs/operations/release-cache-rollback.md index 2ec859a3..c5460b22 100644 --- a/docs/operations/release-cache-rollback.md +++ b/docs/operations/release-cache-rollback.md @@ -80,6 +80,24 @@ evidence for this one (review 1101/13-01). That release is `/dist` with `-- --release-root ` (FE-GATE-019 passes the promoted archive), otherwise the local `dist`. +Those two names come from the CI run, so a release rebuilt in the same run +carries them as well. The served `config.json` must therefore equal the +release's `dist/config.json`, the document release admission (FE-GATE-027) +admitted, in every field except the two emergency switches +`CAPABILITY_OVERRIDES` and `FEATURE_OVERRIDES` (FE-RB-001), and the served +`index.html` must name the release's entry script (review 1103/13-01). + +The probe also checks the two serving premises the bundle budget and the split +initial chunks rest on (review 1103/13-02): the entry script arrives with a +`Content-Encoding` from `hashedAsset.contentEncodings` (the budget counts gzip +bytes; uncompressed, the initial JavaScript is about three times larger), and +the TLS handshake negotiates a protocol from `transport.alpnProtocols` (`h2`; +over HTTP/1.1 the initial files queue for six connections). A host that cannot +meet them fails FE-GATE-019; a product that has to serve that way changes the +declaration in `config/hosting/cache-policy.json` in the same change that +groups its initial chunks ("초기 청크 수와 HTTP/1.1" in +[`performance-evidence.md`](performance-evidence.md)). + ### Example: nginx on a single server Written by hand for the default base path `/`; nothing in CI runs it. The live @@ -100,9 +118,18 @@ add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always; ```nginx server { listen 443 ssl; + # nginx 1.25.1 and later; before it, `listen 443 ssl http2;`. + http2 on; server_name app.example.com; # ssl_certificate / ssl_certificate_key ... + # The bundle budget counts gzip bytes, and FE-GATE-019 fails an + # uncompressed entry script (cache-policy.json `hashedAsset`). nginx + # compresses only text/html unless gzip_types names the rest. + gzip on; + gzip_vary on; + gzip_types text/javascript application/javascript application/json text/css image/svg+xml; + # The active release directory. Switch it with an atomic symlink rename. root /srv/frontend/current; diff --git a/scripts/check-release-admission.ts b/scripts/check-release-admission.ts index c9f28cf7..dbf826a8 100644 --- a/scripts/check-release-admission.ts +++ b/scripts/check-release-admission.ts @@ -12,6 +12,10 @@ import { unknownProductFeatureOverrides } from "../src/contracts/product-feature import { parseRuntimeConfigArtifact } from "../src/contracts/release-artifacts.ts"; import { EXPECTED_CONTRACT_SET_PACKAGES } from "../src/features/installed-contract-contributions.ts"; import { COMPILED_PRODUCT_FEATURE_IDS } from "../src/features/installed-product-manifest.ts"; +import { + changedRuntimeConfigBuildFields, + RUNTIME_CONFIG_EMERGENCY_SWITCHES, +} from "./lib/runtime-config-switches.ts"; /** * §6.4 / FE-GATE-027. Refuses to admit an artifact to an environment it was not @@ -30,17 +34,7 @@ import { COMPILED_PRODUCT_FEATURE_IDS } from "../src/features/installed-product- const RUNTIME_CONFIG_PATH = "dist/config.json"; const RECORD_PATH = "artifacts/release/deployment-admission.json"; - -/** - * 1101/13-05. The only fields an operator may change in a deployed config.json - * without a rebuild (docs/runbooks/FE-RB-001.md). Every other field belongs to - * the build: BUILD_ID and RELEASE_ID must still match the deployed HTML and - * release manifest, or every boot stops with CONFIG_BUILD_MISMATCH. - */ -const EMERGENCY_SWITCHES: ReadonlySet = new Set([ - "CAPABILITY_OVERRIDES", - "FEATURE_OVERRIDES", -]); +const EMERGENCY_SWITCHES = RUNTIME_CONFIG_EMERGENCY_SWITCHES; function refuse(reason: string): void { process.stderr.write(`release admission refused: ${reason}\n`); @@ -67,18 +61,6 @@ async function readRuntimeConfig(file: string): Promise { } } -function changedBuildFields(original: object, edited: object): string[] { - const before = new Map(Object.entries(original)); - const after = new Map(Object.entries(edited)); - return [...new Set([...before.keys(), ...after.keys()])] - .filter( - (field) => - !EMERGENCY_SWITCHES.has(field) && - JSON.stringify(before.get(field)) !== JSON.stringify(after.get(field)), - ) - .sort(); -} - async function main(): Promise { // `pnpm check:release-admission -- --config …` may pass the separator through. const argv = process.argv.slice(2); @@ -127,7 +109,7 @@ async function main(): Promise { if (options.original !== undefined) { const original = await readRuntimeConfig(options.original); if (original === null) return; - const changed = changedBuildFields(original, config); + const changed = changedRuntimeConfigBuildFields(original, config); if (changed.length > 0) { refuse( `${configPath} changes ${changed.join(", ")}; without a rebuild only ` + diff --git a/scripts/lib/hosting-probe.ts b/scripts/lib/hosting-probe.ts index faf6473b..2caf9ab6 100644 --- a/scripts/lib/hosting-probe.ts +++ b/scripts/lib/hosting-probe.ts @@ -1,4 +1,8 @@ +import { isIP } from "node:net"; +import { connect } from "node:tls"; + import type { InstalledServiceWorkerSelection } from "../../src/contracts/service-worker.ts"; +import { changedRuntimeConfigBuildFields } from "./runtime-config-switches.ts"; const LOOPBACK_IPV4 = /^127(?:\.\d{1,3}){3}$/; @@ -39,6 +43,49 @@ export type ProbeResult = Readonly<{ export type ResponseHeaders = Record>; export type HostingFetcher = (url: URL) => Promise; export type ReleaseIdentity = Readonly<{ buildId: string; releaseId: string }>; +/** The promoted candidate: its manifest names and the texts of its dist/config.json and dist/index.html. */ +export type CandidateRelease = ReleaseIdentity & Readonly<{ runtimeConfig: string; indexHtml: string }>; +export type ProbeTransport = Readonly<{ + fetcher?: HostingFetcher; + /** The ALPN protocol the host negotiates over TLS, or null when none. */ + negotiateAlpn?: (base: URL) => Promise; + /** Accepted protocols (`transport.alpnProtocols` in config/hosting/cache-policy.json); empty skips the check. */ + alpnProtocols?: readonly string[]; +}>; + +/** + * 1103/13-02. Node's fetch speaks HTTP/1.1 even to a host that offers h2, so + * the protocol a browser gets is read from the TLS handshake instead: the + * client offers h2 and http/1.1 and the host picks one. The certificate is + * verified as fetch verifies it. + */ +export function negotiatedAlpnProtocol(base: URL, timeoutMs = 10_000): Promise { + return new Promise((resolve, reject) => { + const host = base.hostname.replace(/^\[|\]$/gu, ""); + const socket = connect({ + host, + port: Number(base.port || 443), + ...(isIP(host) === 0 ? { servername: host } : {}), + ALPNProtocols: ["h2", "http/1.1"], + }); + socket.setTimeout(timeoutMs, () => socket.destroy(new Error("TLS handshake timed out"))); + socket.once("secureConnect", () => { + const protocol = socket.alpnProtocol; + socket.end(); + resolve(typeof protocol === "string" ? protocol : null); + }); + socket.once("error", reject); + }); +} + +function parsedJsonObject(text: string | null): object | null { + try { + const value: unknown = JSON.parse(text ?? ""); + return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null; + } catch { + return null; + } +} /** `buildId` and `releaseId` of a release-manifest.json text, or null. */ export function releaseIdentity(manifest: string | null): ReleaseIdentity | null { @@ -64,13 +111,24 @@ export function releaseIdentity(manifest: string | null): ReleaseIdentity | null * * 1101/13-01. The served release manifest must name the candidate's build and * release. Correct headers on an earlier release are not evidence for this one. + * + * 1103/13-01. Those names come from the CI run, so a release rebuilt in the + * same run (say with the local profile) carries them too. The served + * config.json must equal the candidate's, the one release admission + * (FE-GATE-027) admitted, except for the two emergency switches FE-RB-001 may + * change; and the served index.html must name the candidate's entry script. + * + * 1103/13-02. The host must negotiate a declared protocol (HTTP/2): the + * template splits its initial chunks on that premise. */ export async function probeLiveRelease( base: URL, paths: Readonly>, - candidate: ReleaseIdentity, - fetcher: HostingFetcher = (url) => fetch(url, { redirect: "follow" }), + candidate: CandidateRelease, + transport: ProbeTransport = {}, ): Promise<{ responses: ResponseHeaders; results: ProbeResult[] }> { + const fetcher = transport.fetcher ?? ((url: URL) => fetch(url, { redirect: "follow" })); + const negotiateAlpn = transport.negotiateAlpn ?? negotiatedAlpnProtocol; const responses: ResponseHeaders = {}; const results: ProbeResult[] = []; const probe = async (surface: string, pathname: string): Promise => { @@ -145,6 +203,50 @@ export async function probeLiveRelease( passed: entryScript !== null && observed === entryScript, }); } + const candidateEntryScript = servedEntryScript(candidate.indexHtml); + results.push({ + surface: "index", + header: "candidate-entry-script", + expected: candidateEntryScript, + observed: entryScript, + passed: candidateEntryScript !== null && entryScript === candidateEntryScript, + }); + if ("runtimeConfig" in paths) { + const served = parsedJsonObject(bodies["runtimeConfig"] ?? null); + const admitted = parsedJsonObject(candidate.runtimeConfig); + const changed = served && admitted ? changedRuntimeConfigBuildFields(admitted, served) : null; + results.push({ + surface: "runtimeConfig", + header: "build-fields", + expected: [], + observed: changed ?? "unreadable", + ...(changed === null + ? { reason: "the served or the candidate config.json is not a JSON object" } + : changed.length > 0 + ? { reason: "differs from the candidate's config.json beyond the emergency switches" } + : {}), + passed: changed !== null && changed.length === 0, + }); + } + const alpnProtocols = transport.alpnProtocols ?? []; + if (alpnProtocols.length > 0) { + let observed: string | null; + try { + observed = await negotiateAlpn(base); + } catch (error: unknown) { + observed = error instanceof Error ? error.name : "UnknownError"; + } + results.push({ + surface: "transport", + header: "alpn", + expected: alpnProtocols, + observed, + ...(observed !== null && alpnProtocols.includes(observed) + ? {} + : { reason: "the split initial chunks assume HTTP/2 (docs/architecture/static-delivery.md)" }), + passed: observed !== null && alpnProtocols.includes(observed), + }); + } return { responses, results }; } diff --git a/scripts/lib/runtime-config-switches.ts b/scripts/lib/runtime-config-switches.ts new file mode 100644 index 00000000..ec66ea74 --- /dev/null +++ b/scripts/lib/runtime-config-switches.ts @@ -0,0 +1,27 @@ +/** + * 1101/13-05. The only fields an operator may change in a deployed config.json + * without a rebuild (docs/runbooks/FE-RB-001.md). Every other field belongs to + * the build: BUILD_ID and RELEASE_ID must still match the deployed HTML and + * release manifest, or every boot stops with CONFIG_BUILD_MISMATCH. + * + * 1103/13-01. The live hosting probe (FE-GATE-019) compares the served + * config.json with the promoted candidate's by the same rule, so the release + * admission and the probe agree on what an edited document may change. + */ +export const RUNTIME_CONFIG_EMERGENCY_SWITCHES: ReadonlySet = new Set([ + "CAPABILITY_OVERRIDES", + "FEATURE_OVERRIDES", +]); + +/** Fields other than the emergency switches whose values differ, sorted. */ +export function changedRuntimeConfigBuildFields(original: object, edited: object): string[] { + const before = new Map(Object.entries(original)); + const after = new Map(Object.entries(edited)); + return [...new Set([...before.keys(), ...after.keys()])] + .filter( + (field) => + !RUNTIME_CONFIG_EMERGENCY_SWITCHES.has(field) && + JSON.stringify(before.get(field)) !== JSON.stringify(after.get(field)), + ) + .sort(); +} diff --git a/scripts/verify-hosting-headers.ts b/scripts/verify-hosting-headers.ts index 5d883661..e9e6365b 100644 --- a/scripts/verify-hosting-headers.ts +++ b/scripts/verify-hosting-headers.ts @@ -99,11 +99,20 @@ if (liveTarget?.passed && !slotEmpty) { ), ); const candidateManifest = await readFile(path.join(distRoot, "release-manifest.json"), "utf8").catch(() => null); - const candidate = releaseIdentity(candidateManifest); - if (!candidate) { + const identity = releaseIdentity(candidateManifest); + if (!identity) { throw new Error(`${distRoot}/release-manifest.json does not name a buildId and releaseId`); } - const probed = await probeLiveRelease(liveTarget.url, paths, candidate); + // 1103/13-01. The served config.json and index.html are compared with the + // candidate's, not only the manifest names a rebuild in the same run shares. + const candidate = { + ...identity, + runtimeConfig: await readFile(path.join(distRoot, "config.json"), "utf8"), + indexHtml: await readFile(path.join(distRoot, "index.html"), "utf8"), + }; + const probed = await probeLiveRelease(liveTarget.url, paths, candidate, { + alpnProtocols: strings(recordValue(cachePolicy.transport).alpnProtocols), + }); responses = probed.responses; probeResults.push(...probed.results); } else if (liveTarget && !liveTarget.passed) { @@ -148,6 +157,19 @@ for (const [surface, policy] of requiredSurfaces) { observed: observedContentType, passed: observedMime !== undefined && contentTypes.includes(observedMime), }); + // 1103/13-02. The bundle budget counts gzip bytes. The probe's fetch offers + // br and gzip, so an uncompressed answer is the host's choice. + const contentEncodings = strings(policy.contentEncodings); + if (contentEncodings.length > 0) { + const observedEncoding = responses[surface]?.["content-encoding"]; + results.push({ + surface, + header: "content-encoding", + expected: contentEncodings, + observed: observedEncoding, + passed: observedEncoding !== undefined && contentEncodings.includes(observedEncoding.trim().toLowerCase()), + }); + } if (policy.securityHeaders === true) { for (const [header, expected] of Object.entries(securityHeaders)) { const observedSecurity = responses[surface]?.[header.toLowerCase()]; diff --git a/tests/unit/hosting-probe.test.ts b/tests/unit/hosting-probe.test.ts index 258e0825..86e6aa34 100644 --- a/tests/unit/hosting-probe.test.ts +++ b/tests/unit/hosting-probe.test.ts @@ -150,11 +150,21 @@ describe("SPA fallback and worker script surfaces (1101/13-04)", () => { releaseManifest: "/release-manifest.json", appRoute: "/__probe/deep-link", }; - const CANDIDATE = { buildId: "gitea-42-1", releaseId: "refs/tags/v1.2.0-42-1" }; + const IDENTITY = { buildId: "gitea-42-1", releaseId: "refs/tags/v1.2.0-42-1" }; + const CONFIG = JSON.stringify({ + APP_ENV: "production", + AUTH_MODE: "external", + API_BASE_URL: "https://api.frontend.example.test/", + BUILD_ID: IDENTITY.buildId, + RELEASE_ID: IDENTITY.releaseId, + CAPABILITY_OVERRIDES: {}, + FEATURE_OVERRIDES: {}, + }); + const CANDIDATE = { ...IDENTITY, runtimeConfig: CONFIG, indexHtml: INDEX }; const RELEASE: Record = { "/": [200, INDEX], - "/config.json": [200, "{}"], - "/release-manifest.json": [200, JSON.stringify({ schemaVersion: 2, ...CANDIDATE })], + "/config.json": [200, CONFIG], + "/release-manifest.json": [200, JSON.stringify({ schemaVersion: 2, ...IDENTITY })], "/assets/index-A1.js": [200, ""], }; const host = (routes: Record) => async (url: URL) => { @@ -164,8 +174,14 @@ describe("SPA fallback and worker script surfaces (1101/13-04)", () => { return response; }; const base = new URL("https://frontend.example.test/"); - const failed = async (routes: Record) => - (await probeLiveRelease(base, PATHS, CANDIDATE, host(routes))).results + const probe = (routes: Record, alpn: string | null = "h2") => + probeLiveRelease(base, PATHS, CANDIDATE, { + fetcher: host(routes), + negotiateAlpn: async () => alpn, + alpnProtocols: ["h2"], + }); + const failed = async (routes: Record, alpn?: string | null) => + (await probe(routes, alpn)).results .filter((result) => !result.passed) .map((result) => `${result.surface} ${result.header}`); @@ -196,6 +212,72 @@ describe("SPA fallback and worker script surfaces (1101/13-04)", () => { ).toEqual(["releaseManifest build-id", "releaseManifest release-id"]); }); + // 1103/13-01. The manifest names come from the CI run, so a release rebuilt + // in the same run with the local profile (APP_ENV=local, AUTH_MODE=demo, a + // loopback API) passed. The candidate's config.json is the one release + // admission (FE-GATE-027) admitted, so the served one must equal it. + it("fails a host whose config.json is not the candidate's", async () => { + const local = JSON.stringify({ + ...JSON.parse(CONFIG), + APP_ENV: "local", + AUTH_MODE: "demo", + API_BASE_URL: "http://localhost:8080/", + }); + const { results } = await probe({ + ...RELEASE, + "/__probe/deep-link": [200, INDEX], + "/config.json": [200, local], + }); + expect(results.filter(({ passed }) => !passed)).toEqual([ + expect.objectContaining({ + surface: "runtimeConfig", + header: "build-fields", + observed: ["API_BASE_URL", "APP_ENV", "AUTH_MODE"], + }), + ]); + }); + + // FE-RB-001 changes the two emergency switches without a rebuild; the + // probe after it must still pass. + it("passes a host whose config.json differs only in the emergency switches", async () => { + const switched = JSON.stringify({ + ...JSON.parse(CONFIG), + CAPABILITY_OVERRIDES: { realtime: "DISABLED" }, + FEATURE_OVERRIDES: { "reference-feature": false }, + }); + expect( + await failed({ ...RELEASE, "/__probe/deep-link": [200, INDEX], "/config.json": [200, switched] }), + ).toEqual([]); + }); + + it("fails a host whose config.json is unreadable", async () => { + expect( + await failed({ ...RELEASE, "/__probe/deep-link": [200, INDEX], "/config.json": [200, ""] }), + ).toEqual(["runtimeConfig build-fields"]); + }); + + // 1103/13-01. A build of other sources under the same run names serves its + // own entry script; the fallback check compared the host only with itself. + it("fails a host whose index.html names another entry script than the candidate's", async () => { + const other = ''; + expect( + await failed({ + ...RELEASE, + "/": [200, other], + "/__probe/deep-link": [200, other], + "/assets/index-B2.js": [200, ""], + }), + ).toEqual(["index candidate-entry-script"]); + }); + + // 1103/13-02. The split initial chunks assume HTTP/2 + // (docs/architecture/static-delivery.md); over HTTP/1.1 they queue. + it("fails a host that does not negotiate a declared protocol", async () => { + const release: Record = { ...RELEASE, "/__probe/deep-link": [200, INDEX] }; + expect(await failed(release, "http/1.1")).toEqual(["transport alpn"]); + expect(await failed(release, null)).toEqual(["transport alpn"]); + }); + it("fails when the served release manifest is unreadable", async () => { expect( await failed({ @@ -213,6 +295,7 @@ describe("verify-hosting-headers on a promoted release root (1101/13-01)", () => async function verify( distFiles: Readonly>, env: Readonly> = {}, + editFixture?: (responses: Record>) => void, ) { const root = await mkdtemp(path.join(tmpdir(), "hosting-release-root-")); try { @@ -220,6 +303,14 @@ describe("verify-hosting-headers on a promoted release root (1101/13-01)", () => for (const file of ["cache-policy.json", "security-headers.json", "response-headers.fixture.json"]) { await copyFile(`config/hosting/${file}`, path.join(root, "config/hosting", file)); } + if (editFixture) { + const fixturePath = path.join(root, "config/hosting/response-headers.fixture.json"); + const fixture = JSON.parse(await readFile(fixturePath, "utf8")) as { + responses: Record>; + }; + editFixture(fixture.responses); + await writeFile(fixturePath, JSON.stringify(fixture)); + } for (const [file, content] of Object.entries(distFiles)) { await mkdir(path.dirname(path.join(root, "candidate/dist", file)), { recursive: true }); await writeFile(path.join(root, "candidate/dist", file), content); @@ -269,4 +360,25 @@ describe("verify-hosting-headers on a promoted release root (1101/13-01)", () => expect(result.status).toBe(3); expect(result.stderr).toContain("deployment slot"); }); + + // 1103/13-02. The bundle budget counts gzip bytes; an uncompressed entry + // script means about three times as many bytes on the wire. + it("declares compression for hashed assets and HTTP/2 for the host", async () => { + const policy = JSON.parse(await readFile("config/hosting/cache-policy.json", "utf8")) as { + transport?: { alpnProtocols?: string[] }; + surfaces: Record; + }; + expect(policy.transport?.alpnProtocols).toEqual(["h2"]); + expect(policy.surfaces["hashedAsset"]?.contentEncodings).toEqual( + expect.arrayContaining(["br", "gzip"]), + ); + }); + + it("fails a hashed asset served without a declared content encoding", async () => { + const result = await verify(DIST, {}, (responses) => { + delete responses["hashedAsset"]?.["content-encoding"]; + }); + expect(result.failed, result.stderr).toEqual(["hashedAsset content-encoding"]); + expect(result.status).toBe(1); + }); }); From 2e12d2f0d128b68e86c182351989d503a6ab2796 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 20:43:19 +0900 Subject: [PATCH 07/12] =?UTF-8?q?fix(ci):=20=EB=B0=B0=ED=8F=AC=20=EC=8A=AC?= =?UTF-8?q?=EB=A1=AF=EC=9D=B4=20=EC=8A=B9=EA=B2=A9=20=ED=9B=84=EB=B3=B4?= =?UTF-8?q?=EB=A5=BC=20=EB=B0=9B=EA=B2=8C=20=ED=95=98=EA=B3=A0=20secret?= =?UTF-8?q?=EC=9D=84=20deploy=20=EB=8B=A8=EA=B3=84=EC=97=90=EB=A7=8C=20?= =?UTF-8?q?=EC=A4=80=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: (1) 배포 슬롯 계약은 단계 종류만 제한하고 "마지막이 deploy 하나"만 강제했다. checkout → setup-node → frozen-install → deploy(script)처럼 후보 archive를 받지 않고 다시 빌드하는 슬롯도 check:ci를 통과했고, 생성된 job 이름은 그대로 deploy-promoted-release였다(리뷰 실험 E-3). (2) 생성기는 슬롯의 환경 바인딩을 job 수준 env:로 썼다. 그래서 secrets.* 배포 자격 증명이 checkout, setup-node, frozen-install과 제3자 download action에도 보였다. 고른 방법: (1) deploy 단계에 script가 있으면 promoted-release 전송 하나만 download하고, 그 경로의 release-candidate.tar.gz를 extract하고, CANDIDATE_ARCHIVE_SHA256을 immutable_build의 digest로 바인딩해야 한다. extract는 verify-ci-candidate-archive.ts가 digest로 확인한다. 빈 슬롯은 그대로 허용한다. (2) 배포 슬롯의 secrets.* 바인딩은 deploy 단계의 env:로만 렌더링한다. vars.*와 후보 digest는 job 수준에 남는다(extract가 digest를 쓴다). 버린 대안: 슬롯 단계를 템플릿이 통째로 고정하기. 다음 커밋의 제품 overlay가 채우는 모양을 고정하고, gates.json으로 채우는 길은 이 규칙으로 막는다. 위험·한계: 슬롯이 받은 파일을 deploy 스크립트가 실제로 올리는지는 계약이 볼 수 없다. 그것은 FE-GATE-019의 config.json·entry 대조(앞 커밋)가 결과로 본다. 템플릿 슬롯은 비어 있어 생성 workflow 바이트는 바뀌지 않는다. 검증: ci-workflow-generation.test.ts에 후보 없이 deploy하는 슬롯과 digest 없이 extract하는 슬롯의 거절, secret이 deploy 단계 env에만 한 번 나오는 것을 더했다(고치기 전 3건 실패). 425건 통과. check:ci PASS, CI workflow bytes PASS. Refs: docs/reviews/2026-11-03-maturity-review/13-build-release-supply-chain.md 13-01, 13-05 --- docs/operations/ci-quality-gates.md | 7 +++- scripts/contracts/ci-gates.ts | 42 +++++++++++++++++++++++ scripts/generate-ci-workflow.ts | 22 ++++++++++-- tests/unit/ci-workflow-generation.test.ts | 21 +++++++++++- 4 files changed, 87 insertions(+), 5 deletions(-) diff --git a/docs/operations/ci-quality-gates.md b/docs/operations/ci-quality-gates.md index 7b7d4a6f..c54fd10e 100644 --- a/docs/operations/ci-quality-gates.md +++ b/docs/operations/ci-quality-gates.md @@ -348,7 +348,12 @@ generate:ci-workflow`. The contract allows the steps `checkout`, `setup-node`, `frozen-install`, `download` (the `promoted-release` transfer), `extract`, and one final `deploy` step whose `script` names a package script. Its variables may only be the `CANDIDATE_ARCHIVE_SHA256` digest of `immutable_build` and -`vars.*` or `secrets.*` values. The `deploy` step writes `deployed=true` only +`vars.*` or `secrets.*` values. A slot with a deploy script must download only +the `promoted-release` transfer, extract its `release-candidate.tar.gz` and +bind the digest, so the script deploys the promoted candidate rather than a +rebuild (1103/13-01). `secrets.*` values are rendered on the `deploy` step +alone, not on the job, so checkout, setup-node and the download action never +see them (1103/13-05). The `deploy` step writes `deployed=true` only after the script succeeds. The job owns no gate, so filling it changes neither gate ownership nor the contract baseline. Browser boot, live API traffic, smoke after a provider switch, and anything the runbook marks as needing provider verification are diff --git a/scripts/contracts/ci-gates.ts b/scripts/contracts/ci-gates.ts index 066250b3..aa53ef0d 100644 --- a/scripts/contracts/ci-gates.ts +++ b/scripts/contracts/ci-gates.ts @@ -1027,6 +1027,7 @@ function validateContractSemantics( if (duplicate || foreign.length > 0) { issue(`deployment slot binding must be the candidate digest or a vars.* or secrets.* value: ${job.id}`); } + for (const failure of deploymentSlotInputFailures(job)) issue(failure); } else if (duplicate || JSON.stringify(job.environment) !== JSON.stringify(expectedEnvironmentBindings[job.id])) { issue(`job environment binding drift: ${job.id}`); } @@ -1244,6 +1245,47 @@ function validateCanonicalStepFields( } } +/** + * 1103/13-01. A slot that runs a deploy script deploys the promoted candidate: + * it downloads the promoted-release transfer and extracts its + * release-candidate.tar.gz, checked against the digest immutable_build + * recorded, before the script runs. A slot that rebuilt instead passed the + * contract under the name deploy-promoted-release, and FE-GATE-019 could not + * tell the rebuild from the candidate. + */ +function deploymentSlotInputFailures(job: z.infer): string[] { + const deploy = job.steps.find((step) => step.kind === "deploy"); + if (deploy?.kind !== "deploy" || deploy.script === undefined) return []; + const failures: string[] = []; + const downloads = job.steps.filter((step) => step.kind === "download"); + const download = downloads[0]; + const extract = job.steps.find((step) => step.kind === "extract"); + if ( + downloads.length !== 1 || + download?.kind !== "download" || + download.transferId !== "promoted-release" || + extract?.kind !== "extract" || + extract.archivePath !== `${download.path}/release-candidate.tar.gz` || + job.steps.indexOf(download) > job.steps.indexOf(extract) + ) { + failures.push( + `deployment slot with a deploy script must download only the promoted-release transfer and extract its release-candidate.tar.gz before deploying: ${job.id}`, + ); + } + if ( + !job.environment.some( + ({ name, value }) => + name === "CANDIDATE_ARCHIVE_SHA256" && + value === "${{ needs.immutable_build.outputs.archive_sha256 }}", + ) + ) { + failures.push( + `deployment slot with a deploy script must bind CANDIDATE_ARCHIVE_SHA256 so its extract step checks the promoted archive: ${job.id}`, + ); + } + return failures; +} + function validateJobStepKinds( job: z.infer, issue: (message: string, path?: PropertyKey[]) => void, diff --git a/scripts/generate-ci-workflow.ts b/scripts/generate-ci-workflow.ts index b37d8b58..81db43cd 100644 --- a/scripts/generate-ci-workflow.ts +++ b/scripts/generate-ci-workflow.ts @@ -144,9 +144,10 @@ function renderJob( if (job.kind === "deployment") { lines.push(" outputs:", " deployed: ${{ steps.deploy.outputs.deployed }}"); } - if (job.environment.length > 0) { + const jobEnvironment = job.environment.filter((binding) => !isStepScopedSecret(job, binding)); + if (jobEnvironment.length > 0) { lines.push(" env:"); - for (const binding of job.environment) { + for (const binding of jobEnvironment) { lines.push(` ${binding.name}: ${yamlScalar(binding.value)}`); } } @@ -276,11 +277,15 @@ function renderStep( ]; // 1101/13-01. `run` fails on the first failing command, so deployed=true // is written only after the project's script succeeded. - case "deploy": + case "deploy": { + const secrets = job.environment.filter((binding) => isStepScopedSecret(job, binding)); return step.script ? [ " - name: Deploy the promoted release", " id: deploy", + ...(secrets.length > 0 + ? [" env:", ...secrets.map((binding) => ` ${binding.name}: ${yamlScalar(binding.value)}`)] + : []), " run: |", // The contract limits the name to [A-Za-z0-9:_-], a plain shell word. ` corepack pnpm ${step.script}`, @@ -291,6 +296,7 @@ function renderStep( " id: deploy", ' run: echo "deployed=false" >> "$GITHUB_OUTPUT"', ]; + } case "upload": { const lines = [ ` - name: Upload ${humanize(step.transferId)}`, @@ -310,6 +316,16 @@ function renderStep( } } +/** + * 1103/13-05. Job env reaches every step of the job: checkout, setup-node and + * the third-party download action as well. In the deployment slot a + * `secrets.*` binding is rendered on the deploy step instead, the one step + * that uses it. + */ +function isStepScopedSecret(job: CiWorkflowJob, binding: CiWorkflowJob["environment"][number]): boolean { + return job.kind === "deployment" && /^\$\{\{ secrets\./u.test(binding.value); +} + function requiredStepActionUses(stepKind: string): string { const uses = resolveCiStepActionUses(stepKind); if (!uses) throw new TypeError(`workflow step has no registered CI action: ${stepKind}`); diff --git a/tests/unit/ci-workflow-generation.test.ts b/tests/unit/ci-workflow-generation.test.ts index 1fa8fb94..ea0d5866 100644 --- a/tests/unit/ci-workflow-generation.test.ts +++ b/tests/unit/ci-workflow-generation.test.ts @@ -386,7 +386,14 @@ describe("CI gate contract", () => { ); const workflow = renderCiWorkflow(contract); const job = workflow.slice(workflow.indexOf(" deployment:\n"), workflow.indexOf(" production_gate:\n")); - expect(job).toContain('DEPLOY_SSH_KEY: "${{ secrets.DEPLOY_SSH_KEY }}"'); + // 1103/13-05. Job env reaches every step, checkout and the third-party + // download action included; a credential belongs to the deploy step only. + const jobEnvironment = job.slice(job.indexOf(" env:\n"), job.indexOf(" steps:\n")); + const deployStep = job.slice(job.indexOf(" - name: Deploy the promoted release")); + expect(jobEnvironment).toContain('DEPLOY_HOST: "${{ vars.DEPLOY_HOST }}"'); + expect(jobEnvironment).not.toContain("secrets."); + expect(deployStep).toContain(' env:\n DEPLOY_SSH_KEY: "${{ secrets.DEPLOY_SSH_KEY }}"\n'); + expect(job.match(/secrets\./gu)).toHaveLength(1); expect(job.indexOf("--extract-to")).toBeLessThan(job.indexOf("corepack pnpm deploy:release")); expect(job.indexOf("corepack pnpm deploy:release")).toBeLessThan( job.indexOf('echo "deployed=true" >> "$GITHUB_OUTPUT"'), @@ -411,6 +418,18 @@ describe("CI gate contract", () => { (slot: Record) => slot.steps.push({ kind: "checkout" }), /deploy step/u, ], + // 1103/13-01. A slot that rebuilt (or deployed anything but the promoted + // archive) passed the contract under the name deploy-promoted-release. + [ + "a slot that deploys without the promoted candidate", + (slot: Record) => slot.steps.splice(3, 2), + /promoted-release/u, + ], + [ + "a slot that extracts the candidate without its digest", + (slot: Record) => slot.environment.shift(), + /CANDIDATE_ARCHIVE_SHA256/u, + ], ])("rejects %s (1101/13-01)", async (_name, mutate, diagnostic) => { const contract = fillDeploymentSlot( JSON.parse(JSON.stringify(await loadCiGateContract(process.cwd()))), From 4c4248aac54bec50a84fdbbfb4905cdaaf4a0a4c Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 20:48:50 +0900 Subject: [PATCH 08/12] =?UTF-8?q?feat(ci):=20=EC=A0=9C=ED=92=88=EC=9D=B4?= =?UTF-8?q?=20=EB=B0=B0=ED=8F=AC=20job=EA=B3=BC=20merge=20=EA=B2=80?= =?UTF-8?q?=EC=82=AC=EB=A5=BC=20=EC=A0=9C=ED=92=88=20=EC=86=8C=EC=9C=A0=20?= =?UTF-8?q?overlay=EC=97=90=20=EC=A0=81=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 배포 슬롯을 채우거나 제품 전용 merge 검사를 더하려면 템플릿 소유 config/ci/gates.json(약 3,000줄)과 생성 workflow를 고쳐야 했다. 문서도 "deployment job을 gates.json에서 고치라"고 적었다. 템플릿 gates.json이 바뀔 때마다 제품은 큰 JSON과 생성 YAML의 충돌을 손으로 풀어야 했고, 다운스트림 tech-log는 이미 제품 커밋 3개에서 gates.json을 고쳤다. 고른 방법: 제품 소유 config/ci/product-gates.json을 둔다. 템플릿은 빈 파일로 싣고 고치지 않는다. 담을 수 있는 것은 둘뿐이다. - deployment: deploy package script와 vars.*·secrets.* 바인딩. 나머지 슬롯(promoted-release download, digest로 확인하는 extract, deploy)은 템플릿이 렌더링하고, 채운 계약을 다시 parse해 슬롯 규칙(앞 커밋)을 그대로 적용한다. secret은 deploy 단계에만 간다. gates.json과 overlay 양쪽에서 슬롯을 채우면 거절한다. - mergeGates: PRODUCT-GATE-NNN id의 package script. 템플릿 job 뒤의 product_merge_gate job이 merge와 같은 조건에서 matrix로 돈다. FE-GATE id·명령·산출물·readiness 공식은 건드리지 못한다. loadCiGateContract와 생성기, check:ci가 두 파일을 함께 읽고, 계약 기준선(contract-baseline.json)은 템플릿 계약만 센다. 없는 script는 거절하고, 제품 gate script는 ungated 검사에서 gated로 센다. 버린 대안: 저장소 변수로 배포 명령만 받기(제품 게이트를 못 풀고 실행할 명령이 저장소 밖에 숨는다), 제품 전용 workflow 파일(Gitea에서 run 사이 산출물 전달이 검증되지 않았다). 위험·한계: 제품 gate는 ci:gate의 로그·증거 산출물과 readiness 공식 밖이다. merge를 막으려면 제품이 그 job을 필수 검사로 지정한다. 생성 workflow는 여전히 커밋되는 파일이라, 템플릿 변경과 같은 줄을 건드리면 재생성이 필요하다. 실제 Gitea runner에서는 돌리지 않았다. 검증: tests/unit/product-ci-overlay.test.ts 11건(빈 overlay, 슬롯 채우기와 기준선 유지, 양쪽 채우기 거절, 없는 script 거절, 제품 job 렌더링과 실행 확인, 스키마 거절 6건). 작업 트리에서 overlay와 script를 채워 generate:ci-workflow → check:ci PASS, CI workflow bytes PASS, 생성 YAML 파싱 확인 후 되돌렸다. 그 상태의 workflow와 gates.json에 템플릿 변경(게이트 이름 2개)을 diff3로 3-way 병합하면 충돌 0이다. ci-workflow-generation 425건, check:ci PASS. Refs: docs/reviews/2026-11-03-maturity-review/12-guardrails-ci.md 12-07 --- config/ci/product-gates.json | 5 + docs/manual/03-outside-feature-folder.md | 1 + docs/operations/ci-quality-gates.md | 41 ++++- scripts/check-ci-contract.ts | 15 +- scripts/contracts/ci-gates.ts | 26 +++- scripts/contracts/product-ci-overlay.ts | 146 ++++++++++++++++++ scripts/generate-ci-workflow.ts | 74 ++++++++- scripts/verify-hosting-headers.ts | 2 +- tests/unit/product-ci-overlay.test.ts | 184 +++++++++++++++++++++++ 9 files changed, 473 insertions(+), 21 deletions(-) create mode 100644 config/ci/product-gates.json create mode 100644 scripts/contracts/product-ci-overlay.ts create mode 100644 tests/unit/product-ci-overlay.test.ts diff --git a/config/ci/product-gates.json b/config/ci/product-gates.json new file mode 100644 index 00000000..2849a590 --- /dev/null +++ b/config/ci/product-gates.json @@ -0,0 +1,5 @@ +{ + "schemaVersion": 1, + "deployment": null, + "mergeGates": [] +} diff --git a/docs/manual/03-outside-feature-folder.md b/docs/manual/03-outside-feature-folder.md index 1c13012f..0a777c43 100644 --- a/docs/manual/03-outside-feature-folder.md +++ b/docs/manual/03-outside-feature-folder.md @@ -107,6 +107,7 @@ release admission refused for staging: - `src/contracts/product-contracts.ts`: 제품 인증 프로필이나 제품 런타임 설정 키가 필요할 때. - 템플릿 파일 `src/contracts/rest-profiles.ts`는 고치지 않는다. - `config/runtime/.json`: 환경별로 기능을 끄고 싶을 때(`FEATURE_OVERRIDES`). +- `config/ci/product-gates.json`: 배포 job(`deployment`)을 채우거나 제품 전용 merge 검사(`PRODUCT-GATE-NNN`)를 더할 때. 템플릿 파일 `config/ci/gates.json`은 고치지 않는다. 형식은 [`ci-quality-gates.md`](../operations/ci-quality-gates.md)에 있다. - `package.json`, lockfile, `config/security/dependency-change-evidence.json`: 계약 패키지를 더할 때(B절). 정본 표에 없는 것: diff --git a/docs/operations/ci-quality-gates.md b/docs/operations/ci-quality-gates.md index c54fd10e..63634d0f 100644 --- a/docs/operations/ci-quality-gates.md +++ b/docs/operations/ci-quality-gates.md @@ -342,9 +342,44 @@ name the candidate's entry script (1103/13-01). The workflow deploys nothing itself. Between `promotion` and `production_gate` sits the `deployment` job, the project's deployment slot. It is empty by default: it reports `deployed=false`, FE-GATE-019 does not probe the host and ends `UNVERIFIED` -(exit 3), and the production stage stays open. To fill it, edit the -`deployment` job in `config/ci/gates.json` and run `corepack pnpm -generate:ci-workflow`. The contract allows the steps `checkout`, `setup-node`, +(exit 3), and the production stage stays open. To fill it, set `deployment` +in the product-owned `config/ci/product-gates.json` and run `corepack pnpm +generate:ci-workflow` (1103/12-07): + +```json +{ + "schemaVersion": 1, + "deployment": { + "script": "deploy:desktop", + "environment": [ + { "name": "DEPLOY_HOST", "value": "${{ vars.DEPLOY_HOST }}" }, + { "name": "DEPLOY_SSH_KEY", "value": "${{ secrets.DEPLOY_SSH_KEY }}" } + ] + }, + "mergeGates": [] +} +``` + +The template renders the rest of the slot: it downloads the `promoted-release` +transfer, extracts it to `.release/promoted-release` against the candidate +digest, then runs the script, which deploys `.release/promoted-release/dist`. +`environment` takes only `vars.*` and `secrets.*` values. The template ships +this file empty and never changes it, so a template sync does not meet it; +`config/ci/gates.json` stays the template's, and its contract baseline counts +the template contract only. A slot filled in both files is refused. + +`mergeGates` adds the product's own checks, such as a contract check against +the paired backend: `{ "id": "PRODUCT-GATE-001", "name": "backend-contract", +"script": "check:backend-contract" }`. Ids are `PRODUCT-GATE-NNN`; the +`FE-GATE-NNN` ids, their commands, artifacts and readiness formula stay the +template's. Each runs as `corepack pnpm