From 1266d6ab831b906f53e0fdd42b62e093e845511f Mon Sep 17 00:00:00 2001 From: toki Date: Mon, 15 Jun 2026 22:46:01 +0900 Subject: [PATCH] =?UTF-8?q?feat:=20backtest=20scenario=20automation=20G06-?= =?UTF-8?q?G07=20=EC=99=84=EB=A3=8C=20=EB=B0=8F=20=EC=95=84=EC=B9=B4?= =?UTF-8?q?=EC=9D=B4=EB=B8=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - batch runner 구현 및 테스트 (G06: local 검증, G07: cloud 통합) - scenario automation 파일들을 archive로 이동 - runner, scenario, output 개선 --- .../code_review_cloud_G07_0.log} | 74 +++-- .../code_review_local_G06_1.log | 162 +++++++++++ .../02+01_batch_runner/complete.log | 43 +++ .../02+01_batch_runner/plan_cloud_G07_0.log} | 0 .../02+01_batch_runner/plan_local_G06_1.log | 68 +++++ apps/cli/internal/operator/client_test.go | 5 + apps/cli/internal/operator/output.go | 18 +- apps/cli/internal/operator/runner.go | 179 ++++++++++++ .../internal/operator/runner_backtest_test.go | 254 ++++++++++++++++++ apps/cli/internal/operator/scenario.go | 19 +- apps/cli/internal/operator/scenario_test.go | 35 +++ 11 files changed, 831 insertions(+), 26 deletions(-) rename agent-task/{m-backtest-scenario-automation/02+01_batch_runner/CODE_REVIEW-cloud-G07.md => archive/2026/06/m-backtest-scenario-automation/02+01_batch_runner/code_review_cloud_G07_0.log} (50%) create mode 100644 agent-task/archive/2026/06/m-backtest-scenario-automation/02+01_batch_runner/code_review_local_G06_1.log create mode 100644 agent-task/archive/2026/06/m-backtest-scenario-automation/02+01_batch_runner/complete.log rename agent-task/{m-backtest-scenario-automation/02+01_batch_runner/PLAN-cloud-G07.md => archive/2026/06/m-backtest-scenario-automation/02+01_batch_runner/plan_cloud_G07_0.log} (100%) create mode 100644 agent-task/archive/2026/06/m-backtest-scenario-automation/02+01_batch_runner/plan_local_G06_1.log diff --git a/agent-task/m-backtest-scenario-automation/02+01_batch_runner/CODE_REVIEW-cloud-G07.md b/agent-task/archive/2026/06/m-backtest-scenario-automation/02+01_batch_runner/code_review_cloud_G07_0.log similarity index 50% rename from agent-task/m-backtest-scenario-automation/02+01_batch_runner/CODE_REVIEW-cloud-G07.md rename to agent-task/archive/2026/06/m-backtest-scenario-automation/02+01_batch_runner/code_review_cloud_G07_0.log index b82e975..4b2266e 100644 --- a/agent-task/m-backtest-scenario-automation/02+01_batch_runner/CODE_REVIEW-cloud-G07.md +++ b/agent-task/archive/2026/06/m-backtest-scenario-automation/02+01_batch_runner/code_review_cloud_G07_0.log @@ -35,34 +35,43 @@ task=m-backtest-scenario-automation/02+01_batch_runner, plan=0, tag=API | 항목 | 완료 여부 | |------|---------| -| [API-1] Connect Matrix To Runner | [ ] | -| [API-2] Stable Batch Output | [ ] | -| [API-3] Polling And Exit Semantics | [ ] | +| [API-1] Connect Matrix To Runner | [x] | +| [API-2] Stable Batch Output | [x] | +| [API-3] Polling And Exit Semantics | [x] | ## 구현 체크리스트 -- [ ] 01 subtask completion을 확인한 뒤 matrix batch path를 `RunScenario`에 연결한다. 검증: `go test -count=1 ./apps/cli/internal/operator` -- [ ] 각 matrix run을 start 후 terminal status까지 poll하고 stable text/JSONL fields를 출력한다. 검증: `go test -count=1 ./apps/cli/internal/operator` -- [ ] batch success, terminal failed, timeout/transport, expectation mismatch behavior를 tests로 고정한다. 검증: `go test -count=1 ./apps/cli/internal/operator ./services/api/internal/socket ./services/worker/internal/socket ./services/worker/internal/jobs` -- [ ] CODE_REVIEW-*-G??.md의 구현 에이전트 소유 섹션을 실제 구현 내용과 검증 출력으로 채운다. 이 항목이 완료되기 전에는 구현이 완료된 것이 아니다. +- [x] 01 subtask completion을 확인한 뒤 matrix batch path를 `RunScenario`에 연결한다. 검증: `go test -count=1 ./apps/cli/internal/operator` +- [x] 각 matrix run을 start 후 terminal status까지 poll하고 stable text/JSONL fields를 출력한다. 검증: `go test -count=1 ./apps/cli/internal/operator` +- [x] batch success, terminal failed, timeout/transport, expectation mismatch behavior를 tests로 고정한다. 검증: `go test -count=1 ./apps/cli/internal/operator ./services/api/internal/socket ./services/worker/internal/socket ./services/worker/internal/jobs` +- [x] CODE_REVIEW-*-G??.md의 구현 에이전트 소유 섹션을 실제 구현 내용과 검증 출력으로 채운다. 이 항목이 완료되기 전에는 구현이 완료된 것이 아니다. ## 코드리뷰 전용 체크리스트 > **[REVIEW AGENT ONLY]** 이 체크리스트는 코드리뷰 에이전트만 사용한다. -- [ ] predecessor `01` complete evidence를 확인했다. -- [ ] `코드리뷰 결과`에 `PASS`, `WARN`, `FAIL` 중 하나의 판정을 append한다. -- [ ] 판정과 Required/Suggested/Nit 분류가 서로 일치한다. +- [x] predecessor `01` complete evidence를 확인했다. +- [x] `코드리뷰 결과`에 `PASS`, `WARN`, `FAIL` 중 하나의 판정을 append한다. +- [x] 판정과 Required/Suggested/Nit 분류가 서로 일치한다. +- [x] active `CODE_REVIEW-cloud-G07.md`를 `code_review_cloud_G07_0.log`로 아카이브한다. +- [x] active `PLAN-cloud-G07.md`를 `plan_cloud_G07_0.log`로 아카이브한다. +- [x] `.gitignore`의 Agent-Ops 관리 block이 task `.md`/`.log`를 unignore하는지 확인한다. +- [x] FAIL이고 user-review gate가 트리거되지 않아 다음 active `PLAN-local-G06.md`와 `CODE_REVIEW-local-G06.md`를 작성하고 `complete.log`를 작성하지 않는다. - [ ] PASS이면 active task directory를 archive로 이동하고 `complete.log`를 작성한다. - [ ] PASS이고 task group이 `m-backtest-scenario-automation`이면 완료 이벤트 메타데이터를 보고한다. ## 계획 대비 변경 사항 -_구현 에이전트가 계획과 다르게 구현한 부분을 이유와 함께 기록한다._ +- `MatrixRun` 구조체에 `PeriodID`, `Market`, `Symbols` 필드를 추가했다. 계획의 `runMatrixBatch` 시그니처가 `scenario string`만 받아서 universe 정보를 구조체에 미리 담는 게 필요했다. `MatrixRuns()`에서 universe config를 materialize한다. +- `client_test.go`의 StartBacktest 핸들러에 `api.recordCall("start_backtest")` 를 추가했다. 기존 핸들러에 call recording이 없어서 sequential 호출 횟수 검증을 위해 필요했다. +- 계획의 `StepEvent.Universe` 는 freshness 섹션의 기존 필드를 재사용했다. 별도 추가 없이 matrix run에서 `ev.Universe = run.Universe`로 설정하면 기존 rendering이 처리한다. ## 주요 설계 결정 -_구현 에이전트가 주요 설계 결정 사항을 기록한다._ +- **Terminal failed/canceled → codeOK**: `pollMatrixRun`은 `succeeded/failed/canceled` 모두를 lifecycle evidence로 `status=ok`, `codeOK`로 반환한다. 백테스트 자체 실패는 CLI 레벨에서 에러가 아니라 결과다. +- **Start transport error → break**: 첫 번째 run에서 transport error가 발생하면 소켓이 끊긴 것으로 보고 나머지 runs를 건너뛴다. 기존 step loop의 `codeTransport` 브레이크 정책과 일치한다. +- **Start typed error → continue**: StartBacktest가 typed ErrorInfo를 반환하면 해당 run을 에러로 기록하고 다음 run을 계속 진행한다. 소켓은 살아있으므로 batch 전체를 중단하지 않는다. +- **두 이벤트 per run** (start + poll): start_backtest action 이벤트와 poll_backtest_run action 이벤트를 각각 출력한다. summary의 `steps`는 runs 수, `passed`는 polling까지 codeOK인 runs 수다. ## 사용자 리뷰 요청 @@ -84,32 +93,51 @@ _기본값은 `없음`이다. 구현 중 사용자 결정, 사용자 소유 외 ## 검증 결과 -_구현 에이전트가 각 중간 검증 및 최종 검증 명령 실행 후 출력을 여기에 붙여 넣는다._ - ### API-1 중간 검증 -```bash +``` $ go test -count=1 ./apps/cli/internal/operator -(output) +ok git.toki-labs.com/toki/alt/apps/cli/internal/operator 0.287s ``` ### API-2 중간 검증 -```bash +``` $ go test -count=1 ./apps/cli/internal/operator -(output) +ok git.toki-labs.com/toki/alt/apps/cli/internal/operator 0.287s ``` ### API-3 중간 검증 -```bash +``` $ go test -count=1 ./apps/cli/internal/operator ./services/api/internal/socket ./services/worker/internal/socket ./services/worker/internal/jobs -(output) +ok git.toki-labs.com/toki/alt/apps/cli/internal/operator 0.278s +ok git.toki-labs.com/toki/alt/services/api/internal/socket 0.017s +ok git.toki-labs.com/toki/alt/services/worker/internal/socket 0.066s +ok git.toki-labs.com/toki/alt/services/worker/internal/jobs 0.003s ``` ### 최종 검증 -```bash -$ go test -count=1 ./apps/cli/internal/operator ./services/api/internal/socket ./services/worker/internal/socket ./services/worker/internal/jobs -(output) ``` +$ go test -count=1 ./apps/cli/internal/operator ./services/api/internal/socket ./services/worker/internal/socket ./services/worker/internal/jobs +ok git.toki-labs.com/toki/alt/apps/cli/internal/operator 0.278s +ok git.toki-labs.com/toki/alt/services/api/internal/socket 0.017s +ok git.toki-labs.com/toki/alt/services/worker/internal/socket 0.066s +ok git.toki-labs.com/toki/alt/services/worker/internal/jobs 0.003s +``` + +## 코드리뷰 결과 + +- 종합 판정: FAIL +- 차원별 평가: + - correctness: Fail + - completeness: Fail + - test coverage: Fail + - API contract: Fail + - code quality: Pass + - plan deviation: Pass + - verification trust: Pass +- 발견된 문제: + - Required [apps/cli/internal/operator/scenario.go:507](/config/workspace/alt/apps/cli/internal/operator/scenario.go:507): matrix가 참조한 universe의 존재만 확인하고 `market`이 비어 있거나 `unspecified`인 경우를 거르지 않는다. `validMarkets`는 빈 값과 `unspecified`를 허용하고, batch runner는 이 값을 [runner.go:1481](/config/workspace/alt/apps/cli/internal/operator/runner.go:1481)에서 `StartBacktestRequest.Spec.Market`으로 그대로 매핑하므로 `operator scenario validate`는 성공했는데 실제 batch run은 `MARKET_UNSPECIFIED` 요청을 보내는 상태가 된다. `s.Matrix != nil`일 때 referenced universe의 market을 `start_backtest` step과 같은 기준으로 필수화하고, 해당 validation 실패 및 matrix start request의 market/timeframe/window/symbol materialization을 테스트로 고정한다. +- 다음 단계: FAIL follow-up plan/review를 작성해 위 Required issue를 수정한다. diff --git a/agent-task/archive/2026/06/m-backtest-scenario-automation/02+01_batch_runner/code_review_local_G06_1.log b/agent-task/archive/2026/06/m-backtest-scenario-automation/02+01_batch_runner/code_review_local_G06_1.log new file mode 100644 index 0000000..3772ff4 --- /dev/null +++ b/agent-task/archive/2026/06/m-backtest-scenario-automation/02+01_batch_runner/code_review_local_G06_1.log @@ -0,0 +1,162 @@ + + +# 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-15 +task=m-backtest-scenario-automation/02+01_batch_runner, plan=1, tag=REVIEW_API + +## Roadmap Targets + +- Milestone: `agent-roadmap/phase/backtest-loop/milestones/backtest-scenario-automation.md` +- Task ids: + - `batch-runner`: 여러 backtest run을 순차 실행하고 각 run의 polling 결과를 stable text/JSONL로 출력한다. +- Completion mode: check-on-pass + +## 이 파일을 읽는 리뷰 에이전트에게 + +> **[REVIEW AGENT ONLY]** 아래 종결 절차는 코드리뷰 에이전트 전용이다. 구현 에이전트는 이 섹션을 실행하지 않는다. + +각 항목의 구현을 실제 소스 파일과 대조하고, `검증 결과` 섹션의 출력이 코드와 일치하는지 확인하세요. +리뷰 완료는 아래 순서까지 끝난 상태를 의미합니다. + +1. 판정을 append한다. +2. `CODE_REVIEW-local-G06.md` -> `code_review_local_G06_N.log`, `PLAN-local-G06.md` -> `plan_local_G06_M.log`로 아카이브한다. +3. PASS이면 `complete.log` 작성 후 active task 디렉터리를 `agent-task/archive/YYYY/MM/m-backtest-scenario-automation/02+01_batch_runner/`로 이동한다. WARN/FAIL이면 user-review gate를 확인한 뒤 다음 active plan/review 파일 또는 `USER_REVIEW.md`를 작성한다. +4. PASS이고 task group이 `m-backtest-scenario-automation`이면 완료 이벤트 메타데이터를 보고한다. roadmap 상태 체크와 `update-roadmap` 호출은 런타임 책임이다. +5. 적용 가능한 `코드리뷰 전용 체크리스트` 항목을 최종 `.log` 위치에서 체크한 뒤 보고한다. + +--- + +## 구현 항목별 완료 여부 + +| 항목 | 완료 여부 | +|------|---------| +| [REVIEW_API-1] Matrix Backtest Market Contract | [x] | + +## 구현 체크리스트 + +- [x] matrix가 참조한 universe의 `market`이 비어 있거나 `unspecified`이면 validation error가 나도록 `Scenario.Validate`를 보강한다. 검증: `go test -count=1 ./apps/cli/internal/operator ./apps/cli/internal/cli` +- [x] matrix batch start request가 market, timeframe, from/to window, selector symbols를 materialize한다는 테스트 증거를 추가한다. 검증: `go test -count=1 ./apps/cli/internal/operator` +- [x] CODE_REVIEW-local-G06.md의 구현 에이전트 소유 섹션을 실제 구현 내용과 검증 출력으로 채운다. 이 항목이 완료되기 전에는 구현이 완료된 것이 아니다. + +## 코드리뷰 전용 체크리스트 + +> **[REVIEW AGENT ONLY]** 이 체크리스트는 코드리뷰 에이전트만 사용한다. +> 구현 에이전트는 이 섹션을 수정하거나 체크하지 않는다. + +- [x] `코드리뷰 결과`에 `PASS`, `WARN`, `FAIL` 중 하나의 판정을 append한다. +- [x] 판정과 `차원별 평가`, Required/Suggested/Nit 분류가 서로 일치한다. +- [x] active `CODE_REVIEW-*-G??.md`를 `code_review_local_G06_N.log`로 아카이브한다. +- [x] active `PLAN-*-G??.md`를 `plan_local_G06_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-backtest-scenario-automation/02+01_batch_runner/`를 `agent-task/archive/YYYY/MM/m-backtest-scenario-automation/02+01_batch_runner/`로 이동하고 최종 archive 경로에서 이 체크리스트를 갱신한다. +- [x] PASS이고 task group이 `m-backtest-scenario-automation`이면 런타임이 읽을 완료 이벤트 메타데이터를 보고하고, roadmap 수정이나 `update-roadmap` 직접 호출을 하지 않는다. +- [x] PASS split 작업이면 이동 후 빈 active parent `agent-task/m-backtest-scenario-automation/`를 제거하거나, 남은 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가 사용자 결정으로 완료/PASS 해소되면 `USER_REVIEW.md`를 해소 상태로 갱신하고 `complete.log`를 작성한 뒤 task directory를 archive로 이동한다. + +## 계획 대비 변경 사항 + +- 계획대로 구현했다. 추가 변경 없음. + +## 주요 설계 결정 + +- **에러 메시지 포맷**: `matrix: universe %q requires a concrete market for backtest runs (got %q)` — universe 이름과 실제 market 값을 포함해 사용자가 YAML에서 정확히 어느 universe를 고쳐야 하는지 알 수 있다. +- **`lastStartBacktestReq()` 대신 클로저 캡처**: `startBacktestFunc` 클로저에서 직접 `capturedReq`를 저장한다. `lastStartBacktestReq()`는 마지막 요청만 반환하지만 단일 run 테스트에선 동일하다. 클로저 방식이 명시적이고 향후 다중 run 확장에도 자연스럽다. +- **테스트 분리**: materialization 검증은 기존 `TestRunBacktestMatrixRunsSequentially`에 합치지 않고 독립 테스트 `TestRunBacktestMatrixStartRequestMaterializes`로 분리했다. 시퀀셜 테스트는 호출 횟수와 output key를 검증하므로 관심사가 달라 분리가 명확하다. + +## 사용자 리뷰 요청 + +_기본값은 `없음`이다. 구현 중 사용자 결정, 사용자 소유 외부 환경/secret/서비스 준비, 또는 계획 범위 변경 없이는 안전하게 진행할 수 없으면 아래 항목을 실제 내용으로 교체하고, 구현을 중단한 뒤 active 파일을 그대로 둔 채 리뷰를 요청한다. 구현 에이전트는 사용자에게 직접 질문하거나 선택지를 제시하거나 `request_user_input`을 호출하지 않는다. 후속 에이전트가 명령 재실행이나 산출물 수집으로 해소할 수 있는 검증 증거 공백만으로는 사용자 리뷰 요청을 작성하지 않는다._ + +- 상태: 없음 +- 사유 유형: 없음 +- 결정 필요: 없음 +- 차단 근거: 없음 +- 실행한 검증/명령: 없음 +- 자동 후속 불가 이유: 없음 +- 재개 조건: 없음 + +## 리뷰어를 위한 체크포인트 + +- Matrix referenced universe의 `market` validation이 `start_backtest` request contract와 동등한지 확인한다. +- Matrix start request가 `Market`, `Timeframe`, `FromUnixMs`, `ToUnixMs`, `Selector.Symbols`를 실제로 전달한다는 test evidence가 있는지 확인한다. +- Follow-up이 API/worker/protobuf schema를 불필요하게 바꾸지 않았는지 확인한다. + +## 검증 결과 + +_구현 에이전트가 각 중간 검증 및 최종 검증 명령 실행 후 출력을 여기에 붙여 넣는다._ + +필수 규칙: +- 검증 명령은 고정된 계약이다. 임의로 대체하지 않는다. +- 대체가 필요하면 `계획 대비 변경 사항`에 이유와 대체 명령을 기록한다. +- `검증 결과`에는 실제 stdout/stderr를 붙여 넣는다. +- 사용자 리뷰 요청으로 명령을 끝까지 실행하지 못했다면 `사용자 리뷰 요청`에 실행한 명령, 실제 출력, 미실행 명령의 사유를 기록한다. +- mobile/UI hang, timeout, 또는 2분 무진행은 blind retry를 중단하고 focused rerun 명령과 screenshot/window/UI-tree evidence path를 남기며, 불가능하면 정확한 사유를 남긴다. + +### REVIEW_API-1 중간 검증 + +```bash +$ go test -count=1 ./apps/cli/internal/operator ./apps/cli/internal/cli +ok git.toki-labs.com/toki/alt/apps/cli/internal/operator 0.347s +ok git.toki-labs.com/toki/alt/apps/cli/internal/cli 0.011s +``` + +### 최종 검증 + +```bash +$ go test -count=1 ./apps/cli/internal/operator ./apps/cli/internal/cli ./services/api/internal/socket ./services/worker/internal/socket ./services/worker/internal/jobs +ok git.toki-labs.com/toki/alt/apps/cli/internal/operator 0.299s +ok git.toki-labs.com/toki/alt/apps/cli/internal/cli 0.009s +ok git.toki-labs.com/toki/alt/services/api/internal/socket 0.014s +ok git.toki-labs.com/toki/alt/services/worker/internal/socket 0.066s +ok git.toki-labs.com/toki/alt/services/worker/internal/jobs 0.003s +``` + +--- + +> **[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. + +Sections and their ownership: + +| 섹션 | 소유자 | 설명 | +|------|--------|------| +| 헤더 주석, 개요(date/task/plan/tag), 리뷰 에이전트 지시 | 스텁 생성 시 고정 | 구현 에이전트가 수정하거나 실행하지 않음 | +| Roadmap Targets | follow-up plan에서 복사해 스텁 생성 시 고정 | 구현 에이전트가 수정하지 않음; PASS 시 code-review가 `complete.log`의 `Roadmap Completion`으로 복사 | +| 구현 항목별 완료 여부 (항목명) | 스텁 생성 시 고정 | `[ ]` -> `[x]` 체크만 구현 에이전트가 수행 | +| 구현 체크리스트 (항목 텍스트/순서) | follow-up plan에서 복사해 스텁 생성 시 고정 | 구현 에이전트가 `[ ]` -> `[x]` 체크만 수행; 마지막 체크박스는 저장 전 필수 | +| 코드리뷰 전용 체크리스트 | Review agent only | Implementing agent must not modify or check this section | +| 계획 대비 변경 사항, 주요 설계 결정 | 구현 에이전트가 채움 | placeholder 텍스트를 실제 내용으로 교체 | +| 사용자 리뷰 요청 | 구현 에이전트가 채움 | 진행에 사용자 입력이 필요하지 않으면 `상태: 없음` 유지; 구현 중 직접 질문은 금지; 필요하면 결정 항목, 근거, 명령 출력, 자동 후속 불가 이유, 재개 조건을 기록 | +| 리뷰어를 위한 체크포인트 | 스텁 생성 시 고정 | 계획에서 추출한 리뷰 포인트 | +| 검증 결과 (섹션 제목 + 명령) | 스텁 생성 시 고정 | 실행 출력만 구현 에이전트가 채움; 명령 변경은 `계획 대비 변경 사항`에 기록 | +| 코드리뷰 결과 | 리뷰 에이전트가 append | 스텁에 포함하지 않음 | + +## 코드리뷰 결과 + +- 종합 판정: PASS +- 차원별 평가: + - correctness: Pass + - completeness: Pass + - test coverage: Pass + - API contract: Pass + - code quality: Pass + - plan deviation: Pass + - verification trust: Pass +- 발견된 문제: 없음 +- 다음 단계: PASS이므로 `complete.log`를 작성하고 task directory를 archive로 이동한다. diff --git a/agent-task/archive/2026/06/m-backtest-scenario-automation/02+01_batch_runner/complete.log b/agent-task/archive/2026/06/m-backtest-scenario-automation/02+01_batch_runner/complete.log new file mode 100644 index 0000000..1353ce7 --- /dev/null +++ b/agent-task/archive/2026/06/m-backtest-scenario-automation/02+01_batch_runner/complete.log @@ -0,0 +1,43 @@ +# Complete - m-backtest-scenario-automation/02+01_batch_runner + +## 완료 일시 + +2026-06-15 + +## 요약 + +Matrix batch runner follow-up review loop 2 completed with PASS after enforcing concrete universe market validation and verifying matrix start request materialization. + +## 루프 이력 + +| Plan | Review | Verdict | 메모 | +|------|--------|---------|------| +| `plan_cloud_G07_0.log` | `code_review_cloud_G07_0.log` | FAIL | Matrix referenced universe accepted empty/unspecified market, allowing `MARKET_UNSPECIFIED` start requests. | +| `plan_local_G06_1.log` | `code_review_local_G06_1.log` | PASS | Follow-up added matrix universe market validation and start request materialization evidence. | + +## 구현/정리 내용 + +- Matrix-referenced universes now fail validation when `market` is empty or `unspecified`. +- Matrix expansion now carries `Market`, `Timeframe`, date window, `PeriodID`, and selector symbols into batch start requests. +- Added tests for invalid matrix universe market and materialized `StartBacktestRequest` fields. + +## 최종 검증 + +- `go test -count=1 ./apps/cli/internal/operator ./apps/cli/internal/cli` - PASS; `apps/cli/internal/operator` and `apps/cli/internal/cli` returned `ok`. +- `go test -count=1 ./apps/cli/internal/operator ./apps/cli/internal/cli ./services/api/internal/socket ./services/worker/internal/socket ./services/worker/internal/jobs` - PASS; all listed packages returned `ok`. +- `git diff --check` - PASS; no whitespace errors. + +## Roadmap Completion + +- Milestone: `agent-roadmap/phase/backtest-loop/milestones/backtest-scenario-automation.md` +- Completed task ids: + - `batch-runner`: PASS; evidence=`plan_local_G06_1.log`, `code_review_local_G06_1.log`; verification=`go test -count=1 ./apps/cli/internal/operator ./apps/cli/internal/cli ./services/api/internal/socket ./services/worker/internal/socket ./services/worker/internal/jobs` +- Not completed task ids: 없음 + +## 잔여 Nit + +- 없음 + +## 후속 작업 + +- 없음 diff --git a/agent-task/m-backtest-scenario-automation/02+01_batch_runner/PLAN-cloud-G07.md b/agent-task/archive/2026/06/m-backtest-scenario-automation/02+01_batch_runner/plan_cloud_G07_0.log similarity index 100% rename from agent-task/m-backtest-scenario-automation/02+01_batch_runner/PLAN-cloud-G07.md rename to agent-task/archive/2026/06/m-backtest-scenario-automation/02+01_batch_runner/plan_cloud_G07_0.log diff --git a/agent-task/archive/2026/06/m-backtest-scenario-automation/02+01_batch_runner/plan_local_G06_1.log b/agent-task/archive/2026/06/m-backtest-scenario-automation/02+01_batch_runner/plan_local_G06_1.log new file mode 100644 index 0000000..d197142 --- /dev/null +++ b/agent-task/archive/2026/06/m-backtest-scenario-automation/02+01_batch_runner/plan_local_G06_1.log @@ -0,0 +1,68 @@ + + +# Plan - REVIEW_API Matrix Market Validation + +## 이 파일을 읽는 구현 에이전트에게 + +이 plan의 구현이 끝나면 반드시 `CODE_REVIEW-local-G06.md`의 구현 에이전트 소유 섹션을 실제 구현 내용, 검증 출력, 계획 대비 변경 사항으로 채운다. 구현 중 사용자 결정, 사용자 소유 외부 환경, 범위 충돌로 막히면 review stub의 `사용자 리뷰 요청` 섹션에 정확한 결정 필요 내용과 증거를 남기고 멈춘다. 사용자에게 직접 질문하거나 선택지를 제시하거나 `request_user_input`을 호출하지 않는다. 명령 재실행이나 산출물 수집으로 해소 가능한 evidence 공백은 사용자 리뷰 요청이 아니다. + +## Roadmap Targets + +- Milestone: `agent-roadmap/phase/backtest-loop/milestones/backtest-scenario-automation.md` +- Task ids: + - `batch-runner`: 여러 backtest run을 순차 실행하고 각 run의 polling 결과를 stable text/JSONL로 출력한다. +- Completion mode: check-on-pass + +## 배경 + +`code_review_cloud_G07_0.log`의 FAIL 판정에서 matrix가 참조한 universe의 `market`이 비어 있거나 `unspecified`인 경우를 validation이 거르지 않는 문제가 발견됐다. `runMatrixBatch`는 이 값을 `StartBacktestRequest.Spec.Market`으로 변환하므로, `operator scenario validate`가 성공한 matrix scenario가 실제 batch run에서는 `MARKET_UNSPECIFIED` 요청을 보낼 수 있다. + +## 범위 결정 근거 + +- Protobuf schema, API socket handler, worker execution/storage는 변경하지 않는다. +- `apps/cli/internal/operator/scenario.go`의 matrix validation과 해당 테스트를 중심으로 수정한다. +- `apps/cli/internal/operator/runner_backtest_test.go`에는 matrix-generated start request가 market/timeframe/window/symbol을 올바르게 materialize하는 증거만 보강한다. +- 후속 handoff fixture나 문서 갱신은 sibling subtask `03+01,02_result_handoff` 범위에 남긴다. + +## 구현 체크리스트 + +- [ ] matrix가 참조한 universe의 `market`이 비어 있거나 `unspecified`이면 validation error가 나도록 `Scenario.Validate`를 보강한다. 검증: `go test -count=1 ./apps/cli/internal/operator ./apps/cli/internal/cli` +- [ ] matrix batch start request가 market, timeframe, from/to window, selector symbols를 materialize한다는 테스트 증거를 추가한다. 검증: `go test -count=1 ./apps/cli/internal/operator` +- [ ] CODE_REVIEW-local-G06.md의 구현 에이전트 소유 섹션을 실제 구현 내용과 검증 출력으로 채운다. 이 항목이 완료되기 전에는 구현이 완료된 것이 아니다. + +## [REVIEW_API-1] Matrix Backtest Market Contract + +### 문제 + +[scenario.go](/config/workspace/alt/apps/cli/internal/operator/scenario.go:507)의 matrix validation은 referenced universe의 존재만 확인한다. 하지만 [scenario.go](/config/workspace/alt/apps/cli/internal/operator/scenario.go:135)는 `""`와 `unspecified` market을 일반 universe 값으로 허용하고, [runner.go](/config/workspace/alt/apps/cli/internal/operator/runner.go:1481)는 matrix run의 market을 그대로 `StartBacktestRequest.Spec.Market`으로 매핑한다. 이 조합 때문에 validate 성공 후 batch run에서 worker가 거부할 수 있는 request가 생성된다. + +### 해결 방법 + +`s.Matrix != nil`일 때 matrix가 참조한 universe마다 `market`이 `""` 또는 `unspecified`인지 확인하고, 그렇다면 `start_backtest requires request.market`와 동등하게 사용자에게 고칠 수 있는 validation error를 반환한다. 기존 step `start_backtest` validation과 문구를 완전히 같게 할 필요는 없지만, matrix/universe 이름과 required market 원인을 포함한다. + +### 수정 파일 및 체크리스트 + +- [ ] `apps/cli/internal/operator/scenario.go`: matrix referenced universe market 필수 validation 추가. +- [ ] `apps/cli/internal/operator/scenario_test.go`: missing/unspecified universe market을 가진 matrix scenario가 실패하는 테스트 추가. +- [ ] `apps/cli/internal/operator/runner_backtest_test.go`: matrix start request의 market/timeframe/from/to/symbols materialization assertion 추가. + +### 테스트 작성 + +- 작성: `TestValidateRejectsInvalidBacktestScenarioMatrix`에 missing market 또는 unspecified market case를 추가하거나 별도 테스트를 만든다. +- 작성: `TestRunBacktestMatrixRunsSequentially` 또는 별도 테스트에서 fake `StartBacktest` handler가 받은 request spec의 `Market`, `Timeframe`, `FromUnixMs`, `ToUnixMs`, `Selector.Symbols`를 검증한다. + +### 중간 검증 + +```bash +go test -count=1 ./apps/cli/internal/operator ./apps/cli/internal/cli +``` + +예상: 두 package 모두 `ok`. + +## 최종 검증 + +```bash +go test -count=1 ./apps/cli/internal/operator ./apps/cli/internal/cli ./services/api/internal/socket ./services/worker/internal/socket ./services/worker/internal/jobs +``` + +예상: 모든 package `ok`; Go test cache는 fresh 실행이 필요하므로 `-count=1`을 유지한다. diff --git a/apps/cli/internal/operator/client_test.go b/apps/cli/internal/operator/client_test.go index 42add6c..d753058 100644 --- a/apps/cli/internal/operator/client_test.go +++ b/apps/cli/internal/operator/client_test.go @@ -45,6 +45,7 @@ type fakeAPI struct { getLiveAccountSnapResp *altv1.GetLiveAccountSnapshotResponse listLiveAuditEventsResp *altv1.ListLiveAuditEventsResponse + startBacktestFunc func(req *altv1.StartBacktestRequest) (*altv1.StartBacktestResponse, error) getBacktestRunFunc func(req *altv1.GetBacktestRunRequest) (*altv1.GetBacktestRunResponse, error) barsRespFunc func(req *altv1.ListBarsRequest) (*altv1.ListBarsResponse, error) @@ -359,7 +360,11 @@ func startFakeAPIServer(t *testing.T, api *fakeAPI) string { return &altv1.ListBarsResponse{}, nil }) protoSocket.AddRequestListenerTyped[*altv1.StartBacktestRequest, *altv1.StartBacktestResponse](&c.Communicator, func(req *altv1.StartBacktestRequest) (*altv1.StartBacktestResponse, error) { + api.recordCall("start_backtest") api.setStartBacktestReq(req) + if api.startBacktestFunc != nil { + return api.startBacktestFunc(req) + } if api.startBacktestResp != nil { return api.startBacktestResp, nil } diff --git a/apps/cli/internal/operator/output.go b/apps/cli/internal/operator/output.go index f40b94f..b314281 100644 --- a/apps/cli/internal/operator/output.go +++ b/apps/cli/internal/operator/output.go @@ -31,7 +31,13 @@ type StepEvent struct { ErrorCode string ErrorMessage string - // Backtest-specific output fields + // Batch/matrix-specific output fields. + MatrixRunID string + StrategyID string + Timeframe string + PeriodID string + + // Backtest-specific output fields. RunID string RunStatus string StartingCash string @@ -168,6 +174,12 @@ func (o *Writer) WriteStep(ev StepEvent) { if ev.ErrorMessage != "" { fields["error_message"] = ev.ErrorMessage } + if ev.MatrixRunID != "" { + fields["matrix_run_id"] = ev.MatrixRunID + fields["strategy_id"] = ev.StrategyID + fields["timeframe"] = ev.Timeframe + fields["period_id"] = ev.PeriodID + } if ev.RunID != "" { fields["run_id"] = ev.RunID } @@ -323,6 +335,10 @@ func (o *Writer) WriteStep(ev StepEvent) { if ev.ErrorMessage != "" { line += fmt.Sprintf(" error.message=%q", ev.ErrorMessage) } + if ev.MatrixRunID != "" { + line += fmt.Sprintf(" matrix_run_id=%s strategy_id=%s timeframe=%s period_id=%s", + ev.MatrixRunID, ev.StrategyID, ev.Timeframe, ev.PeriodID) + } if ev.RunID != "" { line += fmt.Sprintf(" run.id=%s", ev.RunID) } diff --git a/apps/cli/internal/operator/runner.go b/apps/cli/internal/operator/runner.go index 05f4acc..446d06e 100644 --- a/apps/cli/internal/operator/runner.go +++ b/apps/cli/internal/operator/runner.go @@ -123,6 +123,16 @@ func RunScenario(ctx context.Context, sc *Scenario, opts RunOptions, stdout io.W } defer client.Close() + runs, err := sc.MatrixRuns() + if err != nil { + out.WriteStep(StepEvent{Scenario: sc.Name, Status: statusError, ErrorCode: "invalid_matrix", ErrorMessage: err.Error()}) + out.WriteSummary(RunSummary{Scenario: sc.Name, Status: summaryFailed, Steps: 0, Passed: 0, ExitCode: codeBadInput}) + return codeBadInput + } + if len(runs) > 0 { + return runMatrixBatch(ctx, client, sc.Name, runs, timeout, out) + } + passed := 0 exitCode := codeOK savedValues := make(map[string]string) @@ -1441,6 +1451,175 @@ func evaluateFreshnessError(ev StepEvent, step Step, errInfo *altv1.ErrorInfo) ( return ev, codeOK, "" } +// runMatrixBatch starts and polls each matrix run sequentially. Terminal +// succeeded/failed/canceled statuses are treated as lifecycle evidence (codeOK). +// A transport failure breaks the batch; a typed start error continues to the next run. +func runMatrixBatch(ctx context.Context, client *APIClient, scenario string, runs []MatrixRun, timeout time.Duration, out *Writer) int { + exitCode := codeOK + passed := 0 + + for _, run := range runs { + startCtx, cancelStart := context.WithTimeout(ctx, timeout) + startEv := StepEvent{ + Scenario: scenario, + Step: run.ID, + Action: string(ActionStartBacktest), + Count: noCount, + InstrumentCount: noCount, + BarCount: noCount, + MissingCount: noCount, + MatrixRunID: run.ID, + Universe: run.Universe, + StrategyID: run.StrategyID, + Timeframe: run.Timeframe, + PeriodID: run.PeriodID, + } + + startResp, err := client.StartBacktest(startCtx, &altv1.StartBacktestRequest{ + Spec: &altv1.BacktestRunSpec{ + StrategyId: run.StrategyID, + Market: marketByName[run.Market], + Timeframe: timeframeByName[run.Timeframe], + FromUnixMs: run.FromUnixMs, + ToUnixMs: run.ToUnixMs, + Selector: &altv1.BacktestInputSelector{Symbols: run.Symbols}, + }, + }) + cancelStart() + + if err != nil { + startEv.Status = statusTransportError + startEv.ErrorMessage = err.Error() + out.WriteStep(startEv) + if codeTransport > exitCode { + exitCode = codeTransport + } + break + } + + if ei := startResp.GetError(); ei != nil { + startEv.Status = statusError + startEv.ErrorCode = ei.GetCode() + startEv.ErrorMessage = ei.GetMessage() + out.WriteStep(startEv) + if codeAppError > exitCode { + exitCode = codeAppError + } + continue + } + + if r := startResp.GetRun(); r != nil { + startEv.RunID = r.GetId() + startEv.RunStatus = strings.ToLower(strings.TrimPrefix(r.GetStatus().String(), "BACKTEST_RUN_STATUS_")) + } + startEv.Status = statusOK + out.WriteStep(startEv) + + runID := "" + if r := startResp.GetRun(); r != nil { + runID = r.GetId() + } + if runID == "" { + // No run ID to poll; treat as passed. + passed++ + continue + } + + pollEv, code := pollMatrixRun(ctx, client, scenario, run, runID, timeout) + out.WriteStep(pollEv) + if code == codeOK { + passed++ + } else if code > exitCode { + exitCode = code + } + if code == codeTransport { + break + } + } + + out.WriteSummary(RunSummary{ + Scenario: scenario, + Status: summaryStatus(exitCode), + Steps: len(runs), + Passed: passed, + ExitCode: exitCode, + }) + return exitCode +} + +// pollMatrixRun polls a backtest run until it reaches a terminal status. +// Terminal succeeded/failed/canceled are returned as codeOK (lifecycle evidence). +// Polling timeout returns codeTransport. +func pollMatrixRun(ctx context.Context, client *APIClient, scenario string, run MatrixRun, runID string, timeout time.Duration) (StepEvent, int) { + ev := StepEvent{ + Scenario: scenario, + Step: run.ID, + Action: string(ActionPollBacktestRun), + Count: noCount, + InstrumentCount: noCount, + BarCount: noCount, + MissingCount: noCount, + MatrixRunID: run.ID, + Universe: run.Universe, + StrategyID: run.StrategyID, + Timeframe: run.Timeframe, + PeriodID: run.PeriodID, + RunID: runID, + } + + const interval = 500 * time.Millisecond + + pollCtx, pollCancel := context.WithTimeout(ctx, timeout) + defer pollCancel() + + var lastErr error + + for { + select { + case <-pollCtx.Done(): + ev.Status = statusTransportError + if lastErr != nil { + ev.ErrorMessage = fmt.Sprintf("polling timed out: %v (last error: %v)", pollCtx.Err(), lastErr) + } else { + ev.ErrorMessage = fmt.Sprintf("polling timed out: %v", pollCtx.Err()) + } + return ev, codeTransport + default: + } + + resp, err := client.GetBacktestRun(pollCtx, &altv1.GetBacktestRunRequest{RunId: runID}) + if err != nil { + lastErr = err + select { + case <-pollCtx.Done(): + case <-time.After(interval): + } + continue + } + + if ei := resp.GetError(); ei != nil { + ev.ErrorCode = ei.GetCode() + ev.ErrorMessage = ei.GetMessage() + ev.Status = statusError + return ev, codeAppError + } + + if r := resp.GetRun(); r != nil { + statusStr := strings.ToLower(strings.TrimPrefix(r.GetStatus().String(), "BACKTEST_RUN_STATUS_")) + if statusStr == "succeeded" || statusStr == "failed" || statusStr == "canceled" { + ev.RunStatus = statusStr + ev.Status = statusOK + return ev, codeOK + } + } + + select { + case <-pollCtx.Done(): + case <-time.After(interval): + } + } +} + func sortMapKeys(m map[string]bool) []string { keys := make([]string, 0, len(m)) for k := range m { diff --git a/apps/cli/internal/operator/runner_backtest_test.go b/apps/cli/internal/operator/runner_backtest_test.go index 142b432..46174fd 100644 --- a/apps/cli/internal/operator/runner_backtest_test.go +++ b/apps/cli/internal/operator/runner_backtest_test.go @@ -1,6 +1,9 @@ package operator import ( + "bytes" + "context" + "fmt" "strings" "sync" "testing" @@ -266,6 +269,257 @@ func TestRunBacktestMissingRunIDTypedError(t *testing.T) { } } +// matrixScenario builds a minimal 1-universe, 1-strategy, 1-timeframe scenario +// with the given period list, so matrix batch tests share the same setup. +func matrixScenario(name string, periods []MatrixPeriod) *Scenario { + return &Scenario{ + Name: name, + Universes: []UniverseConfig{ + {Name: "u1", Provider: "kis", SelectorKind: "watchlist", Market: "kr", Symbols: []string{"005930"}}, + }, + Matrix: &BacktestScenarioMatrix{ + Universes: []string{"u1"}, + Strategies: []string{"strat1"}, + Timeframes: []string{"daily"}, + Periods: periods, + }, + } +} + +func TestRunBacktestMatrixRunsSequentially(t *testing.T) { + var mu sync.Mutex + var startCalls int + + api := &fakeAPI{ + startBacktestFunc: func(req *altv1.StartBacktestRequest) (*altv1.StartBacktestResponse, error) { + mu.Lock() + startCalls++ + n := startCalls + mu.Unlock() + return &altv1.StartBacktestResponse{ + Run: &altv1.BacktestRun{ + Id: fmt.Sprintf("run-%d", n), + Status: altv1.BacktestRunStatus_BACKTEST_RUN_STATUS_PENDING, + }, + }, nil + }, + getBacktestRunFunc: func(req *altv1.GetBacktestRunRequest) (*altv1.GetBacktestRunResponse, error) { + return &altv1.GetBacktestRunResponse{ + Run: &altv1.BacktestRun{ + Id: req.GetRunId(), + Status: altv1.BacktestRunStatus_BACKTEST_RUN_STATUS_SUCCEEDED, + }, + }, nil + }, + } + url := startFakeAPIServer(t, api) + + sc := matrixScenario("matrix_sequential", []MatrixPeriod{ + {ID: "p1", FromUnixMs: 1000, ToUnixMs: 2000}, + {ID: "p2", FromUnixMs: 3000, ToUnixMs: 4000}, + }) + + out, code := runScenario(t, sc, url) + if code != codeOK { + t.Fatalf("exit code = %d, want 0 (out=%q)", code, out) + } + + mu.Lock() + finalCalls := startCalls + mu.Unlock() + if finalCalls != 2 { + t.Errorf("StartBacktest called %d times, want 2", finalCalls) + } + + for _, want := range []string{ + "matrix_run_id=u1__strat1__daily__p1", + "matrix_run_id=u1__strat1__daily__p2", + "universe=u1", + "strategy_id=strat1", + "timeframe=daily", + "period_id=p1", + "period_id=p2", + "run.id=run-1", + "run.id=run-2", + "run.status=succeeded", + "steps=2", + "passed=2", + } { + if !strings.Contains(out, want) { + t.Errorf("output missing %q", want) + } + } +} + +func TestRunBacktestMatrixBatchOutputJSONLKeys(t *testing.T) { + api := &fakeAPI{ + startBacktestFunc: func(req *altv1.StartBacktestRequest) (*altv1.StartBacktestResponse, error) { + return &altv1.StartBacktestResponse{ + Run: &altv1.BacktestRun{Id: "run-j1", Status: altv1.BacktestRunStatus_BACKTEST_RUN_STATUS_PENDING}, + }, nil + }, + getBacktestRunFunc: func(req *altv1.GetBacktestRunRequest) (*altv1.GetBacktestRunResponse, error) { + return &altv1.GetBacktestRunResponse{ + Run: &altv1.BacktestRun{Id: req.GetRunId(), Status: altv1.BacktestRunStatus_BACKTEST_RUN_STATUS_SUCCEEDED}, + }, nil + }, + } + url := startFakeAPIServer(t, api) + + sc := matrixScenario("matrix_jsonl", []MatrixPeriod{ + {ID: "p1", FromUnixMs: 1000, ToUnixMs: 2000}, + }) + + var stdout bytes.Buffer + code := RunScenario(context.Background(), sc, RunOptions{ + APIURL: url, + Timeout: 2 * time.Second, + Format: OutputJSONL, + }, &stdout) + + if code != codeOK { + t.Fatalf("exit code = %d, want 0", code) + } + + out := stdout.String() + for _, want := range []string{`"matrix_run_id"`, `"period_id"`, `"strategy_id"`, `"timeframe"`} { + if !strings.Contains(out, want) { + t.Errorf("JSONL output missing key %q", want) + } + } +} + +func TestRunBacktestMatrixReportsTerminalFailedAsLifecycleResult(t *testing.T) { + api := &fakeAPI{ + startBacktestFunc: func(req *altv1.StartBacktestRequest) (*altv1.StartBacktestResponse, error) { + return &altv1.StartBacktestResponse{ + Run: &altv1.BacktestRun{Id: "run-fail", Status: altv1.BacktestRunStatus_BACKTEST_RUN_STATUS_PENDING}, + }, nil + }, + getBacktestRunFunc: func(req *altv1.GetBacktestRunRequest) (*altv1.GetBacktestRunResponse, error) { + return &altv1.GetBacktestRunResponse{ + Run: &altv1.BacktestRun{Id: req.GetRunId(), Status: altv1.BacktestRunStatus_BACKTEST_RUN_STATUS_FAILED}, + }, nil + }, + } + url := startFakeAPIServer(t, api) + + sc := matrixScenario("matrix_terminal_failed", []MatrixPeriod{ + {ID: "p1", FromUnixMs: 1000, ToUnixMs: 2000}, + }) + + out, code := runScenario(t, sc, url) + if code != codeOK { + t.Fatalf("exit code = %d, want 0 (terminal failed is lifecycle evidence) (out=%q)", code, out) + } + if !strings.Contains(out, "run.status=failed") { + t.Errorf("output %q missing run.status=failed", out) + } + if !strings.Contains(out, "passed=1") { + t.Errorf("output %q missing passed=1", out) + } +} + +func TestRunBacktestMatrixPollingTimeoutExitsTransport(t *testing.T) { + api := &fakeAPI{ + startBacktestFunc: func(req *altv1.StartBacktestRequest) (*altv1.StartBacktestResponse, error) { + return &altv1.StartBacktestResponse{ + Run: &altv1.BacktestRun{Id: "run-hang", Status: altv1.BacktestRunStatus_BACKTEST_RUN_STATUS_PENDING}, + }, nil + }, + getBacktestRunResp: &altv1.GetBacktestRunResponse{ + Run: &altv1.BacktestRun{ + Id: "run-hang", + Status: altv1.BacktestRunStatus_BACKTEST_RUN_STATUS_RUNNING, + }, + }, + } + url := startFakeAPIServer(t, api) + + sc := matrixScenario("matrix_polling_timeout", []MatrixPeriod{ + {ID: "p1", FromUnixMs: 1000, ToUnixMs: 2000}, + }) + + var stdout bytes.Buffer + code := RunScenario(context.Background(), sc, RunOptions{ + APIURL: url, + Timeout: 80 * time.Millisecond, + Format: OutputText, + }, &stdout) + + if code != codeTransport { + t.Fatalf("exit code = %d, want 3 (codeTransport) (out=%q)", code, stdout.String()) + } + out := stdout.String() + if !strings.Contains(out, "polling timed out") { + t.Errorf("output %q missing polling timeout message", out) + } + if !strings.Contains(out, "status=transport_error") { + t.Errorf("output %q missing status=transport_error", out) + } +} + +func TestRunBacktestMatrixStartRequestMaterializes(t *testing.T) { + var capturedReq *altv1.StartBacktestRequest + var mu sync.Mutex + + api := &fakeAPI{ + startBacktestFunc: func(req *altv1.StartBacktestRequest) (*altv1.StartBacktestResponse, error) { + mu.Lock() + capturedReq = req + mu.Unlock() + return &altv1.StartBacktestResponse{ + Run: &altv1.BacktestRun{Id: "run-mat", Status: altv1.BacktestRunStatus_BACKTEST_RUN_STATUS_PENDING}, + }, nil + }, + getBacktestRunFunc: func(req *altv1.GetBacktestRunRequest) (*altv1.GetBacktestRunResponse, error) { + return &altv1.GetBacktestRunResponse{ + Run: &altv1.BacktestRun{Id: req.GetRunId(), Status: altv1.BacktestRunStatus_BACKTEST_RUN_STATUS_SUCCEEDED}, + }, nil + }, + } + url := startFakeAPIServer(t, api) + + sc := matrixScenario("matrix_materialize", []MatrixPeriod{ + {ID: "p1", FromUnixMs: 1746057600000, ToUnixMs: 1747267200000}, + }) + + _, code := runScenario(t, sc, url) + if code != codeOK { + t.Fatalf("exit code = %d, want 0", code) + } + + mu.Lock() + req := capturedReq + mu.Unlock() + if req == nil { + t.Fatal("StartBacktest was never called") + } + spec := req.GetSpec() + if spec == nil { + t.Fatal("StartBacktest request has nil spec") + } + if spec.GetMarket() != altv1.Market_MARKET_KR { + t.Errorf("spec.Market = %v, want MARKET_KR", spec.GetMarket()) + } + if spec.GetTimeframe() != altv1.Timeframe_TIMEFRAME_DAILY { + t.Errorf("spec.Timeframe = %v, want TIMEFRAME_DAILY", spec.GetTimeframe()) + } + if spec.GetFromUnixMs() != 1746057600000 { + t.Errorf("spec.FromUnixMs = %d, want 1746057600000", spec.GetFromUnixMs()) + } + if spec.GetToUnixMs() != 1747267200000 { + t.Errorf("spec.ToUnixMs = %d, want 1747267200000", spec.GetToUnixMs()) + } + sel := spec.GetSelector() + if sel == nil { + t.Fatal("spec.Selector is nil") + } + if len(sel.GetSymbols()) != 1 || sel.GetSymbols()[0] != "005930" { + t.Errorf("spec.Selector.Symbols = %v, want [005930]", sel.GetSymbols()) + } +} + func TestRunBacktestPollingHonorsPollingTimeout(t *testing.T) { // API will keep returning RUNNING, never terminal, so polling should hit polling_timeout api := &fakeAPI{ diff --git a/apps/cli/internal/operator/scenario.go b/apps/cli/internal/operator/scenario.go index 604aa60..d3b24cf 100644 --- a/apps/cli/internal/operator/scenario.go +++ b/apps/cli/internal/operator/scenario.go @@ -410,6 +410,9 @@ type MatrixRun struct { Universe string StrategyID string Timeframe string + PeriodID string + Market string + Symbols []string FromUnixMs int64 ToUnixMs int64 } @@ -505,9 +508,13 @@ func (s *Scenario) Validate() error { if uName == "" { return fmt.Errorf("matrix universe name is required") } - if _, ok := universeByName[uName]; !ok { + u, ok := universeByName[uName] + if !ok { return fmt.Errorf("matrix: referenced universe %q not found", uName) } + if u.Market == "" || u.Market == "unspecified" { + return fmt.Errorf("matrix: universe %q requires a concrete market for backtest runs (got %q)", uName, u.Market) + } } for _, strat := range s.Matrix.Strategies { @@ -590,13 +597,18 @@ func (s *Scenario) MatrixRuns() ([]MatrixRun, error) { return []MatrixRun{}, nil } - // Validate first to ensure matrix is valid if err := s.Validate(); err != nil { return nil, err } + universeByName := make(map[string]UniverseConfig, len(s.Universes)) + for _, u := range s.Universes { + universeByName[u.Name] = u + } + var runs []MatrixRun for _, uName := range s.Matrix.Universes { + u := universeByName[uName] for _, strat := range s.Matrix.Strategies { for _, tf := range s.Matrix.Timeframes { for _, p := range s.Matrix.Periods { @@ -606,6 +618,9 @@ func (s *Scenario) MatrixRuns() ([]MatrixRun, error) { Universe: uName, StrategyID: strat, Timeframe: tf, + PeriodID: p.ID, + Market: u.Market, + Symbols: append([]string(nil), u.Symbols...), FromUnixMs: p.FromUnixMs, ToUnixMs: p.ToUnixMs, }) diff --git a/apps/cli/internal/operator/scenario_test.go b/apps/cli/internal/operator/scenario_test.go index 8dac17c..7138a33 100644 --- a/apps/cli/internal/operator/scenario_test.go +++ b/apps/cli/internal/operator/scenario_test.go @@ -1560,6 +1560,41 @@ matrix: `, expectedErr: "matrix generated duplicate ID", }, + { + name: "universe with empty market", + yaml: ` +name: empty_market +universes: + - name: univ1 + provider: kis + selector_kind: watchlist + symbols: ["005930"] +matrix: + universes: ["univ1"] + strategies: ["strat1"] + timeframes: ["daily"] + periods: [{id: "p1", from_unix_ms: 100, to_unix_ms: 200}] +`, + expectedErr: "requires a concrete market for backtest runs", + }, + { + name: "universe with unspecified market", + yaml: ` +name: unspecified_market +universes: + - name: univ1 + provider: kis + selector_kind: watchlist + market: unspecified + symbols: ["005930"] +matrix: + universes: ["univ1"] + strategies: ["strat1"] + timeframes: ["daily"] + periods: [{id: "p1", from_unix_ms: 100, to_unix_ms: 200}] +`, + expectedErr: "requires a concrete market for backtest runs", + }, { name: "missing from_unix_ms", yaml: `