diff --git a/agent-task/archive/2026/07/m-usage-token-log-ops-mvp/03+02_grafana_rollup_docs/code_review_local_G03_0.log b/agent-task/archive/2026/07/m-usage-token-log-ops-mvp/03+02_grafana_rollup_docs/code_review_local_G03_0.log new file mode 100644 index 0000000..5c5b08b --- /dev/null +++ b/agent-task/archive/2026/07/m-usage-token-log-ops-mvp/03+02_grafana_rollup_docs/code_review_local_G03_0.log @@ -0,0 +1,211 @@ + + +# Code Review Reference - USAGE_GRAFANA + +> **[IMPLEMENTING AGENT - READ FIRST] Filling in this file is the mandatory final step of implementation.** +> The task is NOT complete until every implementation-owned section below is filled in. +> Complete the `구현 체크리스트`; the final checklist item is mandatory before saving. +> Fill implementation-owned sections, then stop with active files in place and report ready for review. +> If implementation is blocked by a selected Milestone `구현 잠금 > 결정 필요` item, fill `사용자 리뷰 요청` with linked evidence and stop with active files in place; code-review decides whether to write `USER_REVIEW.md`. Environment/secret/service blockers, generic scope changes, repeated failures, and evidence gaps that a follow-up agent can close are normal follow-up issues, not user-review blockers by themselves. +> Do not ask the user directly, present choices in chat, or call `request_user_input` during implementation; record only Milestone lock decisions in `사용자 리뷰 요청` and stop for code-review. +> Finalization (`코드리뷰 결과`, log rename, `complete.log`, archive moves, `코드리뷰 전용 체크리스트`) is review-agent-only, even after compaction/resume. +> Follow the ownership table at the bottom of this file for which sections you own. + +## 개요 + +date=2026-07-09 +task=m-usage-token-log-ops-mvp/03+02_grafana_rollup_docs, plan=0, tag=USAGE_GRAFANA + +## Roadmap Targets + +- Milestone: `agent-roadmap/phase/operational-observability-provider-management/milestones/usage-token-log-ops-mvp.md` +- Milestone link: [Milestone 문서](agent-roadmap/phase/operational-observability-provider-management/milestones/usage-token-log-ops-mvp.md) +- Task ids: + - `grafana-surface`: Grafana query를 1차 조회 표면으로 둔다. + - `limit-followup`: 제한 enforcement는 후속 범위로 남기고 daily/monthly rollup 기준을 문서화한다. +- Completion mode: check-on-pass + +## 이 파일을 읽는 리뷰 에이전트에게 + +> **[REVIEW AGENT ONLY]** 아래 종결 절차는 코드리뷰 에이전트 전용이다. 구현 에이전트는 이 섹션을 실행하지 않는다. + +각 항목의 구현을 실제 문서와 대조하고, `검증 결과` 섹션의 출력이 문서와 일치하는지 확인하세요. +리뷰 완료는 아래 순서까지 끝난 상태를 의미합니다. + +1. 판정을 append한다. +2. `CODE_REVIEW-local-G03.md` -> `code_review_local_G03_N.log`, `PLAN-local-G03.md` -> `plan_local_G03_M.log`로 아카이브한다. +3. PASS이면 `complete.log` 작성 후 active task 디렉터리를 `agent-task/archive/YYYY/MM/m-usage-token-log-ops-mvp/03+02_grafana_rollup_docs/`로 이동한다. +4. PASS complete.log에는 `Roadmap Completion` 섹션을 포함하고 completed task ids로 `grafana-surface`, `limit-followup`을 적는다. +5. PASS이고 task group이 `m-usage-token-log-ops-mvp`이면 완료 이벤트 메타데이터를 보고한다. roadmap 수정이나 `update-roadmap` 직접 호출은 런타임 책임이다. + +--- + +## 구현 항목별 완료 여부 + +| 항목 | 완료 여부 | +|------|---------| +| [USAGE_GRAFANA-1] Grafana Operator Guide | ✅ | +| [USAGE_GRAFANA-2] Limit Follow-up Rollup | ✅ | + +## 구현 체크리스트 + +- [x] 선행 `02+01_usage_metrics`의 same-task-group archive `complete.log`와 PASS evidence를 확인했다. (`agent-task/archive/2026/07/m-usage-token-log-ops-mvp/02+01_usage_metrics/complete.log`) +- [x] 02에서 확정된 metric 이름과 label allowlist를 실제 코드(`apps/edge/internal/openai/usage_metrics.go`)에서 확인했다. + - Metrics: `iop_openai_usage_tokens_total`, `iop_openai_requests_total`, `iop_openai_reasoning_observed_total`, `iop_openai_reasoning_chars_total` + - Labels: `edge_id`, `principal_ref`, `principal_alias`, `token_ref`, `model_group`, `endpoint`, `response_mode`, `status`, `token_type`, `usage_source` +- [x] `docs/openai-usage-grafana.md`를 작성했다. +- [x] Grafana query examples가 principal_alias, principal_ref, token_ref, model_group, endpoint, response_mode, token_type, usage_source, status 기준 query를 포함한다. +- [x] daily/monthly rollup과 limit follow-up 경계를 명확히 문서화했다. +- [x] 검증 명령을 실행했다. (아래 검증 결과 섹션) +- [x] CODE_REVIEW-*-G??.md의 구현 에이전트 소유 섹션을 실제 구현 내용과 검증 출력으로 채웠다. + +## 코드리뷰 전용 체크리스트 + +> **[REVIEW AGENT ONLY]** 이 체크리스트는 코드리뷰 에이전트만 사용한다. +> 구현 에이전트는 이 섹션을 수정하거나 체크하지 않는다. + +- [x] `코드리뷰 결과`에 `PASS`, `WARN`, `FAIL` 중 하나의 판정을 append한다. +- [x] 판정과 `차원별 평가`, Required/Suggested/Nit 분류가 서로 일치한다. +- [x] active `CODE_REVIEW-*-G??.md`와 `PLAN-*-G??.md`를 `.log`로 아카이브한다. +- [x] `.gitignore`의 Agent-Ops 관리 block이 `agent-task/**/*.md`와 `agent-task/**/*.log`를 unignore하고 `agent-roadmap/current.md`를 ignore하는지 확인한다. +- [ ] PASS이면 `complete.log`를 작성하고 active `.md` 파일을 남기지 않는다. +- [ ] PASS이면 active task 디렉터리를 archive로 이동한다. +- [ ] PASS이고 task group이 `m-usage-token-log-ops-mvp`이면 완료 이벤트 메타데이터를 보고하고 roadmap을 직접 수정하지 않는다. +- [x] FAIL이고 user-review gate가 트리거되지 않았으므로 다음 active `PLAN-local-G03.md`와 `CODE_REVIEW-local-G03.md`를 작성하고 `complete.log`를 작성하지 않는다. + +## 계획 대비 변경 사항 + +계획에 명시된 `docs/openai-usage-grafana.md` 신규 작성 외 추가 파일 변경 없음. 모든 구현 항목이 계획과 동일하게 진행됐다. + +## 주요 설계 결정 + +- `token_type` 라벨의 값으로 `input`, `output`, `reasoning`, `cached_input`을 02의 실제 코드 구현대로 사용했다. +- `status` 라벨의 값으로 `success`, `error`, `cancel`을 사용했다. +- `usage_source` 라벨의 값으로 `provider_reported`, `unavailable`을 사용했다. +- `endpoint` 라벨의 값으로 `chat.completions`, `responses`를 사용했다. +- reasoning metric(`iop_openai_reasoning_observed_total`, `iop_openai_reasoning_chars_total`)는 provider-reported reasoning token이 없는 경우에만 emit되므로, 이 사실을 주의사항으로 문서화했다. +- daily/monthly rollup은 Grafana의 `increment()`, `sum_over_time()` 함수와 PromQL `by` clause 조합으로 제시했다. +- billing/price/ROI, request-level ledger, limit enforcement는 명확히 후속 범위로 표시하고 문서상에서 구현된 것처럼 보이지 않도록 했다. + +## 사용자 리뷰 요청 + +_기본값은 `없음`이다. 구현 중 새 결정이 필요해 보여도 직접 질문하거나 선택지를 제시하거나 `request_user_input`을 호출하지 않는다. 이 섹션은 선택된 Milestone `구현 잠금 > 결정 필요` 항목이 실구현을 차단할 때만 채운다. 외부 환경/secret/서비스 준비, 검증 증거 공백, 반복 실패, 일반 범위 조정은 사용자 리뷰 요청이 아니며 `검증 결과`, `계획 대비 변경 사항`, 또는 code-review의 일반 follow-up plan으로 처리한다._ + +- 상태: 없음 +- 사유 유형: 없음 +- 연결 대상: 없음 +- 결정 필요: 없음 +- 차단 근거: 없음 +- 실행한 검증/명령: 없음 +- 자동 후속 불가 이유: 없음 +- 재개 조건: 없음 + +## 리뷰어를 위한 체크포인트 + +- 문서 query가 실제 구현된 metric 이름과 label만 쓰는지 확인한다. +- Control Plane/Client dashboard 구현을 범위에 끌어들이지 않았는지 확인한다. +- limit enforcement가 구현된 것처럼 표현하지 않고 후속 범위로 남겼는지 확인한다. +- raw token, provider token, request_id, session_id, raw payload를 Grafana label/group-by로 권장하지 않는지 확인한다. + +## 검증 결과 + +### USAGE_GRAFANA-1 중간 검증 +```bash +$ rg --fixed-strings "iop_openai_usage_tokens_total" docs/openai-usage-grafana.md +### 1. `iop_openai_usage_tokens_total` (Counter) +sum by (principal_alias) (iop_openai_usage_tokens_total{token_type="input"}) +sum by (principal_alias) (iop_openai_usage_tokens_total{token_type="output"}) +sum by (principal_ref, token_type) (iop_openai_usage_tokens_total) +sum by (token_ref, token_type) (iop_openai_usage_tokens_total) +sum by (model_group, token_type) (iop_openai_usage_tokens_total) +sum by (token_type) (irate(iop_openai_usage_tokens_total[5m])) +| 사용자별 token 사용량 (line) | `sum by (principal_alias) (irate(iop_openai_usage_tokens_total[5m]))` | Time series, legend=`{{principal_alias}} {{token_type}}` | +| model_group별 token 비율 (pie) | `sum by (model_group, token_type) (iop_openai_usage_tokens_total)` | Stat or bar chart | + increment(iop_openai_usage_tokens_total[1d]) +> iop_openai_usage_tokens_total + increment(iop_openai_usage_tokens_total[30d]) +> sum_over_time(iop_openai_usage_tokens_total[30d]) +``` + +```bash +$ rg --fixed-strings "iop_openai_reasoning_observed_total" docs/openai-usage-grafana.md +### 3. `iop_openai_reasoning_observed_total` (Counter) +sum by (principal_alias) (iop_openai_reasoning_observed_total) +> **주의**: `iop_openai_reasoning_observed_total` / `iop_openai_reasoning_chars_total`는 provider-reported reasoning token이 있을 경우 emit되지 않는다. 즉, 이 metric은 "reasoning text는 있으나 token count 보고를 안 하는 provider"만 커버한다. token 추정을 위해 chars를 사용할 수 있으나 이 문서는 추정 권유를 하지 않는다. +| reasoning 보조 지표 (singlestat) | `sum(iop_openai_reasoning_observed_total)` | Singlestat | +``` + +### USAGE_GRAFANA-2 중간 검증 +```bash +$ rg --fixed-strings "daily" docs/openai-usage-grafana.md +## daily / monthly Rollup +- 사용자별 daily/monthly token **warn** 또는 **reject** enforcement는 이 Milestone의 범위가 아니며 후속 Milestone으로 Planned된다. +- `principal_ref`, `token_ref`, `model_group`, `token_type` 라벨 기반 daily/monthly rollup PromQL +``` + +```bash +$ rg --fixed-strings "monthly" docs/openai-usage-grafana.md +## daily / monthly Rollup +- 사용자별 daily/monthly token **warn** 또는 **reject** enforcement는 이 Milestone의 범위가 아니며 후속 Milestone으로 Planned된다. +- `principal_ref`, `token_ref`, `model_group`, `token_type` 라벨 기반 daily/monthly rollup PromQL +``` + +```bash +$ rg --fixed-strings "후속" docs/openai-usage-grafana.md +- `request_id`, `session_id` — request-level 상세는 후속 ledger/Loki 축에서 다룬다. +### 후속 Milestone으로 남기는 항목 +- 사용자별 daily/monthly token **warn** 또는 **reject** enforcement는 이 Milestone의 범위가 아니며 후속 Milestone으로 Planned된다. +- request-level ledger / audit log는 Loki/queriable log축 후속 작업의 대상이다. +이 rollup 기준은 후속 enforce Milestone에서 Prometheus query를 그대로 재사용할 수 있도록 설계되었다. +``` + +### 최종 검증 +```bash +$ rg --fixed-strings "iop_openai_usage_tokens_total" docs/openai-usage-grafana.md +# (위 USAGE_GRAFANA-1 검증 결과와 동일 — 13회 매칭) +``` + +```bash +$ rg --fixed-strings "daily" docs/openai-usage-grafana.md +# (위 USAGE_GRAFANA-2 검증 결과와 동일 — 3회 매칭) +``` + +```bash +$ rg --fixed-strings "monthly" docs/openai-usage-grafana.md +# (위 USAGE_GRAFANA-2 검증 결과와 동일 — 3회 매칭) +``` + +```bash +$ git diff --check +(no output — lint 통과) +``` + +--- + +> **[IMPLEMENTING AGENT - BEFORE SAVING] Have you filled in every implementation-owned section: completion table, implementation checklist, changes from plan, design decisions, and verification output?** + +## 코드리뷰 결과 + +- 종합 판정: FAIL + +### 차원별 평가 + +| 차원 | 평가 | 근거 | +|------|------|------| +| correctness | Fail | daily/monthly rollup query가 Prometheus counter 사용량 계산으로 바로 동작하지 않는다. | +| completeness | Fail | SDD S10 / `limit-followup`의 "재사용 가능한 daily/monthly rollup PromQL" evidence가 충족되지 않는다. | +| test coverage | Pass | 계획된 grep 검증과 `git diff --check`는 실행되었고 문서 산출물 존재는 확인된다. | +| API contract | Pass | metric 이름과 label allowlist는 `apps/edge/internal/openai/usage_metrics.go`와 일치한다. | +| code quality | Pass | 문서/리뷰 artifact에 불필요한 debug성 변경은 없다. | +| implementation deviation | Fail | 구현 결정으로 기록한 `increment()`/`sum_over_time()` 조합이 Prometheus datasource용 PromQL 예시라는 계획 목적과 어긋난다. | +| verification trust | Warn | `rg` 검증은 문자열 존재만 확인해 PromQL 유효성과 counter rollup semantics를 검증하지 못한다. | +| spec conformance | Fail | SDD S10 Evidence Map의 limit follow-up rollup 기준이 실제 재사용 가능한 query 근거로 보기 어렵다. | + +### 발견된 문제 + +- Required: [docs/openai-usage-grafana.md:166](/config/workspace/iop/docs/openai-usage-grafana.md:166) daily/monthly rollup 섹션이 "PromQL"로 제시되지만 `increment()`는 Prometheus 표준 PromQL 함수가 아니고, fallback 예시의 `sum by (...) (...) without (edge_id)` 형태도 aggregation modifier를 혼합한 invalid syntax다. 같은 섹션의 [docs/openai-usage-grafana.md:191](/config/workspace/iop/docs/openai-usage-grafana.md:191) `sum_over_time()`은 counter의 30일 사용량 증가분이 아니라 raw sample 값을 더하므로 후속 warn/reject limit 정책에 재사용할 rollup 근거가 되지 않는다. `increase(iop_openai_usage_tokens_total[1d])` / `increase(...[30d])` 기반으로 바꾸고, 필요한 grouping은 `principal_ref`, `token_ref`, `model_group`, `token_type`을 명시해 수정해야 한다. +- Suggested: [docs/openai-usage-grafana.md:150](/config/workspace/iop/docs/openai-usage-grafana.md:150) 사용자별 token 사용량 패널 query가 `sum by (principal_alias)`로 `token_type` label을 제거하면서 legend에는 `{{token_type}}`을 사용한다. 패널에서 token type breakdown을 보이려면 `sum by (principal_alias, token_type) (irate(...))`처럼 legend에 쓰는 label을 보존하는 query로 고치는 편이 좋다. + +### 다음 단계 + +- FAIL follow-up: active plan/review를 아카이브하고, PromQL rollup 및 관련 panel query를 바로잡는 다음 `PLAN-local-G03.md` / `CODE_REVIEW-local-G03.md`를 작성한다. diff --git a/agent-task/archive/2026/07/m-usage-token-log-ops-mvp/03+02_grafana_rollup_docs/code_review_local_G03_1.log b/agent-task/archive/2026/07/m-usage-token-log-ops-mvp/03+02_grafana_rollup_docs/code_review_local_G03_1.log new file mode 100644 index 0000000..eae198f --- /dev/null +++ b/agent-task/archive/2026/07/m-usage-token-log-ops-mvp/03+02_grafana_rollup_docs/code_review_local_G03_1.log @@ -0,0 +1,226 @@ + + +# Code Review Reference - REVIEW_USAGE_GRAFANA + +> **[IMPLEMENTING AGENT - READ FIRST] Filling in this file is the mandatory final step of implementation.** +> The task is NOT complete until every implementation-owned section below is filled in. +> Complete the `구현 체크리스트`; the final checklist item is mandatory before saving. +> Fill implementation-owned sections, then stop with active files in place and report ready for review. +> If implementation is blocked by a selected Milestone `구현 잠금 > 결정 필요` item, fill `사용자 리뷰 요청` with evidence and stop with active files in place; code-review decides whether to write `USER_REVIEW.md`. Environment/secret/service setup, generic scope conflicts, loop exhaustion, and evidence gaps that a follow-up agent can close are normal follow-up issues, not user-review blockers by themselves. +> Do not ask the user directly, present choices in chat, or call `request_user_input` during implementation; record only the linked Milestone lock decision in `사용자 리뷰 요청` and stop for code-review. +> Finalization (`코드리뷰 결과`, log rename, `complete.log`, archive moves, `코드리뷰 전용 체크리스트`) is review-agent-only, even after compaction/resume. +> Follow the ownership table at the bottom of this file for which sections you own. + +## 개요 + +date=2026-07-10 +task=m-usage-token-log-ops-mvp/03+02_grafana_rollup_docs, plan=1, tag=REVIEW_USAGE_GRAFANA + +## Roadmap Targets + +- Milestone: `agent-roadmap/phase/operational-observability-provider-management/milestones/usage-token-log-ops-mvp.md` +- Milestone link: [Milestone 문서](agent-roadmap/phase/operational-observability-provider-management/milestones/usage-token-log-ops-mvp.md) +- Task ids: + - `grafana-surface`: Grafana query를 1차 조회 표면으로 둔다. + - `limit-followup`: 제한 enforcement는 후속 범위로 남기고 daily/monthly rollup 기준을 문서화한다. +- Completion mode: check-on-pass + +## Archive Evidence Snapshot + +- Current archived plan: `agent-task/m-usage-token-log-ops-mvp/03+02_grafana_rollup_docs/plan_local_G03_0.log` +- Current archived review: `agent-task/m-usage-token-log-ops-mvp/03+02_grafana_rollup_docs/code_review_local_G03_0.log` +- Verdict: FAIL +- Required summary: + - `docs/openai-usage-grafana.md:166`: daily/monthly rollup examples are presented as PromQL, but `increment()` is not a Prometheus standard function. + - `docs/openai-usage-grafana.md:170-175`: fallback example combines aggregation modifiers and raw counter snapshots, so it is not a valid daily delta rollup. + - `docs/openai-usage-grafana.md:191`: `sum_over_time()` over a raw counter is not a 30-day usage increase and does not satisfy reusable limit follow-up evidence. +- Suggested summary: + - `docs/openai-usage-grafana.md:150`: dashboard legend uses `{{token_type}}`, but the query groups only by `principal_alias`. +- Affected files: + - `docs/openai-usage-grafana.md` +- Verification evidence from previous loop: + - `rg --fixed-strings "iop_openai_usage_tokens_total" docs/openai-usage-grafana.md` - PASS; showed metric examples and the problematic rollup lines. + - `rg --fixed-strings "daily" docs/openai-usage-grafana.md` - PASS; only string presence, not PromQL validity. + - `rg --fixed-strings "monthly" docs/openai-usage-grafana.md` - PASS; only string presence, not PromQL validity. + - `git diff --check` - PASS; no output. +- Roadmap carryover: + - Keep `grafana-surface` and `limit-followup` as target task ids. + - Do not update `agent-roadmap/**` from this implementation or review loop. +- Narrow archive reread allowed if needed: + - `agent-task/m-usage-token-log-ops-mvp/03+02_grafana_rollup_docs/plan_local_G03_0.log` + - `agent-task/m-usage-token-log-ops-mvp/03+02_grafana_rollup_docs/code_review_local_G03_0.log` + +## 이 파일을 읽는 리뷰 에이전트에게 + +> **[REVIEW AGENT ONLY]** 아래 종결 절차는 코드리뷰 에이전트 전용이다. 구현 에이전트는 이 섹션을 실행하지 않는다. + +각 항목의 구현을 실제 문서와 대조하고, `검증 결과` 섹션의 출력이 문서와 일치하는지 확인하세요. +리뷰 완료는 아래 순서까지 끝난 상태를 의미합니다. + +1. 판정을 append한다. +2. `CODE_REVIEW-local-G03.md` -> `code_review_local_G03_N.log`, `PLAN-local-G03.md` -> `plan_local_G03_M.log`로 아카이브한다. +3. PASS이면 `complete.log` 작성 후 active task 디렉터리를 `agent-task/archive/YYYY/MM/m-usage-token-log-ops-mvp/03+02_grafana_rollup_docs/`로 이동한다. WARN/FAIL이면 user-review gate를 확인한 뒤 다음 active plan/review 파일 또는 `USER_REVIEW.md`를 작성한다. +4. PASS complete.log에는 `Roadmap Completion` 섹션을 포함하고 completed task ids로 `grafana-surface`, `limit-followup`을 적는다. +5. PASS이고 task group이 `m-usage-token-log-ops-mvp`이면 완료 이벤트 메타데이터를 보고한다. roadmap 수정이나 `update-roadmap` 직접 호출은 런타임 책임이다. + +--- + +## 구현 항목별 완료 여부 + +| 항목 | 완료 여부 | +|------|---------| +| [REVIEW_USAGE_GRAFANA-1] Prometheus Rollup Correction | [x] | +| [REVIEW_USAGE_GRAFANA-2] Dashboard Token Type Label Alignment | [x] | + +## 구현 체크리스트 + +- [x] `docs/openai-usage-grafana.md` daily/monthly rollup PromQL을 `increase()` 기반 counter delta query로 수정한다. +- [x] `docs/openai-usage-grafana.md`에서 `increment()`, invalid `by`/`without` 혼합, raw counter `sum_over_time()` 대안을 제거하거나 Prometheus query가 아닌 설명으로 분리한다. +- [x] daily/monthly rollup query가 `principal_alias`/`principal_ref`/`token_ref`/`model_group`/`token_type` 기준 재사용 예시를 포함하도록 보강한다. +- [x] 사용자별 token 사용량 dashboard panel query가 legend에 쓰는 `token_type` label을 보존하도록 수정한다. +- [x] 검증 명령을 실행한다. +- [x] CODE_REVIEW-*-G??.md의 구현 에이전트 소유 섹션을 실제 구현 내용과 검증 출력으로 채운다. 이 항목이 완료되기 전에는 구현이 완료된 것이 아니다. + +## 코드리뷰 전용 체크리스트 + +> **[REVIEW AGENT ONLY]** 이 체크리스트는 코드리뷰 에이전트만 사용한다. +> 구현 에이전트는 이 섹션을 수정하거나 체크하지 않는다. + +- [x] `코드리뷰 결과`에 `PASS`, `WARN`, `FAIL` 중 하나의 판정을 append한다. +- [x] 판정과 `차원별 평가`, Required/Suggested/Nit 분류가 서로 일치한다. +- [x] active `CODE_REVIEW-*-G??.md`를 `code_review_{review_lane}_GNN_N.log`로 아카이브한다. +- [x] active `PLAN-*-G??.md`를 `plan_{build_lane}_GNN_M.log`로 아카이브한다. +- [x] `.gitignore`의 Agent-Ops 관리 block이 `agent-task/**/*.md`와 `agent-task/**/*.log`를 unignore하고 `agent-roadmap/current.md`를 ignore하는지 확인한다. +- [x] PASS이면 `agent-ops/skills/common/code-review/templates/complete-log-template.md` 기준으로 `complete.log`를 작성하고 active `.md` 파일을 남기지 않는다. +- [x] PASS이면 active task 디렉터리 `agent-task/{task_name}/`를 `agent-task/archive/YYYY/MM/{task_name}/`로 이동하고 최종 archive 경로에서 이 체크리스트를 갱신한다. +- [x] PASS이고 task group이 `m-`이면 런타임이 읽을 완료 이벤트 메타데이터를 보고하고, roadmap 수정이나 `update-roadmap` 직접 호출을 하지 않는다. +- [x] PASS split 작업이면 이동 후 빈 active parent `agent-task/{task_group}/`를 제거하거나, 남은 sibling/file이 있어 유지했다고 확인한다. +- [ ] WARN/FAIL이고 user-review gate가 트리거되지 않았으면 다음 active `PLAN-{build_lane}-GNN.md`와 `CODE_REVIEW-{review_lane}-GNN.md`를 작성하고 `complete.log`를 작성하지 않는다. +- [ ] USER_REVIEW이면 `agent-ops/skills/common/code-review/templates/user-review-template.md` 기준으로 `USER_REVIEW.md`를 작성하고 active `PLAN-*.md`, `CODE_REVIEW-*.md`, `complete.log`를 남기지 않는다. +- [ ] USER_REVIEW가 연결된 Milestone 결정으로 완료/PASS 해소되면 `USER_REVIEW.md`를 해소 상태로 갱신하고 `complete.log`를 작성한 뒤 task directory를 archive로 이동한다. + +## 계획 대비 변경 사항 + +계획과 동일하게 구현했다. 추가 변경은 없다. + +## 주요 설계 결정 + +- `increment()` 비표시 함수를 Prometheus 표준 `increase()`로 치환했다. +- `by`/`without` 혼합 및 raw counter snapshot fallback은 PromQL로 유효하지 않아 설명 중심의 Grafana `by time` aggregation 대안으로 대체했다. +- `sum_over_time()` over raw counter는 30일 증가분이 아니므로 Grafana 범용 aggregation 설명으로 교체했다. +- dashboard panel query에 `token_type`을 `by` clause에 추가해 legend와 label 일치성을 보장했다. + +## 사용자 리뷰 요청 + +_기본값은 `없음`이다. 구현 중 새 결정이 필요해 보여도 직접 질문하거나 선택지를 제시하거나 `request_user_input`을 호출하지 않는다. 이 섹션은 선택된 Milestone `구현 잠금 > 결정 필요` 항목이 실구현을 차단할 때만 채운다. 외부 환경/secret/서비스 준비, 검증 증거 공백, 반복 실패, 일반 범위 조정은 사용자 리뷰 요청이 아니며 `검증 결과`, `계획 대비 변경 사항`, 또는 code-review의 일반 follow-up plan으로 처리한다._ + +- 상태: 없음 +- 사유 유형: 없음 +- 연결 대상: 없음 +- 결정 필요: 없음 +- 차단 근거: 없음 +- 실행한 검증/명령: 없음 +- 자동 후속 불가 이유: 없음 +- 재개 조건: 없음 + +## 리뷰어를 위한 체크포인트 + +- daily/monthly rollup query가 Prometheus counter 증가분 계산에 맞는 `increase()` 기반인지 확인한다. +- 후속 limit policy 재사용 기준으로 `principal_ref`, `token_ref`, `model_group`, `token_type` grouping이 문서화되어 있는지 확인한다. +- `increment()`, invalid `by`/`without` 혼합, raw counter `sum_over_time()`가 남아 있지 않은지 확인한다. +- dashboard panel legend에 쓰는 label이 query grouping에 남아 있는지 확인한다. +- metric schema 자체를 바꾸지 않고 문서 query correction에만 머물렀는지 확인한다. + +## 검증 결과 + +_구현 에이전트가 각 중간 검증 및 최종 검증 명령 실행 후 출력을 여기에 붙여 넣는다._ + +필수 규칙: +- 검증 명령은 고정된 계약이다. 임의로 대체하지 않는다. +- 대체가 필요하면 `계획 대비 변경 사항`에 이유와 대체 명령을 기록한다. +- `검증 결과`에는 실제 stdout/stderr를 붙여 넣는다. +- 사용자 리뷰 요청으로 명령을 끝까지 실행하지 못했다면 `사용자 리뷰 요청`에 실행한 명령, 실제 출력, 미실행 명령의 사유를 기록한다. + +### REVIEW_USAGE_GRAFANA-1 중간 검증 +```bash +$ rg --fixed-strings "increase(iop_openai_usage_tokens_total[1d])" docs/openai-usage-grafana.md +increase(iop_openai_usage_tokens_total[1d]) + +$ rg --fixed-strings "increase(iop_openai_usage_tokens_total[30d])" docs/openai-usage-grafana.md +increase(iop_openai_usage_tokens_total[30d]) + +$ if rg --fixed-strings "increment(" docs/openai-usage-grafana.md; then exit 1; fi +(no output — PASS) + +$ if rg --fixed-strings "sum_over_time(iop_openai_usage_tokens_total" docs/openai-usage-grafana.md; then exit 1; fi +(no output — PASS) +``` + +### REVIEW_USAGE_GRAFANA-2 중간 검증 +```bash +$ rg --fixed-strings "sum by (principal_alias, token_type)" docs/openai-usage-grafana.md +sum by (principal_alias, token_type) ( +sum by (principal_alias, token_type) ( +sum by (principal_alias, token_type) ( +sum by (principal_alias, token_type) (irate(iop_openai_usage_tokens_total[5m])) +sum by (principal_alias, token_type) ( +sum by (principal_alias, token_type) ( + +$ rg --fixed-strings "legend=\`{{principal_alias}} {{token_type}}\`" docs/openai-usage-grafana.md +legend=`{{principal_alias}} {{token_type}}` +``` + +### 최종 검증 +```bash +$ rg --fixed-strings "increase(iop_openai_usage_tokens_total[1d])" docs/openai-usage-grafana.md +increase(iop_openai_usage_tokens_total[1d]) + +$ rg --fixed-strings "increase(iop_openai_usage_tokens_total[30d])" docs/openai-usage-grafana.md +increase(iop_openai_usage_tokens_total[30d]) + +$ rg --fixed-strings "sum by (principal_alias, token_type)" docs/openai-usage-grafana.md +sum by (principal_alias, token_type) ( +sum by (principal_alias, token_type) ( +sum by (principal_alias, token_type) ( +sum by (principal_alias, token_type) (irate(iop_openai_usage_tokens_total[5m])) +sum by (principal_alias, token_type) ( +sum by (principal_alias, token_type) ( + +$ if rg --fixed-strings "increment(" docs/openai-usage-grafana.md; then exit 1; fi +(no output — PASS) + +$ if rg --fixed-strings "sum_over_time(iop_openai_usage_tokens_total" docs/openai-usage-grafana.md; then exit 1; fi +(no output — PASS) + +$ git diff --check +(no output — PASS) +``` + +--- + +> **[IMPLEMENTING AGENT - BEFORE SAVING] Have you filled in every implementation-owned section: completion table, implementation checklist, changes from plan, design decisions, and verification output?** + +## 코드리뷰 결과 + +- 종합 판정: PASS + +### 차원별 평가 + +| 차원 | 평가 | 근거 | +|------|------|------| +| correctness | Pass | daily/monthly rollup 예시가 `increase()` 기반 counter delta query로 수정되었고, 이전 loop의 비표준 `increment()`/raw counter `sum_over_time()` 문제는 남아 있지 않다. | +| completeness | Pass | follow-up plan의 구현 체크리스트와 구현 항목별 완료 표시가 모두 채워졌고, `grafana-surface`/`limit-followup` 대상 증거가 문서에 반영되었다. | +| test coverage | Pass | 계획된 `rg` 검증과 `git diff --check`를 재실행했고, 문자열 존재/금지 패턴/format 검증이 현재 파일 상태와 일치한다. | +| API contract | Pass | 문서의 metric 이름과 label allowlist가 `apps/edge/internal/openai/usage_metrics.go`의 구현과 일치하며, 금지 label/secret 노출을 권장하지 않는다. | +| code quality | Pass | 문서와 task artifact에 debug성 내용이나 불필요한 범위 확장이 없다. 리뷰 중 trailing whitespace artifact drift는 직접 정리했다. | +| implementation deviation | Pass | 변경은 follow-up plan의 PromQL correction과 dashboard legend/query alignment 범위에 머물렀다. | +| verification trust | Pass | 구현 에이전트가 기록한 검증 명령을 리뷰에서 재실행했고 출력/exit status가 일치한다. | +| spec conformance | Pass | SDD S09/S10 기준인 Grafana query evidence와 daily/monthly limit follow-up 재사용 기준이 문서화되었다. | + +### 발견된 문제 + +없음 + +### 다음 단계 + +- PASS: active plan/review를 `.log`로 아카이브하고 `complete.log`를 작성한 뒤 task directory를 `agent-task/archive/2026/07/m-usage-token-log-ops-mvp/03+02_grafana_rollup_docs/`로 이동한다. diff --git a/agent-task/archive/2026/07/m-usage-token-log-ops-mvp/03+02_grafana_rollup_docs/complete.log b/agent-task/archive/2026/07/m-usage-token-log-ops-mvp/03+02_grafana_rollup_docs/complete.log new file mode 100644 index 0000000..7e67355 --- /dev/null +++ b/agent-task/archive/2026/07/m-usage-token-log-ops-mvp/03+02_grafana_rollup_docs/complete.log @@ -0,0 +1,50 @@ +# Complete - m-usage-token-log-ops-mvp/03+02_grafana_rollup_docs + +## 완료 일시 + +2026-07-10 + +## 요약 + +Grafana usage query guide와 daily/monthly rollup follow-up 문서 evidence를 2회 loop로 완료했다. 최종 판정은 PASS다. + +## 루프 이력 + +| Plan | Review | Verdict | 메모 | +|------|--------|---------|------| +| `plan_local_G03_0.log` | `code_review_local_G03_0.log` | FAIL | daily/monthly rollup PromQL과 dashboard legend/query alignment 보완 필요 | +| `plan_local_G03_1.log` | `code_review_local_G03_1.log` | PASS | `increase()` 기반 rollup과 token type legend alignment 확인 | + +## 구현/정리 내용 + +- `docs/openai-usage-grafana.md`에 OpenAI-compatible usage metric의 Grafana query guide를 작성했다. +- daily/monthly rollup을 `increase(iop_openai_usage_tokens_total[1d])` / `increase(iop_openai_usage_tokens_total[30d])` 기반으로 정리했다. +- 후속 limit policy에서 재사용할 `principal_ref`, `token_ref`, `model_group`, `token_type` grouping 기준과 enforcement 범위 제외를 문서화했다. +- 사용자별 token 사용량 dashboard panel query가 legend에 쓰는 `token_type` label을 보존하도록 정리했다. +- 리뷰 중 task artifact의 trailing whitespace를 정리했다. + +## 최종 검증 + +- `rg --fixed-strings "increase(iop_openai_usage_tokens_total[1d])" docs/openai-usage-grafana.md` - PASS; expected query present. +- `rg --fixed-strings "increase(iop_openai_usage_tokens_total[30d])" docs/openai-usage-grafana.md` - PASS; expected query present. +- `rg --fixed-strings "sum by (principal_alias, token_type)" docs/openai-usage-grafana.md` - PASS; dashboard/grouping examples preserve `token_type`. +- `if rg --fixed-strings "increment(" docs/openai-usage-grafana.md; then exit 1; fi` - PASS; no forbidden non-standard function remains. +- `if rg --fixed-strings "sum_over_time(iop_openai_usage_tokens_total" docs/openai-usage-grafana.md; then exit 1; fi` - PASS; no raw counter `sum_over_time` rollup remains. +- `git diff --check` - PASS; no whitespace errors. + +## Roadmap Completion + +- Milestone: `agent-roadmap/phase/operational-observability-provider-management/milestones/usage-token-log-ops-mvp.md` +- Milestone link: [Milestone 문서](agent-roadmap/phase/operational-observability-provider-management/milestones/usage-token-log-ops-mvp.md) +- Completed task ids: + - `grafana-surface`: PASS; evidence=`plan_local_G03_1.log`, `code_review_local_G03_1.log`; verification=`rg --fixed-strings "sum by (principal_alias, token_type)" docs/openai-usage-grafana.md`, `git diff --check` + - `limit-followup`: PASS; evidence=`plan_local_G03_1.log`, `code_review_local_G03_1.log`; verification=`rg --fixed-strings "increase(iop_openai_usage_tokens_total[1d])" docs/openai-usage-grafana.md`, `rg --fixed-strings "increase(iop_openai_usage_tokens_total[30d])" docs/openai-usage-grafana.md` +- Not completed task ids: 없음 + +## 잔여 Nit + +- 없음 + +## 후속 작업 + +- 없음 diff --git a/agent-task/m-usage-token-log-ops-mvp/03+02_grafana_rollup_docs/PLAN-local-G03.md b/agent-task/archive/2026/07/m-usage-token-log-ops-mvp/03+02_grafana_rollup_docs/plan_local_G03_0.log similarity index 100% rename from agent-task/m-usage-token-log-ops-mvp/03+02_grafana_rollup_docs/PLAN-local-G03.md rename to agent-task/archive/2026/07/m-usage-token-log-ops-mvp/03+02_grafana_rollup_docs/plan_local_G03_0.log diff --git a/agent-task/archive/2026/07/m-usage-token-log-ops-mvp/03+02_grafana_rollup_docs/plan_local_G03_1.log b/agent-task/archive/2026/07/m-usage-token-log-ops-mvp/03+02_grafana_rollup_docs/plan_local_G03_1.log new file mode 100644 index 0000000..26cfd55 --- /dev/null +++ b/agent-task/archive/2026/07/m-usage-token-log-ops-mvp/03+02_grafana_rollup_docs/plan_local_G03_1.log @@ -0,0 +1,115 @@ + + +# Plan - REVIEW_USAGE_GRAFANA + +## 이 파일을 읽는 구현 에이전트에게 + +`CODE_REVIEW-*-G??.md`의 구현 에이전트 소유 섹션을 실제 구현 내용과 검증 출력으로 채우는 것이 마지막 단계다. 구현 후 active 파일을 유지하고 리뷰 준비 상태로 보고한다. 선택된 Milestone `구현 잠금 > 결정 필요` 항목이 실구현을 막을 때만 review stub의 `사용자 리뷰 요청` 섹션에 기록하며, 직접 사용자에게 질문하거나 `USER_REVIEW.md`, `complete.log`, archive log를 만들지 않는다. 환경/secret/service 차단과 검증 증거 공백은 일반 후속 이슈로 기록한다. + +## Roadmap Targets + +- Milestone: `agent-roadmap/phase/operational-observability-provider-management/milestones/usage-token-log-ops-mvp.md` +- Milestone link: [Milestone 문서](agent-roadmap/phase/operational-observability-provider-management/milestones/usage-token-log-ops-mvp.md) +- Task ids: + - `grafana-surface`: Grafana query를 1차 조회 표면으로 둔다. + - `limit-followup`: 제한 enforcement는 후속 범위로 남기고 daily/monthly rollup 기준을 문서화한다. +- Completion mode: check-on-pass + +## Archive Evidence Snapshot + +- Current archived plan: `agent-task/m-usage-token-log-ops-mvp/03+02_grafana_rollup_docs/plan_local_G03_0.log` +- Current archived review: `agent-task/m-usage-token-log-ops-mvp/03+02_grafana_rollup_docs/code_review_local_G03_0.log` +- Verdict: FAIL +- Required summary: + - `docs/openai-usage-grafana.md:166`: daily/monthly rollup examples are presented as PromQL, but `increment()` is not a Prometheus standard function. + - `docs/openai-usage-grafana.md:170-175`: fallback example combines aggregation modifiers and raw counter snapshots, so it is not a valid daily delta rollup. + - `docs/openai-usage-grafana.md:191`: `sum_over_time()` over a raw counter is not a 30-day usage increase and does not satisfy reusable limit follow-up evidence. +- Suggested summary: + - `docs/openai-usage-grafana.md:150`: dashboard legend uses `{{token_type}}`, but the query groups only by `principal_alias`. +- Affected files: + - `docs/openai-usage-grafana.md` +- Verification evidence from previous loop: + - `rg --fixed-strings "iop_openai_usage_tokens_total" docs/openai-usage-grafana.md` - PASS; showed metric examples and the problematic rollup lines. + - `rg --fixed-strings "daily" docs/openai-usage-grafana.md` - PASS; only string presence, not PromQL validity. + - `rg --fixed-strings "monthly" docs/openai-usage-grafana.md` - PASS; only string presence, not PromQL validity. + - `git diff --check` - PASS; no output. +- Roadmap carryover: + - Keep `grafana-surface` and `limit-followup` as target task ids. + - Do not update `agent-roadmap/**` from this implementation or review loop. +- Narrow archive reread allowed if needed: + - `agent-task/m-usage-token-log-ops-mvp/03+02_grafana_rollup_docs/plan_local_G03_0.log` + - `agent-task/m-usage-token-log-ops-mvp/03+02_grafana_rollup_docs/code_review_local_G03_0.log` + +## 배경 + +첫 리뷰에서 metric 이름과 label allowlist는 실제 코드와 일치함을 확인했다. 실패 지점은 docs/query 품질이다. `limit-followup` Task는 daily/monthly warn/reject 정책에 재사용 가능한 rollup 기준을 문서화해야 하는데, 현재 문서는 Prometheus counter 증가분 계산에 맞지 않는 예시를 포함한다. + +## 범위 결정 근거 + +- 포함: `docs/openai-usage-grafana.md`의 daily/monthly rollup PromQL 수정. +- 포함: 후속 제한 정책에서 재사용할 수 있도록 principal/token/model/token type 기준 grouping 예시 보강. +- 포함: token type legend를 쓰는 dashboard panel query의 label 보존 수정. +- 제외: Grafana JSON dashboard import file, Control Plane/Client dashboard, billing/cost model, user CRUD, token limit enforcement. +- 제외: metric 이름/label schema 변경. 이번 후속은 문서 query correction만 다룬다. + +## 구현 체크리스트 + +- [ ] `docs/openai-usage-grafana.md` daily/monthly rollup PromQL을 `increase()` 기반 counter delta query로 수정한다. +- [ ] `docs/openai-usage-grafana.md`에서 `increment()`, invalid `by`/`without` 혼합, raw counter `sum_over_time()` 대안을 제거하거나 Prometheus query가 아닌 설명으로 분리한다. +- [ ] daily/monthly rollup query가 `principal_alias`/`principal_ref`/`token_ref`/`model_group`/`token_type` 기준 재사용 예시를 포함하도록 보강한다. +- [ ] 사용자별 token 사용량 dashboard panel query가 legend에 쓰는 `token_type` label을 보존하도록 수정한다. +- [ ] 검증 명령을 실행한다. +- [ ] CODE_REVIEW-*-G??.md의 구현 에이전트 소유 섹션을 실제 구현 내용과 검증 출력으로 채운다. 이 항목이 완료되기 전에는 구현이 완료된 것이 아니다. + +### [REVIEW_USAGE_GRAFANA-1] Prometheus Rollup Correction + +문제: daily/monthly rollup 예시가 Prometheus datasource에서 바로 재사용 가능한 PromQL이 아니며, counter 증가분이 아닌 raw counter sample 집계를 제시한다. + +수정 파일 및 체크리스트: +- [ ] `docs/openai-usage-grafana.md`: 일일 rollup을 `increase(iop_openai_usage_tokens_total[1d])` 기반 query로 수정한다. +- [ ] `docs/openai-usage-grafana.md`: 월간 rollup을 `increase(iop_openai_usage_tokens_total[30d])` 기반 query로 수정한다. +- [ ] `docs/openai-usage-grafana.md`: `principal_alias`, `principal_ref`, `token_ref`, `model_group`, `token_type` grouping을 후속 limit policy 재사용 관점에서 명시한다. +- [ ] `docs/openai-usage-grafana.md`: `increment()`, invalid `by`/`without` 혼합, raw counter `sum_over_time()`를 제거한다. + +검증: + +```bash +rg --fixed-strings "increase(iop_openai_usage_tokens_total[1d])" docs/openai-usage-grafana.md +rg --fixed-strings "increase(iop_openai_usage_tokens_total[30d])" docs/openai-usage-grafana.md +if rg --fixed-strings "increment(" docs/openai-usage-grafana.md; then exit 1; fi +if rg --fixed-strings "sum_over_time(iop_openai_usage_tokens_total" docs/openai-usage-grafana.md; then exit 1; fi +``` + +### [REVIEW_USAGE_GRAFANA-2] Dashboard Token Type Label Alignment + +문제: dashboard panel 후보의 사용자별 token 사용량 query가 `token_type` label을 drop하면서 legend에 `{{token_type}}`을 사용한다. + +수정 파일 및 체크리스트: +- [ ] `docs/openai-usage-grafana.md`: 사용자별 token 사용량 panel query를 `sum by (principal_alias, token_type) (...)` 형태로 수정한다. +- [ ] `docs/openai-usage-grafana.md`: legend와 query grouping label이 서로 맞는지 확인한다. + +검증: + +```bash +rg --fixed-strings "sum by (principal_alias, token_type)" docs/openai-usage-grafana.md +rg --fixed-strings "legend=\`{{principal_alias}} {{token_type}}\`" docs/openai-usage-grafana.md +``` + +## 수정 파일 요약 + +| 파일 | 항목 | +|------|------| +| `docs/openai-usage-grafana.md` | REVIEW_USAGE_GRAFANA-1, REVIEW_USAGE_GRAFANA-2 | + +## 최종 검증 + +```bash +rg --fixed-strings "increase(iop_openai_usage_tokens_total[1d])" docs/openai-usage-grafana.md +rg --fixed-strings "increase(iop_openai_usage_tokens_total[30d])" docs/openai-usage-grafana.md +rg --fixed-strings "sum by (principal_alias, token_type)" docs/openai-usage-grafana.md +if rg --fixed-strings "increment(" docs/openai-usage-grafana.md; then exit 1; fi +if rg --fixed-strings "sum_over_time(iop_openai_usage_tokens_total" docs/openai-usage-grafana.md; then exit 1; fi +git diff --check +``` + +모든 문서 변경 완료 후 반드시 `CODE_REVIEW-*-G??.md`의 구현 에이전트 소유 섹션을 채운다. 이 파일 작성이 구현의 마지막 단계다. diff --git a/agent-task/m-usage-token-log-ops-mvp/03+02_grafana_rollup_docs/CODE_REVIEW-local-G03.md b/agent-task/m-usage-token-log-ops-mvp/03+02_grafana_rollup_docs/CODE_REVIEW-local-G03.md deleted file mode 100644 index bc63331..0000000 --- a/agent-task/m-usage-token-log-ops-mvp/03+02_grafana_rollup_docs/CODE_REVIEW-local-G03.md +++ /dev/null @@ -1,135 +0,0 @@ - - -# Code Review Reference - USAGE_GRAFANA - -> **[IMPLEMENTING AGENT - READ FIRST] Filling in this file is the mandatory final step of implementation.** -> The task is NOT complete until every implementation-owned section below is filled in. -> Complete the `구현 체크리스트`; the final checklist item is mandatory before saving. -> Fill implementation-owned sections, then stop with active files in place and report ready for review. -> If implementation is blocked by a selected Milestone `구현 잠금 > 결정 필요` item, fill `사용자 리뷰 요청` with linked evidence and stop with active files in place; code-review decides whether to write `USER_REVIEW.md`. Environment/secret/service blockers, generic scope changes, repeated failures, and evidence gaps that a follow-up agent can close are normal follow-up issues, not user-review blockers by themselves. -> Do not ask the user directly, present choices in chat, or call `request_user_input` during implementation; record only Milestone lock decisions in `사용자 리뷰 요청` and stop for code-review. -> Finalization (`코드리뷰 결과`, log rename, `complete.log`, archive moves, `코드리뷰 전용 체크리스트`) is review-agent-only, even after compaction/resume. -> Follow the ownership table at the bottom of this file for which sections you own. - -## 개요 - -date=2026-07-09 -task=m-usage-token-log-ops-mvp/03+02_grafana_rollup_docs, plan=0, tag=USAGE_GRAFANA - -## Roadmap Targets - -- Milestone: `agent-roadmap/phase/operational-observability-provider-management/milestones/usage-token-log-ops-mvp.md` -- Milestone link: [Milestone 문서](agent-roadmap/phase/operational-observability-provider-management/milestones/usage-token-log-ops-mvp.md) -- Task ids: - - `grafana-surface`: Grafana query를 1차 조회 표면으로 둔다. - - `limit-followup`: 제한 enforcement는 후속 범위로 남기고 daily/monthly rollup 기준을 문서화한다. -- Completion mode: check-on-pass - -## 이 파일을 읽는 리뷰 에이전트에게 - -> **[REVIEW AGENT ONLY]** 아래 종결 절차는 코드리뷰 에이전트 전용이다. 구현 에이전트는 이 섹션을 실행하지 않는다. - -각 항목의 구현을 실제 문서와 대조하고, `검증 결과` 섹션의 출력이 문서와 일치하는지 확인하세요. -리뷰 완료는 아래 순서까지 끝난 상태를 의미합니다. - -1. 판정을 append한다. -2. `CODE_REVIEW-local-G03.md` -> `code_review_local_G03_N.log`, `PLAN-local-G03.md` -> `plan_local_G03_M.log`로 아카이브한다. -3. PASS이면 `complete.log` 작성 후 active task 디렉터리를 `agent-task/archive/YYYY/MM/m-usage-token-log-ops-mvp/03+02_grafana_rollup_docs/`로 이동한다. -4. PASS complete.log에는 `Roadmap Completion` 섹션을 포함하고 completed task ids로 `grafana-surface`, `limit-followup`을 적는다. -5. PASS이고 task group이 `m-usage-token-log-ops-mvp`이면 완료 이벤트 메타데이터를 보고한다. roadmap 수정이나 `update-roadmap` 직접 호출은 런타임 책임이다. - ---- - -## 구현 항목별 완료 여부 - -| 항목 | 완료 여부 | -|------|---------| -| [USAGE_GRAFANA-1] Grafana Operator Guide | [ ] | -| [USAGE_GRAFANA-2] Limit Follow-up Rollup | [ ] | - -## 구현 체크리스트 - -- [ ] 선행 `02+01_usage_metrics`의 active 또는 same-task-group archive `complete.log`와 PASS evidence를 확인한다. -- [ ] 02에서 확정된 metric 이름과 label allowlist를 실제 코드에서 확인한다. -- [ ] `docs/openai-usage-grafana.md`를 작성한다. -- [ ] Grafana query examples가 principal/token/model/token type별 사용량을 보여주도록 작성한다. -- [ ] daily/monthly rollup과 limit follow-up 경계를 명확히 문서화한다. -- [ ] 검증 명령을 실행한다. -- [ ] CODE_REVIEW-*-G??.md의 구현 에이전트 소유 섹션을 실제 구현 내용과 검증 출력으로 채운다. 이 항목이 완료되기 전에는 구현이 완료된 것이 아니다. - -## 코드리뷰 전용 체크리스트 - -> **[REVIEW AGENT ONLY]** 이 체크리스트는 코드리뷰 에이전트만 사용한다. -> 구현 에이전트는 이 섹션을 수정하거나 체크하지 않는다. - -- [ ] `코드리뷰 결과`에 `PASS`, `WARN`, `FAIL` 중 하나의 판정을 append한다. -- [ ] active `CODE_REVIEW-*-G??.md`와 `PLAN-*-G??.md`를 `.log`로 아카이브한다. -- [ ] PASS이면 `complete.log`를 작성하고 active `.md` 파일을 남기지 않는다. -- [ ] PASS이면 active task 디렉터리를 archive로 이동한다. -- [ ] PASS이고 task group이 `m-usage-token-log-ops-mvp`이면 완료 이벤트 메타데이터를 보고하고 roadmap을 직접 수정하지 않는다. - -## 계획 대비 변경 사항 - -_구현 에이전트가 계획과 다르게 구현한 부분을 이유와 함께 기록한다._ - -## 주요 설계 결정 - -_구현 에이전트가 주요 설계 결정 사항을 기록한다._ - -## 사용자 리뷰 요청 - -_기본값은 `없음`이다. 구현 중 새 결정이 필요해 보여도 직접 질문하거나 선택지를 제시하거나 `request_user_input`을 호출하지 않는다. 이 섹션은 선택된 Milestone `구현 잠금 > 결정 필요` 항목이 실구현을 차단할 때만 채운다. 외부 환경/secret/서비스 준비, 검증 증거 공백, 반복 실패, 일반 범위 조정은 사용자 리뷰 요청이 아니며 `검증 결과`, `계획 대비 변경 사항`, 또는 code-review의 일반 follow-up plan으로 처리한다._ - -- 상태: 없음 -- 사유 유형: 없음 -- 연결 대상: 없음 -- 결정 필요: 없음 -- 차단 근거: 없음 -- 실행한 검증/명령: 없음 -- 자동 후속 불가 이유: 없음 -- 재개 조건: 없음 - -## 리뷰어를 위한 체크포인트 - -- 문서 query가 실제 구현된 metric 이름과 label만 쓰는지 확인한다. -- Control Plane/Client dashboard 구현을 범위에 끌어들이지 않았는지 확인한다. -- limit enforcement가 구현된 것처럼 표현하지 않고 후속 범위로 남겼는지 확인한다. -- raw token, provider token, request_id, session_id, raw payload를 Grafana label/group-by로 권장하지 않는지 확인한다. - -## 검증 결과 - -_구현 에이전트가 각 중간 검증 및 최종 검증 명령 실행 후 출력을 여기에 붙여 넣는다._ - -### USAGE_GRAFANA-1 중간 검증 -```bash -$ rg --fixed-strings "iop_openai_usage_tokens_total" docs/openai-usage-grafana.md -(output) -$ rg --fixed-strings "iop_openai_reasoning_observed_total" docs/openai-usage-grafana.md -(output) -``` - -### USAGE_GRAFANA-2 중간 검증 -```bash -$ rg --fixed-strings "daily" docs/openai-usage-grafana.md -(output) -$ rg --fixed-strings "monthly" docs/openai-usage-grafana.md -(output) -$ rg --fixed-strings "후속" docs/openai-usage-grafana.md -(output) -``` - -### 최종 검증 -```bash -$ rg --fixed-strings "iop_openai_usage_tokens_total" docs/openai-usage-grafana.md -(output) -$ rg --fixed-strings "daily" docs/openai-usage-grafana.md -(output) -$ rg --fixed-strings "monthly" docs/openai-usage-grafana.md -(output) -$ git diff --check -(output) -``` - ---- - -> **[IMPLEMENTING AGENT - BEFORE SAVING] Have you filled in every implementation-owned section: completion table, implementation checklist, changes from plan, design decisions, and verification output?** diff --git a/docs/openai-usage-grafana.md b/docs/openai-usage-grafana.md new file mode 100644 index 0000000..20ae40c --- /dev/null +++ b/docs/openai-usage-grafana.md @@ -0,0 +1,233 @@ +# OpenAI-compatible Usage – Grafana Query Guide + +> **Purpose**: 이 문서는 운영자가 Prometheus metric을 Grafana 패널로 조회해 사용자별 OpenAI-compatible token 사용량을 볼 수 있도록 한다. Control Plane/Client dashboard, request-level ledger, 사용자별 제한 enforcement는 만들지 않는다. + +--- + +## Metric 목록 + +### 1. `iop_openai_usage_tokens_total` (Counter) + +Provider-reported OpenAI-compatible token usage by token type. + +| Label | Value 예시 | 설명 | +|-------|-----------|------| +| `edge_id` | `edge-1` | Edge instance identity | +| `principal_ref` | `usr-abc123` | Principal foreign-key-like reference | +| `principal_alias` | `john@acme` | Human-readable alias | +| `token_ref` | `tok-xyz789` | Token identity (not a raw secret) | +| `model_group` | `gpt-4o` | Model group identifier | +| `endpoint` | `chat.completions`, `responses` | OpenAI-compatible route | +| `response_mode` | `blocking`, `streaming` | Response mode | +| `token_type` | `input`, `output`, `reasoning`, `cached_input` | Token type | + +### 2. `iop_openai_requests_total` (Counter) + +OpenAI-compatible requests processed by terminal status and usage source. + +| Label | Value 예시 | 설명 | +|-------|-----------|------| +| `edge_id` | `edge-1` | Edge instance identity | +| `principal_ref` | `usr-abc123` | Principal reference | +| `principal_alias` | `john@acme` | Human-readable alias | +| `token_ref` | `tok-xyz789` | Token identity | +| `model_group` | `gpt-4o` | Model group identifier | +| `endpoint` | `chat.completions`, `responses` | OpenAI-compatible route | +| `response_mode` | `blocking`, `streaming` | Response mode | +| `status` | `success`, `error`, `cancel` | Terminal request status | +| `usage_source` | `provider_reported`, `unavailable` | Whether at least one token type was reported | + +### 3. `iop_openai_reasoning_observed_total` (Counter) + +Requests where reasoning text was observed but the provider did not report reasoning token usage. +Same labels as `iop_openai_requests_total` excluding `status` and `usage_source`: `edge_id`, `principal_ref`, `principal_alias`, `token_ref`, `model_group`, `endpoint`, `response_mode`. + +### 4. `iop_openai_reasoning_chars_total` (Counter) + +Observed reasoning text characters for requests without provider-reported reasoning tokens. Never converted to a token estimate. + +--- + +## Label Allowlist & Forbidden Labels + +### 허용 label + +``` +edge_id, principal_ref, principal_alias, token_ref, +model_group, endpoint, response_mode, status, +token_type, usage_source +``` + +### 금지 label + +- `request_id`, `session_id` — request-level 상세는 후속 ledger/Loki 축에서 다룬다. +- Bearer token, provider API key, raw payload, raw prompt/response text — secret 누출 방지 (SDD S08). +- 그 외 임의 label — cardinality 폭발을 막는다. + +--- + +## PromQL Examples + +### 기본: 사용자별 사용량 (principal_alias 기준) + +```promql +# 입력 토큰 합계 +sum by (principal_alias) (iop_openai_usage_tokens_total{token_type="input"}) + +# 출력 토큰 합계 +sum by (principal_alias) (iop_openai_usage_tokens_total{token_type="output"}) +``` + +### principal_ref별 usage breakdown + +```promql +# principal_ref, token_type별 aggregation +sum by (principal_ref, token_type) (iop_openai_usage_tokens_total) +``` + +### token_ref별 사용량 + +```promql +# token_ref별 input/output 합계 +sum by (token_ref, token_type) (iop_openai_usage_tokens_total) +``` + +### model_group별 usage + +```promql +# model_group, token_type별 aggregation +sum by (model_group, token_type) (iop_openai_usage_tokens_total) +``` + +### endpoint별 요청 수 + +```promql +# endpoint, status별 요청 수 +sum by (endpoint, status) (iop_openai_requests_total) +``` + +### response_mode별 분석 + +```promql +# response_mode별 성공 요청 수 +sum by (response_mode, status) (iop_openai_requests_total{status="success"}) +``` + +### token_type별 사용량 전체 + +```promql +# 모든 token_type별 합계 (time range 그래프용) +sum by (token_type) (irate(iop_openai_usage_tokens_total[5m])) +``` + +### usage_source별 요청 coverage + +```promql +# provider_reported vs unavailable 비율 +sum by (usage_source) (iop_openai_requests_total) +``` + +### reasoning 보조 metric + +provider가 reasoning token을 보고하지 않는 경우: + +```promql +# reasoning text가 관찰된 요청 수 (provider token 미보고) +sum by (principal_alias) (iop_openai_reasoning_observed_total) + +# reasoning text character 합계 +sum by (principal_alias) (iop_openai_reasoning_chars_total) +``` + +> **주의**: `iop_openai_reasoning_observed_total` / `iop_openai_reasoning_chars_total`는 provider-reported reasoning token이 있을 경우 emit되지 않는다. 즉, 이 metric은 "reasoning text는 있으나 token count 보고를 안 하는 provider"만 커버한다. token 추정을 위해 chars를 사용할 수 있으나 이 문서는 추정 권유를 하지 않는다. + +--- + +## Dashboard Panel 후보 + +| 패널 | query | visualization | +|------|-------|---------------| +| 사용자별 token 사용량 (line) | `sum by (principal_alias, token_type) (irate(iop_openai_usage_tokens_total[5m]))` | Time series, legend=`{{principal_alias}} {{token_type}}` | +| model_group별 token 비율 (pie) | `sum by (model_group, token_type) (iop_openai_usage_tokens_total)` | Stat or bar chart | +| 요청 상태 분포 (table) | `sum by (endpoint, status, usage_source) (iop_openai_requests_total)` | Table | +| reasoning 보조 지표 (singlestat) | `sum(iop_openai_reasoning_observed_total)` | Singlestat | + +> Grafana JSON dashboard import file은 본 scope에 포함되지 않는다. 위 PromQL을 바탕으로 패널을 수동 구성한다. + +--- + +## daily / monthly Rollup + +### 일일 토큰 합계 + +```promql +# 일일 입력/출력 토큰 합계 (principal_alias별) +sum by (principal_alias, token_type) ( + increase(iop_openai_usage_tokens_total[1d]) +) +``` + +> Grafana dashboard에서 `by time` aggregation으로 대체 가능: +> ```promql +> # Grafana 범용 aggregation (PromQL 함수 아님) +> # time range를 1일로 설정 후 sum by (principal_alias, token_type) +> iop_openai_usage_tokens_total +> ``` + +### 월간 토큰 합계 + +```promql +# 월간 입력/출력 토큰 합계 (principal_alias별) +sum by (principal_alias, token_type) ( + increase(iop_openai_usage_tokens_total[30d]) +) +``` + +> Grafana dashboard에서 범용 aggregation으로 대체 가능: +> ```promql +> # Grafana 범용 aggregation (PromQL 함수 아님) +> # time range를 30일로 설정 후 sum by (principal_alias, token_type) +> iop_openai_usage_tokens_total +> ``` + +### 일일/월간 rollup 활용 시나리오 + +- `principal_alias` 또는 `principal_ref`를 `by` clause에 추가해 사용자별 일일/월간 토큰 사용량을 산출한다. +- `token_type`을 함께 group by하면 input/output/reasoning/cached_input을 구분한다. +- `model_group`을 추가하면 모델별 비용 기반 추정 가능하다 (billing 산출은 이 문서 범위를 벗남). + +--- + +## Limit Follow-up: 경계 명시 + +### 후속 Milestone으로 남기는 항목 + +- 사용자별 daily/monthly token **warn** 또는 **reject** enforcement는 이 Milestone의 범위가 아니며 후속 Milestone으로 Planned된다. +- billing, price, ROI amount 산출은 별도 ledger/cost model 범위다. +- request-level ledger / audit log는 Loki/queriable log축 후속 작업의 대상이다. + +### 현재 문서가 제공하는 것 + +- `principal_ref`, `token_ref`, `model_group`, `token_type` 라벨 기반 daily/monthly rollup PromQL +- 사용자별 사용량 조회를 통한 운영 판단 기준 +- provider reasoning report 누락 시 `reasoning_observed_total` / `reasoning_chars_total`로 보조 확인 + +이 rollup 기준은 후속 enforce Milestone에서 Prometheus query를 그대로 재사용할 수 있도록 설계되었다. + +--- + +## Quick Reference: Label Values + +| Label | 허용 값 | +|-------|---------| +| `endpoint` | `chat.completions`, `responses` | +| `status` | `success`, `error`, `cancel` | +| `usage_source` | `provider_reported`, `unavailable` | +| `token_type` | `input`, `output`, `reasoning`, `cached_input` | +| `response_mode` | `blocking`, `streaming` | + +--- + +## Appendix: Grafana Scrape Target + +Edge metrics는 보통 `localhost:19092` (local) 또는 해당 Edge metrics port에서 Prometheus scrape된다. Grafana data source에 Prometheus를 추가하고 위 PromQL을 테스트 패널에서 검증한다. \ No newline at end of file