[GH-ISSUE #4704] [Issue]: Background-autonomous poll fetches full /chats every 30s app-wide (+ O(messages) DM-cleanup scans per hit; mis-wired 30s character-list invalidation) #2579

Closed
opened 2026-10-21 05:50:34 +07:00 by bsakaguchi · 1 comment
Owner

Originally created by @kolacheee on GitHub (Aug 7, 2026).
Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/4704

Originally assigned to: @kolacheee on GitHub.

Summary

The background-autonomous poller fetches the full /chats list every 30 seconds, app-wide, even when zero chats have autonomous messaging enabled — and each of those GETs also triggers cleanupEmptyRoleplayDmChats, which runs an O(total-messages) countMessages scan per roleplay-DM chat on the file-native store. On a Termux self-host the phone pays both sides of this every 30s for the whole session. A sibling in the active-chat autonomous poll additionally invalidates the full character list every 30s tick — and the invalidation is mis-wired (its stated purpose reads a different cache).

Follow-up from the mobile-battery investigation (#4628/#4629/#4630 round; the reporting Termux user still sees no improvement — this poll is the heaviest remaining client-side chatter).

Expected behavior

Idle-tab network activity near zero when no autonomous chats exist; when they do exist, discovery stays within the current ≤30s window (including chats enabled from another device/tab), with a payload proportional to what the poller actually needs (chat ids), not every chat's full metadata/summary blobs.

Actual behavior

  • useBackgroundAutonomousPolling (packages/client/src/hooks/use-background-autonomous.ts:64, mounted once at AppShell.tsx:239) fetches api.get<RawChat[]>("/chats") every 30s (:92, cadence :332-339, visible-tab gated :80), then filters client-side for conversation chats with metadata.autonomousMessages (:99-110). The full list fetch is the discovery mechanism — it runs forever regardless of whether any chat qualifies.
  • Server side, every GET /chats first runs cleanupEmptyRoleplayDmChats (chats.routes.ts:627-631, :579-594): storage.list() + storage.countMessages per roleplay-DM-thread chat — countMessages is a full messages-table filter (chats.storage.ts:844-847) — then storage.list() again and serializes every chat row including full metadata blobs. All of this every 30s, per open tab.
  • Sibling: use-autonomous-messaging.ts:139-145 — while an autonomous-enabled conversation chat is open, every 30s tick unconditionally invalidates characterKeys.list() (comment says "sidebar status dots"). That prefix refetches the full GET /characters for any active consumer — but the sidebar dots actually read useCharacterSummaries (["characters","summaries"], ChatSidebar.tsx:349), which this invalidation does not match. The header presence dots are served by ConversationPresenceCard, which already polls a lightweight status endpoint and invalidates only on actual signature change (ConversationPresenceCard.tsx:177-204).

Steps to reproduce

  1. Open Marinara (any screen), zero autonomous chats configured.
  2. Network tab: GET /chats every 30s indefinitely while the tab is visible.
  3. Server logs / profiling: each hit walks the messages table per DM chat via the cleanup pass.

Environment

  • Marinara Engine version: staging d6275fa0b
  • Install type: any; battery-relevant on Termux self-host (phone pays radio + server CPU per tick)
  • OS + version: any
  • Browser or app shell: any

Logs, screenshots, or video

Verified by code trace + live measurement on the built client (idle fetch counter). All line references against staging d6275fa0b.

Additional context

Does gating this poll risk losing user edits? (checked explicitly — no)

Concern raised during review: "user edits messages, goes afk, closes Marinara, reopens later — could edits disappear?" Traced end-to-end, twice (design pass + independent adversarial re-trace), verdict: the poll plays zero role in edit persistence. Message edits PATCH immediately at save time via a per-message serialized queue with retry (use-chats.ts:87-104, :1084-1085); the server writes the row synchronously in the request (chats.storage.ts:1040-1057); durability is entirely server-timer-driven (750ms debounced flush + 10s safety interval + beforeExit/close() drains, file-backed-store.ts:154-155, :1207-1225, :1442-1451). No step waits for, or is triggered by, any subsequent client GET /chats. The inverse risk (a stale poll snapshot clobbering a fresh local edit) is also absent: the poll's fetch result is hook-local and never written to any TanStack cache (use-background-autonomous.ts:90-96); its only cache writes happen after a completed background generation, target a non-active chat (:100, :241-248), and the sub-5-minute recentMessageContentEdits overlay (use-chats.ts:174-200, :280) protects fresh edits from stale refetches anyway. (Pre-existing and unchanged by this fix: an edit whose PATCH fails hard while the server is down lives only in the 5-minute client overlay — the poll never protected that case either.)

Regression-safe fix (designed + red-teamed)

Add a lightweight GET /chats/autonomous-candidates endpoint returning [{ id }] for chats where mode === "conversation", parsed metadata.autonomousMessages is truthy, and metadata.internalAssistant !== "professor-mari" (unparseable metadata → skipped, mirroring the client filter at :107-108). Implementation: single storage.list() + per-row metadata parse — no cleanupEmptyRoleplayDmChats, no countMessages scans, no full-metadata serialization. Client: swap the fetch at :92, drop the mode/metadata filtering, keep the activeChatId and generatingForRef exclusions client-side (:100-101) — everything downstream uses only chat.id (verified: :119-124, :133, :136, :146, :202, :241-248, :287). Same 30s cadence → identical ≤30s cross-device discovery; ~99% payload reduction.

Notes from the red-team pass to carry into implementation:

  • Route registration order: register /chats/autonomous-candidates before the parametric GET /chats/:id (chats.routes.ts:827) or it will be captured as id = "autonomous-candidates".
  • Version skew: a new client against an old server would hit the parametric route and error; the poll's catch (:93-96) would swallow it and background autonomous messaging would go silently dead. Client should fall back to the legacy full-/chats fetch when the new endpoint errors or returns an unexpected shape.
  • cleanupEmptyRoleplayDmChats keeps running on real /chats hits (sidebar mount, post-mutation invalidations) — nothing depends on the 30s cadence, but it must not disappear entirely.
  • Sibling fix: drop or re-target the unconditional characterKeys.list() invalidation in use-autonomous-messaging.ts:145 — the presence path already handles dot freshness change-driven; if any consumer genuinely needs it, mirror ConversationPresenceCard's invalidate-on-signature-change pattern instead of every-tick.

Template check

  • I DID NOT read this template and provide the requested details.
Originally created by @kolacheee on GitHub (Aug 7, 2026). Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/4704 Originally assigned to: @kolacheee on GitHub. ## Summary The background-autonomous poller fetches the **full `/chats` list every 30 seconds, app-wide, even when zero chats have autonomous messaging enabled** — and each of those GETs also triggers `cleanupEmptyRoleplayDmChats`, which runs an O(total-messages) `countMessages` scan per roleplay-DM chat on the file-native store. On a Termux self-host the phone pays both sides of this every 30s for the whole session. A sibling in the active-chat autonomous poll additionally invalidates the **full character list** every 30s tick — and the invalidation is mis-wired (its stated purpose reads a different cache). Follow-up from the mobile-battery investigation (#4628/#4629/#4630 round; the reporting Termux user still sees no improvement — this poll is the heaviest remaining client-side chatter). ## Expected behavior Idle-tab network activity near zero when no autonomous chats exist; when they do exist, discovery stays within the current ≤30s window (including chats enabled from another device/tab), with a payload proportional to what the poller actually needs (chat ids), not every chat's full metadata/summary blobs. ## Actual behavior - `useBackgroundAutonomousPolling` (`packages/client/src/hooks/use-background-autonomous.ts:64`, mounted once at `AppShell.tsx:239`) fetches `api.get<RawChat[]>("/chats")` every 30s (`:92`, cadence `:332-339`, visible-tab gated `:80`), then filters client-side for conversation chats with `metadata.autonomousMessages` (`:99-110`). The full list fetch **is** the discovery mechanism — it runs forever regardless of whether any chat qualifies. - Server side, **every** `GET /chats` first runs `cleanupEmptyRoleplayDmChats` (`chats.routes.ts:627-631`, `:579-594`): `storage.list()` + `storage.countMessages` per roleplay-DM-thread chat — `countMessages` is a full messages-table filter (`chats.storage.ts:844-847`) — then `storage.list()` **again** and serializes every chat row including full metadata blobs. All of this every 30s, per open tab. - Sibling: `use-autonomous-messaging.ts:139-145` — while an autonomous-enabled conversation chat is open, every 30s tick unconditionally invalidates `characterKeys.list()` (comment says "sidebar status dots"). That prefix refetches the full `GET /characters` for any active consumer — but the sidebar dots actually read `useCharacterSummaries` (`["characters","summaries"]`, `ChatSidebar.tsx:349`), **which this invalidation does not match**. The header presence dots are served by `ConversationPresenceCard`, which already polls a lightweight status endpoint and invalidates only on actual signature change (`ConversationPresenceCard.tsx:177-204`). ## Steps to reproduce 1. Open Marinara (any screen), zero autonomous chats configured. 2. Network tab: `GET /chats` every 30s indefinitely while the tab is visible. 3. Server logs / profiling: each hit walks the messages table per DM chat via the cleanup pass. ## Environment - Marinara Engine version: staging d6275fa0b - Install type: any; battery-relevant on Termux self-host (phone pays radio + server CPU per tick) - OS + version: any - Browser or app shell: any ## Logs, screenshots, or video Verified by code trace + live measurement on the built client (idle fetch counter). All line references against staging d6275fa0b. ## Additional context ### Does gating this poll risk losing user edits? (checked explicitly — no) Concern raised during review: *"user edits messages, goes afk, closes Marinara, reopens later — could edits disappear?"* Traced end-to-end, twice (design pass + independent adversarial re-trace), verdict: **the poll plays zero role in edit persistence.** Message edits PATCH immediately at save time via a per-message serialized queue with retry (`use-chats.ts:87-104`, `:1084-1085`); the server writes the row synchronously in the request (`chats.storage.ts:1040-1057`); durability is entirely server-timer-driven (750ms debounced flush + 10s safety interval + `beforeExit`/`close()` drains, `file-backed-store.ts:154-155`, `:1207-1225`, `:1442-1451`). No step waits for, or is triggered by, any subsequent client `GET /chats`. The inverse risk (a stale poll snapshot clobbering a fresh local edit) is also absent: the poll's fetch result is hook-local and never written to any TanStack cache (`use-background-autonomous.ts:90-96`); its only cache writes happen after a completed background generation, target a non-active chat (`:100`, `:241-248`), and the sub-5-minute `recentMessageContentEdits` overlay (`use-chats.ts:174-200`, `:280`) protects fresh edits from stale refetches anyway. (Pre-existing and unchanged by this fix: an edit whose PATCH fails hard while the server is down lives only in the 5-minute client overlay — the poll never protected that case either.) ### Regression-safe fix (designed + red-teamed) Add a lightweight **`GET /chats/autonomous-candidates`** endpoint returning `[{ id }]` for chats where `mode === "conversation"`, parsed `metadata.autonomousMessages` is truthy, and `metadata.internalAssistant !== "professor-mari"` (unparseable metadata → skipped, mirroring the client filter at `:107-108`). Implementation: single `storage.list()` + per-row metadata parse — **no** `cleanupEmptyRoleplayDmChats`, **no** `countMessages` scans, **no** full-metadata serialization. Client: swap the fetch at `:92`, drop the mode/metadata filtering, **keep** the `activeChatId` and `generatingForRef` exclusions client-side (`:100-101`) — everything downstream uses only `chat.id` (verified: `:119-124`, `:133`, `:136`, `:146`, `:202`, `:241-248`, `:287`). Same 30s cadence → identical ≤30s cross-device discovery; ~99% payload reduction. Notes from the red-team pass to carry into implementation: - **Route registration order**: register `/chats/autonomous-candidates` before the parametric `GET /chats/:id` (`chats.routes.ts:827`) or it will be captured as `id = "autonomous-candidates"`. - **Version skew**: a new client against an old server would hit the parametric route and error; the poll's catch (`:93-96`) would swallow it and background autonomous messaging would go **silently dead**. Client should fall back to the legacy full-`/chats` fetch when the new endpoint errors or returns an unexpected shape. - `cleanupEmptyRoleplayDmChats` keeps running on real `/chats` hits (sidebar mount, post-mutation invalidations) — nothing depends on the 30s cadence, but it must not disappear entirely. - **Sibling fix**: drop or re-target the unconditional `characterKeys.list()` invalidation in `use-autonomous-messaging.ts:145` — the presence path already handles dot freshness change-driven; if any consumer genuinely needs it, mirror `ConversationPresenceCard`'s invalidate-on-signature-change pattern instead of every-tick. ## Template check - [ ] I DID NOT read this template and provide the requested details.
bsakaguchi 2026-10-21 05:50:34 +07:00
Author
Owner

@kolacheee commented on GitHub (Aug 7, 2026):

Scope note: #4703 looks superficially similar (idle network traffic) but is a distinct mechanism — a runaway messages?limit=100 refetch loop (~2.5 req/s, no designed poll exists for that endpoint) vs. this issue's designed 30s /chats list poll. The fix proposed here would not affect #4703; both stay open, cross-linked. #4703's root cause is being investigated separately.

<!-- gh-comment-id:5216232794 --> @kolacheee commented on GitHub (Aug 7, 2026): Scope note: #4703 looks superficially similar (idle network traffic) but is a distinct mechanism — a runaway `messages?limit=100` refetch loop (~2.5 req/s, no designed poll exists for that endpoint) vs. this issue's designed 30s `/chats` list poll. The fix proposed here would not affect #4703; both stay open, cross-linked. #4703's root cause is being investigated separately.
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#2579
No description provided.