From b5f28e523621ae1c04623c0f13aca3e470f58823 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 20 Nov 2026 13:13:25 +0900 Subject: [PATCH 1/2] =?UTF-8?q?fix(ci):=20=EC=BB=A8=ED=85=8C=EC=9D=B4?= =?UTF-8?q?=EB=84=88=20=EB=9E=98=ED=8D=BC=EA=B0=80=20TERM=C2=B7INT=C2=B7HU?= =?UTF-8?q?P=EC=97=90=EB=8F=84=20artifacts=EB=A5=BC=20=EB=90=98=EA=B0=80?= =?UTF-8?q?=EC=A0=B8=EC=98=A4=EA=B3=A0=20=EC=BB=A8=ED=85=8C=EC=9D=B4?= =?UTF-8?q?=EB=84=88=EB=A5=BC=20=EC=A7=80=EC=9A=B4=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: FE-GATE-013을 감싸는 `scripts/run-in-system-container.sh`는 게이트의 `docker exec`를 앞에서 돌리고, 끝난 뒤에야 `artifacts/`를 되가져온다. bash는 앞 명령이 끝나야 trap을 돌린다. - 게이트 도중 TERM(시간 초과)·HUP(터미널 끊김)이 오면 EXIT trap이 컨테이너만 지우고 끝난다. 그때까지 쌓인 게이트 증거는 오지 않는다. - 래퍼에만 온 INT는 게이트가 끝날 때까지 밀린다. 터미널의 Ctrl-C는 docker 단계가 자기 상태 코드로 끝나서 bash가 다음 줄로 간다. 게이트 전이면 부팅·복사를 이어 가 게이트까지 돈다. - 정리 trap은 `docker run`이 id를 돌려준 뒤에 걸린다. 그 전에 온 신호는 컨테이너를 남긴다. - 정리의 docker 호출은 두 번째 Ctrl-C에 끊긴다. Go로 된 docker CLI는 셸이 무시한 SIGINT를 다시 켠다. 고른 방법: - 게이트는 `docker exec … &` + `wait`로 띄운다. 그래야 trap이 바로 돈다. - 게이트가 도는 동안 TERM·INT·HUP을 받으면 `on_signal`이 아래를 한다. - 다른 신호와 PIPE를 무시한다(두 번째 Ctrl-C, 사라진 로그 독자). - 그때까지 쓴 `artifacts/`를 되가져오고 컨테이너를 지운다. - EXIT trap을 지우고 같은 신호로 자기를 죽인다(셸에는 128+번호, `ci:gate`는 신호 이름을 댄다). 그래도 살아 있으면 `exit 128+번호`. - 게이트가 끝나 되가져오는 중에 온 신호는 다시 복사하지 않는다 (`copying=1`). bash가 그 복사가 끝난 뒤 trap을 돌리므로 복사는 끝나 있다. - 컨테이너 이름을 `fe-system-container-`로 미리 정해 `--name`으로 준다. 정리는 id 없이 이름으로 지운다. 같은 daemon을 쓰는 job 컨테이너들은 PID가 각자 작게 시작해 `$$`·`$RANDOM`으로 지은 이름이 겹칠 수 있고, 겹치면 남의 컨테이너를 지운다. - `trap cleanup EXIT`를 이미지 build 전에 건다. 게이트 전의 TERM·HUP은 bash 기본 동작대로 바로 끝나고, EXIT trap이 컨테이너를 지운다. INT만 `early_signal`로 받는다. docker 단계가 Ctrl-C에 상태 코드로 끝나면 bash가 계속 가기 때문이다. `early_signal`도 컨테이너를 지운 뒤 그 신호로 끝난다. - `docker run -d` 동안만 TERM·HUP도 `early_signal`로 미룬다. run은 래퍼가 죽어도 계속 돌아 컨테이너를 만든다. 그 전에 지우면 남는다. - 정리와 되가져오기의 docker 호출은 `setsid -w`로 자기 세션에서 돈다. `setsid -w`를 못 쓰는 호스트에서는 그냥 돈다. - `say`는 stderr 쓰기가 실패해도(터미널 끊김) 스크립트를 끝내지 않는다. - 운영 문서 FE-GATE-013 절에 신호 때 동작과, SIGKILL 뒤 남은 컨테이너를 찾아 지우는 명령을 적는다. 버린 것: - `exit 128+번호`로만 끝내기: 셸은 같은 값을 보지만, 프로세스로 부른 쪽(`ci:gate`)은 신호로 죽은 것과 그 상태 코드로 끝난 것을 구분하지 못한다. Ctrl-C를 받은 셸 스크립트를 부른 셸도 신호로 죽은 자식을 봐야 멈춘다. - 처음부터 `on_signal`을 걸기: 게이트 전 단계(작업 트리 복사 등)가 길면 trap은 그 단계가 끝난 뒤에야 돈다. 되가져올 것도 없는데 TERM·HUP이 그 단계 끝까지 밀린다. - 신호를 컨테이너 안 게이트에 넘기기: 게이트가 신호를 받아 자기 로그를 쓰게 하려면 안쪽 `ci:gate`에도 신호 처리가 필요하고, 시간 초과 뒤 SIGKILL 전 유예 안에 끝난다는 보장도 없다. 이 변경은 그때까지 쓴 것을 되가져오는 데서 멈춘다. 위험·한계: - SIGKILL(job 강제 종료, OOM)은 잡을 수 없다. 아무것도 되가져오지 못하고 컨테이너가 남는다. 운영 문서에 `docker ps -a --filter name=fe-system-container-`와 `docker rm -f`를 적었다. - 게이트 도중 되가져오는 tar는 게이트가 그때 쓰고 있는 파일을 덜 쓴 채로 가져올 수 있다. - 게이트 로그(`artifacts/quality/gates/FE-GATE-013.txt`)는 게이트가 끝날 때 쓰므로, 신호로 끊긴 실행에서는 오지 않는다. - `setsid -w`가 없는 호스트에서는 두 번째 Ctrl-C가 정리를 끊어 컨테이너가 남을 수 있다. 이름은 Linux의 `/proc/sys/kernel/random/uuid`로 짓는다. - CI run 취소가 래퍼에 어떤 신호로 닿는지는 실제로 취소해 보지 않았다. runner가 job 컨테이너를 SIGKILL로 끝내면 첫 항목이다. 검증(desktop `scripts/verify.sh`, 깨끗한 worktree): - RED: 기준 cbed9467 래퍼 + 새 시험 → 새 신호 시험 10개가 모두 실패, 나머지는 통과. - 변이 16건, 각자 겨눈 시험이 실패: - on_signal에서 되가져오기를 뺌, 게이트를 앞에서 돌림, on_signal의 자기 kill을 뺌, on_signal이 EXIT trap을 남김 → 게이트 중 신호 시험들. - `copying` 확인을 뺌, `copying=1`을 뺌 → 게이트 뒤 되가져오는 중 신호. - 처리기의 신호 무시를 뺌 → 두 번째 신호·독자 없는 SIGHUP. - `say`의 `|| :`를 뺌 → 독자 없는 SIGHUP. `setsid -w`를 뺌 → 두 번째 신호. - on_signal을 처음부터 검, INT의 early_signal을 뺌, early_signal의 자기 kill이나 EXIT trap 해제를 뺌 → 작업 트리 복사 중 Ctrl-C. - id로 지움 → 신호 시험 10개 전부. run 동안의 TERM·HUP trap을 뺌 → docker run 중 SIGHUP. `trap - TERM HUP`을 뺌 → 작업 트리 복사 중 TERM·HUP. - 실제 docker(desktop daemon, 실제 이미지)에서 래퍼를 돌려 신호를 보냄: 게이트 중 TERM → SIGTERM으로 끝나고 게이트가 쓴 파일이 옴. 게이트 중 Ctrl-C 두 번 → SIGINT, 파일이 옴. 컨테이너가 생긴 뒤 게이트 전의 Ctrl-C → SIGINT, HUP → SIGHUP. 네 경우 모두 남은 컨테이너 0개. - GREEN: `tests/unit/ci-gate-host-environment.test.ts` 3회 연속 15 통과. `lint`·`check:types` rc=0. 신호 시험 timeout은 FE-GATE-005 test:unit에서 잰 최장 1135ms(부하 2.7, test:coverage는 더 짧음). - merge 단계 게이트는 PR 본문에 적는다. Refs: fe-ci-next (3b) --- docs/operations/ci-quality-gates.md | 6 + scripts/run-in-system-container.sh | 91 ++++- tests/unit/ci-gate-host-environment.test.ts | 356 ++++++++++++++++++-- 3 files changed, 419 insertions(+), 34 deletions(-) diff --git a/docs/operations/ci-quality-gates.md b/docs/operations/ci-quality-gates.md index 092ff137..4195f60c 100644 --- a/docs/operations/ci-quality-gates.md +++ b/docs/operations/ci-quality-gates.md @@ -261,6 +261,12 @@ runner의 Docker proxy가 안쪽 dind daemon에 컨테이너를 띄운다. release 단계 provider job은 아직 job 컨테이너에서 돈다. - runner가 privileged 컨테이너를 막는 설정(rootless dind 등)으로 바뀌면 이 길이 깨진다. 그때는 위 조건을 갖춘 전용 runner(VM 등)로 옮긴다. +- 게이트가 도는 동안 래퍼가 TERM·INT·HUP(시간 초과, Ctrl-C, 터미널 끊김)을 받으면 + 그때까지 쌓인 `artifacts/`를 되가져오고 컨테이너를 지운 뒤 그 신호로 끝난다(셸에는 + 128+신호 번호). 게이트 로그는 게이트가 끝날 때 쓰므로 이때는 오지 않는다. 게이트 + 전에 받으면 컨테이너만 지우고 그 신호로 끝난다. SIGKILL(job 강제 종료, OOM)은 + 잡을 수 없어 아무것도 되가져오지 못하고 컨테이너가 남는다. + `docker ps -a --filter name=fe-system-container-`로 찾아 `docker rm -f`로 지운다. - 컨테이너의 첫 프로세스는 systemd를 띄우기 전에 root cgroup의 프로세스를 `init.scope`로 옮기고 root에 cgroup 제어기를 켠다. 그러지 않으면 부팅 중에 닿은 `docker exec`가 root cgroup에 들어가 systemd가 제어기를 넘기지 못하고, diff --git a/scripts/run-in-system-container.sh b/scripts/run-in-system-container.sh index 0db07ac1..0f3465f1 100755 --- a/scripts/run-in-system-container.sh +++ b/scripts/run-in-system-container.sh @@ -9,13 +9,17 @@ # The command runs as root there, so bubblewrap needs no unprivileged user namespace from the host kernel # (Ubuntu 23.10+ refuses those to unconfined processes). Node and pnpm come from the caller, copied in with the # working tree and its git history; artifacts/ is copied back and the container removed, whatever the result. +# A TERM, INT or HUP (a timeout, Ctrl-C, a closed terminal) while the command runs copies back what it wrote so +# far, removes the container and ends this script on that signal. Before that it only removes the container and +# ends on the signal. SIGKILL cannot be caught: the container (fe-system-container-) stays. # Docker: the CI job reaches the runner's own daemon through its Docker proxy # (platform-core infrastructure/ci/gitea-runner); on desktop it is the host daemon. # Environment: SYSTEM_CONTAINER_DOCKER (default docker), SYSTEM_CONTAINER_KEEP=1 keeps the container for debugging. -# Exit code: the command's, or 3 when the container could not be prepared. +# Exit code: the command's, or 3 when the container could not be prepared; on TERM, INT or HUP, death by that +# signal (128 + its number to a shell). set -euo pipefail -[ $# -gt 0 ] || { sed -n '2,13p' "$0" | sed 's/^# \{0,1\}//' >&2; exit 2; } +[ $# -gt 0 ] || { sed -n '2,19p' "$0" | sed 's/^# \{0,1\}//' >&2; exit 2; } docker=${SYSTEM_CONTAINER_DOCKER:-docker} root=$(git rev-parse --show-toplevel) cd "$root" @@ -35,9 +39,40 @@ for name in PNPM_CONFIG_STORE_DIR PNPM_CONFIG_CACHE_DIR; do fi done -say() { echo "system-container: $*" >&2; } +# A message must not end the script: a closed terminal or a gone log reader makes the write fail. +say() { echo "system-container: $*" >&2 || :; } fail() { say "$*"; exit 3; } +# The container's name, so the cleanup finds it even when a signal comes before `docker run` gives its id. A +# job container's PIDs start over, so the name is random. +container_name="fe-system-container-$(cat /proc/sys/kernel/random/uuid)" +# The cleanup's docker calls run in a session of their own: the docker CLI ends a call on Ctrl-C even when the +# shell ignores it (Go turns an ignored SIGINT back on), so a second Ctrl-C would cancel the copy or the removal. +own_session=() +if setsid -w true 2> /dev/null; then own_session=(setsid -w); fi +cleanup() { + # The boot step writes to the container log only when it gave up; say so whatever ends the run. + "${own_session[@]}" $docker logs "$container_name" 2>&1 | grep '^system-container:' >&2 || : + if [ "${SYSTEM_CONTAINER_KEEP:-0}" = 1 ]; then + say "kept container $container_name" + else + "${own_session[@]}" $docker rm -f "$container_name" > /dev/null 2>&1 || : + fi +} +# Before the command starts, a TERM or HUP ends the script at once (bash's default), and this trap removes the +# container: bash runs it when a signal ends it too. An INT is trapped, because bash carries on after a step +# that ends on Ctrl-C with a status of its own, as the docker CLI does; it ends the script once that step returns. +trap cleanup EXIT +early_signal() { + trap '' TERM INT HUP PIPE + say "SIG$1: ending before the command started" + cleanup + trap - EXIT "$1" + kill -s "$1" $$ + exit $((128 + $2)) # only if the signal did not end it +} +trap 'early_signal INT 2' INT + if ! $docker image inspect "$tag" > /dev/null 2>&1; then say "building $tag" $docker build -q -t "$tag" -f "$dockerfile" config/ci > /dev/null || fail "image build failed" @@ -63,14 +98,13 @@ if [ -n "$controllers" ]; then done fi exec /sbin/init' -cid=$($docker run -d --privileged --cgroupns=private --tmpfs /run --tmpfs /run/lock "$tag" /bin/sh -c "$boot") \ +# `docker run` makes the container before it hands back the id, and goes on when this script is gone, so a +# TERM or HUP meanwhile waits for it: a removal before the container exists would leave it behind. +trap 'early_signal TERM 15' TERM +trap 'early_signal HUP 1' HUP +cid=$($docker run -d --name "$container_name" --privileged --cgroupns=private --tmpfs /run --tmpfs /run/lock "$tag" /bin/sh -c "$boot") \ || fail "container did not start" -cleanup() { - # The boot step writes to the container log only when it gave up; say so whatever ends the run. - $docker logs "$cid" 2>&1 | grep '^system-container:' >&2 || : - if [ "${SYSTEM_CONTAINER_KEEP:-0}" = 1 ]; then say "kept container $cid"; else $docker rm -f "$cid" > /dev/null 2>&1 || :; fi -} -trap cleanup EXIT +trap - TERM HUP # systemd reaches a final state, then root's lingering user manager opens its bus. Until PID 1 has its own # bus up, systemctl cannot connect and answers nothing, so ask again for up to a minute. @@ -115,10 +149,39 @@ exec_env=(-e PATH=/opt/node/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bi for name in "${pass_env[@]}"; do [ -z "${!name+x}" ] || exec_env+=(-e "$name=${!name}") done +copy_back() { + mkdir -p artifacts + "${own_session[@]}" $docker exec "$cid" sh -c '[ -d /work/artifacts ] && tar -C /work -cf - artifacts' \ + | tar -C "$root" -xf - || say "copying artifacts back failed" +} +# While the command runs, a TERM, INT or HUP copies back what it wrote so far (the gate's own log comes at its +# end, so it is not there yet), removes the container, and ends the script on that signal itself, so a shell +# sees 128 + its number and ci:gate in the job names it. Another of them, or a gone stderr reader (PIPE), +# does not cut that short. Once the command has ended the copy below has begun: bash runs a trap only after +# the command in front, so the trap finds the copy done. +copying=0 +on_signal() { + trap '' TERM INT HUP PIPE + if [ "$copying" = 0 ]; then + say "SIG$1: copying artifacts/ back, then ending" + copy_back + else + say "SIG$1: ending after the copy back" + fi + cleanup + # bash would run the EXIT trap again when the signal ends it. + trap - EXIT "$1" + kill -s "$1" $$ + exit $((128 + $2)) # only if the signal did not end it +} +trap 'on_signal TERM 15' TERM +trap 'on_signal INT 2' INT +trap 'on_signal HUP 1' HUP +# In the background, so the trap runs at once: bash runs one only after the command in front ends. rc=0 -$docker exec -w /work "${exec_env[@]}" "$cid" "$@" || rc=$? +$docker exec -w /work "${exec_env[@]}" "$cid" "$@" & +wait $! || rc=$? # The gate's log and evidence come back even when it failed. -mkdir -p artifacts -$docker exec "$cid" sh -c '[ -d /work/artifacts ] && tar -C /work -cf - artifacts' | tar -C "$root" -xf - \ - || say "copying artifacts back failed" +copying=1 +copy_back exit "$rc" diff --git a/tests/unit/ci-gate-host-environment.test.ts b/tests/unit/ci-gate-host-environment.test.ts index e343fd9a..48a21af0 100644 --- a/tests/unit/ci-gate-host-environment.test.ts +++ b/tests/unit/ci-gate-host-environment.test.ts @@ -1,9 +1,9 @@ -import { spawnSync } from "node:child_process"; +import { spawn, spawnSync } from "node:child_process"; import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; -import { describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it } from "vitest"; import { loadCiGateContract } from "../../scripts/contracts/ci-gates.ts"; import { renderCiWorkflow } from "../../scripts/generate-ci-workflow.ts"; @@ -20,6 +20,12 @@ import { childProcessTimeout } from "../helpers/child-process-timeout.ts"; * (2026-11-20). Alone or in test:coverage they took 1.0 to 1.5 s. */ const GATE_STEP_MS = 3688; +/** + * Longest desktop run of a test below: the one on SIGHUP while docker run starts + * the container, in FE-GATE-005's test:unit at load 2.7 (2026-11-20); its + * test:coverage run there was shorter, and the others took 0.1 to 0.3 s. + */ +const SIGNAL_MS = 1135; const repository = process.cwd(); const GATE = "FE-GATE-013"; @@ -38,22 +44,48 @@ exit "\${STAND_IN_EXIT:-0}" const CONTAINER_WRAPPER = "scripts/run-in-system-container.sh"; const STAND_IN_CONTAINER = "stand-in-container"; const CALL_END = ""; +const HELD_CALL_ENDED = ""; /** * Stands in for docker under the real wrapper (SYSTEM_CONTAINER_DOCKER): it * writes each call's arguments one per line, then CALL_END, starts a * container that is at once running, takes what is piped in, and hands back - * an empty artifacts archive. + * an empty artifacts archive. For the signal tests: STAND_IN_ARTIFACTS is a + * folder whose artifacts/ it hands back instead; the first call with + * STAND_IN_HOLD_CALL in its arguments creates the file STAND_IN_HOLD, waits + * until STAND_IN_HOLD.sent exists (or STAND_IN_HOLD_TICKS times 50 ms), then + * creates STAND_IN_HOLD.released and writes HELD_CALL_ENDED as a call; on an + * INT it ends with status 1 instead, as the docker CLI does on Ctrl-C. With + * STAND_IN_GATE the gate creates that file and runs until the container is + * removed. Each call also adds its first argument and its session id to + * DOCKER_CALLS.sessions. */ const STAND_IN_DOCKER = `#!/bin/sh for argument in "$@"; do printf '%s\\n' "$argument"; done >> "$DOCKER_CALLS" echo '${CALL_END}' >> "$DOCKER_CALLS" +echo "$1 $(cut -d ' ' -f 6 /proc/$$/stat)" >> "$DOCKER_CALLS.sessions" case "$1 $2" in "run -d") echo ${STAND_IN_CONTAINER} ;; "exec -i") cat > /dev/null ;; esac +case "\${STAND_IN_HOLD:+hold} $*" in + "hold "*"\${STAND_IN_HOLD_CALL:-}"*) + if [ ! -f "$STAND_IN_HOLD" ]; then + trap 'exit 1' INT + : > "$STAND_IN_HOLD" + i=0 + while [ ! -f "$STAND_IN_HOLD.sent" ] && [ $i -lt "\${STAND_IN_HOLD_TICKS:-600}" ]; do sleep 0.05; i=$((i + 1)); done + : > "$STAND_IN_HOLD.released" + printf '%s\\n' '${HELD_CALL_ENDED}' '${CALL_END}' >> "$DOCKER_CALLS" + fi ;; +esac case "$*" in *is-system-running*) echo running ;; - *"-cf - artifacts"*) tar -cf - -T /dev/null ;; + *"-cf - artifacts"*) + if [ -n "\${STAND_IN_ARTIFACTS:-}" ]; then tar -C "$STAND_IN_ARTIFACTS" -cf - artifacts; else tar -cf - -T /dev/null; fi ;; + *"${STAND_IN_CONTAINER} corepack pnpm ci:gate -- "*) + if [ -n "\${STAND_IN_GATE:-}" ]; then echo $$ > "$STAND_IN_GATE.pid"; : > "$STAND_IN_GATE"; exec sleep 600; fi ;; + "rm -f "*) + if [ -n "\${STAND_IN_GATE:-}" ] && [ -f "$STAND_IN_GATE.pid" ]; then kill "$(cat "$STAND_IN_GATE.pid")" 2> /dev/null || :; fi ;; esac exit 0 `; @@ -84,6 +116,38 @@ function wrapperCheckout(root: string): string { return checkout; } +const GATE_COMMAND = ["corepack", "pnpm", "ci:gate", "--", GATE]; + +/** + * The environment the real wrapper runs in under wrapperCheckout: the node + * stand-in first on PATH, the docker stand-in writing its calls to `calls`, + * and no corepack cache or pnpm store to copy in. + */ +function wrapperEnvironment( + root: string, + calls: string, + extra: Readonly>, +): NodeJS.ProcessEnv { + return { + ...process.env, + PATH: `${path.join(root, "node/bin")}${path.delimiter}${process.env["PATH"] ?? ""}`, + SYSTEM_CONTAINER_DOCKER: path.join(root, "docker"), + DOCKER_CALLS: calls, + COREPACK_HOME: path.join(root, "no-corepack"), + PNPM_CONFIG_STORE_DIR: "", + PNPM_CONFIG_CACHE_DIR: "", + ...extra, + }; +} + +/** Each docker call the stand-in wrote, as its arguments. */ +function dockerCalls(calls: string): string[][] { + return readFileSync(calls, "utf8") + .split(`${CALL_END}\n`) + .map((call) => call.split("\n").filter((argument) => argument !== "")) + .filter((call) => call.length > 0); +} + /** The merge job's run line for FE-GATE-013, as the generated workflow has it. */ async function gateRunLine(): Promise { const workflow = renderCiWorkflow(await loadCiGateContract(repository)); @@ -227,27 +291,16 @@ describe("FE-GATE-013 in a merge job", { timeout: childProcessTimeout(GATE_STEP_ try { const checkout = wrapperCheckout(root); const calls = path.join(root, "docker-calls"); - const result = spawnSync(CONTAINER_WRAPPER, ["corepack", "pnpm", "ci:gate", "--", GATE], { + const result = spawnSync(CONTAINER_WRAPPER, GATE_COMMAND, { cwd: checkout, encoding: "utf8", - env: { - ...process.env, - PATH: `${path.join(root, "node/bin")}${path.delimiter}${process.env["PATH"] ?? ""}`, - SYSTEM_CONTAINER_DOCKER: path.join(root, "docker"), - DOCKER_CALLS: calls, - COREPACK_HOME: path.join(root, "no-corepack"), - PNPM_CONFIG_STORE_DIR: "", - PNPM_CONFIG_CACHE_DIR: "", - CI: "true", - [PR_BASE_REF_VARIABLE]: "main", - }, + env: wrapperEnvironment(root, calls, { CI: "true", [PR_BASE_REF_VARIABLE]: "main" }), }); expect(result.status, result.stderr).toBe(0); - const gateCalls = readFileSync(calls, "utf8") - .split(`${CALL_END}\n`) - .map((call) => call.split("\n").filter((argument) => argument !== "")) - .filter((call) => call.join(" ").endsWith(`${STAND_IN_CONTAINER} corepack pnpm ci:gate -- ${GATE}`)); + const gateCalls = dockerCalls(calls).filter((call) => + call.join(" ").endsWith(`${STAND_IN_CONTAINER} ${GATE_COMMAND.join(" ")}`), + ); expect(gateCalls).toHaveLength(1); const [call] = gateCalls as [string[]]; expect(call.slice(0, 3)).toEqual(["exec", "-w", "/work"]); @@ -262,3 +315,266 @@ describe("FE-GATE-013 in a merge job", { timeout: childProcessTimeout(GATE_STEP_ } }); }); + +// fe-ci-next (3b). A timeout's TERM, Ctrl-C (INT) or a closed terminal (HUP) +// ended the wrapper before it copied artifacts/ back: the copy came only after +// the gate, and a running gate kept the shell from reaching a trap. Now, while +// the gate runs, such a signal copies back what it wrote so far, removes the +// container, and ends the wrapper on that signal, so a shell that ran it sees +// 128 + its number and ci:gate in the job names it. Before the gate the +// wrapper still ends at once. Each run is the real wrapper on the docker +// stand-in, in its own process group so that nothing it started outlives the +// test. +describe("the container wrapper on a signal", { timeout: childProcessTimeout(SIGNAL_MS) }, () => { + const SIGNALS = ["SIGTERM", "SIGINT", "SIGHUP"] as const; + const groups: number[] = []; + + afterEach(() => { + for (const group of groups.splice(0)) { + try { + process.kill(-group, "SIGKILL"); + } catch { + // Everything in it has ended. + } + } + }); + + type Step = { + /** The file the stand-in creates when it holds a call. */ + held: string; + signal: NodeJS.Signals; + /** Creates `held`.sent after the signal, so the held call goes on (default true). */ + release?: boolean; + /** Sends the signal to the wrapper's process group, as Ctrl-C does, instead of to the wrapper alone. */ + group?: boolean; + }; + + /** + * Starts the real wrapper on the gate command and, for each step in turn, + * sends its signal once its `held` file appears; gives how the wrapper ended. + * With `closeStderr`, the wrapper's stderr has no reader by the first signal. + */ + async function signalled( + root: string, + steps: readonly Step[], + extra: Record, + { closeStderr = false } = {}, + ) { + const checkout = wrapperCheckout(root); + const calls = path.join(root, "docker-calls"); + const child = spawn(CONTAINER_WRAPPER, GATE_COMMAND, { + cwd: checkout, + env: wrapperEnvironment(root, calls, extra), + stdio: ["ignore", "ignore", "pipe"], + detached: true, + }); + groups.push(child.pid!); + let stderr = ""; + child.stderr.setEncoding("utf8").on("data", (chunk: string) => (stderr += chunk)); + let exit: { code: number | null; signal: NodeJS.Signals | null } | undefined; + const ended = new Promise>((resolve) => + child.on("exit", (code, signal) => resolve((exit = { code, signal }))), + ); + for (const { held, signal, release = true, group = false } of steps) { + while (!existsSync(held)) { + if (exit) throw new Error(`the wrapper ended before ${path.basename(held)}: ${stderr}`); + await new Promise((resolve) => setTimeout(resolve, 20)); + } + if (closeStderr && !child.stderr.destroyed) child.stderr.destroy(); + if (group) process.kill(-child.pid!, signal); + else child.kill(signal); + if (release) writeFileSync(`${held}.sent`, ""); + } + const result = await ended; + const sessions = readFileSync(`${calls}.sessions`, "utf8") + .split("\n") + .filter((line) => line !== "") + .map((line) => line.split(" ")); + return { ...result, stderr, checkout, calls: dockerCalls(calls), sessions, pid: child.pid! }; + } + + /** The container's work folder as the docker stand-in hands it back: one artifact the gate wrote before the signal. */ + function containerWork(root: string): string { + const written = path.join(root, "container-work"); + mkdirSync(path.join(written, "artifacts/quality"), { recursive: true }); + writeFileSync(path.join(written, "artifacts/quality/partial.txt"), "written before the signal\n"); + return written; + } + + const copiedBack = (checkout: string) => readFileSync(path.join(checkout, "artifacts/quality/partial.txt"), "utf8"); + const copiesBack = (call: readonly string[]) => call.join(" ").includes("-cf - artifacts"); + const removes = (call: readonly string[]) => + call.length === 3 && call[0] === "rm" && call[1] === "-f" && /^fe-system-container-[0-9a-f-]{36}$/u.test(call[2]!); + const runsGate = (call: readonly string[]) => call.join(" ").endsWith(`${STAND_IN_CONTAINER} ${GATE_COMMAND.join(" ")}`); + + it.each(SIGNALS)("on %s while the gate runs, copies artifacts/ back, removes the container, and ends on it", async (signal) => { + const root = mkdtempSync(path.join(tmpdir(), "ci-gate-host-environment-")); + try { + const gate = path.join(root, "gate-running"); + const result = await signalled(root, [{ held: gate, signal }], { + STAND_IN_GATE: gate, + STAND_IN_ARTIFACTS: containerWork(root), + }); + + expect(result.signal, result.stderr).toBe(signal); + expect(result.code).toBeNull(); + expect(copiedBack(result.checkout)).toBe("written before the signal\n"); + expect(result.calls.filter(copiesBack)).toHaveLength(1); + expect(result.calls.filter(removes)).toHaveLength(1); + expect(result.calls.findIndex(removes)).toBeGreaterThan(result.calls.findIndex(copiesBack)); + expect(result.stderr).toContain(`system-container: ${signal}: copying artifacts/ back, then ending`); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + // A closed terminal or a gone log reader: writing the message fails. + it("on SIGHUP with no reader left on stderr, still copies back and removes the container", async () => { + const root = mkdtempSync(path.join(tmpdir(), "ci-gate-host-environment-")); + try { + const gate = path.join(root, "gate-running"); + const result = await signalled( + root, + [{ held: gate, signal: "SIGHUP" }], + { STAND_IN_GATE: gate, STAND_IN_ARTIFACTS: containerWork(root) }, + { closeStderr: true }, + ); + + expect(result.signal).toBe("SIGHUP"); + expect(copiedBack(result.checkout)).toBe("written before the signal\n"); + expect(result.calls.filter(removes)).toHaveLength(1); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + // Ctrl-C pressed twice: the second one does not start the copy and the + // removal again. + it("on a second signal while it copies back, copies back and removes the container once", async () => { + const root = mkdtempSync(path.join(tmpdir(), "ci-gate-host-environment-")); + try { + const gate = path.join(root, "gate-running"); + const copying = path.join(root, "copying-back"); + const result = await signalled( + root, + [ + { held: gate, signal: "SIGINT" }, + { held: copying, signal: "SIGINT" }, + ], + { + STAND_IN_GATE: gate, + STAND_IN_ARTIFACTS: containerWork(root), + STAND_IN_HOLD: copying, + STAND_IN_HOLD_CALL: "-cf - artifacts", + }, + ); + + expect(result.signal, result.stderr).toBe("SIGINT"); + expect(copiedBack(result.checkout)).toBe("written before the signal\n"); + expect(result.calls.filter(copiesBack)).toHaveLength(1); + expect(result.calls.filter(removes)).toHaveLength(1); + // The docker CLI turns an ignored SIGINT back on, so the copy and the + // removal must be out of the reach of the terminal's Ctrl-C: each runs + // in a session of its own. The wrapper leads its own (detached). + const late = result.sessions.filter(([command]) => command === "rm" || command === "exec").slice(-2); + expect(late.map(([command]) => command)).toEqual(["exec", "rm"]); + for (const [, session] of late) expect(session).not.toBe(String(result.pid)); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + // The gate has ended and its copy is under way: the signal waits for it + // instead of copying again. + it("on a signal while it copies back after the gate, copies back once and ends on it", async () => { + const root = mkdtempSync(path.join(tmpdir(), "ci-gate-host-environment-")); + try { + const copying = path.join(root, "copying-back"); + const result = await signalled(root, [{ held: copying, signal: "SIGTERM" }], { + STAND_IN_ARTIFACTS: containerWork(root), + STAND_IN_HOLD: copying, + STAND_IN_HOLD_CALL: "-cf - artifacts", + }); + + expect(result.signal, result.stderr).toBe("SIGTERM"); + expect(copiedBack(result.checkout)).toBe("written before the signal\n"); + expect(result.calls.filter(copiesBack)).toHaveLength(1); + expect(result.calls.filter(removes)).toHaveLength(1); + expect(result.stderr).toContain("system-container: SIGTERM: ending after the copy back"); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + // Ctrl-C reaches the step in front too, and a docker step ends on it with a + // status of its own; bash would carry on after it. + it("on Ctrl-C while it copies the working tree in, ends on SIGINT and removes the container", async () => { + const root = mkdtempSync(path.join(tmpdir(), "ci-gate-host-environment-")); + try { + const copyingIn = path.join(root, "copying-in"); + const result = await signalled(root, [{ held: copyingIn, signal: "SIGINT", release: false, group: true }], { + STAND_IN_HOLD: copyingIn, + STAND_IN_HOLD_CALL: "mkdir -p /work &&", + }); + + expect(result.signal, result.stderr).toBe("SIGINT"); + expect(result.calls.some(runsGate)).toBe(false); + expect(result.calls.filter(removes)).toHaveLength(1); + expect(result.stderr).toContain("system-container: SIGINT: ending before the command started"); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + // `docker run` makes the container before it hands its id back, and goes on + // without the wrapper: the cleanup waits for it, then removes the container + // by the name the wrapper gave it. The held run ends by itself after 1 s. + it("on SIGHUP while docker run starts the container, removes it by its name once the run returns", async () => { + const root = mkdtempSync(path.join(tmpdir(), "ci-gate-host-environment-")); + try { + const starting = path.join(root, "starting"); + const result = await signalled(root, [{ held: starting, signal: "SIGHUP", release: false }], { + STAND_IN_HOLD: starting, + STAND_IN_HOLD_CALL: "run -d", + STAND_IN_HOLD_TICKS: "20", + }); + + expect(result.signal, result.stderr).toBe("SIGHUP"); + const run = result.calls.find((call) => call[0] === "run")!; + const name = run[run.indexOf("--name") + 1]; + expect(result.calls.filter(removes)).toEqual([["rm", "-f", name]]); + expect(result.calls.findIndex(removes)).toBeGreaterThan( + result.calls.findIndex((call) => call[0] === HELD_CALL_ENDED), + ); + expect(result.calls.findIndex((call) => call[0] === HELD_CALL_ENDED)).toBeGreaterThan(-1); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + // Before the gate there is nothing to copy back, and a step such as copying + // the working tree in can take long: the wrapper ends at once, not after the + // step, and still removes the container. A signal to the wrapper alone, as a + // parent process sends it (Ctrl-C reaches the step too). + it.each(["SIGTERM", "SIGHUP"] as const)( + "on %s while it copies the working tree in, ends at once and removes the container", + async (signal) => { + const root = mkdtempSync(path.join(tmpdir(), "ci-gate-host-environment-")); + try { + const copyingIn = path.join(root, "copying-in"); + const result = await signalled(root, [{ held: copyingIn, signal, release: false }], { + STAND_IN_HOLD: copyingIn, + STAND_IN_HOLD_CALL: "mkdir -p /work &&", + }); + + expect(result.signal, result.stderr).toBe(signal); + expect(existsSync(`${copyingIn}.released`)).toBe(false); + expect(result.calls.some(copiesBack)).toBe(false); + expect(result.calls.some(runsGate)).toBe(false); + expect(result.calls.filter(removes)).toHaveLength(1); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }, + ); +}); -- 2.54.0 From db59c1c32cdcf4f8ce366e2f49f1559d2c199ffd Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 20 Nov 2026 13:14:01 +0900 Subject: [PATCH 2/2] =?UTF-8?q?docs(changelog):=20=EC=BB=A8=ED=85=8C?= =?UTF-8?q?=EC=9D=B4=EB=84=88=20=EB=9E=98=ED=8D=BC=EA=B0=80=20=EC=8B=A0?= =?UTF-8?q?=ED=98=B8=EC=97=90=EB=8F=84=20artifacts=EB=A5=BC=20=EB=90=98?= =?UTF-8?q?=EA=B0=80=EC=A0=B8=EC=98=A4=EB=8A=94=20=EA=B2=83=EC=9D=84=20?= =?UTF-8?q?=EC=A0=81=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: `b5f28e52`가 FE-GATE-013 컨테이너 래퍼의 신호 처리를 바꿨는데 변경 이력에 없다. 복사한 프로젝트가 가져갈지 고를 수 없다. 고른 방법: 첫 미출시 절 「그 밖의 변경」 표의 끝에 한 줄을 더한다. 바뀐 동작(게이트 도중 TERM·INT·HUP에 `artifacts/`를 되가져오고 컨테이너를 지운 뒤 그 신호로 끝남, 게이트 전에는 컨테이너만 지움), 고치기 전 동작, 이름 `fe-system-container-`, 게이트 로그가 오지 않는 것, SIGKILL 뒤 정리 명령의 위치(운영 문서 FE-GATE-013 절)를 적고, 해시는 `b5f28e52`다. 위험·한계: 문서 한 줄이다. 검증: `git merge-base --is-ancestor b5f28e52 HEAD` 통과. 노트북 `scripts/verify.sh docs`와 desktop `verify:documentation`은 PR 본문에 적는다. Refs: fe-ci-next (3b) --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1025fdac..5a766e89 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -151,6 +151,7 @@ Gitea runner에서 merge 단계를 초록으로 만들고, worker를 늘리지 | 끊을 곳 없는 긴 RELEASE_ID·build id, 서버의 상관 ID(128자까지)와 item id가 320px 화면을 넘치지 않는다. 지원 참조는 새 `SupportReference` 하나가 그리고(`ui-support-reference`), 홈 런타임 요약·부팅 오류 화면의 값·상세 화면 메타데이터의 값은 `overflow-wrap: anywhere`를 쓴다. 홈은 grid 항목이라 고치기 전 세 엔진에서 594~641px로 넓어졌다. 기능 화면이 지원 참조를 직접 그렸으면 디자인 시스템 배럴의 컴포넌트에 넘긴다. 오류 화면은 `TerminalErrorSurface`·`StatusPage`의 `supportReference`로 넘긴다. `AsyncSurface`의 `supportReference`는 결과를 모르는 저장일 때만 그려지고(`useAppForm().supportReference`), 오류로 끝난 상태는 `failure.requestId`를 스스로 그린다. `SupportReference`는 배럴 밖이다 | `src/presentation/components/support-reference.tsx`, `src/presentation/components/async-surface.tsx`, `src/presentation/templates/page-templates.tsx`, `src/presentation/boundaries/`, `src/presentation/styles/theme/`, `tests/e2e/responsive.spec.ts`, `tests/e2e/generated-feature.spec.ts`, `tests/e2e/support/reflow.ts` | `953e1ca5` | | `scripts/verify.sh`가 RELEASE_ID에 checkout 브랜치 이름을 넣지 않고 CI와 같은 꼴의 고정 ref(`refs/heads/verify-1-1`)를 쓴다. 같은 트리의 FE-GATE-008 결과가 브랜치 이름 길이로 갈렸다 | `scripts/verify.sh`, `scripts/tests/test_verify.py` | `4ab62f81` | | 제거 drill의 사본 준비(`prepareRemovalFixture`)가 checkout에 없는 `optional` 등록부 항목(`recipes`)을 건너뛴다. 없는 필수 경로에서는 cp의 ENOENT 스택 대신, 사본 폴더를 비우기 전에 그 경로와 고르는 등록부 항목, 고칠 곳(경로를 되살리거나 항목을 지우거나 그 항목의 `setPaths`에서 빼기)을 대고 멈춘다. 등록부가 고르지 않는 경로도 이름으로 댄다. 매뉴얼 03 R1이 추적하는 항목도 drill 사본이나 제품 사본에 없을 수 있으면 `optional`로 적으라고 한다 | `scripts/lib/removal-fixture.ts`, `tests/unit/removal-fixture.test.ts`, `docs/manual/03-outside-feature-folder.md` | `44453592` | +| FE-GATE-013의 시스템 컨테이너 래퍼(`scripts/run-in-system-container.sh`)가 게이트 도중 TERM·INT·HUP(시간 초과, Ctrl-C, 터미널 끊김)을 받으면 그때까지 쌓인 `artifacts/`를 되가져오고 컨테이너를 지운 뒤 그 신호로 끝난다. 게이트 전에 받으면 컨테이너만 지우고 그 신호로 끝난다. 고치기 전에는 게이트 도중 TERM·HUP에 증거 없이 끝났고, 게이트 전 Ctrl-C에는 부팅·복사를 이어 가 게이트까지 돌았고, `docker run` 도중의 신호에는 컨테이너가 남았다. 컨테이너 이름은 `fe-system-container-`이고 정리는 이름으로 지운다. 게이트 로그는 끝날 때 쓰므로 신호로 끊긴 실행에서는 오지 않는다. SIGKILL 뒤 남은 컨테이너를 찾아 지우는 명령은 운영 문서 FE-GATE-013 절에 있다 | `scripts/run-in-system-container.sh`, `tests/unit/ci-gate-host-environment.test.ts`, `docs/operations/ci-quality-gates.md` | `b5f28e52` | ## 미출시 — `8327e221` → 하네스와 작업 매뉴얼 -- 2.54.0