Skip to content

環状路線の到着時間推定で継ぎ目をラップする弧を選択し山手線のETAが出ない問題を修正する - #1581

Merged
TinyKitten merged 2 commits into
devfrom
fix/loop-line-eta
Jul 2, 2026
Merged

TinyKitten merged 2 commits into
devfrom
fix/loop-line-eta

Conversation

@TinyKitten

@TinyKitten TinyKitten commented Jul 2, 2026 •

Copy link
Copy Markdown
Member

概要

山手線などの環状路線で、走行方向が格納順の継ぎ目(品川⇔大崎)を跨ぐ乗車の到着時間推定が逆側の弧を返し、実際に通過する駅がレスポンスに含まれずクライアントでETAが表示されない問題を修正する。

変更の種類

  • バグ修正
  • 新機能
  • データの修正・追加
  • リファクタリング
  • ドキュメント
  • CI/CD
  • その他

変更内容

  • estimate_route_arrival_times の経路絞り込みは group_stops[fi..=ti] の連続スライスのみで環状の概念が無く、山手線(line_group_cd 363、大崎→…→品川の線形順で格納)では継ぎ目を跨ぐ乗車(例: 外回り 田町→渋谷)で東京・池袋経由の逆側24駅の弧を返していた
  • arrival_estimation.rs に環状経路をヒューリスティックに判定する is_circular_route を追加: ①駅数≥6 ②先頭≠末尾駅 ③シーム(末尾→先頭)≤2.0×平均駅間 ④シーム≤3,000m ⑤最大駅間≤3.0×中央値 の5条件。シードデータ全路線・全line_groupに対して山手線・大阪環状線(環状運転系統)・名城線・札幌市電・富山都心線・伊予鉄環状線のみを検出し、誤検出ゼロを確認済み(成田線・近鉄奈良線などの不連続な格納順は⑤で除外)
  • 継ぎ目をラップする弧を選択する select_circular_arc を追加: direction_id 指定時は格納された向きに沿って進み(反転しない)、未指定時は直線距離合計が短い方の弧を返す
  • query.rs の絞り込みは環状グループのみ分岐を追加。非環状経路の挙動は従来と完全に同一(proto・SQL・リポジトリ層の変更なし)
  • テスト追加10本: 山手線30駅の実座標による環状判定・田町→渋谷が品川経由8駅/約15分になるバグ再現回帰、判定の負例(直線・小規模リング・閉じたループ・不連続順)、弧選択の単体テスト、モックリポジトリ経由の統合テスト2本

既知の制約

  • direction_id 未指定時の「短い弧」はヒューリスティックで、遠回り方向に乗車中の利用者には逆向きのETAになる(従来の「通る駅が一切返らない」よりは改善)。環状路線ではクライアントから direction_id を送ることを推奨
  • 大阪環状線の直通快速系統(環状部+大和路線等でグループ全体は非環状)は検出対象外

テスト

  • cargo fmt --all -- --check が通ること
  • cargo clippy -- -D warnings が通ること
  • cargo test(SQLX_OFFLINE=true)が通ること

関連Issue

スクリーンショット(任意)

🤖 Generated with Claude Code

https://claude.ai/code/session_01KZrVUqfmEjpBcmNbF4ZyG8


Generated by Claude Code

Summary by CodeRabbit

  • 新機能
    • 環状(継ぎ目をまたぐ)経路を検出し、適切な弧として到着時刻推定を行えるようにしました。
    • 方向指定なしでも、より短い弧を選んで推定します。
  • バグ修正
    • 継ぎ目付近で誤った区間が選ばれてしまう問題を修正し、推定結果を改善しました。
  • テスト
    • 環状経路の判定・弧選択・回帰ケースの検証を追加しました。

到着時間推定の経路絞り込みは group_stops[fi..=ti] の連続スライスのみで
環状の概念が無く、山手線(line_group_cd 363、大崎→…→品川の線形順で格納)
では走行方向が格納順の継ぎ目(品川⇔大崎)を跨ぐ乗車で逆側の弧を返して
いた。実際に通過する駅がレスポンスに含まれないため、クライアント側の
突き合わせが失敗しETAが表示されない。

座標のみから環状経路をヒューリスティックに判定する is_circular_route と、
継ぎ目をラップする弧を選択する select_circular_arc を追加する。
direction_id 指定時は格納された向きに沿って進み(反転しない)、未指定時は
直線距離合計が短い方の弧を返す。判定条件はシードデータ全路線・全 line_group
に対して山手線・大阪環状線(環状運転系統)・名城線・札幌市電・富山都心線・
伊予鉄環状線のみを検出し、誤検出が無いことを確認済み。非環状経路の挙動は
従来と同一。

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KZrVUqfmEjpBcmNbF4ZyG8
@TinyKitten TinyKitten self-assigned this Jul 2, 2026
@github-actions github-actions Bot added the fix 直した label Jul 2, 2026
@coderabbitai

coderabbitai Bot commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

駅列から環状経路を判定する処理と、シームを跨ぐ弧を選ぶ処理を追加し、到着時刻推定では閉ループデータの重複終端を除外して環状区間を扱うように変更した。関連するテストも追加された。

Changes

環状経路推定機能

Layer / File(s) Summary
環状判定・弧選択ロジックの実装
stationapi/src/domain/arrival_estimation.rs
駅間距離・シーム距離・ギャップ分布から環状経路を判定する is_circular_route、および直線距離合計に基づき弧を選ぶ select_circular_arc/arc_length_meters を新設。
到着時刻推定への統合
stationapi/src/use_case/interactor/query.rs
estimate_route_arrival_times で重複終端を除外した route_stops を使い、環状時は弧選択結果を estimate_arrival_minutes に渡すよう変更。
環状判定と推定結果のテスト
stationapi/src/domain/arrival_estimation.rs, stationapi/src/use_case/interactor/query.rs
ring_stations、yamanote_stations、ring_stops を追加し、環状判定、弧選択、シーム跨ぎの推定結果を検証。

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant QueryInteractor
  participant is_circular_route
  participant select_circular_arc
  participant estimate_arrival_minutes

  Client->>QueryInteractor: estimate_route_arrival_times
  QueryInteractor->>is_circular_route: route_stops を判定
  is_circular_route-->>QueryInteractor: 環状かどうか
  alt 環状経路
    QueryInteractor->>select_circular_arc: シームを跨ぐ弧を選択
    select_circular_arc-->>QueryInteractor: 選択した駅列
  else 非環状経路
    QueryInteractor->>QueryInteractor: 線形区間を切り出し
  end
  QueryInteractor->>estimate_arrival_minutes: 区間を推定
  estimate_arrival_minutes-->>QueryInteractor: 到着時刻
  QueryInteractor-->>Client: 推定結果
Loading

Possibly related PRs

  • TrainLCD/StationAPI#1563: arrival_estimation と estimate_route_arrival_times の基盤を追加したPRで、今回の環状判定と弧選択はその同じ経路推定系に対する拡張。
  • TrainLCD/StationAPI#1575: estimate_route_arrival_times の区間切り出しロジックを変更しており、今回の fi/ti と弧選択分岐の変更に直接つながる。

Poem

ぴょんと回って環をみつけ
シームもこわくないよ
近い弧をひとつ選んで
時刻はすいすい並ぶ
にんじんみたいにきれいに着地 🥕

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed 主要変更である環状路線の継ぎ目跨ぎ弧の選択と山手線ETA不具合修正を具体的に示しており、内容と一致しています。
Description check ✅ Passed 必須セクションの概要、変更の種類、変更内容、テストが揃っており、任意項目の未記入も許容範囲です。
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ 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 fix/loop-line-eta

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

@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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
stationapi/src/use_case/interactor/query.rs (1)

1118-1147: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

重複終端を持つ閉ループも環状分岐に入れてください。

is_circular_route は stops[0].station_cd == stops[n - 1].station_cd の駅列で false を返すため、[1,2,...,8,1] のような閉ループは Line 1138 で非環状扱いになります。その場合、7→2 は Line 1144-1146 の逆順スライスで 7,6,...,2 になり、シーム経由の弧を返せません。重複した終端駅を除いた slice で判定・選択してください。

修正例
         let mut result: Vec<EstimatedStop> = Vec::new();
         for (_line_group_cd, group_stops) in route_row_tree_map.iter() {
-            let from_pos = group_stops
+            let mut route_stops = group_stops.as_slice();
+            if route_stops.len() > 1 {
+                if let (Some(first), Some(last)) = (route_stops.first(), route_stops.last()) {
+                    if first.station_cd == last.station_cd {
+                        route_stops = &route_stops[..route_stops.len() - 1];
+                    }
+                }
+            }
+
+            let from_pos = route_stops
                 .iter()
                 .position(|s| s.station_cd as u32 == from_station_id);
-            let to_pos = group_stops
+            let to_pos = route_stops
                 .iter()
                 .position(|s| s.station_cd as u32 == to_station_id);
@@
-            if is_circular_route(group_stops) {
-                let arc = select_circular_arc(group_stops, fi, ti, direction_id.is_some());
+            if is_circular_route(route_stops) {
+                let arc = select_circular_arc(route_stops, fi, ti, direction_id.is_some());
                 result.extend(estimate_arrival_minutes(&arc, &params));
             } else if fi < ti {
-                result.extend(estimate_arrival_minutes(&group_stops[fi..=ti], &params));
+                result.extend(estimate_arrival_minutes(&route_stops[fi..=ti], &params));
             } else {
-                let mut segment: Vec<&Station> = group_stops[ti..=fi].to_vec();
+                let mut segment: Vec<&Station> = route_stops[ti..=fi].to_vec();
                 segment.reverse();
                 result.extend(estimate_arrival_minutes(&segment, &params));
             }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@stationapi/src/use_case/interactor/query.rs` around lines 1118 - 1147,
`query.rs` の経路選択ロジックで、`is_circular_route`
が重複終端を持つ閉ループ列を非環状扱いにしているため、`select_circular_arc`
に入らず逆順スライス側へ落ちています。`route_row_tree_map` を走査するこの分岐で、`group_stops`
の末尾が先頭と同じ場合は重複終端を除いたスライスで環状判定し、`select_circular_arc` に渡す対象も同じく重複を除外した列にしてください。
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@stationapi/src/use_case/interactor/query.rs`:
- Around line 1118-1147: `query.rs` の経路選択ロジックで、`is_circular_route`
が重複終端を持つ閉ループ列を非環状扱いにしているため、`select_circular_arc`
に入らず逆順スライス側へ落ちています。`route_row_tree_map` を走査するこの分岐で、`group_stops`
の末尾が先頭と同じ場合は重複終端を除いたスライスで環状判定し、`select_circular_arc` に渡す対象も同じく重複を除外した列にしてください。

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 896083b4-e338-4d26-9f34-113f87cea69a

📥 Commits

Reviewing files that changed from the base of the PR and between 5b10042 and 9121f96.

📒 Files selected for processing (2)
  • stationapi/src/domain/arrival_estimation.rs
  • stationapi/src/use_case/interactor/query.rs

ポートライナー等は先頭駅が末尾にも重複格納されており、is_circular_route が
閉じ駅の二重出現を避けるため非環状扱いにしていた。その結果、継ぎ目を跨ぐ
乗車が逆順スライスに落ちて誤った弧を返していた。経路候補の走査時に重複
終端を除いたスライスで環状判定・弧選択するようにする。

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KZrVUqfmEjpBcmNbF4ZyG8

@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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
stationapi/src/use_case/interactor/query.rs (1)

1119-1157: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

環状判定に失敗した候補まで重複終端を落とさないでください。

Line 1122-1127 で先に route_stops を短縮しているため、重複終端を持つが is_circular_route で除外される候補は、Line 1151 以降の線形フォールバックでも末尾駅を失った状態で推定されます。生の group_stops は線形用に残し、重複終端を除いたスライスは環状として採用する場合だけ使うのが安全です。

修正案
-            let mut route_stops: &[&Station] = group_stops.as_slice();
-            if route_stops.len() > 1
-                && route_stops[0].station_cd == route_stops[route_stops.len() - 1].station_cd
+            let raw_route_stops: &[&Station] = group_stops.as_slice();
+            let circular_route_stops = if raw_route_stops.len() > 1
+                && raw_route_stops[0].station_cd
+                    == raw_route_stops[raw_route_stops.len() - 1].station_cd
             {
-                route_stops = &route_stops[..route_stops.len() - 1];
-            }
+                &raw_route_stops[..raw_route_stops.len() - 1]
+            } else {
+                raw_route_stops
+            };
+            let use_circular_route = is_circular_route(circular_route_stops);
+            let route_stops = if use_circular_route {
+                circular_route_stops
+            } else {
+                raw_route_stops
+            };
 
             let from_pos = route_stops
                 .iter()
                 .position(|s| s.station_cd as u32 == from_station_id);
@@
-            if is_circular_route(route_stops) {
+            if use_circular_route {
                 let arc = select_circular_arc(route_stops, fi, ti, direction_id.is_some());
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@stationapi/src/use_case/interactor/query.rs` around lines 1119 - 1157, The
pre-trimming of route_stops removes the duplicated terminal station too early,
so non-circular candidates that fail is_circular_route still get estimated with
the last stop missing. Keep the original group_stops slice intact for the linear
fallback path in query.rs, and create/use the de-duplicated slice only inside
the circular-route branch before calling select_circular_arc and
estimate_arrival_minutes.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@stationapi/src/use_case/interactor/query.rs`:
- Around line 1119-1157: The pre-trimming of route_stops removes the duplicated
terminal station too early, so non-circular candidates that fail
is_circular_route still get estimated with the last stop missing. Keep the
original group_stops slice intact for the linear fallback path in query.rs, and
create/use the de-duplicated slice only inside the circular-route branch before
calling select_circular_arc and estimate_arrival_minutes.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 367937c8-3217-4a90-bb55-104bbe272b4d

📥 Commits

Reviewing files that changed from the base of the PR and between 9121f96 and de4a404.

📒 Files selected for processing (1)
  • stationapi/src/use_case/interactor/query.rs

Copy link
Copy Markdown
Member Author

@coderabbitai 「環状判定に失敗した候補まで重複終端を落とさないでください」の指摘について検証しましたが、到達不能なケースのため現状のままとします。

理由: 重複終端(stops[n-1].station_cd == stops[0].station_cd)を除去しても、from_pos / to_pos の position() は最初の一致を返すため、重複駅は必ず先頭のインデックス 0 に解決されます。したがって fi / ti が n-1 を指すことはなく、線形フォールバックのスライス [fi..=ti](および反転スライス)が除去済みの末尾要素を含むことは構造上ありません。環状判定に失敗した候補でも、トリム前後で from_pos / to_pos の値・スライス内容は完全に一致し、挙動は変わりません。


Generated by Claude Code

@coderabbitai

coderabbitai Bot commented Jul 2, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
fd -e rs query.rs --path stationapi | head
ast-grep run --pattern 'fn estimate_route_arrival_times($$$) { $$$ }' --lang rust stationapi/src/use_case/interactor/query.rs 2>/dev/null | head -c 4000
echo "---"
rg -n "position\(|fi|ti|dedup|is_circular_route|route_stops" stationapi/src/use_case/interactor/query.rs | head -80

Length of output: 4760


🏁 Script executed:

#!/bin/bash
rg -n "fn estimate_route_arrival_times" stationapi/src/use_case/interactor/query.rs
sed -n '/fn estimate_route_arrival_times/,/^    }/p' stationapi/src/use_case/interactor/query.rs | head -150

Length of output: 2820


@TinyKitten ご説明ありがとうございます。コードを再確認しました。

position() は最初に一致したインデックスを返す仕様のため、重複終端がある場合、from_station_id / to_station_id が末尾と同じ station_cd を指していても常にインデックス 0 に解決されます。つまり fi / ti が末尾のインデックス(n-1、除去対象)を指すことは構造上あり得ず、環状判定に失敗した場合の線形フォールバック route_stops[fi..=ti](および逆順スライス)は、トリムの有無に関わらず全く同じ範囲になります。

ご指摘の通り、この重複終端の除去は環状判定に失敗するケースには一切影響を与えないことを確認できました。私の元の指摘は誤りでした。ご対応ありがとうございます。

ヽ(°〇°)ノ

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.

2 participants