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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 56 additions & 10 deletions .github/workflows/auto-fix.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,45 @@ permissions:
contents: read

jobs:
codex:
name: Draft
prepare:
name: Prepare
if: github.event.label.name == 'auto-fix'
runs-on: ubuntu-latest
outputs:
branch: ${{ steps.branch.outputs.branch }}
skip: ${{ steps.branch.outputs.skip }}

steps:
- name: Check existing fix
id: branch
env:
GH_TOKEN: ${{ secrets.GH_AUTOMATION_TOKEN }}
ISSUE_NUMBER: ${{ github.event.issue.number }}
ISSUE_BODY: ${{ github.event.issue.body }}
run: |
marker="$(printf '%s' "$ISSUE_BODY" | sed -nE 's/.*<!-- crashlytics:([^ ]+) -->.*/\1/p' | head -n 1)"
if [ -n "$marker" ]; then
branch="auto-fix/crashlytics-$(printf '%s' "$marker" | tr -c 'A-Za-z0-9_-' '-')"
else
branch="auto-fix/issue-${ISSUE_NUMBER}"
fi
echo "branch=$branch" >> "$GITHUB_OUTPUT"

if gh api "repos/$GITHUB_REPOSITORY/git/ref/heads/$branch" > /dev/null 2>&1; then
pr="$(gh pr list --repo "$GITHUB_REPOSITORY" --head "$branch" --state all --json url --jq '.[0].url // empty')"
gh issue comment "$ISSUE_NUMBER" --repo "$GITHUB_REPOSITORY" \
--body "같은 오류의 자동 수정 브랜치 \`$branch\`가 이미 있어 수정 초안을 만들지 않음${pr:+ ($pr)}"
echo "skip=true" >> "$GITHUB_OUTPUT"
else
echo "skip=false" >> "$GITHUB_OUTPUT"
fi

codex:
name: Draft
needs: prepare
if: needs.prepare.outputs.skip == 'false'
# Ubuntu 26.04에서 codex-action의 drop-sudo가 실패해 24.04 고정 (openai/codex-action#188)
runs-on: ubuntu-24.04
outputs:
has_changes: ${{ steps.patch.outputs.has_changes }}

Expand All @@ -39,6 +74,11 @@ jobs:
npm ci --prefix functions
npm ci --prefix nestjs-api

- name: Install bubblewrap
run: |
sudo apt-get update
sudo apt-get install -y --no-install-recommends bubblewrap

- name: Write task
env:
ISSUE_NUMBER: ${{ github.event.issue.number }}
Expand Down Expand Up @@ -100,7 +140,9 @@ jobs:

open_pr:
name: Pull Request
needs: codex
needs:
- prepare
- codex
if: needs.codex.outputs.has_changes == 'true'
runs-on: ubuntu-latest

Expand Down Expand Up @@ -140,13 +182,9 @@ jobs:
GH_TOKEN: ${{ secrets.GH_AUTOMATION_TOKEN }}
ISSUE_NUMBER: ${{ github.event.issue.number }}
ISSUE_TITLE: ${{ github.event.issue.title }}
BRANCH: ${{ needs.prepare.outputs.branch }}
run: |
branch="auto-fix/issue-${ISSUE_NUMBER}"
if git ls-remote --exit-code --heads origin "$branch" > /dev/null 2>&1; then
echo "이미 같은 브랜치가 있어 건너뜀: $branch"
exit 0
fi

branch="$BRANCH"
login="$(gh api user --jq .login)"
id="$(gh api user --jq .id)"
git config user.name "$login"
Expand All @@ -155,7 +193,15 @@ jobs:
git checkout -b "$branch"
git apply --index "$RUNNER_TEMP/artifact/changes.patch"
git commit -m "fix: Crashlytics 이슈 #${ISSUE_NUMBER} 대응"
git push origin "$branch"
if ! git push origin "$branch"; then
if ! git ls-remote --exit-code --heads origin "$branch" > /dev/null 2>&1; then
exit 1
fi
pr="$(gh pr list --repo "$GITHUB_REPOSITORY" --head "$branch" --state all --json url --jq '.[0].url // empty')"
gh issue comment "$ISSUE_NUMBER" --repo "$GITHUB_REPOSITORY" \
--body "같은 오류의 자동 수정 브랜치 \`$branch\`가 먼저 만들어져 PR을 만들지 않음${pr:+ ($pr)}"
exit 0
fi

summary="$(head -c 1500 "$RUNNER_TEMP/artifact/summary.md")"
{
Expand Down
22 changes: 19 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,8 @@ Cloud Run 배포와 직접 호출 검증은 [`docs/cloud-run-staging.md`](docs/c
4. OpenAI 모델이 판단마다 근거를 인용한 JSON을 내고, 코드가 인용한 원문을 검증한 뒤 위험도를 계산합니다. 알림 등급은 영향도와 심각도 중 큰 값입니다.
5. 분석한 모든 오류를 Discord 요약으로 보냅니다. 등급 2 이상 상위 5건은 상세로, 나머지는 한 줄로 표시합니다.
6. 자동 수정 자격이 있는 오류만 이 저장소에 `auto-fix` 라벨이 붙은 이슈로 만듭니다. 같은 오류의 열린 이슈가 있으면 댓글로 갱신합니다.
7. `.github/workflows/auto-fix.yml`이 `auto-fix` 라벨이 붙은 이슈를 Codex로 수정하고 Draft PR을 올립니다. 머지는 사람이 합니다.
7. 열린 이슈가 있는 오류는 신규, 급증, 회귀가 아니어도 전날 발생했으면 미해결로 보고합니다. 다시 분석하지 않고 영향 사용자 수와 발생 건수를 이슈 댓글과 Discord 요약의 미해결 목록에 남깁니다. 그날 신규, 급증, 회귀로 분석된 오류는 요약에 분석 항목으로 나오고, 6번에서 댓글이 남지 않았으면 이슈에 미해결 댓글만 남깁니다. 이슈가 닫히면 보고를 멈춥니다.
8. `.github/workflows/auto-fix.yml`이 `auto-fix` 라벨이 붙은 이슈를 Codex로 수정하고 Draft PR을 올립니다. 머지는 사람이 합니다.

자동 수정 자격이 없는 오류는 이슈를 만들지 않고 Discord 요약에서 끝납니다.

Expand All @@ -66,7 +67,7 @@ Cloud Run 배포와 직접 호출 검증은 [`docs/cloud-run-staging.md`](docs/c
- 변경 위험과 불확실성이 모두 1 이하
- 데이터 손실과 보안 문제가 없다는 판단에 근거가 있음

수정 워크플로는 변경이 300줄을 넘거나 `.github`, 인증 코드, 설정, 의존성 파일을 건드리면 PR을 만들지 않고 이슈에 사유를 댓글로 남깁니다. 같은 이름의 브랜치(`auto-fix/issue-<번호>`)가 이미 있으면 PR을 만들지 않습니다.
수정 워크플로는 Codex 실행 전에 `functions`와 `nestjs-api` 의존성, Codex 샌드박스가 쓰는 `bubblewrap`을 설치합니다. 변경이 300줄을 넘거나 `.github`, 인증 코드, 설정, 의존성 파일을 건드리면 PR을 만들지 않고 이슈에 사유를 댓글로 남깁니다. 수정 브랜치는 오류 단위로 `auto-fix/crashlytics-<Crashlytics 이슈 ID>-<상태 코드>` 이름을 씁니다. 같은 오류의 브랜치가 이미 있으면 Codex를 실행하지 않고 이슈에 기존 PR 링크를 댓글로 남기므로, 같은 오류의 이슈가 여러 개여도 Draft PR은 하나만 만들어집니다. 같은 오류의 이슈 두 개에 거의 동시에 라벨이 붙으면 Codex는 두 번 실행될 수 있지만, PR은 먼저 끝난 실행만 만들고 나중 실행은 이슈에 기존 PR 링크를 남깁니다. 머지된 PR의 브랜치는 자동으로 지워지므로 재발하면 다시 수정을 시도하고, 머지하지 않고 닫은 PR은 브랜치를 지워야 다시 시도합니다.

### 필요한 설정

Expand All @@ -82,14 +83,29 @@ Cloud Run 배포와 직접 호출 검증은 [`docs/cloud-run-staging.md`](docs/c

### 수동 실행

Cloud Scheduler 작업을 직접 실행해 하루 분량을 즉시 처리할 수 있습니다. 같은 날 연달아 실행하면 방금 만든 이슈가 목록 조회에 늦게 반영되어 같은 오류의 이슈가 중복으로 생길 수 있습니다.
Cloud Scheduler 작업을 직접 실행해 하루 분량을 즉시 처리할 수 있습니다. 함수는 한 번에 하나만 실행하므로, 실행 중에 다시 실행하면 두 번째 요청은 잠시 대기한 뒤 실패합니다. 같은 날 연달아 실행하면 방금 만든 이슈가 목록 조회에 늦게 반영되어 같은 오류의 이슈가 중복으로 생길 수 있지만, Draft PR은 오류 단위로 하나만 만들어집니다.

```bash
gcloud scheduler jobs run firebase-schedule-sendDailyIncidentReport-asia-northeast3 \
--project <project-id> \
--location asia-northeast3
```

### 운영 확인

일일 실행은 다음 순서로 확인합니다.

1. Cloud Scheduler 작업의 마지막 실행 상태가 성공인지 확인합니다.
2. Discord에 요약이 왔는지 확인합니다. 대상 오류가 없는 날은 `신규·급증·회귀 이슈가 없습니다` 메시지가 오고, 미해결 오류가 있으면 본문 끝의 `미해결 N건`과 미해결 목록이 함께 옵니다. `일일 오류 요약을 만들지 못했습니다` 메시지가 오면 `일일 오류 요약 생성 실패` 로그를 확인합니다.
3. Cloud Functions 로그에서 오류별 `이슈 분석 완료`, `이슈 동기화 완료`의 `created`, `commented`, `failed` 수, `미해결 이슈 갱신 완료`의 `count`를 확인합니다.

자동 수정은 다음 순서로 확인합니다.

1. 새 이슈에 `crashlytics`와 `auto-fix` 라벨이 붙었는지 확인합니다.
2. Actions에서 이슈 하나당 `Auto Fix` 실행이 하나인지 확인합니다. `crashlytics` 라벨 이벤트로 생긴 실행은 건너뜀으로 표시됩니다. 같은 오류의 브랜치가 이미 있으면 `Prepare` job만 실행되고 이슈에 기존 PR 링크 댓글이 남습니다.
3. `codex` job에서 의존성과 `bubblewrap` 설치가 성공했는지, Codex 로그에 테스트 실행 결과가 있는지 확인합니다.
4. 변경이 있으면 `auto-fix/crashlytics-<Crashlytics 이슈 ID>-<상태 코드>` 브랜치와 Draft PR이 만들어지고 PR의 CI가 실행되는지 확인합니다. 제한에 걸리면 이슈에 사유 댓글이 남습니다.

## 환경 변수

Firebase CLI의 `--project`로 staging 또는 prod Firebase project를 선택합니다. 각 project에 배포된 함수는 인자 없는 `getFirestore()`로 해당 project의 `(default)` database를 사용합니다.
Expand Down
66 changes: 65 additions & 1 deletion functions/src/incident/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,30 @@ ORDER BY affectedUsers DESC, eventsDay DESC
LIMIT @maxGroups
`;

// 열린 이슈로 추적 중인 Crashlytics 이슈들의 대상 날짜 발생량을 이슈와 상태 코드 단위로 조회하는 쿼리
const selectOccurrencesQuery = `
WITH events AS (
SELECT
issue_id,
issue_subtitle,
installation_uuid,
IFNULL((SELECT value FROM UNNEST(custom_keys) WHERE key = "restStatusCode"), "") AS status
FROM \`${crashlyticsTable}\`
WHERE event_timestamp >= @dayStart
AND event_timestamp < @dayEnd
AND issue_id IN UNNEST(@issueIds)
)
SELECT
issue_id AS issueId,
status AS restStatusCode,
ANY_VALUE(issue_subtitle) AS issueSubtitle,
COUNT(DISTINCT installation_uuid) AS affectedUsers,
COUNT(*) AS events
FROM events
GROUP BY issue_id, status
ORDER BY affectedUsers DESC, events DESC
`;

// 이슈 그룹의 대표 이벤트와 스택, 사용자 정보를 조회하는 쿼리
const selectSamplesQuery = `
SELECT
Expand Down Expand Up @@ -182,6 +206,20 @@ export type ErrorGroup = {
isSurge: boolean;
};

// 열린 이슈로 추적 중인 오류의 대상 날짜 발생량
export type Occurrence = {
// Crashlytics 이슈 ID
issueId: string;
// 오류에 기록된 HTTP 상태 코드. REST 오류가 아니면 빈 문자열
restStatusCode: string;
// Crashlytics 이슈 부제. 오류 도메인과 코드를 담음
issueSubtitle: string;
// 대상 날짜에 오류를 겪은 고유 설치 수
affectedUsers: number;
// 대상 날짜 발생 건수
events: number;
};

// 조회한 대표 이벤트 하나
type SampleEvent = {
// 이벤트 ID
Expand Down Expand Up @@ -283,6 +321,32 @@ export async function selectErrorGroups(date: string): Promise<ErrorGroup[]> {
}));
}

// 지정한 Crashlytics 이슈들의 대상 날짜 발생량을 영향 사용자 수 순으로 조회
// 발생하지 않은 이슈는 결과에서 빠짐
export async function selectOccurrences(
date: string,
issueIds: string[]
): Promise<Occurrence[]> {
if (issueIds.length === 0) { return []; }

const { dayStart, dayEnd } = dayWindow(date);
const [rows] = await new BigQuery().query({
query: selectOccurrencesQuery,
params: {
dayStart,
dayEnd,
issueIds
}
});
return (rows as Occurrence[]).map((row) => ({
issueId: row.issueId,
restStatusCode: row.restStatusCode,
issueSubtitle: row.issueSubtitle,
affectedUsers: Number(row.affectedUsers),
events: Number(row.events)
}));
}

// 이슈 그룹의 영향도 계산 입력 생성
export function toImpactMetrics(group: ErrorGroup): ImpactMetrics {
return {
Expand All @@ -292,7 +356,7 @@ export function toImpactMetrics(group: ErrorGroup): ImpactMetrics {
}

// 이슈 그룹을 Discord 요약에 보여 줄 제목 생성
export function groupTitle(group: ErrorGroup): string {
export function groupTitle(group: Pick<ErrorGroup, "issueSubtitle" | "restStatusCode">): string {
return group.restStatusCode === ""
? group.issueSubtitle
: `${group.issueSubtitle} · ${group.restStatusCode}`;
Expand Down
84 changes: 76 additions & 8 deletions functions/src/incident/daily.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
groupTitle,
issueUrl,
selectErrorGroups,
selectOccurrences,
toImpactMetrics,
yesterdayInSeoul
} from "./context";
Expand All @@ -20,9 +21,21 @@ import {
buildDailySummary,
sendDiscordMessages
} from "./discord";
import type { SummaryItem } from "./discord";
import { syncIncidentIssues } from "./github";
import { buildIncidentIssue } from "./report";
import type {
OngoingItem,
SummaryItem
} from "./discord";
import {
commentOnIssue,
githubIssueUrl,
listOpenIncidentIssues,
syncIncidentIssues
} from "./github";
import {
buildIncidentIssue,
buildOngoingComment,
incidentMarkerKey
} from "./report";
import type { RiskEvidence } from "./schema";
import { scoreRisk } from "./score";
import { verifyRiskEvidence } from "./verify";
Expand All @@ -49,6 +62,7 @@ type AnalyzedGroup = {
// 어제 신규, 급증, 회귀 이슈를 분석해 Discord 일일 요약으로 전송
export const sendDailyIncidentReport = onSchedule({
maxInstances: 1,
concurrency: 1,
region: LOCATION,
schedule: "0 9 * * *",
timeZone: "Asia/Seoul",
Expand All @@ -61,10 +75,11 @@ export const sendDailyIncidentReport = onSchedule({
try {
const date = yesterdayInSeoul(new Date());
const analyzed = await analyzeGroups(date);
await reportIssues(analyzed, date);
const synced = await reportIssues(analyzed, date);
const ongoing = await reportOngoingIssues(analyzed, synced, date);
await sendDiscordMessages(
webhookUrl,
buildDailySummary(analyzed.map(({ item }) => item), date)
buildDailySummary(analyzed.map(({ item }) => item), date, ongoing)
);
} catch (error) {
logger.error("일일 오류 요약 생성 실패", toError(error));
Expand All @@ -86,17 +101,19 @@ async function analyzeGroups(date: string): Promise<AnalyzedGroup[]> {
}

// 자동 수정 대상인 이슈 그룹만 GitHub 이슈로 만들거나 갱신. 그 밖의 오류는 요약 알림에서 끝냄. 토큰이 없거나 실패해도 요약 전송은 계속
// 이슈를 만들거나 댓글을 남긴 이슈 그룹의 식별 키 반환
async function reportIssues(
analyzed: AnalyzedGroup[],
date: string
): Promise<void> {
): Promise<Set<string>> {
const synced = new Set<string>();
const targets = analyzed.filter(({ item }) => item.score.autoFixEligible);
if (targets.length === 0) { return; }
if (targets.length === 0) { return synced; }

const token = ghAutomationTokenSecret.value();
if (token === "") {
logger.warn("GitHub 토큰이 없어 이슈를 만들지 않습니다.");
return;
return synced;
}

try {
Expand All @@ -109,9 +126,60 @@ async function reportIssues(
commented: results.filter((result) => result.action === "commented").length,
failed: results.filter((result) => result.action === "failed").length
});
for (const result of results) {
if (result.action !== "failed") { synced.add(result.markerKey); }
}
} catch (error) {
logger.error("이슈 동기화 실패", toError(error));
}
return synced;
}

// 열린 이슈가 있는 오류 중 그날 이슈 댓글이 남지 않은 오류의 대상 날짜 발생량을 이슈 댓글로 남김
// 신규·급증·회귀로 분석되지 않은 오류만 요약의 미해결 항목으로 반환
// 해결되지 않은 오류를 매일 보고하려는 목적이며 재분석은 하지 않음
// 토큰이 없거나 조회가 실패해도 요약 전송은 계속
async function reportOngoingIssues(
analyzed: AnalyzedGroup[],
synced: Set<string>,
date: string
): Promise<OngoingItem[]> {
const token = ghAutomationTokenSecret.value();
if (token === "") { return []; }

try {
const analyzedKeys = new Set(analyzed.map(({ group }) => incidentMarkerKey(group)));
const openIssues = await listOpenIncidentIssues(token);
const trackedIssueIds = [...openIssues.keys()]
.filter((markerKey) => !synced.has(markerKey))
.map((markerKey) => markerKey.split(":")[0]);
const occurrences = await selectOccurrences(date, [...new Set(trackedIssueIds)]);

const items: OngoingItem[] = [];
for (const occurrence of occurrences) {
const markerKey = incidentMarkerKey(occurrence);
const number = openIssues.get(markerKey);
if (number === undefined || synced.has(markerKey)) { continue; }

try {
await commentOnIssue(token, number, buildOngoingComment(occurrence, date));
} catch (error) {
logger.error("미해결 이슈 댓글 실패", toError(error), { number });
}
if (analyzedKeys.has(markerKey)) { continue; }
items.push({
title: groupTitle(occurrence),
url: githubIssueUrl(number),
affectedUsers: occurrence.affectedUsers,
events: occurrence.events
});
}
logger.info("미해결 이슈 갱신 완료", { count: items.length });
return items;
} catch (error) {
logger.error("미해결 이슈 조회 실패", toError(error));
return [];
}
}

// 이슈 그룹 하나를 분석하고 근거 검증과 위험도 계산을 거쳐 요약 항목으로 변환. 분석에 실패하면 판단 불가 항목으로 대체
Expand Down
Loading
Loading