Skip to content

fix(android): detect boarding from the rider's own track - #117

Merged
AvianJay merged 27 commits into
mainfrom
fix/background-boarding-detection
Nov 18, 2026
Merged

AvianJay merged 27 commits into
mainfrom
fix/background-boarding-detection

Conversation

@AvianJay

Copy link
Copy Markdown
Collaborator

問題

背景乘車偵測常常沒偵測到上車,「你上車了嗎」的通知也有機率不跳出來。查到四個各自獨立的原因:

  1. App 開著就完全不偵測。 commit 813be81 在輪詢迴圈、定位回呼、即時資料抓取三處加了 if (!appInForeground)。而 keepScreenAwakeOnRouteDetail 預設開啟,所以只要停在路線頁面上,整個狀態機就不會跑——跟設定名稱暗示的正好相反。

  2. 雙北根本不可能偵測到。 那裡的 ETA feed 不帶車牌,而舊程式的兩個強訊號都要求車牌。但 /realtime/buses 在所有城市都帶車牌與 GPS。

  3. 判斷視窗太脆。 只在使用者還站在站牌附近時存在,5 分鐘後過期就不再開。

  4. 過站的車會卡住。 鎖定一輛車之後就不放,後面的車來了也不會重新判斷。

做法

判斷邏輯移到 TripRideDetector:純 Kotlin、無 Android 依賴、可完整重播的狀態機。比較方式是把使用者和每輛車都換算成「沿站序的距離(公尺)」,因為 2D 鄰近判斷會被橫向誤差主宰——對站牌連線而言,公車定位誤差中位數 8–16 m,但 p90 達 65–295 m。

三層判斷,由強到弱:

  • 與實際車輛同步位移:需要 ≥3 筆配對、≥30 秒、公車移動 ≥150 m,且使用者的速度與位移都跟得上
  • 使用者自己沿路線前進:涵蓋「有上車但那輛車沒有定位 feed」的情況
  • 直接問使用者:連完全沒有定位也能用

公車 GPS 比抓取時間落後 22–39 秒(p50),所以同步位移是量測兩條軌跡之間的固定位移差,而不是鄰近程度;資料新鮮度則以「App 收到的時間」判斷,不是 GPS 時間。

路線家族(family)變更時會重建這趟車,這是「先回主要路線、之後變體才到」的收斂方式;但使用者已確認的乘車不會被重建掉。

另外,等待時通知就有「我已上車」可按,偵測不再是唯一路徑。

順帶修掉的第二個 bug

高雄的站牌 ID 超過 32 bit(像 100100128221),而 App 兩邊把它折成 32 bit 的方式不一致:session 端取低 32 bit(可能變負數並被 > 0 濾掉),即時 feed 端數字太大就改用 hash。兩者永遠不可能相等,所以高雄站牌的即時到站時刻一直查不到。現在統一走 foldStopId(),也涵蓋 TripMonitorFamilyRealtime 自己複製的那一份 parser。

後端 bus.db 的 114,903 個 distinct stop id 裡有 18,203 個超過 int32,其中 5,821 個折完會變負數(高雄 172 條路線受影響)。

驗證

56 個 Android 測試全綠,其中 15 個是重播測試——用 TXG300、KHH100、TPE157463 的真實錄製資料回放:

  • 上車在 180 秒內被偵測到
  • 在站牌等待(含市區峽谷 GPS 雜訊)與沿同一條街走路都被拒絕
  • 高雄的 fixture 特意選在需要折疊的站牌上車
  • 折疊用「低 32 bit 為負」的真實 ID 驗證——折完剛好是正數的 ID 會碰巧通過,測不出 bug

與 family 功能的整合

origin/main 上 6c6c8d7(itousouta15)已經先加了 family 路線處理。兩者動到同一條即時資料路徑,這個 PR 是疊在它上面整合的:

  • updateLiveData 的節流/退避現在包住 familyRealtime.fetch,家族變體一起抓但共用同一個 rate-limit 桶
  • fetchBackendJson 拆成 fetchBackendJsonText / fetchBackendJson(物件) / fetchBackendJsonArray(陣列),因為 /realtime/buses 回傳的是陣列
  • family 的兩條測試改成針對 detector 斷言(rideConfirmed/trackedBusId 已被 detector 取代)

Boarding was often missed, and the prompt asking whether the user got on
sometimes never appeared. Four independent causes:

- Commit 813be81 gated the refresh loop, the location callback and the live
  fetch on `!appInForeground`. Because keepScreenAwakeOnRouteDetail defaults
  to true, the whole state machine stopped running while the route page was
  open — the opposite of what the setting suggests.

- 雙北 boards could never be detected: the ETA feed there carries no plates,
  and both strong signals required one. Vehicle positions come from
  /realtime/buses, which does carry plates and GPS for every city.

- The boarding window only existed while the user was still near the stop and
  expired after five minutes, after which it never reopened.

- A vehicle that had already passed stayed locked, so the next bus could not
  be tracked. Tracking now follows the rider's own position.

The decision moves to TripRideDetector, a pure Kotlin state machine with no
Android dependencies, comparing the rider and each vehicle in metres along
the stop sequence. A 2-D proximity test would be dominated by cross-track
error: against the stop-chord line, bus fixes sit 8-16 m off at the median
but 65-295 m at p90. Rides are recognised three ways, strongest first:
co-movement with a live vehicle, the rider's own progress along the route,
and finally asking the user — so boarding is detected even with no location
at all, and the notification offers "我已上車" while waiting.

Vehicle GPS trails the fetch by 22-39 s (p50), so co-movement is measured as
a stable offset between the two tracks rather than proximity, and feed
recency is judged by when the app received it.

The ride is rebuilt when the route family changes, which is how a preliminary
primary-route response is replaced once the variants arrive; a ride the user
already confirmed is never dropped.

Separately, 高雄 stop ids exceed 32 bits and the two sides of that join
folded them differently: the session payload wrapped the low 32 bits while
the live feed hashed the digits, so a 高雄 stop's live ETA could never be
found, and ids that wrapped negative were dropped outright. Both now call
foldStopId(), including the family fetch's own copy of that parser.

Verified by 15 replay tests over real recorded feeds from TXG300, KHH100 and
TPE157463: the ride is detected within 180 s while waiting at the stop and
walking the same street are both rejected. The 高雄 fixture boards at a stop
whose id needs folding, and the fold is checked against the ids whose low 32
bits are negative, since an id that wraps positive would agree by accident.

@Av1anJay Av1anJay left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Review summary

Requesting changes for four regressions affecting stale location handling, trips without a destination, subsequent boarding detection, and large stop IDs in widget launches. See inline comments.

Checks: git diff --check passed. Local Android unit tests could not run because the checkout has no android/gradlew; Flutter tests could not run because Flutter is not installed. GitHub Actions Verify (including Flutter analyze/tests), Linux, Web, Windows, iOS, macOS, and Wear OS builds passed; Android APK build was still running when checked.

// cached position; ageing them here keeps the whole detector on
// the wall clock the rest of the service uses.
timestampMs = System.currentTimeMillis() -
(SystemClock.elapsedRealtime() - location.time).coerceAtLeast(0L),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Blocking — mismatched clocks make every cached fix appear fresh. Location.time is Unix epoch milliseconds, whereas SystemClock.elapsedRealtime() is time since boot, so their difference is negative and is clamped to zero. For example, a five-minute-old lastLocation becomes a current fix; it can anchor a trip at the wrong stop and be treated as usable for destination/boarding decisions. Use location.elapsedRealtimeNanos with the matching monotonic clock (and handle synthetic session locations with no timestamp), or use the epoch location.time directly. Add a service-level test for an old cached fix.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

已在 5987fb5 修正。

  • 新增 rideFixTimestampMs():用 location.elapsedRealtimeNanos 對 SystemClock.elapsedRealtimeNanos() 算出 fix 的年齡,再從目前 wall clock 扣掉;沒有 monotonic 時間戳的手工 Location(session 的初始位置)改用它自己的 epoch time。
  • Flutter 端的 session 現在會帶 initialLocationTimestampMs(_lastPosition.timestamp),所以路線頁幾分鐘前的定位不會再被當成現在。
  • 順帶修掉同一個問題的另一半:未選上車站時,原本「收到任何 fix 就永久錨定上車站」,現在只有仍新鮮的 fix 才會錨定。

測試:RideFixTimeTest(4 個)以及 service 層的 aCachedFixFromMinutesAgoIsNotTreatedAsWhereTheRiderIs、theSessionsStartingPositionIsAgedByWhenFlutterMeasuredIt。把這行改回原本的寫法,兩個 service 測試都會失敗。

val boardingPointCount = boardingIndex + 1
val boardingProgressPoint =
boardingBusIndex?.plus(1)?.coerceAtMost(boardingPointCount) ?: 0
if (destinationStop == null || !ride.hasBoarded) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Blocking — a trip without a destination never exposes boarding. This branch runs whenever destinationStop == null, even after the detector or the user confirms boarding, and returns hasBoarded = false below. Consequently maybeSendTripAlerts never reaches its hasBoarded && destinationName == null branch, so it does not prompt the rider to choose a destination or pause as intended; the ongoing notification remains in waiting mode as well. Render an onboard snapshot when ride.hasBoarded is true even without a destination, and test the full confirm/detect → destination setup flow.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

已在 5987fb5 修正。

  • buildSnapshot 在所有 waiting 分支之前(包含「上下車站都沒選」那個提前 return)先處理 ride.hasBoarded && destinationStop == null,回傳 hasBoarded = true 的 onboard snapshot,所以 maybeSendTripAlerts 會走到提示設定下車站並暫停。
  • 追下去發現流程後半段也是斷的:暫停時 detector 被清掉,使用者選了下車站後會變回「等待上車」;而且 Dart 端的 paused 旗標會讓新的 session 根本送不到 native。現在同一趟(provider/route/path/上車站相同、原因是 boarded_no_destination、一小時內)補上目的地時會以已上車狀態接續,路線頁選目的地時也會重新比對暫停狀態。

測試:boardingWithoutADestinationAsksForOneAndPicksTheRideBackUp(有/沒有選上車站兩種都跑:確認上車 → 提示通知 → 暫停 → 選目的地 → 仍是已上車)、onlyTheRidePausedForADestinationIsPickedBackUp(使用者自己暫停、不同上車站、超過一小時都不會接續),以及 Dart 的 choosing a destination restarts a monitor paused without one。

boarded = false
evidence = BoardingEvidence.NONE
trackedVehicleId = null
autoDetectionSuppressed = true

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Blocking — declining one bus disables detection for all later buses. If the rider taps 還沒上車 on the question for a bus they did not take, this flag permanently disables both automatic detection and future departure questions until the trip is rebuilt. When their actual bus arrives, boarding and therefore destination alerts will never start unless they discover and press the manual action. Scope suppression to the rejected vehicle/evidence or a bounded snooze, then re-arm for the next departure; add a regression test covering decline of bus A followed by boarding bus B.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

已在 5987fb5 修正,拿掉整趟的 autoDetectionSuppressed。

  • 「還沒上車」只排除被問到(或被自動判定)的那輛車,20 分鐘後失效。
  • 回答之前的移動不再算 self-progress 證據,避免剛回答完又立刻被判上車。
  • 下一班離站會重新詢問。同一次離站被位置 feed 與 ETA 重複回報時的去重視窗從「離站」起算而不是從回答起算,所以使用者晚幾分鐘才回答也不會吃掉下一班。

測試:TripRideDetectorDeclineTest(6 個),包含 decliningOneBusStillDetectsTheNext(拒絕 A 車後搭上 B 車,且鎖定的是 B)、theBoardingQuestionComesBackForTheNextBus、aLateAnswerDoesNotSwallowTheNextDeparture。把永久 suppression 加回去會讓其中 3 個失敗。

val stopId = item.optInt("stopId", 0)
// The config is written by Dart with the raw feed id, which can
// exceed Int for 高雄; fold it the same way the live feed does.
val stopId = foldStopId(item.opt("stopId"))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Blocking — folding the stored ID also changes the ID sent back to Flutter. createItemPendingIntent passes item.stopId and item.destinationStopId into AppLaunchConstants, while Dart route stops retain the full 64-bit IDs and compare them directly. For example, stop 101111144601 is sent as 179413145, so tapping a Kaohsiung favorite widget cannot select the requested boarding/destination stop. The same issue applies to the folded IDs sent from the trip-monitor and smart-route notification intents. Keep a full-width/raw ID for launch payloads (including changing the intent extra types), and use folded values only for native feed joins. Add a widget/notification launch round-trip test with a 64-bit ID.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

已在 5987fb5 修正。折疊後的 Int 現在只用在 native 的 feed join,送回 Flutter 的一律是完整寬度的 ID。

  • createRouteDetailIntent 的 stopId/destinationStopId 改成 Long,extras 也存 Long。
  • widget item、trip monitor session/stop、smart route stop 各自多帶一個 launchStopId,三個產生 intent 的地方都改用它。
  • MainActivity 釘選捷徑原本用 call.argument<Int> 讀 stop id,高雄的 ID 會讀成 null,一併改掉。
  • 讀取端相容舊版已釘選捷徑裡的 Int extra(getLongExtra 遇到型別不同的 extra 會回傳預設值)。

測試:AppLaunchStopIdTest 用 101111144601 實際走完 widget 點擊與智慧推薦通知的 PendingIntent → extractLaunchPayload,RouteTripMonitorServiceTest.tappingATripNotificationLaunchesWithTheFullWidthStopId 涵蓋乘車通知,另有舊 Int extra 的相容測試與 Dart 端 AppLaunchAction.fromMap 的測試。改回送折疊值時會得到你提到的 179413145 而失敗。

Four regressions from the boarding-detection rewrite, each with a
regression test that fails when the fix is reverted.

- Fix age: Location.time (epoch) was subtracted from elapsedRealtime
  (since boot), so every cached fix looked current. Age is now read off
  the monotonic clock, the session's seed position carries the time
  Flutter measured it, and only a fresh fix may anchor the boarding stop.
- Boarded without a destination: the snapshot always reported "waiting",
  so the destination prompt never fired. It now reports the ride, and
  choosing a stop afterwards continues that ride instead of starting a
  new wait. The route screen re-checks the paused state when a
  destination is chosen so the new session is actually sent.
- Declining a bus no longer disables detection for the trip. Only the
  declined vehicle is set aside (20 min), movement before the answer no
  longer counts, and the next departure is asked about again.
- Launch payloads carry the full-width stop id. The folded Int is kept
  for native feed joins only; widget, trip and smart-route notification
  taps and pinned shortcuts send the id Flutter holds. Int extras from
  shortcuts pinned by older builds are still read.
@AvianJay

Copy link
Copy Markdown
Collaborator Author

Review 的四項都已在 5987fb5 處理,細節回在各個 thread。

本機驗證(CI 的 Verify 不跑 Android 單元測試):

  • :app:testDebugUnitTest:91 個通過
  • flutter test:549 個通過
  • flutter analyze:這個分支的檔案沒有問題

每個修正都有暫時改回錯誤版本、確認對應測試會失敗。

另外兩個已知但不在這次範圍內的限制:離開路線頁(dispose)以及從最近使用清單滑掉 App(onTaskRemoved/stopWithTask)仍然會停止監測。

@Av1anJay Av1anJay left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Review summary

The previous four reported issues have targeted fixes, but I found three additional blocking cases affecting boarding detection and direction changes. Please see the inline comments.

Checks: git diff --check passed. Node runtime tests passed (3/3) using Node 22.23.4; the host's default Node 22.23.1 is rejected by the project's security guard. GitHub Actions Verify passed (including flutter analyze, Flutter tests, and the Chrome geometry test), and the Android, Wear OS, Linux, Web, Windows, iOS and macOS builds passed. I could not run Android unit tests locally: Flutter and the generated android/gradlew are absent. The CI workflow does not run the Android unit tests.

val liveStop = liveStops[boardingStopId] ?: return
val etaEntry = liveStop.etaEntries.firstOrNull()
val arriving = liveStop.seconds?.let { it <= 0 } == true ||
liveStop.vehicleIds.isNotEmpty() ||

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Blocking — a vehicle with a future ETA is treated as already arriving. parseTripMonitorLiveStop includes vehicle IDs from ETA entries regardless of their ETA, and family merging likewise retains IDs for later buses. Thus when the current bus leaves and the next plated bus has, say, a 600-second ETA, vehicleIds.isNotEmpty() keeps arriving true, so onBoardingStopEta resets its arrival timestamp instead of detecting the rollover. This removes the fallback boarding question exactly when the departed bus has no usable GPS feed. Determine arrival from the selected ETA/message or an actual at-stop bus, not any future vehicle ID; add a service-level test for 0 → 600 seconds with a plate on the next ETA.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

已在 2c66fac 修正。LiveStopState 多了 busesAtStop,只放 feed 的 buses(實際在站的車),family 合併時取聯集;vehicleIds 維持原樣給車輛追蹤用。feedBoardingEta 的 arriving 改看 ETA ≤ 0、進站/到站訊息,或 busesAtStop,不再看 ETA entry 上的車牌。

測試:theEtaRollingOverToAPlatedLaterBusStillRaisesTheQuestion——service 層餵 0 秒(帶車牌)→ 600 秒(下一班帶車牌),確認離站有被登記。改回 vehicleIds.isNotEmpty() 會失敗。

// route with stops to look up that answers with nothing is a
// failure rather than an empty feed — so back off rather than
// spend the shared rate limit on retries.
if (liveStops.isEmpty()) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Blocking — a missing stop feed also disables the independent vehicle feed. If the stop endpoint fails or returns an empty map, this return (and the shared backoff above) prevents /realtime/buses from being fetched at all, even if that endpoint is healthy. A rider with limited/no phone fixes then loses bus-based departure questions and vehicle tracking for every retry, despite the live positions being available. Back off the failing stop fetch independently and still attempt the bus fetch; cover an empty/failed stop response with a successful bus response.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

已在 2c66fac 修正。站牌 feed 與車輛 feed 各自有退避(liveStopBackoffUntilMs/liveBusBackoffUntilMs),站牌 feed 失敗或回空只退避自己,/realtime/buses 照常抓。車輛 feed 原本失敗時沒有退避、每次 refresh 都會重試,也一併補上。

測試:aFailingStopFeedDoesNotSilenceTheVehicleFeed——站牌請求失敗、車輛請求成功,確認車輛報告有進來,且站牌退避期間車輛 feed 仍持續抓、站牌不重試。還原成共用退避會失敗。

@@ -261,72 +270,148 @@ class RouteTripMonitorService : Service() {
AppRuntimeStateStore.setAppInForeground(this, appInForeground)
val tripOriginChanged =

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Blocking — switching direction can reuse the old detector and geometry. The rebuild identity compares boarding stop, route ID and route key, but not pathId or the stop sequence. When the rider switches direction on the same route and the boarding stop is shared (or both boarding IDs are null), neither this condition nor familyChanged changes. The detector continues projecting onto the previous direction's stops with its previous pathId, potentially retaining a confirmed ride and using wrong stop counts/alerts on the new tab. Include direction (and changed route topology where relevant) in detector identity and test switching paths with the same boarding stop.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

已在 2c66fac 修正。重建 detector 的判斷加入 pathId 與站序(各站 folded id 的順序),所以同路線切換方向、或站序變了,都會重建而不是沿用舊方向的幾何;站序相同的一般 refresh 不受影響。

測試:switchingDirectionRebuildsTheRideEvenWithTheSameBoardingStop——上車站相同、切到反向後已確認的乘車被清掉,上車站 index 依新方向的站序重新算;另外驗證 pathId 不變但站序改變也會重建。

Three further review findings, each with a service-level test.

- A plate on an ETA entry is a bus still on its way, not one at the
  stop. Counting it as "arriving" hid the ETA rolling over to the next
  bus, which is the only departure signal when the bus that left has no
  position feed. Only buses the feed places at the stop count now.
- The stop feed and the vehicle feed back off separately, so a failing
  stop feed no longer stops vehicle positions from being fetched.
- Direction and stop order are part of what makes a trip. Switching to
  the other direction with the same boarding stop rebuilds the detector
  instead of measuring along the previous direction's stops.

The service tests no longer reach the real backend, and tests about a
continuing ride give it a destination: a ride confirmed without one is
paused to ask for it, which they had been racing.
@AvianJay

Copy link
Copy Markdown
Collaborator Author

第二輪的三項已在 2c66fac 處理,細節回在各 thread。本機 :app:testDebugUnitTest 97 個通過(這次只動 Kotlin);三個修正都有改回原本行為確認對應測試會失敗。

另外:service 測試現在不會再打到真正的後端(每個測試自己決定後端回什麼);幾個「已確認乘車後續行為」的測試補上了下車站——沒有下車站的已上車行程會被暫停去詢問,原本這些測試是靠時序僥倖通過的。

@Av1anJay Av1anJay left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Review summary

Requesting changes for two boarding-state regressions: co-movement can confirm a bus explicitly marked as the other direction, and an in-flight fetch for an old trip can feed its data into a newly rebuilt detector. Details and suggested regression tests are inline.

Checks: git diff --check passed; Node 22.23.4 npm run test:node and npm run test:web passed (3 tests each). I compiled the actual pure-Kotlin detector and route line with a minimal TrackingStop shim and reproduced the opposite-direction false boarding. GitHub Actions on this head passed Verify (Flutter analysis/tests and Web geometry) and Android, Wear OS, Linux, Web, Windows, iOS and macOS builds. Android unit tests were not run locally: Flutter and the generated Gradle wrapper are unavailable; the CI workflow does not run those unit tests.

return@forEach
}
pairs.clear()
track.forEach { report ->

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Blocking — co-movement ignores direction and on-route validity. onBusReports records samePath and onRoute, but this loop feeds every report to isCoMovement without checking either. A vehicle reporting the opposite direction can therefore confirm boarding and be locked as the rider's bus if its projected track moves alongside the phone. I reproduced this with the actual detector: a path-0 trip and a path-1 vehicle at the same coordinates produced hasBoarded=true, BUS_CO_MOVEMENT, and trackedVehicleId=WRONG-DIRECTION at 40 seconds. If the phone then loses fixes, that wrong bus drives destination alerts. Exclude wrong-path and off-route samples before matching (and ensure the resulting track is coherent); add negative tests for both.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

已在 2cc01e7 修正。

  • detectCoMovement 在配對前先排除 !samePath || !onRoute 的回報,而且這種回報會中斷該車的連續紀錄(pairs.clear()):只有「同方向、在路線上、沒被打斷」的那一段才算證據。這是你提到的 track 要 coherent 的部分——反方向/偏離路線那段前後的回報不會被接成同一段。
  • 你重現的情境(path 0 的行程、path 1 的車在相同座標)寫成了 aBusOfTheOtherDirectionIsNotTheRidersBus:不會 hasBoarded,也不會有 trackedVehicleId。
  • 另外補了一處這則 comment 沒提到的:上車後挑「正在搭的車」的 resolveTrackedVehicle 原本只看 samePath,現在也要求 onRoute,停在路線旁的車不會因為投影位置最近而被選中。

測試在 TripRideDetectorCoMovementTest(5 個):

  • ridingABusOfThisDirectionIsDetected:正向對照組,確認下面的負向測試不是因為情境本身就測不到
  • aBusOfTheOtherDirectionIsNotTheRidersBus
  • aVehicleOffTheRouteIsNotTheRidersBus(偏離路線 350 m)
  • reportsEitherSideOfAStretchOnTheOtherDirectionDoNotAddUp
  • aVehicleParkedBesideTheRouteIsNotPickedAsTheBusBeingRidden

把修正改回去確認測試會紅:

改回去的內容 變紅的測試
拿掉過濾 aBusOfTheOtherDirection…、aVehicleOffTheRoute…、reportsEitherSide…
保留過濾但不中斷連續紀錄 reportsEitherSide…
挑車不看 onRoute aVehicleParkedBeside…(拿到 PARKED 而不是 AAA-001)

對正常偵測的影響:TripRideDetectorReplayTest 用的三段實際錄製 feed,偵測延遲改前改後相同(TXG300 130 s、KHH100 111 s、TPE157463 73 s)。同一批錄製資料裡,同方向營運中車輛被判 off-route 的比例是 0–7%,連續紀錄中間孤立的 off-route 只有 1 筆;58 輛車約 2900 筆回報中方向改變 12 次,沒有單筆 A→B→A 的抖動,所以「中斷就重來」不會讓正常行駛的車測不到。

沒變的一點:車輛沒回報方向(pathId == null)時仍當作同方向,因為無從判斷。

cachedBusReports = reports
}
synchronized(detectorLock) {
detector?.onBusReports(reports)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Blocking — stale fetches can mutate a different trip's detector. refreshNotification checks the session before updateLiveData, but this method performs blocking HTTP requests; meanwhile the main thread can replace session and rebuild detector after the user changes routes or direction. When the old request completes, this line feeds the old route's buses into the new detector; feedBoardingEta above has the same issue for the old boarding stop. The later identity check at snapshot rendering is too late to undo that state. Check the session/generation again atomically with detector mutation and cache updates (also after each network wait), and add a test that holds an old fetch open, switches the trip, then releases it and verifies the new detector receives none of the old data.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

已在 2cc01e7 修正,作法就是你建議的:與 detector 的變更放在同一把鎖內再檢查一次,每次網路等待之後都檢查。

  • 行程交接:session 與為它建立的 detector 現在在主執行緒、同一個 detectorLock 區塊內一起替換(原本是 session 先換、detector 之後才重建)。
  • 套用前檢查:refreshTrip 一開始在鎖內取得 TrackedTrip(session, detector)。每個請求回來後,結果都經過 applyToTrip(trip):在同一把鎖內確認 detector === trip.detector,接著才寫 cache、退避、餵 detector,檢查與寫入之間不可能被換掉。站牌與車輛兩個請求各檢查一次;行程一旦被換掉,這次 refresh 就停止,不再發下一個請求,也不產生快照。
  • 資料只給擷取到的那個 detector:onBusReports/onBoardingStopEta 的對象是 trip.detector,不再是「目前的 detector」。所以就算拿掉檢查,舊資料也進不了新 detector;檢查另外保護的是新行程會讀到的 cache 與退避時間。
  • 新行程從乾淨狀態開始:重建 detector 時呼叫 forgetLiveFeeds(),兩個 feed 立刻到期。取捨:切換行程後不承接上一趟的失敗退避,原本在退避中的 feed 會立刻重試一次。
  • 結尾的動作(超出這則 comment,但是同一類問題):通知與 alert 在 IO 執行緒算好後改丟回主執行緒,執行前比對 session 與 ride 快照是否仍是計算時的那一份(postIfStillTracking)。原本 IO 執行緒上的 pauseTracking/stopTracking 可能作用到已經換掉的新行程;現在為舊行程決定的暫停,或是使用者回答「還沒上車」、選了下車站之前算出來的暫停,都會被丟棄。

測試(RouteTripMonitorServiceTest):

  • aFetchStillInFlightForTheLastTripDoesNotReachTheNextOne:照你描述的寫法——用 latch 卡住舊行程的站牌請求、切換行程、放行,再驗證新行程第一次 refresh 看到的是自己的車(NEW-001),而且舊行程的 ETA=0 沒有變成「公車離站」的詢問。「換成另一條路線」與「同路線換方向」各跑一次,兩種情況的站牌都相同,舊資料完全套得上。
  • aRebuiltTripHearsOfTheVehiclesOnItsFirstRefresh
  • whatARefreshDecidedForAReplacedTripIsNotActedOn
  • whatARefreshDecidedBeforeTheRiderAnsweredIsNotActedOn
  • whatARefreshDecidedBeforeADestinationWasChosenIsNotActedOn

把修正改回去確認測試會紅:

改回去的內容 結果
還原成你回報的行為(不檢查、結果餵給「目前的」detector) stale-fetch 測試紅,新行程拿到 OLD-001
只拿掉 applyToTrip 的身分檢查 同一個測試紅:新行程第一次 refresh 被舊行程寫入的 cache 時間擋住,拿到 null
新行程不重設 feed 狀態 aRebuiltTrip… 紅
拿掉結尾的 session 比對 …BeforeADestinationWasChosen… 紅
拿掉結尾的 ride 比對 …BeforeTheRiderAnswered… 紅
結尾兩個比對都拿掉 三個 whatARefreshDecided… 全紅

Two further review findings, plus what turned up beside them.

- Co-movement counted any vehicle of the route: the other direction's,
  and ones parked or deadheading beside it, all project to some position
  along the line. Only an unbroken run of reports on this trip's
  direction and on the route is evidence now, and a report that is
  neither breaks the run instead of being bridged over. The vehicle
  followed once on board has to be on the route as well.
- A fetch still out when the rider switched trip was applied to whatever
  trip was current when it came back. The session and its detector now
  change hands together under the detector lock, and each response is
  applied under that lock only if the detector it was fetched for is
  still the current one — caches and back-off included. A new trip
  starts with both feeds due and without the last trip's back-off.
- Notifications and alerts are worked out on the IO thread but acted on
  on the main thread, and only if neither the session nor the ride has
  changed since: a pause decided for the last trip, or from before the
  rider answered or chose a destination, is dropped.
- While the app is open it does the fetching, so the detector never
  heard the boarding stop's ETA. The stop feed the app hands over now
  reaches it.

Each has a test that fails when the fix is reverted.
@AvianJay

Copy link
Copy Markdown
Collaborator Author

第三輪的兩項都在 2cc01e7 處理,細節回在各自的 thread。

本機驗證

  • Android 單元測試(:app:testDebugUnitTest,Robolectric SDK 28/34):114 個全過。
  • git diff --check 無問題。
  • 這輪只動 Kotlin,Flutter 的 analyze/test 沒有重跑。
  • CI 不跑 Android 單元測試,所以上面的結果只來自本機。

超出兩則 comment 的變更(請一併看)

  1. resolveTrackedVehicle 挑車也要求 onRoute。
  2. App 在前景時站牌資料由 Dart 抓好交給 service,service 自己不抓。原本這份資料只進 cache,detector 在前景聽不到上車站的 ETA,也就沒有「ETA 歸零後跳到下一班」這個離站訊號;現在交接時也會餵給 detector。測試:theStopFeedTheAppHandsOverWhileOpenReachesTheDetector。
  3. 通知與 alert 改在主執行緒、比對 session 與 ride 快照後才執行。
  4. 重建行程時重設 feed cache 與退避(取捨寫在 stale fetch 那則 thread)。
  5. 移除沒有任何讀取者的 cachedBusReports;detectorLock 由 var 改為 val。

已知、這個 PR 沒處理

  • 車輛沒回報方向時仍視為同方向。
  • 離開路線頁、或從最近使用清單滑掉 App,仍會停止監測(先前留言提過)。

@Av1anJay Av1anJay left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Review summary

Requesting changes for two remaining trip-monitor regressions: an overshot destination can bypass arrival/overshoot alerts, and an older in-flight stop fetch can overwrite a newer foreground update for the same detector. Details are inline.

Checks: git diff --check passed; Node 22.23.4 npm run test:node and npm run test:web passed (3 tests each). GitHub Actions for this head passed Verify (including Flutter analysis/tests and Web geometry) and Android, Wear OS, Linux, Web, Windows, iOS and macOS builds. Android unit tests were not run locally: Flutter and the generated Gradle wrapper are absent, and CI Verify does not run them.

boardingCheckId = pendingCheckSinceMs,
boardingPromptDue = boardingPromptDue,
remainingStops = stopsToGo?.coerceAtLeast(0),
passedDestinationByStops = stopsToGo?.let { -it }?.takeIf { it > 0 },

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Blocking — skipping directly past the destination can suppress all destination alerts. The new detector uses the last stop reached, so between two refreshes a fix can jump from two stops before the destination to the next stop after it (for example when fixes resume after a gap, or on short stop spacing). passedDestinationByStops is then non-null, so this branch returns before maybeSendDestinationAlert can set arrivalDetectedAtMs; maybeSendOvershotAlert also refuses to run while that timestamp is zero, and maybePauseAfterArrivalGrace does the same. Subsequent overshot snapshots follow the same branch forever: no arrival or overshoot alert and no auto-pause. Establish an arrival/overshoot baseline when progress has already passed the destination, and test a direct pre-destination → past-destination jump without an intermediate arrival snapshot.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

已在 c8d42d1 修正。

  • maybeSendTripAlerts 收到已越過目的站的 snapshot 時,若還沒有 arrivalDetectedAtMs,先建立到站基準,再走原有的過站確認與到站寬限流程;後續 snapshot 不會重設已開始的倒數。
  • 保留原有門檻:45 秒後,符合路線距離條件時發出「可能坐過站了」並以 overshot 暫停;無法確認過站時,60 秒到站寬限仍可結束並以 arrived 暫停。

回歸測試(RouteTripMonitorServiceTest,SDK 28/34):

  • skippingTheDestinationStillRaisesTheOvershootAlert:定位直接從目的站前跳到下一站,沒有中間到站 snapshot;驗證建立基準、倒數不重設,最後確實發出通知並暫停。
  • skippingTheDestinationStillPausesAfterArrivalGraceWhenOffRoute:跳過目的站後距路線約 150 m,無法確認過站時仍會在寬限後暫停。

本機 :app:testDebugUnitTest:122 個測試全過;git diff --check 通過。

*/
private fun applyToTrip(trip: TrackedTrip, apply: () -> Unit): Boolean =
synchronized(detectorLock) {
if (detector !== trip.detector) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Blocking — a stale fetch can still overwrite a newer update for the same trip. The guard compares only detector identity, but ACTION_START_OR_UPDATE replaces session and feeds/caches the foreground screen's providedStops without rebuilding the detector on ordinary updates. If an earlier stop request is in flight, the new foreground update can record ETA=0, then the older response (e.g. ETA=600 from before arrival) passes this check, overwrites the newer cache and is fed into onBoardingStopEta, which registers a false departure. This can raise a spurious boarding question while the bus has only just arrived. Guard stop-feed results against session/update generations or compare fetch/update freshness before applying them (while still allowing valid vehicle results), and add a latch-based test for an in-flight old fetch followed by a newer same-trip foreground ETA update.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

已在 c8d42d1 修正。

  • 增加由 detectorLock 保護的 stopFeedRevision;每次套用 App 提供的站牌資料時遞增,currentTrip() 在同一把鎖內擷取當時的版本。
  • 舊站牌請求回來後,在 applyToTrip 的鎖內同時檢查 detector 身分與站牌版本。版本已變時,不寫 cache、不餵 ETA,也不套用舊請求失敗的退避。
  • 只丟棄過時的站牌回應,不結束整個 refresh;同趟仍有效的車輛定位照常抓取並送入 detector。

新增兩個 latch-based service 測試(SDK 28/34):

  • anOldStopFetchCannotOverwriteANewerAppUpdateForTheSameTrip:卡住舊請求,同一 detector 收到前景 ETA=0 更新後才放回舊 ETA=600;驗證新 cache 保留、不產生假離站,而且有效車輛資料仍被接收。
  • anOldStopFetchFailureCannotBackOffANewerAppUpdateForTheSameTrip:同樣的交錯順序,舊請求改為失敗,驗證不套用過時退避且車輛定位不受影響。

本機 :app:testDebugUnitTest:122 個測試全過;git diff --check 通過。

Start the arrival baseline when progress skips directly past the destination, retaining overshoot reminders and the arrival grace pause.

Version app-provided stop data so older in-flight responses cannot overwrite its cache, invent departures, or apply obsolete backoff; keep valid vehicle results.

Add four service regression tests across SDK 28 and 34. All 122 Android unit tests pass.
@AvianJay

Copy link
Copy Markdown
Collaborator Author

最新兩項 Request changes 已在 c8d42d1 修正並推送。

  1. 直接越過目的站:先建立到站基準,保留 45 秒過站確認與 60 秒到站寬限;後續 snapshot 不會重設倒數。對應 thread
  2. 同趟行程的舊請求:用站牌版本拒收被前景更新取代的回應與失敗退避,避免舊 ETA 製造假離站;有效的車輛定位仍會套用。對應 thread

本機驗證

  • :app:testDebugUnitTest:122 個測試全過,0 failure/error/skip。
  • 新增 4 個 service 回歸測試,SDK 28/34 各跑一次,共 8 個案例;涵蓋直接越站、離線路時的寬限暫停,以及舊站牌請求成功/失敗的交錯更新。
  • git diff --check 通過。
  • 本輪只改 Kotlin 與 Android 測試,未重跑 Flutter analyze/test。

@Av1anJay Av1anJay left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Review summary — changes requested

  1. Blocking — family-variant buses never reach the detector (RouteTripMonitorService.kt:820–832). The stop feed merges session.realtimeRouteIds, but the vehicle branch fetches only primaryRouteId. If a rider takes a family variant and the phone has no usable fixes, ETA rollover can still lead to manual confirmation, but vehicleJustPastBoardingStop cannot find the variant bus; trackedVehicleId and progress remain unknown, so destination reminders never fire. Fetch and merge positions for the same family routes, with direction/geometry validation and shared throttling; add a service test with only a variant vehicle, confirmation, and no phone fixes.

  2. Blocking — a bus-only overshoot is silently paused instead of alerted (RouteTripMonitorService.kt:1589–1599, :1857–1864). The detector falls back to the tracked vehicle without phone fixes, so it can report an overshoot and vehicle-based destination distance, but maybeSendOvershotAlert also requires nearestStopDistanceMeters, which buildSnapshot derives only from latestLocation. With no fix it is null (or can be stale and far away), so the overshoot check fails and the trip is paused as arrived after 60 seconds without an overshoot alert. Carry a route-validity/proximity signal from the tracked bus or otherwise handle missing/stale phone fixes; test a confirmed tracked bus passing the destination without usable phone location.

Checks: git diff --check passed. Node 24.22.1 runtime tests and web worker tests passed (3/3 each); the host default Node 22.23.1 was rejected by the project's version guard. GitHub Actions Verify passed (Flutter analyze/tests and Web geometry), as did Linux, Web, and Windows builds; Android, Wear OS, iOS, and macOS builds were pending when checked. Android unit tests were not run locally: Flutter and the generated Gradle wrapper are unavailable, and the Verify job does not run them.

GitHub rejected the attempted inline review with HTTP 422 Line could not be resolved; its files API omits the patch for this large file, so the findings are included here with exact line references instead.

Fetch every realtime family route with per-endpoint throttling and backoff, merge each vehicle's newest report, and reject results from removed variants.

Carry route validity with the actual progress source so missing or stale phone fixes cannot suppress a valid bus-only overshoot alert. Preserve ride identity through invalid reports or outages without trusting their positions, and support confirmation before vehicle reports arrive.

Add service and detector regression coverage. All 140 Android unit tests pass.
@AvianJay

Copy link
Copy Markdown
Collaborator Author

回覆這輪 review:兩項已在 209fd7b 修正並推送。

1. 家族變體車輛沒有進入 detector

  • 車輛定位改抓 session.realtimeRouteIds 的所有路線,而不是只抓 primary。相同車牌保留 GPS 時間最新的報告,再交給 detector 的方向/路線幾何驗證。
  • 每個端點共用同一套 15 秒刷新、失敗退避 60 秒的政策,但各自計時;一條變體失敗不會阻止其他路線更新。晚到的 family 變體會立即補抓,不會重抓仍新鮮的 primary。
  • 每次網路等待後仍在 detectorLock 內檢查行程身分,並檢查路線是否還屬於目前 family;已移除變體的舊回應不會重新寫入刷新狀態或送進 detector。
  • service 測試包含 aFamilyVariantCarriesAConfirmedRideWithoutPhoneFixes:只有變體車輛、沒有手機定位、使用者確認上車後,確實追到同一輛變體車,站數隨車前進,並發出「準備下車」。另測節流、部分失敗、family 晚到,以及變體移除時仍在途中的請求。

2. 只有公車定位時,過站被靜默當成到站暫停

  • RideSnapshot 現在攜帶 hasRouteValidProgress,由提供進度的同一筆有效資料決定。手機定位可用時保留原有的近站保護;手機定位缺失或過期時,改用被追蹤車輛的方向與路線有效性,不再讓 latestLocation 的 null/過期位置否決車輛進度。
  • 保留原有 45 秒過站確認與 60 秒到站寬限;有效的 bus-only 過站會先發出「可能坐過站了」,再以 overshot 暫停,而不是靜默以 arrived 暫停。
  • aTrackedBusRaisesAnOvershootAlertWithoutPhoneFixes 與 aStaleFarAwayPhoneFixDoesNotHideATrackedBusOvershoot 都實際驗證通知標題與暫停原因,不只驗證 detector 的站數。

同一路徑補齊的邊界

  • 已確認乘車在定位中斷、反向或偏離路線回報期間保留車輛身分,但不拿無效位置計算進度;正常回報恢復後繼續追同一輛,不會跳到另一班。
  • 手動確認早於第一份車輛資料、或僅有過期手機定位時,仍可在有效車輛資料到達後接續追蹤。
  • 偏離路線的報告不會單獨被當成離站訊號。

本機驗證

  • :app:testDebugUnitTest:140 個測試全過,0 failure/error/skip;本輪增加 18 個案例,service 測試涵蓋 SDK 28/34。
  • git diff --check 通過。
  • 本輪僅修改 Kotlin 與 Android 測試,未重跑 Flutter analyze/test。

@Av1anJay Av1anJay left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Review summary — changes requested

Manual confirmation without a usable phone fix can lock onto an unrelated bus far ahead of the boarding stop, causing false arrival/overshoot alerts and pausing the trip. See inline finding.

Checks: git diff --check passed. With Node 24.22.1, npm run test:node and npm run test:web passed (3/3 each). Compiled the actual pure-Kotlin detector and route-line classes with a minimal TrackingStop shim and reproduced the far-ahead-bus selection. GitHub Actions Verify (Flutter analyze/tests and Chrome geometry), Android, Wear OS, Linux, Web, Windows, iOS and macOS builds passed. Android unit tests were not run locally: Flutter and the generated Gradle wrapper are absent; CI Verify does not run those Android unit tests.

}
val boardingAlong = line.alongOfStop(boardingStop)
return liveVehicles(nowMs)
.filter { it.samePath && it.onRoute && it.alongMeters >= boardingAlong - AT_STOP_MARGIN_METERS }

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Blocking — manual confirmation can lock onto a bus already far down the route. With no usable phone fix and no identified departure, vehicleJustPastBoardingStop has only a lower bound; if the only fresh same-direction vehicle is multiple stops past the boarding stop, confirming "我已上車" selects it as the rider's bus. Its progress then drives destination reminders even though it may be an earlier bus: I compiled the actual detector with six stops and a destination at stop 3; a single bus at stop 5 produced trackedVehicleId=AHEAD-ONLY, passedDestinationByStops=2, and hasRouteValidProgress=true immediately after confirmation. The service can consequently issue a false overshoot alert and pause the real trip. Require evidence that the vehicle was at/just departed the boarding stop (and an upper distance/time bound), otherwise retain an unknown vehicle until it can be identified. Add a regression test for an earlier bus several stops ahead with no phone fix, including a later actual boarding bus.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

已在 3d607f6 修正。確認「已上車」與確認「是哪輛車」現在是分開的;沒有足夠證據時保留 hasBoarded=true、trackedVehicleId=null,不讓前方舊車的進度觸發目的站提醒。

車輛關聯條件

  • 必須在最近 90 秒收到過實際在站觀測:距上車站不超過 80 m、沿線位置在站點 ±40 m 內;從那筆觀測到現在的回報須連續保持同方向、在路線上。
  • 最新回報也須在 90 秒內,且目前沿線位置不得超前上車站 250 m。原本直接採用 pendingCheckVehicleId 的捷徑也移除;具名離站提示不能繞過相同的距離/時間條件。
  • 延後辨識只在首次手動確認後 120 秒內進行,重按不會刷新窗口;已辨識的乘車也不會因重按而換成另一輛較靠近站牌的車。
  • 多個候選且無有效具名離站證據時保留未知,不會因其中一輛駛出距離界線就轉鎖另一輛;手機定位恢復後仍能辨識。
  • 在站證據使用實際座標距離,不只看投影:站前車輛會被 polyline 夾到進度 0、平行街道的車也可能投影到站點,這兩種都另有負向測試。

回歸驗證

  • TripRideDetectorManualBoardingTest:15 個測試,包含你提供的六站路線/前方車已過目的站兩站,以及稍後真正上車的車出現後才開始追蹤;另涵蓋距離/時間邊界、重複舊 GPS、反向/離線路中斷證據、過期具名提示、候選歧義與重複確認。
  • RouteTripMonitorServiceTest.manualBoardingWaitsForTheActualBusInsteadOfAnEarlierBusPastTheDestination(SDK 28/34):確認前方舊車不會建立到站計時或暫停行程;真正車輛抵站後才追蹤,隨它前進並發出正常的「快到了」。修正前,遠車誤鎖與這個 service 回歸案例都會失敗。
  • 三個原有正向測試的首筆車位改為實際在上車站,保留後續異常/斷線/恢復斷言;另有僅在站前方 100/200 m、沒有在站證據時拒絕辨識的測試。

本機 :app:testDebugUnitTest:157 個測試全過(新增 17 個案例),0 failure/error/skip;git diff --check 通過。本輪僅修改 Kotlin 與 Android 測試,未重跑 Flutter analyze/test。

Manual confirmation preserves boarding without assigning an unrelated vehicle far along the route. Require a recent physical at-stop observation, a bounded uninterrupted route-valid track, and a short identification window; validate named departures against the same bounds.

Keep ambiguous rides unidentified, preserve an already identified vehicle on repeated confirmation, and do not refresh the identification window by repeated taps.

Add pure detector and service regressions for the earlier bus followed by the actual boarding bus, spatial/time boundaries, stale evidence and ambiguity. All 157 Android unit tests pass.
@AvianJay

Copy link
Copy Markdown
Collaborator Author

本輪「沒手機定位時,手動確認誤鎖前方舊車」已在 3d607f6 修正並推送,細節與測試回覆在 review thread。

  • 確認上車不再等同確認車號;須有近期實際在站證據、距離與時間上限才可關聯車輛,否則維持「已上車、車輛未知」。
  • 防止具名舊提示繞過限制、重按刷新辨識窗口,以及多車歧義時誤換車;稍後真正上車的車出現時仍可正確追蹤。
  • 本機 :app:testDebugUnitTest:157 個全過,新增 17 個案例;git diff --check 通過。本輪未重跑 Flutter analyze/test。

@Av1anJay Av1anJay left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Review summary — changes requested

The bounded manual-identification window still lets a later, unrelated bus be selected after the rider has already confirmed boarding, causing false destination/overshoot alerts when phone location is unavailable. See the inline finding.

Checks: git diff --check passed. Node 24.22.1 npm run test:node and npm run test:web passed (3/3 each); the host's default Node 22.23.1 is rejected by the version guard. Compiled the actual pure-Kotlin detector and route line with a minimal TrackingStop shim and reproduced the later-bus selection and false overshoot. GitHub Actions Verify (Flutter analyze/tests and Chrome geometry), Android, Wear OS, Linux, Web, Windows, iOS and macOS builds passed for this head. Android unit tests were not run locally: Flutter and the generated Gradle wrapper are unavailable; the CI Verify workflow does not run them.

if (nowMs - latest.receivedAtMs !in 0L..MANUAL_VEHICLE_EVIDENCE_MAX_AGE_MS) {
return@filter false
}
track.reversed().takeWhile { it.samePath && it.onRoute }.any { sample ->

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Blocking — a later bus can still be mistaken for the confirmed ride. The candidate's at-stop sample may be recorded after manualConfirmationAtMs, and it does not need to be tied to a named departure or any pre-confirmation observation. With no usable phone fix, if the rider confirms at t=0 while their actual bus has no feed, then a different bus arrives at the boarding stop at t=60s, this picks and permanently locks that later bus. I reproduced this with the actual detector: the t=60 snapshot tracked LATER-BUS, and its t=120 progress beyond the destination produced passedDestinationByStops=1 and hasRouteValidProgress=true; the service can then issue false alerts and pause the trip. Please require evidence that ties the vehicle to the departure the rider confirmed, rather than accepting an arbitrary future stop visit, and add a regression test for a later bus arriving during the identification window.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

已在 5665a40 修正。

這則的問題:原本只要求「最近 90 秒內看過這輛車在站上」,用的是 app 收到回報的時間,所以確認之後才進站的車也符合。現在改成:能認定車輛的那筆在站定位,必須是車機時間落在使用者確認前 90 秒內(confirmedAt - gpsTimeMs in 0..90s)。回報本身可以晚到(feed 本來就落後半分鐘),兩分鐘的認定視窗只為這件事保留;確認之後才進站的車,不管什麼時候被看到都不算。

你重現的情境寫成 aLaterBusCallingAtTheStopIsNotTheConfirmedRide:t=0 確認、實際搭的車沒有 feed,另一輛車在確認後 1/20/60/110 秒進站,之後開過目的地——每一種都維持 trackedVehicleId == null、passedDestinationByStops == null、hasRouteValidProgress == false。

被問到的那輛車:你提到要「綁到使用者確認的那次離站」。「你有上車嗎?」如果是針對某輛被看著進站又離站的車,回答「我已上車」現在直接鎖定那輛車(answeringTheQuestionAboutANamedBusFollowsThatBus)。這裡我改掉了上一輪自己加的限制:上一輪讓被問到的車也受 250 m 上限約束,但問題要在離站 40 秒後才顯示,那時車幾乎一定超過 250 m,等於回答了也認不到車。現在的上限改用時間:問題超過 5 分鐘就不再指向任何車(aQuestionThatHasLapsedNamesNoBus),而且離站本身也多了下面第 1 點的限制。

我自己重新審這段時另外找到、一併修掉的:

  1. 車輛在站前被看到、沉默很久之後出現在站後,會被當成「剛離站」並跳出詢問(集合從不過期)。現在兩筆回報相隔超過 180 秒就不算離站。aVehicleBackAfterALongSilenceDidNotJustLeaveTheStop。
  2. 「已上車但沒選下車站」暫停後,選了下車站恢復行程時,是用當下時間重新確認一次——等於在使用者早就離開的上車站重開認定視窗,會把此刻剛好在那一站的車當成他搭的車。現在恢復時車輛維持未知,等手機定位來認。aRidePickedBackUpDoesNotAdoptTheBusNowAtTheBoardingStop,service 層是 boardingWithoutADestinationAsksForOneAndPicksTheRideBackUp 新增的斷言。

把修正改回去確認測試會紅(6 個都紅):

改回去的內容 變紅的測試
在站證據改回看收到時間 aLaterBusCallingAtTheStop…
在站證據不限 90 秒 atStopEvidenceMustBeFromTheNinetySecondsBeforeConfirming
回答不綁被問到的車 answeringTheQuestion…、aValidNamedDeparture…
問題不會失效 aQuestionThatHasLapsedNamesNoBus
離站不看回報間隔 aVehicleBackAfterALongSilence…
恢復行程時重新確認 boardingWithoutADestination…(拿到 NEXT-BUS)

改動到的既有測試(請確認這些預期的改變你同意):

  • anUnknownRideWaitsForItsActualBoardingBus、lateIdentificationExpires…、service 的 manualBoardingWaitsForTheActualBus…:原本是「確認之後才出現在站上的車」被認定,這正是這則 comment 指出的行為;改成「確認前就在站上、回報晚到」。
  • 移除 anIdentifiedDepartureStillHasAnUpperDistanceBound 與 anExpiredDepartureQuestionCannotDisambiguateFreshVehicles,由上面兩個關於問題的測試取代。
  • service 測試的車輛回報時間改用目前時間(原本寫死 2023 年的時間戳,現在會被判定為太舊)。

取捨與已知限制:

  • 沒有手機定位、實際搭的車也沒有 feed 時,行程會維持「已上車、車輛未知」,不會有到站提醒。這是刻意選的失敗方式:不提醒,好過跟著別的車誤報過站並暫停行程。
  • 手機時鐘與車機時鐘的誤差沒有留容許值。如果使用者在車還沒回報在站定位前就按下確認,那筆之後的定位不算數。
  • 本機 Android 單元測試 161 個全過;CI 不跑這組測試。這輪沒動 Dart。

The review's finding, and what a pass over the same code turned up.

- Confirming by hand could adopt a bus that called at the boarding stop
  afterwards. The at-stop fix that identifies a vehicle must now have
  been made, by the vehicle's clock, in the ninety seconds up to the
  confirmation; the report carrying it may still arrive later.
- Answering the question about a named departure follows that bus. It
  used to be held to the 250 m bound, which a bus has nearly always
  passed by the time the question is shown, so the answer named nothing.
  A question that has lapsed names nothing either.
- A vehicle last seen short of the stop and next seen past it more than
  three minutes later did not just leave: no departure, no question.
- A ride picked back up after choosing a destination was confirmed again
  at that moment, opening identification at a stop the rider had left
  minutes before. It now resumes with the vehicle unknown until the
  rider's own position finds it.
- latestLocation and appInForeground are read off the main thread and
  are now volatile.

Service tests stamp vehicle reports with the current time, as the feed
does. All 161 Android unit tests pass; each fix fails its test when
reverted.

@Av1anJay Av1anJay left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Review summary — changes requested

The new named-departure shortcut also applies to the independent, always-available manual boarding action, so it can lock an unrelated departed bus. See inline finding.

Checks: git diff --check passed; npm run test:web passed (3/3). Local npm run test:node failed because the host's Node 22.23.1 is rejected by the project's version guard. GitHub Actions Verify passed, including patched-Node runtime checks, Flutter analysis/tests and the Web geometry test; Web and Linux builds passed, and the other builds were still running when checked. Android unit tests could not be run locally because Flutter and the generated Android Gradle wrapper are absent; the CI Verify job does not run those unit tests.

// up to the stop and leaving it, and "yes" is the rider's answer to
// exactly that. Nothing seen afterwards can be tied to the ride as
// firmly, however near the stop it is.
val askedAbout = pendingCheckVehicleId.takeIf {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Blocking — the generic manual action can lock the wrong bus. confirmBoardedByUser treats any pending departure as the bus the rider explicitly answered about, but the persistent tracking notification's independent 我已上車 action and the boarding-question action both call this same method. For example, bus A leaves and creates a pending check; before its 40-second prompt is even shown, the rider boards bus B (which has no position feed) and taps the persistent manual action. askedAbout is A, so with no usable phone fix A is permanently followed, potentially triggering false destination/overshoot alerts and pausing the real trip. Pass the question identity/action source separately and only adopt its named bus when the user actually answers that still-current question; the generic action must not use an unseen pending check. Please add a regression test for a manual confirmation before the prompt with a different bus pending.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

已在 4fb8c82 修正,作法照你說的:把「回答的是哪一個問題」另外傳進來。

  • 「你有上車嗎?」通知自己的兩個按鈕,PendingIntent 現在帶著該問題的 boardingCheckId(另外的 request code,不會跟常駐通知的按鈕共用同一個 PendingIntent)。常駐通知(以及 Hyper island)的「我已上車」不帶任何 id。
  • confirmBoardedByUser(nowMs, answeredCheckId):只有 answeredCheckId 等於目前仍待回答的問題時,才採用該問題指名的車。沒帶 id、或帶的是已經被取代的舊問題 id,都不指名任何車。

你的情境寫成 confirmingUnpromptedDoesNotAdoptABusAboutToBeAskedAbout(A 離站產生待問、提示還沒顯示、使用者按常駐按鈕 → 車輛未知,A 之後開過目的地也不會有 passedDestinationByStops),service 層是 onlyTheQuestionsOwnButtonsAnswerTheQuestion:實際從貼出的通知取出按鈕的 intent 送回 service,常駐按鈕 → 未知;問題按鈕 → BUS-A;並確認顯示問題後常駐按鈕的 intent 仍不帶 id。

照你的情境實測時發現光這樣不夠,所以多修了一處:拿掉 askedAbout 之後,A 還是被選中——走的是另一條路:A 30 秒前在站上、現在在 250 m 內,符合「未被詢問時的在站證據」。所以再加一條:使用者確認之前就已經被看到駛離(超過離站門檻 120 m)的車,不能用先前的在站定位來認定;那種情況只有回答問題才算。車到目前為止回報都還在站上的,仍然認定(aBusStillAtTheStopWhenTheRiderConfirmsIsTheirs)。

同一類、順手修掉的:舊問題的通知還在畫面上時,新的離站已經變成待問(新通知要 40 秒後才貼出)。這時按舊通知的「還沒上車」,原本會把新問題那輛車排除掉。現在對已被取代的問題回答「還沒上車」不影響新問題。anAnswerToAQuestionSinceReplacedNamesNoBus 涵蓋「已上車/還沒上車」兩種回答。

把修正改回去確認測試會紅(5 個都紅):

改回去的內容 變紅的測試
任何確認都採用待問的車(你回報的行為) confirmingUnprompted… ×2、anAnswerToAQuestionSinceReplaced…、service 測試
未被詢問時可採用已駛離的車 confirmingUnpromptedDoesNotAdopt…、anAnswerToAQuestionSinceReplaced…
舊問題的「還沒上車」照樣生效 anAnswerToAQuestionSinceReplaced…
問題按鈕不帶 id service 測試(拿不到 BUS-A)
兩種按鈕共用 request code service 測試(常駐按鈕變成帶 id)

改動到的既有測試:aRecentBoundedDepartureCanBeIdentified(車已開到 200 m 才按常駐確認 → 認定)與新規則相反,改成 aBusStillAtTheStopWhenTheRiderConfirmsIsTheirs。

取捨:使用者真的搭上 A、但在 A 被看到駛離之後、問題顯示之前按了常駐按鈕,現在會是「已上車、車輛未知」,要靠手機定位才有到站提醒。這是往保守的方向錯。

本機 Android 單元測試 166 個全過;CI 不跑這組。這輪沒動 Dart。

"I have boarded" is always on offer on the tracking notification, and a
question about a bus that just left can be pending for 40 s before it is
shown. Confirming unprompted in that window adopted the pending bus,
though the rider had not been asked about it and could be on another.

- The boarding question's own buttons now carry the id of the question
  they answer, on PendingIntents of their own; the tracking
  notification's button carries none. The named bus is adopted only when
  the answer is to the question still pending.
- Unprompted, a bus already seen pulling away before the rider confirmed
  is not adopted from its earlier fix at the stop either: whether they
  were on it is what the question is for. A bus still standing at the
  stop, as far as the feed has said, still is.
- "Not yet" to a question since replaced by another no longer sets aside
  the bus the new question is about.

All 166 Android unit tests pass; each change fails a test when reverted.

@Av1anJay Av1anJay left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Review summary — changes requested

A 90-second deduplication rule conflates two distinct buses and can associate a boarding answer with the wrong vehicle, leading to false destination/overshoot alerts. Details are in the inline finding.

Checks: git diff --check passed. With Node 24.22.1, npm run test:node and npm run test:web passed (3 tests each); the host's default Node 22.23.1 is rejected by the version guard. GitHub Actions Verify (Flutter analysis/tests and Web geometry) and Android, Wear OS, Linux, Web, Windows, iOS and macOS builds passed. Android unit tests could not be run locally: Flutter and the generated Gradle wrapper are absent; the CI workflow does not run those Android tests. An attempt to compile a small pure-Kotlin reproduction timed out, so this finding is based on code inspection rather than a successful local reproduction.

// A different vehicle this close behind is a second bus, and gets
// a question of its own.
}
if (pendingCheckSinceMs != 0L && nowMs - pendingCheckSinceMs < DEPARTURE_DEDUPE_MS) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Blocking — distinct buses leaving within 90 seconds are treated as one departure. If A and B are both seen at the stop, A leaves first, and B leaves 40 seconds later, registerDeparture(B, ...) enters this branch and keeps the pending question's pendingCheckVehicleId as A (the Elvis assignment only fills null). The prompt shown after B departs still carries A's check ID; a rider who boarded B and answers yes is permanently associated with A. With no usable phone location, A's subsequent progress can generate false destination/overshoot alerts and pause the trip. Deduplicate only observations that can be tied to the same departure; preserve/queue or replace the question when two known vehicle IDs differ, and add a regression test for two buses departing within the dedupe window and the rider boarding the second.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

已在 8901d97 修正。

問題本身:90 秒內的離站回報原本不管是哪輛車都當成同一次離站,所以 A、B 先後離站時,問題一直指著 A。現在「同一次離站」只在能對得上的時候才合併:

  • 位置 feed(有車號)與 ETA 跳號(沒車號)各一筆 → 同一次離站。
  • 同一輛車再被回報一次(定位飄回站上又離開)→ 同一次離站。
  • 兩輛不同的車 → 兩次離站,間隔多短都一樣。第二次 ETA 跳號也算另一輛。

為什麼是「兩輛都記著」而不是把問題換成 B:你給的兩個選項(preserve/queue 或 replace)我選了前者。通知上只寫「公車剛剛離站了」,使用者不知道車號,所以 A、B 都離站之後的「我已上車」對兩輛都成立。換成 B,你的情境(搭 B)會對,但搭 A 的人回答同一個問題就會被鎖到 B。所以現在:

  • 「我已上車」只有在問題存續期間恰好一輛離站、位置 feed 有給車號、而且當下沒有別的車在使用者可能上車的位置時,才指名那輛車。否則維持「已上車、車輛未知」。
  • 「還沒上車」把這段期間離站的車全部排除(還在等車的人不在其中任何一輛上)。
  • 第二輛在上次發問 90 秒內離站 → 併入同一個問題(同一個 id,不重複跳通知);超過 90 秒 → 重新發問(新 id),但仍涵蓋 5 分鐘內還沒被回答的離站。重新發問跟第一次發問一樣,要求使用者最近在站牌附近。

你要求的回歸測試:twoBusesLeavingCloseTogetherAreNotOneDeparture(A、B 同在站上,A 先走、B 40 秒後走,使用者搭 B 回答「我已上車」→ 車輛未知;A 之後開過目的地也不會有 passedDestinationByStops)。service 層是 theAnswerAfterTwoBusesLeftCloseTogetherFollowsNeither,實際按問題通知上的按鈕,並確認沒有設定到站基準、沒有暫停行程。

我自己重審這段時另外找到、一併修掉的(都是「可能跟錯車」的同類問題):

  1. 只有一輛離站,但站上已經有另一輛:A 走了、B 進站,使用者上了 B 才回答「我已上車」,原本會指名 A。現在只要有另一輛車在站上、剛離站 250 m 內、或在站前 300 m 內(回報大約落後半分鐘,這個距離內的車可能已經進站),就不指名。aBusTheRiderCouldHaveBoardedSinceLeavesTheAnswerOpen。
  2. 常駐按鈕也有同樣的問題:A 已離站還沒被回答、B 停在站上,使用者按常駐的「我已上車」,原本會認定 B,但他也可能在 A 上。現在有未回答的離站時,常駐確認不認定站上的車(unpromptedTheBusAtTheStopIsNotAdoptedWhileOneThatLeftIsUnanswered);站牌附近有第二輛車時也不認定(unpromptedASecondBusNearTheStopLeavesTheRideUnidentified)。
  3. 回答與 snapshot 的先後:離站是在 snapshot() 裡才計數的。service 套用新回報與重算 snapshot 是兩個分開的鎖區塊,使用者的回答可能剛好插在中間,那時第二輛車已經回報離站卻還沒被算進去。現在回答(確認與拒絕)會先依目前收到的回報把離站補算完。aSecondBusAlreadyReportedGoneCountsBeforeAnySnapshotIsTaken。
  4. 手動確認不再清掉先前的「還沒上車」:原本 confirmBoardedByUser 會 rejectedAt.clear()。這樣一來,剛被拒絕、還卡在站牌前方的 A 會被當成「可能上車的另一輛」,使用者接著上 B 並按確認時反而認不到 B。現在保留拒絕紀錄。unpromptedABusAlreadyTurnedDownDoesNotLeaveTheRideUnidentified(含 B 的在站回報晚到的情況)。

把每條規則改回去確認測試會紅(19 個全紅,以下是代表性的幾個):

改回去的內容 變紅的測試
你回報的行為(不同車也併成同一次離站) twoBusesLeavingCloseTogether…、notYetSetsAsideEveryBus…、aSecondBusAlreadyReportedGone…,service 測試拿到 BUS-A
多輛離站時取第一輛 twoBusesLeavingCloseTogether…、theEtaCatchingUp…,service 測試拿到 BUS-A
回答時不看站上有沒有別的車 aBusTheRiderCouldHaveBoardedSince…
常駐確認不看未回答的離站 unpromptedTheBusAtTheStopIsNotAdopted…
「還沒上車」只排除第一輛 notYetSetsAsideEveryBusThatHasLeft
ETA 補報算成第二輛/第二次跳號被吞掉 theEtaCatchingUpWithABusAlreadySeenLeavingIsNotASecondBus(兩個方向各一)
同一輛車離站兩次算兩輛 aBusSeenLeavingTwiceIsOneDeparture
永不重新發問/每次都重新發問/不管人在不在站牌都重新發問 anAnswerToAQuestionSinceReplaced…/twoBusesLeavingCloseTogether…/aRiderNoLongerAtTheStopIsNotAskedAfresh
確認時清掉拒絕紀錄 unpromptedABusAlreadyTurnedDown…
回答時不先補算離站 aSecondBusAlreadyReportedGone…(確認與拒絕各一)

關於 service 測試,有一點要講清楚:這個測試的第一版在 bug 還在的時候也會通過。原因是 service 讀的是 JVM 真實時鐘,而測試把車機時間每步往後加 20 秒,車機時間跑到手機時鐘前面,B 被當成「還在站上」,結果碰巧一樣。現在這個測試把回報時間戳放在現在之前的一分鐘內,用你回報的行為驗證過會失敗(拿到 BUS-A)。其他既有的 service 測試仍有車機時間超前的寫法,它們斷言的內容不依賴這個比較,這輪沒有動。

改動到的既有測試(請確認這些預期的改變你同意):

  • 移除 aValidNamedDepartureCanDisambiguateNearbyVehicles:它的預期是「A 已離站、另一輛車停在站上時回答,指名 A」,跟上面第 1 點相反,由 aBusTheRiderCouldHaveBoardedSinceLeavesTheAnswerOpen 取代。
  • answeringTheQuestionAboutANamedBusFollowsThatBus:同樣原因,拿掉了回答當下停在站上的另一輛車,只留「恰好一輛離站」的情況。
  • anAnswerToAQuestionSinceReplacedNamesNoBus 的後半:新問題現在涵蓋 A、B 兩輛,所以對新問題回答「我已上車」也是未知。
  • aQuestionThatHasLapsedNamesNoBus:多放了一輛停在站上的車,確認對過期問題的回答不會改去認定站上的車。
  • aLateFamilyVariantIsFetchedWithoutRefetchingTheFreshPrimary:車機時間改成固定在確認之前。原本用的是回應當下的時間,確認與回應跨到不同秒時會偶發失敗。

取捨與已知限制:

  • 這輪每一條規則都往「不指名」的方向收。沒有手機定位時,班次密的路線會更常落在「已上車、車輛未知」,那種情況不會有靠公車位置的到站提醒;有手機定位時不受影響(進度用使用者自己的位置)。
  • 「站前 300 m」是依回報延遲估的距離,不是保證:回報延遲特別久時,更遠的車也可能已經進站。
  • 常駐確認當下只看已收到的回報。確認後才送達、顯示當時站牌附近還有另一輛車的回報,不會把已經認定的車撤銷。
  • ETA 跳號與一輛有車號的離站在 90 秒內仍視為同一次離站;如果它們其實是兩輛(其中一輛沒有位置 feed),會指名有車號的那輛。
  • 本機 Android 單元測試 178 個全過;CI 不跑這組。這輪只動 TripRideDetector.kt 與測試,沒有動 service 與 Dart。

A departure within ninety seconds of the pending question was taken for
the same bus whichever vehicle it was. Two buses leaving close together
left the question naming the first, and "yes" from a rider on the second
followed the wrong bus.

- Two reports are one departure only when they can be: one from the
  position feed and one from the ETA rolling over, or the same vehicle
  again. A different vehicle is another bus, and joins what the question
  is about. Ninety seconds or more after the last time of asking, a
  rider still at the stop is asked afresh.
- "Yes" names a bus only when exactly one has left while the question
  stood, the position feed named it, and no other bus is where the rider
  could have boarded it since. "Not yet" sets aside every bus that left.
- Unprompted, the bus at the stop is adopted only when it is the only
  one there and no bus that has left is still unanswered for.
- An answer is read against the reports received so far rather than the
  last snapshot, and a manual confirmation no longer forgets the buses
  the rider turned down.

The new service test stamps its vehicle reports in the past: the service
reads the JVM wall clock, and reports dated ahead of it hid the bug.
All 178 Android unit tests pass; each rule fails a test when reverted.

@Av1anJay Av1anJay left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Review summary — changes requested

Two remaining ETA/GPS reconciliation cases can either attach a rider to the wrong bus or suppress the next bus's boarding question. See inline findings.

Checks: git diff --check passed. With Node 24.22.1, npm run test:node and npm run test:web passed (3 tests each). GitHub Actions for this exact head passed Verify (Node, Flutter analysis/tests and Chrome geometry) and Android, Wear OS, Linux, Web, Windows, iOS and macOS builds. Local Android unit tests could not run: Flutter and the generated Gradle wrapper are unavailable; CI Verify does not run them. An attempt to compile a small pure-Kotlin reproduction timed out, so the findings are based on code inspection, not a successful reproduction.

val recent = pendingDepartures.filter { nowMs - it.atMs < DEPARTURE_DEDUPE_MS }
if (vehicleId == null) {
// The ETA's account of a bus the position feed has reported.
val unreported = recent.firstOrNull { !it.reportedByEta } ?: return false

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Blocking — an ETA-only second bus is identified as the first GPS bus. A is seen at the stop and leaving, creating a named departure. If a distinct B has no usable position feed, arrives and causes the ETA to roll over within 90 seconds, this branch sets reportedByEta on A instead of recording B; the feeds provide no evidence that the rollover was A rather than B. With no usable phone fix or B vehicle report, the rider can board B and answer the prompt, and busTheQuestionIsAbout returns A as the only departure. A's subsequent progress can then trigger false destination/overshoot alerts and pause the trip. I see the author has noted this limitation; please keep the identity ambiguous unless the two reports can actually be correlated (or otherwise preserve the possibility of two buses), and add a test with GPS-only A followed by ETA-only B and the rider boarding B.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

已在 514d9c0 修正。

不再把沒有車號的 ETA 跳號當成有位置回報的那輛車。 位置 feed 回報 A 離站後 90 秒內出現一次沒有車號的跳號時:仍然只問一次(最常見的情況確實是同一輛),但這次離站會被標成「可能是兩輛」,busTheQuestionIsAbout 對它不指名任何車。順序反過來(先跳號、後來位置 feed 才回報 A 離站)也一樣。

能對應的時候才對應。 你提到「unless the two reports can actually be correlated」——站牌 feed 其實常常有這個資訊:站上的車(buses,或 ETA ≤ 0 的那筆的車牌)。現在 feedBoardingEta 會把「站上唯一的那輛車」一起傳給 onBoardingStopEta,跳號時就帶著那個車牌登記離站:

  • 車牌與位置 feed 的離站相同 → 同一次離站,回答可以指名。
  • 車牌不同 → 另一輛車,問題涵蓋兩輛,回答不指名。
  • 站牌 feed 沒給車牌 → 無從對應,回答不指名。

測試:aRolloverBesideABusSeenLeavingIsThatBusOnlyWhenTheFeedSaysSo(你要的「GPS 的 A 之後 ETA 的 B、使用者搭 B」是其中 atStop = null 與 atStop = "BUS-B" 兩種,都是車輛未知;atStop = A 才指名 A)、aBusSeenLeavingBesideAnUnnamedRolloverIsNotNamedByTheAnswer(反過來的順序)、service 層 theBusTheStopFeedPlacesAtTheStopIsTheOneItsRolloverReports(車牌確實從站牌 feed 傳到 detector)。

改回去確認會紅:拿掉任一方向的「可能是兩輛」標記、回答時不看該標記、detector 丟掉車牌、service 不傳車牌——5 個都紅。

取捨:站牌 feed 不帶車牌的地方,只要位置 feed 的離站旁邊有一次跳號,回答「我已上車」就不會指名車輛,沒有手機定位時就沒有靠公車位置的到站提醒。這是照你要求的方向收的。

本機 Android 單元測試 183 個全過;CI 不跑這組。

declinedDepartures.removeAll { nowMs - it.atMs >= DEPARTURE_DEDUPE_MS }
if (vehicleId == null) {
// The ETA catching up with what the rider has just answered for.
return declinedDepartures.isNotEmpty() ||

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Blocking — declining an ETA-only departure can swallow the next ETA-only departure. When A is reported only by ETA and the rider answers 還沒上車, declinedDepartures contains A with reportedByEta=true. If another bus B, also without usable GPS, arrives and its ETA rolls over within 90 seconds of A, this branch drops B merely because declinedDepartures is nonempty, even though the earlier ETA report cannot be its own second-feed echo. No new question is raised, so with no usable phone location there is no automatic way to confirm B. Only suppress an ETA echo for a declined departure that has not already been reported by ETA, consuming that echo once, and add a regression test for two ETA-only rollovers separated by a decline.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

已在 514d9c0 修正,照你說的:每個被拒絕的離站只抵銷一次 ETA 補報。

  • 沒有車號的跳號只會被「還沒被 ETA 回報過」的已拒絕離站吸收,吸收後該離站標成已回報。ETA 自己回報的離站(reportedByEta = true)不會再吸收下一次跳號,所以第二輛只有 ETA 的車會被問到。
  • 拒絕的是「偵測到的乘車」(沒有問題)時,同樣只抵銷一次。
  • 帶車牌的跳號如果是已拒絕的那輛,會把那次離站標成已回報,之後沒車號的跳號就不會被誤吸收。

你要的回歸測試:eachDeclinedBusIsCaughtUpWithByTheEtaOnce,兩段:(1) 兩次只有 ETA 的跳號、中間一次「還沒上車」→ 第二次會被問;(2) 位置 feed 看到離站的車被拒絕 → 它自己的跳號被吸收、下一次跳號會被問。

同一段裡我另外修掉的相鄰問題:只有 ETA 的離站被拒絕後,90 秒內第一輛被位置 feed 回報離站的車,原本一律當成「那輛車現在有車號了」並排除 20 分鐘。如果那其實是後面的車,使用者搭上去也不會被問、也不會被 co-movement 偵測到。現在只有在那輛車的位置回報沒有顯示它「跳號之後還在站上」時才這樣合併;跳號之後還在站上的就是下一輛,照常發問。aBusStillAtTheStopAfterADeclinedRolloverIsTheNextBus(兩種情況各一)。同一個判斷也用在還沒回答的問題上。

改回去確認會紅:任何跳號都被吸收、吸收後不標記、合併時不看是否還在站上——3 個都紅。

已知限制:後面那輛車如果進站又離站之間沒有任何一筆在站上的位置回報(回報間隔約 20 秒),仍會被當成同一輛而排除。

Two review findings about reconciling the ETA feed with the position
feed.

- A rollover naming no bus, within ninety seconds of a departure the
  position feed reported, was taken for that bus. It may as well be a
  second bus with no position feed, so the pair is still asked about
  once but an answer no longer names the bus that has a plate. The same
  holds in the other order.
- The stop feed often says which bus is standing at the stop. That plate
  now travels with the rollover, which is the evidence that does tie it
  to a vehicle: the same plate is the same departure, another plate is
  another bus.
- After "not yet", each declined bus absorbs one ETA rollover, not every
  rollover in the window: the next bus without a position feed is asked
  about. A bus the position feed shows still at the stop after a
  declined rollover is the next bus too, not that one named late.

All 183 Android unit tests pass; each rule fails a test when reverted.

@Av1anJay Av1anJay left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Review summary — changes requested

A previously unique ETA vehicle remains named after later stop-feed updates make its identity ambiguous; an answer can therefore follow the wrong bus and produce false destination alerts. See the inline finding.

Checks: git diff --check passed; Node 22.23.4 npm run test:node and npm run test:web each passed 3/3. GitHub Actions Verify (Flutter analysis/tests and Web geometry) and Android, Wear OS, Linux, Web, Windows, iOS and macOS builds passed. Android unit tests were not run locally: Flutter and the generated Android Gradle wrapper are unavailable, and CI Verify does not run them. Compiling a small pure-Kotlin reproduction timed out; the finding is based on code inspection, not a successful local reproduction.

// Where the stop feed says which bus is standing there, the
// rollover that follows is that bus leaving — the one thing that
// ties an ETA departure to a vehicle.
if (arrivingVehicleId != null) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Blocking — a formerly unique plate survives an ambiguous stop update. Suppose the stop feed first reports only A at the stop, then reports both A and B while still arriving. feedBoardingEta passes null on the second update because singleOrNull() fails, but this branch leaves etaArrivingVehicleId set to A. When the ETA rolls over, it registers A as the sole departed bus even if B is the one that left. A rider who boarded B and answers the prompt can therefore be attached to A, whose progress can trigger false destination/overshoot alerts and pause the trip. Preserve ambiguity when the current arriving update cannot uniquely identify the vehicle (distinguish an ambiguous list from a missing plate if needed), and add a test for unique A → A and B together → B leaves/ETA rolls over, with no phone fix.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

已在 bd52f8c 修正。

原因如你所說:service 只在站上恰好一輛時才傳車牌,兩輛時傳 null,而 detector 把 null 當成「這次沒資訊」,所以先前單獨出現的 A 留了下來。

現在把判斷移到 detector,照你建議區分「清單有歧義」與「沒有車牌」:

  • feedBoardingEta 把站牌 feed 放在站上的車全部傳過去(arrivingVehicleIds),不再自己取 singleOrNull()。
  • detector 累積「ETA 歸零以來出現在站上的所有車」,跳號時只有從頭到尾只有一輛才用它的車牌登記離站;否則登記成沒有車號的離站,回答不指名。
  • 沒帶任何車牌的更新不改變已知的集合(「沒資訊」不等於「有歧義」)。

測試:

  • aPlateNoLongerAloneAtTheStopDoesNotNameTheRollover(沒有手機定位、沒有位置 feed):你的情境 A → A 與 B 同時 → 跳號 → 回答「我已上車」→ 車輛未知。另外涵蓋 A → 只剩 B → 跳號(A 沒被回報就走了,使用者也可能在 A 上)→ 未知;A → A、A → 無車牌 → 仍指名 A。
  • service 層 twoBusesTheStopFeedPlacesAtTheStopLeaveItsRolloverUnnamed:用站牌 feed 的 buses 走完整流程並按問題通知的按鈕。
  • theNextArrivalStartsWithNoPlatesFromTheLast:上一班的車牌不會帶到下一班。

把修正改回去:

改回去的內容 結果
service 只傳單獨一輛的車牌(你回報的行為) service 測試紅
detector 只保留最近一次更新的車牌 aPlateNoLongerAlone… 紅
多輛時取第一輛 兩個測試都紅
跳號時不清空集合 沒有測試變紅——下一次進站時本來就會清空(etaArrivingAtMs == 0L),所以這一行是多餘的保險,不是有測試保護的行為

取捨:同一次「進站中」期間只要站牌 feed 曾經列出第二輛車,這次離站就不指名,即使第二輛其實還沒走。

本機 Android 單元測試 187 個全過;CI 不跑這組。

… stop

The service handed the detector a plate only when the stop feed placed
exactly one bus at the stop, and nothing when it placed two. The plate
from an earlier update, when a bus stood there alone, was left standing,
so the rollover was registered as that bus leaving though either could
have left.

The service now passes every bus the feed places at the stop, and the
detector names the rollover only if one vehicle alone has been there
since the ETA last reached zero. A second bus beside it, or one that
replaced it, leaves the departure unnamed.

All 187 Android unit tests pass.

@Av1anJay Av1anJay left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Consolidated full-scope review — changes requested

This updates the existing review for the same commit, rather than starting another Request Changes round. The earlier review was incomplete; the author should not have had to discover this audit in one-or-two-issue installments.

Revision: bd52f8ce1dba4f3246134063b2c4e745faeebe4d, base 6c6c8d74719e8efe01a99c12b286c2ae8a8f1bad.

Scope: all 28 changed files and affected Kotlin detector/geometry/service, Flutter bridge/UI, identifiers, notification launches, family feed contracts, persistence, lifecycle, asynchronous request/answer paths and tests; three read-only reviewers, adversarial second pass, then parent reconciliation. The independent contract audit's three detector findings duplicate D1–D3 and are merged, not counted again. The family read-before-handoff race candidate was not established as a new regression over base and is not promoted to a blocker.

Result: 17 newly consolidated findings (8 P1, 9 P2), plus the previously reported still-open arrival-contract issue below. Each item states its evidence; “executed” refers only to the unchanged production JVM classes, never to a device notification/service run. P1 = incorrect/missed ride reminders or user-action/state corruption; P2 = conditional correctness, fallback, latency or display failure, not a style request.

Previously reported issue still open

  • Original finding: future buses entries are not at-stop vehicles. Native busesAtStop and foreground bridge still copy future vehicles, keeping arrival true and contaminating departure identity. The older ETA-entry-membership fix is present, but its replacement incorrectly assumes buses has physical-arrival semantics. This is the same existing blocker, not an additional new finding. A fresh read-only sample during consolidation again has positive ETA and is_arriving:false for a plate in buses.

New findings — complete consolidated list

D1 · [P1] A negative answer immediately reboards under another bus

Location: TripRideDetector.kt:557–561. Evidence: executed_production_JVM.

With buses A/B matching the same phone track at t=0/20/40/60 (5 m/s), production first boards A. declineBoarding(t=61) then snapshot(t=61), without any new fix/report, immediately returns hasBoarded=true, BUS_CO_MOVEMENT, vehicle B. The service performs exactly this decline→snapshot sequence. Co-movement ignores lastDeclineAtMs and reuses the evidence the rider just rejected; self-progress already has a boundary. Require post-decline evidence, including interpolation endpoints, rather than merely excluding A. Base cleared movement/confirmation history. This is not the older fixed issue that disabled detection for every later bus.

D2 · [P1] A GPS gap switches an established ride to the next bus

Location: TripRideDetector.kt:918–927. Evidence: executed_production_JVM.

Confirm A with phone/A at the boarding stop at t=0. Stop phone updates. At t=60 report A 700 m down-route and B at the stop: the still-usable old phone fix rejects locked A and chooses B. At t=100 the expired-fix branch preserves B and uses its progress. Normally delayed bus GPS also reproduces it. Compare time-aligned observations or preserve identity through a phone gap: the old coordinate is not fresh evidence against A. The outage test lacks a retained usable phone fix and misses this intermediate-age branch. Base retained an identified plate still present in the live stop feed.

D3 · [P1] Off-route phone movement confirms boarding in both detection layers

Location: TripRideDetector.kt:180–189. Evidence: executed_production_JVM.

Move the phone north at 5 m/s on a parallel road 3 km east of a straight northbound route. With an on-route bus at matching northings t=0/20/40, production returns BUS_CO_MOVEMENT; without a bus feed, phone fixes every 20 seconds return SELF_PROGRESS at t=100. Both have hasBoarded=true and hasRouteValidProgress=false. Recording the phone projection discards cross-track distance, and neither co-movement (540–561) nor the self-progress origin check (632–643) validates geographic origin/route. With no destination the service can announce boarding and pause for destination setup on an unrelated journey. Retain/check phone geographic evidence in both layers. The no-feed self-progress false-positive path is new; base required an arrival/departure window.

D4 · [P1] The hint traps forward travel on the outbound leg of a hairpin

Location: RideRouteLine.kt:83–90. Evidence: executed_production_JVM.

Use metre coordinates (x,y): (0,0),(0,1000),(40,1000),(40,500),(40,0),(500,0), boarding 1/destination 6. Feed the first five stops at t=0/100/104/154/204, at plausible speeds. Actual remainingStops is 5→4→4→5→5. Phone-only fixes reproduce the same reversal. At the turn the outbound endpoint is within 60 m slack and closest to the old along hint; later exact return-leg fixes perpetually select the outbound leg. Add segment/direction continuity or a turn-transition rule. Base nearest-stop fallback chooses the actual return-leg stops. This is independent of the inconsistent projection tuple in D9.

D5 · [P2] Exact timestamp matches are rejected as interpolation gaps

Location: TripRideDetector.kt:1035–1048. Evidence: executed_production_JVM.

With 200 m stop spacing, feed bus and phone at exactly t=0/40/80, y=0/200/400 m. Actual snapshot(t=80) stays unboarded; adding only phone samples t=20/60 produces BUS_CO_MOVEMENT. userAlongAt rejects the previous-to-current span over 30 seconds even when the requested timestamp equals the current measured sample and no interpolation is needed. Return exact matches before the gap limit. This is a defect in the new matcher, not a claim that base had timestamp-aligned co-movement. The 500 m self-progress threshold is not reached here.

D6 · [P1] An ETA-only alternative does not make vehicle confirmation ambiguous

Location: TripRideDetector.kt:1009–1017. Evidence: executed_production_JVM.

No phone: GPS A leaves at t=20 and creates q. At t=65 feed an accurate arriving ETA naming B at the boarding stop, with no GPS for B. Rider boards B and answers q at t=70: production selects A; A can then drive false overshoot. An unprompted confirmation with accurate at-stop list [A,B] and GPS only for A also selects A. anotherBusIsBoardable consults only busTracks, ignoring etaArrivingVehicles at line 251. Include fresh ETA alternatives in question/manual identity checks (338–348,988–999). No bad buses parsing is required: B is accurately known at-stop and has not departed or rolled over, unlike the previously fixed two-departure cases.

D7 · [P2] Generic confirmation reselects a still-rejected vehicle

Location: TripRideDetector.kt:923–927. Evidence: executed_production_JVM.

Decline A’s departure question at t=65. At t=70 give a phone fix at the boarding stop and A at 200 m; rider boards B with no GPS and presses generic I-have-boarded at t=75. Actual trackedVehicleId=A despite its live rejectedAt entry. When phone fixes expire, A drives progress. resolveTrackedVehicle and manual candidates (963–987) omit isRejected. Allow positive confirmation, but keep identity unknown rather than assuming it explicitly selects A’s plate. This differs from D1: a later positive action occurs here; D1 immediately overrides the negative answer with no action/input. It violates the PR’s new retained per-vehicle rejection contract, not a matching base feature.

D8 · [P1] An impossible on-route bus jump supplies valid overshoot progress

Location: TripRideDetector.kt:196–222. Evidence: executed_production_JVM.

No phone: identify A at y=0/t=0, then report y=2000/t=20 on-route (100 m/s). Production yields remainingStops=0, passedDestinationByStops=1, hasRouteValidProgress=true; it remains valid at t=65/80 without a correction. The service’s 45-second overshoot timer can pause the trip. Phone fixes have a 55 m/s jump guard; bus samples have no physical jump quarantine. Reject/corroborate implausible vehicle steps before exposing arrival progress. The recorded TXG300 fixture contains a ~169.6 m/s pair, but that actual pair is off-route and rejected: the triggering on-route probe is synthetic, not a claimed recorded alarm. Bus-only progress is new; notifications were statically traced, not Android-executed.

D9 · [P2] Projection combines one segment’s position with another segment’s distance

Location: RideRouteLine.kt:93. Evidence: executed_production_JVM.

Returns alongs[chosen]/chosen but distances[closest]. Stops (0,0),(0,1000),(50,200),(50,0), hint 0, point (640,100) yield along≈100/segment0/distance≈590. Segment0 is actually 640 m away; 590 belongs to segment2. The detector’s selected-segment-dependent limit is 600 m, so the mixed tuple falsely passes. All actual segment distance/limit pairs fail (640/600,598.41/480.94,590/150), yet production hasRouteValidProgress=true. Return distances[chosen]. This is new geometry code, independent of D4’s turn policy.

S1 · [P2] Family GPS can infer arrival at a platform the variant never serves

Location: RouteTripMonitorService.kt:861–863. Evidence: live_topology_plus_static_trace.

Select 500/TXG5000 direction1/destination25054 臺中國際機場2月台; confirm 500延/TXG5002 at a shared stop and lose phone fixes. Vehicle merge drops originating route identity and projects onto the primary geometry. Live direction1 variant serves 13448→14199→25056 臺中國際機場(中航路), never25054; these positions project to 2→1→0 remaining on the primary. 25056 projects to the terminal ~71 m off-line, within acceptance, so arrival starts at the wrong platform. Family stop-map matching refuses this destination mapping (different ID/name, >60 m), but GPS bypasses it. Preserve originating route/served-destination coverage. Parent independently fetched both topologies; the scenario is a controlled replay/source trace, not a recorded ride. This concerns the new family-GPS fallback.

S2 · [P1] Retired boarding actions can confirm or undo a different trip

Location: RouteTripMonitorService.kt:199–200. Evidence: executed_detector_boundary_plus_static_Android_trace.

Queue question-A’s intent, switch route/direction to B, then deliver A’s original intent. No trip/question ownership guard precedes mutation. Parent executed the current detector: unmatched old YES boards B; old NO while B is boarded erases B’s ride. Service also resets alerts/cancels prompts for irrelevant NO (217–225). All prompted answers reuse request407/408 and FLAG_UPDATE_CURRENT (2034–2036), so retained PendingIntent tokens may alias newer questions because extras do not distinguish tokens. Scope action identity to trip/question and reject stale actions before touching detector/alerts; keep real unprompted actions separate. Detector transitions executed, Android dispatch/token behavior statically traced. Different from the fixed generic-action-vs-question ambiguity.

S3 · [P2] An explicitly non-arriving negative ETA fabricates a departure cycle

Location: RouteTripMonitorService.kt:877–889. Evidence: live_payload_plus_executed_detector_boundary.

Live TPE157463 returns eta:-1,message:"",buses:[],etas:[{plate:null,eta:-1,is_arriving:false}]. Native ingestion discards is_arriving and treats <=0 as arrival; detector also infers arrival numerically even if arriving=false. Feed that sample then eta600 with no buses: parent-executed detector raises a departure question 40 seconds later. The live payload was independently fetched; the transition is controlled, not observed on one real stop. Other negative ETAs legitimately have is_arriving:true, so dropping every negative is wrong. Preserve explicit validity/arrival semantics through DTO and detector. Independent of the old buses-array issue (empty here). Nonpositive display behavior predates PR; this detector departure inference is new.

S4 · [P2] Placeholder and display-cache snapshots are fed as fresh detector observations

Location: RouteTripMonitorService.kt:333–343. Evidence: static_cross_layer_trace.

TripMonitorStop.fromStop always emits liveData, including null placeholders or stale display ETA/message, without observed-at/provenance. Any nonempty map is timestamped fresh and immediately fed. A true eta0 followed by a same-trip topology-only null-ETA snapshot is interpreted as departure; replayed old zero renews arrival time. The screen retains old display data on errors (route_detail_screen:1079–1113); bridge drops stale plates but keeps ETA/message. Frequent foreground updates can also keep resetting the 20-second native stop-fetch clock. Carry freshness/authority and do not feed absent/replayed display state as new evidence. Static trace, not executed Flutter/service test. Only the new detector-evidence use is asserted as new; foreground caching itself predates PR. Not the fixed stale HTTP overwrite guarded by stopFeedRevision.

S5 · [P2] One slow family endpoint delays healthy-bus and local-fix progress

Location: RouteTripMonitorService.kt:833–855. Evidence: static_IO_scheduling_trace.

Return primary vehicle data promptly near destination, then hold a variant HTTP response. Healthy reports stay buffered until the entire serial loop ends; advanceRide/alerts run only after updateLiveData returns (743–762). Phone callbacks update history but queue the same single executor, so destination fixes also cannot publish during the wait. Each endpoint allows 10s connect+10s read, plus serial family stop/topology fetches, with no refresh-wide budget. Multiple slow variants can exceed the reminder window. Existing independent-backoff tests only fake immediate failures. Decouple available-report/local-timer progress from blocking fan-out and bound refresh latency. This is a source-level dependency, not an executed latency measurement/deadlock; all-family vehicle fan-out is new.

S6 · [P2] Cold destination-setup launch changes the paused boarding identity

Location: RouteTripMonitorService.kt:1983–1984. Evidence: static_notification_Flutter_resume_trace.

Board without destination using a non-first stop (or no explicit boarding stop); let destination setup pause. Tap the preserved notification without an existing matching route screen. The generic intent passes the first stop, not boardingLaunchStopId; bus_app:933–958 creates a route screen and route_detail_screen:252–257 adopts it as boardingStopId. Selecting a destination then fails continuesBoardedRide’s identity equality (service449), returning to waiting mid-ride. Preserve the exact paused identity, including unset boarding stop, through destination setup. Existing resume test resubmits original identity directly and bypasses launch. Generic first-stop fallback predates PR; this breaks the new pause/resume flow. Android/Flutter cold launch was traced, not executed.

S7 · [P2] No-fix display turns future ETA membership into a stop reached

Location: RouteTripMonitorService.kt:1100–1102. Evidence: live_feed_plus_static_display_trace.

After an identified ride loses phone and vehicle GPS, nearestStopIndexOnBoard calls findTrackedBusIndex, returning the first stop naming that plate in vehicleIds/etaEntries (2266–2271), even for future ETA. A live capture names one plate at24 downstream stops, first ETA450 seconds; that is not its location. Progress may advance at an unreached stop while remainingStops falls back to the whole boarding-to-destination distance (1121–1128). Restricting buses parsing is insufficient: etaEntries alone trigger this. Show unknown unless stop data establishes actual position. This is display/progress, not an independent alert trigger (distance is null). Membership heuristic existed in base; new no-fix fallback exposes it as onboard progress. Rendering source-traced, not Android-executed.

S8 · [P1] Matching pause/resume loses the known bus needed for no-phone reminders

Location: RouteTripMonitorService.kt:312–316. Evidence: executed_detector_boundary_plus_static_persistence_trace.

Keep identical route/direction/boarding IDs, unlike S6. Identify a plate without destination, allow destination-setup pause, then choose a destination with no phone fixes while that same bus feed remains healthy. pauseTracking stores session IDs/reason/time but destroys detector (2054–2075; AppRuntimeStateStore26–39). resumeConfirmedRide clears trackedVehicleId/manualConfirmationAtMs (358–364), so no-location resolution cannot restore the already-known bus. Parent executed resumed detector: hasBoarded=true but null progress/destinationDistanceMeters; alert code requires distance. Persist safely established plate bound to paused trip; keep unknown only if never identified. Existing resume test starts with unknown vehicle. Detector result executed; persistence/alerts statically traced, not Android integration.

Historical reconciliation

The original clock-age mismatch, no-destination onboard rendering, global suppression after decline, full-width launch IDs, outright stop-failure→bus-feed suppression, direction/stop-order detector reuse, opposite-direction co-movement, cross-trip stale fetch, same-trip stale fetch overwrite, skipped-destination timer baseline, far-ahead/manual-after-confirmation selection, generic action/question source confusion, two-GPS-departure collapse, ETA/GPS two-departure ambiguity, declined ETA echo swallowing, and unique→multi-plate arrival ambiguity all have their stated targeted fixes in this head. They are not re-filed as if unfixed. D/S findings above are remaining combinations or new-feature defects; they explicitly distinguish them from those prior reports. The future-ETA-membership report is superseded by the still-open actual buses contract report linked above.

Executed verification and limits

  • Parent reran 60 original JUnit tests, zero failures: TripRideDetectorCoMovementTest, TripRideDetectorDeclineTest, TripRideDetectorManualBoardingTest, StopIdCodecTest. Unchanged production TripRideDetector.kt, RideRouteLine.kt, StopIdCodec.kt plus exact DTOs extracted from this service, not a replacement implementation. Artifact SHA-256: 7477a1eda2221fe3c3dd130a4615d4584648399dcd42321059b90966f6ccd153.
  • Parent compiled and executed the deterministic probe below against those production classes: all nine D1–D9 reproductions and three service-boundary probes observed; exit 0. Boundary probes demonstrate detector results only; Android dispatch, notifications, persistence and Flutter launch consequences remain source-level traces.
  • Detector reviewer also exercised rider/waiting/walking tracks from all three checked-in replay fixtures against production bytecode (nine fixture scenarios). That is not a claim the original serialization-based Replay JUnit class ran.
  • Read-only live API samples validated topology/arrival payload discrepancies. Modeled transitions and route projections are explicitly separated from recorded real rides.
  • git diff --check origin/main...HEAD passed; checkout unchanged. Exact-head GitHub Actions Verify plus Android, Wear OS, Linux, Web, Windows, iOS and macOS builds pass; nightly publishing is skipped. The workflow does not invoke Android unit tests. Earlier Node/Web checks do not substitute for testing the changed detector.
  • Not executed: full Android/Robolectric service/fix-time suites, Flutter suites locally, device/notification/real-ride end-to-end tests. No local Gradle wrapper/Flutter SDK; a cached Kotlin compiler was sufficient for the focused JVM evidence. Passing tests do not establish that the scenarios above are covered or that no other defects remain.
Deterministic Kotlin reproduction (same package; compile against the unchanged production detector/geometry plus exact DTOs)
package tw.avianjay.taiwanbus.flutter

import kotlin.math.PI
import kotlin.math.cos
import kotlin.math.abs

private const val BASE=1_700_000_000_000L
private val scale=6_371_000.0*PI/180.0
private fun at(s:Long)=BASE+s*1000
private fun lat(y:Double)=24.1+y/scale
private fun lon(x:Double)=120.6+x/(scale*cos(24.1*PI/180.0))
private fun stops(spacing:Double=500.0)=(0..5).map { TrackingStop(it+1,"s$it",it,lat(it*spacing),lon(0.0)) }
private fun custom(points:List<Pair<Double,Double>>)=points.mapIndexed { i,p -> TrackingStop(i+1,"s$i",i,lat(p.second),lon(p.first)) }
private fun detector(destination:Int?=4,spacing:Double=500.0)=TripRideDetector(stops(spacing),0,1,destination)
private fun fix(t:Long,y:Double,x:Double=0.0)=RideGeoPoint(lat(y),lon(x),at(t),10f,5f)
private fun bus(t:Long,y:Double,id:String="A",x:Double=0.0)=RideBusReport(id,0,lat(y),lon(x),at(t),at(t))
private fun TripRideDetector.feed(t:Long,y:Double,id:String="A",x:Double=0.0) { onBusReports(listOf(bus(t,y,id,x))) }
private fun TripRideDetector.snap(t:Long)=snapshot(at(t))
private fun printResult(id:String,value:Any?)=println("$id: $value")

fun main() {
    // F1: negative answer consumes no new inputs, but auto-boards the second convoy bus.
    val d1=detector()
    for(t in 0L..60L step 20L) {
        d1.onBusReports(listOf(bus(t,t*5.0),bus(t,t*5.0,"B")))
        d1.onUserLocation(fix(t,t*5.0)); d1.snap(t)
    }
    check(d1.snap(60).trackedVehicleId=="A")
    d1.declineBoarding(at(61)); val r1=d1.snap(61)
    check(r1.hasBoarded && r1.trackedVehicleId=="B"); printResult("F1_decline_reboards",r1)

    val d2=detector(); d2.feed(0,0.0); d2.onUserLocation(fix(0,0.0)); d2.confirmBoardedByUser(at(0))
    check(d2.snap(0).trackedVehicleId=="A")
    d2.onBusReports(listOf(bus(60,700.0),bus(60,0.0,"B")))
    check(d2.snap(60).trackedVehicleId=="B")
    d2.onBusReports(listOf(bus(100,1000.0),bus(100,300.0,"B")))
    val r2=d2.snap(100); check(!r2.hasUsableLocation && r2.trackedVehicleId=="B")
    printResult("F2_stale_fix_switch",r2)

    val d3=detector(null)
    for(t in 0L..100L step 20L) { d3.onUserLocation(fix(t,t*5.0,3000.0)); d3.snap(t) }
    val r3=d3.snap(100); check(r3.hasBoarded && !r3.hasRouteValidProgress && r3.evidence==BoardingEvidence.SELF_PROGRESS)
    val d3b=detector()
    for(t in 0L..40L step 20L) { d3b.onUserLocation(fix(t,t*5.0,3000.0)); d3b.feed(t,t*5.0); d3b.snap(t) }
    check(d3b.snap(40).evidence==BoardingEvidence.BUS_CO_MOVEMENT)
    printResult("F3_off_route_self",r3); printResult("F3_off_route_comovement",d3b.snap(40))

    val hairpin=listOf(0.0 to 0.0,0.0 to 1000.0,40.0 to 1000.0,40.0 to 500.0,40.0 to 0.0,500.0 to 0.0)
    val d4=TripRideDetector(custom(hairpin),0,1,6)
    d4.feed(0,0.0); d4.confirmBoardedByUser(at(0)); d4.snap(0)
    val remaining=mutableListOf<Int?>()
    for((t,p) in listOf(100L to hairpin[1],104L to hairpin[2],154L to hairpin[3],204L to hairpin[4])) {
        d4.feed(t,p.second,x=p.first); remaining+=d4.snap(t).remainingStops
    }
    check(remaining==listOf(4,4,5,5)); printResult("F4_hairpin_remaining",remaining)

    fun sparse(dense:Boolean):RideSnapshot {
        val d=detector(spacing=200.0)
        for(t in 0L..80L step 20L) {
            if(dense || t%40L==0L) d.onUserLocation(fix(t,t*5.0))
            if(t%40L==0L) d.feed(t,t*5.0)
            d.snap(t)
        }
        return d.snap(80)
    }
    val r5=sparse(false); val c5=sparse(true)
    check(!r5.hasBoarded && c5.evidence==BoardingEvidence.BUS_CO_MOVEMENT)
    printResult("F5_exact_sparse",r5); printResult("F5_dense_control",c5)

    val d6=detector(); d6.feed(0,0.0); d6.snap(0); d6.feed(20,150.0); d6.snap(20)
    val q6=d6.snap(60).boardingCheckId; check(q6!=0L)
    d6.onBoardingStopEta(0,true,at(65),listOf("B")); d6.confirmBoardedByUser(at(70),q6)
    val r6=d6.snap(70); check(r6.trackedVehicleId=="A"); printResult("F6_ETA_alternative_ignored",r6)

    val d7=detector(); d7.feed(0,0.0); d7.snap(0); d7.feed(20,150.0); d7.snap(20)
    val q7=d7.snap(60).boardingCheckId; d7.declineBoarding(at(65),q7)
    d7.onUserLocation(fix(70,0.0)); d7.feed(70,200.0); d7.confirmBoardedByUser(at(75))
    val r7=d7.snap(75); check(r7.trackedVehicleId=="A"); printResult("F7_rejected_vehicle_reselected",r7)

    val d8=detector(); d8.feed(0,0.0); d8.confirmBoardedByUser(at(0)); check(d8.snap(0).trackedVehicleId=="A")
    d8.feed(20,2000.0); val r8=d8.snap(20)
    check(r8.passedDestinationByStops==1 && r8.hasRouteValidProgress)
    check(d8.snap(65).passedDestinationByStops==1 && d8.snap(80).hasRouteValidProgress)
    printResult("F8_impossible_jump",r8)

    val folded=custom(listOf(0.0 to 0.0,0.0 to 1000.0,50.0 to 200.0,50.0 to 0.0))
    val projection=RideRouteLine(folded).project(lat(100.0),lon(640.0),0.0)
    check(projection.segmentIndex==0 && abs(projection.crossTrackMeters-590.0)<0.01)
    val d9=TripRideDetector(folded,0,1,4); d9.feed(0,0.0); d9.confirmBoardedByUser(at(0)); d9.snap(0)
    d9.feed(20,100.0,x=640.0); val r9=d9.snap(20); check(r9.hasRouteValidProgress)
    printResult("F9_inconsistent_projection",projection); printResult("F9_invalid_route_accepted",r9)

    // Service action boundary: old question ID is not rejected by detector.
    val stale=detector(); stale.confirmBoardedByUser(at(1),at(-100)); val yes=stale.snap(1)
    check(yes.hasBoarded); stale.declineBoarding(at(2),at(-100)); val no=stale.snap(2)
    check(!no.hasBoarded); printResult("S2_old_yes_confirms",yes); printResult("S2_old_no_undoes",no)

    // Service feed boundary, no buses list required: explicitly not-arriving negative still counts.
    val negative=detector(); negative.onBoardingStopEta(-1,false,at(0),emptyList())
    negative.onBoardingStopEta(600,false,at(20),emptyList()); val neg=negative.snap(60)
    check(neg.boardingPromptDue); printResult("S3_negative_eta_question",neg)

    // Pause/resume creates a fresh detector with no remembered identity or identification window.
    val resumed=detector(); resumed.resumeConfirmedRide(); resumed.feed(0,2000.0)
    val resume=resumed.snap(0); check(resume.hasBoarded && resume.trackedVehicleId==null && resume.destinationDistanceMeters==null)
    printResult("S8_resume_loses_known_vehicle",resume)
    println("PASS: 9 detector/geometry reproductions + 3 service-boundary probes; no Android service execution")
}

The probe asserts the current incorrect outputs so the audit itself fails if a reproduction is not observed. Product regression tests should assert the corrected outcomes. The DTO extraction must preserve the exact production data classes; it contains no service/detector replacement logic.

message = text(stop, "message"),
vehicleIds = (buses + etas.mapNotNull { it.vehicleId }).distinct(),
etaEntries = etas,
busesAtStop = buses,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Blocking — buses does not mean buses physically at this stop. A live TXG300 response for stop 12251 had eta: 811 and six entries in buses, with matching etas of 811–2791 seconds and is_arriving: false. The same data reaches this parser from the foreground session (TripMonitorStop.fromStop copies stop.buses). Consequently feedBoardingEta treats future buses as arriving and passes their plates as at-stop vehicles. After the current bus departs, a future bus in buses keeps arriving true, so the 0 → 811 rollover never registers and riders without usable GPS receive no boarding question; with only one future bus, its plate can also incorrectly name an ETA departure. Derive at-stop identity from actual arrival/vehicle-position semantics, not the presence of an entry in buses, preserving unknown identity when the feed cannot establish it. Add a service regression using real-shaped buses plus positive ETA entries for the next bus.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

已在 e504d38 修正。這次不是再換一個成員判斷,而是把「buses 是在站車輛」這個假設整個拿掉。

為什麼先前還是錯

我把上一輪的 ETA-entry 成員判斷換成了 buses,等於只是換一個欄位做同樣的假設。對照後端 sync_realtime.py:每個車牌是被放進它「下一站」的 buses,所以十幾分鐘外的車也在裡面,和你取樣到的「buses 裡的車牌帶正的 ETA、is_arriving:false」一致。

修法

  • Native:LiveStopState.busesAtStop 移除。service 把站牌 feed 對每輛車說的內容原樣交給 detector(StopFeedBus(vehicleId, etaSeconds, arriving));只出現在 buses、沒有自己 ETA entry 的車牌以 etaSeconds = null 傳入,只代表「正在往這站來」。
  • 一輛車「在站」只有兩種依據:它自己的 is_arriving,或它自己的 ETA 已歸零/用完。被列出不算。
  • 站牌層級的「有車到站」同理:is_arriving(或訊息是進站/到站)、站牌 ETA 在 0–30 秒內,或接在一段倒數後面的負數 ETA(S3,見 PR 留言)。buses 非空不再讓 arrival 成立。
  • 離站要指名某輛車,必須整個進站期間恰好一輛被放在站上、沒有「在站但沒車牌」的 entry,而且期間沒有別的有車牌的車在 4 分鐘內(兩次輪詢之間它可能已經來了又走)。否則離站照樣成立,但不指名。
  • Foreground bridge:TripMonitorStop.fromStop 改成送出每一筆 ETA entry(含沒車牌的)與 is_arriving;StopEta.isArriving 由後端的 is_arriving 解析,家族合併時保留。

測試

  • RouteTripMonitorServiceTest.busesStillOnTheirWayAreNotBusesAtTheStop:你要求的真實形狀——buses 列六輛車(811 到 2791 秒,取自台中 300 的回應形狀),各自帶正的 ETA 與 is_arriving:false;交叉「在站車有/沒有車牌」與「後面列六輛/一輛」四種組合。斷言:站上的車離開會產生問題;還沒到的車永遠不是離站的那輛。
  • aBusListedForTheStopButStillOnItsWayIsNotAnArrival、twoBusesTheStopFeedPlacesAtTheStopLeaveItsRolloverUnnamed、aBusTheFeedFlagsAsArrivingIsAtTheStopWhateverItsEstimate(service)。
  • aBusListedForTheStopIsNotABusAtTheStop、aBusAtTheStopTheFeedDidNotNameLeavesTheRolloverUnnamed、aBusCloseBehindMayHaveComeAndGoneBetweenTwoPolls、aBusOnlyEverListedOnItsWayNeverLeft、aBusFlaggedAsArrivingIsAtTheStopWhateverItsEstimate(detector)。
  • Dart:stop entries reach the monitor as the feed has them、a variant bus the feed has arriving is still arriving once merged,以及 route_realtime_parsing_test 對 isArriving 的斷言。
  • Mutation:把只被列出的車當成在站、把任何 ETA 都當成在站、不傳/不看逐車的 is_arriving、忽略「在站但沒車牌」、忽略「4 分鐘內的其他車」,每一個都有測試轉紅。其中「逐車 is_arriving」那兩個第一次跑是存活的(原本的 fixture 裡被標記的車 ETA 都是 -1,旗標本身沒被單獨測到),補了上面兩個 …FlagsAsArriving…/…FlaggedAsArriving… 測試之後才被殺。

資料

錄製的 feed 裡,buses 的每輛車都有自己的 ETA entry(高雄 100:1375 筆、台中 300:1628 筆,沒有例外),所以改用「該車自己的 entry」判斷不會漏掉車。用同一份錄製資料重放新規則:高雄 100 的 86 次離站指名 71 次、台中 300 的 70 次指名 49 次;雙北那條的 feed 不帶車牌,96 次離站都不指名。

取捨

「4 分鐘內有別的有車牌的車就不指名」是偏保守的:兩班車貼得很近時,離站後會問乘客但不會自動鎖定車牌,要等乘客自己的定位把車挑出來。跟錯車會對不是乘客搭的那班車響下車提醒,所以選擇寧可不指名。

…e route

Review D4 and D9.

A fix was placed on whichever nearby segment lay closest to the previous
along-route position. On a hairpin whose legs run 40 m apart that held a
vehicle on the outbound leg once it had turned: the outbound leg was nearer
where it had been than the leg it was now exactly on, and every fix after
that put it further back. Stops to go read 4, 4, 5, 5 where they should have
read 4, 3, 2, 1, for a bus's reports and a rider's own fixes alike.

Candidate segments are now costed by their distance from the fix plus a
share of the travel along the route they would imply, with travel backwards
costing four times travel onwards. A street used twice is still told apart
by which pass continues the journey, and a single fix that reads a little
back along the route does not jump to the other leg.

The projection also returned the chosen segment's position together with
the nearest segment's distance. A vehicle 640 m from the stretch it was
placed on was measured as 590 m — the distance to another stretch — and so
passed that stretch's 600 m limit. The distance is now the chosen segment's.
…can give

Review D1, D3 and D5.

D1. Turning down a detected ride set its vehicle aside, but the minute of
movement that had detected it still counted for any other bus. With two
buses running together the second was detected, from the same minute, the
moment the first was turned down. Co-movement now uses only reports and
fixes made since the rider last said "not yet", and does not interpolate
from a fix made before it; the rider's own progress already worked this way.

D3. Everything is measured along the stop sequence, and a phone on a road
three kilometres to one side still has a position along it. It kept level
with a bus on the route and was taken to be riding it, and with no vehicle
feed at all its own "progress" from the boarding stop confirmed a ride. A
fix now records whether it is on the route, by the rule already used for
vehicles. Co-movement needs the rider on the route at each report, and the
rider's own progress has to start at the boarding stop itself and stay on
the route. A trip with no boarding stop chosen is no longer anchored to
the stop a far-off fix happens to be level with.

That progress must also be ground the phone covered. Where a route uses a
street twice, a fix a little way back down it can be placed on the later
pass, a loop further on, and read as hundreds of metres of travel.

D5. Where the rider was when a bus reported was refused whenever the fixes
either side were more than 30 s apart, even if one of them was made at
that very moment and nothing needed interpolating. A fix made at the
moment, or within the few seconds already allowed at either end of the
track, now stands for it.
…inst it

Review D2, D7 and D8.

D2. The vehicle a ride was on was checked against the rider's latest fix,
which stays usable for a minute and a half. When the phone went quiet the
bus drove on, the fix left behind at the boarding stop no longer matched
it, and the ride was handed to whichever bus pulled in next; once the fix
lapsed that bus carried the ride on. A vehicle is now held against where
the rider was at the time of its report. With no fix from around then
there is nothing to show the rider left it, and it is kept. The same goes
for a vehicle whose own feed stops or sends one unusable report: it is no
longer replaced by the nearest bus still reporting, unless it has not been
heard from for so long that its track is gone.

D7. "I have boarded" could put the rider back on a bus they had turned
down, because neither the tracked-vehicle choice nor the candidates for an
unprompted confirmation looked at rejections. The confirmation still
confirms the ride; a rejected vehicle is no longer picked for it.

D8. A single report placing a vehicle two kilometres on, twenty seconds
after it was at the boarding stop, was taken as progress: with no phone
fix it put the ride past its destination, valid for the overshoot alarm.
The rider's fixes had a jump guard and vehicle reports had none. A report
further away than a bus could have driven is now kept back until the next
one shows which place was right. If that fits the track the leap is
dropped; if it carries on from the leap, the leap is accepted as the start
of a new stretch. Meanwhile the vehicle supplies no progress, is not seen
approaching or leaving the boarding stop, and a leap across the stop,
even once confirmed, is not a departure anyone could have boarded.
The `buses` contract reported on the previous head, with review S3 and D6.

`buses` does not list the buses at a stop. The backend lists each vehicle
under the stop it will reach next, with an estimate that can be three
quarters of an hour away: in recorded 台中 and 高雄 feeds a fifth to a
third of the vehicles in `buses` were more than ten minutes out. Treating
them as at the stop kept "a bus is arriving" true after the real one had
left, so the estimate going from zero to 811 s was never read as a
departure and a rider without GPS was never asked; and a single future
bus could give that departure its plate.

The detector is now handed what the feed says of each bus — its plate, its
own estimate, and `is_arriving` — and decides for itself. A bus is at the
stop when it is flagged as arriving or its own estimate has run out. A
rollover names a bus only when exactly one named bus was placed there,
none was there without a plate, and no other named bus was within four
minutes of the stop meanwhile, since one that close can come and go
between two polls. `LiveStopState.busesAtStop` is gone.

S3. An estimate left at -1 and explicitly not arriving counted as a bus at
the stop, so that and a later 600 s raised a question about a bus nobody
saw. It now counts only as the end of a countdown the detector watched: a
live estimate within the last 90 s. Dropping every negative estimate would
be wrong the other way — in the recorded 雙北 feed, which never flags an
arrival, 76 of 98 departures are seen only through one, and each was a
vehicle within 150 m of the stop.

D6. Whether another bus was there for the rider to board looked only at
vehicle positions. A bus the stop feed has at the stop, with no position
feed, now leaves an answer about another bus, or an unprompted
confirmation beside one, unnamed.

The app's own copy of the feed carries `is_arriving` and the entries with
no plate, which it used to drop.
Review S4 and S7.

S4. While the app is open the route screen hands the monitor its display
state: an entry for every stop, a placeholder where it has nothing to
show, estimates it has counted down since the last refresh, and the last
data it had for as long as its refreshes fail. All of it was stamped as
fresh and fed to the detector. A bus at the stop followed by a
topology-only update read as the estimate vanishing — a departure; an old
arrival sent again renewed the arrival; and every update, stale or not,
put off the monitor's own fetch for another twenty seconds.

The screen now says what the backend observed (`observedEta`) apart from
what it is showing, and when it was observed (`observedAtMs`). The monitor
tells the detector of each observation once, whichever way it arrived,
using the backend's `eta_reference_at` for its own fetches. From the
screen it takes up only an observation that is newer than any it has and
no more than a minute and a half old; anything else leaves its cache and
its fetch schedule alone, so it goes on fetching for itself while the
screen has nothing new.

S7. With no phone fix and no usable vehicle position, on-board progress
fell back to the first stop whose entries named the tracked plate. The
feed names a vehicle at every stop it has yet to reach, so that was a stop
it was still minutes away from. The fallback is now the stop the feed has
the vehicle at — flagged arriving, or its own estimate run out — and
otherwise nothing. The approaching bus's place on the waiting progress bar
comes from its reported position rather than from which stops name it.

Family merges keep the soonest estimate of any variant as what was
observed, run out or not; the badge still shows the next bus to come.
Review S2.

"I have boarded" and "not yet" were acted on whatever trip they had been
made for. A tap on the outbound trip's question, delivered after the rider
had switched to the other direction, confirmed a ride on the new trip, or
erased one already under way there and reset its alerts.

Every boarding button now carries the id of the trip it was made for, and
one made for another trip is dropped before the detector or the alerts are
touched.

The buttons of two questions were also the same PendingIntent: same
action, same request code, differing only in extras, which do not tell
PendingIntents apart. Making the second rewrote what the first one sent.
Each trip and question now has its own, told apart by the intent's data.

"Not yet" to a question that is no longer the pending one — because a ride
was detected or confirmed after it was asked — no longer undoes that ride,
and the service leaves the alerts and any newer question alone when the
answer changed nothing.
…ride

Review S6 and S8.

A ride confirmed with no destination is paused while the rider is asked to
choose one, and choosing one is meant to carry on that ride.

S8. Pausing threw away the detector, and with it the bus the ride had been
identified as being on. Resumed, the ride was boarded with no vehicle;
with no phone fix that left it with no progress and no distance to the
destination, which the reminders need. The bus is now saved with the
paused ride and given back to the new detector. A pause the app requests
for a session it names does not take the tracked trip's bus with it.

S6. Tapping the prompt with no route screen open launched one with the
route's first stop — the fallback when there is no destination — and that
screen took it as the boarding stop. The trip it then sent no longer
matched the paused ride's boarding stop, so the ride came back as
"waiting". The prompt now launches with the ride's own boarding stop, and
with no stop when none was chosen. A ride paused with no boarding stop is
matched whichever stop the screen has filled in by then, on the same
route and direction.

The cold launch itself runs through Flutter and is not exercised here:
the tests cover what the notification launches with and what the service
accepts back.
… destination

Follow-up to the S6 fix, found on reading it back.

A ride paused to ask for a destination with no boarding stop chosen was no
longer "the paused trip" as soon as the route screen filled in the stop
nearest the rider and sent the trip again, still without a destination.
The monitor started afresh, waiting at a stop the bus was riding past, and
with a detector now running the ride was not picked up when the rider did
choose where to get off. Such a pause now matches whichever boarding stop
the session names, on the same route and direction.
…nly where it runs

Review S5 and S1.

S5. One refresh fetched the stop feed and then each family route's
vehicles, one after another, on the single thread that also publishes the
ride. A request can hang for twenty seconds before timing out, so one slow
variant held back the vehicles already fetched from healthy endpoints, the
rider's own fixes, and the timers for the boarding question and the
arrival countdown — past the point where a reminder is of use.

A refresh now asks for whatever is due and publishes what the detector
already knows without waiting. Each feed is fetched on a small pool of its
own; each response is handed to the detector when it arrives and has the
ride published again. A feed with a request out is not asked for again,
and the interval and back-off rules are as before. Vehicles no longer wait
to be merged across endpoints: the detector already keeps a vehicle's
reports in the order they were made.

S1. A vehicle of another route of the family was projected onto this
trip's stops wherever it was. A variant that shares the route up to the
last stop but one, and then runs to its own platform seventy metres from
this route's terminal, projected onto the terminal, and the ride was taken
to have arrived at a stop that bus never calls at. A variant's reports now
carry which of this trip's stops its route calls at, matched the way its
live stops already are, and its position counts only between the first and
last of them. If a variant's stops cannot be fetched its vehicles are not
used, and the endpoint backs off like one that failed.
…pending on timing

Found reviewing the per-feed fetching before pushing it.

A fetch that failed in a way it does not itself account for had its feed
marked as no longer being fetched, and nothing else: the next refresh, as
little as two seconds on, asked again, and went on asking, out of the rate
limit the monitor shares with the app. It now backs off like any other
failure.

That clearing was not held to the trip the request was made for. Opening
another trip on the same route hands the feed's bookkeeping to the new
trip, whose own request is then out; the old trip's request failing
cleared the mark, and the feed was asked for a second time while the first
request was still out. It applies only to the trip that asked.

With each endpoint fetched on its own, a bus listed by two routes of a
family had the same fix handed over twice, in whichever order they
answered. From the variant first it was recorded as off this route where
the variant leaves it, and the route's own listing of it, arriving second,
was dropped as a repeat. A fix another endpoint lists again is now on the
route if either route runs there. As far as the backend can be read it
assigns a vehicle to one route's endpoint, so this guards against the
order mattering rather than fixing something seen.

The fetch threads are no longer capped at four: a family can have more
endpoints than that, and four that hang must not hold up a fifth. A feed
is never asked for while its last request is out, so there are no more
threads than feeds.

Also corrects a comment that still named updateLiveData.
…rules in place

Changing these one at a time left every test passing:

- not passing a bus's own `is_arriving` to the detector, or the detector
  not reading it: every flagged bus in the fixtures also had an estimate
  that had run out, which places it at the stop by itself;
- feeding the detector an observation no newer than one it had taken;
- taking the route screen's old copy of the boarding stop as news because
  another stop in the same update was current;
- letting the same observation, sent again, put off the monitor's own
  fetch, or old data start a trip's cache.

Each now has a test that fails without it. On the Dart side, parsing
`is_arriving` and keeping it through the family merge are asserted too.
@AvianJay

Copy link
Copy Markdown
Collaborator Author

彙整版 review 的 17 項(D1–D9、S1–S8)逐項回覆如下;buses 那一項回在原本的 thread。謝謝把重現程式整份附上,省了很多來回。

新的 head 是 c2d4035(bd52f8c 之後 11 個 commit)。

我怎麼驗證的

  • 你附的重現程式:我把它逐項改寫成斷言「修正後結果」的 JUnit(同一批輸入、同一批座標),對新 head 跑:D1–D9 加三個 service 邊界探針,12 個全過。這支只是驗證用,沒有提交;每一項對應的回歸測試列在下面。
  • 先紅後綠:D1–D9、buses/S3、S4/S7 的回歸測試都是先加、在 bd52f8c 的程式上確認會紅,再修。D4/D9 在舊程式上得到的就是你列的 [4, 4, 5, 5] 與 590 m。
  • Mutation:S2、S6/S8、S5/S1 依賴新欄位,沒辦法在舊程式上跑紅,改成把修正逐一改壞、確認有測試轉紅。本輪共 45 個 mutant(Kotlin 40、Dart 5),最後全部被殺。其中 7 個第一次是存活的——都是「修正在、但沒有測試守著」——補了測試之後才被殺:逐車的 is_arriving 2 個、S4 的邊界 4 個、S5「回應到了要再發佈一次」1 個。
  • Android 單元測試:完整 :app:testDebugUnitTest 在新 head 上 283 個測試案例全過(service 的測試在 SDK 28 與 34 各跑一次,所以有重複計數)。CI 的 Verify 不跑這個 task,所以這是我本機的結果。
  • Flutter:只跑了和改動有關的四個檔(android_trip_monitor_test、route_family_test、route_realtime_parsing_test、samsung_live_notification_prompt_service_test,共 18 個測試,全過),以及對改到的 Dart 檔跑 flutter analyze。完整的 Flutter 測試我沒有在本機重跑,以 CI 為準。
  • 沒做的:實機、通知、冷啟動與真實乘車的端到端測試都沒有。service 測試是 Robolectric(SDK 28/34)。

Detector/幾何

修正 commit 回歸測試
D1 Co-movement 只採計「還沒上車」之後的證據:車機回報與用來內插的手機定位都必須晚於 lastDeclineAtMs。 02c45b4 turningDownOneOfTwoBusesRunningTogetherIsNotAnsweredWithTheOther、onlyWhatHappensAfterNotYetCountsTowardsTheNextBus
D2 換車判斷改成對齊時間:用「車機回報那一刻乘客在哪」去比,而不是用最新的一筆定位。那一刻沒有定位就保留原車;原車暫時沒回報也保留。 f5d795c anIdentifiedRideIsNotHandedToTheNextBusWhenThePhoneGoesQuiet、aVehicleReportIsHeldAgainstWhereTheRiderWasWhenItWasMade、aVehicleFeedOutageWithAFixStillInHandDoesNotMoveTheRide、aBusThatFallsSilentIsNotReplacedByOneThatHappensToBeNear;反向保護:aFreshFixThatAnotherBusExplainsStillMovesTheRideToIt
D3 手機定位保留「是否在路線上」(和公車同一條規則)。Co-movement 遇到不在路線上的定位就清空配對;self-progress 的起點要在上車站 250 m 內(實際距離),之後不能有離線定位,而且沿線位移不能超過實際移動距離的兩倍加 100 m。沒選上車站時,只有在路線上的定位才決定起點。 02c45b4 aPhoneOnAnotherRoadIsNotRidingTheBusItKeepsLevelWith、aPhoneOnAnotherRoadHasNotLeftTheBoardingStopAlongTheRoute、aTripWithNoBoardingStopStartsWhereTheRiderIsOnTheRoute、walkingBackDownAStreetTheRouteUsesTwiceIsNotTravelAlongIt
D4 投影不再只在「離舊位置最近」的線段裡挑。在距離差 60 m 內的候選線段中,取「橫向距離 + 沿線位移成本」最小者,往前每公尺 0.05、往回每公尺 0.2。髮夾彎的回程因此是「往前走」,而雜訊造成的小幅倒退不會把點甩到另一條腿。 045b9dd RideRouteLineTest:travelRoundAHairpinGoesForwardAlongTheReturnLeg、aFixOnTheReturnLegIsNotPulledBackOntoTheOutboundLeg、aNoisyFixBesideAHairpinStaysOnTheLegBeingTravelled、aStreetUsedTwiceIsToldApartByWhichPassContinuesTheJourney、aBackwardGlitchDoesNotThrowTheFixOntoTheOtherLeg、aRideRoundAHairpinCountsItsStopsDown
D5 時間戳完全相同就直接用那筆定位,不經過內插間隔的限制。間隔超過 30 秒時,只接受 6 秒內最近的一筆,不內插。 02c45b4 fixesMadeAsTheBusReportedNeedNoFixBetweenThem;反向保護:aLongGapWithNoFixNearTheReportIsStillNotGuessedAcross
D6 「還有別的車可以上」現在也看站牌 feed:被 feed 放在站上的另一輛車(即使沒有 GPS)就讓指名變成不確定。容許 feed 落後 30 秒。 e504d38 aBusTheStopFeedHasAtTheStopLeavesAnAnswerAboutAnotherOpen、unpromptedABusOnlyTheStopFeedHasAtTheStopLeavesTheRideUnidentified
D7 被拒絕的車不會再被選中:resolveTrackedVehicle 與手動確認的候選都排除它。確認本身仍然成立,車牌維持未知。 f5d795c confirmingByHandDoesNotPutTheRiderBackOnABusTheyTurnedDown、aRideDetectedOnABusLaterTurnedDownByNameIsNotKept
D8 車機回報先對既有軌跡檢查「開得到嗎」(150 m + 35 m/s × 經過秒數)。開不到的先扣住:這輛車算有回報,但不算在任何位置——不給進度、不算離站、不當下一班車。下一筆若接回原軌跡,扣住的那筆丟掉;若從扣住的位置繼續走,兩筆才一起入軌。 f5d795c aVehicleCannotCarryTheRidePastTheDestinationInOneLeap、aSingleWildPositionDoesNotDisturbTheRide、aWildPositionDoesNotAnnounceADeparture、aVehicleThatLeaptPastTheStopWasNotSeenLeavingIt;反向保護:aVehicleThatGoesOnReportingFromItsNewPlaceIsBelievedThere
D9 回傳 distances[chosen]。 045b9dd theDistanceReportedIsToTheSegmentChosen、aVehicleFarOffAFoldedRouteIsNotTakenForOneOnIt

D8 的門檻來自錄製資料:52 輛車 2103 步,p99.9 車速 19.1 m/s;唯一離譜的就是你提到的那一對(40 秒 6782 m)。所以 35 m/s 加 150 m 的容許值不會扣住正常回報。

Service

修正 commit 回歸測試
S1 家族變體的車機回報帶著「這條變體在本行程路線上停哪些站」(和 live stop 用同一套比對:ID,或站名加 60 m 內)。變體的位置只在兩條路線共用的第一站到最後一站之間(±40 m)才算在路線上。拿不到變體站序時,該端點的車完全不用,並照失敗處理進入 back-off。 fb6f334 aVariantsBusIsNotFollowedToAStopItsRouteNeverCallsAt、aVariantsBusThatCallsAtTheDestinationArrivesAtIt、aVariantWhoseStopsCannotBeFetchedLendsNoVehicles、aVariantsBusCountsOnlyWhereItsRouteSharesThisOnes
S2 每次建立 detector 都有新的 tripId。上車/還沒上車的按鈕帶著 trip_id,而且 intent 的 data URI 含行程與問題 ID,所以不同行程、不同問題是不同的 PendingIntent,不會被 FLAG_UPDATE_CURRENT 蓋掉。service 在碰 detector 或提醒狀態之前就先比對行程。對已經不是待答問題的「還沒上車」不再取消乘車,也不重設提醒。 0b18bdc buttonsMadeForAnotherTripDoNotSpeakForThisOne、aLaterQuestionsButtonsDoNotRewriteAnEarlierOnes、notYetToAQuestionSettledSinceLeavesTheRideAndItsAlertsAlone、notYetToAQuestionNoLongerPendingChangesNothing
S3 is_arriving 一路保留到 detector。負數 ETA 只有接在一段「看得到的倒數」後面才算有車到站:距上次有效估計(is_arriving 或 0–239 秒)90 秒內。單獨出現的 -1、is_arriving:false 不算。 e504d38 anEstimateThatRanOutBeforeTheTripBeganIsNotABusLeaving、anEstimateThatHasRunOutIsABusOnlyAtTheEndOfACountdown
S4 Bridge 多送兩樣:後端原始的估計(observedEta,和畫面倒數後的值分開)與後端做出這次觀測的時間(observedAtMs,取 eta_reference_at)。Native 每一次觀測只餵 detector 一次;App 送來的資料必須帶觀測時間、在 90 秒內、而且比已經收過的新,才會取代快取並重設抓取時鐘。Placeholder 沒有觀測時間,所以不會被當成「估計消失」。 c2b2d47、c2d4035 whatTheRouteScreenGoesOnShowingIsNotNewsFromTheFeed、anOldObservationShownAgainDoesNotBringABusBackToTheStop、theMonitorFetchesForItselfWhileTheRouteScreenHasNothingNew、aStopTheScreenHasOnlyOldDataForIsNotNewsBecauseAnotherStopIs、anObservationOlderThanOneAlreadyTakenIsNotTheEstimateRollingOver、theSameObservationSentAgainDoesNotPutOffTheMonitorsOwnFetch、aTripBegunOnOldDataFromTheScreenFetchesItsOwnAtOnce、aStopSaysWhatTheBackendObservedAndWhen、aVariantsBusAtTheStopIsWhatWasObservedThereWhateverTheBadgeShows;Dart:live data says what the backend observed, and when
S5 一次 refresh 不再等網路:它送出到期的請求,然後立刻用 detector 已經知道的東西發佈。每個 feed 各自在自己的執行緒上抓,回來時各自交給 detector 並再發佈一次。同一個 feed 有請求在外時不會重複送。 fb6f334、9e11816 aFamilyEndpointThatHangsDoesNotHoldBackTheRide、aFeedWithARequestOutIsNotAskedForAgain
S6 目的地設定的通知帶 destinationLaunchStopId ?: boardingLaunchStopId,不再退回路線第一站;沒選上車站就不帶站牌。暫停時沒有上車站的乘車,之後畫面補上哪一站都算同一趟,而且在選好目的地之前維持暫停。 3502c03、46ec6ea theDestinationPromptOpensTheRouteAtTheStopTheRideBeganFrom、theDestinationPromptNamesNoStopWhenTheRideHadNoBoardingStop、aRideWithNoBoardingStopStaysPausedUntilItsDestinationIsChosen
S7 「這輛車到了哪一站」只認 feed 把它放在站上的站(is_arriving 或後端原始 ETA ≤ 0),取最後一個。被列在還沒到的站不算,沒有就顯示未知。 c2b2d47 aBusNamedAtStopsItHasYetToReachIsNotShownAsHavingReachedThem
S8 暫停時把已經確定的車牌一起存下來(只限暫停的是正在追蹤的行程,而且已上車);回來時 resumeConfirmedRide(knownVehicleId) 直接接回那輛車。從沒確定過車牌的維持未知。 3502c03 aRidePausedForADestinationComesBackOnTheBusItWasOn、aPauseTheAppAsksForOnAnotherSessionDoesNotCarryThisRidesBus、aRidePickedBackUpOnAKnownBusIsMeasuredByThatBus

S3 的 90 秒與「不能把負數一律丟掉」都是對著錄製資料定的:

路線(離站/指名) 負數一律算到站 負數全丟 現在的規則
高雄 100 86/71 77/55 86/71
雙北 TPE157463 97/0 21/0 96/0
台中 300 71/50 59/35 70/49

雙北那條有 76 次離站只看得到負數 ETA,全丟會漏掉大部分。另外,「負數且非 arriving、之後跳號」的每一次,位置 feed 在 150 m 內都有車(高雄 9/9、雙北 76/76、台中 12/12);負數持續的時間距上次有效估計幾乎都在 60 秒內。

推送前自審另外找到的(review 沒列)

照同一套標準自己再審了一遍 bd52f8c..HEAD,多修了這幾個,都在 9e11816:

  1. 抓取失敗的例外路徑會讓 feed 每次 refresh 都被重問。 S5 的新程式在抓取丟出未預期例外時只把「請求在外」的旗標清掉,沒有 back-off,下一次 refresh(最短 2 秒)就會再送一次,持續消耗和 App 共用的 rate limit。現在和一般失敗一樣退 60 秒。測試:aFeedWhoseRequestBlowsUpIsLeftAloneLikeOneThatFailed。
  2. 上一個行程的請求失敗,會把新行程的「請求在外」旗標清掉。 同一條路線換行程時,舊請求失敗的清理沒有比對行程,新行程自己的請求還在外就會被重複送出。現在清理只對發出請求的那個行程生效。測試:aRequestOfTheLastTripThatBlowsUpDoesNotFreeThisTripsFeed。
  3. 同一輛車同時出現在兩個端點時,結果取決於誰先回來。 各端點分開抓之後,變體端點若先到,同一筆定位會以「變體不走這段」被記成不在路線上,路線自己的端點後到時被當成重複而丟掉。現在同一筆定位被另一個端點列出時,只要其中一條路線走這段就算在路線上。測試:aBusTwoRoutesOfTheFamilyListRunsWhereEitherOfThemDoes(兩種先後順序都跑)。後端批次同步那一段是把每輛車對到單一路線 ID(其他路徑我沒有逐一確認),所以這是防禦性的修正,不是觀察到的故障。
  4. 抓取用的執行緒池從固定 4 條改成依需求建立:家族有五、六個端點時,四個卡住的請求不該擋住第五個。上限是「feed 數量」,因為同一個 feed 不會同時有兩個請求。
  5. 一處 KDoc 還指向已經不存在的 updateLiveData。

c2d4035 只有測試:補上 mutation 第一次沒殺掉的那幾個(逐車 is_arriving、S4 的四個邊界),以及 Dart 端對 is_arriving 解析與家族合併的斷言。

行為變更與已知限制

請特別看這幾點,有不同意的我再改:

  • 沒帶 trip_id 的上車按鈕會被忽略(S2)。更新 App 前就留在通知列的舊通知,按鈕按了不會有反應。
  • 拿不到站序的變體,車輛完全不用(S1)。每個變體多一次 /stops 請求(同一個 service 內有快取)。
  • 兩班車貼很近時離站不指名(buses 那項的取捨)。
  • 兩端都沒選時的「公車還有 N 站」 改用 detector 的 busStopsUntilBoarding(S7 的連帶變更,原本用的是同一個「被列出就算到了」的來源)。
  • S6 的冷啟動沒有端到端執行。 測試涵蓋的是通知帶出的參數,以及 service 收到後續 session 時的判斷;中間經過 Flutter 開路線頁的那一段是靠讀程式確認的。
  • D4 的成本係數(0.05/0.2/60 m)是對著測試裡的幾何形狀調的。 既有的三份 replay fixture(TripRideDetectorReplayTest)在新投影下仍然通過,但我沒有確認那三條路線裡有沒有髮夾彎,所以不能算是用真實的髮夾彎資料校正過。
  • S5 之後各端點的車輛不再先合併才交給 detector;detector 本來就依回報時間排序並丟掉不比上一筆新的回報。
  • 自審時看到但沒動的(main 上就是這樣,不在這個 PR 範圍):過站提醒要求乘客在某個站牌 100 m 內;離開路線頁或把 App 從最近使用滑掉仍會停止監測。

@Av1anJay Av1anJay left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Consolidated review — changes requested

Revision c2d403550be8ea8c46da795666477d3cc3e42e07, base 6c6c8d74719e8efe01a99c12b286c2ae8a8f1bad. The five inline findings below cover all currently validated issues; the scenarios are static source traces, not executed Android/JVM reproductions. Each is conditional on the stated inputs/interleaving.

Historical reconciliation

For the exact scenarios in the previous consolidated review, D1–D9 and S1–S8 are fixed by source and regression-assertion inspection. The earlier future buses membership issue is also fixed for its reported scenario, as described in the author's reply. This is not a claim that the current-head Android tests were independently run or that every related interaction is correct. The same-trip question, family aggregate, individual-stop watermark and request-generation cases below are distinct from the original S2, S3, S4 and S5 scenarios; see also the author's detailed fix response.

Evidence and limits

Reviewed the changed production/test files and affected callers, the previous findings and author responses, and independent adversarial reports. Existing CI run 43938824622 attempt 2 checked out merge 222ec2761f47f2da2bc62e10fca749d32fd57708 of this base and head: its saved Verify log reports clean flutter analyze, 552 Flutter tests and 2 Chrome geometry tests. Android APK/AAB were built, but there was no Android unit-test step. The exact-head serialized SDK-free Kotlin compile timed out after 540 seconds; no current-head JVM, Robolectric, device notification or live-ride test was independently executed. git diff --check passed. Captured backend payloads establish some individual ETA shapes, not the modeled mixed-family ride transitions. The author's local Android test results are self-reported.

We did not promote the synthetic skipped-interior topology or stale-source/reference hypotheses: the necessary real topology or upstream event transition was not established. Native polling can mitigate the foreground watermark issue but is not guaranteed to observe the missed transition.

// answered for: the rider may be on that one, and has not said.
manualVehicleAmbiguous = departuresTheQuestionCovers(nowMs).isNotEmpty()
}
boarded = true

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P1] Ignore a question-bound answer after that question is retired, rather than confirming a new ride. For the same trip, queue YES for question A; A is subsequently declined or superseded by B; then deliver the old YES. The service checks only trip identity, and although the mismatched ID makes askedAbout null, this branch still sets boarded = true, clears B, cancels its prompt and suppresses further boarding checks. This is different from the fixed cross-trip S2: the trip token is still valid here. A question-bound stale NO also changes lastDeclineAtMs at lines 592–599, discarding movement evidence obtained since the answer was originally made despite returning false. Reject mismatched non-null IDs before any detector/service mutations; preserve the intentional null-ID permanent-notification confirmation. Evidence: source-level delivery-order trace; Android dispatch was not executed.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

已在 016576c 修正。

修法

  • confirmBoardedByUser 與 declineBoarding 在動任何狀態之前先比對:帶著問題 ID 的回答,只有在它回答的就是目前待答的那一題時才算數;否則直接回傳 false,什麼都不改。所以過期的「我已上車」不會把乘客設成已上車、不會撤掉 B 的問題;過期的「還沒上車」也不再移動 lastDeclineAtMs。
  • Service 兩個 action 都看回傳值:沒被採用就直接返回,不碰 boardingAlertSent、不取消畫面上的問題、不重設提醒。
  • 不帶問題 ID 的「我已上車」(常駐通知上的那顆)照舊一律採用。

連帶的變更(請看一下)

回答只對待答的那一題有效之後,會多出一個情況:問題 A 還掛在通知列,另一班車離站、要重新問(新的問題 B 要 40 秒後才到期),這段時間畫面上那則通知的按鈕還是 A 的,按了會沒反應。所以現在只要畫面上已經有一則問題,待答的題目一換,就立刻把那則通知的按鈕換成新題目的——安靜地更新(setOnlyAlertOnce),等新題目到期時才再響一次。原本沒有問題在畫面上時,仍然要等到期才顯示。

測試

  • Detector:yesToAQuestionSinceTurnedDownIsNotYesToTheNext(A 被回「還沒」之後、以及 B 的問題待答時,A 的「我已上車」都不生效,B 的問題仍在;不帶 ID 的仍然生效)、anAnswerToAQuestionSinceReplacedNamesNoBus(改寫:被取代的問題的「我已上車」不再確認乘車)、notYetToAQuestionNoLongerPendingLeavesWhatTheRiderHasDoneSinceAsEvidence(過期的「還沒」之後,乘客跟著公車走的三筆回報仍然成立)。
  • Service:yesToAQuestionTheRiderHasSinceAnsweredNoIsNotActedOn(同一個行程,用通知上實際的 PendingIntent)、theQuestionOnScreenAnswersTheQuestionNowPending(畫面上的按鈕跟著待答的題目換;已經在路上的舊點擊不生效)。
  • 這些在修正前的程式上都是紅的。Mutation:拿掉 detector 的比對、讓過期的「還沒」仍移動證據起點、service 忽略回傳值、不更新畫面上的按鈕、問題未到期就顯示——5 個都有測試轉紅。

限制

從題目換掉到通知更新之間(下一次發佈,通常是當下那次車機回應之後)點到舊按鈕會沒有反應,通知還在,可以再點一次。Android 實際的派送順序沒有在實機上跑,測試是 Robolectric。

line.metersToStop(usableUser.latitude, usableUser.longitude, boardingStop) >
BOARDING_STOP_ABANDONED_RADIUS_METERS
) {
// The user is nowhere near the stop any more, so this bus was never

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P1] Distance from the boarding stop does not prove that the rider abandoned the question: they may have boarded the departing bus. With no usable bus-position feed, observe ETA 0 at t=0, 600 at t=20 (creating the pending question), then a valid on-route phone fix 420 m from the stop at t=35, before the 40-second prompt delay. snapshot() clears the question here; self-progress has not yet reached its 500 m threshold. If fixes then stop, neither the boarding question nor automatic confirmation occurs, so destination reminders never start. Preserve a pending departure when forward travel could be the ride, or distinguish an actual abandonment from movement along the route. Evidence: source-level modeled sequence; no Kotlin/device execution.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

已在 016576c 修正。

修法

離上車站超過 400 m 就撤掉問題的規則,現在多一個條件:乘客不是「在路線上、而且在上車站的下游」。那正是剛離站的那班車去的方向,乘客如果上了車也會在那裡,所以這時候不能當成「人走了」。往旁邊離開(包括人在另一條路上、只是剛好和下游某一點平行)、或沿路線往回走,仍然照舊撤掉問題。

判斷用的是和其他地方同一條「在路線上」的規則(UserSample.onRoute),加上沿線位置大於上車站。

測試

  • aRiderCarriedOnAlongTheRouteHasNotWalkedAwayFromTheQuestion:就是你列的序列——沒有車機位置,ETA 0(t=0)→ 600(t=20),t=35 手機在路線上離站 420 m,之後定位中斷。斷言:t=35 問題還在;t=65 問題到期可以問。修正前在 t=35 問題就被清掉。
  • aRiderGoneFromTheStopAnyOtherWayHasWalkedAwayFromTheQuestion:往路線旁邊 420 m、以及沿路線往回 420 m,問題仍然被撤掉。
  • Mutation:前進也算離開、只要在路線上就算、不在路線上也算——3 個都有測試轉紅。最後一個第一次是存活的,補了「人在另一條路上、和下游某點平行」那一段(在 de71e16)之後才被殺。

取捨

沿著路線往下游走路超過 400 m 的人(例如走去下一站)現在也會保留問題,所以可能被問一次「你有上車嗎?」。在只有站牌 ETA、沒有車機位置的情況下,這兩種人分不出來;問一次比完全不提醒好。問題本身 5 分鐘的期限不變。

// The badge shows the soonest bus still to come. What was observed is
// the soonest estimate of any variant, run out or not: an estimate at
// -1 is the bus that is at the stop, and the one to watch leave.
observedSeconds = stops.mapNotNull { it.observedSeconds }.minOrNull(),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P2] Preserve per-variant arrival semantics and timestamp provenance when merging. For the same boarding stop, suppose variant A reports eta=-1, is_arriving=false without an earlier watched countdown, while B reports eta=0, is_arriving=false. The aggregate selects -1, so onBoardingStopEta ignores it as an unwatched expired estimate even though B's zero means due; when both advance to 600, no arrival was opened and the departure/boarding fallback is missed. Separately, taking min ETA and max timestamp independently can attach B's newer time to A's unchanged value, replaying it as a fresh observation. Keep values with their originating timestamp and combine the per-source due/rollover semantics rather than choosing an unrelated minimum and maximum. A saved TPE157463 payload establishes that -1/non-arriving exists; this mixed-family transition and timestamp sequence are modeled, not observed in a live ride. Static source trace only; relates to but is distinct from the isolated historical S3/S4 cases.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

已在 de71e16 修正,兩個部分都處理了,而且 Flutter 那一側的合併也一起改(它有同樣的「挑最小的」問題)。

修法

  • 合併後的站牌不再只有一個「observed ETA」加一個「observed 時間」。LiveStopState.observations 保留每條路線各自的 (source, seconds, atMs),估計值和它自己的觀測時間綁在一起;mergeStops 只是把各路線的觀測並列,不再各取 min/max。
  • Detector 新增 onBoardingStopFeed(estimates: List<StopEstimate>, …),每條路線的估計各自判斷:
    • 任何一條路線有車到站(0–30 秒,或接在同一條路線看得到的倒數後面的負數)就是有車到站。所以 A 的 -1(沒人在倒數)不會蓋掉 B 的 0。「最近有有效估計」改成每個來源各記各的,A 的倒數不能替 B 的 -1 背書。
    • 跳號看的是還沒到的估計裡最小的那個;只剩用完的負數時不算跳號。
  • 時間來源:service 對上車站記下每條路線「已經告訴過 detector 的最新觀測」。只有比它新的才算新消息;這次沒有更新的路線,以它上次的值一併交給 detector,但標成 observedNow = false——它不會重新開啟或延長到站視窗(不會讓同一班車「再到站一次」),不過只要它仍然有車到站,其他路線跳號就不算那班車離站。沒更新的路線超過 90 秒就不再保留。
  • Flutter:mergeRouteFamilyStopLiveData 另外保留 routeObservations(每條路線的 sec 與 etaReferenceAt),bridge 以 observations: [{source, eta, atMs}] 送出;native 兩個來源(App 送的、自己抓的)用同一個路線 ID 當 source,所以同一筆觀測不論從哪邊來都只算一次。

測試

  • aBusOneRouteOfTheFamilyHasDueIsDueWhateverAnotherRoutesEstimateSays(service):你列的情境——A -1/B 0,之後都變 600,要產生離站問題。修正前沒有。
  • aRouteOfTheFamilyNotHeardFromAgainIsNotItsBusArrivingAgain(service):B 有車到站、只有 A 更新時,到站時間不被刷新、也不算離站;B 更新成 900 之後才算離站。修正前到站時間被刷新。
  • eachRoutesEstimateForTheStopIsReadByItself(detector):上面四種組合,包含「A 的倒數不能讓 B 的 -1 算到站」。
  • whatEachRouteObservedOfASharedStopStaysItsOwn、aStopSaysWhatTheBackendObservedAndWhen(TripMonitorFamilyRealtimeTest);Dart:a merged stop keeps what each route observed, and when、live data says what the backend observed, and when,以及整條路線合併那個測試裡新增的斷言。
  • Mutation(Kotlin 8 個):只保留一條路線的觀測、各路線共用同一個「最近有有效估計」、沒更新的路線照樣刷新到站時間、沒更新的路線不擋跳號、全部當成新觀測、沒更新的路線永久保留、不解析 App 送來的 observations、App 與 native 用不同的來源名稱——最後都有測試轉紅。其中 3 個第一次是存活的,補了 aRouteOfTheFamilyLongNotHeardFromNoLongerHoldsItsBusAtTheStop、theSameObservationFromTheScreenAndFromTheMonitorsOwnFetchIsOneObservation 以及 detector 測試裡「車還在站上、該路線沒更新」那一段之後才被殺。Dart 端另外 7 個(合併丟掉觀測、沒帶路線 ID、placeholder 也算觀測、bridge 不送、送成 badge 的值、觀測時間取錯欄位、copyWith 丟掉)也都被殺。

限制

  • is_arriving 與「進站/到站」訊息仍然是整個站牌一個旗標,沒有分路線;被標成 arriving 時,這次有更新的每個來源都算有有效估計。
  • 同一條變體在同一個站牌對到兩個站位時,只取第一個。
  • 如你所說,這個混合情境是依程式推出來的,我手上的錄製資料是單一路線的,沒有家族合併的實際樣本可以重放。

if (observedAtMs != null && observedAtMs > liveStopsObservedAtMs) {
liveStopsObservedAtMs = observedAtMs
stopFeedRevision++
synchronized(refreshLock) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P2] Gate the boarding stop by its own observation time, not the newest timestamp of any stop in the screen payload. For one trip, let the first accepted map have boarding (t=10, ETA=0) and another stop t=30; the next map has boarding (t=20, ETA=600) but the other stop remains t=30. The global maximum has not advanced, so the second map is dropped although the boarding observation is new, and the detector misses its 0→600 rollover. The Flutter bridge carries individual stop timestamps and family merge can choose different contributors. Native polling may independently recover the observation, but can be delayed/backed off and need not see this transition. This is a source-level modeled per-stop sequence, not an observed live ride; it is distinct from S4's repeated identical boarding observation.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

已在 de71e16 修正。

修法

  • 拿掉整份 payload 共用的那個「最新觀測時間」。上車站要不要餵給 detector,只看上車站自己的觀測(而且如上一則所述,是分路線看的),和其他站牌的時間無關。
  • 快取也改成逐站判斷:takeUpStopsFromTheApp 對每個站牌各自比對「這個站牌、這條路線目前收過的最新觀測」(stopObservationsTaken,App 送來的和自己抓的都記),是新消息的站牌才取代快取裡的那一站。
  • 「App 的資料可以頂替一次自己抓取」現在以上車站為準:上車站有新消息才延後 native 的抓取;只有別的站牌更新時,native 照自己的排程抓。沒選上車站時,任何站牌有新消息都算。

測試

  • theBoardingStopIsNewsWhenItIsEvenIfAnotherStopWasObservedLater:你列的序列——第一份上車站 (t, ETA 0)、另一站 t+20;第二份上車站 (t+10, ETA 600)、另一站不變。斷言:產生離站問題,而且快取裡上車站是 600。修正前第二份整份被丟掉。
  • 既有的反向保護仍然通過:aStopTheScreenHasOnlyOldDataForIsNotNewsBecauseAnotherStopIs、theSameObservationSentAgainDoesNotPutOffTheMonitorsOwnFetch、anObservationOlderThanOneAlreadyTakenIsNotTheEstimateRollingOver、theMonitorFetchesForItselfWhileTheRouteScreenHasNothingNew。
  • Mutation(5 個):只有整份 payload 有更新時才餵 detector、任何站牌有新消息都延後抓取、自己抓到的觀測不列入已收、過舊的站牌也算新消息,加上「第一次只有別站有消息時站牌 feed 要立刻到期」——5 個最後都有測試轉紅。其中 2 個第一次存活,補了 newsOfOtherStopsDoesNotPutOffFetchingTheBoardingStop 與 whatTheMonitorFetchedIsNotReplacedByAnEarlierObservationFromTheScreen。

行為變更

App 在前景、但畫面對上車站一直沒有新資料時(其他站有),native 現在會自己抓站牌 feed,約每 20 秒一次;先前只要任何一站有新資料就不抓。

val applied = applyToTrip(trip) {
// A confirmed ride survives family updates, but an endpoint
// removed from its family must not publish an in-flight result.
if (routeId !in this.session?.realtimeRouteIds.orEmpty()) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P2] Include a request/family generation in this guard. On a confirmed ride, start B request R1, remove B from the family (its refresh state is removed), re-add B and start R2, then let R1 return while R2 is in flight. The detector and current route membership still match, so R1 writes into R2's refresh slot: success clears its in-flight state and can permit an extra R3, while failure installs a 60-second retry/backoff or a late failure can replace newer bookkeeping. Route-screen family enrichment can drop and later restore a variant on a transient failure. Reject responses belonging to a removed generation, including failure/abandon callbacks. Per-vehicle GPS ordering limits stale-position overwrite; this report claims the deterministic conditional bookkeeping race, not an observed incorrect notification. Static trace only; different from historical S5's independent-feed scheduling.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

已在 de71e16 修正。

修法

每次送出某條路線的車機請求時,在它的 BusFeedRefresh 上放一個只屬於這次請求的標記(request,取代原本的 inFlight 布林)。回應、失敗、以及例外路徑的 abandon,都要先確認那個標記還是自己的才會動 bookkeeping;不是的話整個回應丟掉(車輛也不交給 detector)。

路線被移出家族時它的狀態會被刪掉,加回來是新的狀態、新的標記,所以 R1 回來時對不上 R2 的標記:不會清掉 R2 的「請求在外」、不會替它裝上 60 秒的 back-off,也不會蓋掉較新的紀錄。原本「路線還在不在家族裡」的檢查被這個標記涵蓋了。

測試

  • anAnswerForARouteSinceDroppedFromTheFamilyAndPutBackIsNotThisRequestsAnswer:已確認上車的乘車中,B 的 R1 在外 → 家族拿掉 B → 加回 B、R2 送出 → R1 回來(R2 還在外)→ 90 秒後再 refresh。斷言 B 只被請求過兩次。修正前是三次。
  • 上一輪的 aRequestOfTheLastTripThatBlowsUpDoesNotFreeThisTripsFeed、aFeedWithARequestOutIsNotAskedForAgain 仍然通過。
  • 要老實說的一點:這個測試第一版其實沒有測到東西。乘車沒設目的地,確認上車後馬上被暫停去問目的地,後面變成新的行程,R1 是被「行程已換」擋掉的,不是被標記擋掉的;而且它在 refresh 之後立刻數請求數,請求卻是在別的執行緒上才送出。Mutation 把標記檢查拿掉它照樣通過,我才發現。現在乘車有目的地、斷言 detector 全程是同一個,並且等這次 refresh 自己的請求都回來之後才數。上一輪的 aRequestOfTheLastTripThatBlowsUpDoesNotFreeThisTripsFeed 有同樣的「太早數」問題,也一起改了。
  • Mutation(2 個):任何回應都算數、任何請求的失敗都能 abandon——都有測試轉紅,後者靠新增的 aFailureForARouteSinceDroppedFromTheFamilyAndPutBackIsNotThisRequestsFailure。

站牌 feed 那一側只有一個請求旗標,換行程時由 detector 身分擋掉;同一行程內家族變動時,舊請求回來的資料會以舊的家族組合存進快取、下一次 refresh 就因組合不符重抓,我沒有另外加標記。

…nd keep that question for a rider carried off

Review of c2d4035, the two P1s.

An answer to a question that was no longer the one pending was still
acted on. "I have boarded" tapped on the question about bus A, and
delivered after A's question had been turned down or replaced by one
about bus B, confirmed a ride: it named no bus, but it set the rider on
board, withdrew B's question and ended the boarding checks. The trip was
the same, so the trip check let it through. A late "not yet" likewise
moved the mark that says which of the rider's movement still counts as
evidence, discarding what they had done since.

Both answers now do nothing at all unless they are for the question
pending when they arrive, and the service leaves the ride, its alerts and
the prompt on screen alone when one is not. "I have boarded" with no
question attached is heard as before.

So that a question on screen can always be answered: when another bus
leaves and the rider is to be asked afresh, the prompt already showing is
given the new question's buttons at once, quietly, instead of standing
with buttons that have stopped working until the new one falls due. It
alerts again when it does.

The pending question was also dropped once the rider was 400 m from the
boarding stop, taken as having walked away. With no vehicle positions,
a rider who boarded the bus that left is 400 m off within half a minute,
before the question is due and before their own progress amounts to a
ride; if their fixes stop there, nothing ever asks and nothing confirms,
and the destination reminders never start. Being on the route beyond the
boarding stop is where that bus went, and no longer retires the question.
Off to one side, or back up the route, still does.

Also makes aFetchStillInFlightForTheLastTripDoesNotReachTheNextOne
independent of timing: the new trip's own first refresh could run before
the test's backend had switched to the new trip's answers.
…stop, request by request

Review of c2d4035, the three P2s.

A stop the routes of a family share was merged into one observation: the
soonest estimate of any of them, with the latest moment any of them was
observed. Neither half was right. One route's estimate that had run out
unwatched (-1) hid another's bus due this moment (0), so no arrival was
opened and the departure that followed was missed. And the soonest
estimate with the latest moment is an observation nobody made: one
route's unchanged value was told again as new each time another route
was observed.

A stop now keeps what each route observed, estimate and moment together,
and the detector reads each by itself. Any one of them makes a bus due; a
run-out estimate counts only after a countdown watched from that same
route. The service tells the detector when any route's observation is
new, and gives it the others as they last stood, marked as nothing new:
they open nothing and renew nothing, but while one still has a bus due
the others moving on is not that bus leaving. One not heard from for a
minute and a half is dropped. The route screen's own merge keeps the same
per-route observations and sends them, and both channels name a route the
same way, so one observation is one observation whichever way it comes.

What the route screen sends was taken up, or not, as a whole, by the
newest observation anywhere in it. A boarding stop observed anew in an
update whose newest stop was already known was dropped, and its estimate
rolling over with it. Stops are now taken up one by one, against what has
been taken for that stop and route so far, from either channel. News of
the boarding stop is what stands in for the monitor's own fetch; news of
other stops alone no longer puts that fetch off.

A route's vehicle request is now marked on its bookkeeping, and only the
answer, or failure, of the request so marked may change it. A route
dropped from the family and put back starts over with a new request; the
answer to the one from before used to clear the new one's mark, letting a
third go out, or leave the route backing off for a failure not its own.

Tests that counted requests right after a refresh now wait for the
refresh's own requests to settle first: requests go out on threads of
their own, and two of last round's tests could pass without having seen
what they were looking for.

@Av1anJay Av1anJay left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Follow-up review — de71e16

謝謝補充五個修正與測試,也特別謝謝指出並修正原本會假綠的 request 測試。依目前程式與測試斷言,上一輪五個原始重現情境均已修正:過期回答、沿線 420m、家族 ETA 數值與時間來源、逐站 watermark、變體移除/加回的 request generation。以下是這次交互檢查發現的不同條件序列;其中到站旗標與 watermark 與第三項原問題相關,但不是重複其已修好的 -1/0 案例。

需要處理四個問題:舊行程在重設後搶佔新行程的 feed、回答處理途中產生新題目而誤拒下一班、家族舊到站旗標被新觀測重播、過期 observation 的 watermark 被刪除後又接受同一筆資料。詳見 inline。

證據限制:上述 Android 行為皆為靜態程式路徑/條件事件順序追蹤,家族多來源轉換不是實際乘車觀測,也未在此機執行 Kotlin、Robolectric 或裝置測試。Actions run 44120173361 的 exact-head merge 之 Verify log 顯示 Flutter analyze 無問題、553 個 Flutter 測試與 2 個 Chrome geometry 測試通過;Android job 建置 APK/AAB,未執行 Android unit tests。先前本機 Kotlin 編譯在資源受限環境逾時,未重複執行。

(state.fetchedAtElapsedMs == null ||
nowElapsed - state.fetchedAtElapsedMs >= LIVE_BUS_REFRESH_INTERVAL_MS))
}.associateWith { Any() }
busesDue.forEach { (routeId, request) ->

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P1] 舊行程可能在新行程重設後才預約 feed,讓新行程永久等一個不會被清掉的請求。具體順序:IO thread 的 refreshTrip 已在 885 取到 A,但在 895 前被切走;主執行緒建立 B 並在 400 forgetLiveFeeds();A 恢復後在此以舊的 trip 佔用 stop in-flight 和共用 route 的 bus request。單一 IO executor 接著處理 B,看到這兩個 feed 已 in-flight 而不再發送;A 成功或例外時,applyToTrip 因 detector 已換而跳過其清理,因此這些標記不會因時間到期。B 後續同一行程也不會重設它們;前景畫面可能補上站牌資料,但不會解除 bus request,背景車機/站牌抓取可能一直停到下次換行程。請在持有與換行程一致的鎖時驗證 trip 身分再預約,或讓 reservation 有自己安全的 generation/清理機制。這是靜態鎖與排程交錯追蹤,未執行併發測試;不同於已修的 變體 R1/R2 回覆。

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

已在 ad64335 修正。

修法

採用你建議的第一種:requestLiveData 現在先拿 detectorLock(換行程用的那把鎖),確認 detector 還是這次 refresh 拿到的那個,才在裡面拿 refreshLock 做預約;不是的話直接返回,什麼都不標記。鎖的順序和其他地方一致(detectorLock → refreshLock)。

換行程時 forgetLiveFeeds() 也是在 detectorLock 裡執行,所以兩者只有兩種順序:預約在前——標記被 forgetLiveFeeds() 清掉,舊請求回來時被 detector 身分擋掉;換行程在前——舊 refresh 看到 detector 已換,不預約。stopTracking() 把 detector 設成 null 之後才清 feed 狀態,中間插進來的 refresh 同樣會被擋下。

測試

  • aRefreshThatPickedUpTheLastTripDoesNotTakeUpThisTripsFeeds:照你列的順序——先取得行程 A(currentTrip())、主執行緒換成 B(同一條路線的反向,端點相同)、再用 A 呼叫 requestLiveData。之後過 60 秒 refresh,斷言 B 的車機與站牌 feed 都有被請求。修正前兩個都沒有。
  • Mutation(1 個):拿掉身分檢查 → 這個測試轉紅。

限制

這是用測試直接排出那個交錯順序(IO thread 被擋住時在主執行緒換行程),不是真的併發壓力測試。

if (answeredCheckId != null && answeredCheckId != pendingCheckSinceMs) {
return false
}
noteDepartures(nowMs)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P1] ID 檢查與真正消費題目之間,noteDepartures 自己可能換題。假設 A 題已待答至少 90 秒,先前 snapshot 看過 B 在站上;乘客在 B 離站前點 A 的「還沒上車」,B 離站回報在 intent 處理前進入 onBusReports,但尚未 snapshot。此處檢查時 A 仍 pending,noteDepartures 接著在 983–1007 發現 B,並在 1056–1069 把 pending ID 更新成 B 的新題;隨後 664–680 卻把 B 列為拒絕車輛並清掉新題,service 也撤掉通知。若乘客之後搭上 B,這個回答本來不能排除 B;B 又被拒絕 20 分鐘,可能錯失上車與後續到站提醒。請保留答案原本涵蓋的 departures,並在計數導致換題時避免消費/拒絕新題。正向確認表示乘客確實已上車,將其保留但不猜車牌是不同語意,不是這項主張。這與 舊 ID 在進入 handler 時已失效 的已修案例不同;以上是靜態事件順序。

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

已在 ad64335 修正。

修法

declineBoarding 在呼叫 noteDepartures 之前先記下「這一題當時涵蓋的 departures」和題目 ID。計數之後如果題目 ID 變了(計數本身讓乘客被重新問):

  • 回答只套用在原本那一題涵蓋的車上:只有它們被列為拒絕、進 declinedDepartures。
  • 新題目不清掉,只把已經回答過的 departures 從裡面拿掉,所以新題目只剩剛離站的那班車。
  • Service 這邊照舊撤掉畫面上的通知(那是舊題目的),新題目 40 秒後到期時才重新顯示。

題目沒換的情況不變:90 秒內離站的車是「併進同一題」,回答時一併算進去。

「我已上車」沒有動,如你所說那是不同語意(保留確認、不猜車牌),上一輪已處理。

測試

  • notYetIsNotSaidOfABusThatHasTheRiderAskedAfreshAsItIsCounted(detector):A 的題目掛了 100 秒以上,B 進站被 snapshot 看過,B 離站的回報進來後、snapshot 之前回答 A 的「還沒上車」。斷言:回答被採用;新題目仍在、ID 不同、40 秒後到期;對新題目答「我已上車」追蹤的是 B(表示 A 仍被排除、B 沒被排除)。修正前新題目被清掉。
  • notYetIsNotSaidOfABusWhoseLeavingHasTheRiderAskedAfresh(service):同一個順序,用通知上實際的 PendingIntent。
  • notYetToTheQuestionABusHasJoinedIsSaidOfThatBusToo(detector):反向保護——B 在 90 秒內離站(併入同一題)時,回答仍然涵蓋 B,不會留下題目。
  • Mutation(4 個):回答套用到新題目的車、清掉新題目、已回答的車留在新題目裡、併入同一題的車不算被回答——都有測試轉紅。最後一個第一次存活,補了「站牌 feed 之後指名回報那班車離站時不再問」的斷言才被殺。

限制

順序是直接呼叫 onBusReports 再送 intent 排出來的,不是實機上的派送時序。

.filter { id -> liveStop.etaEntries.none { normalizeVehicleId(it.vehicleId) == id } }
.map { StopFeedBus(vehicleId = it, etaSeconds = null) }
synchronized(detectorLock) {
target.onBoardingStopFeed(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P2] 分來源去重只套在 estimates,沒有套在這裡合併後的 arriving/buses。例如 B 一次回報 is_arriving=true,之後 B 留在 batch 快取但觀測時間不變;A 不斷提供較新的非到站估計。每次 A 是 news,整份 liveStop.etaEntries 仍含 B 舊旗標,1182 將 arriving=true 傳入 detector;TripRideDetector 421、434–450 因而重新更新 etaArrivingAtMs,也可能給本次更新的 A 補上 live 時間。結果舊的 B 到站被反覆當成新的,並可讓真實的離站 rollover 一直無法觸發;沒有車機定位時會漏掉上車確認。需要讓到站旗標及車輛項目也保留來源/時間並依該來源是否為 news 處理。這是 前次家族來源問題 的不同旗標路徑;其數值 -1/0 範例已修。已有保存的 TXG300 實際 payload:path 0 stop 16564、eta=-1、eta_reference_at=1794795873、plate EAL-5389 的 is_arriving=true;上面的多路線連續變化是靜態模型,並非實際乘車重播。

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

已在 ad64335 修正,Flutter 那一側也一起改(App 在前景時合併是它做的,有同樣的問題)。

修法

到站旗標和車輛項目現在跟估計值一樣,跟著「哪條路線說的」走:

  • StopObservation 多一個 arriving:該路線自己的 feed 有車輛 is_arriving,或它自己的訊息是進站/到站。StopEstimate 帶著它進 detector,onBoardingStopFeed 不再有整個站牌共用的 arriving 參數。
  • Detector 裡:沒更新的路線的旗標不會重新開啟或延長到站(不更新 etaArrivingAtMs),也不會替這次有更新的其他路線補上「最近有有效估計」;但它仍算「那條路線還有車在站上」,所以別的路線跳號不算那班車離站——和上一輪估計值的規則一致。
  • 車輛項目:LiveEtaEntry 記下列出它的路線(sources),StopFeedBus 多一個 observedNow。列出它的路線這次都沒更新時,不會再次把那台車記成「在站上」(etaArrivingVehicles 的時間不動)。
  • 同一台車被兩條路線以相同內容列出時,合併成一筆、來源是兩條路線;任一條有更新就算這次有看到。(這是自審時補的:原本只記第一條。)
  • Flutter:StopRouteObservation 多了 isArriving、msg;StopEta 多了 routeIds;bridge 在 observations[] 送 arriving/message,在 etas[] 送 routes。

測試

  • aBusARouteOfTheFamilyFlaggedAsArrivingIsNotArrivingAgainWhenAnotherRouteIsObserved(service):你列的情境,用你提到的那筆 payload 的形狀(eta=-1、EAL-5389 is_arriving=true)——B 回報一次後時間不變,A 連續更新兩次。斷言 etaArrivingAtMs 與該車「最後在站上」的時間都沒動、沒有離站問題;B 更新成 900 之後才產生離站問題。修正前第一次 A 更新時到站時間就被刷新。
  • whatTheScreenMergedOfAFamilyIsReadRouteByRouteToo(service):同樣的情境走 App 送來的合併資料。
  • aBusTwoRoutesOfTheFamilyListIsSeenAtTheStopWhenEitherIsObservedAgain(service):兩條路線都列出同一台車,只有一條更新時仍算有看到。
  • aBusOneRouteFlagsAsArrivingIsThatRoutesToSay(detector):旗標沒更新時不重開到站視窗;更新後離站並且指認出那台車;A 的 -1 不能靠 B 的旗標算成到站;只有旗標沒有估計值也算到站。
  • TripMonitorFamilyRealtimeTest:aBusOneRouteHasArrivingAtASharedStopIsThatRoutesToSay、aStopSaysABusIsArrivingByAVehiclesFlagOrItsMessage、whatTheScreenMergedSaysWhichRouteSaidWhat、aBusTwoRoutesListAlikeIsOneBusListedByBoth。
  • Dart:a merged stop keeps what each route observed, and when、live data says what the backend observed, and when 都加了旗標、訊息、車輛來源的斷言。
  • Mutation:Kotlin 15 個(沒更新的旗標不再算有車在站、沒更新的旗標重開到站、旗標替別的路線補倒數、沒更新的旗標讓車牌無法指認、沒更新路線的車再次記成在站上、service 把每台車都當成這次看到、要每條路線都更新才算看到、service 丟掉旗標、解析不讀車輛旗標/訊息/App 送的旗標/App 送的訊息/車輛來源、合併只留第一條路線、只被列出的車沒有來源)最後都有測試轉紅;其中 3 個第一次存活,補了「另一條路線自己有車到站時,沒更新路線的車也不重新記成在站上」與只被列出車輛的來源斷言之後才被殺。Dart 9 個也都被殺。

行為變更/限制

  • 上一輪我列的限制「is_arriving 與進站/到站訊息仍然是整個站牌一個旗標」不再成立,這次就是修它。
  • 沒更新路線列出的車,仍然會被記進「四分鐘內附近的車」(etaNearbyVehicles)。這只會讓離站時比較不容易指認車牌,不會產生到站或離站。
  • 同樣如你所說:多路線連續變化是依程式推的,我手上沒有家族合併的實際錄製可以重放。

return
}
news.forEach { told[it.source] = it }
told.values.retainAll { it in news || it.wasMadeRecently(now) }

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P2] 到期時同時刪掉來源的「最後已處理時間」,下一次 native fetch 就會把完全相同的舊 observation 當成 news。例:B 在 t0 回 ETA=0,此後 B 一直回同一個 timestamp;A 持續更新。當 A 的更新使 B 超過 90 秒時,這行把 B 從 told 移除;下一筆含新 A 和舊 B 的 native 回應,1147 因查不到 B 而用 0 當 watermark,重新接受 t0(native 分支又不檢查 wasMadeRecently),並把 B 標為 observedNow,重新開啟/延長到站。其後 A 更新可再次刪掉 B,於是同一快取觀測可反覆到站,干擾離站與上車 fallback。請將永久/足夠長的 last-seen watermark 與 90 秒後應過期的活躍估計分開,或以等效方式禁止舊 native 觀測重播。這是靜態條件序列;保存的真實 payload 確認帶時間戳,但未觀測到該多來源重播。與 已修的跨站 watermark 不同。

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

已在 ad64335 修正。

修法

照你建議的把兩件事分開:

  • boardingStopObservationsToldAtMs:每條路線「已經告訴過 detector 的最新觀測時間」,整個行程都保留,只在換行程/停止追蹤時清掉。是不是新消息只看它。
  • boardingStopObservations:仍然有效的估計值,90 秒後照舊移除(移除後不再擋住其他路線的跳號)。

所以 B 的 t0 觀測過期被移除之後,native 再抓到同一筆,時間沒有比已告知的新,不算新消息,不會被標成 observedNow。

測試

  • anObservationGrownTooOldToCountIsNotNewsWhenItIsFetchedAgain:B 在 t−88 秒回 ETA=0 之後一直回同一個時間戳,A 持續更新。B 超過 90 秒被移除(此時 A 跳號算離站、etaArrivingAtMs 歸零);下一次 fetch 仍帶著同一筆 B,斷言 etaArrivingAtMs 仍是 0。修正前它又被設成當下時間。
  • aNewTripIsToldWhatTheLastOneWasToldAlready:反向保護——換行程後,後端同一筆觀測對新 detector 仍是新消息(watermark 有跟著清)。
  • 上一輪的 aRouteOfTheFamilyLongNotHeardFromNoLongerHoldsItsBusAtTheStop 仍然通過(過期的估計照樣放手)。
  • Mutation(3 個):watermark 跟著估計值一起移除、換行程不清 watermark、估計值永不移除——都有測試轉紅。

限制

沒有時間戳的 native 觀測(eta_reference_at 缺漏)仍然每次都當成新的,這點沒有變;錄製資料裡每個站牌都有時間戳。

…each was said of

Four ways something said of one thing was taken for another.

A refresh reads its trip, then asks for the feeds. With the rider moving on
to another trip in between, the refresh marked the new trip's feeds as asked
for on behalf of the old one — and whatever a request brings back for a trip
that is over is dropped along with its bookkeeping, so nothing ever unmarked
them: no stop feed and no vehicles until the trip changed again. Feeds are
now marked under the lock the trip is replaced under, and only for the trip
still being tracked.

"Not yet" counts the departures reported so far before it is acted on, and
counting one can have the rider asked afresh. The answer then took the new
question with it and set aside the bus that had just left, for twenty
minutes — the one bus the rider had not been asked about. It is now said of
the buses its question covered when it was given; the new question stays.

A route of a family flagging a bus as arriving was read as the stop's flag:
with that route not observed again, every observation of another route made
its bus arrive once more, kept the arrival open and placed its vehicle at the
stop again, so the estimate rolling over never read as a bus leaving. The
flag, and each bus a route lists, now go with that route's observation like
its estimate does — on the monitor's own fetch and in what the route screen
passes on.

An observation of the boarding stop let go of as too old took with it the
record of having been told: fetched again unchanged, it was news, and a bus
due all over again. When each route was last told of is now kept for the
whole trip.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Changes recommended

Both Dart and Android still discard arrival-only ETA entries without estimates or plates, preventing those observations from triggering the boarding question.

2 open issues
What changed in this PR

This PR improves Android boarding detection using the rider’s movement along the route, supported by bus positions and manual confirmation. It also preserves route-family arrival evidence and fixes stop-ID handling for Kaohsiung feeds and launch payloads.

Changes:

  • Adds route projection, location-age handling, and extensive boarding-detection regression tests.
  • Carries arrival flags, observation timestamps, and route ownership through Flutter and native parsing.
  • Standardizes native stop-ID folding while preserving full-width IDs for navigation.
File Description
test/​route_realtime_parsing_test.dart Checks arrival-flag parsing.
test/​route_family_test.dart Tests merged arrival evidence and route ownership.
test/​route_detail_screen_loading_test.dart Tests restarting monitoring after destination selection.
test/​app_routes_test.dart Checks full-width launch IDs.
test/​android_trip_monitor_test.dart Tests observation, location-time, and stop-ID payloads.
lib/​screens/​route_detail_screen.dart Preserves observations and refreshes paused-monitor state.
lib/​core/​route_family.dart Retains each route’s observations and vehicle ownership.
lib/​core/​models.dart Adds arrival and observation metadata.
lib/​core/​bus_repository.dart Parses arrival flags and documents stop-ID handling.
lib/​core/​android_trip_monitor.dart Sends observation metadata and initial location timestamps.
android/​app/​src/​test/​kotlin/​tw/​avianjay/​taiwanbus/​flutter/​TripRideDetectorReplayTest.kt Adds recorded-feed boarding replays.
android/​app/​src/​test/​kotlin/​tw/​avianjay/​taiwanbus/​flutter/​TripRideDetectorManualBoardingTest.kt Tests manual confirmation and vehicle identification.
android/​app/​src/​test/​kotlin/​tw/​avianjay/​taiwanbus/​flutter/​TripRideDetectorDeclineTest.kt Tests rejection handling and subsequent boarding.
android/​app/​src/​test/​kotlin/​tw/​avianjay/​taiwanbus/​flutter/​TripRideDetectorCoMovementTest.kt Tests movement matching and invalid-route rejection.
android/​app/​src/​test/​kotlin/​tw/​avianjay/​taiwanbus/​flutter/​TripMonitorFamilyRealtimeTest.kt Tests native observation parsing and family merging.
android/​app/​src/​test/​kotlin/​tw/​avianjay/​taiwanbus/​flutter/​StopIdCodecTest.kt Tests consistent native stop-ID folding.
android/​app/​src/​test/​kotlin/​tw/​avianjay/​taiwanbus/​flutter/​RideRouteLineTest.kt Tests projection on hairpins and overlapping routes.
android/​app/​src/​test/​kotlin/​tw/​avianjay/​taiwanbus/​flutter/​RideFixTimeTest.kt Tests location timestamp conversion.
android/​app/​src/​test/​kotlin/​tw/​avianjay/​taiwanbus/​flutter/​AppLaunchStopIdTest.kt Tests full-width IDs and legacy shortcut compatibility.
android/​app/​src/​main/​kotlin/​tw/​avianjay/​taiwanbus/​flutter/​TripMonitorFamilyRealtime.kt Preserves arrival observations and shared-stop coverage.
android/​app/​src/​main/​kotlin/​tw/​avianjay/​taiwanbus/​flutter/​StopIdCodec.kt Separates folded lookup IDs from full-width launch IDs.
android/​app/​src/​main/​kotlin/​tw/​avianjay/​taiwanbus/​flutter/​SmartRouteNotificationWorker.kt Uses full-width IDs for notification navigation.
android/​app/​src/​main/​kotlin/​tw/​avianjay/​taiwanbus/​flutter/​RideRouteLine.kt Projects positions into distance along the route.
android/​app/​src/​main/​kotlin/​tw/​avianjay/​taiwanbus/​flutter/​RideFixTime.kt Converts location age into detector timestamps.
android/​app/​src/​main/​kotlin/​tw/​avianjay/​taiwanbus/​flutter/​MainActivity.kt Accepts full-width stop IDs from Flutter.
android/​app/​src/​main/​kotlin/​tw/​avianjay/​taiwanbus/​flutter/​FavoriteGroupWidgetProvider.kt Separates widget lookup and navigation IDs.
android/​app/​src/​main/​kotlin/​tw/​avianjay/​taiwanbus/​flutter/​AppRuntimeStateStore.kt Preserves paused vehicle identity and destination-waiting state.
android/​app/​src/​main/​kotlin/​tw/​avianjay/​taiwanbus/​flutter/​AppLaunchConstants.kt Supports full-width IDs and legacy integer extras.
android/​app/​src/​main/​AndroidManifest.xml Declares wake-lock permission for monitoring.

Review effort: Balanced

?.let { routes -> (0 until routes.length()).mapNotNull { routes.optString(it).takeIf(String::isNotEmpty) } }
?.takeIf { it.isNotEmpty() }?.toSet()
?: setOf(source),
).takeIf { it.seconds != null || it.message != null || it.vehicleId != null }

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

已在 8e744b5 修正。

修法

parseTripMonitorLiveStop 保留條件加上 it.isArriving:只有旗標、沒有估計值/訊息/車牌的項目現在會留下來。完全沒內容的項目(旗標也是 false)照舊丟掉。

留下來之後:observations 的 arriving 為 true(背景抓取可以據此認定有車在站上);進 detector 時是一台沒有車牌、被標成到站的車,所以離站後會問「是否已上車」,但不會指認車牌。

測試(修正前都是紅的)

  • anEntrySayingOnlyThatABusIsArrivingIsStillABusArriving(解析):{"plate":null,"eta":null,"is_arriving":true} 被保留、arriving 為 true;同一個站牌裡旗標為 false 的空項目和 {} 仍被丟掉。
  • aBusTheFeedOnlyFlagsAsArrivingIsABusAtTheStop(service,背景抓取):站牌 eta=null、唯一的項目只有旗標 → 記為有車在站上;之後估計值跳到 811 → 產生離站問題;回答「我已上車」後已上車、沒有車牌。
  • aBusTheScreensCopyOnlyFlagsAsArrivingIsABusAtTheStop(service,App 轉送的資料):同一個情境走 route screen 送來的 liveData。
  • Mutation(5 個):拿掉 isArriving 條件(解析測試、service 測試分開各跑一次都轉紅)、每個項目都保留、只保留有旗標的項目——都有測試轉紅。

限制

  • 這是防禦性修正:目前後端的 _append_stop_eta 在 eta is None 時直接不輸出該項目,_finalize_stop_eta_list 也會再濾一次,所以現行 API 不會送出這種項目。我手上的錄製資料裡也沒有這種形狀,測試用的是你舉的 payload。
  • Android 單元測試只在本機跑(336 個通過),CI 的 Verify 不跑 Kotlin 單元測試;沒有在實機上驗證。

Comment thread lib/core/bus_repository.dart Outdated
estimated: _truthyPayloadValue(rawEta['estimated']),
isArriving: _truthyPayloadValue(rawEta['is_arriving']),
);
if (eta.sec == null && eta.msg == null && eta.vehicleId == null) {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

已在 8e744b5 修正。

修法

_parseStopEtas 的空項目檢查加上 !eta.isArriving:{"eta": null, "plate": null, "is_arriving": true} 現在會保留,完全沒內容的項目照舊丟掉。

保留下來的項目經 TripMonitorStop 送到 native 時是 {'plate': null, 'eta': null, 'observedEta': null, 'message': null, 'is_arriving': true};native 那一側原本也會丟掉它,已在同一個 commit 一起修(見另一則)。

測試

  • an entry saying only that a bus is arriving is kept(route_realtime_parsing_test.dart):走 getCompleteBusInfo 實際解析 realtime 回應,三個項目裡只有帶旗標的那一個留下,sec/msg/vehicleId 都是 null。修正前是紅的。
  • stop entries reach the monitor as the feed has them(android_trip_monitor_test.dart):加了只有旗標的 StopEta,斷言 bridge 原樣送出。這個修正前就會過(bridge 本來就不過濾),只是把格式釘住。
  • Mutation(3 個):拿掉 isArriving 條件、每個項目都保留、只保留有旗標的項目——都有測試轉紅。
  • flutter analyze lib 無問題;完整 flutter test 554 個通過(本機另有 1 個載入失敗來自未追蹤的 test/feedback_screen_test.dart,屬於 PR feat(feedback): add optional context and opt-in diagnostics #116,不在這個分支裡)。

行為變更/限制

  • 這種項目留下來之後,該站牌的 etas 不再是空的,所以 hasRealtimeStopData/_hasEmbeddedLiveData 對「只有這一個項目」的站牌會回 true(視為有即時資料)。畫面上其他讀 stop.etas 的地方只看車牌或訊息,不受影響。
  • 目前後端不會輸出沒有 eta 的項目,所以這是防禦性修正,沒有實際錄到的樣本。

An entry of a stop's `etas` with no estimate, no message and no plate was
dropped as saying nothing — even one flagged `is_arriving`. The flag is
something said of a bus: one at the stop that the feed neither names nor has
an estimate for. Dropped, the stop no longer had a bus arriving, and nothing
armed the question of whether the rider boarded when it left; the route
screen dropped it before it could pass it on, and the monitor dropped it from
its own fetch and from what the screen passed on.

Both parsers now keep such an entry. One that says nothing at all is still
none.

The backend as it stands gives every entry an estimate, so this is for a
feed it does not produce today.

@Av1anJay Av1anJay left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Follow-up review — 8e744b5

目前沒有確認需要阻擋合併的問題。依程式與測試斷言檢查,上一輪四個問題的原始情境均已修正:舊行程搶佔 feed、回答舊問題時誤拒下一班、家族到站旗標跨來源重播,以及 observation 過期後的 watermark 重播。較早的 D1–D9 / S1–S8、變體車輛及無手機定位過站提醒的原始情境,以及最近兩個 arrival-only parser 意見,也有對應修正。這些是針對原始情境的程式與斷言檢查,不代表相關情境都已在 Android 上執行。

審查涵蓋整個 base…head 變更、相關呼叫與狀態轉移、既有 review/作者回覆和獨立交叉檢查;未將缺乏可證實使用者影響的條件性候選當成阻擋問題。

驗證:git diff --check 通過。此 head 的 CI merge 上 flutter analyze 通過、554 個 Flutter 測試與 2 個 Chrome geometry 測試通過;Android job 建置 APK/AAB,沒有執行 Android 單元測試。本機針對此 head 的 SDK-free JVM 測試嘗試逾時中斷,沒有測試結果;也未獨立執行 Robolectric、裝置通知或真實乘車測試。

@AvianJay
AvianJay merged commit dfa3cd2 into main Nov 18, 2026
9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants