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
+155 -37
View File
@@ -73,13 +73,23 @@ type Logic struct {
retryChan chan string // auto-save retries
autosaveChan chan struct{} // auto-save debounce ticks (timer -> owner)
inspectChan chan *inspectReq
workerPool *pool.WorkerPool
mockFS pool.FileSystem
done chan struct{}
exitWg sync.WaitGroup
saveTimer *time.Timer // auto-save debounce timer; non-nil while pending
lastEmit time.Time // time of the last frame emission (profiler cadence)
debugCmdC chan string // one-shot debug commands from the cmd-file poller; nil = disabled
// Per-file write protocol (see requestSave). Workers are a shared pool and
// the on-disk staging file is per-file, so two concurrent writes for the
// same file would interleave on the temp file; the protocol keeps at most
// one write in flight per file and re-issues deferred saves from the write
// result, so the rename that lands last always carries the newest content.
// All three maps are touched only on the owner goroutine.
writeInFlight map[string]int // filename -> fileVersion carried by the in-flight write
savePending map[string]bool // filename -> save requested while a write was in flight
retryScheduled map[string]time.Time // filename -> armed-but-unfired backoff retry
workerPool *pool.WorkerPool
mockFS pool.FileSystem
done chan struct{}
exitWg sync.WaitGroup
saveTimer *time.Timer // auto-save debounce timer; non-nil while pending
lastEmit time.Time // time of the last frame emission (profiler cadence)
debugCmdC chan string // one-shot debug commands from the cmd-file poller; nil = disabled
}
// NewLogic creates a new Logic instance, accepting an optional mockFS.
@@ -121,6 +131,9 @@ func NewLogic(mfs pool.FileSystem, path string, openfunc func(string)) *Logic {
retryChan: make(chan string, 1), // Buffered channel
autosaveChan: make(chan struct{}),
inspectChan: make(chan *inspectReq),
writeInFlight: make(map[string]int),
savePending: make(map[string]bool),
retryScheduled: make(map[string]time.Time),
workerPool: wp,
mockFS: mockFS,
done: make(chan struct{}),
@@ -192,6 +205,11 @@ func (l *Logic) Run() {
for {
select {
case <-l.done:
// Settle in-flight file writes before exiting: the post-exit
// synchronous FlushAll and workerPool.Stop must not race a
// straggling worker write, whose rename could otherwise land after
// the final flush and promote a stale snapshot.
l.drainWrites()
return
case update := <-l.configChan:
update.apply(l.state)
@@ -232,30 +250,13 @@ func (l *Logic) Run() {
l.workerPool.Dispatch(pool.NewStatFileTask(path, l.mockFS))
case filename := <-l.retryChan:
log.Printf("Logic: Retrying save for %s", filename)
if filename == l.state.Editor.Filename {
// Reconstruct full content from chunked buffer for saving
content, ok := l.fullContentBytes()
if !ok {
break
}
l.workerPool.DispatchNonBlocking(
pool.NewWriteFileTask(filename, content, l.mockFS),
)
}
delete(l.retryScheduled, filename)
l.requestSave(filename)
case <-l.autosaveChan:
// Auto-save debounce tick. The timer goroutine only sent a token;
// the owner reconstructs content and dispatches the write.
// the owner snapshots content and dispatches the write.
l.saveTimer = nil
if l.state.Editor.Filename == "" {
break
}
content, ok := l.fullContentBytes()
if !ok {
break
}
l.workerPool.DispatchNonBlocking(
pool.NewWriteFileTask(l.state.Editor.Filename, content, l.mockFS),
)
l.requestSave(l.state.Editor.Filename)
case p := <-l.state.pasteChan:
// Clipboard content arrived from the main goroutine: insert it
// (replacing any live selection, per the selection-aware edit rule).
@@ -304,7 +305,14 @@ func (l *Logic) emitFrame() {
}
PerfRecord(rec)
}
l.frameChan <- l.frameOf(elems)
select {
case l.frameChan <- l.frameOf(elems):
default:
// Main has not consumed the previous frame yet; drop this one. Frames
// are snapshots and the next emission carries the latest state. Keeps
// the owner from ever blocking on a slow/gone main (e.g. during the
// post-done write drain).
}
}
// EnableDebugCmdPoll starts a background poller (debug-only) that watches
@@ -500,26 +508,50 @@ func (l *Logic) handleWorkerResult(res pool.Result) {
}
}
} else if res.TaskType == pool.TypeWriteFile {
f := res.FilePath
wrote, tracked := l.writeInFlight[f]
delete(l.writeInFlight, f)
pending := l.savePending[f]
delete(l.savePending, f)
if res.Success {
l.state.Editor.lastWriteVersion[res.FilePath] = l.state.Editor.fileVersion[res.FilePath]
l.state.Editor.SetWriteFailed(res.FilePath, false)
if tracked {
// Record the version whose content was actually written (the
// snapshot version), not the version now: edits made while the
// write was in flight sit ahead of it and trigger the re-issue
// below.
l.state.Editor.lastWriteVersion[f] = wrote
}
l.state.Editor.SetWriteFailed(f, false)
// Latest-state-wins re-issue: a save was deferred while this write
// was in flight, or an edit arrived during it — write the newer
// content now (only the active file is reconstructable).
if f == l.state.Editor.Filename && (pending || l.state.Editor.fileVersion[f] > l.state.Editor.lastWriteVersion[f]) {
l.requestSave(f)
}
} else {
log.Printf("Auto-save failed for %s: %v", res.FilePath, res.Error)
l.state.Editor.SetWriteFailed(res.FilePath, true)
log.Printf("Auto-save failed for %s: %v", f, res.Error)
l.state.Editor.SetWriteFailed(f, true)
// Trigger retry logic: exponential backoff
attempts := l.state.Editor.IncrementRetryAttempts(res.FilePath)
attempts := l.state.Editor.IncrementRetryAttempts(f)
// Simple backoff: 1s, 2s, 4s, 8s... max 30s
delay := time.Duration(1<<(attempts-1)) * time.Second
if delay > 30*time.Second {
delay = 30 * time.Second
}
filename := res.FilePath
l.retryScheduled[f] = time.Now().Add(delay)
filename := f
log.Printf("Scheduling retry for %s in %v (attempt %d)", filename, delay, attempts)
time.AfterFunc(delay, func() {
log.Printf("Firing retry for %s", filename)
l.retryChan <- filename
select {
case l.retryChan <- filename:
default:
// A token for the same file is already queued; it will
// re-snapshot the latest content when it fires. Dropping
// keeps the timer goroutine from ever blocking.
log.Printf("Retry token for %s dropped: one already queued", filename)
}
})
}
}
@@ -581,6 +613,14 @@ func (l *Logic) WaitForExit() {
func (l *Logic) FlushAll() {
for filename := range l.state.Editor.fileVersion {
if l.state.Editor.IsDirty() && l.state.Editor.Filename == filename {
if _, inflight := l.writeInFlight[filename]; inflight {
// A worker is already writing this file and we cannot block the
// owner (we are it): defer. The write's result handler re-issues
// a fresh write while the file is still dirty, so the disk ends
// up with the latest content.
l.savePending[filename] = true
continue
}
content, ok := l.fullContentBytes()
if !ok {
continue
@@ -592,6 +632,84 @@ func (l *Logic) FlushAll() {
}
}
// requestSave is the single entry point for "persist the active file now"
// (autosave tick, retry token, deferred re-issue). It implements the
// per-file write protocol:
//
// - at most one write per file is in flight at any time. The worker pool is
// shared and the on-disk staging file is per-file, so two concurrent
// writes for the same file would interleave on the staging file and could
// rename a byte-mixture into place;
// - each write carries the file version at the moment its content was
// snapshotted (writeInFlight[f]); on success exactly that version is
// recorded as written, so any edit that arrived while the write was in
// flight leaves the file dirty and the result handler re-issues a fresh
// write with the newer content;
// - a save requested while a write is in flight is deferred (savePending)
// and re-issued by the result handler, so "last rename wins" always
// coincides with "newest snapshot wins".
//
// Must be called on the owner goroutine.
func (l *Logic) requestSave(filename string) {
if filename == "" || filename != l.state.Editor.Filename {
// Only the active file's content lives in memory (its ChunkedBuffer);
// a save for any previously opened file cannot be reconstructed.
return
}
if _, inflight := l.writeInFlight[filename]; inflight {
l.savePending[filename] = true
return
}
content, ok := l.fullContentBytes()
if !ok {
return
}
l.writeInFlight[filename] = l.state.Editor.fileVersion[filename]
l.workerPool.DispatchNonBlocking(pool.NewWriteFileTask(filename, content, l.mockFS))
}
const (
// writeDrainTimeout bounds the post-done wait for in-flight writes so a
// pathologically failing write can never hang shutdown.
writeDrainTimeout = 5 * time.Second
// writeDrainTick is the idle poll interval of the drain loop.
writeDrainTick = 20 * time.Millisecond
)
// drainWrites waits for in-flight file writes (and armed retries) to settle
// after the done signal, so that Shutdown's post-exit synchronous FlushAll
// and workerPool.Stop cannot race a straggling worker write. The write
// protocol may re-issue follow-up writes while draining; the deadline bounds
// the wait. Must be called on the owner goroutine.
func (l *Logic) drainWrites() {
if len(l.writeInFlight) == 0 && len(l.retryScheduled) == 0 {
return
}
log.Printf("Logic: draining %d in-flight write(s) before exit", len(l.writeInFlight))
deadline := time.Now().Add(writeDrainTimeout)
for {
if len(l.writeInFlight) == 0 && len(l.retryScheduled) == 0 {
return
}
if time.Now().After(deadline) {
log.Printf("Logic: write drain timed out with %d in flight; exiting (per-write unique temp files keep every rename a complete snapshot)", len(l.writeInFlight))
return
}
select {
case res := <-l.workerPool.ResultChan():
l.handleWorkerResult(res)
case filename := <-l.retryChan:
delete(l.retryScheduled, filename)
l.requestSave(filename)
case <-l.autosaveChan:
l.saveTimer = nil
l.requestSave(l.state.Editor.Filename)
case <-time.After(writeDrainTick):
// No events: re-check settle and deadline.
}
}
}
// Shutdown gracefully shuts down the logic goroutine and worker pool.
// The logic goroutine is stopped FIRST so that FlushAll can touch state
// single-threaded; the worker pool is stopped last so in-flight results