Fix write-concurrency race: per-file write protocol + unique temps

The review-identified race: saves are async (owner snapshots content,
worker pool writes), nothing serialized per file, and every write of a
file used the SAME deterministic temp ('.<name>.tmp'). Two overlapping
writes (autosave x autosave, retry x autosave, or the synchronous
FlushAll on GoToBrowser/Shutdown x a worker write) interleaved on the
shared temp and could rename a byte-mixture into place; even without
interleaving, last-rename-wins could promote a STALE snapshot.

Owner-side protocol (logic.go, requestSave + result handler):
- at most one write in flight per file (writeInFlight maps filename ->
  the file version whose content the in-flight write carries);
- a save requested while one is in flight is deferred (savePending) and
  re-issued by the write's result handler with a FRESH snapshot, so
  'last rename wins' coincides with 'newest snapshot wins';
- on success the SNAPSHOT version (not the current one) is recorded as
  written, so an edit that arrived during the write leaves the file
  dirty and triggers the re-issue;
- FlushAll (GoToBrowser, Shutdown) defers via the same protocol instead
  of writing concurrently on the shared temp;
- shutdown drain: on done the owner waits (bounded 5 s) for in-flight
  writes and armed retries to settle before exiting, so the post-exit
  synchronous FlushAll and workerPool.Stop cannot race a straggling
  worker write;
- retry timer now sends a non-blocking token (no timer-goroutine stall
  on a full channel); emitFrame no longer blocks on a slow/gone main
  (frames are snapshots; the next emission wins) - also required so the
  drain can never deadlock on frame delivery.

Mechanism (real/filesystem.go):
- WriteFileAtomic uses a unique per-call temp ('.<name>.tmp.<pid>.<seq>'),
  making same-file staging-file interleaving structurally impossible even
  if the serialization regressed (defense in depth);
- each successful write best-effort removes stale temps of the same file
  (crash leftovers, plus the legacy deterministic name for upgraded
  installs); a failed write removes its own temp.

Tests:
- write_serialization_test.go (e2e): a counting FS wrapper proves the
  peak concurrent same-file saves is 1 across two deliberately
  overlapping autosaves (2 s saves; the second edit lands inside the
  first save's window and its token is deferred, then re-issued with the
  newer content), and that a Flush during an in-flight save adds no
  concurrent writer and the newest snapshot still wins. Mutation-verified:
  disabling the deferral fails it with peak = 2. (The pool's WriteFileTask
  calls FS.WriteFile, not WriteFileAtomic - the real FS is atomic only
  because WriteFile delegates to WriteFileAtomic; the wrapper mirrors that
  delegation or the overlap window does not exist.)
- filesystem_test.go: stale-temp test updated to the new pattern, also
  covering the legacy name and asserting a different file's temp is
  untouched.
- real_file_fuzz_test.go: stray-temp check matches both patterns.

Docs: architecture.md 6.5 rewritten (protocol invariants), spec.md
autosave line, development_plan.md v11 + Phase 12.

On-device smoke: open, type, autosave lands exact content on disk, no
temp files left, clean relaunch. Full suite green under -race.

Residuals (documented): no fsync before rename (power-loss window only);
external-change detection absent; a drain-deadline exit with a straggling
write can only lose freshness (unique temps keep every rename a complete
snapshot).
This commit is contained in:
gmp
2026-08-17 16:29:47 -04:00
parent 5205906de4
commit 6c6a0c1a27
8 changed files with 545 additions and 60 deletions
+32 -5
View File
@@ -369,15 +369,42 @@ Only the visible byte range is shaped and drawn each frame:
`deleteSurroundingText` (backspace/autocorrect replacement), and composition
all arrive through this one path.
### 6.5 Autosave
### 6.5 Autosave and the per-file write protocol
- Any edit calls `markDirty()`: a 1 s debounce timer; each keystroke restarts
it. On expiry the timer goroutine sends a token on `autosaveChan`; the owner
reconstructs the full content from the chunked buffer and dispatches a
`WriteFile` task.
snapshots the full content from the chunked buffer and requests a save.
- **Per-file write protocol (corruption guard).** The worker pool is shared
and the on-disk staging path is per-file, so two concurrent writes of the
same file would race on the staging file. The owner therefore guarantees:
- at most **one write in flight per file** (`writeInFlight`, keyed by
filename, recording the file version whose content the write carries);
- a save requested while one is in flight is **deferred** (`savePending`)
and re-issued by the write's result handler — so the rename that lands
last always carries the **newest** content ("latest state wins");
- on success the recorded written version is the **snapshot's** version,
so any edit that arrived during the write leaves the file dirty and
triggers the re-issue.
- `FlushAll` (page switch, shutdown) obeys the same protocol: if a write is
in flight it defers instead of writing concurrently.
- **Shutdown drain:** on the `done` signal the owner waits (bounded, 5 s) for
in-flight writes and armed retries to settle before exiting, so the
post-exit `FlushAll` and `workerPool.Stop` cannot race a straggling worker
write.
- **Staging file:** `WriteFileAtomic` uses a **unique per-call temp name**
("`.<name>.tmp.<pid>.<seq>`") in the target directory and renames it into
place, so readers and crash recovery only ever see a complete file. Each
successful write also best-effort removes stale temps of the same file
(crash leftovers, plus the legacy deterministic "`.<name>.tmp`" name).
Unique temp names make same-file interleaving structurally impossible even
if the serialization regressed.
- Write failures are tracked per file (`writeFailed`, `retryAttempts`) and
retried via `retryChan`. There is no save button; autosave is the only
persistence.
retried via `retryChan` (exponential backoff 1 s … 30 s; the timer sends a
non-blocking token and the owner re-snapshots at fire time). There is no
save button; autosave is the only persistence.
- Known residual (out of scope): no `fsync` before the rename — a **power
loss** inside the rename window can lose the last save (process death
cannot: the page cache survives).
### 6.6 Opening a file
+70 -2
View File
@@ -1,9 +1,10 @@
# Development Plan: reach a lean, usable Android text editor
Status: v10, 2026-08-17 (Phases 0–3 + doc reorg + Phase 6 scroll-perf/clamping
Status: v11, 2026-08-17 (Phases 0–3 + doc reorg + Phase 6 scroll-perf/clamping
verification + tap-to-position-cursor fix + selection + real-file e2e +
Android arrow/shift workaround + touch selection + scroll-offset tap proof &
float32 decomposition fix + font-scale (user font-size setting) support).
float32 decomposition fix + font-scale (user font-size setting) support +
data-corruption test suite & write-concurrency fix).
Written
against the **live** repo `/home/gmp/pad`. v1 (the widget-rebuild plan) is
superseded — see §12 for why. Doc reorganization (2026-08-16): the over-detailed
@@ -497,6 +498,73 @@ configurations, or only on this AVD's density?
marker → read the file off the device) is the ground truth and needs no
profiler.
### Phase 12 — data-corruption test suite + write-concurrency fix — DONE (2026-08-17)
Two questions: (a) how do we *prove* the edit→persist path cannot corrupt
file data; (b) fix the write-concurrency race the review identified (user
deprioritized it, then asked for it to be implemented after the test suite).
**Test suite (5 layers, all differential/oracle-based):**
- `chunked_buffer_fuzz_test.go` — every random Insert/Delete/replace mirrored
on a plain `[]byte` shadow model (chunk sizes 1…64 KB, 500–2000 ops each);
after every op: FileLen, FullContent, Content probes, chunk-size invariant.
Rune-aligned variant adds UTF-8 validity + an independent RuneIndexToByte
oracle.
- `line_index_fuzz_test.go` — incremental LineIndex updates vs a
full-recomputation oracle (mixed / no-newline / single-line / CRLF /
trailing-newline shapes), plus a trailing-empty-line structural test.
- `state_api_fuzz_test.go` — the production edit entry points
(HandleInsert/Backspace/Delete/ReplaceRange incl. selection variants);
after every op: content, UTF-8, chunk invariant, line index, exact cursor.
- `real_file_fuzz_test.go` (e2e) — random edit sequences incl. window-relative
IME replaces against the real FS; per-batch IME-window-consistency checks,
forced-flush disk byte-compare every batch, then a second Logic instance
(restart simulation) must reload byte-identical content; no stray temps.
- `filesystem_test.go` (real) — the atomicity contract: exact round trips, a
concurrent reader never sees a torn file across 150 alternating 2 MB
writes, a failed write leaves the original byte-identical, stale temps are
consumed.
**What the testing found (fixed in `5205906`):** `Insert` halved an oversized
spliced result once, so a large paste into a non-empty buffer left chunks up
to ~P/2 (8× the documented 2× bound at 1 MB/64 KB). `Insert` now re-chunks
the oversized result into pieces ≤ chunkSize, so "no chunk exceeds 2× target
after any edit" holds universally. Mutation-tested: dropping one byte in
Insert and one entry in UpdateLineIndexAfterInsert are both caught in ms.
**Write-concurrency fix (this round):**
- **Protocol (owner-side, per file):** at most one write in flight per file
(`writeInFlight[f]` = snapshot version); a save requested during a write is
deferred (`savePending`) and re-issued by the result handler; on success the
*snapshot's* version is recorded as written, so edits that landed during the
write trigger the re-issue — "last rename wins" coincides with "newest
snapshot wins". `FlushAll` (GoToBrowser/Shutdown) obeys the same protocol
instead of racing a worker write on the same temp file.
- **Mechanism (real FS):** `WriteFileAtomic` now uses a unique per-call temp
("`.<name>.tmp.<pid>.<seq>`"), so same-file interleaving is structurally
impossible even if the serialization regressed; each successful write also
best-effort removes stale temps of the same file (crash leftovers + the
legacy deterministic name).
- **Shutdown drain:** on `done`, the owner waits (bounded 5 s) for in-flight
writes and armed retries to settle before exiting, so the post-exit
synchronous `FlushAll` and `workerPool.Stop` cannot race a straggling
worker write. The retry timer now sends a non-blocking token (no timer-
goroutine stall on a full channel), and `emitFrame` no longer blocks on a
slow/gone main (dropped frames are snapshots; the next emission wins).
- **Proof:** `write_serialization_test.go` — a counting FS wrapper proves the
peak concurrent same-file saves is 1 across two deliberately overlapping
autosaves (2 s saves, edit inside the first save's window), and that a
Flush during an in-flight save neither adds a concurrent writer nor lets a
stale snapshot win. The test was mutation-verified: disabling the deferral
makes it fail with peak = 2. (Debugging note: the pool's `WriteFileTask`
calls `FS.WriteFile`, not `WriteFileAtomic` — the real FS is atomic only
because `WriteFile` delegates to `WriteFileAtomic`; the wrapper mirrors
that delegation or the timing window doesn't exist.)
- **Residuals (documented, out of scope):** no `fsync` before rename (power-
loss window only); external-change detection absent; a drain-deadline exit
with a straggling write can only lose freshness (unique temps keep every
rename a complete snapshot).
## 6. File-size decision (re-framed)
v1 framed this as "accept a limit vs build a windowed editor." The live repo
+6 -2
View File
@@ -72,8 +72,12 @@ elsewhere.
is tracked by the app, since Gio's Android bridge drops modifier keys —
architecture.md §2.1.)
- **Autosave:** every edit restarts a 1 s debounce; on expiry the full content
is written to disk by a worker. Failed writes are retried. This is the only
persistence mechanism.
is written to disk by a worker. At most one write per file is in flight at
any time; saves requested during a write are deferred and re-issued with
the newer content when it completes ("latest state wins"). Writes stage to
a unique per-call temp file and rename into place, so a crash or a
concurrent reader never observes a partial file. Failed writes are retried.
This is the only persistence mechanism.
### 2.3 Large files (measured)