Skip to content

路線推定の候補路線駅取得をlineListStationsに変更しN+1問題を解消 - #5755

Merged
TinyKitten merged 3 commits into
devfrom
feature/fix-route-estimation-n-plus-1
Apr 3, 2026
Merged

TinyKitten merged 3 commits into
devfrom
feature/fix-route-estimation-n-plus-1

Conversation

@TinyKitten

@TinyKitten TinyKitten commented Apr 3, 2026 •

Copy link
Copy Markdown
Member

Summary

  • useRouteEstimationで候補路線の駅リスト取得にlineStationsを路線数分ループ呼び出し(N+1)していたのを、lineListStationsによる一括取得に変更
  • GET_LINE_LIST_STATIONSクエリ(StationFieldsフラグメント使用)を新規追加
  • 返却されたフラットな駅リストを路線IDごとに振り分けてCandidateLine[]を構築

Test plan

  • 路線推定デバッグモーダルで推定が正常に動作すること
  • 候補路線と駅リストが従来と同じ結果になること
  • npm run typecheck パス済み

🤖 Generated with Claude Code

Summary by CodeRabbit

  • 改善
    • 複数路線の駅情報取得を一括化し、駅データ取得と推定処理の効率を向上しました(検索応答速度と処理効率が向上)。
  • 新機能
    • 複数路線向けの一括駅取得APIを利用するようになりました。
  • テスト
    • ルート推定の初期状態、開始・停止、候補選択、リセット、および統計算出を検証する包括的なテストを追加しました。

@github-actions github-actions Bot added the react label Apr 3, 2026
@coderabbitai

coderabbitai Bot commented Apr 3, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

単一のバルクGraphQLクエリ(GET_LINE_LIST_STATIONS)を導入し、フック内のステーション取得を個別クエリの Promise.all から一度のバルク取得へ置換。取得後は返却ステーションを行IDごとにメモリ上で振り分けて従来の候補構築へ利用。テストファイルを追加。

Changes

Cohort / File(s) Summary
GraphQL クエリ定義
src/lib/graphql/queries.ts
GET_LINE_LIST_STATIONS を新規追加。複数行ID($lineIds: [Int!]!)で lineListStations を取得し ...StationFields を返す。
経路予測フック
src/hooks/useRouteEstimation.ts
各行ごとの GET_LINE_STATIONS を使った個別フェッチ(Promise.all)を廃止し、GET_LINE_LIST_STATIONS で一括取得。レスポンスの lineListStations を行IDでグループ化して従来の candidates 構築ロジックに組み込むよう変更。内部型・変数名(lineStations → lineListStations 等)を更新。
テスト追加
src/hooks/useRouteEstimation.test.tsx
useRouteEstimation と useRouteEstimationControl の挙動を検証するテストを新規追加。Apollo の useLazyQuery、Jotai、前処理ユーティリティ、estimateRoutes 等をモックし、初期状態、開始・停止、選択・リセット、および bufferInfo の算出を検証。

Sequence Diagram(s)

sequenceDiagram
  participant Hook as "useRouteEstimation\n(hook)"
  participant Apollo as "Apollo\nuseLazyQuery"
  participant Server as "GraphQL\nServer"
  participant Grouper as "In-memory\nGrouper"

  Hook->>Apollo: execute GET_LINE_LIST_STATIONS(lineIds)
  Apollo->>Server: GraphQL request\nGetLineListStations(lineIds)
  Server-->>Apollo: response: lineListStations[{station, lines[]},...]
  Apollo-->>Hook: return lineListStations
  Hook->>Grouper: group stations by station.lines[].id
  Grouper-->>Hook: per-line station lists
  Hook->>Hook: build candidates and update state
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐰✨ 駅をまとめて一度に取ってきたよ、
メモリで分けて候補を並べる。
小さなラビット、コードを跳ねて、
テストで確かめて、今日も満足。

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed PRタイトルは、N+1問題の解消とlineListStationsへの変更という主要な変更内容を正確に反映しており、簡潔で明確です。
Description check ✅ Passed PR説明は「概要」「変更内容」「テスト」の主要セクションは含まれていますが、テンプレートの「変更の種類」セクションが未記入です。
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/fix-route-estimation-n-plus-1

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
src/hooks/useRouteEstimation.ts (1)

178-204: N+1問題の解消を確認しました。

一括取得と路線IDごとのグルーピングロジックは正しく実装されています。station.linesをイテレートして複数路線に駅を振り分けるアプローチは適切です。

軽微な考慮点として、lineIdsが空配列の場合でもクエリが実行されます。現状の実装ではnearbyStationsが空でない限り問題ありませんが、早期リターンを追加することで不要なネットワークリクエストを防げます。

♻️ 空配列の場合の早期リターン(オプション)
         // 全候補路線の駅リストを一括取得
         const lineIds = Array.from(lineIdSet);
+        if (lineIds.length === 0) {
+          setState((prev) => ({ ...prev, status: 'collecting' }));
+          return;
+        }
         const lineListResult = await fetchLineListStations({
           variables: { lineIds },
         });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/hooks/useRouteEstimation.ts` around lines 178 - 204, If lineIds (derived
from lineIdSet) is empty you should avoid calling fetchLineListStations and
return early; inside useRouteEstimation (where lineIdSet, lineIds, and
fetchLineListStations are used) add a guard like if (lineIds.length === 0)
return an appropriate empty candidates result (or skip the block) so no
unnecessary network request is made when there are no line IDs to query.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@src/hooks/useRouteEstimation.ts`:
- Around line 178-204: If lineIds (derived from lineIdSet) is empty you should
avoid calling fetchLineListStations and return early; inside useRouteEstimation
(where lineIdSet, lineIds, and fetchLineListStations are used) add a guard like
if (lineIds.length === 0) return an appropriate empty candidates result (or skip
the block) so no unnecessary network request is made when there are no line IDs
to query.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 933e6ea1-7168-4319-8456-4472f6e9a205

📥 Commits

Reviewing files that changed from the base of the PR and between d40e75c and 7739aa4.

📒 Files selected for processing (2)
  • src/hooks/useRouteEstimation.ts
  • src/lib/graphql/queries.ts

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@TinyKitten TinyKitten self-assigned this Apr 3, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/hooks/useRouteEstimation.test.tsx (1)

119-298: N+1解消の回帰を防ぐ検証が不足しています

このPRの主目的(lineListStations への一括取得移行)に対して、呼び出し回数・引数(lineIds)・結果の路線別振り分けを直接検証するアサーションがありません。ここを1ケース追加しておくと、将来の退行を確実に検出できます。

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/hooks/useRouteEstimation.test.tsx` around lines 119 - 298, Add a test
that verifies the batched fetch to lineListStations is called once with the
aggregated lineIds and that returned stations are correctly mapped per line to
prevent N+1 regressions: mock the lineListStations query used in setupQueries
(or the module exposing lineListStations), prepare multiple lines and expected
station lists keyed by line id, call the hook via HookBridge (using
setupAtoms/setupQueries as in other tests) to trigger the fetch (e.g. start
estimation or whatever action in useRouteEstimation causes lineListStations to
run), then assert the mocked lineListStations was called exactly once with the
combined lineIds and that the hook result (hookRef.current?.candidates or the
state updated by selectCandidate) receives stations correctly partitioned by
line id. Ensure you reference setupQueries, lineListStations, HookBridge and
useRouteEstimation in the test so future changes will fail if N+1 behavior is
reintroduced.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/hooks/useRouteEstimation.test.tsx`:
- Around line 86-89: The cyclic mock for mockUseSetAtom (using setters and
setterIndex) should be tightened so extra calls fail instead of wrapping via
modulus; change the mockImplementation for mockUseSetAtom to return
setters[setterIndex] only while setterIndex < setters.length and otherwise throw
an error (increment setterIndex after returning), and apply the same stricter
behavior to the mockUseLazyQuery mock (the analogous arrays/indices used at
lines ~107-109) so any unexpected call count causes the test to fail rather than
silently reuse mocks.

---

Nitpick comments:
In `@src/hooks/useRouteEstimation.test.tsx`:
- Around line 119-298: Add a test that verifies the batched fetch to
lineListStations is called once with the aggregated lineIds and that returned
stations are correctly mapped per line to prevent N+1 regressions: mock the
lineListStations query used in setupQueries (or the module exposing
lineListStations), prepare multiple lines and expected station lists keyed by
line id, call the hook via HookBridge (using setupAtoms/setupQueries as in other
tests) to trigger the fetch (e.g. start estimation or whatever action in
useRouteEstimation causes lineListStations to run), then assert the mocked
lineListStations was called exactly once with the combined lineIds and that the
hook result (hookRef.current?.candidates or the state updated by
selectCandidate) receives stations correctly partitioned by line id. Ensure you
reference setupQueries, lineListStations, HookBridge and useRouteEstimation in
the test so future changes will fail if N+1 behavior is reintroduced.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 5a903ed3-d8c3-4671-b7d8-17ac77cb7f93

📥 Commits

Reviewing files that changed from the base of the PR and between 7739aa4 and 7bb4eeb.

📒 Files selected for processing (1)
  • src/hooks/useRouteEstimation.test.tsx

Comment thread src/hooks/useRouteEstimation.test.tsx Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
src/hooks/useRouteEstimation.test.tsx (1)

100-127: lineListStations 一括取得の回帰を直接検証するケースを1件追加したいです。

現状は useLazyQuery の呼び出し順と状態遷移は検証できていますが、今回の主目的である「候補路線をまとめて1回取得し、返却駅を路線IDごとに振り分ける」挙動を直接アサートできていません。ここを1ケース足すと、N+1再発の検知力が上がります。

As per coding guidelines: **/*.{test,spec}.{ts,tsx,js,jsx,py,java,go,cs}: Test agents in isolation and with integration tests to ensure correctness and compatibility.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/hooks/useRouteEstimation.test.tsx` around lines 100 - 127, The test setup
in setupQueries (mockFetchNearbyStart, mockFetchNearbyEnd,
mockFetchLineListStations and mockUseLazyQuery) lacks a concrete case that
asserts lineListStations are fetched once in batch and that returned stations
are partitioned by line ID; add a new test that configures
mockFetchLineListStations to return a combined list of stations with multiple
lineId values, invoke the hook (useRouteEstimation) flow to trigger all lazy
queries, then assert mockFetchLineListStations was called exactly once (no N+1)
and that the hook's result assigns stations to each route/lineId correctly
(verify counts/contents per lineId), and also assert
mockFetchNearbyStart/mockFetchNearbyEnd call expectations remain unchanged.
Ensure you reference the existing helpers (setupQueries, mockUseLazyQuery,
mockFetchLineListStations) when implementing the test.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@src/hooks/useRouteEstimation.test.tsx`:
- Around line 100-127: The test setup in setupQueries (mockFetchNearbyStart,
mockFetchNearbyEnd, mockFetchLineListStations and mockUseLazyQuery) lacks a
concrete case that asserts lineListStations are fetched once in batch and that
returned stations are partitioned by line ID; add a new test that configures
mockFetchLineListStations to return a combined list of stations with multiple
lineId values, invoke the hook (useRouteEstimation) flow to trigger all lazy
queries, then assert mockFetchLineListStations was called exactly once (no N+1)
and that the hook's result assigns stations to each route/lineId correctly
(verify counts/contents per lineId), and also assert
mockFetchNearbyStart/mockFetchNearbyEnd call expectations remain unchanged.
Ensure you reference the existing helpers (setupQueries, mockUseLazyQuery,
mockFetchLineListStations) when implementing the test.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: beb700eb-cc10-4f8b-b327-ea3892c03165

📥 Commits

Reviewing files that changed from the base of the PR and between 7bb4eeb and bd8fca7.

📒 Files selected for processing (1)
  • src/hooks/useRouteEstimation.test.tsx

@TinyKitten
TinyKitten merged commit d8df3b6 into dev Apr 3, 2026
5 checks passed
@TinyKitten
TinyKitten deleted the feature/fix-route-estimation-n-plus-1 branch April 3, 2026 09:28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant