338 MB Backups Inside 512 MiB, a 6/100 Loro False Fork, and Intercepting macOS Dock Quit
Distilling 233 audit findings into 18 isolated commits on Mindloft: streaming a 338 MB dual-account backup without OOM in a 512 MiB swapless cgroup, eliminating a 6/100 Loro false-fork bug, and subclassing NSApplicationDelegate for Dock Quit.
On November 11, a 16-report code audit across Mindloft (formerly Brainlet / 枝间) surfaced 233 numbered findings: 16 high, 97 medium, and 120 low.
After consolidating the 188 modified files from parent commit 847cf50 into baseline 75f888fd on November 12, we pushed 18 isolated gate commits (c78005ad through 3320e862) on November 13. Each batch touched only its frozen slice and ran the full workspace check before landing. Test coverage climbed from 2,856 to 3,459 tests, closing 33/233 items including 15/16 high-severity entries (tracked in reviews/2026-11-12-remediation.md).
Three bugs from that sprint are worth writing down in full.
Streaming a 338 MB backup inside a 512 MiB swapless container
The old export route assembled the entire JSON backup in memory before writing the HTTP response, and the restore endpoint fed the whole payload straight into JSON.parse.
Under a Linux cgroup capped at memory.max=536870912 (512 MiB) and swap.max=0, we ran a backup generated from real authority.handleUpdate traffic: 140 DURABLE_ACK commits per account, 252,057,852 bytes of raw update payloads, and 338,499,381 bytes of exported JSON. The legacy GET route immediately blew the limit and died with exit code 137 (oom_kill=1).
Four commits (f3d2a489, 39a3cf53, 12d0db49, fb71bce3) replaced the path with a bounded streaming pipeline (services/api/docs/bounded-backup-restore.md):
- Server-side streaming export and temp budgets: Memory, SQLite, and PostgreSQL read by fixed watermarks and content generations with per-page byte budgets, encoding chunks into anonymous temp files (
1 GiBper file,3 GiBper job,6 GiBprocess-wide active cap) and re-checking session and ACL after sealing. 8 MiBmulti-request chunk uploads instead ofTransfer-Encoding: chunked: The client creates an upload job, then posts fixed8 MiBrawapplication/octet-streamslices toPOST /v0/backups/uploads/:uploadId/chunks/:indexwithx-ramilo-backup-chunk-sha256(up to1 GiB/128chunks). That fits cleanly under Cloudflare Worker and Nginx/api/8 MiBbody limits without raising gateway thresholds for every endpoint.- Zero full-buffer parsing in the browser: Web restore slices
8 MiBat a time fromFile, hashes it, and waits for the chunk ack before reading the next slice. Backup downloads only enable on browsers with secure-contextshowSaveFilePicker, writing64 KiBblocks into a native writable stream and refusing to silently fall back to an in-memoryBlob.
TCP edge tests caught two subtle races: the response generator hit EOF before the HTTP trailer flushed to the socket, freeing the global 2 / per-account 1 concurrency slot early; and complete or cancel requests could execute before the client finished its request EOF. Separating storage-read completion from socket-flush and file-close completion closed both holes.
In the same 512 MiB swapless cgroup, both single-account and dual-account concurrent export/restore runs returned HTTP 200 with oom_kill=0 and a peak dual-export process RSS of 346,263,552 bytes. Raw cgroup monitoring stayed honest: transient group peaks hit 536,928,256–537,047,040 bytes, and in V4 our psql verifier itself exited 137 from full-result buffering until V5 switched it to a FETCH_COUNT=1 cursor.
5,000-level deep trees and a 6/100 Loro false fork
To fix DC-06 stack overflows (205b10e0), we rewrote layout, ancestor offsets, visible-node collection, and canvas layers iteratively and verified a 5,000-level tree in Chrome 157 (a separate 15,000-level shared-view probe ran ~59s, missing the 20s cutoff, and stayed marked failed).
While running the full suite, a ghost bug surfaced: two replicas holding identical text, version vectors, and raw operations were flagged as forked 6/100 and 5/100 times across two 100-run concurrency experiments.
Loro’s default JSON export emits a local peer mapping table whose order is not deterministic, and our history digest hashed that local encoding directly. Canonicalizing by real peer identity dropped false forks to 0/100.
An independent counterexample then proved that identical version vectors and visible projections still do not guarantee identical raw operation history—overwritten or deleted early ops could still be spliced in. Commit f55cd080 added line-by-line history comparison using Loro’s pinned-version binary conflict check via a disposable temporary peer, without mutating the document or consuming its last available peer or op quota.
Intercepting macOS Dock Quit with ClassBuilder
Tracking down WH-01 revealed a macOS-only data-loss path: clicking the window close button or pressing ⌘Q went through the WebView save handshake, but right-clicking Quit in the Dock—or triggering an OS shutdown—invokes applicationShouldTerminate: on NSApplicationDelegate. Tauri’s underlying Tao window layer does not implement that selector, so AppKit terminated the process immediately and dropped unsaved edits.
Commit 56c44ad6 (apps/desktop/src-tauri/src/macos_quit.rs) uses objc2::runtime::ClassBuilder on the main thread during startup to subclass the active delegate as RamiloSaveBeforeQuitDelegate, returning NSTerminateLater (2):
let original = delegate.class();
let mut builder = ClassBuilder::new(c"RamiloSaveBeforeQuitDelegate", original)
.ok_or("quit delegate class already exists")?;
builder.add_method(
sel!(applicationShouldTerminate:),
should_terminate as extern "C-unwind" fn(_, _, _) -> _,
);
let subclass = builder.register();
let previous = AnyObject::set_class(delegate, subclass);
Dock quit, ⌘Q, and window close now share one epoch-based save handshake (verified across an 8s commit delay, a 30s stall prompting retry/cancel/force-quit, and a 5s no-bridge fallback) before dispatching replyToApplicationShouldTerminate: back on the main thread. We also stripped the process plugin from desktop capabilities, leaving file import with only read-file and stat.
At the end of that day, 33/233 audit items were closed—all verified in isolated branches and local cgroup/PostgreSQL runs, with none deployed to production yet.
Comments