[PR #4716] [MERGED] fix(autonomous): gate the 60s scheduler sweep behind a chats write-generation counter #6475

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

📋 Pull Request Information

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

Base: staging ← Head: fix/4705-autonomous-scheduler-gate


📝 Commits (3)

  • 78aeb79 fix(autonomous): gate the 60s scheduler sweep behind a chats write-generation counter
  • 6db53a2 Merge branch 'staging' into fix/4705-autonomous-scheduler-gate
  • bed41a0 test(regressions): close the write-generation store from the finally path

📊 Changes

4 files changed (+173 additions, -3 deletions)

View changed files

📝 package.json (+1 -1)
📝 packages/server/src/db/file-backed-store.ts (+21 -0)
📝 packages/server/src/services/conversation/server-autonomous-scheduler.service.ts (+59 -2)
➕ scripts/regressions/autonomous-scheduler-gate.regression.ts (+92 -0)

📄 Description

Linked issue

Closes #4705 (from the Termux battery follow-up audit; sibling of #4715/#4704 — client-side autonomous polling — and the pattern-precedent Noodler gate from #4635)

Why this change

The server-side autonomous scheduler ran chats.list() plus a per-chat metadata JSON.parse sweep every 60 seconds, forever, with no opt-in gate — even with zero autonomous chats and zero connected clients. On a phone-hosted (Termux) install that's a permanent idle cost.

What changed

The file-native store has no cheap "any chat enabled?" probe (no indexes; a raw-metadata substring probe would couple to serialization details, where a false negative silently kills the feature — the regression class this design avoids). Instead:

  • Store: a monotonic per-table write-generation counter, bumped at the top of markDirty — the single choke point every insert/update/delete funnels through (including cascades and capability-package writers) — exposed as getTableWriteGeneration on the store controller. Deliberately never rolled back.
  • Scheduler: the poll skips its sweep when a conclusive none-eligible sweep has run and the chats generation is unchanged since. Any chats-table write (including enabling autonomous messages from another device — all writes flow through this server) re-arms it, so pickup stays within one poll interval. Missing counter (non-file-native stores) degrades to always sweeping. Generation is captured before the list, so mid-sweep writes err on the re-sweep side.
  • Two load-bearing properties, both regression-pinned (new autonomous-scheduler-gate.regression.ts, wired into regression:issues):
    1. Inconclusive sweeps prove nothing. The concurrency-cap break fires before eligibility is evaluated, and delayed generations can finish through paths that never write the chats table — so a sweep cut short by the cap or a stop never records the idle conclusion. The gate decisions are exported as pure functions (shouldSkipAutonomousSweep / concludeAutonomousSweep) and the full decision matrix is pinned.
    2. Transaction rollback bumps the counter for every restored table. Store reads are not transaction-isolated, so a poll landing inside a long transaction (the profile-import restore spans minutes — a 60s poll will land in one) can record a conclusion derived from uncommitted rows. Restoring the rows without advancing the generation would let that stale conclusion match the live counter indefinitely — scheduler dormant until an unrelated write. Found by adversarial review with an executed reproduction; the regression suite now replays the exact sequence (mid-transaction sample → rollback → generation must advance past the sample).

Review provenance (tiered): a mechanical 57-site inventory of chats-table writers and scheduler neighbors, classification to 3 suspects, then adversarial verification — 1 real defect confirmed (the rollback dirty-read above, fixed here), 6 gate-semantics points explicitly refuted (capture ordering, stop/cap-break lifecycle equivalence, eligible-chat re-arming, degradation paths, restart behavior, post-generation re-arm correctness).

Known trade-offs (accepted, safe-direction):

  • While two delayed generations hold concurrency slots (long busy-delay windows), every sweep is inconclusive and the gate never engages — full sweeps continue for that stretch. Correct by design: never record conclusions from partial sweeps.
  • A capability package (or any writer) that writes the chats table while idle re-arms the gate — writes legitimately mean "re-check".

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

Automated/scripted checks already performed (green):

  • pnpm check (lint + production build)
  • New regression lane autonomous-scheduler-gate.regression.ts: counter semantics (fresh-zero, insert/update bumps, unrelated-table isolation), the rollback dirty-read sequence, and the full gate decision matrix — all passing against the real file store in a temp dir

Still to verify manually (please tick above once done):

  1. With zero autonomous chats: server logs show the sweep going quiet after the first conclusive poll (no chats.list() churn every 60s).
  2. Enable autonomous messages on a conversation chat (from the UI, and ideally from a second device/tab) → the scheduler picks it up within ~2 poll intervals and background messages behave as before.
  3. Disable it again → after the next conclusive sweep, the scheduler goes quiet again.
  4. Run a profile import that fails/rolls back mid-way → autonomous messaging still works afterward (the dirty-read fix).

Docs and release impact

  • No docs changes needed
  • Updated docs (README / CONTRIBUTING / android/README / CHANGELOG) as needed
  • Version/release files updated (only if this PR includes a version bump)

Summary by CodeRabbit

  • Performance

    • Autonomous scheduling now skips redundant sweeps when no relevant chat changes have occurred.
  • Reliability

    • Incomplete or interrupted sweeps are retried appropriately.
    • Chat updates remain accurately tracked, including changes restored through transaction rollbacks.
  • Tests

    • Added regression coverage for scheduler gating, database write tracking, and rollback behavior.
    • Expanded regression checks to include scheduler and scene-related scenarios.

🔄 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/4716 **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/4705-autonomous-scheduler-gate` --- ### 📝 Commits (3) - [`78aeb79`](https://github.com/Pasta-Devs/Marinara-Engine/commit/78aeb79c43eea333aa29e31df9f6cd27f510a2a9) fix(autonomous): gate the 60s scheduler sweep behind a chats write-generation counter - [`6db53a2`](https://github.com/Pasta-Devs/Marinara-Engine/commit/6db53a2415e14f814068fb8d82eb0202f92d3d8f) Merge branch 'staging' into fix/4705-autonomous-scheduler-gate - [`bed41a0`](https://github.com/Pasta-Devs/Marinara-Engine/commit/bed41a076ae25f07a46999f8957b49caf4d39053) test(regressions): close the write-generation store from the finally path ### 📊 Changes **4 files changed** (+173 additions, -3 deletions) <details> <summary>View changed files</summary> 📝 `package.json` (+1 -1) 📝 `packages/server/src/db/file-backed-store.ts` (+21 -0) 📝 `packages/server/src/services/conversation/server-autonomous-scheduler.service.ts` (+59 -2) ➕ `scripts/regressions/autonomous-scheduler-gate.regression.ts` (+92 -0) </details> ### 📄 Description <!-- Target branch: `staging`. --> ## Linked issue Closes #4705 (from the Termux battery follow-up audit; sibling of #4715/#4704 — client-side autonomous polling — and the pattern-precedent Noodler gate from #4635) ## Why this change The server-side autonomous scheduler ran `chats.list()` plus a per-chat metadata `JSON.parse` sweep **every 60 seconds, forever, with no opt-in gate** — even with zero autonomous chats and zero connected clients. On a phone-hosted (Termux) install that's a permanent idle cost. ## What changed The file-native store has no cheap "any chat enabled?" probe (no indexes; a raw-metadata substring probe would couple to serialization details, where a false negative silently kills the feature — the regression class this design avoids). Instead: - **Store**: a monotonic per-table **write-generation counter**, bumped at the top of `markDirty` — the single choke point every insert/update/delete funnels through (including cascades and capability-package writers) — exposed as `getTableWriteGeneration` on the store controller. Deliberately never rolled back. - **Scheduler**: the poll skips its sweep when a **conclusive** none-eligible sweep has run and the chats generation is unchanged since. Any chats-table write (including enabling autonomous messages from another device — all writes flow through this server) re-arms it, so pickup stays within one poll interval. Missing counter (non-file-native stores) degrades to always sweeping. Generation is captured **before** the list, so mid-sweep writes err on the re-sweep side. - **Two load-bearing properties, both regression-pinned** (new `autonomous-scheduler-gate.regression.ts`, wired into `regression:issues`): 1. **Inconclusive sweeps prove nothing.** The concurrency-cap break fires *before* eligibility is evaluated, and delayed generations can finish through paths that never write the chats table — so a sweep cut short by the cap or a stop never records the idle conclusion. The gate decisions are exported as pure functions (`shouldSkipAutonomousSweep` / `concludeAutonomousSweep`) and the full decision matrix is pinned. 2. **Transaction rollback bumps the counter for every restored table.** Store reads are not transaction-isolated, so a poll landing inside a long transaction (the profile-import restore spans minutes — a 60s poll *will* land in one) can record a conclusion derived from uncommitted rows. Restoring the rows without advancing the generation would let that stale conclusion match the live counter indefinitely — scheduler dormant until an unrelated write. Found by adversarial review **with an executed reproduction**; the regression suite now replays the exact sequence (mid-transaction sample → rollback → generation must advance past the sample). **Review provenance (tiered):** a mechanical 57-site inventory of chats-table writers and scheduler neighbors, classification to 3 suspects, then adversarial verification — 1 real defect confirmed (the rollback dirty-read above, fixed here), 6 gate-semantics points explicitly refuted (capture ordering, stop/cap-break lifecycle equivalence, eligible-chat re-arming, degradation paths, restart behavior, post-generation re-arm correctness). **Known trade-offs (accepted, safe-direction):** - While two delayed generations hold concurrency slots (long busy-delay windows), every sweep is inconclusive and the gate never engages — full sweeps continue for that stretch. Correct by design: never record conclusions from partial sweeps. - A capability package (or any writer) that writes the chats table while idle re-arms the gate — writes legitimately mean "re-check". ## Validation <!-- Required: include commands run and/or manual checks performed --> - [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 Automated/scripted checks already performed (green): - `pnpm check` (lint + production build) - New regression lane `autonomous-scheduler-gate.regression.ts`: counter semantics (fresh-zero, insert/update bumps, unrelated-table isolation), the rollback dirty-read sequence, and the full gate decision matrix — all passing against the real file store in a temp dir Still to verify manually (please tick above once done): 1. With zero autonomous chats: server logs show the sweep going quiet after the first conclusive poll (no `chats.list()` churn every 60s). 2. Enable autonomous messages on a conversation chat (from the UI, and ideally from a second device/tab) → the scheduler picks it up within ~2 poll intervals and background messages behave as before. 3. Disable it again → after the next conclusive sweep, the scheduler goes quiet again. 4. Run a profile import that fails/rolls back mid-way → autonomous messaging still works afterward (the dirty-read fix). ## Docs and release impact - [x] No docs changes needed - [ ] Updated docs (README / CONTRIBUTING / android/README / CHANGELOG) as needed - [ ] 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** * Autonomous scheduling now skips redundant sweeps when no relevant chat changes have occurred. * **Reliability** * Incomplete or interrupted sweeps are retried appropriately. * Chat updates remain accurately tracked, including changes restored through transaction rollbacks. * **Tests** * Added regression coverage for scheduler gating, database write tracking, and rollback behavior. * Expanded regression checks to include scheduler and scene-related scenarios. <!-- 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:46 +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#6475
No description provided.