fix: reward pipeline skips abandoned episodes (3 related fixes)
Problem
The reward scoring pipeline processes only ~7 episodes on bootstrap and then goes permanently idle, leaving the vast majority of traces unscored. On a 43 MB database with 3,600 traces, only 45 (1.3%) had r_human scores before fixing.
Root Cause & Fixes
Three interacting bugs, all in apps/memos-local-plugin/:
Fix 1: episodeRewardIsDirty() excluded abandoned episodes
The dirty-check condition only matched closeReason === "finalized" or recoveryReason === "missed_session_end". 219 of 224 closed episodes had closeReason: "abandoned".
Fix: Add closeReason === "abandoned" to the rescore condition + a 10-minute periodic rescore timer.
Fix 2: Daemon HTTP server must bind before core.init()
The daemon bridge started core.init() before startHttpServer(). When init rescores dirty episodes (5+ minutes of LLM calls), port 18800 stays free. The Python watchdog times out its 15-second health probe and spawns a new daemon — killing the in-progress one.
Fix: In daemon mode, bind HTTP server first, then run init asynchronously.
Fix 3: reward.skipped blocked abandoned episodes from recovery
episodeRewardIsDirty() checked reward.skipped === true BEFORE closeReason === "abandoned". The reward runner correctly skipped 173 one-turn episodes in a previous session, but that flag permanently excluded them from recovery.
Fix: reward.skipped is only honored if the episode is NOT (abandoned + no prior recovery). Abandoned episodes get one pass; after that, closeReason is patched to "finalized" and the normal skip guard works.
Verification
- Daemon bridge: 7+ hours uptime, zero restart loops
- All 219 abandoned episodes processed
- r_human scores flowing for traces from May 9 onward
- Closes #1782
Added 4 additional fixes discovered during validation:
-
510cabdb— Migration 013: repair brokentraces_ftstriggers. A previous FTS rebuild used incorrect UPDATE trigger syntax that silently failed on everyupdateScore()call. Scores were computed via ONNX but never persisted to the DB. -
90f60f68— ClearrewardDirtyflag on skip path. Prevents skipped episodes from being re-scanned on every bridge restart. -
f1098bd0— Setr_task=0on skipped episodes. Short-circuit episodes with no qualifying turns so the dirty scan doesn't process them in a loop forever. -
027512f9— Paginate closed-episode dirty scan.clampLimit()caps alllist()calls at 500, so episodes beyond rank 500 were permanently invisible to the scan. Replaced with acollectDirtyClosedEpisodes()helper that paginates through all closed episodes.
Verified across 3 hosts with DBs ranging from 462 to 30K traces.
Thanks for the very thorough investigation here, and for filing #1782 with a clean reproduction — the root-cause write-up was genuinely helpful.
Status: closing this as largely superseded, with one piece that is worth resubmitting on its own (details at the end).
Headline fix already landed
The core of this PR — adding closeReason === "abandoned" to episodeRewardIsDirty() plus the 10-minute periodic rescore timer — was merged to main via #1872 (2026-06-04), which closed #1782. main has since evolved further on top of it (#1808 backoff, #1966 / #1787 trace-count / newer-than checks, #2063 lightweight no-op), so this branch now conflicts.
Re-evaluating the remaining commits against current main
-
Daemon: bind HTTP before
core.init()(bridge.cts).core.init()is now non-blocking (#1758 / #2002): it returns after a synchronous classification pass and runs recovery in the background, so the "init blocks for minutes → 15s health probe times out → replacement daemon → restart loop" premise no longer holds. It also collides head-on with the #1747 startup-ordering invariant and its pinning test. -
reward.skippedone-pass for abandoned + thereward.tsskip-path changes (setRTask(0)/traceCount/ clearingrewardDirty). Onmain,episodeRewardIsDirty()short-circuits onreward.skipped === truebefore therTask == null/ abandoned branch, so the "skipped episodes loop forever" scenario does not occur, and abandoned episodes are already scored via #1872. These no longer apply. -
Migration 013 (traces_fts triggers). This repairs damage attributed to commit
a054c9b8, which is not in this repository's history. Upstream001-initial.sqlalready definestraces_ftswith the canonicaltrace_idcolumn and correct direct-DELETE triggers, matching the JOIN inrepos/traces.ts, and no migration between 002–012 rebuilds it. Running 013 upstream would drop and rebuild the FTS on every user's DB to fix a bug they never had, so it should not be merged here.
The one piece worth keeping: paginated dirty-closed scan
collectDirtyClosedEpisodes() addresses a real gap: main still scans with list({ status: "closed", limit: 500 }), and clampLimit() hard-caps at 500, so closed episodes past rank 500 (newest-first) are invisible to both the startup scan and the periodic rescore. On large DBs those episodes never get scored — consistent with the "dirty-17 at ranks 536–924" you observed.
If you would like to resubmit just this as a small, focused PR against current main, a few things need to be addressed for it to be mergeable:
-
Bound the scan cost (blocking).
episodeRewardIsDirty()is heavier onmainnow — for #1966 / #1787 it issues a per-episodecountExisting(SELECT COUNT) /hasAnyNewerThan(SELECT 1). The current 500 cap incidentally bounds each pass to ~500 of those; removing it makes every startup and every 10-minute tick walk all closed episodes and issue up to O(N) queries even when nothing is dirty. Please add a compensating bound (e.g. acount()short-circuit, a page/row ceiling, or an "already-fully-scored" watermark) and include a measurement on a large DB. -
Pagination stability. OFFSET paging over
started_at DESCwhile new closed episodes are inserted at the top can shift rows across page boundaries (andstarted_atis not unique), risking a skipped row — which would silently reintroduce the exact blind spot this fixes. Keyset / seek pagination on a stable key (idor(started_at, id)) would be more robust than OFFSET. -
Add a boundary test. The behavior being fixed is a scale / boundary bug, so it should be pinned by a test that seeds >500 closed dirty episodes and asserts the one past rank 500 is collected and scored.
tests/unit/storage/traces-count.test.tsalready demonstrates the pattern for seeding >500 rows.
Thanks again — the analysis here was high quality, and a tightly-scoped pagination PR (with a cost bound + a >500 test) would be easy to review and land.