From 914c2083382643945933b410a6e6330701a4ef9f Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 6 Nov 2026 19:58:00 +0900 Subject: [PATCH 01/71] =?UTF-8?q?build(claude):=20=ED=94=84=EB=A1=9C?= =?UTF-8?q?=EC=A0=9D=ED=8A=B8=20=EC=84=A4=EC=A0=95=EC=9C=BC=EB=A1=9C=20Age?= =?UTF-8?q?nt=20=EB=8F=84=EA=B5=AC=EB=A5=BC=20=EB=A7=89=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 소유자 규칙은 "세션 안의 하위 에이전트(Agent 도구)를 쓰지 않고, 일을 나눌 때는 사람이 열어 보고 멈출 수 있는 별도 세션에 맡긴다"이다. 그런데 이 규칙은 문서와 메모리에만 있었고, AGENTS.md 「Superpowers Workflow」는 오히려 subagent-driven-development·dispatching-parallel-agents를 쓰라고 안내했다. 하위 세션 시작이 막혔을 때 Agent로 우회한 일도 있었다. 고른 방법: 이 repo의 .claude/settings.json에 permissions.deny "Agent"를 둔다 (2026-11-06 소유자 결정 D5: 사용자 설정이 아니라 두 템플릿 repo의 프로젝트 설정). Claude Code 권한 문서대로 맨 도구 이름 deny는 그 도구를 세션에서 없애고, 한 설정 단계의 deny는 다른 단계의 allow로 풀리지 않는다. .gitignore는 .claude/ 전체 무시를 .claude/* + !.claude/settings.json으로 바꿔 이 파일 하나만 추적한다. settings.local.json, worktree, 노트는 계속 무시한다. AGENTS.md의 두 스킬 문장은 "이 저장소에서는 쓰지 않는다"로 바꿨다. 버린 대안: 사용자 설정(~/.claude/settings.json)에 두기는 다른 프로젝트에서 Agent를 쓸 여지를 없앤다. PreToolUse 훅은 deny 규칙 하나로 충분한 일에 스크립트를 더한다. 위험·한계: 추적 파일이라 이 템플릿을 받는 파생 서비스(tech-log-backend 등)에도 넘어간다. 파생 서비스가 Agent를 쓰려면 그 파일을 자기 repo에서 고쳐야 한다. deny가 실제로 막는지는 Agent를 불러 보는 방식으로 시험하지 않았다(막히지 않으면 하위 에이전트가 떠서 규칙을 어긴다). 대신 공식 권한 문서의 문법과 우선순위를 확인했다. 검증 - jq -e '.permissions.deny | index("Agent")' .claude/settings.json: rc=0 - git check-ignore: .claude/settings.json 추적 가능, settings.local.json· .claude/worktrees/·.claude/review-followup/ 무시 --- .claude/settings.json | 7 +++++++ .gitignore | 5 ++++- AGENTS.md | 6 ++++-- 3 files changed, 15 insertions(+), 3 deletions(-) create mode 100644 .claude/settings.json diff --git a/.claude/settings.json b/.claude/settings.json new file mode 100644 index 00000000..3a3d67f9 --- /dev/null +++ b/.claude/settings.json @@ -0,0 +1,7 @@ +{ + "permissions": { + "deny": [ + "Agent" + ] + } +} diff --git a/.gitignore b/.gitignore index b2ef4065..8b8a6e09 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,9 @@ .vscode/ src/**/bin/ -.claude/ +# Local Claude Code state (worktrees, settings.local.json, notes) stays out. The shared project +# settings file is committed: it denies the Agent tool for everyone (AGENTS.md 「Superpowers Workflow」). +.claude/* +!.claude/settings.json # Operator input, not a build input. The examples beside it are the tracked contract; # verifyEnvKeys reads the registry, the profile YAMLs and .env.example, never a real one. diff --git a/AGENTS.md b/AGENTS.md index b37bbaf3..3341d675 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -35,8 +35,10 @@ root `CLAUDE.md`는 이 목록의 동기화된 요약이다. 두 문서가 어 - `superpowers:brainstorming`: 기능 설계, 구조 변경, 동작 변경, 새 문서 정책 수립 전에 사용한다. - `superpowers:writing-plans`: 승인된 설계가 있고 작업이 여러 단계로 나뉠 때 사용한다. - `superpowers:executing-plans`: 작성된 계획을 현재 세션에서 순차 실행할 때 사용한다. -- `superpowers:subagent-driven-development`: 계획을 작업 단위로 나누어 독립 에이전트에게 맡길 때 사용한다. -- `superpowers:dispatching-parallel-agents`: 서로 독립적인 조사나 구현을 병렬로 진행할 때 사용한다. +- `superpowers:subagent-driven-development`, `superpowers:dispatching-parallel-agents`: 이 저장소에서는 + 쓰지 않는다. 세션 안의 하위 에이전트(Agent 도구)는 `.claude/settings.json`이 막는다. 일을 나눠 + 맡길 때는 사람이 열어 보고 멈출 수 있는 별도 세션에 맡긴다. 다른 스킬이 + 하위 에이전트를 띄우라고 하면 그 단계는 같은 세션이 직접 한다. - `superpowers:test-driven-development`: 기능 추가와 버그 수정을 테스트 우선으로 진행할 때 사용한다. - `superpowers:systematic-debugging`: 버그, 실패한 테스트, 예상 밖 동작을 다룰 때 사용한다. - `superpowers:verification-before-completion`: 완료, 수정됨, 통과함을 주장하기 전에 사용한다. From d35bbb614b2b7b413bf80459b306344c7d500a70 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 6 Nov 2026 19:58:15 +0900 Subject: [PATCH 02/71] =?UTF-8?q?feat(scripts):=20=EC=9E=91=EC=97=85=20?= =?UTF-8?q?=EB=A7=A4=EB=89=B4=EC=96=BC=20=EA=B2=80=EC=82=AC=EC=99=80=20?= =?UTF-8?q?=EB=A6=AC=EB=B7=B0=20=EC=83=89=EC=9D=B8=20=EB=8C=80=EC=A1=B0=20?= =?UTF-8?q?=EC=8A=A4=ED=81=AC=EB=A6=BD=ED=8A=B8=EB=A5=BC=20=EB=8D=94?= =?UTF-8?q?=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 옛 개선 매뉴얼은 진입 경로가 717줄이었고 본문에 지난 리뷰 ID가 든 줄이 많아, 이력을 모르는 세션은 근거를 따라가지 못했다. 이것을 사람 눈으로만 지키면 다시 늘어난다. 리뷰 색인도 손으로 옮기다 발견 5건이 빠져 어떤 수정 묶음에도 배정되지 않은 적이 있다(원래 리뷰 124건이 색인에는 119건). 고른 방법: Gradle 밖 Python 스크립트 두 개를 둔다(2026-11-06 소유자 결정 D6: 이 repo는 문서를 파싱하는 Gradle 검사를 두지 않는다). - check-work-docs.py: 지도(CLAUDE.md)와 docs/work/의 분량 상한(지도 120, README 80, playbook 150, 진입 경로 350), playbook 9칸 뼈대, 「자주 하는 실수」 10줄, 본문 이력 ID 0(evidence.md와 reference/의 두 색인 문서는 제외), 상대 링크를 본다. --links, --history 모드로 다른 문서에도 쓴다. - check-review-index.py: 리뷰 폴더의 영역 문서 제목에 있는 발견 ID가 README 색인에 모두 있는지 본다. 범위(A~B)와 이어 쓰기(A·07)를 읽고, NN- 자리표시자를 잡는다. 정규식은 re.ASCII로 쓴다. Python의 \w·\b가 한글을 단어 문자로 봐서 "RR6-01-07과" 같은 표기를 놓쳤다. 버린 대안: document-contract Gradle lane(이 repo 원칙과 충돌), 검사 없이 cold-read 시험에서만 확인(매번 사람이 세야 한다). 위험·한계: check-work-docs.py가 보는 docs/work/는 다음 커밋에 들어온다. 이 커밋만으로는 "missing"으로 실패한다. 이력 ID 패턴은 이 repo가 쓴 형식만 안다 (MMDD/, RR-, 묶음 이름, round, 번호만 쓴 결정, 커밋 sha). 색인 검사는 "이름이 있나"만 보고 고쳤는지는 보지 않는다. 검증 - check-review-index.py docs/reviews/2026-11-01-maturity-review --index-heading "12. 발견 색인": 124/124, rc=0 - 같은 폴더를 사고 시점 34565130에서 꺼내 돌림: NN-10~NN-14 5건, rc=1 - check-review-index.py docs/reviews/2026-11-03-rereview: 157 중 135, rc=1 (README가 ID 대신 내용·건수로 적은 22건) - check-work-docs.py를 일부러 망가뜨린 사본 18가지에 돌림: 이력 ID 7형식, 분량 3종, 뼈대, 실수 줄 수, 깨진 링크, 빠진 파일은 rc=1, ID가 허용된 파일과 "결정 3개" 같은 개수 표현은 rc=0 --- scripts/check-review-index.py | 129 ++++++++++++++++ scripts/check-work-docs.py | 269 ++++++++++++++++++++++++++++++++++ 2 files changed, 398 insertions(+) create mode 100755 scripts/check-review-index.py create mode 100755 scripts/check-work-docs.py diff --git a/scripts/check-review-index.py b/scripts/check-review-index.py new file mode 100755 index 00000000..e3348c9d --- /dev/null +++ b/scripts/check-review-index.py @@ -0,0 +1,129 @@ +#!/usr/bin/env python3 +"""Fail when a finding written in a review's area documents is missing from that review's index. + +A review folder (`docs/reviews/-/`) holds one README and one document per area (and, +for confirmation reviews, `roundN/` documents). Each finding is a heading that starts with its ID: +`### 05-01 ...`, `#### RR-02-03 · ...`, `### RR6-01-01 · Important · ...`. Fix bundles are assigned +from the README, so a finding the README does not name is a finding nobody fixes. That happened +once: five findings were dropped while IDs were copied into the index by hand. + +This compares the two mechanically. Every finding ID in an area heading must appear in the README +(or, with --index-heading, in that README section). A range such as `RR-01-11~17` or +`06-10~06-14` counts for every ID inside it. A heading ID that still has a placeholder area +(`NN-10`) is reported too, because it cannot be assigned at all. + + python3 scripts/check-review-index.py docs/reviews/2026-11-01-maturity-review --index-heading "12. 발견 색인" + python3 scripts/check-review-index.py docs/reviews/2026-11-03-rereview +""" + +from __future__ import annotations + +import argparse +import re +import sys +from pathlib import Path + +# re.ASCII: Korean letters are word characters to Python's \w, so "RR6-01-07과" would not match. +FINDING_HEADING = re.compile(r"^#{2,6}\s+`?((?:RR\d*-)?(?:\d{2}|NN)-\d{2})\b", re.ASCII) +ID = r"(?:RR\d*-)?\d{2}-\d{2}" +# A list starts with a full ID and may go on with "~NN" (a range up to NN) or "·NN" (one more number +# with the same prefix): "RR-04-06~08·10·11" is 06, 07, 08, 10 and 11. "06-10~06-14" is a range too. +LIST = re.compile( + rf"`?(? dict[str, list[str]]: + findings: dict[str, list[str]] = {} + for path in sorted(review.rglob("*.md")): + if path.name == "README.md" and path.parent == review: + continue + for number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1): + match = FINDING_HEADING.match(line) + if match: + findings.setdefault(match.group(1), []).append( + f"{path.relative_to(review).as_posix()}:{number}" + ) + return findings + + +def index_text(readme: Path, heading: str | None) -> str: + lines = readme.read_text(encoding="utf-8").splitlines() + if heading is None: + return "\n".join(lines) + for start, line in enumerate(lines): + match = re.match(r"^(#+)\s+(.*)$", line) + if match and match.group(2).strip() == heading: + level = len(match.group(1)) + end = len(lines) + for later in range(start + 1, len(lines)): + other = re.match(r"^(#+)\s", lines[later]) + if other and len(other.group(1)) <= level: + end = later + break + return "\n".join(lines[start:end]) + raise SystemExit(f"{readme}: no heading '{heading}'") + + +def indexed_ids(text: str) -> set[str]: + ids = set(SINGLE.findall(text)) + for first, tail in LIST.findall(text): + prefix, number = first.rsplit("-", 1) + current = int(number) + for kind, value in STEP.findall(tail): + if "-" in value: + value_prefix, value = value.rsplit("-", 1) + if value_prefix != prefix: + ids.add(f"{value_prefix}-{value}") + continue + target = int(value) + if kind == "·": + ids.add(f"{prefix}-{target:02d}") + else: + ids.update(f"{prefix}-{n:02d}" for n in range(current, target + 1)) + current = target + return ids + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("review", type=Path, help="review folder, e.g. docs/reviews/2026-11-01-maturity-review") + parser.add_argument("--index-heading", help="compare against this README section only (heading text)") + args = parser.parse_args() + + readme = args.review / "README.md" + if not readme.is_file(): + print(f"{readme}: missing", file=sys.stderr) + return 1 + + findings = area_findings(args.review) + indexed = indexed_ids(index_text(readme, args.index_heading)) + placeholder = sorted(finding for finding in findings if "NN-" in finding) + missing = sorted(f for f in findings if f not in indexed and f not in placeholder) + duplicated = sorted(f for f, places in findings.items() if len(places) > 1) + + scope = f"section '{args.index_heading}'" if args.index_heading else "whole README" + print(f"review: {args.review}") + print(f"index: README.md, {scope}") + print(f"finding headings in area documents: {len(findings)}") + print(f"found in index: {len(findings) - len(missing) - len(placeholder)}") + print(f"missing from index: {len(missing)}") + for finding in missing: + print(f" {finding} ({', '.join(findings[finding])})") + if placeholder: + print(f"placeholder area (NN-): {len(placeholder)}") + for finding in placeholder: + print(f" {finding} ({', '.join(findings[finding])})") + if duplicated: + print(f"same ID in more than one heading (check they are one finding): {len(duplicated)}") + for finding in duplicated: + print(f" {finding} ({', '.join(findings[finding])})") + + return 1 if missing or placeholder else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/check-work-docs.py b/scripts/check-work-docs.py new file mode 100755 index 00000000..0a40e226 --- /dev/null +++ b/scripts/check-work-docs.py @@ -0,0 +1,269 @@ +#!/usr/bin/env python3 +"""Fail when the work manual stops being readable without history or grows past its size limits. + +The work manual is the root `CLAUDE.md` (the map) plus `docs/work/`. A session that has never seen +this repository's history reads the map, `docs/work/README.md` and one playbook, and must be able +to finish the job from those alone. Two things break that, and both are mechanical: + +1. History IDs in the body. A sentence such as "fixed as in 1101/05-01" means nothing to a reader + who does not know that review. History belongs in `docs/work/evidence.md`, and the two reference + files that are indexes of history (`reference/decisions.md`, `reference/defect-patterns.md`). +2. Length. Each entry file has a line limit, and the entry path (map + README + one playbook) has a + total limit, so a session reads the whole path instead of skimming it. + +It also checks that every playbook keeps the shared nine-section skeleton, that the +"common mistakes" section stays short, and that relative links in the checked files resolve. + +This lives outside Gradle on purpose: the build does not parse documents. + + python3 scripts/check-work-docs.py + python3 scripts/check-work-docs.py --links docs README.md # relative links only, any files + python3 scripts/check-work-docs.py --history docs/manual # history IDs only, any files + +The --links form is for machines without lychee (the link checker the pull-request workflow runs). +The --history form applies the same history-ID patterns to documents outside docs/work/. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parent.parent +MAP = REPO_ROOT / "CLAUDE.md" +WORK = REPO_ROOT / "docs/work" +README = WORK / "README.md" + +PLAYBOOKS = [ + "new-feature.md", + "improve.md", + "research-design.md", + "docs-writing.md", + "operate.md", + "delegate.md", +] +REFERENCES = [ + "reference/gates.md", + "reference/review-criteria.md", + "reference/defect-patterns.md", + "reference/decisions.md", +] +EVIDENCE = "evidence.md" + +# Files that may name history, relative to docs/work/. Everything else must not. +HISTORY_ALLOWED = {EVIDENCE, "reference/decisions.md", "reference/defect-patterns.md"} + +MAP_LIMIT = 120 +README_LIMIT = 80 +PLAYBOOK_LIMIT = 150 +ENTRY_PATH_LIMIT = 350 +MISTAKES_LIMIT = 10 + +SKELETON = [ + "1. 언제 쓰나", + "2. 받아야 할 것", + "3. 크기와 사고 순서", + "4. 절차", + "5. 완료 기준", + "6. 하지 말 것", + "7. 막혔을 때", + "8. 보고 형식", + "9. 자주 하는 실수", +] + +# Each pattern names a kind of history identifier. A match is a sentence that only a reader who +# knows the past can follow. re.ASCII keeps \b and \w to ASCII: Python counts Korean letters as +# word characters, so "RR6-01-07과" would otherwise slip through. +HISTORY_PATTERNS = [ + ("review ID with a date prefix (MMDD/...)", + re.compile(r"(? str: + return path.relative_to(REPO_ROOT).as_posix() + + +def line_count(path: Path) -> int: + return len(path.read_text(encoding="utf-8").splitlines()) + + +def check_exists(errors: list[str]) -> bool: + expected = [MAP, README, WORK / EVIDENCE] + expected += [WORK / name for name in PLAYBOOKS + REFERENCES] + missing = [rel(path) for path in expected if not path.is_file()] + for name in missing: + errors.append(f"{name}: missing") + return not missing + + +def check_limits(errors: list[str], report: list[str]) -> None: + for path, limit in [(MAP, MAP_LIMIT), (README, README_LIMIT)]: + lines = line_count(path) + report.append(f"{rel(path)}: {lines}/{limit}") + if lines > limit: + errors.append(f"{rel(path)}: {lines} lines, limit {limit}") + base = line_count(MAP) + line_count(README) + for name in PLAYBOOKS: + path = WORK / name + lines = line_count(path) + entry = base + lines + report.append(f"{rel(path)}: {lines}/{PLAYBOOK_LIMIT}, entry path {entry}/{ENTRY_PATH_LIMIT}") + if lines > PLAYBOOK_LIMIT: + errors.append(f"{rel(path)}: {lines} lines, limit {PLAYBOOK_LIMIT}") + if entry > ENTRY_PATH_LIMIT: + errors.append( + f"{rel(path)}: entry path CLAUDE.md + docs/work/README.md + this file is {entry} lines," + f" limit {ENTRY_PATH_LIMIT}" + ) + + +def outside_code_blocks(lines: list[str]) -> list[str]: + """Blank out fenced code blocks, so an example such as a report template is not a section.""" + kept: list[str] = [] + fenced = False + for line in lines: + if line.lstrip().startswith("```"): + fenced = not fenced + kept.append("") + else: + kept.append("" if fenced else line) + return kept + + +def check_skeleton(errors: list[str]) -> None: + for name in PLAYBOOKS: + path = WORK / name + lines = outside_code_blocks(path.read_text(encoding="utf-8").splitlines()) + headings = [line[3:].strip() for line in lines if line.startswith("## ")] + if headings != SKELETON: + errors.append( + f"{rel(path)}: sections must be exactly {SKELETON} in that order, found {headings}" + ) + continue + start = lines.index("## " + SKELETON[-1]) + items = [line for line in lines[start + 1:] if re.match(r"^(?:[-*]|\d+\.) ", line)] + if len(items) > MISTAKES_LIMIT: + errors.append( + f"{rel(path)}: '{SKELETON[-1]}' has {len(items)} items, limit {MISTAKES_LIMIT}" + " (move one to a reference file or delete one)" + ) + + +def history_checked_files() -> list[Path]: + files = [MAP] + for path in sorted(WORK.rglob("*.md")): + if path.relative_to(WORK).as_posix() not in HISTORY_ALLOWED: + files.append(path) + return files + + +def history_hits(files: list[Path]) -> list[tuple[Path, int, str, str]]: + hits = [] + for path in files: + for number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1): + for label, pattern in HISTORY_PATTERNS: + match = pattern.search(line) + if match: + hits.append((path, number, label, match.group(0))) + break + return hits + + +def broken_links(files: list[Path]) -> tuple[int, list[tuple[Path, int, str]]]: + checked = 0 + broken = [] + for path in files: + for number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1): + for target in LINK.findall(line): + if re.match(r"^[a-z][a-z0-9+.-]*:", target) or target.startswith("#"): + continue + checked += 1 + if not (path.parent / target.split("#", 1)[0]).exists(): + broken.append((path, number, target)) + return checked, broken + + +def check_history(errors: list[str], report: list[str]) -> None: + hits = history_hits(history_checked_files()) + for path, number, label, text in hits: + errors.append( + f"{rel(path)}:{number}: {label} '{text}'" + " - write the content instead, and move the ID to docs/work/evidence.md" + ) + report.append(f"history ID lines in checked files: {len(hits)}") + + +def check_links(errors: list[str], report: list[str]) -> None: + checked, broken = broken_links([MAP] + sorted(WORK.rglob("*.md"))) + for path, number, target in broken: + errors.append(f"{rel(path)}:{number}: broken relative link '{target}'") + report.append(f"relative links checked: {checked}") + + +def markdown_files(targets: list[str]) -> list[Path]: + files: list[Path] = [] + for target in targets: + path = (Path.cwd() / target).resolve() + files += sorted(path.rglob("*.md")) if path.is_dir() else [path] + return files + + +def links_only(targets: list[str]) -> int: + files = markdown_files(targets) + checked, broken = broken_links(files) + print(f"files: {len(files)}, relative links checked: {checked}, broken: {len(broken)}") + for path, number, target in broken: + print(f" {path}:{number}: broken relative link '{target}'", file=sys.stderr) + return 1 if broken else 0 + + +def history_only(targets: list[str]) -> int: + files = markdown_files(targets) + hits = history_hits(files) + print(f"files: {len(files)}, lines with history IDs: {len(hits)}") + for path, number, label, text in hits: + print(f" {path}:{number}: {label} '{text}'", file=sys.stderr) + return 1 if hits else 0 + + +MODES = {"--links": links_only, "--history": history_only} + + +def main() -> int: + if sys.argv[1:2] and sys.argv[1] in MODES: + if len(sys.argv) < 3: + print(f"usage: check-work-docs.py {sys.argv[1]} ...", file=sys.stderr) + return 2 + return MODES[sys.argv[1]](sys.argv[2:]) + errors: list[str] = [] + report: list[str] = [] + if check_exists(errors): + check_limits(errors, report) + check_skeleton(errors) + check_history(errors, report) + check_links(errors, report) + for line in report: + print(line) + if errors: + print(f"\nFAILED: {len(errors)} problem(s)", file=sys.stderr) + for error in errors: + print(f" {error}", file=sys.stderr) + return 1 + print("\nOK") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) From 63c63413d19c8a80ab433fdbebd1f031a6399caa Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 6 Nov 2026 19:58:44 +0900 Subject: [PATCH 03/71] =?UTF-8?q?docs(work):=20=EC=A7=80=EB=8F=84=EC=99=80?= =?UTF-8?q?=20=EC=9E=91=EC=97=85=20=EC=A2=85=EB=A5=98=EB=B3=84=20playbook?= =?UTF-8?q?=EC=9C=BC=EB=A1=9C=20=EC=9E=91=EC=97=85=20=EB=A7=A4=EB=89=B4?= =?UTF-8?q?=EC=96=BC=EC=9D=84=20=EB=A7=8C=EB=93=A0=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 이 repo의 진입 문서는 아키텍처 규칙을 길게 다시 쓴 CLAUDE.md(183줄)와 리뷰·수정만 다루는 옛 개선 매뉴얼(진입 717줄, 미병합)이었다. 이력 없는 세션이 "이 일이면 무엇을 읽나"를 알 수 없었고, 새 기능·조사·문서·운영·총괄의 절차는 없었다. 규칙도 서로 달랐다: 하위 에이전트(AGENTS.md는 권함, 소유자는 금지), 커밋(human-only와 브랜치 커밋 허용), 리뷰 멈춤 기준(거둔 기준이 남음). 고른 방법(2026-11-06 소유자 결정 D1, D2, D4, D12; 설계 design-docs delegation-loop/02-design.md 4~6·10절): - CLAUDE.md를 72줄 지도로 바꿨다: 이 repo, HARD-STOP 7개 한 줄씩(정본 AGENTS.md), 일 → playbook 표, 검증 명령과 실행 위치, 코드만 보고는 헷갈리는 곳, 소유자 환경 포인터. AGENTS.md를 요약하던 절은 지웠다. AGENTS.md에 없던 내용은 옮겼다: messaging 예외는 지도 5절, 판단 보고 규칙은 reference/review-criteria.md 11절, 위험 비례 원칙은 docs/work/README.md 2절. - docs/work/: README(라우터·크기·공통 단계·커밋·막혔을 때·보고), playbook 6개 (new-feature, improve, research-design, docs-writing, operate, delegate, 모두 같은 9칸 뼈대), reference/ 4개(gates, review-criteria, defect-patterns, decisions), evidence.md. 옛 매뉴얼 03~06장은 reference/를 늘리지 않고 review-criteria(점검 기준), defect-patterns(막는 기준), gates(성능 lane)에 나눠 넣었다. 다섯 번째 reference 파일은 설계의 파일 구성과 달라 버렸고, improve.md 본문에 넣는 안은 150줄 상한을 넘어 버렸다. - improve.md에 수정 보고의 「새로 가정하는 것」 칸(확인 리뷰가 여기서 시작)과 수정 묶음 상한(영역 하나·발견 8건, 확인 리뷰당 추가 1,500줄)을 넣었다. 지난 수정 커밋의 추가 줄과 다음 확인 리뷰 발견 수(+906→9, +1,877→7, +5,420→25, +13,479→29)가 근거다(evidence.md 3절). 멈춤 기준은 "발견 0"으로 하나만 둔다. - 커밋: AGENTS.md human-only는 두고 "brief가 허용할 때만 자기 브랜치에" 예외를 README 4절과 AGENTS.md에 같은 말로 적었다. - 본문 이력 ID 0. 지난 리뷰 ID와 사건은 evidence.md와 두 색인 (reference/decisions.md, reference/defect-patterns.md)에만 둔다. - 연결: README.md(HARD-STOP을 "8개"로 잘못 적은 것도 7개로), docs/README.md, docs/manual/README.md(입구 연결), docs/manual/02-new-feature.md(지운 CLAUDE.md 「Layer workflow」를 가리키던 줄). 위험·한계: 이 매뉴얼은 이력 없는 새 세션으로 시험(cold-read)하기 전이라 초안이다. 정식 시험은 총괄이 따로 한다. 작성 중 자가 점검(지도부터 읽어 docs-writing.md로 brief 하나를 써 봄)에서 막힌 네 곳은 고쳤다. docs/manual/ 본문에는 아직 이력 ID 9줄이 남아 있다(범위 밖, 후속 작업). gates.md 5절의 성능 단언 속성 문장은 성능 게이트를 고치는 다른 작업과 겹친다. 검증 - python3 scripts/check-work-docs.py: rc=0. 지도 72/120, README 75/80, playbook 79~132/150, 진입 경로 최대 279/350, 본문 이력 ID 0줄 - python3 scripts/check-work-docs.py --links docs README.md CLAUDE.md AGENTS.md: 504파일, 상대 링크 447개, 깨진 것 0 - CLAUDE.md를 읽는 테스트 DeveloperExperienceContractTest .guidanceNamesTheArchitectureSourceSetTask가 기대하는 "./gradlew :app-bootstrap:architectureTest"를 지도에 남겼다. Gradle 게이트는 이 커밋을 push한 뒤 desktop에서 돌린다 --- AGENTS.md | 9 +- CLAUDE.md | 207 +++++------------- README.md | 5 +- docs/README.md | 3 +- docs/manual/02-new-feature.md | 4 +- docs/manual/README.md | 5 +- docs/work/README.md | 75 +++++++ docs/work/delegate.md | 116 ++++++++++ docs/work/docs-writing.md | 83 ++++++++ docs/work/evidence.md | 150 +++++++++++++ docs/work/improve.md | 132 ++++++++++++ docs/work/new-feature.md | 79 +++++++ docs/work/operate.md | 115 ++++++++++ docs/work/reference/decisions.md | 188 ++++++++++++++++ docs/work/reference/defect-patterns.md | 131 ++++++++++++ docs/work/reference/gates.md | 129 +++++++++++ docs/work/reference/review-criteria.md | 283 +++++++++++++++++++++++++ docs/work/research-design.md | 90 ++++++++ 18 files changed, 1636 insertions(+), 168 deletions(-) create mode 100644 docs/work/README.md create mode 100644 docs/work/delegate.md create mode 100644 docs/work/docs-writing.md create mode 100644 docs/work/evidence.md create mode 100644 docs/work/improve.md create mode 100644 docs/work/new-feature.md create mode 100644 docs/work/operate.md create mode 100644 docs/work/reference/decisions.md create mode 100644 docs/work/reference/defect-patterns.md create mode 100644 docs/work/reference/gates.md create mode 100644 docs/work/reference/review-criteria.md create mode 100644 docs/work/research-design.md diff --git a/AGENTS.md b/AGENTS.md index 3341d675..b5c1d5a7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -22,8 +22,9 @@ 6. 관련 검증 없이, 또는 실행하지 못한 이유를 밝히지 않고 완료를 주장한다. 7. 결론의 범위와 위험에 맞는 증거 없이 repository/corpus 전체 결론을 내린다. -root `CLAUDE.md`는 이 목록의 동기화된 요약이다. 두 문서가 어긋나면 이 `AGENTS.md` 목록이 -우선한다. 자동 강제 범위는 아래 Gradle 정책 권위와 ArchUnit/Test가 담당한다. +root `CLAUDE.md`는 작업을 시작할 때 읽는 지도이고, 이 목록을 한 줄씩 가리킨다. 두 문서가 어긋나면 +이 `AGENTS.md` 목록이 우선한다. 일의 종류별 절차는 `docs/work/`에 있다. 자동 강제 범위는 아래 Gradle +정책 권위와 ArchUnit/Test가 담당한다. ## Superpowers Workflow @@ -37,7 +38,7 @@ root `CLAUDE.md`는 이 목록의 동기화된 요약이다. 두 문서가 어 - `superpowers:executing-plans`: 작성된 계획을 현재 세션에서 순차 실행할 때 사용한다. - `superpowers:subagent-driven-development`, `superpowers:dispatching-parallel-agents`: 이 저장소에서는 쓰지 않는다. 세션 안의 하위 에이전트(Agent 도구)는 `.claude/settings.json`이 막는다. 일을 나눠 - 맡길 때는 사람이 열어 보고 멈출 수 있는 별도 세션에 맡긴다. 다른 스킬이 + 맡길 때는 사람이 열어 보고 멈출 수 있는 별도 세션에 맡긴다(`docs/work/delegate.md`). 다른 스킬이 하위 에이전트를 띄우라고 하면 그 단계는 같은 세션이 직접 한다. - `superpowers:test-driven-development`: 기능 추가와 버그 수정을 테스트 우선으로 진행할 때 사용한다. - `superpowers:systematic-debugging`: 버그, 실패한 테스트, 예상 밖 동작을 다룰 때 사용한다. @@ -107,6 +108,8 @@ root `CLAUDE.md`는 이 목록의 동기화된 요약이다. 두 문서가 어 변경한 경계와 런타임·보안·데이터 영향에 맞춰 설계·리뷰·검증 강도를 높인다. commit 정책은 모든 플랫폼에서 `human-only`이며 agent는 stage/commit/amend/push하지 않는다. +예외는 하나다: 작업 지시(brief)가 허용하면 그 작업의 자기 브랜치에만 commit·push한다. main 병합, +다른 브랜치 push, force push는 하지 않는다(`docs/work/README.md` 「커밋」). ## 강제 수준 diff --git a/CLAUDE.md b/CLAUDE.md index 4921a632..2bcb271e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,136 +1,45 @@ -# CLAUDE.md +# CLAUDE.md — 이 repo의 지도 -Repository guidance for the Java 21 + Spring Boot 4.0.8 Clean Architecture template. +이 파일은 세션이 처음 읽는 지도다. 규칙을 담지 않고, 어떤 일이면 무엇을 읽을지 가리킨다. -## Prime Directive +## 1. 이 repo -Preserve architecture before optimizing for speed. The following seven HARD-STOP conditions are a -synchronized summary of the canonical local policy in `AGENTS.md`: +- Java 21 + Spring Boot 4.0.8 Gradle 멀티모듈 Clean Architecture 백엔드 템플릿이다. 서비스는 이 repo를 받아 도메인을 채운다. +- Gradle 루트는 `src/`다. Gradle 명령은 `src/`에서 실행한다. +- 규칙의 정본은 `AGENTS.md`다. leaf 목록·경로·허용 의존의 정본은 `src/config/architecture/modules.json`(registry)이다. 각 leaf의 지역 규칙은 가장 가까운 `src/**/CLAUDE.md`가 정한다. -1. `domain-core` gains framework, transport, database, or cloud dependencies. -2. A controller directly uses a repository, Spring Data interface, or persistence entity. -3. An inbound DTO leaks into `application-core` or `domain-core`. -4. Business rules move into mappers, filters, configuration, settings, or controllers. -5. Project dependencies violate `src/config/architecture/modules.json` or the Gradle dependency - gate. -6. Completion is claimed without the relevant verification or a named reason it could not run. -7. A repository/corpus conclusion is made without evidence proportional to its scope and risk. +## 2. HARD-STOP — 하나라도 어기면 완료가 아니다 -If this summary drifts from `AGENTS.md`, `AGENTS.md` wins and this summary must be resynchronized. +정본은 `AGENTS.md` 「Prime Directive」다. 두 문서가 다르면 `AGENTS.md`가 맞다. -## Gradle policy authorities +1. `domain-core`가 framework·transport·database·cloud 의존성을 가진다. +2. controller가 repository·Spring Data interface·persistence entity를 직접 쓴다. +3. inbound DTO가 `application-core`나 `domain-core`로 들어간다. +4. 업무 규칙이 mapper·filter·configuration·settings·controller로 옮겨 간다. +5. 프로젝트 의존성이 registry나 Gradle 의존성 검증을 어긴다. +6. 관련 검증 없이, 또는 돌리지 못한 이유를 밝히지 않고 완료를 말한다. +7. 결론의 범위와 위험에 맞는 증거 없이 저장소 전체에 대한 결론을 낸다. -- `src/config/architecture/modules.json`: every registered leaf identity, repository-relative source - paths, Gradle paths and allowed production project dependency edges. There is no runtime - membership list: what a composition root may take is its `allowed_dependencies`, and the direction - gate refuses any other edge. The registry owns the leaf list and its size; no document restates - the count, because a number written in prose drifts the moment a leaf is added. -- `src/settings.gradle`: fail-closed registry validation, project inclusion, and directory mapping. -- `src/build-logic/`: the architecture core (registry, direction and purity tasks), the conventions, - and one test-lane mechanism (`strictTestLanes`). Feature-specific checks are the owning leaf's - tests; a test that reads repository files declares them as that leaf's test `inputs`, and a test - that compares a leaf with repository documents is a `mainStage()` lane (tag `document-contract`) - in that leaf's `mainCheck`; a merge-blocking contract over non-document repository files is a - pull-request lane whose inputs are exactly those files (app-bootstrap `repository-contract`). - `TEST`/`ARCHITECTURE` lanes are cacheable; `INTEGRATION`/`SYSTEM`/`PERFORMANCE` and main-stage - lanes rerun every time. -- `verifyEnvKeys` stays an app-bootstrap task (owner decision 4); its implementation is build-logic's - `ca.config-contract`. The `src/build-tools/` included build was emptied and removed. -- `src/build.gradle`: the root lifecycle (`ci`, `mainCheck`, `integrationCheck`, `performanceCheck`, - `releaseCheck` and the named repository-wide gates). `verifyStrictLaneStages --dry-run` (pull - request; the main build and, as `-p optional-platforms`, the optional build each run their own) - fails when a non-`explicitOnly` strict lane is in no stage a workflow executes — a lane the - command removes with `-x` (abbreviations matched as Gradle does) is not covered; a command after - which Gradle runs no task (`--dry-run`, `-v`, `--help`, `--status`, `--stop`, …, bundles such as - `-qm` included), a short-option bundle Gradle rejects (`-mx`) and a command for another build do - not count, nor does one that does not gate for one of three reasons: (1) its failure may not fail - its step (an `||` other than `|| exit `, a pipe without pipefail, an `if` condition, - after `set +e` or an `exit 0` trap, `continue-on-error`, …); (2) it may not run (inside - `if`/`for`/`case` or a function, after a top-level or conditional `exit 0`, `exec` or `set -n`, - under a non-status `if:`, in a workflow only a request starts or a `workflow_call` one no counted - job calls, in a job that `needs` a conditional job, …); (3) the check does not read it although - its failure would fail the step (`|| exit 1`, inside `{ }`, `( )`, `$( )` or `bash -c`, after a - `cd` it cannot follow, a `shell:` other than bash or sh, a runner that may be Windows with its - `pwsh` default, …) — the failure names each command's reason and says to put the stage command - on a line of its own; the build a command runs is its `working-directory`, then the - `cd ` the same shell surely ran before it, joined with `-p` — or a folded workflow - `run:` block splits an option off its command. +## 3. 맡은 일 → 읽을 문서 -Commit policy is `human-only`: agents do not stage, commit, amend, or push implementation changes. +먼저 [docs/work/README.md](docs/work/README.md)를 읽는다. 크기 정하기, 모든 작업의 공통 단계, 커밋 규칙이 거기 있다. 그다음 맡은 일의 playbook 하나를 끝까지 읽는다. -## Proportional workflow +| 맡은 일 | playbook | +| --- | --- | +| 새 업무 기능, 새 capability 모듈 | [docs/work/new-feature.md](docs/work/new-feature.md) → `docs/manual/` | +| 리뷰, 결함 수정, 리팩터링, 성능, 구조·테스트 구조 개선 | [docs/work/improve.md](docs/work/improve.md) | +| 바꾸기 전에 대안 비교와 소유자 결정 | [docs/work/research-design.md](docs/work/research-design.md) | +| 매뉴얼·안내 문서 쓰기 | [docs/work/docs-writing.md](docs/work/docs-writing.md) | +| 게이트 실행, desktop 검증, 릴리스, 파생 서비스 | [docs/work/operate.md](docs/work/operate.md) | +| 큰 일을 나눠 다른 세션에 맡기기 | [docs/work/delegate.md](docs/work/delegate.md) | -- Low risk: work in the owning leaf, follow its nearest guidance, and run the focused check. -- Medium risk: use the relevant Superpowers design, planning, TDD, debugging, and review workflows - in proportion to the affected boundaries. -- High risk: make architecture and behavior decisions explicit, use staged architecture/spec/quality - review, and run architecture-wide verification authorized by the task. +brief(작업 지시문)가 있으면 brief의 범위·크기·완료 기준이 먼저다. playbook은 brief에 없는 공통 절차를 채운다. -Risk comes from change surface and runtime, security, data, or public-contract impact, not file -count. +## 4. 검증 명령과 실행 위치 -## Module families - -`src/config/architecture/modules.json` owns the complete leaf list. Root guidance summarizes -families; the nearest `src/**/CLAUDE.md` owns local rules. No task enforces this any more: -`verifyDocumentedLeafCount` was deleted along with the other documentation-drift parsers. A stated -count that disagrees with the registry is a defect, not a build failure — so do not state one. - -| Family | Responsibility | Stable dependency direction | -| --- | --- | --- | -| `domain-core` | Pure domain model, invariants, events, ports | Java stdlib and registered value-only contracts | -| `application-core` | Commands, use cases, application policies, transaction ports | `domain-core`, `shared-contract` | -| `adapter:inbound:*` | HTTP, gRPC, GraphQL, WebSocket transport boundaries | application/domain/shared contracts | -| `adapter:outbound:persistence-*` | JPA/PostgreSQL and MongoDB persistence adapters | application/domain/shared contracts as registered | -| `adapter:outbound:*` | support, messaging, cache, notification, storage, file, HTTP client, identifier capabilities | application/domain/shared and registered support edge | -| `shared-contract` | Skeleton-wide operational contracts | Java stdlib only | -| `messaging:*` | Vendored messaging platform: a product with its own API, SPI, adapters and composition boundary, not a layer of this application | `messaging:*` only — it depends on no `domain-core`, `application-core`, or `shared-contract` type | -| `sample-portfolio` | Fixture/reference consumer | registered runtime leaves; never a production dependency | -| `app-bootstrap` | Spring Boot entrypoint and composition root | registered runtime leaves | - -The `messaging:*` family is the one entry that is not a Clean Architecture layer, and it is listed so -that the exception is stated rather than inferred from a directory. It is a vendored library — its -own `*-api` leaves are its ports, its broker leaves are its adapters, its starter is its composition -root — and the messaging module review (`docs/reviews/2026-08-14-messaging-module-code-review.md` -MSG-023 §6.2) chose that layout deliberately over folding it into `adapter:outbound:*`. This -application reaches it through the application-owned anti-corruption bridge in -`adapter:outbound:messaging` (MSG-015). The canonical bridge is the only path: the legacy outbox -append port and the legacy Kafka publishing seam were deleted (owner decision 7). - -Never infer an individual leaf's Gradle path, allowed dependency, or test command from this table. -Read its `gradle_path` and `allowed_dependencies` from `src/config/architecture/modules.json`; runtime -composition is established by actual Gradle dependencies/auto-configuration, not a registry -`runtime_memberships` field that does not exist. - -## Layer workflow - -For a full use case, work in this order: - -```text -domain-core - -> application-core - -> adapter:outbound:* (or persistence/identifier) - -> adapter:inbound:* - -> app-bootstrap wiring -``` - -Layer-only work stays inside that registered leaf plus its tests. If a required fix crosses a layer -or writable scope, stop and request context rather than expanding silently. - -## Testing - -- `domain-core`: pure JUnit unit tests. -- `application-core`: use-case tests with hand-rolled fakes; no web or persistence context. -- inbound adapters: focused transport slice/contract tests. -- persistence adapters: mapping/port contract tests; use a real datastore only when vendor semantics - require it. -- other outbound adapters: port contract tests with fake external systems; no real network. -- identifier: pure deterministic unit tests. -- bootstrap/settings: binding, validation, wiring, and architecture tests. - -From `src/`, read the owning leaf's `gradle_path` from -`config/architecture/modules.json` and run `./gradlew :test --console=plain`. -Architecture-wide commands: +- **실행 위치**: Gradle·Docker·테스트·게이트는 이 repo 소유자 환경에서 desktop에서만 돌린다. 절차는 [docs/work/operate.md](docs/work/operate.md) 4.1절이다. +- **leaf 하나**: registry에서 그 leaf의 `gradle_path`를 읽고 `./gradlew :test --console=plain` 또는 `:check`를 돌린다. 기억이나 디렉터리 이름으로 Gradle path를 짐작하지 않는다. +- **저장소 전체 질문**: ```bash ./gradlew architectureCheck --console=plain @@ -139,45 +48,25 @@ Architecture-wide commands: ./gradlew :app-bootstrap:verifyEnvKeys --console=plain ``` -A leaf's `check` covers that leaf only — compile, its tests, Spotless, Checkstyle, Error Prone. -Repository-wide questions have their own names: `architectureCheck` (dependency direction, purity -of domain-core/shared-contract/application-*, Git-carryable sources, ArchUnit), `qualityCheck` -(SpotBugs, FindSecBugs over production code), `testQualityCheck` (the same over every test source -set, against `config/spotbugs/exclude-test.xml`), `configContractCheck` (the environment contract), `integrationCheck` (the -declared strict integration lanes; a lane that needs an input the build was not given is left out -and named), `performanceCheck` (the declared performance lanes; main and nightly). `ci` (pull -request) is leaf checks (API surfaces included, owner decision 20) + architectureCheck + -qualityCheck, and the workflow also runs `verifyStrictLaneStages --dry-run`; `mainCheck` (main branch) is configContractCheck + -qualificationCheck (which includes testQualityCheck) + the sample web contract + the sample full boot (`:sample-portfolio:systemTest`) -+ the public-path snapshot + the transport and messaging qualification lanes + the feature -generator round trip (`verifyFeatureScaffold`) + every leaf's `mainCheck` (document-contract lanes -and any lane the leaf adds). `releaseCheck` is the tag-only checks: release provenance and the -public-path snapshot. +- 공개 경로 검사와 env 키 검사는 그 표면이 바뀌었을 때 돌린다. 전체 `test`·`check`·`ci`는 brief가 시킬 때 돌린다. +- 게이트 목록(`ci`, `mainCheck`, `integrationCheck`, `performanceCheck`, `releaseCheck` 등)과 바꾼 것에 맞는 게이트는 [docs/work/reference/gates.md](docs/work/reference/gates.md)다. +- `docs/work/`나 이 파일을 고쳤으면 `python3 scripts/check-work-docs.py`를 돌린다. -Test-writing rules (behavior-sentence names that assert what they promise, `@DisplayName` in Korean -only when the name cannot say it (owner decision 5), given/when/then comments, one `// when`, one -fake per port in the port owner's testFixtures, fake and adapter sharing one abstract contract test) -are canonical in `AGENTS.md`. +## 5. 코드만 보고는 헷갈리는 곳 -Use public-path and env-key checks only when their surfaces changed. Full `test`, `check` or `ci` -requires the controller's workflow authorization. +- **leaf 목록은 registry 하나다.** 문서는 leaf 개수를 적지 않는다(적힌 수는 leaf가 늘면 틀린다). runtime membership 목록은 없다. 조립 루트가 받을 수 있는 모듈은 registry의 `allowed_dependencies`가 정하고, 방향 게이트가 그 밖의 edge를 막는다. +- **`src/messaging/*`는 Clean Architecture 계층이 아니다.** 자기 API·SPI·adapter·조립 경계를 가진, 들여온(vendored) 메시징 제품이다. `domain-core`·`application-core`·`shared-contract`에 의존하지 않는다. 이 애플리케이션은 `adapter:outbound:messaging`의 bridge로만 닿는다. 이유와 지역 규칙은 `src/messaging/CLAUDE.md`다. +- **`composition:*` leaf는 조립만 한다.** outbox relay, 멱등성 executor, durable operation처럼 bootstrap에서 떼어 낸 조립이다. 각각 `runtimeOnly` 한 줄로 고른다. +- **capability는 한 줄로 켜고 끈다.** 기본 조립은 web inbound, 운영 관측, core들, support·identifier뿐이다. JPA도 `src/app-bootstrap/build.gradle`의 `runtimeOnly` 한 줄로 켠다. 규칙은 `AGENTS.md` 「부가 기능(capability) 모듈 규칙」이다. +- **gRPC 플랫폼 라이브러리는 다른 빌드다.** `src/grpc/*`·`src/grpc-advanced/*`(registry의 `"build": "optional-grpc"`)는 `-p optional-platforms`로 돈다. `adapter:inbound:grpc`는 애플리케이션 adapter라 주 빌드에 있다. +- **`src/sample-portfolio`는 지울 수 있는 샘플이다.** 한 leaf에 모든 계층을 둔 모양이라 배치를 따라 하지 않는다. 새 기능의 예시는 `scripts/new-feature.sh`의 출력이다. +- **저장소 파일을 읽는 테스트는 태그가 있다.** 문서와 대조하는 테스트는 `document-contract`(main 단계 `mainCheck`), 빌드 스크립트·workflow를 읽는 테스트는 `repository-contract`(PR)다. 문서를 고치면 그 문서를 읽는 테스트를 찾는다. +- **커밋 정책은 `human-only`다.** brief가 허용할 때만 자기 브랜치에 커밋·push한다. 자세한 것은 [docs/work/README.md](docs/work/README.md) 4절이다. +- **문서 위치 규칙은 [docs/README.md](docs/README.md)다.** 설계서는 `docs/superpowers/specs/`, 결정 기록은 `docs/adr/`, 리뷰는 `docs/reviews/`, 파생 서비스용 변경 안내는 `docs/upgrade/`다. -## Capability modules +## 6. 소유자 환경 -Optional features (JPA, Redis, Kafka, notification, Mongo, object storage, HTTP client, GraphQL, -WebSocket, gRPC, file server) are modules that turn on when present and disappear when removed. A -service selects them with one `runtimeOnly` line each in `app-bootstrap/build.gradle`; the template's -default composition is the web inbound adapter, observability, the cores, and support/identifier. The -seven completion criteria for a capability module are canonical in `AGENTS.md`. - -## Advisory and reporting - -Use dependency-DAG/topological reasoning and 3–5 materially distinct alternatives when that many -exist; use fewer when the option set is smaller. Judgment findings include falsifiable assumptions -and counterarguments. Deterministic compile, dependency, secret, or failed-test findings use -Rule → Evidence → Fix without manufactured debate. - -Citation verification is profile-based: none for `review-lite`, blocking citations for -`review-standard`, and all material citations for `audit-deep`/`regulated`. Durable reports are -triggered by high risk, at least 3 blocking findings, an architecture decision, explicit user request, -or the regulated profile. Otherwise a concise result is allowed. +- 이 repo 소유자의 기계·세션 도구에 묶인 규칙은 두 곳에만 있다: [docs/work/operate.md](docs/work/operate.md) 4.1절(실행 위치)과 [docs/work/delegate.md](docs/work/delegate.md) 4.3절(세션). 공용 정본은 design-docs `conventions/delegation-loop.md` 11절이다. +- Agent 도구(세션 안의 하위 에이전트)는 이 repo의 `.claude/settings.json`이 막는다. 일을 나눌 때는 delegate.md대로 별도 세션에 맡긴다. +- 작업 사고 순서의 정본은 design-docs `conventions/work-thinking-order.md`, 커밋·PR 형식은 `conventions/commit-and-pr.md`다. +- 보고 말투와 형식은 소유자의 전역 `~/.claude/CLAUDE.md`를 따른다. diff --git a/README.md b/README.md index d114e00a..3d6b69a0 100644 --- a/README.md +++ b/README.md @@ -112,8 +112,9 @@ cd src ## 아키텍처 규칙과 검증 -애플리케이션이 동작하더라도 아래를 어기면 병합하지 않습니다. 8개 HARD-STOP 조건의 정본 로컬 -정책 권위는 [AGENTS.md](AGENTS.md)이며, [CLAUDE.md](CLAUDE.md)는 동기화된 요약입니다. +애플리케이션이 동작하더라도 아래를 어기면 병합하지 않습니다. HARD-STOP 7개 조건의 정본 로컬 +정책 권위는 [AGENTS.md](AGENTS.md)이며, [CLAUDE.md](CLAUDE.md)는 작업을 시작할 때 읽는 지도입니다. +일의 종류별 절차는 [docs/work/](docs/work/README.md)에 있습니다. - `domain-core`는 Spring·JPA·Servlet·HTTP·DB·cloud SDK 타입을 import하지 않습니다. - controller는 repository를 직접 호출하거나 persistence entity를 반환하지 않습니다. diff --git a/docs/README.md b/docs/README.md index 4d745431..eb2e413c 100644 --- a/docs/README.md +++ b/docs/README.md @@ -24,7 +24,8 @@ | --- | --- | | `adr/` | 아키텍처 결정 기록 | | `architecture/` | 공개 API 표면 스냅숏 | -| `manual/` | 개발 매뉴얼: 새 기능을 만드는 순서와 판단 지점, 생성 명령(`scripts/new-feature.sh`) | +| `work/` | 작업 매뉴얼: 이 repo에서 하는 일(새 기능, 개선, 조사·설계, 문서 작성, 운영, 총괄)의 절차서. 루트 `CLAUDE.md` 다음에 읽는다 | +| `manual/` | 개발 매뉴얼: 새 기능을 만드는 순서와 판단 지점, 생성 명령(`scripts/new-feature.sh`). 입구는 `work/new-feature.md` | | `evidence/` | 작업 단계별 증거·체크포인트 | | `registries/` | env 키·에러 코드·메트릭·헤더 등 레지스트리 SSOT | | `reviews/` | 모듈 코드 리뷰 결과 | diff --git a/docs/manual/02-new-feature.md b/docs/manual/02-new-feature.md index 8bdf7814..d4902048 100644 --- a/docs/manual/02-new-feature.md +++ b/docs/manual/02-new-feature.md @@ -12,8 +12,8 @@ ``` 바깥 계층은 안쪽을 알지만 안쪽은 바깥을 모른다. 그래서 안쪽부터 만들면 각 단계가 앞 단계만 보고 -컴파일된다. 한 단계가 다른 leaf나 계층을 고쳐야 하면 거기서 멈추고 설계를 다시 본다(`CLAUDE.md` -Layer workflow). +컴파일된다. 한 단계가 다른 leaf나 계층을 고쳐야 하면 거기서 멈추고 설계를 다시 본다 +([새 기능 playbook](../work/new-feature.md) 「하지 말 것」). ## 0단계 — 배치를 정한다 diff --git a/docs/manual/README.md b/docs/manual/README.md index d5216db7..8ad6ff24 100644 --- a/docs/manual/README.md +++ b/docs/manual/README.md @@ -4,6 +4,9 @@ 무엇을 기준으로 고르는지를 적는다. 규칙의 정본은 따로 있다. 이 매뉴얼은 그 정본을 **가리키고** 작업 순서로 엮을 뿐, 규칙을 다시 쓰지 않는다(아래 「정본 위치」). +입구는 작업 매뉴얼의 [새 기능 playbook](../work/new-feature.md)이다. 일의 크기, 완료 기준, 하지 말 것은 +거기에 있다. 새 기능이 아닌 일(개선, 조사·설계, 문서, 운영)은 [docs/work/](../work/README.md)가 맡는다. + 판단 지점은 모두 같은 틀로 적는다. - **고르는 기준** — 무엇을 보고 고르는가 @@ -37,7 +40,7 @@ | 무엇 | 정본 | | --- | --- | -| 계층 경계·금지 규칙·테스트 작성 규칙 | `AGENTS.md`(요약은 `CLAUDE.md`) | +| 계층 경계·금지 규칙·테스트 작성 규칙 | `AGENTS.md`(작업 지도는 `CLAUDE.md`) | | leaf 목록·허용 의존 | `src/config/architecture/modules.json` | | 이름 규칙(유스케이스·포트·command·query) | `src/application-core/CLAUDE.md` 「Naming convention」. 기계 검사는 `src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/NamingConventionTest.java`와 `ApplicationBoundaryArchitectureTest.java` | | 유스케이스 모양·트랜잭션 모양 | `src/application-core/CLAUDE.md` 「Canonical use case shape」「Allowed transactional shapes」 | diff --git a/docs/work/README.md b/docs/work/README.md new file mode 100644 index 00000000..3926c8a7 --- /dev/null +++ b/docs/work/README.md @@ -0,0 +1,75 @@ +# 작업 매뉴얼 + +이 폴더는 이 repo에서 하는 모든 일의 절차서다. 사람과 AI 세션이 같은 절차를 쓴다. +읽는 순서는 하나다: 루트 `CLAUDE.md`(지도) → 이 README → 맡은 일의 playbook 하나. +규칙의 정본은 `AGENTS.md`와 registry(`src/config/architecture/modules.json`)다. 이 폴더는 규칙을 다시 쓰지 않고, 일하는 순서를 정한다. + +## 1. 어떤 playbook인가 + +| 맡은 일 | playbook | +| --- | --- | +| 새 업무 기능이나 새 capability 모듈을 만든다 | [new-feature.md](new-feature.md) | +| 있는 코드를 리뷰·수정·리팩터링·최적화한다. 구조·테스트 구조를 바꾼다 | [improve.md](improve.md) | +| 바꾸기 전에 대안을 비교하고 소유자 결정을 받는다 | [research-design.md](research-design.md) | +| 매뉴얼·안내 문서를 쓰거나 고친다 | [docs-writing.md](docs-writing.md) | +| 게이트를 돌린다, 릴리스한다, 파생 서비스에 템플릿 변경을 넘긴다 | [operate.md](operate.md) | +| 큰 일을 나눠 다른 세션에 맡긴다 | [delegate.md](delegate.md) | + +둘에 걸리면 이렇게 고른다. 결정이 먼저 필요하면 research-design이다. 동작이 바뀌는 코드가 있으면 new-feature나 improve다. 문서만 바뀌면 docs-writing이다. + +## 2. 크기 정하기 + +- 크기는 작음·중간·큼 셋이다. 정의와 크기별로 할 단계는 design-docs `conventions/work-thinking-order.md` 2절이 정본이다. +- 요약: 작음은 파일 몇 개·새 결정 없음·되돌리기 쉬움, 중간은 leaf(또는 문서 폴더) 하나 안의 여러 파일이나 소유자 없이 정할 작은 결정 하나, 큼은 새 체계·아키텍처·공개 계약·소유자 결정이 필요한 일이다. +- brief(작업 지시문)에 크기가 있으면 그대로 한다. 올릴 수는 있고 내릴 수는 없다. 올리면 이유를 보고에 쓴다. +- brief가 없으면 스스로 정한다. 망설여지면 큰 쪽이다. +- 이 repo에서 "경계"는 registry의 leaf 하나다. 파일 수가 아니라 바뀌는 경계와 영향으로 정한다. +- 아래는 파일이 하나여도 큼이다: 공개 계약(HTTP wire 계약 `docs/web/http-contract.md`, 오류 코드 레지스트리, API surface 스냅숏, env 키), 파생 서비스가 따라 고쳐야 하는 변경, 새 leaf, 보안 정책. +- 큰 일은 만들기 전에 멈추고 소유자 검토를 받는다([research-design.md](research-design.md)). + +## 3. 모든 작업의 공통 단계 + +1. 기준 커밋을 고정한다. `git rev-parse HEAD`를 산출물과 보고에 적는다. +2. 이미 정한 것을 읽는다: [reference/decisions.md](reference/decisions.md), `docs/reviews/`에서 가장 최근 리뷰 README의 결정·남은 것 절. 정한 것은 다시 묻지 않는다. +3. 소유 leaf를 찾는다. registry의 `source_path`로 정하고, 가장 가까운 `src/**/CLAUDE.md`를 읽는다. +4. 스킬을 고른다. 정본은 `AGENTS.md` 「Superpowers Workflow」다. playbook에 작업별 스킬이 있다. +5. 자기 worktree와 자기 브랜치에서 일한다. 다른 세션과 같은 checkout을 쓰지 않는다. +6. 무거운 실행(Gradle, Docker, 테스트, 게이트)은 [operate.md](operate.md) 「실행 위치」대로 한다. +7. 일이 다른 leaf·계층이나 brief 범위를 넘어야 하면 거기서 멈추고 묻는다(5절). +8. 완료를 말하기 전에 검증한다(`superpowers:verification-before-completion`). 돌리지 못한 검증은 못 돌렸다고, 이유와 함께 쓴다(HARD-STOP 6). + +## 4. 커밋 + +- 기본 정책은 `human-only`다(`AGENTS.md`). 에이전트는 stage·commit·amend·push하지 않는다. +- 예외는 하나다. brief가 커밋을 허용하면, 그 작업의 자기 브랜치에만 커밋하고 push한다. +- 그때도 main 병합, 다른 브랜치 push, force push, PR 병합은 하지 않는다. 그것은 소유자가 한다. +- 메시지 형식은 design-docs `conventions/commit-and-pr.md`를 따른다. AI 꼬리말과 자리표시자(`TBD`, `TODO`, 채우지 않은 칸)를 넣지 않는다. + +## 5. 막혔을 때 + +- 소유자만 정할 수 있는 것(공개 계약, 파생 서비스 동작, 보안 정책, 새 leaf, 되돌리기 비싼 선택)은 근거와 권하는 안을 붙여 한 번 묻고, 그 항목만 멈춘다. +- brief를 준 쪽이 있으면 그쪽에 묻는다. 없으면 소유자에게 묻는다. +- 묻는 형식: 항목 · 선택지 · 권하는 안과 이유 · 정할 사람. + +## 6. 보고 + +- 맨 앞에 결과(완료 / 부분 / 못 함)와 브랜치·커밋을 쓴다. +- 그다음 변경, 확인(명령 · 실행 위치 · rc · 로그 경로), 남은 문제를 쓴다. 남은 문제를 숨기지 않는다. +- 숫자(테스트 수, 실패 수, 태스크 이름)는 로그에서 옮긴다. 기억으로 쓰지 않는다. +- 사고 순서 흔적 칸을 둔다(`conventions/work-thinking-order.md` 3절). 다른 세션이 맡긴 일이면 design-docs `conventions/delegation-loop.md` 5절 양식을 쓴다. + +## 7. 필요할 때만 읽는 문서 + +| 문서 | 내용 | +| --- | --- | +| [reference/gates.md](reference/gates.md) | 게이트 목록, 바꾼 것에 맞는 게이트, 결과 기록 형식, 거짓 통과 막기 | +| [reference/review-criteria.md](reference/review-criteria.md) | 결함 정의, 심각도, 증거·통제 수준, 점검 항목, 리뷰 문서 양식 | +| [reference/defect-patterns.md](reference/defect-patterns.md) | 반복해서 나온 결함의 모양과 막는 기준 | +| [reference/decisions.md](reference/decisions.md) | 이미 정한 결정의 색인, 결정을 다시 여는 조건과 기록하는 법 | +| [evidence.md](evidence.md) | 이 매뉴얼의 규칙이 나온 사건과 지난 리뷰 ID | + +## 8. 이 폴더를 고칠 때 + +- 분량 상한: 지도 120줄, 이 README 80줄, playbook 150줄, 진입 경로(지도 + README + playbook 하나) 350줄. `reference/`는 상한이 없다. +- 본문에 지난 리뷰 ID·묶음 이름·번호만 쓴 결정을 넣지 않는다. 내용과 날짜를 쓰고 ID는 [evidence.md](evidence.md)로 옮긴다. +- 고친 뒤 `python3 scripts/check-work-docs.py`가 통과해야 한다. 절차는 [docs-writing.md](docs-writing.md)다. diff --git a/docs/work/delegate.md b/docs/work/delegate.md new file mode 100644 index 00000000..5e8a49f9 --- /dev/null +++ b/docs/work/delegate.md @@ -0,0 +1,116 @@ +# 총괄 — 큰 일을 나눠 다른 세션에 맡긴다 + +총괄 세션이 일을 나누고, brief를 쓰고, 결과를 대조하고, 합치는 절차다. 공용 절차(brief 양식, 보고 양식, 대조, 교훈 정리, 장부, 지표, cold-read 시험)의 정본은 design-docs `conventions/delegation-loop.md`다. 이 playbook은 그것을 다시 쓰지 않고, 이 repo의 일을 나누는 법만 더한다. + +## 1. 언제 쓰나 + +- 일이 커서 여러 세션으로 나눠야 할 때: 전체 리뷰, 영역별 수정 묶음, 리뷰와 수정과 확인 리뷰의 반복, 여러 playbook에 걸친 일. +- 세션 하나가 끝까지 할 수 있는 일이면 이 playbook이 아니다. 그 일의 playbook을 쓴다. +- 맡은 쪽(하위 세션)은 이 playbook이 아니라 brief가 가리킨 playbook을 따른다. + +## 2. 받아야 할 것 + +- 소유자의 목표와 이미 정한 결정. 큰 일이면 소유자가 계획을 검토한 시각. +- 결과가 올라갈 브랜치와 그 최신 커밋(기준 커밋). +- 커밋·push 허용 범위. 하위 세션 브랜치 push는 desktop 검증에 필요하다. main 병합·push는 소유자가 한다. +- 마감과 보고 받을 방법. + +## 3. 크기와 사고 순서 + +- 크기는 총괄이 정해 brief에 적는다. 정의는 design-docs `conventions/work-thinking-order.md` 2절이다. +- 큰 일은 하위 세션이 1~5단계와 대안 비교까지만 하고 멈추게 brief를 쓴다. 소유자 검토 뒤 만들기를 다시 맡긴다. +- 총괄 자신의 선행 사례는 지난 라운드의 나누는 법이다: 가장 최근 리뷰 README의 영역 표와 처리 표, [evidence.md](evidence.md) 2절. +- 스킬: `delegate`(소유자 환경의 실행판)가 있으면 쓴다. 정본과 다르면 정본이 맞다. + +## 4. 절차 + +### 4.1 맡기고 닫는 순서 + +design-docs `conventions/delegation-loop.md` 3절 순서대로 한다: 크기 → 나누기(4.2절) → 기준 커밋 → brief(그 문서 4절 양식, 60줄 이하) → 하위 세션 띄우기 → 보고 대조(그 문서 6절) → 합치기 → 교훈 정리(그 문서 7절) → 장부 한 줄(그 문서 8절) → 소유자 보고. + +이 repo에서 더할 것: + +- brief의 「작업 종류」는 이 repo의 `docs/work/<종류>.md`다. 「이미 아는 것」에는 [reference/decisions.md](reference/decisions.md)의 결정을 **내용으로** 옮긴다. 검증 명령은 [reference/gates.md](reference/gates.md)와 빌드 파일에서 실제 태스크 이름을 확인해 쓴다. +- 검증 칸에는 실행 위치와 증거 위치를 쓴다: desktop worktree, `flock /tmp/claude-gates/heavy.lock`, 로그 `~/<작업 이름>-logs/`([operate.md](operate.md) 4.1절). desktop 검증이 필요하면 7절에 자기 브랜치 push를 허용한다. +- 수정 묶음 brief에는 보고의 「새로 가정하는 것」 칸을 요구한다. 확인 리뷰 brief에는 그 칸부터 보라고 적는다. +- 리뷰 brief에는 쓸 심각도 체계([reference/review-criteria.md](reference/review-criteria.md) 3절)와 "발견마다 이번 수정이 만들었나 / 이전부터"를 요구한다. +- 대조할 때: 보고의 태스크 이름·테스트 수를 desktop 로그에서 grep으로 찾는다. High·Important 이상은 총괄이 코드에서 직접 다시 확인한다. +- 리뷰 결과를 받으면 `python3 scripts/check-review-index.py docs/reviews/<폴더>`로 색인이 빠짐없는지 본다. 수정 묶음은 색인에서 배정한다. +- 교훈을 보낼 곳: 그 playbook의 「자주 하는 실수」, 코드 결함 모양은 [reference/defect-patterns.md](reference/defect-patterns.md), 거짓 통과는 [reference/gates.md](reference/gates.md) 6절, 근거는 [evidence.md](evidence.md). + +### 4.2 나누는 법 — 이 repo + +영역은 가장 최근 리뷰 README의 영역 표를 다시 쓴다. 없으면 아래를 쓴다. 영역 하나에 하위 세션 하나다. + +| 영역 | 경로 | +| --- | --- | +| core·application | `src/domain-core`, `src/application-*`, `src/shared-contract` | +| inbound 전송 | `src/adapter/inbound/*`, `src/grpc/*`·`src/grpc-advanced/*`(optional 빌드) | +| persistence | `src/adapter/outbound/persistence-*`, 마이그레이션 | +| outbound capability | 그 밖의 `src/adapter/outbound/*`, 멱등성 store | +| messaging | `src/messaging/*`, `src/adapter/outbound/messaging` | +| bootstrap·build·CI | `src/app-bootstrap`, `src/composition/*`, `src/build-logic`, `src/build.gradle`, `.github/` | +| 보안(영역을 가로질러) | 인증·인가 체인, 비밀, 공개 경로 | +| 샘플·문서 | `src/sample-portfolio`, `docs/` | + +두 세션이 동시에 만지면 손으로 풀어야 하는 파일이다. 한 세션만 맡기거나, 총괄이 합칠 때 직접 고친다. + +| 파일 | 왜 | +| --- | --- | +| `docs/upgrade/` 안내 문서 | 묶음마다 행을 더해 번호가 겹친다 | +| `docs/reviews/<폴더>/README.md` | 처리 표·결정·게이트 기록은 총괄이 쓴다 | +| `src/config/architecture/modules.json`, `src/settings.gradle` | registry 하나가 모든 leaf를 정한다 | +| `src/gradle/libs.versions.toml`, lockfile | 의존성을 바꾸면 lockfile 전체가 바뀐다 | +| `src/build.gradle`, `src/app-bootstrap/build.gradle` | 라이프사이클과 기본 조립 | +| `docs/registries/*.yaml` | 오류 코드·env 키·지표를 여러 기능이 함께 쓴다 | +| `docs/architecture/*-api-surface.txt`, `docs/security/public-paths-snapshot.txt` | 생성되는 스냅숏이다 | +| `AGENTS.md`, 루트 `CLAUDE.md`, `docs/work/` | 모든 세션이 읽는다 | +| `.github/workflows/*` | 단계 검사가 workflow 전체를 읽는다 | + +나눌 때 지킬 것: + +- 두 묶음이 같은 파일을 건드리지 않게 나눈다. +- 묶음마다 그 시점 최신 기준에서 시작한다. +- 묶음 크기 상한을 지킨다([improve.md](improve.md) 4.4절: 영역 하나, 발견 8건 이하, 확인 리뷰당 추가 1,500줄 이하). +- 전 leaf의 import를 바꾸는 묶음은 나머지를 합친 뒤 혼자 마지막에 한다. +- 같은 결함을 두 영역이 보면 한 묶음에만 배정한다. +- 합칠 때는 하위 브랜치를 모아 [reference/gates.md](reference/gates.md) 3절 묶음을 돌린다. 합치기와 그 게이트도 하위 세션에 맡길 수 있다. + +### 4.3 소유자 환경 + +하위 세션을 띄우는 법, 하위 세션 보고가 총괄에게 전달되는 길이, 공유 노트 폴더, 프론트 repo 일의 경로 같은 소유자 환경 규칙은 design-docs `conventions/delegation-loop.md` 11절 한 곳에 있다. 다시 쓰지 않는다. 이 repo에서 더할 것은 둘이다. + +- Agent 도구(세션 안의 하위 에이전트)는 이 repo의 `.claude/settings.json`이 막는다. 스킬이 하위 에이전트를 띄우라고 하면 그 단계는 그 세션이 직접 하거나, 이 playbook대로 별도 세션에 맡긴다. 막혔다고 Agent로 우회하지 않는다. +- 실행 위치(desktop, 공유 잠금, desktop worktree)는 [operate.md](operate.md) 4.1절이다. + +## 5. 완료 기준 + +- 하위 세션마다 brief가 양식대로이고 자리표시자가 없다. +- 보고를 diff·커밋·로그와 대조했고 불일치를 셌다. +- 합친 트리에서 라운드 끝 게이트가 통과했다(desktop 로그). +- 리뷰·수정 반복이면 [improve.md](improve.md) 4.5절 멈춤 기준이 모두 참이다. +- 교훈 정리와 장부 한 줄을 끝냈다. +- 소유자 보고에 변경 / 확인(명령·결과·커밋) / 남은 문제가 있다. + +## 6. 하지 말 것 + +- 하위 세션의 일을 대신 하지 않는다. 대조에 필요한 읽기와 확인만 직접 한다. +- 보고를 그대로 믿지 않는다. 보고는 E0 증거다. +- 같은 파일을 두 세션에 맡기지 않는다. +- 하위 세션에 main 병합·push, force push, 다른 브랜치 push를 허용하지 않는다. +- brief에 결정 번호만 쓰지 않는다. 내용을 쓴다. + +## 7. 막혔을 때 + +- 소유자만 정할 수 있는 것은 근거와 권하는 안을 붙여 소유자에게 한 번 묻는다. 그 결정에 기대는 묶음만 멈추고 나머지는 계속한다. +- 하위 세션이 묻는 질문에는 답하고, 질문 원문과 "답이 매뉴얼에 있었나"를 적어 둔다. 장부의 질문 수가 된다. + +## 8. 보고 형식 + +소유자에게는 변경 / 확인 / 남은 문제 세 칸으로 쓴다. 하위 세션 보고 양식과 대조표는 design-docs `conventions/delegation-loop.md` 5·6절이다. 소유자가 이미 아는 외부 일(PR 병합, CI runner 켜기)은 남은 문제와 섞지 않는다. + +## 9. 자주 하는 실수 + +- 영역 문서의 ID를 색인에 손으로 옮기다 빠뜨린다. 색인 검사 스크립트를 돌린다. +- 묶음을 너무 크게 만들어 마감 안에 검증 보고가 오지 않는다. 묶음 크기 상한을 지킨다. +- 하위 세션이 적은 태스크 이름을 확인하지 않고 소유자에게 옮긴다. diff --git a/docs/work/docs-writing.md b/docs/work/docs-writing.md new file mode 100644 index 00000000..cd12d358 --- /dev/null +++ b/docs/work/docs-writing.md @@ -0,0 +1,83 @@ +# 문서 작성 — 매뉴얼과 안내 문서를 쓰고 고친다 + +읽은 사람이 묻지 않고 그대로 일할 수 있는 문서를 쓰는 절차다. 매뉴얼은 시험하기 전까지 초안이다. + +## 1. 언제 쓰나 + +- `docs/work/`, `docs/manual/`, 루트·leaf `CLAUDE.md`, 모듈 README, runbook, 안내 문서를 쓰거나 고칠 때. +- 이것은 아니다. + - 리뷰 문서 → [improve.md](improve.md)(리뷰 양식은 [reference/review-criteria.md](reference/review-criteria.md) 10절) + - 설계서·ADR → [research-design.md](research-design.md) + - 코드 동작이 바뀌어 문서를 따라 고치는 일 → 그 코드 변경의 playbook(같은 변경에서 고친다) + +## 2. 받아야 할 것 + +- 독자: 누가, 무엇을 하려고 읽나. 사람인가, 이력 없는 세션인가, 파생 서비스 개발자인가. +- 그 문서가 가리킬 정본: 규칙이 이미 어디에 있나. +- 위치와 분량 상한. +- 시험 방법: cold-read 시험을 누가 하나(보통 맡긴 쪽이 따로 한다). + +## 3. 크기와 사고 순서 + +- 오타·깨진 링크·한 문장 정정은 작음이다: 목적 한 줄, 대상 확인, 검증. +- 새 안내 문서나 playbook 하나는 중간이다. +- 문서 체계(매뉴얼 구성, 진입 경로)를 바꾸는 일은 큼이다. 소유자 검토가 먼저다. +- 선행 사례: 같은 독자를 둔 이 repo의 문서(`docs/manual/`, `docs/work/`)와, 그 문서를 읽고 일한 기록(보고, cold-read 시험 기록). +- 스킬: `technical-writing-best-practices`, `documentation-and-adrs`. 사람이 터미널에서 따라 하는 절차서면 `writing-practitioner-guides`. + +## 4. 절차 + +1. 독자와 목적을 한 문장으로 쓴다: "<누가> 이 문서만 읽고 <무엇을> 끝낸다". +2. 정본을 찾는다. 규칙이 이미 `AGENTS.md`, registry, leaf `CLAUDE.md`, `docs/web/http-contract.md`, `docs/registries/`에 있으면 다시 쓰지 않고 가리킨다. 정본과 다르면 정본이 맞다. +3. 위치를 정한다. 문서 위치 규칙은 `docs/README.md`다. 여러 repo나 소유자 운영에 걸친 내용은 이 repo가 아니라 design-docs에 둔다. +4. 결론을 먼저 쓴다. 한 문장에 개념 하나, 처음 나온 용어는 그 자리에서 한 줄로 푼다. 흐름이 있으면 화살표 도식을 먼저 둔다. 표는 둘 이상을 비교할 때만 쓴다. +5. 절차는 한 줄에 한 단계, 동사로 시작한다. 명령은 실제로 있는 것만 쓴다. 태스크 이름은 `src/build.gradle`이나 leaf `build.gradle`에서, 경로는 `ls`로 확인한다. +6. 지난 일을 근거로 쓸 때는 날짜, 무엇이 일어났나, 숫자를 한 줄로 쓴다. 리뷰 ID·묶음 이름·번호만 쓴 결정은 매뉴얼 본문에 쓰지 않는다. 걷어낸 ID 중 근거로 남길 것은 어느 문서에서 왔든 [evidence.md](evidence.md)에 원래 문서·문장과 함께 모은다. +7. 링크: repo 안 문서는 상대 링크로 쓴다. repo 밖 문서(design-docs 등)와 `file:line`은 링크가 아니라 코드 표기로 쓴다. 링크 검사(lychee)가 따라가지 못하기 때문이다. +8. 숫자를 복제하지 않는다. leaf 개수, 테스트 수처럼 코드가 정하는 값은 쓰는 순간 낡는다. 정본을 가리킨다. +9. 그 문서를 읽는 테스트가 있는지 찾는다: `grep -rn '<파일 이름>' src --include=*.java`. 있으면 그 테스트가 기대하는 문장을 지키고, 그 lane을 desktop에서 돌린다([reference/gates.md](reference/gates.md) 2절). +10. `docs/work/`나 루트 `CLAUDE.md`를 바꿨으면 `python3 scripts/check-work-docs.py`를 돌린다. 분량 상한, 본문 이력 ID 0, playbook 뼈대, 상대 링크를 본다. +11. 리뷰 폴더 README를 만들거나 고쳤으면 `python3 scripts/check-review-index.py docs/reviews/<폴더>`를 돌린다. +12. 다른 문서는 같은 스크립트의 모드로 본다: 상대 링크는 `--links <파일 또는 폴더>`(PR에서는 lychee가 다시 본다), 이력 ID는 `--history <파일 또는 폴더>`. +13. 매뉴얼·playbook·진입 경로를 새로 만들거나 크게 바꿨으면 cold-read 시험을 한다. 정본은 design-docs `conventions/delegation-loop.md` 10절이다. 혼자 하는 일이면 최소한 자가 점검을 한다: 지도부터 읽어 그 문서만으로 실제 일 하나의 brief를 써 보고, 막힌 곳을 고친다. + +**playbook을 새로 만들 때의 뼈대** (모든 playbook이 같은 제목을 쓴다. 검사 스크립트가 본다): + +`1. 언제 쓰나` · `2. 받아야 할 것` · `3. 크기와 사고 순서` · `4. 절차` · `5. 완료 기준` · `6. 하지 말 것` · `7. 막혔을 때` · `8. 보고 형식` · `9. 자주 하는 실수`(10줄 이하) + +## 5. 완료 기준 + +- 독자 한 문장이 있고, 문서가 그 독자의 일을 처음부터 끝까지 다룬다. +- 문서의 명령·태스크 이름·경로가 기준 커밋에 실제로 있다. +- 정본을 복사한 문장이 없다. 가리키는 줄만 있다. +- `docs/work/`·루트 `CLAUDE.md`를 바꿨으면 `scripts/check-work-docs.py`가 rc=0이다. +- 그 문서를 읽는 document-contract lane이 있으면 rc=0이다(desktop 로그). +- 매뉴얼을 새로 만들었거나 진입 경로를 바꿨으면 cold-read 시험이나 자가 점검 결과가 보고에 있다. + +## 6. 하지 말 것 + +- 정본의 규칙을 문서에 다시 쓰지 않는다. 갈라진 복사본이 된다. +- 계획서를 나중에 고치지 않는다. 계획의 기록이 아니라 결과를 계획처럼 보이게 만든 글이 된다(`docs/README.md`). +- 리뷰 영역 문서를 리뷰 뒤에 고치지 않는다. 처리 결과는 리뷰 README에 쓴다. +- 소유자 환경 규칙(실행 위치, 세션 도구)을 여러 곳에 쓰지 않는다. [operate.md](operate.md) 「실행 위치」와 [delegate.md](delegate.md) 「소유자 환경」에만 둔다. +- 분량 상한을 넘기지 않는다. 넘으면 같은 문서에서 한 줄을 빼거나 `reference/`로 내린다. + +## 7. 막혔을 때 + +- 정본끼리 다른 말을 하면 어느 쪽이 맞는지 정하지 않는다. 두 위치와 차이를 적어 묻는다. +- 소유자 파일(전역 `~/.claude/CLAUDE.md`, 사용자 설정·스킬, design-docs)을 고쳐야 하면 승인을 받고 고친다. + +## 8. 보고 형식 + +[README](README.md) 6절에 더해 적는다. + +- 바꾼 문서와 줄 수, 분량 상한 대비. +- 검사 결과: `check-work-docs.py`, `check-review-index.py`, 링크 검사, document-contract lane의 rc와 로그 경로. +- cold-read 시험이나 자가 점검: 써 본 brief, 막힌 곳, 고친 것. +- 정본과 다른 곳을 찾았으면 그 위치. + +## 9. 자주 하는 실수 + +- 지난 리뷰 ID로 이유를 대신한다. 내용과 날짜를 쓴다. +- 저장소 밖 문서를 상대 링크로 써서 링크 검사가 실패한다. 코드 표기로 쓴다. +- 없는 태스크 이름이나 옛 경로를 쓴다. 쓰기 전에 빌드 파일과 `ls`로 확인한다. diff --git a/docs/work/evidence.md b/docs/work/evidence.md new file mode 100644 index 00000000..2c2fe750 --- /dev/null +++ b/docs/work/evidence.md @@ -0,0 +1,150 @@ +# 근거와 이력 + +`docs/work/` 본문은 지난 리뷰를 모르는 사람도 읽을 수 있게 썼다. 그래서 규칙이 나온 사건과 지난 리뷰 ID는 본문에 넣지 않고 여기에 모았다. 본문을 따르는 데 이 문서는 필요 없다. 규칙의 이유를 확인하거나 규칙을 바꾸려 할 때 읽는다. + +표기: `1101/05-01`은 `docs/reviews/2026-11-01-maturity-review/`의 발견 05-01이다. `1103/RR6-01-05`는 `docs/reviews/2026-11-03-rereview/`의 발견이다(`RR-`는 1차 재리뷰, `RR2-`~`RR6-`는 round2~round6). `1101` README, `1103` README는 각 폴더의 `README.md`다. 「결정 N」은 `docs/reviews/2026-09-25-review-followup-status.md` 「소유자 결정」의 N번이다. + +## 1. 이 매뉴얼이 나온 곳 + +- 조사와 설계: design-docs `delegation-loop/01-research.md`(1~5단계), `delegation-loop/02-design.md`(6단계, 4·5·6·7·10절). 2026-11-06 소유자가 결정 D1~D14를 모두 권하는 안대로 승인했다. +- 공통 정본: design-docs `conventions/work-thinking-order.md`(작업 사고 순서), `conventions/delegation-loop.md`(위임 루프 운영). +- 재료: 옛 개선 매뉴얼 브랜치 `claude/improvement-manual-6ae516`(커밋 `3b66358e`, `319cff91`, `06477350`, 2026-11-05). 병합하지 않고 설계 10절 표대로 옮겼다(결정 D12). +- 옛 매뉴얼을 버린 이유(2026-11-06 소유자 판정): 조사 없이 만들었다, 범위가 리뷰·수정뿐이다, 본문 159줄에 지난 리뷰 ID가 있다, 진입 분량이 717줄이다, 시험한 적이 없다. + +옛 매뉴얼에서 옮긴 곳: + +| 옛 위치 | 새 위치 | +| --- | --- | +| README 「정본 표」, 적용 범위 | `docs/work/README.md` 1·7절, 각 playbook | +| 결정 M-5(저장소 밖 문서는 코드 표기), M-6(소유자 환경 규칙은 한 절에만) | `docs-writing.md` 4절, `operate.md` 4.1절 | +| 결정 M-3(심각도 두 체계) | `reference/review-criteria.md` 3절 | +| 결정 M-4(결정 표는 색인) | `reference/decisions.md` 머리말 | +| 결정 M-7(커밋 정책은 두고 예외만) | `docs/work/README.md` 4절, `AGENTS.md` 커밋 문장 | +| 결정 M-8(개선 제안도 닫는다) | `reference/review-criteria.md` 1절 | +| 결정 M-9(분업과 "Minor도 고친다"의 저장소 안 정본) | `improve.md` 4.5절, `delegate.md` | +| 결정 M-1(위치 `docs/improvement/`), M-2(프론트와 장 번호 맞추기) | 버림. 위치는 `docs/work/`, 두 repo는 장 번호 대신 같은 playbook 파일 이름을 쓴다 | +| 01장 판정표, 0절 공통 단계, 1~6절 | `docs/work/README.md` 3절, `improve.md` | +| 02장 | `reference/review-criteria.md`(지난 예는 이 문서 5절) | +| 03장 | `reference/review-criteria.md` 9절 | +| 04장 P1~P11 | `reference/defect-patterns.md` 「막는 기준」 | +| 05장 | `reference/review-criteria.md` 7절, `improve.md` 4.2·4.3절 | +| 06장 | `reference/review-criteria.md` 8절, `reference/gates.md` 5절, 기준선은 이 문서 6절 | +| 07장 | `reference/gates.md`, `operate.md` | +| 08장 | `reference/decisions.md` | +| 09장 | `delegate.md`, `improve.md` 4.4·4.5절, design-docs `conventions/delegation-loop.md` | +| 부록 결함 패턴 | `reference/defect-patterns.md` + 이 문서 4절 | + +## 2. 규칙과 사건 + +| 규칙(본문 위치) | 사건 | 근거 | +| --- | --- | --- | +| 무거운 실행은 desktop에서, 공유 잠금으로 (`operate.md` 4.1) | 2026-11-05 하위 세션 넷이 노트북에서 Gradle을 돌려 노트북 부하가 22까지 올랐다 | `1103` README 17.1절, design-docs `delegation-loop/01-research.md` 4.2절 | +| 진입 분량 상한, 본문 이력 ID 금지 (`docs/work/README.md` 8절) | 옛 개선 매뉴얼은 진입 717줄, 이력 ID가 든 본문 159줄 | `01-research.md` 4.1절 | +| 색인은 기계로 대조한다 (`improve.md` 4.1) | 원래 리뷰 색인이 119건이었다. 06 영역 문서의 `NN-10`~`NN-14` 5건이 색인과 모든 수정 묶음에서 빠졌다. 실제는 124건 | `1101` README 12절 정정, `1103` README 1절, `1103/RR-05-10` | +| 「새로 가정하는 것」 칸, 수정 묶음 크기 상한 (`improve.md` 4.4, 8절) | round6 발견 25건 중 17건(68%)을 직전 수정 커밋이 만들었다. 짝 프론트 1106 리뷰도 25건 중 16건(64%) | `01-research.md` 4.3절, design-docs `delegation-loop/02-design.md` 4.3절 | +| 보고한 태스크가 로그에 있는지 확인 (`improve.md` 9절, `gates.md` 4절) | 묶음 보고가 없는 태스크 `:adapter:outbound:persistence-jpa:documentContractTest`를 적었다 | `1103` README 17.2절 | +| 성능 lane은 workflow와 같은 단언 속성으로 (`gates.md` 5절) | r10 desktop 게이트의 `performanceCheck`가 `-Pperformance.assertions.enabled=true` 없이 돌아, httpclient 시간 단언 없이 통과했다 | desktop `~/r10-logs/gates.sh`, 공유 노트 「백엔드 개선 매뉴얼 인계」 | +| 묶음을 너무 크게 만들지 않는다 (`delegate.md` 4.2) | 알림·파일 서버를 한 묶음(r2-05a)으로 묶었다가 마감 안에 검증 보고가 오지 않아 합치지 못했다. 다음 라운드(r3-a)에 다시 올려 합쳤다 | `1101` README 14.3절, 16절 | +| 두 묶음이 같은 파일을 건드리지 않게 (`delegate.md` 4.2) | 2라운드 묶음 r2-06이 10개 파일 충돌로 처음부터 다시 작업했다 | `1101` README 14.1절 | +| 전 leaf import를 바꾸는 묶음은 마지막에 혼자 (`improve.md` 6절, `delegate.md` 4.2) | r3-G | `1101` README 15.1절 | +| 묶음마다 그 시점 최신 기준에서 시작 (`delegate.md` 4.2) | 3라운드가 2라운드보다 충돌이 적었다 | `1101` README 16.1절 | +| 합친 트리는 따로 검증 (`improve.md` 4.4, `gates.md` 3절) | 두 묶음의 수정이 한 트리에서 처음 만나 `BC_IMPOSSIBLE_INSTANCEOF`가 생겼다. 최종 게이트에서 드러난 2건 | `1101` README 16.1절, `1103` README 6.1절 | +| 캐시로 통과한 것은 그렇게 적는다 (`gates.md` 4절) | `ci`가 434초에서 51초로 준 것은 캐시 재사용이었다 | `1101` README 16.2절 | +| 같은 결함은 한 묶음에만 (`delegate.md` 4.2) | 같은 runbook 문장을 두 리뷰가 적어 한 번 고쳤다(`1103/RR6-01-07`, `1103/RR6-02-03`) | `1103` README 17절 | +| RED가 머신에 따라 통과하지 않게 (`improve.md` 7절) | watchdog RED 테스트가 공용 풀 병렬도 1인 머신에서 옛 코드도 통과시켰다 | `1103/RR4-03-01`, `1103` README 16절 r9-b | +| 실 vendor 결함은 실 vendor에서 RED (`improve.md` 4.2) | 새 실 PostgreSQL 테스트 3개의 수정 전 실패를 실 PostgreSQL로 확인하지 않았다 | `1101` README 14절 r2-04 | +| Agent 도구를 쓰지 않는다 (`delegate.md` 4.3) | 하위 세션 시작이 막히자 Agent 하위 에이전트로 우회했다. 지난 라운드는 사용량 한도 때문에도 하위 에이전트 없이 진행했다 | `01-research.md` 4.2절, `1101` README 16절, `1103` README 6절 | +| 예전 멈춤 기준을 거둠 (`improve.md` 4.5) | 2026-11-05 소유자 지시 "보고할 때 남은 문제가 없어야 한다". "새 Important 0이면 멈춤"(9.1절), "Minor는 기록만"(11.1절)을 거뒀다 | `1103` README 16절 | +| 종료 조건은 repo마다 (`improve.md` 4.5) | 2026-11-05 소유자 원문 "각자 유지" | 2026-11-05 총괄 세션 전달 | + +## 3. 수정 묶음 크기 (`improve.md` 4.4) + +추가 줄은 `git show --shortstat`의 insertions다(테스트·문서 포함). + +| 수정 커밋 | 고친 것 | 추가 줄 | 다음 확인 리뷰 | 그 리뷰의 발견 | +| --- | --- | --- | --- | --- | +| `01a8a2a70..5786126c`(커밋 3개) | 원래 리뷰 발견 | +60,167 | 1차 재리뷰 | Important 27, Minor 41 | +| `bbe944bd` | 1차 재리뷰 발견 + 색인에서 빠졌던 5건 | +13,479 | round2 | Important 7, Minor 22 | +| `1885bf8d` | 2차 재리뷰 결함 29건 | +5,495 | round3 | Important 0, Minor 19 | +| `f40c03c6` | Minor 19건(영역 묶음 4개) | +1,877 | round4 | Important 0, Minor 7 | +| `70fb80bf` | 소유자가 다시 정한 기본값 3가지 | +906 | round5 | Important 0, Minor 9 | +| `45d2a478` | 기록만 했던 결함 전부(영역 묶음 4개) | +5,420 | round6 | Important 2, Minor 23(17건은 이 커밋이 만듦) | +| `6e992970` | round6 결함 25건(영역 묶음 4개) | +5,143 | 아직 없음 | — | + +읽는 법: 추가 2,000줄 아래 두 번은 다음 발견이 7·9건, 5,000줄 위 네 번은 19·25·29·68건이었다. 상한(묶음 8건, 확인 리뷰당 1,500줄)은 이 표에서 정한 판단 값이다. 위임 루프 지표(라운드당 새 결함, 수정이 만든 결함 비율)로 다시 맞춘다. + +## 4. 결함 패턴의 근거 (`reference/defect-patterns.md`) + +| 패턴 | 근거 | +| --- | --- | +| A1 갈라진 복사본 | `1101/01-03`, `1101/01-07`, `1101/04-06`, `1101/05-09`, `1101/07-06`, `1101/01-11`, `1103/RR-01-14`, `1101` README 16.3절(템플릿 패키지 목록 두 곳), `1103` README 16절 r9-c(버전 정규식 사본) | +| A2 문서와 코드 불일치 | `1101/02-01`, `1101/07-11`, `1101/03-04`, `1101/06-11`, `1103/RR-01-03`, `1103/RR-01-11`, `1103/RR5-01-01`, `1103/RR6-02-05`, `1103/RR6-03-05`, `1103/RR6-04-05` | +| A3 선언과 실행이 떨어져 있다 | `1101/05-15`, `1101/03-11`, `1101/02-03`, `1101/07-06`, `1103/RR-06-01`, `1103/RR2-04-03`, `1103` README 6.1절(`redis.capability.*` 6개) | +| A4 결과 불명을 확실함으로 | `1101/05-01`, `1101/04-01`, `1101/06-01`, `1101/05-17`, `1101/05-11`, `1103/RR-02-03`, `1103/RR-01-11`, `1101` README 4절 원인 1 | +| A5 중복·경쟁을 코드 순서로 | `1101/09-02`, `1101/04-08`, `1101/04-02`, `1101/03-10`, `1101/04-13`, `1103/RR-03-01`, `1103/RR-02-04` | +| A6 주장하는 것을 보지 않는 테스트 | `1101/05-08`, `1101/02-02`, `1101/01-05`, `1103` README 14절(`CountDownLatch` 7건), `1103/RR4-03-01`, `1103/RR6-01-08`, `1103/RR6-02-02` | +| A7 거짓 통과 게이트 | `1101/08-01`, `1101/04-04`, `1101/03-12`, `1103/RR-06-02`, `1103/RR-06-03`, `1103/RR-04-05`, `1103` README 14절(테스트 SpotBugs 53개), `1103/RR3-04-02`, `1103/RR6-04-01`, r10 desktop `performanceCheck`(2절) | +| A8 로그로 새는 입력값·원인 | `1103/RR6-01-05`, `1103/RR6-01-06`, `1103` README 16절 r9-a, `1101/02-11`, `1101/01-04` | +| A9 이름만 보는 허용·거부 | `1103/RR-07-02`, `1103/RR2-04-02`, `1103/RR2-04-01`, `1101/07-14` | +| A10 글로만 있는 규칙 | `1103/RR-01-02`, `1101/04-03`, `1101/05-16` | +| A11 샘플·fixture가 운영과 다르게 조립 | `1101/07-03`, `1101/09-03`, `1101/09-08`, `1101/07-04`, `1101/01-02`, `1101/07-09` | +| A12 수정이 새 결함을 만든다 | `1103` README 1절(Important 27), 9절, `1103/RR6-01-01`(회귀), `1101` README 16.1절, `1103` README 6.1절, round6 68%(2절) | +| A13 합치는 과정의 누락 | `1101` README 12절 정정, `1101` README 14.1절(충돌 처리 목록) | +| A14 타이밍에 기댄 약속 | `1103` README 16.1절(`ClientRuntimeRegistry.close`), `1103/RR3-03-01`, `1101/05-06` | +| A15 사라지는 외부 공급원 | `1101/05-09`, `1101/08-04` | +| A16 상한 없는 자원 | `1101/03-06`, `1101/03-09`, `1101/04-10`, `1101/02-09`, `1101/04-12` | + +## 5. 리뷰 기준의 예 (`reference/review-criteria.md`) + +**결함의 모양(1절)**: 이름과 다른 동작 `1101/05-03`(`ONLY_IF_SOURCE_REVISION_NEWER`가 조건 없이 덮어씀), HARD-STOP 위반 `1101/07-08`(기본 조립 루트가 선택 capability를 앎), 갈라진 복사본 `1101/01-03`(`TenantId` 3벌)·`1101/04-06`(SQLState 표 2벌), 막지 못하는 게이트 `1101/05-08`(소유자 검사를 지워도 442개 통과)·`1101/08-01`(어떤 workflow도 돌리지 않는 strict lane 14개), 틀린 조치를 시키는 문서 `1103/RR-05-01`(DEAD 재발행 SQL을 따르면 다시 DEAD), 기본값 뒤에 숨은 위험 `1101/02-03`(JWT audience가 비면 검증을 건너뜀). + +**성격(2절)**: 구조적 위험 `1101` README 6절, 미검증 `1103` README 10.3절(CI runner가 꺼져 있다). + +**심각도(3절)**: 전체 리뷰 체계는 `1101` README 12절. High 예 `1101/05-01`, `1101/04-02`, `1101/02-03`. Medium 예 `1101/04-06`, `1101/04-05`. Low 예 `1101/07-11`. 확인 리뷰 체계는 `1103` README 2절 이후 모든 round, Important 기준은 `1103` README 11절, Minor 예는 `1103/round4/review.md`·`round6/`. "이번 커밋 / 이전부터"는 `1103/round6/04-build-logic.md` 「결론」. Minor도 고친다는 규칙은 `1103` README 16절, High·Important 재확인은 `1101` README 2절. + +**증거 수준(4절)**: 이전 결과를 쓰지 않은 예 `1101/09-performance-measurement.md` 1절, 섞인 증거 수준 표기 예 `1103/round6/03-persistence.md` RR6-03-01. + +**통제 수준(5절)**: M0 예 2026-11-01 시점 JPA 양방향 연관관계 금지(`1101/04-03`), M1 예 `@SystemInvoked`를 bean으로 등록하지 말라는 주석(`1103/RR-01-02`), M4 예 DB 유일 제약(`1101/09-02` 수정 뒤). + +**28개 관점(6절)의 지난 예**: 1 `1101/05-03` · 2 `1101/07-08`, `1101/08-05` · 3 `1101/01-07` · 4 `1101/01-01`, `1101/07-09` · 5 `1101/02-03`, `1103/RR-07-02` · 6 `1101/04-01`, `1101/06-01`, `1101/05-01` · 7 `1103/RR-05-01`, `1103` README 6.1절 · 8 `1103` README 16절 r9-a, `1101/01-04` · 9 `1101/04-06`, `1101/07-11` · 10 `1101/05-08`, `1101/02-02` · 11 `1101/09-02`, `1103/RR-02-09` · 12 `1101/04-02`, `1101/03-10` · 13 `1101/03-06`, `1101/03-09` · 14 `1101/09-01`, `1101/09-02` · 15 `1101/02-03`, `1101/07-03`, `1103/RR6-01-05` · 16 `1101/05-09`, `1101/09-09` · 17 `1101/02-01`, `1101/02-02` · 18 `1101/07-04`, `1101/06-02` · 19 `1101/05-15`, `1101/07-06` · 20 `1103/RR-01-01`, `1103/RR-01-03` · 21 `1101/08-01`, `1103/RR-06-02`, `1103` README 14절 · 22 `1101/04-13` · 23 `1101/01-03`, `1101/01-12` · 24 `1101/05-21` · 25 `1101/01-10` · 26 `1101/04-16` · 27 `1101/07-08`, `1101/05-19` · 28 `1101/03-10`, `1101/06-03`. + +**시나리오(6절)의 지난 추적**: `1101/01-core-and-feature-pattern.md` 4.1·4.2·4.4절, `1101/09-performance-measurement.md` 5.1~5.3절, `1101/05-05`·`05-06`·`05-01`, `1101/04-01`·`04-05`, `1103/RR-03-03`, `1101/06-01`, `1103/RR-03-02`, `1103/RR-02-09`·`RR-02-10`, `1101/04-02`·`03-10`, `1101/05-08`, `1101/03-01`·`02-09`, `1101/06-02`·`07-07`, `1101/08-build-ci-test.md` 4절. + +**테스트 점검표(7절)**: `1103/RR6-01-08`, `1101/02-02`, `1101/05-08`, `1103` README 14절, `1103/RR6-02-02`, `1103/RR6-01-03`, `1103` README 17절 r10-01, `1103` README 16.1절. fake 예 `1103/RR-01-04`, `1103` README 17절 r10-02(손 사본 20건 삭제, skip 17 → 0). + +**리뷰 문서 양식(10절)**: 전체 리뷰 README는 `1101` README 절 순서, 영역 문서는 `1101/01-core-and-feature-pattern.md`, 확인 리뷰 문서는 `1103/round6/*.md`, 확인 리뷰 발견 필드는 `1103/round6/03-persistence.md` RR6-03-01, 전체 리뷰 발견 필드는 `1101/08-build-ci-test.md` 08-01. + +## 6. 성능 기준선 (`improve.md` 4.3) + +잰 커밋과 함께만 쓴다. 현재 HEAD에서 다시 잰 값이 아니다. 성능 작업을 시작하면 현재 커밋에서 다시 재고 이 표와 비교한다. + +| 측정 | 값 | 커밋·출처 | +| --- | --- | --- | +| 기본 조합 bootJar / 기동 중앙값 / 빈 수 | 41.4 MB / 3.44 s / 407 | `01a8a2a70`, `1101/09-performance-measurement.md` 3.1절 | +| 샘플 bootJar / 기동 중앙값 / 빈 수 | 99.0 MB / 8.05 s / 603 | 같음 | +| 필터 체인만 지나는 요청 | 27,130 rps, p50 0.51 ms | 같은 문서 3.4절 (d) | +| 샘플 단건 조회 | 5,521 rps, p50 2.70 ms, SQL 7개 | 같은 문서 3.2·3.3절 | +| 샘플 목록 20건 | 829 rps, p50 15.54 ms, SQL 46개 | 같음(수정 전) | +| 샘플 목록 20건(수정 뒤) | SQL 46 → 6, 765 → 2,528 rps | `1101` README 14절 r2-09(묶음 보고 — E0, 다시 재지 않음) | +| 관측 기능 비용 | 처리량 약 3% | 같은 문서 3.4절 (b) | +| 가상 스레드 | 처리량 차이 없음(병목은 커넥션 10개와 DB 왕복) | 같은 문서 3.3절 | +| 설정만 바꾼 실험 | `hibernate.default_batch_fetch_size=100`만으로 목록 처리량 2.9배 | 같은 문서 3.4절 | +| 게이트 시간(desktop, 12코어·31GB) | `ci`+`verifyDependencyLocks` 5분 42초, `mainCheck` 8분 8초, `integrationCheck` 17분 10초 | `2c692554`, `1103` README 17.2절 | + +측정 스크립트(`run-app.sh`, `Load.java`, `sqlcount.sh`)는 그때 scratchpad에 두었고 repo에는 없다. 다시 재려면 `1101/09-performance-measurement.md` 「측정 명령 (다시 돌리는 법)」으로 다시 만든다. + +## 7. 리뷰 색인 대조 결과 (2026-11-06) + +`scripts/check-review-index.py`를 지난 리뷰 폴더 두 곳에 돌린 결과다(기준 커밋 `3d73b6f1`). + +| 폴더 | 명령 | 영역 문서 발견 | 색인에 있음 | 없음 | rc | +| --- | --- | --- | --- | --- | --- | +| `docs/reviews/2026-11-01-maturity-review/` | `--index-heading "12. 발견 색인"` | 124 | 124 | 0 | 0 | +| `docs/reviews/2026-11-03-rereview/` | README 전체 | 157 | 135 | 22 | 1 | + +- 2026-11-01 폴더: 지금은 모두 있다. 같은 검사를 사고 시점 커밋 `34565130`의 폴더에 돌리면 `NN-10`~`NN-14` 5건을 "자리표시자 영역"으로 잡고 rc=1로 실패한다. 이 검사가 그 사고를 막았을 것이다. +- 2026-11-03 폴더의 22건은 처리되지 않은 발견이 아니라 README가 ID로 적지 않은 발견이다. + - `RR-05-10`(색인 누락 5건 자체에 대한 발견)은 README 1절 정정과 6.1절이 내용으로 다룬다. + - `RR-07-05`(CSRF 제외 규칙의 이유)는 README 6절 r4-f 행이 내용으로 다룬다. + - 나머지 20건은 round6 Minor다(`RR6-01-02`~`06`·`08`·`09`, `RR6-02-02`·`04`·`05`, `RR6-03-02`~`05`, `RR6-04-01`~`06`). README 17절은 영역별 건수만 적었고, r10 묶음이 영역 단위로 고쳤다. +- 이 검사는 "색인에 이름이 있나"만 본다. 고쳤는지는 처리 표와 확인 리뷰가 본다. 앞으로의 리뷰 README는 모든 ID를 이름으로 적는다(`improve.md` 4.1절 7단계). diff --git a/docs/work/improve.md b/docs/work/improve.md new file mode 100644 index 00000000..954ea146 --- /dev/null +++ b/docs/work/improve.md @@ -0,0 +1,132 @@ +# 개선 — 리뷰, 결함 수정, 리팩터링, 성능, 구조, 테스트 구조 + +이미 있는 코드를 평가하거나 고치는 일의 절차다. 핵심은 하나다: 리뷰 → 수정 → 확인 리뷰를 발견이 0이 될 때까지 돈다. + +## 1. 언제 쓰나 + +| 지금 상태 | 작업 | +| --- | --- | +| 무엇이 틀렸는지 아직 모른다 | 리뷰 | +| 계약(이름·Javadoc·문서·레지스트리·테스트 이름이 약속한 것)과 다른 동작이 확인됐다 | 결함 수정 | +| 동작은 맞는데 구조 비용이 크다 | 리팩터링 | +| 숫자로 잰 비용이 크다 | 성능 최적화 | +| leaf·패키지·허용 의존이 바뀐다 | 구조 변경 | +| 테스트가 이름이 말한 것을 증명하지 못한다 | 테스트 구조 개선 | + +- 새 업무 기능은 [new-feature.md](new-feature.md)다. +- 고치기 전에 소유자 결정이 필요하면 [research-design.md](research-design.md)가 먼저다. + +## 2. 받아야 할 것 + +- 리뷰: 범위(전체 / 영역 / 커밋 범위 `..`와 pathspec), 쓸 심각도 체계(전체 리뷰용인지 확인 리뷰용인지). +- 수정: 고칠 발견 목록(ID, 위치)과 리뷰 문서 경로. +- 공통: 기준 커밋, 브랜치, 커밋 허용 여부, 검증할 게이트. +- 그 발견에 필요한 소유자 결정이 났는지. [reference/decisions.md](reference/decisions.md)에 없고 brief에도 없으면 그 발견만 멈추고 묻는다. + +## 3. 크기와 사고 순서 + +- 보통 중간이다: 확인 리뷰 하나, 수정 묶음 하나. +- 큼: 전체 리뷰, 구조 변경, 공개 계약을 바꾸는 수정. 큰 일은 1~5단계 결과와 대안을 소유자가 먼저 본다. +- 이 작업에서 선행 사례는 둘이다: 같은 원인이 남은 다른 자리, 그리고 [reference/defect-patterns.md](reference/defect-patterns.md)의 같은 모양. +- 대안은 고치는 법 2~3개를 비교한다. 고른 것과 버린 것을 커밋 본문에 쓴다. +- 스킬: 리뷰는 `superpowers:requesting-code-review`의 리뷰어 지침과 바뀐 경계의 영역 스킬, 결함 수정은 `superpowers:systematic-debugging` → `superpowers:test-driven-development`, 리팩터링은 `refactor`·`codebase-design`, 성능은 `performance-optimization`, 구조 변경은 `superpowers:brainstorming` → `superpowers:writing-plans`. 리뷰 결과를 받아 고칠 때는 `superpowers:receiving-code-review`. +- 스킬이 하위 에이전트를 띄우라고 하면 그 단계는 이 세션이 직접 한다. 나눠야 하면 [delegate.md](delegate.md)대로 별도 세션에 맡긴다. + +## 4. 절차 + +### 4.1 리뷰 + +1. 범위를 고정한다. 확인 리뷰는 pathspec과 `git diff --stat .. -- ` 결과를 문서에 적는다. +2. 확인 리뷰는 수정 보고의 「새로 가정하는 것」 칸부터 본다. 가정마다 다른 코드·설정·운영에서 참인지 확인한다. +3. 그다음 수정 diff와, diff가 바꾼 동작의 주변 코드를 읽는다. 확인 리뷰는 저장소 전체가 아니라 그 수정만 본다. +4. 전체 리뷰는 게이트를 먼저 한 번 돌려 결과를 적고([reference/gates.md](reference/gates.md)), 영역을 나눈다([delegate.md](delegate.md) 「나누는 법」). +5. 의심 결함은 별도 worktree의 임시 테스트(탐침)로 확인한다. 탐침 코드는 고칠 때 옮겨 쓸 수 있게 남기고(소유자 환경에서는 공유 노트 폴더, design-docs `conventions/delegation-loop.md` 11절), worktree는 지운다. +6. 발견을 [reference/review-criteria.md](reference/review-criteria.md) 양식으로 적는다. 발견마다 증거 수준과 "이번 수정이 만들었나 / 이전부터 있었나"를 적는다. +7. 리뷰 폴더 README에 색인을 만든다. 발견 ID를 모두 이름으로 적는다. 범위(`A~B`)와 이어 쓰기(`A·07`)는 된다. 건수만 쓰지 않는다. +8. `python3 scripts/check-review-index.py docs/reviews/<폴더>`를 돌린다. 색인 절이 따로 있으면 `--index-heading "<절 제목>"`을 붙인다. rc=0이어야 한다. +9. 판단하지 않은 항목은 「Declined to judge」에 위치와 이유를 적는다. 맡긴 쪽이 다음 묶음에 배정하거나 결정으로 닫는다. + +### 4.2 결함 수정 + +1. 원인 경로를 확인한다. 증상이 아니라 원인을 적는다. +2. RED: 결함을 재현하는 테스트를 먼저 쓰고, 수정 전 코드에서 실패하는 것을 실행으로 본다. 실패 메시지가 그 결함을 말해야 한다. 컴파일 오류나 준비 실패는 RED가 아니다. +3. 수정과 테스트를 이미 같이 썼으면, 기준 커밋에 테스트만 얹은 임시 worktree에서 RED를 본다. 실 DB·Redis가 필요한 결함은 실 vendor lane에서 본다. +4. 가장 작은 수정으로 GREEN을 본다. +5. 같은 원인의 다른 자리를 찾는다. 경계마다 다시 구현된 규칙은 한 곳만 고치면 다른 곳에서 다시 갈라진다. +6. 그 동작을 설명하는 문서를 같은 변경에서 고친다: `docs/web/http-contract.md`, `docs/registries/`, runbook, `docs/manual/`, leaf README·`CLAUDE.md`, Javadoc. 고친 뒤 옛 표현을 grep으로 찾는다. +7. 파생 서비스가 따라 고쳐야 하면 `docs/upgrade/`의 안내에 행을 더하고, 커밋 제목에 `!`와 `BREAKING CHANGE:` 꼬리말을 단다. +8. 영향 leaf의 `check`와 그 코드를 지키는 lane을 돌린다([reference/gates.md](reference/gates.md) 2절, 실행 위치는 [operate.md](operate.md)). + +### 4.3 리팩터링, 성능, 구조, 테스트 구조 + +- 리팩터링: 지킬 동작·타입·실패·진단을 "보존 조건"으로 적는다. 그 조건을 지키는 테스트가 지금 통과하는지 먼저 본다. 리팩터링과 동작 변경을 한 커밋에 섞지 않는다. +- 복사본을 합칠 때: 정본 하나를 정하고 나머지를 지운다. 못 지우면 이유를 가까운 `CLAUDE.md`에 적고, 두 벌이 같은지 보는 대조 테스트를 둔다. +- 성능: 숫자 없이 시작하지 않는다. 기준선 측정 → 원인 좁히기 → 변경 하나 → 같은 조건으로 재측정 → 회귀 테스트로 고정. 조건은 review-criteria.md 「성능 측정」, 지난 기준선은 [evidence.md](evidence.md)다. 지난 숫자는 현재 커밋에서 다시 잰다. +- 구조 변경: 설계서(`docs/superpowers/specs/`)와 계획서(`docs/superpowers/plans/`)를 먼저 둔다. review-criteria.md 「leaf 변경 체크리스트」를 따른다. ArchUnit 규칙을 바꾸면 잡혀야 할 위반 fixture와 통과해야 할 허용 fixture를 둘 다 둔다. +- 테스트 구조: 지금 테스트가 증명하는 것(이름, 단언, skip 수)을 적는다. 고친 뒤 지키려는 production 코드를 일부러 망가뜨려 테스트가 실패하는지(변이) 본다. 옮겼으면 lane별 테스트 수를 전후로 비교한다. + +### 4.4 수정 묶음의 크기 + +- 묶음 하나는 리뷰 영역 하나 안이고 발견 8건 이하다. 묶음마다 커밋 하나다. +- 확인 리뷰 하나가 보는 수정 diff는 추가 1,500줄 이하다(`git diff --shortstat ..`, 테스트 포함, lockfile·스냅숏 같은 생성 파일 제외). 넘으면 묶음 커밋별로 나눠 따로 확인 리뷰한다. +- 왜: 지난 수정 라운드에서 추가 줄이 2,000줄 아래면 다음 확인 리뷰 발견이 9건 이하였고, 5,000줄을 넘으면 19건 이상이었다([evidence.md](evidence.md) 「수정 묶음 크기」). 상한 값은 판단이다. 라운드당 새 결함 수로 다시 맞춘다. +- 묶음을 합친 트리는 따로 검증한다([reference/gates.md](reference/gates.md) 「라운드 끝」). 두 묶음의 수정은 한 트리에서 처음 만날 때 새 결함을 만든다. + +### 4.5 멈춤 기준 — 이 repo는 하나다 + +리뷰 → 수정 → 확인 리뷰는 아래 넷이 모두 참일 때만 멈춘다. + +1. 마지막 확인 리뷰의 발견이 심각도와 상관없이 0이다. Minor도 기록만 하지 않고 고친다. +2. 열린 「Declined to judge」가 0이다. +3. 합친 트리에서 라운드 끝 게이트가 모두 통과했다. +4. 리뷰 README의 남은 항목이 0이다. 결정으로 닫은 항목은 결정 위치를 적었다. + +- 다른 멈춤 기준은 이 repo에서 쓰지 않는다. "새 Important가 0이면 멈춤"과 "Minor는 기록만"은 소유자가 거뒀다. 짝 프론트 repo는 자기 기준을 쓴다(소유자 결정 "각자 유지"). +- 코드로 닫을 수 없는 것은 소유자 결정이 필요한 항목뿐이다. 근거와 권하는 안을 붙여 질문으로 보고하고, 답을 받으면 다시 고친다. + +## 5. 완료 기준 + +- 리뷰: 모든 발견이 양식대로이고 증거 수준이 있다. 색인 검사가 rc=0이다. 결정이 필요한 항목마다 선택지와 권하는 안이 있다. +- 결함 수정: 수정 전 실패(RED)와 수정 뒤 통과(GREEN) 로그가 있다. 같은 원인의 다른 자리를 확인했다. 해당 게이트가 rc=0이다(desktop 로그 경로). 보고에 「새로 가정하는 것」이 있다. +- 리팩터링: 보존 조건 테스트가 전후 모두 통과하고 `architectureCheck`가 통과한다. 지운 코드를 가리키는 문서·주석이 grep으로 0이다. +- 성능: 전후 숫자가 같은 조건에서 나왔다. 회귀 테스트가 어떤 단계에 속한다(`verifyStrictLaneStages --dry-run` 통과). +- 구조 변경: `architectureCheck`, `verifyDependencyLocks`, `ci`, `mainCheck`가 통과한다. 문서에 leaf 개수를 적지 않았다. +- 테스트 구조: 변이가 잡혔다. 새 lane이 단계에 속한다. `testQualityCheck`가 통과한다. +- `docs/work/`나 루트 `CLAUDE.md`를 고쳤으면 `python3 scripts/check-work-docs.py`가 rc=0이다. + +## 6. 하지 말 것 + +- 리뷰 중에 코드를 고치지 않는다. 리뷰는 읽기 전용이다. +- 이전 라운드의 실행 결과나 묶음 보고의 "통과"를 현재 증거로 쓰지 않는다. 바뀐 커밋에서 다시 돌린다. +- 정한 결정을 결함으로 다시 올리지 않는다. 전제가 틀렸다는 새 증거가 있을 때만 근거와 함께 다시 연다. +- 범위 밖 결함을 고치지 않는다. 버리지도 않는다. 위치와 함께 「Declined to judge」나 보고의 「범위 밖에서 본 것」에 적는다. +- 같은 결함을 여러 번 세지 않는다. 두 영역이 같은 결함을 적으면 색인에서 하나로 합친다. +- 어딘가에 적용된 마이그레이션 파일을 고치지 않는다. +- 전 leaf의 import를 바꾸는 이동을 다른 묶음과 동시에 하지 않는다. 나머지를 합친 뒤 혼자 마지막에 한다. + +## 7. 막혔을 때 + +- 고치는 법이 공개 동작(응답 코드, 기동 실패 조건, env 키, 파생 서비스 동작)을 바꾸면 고치기 전에 멈추고 묻는다. 형식은 [README](README.md) 5절이다. +- RED를 만들 수 없으면(실 vendor가 없다, 머신에 따라 통과한다) 그 사실과 이유를 보고하고 그 발견만 멈춘다. + +## 8. 보고 형식 + +[README](README.md) 6절에 더해, 고친 발견마다 아래 칸을 쓴다. 리뷰 README의 처리 표에 그대로 옮길 수 있게 쓴다. + +| 칸 | 적을 것 | +| --- | --- | +| 발견 | 고친 발견의 ID와 한 줄 내용(brief와 리뷰 문서에서는 ID를 쓴다) | +| 상태 | 완료 / 부분(무엇이 남았나) / 못 함(이유) | +| RED | 수정 전 실패한 테스트 이름과 수, 로그 경로 | +| 검증 | 명령, 테스트 수, rc, 로그 경로 | +| 처리 내용 | 바꾼 것, 고치다 새로 찾아 고친 것 | +| 새로 가정하는 것 | 이 변경이 다른 코드·설정·운영에 새로 기대는 것. 확인 리뷰가 여기서 시작한다 | +| 정한 기본값 | 소유자가 확인할 것 | +| 범위 밖에서 본 것 | 위치와 내용. 고치지 않았다 | + +## 9. 자주 하는 실수 + +- 색인을 손으로 옮기다 발견이 빠진다. 색인 검사 스크립트를 돌린다. +- 보고에 없는 태스크 이름을 적는다. 로그에서 태스크 이름을 grep해 확인한다. +- 성능 lane을 workflow와 다른 속성으로 돌린다. [reference/gates.md](reference/gates.md) 「성능 lane」을 따른다. +- 묶음별 검증으로 합친 트리 검증을 대신한다. 라운드 끝 게이트를 따로 돌린다. diff --git a/docs/work/new-feature.md b/docs/work/new-feature.md new file mode 100644 index 00000000..73007fff --- /dev/null +++ b/docs/work/new-feature.md @@ -0,0 +1,79 @@ +# 새 기능 — 업무 기능과 capability 모듈 만들기 + +이 playbook은 입구다. 만드는 순서와 판단 지점은 개발 매뉴얼 [`docs/manual/`](../manual/README.md)이 정본이다. 여기에는 크기, 완료 기준, 하지 말 것만 더한다. + +## 1. 언제 쓰나 + +- 새 업무 기능(도메인 개념, 유스케이스, endpoint)을 더할 때. +- 새 capability 모듈(의존성 한 줄로 켜지는 부가 기능)을 만들 때. +- 아니면 다른 playbook이다. + - 있는 기능의 결함·구조를 고친다 → [improve.md](improve.md) + - 어디에 둘지, 어떤 저장소를 쓸지 같은 결정이 먼저 필요하다 → [research-design.md](research-design.md) + - 있는 capability를 켜거나 끈다(`runtimeOnly` 한 줄) → 이 playbook의 4절 3단계에서 `docs/manual/10-capabilities.md`만 따른다 + +## 2. 받아야 할 것 + +- 기능 이름(PascalCase, 예: `Invoice`)과 경로 이름이 규칙대로 안 될 때의 경로(`--path`). +- 요구사항: 무엇을 저장하나, 누가 호출하나, 어떤 권한인가, 재전송될 수 있는 쓰기인가. +- 저장소 선택(어떤 persistence leaf, 마이그레이션 번호대). 서비스마다 달라 사람이 정한다(`docs/manual/04-persistence.md`). brief에 없으면 묻는다. +- 공개 계약(HTTP 경로, 오류 코드, env 키)을 새로 만드는지. 만들면 크기는 큼이다. +- 기준 커밋, 브랜치, 커밋 허용 여부. + +## 3. 크기와 사고 순서 + +- 업무 기능 하나는 보통 중간이다: 계층 leaf 여러 곳에 파일이 생기지만 판단은 매뉴얼이 정해 둔 범위 안이다. +- 큼: 새 capability 모듈, 새 leaf, 새 공개 계약, 파생 서비스가 따라 고쳐야 하는 변경. 큰 일은 설계와 소유자 검토가 먼저다([research-design.md](research-design.md)). +- 선행 사례는 생성 명령의 출력 하나다. `src/sample-portfolio`는 개별 기법(조건부 PATCH, 페이지, outbox, DB 유일 제약)의 참고일 뿐 배치를 따라 하지 않는다. +- 스킬: 설계가 바뀌면 `superpowers:brainstorming`, 여러 단계면 `superpowers:writing-plans`, 구현은 `superpowers:test-driven-development`. + +## 4. 절차 + +1. `docs/manual/README.md`를 읽는다. 처음이면 01 → 02 → 03장을 읽는다. +2. 배치를 정한다(`docs/manual/03-placement.md`). 기본은 계층 leaf 안 `` 패키지다. 이름이 템플릿 패키지(`src/application-core/CLAUDE.md` 「Package ownership」)와 겹치지 않는지 본다. +3. capability 모듈이면 `docs/manual/10-capabilities.md`와 `AGENTS.md` 「부가 기능(capability) 모듈 규칙」의 완료 기준 7개를 먼저 읽는다. 새 leaf가 생기면 [reference/review-criteria.md](reference/review-criteria.md) 「leaf 변경 체크리스트」를 따른다. +4. 뼈대를 만든다: `scripts/new-feature.sh `(`docs/manual/01-generator.md`). 이 명령은 끝에 Gradle `spotlessApply`를 돈다. 노트북에서는 `--no-format`으로 파일만 만들고, 포맷은 desktop에서 `./gradlew spotlessApply`로 한다([operate.md](operate.md) 「실행 위치」). +5. `docs/manual/02-new-feature.md`의 순서대로 채운다: domain-core → application-core → outbound adapter → inbound adapter → app-bootstrap 조립. 안쪽부터 만들면 각 단계가 앞 단계만 보고 컴파일된다. +6. 기능에 필요한 장만 더 읽는다: 저장(04), 재시도될 쓰기(05), 오류(06), 권한(07), 테스트 배치(08), 이벤트(09). +7. 동작은 테스트를 먼저 쓴다. 포트마다 fake 하나와 공유 계약(`XxxRepositoryContract`)을 포트 소유 leaf의 `testFixtures`에 두고, 실제 adapter도 같은 계약을 실 DB lane에서 상속한다. +8. 건드린 leaf마다 `check`, 경계를 넘었으면 `architectureCheck`, 바뀐 표면의 검사를 desktop에서 돌린다([reference/gates.md](reference/gates.md) 2절). +9. `docs/manual/11-checklist.md`를 한 줄씩 확인한다. +10. 매뉴얼과 코드가 다른 곳을 찾았으면 매뉴얼을 고치는 변경을 따로 낸다(정본이 맞다). + +## 5. 완료 기준 + +- `docs/manual/11-checklist.md`의 항목이 모두 참이다. 아닌 항목은 이유를 보고에 적었다. +- 건드린 leaf의 `check`와 `architectureCheck`가 desktop에서 rc=0이다. 로그 경로가 보고에 있다. +- 공개 경로·env 키·의존성을 바꿨으면 `verifyPublicPathSnapshot`·`:app-bootstrap:verifyEnvKeys`·`verifyDependencyLocks`가 rc=0이다. +- 저장 adapter가 있으면 공유 계약을 실 DB lane에서 상속하고, 그 lane이 어떤 단계에 속한다(`verifyStrictLaneStages --dry-run`). +- capability 모듈이면 완료 기준 7개가 모두 참이고, 모듈 README에 세 가지(제공하는 것, 추가할 한 줄, 필요한 env 키)가 있다. +- 생성 명령의 템플릿이나 패키지 규칙을 바꿨으면 `verifyFeatureScaffold`가 통과한다. + +## 6. 하지 말 것 + +- `AGENTS.md` HARD-STOP을 어기지 않는다. 특히 controller가 repository를 부르거나, inbound DTO가 application으로 들어가거나, 업무 규칙이 mapper·filter·설정에 들어가는 것. +- `src/sample-portfolio`의 배치(한 leaf에 모든 계층)를 따라 하지 않는다. onboarding 테스트 fixture도 따라 하지 않는다. +- 업무 코드를 템플릿 패키지에 넣지 않는다. +- 저장 adapter를 `persistence-jpa` leaf 안에 만들지 않는다. 서비스 전용 persistence leaf에 둔다. +- 한 단계가 다른 leaf나 계층을 고쳐야 하면 범위를 조용히 넓히지 않는다. 거기서 멈추고 설계를 다시 본다(7절). +- bootstrap에 capability 이름·스위치 목록·scan 정규식을 넣지 않는다. 모듈이 자기 `AutoConfiguration.imports`로 켜진다. +- 노트북에서 Gradle을 돌리지 않는다. + +## 7. 막혔을 때 + +- 저장소 선택, 공개 계약, 권한 매핑처럼 매뉴얼이 "사람이 정한다"고 한 것은 근거와 권하는 안을 붙여 한 번 묻고 그 부분만 멈춘다([README](README.md) 5절). +- 매뉴얼의 판단 지점이 이 기능에 맞지 않으면(기본값도 예외도 해당 없음) 멈추고 묻는다. 새 판단 지점은 매뉴얼에 더할 후보로 보고한다. + +## 8. 보고 형식 + +[README](README.md) 6절에 더해 적는다. + +- 만든 기능과 배치: leaf별 패키지와 주요 타입. +- 읽은 매뉴얼 장과 그 장에서 고른 기본값·예외. +- 정한 것(소유자 확인 대상): 경로, 권한 이름, 오류 코드, 마이그레이션 번호. +- 11장 체크리스트 결과: 참이 아닌 항목과 이유. + +## 9. 자주 하는 실수 + +- 샘플을 베껴 한 leaf에 모든 계층을 둔다. 생성 명령의 출력을 따른다. +- 생성 명령을 노트북에서 기본 옵션으로 돌려 Gradle이 노트북에서 돈다. `--no-format`을 쓴다. +- 역할 → 권한 매핑을 빠뜨려 쓰기 API가 모든 요청에 403이다. `docs/manual/07-authorization.md`를 본다. diff --git a/docs/work/operate.md b/docs/work/operate.md new file mode 100644 index 00000000..3128b753 --- /dev/null +++ b/docs/work/operate.md @@ -0,0 +1,115 @@ +# 운영 — 게이트 실행, desktop 검증, 릴리스, 파생 서비스 + +검증을 실제로 돌리고, 릴리스하고, 템플릿 변경을 파생 서비스에 넘기는 절차다. 무엇을 돌릴지는 [reference/gates.md](reference/gates.md)가 정하고, 이 playbook은 어디서 어떻게 돌리는지 정한다. + +## 1. 언제 쓰나 + +- 다른 playbook의 검증 단계에서 Gradle·Docker·테스트·게이트를 돌릴 때(4.1·4.2절). +- 여러 묶음을 합친 트리를 라운드 끝 게이트로 검증할 때. +- 릴리스 태그 전 확인을 할 때(4.3절). +- 템플릿 변경을 파생 서비스가 받을 수 있게 준비할 때(4.4절). +- 게이트 자체(build-logic, workflow)를 고치는 일은 [improve.md](improve.md)다. + +## 2. 받아야 할 것 + +- 대상 브랜치와 커밋 sha. desktop은 push된 브랜치만 받을 수 있다. +- 자기 브랜치 push 허용 여부. desktop 검증이 필요한 일이면 brief가 허용해야 한다. main push는 허용되지 않는다. +- 돌릴 게이트 목록(없으면 [reference/gates.md](reference/gates.md) 2절로 정한다)과 로그를 둘 이름. + +## 3. 크기와 사고 순서 + +- 게이트를 돌리고 기록하는 일은 보통 작음이다: 목적 한 줄, 대상 확인, 실행과 기록. +- 라운드 끝 전체 묶음, 첫 실행이 실패해 원인을 찾는 일은 중간이다. 실패 원인 찾기는 `superpowers:systematic-debugging`. +- 릴리스와 파생 서비스 쪽 병합은 소유자가 정한다. + +## 4. 절차 + +### 4.1 실행 위치 — 소유자 환경 + +> 이 절은 이 repo 소유자의 기계에 묶인 규칙이다. 공용 정본은 design-docs `conventions/delegation-loop.md` 11절이다. 다른 환경(파생 서비스 등)은 이 절만 자기 환경으로 바꾼다. + +- 노트북에서는 git, grep, 파일 읽기, 문서 편집, `python3 scripts/*.py` 검사만 한다. **Gradle, Docker, Testcontainers, 테스트, 게이트, 성능 측정은 desktop에서 돌린다.** +- desktop의 Gradle·Docker 실행은 모두 공유 잠금 `flock /tmp/claude-gates/heavy.lock`으로 감싼다. 짝 프론트 repo도 같은 desktop에서 같은 잠금을 쓴다. +- desktop의 기존 checkout `~/workspace/clean-architecture-backend-template`은 여러 세션이 함께 쓴다. 그 `stash@{0}`는 소유자의 보관분이다. 건드리지 않는다. `git stash pop`·`drop`·`clear`와 이름 없는 `git stash`를 쓰지 않는다. +- design-docs repo는 노트북 `~/workspace/desktop-server-git/design-docs`에 있다. + +절차: + +```bash +# 1) 노트북: 검증할 변경을 자기 브랜치에 커밋하고 push한다(brief가 허용한 경우) +git push origin <자기 브랜치> + +# 2) desktop: 기존 checkout을 건드리지 않게 따로 worktree를 만든다 +ssh desktop +cd ~/workspace/clean-architecture-backend-template +git fetch origin +git worktree add ~/workspace/<작업 이름> origin/<자기 브랜치> +mkdir -p ~/<작업 이름>-logs +uptime # 다른 빌드가 돌고 있는지 부하를 본다 + +# 3) 공유 잠금 아래에서 한 번에 하나씩 돌리고 rc와 로그를 남긴다 +cd ~/workspace/<작업 이름>/src +flock /tmp/claude-gates/heavy.lock ./gradlew <게이트> --console=plain > ~/<작업 이름>-logs/<게이트>.log 2>&1; echo "rc=$?" + +# 4) 끝나면 worktree를 지운다 +cd ~/workspace/clean-architecture-backend-template +git worktree remove ~/workspace/<작업 이름> +``` + +- 로그는 desktop `~/<작업 이름>-logs/`에 남기고, 보고에 그 desktop 경로와 rc를 쓴다. +- RED 확인용 임시 worktree도 같은 방법으로 만들고 끝나면 지운다. +- Python 검사 스크립트는 노트북에서 돌려도 된다. 보고 증거로 쓸 때는 desktop worktree에서 한 번 더 돌린다. + +### 4.2 게이트 실행과 기록 + +1. [reference/gates.md](reference/gates.md) 2절로 돌릴 게이트를 고른다. 라운드 끝이면 3절 묶음 전체다. +2. 잠금을 얻은 뒤 1분 부하를 적고 돌린다. 한 번에 하나씩이다. +3. 첫 실행이 실패하면 원인을 찾아 고치고 다시 돌린다. 첫 실행과 다시 돌린 결과를 둘 다 적는다. +4. 결과를 [reference/gates.md](reference/gates.md) 4절 형식으로 적는다: 게이트, rc, 시간, 직전 부하, 로그 경로, 대상 커밋. +5. 보고한 태스크 이름과 테스트 수가 로그에 있는지 grep으로 확인한다. + +### 4.3 릴리스 + +- 릴리스는 `v*` 태그 push로 시작한다(`.github/workflows/release.yml`). 태그와 push는 소유자가 한다. +- 태그 전에 그 커밋에서 `./gradlew :releaseCheck -PgitRevision= --console=plain`을 desktop에서 돌린다. sha 없이 돌리면 설계대로 실패한다. +- 태그는 PR 게이트와 main 단계를 이미 통과한 main 커밋에서 자른다. 그래서 `releaseCheck`는 `ci`를 다시 돌리지 않는다. +- 이미지 서명·SBOM은 workflow가 한다(cosign keyless). + +### 4.4 파생 서비스에 템플릿 변경 넘기기 + +- 파생 서비스는 이 템플릿을 받아 도메인을 채운 repo다. 템플릿 변경을 두 방식으로 받는다: 기준 커밋을 적은 tracked snapshot에 3-way로 반영하거나(`template.lock.json`), `git merge upstream/main`을 한다. +- 템플릿 쪽에서 할 일: 파생 서비스가 따라 고쳐야 하는 변경은 `docs/upgrade/`의 안내에 행을 더하고 커밋 제목에 `!`를 단다. 안내 문서 형식은 `docs/upgrade/2026-11-maturity-review.md`다. +- 파생 서비스가 유지할 게이트와 지워도 되는 템플릿 전용 게이트는 `docs/ci-cd/template-vs-consumer.md`다. +- 파생 서비스의 동기화는 루트 `CLAUDE.md`를 걸러낸다. 그래서 파생 서비스는 자기 `CLAUDE.md` 지도에서 `docs/work/README.md`를 가리켜야 한다. `docs/work/`는 걸러지지 않는다. +- `.claude/settings.json`(Agent 도구 금지)은 추적 파일이라 함께 넘어간다. 한 설정 단계에서 deny된 도구는 다른 단계(`settings.local.json`, 사용자 설정)의 allow로 풀리지 않는다(Claude Code 권한 문서 「Settings precedence」). 파생 서비스가 Agent 도구를 쓰려면 그 파일을 자기 repo에서 고친다. +- 파생 서비스 쪽 병합과 그 게이트는 그 repo의 일이다. 템플릿 세션이 파생 서비스 repo를 고치지 않는다. + +## 5. 완료 기준 + +- brief가 요구한 게이트마다 rc, 시간, 직전 부하, desktop 로그 경로, 대상 커밋이 있다. +- 못 돌린 게이트는 이유가 있다. 캐시로 통과한 것과 집계가 뺀 lane을 적었다. +- desktop에 만든 worktree를 지웠다(`git worktree list`에 없다). 기존 checkout의 브랜치와 `stash@{0}`가 그대로다. +- 노트북에서 Gradle·Docker를 돌리지 않았다. + +## 6. 하지 말 것 + +- 노트북에서 Gradle·Docker·테스트를 돌리지 않는다. +- 잠금 없이 desktop에서 무거운 명령을 돌리지 않는다. +- desktop 기존 checkout에서 브랜치를 바꾸거나 stash를 꺼내지 않는다. 자기 worktree를 쓴다. +- 다른 브랜치나 main에 push하지 않는다. 태그를 만들지 않는다. +- 첫 실행 실패를 지우고 두 번째 성공만 보고하지 않는다. + +## 7. 막혔을 때 + +- desktop에 접속할 수 없거나 잠금이 오래 풀리지 않으면 기다린 시간과 상태(`uptime`, 잠금을 쥔 프로세스)를 적어 묻는다. 노트북에서 대신 돌리지 않는다. +- 게이트가 이 일과 무관해 보이는 이유로 실패하면 같은 게이트를 기준 커밋에서 돌려 원래 있던 실패인지 가린다. 원래 있던 실패면 보고하고 그 게이트만 멈춘다. + +## 8. 보고 형식 + +[README](README.md) 6절에 더해 [reference/gates.md](reference/gates.md) 4절 표를 붙인다. desktop 정리 결과(지운 worktree, checkout 브랜치, `stash@{0}` 상태)를 한 줄로 적는다. + +## 9. 자주 하는 실수 + +- desktop 기존 checkout에서 브랜치를 바꿔 다른 세션의 작업을 방해한다. 자기 worktree를 만든다. +- 짧게 끝난 실행을 통과로 적는다. 캐시 재사용인지, 태스크가 실제로 돌았는지 로그로 확인한다. +- performance lane을 workflow와 다른 속성으로 돌린다. [reference/gates.md](reference/gates.md) 5절을 따른다. diff --git a/docs/work/reference/decisions.md b/docs/work/reference/decisions.md new file mode 100644 index 00000000..f0506d09 --- /dev/null +++ b/docs/work/reference/decisions.md @@ -0,0 +1,188 @@ +# 결정 색인 + +이미 정한 것을 한곳에서 찾는 색인이다. 결정의 원문은 「출처」 칸의 문서에 있고, 원문이 정본이다. 이 표와 원문이 다르면 원문이 맞고 이 표를 고친다. 이 문서는 지난 리뷰 ID와 결정 번호를 출처로 쓴다(매뉴얼 본문에는 쓰지 않는다). + +```text +작업 시작 ─> 이 색인에서 주제를 찾는다 ─> 있으면: 원문을 읽고 그대로 따른다 + └> 없으면: 소유자 몫인가? ─> 그렇다: 묻는다(3절) + └> 아니다: 정하고 기록한다(3절) +``` + +## 1. 결정을 다시 묻지 않는 규칙 + +1. 작업을 시작하기 전에 이 색인과 원문을 읽는다. 표에 있는 주제면 그 결정대로 한다. brief에도 결정의 **내용**을 옮겨 적는다. +2. 다시 열 수 있는 경우는 셋뿐이다. + - 결정의 전제가 코드나 측정으로 틀렸다고 확인됐다. + - 두 결정이 서로 충돌한다. + - 결정이 `AGENTS.md` HARD-STOP과 충돌한다. +3. 다시 열 때는 "다시 따져 본 것"과 권하는 안을 붙여 소유자에게 묻는다. 예: 2026-11-04 소유자가 수정 묶음의 기본값 셋을 다시 물었을 때, 총괄은 각각 근거를 다시 따져 적었고 소유자가 다시 정했다(`docs/reviews/2026-11-03-rereview/README.md` 15절). +4. 위임·기본값으로 정한 것은 보고에 따로 적는다. 소유자가 뒤집을 수 있게 한다. +5. 뒤집힌 결정은 원문에서 지우지 않는다. 취소선이나 "→ N절에서 바꿈"으로 새 위치를 가리킨다. +6. 리뷰어는 정한 결정을 결함으로 다시 올리지 않는다. + +## 2. 색인 + +「누가」 칸: **소유자**는 소유자가 직접 정했다. **위임**은 소유자가 "지금 정하고 진행하라"고 맡겨 총괄이 정했다(소유자가 뒤집을 수 있다). **기본값**은 수정 묶음이 정하고 처리 표에 남겼다(소유자 확인 대상). **총괄 지시**는 소유자 환경을 운영하려고 총괄 세션이 정한 작업 규칙이다. **정책**은 `AGENTS.md`에 적힌 규칙이다. + +「결정 N」은 `docs/reviews/2026-09-25-review-followup-status.md` 「소유자 결정」의 N번, `1101`은 `docs/reviews/2026-11-01-maturity-review/README.md`, `1103`은 `docs/reviews/2026-11-03-rereview/README.md`다. + +### 2.1 작업 방식 + +| 주제 | 결정 | 누가 | 날짜 | 출처 | +| --- | --- | --- | --- | --- | +| 커밋 정책 기본 | `human-only`. 에이전트는 stage·commit·amend·push하지 않는다 | 정책 | — | `AGENTS.md` 「Gradle 정책 권위」 끝 | +| 커밋 예외 | brief가 허용하면 그 작업의 자기 브랜치에만 커밋·push한다. main 병합·다른 브랜치 push·force push는 하지 않는다 | 소유자 | 2026-11-06 | design-docs `conventions/delegation-loop.md` 11절, `docs/work/README.md` 4절 | +| 커밋 예외(지난 것) | `refactor/review-followup`에 Wave마다 커밋(2026-09-25), 리뷰 수정을 `refactor/maturity-review-2026-11`에 커밋·push(2026-11-03) | 소유자 | 2026-09-25, 2026-11-03 | 결정 1, `1101` 17절 | +| 리뷰 발견 처리 | Minor도 기록만 하지 않고 고친다. 보고할 때 남은 문제가 0이어야 한다. 수정이 새 결함을 만들면 리뷰·수정을 0까지 반복한다 | 소유자 | 2026-11-05 | `1103` 16절 | +| 옛 멈춤 기준 | "새 Important 0이면 멈춤", "Minor는 기록만" — 거둠 | 위임 → 소유자가 거둠 | 2026-11-05 | `1103` 9.1·11.1·16절 | +| 두 repo의 종료 조건 | 각자 유지한다. 백엔드는 발견이 0이 될 때까지, 짝 프론트는 자기 매뉴얼의 조건 | 소유자 | 2026-11-05 | 2026-11-05 총괄 세션 전달(소유자 원문 "각자 유지") | +| 무거운 실행 위치 | 노트북에서 Gradle·Docker를 돌리지 않는다. desktop에서 브랜치를 받아 돌린다 | 소유자 | 2026-11-05 | `1103` 17.1절 | +| desktop 공유 잠금 | desktop의 Gradle·Docker 실행은 `flock /tmp/claude-gates/heavy.lock`으로 감싼다. 프론트와 부하·포트(4173·4174)가 겹치지 않게 | 총괄 지시 | 2026-11-05 | 2026-11-05 총괄 세션 brief, design-docs `conventions/delegation-loop.md` 11절 | +| 세션 분업 | 총괄 세션은 지휘만, 실제 작업은 하위 세션 | 소유자 | 2026-11-05 | design-docs `conventions/delegation-loop.md` 2절 | +| 하위 에이전트 | Agent 도구(세션 안의 하위 에이전트)를 쓰지 않는다. 막는 장치는 두 템플릿 repo의 프로젝트 설정(`.claude/settings.json`) | 소유자 | 2026-11-06 | design-docs `delegation-loop/02-design.md` 13절 D5 | +| 매뉴얼 체계 | 짧은 지도(`CLAUDE.md`) + 작업 종류별 playbook(`docs/work/`) + 예외 없는 규칙은 훅·게이트. repo 스킬 없이 시작 | 소유자 | 2026-11-06 | 같은 문서 D1, D4 | +| 크기별 생략 | 작음·중간·큼으로 사고 순서 단계를 줄인다. 크기는 맡기는 쪽이 정하고 맡은 쪽은 올리기만 한다 | 소유자 | 2026-11-06 | 같은 문서 D2, design-docs `conventions/work-thinking-order.md` | +| 매뉴얼 검사 장치 | 이력 ID·분량 검사와 리뷰 색인 검사는 Gradle 밖 `scripts/`(`check-work-docs.py`, `check-review-index.py`) | 소유자 | 2026-11-06 | 같은 문서 D6 | +| 규칙 ID | 규칙마다 ID(`R-…`)는 아직 붙이지 않는다. 원장이 생길 때 붙인다 | 소유자 | 2026-11-06 | 같은 문서 D7 | +| 옛 개선 매뉴얼 | 브랜치 `claude/improvement-manual-6ae516`은 병합하지 않고 재료로만 쓴다 | 소유자 | 2026-11-06 | 같은 문서 D12 | +| 개선 매뉴얼을 먼저(지난 것) | 다음 개선 작업 전에 repo마다 개선 매뉴얼을 만든다 → 2026-11-06 「매뉴얼 체계」로 바뀜 | 소유자 | 2026-11-05 | 2026-11-05 총괄 세션 brief | +| 스킬 | 리뷰·수정에 알맞은 스킬을 쓴다 | 소유자 | 2026-11-05 | `1103` 2절 | +| `@DisplayName` 언어 | 한국어(기본값 영어를 거부) | 소유자 | 2026-09-25 | 결정 5, `AGENTS.md` 테스트 작성 규칙 2 | +| 학습 문서 | 삭제된 코드를 설명하는 학습 문서(`docs/study/*.ko.md`, `docs/*-superpowers-package/`)는 현재 코드에 맞게 갱신 | 소유자 | 2026-09-25 | 결정 6 | +| client 오류 문구 | 한국어. `Category`별 문구 표 하나를 shared-contract에 | 소유자 | 2026-09-25 | 결정 11 | + +### 2.2 구조·조립 + +| 주제 | 결정 | 누가 | 출처 | +| --- | --- | --- | --- | +| outbox relay·멱등성 executor 조립 | app-bootstrap이 아니라 별도 `composition:*` 모듈 | 소유자 | 결정 3 | +| 새 leaf | `composition:durable-operation`, `adapter:inbound:messaging` 등록 승인 | 위임 | `1101` 15절 | +| edge 없는 복사본 | 템플릿 leaf는 `shared-contract` edge를 더해 정본을 쓴다. vendored(`messaging:*`·`grpc:*`)는 복사본을 두고 family `CLAUDE.md`에 이유 | 위임 | `1101` 15절(01-11) | +| caller 트랜잭션 guard | `persistence-notification`·`persistence-fileserver` → `persistence-jpa` edge, `CallerTransaction` 하나 | 소유자 | 결정 33 | +| id 포트 | notification·fileserver id 포트를 domain `IdFactory`로 옮기지 않음(보류) | 소유자 | 결정 34 | +| 소비자 없는 필드 | principal tenant, GraphQL Spring Security resolver, 가명화 키 분리는 하지 않음(보류) | 소유자 | 결정 35 | +| notification `TenantId` | 통합하지 않음. 차이와 이유는 그 타입 Javadoc | 위임 | `1101` 15절(01-03) | +| 생성 명령 | JPA adapter를 만들지 않음(서비스 전용 persistence leaf가 기본), 생성된 쓰기 API는 역할 매핑 전 403 | 위임 | `1101` 15절(r2-10) | +| `@SystemInvoked` | bean으로 등록돼 있으면 기동 실패, inbound adapter가 직접 부르지 못하게 ArchUnit | 위임 | `1103` 4절(RR-01-02) | +| 시스템 호출 경로 | 사용자가 닿는 전송(web·GraphQL·gRPC·WebSocket)만 `@SystemInvoked`에 닿지 못한다. 메시지 소비자·스케줄러는 `@SystemCaller(reason)` 표시로 허용 | 위임 | `1103` 9.1절(RR-01-12), 10절 r5-b | + +### 2.3 계약·오류 + +| 주제 | 결정 | 누가 | 출처 | +| --- | --- | --- | --- | +| HTTP 오류 응답 | Envelope 하나. fileserver problem+json도 Envelope로, tus 프로토콜 헤더만 유지 | 소유자 | 결정 2 | +| 처리 중 409 | `IDEMPOTENT_IN_FLIGHT`는 `retryable=true` + `Retry-After: 2`, 계약 문서에 고정 | 소유자 | `1101` 5절(02-01), 15절 | +| Envelope null 필드 | 백엔드가 생략(`NON_NULL`) | 소유자 | `1101` 5절(02-02) | +| `INTERNAL_ERROR` retryable | `false`. 일시적 실패는 전용 코드가 retryable을 가진다 | 소유자 | 결정 28 | +| 새 오류 코드 소유 | 코드를 쓰는 leaf의 enum. 계약은 `docs/web/http-contract.md` §4 | 위임 | `1101` 15절 | +| correlation ID | 규칙 밖이면 서버가 새 값으로 교체 | 위임 | `1101` 15절(02-11) | +| JSON 아닌 본문 상한 | 전역 상한 없음. 엔드포인트가 직접 둔다 | 위임 | `1101` 15절(02-09) | +| GraphQL 복잡도 | 크기 미선언 list = 20, `first`·`last` 둘 다면 큰 쪽, per-parent 경고 임계 10 | 위임 | `1101` 15절(03-01·03-03) | +| GraphQL DataLoader 키 실패 | 등록된 `ApiErrorCode`만 노출 | 소유자 | 결정 25 | +| Draft-12 offset 불일치 | problem 문서는 프로토콜 예외로 유지 | 소유자 | 결정 12 | +| 알림 category 생략 | 거부(400), 판정은 유스케이스 | 소유자 | 결정 13 | + +### 2.4 멱등성 + +| 주제 | 결정 | 누가 | 출처 | +| --- | --- | --- | --- | +| complete 단계 연결 포화 | `UNAVAILABLE` 현재 동작 유지 + 문서화 | 소유자 | 결정 24 | +| complete 단계 저장소 실패 | "결과 불명"으로 따로 알린다(실행 전 503과 구분). 같은 키 재전송은 서버가 판정 | 위임 | `1103` 4절(RR-02-03) | +| lease 지난 실행 중 기록 | PostgreSQL·Redis store가 같은 계약: 작업을 다시 돌리지 않고 "회복 필요" | 위임 | `1103` 9.1절(RR-01-11) | +| Redis key TTL | claim·renew 모두 key TTL ≥ max(replay TTL, processing lease), 설정 검사 | 위임 | `1103` 9.1절(RR-03-11) | +| 늦은 완료 | 늦게 끝난 첫 시도의 완료는 **기록한다**(묶음 기본값 "버린다"를 뒤집음). 다시 실행은 여전히 하지 않음 | 소유자 | `1103` 15절 ① | +| 보존 기간 관계 | `failure-retention < replay-ttl`이면 기동 실패 | 소유자 | `1103` 15절 ③ | +| 같은 attempt 재claim | lease 지난 `CLAIMED`·`FAILED_RETRYABLE`을 넘겨받는다. 같은 attempt를 두 호출이 동시에 쓰는 것은 호출자 계약 | 기본값 | `1103` 17절 r10-02 | +| 다른 핸들의 시작 답 | PostgreSQL도 Redis와 같게 `NOT_OWNER`/`NOT_CLAIMED`로 답한다 | 기본값 | `1103` 17절 r10-02 | +| Redis 연결 예산 | 캐시 조건부 쓰기는 멱등성·lease와 다른 연결 예산(SCRIPT lane) | 위임 | `1103` 4절(RR-04-02) | + +### 2.5 영속성 + +| 주제 | 결정 | 누가 | 출처 | +| --- | --- | --- | --- | +| JPA 기본값 | 트랜잭션 제한 30초, JDBC batch 50, H2 운영 jar 제거, 격리 수준 Hikari 고정, upsert `DO NOTHING` 후 갱신 | 위임 | `1101` 15절(04) | +| 포트 시그니처 | claim에 lease·`claimFence`, fileserver `claimDue`·`markAbandoned`·`claimToken` | 위임 | `1101` 15절 | +| 마이그레이션 번호 | 스트림별 순번. 샘플은 운영 스트림과 합쳐 도는 테스트가 있어 `V8_1`. notification은 `V13` | 위임 | `1101` 15절 | +| V21 유일 인덱스 | 기존 중복이 있으면 마이그레이션 실패. runbook에 확인 쿼리 | 위임 | `1101` 15절 | +| 순서 번호 seed | counter가 없으면 전역 floor부터 | 위임 | `1103` 4절(RR-03-02) | +| 마이그레이션 잠금 | 강한 잠금을 거는 마이그레이션은 `SET LOCAL lock_timeout`, 같은 모양의 lane 테스트 | 위임 | `1103` 9.1절(RR-02-09) | +| Flyway PostgreSQL 잠금 | 세션 수준(`transactional-lock: false`). 전제: Hikari 직접 연결. transaction-mode PgBouncer 뒤에서는 깨진다 | 기본값 | `1103` 17절 r10-03(RR6-03-01) | +| persistence-jpa 설정 prefix | 플랫폼 자체는 `app.persistence-jpa.*`, 공유 기능은 기능 트리(`app.outbox`·`app.lock`·`app.realtime.replay`) | 소유자 | 결정 36 | +| 분산 lock·lease | 둘 다 capability로 유지, 공통 계약 테스트 | 소유자 | 결정 8 | + +### 2.6 샘플·메시징·보안·설정 + +| 주제 | 결정 | 누가 | 출처 | +| --- | --- | --- | --- | +| 포스터 업로드 abort·reconcile 경합 | 먼저 끝난 쪽이 이김(이미 게시됐으면 abort는 409) | 소유자 | 결정 22 | +| work log 권한·batch | 관리자도 남의 work log 수정 불가, `batchCreate` 상한 1000·한 트랜잭션 | 위임 | `1101` 15절(09) | +| 이벤트 tenant·오류 코드 | 이벤트 tenant 범위 `global`, `WORKLOG_INVALID`·`OPERATION_NOT_FOUND` | 위임 | `1101` 15절(01) | +| outbox append 모델 | canonical(`OutboxAppendPort`)로 통일, legacy 포트·legacy Kafka 발행 경로 삭제 | 소유자 | 결정 7 | +| Kafka 소비 | 지원. `MessageHandler` 하나 + starter-kafka가 consumer 조립 | 소유자 | 결정 10 | +| decode 타입 등록 | handler bean이 선언한 타입으로 decode 목록을 만든다 | 위임 | `1101` 15절(06-08 후속) | +| relay 재시도 | 재시도 가능 거부는 무한 재시도(5분 간격), 예산 설정 키 없음, 인증 오류는 경보로 | 위임 | `1101` 15절(06-01·06-03) | +| 끝나지 않는 재시도 | bridge가 원인 코드를 행에 남기고, 오래 재시도 중인 행 수·나이를 지표로, runbook에 park·재개 절차와 테스트된 SQL | 위임 | `1103` 4절(RR-05-03) | +| 카드 검증기 YAML | messaging leaf 테스트에서만 snakeyaml(main 금지) | 소유자 | 결정 29 | +| JWT audience·role | audience 필수, 자기 client role만(기존 배포는 env 하나를 채움) | 소유자 | `1101` 5절(02-03), 15절 | +| 데모 계정 | `local`·`test`·`demo` 프로필이 명시적으로 켜졌을 때만(허용 목록). 각 프로필은 sample이 실제로 뜨는 프로필 | 위임 | `1103` 4절(RR-07-02), 9.1절(RR2-04-02) | +| `fixture-` 값 거부 | 비밀로 분류된 키(`docs/registries/secrets-classification.yaml`)만 검사 | 위임 | `1103` 9.1절(RR2-04-01) | +| 파일 서버 인가 | 역할 검사(`file:*` 권한)와 소유자·tenant 검사(`ownerPrincipalId`)를 둘 다 | 소유자 | 결정 14, 결정 32 | +| cross-origin redirect | 호출자 헤더 전부 제거, 안전한 헤더만 유지 | 소유자 | 결정 23 | +| 개발 compose Redis | lane Redis에 ACL 계정, "기동 WARN 없음" 검사 유지 | 위임 | `1101` 15절(r3-J) | +| 서블릿 오류 디스패치 | 보안 체인이 ERROR 디스패치만 허용 | 기본값 | `1103` 6절 r4-b, 8절 | +| 설정 prefix | `app.*`로 통일, `APP_*` env 키 유지 | 소유자 | 결정 16 | +| Redis prefix 예외 | `app.redis.*`·`app.capabilities.*`·`app.rate-limit.*` 세 트리 유지, 네 번째 금지 | 위임 | `1101` 15절(05-18), `AGENTS.md` capability 기준 4 | +| 로그 설정 | logback이 `app.logging.*`을 읽음, `APP_CACHE_REDIS_TTL_JITTER` deprecated | 위임 | `1101` 15절(07) | +| 빈 env 값 | 선택 숫자 설정의 빈 값은 "미설정". 오타·모르는 키 거부는 그대로 | 위임 | `1101` 15절 | +| `APP_FLYWAY_ENABLED` | dev·prod에도 적용 | 위임 | `1101` 15절(r3-F) | +| 전송 상한 기본값 | gRPC 스레드 32·큐 256·동시 100·deadline 10s·drain 2s, ledger `claimTtl` 5m·보존 24h, WebSocket `max-connections` 1000(초과 시 1013) | 위임 | `1101` 15절(03-06·03-09·03-10) | + +### 2.7 빌드·게이트·capability + +| 주제 | 결정 | 누가 | 출처 | +| --- | --- | --- | --- | +| 빌드 게이트 | `verifyEnvKeys`는 app-bootstrap 태스크로 유지(구현은 build-logic `ca.config-contract`), JPA evidence manifest는 폐기하고 leaf 테스트로, redis topology lane 유지 | 소유자 | 결정 4 | +| API surface 단계 | PR(leaf `check` 안) | 소유자 | 결정 20 | +| PR `ci` 범위 | 변경 모듈만 돌리지 않음. 전체 실행 + Gradle 캐시(보류) | 소유자 | 결정 30 | +| 의존성 checksum | 추가 안 함(보류) | 소유자 | 결정 19 | +| build-logic 의존성 잠금 | 잠그지 않음 + 문서화(보류) | 소유자 | 결정 27 | +| 릴리스 이미지 서명 | cosign keyless, tag 릴리스에서 서명·검증 | 소유자 | 결정 31 | +| gRPC `.proto` | protobuf Gradle 플러그인 + Buf(CI) | 소유자 | 결정 18 | +| SpotBugs 신뢰도 | MEDIUM으로 내림. 패턴 단위 제외는 이유를 단다 | 위임 | `1101` 15절(08-07) | +| 테스트 코드 정적 분석 | `testQualityCheck`는 main 빌드 `mainCheck`, optional 빌드 `ci` | 위임 | `1103` 14절 | +| lane 정책과 캐시 | lane 정책 값(`rejectSkipped` 등)은 모두 캐시 입력 | 위임 | `1103` 4절(RR-06-02) | +| workflow 명령의 빌드 판정 | 같은 셸의 `cd <상대 경로>`도 따라간다 | 소유자 | `1103` 15절 ② | +| 문서 파싱 검사 | 문서를 파싱해 대조하는 Gradle 검사를 두지 않는다(`verifyDocumentedLeafCount` 등 삭제). 문서와 코드 대조는 leaf의 document-contract lane | 정책 | `AGENTS.md` 「Gradle 정책 권위」 | +| MinIO 이미지 | `pgsty/minio` digest | 위임 | `1101` 15절(05-09) | +| Jackson 2 | 기본 jar에 남김(logstash encoder·springdoc 요구) | 위임 | `1101` 15절(09-11) | +| httpclient reactive | 삭제 | 소유자 | 결정 9 | +| SES 연동 | AWS SDK(sesv2) | 소유자 | 결정 17 | +| durable operation | HTTP 어댑터 추가, 설계 4개(서버 생성 id, payload 지문으로 재제출 판정, 고정 event type, 1일 보존) 승인 | 소유자 | 결정 15, 결정 26 | +| 알림 provider profile 소실 | 일반 재시도 정책 후 FAILED | 소유자 | 결정 21 | +| notification INGEST_ONLY | runtime 없이도 accept 때 route 이름 기록 | 위임 | `1101` 15절(r3-I) | +| 파일 서버 쿼터 | 상한 미설정 = 무제한, 동시 예약은 상한을 넘을 수 있음, 정리 worker 기본 켜짐 | 위임 | `1101` 15절(r2-05a) | +| objectstorage | provider type 하나 추가 | 위임 | `1101` 15절(05-16) | +| 에이전트가 원칙에서 바로 정한 것 | Kafka 주소 키 하나, composition이 persistence-jpa를 함께 가져옴 등 7건 | 기본값 | `docs/reviews/2026-09-25-review-followup-status.md` 「소유자 결정」 끝 목록 | +| 묶음별 기본값 | 각 라운드 처리 표의 「결정」 칸(예: SES replay 창 1h, Retry-After 30) | 기본값 | `1101` 13·14·16절, `1103` 6·10·12·15·16·17절 표 | + +## 3. 새 결정을 기록하는 법 + +**누가 정하나** + +| 소유자에게 묻는다 | 직접 정하고 기록한다 | +| --- | --- | +| 공개 계약·wire 형식 변경, 파생 서비스 동작을 바꾸는 기본값, 보안 정책, 새 leaf, 커밋 정책, 되돌리기 비싼 선택, 비용이 드는 외부 일 | 기존 원칙에서 바로 따라 나오는 것, 결함 수정의 구현 방법, 문서 위치 | + +**묻는 법**: 항목 · 선택지 · 권하는 안과 이유 · 정할 사람을 한 표로 쓴다. + +**어디에 쓰나** + +| 결정의 종류 | 위치 | +| --- | --- | +| 리뷰 라운드에서 나온 결정 | 그 라운드 README의 「결정」 절. 항목 · 결정 · 이유 · 버린 대안 | +| 수정 묶음의 구현 기본값 | 처리 표의 「결정」 칸 | +| 되돌리기 비싼 아키텍처 선택 | `docs/adr/ADR-<영역>-<번호>-<제목>.md`(기존 번호를 잇는다) | +| 매뉴얼을 만들거나 고치며 정한 것 | 이 색인 + 근거는 `docs/work/evidence.md` | +| 여러 repo와 소유자 운영에 걸친 결정 | design-docs | + +**기록한 뒤**: 이 색인에 한 줄(주제 · 결정 · 누가 · 날짜 · 출처)을 더한다. diff --git a/docs/work/reference/defect-patterns.md b/docs/work/reference/defect-patterns.md new file mode 100644 index 00000000..590ff58c --- /dev/null +++ b/docs/work/reference/defect-patterns.md @@ -0,0 +1,131 @@ +# 결함 패턴 + +이 repo의 리뷰에서 반복해서 나온 결함을 **모양**으로 묶은 목록이다. 리뷰를 시작하기 전에 훑어보고, 고칠 때는 「막는 기준」을 따른다. 리뷰 README의 「반복되는 원인」에 이 번호(A1~)를 붙인다. 패턴마다 근거가 된 지난 발견은 [evidence.md](../evidence.md) 「결함 패턴의 근거」에 있다. + +계층·경계 규칙 자체의 정본은 `AGENTS.md`(HARD-STOP, 모듈 책임, 금지된 지름길)와 가장 가까운 `src/**/CLAUDE.md`다. 이 문서는 그 규칙을 다시 쓰지 않고, 고치거나 리뷰할 때 반복해서 틀린 곳만 적는다. + +## 패턴 + +### A1. 갈라진 복사본 + +- **모양**: 같은 규칙·표·정규식·상수·이미지 참조가 여러 곳에 있고 이미 다르다. +- **막는 기준**: 규칙·표·정규식·상수·이미지 참조는 한 곳에 둔다. 두 곳이 꼭 필요하면 하나를 정본으로 명시하고, 다른 하나가 정본과 같은지 보는 대조 테스트를 둔다. +- **볼 것**: 새로 쓴 상수·정규식·표가 이미 어딘가에 있는지 grep. 같은 판정을 두 클래스가 하는지. +- **장치**: 정본을 가져다 쓰기(예: 마이그레이션 버전 판정 정본 `VersionedMigrationFiles`를 grpc 빌드가 Sync 태스크로 가져온다), 대조 테스트(`TemplatePackageOwnershipDocumentTest`). 테스트 lane의 컨테이너 이미지는 `src/config/testing/container-images.properties` 한 곳이다(MinIO qualification 이미지만 objectstorage leaf 소유). + +### A2. 문서와 코드 불일치 + +- **모양**: 계약·runbook·매뉴얼·README·Javadoc·실패 메시지가 현재 동작과 다르다. +- **막는 기준**: 동작을 바꾸는 변경은 그 동작을 설명하는 모든 문서를 같은 변경에서 고친다. 대상: `docs/web/http-contract.md`, `docs/registries/`, runbook, 매뉴얼, leaf README·`CLAUDE.md`, Javadoc, 업그레이드 안내. 고친 뒤 옛 표현을 grep으로 찾아 남은 곳을 없앤다. +- **볼 것**: diff가 바꾼 동작의 키워드(오류 코드, 설정 키, 상태 이름)로 `docs/`, `src/**/README.md`, `src/**/CLAUDE.md`를 grep. +- **장치**: 일부만 있다. runbook 숫자와 상수를 비교하는 document-contract lane, runbook SQL을 실 PostgreSQL에서 그대로 실행하는 lane. 나머지는 리뷰가 본다. 이 repo는 문서 전체를 파싱하는 검사를 일부러 두지 않는다(`docs/testing/TESTING_STRATEGY.md` 8절). + +### A3. 선언과 실행이 떨어져 있다 + +- **모양**: 설정 키는 바인딩되지만 동작하지 않는다. 선언한 설정 bean이 조용히 바인딩되지 않는다. 레지스트리 행·지표를 아무 코드도 쓰지 않는다. +- **막는 기준**: 선언(설정 키, 레지스트리 행, 지표 이름, 옵션)마다 그것을 실행하는 코드가 있어야 한다. 실행 코드가 없으면 선언을 지운다. 동작하지 않는 옵션은 설정 키 자체를 두지 않는다(`AGENTS.md` capability 기준 3). +- **볼 것**: 새 설정 키를 읽는 곳, 새 레지스트리 행을 내보내는 곳, 문서가 말한 옵션의 분기. 기동 rule이 `static @Bean`이고 필드 주입이 없는지. +- **장치**: `StrictSettingsBinder`(모르는 키·오타 거부), `verifyEnvKeys`, 레지스트리와 코드를 대조하는 테스트(`ErrorCodeRegistryMappingTest`, `HeaderRegistryRuntimeAlignmentTest` 등). + +### A4. 결과 불명을 "확실함"으로 기록한다 + +- **모양**: 외부 효과의 결과를 모르는데 "시작 안 함", "재시도 가능", "확정 거부"로 기록한다. 또는 반대로 확실한 실패를 결과 불명으로 부풀린다. +- **막는 기준**: 외부 효과(DB 커밋, 알림 발송, broker 전송)의 결과를 모르면 "결과 불명"으로 기록·응답한다. 결과 불명을 자동으로 다시 실행하지 않는다. 확실히 실패한 것을 결과 불명으로 부풀리지 않는다. +- **볼 것**: 외부 호출 전후의 상태 기록 순서, 예외를 retryable·terminal·unknown으로 나누는 분기, 응답의 `retryable`. +- **장치**: 멱등성 공유 계약(`IdempotencyStoreContract` — PostgreSQL·Redis store가 같은 판정), `PersistenceExceptionTranslator`의 커밋 단계 분류, `docs/adr/ADR-JPA-003-completion-unknown.md`. + +### A5. 중복·경쟁을 코드 순서로 막는다 + +- **모양**: 조회 후 insert, 찾고 없으면 넣기, 트랜잭션 없는 `SKIP LOCKED`, lease 없는 claim, 프로세스 메모리에 둔 소유권. +- **막는 기준**: 유일성은 DB 유일 제약이 막고, adapter는 그 제약 위반만 기능 예외로 바꾼다. 여러 인스턴스가 집는 작업은 트랜잭션 안의 claim + lease로 소유권을 정한다. +- **볼 것**: 존재 확인 뒤 쓰기, 트랜잭션 밖 잠금, 메모리 안 소유권. +- **장치**: `CallerTransaction`(store는 호출자 트랜잭션을 요구), 동시 요청 통합 테스트(`CreatePosterConcurrencyIntegrationTest`). 정본: `docs/manual/04-persistence.md`. + +### A6. 주장하는 것을 보지 않는 테스트 + +- **모양**: 이름이 말한 성질을 단언하지 않는다. 지키려는 코드를 지워도 통과한다. 시간 제한 대기의 결과를 버린다. 계약 케이스를 skip한다. +- **막는 기준**: [review-criteria.md](review-criteria.md) 7절 점검표. 변이로 확인한다. skip은 0이거나 설계 이유를 적는다. +- **장치**: 포트당 fake와 공유 계약 상속(`AGENTS.md` 테스트 작성 규칙 6), `rejectSkipped`. + +### A7. 거짓 통과 게이트 + +- **모양**: 어떤 단계도 돌리지 않는 lane·검사, 캐시가 옛 결과로 통과, 실패를 막지 못하는 workflow 명령을 실행으로 셈, 시간 단언을 끈 채 돈 performance lane. +- **막는 기준**: [gates.md](gates.md) 6절. 게이트 장치를 바꾸면 일부러 망가뜨린 입력으로 실패하는 것을 본다. +- **장치**: `verifyStrictLaneStages --dry-run`(두 빌드), lane 정책 값의 캐시 입력 선언, `testQualityCheck`. + +### A8. 로그로 새는 입력값·원인 + +- **모양**: 클라이언트 입력이나 SQL 원인이 로그 메시지에 실린다. 서버 실패를 남기지 않거나 클라이언트 실패를 ERROR로 남긴다. +- **막는 기준**: 클라이언트 탓 실패(입력 오류)는 WARN 한 줄로 남기고 입력값을 싣지 않는다. 서버 실패는 전송마다 같은 실패 로그 줄(`ServerFailureLog`)을 쓰고, 원인 체인의 SQL·입력값을 메시지에 붙이지 않는다. 클라이언트가 보낸 식별자가 규칙 밖이면 서버가 새 값으로 바꾼다. +- **볼 것**: 새 `log.warn`·`log.error`의 인자, 예외 메시지에 사용자 입력을 넣는 곳, 전송별 예외 처리기. +- **장치**: `src/shared-contract/src/main/java/dev/caskeleton/shared/error/ServerFailureLog.java`(`refusedArgument` 포함), 비밀 분류 `docs/registries/secrets-classification.yaml`. + +### A9. 이름만 보는 허용·거부 + +- **모양**: 프로필·환경 이름 하나가 다르면 위험한 기능이 열린다. 허용한 값으로는 실제로 동작하지 않는다. +- **막는 기준**: 위험한 기능(데모 계정, 비밀 검사 면제 등)은 거부 목록이 아니라 허용 목록으로 연다. 허용 목록의 값마다 실제로 그 값으로 동작해야 한다. +- **볼 것**: 프로필·환경 이름 문자열 비교, 허용 값마다 실제로 기동하는 테스트가 있는지. +- **장치**: `SampleDemoProfilesStartupSystemTest`(허용 프로필마다 기동). + +### A10. 글로만 있는 규칙 + +- **모양**: "하지 마라", "반드시"가 주석·Javadoc·문서에만 있고 막는 장치가 없다(통제 M0~M1). +- **막는 기준**: 위반하면 데이터·권한이 깨지는 규칙은 기동 실패, ArchUnit, 타입으로 막는다. +- **볼 것**: "must not", "하지 않는다", "금지", "반드시"가 붙은 문장마다 막는 장치가 있는지. +- **장치**: 이유를 요구하는 표시(`@SystemCaller(reason)`), 기동 rule, ArchUnit. + +### A11. 샘플·fixture가 운영과 다르게 조립된다 + +- **모양**: 샘플이 자동 설정을 빼거나 런타임 기본값이 다르다. "따라 할 모양"으로 둔 fixture가 기동하지 않는다. +- **막는 기준**: 샘플은 운영과 같은 자동 설정과 런타임 기본값을 쓴다. 무엇을 빼면 이유와 대체 장치를 같은 곳에 적는다. 새 기능의 모양으로 둔 fixture는 실제로 기동되는 모양이어야 한다. +- **볼 것**: 샘플 `@SpringBootApplication(exclude=…)`, 샘플 `application.yml`과 기본 조합의 차이. +- **장치**: 샘플 전체 기동 lane(`:sample-portfolio:systemTest`, `mainCheck`), 샘플 실서버 계약(`sampleWebContractCheck`). + +### A12. 수정이 새 결함을 만든다 + +- **모양**: 고친 커밋에서 새 Important·회귀가 나온다. 두 수정이 한 트리에서 처음 만나 새 결함이 생긴다. +- **막는 기준**: 수정 보고에 「새로 가정하는 것」을 쓰고 확인 리뷰가 그 칸부터 본다. 수정 묶음 크기 상한을 지킨다([improve.md](../improve.md) 4.4절). 합친 트리를 라운드 끝 게이트로 따로 검증한다. +- **장치**: 확인 리뷰(수정 diff만), [gates.md](gates.md) 3절. + +### A13. 합치는 과정의 누락 + +- **모양**: 색인을 손으로 옮기다 발견이 빠진다. 손으로 푼 충돌이 한쪽 변경을 지운다. +- **막는 기준**: 색인은 영역 문서에서 기계로 대조한다. 두 묶음이 같은 파일을 건드리지 않게 나눈다([delegate.md](../delegate.md) 「나누는 법」). +- **장치**: `python3 scripts/check-review-index.py docs/reviews/<폴더>`. + +### A14. 타이밍에 기댄 약속 + +- **모양**: "스레드를 남기지 않는다", "시간 안에 끊는다"가 공용 풀이나 "보통은 끝나 있다"에 기댄다. +- **막는 기준**: 그런 약속은 join·종료 대기·전용 스레드로 보장한다. +- **볼 것**: `awaitTermination` 뒤 스레드 생존 확인, 시간 제한을 거는 실행기가 공용인지. +- **장치**: 부하·자원 한계 lane(`httpClientPerformanceTest` 등, `performanceCheck`). + +### A15. 사라지는 외부 공급원 + +- **모양**: 고정한 컨테이너 이미지를 더는 받을 수 없어 다른 lane 결과까지 가린다. +- **막는 기준**: 테스트 이미지는 한 곳에 digest로 고정하고, pull 실패는 따로 구분되는 메시지로 실패하게 한다. +- **장치**: `src/config/testing/container-images.properties`, `PinnedImageUnavailableException`, main 단계 `--continue`. + +### A16. 상한 없는 자원 + +- **모양**: 연결·구독·동시 호출·본문 크기·트랜잭션 시간·큐 길이에 상한이 없거나 코드에 드러나지 않는다. +- **막는 기준**: 상한이 있고 그 값이 코드나 설정에 드러난다. 상한을 넘으면 정해진 응답(예: WebSocket 1013, gRPC 즉시 닫기)을 준다. +- **정한 값**: [decisions.md](decisions.md) 「전송 상한 기본값」, JPA 기본 트랜잭션 제한 30초. JSON 아닌 본문 상한은 엔드포인트가 직접 둔다. + +## 코드에 결정을 드러내는 곳 + +고칠 때 "왜 이 모양인가"를 코드 가까이에 남긴다. 다음 리뷰가 같은 질문을 다시 하지 않게 하려는 것이다. + +| 경우 | 남기는 곳 | +| --- | --- | +| 규칙을 일부러 다르게 둔 타입 | 그 타입의 Javadoc | +| 정적 분석 제외 | 제외 항목 옆 이유(`src/config/spotbugs/exclude-test.xml` 등) | +| 규칙의 예외 경로 | 이유를 요구하는 표시(`@SystemCaller(reason)`) | +| 복사본을 남긴 이유 | 가까운 `CLAUDE.md`(예: `src/messaging/CLAUDE.md`) | +| 되돌리기 비싼 선택 | `docs/adr/ADR-<영역>-<번호>-<제목>.md` | + +## 패턴을 더하는 법 + +- 새 라운드에서 **두 건 이상**이 같은 모양이면 행을 더한다. 한 건이면 그 라운드 README에만 둔다. +- 모양은 원인 추측이 아니라 코드에서 실제로 본 모양을 쓴다. 근거 ID는 [evidence.md](../evidence.md)에 쓴다. +- 번호는 다시 매기지 않는다. 지운 패턴은 행을 남기고 "합침 → A"으로 적는다. diff --git a/docs/work/reference/gates.md b/docs/work/reference/gates.md new file mode 100644 index 00000000..4ed57d7b --- /dev/null +++ b/docs/work/reference/gates.md @@ -0,0 +1,129 @@ +# 게이트 + +무엇을, 언제, 어디서 돌리는지 정한다. 게이트 구성의 정본은 `src/build.gradle`의 라이프사이클과 `.github/workflows/`다. 이 문서와 그 둘이 다르면 그 둘이 맞고, 이 문서를 고친다. 실행 위치(desktop, 잠금)는 [operate.md](../operate.md) 「실행 위치」다. + +```text +작업 중 :check (+ 그 leaf의 관련 strict lane) +묶음 끝 + architectureCheck · 바뀐 표면의 검사(env 키·공개 경로·의존성 잠금) · 관련 lane +라운드 끝 합친 트리에서 3절 묶음 전체 — workflow가 PR·main에서 돌리는 것과 같은 명령 +``` + +## 1. 게이트 목록 + +명령은 모두 `src/`에서 실행한다. leaf의 Gradle path는 `src/config/architecture/modules.json`의 `gradle_path`에서 읽는다. leaf별 명령 목록을 문서에 적지 않는다. + +| 게이트 | 무엇 | 단계 | 정의·workflow | +| --- | --- | --- | --- | +| `./gradlew :check` | 그 leaf만: 컴파일, 테스트, Spotless, Checkstyle, Error Prone, API surface | 작업 중 | leaf 컨벤션 플러그인 | +| `architectureCheck` | 의존 방향, domain-core·shared-contract·application-* 순수성, Git이 옮길 수 있는 소스, ArchUnit | PR(`ci` 안) | `src/build.gradle` | +| `./gradlew :app-bootstrap:architectureTest` | 저장소 전체 ArchUnit suite만 | 작업 중 | app-bootstrap `architectureTest` source set | +| `qualityCheck` | SpotBugs, FindSecBugs(운영 코드) | PR(`ci` 안) | `src/build.gradle` | +| `testQualityCheck` | 같은 분석을 모든 테스트 source set에(`config/spotbugs/exclude-test.xml` 기준) | main(`mainCheck` 안), optional 빌드는 `ci` | `src/build.gradle` | +| `ci` | leaf `check`(API surface 포함) + `architectureCheck` + `qualityCheck` | PR | `ci-quality-gates.yml`: `./gradlew :ci :verifyDependencyLocks --warning-mode=fail` | +| `verifyStrictLaneStages --dry-run` | `explicitOnly`가 아닌 strict lane이 workflow가 실행하는 단계에 속하는가 | PR(두 빌드 각각) | `ci-quality-gates.yml`, optional 빌드는 `-p optional-platforms` | +| `:sample-portfolio:check :sample-portfolio:qualityCheck` | 샘플(`ci` 밖) | PR | `ci-quality-gates.yml` | +| `-p optional-platforms ci` | gRPC 플랫폼 빌드 | PR | `ci-quality-gates.yml` | +| `bash scripts/verify-compose-profile-contracts.sh` | compose lane이 선언대로 렌더링되는가(저장소 루트에서) | PR | `ci-quality-gates.yml` | +| `mainCheck` | `configContractCheck` + `qualificationCheck`(`testQualityCheck` 포함) + 샘플 실서버 계약 + 샘플 전체 기동(`:sample-portfolio:systemTest`) + 공개 경로 스냅숏 + 전송·메시징 qualification lane + 생성 명령 왕복(`verifyFeatureScaffold`) + 모든 leaf의 `mainCheck`(document-contract lane 등) | main | `integration-main.yml`: `./gradlew :mainCheck --continue --warning-mode=fail` | +| `integrationCheck` | 선언된 strict integration lane 전체(실 컨테이너). 입력이 없는 lane은 빼고 이름을 댄다 | main·nightly | `integration-main.yml`, optional 빌드도 | +| `performanceCheck` | 선언된 performance lane 전체(부하·종료·풀·자원 한계, 실 서버와 컨테이너). main·nightly에서 돈다 | main·nightly | `integration-main.yml`, optional 빌드도. 5절 | +| `releaseCheck -PgitRevision=` | 릴리스 provenance + 공개 경로 스냅숏. sha 없이 돌리면 설계대로 실패한다 | 태그 | `release.yml` | +| `:app-bootstrap:verifyEnvKeys` | env 키 레지스트리와 profile YAML·`.env.example` | `mainCheck` 안(`configContractCheck`) | build-logic `ca.config-contract` | +| `verifyPublicPathSnapshot` | 기본 공개 경로가 `docs/security/public-paths-snapshot.txt`와 같은가 | `mainCheck`·`releaseCheck` 안 | `src/build.gradle` | +| `verifyDependencyLocks` | lockfile | PR | `ci-quality-gates.yml` | +| `:app-bootstrap:documentContractTest` | 문서와 코드를 대조하는 lane(태그 `document-contract`) | main(`mainCheck` 안) | `src/app-bootstrap/build.gradle` | +| `:app-bootstrap:repositoryContractTest` | 빌드 스크립트·workflow·compose를 읽는 계약(태그 `repository-contract`) | PR | `src/app-bootstrap/build.gradle` | + +- leaf의 `check`는 그 leaf만 본다. 저장소 전체 질문은 이름이 따로 있는 루트 태스크가 답한다. +- 전체 `test`·`check`·`ci`는 brief가 시킬 때 돌린다. +- 공개 경로 검사와 env 키 검사는 그 표면이 바뀌었을 때 돌린다. + +## 2. 바꾼 것에 맞춰 고르기 + +| 바꾼 것 | 추가로 돌릴 것 | +| --- | --- | +| 한 leaf 안의 코드 | 그 leaf `check` + 그 코드를 지키는 strict lane(실 DB 등) | +| leaf 경계·의존·registry | `architectureCheck`, `verifyDependencyLocks` | +| env 키 | `:app-bootstrap:verifyEnvKeys` | +| 공개 경로·보안 체인 | `verifyPublicPathSnapshot` | +| 의존성 | `verifyDependencyLocks` | +| 문서(`docs/**`, `CLAUDE.md`, README) | 그 문서를 읽는 document-contract lane(예: `:app-bootstrap:documentContractTest`) + 링크 검사(아래) | +| `docs/work/`, 루트 `CLAUDE.md` | `python3 scripts/check-work-docs.py` | +| 다른 매뉴얼에서 이력 ID를 걷어냄 | `python3 scripts/check-work-docs.py --history <파일 또는 폴더>` | +| build-logic·workflow | `-p build-logic check javadoc`, 두 빌드의 `verifyStrictLaneStages --dry-run` | +| 패키지 규칙, 생성 명령 템플릿 | `verifyFeatureScaffold`(`mainCheck` 안) | +| 마이그레이션 | persistence-jpa `check`, 잠금 대기 lane(`postgresqlMigrationLockWaitIntegrationTest`), 마이그레이션 lane | +| 테스트 코드 | 그 leaf `testQualityCheck` | +| compose·Dockerfile | compose 검사 스크립트, 실제 `docker build`와 기동 | + +어떤 테스트가 그 문서를 읽는지는 `grep -rn '<파일 이름>' src --include=*.java`로 찾는다. + +**링크 검사**: workflow `link-check.yml`(lychee)이 PR에서 `README.md`, `src/README.md`, `src/**/README.md`, `src/**/CLAUDE.md`, `docs/**/*.md`, `.github/**/*.md`를 검사한다. 루트 `CLAUDE.md`는 그 범위 밖이라 `scripts/check-work-docs.py`가 본다. lychee가 없는 곳에서는 `python3 scripts/check-work-docs.py --links docs`로 상대 링크만 확인한다. 저장소 밖 경로와 `file:line`은 링크로 쓰지 않는다(lychee가 따라가지 못한다). + +## 3. 라운드 끝 — 합친 트리의 전체 묶음 + +여러 묶음을 합친 트리는 workflow와 같은 명령으로 검증한다. 한 번에 하나씩, 공유 잠금 아래에서 돌린다. + +```bash +cd src +./gradlew :ci :verifyDependencyLocks --warning-mode=fail --console=plain +./gradlew :sample-portfolio:check :sample-portfolio:qualityCheck --console=plain +./gradlew :verifyStrictLaneStages --dry-run --console=plain +./gradlew -p optional-platforms :verifyStrictLaneStages --dry-run --console=plain +./gradlew :mainCheck --continue --warning-mode=fail --console=plain +./gradlew :integrationCheck --continue --console=plain +./gradlew -p optional-platforms ci integrationCheck performanceCheck -Pperformance.assertions.enabled=true --console=plain +./gradlew :performanceCheck --continue -Pperformance.assertions.enabled=true --console=plain +./gradlew :releaseCheck -PgitRevision="$(git rev-parse HEAD)" --console=plain +cd .. && bash scripts/verify-compose-profile-contracts.sh +``` + +- 첫 실행이 실패하면 고치고 다시 돌린다. 둘 다 기록한다. +- 합친 뒤에만 드러나는 결함이 있다. 묶음별 검증으로 이 단계를 대신하지 않는다. + +## 4. 결과 기록 + +| 게이트 | 결과 | 시간 | 실행 직전 1분 부하 | 로그 | +| --- | --- | --- | --- | --- | +| `:ci :verifyDependencyLocks --warning-mode=fail` | rc=0 | 5분 42초 | 2.65 | desktop `~/<작업 이름>-logs/ci.log` | + +함께 적는다: + +- 대상 커밋 sha. 작업 트리가 커밋되지 않았으면 그렇다고 적는다. +- 못 돌린 것과 이유. 이유 없이 빠진 검증은 HARD-STOP 6 위반이다. +- 캐시로 통과한 것. 실행 시간이 짧으면 캐시 재사용인지 적는다. +- 집계가 뺀 lane. 입력이 없어 빠진 lane의 이름. +- 고친 테스트가 실제로 돌았는지. 큰 집계 안에서 몇 개가 돌았는지 테스트 수로. +- 보고한 태스크가 로그에 있는지. 로그에서 태스크 이름을 grep해 확인한다. + +## 5. 성능 lane + +- 일부 performance lane은 시간 단언을 `performance.assertions.enabled` 속성으로 켠다. workflow는 이 값을 `true`로 준다(`integration-main.yml`의 `GRADLE_OPTS`). +- leaf마다 기본값이 다르다: httpclient lane은 `false`(`src/adapter/outbound/httpclient/build.gradle`), persistence-mongo lane은 `true`(`src/adapter/outbound/persistence-mongo/build.gradle`). +- 그래서 desktop에서 `performanceCheck`를 돌릴 때는 workflow와 같게 `-Pperformance.assertions.enabled=true`를 준다. 안 주면 httpclient의 시간 단언 없이 통과한다. +- 시간 단언은 다른 빌드가 돌지 않는 머신에서만 뜻이 있다. 그래서 performance lane은 PR·main 단계가 아니라 `performanceCheck`에 있다. + +회귀를 막는 장치: + +| 장치 | 고정하는 것 | 단계 | +| --- | --- | --- | +| 요청당 SQL 수 단언(`WorkLogStatementCostSystemTest`) | 목록 20건과 100건의 문장 수가 같음, 제목만 바꾸는 PATCH가 컬렉션 행을 건드리지 않음, batch 생성이 JDBC batch로 감 | sample `systemTest`(`mainCheck`) | +| 자원 한계 lane | Tomcat·Jetty 부하·느린 클라이언트·종료, HTTP client 풀·스트리밍·재시도, Hikari 풀 | `performanceCheck` | +| JMH 벤치마크 | `src/messaging/messaging-kafka/src/jmh`, `src/messaging/messaging-testkit/src/jmh`, `src/adapter/outbound/httpclient/src/jmh` | 명시 실행 | + +## 6. 게이트를 믿을 조건 — 거짓 통과 막기 + +초록이라는 사실만으로 그 게이트가 무언가를 막았다는 뜻은 아니다. + +| 거짓 통과 모양 | 지금의 장치 | +| --- | --- | +| 어떤 workflow도 돌리지 않는 lane | `verifyStrictLaneStages --dry-run`(PR) | +| optional 빌드를 보지 않음 | optional 빌드도 같은 검사 | +| 실패를 막지 못하는 workflow 명령을 실행으로 셈(`\|\| true`, pipefail 없는 파이프, `if` 조건 등) | `AGENTS.md` 「Gradle 정책 권위」의 세는 규칙 | +| lane 정책을 바꿨는데 캐시가 옛 결과로 통과 | lane 정책 값을 Test 입력으로 | +| 게이트 밖에서 실패한 채 방치된 검사 | `testQualityCheck`(`mainCheck`) | +| 실서버 계약이 어느 게이트에도 없음 | lane을 단계에 연결 | +| 시간 단언을 끈 채 performance lane 실행 | 5절 속성 | +| 외부 이미지가 사라져 다른 lane 결과까지 가림 | 테스트 이미지를 `src/config/testing/container-images.properties` 한 곳에 digest로 고정, main 단계는 `--continue` | + +게이트 장치 자체를 바꿨으면 일부러 망가뜨린 입력으로 실패하는 것을 본다. 판독기를 바꿨으면 바꾸기 전후로 실제 workflow의 판정이 같은지 비교한다. diff --git a/docs/work/reference/review-criteria.md b/docs/work/reference/review-criteria.md new file mode 100644 index 00000000..de30a617 --- /dev/null +++ b/docs/work/reference/review-criteria.md @@ -0,0 +1,283 @@ +# 리뷰 기준 + +리뷰와 수정에서 무엇을 결함으로 보고, 어떻게 판정하고, 어떤 형식으로 적는지 정한다. [improve.md](../improve.md)가 필요할 때 이 문서의 절을 가리킨다. 지난 리뷰에서 실제로 나온 예는 [evidence.md](../evidence.md) 「리뷰 기준의 예」에 있다. + +공용 리뷰 가이드는 이 repo 밖에 있다: design-docs `conventions/template-maturity-review-guide.md`. 아래 「가이드 N절」은 그 문서의 절이다. 이 문서는 가이드 없이도 판정할 수 있게 썼다. 일반 설명이 더 필요할 때만 가이드를 읽는다. + +## 1. 결함이란 + +리뷰는 **약속과 실제 동작이 다른 곳**을 찾는다. 약속은 코드 이름, Javadoc, 문서, 레지스트리, 테스트 이름, 게이트가 한 것이다. 약속을 어긴 증거가 있으면 결함이고, 없으면 개선 제안이다. + +| 결함의 모양 | 증거 | +| --- | --- | +| 이름·Javadoc·문서가 말한 동작과 실제 동작이 다르다 | 코드 경로 또는 실행 결과 | +| `AGENTS.md` HARD-STOP을 어긴다 | 의존 방향 게이트, ArchUnit, 코드 | +| 같은 규칙·값·표가 두 곳 이상에 있고, 서로 다르거나 같게 지키는 장치가 없다 | 두 위치와 차이 | +| 테스트나 게이트가 통과하지만 막겠다고 한 것을 막지 못한다 | 변이 실험, 실행 그래프 대조 | +| 운영자·개발자에게 틀린 조치를 시키는 문서 | 문서대로 실행한 결과 | +| 위험한 동작이 기본값·설정 뒤에 숨어 있다 | 기본값과 그 효과 | + +**개선 제안**은 계약 위반 없이 이해나 비용을 줄일 여지다. 현재 선택과 대안을 비교해 적는다(가이드 41절). 받으면 고치고, 받지 않으면 이유를 결정으로 남긴다. 기록만 하고 열어 두지 않는다. + +다음 말은 결함 근거가 아니다. + +| 근거가 아닌 말 | 결함으로 적으려면 | +| --- | --- | +| "추상화가 많다" | 어느 wrapper가 무엇을 보호하지 않는지, 지우면 무엇이 유지되는지 | +| "운영 준비가 안 됐다" | 어떤 절차를 어떤 버전에서 실행한 증거가 없는지 | +| "업계 표준이 아니다" | 이 repo의 어느 계약을 어기는지 | + +## 2. 발견의 성격 + +| 성격 | 뜻 | +| --- | --- | +| 확인된 결함 | 현재 커밋의 코드·실행으로 계약 위반을 보였다. 정적 증거만으로도 확정할 수 있다 | +| 구조적 위험 | 인과 경로는 있으나 영향 확인이 남았다. 예: 다중 인스턴스 경쟁을 코드 경로로만 봤다 | +| 미검증 | 이 환경에서 확인할 수 없다. 예: 실제 CI runner 실행 | +| 개선 제안 | 1절 | + +## 3. 심각도 + +심각도 체계는 둘이다. 리뷰 종류로 고른다. + +**전체 리뷰 — Critical / High / Medium / Low, 우선순위 P0~P3** (가이드 35.2·35.3절) + +| 등급 | 이 repo에서 | +| --- | --- | +| Critical | 인증 없이 민감정보 접근, 실제 데이터의 비가역 대량 손상 | +| High | 지원 조건에서 업무 중복 실행, 결과 불명 작업의 재실행, 기본 조합에서 보안 검사가 꺼짐 | +| Medium | 피해가 제한되거나 변경 비용을 반복해서 올림 | +| Low | 가독성·편의, 제한된 문서 불일치 | + +우선순위는 고치는 순서다. P1은 해당 용도 도입 전 해결, P2는 계획적 개선, P3는 선택이다. + +**확인 리뷰 — Critical / Important / Minor** (`superpowers:requesting-code-review` 리뷰어 지침의 체계) + +| 등급 | 정의 | +| --- | --- | +| Critical | 전체 리뷰의 Critical과 같다 | +| Important | 현실적 조건에서 틀린 동작·보안·데이터·공개 계약, 또는 운영자에게 틀린 조치를 시키는 문서 | +| Minor | 그 밖의 결함. 예: 거짓 실패 쪽 검사, 좁은 조건의 불일치, 문구 | + +확인 리뷰 발견에는 "이번 수정이 만들었나 / 이전부터 있었나"를 적는다. 이번 수정이 만든 것은 회귀로 따로 센다. + +**심각도가 정하지 않는 것** + +- 고칠지 말지. 이 repo는 모든 발견을 고치거나 결정으로 닫는다([improve.md](../improve.md) 4.5절). 심각도는 고치는 순서와, 맡긴 쪽이 코드에서 다시 확인할 범위(High·Important 이상)만 정한다. +- 건수. 한 결함이 여러 관점에 걸치면 항목 하나에 관점 번호를 모두 붙인다. 두 영역이 같은 결함을 적으면 색인에서 합친다. + +## 4. 증거 수준 E0~E4 (가이드 35.5절) + +| 수준 | 이 repo의 증거 | 주장할 수 없는 것 | +| --- | --- | --- | +| E0 설명·주장 | README, `CLAUDE.md`, Javadoc, 리뷰 문서의 이전 실행 기록, 묶음 보고의 "통과" | 현재 커밋의 동작 | +| E1 정적 확인 | 현재 커밋의 코드·설정·`build.gradle`·workflow를 `file:line`으로 읽음, `--dry-run` 그래프 | 실행 결과 | +| E2 테스트 실행 | 이름을 댄 테스트, leaf `check`, `ci`가 현재 커밋에서 통과(명령, rc, 테스트 수) | 실 vendor, 부하, 장애 | +| E3 통합·실험 | Testcontainers 실 PostgreSQL·Redis·Kafka·MinIO lane, `java -jar`·compose 실제 기동, 부하·장애 주입·동시 요청 실험 | 운영 환경, 운영 기간 | +| E4 운영 관찰 | 이 템플릿에는 없다 | — | + +- 이전 라운드의 실행 결과는 현재 증거가 아니다. 바뀐 커밋에서 다시 돌린다. +- 묶음 보고의 "통과"는 E0다. 맡긴 쪽은 보고를 diff와 실행 로그에 대조한다. +- build cache로 통과한 실행은 그렇다고 적는다. 실행 시간이 짧으면 캐시 재사용인지 확인한다. +- 발견마다 증거 수준을 적는다. 섞이면 나눠 적는다. 예: "E3 — 명령 9·10, 잠금 동작은 E1". + +## 5. 통제 수준 M0~M4 (가이드 35.4절) + +| 수준 | 뜻 | 이 repo의 예 | +| --- | --- | --- | +| M0 | 지킬 수단이 없다 | — | +| M1 | 적혀만 있다 | "하지 마라"가 주석·문서에만 있다 | +| M2 | 구현되어 있다 | 코드 경로에 규칙이 있고 검사는 없다 | +| M3 | 자동 검증이 위반을 잡는다 | ArchUnit(`src/app-bootstrap/src/architectureTest/`), 공유 계약 테스트, `verifyStrictLaneStages` | +| M4 | 경계에서 강제한다 | Gradle 의존 방향 게이트(`verifyCleanArchitectureDependencies`), DB 유일 제약, 기동 실패 rule | + +- 확인하지 못한 것은 M0가 아니라 "미확인"이다. +- 위반하면 데이터·권한이 깨지는 규칙이 M1이면 결함으로 적는다. + +## 6. 28개 관점 — 이 repo에서 볼 곳 + +관점의 일반 설명은 가이드 1~28절이다. 판정 기호: O 충족 · P 부분 · X 미충족 · ? 미검증 · - 적용 제외 · > 다른 영역. 종합은 평균하지 않는다. 한 영역이라도 X면 X다. + +| # | 관점 | 볼 곳 | 이런 증거면 결함 | +| --- | --- | --- | --- | +| 1 | 코드 성숙도 | 바뀐 클래스와 호출자, 예외 경로 | 이름·Javadoc과 다른 동작, 항상 참·거짓인 조건 | +| 2 | 구조적 성숙도 | registry `allowed_dependencies`, ArchUnit, leaf `CLAUDE.md` | HARD-STOP 위반, registry 밖 leaf 디렉터리, 템플릿 패키지가 기능 패키지를 import | +| 3 | 변경 용이성 | 기능 하나를 더하거나 뺄 때 고칠 파일, `scripts/new-feature.sh` 왕복 | 같은 규칙을 여러 곳에서 바꿔야 함 | +| 4 | 인지 부하 | 따라 할 예시 수, 같은 질문에 답하는 문서 수 | 예시·규칙이 여러 갈래이고 고르는 기준이 없음 | +| 5 | 위험 가시성 | 기본값, 설정 검증, 기동 rule, 프로필 허용 목록 | 위험이 기본값 뒤에 숨음, 레지스트리 `required`인데 코드는 빈 값 허용 | +| 6 | 실패 성숙도 | 예외 분류, `retryable`, 결과 불명 | 결과 불명을 확실함으로, 재시도 가능을 확정 실패로 기록 | +| 7 | 운영 성숙도 | `docs/runbooks/`, `docs/registries/metrics.yaml`, 종료 순서 | runbook이 틀린 조치를 시킴, 레지스트리 지표를 아무 코드도 내보내지 않음 | +| 8 | 디버깅 가능성 | `ServerFailureLog`, correlation id, 오류 코드 | 서버 실패를 남기지 않음, 원인이 다른 실패를 같은 코드로 | +| 9 | 유지보수 성숙도 | 복사본, 죽은 코드, 낡은 주석 | 갈라진 복사본, 현재 동작과 다른 주석·문서 | +| 10 | 테스트 성숙도 | 7절 | 이름의 성질을 단언하지 않음, 변이 생존, 계약 밖 fake | +| 11 | 데이터 성숙도 | 마이그레이션 스트림, 유일 제약, `@Version`, 잠금 시간 제한 | 중복 규칙에 DB 제약 없음, 적용된 마이그레이션 수정, `lock_timeout` 없는 강한 잠금 | +| 12 | 동시성 성숙도 | claim·lease, `SKIP LOCKED`, 트랜잭션 경계 | 트랜잭션 없는 `SKIP LOCKED`, lease 없는 claim | +| 13 | 확장성 | 연결·구독·동시 호출·본문 크기 상한 | 상한이 없거나 코드에 드러나지 않음 | +| 14 | 성능 성숙도 | 8절 | 데이터 수에 비례하는 SQL 수(N+1), 순차 스캔 | +| 15 | 보안 성숙도 | 인증·인가 체인, `docs/security/public-paths-snapshot.txt`, `docs/registries/secrets-classification.yaml`, 로그 | 기본으로 꺼진 검증, 권한 검사 없는 경로, 로그로 새는 입력값 | +| 16 | 의존성 성숙도 | `src/gradle/libs.versions.toml`, lockfile, `src/config/testing/container-images.properties` | 사라진 외부 이미지, 운영 jar의 테스트용 드라이버 | +| 17 | API·계약 성숙도 | `docs/web/http-contract.md`, `docs/registries/error-codes.yaml`, `docs/architecture/*-api-surface.txt`, 짝 프론트 계약 | 코드·문서·짝 계약이 서로 다름 | +| 18 | 배포 성숙도 | `src/Dockerfile`, `src/Dockerfile.sample`, compose, `release.yml` | 빌드되지 않는 Dockerfile, relay를 모르는 종료 순서 | +| 19 | 설정 성숙도 | `StrictSettingsBinder`, `docs/registries/env-keys.yaml`, `config/module-defaults/<모듈>.yml`, `verifyEnvKeys` | 바인딩되지만 동작하지 않는 키, 한 설정을 두 곳에서 읽음 | +| 20 | 개발자 경험 | `scripts/new-feature.sh`, `docs/manual/`, 게이트 시간 | 매뉴얼·생성 명령대로 하면 게이트를 통과하지 못함 | +| 21 | Guardrail 성숙도 | ArchUnit, `verifyStrictLaneStages`, 기동 rule, 정적 분석 단계 | 거짓으로 통과하는 게이트, 어떤 단계도 돌리지 않는 검사 | +| 22 | 추상화 성숙도 | 포트·SPI가 보호하는 것 | adapter가 정책을 소유, 역할 없는 단계 | +| 23 | 일관성 | 같은 역할의 이름·모양·규칙 | 같은 개념이 여러 벌 | +| 24 | 네이밍·의미 | `src/application-core/CLAUDE.md` 「Naming convention」, `NamingConventionTest` | 이름과 내용이 다름 | +| 25 | 조직 확장성 | 파생 서비스가 upstream을 받을 때 겹치는 곳 | 기능 패키지가 템플릿 패키지와 섞임 | +| 26 | Ownership | leaf마다 가까운 `CLAUDE.md`·README | 안내 문서 없음, 패키지가 평평해 소유가 안 보임 | +| 27 | 삭제 가능성 | capability `runtimeOnly` 한 줄 제거, sample 제거 | 한 줄 지워도 흔적이 남음, bootstrap이 capability 이름을 앎 | +| 28 | 회복 가능성 | runbook SQL, DEAD·park, ledger 회수 | 영구히 막히는 key, 복구가 행마다 수작업 | + +**따라갈 시나리오** (가이드 31절). 전체 리뷰는 시나리오마다 요청 하나를 끝까지 따라가며 입력 신뢰 수준, 권한 판단 위치, 규칙 소유자, 트랜잭션 시작과 끝, 외부 부작용, 오류 변환을 적는다. 해당 기능이 없으면 적용 제외 사유를 한 줄 적는다. + +| 시나리오 | 따라갈 경로 | +| --- | --- | +| 정상 쓰기 요청 | sample `POST /api/worklogs`, 생성 명령으로 만든 기능 | +| 중복·동시 요청 | 같은 제목 동시 `POST /api/posters`, 멱등 키(`docs/manual/05-idempotency.md`) | +| 외부 응답 지연·유실 | httpclient 시간 예산·breaker, 알림 발송 attempt | +| DB 오류·경쟁 | `PersistenceExceptionTranslator`, `@Version`, 트랜잭션 마감 | +| 메시지 중복·역순 | outbox relay, inbox 재전달, aggregate 순서 번호 | +| 신·구 버전 공존 | 마이그레이션 잠금, 배포 중 섞인 인스턴스 | +| 여러 서버의 작업 실행 | 알림 정산 job claim, gRPC ledger claim | +| 다른 사용자 리소스 접근 | 파일 서버 소유자 검사, sample 소유자 검사 | +| 큰 입력·목록 조회 | `GET /api/worklogs?size=100`, GraphQL 복잡도, JSON 아닌 본문 | +| 종료·재시작 | relay·platform 종료 순서, 종료 시간 예산 | +| 선택 어댑터 제거 | `src/app-bootstrap/build.gradle`의 `runtimeOnly` 한 줄 제거 | + +## 7. 테스트가 증명해야 하는 것 + +정본: 테스트 작성 규칙은 `AGENTS.md` 「테스트 전략」, 테스트 분류·배치·source set은 `docs/testing/TESTING_STRATEGY.md`(기계 기준 `TestLaneCategory`), 새 기능의 테스트 배치는 `docs/manual/08-testing.md`다. + +| 점검 | 결함 모양 | +| --- | --- | +| 이름이 말한 성질을 단언하나 | 이름은 "X를 남기지 않는다"인데 준비가 다른 예외를 넣는다 | +| 부재 단언이 null과 "키 없음"을 구분하나 | `doesNotExist`가 null 필드도 통과 | +| 지키려는 코드를 지우면 실패하나(변이) | 검사를 지워도 전부 통과 | +| 시간 제한 대기의 반환값을 단언하나 | `CountDownLatch.await(timeout)` 결과를 버려 시간 초과에도 다음 단계로 감 | +| skip이 0이거나 설계 이유가 있나 | 계약 케이스가 조용히 skip | +| 규칙 테스트가 위반·허용 fixture를 둘 다 가지나 | 위반 fixture만 있어 거짓 양성을 못 봄 | +| `// when`이 하나인가 | 두 동작을 한 테스트가 봄 | +| 테스트 코드도 정적 분석을 통과하나 | 게이트 밖에서 실패한 채 방치 | +| 타이밍에 기대지 않나 | 부하가 높으면 실패하는 "스레드 없음" 단언 | + +fake와 공유 계약: 포트마다 hand-rolled fake 하나를 포트 소유 leaf의 `testFixtures`에 두고, fake와 실제 adapter가 같은 추상 계약(`XxxContract`)을 상속한다. 계약 밖 fake, 소비자 없는 fake, 계약과 겹친 adapter 손 사본 테스트는 만들지 않는다. fake 동작을 바꾸면 계약 케이스를 같이 바꾼다. 포트를 더하거나 계약을 옮기면 `docs/testing/TESTING_STRATEGY.md`의 현황표를 고친다. + +lane: 새 lane은 반드시 어떤 단계에 속한다(`verifyStrictLaneStages --dry-run`). 반드시 돌아야 하는 테스트는 `requires(클래스)` + `rejectSkipped`로 이름을 박는다. lane 정책 값은 Test 입력으로 선언한다. 저장소 파일을 읽는 테스트는 태그를 단다(문서와 대조하면 `document-contract`, 빌드 스크립트·workflow·compose를 읽으면 `repository-contract`). + +RED가 증거가 되려면: 실패 메시지가 그 결함을 말한다. 머신에 따라 통과하지 않는다. 실 vendor가 필요한 결함은 실 vendor에서 본다(단위 테스트로 대신했으면 그렇게 적는다). 기록은 테스트 이름과 실패 수로 쓴다. + +## 8. 성능 측정 + +이 템플릿에는 지연·처리량 목표가 없다. 그래서 요청당 비용(SQL 수, 지연, 처리량, CPU)과 그 비용이 데이터 수에 비례해 늘어나는지로 판정한다. + +| 지표 | 재는 법 | 결함 신호 | +| --- | --- | --- | +| 아티팩트 | bootJar 크기, `BOOT-INF/lib` 목록 | 운영 jar에 테스트용·중복 라이브러리 | +| 기동 | `Started … in`, 기동 3초 뒤 RSS·heap, 빈 수, 스레드 수 | 빈 수에 비해 긴 공백 한 곳 | +| 요청당 SQL 수 | PostgreSQL `log_statement='all'`로 요청 하나 전후의 문장 수 | 페이지 크기에 비례(N+1) | +| 지연·처리량 | 닫힌 루프 부하, p50·p95·p99·rps | 목록 처리량이 SQL 수 비율만큼 떨어짐 | +| 요청당 CPU | JFR `settings=profile`, 상위 프레임 | 한 라이브러리가 CPU의 큰 몫 | +| 데이터 증가 | 같은 요청을 행 수를 늘려 반복 | 행 수에 비례해 느려짐 | +| 게이트 시간 | 게이트별 rc·초, 테스트 결과 XML 합계 | 바뀐 것이 없는데 매번 다시 도는 lane | + +측정 조건(전후가 같아야 비교할 수 있다): + +- 머신: 다른 빌드가 돌지 않는다. 측정 직전 1분 load average를 회차마다 적는다. 15를 넘은 회차는 비교에 쓰지 않는다. +- JVM: 옵션을 고정하고 적는다(예: `-Xmx1g -XX:+ExitOnOutOfMemoryError`). +- DB: 자원을 제한한 컨테이너(예: `--cpus 4 --memory 1g`), 튜닝 없음. +- 데이터: 행 수를 정해 적는다. 측정 중 늘어나는 테이블은 행 수를 함께 적는다. +- 부하: 닫힌 루프 N 스레드, 앞 20%는 워밍업으로 버린다. 생성기가 같은 호스트면 한계로 적는다. +- 반복: 3회, 중앙값. 튀는 회차는 이유와 함께 빼고 적는다. +- 설정만 바꾼 실험으로 원인을 먼저 확인한다(코드는 그대로, 시스템 프로퍼티 하나만). +- 측정은 E3다. "운영에서 N배 빨라진다"고 쓰지 않는다. 꼬리 지연의 원인을 확인하지 않았으면 미검증으로 적는다. + +최적화를 고르는 순서는 비용이 작은 것부터다: 설정 → DB(인덱스, 유일 제약, 쿼리 모양) → 매핑·쿼리 코드(N+1, 불필요한 컬렉션 재작성) → 구조(캐시, 비동기, 새 인프라). 캐시를 넣으면 무효화와 경합을 함께 검증한다. 고친 비용은 SQL 수처럼 머신과 무관한 숫자로 먼저 고정한다. + +## 9. 구조 기준과 leaf 변경 체크리스트 + +- 모듈 구조는 디렉터리가 아니라 registry가 정한다. 폴더를 바꾸는 일은 registry를 바꾸는 일이다. +- 문서는 leaf 목록·개수·leaf별 명령을 적지 않는다. leaf 명령은 registry의 `gradle_path`에서 만든다. +- 새 업무 기능은 계층 leaf 안의 패키지가 기본이다(`docs/manual/03-placement.md`). +- 템플릿 패키지 목록은 `src/application-core/CLAUDE.md` 「Package ownership」 표 하나가 정본이다. 템플릿에 패키지를 더하면 같은 변경에서 표에 넣는다. +- capability는 자기 `AutoConfiguration.imports`로 켜진다. `app-bootstrap`은 capability 이름·스위치 목록·scan 정규식을 갖지 않는다. +- vendored family(`messaging:*`, 같은 방식의 `grpc:*`)는 `domain-core`·`application-core`·`shared-contract`에 의존하지 않는다. 그래서 남는 복사본은 이유를 family `CLAUDE.md`에 적고, 값이 같아야 하면 대조 테스트를 둔다. +- source set은 runtime·classpath·외부 인프라·JVM 옵션·실행 비용 중 하나가 다를 때만 나눈다. 공유 테스트 코드는 `src/testFixtures/java`다(`docs/adr/ADR-BUILD-001-one-convention-for-shared-test-code.md`). +- 마이그레이션은 저장소마다 자기 디렉터리와 history table을 가진다. 번호는 스트림 안의 순번이다. 어딘가에 적용된 파일은 고치지 않는다(`src/adapter/outbound/persistence-jpa/src/test/resources/db/applied-migrations.sha256`이 해시를 고정한다). +- 문서 위치 규칙은 `docs/README.md`가 정본이다. + +leaf를 더하거나 옮기거나 지울 때 같은 변경에서 함께 바꾼다: + +- [ ] `src/config/architecture/modules.json`: ID, `source_path`, `gradle_path`, `allowed_dependencies` +- [ ] leaf `build.gradle`: `ca.java-library`·`ca.spring-library`·`ca.platform-module` 중 하나 +- [ ] lockfile(`verifyDependencyLocks`가 통과하게 다시 만든다) +- [ ] capability면 `src/app-bootstrap/build.gradle`의 `runtimeOnly` 한 줄과 자기 `AutoConfiguration.imports` +- [ ] leaf `CLAUDE.md`, capability면 README 세 가지(제공하는 것, 추가할 한 줄, 필요한 env 키) +- [ ] 템플릿 패키지를 더하거나 지우면 「Package ownership」 표 +- [ ] ArchUnit 규칙과 그 위반·허용 fixture +- [ ] 지운 leaf를 가리키던 문서·workflow·주석(grep으로 찾는다) +- [ ] 파생 서비스에 영향이 있으면 `docs/upgrade/`의 안내 행 + +검증은 [gates.md](gates.md) 2절의 "leaf 경계·의존·registry" 행이다. + +## 10. 리뷰 문서 양식 + +**위치**: 전체 리뷰는 `docs/reviews/-<종류>/README.md` + 영역 문서 `NN-<영역>.md`. 확인 리뷰는 그 폴더 아래 `roundN/`. 리뷰 문서는 리뷰 시점 기록이다. 수정 뒤에도 영역 문서를 고치지 않고 처리 결과는 README에 적는다. + +**전체 리뷰 README의 절** (가이드 36.5절 양식에 처리 현황·결정 기록을 더한 것): + +1. 사용 결정 — 용도별 사용 가능·조건부·보류와 막는 항목 +2. 차단 항목(High·P1) — 맡긴 쪽의 재확인 방법을 칸으로 +3. 확인된 강점 +4. 반복되는 원인 — [defect-patterns.md](defect-patterns.md) 번호를 붙인다 +5. 결정이 필요한 것 — 선택지, 권고, 승인자 +6. 미검증 — 무엇, 왜, 확인하려면 +7. 개선 순서 — 순서, 대상, 이유, 완료 기준 +8. 재검토 조건 +9. 리뷰 범위 — 기준 커밋, 게이트 결과 표, 영역 표 +10. 28개 관점 판정 +11. 발견 색인 — ID, 심각도, 우선순위, 한 줄 내용. 모든 ID를 이름으로 적는다 +12. 이후 라운드 — 처리 표, 합칠 때 생긴 충돌과 처리, 합친 뒤 게이트, 결정, 남은 것 + +**영역 문서**: 범위 → 지난 발견 재확인 → 새 발견 → 시나리오 추적 → 설계 선택 검토(가이드 41절) → 리팩터링 후보 → 28개 관점 판정표. + +**확인 리뷰 문서**: + +| 절 | 적을 것 | +| --- | --- | +| 범위 | pathspec, `git diff --stat` 결과, 함께 읽은 주변 코드, 수정 보고의 「새로 가정하는 것」 | +| 불러온 스킬과 적용한 기준 | 스킬, 그 스킬의 기준, 그 기준으로 본 것 | +| 실행한 명령과 결과 | 명령, rc, 직전 1분 부하 | +| 못 본 것 | 무엇과 이유 | +| 항목 재확인 | 고쳤다고 한 항목마다 닫힘 / 부분 / 안 닫힘 | +| 결함 | `### · <심각도> · <한 줄 제목>` 아래 발견 필드 | +| Declined to judge | 판단하지 않은 것, 위치, 이유 | +| 결론 | Critical·Important·회귀 수, 결함 수와 "이번 수정 / 이전부터" 구분 | + +**발견 하나의 필드** + +- 전체 리뷰: 가이드 36.3절 표 필드 전체(성격, 관련 관점, 근거, 발생 조건, 영향, 심각도, 확실성, 결정의 근거, 이해 비용, 최소 개선 방향, 대안 비교, 단순화의 보존 조건, 비용, 재검토 조건, 완료 기준, 검증 방법). 선택 비교가 필요 없는 단순 결함은 설계 선택 필드를 `적용 제외 — <이유 한 문장>`으로 둔다. +- 확인 리뷰: 위치(`file:line`, 문서·설정·코드를 나눠서), 무엇이 틀렸나(한 문장에 사실 하나), 발생 조건·영향, 테스트가 못 본 이유, 고치는 법(권장안·대안·RED 테스트 모양), 이번 수정 / 이전부터, 증거(E 수준과 명령 번호). + +**ID** + +- 라운드 안에서는 `NN-MM`(영역-순번)이다. 확인 리뷰는 라운드 접두어를 붙여 `RR-NN-MM`으로 쓴다(첫 재리뷰만 `` 없이). +- 라운드 밖(다른 문서, 커밋, 주석)에서는 리뷰 폴더 날짜의 월일을 붙인다: `MMDD/`(가이드 36.3절). +- 영역 번호 자리에 `NN` 같은 자리표시자를 남기지 않는다. 리뷰가 끝난 뒤 영역 접두어를 바꾸지 않는다. +- ID는 리뷰 문서·brief·커밋에서 쓴다. 매뉴얼(`docs/work/`) 본문에는 쓰지 않는다. + +## 11. 판단을 적는 법 + +- 판단 발견(설계·구조·비용)은 반증할 수 있는 가정과 반론을 함께 적는다. "이 판단이 틀렸다면 어디서 드러나나"를 쓴다. +- 결정적 발견(컴파일 오류, 의존 위반, 비밀 노출, 실패한 테스트)은 규칙 → 증거 → 고치는 법 세 줄로 쓴다. 억지 반론을 만들지 않는다. +- 대안이 3~5개 있으면 그만큼 비교한다. 실제로 더 적으면 적게 쓴다. 의존 순서가 있는 변경은 의존 그래프 순서로 따진다. +- 인용 확인은 리뷰 수준에 따른다: `review-lite`는 확인하지 않는다, `review-standard`는 차단 발견의 인용을 확인한다, `audit-deep`·`regulated`는 결론에 쓰인 인용을 모두 확인한다. +- 리뷰 결과를 문서 파일로 남기는 경우: 위험이 높다, 차단 발견이 3건 이상이다, 아키텍처 결정이 있다, 요청자가 원한다, `regulated` 수준이다. 그 밖에는 짧은 결과 보고로 충분하다. + +## 12. 리뷰어가 하지 않는 것 + +- 코드를 고치지 않는다. 실험은 별도 worktree에서 하고 지운다. +- 이전 실행 결과를 현재 증거로 쓰지 않는다(4절). +- 같은 결함을 여러 번 세지 않는다(3절). +- 정한 결정을 결함으로 다시 올리지 않는다. 결정의 전제가 틀렸다는 새 증거가 있을 때만 근거와 함께 다시 연다([decisions.md](decisions.md) 1절). +- 범위 밖 결함을 버리지 않는다. 「Declined to judge」에 위치와 함께 적어 맡긴 쪽에 넘긴다. diff --git a/docs/work/research-design.md b/docs/work/research-design.md new file mode 100644 index 00000000..de9d32a8 --- /dev/null +++ b/docs/work/research-design.md @@ -0,0 +1,90 @@ +# 조사·설계 — 바꾸기 전에 대안을 비교하고 결정을 받는다 + +코드를 바꾸기 전에 무엇을 할지 정하는 일이다. 사고 순서(목적 → 선행 사례 → 방법 → 필요한 정보 → 격차 → 만들고 시험)의 정본은 design-docs `conventions/work-thinking-order.md`다. 이 playbook은 순서를 다시 쓰지 않고, 이 repo에서 어디를 보고 결과를 어디에 두는지만 정한다. + +## 1. 언제 쓰나 + +- 고치거나 만들기 전에 소유자 결정이 필요하다(공개 계약, 파생 서비스 동작, 보안 정책, 새 leaf, 되돌리기 비싼 선택). +- 리뷰가 "판단하지 않음"으로 남긴 항목을 어떻게 닫을지 정해야 한다. +- 큰 일의 1~5단계와 대안 비교를 소유자 검토용으로 만든다. +- 설계 메모 하나를 쓴다(예: 레지스트리의 칸 하나를 규범으로 둘지). +- 결정이 이미 [reference/decisions.md](reference/decisions.md)에 있으면 이 playbook이 아니다. 그 결정대로 [improve.md](improve.md)나 [new-feature.md](new-feature.md)로 간다. + +## 2. 받아야 할 것 + +- 정할 질문 한 문장과 누가 왜 묻는가(요청 원문). +- 크기와 결정할 사람. 큼이면 소유자 검토가 만들기 전에 있어야 한다. +- 산출물 위치(4절 6단계 기준과 다르면 brief를 따른다). +- 코드를 바꿔도 되는지. 기본은 바꾸지 않는다. + +## 3. 크기와 사고 순서 + +- 설계 메모 하나는 보통 중간이다: 선행 사례 2~3곳(내부 선례 포함), 대안 2~3개. +- 새 체계·아키텍처·공개 계약은 큼이다: 선행 사례 10~15곳, 대안 3~5개. 1~5단계 결과와 대안 비교를 소유자가 먼저 본다. +- 이 repo의 내부 선례를 찾는 곳: + - [reference/decisions.md](reference/decisions.md)와 그 출처 문서 + - `docs/reviews/`의 리뷰 README 「결정」 절과 영역 문서의 「Declined to judge」 + - `docs/adr/`(되돌리기 비싼 선택), `docs/superpowers/specs/`(설계서), `docs/superpowers/plans/`(계획서) + - `git log --oneline -- <경로>`와 커밋 본문의 "고른 방법과 버린 대안" + - 가장 가까운 `src/**/CLAUDE.md`와 모듈 README +- 외부 선례: 쓰는 라이브러리의 공식 문서와 릴리스 노트(Spring Boot, Flyway, Hibernate 등), 같은 문제를 다룬 공개 저장소. 직접 쓴 글(1차)인지 정리한 글(2차)인지 표시한다. +- 스킬: `superpowers:brainstorming`, 결정 기록은 `documentation-and-adrs`, 공식 문서 확인은 `source-driven-development`. 큰 판단은 `doubt-driven-development`로 반론을 세운다. + +## 4. 절차 + +1. 목적을 한 문장으로 적고 성공 기준을 정한다. 요청 원문이 있으면 인용한다. +2. 이미 정한 것을 찾는다(3절의 내부 선례). 이미 정해져 있으면 멈추고 그 결정을 보고한다. +3. 현황을 확인한다. 주장마다 출처를 단다: `file:line`, 커밋, 명령 결과. 실제 동작이 궁금하면 별도 worktree에서 탐침 테스트를 desktop으로 돌리고, 탐침 코드는 남기지 않는다. +4. 선행 사례 표를 만든다: 출처 · 1차/2차 · 그들이 한 것 · 실패와 비판 · 가져올 것. +5. 대안을 비교한다. 실제로 다른 대안 2~5개(크기에 맞게), 기준(효과, 비용, 되돌리기, 파생 서비스 영향, 기존 결정과 충돌), 권하는 안과 이유. 의존 순서가 있는 변경은 의존 그래프 순서로 따진다. +6. 반증할 수 있는 가정을 적는다: "이 안이 틀렸다면 어디서 드러나나". 반론과 답도 적는다. +7. 산출물을 둔다. + - 이 repo에만 해당: 설계서 `docs/superpowers/specs/-<주제>-design.md`, 되돌리기 비싼 선택이면 `docs/adr/ADR-<영역>-<번호>-<제목>.md`(기존 번호를 잇는다). + - 여러 repo나 소유자 운영에 걸침: design-docs. 템플릿 `docs/`는 파생 서비스로 복사되므로 로드맵·운영 설계는 여기에 두지 않는다. + - 짧은 설계 메모는 보고 본문으로 충분하다(brief가 파일을 요구하지 않으면). +8. 소유자 결정 목록을 쓴다: 항목 · 선택지 · 권하는 안과 이유 · 정할 사람. 한 번에 묻는다. +9. 멈추고 검토를 받는다. 승인을 받으면 승인 시각을 적는다. +10. 결정을 기록한다([reference/decisions.md](reference/decisions.md) 3절). 만들기는 [new-feature.md](new-feature.md)나 [improve.md](improve.md)로 넘긴다. + +## 5. 완료 기준 + +- 보고에 사고 순서 흔적이 있다. 크기에 맞는 단계가 있고, 생략한 단계는 이유가 한 줄 있다. +- 사실마다 출처(`file:line`, 커밋, 명령 결과)가 있다. 추정은 추정이라고 적었다. +- 대안 비교 표, 권하는 안, 반증할 수 있는 가정이 있다. +- 소유자 결정 목록이 있고, 질문을 보냈거나 승인 시각이 있다. +- brief가 허용하지 않았으면 코드가 바뀌지 않았다(`git diff --stat`에 문서만). + +## 6. 하지 말 것 + +- 소유자 검토 전에 만들지 않는다. 큰 일은 1~5단계와 대안 비교까지만 하고 멈춘다. +- 크기를 스스로 내리지 않는다. +- 이미 정한 결정을 다시 묻지 않는다. 다시 열 조건은 [reference/decisions.md](reference/decisions.md) 1절이다. +- "업계 표준이다", "추상화가 많다" 같은 말을 근거로 쓰지 않는다. 이 repo의 어느 계약·비용에 닿는지로 쓴다. +- 대안을 하나만 놓고 권하지 않는다. +- 탐침 코드를 제품 코드에 남기지 않는다. + +## 7. 막혔을 때 + +- 필요한 정보가 이 repo와 공개 자료에 없으면(운영 수치, 소유자의 계획) 그 칸을 "모름"으로 두고 질문 목록에 넣는다. +- 질문은 한 번에 모아 보낸다. 형식은 [README](README.md) 5절이다. 답이 올 때까지 그 결정에 기대는 단계만 멈춘다. + +## 8. 보고 형식 + +[README](README.md) 6절에 더해 적는다. + +```markdown +## 결론 (권하는 안 한 문장) +## 사고 순서 흔적 (크기: 중간) +1. 목적: 2. 선행 사례: 3. 방법: 4. 필요한 정보: 5. 격차: 6. 만들고 시험: +## 대안 비교 +| 대안 | 효과 | 비용 | 되돌리기 | 기존 결정과 충돌 | +## 반증할 수 있는 가정 / 반론과 답 +## 소유자가 정할 것 +| 항목 | 선택지 | 권하는 안과 이유 | 정할 사람 | +``` + +## 9. 자주 하는 실수 + +- 정리한 글(2차)을 원문처럼 인용한다. 원문을 찾아 확인하고 1차/2차를 표시한다. +- 지난 리뷰의 결정을 찾지 않아 같은 질문을 다시 한다. 결정 색인과 리뷰 README 「결정」 절부터 본다. +- 조사하다 바로 고친다. 고치는 일은 결정 뒤에 다른 playbook으로 한다. From d04de2e85f8f775d1585a480b04f18004308b8c5 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 6 Nov 2026 20:00:49 +0900 Subject: [PATCH 04/71] =?UTF-8?q?docs(work):=20=ED=99=95=EC=9D=B8=20?= =?UTF-8?q?=EB=A6=AC=EB=B7=B0=20=EC=83=81=ED=95=9C=EC=9D=84=20=EB=84=98?= =?UTF-8?q?=EB=8A=94=20=ED=95=9C=20=EC=BB=A4=EB=B0=8B=EC=9D=80=20=EC=98=81?= =?UTF-8?q?=EC=97=AD=20pathspec=EC=9C=BC=EB=A1=9C=20=EB=82=98=EB=88=88?= =?UTF-8?q?=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: improve.md 4.4절은 확인 리뷰 하나가 보는 수정 diff를 추가 1,500줄로 묶고, 넘으면 "묶음 커밋별로" 나누라고만 했다. 여러 영역 묶음을 한 커밋에 합친 수정(예: 영역 묶음 넷을 합친 +5,143줄 커밋)은 커밋으로 나눌 수 없어, 그 확인 리뷰를 맡은 세션이 어떻게 나눌지 답이 없었다. 고른 방법: 커밋이 따로 있으면 커밋별로, 한 커밋에 섞였으면 영역 pathspec별로 `git diff --shortstat .. -- `를 재서 각각 상한 안이 되게 나눈다. 지난 확인 리뷰도 영역 4개를 pathspec으로 나눠 봤다. 위험·한계: pathspec 하나가 그 자체로 1,500줄을 넘으면 더 나눌 기준은 아직 없다. 그때는 그 영역을 맡은 리뷰를 둘로 나누거나 맡긴 쪽에 묻는다. 검증 - python3 scripts/check-work-docs.py: rc=0, improve.md 132/150 --- docs/work/improve.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/work/improve.md b/docs/work/improve.md index 954ea146..39f3a8e2 100644 --- a/docs/work/improve.md +++ b/docs/work/improve.md @@ -68,7 +68,7 @@ ### 4.4 수정 묶음의 크기 - 묶음 하나는 리뷰 영역 하나 안이고 발견 8건 이하다. 묶음마다 커밋 하나다. -- 확인 리뷰 하나가 보는 수정 diff는 추가 1,500줄 이하다(`git diff --shortstat ..`, 테스트 포함, lockfile·스냅숏 같은 생성 파일 제외). 넘으면 묶음 커밋별로 나눠 따로 확인 리뷰한다. +- 확인 리뷰 하나가 보는 수정 diff는 추가 1,500줄 이하다(`git diff --shortstat ..`, 테스트 포함, lockfile·스냅숏 같은 생성 파일 제외). 넘으면 확인 리뷰를 나눈다. 묶음 커밋이 따로 있으면 커밋별로, 한 커밋에 여러 영역이 섞였으면 영역 pathspec별로(`git diff --shortstat .. -- `) 나눠 각각 상한 안이 되게 한다. - 왜: 지난 수정 라운드에서 추가 줄이 2,000줄 아래면 다음 확인 리뷰 발견이 9건 이하였고, 5,000줄을 넘으면 19건 이상이었다([evidence.md](evidence.md) 「수정 묶음 크기」). 상한 값은 판단이다. 라운드당 새 결함 수로 다시 맞춘다. - 묶음을 합친 트리는 따로 검증한다([reference/gates.md](reference/gates.md) 「라운드 끝」). 두 묶음의 수정은 한 트리에서 처음 만날 때 새 결함을 만든다. From 1a4046f62f74462c5106b7dcb5bf830d2b8169a7 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 6 Nov 2026 20:02:27 +0900 Subject: [PATCH 05/71] =?UTF-8?q?docs(claude):=20=EC=A7=80=EB=8F=84?= =?UTF-8?q?=EC=9D=98=20=EC=8B=A4=ED=96=89=20=EC=9C=84=EC=B9=98=20=EB=AC=B8?= =?UTF-8?q?=EC=9E=A5=EC=9D=84=20=EA=B3=A0=EC=B9=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit "이 repo 소유자 환경에서 desktop에서만"을 "소유자 환경에서는 desktop에서만"으로 고친다. 뜻은 같다. 검증 - python3 scripts/check-work-docs.py: rc=0 --- CLAUDE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CLAUDE.md b/CLAUDE.md index 2bcb271e..4782a4d7 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -37,7 +37,7 @@ brief(작업 지시문)가 있으면 brief의 범위·크기·완료 기준이 ## 4. 검증 명령과 실행 위치 -- **실행 위치**: Gradle·Docker·테스트·게이트는 이 repo 소유자 환경에서 desktop에서만 돌린다. 절차는 [docs/work/operate.md](docs/work/operate.md) 4.1절이다. +- **실행 위치**: 소유자 환경에서는 Gradle·Docker·테스트·게이트를 desktop에서만 돌린다. 절차는 [docs/work/operate.md](docs/work/operate.md) 4.1절이다. - **leaf 하나**: registry에서 그 leaf의 `gradle_path`를 읽고 `./gradlew :test --console=plain` 또는 `:check`를 돌린다. 기억이나 디렉터리 이름으로 Gradle path를 짐작하지 않는다. - **저장소 전체 질문**: From e6b6e18eae73aab8b19546a2f4458ed3d7a2198b Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 6 Nov 2026 20:33:47 +0900 Subject: [PATCH 06/71] =?UTF-8?q?fix(strict-lane)!:=20=EC=84=B1=EB=8A=A5?= =?UTF-8?q?=20lane=EC=9D=B4=20=EC=83=81=ED=95=9C=EC=9D=84=20=EC=9E=AC?= =?UTF-8?q?=EC=A7=80=20=EC=95=8A=EA=B3=A0=20=ED=86=B5=EA=B3=BC=ED=95=98?= =?UTF-8?q?=EC=A7=80=20=EB=AA=BB=ED=95=98=EA=B2=8C=20=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 성능 lane의 기계 의존 상한(httpclient 스트리밍 힙 증가, Mongo 시간 gate)이 performance.assertions.enabled 뒤에 있었고 기본값이 자리마다 달랐다(httpclient build false, Mongo build true, Mongo 테스트 코드 false). workflow만 GRADLE_OPTS로 켰다. 그래서 desktop에서 손으로 돌린 ./gradlew :performanceCheck가 httpclient 힙 상한을 재지 않고 통과했다 (2026-11-05 r10 게이트). JPA pool lane도 전에 같은 속성 뒤에서 아무 상한도 비교하지 않았다(PoolLaneClaimTest). 방법: 규칙을 build-logic strict-lane convention 한 곳에 둔다. - PERFORMANCE lane 테스트 JVM에 performance.assertions.enabled=true를 넣는다. 빌드(-P, GRADLE_OPTS)나 lane(systemProperty, jvmArgs, task 설정)이 true 아닌 값을 주면 테스트 전에 실패하고, 지우거나 true로 바꾸라고 알려 준다. true는 받아 준다(파생 서비스 workflow가 넘긴다). - PERFORMANCE lane은 skip된 테스트가 있으면 실패한다. - httpclient·Mongo 테스트는 조건 없이 단언하고 잰 값을 한 줄 남긴다. 두 leaf의 속성 선언과 integration-main·release workflow의 GRADLE_OPTS 줄을 지웠다. 사람과 workflow가 같은 명령을 쓴다. verifyStrictLaneStages가 읽는 run: 줄은 그대로다. 버린 대안: 두 leaf 기본값만 true로(정의가 leaf마다 남아 다음 lane이 다시 복사한다), 속성 삭제만(옛 속성을 기본값 false로 읽는 파생 서비스 테스트가 조용히 건너뛴다), 측정 전용 태스크(쓸 곳이 없다: 숫자만 볼 때는 JMH, 실패한 단언과 매 실행 출력이 값을 남긴다). 같은 원인으로 함께 고친 문서: httpclient support-matrix·release-checklist의 없는 lane 이름 spring62CompatibilityTest와 빠진 main push 주기. 위험·한계: 손으로 돌린 performanceCheck가 이제 상한을 실제로 재므로 느린 기계에서는 실패할 수 있다. JVM 인자 공급자(jvmArgumentProviders)가 넣는 -D는 보지 않는다. Docker가 없을 때 skip되는 통합·시스템 lane은 지금 모두 실패한다(전부 skip이면 executed no test, 아니면 skip 안 되는 컨테이너 테스트가 실패) — 거짓 통과가 아니어서 고치지 않았다. 검증(desktop ~/b4-logs, flock 아래, 노트북과 같은 트리 — git diff sha256 일치): - RED(고치기 전 트리 + 새 테스트): build-logic 새 테스트 4건이 UnexpectedBuildSuccess로 실패 — aPerformanceLaneFailsOnAnExceededBound WhenTheBuildSetsNoAssertionsProperty, …FailsBeforeTestingWhenTheBuild TurnsItsAssertionsOff, …FailsWhenItsOwnDeclarationTurnsTheAssertionsOff, …FailsWhenOneOfItsTestsIsSkipped. jvmArgs 경로(…FailsWhenItsJvmArguments TurnTheAssertionsOff)도 같은 실패. 실제 lane: 속성 없이 httpClientPerformanceTest rc=0인데 "skipped machine-dependent bound" 출력. - GREEN: -p build-logic check javadoc rc=0. :performanceCheck rc=0(lane 5개 테스트 26, skip 0; httpclient 힙 증가 5,243,880 B / 상한 16,777,216 B, Mongo p50·p95·p99 1ms, examined/returned 1.0, pool 대기 0). -p optional-platforms performanceCheck rc=0(grpc 1). 두 명령에 -Pperformance.assertions.enabled=false → rc=1, 6개 lane 모두 테스트 전 실패. =true → rc=0. verifyStrictLaneStages --dry-run 두 빌드 rc=0, architectureCheck rc=0, ci·mainCheck·integrationCheck·releaseCheck· performanceCheck --dry-run --configuration-cache rc=0, :mainCheck --continue --warning-mode=fail rc=0, -p optional-platforms ci rc=0, persistence-mongo:check rc=0, verify-httpclient-docs.py rc=0. - 이 변경 밖 실패: :ci :verifyDependencyLocks --continue와 httpclient:check가 CircuitBreakerStatusAccountingTest JDK 2건으로 rc=1. 기준 커밋 3d73b6f1에서도 10/10 실패(이 트리도 10/10). ci의 다른 task는 모두 통과했다. Refs: docs/upgrade/2026-11-maturity-review.md B-43, docs/testing/TESTING_STRATEGY.md 6절 BREAKING CHANGE: PERFORMANCE lane은 performance.assertions.enabled가 true가 아니거나 skip된 테스트가 있으면 실패한다. 자기 성능 lane의 그 속성 선언(false)과 skip을 없앤다. --- .github/workflows/integration-main.yml | 5 +- .github/workflows/release.yml | 4 - AGENTS.md | 6 +- CLAUDE.md | 7 +- docs/httpclient/performance-baseline.md | 17 +- docs/httpclient/release-checklist.md | 5 +- docs/httpclient/support-matrix.md | 22 +-- docs/testing/TESTING_STRATEGY.md | 16 ++ docs/upgrade/2026-11-maturity-review.md | 5 +- src/README.md | 2 +- src/adapter/outbound/httpclient/CLAUDE.md | 5 +- src/adapter/outbound/httpclient/README.md | 5 +- src/adapter/outbound/httpclient/build.gradle | 7 +- .../performance/LargeBodyResourceTest.java | 13 +- .../performance/PerformanceAssertions.java | 27 +-- .../outbound/persistence-mongo/build.gradle | 5 +- .../MongoResourceBudgetLaneTest.java | 18 +- src/build-logic/README.md | 2 +- .../strictlane/StrictTestLanePlugin.java | 84 ++++++++- .../strictlane/StrictTestLaneSpec.java | 6 + .../StrictTestLaneConventionTest.java | 167 ++++++++++++++++++ 21 files changed, 346 insertions(+), 82 deletions(-) diff --git a/.github/workflows/integration-main.yml b/.github/workflows/integration-main.yml index 7bd70230..2fdf8b10 100644 --- a/.github/workflows/integration-main.yml +++ b/.github/workflows/integration-main.yml @@ -189,13 +189,12 @@ jobs: # never catches. This job replaced `web-load-abuse-and-shutdown`, which despite its name ran # `:adapter:inbound:web:test` and `webJettyCompatTest` — two lanes the pull-request and main stages # already run — and never the load lanes (review 2026-11-01 08-01), and `httpclient-performance`. + # No assertions switch: the strict-lane convention asserts every performance lane's bounds, so this + # job and a person on a workstation run the same command and get the same bounds. performance-check: runs-on: ubuntu-latest timeout-minutes: 120 env: - # A project property rather than a command-line flag, so the run command stays a plain, - # verifiable task invocation while the machine-dependent bounds are still asserted. - GRADLE_OPTS: -Dorg.gradle.project.performance.assertions.enabled=true TESTCONTAINERS_REUSE_ENABLE: "false" steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # actions/checkout@v4.2.2 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 8cdecab9..654739fe 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -160,10 +160,6 @@ jobs: defaults: run: working-directory: src - env: - # A project property rather than a command-line flag, so each run command stays a plain, - # verifiable task invocation while the machine-dependent bounds are still asserted. - GRADLE_OPTS: -Dorg.gradle.project.performance.assertions.enabled=true steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # actions/checkout@v4.2.2 - uses: ./.github/actions/setup-gradle-java diff --git a/AGENTS.md b/AGENTS.md index b37bbaf3..063bf11f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -73,6 +73,10 @@ root `CLAUDE.md`는 이 목록의 동기화된 요약이다. 두 문서가 어 `INTEGRATION`·`SYSTEM`·`PERFORMANCE` lane과 `mainStage()` lane은 이미지·네트워크·시간·문서처럼 입력으로 잡히지 않는 것에 기대므로 매번 다시 돈다. hermetic lane이 저장소 파일을 읽으면 그 파일을 입력으로 선언해야 캐시가 거짓 통과를 내지 않는다. +- `PERFORMANCE` lane은 상한을 매번 단언한다. 끄는 스위치가 없다: convention이 테스트 JVM에 + `performance.assertions.enabled=true`를 넣고, 빌드(`-P`·`GRADLE_OPTS`)나 lane이 다른 값을 주면 + 테스트 전에 실패한다. skip된 테스트가 하나라도 있어도 실패한다(`rejectSkipped`를 따로 쓰지 않아도). + 사람이 손으로 돌리는 `./gradlew performanceCheck`와 workflow가 같은 상한을 단언한다. - `verifyEnvKeys`는 app-bootstrap 태스크로 유지한다(소유자 결정 4). 구현은 build-logic의 `ca.config-contract`다. `src/build-tools/` included build는 비워서 삭제했다. - `src/build.gradle`: 루트 라이프사이클(`ci`, `mainCheck`, `integrationCheck`, `performanceCheck`, @@ -222,7 +226,7 @@ cd src ./gradlew ci # PR 게이트 = leaf check + architecture + quality ./gradlew mainCheck # main 단계 = env 계약·전체 기동(샘플 포함)·public path·전송/메시징 레인·leaf 문서 대조 레인·기능 생성 왕복(verifyFeatureScaffold)·테스트 코드 정적 분석(testQualityCheck) ./gradlew integrationCheck # 실제 컨테이너 integration 레인 전체(main·nightly, Docker 필요) -./gradlew performanceCheck # 부하·종료·자원 한계 레인(main·nightly) +./gradlew performanceCheck # 부하·종료·자원 한계 레인(main·nightly). 상한은 항상 단언, 끄면 실패 ./gradlew verifyStrictLaneStages --dry-run # 이 빌드의 strict lane이 workflow가 실행하는 단계에 속하는지(optional 빌드는 -p optional-platforms로 따로) ./gradlew verifyPublicPathSnapshot ./gradlew :app-bootstrap:verifyEnvKeys diff --git a/CLAUDE.md b/CLAUDE.md index 4921a632..396f0dab 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -33,7 +33,9 @@ If this summary drifts from `AGENTS.md`, `AGENTS.md` wins and this summary must in that leaf's `mainCheck`; a merge-blocking contract over non-document repository files is a pull-request lane whose inputs are exactly those files (app-bootstrap `repository-contract`). `TEST`/`ARCHITECTURE` lanes are cacheable; `INTEGRATION`/`SYSTEM`/`PERFORMANCE` and main-stage - lanes rerun every time. + lanes rerun every time. A `PERFORMANCE` lane asserts its bounds in every run and rejects skipped + tests: the convention sets `performance.assertions.enabled=true`, and a build or lane that sets + anything else fails before a test runs. - `verifyEnvKeys` stays an app-bootstrap task (owner decision 4); its implementation is build-logic's `ca.config-contract`. The `src/build-tools/` included build was emptied and removed. - `src/build.gradle`: the root lifecycle (`ci`, `mainCheck`, `integrationCheck`, `performanceCheck`, @@ -145,7 +147,8 @@ of domain-core/shared-contract/application-*, Git-carryable sources, ArchUnit), (SpotBugs, FindSecBugs over production code), `testQualityCheck` (the same over every test source set, against `config/spotbugs/exclude-test.xml`), `configContractCheck` (the environment contract), `integrationCheck` (the declared strict integration lanes; a lane that needs an input the build was not given is left out -and named), `performanceCheck` (the declared performance lanes; main and nightly). `ci` (pull +and named), `performanceCheck` (the declared performance lanes, bounds always asserted — the same +command by hand or in a workflow; main and nightly). `ci` (pull request) is leaf checks (API surfaces included, owner decision 20) + architectureCheck + qualityCheck, and the workflow also runs `verifyStrictLaneStages --dry-run`; `mainCheck` (main branch) is configContractCheck + qualificationCheck (which includes testQualityCheck) + the sample web contract + the sample full boot (`:sample-portfolio:systemTest`) diff --git a/docs/httpclient/performance-baseline.md b/docs/httpclient/performance-baseline.md index 7335d020..0a1ee87e 100644 --- a/docs/httpclient/performance-baseline.md +++ b/docs/httpclient/performance-baseline.md @@ -8,19 +8,20 @@ from an explicit profile setting. ## How to run ```bash -# structural bounds only (default; still executes every test) +# every bound, structural and machine-dependent ./gradlew :adapter:outbound:httpclient:httpClientPerformanceTest --console=plain -# full certification, including machine-dependent bounds -./gradlew :adapter:outbound:httpclient:httpClientPerformanceTest \ - -Pperformance.assertions.enabled=true --console=plain - -# JMH benchmarks +# JMH benchmarks: numbers only, never a gate ./gradlew :adapter:outbound:httpclient:jmh --console=plain ``` -Machine-dependent assertions are reported as explicitly skipped when the flag is absent — the lane -never silently degrades into a pass. +The lane asserts every bound in every run. There is no switch that turns the machine-dependent one +off: the strict-lane convention fails a performance lane before it runs when the build sets +`performance.assertions.enabled` to anything but `true`, and fails it when one of its tests is +skipped. The same command is what `integration-main.yml` (`:performanceCheck`) and `release.yml` +run. Every run prints the measured heap increase (`[httpclient-performance] streaming download heap +increase … bytes, bound … bytes`) to the test output and report, and a bound that fails repeats the +value in its assertion message; for numbers without a verdict, use JMH. ## Certified bounds diff --git a/docs/httpclient/release-checklist.md b/docs/httpclient/release-checklist.md index 6b21cf41..a11e0f7f 100644 --- a/docs/httpclient/release-checklist.md +++ b/docs/httpclient/release-checklist.md @@ -9,11 +9,10 @@ cd src ./gradlew :adapter:outbound:httpclient:test --console=plain ./gradlew :adapter:outbound:httpclient:httpClientStableContractTest --console=plain ./gradlew :adapter:outbound:httpclient:httpClientSecurityTest --console=plain -./gradlew :adapter:outbound:httpclient:spring62CompatibilityTest --console=plain +./gradlew :adapter:outbound:httpclient:spring62ApiSurfaceScan --console=plain ./gradlew :adapter:outbound:httpclient:spring70CompatibilityTest --console=plain ./gradlew :adapter:outbound:httpclient:httpClientFailureInjectionTest --console=plain # needs Docker -./gradlew :adapter:outbound:httpclient:httpClientPerformanceTest \ - -Pperformance.assertions.enabled=true --console=plain +./gradlew :adapter:outbound:httpclient:httpClientPerformanceTest --console=plain # every bound asserted ./gradlew verifyCleanArchitectureDependencies --console=plain ./gradlew :app-bootstrap:architectureTest --console=plain python3 ../scripts/verify-httpclient-docs.py diff --git a/docs/httpclient/support-matrix.md b/docs/httpclient/support-matrix.md index 7d3966c1..a253cfd9 100644 --- a/docs/httpclient/support-matrix.md +++ b/docs/httpclient/support-matrix.md @@ -57,19 +57,19 @@ gives route-scoped pooling and Dynamic Target pinning, JDK gives HTTP/2. | Profile | Frequency | Release gate | Task | |---|---|---|---| -| Spring Framework 7.0 (repository baseline) | every PR | required | `spring70CompatibilityTest` | -| Spring Framework 6.2 API surface | every PR | required | `spring62CompatibilityTest` | -| Apache HC5 + RestClient | every PR | required | `httpClientStableContractTest -Phttpclient.contract.transports=apache` | -| JDK HttpClient + RestClient | every PR | required | `httpClientStableContractTest -Phttpclient.contract.transports=jdk` | -| SSRF / cardinality suite | every PR | required | `httpClientSecurityTest` | -| Toxiproxy fault suite | nightly, release | required | `httpClientFailureInjectionTest` | -| Performance certification | nightly, release | required | `httpClientPerformanceTest -Pperformance.assertions.enabled=true` | -| Jetty HTTP/3 | nightly | Experimental, non-blocking | `test -Phttp3.tests.enabled=true` | +| Spring Framework 7.0 (repository baseline) | PR touching this leaf, main push, release | required | `spring70CompatibilityTest` | +| Spring Framework 6.2 API surface | every PR (`check`), release | required | `spring62ApiSurfaceScan` | +| Apache HC5 + RestClient | PR touching this leaf (both transports together on every PR through `check`), release | required | `httpClientStableContractTest -Phttpclient.contract.transports=apache` | +| JDK HttpClient + RestClient | PR touching this leaf (both transports together on every PR through `check`), release | required | `httpClientStableContractTest -Phttpclient.contract.transports=jdk` | +| SSRF / cardinality suite | every PR (`check`), release | required | `httpClientSecurityTest` | +| Toxiproxy fault suite | main push, nightly (`integrationCheck`), release | required | `httpClientFailureInjectionTest` | +| Performance certification | main push, nightly (`performanceCheck`), release | required | `httpClientPerformanceTest` (every bound asserted; no switch turns them off) | +| Jetty HTTP/3 | main push, nightly | Experimental, non-blocking | `test -Phttp3.tests.enabled=true` | ### Known limitation of the Spring 6.2 lane This repository's Spring Boot 4.0 baseline pins Spring Framework 7, so a real 6.2 runtime cannot be -resolved here. `spring62CompatibilityTest` therefore verifies the **API surface**: the common +resolved here. `spring62ApiSurfaceScan` therefore verifies the **API surface**: the common packages must not reference any Spring 7-only type, and no class uses `org.springframework.web.service.registry`. Executing the suite against an actual 6.2 distribution requires a host project on that line. This limitation is stated rather than hidden behind a passing @@ -83,5 +83,5 @@ Stated so the matrix is read as a measurement rather than an aspiration. | Gap | Why | What is proven instead | |---|---|---| | HTTP/2 frame injection (`REFUSED_STREAM`, arbitrary `GOAWAY`) | The fixture server exposes no frame-level control, and a purpose-built h2 server is a larger dependency than the guarantee is worth here | `Http2EvidenceMapperTest` proves the frame → evidence mapping, and `NegotiatedProtocolContractTest` proves h2 is really negotiated | -| Spring 6.2 runtime | This repository's Boot 4.0 baseline pins Spring 7 | `spring62CompatibilityTest` confines the common packages to the 6.2 API surface | -| Performance latency baseline | Numbers measured on a build agent are not a certification | `httpClientPerformanceTest` asserts structural bounds unconditionally; latency and heap bounds run under `-Pperformance.assertions.enabled=true` | +| Spring 6.2 runtime | This repository's Boot 4.0 baseline pins Spring 7 | `spring62ApiSurfaceScan` confines the common packages to the 6.2 API surface | +| Performance latency baseline | Numbers measured on a build agent are not a certification | `httpClientPerformanceTest` asserts its structural bounds and the streaming heap bound in every run; it asserts no latency figure | diff --git a/docs/testing/TESTING_STRATEGY.md b/docs/testing/TESTING_STRATEGY.md index 19e705ea..8f870afa 100644 --- a/docs/testing/TESTING_STRATEGY.md +++ b/docs/testing/TESTING_STRATEGY.md @@ -154,6 +154,22 @@ fixture는 **지원 코드**다. TEST/INTEGRATION/SYSTEM/ARCHITECTURE/PERFORMANC PERFORMANCE는 기본 로컬 `check`에 붙이지 않는다. 명시적 benchmark/performance task나 scheduled workflow가 실행한다. +PERFORMANCE lane은 상한을 매번 단언한다. 측정만 하고 통과하는 모드는 없다. + +- convention(`ca.strict-test-lane`)이 테스트 JVM에 `performance.assertions.enabled=true`를 넣는다. + leaf나 lane이 이 값을 따로 선언하지 않는다. +- 빌드가 `-Pperformance.assertions.enabled`(또는 `GRADLE_OPTS`의 + `-Dorg.gradle.project.performance.assertions.enabled`)에 `true` 아닌 값을 주거나, lane이 테스트 + JVM 값을 덮어쓰면 테스트 전에 실패한다. 메시지가 지우거나 `true`로 바꿀 곳을 알려 준다. +- skip된 테스트가 하나라도 있으면 실패한다. skip은 아무도 재지 않은 상한이다. +- 그래서 사람이 desktop에서 돌리는 `./gradlew performanceCheck`와 workflow가 같은 상한을 단언한다. +- 판정 없이 숫자만 보려면 JMH가 있는 leaf의 `./gradlew ::jmh`를 쓴다. 게이트가 아니다. + 실패한 상한은 잰 값을 단언 메시지에 남긴다. + +2026-11-05 desktop 게이트에서 httpclient lane이 이 속성 기본값 `false`로 돌아, 힙 상한을 재지 않고 +통과했다. 그 전에는 JPA pool lane이 같은 속성 뒤에 숨어 아무 상한도 비교하지 않았다 +(`PoolLaneClaimTest`). 이 규칙은 그 두 번을 되풀이하지 않기 위한 것이다. + ## 7. 새 테스트를 추가할 때 판단 순서 1. 실제 외부 인프라가 필요한가? diff --git a/docs/upgrade/2026-11-maturity-review.md b/docs/upgrade/2026-11-maturity-review.md index aaa5e736..ef50f035 100644 --- a/docs/upgrade/2026-11-maturity-review.md +++ b/docs/upgrade/2026-11-maturity-review.md @@ -4,7 +4,7 @@ - 커밋: `34565130` High·P1 19건 · `1400dc15` 남은 발견·매뉴얼·생성 명령 · `5786126c` 남은 항목과 합친 뒤 결함 · `7ef8d0b4` 재리뷰 기록 · `bbe944bd` 재리뷰 결함 · `ecc74b7d` 2차 재리뷰 기록·이 안내 · `1885bf8d` 2차 재리뷰 결함 · `339cf8fd` 3차 확인 리뷰 기록 · `f40c03c6` 3차 확인 리뷰 Minor · `c2e55510` 마지막 확인 리뷰 기록 · - `2678955c` 테스트 코드 정적 분석(B-40) · `70fb80bf` 소유자가 다시 정한 기본값 3가지(늦은 멱등 완료 기록, `failure-retention` 기동 검사, workflow `cd`) — `docs(...)` 커밋은 문서만 바꾼다 + `2678955c` 테스트 코드 정적 분석(B-40) · `70fb80bf` 소유자가 다시 정한 기본값 3가지(늦은 멱등 완료 기록, `failure-retention` 기동 검사, workflow `cd`) · B4 성능 lane 단언 상시화(2026-11-06, B-43) — `docs(...)` 커밋은 문서만 바꾼다 - 근거 문서: `docs/reviews/2026-11-01-maturity-review/README.md` 13~16절, `docs/reviews/2026-11-03-rereview/README.md` 4·6·8~13절, 각 커밋의 `BREAKING CHANGE:` 꼬리말 - 아래 표의 각 줄은 위 범위의 diff와 코드로 확인했다. 확인하지 못한 것은 그 자리에 "확인 못 함"으로 적었고 9절에 @@ -36,6 +36,7 @@ | 13 | `.env`에 옛 `.env.example` 값을 복사해 두었다면 5.6절 키를 다시 맞춘다 | 새 기본값이 안 먹거나(JDBC batch), 기동 실패(알림 콜백 상한) | `.env`를 복사해 쓰는 서비스 | | 14 | 자기 테스트 코드에 `./gradlew testQualityCheck`를 돌려 보고, 발견을 고치거나 이유를 단 Match로 뺀다(B-40) | `mainCheck`가 실패 | 테스트 코드가 있는 모든 서비스 | | 15 | staging·prod 배포 마이그레이션 도구에 `flyway.postgresql.transactional.lock=false`(환경 변수 `FLYWAY_POSTGRESQL_TRANSACTIONAL_LOCK=false`)를 넣는다. 자기 Flyway stream은 `Flyway.configure()` 대신 `FlywaySchemaPolicy.configure()`로 만든다(5절 「Flyway 잠금」) | `CREATE INDEX CONCURRENTLY`·`REINDEX … CONCURRENTLY` 마이그레이션에서 배포가 오류 없이 멈춘다. 자기 stream이 `Flyway.configure()`를 부르면 `:app-bootstrap:architectureTest` 실패 | persistence-jpa 선택 + 배포 도구로 마이그레이션하거나 자기 stream을 둔 서비스 | +| 16 | 자기 성능 lane(`performance()`)에서 `performance.assertions.enabled`를 `false`로 두는 `systemProperty` 줄을 지우고, 그 속성을 읽어 상한 단언을 건너뛰던 테스트는 항상 단언하게 고친다. 성능 lane의 `@Disabled`·assumption skip을 없앤다(B-43) | `performanceCheck`가 테스트 전에 실패(`its test JVM would get performance.assertions.enabled=false`)하거나 skip 때문에 실패(`forbids skipped tests`) | 자기 성능 lane이 있는 서비스 | ### 되돌릴 수 없는 것 @@ -109,6 +110,7 @@ | B-37 | app-bootstrap 테스트 lane 분리: 저장소 파일을 읽는 테스트는 태그 `document-contract`(main 단계) 또는 `repository-contract`(`check`)여야 하고, 일반 `test` lane에는 `ca.repository.root`가 없다 | app-bootstrap에 둔 자기 테스트가 저장소 파일을 읽으면 `test`에서 실패 | 태그를 단다 | `1400dc15` · `src/app-bootstrap/build.gradle` | | B-40 | 테스트 코드 정적 분석 `testQualityCheck`: SpotBugs·FindSecBugs를 main 밖 모든 source set(test, testFixtures, integrationTest, systemTest 등)에 돌린다. 테스트용 제외 목록은 `config/spotbugs/exclude-test.xml`(보안 범주·내부 상태 노출·생성자 예외·반환값 null 역참조·아키텍처 위반 fixture). 분석 classpath가 그 source set의 runtime classpath로 넓어졌고, 분석이 불완전하면(빠진 클래스) 실패한다. main 빌드는 `mainCheck`(`qualificationCheck`), optional 빌드는 `ci` | 자기 테스트 코드의 SpotBugs 발견(예: `CountDownLatch.await` 반환값 무시, 공유 변수 비원자 쓰기, 닫지 않은 `Statement`)이 main 단계를 막는다. 테스트 classpath에 없는 타입을 참조하면 `SpotBugs analysis incomplete` | 고치거나, 클래스·메서드로 좁힌 Match를 이유와 함께 `exclude-test.xml`에 더한다. 빠진 타입은 그 테스트 suite 의존성에 넣는다 | `2678955c` · `src/build-logic/.../quality/QualityConventionsPlugin.java`, `src/config/spotbugs/exclude-test.xml`, `src/build.gradle` | | B-42 | shared-contract 패키지 규칙 `SHARED_CONTRACT_CONTAINS_ONLY_OPERATIONAL_CONTRACT_PACKAGES`가 실제로 검사한다. 대상은 `dev.caskeleton.shared..`뿐이고, 허용은 목록의 패키지(`concurrency digest error metrics observability ratelimit request response retry runtime security tracing`)와 그 아래, 뿌리 패키지에는 `package-info`만이다. 전에는 뿌리를 허용 목록에 넣고 접두어로 비교해서 모듈 안은 아무것도 잡지 못했고, 다른 leaf의 `..shared..` 패키지를 잡았다 | `dev.caskeleton.shared`에 목록에 없는 패키지나 뿌리 클래스를 둔 파생 서비스는 architectureTest 실패. 다른 leaf의 `shared` 패키지는 더는 걸리지 않는다 | 업무 개념이면 그것을 소유하는 모듈로 옮긴다. 운영 계약이면 `ForbiddenApiArchitectureTest.SHARED_CONTRACT_PACKAGES`와 shared-contract CLAUDE.md 「Responsibility」에 함께 더한다 | r10 · `src/app-bootstrap/src/architectureTest/.../ForbiddenApiArchitectureTest.java`, `SharedContractPackageRuleTest.java` | +| B-43 | 성능 lane 단언 상시화: `performance()` lane은 convention이 테스트 JVM에 `performance.assertions.enabled=true`를 넣는다. 빌드가 `-P`·`GRADLE_OPTS`(`-Dorg.gradle.project.…`)로 `true` 아닌 값을 주거나, lane `systemProperty`·`jvmArgs`(`-D…`)·task 설정이 테스트 JVM 값을 `true` 아닌 값으로 덮으면 테스트 전에 실패한다. 성능 lane은 `rejectSkipped` 없이도 skip된 테스트가 있으면 실패한다. httpclient·Mongo leaf의 속성 선언과 `integration-main.yml` `performance-check`·`release.yml` `httpclient-release-gate`의 `GRADLE_OPTS` 줄을 지웠다. 측정만 하는 모드는 만들지 않았다(JMH가 그 용도) | `performanceCheck`·`::performanceTestLaneCheck`가 `is a performance lane, and this build sets performance.assertions.enabled=false`, `its test JVM would get performance.assertions.enabled=false`, `forbids skipped tests … a skipped test is a bound nobody measured` 중 하나로 실패 | `-Pperformance.assertions.enabled=false`를 지운다. 자기 lane의 그 `systemProperty`·`jvmArgs` 줄을 지우고, 그 속성을 읽던 테스트는 항상 단언하게 고친다. 성능 lane의 skip은 없애거나 그 테스트를 다른 lane으로 옮긴다. `GRADLE_OPTS=-Dorg.gradle.project.performance.assertions.enabled=true`·`-P…=true`는 받아 주므로 그대로 둬도 된다 | B4(2026-11-06) · `src/build-logic/.../strictlane/StrictTestLanePlugin.java`, `.../strictlane/StrictTestLaneConventionTest.java`(test), `docs/testing/TESTING_STRATEGY.md` 6절 | ### 3.5 모듈 registry·새 leaf @@ -240,6 +242,7 @@ V21 실패의 분류는 `docs/runbooks/migration-failed.md` "Classify the failur | 서버 로그(GraphQL·gRPC·STOMP) | carrier로 답한 실패를 web과 같은 줄(shared-contract `ServerFailureLog`)로 ERROR에 남긴다: persistence 실패는 분류만, 5xx carrier는 예외와 함께, 4xx carrier는 남기지 않는다. gRPC는 ` (method=…)`, GraphQL은 ` (executionId=…)`를 붙인다. gRPC는 인식 못 한 실패(`INTERNAL_ERROR`)도 `unhandled failure on …`로 남긴다. 클라이언트가 취소한 호출은 남기지 않고, 서비스가 `CANCELLED` status로 끝낸 살아 있는 호출은 남긴다. raw status는 넘겼든 던졌든 설명을 남기지 않는다(원인 예외가 있으면 그것만 붙인다). `IllegalArgumentException`(`BAD_PARAMETER`)은 web과 같은 WARN 한 줄 `request refused as BAD_PARAMETER by <예외 타입>`(메시지 없음)으로 남긴다. STOMP `@MessageMapping` 실패는 Spring의 `Unhandled exception from message handler method`(예외 전체) 대신 같은 줄로 남는다 | ERROR 로그가 늘어난다(전에는 gRPC가 아무것도 남기지 않았다). GraphQL·gRPC·STOMP는 잘못된 입력마다 WARN 한 줄이 생긴다. STOMP에서 Spring 문구로 경보를 걸었다면 고친다. `IDEMPOTENCY_RECOVERY_REQUIRED`의 scope digest를 모든 전송에서 찾을 수 있다(`docs/runbooks/idempotency-unavailable.md`) | r9 · `src/shared-contract/.../error/ServerFailureLog.java`, `GrpcExceptionHandlingInterceptor.java`, `GraphQlWireErrorMapper.java`, `StompHandlerFailureLog.java` | | sample-portfolio | 익명 쓰기 401, 포스터 제목 대소문자 무시 유일(409 `POSTER_ALREADY_EXISTS`), 관리자도 남의 work log 수정 불가, 샘플 이벤트 tenant `global` | sample을 남긴 서비스만 | `34565130`, `1400dc15` | | Flyway 잠금 | Flyway의 PostgreSQL 마이그레이션 잠금을 트랜잭션 대신 세션에 둔다. Spring Boot의 Flyway는 module-defaults `spring.flyway.postgresql.transactional-lock: false`, 템플릿이 직접 만드는 Flyway(멱등성·알림·sample stream, schema-per-tenant, testkit `MigrationContractRunner`)는 `FlywaySchemaPolicy.configure()`, messaging inbox stream은 같은 값을 직접 넣는다. 운영 코드의 `Flyway.configure()` 직접 호출은 `JpaProductionArchitectureTest`가 거부한다 | Flyway 기본값에서는 동시 인덱스 마이그레이션이 Flyway 자신의 열린 트랜잭션을 기다려 끝나지 않았다. 이제 끝난다. 마이그레이션은 잠금을 잡은 연결 하나로 돈다. transaction 모드 PgBouncer 뒤에서는 잠금 해제가 다른 서버 연결로 가 다음 배포가 기다릴 수 있으니 마이그레이션은 직접 연결이나 session 모드 pool로 돌린다. 배포 도구는 이 repo 밖이라 2절 15번으로 맞춘다 | 재리뷰 round6 RR6-03-01 · `persistence-jpa.yml`, `.../migration/FlywaySchemaPolicy.java`, `docs/jpa/migration-guide.md` "Who may change the schema"·"Concurrent index builds" | +| 성능 lane(HTTP client·Mongo) | httpclient `LargeBodyResourceTest`의 힙 상한(32 MiB 스트리밍 중 힙 증가 16 MiB 미만)을 매번 단언한다. 전에는 `-Pperformance.assertions.enabled=true`일 때만 단언하고 아니면 건너뛴다는 줄만 찍었다. Mongo `MongoResourceBudgetLaneTest`는 표준 gate 전체(p99 500ms, pool 대기 250ms, 힙 512 MiB, examined/returned 10, spill 금지)를 Gradle 밖 실행에서도 단언한다(B-43) | 손으로 돌린 `performanceCheck`가 상한을 실제로 재므로, 전에는 통과하던 느린 기계에서 실패할 수 있다 | B4(2026-11-06) · `LargeBodyResourceTest`, `MongoResourceBudgetLaneTest` | ## 6. 따라오는 순서 diff --git a/src/README.md b/src/README.md index c6ba7a83..4e8b0fa4 100644 --- a/src/README.md +++ b/src/README.md @@ -27,7 +27,7 @@ Checkstyle은 **포매터가 표현할 수 없는 것만** — 네이밍과 몇 | `configContractCheck` | `:app-bootstrap:verifyEnvKeys`로 환경 설정 계약을 검사 | | `qualificationCheck` | 전체 기동(system) 레인과 보조 source set Checkstyle을 실행 | | `integrationCheck` | 선언된 strict integration lane(sample 포함)을 실행. 대부분 container runtime이 필요. 입력이 필요한 lane(Redis topology: `-Predis.topology.mode`, AWS: 보호 자격 증명 env)은 입력이 없으면 빠지고 집계가 그 이유를 출력 | -| `performanceCheck` | 선언된 strict performance lane(부하·종료·pool·자원 상한)을 실행. 실서버·container가 필요. `integration-main.yml` `performance-check`가 main·nightly에 돌림 | +| `performanceCheck` | 선언된 strict performance lane(부하·종료·pool·자원 상한)을 실행. 실서버·container가 필요. 상한은 매번 단언하고 끄는 속성이 없다(`-Pperformance.assertions.enabled`가 `true`가 아니면 실패, skip된 테스트가 있어도 실패). `integration-main.yml` `performance-check`가 main·nightly에 같은 명령으로 돌림 | | `verifyStrictLaneStages` | `--dry-run` 전용. `explicitOnly`가 아닌 strict lane이 workflow가 실제 실행하는 단계(`ci`·`:sample-portfolio:check`·`mainCheck`·`integrationCheck`·`performanceCheck`·`releaseCheck`) 중 하나의 계획에 있는지, 각 단계를 workflow가 `--dry-run` 없이 실행하는지 검사. Gradle이 작업을 돌리지 않는 명령(`--dry-run`·`-v`·`--help` 등)과, 실패해도 단계가 실패하지 않을 수 있거나(`\|\| true`, pipefail 없는 파이프, `if` 조건 등) 돌지 않을 수 있거나(조건부 `exit 0` 뒤, 요청으로만 시작하는 workflow 등) 검사가 읽지 않는(`\|\| exit 1`, `{ }` 안 등) 명령은 실행으로 세지 않는다. 자세한 목록은 `build-logic/README.md`. PR 게이트가 돌림 | | `ci` | PR 게이트: 모든 leaf `check`(API surface 검사 포함, 소유자 결정 20) + `architectureCheck` + `qualityCheck` | | `mainCheck` | main 단계: `configContractCheck` + `qualificationCheck` + sample web 계약 + sample 전체 기동(`:sample-portfolio:systemTest`) + `verifyPublicPathSnapshot` + 전송·메시징 qualification 레인 + 각 leaf의 `mainCheck`(문서 대조 레인 `*DocumentContractTest`, objectstorage MinIO 레인) | diff --git a/src/adapter/outbound/httpclient/CLAUDE.md b/src/adapter/outbound/httpclient/CLAUDE.md index 9b819b9a..6b7e27d2 100644 --- a/src/adapter/outbound/httpclient/CLAUDE.md +++ b/src/adapter/outbound/httpclient/CLAUDE.md @@ -81,8 +81,9 @@ Default lane: `./gradlew :adapter:outbound:httpclient:test`. Additional lanes, a | `jmh` | per-call overhead benchmarks | A selected lane never skips silently: the fault lane throws without Docker, the contract lane throws -on an empty or unknown transport selection, and the performance lane prints which machine-dependent -bounds were not asserted. +on an empty or unknown transport selection, and the performance lane asserts every bound in every +run — the strict-lane convention fails it when the build sets `performance.assertions.enabled` to +anything but `true` or when one of its tests is skipped. The transport port (`BlockingTransportProvider`) has one abstract contract in the test fixtures, `testkit/BlockingTransportProviderContract`. The engines pass it over a real socket diff --git a/src/adapter/outbound/httpclient/README.md b/src/adapter/outbound/httpclient/README.md index 9ae38727..4130afdc 100644 --- a/src/adapter/outbound/httpclient/README.md +++ b/src/adapter/outbound/httpclient/README.md @@ -111,8 +111,9 @@ cd src ``` No lane skips silently. The fault lane fails without Docker, the contract lane fails on an empty or -unknown transport selection, and the performance lane reports which machine-dependent bounds it did -not assert. +unknown transport selection, and the performance lane asserts every bound in every run (it fails +when the build sets `performance.assertions.enabled` to anything but `true`, or when a test is +skipped). ## Further reading diff --git a/src/adapter/outbound/httpclient/build.gradle b/src/adapter/outbound/httpclient/build.gradle index 40108ed1..2e4041d9 100644 --- a/src/adapter/outbound/httpclient/build.gradle +++ b/src/adapter/outbound/httpclient/build.gradle @@ -138,8 +138,9 @@ dependencies { } // Which transports the contract suites cover and whether the HTTP/3 opt-in runs: the same two -// properties for every Test task of this leaf, declared once (review 2026-11-01 O-10a). Values a -// single lane needs (the performance assertions, the httpbin image) stay in that lane. +// properties for every Test task of this leaf, declared once (review 2026-11-01 O-10a). A value a +// single lane needs (the httpbin image) stays in that lane. The performance lane's bounds have no +// switch here: the strict-lane convention asserts them in every run. tasks.withType(Test).configureEach { systemProperty 'httpclient.contract.transports', providers.gradleProperty('httpclient.contract.transports').orElse('apache,jdk').get() @@ -193,8 +194,6 @@ strictTestLanes { performance() sourceSet = 'httpClientPerformanceTest' description = 'Certifies pool, streaming, retry, and rotation resource bounds (design §28.8).' - systemProperty 'performance.assertions.enabled', - providers.gradleProperty('performance.assertions.enabled').orElse('false').get() } lane('httpClientFailureInjectionTest') { integration() diff --git a/src/adapter/outbound/httpclient/src/httpClientPerformanceTest/java/dev/caskeleton/adapter/outbound/httpclient/performance/LargeBodyResourceTest.java b/src/adapter/outbound/httpclient/src/httpClientPerformanceTest/java/dev/caskeleton/adapter/outbound/httpclient/performance/LargeBodyResourceTest.java index 2c2837da..68f54585 100644 --- a/src/adapter/outbound/httpclient/src/httpClientPerformanceTest/java/dev/caskeleton/adapter/outbound/httpclient/performance/LargeBodyResourceTest.java +++ b/src/adapter/outbound/httpclient/src/httpClientPerformanceTest/java/dev/caskeleton/adapter/outbound/httpclient/performance/LargeBodyResourceTest.java @@ -52,11 +52,18 @@ class LargeBodyResourceTest { } } long peakIncrease = usedHeap() - before; + // The measured value, so a passing run is a recorded number and not only a green line. + System.out.println( + "[httpclient-performance] streaming download heap increase " + + peakIncrease + + " bytes, bound " + + payloadBytes / 2 + + " bytes"); assertThat(consumed).isEqualTo(payloadBytes); - PerformanceAssertions.machineDependent( - "streaming download heap increase stays well below the payload size", - () -> assertThat(peakIncrease).isLessThan((long) payloadBytes / 2)); + assertThat(peakIncrease) + .as("streaming download heap increase stays well below the payload size") + .isLessThan((long) payloadBytes / 2); } } } diff --git a/src/adapter/outbound/httpclient/src/httpClientPerformanceTest/java/dev/caskeleton/adapter/outbound/httpclient/performance/PerformanceAssertions.java b/src/adapter/outbound/httpclient/src/httpClientPerformanceTest/java/dev/caskeleton/adapter/outbound/httpclient/performance/PerformanceAssertions.java index ca812905..924e9b10 100644 --- a/src/adapter/outbound/httpclient/src/httpClientPerformanceTest/java/dev/caskeleton/adapter/outbound/httpclient/performance/PerformanceAssertions.java +++ b/src/adapter/outbound/httpclient/src/httpClientPerformanceTest/java/dev/caskeleton/adapter/outbound/httpclient/performance/PerformanceAssertions.java @@ -3,32 +3,19 @@ package dev.caskeleton.adapter.outbound.httpclient.performance; import static org.assertj.core.api.Assertions.assertThat; /** - * Separates deterministic bounds from machine-dependent ones (design §28.8, §37). + * Structural bounds — retry budget arithmetic, a refresh collapsing to one request, drain + * completing — that hold on any machine (design §28.8, §37). * - *

Structural bounds — retry budget arithmetic, streaming not buffering the whole payload, drain - * completing — always run. Latency and absolute memory numbers depend on the host, so they are - * asserted only when the certification flag is set; when it is off the lane still executes and - * still reports, rather than becoming a silent pass. + *

The machine-dependent bound (the streaming heap increase) is asserted in place, in every run. + * It used to sit behind {@code performance.assertions.enabled}, which defaulted to {@code false} in + * this leaf, so a lane run by hand reported success with the bound compared to nothing. A + * performance lane now asserts all of its bounds; the strict-lane convention rejects a build that + * tries to turn them off. */ final class PerformanceAssertions { private PerformanceAssertions() {} - static boolean certificationEnabled() { - return Boolean.parseBoolean(System.getProperty("performance.assertions.enabled", "false")); - } - - static void machineDependent(String description, Runnable assertion) { - if (certificationEnabled()) { - assertion.run(); - return; - } - System.out.println( - "[httpclient-performance] skipped machine-dependent bound (enable with " - + "-Pperformance.assertions.enabled=true): " - + description); - } - static void structural(String description, boolean condition) { assertThat(condition).describedAs(description).isTrue(); } diff --git a/src/adapter/outbound/persistence-mongo/build.gradle b/src/adapter/outbound/persistence-mongo/build.gradle index e32912e3..c33c1752 100644 --- a/src/adapter/outbound/persistence-mongo/build.gradle +++ b/src/adapter/outbound/persistence-mongo/build.gradle @@ -239,9 +239,8 @@ strictTestLanes { providers.gradleProperty('mongoCompatibilityImage').orElse(testContainerImages['mongo-7']).get() systemProperty 'mongodb.toxiproxy.image', providers.gradleProperty('mongoToxiproxyImage').orElse(testContainerImages['toxiproxy']).get() - // Assertions on by default: a performance gate without bounds is only a report. - systemProperty 'performance.assertions.enabled', - providers.gradleProperty('performance.assertions.enabled').orElse('true').get() + // No assertions switch: the strict-lane convention asserts a performance lane's bounds in + // every run, because a performance gate without bounds is only a report. } } diff --git a/src/adapter/outbound/persistence-mongo/src/mongoPerformanceTest/java/dev/caskeleton/adapter/outbound/mongo/performance/MongoResourceBudgetLaneTest.java b/src/adapter/outbound/persistence-mongo/src/mongoPerformanceTest/java/dev/caskeleton/adapter/outbound/mongo/performance/MongoResourceBudgetLaneTest.java index 969d1690..15441d34 100644 --- a/src/adapter/outbound/persistence-mongo/src/mongoPerformanceTest/java/dev/caskeleton/adapter/outbound/mongo/performance/MongoResourceBudgetLaneTest.java +++ b/src/adapter/outbound/persistence-mongo/src/mongoPerformanceTest/java/dev/caskeleton/adapter/outbound/mongo/performance/MongoResourceBudgetLaneTest.java @@ -27,16 +27,16 @@ import org.junit.jupiter.api.Test; * it is the same on an idle machine and a busy one, and it is what actually predicts the query * falling over as the collection grows. * - *

Timing bounds are asserted only when {@code -Pperformance.assertions.enabled=true}, for the - * same reason. The ratio bound is always asserted. + *

The timing bounds are asserted too, in every run, but the gate's bounds are generous for the + * same reason: they catch a query that falls over, not one that was slower than last time. They + * used to sit behind {@code performance.assertions.enabled}, which the build defaulted to on and + * this class to off, so a run outside Gradle skipped them; the strict-lane convention now asserts a + * performance lane's bounds in every run. */ class MongoResourceBudgetLaneTest { private static final int DOCUMENT_COUNT = 5_000; - private static final boolean TIMING_ASSERTIONS = - Boolean.parseBoolean(System.getProperty("performance.assertions.enabled", "false")); - private static MongoSingleReplicaSetContainer container; private static MongoClient client; @@ -75,18 +75,16 @@ class MongoResourceBudgetLaneTest { @Test void anIndexedQueryStaysInsideTheResourceBudget() { MongoResourceBudgetReport report = measure(new Document("status", "PENDING"), "ix_status"); + // The measured values, so a passing run is a recorded number and not only a green line. + System.out.println("[mongo-performance] indexed query " + report.asArtifact()); assertThat(report.documentsReturned()).isEqualTo(DOCUMENT_COUNT / 50); assertThat(report.examinedToReturnedRatio()) .as("an index seek examines about what it returns") .isLessThanOrEqualTo(MongoPerformanceGate.standard().maximumExaminedToReturnedRatio()); assertThat(MongoPerformanceGate.standard().violations(report)) - .filteredOn(violation -> violation.startsWith("examined/returned")) + .as("an indexed query stays inside every bound of the standard gate") .isEmpty(); - - if (TIMING_ASSERTIONS) { - assertThat(MongoPerformanceGate.standard().passes(report)).isTrue(); - } } @Test diff --git a/src/build-logic/README.md b/src/build-logic/README.md index 22a7340b..52ae07a2 100644 --- a/src/build-logic/README.md +++ b/src/build-logic/README.md @@ -15,7 +15,7 @@ capability, and the files it reads are declared as that test task's inputs. | `ca.quality-conventions` | Spotless, Checkstyle, Error Prone, SpotBugs/FindSecBugs wiring shared by Java leaves | | `ca.java-library` / `ca.spring-library` / `ca.spring-config` | leaf-level composition of the Java/quality conventions for plain and Spring libraries | | `ca.platform-module` / `ca.grpc-platform-module` | what a vendored platform leaf (`messaging:*`, `grpc:*`, `grpc-advanced:*`) is: `java-library`, plus the gRPC BOM for the leaves that had it | -| `ca.strict-test-lane` | the one "named tests ran, none skipped" mechanism: tagged / named / own-source-set `Test` lanes that fail when they execute nothing, miss a `requires` class, or (with `rejectSkipped`) skip anything. `mainStage()` moves a tagged lane out of `test` into the leaf's `mainCheck`; `explicitOnly(reason)` keeps a lane that needs an outside input out of every aggregate, and the aggregate prints the reason. Extra test source sets are Gradle `jvm-test-suite` suites declared in the leaf (`testing { suites { … } }`); a lane named after its suite makes the suite's own `Test` task strict, and `ca.java-conventions` gives every suite the BOM's JUnit | +| `ca.strict-test-lane` | the one "named tests ran, none skipped" mechanism: tagged / named / own-source-set `Test` lanes that fail when they execute nothing, miss a `requires` class, or (with `rejectSkipped`) skip anything. A `performance()` lane always rejects skips and runs with `performance.assertions.enabled=true`; a build (`-P`, `GRADLE_OPTS`) or lane that sets another value fails it before a test runs. `mainStage()` moves a tagged lane out of `test` into the leaf's `mainCheck`; `explicitOnly(reason)` keeps a lane that needs an outside input out of every aggregate, and the aggregate prints the reason. Extra test source sets are Gradle `jvm-test-suite` suites declared in the leaf (`testing { suites { … } }`); a lane named after its suite makes the suite's own `Test` task strict, and `ca.java-conventions` gives every suite the BOM's JUnit | | `ca.strict-lane-stages` (root of each build with strict lanes: the main build and optional-platforms) | the other half of the lane mechanism: `verifyStrictLaneStages --dry-run` fails when a strict lane of that build that is not `explicitOnly` is in the task plan of no declared stage that a workflow executes, or when a declared stage is executed by no workflow. The workflows are read together (`WorkflowGradleInvocations.readAll`, so a reusable workflow is judged by its callers) and their `run:` scripts parsed as bash (`ShellScript`: quotes, comments, heredoc bodies, substitutions and compound commands are read as the shell reads them, so a `cd` in a heredoc or a string is data). A command does not count when Gradle runs no task with it — `--dry-run`/`-m` (also in a bundle such as `-qm`), `-v`/`--version`, `-h`/`-?`/`--help`, `--status`, `--stop`, `--foreground` (also in a bundle such as `-qv`) — or rejects it: a short-option bundle whose later letter takes a value (`-mx`: only the first letter of a bundle takes one), or a value given to an option that takes none (`-m=yes`). The reader follows Gradle 9.0's parser. `GradleCommandLineTest` holds its option tables to the `--help` of the Gradle that runs build-logic — an upgrade that adds an option, as 9.2 adds `--task-graph`, fails until the option is placed — and runs the launcher with each no-task option but `--stop` and `--foreground` (both return a daemon action, not a build, in Gradle's `BuildActionsFactory`); which options take a value was probed against 9.0.0 in round 9 and is not re-run. Nor does a command for another build count (the build a command starts is its step's `working-directory`, or the job's or workflow's `defaults.run.working-directory`, moved by each `cd ` the same `run:` shell surely ran before it — alone in its list, or before the command in the same `&&` list — then joined with `-p`; the plugin reads this build's own directory from where it sits under the repository that holds `.github/workflows`). Every other command that does not count gives one of three reasons. **Its failure may not fail its step**: `\|\| true`, `\|\| :` or any `\|\|` but `\|\| exit `, a pipe's left side without `pipefail` (on with `shell: bash` or a top-level `set -o pipefail`), `!`, `&`, an `if`/`while` condition, the part before `&&` of a list that is not the script's last command, after `set +e`, after a `trap` whose `EXIT` or `ERR` action may `exit` with status 0 (a bare `exit` keeps the status in an `EXIT` trap, not in an `ERR` one), and `continue-on-error`. **It may not run**: after `\|\|`, after `&&` in a list that is not the script's last command, inside `if`/`while`/`for`/`case` or a function body, after a top-level `exit`, `exec ` or `set -n`, after one elsewhere — in a compound command, an and-or list or a function the script calls — that may end the script with status 0 (`exit 0`, a bare `exit` other than right after `\|\|`, `exit "$code"`), replace it or stop it running commands (`set -o noexec`), under an `if:` other than `always()`/`success()`/`!cancelled()`, in a workflow that starts only on events someone or something asks for (`workflow_dispatch`, `repository_dispatch`, `issue_comment`, a pull request with `types: [labeled]`, `workflow_run`, …; `push`, `pull_request`, `pull_request_target`, `merge_group`, `schedule` and `release` count), in a reusable (`workflow_call`-only) workflow that no counted job calls with `uses: ./.github/workflows/`, and in a job that `needs`, directly or through other jobs, a job with such an `if:` or with `continue-on-error`, unless its own `if:` is `always()` or `!cancelled()`. **This check does not read it**, although its failure would fail the step (a false failure on purpose): `\|\| exit 1`, `\|\| { …; exit 1; }`, inside `{ }` or `( )`, `$( )`, `bash -c`, `gradlew` as another command's argument (`timeout 60 ./gradlew`), after a directory change the reader does not follow (`cd "$VAR"`, `cd -`, `cd ~`, an absolute path, `pushd`/`popd`, `builtin cd`, `eval`/`source`, a `cd` anywhere inside a compound command or a function body, one joined with `\|\|`, piped or in the background, and the lines after a `cd` that shares an `&&` list with other commands — not guessed), a step whose `shell:` is not `bash` or `sh`, and a step with no `shell:` in a job whose `runs-on` may be a Windows runner, whose default shell is `pwsh` (a Windows label, an expression such as `${{ matrix.os }}`, a self-hosted label set without `linux` or `macos`; Linux and macOS runners default to `bash -e` and a `container:` job to `sh -e`, which are read alike). An `exit` that fails the step — `exit 1`, or `cmd \|\| exit` — and one in an uncalled function, a `( )` subshell or `$( )` stop nothing after them from counting. The failure names every command that names the stage but does not execute it, with its reason or the other build it starts, and says to run the stage as `./gradlew` on a line of its own. A lane the command removes with `-x` is not covered — matched the way Gradle matches task and project names, abbreviations included (`TaskSelectors`, a copy of Gradle's internal `NameMatcher`). A `run:` input of a `uses:` step is not a command. The plan is Gradle's own; the workflows are read for their `run:` steps with YAML folding applied (review 2026-11-01 08-01, 2026-11-03 RR-06-03/04, 2026-11-04 RR2-04-04, owner decision 2026-11-04 on `cd`, RR5-02-01/02/03 in round 9, 2026-11-05 RR6-04-01..06) | | `ca.redis-topology-lane` | the Redis topology lane (mode selection, `-P` property validation, per-mode required classes) the redis-sdk-topology workflow drives | | `ca.api-surface` | read-only public API surface verification with a separate update task, wired into the leaf's `check` (owner decision 20); optionally holds other leaves' imports to a reviewed adopter subset (`adopterBaseline`) | diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictTestLanePlugin.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictTestLanePlugin.java index 104671df..628cea88 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictTestLanePlugin.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictTestLanePlugin.java @@ -10,12 +10,26 @@ import org.gradle.api.NamedDomainObjectContainer; import org.gradle.api.Plugin; import org.gradle.api.Project; import org.gradle.api.plugins.JavaPluginExtension; +import org.gradle.api.provider.Provider; import org.gradle.api.tasks.SourceSet; import org.gradle.api.tasks.TaskProvider; import org.gradle.api.tasks.testing.Test; import org.gradle.testing.base.TestingExtension; public final class StrictTestLanePlugin implements Plugin { + /** + * The switch a performance lane's machine-dependent bounds used to sit behind, now always on. + * + *

Each leaf declared it with its own default — {@code false} for the httpclient lane, {@code + * true} for the Mongo lane — and only the workflows set it. {@code ./gradlew :performanceCheck} + * typed by hand therefore passed with the httpclient heap bound compared to nothing (the + * 2026-11-05 desktop gate). The convention owns it now: every performance lane's test JVM gets + * {@code true}, so a test that still reads the switch asserts, and a build that sets it to + * anything else fails before the lane runs. Nothing in this repository reads it any more; the + * value is for tests written against the old switch, such as a derived service's. + */ + static final String PERFORMANCE_ASSERTIONS = "performance.assertions.enabled"; + @Override public void apply(Project project) { project.getPluginManager().withPlugin("java", ignored -> configure(project)); @@ -229,7 +243,8 @@ public final class StrictTestLanePlugin implements Plugin { // judge the lane again rather than reuse a result produced under the looser policy. Without // this a lane that skipped a test stayed green, up to date and from the build cache, after // rejectSkipped was switched on (review 2026-11-03 RR-06-02). - test.getInputs().property("strictLane.rejectSkipped", project.provider(lane::isRejectSkipped)); + test.getInputs() + .property("strictLane.rejectSkipped", project.provider(() -> rejectsSkipped(lane))); test.getInputs() .property("strictLane.requiredTests", project.provider(lane::getRequiredTests)); test.getInputs() @@ -243,6 +258,17 @@ public final class StrictTestLanePlugin implements Plugin { test.getOutputs().upToDateWhen(ignored -> false); test.getOutputs().doNotCacheIf(rerunReason, ignored -> true); } + boolean performance = lane.getCategory() == TestLaneCategory.PERFORMANCE; + if (performance) { + // Set before the lane's own JVM arguments and system properties — Gradle turns a -D in + // jvmArgs into a system property — so a lane that still declares the switch replaces this + // value and the check below sees the override, instead of the override disappearing silently. + test.systemProperty(PERFORMANCE_ASSERTIONS, "true"); + Provider requested = project.getProviders().gradleProperty(PERFORMANCE_ASSERTIONS); + String laneName = lane.getName(); + test.doFirst( + running -> requireAssertionsOn(laneName, ownerPath, requested.getOrNull(), (Test) running)); + } if (lane.getMaxHeapSize() != null && !lane.getMaxHeapSize().isBlank()) { test.setMaxHeapSize(lane.getMaxHeapSize()); } @@ -288,7 +314,7 @@ public final class StrictTestLanePlugin implements Plugin { + detail + " — a lane that runs nothing reports success for whatever it was meant to prove."); } - if (lane.isRejectSkipped() && tracker.skippedCount() > 0L) { + if (rejectsSkipped(lane) && tracker.skippedCount() > 0L) { throw new GradleException( "strict test lane '" + lane.getName() @@ -296,7 +322,10 @@ public final class StrictTestLanePlugin implements Plugin { + ownerPath + " forbids skipped tests but observed " + tracker.skippedCount() - + " skipped test(s)."); + + " skipped test(s)." + + (performance + ? " A performance lane always does: a skipped test is a bound nobody measured." + : "")); } if (!required.isEmpty()) { List absent = @@ -318,6 +347,55 @@ public final class StrictTestLanePlugin implements Plugin { } } + /** + * A performance lane rejects skipped tests whatever it declares: its tests are its bounds, and a + * skip is a bound the run reports as passed without comparing it to anything. + */ + private static boolean rejectsSkipped(StrictTestLaneSpec lane) { + return lane.isRejectSkipped() || lane.getCategory() == TestLaneCategory.PERFORMANCE; + } + + /** + * Fails a performance lane, before any test runs, when the build or the lane turns its bounds off. + * {@code true} from the build is accepted, so a command that still passes it keeps working. + */ + private static void requireAssertionsOn( + String laneName, String ownerPath, String requestedByBuild, Test test) { + if (requestedByBuild != null && !Boolean.parseBoolean(requestedByBuild.trim())) { + throw new GradleException( + "strict test lane '" + + laneName + + "' in " + + ownerPath + + " is a performance lane, and this build sets " + + PERFORMANCE_ASSERTIONS + + "=" + + requestedByBuild + + " (-P" + + PERFORMANCE_ASSERTIONS + + ", or -Dorg.gradle.project." + + PERFORMANCE_ASSERTIONS + + " in GRADLE_OPTS). A performance lane asserts its bounds in every run: one without" + + " them measures nothing it can fail on and still reports success. Remove the" + + " property or set it to true."); + } + Object effective = test.getSystemProperties().get(PERFORMANCE_ASSERTIONS); + if (effective == null || !Boolean.parseBoolean(String.valueOf(effective).trim())) { + throw new GradleException( + "strict test lane '" + + laneName + + "' in " + + ownerPath + + " is a performance lane, but its test JVM would get " + + PERFORMANCE_ASSERTIONS + + "=" + + effective + + " from this project's build (a lane systemProperty or jvmArgs, or a block that" + + " configures the task). The strict-lane convention sets it to true for every" + + " performance lane; delete the override."); + } + } + private static boolean startsARealServer(StrictTestLaneSpec lane) { return lane.getCategory() != TestLaneCategory.TEST && lane.getCategory() != TestLaneCategory.ARCHITECTURE; diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictTestLaneSpec.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictTestLaneSpec.java index f34537e8..197d1020 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictTestLaneSpec.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictTestLaneSpec.java @@ -137,6 +137,12 @@ public class StrictTestLaneSpec implements Named { category = TestLaneCategory.ARCHITECTURE; } + /** + * A lane whose tests are resource or latency bounds. Besides rerunning every time and taking the + * build-wide real-server slot, it rejects skipped tests and always runs with its bounds asserted: + * the convention sets {@code performance.assertions.enabled=true}, and a build or lane that sets + * it to anything else fails before a test runs. + */ public void performance() { category = TestLaneCategory.PERFORMANCE; } diff --git a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/StrictTestLaneConventionTest.java b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/StrictTestLaneConventionTest.java index 5cda0950..208f2cde 100644 --- a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/StrictTestLaneConventionTest.java +++ b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/StrictTestLaneConventionTest.java @@ -611,6 +611,147 @@ class StrictTestLaneConventionTest { assertThat(result.getOutput()).contains("rulesLane=false").contains("databaseLane=true"); } + @Test + void aPerformanceLaneFailsOnAnExceededBoundWhenTheBuildSetsNoAssertionsProperty() + throws Exception { + // given + buildFile(performanceLane("")); + writePerformanceTest( + "BoundTest.java", + """ + import org.junit.jupiter.api.Test; + class BoundTest { + @Test void staysInsideTheBound() { + long p99Millis = 900; + // The shape the httpclient lane had: the machine-dependent bound behind the switch. + if (Boolean.parseBoolean(System.getProperty("performance.assertions.enabled", "false")) + && p99Millis > 500) { + throw new AssertionError("p99 900ms above the 500ms bound"); + } + } + } + """); + + // when + BuildResult result = runner("performanceTestLaneCheck").buildAndFail(); + + // then + assertThat(result.getOutput()).contains("BoundTest > staysInsideTheBound() FAILED"); + } + + @Test + void aPerformanceLaneFailsBeforeTestingWhenTheBuildTurnsItsAssertionsOff() throws Exception { + // given + buildFile(performanceLane("")); + writePerformanceTest( + "MeasuredTest.java", + """ + import org.junit.jupiter.api.Test; + class MeasuredTest { + @Test void measured() { throw new AssertionError("the lane ran a test"); } + } + """); + + // when + BuildResult result = + runner("performanceTestLaneCheck", "-Pperformance.assertions.enabled=false") + .buildAndFail(); + + // then + assertThat(result.getOutput()) + .contains("this build sets performance.assertions.enabled=false") + .contains("set it to true") + .doesNotContain("MeasuredTest > measured() FAILED"); + } + + @Test + void aPerformanceLaneFailsWhenItsOwnDeclarationTurnsTheAssertionsOff() throws Exception { + // given + buildFile( + performanceLane( + """ + systemProperty 'performance.assertions.enabled', + providers.gradleProperty('performance.assertions.enabled').orElse('false').get() + """)); + writePerformanceTest( + "MeasuredTest.java", + """ + import org.junit.jupiter.api.Test; + class MeasuredTest { @Test void measured() {} } + """); + + // when + BuildResult result = runner("performanceTestLaneCheck").buildAndFail(); + + // then + assertThat(result.getOutput()) + .contains("its test JVM would get performance.assertions.enabled=false") + .contains("delete the override"); + } + + @Test + void aPerformanceLaneFailsWhenItsJvmArgumentsTurnTheAssertionsOff() throws Exception { + // given + buildFile(performanceLane("jvmArgs '-Dperformance.assertions.enabled=false'")); + writePerformanceTest( + "MeasuredTest.java", + """ + import org.junit.jupiter.api.Test; + class MeasuredTest { @Test void measured() {} } + """); + + // when + BuildResult result = runner("performanceTestLaneCheck").buildAndFail(); + + // then + assertThat(result.getOutput()) + .contains("its test JVM would get performance.assertions.enabled=false") + .contains("delete the override"); + } + + @Test + void aPerformanceLaneFailsWhenOneOfItsTestsIsSkipped() throws Exception { + // given + buildFile(performanceLane("")); + writePerformanceTest( + "PartlyMeasuredTest.java", + """ + import org.junit.jupiter.api.Disabled; + import org.junit.jupiter.api.Test; + class PartlyMeasuredTest { + @Test void measured() {} + @Test @Disabled("too slow on this machine") void quarantined() {} + } + """); + + // when + BuildResult result = runner("performanceTestLaneCheck").buildAndFail(); + + // then + assertThat(result.getOutput()) + .contains("forbids skipped tests") + .contains("a skipped test is a bound nobody measured"); + } + + @Test + void aPerformanceLaneAcceptsABuildThatTurnsItsAssertionsOnExplicitly() throws Exception { + // given + buildFile(performanceLane("")); + writePerformanceTest( + "MeasuredTest.java", + """ + import org.junit.jupiter.api.Test; + class MeasuredTest { @Test void measured() {} } + """); + + // when + BuildResult result = + runner("performanceTestLaneCheck", "-Pperformance.assertions.enabled=true").build(); + + // then + assertThat(result.task(":loadLane").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + } + private void buildFile(String laneBlock) throws Exception { Files.writeString( projectDir.resolve("build.gradle"), @@ -631,6 +772,32 @@ class StrictTestLaneConventionTest { Files.writeString(testSource.resolve(fileName), source); } + private void writePerformanceTest(String fileName, String source) throws Exception { + Path performanceSource = projectDir.resolve("src/performance/java"); + Files.createDirectories(performanceSource); + Files.writeString(performanceSource.resolve(fileName), source); + } + + private static String performanceLane(String extraDeclarations) { + return """ + sourceSets { performance } + dependencies { + performanceImplementation platform('org.junit:junit-bom:5.11.3') + performanceImplementation 'org.junit.jupiter:junit-jupiter' + performanceRuntimeOnly 'org.junit.platform:junit-platform-launcher' + } + strictTestLanes { + lane('loadLane') { + performance() + sourceSet = 'performance' + description = 'Measures a resource bound.' + %s + } + } + """ + .formatted(extraDeclarations); + } + private static String junitDependencies() { return """ dependencies { From 06f520e6673919ac2fdb2df05729b8f92e82cf5a Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 6 Nov 2026 21:30:26 +0900 Subject: [PATCH 07/71] =?UTF-8?q?docs(work):=20=EC=84=B1=EB=8A=A5=20lane?= =?UTF-8?q?=20=EB=8B=A8=EC=96=B8=20=EA=B0=95=EC=A0=9C=EC=99=80=20=EC=BA=90?= =?UTF-8?q?=EC=8B=9C=20=EA=B2=B0=EA=B3=BC=EC=9D=98=20=ED=95=9C=EA=B3=84?= =?UTF-8?q?=EB=A5=BC=20=EB=A7=A4=EB=89=B4=EC=96=BC=EC=97=90=20=EB=A7=9E?= =?UTF-8?q?=EC=B6=98=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 성능 lane 단언을 빌드가 강제하게 된 뒤에도 docs/work/는 옛 동작을 안내했다. gates.md 5절은 "desktop에서 -Pperformance.assertions.enabled=true를 준다. 안 주면 httpclient의 시간 단언 없이 통과한다"고 했고, 3절 라운드 끝 명령과 improve.md·operate.md의 「자주 하는 실수」도 그 속성을 맞추라고 했다. 지금은 convention이 단언을 켜고 true 아닌 값이나 skip이 있으면 테스트 전에 실패하므로, 그 문장은 틀렸고 그 속성은 필요 없다. 또 2026-11-06 B3 desktop ci rc=0은 캐시 결과(태스크 701개 중 403개)였는데, 그 사이 httpclient CircuitBreakerStatusAccountingTest 2건은 기준 커밋에서도 10번 중 10번 실패하고 있었다. 캐시 결과를 현재 통과의 증거로 쓰면 이런 기존 결함을 놓친다. 고른 방법: - gates.md 5절을 새 동작으로 다시 쓰고(정본 AGENTS.md 「Gradle 정책 권위」, docs/testing/TESTING_STRATEGY.md), 1절 표와 6절 거짓 통과 표를 맞췄다. 3절 명령에서는 그 속성을 뺐다. workflow도 이제 주지 않는다. - improve.md의 같은 실수 줄은 지웠다. 빌드가 막으므로 더는 실수가 아니다. - operate.md 「자주 하는 실수」의 그 줄 자리에 캐시 교훈을 넣었다: 기준 상태와 시간·환경에 민감한 테스트는 그 태스크를 --rerun으로 다시 돌린다. gates.md 6절에도 한 줄, 근거는 evidence.md 2절, 결정은 decisions.md 2.7, 장치는 defect-patterns.md A7에 더했다. 위험·한계: --rerun은 지정한 태스크 하나만 다시 돈다. 집계 태스크 전체를 캐시 없이 돌리려면 --rerun-tasks가 필요하고 시간이 훨씬 길다. 이 매뉴얼은 그 둘을 가르는 기준까지는 정하지 않았다. 검증 - python3 scripts/check-work-docs.py: rc=0, 본문 이력 ID 0줄, improve.md 131/150, operate.md 115/150 - python3 scripts/check-work-docs.py --links docs README.md CLAUDE.md AGENTS.md: 깨진 링크 0 --- docs/work/evidence.md | 3 ++- docs/work/improve.md | 1 - docs/work/operate.md | 2 +- docs/work/reference/decisions.md | 1 + docs/work/reference/defect-patterns.md | 2 +- docs/work/reference/gates.md | 17 ++++++++++------- 6 files changed, 15 insertions(+), 11 deletions(-) diff --git a/docs/work/evidence.md b/docs/work/evidence.md index 2c2fe750..0beb7a9d 100644 --- a/docs/work/evidence.md +++ b/docs/work/evidence.md @@ -43,7 +43,8 @@ | 색인은 기계로 대조한다 (`improve.md` 4.1) | 원래 리뷰 색인이 119건이었다. 06 영역 문서의 `NN-10`~`NN-14` 5건이 색인과 모든 수정 묶음에서 빠졌다. 실제는 124건 | `1101` README 12절 정정, `1103` README 1절, `1103/RR-05-10` | | 「새로 가정하는 것」 칸, 수정 묶음 크기 상한 (`improve.md` 4.4, 8절) | round6 발견 25건 중 17건(68%)을 직전 수정 커밋이 만들었다. 짝 프론트 1106 리뷰도 25건 중 16건(64%) | `01-research.md` 4.3절, design-docs `delegation-loop/02-design.md` 4.3절 | | 보고한 태스크가 로그에 있는지 확인 (`improve.md` 9절, `gates.md` 4절) | 묶음 보고가 없는 태스크 `:adapter:outbound:persistence-jpa:documentContractTest`를 적었다 | `1103` README 17.2절 | -| 성능 lane은 workflow와 같은 단언 속성으로 (`gates.md` 5절) | r10 desktop 게이트의 `performanceCheck`가 `-Pperformance.assertions.enabled=true` 없이 돌아, httpclient 시간 단언 없이 통과했다 | desktop `~/r10-logs/gates.sh`, 공유 노트 「백엔드 개선 매뉴얼 인계」 | +| 성능 lane은 상한을 매번 단언하고, 끄는 값은 테스트 전에 실패한다 (`gates.md` 5절) | r10 desktop 게이트의 `performanceCheck`가 `-Pperformance.assertions.enabled=true` 없이 돌아, httpclient 시간 단언 없이 통과했다. 그 전에는 JPA pool lane이 같은 속성 뒤에 숨어 상한을 비교하지 않았다(`PoolLaneClaimTest`). 2026-11-06 빌드가 강제하게 바꿨다 | desktop `~/r10-logs/gates.sh`, `docs/testing/TESTING_STRATEGY.md` PERFORMANCE 문단, 커밋 `e6b6e18e` | +| 캐시에서 가져온 결과는 지금 통과한다는 증거가 아니다. 기준 상태와 시간·환경에 민감한 테스트는 `--rerun`으로 (`operate.md` 9절, `gates.md` 6절) | 2026-11-06 B3 desktop `ci` rc=0은 캐시 결과였다(태스크 701개 중 403개를 캐시에서). 그 사이 httpclient `CircuitBreakerStatusAccountingTest` 2건은 기준 커밋 `3d73b6f1`에서도 10번 중 10번 실패하고 있었다 | desktop `~/b3-logs/ci.log`, 2026-11-06 총괄 전달 | | 묶음을 너무 크게 만들지 않는다 (`delegate.md` 4.2) | 알림·파일 서버를 한 묶음(r2-05a)으로 묶었다가 마감 안에 검증 보고가 오지 않아 합치지 못했다. 다음 라운드(r3-a)에 다시 올려 합쳤다 | `1101` README 14.3절, 16절 | | 두 묶음이 같은 파일을 건드리지 않게 (`delegate.md` 4.2) | 2라운드 묶음 r2-06이 10개 파일 충돌로 처음부터 다시 작업했다 | `1101` README 14.1절 | | 전 leaf import를 바꾸는 묶음은 마지막에 혼자 (`improve.md` 6절, `delegate.md` 4.2) | r3-G | `1101` README 15.1절 | diff --git a/docs/work/improve.md b/docs/work/improve.md index 39f3a8e2..fa655b75 100644 --- a/docs/work/improve.md +++ b/docs/work/improve.md @@ -128,5 +128,4 @@ - 색인을 손으로 옮기다 발견이 빠진다. 색인 검사 스크립트를 돌린다. - 보고에 없는 태스크 이름을 적는다. 로그에서 태스크 이름을 grep해 확인한다. -- 성능 lane을 workflow와 다른 속성으로 돌린다. [reference/gates.md](reference/gates.md) 「성능 lane」을 따른다. - 묶음별 검증으로 합친 트리 검증을 대신한다. 라운드 끝 게이트를 따로 돌린다. diff --git a/docs/work/operate.md b/docs/work/operate.md index 3128b753..de17203d 100644 --- a/docs/work/operate.md +++ b/docs/work/operate.md @@ -112,4 +112,4 @@ git worktree remove ~/workspace/<작업 이름> - desktop 기존 checkout에서 브랜치를 바꿔 다른 세션의 작업을 방해한다. 자기 worktree를 만든다. - 짧게 끝난 실행을 통과로 적는다. 캐시 재사용인지, 태스크가 실제로 돌았는지 로그로 확인한다. -- performance lane을 workflow와 다른 속성으로 돌린다. [reference/gates.md](reference/gates.md) 5절을 따른다. +- 빌드 캐시에서 가져온 테스트 결과를 지금 이 환경에서 통과한 증거로 쓴다. 기준 상태를 확인하거나 시간·환경에 민감한 테스트를 볼 때는 그 태스크를 `--rerun`으로 다시 돌린다. diff --git a/docs/work/reference/decisions.md b/docs/work/reference/decisions.md index f0506d09..227e493b 100644 --- a/docs/work/reference/decisions.md +++ b/docs/work/reference/decisions.md @@ -152,6 +152,7 @@ | 테스트 코드 정적 분석 | `testQualityCheck`는 main 빌드 `mainCheck`, optional 빌드 `ci` | 위임 | `1103` 14절 | | lane 정책과 캐시 | lane 정책 값(`rejectSkipped` 등)은 모두 캐시 입력 | 위임 | `1103` 4절(RR-06-02) | | workflow 명령의 빌드 판정 | 같은 셸의 `cd <상대 경로>`도 따라간다 | 소유자 | `1103` 15절 ② | +| 성능 lane 단언 | 끄는 스위치 없음. convention이 `performance.assertions.enabled=true`를 넣고, 빌드·lane이 다른 값을 주거나 skip이 있으면 테스트 전에 실패. 손으로 돌리든 workflow든 같은 상한 | 소유자(2026-11-06 병합 승인) | design-docs `delegation-loop/02-design.md` 13절 D9, 커밋 `e6b6e18e`, `AGENTS.md` 「Gradle 정책 권위」 | | 문서 파싱 검사 | 문서를 파싱해 대조하는 Gradle 검사를 두지 않는다(`verifyDocumentedLeafCount` 등 삭제). 문서와 코드 대조는 leaf의 document-contract lane | 정책 | `AGENTS.md` 「Gradle 정책 권위」 | | MinIO 이미지 | `pgsty/minio` digest | 위임 | `1101` 15절(05-09) | | Jackson 2 | 기본 jar에 남김(logstash encoder·springdoc 요구) | 위임 | `1101` 15절(09-11) | diff --git a/docs/work/reference/defect-patterns.md b/docs/work/reference/defect-patterns.md index 590ff58c..e559218b 100644 --- a/docs/work/reference/defect-patterns.md +++ b/docs/work/reference/defect-patterns.md @@ -51,7 +51,7 @@ - **모양**: 어떤 단계도 돌리지 않는 lane·검사, 캐시가 옛 결과로 통과, 실패를 막지 못하는 workflow 명령을 실행으로 셈, 시간 단언을 끈 채 돈 performance lane. - **막는 기준**: [gates.md](gates.md) 6절. 게이트 장치를 바꾸면 일부러 망가뜨린 입력으로 실패하는 것을 본다. -- **장치**: `verifyStrictLaneStages --dry-run`(두 빌드), lane 정책 값의 캐시 입력 선언, `testQualityCheck`. +- **장치**: `verifyStrictLaneStages --dry-run`(두 빌드), lane 정책 값의 캐시 입력 선언, `testQualityCheck`, 성능 lane 단언 강제(strict lane convention이 `performance.assertions.enabled=true`를 넣고 다른 값·skip은 실패). 캐시에서 가져온 결과는 현재 통과의 증거가 아니다(필요하면 `--rerun`). ### A8. 로그로 새는 입력값·원인 diff --git a/docs/work/reference/gates.md b/docs/work/reference/gates.md index 4ed57d7b..39bbf98c 100644 --- a/docs/work/reference/gates.md +++ b/docs/work/reference/gates.md @@ -26,7 +26,7 @@ | `bash scripts/verify-compose-profile-contracts.sh` | compose lane이 선언대로 렌더링되는가(저장소 루트에서) | PR | `ci-quality-gates.yml` | | `mainCheck` | `configContractCheck` + `qualificationCheck`(`testQualityCheck` 포함) + 샘플 실서버 계약 + 샘플 전체 기동(`:sample-portfolio:systemTest`) + 공개 경로 스냅숏 + 전송·메시징 qualification lane + 생성 명령 왕복(`verifyFeatureScaffold`) + 모든 leaf의 `mainCheck`(document-contract lane 등) | main | `integration-main.yml`: `./gradlew :mainCheck --continue --warning-mode=fail` | | `integrationCheck` | 선언된 strict integration lane 전체(실 컨테이너). 입력이 없는 lane은 빼고 이름을 댄다 | main·nightly | `integration-main.yml`, optional 빌드도 | -| `performanceCheck` | 선언된 performance lane 전체(부하·종료·풀·자원 한계, 실 서버와 컨테이너). main·nightly에서 돈다 | main·nightly | `integration-main.yml`, optional 빌드도. 5절 | +| `performanceCheck` | 선언된 performance lane 전체(부하·종료·풀·자원 한계, 실 서버와 컨테이너). 상한을 매번 단언한다. 손으로 돌리든 workflow든 같은 상한이다 | main·nightly | `integration-main.yml`, optional 빌드도. 5절 | | `releaseCheck -PgitRevision=` | 릴리스 provenance + 공개 경로 스냅숏. sha 없이 돌리면 설계대로 실패한다 | 태그 | `release.yml` | | `:app-bootstrap:verifyEnvKeys` | env 키 레지스트리와 profile YAML·`.env.example` | `mainCheck` 안(`configContractCheck`) | build-logic `ca.config-contract` | | `verifyPublicPathSnapshot` | 기본 공개 경로가 `docs/security/public-paths-snapshot.txt`와 같은가 | `mainCheck`·`releaseCheck` 안 | `src/build.gradle` | @@ -72,8 +72,8 @@ cd src ./gradlew -p optional-platforms :verifyStrictLaneStages --dry-run --console=plain ./gradlew :mainCheck --continue --warning-mode=fail --console=plain ./gradlew :integrationCheck --continue --console=plain -./gradlew -p optional-platforms ci integrationCheck performanceCheck -Pperformance.assertions.enabled=true --console=plain -./gradlew :performanceCheck --continue -Pperformance.assertions.enabled=true --console=plain +./gradlew -p optional-platforms ci integrationCheck performanceCheck --console=plain +./gradlew :performanceCheck --continue --console=plain ./gradlew :releaseCheck -PgitRevision="$(git rev-parse HEAD)" --console=plain cd .. && bash scripts/verify-compose-profile-contracts.sh ``` @@ -98,9 +98,11 @@ cd .. && bash scripts/verify-compose-profile-contracts.sh ## 5. 성능 lane -- 일부 performance lane은 시간 단언을 `performance.assertions.enabled` 속성으로 켠다. workflow는 이 값을 `true`로 준다(`integration-main.yml`의 `GRADLE_OPTS`). -- leaf마다 기본값이 다르다: httpclient lane은 `false`(`src/adapter/outbound/httpclient/build.gradle`), persistence-mongo lane은 `true`(`src/adapter/outbound/persistence-mongo/build.gradle`). -- 그래서 desktop에서 `performanceCheck`를 돌릴 때는 workflow와 같게 `-Pperformance.assertions.enabled=true`를 준다. 안 주면 httpclient의 시간 단언 없이 통과한다. +- performance lane은 상한을 매번 단언한다. 측정만 하고 통과하는 모드는 없다. 정본은 `AGENTS.md` 「Gradle 정책 권위」와 `docs/testing/TESTING_STRATEGY.md`의 PERFORMANCE 문단이다. +- strict lane convention이 테스트 JVM에 `performance.assertions.enabled=true`를 넣는다. leaf나 lane은 이 값을 선언하지 않는다. +- 빌드(`-P`, `GRADLE_OPTS`)나 lane이 `true` 아닌 값을 주면 테스트 전에 실패한다. skip된 테스트가 하나라도 있어도 실패한다. `-Pperformance.assertions.enabled=true`는 받지만 줄 필요가 없다. +- 그래서 desktop에서 손으로 돌리는 `./gradlew performanceCheck`와 workflow가 같은 상한을 단언한다. +- 판정 없이 숫자만 보려면 JMH가 있는 leaf의 `./gradlew ::jmh`를 쓴다. 게이트가 아니다. - 시간 단언은 다른 빌드가 돌지 않는 머신에서만 뜻이 있다. 그래서 performance lane은 PR·main 단계가 아니라 `performanceCheck`에 있다. 회귀를 막는 장치: @@ -123,7 +125,8 @@ cd .. && bash scripts/verify-compose-profile-contracts.sh | lane 정책을 바꿨는데 캐시가 옛 결과로 통과 | lane 정책 값을 Test 입력으로 | | 게이트 밖에서 실패한 채 방치된 검사 | `testQualityCheck`(`mainCheck`) | | 실서버 계약이 어느 게이트에도 없음 | lane을 단계에 연결 | -| 시간 단언을 끈 채 performance lane 실행 | 5절 속성 | +| 시간 단언을 끈 채 performance lane 실행 | convention이 단언을 켜고, 끄는 값이나 skip이 있으면 테스트 전에 실패(5절) | +| 캐시에서 가져온 결과를 지금 통과한 것으로 셈 | 기준 상태 확인과 시간·환경에 민감한 테스트는 그 태스크를 `--rerun`으로 다시 돌린다 | | 외부 이미지가 사라져 다른 lane 결과까지 가림 | 테스트 이미지를 `src/config/testing/container-images.properties` 한 곳에 digest로 고정, main 단계는 `--continue` | 게이트 장치 자체를 바꿨으면 일부러 망가뜨린 입력으로 실패하는 것을 본다. 판독기를 바꿨으면 바꾸기 전후로 실제 workflow의 판정이 같은지 비교한다. From aef713b3c5660a564f55d4983d816e5de346322e Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 6 Nov 2026 21:44:33 +0900 Subject: [PATCH 08/71] =?UTF-8?q?docs(manual):=20=EB=B3=B8=EB=AC=B8?= =?UTF-8?q?=EC=9D=98=20=EC=9D=B4=EB=A0=A5=20ID=EB=A5=BC=20=EA=B1=B7?= =?UTF-8?q?=EC=96=B4=EB=82=B4=EA=B3=A0=20=EA=B7=BC=EA=B1=B0=EB=A5=BC=20evi?= =?UTF-8?q?dence=EB=A1=9C=20=EC=98=AE=EA=B8=B4=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit docs/manual/ 본문 9줄에 리뷰 ID(RR-, RR3-, RR5-, RR6-), 설계 결정 번호(D4), 번호만 쓴 소유자 결정("소유자 결정 5")이 있었다. 지난 리뷰를 모르는 독자는 이 괄호를 따라갈 수 없고, docs-writing.md 4절 6단계가 금지한다. 괄호 안의 ID만 걷어내고 문장의 뜻은 바꾸지 않았다. 지난 일을 근거로 든 곳은 날짜와 내용으로 바꿨다(2026-11-05 확인 리뷰, 2026-09-25 소유자 결정). D4는 규칙 이름 대신 "쓰기 유스케이스의 권한 선언 검사"로 풀었다. 걷어낸 ID와 원래 괄호, 원래 리뷰 문서는 docs/work/evidence.md 8절에 모았다. 리뷰 문서로 링크를 거는 안은 본문이 다시 이력을 가리키게 되어 버렸다. 검사 스크립트 패턴이 못 잡는 "리뷰 NN-NN", "1라운드 NN-NN" 꼴의 ID는 이 커밋 범위 밖이라 남겼다. 검증: python3 scripts/check-work-docs.py --history docs/manual (lines with history IDs: 0, rc=0), check-work-docs.py 전체 rc=0, --links docs 깨진 링크 0. document-contract lane은 desktop에서 돌린다. --- docs/manual/05-idempotency.md | 14 +++++++------- docs/manual/07-authorization.md | 6 +++--- docs/manual/08-testing.md | 2 +- docs/manual/09-outbox-events.md | 4 ++-- docs/work/evidence.md | 17 +++++++++++++++++ 5 files changed, 30 insertions(+), 13 deletions(-) diff --git a/docs/manual/05-idempotency.md b/docs/manual/05-idempotency.md index a076b5a4..72cde83c 100644 --- a/docs/manual/05-idempotency.md +++ b/docs/manual/05-idempotency.md @@ -54,7 +54,7 @@ DB 커밋 중 연결 끊김 ───────────────── | 500 `IDEMPOTENCY_RECOVERY_REQUIRED` | 이전 시도 효과를 증명 못함 | 자동 재시도 안 함. 같은 키 재전송은 안전(재생·실행·다시 500을 서버가 판정, 다시 돌리지 않음). 업무 데이터로 확인하고, 효과가 없다고 확인된 뒤에만 운영 절차에 따라 새 키 | | 500 `DB_COMPLETION_UNKNOWN`, `retryable=false` | DB 커밋 중 연결 끊김. 커밋됐을 수도 있음 | 키 없이 재시도 금지. KEYED면 같은 키로 재전송하면 서버가 판정 | -같은 키 재전송이 무엇을 막는지는 저장소마다 다르다(재리뷰 2026-11-04 RR5-01-05, 라운드6 RR6-02-05, 정본 +같은 키 재전송이 무엇을 막는지는 저장소마다 다르다(정본 `docs/web/http-contract.md` 2절). Redis 저장소에서 같은 키 재전송은 효과가 있었을 수 있는 작업을 다시 돌리지 않는다. PostgreSQL 저장소를 템플릿처럼 쓰기 트랜잭션 하나로 쓰면 실패한 요청의 기록은 롤백되어 다음 같은 키 요청이 다시 실행한다. 그래서 트랜잭션 밖 효과는 따로 멱등하게 만든다. 첫 시도가 processing lease(기본 30s)보다 @@ -74,15 +74,15 @@ DB 커밋 중 연결 끊김 ───────────────── claim의 lease가 작업 시작 전에 끝나면 두 저장소 모두 시작을 거절하고(`LEASE_EXPIRED`), executor는 작업을 돌리지 않은 채 503 `IDEMPOTENCY_UNAVAILABLE`로 답한다. 다음 같은 키 요청이 그 claim을 넘겨받아 실행한다. -`IdempotencyClaimAttempt`를 재시도 사이에 들고 있다가 같은 attempt로 다시 부르는 호출자도 넘겨받는다(라운드6 -RR6-02-01. 전에는 같은 claim을 재생받아 시작을 다시 거절당해 기록이 사라질 때까지 503이었다). 같은 attempt를 -두 호출이 동시에 쓰면 서버가 가려내지 못하므로, 재시도는 앞 호출이 돌아온 뒤에 한다. +`IdempotencyClaimAttempt`를 재시도 사이에 들고 있다가 같은 attempt로 다시 부르는 호출자도 넘겨받는다(2026-11-05 +확인 리뷰가 찾아 고쳤다. 전에는 같은 claim을 재생받아 시작을 다시 거절당해 기록이 사라질 때까지 503이었다). +같은 attempt를 두 호출이 동시에 쓰면 서버가 가려내지 못하므로, 재시도는 앞 호출이 돌아온 뒤에 한다. 기록은 lease + `replay-ttl` 동안 남고, `replay-ttl`이 lease보다 짧으면 기동이 실패한다 -(`IdempotencyStoreContract`, 재리뷰 2026-11-04 RR-01-11·RR-03-11). 작업이 실패로 끝나 executor가 포기나 +(`IdempotencyStoreContract`). 작업이 실패로 끝나 executor가 포기나 재시도 가능으로 표시한 기록은 표시한 때부터 `failure-retention`(기본 24h) 동안 남는다(PostgreSQL을 트랜잭션 하나로 쓰면 위처럼 롤백과 함께 사라진다). `failure-retention`이 `replay-ttl`보다 짧으면 기동이 실패한다. -짧으면 효과 불명으로 포기한 기록이 먼저 사라져 같은 키 재전송이 작업을 다시 돌리기 때문이다(RR3-03-02, -2026-11-04 소유자 결정). 거꾸로 말하면 `replay-ttl`(`APP_IDEMPOTENCY_TTL`)은 lease 이상, `failure-retention` +짧으면 효과 불명으로 포기한 기록이 먼저 사라져 같은 키 재전송이 작업을 다시 돌리기 때문이다(2026-11-04 +소유자 결정). 거꾸로 말하면 `replay-ttl`(`APP_IDEMPOTENCY_TTL`)은 lease 이상, `failure-retention` 이하로 둔다. 409를 `retryable=true`로 바꾼 이유(리뷰 02-01 결정): 같은 키 재전송은 서버가 안전하게 판정하므로 다시 diff --git a/docs/manual/07-authorization.md b/docs/manual/07-authorization.md index 468f0901..c1f0bd40 100644 --- a/docs/manual/07-authorization.md +++ b/docs/manual/07-authorization.md @@ -95,7 +95,7 @@ JWT의 `realm_access.roles`와 **자기 client**(`app.security.audience`)의 `re 예약 작업은 controller와 같은 leaf에 놓이기 쉽다. 그때 "지금 실행" endpoint가 작업 bean을 주입받아 부르면 권한 검사 없는 쓰기를 사용자가 부르게 된다. 아래 `USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS`가 이것을 빌드에서 막는다. 사용자도 같은 일을 시켜야 하면 `@RequiresPermission`을 단 사용자용 유스케이스를 따로 -만든다(아래 D4 문단). +만든다(아래 권한 선언 검사 문단). | 규칙 | 무엇을 막나 | 어디 | | --- | --- | --- | @@ -112,8 +112,8 @@ JWT의 `realm_access.roles`와 **자기 client**(`app.security.audience`)의 `re 들이면 그 패키지를 이 목록에 더한다. 설정 안의 요청 처리 코드를 알아보는 요청 처리기 타입 (`ARE_REQUEST_HANDLER_TYPES`)도 나열 목록이라, 새 전송 라이브러리의 handler 타입을 함께 더한다. -D4 실패(`MUTATING_USE_CASES_DECLARE_REQUIRED_PERMISSION`)를 끄려고 이 표시를 쓰지 않는다. 사용자가 부르는 -쓰기라면 권한을 선언하고 역할에 매핑한다. 같은 쓰기를 사용자도 시스템도 부르면 유스케이스를 둘로 나눈다 +쓰기 유스케이스의 권한 선언 검사(`MUTATING_USE_CASES_DECLARE_REQUIRED_PERMISSION`) 실패를 끄려고 이 표시를 +쓰지 않는다. 사용자가 부르는 쓰기라면 권한을 선언하고 역할에 매핑한다. 같은 쓰기를 사용자도 시스템도 부르면 유스케이스를 둘로 나눈다 (사용자용 `@RequiresPermission`, 시스템용 `@SystemInvoked`). 업무 규칙은 domain에 두고 둘이 같이 쓴다. ### 규칙이 못 보는 길 diff --git a/docs/manual/08-testing.md b/docs/manual/08-testing.md index 631d0af7..8cba48dd 100644 --- a/docs/manual/08-testing.md +++ b/docs/manual/08-testing.md @@ -35,7 +35,7 @@ fake와 실제 adapter가 **같은 계약**을 통과해야 fake 위의 유스 1. 이름은 lowerCamelCase 행동 문장. 이름이 말한 성질을 단언한다. 예: 이름에 "트랜잭션 전에"를 넣었으면 트랜잭션이 없었다는 것도 단언하거나, 이름에서 뺀다. 2. `@DisplayName`은 메서드 이름으로 못 쓰는 내용(숫자, 기호, 이유)이 있을 때만, **한국어**로 - (소유자 결정 5). 예: `@DisplayName("이름이 NAME_MAX_LENGTH + 1자이면 거절한다")`. + (2026-09-25 소유자 결정). 예: `@DisplayName("이름이 NAME_MAX_LENGTH + 1자이면 거절한다")`. 3. 본문 3문장 이상이면 `// given` `// when` `// then`. `// when`은 하나. 예외는 `catchThrowable`로 분리. 4. then은 when의 결과 하나만. 예외는 타입과 reason/code를 함께. 5. 포트 대역은 hand-rolled fake 하나, **포트 소유 leaf의 testFixtures**에. Mockito는 프레임워크 경계와 diff --git a/docs/manual/09-outbox-events.md b/docs/manual/09-outbox-events.md index 61b75b94..8d884b87 100644 --- a/docs/manual/09-outbox-events.md +++ b/docs/manual/09-outbox-events.md @@ -75,7 +75,7 @@ draft는 `IntegrationEventDrafts.draft(contract, eventId, aggregate, order, occu 아니라 약 1.7×10¹⁵일 수 있다. 소비자는 번호를 "마지막으로 본 값보다 큰가"로만 비교하고 연속성을 가정하지 않는다. 비교는 aggregate identity(tenant scope 포함) 단위다. tenant scope를 바꾸는 배포는 옛 버전 인스턴스를 모두 멈춘 뒤 새 버전을 띄운다 — 섞여 돌면 새 scope의 번호가 옛 버전이 방금 쓴 번호보다 - 작을 수 있다(runbook `outbox-dead-letter.md` §8, 재리뷰 2차 RR-02-10). + 작을 수 있다(runbook `outbox-dead-letter.md` §8). ## relay와 실패 @@ -86,7 +86,7 @@ draft는 `IntegrationEventDrafts.draft(contract, eventId, aggregate, order, occu DEAD가 되지 않는다(1라운드 06-01·06-03). 대신 끝이 없다: 진짜 인증 오류, Kafka adapter가 이름을 모르는 broker 거부도 영원히 재시도된다. 행의 `last_failure_code`와 로그의 `error.reason`이 원인 코드를 남기고, `outbox.retry.long.size`가 오래 재시도 중인 행을 센다. 처분(보류·재개·skip)은 publish-failed runbook - §4.1이다(재리뷰 RR-05-03). + §4.1이다. - 발행 응답을 못 받으면 결과 불명(`OutboxPublishAmbiguousException`) — 05장 규칙과 같다. - 운영: `docs/runbooks/outbox-dead-letter.md`, `docs/runbooks/outbox-publish-failed.md`. diff --git a/docs/work/evidence.md b/docs/work/evidence.md index 0beb7a9d..5135dcf4 100644 --- a/docs/work/evidence.md +++ b/docs/work/evidence.md @@ -149,3 +149,20 @@ - `RR-07-05`(CSRF 제외 규칙의 이유)는 README 6절 r4-f 행이 내용으로 다룬다. - 나머지 20건은 round6 Minor다(`RR6-01-02`~`06`·`08`·`09`, `RR6-02-02`·`04`·`05`, `RR6-03-02`~`05`, `RR6-04-01`~`06`). README 17절은 영역별 건수만 적었고, r10 묶음이 영역 단위로 고쳤다. - 이 검사는 "색인에 이름이 있나"만 본다. 고쳤는지는 처리 표와 확인 리뷰가 본다. 앞으로의 리뷰 README는 모든 ID를 이름으로 적는다(`improve.md` 4.1절 7단계). + +## 8. `docs/manual/`에서 걷어낸 이력 ID (2026-11-06) + +`docs/manual/` 본문에서 리뷰 ID와 번호만 쓴 결정을 걷어냈다. 문장의 뜻은 그대로이고, 괄호 안 근거만 여기로 옮겼다. 줄 번호는 걷어내기 전 기준 커밋 `06f520e6`의 줄이다. + +| 원래 위치 | 원래 괄호 | 지금 본문 | 근거 | +| --- | --- | --- | --- | +| `docs/manual/05-idempotency.md:57` | "재리뷰 2026-11-04 RR5-01-05, 라운드6 RR6-02-05, 정본 `docs/web/http-contract.md` 2절" | 정본 가리킴만 남겼다 | `1103/RR5-01-05`(PostgreSQL 기본 모양에서는 lease 상황이 생기지 않는다, `round5/review.md`), `1103/RR6-02-05`(매뉴얼 첫 문장이 PostgreSQL 항목과 어긋났다, `round6/02-idempotency-outbound.md`) | +| `docs/manual/05-idempotency.md:78` | "라운드6 RR6-02-01" | "2026-11-05 확인 리뷰가 찾아 고쳤다" | `1103/RR6-02-01`(`LEASE_EXPIRED`로 거절당한 attempt를 다시 보내도 503만 받았다, `round6/02-idempotency-outbound.md`). 수정 커밋 `6e992970`(2026-11-05), `1103` README 17절 r10-02 | +| `docs/manual/05-idempotency.md:81` | "재리뷰 2026-11-04 RR-01-11·RR-03-11" | `IdempotencyStoreContract` 가리킴만 남겼다 | `1103/RR-01-11`(lease가 지난 실행 기록을 Redis가 넘겨받아 다시 실행했다, `round2/01-core-app-inbound.md`), `1103/RR-03-11`(replay TTL이 lease보다 짧으면 key가 lease 도중 사라졌다, `round2/03-outbound.md`). 수정 커밋 `1885bf8d`(2026-11-04) | +| `docs/manual/05-idempotency.md:84` | "RR3-03-02, 2026-11-04 소유자 결정" | "2026-11-04 소유자 결정" | `1103/RR3-03-02`(서버가 기억하는 기간 문서가 `failure-retention`을 빠뜨렸다, `round3/03-outbound.md`) | +| `docs/manual/07-authorization.md:98`, `:115` | "D4 문단", "D4 실패" | "권한 선언 검사 문단", "쓰기 유스케이스의 권한 선언 검사 실패" | D4는 인증·인가 계약 설계(`feature-authentication-authorization-contract`)의 결정 번호로, 규칙 `MUTATING_USE_CASES_DECLARE_REQUIRED_PERMISSION`을 가리킨다. 그 설계 문서는 이 repo에 없다. `ApplicationBoundaryArchitectureTest`의 주석 "D1 / D4"와 `1101/01-core-and-feature-pattern.md` 「ArchUnit D4」가 같은 번호다 | +| `docs/manual/08-testing.md:38` | "소유자 결정 5" | "2026-09-25 소유자 결정" | `docs/reviews/2026-09-25-review-followup-status.md` 「소유자 결정」 5번(`@DisplayName`은 한국어) | +| `docs/manual/09-outbox-events.md:78` | "재리뷰 2차 RR-02-10" | runbook 가리킴만 남겼다 | `1103/RR-02-10`(tenant scope가 바뀌는 배포의 rolling 구간에서 새 번호가 옛 버전이 쓴 번호보다 작다, `round2/02-persistence-messaging.md`) | +| `docs/manual/09-outbox-events.md:89` | "재리뷰 RR-05-03" | runbook 가리킴만 남겼다 | `1103/RR-05-03`(끝나지 않는 재시도 행을 운영자가 구분·처분할 수단이 없었다, `05-messaging.md`) | + +- `RR-01-11`·`RR-02-10`·`RR-03-11`은 2차 재리뷰(`round2/`) 문서의 발견이다. 그 문서들은 1차 번호에 이어 `RR-` 접두어를 그대로 썼다. 머리말 표기("`RR-`는 1차 재리뷰")의 예외다. From 319964912590b46e85e60151bb21b9edf05b5242 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 6 Nov 2026 21:50:48 +0900 Subject: [PATCH 09/71] =?UTF-8?q?docs(specs):=20error-codes.yaml=20log=5Fl?= =?UTF-8?q?evel=20=EC=B9=B8=20=EC=B2=98=EB=A6=AC=20=EC=84=A4=EA=B3=84=20?= =?UTF-8?q?=EB=A9=94=EB=AA=A8=EB=A5=BC=20=EB=8D=94=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: docs/registries/error-codes.yaml의 log_level 칸은 읽는 코드와 테스트가 없다. 코드의 로그 레벨은 오류 코드가 아니라 실패 종류와 경로가 정한다 (ServerFailureLog, AuthErrorResponseWriter). 그래서 내는 곳이 있는 47행 중 33행이 실제 레벨과 다르고, 런북 2곳이 틀린 레벨을 증상으로 적는다. 고른 방법: 설계 메모만 쓴다. 대안 셋(A 칸 삭제, B 코드 규칙에 맞추고 테스트로 고정, C 규범화해 코드가 읽음)을 비교하고 A를 권한다. B는 규칙의 손 사본을 테스트에 하나 더 만들고, C는 리뷰를 거친 4xx 무로그 설계를 뒤집고 로그 양을 늘린다. 소유자 결정 4건(칸, 재생성 방지 단언, 보안 필터 5xx 레벨, 401 서명 불일치 레벨)을 7절에 모았다. 위험·한계: 60행 대조는 코드 읽기 결과이고 실행 탐침은 돌리지 않았다. repo 밖 운영 도구가 이 칸을 읽는지는 모른다(결정 4). 코드와 yaml은 바꾸지 않았다. 조사 중 본 LockAcquisitionTimeoutException 미매핑은 9절에 범위 밖 결함 후보로만 적었다. 검증: python3 scripts/check-work-docs.py rc=0. 메모 2.3 표의 코드 목록을 레지스트리 60개 코드와 대조해 누락·중복 0을 확인했다. --- .../2026-11-06-error-code-log-level-design.md | 231 ++++++++++++++++++ 1 file changed, 231 insertions(+) create mode 100644 docs/superpowers/specs/2026-11-06-error-code-log-level-design.md diff --git a/docs/superpowers/specs/2026-11-06-error-code-log-level-design.md b/docs/superpowers/specs/2026-11-06-error-code-log-level-design.md new file mode 100644 index 00000000..dc736ed0 --- /dev/null +++ b/docs/superpowers/specs/2026-11-06-error-code-log-level-design.md @@ -0,0 +1,231 @@ +# `error-codes.yaml`의 `log_level` 칸 — 설계 메모 + +- 상태: **소유자 결정 대기** (2026-11-06). 결정할 것은 7절이다. +- 기준 커밋: `06f520e6` (`refactor/maturity-review-2026-11`) +- 크기: 중간(brief). 이 메모가 고르는 안을 실제로 적용하는 일은 **큼**이다. 오류 코드 레지스트리는 공개 계약이라 + 파일 하나여도 큼이다(`docs/work/README.md` 2절). 그래서 이 메모는 대안 비교까지 하고 멈춘다. 코드와 yaml은 + 바꾸지 않았다. +- 요청(총괄 brief 원문): "`docs/registries/error-codes.yaml`의 `log_level` 칸은 읽는 코드가 없고, 값이 코드와 다른 + 곳이 있다(`IDEMPOTENCY_UNAVAILABLE`: 문서 WARN, 코드 ERROR). 이 칸을 어떻게 할지 설계 메모를 쓰고 소유자 결정을 + 묻는다." +- 처음 나온 곳: 재리뷰 round6이 "규범인지 판단하지 않았다"로 남긴 항목 + (`docs/reviews/2026-11-03-rereview/round6/02-idempotency-outbound.md:217`). + +## 1. 결론 + +권하는 안은 **A — 칸을 지운다**이다. 로그 레벨은 오류 코드 하나가 아니라 실패의 종류와 경로가 정하고, 그 규칙은 +이미 코드 한 곳(`ServerFailureLog`)에 있다. 레지스트리 머리말은 그 규칙을 가리키기만 한다. 칸 값을 증상으로 적은 +런북 2곳은 실제 로그 줄로 고친다. + +칸과 별개로 동작 질문이 둘 남는다. 보안 필터가 5xx 두 코드를 WARN으로 남기는 것(결정 2), 문서가 ERROR로 의도한 401 +세 코드(결정 3)다. + +## 2. 지금 어떻게 되어 있나 + +### 2.1 칸을 읽는 곳 + +- 스키마: `docs/registries/error-codes.yaml:18` `log_level: ERROR | WARN | INFO`. 60행 모두 값이 있다(ERROR 25, + WARN 26, INFO 9). +- 코드와 테스트: 읽는 곳이 없다. `src`·`scripts`의 java·py·gradle·sh에서 `log_level`·`logLevel` 검색 결과 0건이다. +- 테스트가 읽는 칸: `category`·`http_status`·`retryable`·`client_safe_message`·`runbook_link`·`owner_branch`· + `compatibility_impact`·`required_test`다(테스트 코드의 `get("<칸>")` 집계). `log_level`과 `owner_layer`만 + 아무도 읽지 않는다. +- 스키마 검사(`ContractRegistrySchemaGovernanceTest`, `RegistryGovernanceCatalog.java:217, 247-253`)는 필수 칸만 본다. + 모르는 칸을 막지 않는다. +- 값의 이력: `git log -S log_level`의 네 커밋(`821fe00c`, `9da00eb7`, `c4a066df`, `bbe944bd`)은 행을 넣거나 뺐다. + 있던 행의 레벨 값이 바뀐 적은 없다(커밋 사이 코드별 값 비교 결과 차이 0). +- 런북: 두 곳이 칸 값을 증상으로 적는다. + - `docs/runbooks/auth-token-invalid-signature.md:16`: "`log_level=ERROR` — may indicate forged tokens" + - `docs/runbooks/authz-tenant-mismatch.md:16`: "`log_level=ERROR`" +- 경보: `docs/registries/metrics.yaml`의 경보 기준은 모두 지표다(error_rate, p99 등). 로그 레벨을 세는 경보는 없다 + (`logback_events`·`level=error` 검색 0건). +- 파생 서비스 `tech-log-backend`(`a000f87`): 자기 `error-codes.yaml` 96행에 `log_level`을 채운다. 설계서가 새 행마다 + 이 칸을 채우라고 적는다(`docs/superpowers/specs/2026-08-18-techlog-studio-backend-design.md:382`). 그쪽에도 이 + 칸을 읽는 코드는 없다(`git grep log_level`, java·gradle·yaml·sh 0건). + +### 2.2 코드가 로그 레벨을 정하는 방식 + +레벨은 오류 코드가 아니라 **실패의 종류와 경로**가 정한다. + +```text +요청 실패 ─┬─ 보안 필터(401·403·JWKS·인증 설정) ─ AuthErrorResponseWriter ─────────── 늘 WARN + ├─ IllegalArgumentException ─────────── ServerFailureLog.refusedArgument ─── WARN + ├─ ApiErrorCarrier ─ ServerFailureLog.of ─┬─ PersistenceFailureException ── ERROR (상태 무관) + │ ├─ DependencyFailureException ── ERROR (상태 무관) + │ ├─ 그 밖의 5xx ───────────────── ERROR + │ └─ 4xx ───────────────────────── 남기지 않음 + ├─ Spring MVC 예외 ─ handleExceptionInternal ── 5xx면 ERROR, 4xx면 남기지 않음 + └─ 그 밖의 예외 ─ handleUnknown ── INTERNAL_ERROR로 답하고 ERROR +배경 작업 ─ outbox 실패 보고, executor 거절 ── ERROR +``` + +출처: + +- 규칙: `src/shared-contract/src/main/java/dev/caskeleton/shared/error/ServerFailureLog.java:54-79`. + 4xx를 남기지 않는 이유는 같은 파일 25행 "A client-side carrier is not logged: it is an answer, not an incident"다. + IAE WARN은 91-96행이다. +- 네 전송이 같은 줄을 쓴다. + - carrier ERROR: web `GlobalExceptionHandler.java:173-176`, gRPC `GrpcExceptionHandlingInterceptor.java:135-136`, + GraphQL `GraphQlWireErrorMapper.java:134-135`, STOMP `StompHandlerFailureLog.java:35-36` + - IAE WARN: web `GlobalExceptionHandler.java:96-97`, gRPC `:139-140`, GraphQL `:137-138`, STOMP `:40-41` +- 보안 필터: `src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/AuthErrorResponseWriter.java:32` + `log.warn("security failure: code={} …")`. 인증 진입점과 접근 거부 처리기가 둘 다 이 writer를 쓴다. +- Spring MVC: `GlobalExceptionHandler.java:397-401`. 그 밖의 예외: 같은 파일 195-203행. +- 배경 작업: `Slf4jOutboxRelayFailureReportAdapter.java`의 `atError()`, `LoggingAbortPolicy.java:35`. +- 이 규칙은 리뷰를 거쳐 정한 설계다. 네 전송이 한 정책을 쓰게 했고(`ServerFailureLog` Javadoc 첫 문단), IAE를 네 + 전송에서 같은 WARN 한 줄로 남기게 했다(RR6-01-06, `docs/reviews/2026-11-03-rereview/README.md` 17절 r10-01). + +그래서 레벨은 오류 코드 하나에 값 하나로 떨어지지 않는다. + +- 같은 `BAD_PARAMETER`라도 IAE에서 오면 WARN이다. 타입 변환 실패에서 오면 남기지 않는다 + (`GlobalExceptionHandler.java:108-116`). +- 같은 409라도 영속성 실패면 ERROR다. 멱등 in-flight면 남기지 않는다. + +### 2.3 60행 대조 + +방법: 행마다 main 코드에서 그 코드를 내는 곳을 찾았다(`grep -rlw src --include='*.java'` 중 `/main/`). 그 경로에 +2.2의 규칙을 대어 레벨을 정했다. 코드를 읽은 결과이고, 실행 탐침은 돌리지 않았다(이유는 6절 가정 4). + +| 결과 | 행 | 코드 | +| --- | --- | --- | +| 같다 | 14 | WARN: `AUTH_TOKEN_MISSING`, `AUTH_TOKEN_MALFORMED`, `AUTH_TOKEN_EXPIRED`, `AUTH_KID_UNKNOWN`. ERROR: `DB_UNAVAILABLE`, `DB_IDLE_IN_TX_TIMEOUT`, `DB_COMPLETION_UNKNOWN`, `IDEMPOTENCY_COMPLETION_UNKNOWN`, `IDEMPOTENCY_RECOVERY_REQUIRED`, `ADAPTER_DISABLED`, `INTERNAL_ERROR`, `OUTBOX_PUBLISH_FAILED`, `OUTBOX_DEAD_LETTER`, `JOB_EXECUTOR_REJECTED` | +| 문서 ERROR, 코드 WARN | 5 | `AUTH_TOKEN_INVALID_SIGNATURE`, `AUTH_ISSUER_MISMATCH`, `AUTH_AUDIENCE_MISMATCH`(401), `AUTH_JWKS_UNAVAILABLE`(503), `INTERNAL_AUTH_MISCONFIGURATION`(500). 보안 필터가 모두 WARN으로 남긴다 | +| 문서 WARN, 코드 ERROR | 10 | `IDEMPOTENCY_UNAVAILABLE`(503 carrier). 영속성 실패 9개: `DB_SERIALIZATION_FAILURE`, `DB_DEADLOCK`, `DB_NULL_VIOLATION`, `DB_FK_VIOLATION`, `DB_UNIQUE_VIOLATION`, `DB_CHECK_VIOLATION`, `DB_OPTIMISTIC_CONFLICT`, `DB_LOCK_TIMEOUT`(409), `DB_QUERY_CANCELED`(503). JPA 예외는 모두 `PersistenceFailureException`의 하위 타입이다(`JpaPersistenceException.java:22`) | +| 문서는 레벨, 코드는 남기지 않음 | 15 | `IDEMPOTENT_IN_FLIGHT`, `IDEMPOTENT_REQUEST_MISMATCH`, `MAPPING_FAILED`, `VALIDATION_FAILED`, `PRECONDITION_FAILED`, `METHOD_NOT_ALLOWED`, `NOT_ACCEPTABLE`, `PAYLOAD_TOO_LARGE`, `URI_TOO_LONG`, `UNSUPPORTED_MEDIA_TYPE`, `ROUTE_NOT_FOUND`, `RATE_LIMIT_EXCEEDED`, `INVALID_TOKEN`, `FORBIDDEN`, `BATCH_PARTIAL_FAILURE` | +| 경로마다 다름 | 3 | `BAD_PARAMETER`(문서 INFO; IAE면 WARN, 타입 변환이면 없음). `AUTHZ_INSUFFICIENT_PERMISSION`(문서 WARN; 필터면 WARN, controller method security면 `handleForbidden`이라 없음). `UNAUTHENTICATED`(문서 WARN; web은 없음, gRPC는 인증 정책이 예외를 던질 때만 WARN — `GrpcAuthenticationInterceptor.java:55`) | +| 템플릿 main에 내는 곳 없음 | 13 | `AUTH_CLAIM_MAPPING_FAILED`, `AUTHZ_TENANT_MISMATCH`, `JVM_OOM`, `DEPENDENCY_TIMEOUT`, `DEPENDENCY_CONNECT_FAILED`, `DEPENDENCY_DNS_FAILED`, `DEPENDENCY_4XX_CLIENT`, `DEPENDENCY_5XX_SERVER`, `DEPENDENCY_CIRCUIT_OPEN`, `JOB_TIMEOUT`, `JOB_DEAD_LETTER`, `ACTUATOR_FORBIDDEN`, `LOCK_ACQUISITION_TIMEOUT` | + +- 내는 곳이 있는 47행 중 33행이 문서와 다르다. brief가 든 `IDEMPOTENCY_UNAVAILABLE`은 그중 하나다. +- `DEPENDENCY_*`: 파생 서비스의 어댑터가 `DependencyFailureException`으로 던지면 ERROR가 된다. 그때는 문서가 WARN인 + `DEPENDENCY_CIRCUIT_OPEN`도 어긋난다. +- `LOCK_ACQUISITION_TIMEOUT`은 레벨과 별개의 문제가 있다(9절). + +### 2.4 어긋남이 실제로 해를 끼치는 곳 + +- **런북 증상이 틀렸다.** `auth-token-invalid-signature.md`는 `log_level=ERROR`를 증상으로 적는다. 실제 줄은 + WARN `security failure: code=AUTH_TOKEN_INVALID_SIGNATURE …`다. ERROR로 거르는 운영자는 이 사건을 못 본다. +- **칸을 채우는 일이 헛수고다.** 새 코드를 만드는 사람이 칸을 채워도 동작이 바뀌지 않는다. 파생 서비스는 96행에 + 값을 골라 적었다. +- 경보는 로그 레벨을 쓰지 않는다. 그래서 이 어긋남으로 경보가 빠지지는 않는다. + +## 3. 선행 사례 + +| 출처 | 1차/2차 | 그들이 한 것 | 한계 | 가져올 것 | +| --- | --- | --- | --- | --- | +| 이 repo `client_safe_message` 칸 (`c4a066df`, 소유자 결정 11) | 1차 | 행마다 다르던 문구를 Category별 문구 표 하나(`ClientErrorMessages`)로 코드에 두었다. 칸은 그 값과 같아야 한다고 테스트로 고정했다(`OperationalErrorRegistryContractTest.everyRegistryClientMessageIsTheSharedCategoryMessage`) | 문구가 category만으로 정해져서 고정이 쉬웠다 | 코드가 원본이고 칸은 테스트가 고정한다. 레벨은 코드 하나로 정해지지 않는다는 점이 다르다(2.2) | +| 이 repo `category`·`http_status`·`retryable` | 1차 | enum이 원본이다. yaml을 enum과 테스트로 대조한다(`theEnumAndTheRegistryAgree`) | — | 레지스트리 칸은 코드가 읽거나 테스트가 고정한다는 이 repo의 관행 | +| 이 repo `env-keys.yaml`의 `required_when` (`0a6dd0e4`) | 1차 | 런타임이 강제한 적 없는 요구("app.redis.mode=sentinel")를 지우고 실제 동작에 맞췄다(`docs/registries/env-keys.yaml:2269-2273`) | — | 강제하지 않는 레지스트리 문장을 규범처럼 두지 않는다. 실제 동작으로 고친다 | +| JBoss Logging Tools (Hibernate·WildFly가 씀) | 1차, | 메시지 id와 레벨을 코드의 annotation 한 곳에 둔다(`@Message(id = …)`, `@LogMessage(level = ERROR)`). 보고서(id, 해결 문서 링크, 메시지, 레벨)는 annotation에서 만든다(AsciiDoc·XML) | 메시지마다 레벨이 하나인 모델이다. 경로마다 레벨이 다른 우리 설계에는 그대로 맞지 않는다 | 레벨을 문서로 보이고 싶으면 손으로 쓴 칸이 아니라 코드에서 뽑는다 | +| Spring Framework `AbstractHandlerExceptionResolver` | 1차, `spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerExceptionResolver.java`(main) | 예외 처리 로그는 처리기 코드가 정한다. 기본은 남기지 않고, `setWarnLogCategory`로 켜면 WARN 한 레벨로 남긴다 | 오류 코드별 레벨 표는 없다 | 처리된 클라이언트 오류는 기본으로 남기지 않는다. `ServerFailureLog`의 "4xx는 답이지 사건이 아니다"와 같은 판단이다 | + +## 4. 대안 + +### A. 칸을 지운다 + +- 머리말 스키마에서 `log_level` 줄을 뺀다. 대신 "로그 레벨은 오류 코드가 아니라 실패 종류와 경로가 정한다. 규칙은 + `ServerFailureLog` Javadoc과 `AuthErrorResponseWriter`"라고 적는다. +- 60행에서 `log_level:` 줄을 지운다. +- 런북 2곳의 증상 줄을 실제 로그 줄로 고친다. +- `docs/upgrade/`에 파생 서비스 안내를 한 줄 더한다. +- 선택(결정 1-b): 칸이 다시 생기지 않게 "행에 `log_level`이 없다"는 단언을 레지스트리 테스트에 둔다. 두면 파생 + 서비스도 자기 행에서 칸을 지워야 merge 뒤 테스트가 통과한다. + +### B. 칸을 남기고 코드에 맞춘 뒤 테스트로 고정한다 + +- 값 집합에 `NONE`(남기지 않음)과 `BY_PATH`(경로마다 다름)를 더한다. 60행을 2.3 표대로 고친다. +- 테스트는 `ServerFailureLog` 규칙을 다시 구현한 표(코드 → 기대 레벨)와 yaml을 대조한다. +- 문제: 레벨이 코드만으로 정해지지 않아서, 표가 규칙의 손 사본이 된다. 예외 종류(영속성·의존성 carrier)는 행에 + 없으므로, 테스트가 "`DB_*`면 ERROR"를 이름 접두어로 짐작해야 한다. 템플릿 main에 내는 곳이 없는 13행은 기대값을 + 정할 근거가 없다. + +### C. 칸을 규범으로 만들고 코드가 읽는다 + +- `ApiErrorCode`에 `logLevel()`을 더한다. `OperationalError`는 값을 갖고, 파생 enum은 default 메서드로 지금 규칙을 쓴다. +- 네 전송, 보안 필터, 배경 작업이 그 값으로 남긴다. yaml은 enum과 테스트로 대조한다. +- 동작이 바뀐다. 2.3의 33행이 지금과 다른 레벨이 된다. + - 문서가 INFO·WARN인 4xx 15행이 새로 로그를 남긴다. 404·400·429마다 한 줄씩이라, 스캐너·공격 트래픽이 로그 + 양을 정한다. + - 409 영속성 실패는 ERROR에서 WARN으로 내려간다. +- `ServerFailureLog`의 "4xx는 남기지 않는다"와 RR6-01-06 결정을 뒤집는다. 다시 열 조건(`docs/work/reference/decisions.md` + 1절)에 맞는 새 근거가 없다. +- `ApiErrorCode`는 shared-contract의 공개 인터페이스다. 파생 서비스의 enum이 영향을 받는다. + +### 버린 기준선: 주석만 달기 + +칸에 "참고용"이라 적고 `IDEMPOTENCY_UNAVAILABLE` 한 행만 고치는 안이다. 틀린 33행 중 1행만 고쳐지고 런북은 여전히 +틀린 증상을 적는다. 버린다. + +### 비교 + +| 대안 | 효과 | 비용 | 되돌리기 | 파생 서비스 영향 | 기존 결정과 충돌 | +| --- | --- | --- | --- | --- | --- | +| A 지움 | 틀린 값 33행과 틀린 런북 증상 2곳이 사라진다. 레벨의 원본이 코드 하나로 준다 | yaml 머리말·60줄, 런북 2곳, upgrade 1줄. 코드 변경 0 (1-b면 테스트 단언 1개) | 쉽다(revert) | 1-b 없으면 할 일 없음. 1-b면 자기 96행에서 칸을 지운다 | 없다. `client_safe_message`·`env-keys` 선례와 같은 방향 | +| B 맞추고 고정 | 칸이 맞는 값이 된다 | yaml 33행, 스키마, 새 테스트(규칙의 손 사본). 규칙을 바꿀 때마다 두 곳을 고친다 | 쉽다 | 같은 테스트가 파생 행도 읽으면 자기 행도 맞춰야 한다 | 없다. 다만 규칙 사본을 하나 더 만든다 | +| C 규범화 | 소유자가 코드마다 레벨을 고를 수 있다 | shared-contract 인터페이스, 전송 넷, 보안 필터, 배경 작업, 테스트. 로그 양이 는다 | 어렵다(공개 인터페이스, 운영 로그 모양) | `ApiErrorCode` 구현 enum, 로그 수집 규칙 | `ServerFailureLog` 설계, RR6-01-06 | + +## 5. 권하는 안: A + +- 이 칸이 담으려던 정보("이 코드가 얼마나 시끄러운가")는 코드가 이미 실패 종류로 정한다. 그 규칙은 리뷰를 거쳐 네 + 전송에 하나로 모였다. 코드별 칸은 그 규칙을 담을 모양이 아니다(2.2). +- B는 그 규칙의 손 사본을 테스트에 하나 더 만든다. 사본은 고칠 곳만 늘린다. 내는 곳이 없는 13행에는 고정할 값도 + 없다. +- C는 코드가 맞고 문서가 틀린 상황에서 코드를 문서에 맞춘다. 문서 값은 행을 처음 넣을 때 적은 뒤 한 번도 고친 적이 + 없다(2.1). 레벨을 따져 본 리뷰를 거친 쪽은 코드다. +- 이 repo의 관행은 "칸은 코드가 읽거나 테스트가 고정한다"이다. 이 관행에 맞는 길은 A와 B인데, B는 고정할 값이 + 없다. 그래서 A다. + +## 6. 반증할 수 있는 가정, 반론과 답 + +### 가정 + +1. **템플릿과 파생 서비스 밖에서 이 칸을 읽는 도구가 없다.** 틀렸다면: 로그 파이프라인이나 대시보드가 이 yaml을 + 읽고 있다면 칸 삭제가 그것을 깨뜨린다. 확인한 범위는 두 repo의 추적 파일이다. repo 밖 운영 도구는 모른다(결정 4). +2. **레벨은 오류 코드 하나로 정해지지 않는다.** 틀렸다면 B의 비용이 크게 준다. 확인: + `GlobalExceptionHandler.java:96-97`(IAE, WARN)과 `:108-116`(타입 변환, 로그 없음)가 같은 `BAD_PARAMETER`를 낸다. +3. **4xx를 남기지 않는 것은 의도다.** 틀렸다면, 즉 소유자가 4xx를 줄 단위로 추적하길 원하면 C가 맞다. 근거: + `ServerFailureLog.java:25`의 문장. 4xx 양은 `http.server.requests`의 `status=4xx` 지표로 이미 보인다 + (`metrics.yaml:18-40`). +4. **2.3 표는 코드 읽기로 충분하다.** 틀렸다면: 다른 경로가 같은 코드를 다른 레벨로 남기면 표 칸이 바뀐다. 결론 + ("대부분 다르다")은 33행 중 몇 행이 바뀌어도 유지된다. 탐침을 돌리지 않은 이유는 둘이다. + - 각 경로는 레벨을 바꾸는 분기가 없는 `log.error`/`log.warn` 한 줄이다. + - 기존 테스트가 같은 레벨을 고정한다: `GrpcExceptionHandlingInterceptorTest`·`StompHandlerFailureLogTest`· + `GraphQlWireErrorMapperTest`의 `Level.ERROR`/`Level.WARN` 단언, + `GlobalExceptionHandlerTest.anIllegalArgumentIsLoggedAtWarnByItsTypeWithoutItsMessage`. + +### 반론과 답 + +- **"레벨을 문서에서 한눈에 보는 가치가 있다."** 그 가치는 값이 맞을 때만 있다. 지금은 47행 중 33행이 틀렸다. + 꼭 보이고 싶다면 JBoss Logging처럼 코드에서 뽑아야 한다. 그것은 레벨이 코드별 값이 된 뒤(C)에나 가능하다. +- **"보안 쪽 ERROR(위조 토큰 의심)는 의도였다."** 의도는 런북 문장에 남아 있지만 구현된 적이 없다. 401 서명 실패를 + ERROR로 남기면 공격자가 ERROR 양을 정하게 된다. 감지가 필요하면 결정 3에서 따로 고른다. +- **"칸을 지우면 파생 서비스가 upstream merge 때 할 일이 생긴다."** 1-b를 두지 않으면 할 일이 없다. 1-b를 두면 + 지울 일이 생기지만, 같은 거짓 칸이 파생 서비스 96행에 남지 않는다. + +## 7. 소유자가 정할 것 + +| # | 항목 | 선택지 | 권하는 안과 이유 | 정할 사람 | +| --- | --- | --- | --- | --- | +| 1 | `log_level` 칸 | A 지움 / B 코드 규칙에 맞추고 테스트로 고정 / C 규범화(코드가 읽음) | **A**. 5절 | 소유자 | +| 1-b | A일 때 칸이 다시 생기는 것을 막는 단언 | 둔다(파생 서비스도 자기 행에서 지운다) / 두지 않는다 | **둔다**. 칸이 거짓인 것은 파생 서비스 행도 같다. upgrade 안내 "반드시 할 일"에 한 줄 | 소유자 | +| 2 | 보안 필터가 5xx 두 코드(`AUTH_JWKS_UNAVAILABLE` 503, `INTERNAL_AUTH_MISCONFIGURATION` 500)를 WARN으로 남기는 것 | ERROR로 올림 / WARN 유지 | **ERROR로 올림**. 다른 모든 경로가 5xx를 ERROR로 남긴다. 둘 다 서버 쪽 고장(키 서버 장애, 설정 오류)이다. 1번과 관계없이 동작 변경이라 별도 개선 작업으로 한다 | 소유자 | +| 3 | 401 서명·issuer·audience 불일치(문서가 ERROR로 의도) | WARN 유지, 런북은 WARN 줄의 code로 찾게 고침 / ERROR로 올림 / WARN 유지 + 코드별 인증 실패 지표를 새로 둠 | **WARN 유지**. 클라이언트가 만드는 실패라 ERROR로 올리면 공격 트래픽이 ERROR 양을 정한다. 경보가 필요하면 세 번째 안이다. 지금은 코드별 인증 실패 지표가 없다(`metrics.yaml`) | 소유자 | +| 4 | repo 밖에서 이 칸을 읽는 도구 | 있음 / 없음 | **모름**. 두 repo의 추적 파일에는 없다. 있으면 A를 다시 본다 | 소유자 | + +## 8. 결정 뒤 할 일 (이 메모에서는 하지 않았다) + +- A를 고르면: `docs/registries/error-codes.yaml` 머리말과 60행, 런북 2곳, `docs/upgrade/` 안내 한 줄, (1-b면) + 레지스트리 테스트 단언. 공개 계약 변경이라 크기는 큼이고 `docs/work/improve.md`로 한다. 결정은 + `docs/work/reference/decisions.md`에 기록한다. +- 결정 2를 고르면: `AuthErrorResponseWriter`의 레벨 분기와 테스트(RED → GREEN). +- B나 C를 고르면 이 메모의 4절을 계획서로 옮겨 다시 크기를 잡는다. + +## 9. 이 조사 중 본 별개 문제 (범위 밖, 고치지 않았다) + +- `LockAcquisitionTimeoutException`은 `ApiErrorCarrier`를 구현하지 않는다 + (`src/application-core/src/main/java/dev/caskeleton/application/lock/LockAcquisitionTimeoutException.java:13`). + inbound 어디에도 이 예외의 처리기가 없다(`grep -rln LockAcquisitionTimeoutException src`: persistence-jpa와 테스트뿐). + - Javadoc은 "The web adapter maps it to 409"라고 적는다. 하지만 web은 `handleUnknown`을 거쳐 `INTERNAL_ERROR` 500으로 + 답할 것으로 읽힌다(`GlobalExceptionHandler.java:195-203`). + - `LockAcquisitionTimeoutClassificationContractTest`가 막으려는 "500 INTERNAL로 뭉개기"(D7)와 같은 모양이다. 그 + 테스트는 enum과 레지스트리만 보고 전송 경로는 보지 않는다. + - 코드 읽기 결과이고 탐침은 돌리지 않았다. 결함 후보로 `docs/work/improve.md` 절차에 넘긴다. From 416d88247100c7b9bdeee2a2f0933d54b29bee14 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 6 Nov 2026 22:01:08 +0900 Subject: [PATCH 10/71] =?UTF-8?q?fix(httpclient):=20JDK=20=EC=8B=9C?= =?UTF-8?q?=EB=8F=84=EA=B0=80=20deadline=20=EC=A7=81=EC=A0=84=EC=97=90=20?= =?UTF-8?q?=EB=81=8A=EA=B2=A8=20=EC=9D=91=EB=8B=B5=20timeout=EC=9C=BC?= =?UTF-8?q?=EB=A1=9C=20=EB=B3=B4=EA=B3=A0=EB=90=98=EC=A7=80=20=EC=95=8A?= =?UTF-8?q?=EA=B2=8C=20=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: JDK transport는 attempt deadline을 Spring JdkClientHttpRequest의 read timeout 하나로 끊는다. DeadlineAwareJdkRequestFactory는 그 값을 AttemptDeadline.bound(response-header)로 정하고, bound는 남은 시간을 나노초까지 그대로 돌려준다. Spring 7.0.9 TimeoutHandler는 이 값을 Duration.toMillis()로 잘라 timer를 건다. 그래서 timer가 deadline보다 최대 1ms 먼저 터진다. BlockingAttemptExecutor.finish와 circuit breaker 제외 조건 (deadline.setByCaller() && scope.expired())은 엔진이 포기한 뒤에 scope.expired()로 deadline이 원인인지 묻는다. 그 순간 deadline은 아직 지나지 않았다. 그래서 호출자 deadline으로 끊긴 시도가 HttpResponseTimeoutException(헤더 대기 중)이나 HttpResponseTruncatedException(본문 중)으로 보고되고, breaker는 그것을 상대 장애로 센다. 건강한 상대 서버에 circuit이 열릴 수 있다. CircuitBreakerStatusAccountingTest의 JDK 변형 2건이 이 경로로 실패했다. 고른 방법: bound가 남은 시간으로 줄인 값을 다음 밀리초로 올린다. 엔진 timer는 bound를 계산한 뒤에 걸리므로, 올린 값을 밀리초로 잘라 건 timer도 deadline보다 먼저 끝나지 않는다. 단계 timeout이 더 짧으면 그 값을 그대로 둔다. 버린 대안: - JDK 일반 요청도 scope abort로 끊기(Apache·Jetty 방식). Spring 요청의 응답 future에 닿을 수 없어 JdkClientHttpRequest를 본문 닫기까지 다시 구현해야 한다. 결함 크기에 비해 바뀌는 면이 크다. - finish에서 1ms 여유를 두고 deadline으로 판정. deadline 근처에서 터진 진짜 단계 timeout도 deadline으로 바꿔 부르는 추측이다. - factory에서만 올리기. bound를 쓰는 다음 엔진이 같은 함정에 빠진다. 위험·한계: - deadline으로 줄인 JDK timer는 deadline보다 1ms 미만 늦게 끝난다. JDK 일반 요청이 deadline을 넘기는 시간이 그만큼 늘어난다. - 같은 원인을 찾아본 곳: JDK 스트리밍 setup(JDK 요청 timeout은 나노초를 지키고 deadline은 scope abort가 끊는다), Apache·Jetty(scope abort가 fired를 먼저 세운다), messaging DefaultMessagePublisher.withDeadline (밀리초로 자르지만 원인을 TimeoutException 타입으로 판정한다), gRPC·Redis(나노초 단위). 같은 원인은 없었다. 검증(desktop, 공유 잠금 아래, 로그 ~/t2-cb-logs/): - RED: 기준 커밋 06f520e6에 새 테스트만 얹고 CircuitBreakerStatusAccountingTest·AttemptDeadlineTest를 --rerun으로 10회. 10/10 rc=1. 새 단위 테스트 10/10 실패, CircuitBreaker JDK 변형은 10회 중 9회 실패(JDK 케이스 20건 중 14건). - GREEN: 수정 트리에서 같은 명령 10회 두 번. 20/20 rc=0, 실패 0. - ./gradlew ci: rc=0(93초, 다른 leaf는 캐시 재사용, httpclient test 359건·계약 23건·보안 9건·Spring 6.2 스캔 7건 실제 실행). - :adapter:outbound:httpclient:testQualityCheck spring70CompatibilityTest (23건) rc=0, httpClientFailureInjectionTest(Toxiproxy, 4건) rc=0. Fixes: 34565130e021 ("fix!: 성숙도 리뷰의 High·P1 결함 19건을 고친다") --- .../jdk/DeadlineAwareJdkRequestFactory.java | 5 ++++ .../httpclient/transport/AttemptDeadline.java | 19 +++++++++++++- .../transport/AttemptDeadlineTest.java | 26 +++++++++++++++++++ 3 files changed, 49 insertions(+), 1 deletion(-) diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/DeadlineAwareJdkRequestFactory.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/DeadlineAwareJdkRequestFactory.java index 6b28ad8f..943f3a5d 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/DeadlineAwareJdkRequestFactory.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/DeadlineAwareJdkRequestFactory.java @@ -22,6 +22,11 @@ import org.springframework.http.client.JdkClientHttpRequestFactory; * timeout, remaining deadline)} from {@link AttemptDeadline}. The factory only holds references; * the client and the write executor are shared. * + *

That timer is the only thing that ends a JDK attempt at its deadline, and it keeps whole + * milliseconds. {@link AttemptDeadline#bound(Duration)} rounds the remaining time up for that + * reason: truncated, the timer fired just before the deadline and the attempt was reported as a + * response timeout rather than the deadline. + * *

A streaming download cannot use that request. Its body is handed to the caller and may run for * minutes, but Spring's timer only stops when the body stream is closed, so every JDK download * longer than the response-header timeout was cut mid-body (review 2026-11-03 RR-04-03). Inside a diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/transport/AttemptDeadline.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/transport/AttemptDeadline.java index 36d072bb..b2ac3dfa 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/transport/AttemptDeadline.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/transport/AttemptDeadline.java @@ -1,6 +1,7 @@ package dev.caskeleton.adapter.outbound.httpclient.transport; import java.time.Duration; +import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; import java.util.Objects; @@ -83,14 +84,30 @@ public final class AttemptDeadline { return Optional.ofNullable(CURRENT.get()).map(Scope::remaining); } - /** A stage timeout no longer than the current attempt's remaining time. */ + /** + * A stage timeout cut down to the current attempt's remaining time when that is shorter. + * + *

A cut-down value is rounded up to the next whole millisecond, so an engine timer armed from + * it never ends before the deadline. Engines keep their timeouts in milliseconds — Spring's JDK + * request arms its timer with {@code Duration.toMillis()} — and the truncated remainder made that + * timer fire just before the deadline. The executor names the deadline by asking the scope after + * the engine gave up, so such an attempt was reported as a response timeout on a healthy upstream + * and the circuit breaker counted the caller's own deadline against it. Ending under a + * millisecond late costs nothing: by then the scope reports itself expired. + */ public static Duration bound(Duration stageTimeout) { Objects.requireNonNull(stageTimeout, "stage timeout"); return remaining() .filter(remaining -> remaining.compareTo(stageTimeout) < 0) + .map(AttemptDeadline::toWholeMillisecondsUp) .orElse(stageTimeout); } + private static Duration toWholeMillisecondsUp(Duration duration) { + Duration truncated = duration.truncatedTo(ChronoUnit.MILLIS); + return truncated.equals(duration) ? duration : truncated.plusMillis(1); + } + /** * Registers how to abort the exchange the current attempt is about to start. * diff --git a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/transport/AttemptDeadlineTest.java b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/transport/AttemptDeadlineTest.java index 388bb2c6..fa2cfc77 100644 --- a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/transport/AttemptDeadlineTest.java +++ b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/transport/AttemptDeadlineTest.java @@ -6,6 +6,7 @@ import java.time.Duration; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.locks.LockSupport; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -41,6 +42,31 @@ class AttemptDeadlineTest { } } + @Test + @DisplayName("bound 값을 밀리초로 잘라 건 엔진 timer도 attempt deadline보다 먼저 끝나지 않는다") + void anEngineTimerArmedInWholeMillisecondsDoesNotEndBeforeTheDeadline() { + // Spring's JDK request arms its timer with Duration.toMillis(). A remaining time with a + // sub-millisecond part lost it there, the engine gave up just before the deadline, and the + // executor, asking the scope a moment later, reported a response timeout instead. + try (AttemptDeadline.Scope scope = + AttemptDeadline.open(Duration.ofMillis(20).plusNanos(900_000))) { + // given + Duration bounded = AttemptDeadline.bound(Duration.ofSeconds(2)); + long armedAt = System.nanoTime(); + long firesAt = armedAt + TimeUnit.MILLISECONDS.toNanos(bounded.toMillis()); + + // when + while (System.nanoTime() - firesAt < 0) { + LockSupport.parkNanos(firesAt - System.nanoTime()); + } + + // then + assertThat(scope.expired()) + .as("deadline passed when a whole-millisecond timer from bound() = %s fired", bounded) + .isTrue(); + } + } + @Test @DisplayName("deadline이 지나면 등록된 중단 동작을 실행하고 scope는 만료로 보고한다") void theRegisteredAbortRunsWhenTheDeadlinePasses() throws Exception { From 05d0de766c5133d1d43a32beff4351497e083ec5 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 6 Nov 2026 22:05:30 +0900 Subject: [PATCH 11/71] =?UTF-8?q?docs(review):=20r10=20=ED=99=95=EC=9D=B8?= =?UTF-8?q?=20=EB=A6=AC=EB=B7=B0=20round7=EC=9D=84=20=EC=98=81=EC=97=AD=20?= =?UTF-8?q?=EB=8B=A4=EC=84=AF=EC=9C=BC=EB=A1=9C=20=EA=B8=B0=EB=A1=9D?= =?UTF-8?q?=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: r10(6e992970)은 round6 결함 25건을 고친 커밋 하나로 +5,143줄이다. 확인 리뷰 상한(추가 1,500줄, docs/work/improve.md 4.4절)을 넘어, 수정이 새로 만든 결함을 영역마다 따로 봐야 했다. 방법: 영역 pathspec 다섯(01 core·inbound +1056, 02 멱등성 +407, 03 persistence +877, 04 build-logic 셸 판독 +659, 05 workflow 판독 +1288)으로 나눠 차례로 리뷰했다. build-logic은 한 묶음이 +1,916줄이라 둘로 갈랐다. 의심 결함은 desktop 임시 worktree의 탐침으로 확인했다. r9(45d2a478)에 같은 탐침을 돌려 회귀인지 가렸다. 버린 대안: 커밋 전체를 한 문서로 보는 것(상한 위반), 리뷰 기록 round6(+829줄)까지 읽는 것. 결과: Critical 0, Important 0, 회귀 1. 결함 5건 모두 Minor. RR7-01-01 설정에 중첩된 JAX-RS 자원·@ServerEndpoint를 놓침(회귀), RR7-01-02 메서드 참조 route 설정의 거짓 실패, RR7-03-01 ledger IT의 없는 예외 장치 안내, RR7-03-02 REINDEX SCHEMA|DATABASE CONCURRENTLY 설명 오류, RR7-05-01 경로 필터 workflow를 "매 변경"으로 셈. RR6 항목은 RR6-03-05만 부분이고 나머지는 닫혔다. 위험·한계: 라운드 끝 게이트와 실 Redis·실 PG 계약 lane은 다시 돌리지 않았다(17.2절 2c692554 결과가 마지막). leaf test 10개는 FROM-CACHE다. RR7-05-01은 경로 필터 정책을 소유자가 정해야 고칠 수 있다(18.3절). round6 Declined 30건이 처리 기록 없이 남아 멈춤 기준 2가 거짓이다. 검증: python3 scripts/check-review-index.py docs/reviews/2026-11-03-rereview rc=0(162건 모두 색인). check-work-docs.py --links(새 문서 6개) rc=0. desktop 탐침 4종 rc=0(~/t1-r10-review-logs/summary.txt), 탐침 코드는 공유 노트 rr7-probes/. architectureTest --rerun 229건, build-logic test --rerun 169건, persistence-jpa test 664건 실패 0. Refs: docs/reviews/2026-11-03-rereview/README.md 18절 --- docs/reviews/2026-11-03-rereview/README.md | 72 +++++++++ .../round7/01-core-inbound.md | 141 ++++++++++++++++++ .../round7/02-idempotency-outbound.md | 94 ++++++++++++ .../round7/03-persistence.md | 129 ++++++++++++++++ .../round7/04-build-logic-shell.md | 81 ++++++++++ .../round7/05-build-logic-workflow.md | 97 ++++++++++++ 6 files changed, 614 insertions(+) create mode 100644 docs/reviews/2026-11-03-rereview/round7/01-core-inbound.md create mode 100644 docs/reviews/2026-11-03-rereview/round7/02-idempotency-outbound.md create mode 100644 docs/reviews/2026-11-03-rereview/round7/03-persistence.md create mode 100644 docs/reviews/2026-11-03-rereview/round7/04-build-logic-shell.md create mode 100644 docs/reviews/2026-11-03-rereview/round7/05-build-logic-workflow.md diff --git a/docs/reviews/2026-11-03-rereview/README.md b/docs/reviews/2026-11-03-rereview/README.md index 84e7b67c..10a0cccf 100644 --- a/docs/reviews/2026-11-03-rereview/README.md +++ b/docs/reviews/2026-11-03-rereview/README.md @@ -403,3 +403,75 @@ Minor 중 RR5-01-01(`IDEMPOTENCY_RECOVERY_REQUIRED`의 클라이언트 안내가 - GREEN: 03 동시 인덱스 검사기(`ConcurrentIndexMigrationInspectorTest`)와 손 포맷(persistence-jpa `spotlessCheck`), 01 `architectureTest` 228·`spotbugsArchitectureTest`(A5 최종본), optional ledger `check`를 게이트 전에 따로 돌렸다(1분 50초, rc=0). - 게이트 안에서 확인한 보고서 항목: `:app-bootstrap:documentContractTest` 65, `verifyEnvKeys`, `verifyJpaApiSurface`, `redisContainerContractTest` 78, `jpaPlatformContractTest` 407, `jpaPlatformMigrationTest` 45, 새 lane `postgresqlConcurrentIndexMigrationIntegrationTest` 4(`integrationCheck`에서 실행), `postgresqlMigrationLockWaitIntegrationTest` 36, `postgresqlNotificationSchemaActivationIntegrationTest` 8, `postgresqlIdempotencyIntegrationTest` 10, `messagingInboxRedeliveryIntegrationTest` 3, app-bootstrap `integrationTest` 10(`PostgreSqlIdempotencyProviderIntegrationTest` 포함), sample `integrationTest` 63(`SampleIdempotencyReplayIntegrationTest`·`SampleMigrationStreamIsolationTest` 포함), ledger `integrationTest` 46. 모두 실패 0. in-memory fake 계약의 skip 19는 시간 케이스(설계). - 다시 돌리지 않은 것: 각 묶음이 로컬에서 이미 확인한 RED(01의 gRPC·STOMP·GraphQL·shared-contract·shared 규칙, 02 표, 03, 04). r10-03 보고서가 적은 `:adapter:outbound:persistence-jpa:documentContractTest`는 없는 태스크다(그 lane은 app-bootstrap에만 있다). + +## 18. r10 확인 리뷰 round7 (2026-11-06) + +`6e992970`(r10)만 봤다. 기준 커밋 `06f520e6`(브랜치 `refactor/maturity-review-2026-11` 위, 그 사이 커밋은 문서·성능 lane이라 리뷰한 +파일을 바꾸지 않았다). 리뷰어 1명이 영역을 차례로 봤다. 영역 문서는 `round7/01~05`다. + +커밋 하나가 +5,143줄이라 확인 리뷰 상한(추가 1,500줄, `docs/work/improve.md` 4.4절)을 넘는다. 영역 pathspec으로 나눴다. 정확한 +pathspec은 각 영역 문서 「범위」에 있다. + +| 영역 | 대상 | `git diff --shortstat` | +|---|---|---| +| [01 core·inbound](round7/01-core-inbound.md) | shared-contract, inbound web·GraphQL·gRPC·WebSocket, app-bootstrap(Flyway 규칙 제외), 매뉴얼 07, runbook | 33 파일, +1056 −137 | +| [02 멱등성·outbound](round7/02-idempotency-outbound.md) | application-core, cache-redis, redis-runtime, PG 멱등성 store, 매뉴얼 05 | 15 파일, +407 −458 | +| [03 persistence](round7/03-persistence.md) | persistence-jpa(멱등성·lockfile 제외), persistence-notification, inbound messaging, grpc ledger, sample, Flyway 규칙, `docs/jpa`·매뉴얼 04·study | 28 파일, +877 −113 | +| [04 build-logic 셸 판독](round7/04-build-logic-shell.md) | `ShellScript`, `StrictLaneStagesPlugin`, TestKit 테스트, build-logic `build.gradle`·README | 5 파일, +659 −100 | +| [05 build-logic workflow 판독](round7/05-build-logic-workflow.md) | `WorkflowGradleInvocations`와 그 테스트, `GradleCommandLineTest`, AGENTS.md·CLAUDE.md·`src/README.md` | 6 파일, +1288 −101 | +| 공통 문서(영역마다 자기 행을 읽음) | `docs/upgrade/`, `docs/testing/`, 2026-11-01 README | 3 파일, +25 −14 | +| 보지 않음 | 리뷰 기록 `round6/*`·이 README 17절(+829), lockfile 2줄 | — | + +### 18.1 결과 + +Critical 0, Important 0, 회귀 1(RR7-01-01). 결함 5건, 모두 Minor. 이번 수정이 만든 것 3건, 이전부터 있던 것을 이번 수정이 넓히거나 새로 +약속한 것 2건(섞임). + +| ID | 심각도 | 내용 | 이번 수정 / 이전부터 | 증거 | +|---|---|---|---|---| +| RR7-01-01 | Minor(회귀) | 설정에 중첩된 클래스를 요청 처리기 목록으로만 보아, 설정 안의 JAX-RS 자원·`@ServerEndpoint`가 `@SystemCaller`를 불러도 잡히지 않는다. r9는 잡았다 | 이번 수정 | E2 탐침, 두 커밋 | +| RR7-01-02 | Minor | 메서드 참조로 route만 등록한 설정도 사용자 전송이라, 같은 설정이 handler bean을 등록하면 거짓 실패. Javadoc·매뉴얼 07·B-16의 "요청 처리 코드를 다른 클래스에" 안내와 다르다 | 이번 수정 | E2 탐침 | +| RR7-03-01 | Minor | ledger 잠금 대기 IT가 "이 테스트에 예외로 적으라"고 안내하지만 예외를 적을 곳이 없다 | 이번 수정 | E1 | +| RR7-03-02 | Minor | "Flyway는 `REINDEX … CONCURRENTLY`를 트랜잭션 안에서 돌린다"는 설명이 `REINDEX SCHEMA|DATABASE CONCURRENTLY`에서 틀린다(Flyway가 트랜잭션 밖에서 적용) | 섞임 | E3 실 PostgreSQL | +| RR7-05-01 | Minor | 메시지·B-36은 "매 push·pull request·schedule에 도는 workflow"를 요구하지만 판독기는 `paths:` 필터 workflow도 센다 | 섞임(동작은 이전부터, 약속은 이번 수정) | E2 탐침 | + +r10이 고쳤다고 한 항목의 재확인(영역 문서 「항목 재확인」): + +- 닫힘: RR6-01-01~09, RR6-02-01~05, RR6-03-01~04, RR6-04-01~06. +- 부분: RR6-03-05(설명을 고치며 RR7-03-01·02가 생김). + +색인 보완: 이 README가 ID 대신 내용으로만 적은 지난 발견 둘을 이름으로 적는다(`docs/work/evidence.md` 7절). RR-05-10(06 영역 발견 5건의 +색인 누락)은 1절 정정과 6.1절이, RR-07-05(CSRF 제외 규칙의 이유)는 6절 r4-f 행의 "RR-06-05+07-05"가 다룬다. + +### 18.2 실행 (2026-11-06, desktop) + +임시 worktree `~/workspace/t1-r10-review`(`06f520e6`)와 `~/workspace/t1-r10-review-r9`(`45d2a478`, r9 비교용)에 탐침을 얹어 +`flock /tmp/claude-gates/heavy.lock` 아래에서 차례로 돌렸다. 로그 `~/t1-r10-review-logs/`(desktop, `summary.txt`). 탐침 코드와 결과는 공유 노트 +폴더 `rr7-probes/`에 있어 고칠 때 fixture로 옮겨 쓸 수 있다. 끝나고 두 worktree를 지웠다. + +| 명령 | 대상 | 결과 | 시간 | 직전 부하(1분) | +|---|---|---|---|---| +| `:app-bootstrap:architectureTest --tests …Rr7ProbeTest` | `06f520e6` | rc=0(탐침 P1·P2 위반 없음, P3 위반) | 21초 | 4.58 | +| 같은 명령 | `45d2a478` | rc=0(P1·P2 위반, P3 위반 없음) | 20초 | 4.89 | +| `-p build-logic test --tests …Rr7WorkflowProbeTest` | `06f520e6` | rc=0(경로 필터 workflow를 셈) | 2초 | 4.66 | +| `:adapter:outbound:persistence-jpa:rr7ReindexProbe`(임시 lane, 실 PostgreSQL) | `06f520e6` | rc=0(REINDEX 다섯 형태 중 SCHEMA·DATABASE만 적용) | 19초 | 4.28 | +| `:shared-contract:test :application-core:test :adapter:outbound:redis-runtime:test :adapter:outbound:cache-redis:test :adapter:outbound:persistence-jpa:test :adapter:outbound:persistence-notification:test :adapter:inbound:messaging:test :adapter:inbound:web:test :adapter:inbound:grpc:test :adapter:inbound:graphql:test :adapter:inbound:websocket:test :app-bootstrap:architectureTest --rerun --continue` | `06f520e6` + 탐침 | rc=0. 실행: persistence-jpa `test` 664건, `architectureTest` 229건(탐침 1건 포함), 실패 0. 나머지 10개 `test`는 FROM-CACHE(같은 입력의 이전 실행 결과) | 47초 | 4.46 | +| `-p build-logic test --rerun` | `06f520e6` + 탐침 | rc=0, 169건 실패 0 skip 0(탐침 1건 포함) | 40초 | 3.69 | + +다시 돌리지 않은 것: 라운드 끝 게이트(`ci`, `mainCheck`, `integrationCheck`, `-p optional-platforms …`, compose)와 실 Redis·실 PG 계약 +lane. 마지막 실행은 17.2절의 `2c692554`다(이 리뷰에는 E0). + +### 18.3 결정이 필요한 것 + +| 항목 | 선택지 | 권하는 안과 이유 | 정할 사람 | +|---|---|---|---| +| RR7-05-01 경로 필터 workflow를 단계 실행으로 셀지 | (a) `paths:`·`paths-ignore:` trigger만으로는 세지 않는다 (b) 세고, 메시지·B-36의 "매 변경" 약속을 고친다 | (a). 단계 검사는 "모든 변경이 이 lane을 지난다"를 보장하려는 것이고, 경로 필터는 그 보장을 깬다. 이 repo의 단계 명령은 필터 없는 workflow에 있어 판정이 바뀌지 않는다. round6 04가 "저장소 정책"으로 판단하지 않은 항목이라 정책으로 닫는다 | 소유자 | + +### 18.4 멈춤 기준 상태 (`docs/work/improve.md` 4.5절) + +1. 마지막 확인 리뷰 발견 0: **아님.** 5건(18.1절). +2. 열린 「Declined to judge」 0: **아님.** + - round6 01~04의 Declined 30건이 17절 처리 표·결정에 배정되거나 닫힌 기록이 없다(03의 중첩 블록 주석 1건은 r10이 고쳤다). 영역 문서에 위치가 있다. + - round7의 Declined 12건(01: 3, 02: 2, 03: 2, 04: 2, 05: 3)은 각 영역 문서에 있다. 판단이 필요한 것은 02의 "같은 owner token·다른 operation id의 넘겨받기"(업그레이드 안내에 없는 동작 변경)와 03의 "`new FluentConfiguration()` 경로"다. +3. 합친 트리의 라운드 끝 게이트: r10 트리 `2c692554`에서 통과(17.2절). 이 리뷰는 다시 돌리지 않았다. +4. README의 남은 항목 0: **아님.** 위 1·2와 18.3절 결정. diff --git a/docs/reviews/2026-11-03-rereview/round7/01-core-inbound.md b/docs/reviews/2026-11-03-rereview/round7/01-core-inbound.md new file mode 100644 index 00000000..0c140fc5 --- /dev/null +++ b/docs/reviews/2026-11-03-rereview/round7/01-core-inbound.md @@ -0,0 +1,141 @@ +# 01 core·inbound r10 확인 리뷰 (2026-11-06) + +> 대상: `6e992970`(r10)의 r10-01 묶음. RR6-01-01~09 수정: 설정 안 요청 처리 코드 판정, record·enum·예외 +> 상위 타입, gRPC 취소·raw status 로그, 네 전송의 `IllegalArgumentException` WARN 한 줄, shared-contract 패키지 규칙. +> 기준 커밋 `06f520e6`(이 영역의 코드는 `6e992970` 뒤로 바뀌지 않았다). + +## 범위 + +### pathspec + +``` +src/shared-contract src/adapter/inbound/graphql src/adapter/inbound/grpc src/adapter/inbound/web src/adapter/inbound/websocket +src/app-bootstrap ':!src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/JpaProductionArchitectureTest.java' +docs/manual/07-authorization.md docs/runbooks/idempotency-unavailable.md +``` + +`git diff --shortstat 6e992970^ 6e992970 -- `: 33개 파일, +1056 −137. 커밋 하나가 +5,143줄이라 +`docs/work/improve.md` 4.4절대로 영역 pathspec으로 나눴다(README 18절). `JpaProductionArchitectureTest`(Flyway 규칙)는 03, +`web/README.md`의 503 행은 02에서 함께 봤다. + +함께 읽은 주변 코드: `ApplicationBoundaryArchitectureTest`의 `ARE_USER_TRANSPORT_TYPES`(`:471-491`)와 `45d2a478`(r9)의 같은 판정식, +`GraphQlWireErrorMapper.sharedCodeOf`, `ServerFailureLog.of`, `GrpcExceptionHandlingInterceptor` 전체, shared-contract 패키지 디렉터리, +매뉴얼 07 「시스템이 부르는 쓰기」·「규칙이 못 보는 길」, round6 RR6-01-01·02의 고치는 법. + +### 수정 보고의 「새로 가정하는 것」 + +README 17절 처리 표에는 이 칸이 없고 묶음 보고는 repo에 남지 않았다. 커밋 본문 「위험·한계」와 17절 「결정」 칸에서 뽑았다. + +| 가정 | 확인 | +|---|---| +| 설정 안의 endpoint는 `ARE_REQUEST_HANDLER_TYPES` 목록 타입에 의존한다 | 거짓인 경우가 있다. 목록에 JAX-RS와 주석형 JSR-356 endpoint가 없다. 그런데 이 목록이 이제 설정에 **중첩된** 클래스에도 쓰인다(RR7-01-01) | +| 설정이 요청 처리기 타입에 의존하면 그 설정 안에 요청 처리 코드가 있다 | 거짓인 경우가 있다. 메서드 참조로 route만 등록한 설정도 의존한다(RR7-01-02) | +| 네 전송의 IAE는 carrier 검사 뒤에만 `refusedArgument`로 간다 | 참. web `GlobalExceptionHandler.java:93-97`, GraphQL `GraphQlWireErrorMapper.java:133-139`, gRPC `GrpcExceptionHandlingInterceptor.java:133-141`(carrier 분기 뒤 `status.getCause()`), STOMP `StompHandlerFailureLog.java:34-43` | + +### 불러온 스킬과 적용한 기준 + +| 스킬 | 기준 | 본 것 | +|---|---|---| +| `superpowers:requesting-code-review` | 주장(README 17절 r10-01)과 구현이 맞는가, 테스트가 이름대로를 보는가, 심각도 보정, Declined to judge, 읽기 전용. 하위 에이전트는 repo 설정이 막아 diff를 여러 번에 나눠 직접 봤다 | 항목마다 닫힘 여부, 새 fixture가 막으려는 모양 밖에서 무엇이 바뀌었나 | +| `docs/work/reference/review-criteria.md` 7절 | 규칙 테스트는 위반·허용 fixture를 둘 다 가지나, 변이·탐침으로 확인 | 새 판정식을 r9 판정식과 같은 fixture에 돌림 | +| `docs/work/reference/defect-patterns.md` A1·A10 | 갈라진 복사본(두 타입 목록), 글로만 있는 규칙 | `ARE_USER_TRANSPORT_TYPES`와 `ARE_REQUEST_HANDLER_TYPES`의 차이 | + +### 실행한 명령과 결과 + +desktop(`ssh desktop`) 임시 worktree 두 개(`~/workspace/t1-r10-review` = `06f520e6`, `~/workspace/t1-r10-review-r9` = `45d2a478`)에 +탐침을 얹고 `flock /tmp/claude-gates/heavy.lock` 아래에서 돌렸다. 로그 `~/t1-r10-review-logs/`(desktop), 탐침 코드와 결과는 공유 노트 폴더 +`rr7-probes/`. + +| # | 명령 | 결과 | 직전 부하(1분) | +|---|---|---|---| +| 1 | `./gradlew :app-bootstrap:architectureTest --tests dev.caskeleton.bootstrap.architecture.Rr7ProbeTest` (`06f520e6`) | rc=0, 21초. 결과는 아래 표 | 4.58 | +| 2 | 같은 명령 (`45d2a478`, 같은 탐침) | rc=0, 20초 | 4.89 | +| 3 | `./gradlew :shared-contract:test … :adapter:inbound:web:test :adapter:inbound:grpc:test :adapter:inbound:graphql:test :adapter:inbound:websocket:test :app-bootstrap:architectureTest --rerun --continue` (`06f520e6`, 탐침 포함 트리) | README 18.2절 | README 18.2절 | + +탐침 `Rr7ProbeTest`는 `USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS`를 다섯 모양에 돌려 위반 여부를 파일에 적는다. + +| 탐침 | 모양 | `06f520e6` | `45d2a478` | +|---|---|---|---| +| P1 | `@Configuration` 안의 중첩 JAX-RS 자원(`@Path`·`@POST`)이 `@SystemCaller`를 부름 | 위반 없음 | 위반(`NestedJaxRsConfiguration$RunNowResource`) | +| P1c | 같은 자원을 최상위 클래스로(대조군) | 위반 | 위반 | +| P2 | `@Configuration` 안의 중첩 `@ServerEndpoint`·`@OnMessage`가 `@SystemCaller`를 부름 | 위반 없음 | 위반(`…$RunNowEndpoint`) | +| P3 | 한 설정이 메서드 참조 route(`orders::list`, 처리 코드는 `OrderHandler`)와 `@SystemCaller` bean을 함께 등록 | 위반(`MethodRefRouteConfiguration`) | 위반 없음 | +| P3c | 같은 route만 있는 설정(대조군) | 위반 없음 | 위반 없음 | + +### 못 본 것 + +- 멱등성 저장소·계약 변경은 02, Flyway 규칙(`JpaProductionArchitectureTest`)은 03에서 봤다. +- 실제 JAX-RS·JSR-356 런타임 기동: 이 템플릿에는 그 런타임이 없다(app-bootstrap `testCompileOnly 'jakarta.ws.rs:jakarta.ws.rs-api'`만). 탐침은 규칙 판정만 본다. +- `ARE_REQUEST_HANDLER_TYPES`에 빠진 타입을 모두 찾지는 않았다. 목록 방식의 한계는 매뉴얼 07 「규칙이 못 보는 길」에 적혀 있다. 아래 RR7-01-01은 그중 **r9가 잡던 것을 r10이 놓치게 된** 모양만 적는다. + +## 항목 재확인 + +| ID | 판정 | 근거 | +|---|---|---| +| RR6-01-01 (설정 안 함수형 endpoint 회귀) | 닫힘 | 람다 route·data fetcher를 가진 설정을 다시 사용자 전송으로 센다(`ApplicationBoundaryArchitectureTest.java:534-581`). 위반 fixture `RunNowRouteConfigurationFixture`·`RunNowDataFetcherConfigurationFixture`와 테스트 `aConfigurationWhoseFunctionalRouteCallsASystemCallerIsCaught`·`…DataFetcher…`. 다만 고친 방법이 중첩 클래스 판정을 좁혀 새 구멍(RR7-01-01)과 새 거짓 실패(RR7-01-02)를 만들었다 | +| RR6-01-02 (익명 configurer 필드 거짓 양성) | 닫힘 | 허용 fixture `SystemCallerBesideFieldReadingWebMvcConfigurerFixture`, 테스트 `aWebMvcConfigurerNestedInAConfigurationMayReadTheConfigurationsField`. 이 수정의 부작용이 RR7-01-01이다 | +| RR6-01-03 (record·enum·예외 거짓 양성) | 닫힘 | `ApplicationBoundaryArchitectureTest.java:741-809`, fixture 3개와 테스트 3개(`Runnable` record는 여전히 잡힘) | +| RR6-01-04 (gRPC 취소 판정) | 닫힘 | `GrpcExceptionHandlingInterceptor.java`의 `delegate.isCancelled()` 분기(`:143`), 테스트 `aFailureOnACallTheClientCancelledIsNotLogged`·`aCancelledStatusTheServiceClosesALiveCallWithIsLoggedAsUnhandled` | +| RR6-01-05 (던진 raw status 설명 로그) | 닫힘 | `failureBehind`가 status 예외를 건너뛴다. 테스트 `aThrownRawStatusIsLoggedByItsCodeWithoutItsDescription`·`…WithACauseIsLoggedWithTheCauseAlone` | +| RR6-01-06 (STOMP IAE ERROR) | 닫힘 | `ServerFailureLog.refusedArgument`를 네 전송이 쓴다. 테스트 4개(web·GraphQL·gRPC·STOMP)와 `ServerFailureLogTest` | +| RR6-01-07 (runbook 문구, RR6-02-03과 같음) | 닫힘 | `docs/runbooks/idempotency-unavailable.md:22-25`·`:102-105` | +| RR6-01-08 (GraphQL 테스트가 carrier 대신 IAE) | 닫힘 | `aClientSideCarrierIsNotLogged`가 `IdempotencyInFlightException`을 넣는다 | +| RR6-01-09 (shared-contract 규칙이 아무것도 못 잡음) | 닫힘 | 대상 `dev.caskeleton.shared..`, 목록 12개가 `src/shared-contract/src/main/java/dev/caskeleton/shared/`의 디렉터리와 같다(ls). 다른 leaf에 `dev.caskeleton.shared` 패키지는 없다(grep). 위반·허용 fixture와 목록 대조 테스트 `SharedContractPackageRuleTest` | + +## 결함 + +### RR7-01-01 · Minor · 설정에 중첩된 클래스를 요청 처리기 목록으로만 보아, 설정 안의 JAX-RS 자원·`@ServerEndpoint`가 `@SystemCaller`를 불러도 잡히지 않는다 (회귀) + +- **위치**: + - 코드: `src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java:574-577`(중첩 클래스도 `ARE_REQUEST_HANDLER_TYPES`), `:498-548`(목록에 `jakarta.ws.rs..`, `jakarta.websocket.server..`·`jakarta.websocket.OnMessage` 없음), `:471-491`(`ARE_USER_TRANSPORT_TYPES`에는 `jakarta.ws.rs..`·`jakarta.websocket..` 있음). + - 문서: `docs/manual/07-authorization.md:104`(표시 검사는 JAX-RS를 사용자 전송 타입으로 센다), `:105` ②. +- **무엇이 틀렸나**: + - r9는 설정 클래스 자신만 판정에서 뺐다. 설정에 중첩된 다른 클래스는 `ARE_USER_TRANSPORT_TYPES`로 봤다(`45d2a478`의 같은 파일 `:516-522`). + - r10은 설정에 중첩된 클래스도 설정처럼 `ARE_REQUEST_HANDLER_TYPES`로만 본다(RR6-01-02 고치는 법을 따랐다). + - 두 목록은 다르다. 요청 처리기 목록에는 JAX-RS(`jakarta.ws.rs..`)와 주석형 JSR-356 endpoint(`@ServerEndpoint`, `@OnMessage`)가 없다. 사용자 전송 타입 목록에는 둘 다 있다. + - 그래서 설정에 중첩된 JAX-RS 자원이나 `@ServerEndpoint`는 r9에서는 잡혔고 r10에서는 잡히지 않는다. 탐침 P1·P2가 두 커밋에서 반대로 나왔다. 최상위 클래스로 두면 r10도 잡는다(P1c). + - 두 목록이 왜 다른지 적힌 곳이 없다. Javadoc(`:520-532`)은 요청 처리기 목록을 "controller, route, servlet, filter, interceptor, WebSocket handler, GraphQL, gRPC"로 적고 JAX-RS를 말하지 않는다. +- **발생 조건·영향**: + - 조건: 파생 서비스가 JAX-RS나 주석형 JSR-356 endpoint를 쓰고, 그 endpoint 클래스를 작업 bean을 등록하는 설정 안에 중첩해 둔다. 이 템플릿에는 두 런타임이 없어서 드물다. + - 영향: 인증만 된 사용자 요청이 권한 검사 없는 `@SystemInvoked` 쓰기를 부른다. 빌드는 신호를 내지 않는다. RR3-01-01·RR6-01-01과 같은 피해다. + - Minor로 둔 이유: 두 전송 모두 템플릿에 없는 런타임이고, 중첩 위치까지 겹쳐야 한다. 다만 이 커밋이 만든 회귀라 따로 센다. +- **테스트가 못 본 이유**: 새 fixture는 `HandlerFunction`(목록에 있음)을 중첩한 모양 하나뿐이다. r9가 잡던 중첩 모양 가운데 목록 밖 타입을 쓴 것은 없다. +- **고치는 법**: + - 권장: 설정 클래스 **자신**만 `ARE_REQUEST_HANDLER_TYPES`로 보고, 중첩 클래스는 r9처럼 `ARE_USER_TRANSPORT_TYPES`로 본다. 대신 RR6-01-02 모양(익명 `WebMvcConfigurer`가 바깥 필드를 읽음)은 "바깥 설정 인스턴스(`this$0`)로 가는 의존만 있는 경로"를 빼는 식으로 따로 허용한다. 그러면 두 목록의 차이가 중첩 클래스에 새지 않는다. + - 대안 1: `ARE_REQUEST_HANDLER_TYPES`에 `jakarta.ws.rs..`, `jakarta.websocket.server..`, `jakarta.websocket.OnMessage`·`OnOpen`을 더한다. 간단하지만 두 목록이 계속 갈라질 수 있어(A1), 두 목록의 차이를 단언하는 테스트를 같이 둬야 한다. + - 대안 2: 요청 처리기 목록을 `ARE_USER_TRANSPORT_TYPES`에서 "설정용 타입"(`WebMvcConfigurer`, `CorsRegistry`, `…config.annotation..`)을 뺀 것으로 정의해 목록을 하나로 만든다. + - RED 테스트 모양: 탐침 P1·P2를 위반 fixture로 옮긴다(`rr7-probes/…/probe/rr7/NestedJaxRsConfiguration.java`, `NestedServerEndpointConfiguration.java`). `06f520e6`에서 위반 0으로 실패해야 한다. +- **이번 수정 / 이전부터**: 이번 수정(회귀). +- **증거**: E2 — 명령 1·2(탐침 P1·P1c·P2를 두 커밋에서 실행). 코드 경로는 E1. + +### RR7-01-02 · Minor · 메서드 참조로 함수형 route만 등록한 설정도 사용자 전송으로 세어, 같은 설정이 handler bean을 등록하면 거짓 실패한다 — Javadoc·매뉴얼은 "요청 처리 코드가 있을 때만"이라고 적는다 + +- **위치**: + - 코드: `ApplicationBoundaryArchitectureTest.java:525-527`(Javadoc "A configuration names one only when request-handling code is in it"), `:574-579`(설정이 `RouterFunctions` 같은 목록 타입에 의존하기만 하면 전송). + - 문서: `docs/manual/07-authorization.md:105`("요청 처리 코드는 handler를 등록하는 설정과 다른 클래스에 둔다"), `docs/upgrade/2026-11-maturity-review.md` B-16("요청 처리 코드는 handler를 등록하는 설정과 다른 클래스에 둔다"). +- **무엇이 틀렸나**: + - 설정이 `RouterFunctions.route().GET("/orders", orders::list)`처럼 메서드 참조로 route를 등록하면, 요청 처리 코드는 `OrderHandler`에 있고 설정에는 없다. + - 그래도 설정은 `org.springframework.web.servlet.function..` 타입에 의존하므로 사용자 전송이 된다. 같은 설정이 `@SystemCaller` bean을 `new`로 만들면 위반이다(탐침 P3). route만 있는 설정은 통과한다(P3c). + - Javadoc은 "요청 처리 코드가 있을 때만" 설정이 요청 처리기 타입을 부른다고 적는다. 매뉴얼과 업그레이드 안내는 "요청 처리 코드를 다른 클래스에 두라"고만 한다. 그대로 따라 처리 코드를 `OrderHandler`로 옮겨도 빌드는 실패하고, 메시지는 요청이 지나가지 않는 경로를 말한다. +- **발생 조건·영향**: 함수형 endpoint를 쓰는 서비스가 한 기능의 설정에 route 등록과 예약 작업 bean을 함께 둔다. Spring 문서가 보여 주는 route 등록 모양 그대로다. 빌드가 실패하는 쪽(거짓 실패)이라 데이터·권한 피해는 없다. 고치는 사람은 안내와 다른 이유로 막힌다. +- **테스트가 못 본 이유**: 허용 fixture는 `WebMvcConfigurer`와 controller bean 두 모양뿐이다. route를 등록하지만 처리 코드는 없는 설정의 fixture가 없다. +- **고치는 법**: + - 권장: 문서를 동작에 맞춘다. 매뉴얼 07 ②·B-16·Javadoc에 "함수형 route·data fetcher·interceptor를 **등록하는** 설정은 처리 코드가 다른 클래스에 있어도 사용자 전송이다. route 등록은 handler bean을 만드는 설정과 다른 설정에 둔다"를 적는다. 탐침 P3을 "걸리는" fixture로 남긴다. + - 대안: 판정을 좁힌다. 설정이 요청 처리기 타입에 의존해도, 설정 자신의 메서드(람다 본문 포함)가 `@SystemCaller` 쪽으로 가는 호출을 갖지 않으면 빼는 식이다. 정확하지만 ArchUnit 규칙이 복잡해지고, `@Bean` 메서드가 작업을 `new`하는 호출과 람다 안 호출을 구별해야 한다. + - RED 테스트 모양: 권장안이면 문서 변경이라 RED가 없다. 대안이면 P3을 허용 fixture로 두고 `06f520e6`에서 위반 1로 실패하는 것을 본다. +- **이번 수정 / 이전부터**: 이번 수정(r9에서는 설정을 통째로 뺐으므로 P3이 통과했다). +- **증거**: E2 — 명령 1·2(탐침 P3·P3c). 문서 대조는 E1. + +## Declined to judge + +- `ARE_REQUEST_HANDLER_TYPES`에 빠진 다른 타입(예: 리액티브 `org.springframework.web.server.WebFilter`·`WebHandler`): 이 템플릿은 서블릿 스택이고 WebFlux가 classpath에 없다. 목록 방식의 한계로 매뉴얼 07 `:128-129`가 적는다. RR7-01-01은 r9가 잡던 모양만 다룬다. +- gRPC: 취소된 호출에서 carrier나 IAE로 끝나면 여전히 로그가 남는다. 문서(`src/adapter/inbound/grpc/README.md`)는 "인식 못 한 실패"에 대해서만 취소를 빼므로 어긋나지 않는다. +- gRPC: 서비스가 raw status를 다른 예외로 감싸 던지면(`new IllegalStateException("…", statusException)`) 원인 사슬의 status 설명이 스택에 남는다. RR6-01-05가 약속한 것은 "서비스가 끝낸 raw status"라 범위 밖으로 봤다. 입력값 유출 정책을 넓힐지는 결정할 일이다. +- round6 01의 「Declined to judge」 7건이 README 17절에서 배정·결정으로 닫히지 않았다(README 18절 「멈춤 기준 상태」). + +## 결론 + +Critical 0, Important 0, 회귀 1(RR7-01-01). 결함 2건, 모두 Minor, 모두 이번 수정이 만들었다. + +- RR6-01-01~09는 모두 닫혔다. 주장한 fixture·테스트가 있고 이름대로 본다. +- 새 결함 둘은 RR6-01-01·02를 고친 방법에서 나왔다. 하나는 r9가 잡던 중첩 endpoint를 놓치는 회귀, 하나는 안내대로 해도 실패하는 거짓 실패다. diff --git a/docs/reviews/2026-11-03-rereview/round7/02-idempotency-outbound.md b/docs/reviews/2026-11-03-rereview/round7/02-idempotency-outbound.md new file mode 100644 index 00000000..0f353c58 --- /dev/null +++ b/docs/reviews/2026-11-03-rereview/round7/02-idempotency-outbound.md @@ -0,0 +1,94 @@ +# 02 멱등성·outbound r10 확인 리뷰 (2026-11-06) + +> 대상: `6e992970`(r10)의 r10-02 묶음. RR6-02-01~05 수정: 같은 attempt의 재claim이 lease 지난 claim과 재시도 가능 실패를 +> 넘겨받음, 시작 확인을 그 시작을 적용한 핸들로만, command fake의 시계·key TTL, 503 뜻과 매뉴얼 05 문구. +> 기준 커밋 `06f520e6`(이 영역의 코드는 `6e992970` 뒤로 바뀌지 않았다). + +## 범위 + +### pathspec + +``` +src/application-core src/adapter/outbound/cache-redis src/adapter/outbound/redis-runtime +src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency +docs/manual/05-idempotency.md +``` + +`git diff --shortstat 6e992970^ 6e992970 -- `: 15개 파일, +407 −458. 함께 본 것: `src/adapter/inbound/web/README.md`의 503 행, +`docs/upgrade/2026-11-maturity-review.md` 「멱등성(같은 attempt의 재시도, r10)」 행, `src/adapter/outbound/persistence-jpa/README.md`의 +멱등성 문단, `docs/study/postgresql-jpa-walkthrough.ko.md` 1720줄 근처의 판정 순서표. + +함께 읽은 주변 코드: `IdempotencyExecutor`의 claim·시작·재조정 분기 전체(`:126-232`), Redis `CLAIM`·`TRANSITION` 프로그램 전체 +(`IdempotencyScripts.java`), `PostgreSqlIdempotencyStore.claim`·`markExecutionStarted`, `InMemoryIdempotencyStore` 전체, +`InMemorySemanticRedisCommands`의 CLAIM·TRANSITION·RENEW·INSPECT 사본, 샘플 `PublishPosterImageUseCase:106`(요청마다 새 attempt). + +### 수정 보고의 「새로 가정하는 것」 + +| 가정 | 확인 | +|---|---| +| 같은 attempt를 두 호출이 **동시에** 쓰지 않는다(호출자 계약) | 문서화는 됐다: `IdempotencyClaimAttempt` Javadoc, 매뉴얼 05 `:77-79`, application-core README. 템플릿의 HTTP 경로는 요청마다 새 attempt를 만든다(샘플 `PublishPosterImageUseCase.java:106`). 계약을 어기면 두 번째 호출은 `NOT_CLAIMED` → 500 `IDEMPOTENCY_RECOVERY_REQUIRED`를 받고 작업은 두 번 돌지 않는다(E1, 아래 시나리오 3) | +| 시작이 적용된 기록의 revision은 그 시작을 낸 핸들 revision + 1뿐이다 | 참. 넘겨받기는 늘 revision을 올리고(`CLAIM`의 `rev + 1`, PG `resetClaim`), 시작 전에 revision을 바꾸는 다른 전이가 없다. renew는 실행 중에만 된다 | +| 넘겨받기 판정을 같은 attempt 재생보다 먼저 해도 지문 불일치·완료 재생 판정은 그대로다 | 참. 세 저장소 모두 지문 → 완료 → 포기 → 넘겨받기 → 같은 attempt 순서다(Redis `CLAIM`, PG `PostgreSqlIdempotencyStore.java:117-171`, fake `InMemoryIdempotencyStore.java:52-86`) | + +### 불러온 스킬과 적용한 기준 + +| 스킬 | 기준 | 본 것 | +|---|---|---| +| `superpowers:requesting-code-review` | 주장과 구현, 테스트가 이름대로 보는가, 읽기 전용 | RR6-02-01~05 닫힘, 바뀐 판정 순서가 다른 경로에 미치는 영향 | +| `docs/work/reference/defect-patterns.md` A4·A5·A6 | 결과 불명을 확실함으로, 경쟁을 코드 순서로, 주장하는 것을 보지 않는 테스트 | 같은 attempt의 늦은 시작·재생 핸들 시작이 작업을 두 번 돌리는 길이 남았나, 계약 케이스가 그 길을 보나 | + +### 실행한 명령과 결과 + +| # | 명령 | 결과 | 직전 부하(1분) | +|---|---|---|---| +| 1 | `./gradlew … :application-core:test :adapter:outbound:redis-runtime:test :adapter:outbound:cache-redis:test :adapter:outbound:persistence-jpa:test … --continue` (`06f520e6`, desktop) | README 18.2절 | README 18.2절 | + +실 Redis·실 PostgreSQL 계약 lane(`redisContainerContractTest`, `jpaPlatformContractTest`의 멱등성 계약, `postgresqlIdempotencyIntegrationTest`)은 +다시 돌리지 않았다. 17.2절의 `2c692554` 실행이 마지막이다(E0). 이 영역에서 결함을 찾지 못해 실 vendor로 확인할 의심이 없었다. + +### 따라간 시나리오 (E1) + +1. **시작을 거절당한 attempt의 재시도**: claim(rev r) → lease 지남 → 시작 `LEASE_EXPIRED`(503) → 같은 attempt 재claim → 세 저장소 모두 + `TakenOverClaimed`(attempt 2, rev r+1) → 시작 → 실행. 계약 `anAttemptWhoseStartWasRefusedTakesItsClaimOverWhenItClaimsAgain`. +2. **멈췄던 첫 호출의 늦은 시작**: 위 1의 넘겨받기 뒤 첫 호출이 rev r 핸들로 시작 → Redis `TRANSITION`은 상태가 목표와 같아도 rev가 + r+1이 아니면(넘겨받은 쪽이 시작했으면 r+2) `ALREADY`를 주지 않고 rev 검사로 `NOT_OWNER`. PG는 기록된 시작 digest가 다른 핸들의 것이라 + `classifyStartMismatch` → `NOT_OWNER`. 계약 `aLateStartThroughTheHandleBeforeTheTakeoverIsRefusedAsAStaleOwner`. +3. **같은 attempt의 두 번째 호출이 실행 중에 옴**: 재claim은 `ReplayedAcquire`(현재 핸들) → 시작 → `NOT_CLAIMED` → executor `default` + → 500. 전에는 Redis가 `ALREADY`로 작업을 한 번 더 돌렸다. 계약 `theSameAttemptStartingAnExecutionItAlreadyStartedIsToldItIsNotClaimed`. +4. **시작 응답을 잃은 호출의 같은 호출 안 회복**: `INDETERMINATE` → `inspect` → `EXECUTING_SAME_OPERATION` → `runStarted`. 바뀐 `ALREADY` + 조건은 같은 핸들(rev r → 기록 r+1)이라 그대로 확인된다. + +## 못 본 것 + +- 실 Redis·실 PostgreSQL에서의 재실행(위 설명). +- 배포 중 섞인 버전(옛 인스턴스의 `TRANSITION`은 재생 핸들 시작에 `ALREADY`): round6 02의 Declined to judge에 이미 있다. README 17절에서 + 닫히지 않았다(README 18절). + +## 항목 재확인 + +| ID | 판정 | 근거 | +|---|---|---| +| RR6-02-01 (시작 거절 뒤 같은 attempt가 영원히 503) | 닫힘 | Redis `IdempotencyScripts.java` CLAIM의 넘겨받기 분기가 같은 owner 재생보다 앞, PG `PostgreSqlIdempotencyStore.java:141-160`, fake `InMemoryIdempotencyStore.java:71-84`, command fake 같은 순서. 계약 케이스 6개 추가(위 시나리오 1~3과 재시도 가능 실패·포기·지문) | +| RR6-02-02 (command fake 위 시간 케이스 skip) | 닫힘 | `RedisIdempotencyStoreContractTest`가 `elapse`를 `commands.advance`로 재정의, command fake의 hash TTL(`InMemorySemanticRedisCommands`의 `expireHashAfter`·`hash`). adapter 손 사본 20개 삭제는 "계약과 겹친 것"이라는 README 17절 설명을 따랐다(E0). 하나씩 계약 케이스와 대조하지는 않았다 | +| RR6-02-03 (runbook "message") | 닫힘 | 01의 RR6-01-07과 같은 문장. `docs/runbooks/idempotency-unavailable.md:22-25` | +| RR6-02-04 (503 뜻이 웹 매핑 표·인계 표에 없음) | 닫힘 | `src/adapter/inbound/web/README.md` 503 행, `docs/upgrade/2026-11-maturity-review.md` 프론트 인계 표 503 행 | +| RR6-02-05 (매뉴얼 05 첫 문장과 PG 항목 어긋남) | 닫힘 | `docs/manual/05-idempotency.md:57-61`이 저장소별로 나눠 적는다 | + +## 결함 + +없음. + +## Declined to judge + +- `InMemoryIdempotencyStore`는 시작 응답을 잃은 같은 핸들의 재시작(기록 rev r+1, 핸들 rev r)에 `NOT_OWNER`를 준다. 두 저장소는 + `ALREADY_STARTED_SAME_OPERATION`이다. fake는 응답 유실을 만들지 못하고 계약에 그 케이스가 없어 드러나지 않는다. 이 커밋 전부터이고, + fake와 저장소의 차이를 계약 밖에서 고칠지는 범위 밖이다. +- 같은 owner token에 다른 operation id로 온 claim이 재시도 가능 실패·lease 지난 claim을 만나면, 전에는 `OwnerOperationConflict`(500)였고 + 이제 넘겨받는다(넘겨받기가 같은 owner 판정보다 앞이 되어서). 아무것도 실행되지 않은 기록이라 안전하고, 계약에 이 경우 케이스가 없다. + 동작 변경으로 적어 둔다. 업그레이드 안내에는 없다. +- round6 02의 「Declined to judge」 6건이 README 17절에서 배정·결정으로 닫히지 않았다(README 18절 「멈춤 기준 상태」). + +## 결론 + +Critical 0, Important 0, 회귀 0. 결함 0건. RR6-02-01~05는 모두 닫혔다. 바뀐 판정 순서와 시작 확인 조건은 세 저장소·두 fake에서 +같고, 같은 attempt의 늦은 시작·재생 핸들 시작으로 작업이 두 번 도는 길은 남지 않았다(E1). 실 vendor 재실행은 하지 않았다. diff --git a/docs/reviews/2026-11-03-rereview/round7/03-persistence.md b/docs/reviews/2026-11-03-rereview/round7/03-persistence.md new file mode 100644 index 00000000..e41a5798 --- /dev/null +++ b/docs/reviews/2026-11-03-rereview/round7/03-persistence.md @@ -0,0 +1,129 @@ +# 03 persistence r10 확인 리뷰 (2026-11-06) + +> 대상: `6e992970`(r10)의 r10-03 묶음. RR6-03-01~05 수정: Flyway PostgreSQL 잠금을 세션 수준으로(module-defaults와 +> `FlywaySchemaPolicy.configure()`), 직접 `Flyway.configure()` 금지 규칙, 동시 인덱스 IT, 검사기의 `E'…'`·중첩 주석, +> Flyway 목록 고정 테스트, ledger Spotless, "Flyway는 늘 트랜잭션으로 감싼다" 설명 정정. +> 기준 커밋 `06f520e6`(이 영역의 코드는 `6e992970` 뒤로 바뀌지 않았다). + +## 범위 + +### pathspec + +``` +src/adapter/outbound/persistence-jpa ':!src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency' +':!src/adapter/outbound/persistence-jpa/gradle.lockfile' src/adapter/outbound/persistence-notification +src/adapter/inbound/messaging ':!src/adapter/inbound/messaging/gradle.lockfile' src/grpc src/sample-portfolio +src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/JpaProductionArchitectureTest.java +docs/jpa docs/manual/04-persistence.md docs/study +``` + +`git diff --shortstat 6e992970^ 6e992970 -- `: 28개 파일, +877 −113(lockfile 두 줄 제외). 함께 본 것: +`docs/upgrade/2026-11-maturity-review.md` 2절 15번과 「Flyway 잠금」 행. + +함께 읽은 주변 코드: 운영 코드에서 Flyway를 만드는 모든 곳(`grep org.flywaydb`의 main 6개 파일), `MigrationStartupRunner`, +`src/grpc/CLAUDE.md` 「Durable operation ledger adoption」(ledger는 서비스 Flyway에 위치를 더한다), Flyway 11.14.1 +`PostgreSQLAdvisoryLockTemplate`(`javap`), `LockWaitMigrationInspector` 전체, round6 03. + +### 수정 보고의 「새로 가정하는 것」 + +| 가정 | 확인 | +|---|---| +| Flyway가 잡은 연결은 실행 내내 그것의 것이다(Hikari 직접 연결) | 참. Spring Boot의 Flyway와 템플릿 스트림 모두 애플리케이션 `DataSource`(Hikari)를 받는다. Flyway는 한 연결로 잠그고 푼다. PgBouncer transaction 모드에서 깨진다는 한계는 `docs/jpa/migration-guide.md:27-31`에 적혔다 | +| 세션 잠금으로 바꿔도 잠금 대기 동작은 같다 | 참. Flyway 11.14.1은 두 방식 모두 `pg_try_advisory_[xact_]lock`을 `lockRetryCount`만큼 다시 시도한다(`PostgreSQLAdvisoryLockTemplate.lock`, `javap`). 무한 대기로 바뀌지 않는다 | +| 배포 마이그레이션 도구도 같은 값을 쓴다 | 이 repo 밖이라 확인할 수 없다. 업그레이드 안내 2절 15번과 가이드 `:24-25`가 시킨다 | +| 템플릿이 직접 만드는 Flyway는 모두 `FlywaySchemaPolicy.configure()`를 거친다 | 운영 코드는 참(멱등성·알림·sample 스트림, schema-per-tenant, inbox는 같은 값 사본). 규칙은 `Flyway.configure()`·`configure(ClassLoader)` 호출만 본다(아래 Declined) | + +### 불러온 스킬과 적용한 기준 + +| 스킬 | 기준 | 본 것 | +|---|---|---| +| `superpowers:requesting-code-review` | 주장과 구현, 문서가 동작과 맞는가 | RR6-03-01~05 닫힘, 새로 쓴 설명이 Flyway 실제 동작과 맞나 | +| `supabase-postgres-best-practices` 관점(잠금·마이그레이션) | 강한 잠금은 시간 제한, 동시 빌드는 트랜잭션 밖, 오래된 트랜잭션 확인 | 세션 잠금의 전제, CIC 대기 대상 | +| `docs/work/reference/defect-patterns.md` A2 | 문서와 코드 불일치 | 고친 설명 문장마다 Flyway 실제 동작과 대조 | + +### 실행한 명령과 결과 + +desktop 임시 worktree `~/workspace/t1-r10-review`(`06f520e6`), 공유 잠금 아래. 로그 `~/t1-r10-review-logs/`(desktop). + +| # | 명령 | 결과 | 직전 부하(1분) | +|---|---|---|---| +| 1 | `./gradlew :adapter:outbound:persistence-jpa:rr7ReindexProbe` — 탐침 `Rr7ReindexProbeIntegrationTest`를 임시 lane으로 등록(worktree의 `build.gradle`만 고침), 실 PostgreSQL(Testcontainers, `PostgreSqlReadinessSupport`) | rc=0, 19초. 결과는 아래 표 | 4.28 | +| 2 | `./gradlew … :adapter:outbound:persistence-jpa:test :adapter:outbound:persistence-notification:test :adapter:inbound:messaging:test … :app-bootstrap:architectureTest --rerun --continue` | rc=0. persistence-jpa `test` 664건 실패 0(실행, 임시 lane 때문에 캐시 아님), persistence-notification·messaging `test`는 FROM-CACHE, `architectureTest` 229건 실패 0(`--rerun`, 탐침 1건 포함) | 4.46 | +| 3 | `javap -c -p org.flywaydb.database.postgresql.PostgreSQLAdvisoryLockTemplate`(flyway-database-postgresql 11.14.1, 노트북 Gradle 캐시의 jar) | 세션 모드 `pg_try_advisory_lock` + `RetryStrategy` | — | + +탐침 1은 각 문장 하나만 든 `V1__reindex.sql`을 `.sql.conf` 없이 `FlywaySchemaPolicy.configure()`로 적용한다. Flyway가 트랜잭션 안에서 +돌리면 PostgreSQL이 `25001`로 거부하고, 트랜잭션 밖에서 돌리면 적용된다. + +| 문장 | 결과 | +|---|---| +| `REINDEX TABLE CONCURRENTLY probe` | 실패 `25001` (REINDEX CONCURRENTLY cannot run inside a transaction block) | +| `REINDEX INDEX CONCURRENTLY ix_probe_note` | 실패 `25001` | +| `REINDEX (CONCURRENTLY) TABLE probe` | 실패 `25001` | +| `REINDEX SCHEMA CONCURRENTLY public` | **적용됨**(Flyway가 트랜잭션 밖에서 돌림) | +| `REINDEX DATABASE CONCURRENTLY ` | **적용됨** | + +### 못 본 것 + +- `postgresqlConcurrentIndexMigrationIntegrationTest`·`postgresqlMigrationLockWaitIntegrationTest`·ledger `integrationTest`는 다시 돌리지 않았다. + 17.2절의 `2c692554` 실행이 마지막이다(E0). +- transaction 모드 PgBouncer 뒤의 실제 동작: 환경이 없다. 가이드의 설명은 Flyway 코드(한 연결로 잠그고 풂)와 맞는다(E1). + +## 항목 재확인 + +| ID | 판정 | 근거 | +|---|---|---| +| RR6-03-01 (CIC·REINDEX CONCURRENTLY가 Flyway 기본값에서 끝나지 않음) | 닫힘 | `persistence-jpa.yml:140-149`, `FlywaySchemaPolicy.java:115-127`, 스트림 5곳과 testkit `MigrationContractRunner`가 그것을 쓴다. inbox 사본은 `MessagingInboxSchemaStreamTest`가 값 대조. `JpaProductionArchitectureTest.everyProductionFlywayIsConfiguredThroughTheSchemaPolicy`. 실 PG IT 4건(17.2절, E0). 다만 고치며 쓴 설명 하나가 Flyway 동작과 다르다(RR7-03-02) | +| RR6-03-02 (`E'…\'…'` 문자열 판정) | 닫힘 | `LockWaitMigrationInspector.java`의 `opensEscapeString`·`endOfLiteral`, 테스트 `aLockAfterAnEscapeStringIsStillFound`(4 형태)·`aStatementFlywayRunsOutsideATransactionAfterAnEscapeStringIsNamed`. 중첩 주석(round6 Declined)도 `endOfBlockComment`로 함께 고쳤다 | +| RR6-03-03 (Flyway 목록에 문장이 더해지는 경우) | 닫힘 | `LockWaitMigrationInspectorTest.flywaysPostgreSqlParserStillHasTheStatementListTheInspectorCopied`가 `PostgreSQLParser`의 정적 패턴 전부를 고정한다(PR `ci`) | +| RR6-03-04 (ledger Spotless가 Sync 사본 검사) | 닫힘 | `src/grpc/grpc-operation-ledger-jpa/build.gradle:37-41` `targetExclude` | +| RR6-03-05 ("Flyway는 늘 트랜잭션으로 감싼다" 설명) | 부분 | 세 곳 모두 고쳤다(가이드 `:121-135`, 검사기 Javadoc, study 문서 `:1337-1367`). 새 문장이 "Flyway는 `REINDEX … CONCURRENTLY`를 트랜잭션 안에서 돌린다"로 넓게 적어 `SCHEMA`·`DATABASE` 형태에서 틀린다(RR7-03-02). ledger IT에 더한 안내는 없는 장치를 가리킨다(RR7-03-01) | + +## 결함 + +### RR7-03-01 · Minor · ledger 잠금 대기 IT가 동시 인덱스 파일을 "이 테스트에 예외로 적으라"고 안내하지만 예외를 적을 곳이 없다 + +- **위치**: + - 코드: `src/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerMigrationLockWaitIT.java:38-43`(Javadoc "Name such a file as an exception in this test"), `:98-104`(실패 메시지 "name it as an exception here"), `:69-72`(`migrationsAfterTheFirst()`는 V001 뒤 모든 파일, 거르는 목록 없음). +- **무엇이 틀렸나**: + - r10은 ledger 트리에 동시 인덱스 파일(트랜잭션 밖에서 도는 파일)이 생기면 이 IT가 `25001`로 실패할 때 안내를 붙였다(RR6-03-05). + - 안내는 "그 파일을 이 테스트에 예외로 적으라"다. 그러나 IT에는 예외 목록도, 파일을 거르는 장치도 없다. 매개변수는 트리의 V001 뒤 파일 전부다. +- **발생 조건·영향**: ledger에 `CREATE INDEX CONCURRENTLY` V004를 더하는 사람. IT가 실패하고, 메시지대로 하려면 테스트 구조를 새로 만들어야 한다. 무엇을 어떻게 빼야 하는지(빼도 되는 조건, 빼면 대신 무엇이 그 파일을 보나)는 안내에 없다. 거짓 실패 쪽이라 데이터 피해는 없다. +- **테스트가 못 본 이유**: ledger 트리에 지금 그런 파일이 없다. 안내는 오지 않을 실패에만 붙는다. +- **고치는 법**: + - 권장: IT에 "트랜잭션 밖에서 도는 파일" 목록(파일 이름과 이유)을 두고 `migrationsAfterTheFirst()`에서 뺀다. 그 목록의 파일은 `ConcurrentIndexMigrationInspector`의 두 검사(`.sql.conf`, 혼자인 문장)로 대신 본다. 메시지는 그 목록 이름을 가리킨다. + - 대안: 안내를 "이 IT는 그런 파일을 다룰 수 없다. 테스트에 거르는 장치를 더하는 변경이 필요하다"로 바꾼다. 장치를 만들지 않는 대신 기대를 바로잡는다. + - RED 테스트 모양: 임시 ledger 트리에 `V004__cic.sql`(+`.sql.conf`)을 두고 IT를 돌려 `25001` 실패를 본다. 권장안 뒤에는 목록에 이름을 넣으면 통과하고 inspector가 그 파일을 검사한다. +- **이번 수정 / 이전부터**: 이번 수정. +- **증거**: E1 — 코드 위치(grep으로 IT에 예외·제외 장치가 없음을 확인). 실행 탐침은 하지 않았다(ledger 트리를 바꿔야 해서 optional 빌드 integrationTest가 필요, 결함이 메시지의 사실 문제라 코드로 충분). + +### RR7-03-02 · Minor · "Flyway는 `REINDEX … CONCURRENTLY`를 트랜잭션 안에서 돌린다"고 적었지만 `REINDEX SCHEMA|DATABASE CONCURRENTLY`는 트랜잭션 밖에서 돌린다 + +- **위치**: + - 문서: `docs/jpa/migration-guide.md:122-125`("but not `REINDEX … CONCURRENTLY`, which it runs in the transaction for PostgreSQL to refuse"), `docs/study/postgresql-jpa-walkthrough.ko.md:1340-1342`("`REINDEX … CONCURRENTLY`는 모른다. 그 파일은 트랜잭션 안에서 돌고"). + - 코드: `src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/ConcurrentIndexMigrationInspector.java:13-16`(Javadoc), `:54-57`(실패 메시지 "Flyway runs REINDEX ... CONCURRENTLY in one unless the migration says otherwise"). +- **무엇이 틀렸나**: + - Flyway 11의 트랜잭션 밖 목록에는 `^REINDEX( VERBOSE)? (SCHEMA|DATABASE|SYSTEM)`이 있다(`LockWaitMigrationInspectorTest.java:295`가 고정한 Flyway 패턴). 그래서 `REINDEX SCHEMA CONCURRENTLY`·`REINDEX DATABASE CONCURRENTLY`는 Flyway가 스스로 트랜잭션 밖에서 돌린다. + - 탐침 1: 그 두 문장은 `.sql.conf` 없이 적용됐다. `REINDEX TABLE|INDEX CONCURRENTLY`와 `REINDEX (CONCURRENTLY) TABLE`만 `25001`로 거부됐다. + - 문서·Javadoc·실패 메시지는 `REINDEX … CONCURRENTLY` 전체를 "Flyway가 모르는, 트랜잭션 안에서 도는" 문장으로 적는다. RR6-03-05가 고치려던 것과 같은 종류(Flyway가 언제 트랜잭션을 쓰는지에 대한 틀린 설명)다. 가이드의 "but not `REINDEX … CONCURRENTLY`"는 이전부터 있었고, r10이 "which it runs in the transaction"을 붙이고 같은 말을 검사기 Javadoc·메시지·study 문서로 넓혔다. +- **발생 조건·영향**: 행동 지시("동시 문장마다 `executeInTransaction=false`를 적는다")는 맞으므로 잘못된 배포로 이어지지 않는다. 틀린 것은 이유다. 검사기 메시지를 받은 사람이 `REINDEX SCHEMA CONCURRENTLY` 파일에서 "Flyway가 트랜잭션 안에서 돌린다"고 믿고 원인을 잘못 짚을 수 있다. `LockWaitMigrationInspector` Javadoc(`:150-151`, "`REINDEX TABLE CONCURRENTLY`는 목록에 없다")은 정확하다 — 같은 주제에 정확한 문장과 넓은 문장이 함께 있다. +- **테스트가 못 본 이유**: IT `flywayRunsReindexConcurrentlyInATransactionWherePostgresqlRefusesIt`는 `REINDEX TABLE CONCURRENTLY`만 본다. 문장은 문서·메시지라 대조하는 테스트가 없다. +- **고치는 법**: + - 권장: 네 곳을 "Flyway는 `REINDEX INDEX|TABLE … CONCURRENTLY`(괄호 옵션 형태 포함)를 트랜잭션 안에서 돌린다. `REINDEX SCHEMA|DATABASE|SYSTEM`은 `CONCURRENTLY`와 상관없이 트랜잭션 밖에서 돌린다"로 고친다. 행동 지시는 그대로 둔다. + - 대안: IT의 REINDEX 케이스를 탐침 1처럼 다섯 형태로 넓혀 Flyway 동작을 고정하고, 문서는 그 IT를 가리킨다. + - RED 테스트 모양: 대안을 쓰면 `REINDEX SCHEMA CONCURRENTLY public`이 "트랜잭션 안에서 거부된다"고 단언하는 케이스가 지금 실패한다(탐침 1 결과). +- **이번 수정 / 이전부터**: 섞임. 가이드의 "but not `REINDEX … CONCURRENTLY`"는 이전부터, "which it runs in the transaction"과 검사기 Javadoc·메시지·study 문서의 같은 문장은 이번 수정. +- **증거**: E3 — 명령 1(실 PostgreSQL, Flyway 11.14.1). 패턴은 E1. + +## Declined to judge + +- `JpaProductionArchitectureTest`의 Flyway 규칙은 `Flyway.configure()`·`Flyway.configure(ClassLoader)` 호출만 본다. `new FluentConfiguration()`·`new ClassicConfiguration()`으로 만든 Flyway는 지나간다. 문서(`persistence-jpa/CLAUDE.md:100-104`, 매뉴얼 04 `:122-124`)는 "`Flyway.configure()`를 부르면 실패한다"로 정확히 적는다. 생성자 경로를 막을지는 규칙 범위 결정이라 판단하지 않았다. +- 세션 잠금에서 연결이 끊기지 않은 채 unlock이 실패하면(Flyway가 "Unable to release PostgreSQL advisory lock"을 로그로만 남기는 경우) 잠금이 Hikari 풀의 연결에 남을 수 있다. Flyway 코드 경로로만 본 것이고 재현하지 않았다. 트랜잭션 잠금에는 없던 위험이다. 결정(Flyway 공식 옵션 채택)의 전제를 바꿀 만한 증거는 아니다. +- round6 03의 「Declined to judge」 10건 중 중첩 블록 주석은 r10이 고쳤고, 나머지 9건은 README 17절에서 배정·결정으로 닫히지 않았다(README 18절 「멈춤 기준 상태」). + +## 결론 + +Critical 0, Important 0, 회귀 0. 결함 2건, 모두 Minor. + +- 이번 수정: RR7-03-01(ledger IT의 없는 예외 장치 안내). +- 섞임: RR7-03-02(REINDEX 설명 — 이전부터 있던 넓은 문장을 이번 수정이 이유를 붙여 네 곳으로 넓힘). +- RR6-03-01~04는 닫혔고, RR6-03-05는 부분이다(위 두 결함). 세션 잠금 전제(한 연결, 재시도 대기)는 Flyway 코드와 맞는다. diff --git a/docs/reviews/2026-11-03-rereview/round7/04-build-logic-shell.md b/docs/reviews/2026-11-03-rereview/round7/04-build-logic-shell.md new file mode 100644 index 00000000..cf37c3c2 --- /dev/null +++ b/docs/reviews/2026-11-03-rereview/round7/04-build-logic-shell.md @@ -0,0 +1,81 @@ +# 04 build-logic 셸 판독 r10 확인 리뷰 (2026-11-06) + +> 대상: `6e992970`(r10)의 r10-04 묶음 중 셸 스크립트 판독(`ShellScript`)과 단계 검사 플러그인 쪽. RR6-04-03(조건부 `exit`·`exec`· +> `set -n`·`trap`), RR6-04-05(세지 않는 이유 셋과 실패 메시지). workflow 판독·Gradle 명령줄 쪽은 05다. +> 기준 커밋 `06f520e6`. 그 뒤 커밋 `e6b6e18e`가 같은 패키지의 `StrictTestLanePlugin`을 바꿨지만 이 pathspec의 파일은 바꾸지 않았다. + +## 범위 + +### pathspec + +``` +src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/ShellScript.java +src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesPlugin.java +src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesFunctionalTest.java +src/build-logic/build.gradle src/build-logic/README.md +``` + +`git diff --shortstat 6e992970^ 6e992970 -- `: 5개 파일, +659 −100. build-logic 묶음 전체는 +1,916줄이라 상한(1,500줄)을 넘어 +셸 판독(04)과 workflow 판독(05)으로 나눴다. 셸 모양의 테스트는 대부분 `WorkflowGradleInvocationsTest`에 있어(05 pathspec) 그 파일의 +셸 케이스도 함께 읽었다. + +함께 읽은 주변 코드: `ShellScript.java` 전체(1,659줄 중 `Evaluator`·`Parser`의 바뀐 곳과 그 호출자), `OPAQUE_COMMANDS`(`eval`·`source`·`.` +뒤의 디렉터리를 읽지 않음), round6 04의 RR6-04-03·05와 그 Declined. + +### 수정 보고의 「새로 가정하는 것」 + +| 가정 | 확인 | +|---|---| +| 스크립트가 0으로 끝날 수 있는 길은 `exit`·`exec`·`set -n`·`EXIT`/`ERR` trap과 그것을 부르는 함수다 | 남은 길(`eval "exit 0"`, `source`한 파일 안의 `exit`)은 `OPAQUE_COMMANDS`가 그 뒤 디렉터리를 "읽지 않음"으로 만들어 뒤 명령이 세어지지 않는다(거짓 실패 쪽). 거짓 통과로 새지 않는다(E1) | +| 리터럴이 아닌 `exit` 값은 0일 수 있다 | 판독기가 그렇게 본다(`exitsWithSuccess`). 거짓 실패 쪽 | +| 파이프 안·`( )`·`$( )` 안의 `exit`은 그 하위 셸만 끝낸다 | 참(bash에 `lastpipe`가 기본으로 꺼져 있음). 판독기는 그 경우를 건너뛴다(`walk`) | + +### 불러온 스킬과 적용한 기준 + +| 스킬 | 기준 | 본 것 | +|---|---|---| +| `superpowers:requesting-code-review` | 주장과 구현, 테스트가 이름대로 보는가 | RR6-04-03·05 닫힘 | +| `docs/work/reference/defect-patterns.md` A7 | 거짓 통과 게이트 | 새 분기마다 "세지 말아야 할 명령을 세는가"(거짓 통과)와 "셀 명령을 안 세는가"(설계상 허용된 거짓 실패)를 나눠 봄 | + +### 실행한 명령과 결과 + +| # | 명령 | 결과 | 직전 부하(1분) | +|---|---|---|---| +| 1 | `./gradlew -p build-logic test --rerun` (desktop `~/workspace/t1-r10-review`, `06f520e6` + 05의 탐침 1건) | rc=0, 40초, 169건 실패 0 skip 0 | 3.69 | + +### 따라간 모양 (E1) + +- 최상위 `exit 0` 뒤, `[ -z "$X" ] && exit 0` 뒤, `if …; then exit 0; fi` 뒤: 앞은 `terminated`, 뒤 둘은 `mayHaveEnded`로 뒤 명령을 세지 않는다. +- `./gradlew ci || exit`·`|| exit 1`: 인자 없는 `exit`은 실패 상태를 지키고, 그 명령은 "읽지 않음"(3번 이유)으로 남는다. +- `trap 'exit 0' EXIT`, `trap cleanup EXIT`(함수 안 인자 없는 `exit`), `trap 'exit' ERR`: 첫째와 셋째만 뒤 명령을 세지 않는다. EXIT trap의 인자 없는 `exit`은 상태를 지킨다는 판단은 bash 동작과 맞다. +- `exec > log 2>&1`(재지정만): 셸을 바꾸지 않으므로 끝내지 않는다고 본다. `exec ./gradlew ci`: 바꾼다. +- `set +o errexit`, `set -n`, `set -o noexec`, `set "$OPTS"`: 앞 둘은 읽고, 값이 펼쳐지는 `set`은 "알 수 없음"으로 errexit·noexec 둘 다 꺼졌을 수 있다고 본다. +- `echo | exit 0`: 파이프 안이라 하위 셸만 끝난다. 세는 데 영향 없음. +- 사용자 정의 `shell:` 템플릿(`bash {0}`처럼 `-e` 없는 것): `SHELLS` 표에 없는 이름이라 "읽지 않음"으로 남는다(05 `WorkflowGradleInvocations.java:155-159`, `:412-420`). + +## 못 본 것 + +- 실제 GitHub runner의 bash 동작: 실행할 수 없다. 판단은 bash 매뉴얼의 `exit`·`trap`·`set -e` 설명과 판독기 코드 대조다(E1). +- 이 repo의 실제 workflow 판정이 수정 전후 같다는 README 17절 주장("세는 명령 48개")은 다시 세지 않았다. 두 빌드의 `verifyStrictLaneStages --dry-run`은 17.2절 `2c692554`에서 통과했다(E0). + +## 항목 재확인 + +| ID | 판정 | 근거 | +|---|---|---| +| RR6-04-03 (맨 위 `exit`만 봄) | 닫힘 | `ShellScript.java`의 `effects`·`mayEnd`·`trap`·`endingIn`·`called`, 테스트(`WorkflowGradleInvocationsTest`의 조건부 `exit`·`exec`·`set -n`·함수 안 `exit`·EXIT/ERR trap 케이스) | +| RR6-04-05 (세지 않는 이유를 반대로 적음) | 닫힘 | 이유를 셋(실패를 막지 못함 / 돌지 않을 수 있음 / 판독기가 읽지 않음)으로 나눴다. `ShellScript` Javadoc `:25-56`, 각 이유 문구, `StrictLaneStagesPlugin.NOT_COUNTED`(`:61-75`), AGENTS.md·CLAUDE.md·`src/README.md`·`build-logic/README.md`·업그레이드 B-36이 같은 셋을 적는다. 단 `NOT_COUNTED`의 끝 문장은 05의 RR7-05-01 | + +## 결함 + +없음. + +## Declined to judge + +- 한 번 걸린 `trap 'exit 0' EXIT`를 `trap - EXIT`로 풀어도 판독기는 뒤 명령을 계속 세지 않는다. 거짓 실패 쪽이고 이 모양을 쓰는 workflow는 드물다. +- `kill $$`, `kill -TERM 0`처럼 셸을 신호로 끝내는 명령: 판독기가 보지 않는다. 신호로 끝난 단계는 실패로 끝나므로 거짓 통과가 아니다. +- round6 04의 「Declined to judge」 7건이 README 17절에서 배정·결정으로 닫히지 않았다(README 18절 「멈춤 기준 상태」). 그중 경로·브랜치 필터 항목은 05의 RR7-05-01과 겹친다. + +## 결론 + +Critical 0, Important 0, 회귀 0. 결함 0건. RR6-04-03·05는 닫혔다. 새 분기가 만드는 오판은 모두 "세지 않음"(거짓 실패) 쪽이고, 따라간 모양에서 +세지 말아야 할 명령을 세는 길은 찾지 못했다(E1). diff --git a/docs/reviews/2026-11-03-rereview/round7/05-build-logic-workflow.md b/docs/reviews/2026-11-03-rereview/round7/05-build-logic-workflow.md new file mode 100644 index 00000000..348ef811 --- /dev/null +++ b/docs/reviews/2026-11-03-rereview/round7/05-build-logic-workflow.md @@ -0,0 +1,97 @@ +# 05 build-logic workflow 판독 r10 확인 리뷰 (2026-11-06) + +> 대상: `6e992970`(r10)의 r10-04 묶음 중 workflow 판독(`WorkflowGradleInvocations`)과 Gradle 명령줄 쪽. RR6-04-01(작업 없이 끝나는 +> 옵션), RR6-04-02(옵션 표를 Gradle과 대조), RR6-04-04(Windows runner 기본 셸), RR6-04-06(요청형 trigger·`workflow_call`·`needs`). +> 셸 판독 쪽은 04다. 기준 커밋 `06f520e6`(이 pathspec의 파일은 `6e992970` 뒤로 바뀌지 않았다). + +## 범위 + +### pathspec + +``` +src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocations.java +src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocationsTest.java +src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/GradleCommandLineTest.java +AGENTS.md CLAUDE.md src/README.md +``` + +`git diff --shortstat 6e992970^ 6e992970 -- `: 6개 파일, +1288 −101. 함께 본 것: `docs/upgrade/2026-11-maturity-review.md` B-36, +`StrictLaneStagesPlugin.NOT_COUNTED`(04 pathspec), 이 repo의 `.github/workflows/*.yml` 15개의 trigger. + +### 수정 보고의 「새로 가정하는 것」 + +| 가정 | 확인 | +|---|---| +| change·release trigger(`push`, `pull_request`(+types), `pull_request_target`, `merge_group`, `schedule`, `release`)가 하나라도 있으면 그 workflow는 "매 변경에 돈다" | 거짓인 경우가 있다. `paths:` 필터가 붙은 trigger는 그 경로가 바뀔 때만 돈다. 그런데 실패 메시지·문서는 "매 push·pull request·schedule에 도는 workflow"에서 단계를 돌리라고 한다(RR7-05-01) | +| `workflow_call` workflow는 `uses: ./.github/workflows/`로 부르는 job을 통해서만 돈다 | 참. 다른 repo 표기(`owner/repo/.github/workflows/x.yml@ref`)로 같은 repo를 부르면 못 알아보지만 세지 않는 쪽(거짓 실패)이다 | +| 판독기의 Gradle 옵션 표는 실행 중인 Gradle의 `--help`와 같다 | 참. `GradleCommandLineTest`가 대조한다(이 실행에서 통과, 아래 명령 1) | + +### 불러온 스킬과 적용한 기준 + +| 스킬 | 기준 | 본 것 | +|---|---|---| +| `superpowers:requesting-code-review` | 주장과 구현, 문서·메시지가 동작과 같은가 | RR6-04-01·02·04·06 닫힘, 새 메시지가 시키는 것과 판독기가 세는 것 | +| `ci-cd-and-automation` | 게이트가 매 변경에 도는가 | trigger·필터·job 조건 | +| `docs/work/reference/defect-patterns.md` A2·A7 | 문서와 코드 불일치, 거짓 통과 게이트 | 판독기가 "돈다"고 보는 workflow의 범위 | + +### 실행한 명령과 결과 + +desktop 임시 worktree `~/workspace/t1-r10-review`(`06f520e6`), 공유 잠금 아래. 로그 `~/t1-r10-review-logs/`(desktop), 탐침 코드는 공유 노트 폴더 `rr7-probes/`. + +| # | 명령 | 결과 | 직전 부하(1분) | +|---|---|---|---| +| 1 | `./gradlew -p build-logic test --tests dev.caskeleton.buildlogic.strictlane.Rr7WorkflowProbeTest` | rc=0. 결과는 아래 | 4.66 | +| 2 | `./gradlew -p build-logic test --rerun` | rc=0, 40초, 169건 실패 0 skip 0(탐침 1건 포함) | 3.69 | + +탐침 `Rr7WorkflowProbeTest`는 `WorkflowGradleInvocations.read`에 두 workflow를 준다. + +| workflow | 읽은 결과 | +|---|---| +| `on: pull_request: paths: ["docs/**"]` + `push: branches: [main], paths: ["docs/**"]`, `run: ./gradlew ci` | `uncountedReason=null` — 실행으로 센다 | +| `on: workflow_dispatch`, 같은 step(대조군) | "its workflow starts only on workflow_dispatch … so it may not run" — 세지 않는다 | + +## 못 본 것 + +- 실제 GitHub의 trigger 해석(`paths` 필터, `types`, `needs`의 건너뜀): 실행할 수 없다. GitHub 문서 기준(E1). +- `--stop`·`--foreground`는 `GradleCommandLineTest`도 실행하지 않는다(데몬을 멈추거나 붙잡음). 표에 둔 근거는 Javadoc의 Gradle 소스 설명뿐이다(E0). + +## 항목 재확인 + +| ID | 판정 | 근거 | +|---|---|---| +| RR6-04-01 (작업 없이 끝나는 Gradle 옵션) | 닫힘 | `GRADLE_OPTIONS_THAT_RUN_NO_TASK`(`WorkflowGradleInvocations.java:134-143`), 묶음(`-qv`) 처리, 테스트 | +| RR6-04-02 (옵션 표를 지키는 테스트 없음) | 닫힘 | `GradleCommandLineTest`가 옵션 표 전체를 실행 중인 Gradle `--help`와 대조하고, 작업 없이 끝나는 옵션을 실제로 실행한다(`--stop`·`--foreground` 제외) | +| RR6-04-04 (Windows runner 기본 셸) | 닫힘 | `defaultShellReason`: `container:`가 있거나 `ubuntu-*`·`macos-*`·`linux`·`macos` 라벨일 때만 기본 셸을 bash로 읽는다. 식(`${{ matrix.os }}`)·Windows 라벨·라벨 없는 self-hosted는 세지 않는다 | +| RR6-04-06 (요청형 trigger·`workflow_call`·`needs`) | 닫힘 | `startReason`·`runsOnChanges`·`needsReason`, 테스트. 다만 고치며 쓴 메시지·문서가 새 약속을 했다(RR7-05-01) | + +## 결함 + +### RR7-05-01 · Minor · 실패 메시지와 문서는 "매 push·pull request·schedule에 도는 workflow"에서 단계를 돌리라고 하지만, 판독기는 `paths:` 필터로 일부 변경에만 도는 workflow도 센다 + +- **위치**: + - 코드: `src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesPlugin.java:61-75`(`NOT_COUNTED` 끝: "in a step and job that run on every push, pull request or schedule"), `WorkflowGradleInvocations.java:44-55`(Javadoc "A workflow counts when one of its triggers is part of the change or release flow"), `:96-101`(`CHANGE_TRIGGERS`), `:620-627`(`runsOnChanges`는 trigger 이름과 `types`만 본다). + - 문서: `docs/upgrade/2026-11-maturity-review.md` B-36 할 일 칸("단계는 매 push·pull request·schedule에 도는 workflow와 job에서"). +- **무엇이 틀렸나**: + - r10은 "요청이 있어야 도는 workflow"를 세지 않게 하면서, 무엇이 "매 변경에 도는" workflow인지를 메시지와 문서에 처음 적었다: 매 push·pull request·schedule. + - 판독기는 trigger 이름과 `types`만 본다. `paths:`·`paths-ignore:` 필터는 읽지 않는다. + - 탐침: `pull_request`와 `push` 모두 `paths: ["docs/**"]`인 workflow의 `./gradlew ci`를 실행으로 센다. 이 workflow는 docs만 바뀐 변경에서만 돌고, 코드가 바뀐 PR에서는 돌지 않는다. + - 이 repo에도 `paths:` 필터가 있는 workflow가 7개 있다(`build-logic.yml`, `fileserver-pr.yml`, `link-check.yml`, `messaging-certification.yml`, `notification-platform.yml`, `object-storage-qualification.yml`, `redis-sdk-topology.yml`). 지금은 단계 명령을 거기서만 돌리지 않아 판정은 맞다. +- **발생 조건·영향**: 파생 서비스가 무거운 단계(`integrationCheck` 등)를 비용 때문에 `paths:` 필터 workflow로 옮긴다. 검사는 통과하고, 필터 밖 변경에서는 그 단계가 돌지 않는다. 메시지와 업그레이드 안내가 약속한 "매 변경"과 다르다. +- **테스트가 못 본 이유**: `WorkflowGradleInvocationsTest`의 trigger 케이스는 이벤트 이름·`types`·`workflow_call`·`needs`만 다룬다. 필터 케이스가 없다. +- **이번 수정 / 이전부터**: 섞임. 필터를 읽지 않는 동작은 이전부터다(round6 04 「Declined to judge」 첫 줄: "어떤 필터가 충분한지는 저장소 정책이라 판단하지 않았다"). "매 push·pull request·schedule"이라는 약속은 이번 수정이 메시지·문서에 썼다. +- **고치는 법** — 정책 선택이 먼저다(README 18절 「결정이 필요한 것」): + - 권장(a): `paths:`·`paths-ignore:`가 붙은 trigger는 "매 변경"이 아니므로 그 trigger만으로는 세지 않는다. 이유는 2번(돌지 않을 수 있음). `branches:` 필터는 기본 브랜치를 포함하면 센다. 이 repo의 단계 명령은 필터 없는 workflow에 있어 판정이 바뀌지 않는다. + - 대안(b): 동작은 두고 메시지·B-36을 "change trigger 중 하나로 시작하는 workflow(경로 필터는 보지 않는다)"로 고친다. 필터의 충분성은 저장소 책임으로 문서에 적는다. + - RED 테스트 모양: (a)면 탐침 workflow를 `WorkflowGradleInvocationsTest`에 넣고 `uncountedReason`이 null이 아님을 단언한다. `06f520e6`에서 실패한다(탐침 결과). +- **증거**: E2 — 명령 1(탐침). 이 repo workflow의 필터 목록은 E1(`grep -n "paths:" .github/workflows/*.yml`). + +## Declined to judge + +- `push: tags: ['v*']`만 있는 workflow(태그 push에만 돈다)도 change trigger로 센다. 릴리스 단계(`releaseCheck`)는 그런 workflow에서 도는 것이 맞아서 결함으로 보지 않았다. 다른 단계를 거기에만 두는 경우는 RR7-05-01과 같은 정책 질문이다. +- `runs-on`을 `group:` 매핑으로만 쓰고 `labels:`가 없는 job은 Windows일 수 있다고 보아 세지 않는다(거짓 실패 쪽, 메시지가 이유를 말함). +- 다른 repo 표기로 같은 repo의 재사용 workflow를 부르는 job: 위 「새로 가정하는 것」 둘째 줄. 거짓 실패 쪽. + +## 결론 + +Critical 0, Important 0, 회귀 0. 결함 1건(Minor, 섞임 — 동작은 이전부터, 약속은 이번 수정). RR6-04-01·02·04·06은 닫혔다. RR7-05-01은 +고치기 전에 소유자가 경로 필터 정책을 정해야 한다. From 7ce83b73d949e510ac0e7150be1ccdcc943e24b3 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 6 Nov 2026 22:17:02 +0900 Subject: [PATCH 12/71] =?UTF-8?q?fix(web):=20=EB=B3=B4=EC=95=88=20?= =?UTF-8?q?=ED=95=84=ED=84=B0=EA=B0=80=205xx=20=EC=9D=B8=EC=A6=9D=20?= =?UTF-8?q?=EC=8B=A4=ED=8C=A8=EB=A5=BC=20ERROR=EB=A1=9C=20=EB=82=A8?= =?UTF-8?q?=EA=B8=B4=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: AuthErrorResponseWriter는 보안 필터가 답한 실패를 모두 WARN으로 남긴다. AUTH_JWKS_UNAVAILABLE(503, 키 서버 장애)과 INTERNAL_AUTH_MISCONFIGURATION(500, 인증 설정 오류)은 서버 쪽 고장인데도 WARN이다. 다른 모든 경로는 5xx를 ERROR로 남기므로(ServerFailureLog) 규칙이 갈라져 있고, ERROR로 거르는 운영자는 이 둘을 놓친다. 고른 방법: 응답 상태로 레벨을 고른다. 5xx는 ERROR, 4xx는 WARN이다. 줄의 모양(code·category·method·path, 예외 없음)은 그대로다. 401 서명·issuer· audience 불일치는 WARN으로 둔다(소유자 결정 3, 2026-11-06). 테스트가 서명 실패 WARN도 고정한다. 버린 대안: 두 코드를 이름으로 나열하기 — 새 5xx 보안 코드가 생기면 조용히 WARN에 남는다. ServerFailureLog 줄로 바꾸기 — 예외를 붙이는 줄이라, 토큰이 섞일 수 있는 실패 메시지를 남기지 않는 이 writer의 계약과 맞지 않는다. 위험·한계: ERROR 수로 경보를 거는 곳에 JWKS 장애와 인증 설정 오류가 새로 잡힌다. upgrade 안내 5절에 적었다. 결정은 docs/superpowers/specs/2026-11-06-error-code-log-level-design.md 10절이다. 검증(desktop, 공유 잠금, 로그는 desktop ~/t3-loglevel-logs/): - RED: 기준 writer로 EnvelopeAuthenticationEntryPointTest 8건 중 2건 실패 (aKeyServiceOutageIsLoggedAtError, aDecoderMisconfigurationIsLoggedAtError — WARN이 나오고 ERROR를 기대). rc=1, red-web.log - GREEN: :adapter:inbound:web:check rc=0, 테스트 329건 실패 0. green-web-check.log - :adapter:inbound:web:testQualityCheck rc=0, green-quality.log --- docs/runbooks/auth-jwks-unavailable.md | 4 +- .../auth-public-path-misconfiguration.md | 4 +- docs/upgrade/2026-11-maturity-review.md | 1 + src/adapter/inbound/web/README.md | 4 + .../web/auth/AuthErrorResponseWriter.java | 18 ++-- .../EnvelopeAuthenticationEntryPointTest.java | 86 +++++++++++++++++++ 6 files changed, 108 insertions(+), 9 deletions(-) diff --git a/docs/runbooks/auth-jwks-unavailable.md b/docs/runbooks/auth-jwks-unavailable.md index 42bcc829..b7c529e4 100644 --- a/docs/runbooks/auth-jwks-unavailable.md +++ b/docs/runbooks/auth-jwks-unavailable.md @@ -4,7 +4,7 @@ category: TRANSIENT_DEPENDENCY error_codes: [AUTH_JWKS_UNAVAILABLE] severity: P1 owner: oncall -last_updated: 2026-06-15 +last_updated: 2026-11-06 status: stub --- @@ -13,6 +13,8 @@ status: stub ## Symptoms - HTTP 503 with `error.code=AUTH_JWKS_UNAVAILABLE` +- ERROR log line `security failure: code=AUTH_JWKS_UNAVAILABLE category=TRANSIENT_DEPENDENCY method=… path=…` + (logger `AuthErrorResponseWriter`) - All authentication failing; JWKS refresh attempts failing ## Diagnosis diff --git a/docs/runbooks/auth-public-path-misconfiguration.md b/docs/runbooks/auth-public-path-misconfiguration.md index df069a67..019a1976 100644 --- a/docs/runbooks/auth-public-path-misconfiguration.md +++ b/docs/runbooks/auth-public-path-misconfiguration.md @@ -4,7 +4,7 @@ category: INTERNAL error_codes: [INTERNAL_AUTH_MISCONFIGURATION] severity: P1 owner: oncall -last_updated: 2026-06-15 +last_updated: 2026-11-06 status: stub --- @@ -13,6 +13,8 @@ status: stub ## Symptoms - HTTP 500 with `error.code=INTERNAL_AUTH_MISCONFIGURATION` +- ERROR log line `security failure: code=INTERNAL_AUTH_MISCONFIGURATION category=INTERNAL method=… path=…` + (logger `AuthErrorResponseWriter`) - Security filter misconfiguration detected at runtime ## Diagnosis diff --git a/docs/upgrade/2026-11-maturity-review.md b/docs/upgrade/2026-11-maturity-review.md index ef50f035..4c768e01 100644 --- a/docs/upgrade/2026-11-maturity-review.md +++ b/docs/upgrade/2026-11-maturity-review.md @@ -243,6 +243,7 @@ V21 실패의 분류는 `docs/runbooks/migration-failed.md` "Classify the failur | sample-portfolio | 익명 쓰기 401, 포스터 제목 대소문자 무시 유일(409 `POSTER_ALREADY_EXISTS`), 관리자도 남의 work log 수정 불가, 샘플 이벤트 tenant `global` | sample을 남긴 서비스만 | `34565130`, `1400dc15` | | Flyway 잠금 | Flyway의 PostgreSQL 마이그레이션 잠금을 트랜잭션 대신 세션에 둔다. Spring Boot의 Flyway는 module-defaults `spring.flyway.postgresql.transactional-lock: false`, 템플릿이 직접 만드는 Flyway(멱등성·알림·sample stream, schema-per-tenant, testkit `MigrationContractRunner`)는 `FlywaySchemaPolicy.configure()`, messaging inbox stream은 같은 값을 직접 넣는다. 운영 코드의 `Flyway.configure()` 직접 호출은 `JpaProductionArchitectureTest`가 거부한다 | Flyway 기본값에서는 동시 인덱스 마이그레이션이 Flyway 자신의 열린 트랜잭션을 기다려 끝나지 않았다. 이제 끝난다. 마이그레이션은 잠금을 잡은 연결 하나로 돈다. transaction 모드 PgBouncer 뒤에서는 잠금 해제가 다른 서버 연결로 가 다음 배포가 기다릴 수 있으니 마이그레이션은 직접 연결이나 session 모드 pool로 돌린다. 배포 도구는 이 repo 밖이라 2절 15번으로 맞춘다 | 재리뷰 round6 RR6-03-01 · `persistence-jpa.yml`, `.../migration/FlywaySchemaPolicy.java`, `docs/jpa/migration-guide.md` "Who may change the schema"·"Concurrent index builds" | | 성능 lane(HTTP client·Mongo) | httpclient `LargeBodyResourceTest`의 힙 상한(32 MiB 스트리밍 중 힙 증가 16 MiB 미만)을 매번 단언한다. 전에는 `-Pperformance.assertions.enabled=true`일 때만 단언하고 아니면 건너뛴다는 줄만 찍었다. Mongo `MongoResourceBudgetLaneTest`는 표준 gate 전체(p99 500ms, pool 대기 250ms, 힙 512 MiB, examined/returned 10, spill 금지)를 Gradle 밖 실행에서도 단언한다(B-43) | 손으로 돌린 `performanceCheck`가 상한을 실제로 재므로, 전에는 통과하던 느린 기계에서 실패할 수 있다 | B4(2026-11-06) · `LargeBodyResourceTest`, `MongoResourceBudgetLaneTest` | +| 보안 필터 로그 레벨 | 보안 필터(`AuthErrorResponseWriter`)의 `security failure` 줄을 5xx(`AUTH_JWKS_UNAVAILABLE` 503, `INTERNAL_AUTH_MISCONFIGURATION` 500)면 ERROR, 4xx면 WARN으로 남긴다. 전에는 모두 WARN이었다. 다른 경로가 5xx를 ERROR로 남기는 규칙(`ServerFailureLog`)과 같아졌다 | ERROR로 거르는 로그 경보·대시보드에 JWKS 장애와 인증 설정 오류가 새로 잡힌다. 401·403은 그대로 WARN | 설계 메모 2026-11-06 7절 결정 2 · `src/adapter/inbound/web/.../auth/AuthErrorResponseWriter.java`, `docs/superpowers/specs/2026-11-06-error-code-log-level-design.md` | ## 6. 따라오는 순서 diff --git a/src/adapter/inbound/web/README.md b/src/adapter/inbound/web/README.md index 7b2336ca..6383ea21 100644 --- a/src/adapter/inbound/web/README.md +++ b/src/adapter/inbound/web/README.md @@ -115,6 +115,10 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML 코드의 일반 `client_safe_message` 만 담고, 원시 예외 텍스트·`Authorization` 헤더·issuer·audience 는 절대 포함하지 않는다. 로그 라인엔 code/category/요청 path 만 기록하고 bearer token 은 절대 로깅하지 않는다(leak 테스트가 강제하는 계약). 전체 로그 마스킹 필터는 별도 log-management 영역에서 다룬다. +- **로그 레벨.** 4xx(토큰 누락·만료·서명·issuer·audience·kid 실패, 권한 부족)는 호출자 쪽 실패라 WARN이다. + 5xx(`AUTH_JWKS_UNAVAILABLE` 503, `INTERNAL_AUTH_MISCONFIGURATION` 500)는 서버 쪽 고장이라 ERROR다. 다른 + 경로가 5xx를 ERROR로 남기는 규칙(shared-contract `ServerFailureLog`)과 같다. 레벨은 오류 코드 레지스트리의 + 칸이 아니라 이 코드가 정한다(설계 메모 `docs/superpowers/specs/2026-11-06-error-code-log-level-design.md`). - **WWW-Authenticate(RFC 9110 §15.5.2).** 401 응답은 반드시 WWW-Authenticate 헤더를 갖되, `error_description` 으로 issuer/token 세부가 새지 않도록 최소한으로 유지한다. diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/AuthErrorResponseWriter.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/AuthErrorResponseWriter.java index 79068f66..7893d1ba 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/AuthErrorResponseWriter.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/AuthErrorResponseWriter.java @@ -8,6 +8,7 @@ import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.slf4j.event.Level; import org.springframework.http.HttpHeaders; import tools.jackson.databind.ObjectMapper; @@ -28,13 +29,16 @@ class AuthErrorResponseWriter { void write(HttpServletRequest request, HttpServletResponse response, OperationalError code) throws IOException { - // Log only safe metadata — never the token or the raw failure message. - log.warn( - "security failure: code={} category={} method={} path={}", - code.code(), - code.category(), - request.getMethod(), - request.getRequestURI()); + // Log only safe metadata — never the token or the raw failure message. A 5xx is the server's + // own failure (the key service is down, the decoder is misconfigured) and is an ERROR, as a 5xx + // is on every other path (ServerFailureLog); a 4xx is the caller's and stays a WARN. + log.atLevel(code.httpStatus() >= 500 ? Level.ERROR : Level.WARN) + .log( + "security failure: code={} category={} method={} path={}", + code.code(), + code.category(), + request.getMethod(), + request.getRequestURI()); // A 401 response carries a minimal WWW-Authenticate header (no issuer / token detail). if (code.httpStatus() == 401) { diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/EnvelopeAuthenticationEntryPointTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/EnvelopeAuthenticationEntryPointTest.java index 3ad25ca3..d580043b 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/EnvelopeAuthenticationEntryPointTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/EnvelopeAuthenticationEntryPointTest.java @@ -2,17 +2,23 @@ package dev.caskeleton.adapter.inbound.web.auth; import static org.assertj.core.api.Assertions.assertThat; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; import dev.caskeleton.shared.error.Category; import dev.caskeleton.shared.error.ClientErrorMessages; +import java.io.IOException; import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.slf4j.LoggerFactory; import org.springframework.boot.test.system.CapturedOutput; import org.springframework.boot.test.system.OutputCaptureExtension; import org.springframework.http.HttpHeaders; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.authentication.InsufficientAuthenticationException; +import org.springframework.security.core.AuthenticationException; import org.springframework.security.oauth2.core.OAuth2Error; import org.springframework.security.oauth2.core.OAuth2ErrorCodes; import org.springframework.security.oauth2.jwt.BadJwtException; @@ -106,6 +112,86 @@ class EnvelopeAuthenticationEntryPointTest { .isEqualTo("AUTH_JWKS_UNAVAILABLE"); } + @Test + void aKeyServiceOutageIsLoggedAtError() throws Exception { + // given + AuthenticationException outage = + new InvalidBearerTokenException( + "invalid", + new JwtDecoderConfig.AuthenticationKeyServiceUnavailableException( + new IOException("connect timed out"))); + + // when + List lines = writerLinesFor(outage); + + // then + assertThat(lines) + .singleElement() + .extracting(event -> event.getLevel().toString(), ILoggingEvent::getFormattedMessage) + .containsExactly( + "ERROR", + "security failure: code=AUTH_JWKS_UNAVAILABLE category=TRANSIENT_DEPENDENCY" + + " method=GET path=/v1/things"); + } + + @Test + void aDecoderMisconfigurationIsLoggedAtError() throws Exception { + // given + AuthenticationException misconfiguration = + new InvalidBearerTokenException( + "invalid", + new JwtDecoderConfig.AuthenticationDecoderMisconfigurationException( + new IllegalStateException("issuer metadata does not match"))); + + // when + List lines = writerLinesFor(misconfiguration); + + // then + assertThat(lines) + .singleElement() + .extracting(event -> event.getLevel().toString(), ILoggingEvent::getFormattedMessage) + .containsExactly( + "ERROR", + "security failure: code=INTERNAL_AUTH_MISCONFIGURATION category=INTERNAL" + + " method=GET path=/v1/things"); + } + + @Test + void aRejectedSignatureStaysAtWarn() throws Exception { + // given + AuthenticationException rejected = + new InvalidBearerTokenException( + "invalid", new BadJwtException("Signed JWT rejected: Invalid signature")); + + // when + List lines = writerLinesFor(rejected); + + // then + assertThat(lines) + .singleElement() + .extracting(event -> event.getLevel().toString(), ILoggingEvent::getFormattedMessage) + .containsExactly( + "WARN", + "security failure: code=AUTH_TOKEN_INVALID_SIGNATURE category=AUTH" + + " method=GET path=/v1/things"); + } + + /** The lines the security writer logs while the entry point answers {@code failure}. */ + private List writerLinesFor(AuthenticationException failure) throws Exception { + Logger logger = (Logger) LoggerFactory.getLogger(AuthErrorResponseWriter.class); + ListAppender appender = new ListAppender<>(); + appender.start(); + logger.addAppender(appender); + try { + entryPoint.commence( + new MockHttpServletRequest("GET", "/v1/things"), new MockHttpServletResponse(), failure); + } finally { + logger.detachAppender(appender); + appender.stop(); + } + return appender.list; + } + @Test void tokenValueNeverLeaksIntoResponseBodyOrLogs(CapturedOutput output) throws Exception { // §테스트 계약: a JWT value must never appear in the response or the log output. From e0beeca214e463124d9763ae5972878bb8b14e52 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 6 Nov 2026 22:17:13 +0900 Subject: [PATCH 13/71] =?UTF-8?q?fix(error-codes)!:=20=EB=A0=88=EC=A7=80?= =?UTF-8?q?=EC=8A=A4=ED=8A=B8=EB=A6=AC=EC=97=90=EC=84=9C=20log=5Flevel=20?= =?UTF-8?q?=EC=B9=B8=EC=9D=84=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 문제: docs/registries/error-codes.yaml의 log_level 칸은 읽는 코드가 없다. 로그 레벨은 오류 코드가 아니라 실패의 종류와 경로가 정한다 (ServerFailureLog, AuthErrorResponseWriter). 그래서 그 코드를 내는 곳이 있는 47행 중 33행이 실제 레벨과 달랐고, 런북 2곳이 틀린 레벨을 증상으로 적었다. 고른 방법: 칸을 지우고, 머리말이 레벨을 정하는 코드를 가리킨다(설계 메모 안 A, 소유자 결정 2026-11-06). 칸이 다시 생기지 않게 OperationalErrorRegistryContractTest에 단언을 둔다. client_safe_message를 코드에 고정한 테스트가 있는 자리다. 모든 레지스트리의 공통 스키마를 보는 ContractRegistrySchemaGovernanceTest는 한 레지스트리의 칸 뜻을 다루지 않아 고르지 않았다. 런북은 실제 로그 줄을 증상으로 적는다. 결정 색인 2.3절과 설계 메모 10절에 결정을 남겼다. 버린 대안: 칸을 코드에 맞추고 테스트로 고정(B) — 규칙의 손 사본이 생기고, 템플릿이 내지 않는 13행은 고정할 값이 없다. 칸을 규범으로 만들어 코드가 읽기(C) — 4xx를 남기지 않는 설계를 뒤집고 로그 양이 는다. 위험·한계: 자기 error-codes.yaml 행에 log_level을 둔 파생 서비스는 merge 뒤 mainCheck(documentContractTest)가 실패한다. upgrade 안내 「반드시 할 일」 17과 B-44에 적었다. repo 밖에서 이 칸을 읽는 도구는 없는 것으로 본다(소유자 결정 4). 검증(desktop, 공유 잠금, 로그는 desktop ~/t3-loglevel-logs/): - RED: 기준 yaml로 OperationalErrorRegistryContractTest 3건 중 noRegistryRowCarriesALogLevel 1건 실패(log_level이 있는 행 목록 출력). rc=1, red-registry.log - GREEN: :app-bootstrap:documentContractTest rc=0, 66건 실패 0 (RunbookCoverageContractTest 포함). green-doc-contract.log - :app-bootstrap:testQualityCheck :app-bootstrap:spotlessCheck rc=0. green-quality.log - python3 scripts/check-work-docs.py rc=0, --links docs 깨진 링크 0 BREAKING CHANGE: error-codes.yaml 행에 log_level이 있으면 OperationalErrorRegistryContractTest가 실패한다. 파생 서비스는 자기 행에서 log_level: 줄을 지운다. 레벨을 바꾸려면 그 실패를 로그로 남기는 코드를 고친다. --- docs/registries/error-codes.yaml | 70 +++---------------- docs/runbooks/auth-token-invalid-signature.md | 6 +- docs/runbooks/authz-tenant-mismatch.md | 6 +- .../2026-11-06-error-code-log-level-design.md | 16 ++++- docs/upgrade/2026-11-maturity-review.md | 2 + docs/work/reference/decisions.md | 1 + .../OperationalErrorRegistryContractTest.java | 19 +++++ 7 files changed, 53 insertions(+), 67 deletions(-) diff --git a/docs/registries/error-codes.yaml b/docs/registries/error-codes.yaml index d569b16b..6b29101f 100644 --- a/docs/registries/error-codes.yaml +++ b/docs/registries/error-codes.yaml @@ -1,7 +1,7 @@ # Registry: Error Codes # Schema owner: feature-contract-registry-governance # Category enum owner: feature-operational-error-observability-foundation -# Last updated: 2026-09-28 +# Last updated: 2026-11-06 # Scope: skeleton-wide OperationalError SSOT. Product/fork ApiErrorCode enums own local registries/contracts. # # Schema (per row): @@ -15,7 +15,6 @@ # owner_layer: presentation | application | domain | infrastructure | crosscut # client_safe_message: = shared-contract ClientErrorMessages.of(category) — category별 한국어 문구 표 # 하나(소유자 결정 11). no token / no principal raw / no internal path / no stack trace -# log_level: ERROR | WARN | INFO # runbook_link: runbook://area/scenario OR null (client-error만 null 허용) # compatibility_impact: none | additive | behavior-change | breaking # required_test: owning contract test identifier @@ -25,6 +24,13 @@ # TRANSIENT_DEPENDENCY, PERMANENT_DEPENDENCY} ⇒ runbook_link 필수. # VALIDATION/NOT_FOUND/CONFLICT/DATA_INTEGRITY는 client-error로 runbook 면제 가능. # retryable=true 인 모든 row는 runbook_link 필수. +# +# 로그 레벨은 행의 칸이 아니다. 레벨은 오류 코드가 아니라 실패의 종류와 경로가 정한다. +# shared-contract ServerFailureLog — 모든 전송이 쓴다. 영속성·의존성 carrier와 5xx carrier는 ERROR, +# 4xx carrier는 남기지 않는다. IllegalArgumentException(BAD_PARAMETER)은 WARN. +# web AuthErrorResponseWriter — 보안 필터. 5xx는 ERROR, 4xx는 WARN. +# 행에 log_level을 두면 OperationalErrorRegistryContractTest가 실패한다. +# 결정: docs/superpowers/specs/2026-11-06-error-code-log-level-design.md 7·10절. errors: @@ -41,7 +47,6 @@ errors: owner_branch: feature-security-operational-baseline owner_layer: presentation client_safe_message: "인증이 필요합니다." - log_level: WARN runbook_link: "runbook://auth/token-missing" compatibility_impact: none required_test: contract-verification:auth-category @@ -55,7 +60,6 @@ errors: owner_branch: feature-security-operational-baseline owner_layer: presentation client_safe_message: "인증이 필요합니다." - log_level: WARN runbook_link: "runbook://auth/token-malformed" compatibility_impact: none required_test: contract-verification:auth-category @@ -69,7 +73,6 @@ errors: owner_branch: feature-security-operational-baseline owner_layer: presentation client_safe_message: "인증이 필요합니다." - log_level: WARN runbook_link: "runbook://auth/token-expired" compatibility_impact: none required_test: contract-verification:auth-category @@ -83,7 +86,6 @@ errors: owner_branch: feature-security-operational-baseline owner_layer: presentation client_safe_message: "인증이 필요합니다." - log_level: ERROR runbook_link: "runbook://auth/token-invalid-signature" compatibility_impact: none required_test: contract-verification:auth-category @@ -97,7 +99,6 @@ errors: owner_branch: feature-security-operational-baseline owner_layer: presentation client_safe_message: "인증이 필요합니다." - log_level: ERROR runbook_link: "runbook://auth/issuer-mismatch" compatibility_impact: none required_test: contract-verification:auth-category @@ -111,7 +112,6 @@ errors: owner_branch: feature-security-operational-baseline owner_layer: presentation client_safe_message: "인증이 필요합니다." - log_level: ERROR runbook_link: "runbook://auth/audience-mismatch" compatibility_impact: none required_test: contract-verification:auth-category @@ -126,7 +126,6 @@ errors: owner_branch: feature-security-operational-baseline owner_layer: presentation client_safe_message: "인증이 필요합니다." - log_level: WARN runbook_link: "runbook://auth/kid-unknown" compatibility_impact: none required_test: contract-verification:auth-category @@ -140,7 +139,6 @@ errors: owner_branch: feature-security-operational-baseline owner_layer: infrastructure client_safe_message: "일시적인 오류입니다. 잠시 후 다시 시도해 주세요." - log_level: ERROR runbook_link: "runbook://auth/jwks-unavailable" compatibility_impact: none required_test: contract-verification:auth-category @@ -154,7 +152,6 @@ errors: owner_branch: feature-security-operational-baseline owner_layer: presentation client_safe_message: "인증이 필요합니다." - log_level: ERROR runbook_link: "runbook://auth/claim-mapping-failed" compatibility_impact: none required_test: contract-verification:auth-category @@ -172,7 +169,6 @@ errors: owner_branch: feature-security-operational-baseline owner_layer: presentation client_safe_message: "이 작업을 수행할 권한이 없습니다." - log_level: WARN runbook_link: "runbook://authz/insufficient-permission" compatibility_impact: none required_test: contract-verification:authz-category @@ -186,7 +182,6 @@ errors: owner_branch: feature-security-operational-baseline owner_layer: presentation client_safe_message: "이 작업을 수행할 권한이 없습니다." - log_level: ERROR runbook_link: "runbook://authz/tenant-mismatch" compatibility_impact: none required_test: contract-verification:authz-category @@ -204,7 +199,6 @@ errors: owner_branch: feature-security-operational-baseline owner_layer: crosscut client_safe_message: "요청을 처리할 수 없습니다." - log_level: ERROR runbook_link: "runbook://auth/public-path-misconfiguration" compatibility_impact: none required_test: contract-verification:auth-category @@ -218,7 +212,6 @@ errors: owner_branch: feature-container-runtime-contract owner_layer: infrastructure client_safe_message: "요청을 처리할 수 없습니다." - log_level: ERROR runbook_link: "runbook://runtime/jvm-oom" compatibility_impact: none required_test: contract-verification:container-runtime-oom @@ -236,7 +229,6 @@ errors: owner_branch: feature-persistence-failure-baseline owner_layer: infrastructure client_safe_message: "일시적인 오류입니다. 잠시 후 다시 시도해 주세요." - log_level: ERROR runbook_link: "runbook://db/unavailable" compatibility_impact: none required_test: contract-verification:persistence-mapping @@ -250,7 +242,6 @@ errors: owner_branch: feature-persistence-failure-baseline owner_layer: infrastructure client_safe_message: "현재 상태에서는 요청을 처리할 수 없습니다." - log_level: WARN runbook_link: "runbook://db/serialization-failure" compatibility_impact: none required_test: contract-verification:persistence-mapping @@ -264,7 +255,6 @@ errors: owner_branch: feature-persistence-failure-baseline owner_layer: infrastructure client_safe_message: "현재 상태에서는 요청을 처리할 수 없습니다." - log_level: WARN runbook_link: "runbook://db/deadlock" compatibility_impact: none required_test: contract-verification:persistence-mapping @@ -278,7 +268,6 @@ errors: owner_branch: feature-persistence-failure-baseline owner_layer: infrastructure client_safe_message: "요청을 처리할 수 없습니다." - log_level: WARN runbook_link: null compatibility_impact: none required_test: contract-verification:persistence-mapping @@ -292,7 +281,6 @@ errors: owner_branch: feature-persistence-failure-baseline owner_layer: infrastructure client_safe_message: "요청을 처리할 수 없습니다." - log_level: WARN runbook_link: null compatibility_impact: none required_test: contract-verification:persistence-mapping @@ -306,7 +294,6 @@ errors: owner_branch: feature-persistence-failure-baseline owner_layer: infrastructure client_safe_message: "현재 상태에서는 요청을 처리할 수 없습니다." - log_level: WARN runbook_link: null compatibility_impact: none required_test: contract-verification:persistence-mapping @@ -320,7 +307,6 @@ errors: owner_branch: feature-persistence-failure-baseline owner_layer: infrastructure client_safe_message: "요청을 처리할 수 없습니다." - log_level: WARN runbook_link: null compatibility_impact: none required_test: contract-verification:persistence-mapping @@ -334,7 +320,6 @@ errors: owner_branch: feature-persistence-failure-baseline owner_layer: infrastructure client_safe_message: "일시적인 오류입니다. 잠시 후 다시 시도해 주세요." - log_level: ERROR runbook_link: "runbook://db/idle-in-tx-timeout" compatibility_impact: none required_test: contract-verification:persistence-mapping @@ -348,7 +333,6 @@ errors: owner_branch: feature-persistence-failure-baseline owner_layer: infrastructure client_safe_message: "일시적인 오류입니다. 잠시 후 다시 시도해 주세요." - log_level: WARN runbook_link: "runbook://db/query-canceled" compatibility_impact: none required_test: contract-verification:persistence-mapping @@ -362,7 +346,6 @@ errors: owner_branch: feature-persistence-failure-baseline owner_layer: infrastructure client_safe_message: "현재 상태에서는 요청을 처리할 수 없습니다." - log_level: WARN runbook_link: null compatibility_impact: additive required_test: persistence-jpa:JpaPersistenceExceptionCodeTest @@ -376,7 +359,6 @@ errors: owner_branch: feature-persistence-failure-baseline owner_layer: infrastructure client_safe_message: "요청을 처리할 수 없습니다." - log_level: ERROR runbook_link: null compatibility_impact: additive required_test: persistence-jpa:JpaPersistenceExceptionCodeTest @@ -394,7 +376,6 @@ errors: owner_branch: feature-rate-limit-idempotency-contract owner_layer: presentation client_safe_message: "요청이 너무 잦습니다. 잠시 후 다시 시도해 주세요." - log_level: WARN runbook_link: "runbook://rate-limit/exceeded" compatibility_impact: none required_test: contract-verification:rate-limit @@ -412,7 +393,6 @@ errors: owner_branch: feature-rate-limit-idempotency-contract owner_layer: application client_safe_message: "현재 상태에서는 요청을 처리할 수 없습니다." - log_level: INFO runbook_link: null compatibility_impact: behavior-change required_test: contract-verification:idempotency @@ -426,7 +406,6 @@ errors: owner_branch: feature-rate-limit-idempotency-contract owner_layer: application client_safe_message: "요청 값이 올바르지 않습니다." - log_level: WARN runbook_link: null compatibility_impact: none required_test: contract-verification:idempotency @@ -440,7 +419,6 @@ errors: owner_branch: feature-rate-limit-idempotency-contract owner_layer: application client_safe_message: "일시적인 오류입니다. 잠시 후 다시 시도해 주세요." - log_level: WARN runbook_link: "runbook://idempotency/unavailable" compatibility_impact: additive required_test: contract-verification:idempotency @@ -456,7 +434,6 @@ errors: owner_branch: feature-rate-limit-idempotency-contract owner_layer: application client_safe_message: "일시적인 오류입니다. 잠시 후 다시 시도해 주세요." - log_level: ERROR runbook_link: "runbook://idempotency/unavailable" compatibility_impact: additive required_test: contract-verification:idempotency @@ -470,7 +447,6 @@ errors: owner_branch: feature-rate-limit-idempotency-contract owner_layer: application client_safe_message: "요청을 처리할 수 없습니다." - log_level: ERROR runbook_link: "runbook://idempotency/unavailable" compatibility_impact: additive required_test: contract-verification:idempotency @@ -498,7 +474,6 @@ errors: owner_branch: feature-api-contract-baseline owner_layer: presentation client_safe_message: "요청 값이 올바르지 않습니다." - log_level: INFO runbook_link: null compatibility_impact: none required_test: contract-verification:api-contract-status-mapping @@ -512,7 +487,6 @@ errors: owner_branch: feature-api-contract-baseline owner_layer: presentation client_safe_message: "요청 값이 올바르지 않습니다." - log_level: INFO runbook_link: null compatibility_impact: none required_test: contract-verification:api-contract-status-mapping @@ -526,7 +500,6 @@ errors: owner_branch: feature-api-contract-baseline owner_layer: presentation client_safe_message: "현재 상태에서는 요청을 처리할 수 없습니다." - log_level: INFO runbook_link: null compatibility_impact: none required_test: contract-verification:api-contract-status-mapping @@ -540,7 +513,6 @@ errors: owner_branch: feature-api-contract-baseline owner_layer: presentation client_safe_message: "요청 값이 올바르지 않습니다." - log_level: WARN runbook_link: null compatibility_impact: none required_test: contract-verification:api-contract-status-mapping @@ -557,7 +529,6 @@ errors: owner_branch: feature-api-contract-baseline owner_layer: presentation client_safe_message: "요청 값이 올바르지 않습니다." - log_level: WARN runbook_link: null compatibility_impact: none required_test: contract-verification:api-contract-status-mapping @@ -571,7 +542,6 @@ errors: owner_branch: feature-api-contract-baseline owner_layer: presentation client_safe_message: "요청 값이 올바르지 않습니다." - log_level: INFO runbook_link: null compatibility_impact: none required_test: contract-verification:api-contract-status-mapping @@ -609,7 +579,6 @@ errors: owner_branch: feature-outbound-http-client-baseline owner_layer: infrastructure client_safe_message: "일시적인 오류입니다. 잠시 후 다시 시도해 주세요." - log_level: ERROR runbook_link: "runbook://dependency/timeout" compatibility_impact: none required_test: contract-verification:outbound-http @@ -623,7 +592,6 @@ errors: owner_branch: feature-outbound-http-client-baseline owner_layer: infrastructure client_safe_message: "일시적인 오류입니다. 잠시 후 다시 시도해 주세요." - log_level: ERROR runbook_link: "runbook://dependency/connect-failed" compatibility_impact: none required_test: contract-verification:outbound-http @@ -637,7 +605,6 @@ errors: owner_branch: feature-outbound-http-client-baseline owner_layer: infrastructure client_safe_message: "일시적인 오류입니다. 잠시 후 다시 시도해 주세요." - log_level: ERROR runbook_link: "runbook://dependency/dns-failed" compatibility_impact: none required_test: contract-verification:outbound-http @@ -651,7 +618,6 @@ errors: owner_branch: feature-outbound-http-client-baseline owner_layer: infrastructure client_safe_message: "요청을 처리할 수 없습니다." - log_level: ERROR runbook_link: "runbook://dependency/4xx-client" compatibility_impact: none required_test: contract-verification:outbound-http @@ -665,7 +631,6 @@ errors: owner_branch: feature-outbound-http-client-baseline owner_layer: infrastructure client_safe_message: "일시적인 오류입니다. 잠시 후 다시 시도해 주세요." - log_level: ERROR runbook_link: "runbook://dependency/5xx-server" compatibility_impact: none required_test: contract-verification:outbound-http @@ -679,7 +644,6 @@ errors: owner_branch: feature-outbound-http-client-baseline owner_layer: infrastructure client_safe_message: "일시적인 오류입니다. 잠시 후 다시 시도해 주세요." - log_level: WARN runbook_link: "runbook://dependency/circuit-open" compatibility_impact: none required_test: contract-verification:outbound-http @@ -697,7 +661,6 @@ errors: owner_branch: feature-domain-event-outbox-contract owner_layer: infrastructure client_safe_message: "일시적인 오류입니다. 잠시 후 다시 시도해 주세요." - log_level: ERROR runbook_link: "runbook://outbox/publish-failed" compatibility_impact: none required_test: contract-verification:outbox-publish @@ -711,7 +674,6 @@ errors: owner_branch: feature-domain-event-outbox-contract owner_layer: infrastructure client_safe_message: "요청을 처리할 수 없습니다." - log_level: ERROR runbook_link: "runbook://outbox/dead-letter" compatibility_impact: none required_test: contract-verification:outbox-dlq @@ -729,7 +691,6 @@ errors: owner_branch: feature-background-job-async-contract owner_layer: infrastructure client_safe_message: "일시적인 오류입니다. 잠시 후 다시 시도해 주세요." - log_level: ERROR runbook_link: "runbook://job/executor-rejected" compatibility_impact: none required_test: contract-verification:async-saturation @@ -743,7 +704,6 @@ errors: owner_branch: feature-background-job-async-contract owner_layer: infrastructure client_safe_message: "일시적인 오류입니다. 잠시 후 다시 시도해 주세요." - log_level: ERROR runbook_link: "runbook://job/timeout" compatibility_impact: none required_test: contract-verification:async-timeout @@ -757,7 +717,6 @@ errors: owner_branch: feature-background-job-async-contract owner_layer: infrastructure client_safe_message: "요청을 처리할 수 없습니다." - log_level: ERROR runbook_link: "runbook://job/dead-letter" compatibility_impact: none required_test: contract-verification:async-dlq @@ -782,7 +741,6 @@ errors: owner_branch: feature-distributed-lock-contract owner_layer: infrastructure client_safe_message: "현재 상태에서는 요청을 처리할 수 없습니다." - log_level: WARN runbook_link: "runbook://lock/acquisition-timeout" compatibility_impact: none required_test: contract-verification:lock-acquisition-timeout @@ -800,7 +758,6 @@ errors: owner_branch: feature-integration-adapter-templates owner_layer: infrastructure client_safe_message: "요청을 처리할 수 없습니다." - log_level: ERROR runbook_link: "runbook://adapter/adapter-disabled" compatibility_impact: none required_test: adapter-contract:adapter-disabled-runtime-call @@ -819,7 +776,6 @@ errors: owner_branch: feature-management-actuator-security-contract owner_layer: presentation client_safe_message: "이 작업을 수행할 권한이 없습니다." - log_level: WARN runbook_link: "runbook://management/actuator-forbidden" compatibility_impact: none required_test: contract-verification:management-actuator @@ -838,7 +794,6 @@ errors: owner_branch: 2026-09-21-core-web-review-remediation owner_layer: application client_safe_message: "요청 값이 올바르지 않습니다." - log_level: INFO runbook_link: null compatibility_impact: additive required_test: contract-verification:operational-error-registry @@ -851,7 +806,6 @@ errors: owner_branch: 2026-09-21-core-web-review-remediation owner_layer: presentation client_safe_message: "요청 값이 올바르지 않습니다." - log_level: INFO runbook_link: null compatibility_impact: additive required_test: contract-verification:operational-error-registry @@ -864,7 +818,6 @@ errors: owner_branch: 2026-09-21-core-web-review-remediation owner_layer: presentation client_safe_message: "요청 값이 올바르지 않습니다." - log_level: INFO runbook_link: null compatibility_impact: additive required_test: contract-verification:operational-error-registry @@ -877,7 +830,6 @@ errors: owner_branch: 2026-09-21-core-web-review-remediation owner_layer: application client_safe_message: "요청 값이 올바르지 않습니다." - log_level: WARN runbook_link: null compatibility_impact: additive required_test: contract-verification:operational-error-registry @@ -890,7 +842,6 @@ errors: owner_branch: 2026-09-21-core-web-review-remediation owner_layer: crosscut client_safe_message: "요청을 처리할 수 없습니다." - log_level: ERROR runbook_link: "runbook://internal/error-spike" compatibility_impact: additive required_test: contract-verification:operational-error-registry @@ -903,7 +854,6 @@ errors: owner_branch: 2026-09-21-core-web-review-remediation owner_layer: presentation client_safe_message: "인증이 필요합니다." - log_level: WARN runbook_link: "runbook://auth/token-missing" compatibility_impact: additive required_test: contract-verification:operational-error-registry @@ -916,7 +866,6 @@ errors: owner_branch: 2026-09-21-core-web-review-remediation owner_layer: presentation client_safe_message: "인증이 필요합니다." - log_level: WARN runbook_link: "runbook://auth/token-malformed" compatibility_impact: additive required_test: contract-verification:operational-error-registry @@ -929,7 +878,6 @@ errors: owner_branch: 2026-09-21-core-web-review-remediation owner_layer: presentation client_safe_message: "이 작업을 수행할 권한이 없습니다." - log_level: WARN runbook_link: "runbook://authz/insufficient-permission" compatibility_impact: additive required_test: contract-verification:operational-error-registry @@ -942,7 +890,6 @@ errors: owner_branch: 2026-09-21-core-web-review-remediation owner_layer: presentation client_safe_message: "요청한 리소스를 찾을 수 없습니다." - log_level: INFO runbook_link: null compatibility_impact: additive required_test: contract-verification:operational-error-registry @@ -955,7 +902,6 @@ errors: owner_branch: 2026-09-21-core-web-review-remediation owner_layer: infrastructure client_safe_message: "현재 상태에서는 요청을 처리할 수 없습니다." - log_level: WARN runbook_link: null compatibility_impact: additive required_test: contract-verification:operational-error-registry diff --git a/docs/runbooks/auth-token-invalid-signature.md b/docs/runbooks/auth-token-invalid-signature.md index ce057a1f..02051f53 100644 --- a/docs/runbooks/auth-token-invalid-signature.md +++ b/docs/runbooks/auth-token-invalid-signature.md @@ -4,7 +4,7 @@ category: AUTH error_codes: [AUTH_TOKEN_INVALID_SIGNATURE] severity: P1 owner: oncall -last_updated: 2026-06-15 +last_updated: 2026-11-06 status: stub --- @@ -13,7 +13,9 @@ status: stub ## Symptoms - HTTP 401 with `error.code=AUTH_TOKEN_INVALID_SIGNATURE` -- `log_level=ERROR` — may indicate forged tokens or wrong signing key +- WARN log line `security failure: code=AUTH_TOKEN_INVALID_SIGNATURE category=AUTH method=… path=…` + (logger `AuthErrorResponseWriter`). It is a WARN because the caller sent the token; search by + `code=`, not by level. A burst of these may indicate forged tokens or a wrong signing key ## Diagnosis diff --git a/docs/runbooks/authz-tenant-mismatch.md b/docs/runbooks/authz-tenant-mismatch.md index 1bd30beb..47747cd9 100644 --- a/docs/runbooks/authz-tenant-mismatch.md +++ b/docs/runbooks/authz-tenant-mismatch.md @@ -4,7 +4,7 @@ category: AUTHZ error_codes: [AUTHZ_TENANT_MISMATCH] severity: P1 owner: oncall -last_updated: 2026-06-15 +last_updated: 2026-11-06 status: stub --- @@ -13,7 +13,9 @@ status: stub ## Symptoms - HTTP 403 with `error.code=AUTHZ_TENANT_MISMATCH` -- `log_level=ERROR` — cross-tenant access attempt detected +- The template does not emit this code; the service that decides cross-tenant access does. A 403 + carrier is answered without a log line (`ServerFailureLog`), so that service logs + `code=AUTHZ_TENANT_MISMATCH` where it decides, if this runbook is to find the attempt ## Diagnosis diff --git a/docs/superpowers/specs/2026-11-06-error-code-log-level-design.md b/docs/superpowers/specs/2026-11-06-error-code-log-level-design.md index dc736ed0..4392d283 100644 --- a/docs/superpowers/specs/2026-11-06-error-code-log-level-design.md +++ b/docs/superpowers/specs/2026-11-06-error-code-log-level-design.md @@ -1,6 +1,6 @@ # `error-codes.yaml`의 `log_level` 칸 — 설계 메모 -- 상태: **소유자 결정 대기** (2026-11-06). 결정할 것은 7절이다. +- 상태: **확정** (2026-11-06, 소유자 답 "권하는 안대로"). 결정은 10절이다. 아래 1~9절은 결정 전에 쓴 그대로 둔다. - 기준 커밋: `06f520e6` (`refactor/maturity-review-2026-11`) - 크기: 중간(brief). 이 메모가 고르는 안을 실제로 적용하는 일은 **큼**이다. 오류 코드 레지스트리는 공개 계약이라 파일 하나여도 큼이다(`docs/work/README.md` 2절). 그래서 이 메모는 대안 비교까지 하고 멈춘다. 코드와 yaml은 @@ -229,3 +229,17 @@ - `LockAcquisitionTimeoutClassificationContractTest`가 막으려는 "500 INTERNAL로 뭉개기"(D7)와 같은 모양이다. 그 테스트는 enum과 레지스트리만 보고 전송 경로는 보지 않는다. - 코드 읽기 결과이고 탐침은 돌리지 않았다. 결함 후보로 `docs/work/improve.md` 절차에 넘긴다. + +## 10. 결정 (2026-11-06) + +소유자 답은 "권하는 안대로"다(총괄 세션 전달, 2026-11-06). 7절 각 항목은 이렇게 정해졌다. + +| # | 결정 | 적용한 곳 | +| --- | --- | --- | +| 1 | A. `log_level` 칸을 지운다. 레지스트리 머리말이 레벨을 정하는 코드(`ServerFailureLog`, `AuthErrorResponseWriter`)를 가리킨다 | `docs/registries/error-codes.yaml` 머리말과 60행 | +| 1-b | 칸이 다시 생기지 않게 단언을 둔다. 파생 서비스는 자기 행에서도 지운다 | `OperationalErrorRegistryContractTest.noRegistryRowCarriesALogLevel`(태그 `document-contract`), `docs/upgrade/2026-11-maturity-review.md` 「반드시 할 일」 17·B-44 | +| 2 | 보안 필터는 5xx(`AUTH_JWKS_UNAVAILABLE` 503, `INTERNAL_AUTH_MISCONFIGURATION` 500)를 ERROR로 남긴다 | `AuthErrorResponseWriter`(5xx ERROR, 4xx WARN), `EnvelopeAuthenticationEntryPointTest`, web README, 런북 2곳, upgrade 5절 | +| 3 | 401 서명·issuer·audience 불일치는 WARN으로 둔다. 런북은 WARN 줄의 `code=`로 찾게 고친다 | `docs/runbooks/auth-token-invalid-signature.md`, 서명 실패 WARN을 고정한 테스트 | +| 4 | repo 밖에서 이 칸을 읽는 도구는 없는 것으로 본다 | — | + +결정 색인: `docs/work/reference/decisions.md` 2.3절 「오류 코드 로그 레벨」. diff --git a/docs/upgrade/2026-11-maturity-review.md b/docs/upgrade/2026-11-maturity-review.md index 4c768e01..8bc96132 100644 --- a/docs/upgrade/2026-11-maturity-review.md +++ b/docs/upgrade/2026-11-maturity-review.md @@ -37,6 +37,7 @@ | 14 | 자기 테스트 코드에 `./gradlew testQualityCheck`를 돌려 보고, 발견을 고치거나 이유를 단 Match로 뺀다(B-40) | `mainCheck`가 실패 | 테스트 코드가 있는 모든 서비스 | | 15 | staging·prod 배포 마이그레이션 도구에 `flyway.postgresql.transactional.lock=false`(환경 변수 `FLYWAY_POSTGRESQL_TRANSACTIONAL_LOCK=false`)를 넣는다. 자기 Flyway stream은 `Flyway.configure()` 대신 `FlywaySchemaPolicy.configure()`로 만든다(5절 「Flyway 잠금」) | `CREATE INDEX CONCURRENTLY`·`REINDEX … CONCURRENTLY` 마이그레이션에서 배포가 오류 없이 멈춘다. 자기 stream이 `Flyway.configure()`를 부르면 `:app-bootstrap:architectureTest` 실패 | persistence-jpa 선택 + 배포 도구로 마이그레이션하거나 자기 stream을 둔 서비스 | | 16 | 자기 성능 lane(`performance()`)에서 `performance.assertions.enabled`를 `false`로 두는 `systemProperty` 줄을 지우고, 그 속성을 읽어 상한 단언을 건너뛰던 테스트는 항상 단언하게 고친다. 성능 lane의 `@Disabled`·assumption skip을 없앤다(B-43) | `performanceCheck`가 테스트 전에 실패(`its test JVM would get performance.assertions.enabled=false`)하거나 skip 때문에 실패(`forbids skipped tests`) | 자기 성능 lane이 있는 서비스 | +| 17 | 자기 `docs/registries/error-codes.yaml` 행에서 `log_level:` 줄을 지운다(B-44) | `mainCheck`의 `:app-bootstrap:documentContractTest`가 실패(`docs/registries/error-codes.yaml rows with a log_level; the code decides the level, not the registry`) | `error-codes.yaml`에 자기 행을 더한 서비스 | ### 되돌릴 수 없는 것 @@ -111,6 +112,7 @@ | B-40 | 테스트 코드 정적 분석 `testQualityCheck`: SpotBugs·FindSecBugs를 main 밖 모든 source set(test, testFixtures, integrationTest, systemTest 등)에 돌린다. 테스트용 제외 목록은 `config/spotbugs/exclude-test.xml`(보안 범주·내부 상태 노출·생성자 예외·반환값 null 역참조·아키텍처 위반 fixture). 분석 classpath가 그 source set의 runtime classpath로 넓어졌고, 분석이 불완전하면(빠진 클래스) 실패한다. main 빌드는 `mainCheck`(`qualificationCheck`), optional 빌드는 `ci` | 자기 테스트 코드의 SpotBugs 발견(예: `CountDownLatch.await` 반환값 무시, 공유 변수 비원자 쓰기, 닫지 않은 `Statement`)이 main 단계를 막는다. 테스트 classpath에 없는 타입을 참조하면 `SpotBugs analysis incomplete` | 고치거나, 클래스·메서드로 좁힌 Match를 이유와 함께 `exclude-test.xml`에 더한다. 빠진 타입은 그 테스트 suite 의존성에 넣는다 | `2678955c` · `src/build-logic/.../quality/QualityConventionsPlugin.java`, `src/config/spotbugs/exclude-test.xml`, `src/build.gradle` | | B-42 | shared-contract 패키지 규칙 `SHARED_CONTRACT_CONTAINS_ONLY_OPERATIONAL_CONTRACT_PACKAGES`가 실제로 검사한다. 대상은 `dev.caskeleton.shared..`뿐이고, 허용은 목록의 패키지(`concurrency digest error metrics observability ratelimit request response retry runtime security tracing`)와 그 아래, 뿌리 패키지에는 `package-info`만이다. 전에는 뿌리를 허용 목록에 넣고 접두어로 비교해서 모듈 안은 아무것도 잡지 못했고, 다른 leaf의 `..shared..` 패키지를 잡았다 | `dev.caskeleton.shared`에 목록에 없는 패키지나 뿌리 클래스를 둔 파생 서비스는 architectureTest 실패. 다른 leaf의 `shared` 패키지는 더는 걸리지 않는다 | 업무 개념이면 그것을 소유하는 모듈로 옮긴다. 운영 계약이면 `ForbiddenApiArchitectureTest.SHARED_CONTRACT_PACKAGES`와 shared-contract CLAUDE.md 「Responsibility」에 함께 더한다 | r10 · `src/app-bootstrap/src/architectureTest/.../ForbiddenApiArchitectureTest.java`, `SharedContractPackageRuleTest.java` | | B-43 | 성능 lane 단언 상시화: `performance()` lane은 convention이 테스트 JVM에 `performance.assertions.enabled=true`를 넣는다. 빌드가 `-P`·`GRADLE_OPTS`(`-Dorg.gradle.project.…`)로 `true` 아닌 값을 주거나, lane `systemProperty`·`jvmArgs`(`-D…`)·task 설정이 테스트 JVM 값을 `true` 아닌 값으로 덮으면 테스트 전에 실패한다. 성능 lane은 `rejectSkipped` 없이도 skip된 테스트가 있으면 실패한다. httpclient·Mongo leaf의 속성 선언과 `integration-main.yml` `performance-check`·`release.yml` `httpclient-release-gate`의 `GRADLE_OPTS` 줄을 지웠다. 측정만 하는 모드는 만들지 않았다(JMH가 그 용도) | `performanceCheck`·`::performanceTestLaneCheck`가 `is a performance lane, and this build sets performance.assertions.enabled=false`, `its test JVM would get performance.assertions.enabled=false`, `forbids skipped tests … a skipped test is a bound nobody measured` 중 하나로 실패 | `-Pperformance.assertions.enabled=false`를 지운다. 자기 lane의 그 `systemProperty`·`jvmArgs` 줄을 지우고, 그 속성을 읽던 테스트는 항상 단언하게 고친다. 성능 lane의 skip은 없애거나 그 테스트를 다른 lane으로 옮긴다. `GRADLE_OPTS=-Dorg.gradle.project.performance.assertions.enabled=true`·`-P…=true`는 받아 주므로 그대로 둬도 된다 | B4(2026-11-06) · `src/build-logic/.../strictlane/StrictTestLanePlugin.java`, `.../strictlane/StrictTestLaneConventionTest.java`(test), `docs/testing/TESTING_STRATEGY.md` 6절 | +| B-44 | `docs/registries/error-codes.yaml`에서 `log_level` 칸을 지웠다. 행에 `log_level`이 있으면 `OperationalErrorRegistryContractTest.noRegistryRowCarriesALogLevel`(태그 `document-contract`, `mainCheck`)이 실패한다. 칸을 읽는 코드는 없었고 값 대부분이 실제 로그 레벨과 달랐다. 레벨은 실패 종류·경로가 정한다(`ServerFailureLog`, 보안 필터 `AuthErrorResponseWriter`) | 자기 행에 `log_level`이 남은 서비스는 `mainCheck` 실패(`… rows with a log_level; the code decides the level, not the registry`와 그 행의 code 목록) | 자기 행에서 `log_level:` 줄을 지운다. 레벨을 바꾸려면 그 실패를 로그로 남기는 코드를 고친다. 자기 설계서가 "행마다 `log_level`을 채운다"고 적었으면 그 문장도 지운다 | 설계 메모 2026-11-06 7절 결정 1·1-b · `docs/registries/error-codes.yaml` 머리말, `src/app-bootstrap/src/test/.../contract/OperationalErrorRegistryContractTest.java` | ### 3.5 모듈 registry·새 leaf diff --git a/docs/work/reference/decisions.md b/docs/work/reference/decisions.md index 227e493b..c5ec382a 100644 --- a/docs/work/reference/decisions.md +++ b/docs/work/reference/decisions.md @@ -81,6 +81,7 @@ | GraphQL DataLoader 키 실패 | 등록된 `ApiErrorCode`만 노출 | 소유자 | 결정 25 | | Draft-12 offset 불일치 | problem 문서는 프로토콜 예외로 유지 | 소유자 | 결정 12 | | 알림 category 생략 | 거부(400), 판정은 유스케이스 | 소유자 | 결정 13 | +| 오류 코드 로그 레벨 | `error-codes.yaml`에 `log_level` 칸을 두지 않는다. 레벨은 실패 종류·경로가 정한다(`ServerFailureLog`, 보안 필터 `AuthErrorResponseWriter`). 칸이 다시 생기면 `OperationalErrorRegistryContractTest`가 실패한다. 보안 필터는 5xx(`AUTH_JWKS_UNAVAILABLE`·`INTERNAL_AUTH_MISCONFIGURATION`)를 ERROR, 4xx를 WARN으로 남긴다. 401 서명·issuer·audience 불일치는 WARN | 소유자 | 2026-11-06, `docs/superpowers/specs/2026-11-06-error-code-log-level-design.md` 10절 | ### 2.4 멱등성 diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/OperationalErrorRegistryContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/OperationalErrorRegistryContractTest.java index 5f561936..2e043b83 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/OperationalErrorRegistryContractTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/OperationalErrorRegistryContractTest.java @@ -98,6 +98,25 @@ class OperationalErrorRegistryContractTest { assertThat(actual).isNotEmpty().isEqualTo(expected); } + /** + * The log level is not a registry column. The failure's kind and path decide it — {@code + * ServerFailureLog} on every transport, {@code AuthErrorResponseWriter} in the security filter — + * not the code, so a per-row value can only drift from what is logged, as the column that was + * removed did (docs/superpowers/specs/2026-11-06-error-code-log-level-design.md). + */ + @Test + void noRegistryRowCarriesALogLevel() { + List rowsWithALogLevel = + registryRows().stream() + .filter(row -> row.containsKey("log_level")) + .map(row -> String.valueOf(row.get("code"))) + .toList(); + + assertThat(rowsWithALogLevel) + .as("%s rows with a log_level; the code decides the level, not the registry", REGISTRY) + .isEmpty(); + } + @SuppressWarnings("unchecked") private static List> registryRows() { Object loaded = new Yaml(new SafeConstructor(new LoaderOptions())).load(read(REGISTRY)); From 200019aa5cc3914cfd3ee10b80359c755c8571f7 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 6 Nov 2026 22:25:45 +0900 Subject: [PATCH 14/71] =?UTF-8?q?fix(idempotency)!:=20=EB=91=90=20?= =?UTF-8?q?=EB=A9=B1=EB=93=B1=20=EC=A0=80=EC=9E=A5=EC=86=8C=EA=B0=80=20ope?= =?UTF-8?q?ration=20id=C2=B7release=C2=B7inspect=EC=97=90=20=EA=B0=99?= =?UTF-8?q?=EA=B2=8C=20=EB=8B=B5=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 같은 호출에 Redis와 PostgreSQL 저장소(와 in-memory fake)가 다르게 답한다. - owner token이 같아도 호출이 claim과 다른 operation id를 대면 Redis는 다섯 전이(start·renew·complete·fail·release)를 OPERATION_CONFLICT로 거절하고 PostgreSQL·fake는 적용한다. PostgreSQL은 CAS에 핸들의 claim operation만 쓰고 호출의 id는 last_transition_operation_id에 적기만 한다. - PostgreSQL complete 재생은 operation id만 보고 owner를 보지 않아, 같은 id를 쓴 다른 attempt의 늦은 complete를 이미 적용된 완료로 확인한다. Redis는 NOT_OWNER. - fake의 claim·inspect는 같은 token·다른 operation에 OwnerOperationConflict ·OPERATION_CONFLICT를 내지 않는다. PostgreSQL·fake의 inspect는 완료된 기록이면 그 응답을 재생하고 Redis는 OPERATION_CONFLICT. - 기록이 없는 release에 Redis는 ALREADY_RELEASED_SAME_OPERATION, PostgreSQL ·fake는 ABSENT. Redis release는 revision을 보지 않아, 같은 attempt가 claim을 넘겨받기 전 핸들로 지금의 claim을 지운다. 방법: 소유자 결정 (a)로 PostgreSQL·fake를 Redis에 맞춘다. owner token이 같고 호출 id가 기록의 claim id와 다르면 다섯 전이 모두 OPERATION_CONFLICT, 기록은 그대로. 나머지 셋은 "거절이 안전한 쪽, 운영 호출자 경로가 안 바뀌는 쪽"으로 정했다. - complete 재생은 같은 owner token에만 확인한다(Redis에 맞춤). - fake claim은 진행 중 기록에 OwnerOperationConflict, inspect는 같은 token· 다른 operation이면 상태와 상관없이 OPERATION_CONFLICT. PostgreSQL inspect도 완료 재생보다 이 검사를 먼저 한다. - 기록 없는 release는 셋 다 ABSENT. Redis adapter가 ABSENT를 그대로 넘기고 RELEASE 스크립트와 command fake가 핸들 revision을 본다. release한 기록을 지울지 남길지는 저장소 선택이라 release 재시도는 ABSENT(Redis·fake)와 ALREADY_RELEASED_SAME_OPERATION(PostgreSQL)으로 갈리는 것을 계약이 허용한다. 버린 대안: Redis를 PostgreSQL에 맞추기(Redis에는 전이 id를 둘 필드가 없어 인자가 죽는다), PostgreSQL release를 삭제로 바꾸기(release 뒤 기록 모양은 계약이 저장소 선택으로 정해 두었다), 기록 없는 release를 셋 다 ALREADY_RELEASED로(찾지 못한 것을 성공으로 확인한다 — JPA 설계 22.2와 반대). 공유 계약 IdempotencyStoreContract에 12케이스를 더했다. 포트·결과 enum Javadoc, persistence-jpa·cache-redis README, TESTING_STRATEGY, application-core CLAUDE.md, 결정 색인, 업그레이드 안내 5절을 같이 고쳤다. 위험·한계: 템플릿의 호출자(IdempotencyExecutor)는 늘 claim의 id를 넘기고 release를 부르지 않아 HTTP 동작은 같다. store 포트를 직접 부르며 전이마다 다른 id를 넘기던 코드는 OPERATION_CONFLICT를 받는다. PostgreSQL 통합 테스트가 그렇게 쓰고 있어 claim의 id로 바꿨다. last_transition_operation_id 열은 이제 늘 claim_operation_id와 같다(마이그레이션은 건드리지 않음). 같은 token의 넘겨받기 전 핸들로 이미 끝난 complete·markFailed를 다시 보내는 경우는 저장소마다 답이 다르다(범위 밖, 보고에 적음). 검증: desktop, 공유 잠금, 기준 06f520e6. - RED(기준 커밋 + 계약만): in-memory fake 계약 49 중 8 실패, Redis command fake 2, 실 Redis(redisContainerContractTest) 2, 실 PostgreSQL (jpaPlatformContractTest) 7 — 실패 메시지가 위 차이 그대로("expected: OPERATION_CONFLICT but was: STARTED", "expected: ABSENT but was: ALREADY_RELEASED_SAME_OPERATION" 등). - GREEN(이 커밋과 같은 트리): 네 leaf check(application-core 412·skip 19 시간 케이스, persistence-jpa 664, cache-redis 215, redis-runtime 65), 네 leaf testQualityCheck, jpaPlatformContractTest 419, postgresqlIdempotencyIntegrationTest 10, redisContainerContractTest 90, app-bootstrap integrationTest 10, sample integrationTest 63, documentContractTest 65, architectureTest 228, composition:idempotency check 32 — 모두 rc=0, 실패·skip 0(fake 시간 케이스 19 제외). - scripts/check-work-docs.py, --links docs, git diff --check 통과. Refs: docs/reviews/2026-11-03-rereview/round6/02-idempotency-outbound.md Declined to judge BREAKING CHANGE: 멱등 store 포트를 직접 부르는 코드는 전이마다 claim의 operation id(IdempotencyOwner.claimOperationId())를 넘겨야 한다. 다른 id는 OPERATION_CONFLICT다. Redis release는 기록이 없으면 ABSENT를 돌려준다. 직접 구현한 store는 IdempotencyStoreContract의 새 케이스를 통과해야 한다. --- docs/testing/TESTING_STRATEGY.md | 8 +- docs/upgrade/2026-11-maturity-review.md | 1 + docs/work/reference/decisions.md | 4 + src/adapter/outbound/cache-redis/README.md | 9 + .../redis/idempotency/IdempotencyScripts.java | 13 +- .../RedisIdempotencyStoreAdapter.java | 5 +- .../outbound/persistence-jpa/README.md | 9 +- .../PostgreSqlIdempotencyStore.java | 47 +++- .../PostgreSqlIdempotencyIntegrationTest.java | 47 ++-- .../InMemorySemanticRedisCommands.java | 4 + src/application-core/CLAUDE.md | 3 + .../IdempotencyCompleteOutcome.java | 4 + .../idempotency/IdempotencyFailOutcome.java | 5 + .../IdempotencyInspectionOutcome.java | 4 + .../IdempotencyReleaseOutcome.java | 9 + .../idempotency/IdempotencyRenewOutcome.java | 5 +- .../idempotency/IdempotencyStartOutcome.java | 6 +- .../idempotency/IdempotencyStorePort.java | 8 + .../testkit/IdempotencyStoreContract.java | 238 ++++++++++++++++++ .../testkit/InMemoryIdempotencyStore.java | 55 +++- 20 files changed, 437 insertions(+), 47 deletions(-) diff --git a/docs/testing/TESTING_STRATEGY.md b/docs/testing/TESTING_STRATEGY.md index 8f870afa..f95dfa50 100644 --- a/docs/testing/TESTING_STRATEGY.md +++ b/docs/testing/TESTING_STRATEGY.md @@ -252,11 +252,15 @@ source set에서 태그 `jpa-contract`로 `jpaPlatformContractTest` lane이 돌 갖게 고쳤다. `committed()`는 이제 실제로 커밋된 경계만 담는다(바깥이 롤백되면 안쪽도 빠진다). - PostgreSQL 멱등성 store는 (1) 이전 revision의 핸들을 `OPERATION_CONFLICT`로, Redis·fake는 `NOT_OWNER`로 답했다. 핸들의 owner 튜플에는 revision이 들어가므로 `NOT_OWNER`로 맞췄다. - `OPERATION_CONFLICT`는 "같은 operation id가 다른 인자로 이미 적용됨" 한 뜻만 남는다. (2) 실행 + 그때 `OPERATION_CONFLICT`는 "같은 operation id가 다른 인자로 이미 적용됨" 한 뜻만 남겼다. 2026-11-06 소유자 + 결정으로 뜻이 하나 늘었다: owner token이 같아도 호출이 claim과 다른 operation id를 대면 다섯 전이 모두 + `OPERATION_CONFLICT`다(Redis만 거절하고 PostgreSQL·fake는 적용했다). (2) 실행 전(CLAIMED) claim의 renew를 받아 줬고 Redis·fake는 거부했다. renew는 실행 중인 작업의 lease만 늘리도록 PostgreSQL을 맞췄다(호출자 없음 — 템플릿 안 동작 변화 없음). (3) release 뒤의 다음 claim을 `TakenOverClaimed`(attempt 2)로, Redis는 `Acquired`로 답한다. executor는 둘을 같게 - 처리하므로 계약은 "다음 claim이 scope를 가진다"만 요구한다. + 처리하므로 계약은 "다음 claim이 scope를 가진다"만 요구한다. 같은 이유로 release 재시도는 PostgreSQL이 + `ALREADY_RELEASED_SAME_OPERATION`, Redis·fake가 `ABSENT`다. 기록이 없으면 셋 다 `ABSENT`다(Redis는 전에 + `ALREADY_RELEASED_SAME_OPERATION`으로 답해 확인할 수 없는 해제를 확인했다, 2026-11-06). - `OutboxAppendContract`는 static helper 두 개였고 JPA readiness 테스트만 불렀다. 추상 계약으로 바꿔 readiness 테스트가 상속한다(같은 두 케이스 + 트랜잭션 밖·읽기 전용·중복 eventId). 실 PostgreSQL에서 `inRead` 안의 append가 예외 없이 사라지는 것을 찾았다(실측: 예외 없음, 행 없음) — JPA 트랜잭션 diff --git a/docs/upgrade/2026-11-maturity-review.md b/docs/upgrade/2026-11-maturity-review.md index ef50f035..6802551e 100644 --- a/docs/upgrade/2026-11-maturity-review.md +++ b/docs/upgrade/2026-11-maturity-review.md @@ -238,6 +238,7 @@ V21 실패의 분류는 `docs/runbooks/migration-failed.md` "Classify the failur | 멱등성(lease가 지난 실행) | lease가 지난 `EXECUTING` 기록을 claim이 만나면 기록을 바꾸지 않고 500 `IDEMPOTENCY_RECOVERY_REQUIRED`로 답한다. 그 실행의 주인이 늦게 부른 `complete`·`markFailed`는 기록된다. 전에는 두 저장소 모두 기록을 `ABANDONED`로 바꿔(PostgreSQL은 `last_transition_kind` `EXPIRED_EXECUTION`) 늦은 결과를 거절했고 첫 요청도 500이었다. 이미 끝난 lease의 `renew`는 두 저장소 모두 거절한다(Redis는 전에 받아들였다). 남의 lease 지난 실행을 `inspect`하면 `ABANDONED`(전에는 `IN_PROGRESS_OTHER`) | 30s를 넘는 정상 요청이 이제 결과를 남기고 정상 응답을 받는다. 같은 키 재전송은 500을 받은 뒤 재생을 받을 수 있다. 직접 구현한 store는 `IdempotencyStoreContract`의 바뀐 시간 케이스로 확인한다. 운영자는 `EXECUTING` 기록을 지우지 않는다 — 살아 있는 실행의 늦은 결과가 기록을 못 찾아(`ABSENT`) 사라진다(`docs/runbooks/idempotency-unavailable.md`) | `70fb80bf`(2026-11-04 소유자 결정) · `src/application-core/src/testFixtures/.../IdempotencyStoreContract.java`, `src/adapter/outbound/cache-redis/.../idempotency/IdempotencyScripts.java`, `src/adapter/outbound/persistence-jpa/.../postgresql/PostgreSqlIdempotencyStore.java` | | 멱등성(lease가 끝난 시작, r9) | lease가 지난 `CLAIMED`는 주인도 시작할 수 없다(`LEASE_EXPIRED`). executor는 작업을 돌리지 않고 503 `IDEMPOTENCY_UNAVAILABLE`(실행 전 거부, 메시지 `the claim's processing lease ran out before the action started`)로 답하고, 다음 같은 키 요청이 그 claim을 넘겨받아 실행한다. 전에는 Redis가 시작해 작업을 돌렸고 그동안 다른 요청은 lease가 지난 실행으로 500을 받았다. PostgreSQL은 `NOT_OWNER`로 거절해 500 `IDEMPOTENCY_RECOVERY_REQUIRED`였다. | claim과 시작 사이가 lease(기본 30s)보다 길었던 드문 요청이 500 대신 503(같은 키 재전송)을 받는다. 클라이언트는 `error.code`로 이미 가르므로 바꿀 것이 없다. 운영자는 이 503에서 저장소 장애를 찾지 않는다(runbook) | r9(재리뷰 README 15 남음, RR5-01-02·03) · `IdempotencyExecutor.java`, `src/adapter/outbound/cache-redis/.../idempotency/IdempotencyScripts.java`, `src/adapter/outbound/persistence-jpa/.../postgresql/PostgreSqlIdempotencyStore.java` | | 멱등성(같은 attempt의 재시도, r10) | lease가 지나 시작을 거절당한 claim과 재시도 가능 실패 기록은 같은 attempt로 다시 claim해도 넘겨받는다(`TakenOverClaimed`, attempt+1). 전에는 두 저장소가 그 claim을 재생해(`ReplayedAcquire`) 시작이 다시 거절되거나(503, 기록이 사라질 때까지) 시작할 수 없는 기록이라 500 `IDEMPOTENCY_RECOVERY_REQUIRED`였다. 효과 불명으로 포기한 기록은 같은 attempt에도 `RecoveryRequired`(PostgreSQL은 전에 `ReplayedAcquire`). Redis는 이미 실행 중인 기록에 같은 attempt의 다른 핸들(넘겨받기 전 핸들, 재생받은 현재 핸들)로 온 시작을 `ALREADY_STARTED_SAME_OPERATION`으로 확인하지 않는다 — 전에는 executor가 작업을 한 번 더 돌렸다(PostgreSQL은 전부터 거절). in-memory fake는 재시도 가능 실패 기록에 다른 요청 본문이 오면 넘겨주지 않고 `FingerprintMismatch` | attempt를 재시도 사이에 들고 있다가 503 뒤 같은 attempt로 다시 부르는 호출자(재시도 래퍼, 메시지 소비자)가 이제 실행된다. 요청마다 새 attempt를 만드는 호출자(템플릿의 HTTP 경로)는 바뀌는 것이 없다. 같은 attempt를 두 호출이 동시에 쓰는 것은 여전히 가려내지 못한다 — 재시도는 앞 호출이 돌아온 뒤에. 직접 구현한 store는 `IdempotencyStoreContract`의 새 케이스로 확인한다 | r10(라운드6 RR6-02-01) · `src/adapter/outbound/cache-redis/.../idempotency/IdempotencyScripts.java`, `src/adapter/outbound/persistence-jpa/.../postgresql/PostgreSqlIdempotencyStore.java`, `src/application-core/src/testFixtures/.../IdempotencyStoreContract.java`, `InMemoryIdempotencyStore.java` | +| 멱등성(전이의 operation id·release·inspect, 2026-11-06) | owner token이 같아도 호출이 claim과 다른 operation id를 대면 PostgreSQL·in-memory fake도 다섯 전이(start·renew·complete·fail·release)를 `OPERATION_CONFLICT`로 거절하고 기록을 바꾸지 않는다(전에는 적용했다. Redis는 전부터 거절). in-memory fake의 claim은 같은 token·다른 operation에 `OwnerOperationConflict`(전에는 `InProgress`), inspect는 `OPERATION_CONFLICT`(전에는 `IN_PROGRESS_OTHER`). PostgreSQL·fake의 inspect는 완료된 기록에도 `OPERATION_CONFLICT`(전에는 응답을 재생). PostgreSQL complete는 같은 operation id를 쓴 다른 attempt에 `NOT_OWNER`(전에는 `ALREADY_COMPLETED_SAME_RESULT`). Redis release는 기록이 없으면 `ABSENT`(전에는 `ALREADY_RELEASED_SAME_OPERATION`)이고 핸들 revision을 본다: 같은 attempt가 넘겨받기 전 핸들로 release하면 `NOT_OWNER`(전에는 지금의 claim을 지웠다) | 템플릿의 호출자(`IdempotencyExecutor`)는 늘 claim의 operation id를 넘기고 release를 부르지 않아 HTTP 동작은 같다. store 포트를 직접 부르며 전이마다 다른 operation id를 넘기던 코드는 이제 `OPERATION_CONFLICT`를 받는다 — `IdempotencyOwner.claimOperationId()`를 넘긴다. Redis release의 `ALREADY_RELEASED_SAME_OPERATION`을 기다리던 코드는 `ABSENT`도 "해제됨"으로 읽는다. 직접 구현한 store는 `IdempotencyStoreContract`의 새 케이스로 확인한다 | 2026-11-06(소유자 결정 "(a)로 진행", 라운드6 02 Declined) · `src/adapter/outbound/persistence-jpa/.../postgresql/PostgreSqlIdempotencyStore.java`, `src/adapter/outbound/cache-redis/.../idempotency/IdempotencyScripts.java`, `RedisIdempotencyStoreAdapter.java`, `src/application-core/src/testFixtures/.../IdempotencyStoreContract.java`, `InMemoryIdempotencyStore.java` | | 빌드 단계(HTTP client) | `httpClientFailureInjectionTest`(Toxiproxy 장애 주입)가 `mainCheck`에서 빠졌다. `integrationCheck`에만 있고, main push·nightly의 `integration-main.yml` `integration-check` job이 돌린다 | main push마다 같은 lane이 `main-check`·`integration-check` 두 job에서 두 번 돌던 것이 한 번이 된다. 로컬에서 `mainCheck`만 돌리면 이 lane은 돌지 않는다(`integrationCheck`로 돌린다) | r9 · `src/adapter/outbound/httpclient/build.gradle` | | 서버 로그(GraphQL·gRPC·STOMP) | carrier로 답한 실패를 web과 같은 줄(shared-contract `ServerFailureLog`)로 ERROR에 남긴다: persistence 실패는 분류만, 5xx carrier는 예외와 함께, 4xx carrier는 남기지 않는다. gRPC는 ` (method=…)`, GraphQL은 ` (executionId=…)`를 붙인다. gRPC는 인식 못 한 실패(`INTERNAL_ERROR`)도 `unhandled failure on …`로 남긴다. 클라이언트가 취소한 호출은 남기지 않고, 서비스가 `CANCELLED` status로 끝낸 살아 있는 호출은 남긴다. raw status는 넘겼든 던졌든 설명을 남기지 않는다(원인 예외가 있으면 그것만 붙인다). `IllegalArgumentException`(`BAD_PARAMETER`)은 web과 같은 WARN 한 줄 `request refused as BAD_PARAMETER by <예외 타입>`(메시지 없음)으로 남긴다. STOMP `@MessageMapping` 실패는 Spring의 `Unhandled exception from message handler method`(예외 전체) 대신 같은 줄로 남는다 | ERROR 로그가 늘어난다(전에는 gRPC가 아무것도 남기지 않았다). GraphQL·gRPC·STOMP는 잘못된 입력마다 WARN 한 줄이 생긴다. STOMP에서 Spring 문구로 경보를 걸었다면 고친다. `IDEMPOTENCY_RECOVERY_REQUIRED`의 scope digest를 모든 전송에서 찾을 수 있다(`docs/runbooks/idempotency-unavailable.md`) | r9 · `src/shared-contract/.../error/ServerFailureLog.java`, `GrpcExceptionHandlingInterceptor.java`, `GraphQlWireErrorMapper.java`, `StompHandlerFailureLog.java` | | sample-portfolio | 익명 쓰기 401, 포스터 제목 대소문자 무시 유일(409 `POSTER_ALREADY_EXISTS`), 관리자도 남의 work log 수정 불가, 샘플 이벤트 tenant `global` | sample을 남긴 서비스만 | `34565130`, `1400dc15` | diff --git a/docs/work/reference/decisions.md b/docs/work/reference/decisions.md index 227e493b..30cc6ac2 100644 --- a/docs/work/reference/decisions.md +++ b/docs/work/reference/decisions.md @@ -94,6 +94,10 @@ | 보존 기간 관계 | `failure-retention < replay-ttl`이면 기동 실패 | 소유자 | `1103` 15절 ③ | | 같은 attempt 재claim | lease 지난 `CLAIMED`·`FAILED_RETRYABLE`을 넘겨받는다. 같은 attempt를 두 호출이 동시에 쓰는 것은 호출자 계약 | 기본값 | `1103` 17절 r10-02 | | 다른 핸들의 시작 답 | PostgreSQL도 Redis와 같게 `NOT_OWNER`/`NOT_CLAIMED`로 답한다 | 기본값 | `1103` 17절 r10-02 | +| 전이의 operation id | owner token이 같아도 호출의 operation id가 기록된 claim의 operation id와 다르면 다섯 전이(start·renew·complete·fail·release) 모두 `OPERATION_CONFLICT`로 거절하고 기록은 그대로 둔다. PostgreSQL·in-memory fake를 Redis에 맞췄다. 그래서 `OPERATION_CONFLICT`는 "claim과 다른 id"와 "같은 id·다른 인자" 두 뜻이다 | 소유자(2026-11-06) | 2026-11-06 총괄 세션 전달(소유자 원문 "(a)로 진행"), `IdempotencyStoreContract` | +| 같은 token·다른 operation의 claim·inspect | claim은 진행 중인 기록에 `OwnerOperationConflict`, inspect는 상태와 상관없이(완료된 기록도) `OPERATION_CONFLICT`. 거절이 안전한 쪽을 골랐다 | 기본값(2026-11-06) | 위 결정과 같은 전달의 판단 원칙, `IdempotencyStoreContract` | +| complete 재생 판정 | 완료 확인은 같은 owner token에만 준다. 같은 operation id를 쓴 다른 attempt의 늦은 complete는 `NOT_OWNER` | 기본값(2026-11-06) | Redis TRANSITION에 맞춤, `IdempotencyStoreContract` | +| 기록 없는 release | 저장소 셋 다 `ABSENT`로 답한다(확인할 수 없는 해제를 확인하지 않는다). Redis release도 핸들 revision을 본다. release한 기록을 지울지 남길지는 저장소가 정하므로 release 재시도 답은 `ABSENT`(Redis·fake)와 `ALREADY_RELEASED_SAME_OPERATION`(PostgreSQL)으로 갈린다 | 기본값(2026-11-06) | JPA 설계 22.2 "affected row가 0이면 성공으로 간주하지 않는다", `IdempotencyStoreContract` | | Redis 연결 예산 | 캐시 조건부 쓰기는 멱등성·lease와 다른 연결 예산(SCRIPT lane) | 위임 | `1103` 4절(RR-04-02) | ### 2.5 영속성 diff --git a/src/adapter/outbound/cache-redis/README.md b/src/adapter/outbound/cache-redis/README.md index 7761b8d6..2e8f9902 100644 --- a/src/adapter/outbound/cache-redis/README.md +++ b/src/adapter/outbound/cache-redis/README.md @@ -287,6 +287,15 @@ A lost renewal reply is recognised by what the renewal recorded — the revision the lease it asked for: the same lease is `ALREADY_RENEWED_SAME_OPERATION` with the current handle, a different lease is `OPERATION_CONFLICT`. +Every program compares the operation a call names with the one the record was claimed under, right +after the owner token: another operation is `OPERATION_CONFLICT` and changes nothing. The PostgreSQL +store and the in-memory fake used to apply it; they now answer the same (owner decision 2026-11-06, +`IdempotencyStoreContract`). The release program also checks the handle's revision, as the +transition does: owner token and operation alone let the handle from before the same attempt took +its claim over release the claim it holds now. A release deletes the record, so a release that finds +no record — its own retry, an expired record, one never claimed — is `ABSENT`; it used to be +confirmed as `ALREADY_RELEASED_SAME_OPERATION`, which the store cannot know. + A lease that runs out is taken over only from a claim that never started or an attempt marked retryable — by whoever claims next, the holder's own attempt included: the claim program checks for a takeover before it replays a same-owner claim, so an attempt whose start was refused takes its diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/IdempotencyScripts.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/IdempotencyScripts.java index d68e6b8a..2df2090d 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/IdempotencyScripts.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/IdempotencyScripts.java @@ -267,7 +267,15 @@ public final class IdempotencyScripts { return {'APPLIED', attempt, rev + 1, owner, '', ''} """; - /** Release before execution: only from CLAIMED, and only by the owner that holds it. */ + /** + * Release before execution: only from CLAIMED, and only by the owner that holds it at the + * revision its handle carries. + * + *

The release deletes the record, so a retry finds nothing and is {@code ABSENT}, as is a + * release whose record expired. The revision is checked as in {@link #TRANSITION}: the owner + * token and operation alone let the handle from before the same attempt took its claim over + * release the claim it holds now ({@code IdempotencyStoreContract}). + */ private static final String RELEASE = """ local state = redis.call('HGET', KEYS[1], 'state') @@ -284,6 +292,9 @@ public final class IdempotencyScripts { if op ~= ARGV[3] then return {'OPERATION_CONFLICT', attempt, rev, owner, '', ''} end + if rev ~= tonumber(ARGV[2]) then + return {'NOT_OWNER', attempt, rev, owner, '', ''} + end if state ~= 'CLAIMED' then return {'WRONG_STATE', attempt, rev, owner, state, ''} end diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreAdapter.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreAdapter.java index 7329ae62..c1890ffd 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreAdapter.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreAdapter.java @@ -320,7 +320,10 @@ public final class RedisIdempotencyStoreAdapter implements IdempotencyStorePort operationId.value()))); return switch (reply.status()) { case APPLIED -> IdempotencyReleaseOutcome.RELEASED_BEFORE_EXECUTION; - case ABSENT -> IdempotencyReleaseOutcome.ALREADY_RELEASED_SAME_OPERATION; + // The release deletes the record, so nothing tells this release's retry from a record + // that expired or was never there. It was confirmed as the release already applied; + // the PostgreSQL store answers a missing record ABSENT (IdempotencyStoreContract). + case ABSENT -> IdempotencyReleaseOutcome.ABSENT; case NOT_OWNER -> IdempotencyReleaseOutcome.NOT_OWNER; case OPERATION_CONFLICT -> IdempotencyReleaseOutcome.OPERATION_CONFLICT; case WRONG_STATE -> IdempotencyReleaseOutcome.EXECUTION_ALREADY_STARTED; diff --git a/src/adapter/outbound/persistence-jpa/README.md b/src/adapter/outbound/persistence-jpa/README.md index e3334e9b..a13880a2 100644 --- a/src/adapter/outbound/persistence-jpa/README.md +++ b/src/adapter/outbound/persistence-jpa/README.md @@ -437,8 +437,13 @@ RR6-02-01). raw client key는 저장하지 않고 versioned HMAC scope digest만 Redis store·in-memory fake와 같은 계약(`IdempotencyStoreContract`)을 실 PostgreSQL에서 통과한다 (`PostgreSqlIdempotencyStoreContractTest`, `jpaPlatformContractTest`). 그 계약에 맞춰 두 가지를 -정했다(review 2026-11-01 01-05). 이전 revision의 핸들은 owner 튜플이 다르므로 `NOT_OWNER`다 -(`OPERATION_CONFLICT`는 같은 operation id가 다른 인자로 이미 적용된 경우만). 시작은 핸들 말고 인자가 없어서, +정했다(review 2026-11-01 01-05). 이전 revision의 핸들은 owner 튜플이 다르므로 `NOT_OWNER`다. +`OPERATION_CONFLICT`는 둘이다. 하나는 owner token이 같은데 호출이 claim과 다른 operation id를 댄 경우로, 다섯 +전이(start·renew·complete·fail·release) 모두 거절하고 행을 바꾸지 않는다. 같은 token·다른 operation의 inspect도 +상태와 상관없이(완료된 행도) `OPERATION_CONFLICT`다(2026-11-06 소유자 결정 — 전에는 CAS가 핸들의 claim +operation만 보고 호출의 id는 `last_transition_operation_id`에 적기만 해서 적용했다). 다른 하나는 같은 operation +id가 다른 인자로 이미 적용된 경우다. complete 재생은 같은 owner token에만 확인한다 — 같은 operation id를 쓴 다른 +attempt의 늦은 complete는 `NOT_OWNER`다(전에는 operation id만 보고 `ALREADY_COMPLETED_SAME_RESULT`). 시작은 핸들 말고 인자가 없어서, 이미 기록된 시작과 digest가 다르면 다른 핸들이다 — 넘겨받기 전 핸들은 `NOT_OWNER`, 재생받은 현재 핸들은 `NOT_CLAIMED`(라운드6 RR6-02-01, 전에는 `OPERATION_CONFLICT`). renew는 `EXECUTING`의 lease만 늘리고, 시작 전 `CLAIMED`는 `NOT_IN_PROGRESS`다. diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/PostgreSqlIdempotencyStore.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/PostgreSqlIdempotencyStore.java index 54a99f0b..0b83e9c5 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/PostgreSqlIdempotencyStore.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/PostgreSqlIdempotencyStore.java @@ -183,6 +183,9 @@ public final class PostgreSqlIdempotencyStore implements IdempotencyStorePort { if (row == null) { return startResult(IdempotencyStartOutcome.ABSENT, null); } + if (namesAnotherOperation(row, owner, operationId)) { + return startResult(IdempotencyStartOutcome.OPERATION_CONFLICT, null); + } String startDigest = transitionDigest("START", operationId, owner); // A start carries no argument but the handle, so a recorded start with another digest was // applied from another handle of the same operation — one from before a takeover by the same @@ -220,6 +223,9 @@ public final class PostgreSqlIdempotencyStore implements IdempotencyStorePort { if (row == null) { return renewResult(IdempotencyRenewOutcome.ABSENT, null); } + if (namesAnotherOperation(row, owner, operationId)) { + return renewResult(IdempotencyRenewOutcome.OPERATION_CONFLICT, null); + } // The lease TTL is part of what a renewal decided, so it is part of the digest. Without it, a // retry asking for a different lease was confirmed as the renewal already applied, and the // caller went on believing it held the record for longer than the row says it does. @@ -267,9 +273,16 @@ public final class PostgreSqlIdempotencyStore implements IdempotencyStorePort { if (row == null) { return IdempotencyCompleteOutcome.ABSENT; } + if (namesAnotherOperation(row, owner, operationId)) { + return IdempotencyCompleteOutcome.OPERATION_CONFLICT; + } String responseDigest = sha256(response.payload()); + // A completion is reported back to its own owner only. The operation id alone confirmed the + // late completion of another attempt that carried the same id, which the Redis store refuses + // as NOT_OWNER (IdempotencyStoreContract). if (row.state() == IdempotencyState.COMPLETED && "COMPLETE".equals(row.lastTransitionKind()) + && row.ownerToken().equals(owner.ownerToken()) && operationId.value().equals(row.lastTransitionOperationId())) { return responseDigest.equals(row.responseDigest()) ? IdempotencyCompleteOutcome.ALREADY_COMPLETED_SAME_RESULT @@ -315,6 +328,9 @@ public final class PostgreSqlIdempotencyStore implements IdempotencyStorePort { if (row == null) { return IdempotencyFailOutcome.ABSENT; } + if (namesAnotherOperation(row, owner, operationId)) { + return IdempotencyFailOutcome.OPERATION_CONFLICT; + } String transitionKind = disposition == IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE ? "FAIL_RETRYABLE" @@ -372,6 +388,9 @@ public final class PostgreSqlIdempotencyStore implements IdempotencyStorePort { if (row == null) { return IdempotencyReleaseOutcome.ABSENT; } + if (namesAnotherOperation(row, owner, operationId)) { + return IdempotencyReleaseOutcome.OPERATION_CONFLICT; + } String releaseDigest = transitionDigest("RELEASE", operationId, owner); switch (replayVerdict(row, "RELEASE", operationId, releaseDigest)) { case SAME_ARGUMENTS -> { @@ -411,6 +430,11 @@ public final class PostgreSqlIdempotencyStore implements IdempotencyStorePort { return IdempotencyInspection.outcome(IdempotencyInspectionOutcome.FINGERPRINT_MISMATCH); } boolean sameAttempt = sameClaimAttempt(row, request.claimAttempt()); + // The owner token under another operation is refused in every state, a completed record + // included, as the Redis store refuses it; the response used to be replayed to it here. + if (row.ownerToken().equals(request.claimAttempt().ownerToken()) && !sameAttempt) { + return IdempotencyInspection.outcome(IdempotencyInspectionOutcome.OPERATION_CONFLICT); + } if (row.state() == IdempotencyState.COMPLETED && row.responsePayload() != null) { return new IdempotencyInspection( IdempotencyInspectionOutcome.COMPLETED_REPLAY, @@ -425,9 +449,6 @@ public final class PostgreSqlIdempotencyStore implements IdempotencyStorePort { if (sameAttempt && row.state() == IdempotencyState.EXECUTING) { return inspectionWithOwner(IdempotencyInspectionOutcome.EXECUTING_SAME_OPERATION, row); } - if (row.ownerToken().equals(request.claimAttempt().ownerToken()) && !sameAttempt) { - return IdempotencyInspection.outcome(IdempotencyInspectionOutcome.OPERATION_CONFLICT); - } // Somebody else's execution whose lease ran out is reported as a claim would answer it. The // database's clock decides, as it does for the claim; the read takes no lock, so a lease that // ends between the row and the clock is reported as ended, which is what a claim would see. @@ -452,9 +473,25 @@ public final class PostgreSqlIdempotencyStore implements IdempotencyStorePort { return new IdempotencyClaimOutcome.TakenOverClaimed(owner(reset), reset.processingLeaseUntil()); } + /** + * Whether the holder of the record names an operation other than the one it was claimed under. + * + *

Every transition names the claim's operation, and a holder naming another one is refused + * before anything else is read: nothing changes, as in the Redis store and the in-memory fake. It + * used to be applied — the owner tuple took the claim's operation from the handle, and the named + * one was only written to {@code last_transition_operation_id} (owner decision 2026-11-06, {@code + * IdempotencyStoreContract}). Another owner token is still {@code NOT_OWNER}. + */ + private static boolean namesAnotherOperation( + IdempotencyRecordRow row, IdempotencyOwner owner, OperationId operationId) { + return row.ownerToken().equals(owner.ownerToken()) + && !row.claimOperationId().equals(operationId.value()); + } + // A handle at an older revision is a stale owner tuple, so it is NOT_OWNER — what the Redis store - // and the in-memory fake answer (IdempotencyStoreContract). OPERATION_CONFLICT keeps its one - // meaning: the same operation id already applied this transition with different arguments. + // and the in-memory fake answer (IdempotencyStoreContract). OPERATION_CONFLICT means the holder + // named another operation than the claim's (namesAnotherOperation), or the same operation id + // already applied this transition with different arguments. private IdempotencyStartOutcome classifyStartMismatch( IdempotencyRecordRow row, IdempotencyOwner owner) { if (!sameOwnerIdentity(row, owner)) { diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlIdempotencyIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlIdempotencyIntegrationTest.java index c231797e..646191ce 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlIdempotencyIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlIdempotencyIntegrationTest.java @@ -91,8 +91,7 @@ class PostgreSqlIdempotencyIntegrationTest { ignored -> { IdempotencyOwner owner = ((IdempotencyClaimOutcome.Acquired) store.claim(request)).owner(); - owner = - store.markExecutionStarted(owner, new OperationId("start-1")).owner().orElseThrow(); + owner = store.markExecutionStarted(owner, owner.claimOperationId()).owner().orElseThrow(); jdbc.update( "insert into idempotency_business_probe(scope_hash, mutation_count) values (?, 1)", SCOPE.digest()); @@ -102,7 +101,7 @@ class PostgreSqlIdempotencyIntegrationTest { owner, new StoredResponse("{\"workLogId\":\"42\"}"), Duration.ofHours(24), - new OperationId("complete-1"))) + owner.claimOperationId())) .isEqualTo(IdempotencyCompleteOutcome.COMPLETED); }); @@ -157,7 +156,7 @@ class PostgreSqlIdempotencyIntegrationTest { transactions .execute( ignored -> - store.markExecutionStarted(staleOwner, new OperationId("stale-start"))) + store.markExecutionStarted(staleOwner, staleOwner.claimOperationId())) .outcome()) .isEqualTo(IdempotencyStartOutcome.NOT_OWNER); } @@ -173,7 +172,7 @@ class PostgreSqlIdempotencyIntegrationTest { store.claim(request(original, Duration.ofMillis(25)))) .owner(); return store - .markExecutionStarted(owner, new OperationId("start-executing")) + .markExecutionStarted(owner, owner.claimOperationId()) .owner() .orElseThrow(); }); @@ -217,7 +216,7 @@ class PostgreSqlIdempotencyIntegrationTest { ((IdempotencyClaimOutcome.Acquired) store.claim(firstRequest)).owner(); owner = store - .markExecutionStarted(owner, new OperationId("start-first")) + .markExecutionStarted(owner, owner.claimOperationId()) .owner() .orElseThrow(); jdbc.update( @@ -229,7 +228,7 @@ class PostgreSqlIdempotencyIntegrationTest { owner, new StoredResponse("done"), Duration.ofHours(1), - new OperationId("complete-first"))) + owner.claimOperationId())) .isEqualTo(IdempotencyCompleteOutcome.COMPLETED); firstHasCompletedInsideTransaction.countDown(); await(allowFirstCommit); @@ -284,7 +283,7 @@ class PostgreSqlIdempotencyIntegrationTest { ((IdempotencyClaimOutcome.Acquired) store.claim(firstRequest)).owner(); IdempotencyOwner executing = store - .markExecutionStarted(owner, new OperationId("start-slow")) + .markExecutionStarted(owner, owner.claimOperationId()) .owner() .orElseThrow(); firstStarted.countDown(); @@ -293,7 +292,7 @@ class PostgreSqlIdempotencyIntegrationTest { executing, new StoredResponse("slow-but-done"), Duration.ofHours(1), - new OperationId("complete-slow")); + executing.claimOperationId()); }); return null; }); @@ -346,7 +345,7 @@ class PostgreSqlIdempotencyIntegrationTest { ((IdempotencyClaimOutcome.Acquired) store.claim(firstRequest)).owner(); IdempotencyOwner executing = store - .markExecutionStarted(owner, new OperationId("start-fails")) + .markExecutionStarted(owner, owner.claimOperationId()) .owner() .orElseThrow(); firstStarted.countDown(); @@ -357,7 +356,7 @@ class PostgreSqlIdempotencyIntegrationTest { executing, IdempotencyFailureDisposition.EFFECT_UNKNOWN_ABANDONED, Duration.ofHours(1), - new OperationId("fail-unknown")); + executing.claimOperationId()); throw new IllegalStateException("the action failed"); }); return null; @@ -383,7 +382,7 @@ class PostgreSqlIdempotencyIntegrationTest { @Test void aRetriedFailureWithTheSameArgumentsIsConfirmedRatherThanAppliedTwice() { - IdempotencyOwner executing = claimAndStart("claim-fail-replay", "start-fail-replay"); + IdempotencyOwner executing = claimAndStart("claim-fail-replay"); IdempotencyFailOutcome first = transactions.execute( @@ -392,7 +391,7 @@ class PostgreSqlIdempotencyIntegrationTest { executing, IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE, Duration.ofHours(1), - new OperationId("fail-1"))); + executing.claimOperationId())); IdempotencyFailOutcome retry = transactions.execute( ignored -> @@ -400,7 +399,7 @@ class PostgreSqlIdempotencyIntegrationTest { executing, IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE, Duration.ofHours(1), - new OperationId("fail-1"))); + executing.claimOperationId())); assertThat(first).isEqualTo(IdempotencyFailOutcome.MARKED_RETRYABLE); assertThat(retry).isEqualTo(IdempotencyFailOutcome.ALREADY_MARKED_SAME_OPERATION); @@ -408,7 +407,7 @@ class PostgreSqlIdempotencyIntegrationTest { @Test void aFailureRepeatedUnderOneOperationIdWithDifferentRetentionIsAConflict() { - IdempotencyOwner executing = claimAndStart("claim-fail-conflict", "start-fail-conflict"); + IdempotencyOwner executing = claimAndStart("claim-fail-conflict"); transactions.execute( ignored -> @@ -416,7 +415,7 @@ class PostgreSqlIdempotencyIntegrationTest { executing, IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE, Duration.ofHours(1), - new OperationId("fail-2"))); + executing.claimOperationId())); IdempotencyFailOutcome different = transactions.execute( ignored -> @@ -424,7 +423,7 @@ class PostgreSqlIdempotencyIntegrationTest { executing, IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE, Duration.ofHours(9), - new OperationId("fail-2"))); + executing.claimOperationId())); assertThat(different) .as( @@ -443,25 +442,25 @@ class PostgreSqlIdempotencyIntegrationTest { @Test void aRenewalRepeatedUnderOneOperationIdWithADifferentLeaseIsAConflict() { // Started first: only an executing operation's lease is renewed (IdempotencyStoreContract). - IdempotencyOwner executing = claimAndStart("claim-renew-conflict", "start-renew-conflict"); + IdempotencyOwner executing = claimAndStart("claim-renew-conflict"); IdempotencyRenewOutcome first = transactions .execute( ignored -> - store.renew(executing, Duration.ofSeconds(30), new OperationId("renew-1"))) + store.renew(executing, Duration.ofSeconds(30), executing.claimOperationId())) .outcome(); IdempotencyRenewOutcome same = transactions .execute( ignored -> - store.renew(executing, Duration.ofSeconds(30), new OperationId("renew-1"))) + store.renew(executing, Duration.ofSeconds(30), executing.claimOperationId())) .outcome(); IdempotencyRenewOutcome different = transactions .execute( ignored -> - store.renew(executing, Duration.ofMinutes(45), new OperationId("renew-1"))) + store.renew(executing, Duration.ofMinutes(45), executing.claimOperationId())) .outcome(); assertThat(first).isEqualTo(IdempotencyRenewOutcome.RENEWED); @@ -488,10 +487,12 @@ class PostgreSqlIdempotencyIntegrationTest { .owner()); } - private static IdempotencyOwner claimAndStart(String claimOperation, String startOperation) { + // Every transition names the operation its record was claimed under; these tests gave each + // transition an id of its own, which the store now refuses (owner decision 2026-11-06). + private static IdempotencyOwner claimAndStart(String claimOperation) { IdempotencyOwner claimed = claim(claimOperation); return transactions - .execute(ignored -> store.markExecutionStarted(claimed, new OperationId(startOperation))) + .execute(ignored -> store.markExecutionStarted(claimed, claimed.claimOperationId())) .owner() .orElseThrow(); } diff --git a/src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/command/InMemorySemanticRedisCommands.java b/src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/command/InMemorySemanticRedisCommands.java index b27a92ab..f25a5a11 100644 --- a/src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/command/InMemorySemanticRedisCommands.java +++ b/src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/command/InMemorySemanticRedisCommands.java @@ -366,6 +366,7 @@ public final class InMemorySemanticRedisCommands implements SemanticRedisCommand private List idempotencyRelease(String rendered, List arguments) { String ownerToken = text(arguments.get(0)); + long expectedRev = Long.parseLong(text(arguments.get(1))); String operationId = text(arguments.get(2)); String state = field(rendered, "state"); if (state == null) { @@ -380,6 +381,9 @@ public final class InMemorySemanticRedisCommands implements SemanticRedisCommand if (!operationId.equals(field(rendered, "op"))) { return reply("OPERATION_CONFLICT", attempt, rev, owner, "", ""); } + if (rev != expectedRev) { + return reply("NOT_OWNER", attempt, rev, owner, "", ""); + } if (!"CLAIMED".equals(state)) { return reply("WRONG_STATE", attempt, rev, owner, state, ""); } diff --git a/src/application-core/CLAUDE.md b/src/application-core/CLAUDE.md index 366e2dbe..e69b39d1 100644 --- a/src/application-core/CLAUDE.md +++ b/src/application-core/CLAUDE.md @@ -288,6 +288,9 @@ generation; the V1 `IdempotencyScope`/`tryBegin` API is gone. (owner decision 2026-11-04, re-review RR5-01-02·03). A record lives for the lease plus the replay TTL. `IdempotencyStoreContract` holds Redis and PostgreSQL to both on real servers; the in-memory fake models no time, so it runs only the contract's time-free cases (re-review 2026-11-04 RR-01-11, RR-03-11, RR3-03-04). +- Every transition names the operation its record was claimed under (`IdempotencyOwner.claimOperationId()`). + Another one is `OPERATION_CONFLICT` in every store and changes nothing; so is an inspection that + brings the owner token under another operation (owner decision 2026-11-06). The former ArchUnit freeze rule `inbound_port_implementations_do_not_declare_keyed_idempotency` and its fixture were removed when this branch merged. diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyCompleteOutcome.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyCompleteOutcome.java index c325e0eb..4f09a42c 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyCompleteOutcome.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyCompleteOutcome.java @@ -8,6 +8,10 @@ public enum IdempotencyCompleteOutcome { ABSENT, NOT_OWNER, NOT_IN_PROGRESS, + /** + * The call names an operation other than the one the record was claimed under; nothing was + * recorded (owner decision 2026-11-06). + */ OPERATION_CONFLICT, INDETERMINATE, UNAVAILABLE diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyFailOutcome.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyFailOutcome.java index efee562e..9d65912d 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyFailOutcome.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyFailOutcome.java @@ -8,6 +8,11 @@ public enum IdempotencyFailOutcome { ABSENT, NOT_OWNER, NOT_IN_PROGRESS, + /** + * The call names an operation other than the one the record was claimed under (owner decision + * 2026-11-06), or this failure was already recorded with another disposition or retention. + * Nothing changed. + */ OPERATION_CONFLICT, INDETERMINATE, UNAVAILABLE diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyInspectionOutcome.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyInspectionOutcome.java index b8ed05d6..a60b6341 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyInspectionOutcome.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyInspectionOutcome.java @@ -16,6 +16,10 @@ public enum IdempotencyInspectionOutcome { */ ABANDONED, FINGERPRINT_MISMATCH, + /** + * The attempt's owner token holds the record under another operation. It is the answer in every + * state, a completed record included: its response is not replayed to it. + */ OPERATION_CONFLICT, UNAVAILABLE } diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyReleaseOutcome.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyReleaseOutcome.java index 952f8012..fe066580 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyReleaseOutcome.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyReleaseOutcome.java @@ -3,10 +3,19 @@ package dev.caskeleton.application.idempotency; /** Outcomes of releasing a claim only while business execution has not started. */ public enum IdempotencyReleaseOutcome { RELEASED_BEFORE_EXECUTION, + /** This release was already applied: a store that keeps released records recognises it. */ ALREADY_RELEASED_SAME_OPERATION, + /** + * No record exists: it expired, was never there, or was released by a store that deletes what it + * releases — that store cannot tell its own release's retry apart, so it confirms nothing. + */ ABSENT, NOT_OWNER, EXECUTION_ALREADY_STARTED, + /** + * The call names an operation other than the one the record was claimed under; nothing was + * released (owner decision 2026-11-06). + */ OPERATION_CONFLICT, INDETERMINATE, UNAVAILABLE diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyRenewOutcome.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyRenewOutcome.java index 7e94d129..6ae5b541 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyRenewOutcome.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyRenewOutcome.java @@ -29,7 +29,10 @@ public enum IdempotencyRenewOutcome { * with the same handle are still recorded (owner decision 2026-11-04). */ LEASE_EXPIRED(false), - /** The same operation id already renewed with different arguments. */ + /** + * The call names an operation other than the one the record was claimed under (owner decision + * 2026-11-06), or this renewal was already applied asking for a different lease. Nothing changed. + */ OPERATION_CONFLICT(false), /** The store may have applied the renewal; inspect before relying on either answer. */ INDETERMINATE(false), diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyStartOutcome.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyStartOutcome.java index 2a4c52d0..c35ea305 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyStartOutcome.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyStartOutcome.java @@ -33,7 +33,11 @@ public enum IdempotencyStartOutcome { * store started it). */ LEASE_EXPIRED(false), - /** The same operation id already started this record with different arguments. */ + /** + * The handle's owner token holds the record, but the call names an operation other than the one + * the record was claimed under; nothing changed. Every store refuses it (owner decision + * 2026-11-06 — the PostgreSQL store started it). + */ OPERATION_CONFLICT(false), /** The store may have applied the start; inspect before relying on either answer. */ INDETERMINATE(false), diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyStorePort.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyStorePort.java index 062c4675..8e93af90 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyStorePort.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyStorePort.java @@ -21,6 +21,14 @@ import java.time.Duration; * record from its holder. Only the record's own lifetime ends it: once it is gone, every call * answers {@code ABSENT} (owner decision 2026-11-04; re-review 2026-11-04 RR5-01-02·03; {@code * IdempotencyStoreContract}). + * + *

Every transition names the operation its record was claimed under — the handle's {@link + * IdempotencyOwner#claimOperationId()}. A holder naming another one is answered {@code + * OPERATION_CONFLICT} and nothing changes; a claim that brings the owner token under another + * operation to a record still in progress is {@link + * IdempotencyClaimOutcome.OwnerOperationConflict}, and an inspection is {@code OPERATION_CONFLICT} + * in every state (owner decision 2026-11-06). For renew and failure {@code OPERATION_CONFLICT} also + * still means the same transition was already applied with other arguments. */ public interface IdempotencyStorePort { diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/IdempotencyStoreContract.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/IdempotencyStoreContract.java index 1eb77aa8..c378a743 100644 --- a/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/IdempotencyStoreContract.java +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/IdempotencyStoreContract.java @@ -514,6 +514,244 @@ public abstract class IdempotencyStoreContract { .isGreaterThan(claimed.stateRevision()); } + // Every transition names the operation its record was claimed under. A holder naming another one + // is refused as OPERATION_CONFLICT and the record is left as it was: the Redis store refused it, + // the PostgreSQL store and the in-memory fake applied it — the PostgreSQL store wrote the named + // operation beside the claim's and read the claim's from the handle (owner decision 2026-11-06). + + @Test + void startingUnderAnotherOperationThanTheClaimIsAConflictThatStartsNothing() { + // given + IdempotencyStorePort store = subject(); + IdempotencyOwner claimed = acquire(store); + + // when + IdempotencyMutationResult conflict = + store.markExecutionStarted(claimed, OTHER_OPERATION); + + // then + assertThat(conflict.outcome()).isEqualTo(IdempotencyStartOutcome.OPERATION_CONFLICT); + assertThat(store.markExecutionStarted(claimed, OPERATION).outcome()) + .isEqualTo(IdempotencyStartOutcome.STARTED); + } + + @Test + void renewingUnderAnotherOperationThanTheClaimIsAConflictThatRenewsNothing() { + // given + IdempotencyStorePort store = subject(); + IdempotencyOwner executing = executing(store); + + // when + IdempotencyMutationResult conflict = + store.renew(executing, Duration.ofSeconds(30), OTHER_OPERATION); + + // then + assertThat(conflict.outcome()).isEqualTo(IdempotencyRenewOutcome.OPERATION_CONFLICT); + // The revision did not move, so the handle the start returned still completes the record. + assertThat(store.complete(executing, new StoredResponse("{}"), Duration.ofHours(1), OPERATION)) + .isEqualTo(IdempotencyCompleteOutcome.COMPLETED); + } + + @Test + void completingUnderAnotherOperationThanTheClaimIsAConflictThatRecordsNothing() { + // given + IdempotencyStorePort store = subject(); + IdempotencyOwner executing = executing(store); + + // when + IdempotencyCompleteOutcome conflict = + store.complete( + executing, new StoredResponse("{\"v\":1}"), Duration.ofHours(1), OTHER_OPERATION); + + // then + assertThat(conflict).isEqualTo(IdempotencyCompleteOutcome.OPERATION_CONFLICT); + // No response was recorded: another one completes the record rather than conflicting with it. + assertThat( + store.complete( + executing, new StoredResponse("{\"v\":2}"), Duration.ofHours(1), OPERATION)) + .isEqualTo(IdempotencyCompleteOutcome.COMPLETED); + } + + @Test + void markingFailedUnderAnotherOperationThanTheClaimIsAConflictThatMarksNothing() { + // given + IdempotencyStorePort store = subject(); + IdempotencyOwner executing = executing(store); + + // when + IdempotencyFailOutcome conflict = + store.markFailed( + executing, + IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE, + Duration.ofHours(1), + OTHER_OPERATION); + + // then + assertThat(conflict).isEqualTo(IdempotencyFailOutcome.OPERATION_CONFLICT); + assertThat(store.complete(executing, new StoredResponse("{}"), Duration.ofHours(1), OPERATION)) + .isEqualTo(IdempotencyCompleteOutcome.COMPLETED); + } + + @Test + void releasingUnderAnotherOperationThanTheClaimIsAConflictThatReleasesNothing() { + // given + IdempotencyStorePort store = subject(); + IdempotencyOwner claimed = acquire(store); + + // when + IdempotencyReleaseOutcome conflict = store.releaseBeforeExecution(claimed, OTHER_OPERATION); + + // then + assertThat(conflict).isEqualTo(IdempotencyReleaseOutcome.OPERATION_CONFLICT); + assertThat(store.markExecutionStarted(claimed, OPERATION).outcome()) + .isEqualTo(IdempotencyStartOutcome.STARTED); + } + + @Test + void anotherAttemptCompletingARecordCompletedUnderTheSameOperationIsNotItsOwner() { + // given + // One operation id on two attempts — a caller that keeps its operation id across resends. The + // second attempt took the retryable failure over and completed it; the first attempt's late + // completion is not that completion. The PostgreSQL store confirmed it, because its replay + // check read the operation id and not the owner. + IdempotencyStorePort store = subject(); + IdempotencyOwner first = executing(store); + store.markFailed( + first, IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE, Duration.ofHours(1), OPERATION); + IdempotencyOwner second = + started(store, ownerOf(store.claim(claim(store.newClaimAttempt(OPERATION), FINGERPRINT)))); + store.complete(second, new StoredResponse("{\"v\":1}"), Duration.ofHours(1), OPERATION); + + // when + IdempotencyCompleteOutcome late = + store.complete(first, new StoredResponse("{\"v\":1}"), Duration.ofHours(1), OPERATION); + + // then + assertThat(late).isEqualTo(IdempotencyCompleteOutcome.NOT_OWNER); + } + + @Test + void aClaimWithTheOwnerTokenUnderAnotherOperationIsAnOwnerOperationConflict() { + // given + IdempotencyStorePort store = subject(); + IdempotencyClaimAttempt attempt = store.newClaimAttempt(OPERATION); + IdempotencyOwner claimed = ownerOf(store.claim(claim(attempt, FINGERPRINT))); + + // when + IdempotencyClaimOutcome conflict = + store.claim( + claim(new IdempotencyClaimAttempt(attempt.ownerToken(), OTHER_OPERATION), FINGERPRINT)); + + // then + assertThat(conflict).isInstanceOf(IdempotencyClaimOutcome.OwnerOperationConflict.class); + assertThat(store.markExecutionStarted(claimed, OPERATION).outcome()) + .isEqualTo(IdempotencyStartOutcome.STARTED); + } + + @Test + void inspectingAClaimWithTheOwnerTokenUnderAnotherOperationIsAnOperationConflict() { + // given + IdempotencyStorePort store = subject(); + IdempotencyClaimAttempt attempt = store.newClaimAttempt(OPERATION); + store.claim(claim(attempt, FINGERPRINT)); + + // when + IdempotencyInspection inspection = + store.inspect( + new IdempotencyInspectionRequest( + SCOPE, + FINGERPRINT, + new IdempotencyClaimAttempt(attempt.ownerToken(), OTHER_OPERATION))); + + // then + assertThat(inspection.outcome()).isEqualTo(IdempotencyInspectionOutcome.OPERATION_CONFLICT); + } + + @Test + void inspectingACompletedRecordWithTheOwnerTokenUnderAnotherOperationIsAnOperationConflict() { + // given + // In every state, a completed record included: the Redis store refused it, the PostgreSQL + // store and the in-memory fake replayed the response to it. + IdempotencyStorePort store = subject(); + IdempotencyClaimAttempt attempt = store.newClaimAttempt(OPERATION); + store.complete( + started(store, ownerOf(store.claim(claim(attempt, FINGERPRINT)))), + new StoredResponse("{\"ok\":true}"), + Duration.ofHours(1), + OPERATION); + + // when + IdempotencyInspection inspection = + store.inspect( + new IdempotencyInspectionRequest( + SCOPE, + FINGERPRINT, + new IdempotencyClaimAttempt(attempt.ownerToken(), OTHER_OPERATION))); + + // then + assertThat(inspection.outcome()).isEqualTo(IdempotencyInspectionOutcome.OPERATION_CONFLICT); + } + + @Test + void releasingAScopeWithNoRecordIsAbsent() { + // given + // A handle whose record is gone — expired, reaped — stands in here as one for a scope nobody + // claimed. Nothing was found, so nothing is confirmed: the Redis store answered that it had + // already released it. + IdempotencyStorePort store = subject(); + IdempotencyOwner gone = + new IdempotencyOwner(SCOPE, store.newClaimAttempt(OPERATION).ownerToken(), 1, 1, OPERATION); + + // when + IdempotencyReleaseOutcome released = store.releaseBeforeExecution(gone, OPERATION); + + // then + assertThat(released).isEqualTo(IdempotencyReleaseOutcome.ABSENT); + } + + @Test + void aReleaseRetriedAfterItWasAppliedReleasesNothingMore() { + // given + IdempotencyStorePort store = subject(); + IdempotencyOwner claimed = acquire(store); + store.releaseBeforeExecution(claimed, OPERATION); + + // when + IdempotencyReleaseOutcome again = store.releaseBeforeExecution(claimed, OPERATION); + + // then + // A store that keeps the released record recognises the release (PostgreSQL); one that forgets + // it finds no record (Redis, the in-memory fake). Neither releases a second time. + assertThat(again) + .isIn( + IdempotencyReleaseOutcome.ALREADY_RELEASED_SAME_OPERATION, + IdempotencyReleaseOutcome.ABSENT); + } + + @Test + void releasingThroughTheHandleFromBeforeTheAttemptTookItsClaimOverIsRefusedAsAStaleOwner() { + // given + // The same attempt took its retryable failure over, so the record is a claim again under the + // same owner token and operation. The Redis program read no revision and released it. + IdempotencyStorePort store = subject(); + IdempotencyClaimAttempt attempt = store.newClaimAttempt(OPERATION); + IdempotencyOwner before = ownerOf(store.claim(claim(attempt, FINGERPRINT))); + store.markFailed( + started(store, before), + IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE, + Duration.ofHours(1), + OPERATION); + IdempotencyOwner current = ownerOf(store.claim(claim(attempt, FINGERPRINT))); + + // when + IdempotencyReleaseOutcome released = store.releaseBeforeExecution(before, OPERATION); + + // then + assertThat(released).isEqualTo(IdempotencyReleaseOutcome.NOT_OWNER); + assertThat(store.markExecutionStarted(current, OPERATION).outcome()) + .isEqualTo(IdempotencyStartOutcome.STARTED); + } + @Test @DisplayName("실행 중인 자기 기록을 inspect하면 기록 수명이 아니라 claim이 받은 처리 lease 만료 시각이 나온다") void inspectingAnOwnExecutionReportsItsProcessingLeaseNotTheRecordLifetime() { diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/InMemoryIdempotencyStore.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/InMemoryIdempotencyStore.java index 12589761..d840a5d9 100644 --- a/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/InMemoryIdempotencyStore.java +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/InMemoryIdempotencyStore.java @@ -34,7 +34,8 @@ import java.util.Random; * attempt against an in-flight record is always {@code InProgress}. Leases and replay windows are * reported as {@link Instant#MAX}. What it keeps exact is what a test of a caller relies on: one * claim wins, the owner handle's revision advances on every transition, a completed response - * replays, a different fingerprint is refused, and a retryable failure can be claimed again. + * replays, a different fingerprint is refused, a retryable failure can be claimed again, and an + * owner naming an operation other than its claim's is refused. */ public final class InMemoryIdempotencyStore implements IdempotencyStorePort { @@ -82,6 +83,10 @@ public final class InMemoryIdempotencyStore implements IdempotencyStorePort { && row.owner.claimOperationId().equals(request.claimAttempt().operationId())) { return new IdempotencyClaimOutcome.ReplayedAcquire(row.owner, Instant.MAX); } + // The owner token under another operation is refused, not reported in progress. + if (row.owner.ownerToken().equals(request.claimAttempt().ownerToken())) { + return new IdempotencyClaimOutcome.OwnerOperationConflict(); + } return new IdempotencyClaimOutcome.InProgress(Duration.ZERO, row.owner.attempt()); } @@ -92,11 +97,13 @@ public final class InMemoryIdempotencyStore implements IdempotencyStorePort { IdempotencyStartOutcome outcome = row == null ? IdempotencyStartOutcome.ABSENT - : !row.owner.equals(owner) - ? IdempotencyStartOutcome.NOT_OWNER - : row.state != IdempotencyState.CLAIMED - ? IdempotencyStartOutcome.NOT_CLAIMED - : IdempotencyStartOutcome.STARTED; + : row.namesAnotherOperation(owner, operationId) + ? IdempotencyStartOutcome.OPERATION_CONFLICT + : !row.owner.equals(owner) + ? IdempotencyStartOutcome.NOT_OWNER + : row.state != IdempotencyState.CLAIMED + ? IdempotencyStartOutcome.NOT_CLAIMED + : IdempotencyStartOutcome.STARTED; if (outcome != IdempotencyStartOutcome.STARTED) { return new IdempotencyMutationResult<>(outcome, null, IdempotencyStartOutcome::carriesOwner); } @@ -114,11 +121,13 @@ public final class InMemoryIdempotencyStore implements IdempotencyStorePort { IdempotencyRenewOutcome refused = row == null ? IdempotencyRenewOutcome.ABSENT - : !row.owner.equals(owner) - ? IdempotencyRenewOutcome.NOT_OWNER - : row.state != IdempotencyState.EXECUTING - ? IdempotencyRenewOutcome.NOT_IN_PROGRESS - : null; + : row.namesAnotherOperation(owner, operationId) + ? IdempotencyRenewOutcome.OPERATION_CONFLICT + : !row.owner.equals(owner) + ? IdempotencyRenewOutcome.NOT_OWNER + : row.state != IdempotencyState.EXECUTING + ? IdempotencyRenewOutcome.NOT_IN_PROGRESS + : null; if (refused != null) { return new IdempotencyMutationResult<>(refused, null, IdempotencyRenewOutcome::carriesOwner); } @@ -137,6 +146,9 @@ public final class InMemoryIdempotencyStore implements IdempotencyStorePort { if (row == null) { return IdempotencyCompleteOutcome.ABSENT; } + if (row.namesAnotherOperation(owner, operationId)) { + return IdempotencyCompleteOutcome.OPERATION_CONFLICT; + } if (row.state == IdempotencyState.COMPLETED && owner.equals(row.completedBy)) { // The completing handle retried, as after a lost reply: the same result is a no-op, another // result is a conflict, exactly as the stores answer. @@ -166,6 +178,9 @@ public final class InMemoryIdempotencyStore implements IdempotencyStorePort { if (row == null) { return IdempotencyFailOutcome.ABSENT; } + if (row.namesAnotherOperation(owner, operationId)) { + return IdempotencyFailOutcome.OPERATION_CONFLICT; + } if (!row.owner.equals(owner)) { return IdempotencyFailOutcome.NOT_OWNER; } @@ -186,6 +201,9 @@ public final class InMemoryIdempotencyStore implements IdempotencyStorePort { if (row == null) { return IdempotencyReleaseOutcome.ABSENT; } + if (row.namesAnotherOperation(owner, operationId)) { + return IdempotencyReleaseOutcome.OPERATION_CONFLICT; + } if (!row.owner.equals(owner)) { return IdempotencyReleaseOutcome.NOT_OWNER; } @@ -205,6 +223,11 @@ public final class InMemoryIdempotencyStore implements IdempotencyStorePort { if (!row.fingerprint.equals(request.requestFingerprint())) { return IdempotencyInspection.outcome(IdempotencyInspectionOutcome.FINGERPRINT_MISMATCH); } + // The stores' order: the owner token under another operation is refused in every state. + if (row.owner.ownerToken().equals(request.claimAttempt().ownerToken()) + && !row.owner.claimOperationId().equals(request.claimAttempt().operationId())) { + return IdempotencyInspection.outcome(IdempotencyInspectionOutcome.OPERATION_CONFLICT); + } if (row.state == IdempotencyState.COMPLETED) { return new IdempotencyInspection( IdempotencyInspectionOutcome.COMPLETED_REPLAY, @@ -274,5 +297,15 @@ public final class InMemoryIdempotencyStore implements IdempotencyStorePort { owner = owner.withStateRevision(owner.stateRevision() + 1); state = next; } + + /** + * Whether the record's owner names an operation other than its claim's. The stores refuse that + * before anything else is read, whatever the handle's revision ({@code + * IdempotencyStoreContract}). + */ + boolean namesAnotherOperation(IdempotencyOwner caller, OperationId operationId) { + return owner.ownerToken().equals(caller.ownerToken()) + && !owner.claimOperationId().equals(operationId); + } } } From a9b6bcd52da0f9267d4708d9c408d6435a176a87 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 6 Nov 2026 22:31:07 +0900 Subject: [PATCH 15/71] =?UTF-8?q?docs(review):=20round7=EC=97=90=20?= =?UTF-8?q?=EB=8B=A4=EB=A5=B8=20=EB=A6=AC=EB=B7=B0=EC=9D=98=20=EB=B0=9C?= =?UTF-8?q?=EA=B2=AC=EA=B3=BC=20round6=20Declined=20=ED=8C=90=EC=A0=95?= =?UTF-8?q?=EC=9D=84=20=EB=8D=94=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 같은 커밋 6e992970을 따로 본 리뷰(claude/t1-baseline-7d623a 3add4917)가 이 리뷰에 없는 결함 셋을 찾았고 ID가 겹쳤다. 다른 세션이 코드 읽기로만 찾은 결함 후보(LockAcquisitionTimeoutException)가 남아 있었다. round6 「Declined to judge」 30건은 처리 기록이 없어 멈춤 기준 2가 거짓이었다. 방법: 넘겨받은 셋은 그쪽 근거를 읽고 이 리뷰의 기준 커밋 06f520e6에서 탐침을 다시 돌려 새 ID로 넣었다(RR7-01-03, RR7-03-03, RR7-03-04, 겹친 RR7-01-01은 합침, README 18.2절 대응표). 동시 인덱스 복구는 실패 이력 행 삭제를 더한 경우도 돌려 권하는 절차를 확인했다. 락 후보는 web· GraphQL 탐침으로 500 INTERNAL_ERROR를 확인해 RR7-01-04(Important)로 넣었다. round6 Declined 30건은 (a) 4 · (b) 24 · (c) 2로 판정해 (a)를 RR7-01-05·06, RR7-02-01, RR7-03-05로 올렸다. 소유자 결정 셋(RR7-05-01, RR7-03-03 복구, RR7-01-05 방향)을 18.4절 한 표로 모았다. 버린 대안: 다른 리뷰의 review.md를 그대로 합치기(같은 ID가 다른 결함을 가리킴). 결과: 결함 13건(Important 2, Minor 11, 회귀 1). 위험·한계: RR7-01-05·06, RR7-02-01, RR7-03-01·05는 코드 경로만(E1) 봤다. 라운드 끝 게이트는 다시 돌리지 않았다. round7 1차 Declined 12건은 아직 판정하지 않았다. (b) 2건은 t3·t5 브랜치가 병합돼야 닫힌다. 검증: check-review-index.py docs/reviews/2026-11-03-rereview rc=0(170건), check-work-docs.py --links(round7 6개 문서) rc=0. desktop 공유 잠금 아래 탐침 B1~B4(~/t1-r10-review-logs/summary.txt), 결과는 공유 노트 rr7-probes/results/pass2-06f520e6.txt. Refs: docs/reviews/2026-11-03-rereview/README.md 18절 --- docs/reviews/2026-11-03-rereview/README.md | 129 ++++++++++++++---- .../round7/01-core-inbound.md | 88 +++++++++++- .../round7/02-idempotency-outbound.md | 27 +++- .../round7/03-persistence.md | 71 +++++++++- .../round7/04-build-logic-shell.md | 2 +- .../round7/05-build-logic-workflow.md | 2 +- 6 files changed, 283 insertions(+), 36 deletions(-) diff --git a/docs/reviews/2026-11-03-rereview/README.md b/docs/reviews/2026-11-03-rereview/README.md index 10a0cccf..970ef6c0 100644 --- a/docs/reviews/2026-11-03-rereview/README.md +++ b/docs/reviews/2026-11-03-rereview/README.md @@ -412,6 +412,9 @@ Minor 중 RR5-01-01(`IDEMPOTENCY_RECOVERY_REQUIRED`의 클라이언트 안내가 커밋 하나가 +5,143줄이라 확인 리뷰 상한(추가 1,500줄, `docs/work/improve.md` 4.4절)을 넘는다. 영역 pathspec으로 나눴다. 정확한 pathspec은 각 영역 문서 「범위」에 있다. +같은 날 2차로 총괄이 세 가지를 더 맡겼다: 같은 커밋을 따로 본 리뷰의 발견 중 겹치지 않는 것(18.2절), 다른 세션이 코드 읽기로 찾은 결함 +후보 하나(RR7-01-04), round6 「Declined to judge」 30건 판정(18.5절). 2차 결함은 각 영역 문서의 「2차 추가 결함」 절에 있다. + | 영역 | 대상 | `git diff --shortstat` | |---|---|---| | [01 core·inbound](round7/01-core-inbound.md) | shared-contract, inbound web·GraphQL·gRPC·WebSocket, app-bootstrap(Flyway 규칙 제외), 매뉴얼 07, runbook | 33 파일, +1056 −137 | @@ -424,54 +427,126 @@ pathspec은 각 영역 문서 「범위」에 있다. ### 18.1 결과 -Critical 0, Important 0, 회귀 1(RR7-01-01). 결함 5건, 모두 Minor. 이번 수정이 만든 것 3건, 이전부터 있던 것을 이번 수정이 넓히거나 새로 -약속한 것 2건(섞임). +Critical 0, Important 2, Minor 11, 회귀 1. 결함 13건: 이번 수정이 만든 것 4건, 섞임 2건(이전부터 있던 것을 이번 수정이 넓히거나 새로 +약속함), 이전부터 7건. -| ID | 심각도 | 내용 | 이번 수정 / 이전부터 | 증거 | -|---|---|---|---|---| -| RR7-01-01 | Minor(회귀) | 설정에 중첩된 클래스를 요청 처리기 목록으로만 보아, 설정 안의 JAX-RS 자원·`@ServerEndpoint`가 `@SystemCaller`를 불러도 잡히지 않는다. r9는 잡았다 | 이번 수정 | E2 탐침, 두 커밋 | -| RR7-01-02 | Minor | 메서드 참조로 route만 등록한 설정도 사용자 전송이라, 같은 설정이 handler bean을 등록하면 거짓 실패. Javadoc·매뉴얼 07·B-16의 "요청 처리 코드를 다른 클래스에" 안내와 다르다 | 이번 수정 | E2 탐침 | -| RR7-03-01 | Minor | ledger 잠금 대기 IT가 "이 테스트에 예외로 적으라"고 안내하지만 예외를 적을 곳이 없다 | 이번 수정 | E1 | -| RR7-03-02 | Minor | "Flyway는 `REINDEX … CONCURRENTLY`를 트랜잭션 안에서 돌린다"는 설명이 `REINDEX SCHEMA|DATABASE CONCURRENTLY`에서 틀린다(Flyway가 트랜잭션 밖에서 적용) | 섞임 | E3 실 PostgreSQL | -| RR7-05-01 | Minor | 메시지·B-36은 "매 push·pull request·schedule에 도는 workflow"를 요구하지만 판독기는 `paths:` 필터 workflow도 센다 | 섞임(동작은 이전부터, 약속은 이번 수정) | E2 탐침 | +| ID | 심각도 | 내용 | 이번 수정 / 이전부터 | 출처 | 증거 | +|---|---|---|---|---|---| +| RR7-01-01 | Minor(회귀) | 설정에 중첩된 JAX-RS 자원·`@ServerEndpoint`가 `@SystemCaller`를 불러도 잡히지 않는다. r9는 잡았다 | 이번 수정 | 이 리뷰(다른 리뷰도 같은 결함) | E2 | +| RR7-01-02 | Minor | 메서드 참조로 route만 등록한 설정도 사용자 전송이라 handler bean과 같이 두면 거짓 실패. Javadoc·매뉴얼 07·B-16 안내와 다르다 | 이번 수정 | 이 리뷰 | E2 | +| RR7-01-03 | Minor | gRPC가 IAE를 원인으로 든 raw status를 던지면 `INTERNAL`·ERROR(메시지 첨부), `onError`로 넘기면 `BAD_PARAMETER`·WARN | 이전부터 | 다른 리뷰 | E2 | +| RR7-01-04 | Important | `LockAcquisitionTimeoutException`이 carrier가 아니고 처리기도 없어 409(재시도 가능) 대신 500 `INTERNAL_ERROR`(재시도 불가) | 이전부터 | 총괄 전달 후보 | E2 | +| RR7-01-05 | Minor | 감싼 carrier를 web·GraphQL·STOMP는 못 보고 gRPC만 찾아 응답 코드·로그가 전송마다 다르다 | 이전부터 | round6 01 Declined | E1 | +| RR7-01-06 | Minor | STOMP payload 변환·검증 실패를 ERROR와 예외 메시지(입력 조각)로 남긴다 | 이전부터 | round6 01 Declined | E1 | +| RR7-02-01 | Minor | httpclient `ClientRuntimeRegistry.close()`가 interrupt 상태면 drain 스레드 종료를 확인하지 않고 정상 반환 | 이전부터 | round6 02 Declined | E1 | +| RR7-03-01 | Minor | ledger 잠금 대기 IT가 "예외로 적으라"고 안내하지만 예외를 적을 곳이 없다 | 이번 수정 | 이 리뷰 | E1 | +| RR7-03-02 | Minor | "Flyway는 `REINDEX … CONCURRENTLY`를 트랜잭션 안에서 돌린다"가 `SCHEMA`·`DATABASE` 형태에서 틀린다 | 섞임 | 이 리뷰 | E3 | +| RR7-03-03 | Important | 실패한 동시 인덱스 복구를 "`DROP INDEX` 하나"로 안내하지만 `success=false` 이력 행이 다음 배포를 막고 runbook은 그 행 삭제를 금지 | 이전부터 | 다른 리뷰 | E3 | +| RR7-03-04 | Minor | "섞인 파일은 부분 적용되지 않는다"가 `.sql.conf`(`executeInTransaction=false`)를 붙이면 틀린다 | 이번 수정 | 다른 리뷰 | E3 | +| RR7-03-05 | Minor | 잠금 대기 검사기 Javadoc은 `VACUUM FULL`을 늘 거부한다지만 `executeInTransaction=true` 설정 파일에서는 통과 | 이전부터 | round6 03 Declined | E1 | +| RR7-05-01 | Minor | 메시지·B-36은 "매 push·PR·schedule"을 요구하지만 판독기는 `paths:` 필터 workflow도 센다 | 섞임 | 이 리뷰(round6 04 Declined와 같음) | E2 | r10이 고쳤다고 한 항목의 재확인(영역 문서 「항목 재확인」): - 닫힘: RR6-01-01~09, RR6-02-01~05, RR6-03-01~04, RR6-04-01~06. -- 부분: RR6-03-05(설명을 고치며 RR7-03-01·02가 생김). +- 부분: RR6-03-05(설명을 고치며 RR7-03-01·02·04가 생김). 색인 보완: 이 README가 ID 대신 내용으로만 적은 지난 발견 둘을 이름으로 적는다(`docs/work/evidence.md` 7절). RR-05-10(06 영역 발견 5건의 색인 누락)은 1절 정정과 6.1절이, RR-07-05(CSRF 제외 규칙의 이유)는 6절 r4-f 행의 "RR-06-05+07-05"가 다룬다. -### 18.2 실행 (2026-11-06, desktop) +### 18.2 출처 리뷰와 ID 대응 + +같은 커밋 `6e992970`을 다른 리뷰어가 따로 리뷰했다: 브랜치 `claude/t1-baseline-7d623a`, 커밋 `3add4917`, 파일 +`docs/reviews/2026-11-03-rereview/round7/review.md`(그 브랜치에만 있음), 매뉴얼 `docs/improvement/` 기준. 그 리뷰도 `RR7-NN-MM`을 썼고 번호가 +이 리뷰와 겹치지만 뜻이 다르다. 넘겨받은 발견은 그쪽 근거를 확인한 뒤 이 리뷰의 기준 커밋에서 탐침을 다시 돌렸다. + +| 다른 리뷰 ID | 이 리뷰 ID | 처리 | +|---|---|---| +| RR7-01-01 | RR7-01-01 | 같은 결함. 하나로 센다(01 문서 RR7-01-01에 한 줄) | +| RR7-01-02 | RR7-01-03 | 넘겨받음. 명령 B3으로 재현 | +| RR7-03-01 | RR7-03-04 | 넘겨받음. 명령 B4로 재현 | +| RR7-03-02(Important) | RR7-03-03(Important) | 넘겨받음. 명령 B4로 재현, 고치는 법의 SQL도 확인 | + +- 그 리뷰의 「Declined to judge」 중 경로 필터는 RR7-05-01, `new FluentConfiguration()` 경로·같은 owner token의 다른 operation id는 이 리뷰 + 1차 Declined(03·02 문서)와 같다. "설정이 `@CrossOrigin`·`RequestMethod`·`HttpServletRequest`를 쓰면 거짓 실패"는 RR7-01-02와 같은 모양이라 + 01 문서 RR7-01-02에 한 줄로 더했다. +- 두 리뷰 문서를 한 브랜치에 합치면 같은 ID가 다른 결함을 가리켜 색인 검사가 중복으로 보고한다. `round7/review.md`는 그대로 합치지 말고, + 출처 기록으로 그 브랜치에 두거나 위 표대로 번호를 바꿔 합친다. + +### 18.3 실행 (2026-11-06, desktop) 임시 worktree `~/workspace/t1-r10-review`(`06f520e6`)와 `~/workspace/t1-r10-review-r9`(`45d2a478`, r9 비교용)에 탐침을 얹어 `flock /tmp/claude-gates/heavy.lock` 아래에서 차례로 돌렸다. 로그 `~/t1-r10-review-logs/`(desktop, `summary.txt`). 탐침 코드와 결과는 공유 노트 -폴더 `rr7-probes/`에 있어 고칠 때 fixture로 옮겨 쓸 수 있다. 끝나고 두 worktree를 지웠다. +폴더 `rr7-probes/`(1차)·`rr7-probes/pass2/`(2차)에 있어 고칠 때 fixture로 옮겨 쓸 수 있다. 1차·2차 모두 끝나고 worktree를 지웠다. -| 명령 | 대상 | 결과 | 시간 | 직전 부하(1분) | -|---|---|---|---|---| -| `:app-bootstrap:architectureTest --tests …Rr7ProbeTest` | `06f520e6` | rc=0(탐침 P1·P2 위반 없음, P3 위반) | 21초 | 4.58 | -| 같은 명령 | `45d2a478` | rc=0(P1·P2 위반, P3 위반 없음) | 20초 | 4.89 | -| `-p build-logic test --tests …Rr7WorkflowProbeTest` | `06f520e6` | rc=0(경로 필터 workflow를 셈) | 2초 | 4.66 | -| `:adapter:outbound:persistence-jpa:rr7ReindexProbe`(임시 lane, 실 PostgreSQL) | `06f520e6` | rc=0(REINDEX 다섯 형태 중 SCHEMA·DATABASE만 적용) | 19초 | 4.28 | -| `:shared-contract:test :application-core:test :adapter:outbound:redis-runtime:test :adapter:outbound:cache-redis:test :adapter:outbound:persistence-jpa:test :adapter:outbound:persistence-notification:test :adapter:inbound:messaging:test :adapter:inbound:web:test :adapter:inbound:grpc:test :adapter:inbound:graphql:test :adapter:inbound:websocket:test :app-bootstrap:architectureTest --rerun --continue` | `06f520e6` + 탐침 | rc=0. 실행: persistence-jpa `test` 664건, `architectureTest` 229건(탐침 1건 포함), 실패 0. 나머지 10개 `test`는 FROM-CACHE(같은 입력의 이전 실행 결과) | 47초 | 4.46 | -| `-p build-logic test --rerun` | `06f520e6` + 탐침 | rc=0, 169건 실패 0 skip 0(탐침 1건 포함) | 40초 | 3.69 | +| # | 명령 | 대상 | 결과 | 시간 | 직전 부하(1분) | +|---|---|---|---|---|---| +| A1 | `:app-bootstrap:architectureTest --tests …Rr7ProbeTest` | `06f520e6` | rc=0(탐침 P1·P2 위반 없음, P3 위반) | 21초 | 4.58 | +| A2 | 같은 명령 | `45d2a478` | rc=0(P1·P2 위반, P3 위반 없음) | 20초 | 4.89 | +| A3 | `-p build-logic test --tests …Rr7WorkflowProbeTest` | `06f520e6` | rc=0(경로 필터 workflow를 셈) | 2초 | 4.66 | +| A4 | `:adapter:outbound:persistence-jpa:rr7ReindexProbe`(임시 lane, 실 PostgreSQL) | `06f520e6` | rc=0(REINDEX 다섯 형태 중 SCHEMA·DATABASE만 적용) | 19초 | 4.28 | +| A5 | `:shared-contract:test :application-core:test :adapter:outbound:redis-runtime:test :adapter:outbound:cache-redis:test :adapter:outbound:persistence-jpa:test :adapter:outbound:persistence-notification:test :adapter:inbound:messaging:test :adapter:inbound:web:test :adapter:inbound:grpc:test :adapter:inbound:graphql:test :adapter:inbound:websocket:test :app-bootstrap:architectureTest --rerun --continue` | `06f520e6` + 탐침 | rc=0. 실행: persistence-jpa `test` 664건, `architectureTest` 229건(탐침 1건 포함), 실패 0. 나머지 10개 `test`는 FROM-CACHE(같은 입력의 이전 실행 결과) | 47초 | 4.46 | +| A6 | `-p build-logic test --rerun` | `06f520e6` + 탐침 | rc=0, 169건 실패 0 skip 0(탐침 1건 포함) | 40초 | 3.69 | +| B1 | `:adapter:inbound:web:test --tests …Rr7LockTimeoutWebProbeTest` | `06f520e6` | rc=0(500 `INTERNAL_ERROR` `retryable=false`) | 9초 | 1.32 | +| B2 | `:adapter:inbound:graphql:test --tests …Rr7LockTimeoutGraphQlProbeTest` | `06f520e6` | rc=0(`INTERNAL_ERROR`) | 8초 | 1.73 | +| B3 | `:adapter:inbound:grpc:test --tests "…GrpcExceptionHandlingInterceptorTest.rr7probe*"` | `06f520e6` | rc=0(던짐 `INTERNAL`·ERROR+메시지, 넘김 `INVALID_ARGUMENT`·WARN) | 4초 | 2.01 | +| B4 | `:adapter:outbound:persistence-jpa:rr7CicProbe`(임시 lane, 실 PostgreSQL) | `06f520e6` | 첫 실행 rc=1(내 탐침 컴파일 오류), 고친 뒤 rc=0(섞임·복구 네 경우, 03 문서 표) | 3초 / 15초 | 2.01 / 2.66 | 다시 돌리지 않은 것: 라운드 끝 게이트(`ci`, `mainCheck`, `integrationCheck`, `-p optional-platforms …`, compose)와 실 Redis·실 PG 계약 lane. 마지막 실행은 17.2절의 `2c692554`다(이 리뷰에는 E0). -### 18.3 결정이 필요한 것 +### 18.4 결정이 필요한 것 | 항목 | 선택지 | 권하는 안과 이유 | 정할 사람 | |---|---|---|---| -| RR7-05-01 경로 필터 workflow를 단계 실행으로 셀지 | (a) `paths:`·`paths-ignore:` trigger만으로는 세지 않는다 (b) 세고, 메시지·B-36의 "매 변경" 약속을 고친다 | (a). 단계 검사는 "모든 변경이 이 lane을 지난다"를 보장하려는 것이고, 경로 필터는 그 보장을 깬다. 이 repo의 단계 명령은 필터 없는 workflow에 있어 판정이 바뀌지 않는다. round6 04가 "저장소 정책"으로 판단하지 않은 항목이라 정책으로 닫는다 | 소유자 | +| RR7-05-01(= round6 04 Declined ①) 경로 필터 workflow를 단계 실행으로 셀지 | (a) `paths:`·`paths-ignore:` trigger만으로는 세지 않는다 (b) 세고, 메시지·B-36의 "매 변경" 약속을 고친다 | (a). 단계 검사는 "모든 변경이 이 lane을 지난다"를 보장하려는 것이고 경로 필터는 그 보장을 깬다. 이 repo의 단계 명령은 필터 없는 workflow에 있어 판정이 바뀌지 않는다 | 소유자 | +| RR7-03-03 실패한 동시 인덱스 마이그레이션의 복구 절차 | (a) runbook에 "그 버전의 실패 이력 행만 지운다" 예외와 SQL(`DELETE FROM WHERE version = '' AND NOT success`)을 둔다 (b) 이 경우 `flyway repair`를 허용한다 (c) 동시 인덱스 마이그레이션을 금지하고 운영 절차로 돌린다 | (a). 실패 행은 적용되지 않은 버전의 기록이라 지워도 성공한 마이그레이션의 순서·checksum은 그대로다(명령 B4 넷째 경우로 재배포 성공 확인). (b)의 repair는 checksum·설명까지 다시 맞춰 가이드가 막으려는 불일치를 지운다. (c)는 r10이 이미 버린 대안이다(큰 테이블 인덱스 추가가 번거로워짐). "이력을 고치지 않는다" 정책의 예외라 소유자 확인이 필요하다 | 소유자 | +| RR7-01-05(= round6 01 Declined ①) 감싼 carrier를 전송이 어떻게 볼지 | (a) 네 전송 모두 원인 사슬의 첫 carrier를 본다 — web·GraphQL·STOMP에서 감싼 carrier의 응답이 500 → carrier 코드로 바뀐다 (b) 네 전송 모두 맨 위만 본다 — gRPC 응답이 carrier 코드 → `INTERNAL`로 바뀐다 (c) 차이를 두고 문서화한다 | (a). use case가 뜻한 코드로 답하고, persistence 실패의 SQL 원인이 어느 전송 로그에도 남지 않는다. gRPC가 이미 그렇게 해서 바뀌는 쪽이 셋이지만, 바뀌는 응답은 지금 500 `INTERNAL_ERROR`로 뭉개지는 경우뿐이다. 응답 코드가 바뀌는 수정이라 고치기 전에 확인받는다(`docs/work/improve.md` 7절) | 소유자 | -### 18.4 멈춤 기준 상태 (`docs/work/improve.md` 4.5절) +### 18.5 round6 「Declined to judge」 30건 판정 (2026-11-06) -1. 마지막 확인 리뷰 발견 0: **아님.** 5건(18.1절). +(a) 실제 결함 → round7 발견으로 넣음, (b) 결함 아님 → 닫음, (c) 소유자 결정 필요 → 18.4절. 번호는 round6 각 영역 문서 「Declined to judge」의 +순서다. 결과: (a) 4건(그중 1건은 RR7-01-01에 합침), (b) 24건, (c) 2건. + +| 영역 | # | 항목 | 판정 | 근거 | +|---|---|---|---|---| +| 01 | ① | 감싼 carrier를 전송마다 다르게 봄 | (c) → RR7-01-05 | 같은 규칙이 전송마다 갈라졌다(A1). 고치는 방향이 응답 코드를 바꿔 18.4절 | +| 01 | ② | dependency·5xx carrier를 원인 사슬째 남김 | (b) | 서버 실패를 원인과 함께 남기는 것이 정한 설계다(`ServerFailureLog.of`가 dependency·5xx carrier에 예외를 붙임). A8이 막는 것은 SQL 원인과 입력값이다. 자격 증명이 실리는 구체적 경로를 세우지 못했다 | +| 01 | ③ | GraphQL이 실패한 필드마다 한 줄 | (b) | 필드 단위 오류 설계의 결과다. 약속 위반이 없다 | +| 01 | ④ | 업그레이드 B-34가 템플릿 패키지 이름을 다시 나열 | (b) | 업그레이드 안내는 그 릴리스의 변경 기록이다. 정본은 `src/application-core/CLAUDE.md` 표이고 `TemplatePackageOwnershipDocumentTest`가 코드 사본과 대조한다 | +| 01 | ⑤ | STOMP 변환·검증 실패 ERROR | (a) → RR7-01-06 | 클라이언트 탓 실패를 ERROR와 입력 조각으로 남겨 A8을 어긴다 | +| 01 | ⑥ | RR6-01-01 고치는 법의 endpoint 목록 완전성 | (a) → RR7-01-01에 합침 | 목록이 사용자 전송 타입 목록보다 좁아 r9가 잡던 중첩 endpoint를 놓친다 | +| 01 | ⑦ | 규칙 탐침이 정적 `@ArchTest`만 돌림 | (b) | 방법 메모이고 결함 주장이 아니다. 메서드형 `@ArchTest`는 지금도 없다(architectureTest 전체 grep, `@ArchTest` 뒤 메서드 0) | +| 02 | ① | watchdog 스레드의 `inheritedAccessControlContext` | (b) | 템플릿은 실행 jar로 배포해 class loader가 하나다. 스레드는 마지막 예약 60초 뒤 끝난다. 공유 부모 loader 배포는 지원하는 형태가 아니다 | +| 02 | ② | `ClientRuntimeRegistry.close()`의 interrupt 처리 | (a) → RR7-02-01 | "돌아오면 스레드가 없다"는 Javadoc 약속이 interrupt 경로에서 확인 없이 깨진다(A14) | +| 02 | ③ | 배포 중 섞인 버전의 lease 지난 시작 | (b) | 배포 동안만이고 중복 실행이 없다(새 인스턴스는 옛 인스턴스가 시작한 기록을 넘겨받지 않는다) | +| 02 | ④ | `error-codes.yaml` `IDEMPOTENCY_UNAVAILABLE` `log_level` | (b) 다른 세션 처리 | `claude/t3-error-codes-loglevel-fcf427`에서 고침. 그 브랜치가 병합되면 닫힌다 | +| 02 | ⑤ | 시작 호출의 operation id가 claim과 다를 때 저장소 답이 다름 | (b) 다른 세션 처리 중 | `claude/t5-idempotency-operation-id-9bd973`에서 고치는 중. 병합 전까지 그 브랜치에서 열림 | +| 02 | ⑥ | in-memory fake가 lease를 모델링하지 않음 | (b) | RR-01-06 결정의 설계다(시간 케이스는 skip으로 보고). executor의 `LEASE_EXPIRED` → 503 매핑은 단위 테스트가 본다 | +| 03 | ① | 검사기의 10단어 셈이 Flyway와 다름 | (b) | 결과가 달라지는 입력이 없다(판정 단어가 첫 4개 키워드 안, 앞 괄호는 많아야 6단어) | +| 03 | ② | 중첩 블록 주석 | (b) r10이 고침 | `6e992970`: `LockWaitMigrationInspector.endOfBlockComment`, 테스트 `aStatementInsideANestedBlockCommentIsNotRead` | +| 03 | ③ | `executeInTransaction=true` + `SET LOCAL` + `VACUUM FULL` 통과 | (a) → RR7-03-05 | Javadoc의 "늘 거부"와 동작이 다르다(A2) | +| 03 | ④ | `REINDEX (CONCURRENTLY 'false')`를 동시로 판정 | (b) | 거부 쪽 오판이라 거짓 통과가 없고, 쓸 이유가 없는 입력이다 | +| 03 | ⑤ | `.sql.conf`의 placeholder·환경 변수에서 검사기 실패 | (b) | 거부 쪽이다. Flyway 치환 결과를 모른 채 통과시키지 않는 것이 맞는 방향이다 | +| 03 | ⑥ | Sync 사본과 IDE | (b) | 생성 소스의 일반 성질이다. IntelliJ 기본(Gradle 위임)에서는 Sync가 먼저 돈다 | +| 03 | ⑦ | persistence-jpa 디렉터리가 없는 파생 서비스 | (b) | 문서화된 capability 제거는 `runtimeOnly` 한 줄 제거이지 디렉터리 삭제가 아니다 | +| 03 | ⑧ | ledger V002 주석 "Flyway runs each migration in a transaction" | (b) | 적용된 마이그레이션은 고치지 않는다는 규칙이 정한다(`docs/work/reference/review-criteria.md` 9절, checksum). 틀린 설명은 r10이 가이드·검사기 Javadoc에서 바로잡았다 | +| 03 | ⑨ | `MessagingMigrationNamespaceTest` 정규식 | (b) | 소수 버전을 실패시키는 거부 쪽이라 조용히 빠지지 않는다 | +| 03 | ⑩ | `mixed=true`·전역 `executeInTransaction=false`를 쓰는 서비스 | (b) | 검사기 Javadoc과 가이드가 가정으로 적는다(약속 범위 밖으로 명시) | +| 04 | ① | 경로·브랜치 필터 trigger | (c) → RR7-05-01 | r10이 "매 변경"을 약속하며 정책 질문이 결함이 됐다. 18.4절 | +| 04 | ② | 설계상 거짓 실패 모양(`timeout ./gradlew`, `|| exit 1` 등) | (b) | README 16절 결정(거짓 실패 쪽을 받아들임) | +| 04 | ③ | `${{ }}` 값이 `--dry-run`·`|| true`로 펼쳐짐 | (b) | 실행 전 값을 알 수 없고, workflow 작성자가 자기 식으로 넣는 의도된 변경이다. 식 인자를 모두 세지 않으면 matrix 플래그마다 거짓 실패가 난다 | +| 04 | ④ | `CDPATH`·심볼릭 링크 | (b) | GitHub runner 기본 환경에 `CDPATH`가 없다 | +| 04 | ⑤ | composite action 안의 `run:` | (b) | 판독기가 읽지 않아 세지 않는 쪽(거짓 실패)이다 | +| 04 | ⑥ | httpclient 문서의 lane 이름·장애 주입 주기 | (b) 다른 커밋 처리 | `e6b6e18e`. 기준 커밋에서 `docs/httpclient/support-matrix.md:61`(`spring62ApiSurfaceScan`)·`:65`(main push, nightly)·`release-checklist.md:12`가 맞다 | +| 04 | ⑦ | 실제 GitHub runner·pwsh 동작 | (b) | 결함 주장이 아니라 실행 환경의 한계다. RR6-04-04는 코드·테스트로 닫혔다 | + +### 18.6 멈춤 기준 상태 (`docs/work/improve.md` 4.5절) + +1. 마지막 확인 리뷰 발견 0: **아님.** 13건(18.1절). 2. 열린 「Declined to judge」 0: **아님.** - - round6 01~04의 Declined 30건이 17절 처리 표·결정에 배정되거나 닫힌 기록이 없다(03의 중첩 블록 주석 1건은 r10이 고쳤다). 영역 문서에 위치가 있다. - - round7의 Declined 12건(01: 3, 02: 2, 03: 2, 04: 2, 05: 3)은 각 영역 문서에 있다. 판단이 필요한 것은 02의 "같은 owner token·다른 operation id의 넘겨받기"(업그레이드 안내에 없는 동작 변경)와 03의 "`new FluentConfiguration()` 경로"다. + - round6 30건은 모두 판정했다(18.5절). (b) 중 2건은 다른 브랜치(`claude/t3-error-codes-loglevel-fcf427`, `claude/t5-idempotency-operation-id-9bd973`)가 + 병합돼야 닫힌다. + - round7 1차 Declined 12건(01: 3, 02: 2, 03: 2, 04: 2, 05: 3)은 아직 판정하지 않았다. 각 영역 문서에 있다. 3. 합친 트리의 라운드 끝 게이트: r10 트리 `2c692554`에서 통과(17.2절). 이 리뷰는 다시 돌리지 않았다. -4. README의 남은 항목 0: **아님.** 위 1·2와 18.3절 결정. +4. README의 남은 항목 0: **아님.** 위 1·2와 18.4절 결정 3건. diff --git a/docs/reviews/2026-11-03-rereview/round7/01-core-inbound.md b/docs/reviews/2026-11-03-rereview/round7/01-core-inbound.md index 0c140fc5..4091701f 100644 --- a/docs/reviews/2026-11-03-rereview/round7/01-core-inbound.md +++ b/docs/reviews/2026-11-03-rereview/round7/01-core-inbound.md @@ -50,7 +50,7 @@ desktop(`ssh desktop`) 임시 worktree 두 개(`~/workspace/t1-r10-review` = `06 |---|---|---|---| | 1 | `./gradlew :app-bootstrap:architectureTest --tests dev.caskeleton.bootstrap.architecture.Rr7ProbeTest` (`06f520e6`) | rc=0, 21초. 결과는 아래 표 | 4.58 | | 2 | 같은 명령 (`45d2a478`, 같은 탐침) | rc=0, 20초 | 4.89 | -| 3 | `./gradlew :shared-contract:test … :adapter:inbound:web:test :adapter:inbound:grpc:test :adapter:inbound:graphql:test :adapter:inbound:websocket:test :app-bootstrap:architectureTest --rerun --continue` (`06f520e6`, 탐침 포함 트리) | README 18.2절 | README 18.2절 | +| 3 | `./gradlew :shared-contract:test … :adapter:inbound:web:test :adapter:inbound:grpc:test :adapter:inbound:graphql:test :adapter:inbound:websocket:test :app-bootstrap:architectureTest --rerun --continue` (`06f520e6`, 탐침 포함 트리) | README 18.3절 | README 18.3절 | 탐침 `Rr7ProbeTest`는 `USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS`를 다섯 모양에 돌려 위반 여부를 파일에 적는다. @@ -107,6 +107,7 @@ desktop(`ssh desktop`) 임시 worktree 두 개(`~/workspace/t1-r10-review` = `06 - RED 테스트 모양: 탐침 P1·P2를 위반 fixture로 옮긴다(`rr7-probes/…/probe/rr7/NestedJaxRsConfiguration.java`, `NestedServerEndpointConfiguration.java`). `06f520e6`에서 위반 0으로 실패해야 한다. - **이번 수정 / 이전부터**: 이번 수정(회귀). - **증거**: E2 — 명령 1·2(탐침 P1·P1c·P2를 두 커밋에서 실행). 코드 경로는 E1. +- **다른 리뷰와 합침**: 같은 커밋을 따로 본 리뷰(`claude/t1-baseline-7d623a` `3add4917`, `round7/review.md`의 RR7-01-01)가 같은 결함을 같은 모양(중첩 `@Path`·`@ServerEndpoint`, r9 위반 1건 → r10 0건)으로 찾았다. 그 리뷰는 WebFlux `WebFilter`·`WebHandler`도 같은 방식으로 빠진다고 적었다(E1). 결함 하나로 센다. ### RR7-01-02 · Minor · 메서드 참조로 함수형 route만 등록한 설정도 사용자 전송으로 세어, 같은 설정이 handler bean을 등록하면 거짓 실패한다 — Javadoc·매뉴얼은 "요청 처리 코드가 있을 때만"이라고 적는다 @@ -125,13 +126,14 @@ desktop(`ssh desktop`) 임시 worktree 두 개(`~/workspace/t1-r10-review` = `06 - RED 테스트 모양: 권장안이면 문서 변경이라 RED가 없다. 대안이면 P3을 허용 fixture로 두고 `06f520e6`에서 위반 1로 실패하는 것을 본다. - **이번 수정 / 이전부터**: 이번 수정(r9에서는 설정을 통째로 뺐으므로 P3이 통과했다). - **증거**: E2 — 명령 1·2(탐침 P3·P3c). 문서 대조는 E1. +- **같은 모양(2차)**: 다른 리뷰(`3add4917`)가 Declined로 적은 경우도 같은 원인이다. `ARE_REQUEST_HANDLER_TYPES`가 `org.springframework.web.bind.annotation..`·`jakarta.servlet.http..`를 패키지째 담아, `@CrossOrigin`·`RequestMethod`(CORS 설정에서 흔함)나 `HttpServletRequest`를 쓰는 설정이 handler bean을 함께 등록해도 거짓 실패한다(E1). 고칠 때 이 모양도 허용 fixture로 둔다. ## Declined to judge - `ARE_REQUEST_HANDLER_TYPES`에 빠진 다른 타입(예: 리액티브 `org.springframework.web.server.WebFilter`·`WebHandler`): 이 템플릿은 서블릿 스택이고 WebFlux가 classpath에 없다. 목록 방식의 한계로 매뉴얼 07 `:128-129`가 적는다. RR7-01-01은 r9가 잡던 모양만 다룬다. - gRPC: 취소된 호출에서 carrier나 IAE로 끝나면 여전히 로그가 남는다. 문서(`src/adapter/inbound/grpc/README.md`)는 "인식 못 한 실패"에 대해서만 취소를 빼므로 어긋나지 않는다. - gRPC: 서비스가 raw status를 다른 예외로 감싸 던지면(`new IllegalStateException("…", statusException)`) 원인 사슬의 status 설명이 스택에 남는다. RR6-01-05가 약속한 것은 "서비스가 끝낸 raw status"라 범위 밖으로 봤다. 입력값 유출 정책을 넓힐지는 결정할 일이다. -- round6 01의 「Declined to judge」 7건이 README 17절에서 배정·결정으로 닫히지 않았다(README 18절 「멈춤 기준 상태」). +- round6 01의 「Declined to judge」 7건은 2차에서 판정했다(README 18.5절). 그중 둘이 아래 RR7-01-05·06이 됐다. ## 결론 @@ -139,3 +141,85 @@ Critical 0, Important 0, 회귀 1(RR7-01-01). 결함 2건, 모두 Minor, 모두 - RR6-01-01~09는 모두 닫혔다. 주장한 fixture·테스트가 있고 이름대로 본다. - 새 결함 둘은 RR6-01-01·02를 고친 방법에서 나왔다. 하나는 r9가 잡던 중첩 endpoint를 놓치는 회귀, 하나는 안내대로 해도 실패하는 거짓 실패다. + +## 2차 추가 결함 (2026-11-06, 총괄 요청) + +총괄이 세 가지를 더 맡겼다. 같은 커밋을 따로 본 리뷰(`claude/t1-baseline-7d623a` `3add4917`)의 발견 중 이 리뷰와 겹치지 않는 것, 다른 세션이 +코드 읽기로만 찾은 결함 후보 하나, round6 01의 「Declined to judge」 판정. 넘겨받은 발견은 그쪽 근거를 읽은 뒤 이 리뷰의 기준 커밋 +`06f520e6`에서 탐침을 다시 돌려 확인했다. + +### 2차 실행 + +desktop 임시 worktree `~/workspace/t1-r10-review`(`06f520e6`, 다시 만들고 끝나고 지움), 공유 잠금 아래. 로그 `~/t1-r10-review-logs/`, +탐침 코드와 결과는 공유 노트 `rr7-probes/pass2/`·`rr7-probes/results/pass2-06f520e6.txt`. + +| # | 명령 | 결과 | 직전 부하(1분) | +|---|---|---|---| +| 4 | `./gradlew :adapter:inbound:web:test --tests …Rr7LockTimeoutWebProbeTest` | rc=0. `GlobalExceptionHandler.handleUnknown`이 `LockAcquisitionTimeoutException`에 500 `INTERNAL_ERROR` `retryable=false` | 1.32 | +| 5 | `./gradlew :adapter:inbound:graphql:test --tests …Rr7LockTimeoutGraphQlProbeTest` | rc=0. `GraphQlWireErrorMapper.masking()`이 같은 예외를 `INTERNAL_ERROR`·`INTERNAL`·`retryable=false`로 | 1.73 | +| 6 | `./gradlew :adapter:inbound:grpc:test --tests "…GrpcExceptionHandlingInterceptorTest.rr7probe*"` (다른 리뷰의 탐침을 결과를 파일로 쓰게 바꿔 기존 테스트 클래스에 끼움) | rc=0. 던짐: `INTERNAL`, ERROR 한 줄에 `IllegalArgumentException: unknown recipient alice@example.com` 첨부. 넘김: `INVALID_ARGUMENT`, WARN 한 줄(메시지 없음) | 2.01 | + +### RR7-01-03 · Minor · gRPC 서비스가 `IllegalArgumentException`을 원인으로 든 raw status를 던지면 `INTERNAL_ERROR`로 답하고 그 메시지를 ERROR로 남긴다 — 같은 status를 `onError`로 넘기면 `BAD_PARAMETER`·WARN이다 + +- **출처**: 다른 리뷰 `3add4917` `round7/review.md` RR7-01-02. 그쪽 근거(코드 경로·탐침)를 확인하고 명령 6으로 다시 재현했다. +- **위치**: + - 코드: `src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcExceptionHandlingInterceptor.java:137`(`status.getCause() instanceof IllegalArgumentException` — 던진 경우 원인 자리에는 status 예외가 있다), `:153`(`closeWithError`가 던진 예외 자체를 status의 원인으로 둔다), `:156-178`(`logUnrecognised`가 `failureBehind`로 status 예외를 벗겨 그 뒤의 IAE를 붙인다). + - 문서: `src/adapter/inbound/grpc/README.md:157-158`("`IllegalArgumentException`은 … WARN 한 줄 … 메시지 없음"), `:160`("raw status는 `onError`로 넘겼든 던졌든"), `src/shared-contract/README.md:94-98`("네 전송 모두 … 메시지는 … 남기지 않고 예외도 붙이지 않는다"). +- **무엇이 틀렸나**: + - `onError(Status.INVALID_ARGUMENT.withCause(iae).asRuntimeException())`는 `close(Status.fromThrowable(t))`가 되어 status의 원인이 IAE다. `BAD_PARAMETER`·WARN. + - 같은 예외를 던지면 원인 자리에 status 예외가 온다. `:137` 판정이 IAE를 보지 못해 `INTERNAL_ERROR`로 답한다. + - 이어서 r10의 `failureBehind`가 status 예외를 벗기고 IAE를 ERROR 줄에 붙인다. 입력값이 든 메시지가 로그에 남는다. +- **발생 조건·영향**: 입력 검증 실패를 `Status.INVALID_ARGUMENT.withCause(e).asRuntimeException()`로 던지는 서비스(grpc-java의 흔한 모양). 클라이언트는 재시도할 수 없는 `INTERNAL`을 받고, 서버 로그에 입력값이 ERROR와 스택으로 남는다. grpc 어댑터는 기본 조립에 없어 Minor. +- **테스트가 못 본 이유**: r10의 테스트는 원인이 `IllegalStateException`인 raw status와 원인 없는 raw status만 던진다. +- **고치는 법**: `close`에서 판정용 원인을 `failureBehind(status.getCause())`로 한 번 구해 carrier·IAE 판정과 로그에 같은 값을 쓴다. 대안: `closeWithError`가 던진 예외가 `StatusRuntimeException`·`StatusException`이면 그 status를 그대로 쓰고 원인은 status의 원인으로 둔다. RED: 명령 6의 탐침을 "던짐과 넘김의 status·로그 줄이 같다"는 단언으로 옮긴다. 지금 `INTERNAL ≠ INVALID_ARGUMENT`로 실패한다. +- **이번 수정 / 이전부터**: 이전부터. r9도 같은 답을 했다. r10이 RR6-01-05를 고치며 이 경로를 다시 썼는데 이 경우를 놓쳤다. +- **증거**: E2 — 명령 6. r9 동작은 다른 리뷰의 E1. + +### RR7-01-04 · Important · `LockAcquisitionTimeoutException`은 오류 코드를 운반하는 타입이 아니고 받는 처리기도 없어, 409 `LOCK_ACQUISITION_TIMEOUT`(재시도 가능) 대신 500 `INTERNAL_ERROR`(재시도 불가)로 답한다 + +- **출처**: 다른 세션이 코드 읽기로 찾은 후보(총괄 전달). 명령 4·5로 확인했다. +- **위치**: + - 코드: `src/application-core/src/main/java/dev/caskeleton/application/lock/LockAcquisitionTimeoutException.java:13`(`extends RuntimeException`만, `ApiErrorCarrier` 아님), `:6-11`(Javadoc "The web adapter maps it to 409"), `src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/GlobalExceptionHandler.java:195-202`(carrier가 아니면 `INTERNAL_ERROR`), GraphQL `GraphQlWireErrorMapper.java:199-206`(`sharedCodeOf`도 carrier만). + - 계약·문서: `docs/registries/error-codes.yaml:777-785`(409, `retryable: true`, `retry_after_seconds: 1`), `docs/runbooks/lock-acquisition-timeout.md:15`(증상 "HTTP 409 with `error.code=LOCK_ACQUISITION_TIMEOUT`"), `src/application-core/README.md:574-580`("web adapter 가 `errorCode()` + 고정 client-safe 메시지로 409 를 만든다"). + - 테스트: `src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/LockAcquisitionTimeoutClassificationContractTest.java:20-27`(Javadoc "D7 forbids collapsing a lock-acquisition timeout to a generic 500"), `:84-90`(예외의 `errorCode()`만 본다). +- **무엇이 틀렸나**: + - 예외는 `errorCode()` 메서드를 갖지만 `ApiErrorCarrier`를 구현하지 않는다. 전송들은 `ApiErrorCarrier`인지로만 코드를 읽는다. + - 이 예외를 받는 `@ExceptionHandler`도, GraphQL·gRPC 매핑도 없다(grep: main 코드에서 이 타입을 아는 곳은 던지는 persistence-jpa lock 둘과 지표 decorator뿐). + - 그래서 web은 500 `INTERNAL_ERROR` `retryable=false`(명령 4), GraphQL은 `INTERNAL_ERROR`(명령 5)로 답하고 "unhandled exception"으로 ERROR를 남긴다. gRPC도 carrier가 아니라 `INTERNAL`이다(E1). + - 레지스트리·runbook·Javadoc·README는 409 재시도 가능을 약속한다. 분류 계약 테스트는 "일반 500으로 뭉개지 않는다"(D7)를 이름에 걸지만 enum과 레지스트리 행만 본다. +- **발생 조건·영향**: + - 조건: 파생 서비스가 분산 lock capability(`DistributedLockPort.tryAcquire`)를 요청 처리 경로에서 쓰고 경합이 생긴다. 템플릿 자체의 운영 코드에는 호출자가 없다. + - 영향: 클라이언트는 재시도하면 될 경합을 재시도 불가 500으로 받는다. 운영자는 runbook대로 409를 찾지만 500 `INTERNAL_ERROR`와 "unhandled exception" ERROR만 보인다. 공개 계약(오류 코드 레지스트리)과 다른 응답이라 Important다. +- **테스트가 못 본 이유**: 분류 계약 테스트가 enum·레지스트리만 보고, 실제 전송 응답을 보는 테스트가 없다(A6 — 이름이 말한 성질을 단언하지 않음). +- **고치는 법**: + - 권장: `LockAcquisitionTimeoutException`이 `ApiErrorCarrier`를 구현한다(`errorCode()`의 반환 타입을 `ApiErrorCode`로). 그러면 네 전송이 따로 고치지 않아도 409·`Retry-After: 1`·4xx라 로그 없음으로 답한다. + - 대안: web에 전용 `@ExceptionHandler`를 둔다. web만 고쳐지고 GraphQL·gRPC는 그대로라 권하지 않는다. + - RED: 명령 4의 탐침을 `GlobalExceptionHandlerTest`에 "409·`LOCK_ACQUISITION_TIMEOUT`·`retryable=true`·`Retry-After`" 단언으로 옮긴다. 지금 500으로 실패한다. 분류 계약 테스트에 "예외가 `ApiErrorCarrier`다"를 더한다. +- **이번 수정 / 이전부터**: 이전부터(r10이 바꾼 파일이 아니다). +- **증거**: E2 — 명령 4·5. gRPC는 E1. + +### RR7-01-05 · Minor · 다른 예외에 감싼 carrier를 web·GraphQL·STOMP는 못 보고 gRPC만 원인 사슬에서 찾아, 같은 실패의 응답 코드와 로그가 전송마다 다르다 + +- **출처**: round6 01 「Declined to judge」 첫째 항목(README 18.5절 판정 (c)). 응답 코드가 바뀌는 수정이라 방향은 소유자 결정이다(README 18.4절). +- **위치**: web `GlobalExceptionHandler.java:195-198`(`ex instanceof ApiErrorCarrier`), GraphQL `GraphQlWireErrorMapper.java:200`, STOMP `StompHandlerFailureLog.java:34`, gRPC `GrpcExceptionHandlingInterceptor.java:180-192`(`carrierOf`가 원인 사슬을 따라감). 약속: `src/shared-contract/README.md` 「ServerFailureLog」("전송은 같은 줄을 쓴다", persistence 실패는 분류만). +- **무엇이 틀렸나**: 서비스가 `PersistenceFailureException`을 다른 예외로 감싸 던지면 web·GraphQL·STOMP는 500 `INTERNAL_ERROR`로 답하고 "unhandled"로 원인 사슬째(SQL 원인 포함) ERROR를 남긴다. gRPC는 감싼 carrier의 코드로 답하고 분류만 남긴다. 같은 규칙(실패 → 코드·로그)이 전송마다 다시 구현돼 갈라졌다(A1). web 쪽은 A8(SQL 원인을 로그에 싣지 않는다)도 어긴다. +- **발생 조건·영향**: use case나 adapter가 carrier를 감싸 던질 때. 템플릿 코드에는 그런 곳이 없다(round6 01 확인). 같은 실패에 클라이언트가 받는 코드가 전송마다 다르고, web 로그에 SQL 값·제약 이름이 남는다. +- **테스트가 못 본 이유**: 전송 테스트가 모두 맨 위 carrier만 넣는다. +- **고치는 법**: shared-contract에 "원인 사슬의 첫 carrier"를 찾는 함수 하나를 두고 네 전송이 쓴다(gRPC의 `carrierOf`를 옮김). 방향 선택지는 README 18.4절. RED: 네 전송 테스트에 감싼 `PersistenceFailureException`을 넣어 코드와 로그 줄이 같음을 단언한다. +- **이번 수정 / 이전부터**: 이전부터. +- **증거**: E1(네 전송의 판정 코드). 실행 탐침 없음 — 판정이 `instanceof` 한 줄이라 코드로 결정적이다. + +### RR7-01-06 · Minor · STOMP `@MessageMapping`의 payload 변환·검증 실패(`MessageConversionException`, `MethodArgumentNotValidException`)를 ERROR로, 예외 메시지(입력 조각)까지 남긴다 + +- **출처**: round6 01 「Declined to judge」 다섯째 항목(README 18.5절 판정 (a)). +- **위치**: `src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/StompHandlerFailureLog.java:32-45`(carrier·IAE가 아니면 `log.error("unhandled failure in a STOMP message handler", failure)`). 기준: `docs/work/reference/defect-patterns.md` A8("클라이언트 탓 실패(입력 오류)는 WARN 한 줄로 남기고 입력값을 싣지 않는다"). +- **무엇이 틀렸나**: payload를 읽지 못하거나 검증에 실패한 메시지는 클라이언트 탓 실패다. r10은 IAE만 WARN 한 줄로 바꿨고, 변환·검증 실패는 여전히 ERROR와 예외 전체로 남는다. Jackson 변환 실패 메시지는 받은 JSON 조각을 담는다. +- **발생 조건·영향**: 잘못된 JSON이나 검증에 걸리는 payload를 보내는 클라이언트마다 ERROR 한 줄과 스택이 남고, 입력 조각이 로그에 실린다. 경보가 ERROR에 걸리면 클라이언트 실수가 사고로 보인다. +- **테스트가 못 본 이유**: `StompHandlerFailureLogTest`에 변환·검증 실패 케이스가 없다. +- **고치는 법**: `MessageConversionException`·`MethodArgumentNotValidException`(Spring messaging)을 IAE와 같이 `BAD_PARAMETER`/`VALIDATION_FAILED`의 WARN 한 줄(타입만)로 남긴다. 프레임 응답은 그대로(보내지 않음). RED: 실제 `WebSocketAnnotationMethodMessageHandler`로 깨진 JSON payload를 보내 ERROR가 남는 것을 본다(round6 01 탐침 `Rr6StompProbeTest`의 모양). +- **이번 수정 / 이전부터**: 이전부터(r10이 같은 클래스에 IAE만 더함). +- **증거**: E1. 실행 탐침은 돌리지 않았다(Spring이 변환 실패를 `@MessageExceptionHandler`로 넘기는 경로는 round6 01이 같은 handler로 확인한 경로와 같다). + +### 2차 반영 뒤 결론 + +Critical 0, Important 1(RR7-01-04), 회귀 1(RR7-01-01). 결함 6건: 이번 수정 2(RR7-01-01·02), 이전부터 4(RR7-01-03~06). diff --git a/docs/reviews/2026-11-03-rereview/round7/02-idempotency-outbound.md b/docs/reviews/2026-11-03-rereview/round7/02-idempotency-outbound.md index 0f353c58..da77e813 100644 --- a/docs/reviews/2026-11-03-rereview/round7/02-idempotency-outbound.md +++ b/docs/reviews/2026-11-03-rereview/round7/02-idempotency-outbound.md @@ -41,7 +41,7 @@ docs/manual/05-idempotency.md | # | 명령 | 결과 | 직전 부하(1분) | |---|---|---|---| -| 1 | `./gradlew … :application-core:test :adapter:outbound:redis-runtime:test :adapter:outbound:cache-redis:test :adapter:outbound:persistence-jpa:test … --continue` (`06f520e6`, desktop) | README 18.2절 | README 18.2절 | +| 1 | `./gradlew … :application-core:test :adapter:outbound:redis-runtime:test :adapter:outbound:cache-redis:test :adapter:outbound:persistence-jpa:test … --continue` (`06f520e6`, desktop) | README 18.3절 | README 18.3절 | 실 Redis·실 PostgreSQL 계약 lane(`redisContainerContractTest`, `jpaPlatformContractTest`의 멱등성 계약, `postgresqlIdempotencyIntegrationTest`)은 다시 돌리지 않았다. 17.2절의 `2c692554` 실행이 마지막이다(E0). 이 영역에서 결함을 찾지 못해 실 vendor로 확인할 의심이 없었다. @@ -61,8 +61,8 @@ docs/manual/05-idempotency.md ## 못 본 것 - 실 Redis·실 PostgreSQL에서의 재실행(위 설명). -- 배포 중 섞인 버전(옛 인스턴스의 `TRANSITION`은 재생 핸들 시작에 `ALREADY`): round6 02의 Declined to judge에 이미 있다. README 17절에서 - 닫히지 않았다(README 18절). +- 배포 중 섞인 버전(옛 인스턴스의 `TRANSITION`은 재생 핸들 시작에 `ALREADY`): round6 02의 Declined to judge에 이미 있다. 2차에서 + 결함 아님으로 닫았다(README 18.5절). ## 항목 재확인 @@ -86,9 +86,28 @@ docs/manual/05-idempotency.md - 같은 owner token에 다른 operation id로 온 claim이 재시도 가능 실패·lease 지난 claim을 만나면, 전에는 `OwnerOperationConflict`(500)였고 이제 넘겨받는다(넘겨받기가 같은 owner 판정보다 앞이 되어서). 아무것도 실행되지 않은 기록이라 안전하고, 계약에 이 경우 케이스가 없다. 동작 변경으로 적어 둔다. 업그레이드 안내에는 없다. -- round6 02의 「Declined to judge」 6건이 README 17절에서 배정·결정으로 닫히지 않았다(README 18절 「멈춤 기준 상태」). +- round6 02의 「Declined to judge」 6건은 2차에서 판정했다(README 18.5절). 그중 하나가 아래 RR7-02-01이 됐다. ## 결론 Critical 0, Important 0, 회귀 0. 결함 0건. RR6-02-01~05는 모두 닫혔다. 바뀐 판정 순서와 시작 확인 조건은 세 저장소·두 fake에서 같고, 같은 attempt의 늦은 시작·재생 핸들 시작으로 작업이 두 번 도는 길은 남지 않았다(E1). 실 vendor 재실행은 하지 않았다. + +## 2차 추가 결함 (2026-11-06, 총괄 요청) + +round6 02의 「Declined to judge」를 판정하며(README 18.5절) 하나를 결함으로 올렸다. 다른 리뷰(`3add4917`)는 이 영역에서 새 결함을 적지 않았다. + +### RR7-02-01 · Minor · `ClientRuntimeRegistry.close()`는 닫는 스레드가 interrupt 상태면 drain 스레드가 끝났는지 보지 않고 정상으로 돌아온다 — "돌아오면 스레드가 남지 않는다"는 약속과 다르다 + +- **출처**: round6 02 「Declined to judge」 둘째 항목(README 18.5절 판정 (a)). +- **위치**: `src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/profile/ClientRuntimeRegistry.java:164-171`(Javadoc "Joining the thread is what makes 'no thread left' true when this returns"), `:181`·`:186`(`awaitTermination`·`join`은 interrupt 상태면 바로 `InterruptedException`), `:192-194`(잡아서 flag만 되살리고 반환), `:148-161`(`close()`는 그대로 정상 종료). +- **무엇이 틀렸나**: 16.1절 수정이 "close가 돌아오면 drain 스레드가 없다"를 join으로 보장했다. 그런데 닫는 스레드가 이미 interrupt 상태면 기다리는 첫 호출이 곧바로 예외를 내고, 그 catch는 flag를 되살린 뒤 아무 확인 없이 돌아온다. `close()`는 예외 없이 끝나지만 drain 스레드는 살아 있을 수 있다. 다른 실패 경로(`awaitTermination` 시간 초과, join 뒤 생존)는 `IllegalStateException`을 던지는데 interrupt 경로만 조용하다(A14). +- **발생 조건·영향**: interrupt된 스레드에서 registry를 닫는 경우(종료 훅을 interrupt로 끊는 런처, 테스트 프레임워크의 시간 제한 interrupt 뒤 정리). Spring 기본 종료 스레드는 보통 interrupt되지 않아 드물다. 그때 스레드가 남아도 호출자는 모른다. +- **테스트가 못 본 이유**: `ClientRuntimeRegistryTest`의 두 스레드 테스트가 interrupt되지 않은 스레드에서만 닫는다. +- **고치는 법**: interrupt를 받으면 남은 마감까지 interrupt를 무시하고 기다린 뒤(끝에 flag 복원) 스레드 생존을 확인하고, 살아 있으면 다른 경로처럼 `IllegalStateException`을 던진다. 대안: interrupt 경로에서도 바로 `IllegalStateException("interrupted before the drain thread exited")`를 던진다(더 단순하지만 정상 종료가 실패로 보일 수 있다). RED: 테스트 스레드에 `Thread.currentThread().interrupt()` 뒤 `close()`를 부르고, 돌아온 직후 drain 스레드가 살아 있으면 예외가 있었어야 함을 단언한다. +- **이번 수정 / 이전부터**: 이전부터(r9 16.1절 수정). r10이 바꾼 파일이 아니다. +- **증거**: E1(코드 경로). 실행 탐침은 돌리지 않았다 — interrupt 상태에서 `awaitTermination`이 바로 던지는 것은 `ThreadPoolExecutor` 계약이고, 그 뒤 경로는 catch 블록 하나라 코드로 결정적이다. + +### 2차 반영 뒤 결론 + +Critical 0, Important 0, 회귀 0. 결함 1건(RR7-02-01, Minor, 이전부터). 멱등성 쪽 r10 변경에서 찾은 새 결함은 여전히 0이다. diff --git a/docs/reviews/2026-11-03-rereview/round7/03-persistence.md b/docs/reviews/2026-11-03-rereview/round7/03-persistence.md index e41a5798..3ff9ae39 100644 --- a/docs/reviews/2026-11-03-rereview/round7/03-persistence.md +++ b/docs/reviews/2026-11-03-rereview/round7/03-persistence.md @@ -118,7 +118,7 @@ desktop 임시 worktree `~/workspace/t1-r10-review`(`06f520e6`), 공유 잠금 - `JpaProductionArchitectureTest`의 Flyway 규칙은 `Flyway.configure()`·`Flyway.configure(ClassLoader)` 호출만 본다. `new FluentConfiguration()`·`new ClassicConfiguration()`으로 만든 Flyway는 지나간다. 문서(`persistence-jpa/CLAUDE.md:100-104`, 매뉴얼 04 `:122-124`)는 "`Flyway.configure()`를 부르면 실패한다"로 정확히 적는다. 생성자 경로를 막을지는 규칙 범위 결정이라 판단하지 않았다. - 세션 잠금에서 연결이 끊기지 않은 채 unlock이 실패하면(Flyway가 "Unable to release PostgreSQL advisory lock"을 로그로만 남기는 경우) 잠금이 Hikari 풀의 연결에 남을 수 있다. Flyway 코드 경로로만 본 것이고 재현하지 않았다. 트랜잭션 잠금에는 없던 위험이다. 결정(Flyway 공식 옵션 채택)의 전제를 바꿀 만한 증거는 아니다. -- round6 03의 「Declined to judge」 10건 중 중첩 블록 주석은 r10이 고쳤고, 나머지 9건은 README 17절에서 배정·결정으로 닫히지 않았다(README 18절 「멈춤 기준 상태」). +- round6 03의 「Declined to judge」 10건은 2차에서 판정했다(README 18.5절). 그중 하나가 아래 RR7-03-05가 됐다. ## 결론 @@ -127,3 +127,72 @@ Critical 0, Important 0, 회귀 0. 결함 2건, 모두 Minor. - 이번 수정: RR7-03-01(ledger IT의 없는 예외 장치 안내). - 섞임: RR7-03-02(REINDEX 설명 — 이전부터 있던 넓은 문장을 이번 수정이 이유를 붙여 네 곳으로 넓힘). - RR6-03-01~04는 닫혔고, RR6-03-05는 부분이다(위 두 결함). 세션 잠금 전제(한 연결, 재시도 대기)는 Flyway 코드와 맞는다. + +## 2차 추가 결함 (2026-11-06, 총괄 요청) + +같은 커밋을 따로 본 리뷰(`claude/t1-baseline-7d623a` `3add4917`, `round7/review.md`)의 03 영역 발견 둘을 넘겨받았다. 그쪽의 RR7-03-01·02는 이 +리뷰의 RR7-03-01·02와 번호만 같고 다른 결함이라 새 번호를 붙였다(README 18.2절 대응표). 그쪽 탐침(공유 노트 `r7-probes/probe/pg/`)과 같은 +모양을 이 리뷰의 기준 커밋 `06f520e6`에서 다시 돌렸고, 고치는 법을 확인하려고 "실패 이력 행 삭제" 경우를 하나 더했다. round6 03의 +「Declined to judge」 판정에서 하나를 더 올렸다. + +### 2차 실행 + +desktop 임시 worktree `~/workspace/t1-r10-review`(`06f520e6`), 공유 잠금 아래. 탐침 `Rr7CicRecoveryProbeIntegrationTest`를 임시 lane +`rr7CicProbe`로 등록해 실 PostgreSQL(Testcontainers)에서 돌렸다. 모두 `FlywaySchemaPolicy.configure()`(세션 잠금)로 적용했다. 탐침 코드는 +공유 노트 `rr7-probes/pass2/`, 결과는 `rr7-probes/results/pass2-06f520e6.txt`. + +| # | 명령 | 결과 | 직전 부하(1분) | +|---|---|---|---| +| 4 | `./gradlew :adapter:outbound:persistence-jpa:rr7CicProbe` 첫 실행 | rc=1, 3초 — 내 탐침의 컴파일 오류(타입). 고쳐 다시 돌림 | 2.01 | +| 5 | 같은 명령 | rc=0, 15초. 아래 표 | 2.66 | + +V1은 `probe` 테이블, 일반 인덱스, `note`가 겹치는 행 하나(2001, `'note 1'`)를 만든다. + +| 경우 | V2 | 결과 | +|---|---|---| +| 섞임, `.sql.conf` 없음 | `INSERT (3001)` + `CREATE UNIQUE INDEX CONCURRENTLY` | Flyway가 실행 전에 거부("Detected both transactional and non-transactional statements"). 행 3001 없음, 이력 V1만 | +| 섞임, `executeInTransaction=false` | 같음 | `FlywayMigrateException`. **행 3001이 남음**(부분 적용), `ix_probe_note_u valid=false`, 이력 `2 success=false` | +| 복구: 가이드대로 | 유일 인덱스 하나 + `.sql.conf` → 실패 → 겹친 행 삭제, `DROP INDEX` → 재배포 | `FlywayValidateException: … Detected failed migration to version 2`. 이력 `2 success=false`가 그대로 | +| 복구: 실패 행도 삭제 | 위 + `DELETE FROM flyway_schema_history WHERE version = '2' AND NOT success` → 재배포 | 성공. `ix_probe_note_u valid=true`, 이력 `2 success=true` | + +### RR7-03-03 · Important · 실패한 동시 인덱스 마이그레이션의 복구를 "`DROP INDEX` 하나"라고 안내하지만, 남은 실패 이력이 다음 배포를 막고 runbook은 그 행을 지우는 것을 금지한다 + +- **출처**: 다른 리뷰 `3add4917` RR7-03-02. 그쪽 근거(가이드·runbook 문장, 탐침)를 확인하고 명령 5로 다시 재현했다. +- **위치**: + - 안내(같은 문장 세 벌): `docs/jpa/migration-guide.md:147-149`, `src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/ConcurrentIndexMigrationInspector.java:18-19`·`:71-73`(`requireIsolatedStatement` Javadoc), `:92`(실패 메시지), `docs/study/postgresql-jpa-walkthrough.ko.md:1369-1371`. + - 막는 규칙: `docs/runbooks/migration-failed.md:42-66`(실패 분류에 이 경우가 없다), `:95`("delete or rewrite Flyway history to make validation green" 금지), `:107`(history repair 전 DB 소유자에게). +- **무엇이 틀렸나**: + - 트랜잭션 밖에서 돈 마이그레이션이 실패하면 Flyway는 이력에 `success=false` 행을 남긴다. + - 다음 배포의 validate는 그 행 때문에 실패한다. 무효 인덱스를 지우고 원인 데이터를 고쳐도 같다(명령 5 셋째 경우). + - 실패 행까지 지우면 재배포가 성공한다(넷째 경우). 그런데 문서 어디에도 그 단계가 없고, runbook은 이력 수정을 금지한다. +- **발생 조건·영향**: 가이드대로 쓴 동시 인덱스 마이그레이션이 실패한다(유일 인덱스의 중복 값, deadlock, `statement_timeout`, 운영자 취소). 운영자가 안내대로 `DROP INDEX` 뒤 다시 배포해도 기동이 또 멈추고, runbook에서 이 실패를 찾을 수 없다. r10 전에는 Flyway 기본 잠금 때문에 빌드가 실패까지 가지 못하고 멈췄다. r10이 빌드를 실제로 돌게 해 이 경로가 흔해졌다. 운영자에게 효과 없는 조치를 시키는 문서라 Important다. +- **테스트가 못 본 이유**: 동시 인덱스 IT는 성공하는 빌드와 상한에 걸려 취소되는 경우만 본다. 실패 뒤 재배포를 돌린 테스트가 없다. +- **고치는 법**: 정책 예외라 소유자 결정이 먼저다(README 18.4절). 권장안은 세 문장을 "무효 인덱스를 `DROP INDEX`하고, 그 버전의 실패 이력 행만 지운 뒤(`DELETE FROM WHERE version = '' AND NOT success`), 원인을 고쳐 다시 배포한다"로 고치고, runbook 「Classify the failure」에 이 경우와 SQL을, 「Do not」에 이 한 가지 예외를 적는 것이다. 성공한 행과 checksum은 건드리지 않는다. RED: 명령 5의 셋째 경우를 IT로 옮기고 문서 절차(넷째 경우)를 그대로 실행하게 한다. +- **이번 수정 / 이전부터**: 이전부터(가이드 문장은 `6d27356e`부터). r10이 바로 옆 문단을 고쳐 쓰고 빌드를 실제로 돌게 했다. +- **증거**: E3 — 명령 5(실 PostgreSQL, Flyway 11.14.1). 고치는 법의 SQL도 E3(넷째 경우). + +### RR7-03-04 · Minor · 학습 문서와 검사기 Javadoc이 "섞인 파일은 부분 적용되지 않는다"고 적지만, 가이드가 요구하는 `.sql.conf`를 붙이면 부분 적용된다 + +- **출처**: 다른 리뷰 `3add4917` RR7-03-01. 명령 5로 다시 재현했다. +- **위치**: `docs/study/postgresql-jpa-walkthrough.ko.md:1346-1348`(r10이 쓴 문장), `ConcurrentIndexMigrationInspector.java:16-19`(Javadoc: "Next to any other statement, one Flyway runs outside a transaction makes Flyway refuse the whole script before it runs any of it"). +- **무엇이 틀렸나**: Flyway의 `mixed=false` 거부는 `.sql.conf`가 트랜잭션 여부를 정하지 않은 파일에만 걸린다. 가이드·검사기 `validate`는 동시 인덱스 문장마다 `executeInTransaction=false`를 적으라고 한다. 그 설정이 붙은 섞인 파일은 Flyway가 문장마다 따로 커밋해 앞 문장이 남는다(명령 5 둘째 경우: 행 3001이 남고 무효 인덱스와 실패 이력이 생김). +- **발생 조건·영향**: 학습 문서를 믿고 `.sql.conf`를 붙인 채 다른 문장과 동시 인덱스를 섞는다. `requireIsolatedStatement`가 그 파일을 거부하지만 서비스가 마이그레이션 테스트를 둘 때만 돈다(가이드 `:146-147` "nothing checks it at startup"). 그 밖에서는 부분 적용과 실패 이력(RR7-03-03의 복구 문제)이 남는다. 문서 오류라 Minor. +- **테스트가 못 본 이유**: `.sql.conf`가 있는 섞인 파일을 Flyway로 끝까지 돌린 테스트가 없다. +- **고치는 법**: 두 곳을 "`.sql.conf` 없이 섞으면 Flyway가 실행 전에 거부한다. `executeInTransaction=false`를 붙이고 섞으면 문장마다 따로 커밋해 부분 적용된다. 그래서 동시 인덱스 문장은 혼자 둔다"로 고친다. 회귀 방지로 명령 5의 첫째·둘째 경우를 IT에 사실로 고정한다. +- **이번 수정 / 이전부터**: 이번 수정(RR6-03-05를 고치며 쓴 문장). +- **증거**: E3 — 명령 5. + +### RR7-03-05 · Minor · 잠금 대기 검사기 Javadoc은 `VACUUM FULL`을 늘 거부한다고 적지만, `.sql.conf`가 `executeInTransaction=true`를 정하면 `SET LOCAL` 뒤의 `VACUUM FULL`을 통과시킨다 + +- **출처**: round6 03 「Declined to judge」 셋째 항목(README 18.5절 판정 (a)). +- **위치**: `src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/LockWaitMigrationInspector.java:62-64`(Javadoc: "A locking statement that cannot run in a transaction itself ({@code VACUUM FULL}, …) can never be bounded and is refused"), `:248-252`(설정이 `IN_A_TRANSACTION`이면 `SET LOCAL` 범위를 적용해 상한 있는 것으로 판정). +- **무엇이 틀렸나**: `.sql.conf`에 `executeInTransaction=true`를 쓰면 검사기는 그 파일을 트랜잭션 안이라 보고 `SET LOCAL` 뒤의 `VACUUM FULL`을 상한 있는 문장으로 통과시킨다. Javadoc의 "늘 거부"와 다르다. +- **발생 조건·영향**: 그 조합의 마이그레이션은 PostgreSQL이 배포 때 `25001`로 거부해 잠금 대기는 생기지 않는다. 검사기의 목적(상한 없는 잠금 대기를 막음)은 지켜지고, 검사기가 먼저 알려 주지 못할 뿐이다. 문서와 동작의 차이라 Minor. +- **테스트가 못 본 이유**: `LockWaitMigrationInspectorTest`에 `executeInTransaction=true` + `VACUUM FULL` 케이스가 없다. +- **고치는 법**: 권장: 트랜잭션 안에서 돌 수 없는 문장(`VACUUM`, 비동시 `REINDEX SCHEMA|DATABASE|SYSTEM` 등)이 `executeInTransaction=true` 파일에 있으면 검사기가 "PostgreSQL이 배포 때 거부한다"는 이유로 거부한다. 대안: Javadoc을 "설정이 트랜잭션을 정하지 않은 파일에서"로 좁힌다. RED: 그 조합 파일을 `unboundedLockingStatements(Path)`에 넣어 빈 결과가 나오는 것을 본다. +- **이번 수정 / 이전부터**: 이전부터. +- **증거**: E1(판정 코드). round6 03도 같은 판정을 코드 위치로 적었다(E0). 실행 탐침은 돌리지 않았다. + +### 2차 반영 뒤 결론 + +Critical 0, Important 1(RR7-03-03), 회귀 0. 결함 5건: 이번 수정 2(RR7-03-01·04), 섞임 1(RR7-03-02), 이전부터 2(RR7-03-03·05). diff --git a/docs/reviews/2026-11-03-rereview/round7/04-build-logic-shell.md b/docs/reviews/2026-11-03-rereview/round7/04-build-logic-shell.md index cf37c3c2..016437a6 100644 --- a/docs/reviews/2026-11-03-rereview/round7/04-build-logic-shell.md +++ b/docs/reviews/2026-11-03-rereview/round7/04-build-logic-shell.md @@ -73,7 +73,7 @@ src/build-logic/build.gradle src/build-logic/README.md - 한 번 걸린 `trap 'exit 0' EXIT`를 `trap - EXIT`로 풀어도 판독기는 뒤 명령을 계속 세지 않는다. 거짓 실패 쪽이고 이 모양을 쓰는 workflow는 드물다. - `kill $$`, `kill -TERM 0`처럼 셸을 신호로 끝내는 명령: 판독기가 보지 않는다. 신호로 끝난 단계는 실패로 끝나므로 거짓 통과가 아니다. -- round6 04의 「Declined to judge」 7건이 README 17절에서 배정·결정으로 닫히지 않았다(README 18절 「멈춤 기준 상태」). 그중 경로·브랜치 필터 항목은 05의 RR7-05-01과 겹친다. +- round6 04의 「Declined to judge」 7건은 2차에서 판정했다(README 18.5절). 그중 경로·브랜치 필터 항목은 05의 RR7-05-01로 합쳤다. ## 결론 diff --git a/docs/reviews/2026-11-03-rereview/round7/05-build-logic-workflow.md b/docs/reviews/2026-11-03-rereview/round7/05-build-logic-workflow.md index 348ef811..d5d954d3 100644 --- a/docs/reviews/2026-11-03-rereview/round7/05-build-logic-workflow.md +++ b/docs/reviews/2026-11-03-rereview/round7/05-build-logic-workflow.md @@ -79,7 +79,7 @@ desktop 임시 worktree `~/workspace/t1-r10-review`(`06f520e6`), 공유 잠금 - **발생 조건·영향**: 파생 서비스가 무거운 단계(`integrationCheck` 등)를 비용 때문에 `paths:` 필터 workflow로 옮긴다. 검사는 통과하고, 필터 밖 변경에서는 그 단계가 돌지 않는다. 메시지와 업그레이드 안내가 약속한 "매 변경"과 다르다. - **테스트가 못 본 이유**: `WorkflowGradleInvocationsTest`의 trigger 케이스는 이벤트 이름·`types`·`workflow_call`·`needs`만 다룬다. 필터 케이스가 없다. - **이번 수정 / 이전부터**: 섞임. 필터를 읽지 않는 동작은 이전부터다(round6 04 「Declined to judge」 첫 줄: "어떤 필터가 충분한지는 저장소 정책이라 판단하지 않았다"). "매 push·pull request·schedule"이라는 약속은 이번 수정이 메시지·문서에 썼다. -- **고치는 법** — 정책 선택이 먼저다(README 18절 「결정이 필요한 것」): +- **고치는 법** — 정책 선택이 먼저다(README 18.4절 「결정이 필요한 것」): - 권장(a): `paths:`·`paths-ignore:`가 붙은 trigger는 "매 변경"이 아니므로 그 trigger만으로는 세지 않는다. 이유는 2번(돌지 않을 수 있음). `branches:` 필터는 기본 브랜치를 포함하면 센다. 이 repo의 단계 명령은 필터 없는 workflow에 있어 판정이 바뀌지 않는다. - 대안(b): 동작은 두고 메시지·B-36을 "change trigger 중 하나로 시작하는 workflow(경로 필터는 보지 않는다)"로 고친다. 필터의 충분성은 저장소 책임으로 문서에 적는다. - RED 테스트 모양: (a)면 탐침 workflow를 `WorkflowGradleInvocationsTest`에 넣고 `uncountedReason`이 null이 아님을 단언한다. `06f520e6`에서 실패한다(탐침 결과). From 2c8a359d322bea118342522d6fe72112232a9876 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 6 Nov 2026 22:57:15 +0900 Subject: [PATCH 16/71] =?UTF-8?q?docs(work):=20=EC=86=8C=EC=9C=A0=EC=9E=90?= =?UTF-8?q?=20=EA=B2=B0=EC=A0=95=20=EB=84=A4=20=EA=B1=B4=EC=9D=84=20?= =?UTF-8?q?=EA=B2=B0=EC=A0=95=20=EC=83=89=EC=9D=B8=EC=97=90=20=EC=A0=81?= =?UTF-8?q?=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit round7 확인 리뷰와 멱등 저장소 수정(t5)이 소유자 결정 네 건을 남겼고, 소유자가 2026-11-06 모두 권하는 안으로 정했다. 다음 수정 묶음이 다시 묻지 않도록 결정 색인의 해당 절에 내용과 출처를 적는다. - 계약·오류: 네 전송이 원인 사슬의 첫 carrier를 본다 - 멱등성: 넘겨받기 전 핸들의 재전송은 적용한 핸들에게만 확인한다, 해제된 핸들의 start는 ABSENT와 NOT_OWNER를 둘 다 받는다 - 영속성: 실패한 동시 인덱스 마이그레이션은 그 버전의 실패 이력 행만 지우고 다시 배포한다 - 빌드·게이트: paths 필터 trigger만 있는 workflow는 단계 실행으로 세지 않는다 검증: scripts/check-work-docs.py rc=0. --- docs/work/reference/decisions.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/work/reference/decisions.md b/docs/work/reference/decisions.md index c77ee676..2abff16a 100644 --- a/docs/work/reference/decisions.md +++ b/docs/work/reference/decisions.md @@ -82,6 +82,7 @@ | Draft-12 offset 불일치 | problem 문서는 프로토콜 예외로 유지 | 소유자 | 결정 12 | | 알림 category 생략 | 거부(400), 판정은 유스케이스 | 소유자 | 결정 13 | | 오류 코드 로그 레벨 | `error-codes.yaml`에 `log_level` 칸을 두지 않는다. 레벨은 실패 종류·경로가 정한다(`ServerFailureLog`, 보안 필터 `AuthErrorResponseWriter`). 칸이 다시 생기면 `OperationalErrorRegistryContractTest`가 실패한다. 보안 필터는 5xx(`AUTH_JWKS_UNAVAILABLE`·`INTERNAL_AUTH_MISCONFIGURATION`)를 ERROR, 4xx를 WARN으로 남긴다. 401 서명·issuer·audience 불일치는 WARN | 소유자 | 2026-11-06, `docs/superpowers/specs/2026-11-06-error-code-log-level-design.md` 10절 | +| 감싼 carrier를 전송이 읽는 법 | web·GraphQL·STOMP·gRPC 네 전송 모두 원인 사슬의 첫 carrier를 본다. 감싼 carrier의 응답이 500 `INTERNAL_ERROR` 대신 그 carrier의 코드가 된다 | 소유자 | `1103` 18.4절(RR7-01-05), 2026-11-06 | ### 2.4 멱등성 @@ -100,6 +101,8 @@ | complete 재생 판정 | 완료 확인은 같은 owner token에만 준다. 같은 operation id를 쓴 다른 attempt의 늦은 complete는 `NOT_OWNER` | 기본값(2026-11-06) | Redis TRANSITION에 맞춤, `IdempotencyStoreContract` | | 기록 없는 release | 저장소 셋 다 `ABSENT`로 답한다(확인할 수 없는 해제를 확인하지 않는다). Redis release도 핸들 revision을 본다. release한 기록을 지울지 남길지는 저장소가 정하므로 release 재시도 답은 `ABSENT`(Redis·fake)와 `ALREADY_RELEASED_SAME_OPERATION`(PostgreSQL)으로 갈린다 | 기본값(2026-11-06) | JPA 설계 22.2 "affected row가 0이면 성공으로 간주하지 않는다", `IdempotencyStoreContract` | | Redis 연결 예산 | 캐시 조건부 쓰기는 멱등성·lease와 다른 연결 예산(SCRIPT lane) | 위임 | `1103` 4절(RR-04-02) | +| 넘겨받기 전 핸들의 재전송 | 같은 attempt를 넘겨받기 전의 핸들이 이미 일어난 complete·markFailed를 다시 보내면, 그 전이를 실제로 적용한 핸들에게만 "이미 처리됨"으로 확인하고 그 밖의 핸들은 거절한다. Redis TRANSITION 주석의 원래 의도를 뒤집는다 | 소유자 | t5 보고 「남은 문제」, 2026-11-06 | +| 해제된 핸들로 start | 계약은 `ABSENT`와 `NOT_OWNER`를 둘 다 받는다. 포트 Javadoc에 그렇게 적는다 | 소유자 | t5 보고 「남은 문제」, 2026-11-06 | ### 2.5 영속성 @@ -114,6 +117,7 @@ | Flyway PostgreSQL 잠금 | 세션 수준(`transactional-lock: false`). 전제: Hikari 직접 연결. transaction-mode PgBouncer 뒤에서는 깨진다 | 기본값 | `1103` 17절 r10-03(RR6-03-01) | | persistence-jpa 설정 prefix | 플랫폼 자체는 `app.persistence-jpa.*`, 공유 기능은 기능 트리(`app.outbox`·`app.lock`·`app.realtime.replay`) | 소유자 | 결정 36 | | 분산 lock·lease | 둘 다 capability로 유지, 공통 계약 테스트 | 소유자 | 결정 8 | +| 실패한 동시 인덱스 마이그레이션 복구 | runbook에 예외 하나를 둔다: 그 버전의 실패 이력 행(`success = false`)만 지우고 다시 배포한다. `flyway repair`는 계속 쓰지 않는다 | 소유자 | `1103` 18.4절(RR7-03-03), 2026-11-06 | ### 2.6 샘플·메시징·보안·설정 @@ -170,6 +174,7 @@ | objectstorage | provider type 하나 추가 | 위임 | `1101` 15절(05-16) | | 에이전트가 원칙에서 바로 정한 것 | Kafka 주소 키 하나, composition이 persistence-jpa를 함께 가져옴 등 7건 | 기본값 | `docs/reviews/2026-09-25-review-followup-status.md` 「소유자 결정」 끝 목록 | | 묶음별 기본값 | 각 라운드 처리 표의 「결정」 칸(예: SES replay 창 1h, Retry-After 30) | 기본값 | `1101` 13·14·16절, `1103` 6·10·12·15·16·17절 표 | +| 경로 필터 workflow와 단계 검사 | `paths:`·`paths-ignore:` trigger만 있는 workflow는 strict lane 단계 실행으로 세지 않는다 | 소유자 | `1103` 18.4절(RR7-05-01), 2026-11-06 | ## 3. 새 결정을 기록하는 법 From b872b0ea931f6e26daf28b84f16a77c6b7ef5e90 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 6 Nov 2026 23:18:33 +0900 Subject: [PATCH 17/71] =?UTF-8?q?fix(scripts):=20=EC=9D=B4=EB=A0=A5=20?= =?UTF-8?q?=EA=B2=80=EC=82=AC=EA=B0=80=20"=EB=A6=AC=EB=B7=B0=2002-01"?= =?UTF-8?q?=C2=B7"1=EB=9D=BC=EC=9A=B4=EB=93=9C=2006-01"=20=EA=BC=B4?= =?UTF-8?q?=EC=9D=84=20=EC=9E=A1=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: check-work-docs.py --history는 날짜 접두어(MMDD/), RR 접두어, 묶음 이름, round 폴더, 번호만 쓴 결정, 커밋 sha만 이력 ID로 본다. 그래서 "리뷰 02-01 결정", "1라운드 06-01·06-03", "리뷰 README 13절"처럼 날짜 접두어 없이 쓴 리뷰 번호를 놓친다. 2026-11-06 docs/manual 이력 걷어내기 시험에서 --history가 0을 냈는데, 손으로 찾으니 16줄이 남아 있었다. 고른 방법: 패턴 셋을 더한다. - 리뷰·라운드·review 낱말 뒤 20자 안에 홀로 선 NN-NN. 2026-11-01 같은 날짜의 일부는 홀로 선 번호가 아니라 잡지 않는다 - 한국어 라운드 번호(1라운드, 라운드6) - 리뷰 README 절 번호(리뷰 README 13절) 버린 대안: 앞말 없이 모든 NN-NN을 잡기. 장 번호·시각 범위 같은 보통 숫자까지 잡아 오탐이 많다. 위험·한계: 검사는 아는 꼴만 잡는다. 다른 꼴은 걷어낸 뒤 grep으로 한 번 더 읽는다(docs-writing.md 자주 하는 실수). 이 커밋 뒤 --history docs/manual은 16줄을 내고 rc=1이 된다. 그 16줄은 이번에 고치지 않는다. 다음 cold-read 시험 과제다. 기본 모드(docs/work 본문, 루트 CLAUDE.md)는 0줄 그대로다. 검증: - 고치기 전 python3 scripts/check-work-docs.py --history docs/manual 결과 0줄, rc=0 - 고친 뒤 같은 명령 결과 16줄, rc=1. 2026-11-06 시험 세션이 손으로 찾은 16줄과 같다 - 오탐 시험 12건(보통 문장 7, 이력 5)이 모두 기대대로 나왔다 - 기본 모드 rc=0, 본문 이력 0줄. desktop worktree에서도 같다 --- scripts/check-work-docs.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/scripts/check-work-docs.py b/scripts/check-work-docs.py index 0a40e226..ed88b94b 100755 --- a/scripts/check-work-docs.py +++ b/scripts/check-work-docs.py @@ -81,6 +81,15 @@ HISTORY_PATTERNS = [ ("review round prefix (RR-, RR2-, ...)", re.compile(r"\bRR\d*-", re.ASCII)), ("fix bundle name (r2-05a, r9-a, r10-03)", re.compile(r"\br\d{1,2}-(?:\d{2}[a-z]?|[A-Za-z])\b", re.ASCII)), ("review round folder name (round6)", re.compile(r"\bround\d+\b", re.ASCII)), + # A finding number written after the word for review or round, with no folder date in front: + # "리뷰 02-01", "1라운드 06-01", "리뷰 README 13.2, 09-02", "review 2026-11-01 05-15". The number + # must stand alone, so a date such as 2026-11-01 is not a finding number by itself. + ("finding number after a review or round word (리뷰 02-01)", + re.compile(r"(?:리뷰|라운드|(? Date: Fri, 6 Nov 2026 23:18:47 +0900 Subject: [PATCH 18/71] =?UTF-8?q?docs(work):=20cold-read=20=EC=8B=9C?= =?UTF-8?q?=ED=97=98=201=ED=9A=8C=EC=B0=A8=EC=9D=98=20=EB=B9=88=ED=8B=88?= =?UTF-8?q?=EA=B3=BC=20=EB=AA=A8=EC=88=9C=EC=9D=84=20=EB=A7=A4=EB=89=B4?= =?UTF-8?q?=EC=96=BC=EC=97=90=20=EB=B0=98=EC=98=81=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 2026-11-06 이력 없는 세션 6개에 이 매뉴얼만 주고 실제 일을 시켰다. 6개 모두 일은 끝냈지만 매뉴얼에서 답을 못 찾은 곳이 세션마다 1~9건 나왔고, 세 곳은 문서끼리 다르게 말했다. - 리뷰 README를 누가 쓰나: delegate.md는 총괄, improve.md는 리뷰어 - push: README 4절·decisions.md는 "커밋을 허용하면 push도", 정본 delegation-loop.md 11절은 brief가 push를 따로 허용해야 한다 - evidence.md 머리말은 "RR-는 1차 재리뷰"라는데 round2도 RR-를 썼다 고른 방법: - 리뷰어는 README에 자기 라운드 색인 절 하나만 쓰고, 처리 표·결정의 답·게이트 기록은 총괄이 쓴다(improve.md 4.1, delegate.md 4.2, decisions.md 2.1) - 커밋과 push는 brief 7절이 따로 허용한다. 커밋만 허용되면 push하지 않는다. push 없이도 패치와 트리 해시로 desktop에서 검증한다 (operate.md 4.1 「push 전에 검증하기」). 이 방법은 커밋 본문에 desktop 결과를 넣으려는 세션의 빈틈도 닫는다 - evidence.md 머리말을 접두어별 문서로 고친다 - 나머지 빈틈은 그 일을 하는 playbook의 절차 단계나 자주 하는 실수, reference에 한 줄씩 넣는다. 36행 처리 표는 evidence.md 9절이다 (고침 35, 고치지 않음 1: 새 매뉴얼에 이미 답이 있던 것) 버린 대안: push를 "커밋 허용이면 push도"로 읽기. 정본 11절과 실제 brief(백엔드는 push, design-docs는 push 안 함)가 push를 따로 다룬다. 버린 대안: 빈틈을 모두 자주 하는 실수에 넣기. 10줄 상한을 넘고, 절차의 한 단계인 것은 그 단계에 있어야 읽힌다. 위험·한계: - 리뷰 README 분담, push를 따로 읽는 것, 하위 세션 Slack은 기본값이다. 소유자가 뒤집을 수 있게 decisions.md에 기본값으로 적었다 - AGENTS.md의 커밋 예외 문장은 이번 범위 밖이라 그대로다. 세부는 이 README 4절을 가리키므로 README가 정한다 - 고친 매뉴얼은 2회차 cold-read 시험 전이다 검증: - python3 scripts/check-work-docs.py rc=0. 지도 73/120, README 76/80, improve.md 134/150, 진입 경로 최대 283/350, 본문 이력 0줄 - python3 scripts/check-work-docs.py --links docs CLAUDE.md 결과 링크 432개, 깨진 것 0 - desktop: 바꾼 것을 패치로 기준 커밋 2c8a359d 위에 얹어 노트북과 같은 트리 3d0e5900을 만들고 flock 아래 :app-bootstrap:documentContractTest --rerun rc=0, 66건 실패 0 건너뜀 0, 13초, 직전 1분 부하 3.13 (desktop ~/manual-gap-fix-1-logs/documentContractTest.log) --- CLAUDE.md | 2 +- docs/work/README.md | 7 ++-- docs/work/delegate.md | 11 +++--- docs/work/docs-writing.md | 5 ++- docs/work/evidence.md | 54 +++++++++++++++++++++++++- docs/work/improve.md | 17 ++++---- docs/work/operate.md | 21 ++++++++-- docs/work/reference/decisions.md | 4 +- docs/work/reference/gates.md | 4 +- docs/work/reference/review-criteria.md | 4 +- docs/work/research-design.md | 6 +-- 11 files changed, 105 insertions(+), 30 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 3f75426f..406fc9db 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -62,7 +62,7 @@ brief(작업 지시문)가 있으면 brief의 범위·크기·완료 기준이 - **`src/sample-portfolio`는 지울 수 있는 샘플이다.** 한 leaf에 모든 계층을 둔 모양이라 배치를 따라 하지 않는다. 새 기능의 예시는 `scripts/new-feature.sh`의 출력이다. - **성능 lane에는 단언을 끄는 스위치가 없다.** convention이 상한을 매번 단언하고, `performance.assertions.enabled`에 `true` 아닌 값이 들어오거나 skip이 있으면 테스트 전에 실패한다. 손으로 돌리든 workflow든 같다(`AGENTS.md` 「Gradle 정책 권위」). - **저장소 파일을 읽는 테스트는 태그가 있다.** 문서와 대조하는 테스트는 `document-contract`(main 단계 `mainCheck`), 빌드 스크립트·workflow를 읽는 테스트는 `repository-contract`(PR)다. 문서를 고치면 그 문서를 읽는 테스트를 찾는다. -- **커밋 정책은 `human-only`다.** brief가 허용할 때만 자기 브랜치에 커밋·push한다. 자세한 것은 [docs/work/README.md](docs/work/README.md) 4절이다. +- **커밋 정책은 `human-only`다.** brief가 허용한 것만 자기 브랜치에 한다. 커밋과 push는 따로 허용된다. 자세한 것은 [docs/work/README.md](docs/work/README.md) 4절이다. - **문서 위치 규칙은 [docs/README.md](docs/README.md)다.** 설계서는 `docs/superpowers/specs/`, 결정 기록은 `docs/adr/`, 리뷰는 `docs/reviews/`, 파생 서비스용 변경 안내는 `docs/upgrade/`다. ## 6. 소유자 환경 diff --git a/docs/work/README.md b/docs/work/README.md index 3926c8a7..c044abd4 100644 --- a/docs/work/README.md +++ b/docs/work/README.md @@ -41,8 +41,8 @@ ## 4. 커밋 - 기본 정책은 `human-only`다(`AGENTS.md`). 에이전트는 stage·commit·amend·push하지 않는다. -- 예외는 하나다. brief가 커밋을 허용하면, 그 작업의 자기 브랜치에만 커밋하고 push한다. -- 그때도 main 병합, 다른 브랜치 push, force push, PR 병합은 하지 않는다. 그것은 소유자가 한다. +- 예외는 하나다. brief 7절이 허용한 것만 그 작업의 자기 브랜치에 한다. 커밋과 push는 따로 허용된다. 커밋만 허용됐으면 push하지 않는다(desktop 검증은 [operate.md](operate.md) 4.1절 「push 전에 검증하기」). +- 그때도 main 병합, main·다른 브랜치 push, force push, PR 병합은 하지 않는다. 그것은 소유자가 한다. - 메시지 형식은 design-docs `conventions/commit-and-pr.md`를 따른다. AI 꼬리말과 자리표시자(`TBD`, `TODO`, 채우지 않은 칸)를 넣지 않는다. ## 5. 막혔을 때 @@ -54,7 +54,8 @@ ## 6. 보고 - 맨 앞에 결과(완료 / 부분 / 못 함)와 브랜치·커밋을 쓴다. -- 그다음 변경, 확인(명령 · 실행 위치 · rc · 로그 경로), 남은 문제를 쓴다. 남은 문제를 숨기지 않는다. +- 그다음 변경, 확인(명령 · 실행 위치 · rc · 로그 경로), 범위 밖에서 본 것(위치와 내용, 고치지 않음), 남은 문제를 쓴다. 남은 문제를 숨기지 않는다. +- 보고는 쉬운 한국어로 쓴다. 코드·명령·로그 인용만 원문 그대로 둔다. - 숫자(테스트 수, 실패 수, 태스크 이름)는 로그에서 옮긴다. 기억으로 쓰지 않는다. - 사고 순서 흔적 칸을 둔다(`conventions/work-thinking-order.md` 3절). 다른 세션이 맡긴 일이면 design-docs `conventions/delegation-loop.md` 5절 양식을 쓴다. diff --git a/docs/work/delegate.md b/docs/work/delegate.md index 5e8a49f9..c9800dd1 100644 --- a/docs/work/delegate.md +++ b/docs/work/delegate.md @@ -12,7 +12,7 @@ - 소유자의 목표와 이미 정한 결정. 큰 일이면 소유자가 계획을 검토한 시각. - 결과가 올라갈 브랜치와 그 최신 커밋(기준 커밋). -- 커밋·push 허용 범위. 하위 세션 브랜치 push는 desktop 검증에 필요하다. main 병합·push는 소유자가 한다. +- 커밋 허용과 자기 브랜치 push 허용. brief 7절에 따로 적는다. push 없이도 desktop 검증은 된다([operate.md](operate.md) 4.1절 「push 전에 검증하기」). main 병합·main push는 소유자가 한다. - 마감과 보고 받을 방법. ## 3. 크기와 사고 순서 @@ -31,8 +31,8 @@ design-docs `conventions/delegation-loop.md` 3절 순서대로 한다: 크기 이 repo에서 더할 것: - brief의 「작업 종류」는 이 repo의 `docs/work/<종류>.md`다. 「이미 아는 것」에는 [reference/decisions.md](reference/decisions.md)의 결정을 **내용으로** 옮긴다. 검증 명령은 [reference/gates.md](reference/gates.md)와 빌드 파일에서 실제 태스크 이름을 확인해 쓴다. -- 검증 칸에는 실행 위치와 증거 위치를 쓴다: desktop worktree, `flock /tmp/claude-gates/heavy.lock`, 로그 `~/<작업 이름>-logs/`([operate.md](operate.md) 4.1절). desktop 검증이 필요하면 7절에 자기 브랜치 push를 허용한다. -- 수정 묶음 brief에는 보고의 「새로 가정하는 것」 칸을 요구한다. 확인 리뷰 brief에는 그 칸부터 보라고 적는다. +- 검증 칸에는 실행 위치와 증거 위치를 쓴다: desktop worktree, `flock /tmp/claude-gates/heavy.lock`, 로그 `~/<작업 이름>-logs/`([operate.md](operate.md) 4.1절). 7절에는 커밋 허용과 자기 브랜치 push 허용을 따로 쓴다. +- 수정 묶음 brief에는 보고의 「새로 가정하는 것」 칸을 요구한다. 확인 리뷰 brief에는 그 칸부터 보라고 적고, 지난 라운드에서 열린 채 넘어온 「Declined to judge」를 다시 판정시킬지도 적는다. - 리뷰 brief에는 쓸 심각도 체계([reference/review-criteria.md](reference/review-criteria.md) 3절)와 "발견마다 이번 수정이 만들었나 / 이전부터"를 요구한다. - 대조할 때: 보고의 태스크 이름·테스트 수를 desktop 로그에서 grep으로 찾는다. High·Important 이상은 총괄이 코드에서 직접 다시 확인한다. - 리뷰 결과를 받으면 `python3 scripts/check-review-index.py docs/reviews/<폴더>`로 색인이 빠짐없는지 본다. 수정 묶음은 색인에서 배정한다. @@ -58,7 +58,7 @@ design-docs `conventions/delegation-loop.md` 3절 순서대로 한다: 크기 | 파일 | 왜 | | --- | --- | | `docs/upgrade/` 안내 문서 | 묶음마다 행을 더해 번호가 겹친다 | -| `docs/reviews/<폴더>/README.md` | 처리 표·결정·게이트 기록은 총괄이 쓴다 | +| `docs/reviews/<폴더>/README.md` | 처리 표·결정의 답·게이트 기록·남은 것은 총괄이 쓴다. 리뷰어는 자기 라운드 색인 절 하나만 쓴다([improve.md](improve.md) 4.1절 7단계) | | `src/config/architecture/modules.json`, `src/settings.gradle` | registry 하나가 모든 leaf를 정한다 | | `src/gradle/libs.versions.toml`, lockfile | 의존성을 바꾸면 lockfile 전체가 바뀐다 | | `src/build.gradle`, `src/app-bootstrap/build.gradle` | 라이프사이클과 기본 조립 | @@ -97,7 +97,7 @@ design-docs `conventions/delegation-loop.md` 3절 순서대로 한다: 크기 - 하위 세션의 일을 대신 하지 않는다. 대조에 필요한 읽기와 확인만 직접 한다. - 보고를 그대로 믿지 않는다. 보고는 E0 증거다. - 같은 파일을 두 세션에 맡기지 않는다. -- 하위 세션에 main 병합·push, force push, 다른 브랜치 push를 허용하지 않는다. +- 하위 세션에 main 병합·main push, force push, 다른 브랜치 push를 허용하지 않는다. - brief에 결정 번호만 쓰지 않는다. 내용을 쓴다. ## 7. 막혔을 때 @@ -114,3 +114,4 @@ design-docs `conventions/delegation-loop.md` 3절 순서대로 한다: 크기 - 영역 문서의 ID를 색인에 손으로 옮기다 빠뜨린다. 색인 검사 스크립트를 돌린다. - 묶음을 너무 크게 만들어 마감 안에 검증 보고가 오지 않는다. 묶음 크기 상한을 지킨다. - 하위 세션이 적은 태스크 이름을 확인하지 않고 소유자에게 옮긴다. +- 같은 범위를 두 리뷰에 따로 맡기고(비교 시험 등) ID를 매길 쪽을 정하지 않아, 같은 ID가 다른 결함을 가리킨다. brief에 ID를 매길 리뷰 하나를 정한다(규칙은 [reference/review-criteria.md](reference/review-criteria.md) 10절 「ID」). diff --git a/docs/work/docs-writing.md b/docs/work/docs-writing.md index cd12d358..5cb8a524 100644 --- a/docs/work/docs-writing.md +++ b/docs/work/docs-writing.md @@ -32,10 +32,10 @@ 3. 위치를 정한다. 문서 위치 규칙은 `docs/README.md`다. 여러 repo나 소유자 운영에 걸친 내용은 이 repo가 아니라 design-docs에 둔다. 4. 결론을 먼저 쓴다. 한 문장에 개념 하나, 처음 나온 용어는 그 자리에서 한 줄로 푼다. 흐름이 있으면 화살표 도식을 먼저 둔다. 표는 둘 이상을 비교할 때만 쓴다. 5. 절차는 한 줄에 한 단계, 동사로 시작한다. 명령은 실제로 있는 것만 쓴다. 태스크 이름은 `src/build.gradle`이나 leaf `build.gradle`에서, 경로는 `ls`로 확인한다. -6. 지난 일을 근거로 쓸 때는 날짜, 무엇이 일어났나, 숫자를 한 줄로 쓴다. 리뷰 ID·묶음 이름·번호만 쓴 결정은 매뉴얼 본문에 쓰지 않는다. 걷어낸 ID 중 근거로 남길 것은 어느 문서에서 왔든 [evidence.md](evidence.md)에 원래 문서·문장과 함께 모은다. +6. 지난 일을 근거로 쓸 때는 날짜, 무엇이 일어났나, 숫자를 한 줄로 쓴다. 리뷰 ID·묶음 이름·번호만 쓴 결정은 매뉴얼 본문에 쓰지 않는다. 걷어낸 ID 중 근거로 남길 것은 어느 문서에서 왔든 [evidence.md](evidence.md)에 원래 문서·문장과 함께 모은다. 번호의 원래 문서가 이 repo에 없으면 그 번호가 가리키는 규칙 이름과 코드 위치를 근거로 적고, 원래 문서가 repo에 없다고 쓴다. 7. 링크: repo 안 문서는 상대 링크로 쓴다. repo 밖 문서(design-docs 등)와 `file:line`은 링크가 아니라 코드 표기로 쓴다. 링크 검사(lychee)가 따라가지 못하기 때문이다. 8. 숫자를 복제하지 않는다. leaf 개수, 테스트 수처럼 코드가 정하는 값은 쓰는 순간 낡는다. 정본을 가리킨다. -9. 그 문서를 읽는 테스트가 있는지 찾는다: `grep -rn '<파일 이름>' src --include=*.java`. 있으면 그 테스트가 기대하는 문장을 지키고, 그 lane을 desktop에서 돌린다([reference/gates.md](reference/gates.md) 2절). +9. 그 문서를 읽는 테스트가 있는지 찾는다: `grep -rn -e '<파일 이름>' -e '<폴더 경로>' src --include=*.java`. 있으면 그 테스트가 기대하는 문장을 지키고, 그 lane을 desktop에서 돌린다([reference/gates.md](reference/gates.md) 2절). 없으면(주석만 걸리는 것도 없음이다) lane은 돌리지 않고, grep 명령과 결과를 보고에 적는다. 10. `docs/work/`나 루트 `CLAUDE.md`를 바꿨으면 `python3 scripts/check-work-docs.py`를 돌린다. 분량 상한, 본문 이력 ID 0, playbook 뼈대, 상대 링크를 본다. 11. 리뷰 폴더 README를 만들거나 고쳤으면 `python3 scripts/check-review-index.py docs/reviews/<폴더>`를 돌린다. 12. 다른 문서는 같은 스크립트의 모드로 본다: 상대 링크는 `--links <파일 또는 폴더>`(PR에서는 lychee가 다시 본다), 이력 ID는 `--history <파일 또는 폴더>`. @@ -81,3 +81,4 @@ - 지난 리뷰 ID로 이유를 대신한다. 내용과 날짜를 쓴다. - 저장소 밖 문서를 상대 링크로 써서 링크 검사가 실패한다. 코드 표기로 쓴다. - 없는 태스크 이름이나 옛 경로를 쓴다. 쓰기 전에 빌드 파일과 `ls`로 확인한다. +- `--history` 결과 0을 이력이 없다는 증거로 쓴다. 검사는 아는 꼴만 잡는다. 걷어낸 뒤 `grep -n -e 리뷰 -e 라운드 -e 결정 <파일>`로 남은 괄호를 한 번 더 읽고, 못 잡은 꼴은 검사 패턴에 더한다. diff --git a/docs/work/evidence.md b/docs/work/evidence.md index 5135dcf4..05b9697b 100644 --- a/docs/work/evidence.md +++ b/docs/work/evidence.md @@ -2,7 +2,7 @@ `docs/work/` 본문은 지난 리뷰를 모르는 사람도 읽을 수 있게 썼다. 그래서 규칙이 나온 사건과 지난 리뷰 ID는 본문에 넣지 않고 여기에 모았다. 본문을 따르는 데 이 문서는 필요 없다. 규칙의 이유를 확인하거나 규칙을 바꾸려 할 때 읽는다. -표기: `1101/05-01`은 `docs/reviews/2026-11-01-maturity-review/`의 발견 05-01이다. `1103/RR6-01-05`는 `docs/reviews/2026-11-03-rereview/`의 발견이다(`RR-`는 1차 재리뷰, `RR2-`~`RR6-`는 round2~round6). `1101` README, `1103` README는 각 폴더의 `README.md`다. 「결정 N」은 `docs/reviews/2026-09-25-review-followup-status.md` 「소유자 결정」의 N번이다. +표기: `1101/05-01`은 `docs/reviews/2026-11-01-maturity-review/`의 발견 05-01이다. `1103/RR6-01-05`는 `docs/reviews/2026-11-03-rereview/`의 발견이다. 접두어와 문서: `RR-`는 1차 재리뷰(폴더 바로 아래 `01`~`07` 영역 문서)와 round2의 `01`~`03` 영역 문서(1차 번호를 이어 썼다), `RR2-`는 round2의 `04` 영역 문서, `RR3-`~`RR7-`는 round3~round7이다. `1101` README, `1103` README는 각 폴더의 `README.md`다. 「결정 N」은 `docs/reviews/2026-09-25-review-followup-status.md` 「소유자 결정」의 N번이다. ## 1. 이 매뉴얼이 나온 곳 @@ -165,4 +165,54 @@ | `docs/manual/09-outbox-events.md:78` | "재리뷰 2차 RR-02-10" | runbook 가리킴만 남겼다 | `1103/RR-02-10`(tenant scope가 바뀌는 배포의 rolling 구간에서 새 번호가 옛 버전이 쓴 번호보다 작다, `round2/02-persistence-messaging.md`) | | `docs/manual/09-outbox-events.md:89` | "재리뷰 RR-05-03" | runbook 가리킴만 남겼다 | `1103/RR-05-03`(끝나지 않는 재시도 행을 운영자가 구분·처분할 수단이 없었다, `05-messaging.md`) | -- `RR-01-11`·`RR-02-10`·`RR-03-11`은 2차 재리뷰(`round2/`) 문서의 발견이다. 그 문서들은 1차 번호에 이어 `RR-` 접두어를 그대로 썼다. 머리말 표기("`RR-`는 1차 재리뷰")의 예외다. +- `RR-01-11`·`RR-02-10`·`RR-03-11`은 2차 재리뷰(`round2/`) 문서의 발견이다. 그 문서들은 1차 번호에 이어 `RR-` 접두어를 그대로 썼다(머리말 「표기」). + +## 9. cold-read 시험 1회차 빈틈 처리 (2026-11-06) + +2026-11-06 이력 없는 세션 6개에 이 매뉴얼만 주고 실제 일을 시켰다(기준선 1개는 옛 매뉴얼). 6개 모두 일은 끝냈지만 매뉴얼에서 답을 못 찾은 곳이 1~9건씩 나와 모두 불합격이었다. 아래는 시험 기록(design-docs `delegation-loop/trials/2026-11-06-*.md`)의 「질문」·「위반」 표와 각 세션 공유 노트(`~/.config/Claude/side-session-notes/local_fcd89c34-c754-4c5b-a38f-fa322834286f/`)의 「매뉴얼에서 답을 못 찾은 곳」을 한 줄씩 처리한 결과다. 기준 커밋 `2c8a359d`. + +- 세션: T1 `c-t1-r10-review`(확인 리뷰), B `c-t1-baseline`(같은 리뷰를 옛 매뉴얼로, 기준선), T2 `c-t2-circuit-breaker`(결함 수정), T3 `c-t3-error-codes`(조사·설계 → 구현), T4 `c-t4-manual-ids`(문서), T5 `c-t5-idempotency-opid`(결함 수정). +- 출처 칸: `기록 N`은 시험 기록 「질문」 표의 N번, `노트 N`은 공유 노트의 N번이다. T3 노트는 1단계 `1-N`, 2단계 `2-N`이다. +- 처리 칸: 고침(고친 곳) / 고치지 않음(이유) / 소유자 결정 필요. 기준선(B)은 새 매뉴얼에도 해당하는 것만 고쳤다. + +| # | 출처 | 빈틈 | 처리 | +| --- | --- | --- | --- | +| T1-1 | 기록 1, 노트 1 | 상한을 넘어 나눈 확인 리뷰를 한 세션이 차례로 해도 되나 | 고침 — `improve.md` 4.4절: 나누는 것은 맡긴 쪽, brief 하나로 받으면 차례로, 단위마다 문서 하나 | +| T1-2 | 노트 2 | 영역 pathspec이 파일 단위로 안 갈림, 수정 커밋 안의 리뷰 기록을 상한에서 빼나 | 고침 — `improve.md` 4.4절: 리뷰 기록 `docs/reviews/**` 제외, 테스트 파일은 지키는 코드의 영역 | +| T1-3 | 기록 2, 노트 3 | 수정 보고에 「새로 가정하는 것」 칸이 없을 때 | 고침 — `improve.md` 4.1절 2단계: 커밋 본문 「위험·한계」와 처리 표 「결정」에서 뽑고 뽑은 곳을 적는다 | +| T1-4 | 기록 3, 노트 4 | 지난 라운드 색인 누락으로 색인 검사가 처음부터 rc=1 | 고침 — `improve.md` 4.1절 8단계: 이번 색인 절에 「색인 보완」 한 줄 | +| T1-5 | 기록 4, 노트 5 | 리뷰 README를 누가 쓰나: `delegate.md`(총괄)와 `improve.md`(리뷰어)가 다름 — **모순** | 고침 — `improve.md` 4.1절 7단계, `delegate.md` 4.2절 표, `reference/decisions.md` 2.1 「리뷰 README 분담」: 리뷰어는 자기 라운드 색인 절 하나, 나머지는 총괄 | +| T1-6 | 기록 5, 노트 6 | 지난 라운드 영역을 나눌 때 영역 번호 | 고침 — `reference/review-criteria.md` 10절 「ID」: 그 라운드 영역 표의 순번, 나누면 뒤에 새 번호, 「범위」에 대응 | +| T1-7 | 기록 6, 노트 7 | 클래스 이름으로 고르는 strict lane에서 탐침 돌리기 | 고침 — `improve.md` 9절(자주 하는 실수): 기존 클래스에 메서드로, `-Werror` 주의 | +| T1-8 | 기록 7, 노트 8 | `--rerun`이 바로 앞 태스크에만 걸림 | 고침 — `operate.md` 9절, `reference/gates.md` 6절: 태스크마다 붙인다 | +| T1-9 | 노트 9 | 지난 라운드 Declined 30건이 닫힌 기록 없음, 확인 리뷰어가 다시 판정하나 | 고침 — `improve.md` 4.1절 9단계(brief가 맡겼을 때만), `delegate.md` 4.1절(확인 리뷰 brief에 적는다) | +| T1-10 | 기록 8, 노트 10 | 같은 범위를 두 리뷰가 같은 라운드 ID로 씀 | 고침 — `reference/review-criteria.md` 10절 「ID」(정본 리뷰 하나, 다른 쪽은 새 ID와 대응표), `delegate.md` 9절 | +| T1-11 | 기록 9, 노트 11 | 다른 브랜치 병합을 기다리는 Declined는 닫힌 것인가 | 고침 — `improve.md` 4.5절 2: 합친 트리에서 확인할 때까지 열림 | +| B-1 | 기록 1, 노트 1 | 한 리뷰어가 모든 영역을 볼 때 문서 모양 | 고침 — `reference/review-criteria.md` 10절 「위치」: `roundN/NN-<영역>.md`, 영역마다 하나 | +| B-2 | 기록 2, 노트 2 | 리뷰어가 리뷰 README에 쓰나 | 고침 — T1-5와 같은 곳 | +| B-3 | 기록 3, 노트 3 | strict lane 탐침, 탐침에도 `-Werror` | 고침 — T1-7과 같은 곳 | +| B-4 | 기록 4, 노트 4 | 확인 리뷰에 넣을 「이전부터」 결함의 경계 | 고침 — `improve.md` 4.1절 3단계: 읽은 주변 코드에서 본 것은 적고, 그 밖을 찾아 나서지 않는다 | +| B-5 | 기록 5, 노트 5 | 앞 라운드 Declined가 닫히지 않은 채 시작 | 고침 — T1-9와 같은 곳 | +| B-6 | 기록 6, 노트 6 | 리뷰 스킬은 하위 에이전트를 쓰라 하고 매뉴얼은 금지 — 모순 | 고치지 않음 — 새 매뉴얼에 답이 있다: `improve.md` 3절 끝 줄, `delegate.md` 4.3절. 새 매뉴얼로 같은 리뷰를 한 T1은 묻지 않았다 | +| B-7 | 기록 7, 노트 7 | 리뷰 기록 문서도 document-contract lane 대상인가 | 고침 — `reference/gates.md` 2절, `docs-writing.md` 4절 9단계: 읽는 테스트를 파일·폴더로 찾고, 없으면 돌리지 않고 grep 결과를 적는다 | +| T2-1 | 기록 1 | push한 커밋은 못 고치고 desktop은 push된 것만 받는다. 커밋 본문에 desktop 결과를 넣으려면 | 고침 — `operate.md` 2절·4.1절 「push 전에 검증하기」(패치와 트리 해시)·9절, design-docs `conventions/delegation-loop.md` 11절 「실행 위치」 | +| T3-1 | 기록 1, 노트 1-1 | 「파일 하나여도 큼」 표면에 대한 설계 메모만 쓰는 일의 크기 | 고침 — design-docs `conventions/work-thinking-order.md` 2.1절, `research-design.md` 3절, 스킬 `research-first` | +| T3-2 | 기록 5, 노트 1-2 | push 허용: `docs/work/README.md` 4절·`decisions.md`는 "커밋·push", 정본 11절은 "push는 소유자" — **모순** | 고침 — 커밋과 push를 brief 7절이 따로 허용한다: `docs/work/README.md` 4절, `reference/decisions.md` 2.1, `delegate.md` 2·4.1·6절, 루트 `CLAUDE.md` 5절, design-docs `conventions/delegation-loop.md` 2·3·4.1·11절, 스킬 `delegate` | +| T3-3 | 기록 2, 노트 1-3 | 탐침을 생략해도 되는 기준 | 고침 — `research-design.md` 4절 3단계 | +| T3-4 | 기록 3, 노트 1-4 | 파생 서비스 영향을 어떻게 확인하나 | 고침 — `research-design.md` 4절 5단계, design-docs `conventions/delegation-loop.md` 11절 「세션」(파생 서비스 위치) | +| T3-5 | 기록 4, 노트 1-5 | 조사·설계에서 범위 밖 결함을 어디에 적나 | 고침 — `docs/work/README.md` 6절: 모든 보고에 「범위 밖에서 본 것」 | +| T3-6 | 기록 4, 노트 1-6 | 하위 세션이 Slack 브리핑을 하나 | 고침 — design-docs `conventions/delegation-loop.md` 4.1절 7절 칸·11절 「보고」, `reference/decisions.md` 2.1 「하위 세션 보고」: 전역 규칙 그대로, brief가 "Slack 말고"면 안 보냄 | +| T3-7 | 기록 4, 노트 2-1 | push 전에 RED를 보려면 desktop에 무엇을 보내나 | 고침 — `operate.md` 4.1절 「push 전에 검증하기」 RED 줄 | +| T3-8 | 기록 4, 노트 2-2 | 커밋 본문 「검증」 칸과 push 순서 | 고침 — T2-1과 같은 곳 | +| T3-9 | 기록 4, 노트 2-3 | `git add -p` 없이 한 파일을 두 커밋으로 나눠 stage | 고침 — design-docs `conventions/delegation-loop.md` 11절 「커밋과 병합」(패치 hunk를 지우고 `git apply --cached`) | +| T4-1 | 기록 1, 노트 「스크립트가 못 잡는 이력 ID」 | `--history`가 "리뷰 NN-NN"·"N라운드 NN-NN"을 못 잡아 0이 나와도 16줄 남음 | 고침 — `scripts/check-work-docs.py` 패턴 셋, `docs-writing.md` 9절. 새로 드러난 `docs/manual/` 16줄은 고치지 않음 — 이번 범위 밖, 2회차 시험 과제 | +| T4-2 | 기록 2 | 바꾼 문서를 읽는 테스트가 없을 때 무엇을 돌리나 | 고침 — B-7과 같은 곳 | +| T4-3 | 기록 3 | 이 문서 머리말의 ID 표기가 실제(2차 재리뷰도 `RR-`)와 다름 — **모순** | 고침 — 이 문서 머리말 「표기」(접두어별 문서), 8절 끝 줄 | +| T4-4 | 기록 4 | 원래 문서가 repo에 없는 결정 번호 | 고침 — `docs-writing.md` 4절 6단계 | +| T4-5 | 기록 5 | 하위 세션이 Slack 브리핑을 하나 | 고침 — T3-6과 같은 곳 | +| T5-1 | 기록 1 | 설계서 둘과 포트 Javadoc이 서로 다를 때 무엇을 따르나 | 고침 — `improve.md` 7절: 결정이 없으면 고르지 않고 양쪽 근거로 묻는다 | +| T5-2 | 기록 2 | 소유자 지시로 생긴 큰 변경도 따로 멈춰야 하나 | 고침 — design-docs `conventions/work-thinking-order.md` 2.3절, 스킬 `research-first` | +| T5-V | 기록 「위반」 1 | 총괄 보고를 영어로 씀 | 고침 — `docs/work/README.md` 6절, design-docs `conventions/delegation-loop.md` 5·11절. 훅으로는 막지 않는다(보고 문장은 도구 호출이 아니라 훅이 볼 수 없다) | + +- 기준선과 새 매뉴얼의 리뷰 발견은 8건 중 1건만 겹쳤다. 리뷰 방식을 바꿀지는 매뉴얼 규칙으로 넣지 않고 소유자에게 물을 제안으로 남겼다(매뉴얼 수정 세션 보고). +- 「자주 하는 실수」에 넣은 줄: `improve.md`(strict lane 탐침), `operate.md`(`--rerun` 범위를 기존 줄에 더함, push 뒤 검증), `docs-writing.md`(`--history` 0을 믿음), `delegate.md`(두 리뷰의 ID). diff --git a/docs/work/improve.md b/docs/work/improve.md index fa655b75..1c099d3b 100644 --- a/docs/work/improve.md +++ b/docs/work/improve.md @@ -37,14 +37,14 @@ ### 4.1 리뷰 1. 범위를 고정한다. 확인 리뷰는 pathspec과 `git diff --stat .. -- ` 결과를 문서에 적는다. -2. 확인 리뷰는 수정 보고의 「새로 가정하는 것」 칸부터 본다. 가정마다 다른 코드·설정·운영에서 참인지 확인한다. -3. 그다음 수정 diff와, diff가 바꾼 동작의 주변 코드를 읽는다. 확인 리뷰는 저장소 전체가 아니라 그 수정만 본다. +2. 확인 리뷰는 수정 보고의 「새로 가정하는 것」 칸부터 본다. 가정마다 다른 코드·설정·운영에서 참인지 확인한다. 그 칸이 없으면(보고가 repo에 없거나 옛 양식) 수정 커밋 본문의 「위험·한계」와 리뷰 README 처리 표의 「결정」 칸에서 가정을 뽑고, 뽑은 곳을 문서 「범위」 절에 적는다. +3. 그다음 수정 diff와, diff가 바꾼 동작의 주변 코드를 읽는다. 확인 리뷰는 저장소 전체가 아니라 그 수정만 본다. 읽은 주변 코드에서 본 결함은 이전부터 있었어도 발견으로 적고 「이전부터」로 표시한다. 그 밖을 찾아 나서지 않는다. 4. 전체 리뷰는 게이트를 먼저 한 번 돌려 결과를 적고([reference/gates.md](reference/gates.md)), 영역을 나눈다([delegate.md](delegate.md) 「나누는 법」). 5. 의심 결함은 별도 worktree의 임시 테스트(탐침)로 확인한다. 탐침 코드는 고칠 때 옮겨 쓸 수 있게 남기고(소유자 환경에서는 공유 노트 폴더, design-docs `conventions/delegation-loop.md` 11절), worktree는 지운다. 6. 발견을 [reference/review-criteria.md](reference/review-criteria.md) 양식으로 적는다. 발견마다 증거 수준과 "이번 수정이 만들었나 / 이전부터 있었나"를 적는다. -7. 리뷰 폴더 README에 색인을 만든다. 발견 ID를 모두 이름으로 적는다. 범위(`A~B`)와 이어 쓰기(`A·07`)는 된다. 건수만 쓰지 않는다. -8. `python3 scripts/check-review-index.py docs/reviews/<폴더>`를 돌린다. 색인 절이 따로 있으면 `--index-heading "<절 제목>"`을 붙인다. rc=0이어야 한다. -9. 판단하지 않은 항목은 「Declined to judge」에 위치와 이유를 적는다. 맡긴 쪽이 다음 묶음에 배정하거나 결정으로 닫는다. +7. 리뷰 폴더 README에 이번 라운드의 색인 절 하나를 더한다: 발견 ID, 심각도, 한 줄 내용, 결정이 필요한 질문. 발견 ID를 모두 이름으로 적는다. 범위(`A~B`)와 이어 쓰기(`A·07`)는 된다. 건수만 쓰지 않는다. README의 다른 절(처리 표, 결정의 답, 라운드 끝 게이트)은 맡긴 쪽이 쓴다. 한 라운드를 여러 리뷰 세션이 나눠 보면 색인 절도 맡긴 쪽이 쓰고, 리뷰어는 보고에 같은 표를 둔다. +8. `python3 scripts/check-review-index.py docs/reviews/<폴더>`를 돌린다. 색인 절이 따로 있으면 `--index-heading "<절 제목>"`을 붙인다. rc=0이어야 한다. 지난 라운드 색인에서 빠진 ID 때문에 처음부터 rc=1이면, 빠진 ID를 이번 색인 절에 「색인 보완」 한 줄로 이름만 적는다. 지난 영역 문서는 고치지 않는다. +9. 판단하지 않은 항목은 「Declined to judge」에 위치와 이유를 적는다. 맡긴 쪽이 다음 묶음에 배정하거나 결정으로 닫는다. 지난 라운드에서 열린 채 넘어온 Declined는 brief가 맡겼을 때만 다시 판정한다. 맡기지 않았으면 건수와 위치만 적는다. ### 4.2 결함 수정 @@ -68,7 +68,8 @@ ### 4.4 수정 묶음의 크기 - 묶음 하나는 리뷰 영역 하나 안이고 발견 8건 이하다. 묶음마다 커밋 하나다. -- 확인 리뷰 하나가 보는 수정 diff는 추가 1,500줄 이하다(`git diff --shortstat ..`, 테스트 포함, lockfile·스냅숏 같은 생성 파일 제외). 넘으면 확인 리뷰를 나눈다. 묶음 커밋이 따로 있으면 커밋별로, 한 커밋에 여러 영역이 섞였으면 영역 pathspec별로(`git diff --shortstat .. -- `) 나눠 각각 상한 안이 되게 한다. +- 확인 리뷰 하나가 보는 수정 diff는 추가 1,500줄 이하다(`git diff --shortstat ..`, 테스트 포함, lockfile·스냅숏 같은 생성 파일과 리뷰 기록 `docs/reviews/**` 제외). 넘으면 확인 리뷰를 나눈다. 묶음 커밋이 따로 있으면 커밋별로, 한 커밋에 여러 영역이 섞였으면 영역 pathspec별로(`git diff --shortstat .. -- `) 나눠 각각 상한 안이 되게 한다. 테스트 파일은 그 테스트가 지키는 코드의 영역에 넣는다. +- 나누는 것은 맡긴 쪽이 brief로 한다. 상한을 넘는 범위를 brief 하나로 받았으면, 한 세션이 나눈 단위를 차례로 보고 단위마다 문서 하나를 쓴다. 그렇게 했다고 보고에 적는다. - 왜: 지난 수정 라운드에서 추가 줄이 2,000줄 아래면 다음 확인 리뷰 발견이 9건 이하였고, 5,000줄을 넘으면 19건 이상이었다([evidence.md](evidence.md) 「수정 묶음 크기」). 상한 값은 판단이다. 라운드당 새 결함 수로 다시 맞춘다. - 묶음을 합친 트리는 따로 검증한다([reference/gates.md](reference/gates.md) 「라운드 끝」). 두 묶음의 수정은 한 트리에서 처음 만날 때 새 결함을 만든다. @@ -77,7 +78,7 @@ 리뷰 → 수정 → 확인 리뷰는 아래 넷이 모두 참일 때만 멈춘다. 1. 마지막 확인 리뷰의 발견이 심각도와 상관없이 0이다. Minor도 기록만 하지 않고 고친다. -2. 열린 「Declined to judge」가 0이다. +2. 열린 「Declined to judge」가 0이다. 다른 브랜치가 처리했지만 아직 합치지 않은 항목은 합친 트리에서 확인할 때까지 열린 것으로 센다. 3. 합친 트리에서 라운드 끝 게이트가 모두 통과했다. 4. 리뷰 README의 남은 항목이 0이다. 결정으로 닫은 항목은 결정 위치를 적었다. @@ -108,6 +109,7 @@ - 고치는 법이 공개 동작(응답 코드, 기동 실패 조건, env 키, 파생 서비스 동작)을 바꾸면 고치기 전에 멈추고 묻는다. 형식은 [README](README.md) 5절이다. - RED를 만들 수 없으면(실 vendor가 없다, 머신에 따라 통과한다) 그 사실과 이유를 보고하고 그 발견만 멈춘다. +- 계약을 적은 곳끼리(설계서, 포트 Javadoc, 모듈 README, 테스트) 다르게 말하고 [reference/decisions.md](reference/decisions.md)에 결정이 없으면, 어느 쪽도 고르지 않는다. 양쪽 근거를 표로 붙이고 권하는 안과 함께 묻는다. 그 발견만 멈춘다. ## 8. 보고 형식 @@ -129,3 +131,4 @@ - 색인을 손으로 옮기다 발견이 빠진다. 색인 검사 스크립트를 돌린다. - 보고에 없는 태스크 이름을 적는다. 로그에서 태스크 이름을 grep해 확인한다. - 묶음별 검증으로 합친 트리 검증을 대신한다. 라운드 끝 게이트를 따로 돌린다. +- strict lane에 돌릴 탐침을 새 클래스로 만들어 lane이 고르지 않는다. lane은 `build.gradle`의 `requires`(클래스 이름)나 `tag`로 테스트를 고른다. 탐침은 그 lane이 고르는 기존 클래스에 메서드로 넣는다. 탐침도 `-Werror`로 컴파일되니 경고를 남기지 않는다. diff --git a/docs/work/operate.md b/docs/work/operate.md index de17203d..9aaca51c 100644 --- a/docs/work/operate.md +++ b/docs/work/operate.md @@ -12,8 +12,8 @@ ## 2. 받아야 할 것 -- 대상 브랜치와 커밋 sha. desktop은 push된 브랜치만 받을 수 있다. -- 자기 브랜치 push 허용 여부. desktop 검증이 필요한 일이면 brief가 허용해야 한다. main push는 허용되지 않는다. +- 대상 브랜치와 커밋 sha. desktop은 push된 브랜치나, 노트북이 보낸 패치(4.1절 「push 전에 검증하기」)를 받는다. +- 자기 브랜치 push 허용 여부. brief 7절이 push를 허용하지 않았으면 패치로 검증한다. main push는 허용되지 않는다. - 돌릴 게이트 목록(없으면 [reference/gates.md](reference/gates.md) 2절로 정한다)과 로그를 둘 이름. ## 3. 크기와 사고 순서 @@ -60,6 +60,20 @@ git worktree remove ~/workspace/<작업 이름> - RED 확인용 임시 worktree도 같은 방법으로 만들고 끝나면 지운다. - Python 검사 스크립트는 노트북에서 돌려도 된다. 보고 증거로 쓸 때는 desktop worktree에서 한 번 더 돌린다. +**push 전에 검증하기.** push한 커밋은 고쳐 쓰지 않는다. 그래서 커밋 본문에 desktop 결과를 쓰거나 push가 허용되지 않았으면, 커밋 전에 바꾼 것을 패치로 보내 같은 트리에서 돌린다. + +```bash +# 노트북: 커밋할 파일만 stage하고(git status로 확인) 트리 해시를 적어 둔다 +git add <바꾼 파일>... && git status --short && git write-tree +# desktop: 기준 커밋(push된 커밋)에서 worktree를 만든다 +ssh desktop 'cd ~/workspace/clean-architecture-backend-template && git fetch origin && git worktree add --detach ~/workspace/<작업 이름> <기준 커밋>' +# 노트북: 패치를 보내 얹는다. 마지막 줄이 위 트리 해시와 같아야 한다 +git diff --cached --binary <기준 커밋> | ssh desktop 'cd ~/workspace/<작업 이름> && git apply --index && git write-tree' +``` + +- 그다음 위 3) 4)대로 돌리고 지운다. 결과를 본문에 적어 커밋한 뒤 `git rev-parse HEAD^{tree}`가 같은 해시인지 본다. 같으면 desktop이 돌린 트리가 그 커밋이다. +- RED는 같은 방법으로 테스트 파일만 stage해 보낸다. 한 파일의 일부만 stage하는 법은 design-docs `conventions/delegation-loop.md` 11절 「커밋과 병합」이다. + ### 4.2 게이트 실행과 기록 1. [reference/gates.md](reference/gates.md) 2절로 돌릴 게이트를 고른다. 라운드 끝이면 3절 묶음 전체다. @@ -112,4 +126,5 @@ git worktree remove ~/workspace/<작업 이름> - desktop 기존 checkout에서 브랜치를 바꿔 다른 세션의 작업을 방해한다. 자기 worktree를 만든다. - 짧게 끝난 실행을 통과로 적는다. 캐시 재사용인지, 태스크가 실제로 돌았는지 로그로 확인한다. -- 빌드 캐시에서 가져온 테스트 결과를 지금 이 환경에서 통과한 증거로 쓴다. 기준 상태를 확인하거나 시간·환경에 민감한 테스트를 볼 때는 그 태스크를 `--rerun`으로 다시 돌린다. +- 빌드 캐시에서 가져온 테스트 결과를 지금 이 환경에서 통과한 증거로 쓴다. 기준 상태를 확인하거나 시간·환경에 민감한 테스트를 볼 때는 그 태스크를 `--rerun`으로 다시 돌린다. `--rerun`은 바로 앞 태스크 하나에만 걸린다. 태스크마다 붙인다(`:a:test --rerun :b:test --rerun`). +- 커밋하고 push한 뒤 desktop에서 돌려, 결과를 커밋 본문에 못 넣는다. push 전에 패치로 검증한다(4.1절). diff --git a/docs/work/reference/decisions.md b/docs/work/reference/decisions.md index 2abff16a..d28c6a33 100644 --- a/docs/work/reference/decisions.md +++ b/docs/work/reference/decisions.md @@ -31,7 +31,9 @@ | 주제 | 결정 | 누가 | 날짜 | 출처 | | --- | --- | --- | --- | --- | | 커밋 정책 기본 | `human-only`. 에이전트는 stage·commit·amend·push하지 않는다 | 정책 | — | `AGENTS.md` 「Gradle 정책 권위」 끝 | -| 커밋 예외 | brief가 허용하면 그 작업의 자기 브랜치에만 커밋·push한다. main 병합·다른 브랜치 push·force push는 하지 않는다 | 소유자 | 2026-11-06 | design-docs `conventions/delegation-loop.md` 11절, `docs/work/README.md` 4절 | +| 커밋 예외 | brief 7절이 허용한 것만 그 작업의 자기 브랜치에 한다. 커밋과 push는 따로 허용된다. 커밋만 허용됐으면 push하지 않는다. main 병합·main 또는 다른 브랜치 push·force push는 하지 않는다 | 소유자(2026-11-06), 커밋과 push를 나눠 읽는 것은 기본값(2026-11-06) | 2026-11-06 | design-docs `conventions/delegation-loop.md` 11절 「커밋과 병합」, `docs/work/README.md` 4절, `docs/work/evidence.md` 9절 | +| 리뷰 README 분담 | 리뷰어는 리뷰 폴더 README에 자기 라운드의 색인 절 하나만 쓴다. 처리 표·결정의 답·라운드 끝 게이트·남은 것은 총괄이 쓴다. 한 라운드를 여러 리뷰 세션이 나눠 보면 색인 절도 총괄이 쓴다 | 기본값 | 2026-11-06 | `docs/work/evidence.md` 9절 | +| 하위 세션 보고 | 총괄에게도 쉬운 한국어로 쓴다. Slack 브리핑은 전역 `~/.claude/CLAUDE.md` 규칙이 하위 세션에도 그대로 적용된다. brief 7절에 "Slack 말고"가 있으면 보내지 않는다 | 기본값(전역 규칙의 적용 범위를 적음) | 2026-11-06 | design-docs `conventions/delegation-loop.md` 11절 「보고」 | | 커밋 예외(지난 것) | `refactor/review-followup`에 Wave마다 커밋(2026-09-25), 리뷰 수정을 `refactor/maturity-review-2026-11`에 커밋·push(2026-11-03) | 소유자 | 2026-09-25, 2026-11-03 | 결정 1, `1101` 17절 | | 리뷰 발견 처리 | Minor도 기록만 하지 않고 고친다. 보고할 때 남은 문제가 0이어야 한다. 수정이 새 결함을 만들면 리뷰·수정을 0까지 반복한다 | 소유자 | 2026-11-05 | `1103` 16절 | | 옛 멈춤 기준 | "새 Important 0이면 멈춤", "Minor는 기록만" — 거둠 | 위임 → 소유자가 거둠 | 2026-11-05 | `1103` 9.1·11.1·16절 | diff --git a/docs/work/reference/gates.md b/docs/work/reference/gates.md index 39bbf98c..8719fd7e 100644 --- a/docs/work/reference/gates.md +++ b/docs/work/reference/gates.md @@ -56,7 +56,7 @@ | 테스트 코드 | 그 leaf `testQualityCheck` | | compose·Dockerfile | compose 검사 스크립트, 실제 `docker build`와 기동 | -어떤 테스트가 그 문서를 읽는지는 `grep -rn '<파일 이름>' src --include=*.java`로 찾는다. +어떤 테스트가 그 문서를 읽는지는 `grep -rn -e '<파일 이름>' -e '<폴더 경로>' src --include=*.java`로 찾는다. 걸리는 테스트가 없으면(주석만 걸려도 없음이다) document-contract lane은 돌리지 않고 grep 명령과 결과를 보고에 적는다. 리뷰 기록(`docs/reviews/**`)도 같다. **링크 검사**: workflow `link-check.yml`(lychee)이 PR에서 `README.md`, `src/README.md`, `src/**/README.md`, `src/**/CLAUDE.md`, `docs/**/*.md`, `.github/**/*.md`를 검사한다. 루트 `CLAUDE.md`는 그 범위 밖이라 `scripts/check-work-docs.py`가 본다. lychee가 없는 곳에서는 `python3 scripts/check-work-docs.py --links docs`로 상대 링크만 확인한다. 저장소 밖 경로와 `file:line`은 링크로 쓰지 않는다(lychee가 따라가지 못한다). @@ -126,7 +126,7 @@ cd .. && bash scripts/verify-compose-profile-contracts.sh | 게이트 밖에서 실패한 채 방치된 검사 | `testQualityCheck`(`mainCheck`) | | 실서버 계약이 어느 게이트에도 없음 | lane을 단계에 연결 | | 시간 단언을 끈 채 performance lane 실행 | convention이 단언을 켜고, 끄는 값이나 skip이 있으면 테스트 전에 실패(5절) | -| 캐시에서 가져온 결과를 지금 통과한 것으로 셈 | 기준 상태 확인과 시간·환경에 민감한 테스트는 그 태스크를 `--rerun`으로 다시 돌린다 | +| 캐시에서 가져온 결과를 지금 통과한 것으로 셈 | 기준 상태 확인과 시간·환경에 민감한 테스트는 그 태스크를 `--rerun`으로 다시 돌린다. `--rerun`은 바로 앞 태스크 하나에만 걸리므로 태스크마다 붙인다 | | 외부 이미지가 사라져 다른 lane 결과까지 가림 | 테스트 이미지를 `src/config/testing/container-images.properties` 한 곳에 digest로 고정, main 단계는 `--continue` | 게이트 장치 자체를 바꿨으면 일부러 망가뜨린 입력으로 실패하는 것을 본다. 판독기를 바꿨으면 바꾸기 전후로 실제 workflow의 판정이 같은지 비교한다. diff --git a/docs/work/reference/review-criteria.md b/docs/work/reference/review-criteria.md index de30a617..e20a7d52 100644 --- a/docs/work/reference/review-criteria.md +++ b/docs/work/reference/review-criteria.md @@ -222,7 +222,7 @@ leaf를 더하거나 옮기거나 지울 때 같은 변경에서 함께 바꾼 ## 10. 리뷰 문서 양식 -**위치**: 전체 리뷰는 `docs/reviews/-<종류>/README.md` + 영역 문서 `NN-<영역>.md`. 확인 리뷰는 그 폴더 아래 `roundN/`. 리뷰 문서는 리뷰 시점 기록이다. 수정 뒤에도 영역 문서를 고치지 않고 처리 결과는 README에 적는다. +**위치**: 전체 리뷰는 `docs/reviews/-<종류>/README.md` + 영역 문서 `NN-<영역>.md`. 확인 리뷰는 그 폴더 아래 `roundN/NN-<영역>.md`, 영역마다 하나다. 한 리뷰어가 모든 영역을 봐도 영역마다 나눈다. 리뷰 문서는 리뷰 시점 기록이다. 수정 뒤에도 영역 문서를 고치지 않고 처리 결과는 README에 적는다. **전체 리뷰 README의 절** (가이드 36.5절 양식에 처리 현황·결정 기록을 더한 것): @@ -264,6 +264,8 @@ leaf를 더하거나 옮기거나 지울 때 같은 변경에서 함께 바꾼 - 라운드 안에서는 `NN-MM`(영역-순번)이다. 확인 리뷰는 라운드 접두어를 붙여 `RR-NN-MM`으로 쓴다(첫 재리뷰만 `` 없이). - 라운드 밖(다른 문서, 커밋, 주석)에서는 리뷰 폴더 날짜의 월일을 붙인다: `MMDD/`(가이드 36.3절). - 영역 번호 자리에 `NN` 같은 자리표시자를 남기지 않는다. 리뷰가 끝난 뒤 영역 접두어를 바꾸지 않는다. +- 영역 번호는 그 라운드 영역 표의 순번이다. 지난 라운드 번호와 맞추지 않아도 된다. 지난 라운드 영역 하나를 둘로 나누면 뒤에 새 번호를 잇고(04를 나누면 04·05), 「범위」 절에 지난 영역과의 대응을 적는다. +- 한 라운드의 ID는 리뷰 하나가 매긴다. 같은 범위를 두 리뷰가 따로 봤으면 brief가 정한 쪽이 정본이다. 다른 쪽 발견은 정본의 다음 번호로 새 ID를 받고, 두 ID의 대응표를 README의 그 라운드 색인 절에 둔다. 다른 쪽 문서를 그대로 합치지 않는다(같은 ID가 다른 결함을 가리킨다). - ID는 리뷰 문서·brief·커밋에서 쓴다. 매뉴얼(`docs/work/`) 본문에는 쓰지 않는다. ## 11. 판단을 적는 법 diff --git a/docs/work/research-design.md b/docs/work/research-design.md index de9d32a8..1b7ba181 100644 --- a/docs/work/research-design.md +++ b/docs/work/research-design.md @@ -19,7 +19,7 @@ ## 3. 크기와 사고 순서 -- 설계 메모 하나는 보통 중간이다: 선행 사례 2~3곳(내부 선례 포함), 대안 2~3개. +- 설계 메모 하나는 보통 중간이다: 선행 사례 2~3곳(내부 선례 포함), 대안 2~3개. 다루는 대상이 [README](README.md) 2절의 "파일 하나여도 큼" 표면(오류 코드 레지스트리 등)이어도 메모만 쓰고 바꾸지 않으면 중간이다. 큼은 그 메모를 적용하는 일이다(design-docs `conventions/work-thinking-order.md` 2.1절). - 새 체계·아키텍처·공개 계약은 큼이다: 선행 사례 10~15곳, 대안 3~5개. 1~5단계 결과와 대안 비교를 소유자가 먼저 본다. - 이 repo의 내부 선례를 찾는 곳: - [reference/decisions.md](reference/decisions.md)와 그 출처 문서 @@ -34,9 +34,9 @@ 1. 목적을 한 문장으로 적고 성공 기준을 정한다. 요청 원문이 있으면 인용한다. 2. 이미 정한 것을 찾는다(3절의 내부 선례). 이미 정해져 있으면 멈추고 그 결정을 보고한다. -3. 현황을 확인한다. 주장마다 출처를 단다: `file:line`, 커밋, 명령 결과. 실제 동작이 궁금하면 별도 worktree에서 탐침 테스트를 desktop으로 돌리고, 탐침 코드는 남기지 않는다. +3. 현황을 확인한다. 주장마다 출처를 단다: `file:line`, 커밋, 명령 결과. 코드 읽기로 동작이 하나로 정해지지 않으면(분기, 동시성, 설정·외부 시스템에 따라 다름) 별도 worktree에서 탐침 테스트를 desktop으로 돌리고, 탐침 코드는 남기지 않는다. 분기 없는 경로이고 기존 테스트가 그 동작을 고정하면 탐침을 생략하고, 그 테스트 이름을 출처로 적는다. 4. 선행 사례 표를 만든다: 출처 · 1차/2차 · 그들이 한 것 · 실패와 비판 · 가져올 것. -5. 대안을 비교한다. 실제로 다른 대안 2~5개(크기에 맞게), 기준(효과, 비용, 되돌리기, 파생 서비스 영향, 기존 결정과 충돌), 권하는 안과 이유. 의존 순서가 있는 변경은 의존 그래프 순서로 따진다. +5. 대안을 비교한다. 실제로 다른 대안 2~5개(크기에 맞게), 기준(효과, 비용, 되돌리기, 파생 서비스 영향, 기존 결정과 충돌), 권하는 안과 이유. 의존 순서가 있는 변경은 의존 그래프 순서로 따진다. 파생 서비스 영향은 파생 서비스 repo에서 바꿀 이름(키, 칸, 타입)을 `git grep`해 쓰는 곳을 센다. 소유자 환경의 파생 서비스 위치는 design-docs `conventions/delegation-loop.md` 11절이다. 6. 반증할 수 있는 가정을 적는다: "이 안이 틀렸다면 어디서 드러나나". 반론과 답도 적는다. 7. 산출물을 둔다. - 이 repo에만 해당: 설계서 `docs/superpowers/specs/-<주제>-design.md`, 되돌리기 비싼 선택이면 `docs/adr/ADR-<영역>-<번호>-<제목>.md`(기존 번호를 잇는다). From cb340001a6c31d4e464fd3769a4056e6559da61e Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Sat, 7 Nov 2026 00:19:24 +0900 Subject: [PATCH 19/71] =?UTF-8?q?docs(review):=20round7=201=EC=B0=A8=20Dec?= =?UTF-8?q?lined=2012=EA=B1=B4=EC=9D=84=20=ED=8C=90=EC=A0=95=ED=95=9C?= =?UTF-8?q?=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: round7 1차 리뷰의 「Declined to judge」 12건이 판정 없이 남아 멈춤 기준 2(열린 Declined 0)가 거짓이었다. round6 판정 표의 두 줄은 "다른 브랜치 병합 시 닫힘"으로 열려 있었다. 방법: 리뷰 브랜치(2c8a359d, t3·t5 수정과 2026-11-06 결정 포함)로 fast-forward한 뒤 round6 30건과 같은 방식으로 판정했다. (a) 3건 — RR7-02-02(in-memory fake의 같은 핸들 재시작 NOT_OWNER), RR7-03-06 (Flyway 규칙이 Flyway.configure()만 막음), WebFlux 타입은 RR7-01-01에 합침. (b) 8건, 그중 둘은 정해진 결정(같은 token·다른 operation의 claim, Flyway PostgreSQL 잠금)으로 닫음. (c) 1건 — 태그·릴리스 trigger만 있는 workflow를 단계 실행으로 셀지, 18.4절에 선택지와 권하는 안. round6 판정 표의 t3·t5 두 줄은 합친 트리에서 확인해 닫았다. 총괄 지시대로 README는 18.4절과 18.5절 판정 표만 고쳤다(18.1절 색인 표에는 새 발견 둘을 넣지 않았다). 위험·한계: 새 발견 둘은 코드 경로(E1)만 봤다. 실행 탐침은 돌리지 않았다. 검증: check-review-index.py docs/reviews/2026-11-03-rereview rc=0 (172건), check-work-docs.py --links(round7 문서) rc=0. Refs: docs/reviews/2026-11-03-rereview/README.md 18.4·18.5절 --- docs/reviews/2026-11-03-rereview/README.md | 33 +++++++++++++++++-- .../round7/01-core-inbound.md | 1 + .../round7/02-idempotency-outbound.md | 23 +++++++++++++ .../round7/03-persistence.md | 21 ++++++++++++ 4 files changed, 76 insertions(+), 2 deletions(-) diff --git a/docs/reviews/2026-11-03-rereview/README.md b/docs/reviews/2026-11-03-rereview/README.md index 970ef6c0..52693f60 100644 --- a/docs/reviews/2026-11-03-rereview/README.md +++ b/docs/reviews/2026-11-03-rereview/README.md @@ -502,6 +502,7 @@ lane. 마지막 실행은 17.2절의 `2c692554`다(이 리뷰에는 E0). | RR7-05-01(= round6 04 Declined ①) 경로 필터 workflow를 단계 실행으로 셀지 | (a) `paths:`·`paths-ignore:` trigger만으로는 세지 않는다 (b) 세고, 메시지·B-36의 "매 변경" 약속을 고친다 | (a). 단계 검사는 "모든 변경이 이 lane을 지난다"를 보장하려는 것이고 경로 필터는 그 보장을 깬다. 이 repo의 단계 명령은 필터 없는 workflow에 있어 판정이 바뀌지 않는다 | 소유자 | | RR7-03-03 실패한 동시 인덱스 마이그레이션의 복구 절차 | (a) runbook에 "그 버전의 실패 이력 행만 지운다" 예외와 SQL(`DELETE FROM WHERE version = '' AND NOT success`)을 둔다 (b) 이 경우 `flyway repair`를 허용한다 (c) 동시 인덱스 마이그레이션을 금지하고 운영 절차로 돌린다 | (a). 실패 행은 적용되지 않은 버전의 기록이라 지워도 성공한 마이그레이션의 순서·checksum은 그대로다(명령 B4 넷째 경우로 재배포 성공 확인). (b)의 repair는 checksum·설명까지 다시 맞춰 가이드가 막으려는 불일치를 지운다. (c)는 r10이 이미 버린 대안이다(큰 테이블 인덱스 추가가 번거로워짐). "이력을 고치지 않는다" 정책의 예외라 소유자 확인이 필요하다 | 소유자 | | RR7-01-05(= round6 01 Declined ①) 감싼 carrier를 전송이 어떻게 볼지 | (a) 네 전송 모두 원인 사슬의 첫 carrier를 본다 — web·GraphQL·STOMP에서 감싼 carrier의 응답이 500 → carrier 코드로 바뀐다 (b) 네 전송 모두 맨 위만 본다 — gRPC 응답이 carrier 코드 → `INTERNAL`로 바뀐다 (c) 차이를 두고 문서화한다 | (a). use case가 뜻한 코드로 답하고, persistence 실패의 SQL 원인이 어느 전송 로그에도 남지 않는다. gRPC가 이미 그렇게 해서 바뀌는 쪽이 셋이지만, 바뀌는 응답은 지금 500 `INTERNAL_ERROR`로 뭉개지는 경우뿐이다. 응답 코드가 바뀌는 수정이라 고치기 전에 확인받는다(`docs/work/improve.md` 7절) | 소유자 | +| round7 05 Declined ①: 태그·릴리스 trigger만 있는 workflow를 단계 실행으로 셀지 | (a) `push`에 `tags:`만 있거나(`branches`·`paths` 없이) `release` trigger만 있는 workflow는 `releaseCheck` 단계에만 센다 (b) 지금처럼 모든 단계에 센다(릴리스 흐름도 변경 흐름의 일부)고 메시지·B-36에 적는다 | (a). 결정 「경로 필터 workflow와 단계 검사」와 같은 원칙이다 — 태그 push는 매 변경에 돌지 않는다. `releaseCheck`는 정의가 "tag 전용 검사"(`src/README.md`)라 예외로 둔다. 이 repo는 `release.yml`(`push: tags: [v*]`)이 `:releaseCheck`·`-p optional-platforms releaseCheck` 말고도 `-p optional-platforms integrationCheck`를 돌리지만, 같은 단계를 `integration-main.yml`(main push·nightly)도 돌려 판정이 바뀌지 않는다 | 소유자 | ### 18.5 round6 「Declined to judge」 30건 판정 (2026-11-06) @@ -520,8 +521,8 @@ lane. 마지막 실행은 17.2절의 `2c692554`다(이 리뷰에는 E0). | 02 | ① | watchdog 스레드의 `inheritedAccessControlContext` | (b) | 템플릿은 실행 jar로 배포해 class loader가 하나다. 스레드는 마지막 예약 60초 뒤 끝난다. 공유 부모 loader 배포는 지원하는 형태가 아니다 | | 02 | ② | `ClientRuntimeRegistry.close()`의 interrupt 처리 | (a) → RR7-02-01 | "돌아오면 스레드가 없다"는 Javadoc 약속이 interrupt 경로에서 확인 없이 깨진다(A14) | | 02 | ③ | 배포 중 섞인 버전의 lease 지난 시작 | (b) | 배포 동안만이고 중복 실행이 없다(새 인스턴스는 옛 인스턴스가 시작한 기록을 넘겨받지 않는다) | -| 02 | ④ | `error-codes.yaml` `IDEMPOTENCY_UNAVAILABLE` `log_level` | (b) 다른 세션 처리 | `claude/t3-error-codes-loglevel-fcf427`에서 고침. 그 브랜치가 병합되면 닫힌다 | -| 02 | ⑤ | 시작 호출의 operation id가 claim과 다를 때 저장소 답이 다름 | (b) 다른 세션 처리 중 | `claude/t5-idempotency-operation-id-9bd973`에서 고치는 중. 병합 전까지 그 브랜치에서 열림 | +| 02 | ④ | `error-codes.yaml` `IDEMPOTENCY_UNAVAILABLE` `log_level` | (b) 다른 세션 처리, 닫힘 | `claude/t3-error-codes-loglevel-fcf427`에서 고쳤고 리뷰 브랜치에 합쳐졌다(`ddf174cd`). 합친 트리 `2c8a359d`에서 행에 `log_level`이 없고, 두면 `OperationalErrorRegistryContractTest`가 실패한다(`docs/registries/error-codes.yaml` 머리 주석) | +| 02 | ⑤ | 시작 호출의 operation id가 claim과 다를 때 저장소 답이 다름 | (b) 다른 세션 처리, 닫힘 | `claude/t5-idempotency-operation-id-9bd973`(`200019aa`)이 고쳤고 리뷰 브랜치에 합쳐졌다(`0fa01019`). 합친 트리 `2c8a359d`에서 PostgreSQL 시작도 `namesAnotherOperation` → `OPERATION_CONFLICT`로 Redis와 같다 | | 02 | ⑥ | in-memory fake가 lease를 모델링하지 않음 | (b) | RR-01-06 결정의 설계다(시간 케이스는 skip으로 보고). executor의 `LEASE_EXPIRED` → 503 매핑은 단위 테스트가 본다 | | 03 | ① | 검사기의 10단어 셈이 Flyway와 다름 | (b) | 결과가 달라지는 입력이 없다(판정 단어가 첫 4개 키워드 안, 앞 괄호는 많아야 6단어) | | 03 | ② | 중첩 블록 주석 | (b) r10이 고침 | `6e992970`: `LockWaitMigrationInspector.endOfBlockComment`, 테스트 `aStatementInsideANestedBlockCommentIsNotRead` | @@ -541,6 +542,34 @@ lane. 마지막 실행은 17.2절의 `2c692554`다(이 리뷰에는 E0). | 04 | ⑥ | httpclient 문서의 lane 이름·장애 주입 주기 | (b) 다른 커밋 처리 | `e6b6e18e`. 기준 커밋에서 `docs/httpclient/support-matrix.md:61`(`spring62ApiSurfaceScan`)·`:65`(main push, nightly)·`release-checklist.md:12`가 맞다 | | 04 | ⑦ | 실제 GitHub runner·pwsh 동작 | (b) | 결함 주장이 아니라 실행 환경의 한계다. RR6-04-04는 코드·테스트로 닫혔다 | +#### round7 1차 「Declined to judge」 12건 판정 (2026-11-07) + +총괄 요청으로 이 리뷰 1차 문서의 「Declined to judge」를 같은 방식으로 판정했다. 기준은 리뷰 브랜치를 fast-forward한 `2c8a359d`다(t3·t5 수정과 결정 +색인의 2026-11-06 결정 포함). 번호는 각 영역 문서 「Declined to judge」의 순서다(각 영역의 마지막 줄 "round6 …의 Declined"는 위 표가 다뤄 세지 +않는다). 결과: (a) 3건(그중 1건은 RR7-01-01에 합침), (b) 8건, (c) 1건. + +(a)로 새로 올린 발견 둘은 이 표에만 적었다. 총괄 지시가 18절 판정 표와 18.4절만 고치라고 해서 18.1절 색인 표에는 넣지 않았다. + +| 발견 | 심각도 | 한 줄 내용 | 이번 수정 / 이전부터 | 증거 | +|---|---|---|---|---| +| RR7-02-02 | Minor | in-memory fake가 시작을 적용한 같은 핸들의 재시작(응답 유실)에 `NOT_OWNER` — 두 저장소·포트 Javadoc은 `ALREADY_STARTED_SAME_OPERATION` | 이전부터 | E1 | +| RR7-03-06 | Minor | "코드로 만드는 Flyway는 모두 `FlywaySchemaPolicy.configure()`에서" 규칙을 ArchUnit이 `Flyway.configure()` 호출로만 지켜 `new FluentConfiguration()`·`new ClassicConfiguration()`이 빠진다 | 이번 수정 | E1 | + +| 영역 | # | 항목 | 판정 | 근거 | +|---|---|---|---|---| +| 01 | ① | `ARE_REQUEST_HANDLER_TYPES`에 WebFlux `WebFilter`·`WebHandler` 등이 없음 | (a) → RR7-01-01에 합침 | r9는 설정에 중첩된 클래스를 `org.springframework.web..` 전체로 봤다. 목록이 좁아진 같은 원인이고 다른 리뷰도 RR7-01-01에 함께 적었다 | +| 01 | ② | gRPC: 취소된 호출이 carrier·IAE로 끝나면 로그가 남음 | (b) | 문서는 "인식 못 한 실패"에서만 취소를 뺀다(`src/adapter/inbound/grpc/README.md`). 약속 위반이 없다 | +| 01 | ③ | gRPC: raw status를 다른 예외로 감싸 던지면 원인 사슬의 status 설명이 스택에 남음 | (b) | 인식 못 한 실패를 원인 사슬째 남기는 것은 네 전송 공통 설계다(web `GlobalExceptionHandler.handleUnknown`도 같다). RR6-01-05가 약속한 것은 서비스가 끝낸 raw status 자체의 설명이고 그것은 지켜진다 | +| 02 | ① | in-memory fake가 같은 핸들의 재시작에 `NOT_OWNER` | (a) → RR7-02-02 | 포트 Javadoc과 두 저장소, 결정 「넘겨받기 전 핸들의 재전송」(2026-11-06, 전이를 적용한 핸들에게는 "이미 처리됨")과 다르다. fake가 계약 밖으로 갈라졌다(A6) | +| 02 | ② | 같은 owner token·다른 operation id의 claim이 넘겨받을 수 있는 기록에서 `OwnerOperationConflict` 대신 넘겨받음 | (b) | 아무것도 실행되지 않은 기록이라 넘겨받아도 안전하다. `OwnerOperationConflict`에는 Javadoc 약속이 없고, t5가 더한 계약 케이스 `aClaimWithTheOwnerTokenUnderAnotherOperationIsAnOwnerOperationConflict`(살아 있는 claim)는 세 저장소가 같게 답한다. 결정 「같은 token·다른 operation의 claim·inspect」(2026-11-06, `docs/work/reference/decisions.md` 2.4)가 claim의 `OwnerOperationConflict`를 진행 중인 기록으로 한정했다. 넘겨받을 수 있는 기록은 넘겨받기를 먼저 보는 RR6-02-01 순서를 따른다 | +| 03 | ① | `new FluentConfiguration()`·`new ClassicConfiguration()` 경로 | (a) → RR7-03-06 | 규칙 문장(`persistence-jpa/CLAUDE.md`, `FlywaySchemaPolicy` Javadoc)이 모든 생성을 말하는데 장치는 한 길만 막는다(A10) | +| 03 | ② | 세션 잠금: 연결이 살아 있는 채 unlock이 실패하면 잠금이 풀의 연결에 남을 수 있음 | (b) | 결정 「Flyway PostgreSQL 잠금」(세션 수준, `docs/work/reference/decisions.md` 2.5)의 범위 안의 성질이다. 남은 잠금은 다음 배포가 `lockRetryCount` 뒤 오류로 멈추는 닫힌 실패이고, 풀이 그 연결을 닫으면 풀린다. 재현하지 않았고 결정의 전제를 바꿀 증거가 아니다 | +| 04 | ① | `trap 'exit 0' EXIT` 뒤 `trap - EXIT`로 풀어도 계속 세지 않음 | (b) | 거짓 실패 쪽이다(README 16절 결정) | +| 04 | ② | `kill $$` 등 신호로 셸을 끝내는 명령을 모델링하지 않음 | (b) | 신호로 끝난 단계는 실패로 끝나 거짓 통과가 없다 | +| 05 | ① | `push: tags:`만 있거나 `release` trigger만 있는 workflow도 단계 실행으로 셈 | (c) → 18.4절 | 결정 「경로 필터 workflow와 단계 검사」(2026-11-06)는 `paths:`만 정했다. 태그·릴리스 trigger는 같은 원칙(매 변경에 도는가)의 다른 모양이지만 `releaseCheck`는 정의상 태그 전용이라 새 결정이 필요하다 | +| 05 | ② | `runs-on`을 `labels:` 없는 `group:` 매핑으로만 쓰면 세지 않음 | (b) | 거짓 실패 쪽이고 실패 메시지가 이유("may be a Windows runner")를 말한다 | +| 05 | ③ | 같은 repo의 재사용 workflow를 `owner/repo/.github/workflows/x.yml@ref`로 부르면 호출자로 못 알아봄 | (b) | 거짓 실패 쪽이다. 메시지가 "no workflow in this directory calls it"을 말한다 | + ### 18.6 멈춤 기준 상태 (`docs/work/improve.md` 4.5절) 1. 마지막 확인 리뷰 발견 0: **아님.** 13건(18.1절). diff --git a/docs/reviews/2026-11-03-rereview/round7/01-core-inbound.md b/docs/reviews/2026-11-03-rereview/round7/01-core-inbound.md index 4091701f..82e4f842 100644 --- a/docs/reviews/2026-11-03-rereview/round7/01-core-inbound.md +++ b/docs/reviews/2026-11-03-rereview/round7/01-core-inbound.md @@ -108,6 +108,7 @@ desktop(`ssh desktop`) 임시 worktree 두 개(`~/workspace/t1-r10-review` = `06 - **이번 수정 / 이전부터**: 이번 수정(회귀). - **증거**: E2 — 명령 1·2(탐침 P1·P1c·P2를 두 커밋에서 실행). 코드 경로는 E1. - **다른 리뷰와 합침**: 같은 커밋을 따로 본 리뷰(`claude/t1-baseline-7d623a` `3add4917`, `round7/review.md`의 RR7-01-01)가 같은 결함을 같은 모양(중첩 `@Path`·`@ServerEndpoint`, r9 위반 1건 → r10 0건)으로 찾았다. 그 리뷰는 WebFlux `WebFilter`·`WebHandler`도 같은 방식으로 빠진다고 적었다(E1). 결함 하나로 센다. +- **3차 합침(2026-11-07)**: 1차 「Declined to judge」 첫째 항목(WebFlux `WebFilter`·`WebHandler`가 요청 처리기 목록에 없음)도 같은 원인이다. r9는 설정에 중첩된 클래스를 `org.springframework.web..` 전체로 봤다. README 18.5절에서 (a)로 판정해 이 결함에 합쳤다. ### RR7-01-02 · Minor · 메서드 참조로 함수형 route만 등록한 설정도 사용자 전송으로 세어, 같은 설정이 handler bean을 등록하면 거짓 실패한다 — Javadoc·매뉴얼은 "요청 처리 코드가 있을 때만"이라고 적는다 diff --git a/docs/reviews/2026-11-03-rereview/round7/02-idempotency-outbound.md b/docs/reviews/2026-11-03-rereview/round7/02-idempotency-outbound.md index da77e813..9112b1c8 100644 --- a/docs/reviews/2026-11-03-rereview/round7/02-idempotency-outbound.md +++ b/docs/reviews/2026-11-03-rereview/round7/02-idempotency-outbound.md @@ -111,3 +111,26 @@ round6 02의 「Declined to judge」를 판정하며(README 18.5절) 하나를 ### 2차 반영 뒤 결론 Critical 0, Important 0, 회귀 0. 결함 1건(RR7-02-01, Minor, 이전부터). 멱등성 쪽 r10 변경에서 찾은 새 결함은 여전히 0이다. + +## 3차 추가 결함 (2026-11-07, 총괄 요청) + +이 문서 1차 「Declined to judge」 둘을 판정했다(README 18.5절). 첫째를 결함으로 올리고, 둘째는 닫았다. 기준은 리뷰 브랜치를 fast-forward한 +`2c8a359d`다(t5 멱등 수정 `200019aa` 포함). + +### RR7-02-02 · Minor · in-memory fake는 시작을 적용한 그 핸들이 시작을 다시 보내면(응답 유실) `NOT_OWNER`로 답한다 — 두 저장소와 포트 Javadoc은 `ALREADY_STARTED_SAME_OPERATION`이다 + +- **출처**: 이 문서 1차 「Declined to judge」 첫째 항목(README 18.5절 판정 (a)). +- **위치**: + - fake: `src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/InMemoryIdempotencyStore.java`의 `markExecutionStarted` — 시작하면 `row.advance(EXECUTING)`가 기록의 핸들(revision)을 바꾸고, 다시 온 같은 핸들은 `!row.owner.equals(owner)`로 `NOT_OWNER`가 된다. + - 약속: `IdempotencyStartOutcome.ALREADY_STARTED_SAME_OPERATION` Javadoc("This exact start — from the handle presented — was already applied (a lost reply)"). 저장소: Redis `TRANSITION`은 기록 revision이 핸들 + 1이면 `ALREADY`, PostgreSQL은 기록된 시작 digest가 같으면(`replayVerdict` `SAME_ARGUMENTS`) `ALREADY_STARTED_SAME_OPERATION`. + - 결정: 「넘겨받기 전 핸들의 재전송」(2026-11-06, `docs/work/reference/decisions.md` 2.4) — 이미 일어난 전이를 다시 보내면 그 전이를 실제로 적용한 핸들에게만 "이미 처리됨"으로 확인한다. fake는 그 핸들에게도 거절한다. +- **무엇이 틀렸나**: 포트 계약은 "시작 응답을 잃은 호출자가 같은 핸들로 다시 시작하면 이미 시작됐다고 확인한다"이다. 두 저장소는 그렇게 답하고 fake는 `NOT_OWNER`로 답한다. 공유 계약(`IdempotencyStoreContract`)에 그 케이스가 없어 fake가 계약 밖으로 갈라진 채 통과한다(A6). +- **발생 조건·영향**: fake 위에서 executor나 use case를 시험하는 테스트가 같은 핸들로 시작을 두 번 보내면, 운영 저장소에서는 계속 실행될 흐름이 fake에서는 "회복 필요"(500)로 끝난다. 테스트가 운영과 다른 답을 근거로 통과하거나 실패한다. +- **테스트가 못 본 이유**: 계약에 "같은 핸들로 시작 두 번" 케이스가 없다. fake는 응답 유실을 만들 수 없어도 같은 호출을 두 번 하는 것은 할 수 있다. +- **고치는 법**: 계약에 케이스를 더한다 — claim → 시작 → 같은 핸들로 다시 시작 → `ALREADY_STARTED_SAME_OPERATION`과 현재 핸들. fake는 시작을 적용한 핸들(revision)을 기억해 그 핸들이면 `ALREADY_STARTED_SAME_OPERATION`으로 답한다(complete의 `completedBy`와 같은 방식). RED: 그 계약 케이스가 fake 계약 테스트에서 `NOT_OWNER`로 실패한다. 두 저장소 계약 테스트는 통과해야 한다. +- **이번 수정 / 이전부터**: 이전부터. +- **증거**: E1(fake·두 저장소의 판정 코드). 실행 탐침은 돌리지 않았다 — fake 판정은 `equals` 한 줄이라 코드로 결정적이다. + +### 3차 반영 뒤 결론 + +Critical 0, Important 0, 회귀 0. 결함 2건(RR7-02-01·02, 모두 Minor, 이전부터). diff --git a/docs/reviews/2026-11-03-rereview/round7/03-persistence.md b/docs/reviews/2026-11-03-rereview/round7/03-persistence.md index 3ff9ae39..f425b1ff 100644 --- a/docs/reviews/2026-11-03-rereview/round7/03-persistence.md +++ b/docs/reviews/2026-11-03-rereview/round7/03-persistence.md @@ -196,3 +196,24 @@ V1은 `probe` 테이블, 일반 인덱스, `note`가 겹치는 행 하나(2001, ### 2차 반영 뒤 결론 Critical 0, Important 1(RR7-03-03), 회귀 0. 결함 5건: 이번 수정 2(RR7-03-01·04), 섞임 1(RR7-03-02), 이전부터 2(RR7-03-03·05). + +## 3차 추가 결함 (2026-11-07, 총괄 요청) + +이 문서 1차 「Declined to judge」 둘을 판정했다(README 18.5절). 첫째를 결함으로 올리고, 둘째는 결정 「Flyway PostgreSQL 잠금」으로 닫았다. + +### RR7-03-06 · Minor · "코드로 만드는 Flyway는 모두 `FlywaySchemaPolicy.configure()`에서 시작한다"는 규칙을 ArchUnit은 `Flyway.configure()` 호출로만 지킨다 — `new FluentConfiguration()`·`new ClassicConfiguration()`은 Flyway 기본(트랜잭션) 잠금으로 돌아간다 + +- **출처**: 이 문서 1차 「Declined to judge」 첫째 항목(README 18.5절 판정 (a)). 다른 리뷰(`3add4917`)도 같은 항목을 Declined로 적었다. +- **위치**: + - 규칙: `src/adapter/outbound/persistence-jpa/CLAUDE.md:100-104`("every Flyway built in code starts from `FlywaySchemaPolicy.configure()`"), `FlywaySchemaPolicy.java` Javadoc("Every Flyway the template builds itself starts from {@link #configure()}"). + - 지키는 장치: `src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/JpaProductionArchitectureTest.java:167-190`(`callMethod(Flyway, "configure")`·`configure(ClassLoader)`만 거부). +- **무엇이 틀렸나**: Flyway 설정을 만드는 공개 길은 셋이다: `Flyway.configure()`, `new FluentConfiguration()`(+`.load()`), `new ClassicConfiguration()` + `new Flyway(configuration)`. 규칙 문장은 셋 모두를 말하고, ArchUnit은 첫째만 막는다(A10 — 둘째·셋째는 글로만 있음). +- **발생 조건·영향**: 파생 서비스가 자기 스트림을 `new FluentConfiguration()`으로 만든다. 빌드는 통과하고, 그 스트림의 `CREATE INDEX CONCURRENTLY` 마이그레이션은 RR6-03-01처럼 Flyway 자신의 열린 트랜잭션을 기다려 끝나지 않는다. 이 repo 코드에는 그런 생성이 없다(grep). +- **테스트가 못 본 이유**: 규칙에 둘째·셋째 길의 위반 fixture가 없다. +- **고치는 법**: 같은 규칙에 `callConstructor(FluentConfiguration.class, …)`(인자 없는 것과 `ClassLoader` 하나)와 `callConstructor(ClassicConfiguration.class, …)`를 `FlywaySchemaPolicy` 밖에서 거부하는 조건을 더한다. 대안: 문서를 "`Flyway.configure()`를 부르지 않는다"로 좁힌다(지키는 범위에 말을 맞춤, 권하지 않음 — 막으려는 피해가 그대로 남는다). RED: 둘째·셋째 길로 Flyway를 만드는 위반 fixture가 지금 규칙을 통과한다. +- **이번 수정 / 이전부터**: 이번 수정(규칙과 문장 모두 r10이 만들었다). +- **증거**: E1(규칙 코드와 Flyway 11.14.1의 공개 생성자). + +### 3차 반영 뒤 결론 + +Critical 0, Important 1(RR7-03-03), 회귀 0. 결함 6건: 이번 수정 3(RR7-03-01·04·06), 섞임 1(RR7-03-02), 이전부터 2(RR7-03-03·05). From b7d131045993b9b9572f6e27235ca751c65aeb0e Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Sat, 7 Nov 2026 00:24:58 +0900 Subject: [PATCH 20/71] =?UTF-8?q?fix(scripts):=20=EC=9D=B4=EB=A0=A5=20?= =?UTF-8?q?=EA=B2=80=EC=82=AC=EA=B0=80=20=EC=95=9E=EB=A7=90=20=EC=97=86?= =?UTF-8?q?=EB=8A=94=20=EB=B2=88=ED=98=B8=20=EB=AA=A9=EB=A1=9D=C2=B7?= =?UTF-8?q?=EB=A6=AC=EB=B7=B0=20=EC=98=81=EC=97=AD=C2=B7=EB=AC=B6=EC=9D=8C?= =?UTF-8?q?=20=EB=B2=88=ED=98=B8=EB=A5=BC=20=EC=9E=A1=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: check-work-docs.py --history는 리뷰·라운드 낱말 바로 뒤의 NN-NN만 발견 번호로 본다. 그래서 앞말 없이 나열한 "(05-01, 04-01, 06-01)", "리뷰 01 영역 5.2절", "sample P30 결정"을 놓친다. 2026-11-07 docs/manual 이력 걷어내기에서 검사가 찾은 16줄을 고친 뒤 docs-writing.md 9절대로 grep으로 다시 읽으니 이 꼴 3줄이 더 있었다. 고른 방법: 패턴 셋을 더한다. - 쉼표+공백이나 가운뎃점으로 이은 NN-NN 둘 이상. 콜론 뒤 줄 범위 ("Foo.java:10-12,20-24")와 공백 없는 쉼표 범위는 잡지 않는다 - "리뷰 NN 영역", "NN 영역 N.N절" - 2026-09-25 리뷰 후속 묶음 번호 P10~P49와 "W3-P30" 꼴 버린 대안: - 홀로 선 NN-NN 하나까지 잡기. 장 번호·범위 같은 보통 숫자가 걸린다 - P 뒤 두 자리를 모두 잡기. P95·P99 같은 백분위수가 걸린다 위험·한계: 검사는 여전히 아는 꼴만 잡는다. P1~P9 묶음 번호는 우선순위 P0~P3과 겹쳐 잡지 않는다. 문서가 자기 목록에 P10~P49 번호를 붙이면 이력이 아니어도 잡는다(docs/study/graphql-walkthrough.ko.md의 할 일 번호 P10·P11). 지금 검사 대상인 docs/work 본문과 docs/manual에는 그런 줄이 없다. 이 커밋만 있으면 --history docs/manual이 19줄, rc=1이다. 다음 커밋이 그 19줄을 걷어낸다. 기본 모드(docs/work 본문, 루트 CLAUDE.md)는 0줄 그대로다. 검증(desktop worktree, 다음 커밋까지 얹은 트리 8ff82a67과 같은 스크립트): - 기준 커밋 73d39212의 docs/manual: 옛 스크립트 16줄, 새 스크립트 19줄. 더 잡은 3줄은 03-placement.md:40·:54, 05-idempotency.md:93이다 - 오탐 시험 14줄: 보통 문장 8줄(p95·P99, 콜론 뒤 줄 범위, 날짜 쌍, 홀로 선 번호, 장 번호)은 안 잡고 이력 6줄은 잡았다 - 노트북에서 docs/reviews 밖 *.md에 새 패턴을 돌려 걸린 65줄을 읽었다. 위 할 일 번호 4줄 말고는 모두 실제 이력 번호였다 - 기본 모드 rc=0, 본문 이력 0줄 --- scripts/check-work-docs.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/scripts/check-work-docs.py b/scripts/check-work-docs.py index ed88b94b..1789f6db 100755 --- a/scripts/check-work-docs.py +++ b/scripts/check-work-docs.py @@ -87,6 +87,15 @@ HISTORY_PATTERNS = [ ("finding number after a review or round word (리뷰 02-01)", re.compile(r"(?:리뷰|라운드|(? Date: Sat, 7 Nov 2026 00:25:22 +0900 Subject: [PATCH 21/71] =?UTF-8?q?docs(manual):=20=EB=B3=B8=EB=AC=B8?= =?UTF-8?q?=EC=97=90=20=EB=82=A8=EC=9D=80=20=EC=9D=B4=EB=A0=A5=20ID=2019?= =?UTF-8?q?=EC=A4=84=EC=9D=84=20=EB=82=B4=EC=9A=A9=EA=B3=BC=20=EB=82=A0?= =?UTF-8?q?=EC=A7=9C=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 문제: docs/manual 본문 19줄이 "리뷰 02-01 결정", "1라운드 06-01·06-03", "리뷰 README 13.2, 09-02", "(05-01, 04-01, 06-01)", "sample P30 결정"처럼 지난 리뷰 번호만으로 이유를 댄다. 그 리뷰를 모르는 독자는 따라갈 수 없고, docs-writing.md 4절 6단계가 금지한다. 16줄은 --history 검사가 찾았고, 3줄은 걷어낸 뒤 grep으로 다시 읽어 찾았다. 고른 방법: 문장의 뜻은 두고 괄호만 바꾼다. - 문장이 이미 내용을 말하는 곳(6줄)은 괄호를 지운다 - 지난 일이 근거인 곳은 날짜와 일어난 일로 바꾼다. 예: "2026-11-01 소유자 결정", "2026-11-01부터. 전에는 비어 있으면 검증을 건너뛰었다" - README 제목 "1라운드 수정으로 생긴 패턴 (리뷰 README 13절)"은 "리뷰 뒤 첫 수정으로 생긴 패턴"으로 바꾼다. 이 제목을 가리키는 링크는 repo에 없다 걷어낸 번호와 원래 괄호, 원래 리뷰 문서와 발견 내용은 docs/work/evidence.md 8절에 표로 더했다(2026-11-06 표와 같은 칸). 버린 대안: 리뷰 문서로 링크 걸기. 본문이 다시 이력을 가리킨다. 위험·한계: 날짜와 "전에는" 문장은 1101 README 13절·15절과 영역 문서의 색인 문장에서 옮겼다. 코드로 다시 확인하지는 않았다. evidence.md 9절 T4-1 행("16줄은 고치지 않음")은 그때의 기록이라 고치지 않았다. 검증(desktop worktree, 이 커밋과 같은 트리 8ff82a67): - python3 scripts/check-work-docs.py --history docs/manual lines with history IDs: 0, rc=0 - python3 scripts/check-work-docs.py rc=0(분량, 본문 이력 0, 링크) - python3 scripts/check-work-docs.py --links docs/manual docs/work 링크 113개, 깨진 것 0 - ./gradlew :app-bootstrap:documentContractTest rc=0, 22개 클래스 66건 통과, 실패·skip 0. docs/manual과 docs/work를 읽는 테스트는 없다 (src의 Java·Gradle에서 파일 이름·폴더 경로 grep, 주석 2곳만 걸림) - grep -e 리뷰 -e 라운드 -e 결정 docs/manual/*.md로 남은 줄을 읽었다. 모두 날짜와 내용이 있는 문장이다 --- docs/manual/03-placement.md | 4 ++-- docs/manual/04-persistence.md | 4 ++-- docs/manual/05-idempotency.md | 9 +++++---- docs/manual/06-errors.md | 4 ++-- docs/manual/07-authorization.md | 9 +++++---- docs/manual/08-testing.md | 6 ++++-- docs/manual/09-outbox-events.md | 10 +++++----- docs/manual/README.md | 6 +++--- docs/work/evidence.md | 27 ++++++++++++++++++++++++++- 9 files changed, 54 insertions(+), 25 deletions(-) diff --git a/docs/manual/03-placement.md b/docs/manual/03-placement.md index 01ecf57a..3344a841 100644 --- a/docs/manual/03-placement.md +++ b/docs/manual/03-placement.md @@ -37,7 +37,7 @@ - **예외**: ② — 여러 서비스가 쓰는 플랫폼 기능, 배포마다 켜고 끄는 기능, 자기 설정 prefix와 자기 저장소를 가진 기능. 이때는 capability 완료 기준 7개를 모두 지킨다(`AGENTS.md`, 10장). - **다시 볼 조건**: 파생 서비스가 둘 이상 생겨 같은 업무 기능을 공유하거나, application-core 컴파일·테스트 - 시간이 문제가 되면 ①을 ②로 옮긴다(리뷰 01 영역 5.2절). + 시간이 문제가 되면 ①을 ②로 옮긴다. ### 판단: ③을 써도 되나 @@ -51,7 +51,7 @@ | 계층 | 패키지 | 하위 패키지 | | --- | --- | --- | | domain | `dev.caskeleton.domain.` | fake·계약은 testFixtures `dev.caskeleton.domain..testkit` | -| application | `dev.caskeleton.application.` | 종류별 하위 패키지(`command`, `usecase`, `port`)를 만들지 않는다. 기능별 한 패키지(sample P30 결정과 같다) | +| application | `dev.caskeleton.application.` | 종류별 하위 패키지(`command`, `usecase`, `port`)를 만들지 않는다. 기능별 한 패키지(`sample-portfolio`도 2026-09-29에 이 배치로 옮겼다) | | outbound | `dev.caskeleton.adapter.outbound..` | | | inbound | `dev.caskeleton.adapter.inbound.web.` | | | bootstrap | `dev.caskeleton.bootstrap.autoconfigure.` | `@AutoConfiguration`만(`BOOTSTRAP_AUTOCONFIGURE_STEREOTYPES_ARE_AUTO_CONFIGURATIONS`) | diff --git a/docs/manual/04-persistence.md b/docs/manual/04-persistence.md index f009b847..8078aa70 100644 --- a/docs/manual/04-persistence.md +++ b/docs/manual/04-persistence.md @@ -127,8 +127,8 @@ capability 스트림 db/migration/jpa/ 각자 histor - 이미 적용된 파일은 고치지 않는다. 고치면 체크섬 불일치로 기동이 멈추고, `repair`는 쓰지 않는다 (`docs/jpa/migration-guide.md`). - 같은 스트림 안에서 기존 두 버전 사이에 끼워야 하면 소수 버전(`V8_1`)을 쓴다. 샘플 테스트 일부가 운영 - 스트림과 샘플 스트림을 한 목록으로 합치는데, 정수 V9 이상은 운영이 이미 쓰고 있어서 `V8_1`을 골랐다 - (리뷰 README 13.2, 09-02). + 스트림과 샘플 스트림을 한 목록으로 합치는데, 정수 V9 이상은 운영이 이미 쓰고 있어서 2026-11-01 샘플에 + 포스터 제목 유일 제약을 더할 때 `V8_1`을 골랐다. - 기존 데이터가 새 제약을 어기면 마이그레이션이 이유를 남기고 멈추게 쓴다(`V8_1`의 `DO $$` 블록). 조용히 지우지 않는다. - 운영 중인 테이블을 잠그는 문장(`ALTER TABLE`, `CONCURRENTLY` 없는 `CREATE INDEX`, `UPDATE`·`DELETE`, 기존 diff --git a/docs/manual/05-idempotency.md b/docs/manual/05-idempotency.md index 72cde83c..45b62dd5 100644 --- a/docs/manual/05-idempotency.md +++ b/docs/manual/05-idempotency.md @@ -85,13 +85,13 @@ claim의 lease가 작업 시작 전에 끝나면 두 저장소 모두 시작을 소유자 결정). 거꾸로 말하면 `replay-ttl`(`APP_IDEMPOTENCY_TTL`)은 lease 이상, `failure-retention` 이하로 둔다. -409를 `retryable=true`로 바꾼 이유(리뷰 02-01 결정): 같은 키 재전송은 서버가 안전하게 판정하므로 다시 +409를 `retryable=true`로 바꾼 이유(2026-11-01 소유자 결정): 같은 키 재전송은 서버가 안전하게 판정하므로 다시 보내는 것이 맞고, 새 키로 보내면 서버가 막지 못한다. 짝 프론트 분류기도 이 표를 따른다. ## 결과 불명을 만드는 곳마다 같은 규칙 -리뷰가 찾은 반복 원인 1번이 "결과 불명을 확실함으로 기록"이었다(05-01, 04-01, 06-01). 새 경계를 -만들 때 아래 질문에 답한다. +2026-11-01 성숙도 리뷰가 찾은 반복 원인 첫째가 "결과 불명을 확실함으로 기록"이었다. 알림 발송·DB +커밋·메시지 relay 세 경계에서 같은 실수가 나왔다. 새 경계를 만들 때 아래 질문에 답한다. - **고르는 기준**: 실패한 호출이 **상대편에서 이미 효과를 냈을 수 있는가**. - **기본값**: 그럴 수 있으면 "결과 불명"으로 분류한다. 재시도 가능(`retryable=true`)으로 분류하지 @@ -101,7 +101,8 @@ claim의 lease가 작업 시작 전에 끝나면 두 저장소 모두 시작을 - 메시지 발행 응답 없음 → `OutboxPublishAmbiguousException`(application-core `outbox`) - 알림 발송 시작 뒤 crash → 재발송하지 않고 reconcile(application-notification evidence 모델) - **예외**: 요청이 상대에게 **도달하기 전**에 실패한 것이 증명되면(연결 수립 실패, 실행 전 거부) - 재시도 가능이다. 반대 방향 실수(확실히 안 간 것을 불명으로)도 결함이다(리뷰 05-17). + 재시도 가능이다. 반대 방향 실수(확실히 안 간 것을 불명으로)도 결함이다(2026-11-01 성숙도 리뷰가 + Redis 연결 수립 실패에서 찾았다). - 불명 상태를 푸는 방법(reconcile, 키 재전송, 운영자 확인)을 runbook에 적는다(`docs/runbooks/`). ## 지금 이해하면 되는 것 diff --git a/docs/manual/06-errors.md b/docs/manual/06-errors.md index d80efb4b..20a36e35 100644 --- a/docs/manual/06-errors.md +++ b/docs/manual/06-errors.md @@ -42,8 +42,8 @@ gRPC/GraphQL/WebSocket: 같은 ApiErrorCarrier를 자기 status 모양으로 | DB·외부 의존 실패 | adapter가 shared-contract carrier(`PersistenceFailureException`, `DependencyFailureException`)로 | 분류표대로(04·05장) | - `IllegalArgumentException`을 "서버 조립이 틀렸다"에 쓰지 않는다. web은 그것을 400으로 바꾸고 WARN - 한 줄만 남긴다(`GlobalExceptionHandler`). 서버 결함이 클라이언트 오류 통계에 섞여 경보가 울리지 않는다 - (리뷰 01-04). 서버 쪽 잘못은 `IllegalStateException`(500, 로그)이다. + 한 줄만 남긴다(`GlobalExceptionHandler`). 서버 결함이 클라이언트 오류 통계에 섞여 경보가 울리지 않는다. + 서버 쪽 잘못은 `IllegalStateException`(500, 로그)이다. - 메시지는 로그용이다. 클라이언트에는 코드와 category별 고정 문구(`ClientErrorMessages`)만 간다. 메시지에 SQLState·내부 경로·토큰을 넣어도 클라이언트에 새지 않지만, 로그 정책은 지킨다. diff --git a/docs/manual/07-authorization.md b/docs/manual/07-authorization.md index c1f0bd40..ca6d36eb 100644 --- a/docs/manual/07-authorization.md +++ b/docs/manual/07-authorization.md @@ -25,7 +25,8 @@ | 프록시 가능 | `src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/authz/RequiresPermissionProxyabilityTest.java` | 검사 자동 설정은 인증 체인(`WebSecurityAutoConfiguration`)과 **분리**되어 있다. 서비스가 자기 인증 -방식으로 인증 체인을 바꿔도 권한 검사는 꺼지지 않는다(1라운드 07-03 수정). +방식으로 인증 체인을 바꿔도 권한 검사는 꺼지지 않는다(2026-11-01부터. 전에는 샘플이 인증 체인 자동 설정을 +빼자 권한 검사도 함께 빠졌다). ### 지켜야 할 것 셋 @@ -48,8 +49,8 @@ ### 역할은 어디서 오나 JWT의 `realm_access.roles`와 **자기 client**(`app.security.audience`)의 `resource_access..roles`만 -읽는다. audience는 필수다(1라운드 02-03 수정). 같은 issuer의 다른 client가 같은 이름의 역할을 정의해도 -이 서비스 권한이 되지 않는다(`JwtToAuthenticatedPrincipalConverter`, `docs/runbooks/auth-audience-mismatch.md`). +읽는다. audience는 필수다(2026-11-01부터. 전에는 비어 있으면 검증을 건너뛰었다). 같은 issuer의 다른 +client가 같은 이름의 역할을 정의해도 이 서비스 권한이 되지 않는다(`JwtToAuthenticatedPrincipalConverter`, `docs/runbooks/auth-audience-mismatch.md`). ## 객체 단위 권한 @@ -143,7 +144,7 @@ JWT의 `realm_access.roles`와 **자기 client**(`app.security.audience`)의 `re ## web 없는 조립 web이 빠진 조립(gRPC 전용·배치 전용)에는 `@RequiresPermission`을 검사할 advisor가 없다. 그런 조립에 -권한을 선언한 bean이 있으면 `PermissionEnforcementGuard`가 기동을 실패시킨다(리뷰 01-06). web 없이 +권한을 선언한 bean이 있으면 `PermissionEnforcementGuard`가 기동을 실패시킨다. web 없이 조립하는 서비스는 자기 전송에 맞는 검사 advisor를 함께 넣어야 기동한다. ## 지금 이해하면 되는 것 diff --git a/docs/manual/08-testing.md b/docs/manual/08-testing.md index 8cba48dd..738ae979 100644 --- a/docs/manual/08-testing.md +++ b/docs/manual/08-testing.md @@ -46,7 +46,8 @@ fake와 실제 adapter가 **같은 계약**을 통과해야 fake 위의 유스 - **고르는 기준**: 포트 인터페이스가 어느 leaf에 있나. - **기본값**: 그 leaf의 `src/testFixtures/java/...//testkit/`. domain 포트면 domain-core, application 포트면 application-core. 소비 leaf는 `testImplementation testFixtures(project(':'))`. -- **예외**: 없다. 테스트 안 private fake는 계약 밖에 있어 실제와 갈라진다(리뷰 01-05의 lock fake). +- **예외**: 없다. 테스트 안 private fake는 계약 밖에 있어 실제와 갈라진다(2026-11-01 성숙도 리뷰가 + 분산 lock 포트 계약 테스트 안의 fake에서 찾았다). ## lane과 단계 @@ -71,7 +72,8 @@ lane으로 선언하고 단계를 지정한다. 선언은 `ca.strict-test-lane`( - **예외**: 반드시 실행돼야 하는 소수 테스트(계약 자격 검사)는 `requires(클래스)` + `rejectSkipped = true`로 이름을 박는다. 이름이 바뀌거나 지워지면 lane이 실패한다. - 새 lane이 어떤 단계에도 속하지 않으면 PR 게이트의 `verifyStrictLaneStages --dry-run`이 실패한다 - (1라운드 08-01). 단계는 집계 태스크(`integrationCheck` 등)를 통해 붙고, workflow 파일을 고치지 않는다. + (2026-11-01부터. 전에는 어떤 workflow도 돌리지 않는 strict lane이 14개 있었다). 단계는 집계 + 태스크(`integrationCheck` 등)를 통해 붙고, workflow 파일을 고치지 않는다. ## 지금 이해하면 되는 것 diff --git a/docs/manual/09-outbox-events.md b/docs/manual/09-outbox-events.md index 8d884b87..2a208669 100644 --- a/docs/manual/09-outbox-events.md +++ b/docs/manual/09-outbox-events.md @@ -35,7 +35,7 @@ DB 저장과 broker 발행을 따로 하면(dual write) 둘 중 하나만 성공 6. schema를 출시한다: `src/test/resources/contracts/released-payload-schemas.sha256`에 새 version 파일의 해시를 한 줄 더한다. 출시한 version 파일은 고치지 않는다 — 바뀌면 `ReleasedPayloadSchemaContract` 테스트가 실패한다. 필드를 바꾸는 변경은 새 version으로 낸다. 절차: `src/application-core/README.md` - "payload version 올리기"(리뷰 06-10). + "payload version 올리기". ## 판단 지점 @@ -61,7 +61,7 @@ draft는 `IntegrationEventDrafts.draft(contract, eventId, aggregate, order, occu - event id: 정규 소문자 UUIDv7, 소비자 중복 제거 키. draft(`IntegrationEventDraft`)가 다른 값(대문자, v4, `event-1` 같은 문자열)을 거부하므로 업무 쓰기에서 바로 실패한다 — 커밋된 뒤 relay에서 DEAD가 되지 - 않는다(리뷰 06-06). 같은 작업의 재시도가 같은 event id를 내야 하면(durable operation) 작업 id를 쓰고, + 않는다. 같은 작업의 재시도가 같은 event id를 내야 하면(durable operation) 작업 id를 쓰고, 작업 id가 UUIDv7이 아니면 작업 id와 접수 시각에서 UUIDv7을 파생한다. - correlation: 헬퍼가 정한다. 요청의 correlation id가 `IntegrationIdentity` 문법·길이에 맞으면 그것, 아니면 event id. 문법 밖 헤더가 업무 쓰기를 실패시키지 않는다. 값을 미리 검사해야 하면 문법을 베끼지 @@ -70,7 +70,7 @@ draft는 `IntegrationEventDrafts.draft(contract, eventId, aggregate, order, occu - tenant 범위: tenant가 없는 기능은 `IntegrationEventDrafts.SINGLE_TENANT_SCOPE`(`global`). - aggregate 순서: `OutboxAggregateSequencePort.nextSequence(aggregate)`로 같은 `tx.inWrite` 안에서 받는다(V21 카운터, 커밋 순서를 따른다). 이벤트가 하나뿐인 aggregate는 `AggregateOrder.first()`. 발생 - 시각(벽시계)은 쓰지 않는다 — 서버 시계가 어긋나면 순서가 뒤집힌다(리뷰 06-07). 벽시계 번호를 쓰던 + 시각(벽시계)은 쓰지 않는다 — 서버 시계가 어긋나면 순서가 뒤집힌다. 벽시계 번호를 쓰던 서비스가 포트로 옮기면 V21 floor 덕분에 새 번호는 옛 번호 뒤에서 시작한다. 그래서 첫 번호가 1이 아니라 약 1.7×10¹⁵일 수 있다. 소비자는 번호를 "마지막으로 본 값보다 큰가"로만 비교하고 연속성을 가정하지 않는다. 비교는 aggregate identity(tenant scope 포함) 단위다. tenant scope를 바꾸는 배포는 옛 @@ -83,8 +83,8 @@ draft는 `IntegrationEventDrafts.draft(contract, eventId, aggregate, order, occu 선언이 없어서, bean이 되면 전송 계층이 **권한 검사 없이** 닿는다. 그래서 bean으로 등록하면 `PermissionEnforcementGuard`가 기동을 실패시킨다(07장 「시스템이 부르는 쓰기」). - broker의 **재시도 가능한** 거부와 응답 없음은 DEAD가 아니라 backoff 재시도다. broker가 멈춰도 대량 - DEAD가 되지 않는다(1라운드 06-01·06-03). 대신 끝이 없다: 진짜 인증 오류, Kafka adapter가 이름을 모르는 - broker 거부도 영원히 재시도된다. 행의 `last_failure_code`와 로그의 `error.reason`이 원인 코드를 남기고, + DEAD가 되지 않는다(2026-11-01부터. 전에는 broker가 몇 분만 멈춰도 행이 대량으로 DEAD가 됐다). 대신 + 끝이 없다: 진짜 인증 오류, Kafka adapter가 이름을 모르는 broker 거부도 영원히 재시도된다. 행의 `last_failure_code`와 로그의 `error.reason`이 원인 코드를 남기고, `outbox.retry.long.size`가 오래 재시도 중인 행을 센다. 처분(보류·재개·skip)은 publish-failed runbook §4.1이다. - 발행 응답을 못 받으면 결과 불명(`OutboxPublishAmbiguousException`) — 05장 규칙과 같다. diff --git a/docs/manual/README.md b/docs/manual/README.md index 8ad6ff24..ea2ce530 100644 --- a/docs/manual/README.md +++ b/docs/manual/README.md @@ -56,7 +56,7 @@ ## 따라 할 예시는 하나 예시가 셋(sample-portfolio 수직, onboarding fixture, durable operation)이라 어느 것을 베끼느냐에 따라 -배치가 달라졌다(리뷰 2026-11-01 01-01·07-09). 이제 **새 업무 기능의 예시는 생성 명령의 출력 하나**다. +배치가 달라졌다(2026-11-01 성숙도 리뷰). 이제 **새 업무 기능의 예시는 생성 명령의 출력 하나**다. | 코드 | 역할 | 따라 하나 | | --- | --- | --- | @@ -65,9 +65,9 @@ | `src/app-bootstrap/src/test/java/dev/caskeleton/onboarding/**` | ArchUnit 규칙이 새 기능 모양에 적용되는지 확인하는 테스트 fixture | 따르지 않는다 | | `application-core/.../operation` + `DurableOperationAutoConfiguration`(composition:durable-operation) | 템플릿 플랫폼 기능 | 조립 모양(`@ConditionalOnBean` + 유스케이스 `@Bean`)만 본다 | -## 1라운드 수정으로 생긴 패턴 (리뷰 README 13절) +## 리뷰 뒤 첫 수정으로 생긴 패턴 -리뷰 뒤 1라운드에서 굳은 모양이다. 각 장에 반영했다. +2026-11-01 성숙도 리뷰 뒤 같은 날 한 첫 수정에서 굳은 모양이다. 각 장에 반영했다. | 패턴 | 근거 코드 | 장 | | --- | --- | --- | diff --git a/docs/work/evidence.md b/docs/work/evidence.md index 05b9697b..1d985b92 100644 --- a/docs/work/evidence.md +++ b/docs/work/evidence.md @@ -150,7 +150,7 @@ - 나머지 20건은 round6 Minor다(`RR6-01-02`~`06`·`08`·`09`, `RR6-02-02`·`04`·`05`, `RR6-03-02`~`05`, `RR6-04-01`~`06`). README 17절은 영역별 건수만 적었고, r10 묶음이 영역 단위로 고쳤다. - 이 검사는 "색인에 이름이 있나"만 본다. 고쳤는지는 처리 표와 확인 리뷰가 본다. 앞으로의 리뷰 README는 모든 ID를 이름으로 적는다(`improve.md` 4.1절 7단계). -## 8. `docs/manual/`에서 걷어낸 이력 ID (2026-11-06) +## 8. `docs/manual/`에서 걷어낸 이력 ID (2026-11-06, 2026-11-07) `docs/manual/` 본문에서 리뷰 ID와 번호만 쓴 결정을 걷어냈다. 문장의 뜻은 그대로이고, 괄호 안 근거만 여기로 옮겼다. 줄 번호는 걷어내기 전 기준 커밋 `06f520e6`의 줄이다. @@ -167,6 +167,31 @@ - `RR-01-11`·`RR-02-10`·`RR-03-11`은 2차 재리뷰(`round2/`) 문서의 발견이다. 그 문서들은 1차 번호에 이어 `RR-` 접두어를 그대로 썼다(머리말 「표기」). +2026-11-07에 남은 19줄을 같은 방식으로 걷어냈다. 16줄은 2026-11-06 검사 패턴을 넓힌 뒤 드러난 줄이다(9절 T4-1). 3줄(아래 표에서 「손으로 찾음」)은 그 패턴도 못 잡아 `docs-writing.md` 9절대로 grep으로 찾았고, 그 꼴을 잡는 패턴 셋을 `scripts/check-work-docs.py`에 더했다. 줄 번호는 걷어내기 전 기준 커밋 `73d39212`의 줄이다. 「1라운드」는 `1101` README 13절 「조치 현황 (개선 순서 1~3)」으로, 리뷰 직후 2026-11-01에 한 첫 수정이다(같은 날 밤 13.1절 게이트, 14절 「2라운드」가 이어졌다). 영역 문서 이름은 `docs/reviews/2026-11-01-maturity-review/` 안의 파일이다. + +| 원래 위치 | 원래 괄호 | 지금 본문 | 근거 | +| --- | --- | --- | --- | +| `docs/manual/README.md:59` | "리뷰 2026-11-01 01-01·07-09" | "2026-11-01 성숙도 리뷰" | `1101/01-01`(새 기능을 어느 leaf에 두는지 세 가지 모양이 있고 고르는 기준이 없다, `01-core-and-feature-pattern.md`), `1101/07-09`(새 기능을 만들 때 따라 할 예시가 세 갈래다, `07-bootstrap-composition-config.md`) | +| `docs/manual/README.md:68`, `:70` | 제목 "1라운드 수정으로 생긴 패턴 (리뷰 README 13절)", 본문 "리뷰 뒤 1라운드" | 제목 "리뷰 뒤 첫 수정으로 생긴 패턴", 본문 "2026-11-01 성숙도 리뷰 뒤 같은 날 한 첫 수정" | `1101` README 13절. 표의 패턴 행은 13절 각 행의 수정 내용이다 | +| `docs/manual/03-placement.md:40` (손으로 찾음) | "리뷰 01 영역 5.2절" | 괄호를 지웠다. 다시 볼 조건 문장이 내용 전부다 | `01-core-and-feature-pattern.md` 5.2절 「새 기능의 배치」 표의 「7. 바뀔 조건」 | +| `docs/manual/03-placement.md:54` (손으로 찾음) | "sample P30 결정과 같다" | "`sample-portfolio`도 2026-09-29에 이 배치로 옮겼다" | P30은 2026-09-25 리뷰 후속 작업 Wave 3 라운드 4의 묶음 이름이다. 그 묶음이 `S6-#10a`(sample 패키지가 종류별·기능별로 섞였다)를 고쳐 sample application을 기능별 패키지로 옮겼다(`docs/reviews/2026-09-25-review-followup-status.md` `S6-#10a` 행, 커밋 `8bbf1bf01`, 2026-09-29). `07-bootstrap-composition-config.md` 07-09 「근거」의 "P30 결정"도 같은 것이다 | +| `docs/manual/04-persistence.md:131` | "리뷰 README 13.2, 09-02" | "2026-11-01 샘플에 포스터 제목 유일 제약을 더할 때" | `1101/09-02`(포스터 제목 중복 규칙이 동시 요청에서 깨지고 검사 쿼리가 순차 스캔이다, `09-performance-measurement.md`). 번호 선택은 `1101` README 13.2절 「09-02 마이그레이션 번호」 행 | +| `docs/manual/05-idempotency.md:88` | "리뷰 02-01 결정" | "2026-11-01 소유자 결정" | `1101/02-01`("처리 중" 409의 클라이언트 행동이 코드·문서·짝 계약에서 서로 다르다, `02-inbound-web.md`). 고른 안은 `1101` README 5절 (A), 소유자 결정은 15절 「처리 중 409」 행 "소유자 결정(11-01)" | +| `docs/manual/05-idempotency.md:93` (손으로 찾음) | "리뷰가 찾은 반복 원인 1번", "(05-01, 04-01, 06-01)" | "2026-11-01 성숙도 리뷰가 찾은 반복 원인 첫째", "알림 발송·DB 커밋·메시지 relay 세 경계" | `1101` README 4절 1번. `1101/05-01`(알림 attempt를 "시작 안 함(확정)"으로 저장한 채 provider를 부른다), `1101/04-01`(커밋 중 끊김을 재시도 가능으로 답한다), `1101/06-01`(재시도 가능한 거부를 즉시 DEAD로 보낸다) | +| `docs/manual/05-idempotency.md:104` | "리뷰 05-17" | "2026-11-01 성숙도 리뷰가 Redis 연결 수립 실패에서 찾았다" | `1101/05-17`(Redis 연결 실패를 결과 불명으로 보고하고, 시간 초과된 연결을 pool에 돌려준다, `05-outbound-capabilities.md`). README 4절 1번의 "반대 방향" | +| `docs/manual/06-errors.md:46` | "리뷰 01-04" | 괄호를 지웠다 | `1101/01-04`(`IllegalArgumentException` 하나가 입력 오류와 서버 조립 오류를 함께 뜻하고, web은 둘 다 로그 없이 400으로 바꾼다, `01-core-and-feature-pattern.md`) | +| `docs/manual/07-authorization.md:28` | "1라운드 07-03 수정" | "2026-11-01부터. 전에는 샘플이 인증 체인 자동 설정을 빼자 권한 검사도 함께 빠졌다" | `1101/07-03`(실행 중인 샘플에서 `@RequiresPermission`이 아무 일도 하지 않았다, `07-bootstrap-composition-config.md`). 수정은 `1101` README 13절 `07-03+09-03` 행 | +| `docs/manual/07-authorization.md:51` | "1라운드 02-03 수정" | "2026-11-01부터. 전에는 비어 있으면 검증을 건너뛰었다" | `1101/02-03`(JWT audience 검증이 기본으로 꺼져 있고 모든 client의 role을 합친다, `02-inbound-web.md`). 수정은 13절 `02-03+07-05` 행 | +| `docs/manual/07-authorization.md:146` | "리뷰 01-06" | 괄호를 지웠다 | `1101/01-06`(`@RequiresPermission`은 application 계약인데 검사는 web leaf가 켜 주는 AOP에만 있다, `01-core-and-feature-pattern.md`) | +| `docs/manual/08-testing.md:49` | "리뷰 01-05의 lock fake" | "2026-11-01 성숙도 리뷰가 분산 lock 포트 계약 테스트 안의 fake에서 찾았다" | `1101/01-05`(application-core 포트 절반이 fake·adapter 공유 계약 밖에 있다, `01-core-and-feature-pattern.md`). lock fake는 그 근거 칸의 `DistributedLockPortContractTest.java:46` private 클래스다 | +| `docs/manual/08-testing.md:74` | "1라운드 08-01" | "2026-11-01부터. 전에는 어떤 workflow도 돌리지 않는 strict lane이 14개 있었다" | `1101/08-01`(CI가 실행하지 않는 strict lane 14개, `08-build-ci-test.md`). 수정은 13절 `08-01+08-04+03-12` 행 | +| `docs/manual/09-outbox-events.md:38` | "리뷰 06-10" | 괄호를 지웠다 | `1101/06-10`(이벤트 payload 버전을 올리는 방법과 호환성 검사가 없다, `06-messaging.md`. 색인 누락을 정정하며 붙은 번호) | +| `docs/manual/09-outbox-events.md:64` | "리뷰 06-06" | 괄호를 지웠다 | `1101/06-06`(application EventId 문법과 platform MessageId(UUID)가 다르다, `06-messaging.md`) | +| `docs/manual/09-outbox-events.md:73` | "리뷰 06-07" | 괄호를 지웠다 | `1101/06-07`(샘플이 aggregate 순서 번호를 벽시계로 만든다, `06-messaging.md`) | +| `docs/manual/09-outbox-events.md:86` | "1라운드 06-01·06-03" | "2026-11-01부터. 전에는 broker가 몇 분만 멈춰도 행이 대량으로 DEAD가 됐다" | `1101/06-01`(다시 시도하면 될 거부를 relay가 즉시 DEAD로 보낸다), `1101/06-03`(broker가 몇 분만 멈춰도 행이 대량으로 DEAD가 된다), 둘 다 `06-messaging.md`. 수정은 13절 `06-01+06-03` 행 | + +- 더한 패턴 셋: 앞말 없이 나열한 발견 번호(`05-01, 04-01`, `01-01·07-09`), 리뷰 영역 번호(`리뷰 01 영역`, `01 영역 5.2절`), 리뷰 후속 묶음 번호(`P30`, `W3-P30`. P50 이상은 백분위수라 잡지 않는다). 홀로 선 `NN-NN` 하나는 보통 범위나 장 번호일 수 있어 여전히 잡지 않는다. + ## 9. cold-read 시험 1회차 빈틈 처리 (2026-11-06) 2026-11-06 이력 없는 세션 6개에 이 매뉴얼만 주고 실제 일을 시켰다(기준선 1개는 옛 매뉴얼). 6개 모두 일은 끝냈지만 매뉴얼에서 답을 못 찾은 곳이 1~9건씩 나와 모두 불합격이었다. 아래는 시험 기록(design-docs `delegation-loop/trials/2026-11-06-*.md`)의 「질문」·「위반」 표와 각 세션 공유 노트(`~/.config/Claude/side-session-notes/local_fcd89c34-c754-4c5b-a38f-fa322834286f/`)의 「매뉴얼에서 답을 못 찾은 곳」을 한 줄씩 처리한 결과다. 기준 커밋 `2c8a359d`. From 6dd9ef761311d3d4584a1cbe79d3fa0142a03071 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Sat, 7 Nov 2026 00:27:59 +0900 Subject: [PATCH 22/71] =?UTF-8?q?fix(scripts):=20=EC=9D=B4=EB=A0=A5=20?= =?UTF-8?q?=EA=B2=80=EC=82=AC=EA=B0=80=20"2~3=EB=9D=BC=EC=9A=B4=EB=93=9C?= =?UTF-8?q?=20=EB=8F=99=EC=95=88"=20=EA=B0=99=EC=9D=80=20=ED=9A=9F?= =?UTF-8?q?=EC=88=98=EB=A5=BC=20=EC=9E=A1=EC=A7=80=20=EC=95=8A=EA=B2=8C=20?= =?UTF-8?q?=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 앞 커밋에서 더한 한국어 라운드 번호 패턴이 "1라운드"(지난 라운드 하나의 이름)와 "2~3라운드 동안"(라운드 수)을 가르지 못한다. 확인 리뷰를 독립 리뷰어 둘로 하는 소유자 결정을 delegate.md에 옮기다가 "2~3라운드 기록이 쌓이면"이 이력 ID로 잡혀 기본 검사가 rc=1이 됐다. 고른 방법: 범위 기호(~, -) 바로 뒤의 숫자와, 뒤에 동안·마다·씩·간이 붙는 경우를 뺀다. 버린 대안: 문서에서 "라운드 두세 번"으로 돌려 쓰기. 다음에 쓰는 사람이 같은 오탐을 다시 만난다. 위험·한계: "3라운드 뒤"처럼 다른 낱말이 붙는 횟수는 아직 이력으로 잡는다. 그때는 문장을 고치거나 패턴에 낱말을 더한다. 검증: - 패턴 시험 19건(보통 문장 11, 이력 8)이 모두 기대대로 나왔다 - python3 scripts/check-work-docs.py rc=0, 본문 이력 0줄 - --history docs/manual 결과는 16줄 그대로(rc=1) --- scripts/check-work-docs.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/scripts/check-work-docs.py b/scripts/check-work-docs.py index ed88b94b..716bb9e2 100755 --- a/scripts/check-work-docs.py +++ b/scripts/check-work-docs.py @@ -87,8 +87,9 @@ HISTORY_PATTERNS = [ ("finding number after a review or round word (리뷰 02-01)", re.compile(r"(?:리뷰|라운드|(? Date: Sat, 7 Nov 2026 00:28:14 +0900 Subject: [PATCH 23/71] =?UTF-8?q?docs(work):=20=EC=84=B8=20=EA=B2=BD?= =?UTF-8?q?=EC=9A=B0=EC=9D=98=20=ED=99=95=EC=9D=B8=20=EB=A6=AC=EB=B7=B0?= =?UTF-8?q?=EB=A5=BC=20=EB=8F=85=EB=A6=BD=20=EB=A6=AC=EB=B7=B0=EC=96=B4=20?= =?UTF-8?q?=EB=91=98=EB=A1=9C=20=ED=95=98=EA=B3=A0=20=EC=B4=9D=EA=B4=84?= =?UTF-8?q?=EC=9D=B4=20=ED=95=A9=EC=B9=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 2026-11-06 같은 커밋을 두 세션이 따로 확인 리뷰했더니 합친 결함 8건 중 1건만 겹쳤다. 라운드의 Important 2건도 한 리뷰어의 첫 리뷰 밖에서 나왔다. 반복은 마지막 확인 리뷰의 0건으로 멈추는데, 리뷰어 하나의 0은 남은 결함이 0이라는 증거로 약하다. 고른 방법: 2026-11-07 소유자 결정("(c)로 받기")대로 세 경우에만 서로 결과를 보지 않는 리뷰어 둘이 같은 범위를 보고 총괄이 합친다. - 멈추는 확인 리뷰: 리뷰어 하나가 0을 내면 두 번째가 본다. 둘 다 0이어야 멈춘다(improve.md 4.5 1) - 수정 diff가 상한에 가까운 리뷰: 추가 1,000줄 이상 - Critical·Important를 고친 수정의 리뷰 정본 리뷰어만 리뷰 폴더에 커밋하고 ID를 매긴다. 다른 쪽은 보고에 같은 양식을 두고 임시 번호 B-NN-MM을 쓴다. 합칠 때 총괄이 같은 결함끼리 짝짓고, 다른 쪽에만 있는 결함은 정본 리뷰어가 탐침으로 다시 확인해 다음 번호로 넣는다. 겹침 비율을 색인 절과 지표 기록(M11)에 적는다. 버린 대안: 언제나 둘(비용 약 2배), 지금처럼 하나(멈춤 판정이 약함). 소유자가 2~3라운드 겹침 비율을 보고 다시 정한다. 위험·한계: - "상한에 가까움"을 추가 1,000줄 이상으로 정한 것은 기본값이다 (decisions.md 2.1에 적음) - 세션은 공유 노트 폴더의 다른 노트를 먼저 읽는다. 독립성은 brief의 금지 문장과 노트 이름 분리에 기대고, 막는 장치는 없다 - 같은 범위를 두 번 보므로 그 리뷰의 비용이 약 두 배다 검증: 이 커밋의 트리에서 python3 scripts/check-work-docs.py rc=0. desktop 검증은 다음 커밋의 트리로 했다(그 커밋 본문) --- docs/work/delegate.md | 4 ++++ docs/work/evidence.md | 2 +- docs/work/improve.md | 9 ++++++++- docs/work/reference/decisions.md | 1 + docs/work/reference/review-criteria.md | 2 +- 5 files changed, 15 insertions(+), 3 deletions(-) diff --git a/docs/work/delegate.md b/docs/work/delegate.md index c9800dd1..c123b41b 100644 --- a/docs/work/delegate.md +++ b/docs/work/delegate.md @@ -34,6 +34,9 @@ design-docs `conventions/delegation-loop.md` 3절 순서대로 한다: 크기 - 검증 칸에는 실행 위치와 증거 위치를 쓴다: desktop worktree, `flock /tmp/claude-gates/heavy.lock`, 로그 `~/<작업 이름>-logs/`([operate.md](operate.md) 4.1절). 7절에는 커밋 허용과 자기 브랜치 push 허용을 따로 쓴다. - 수정 묶음 brief에는 보고의 「새로 가정하는 것」 칸을 요구한다. 확인 리뷰 brief에는 그 칸부터 보라고 적고, 지난 라운드에서 열린 채 넘어온 「Declined to judge」를 다시 판정시킬지도 적는다. - 리뷰 brief에는 쓸 심각도 체계([reference/review-criteria.md](reference/review-criteria.md) 3절)와 "발견마다 이번 수정이 만들었나 / 이전부터"를 요구한다. +- 독립 리뷰어 둘([improve.md](improve.md) 4.1절의 세 경우)이면 범위·기준 커밋·심각도 체계가 같은 brief 둘을 쓰고, 두 세션을 함께 띄운다. 다른 칸은 셋이다: 정본 리뷰어인지(ID를 매기고 리뷰 폴더에 커밋한다), 출력 위치(다른 쪽은 보고에 두고 `B-NN-MM`), 5절에 "자기 리뷰를 끝내기 전에 상대 리뷰의 브랜치·문서·보고·노트를 읽지 않는다". +- 두 리뷰가 끝나면 총괄이 합친다. 같은 결함(같은 원인·같은 위치)끼리 짝짓고, 다른 쪽에만 있는 결함은 정본 리뷰어에게 보내 탐침으로 다시 확인한 뒤 다음 번호로 넣게 한다. 그 라운드 색인 절은 총괄이 쓰고 대응표(`B-NN-MM` → 정본 ID)를 둔다. +- 겹침 비율(두 리뷰가 모두 찾은 결함 수 / 합친 결함 수)을 그 라운드 색인 절과 design-docs `delegation-loop/metrics.md`의 M11 칸에 적는다. 2~3라운드 기록이 쌓이면 소유자가 이 방식을 다시 본다. - 대조할 때: 보고의 태스크 이름·테스트 수를 desktop 로그에서 grep으로 찾는다. High·Important 이상은 총괄이 코드에서 직접 다시 확인한다. - 리뷰 결과를 받으면 `python3 scripts/check-review-index.py docs/reviews/<폴더>`로 색인이 빠짐없는지 본다. 수정 묶음은 색인에서 배정한다. - 교훈을 보낼 곳: 그 playbook의 「자주 하는 실수」, 코드 결함 모양은 [reference/defect-patterns.md](reference/defect-patterns.md), 거짓 통과는 [reference/gates.md](reference/gates.md) 6절, 근거는 [evidence.md](evidence.md). @@ -82,6 +85,7 @@ design-docs `conventions/delegation-loop.md` 3절 순서대로 한다: 크기 - Agent 도구(세션 안의 하위 에이전트)는 이 repo의 `.claude/settings.json`이 막는다. 스킬이 하위 에이전트를 띄우라고 하면 그 단계는 그 세션이 직접 하거나, 이 playbook대로 별도 세션에 맡긴다. 막혔다고 Agent로 우회하지 않는다. - 실행 위치(desktop, 공유 잠금, desktop worktree)는 [operate.md](operate.md) 4.1절이다. +- 하위 세션은 공유 노트 폴더의 다른 노트를 먼저 읽는다. 독립 리뷰어 둘은 노트 파일 이름을 서로 다르게 정해 주고, brief에 상대 노트를 읽지 말라고 쓴다. ## 5. 완료 기준 diff --git a/docs/work/evidence.md b/docs/work/evidence.md index 05b9697b..5ee1b645 100644 --- a/docs/work/evidence.md +++ b/docs/work/evidence.md @@ -214,5 +214,5 @@ | T5-2 | 기록 2 | 소유자 지시로 생긴 큰 변경도 따로 멈춰야 하나 | 고침 — design-docs `conventions/work-thinking-order.md` 2.3절, 스킬 `research-first` | | T5-V | 기록 「위반」 1 | 총괄 보고를 영어로 씀 | 고침 — `docs/work/README.md` 6절, design-docs `conventions/delegation-loop.md` 5·11절. 훅으로는 막지 않는다(보고 문장은 도구 호출이 아니라 훅이 볼 수 없다) | -- 기준선과 새 매뉴얼의 리뷰 발견은 8건 중 1건만 겹쳤다. 리뷰 방식을 바꿀지는 매뉴얼 규칙으로 넣지 않고 소유자에게 물을 제안으로 남겼다(매뉴얼 수정 세션 보고). +- 기준선과 새 매뉴얼의 리뷰 발견은 8건 중 1건만 겹쳤다. 이를 근거로 확인 리뷰를 독립 리뷰어 둘로 할지 소유자에게 물었고, 2026-11-07 소유자가 세 경우에만 둘로 하는 안을 골랐다(소유자 원문 "(c)로 받기"). 넣은 곳: `improve.md` 4.1절 「독립 리뷰어 둘」·4.5절 1, `delegate.md` 4.1·4.3절, `reference/review-criteria.md` 10절 「ID」, `reference/decisions.md` 2.1, design-docs `conventions/delegation-loop.md` 3절 5·9절 M11, `delegation-loop/metrics.md`. - 「자주 하는 실수」에 넣은 줄: `improve.md`(strict lane 탐침), `operate.md`(`--rerun` 범위를 기존 줄에 더함, push 뒤 검증), `docs-writing.md`(`--history` 0을 믿음), `delegate.md`(두 리뷰의 ID). diff --git a/docs/work/improve.md b/docs/work/improve.md index 1c099d3b..65c2d680 100644 --- a/docs/work/improve.md +++ b/docs/work/improve.md @@ -46,6 +46,13 @@ 8. `python3 scripts/check-review-index.py docs/reviews/<폴더>`를 돌린다. 색인 절이 따로 있으면 `--index-heading "<절 제목>"`을 붙인다. rc=0이어야 한다. 지난 라운드 색인에서 빠진 ID 때문에 처음부터 rc=1이면, 빠진 ID를 이번 색인 절에 「색인 보완」 한 줄로 이름만 적는다. 지난 영역 문서는 고치지 않는다. 9. 판단하지 않은 항목은 「Declined to judge」에 위치와 이유를 적는다. 맡긴 쪽이 다음 묶음에 배정하거나 결정으로 닫는다. 지난 라운드에서 열린 채 넘어온 Declined는 brief가 맡겼을 때만 다시 판정한다. 맡기지 않았으면 건수와 위치만 적는다. +**독립 리뷰어 둘.** 아래 셋 중 하나면 같은 범위를 서로 결과를 보지 않는 리뷰어 둘이 따로 리뷰하고 맡긴 쪽이 합친다([delegate.md](delegate.md) 4.1절). + +- 멈추는 확인 리뷰: 리뷰어 하나가 0을 냈으면 멈추기 전에 두 번째 리뷰어가 같은 범위를 본다(4.5절 1). +- 수정 diff가 추가 1,000줄 이상인 확인 리뷰(상한 1,500줄에 가까움. 세는 법은 4.4절). +- Critical·Important(전체 리뷰는 High)를 고친 수정의 확인 리뷰. +- 리뷰어는 자기 문서를 끝내기 전에 다른 리뷰어의 브랜치·문서·보고·노트를 읽지 않는다. 리뷰 폴더에 문서를 커밋하는 것은 brief가 정한 정본 리뷰어뿐이다. 다른 리뷰어는 같은 양식을 보고에 두고, ID 자리에 임시 번호 `B-NN-MM`을 쓴다. + ### 4.2 결함 수정 1. 원인 경로를 확인한다. 증상이 아니라 원인을 적는다. @@ -77,7 +84,7 @@ 리뷰 → 수정 → 확인 리뷰는 아래 넷이 모두 참일 때만 멈춘다. -1. 마지막 확인 리뷰의 발견이 심각도와 상관없이 0이다. Minor도 기록만 하지 않고 고친다. +1. 마지막 확인 리뷰의 발견이 심각도와 상관없이 0이다. 서로 보지 않은 리뷰어 둘이 모두 0이어야 한다(4.1절 「독립 리뷰어 둘」). Minor도 기록만 하지 않고 고친다. 2. 열린 「Declined to judge」가 0이다. 다른 브랜치가 처리했지만 아직 합치지 않은 항목은 합친 트리에서 확인할 때까지 열린 것으로 센다. 3. 합친 트리에서 라운드 끝 게이트가 모두 통과했다. 4. 리뷰 README의 남은 항목이 0이다. 결정으로 닫은 항목은 결정 위치를 적었다. diff --git a/docs/work/reference/decisions.md b/docs/work/reference/decisions.md index d28c6a33..cba22c15 100644 --- a/docs/work/reference/decisions.md +++ b/docs/work/reference/decisions.md @@ -52,6 +52,7 @@ | `@DisplayName` 언어 | 한국어(기본값 영어를 거부) | 소유자 | 2026-09-25 | 결정 5, `AGENTS.md` 테스트 작성 규칙 2 | | 학습 문서 | 삭제된 코드를 설명하는 학습 문서(`docs/study/*.ko.md`, `docs/*-superpowers-package/`)는 현재 코드에 맞게 갱신 | 소유자 | 2026-09-25 | 결정 6 | | client 오류 문구 | 한국어. `Category`별 문구 표 하나를 shared-contract에 | 소유자 | 2026-09-25 | 결정 11 | +| 확인 리뷰 독립 리뷰어 둘 | 세 경우에 서로 결과를 보지 않는 리뷰어 둘이 같은 범위를 리뷰하고 총괄이 합친다: 반복을 멈추기 직전 확인 리뷰(리뷰어 하나가 0을 내면 두 번째가 본다), 수정 diff가 상한에 가까운 리뷰("가까움"은 추가 1,000줄 이상 — 기본값), Critical·Important를 고친 수정의 리뷰. 그 밖은 하나. 2~3라운드 두 리뷰의 겹침 비율을 기록하고 그 결과로 언제나 하나·언제나 둘로 옮길지 다시 본다 | 소유자 | 2026-11-07 | 2026-11-07 총괄 세션 전달(소유자 원문 "(c)로 받기"), `docs/work/improve.md` 4.1·4.5절, `docs/work/delegate.md` 4.1절 | ### 2.2 구조·조립 diff --git a/docs/work/reference/review-criteria.md b/docs/work/reference/review-criteria.md index e20a7d52..5d861c5a 100644 --- a/docs/work/reference/review-criteria.md +++ b/docs/work/reference/review-criteria.md @@ -265,7 +265,7 @@ leaf를 더하거나 옮기거나 지울 때 같은 변경에서 함께 바꾼 - 라운드 밖(다른 문서, 커밋, 주석)에서는 리뷰 폴더 날짜의 월일을 붙인다: `MMDD/`(가이드 36.3절). - 영역 번호 자리에 `NN` 같은 자리표시자를 남기지 않는다. 리뷰가 끝난 뒤 영역 접두어를 바꾸지 않는다. - 영역 번호는 그 라운드 영역 표의 순번이다. 지난 라운드 번호와 맞추지 않아도 된다. 지난 라운드 영역 하나를 둘로 나누면 뒤에 새 번호를 잇고(04를 나누면 04·05), 「범위」 절에 지난 영역과의 대응을 적는다. -- 한 라운드의 ID는 리뷰 하나가 매긴다. 같은 범위를 두 리뷰가 따로 봤으면 brief가 정한 쪽이 정본이다. 다른 쪽 발견은 정본의 다음 번호로 새 ID를 받고, 두 ID의 대응표를 README의 그 라운드 색인 절에 둔다. 다른 쪽 문서를 그대로 합치지 않는다(같은 ID가 다른 결함을 가리킨다). +- 한 라운드의 ID는 리뷰 하나가 매긴다. 같은 범위를 두 리뷰가 따로 봤으면(독립 리뷰어 둘, [improve.md](../improve.md) 4.1절) brief가 정한 쪽이 정본이다. 다른 쪽은 임시 번호 `B-NN-MM`을 쓰고, 그 발견은 합칠 때 정본의 다음 번호로 새 ID를 받는다. 두 ID의 대응표를 README의 그 라운드 색인 절에 둔다. 다른 쪽 문서를 그대로 합치지 않는다(같은 ID가 다른 결함을 가리킨다). - ID는 리뷰 문서·brief·커밋에서 쓴다. 매뉴얼(`docs/work/`) 본문에는 쓰지 않는다. ## 11. 판단을 적는 법 From 447a77a35da8bf92bb21a5f14e3d16c71f0cdfd0 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Sat, 7 Nov 2026 00:35:12 +0900 Subject: [PATCH 24/71] =?UTF-8?q?docs(work):=20=EC=9A=B4=EC=98=81=20playbo?= =?UTF-8?q?ok=20=EC=8B=9C=ED=97=98=EC=97=90=EC=84=9C=20=EB=82=98=EC=98=A8?= =?UTF-8?q?=20=EA=B2=8C=EC=9D=B4=ED=8A=B8=20=EC=8B=A4=ED=96=89=20=EB=B9=88?= =?UTF-8?q?=ED=8B=88=20=EC=97=AC=EC=84=AF=EC=9D=84=20=EB=8B=AB=EB=8A=94?= =?UTF-8?q?=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 2026-11-07 합친 브랜치 전체 게이트를 매뉴얼만 보고 돌리게 했더니 (1회차 수정 전 매뉴얼) 여섯 곳에서 답이 없었다. - gates.md 3절 묶음에 main job(configuration-cache, compose smoke, http3, notification pr)과 경로 필터 PR lane이 없어 "workflow와 같은 명령"이 아니었다 - 합친 트리가 어떤 경로 필터 lane을 켜는지 정하는 절차가 없었다 - 집계 태스크 전체가 실제로 돌았음을 보이는 법이 없었다(--rerun은 앞 태스크 하나만) - lychee 대체 명령(--links docs)이 lychee 범위보다 좁았고, buf와 dependency review는 대체 안내가 없었다 - compose bind mount가 tmp/heap-dumps를 root로 만들어 git worktree remove가 실패했다 - 결과 기록 형식이 게이트 하나 = Gradle 명령 하나를 가정했다 고른 방법: - gates.md 3절을 (가) 늘 도는 것, (나) 바뀐 파일로 켜지는 것, (다) 로컬 도구가 없는 것으로 나눈다. (가)에 workflow의 run 줄을 더하고, (나)는 git diff --name-only를 on.pull_request.paths(glob)와 pr-adapters.yml emit 줄(정규식)에 맞추는 절차로, (다)는 job마다 로컬 대체와 대체가 못 보는 것을 적은 표로 둔다 - 실제 실행 증명: 새 worktree와 --no-build-cache, 로그의 FROM-CACHE 0 - 링크 검사 대체는 lychee와 같은 glob을 git ls-files로 넘긴다 - operate.md 4.1에 compose down과 root 폴더 지우기 한 줄 - gates.md 4절은 한 줄 = 명령 하나, 여러 명령 job은 순번, 「실제 실행」 칸 - 처리 표(evidence.md 9절)에 T6 여섯 행 버린 대안: workflow의 모든 job 명령을 gates.md에 옮겨 적기. workflow가 정본이라 옮긴 사본이 낡는다. 경로 필터 lane은 절차만 둔다. 위험·한계: - (가)의 명령은 workflow의 사본이다. workflow를 바꾸면 이 블록도 고쳐야 한다 - 경로 필터 맞추기는 손으로 한다. glob을 기계로 맞추는 도구는 없다 - 같은 범위 링크 검사는 지금 rc=1이다. src/README.md와 fileserver· objectstorage README의 상대 링크 3건이 기준 커밋부터 깨져 있다(이번 범위 밖) 검증: - python3 scripts/check-work-docs.py rc=0. improve.md 141/150, delegate.md 121/150, operate.md 131/150, 진입 경로 최대 290/350, 본문 이력 0줄 - 바꾼 문서를 읽는 테스트: grep 결과 0(delivery-evidence.md 이름만 걸림) - desktop: 바꾼 것을 패치로 73d39212 위에 얹어 이 커밋과 같은 트리 7e28874c를 만들고, flock 아래 :app-bootstrap:documentContractTest --rerun --no-build-cache rc=0, 66건 실패 0 건너뜀 0, FROM-CACHE 0, 직전 1분 부하 5.64. 같은 트리에서 check-work-docs.py rc=0, --history docs/manual 16줄 rc=1(기대대로) (desktop ~/manual-gap-fix-2-logs/final-*.log) - 링크 검사(lychee와 같은 범위) rc=1, 깨진 3건은 위 위험·한계의 것 (desktop ~/manual-gap-fix-2-logs/links-lychee-scope.log) --- docs/work/evidence.md | 12 +++++-- docs/work/operate.md | 5 +-- docs/work/reference/gates.md | 69 ++++++++++++++++++++++++++++-------- 3 files changed, 67 insertions(+), 19 deletions(-) diff --git a/docs/work/evidence.md b/docs/work/evidence.md index 5ee1b645..fd7c4353 100644 --- a/docs/work/evidence.md +++ b/docs/work/evidence.md @@ -167,11 +167,11 @@ - `RR-01-11`·`RR-02-10`·`RR-03-11`은 2차 재리뷰(`round2/`) 문서의 발견이다. 그 문서들은 1차 번호에 이어 `RR-` 접두어를 그대로 썼다(머리말 「표기」). -## 9. cold-read 시험 1회차 빈틈 처리 (2026-11-06) +## 9. cold-read 시험 1회차 빈틈 처리 (2026-11-06~07) -2026-11-06 이력 없는 세션 6개에 이 매뉴얼만 주고 실제 일을 시켰다(기준선 1개는 옛 매뉴얼). 6개 모두 일은 끝냈지만 매뉴얼에서 답을 못 찾은 곳이 1~9건씩 나와 모두 불합격이었다. 아래는 시험 기록(design-docs `delegation-loop/trials/2026-11-06-*.md`)의 「질문」·「위반」 표와 각 세션 공유 노트(`~/.config/Claude/side-session-notes/local_fcd89c34-c754-4c5b-a38f-fa322834286f/`)의 「매뉴얼에서 답을 못 찾은 곳」을 한 줄씩 처리한 결과다. 기준 커밋 `2c8a359d`. +2026-11-06 이력 없는 세션 6개에 이 매뉴얼만 주고 실제 일을 시켰다(기준선 1개는 옛 매뉴얼). 6개 모두 일은 끝냈지만 매뉴얼에서 답을 못 찾은 곳이 1~9건씩 나와 모두 불합격이었다. 아래는 시험 기록(design-docs `delegation-loop/trials/2026-11-06-*.md`)의 「질문」·「위반」 표와 각 세션 공유 노트(`~/.config/Claude/side-session-notes/local_fcd89c34-c754-4c5b-a38f-fa322834286f/`)의 「매뉴얼에서 답을 못 찾은 곳」을 한 줄씩 처리한 결과다. 기준 커밋 `2c8a359d`. 2026-11-07 운영 playbook 시험(T6, `trials/2026-11-07-integration-gates.md`, 1회차 수정 전 매뉴얼로 돌림)의 빈틈 6건을 T6 행으로 더했다. -- 세션: T1 `c-t1-r10-review`(확인 리뷰), B `c-t1-baseline`(같은 리뷰를 옛 매뉴얼로, 기준선), T2 `c-t2-circuit-breaker`(결함 수정), T3 `c-t3-error-codes`(조사·설계 → 구현), T4 `c-t4-manual-ids`(문서), T5 `c-t5-idempotency-opid`(결함 수정). +- 세션: T1 `c-t1-r10-review`(확인 리뷰), B `c-t1-baseline`(같은 리뷰를 옛 매뉴얼로, 기준선), T2 `c-t2-circuit-breaker`(결함 수정), T3 `c-t3-error-codes`(조사·설계 → 구현), T4 `c-t4-manual-ids`(문서), T5 `c-t5-idempotency-opid`(결함 수정), T6 `c-t6-integration-gates`(합친 브랜치 전체 게이트). - 출처 칸: `기록 N`은 시험 기록 「질문」 표의 N번, `노트 N`은 공유 노트의 N번이다. T3 노트는 1단계 `1-N`, 2단계 `2-N`이다. - 처리 칸: 고침(고친 곳) / 고치지 않음(이유) / 소유자 결정 필요. 기준선(B)은 새 매뉴얼에도 해당하는 것만 고쳤다. @@ -213,6 +213,12 @@ | T5-1 | 기록 1 | 설계서 둘과 포트 Javadoc이 서로 다를 때 무엇을 따르나 | 고침 — `improve.md` 7절: 결정이 없으면 고르지 않고 양쪽 근거로 묻는다 | | T5-2 | 기록 2 | 소유자 지시로 생긴 큰 변경도 따로 멈춰야 하나 | 고침 — design-docs `conventions/work-thinking-order.md` 2.3절, 스킬 `research-first` | | T5-V | 기록 「위반」 1 | 총괄 보고를 영어로 씀 | 고침 — `docs/work/README.md` 6절, design-docs `conventions/delegation-loop.md` 5·11절. 훅으로는 막지 않는다(보고 문장은 도구 호출이 아니라 훅이 볼 수 없다) | +| T6-1 | 기록 1, 노트 1 | `reference/gates.md` 3절 묶음에 경로 필터 PR lane과 main job(configuration-cache, compose smoke, http3, notification)이 없어 "workflow와 같은 명령"이 성립하지 않음 | 고침 — `reference/gates.md` 3절 (가) 늘 도는 것(main job·optional 빌드·태그 단계 명령 더함) | +| T6-2 | 기록 2, 노트 2 | 합친 트리가 어떤 경로 필터 lane을 켜는지 정하는 절차, "바뀐 영역의 lane"의 정의 | 고침 — `reference/gates.md` 3절 (나): `git diff --name-only`를 `on.pull_request.paths`(glob)와 `pr-adapters.yml` `emit` 줄(정규식)에 맞춘다 | +| T6-3 | 기록 3, 노트 3 | 집계 태스크 전체가 실제로 돌았음을 보이는 법(`--rerun`은 앞 태스크 하나만) | 고침 — `reference/gates.md` 3절 「실제로 돌았음을 보이기」(새 worktree, `--no-build-cache`, FROM-CACHE 0)·6절, `operate.md` 9절 | +| T6-4 | 기록 4, 노트 4 | lychee 대체 명령이 lychee 범위보다 좁음, buf·dependency review 대체 안내 없음 | 고침 — `reference/gates.md` 2절 링크 검사(lychee와 같은 glob을 `git ls-files`로), 3절 (다) 로컬 도구가 없는 job 표 | +| T6-5 | 기록 5, 노트 5 | compose bind mount가 `tmp/heap-dumps`를 root 소유로 만들어 `git worktree remove`가 실패 | 고침 — `operate.md` 4.1절(compose `down` 뒤 컨테이너로 폴더를 지운다) | +| T6-6 | 기록 6, 노트 6 | `reference/gates.md` 4절 기록 형식이 "게이트 하나 = Gradle 명령 하나"를 가정 | 고침 — `reference/gates.md` 4절(한 줄 = 명령 하나, 여러 명령 job은 순번, 「실제 실행」 칸) | - 기준선과 새 매뉴얼의 리뷰 발견은 8건 중 1건만 겹쳤다. 이를 근거로 확인 리뷰를 독립 리뷰어 둘로 할지 소유자에게 물었고, 2026-11-07 소유자가 세 경우에만 둘로 하는 안을 골랐다(소유자 원문 "(c)로 받기"). 넣은 곳: `improve.md` 4.1절 「독립 리뷰어 둘」·4.5절 1, `delegate.md` 4.1·4.3절, `reference/review-criteria.md` 10절 「ID」, `reference/decisions.md` 2.1, design-docs `conventions/delegation-loop.md` 3절 5·9절 M11, `delegation-loop/metrics.md`. - 「자주 하는 실수」에 넣은 줄: `improve.md`(strict lane 탐침), `operate.md`(`--rerun` 범위를 기존 줄에 더함, push 뒤 검증), `docs-writing.md`(`--history` 0을 믿음), `delegate.md`(두 리뷰의 ID). diff --git a/docs/work/operate.md b/docs/work/operate.md index 9aaca51c..75040f6a 100644 --- a/docs/work/operate.md +++ b/docs/work/operate.md @@ -58,6 +58,7 @@ git worktree remove ~/workspace/<작업 이름> - 로그는 desktop `~/<작업 이름>-logs/`에 남기고, 보고에 그 desktop 경로와 rc를 쓴다. - RED 확인용 임시 worktree도 같은 방법으로 만들고 끝나면 지운다. +- compose를 띄웠으면 지우기 전에 `docker compose … down`을 한다. bind mount 폴더(`docker-compose.dev.yml`의 `tmp/heap-dumps`)는 Docker가 root로 만들어 `git worktree remove`가 Permission denied로 실패한다. compose가 이미 받은 이미지(`docker-compose.infra.yml`의 `redis:7.4`)로 폴더를 지운 뒤 다시 지운다: `docker run --rm --pull=never -v "$PWD/tmp:/t" redis:7.4 rm -rf /t/heap-dumps`. - Python 검사 스크립트는 노트북에서 돌려도 된다. 보고 증거로 쓸 때는 desktop worktree에서 한 번 더 돌린다. **push 전에 검증하기.** push한 커밋은 고쳐 쓰지 않는다. 그래서 커밋 본문에 desktop 결과를 쓰거나 push가 허용되지 않았으면, 커밋 전에 바꾼 것을 패치로 보내 같은 트리에서 돌린다. @@ -76,7 +77,7 @@ git diff --cached --binary <기준 커밋> | ssh desktop 'cd ~/workspace/<작업 ### 4.2 게이트 실행과 기록 -1. [reference/gates.md](reference/gates.md) 2절로 돌릴 게이트를 고른다. 라운드 끝이면 3절 묶음 전체다. +1. [reference/gates.md](reference/gates.md) 2절로 돌릴 게이트를 고른다. 라운드 끝이면 3절의 (가) 늘 도는 것, (나) 바뀐 파일로 켜지는 것, (다) 로컬 도구가 없는 것 전체다. 2. 잠금을 얻은 뒤 1분 부하를 적고 돌린다. 한 번에 하나씩이다. 3. 첫 실행이 실패하면 원인을 찾아 고치고 다시 돌린다. 첫 실행과 다시 돌린 결과를 둘 다 적는다. 4. 결과를 [reference/gates.md](reference/gates.md) 4절 형식으로 적는다: 게이트, rc, 시간, 직전 부하, 로그 경로, 대상 커밋. @@ -126,5 +127,5 @@ git diff --cached --binary <기준 커밋> | ssh desktop 'cd ~/workspace/<작업 - desktop 기존 checkout에서 브랜치를 바꿔 다른 세션의 작업을 방해한다. 자기 worktree를 만든다. - 짧게 끝난 실행을 통과로 적는다. 캐시 재사용인지, 태스크가 실제로 돌았는지 로그로 확인한다. -- 빌드 캐시에서 가져온 테스트 결과를 지금 이 환경에서 통과한 증거로 쓴다. 기준 상태를 확인하거나 시간·환경에 민감한 테스트를 볼 때는 그 태스크를 `--rerun`으로 다시 돌린다. `--rerun`은 바로 앞 태스크 하나에만 걸린다. 태스크마다 붙인다(`:a:test --rerun :b:test --rerun`). +- 빌드 캐시에서 가져온 테스트 결과를 지금 이 환경에서 통과한 증거로 쓴다. 기준 상태를 확인하거나 시간·환경에 민감한 테스트를 볼 때는 그 태스크를 `--rerun`으로 다시 돌린다. `--rerun`은 바로 앞 태스크 하나에만 걸린다. 태스크마다 붙인다(`:a:test --rerun :b:test --rerun`). `ci` 같은 집계 태스크는 새 worktree에서 `--no-build-cache`로 돌린다([reference/gates.md](reference/gates.md) 3절). - 커밋하고 push한 뒤 desktop에서 돌려, 결과를 커밋 본문에 못 넣는다. push 전에 패치로 검증한다(4.1절). diff --git a/docs/work/reference/gates.md b/docs/work/reference/gates.md index 8719fd7e..8272269d 100644 --- a/docs/work/reference/gates.md +++ b/docs/work/reference/gates.md @@ -58,34 +58,75 @@ 어떤 테스트가 그 문서를 읽는지는 `grep -rn -e '<파일 이름>' -e '<폴더 경로>' src --include=*.java`로 찾는다. 걸리는 테스트가 없으면(주석만 걸려도 없음이다) document-contract lane은 돌리지 않고 grep 명령과 결과를 보고에 적는다. 리뷰 기록(`docs/reviews/**`)도 같다. -**링크 검사**: workflow `link-check.yml`(lychee)이 PR에서 `README.md`, `src/README.md`, `src/**/README.md`, `src/**/CLAUDE.md`, `docs/**/*.md`, `.github/**/*.md`를 검사한다. 루트 `CLAUDE.md`는 그 범위 밖이라 `scripts/check-work-docs.py`가 본다. lychee가 없는 곳에서는 `python3 scripts/check-work-docs.py --links docs`로 상대 링크만 확인한다. 저장소 밖 경로와 `file:line`은 링크로 쓰지 않는다(lychee가 따라가지 못한다). +**링크 검사**: workflow `link-check.yml`(lychee)이 PR에서 `README.md`, `src/README.md`, `src/**/README.md`, `src/**/CLAUDE.md`, `docs/**/*.md`, `.github/**/*.md`를 검사한다. 루트 `CLAUDE.md`는 그 범위 밖이라 `scripts/check-work-docs.py`가 본다. lychee가 없는 곳에서는 저장소 루트에서 같은 범위의 상대 링크만 확인한다(외부 URL은 보지 못한다): + +```bash +python3 scripts/check-work-docs.py --links $(git ls-files ':(glob)README.md' ':(glob)src/**/README.md' ':(glob)src/**/CLAUDE.md' ':(glob)docs/**/*.md' ':(glob).github/**/*.md') +``` + +`--links docs`만 돌리면 `src/**/README.md`·`src/**/CLAUDE.md`·`.github/**/*.md`를 빠뜨린다. 저장소 밖 경로와 `file:line`은 링크로 쓰지 않는다(lychee가 따라가지 못한다). ## 3. 라운드 끝 — 합친 트리의 전체 묶음 -여러 묶음을 합친 트리는 workflow와 같은 명령으로 검증한다. 한 번에 하나씩, 공유 잠금 아래에서 돌린다. +여러 묶음을 합친 트리는 workflow가 PR과 main push에서 돌리는 것을 모두 돌린다. 정본은 `.github/workflows/`다. (가)는 늘 도는 것, (나)는 바뀐 파일로 켜지는 것, (다)는 로컬에 도구가 없는 것이다. 한 번에 하나씩, 공유 잠금 아래에서 돌린다. + +**실제로 돌았음을 보이기.** 새 detached worktree에서 시작하고 모든 Gradle 명령에 `--no-build-cache`를 붙인다. 로그마다 `grep -c 'FROM-CACHE' <로그>`가 0이어야 한다. UP-TO-DATE는 같은 worktree에서 앞 명령이 만든 출력일 때만 받아들인다. `--rerun`은 바로 앞 태스크 하나에만 걸려 `ci` 같은 집계 태스크의 증거가 되지 않는다. + +(가) 늘 도는 것: ```bash cd src -./gradlew :ci :verifyDependencyLocks --warning-mode=fail --console=plain -./gradlew :sample-portfolio:check :sample-portfolio:qualityCheck --console=plain +# PR: ci-quality-gates.yml +./gradlew :ci :verifyDependencyLocks --warning-mode=fail --no-build-cache --console=plain ./gradlew :verifyStrictLaneStages --dry-run --console=plain +./gradlew :sample-portfolio:check :sample-portfolio:qualityCheck --no-build-cache --console=plain +./gradlew -p optional-platforms ci --no-build-cache --console=plain ./gradlew -p optional-platforms :verifyStrictLaneStages --dry-run --console=plain -./gradlew :mainCheck --continue --warning-mode=fail --console=plain -./gradlew :integrationCheck --continue --console=plain -./gradlew -p optional-platforms ci integrationCheck performanceCheck --console=plain -./gradlew :performanceCheck --continue --console=plain -./gradlew :releaseCheck -PgitRevision="$(git rev-parse HEAD)" --console=plain -cd .. && bash scripts/verify-compose-profile-contracts.sh +# main push: integration-main.yml +./gradlew :mainCheck --continue --warning-mode=fail --no-build-cache --console=plain +./gradlew :integrationCheck --continue --no-build-cache --console=plain +./gradlew :performanceCheck --continue --no-build-cache --console=plain +./gradlew -p optional-platforms performanceCheck --continue --no-build-cache --console=plain +./gradlew -p optional-platforms integrationCheck --no-build-cache --console=plain +./gradlew :adapter:outbound:httpclient:test -Phttp3.tests.enabled=true --no-build-cache --console=plain # 실험 job, 실패해도 workflow는 통과 +# 태그: release.yml (CI는 GITHUB_SHA로 커밋을 받는다. 손으로 돌릴 때는 -PgitRevision) +./gradlew :releaseCheck -PgitRevision="$(git rev-parse HEAD)" --no-build-cache --console=plain +./gradlew -p optional-platforms releaseCheck -PgitRevision="$(git rev-parse HEAD)" --no-build-cache --console=plain +cd .. +bash scripts/verify-compose-profile-contracts.sh +bash scripts/run-compose-runtime-smoke.sh --matrix src/config/runtime/compose-profile-contracts.json ``` +- 여러 명령으로 된 main job 둘은 그 job의 `run` 줄을 차례로 그대로 돌린다: `integration-main.yml`의 `configuration-cache`(로그에 "Reusing configuration cache."가 있어야 한다), `notification-platform.yml`의 `pr`(main push마다 경로와 상관없이 돈다). - 첫 실행이 실패하면 고치고 다시 돌린다. 둘 다 기록한다. - 합친 뒤에만 드러나는 결함이 있다. 묶음별 검증으로 이 단계를 대신하지 않는다. +(나) 바뀐 파일로 켜지는 것 — brief의 "바뀐 영역의 lane"은 이것이다: + +1. 바뀐 파일 목록을 만든다: `git diff --name-only <기준 커밋> <합친 커밋>`. +2. 그 목록을 두 종류의 패턴과 맞춘다. + - `on.pull_request.paths`가 있는 workflow(`grep -l 'paths:' .github/workflows/*.yml`). 패턴은 glob이다(`**`는 폴더 여러 단계). + - `pr-adapters.yml`의 `changes` job에 있는 `emit` 줄. lane(web·websocket·httpclient·jpa)마다 정규식이고, `grep -E`로 맞춘다. +3. 걸린 workflow·job의 `run` 줄을 그대로 돌린다. matrix가 있으면 값마다 한 번이다(예: jpa는 PostgreSQL 버전마다, httpclient는 transport마다). compose가 필요한 job은 그 job의 `docker compose … up`·`down` 단계도 같이 한다. +4. 걸리지 않은 workflow는 이름과 "경로 안 걸림"을, nightly·수동 전용 job은 "PR·main 단계 아님"을 결과 표에 적는다. + +(다) 로컬에 도구가 없는 것: + +| job | 로컬에서 | 대체가 못 보는 것 | +| --- | --- | --- | +| `link-check.yml`(lychee) | 2절 끝의 같은 범위 상대 링크 검사 | 외부 URL | +| `ci-quality-gates.yml` `grpc-proto-buf`(`buf lint`·`buf breaking`) | buf가 있으면 job의 `run` 줄 그대로. 없으면 못 돌림으로 적는다. diff에 `.proto`·`buf*.yaml`이 없으면 "해당 없음 — proto 변경 없음" | 전부 | +| `dependency-vulnerability.yml` `dependency-review`·`dependency-submission` | GitHub에서만 돈다. diff에 lockfile·`src/gradle/libs.versions.toml` 변경이 없으면 "해당 없음", 있으면 PR 결과를 보고 남은 문제로 적는다 | 전부 | +| `dependency-vulnerability.yml` `trivy-fs` | trivy가 있으면 job의 `run` 줄 그대로, 없으면 못 돌림 | — | + ## 4. 결과 기록 -| 게이트 | 결과 | 시간 | 실행 직전 1분 부하 | 로그 | -| --- | --- | --- | --- | --- | -| `:ci :verifyDependencyLocks --warning-mode=fail` | rc=0 | 5분 42초 | 2.65 | desktop `~/<작업 이름>-logs/ci.log` | +| 단계 | 게이트(명령) | 결과 | 시간 | 실행 직전 1분 부하 | 실제 실행 | 로그 | +| --- | --- | --- | --- | --- | --- | --- | +| PR | `:ci :verifyDependencyLocks --warning-mode=fail --no-build-cache` | rc=0 | 6분 32초 | 0.39 | 태스크 756 executed, FROM-CACHE 0, 테스트 7298 실패 0 | desktop `~/<작업 이름>-logs/ci.log` | + +- 한 줄은 명령 하나다. 여러 명령으로 된 job(`configuration-cache`, notification `pr`)은 명령마다 한 줄을 쓰고 「게이트」 칸에 ` 1/7`처럼 순번을 붙인다. Gradle의 태스크 집계 줄은 명령마다 하나씩 나오므로 로그도 명령마다 나눈다. +- 「실제 실행」 칸은 로그의 `> Task` 줄에서 센다: executed(꼬리 없음), UP-TO-DATE, FROM-CACHE. 테스트 수는 그 명령이 새로 쓴 JUnit XML에서 센다. 함께 적는다: @@ -126,7 +167,7 @@ cd .. && bash scripts/verify-compose-profile-contracts.sh | 게이트 밖에서 실패한 채 방치된 검사 | `testQualityCheck`(`mainCheck`) | | 실서버 계약이 어느 게이트에도 없음 | lane을 단계에 연결 | | 시간 단언을 끈 채 performance lane 실행 | convention이 단언을 켜고, 끄는 값이나 skip이 있으면 테스트 전에 실패(5절) | -| 캐시에서 가져온 결과를 지금 통과한 것으로 셈 | 기준 상태 확인과 시간·환경에 민감한 테스트는 그 태스크를 `--rerun`으로 다시 돌린다. `--rerun`은 바로 앞 태스크 하나에만 걸리므로 태스크마다 붙인다 | +| 캐시에서 가져온 결과를 지금 통과한 것으로 셈 | 기준 상태 확인과 시간·환경에 민감한 테스트는 그 태스크를 `--rerun`으로 다시 돌린다. `--rerun`은 바로 앞 태스크 하나에만 걸리므로 태스크마다 붙인다. 집계 태스크는 새 worktree와 `--no-build-cache`로 돌리고 FROM-CACHE 0을 보인다(3절) | | 외부 이미지가 사라져 다른 lane 결과까지 가림 | 테스트 이미지를 `src/config/testing/container-images.properties` 한 곳에 digest로 고정, main 단계는 `--continue` | 게이트 장치 자체를 바꿨으면 일부러 망가뜨린 입력으로 실패하는 것을 본다. 판독기를 바꿨으면 바꾸기 전후로 실제 workflow의 판정이 같은지 비교한다. From 144351063815ef7c412398cf7e9cd20948004012 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Sat, 7 Nov 2026 01:01:41 +0900 Subject: [PATCH 25/71] =?UTF-8?q?fix(idempotency)!:=20=EC=9D=B4=EB=AF=B8?= =?UTF-8?q?=20=EC=A0=81=EC=9A=A9=EB=90=9C=20=EC=A0=84=EC=9D=B4=EB=8A=94=20?= =?UTF-8?q?=EA=B7=B8=20=EC=A0=84=EC=9D=B4=EB=A5=BC=20=EC=A0=81=EC=9A=A9?= =?UTF-8?q?=ED=95=9C=20=ED=95=B8=EB=93=A4=EC=97=90=EA=B2=8C=EB=A7=8C=20?= =?UTF-8?q?=ED=99=95=EC=9D=B8=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 이미 적용된 전이를 다시 보낸 호출에 Redis·PostgreSQL 저장소와 in-memory fake가 다르게 답한다. - 같은 attempt가 넘겨받기 전 핸들로, 넘겨받은 뒤 적용된 complete를 다시 보내면 Redis·PostgreSQL은 ALREADY_COMPLETED_SAME_RESULT, fake는 NOT_OWNER. - 같은 경우의 markFailed는 Redis ALREADY_MARKED_SAME_OPERATION, PostgreSQL OPERATION_CONFLICT, fake NOT_OWNER. markFailed를 적용한 핸들이 응답을 잃고 다시 보내면 fake만 NOT_OWNER. - release한 핸들로 start하면 PostgreSQL은 NOT_OWNER, Redis·fake는 ABSENT. - 같은 원인(재생 판정이 "어느 핸들이 적용했나"를 보지 않음)이 다른 전이에도 있다. PostgreSQL은 기록된 renew·release와 digest가 다른 핸들을 모두 OPERATION_CONFLICT로 답해, 주인이 renew가 돌려준 핸들로 다시 renew해도 거절하고 넘겨받기 전 핸들의 renew·release도 OPERATION_CONFLICT다. fake는 적용한 핸들이 start·renew를 다시 보내도 NOT_OWNER다. 방법: 소유자 결정(2026-11-06) 「넘겨받기 전 핸들의 재전송」「해제된 핸들로 start」대로 맞춘다. "적용한 핸들"은 owner identity가 같고 기록보다 revision이 하나 낮은 핸들이다. 라운드6에서 start에 쓴 기준을 모든 전이에 쓴다. - Redis TRANSITION과 command fake: ALREADY 조건에서 "start가 아니면 아무 핸들" 분기를 지우고 rev == handle rev + 1만 남긴다. 다른 핸들은 revision 검사로 내려가 NOT_OWNER·WRONG_STATE. - PostgreSQL: replayVerdict가 적용한 핸들일 때만 재생(같은 digest → 이미 처리됨, 다른 digest → OPERATION_CONFLICT)으로 읽는다. 다른 핸들은 owner 검사로 내려가 NOT_OWNER. complete 재생 판정도 owner token 대신 적용한 핸들을 본다. - fake: 마지막으로 적용한 전이와 그 핸들·인자(renew lease, fail disposition) 를 기억해 start·renew·complete·markFailed 재전송에 저장소와 같게 답한다. - release한 핸들의 start는 계약이 ABSENT·NOT_OWNER를 둘 다 받고 포트 Javadoc(IdempotencyStartOutcome)에 적는다. 코드 동작은 그대로. 버린 대안: PostgreSQL complete·fail 재생을 전이 digest 비교만으로 하기(complete digest에 replay TTL이 들어가 같은 결과·다른 TTL 재전송이 RESPONSE_CONFLICT가 된다), Redis를 원래 주석 의도대로 두고 fake·PostgreSQL을 "operation의 아무 핸들"로 넓히기(소유자 결정과 반대, 넘겨받기 전 핸들이 남의 결과를 자기 것으로 확인받는다), 재생 핸들을 attempt만으로 가리기(같은 attempt가 넘겨받으면 attempt가 올라가지만 renew 뒤의 낡은 핸들은 attempt가 같다). 공유 계약 IdempotencyStoreContract에 10케이스를 더했다. 포트 결과 enum Javadoc 넷, application-core CLAUDE.md·README, persistence-jpa·cache-redis README, TESTING_STRATEGY, 결정 색인, 업그레이드 안내 5절을 같이 고쳤다. 위험·한계: 템플릿의 호출자(IdempotencyExecutor)는 넘겨받기 전 핸들로 다시 보내지 않고 renew·release를 부르지 않아 HTTP 동작은 같다. store 포트를 직접 부르는 코드는 넘겨받기 전 핸들의 재전송에 NOT_OWNER를 받고, PostgreSQL에서 renew를 이어 부를 수 있게 된다. fake로 응답 유실을 흉내 내던 테스트는 이제 "이미 처리됨"을 받는다. 적용한 핸들이 markFailed를 다른 retention·disposition 으로 다시 보낼 때의 답은 저장소마다 다르고 IdempotencyFailOutcome Javadoc과도 다르다(범위 밖, 보고에 적음). 검증: desktop, 공유 잠금, 기준 73d39212. - RED(기준 커밋 + 계약 테스트만, 로그 ~/r8-f4-red-logs/): in-memory fake 계약 59 중 4 실패(적용한 핸들의 start·renew·markFailed 재전송, "expected: ALREADY_MARKED_SAME_OPERATION but was: NOT_OWNER" 등), Redis command fake 2·실 Redis(redisContainerContractTest) 2 실패("expected: NOT_OWNER but was: ALREADY_COMPLETED_SAME_RESULT"·"…ALREADY_MARKED_SAME_ OPERATION"), 실 PostgreSQL(jpaPlatformContractTest) 5 실패(complete는 ALREADY_COMPLETED_SAME_RESULT, markFailed·renew·release는 OPERATION_CONFLICT, 두 번째 renew는 "expected: RENEWED but was: OPERATION_CONFLICT"). release한 핸들의 start 케이스는 동작 변경이 없어 처음부터 셋 다 통과한다. lane마다 실패 수는 위 계약 실패 수와 같다. - GREEN(이 커밋과 같은 트리 377d1232, 로그 ~/r8-f4-green-logs/): 네 leaf check(application-core 422·skip 19 fake 시간 케이스, persistence-jpa 664, cache-redis 225, redis-runtime 65), 네 leaf testQualityCheck, redisContainerContractTest 100, jpaPlatformContractTest 429, postgresqlIdempotencyIntegrationTest 10, fake를 쓰는 leaf(composition: idempotency check 32, redis-sdk test 310, web test 329, sample-portfolio test 339), documentContractTest 66 — 모두 rc=0, 실패 0. - scripts/check-work-docs.py, git diff --check 통과. BREAKING CHANGE: IdempotencyStorePort 구현은 이미 적용된 전이의 재전송을 그 전이를 적용한 핸들(기록보다 revision이 하나 낮은 핸들)에게만 "이미 처리됨" 으로 확인하고 다른 핸들은 NOT_OWNER로 답해야 한다. 직접 구현한 store는 IdempotencyStoreContract의 새 케이스로 확인한다. --- docs/testing/TESTING_STRATEGY.md | 8 +- docs/upgrade/2026-11-maturity-review.md | 1 + docs/work/reference/decisions.md | 6 +- src/adapter/outbound/cache-redis/README.md | 11 +- .../redis/idempotency/IdempotencyScripts.java | 24 +- .../outbound/persistence-jpa/README.md | 13 +- .../PostgreSqlIdempotencyStore.java | 40 +++- .../InMemorySemanticRedisCommands.java | 9 +- src/application-core/CLAUDE.md | 4 + src/application-core/README.md | 6 +- .../IdempotencyCompleteOutcome.java | 7 + .../idempotency/IdempotencyFailOutcome.java | 7 + .../idempotency/IdempotencyRenewOutcome.java | 10 +- .../idempotency/IdempotencyStartOutcome.java | 10 +- .../testkit/IdempotencyStoreContract.java | 215 ++++++++++++++++++ .../testkit/InMemoryIdempotencyStore.java | 98 +++++--- 16 files changed, 399 insertions(+), 70 deletions(-) diff --git a/docs/testing/TESTING_STRATEGY.md b/docs/testing/TESTING_STRATEGY.md index f95dfa50..c224d85f 100644 --- a/docs/testing/TESTING_STRATEGY.md +++ b/docs/testing/TESTING_STRATEGY.md @@ -260,7 +260,13 @@ source set에서 태그 `jpa-contract`로 `jpaPlatformContractTest` lane이 돌 claim을 `TakenOverClaimed`(attempt 2)로, Redis는 `Acquired`로 답한다. executor는 둘을 같게 처리하므로 계약은 "다음 claim이 scope를 가진다"만 요구한다. 같은 이유로 release 재시도는 PostgreSQL이 `ALREADY_RELEASED_SAME_OPERATION`, Redis·fake가 `ABSENT`다. 기록이 없으면 셋 다 `ABSENT`다(Redis는 전에 - `ALREADY_RELEASED_SAME_OPERATION`으로 답해 확인할 수 없는 해제를 확인했다, 2026-11-06). + `ALREADY_RELEASED_SAME_OPERATION`으로 답해 확인할 수 없는 해제를 확인했다, 2026-11-06). 같은 까닭으로 + release한 핸들로 시작하면 PostgreSQL은 `NOT_OWNER`, Redis·fake는 `ABSENT`이고 계약은 둘 다 받는다. (4) 이미 + 적용된 전이를 "이미 처리됨"으로 확인받는 핸들이 셋 다 달랐다. Redis는 complete·markFailed를 그 operation의 + 어느 핸들에게나, PostgreSQL은 complete를 같은 owner token의 어느 핸들에게나 확인했고 다른 핸들의 + markFailed·renew·release는 `OPERATION_CONFLICT`로 답했다 — 주인이 renew가 돌려준 핸들로 다시 renew해도 + 그랬다. fake는 complete 말고는 적용한 핸들의 재전송도 `NOT_OWNER`였다. 셋 다 적용한 핸들(기록보다 + revision이 하나 낮은 핸들)에게만 확인하고 다른 핸들은 `NOT_OWNER`로 맞췄다(2026-11-06 소유자 결정). - `OutboxAppendContract`는 static helper 두 개였고 JPA readiness 테스트만 불렀다. 추상 계약으로 바꿔 readiness 테스트가 상속한다(같은 두 케이스 + 트랜잭션 밖·읽기 전용·중복 eventId). 실 PostgreSQL에서 `inRead` 안의 append가 예외 없이 사라지는 것을 찾았다(실측: 예외 없음, 행 없음) — JPA 트랜잭션 diff --git a/docs/upgrade/2026-11-maturity-review.md b/docs/upgrade/2026-11-maturity-review.md index 7a0f1509..11c4178b 100644 --- a/docs/upgrade/2026-11-maturity-review.md +++ b/docs/upgrade/2026-11-maturity-review.md @@ -241,6 +241,7 @@ V21 실패의 분류는 `docs/runbooks/migration-failed.md` "Classify the failur | 멱등성(lease가 끝난 시작, r9) | lease가 지난 `CLAIMED`는 주인도 시작할 수 없다(`LEASE_EXPIRED`). executor는 작업을 돌리지 않고 503 `IDEMPOTENCY_UNAVAILABLE`(실행 전 거부, 메시지 `the claim's processing lease ran out before the action started`)로 답하고, 다음 같은 키 요청이 그 claim을 넘겨받아 실행한다. 전에는 Redis가 시작해 작업을 돌렸고 그동안 다른 요청은 lease가 지난 실행으로 500을 받았다. PostgreSQL은 `NOT_OWNER`로 거절해 500 `IDEMPOTENCY_RECOVERY_REQUIRED`였다. | claim과 시작 사이가 lease(기본 30s)보다 길었던 드문 요청이 500 대신 503(같은 키 재전송)을 받는다. 클라이언트는 `error.code`로 이미 가르므로 바꿀 것이 없다. 운영자는 이 503에서 저장소 장애를 찾지 않는다(runbook) | r9(재리뷰 README 15 남음, RR5-01-02·03) · `IdempotencyExecutor.java`, `src/adapter/outbound/cache-redis/.../idempotency/IdempotencyScripts.java`, `src/adapter/outbound/persistence-jpa/.../postgresql/PostgreSqlIdempotencyStore.java` | | 멱등성(같은 attempt의 재시도, r10) | lease가 지나 시작을 거절당한 claim과 재시도 가능 실패 기록은 같은 attempt로 다시 claim해도 넘겨받는다(`TakenOverClaimed`, attempt+1). 전에는 두 저장소가 그 claim을 재생해(`ReplayedAcquire`) 시작이 다시 거절되거나(503, 기록이 사라질 때까지) 시작할 수 없는 기록이라 500 `IDEMPOTENCY_RECOVERY_REQUIRED`였다. 효과 불명으로 포기한 기록은 같은 attempt에도 `RecoveryRequired`(PostgreSQL은 전에 `ReplayedAcquire`). Redis는 이미 실행 중인 기록에 같은 attempt의 다른 핸들(넘겨받기 전 핸들, 재생받은 현재 핸들)로 온 시작을 `ALREADY_STARTED_SAME_OPERATION`으로 확인하지 않는다 — 전에는 executor가 작업을 한 번 더 돌렸다(PostgreSQL은 전부터 거절). in-memory fake는 재시도 가능 실패 기록에 다른 요청 본문이 오면 넘겨주지 않고 `FingerprintMismatch` | attempt를 재시도 사이에 들고 있다가 503 뒤 같은 attempt로 다시 부르는 호출자(재시도 래퍼, 메시지 소비자)가 이제 실행된다. 요청마다 새 attempt를 만드는 호출자(템플릿의 HTTP 경로)는 바뀌는 것이 없다. 같은 attempt를 두 호출이 동시에 쓰는 것은 여전히 가려내지 못한다 — 재시도는 앞 호출이 돌아온 뒤에. 직접 구현한 store는 `IdempotencyStoreContract`의 새 케이스로 확인한다 | r10(라운드6 RR6-02-01) · `src/adapter/outbound/cache-redis/.../idempotency/IdempotencyScripts.java`, `src/adapter/outbound/persistence-jpa/.../postgresql/PostgreSqlIdempotencyStore.java`, `src/application-core/src/testFixtures/.../IdempotencyStoreContract.java`, `InMemoryIdempotencyStore.java` | | 멱등성(전이의 operation id·release·inspect, 2026-11-06) | owner token이 같아도 호출이 claim과 다른 operation id를 대면 PostgreSQL·in-memory fake도 다섯 전이(start·renew·complete·fail·release)를 `OPERATION_CONFLICT`로 거절하고 기록을 바꾸지 않는다(전에는 적용했다. Redis는 전부터 거절). in-memory fake의 claim은 같은 token·다른 operation에 `OwnerOperationConflict`(전에는 `InProgress`), inspect는 `OPERATION_CONFLICT`(전에는 `IN_PROGRESS_OTHER`). PostgreSQL·fake의 inspect는 완료된 기록에도 `OPERATION_CONFLICT`(전에는 응답을 재생). PostgreSQL complete는 같은 operation id를 쓴 다른 attempt에 `NOT_OWNER`(전에는 `ALREADY_COMPLETED_SAME_RESULT`). Redis release는 기록이 없으면 `ABSENT`(전에는 `ALREADY_RELEASED_SAME_OPERATION`)이고 핸들 revision을 본다: 같은 attempt가 넘겨받기 전 핸들로 release하면 `NOT_OWNER`(전에는 지금의 claim을 지웠다) | 템플릿의 호출자(`IdempotencyExecutor`)는 늘 claim의 operation id를 넘기고 release를 부르지 않아 HTTP 동작은 같다. store 포트를 직접 부르며 전이마다 다른 operation id를 넘기던 코드는 이제 `OPERATION_CONFLICT`를 받는다 — `IdempotencyOwner.claimOperationId()`를 넘긴다. Redis release의 `ALREADY_RELEASED_SAME_OPERATION`을 기다리던 코드는 `ABSENT`도 "해제됨"으로 읽는다. 직접 구현한 store는 `IdempotencyStoreContract`의 새 케이스로 확인한다 | 2026-11-06(소유자 결정 "(a)로 진행", 라운드6 02 Declined) · `src/adapter/outbound/persistence-jpa/.../postgresql/PostgreSqlIdempotencyStore.java`, `src/adapter/outbound/cache-redis/.../idempotency/IdempotencyScripts.java`, `RedisIdempotencyStoreAdapter.java`, `src/application-core/src/testFixtures/.../IdempotencyStoreContract.java`, `InMemoryIdempotencyStore.java` | +| 멱등성(이미 적용된 전이의 재전송, 2026-11-06) | 이미 적용된 전이를 "이미 처리됨"으로 확인받는 것은 그 전이를 적용한 핸들(기록보다 revision이 하나 낮은 핸들)뿐이다. 같은 attempt가 넘겨받기 전 핸들로, 넘겨받은 뒤 적용된 complete·markFailed를 다시 보내면 `NOT_OWNER`(전에는 Redis가 `ALREADY_COMPLETED_SAME_RESULT`·`ALREADY_MARKED_SAME_OPERATION`, PostgreSQL이 `ALREADY_COMPLETED_SAME_RESULT`·`OPERATION_CONFLICT`). PostgreSQL은 renew가 돌려준 핸들로 다시 renew하면 한 번 더 renew한다(전에는 `OPERATION_CONFLICT`). 넘겨받기 전 핸들의 renew는 `NOT_OWNER`, release는 `NOT_OWNER`(전에는 둘 다 `OPERATION_CONFLICT`). in-memory fake는 적용한 핸들이 start·renew·markFailed를 다시 보내면 `ALREADY_STARTED_SAME_OPERATION`·`ALREADY_RENEWED_SAME_OPERATION`(다른 lease면 `OPERATION_CONFLICT`)·`ALREADY_MARKED_SAME_OPERATION`(전에는 `NOT_OWNER`). release한 핸들로 start하면 PostgreSQL은 `NOT_OWNER`, Redis·fake는 `ABSENT`이고 계약은 둘 다 받는다(동작 변경 없음, Javadoc만) | 템플릿의 호출자(`IdempotencyExecutor`)는 넘겨받기 전 핸들로 다시 보내지 않고 renew·release를 부르지 않아 HTTP 동작은 같다. store 포트를 직접 부르며 heartbeat로 renew를 이어 부르는 코드는 PostgreSQL에서 두 번째 renew부터 거절당하던 것이 이제 된다. 직접 구현한 store는 `IdempotencyStoreContract`의 새 케이스로 확인한다. fake로 lost reply를 흉내 내던 테스트는 이제 "이미 처리됨"을 받는다 | 2026-11-06(소유자 결정 「넘겨받기 전 핸들의 재전송」「해제된 핸들로 start」) · `src/adapter/outbound/cache-redis/.../idempotency/IdempotencyScripts.java`, `src/adapter/outbound/persistence-jpa/.../postgresql/PostgreSqlIdempotencyStore.java`, `src/application-core/src/testFixtures/.../IdempotencyStoreContract.java`, `InMemoryIdempotencyStore.java`, `IdempotencyStartOutcome.java` | | 빌드 단계(HTTP client) | `httpClientFailureInjectionTest`(Toxiproxy 장애 주입)가 `mainCheck`에서 빠졌다. `integrationCheck`에만 있고, main push·nightly의 `integration-main.yml` `integration-check` job이 돌린다 | main push마다 같은 lane이 `main-check`·`integration-check` 두 job에서 두 번 돌던 것이 한 번이 된다. 로컬에서 `mainCheck`만 돌리면 이 lane은 돌지 않는다(`integrationCheck`로 돌린다) | r9 · `src/adapter/outbound/httpclient/build.gradle` | | 서버 로그(GraphQL·gRPC·STOMP) | carrier로 답한 실패를 web과 같은 줄(shared-contract `ServerFailureLog`)로 ERROR에 남긴다: persistence 실패는 분류만, 5xx carrier는 예외와 함께, 4xx carrier는 남기지 않는다. gRPC는 ` (method=…)`, GraphQL은 ` (executionId=…)`를 붙인다. gRPC는 인식 못 한 실패(`INTERNAL_ERROR`)도 `unhandled failure on …`로 남긴다. 클라이언트가 취소한 호출은 남기지 않고, 서비스가 `CANCELLED` status로 끝낸 살아 있는 호출은 남긴다. raw status는 넘겼든 던졌든 설명을 남기지 않는다(원인 예외가 있으면 그것만 붙인다). `IllegalArgumentException`(`BAD_PARAMETER`)은 web과 같은 WARN 한 줄 `request refused as BAD_PARAMETER by <예외 타입>`(메시지 없음)으로 남긴다. STOMP `@MessageMapping` 실패는 Spring의 `Unhandled exception from message handler method`(예외 전체) 대신 같은 줄로 남는다 | ERROR 로그가 늘어난다(전에는 gRPC가 아무것도 남기지 않았다). GraphQL·gRPC·STOMP는 잘못된 입력마다 WARN 한 줄이 생긴다. STOMP에서 Spring 문구로 경보를 걸었다면 고친다. `IDEMPOTENCY_RECOVERY_REQUIRED`의 scope digest를 모든 전송에서 찾을 수 있다(`docs/runbooks/idempotency-unavailable.md`) | r9 · `src/shared-contract/.../error/ServerFailureLog.java`, `GrpcExceptionHandlingInterceptor.java`, `GraphQlWireErrorMapper.java`, `StompHandlerFailureLog.java` | | sample-portfolio | 익명 쓰기 401, 포스터 제목 대소문자 무시 유일(409 `POSTER_ALREADY_EXISTS`), 관리자도 남의 work log 수정 불가, 샘플 이벤트 tenant `global` | sample을 남긴 서비스만 | `34565130`, `1400dc15` | diff --git a/docs/work/reference/decisions.md b/docs/work/reference/decisions.md index d28c6a33..0a76dea5 100644 --- a/docs/work/reference/decisions.md +++ b/docs/work/reference/decisions.md @@ -100,11 +100,11 @@ | 다른 핸들의 시작 답 | PostgreSQL도 Redis와 같게 `NOT_OWNER`/`NOT_CLAIMED`로 답한다 | 기본값 | `1103` 17절 r10-02 | | 전이의 operation id | owner token이 같아도 호출의 operation id가 기록된 claim의 operation id와 다르면 다섯 전이(start·renew·complete·fail·release) 모두 `OPERATION_CONFLICT`로 거절하고 기록은 그대로 둔다. PostgreSQL·in-memory fake를 Redis에 맞췄다. 그래서 `OPERATION_CONFLICT`는 "claim과 다른 id"와 "같은 id·다른 인자" 두 뜻이다 | 소유자(2026-11-06) | 2026-11-06 총괄 세션 전달(소유자 원문 "(a)로 진행"), `IdempotencyStoreContract` | | 같은 token·다른 operation의 claim·inspect | claim은 진행 중인 기록에 `OwnerOperationConflict`, inspect는 상태와 상관없이(완료된 기록도) `OPERATION_CONFLICT`. 거절이 안전한 쪽을 골랐다 | 기본값(2026-11-06) | 위 결정과 같은 전달의 판단 원칙, `IdempotencyStoreContract` | -| complete 재생 판정 | 완료 확인은 같은 owner token에만 준다. 같은 operation id를 쓴 다른 attempt의 늦은 complete는 `NOT_OWNER` | 기본값(2026-11-06) | Redis TRANSITION에 맞춤, `IdempotencyStoreContract` | +| complete 재생 판정 | 완료 확인은 같은 owner token에만 준다. 같은 operation id를 쓴 다른 attempt의 늦은 complete는 `NOT_OWNER`. → 아래 「넘겨받기 전 핸들의 재전송」이 적용한 핸들 하나로 좁혔다 | 기본값(2026-11-06) | Redis TRANSITION에 맞춤, `IdempotencyStoreContract` | | 기록 없는 release | 저장소 셋 다 `ABSENT`로 답한다(확인할 수 없는 해제를 확인하지 않는다). Redis release도 핸들 revision을 본다. release한 기록을 지울지 남길지는 저장소가 정하므로 release 재시도 답은 `ABSENT`(Redis·fake)와 `ALREADY_RELEASED_SAME_OPERATION`(PostgreSQL)으로 갈린다 | 기본값(2026-11-06) | JPA 설계 22.2 "affected row가 0이면 성공으로 간주하지 않는다", `IdempotencyStoreContract` | | Redis 연결 예산 | 캐시 조건부 쓰기는 멱등성·lease와 다른 연결 예산(SCRIPT lane) | 위임 | `1103` 4절(RR-04-02) | -| 넘겨받기 전 핸들의 재전송 | 같은 attempt를 넘겨받기 전의 핸들이 이미 일어난 complete·markFailed를 다시 보내면, 그 전이를 실제로 적용한 핸들에게만 "이미 처리됨"으로 확인하고 그 밖의 핸들은 거절한다. Redis TRANSITION 주석의 원래 의도를 뒤집는다 | 소유자 | t5 보고 「남은 문제」, 2026-11-06 | -| 해제된 핸들로 start | 계약은 `ABSENT`와 `NOT_OWNER`를 둘 다 받는다. 포트 Javadoc에 그렇게 적는다 | 소유자 | t5 보고 「남은 문제」, 2026-11-06 | +| 넘겨받기 전 핸들의 재전송 | 같은 attempt를 넘겨받기 전의 핸들이 이미 일어난 complete·markFailed를 다시 보내면, 그 전이를 실제로 적용한 핸들에게만 "이미 처리됨"으로 확인하고 그 밖의 핸들은 거절한다. Redis TRANSITION 주석의 원래 의도를 뒤집는다. 적용: 적용한 핸들은 기록보다 revision이 하나 낮은 핸들이고, 거절은 `NOT_OWNER`다. 같은 규칙을 start·renew·release에도 맞췄다 | 소유자 | t5 보고 「남은 문제」, 2026-11-06, `IdempotencyStoreContract` | +| 해제된 핸들로 start | 계약은 `ABSENT`와 `NOT_OWNER`를 둘 다 받는다. 포트 Javadoc에 그렇게 적는다 | 소유자 | t5 보고 「남은 문제」, 2026-11-06, `IdempotencyStartOutcome`, `IdempotencyStoreContract` | ### 2.5 영속성 diff --git a/src/adapter/outbound/cache-redis/README.md b/src/adapter/outbound/cache-redis/README.md index 2e8f9902..c7fd0f6c 100644 --- a/src/adapter/outbound/cache-redis/README.md +++ b/src/adapter/outbound/cache-redis/README.md @@ -277,11 +277,12 @@ revision) come from app-bootstrap `IdempotencySettings`. This leaf reads only `k `renew` has its own program rather than the generic transition. Renewal keeps the record in `EXECUTING`, and the transition answers "already in the target state" before it reads the revision (that answer exists for a retry whose first reply was lost), so a renewal sent through it was always -`ALREADY_RENEWED_SAME_OPERATION` and never moved the lease. For a start that answer is given only to -the handle the start was applied from — the record one revision past it — because the executor runs -the action on it: another handle of the same attempt (one from before a takeover, or the current one -a replayed claim returned) used to be told the start was applied and ran the action a second time; -it is now `NOT_OWNER` or `NOT_CLAIMED`, as in the PostgreSQL store (round6 RR6-02-01). The renew program checks owner, +`ALREADY_RENEWED_SAME_OPERATION` and never moved the lease. That answer is given only to the handle +the transition was applied from — the record one revision past it. Another handle of the same +attempt (one from before a takeover, or the current one a replayed claim returned) used to be told a +start was applied and ran the action a second time (round6 RR6-02-01), and to be told a completion +or failure that followed a takeover was its own (owner decision 2026-11-06); it is now `NOT_OWNER` +or `NOT_CLAIMED`/`NOT_IN_PROGRESS`, as in the PostgreSQL store. The renew program checks owner, operation, revision and state, then extends `leaseUntil` from Redis `TIME` and bumps the revision. A lost renewal reply is recognised by what the renewal recorded — the revision it started from and the lease it asked for: the same lease is `ALREADY_RENEWED_SAME_OPERATION` with the current handle, diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/IdempotencyScripts.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/IdempotencyScripts.java index 2df2090d..6a942373 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/IdempotencyScripts.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/IdempotencyScripts.java @@ -123,6 +123,11 @@ public final class IdempotencyScripts { * execution that had just begun; the PostgreSQL store refused it (re-review 2026-11-04 README 15, * {@code IdempotencyStoreContract}). Completion and failure read no lease: the holder's late * result is recorded (owner decision 2026-11-04). + * + *

A transition already applied is answered {@code ALREADY} only to the handle it was applied + * from. A completion or failure used to be reported back to any handle of its operation, so the + * same attempt's handle from before a takeover was told the completion that followed it was its + * own (owner decision 2026-11-06). */ private static final String TRANSITION = """ @@ -147,17 +152,16 @@ public final class IdempotencyScripts { -- — they never received the reply that would have replaced it — so that check first would -- turn every lost reply into NOT_OWNER and make the idempotent call non-idempotent. -- - -- A start is the one transition whose ALREADY runs the action, so for a start the owner and - -- operation are not proof enough: the same attempt also holds a handle from before a - -- takeover, and the current handle a replayed claim returned after the start. Either one + -- The owner and operation are not proof enough: the same attempt also holds a handle from + -- before a takeover, and the current handle a replayed claim returned. Either one -- presenting a start the record already shows was answered ALREADY, and the executor ran the - -- action a second time (round6 RR6-02-01). A start is confirmed only to the handle it was - -- applied from — the record one revision past it — and any other falls through to the - -- revision check: NOT_OWNER for a stale handle, WRONG_STATE for the current one. The - -- PostgreSQL store answers the same: its start replay digest covers the handle's attempt - -- and revision. A completion or failure already applied is still reported back to any - -- handle of its operation: nothing runs on that answer. - if ARGV[4] ~= 'CLAIMED' or rev == tonumber(ARGV[2]) + 1 then + -- action a second time (round6 RR6-02-01); either one presenting a completion or failure + -- applied after the takeover was told it was its own. A transition is confirmed only to + -- the handle it was applied from — the record one revision past it — and any other falls + -- through to the revision check: NOT_OWNER for a stale handle, WRONG_STATE for the current + -- one (owner decision 2026-11-06). The PostgreSQL store answers the same: it reads a + -- recorded transition as a replay only for the handle one revision behind the row. + if rev == tonumber(ARGV[2]) + 1 then return {'ALREADY', attempt, rev, owner, redis.call('HGET', KEYS[1], 'resp') or '', ''} end end diff --git a/src/adapter/outbound/persistence-jpa/README.md b/src/adapter/outbound/persistence-jpa/README.md index a13880a2..c33c0b29 100644 --- a/src/adapter/outbound/persistence-jpa/README.md +++ b/src/adapter/outbound/persistence-jpa/README.md @@ -442,10 +442,15 @@ Redis store·in-memory fake와 같은 계약(`IdempotencyStoreContract`)을 실 전이(start·renew·complete·fail·release) 모두 거절하고 행을 바꾸지 않는다. 같은 token·다른 operation의 inspect도 상태와 상관없이(완료된 행도) `OPERATION_CONFLICT`다(2026-11-06 소유자 결정 — 전에는 CAS가 핸들의 claim operation만 보고 호출의 id는 `last_transition_operation_id`에 적기만 해서 적용했다). 다른 하나는 같은 operation -id가 다른 인자로 이미 적용된 경우다. complete 재생은 같은 owner token에만 확인한다 — 같은 operation id를 쓴 다른 -attempt의 늦은 complete는 `NOT_OWNER`다(전에는 operation id만 보고 `ALREADY_COMPLETED_SAME_RESULT`). 시작은 핸들 말고 인자가 없어서, -이미 기록된 시작과 digest가 다르면 다른 핸들이다 — 넘겨받기 전 핸들은 `NOT_OWNER`, 재생받은 현재 핸들은 -`NOT_CLAIMED`(라운드6 RR6-02-01, 전에는 `OPERATION_CONFLICT`). renew는 `EXECUTING`의 +id가 다른 인자로 이미 적용된 경우다. 이미 기록된 전이는 그 전이를 적용한 핸들(owner identity가 같고 행보다 +revision이 하나 낮은 핸들)에게만 재생으로 읽는다(2026-11-06 소유자 결정). 그 핸들이면 digest가 같을 때 "이미 +처리됨", 다를 때 `OPERATION_CONFLICT`다. 다른 핸들은 재생이 아니라 owner 검사로 간다. 그래서 같은 operation id를 +쓴 다른 attempt의 늦은 complete와, 같은 attempt가 넘겨받기 전 핸들로 다시 보낸 complete·markFailed·renew·release는 +`NOT_OWNER`다(전에는 complete를 owner token만 보고 `ALREADY_COMPLETED_SAME_RESULT`로 확인했고, 나머지는 digest가 +달라 `OPERATION_CONFLICT`였다). renew가 돌려준 핸들로 다시 renew하면 한 번 더 renew된다(전에는 앞 renew의 digest와 +달라 `OPERATION_CONFLICT`였다). 시작은 핸들 말고 인자가 없어서, 넘겨받기 전 핸들은 `NOT_OWNER`, 재생받은 현재 +핸들은 `NOT_CLAIMED`다(라운드6 RR6-02-01, 전에는 `OPERATION_CONFLICT`). release한 핸들로 시작하면 행이 남아 있어 +`NOT_OWNER`다. 행을 지우는 Redis·fake는 `ABSENT`이고 계약은 둘 다 받는다. renew는 `EXECUTING`의 lease만 늘리고, 시작 전 `CLAIMED`는 `NOT_IN_PROGRESS`다. ### outbox V2 (삭제됨) diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/PostgreSqlIdempotencyStore.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/PostgreSqlIdempotencyStore.java index 0b83e9c5..dec82c02 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/PostgreSqlIdempotencyStore.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/PostgreSqlIdempotencyStore.java @@ -193,7 +193,8 @@ public final class PostgreSqlIdempotencyStore implements IdempotencyStorePort { // handle, which the classification below names as the Redis store does (NOT_OWNER, // NOT_CLAIMED); it used to be OPERATION_CONFLICT (round6 RR6-02-01). It never reaches the // update: a recorded start leaves the row EXECUTING until a later transition replaces it. - if (replayVerdict(row, "START", operationId, startDigest) == ReplayVerdict.SAME_ARGUMENTS) { + if (replayVerdict(row, owner, "START", operationId, startDigest) + == ReplayVerdict.SAME_ARGUMENTS) { return startResult(IdempotencyStartOutcome.ALREADY_STARTED_SAME_OPERATION, owner(row)); } IdempotencyStartOutcome mismatch = classifyStartMismatch(row, owner); @@ -231,7 +232,7 @@ public final class PostgreSqlIdempotencyStore implements IdempotencyStorePort { // caller went on believing it held the record for longer than the row says it does. String renewDigest = transitionDigest("RENEW", operationId, owner, Long.toString(processingLeaseTtl.toMillis())); - switch (replayVerdict(row, "RENEW", operationId, renewDigest)) { + switch (replayVerdict(row, owner, "RENEW", operationId, renewDigest)) { case SAME_ARGUMENTS -> { return renewResult(IdempotencyRenewOutcome.ALREADY_RENEWED_SAME_OPERATION, owner(row)); } @@ -277,13 +278,14 @@ public final class PostgreSqlIdempotencyStore implements IdempotencyStorePort { return IdempotencyCompleteOutcome.OPERATION_CONFLICT; } String responseDigest = sha256(response.payload()); - // A completion is reported back to its own owner only. The operation id alone confirmed the - // late completion of another attempt that carried the same id, which the Redis store refuses - // as NOT_OWNER (IdempotencyStoreContract). + // A completion is reported back only to the handle it was applied from. The operation id alone + // confirmed the late completion of another attempt that carried the same id, and the owner + // token alone confirmed it to the same attempt's handle from before a takeover; the Redis + // store refuses both as NOT_OWNER (IdempotencyStoreContract, owner decision 2026-11-06). if (row.state() == IdempotencyState.COMPLETED && "COMPLETE".equals(row.lastTransitionKind()) - && row.ownerToken().equals(owner.ownerToken()) - && operationId.value().equals(row.lastTransitionOperationId())) { + && operationId.value().equals(row.lastTransitionOperationId()) + && appliedFrom(row, owner)) { return responseDigest.equals(row.responseDigest()) ? IdempotencyCompleteOutcome.ALREADY_COMPLETED_SAME_RESULT : IdempotencyCompleteOutcome.RESPONSE_CONFLICT; @@ -342,7 +344,7 @@ public final class PostgreSqlIdempotencyStore implements IdempotencyStorePort { owner, disposition.name(), Long.toString(retention.toMillis())); - switch (replayVerdict(row, transitionKind, operationId, failDigest)) { + switch (replayVerdict(row, owner, transitionKind, operationId, failDigest)) { case SAME_ARGUMENTS -> { return IdempotencyFailOutcome.ALREADY_MARKED_SAME_OPERATION; } @@ -392,7 +394,7 @@ public final class PostgreSqlIdempotencyStore implements IdempotencyStorePort { return IdempotencyReleaseOutcome.OPERATION_CONFLICT; } String releaseDigest = transitionDigest("RELEASE", operationId, owner); - switch (replayVerdict(row, "RELEASE", operationId, releaseDigest)) { + switch (replayVerdict(row, owner, "RELEASE", operationId, releaseDigest)) { case SAME_ARGUMENTS -> { return IdempotencyReleaseOutcome.ALREADY_RELEASED_SAME_OPERATION; } @@ -591,6 +593,15 @@ public final class PostgreSqlIdempotencyStore implements IdempotencyStorePort { return sameOwnerIdentity(row, owner) && row.stateRevision() == owner.stateRevision(); } + /** + * Whether the row's last transition was applied from this handle: the same owner identity, one + * revision behind the row, as every transition advances the revision by one. Only that handle may + * be told a recorded transition was its own (owner decision 2026-11-06). + */ + private static boolean appliedFrom(IdempotencyRecordRow row, IdempotencyOwner owner) { + return sameOwnerIdentity(row, owner) && row.stateRevision() == owner.stateRevision() + 1; + } + /** * Whether the recorded transition is this call again, and whether it carried these arguments. * @@ -605,14 +616,23 @@ public final class PostgreSqlIdempotencyStore implements IdempotencyStorePort { * the owner handle it presented the first time, so the revision, the owner and every semantic * argument reproduce the stored digest exactly; anything else is a different transition wearing * the same operation id, and belongs in a conflict rather than in a confirmation. + * + *

That holds only for the handle the transition was applied from. Any other handle recomputes + * a different digest from its own attempt and revision, and was answered {@code + * OPERATION_CONFLICT}: the holder's second renewal through the handle its first one returned, and + * the same attempt's handle from before a takeover resending a failure or a release that followed + * it. Neither is a replay — the first is a new transition, the second a stale owner — so both go + * on to the ownership checks, as in the Redis store (owner decision 2026-11-06). */ private static ReplayVerdict replayVerdict( IdempotencyRecordRow row, + IdempotencyOwner owner, String transitionKind, OperationId operationId, String expectedDigest) { if (!transitionKind.equals(row.lastTransitionKind()) - || !operationId.value().equals(row.lastTransitionOperationId())) { + || !operationId.value().equals(row.lastTransitionOperationId()) + || !appliedFrom(row, owner)) { return ReplayVerdict.NOT_A_REPLAY; } return expectedDigest.equals(row.lastTransitionResultDigest()) diff --git a/src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/command/InMemorySemanticRedisCommands.java b/src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/command/InMemorySemanticRedisCommands.java index f25a5a11..bd13f4c3 100644 --- a/src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/command/InMemorySemanticRedisCommands.java +++ b/src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/command/InMemorySemanticRedisCommands.java @@ -280,10 +280,11 @@ public final class InMemorySemanticRedisCommands implements SemanticRedisCommand return reply("OPERATION_CONFLICT", attempt, rev, owner, "", ""); } // ALREADY before the revision check, matching the program: a lost reply leaves the caller - // holding the pre-transition revision. A start is confirmed only to the handle it was applied - // from — the record one revision past it — because its ALREADY runs the action (round6 - // RR6-02-01); any other handle falls through to NOT_OWNER or WRONG_STATE. - if (state.equals(toState) && (!"CLAIMED".equals(fromState) || rev == expectedRev + 1)) { + // holding the pre-transition revision. A transition is confirmed only to the handle it was + // applied from — the record one revision past it (round6 RR6-02-01 for a start, owner decision + // 2026-11-06 for a completion or failure); any other handle falls through to NOT_OWNER or + // WRONG_STATE. + if (state.equals(toState) && rev == expectedRev + 1) { String stored = field(rendered, "resp"); return reply("ALREADY", attempt, rev, owner, stored == null ? "" : stored, ""); } diff --git a/src/application-core/CLAUDE.md b/src/application-core/CLAUDE.md index e69b39d1..368c81c1 100644 --- a/src/application-core/CLAUDE.md +++ b/src/application-core/CLAUDE.md @@ -291,6 +291,10 @@ generation; the V1 `IdempotencyScope`/`tryBegin` API is gone. - Every transition names the operation its record was claimed under (`IdempotencyOwner.claimOperationId()`). Another one is `OPERATION_CONFLICT` in every store and changes nothing; so is an inspection that brings the owner token under another operation (owner decision 2026-11-06). +- A transition already applied is confirmed ("already …") only to the handle it was applied from — + the record one revision past it. Any other handle is `NOT_OWNER`, the same attempt's handle from + before a takeover included; a start through a released handle is `ABSENT` or `NOT_OWNER` by + whether the store keeps the released record (owner decision 2026-11-06, `IdempotencyStoreContract`). The former ArchUnit freeze rule `inbound_port_implementations_do_not_declare_keyed_idempotency` and its fixture were removed when this branch merged. diff --git a/src/application-core/README.md b/src/application-core/README.md index 541e8917..14c805f2 100644 --- a/src/application-core/README.md +++ b/src/application-core/README.md @@ -270,8 +270,10 @@ application 계층이 claim·replay·복구 **정책** 을 소유하고, 저장 - processing lease 와 replay TTL 은 따로 간다. 넘겨받을 수 있는 것은 만료된 `CLAIMED` 와 재시도 가능한 실패뿐이고, 다음 claim 이 누구든 넘겨받는다 — 같은 attempt 를 다시 보낸 caller 도 새 attempt 번호로 넘겨받는다(라운드6 RR6-02-01: 전에는 같은 attempt 가 이 기록을 재생받아 시작을 다시 거절당했다). 넘겨받기 전 - 핸들은 같은 attempt 가 들고 있어도 낡은 핸들이라 시작이 확인되지 않는다. 한 attempt 를 두 호출이 동시에 쓰는 - 것은 가려내지 못하므로 재시도는 앞 호출이 돌아온 뒤에 한다. + 핸들은 같은 attempt 가 들고 있어도 낡은 핸들이라 시작이 확인되지 않는다. 이미 적용된 전이(start·renew· + complete·markFailed·release)를 "이미 처리됨"으로 확인받는 것은 그 전이를 적용한 핸들뿐이다. 넘겨받은 뒤에 + 일어난 complete·markFailed 를 넘겨받기 전 핸들로 다시 보내면 `NOT_OWNER` 다(2026-11-06 소유자 결정). 한 attempt 를 + 두 호출이 동시에 쓰는 것은 가려내지 못하므로 재시도는 앞 호출이 돌아온 뒤에 한다. 만료된 `EXECUTING` 은 다른 caller 에게 `RECOVERY_REQUIRED` 로 답하되 기록은 그대로 둔다. 주인이 늦게 보고한 결과·실패는 기록된다 — 먼저 온 보고 하나만 남고 뒤의 보고는 거절된다(2026-11-04 소유자 결정, 재리뷰 RR5-01-03). lease 가 이미 끝났으면 주인도 시작(`markExecutionStarted`)과 `renew` 를 할 수 없고 diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyCompleteOutcome.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyCompleteOutcome.java index 4f09a42c..205acb69 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyCompleteOutcome.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyCompleteOutcome.java @@ -3,7 +3,14 @@ package dev.caskeleton.application.idempotency; /** Outcomes of an owner-safe EXECUTING to COMPLETED transition. */ public enum IdempotencyCompleteOutcome { COMPLETED, + /** + * This completion, from the handle presented, was already recorded with the same result (a lost + * reply). Only the handle the completion was applied from is told so; another handle of the same + * attempt — one from before a takeover — is {@link #NOT_OWNER} (owner decision 2026-11-06: the + * Redis and PostgreSQL stores confirmed it). + */ ALREADY_COMPLETED_SAME_RESULT, + /** The handle the completion was applied from resent it with another result. */ RESPONSE_CONFLICT, ABSENT, NOT_OWNER, diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyFailOutcome.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyFailOutcome.java index 9d65912d..aecee742 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyFailOutcome.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyFailOutcome.java @@ -4,6 +4,13 @@ package dev.caskeleton.application.idempotency; public enum IdempotencyFailOutcome { MARKED_RETRYABLE, MARKED_ABANDONED, + /** + * This failure, from the handle presented, was already recorded (a lost reply). Only the handle + * the failure was applied from is told so; another handle of the same attempt — one from before a + * takeover — is {@link #NOT_OWNER} (owner decision 2026-11-06: the Redis store confirmed it and + * the PostgreSQL store answered {@link #OPERATION_CONFLICT}; the in-memory fake refused even the + * handle that applied it). + */ ALREADY_MARKED_SAME_OPERATION, ABSENT, NOT_OWNER, diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyRenewOutcome.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyRenewOutcome.java index 6ae5b541..a0093c4d 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyRenewOutcome.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyRenewOutcome.java @@ -10,7 +10,12 @@ package dev.caskeleton.application.idempotency; public enum IdempotencyRenewOutcome { /** The lease was extended; the returned handle carries the advanced revision. */ RENEWED(true), - /** This exact renewal was already applied (a lost reply); the handle is the current one. */ + /** + * This exact renewal was already applied (a lost reply); the handle is the current one. Only the + * handle the renewal was applied from is told so; the handle that renewal returned renews again, + * and any other is {@link #NOT_OWNER} (owner decision 2026-11-06: the PostgreSQL store answered + * both {@link #OPERATION_CONFLICT}). + */ ALREADY_RENEWED_SAME_OPERATION(true), /** No record exists: it expired, or was never there. */ ABSENT(false), @@ -31,7 +36,8 @@ public enum IdempotencyRenewOutcome { LEASE_EXPIRED(false), /** * The call names an operation other than the one the record was claimed under (owner decision - * 2026-11-06), or this renewal was already applied asking for a different lease. Nothing changed. + * 2026-11-06), or this renewal was already applied, from this handle, asking for a different + * lease. Nothing changed. */ OPERATION_CONFLICT(false), /** The store may have applied the renewal; inspect before relying on either answer. */ diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyStartOutcome.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyStartOutcome.java index c35ea305..3806ad6e 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyStartOutcome.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyStartOutcome.java @@ -13,11 +13,17 @@ public enum IdempotencyStartOutcome { * #OPERATION_CONFLICT}). */ ALREADY_STARTED_SAME_OPERATION(true), - /** No record exists: it expired, was released, or was never there. */ + /** + * No record exists: it expired, was released, or was never there. A start through a released + * handle is this or {@link #NOT_OWNER}, by whether the store forgets a released record (Redis, + * the in-memory fake) or keeps it one revision past the handle (PostgreSQL). Both refuse it and + * nothing starts; a caller treats them alike (owner decision 2026-11-06). + */ ABSENT(false), /** * The record belongs to somebody else — the claim was taken over — or this handle's revision is - * stale. + * stale, as after the handle released the claim in a store that keeps the released record (see + * {@link #ABSENT}). */ NOT_OWNER(false), /** The record is not a claim waiting to start: it is executing or has ended. */ diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/IdempotencyStoreContract.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/IdempotencyStoreContract.java index c378a743..d2cb5e34 100644 --- a/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/IdempotencyStoreContract.java +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/IdempotencyStoreContract.java @@ -752,6 +752,221 @@ public abstract class IdempotencyStoreContract { .isEqualTo(IdempotencyStartOutcome.STARTED); } + // A transition already applied is confirmed only to the handle it was applied from — the record + // one revision past it — and any other handle is refused as a stale owner, the same attempt's + // handle from before a takeover included (owner decision 2026-11-06). The stores used to differ: + // the Redis store confirmed an applied completion or failure to every handle of its operation; + // the PostgreSQL store confirmed a completion to every handle of its owner token and answered + // another handle's failure, renewal or release OPERATION_CONFLICT — the holder's own second + // renewal included; the in-memory fake confirmed a completion and nothing else. + + @Test + @DisplayName("같은 attempt가 넘겨받기 전 핸들로, 넘겨받은 뒤 적용된 complete를 다시 보내면 확인하지 않고 NOT_OWNER다") + void theHandleFromBeforeATakeoverIsNotConfirmedTheCompletionThatFollowedIt() { + // given + IdempotencyStorePort store = subject(); + IdempotencyClaimAttempt attempt = store.newClaimAttempt(OPERATION); + IdempotencyOwner before = started(store, ownerOf(store.claim(claim(attempt, FINGERPRINT)))); + store.markFailed( + before, IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE, Duration.ofHours(1), OPERATION); + IdempotencyOwner after = started(store, ownerOf(store.claim(claim(attempt, FINGERPRINT)))); + store.complete(after, new StoredResponse("{\"v\":1}"), Duration.ofHours(1), OPERATION); + + // when + IdempotencyCompleteOutcome resent = + store.complete(before, new StoredResponse("{\"v\":1}"), Duration.ofHours(1), OPERATION); + + // then + assertThat(resent).isEqualTo(IdempotencyCompleteOutcome.NOT_OWNER); + } + + @Test + @DisplayName("같은 attempt가 넘겨받기 전 핸들로, 넘겨받은 뒤 적용된 markFailed를 다시 보내면 확인하지 않고 NOT_OWNER다") + void theHandleFromBeforeATakeoverIsNotConfirmedTheFailureThatFollowedIt() { + // given + IdempotencyStorePort store = subject(); + IdempotencyClaimAttempt attempt = store.newClaimAttempt(OPERATION); + IdempotencyOwner before = started(store, ownerOf(store.claim(claim(attempt, FINGERPRINT)))); + store.markFailed( + before, IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE, Duration.ofHours(1), OPERATION); + IdempotencyOwner after = started(store, ownerOf(store.claim(claim(attempt, FINGERPRINT)))); + store.markFailed( + after, IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE, Duration.ofHours(1), OPERATION); + + // when + IdempotencyFailOutcome resent = + store.markFailed( + before, + IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE, + Duration.ofHours(1), + OPERATION); + + // then + assertThat(resent).isEqualTo(IdempotencyFailOutcome.NOT_OWNER); + } + + @Test + @DisplayName("markFailed를 적용한 핸들이 같은 인자로 다시 보내면 이미 처리됨으로 확인한다") + void aFailureResentThroughTheHandleItWasAppliedFromIsConfirmed() { + // given + // The reply was lost, so the caller still holds the handle it sent the failure with. + IdempotencyStorePort store = subject(); + IdempotencyOwner executing = executing(store); + store.markFailed( + executing, + IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE, + Duration.ofHours(1), + OPERATION); + + // when + IdempotencyFailOutcome resent = + store.markFailed( + executing, + IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE, + Duration.ofHours(1), + OPERATION); + + // then + assertThat(resent).isEqualTo(IdempotencyFailOutcome.ALREADY_MARKED_SAME_OPERATION); + } + + @Test + @DisplayName("release한 핸들로 start하면 ABSENT나 NOT_OWNER로 거절되고 아무것도 시작되지 않는다") + void startingThroughAReleasedHandleStartsNothing() { + // given + IdempotencyStorePort store = subject(); + IdempotencyOwner claimed = acquire(store); + store.releaseBeforeExecution(claimed, OPERATION); + + // when + IdempotencyMutationResult started = + store.markExecutionStarted(claimed, OPERATION); + + // then + // A store that forgets the released record finds none (Redis, the in-memory fake); one that + // keeps it finds the handle one revision behind it (PostgreSQL). Either way nothing started + // and the next claim owns the scope (owner decision 2026-11-06). + assertThat(started.outcome()) + .isIn(IdempotencyStartOutcome.ABSENT, IdempotencyStartOutcome.NOT_OWNER); + IdempotencyClaimOutcome next = + store.claim(claim(store.newClaimAttempt(OTHER_OPERATION), FINGERPRINT)); + assertThat(store.markExecutionStarted(ownerOf(next), OTHER_OPERATION).outcome()) + .isEqualTo(IdempotencyStartOutcome.STARTED); + } + + @Test + @DisplayName("start를 적용한 핸들이 다시 보내면 이미 시작됨과 현재 핸들을 받는다") + void aStartResentThroughTheHandleItWasAppliedFromIsConfirmedWithTheCurrentHandle() { + // given + IdempotencyStorePort store = subject(); + IdempotencyOwner claimed = acquire(store); + IdempotencyOwner started = started(store, claimed); + + // when + IdempotencyMutationResult resent = + store.markExecutionStarted(claimed, OPERATION); + + // then + assertThat(resent.outcome()).isEqualTo(IdempotencyStartOutcome.ALREADY_STARTED_SAME_OPERATION); + assertThat(resent.owner().orElseThrow().stateRevision()).isEqualTo(started.stateRevision()); + } + + @Test + @DisplayName("renew를 적용한 핸들이 같은 lease로 다시 보내면 이미 renew됨과 현재 핸들을 받는다") + void aRenewalResentThroughTheHandleItWasAppliedFromIsConfirmedWithTheCurrentHandle() { + // given + IdempotencyStorePort store = subject(); + IdempotencyOwner executing = executing(store); + IdempotencyOwner renewed = + store.renew(executing, Duration.ofSeconds(30), OPERATION).owner().orElseThrow(); + + // when + IdempotencyMutationResult resent = + store.renew(executing, Duration.ofSeconds(30), OPERATION); + + // then + assertThat(resent.outcome()).isEqualTo(IdempotencyRenewOutcome.ALREADY_RENEWED_SAME_OPERATION); + assertThat(resent.owner().orElseThrow().stateRevision()).isEqualTo(renewed.stateRevision()); + } + + @Test + @DisplayName("renew를 적용한 핸들이 다른 lease로 다시 보내면 OPERATION_CONFLICT다") + void aRenewalResentThroughTheHandleItWasAppliedFromWithAnotherLeaseIsAConflict() { + // given + IdempotencyStorePort store = subject(); + IdempotencyOwner executing = executing(store); + store.renew(executing, Duration.ofSeconds(30), OPERATION); + + // when + IdempotencyMutationResult resent = + store.renew(executing, Duration.ofSeconds(45), OPERATION); + + // then + assertThat(resent.outcome()).isEqualTo(IdempotencyRenewOutcome.OPERATION_CONFLICT); + } + + @Test + @DisplayName("renew가 돌려준 핸들로 다시 renew하면 한 번 더 renew된다") + void aHolderRenewsAgainThroughTheHandleItsRenewalReturned() { + // given + IdempotencyStorePort store = subject(); + IdempotencyOwner executing = executing(store); + IdempotencyOwner renewed = + store.renew(executing, Duration.ofSeconds(30), OPERATION).owner().orElseThrow(); + + // when + IdempotencyMutationResult again = + store.renew(renewed, Duration.ofSeconds(30), OPERATION); + + // then + assertThat(again.outcome()).isEqualTo(IdempotencyRenewOutcome.RENEWED); + assertThat(again.owner().orElseThrow().stateRevision()).isGreaterThan(renewed.stateRevision()); + } + + @Test + @DisplayName("같은 attempt가 넘겨받기 전 핸들로 renew하면, 넘겨받은 뒤 적용된 renew로 확인하지 않고 NOT_OWNER다") + void theHandleFromBeforeATakeoverIsNotConfirmedTheRenewalThatFollowedIt() { + // given + IdempotencyStorePort store = subject(); + IdempotencyClaimAttempt attempt = store.newClaimAttempt(OPERATION); + IdempotencyOwner before = started(store, ownerOf(store.claim(claim(attempt, FINGERPRINT)))); + store.markFailed( + before, IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE, Duration.ofHours(1), OPERATION); + IdempotencyOwner after = started(store, ownerOf(store.claim(claim(attempt, FINGERPRINT)))); + store.renew(after, Duration.ofSeconds(30), OPERATION); + + // when + IdempotencyMutationResult resent = + store.renew(before, Duration.ofSeconds(30), OPERATION); + + // then + assertThat(resent.outcome()).isEqualTo(IdempotencyRenewOutcome.NOT_OWNER); + } + + @Test + @DisplayName("같은 attempt가 넘겨받기 전 핸들로 release하면, 넘겨받은 뒤 적용된 release로 확인하지 않는다") + void theHandleFromBeforeATakeoverIsNotConfirmedTheReleaseThatFollowedIt() { + // given + IdempotencyStorePort store = subject(); + IdempotencyClaimAttempt attempt = store.newClaimAttempt(OPERATION); + IdempotencyOwner before = ownerOf(store.claim(claim(attempt, FINGERPRINT))); + store.markFailed( + started(store, before), + IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE, + Duration.ofHours(1), + OPERATION); + IdempotencyOwner after = ownerOf(store.claim(claim(attempt, FINGERPRINT))); + store.releaseBeforeExecution(after, OPERATION); + + // when + IdempotencyReleaseOutcome resent = store.releaseBeforeExecution(before, OPERATION); + + // then + // As for a start through a released handle: a store that forgets the released record finds + // none, one that keeps it finds the handle stale. + assertThat(resent).isIn(IdempotencyReleaseOutcome.ABSENT, IdempotencyReleaseOutcome.NOT_OWNER); + } + @Test @DisplayName("실행 중인 자기 기록을 inspect하면 기록 수명이 아니라 claim이 받은 처리 lease 만료 시각이 나온다") void inspectingAnOwnExecutionReportsItsProcessingLeaseNotTheRecordLifetime() { diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/InMemoryIdempotencyStore.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/InMemoryIdempotencyStore.java index d840a5d9..39c02f4d 100644 --- a/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/InMemoryIdempotencyStore.java +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/InMemoryIdempotencyStore.java @@ -34,8 +34,9 @@ import java.util.Random; * attempt against an in-flight record is always {@code InProgress}. Leases and replay windows are * reported as {@link Instant#MAX}. What it keeps exact is what a test of a caller relies on: one * claim wins, the owner handle's revision advances on every transition, a completed response - * replays, a different fingerprint is refused, a retryable failure can be claimed again, and an - * owner naming an operation other than its claim's is refused. + * replays, a different fingerprint is refused, a retryable failure can be claimed again, an owner + * naming an operation other than its claim's is refused, and a transition resent after a lost reply + * is confirmed to the handle it was applied from and to no other. */ public final class InMemoryIdempotencyStore implements IdempotencyStorePort { @@ -99,17 +100,18 @@ public final class InMemoryIdempotencyStore implements IdempotencyStorePort { ? IdempotencyStartOutcome.ABSENT : row.namesAnotherOperation(owner, operationId) ? IdempotencyStartOutcome.OPERATION_CONFLICT - : !row.owner.equals(owner) - ? IdempotencyStartOutcome.NOT_OWNER - : row.state != IdempotencyState.CLAIMED - ? IdempotencyStartOutcome.NOT_CLAIMED - : IdempotencyStartOutcome.STARTED; - if (outcome != IdempotencyStartOutcome.STARTED) { - return new IdempotencyMutationResult<>(outcome, null, IdempotencyStartOutcome::carriesOwner); + : row.repeats(owner, Transition.START) + ? IdempotencyStartOutcome.ALREADY_STARTED_SAME_OPERATION + : !row.owner.equals(owner) + ? IdempotencyStartOutcome.NOT_OWNER + : row.state != IdempotencyState.CLAIMED + ? IdempotencyStartOutcome.NOT_CLAIMED + : IdempotencyStartOutcome.STARTED; + if (outcome == IdempotencyStartOutcome.STARTED) { + row.advance(IdempotencyState.EXECUTING, owner, Transition.START, null); } - row.advance(IdempotencyState.EXECUTING); return new IdempotencyMutationResult<>( - outcome, row.owner, IdempotencyStartOutcome::carriesOwner); + outcome, outcome.carriesOwner() ? row.owner : null, IdempotencyStartOutcome::carriesOwner); } @Override @@ -118,22 +120,27 @@ public final class InMemoryIdempotencyStore implements IdempotencyStorePort { Row row = rows.get(owner.scope().digest()); // Only a running execution has a processing lease to extend; the stores answer a claim that // has not started with NOT_IN_PROGRESS, and IdempotencyStoreContract holds the fake to that. - IdempotencyRenewOutcome refused = + // A renewal resent from the handle it was applied from is confirmed for the same lease and a + // conflict for another, as the stores answer. + IdempotencyRenewOutcome outcome = row == null ? IdempotencyRenewOutcome.ABSENT : row.namesAnotherOperation(owner, operationId) ? IdempotencyRenewOutcome.OPERATION_CONFLICT - : !row.owner.equals(owner) - ? IdempotencyRenewOutcome.NOT_OWNER - : row.state != IdempotencyState.EXECUTING - ? IdempotencyRenewOutcome.NOT_IN_PROGRESS - : null; - if (refused != null) { - return new IdempotencyMutationResult<>(refused, null, IdempotencyRenewOutcome::carriesOwner); + : row.repeats(owner, Transition.RENEW) + ? processingLeaseTtl.equals(row.applied.argument()) + ? IdempotencyRenewOutcome.ALREADY_RENEWED_SAME_OPERATION + : IdempotencyRenewOutcome.OPERATION_CONFLICT + : !row.owner.equals(owner) + ? IdempotencyRenewOutcome.NOT_OWNER + : row.state != IdempotencyState.EXECUTING + ? IdempotencyRenewOutcome.NOT_IN_PROGRESS + : IdempotencyRenewOutcome.RENEWED; + if (outcome == IdempotencyRenewOutcome.RENEWED) { + row.advance(row.state, owner, Transition.RENEW, processingLeaseTtl); } - row.advance(row.state); return new IdempotencyMutationResult<>( - IdempotencyRenewOutcome.RENEWED, row.owner, IdempotencyRenewOutcome::carriesOwner); + outcome, outcome.carriesOwner() ? row.owner : null, IdempotencyRenewOutcome::carriesOwner); } @Override @@ -149,7 +156,7 @@ public final class InMemoryIdempotencyStore implements IdempotencyStorePort { if (row.namesAnotherOperation(owner, operationId)) { return IdempotencyCompleteOutcome.OPERATION_CONFLICT; } - if (row.state == IdempotencyState.COMPLETED && owner.equals(row.completedBy)) { + if (row.repeats(owner, Transition.COMPLETE)) { // The completing handle retried, as after a lost reply: the same result is a no-op, another // result is a conflict, exactly as the stores answer. return row.response.equals(response) @@ -163,8 +170,7 @@ public final class InMemoryIdempotencyStore implements IdempotencyStorePort { return IdempotencyCompleteOutcome.NOT_IN_PROGRESS; } row.response = response; - row.completedBy = owner; - row.advance(IdempotencyState.COMPLETED); + row.advance(IdempotencyState.COMPLETED, owner, Transition.COMPLETE, null); return IdempotencyCompleteOutcome.COMPLETED; } @@ -181,6 +187,11 @@ public final class InMemoryIdempotencyStore implements IdempotencyStorePort { if (row.namesAnotherOperation(owner, operationId)) { return IdempotencyFailOutcome.OPERATION_CONFLICT; } + // The failing handle retried with the same disposition, as after a lost reply. Another + // disposition is not this failure and falls through to NOT_OWNER, as in the stores. + if (row.repeats(owner, Transition.FAIL) && disposition.equals(row.applied.argument())) { + return IdempotencyFailOutcome.ALREADY_MARKED_SAME_OPERATION; + } if (!row.owner.equals(owner)) { return IdempotencyFailOutcome.NOT_OWNER; } @@ -188,7 +199,11 @@ public final class InMemoryIdempotencyStore implements IdempotencyStorePort { return IdempotencyFailOutcome.NOT_IN_PROGRESS; } boolean retryable = disposition == IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE; - row.advance(retryable ? IdempotencyState.FAILED_RETRYABLE : IdempotencyState.ABANDONED); + row.advance( + retryable ? IdempotencyState.FAILED_RETRYABLE : IdempotencyState.ABANDONED, + owner, + Transition.FAIL, + disposition); return retryable ? IdempotencyFailOutcome.MARKED_RETRYABLE : IdempotencyFailOutcome.MARKED_ABANDONED; @@ -280,7 +295,7 @@ public final class InMemoryIdempotencyStore implements IdempotencyStorePort { private IdempotencyOwner owner; private IdempotencyState state = IdempotencyState.CLAIMED; private StoredResponse response; - private IdempotencyOwner completedBy; + private Applied applied; Row(RequestFingerprint fingerprint, IdempotencyClaimRequest request, long attempt, long rev) { this.fingerprint = fingerprint; @@ -293,9 +308,20 @@ public final class InMemoryIdempotencyStore implements IdempotencyStorePort { request.claimAttempt().operationId()); } - void advance(IdempotencyState next) { + /** Applies a transition from {@code from}, remembering it for a resend of the same call. */ + void advance(IdempotencyState next, IdempotencyOwner from, Transition kind, Object argument) { owner = owner.withStateRevision(owner.stateRevision() + 1); state = next; + applied = new Applied(from, kind, argument); + } + + /** + * Whether {@code caller} resends the last transition applied, from the handle it was applied + * from. Only that handle is told the transition was already applied; any other is not, the same + * attempt's handle from before a takeover included (owner decision 2026-11-06). + */ + boolean repeats(IdempotencyOwner caller, Transition kind) { + return applied != null && applied.kind() == kind && applied.from().equals(caller); } /** @@ -308,4 +334,22 @@ public final class InMemoryIdempotencyStore implements IdempotencyStorePort { && !owner.claimOperationId().equals(operationId); } } + + /** The transitions a handle can resend after a lost reply. */ + private enum Transition { + START, + RENEW, + COMPLETE, + FAIL + } + + /** + * The last transition applied to a record. + * + * @param from the handle it was applied from + * @param kind which transition + * @param argument what it decided besides the handle: the lease of a renewal, the disposition of + * a failure; {@code null} for the others + */ + private record Applied(IdempotencyOwner from, Transition kind, Object argument) {} } From a8166598d5832f1f1d0401086f01239941ccc54f Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Sat, 7 Nov 2026 01:09:54 +0900 Subject: [PATCH 26/71] =?UTF-8?q?fix(app-bootstrap)!:=20=EC=84=A4=EC=A0=95?= =?UTF-8?q?=EC=97=90=20=EC=A4=91=EC=B2=A9=EB=90=9C=20endpoint=EB=A5=BC=20?= =?UTF-8?q?=EB=8B=A4=EC=8B=9C=20=EC=9E=A1=EA=B3=A0=20route=20=EB=93=B1?= =?UTF-8?q?=EB=A1=9D=20=ED=8C=90=EC=A0=95=EC=9D=84=20=EB=AC=B8=EC=84=9C?= =?UTF-8?q?=EC=97=90=20=EB=A7=9E=EC=B6=98=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 - 설정에 중첩된 클래스를 요청 처리기 목록(ARE_REQUEST_HANDLER_TYPES)으로만 본다. 이 목록에는 JAX-RS와 주석형 JSR-356 타입이 없어서, 설정 안에 둔 JAX-RS 자원이나 @ServerEndpoint가 @SystemCaller를 불러도 잡히지 않는다. r9는 잡았다(RR7-01-01, 회귀). - 메서드 참조로 route만 등록한 설정도 사용자 전송으로 센다. 그런데 Javadoc, 매뉴얼 07, 업그레이드 안내 B-16은 "요청 처리 코드가 있을 때만"이라고 적어, 안내대로 처리 코드를 옮겨도 빌드가 실패한다(RR7-01-02). 같은 원인으로 CORS 설정에 쓰는 RequestMethod도 설정을 사용자 전송으로 만든다. 고른 방법 - 설정 클래스 자신만 요청 처리기 목록으로 본다. 중첩 클래스는 r9처럼 사용자 전송 타입 전체로 본다. 설정용 타입(ARE_TRANSPORT_SETUP_TYPES: MVC·WebFlux· WebSocket·STOMP broker 설정 패키지, CORS 설정, RequestMethod)에만 의존하는 중첩 클래스는 설정의 일부로 둔다. 설정 필드를 읽는 익명 WebMvcConfigurer (RR6-01-02)가 이 경우다. 목록에 없는 타입은 잡히는 쪽(거짓 실패)으로 간다. - RR7-01-02는 판정을 좁히지 않고 문서를 동작에 맞췄다. route·data fetcher· interceptor 등록은 handler bean을 만드는 설정과 다른 설정에 둔다. 실패 메시지에도 이 안내를 넣었다. RequestMethod만 설정용 타입으로 뺐다. - 두 목록이 다시 갈라지지 않게 UserTransportTypeListsTest를 더했다. 요청 처리기·설정용 항목은 모두 사용자 전송 타입이어야 하고, 설정용 항목은 요청 처리기 타입을 덮지 않아야 한다. - 버린 대안: - 중첩 클래스에서 바깥 설정으로 가는 의존을 따라가지 않기(리뷰 권장안). 중첩 endpoint가 설정의 메서드를 거쳐 작업을 부르는 길을 놓친다. r9는 잡던 길이다. 위반 fixture RunNowThroughTheConfigurationFixture로 고정했다. - 요청 처리기 목록에 JAX-RS·JSR-356 타입을 더하기. 목록에 없는 다음 라이브러리에서 같은 구멍이 난다. - 설정 판정을 "요청을 받는 메서드"(파라미터·annotation·상속)로 좁히기. route builder 람다(b -> b.GET(...))도 builder를 받아 목록이 또 필요하고 규칙이 복잡해진다. - @CrossOrigin·HttpServletRequest는 설정용 타입으로 빼지 않았다. @CrossOrigin은 handler에만 붙고, HttpServletRequest를 받는 람다(matcher, CORS source)는 요청마다 돈다. 위험·한계 - 판정이 넓어진 곳: 설정에 중첩된 클래스가 설정용이 아닌 웹 타입(예: HandlerMethodArgumentResolver, RestClient)을 쓰고 설정 필드를 읽으며, 그 설정이 @SystemCaller bean을 만들면 이제 실패한다. r9와 같고 r10보다 엄격하다. 그 타입이 기동 때만 도는 설정용 타입이면 목록에 더한다. - JAX-RS·JSR-356 런타임 기동은 보지 않았다. 규칙 판정만 봤다. 검증 (desktop, flock /tmp/claude-gates/heavy.lock, 로그 ~/r8-f2-arch-rules-logs/) - RED: 73d39212에 테스트·fixture만 얹고 ArchitectureViolationFixtureTest 실행. 87건 중 5건 실패: 중첩 JAX-RS·설정 경유·@ServerEndpoint 셋은 위반 0건, CORS 두 모양은 거짓 위반. rc=1. - GREEN: :app-bootstrap:architectureTest --rerun 237건 실패 0, rc=0. - 변이: 설정용 목록에 servlet.function, 요청 처리기 목록에 io.vertx.ext.web을 넣으면 UserTransportTypeListsTest 2건과 fixture 테스트 3건이 실패했다. - :app-bootstrap:check, architectureCheck, :app-bootstrap:testQualityCheck, :ci :verifyDependencyLocks --warning-mode=fail, :verifyStrictLaneStages --dry-run, :sample-portfolio:check :sample-portfolio:qualityCheck, -p optional-platforms ci, -p optional-platforms :verifyStrictLaneStages --dry-run, scripts/verify-compose-profile-contracts.sh 모두 rc=0. - 매뉴얼 07과 업그레이드 안내를 읽는 테스트는 없다(src grep 0건). check-work-docs.py --links docs: 깨진 링크 0. BREAKING CHANGE: 설정(@Configuration)에 중첩된 클래스를 사용자 전송 타입 전체로 판정한다. 그 안의 JAX-RS 자원·@ServerEndpoint 같은 endpoint가 @SystemCaller에 닿으면(설정의 메서드를 거쳐도) architectureTest가 실패한다. route·data fetcher· interceptor 등록은 handler bean을 만드는 설정과 다른 설정에 둔다 (docs/upgrade/2026-11-maturity-review.md B-16). Refs: docs/reviews/2026-11-03-rereview/round7/01-core-inbound.md RR7-01-01, RR7-01-02 --- docs/manual/07-authorization.md | 19 +- docs/upgrade/2026-11-maturity-review.md | 2 +- .../ApplicationBoundaryArchitectureTest.java | 239 ++++++++++++------ .../ArchitectureViolationFixtureTest.java | 173 ++++++++++++- .../UserTransportTypeListsTest.java | 81 ++++++ .../configuration/OrderHandlerFixture.java | 12 + .../OrderRoutesConfigurationFixture.java | 21 ++ .../SystemCallerBesideCorsMappingFixture.java | 42 +++ .../SystemCallerBesideCorsSourceFixture.java | 33 +++ .../allowed/configuration/package-info.java | 9 +- ...sideASystemCallerConfigurationFixture.java | 32 +++ ...owHandlerFunctionConfigurationFixture.java | 5 +- .../RunNowResourceConfigurationFixture.java | 33 +++ .../RunNowThroughTheConfigurationFixture.java | 34 +++ .../RunNowEndpointConfigurationFixture.java | 29 +++ 15 files changed, 673 insertions(+), 91 deletions(-) create mode 100644 src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/UserTransportTypeListsTest.java create mode 100644 src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/OrderHandlerFixture.java create mode 100644 src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/OrderRoutesConfigurationFixture.java create mode 100644 src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/SystemCallerBesideCorsMappingFixture.java create mode 100644 src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/SystemCallerBesideCorsSourceFixture.java create mode 100644 src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/RoutesBesideASystemCallerConfigurationFixture.java create mode 100644 src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/jaxrs/RunNowResourceConfigurationFixture.java create mode 100644 src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/jaxrs/RunNowThroughTheConfigurationFixture.java create mode 100644 src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/jsr356/RunNowEndpointConfigurationFixture.java diff --git a/docs/manual/07-authorization.md b/docs/manual/07-authorization.md index c1f0bd40..68bedd30 100644 --- a/docs/manual/07-authorization.md +++ b/docs/manual/07-authorization.md @@ -102,15 +102,19 @@ JWT의 `realm_access.roles`와 **자기 client**(`app.security.audience`)의 `re | bean 금지 | `@SystemInvoked` 유스케이스가 bean이면 기동 실패. 호출자가 `new`로 만들어 혼자 들고 있는 것만 허용한다 | `src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/authorization/PermissionEnforcementGuard.java` | | 시스템 호출자만 | inbound adapter가 그 클래스에 의존하면 빌드 실패. `@SystemCaller(reason = "...")`를 단 클래스와 그 안에 중첩된 클래스만 예외 | `ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES`(`ApplicationBoundaryArchitectureTest`) | | 표시 검사 | `@SystemCaller` 클래스와 그 안에 중첩된 클래스는 `..adapter.inbound.messaging..`·`..adapter.inbound.scheduler..`에만 있고, 사용자 전송 타입(controller·JAX-RS·GraphQL·STOMP mapping·gRPC·servlet)에 의존하지 않는다 | `SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS`(같은 파일) | -| 전송 → 시스템 호출자 금지 | 사용자 전송 클래스가 `@SystemCaller`나, 그 클래스가 구현·상속하는 프로젝트 타입(작업의 인터페이스 등)에 의존하면 빌드 실패. 중간 클래스를 거쳐도 잡는다. 사용자 전송 클래스는 셋이다. ① 사용자 전송 패키지에 있는 클래스. ② 설정(`@Configuration`·`@AutoConfiguration`)과 그 안에 중첩된 클래스 가운데 요청 처리기 타입(함수형 `RouterFunction`·`HandlerFunction`, `@RestController`·`@RequestMapping`, servlet·`Filter`·`HandlerInterceptor`, `WebSocketHandler`, GraphQL `DataFetcher`·`RuntimeWiringConfigurer`, gRPC `BindableService`·`ServerInterceptor` 등)에 의존하는 것. 함수형 route나 data fetcher를 람다로 쓰면 그 코드가 설정 클래스의 메서드로 컴파일되어 설정이 곧 endpoint다. ③ 그 밖의 클래스 가운데 사용자 전송 타입에 의존하는 것. 그래서 handler를 bean으로 등록하는 설정은 같은 클래스에서 `WebMvcConfigurer`(설정 필드를 읽는 익명 클래스여도)·controller bean을 함께 만들어도 걸리지 않지만, 같은 클래스에 "지금 실행" route·data fetcher·interceptor를 직접 쓰면 걸린다. 요청 처리 코드는 handler를 등록하는 설정과 다른 클래스에 둔다. 설정이 만드는 controller는 controller 자신이 검사받는다 | `USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS`(같은 파일) | +| 전송 → 시스템 호출자 금지 | 사용자 전송 클래스가 `@SystemCaller`나, 그 클래스가 구현·상속하는 프로젝트 타입(작업의 인터페이스 등)에 의존하면 빌드 실패. 중간 클래스를 거쳐도 잡는다. 사용자 전송 클래스는 넷이다. ① 사용자 전송 패키지에 있는 클래스. ② 설정(`@Configuration`·`@AutoConfiguration`) 클래스 자신이 요청 처리기 타입(함수형 `RouterFunction`·`HandlerFunction`, `@RestController`·`@RequestMapping`, servlet·`Filter`·`HandlerInterceptor`, `WebSocketHandler`, GraphQL `DataFetcher`·`RuntimeWiringConfigurer`, gRPC `BindableService`·`ServerInterceptor` 등)에 의존하는 것. 요청 처리 코드를 설정에 직접 쓴 경우와 등록만 한 경우가 모두 든다. 함수형 route나 data fetcher를 람다로 쓰면 그 코드가 설정 클래스의 메서드로 컴파일되어 설정이 곧 endpoint다. 처리 코드를 다른 클래스에 두고 메서드 참조로 등록만 해도(`route().GET("/orders", orders::list)`) 설정은 route builder에 의존한다. 클래스 의존으로는 등록과 처리 코드를 가를 수 없어서 둘 다 사용자 전송으로 센다. ③ 설정 안에 중첩된 클래스 가운데 사용자 전송 타입에 의존하는 것. 중첩된 JAX-RS 자원·`@ServerEndpoint`도 여기서 잡힌다. 설정용 타입(`WebMvcConfigurer`·`WebSocketConfigurer`·STOMP broker 설정과 그 registry, CORS 설정, `RequestMethod`)에만 의존하는 중첩 클래스는 설정의 일부로 본다. ④ 그 밖의 클래스 가운데 사용자 전송 타입에 의존하는 것. 그래서 handler를 bean으로 등록하는 설정은 같은 클래스에서 `WebMvcConfigurer`(설정 필드를 읽는 익명 클래스여도)·CORS 설정·controller bean을 함께 만들어도 걸리지 않는다. 같은 클래스에 "지금 실행" route·data fetcher·interceptor를 쓰거나, route를 등록하거나, 안에 중첩한 endpoint가 작업을 부르면(설정의 메서드를 거쳐 불러도) 걸린다. route·data fetcher·interceptor 등록은 handler bean을 만드는 설정과 다른 설정에 둔다. 설정이 만드는 controller는 controller 자신이 검사받는다 | `USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS`(같은 파일) | | 프로젝트 밖 상위 타입 금지 | `@SystemCaller` 클래스와 그 안에 중첩된 클래스(익명·지역 클래스와 예외 제외)는 프로젝트(`dev.caskeleton..`) 밖의 클래스·인터페이스를 상속·구현하지 않는다. `Runnable`은 누구나 의존하는 타입이라, endpoint가 작업을 `Runnable`로 주입받아도 위 규칙이 다른 사용과 구별하지 못하기 때문이다. 메시지 handler의 `MessageHandler`는 프로젝트 타입이라 된다. record·enum은 언어가 붙이는 상위 타입(`Record`, `Enum`과 `Enum`이 구현하는 `Comparable`·`Serializable`·`Constable`)만은 가져도 된다. 그래서 handler 안의 파싱 결과 record, 결과 enum, 독(poison) 메시지 예외, record로 쓴 handler는 통과하고, `Runnable`을 구현한 record는 걸린다 | `SYSTEM_CALLERS_HAVE_ONLY_PROJECT_SUPERTYPES`(같은 파일) | 규칙은 "누가 닿으면 안 되나"가 아니라 "누가 닿아도 되나"를 적는다. 이 성질은 **패키지** 쪽에서만 온다. 패키지는 허용 목록이라, 나중에 새 전송 패키지가 생겨도 따로 고치지 않아도 막힌다. 사용자 전송 **타입** 쪽은 나열 목록이다(`ARE_USER_TRANSPORT_TYPES`). 시스템 패키지 안에 놓인 endpoint를 알아보는 데 쓰는 목록이라, 목록에 없는 전송 라이브러리로 만든 endpoint는 전송으로 보이지 않는다. 새 전송 라이브러리를 -들이면 그 패키지를 이 목록에 더한다. 설정 안의 요청 처리 코드를 알아보는 요청 처리기 타입 -(`ARE_REQUEST_HANDLER_TYPES`)도 나열 목록이라, 새 전송 라이브러리의 handler 타입을 함께 더한다. +들이면 그 패키지를 이 목록에 더한다. 설정 클래스 자신을 판정하는 요청 처리기 타입 +(`ARE_REQUEST_HANDLER_TYPES`)도 나열 목록이라, 새 전송 라이브러리의 handler 타입을 함께 더한다. 요청 처리기 +타입은 모두 사용자 전송 타입이어야 하고, 설정용 타입(`ARE_TRANSPORT_SETUP_TYPES`)은 요청 처리기 타입을 덮지 +않아야 한다. `UserTransportTypeListsTest`가 둘을 검사한다. 설정용 타입 목록에 없는 configurer 타입을 쓰는 중첩 +클래스는 사용자 전송으로 읽혀, 설정 필드를 읽으면 빌드가 실패한다. 그 타입이 요청마다 도는 코드가 아니라 기동 때 +한 번 도는 설정용 타입이면 설정용 타입 목록에 더한다. 쓰기 유스케이스의 권한 선언 검사(`MUTATING_USE_CASES_DECLARE_REQUIRED_PERMISSION`) 실패를 끄려고 이 표시를 쓰지 않는다. 사용자가 부르는 쓰기라면 권한을 선언하고 역할에 매핑한다. 같은 쓰기를 사용자도 시스템도 부르면 유스케이스를 둘로 나눈다 @@ -123,10 +127,11 @@ JWT의 `realm_access.roles`와 **자기 client**(`app.security.audience`)의 `re - 이름이나 `Object`로 bean을 찾는 코드: `getBean("nightlyJob")`, `Map` 주입 뒤 reflection 호출. - 설정이 사용자 전송에 작업을 감싼 함수를 넘기는 코드: `new RunNowController(job::run)`처럼 controller는 - `Runnable`만 받는다. 의존은 설정 → 작업 쪽에만 있고, 요청 처리 코드를 직접 갖지 않은 설정은 사용자 전송이 + `Runnable`만 받는다. 의존은 설정 → 작업 쪽에만 있고, 요청 처리기 타입에 의존하지 않는 설정은 사용자 전송이 아니다. -- 설정 안의 요청 처리 코드가 요청 처리기 타입 목록(`ARE_REQUEST_HANDLER_TYPES`)에 없는 타입으로 쓰인 경우. - 목록 방식이라, 목록에 없는 endpoint 타입으로 설정 안에 쓴 endpoint는 사용자 전송으로 보이지 않는다. +- 설정 클래스 자신에 쓴 요청 처리 코드가 요청 처리기 타입 목록(`ARE_REQUEST_HANDLER_TYPES`)에 없는 타입으로 + 쓰인 경우. 목록 방식이라, 목록에 없는 endpoint 타입으로 설정 클래스에 직접 쓴 endpoint는 사용자 전송으로 + 보이지 않는다. 설정 안에 중첩한 클래스는 더 넓은 사용자 전송 타입 목록으로 보므로 여기에 들지 않는다. 이 길을 막는 것은 ArchUnit 규칙이 아니라 다음 셋이다. @@ -137,7 +142,7 @@ JWT의 `realm_access.roles`와 **자기 client**(`app.security.audience`)의 `re 못 한다. 예약 작업은 서비스 자기 leaf에 있어서 같은 leaf의 controller와 사이에는 이 게이트가 없다. 그래서 위 길들은 사실상 controller와 작업이 같은 leaf에 있을 때, 또는 둘을 모두 보는 설정에서 생긴다. - 리뷰: 설정에서 시스템 호출자를 함수로 감싸 다른 bean에 넘기거나, 사용자 전송이 bean을 이름으로 찾거나, 목록에 - 없는 타입으로 설정 안에 endpoint를 쓰는 코드는 리뷰에서 거절한다. 사용자도 같은 일을 시켜야 하면 위 문단대로 + 없는 타입으로 설정 클래스에 endpoint를 쓰는 코드는 리뷰에서 거절한다. 사용자도 같은 일을 시켜야 하면 위 문단대로 사용자용 유스케이스를 따로 만든다. ## web 없는 조립 diff --git a/docs/upgrade/2026-11-maturity-review.md b/docs/upgrade/2026-11-maturity-review.md index 7a0f1509..0da2b54c 100644 --- a/docs/upgrade/2026-11-maturity-review.md +++ b/docs/upgrade/2026-11-maturity-review.md @@ -75,7 +75,7 @@ | B-13 | `app.security.*` strict 바인딩: 접두어 아래 오타 키, 또는 설정·placeholder 어디에도 쓰이지 않는 `APP_SECURITY_*` 환경 변수가 기동을 막는다 | 기동 실패(메시지는 `StrictSettingsBinder`가 키 이름을 담아 냄, 정확한 문구 확인 못 함) | 쓰지 않는 `APP_SECURITY_*` 변수를 지운다 | `5786126c` · `SecuritySettings.bind`, `src/adapter/outbound/support/.../StrictSettingsBinder.java` | | B-14 | prod 프로필에서 `fixture-`로 시작하는 비밀값을 거부(레지스트리 `secret` 행, 모듈이 기여한 비밀, `secret://…/` 참조 대상. `HOSTNAME`·앱 이름 같은 비밀 아닌 값은 보지 않는다 — RR2-04-01). Redis ACL fixture 파일 이름 변경: `infra/redis-sdk/acl/all-accounts.acl` → `lane-fixture-accounts.acl` | prod 기동 실패, 요약 `prod secret/config-source contract is invalid`(exit 78). 옛 ACL 경로를 mount하던 compose는 파일 없음 | prod 값을 진짜 비밀로 바꾼다. compose의 ACL 경로를 새 이름으로. Redis SDK admin 계정(`RedisAccountContribution`)을 조립했다면 그 변수를 `static` `RequiredProductionSecrets` bean으로도 낸다(코드에 든 참조는 검사가 보지 않는다, RR3-04-03, `src/adapter/outbound/redis-sdk/README.md`) | `bbe944bd` · `src/app-bootstrap/.../runtime/SecretSourceValidator.java`, `docs/registries/secrets-classification.yaml` | | B-15 | 기동 rule이 모든 singleton보다 먼저 돈다(`StartupRuleRunner`가 `BeanFactoryPostProcessor`). `StartupRule`과 `RequiredProductionSecrets` bean은 `static @Bean`이고 `Environment`, bean factory, static 무인자 `RequiredProductionSecrets`의 `ObjectProvider`만 받아야 한다. 두 타입의 클래스는 `@Value`·`@Autowired`·`@Inject`·`@Resource` 멤버, `@PostConstruct`·`@PreDestroy`, `@ConfigurationProperties`를 가질 수 없다(post-processor보다 먼저 만들어져 비어 있게 된다, RR2-04-03) | non-static `@Bean`이거나 다른 bean을 받으면 기동 실패 `startup rule or secret list '<이름>' created [] while creating it ... Declare the rule with a static @Bean method ...`, 위 멤버가 있으면 `'<이름>' (...) is a StartupRule or RequiredProductionSecrets ... but it needs one: [...]`(둘 다 exit 78, 둘 다 모든 프로필. runner가 rule과 비밀 목록을 프로필과 무관하게 먼저 만들어, 인터페이스 타입 `@Bean`이 돌려준 실제 클래스까지 본다, RR3-04-01) | rule 선언을 `static`으로, 인자를 위 셋으로 줄인다. 값은 `violations(Environment)`가 받는 `Environment`에서 읽는다. 다른 bean이 필요한 검사는 rule이 아니라 일반 bean으로 둔다 | `34565130`, `bbe944bd` · `src/adapter/outbound/support/.../startup/StartupRule.java`, `StartupRuleRunner.java` | -| B-16 | 권한 가드(새 `PermissionEnforcementGuard`): `@SystemInvoked` 유스케이스가 bean이면 기동 실패. `@RequiresPermission`을 단 bean에 적용되는 advisor가 없어도 기동 실패. ArchUnit `SYSTEM_INVOKED_USE_CASES_DECLARE_NO_PERMISSION`, `ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES`, `SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS`, `USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS`, `SYSTEM_CALLERS_HAVE_ONLY_PROJECT_SUPERTYPES` 추가, 새 표시 `@SystemCaller` | 기동 실패 `@SystemInvoked use cases are registered as beans ...` 또는 `beans declare @RequiresPermission but no advisor enforces it ...`(exit 72). `@SystemCaller`가 아닌 inbound adapter가 그 유스케이스를 부르거나, 사용자 전송(controller 등)이 `@SystemCaller` bean을 직접·중간 클래스를 거쳐·그 작업이 구현하는 프로젝트 인터페이스로 부르면 architectureTest 실패. `@SystemCaller` 클래스가 `Runnable`·`ApplicationRunner` 같은 프로젝트 밖 타입을 구현·상속해도 실패. 설정(`@Configuration`)은 웹 bean과 handler bean을 함께 등록해도 사용자 전송으로 세지 않지만, 요청 처리 코드(함수형 route·data fetcher·interceptor 같은 요청 처리기 타입)를 그 설정이나 그 안에 중첩된 클래스에 직접 쓰면 사용자 전송으로 센다. record·enum이 언어로 받는 상위 타입(`Record`·`Enum` 등)과 예외 클래스는 프로젝트 밖 상위 타입으로 세지 않는다 | 시스템만 부르는 쓰기 유스케이스는 composition에서 `new`로 만들어 스케줄러에 넘기거나, 메시지 handler·예약 작업이면 그 클래스에 `@SystemCaller`를 달고 생성자에서 `new`로 만든다. 예약 작업은 서비스 leaf의 `..adapter.inbound.scheduler..` 패키지에 둔다. 세 경로와 두는 곳은 매뉴얼 07장 「시스템이 부르는 쓰기」(handler 작업 순서는 09장 「소비」 4단계). "지금 실행" endpoint가 필요하면 `@RequiresPermission` 유스케이스를 따로 만든다. 작업을 task scheduler에 직접 등록하던 코드는 작업이 `Runnable`을 구현하는 대신 등록하는 곳에서 `job::run`을 넘긴다. 요청 처리 코드는 handler를 등록하는 설정과 다른 클래스에 둔다. `@RequiresPermission`을 쓰면 web adapter(`MethodSecurityConfig`)가 조립돼 있어야 한다 | `1400dc15`, `bbe944bd`, r9 · `src/composition/service-runtime/.../authorization/PermissionEnforcementGuard.java`, `src/application-core/.../security/SystemInvoked.java`, `SystemCaller.java` | +| B-16 | 권한 가드(새 `PermissionEnforcementGuard`): `@SystemInvoked` 유스케이스가 bean이면 기동 실패. `@RequiresPermission`을 단 bean에 적용되는 advisor가 없어도 기동 실패. ArchUnit `SYSTEM_INVOKED_USE_CASES_DECLARE_NO_PERMISSION`, `ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES`, `SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS`, `USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS`, `SYSTEM_CALLERS_HAVE_ONLY_PROJECT_SUPERTYPES` 추가, 새 표시 `@SystemCaller` | 기동 실패 `@SystemInvoked use cases are registered as beans ...` 또는 `beans declare @RequiresPermission but no advisor enforces it ...`(exit 72). `@SystemCaller`가 아닌 inbound adapter가 그 유스케이스를 부르거나, 사용자 전송(controller 등)이 `@SystemCaller` bean을 직접·중간 클래스를 거쳐·그 작업이 구현하는 프로젝트 인터페이스로 부르면 architectureTest 실패. `@SystemCaller` 클래스가 `Runnable`·`ApplicationRunner` 같은 프로젝트 밖 타입을 구현·상속해도 실패. 설정(`@Configuration`)은 웹 bean(`WebMvcConfigurer`·CORS 설정·controller bean)과 handler bean을 함께 등록해도 사용자 전송으로 세지 않지만, 요청 처리기 타입(함수형 route·data fetcher·interceptor)에 의존하면 사용자 전송으로 센다. 처리 코드를 설정에 직접 쓰든, 다른 클래스의 메서드를 참조해 등록만 하든 같다. 설정 안에 중첩된 클래스는 설정용 타입(configurer·registry·CORS 설정·`RequestMethod`)에만 의존할 때를 빼고 다른 클래스처럼 사용자 전송 타입으로 판정한다(중첩된 JAX-RS 자원·`@ServerEndpoint`도 잡힌다). record·enum이 언어로 받는 상위 타입(`Record`·`Enum` 등)과 예외 클래스는 프로젝트 밖 상위 타입으로 세지 않는다 | 시스템만 부르는 쓰기 유스케이스는 composition에서 `new`로 만들어 스케줄러에 넘기거나, 메시지 handler·예약 작업이면 그 클래스에 `@SystemCaller`를 달고 생성자에서 `new`로 만든다. 예약 작업은 서비스 leaf의 `..adapter.inbound.scheduler..` 패키지에 둔다. 세 경로와 두는 곳은 매뉴얼 07장 「시스템이 부르는 쓰기」(handler 작업 순서는 09장 「소비」 4단계). "지금 실행" endpoint가 필요하면 `@RequiresPermission` 유스케이스를 따로 만든다. 작업을 task scheduler에 직접 등록하던 코드는 작업이 `Runnable`을 구현하는 대신 등록하는 곳에서 `job::run`을 넘긴다. route·data fetcher·interceptor 등록은 handler bean을 만드는 설정과 다른 설정에 둔다. `@RequiresPermission`을 쓰면 web adapter(`MethodSecurityConfig`)가 조립돼 있어야 한다 | `1400dc15`, `bbe944bd`, r9 · `src/composition/service-runtime/.../authorization/PermissionEnforcementGuard.java`, `src/application-core/.../security/SystemInvoked.java`, `SystemCaller.java` | | B-17 | `IntegrationEventDraft`: `eventId`·`causationId`는 소문자 UUIDv7만. ArchUnit `INTEGRATION_EVENT_DRAFTS_ARE_BUILT_BY_THE_SHARED_HELPER`: `new IntegrationEventDraft<>(...)` 금지, `IntegrationEventDrafts.draft(...)`만 | 이벤트를 만드는 쓰기 요청이 `IllegalArgumentException: eventId must be a canonical lower-case UUIDv7...`로 실패. architectureTest 실패 | event id를 UUIDv7로 만든다(예: sample `UuidOutboxEventIdFactory`가 `UuidCreator.getTimeOrderedEpochPlus1()`). draft는 헬퍼로 만든다. tenant가 없는 이벤트는 `IntegrationEventDrafts.SINGLE_TENANT_SCOPE`(`global`) | `1400dc15`, `bbe944bd` · `src/application-core/.../messaging/event/IntegrationEventDraft.java`, `IntegrationEventDrafts.java` | | B-18 | `MessageHandler.schemaVersions()`(vendored `messaging-core-api`, default `{v1}`): 소비자 decode 목록을 handler 선언으로 만든다. 같은 (메시지 타입, 버전)에 다른 payload class를 선언하면 실패 | 컴파일은 된다. v1이 아닌 메시지는 `SCHEMA_VERSION_NOT_REGISTERED`로 거부. 발행 등록(`MessageContracts`)과 class가 다르면 기동 실패 `MESSAGING_CONTRACT_CONFLICT` | v2 이상을 읽는 handler는 `schemaVersions()`를 override한다. 소비 타입을 `MessageContracts`에 따로 등록하던 코드는 지운다 | `5786126c` · `src/messaging/messaging-core-api/.../delivery/MessageHandler.java`, `messaging-spring-boot-starter/.../MessageContracts.java` | | B-19 | `APP_FLYWAY_ENABLED`가 모든 프로필에서 읽힌다. dev·prod 프로필 파일의 `spring.flyway.enabled: true`·`app.persistence.vendor` 고정값을 지우고 persistence-jpa `config/module-defaults`가 `${APP_FLYWAY_ENABLED:true}`를 싣는다 | dev·prod 환경에 `APP_FLYWAY_ENABLED=false`가 있으면 전에는 무시됐지만 이제 기동 때 마이그레이션이 안 돈다 | dev·prod 환경 값을 확인한다. 자기 `application-dev.yml`·`application-prod.yml`에 같은 고정값을 다시 넣지 않는다 | `5786126c` · `src/app-bootstrap/src/main/resources/application-{dev,prod}.yml`, `src/adapter/outbound/persistence-jpa/.../module-defaults/persistence-jpa.yml` | diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java index 24e4f6ef..2e51e6e1 100644 --- a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java @@ -459,43 +459,70 @@ class ApplicationBoundaryArchitectureTest { }; /** - * What makes a class a way in for a user request: a user-transport adapter package or the - * framework types an endpoint is built from. {@code org.springframework.messaging} is named only - * for STOMP ({@code simp}, {@code @MessageMapping}): a broker listener's {@code @Payload} and - * {@code @Header} live beside them and are a system consumer's, not a user's. + * The framework packages user-transport endpoints are built from, each with its subpackages. + * {@code org.springframework.messaging} is named only for STOMP ({@code simp}, {@code + * MessageMapping} in {@link #USER_TRANSPORT_TYPE_NAMES}): a broker listener's {@code @Payload} + * and {@code @Header} live beside them and are a system consumer's, not a user's. * - *

The framework half is a list, unlike the package allowlist above: a transport library - * missing from it is not recognised as one. A service that brings in a new transport library adds - * its packages here (review 2026-11-04 RR3-01-02). + *

This is a list, unlike the package allowlist above: a transport library missing from it is + * not recognised as one. A service that brings in a new transport library adds its packages here + * (review 2026-11-04 RR3-01-02). + */ + static final List USER_TRANSPORT_FRAMEWORK_PACKAGES = + List.of( + "org.springframework.web", + "org.springframework.graphql", + "org.springframework.messaging.simp", + "io.grpc", + "jakarta.servlet", + "jakarta.websocket", + "jakarta.ws.rs", + "graphql"); + + /** The single user-transport types named beside the framework packages. */ + static final Set USER_TRANSPORT_TYPE_NAMES = + Set.of( + "org.springframework.stereotype.Controller", + "org.springframework.messaging.handler.annotation.MessageMapping"); + + /** + * What makes a class a way in for a user request: a user-transport adapter package, or the + * framework types an endpoint is built from ({@link #USER_TRANSPORT_FRAMEWORK_PACKAGES}, {@link + * #USER_TRANSPORT_TYPE_NAMES}). */ private static final DescribedPredicate ARE_USER_TRANSPORT_TYPES = JavaClass.Predicates.resideInAnyPackage( "..adapter.inbound.web..", "..adapter.inbound.graphql..", "..adapter.inbound.grpc..", - "..adapter.inbound.websocket..", - "org.springframework.web..", - "org.springframework.graphql..", - "org.springframework.messaging.simp..", - "io.grpc..", - "jakarta.servlet..", - "jakarta.websocket..", - "jakarta.ws.rs..", - "graphql..") + "..adapter.inbound.websocket..") .or( - com.tngtech.archunit.core.domain.properties.HasName.Predicates.name( - "org.springframework.stereotype.Controller")) - .or( - com.tngtech.archunit.core.domain.properties.HasName.Predicates.name( - "org.springframework.messaging.handler.annotation.MessageMapping")) + JavaClass.Predicates.resideInAnyPackage( + withSubpackages(USER_TRANSPORT_FRAMEWORK_PACKAGES))) + .or(namedAnyOf("user-transport annotations", USER_TRANSPORT_TYPE_NAMES)) .as("user-transport types (web, JAX-RS, GraphQL, gRPC, WebSocket/STOMP endpoints)"); /** Spring's configuration stereotype, which {@code @AutoConfiguration} carries as well. */ private static final String CONFIGURATION = "org.springframework.context.annotation.Configuration"; + /** + * The packages, with their subpackages, of the framework types request-handling code is written + * against or registered with. {@link #ARE_REQUEST_HANDLER_TYPES} names them. + */ + static final List REQUEST_HANDLER_PACKAGES = + List.of( + "org.springframework.web.bind.annotation", + "org.springframework.web.servlet.function", + "org.springframework.web.reactive.function.server", + "org.springframework.web.socket.handler", + "org.springframework.graphql.data.method.annotation", + "org.springframework.graphql.server", + "jakarta.servlet.http", + "graphql.schema"); + /** The single request-handler types {@code ARE_REQUEST_HANDLER_TYPES} names beside packages. */ - private static final Set REQUEST_HANDLER_TYPE_NAMES = + static final Set REQUEST_HANDLER_TYPE_NAMES = Set.of( "org.springframework.stereotype.Controller", "org.springframework.messaging.handler.annotation.MessageMapping", @@ -519,74 +546,134 @@ class ApplicationBoundaryArchitectureTest { "io.grpc.stub.StreamObserver"); /** - * The framework types request-handling code is written against: an annotated controller, a - * functional route or handler function, a servlet, filter or handler interceptor, a WebSocket - * handler, a GraphQL data fetcher, runtime wiring or request interceptor, a gRPC service, call - * handler or server interceptor. A configuration names one only when request-handling code is in - * it — a route or data fetcher written as a lambda compiles into a method of the configuration - * itself — and then the configuration is an endpoint (review 2026-11-05 RR6-01-01). The types a - * configuration names to set a transport up — {@code WebMvcConfigurer}, {@code CorsRegistry}, the - * controller beans it builds — are not here (RR4-01-02). + * The framework types request-handling code is written against or registered with: an annotated + * controller, a functional route or handler function, a servlet, filter or handler interceptor, a + * WebSocket handler, a GraphQL data fetcher, runtime wiring or request interceptor, a gRPC + * service, call handler or server interceptor. A configuration that names one holds or registers + * request-handling code, and then the configuration is an endpoint: a route or data fetcher + * written as a lambda compiles into a method of the configuration itself (review 2026-11-05 + * RR6-01-01), and a route registered by method reference names the same route builder although + * its handling code is in another class (review 2026-11-06 RR7-01-02). Class dependencies cannot + * tell that registration from handling code, so routes are registered in a configuration apart + * from the one that builds a system caller. The types a configuration names to set a transport up + * — {@link #ARE_TRANSPORT_SETUP_TYPES}, the controller beans it builds — do not count + * (RR4-01-02). * - *

Like the type list above, this is a list: a request-handler type missing from it is not - * recognised in a configuration (manual 07 「규칙이 못 보는 길」). + *

Only a configuration itself is read with this list; a class nested in one is read with the + * wider user-transport list (RR7-01-01). Like that list, this one is a list: a request-handler + * type missing from it is not recognised in a configuration (manual 07 「규칙이 못 보는 길」). Every entry + * is a user-transport type too, so an endpoint moved from a configuration into a class nested in + * it is still caught ({@code UserTransportTypeListsTest}). */ private static final DescribedPredicate ARE_REQUEST_HANDLER_TYPES = - JavaClass.Predicates.resideInAnyPackage( - "org.springframework.web.bind.annotation..", - "org.springframework.web.servlet.function..", - "org.springframework.web.reactive.function.server..", - "org.springframework.web.socket.handler..", - "org.springframework.graphql.data.method.annotation..", - "org.springframework.graphql.server..", - "jakarta.servlet.http..", - "graphql.schema..") - .or( - DescribedPredicate.describe( - "request-handler interfaces", - type -> REQUEST_HANDLER_TYPE_NAMES.contains(type.getName()))) + JavaClass.Predicates.resideInAnyPackage(withSubpackages(REQUEST_HANDLER_PACKAGES)) + .or(namedAnyOf("request-handler interfaces", REQUEST_HANDLER_TYPE_NAMES)) .as("request-handler types (controllers, routes, servlets, filters, interceptors, ...)"); + /** + * The packages, with their subpackages, of the types a configuration names to set a transport up + * rather than to handle a request: Spring MVC's, WebFlux's and WebSocket's configurers and + * registries, the STOMP broker registry, and CORS settings. Their code runs while the application + * starts. A class that implements one of them for a request — a CORS source, a CORS processor — + * takes the request as a parameter, and that type counts. + */ + static final List TRANSPORT_SETUP_PACKAGES = + List.of( + "org.springframework.web.servlet.config.annotation", + "org.springframework.web.reactive.config", + "org.springframework.web.socket.config.annotation", + "org.springframework.messaging.simp.config", + "org.springframework.web.cors"); + + /** + * The single setup types: the HTTP method values a CORS mapping lists, which live among the + * controller annotations (review 2026-11-06 RR7-01-02). + */ + static final Set TRANSPORT_SETUP_TYPE_NAMES = + Set.of("org.springframework.web.bind.annotation.RequestMethod"); + + /** + * The types a configuration names to set a transport up: they make neither a configuration nor a + * class nested in one a way in. An anonymous {@code WebMvcConfigurer} that reads the + * configuration's field is part of the configuration (review 2026-11-05 RR6-01-02). + * + *

A setup type missing from here fails the build: the configurer naming it is read as a + * transport. A request-handler type added here would hide an endpoint instead, so no entry may + * cover one ({@code UserTransportTypeListsTest}). + */ + private static final DescribedPredicate ARE_TRANSPORT_SETUP_TYPES = + JavaClass.Predicates.resideInAnyPackage(withSubpackages(TRANSPORT_SETUP_PACKAGES)) + .or(namedAnyOf("transport setup values", TRANSPORT_SETUP_TYPE_NAMES)) + .as("transport setup types (configurers, registries, CORS settings)"); + + /** What makes a configuration a way in: a request-handler type that is no setup type. */ + private static final DescribedPredicate MAKE_A_CONFIGURATION_A_WAY_IN = + ARE_REQUEST_HANDLER_TYPES.and(DescribedPredicate.not(ARE_TRANSPORT_SETUP_TYPES)); + + /** What makes a class nested in a configuration a way in: any user-transport type but setup. */ + private static final DescribedPredicate MAKE_A_NESTED_CLASS_A_WAY_IN = + ARE_USER_TRANSPORT_TYPES.and(DescribedPredicate.not(ARE_TRANSPORT_SETUP_TYPES)); + /** * A class a user request comes in through: it lives in a user-transport package; or it is a - * configuration, or nested in one, that is built from a request-handler type; or it is any other - * class built from a user-transport type. + * configuration built from a request-handler type; or it is nested in a configuration and built + * from a user-transport type other than a setup type; or it is any other class built from a + * user-transport type. * *

A configuration is the composition root, and naming a web type does not make it a way in: a * feature's configuration registers its message handler beside a {@code WebMvcConfigurer} or its * controller without any request passing through it (review 2026-11-04 RR4-01-02). A controller * it builds is checked itself, by its package or its own transport types. What does make it a way - * in is request-handling code written in it: a functional route or a data fetcher is a lambda, - * compiled into the configuration's own method, so the configuration that holds one is the - * endpoint (review 2026-11-05 RR6-01-01). A class nested in a configuration — an anonymous {@code - * WebMvcConfigurer} reading the configuration's field — is read the same way, request handlers - * nested there included (RR6-01-02). + * in is request-handling code it holds or registers: a functional route or a data fetcher written + * as a lambda compiles into the configuration's own method (review 2026-11-05 RR6-01-01), and a + * route registered by method reference names the route builder (review 2026-11-06 RR7-01-02). + * + *

A class nested in a configuration is read like any other class, with the full user-transport + * list, so an endpoint of any transport library kept there is caught — a JAX-RS resource or an + * annotated JSR-356 endpoint as much as a handler function — and so is one that runs the job + * through the configuration that holds it (review 2026-11-06 RR7-01-01). Only setup types are + * left out: an anonymous {@code WebMvcConfigurer} reading the configuration's field is part of + * the configuration (RR6-01-02). */ private static final DescribedPredicate ARE_USER_TRANSPORTS = new DescribedPredicate<>( - "are user transports (in a user-transport package, a configuration with request-handling" - + " code, or another class built from a user-transport type)") { + "are user transports (in a user-transport package, a configuration that holds or registers" + + " request-handling code, or another class built from a user-transport type)") { @Override public boolean test(JavaClass candidate) { if (ARE_USER_TRANSPORT_TYPES.test(candidate)) { return true; } - DescribedPredicate wayIn = - isOrIsNestedInAConfiguration(candidate) - ? ARE_REQUEST_HANDLER_TYPES - : ARE_USER_TRANSPORT_TYPES; + DescribedPredicate wayIn = waysInFor(candidate); return candidate.getDirectDependenciesFromSelf().stream() .anyMatch(dependency -> wayIn.test(dependency.getTargetClass())); } }; - private static boolean isOrIsNestedInAConfiguration(JavaClass candidate) { - for (JavaClass type = candidate; type != null; type = type.getEnclosingClass().orElse(null)) { - if (type.isAnnotatedWith(CONFIGURATION) || type.isMetaAnnotatedWith(CONFIGURATION)) { - return true; + private static DescribedPredicate waysInFor(JavaClass candidate) { + if (isAConfiguration(candidate)) { + return MAKE_A_CONFIGURATION_A_WAY_IN; + } + for (JavaClass type = candidate.getEnclosingClass().orElse(null); + type != null; + type = type.getEnclosingClass().orElse(null)) { + if (isAConfiguration(type)) { + return MAKE_A_NESTED_CLASS_A_WAY_IN; } } - return false; + return ARE_USER_TRANSPORT_TYPES; + } + + private static boolean isAConfiguration(JavaClass type) { + return type.isAnnotatedWith(CONFIGURATION) || type.isMetaAnnotatedWith(CONFIGURATION); + } + + private static String[] withSubpackages(List packages) { + return packages.stream().map(name -> name + "..").toArray(String[]::new); + } + + private static DescribedPredicate namedAnyOf(String description, Set names) { + return DescribedPredicate.describe(description, type -> names.contains(type.getName())); } /** @@ -692,16 +779,17 @@ class ApplicationBoundaryArchitectureTest { * no permission guards (review 2026-11-04 RR3-01-01). Reaching the job's own interface, or any * project type the job extends or implements, counts as reaching the job: that is the type the * endpoint is handed when it injects by interface (RR4-01-01). A configuration may register the - * handler beside web beans (RR4-01-02), but not beside request-handling code of its own, such as - * a functional route (RR6-01-01). + * handler beside web beans (RR4-01-02), but not beside request-handling code it holds or + * registers, such as a functional route, whether written as a lambda (RR6-01-01) or a method + * reference (review 2026-11-06 RR7-01-02). * *

It reads class dependencies, so it sees every typed path, including {@code * ObjectProvider} and {@code getBean(TheJob.class)}: both name the type. It cannot see a * path that names no type the job is handed as — a lookup by bean name or by {@code Object}, or a * configuration that passes a user transport a function wrapping the job ({@code job::run} as a - * {@code Runnable}) — nor request-handling code in a configuration written against a type {@code - * ARE_REQUEST_HANDLER_TYPES} does not list. Manual 07 「시스템이 부르는 쓰기」 lists those paths and what - * holds them. + * {@code Runnable}) — nor request-handling code in a configuration itself written against a type + * {@code ARE_REQUEST_HANDLER_TYPES} does not list. Manual 07 「시스템이 부르는 쓰기」 lists those paths and + * what holds them. */ @ArchTest static final ArchRule USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS = @@ -711,13 +799,16 @@ class ApplicationBoundaryArchitectureTest { .transitivelyDependOnClassesThat(ARE_TYPES_A_SYSTEM_CALLER_IS_HANDED_AS) .as( "USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS: a class a user request comes in " - + "through (a user-transport package; a configuration, or a class nested in one, " - + "with request-handling code such as a functional route or a data fetcher; any " - + "other class built from a web, JAX-RS, GraphQL, gRPC or WebSocket type) does " - + "not reach a @SystemCaller or a " + + "through (a user-transport package; a configuration that holds or registers " + + "request-handling code such as a functional route, a data fetcher or an " + + "interceptor; a class nested in a configuration built from a web, JAX-RS, " + + "GraphQL, gRPC or WebSocket type other than a setup type such as " + + "WebMvcConfigurer; any other class built from one of those types) does not " + + "reach a @SystemCaller or a " + "project type one extends or implements, directly or through other classes — " - + "the system caller runs a @SystemInvoked write with no permission check. A " - + "user-triggered run of the same work is its own use case with " + + "the system caller runs a @SystemInvoked write with no permission check. " + + "Register routes in a configuration apart from the one that builds the system " + + "caller. A user-triggered run of the same work is its own use case with " + "@RequiresPermission (manual 07 「시스템이 부르는 쓰기」)") .allowEmptyShould(true); diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ArchitectureViolationFixtureTest.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ArchitectureViolationFixtureTest.java index 0b82c1e1..aa1b5913 100644 --- a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ArchitectureViolationFixtureTest.java +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ArchitectureViolationFixtureTest.java @@ -13,7 +13,11 @@ import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.S import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.SystemCallerWithNestedValueTypesFixture; import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.web.PingControllerFixture; import dev.caskeleton.bootstrap.architecture.allowed.application.CleanProjectionQueryPort; +import dev.caskeleton.bootstrap.architecture.allowed.configuration.OrderHandlerFixture; +import dev.caskeleton.bootstrap.architecture.allowed.configuration.OrderRoutesConfigurationFixture; import dev.caskeleton.bootstrap.architecture.allowed.configuration.SystemCallerBesideControllerRegistrationFixture; +import dev.caskeleton.bootstrap.architecture.allowed.configuration.SystemCallerBesideCorsMappingFixture; +import dev.caskeleton.bootstrap.architecture.allowed.configuration.SystemCallerBesideCorsSourceFixture; import dev.caskeleton.bootstrap.architecture.allowed.configuration.SystemCallerBesideFieldReadingWebMvcConfigurerFixture; import dev.caskeleton.bootstrap.architecture.allowed.configuration.SystemCallerBesideWebMvcRegistrationFixture; import dev.caskeleton.bootstrap.architecture.fixtures.application.RootWriteTransactionBoundaryUseCase; @@ -44,6 +48,7 @@ import dev.caskeleton.bootstrap.architecture.violations.application.OutboundWith import dev.caskeleton.bootstrap.architecture.violations.application.RawLeakQueryPort; import dev.caskeleton.bootstrap.architecture.violations.application.ReadOnlyRepositoryWriteUseCase; import dev.caskeleton.bootstrap.architecture.violations.application.SystemInvokedFixtureUseCase; +import dev.caskeleton.bootstrap.architecture.violations.configuration.RoutesBesideASystemCallerConfigurationFixture; import dev.caskeleton.bootstrap.architecture.violations.configuration.RunNowHandlerFunctionConfigurationFixture; import dev.caskeleton.bootstrap.architecture.violations.configuration.RunNowRouteConfigurationFixture; import dev.caskeleton.bootstrap.architecture.violations.domain.AnnotatedPublicNoArgValueObjectFixture; @@ -322,9 +327,8 @@ class ArchitectureViolationFixtureTest { "dev.caskeleton.bootstrap.architecture.violations.configuration.graphqljava", "dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging"); - // RR6-01-02: a class nested in a configuration is read as the configuration is — a request - // handler - // nested there is still a transport, a configurer reading the configuration's field is not. + // RR6-01-02: a request handler nested in a configuration is still a transport; a configurer + // reading the configuration's field names only setup types and is not. private static final JavaClasses HANDLER_FUNCTION_NESTED_IN_A_CONFIGURATION_FIXTURE_ONLY = new ClassFileImporter() .importClasses( @@ -345,6 +349,63 @@ class ArchitectureViolationFixtureTest { SystemCallerBesideFieldReadingWebMvcConfigurerFixture.class, SystemCallerHandlerFixture.class)); + // Review 2026-11-06 RR7-01-01: endpoints a configuration keeps nested in it, built from types the + // request-handler list does not name — a JAX-RS resource, one that runs the job through its + // configuration, an annotated JSR-356 endpoint. importPackages, so the compile-only JAX-RS and + // WebSocket types are never linked. + private static final String NESTED_JAXRS_FIXTURES = + "dev.caskeleton.bootstrap.architecture.violations.configuration.jaxrs"; + + private static final JavaClasses JAXRS_RESOURCES_IN_A_CONFIGURATION_FIXTURE_ONLY = + new ClassFileImporter() + .importPackages( + NESTED_JAXRS_FIXTURES, + "dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging"); + + private static final JavaClasses SERVER_ENDPOINT_IN_A_CONFIGURATION_FIXTURE_ONLY = + new ClassFileImporter() + .importPackages( + "dev.caskeleton.bootstrap.architecture.violations.configuration.jsr356", + "dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging"); + + // RR7-01-02: routes registered by method reference make their configuration an endpoint, so the + // configuration that also builds a system caller is caught and the same routes in a configuration + // of their own pass. A CORS setup naming RequestMethod is setup, in the configuration and in its + // configurer alike. + private static final JavaClasses ROUTES_BESIDE_A_SYSTEM_CALLER_FIXTURE_ONLY = + new ClassFileImporter() + .importClasses( + RoutesBesideASystemCallerConfigurationFixture.class, + OrderHandlerFixture.class, + SystemCallerHandlerFixture.class, + SystemInvokedFixtureUseCase.class); + + private static final JavaClasses ROUTES_APART_FROM_A_SYSTEM_CALLER_FIXTURE_ONLY = + new ClassFileImporter() + .importClasses( + OrderRoutesConfigurationFixture.class, + OrderHandlerFixture.class, + SystemCallerHandlerRegistrationFixture.class, + SystemCallerHandlerFixture.class, + SystemInvokedFixtureUseCase.class); + + private static final JavaClasses CORS_SOURCE_BESIDE_A_SYSTEM_CALLER_FIXTURE_ONLY = + new ClassFileImporter() + .importClasses( + SystemCallerBesideCorsSourceFixture.class, + SystemCallerHandlerFixture.class, + SystemInvokedFixtureUseCase.class); + + // The anonymous configurer has no class literal, as above. + private static final JavaClasses CORS_MAPPING_BESIDE_A_SYSTEM_CALLER_FIXTURE_ONLY = + new ClassFileImporter() + .importPackages( + "dev.caskeleton.bootstrap.architecture.allowed.configuration", + "dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging") + .that( + JavaClass.Predicates.belongToAnyOf( + SystemCallerBesideCorsMappingFixture.class, SystemCallerHandlerFixture.class)); + // RR6-01-03: a system caller's nested record, enum and exception, and a system caller that is a // record — none of them a type an endpoint injects it as. private static final JavaClasses SYSTEM_CALLER_WITH_NESTED_VALUE_TYPES_FIXTURE_ONLY = @@ -626,6 +687,112 @@ class ArchitectureViolationFixtureTest { assertThat(result.getFailureReport().getDetails()).isEmpty(); } + @Test + void aJaxRsResourceNestedInAConfigurationThatCallsASystemCallerIsCaught() { + // when + EvaluationResult result = + ApplicationBoundaryArchitectureTest.USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS.evaluate( + JAXRS_RESOURCES_IN_A_CONFIGURATION_FIXTURE_ONLY); + + // then + assertThat(result.getFailureReport().getDetails()) + .anySatisfy( + detail -> + assertThat(detail) + .contains( + "<" + + NESTED_JAXRS_FIXTURES + + ".RunNowResourceConfigurationFixture$RunNowResource>") + .contains(SystemCallerHandlerFixture.class.getName())); + } + + @Test + void aNestedEndpointThatRunsASystemCallerThroughItsConfigurationIsCaught() { + // when + EvaluationResult result = + ApplicationBoundaryArchitectureTest.USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS.evaluate( + JAXRS_RESOURCES_IN_A_CONFIGURATION_FIXTURE_ONLY); + + // then + assertThat(result.getFailureReport().getDetails()) + .anySatisfy( + detail -> + assertThat(detail) + .contains( + "<" + + NESTED_JAXRS_FIXTURES + + ".RunNowThroughTheConfigurationFixture$RunNowResource>") + .contains(SystemCallerHandlerFixture.class.getName())); + } + + @Test + void anAnnotatedWebSocketEndpointNestedInAConfigurationThatCallsASystemCallerIsCaught() { + // when + EvaluationResult result = + ApplicationBoundaryArchitectureTest.USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS.evaluate( + SERVER_ENDPOINT_IN_A_CONFIGURATION_FIXTURE_ONLY); + + // then + assertThat(result.getFailureReport().getDetails()) + .anySatisfy( + detail -> + assertThat(detail) + .contains( + "") + .contains(SystemCallerHandlerFixture.class.getName())); + } + + @Test + void aConfigurationThatRegistersMethodReferenceRoutesBesideASystemCallerIsCaught() { + // when + EvaluationResult result = + ApplicationBoundaryArchitectureTest.USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS.evaluate( + ROUTES_BESIDE_A_SYSTEM_CALLER_FIXTURE_ONLY); + + // then + assertThat(result.getFailureReport().getDetails()) + .anySatisfy( + detail -> + assertThat(detail) + .contains( + "<" + RoutesBesideASystemCallerConfigurationFixture.class.getName() + ">") + .contains(SystemCallerHandlerFixture.class.getName())); + } + + @Test + void routesRegisteredApartFromTheSystemCallersConfigurationPass() { + // when + EvaluationResult result = + ApplicationBoundaryArchitectureTest.USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS.evaluate( + ROUTES_APART_FROM_A_SYSTEM_CALLER_FIXTURE_ONLY); + + // then + assertThat(result.getFailureReport().getDetails()).isEmpty(); + } + + @Test + void aConfigurationNamingRequestMethodForCorsMayRegisterASystemCaller() { + // when + EvaluationResult result = + ApplicationBoundaryArchitectureTest.USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS.evaluate( + CORS_SOURCE_BESIDE_A_SYSTEM_CALLER_FIXTURE_ONLY); + + // then + assertThat(result.getFailureReport().getDetails()).isEmpty(); + } + + @Test + void aCorsConfigurerNestedInAConfigurationMayNameRequestMethodAndReadTheConfigurationsField() { + // when + EvaluationResult result = + ApplicationBoundaryArchitectureTest.USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS.evaluate( + CORS_MAPPING_BESIDE_A_SYSTEM_CALLER_FIXTURE_ONLY); + + // then + assertThat(result.getFailureReport().getDetails()).isEmpty(); + } + @Test void aSystemCallersNestedRecordEnumAndExceptionPassTheSupertypeRule() { // when diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/UserTransportTypeListsTest.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/UserTransportTypeListsTest.java new file mode 100644 index 00000000..766ce6fc --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/UserTransportTypeListsTest.java @@ -0,0 +1,81 @@ +package dev.caskeleton.bootstrap.architecture; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Collection; +import java.util.List; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; + +/** + * The three type lists {@code USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS} reads a class with stay + * in the shape that keeps the rule closed. + * + *

A configuration is read with the request-handler list, a class nested in one with the full + * user-transport list, and both leave out setup types. The two lists drifted apart once: the + * request-handler list named no JAX-RS type, and while nested classes were read with it, a JAX-RS + * resource kept in a configuration passed (review 2026-11-06 RR7-01-01). So every request-handler + * entry has to be a user-transport type too — then moving an endpoint from a configuration into a + * class nested in it cannot hide it — and no setup entry may cover a request-handler type, or it + * would hide that endpoint in both places. + */ +class UserTransportTypeListsTest { + + @Test + void everyRequestHandlerAndSetupEntryIsAUserTransportType() { + // given + List entries = + Stream.>of( + ApplicationBoundaryArchitectureTest.REQUEST_HANDLER_PACKAGES, + ApplicationBoundaryArchitectureTest.REQUEST_HANDLER_TYPE_NAMES, + ApplicationBoundaryArchitectureTest.TRANSPORT_SETUP_PACKAGES, + ApplicationBoundaryArchitectureTest.TRANSPORT_SETUP_TYPE_NAMES) + .flatMap(Collection::stream) + .toList(); + + // when + List outsideTheUserTransportTypes = + entries.stream() + .filter( + entry -> + !ApplicationBoundaryArchitectureTest.USER_TRANSPORT_TYPE_NAMES.contains(entry) + && !isInAnyOf( + entry, + ApplicationBoundaryArchitectureTest.USER_TRANSPORT_FRAMEWORK_PACKAGES)) + .toList(); + + // then + assertThat(outsideTheUserTransportTypes).isEmpty(); + } + + @Test + void noSetupEntryCoversARequestHandlerType() { + // given + List setupPackages = ApplicationBoundaryArchitectureTest.TRANSPORT_SETUP_PACKAGES; + List handlerPackages = ApplicationBoundaryArchitectureTest.REQUEST_HANDLER_PACKAGES; + + // when + List handlerNamesTreatedAsSetup = + ApplicationBoundaryArchitectureTest.REQUEST_HANDLER_TYPE_NAMES.stream() + .filter( + name -> + ApplicationBoundaryArchitectureTest.TRANSPORT_SETUP_TYPE_NAMES.contains(name) + || isInAnyOf(name, setupPackages)) + .toList(); + List overlappingPackages = + Stream.concat( + setupPackages.stream().filter(setup -> isInAnyOf(setup, handlerPackages)), + handlerPackages.stream().filter(handler -> isInAnyOf(handler, setupPackages))) + .toList(); + + // then + assertThat(handlerNamesTreatedAsSetup).isEmpty(); + assertThat(overlappingPackages).isEmpty(); + } + + /** Whether a type or package name is one of the packages or inside one of them. */ + private static boolean isInAnyOf(String name, List packages) { + return packages.stream() + .anyMatch(container -> name.equals(container) || name.startsWith(container + ".")); + } +} diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/OrderHandlerFixture.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/OrderHandlerFixture.java new file mode 100644 index 00000000..e120ae40 --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/OrderHandlerFixture.java @@ -0,0 +1,12 @@ +package dev.caskeleton.bootstrap.architecture.allowed.configuration; + +import org.springframework.web.servlet.function.ServerRequest; +import org.springframework.web.servlet.function.ServerResponse; + +/** A feature's functional-endpoint handler, which reaches no system caller. */ +public final class OrderHandlerFixture { + + public ServerResponse list(ServerRequest request) { + return ServerResponse.ok().build(); + } +} diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/OrderRoutesConfigurationFixture.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/OrderRoutesConfigurationFixture.java new file mode 100644 index 00000000..0297ace6 --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/OrderRoutesConfigurationFixture.java @@ -0,0 +1,21 @@ +package dev.caskeleton.bootstrap.architecture.allowed.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.function.RouterFunction; +import org.springframework.web.servlet.function.RouterFunctions; +import org.springframework.web.servlet.function.ServerResponse; + +/** + * A feature's route registration in a configuration of its own, apart from the configuration that + * builds the feature's message handler ({@code SystemCallerHandlerRegistrationFixture}). This + * configuration is an endpoint, and it reaches no system caller (review 2026-11-06 RR7-01-02). + */ +@Configuration(proxyBeanMethods = false) +public class OrderRoutesConfigurationFixture { + + @Bean + RouterFunction orderRoutes(OrderHandlerFixture orders) { + return RouterFunctions.route().GET("/orders", orders::list).build(); + } +} diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/SystemCallerBesideCorsMappingFixture.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/SystemCallerBesideCorsMappingFixture.java new file mode 100644 index 00000000..2ba2e538 --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/SystemCallerBesideCorsMappingFixture.java @@ -0,0 +1,42 @@ +package dev.caskeleton.bootstrap.architecture.allowed.configuration; + +import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.SystemCallerHandlerFixture; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.servlet.config.annotation.CorsRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +/** + * One feature configuration: a CORS mapping that reads the configuration's own max age, and the + * feature's message handler. The anonymous configurer names only setup types — the configurer, the + * registry and {@code RequestMethod} — so it is part of the configuration, not a way in, although + * it reaches the handler through the field it reads (review 2026-11-06 RR7-01-02). + */ +@Configuration(proxyBeanMethods = false) +public class SystemCallerBesideCorsMappingFixture { + + private final long corsMaxAgeSeconds; + + public SystemCallerBesideCorsMappingFixture(long corsMaxAgeSeconds) { + this.corsMaxAgeSeconds = corsMaxAgeSeconds; + } + + @Bean + WebMvcConfigurer featureCorsMapping() { + return new WebMvcConfigurer() { + @Override + public void addCorsMappings(CorsRegistry registry) { + registry + .addMapping("/features/**") + .allowedMethods(RequestMethod.GET.name(), RequestMethod.HEAD.name()) + .maxAge(corsMaxAgeSeconds); + } + }; + } + + @Bean + SystemCallerHandlerFixture systemCallerHandler() { + return new SystemCallerHandlerFixture(); + } +} diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/SystemCallerBesideCorsSourceFixture.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/SystemCallerBesideCorsSourceFixture.java new file mode 100644 index 00000000..4b15f3f6 --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/SystemCallerBesideCorsSourceFixture.java @@ -0,0 +1,33 @@ +package dev.caskeleton.bootstrap.architecture.allowed.configuration; + +import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.SystemCallerHandlerFixture; +import java.util.List; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.cors.CorsConfiguration; +import org.springframework.web.cors.CorsConfigurationSource; +import org.springframework.web.cors.UrlBasedCorsConfigurationSource; + +/** + * One feature configuration: its CORS source and its message handler. The configuration names + * {@code RequestMethod} for the methods it allows. That enum lives among the controller annotations + * but is a setup value, not request-handling code (review 2026-11-06 RR7-01-02). + */ +@Configuration(proxyBeanMethods = false) +public class SystemCallerBesideCorsSourceFixture { + + @Bean + CorsConfigurationSource featureCorsSource() { + CorsConfiguration cors = new CorsConfiguration(); + cors.setAllowedMethods(List.of(RequestMethod.GET.name(), RequestMethod.HEAD.name())); + UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); + source.registerCorsConfiguration("/features/**", cors); + return source; + } + + @Bean + SystemCallerHandlerFixture systemCallerHandler() { + return new SystemCallerHandlerFixture(); + } +} diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/package-info.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/package-info.java index dd3860fc..1e1a0f07 100644 --- a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/package-info.java +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/package-info.java @@ -1,9 +1,10 @@ /** * "Allowed-as-data" composition for {@code USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS}: a * feature's configuration that registers its message handler beside its web beans — a {@code - * WebMvcConfigurer}, or the feature's controller. A configuration is the composition root, not a - * way a user request comes in, so naming a web type does not make it a user transport (review - * 2026-11-04 RR4-01-02). Manual 09 「소비」 step 4 registers the handler in "this leaf's configuration - * class", which is where both kinds of bean meet. + * WebMvcConfigurer}, a CORS setup, or the feature's controller. A configuration is the composition + * root, not a way a user request comes in, so naming a web type does not make it a user transport + * (review 2026-11-04 RR4-01-02); registering routes does, so the feature's routes sit in a + * configuration of their own (review 2026-11-06 RR7-01-02). Manual 09 「소비」 step 4 registers the + * handler in "this leaf's configuration class", which is where both kinds of bean meet. */ package dev.caskeleton.bootstrap.architecture.allowed.configuration; diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/RoutesBesideASystemCallerConfigurationFixture.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/RoutesBesideASystemCallerConfigurationFixture.java new file mode 100644 index 00000000..4b7a6dbe --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/RoutesBesideASystemCallerConfigurationFixture.java @@ -0,0 +1,32 @@ +package dev.caskeleton.bootstrap.architecture.violations.configuration; + +import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.SystemCallerHandlerFixture; +import dev.caskeleton.bootstrap.architecture.allowed.configuration.OrderHandlerFixture; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.function.RouterFunction; +import org.springframework.web.servlet.function.RouterFunctions; +import org.springframework.web.servlet.function.ServerResponse; + +/** + * Negative fixture for {@code USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS}: one feature + * configuration registers its functional routes and builds its message handler. The handling code + * is in {@link OrderHandlerFixture}, referenced by method, so no request runs through this class. + * Registering the route still names the route builder, a request-handler type, and class + * dependencies cannot tell the registration from handling code: the configuration is read as an + * endpoint that reaches the handler. The routes go in a configuration of their own ({@code + * OrderRoutesConfigurationFixture}) (review 2026-11-06 RR7-01-02). + */ +@Configuration(proxyBeanMethods = false) +public class RoutesBesideASystemCallerConfigurationFixture { + + @Bean + RouterFunction orderRoutes(OrderHandlerFixture orders) { + return RouterFunctions.route().GET("/orders", orders::list).build(); + } + + @Bean + SystemCallerHandlerFixture systemCallerHandler() { + return new SystemCallerHandlerFixture(); + } +} diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/RunNowHandlerFunctionConfigurationFixture.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/RunNowHandlerFunctionConfigurationFixture.java index 46b43112..05036900 100644 --- a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/RunNowHandlerFunctionConfigurationFixture.java +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/RunNowHandlerFunctionConfigurationFixture.java @@ -10,8 +10,9 @@ import org.springframework.web.servlet.function.ServerResponse; /** * Negative fixture for {@code USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS}: the configuration * itself names no request-handler type, but the handler function it registers is a class nested in - * it. A class nested in a configuration is read as the configuration is, request handlers included, - * so the nested endpoint is still a user transport (review 2026-11-05 RR6-01-02). + * it. A class nested in a configuration is a user transport when it is built from a user-transport + * type other than a setup type, so the nested endpoint is caught (review 2026-11-05 RR6-01-02, + * 2026-11-06 RR7-01-01). */ @Configuration(proxyBeanMethods = false) public class RunNowHandlerFunctionConfigurationFixture { diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/jaxrs/RunNowResourceConfigurationFixture.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/jaxrs/RunNowResourceConfigurationFixture.java new file mode 100644 index 00000000..609d6c2f --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/jaxrs/RunNowResourceConfigurationFixture.java @@ -0,0 +1,33 @@ +package dev.caskeleton.bootstrap.architecture.violations.configuration.jaxrs; + +import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.SystemCallerHandlerFixture; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.Path; +import org.springframework.context.annotation.Configuration; + +/** + * Negative fixture for {@code USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS}: a JAX-RS "run now" + * resource kept in the feature configuration. The request-handler list a configuration is read with + * names no JAX-RS type; a class nested in a configuration is read with the full user-transport + * list, so the resource is still a transport (review 2026-11-06 RR7-01-01). Loaded with {@code + * importPackages}: {@code jakarta.ws.rs-api} is compile-only here, so JUnit must never link it. + */ +@Configuration(proxyBeanMethods = false) +public class RunNowResourceConfigurationFixture { + + /** The resource, kept beside the configuration. */ + @Path("/admin/nightly/run-now") + public static final class RunNowResource { + + private final SystemCallerHandlerFixture handler; + + public RunNowResource(SystemCallerHandlerFixture handler) { + this.handler = handler; + } + + @POST + public void runNow() { + handler.handle(); + } + } +} diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/jaxrs/RunNowThroughTheConfigurationFixture.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/jaxrs/RunNowThroughTheConfigurationFixture.java new file mode 100644 index 00000000..6aa24dd7 --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/jaxrs/RunNowThroughTheConfigurationFixture.java @@ -0,0 +1,34 @@ +package dev.caskeleton.bootstrap.architecture.violations.configuration.jaxrs; + +import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.SystemCallerHandlerFixture; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.Path; +import org.springframework.context.annotation.Configuration; + +/** + * Negative fixture for {@code USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS}: a "run now" resource + * nested in the configuration that holds the system caller. The resource never names the caller; it + * asks the configuration to run it. The path through the enclosing configuration is followed like + * any other, so the resource is caught — which is why a configurer reading the configuration's + * field is let through by its setup types, not by skipping that path (review 2026-11-06 RR7-01-01). + * Loaded with {@code importPackages}: {@code jakarta.ws.rs-api} is compile-only here. + */ +@Configuration(proxyBeanMethods = false) +public class RunNowThroughTheConfigurationFixture { + + private final SystemCallerHandlerFixture handler = new SystemCallerHandlerFixture(); + + void runNightly() { + handler.handle(); + } + + /** The resource, an inner class that runs the job through its configuration. */ + @Path("/admin/nightly/run-now") + public final class RunNowResource { + + @POST + public void runNow() { + runNightly(); + } + } +} diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/jsr356/RunNowEndpointConfigurationFixture.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/jsr356/RunNowEndpointConfigurationFixture.java new file mode 100644 index 00000000..219b2b64 --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/jsr356/RunNowEndpointConfigurationFixture.java @@ -0,0 +1,29 @@ +package dev.caskeleton.bootstrap.architecture.violations.configuration.jsr356; + +import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.SystemCallerHandlerFixture; +import jakarta.websocket.OnMessage; +import jakarta.websocket.server.ServerEndpoint; +import org.springframework.context.annotation.Configuration; + +/** + * Negative fixture for {@code USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS}: an annotated JSR-356 + * "run now" endpoint kept in the feature configuration. Like the JAX-RS resource beside it, it is + * built from types only the full user-transport list names (review 2026-11-06 RR7-01-01). Loaded + * with {@code importPackages}: {@code jakarta.websocket-api} is compile-only here. + */ +@Configuration(proxyBeanMethods = false) +public class RunNowEndpointConfigurationFixture { + + /** The endpoint, kept beside the configuration. */ + @ServerEndpoint("/admin/nightly/run-now") + public static final class RunNowEndpoint { + + private final SystemCallerHandlerFixture handler = new SystemCallerHandlerFixture(); + + @OnMessage + public String onMessage(String message) { + handler.handle(); + return message; + } + } +} From 6cd5e925c13337031b5bd19dbf84b79b170756b9 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Sat, 7 Nov 2026 01:10:30 +0900 Subject: [PATCH 27/71] =?UTF-8?q?fix(strict-lane)!:=20paths=20=ED=95=84?= =?UTF-8?q?=ED=84=B0=20trigger=EB=A1=9C=EB=A7=8C=20=EB=8F=84=EB=8A=94=20wo?= =?UTF-8?q?rkflow=EB=8A=94=20=EB=8B=A8=EA=B3=84=20=EC=8B=A4=ED=96=89?= =?UTF-8?q?=EC=9C=BC=EB=A1=9C=20=EC=84=B8=EC=A7=80=20=EC=95=8A=EB=8A=94?= =?UTF-8?q?=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: verifyStrictLaneStages의 workflow 판독기는 trigger 이름과 types만 본다. paths·paths-ignore 필터가 붙은 pull_request·push로만 시작하는 workflow의 `./gradlew :ci`도 실행으로 센다. 그런 workflow는 필터 밖 변경에서 돌지 않는데, 실패 메시지와 업그레이드 안내 B-36은 "매 push·pull request·schedule에 도는 workflow에서 단계를 돌리라"고 약속한다(리뷰 RR7-05-01). 고른 방법: 소유자 결정(2026-11-06, docs/work/reference/decisions.md "경로 필터 workflow와 단계 검사")대로, change trigger에 paths나 paths-ignore가 있으면 그 trigger로는 세지 않는다. 필터 없는 change trigger가 하나라도 있으면 지금처럼 센다. 세지 않는 이유는 "돌지 않을 수 있음" 칸이고, 메시지가 어느 trigger의 어떤 필터인지 적는다 (예: "push (paths-ignore)"). trigger마다 types와 경로 필터를 함께 읽도록 Trigger 레코드를 두었다. 실패 메시지(NOT_COUNTED), AGENTS.md, src/README.md, build-logic/README.md, 업그레이드 안내 B-36을 같은 규칙으로 고쳤다. 버린 대안: 동작은 두고 메시지·B-36의 약속만 고친다 — 소유자가 위 안을 골랐다. branches·tags 필터까지 판정한다 — 결정 범위 밖이라 읽지 않고, Javadoc과 문서에 읽지 않는다고 적었다. 위험·한계: 파생 서비스가 단계 명령을 paths 필터 workflow에만 두었으면 이제 verifyStrictLaneStages --dry-run이 실패한다. 이 repo는 단계 명령이 필터 없는 workflow에 있어 두 빌드 모두 판정이 그대로다. tags와 paths가 함께 있는 push(GitHub은 태그 push에 paths를 보지 않음)도 세지 않는다 — 거짓 실패 쪽이다. 실제 GitHub의 필터 해석은 실행해 보지 않았다. 검증(desktop, 로그 ~/r8-f5-logs/): - RED: 기준 73d39212에 테스트만 얹음. WorkflowGradleInvocationsTest 44건 중 1건 실패 — 필터 workflow 셋 모두 uncountedReason=null (red-rr7-05-01.log, .xml) - GREEN: 같은 테스트 rc=0 (green-rr7-05-01.log) - -p build-logic check javadoc, :verifyStrictLaneStages --dry-run, -p optional-platforms :verifyStrictLaneStages --dry-run, :ci :verifyDependencyLocks rc=0 (summary.txt) Refs: docs/reviews/2026-11-03-rereview/round7/05-build-logic-workflow.md RR7-05-01 BREAKING CHANGE: change trigger가 모두 paths·paths-ignore 필터를 단 workflow에서만 단계(:ci 등)를 부르면 verifyStrictLaneStages --dry-run이 실패한다. 단계 명령을 필터 없는 push·pull_request·schedule workflow로 옮긴다(docs/upgrade/2026-11-maturity-review.md B-36). --- AGENTS.md | 6 +- docs/upgrade/2026-11-maturity-review.md | 4 +- src/README.md | 2 +- src/build-logic/README.md | 2 +- .../strictlane/StrictLaneStagesPlugin.java | 9 +- .../strictlane/WorkflowGradleInvocations.java | 116 +++++++++++++----- .../WorkflowGradleInvocationsTest.java | 81 ++++++++++++ 7 files changed, 177 insertions(+), 43 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 58cd2730..8565f7d2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -98,8 +98,10 @@ root `CLAUDE.md`는 작업을 시작할 때 읽는 지도이고, 이 목록을 `&&` 목록의 뒤쪽, `if`·`while`·`for`·`case`·함수 본문 안, 최상위 `exit`·`exec`·`set -n` 뒤, 조건부이거나 부른 함수 안의 `exit 0`(인자 없는 `exit`, 값을 모르는 `exit` 포함)·`exec`·`set -n` 뒤, 상태 함수(`always()`·`success()`·`!cancelled()`)가 아닌 `if:` 아래, 요청으로만 - 시작하는 workflow(`workflow_dispatch`·`repository_dispatch`·`issue_comment` 등), 세는 job이 부르지 않는 - `workflow_call` 재사용 workflow, 조건부이거나 `continue-on-error`인 job을 `needs`로 기다리는 job. + 시작하는 workflow(`workflow_dispatch`·`repository_dispatch`·`issue_comment` 등), `paths`·`paths-ignore` + 필터가 붙은 change trigger로만 시작하는 workflow(그 경로 밖 변경에는 돌지 않는다), 세는 job이 + 부르지 않는 `workflow_call` 재사용 workflow, 조건부이거나 `continue-on-error`인 job을 `needs`로 기다리는 + job. (3) 실패하면 단계도 실패하지만 검사가 읽지 않는다: `|| exit 1`, `{ }`·`( )`·`$( )`·`bash -c` 안, 다른 명령의 인자인 `gradlew`, 따라갈 수 없는 `cd`(`cd "$VAR"`·`cd -`·`pushd`·조건부·서브셸 등) 뒤, `bash`·`sh`가 아닌 `shell:`, Windows일 수 있는 runner의 기본 셸(`pwsh`). 실패 메시지는 명령마다 이유를 diff --git a/docs/upgrade/2026-11-maturity-review.md b/docs/upgrade/2026-11-maturity-review.md index 7a0f1509..be387166 100644 --- a/docs/upgrade/2026-11-maturity-review.md +++ b/docs/upgrade/2026-11-maturity-review.md @@ -4,7 +4,7 @@ - 커밋: `34565130` High·P1 19건 · `1400dc15` 남은 발견·매뉴얼·생성 명령 · `5786126c` 남은 항목과 합친 뒤 결함 · `7ef8d0b4` 재리뷰 기록 · `bbe944bd` 재리뷰 결함 · `ecc74b7d` 2차 재리뷰 기록·이 안내 · `1885bf8d` 2차 재리뷰 결함 · `339cf8fd` 3차 확인 리뷰 기록 · `f40c03c6` 3차 확인 리뷰 Minor · `c2e55510` 마지막 확인 리뷰 기록 · - `2678955c` 테스트 코드 정적 분석(B-40) · `70fb80bf` 소유자가 다시 정한 기본값 3가지(늦은 멱등 완료 기록, `failure-retention` 기동 검사, workflow `cd`) · B4 성능 lane 단언 상시화(2026-11-06, B-43) — `docs(...)` 커밋은 문서만 바꾼다 + `2678955c` 테스트 코드 정적 분석(B-40) · `70fb80bf` 소유자가 다시 정한 기본값 3가지(늦은 멱등 완료 기록, `failure-retention` 기동 검사, workflow `cd`) · B4 성능 lane 단언 상시화(2026-11-06, B-43) · `paths` 필터 trigger를 단계 실행으로 세지 않음(2026-11-06 소유자 결정, B-36) — `docs(...)` 커밋은 문서만 바꾼다 - 근거 문서: `docs/reviews/2026-11-01-maturity-review/README.md` 13~16절, `docs/reviews/2026-11-03-rereview/README.md` 4·6·8~13절, 각 커밋의 `BREAKING CHANGE:` 꼬리말 - 아래 표의 각 줄은 위 범위의 diff와 코드로 확인했다. 확인하지 못한 것은 그 자리에 "확인 못 함"으로 적었고 9절에 @@ -107,7 +107,7 @@ |---|---|---|---|---| | B-34 | 템플릿 패키지 규칙(ArchUnit): `FEATURE_PACKAGES_DO_NOT_REUSE_TEMPLATE_PACKAGE_NAMES`, `TEMPLATE_PACKAGES_DO_NOT_DEPEND_ON_FEATURE_PACKAGES`. 템플릿 이름: application `usecase command query capability transaction security tenant observability secret messaging outbox idempotency operation lease lock cache realtime notification fileserver objectstorage`, domain `identifier stereotype` | 기능 패키지 이름이 이 목록과 겹치거나(예: `domain.lock`), 업무 코드를 템플릿 패키지(예: `application.usecase.*`)에 두고 기능 패키지를 import하면 `:app-bootstrap:architectureTest` 실패 | 기능 패키지 이름을 바꾸고, 업무 코드를 `dev.caskeleton.application.`로 옮긴다. 규칙 정본은 `src/application-core/CLAUDE.md` "Package ownership" | `5786126c`, r9 · `src/app-bootstrap/src/test/.../TemplatePackageOwnership.java`(표와 대조: `TemplatePackageOwnershipDocumentTest`) | | B-35 | JPA 규칙: 양방향 연관은 한쪽에서만 매핑(`mappedBy`), notification·fileserver 저장소 엔티티는 그 leaf 안에서만, `@Version` 엔티티의 bulk update는 version을 올려야 함 | 위반 엔티티·쿼리가 있으면 architectureTest 실패 | 매핑·쿼리를 고친다 | `34565130`, `1400dc15`, `bbe944bd` · `src/app-bootstrap/src/architectureTest/.../JpaProductionArchitectureTest.java` | -| B-36 | 빌드 검사 강화: `modules.json`에 없는 `build.gradle`이 있으면 `verifyCleanArchitectureDependencies` 실패. `verifyStrictLaneStages --dry-run`은 모든 strict lane이 workflow가 실행하는 단계(`:ci` `:sample-portfolio:check` `:mainCheck` `:integrationCheck` `:performanceCheck` `:releaseCheck`)에 속해야 하고 `.github/workflows`를 읽는다. 명령의 빌드는 `working-directory`(단계·job·workflow `defaults`)에서 시작해 같은 `run:` 셸이 그 앞에서 실행한 `cd <상대 경로>`(`cd src && ./gradlew …`, `cd src; ./gradlew …`, 앞 줄의 `cd src`)를 따라간 뒤 `-p`를 붙인 디렉터리로 정하고(`70fb80bf`(2026-11-04 소유자 결정)), `workflow_dispatch`로만 시작하는 workflow의 명령은 세지 않으며, 축약한 `-x`도 Gradle처럼 맞춰 본다(RR2-04-04). 붙여 쓴 `-x`·`-p

`도 Gradle처럼 읽는다(RR3-04-02). `run:` 스크립트를 bash 문법으로 읽고(heredoc·여러 줄 문자열·함수 본문 안의 `cd`는 따라가지 않음), 세지 않는 명령은 이유를 셋으로 나눠 적는다(r10). (1) 실패해도 단계가 실패하지 않을 수 있음: `\|\| exit <0 아닌 값>` 밖의 `\|\|`(`\|\| true` 등), pipefail 없는 파이프 왼쪽, `!`, `&`, `if`·`while` 조건, 스크립트 마지막이 아닌 `&&` 목록의 앞쪽, `set +e` 뒤, `exit 0` 하는 `EXIT`·`ERR` trap 뒤. (2) 돌지 않을 수 있음: `\|\|` 뒤, 마지막이 아닌 `&&` 목록의 뒤쪽, `if`·`while`·`for`·`case`·함수 본문 안, 최상위 `exit`·`exec <명령>`·`set -n` 뒤, 조건부이거나 부른 함수 안의 `exit 0`·인자 없는 `exit`·값을 모르는 `exit`·`exec`·`set -n` 뒤, 요청으로만 시작하는 workflow(`workflow_dispatch`·`repository_dispatch`·`issue_comment`·`types: [labeled]`인 `pull_request`·`workflow_run` 등; `push`·`pull_request`·`pull_request_target`·`merge_group`·`schedule`·`release`는 센다), 세는 job이 `uses: ./.github/workflows/<파일>`로 부르지 않는 `workflow_call` 재사용 workflow, 조건부이거나 `continue-on-error`인 job을 `needs`로 기다리는 job(자기 `if:`가 `always()`·`!cancelled()`면 센다). (3) 실패하면 단계도 실패하지만 검사가 읽지 않음: `\|\| exit 1`·`\|\| { …; exit 1; }`, `{ }`·`( )`·`$( )`·`bash -c` 안, 다른 명령의 인자인 `gradlew`(`timeout 60 ./gradlew`), `bash`·`sh`가 아닌 `shell:`, `shell:` 없이 Windows일 수 있는 runner(Windows 라벨, `${{ matrix.os }}` 같은 식, `linux`·`macos` 라벨 없는 self-hosted)에서 도는 단계 — 기본 셸이 `pwsh`다(Linux·macOS runner의 기본은 `bash -e`, `container:` job은 `sh -e`이고 둘은 같게 읽는다). Gradle이 작업을 돌리지 않는 명령(`--dry-run`·`-m`·`-v`·`--version`·`-h`·`-?`·`--help`·`--status`·`--stop`·`--foreground`, 묶음 `-qm`·`-qv` 포함)과 Gradle이 거부하는 짧은 옵션 묶음(`-mx`)·값을 받지 않는 옵션에 붙인 값(`-m=yes`)도 세지 않는다. 판독기의 Gradle 옵션 표는 `GradleCommandLineTest`가 build-logic을 돌리는 Gradle의 `--help`와 대조하므로, Gradle을 올려 옵션이 늘면(9.2의 `--task-graph`) 그 테스트가 실패한다. 단계를 부르지만 세지 않은 명령은 다른 빌드로 읽힌 것까지 실패 메시지에 이유와 함께 적는다(r9). `verifyEnvKeys`: lane 계약 json의 `APP_` 밖 키는 `SPRING_`·`MANAGEMENT_`·`SERVER_`이거나 `secret://…/`가 가리키는 변수여야 하고, 레지스트리 `property:` 행은 그 property가 설정 metadata에 있어야 읽히는 것으로 친다(`@ConditionalOnProperty`로만 읽는 스위치는 `META-INF/additional-spring-configuration-metadata.json`에 선언, RR2-04-05). SpotBugs 신뢰도 HIGH → MEDIUM | 등록 안 한 leaf, 단계에 안 걸린 자기 lane, 자기 코드의 MEDIUM 발견이 `ci`·`qualityCheck`를 막는다. `working-directory: src`도 `cd src`도 없이 `./gradlew`를 부르는 자기 workflow 단계는 실행으로 세지 않는다. 확실히 따라갈 수 없는 디렉터리 이동(`cd "$VAR"`, `cd -`, `cd ~`, 절대 경로, `pushd`, `if`/`for`/`case`·`{ }`·서브셸 안의 `cd`, `||`·`|`로 이은 `cd`, 다른 명령과 `&&`로 묶인 `cd` 다음 줄) 뒤의 명령도 세지 않고, 실패 메시지에 그 명령과 이유를 적는다. 단계를 `./gradlew ci \| tee log`(기본 셸), `./gradlew ci \|\| true`, `./gradlew ci \|\| exit 1`, `if ./gradlew ci; then` 같은 모양으로만 부르거나, 조건부 `exit 0` 뒤, `-v`·`--help`를 붙여, 요청형 trigger·호출되지 않는 `workflow_call` workflow·조건부 job을 `needs`로 기다리는 job·`shell:` 없는 Windows runner에서만 부르는 자기 workflow도 실패한다 | leaf를 등록하거나 지운다. 자기 lane은 단계에 건다. 단계를 부르는 workflow 명령에 `working-directory`를 두거나 같은 셸에서 `cd <상대 경로>`로 옮긴 뒤 부른다. 단계 명령은 혼자 한 줄로 두고, 로그를 파이프로 남기려면 `shell: bash`나 앞 줄 `set -o pipefail`을 둔다. Windows runner에서는 `shell: bash`를 둔다. 단계는 매 push·pull request·schedule에 도는 workflow와 job에서, 재사용 workflow라면 그런 job이 조건 없이 부르게 한다. Gradle을 올려 `GradleCommandLineTest`가 실패하면 새 옵션을 값 옵션·플래그·작업 없이 끝나는 옵션 중 하나로 판독기 표에 넣는다. SpotBugs 발견은 고치거나 이유를 단 제외로 | `1400dc15`, `34565130`, `bbe944bd`, `5786126c`, `70fb80bf`(2026-11-04 소유자 결정), r9, r10(RR6-04-01~06) · `src/build-logic/.../ModuleRegistry.java`, `.../strictlane/StrictLaneStagesPlugin.java`, `.../strictlane/WorkflowGradleInvocations.java`, `.../strictlane/ShellScript.java`, `.../strictlane/GradleCommandLineTest.java`(test), `.../quality/QualityConventionsPlugin.java`, `src/build.gradle` | +| B-36 | 빌드 검사 강화: `modules.json`에 없는 `build.gradle`이 있으면 `verifyCleanArchitectureDependencies` 실패. `verifyStrictLaneStages --dry-run`은 모든 strict lane이 workflow가 실행하는 단계(`:ci` `:sample-portfolio:check` `:mainCheck` `:integrationCheck` `:performanceCheck` `:releaseCheck`)에 속해야 하고 `.github/workflows`를 읽는다. 명령의 빌드는 `working-directory`(단계·job·workflow `defaults`)에서 시작해 같은 `run:` 셸이 그 앞에서 실행한 `cd <상대 경로>`(`cd src && ./gradlew …`, `cd src; ./gradlew …`, 앞 줄의 `cd src`)를 따라간 뒤 `-p`를 붙인 디렉터리로 정하고(`70fb80bf`(2026-11-04 소유자 결정)), `workflow_dispatch`로만 시작하는 workflow의 명령은 세지 않으며, 축약한 `-x`도 Gradle처럼 맞춰 본다(RR2-04-04). 붙여 쓴 `-x`·`-p`도 Gradle처럼 읽는다(RR3-04-02). `run:` 스크립트를 bash 문법으로 읽고(heredoc·여러 줄 문자열·함수 본문 안의 `cd`는 따라가지 않음), 세지 않는 명령은 이유를 셋으로 나눠 적는다(r10). (1) 실패해도 단계가 실패하지 않을 수 있음: `\|\| exit <0 아닌 값>` 밖의 `\|\|`(`\|\| true` 등), pipefail 없는 파이프 왼쪽, `!`, `&`, `if`·`while` 조건, 스크립트 마지막이 아닌 `&&` 목록의 앞쪽, `set +e` 뒤, `exit 0` 하는 `EXIT`·`ERR` trap 뒤. (2) 돌지 않을 수 있음: `\|\|` 뒤, 마지막이 아닌 `&&` 목록의 뒤쪽, `if`·`while`·`for`·`case`·함수 본문 안, 최상위 `exit`·`exec <명령>`·`set -n` 뒤, 조건부이거나 부른 함수 안의 `exit 0`·인자 없는 `exit`·값을 모르는 `exit`·`exec`·`set -n` 뒤, 요청으로만 시작하는 workflow(`workflow_dispatch`·`repository_dispatch`·`issue_comment`·`types: [labeled]`인 `pull_request`·`workflow_run` 등; `push`·`pull_request`·`pull_request_target`·`merge_group`·`schedule`·`release`는 센다), change trigger가 모두 `paths`·`paths-ignore` 필터를 단 workflow(그 경로 밖 변경에는 돌지 않는다, 2026-11-06 소유자 결정. `branches`·`tags` 필터는 보지 않는다), 세는 job이 `uses: ./.github/workflows/<파일>`로 부르지 않는 `workflow_call` 재사용 workflow, 조건부이거나 `continue-on-error`인 job을 `needs`로 기다리는 job(자기 `if:`가 `always()`·`!cancelled()`면 센다). (3) 실패하면 단계도 실패하지만 검사가 읽지 않음: `\|\| exit 1`·`\|\| { …; exit 1; }`, `{ }`·`( )`·`$( )`·`bash -c` 안, 다른 명령의 인자인 `gradlew`(`timeout 60 ./gradlew`), `bash`·`sh`가 아닌 `shell:`, `shell:` 없이 Windows일 수 있는 runner(Windows 라벨, `${{ matrix.os }}` 같은 식, `linux`·`macos` 라벨 없는 self-hosted)에서 도는 단계 — 기본 셸이 `pwsh`다(Linux·macOS runner의 기본은 `bash -e`, `container:` job은 `sh -e`이고 둘은 같게 읽는다). Gradle이 작업을 돌리지 않는 명령(`--dry-run`·`-m`·`-v`·`--version`·`-h`·`-?`·`--help`·`--status`·`--stop`·`--foreground`, 묶음 `-qm`·`-qv` 포함)과 Gradle이 거부하는 짧은 옵션 묶음(`-mx`)·값을 받지 않는 옵션에 붙인 값(`-m=yes`)도 세지 않는다. 판독기의 Gradle 옵션 표는 `GradleCommandLineTest`가 build-logic을 돌리는 Gradle의 `--help`와 대조하므로, Gradle을 올려 옵션이 늘면(9.2의 `--task-graph`) 그 테스트가 실패한다. 단계를 부르지만 세지 않은 명령은 다른 빌드로 읽힌 것까지 실패 메시지에 이유와 함께 적는다(r9). `verifyEnvKeys`: lane 계약 json의 `APP_` 밖 키는 `SPRING_`·`MANAGEMENT_`·`SERVER_`이거나 `secret://…/`가 가리키는 변수여야 하고, 레지스트리 `property:` 행은 그 property가 설정 metadata에 있어야 읽히는 것으로 친다(`@ConditionalOnProperty`로만 읽는 스위치는 `META-INF/additional-spring-configuration-metadata.json`에 선언, RR2-04-05). SpotBugs 신뢰도 HIGH → MEDIUM | 등록 안 한 leaf, 단계에 안 걸린 자기 lane, 자기 코드의 MEDIUM 발견이 `ci`·`qualityCheck`를 막는다. `working-directory: src`도 `cd src`도 없이 `./gradlew`를 부르는 자기 workflow 단계는 실행으로 세지 않는다. 확실히 따라갈 수 없는 디렉터리 이동(`cd "$VAR"`, `cd -`, `cd ~`, 절대 경로, `pushd`, `if`/`for`/`case`·`{ }`·서브셸 안의 `cd`, `||`·`|`로 이은 `cd`, 다른 명령과 `&&`로 묶인 `cd` 다음 줄) 뒤의 명령도 세지 않고, 실패 메시지에 그 명령과 이유를 적는다. 단계를 `./gradlew ci \| tee log`(기본 셸), `./gradlew ci \|\| true`, `./gradlew ci \|\| exit 1`, `if ./gradlew ci; then` 같은 모양으로만 부르거나, 조건부 `exit 0` 뒤, `-v`·`--help`를 붙여, 요청형 trigger·`paths` 필터 trigger로만 시작하는 workflow·호출되지 않는 `workflow_call` workflow·조건부 job을 `needs`로 기다리는 job·`shell:` 없는 Windows runner에서만 부르는 자기 workflow도 실패한다 | leaf를 등록하거나 지운다. 자기 lane은 단계에 건다. 단계를 부르는 workflow 명령에 `working-directory`를 두거나 같은 셸에서 `cd <상대 경로>`로 옮긴 뒤 부른다. 단계 명령은 혼자 한 줄로 두고, 로그를 파이프로 남기려면 `shell: bash`나 앞 줄 `set -o pipefail`을 둔다. Windows runner에서는 `shell: bash`를 둔다. 단계는 매 push·pull request·schedule에 도는(`paths`·`paths-ignore` 필터 없는) workflow와 job에서, 재사용 workflow라면 그런 job이 조건 없이 부르게 한다. Gradle을 올려 `GradleCommandLineTest`가 실패하면 새 옵션을 값 옵션·플래그·작업 없이 끝나는 옵션 중 하나로 판독기 표에 넣는다. SpotBugs 발견은 고치거나 이유를 단 제외로 | `1400dc15`, `34565130`, `bbe944bd`, `5786126c`, `70fb80bf`(2026-11-04 소유자 결정), r9, r10(RR6-04-01~06), RR7-05-01(2026-11-06 소유자 결정) · `src/build-logic/.../ModuleRegistry.java`, `.../strictlane/StrictLaneStagesPlugin.java`, `.../strictlane/WorkflowGradleInvocations.java`, `.../strictlane/ShellScript.java`, `.../strictlane/GradleCommandLineTest.java`(test), `.../quality/QualityConventionsPlugin.java`, `src/build.gradle` | | B-37 | app-bootstrap 테스트 lane 분리: 저장소 파일을 읽는 테스트는 태그 `document-contract`(main 단계) 또는 `repository-contract`(`check`)여야 하고, 일반 `test` lane에는 `ca.repository.root`가 없다 | app-bootstrap에 둔 자기 테스트가 저장소 파일을 읽으면 `test`에서 실패 | 태그를 단다 | `1400dc15` · `src/app-bootstrap/build.gradle` | | B-40 | 테스트 코드 정적 분석 `testQualityCheck`: SpotBugs·FindSecBugs를 main 밖 모든 source set(test, testFixtures, integrationTest, systemTest 등)에 돌린다. 테스트용 제외 목록은 `config/spotbugs/exclude-test.xml`(보안 범주·내부 상태 노출·생성자 예외·반환값 null 역참조·아키텍처 위반 fixture). 분석 classpath가 그 source set의 runtime classpath로 넓어졌고, 분석이 불완전하면(빠진 클래스) 실패한다. main 빌드는 `mainCheck`(`qualificationCheck`), optional 빌드는 `ci` | 자기 테스트 코드의 SpotBugs 발견(예: `CountDownLatch.await` 반환값 무시, 공유 변수 비원자 쓰기, 닫지 않은 `Statement`)이 main 단계를 막는다. 테스트 classpath에 없는 타입을 참조하면 `SpotBugs analysis incomplete` | 고치거나, 클래스·메서드로 좁힌 Match를 이유와 함께 `exclude-test.xml`에 더한다. 빠진 타입은 그 테스트 suite 의존성에 넣는다 | `2678955c` · `src/build-logic/.../quality/QualityConventionsPlugin.java`, `src/config/spotbugs/exclude-test.xml`, `src/build.gradle` | | B-42 | shared-contract 패키지 규칙 `SHARED_CONTRACT_CONTAINS_ONLY_OPERATIONAL_CONTRACT_PACKAGES`가 실제로 검사한다. 대상은 `dev.caskeleton.shared..`뿐이고, 허용은 목록의 패키지(`concurrency digest error metrics observability ratelimit request response retry runtime security tracing`)와 그 아래, 뿌리 패키지에는 `package-info`만이다. 전에는 뿌리를 허용 목록에 넣고 접두어로 비교해서 모듈 안은 아무것도 잡지 못했고, 다른 leaf의 `..shared..` 패키지를 잡았다 | `dev.caskeleton.shared`에 목록에 없는 패키지나 뿌리 클래스를 둔 파생 서비스는 architectureTest 실패. 다른 leaf의 `shared` 패키지는 더는 걸리지 않는다 | 업무 개념이면 그것을 소유하는 모듈로 옮긴다. 운영 계약이면 `ForbiddenApiArchitectureTest.SHARED_CONTRACT_PACKAGES`와 shared-contract CLAUDE.md 「Responsibility」에 함께 더한다 | r10 · `src/app-bootstrap/src/architectureTest/.../ForbiddenApiArchitectureTest.java`, `SharedContractPackageRuleTest.java` | diff --git a/src/README.md b/src/README.md index 4e8b0fa4..0159f9ac 100644 --- a/src/README.md +++ b/src/README.md @@ -28,7 +28,7 @@ Checkstyle은 **포매터가 표현할 수 없는 것만** — 네이밍과 몇 | `qualificationCheck` | 전체 기동(system) 레인과 보조 source set Checkstyle을 실행 | | `integrationCheck` | 선언된 strict integration lane(sample 포함)을 실행. 대부분 container runtime이 필요. 입력이 필요한 lane(Redis topology: `-Predis.topology.mode`, AWS: 보호 자격 증명 env)은 입력이 없으면 빠지고 집계가 그 이유를 출력 | | `performanceCheck` | 선언된 strict performance lane(부하·종료·pool·자원 상한)을 실행. 실서버·container가 필요. 상한은 매번 단언하고 끄는 속성이 없다(`-Pperformance.assertions.enabled`가 `true`가 아니면 실패, skip된 테스트가 있어도 실패). `integration-main.yml` `performance-check`가 main·nightly에 같은 명령으로 돌림 | -| `verifyStrictLaneStages` | `--dry-run` 전용. `explicitOnly`가 아닌 strict lane이 workflow가 실제 실행하는 단계(`ci`·`:sample-portfolio:check`·`mainCheck`·`integrationCheck`·`performanceCheck`·`releaseCheck`) 중 하나의 계획에 있는지, 각 단계를 workflow가 `--dry-run` 없이 실행하는지 검사. Gradle이 작업을 돌리지 않는 명령(`--dry-run`·`-v`·`--help` 등)과, 실패해도 단계가 실패하지 않을 수 있거나(`\|\| true`, pipefail 없는 파이프, `if` 조건 등) 돌지 않을 수 있거나(조건부 `exit 0` 뒤, 요청으로만 시작하는 workflow 등) 검사가 읽지 않는(`\|\| exit 1`, `{ }` 안 등) 명령은 실행으로 세지 않는다. 자세한 목록은 `build-logic/README.md`. PR 게이트가 돌림 | +| `verifyStrictLaneStages` | `--dry-run` 전용. `explicitOnly`가 아닌 strict lane이 workflow가 실제 실행하는 단계(`ci`·`:sample-portfolio:check`·`mainCheck`·`integrationCheck`·`performanceCheck`·`releaseCheck`) 중 하나의 계획에 있는지, 각 단계를 workflow가 `--dry-run` 없이 실행하는지 검사. Gradle이 작업을 돌리지 않는 명령(`--dry-run`·`-v`·`--help` 등)과, 실패해도 단계가 실패하지 않을 수 있거나(`\|\| true`, pipefail 없는 파이프, `if` 조건 등) 돌지 않을 수 있거나(조건부 `exit 0` 뒤, 요청으로만 시작하는 workflow, `paths` 필터로만 시작하는 workflow 등) 검사가 읽지 않는(`\|\| exit 1`, `{ }` 안 등) 명령은 실행으로 세지 않는다. 자세한 목록은 `build-logic/README.md`. PR 게이트가 돌림 | | `ci` | PR 게이트: 모든 leaf `check`(API surface 검사 포함, 소유자 결정 20) + `architectureCheck` + `qualityCheck` | | `mainCheck` | main 단계: `configContractCheck` + `qualificationCheck` + sample web 계약 + sample 전체 기동(`:sample-portfolio:systemTest`) + `verifyPublicPathSnapshot` + 전송·메시징 qualification 레인 + 각 leaf의 `mainCheck`(문서 대조 레인 `*DocumentContractTest`, objectstorage MinIO 레인) | | `releaseCheck` | tag 전용 검사: `verifyReleaseProvenance` + `verifyPublicPathSnapshot`(`ci`를 다시 돌리지 않음) | diff --git a/src/build-logic/README.md b/src/build-logic/README.md index 52ae07a2..d6f54997 100644 --- a/src/build-logic/README.md +++ b/src/build-logic/README.md @@ -16,7 +16,7 @@ capability, and the files it reads are declared as that test task's inputs. | `ca.java-library` / `ca.spring-library` / `ca.spring-config` | leaf-level composition of the Java/quality conventions for plain and Spring libraries | | `ca.platform-module` / `ca.grpc-platform-module` | what a vendored platform leaf (`messaging:*`, `grpc:*`, `grpc-advanced:*`) is: `java-library`, plus the gRPC BOM for the leaves that had it | | `ca.strict-test-lane` | the one "named tests ran, none skipped" mechanism: tagged / named / own-source-set `Test` lanes that fail when they execute nothing, miss a `requires` class, or (with `rejectSkipped`) skip anything. A `performance()` lane always rejects skips and runs with `performance.assertions.enabled=true`; a build (`-P`, `GRADLE_OPTS`) or lane that sets another value fails it before a test runs. `mainStage()` moves a tagged lane out of `test` into the leaf's `mainCheck`; `explicitOnly(reason)` keeps a lane that needs an outside input out of every aggregate, and the aggregate prints the reason. Extra test source sets are Gradle `jvm-test-suite` suites declared in the leaf (`testing { suites { … } }`); a lane named after its suite makes the suite's own `Test` task strict, and `ca.java-conventions` gives every suite the BOM's JUnit | -| `ca.strict-lane-stages` (root of each build with strict lanes: the main build and optional-platforms) | the other half of the lane mechanism: `verifyStrictLaneStages --dry-run` fails when a strict lane of that build that is not `explicitOnly` is in the task plan of no declared stage that a workflow executes, or when a declared stage is executed by no workflow. The workflows are read together (`WorkflowGradleInvocations.readAll`, so a reusable workflow is judged by its callers) and their `run:` scripts parsed as bash (`ShellScript`: quotes, comments, heredoc bodies, substitutions and compound commands are read as the shell reads them, so a `cd` in a heredoc or a string is data). A command does not count when Gradle runs no task with it — `--dry-run`/`-m` (also in a bundle such as `-qm`), `-v`/`--version`, `-h`/`-?`/`--help`, `--status`, `--stop`, `--foreground` (also in a bundle such as `-qv`) — or rejects it: a short-option bundle whose later letter takes a value (`-mx`: only the first letter of a bundle takes one), or a value given to an option that takes none (`-m=yes`). The reader follows Gradle 9.0's parser. `GradleCommandLineTest` holds its option tables to the `--help` of the Gradle that runs build-logic — an upgrade that adds an option, as 9.2 adds `--task-graph`, fails until the option is placed — and runs the launcher with each no-task option but `--stop` and `--foreground` (both return a daemon action, not a build, in Gradle's `BuildActionsFactory`); which options take a value was probed against 9.0.0 in round 9 and is not re-run. Nor does a command for another build count (the build a command starts is its step's `working-directory`, or the job's or workflow's `defaults.run.working-directory`, moved by each `cd ` the same `run:` shell surely ran before it — alone in its list, or before the command in the same `&&` list — then joined with `-p`; the plugin reads this build's own directory from where it sits under the repository that holds `.github/workflows`). Every other command that does not count gives one of three reasons. **Its failure may not fail its step**: `\|\| true`, `\|\| :` or any `\|\|` but `\|\| exit `, a pipe's left side without `pipefail` (on with `shell: bash` or a top-level `set -o pipefail`), `!`, `&`, an `if`/`while` condition, the part before `&&` of a list that is not the script's last command, after `set +e`, after a `trap` whose `EXIT` or `ERR` action may `exit` with status 0 (a bare `exit` keeps the status in an `EXIT` trap, not in an `ERR` one), and `continue-on-error`. **It may not run**: after `\|\|`, after `&&` in a list that is not the script's last command, inside `if`/`while`/`for`/`case` or a function body, after a top-level `exit`, `exec ` or `set -n`, after one elsewhere — in a compound command, an and-or list or a function the script calls — that may end the script with status 0 (`exit 0`, a bare `exit` other than right after `\|\|`, `exit "$code"`), replace it or stop it running commands (`set -o noexec`), under an `if:` other than `always()`/`success()`/`!cancelled()`, in a workflow that starts only on events someone or something asks for (`workflow_dispatch`, `repository_dispatch`, `issue_comment`, a pull request with `types: [labeled]`, `workflow_run`, …; `push`, `pull_request`, `pull_request_target`, `merge_group`, `schedule` and `release` count), in a reusable (`workflow_call`-only) workflow that no counted job calls with `uses: ./.github/workflows/`, and in a job that `needs`, directly or through other jobs, a job with such an `if:` or with `continue-on-error`, unless its own `if:` is `always()` or `!cancelled()`. **This check does not read it**, although its failure would fail the step (a false failure on purpose): `\|\| exit 1`, `\|\| { …; exit 1; }`, inside `{ }` or `( )`, `$( )`, `bash -c`, `gradlew` as another command's argument (`timeout 60 ./gradlew`), after a directory change the reader does not follow (`cd "$VAR"`, `cd -`, `cd ~`, an absolute path, `pushd`/`popd`, `builtin cd`, `eval`/`source`, a `cd` anywhere inside a compound command or a function body, one joined with `\|\|`, piped or in the background, and the lines after a `cd` that shares an `&&` list with other commands — not guessed), a step whose `shell:` is not `bash` or `sh`, and a step with no `shell:` in a job whose `runs-on` may be a Windows runner, whose default shell is `pwsh` (a Windows label, an expression such as `${{ matrix.os }}`, a self-hosted label set without `linux` or `macos`; Linux and macOS runners default to `bash -e` and a `container:` job to `sh -e`, which are read alike). An `exit` that fails the step — `exit 1`, or `cmd \|\| exit` — and one in an uncalled function, a `( )` subshell or `$( )` stop nothing after them from counting. The failure names every command that names the stage but does not execute it, with its reason or the other build it starts, and says to run the stage as `./gradlew` on a line of its own. A lane the command removes with `-x` is not covered — matched the way Gradle matches task and project names, abbreviations included (`TaskSelectors`, a copy of Gradle's internal `NameMatcher`). A `run:` input of a `uses:` step is not a command. The plan is Gradle's own; the workflows are read for their `run:` steps with YAML folding applied (review 2026-11-01 08-01, 2026-11-03 RR-06-03/04, 2026-11-04 RR2-04-04, owner decision 2026-11-04 on `cd`, RR5-02-01/02/03 in round 9, 2026-11-05 RR6-04-01..06) | +| `ca.strict-lane-stages` (root of each build with strict lanes: the main build and optional-platforms) | the other half of the lane mechanism: `verifyStrictLaneStages --dry-run` fails when a strict lane of that build that is not `explicitOnly` is in the task plan of no declared stage that a workflow executes, or when a declared stage is executed by no workflow. The workflows are read together (`WorkflowGradleInvocations.readAll`, so a reusable workflow is judged by its callers) and their `run:` scripts parsed as bash (`ShellScript`: quotes, comments, heredoc bodies, substitutions and compound commands are read as the shell reads them, so a `cd` in a heredoc or a string is data). A command does not count when Gradle runs no task with it — `--dry-run`/`-m` (also in a bundle such as `-qm`), `-v`/`--version`, `-h`/`-?`/`--help`, `--status`, `--stop`, `--foreground` (also in a bundle such as `-qv`) — or rejects it: a short-option bundle whose later letter takes a value (`-mx`: only the first letter of a bundle takes one), or a value given to an option that takes none (`-m=yes`). The reader follows Gradle 9.0's parser. `GradleCommandLineTest` holds its option tables to the `--help` of the Gradle that runs build-logic — an upgrade that adds an option, as 9.2 adds `--task-graph`, fails until the option is placed — and runs the launcher with each no-task option but `--stop` and `--foreground` (both return a daemon action, not a build, in Gradle's `BuildActionsFactory`); which options take a value was probed against 9.0.0 in round 9 and is not re-run. Nor does a command for another build count (the build a command starts is its step's `working-directory`, or the job's or workflow's `defaults.run.working-directory`, moved by each `cd ` the same `run:` shell surely ran before it — alone in its list, or before the command in the same `&&` list — then joined with `-p`; the plugin reads this build's own directory from where it sits under the repository that holds `.github/workflows`). Every other command that does not count gives one of three reasons. **Its failure may not fail its step**: `\|\| true`, `\|\| :` or any `\|\|` but `\|\| exit `, a pipe's left side without `pipefail` (on with `shell: bash` or a top-level `set -o pipefail`), `!`, `&`, an `if`/`while` condition, the part before `&&` of a list that is not the script's last command, after `set +e`, after a `trap` whose `EXIT` or `ERR` action may `exit` with status 0 (a bare `exit` keeps the status in an `EXIT` trap, not in an `ERR` one), and `continue-on-error`. **It may not run**: after `\|\|`, after `&&` in a list that is not the script's last command, inside `if`/`while`/`for`/`case` or a function body, after a top-level `exit`, `exec ` or `set -n`, after one elsewhere — in a compound command, an and-or list or a function the script calls — that may end the script with status 0 (`exit 0`, a bare `exit` other than right after `\|\|`, `exit "$code"`), replace it or stop it running commands (`set -o noexec`), under an `if:` other than `always()`/`success()`/`!cancelled()`, in a workflow that starts only on events someone or something asks for (`workflow_dispatch`, `repository_dispatch`, `issue_comment`, a pull request with `types: [labeled]`, `workflow_run`, …; `push`, `pull_request`, `pull_request_target`, `merge_group`, `schedule` and `release` count), in a workflow whose change-flow triggers all carry a `paths` or `paths-ignore` filter (a change outside those paths does not start it; owner decision 2026-11-06 — `branches` and `tags` filters are not read), in a reusable (`workflow_call`-only) workflow that no counted job calls with `uses: ./.github/workflows/`, and in a job that `needs`, directly or through other jobs, a job with such an `if:` or with `continue-on-error`, unless its own `if:` is `always()` or `!cancelled()`. **This check does not read it**, although its failure would fail the step (a false failure on purpose): `\|\| exit 1`, `\|\| { …; exit 1; }`, inside `{ }` or `( )`, `$( )`, `bash -c`, `gradlew` as another command's argument (`timeout 60 ./gradlew`), after a directory change the reader does not follow (`cd "$VAR"`, `cd -`, `cd ~`, an absolute path, `pushd`/`popd`, `builtin cd`, `eval`/`source`, a `cd` anywhere inside a compound command or a function body, one joined with `\|\|`, piped or in the background, and the lines after a `cd` that shares an `&&` list with other commands — not guessed), a step whose `shell:` is not `bash` or `sh`, and a step with no `shell:` in a job whose `runs-on` may be a Windows runner, whose default shell is `pwsh` (a Windows label, an expression such as `${{ matrix.os }}`, a self-hosted label set without `linux` or `macos`; Linux and macOS runners default to `bash -e` and a `container:` job to `sh -e`, which are read alike). An `exit` that fails the step — `exit 1`, or `cmd \|\| exit` — and one in an uncalled function, a `( )` subshell or `$( )` stop nothing after them from counting. The failure names every command that names the stage but does not execute it, with its reason or the other build it starts, and says to run the stage as `./gradlew` on a line of its own. A lane the command removes with `-x` is not covered — matched the way Gradle matches task and project names, abbreviations included (`TaskSelectors`, a copy of Gradle's internal `NameMatcher`). A `run:` input of a `uses:` step is not a command. The plan is Gradle's own; the workflows are read for their `run:` steps with YAML folding applied (review 2026-11-01 08-01, 2026-11-03 RR-06-03/04, 2026-11-04 RR2-04-04, owner decision 2026-11-04 on `cd`, RR5-02-01/02/03 in round 9, 2026-11-05 RR6-04-01..06, 2026-11-06 RR7-05-01) | | `ca.redis-topology-lane` | the Redis topology lane (mode selection, `-P` property validation, per-mode required classes) the redis-sdk-topology workflow drives | | `ca.api-surface` | read-only public API surface verification with a separate update task, wired into the leaf's `check` (owner decision 20); optionally holds other leaves' imports to a reviewed adopter subset (`adopterBaseline`) | | `ca.config-contract` | app-bootstrap's `verifyEnvKeys` (moved from the deleted build-tools included build; owner decision 4 keeps the task in app-bootstrap) | diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesPlugin.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesPlugin.java index e9e0f980..419748ef 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesPlugin.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesPlugin.java @@ -33,7 +33,8 @@ import org.gradle.api.execution.TaskExecutionGraph; * as a workflow runs it — a lane the command removes with {@code -x} is not covered, matched * the way Gradle matches it, abbreviations included ({@link TaskSelectors}); *
  • every declared stage is executed by a workflow. Not counted ({@code NOT_COUNTED}; review - * 2026-11-03 RR-06-04, 2026-11-04 RR2-04-04, RR5-02-02, 2026-11-05 RR6-04-01..06): a command + * 2026-11-03 RR-06-04, 2026-11-04 RR2-04-04, RR5-02-02, 2026-11-05 RR6-04-01..06, 2026-11-06 + * RR7-05-01): a command * after which Gradle runs no task ({@code --dry-run}, {@code -v}, {@code --help}, …) or that * Gradle rejects (a short-option bundle such as {@code -mx}), one for another build, and one * that does not gate for one of three reasons — its failure may not fail its step, it may not @@ -66,13 +67,15 @@ public final class StrictLaneStagesPlugin implements Plugin { + " script's last command, after set +e or a trap that exits 0, continue-on-error); one" + " that may not run (after ||, inside if/while/for/case or a function, after an exit 0," + " exec or set -n, under an if: other than always()/success()/!cancelled(), in a" - + " workflow that starts only on a request or a reusable one no counted job calls, in a" + + " workflow that starts only on a request, or on changes only through a paths or" + + " paths-ignore filter, or a reusable one no counted job calls, in a" + " job that needs a job that may be skipped); and one this check does not read although" + " its failure" + " would fail the step (|| exit 1, inside { } or ( ), $( ), bash -c, gradlew as" + " another command's argument, after a cd it does not follow, a shell other than bash" + " or sh, a runner that may be Windows). Run the stage as ./gradlew on a line of its" - + " own, in a step and job that run on every push, pull request or schedule"; + + " own, in a step and job that run on every push, pull request or schedule, with no" + + " paths or paths-ignore filter"; @Override public void apply(Project project) { diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocations.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocations.java index d02b7b13..ef6c29bb 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocations.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocations.java @@ -44,7 +44,10 @@ import java.util.regex.Pattern; *

    When a workflow runs. A workflow counts when one of its triggers is part of the change * or release flow: {@code push}, {@code pull_request} or {@code pull_request_target} (with a {@code * types} list, only when it holds {@code opened}, {@code synchronize} or {@code reopened}), {@code - * merge_group}, {@code schedule}, {@code release}. One that starts only on other events — {@code + * merge_group}, {@code schedule}, {@code release} — and has no {@code paths} or {@code + * paths-ignore} filter: a change that touches none of the listed paths, or only ignored ones, does + * not start it (owner decision 2026-11-06, review RR7-05-01). Its {@code branches} and {@code tags} + * filters are not read. One that starts only on other events — {@code * workflow_dispatch}, {@code repository_dispatch}, {@code issue_comment}, a {@code labeled} pull * request, {@code workflow_run} and the rest — runs only when someone or something asks (review * 2026-11-04 RR2-04-04, RR6-04-06). A workflow that starts only on {@code workflow_call} counts @@ -98,6 +101,8 @@ public final class WorkflowGradleInvocations { /** The pull-request activity types that come with every new change. */ private static final Set PULL_REQUEST_CHANGE_TYPES = Set.of("opened", "synchronize", "reopened"); + /** The trigger filters that start a workflow only for changes to some files. */ + private static final List PATH_FILTERS = List.of("paths", "paths-ignore"); private static final String REUSABLE_WORKFLOWS = "./.github/workflows/"; /** * Gradle 9.0's command-line options that take a value, by every name it accepts. Probed against @@ -256,9 +261,19 @@ public final class WorkflowGradleInvocations { ShellScript.Options shell, String uncountedReason) {} - /** One workflow file: its name, its lines, its triggers with their {@code types}, its jobs. */ + /** One workflow file: its name, its lines, its triggers by event name, its jobs. */ private record Workflow( - String file, List lines, Map> triggers, Map jobs) {} + String file, List lines, Map triggers, Map jobs) {} + + /** + * One trigger's filters that decide whether it runs on every change. + * + * @param types its {@code types} list, or {@code null} when it has none + * @param pathFilters which of {@code paths} and {@code paths-ignore} it has + */ + private record Trigger(List types, List pathFilters) { + private static final Trigger UNFILTERED = new Trigger(null, List.of()); + } /** A job: its id, the line of its key, and the column of its own keys (-1 when it has none). */ private record Job(String id, int header, int keyIndent) {} @@ -476,12 +491,9 @@ public final class WorkflowGradleInvocations { // --------------------------------------------------------------------------------------------- // When the workflow runs - /** - * The workflow's triggers, each with its {@code types} list, or {@code null} when it has none; - * empty when no {@code on:} is written. - */ - private static Map> triggers(List lines) { - Map> triggers = new LinkedHashMap<>(); + /** The workflow's triggers with their filters; empty when no {@code on:} is written. */ + private static Map triggers(List lines) { + Map triggers = new LinkedHashMap<>(); for (int index = 0; index < lines.size(); index++) { Matcher on = TRIGGER_KEY.matcher(lines.get(index)); if (!on.matches()) { @@ -494,7 +506,7 @@ public final class WorkflowGradleInvocations { int colon = entry.indexOf(':'); triggers.put( stripScalarComment(colon < 0 ? entry : entry.substring(0, colon)), - colon < 0 ? null : flowTypes(entry.substring(colon + 1).trim())); + colon < 0 ? Trigger.UNFILTERED : flowTrigger(entry.substring(colon + 1).trim())); } } else if (!inline.isEmpty()) { String list = @@ -502,7 +514,7 @@ public final class WorkflowGradleInvocations { ? inline.substring(1, inline.length() - 1) : inline; for (String trigger : flowItems(list)) { - triggers.put(trigger, null); + triggers.put(trigger, Trigger.UNFILTERED); } } else { blockTriggers(lines, index, triggers); @@ -514,7 +526,7 @@ public final class WorkflowGradleInvocations { /** The triggers of a block {@code on:} at {@code onLine}: a mapping or a list. */ private static void blockTriggers( - List lines, int onLine, Map> triggers) { + List lines, int onLine, Map triggers) { int childIndent = childIndent(lines, onLine); for (int next = onLine + 1; next < lines.size(); next++) { String line = lines.get(next); @@ -532,35 +544,55 @@ public final class WorkflowGradleInvocations { boolean item = key.startsWith("-"); key = item ? key.substring(1).trim() : key; int colon = key.indexOf(':'); - List types = null; + Trigger trigger = Trigger.UNFILTERED; String inlineDetail = colon < 0 ? "" : key.substring(colon + 1).trim(); if (!item && inlineDetail.startsWith("{")) { - types = flowTypes(stripScalarComment(inlineDetail)); + trigger = flowTrigger(stripScalarComment(inlineDetail)); } else if (!item && colon >= 0) { int detailIndent = childIndent(lines, next); - int typesLine = - detailIndent > childIndent ? mappingKey(lines, next + 1, detailIndent, "types") : -1; - types = typesLine < 0 ? null : listValue(lines, typesLine); + if (detailIndent > childIndent) { + int typesLine = mappingKey(lines, next + 1, detailIndent, "types"); + List pathFilters = new ArrayList<>(); + for (String filter : PATH_FILTERS) { + if (mappingKey(lines, next + 1, detailIndent, filter) >= 0) { + pathFilters.add(filter); + } + } + trigger = + new Trigger(typesLine < 0 ? null : listValue(lines, typesLine), pathFilters); + } } - triggers.put(stripScalarComment(colon < 0 ? key : key.substring(0, colon)), types); + triggers.put(stripScalarComment(colon < 0 ? key : key.substring(0, colon)), trigger); } } - /** The {@code types} of a flow-mapping trigger value such as {@code {types: [created]}}. */ - private static List flowTypes(String value) { + /** + * The filters of a flow-mapping trigger value such as {@code {types: [created]}} or {@code + * {paths: [docs/**]}}. + */ + private static Trigger flowTrigger(String value) { if (!value.startsWith("{") || !value.endsWith("}")) { - return null; + return Trigger.UNFILTERED; } + List types = null; + List pathFilters = new ArrayList<>(); for (String entry : flowItems(value.substring(1, value.length() - 1))) { int colon = entry.indexOf(':'); - if (colon >= 0 && stripScalarComment(entry.substring(0, colon)).equals("types")) { - String types = entry.substring(colon + 1).trim(); - return types.startsWith("[") && types.endsWith("]") - ? flowItems(types.substring(1, types.length() - 1)) - : List.of(stripScalarComment(types)); + if (colon < 0) { + continue; + } + String key = stripScalarComment(entry.substring(0, colon)); + String detail = entry.substring(colon + 1).trim(); + if (key.equals("types")) { + types = + detail.startsWith("[") && detail.endsWith("]") + ? flowItems(detail.substring(1, detail.length() - 1)) + : List.of(stripScalarComment(detail)); + } else if (PATH_FILTERS.contains(key)) { + pathFilters.add(key); } } - return null; + return new Trigger(types, pathFilters); } /** @@ -569,16 +601,27 @@ public final class WorkflowGradleInvocations { */ private static String startReason( Workflow workflow, Map workflows, Set visiting) { - Map> triggers = workflow.triggers(); + Map triggers = workflow.triggers(); if (triggers.isEmpty()) { return null; } - for (Map.Entry> trigger : triggers.entrySet()) { - if (runsOnChanges(trigger.getKey(), trigger.getValue())) { + Map pathFiltered = new LinkedHashMap<>(); + for (Map.Entry trigger : triggers.entrySet()) { + if (!runsOnChanges(trigger.getKey(), trigger.getValue().types())) { + continue; + } + if (trigger.getValue().pathFilters().isEmpty()) { return null; } + pathFiltered.put(trigger.getKey(), trigger.getValue()); } String described = describe(triggers); + if (!triggers.containsKey("workflow_call") && !pathFiltered.isEmpty()) { + return "its workflow starts on changes only through " + + describe(pathFiltered) + + ", which a change that touches none of the listed paths, or only ignored ones, does" + + " not start, so it may not run"; + } if (!triggers.containsKey("workflow_call")) { return "its workflow starts only on " + described @@ -626,12 +669,17 @@ public final class WorkflowGradleInvocations { || types.stream().anyMatch(PULL_REQUEST_CHANGE_TYPES::contains); } - private static String describe(Map> triggers) { + private static String describe(Map triggers) { List described = new ArrayList<>(); triggers.forEach( - (trigger, types) -> - described.add( - types == null ? trigger : trigger + " (types: " + String.join(", ", types) + ")")); + (name, trigger) -> { + List filters = new ArrayList<>(); + if (trigger.types() != null) { + filters.add("types: " + String.join(", ", trigger.types())); + } + filters.addAll(trigger.pathFilters()); + described.add(filters.isEmpty() ? name : name + " (" + String.join("; ", filters) + ")"); + }); return String.join(", ", described); } diff --git a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocationsTest.java b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocationsTest.java index 8f1c7769..b8503153 100644 --- a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocationsTest.java +++ b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocationsTest.java @@ -1283,6 +1283,87 @@ class WorkflowGradleInvocationsTest { .allSatisfy(invocation -> assertThat(invocation.executes(":ci", "src")).isTrue()); } + @Test + @DisplayName("paths·paths-ignore 필터가 붙은 change trigger로만 시작하는 workflow의 명령은 세지 않는다") + void aWorkflowThatStartsOnChangesOnlyThroughAPathFilterGatesNothing() { + // given + List workflows = + List.of( + """ + on: + pull_request: + paths: ["docs/**"] + push: + branches: [main] + paths: + - "docs/**" + jobs: + main: + steps: + - working-directory: src + run: ./gradlew :ci + """, + """ + on: {push: {paths-ignore: ["docs/**"]}, workflow_dispatch: {}} + jobs: + main: + steps: + - working-directory: src + run: ./gradlew :ci + """, + """ + on: + pull_request: {types: [opened, synchronize], paths: ["src/**"]} + jobs: + main: + steps: + - working-directory: src + run: ./gradlew :ci + """); + + // when + List invocations = + workflows.stream().flatMap(workflow -> WorkflowGradleInvocations.read(workflow).stream()) + .toList(); + + // then + assertThat(invocations) + .hasSize(3) + .allSatisfy(invocation -> assertThat(invocation.executes(":ci", "src")).isFalse()); + assertThat(invocations).extracting(Invocation::uncountedReason) + .satisfiesExactly( + reason -> assertThat(reason).contains("pull_request (paths)", "push (paths)"), + reason -> assertThat(reason).contains("push (paths-ignore)"), + reason -> + assertThat(reason).contains("pull_request (types: opened, synchronize; paths)")); + } + + @Test + @DisplayName("paths 필터가 붙은 trigger 옆에 필터 없는 change trigger가 있으면 그 workflow의 명령은 센다") + void aWorkflowWithAnUnfilteredChangeTriggerBesidesAPathFilterCounts() { + // given + String workflow = + """ + on: + pull_request: + paths: ["docs/**"] + schedule: + - cron: '0 3 * * *' + jobs: + main: + steps: + - working-directory: src + run: ./gradlew :ci + """; + + // when + List invocations = WorkflowGradleInvocations.read(workflow); + + // then + assertThat(invocations).singleElement().satisfies( + invocation -> assertThat(invocation.executes(":ci", "src")).isTrue()); + } + @Test @DisplayName("workflow_call로만 시작하는 재사용 workflow의 명령은 매 변경에 도는 호출 job이 있을 때만 센다") void aReusableWorkflowCountsOnlyThroughACallerThatRunsOnEveryChange() { From c746f98091bc62dcabea29a3bd07a93f313f598b Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Sat, 7 Nov 2026 01:10:30 +0900 Subject: [PATCH 28/71] =?UTF-8?q?fix(httpclient):=20interrupt=EB=90=9C=20?= =?UTF-8?q?=EC=8A=A4=EB=A0=88=EB=93=9C=EC=97=90=EC=84=9C=20=EB=8B=AB?= =?UTF-8?q?=EC=95=84=EB=8F=84=20drain=20=EC=8A=A4=EB=A0=88=EB=93=9C=20?= =?UTF-8?q?=EC=A2=85=EB=A3=8C=EB=A5=BC=20=EA=B8=B0=EB=8B=A4=EB=A6=B0?= =?UTF-8?q?=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: ClientRuntimeRegistry.close()는 "돌아오면 drain 스레드가 없다"를 약속하고, 기다리다 시간이 지나면 IllegalStateException을 던진다. 그런데 닫는 스레드가 이미 interrupt 상태면 첫 awaitTermination이 바로 InterruptedException을 내고, catch가 flag만 되살린 뒤 정상으로 돌아온다. drain 스레드가 살아 있어도 호출자는 모른다(리뷰 RR7-02-01). 고른 방법: interrupt를 받아도 같은 마감(5초)까지 다시 기다리고, 기다림이 끝나면 flag를 되살린다. 마감 안에 끝나지 않으면 다른 경로처럼 IllegalStateException을 던진다. 기다리는 부분을 awaitDrainThreadExit로 떼어 내 interrupt마다 남은 시간으로 다시 부른다. 버린 대안: interrupt 경로에서 바로 IllegalStateException을 던진다 — 더 단순하지만, 곧 끝날 스레드를 두고 정상 종료를 실패로 보고한다. 위험·한계: interrupt된 스레드의 close()가 이제 최대 5초까지 막힐 수 있다(전에는 바로 돌아왔다). interrupt된 채 마감을 넘기는 경로는 테스트하지 않았다(5초를 기다려야 한다). 같은 모양을 찾아본 다른 종료 코드(gRPC 서버, notification worker, S3 worker, outbox relay)는 "스레드가 없다"를 약속하지 않고 shutdownNow로 끝내는 최선 노력이라 고치지 않았다. 검증(desktop, 로그 ~/r8-f5-logs/): - RED: 기준 73d39212에 테스트만 얹음. closingFromAnInterruptedThreadStillWaitsForTheDrainThread 실패 — "Expecting empty but was: [httpclient-runtime-drain]" (red-rr7-02-01.log, .xml) - GREEN: ClientRuntimeRegistryTest rc=0 (green-rr7-02-01.log) - :adapter:outbound:httpclient:check, :testQualityCheck, httpClientStableContractTest(apache, jdk), spring70CompatibilityTest, :ci rc=0 (summary.txt) Refs: docs/reviews/2026-11-03-rereview/round7/02-idempotency-outbound.md RR7-02-01 --- .../profile/ClientRuntimeRegistry.java | 42 +++++++++++---- .../profile/ClientRuntimeRegistryTest.java | 53 +++++++++++++++++++ 2 files changed, 84 insertions(+), 11 deletions(-) diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/profile/ClientRuntimeRegistry.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/profile/ClientRuntimeRegistry.java index 8078fc62..6b566576 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/profile/ClientRuntimeRegistry.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/profile/ClientRuntimeRegistry.java @@ -169,6 +169,11 @@ public final class ClientRuntimeRegistry implements AutoCloseable { * the executor reports termination from inside the worker before that thread exits, so under load * the thread could still be listed when close returned. Joining the thread is what makes "no * thread left" true when this returns. + * + *

    An interrupt does not cut the wait short; the flag is restored once the wait is over. A + * closing thread that was already interrupted used to give up at the first wait and return + * normally with the drain thread still running — the one failure path that said nothing (review + * 2026-11-06 RR7-02-01). */ private void stopDrainThread() { ScheduledExecutorService scheduler = drainScheduler.getAndSet(null); @@ -177,23 +182,38 @@ public final class ClientRuntimeRegistry implements AutoCloseable { } scheduler.shutdownNow(); long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(SHUTDOWN_AWAIT_MILLIS); + boolean interrupted = false; try { - if (!scheduler.awaitTermination(SHUTDOWN_AWAIT_MILLIS, TimeUnit.MILLISECONDS)) { - throw new IllegalStateException("http client drain scheduler did not terminate"); - } - for (Thread thread : drainThreads) { - long remaining = TimeUnit.NANOSECONDS.toMillis(deadline - System.nanoTime()); - thread.join(Math.max(1L, remaining)); - if (thread.isAlive()) { - throw new IllegalStateException("http client drain thread did not exit"); + while (true) { + try { + awaitDrainThreadExit(scheduler, deadline); + return; + } catch (InterruptedException interruptedWait) { + interrupted = true; } } - drainThreads.clear(); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); + } finally { + if (interrupted) { + Thread.currentThread().interrupt(); + } } } + private void awaitDrainThreadExit(ScheduledExecutorService scheduler, long deadline) + throws InterruptedException { + if (!scheduler.awaitTermination(deadline - System.nanoTime(), TimeUnit.NANOSECONDS)) { + throw new IllegalStateException("http client drain scheduler did not terminate"); + } + for (Thread thread : drainThreads) { + long remaining = TimeUnit.NANOSECONDS.toMillis(deadline - System.nanoTime()); + thread.join(Math.max(1L, remaining)); + if (thread.isAlive()) { + throw new IllegalStateException("http client drain thread did not exit"); + } + } + drainThreads.clear(); + } + private AtomicReference holder(ClientProfileName name) { AtomicReference holder = runtimes.get(name); if (holder == null) { diff --git a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/profile/ClientRuntimeRegistryTest.java b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/profile/ClientRuntimeRegistryTest.java index 8b3a2501..6c5c29d6 100644 --- a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/profile/ClientRuntimeRegistryTest.java +++ b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/profile/ClientRuntimeRegistryTest.java @@ -7,7 +7,10 @@ import dev.caskeleton.adapter.outbound.httpclient.testkit.ClientProfiles; import java.time.Duration; import java.util.Map; import java.util.Set; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; class ClientRuntimeRegistryTest { @@ -83,6 +86,56 @@ class ClientRuntimeRegistryTest { assertThat(liveDrainThreads()).isEmpty(); } + @Test + @DisplayName("interrupt된 스레드에서 닫아도 drain 스레드가 끝난 뒤에 돌아오고 interrupt 상태는 남긴다") + void closingFromAnInterruptedThreadStillWaitsForTheDrainThread() throws InterruptedException { + // given: the drain thread is busy closing the old generation, and ignores the interrupt + // shutdownNow sends it, when the registry closes + CountDownLatch drainStarted = new CountDownLatch(1); + ClientRuntime busy = + new ClientRuntime( + ClientProfiles.builder("payment").build(), + new RuntimeGeneration(1), + () -> { + drainStarted.countDown(); + sleepIgnoringInterrupts(Duration.ofMillis(500)); + }); + ClientRuntimeRegistry registry = new ClientRuntimeRegistry(Map.of(busy.name(), busy)); + ClientRuntimeLease lease = registry.acquire(busy.name()); + registry.swap(busy.name(), running(2), Duration.ofMillis(1)); + assertThat(drainStarted.await(5, TimeUnit.SECONDS)).isTrue(); + + // when + Thread.currentThread().interrupt(); + boolean stillInterrupted; + try { + registry.close(); + } finally { + stillInterrupted = Thread.interrupted(); + } + + // then + Set left = liveDrainThreads(); + lease.close(); + assertThat(left).isEmpty(); + assertThat(stillInterrupted).isTrue(); + } + + private static void sleepIgnoringInterrupts(Duration duration) { + long end = System.nanoTime() + duration.toNanos(); + boolean interrupted = false; + for (long left = duration.toNanos(); left > 0; left = end - System.nanoTime()) { + try { + Thread.sleep(Duration.ofNanos(left)); + } catch (InterruptedException ignored) { + interrupted = true; + } + } + if (interrupted) { + Thread.currentThread().interrupt(); + } + } + private static Set liveDrainThreads() { return Thread.getAllStackTraces().keySet().stream() .filter(Thread::isAlive) From eab82df1f266f1e688185cee259691caa9f13600 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Sat, 7 Nov 2026 01:10:31 +0900 Subject: [PATCH 29/71] =?UTF-8?q?docs:=20README=EC=9D=98=20=EA=B9=A8?= =?UTF-8?q?=EC=A7=84=20=EC=83=81=EB=8C=80=20=EB=A7=81=ED=81=AC=20=EC=84=B8?= =?UTF-8?q?=20=EA=B0=9C=EB=A5=BC=20=EA=B3=A0=EC=B9=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit src/adapter/outbound/fileserver/README.md와 objectstorage/README.md는 저장소 루트 docs를 ../../../(= src/docs)로 가리켜 없는 파일을 열었다. ../../../../로 고쳤다. src/README.md는 커밋되지 않는 .env를 가리켰다. 커밋된 템플릿 .env.example로 바꾸고 복사해 .env로 쓴다고 적었다. 검증: python3 scripts/check-work-docs.py --links를 src, docs, README.md, .github에 돌려 깨진 링크 0(전에는 src에서 이 셋). lychee는 노트북·desktop에 없어 돌리지 못했다. --- src/README.md | 2 +- src/adapter/outbound/fileserver/README.md | 2 +- src/adapter/outbound/objectstorage/README.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/README.md b/src/README.md index 0159f9ac..d6eeec83 100644 --- a/src/README.md +++ b/src/README.md @@ -3,7 +3,7 @@ `src/` 는 Gradle 멀티모듈 루트입니다. 모듈 경계·의존 방향 규칙은 루트 [CLAUDE.md](../CLAUDE.md) 와 [AGENTS.md](../AGENTS.md), 모듈별 규칙은 각 모듈의 `CLAUDE.md` 가 SSOT 입니다. -이 문서는 [build.gradle](build.gradle) 과 [.env](.env) 의 코드 주석에서 덜어낸 **설정 항목 설명과 +이 문서는 [build.gradle](build.gradle) 과 [.env.example](.env.example)(복사해 `.env` 로 씀) 의 코드 주석에서 덜어낸 **설정 항목 설명과 결정 근거**를 모아둔 참조용 기록입니다. 두 파일에는 짧은 기능 주석과 "자세한 내용은 README 참조" 포인터만 남기고, "왜 이렇게 했나"는 여기서 풀어 설명합니다. diff --git a/src/adapter/outbound/fileserver/README.md b/src/adapter/outbound/fileserver/README.md index 5e71124d..dca317a9 100644 --- a/src/adapter/outbound/fileserver/README.md +++ b/src/adapter/outbound/fileserver/README.md @@ -10,7 +10,7 @@ verification reads that registry. Module rules live in [CLAUDE.md](CLAUDE.md). Transport, security, configuration and operations contracts live in `docs/fileserver/`. For the repository-level choice between this Fileserver platform and Object Storage, see -[`docs/storage-capability-boundary.md`](../../../docs/storage-capability-boundary.md). +[`docs/storage-capability-boundary.md`](../../../../docs/storage-capability-boundary.md). ## Activation diff --git a/src/adapter/outbound/objectstorage/README.md b/src/adapter/outbound/objectstorage/README.md index 97d73e0b..ed713659 100644 --- a/src/adapter/outbound/objectstorage/README.md +++ b/src/adapter/outbound/objectstorage/README.md @@ -11,7 +11,7 @@ in `docs/superpowers/specs/2026-07-28-objectstorage-production-capability-design evidence claims in `docs/registries/object-storage-readiness.yaml`. For when to use this capability rather than the HTTP Fileserver platform, see -[`docs/storage-capability-boundary.md`](../../../docs/storage-capability-boundary.md). +[`docs/storage-capability-boundary.md`](../../../../docs/storage-capability-boundary.md). ## Current readiness From ac3c6a81ebfc5693b28c2479afdc23061060e7f3 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Sat, 7 Nov 2026 01:10:31 +0900 Subject: [PATCH 30/71] =?UTF-8?q?docs(agents):=20=EC=BB=A4=EB=B0=8B=20?= =?UTF-8?q?=EC=98=88=EC=99=B8=EB=A5=BC=20brief=EA=B0=80=20=ED=97=88?= =?UTF-8?q?=EC=9A=A9=ED=95=9C=20=EA=B2=83=EB=A7=8C=20=ED=95=98=EB=8A=94=20?= =?UTF-8?q?=EB=AC=B8=EC=9E=A5=EC=9C=BC=EB=A1=9C=20=EB=A7=9E=EC=B6=98?= =?UTF-8?q?=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit "brief가 허용하면 자기 브랜치에만 commit·push한다"는 commit을 허용하면 push도 된다고 읽힐 수 있다. docs/work/README.md 4절과 루트 CLAUDE.md는 둘을 따로 허용한다. 문장을 "brief가 허용한 것만(commit과 push는 따로) 그 작업의 자기 브랜치에 한다"로 바꿨다. 검증: AGENTS.md 본문을 읽는 테스트는 없다(git grep으로 확인, 걸리는 것은 주석과 루트 표시용 파일 존재 확인뿐). --- AGENTS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index 8565f7d2..0509bd1b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -114,7 +114,7 @@ root `CLAUDE.md`는 작업을 시작할 때 읽는 지도이고, 이 목록을 변경한 경계와 런타임·보안·데이터 영향에 맞춰 설계·리뷰·검증 강도를 높인다. commit 정책은 모든 플랫폼에서 `human-only`이며 agent는 stage/commit/amend/push하지 않는다. -예외는 하나다: 작업 지시(brief)가 허용하면 그 작업의 자기 브랜치에만 commit·push한다. main 병합, +예외는 하나다: brief가 허용한 것만(commit과 push는 따로) 그 작업의 자기 브랜치에 한다. main 병합, 다른 브랜치 push, force push는 하지 않는다(`docs/work/README.md` 「커밋」). ## 강제 수준 From 6ec0c4f7fa0d806bc03487d75c70e333300a4281 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Sat, 7 Nov 2026 01:14:09 +0900 Subject: [PATCH 31/71] =?UTF-8?q?fix(migration):=20=EC=8B=A4=ED=8C=A8?= =?UTF-8?q?=ED=95=9C=20=EB=8F=99=EC=8B=9C=20=EC=9D=B8=EB=8D=B1=EC=8A=A4=20?= =?UTF-8?q?=EB=A7=88=EC=9D=B4=EA=B7=B8=EB=A0=88=EC=9D=B4=EC=85=98=20?= =?UTF-8?q?=EB=B3=B5=EA=B5=AC=EC=99=80=20=EA=B2=80=EC=82=AC=EA=B8=B0=20?= =?UTF-8?q?=EC=84=A4=EB=AA=85=EC=9D=84=20=EC=8B=A4=EC=A0=9C=20=EB=8F=99?= =?UTF-8?q?=EC=9E=91=EC=97=90=20=EB=A7=9E=EC=B6=98=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 (재리뷰 round7 영속성 RR7-03-01~05) - 실패한 동시 인덱스 마이그레이션의 복구를 가이드·검사기·학습 문서가 "DROP INDEX 하나"로 안내한다. Flyway는 트랜잭션 밖에서 실패한 버전의 이력 행(success = false)을 남기고, 다음 배포의 validate가 그 행 때문에 다시 멈춘다. runbook에는 이 경우가 없고 이력 수정은 금지다. docs/jpa/runbooks.md "An invalid index exists"도 같은 이유로 재적용에서 멈춘다. - 검사기 Javadoc·학습 문서가 "섞인 파일은 부분 적용되지 않는다"고 쓴다. 가이드가 요구하는 executeInTransaction=false를 붙이면 Flyway가 문장마다 커밋해 앞 문장이 남는다. - 가이드·검사기 Javadoc·실패 메시지·학습 문서가 "Flyway는 REINDEX … CONCURRENTLY를 트랜잭션 안에서 돌린다"고 쓴다. REINDEX SCHEMA|DATABASE CONCURRENTLY는 Flyway가 스스로 트랜잭션 밖에서 돌린다. - LockWaitMigrationInspector는 .sql.conf가 executeInTransaction=true면 SET LOCAL 뒤의 VACUUM FULL·REINDEX SCHEMA를 통과시킨다. Javadoc은 "늘 거부"라고 쓴다. - ledger 잠금 대기 IT가 동시 인덱스 파일을 "이 테스트에 예외로 적으라"고 안내하지만 예외를 적을 곳이 없다. 같은 원인으로 ledger의 다른 IT 두 개 (GrpcOperationLedgerPostgresIT, JpaGrpcOperationLedgerContractIT)도 모든 파일을 한 문자열로 실행해, 동시 인덱스 파일이 생기면 "cannot be executed within a pipeline"으로 실패한다. 고른 방법 - 복구(RR7-03-03): 소유자 결정(2026-11-06)대로 migration-failed.md에 "Recover a failed concurrent index migration" 절을 둔다. 진행 중 빌드 확인 → 무효 인덱스 DROP INDEX CONCURRENTLY → 원인 정리 → 그 버전의 실패 행만 DELETE → 재배포. "Do not"에 이 한 가지 예외를 적고 flyway repair는 계속 금지한다. SQL 세 블록에 runbook-sql 표시를 달고 postgresqlConcurrentIndexMigrationIntegrationTest가 runbook에서 읽어 실 PostgreSQL에서 돌린다(outbox runbook과 같은 방식). 가이드·검사기 Javadoc·메시지·학습 문서·jpa/runbooks.md는 그 절을 가리킨다. - 섞인 파일(RR7-03-04)·REINDEX(RR7-03-02): 문장을 고치고, 같은 IT와 잠금 대기 IT에 사실을 고정한다(섞인 파일 두 경우, REINDEX 다섯 형태). - 검사기(RR7-03-05): 트랜잭션 안에서 돌 수 없는 잠금 문장은 .sql.conf와 상관없이 거부한다(리뷰 권장안). 버린 안: Javadoc만 좁히기 — 그 파일은 PostgreSQL이 배포 때 25001로 거부하므로 검사기가 먼저 알려 주는 쪽이 맞다. 잠그지 않는 문장(plain VACUUM 등)은 이 검사기의 범위가 아니라 그대로 둔다. - ledger(RR7-03-01): IT에 RUN_OUTSIDE_A_TRANSACTION(파일 → 이유) 목록을 두고 잠금 대기 케이스에서 뺀다. 목록의 파일은 같은 IT가 동시 인덱스 문장 하나·executeInTransaction=false인지 ConcurrentIndexMigration Inspector로 본다. optional 빌드는 testkit에 의존할 수 없어 sharedMigrationFileSources가 그 파일과 MigrationResource를 복사한다 (VersionedMigrationFiles와 같은 방식). ledger IT 셋은 마이그레이션을 파일마다 따로 실행한다(Flyway처럼). 버린 안: 안내만 "다룰 수 없다"로 바꾸기 — 다음 동시 인덱스 파일이 생길 때 같은 질문이 다시 남는다. 위험·한계 - 검사기 변경으로 서비스의 자기 스트림 검사가 새로 실패할 수 있다. 걸리는 파일은 PostgreSQL이 배포 때 거부하는 파일뿐이라 배포된 적이 없다(업그레이드 안내 4.1에 적음). - runbook의 DELETE는 운영자가 version을 옮겨 적는다. NOT success라 성공한 행은 지우지 못하지만, 다른 버전의 실패 행을 잘못 적으면 그 행이 지워진다. 한 행만 지워야 하고 0행이면 다시 분류하라고 적었다. - ledger 복사 파일 두 개도 JDK만 써야 한다(각 Javadoc에 적음). - Spotless 검사는 같은 worktree에서 spotlessApply가 변경 없이 끝난 직후라 UP-TO-DATE로 처리됐다. 검증 (desktop, 공유 잠금, 로그 ~/r8-f3-logs/) RED — 기준 73d39212 + 이 커밋의 테스트(+ 기준 문서 주장을 단언하는 임시 메서드, + 임시 ledger V004): - persistence-jpa test --tests LockWaitMigrationInspectorTest: 80건 중 2건 실패, 검사기가 빈 목록(통과)을 돌려줌 (red-unit.log) - postgresqlMigrationLockWaitIntegrationTest: 47건 중 4건 실패 — 옛 주장 대로면 거부여야 할 REINDEX SCHEMA|DATABASE CONCURRENTLY가 applied, conf=true VACUUM FULL·REINDEX SCHEMA를 PostgreSQL은 25001로 거부하는데 검사기는 통과 (red2-lockwait.log) - postgresqlConcurrentIndexMigrationIntegrationTest: 9건 중 3건 실패 — 옛 절차(DROP INDEX) 뒤 재배포가 "Detected failed migration to version 2", conf를 붙인 섞인 파일이 행 3001·무효 인덱스·실패 이력을 남김, runbook 블록이 없어 복구 테스트 준비 실패(RED로 세지 않음) (red2-concurrent.log) - ledger integrationTest(V004 동시 인덱스): 6건 중 4건 실패 — 잠금 대기 IT "name it as an exception here", 다른 IT 둘 "cannot be executed within a pipeline" (red-ledger.log) GREEN — 이 커밋의 트리 b49369e7: - :adapter:outbound:persistence-jpa:check rc=0 (test 666건 실패 0), :testQualityCheck rc=0 - postgresqlMigrationLockWaitIntegrationTest rc=0 (42건 실패 0) - postgresqlConcurrentIndexMigrationIntegrationTest rc=0 (7건 실패 0) - -p optional-platforms :grpc:grpc-operation-ledger-jpa:check integrationTest testQualityCheck rc=0 (IT 3+2+42건 실패 0) - :app-bootstrap:documentContractTest rc=0 (66건 실패 0) - 두 빌드의 verifyStrictLaneStages --dry-run rc=0 - ledger 탐침(임시 V004): 목록에 없으면 잠금 대기 케이스만 실패하고 메시지가 RUN_OUTSIDE_A_TRANSACTION을 가리킴(48건 중 1건), 목록에 넣으면 rc=0, 목록에 넣고 SET LOCAL을 섞으면 목록 검사가 "mixes a concurrent index statement"로 거부 - python3 scripts/check-work-docs.py --links docs: 깨진 링크 0 Refs: docs/reviews/2026-11-03-rereview/round7/03-persistence.md --- docs/jpa/migration-guide.md | 46 ++++-- docs/jpa/runbooks.md | 6 +- docs/runbooks/migration-failed.md | 64 ++++++- docs/study/postgresql-jpa-walkthrough.ko.md | 49 ++++-- docs/upgrade/2026-11-maturity-review.md | 4 + .../outbound/persistence-jpa/build.gradle | 8 + .../readiness/OutboxRunbookSql.java | 5 +- ...ncurrentIndexMigrationIntegrationTest.java | 156 ++++++++++++++++++ ...reSqlMigrationLockWaitIntegrationTest.java | 70 +++++++- .../LockWaitMigrationInspectorTest.java | 23 +++ .../ConcurrentIndexMigrationInspector.java | 51 ++++-- .../migration/LockWaitMigrationInspector.java | 44 +++-- .../testkit/migration/MigrationResource.java | 3 + .../grpc-operation-ledger-jpa/build.gradle | 10 +- ...rpcOperationLedgerMigrationLockWaitIT.java | 85 +++++++++- .../ledger/GrpcOperationLedgerMigrations.java | 42 ++++- .../ledger/GrpcOperationLedgerPostgresIT.java | 8 +- .../JpaGrpcOperationLedgerContractIT.java | 8 +- 18 files changed, 587 insertions(+), 95 deletions(-) diff --git a/docs/jpa/migration-guide.md b/docs/jpa/migration-guide.md index e42b7ed1..9223d687 100644 --- a/docs/jpa/migration-guide.md +++ b/docs/jpa/migration-guide.md @@ -47,6 +47,10 @@ applied one, and the interesting question is which change is missing from this d makes that question unaskable. It exists only as an explicit admin operation with an operator, a reason, and an approval (design §8.4). +The one change to the history an operator makes is narrower than repair: after a concurrent index +migration fails, the failed row of that one version is deleted so that the version can run again +("Concurrent index builds" below). Every applied row, and its checksum, stays as it was. + Only Flyway's structured error codes reach the exception. Its messages embed the script path and part of the failing statement. @@ -84,7 +88,9 @@ Flyway's list: Flyway runs it in the transaction, PostgreSQL refuses it there, a `VACUUM FULL`, a non-concurrent `REINDEX SCHEMA|DATABASE|SYSTEM` — can never be bounded this way and does not belong in a migration: run it by hand as an operations step, outside a deploy, in a psql session that sets `SET lock_timeout = '5s';` first (the session ends with the step, so the plain -`SET` is the bound there). +`SET` is the bound there). A `.sql.conf` with `executeInTransaction=true` does not change that: it +keeps the statement and its `SET LOCAL` in the transaction only for PostgreSQL to refuse it at +deploy, and the inspector below refuses it as well. Enforced, not remembered: `LockWaitMigrationInspector` (persistence-jpa testkit) reads a script — and the `.sql.conf` beside it, as Flyway reads it (a properties file, `false` in any case), and @@ -112,18 +118,25 @@ optional build, which cannot depend on the testkit: its `GrpcOperationLedgerMigr runs every ledger migration after V001, read from the tree, against a held ledger instead, so its next migration is checked on real PostgreSQL. It finds and orders that tree with the testkit's own `VersionedMigrationFiles`, which the ledger's `build.gradle` copies into its integration-test sources -at build time (`sharedMigrationFileSources`), so both builds read one definition. The rule came from -V21 having the bound and V22, in the same commit, not having it (re-review 2026-11-03 round 2, +at build time (`sharedMigrationFileSources`), so both builds read one definition. A concurrent index +build in that tree runs outside a transaction and is no case for a held ledger: it goes in the +test's `RUN_OUTSIDE_A_TRANSACTION` with its reason, and the same test holds each file listed there to +`ConcurrentIndexMigrationInspector`, copied the same way ("Concurrent index builds"). Every ledger +lane applies the tree one file at a time, as Flyway does, so such a file is not refused inside the +implicit transaction of one string holding many. The rule came +from V21 having the bound and V22, in the same commit, not having it (re-review 2026-11-03 round 2, RR-02-09; round 3, RR3-02-01, RR3-02-03, RR3-02-04; round 4, RR4-02-01; round 6, RR6-03-02, -RR6-03-03). +RR6-03-03; round 7, RR7-03-01). ## Concurrent index builds `CREATE INDEX CONCURRENTLY`, `DROP INDEX CONCURRENTLY` and `REINDEX … CONCURRENTLY` cannot run -inside a transaction block. Flyway recognizes `CREATE`/`DROP INDEX CONCURRENTLY` and runs such a -script outside a transaction on its own (above), but not `REINDEX … CONCURRENTLY`, which it runs in -the transaction for PostgreSQL to refuse. Write the companion configuration for every concurrent -statement anyway, so the file says what it needs and no reader has to know Flyway's list: +inside a transaction block. Flyway runs a script outside a transaction on its own when it holds +`CREATE`/`DROP INDEX CONCURRENTLY` or `REINDEX SCHEMA|DATABASE`, with or without `CONCURRENTLY` +(above). It runs `REINDEX INDEX|TABLE … CONCURRENTLY` — `REINDEX (CONCURRENTLY) TABLE` included — in +the transaction, where PostgreSQL refuses it. `PostgreSqlMigrationLockWaitIntegrationTest` shows the +five forms on real PostgreSQL. Write the companion configuration for every concurrent statement +anyway, so the file says what it needs and no reader has to know Flyway's list: ```conf # V42__order_index.sql.conf @@ -144,9 +157,20 @@ open holds the build, and a file run outside a transaction cannot bound that wai Look for old transactions (`pg_stat_activity.xact_start`) before deploying one. The testkit's `ConcurrentIndexMigrationInspector` checks a script for this in a migration test -(nothing checks it at startup), and additionally requires the migration to contain nothing else. A failed concurrent build leaves an invalid index behind; -recovering is a single `DROP INDEX` when the migration did nothing else, and a manual reconstruction -of partial state when it did. +(nothing checks it at startup), and additionally requires the migration to contain nothing else. +Next to another statement, a concurrent one makes Flyway refuse the file before any of it runs when +nothing configures it; with `executeInTransaction=false` Flyway commits each statement on its own, +and a failed build leaves the statements before it applied — state to reconstruct by hand. + +Alone, a failed build leaves an invalid index and a history row with `success = false` for its +version, and Flyway refuses every later deploy ("Detected failed migration to version …") until that +row is gone: dropping the index is not enough. The recovery is +[migration-failed.md](../runbooks/migration-failed.md) "Recover a failed concurrent index migration": +confirm no build is running, drop the invalid index, remove the cause, delete that version's failed +row and nothing else, deploy again. It is not `flyway repair`, which would also rewrite the +remaining rows' checksums. `PostgreSqlConcurrentIndexMigrationIntegrationTest` +(`postgresqlConcurrentIndexMigrationIntegrationTest`) runs the runbook's SQL, read from the runbook, +after a unique build that failed on a duplicate, and shows both mixed files above. An invalid index is not merely useless — the planner ignores it while every write still maintains it. [runbooks.md](runbooks.md) has the query that finds them. Nothing drops them automatically: an diff --git a/docs/jpa/runbooks.md b/docs/jpa/runbooks.md index ad14f251..b77d3086 100644 --- a/docs/jpa/runbooks.md +++ b/docs/jpa/runbooks.md @@ -73,7 +73,11 @@ A concurrent build failed. The index is ignored by the planner and maintained by 1. Confirm no build is currently running. An in-progress build looks identical in the catalog. 2. Run `DROP INDEX CONCURRENTLY IF EXISTS ;` outside a migration. -3. Re-apply the index migration. +3. If a migration built it, Flyway recorded that version as failed (`success = false`) and refuses + every later deploy until that row is gone: dropping the index does not clear it. Follow + [migration-failed.md](../runbooks/migration-failed.md) "Recover a failed concurrent index + migration", which removes the cause and deletes that one row. +4. Re-apply the index migration. The platform does not drop these automatically: on a rolling deploy every instance would race to drop an index another instance was about to finish building. diff --git a/docs/runbooks/migration-failed.md b/docs/runbooks/migration-failed.md index a2988d75..1f40de1b 100644 --- a/docs/runbooks/migration-failed.md +++ b/docs/runbooks/migration-failed.md @@ -4,7 +4,7 @@ category: INTERNAL error_codes: [MIGRATION_FAILED] severity: P1 owner: oncall -last_updated: 2026-11-04 +last_updated: 2026-11-07 status: active --- @@ -63,6 +63,13 @@ status: active case — clean it up with `outbox-dead-letter.md` §8 and rerun, the migration stays as it is; - checksum mismatch: compare the deployed artifact with the already applied script before considering repair; + - a concurrent index migration failed (`CREATE [UNIQUE] INDEX CONCURRENTLY` or `REINDEX … + CONCURRENTLY` that Flyway ran outside a transaction): a duplicate value for a unique + index, a deadlock, `statement_timeout` or a cancelled build. Outside a transaction nothing + rolled back: the migration left an invalid index and a history row with + `success = false` for that version, and every later deploy fails validation ("Detected failed + migration to version …") until the row is gone. Dropping the index alone does not clear it. + Follow "Recover a failed concurrent index migration" below; - connection/TLS failure: fix transport or credentials without changing Flyway history. ## Action @@ -92,7 +99,9 @@ status: active Do not: - edit an already applied migration; -- delete or rewrite Flyway history to make validation green; +- delete or rewrite Flyway history to make validation green. The one exception is the failed row + of a failed concurrent index migration, deleted as "Recover a failed concurrent index migration" + below says — that row and nothing else; - run `flyway repair` before checksum provenance is proven and reviewed; - use `clean`, destructive rollback, or schema-wide restore as the first response; - mark a capability `ACTIVE` before its migration and adapter readiness succeed. @@ -101,6 +110,57 @@ If commit outcome was indeterminate during the failure, reconcile by the applica `OperationId`/idempotency reference before retrying business work. Never blind-retry a commit whose result is unknown. +## Recover a failed concurrent index migration + +The one case where this runbook changes Flyway history (owner decision, 2026-11-06). It applies to a +migration that holds a single concurrent index statement which Flyway ran outside a transaction — +with the `executeInTransaction=false` the guide asks for, or on its own for `CREATE`/`DROP INDEX +CONCURRENTLY` (`docs/jpa/migration-guide.md` "Concurrent index builds") — and whose row for this +version in the stream's history table says `success = false`. A migration that mixed other +statements in has already committed them: reconstruct that state with the database owner instead. + +1. Confirm no build is still running. An index that is still being built looks invalid in the + catalog too, and dropping it races the build. This query returns no rows when none is: + + +```sql +SELECT pid, relid::regclass AS table_name, index_relid::regclass AS index_name, phase +FROM pg_stat_progress_create_index +WHERE datname = current_database(); +``` + +2. Drop the invalid index the build left (`docs/jpa/runbooks.md` "An invalid index exists" lists + them). Run it on its own, not inside `BEGIN`: `CONCURRENTLY` refuses a transaction block. + + +```sql +DROP INDEX CONCURRENTLY IF EXISTS ; +``` + +3. Remove the cause. For a unique index, clean up the duplicate rows with the data owner (a forward + fix, never by editing the migration). For a deadlock or a timeout, end or wait out the + transaction that held the build. +4. Delete that version's failed row from the stream's history table, and nothing else. `` + is the `version` column of the failed row as the Diagnosis query shows it (`22.1` for + `V22_1__…`). It must delete exactly one row; if it deletes none, this is not the failure this + section is for, so classify it again. + + +```sql +DELETE FROM +WHERE version = '' AND NOT success; +``` + +5. Deploy again. Flyway runs the same migration from the start and builds the index. + +The failed row is the record of a version that never applied, so deleting it leaves the order and +the checksum of every applied version as they were. Do not use `flyway repair` for this: it also +rewrites the checksums and descriptions of the remaining rows to match the scripts on disk, which +removes the evidence a checksum mismatch carries. `:adapter:outbound:persistence-jpa:postgresqlConcurrentIndexMigrationIntegrationTest` +runs the three SQL blocks above, read from this file, against real PostgreSQL: a unique build fails +on a duplicate, steps 1–4 run, and the next deploy applies the version with the index valid and the +earlier version's checksum unchanged. + ## Escalation - P1 immediate: the required application revision cannot become ready. diff --git a/docs/study/postgresql-jpa-walkthrough.ko.md b/docs/study/postgresql-jpa-walkthrough.ko.md index 6e74af3d..6523ab89 100644 --- a/docs/study/postgresql-jpa-walkthrough.ko.md +++ b/docs/study/postgresql-jpa-walkthrough.ko.md @@ -1337,15 +1337,22 @@ startup 동작으로는 절대 아니다. ### 8.2 `ConcurrentIndexMigrationInspector` PostgreSQL은 `CREATE INDEX CONCURRENTLY`·`DROP INDEX CONCURRENTLY`·`REINDEX … CONCURRENTLY`를 -트랜잭션 블록 안에서 거부한다. Flyway 11은 `CREATE`/`DROP INDEX CONCURRENTLY`가 든 파일을 **스스로 -트랜잭션 밖에서** 돌린다. `REINDEX … CONCURRENTLY`는 모른다. 그 파일은 트랜잭션 안에서 돌고, 배포 때 -PostgreSQL이 거부한다. 그래서 검사기는 동시 인덱스 문장이 있으면 `.sql.conf`에 -`executeInTransaction=false`를 적으라고 요구한다. Flyway가 알아서 빼 주는 문장에도 적는다. 파일이 -자기에게 필요한 것을 스스로 말하게 하려는 것이다. +트랜잭션 블록 안에서 거부한다. Flyway 11은 `CREATE`/`DROP INDEX CONCURRENTLY`나 +`REINDEX SCHEMA|DATABASE`(`CONCURRENTLY`가 있든 없든)가 든 파일을 **스스로 트랜잭션 밖에서** 돌린다. +`REINDEX INDEX|TABLE … CONCURRENTLY`(`REINDEX (CONCURRENTLY) TABLE` 포함)는 모른다. 그 파일은 +트랜잭션 안에서 돌고, 배포 때 PostgreSQL이 거부한다. 다섯 형태를 실제 PostgreSQL에서 돌린 결과는 +`PostgreSqlMigrationLockWaitIntegrationTest`에 있다. 그래서 검사기는 동시 인덱스 문장이 있으면 +`.sql.conf`에 `executeInTransaction=false`를 적으라고 요구한다. Flyway가 알아서 빼 주는 문장에도 +적는다. 파일이 자기에게 필요한 것을 스스로 말하게 하려는 것이다. -> 다른 문장과 섞인 파일은 Flyway가 기본값(`mixed=false`)에서 **아무것도 실행하기 전에 거부**한다. -> 부분 적용은 일어나지 않는다. 그래도 한 파일에 하나만 두는 이유는 아래 `requireIsolatedStatement`의 -> 복구 때문이다. +> 다른 문장과 섞인 파일은 설정에 따라 결과가 다르다. +> +> - `.sql.conf`가 없으면 Flyway가 기본값(`mixed=false`)에서 **아무것도 실행하기 전에 거부**한다. +> - 검사기가 요구하는 `executeInTransaction=false`를 붙이면 Flyway가 **문장마다 따로 커밋**한다. +> 동시 빌드가 실패해도 그 앞 문장은 **이미 적용돼 남는다**(부분 적용). +> +> 그래서 동시 인덱스 문장은 한 파일에 하나만 둔다. 두 경우 모두 +> `PostgreSqlConcurrentIndexMigrationIntegrationTest`가 실제 PostgreSQL에서 보여 준다. 트랜잭션 밖에서도 동시 빌드는 **자기보다 먼저 시작한 트랜잭션이 모두 끝나기를 기다린다.** @@ -1366,18 +1373,32 @@ Flyway 기본값: 잠금 트랜잭션(열린 채) ──기다림──▶ 마 검사 대상: `CREATE [UNIQUE] INDEX CONCURRENTLY`, `DROP INDEX CONCURRENTLY`, `REINDEX … CONCURRENTLY` (`REINDEX (CONCURRENTLY) TABLE` 같은 괄호 옵션 포함). -`requireIsolatedStatement`도 있다 — concurrent 빌드가 실패하면 invalid index가 남고, 그 -복구는 마이그레이션이 다른 걸 아무것도 안 했으면 `DROP INDEX` 하나지만 뭔가 했으면 부분 -상태를 손으로 재구성해야 한다. +`requireIsolatedStatement`도 있다 — concurrent 빌드가 실패하면 invalid index와 그 버전의 +**실패 이력 행**(`success = false`)이 남는다. Flyway는 그 행이 있는 한 다음 배포를 validate에서 거부한다. +그래서 인덱스만 지우고 다시 배포하면 또 멈춘다. -`FailedConcurrentIndexRecovery`가 `pg_index.indisvalid = false`를 조회해서 리포트한다. -**자동으로 지우지 않는다.** +``` +실패한 동시 빌드 → invalid index + 실패 이력 행 + → 빌드가 아직 도는지 확인 → DROP INDEX CONCURRENTLY → 원인 정리(중복 행 등) + → 그 버전의 실패 이력 행만 DELETE → 다시 배포 +``` + +- 절차와 SQL은 `docs/runbooks/migration-failed.md` "Recover a failed concurrent index migration"에 있다. + `PostgreSqlConcurrentIndexMigrationIntegrationTest`가 그 SQL을 runbook에서 읽어 실제 PostgreSQL에서 돌린다. +- 실패 이력 행을 지우는 것은 "이력을 고치지 않는다"의 하나뿐인 예외다(소유자 결정 2026-11-06). + 실패 행은 적용되지 않은 버전의 기록이라, 지워도 성공한 버전의 순서와 checksum은 그대로다. +- `flyway repair`는 여전히 쓰지 않는다. 남은 행의 checksum·설명까지 디스크의 스크립트에 맞춰 다시 쓰기 때문이다. +- 마이그레이션이 다른 문장도 담고 있었으면 그 문장은 이미 커밋돼 있다. 부분 상태를 손으로 재구성해야 한다. + +invalid index를 찾는 쿼리는 `docs/jpa/runbooks.md` "An invalid index exists"에 있다(예전의 +`FailedConcurrentIndexRecovery` 클래스는 호출자가 없어 지웠고, 이 쿼리가 대신한다). +플랫폼은 invalid index를 **자동으로 지우지 않는다.** > invalid index는 **빌드가 아직 돌고 있다**는 뜻일 수도 있고, 카탈로그만으로는 둘을 구별할 수 > 없다. 자동 drop은 곧 끝나려던 concurrent 빌드와 경주하게 되고, rolling deploy의 모든 > 인스턴스에서 동시에 그렇게 한다. -리포트는 운영자가 돌릴 statement를 준다(그 자체가 non-transactional인 `DROP INDEX CONCURRENTLY`). +지우는 문장은 운영자가 직접 돌린다(그 자체가 트랜잭션 밖에서만 도는 `DROP INDEX CONCURRENTLY`). ### 8.3 실제 마이그레이션 트리 — 8개 독립 스트림 diff --git a/docs/upgrade/2026-11-maturity-review.md b/docs/upgrade/2026-11-maturity-review.md index 7a0f1509..73a3f76d 100644 --- a/docs/upgrade/2026-11-maturity-review.md +++ b/docs/upgrade/2026-11-maturity-review.md @@ -155,6 +155,9 @@ `GRANT … REFERENCES ON`과 `REINDEX (CONCURRENTLY) …`는 더 이상 거부하지 않는다. 자기 스트림 검사가 새로 실패하면 그 파일은 Flyway가 거부하거나(`mixed=false`) 상한 없이 도는(`mixed=true`) 파일이다. 아직 배포 전이면 문장을 나누고, 이미 배포했으면 규칙 이전 목록에 더한다(r9, 재리뷰 RR4-02-01). + 재리뷰 round7(RR7-03-05) 수정부터는 `.sql.conf`가 `executeInTransaction=true`를 정한 파일의 `VACUUM FULL`·비동시 + `REINDEX SCHEMA|DATABASE|SYSTEM`도 앞의 `SET LOCAL`과 상관없이 같은 이유로 거부한다. 그런 파일은 PostgreSQL이 배포 때 + `25001`로 거부하므로 배포된 적이 없다. 새로 걸리면 그 문장을 마이그레이션에서 빼 운영 절차로 옮긴다. - **번호 충돌**: 템플릿이 이제 postgresql V20~V22, notification V11~V13, sample V8_1, grpc V002·V003을 쓴다. 파생 서비스가 같은 위치에 같은 번호를 두었다면 Flyway가 같은 버전 두 개로 실패한다. 자기 마이그레이션은 템플릿과 떨어진 번호대로 옮긴다 (이미 적용된 파일 이름을 바꾸면 checksum·history가 어긋나므로 운영 DB에 적용된 것이면 DB 담당과 정한다). @@ -245,6 +248,7 @@ V21 실패의 분류는 `docs/runbooks/migration-failed.md` "Classify the failur | 서버 로그(GraphQL·gRPC·STOMP) | carrier로 답한 실패를 web과 같은 줄(shared-contract `ServerFailureLog`)로 ERROR에 남긴다: persistence 실패는 분류만, 5xx carrier는 예외와 함께, 4xx carrier는 남기지 않는다. gRPC는 ` (method=…)`, GraphQL은 ` (executionId=…)`를 붙인다. gRPC는 인식 못 한 실패(`INTERNAL_ERROR`)도 `unhandled failure on …`로 남긴다. 클라이언트가 취소한 호출은 남기지 않고, 서비스가 `CANCELLED` status로 끝낸 살아 있는 호출은 남긴다. raw status는 넘겼든 던졌든 설명을 남기지 않는다(원인 예외가 있으면 그것만 붙인다). `IllegalArgumentException`(`BAD_PARAMETER`)은 web과 같은 WARN 한 줄 `request refused as BAD_PARAMETER by <예외 타입>`(메시지 없음)으로 남긴다. STOMP `@MessageMapping` 실패는 Spring의 `Unhandled exception from message handler method`(예외 전체) 대신 같은 줄로 남는다 | ERROR 로그가 늘어난다(전에는 gRPC가 아무것도 남기지 않았다). GraphQL·gRPC·STOMP는 잘못된 입력마다 WARN 한 줄이 생긴다. STOMP에서 Spring 문구로 경보를 걸었다면 고친다. `IDEMPOTENCY_RECOVERY_REQUIRED`의 scope digest를 모든 전송에서 찾을 수 있다(`docs/runbooks/idempotency-unavailable.md`) | r9 · `src/shared-contract/.../error/ServerFailureLog.java`, `GrpcExceptionHandlingInterceptor.java`, `GraphQlWireErrorMapper.java`, `StompHandlerFailureLog.java` | | sample-portfolio | 익명 쓰기 401, 포스터 제목 대소문자 무시 유일(409 `POSTER_ALREADY_EXISTS`), 관리자도 남의 work log 수정 불가, 샘플 이벤트 tenant `global` | sample을 남긴 서비스만 | `34565130`, `1400dc15` | | Flyway 잠금 | Flyway의 PostgreSQL 마이그레이션 잠금을 트랜잭션 대신 세션에 둔다. Spring Boot의 Flyway는 module-defaults `spring.flyway.postgresql.transactional-lock: false`, 템플릿이 직접 만드는 Flyway(멱등성·알림·sample stream, schema-per-tenant, testkit `MigrationContractRunner`)는 `FlywaySchemaPolicy.configure()`, messaging inbox stream은 같은 값을 직접 넣는다. 운영 코드의 `Flyway.configure()` 직접 호출은 `JpaProductionArchitectureTest`가 거부한다 | Flyway 기본값에서는 동시 인덱스 마이그레이션이 Flyway 자신의 열린 트랜잭션을 기다려 끝나지 않았다. 이제 끝난다. 마이그레이션은 잠금을 잡은 연결 하나로 돈다. transaction 모드 PgBouncer 뒤에서는 잠금 해제가 다른 서버 연결로 가 다음 배포가 기다릴 수 있으니 마이그레이션은 직접 연결이나 session 모드 pool로 돌린다. 배포 도구는 이 repo 밖이라 2절 15번으로 맞춘다 | 재리뷰 round6 RR6-03-01 · `persistence-jpa.yml`, `.../migration/FlywaySchemaPolicy.java`, `docs/jpa/migration-guide.md` "Who may change the schema"·"Concurrent index builds" | +| 실패한 동시 인덱스 마이그레이션 복구 | `docs/runbooks/migration-failed.md`에 「Recover a failed concurrent index migration」을 더했다: 진행 중인 빌드가 없는지 보고, 무효 인덱스를 `DROP INDEX CONCURRENTLY`로 지우고, 원인을 정리하고, 그 버전의 실패 이력 행(`success = false`)만 지운 뒤 다시 배포한다. 「Do not」의 이력 수정 금지에 이 한 가지 예외를 적었다. `flyway repair`는 계속 쓰지 않는다 | 전에는 안내가 "`DROP INDEX` 하나"였고, 그대로 하면 남은 실패 이력 때문에 다음 배포가 validate에서 다시 멈췄다. 동시 인덱스 마이그레이션을 쓰는 서비스의 운영자는 이 절차로 복구한다 | 재리뷰 round7 RR7-03-03, 소유자 결정 2026-11-06 · `docs/jpa/migration-guide.md` "Concurrent index builds", `PostgreSqlConcurrentIndexMigrationIntegrationTest` | | 성능 lane(HTTP client·Mongo) | httpclient `LargeBodyResourceTest`의 힙 상한(32 MiB 스트리밍 중 힙 증가 16 MiB 미만)을 매번 단언한다. 전에는 `-Pperformance.assertions.enabled=true`일 때만 단언하고 아니면 건너뛴다는 줄만 찍었다. Mongo `MongoResourceBudgetLaneTest`는 표준 gate 전체(p99 500ms, pool 대기 250ms, 힙 512 MiB, examined/returned 10, spill 금지)를 Gradle 밖 실행에서도 단언한다(B-43) | 손으로 돌린 `performanceCheck`가 상한을 실제로 재므로, 전에는 통과하던 느린 기계에서 실패할 수 있다 | B4(2026-11-06) · `LargeBodyResourceTest`, `MongoResourceBudgetLaneTest` | | 보안 필터 로그 레벨 | 보안 필터(`AuthErrorResponseWriter`)의 `security failure` 줄을 5xx(`AUTH_JWKS_UNAVAILABLE` 503, `INTERNAL_AUTH_MISCONFIGURATION` 500)면 ERROR, 4xx면 WARN으로 남긴다. 전에는 모두 WARN이었다. 다른 경로가 5xx를 ERROR로 남기는 규칙(`ServerFailureLog`)과 같아졌다 | ERROR로 거르는 로그 경보·대시보드에 JWKS 장애와 인증 설정 오류가 새로 잡힌다. 401·403은 그대로 WARN | 설계 메모 2026-11-06 7절 결정 2 · `src/adapter/inbound/web/.../auth/AuthErrorResponseWriter.java`, `docs/superpowers/specs/2026-11-06-error-code-log-level-design.md` | diff --git a/src/adapter/outbound/persistence-jpa/build.gradle b/src/adapter/outbound/persistence-jpa/build.gradle index 2061a83f..5d5abe27 100644 --- a/src/adapter/outbound/persistence-jpa/build.gradle +++ b/src/adapter/outbound/persistence-jpa/build.gradle @@ -265,6 +265,14 @@ strictTestLanes { } } +// The recovery of a failed concurrent index migration (re-review 2026-11-03 round 7, RR7-03-03) is +// SQL the migration runbook gives an operator; the lane reads it out of the runbook the same way. +tasks.named('postgresqlConcurrentIndexMigrationIntegrationTest', Test) { + def migrationFailedRunbook = new File(rootProject.projectDir.parentFile, 'docs/runbooks/migration-failed.md') + inputs.file(migrationFailedRunbook).withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName('migrationFailedRunbook') + systemProperty 'migration.failed.runbook', migrationFailedRunbook.absolutePath +} + tasks.named('postgresqlSecurityBaselineIntegrationTest') { // Cross-leaf task edge: see the handoff. verifyCleanArchitectureDependencies inspects // configurations, not the task graph, so this edge is invisible to it. diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/OutboxRunbookSql.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/OutboxRunbookSql.java index 395ffcc9..0d2556dc 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/OutboxRunbookSql.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/OutboxRunbookSql.java @@ -7,7 +7,8 @@ import java.nio.file.Path; import java.util.Map; /** - * The SQL an outbox runbook gives an operator, read out of the runbook itself. + * The SQL a runbook gives an operator, read out of the runbook itself: the outbox runbooks, and the + * migration runbook's recovery of a failed concurrent index migration. * *

    A runbook block is marked {@code } and followed by a {@code sql} * fence. The lanes that run these blocks against real PostgreSQL read them from the document rather @@ -48,7 +49,7 @@ final class OutboxRunbookSql { String marker = ""; int at = runbook.indexOf(marker); if (at < 0) { - throw new IllegalStateException("the outbox runbook has no SQL block marked " + id); + throw new IllegalStateException("the runbook has no SQL block marked " + id); } int open = runbook.indexOf("```sql\n", at); int close = runbook.indexOf("\n```", open + 1); diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlConcurrentIndexMigrationIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlConcurrentIndexMigrationIntegrationTest.java index ef691bd0..33b1a78f 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlConcurrentIndexMigrationIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlConcurrentIndexMigrationIntegrationTest.java @@ -14,6 +14,7 @@ import java.sql.SQLException; import java.time.Duration; import java.util.List; import java.util.Locale; +import java.util.Map; import java.util.UUID; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; @@ -24,6 +25,8 @@ import java.util.concurrent.TimeoutException; import javax.sql.DataSource; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; @@ -53,6 +56,14 @@ import org.springframework.jdbc.datasource.DelegatingDataSource; * way every Flyway this template constructs itself does ({@link FlywaySchemaPolicy#configure()}). A * deploy still waiting after {@link #FINISHES_WITHIN} is cancelled, which leaves the invalid index * an interrupted build leaves in production too. + * + *

    Three more cases pin what happens when such a deploy fails (re-review 2026-11-03 round 7, + * RR7-03-03 and RR7-03-04). A concurrent build next to another statement is refused before any of + * it runs when nothing configures the file, and is left half applied when {@code + * executeInTransaction=false} does: Flyway commits each statement on its own. A failed build leaves + * an invalid index and a failed history row, and the deploy after it is refused until the row is + * gone: the recovery case runs the SQL of {@code docs/runbooks/migration-failed.md} ("A concurrent + * index migration failed"), read out of the runbook itself, and deploys again. */ class PostgreSqlConcurrentIndexMigrationIntegrationTest { @@ -64,6 +75,23 @@ class PostgreSqlConcurrentIndexMigrationIntegrationTest { INSERT INTO probe SELECT g, 'note ' || g FROM generate_series(1, 1000) AS g; """; + /** A second row with row 1's note, so that a unique index on the note cannot be built. */ + private static final String DUPLICATE_NOTE = + "INSERT INTO probe (id, note) VALUES (2001, 'note 1');\n"; + + private static final String UNIQUE_NOTE_INDEX = + "CREATE UNIQUE INDEX CONCURRENTLY ix_probe_note_u ON probe (note)"; + + /** A concurrent build after another statement, the file the guide says not to write. */ + private static final String MIXED = + "INSERT INTO probe (id, note) VALUES (3001, 'partial');\n" + UNIQUE_NOTE_INDEX + ";\n"; + + private static final String FLYWAY_REFUSES_A_MIXED_MIGRATION = + "Detected both transactional and non-transactional statements"; + + /** The system property naming {@code docs/runbooks/migration-failed.md} for this lane. */ + private static final String MIGRATION_FAILED_RUNBOOK = "migration.failed.runbook"; + private static PostgreSqlReadinessSupport postgres; @BeforeAll @@ -126,6 +154,103 @@ class PostgreSqlConcurrentIndexMigrationIntegrationTest { } } + @Test + @DisplayName("설정 파일 없이 동시 인덱스 문장과 다른 문장을 섞은 마이그레이션은 Flyway가 아무것도 실행하기 전에 거부한다") + void aMixedMigrationWithoutConfigurationIsRefusedBeforeAnyOfItRuns(@TempDir Path stream) + throws Exception { + try (HikariDataSource database = postgres.createDatabase(databaseName())) { + // given + Files.writeString(stream.resolve("V1__probe.sql"), FIRST_RELEASE + DUPLICATE_NOTE); + migrateTheWayTheTemplateDoes(database, stream); + Files.writeString(stream.resolve("V2__mixed.sql"), MIXED); + + // when + Throwable thrown = catchThrowable(() -> migrateTheWayTheTemplateDoes(database, stream)); + + // then + assertThat( + List.of( + String.valueOf(thrown).contains(FLYWAY_REFUSES_A_MIXED_MIGRATION), + aftermath(database))) + .containsExactly( + true, "row 3001 0, indexes [ix_probe_id true, probe_pkey true], history [1 true]"); + } + } + + @Test + @DisplayName( + "executeInTransaction=false를 붙여 섞은 마이그레이션은 앞 문장을 커밋한 채 동시 빌드에서 실패해 부분 적용, 무효 인덱스, 실패 이력을 남긴다") + void aMixedMigrationMarkedOutsideATransactionIsLeftHalfApplied(@TempDir Path stream) + throws Exception { + try (HikariDataSource database = postgres.createDatabase(databaseName())) { + // given + Files.writeString(stream.resolve("V1__probe.sql"), FIRST_RELEASE + DUPLICATE_NOTE); + migrateTheWayTheTemplateDoes(database, stream); + Files.writeString(stream.resolve("V2__mixed.sql"), MIXED); + Files.writeString(stream.resolve("V2__mixed.sql.conf"), "executeInTransaction=false\n"); + + // when + Throwable thrown = catchThrowable(() -> migrateTheWayTheTemplateDoes(database, stream)); + + // then + assertThat(List.of(thrown != null, aftermath(database))) + .containsExactly( + true, + "row 3001 1, indexes [ix_probe_id true, ix_probe_note_u false, probe_pkey true]," + + " history [1 true, 2 false]"); + } + } + + @Test + @DisplayName( + "실패한 동시 인덱스 마이그레이션은 runbook 절차(빌드 확인, 무효 인덱스 삭제, 원인 정리, 그 버전의 실패 이력 행 삭제) 뒤 다시 배포하면 적용된다") + void aFailedConcurrentIndexMigrationIsRecoveredByTheRunbookProcedure(@TempDir Path stream) + throws Exception { + OutboxRunbookSql runbook = OutboxRunbookSql.fromSystemProperty(MIGRATION_FAILED_RUNBOOK); + try (HikariDataSource database = postgres.createDatabase(databaseName())) { + // given + Files.writeString(stream.resolve("V1__probe.sql"), FIRST_RELEASE + DUPLICATE_NOTE); + migrateTheWayTheTemplateDoes(database, stream); + String checksumOfV1 = checksumOf(database, "1"); + writeConcurrentMigration(stream, UNIQUE_NOTE_INDEX); + Throwable failed = catchThrowable(() -> migrateTheWayTheTemplateDoes(database, stream)); + String afterFailure = aftermath(database); + JdbcTemplate jdbc = new JdbcTemplate(database); + + // when + List> buildsRunning = + jdbc.queryForList(runbook.block("failed-concurrent-index-builds")); + jdbc.execute( + runbook.block( + "failed-concurrent-index-drop", Map.of("invalid_index", "ix_probe_note_u"))); + jdbc.execute("DELETE FROM probe WHERE id = 2001"); + jdbc.execute( + runbook.block( + "failed-concurrent-index-history-row", + Map.of("owned_history_table", "flyway_schema_history", "version", "2"))); + Throwable again = catchThrowable(() -> migrateTheWayTheTemplateDoes(database, stream)); + + // then + assertThat( + List.of( + failed != null, + afterFailure, + buildsRunning.size(), + String.valueOf(again), + aftermath(database), + checksumOf(database, "1"))) + .containsExactly( + true, + "row 3001 0, indexes [ix_probe_id true, ix_probe_note_u false, probe_pkey true]," + + " history [1 true, 2 false]", + 0, + "null", + "row 3001 0, indexes [ix_probe_id true, ix_probe_note_u true, probe_pkey true]," + + " history [1 true, 2 true]", + checksumOfV1); + } + } + /** V2: the one concurrent statement, with the companion configuration the guide asks for. */ private static void writeConcurrentMigration(Path stream, String statement) throws IOException { Files.writeString(stream.resolve("V2__concurrent_index.sql"), statement + ";\n"); @@ -222,6 +347,37 @@ class PostgreSqlConcurrentIndexMigrationIntegrationTest { return "version " + version + ", indexes valid " + valid; } + /** + * What a deploy left behind: whether the row the mixed V2 inserts first is there, every index on + * the table with whether it is valid, and every history row with whether it succeeded. + */ + private static String aftermath(DataSource database) { + JdbcTemplate jdbc = new JdbcTemplate(database); + Integer row = jdbc.queryForObject("SELECT count(*) FROM probe WHERE id = 3001", Integer.class); + List indexes = + jdbc.queryForList( + "SELECT c.relname || ' ' || i.indisvalid FROM pg_index i" + + " JOIN pg_class c ON c.oid = i.indexrelid" + + " WHERE i.indrelid = 'probe'::regclass ORDER BY c.relname COLLATE \"C\"", + String.class); + List history = + jdbc.queryForList( + "SELECT coalesce(version, '-') || ' ' || success FROM flyway_schema_history" + + " ORDER BY installed_rank", + String.class); + return "row 3001 " + row + ", indexes " + indexes + ", history " + history; + } + + /** The checksum the history holds for a successful version. */ + private static String checksumOf(DataSource database, String version) { + return String.valueOf( + new JdbcTemplate(database) + .queryForObject( + "SELECT checksum FROM flyway_schema_history WHERE version = ? AND success", + Integer.class, + version)); + } + private static String databaseName() { return "concurrent_" + UUID.randomUUID().toString().replace("-", "").toLowerCase(Locale.ROOT); } diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlMigrationLockWaitIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlMigrationLockWaitIntegrationTest.java index c0a730d7..2f3b0e53 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlMigrationLockWaitIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlMigrationLockWaitIntegrationTest.java @@ -53,6 +53,13 @@ import org.springframework.jdbc.core.JdbcTemplate; * LockWaitMigrationInspectorTest}, which pins Flyway's own patterns in the pull request's {@code * ci} (round 6, RR6-03-03). * + *

    Two more cases pin what the documents say about the edges of that list (round 7, RR7-03-02 and + * RR7-03-05): Flyway runs {@code REINDEX INDEX|TABLE ... CONCURRENTLY} in the transaction, where + * PostgreSQL refuses it, but {@code REINDEX SCHEMA|DATABASE ... CONCURRENTLY} outside one on its + * own; and a {@code VACUUM FULL} or {@code REINDEX SCHEMA} that a {@code .sql.conf} keeps in the + * transaction ({@code executeInTransaction=true}) is refused by PostgreSQL at deploy, and by the + * inspector before it. + * *

    The migrations run under the template's Flyway settings ({@code FlywaySchemaPolicy}), whose * PostgreSQL lock is held for the session rather than in an open transaction (RR6-03-01): the bound * is shown under the lock the deploy actually takes. @@ -231,15 +238,26 @@ class PostgreSqlMigrationLockWaitIntegrationTest { } } - @Test + @ParameterizedTest + @CsvSource( + delimiter = '|', + value = { + "REINDEX TABLE CONCURRENTLY probe | refused 25001", + "REINDEX INDEX CONCURRENTLY probe_pkey | refused 25001", + "REINDEX (CONCURRENTLY) TABLE probe | refused 25001", + "REINDEX SCHEMA CONCURRENTLY public | applied", + "REINDEX DATABASE CONCURRENTLY | applied" + }) @DisplayName( - "Flyway는 REINDEX TABLE CONCURRENTLY를 트랜잭션 안에서 돌려 PostgreSQL이 거부하므로 executeInTransaction=false가 필요하다") - void flywayRunsReindexConcurrentlyInATransactionWherePostgresqlRefusesIt(@TempDir Path stream) - throws Exception { - try (HikariDataSource database = postgres.createDatabase(databaseName())) { + "Flyway는 REINDEX INDEX·TABLE … CONCURRENTLY를 트랜잭션 안에서 돌려 PostgreSQL이 거부하고, REINDEX SCHEMA·DATABASE … CONCURRENTLY는 스스로 트랜잭션 밖에서 돌린다") + void flywayRunsOnlyReindexIndexOrTableConcurrentlyInATransactionWherePostgresqlRefusesIt( + String statement, String expected, @TempDir Path stream) throws Exception { + String name = databaseName(); + try (HikariDataSource database = postgres.createDatabase(name)) { // given new JdbcTemplate(database).execute("CREATE TABLE probe (id INT PRIMARY KEY)"); - Files.writeString(stream.resolve("V1__reindex.sql"), "REINDEX TABLE CONCURRENTLY probe;\n"); + Files.writeString( + stream.resolve("V1__reindex.sql"), statement.replace("", name) + ";\n"); Flyway flyway = FlywaySchemaPolicy.configure() .dataSource(database) @@ -250,9 +268,47 @@ class PostgreSqlMigrationLockWaitIntegrationTest { // when Throwable thrown = catchThrowable(flyway::migrate); + String outcome = + thrown == null ? "applied" : "refused " + new Attempt(thrown, Duration.ZERO).sqlState(); // then - assertThat(new Attempt(thrown, Duration.ZERO).sqlState()).isEqualTo(ACTIVE_SQL_TRANSACTION); + assertThat(outcome).as("%s (%s)", statement, thrown).isEqualTo(expected); + } + } + + @ParameterizedTest + @ValueSource(strings = {"VACUUM FULL probe", "REINDEX SCHEMA public"}) + @DisplayName( + "executeInTransaction=true로 트랜잭션 안에 둔 VACUUM FULL·REINDEX SCHEMA는 PostgreSQL이 배포 때 거부하고 검사기도 거부한다") + void aLockingStatementAConfigurationKeepsInATransactionIsRefusedByPostgresqlAndTheInspector( + String statement, @TempDir Path stream) throws Exception { + try (HikariDataSource database = postgres.createDatabase(databaseName())) { + // given + new JdbcTemplate(database).execute("CREATE TABLE probe (id INT PRIMARY KEY)"); + Path script = + Files.writeString( + stream.resolve("V1__probe.sql"), + "SET LOCAL lock_timeout = '5s';\n" + statement + ";\n"); + Files.writeString(stream.resolve("V1__probe.sql.conf"), "executeInTransaction=true\n"); + Flyway flyway = + FlywaySchemaPolicy.configure() + .dataSource(database) + .locations("filesystem:" + stream.toAbsolutePath()) + .baselineOnMigrate(true) + .baselineVersion("0") + .load(); + + // when + Throwable thrown = catchThrowable(flyway::migrate); + List named = new LockWaitMigrationInspector().unboundedLockingStatements(script); + + // then + assertThat( + List.of( + String.valueOf(new Attempt(thrown, Duration.ZERO).sqlState()), + named.toString().contains("cannot run in a transaction"))) + .as("%s: Flyway %s, inspector %s", statement, thrown, named) + .containsExactly(ACTIVE_SQL_TRANSACTION, true); } } diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/LockWaitMigrationInspectorTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/LockWaitMigrationInspectorTest.java index 4cc49c68..8f2cf4ad 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/LockWaitMigrationInspectorTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/LockWaitMigrationInspectorTest.java @@ -381,6 +381,29 @@ class LockWaitMigrationInspectorTest { assertThat(unbounded).isEmpty(); } + @ParameterizedTest + @ValueSource( + strings = { + "SET LOCAL lock_timeout = '5s';\nVACUUM FULL outbox_event;", + "SET LOCAL lock_timeout = '5s';\nREINDEX SCHEMA public;" + }) + @DisplayName("executeInTransaction=true 설정이 있어도 트랜잭션 안에서 돌 수 없는 잠금 문장은 마이그레이션에 두지 말라는 이유로 거부된다") + void aLockingStatementThatCannotRunInATransactionIsRefusedWhateverTheConfigurationSays( + String sql, @TempDir Path stream) throws IOException { + // given + Path script = Files.writeString(stream.resolve("V99__change.sql"), sql); + Files.writeString(stream.resolve("V99__change.sql.conf"), "executeInTransaction=true\n"); + + // when + List unbounded = inspector.unboundedLockingStatements(script); + + // then + assertThat(unbounded) + .singleElement(STRING) + .contains("cannot run in a transaction") + .contains("executeInTransaction=true"); + } + /** Every static {@link Pattern} the class declares, by field name. */ private static Map staticPatterns(Class type) throws IllegalAccessException { Map patterns = new TreeMap<>(); diff --git a/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/ConcurrentIndexMigrationInspector.java b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/ConcurrentIndexMigrationInspector.java index b5615b69..7905f8b9 100644 --- a/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/ConcurrentIndexMigrationInspector.java +++ b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/ConcurrentIndexMigrationInspector.java @@ -10,19 +10,35 @@ import java.util.regex.Pattern; * *

    PostgreSQL refuses {@code CREATE INDEX CONCURRENTLY}, {@code DROP INDEX CONCURRENTLY} and * {@code REINDEX ... CONCURRENTLY} inside a transaction block. Flyway 11 runs a script outside its - * transaction on its own when it holds {@code CREATE} or {@code DROP INDEX CONCURRENTLY}, but not - * {@code REINDEX ... CONCURRENTLY}: that one Flyway runs in the transaction, and PostgreSQL refuses - * it at deploy. So {@link #validate} wants {@code executeInTransaction=false} beside every - * concurrent statement, whether Flyway would detect it or not. Next to any other statement, one - * Flyway runs outside a transaction makes Flyway refuse the whole script before it runs any of it - * (its default {@code mixed=false}); {@link #requireIsolatedStatement} wants the statement alone so - * that a failed build is recovered by dropping one invalid index. + * transaction on its own when it holds {@code CREATE} or {@code DROP INDEX CONCURRENTLY}, or {@code + * REINDEX SCHEMA|DATABASE} with or without {@code CONCURRENTLY}. It runs {@code REINDEX INDEX|TABLE + * ... CONCURRENTLY} — the option-list form {@code REINDEX (CONCURRENTLY) TABLE} included — in the + * transaction, and PostgreSQL refuses it at deploy ({@code + * postgresqlMigrationLockWaitIntegrationTest} shows the five forms; re-review 2026-11-03 round 7, + * RR7-03-02). So {@link #validate} wants {@code executeInTransaction=false} beside every concurrent + * statement, whether Flyway would detect it or not. + * + *

    {@link #requireIsolatedStatement} wants the statement alone in its migration. Next to another + * statement it is refused by Flyway before any of the script runs when nothing configures the file + * (Flyway's default {@code mixed=false}); with the {@code executeInTransaction=false} that {@link + * #validate} asks for, Flyway runs and commits each statement on its own, and a failed build leaves + * the statements before it applied (round 7, RR7-03-04). Alone, a failed build leaves an invalid + * index and its version's failed history row, which Flyway refuses the next deploy over until the + * row is gone: {@code docs/runbooks/migration-failed.md} ("Recover a failed concurrent index + * migration") drops the index and deletes that one row ({@code + * postgresqlConcurrentIndexMigrationIntegrationTest} runs it; round 7, RR7-03-03). * *

    Outside a transaction, {@code CREATE INDEX CONCURRENTLY} and {@code REINDEX ... CONCURRENTLY} * still wait for every transaction older than themselves. They finish because the template's Flyway * holds its PostgreSQL lock for the session ({@code FlywaySchemaPolicy.configure()}): under * Flyway's default the lock's own open transaction is one of those, and the deploy never ends * (re-review 2026-11-03 round 6, RR6-03-01 and RR6-03-05). + * + *

    The gRPC ledger's lane uses it too. It lives in the optional build, which cannot depend on + * this testkit, so {@code grpc-operation-ledger-jpa} compiles this file and {@link + * MigrationResource} from here into its integration-test sources at build time (its {@code + * build.gradle}, {@code sharedMigrationFileSources}; round 7, RR7-03-01). Hence the rule for both + * files: the JDK only, nothing else from this testkit. */ public final class ConcurrentIndexMigrationInspector { @@ -53,8 +69,8 @@ public final class ConcurrentIndexMigrationInspector { throw new IllegalStateException( migration.name() + " must set executeInTransaction=false: PostgreSQL refuses a concurrent index" - + " statement inside a transaction block, and Flyway runs REINDEX ... CONCURRENTLY in" - + " one unless the migration says otherwise"); + + " statement inside a transaction block, and Flyway runs REINDEX INDEX|TABLE ..." + + " CONCURRENTLY in one unless the migration says otherwise"); } /** Whether the script contains a statement PostgreSQL forbids inside a transaction. */ @@ -68,9 +84,12 @@ public final class ConcurrentIndexMigrationInspector { /** * Fails when a concurrent-index migration also contains other statements. * - *

    A concurrent index build can fail and leave an invalid index behind. Recovering from that is - * a single {@code DROP INDEX} when the migration did nothing else, and a manual reconstruction of - * partial state when it did. + *

    A concurrent index build can fail and leave an invalid index and its version's failed + * history row behind. When the migration did nothing else, recovering is the runbook's few + * statements: drop the index, delete that one failed row, deploy again ({@code + * docs/runbooks/migration-failed.md}, "Recover a failed concurrent index migration"). When it did + * more, Flyway ran the file outside a transaction and has committed the statements before the + * build, and that partial state has to be reconstructed by hand. */ public void requireIsolatedStatement(MigrationResource migration) { Objects.requireNonNull(migration, "migration"); @@ -88,9 +107,11 @@ public final class ConcurrentIndexMigrationInspector { if (statements > 1L) { throw new IllegalStateException( migration.name() - + " mixes a concurrent index statement with other statements; a failed concurrent" - + " build must be recoverable by dropping one invalid index, which requires the" - + " migration to contain nothing else"); + + " mixes a concurrent index statement with other statements; outside a" + + " transaction Flyway commits each of them on its own, so a failed build leaves the" + + " others applied. Alone, a failed build is recovered by dropping its invalid index" + + " and deleting its version's failed history row (docs/runbooks/migration-failed.md," + + " \"Recover a failed concurrent index migration\")"); } } } diff --git a/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/LockWaitMigrationInspector.java b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/LockWaitMigrationInspector.java index 19a4bca5..3752c1fd 100644 --- a/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/LockWaitMigrationInspector.java +++ b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/LockWaitMigrationInspector.java @@ -61,7 +61,9 @@ import java.util.regex.Pattern; * that holds any other statement is refused at deploy; with {@code mixed=true} it runs, unbounded. * A locking statement that cannot run in a transaction itself ({@code VACUUM FULL}, a * non-concurrent {@code REINDEX SCHEMA}) can never be bounded and is refused with the advice to - * keep it out of migrations (re-review 2026-11-03 round 4, RR4-02-01). The check assumes Flyway's + * keep it out of migrations (re-review 2026-11-03 round 4, RR4-02-01) — whatever the {@code + * .sql.conf} says: {@code executeInTransaction=true} keeps the {@code SET LOCAL} in force, but only + * for PostgreSQL to refuse the statement at deploy (round 7, RR7-03-05). The check assumes Flyway's * defaults, as the template runs it: {@code executeInTransaction=true} and {@code mixed=false} for * the whole run. */ @@ -147,11 +149,11 @@ public final class LockWaitMigrationInspector { * The statements Flyway runs outside a transaction on PostgreSQL 12 and later, as Flyway 11's * {@code PostgreSQLParser#detectCanExecuteInTransaction} lists them: the statement's leading * words outside parentheses, lower case and one space apart, match one of these in full. {@code - * ALTER TYPE ... ADD VALUE} is on Flyway's list only below PostgreSQL 12. {@code REINDEX TABLE - * CONCURRENTLY} is not on it: Flyway runs it in the transaction and PostgreSQL refuses it there. - * {@code LockWaitMigrationInspectorTest} pins Flyway's own patterns, read from {@code - * PostgreSQLParser}, so a Flyway upgrade that adds a statement or changes one fails the pull - * request's {@code ci} until this copy follows. {@code + * ALTER TYPE ... ADD VALUE} is on Flyway's list only below PostgreSQL 12. {@code REINDEX + * INDEX|TABLE CONCURRENTLY} is not on it: Flyway runs it in the transaction and PostgreSQL + * refuses it there. {@code LockWaitMigrationInspectorTest} pins Flyway's own patterns, read from + * {@code PostgreSQLParser}, so a Flyway upgrade that adds a statement or changes one fails the + * pull request's {@code ci} until this copy follows. {@code * postgresqlMigrationLockWaitIntegrationTest} compares this copy with Flyway on real PostgreSQL * for the statements it lists, and only those (re-review 2026-11-03 round 6, RR6-03-03). */ @@ -254,14 +256,15 @@ public final class LockWaitMigrationInspector { for (Pattern pattern : LOCKING) { Matcher statement = pattern.matcher(text); while (statement.find()) { + boolean cannotRunInATransaction = within(statement.start(), outside); Map.Entry setting = bounds.lowerEntry(statement.start()); - boolean bounded = setting != null && setting.getValue(); + boolean bounded = !cannotRunInATransaction && setting != null && setting.getValue(); if (!bounded && !createdEarlier(statement, createdAt)) { String named = statement.group().trim(); found.add( new Located( statement.start(), - inTransaction + inTransaction && !cannotRunInATransaction ? named : named + " (" + whyUnbounded(statement.start(), outside, configured) + ")")); } @@ -274,14 +277,17 @@ public final class LockWaitMigrationInspector { } /** - * Why a locking statement at {@code at} has no bound in a script that runs outside a transaction. + * Why a locking statement at {@code at} has no bound: it cannot run in a transaction itself, or + * the script runs outside one. */ private static String whyUnbounded(int at, List outside, Configured configured) { - for (Statement statement : outside) { - if (statement.start() <= at && at < statement.end()) { - return "cannot run in a transaction, so no SET LOCAL can bound its wait: keep it out of" - + " migrations and run it by hand as an operations step, outside deploys"; - } + if (within(at, outside)) { + return "cannot run in a transaction, so no SET LOCAL can bound its wait" + + (configured == Configured.IN_A_TRANSACTION + ? " (executeInTransaction=true only makes PostgreSQL refuse it at deploy)" + : "") + + ": keep it out of migrations and run it by hand as an operations step, outside" + + " deploys"; } if (configured == Configured.OUTSIDE_A_TRANSACTION) { return "executeInTransaction=false: SET LOCAL does nothing outside a transaction; move it to" @@ -294,6 +300,16 @@ public final class LockWaitMigrationInspector { + " in a migration of its own"; } + /** Whether the position {@code at} is inside one of the statements Flyway runs outside one. */ + private static boolean within(int at, List outside) { + for (Statement statement : outside) { + if (statement.start() <= at && at < statement.end()) { + return true; + } + } + return false; + } + /** * The statements Flyway runs outside a transaction, found the way Flyway finds them: each * statement's words outside parentheses, up to {@link #FLYWAY_DETECTION_WORDS} words in all, diff --git a/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/MigrationResource.java b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/MigrationResource.java index 614452af..6251b391 100644 --- a/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/MigrationResource.java +++ b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/MigrationResource.java @@ -5,6 +5,9 @@ import java.util.Objects; /** * One migration script as the inspector sees it (design §32). * + *

    The gRPC ledger's lane in the optional build compiles this file with {@link + * ConcurrentIndexMigrationInspector} (see there), so it keeps to the JDK only. + * * @param name the versioned script name, e.g. {@code V42__order_index.sql} * @param sql the script body */ diff --git a/src/grpc/grpc-operation-ledger-jpa/build.gradle b/src/grpc/grpc-operation-ledger-jpa/build.gradle index 05d90ae0..e4a8fc38 100644 --- a/src/grpc/grpc-operation-ledger-jpa/build.gradle +++ b/src/grpc/grpc-operation-ledger-jpa/build.gradle @@ -17,9 +17,11 @@ configurations { } // One definition of a versioned migration file and of Flyway's order for both builds (re-review -// README 12, r6-b; r9). This build cannot depend on persistence-jpa's testkit, so the one file the -// ledger lanes need from it — VersionedMigrationFiles, JDK only — is copied from there into this -// lane's sources at build time instead of being kept here as a second copy that could drift. +// README 12, r6-b; r9), and one concurrent index check (round 7, RR7-03-01). This build cannot +// depend on persistence-jpa's testkit, so the files the ledger lanes need from it, all JDK only — +// VersionedMigrationFiles, and ConcurrentIndexMigrationInspector with the MigrationResource it +// takes — are copied from there into this lane's sources at build time instead of being kept here +// as second copies that could drift. // Rejected: that testkit directory as a source root of this lane (Spotless refuses a target outside // this project's directory, and the include filter would cover this lane's own sources too), a // dependency on the main build (it would pull the whole main build into this one), and a test that @@ -27,6 +29,8 @@ configurations { def sharedMigrationFileSources = tasks.register('sharedMigrationFileSources', Sync) { from(file('../../adapter/outbound/persistence-jpa/src/testFixtures/java')) { include 'dev/caskeleton/adapter/outbound/persistence/testkit/migration/VersionedMigrationFiles.java' + include 'dev/caskeleton/adapter/outbound/persistence/testkit/migration/ConcurrentIndexMigrationInspector.java' + include 'dev/caskeleton/adapter/outbound/persistence/testkit/migration/MigrationResource.java' } into(layout.buildDirectory.dir('generated/sources/sharedMigrationFiles/java')) } diff --git a/src/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerMigrationLockWaitIT.java b/src/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerMigrationLockWaitIT.java index 723fe1d4..7efd2632 100644 --- a/src/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerMigrationLockWaitIT.java +++ b/src/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerMigrationLockWaitIT.java @@ -3,19 +3,24 @@ package dev.caskeleton.grpc.ledger; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; +import dev.caskeleton.adapter.outbound.persistence.testkit.migration.ConcurrentIndexMigrationInspector; +import dev.caskeleton.adapter.outbound.persistence.testkit.migration.MigrationResource; import java.io.IOException; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.time.Duration; +import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.stream.Stream; import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.postgresql.ds.PGSimpleDataSource; @@ -38,9 +43,18 @@ import org.testcontainers.postgresql.PostgreSQLContainer; *

    A file Flyway runs outside a transaction — one holding {@code CREATE INDEX CONCURRENTLY} or * another statement on Flyway's list, or with {@code executeInTransaction=false} beside it — is not * one this test can judge: run here in a transaction, PostgreSQL refuses it ({@code 25001}), and no - * {@code SET LOCAL} would bound it in a deploy anyway. Name such a file as an exception in this - * test, and keep it alone in its migration ({@code docs/jpa/migration-guide.md}, "Concurrent index - * builds"; re-review 2026-11-03 round 6, RR6-03-05). + * {@code SET LOCAL} would bound it in a deploy anyway. The one such file the ledger may have is a + * concurrent index build, and it goes in {@link #RUN_OUTSIDE_A_TRANSACTION} with the reason it + * needs to: the lock-wait case leaves it out, and {@code + * everyMigrationListedAsRunningOutsideATransactionIsOneConcurrentIndexBuildThatSaysSo} holds it to + * the guide instead — a concurrent index statement, alone in its file, with {@code + * executeInTransaction=false} beside it ({@code docs/jpa/migration-guide.md}, "Concurrent index + * builds"). The list takes nothing else: a {@code VACUUM FULL} or another locking statement that + * cannot run in a transaction does not belong in a migration at all ("Bound the lock wait"). The + * migrations before the one under test are applied one file at a time ({@link + * GrpcOperationLedgerMigrations#before(String)}), so a listed file is no obstacle to a later one. + * Re-review 2026-11-03 round 6, RR6-03-05; round 7, RR7-03-01: the message pointed at a list this + * test did not have. * *

    Every migration after V001 is held to this, read from the tree itself ({@link * GrpcOperationLedgerMigrations#inOrder()}), so a V004 is checked without anyone naming it here. @@ -66,9 +80,18 @@ class GrpcOperationLedgerMigrationLockWaitIT { .withUsername("grpc") .withPassword("grpc"); - /** Every ledger migration after V001, the one that creates the ledger. */ + /** + * The ledger migrations Flyway runs outside a transaction, by file name, each with why it has to: + * a concurrent index build that would stop the ledger's writes if it were built in a transaction. + * Empty while the tree has none. + */ + static final Map RUN_OUTSIDE_A_TRANSACTION = Map.of(); + + /** Every ledger migration after V001, the one that creates the ledger, that runs in one. */ static Stream migrationsAfterTheFirst() throws IOException { - return GrpcOperationLedgerMigrations.inOrder().stream().skip(1); + return GrpcOperationLedgerMigrations.inOrder().stream() + .skip(1) + .filter(migration -> !RUN_OUTSIDE_A_TRANSACTION.containsKey(migration)); } @ParameterizedTest @@ -80,7 +103,9 @@ class GrpcOperationLedgerMigrationLockWaitIT { Statement statement = setup.createStatement()) { // given statement.execute("DROP TABLE IF EXISTS grpc_operation_ledger"); - statement.execute(GrpcOperationLedgerMigrations.before(migration)); + for (String script : GrpcOperationLedgerMigrations.before(migration)) { + statement.execute(script); + } String schemaBefore = schema(statement); // when @@ -100,13 +125,57 @@ class GrpcOperationLedgerMigrationLockWaitIT { ACTIVE_SQL_TRANSACTION.equals(attempt.sqlState()) ? ". PostgreSQL refused it inside a transaction (25001): Flyway runs such a file" + " outside one, where SET LOCAL bounds nothing, so it is no case for this" - + " test. Keep it alone in its migration and name it as an exception here" - + " (\"Concurrent index builds\")" + + " test. If it is a concurrent index build, keep it alone in its migration" + + " with executeInTransaction=false beside it and add it, with the reason, to" + + " RUN_OUTSIDE_A_TRANSACTION in this test (\"Concurrent index builds\");" + + " anything else that cannot run in a transaction does not belong in a" + + " migration (\"Bound the lock wait\")" : "") .containsExactly(LOCK_NOT_AVAILABLE, true, schemaBefore); } } + @Test + @DisplayName( + "트랜잭션 밖에서 도는 예외 목록의 ledger 마이그레이션은 트리에 있고, 동시 인덱스 문장 하나뿐이며, executeInTransaction=false를 적었다") + void everyMigrationListedAsRunningOutsideATransactionIsOneConcurrentIndexBuildThatSaysSo() + throws IOException { + // given + ConcurrentIndexMigrationInspector inspector = new ConcurrentIndexMigrationInspector(); + List tree = GrpcOperationLedgerMigrations.inOrder(); + + // when + List refused = new ArrayList<>(); + for (String migration : RUN_OUTSIDE_A_TRANSACTION.keySet()) { + if (!tree.contains(migration)) { + refused.add(migration + " is not a migration in the ledger tree"); + continue; + } + MigrationResource resource = + new MigrationResource(migration, GrpcOperationLedgerMigrations.named(migration)); + if (!inspector.containsConcurrentIndexStatement(resource.sql())) { + refused.add( + migration + + " holds no concurrent index statement; only a concurrent index build may run" + + " outside a transaction"); + continue; + } + boolean inATransaction = GrpcOperationLedgerMigrations.executeInTransaction(migration); + Throwable thrown = + catchThrowable( + () -> { + inspector.validate(resource, inATransaction); + inspector.requireIsolatedStatement(resource); + }); + if (thrown != null) { + refused.add(thrown.getMessage()); + } + } + + // then + assertThat(refused).isEmpty(); + } + /** Runs the migration in one transaction while another one holds a write to the ledger. */ private static Attempt whileAWriterHolds(PGSimpleDataSource dataSource, String migration) throws SQLException { diff --git a/src/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerMigrations.java b/src/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerMigrations.java index f8832fc0..c237e178 100644 --- a/src/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerMigrations.java +++ b/src/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerMigrations.java @@ -3,12 +3,16 @@ package dev.caskeleton.grpc.ledger; import dev.caskeleton.adapter.outbound.persistence.testkit.migration.VersionedMigrationFiles; import java.io.IOException; import java.io.InputStream; +import java.io.Reader; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; import java.nio.file.Path; +import java.util.ArrayList; import java.util.List; +import java.util.Properties; /** - * The ledger's Flyway scripts in version order, as one SQL text for a test database. + * The ledger's Flyway scripts in version order, one SQL text per file for a test database. * *

    One list for every PostgreSQL lane, so a new migration is applied by all of them or by none. * The list is the tree on disk, not a copy of it: a hand-kept list let a V004 that nobody added to @@ -38,21 +42,26 @@ final class GrpcOperationLedgerMigrations { .toList(); } - /** Every migration's SQL, concatenated in version order. */ - static String all() throws IOException { + /** Every migration's SQL in version order, one script per file. */ + static List all() throws IOException { return before(null); } - /** The SQL of every migration before the one named, concatenated in version order. */ - static String before(String fileName) throws IOException { - StringBuilder sql = new StringBuilder(); + /** + * The SQL of every migration before the one named, in version order, one script per file. Run + * each as a statement of its own, the way Flyway runs a file: one string holding many files runs + * in one implicit transaction, where PostgreSQL refuses a file Flyway runs outside one — a + * concurrent index build (re-review 2026-11-03 round 7, RR7-03-01). + */ + static List before(String fileName) throws IOException { + List scripts = new ArrayList<>(); for (String name : inOrder()) { if (name.equals(fileName)) { break; } - sql.append(read(name)).append('\n'); + scripts.add(read(name)); } - return sql.toString(); + return scripts; } /** One migration's SQL, by its file name. */ @@ -63,6 +72,23 @@ final class GrpcOperationLedgerMigrations { return read(fileName); } + /** + * Whether Flyway is told to run the migration in a transaction: false only when the {@code + *