[PR #7812] [MERGED] fix(storage): prove local Windows storage so a dead writer lease is reclaimed #7940

Closed
opened 2026-10-24 04:09:01 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/Pasta-Devs/Marinara-Engine/pull/7812
Author: @SpicyMarinara
Created: 10/19/2026
Status: ✅ Merged
Merged: 10/19/2026
Merged by: @SpicyMarinara

Base: staging ← Head: fix/7801-windows-lease-locality


📝 Commits (1)

  • 2cb98e4 fix(storage): prove local Windows storage so a dead writer lease is reclaimed

📊 Changes

2 files changed (+289 additions, -13 deletions)

View changed files

📝 packages/server/src/db/file-backed-store.ts (+117 -13)
📝 scripts/regressions/storage-writer-lock.regression.ts (+172 -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

Follow-up to #7801 and #7804. #7801 is already closed, so this PR has no closing line. The maintainer decided to finish the Windows part before the release.

Why this change

  • #7804 fixed the reported trigger with a MachineGuid probe retry, but the storage proof it extended still never ran on Windows. writerLeaseStorageIsMachineLocal() reads Linux statfs magic numbers, so on Windows it always returns false.
  • Two Windows cases therefore still needed the user to delete data/storage/.writer-lease by hand after a crash:
    • (a) Both MachineGuid probe attempts time out (this process has no host id), and the lease recorded one.
    • (b) The lease has hostId: null because the process that wrote it had a failed probe. The #7801 reporter's current lease is like this. A later start whose probe works hits the #5799 path, which also needs the storage proof.

What changed

All changes are in packages/server/src/db/file-backed-store.ts and scripts/regressions/storage-writer-lock.regression.ts.

  • New writerLeaseWindowsStorageIsMachineLocal(). It resolves the storage folder with fs.realpathSync.native, so a mapped network drive or a link to a share shows up as its UNC path. It strips a \\?\ prefix and then accepts only an X:\ path. UNC (\\server\share, \\?\UNC\...), volume GUID and device paths are not local. For a drive path it runs powershell.exe -NoProfile -NonInteractive -Command "[System.IO.DriveInfo]::new('X:\').DriveType" hidden, with a 5 s timeout, and compares the enum name, which is not localized. Only Fixed counts. Network, Removable, CDRom, Ram, Unknown, NoRootDirectory, any error and a timeout all mean "not local". A failed probe logs one warning. The answer is cached per drive for the process.

  • Lazy probe. The drive type is asked only when a lease blocks startup, one side has no host id, and the lease passes the writer check below. It is never asked at module load or on a normal start.

  • New writerLeaseWrittenByWindowsHere() guard. This was not in the original plan, and reviewers should check it. A Fixed drive proves where the files are, not who wrote them. Docker Desktop bind mounts, WSL's /mnt/c and VM shares reach the same disk from another kernel, and another PC can reach it through a share. Without the guard, the boot check alone would reclaim a live container's lease, because its UUID boot id never matches a Windows timestamp. The Windows proof therefore covers only a lease from a native Windows writer with this machine's name, which requires all of:

    • version 4 with a LastBootUpTime boot id;
    • no PID namespace and no liveness scope;
    • the same hostname.
  • acquireWriterLease(). On win32 it uses a new hostProof value, windows-local-storage, which also appears in the "Reclaimed the writer lease" log. Windows has no PID namespaces, so the PID checks decide directly:

    • an exited PID (ESRCH) is reclaimed;
    • a live PID keeps the lease, even if it might have been reused (pidWasReused is skipped on this proof);
    • a PID whose liveness cannot be determined (EPERM) keeps the lease.

    The existing boot check applies as it does for every same-host proof: a writer from an earlier boot of this machine, outside #7804's 5-minute jitter window, is reclaimed.

  • Test hooks. New hooks writerLeasePlatform, writerLeaseRealpath and writerLeaseDriveType. When the existing writerLeaseStorageIsMachineLocal hook is set, it still selects the Linux-style proof, so the existing regression cases behave the same on every platform. writerLeaseBootIdsMatch now receives the writer's platform, which in production is the same process.platform as before.

  • Unchanged: the Linux/Android statfs proof and its PID-namespace rule, writerLeaseStorageIsMachineLocal() itself, the macOS strict path, the host-id and Termux proofs, the on-disk lease format, storage-format.json and STORAGE_VERSION.

Cases still left to manual recovery, by design:

  • A Windows lease without a boot id (version 2, written when the writer's PowerShell boot probe failed). Nothing in the lease shows that Windows wrote it.
  • A computer rename between the crash and the restart.
  • A Fixed disk shared with a VM or another PC that has the same computer name. The drive type cannot see a re-export, which mirrors the Linux proof's own limit.

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

Commands run by the agent, on macOS and in a Linux container:

  • pnpm build:shared && node ./scripts/run-regressions.mjs --filter storage-writer-lock on macOS: passed. New cases:
    • The storage proof directly:
      • A Fixed drive is local, including d:\ and \\?\C:\, and the probe receives the drive root in upper case.
      • UNC, \\?\UNC\, volume GUID, device and relative paths are not local, and the drive probe is never asked for them.
      • Network, Removable, CDRom, Ram, Unknown, NoRootDirectory, a null probe answer (failure or timeout), a probe that throws and an unresolvable path are all not local.
    • Cases (a) and (b) through createFileNativeDB with an injected platform, realpath result and probe answer, using the reporter's two jittered boot ids:
      • an exited PID is reclaimed;
      • a live PID is refused;
      • a Network drive is refused;
      • a mapped drive that resolves to a share is refused;
      • a failed probe is refused.
    • A Windows writer from an earlier boot is reclaimed.
    • Leases are refused, without probing the drive, for a Linux writer (UUID boot id plus PID namespace), a containerised writer (liveness scope), another PC (different hostname) and a version 2 lease with no boot id.
    • A start that finds no lease never probes the drive.
  • Mutation checks: the regression fails when the code is broken in any of these ways:
    • the Windows proof is disabled;
    • the native-Windows-writer guard is removed;
    • the hostname check is removed;
    • any non-null drive type is accepted;
    • a non-drive path is accepted;
    • pidWasReused is allowed on the Windows proof. This one fails on Linux only, because pidWasReused always returns false on macOS.
  • Linux (node:24-bookworm container with an /etc/machine-id, as on the Ubuntu CI runners): storage-writer-lock passed.
  • Pre-existing, not changed here. In a container without /etc/machine-id, the existing case "a lease naming a different machine is never reclaimed through the storage proof" fails on unmodified staging too. Since #7804, a process without a host id applies the mirror rule, and that case does not pin writerLeaseHostId.
  • Other regressions: backup-folder-lease passed. robustness-boot-performance passed, and its source scan confirms the new drive-type probe runs with windowsHide: true.
  • pnpm check: passed. Its only lint warning is a pre-existing react-hooks/exhaustive-deps warning in a client file not touched here.
  • Other checks:
    • pnpm --filter @marinara-engine/server lint: passed.
    • Prettier on both changed files: clean. The root format:check does not cover scripts/.
    • A one-off tsc type check of the regression file: the new lines are clean. Its three errors are pre-existing, outside this diff, and the file runs under tsx.

Not testable off Windows. These are covered by the manual checks below:

  • The real PowerShell DriveType probe: command line quoting, its output, the 5 s timeout and the hidden window.
  • What realpathSync.native returns on Windows for a mapped network drive, a subst drive or a link to a share.
  • process.kill(pid, 0) on Windows, which should return ESRCH for an exited PID and EPERM for an elevated process.
  • Real LastBootUpTime values and os.hostname() across restarts.

On macOS and Linux, the decision logic ran with the platform, realpath result and drive-type answer injected.

Manual verification notes

  • Manually verify on Windows with the data folder on a local drive (C:), for case (b):
    1. Start the server.
    2. End node.exe with Task Manager "End task".
    3. In data\storage\.writer-lease\owner.json, set "hostId": null. This is the reporter's current lease shape.
    4. Start again. It should start without deleting .writer-lease, and the log should show "Reclaimed the writer lease after confirming its same-host PID exited." with hostProof: "windows-local-storage".
  • Manually verify case (a) on Windows: a crashed lease that recorded a hostId, followed by a start whose MachineGuid probe fails, is reclaimed the same way. Use a machine where the first reg.exe call is slow (the #7801 reporter offered to test a staging build), or a local build where readStableMachineId() temporarily returns null. Do not use a bogus SystemRoot: it also breaks the drive-type probe.
  • Manually verify on Windows that a live writer keeps its lease:
    1. Start a server.
    2. Set "hostId": null in its owner.json.
    3. Start a second server against the same DATA_DIR. It should be refused with StorageWriterLeaseError.
  • Manually verify on Windows that a mapped network drive stays locked:
    1. Set DATA_DIR (or FILE_STORAGE_DIR) to a mapped drive such as Z:\ mapped to \\nas\share.
    2. Repeat the case (b) steps. Startup should still be refused, with no reclaim log.
  • Manually verify that a data folder on a USB stick (Removable) also stays locked after the same steps.
  • Manually verify on Windows that a normal start, with no lease left behind, is not slower: no DriveInfo PowerShell runs. On the blocked path, the probe should finish well inside its 5 s budget.
  • Optionally, if WSL or Docker Desktop is installed: start Marinara there against a folder on C:, then start the Windows server against the same folder. It should be refused while the WSL or container server runs.

Docs and release impact

  • No docs changes needed
  • Updated docs (README / CONTRIBUTING / android/README) 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)

No docs were edited. docs/TROUBLESHOOTING.md already says that Marinara reclaims a crashed lease on local disks and that manual removal remains the fallback for network or shared storage. On Windows, a normal start that has its machine ID already reclaimed a dead lease before this PR. No version, changelog, storage-format.json or STORAGE_VERSION change.

UI evidence (if applicable)

Not applicable: server-only change.

Summary by CodeRabbit

  • Bug Fixes
    • Improved recovery of stale storage locks on Windows when they reside on a confirmed local fixed drive.
    • Preserved locks for active writers and storage locations that cannot be safely verified, reducing the risk of interrupting ongoing work.

🔄 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/7812 **Author:** [@SpicyMarinara](https://github.com/SpicyMarinara) **Created:** 10/19/2026 **Status:** ✅ Merged **Merged:** 10/19/2026 **Merged by:** [@SpicyMarinara](https://github.com/SpicyMarinara) **Base:** `staging` ← **Head:** `fix/7801-windows-lease-locality` --- ### 📝 Commits (1) - [`2cb98e4`](https://github.com/Pasta-Devs/Marinara-Engine/commit/2cb98e420a33c9d03f0efa5c75a51faf18e1b049) fix(storage): prove local Windows storage so a dead writer lease is reclaimed ### 📊 Changes **2 files changed** (+289 additions, -13 deletions) <details> <summary>View changed files</summary> 📝 `packages/server/src/db/file-backed-store.ts` (+117 -13) 📝 `scripts/regressions/storage-writer-lock.regression.ts` (+172 -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 Follow-up to #7801 and #7804. #7801 is already closed, so this PR has no closing line. The maintainer decided to finish the Windows part before the release. ## Why this change - #7804 fixed the reported trigger with a MachineGuid probe retry, but the storage proof it extended still never ran on Windows. `writerLeaseStorageIsMachineLocal()` reads Linux statfs magic numbers, so on Windows it always returns false. - Two Windows cases therefore still needed the user to delete `data/storage/.writer-lease` by hand after a crash: - **(a)** Both MachineGuid probe attempts time out (this process has no host id), and the lease recorded one. - **(b)** The lease has `hostId: null` because the process that wrote it had a failed probe. The #7801 reporter's current lease is like this. A later start whose probe works hits the #5799 path, which also needs the storage proof. ## What changed All changes are in `packages/server/src/db/file-backed-store.ts` and `scripts/regressions/storage-writer-lock.regression.ts`. - **New `writerLeaseWindowsStorageIsMachineLocal()`.** It resolves the storage folder with `fs.realpathSync.native`, so a mapped network drive or a link to a share shows up as its UNC path. It strips a `\\?\` prefix and then accepts only an `X:\` path. UNC (`\\server\share`, `\\?\UNC\...`), volume GUID and device paths are not local. For a drive path it runs `powershell.exe -NoProfile -NonInteractive -Command "[System.IO.DriveInfo]::new('X:\').DriveType"` hidden, with a 5 s timeout, and compares the enum name, which is not localized. Only `Fixed` counts. Network, Removable, CDRom, Ram, Unknown, NoRootDirectory, any error and a timeout all mean "not local". A failed probe logs one warning. The answer is cached per drive for the process. - **Lazy probe.** The drive type is asked only when a lease blocks startup, one side has no host id, and the lease passes the writer check below. It is never asked at module load or on a normal start. - **New `writerLeaseWrittenByWindowsHere()` guard.** This was not in the original plan, and reviewers should check it. A Fixed drive proves where the files are, not who wrote them. Docker Desktop bind mounts, WSL's `/mnt/c` and VM shares reach the same disk from another kernel, and another PC can reach it through a share. Without the guard, the boot check alone would reclaim a live container's lease, because its UUID boot id never matches a Windows timestamp. The Windows proof therefore covers only a lease from a native Windows writer with this machine's name, which requires all of: - version 4 with a `LastBootUpTime` boot id; - no PID namespace and no liveness scope; - the same hostname. - **`acquireWriterLease()`.** On win32 it uses a new `hostProof` value, `windows-local-storage`, which also appears in the "Reclaimed the writer lease" log. Windows has no PID namespaces, so the PID checks decide directly: - an exited PID (`ESRCH`) is reclaimed; - a live PID keeps the lease, even if it might have been reused (`pidWasReused` is skipped on this proof); - a PID whose liveness cannot be determined (`EPERM`) keeps the lease. The existing boot check applies as it does for every same-host proof: a writer from an earlier boot of this machine, outside #7804's 5-minute jitter window, is reclaimed. - **Test hooks.** New hooks `writerLeasePlatform`, `writerLeaseRealpath` and `writerLeaseDriveType`. When the existing `writerLeaseStorageIsMachineLocal` hook is set, it still selects the Linux-style proof, so the existing regression cases behave the same on every platform. `writerLeaseBootIdsMatch` now receives the writer's platform, which in production is the same `process.platform` as before. - **Unchanged:** the Linux/Android statfs proof and its PID-namespace rule, `writerLeaseStorageIsMachineLocal()` itself, the macOS strict path, the host-id and Termux proofs, the on-disk lease format, `storage-format.json` and `STORAGE_VERSION`. **Cases still left to manual recovery, by design:** - A Windows lease without a boot id (version 2, written when the writer's PowerShell boot probe failed). Nothing in the lease shows that Windows wrote it. - A computer rename between the crash and the restart. - A Fixed disk shared with a VM or another PC that has the same computer name. The drive type cannot see a re-export, which mirrors the Linux proof's own limit. ## 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` Commands run by the agent, on macOS and in a Linux container: - **`pnpm build:shared && node ./scripts/run-regressions.mjs --filter storage-writer-lock` on macOS: passed.** New cases: - The storage proof directly: - A Fixed drive is local, including `d:\` and `\\?\C:\`, and the probe receives the drive root in upper case. - UNC, `\\?\UNC\`, volume GUID, device and relative paths are not local, and the drive probe is never asked for them. - Network, Removable, CDRom, Ram, Unknown, NoRootDirectory, a `null` probe answer (failure or timeout), a probe that throws and an unresolvable path are all not local. - Cases (a) and (b) through `createFileNativeDB` with an injected platform, realpath result and probe answer, using the reporter's two jittered boot ids: - an exited PID is reclaimed; - a live PID is refused; - a Network drive is refused; - a mapped drive that resolves to a share is refused; - a failed probe is refused. - A Windows writer from an earlier boot is reclaimed. - Leases are refused, without probing the drive, for a Linux writer (UUID boot id plus PID namespace), a containerised writer (liveness scope), another PC (different hostname) and a version 2 lease with no boot id. - A start that finds no lease never probes the drive. - **Mutation checks: the regression fails when the code is broken in any of these ways:** - the Windows proof is disabled; - the native-Windows-writer guard is removed; - the hostname check is removed; - any non-null drive type is accepted; - a non-drive path is accepted; - `pidWasReused` is allowed on the Windows proof. This one fails on Linux only, because `pidWasReused` always returns false on macOS. - **Linux (`node:24-bookworm` container with an `/etc/machine-id`, as on the Ubuntu CI runners): `storage-writer-lock` passed.** - **Pre-existing, not changed here.** In a container without `/etc/machine-id`, the existing case "a lease naming a different machine is never reclaimed through the storage proof" fails on unmodified `staging` too. Since #7804, a process without a host id applies the mirror rule, and that case does not pin `writerLeaseHostId`. - **Other regressions:** `backup-folder-lease` passed. `robustness-boot-performance` passed, and its source scan confirms the new drive-type probe runs with `windowsHide: true`. - **`pnpm check`: passed.** Its only lint warning is a pre-existing `react-hooks/exhaustive-deps` warning in a client file not touched here. - **Other checks:** - `pnpm --filter @marinara-engine/server lint`: passed. - Prettier on both changed files: clean. The root `format:check` does not cover `scripts/`. - A one-off `tsc` type check of the regression file: the new lines are clean. Its three errors are pre-existing, outside this diff, and the file runs under tsx. **Not testable off Windows.** These are covered by the manual checks below: - The real PowerShell `DriveType` probe: command line quoting, its output, the 5 s timeout and the hidden window. - What `realpathSync.native` returns on Windows for a mapped network drive, a `subst` drive or a link to a share. - `process.kill(pid, 0)` on Windows, which should return `ESRCH` for an exited PID and `EPERM` for an elevated process. - Real `LastBootUpTime` values and `os.hostname()` across restarts. On macOS and Linux, the decision logic ran with the platform, realpath result and drive-type answer injected. ### Manual verification notes - Manually verify on Windows with the data folder on a local drive (C:), for case (b): 1. Start the server. 2. End `node.exe` with Task Manager "End task". 3. In `data\storage\.writer-lease\owner.json`, set `"hostId": null`. This is the reporter's current lease shape. 4. Start again. It should start without deleting `.writer-lease`, and the log should show "Reclaimed the writer lease after confirming its same-host PID exited." with `hostProof: "windows-local-storage"`. - Manually verify case (a) on Windows: a crashed lease that recorded a `hostId`, followed by a start whose MachineGuid probe fails, is reclaimed the same way. Use a machine where the first `reg.exe` call is slow (the #7801 reporter offered to test a staging build), or a local build where `readStableMachineId()` temporarily returns `null`. Do not use a bogus `SystemRoot`: it also breaks the drive-type probe. - Manually verify on Windows that a live writer keeps its lease: 1. Start a server. 2. Set `"hostId": null` in its `owner.json`. 3. Start a second server against the same `DATA_DIR`. It should be refused with `StorageWriterLeaseError`. - Manually verify on Windows that a mapped network drive stays locked: 1. Set `DATA_DIR` (or `FILE_STORAGE_DIR`) to a mapped drive such as `Z:\` mapped to `\\nas\share`. 2. Repeat the case (b) steps. Startup should still be refused, with no reclaim log. - Manually verify that a data folder on a USB stick (Removable) also stays locked after the same steps. - Manually verify on Windows that a normal start, with no lease left behind, is not slower: no `DriveInfo` PowerShell runs. On the blocked path, the probe should finish well inside its 5 s budget. - Optionally, if WSL or Docker Desktop is installed: start Marinara there against a folder on C:, then start the Windows server against the same folder. It should be refused while the WSL or container server runs. ## Docs and release impact - [ ] No docs changes needed - [ ] Updated docs (README / CONTRIBUTING / android/README) 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) No docs were edited. `docs/TROUBLESHOOTING.md` already says that Marinara reclaims a crashed lease on local disks and that manual removal remains the fallback for network or shared storage. On Windows, a normal start that has its machine ID already reclaimed a dead lease before this PR. No version, changelog, `storage-format.json` or `STORAGE_VERSION` change. ## UI evidence (if applicable) Not applicable: server-only change. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Bug Fixes** * Improved recovery of stale storage locks on Windows when they reside on a confirmed local fixed drive. * Preserved locks for active writers and storage locations that cannot be safely verified, reducing the risk of interrupting ongoing work. <!-- 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-24 04:09:01 +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#7940
No description provided.