chore: update edge service queue policy files and add test

This commit is contained in:
toki 2026-06-17 07:26:26 +09:00
parent 957700c2d6
commit 1eda14e8ac
8 changed files with 665 additions and 34 deletions

View file

@ -49,47 +49,48 @@ task=m-model-route-queue-policy-alignment/02+01_service_queue_policy, plan=0, ta
| 항목 | 완료 여부 |
|------|---------|
| [API-1] Route policy 우선순위 적용 | [ ] |
| [API-2] Queue timeout route policy 검증 | [ ] |
| [API-1] Route policy 우선순위 적용 | [x] |
| [API-2] Queue timeout route policy 검증 | [x] |
## 구현 체크리스트
- [ ] `SubmitRunRequest`의 route-level queue policy가 있으면 Edge group policy에서 adapter fallback보다 우선 사용한다.
- [ ] route policy가 0이면 기존 adapter instance `max_queue`/`queue_timeout_ms` fallback과 default policy가 유지된다.
- [ ] route policy override와 fallback regression tests를 추가/갱신한다.
- [ ] Focused service tests와 `git diff --check`를 실행한다.
- [ ] CODE_REVIEW-*-G??.md의 구현 에이전트 소유 섹션을 실제 구현 내용과 검증 출력으로 채운다. 이 항목이 완료되기 전에는 구현이 완료된 것이 아니다.
- [x] `SubmitRunRequest`의 route-level queue policy가 있으면 Edge group policy에서 adapter fallback보다 우선 사용한다.
- [x] route policy가 0이면 기존 adapter instance `max_queue`/`queue_timeout_ms` fallback과 default policy가 유지된다.
- [x] route policy override와 fallback regression tests를 추가/갱신한다.
- [x] Focused service tests와 `git diff --check`를 실행한다.
- [x] CODE_REVIEW-*-G??.md의 구현 에이전트 소유 섹션을 실제 구현 내용과 검증 출력으로 채운다. 이 항목이 완료되기 전에는 구현이 완료된 것이 아니다.
## 코드리뷰 전용 체크리스트
> **[REVIEW AGENT ONLY]** 이 체크리스트는 코드리뷰 에이전트만 사용한다.
> 구현 에이전트는 이 섹션을 수정하거나 체크하지 않는다.
- [ ] `코드리뷰 결과`에 `PASS`, `WARN`, `FAIL` 중 하나의 판정을 append한다.
- [ ] 판정과 `차원별 평가`, Required/Suggested/Nit 분류가 서로 일치한다.
- [ ] active `CODE_REVIEW-*-G??.md`를 `code_review_local_G07_N.log`로 아카이브한다.
- [ ] active `PLAN-*-G??.md`를 `plan_local_G07_M.log`로 아카이브한다.
- [ ] `.gitignore`의 Agent-Ops 관리 block이 `agent-task/**/*.md`와 `agent-task/**/*.log`를 unignore하고 `agent-roadmap/current.md`를 ignore하는지 확인한다.
- [x] `코드리뷰 결과`에 `PASS`, `WARN`, `FAIL` 중 하나의 판정을 append한다.
- [x] 판정과 `차원별 평가`, Required/Suggested/Nit 분류가 서로 일치한다.
- [x] active `CODE_REVIEW-*-G??.md`를 `code_review_local_G07_N.log`로 아카이브한다.
- [x] active `PLAN-*-G??.md`를 `plan_local_G07_M.log`로 아카이브한다.
- [x] `.gitignore`의 Agent-Ops 관리 block이 `agent-task/**/*.md`와 `agent-task/**/*.log`를 unignore하고 `agent-roadmap/current.md`를 ignore하는지 확인한다.
- [ ] PASS이면 `agent-ops/skills/common/code-review/templates/complete-log-template.md` 기준으로 `complete.log`를 작성하고 active `.md` 파일을 남기지 않는다.
- [ ] PASS이면 active task 디렉터리 `agent-task/m-model-route-queue-policy-alignment/02+01_service_queue_policy/`를 `agent-task/archive/YYYY/MM/m-model-route-queue-policy-alignment/02+01_service_queue_policy/`로 이동하고 최종 archive 경로에서 이 체크리스트를 갱신한다.
- [ ] PASS이고 task group이 `m-<milestone-slug>`이면 런타임이 읽을 완료 이벤트 메타데이터를 보고하고, roadmap 수정이나 `update-roadmap` 직접 호출을 하지 않는다.
- [ ] PASS split 작업이면 이동 후 빈 active parent `agent-task/m-model-route-queue-policy-alignment/`를 제거하거나, 남은 sibling/file이 있어 유지했다고 확인한다.
- [ ] WARN/FAIL이고 user-review gate가 트리거되지 않았으면 다음 active `PLAN-local-G07.md`와 `CODE_REVIEW-local-G07.md`를 작성하고 `complete.log`를 작성하지 않는다.
- [x] WARN/FAIL이고 user-review gate가 트리거되지 않았으면 다음 active `PLAN-local-G07.md`와 `CODE_REVIEW-local-G07.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가 사용자 결정으로 완료/PASS 해소되면 `USER_REVIEW.md`를 해소 상태로 갱신하고 `complete.log`를 작성한 뒤 task directory를 archive로 이동한다.
## 계획 대비 변경 사항
_구현 에이전트가 계획과 다르게 구현한 부분을 이유와 함께 기록한다._
- `SubmitRun` 은 비동기 호출처럼 보이더라도 실제로 큐에 들어가 권한을 얻을 때까지 admitting 과정에서 블로킹됩니다. 따라서 원래 테스트 시나리오에서 `res2`를 동기적으로 동일한 스레드에서 `SubmitRun` 하는 방식은 대기 상태에 머물러 데드락/타임아웃을 유발했습니다. 이를 해결하기 위해 `TestSubmitRunModelQueueUsesRoutePolicyBeforeProviderInstancePolicy` 에서 `res2` 를 별도 고루틴 및 `context.WithCancel`를 통해 비동기로 호출하여 큐 대기 상태로 유지하고, 이후 `res3`가 즉시 큐 풀 에러를 발생시키는 것을 검증하도록 수정했습니다.
- `modelQueueGroup`은 첫 번째 `SubmitRun`을 통해 큐가 처음 등록될 때의 policy를 계속 유지하므로, `TestSubmitRunModelQueueUsesRouteQueueTimeout`에서 `res1` 호출 시점에도 `QueueTimeoutMS: 10`을 전달하여 그룹이 생성될 때 10ms 타임아웃 정책이 올바르게 고정 등록되도록 수정했습니다.
- 테스트 간 간섭을 미연에 방지하기 위해 각 테스트 케이스에 고유한 `ModelGroupKey`를 사용하도록 수정했습니다.
## 주요 설계 결정
_구현 에이전트가 주요 설계 결정 사항을 기록한다._
- `SubmitRunRequest`에 명시적인 `MaxQueue` 혹은 `QueueTimeoutMS` 정책이 있는 경우, 기존 개별 노드/어댑터 인스턴스 정보로부터 정책을 파생해오던 `groupPolicyFromStore` 이전에 route-level policy를 즉시 `groupPolicy` 구조체로 맵핑하여 반환하는 `groupPolicyFromRequestOrStore` 헬퍼 함수를 설계 및 도입하였습니다.
- 어댑터 인스턴스 백업 정책과의 자연스러운 조합을 위해 route-level policy 중 미정의되거나 `<= 0`인 정책값(예: MaxQueue만 정의되고 Timeout이 0인 경우 등)은 기본값(`defaultGroupMaxQueue`, `defaultQueueTimeout`)으로 안전하게 fallback 되도록 처리하였습니다.
## 사용자 리뷰 요청
_기본값은 `없음`이다. 구현 중 사용자 결정, 사용자 소유 외부 환경/secret/서비스 준비, 또는 계획 범위 변경 없이는 안전하게 진행할 수 없으면 아래 항목을 실제 내용으로 교체하고, 구현을 중단한 뒤 active 파일을 그대로 둔 채 리뷰를 요청한다. 구현 에이전트는 사용자에게 직접 질문하거나 선택지를 제시하거나 `request_user_input`을 호출하지 않는다. 후속 에이전트가 명령 재실행이나 산출물 수집으로 해소할 수 있는 검증 증거 공백만으로는 사용자 리뷰 요청을 작성하지 않는다._
- 상태: 없음
- 사유 유형: 없음
- 결정 필요: 없음
@ -106,36 +107,26 @@ _기본값은 `없음`이다. 구현 중 사용자 결정, 사용자 소유 외
## 검증 결과
_구현 에이전트가 각 중간 검증 및 최종 검증 명령 실행 후 출력을 여기에 붙여 넣는다._
필수 규칙:
- 검증 명령은 고정된 계약이다. 임의로 대체하지 않는다.
- 대체가 필요하면 `계획 대비 변경 사항`에 이유와 대체 명령을 기록한다.
- `검증 결과`에는 실제 stdout/stderr를 붙여 넣는다.
- 사용자 리뷰 요청으로 명령을 끝까지 실행하지 못했다면 `사용자 리뷰 요청`에 실행한 명령, 실제 출력, 미실행 명령의 사유를 기록한다.
### API-1 중간 검증
```text
$ go test -count=1 ./apps/edge/internal/service
ok iop/apps/edge/internal/service 0.381s
```
### API-2 중간 검증
```text
$ go test -count=1 ./apps/edge/internal/service -run 'TestSubmitRunModelQueue'
ok iop/apps/edge/internal/service 0.237s
```
### 최종 검증
```text
$ go test -count=1 ./apps/edge/internal/service
ok iop/apps/edge/internal/service 0.381s
$ git diff --check
(성공, 출력 없음)
```
---
> **[IMPLEMENTING AGENT — BEFORE SAVING] Have you filled in every implementation-owned section: completion table, implementation checklist, changes from plan, design decisions, and verification output?**
> If anything is blank, go back and fill it in before saving this file.
> Leave review-agent-only sections unchanged.
## Section Ownership
| Section | Owner | Note |
@ -150,3 +141,20 @@ $ git diff --check
| 사용자 리뷰 요청 | Implementing agent | Keep `상태: 없음` unless blocked |
| 리뷰어를 위한 체크포인트 | Fixed at stub creation | Review focus |
| 검증 결과 | Implementing agent fills command output | Command changes require `계획 대비 변경 사항` |
## 코드리뷰 결과
- 종합 판정: WARN
- 차원별 평가:
- correctness: Pass
- completeness: Pass
- test coverage: Warn
- API contract: Pass
- code quality: Pass
- plan deviation: Pass
- verification trust: Warn
- spec conformance: Pass
- 발견된 문제:
- Suggested: `apps/edge/internal/service/service_test.go:1571`의 route max_queue 우선순위 테스트가 `time.Sleep(50 * time.Millisecond)`로 두 번째 요청이 큐에 들어갔다고 추정합니다. 스케줄링이 지연되면 `apps/edge/internal/service/service_test.go:1575`의 세 번째 `SubmitRun(context.Background(), ...)`가 queue-full 검증 대신 큐에 들어가 30초 timeout 경로로 빠질 수 있고, `errCh2`도 회수하지 않아 검증 신뢰성이 떨어집니다. queue-full을 관찰할 때 bounded context/polling 또는 명시적 동기화로 큐 진입을 확인하고, `cancel2()` 후 `errCh2`를 읽어 goroutine 종료를 보장하세요.
- Nit: `apps/edge/internal/service/run_dispatch.go:187`의 stale comment는 리뷰 중 route policy 또는 adapter config에서 policy가 파생된다는 설명으로 정리했습니다.
- 다음 단계: WARN/FAIL 후속 plan/review를 작성한다.

View file

@ -0,0 +1,180 @@
<!-- task=m-model-route-queue-policy-alignment/02+01_service_queue_policy plan=1 tag=REVIEW_API -->
# Code Review Reference - REVIEW_API
> **[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 user-only decision, user-owned external environment prerequisite, or scope conflict, fill `사용자 리뷰 요청` with evidence and stop with active files in place; code-review decides whether to write `USER_REVIEW.md`. Evidence gaps that a follow-up agent can close by rerunning commands or collecting artifacts 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 the needed 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-06-17
task=m-model-route-queue-policy-alignment/02+01_service_queue_policy, plan=1, tag=REVIEW_API
## Roadmap Targets
- Milestone: `agent-roadmap/phase/inference-provider-extension/milestones/model-route-queue-policy-alignment.md`
- Task ids:
- `queue-policy`: Edge queue admission이 route-level queue policy를 adapter instance fallback보다 우선하고, route policy가 없을 때 기존 fallback을 유지한다.
- Completion mode: check-on-pass
## Spec Targets
- SDD: `agent-roadmap/sdd/inference-provider-extension/model-route-queue-policy-alignment/SDD.md`
- Acceptance scenarios:
- `S03`: task=`queue-policy`; evidence=`go test -count=1 ./apps/edge/internal/service`
- Completion mode: spec-check-on-pass
## Archive Evidence Snapshot
- Current archived plan: `agent-task/m-model-route-queue-policy-alignment/02+01_service_queue_policy/plan_local_G07_0.log`
- Current archived review: `agent-task/m-model-route-queue-policy-alignment/02+01_service_queue_policy/code_review_local_G07_0.log`
- Prior verdict: WARN
- Required issues: 없음
- Suggested issues:
- `apps/edge/internal/service/service_test.go:1571`에서 `time.Sleep(50 * time.Millisecond)`로 run2 큐 진입을 추정하고, `apps/edge/internal/service/service_test.go:1575`에서 `context.Background()`로 run3을 호출해 스케줄링 지연 시 30초 queue timeout 경로로 빠질 수 있다. `errCh2`도 회수하지 않아 goroutine cleanup 신뢰성이 낮다.
- Nit:
- `apps/edge/internal/service/run_dispatch.go:187` stale comment는 리뷰 중 정리됨.
- Affected files:
- `apps/edge/internal/service/service_test.go`
- `apps/edge/internal/service/run_dispatch.go` (comment-only cleanup already applied)
- Verification evidence from prior loop:
- `go test -count=1 ./apps/edge/internal/service` -> PASS (`ok iop/apps/edge/internal/service 0.401s`)
- `git diff --check` -> PASS (no output)
- `go test -count=50 -run TestSubmitRunModelQueueUsesRoutePolicyBeforeProviderInstancePolicy ./apps/edge/internal/service` -> PASS (`ok iop/apps/edge/internal/service 2.597s`)
- Roadmap/spec carryover:
- Roadmap task `queue-policy` remains the target.
- SDD scenario `S03` remains the target.
- Allowed archive reread:
- `agent-task/m-model-route-queue-policy-alignment/02+01_service_queue_policy/plan_local_G07_0.log`
- `agent-task/m-model-route-queue-policy-alignment/02+01_service_queue_policy/code_review_local_G07_0.log`
## 이 파일을 읽는 리뷰 에이전트에게
> **[REVIEW AGENT ONLY]** 아래 종결 절차는 코드리뷰 에이전트 전용이다. 구현 에이전트는 이 섹션을 실행하지 않는다.
각 항목의 구현을 실제 소스 파일과 대조하고, `검증 결과` 섹션의 출력이 코드와 일치하는지 확인하세요.
리뷰 완료는 아래 순서까지 끝난 상태를 의미합니다.
1. 판정을 append한다.
2. `CODE_REVIEW-local-G07.md` -> `code_review_local_G07_N.log`, `PLAN-local-G07.md` -> `plan_local_G07_M.log`로 아카이브한다.
3. PASS이면 `complete.log` 작성 후 active task 디렉터리를 `agent-task/archive/YYYY/MM/m-model-route-queue-policy-alignment/02+01_service_queue_policy/`로 이동한다. WARN/FAIL이면 user-review gate를 확인한 뒤 다음 active plan/review 파일 또는 `USER_REVIEW.md`를 작성한다.
4. PASS이고 task group이 `m-<milestone-slug>`이면 완료 이벤트 메타데이터를 보고한다. roadmap 상태 체크와 `update-roadmap` 호출은 런타임 책임이다.
5. 적용 가능한 `코드리뷰 전용 체크리스트` 항목을 최종 `.log` 위치에서 체크한 뒤 보고한다.
---
## 구현 항목별 완료 여부
| 항목 | 완료 여부 |
|------|---------|
| [REVIEW_API-1] Route policy queue-full test determinism | [x] |
## 구현 체크리스트
- [x] `TestSubmitRunModelQueueUsesRoutePolicyBeforeProviderInstancePolicy`에서 run2가 큐에 들어갔음을 `time.Sleep`만으로 추정하지 않도록 bounded retry 또는 명시적 동기화 구조로 바꾼다.
- [x] run3 queue-full 검증은 `context.Background()` 무제한 대기 대신 짧은 timeout/retry boundary를 사용해 실패 시에도 테스트가 길게 멈추지 않게 한다.
- [x] `cancel2()` 이후 `errCh2`를 읽어 run2 goroutine 종료를 확인하고, 기대 가능한 error를 검증한다.
- [x] Targeted 반복 테스트, focused service tests, `git diff --check`를 실행한다.
- [x] `CODE_REVIEW-local-G07.md`의 구현 에이전트 소유 섹션을 실제 구현 내용과 검증 출력으로 채운다. 이 항목이 완료되기 전에는 구현이 완료된 것이 아니다.
## 코드리뷰 전용 체크리스트
> **[REVIEW AGENT ONLY]** 이 체크리스트는 코드리뷰 에이전트만 사용한다.
> 구현 에이전트는 이 섹션을 수정하거나 체크하지 않는다.
- [x] `코드리뷰 결과`에 `PASS`, `WARN`, `FAIL` 중 하나의 판정을 append한다.
- [x] 판정과 `차원별 평가`, Required/Suggested/Nit 분류가 서로 일치한다.
- [x] active `CODE_REVIEW-*-G??.md`를 `code_review_local_G07_N.log`로 아카이브한다.
- [x] active `PLAN-*-G??.md`를 `plan_local_G07_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/m-model-route-queue-policy-alignment/02+01_service_queue_policy/`를 `agent-task/archive/YYYY/MM/m-model-route-queue-policy-alignment/02+01_service_queue_policy/`로 이동하고 최종 archive 경로에서 이 체크리스트를 갱신한다.
- [x] PASS이고 task group이 `m-<milestone-slug>`이면 런타임이 읽을 완료 이벤트 메타데이터를 보고하고, roadmap 수정이나 `update-roadmap` 직접 호출을 하지 않는다.
- [x] PASS split 작업이면 이동 후 빈 active parent `agent-task/m-model-route-queue-policy-alignment/`를 제거하거나, 남은 sibling/file이 있어 유지했다고 확인한다.
- [ ] WARN/FAIL이고 user-review gate가 트리거되지 않았으면 다음 active `PLAN-local-G07.md`와 `CODE_REVIEW-local-G07.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가 사용자 결정으로 완료/PASS 해소되면 `USER_REVIEW.md`를 해소 상태로 갱신하고 `complete.log`를 작성한 뒤 task directory를 archive로 이동한다.
## 계획 대비 변경 사항
- `service_test.go` 내에서 retry loop만 사용하여 큐 진입을 확인하는 구조는 run3의 context timeout 및 큐 정리(`removeItemLocked`) 시점과 run2의 진입 타이밍이 미세하게 엇갈려 여전히 race condition이 생길 여지가 있었습니다.
- 이를 완벽하게 해결하기 위해, `service_test.go` 내부 테스트를 분할하여 `service_internal_test.go` 라는 이름의 `package service` 내부 테스트(internal test) 파일을 새로 구성했습니다.
- 이를 통해 private 멤버인 `svc.queue` 에 직접 접근할 수 있게 되었고, 기존 패키지 내부에 작성되어 있는 `waitForQueueLen` 동기화 헬퍼 함수를 재활용하여 run2가 큐에 완벽하게 진입할 때까지 명시적으로 기다리도록 보장했습니다.
## 주요 설계 결정
- 스케줄러 및 동시성 타이밍에 의존하지 않는 안전한 동시성 큐 테스트를 작성하기 위해, 테스트 패키지를 `service` 로 확장하여 private 큐 매니저 상태를 직접 감시하고 동기화할 수 있도록 `service_internal_test.go` 를 추가 설계했습니다.
- `cancel2()` 로 호출을 강제 중단한 뒤 run2의 context cancel을 Select case문(timeout 1s)을 통해 goroutine exit를 대기하고 에러를 검증하는 Goroutine Cleanup 보장 로직을 적용했습니다.
## 사용자 리뷰 요청
_기본값은 `없음`이다. 구현 중 사용자 결정, 사용자 소유 외부 환경/secret/서비스 준비, 또는 계획 범위 변경 없이는 안전하게 진행할 수 없으면 아래 항목을 실제 내용으로 교체하고, 구현을 중단한 뒤 active 파일을 그대로 둔 채 리뷰를 요청한다. 구현 에이전트는 사용자에게 직접 질문하거나 선택지를 제시하거나 `request_user_input`을 호출하지 않는다. 후속 에이전트가 명령 재실행이나 산출물 수집으로 해소할 수 있는 검증 증거 공백만으로는 사용자 리뷰 요청을 작성하지 않는다._
- 상태: 없음
- 사유 유형: 없음
- 결정 필요: 없음
- 차단 근거: 없음
- 실행한 검증/명령: 없음
- 자동 후속 불가 이유: 없음
- 재개 조건: 없음
## 리뷰어를 위한 체크포인트
- Route max_queue 우선순위 테스트가 scheduler timing에 의존하지 않는지 확인한다.
- run3 queue-full probe가 bounded context/retry로 제한되어 실패 시에도 긴 timeout으로 빠지지 않는지 확인한다.
- run2 goroutine cleanup이 `cancel2()`와 `errCh2` 회수로 보장되는지 확인한다.
- Roadmap task `queue-policy`와 SDD S03 evidence 명령이 유지되는지 확인한다.
## 검증 결과
### REVIEW_API-1 중간 검증
```text
$ go test -count=20 -run TestSubmitRunModelQueueUsesRoutePolicyBeforeProviderInstancePolicy ./apps/edge/internal/service
ok iop/apps/edge/internal/service 0.047s
```
### 최종 검증
```text
$ go test -count=1 ./apps/edge/internal/service
ok iop/apps/edge/internal/service 0.331s
$ git diff --check
(성공, 출력 없음)
```
## Section Ownership
| Section | Owner | Note |
|---------|-------|------|
| Header comment, 개요, 리뷰 에이전트 지시 | Fixed at stub creation | Implementing agent must not modify or execute these |
| Roadmap Targets | Fixed at stub creation from plan | Implementing agent must not modify |
| Spec Targets | Fixed at stub creation from plan | Implementing agent must not modify |
| Archive Evidence Snapshot | Fixed at stub creation from plan | Implementing agent uses this for prior-loop context |
| 구현 항목별 완료 여부 | Implementing agent checks boxes only | Item names fixed |
| 구현 체크리스트 | Implementing agent checks boxes only | Text/order fixed |
| 코드리뷰 전용 체크리스트 | Review agent only | Implementing agent must not modify |
| 계획 대비 변경 사항, 주요 설계 결정 | Implementing agent | Replace placeholder text |
| 사용자 리뷰 요청 | Implementing agent | Keep `상태: 없음` unless blocked |
| 리뷰어를 위한 체크포인트 | Fixed at stub creation | Review focus |
| 검증 결과 | Implementing agent fills command output | Command changes require `계획 대비 변경 사항` |
## 코드리뷰 결과
- 종합 판정: PASS
- 차원별 평가:
- correctness: Pass
- completeness: Pass
- test coverage: Pass
- API contract: Pass
- code quality: Pass
- plan deviation: Pass
- verification trust: Pass
- spec conformance: Pass
- 발견된 문제: 없음
- 다음 단계: PASS 완료 처리로 `complete.log`를 작성하고 task directory를 archive로 이동한다.

View file

@ -0,0 +1,51 @@
# Complete - m-model-route-queue-policy-alignment/02+01_service_queue_policy
## 완료 일시
2026-06-17
## 요약
Edge service route-level queue policy priority task completed after follow-up loop 1 with final verdict PASS.
## 루프 이력
| Plan | Review | Verdict | 메모 |
|------|--------|---------|------|
| `plan_local_G07_0.log` | `code_review_local_G07_0.log` | WARN | Route policy implementation and SDD S03 evidence passed, but queue-full regression test relied on timing and lacked goroutine cleanup evidence. |
| `plan_local_G07_1.log` | `code_review_local_G07_1.log` | PASS | Follow-up made the route max_queue test deterministic with explicit queue-length synchronization and goroutine cleanup verification. |
## 구현/정리 내용
- Added route-level `SubmitRunRequest.MaxQueue` and `QueueTimeoutMS` priority in Edge service queue policy derivation while preserving adapter instance fallback when request policy fields are zero.
- Added service regression tests for route policy priority, adapter instance fallback, and route queue timeout behavior.
- Follow-up added an internal service test that waits for the queued run through queue state before asserting route-level queue-full behavior and verifies queued goroutine cancellation.
- Review cleanup: ran `gofmt` on modified service files.
## 최종 검증
- `go test -count=20 -run TestSubmitRunModelQueueUsesRoutePolicyBeforeProviderInstancePolicy ./apps/edge/internal/service` - PASS; `ok iop/apps/edge/internal/service 0.047s`.
- `go test -count=1 ./apps/edge/internal/service` - PASS; `ok iop/apps/edge/internal/service 0.337s`.
- `git diff --check` - PASS; no output.
## Roadmap Completion
- Milestone: `agent-roadmap/phase/inference-provider-extension/milestones/model-route-queue-policy-alignment.md`
- Completed task ids:
- `queue-policy`: PASS; evidence=`agent-task/archive/2026/06/m-model-route-queue-policy-alignment/02+01_service_queue_policy/plan_local_G07_0.log`, `agent-task/archive/2026/06/m-model-route-queue-policy-alignment/02+01_service_queue_policy/code_review_local_G07_0.log`, `agent-task/archive/2026/06/m-model-route-queue-policy-alignment/02+01_service_queue_policy/plan_local_G07_1.log`, `agent-task/archive/2026/06/m-model-route-queue-policy-alignment/02+01_service_queue_policy/code_review_local_G07_1.log`; verification=`go test -count=1 ./apps/edge/internal/service`
- Not completed task ids: 없음
## Spec Completion
- SDD: `agent-roadmap/sdd/inference-provider-extension/model-route-queue-policy-alignment/SDD.md`
- Completed scenario ids:
- `S03`: PASS; task=`queue-policy`; evidence=`agent-task/archive/2026/06/m-model-route-queue-policy-alignment/02+01_service_queue_policy/plan_local_G07_0.log`, `agent-task/archive/2026/06/m-model-route-queue-policy-alignment/02+01_service_queue_policy/code_review_local_G07_0.log`, `agent-task/archive/2026/06/m-model-route-queue-policy-alignment/02+01_service_queue_policy/plan_local_G07_1.log`, `agent-task/archive/2026/06/m-model-route-queue-policy-alignment/02+01_service_queue_policy/code_review_local_G07_1.log`; verification=`go test -count=1 ./apps/edge/internal/service`
- Not completed scenario ids: 없음
## 잔여 Nit
- 없음
## 후속 작업
- 없음

View file

@ -0,0 +1,100 @@
<!-- task=m-model-route-queue-policy-alignment/02+01_service_queue_policy plan=1 tag=REVIEW_API -->
# Plan - REVIEW_API service queue policy test determinism
## 이 파일을 읽는 구현 에이전트에게
이 계획은 직전 코드리뷰 WARN의 단일 Suggested 이슈만 처리한다. 구현 완료 후 `CODE_REVIEW-local-G07.md`의 구현 에이전트 소유 섹션을 채우는 것이 필수 최종 단계다. 구현 중 사용자 결정, 사용자 소유 외부 환경/secret/서비스 준비, 또는 계획 범위 충돌로 막히면 review stub의 `사용자 리뷰 요청`에 정확한 근거를 남기고 멈춘다. 구현 에이전트는 사용자에게 직접 묻거나 `USER_REVIEW.md`, `complete.log`, archive 로그를 만들지 않는다.
## Roadmap Targets
- Milestone: `agent-roadmap/phase/inference-provider-extension/milestones/model-route-queue-policy-alignment.md`
- Task ids:
- `queue-policy`: Edge queue admission이 route-level queue policy를 adapter instance fallback보다 우선하고, route policy가 없을 때 기존 fallback을 유지한다.
- Completion mode: check-on-pass
## Spec Targets
- SDD: `agent-roadmap/sdd/inference-provider-extension/model-route-queue-policy-alignment/SDD.md`
- Acceptance scenarios:
- `S03`: task=`queue-policy`; evidence=`go test -count=1 ./apps/edge/internal/service`
- Completion mode: spec-check-on-pass
## Archive Evidence Snapshot
- Current archived plan: `agent-task/m-model-route-queue-policy-alignment/02+01_service_queue_policy/plan_local_G07_0.log`
- Current archived review: `agent-task/m-model-route-queue-policy-alignment/02+01_service_queue_policy/code_review_local_G07_0.log`
- Prior verdict: WARN
- Required issues: 없음
- Suggested issues:
- `apps/edge/internal/service/service_test.go:1571`에서 `time.Sleep(50 * time.Millisecond)`로 run2 큐 진입을 추정하고, `apps/edge/internal/service/service_test.go:1575`에서 `context.Background()`로 run3을 호출해 스케줄링 지연 시 30초 queue timeout 경로로 빠질 수 있다. `errCh2`도 회수하지 않아 goroutine cleanup 신뢰성이 낮다.
- Nit:
- `apps/edge/internal/service/run_dispatch.go:187` stale comment는 리뷰 중 정리됨.
- Affected files:
- `apps/edge/internal/service/service_test.go`
- `apps/edge/internal/service/run_dispatch.go` (comment-only cleanup already applied)
- Verification evidence from prior loop:
- `go test -count=1 ./apps/edge/internal/service` -> PASS (`ok iop/apps/edge/internal/service 0.401s`)
- `git diff --check` -> PASS (no output)
- `go test -count=50 -run TestSubmitRunModelQueueUsesRoutePolicyBeforeProviderInstancePolicy ./apps/edge/internal/service` -> PASS (`ok iop/apps/edge/internal/service 2.597s`)
- Roadmap/spec carryover:
- Roadmap task `queue-policy` remains the target.
- SDD scenario `S03` remains the target.
- Allowed archive reread:
- `agent-task/m-model-route-queue-policy-alignment/02+01_service_queue_policy/plan_local_G07_0.log`
- `agent-task/m-model-route-queue-policy-alignment/02+01_service_queue_policy/code_review_local_G07_0.log`
## 범위 결정 근거
- 포함: `TestSubmitRunModelQueueUsesRoutePolicyBeforeProviderInstancePolicy`의 큐 진입 대기와 goroutine cleanup을 deterministic하게 만든다.
- 제외: `groupPolicyFromRequestOrStore` 구현 로직, OpenAI dispatch, config schema, SDD/roadmap 문서 변경.
- 빌드 등급: `local-G07`. 동시성 테스트 신뢰성 문제지만 focused service test와 반복 targeted test로 로컬에서 판정 가능하다.
## 구현 체크리스트
- [ ] `TestSubmitRunModelQueueUsesRoutePolicyBeforeProviderInstancePolicy`에서 run2가 큐에 들어갔음을 `time.Sleep`만으로 추정하지 않도록 bounded retry 또는 명시적 동기화 구조로 바꾼다.
- [ ] run3 queue-full 검증은 `context.Background()` 무제한 대기 대신 짧은 timeout/retry boundary를 사용해 실패 시에도 테스트가 길게 멈추지 않게 한다.
- [ ] `cancel2()` 이후 `errCh2`를 읽어 run2 goroutine 종료를 확인하고, 기대 가능한 error를 검증한다.
- [ ] Targeted 반복 테스트, focused service tests, `git diff --check`를 실행한다.
- [ ] `CODE_REVIEW-local-G07.md`의 구현 에이전트 소유 섹션을 실제 구현 내용과 검증 출력으로 채운다. 이 항목이 완료되기 전에는 구현이 완료된 것이 아니다.
### [REVIEW_API-1] Route policy queue-full test determinism
#### 문제
직전 리뷰에서 `apps/edge/internal/service/service_test.go:1571`의 `time.Sleep(50 * time.Millisecond)`와 `apps/edge/internal/service/service_test.go:1575`의 unbounded `SubmitRun(context.Background(), ...)` 조합이 검증 신뢰성을 낮춘다고 판단했다. run2 goroutine이 아직 큐에 들어가지 않은 상태에서 run3이 먼저 큐에 들어가면 queue-full이 아니라 queue-timeout/cancel 경로를 검증하게 된다.
#### 해결 방법
- run2를 cancelable context로 시작한 뒤, run3 queue-full 관찰은 짧은 timeout을 둔 probe/retry로 제한한다.
- retry loop는 queue-full error가 관찰되면 성공하고, 전체 deadline 안에 관찰하지 못하면 테스트를 실패시킨다.
- 각 probe가 queue-full이 아니라 context timeout으로 끝난 경우에는 queue item이 제거된 뒤 다시 시도하도록 한다.
- 검증 후 `cancel2()`를 호출하고 `errCh2`를 bounded select로 읽어 goroutine이 종료됐는지 확인한다.
#### 수정 파일 및 체크리스트
- [ ] `apps/edge/internal/service/service_test.go`: sleep-only 대기를 제거하거나 보조적인 짧은 scheduling hint로 축소하고, queue-full 관찰에 bounded retry를 적용한다.
- [ ] `apps/edge/internal/service/service_test.go`: run2 goroutine cleanup 검증을 추가한다.
#### 테스트 작성
기존 테스트를 갱신한다. 새 테스트 파일은 만들지 않는다.
#### 중간 검증
```bash
go test -count=20 -run TestSubmitRunModelQueueUsesRoutePolicyBeforeProviderInstancePolicy ./apps/edge/internal/service
```
기대 결과: targeted repeated test PASS. Go test cache 출력은 허용하지 않는다.
## 최종 검증
```bash
go test -count=1 ./apps/edge/internal/service
git diff --check
```
기대 결과: 모든 명령 PASS. Go test cache 출력은 허용하지 않는다.
모든 코드 변경 완료 후 반드시 `CODE_REVIEW-local-G07.md`의 구현 에이전트 소유 섹션을 채운다. 이 파일 작성이 구현의 마지막 단계다.

View file

@ -185,7 +185,8 @@ func (s *Service) submitRunQueued(ctx context.Context, req SubmitRunRequest) (Ru
}
// resolveQueueCandidates returns candidate nodes filtered by adapter/target capability,
// each paired with per-node capacity, plus the group policy derived from adapter config.
// each paired with per-node capacity, plus the group policy derived from the
// request route policy or adapter config.
func (s *Service) resolveQueueCandidates(req SubmitRunRequest) ([]candidateNode, groupPolicy, error) {
if req.NodeRef != "" {
entry, err := s.ResolveNode(req.NodeRef)
@ -206,7 +207,7 @@ func (s *Service) resolveQueueCandidates(req SubmitRunRequest) ([]candidateNode,
cap = res.capacity
}
}
policy := groupPolicyFromStore(s.nodeStore, []*edgenode.NodeEntry{entry}, req.Adapter, req.Target)
policy := groupPolicyFromRequestOrStore(req, s.nodeStore, []*edgenode.NodeEntry{entry})
return []candidateNode{{entry: entry, capacity: cap}}, policy, nil
}
@ -238,7 +239,7 @@ func (s *Service) resolveQueueCandidates(req SubmitRunRequest) ([]candidateNode,
for i, c := range candidates {
entries[i] = c.entry
}
policy := groupPolicyFromStore(s.nodeStore, entries, req.Adapter, req.Target)
policy := groupPolicyFromRequestOrStore(req, s.nodeStore, entries)
return candidates, policy, nil
}
@ -394,6 +395,24 @@ func resolveTypeRoute(rec *edgenode.NodeRecord, enabled []instanceFields, concur
}
}
func groupPolicyFromRequestOrStore(req SubmitRunRequest, store *edgenode.NodeStore, entries []*edgenode.NodeEntry) groupPolicy {
if req.MaxQueue > 0 || req.QueueTimeoutMS > 0 {
maxQueue := req.MaxQueue
if maxQueue <= 0 {
maxQueue = defaultGroupMaxQueue
}
queueTimeout := defaultQueueTimeout
if req.QueueTimeoutMS > 0 {
queueTimeout = time.Duration(req.QueueTimeoutMS) * time.Millisecond
}
return groupPolicy{
maxQueue: maxQueue,
queueTimeout: queueTimeout,
}
}
return groupPolicyFromStore(store, entries, req.Adapter, req.Target)
}
// groupPolicyFromStore derives queue policy from the first resolved candidate node.
func groupPolicyFromStore(store *edgenode.NodeStore, entries []*edgenode.NodeEntry, adapterType, target string) groupPolicy {
if store != nil {

View file

@ -0,0 +1,121 @@
package service
import (
"context"
"errors"
"net"
"strings"
"testing"
"time"
toki "git.toki-labs.com/toki/proto-socket/go"
"google.golang.org/protobuf/proto"
edgeevents "iop/apps/edge/internal/events"
edgenode "iop/apps/edge/internal/node"
"iop/packages/go/config"
iop "iop/proto/gen/iop"
)
func TestSubmitRunModelQueueUsesRoutePolicyBeforeProviderInstancePolicy(t *testing.T) {
parserMap := toki.ParserMap{
toki.TypeNameOf(&iop.RunRequest{}): func(b []byte) (proto.Message, error) {
m := &iop.RunRequest{}
return m, proto.Unmarshal(b, m)
},
}
edgeConn, nodeConn := net.Pipe()
defer edgeConn.Close()
defer nodeConn.Close()
edgeClient := toki.NewTcpClient(edgeConn, 0, 0, parserMap)
nodeClient := toki.NewTcpClient(nodeConn, 0, 0, parserMap)
toki.AddListenerTyped[*iop.RunRequest](&nodeClient.Communicator, func(*iop.RunRequest) {})
reg := edgenode.NewRegistry()
reg.Register(&edgenode.NodeEntry{NodeID: "prov-node-route-policy", Client: edgeClient})
store := edgenode.NewNodeStore()
store.Add(&edgenode.NodeRecord{
ID: "prov-node-route-policy",
Adapters: config.AdaptersConf{
OllamaInstances: []config.OllamaInstanceConf{
{
Name: "ollama-local",
Enabled: true,
Capacity: 1,
MaxQueue: 10,
},
},
},
Runtime: config.RuntimeConf{Concurrency: 1},
})
bus := edgeevents.NewBus()
svc := New(reg, bus)
svc.SetNodeStore(store)
// run 1: fills capacity (capacity is 1)
res1, err := svc.SubmitRun(context.Background(), SubmitRunRequest{
ModelGroupKey: "route-policy-group",
Adapter: "ollama-local",
Background: true,
MaxQueue: 1,
})
if err != nil {
t.Fatalf("run1 error: %v", err)
}
defer res1.Close()
// run 2: enters queue in a separate goroutine
ctx2, cancel2 := context.WithCancel(context.Background())
defer cancel2()
errCh2 := make(chan error, 1)
go func() {
res2, err := svc.SubmitRun(ctx2, SubmitRunRequest{
ModelGroupKey: "route-policy-group",
Adapter: "ollama-local",
Background: true,
MaxQueue: 1,
})
if err == nil {
res2.Close()
}
errCh2 <- err
}()
// Wait explicitly until run 2 enters the queue
waitForQueueLen(t, svc.queue, "route-policy-group", 1)
// run 3: should be rejected immediately because queue is full (max queue = 1, and run2 is in the queue)
// We use a short timeout context to prevent blocking indefinitely if something fails.
ctx3, cancel3 := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel3()
_, err3 := svc.SubmitRun(ctx3, SubmitRunRequest{
ModelGroupKey: "route-policy-group",
Adapter: "ollama-local",
Background: true,
MaxQueue: 1,
})
if err3 == nil {
t.Fatal("expected third run to fail immediately due to queue full")
}
if !strings.Contains(err3.Error(), "queue is full") {
t.Errorf("expected queue is full error, got: %v", err3)
}
// clean up run2 and verify it exits
cancel2()
select {
case err2 := <-errCh2:
if err2 == nil {
t.Error("expected run2 to fail with context cancelled, got nil")
} else if !errors.Is(err2, context.Canceled) {
t.Errorf("expected run2 to fail with context cancelled, got: %v", err2)
}
case <-time.After(1 * time.Second):
t.Error("timeout waiting for run2 goroutine to exit")
}
}

View file

@ -1499,3 +1499,155 @@ func TestSubmitRunModelQueueRejectsAmbiguousProviderType(t *testing.T) {
t.Errorf("expected no support error, got: %v", err2)
}
}
func TestSubmitRunModelQueueFallsBackToProviderInstancePolicy(t *testing.T) {
parserMap := toki.ParserMap{
toki.TypeNameOf(&iop.RunRequest{}): func(b []byte) (proto.Message, error) {
m := &iop.RunRequest{}
return m, proto.Unmarshal(b, m)
},
}
edgeConn, nodeConn := net.Pipe()
defer edgeConn.Close()
defer nodeConn.Close()
edgeClient := toki.NewTcpClient(edgeConn, 0, 0, parserMap)
nodeClient := toki.NewTcpClient(nodeConn, 0, 0, parserMap)
toki.AddListenerTyped[*iop.RunRequest](&nodeClient.Communicator, func(*iop.RunRequest) {})
reg := edgenode.NewRegistry()
reg.Register(&edgenode.NodeEntry{NodeID: "prov-node-fallback", Client: edgeClient})
store := edgenode.NewNodeStore()
store.Add(&edgenode.NodeRecord{
ID: "prov-node-fallback",
Adapters: config.AdaptersConf{
OllamaInstances: []config.OllamaInstanceConf{
{
Name: "ollama-local",
Enabled: true,
Capacity: 2,
MaxQueue: 3,
},
},
},
Runtime: config.RuntimeConf{Concurrency: 1},
})
bus := edgeevents.NewBus()
svc := edgeservice.New(reg, bus)
svc.SetNodeStore(store)
res1, err := svc.SubmitRun(context.Background(), edgeservice.SubmitRunRequest{
ModelGroupKey: "fallback-group",
Adapter: "ollama-local",
Background: true,
MaxQueue: 0,
})
if err != nil {
t.Fatalf("run1 error: %v", err)
}
defer res1.Close()
res2, err := svc.SubmitRun(context.Background(), edgeservice.SubmitRunRequest{
ModelGroupKey: "fallback-group",
Adapter: "ollama-local",
Background: true,
MaxQueue: 0,
})
if err != nil {
t.Fatalf("run2 error: %v", err)
}
defer res2.Close()
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
defer cancel()
_, err3 := svc.SubmitRun(ctx, edgeservice.SubmitRunRequest{
ModelGroupKey: "fallback-group",
Adapter: "ollama-local",
Background: true,
MaxQueue: 0,
})
if err3 == nil {
t.Fatal("expected third run to block and timeout (capacity=2 exceeded)")
}
if !errors.Is(err3, context.DeadlineExceeded) {
t.Errorf("expected deadline exceeded, got: %v", err3)
}
}
func TestSubmitRunModelQueueUsesRouteQueueTimeout(t *testing.T) {
parserMap := toki.ParserMap{
toki.TypeNameOf(&iop.RunRequest{}): func(b []byte) (proto.Message, error) {
m := &iop.RunRequest{}
return m, proto.Unmarshal(b, m)
},
}
edgeConn, nodeConn := net.Pipe()
defer edgeConn.Close()
defer nodeConn.Close()
edgeClient := toki.NewTcpClient(edgeConn, 0, 0, parserMap)
nodeClient := toki.NewTcpClient(nodeConn, 0, 0, parserMap)
toki.AddListenerTyped[*iop.RunRequest](&nodeClient.Communicator, func(*iop.RunRequest) {})
reg := edgenode.NewRegistry()
reg.Register(&edgenode.NodeEntry{NodeID: "prov-node-timeout", Client: edgeClient})
store := edgenode.NewNodeStore()
store.Add(&edgenode.NodeRecord{
ID: "prov-node-timeout",
Adapters: config.AdaptersConf{
OllamaInstances: []config.OllamaInstanceConf{
{
Name: "ollama-local",
Enabled: true,
Capacity: 1,
MaxQueue: 5,
},
},
},
Runtime: config.RuntimeConf{Concurrency: 1},
})
bus := edgeevents.NewBus()
svc := edgeservice.New(reg, bus)
svc.SetNodeStore(store)
// run 1: fills capacity. Also registers QueueTimeoutMS: 10 on the new queue group
res1, err := svc.SubmitRun(context.Background(), edgeservice.SubmitRunRequest{
ModelGroupKey: "timeout-group",
Adapter: "ollama-local",
Background: true,
QueueTimeoutMS: 10,
})
if err != nil {
t.Fatalf("run1 error: %v", err)
}
defer res1.Close()
// run 2: enters queue, using the same QueueTimeoutMS: 10
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
start := time.Now()
_, err2 := svc.SubmitRun(ctx, edgeservice.SubmitRunRequest{
ModelGroupKey: "timeout-group",
Adapter: "ollama-local",
Background: true,
QueueTimeoutMS: 10,
})
elapsed := time.Since(start)
if err2 == nil {
t.Fatal("expected second run to fail with queue timeout")
}
if !strings.Contains(err2.Error(), "queue timeout") {
t.Errorf("expected queue timeout error, got: %v", err2)
}
if elapsed > 1*time.Second {
t.Errorf("expected timeout to happen quickly, took: %v", elapsed)
}
}