[PR #4723] [MERGED] fix(server): replace the env-watcher's 2s stat-poll with an event-driven directory watch #6477

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/4723
Author: @kolacheee
Created: 8/7/2026
Status: ✅ Merged
Merged: 8/7/2026
Merged by: @kolacheee

Base: staging ← Head: fix/4707-env-watcher-idle-wakeups


📝 Commits (3)

  • 597270e fix(server): replace the env-watcher's 2s stat-poll with an event-driven directory watch
  • 58a1f24 fix(server): bound the env-watcher debounce deferral, handle bare watcher close, and harden the regression
  • 8b5a488 docs: describe the env-watch default's debounce and automatic fallback in the reference table

📊 Changes

5 files changed (+330 additions, -27 deletions)

View changed files

📝 .env.example (+5 -0)
📝 docs/CONFIGURATION.md (+5 -2)
📝 package.json (+1 -1)
📝 packages/server/src/config/env-watcher.ts (+175 -24)
➕ scripts/regressions/env-watcher.regression.ts (+144 -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

Closes #4707

Why this change

  • The .env hot-reload watcher stat-polled the env file every 2 seconds for the server's lifetime (fs.watchFile is stat-polling, not inotify). That made it the highest-frequency permanent timer on an idle Marinara server — individually cheap, but 30 wakeups/minute forever prevents deep idle on phone-hosted (Termux) installs, where this class of timer is what keeps the battery drain floor up (follow-up from the mobile-battery investigation, alongside #4704/#4705).
  • The no-restart reload path itself is load-bearing (it's how access-control/security config changes take effect without downtime), so the fix keeps the behavior and removes the idle cost.

What changed

All changes in packages/server/src/config/env-watcher.ts plus docs and a new regression:

  • Event-driven watching: fs.watch on the parent directory of the env path, filtered to the file's basename, with { persistent: false } and a 250 ms debounce funneling into the pre-existing mtime/size dedupe. Directory-watching (rather than watching the file) is deliberate: it survives atomic-replace saves (editors rename a new inode over the file, which detaches file-level watchers) and works when the .env doesn't exist yet. Zero idle wakeups.
  • Fallback, not regression: if the directory watch cannot be established (fs.watch throws at setup or the watcher errors later), the watcher falls back to the old fs.watchFile approach at a 30 s interval instead of 2 s, with a log line saying so. Env edits are human-timescale; worst-case latency stays acceptable at 1/15th the wakeups.
  • Documented escape hatch for silent-non-delivery setups: on some filesystems the watch registers fine but events for externally made edits never arrive (network shares edited from another machine, container bind mounts edited from the host). No error fires there, so no automatic fallback can catch it — instead MARINARA_ENV_WATCH=poll forces the 30 s stat-poll, which sees every write. The docs describe exactly this boundary rather than overpromising automatic detection. (No documented deployment path — native installs, Docker named volumes, Termux $HOME — is affected; all have working change notification.)
  • Documented opt-out: MARINARA_ENV_WATCH=0 (also false/off/no) disables watching entirely; manual reloads and everything else keep working. Both values are checked once at startup (work from the shell env or from .env itself, since the initial env load precedes the watcher start), added to the restart-required key list, docs/CONFIGURATION.md, and .env.example. Deliberately not defaulted off anywhere, including the Termux launcher — that would silently kill the documented no-restart security-config reload for exactly the users who rely on it.
  • Behavior parity preserved: the disappeared-file warning + key-clearing path, the mtime/size dedupe, restart-required warnings, log lines, and the startEnvWatcher() → { stop, reloadNow } interface are unchanged; index.ts is untouched.
  • New regression (scripts/regressions/env-watcher.regression.ts, wired into regression:issues): drives the real watcher against a temp env file — creation-from-nothing pickup (the auto-created header file from runtime-config's import-time load is explicitly removed first, so the missing-file branch genuinely runs) with a 2 s latency ceiling that fails if events aren't driving the pickup, in-place edits, atomic replace via rename (the motivating hazard), deletion clearing loaded keys, stop() effectiveness, the mode resolver, and the opt-out (no watching, reloadNow() still functional). Also pins the 30 s fallback floor so the high-frequency timer can't quietly come back.

An adversarial review pass against the diff caught three things, all addressed: the module comment and docs originally overpromised the fallback (silent non-delivery neither throws nor errors, so it cannot auto-engage — the docs now state the boundary honestly and MARINARA_ENV_WATCH=poll gives those setups a real remedy); the regression's "file does not exist yet" scenario never actually ran (runtime-config auto-creates the env file at import — now unlinked first, with a precondition assert); and the original latency assertion's ceiling equaled its wait budget, making it unfireable (now a literal 2 s bound well under the 10 s budget).

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

  • pnpm check and the full regression:issues lane pass locally, including the new env-watcher regression (event-driven pickup latency, atomic replace, deletion, stop, opt-out).
  • Production-build boot smoke: server starts, logs [env-watcher] Watching …, and a live edit of the env file is applied and logged without restart.

Still to verify manually (contributor to-do):

  • Manually verify on a Linux/Termux install that an .env edit still hot-reloads (the regression runs on Windows; inotify semantics differ from ReadDirectoryChangesW).
  • Manually verify a security-config change (e.g. BASIC_AUTH_PASS) still takes effect without restart on a running install.

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)

docs/CONFIGURATION.md § "Restart or hot reload" updated (reload timing, fallback behavior, MARINARA_ENV_WATCH); [docs-i18n] follow-up filed as #4722.

Summary by CodeRabbit

  • New Features

    • Added automatic .env change detection with debounced reloads.
    • Added event-driven watching, 30-second polling fallback, forced polling, and disabled automatic watching.
    • Preserved manual configuration reloads when automatic watching is disabled.
    • Added cleanup for watcher shutdown and configuration-file removal.
  • Documentation

    • Documented setup failures, fallback polling, missed events, startup behavior, and configuration options.
  • Tests

    • Added regression coverage for edits, replacements, deletions, shutdown, polling, disabled mode, and manual reloads.

🔄 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/4723 **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/4707-env-watcher-idle-wakeups` --- ### 📝 Commits (3) - [`597270e`](https://github.com/Pasta-Devs/Marinara-Engine/commit/597270ea90f213e06d1373fd815996359782067b) fix(server): replace the env-watcher's 2s stat-poll with an event-driven directory watch - [`58a1f24`](https://github.com/Pasta-Devs/Marinara-Engine/commit/58a1f2439553b2635e5d34ac9db22948fcaca10f) fix(server): bound the env-watcher debounce deferral, handle bare watcher close, and harden the regression - [`8b5a488`](https://github.com/Pasta-Devs/Marinara-Engine/commit/8b5a4888f51f1bbef3a100a9083d62f38da30720) docs: describe the env-watch default's debounce and automatic fallback in the reference table ### 📊 Changes **5 files changed** (+330 additions, -27 deletions) <details> <summary>View changed files</summary> 📝 `.env.example` (+5 -0) 📝 `docs/CONFIGURATION.md` (+5 -2) 📝 `package.json` (+1 -1) 📝 `packages/server/src/config/env-watcher.ts` (+175 -24) ➕ `scripts/regressions/env-watcher.regression.ts` (+144 -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 Closes #4707 ## Why this change - The `.env` hot-reload watcher stat-polled the env file **every 2 seconds for the server's lifetime** (`fs.watchFile` is stat-polling, not inotify). That made it the highest-frequency permanent timer on an idle Marinara server — individually cheap, but 30 wakeups/minute forever prevents deep idle on phone-hosted (Termux) installs, where this class of timer is what keeps the battery drain floor up (follow-up from the mobile-battery investigation, alongside #4704/#4705). - The no-restart reload path itself is load-bearing (it's how access-control/security config changes take effect without downtime), so the fix keeps the behavior and removes the idle cost. ## What changed All changes in [`packages/server/src/config/env-watcher.ts`](packages/server/src/config/env-watcher.ts) plus docs and a new regression: - **Event-driven watching**: `fs.watch` on the **parent directory** of the env path, filtered to the file's basename, with `{ persistent: false }` and a 250 ms debounce funneling into the pre-existing mtime/size dedupe. Directory-watching (rather than watching the file) is deliberate: it survives atomic-replace saves (editors rename a new inode over the file, which detaches file-level watchers) and works when the `.env` doesn't exist yet. Zero idle wakeups. - **Fallback, not regression**: if the directory watch cannot be established (`fs.watch` throws at setup or the watcher errors later), the watcher falls back to the old `fs.watchFile` approach at a **30 s** interval instead of 2 s, with a log line saying so. Env edits are human-timescale; worst-case latency stays acceptable at 1/15th the wakeups. - **Documented escape hatch for silent-non-delivery setups**: on some filesystems the watch registers fine but events for *externally made* edits never arrive (network shares edited from another machine, container bind mounts edited from the host). No error fires there, so no automatic fallback can catch it — instead `MARINARA_ENV_WATCH=poll` forces the 30 s stat-poll, which sees every write. The docs describe exactly this boundary rather than overpromising automatic detection. (No documented deployment path — native installs, Docker named volumes, Termux `$HOME` — is affected; all have working change notification.) - **Documented opt-out**: `MARINARA_ENV_WATCH=0` (also `false`/`off`/`no`) disables watching entirely; manual reloads and everything else keep working. Both values are checked once at startup (work from the shell env or from `.env` itself, since the initial env load precedes the watcher start), added to the restart-required key list, `docs/CONFIGURATION.md`, and `.env.example`. Deliberately **not** defaulted off anywhere, including the Termux launcher — that would silently kill the documented no-restart security-config reload for exactly the users who rely on it. - **Behavior parity preserved**: the disappeared-file warning + key-clearing path, the mtime/size dedupe, restart-required warnings, log lines, and the `startEnvWatcher() → { stop, reloadNow }` interface are unchanged; `index.ts` is untouched. - **New regression** ([`scripts/regressions/env-watcher.regression.ts`](scripts/regressions/env-watcher.regression.ts), wired into `regression:issues`): drives the **real** watcher against a temp env file — creation-from-nothing pickup (the auto-created header file from `runtime-config`'s import-time load is explicitly removed first, so the missing-file branch genuinely runs) with a 2 s latency ceiling that fails if events aren't driving the pickup, in-place edits, **atomic replace via rename** (the motivating hazard), deletion clearing loaded keys, `stop()` effectiveness, the mode resolver, and the opt-out (no watching, `reloadNow()` still functional). Also pins the 30 s fallback floor so the high-frequency timer can't quietly come back. An adversarial review pass against the diff caught three things, all addressed: the module comment and docs originally *overpromised* the fallback (silent non-delivery neither throws nor errors, so it cannot auto-engage — the docs now state the boundary honestly and `MARINARA_ENV_WATCH=poll` gives those setups a real remedy); the regression's "file does not exist yet" scenario never actually ran (`runtime-config` auto-creates the env file at import — now unlinked first, with a precondition assert); and the original latency assertion's ceiling equaled its wait budget, making it unfireable (now a literal 2 s bound well under the 10 s budget). ## 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 - `pnpm check` and the full `regression:issues` lane pass locally, including the new env-watcher regression (event-driven pickup latency, atomic replace, deletion, stop, opt-out). - Production-build boot smoke: server starts, logs `[env-watcher] Watching …`, and a live edit of the env file is applied and logged without restart. Still to verify manually (contributor to-do): - Manually verify on a Linux/Termux install that an `.env` edit still hot-reloads (the regression runs on Windows; inotify semantics differ from ReadDirectoryChangesW). - Manually verify a security-config change (e.g. `BASIC_AUTH_PASS`) still takes effect without restart on a running install. ## Docs and release impact - [ ] No docs changes needed - [x] 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) `docs/CONFIGURATION.md` § "Restart or hot reload" updated (reload timing, fallback behavior, `MARINARA_ENV_WATCH`); `[docs-i18n]` follow-up filed as #4722. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added automatic `.env` change detection with debounced reloads. * Added event-driven watching, 30-second polling fallback, forced polling, and disabled automatic watching. * Preserved manual configuration reloads when automatic watching is disabled. * Added cleanup for watcher shutdown and configuration-file removal. * **Documentation** * Documented setup failures, fallback polling, missed events, startup behavior, and configuration options. * **Tests** * Added regression coverage for edits, replacements, deletions, shutdown, polling, disabled mode, and manual reloads. <!-- 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#6477
No description provided.