[PR #749] [MERGED] refactor(folders): null-guard route handlers and atomicity for storage loops #4759

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

📋 Pull Request Information

Original PR: https://github.com/Pasta-Devs/Marinara-Engine/pull/749
Author: @Romuromylus
Created: 5/12/2026
Status: ✅ Merged
Merged: 5/12/2026
Merged by: @Romuromylus

Base: main ← Head: refactor/folder-atomicity


📝 Commits (2)

  • 08a4654 refactor(folders): null-guard route handlers and atomicity for storage loops
  • fa4ac4d refactor(folders): also transaction-wrap /reorder-chats

📊 Changes

5 files changed (+118 additions, -67 deletions)

View changed files

📝 packages/server/src/routes/chat-folders.routes.ts (+18 -9)
📝 packages/server/src/routes/connection-folders.routes.ts (+4 -2)
📝 packages/server/src/services/storage/chat-folders.storage.ts (+34 -20)
📝 packages/server/src/services/storage/chats.storage.ts (+20 -9)
📝 packages/server/src/services/storage/connection-folders.storage.ts (+42 -27)

📄 Description

Linked issue

Closes #747
Closes #748

Why this change

Two follow-ups from CodeRabbit's review of #745, both of which I deferred at the time because applying them only to the new connection-folders files would have diverged from the existing chat-folders pattern. With #745 merged, this PR addresses both findings simultaneously in lockstep across both folder modules:

  1. #747 — POST/PATCH handlers in both folder route modules used folder!.collapsed non-null assertions. Safe under current semantics, but brittle to future error-handling changes.
  2. #748 — create(), reorder(), and reorderConnections() in the folder storage modules — plus POST /api/chat-folders/reorder-chats — issued per-row UPDATE loops without transaction boundaries. A partial failure mid-loop could leave sort_order / folder_id columns in a mixed state.

Folder counts in a single-user Marinara install are O(dozens), so the performance impact of the missing atomicity is negligible — but a transaction wrap gives us actual atomicity, matches the canonical pattern already used in lorebooks.storage.ts / agents.storage.ts, and costs almost nothing.

What changed

Routes — null-guard the create/update responses:

  • packages/server/src/routes/chat-folders.routes.ts — POST + PATCH: replace folder!.collapsed with an explicit if (!folder) return reply.status(500)... guard.
  • packages/server/src/routes/connection-folders.routes.ts — same change.

Storage — wrap per-row loops in db.transaction():

  • packages/server/src/services/storage/chat-folders.storage.ts — create() (shift + insert) and reorder() (per-row sort_order update).
  • packages/server/src/services/storage/connection-folders.storage.ts — create(), reorder(), and reorderConnections() (the route is wired but UI for drag-within-folder is still deferred — wrapping it now means the eventual UI flip is pure-frontend).
  • packages/server/src/services/storage/chats.storage.ts — update() and setFolderForChat() now accept an optional tx parameter (typed structurally as Pick<DB, "select" | "update">, the same shape used by syncLorebookLinks in lorebooks.storage.ts:154). When tx is omitted the behaviour is identical to before.
  • packages/server/src/routes/chat-folders.routes.ts — POST /reorder-chats now wraps the loop in app.db.transaction() and threads tx through both chatsStorage.update and chatsStorage.setFolderForChat, so the sortOrder write and the group-sibling folder propagation commit atomically.

Each transaction uses a single shared now() timestamp so all rows within one reorder share an updated_at value (intentional — the previous "later-timestamp-per-row" behaviour was an accidental side-effect of the per-row loop, not a deliberate semantic).

Why not a single-query bulk UPDATE?

CodeRabbit's original suggestion was tx.update(folders).set({ sortOrder: sql\${folders.sortOrder} + 1` })` to collapse the shift into one statement. That's a no-go on this codebase's default storage backend:

  • Marinara v1.5.7+ defaults to STORAGE_BACKEND=files (see packages/server/src/config/runtime-config.ts:245).
  • The file-native runtime in packages/server/src/db/file-backed-store.ts:932 intentionally treats run() as a no-op and .set() patches as plain row literals — a Drizzle sql template silently breaks for any user not on opt-in STORAGE_BACKEND=sqlite.

The transaction wrap is portable across both backends (file-backed-store has its own transaction implementation at file-backed-store.ts:829 — a deep table snapshot with rollback-on-throw — and this PR's changes flow through it correctly).

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 live against me.romyromulus.com after fork-deploy:

  • Atomic create (connection-folders) — 5 existing folders pre-shift, created a new folder, confirmed via GET /api/connection-folders that the new folder is at sortOrder=0 and the 5 originals shifted to 1..5 exactly.
  • Atomic create (chat-folders) — same flow against /api/chat-folders, no existing folders, new folder inserted at sortOrder=0.
  • Atomic reorder (connection-folders) — POSTed {orderedIds: [...].reverse()} to /api/connection-folders/reorder, confirmed full reverse applied (e.g. LinkAPI LLM from 5 → 0, Tx Test Folder from 0 → 5).
  • No console errors under any of the above flows.
  • Cleanup — test folders deleted, original 5 connection folders + their connections intact.

Things that would benefit from human verification before merge:

  • Manually verify reorder-chats in the UI — drag chats between folders in CONVO/RP/GM tabs, confirm both the per-chat sortOrder and the group-sibling folder propagation still work end-to-end.
  • Manually verify drag-to-reorder folders in the connections panel (the Reorder.Group integration).
  • Manually verify the 500 path on the POST/PATCH null-guard — hard to trigger without inducing a real DB failure; safe to skip if the lower-risk happy paths are confirmed.

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)

UI evidence (if applicable)

No UI changes — pure backend/storage refactor. The connections panel and chat sidebar behaviour are identical to before from the user's point of view, just with stronger consistency guarantees under partial-failure scenarios.

Summary by CodeRabbit

Release Notes

  • Bug Fixes
    • Improved error handling for folder creation and update operations
    • Enhanced reliability of folder reordering to prevent inconsistent states during concurrent updates

Review Change Stack


🔄 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/749 **Author:** [@Romuromylus](https://github.com/Romuromylus) **Created:** 5/12/2026 **Status:** ✅ Merged **Merged:** 5/12/2026 **Merged by:** [@Romuromylus](https://github.com/Romuromylus) **Base:** `main` ← **Head:** `refactor/folder-atomicity` --- ### 📝 Commits (2) - [`08a4654`](https://github.com/Pasta-Devs/Marinara-Engine/commit/08a46540a0d7c4ab8e676c6d6e4973f004404d83) refactor(folders): null-guard route handlers and atomicity for storage loops - [`fa4ac4d`](https://github.com/Pasta-Devs/Marinara-Engine/commit/fa4ac4db38474836f00cb17209e648bdfa7d73d0) refactor(folders): also transaction-wrap /reorder-chats ### 📊 Changes **5 files changed** (+118 additions, -67 deletions) <details> <summary>View changed files</summary> 📝 `packages/server/src/routes/chat-folders.routes.ts` (+18 -9) 📝 `packages/server/src/routes/connection-folders.routes.ts` (+4 -2) 📝 `packages/server/src/services/storage/chat-folders.storage.ts` (+34 -20) 📝 `packages/server/src/services/storage/chats.storage.ts` (+20 -9) 📝 `packages/server/src/services/storage/connection-folders.storage.ts` (+42 -27) </details> ### 📄 Description ## Linked issue Closes #747 Closes #748 ## Why this change Two follow-ups from CodeRabbit's review of [#745](https://github.com/Pasta-Devs/Marinara-Engine/pull/745), both of which I deferred at the time because applying them only to the new `connection-folders` files would have diverged from the existing `chat-folders` pattern. With #745 merged, this PR addresses both findings simultaneously in lockstep across both folder modules: 1. **#747** — POST/PATCH handlers in both folder route modules used `folder!.collapsed` non-null assertions. Safe under current semantics, but brittle to future error-handling changes. 2. **#748** — `create()`, `reorder()`, and `reorderConnections()` in the folder storage modules — plus `POST /api/chat-folders/reorder-chats` — issued per-row UPDATE loops without transaction boundaries. A partial failure mid-loop could leave `sort_order` / `folder_id` columns in a mixed state. Folder counts in a single-user Marinara install are O(dozens), so the *performance* impact of the missing atomicity is negligible — but a transaction wrap gives us actual atomicity, matches the canonical pattern already used in `lorebooks.storage.ts` / `agents.storage.ts`, and costs almost nothing. ## What changed **Routes — null-guard the create/update responses:** - `packages/server/src/routes/chat-folders.routes.ts` — POST + PATCH: replace `folder!.collapsed` with an explicit `if (!folder) return reply.status(500)...` guard. - `packages/server/src/routes/connection-folders.routes.ts` — same change. **Storage — wrap per-row loops in `db.transaction()`:** - `packages/server/src/services/storage/chat-folders.storage.ts` — `create()` (shift + insert) and `reorder()` (per-row sort_order update). - `packages/server/src/services/storage/connection-folders.storage.ts` — `create()`, `reorder()`, and `reorderConnections()` (the route is wired but UI for drag-within-folder is still deferred — wrapping it now means the eventual UI flip is pure-frontend). - `packages/server/src/services/storage/chats.storage.ts` — `update()` and `setFolderForChat()` now accept an optional `tx` parameter (typed structurally as `Pick<DB, "select" | "update">`, the same shape used by `syncLorebookLinks` in `lorebooks.storage.ts:154`). When `tx` is omitted the behaviour is identical to before. - `packages/server/src/routes/chat-folders.routes.ts` — `POST /reorder-chats` now wraps the loop in `app.db.transaction()` and threads `tx` through both `chatsStorage.update` and `chatsStorage.setFolderForChat`, so the sortOrder write and the group-sibling folder propagation commit atomically. Each transaction uses a single shared `now()` timestamp so all rows within one reorder share an `updated_at` value (intentional — the previous "later-timestamp-per-row" behaviour was an accidental side-effect of the per-row loop, not a deliberate semantic). ## Why not a single-query bulk UPDATE? CodeRabbit's original suggestion was `tx.update(folders).set({ sortOrder: sql\`${folders.sortOrder} + 1\` })` to collapse the shift into one statement. That's a no-go on this codebase's default storage backend: - Marinara v1.5.7+ defaults to `STORAGE_BACKEND=files` (see `packages/server/src/config/runtime-config.ts:245`). - The file-native runtime in `packages/server/src/db/file-backed-store.ts:932` intentionally treats `run()` as a no-op and `.set()` patches as plain row literals — a Drizzle `sql` template silently breaks for any user not on opt-in `STORAGE_BACKEND=sqlite`. The transaction wrap is portable across both backends (file-backed-store has its own `transaction` implementation at file-backed-store.ts:829 — a deep table snapshot with rollback-on-throw — and this PR's changes flow through it correctly). ## 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 live against `me.romyromulus.com` after fork-deploy: - **Atomic create (connection-folders)** — 5 existing folders pre-shift, created a new folder, confirmed via `GET /api/connection-folders` that the new folder is at `sortOrder=0` and the 5 originals shifted to `1..5` exactly. - **Atomic create (chat-folders)** — same flow against `/api/chat-folders`, no existing folders, new folder inserted at `sortOrder=0`. - **Atomic reorder (connection-folders)** — POSTed `{orderedIds: [...].reverse()}` to `/api/connection-folders/reorder`, confirmed full reverse applied (e.g. `LinkAPI LLM` from `5 → 0`, `Tx Test Folder` from `0 → 5`). - **No console errors** under any of the above flows. - **Cleanup** — test folders deleted, original 5 connection folders + their connections intact. Things that would benefit from human verification before merge: - Manually verify reorder-chats in the UI — drag chats between folders in CONVO/RP/GM tabs, confirm both the per-chat sortOrder and the group-sibling folder propagation still work end-to-end. - Manually verify drag-to-reorder folders in the connections panel (the `Reorder.Group` integration). - Manually verify the 500 path on the POST/PATCH null-guard — hard to trigger without inducing a real DB failure; safe to skip if the lower-risk happy paths are confirmed. ## 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) ## UI evidence (if applicable) No UI changes — pure backend/storage refactor. The connections panel and chat sidebar behaviour are identical to before from the user's point of view, just with stronger consistency guarantees under partial-failure scenarios. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit ## Release Notes * **Bug Fixes** * Improved error handling for folder creation and update operations * Enhanced reliability of folder reordering to prevent inconsistent states during concurrent updates [![Review Change Stack](https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg)](https://app.coderabbit.ai/change-stack/Pasta-Devs/Marinara-Engine/pull/749) <!-- 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-22 04:10:24 +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#4759
No description provided.