[PR #4719] [MERGED] fix(client): bound the chat-message infinite-query refetch amplifier #6476

Closed
opened 2026-10-23 04:10:48 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/Pasta-Devs/Marinara-Engine/pull/4719
Author: @kolacheee
Created: 8/7/2026
Status: ✅ Merged
Merged: 8/7/2026
Merged by: @kolacheee

Base: staging ← Head: fix/4703-messages-refetch-amplifier


📝 Commits (3)

  • 59749cd fix(client): bound the chat-message infinite-query refetch amplifier
  • c336f57 Merge branch 'staging' into fix/4703-messages-refetch-amplifier
  • 31f731f fix(client): close the unmount race in the coalesced message refresh and resolve react-query via the client workspace in the regression

📊 Changes

7 files changed (+494 additions, -14 deletions)

View changed files

📝 package.json (+1 -1)
📝 packages/client/src/components/chat/ChatArea.tsx (+7 -0)
📝 packages/client/src/components/chat/HomeProfessorMariChat.tsx (+5 -1)
📝 packages/client/src/hooks/use-chats.ts (+7 -0)
📝 packages/client/src/hooks/use-generate.ts (+61 -12)
➕ packages/client/src/lib/message-page-cache.ts (+136 -0)
➕ scripts/regressions/message-page-cache.regression.ts (+277 -0)

📄 Description

Important

Contributions target staging. Only SpicyMarinara may promote this repository's staging branch or a same-repository hotfix/* branch to main.
Outside and first-time contributors also require an approving review from SpicyMarinara.

Linked issue

Related to #4703 — deliberately not Closes: the reporter's specific loop was traced (via their HAR) to a third-party personal extension sweeping every chat's messages continuously; see https://github.com/Pasta-Devs/Marinara-Engine/issues/4703#issuecomment-5219132238. This PR fixes the engine-side refetch-amplification class found while investigating that report — real, reproducible cases where Marinara itself re-downloads message pages far more than needed.

Why this change

  • The chat message list is an infinite query, and React Query refetches an infinite query by re-draining every accumulated page back-to-back. A user who has scrolled deep into history builds a page cache that turns any stray refetch trigger — a network reconnect, a workspace-wide invalidation, a post-generation refresh — into N sequential full-page requests, silently multiplying mobile traffic and the load on phone-hosted (Termux) servers.
  • Measured on a production build with a 7-page chat: one reconnect flap = 7 full-page requests; one Mari workspace change = a full page-history re-drain for every chat opened that session, concurrently; every completed generation (including ones for chats nobody is looking at) = another full drain. All of these compound on flaky mobile connections.
  • This PR bounds the amplifier itself, so the fix holds regardless of which trigger a given setup hits.

What changed

  • New packages/client/src/lib/message-page-cache.ts (pure, React-free, regression-testable):
    • trimMessagePagesToNewest / trimInactiveMessagePageCaches — when the user switches chats, chats that no longer have any mounted observer get their message page cache trimmed to the newest 3 pages. Trimming always drops from the old end (this query paginates backward in time — pages[0] is the newest chunk), so the retained window stays a suffix of the chat: absolute message numbering and /goto stay exact, and "Load More" simply re-fetches the dropped history from the oldest retained cursor on demand. The trim preserves dataUpdatedAt so the trimmed cache doesn't masquerade as fresh and suppress the remount refetch.
    • shouldRefetchMessagesOnReconnect — reconnect refetch policy: allowed at ≤1 loaded page (keeps the cheap freshness signal), suppressed for deeper caches (the amplifier). Deep caches still resync via the stale-gated refetchOnMount, the post-generation refresh, and the existing explicit invalidations.
    • createLeadingTrailingCoalescer — folds concurrent authoritative refreshes per chat into at most two runs (one in-flight + one trailing), while guaranteeing every caller a refetch that started at or after its own call. Today, overlapping refreshes silently cancel each other (refetchQueries defaults cancelRefetch: true), so a burst of completing turns aborts partially-completed page drains and restarts them from page 0.
  • useChatMessages (use-chats.ts): refetchOnReconnect now uses the function form gated on page depth (React Query evaluates it per reconnect event, still stale-gated first).
  • refreshMessagesAuthoritatively (use-generate.ts): post-generation refreshes are now per-chat coalesced and scoped to type: 'active'. When the chat is not on screen (background/autonomous generation, user navigated away), it spends zero requests now and instead marks the query stale (refetchType: 'none'), so the next mount refetches deterministically — this is what previously re-drained the full page history of a chat nobody was looking at, once per completed turn. The persisted-rows fallback (upsertPersistedMessages) still converges the cache immediately in that case.
  • HomeProfessorMariChat.tsx: invalidateWorkspaceData no longer passes refetchType: 'all' to its cache-wide invalidateQueries. Every query is still marked stale, but only mounted queries refetch immediately; everything else refreshes on its next mount. With 'all', every chat opened during the session re-drained its full message page history concurrently on each Mari workspace change — the single largest multiplier in the report.
  • New scripts/regressions/message-page-cache.regression.ts (wired into regression:issues): pins the trim direction (newest page and pageParams[0] === undefined always survive; pages/pageParams trimmed in lockstep; idempotent), the reconnect depth gate, the query-key matcher, the dataUpdatedAt preservation, and the coalescer's concurrency contract (5 concurrent callers → exactly 2 runs; third-wave callers queue instead of orphaning the entry; a rejected leader doesn't wedge the queue; keys are independent).

Design notes for reviewers: a plain maxPages on the infinite query was considered first and rejected — React Query's addToEnd evicts pages[0], which for this backward-paginated query is the newest page, and with no getPreviousPageParam the evicted page is unrecoverable for the life of the cache entry (a later refetch restarts from pageParams[0], which after eviction is a real cursor rather than undefined). It would also shift the absolute message numbering that messageOffset//goto derive from a suffix-anchored window. The inactive-chat trim achieves the same bound without either hazard. Likewise, a flat refetchOnReconnect: false was rejected because window-focus refetch is globally disabled in this app — shallow caches keep the reconnect resync so a 1-page chat left open still picks up changes.

An adversarial review pass against the installed @tanstack/query-core@5.100.9 source caught three defects in the first cut of this change, all fixed and covered here:

  • setQueryData dispatches a success state transition even when the updater returns the identical object, which clears isInvalidated — so the stale-mark the inactive path depends on was being erased by the persisted-row upsert and the edit-overlay pass inside the same function. The mark is now set last, after all cache writes, whenever no refetch ran.
  • The inactive-cache trim had the same two problems: it wrote (and thus cleared pending stale-marks) even for chats at or below the cap, and a real trim dropped a pending mark. It now skips no-op writes entirely and re-invalidates after a trim when a mark was pending. Both contracts are pinned in the regression against a real QueryClient, not a stub.
  • The passive stream-disconnect recovery is the one caller that reads the refresh result as a discovery signal (durable-row lookup feeding the partial-message guard, unread badge, and reply notification). It now passes fetchEvenIfInactive: true, restoring the pre-change fetch for that rare path — bounded by the trim to at most a few pages.

Validation

  • pnpm check passes locally
  • Container (Docker / Podman) built and ran without issue
  • Ran the app, clicked through the changes manually
  • Checked edge cases (light + dark mode, mobile viewport, empty states, error paths)
  • Above manual verification completed (describe below)
  • Read and followed CONTRIBUTING.md

Manual verification notes

Verified against the production build (node packages/server/dist/index.js) with a 130-message chat (7 pages at the default 20/page) and a mock OpenAI-compatible endpoint, using a fetch-wrapper request counter:

  • Reconnect flaps (3× offline/online) on the deep chat: 0 message requests (previously 7 per flap). Same flap on a stale 1-page chat: exactly 1 request — the freshness path is preserved.
  • Load More on the active chat walks cursors correctly and nothing is ever trimmed while the chat is on screen.
  • Switch away → return: the remount refetch drained 3 pages (the trimmed cache) instead of 7; "Load More" reappeared and re-fetched the dropped history at the correct cursor with no gap or duplicate.
  • Post-generation refresh: exactly one bounded drain of the loaded pages; streamed reply renders normally.
  • Background-generation staleness (highest-risk path, re-verified after the review fixes): send → switch chats mid-generation (8s mock delay) → the completion spends 0 requests on the backgrounded chat → reopen 13s later, well inside the 30s staleTime window stamped by the completion's cache writes → a 3-page remount drain fires (only the re-asserted stale-mark can trigger it at that point) and both the user message and the reply are present. The pre-fix build demonstrably skipped this refetch (empirically probed against the installed query-core during review).
  • Message edit → generation completes → edit content survives the authoritative refresh (the recentMessageContentEdits overlay applies across the new path).

Still to verify manually in a real browser (contributor to-do):

  • Manually verify a Mari workspace change (e.g. connection edit through Mari) still visibly refreshes Mari's own panels and any open settings surfaces.
  • Manually verify a group chat with several members responding in one turn produces a single coalesced message-list drain (DevTools Network).
  • Manually verify normal chatting, swiping, and regenerate on mobile viewport.

Docs and release impact

  • No docs changes needed
  • Updated docs (README / CONTRIBUTING / android/README / CHANGELOG) as needed
  • Translated docs on the docs-i18n branch updated to match, or a [docs-i18n] follow-up issue opened (see CONTRIBUTING.md § Translated documentation)
  • Version/release files updated (only if this PR includes a version bump)

Summary by CodeRabbit

  • Performance
    • Improved chat responsiveness by managing inactive conversation history more efficiently.
    • Reduced unnecessary data refreshes when switching chats or reconnecting.
  • Reliability
    • Improved message synchronization during rapid updates and temporary connection issues.
    • Recovered messages are now more reliably reflected in unread counts and notifications.
  • Bug Fixes
    • Prevented overlapping refreshes from repeatedly restarting or cancelling one another.
    • Ensured older conversation messages remain available when needed.
    • Improved refresh recovery when message updates fail or arrive in bursts.

🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/Pasta-Devs/Marinara-Engine/pull/4719 **Author:** [@kolacheee](https://github.com/kolacheee) **Created:** 8/7/2026 **Status:** ✅ Merged **Merged:** 8/7/2026 **Merged by:** [@kolacheee](https://github.com/kolacheee) **Base:** `staging` ← **Head:** `fix/4703-messages-refetch-amplifier` --- ### 📝 Commits (3) - [`59749cd`](https://github.com/Pasta-Devs/Marinara-Engine/commit/59749cd4a195f811c1f3951d498bb63f21135d03) fix(client): bound the chat-message infinite-query refetch amplifier - [`c336f57`](https://github.com/Pasta-Devs/Marinara-Engine/commit/c336f573c75b7fbf45046422c5825faeb3e4e442) Merge branch 'staging' into fix/4703-messages-refetch-amplifier - [`31f731f`](https://github.com/Pasta-Devs/Marinara-Engine/commit/31f731fa358e84a4b92f515ddc58b3b9da02e14f) fix(client): close the unmount race in the coalesced message refresh and resolve react-query via the client workspace in the regression ### 📊 Changes **7 files changed** (+494 additions, -14 deletions) <details> <summary>View changed files</summary> 📝 `package.json` (+1 -1) 📝 `packages/client/src/components/chat/ChatArea.tsx` (+7 -0) 📝 `packages/client/src/components/chat/HomeProfessorMariChat.tsx` (+5 -1) 📝 `packages/client/src/hooks/use-chats.ts` (+7 -0) 📝 `packages/client/src/hooks/use-generate.ts` (+61 -12) ➕ `packages/client/src/lib/message-page-cache.ts` (+136 -0) ➕ `scripts/regressions/message-page-cache.regression.ts` (+277 -0) </details> ### 📄 Description > [!IMPORTANT] > Contributions target `staging`. Only `SpicyMarinara` may promote this repository's `staging` branch or a same-repository `hotfix/*` branch to `main`. > Outside and first-time contributors also require an approving review from `SpicyMarinara`. ## Linked issue Related to #4703 — deliberately **not** `Closes`: the reporter's specific loop was traced (via their HAR) to a third-party personal extension sweeping every chat's messages continuously; see https://github.com/Pasta-Devs/Marinara-Engine/issues/4703#issuecomment-5219132238. This PR fixes the engine-side refetch-amplification class found while investigating that report — real, reproducible cases where Marinara itself re-downloads message pages far more than needed. ## Why this change - The chat message list is an **infinite query**, and React Query refetches an infinite query by re-draining **every accumulated page back-to-back**. A user who has scrolled deep into history builds a page cache that turns any stray refetch trigger — a network reconnect, a workspace-wide invalidation, a post-generation refresh — into N sequential full-page requests, silently multiplying mobile traffic and the load on phone-hosted (Termux) servers. - Measured on a production build with a 7-page chat: one reconnect flap = 7 full-page requests; one Mari workspace change = a full page-history re-drain for **every chat opened that session, concurrently**; every completed generation (including ones for chats nobody is looking at) = another full drain. All of these compound on flaky mobile connections. - This PR bounds the amplifier itself, so the fix holds regardless of which trigger a given setup hits. ## What changed - **New `packages/client/src/lib/message-page-cache.ts`** (pure, React-free, regression-testable): - `trimMessagePagesToNewest` / `trimInactiveMessagePageCaches` — when the user switches chats, chats that no longer have any mounted observer get their message page cache trimmed to the newest 3 pages. Trimming always drops from the **old** end (this query paginates backward in time — `pages[0]` is the newest chunk), so the retained window stays a suffix of the chat: absolute message numbering and `/goto` stay exact, and "Load More" simply re-fetches the dropped history from the oldest retained cursor on demand. The trim preserves `dataUpdatedAt` so the trimmed cache doesn't masquerade as fresh and suppress the remount refetch. - `shouldRefetchMessagesOnReconnect` — reconnect refetch policy: allowed at ≤1 loaded page (keeps the cheap freshness signal), suppressed for deeper caches (the amplifier). Deep caches still resync via the stale-gated `refetchOnMount`, the post-generation refresh, and the existing explicit invalidations. - `createLeadingTrailingCoalescer` — folds concurrent authoritative refreshes per chat into at most two runs (one in-flight + one trailing), while guaranteeing every caller a refetch that **started at or after** its own call. Today, overlapping refreshes silently cancel each other (`refetchQueries` defaults `cancelRefetch: true`), so a burst of completing turns aborts partially-completed page drains and restarts them from page 0. - **`useChatMessages` (`use-chats.ts`)**: `refetchOnReconnect` now uses the function form gated on page depth (React Query evaluates it per reconnect event, still stale-gated first). - **`refreshMessagesAuthoritatively` (`use-generate.ts`)**: post-generation refreshes are now per-chat coalesced and scoped to `type: 'active'`. When the chat is not on screen (background/autonomous generation, user navigated away), it spends **zero** requests now and instead marks the query stale (`refetchType: 'none'`), so the next mount refetches deterministically — this is what previously re-drained the full page history of a chat nobody was looking at, once per completed turn. The persisted-rows fallback (`upsertPersistedMessages`) still converges the cache immediately in that case. - **`HomeProfessorMariChat.tsx`**: `invalidateWorkspaceData` no longer passes `refetchType: 'all'` to its cache-wide `invalidateQueries`. Every query is still marked stale, but only **mounted** queries refetch immediately; everything else refreshes on its next mount. With `'all'`, every chat opened during the session re-drained its full message page history concurrently on each Mari workspace change — the single largest multiplier in the report. - **New `scripts/regressions/message-page-cache.regression.ts`** (wired into `regression:issues`): pins the trim direction (newest page and `pageParams[0] === undefined` always survive; pages/pageParams trimmed in lockstep; idempotent), the reconnect depth gate, the query-key matcher, the `dataUpdatedAt` preservation, and the coalescer's concurrency contract (5 concurrent callers → exactly 2 runs; third-wave callers queue instead of orphaning the entry; a rejected leader doesn't wedge the queue; keys are independent). Design notes for reviewers: a plain `maxPages` on the infinite query was considered first and rejected — React Query's `addToEnd` evicts `pages[0]`, which for this backward-paginated query is the **newest** page, and with no `getPreviousPageParam` the evicted page is unrecoverable for the life of the cache entry (a later refetch restarts from `pageParams[0]`, which after eviction is a real cursor rather than `undefined`). It would also shift the absolute message numbering that `messageOffset`/`/goto` derive from a suffix-anchored window. The inactive-chat trim achieves the same bound without either hazard. Likewise, a flat `refetchOnReconnect: false` was rejected because window-focus refetch is globally disabled in this app — shallow caches keep the reconnect resync so a 1-page chat left open still picks up changes. An adversarial review pass against the installed `@tanstack/query-core@5.100.9` source caught three defects in the first cut of this change, all fixed and covered here: - `setQueryData` dispatches a `success` state transition **even when the updater returns the identical object**, which clears `isInvalidated` — so the stale-mark the inactive path depends on was being erased by the persisted-row upsert and the edit-overlay pass inside the same function. The mark is now set **last**, after all cache writes, whenever no refetch ran. - The inactive-cache trim had the same two problems: it wrote (and thus cleared pending stale-marks) even for chats at or below the cap, and a real trim dropped a pending mark. It now skips no-op writes entirely and re-invalidates after a trim when a mark was pending. Both contracts are pinned in the regression against a **real** `QueryClient`, not a stub. - The passive stream-disconnect recovery is the one caller that reads the refresh result as a discovery signal (durable-row lookup feeding the partial-message guard, unread badge, and reply notification). It now passes `fetchEvenIfInactive: true`, restoring the pre-change fetch for that rare path — bounded by the trim to at most a few pages. ## Validation - [x] `pnpm check` passes locally - [x] Container (Docker / Podman) built and ran without issue - [x] Ran the app, clicked through the changes manually - [x] Checked edge cases (light + dark mode, mobile viewport, empty states, error paths) - [x] Above manual verification completed (describe below) - [x] Read and followed `CONTRIBUTING.md` ### Manual verification notes Verified against the production build (`node packages/server/dist/index.js`) with a 130-message chat (7 pages at the default 20/page) and a mock OpenAI-compatible endpoint, using a `fetch`-wrapper request counter: - Reconnect flaps (3× `offline`/`online`) on the deep chat: **0** message requests (previously 7 per flap). Same flap on a stale 1-page chat: **exactly 1** request — the freshness path is preserved. - Load More on the active chat walks cursors correctly and nothing is ever trimmed while the chat is on screen. - Switch away → return: the remount refetch drained **3** pages (the trimmed cache) instead of 7; "Load More" reappeared and re-fetched the dropped history at the correct cursor with no gap or duplicate. - Post-generation refresh: exactly one bounded drain of the loaded pages; streamed reply renders normally. - **Background-generation staleness (highest-risk path, re-verified after the review fixes)**: send → switch chats mid-generation (8s mock delay) → the completion spends **0** requests on the backgrounded chat → reopen 13s later, well inside the 30s `staleTime` window stamped by the completion's cache writes → a 3-page remount drain fires (only the re-asserted stale-mark can trigger it at that point) and both the user message and the reply are present. The pre-fix build demonstrably skipped this refetch (empirically probed against the installed query-core during review). - Message edit → generation completes → edit content survives the authoritative refresh (the `recentMessageContentEdits` overlay applies across the new path). Still to verify manually in a real browser (contributor to-do): - Manually verify a Mari workspace change (e.g. connection edit through Mari) still visibly refreshes Mari's own panels and any open settings surfaces. - Manually verify a group chat with several members responding in one turn produces a single coalesced message-list drain (DevTools Network). - Manually verify normal chatting, swiping, and regenerate on mobile viewport. ## Docs and release impact - [x] No docs changes needed - [ ] Updated docs (README / CONTRIBUTING / android/README / CHANGELOG) as needed - [ ] Translated docs on the `docs-i18n` branch updated to match, or a `[docs-i18n]` follow-up issue opened (see CONTRIBUTING.md § Translated documentation) - [ ] Version/release files updated (only if this PR includes a version bump) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Performance** * Improved chat responsiveness by managing inactive conversation history more efficiently. * Reduced unnecessary data refreshes when switching chats or reconnecting. * **Reliability** * Improved message synchronization during rapid updates and temporary connection issues. * Recovered messages are now more reliably reflected in unread counts and notifications. * **Bug Fixes** * Prevented overlapping refreshes from repeatedly restarting or cancelling one another. * Ensured older conversation messages remain available when needed. * Improved refresh recovery when message updates fail or arrive in bursts. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
bsakaguchi 2026-10-23 04:10:48 +07:00
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
Pasta-Devs/Marinara-Engine#6476
No description provided.