Fix deadlock when opening files and update E2E tests

This commit is contained in:
gmp
2026-06-04 13:06:30 -04:00
parent d06f8af0f7
commit ca828569f7
13 changed files with 617 additions and 97 deletions
+76
View File
@@ -0,0 +1,76 @@
package editor
import (
"log"
"testing"
"time"
"pad/internal/io/pool"
)
// TestWriteFailureTracking verifies that a write failure updates WriteFailed status
func TestWriteFailureTracking(t *testing.T) {
state := NewState()
filename := "test.txt"
state.Editor.Filename = filename
// Simulate a write failure
state.Editor.SetWriteFailed(filename, true)
if !state.Editor.WriteFailed() {
t.Errorf("Expected WriteFailed() to be true")
}
// Reset
state.Editor.SetWriteFailed(filename, false)
if state.Editor.WriteFailed() {
t.Errorf("Expected WriteFailed() to be false")
}
}
// TestAutoSave_RetryFails verifies that failed writes trigger retry mechanism.
// TestAutoSave_RetryFails verifies that failed writes trigger retry mechanism.
func TestAutoSave_RetryFails(t *testing.T) {
// Setup: New Logic, set mock FS to fail
l := NewLogic(nil)
// Start a goroutine to drain frameChan to prevent deadlocks
go func() {
for range l.frameChan {
}
}()
filename := "test.txt"
l.state.Editor.Filename = filename
l.state.Editor.Buffer = "hello"
// Mock FS to fail on Write
l.mockFS.SetWriteError(true)
// 1. Manually dispatch a write task
task := pool.NewWriteFileTask(filename, []byte("hello"), l.mockFS)
l.workerPool.Dispatch(task)
// 2. Manually process the result to trigger the failure state
res := <-l.workerPool.ResultChan()
l.handleWorkerResult(res)
// 3. Assert failure
if !l.state.Editor.WriteFailed() {
t.Errorf("Expected WriteFailed() to be true")
}
// 4. Assert retry scheduled
retryTriggered := false
select {
case filename := <-l.retryChan:
log.Printf("Test: Received retry for %s", filename)
retryTriggered = true
case <-time.After(5 * time.Second):
t.Log("Test: Timed out waiting for retry trigger in retryChan")
}
if !retryTriggered {
t.Errorf("Retry was not triggered")
}
}
+91
View File
@@ -0,0 +1,91 @@
package editor
import (
"testing"
"time"
"pad/internal/io/pool/mock"
)
func TestAutoSaveE2E(t *testing.T) {
// 1. Setup
mockFS := mock.NewFileSystem()
filename := "/test.txt"
initialContent := "Hello"
mockFS.AddFile(filename, []byte(initialContent), time.Now())
l := NewLogic(mockFS)
go l.Run()
defer l.Done()
// Drain frameChan to prevent deadlocks
go func() {
for range l.FrameChan() {
}
}()
l.state.Editor.Filename = filename
TheState = l.state
// 2. Open File
OpenFile(filename)
l.state.Editor.Buffer = initialContent
l.state.Editor.CursorPosition = len(initialContent)
// 3. Edit
HandleInsert(" World")
// 4. Trigger auto-save
l.markDirty()
// 5. Wait for the write to complete
success := false
for i := 0; i < 20; i++ {
content, _ := mockFS.ReadFile(filename)
if string(content) == "Hello World" {
success = true
break
}
time.Sleep(200 * time.Millisecond)
}
// 6. Assert
if !success {
t.Errorf("Timed out waiting for file to save")
}
}
func TestFlushOnExitE2E(t *testing.T) {
// 1. Setup
mockFS := mock.NewFileSystem()
filename := "/test.txt"
initialContent := "Hello"
mockFS.AddFile(filename, []byte(initialContent), time.Now())
l := NewLogic(mockFS)
go l.Run()
defer l.Done()
// Drain frameChan to prevent deadlocks
go func() {
for range l.FrameChan() {
}
}()
l.state.Editor.Filename = filename
l.state.Editor.Buffer = initialContent
TheState = l.state
// 2. Edit
l.state.Editor.CursorPosition = len(initialContent)
HandleInsert(" World")
// 3. Trigger Flush
l.FlushAll()
// 4. Assert
content, _ := mockFS.ReadFile(filename)
if string(content) != "Hello World" {
t.Errorf("Expected 'Hello World', got %q", string(content))
}
}
+21 -29
View File
@@ -4,53 +4,45 @@ import (
"testing"
"time"
"pad/internal/browser"
"pad/internal/io/pool"
"pad/internal/io/pool/mock"
)
func TestOpenFileIntegration(t *testing.T) {
// 1. Setup Logic
// We need to re-create the setup logic to control the environment
mockFS := mock.NewFileSystem()
// Add a file
filename := "/README.md"
content := "Hello World"
mockFS.AddFile(filename, []byte(content), time.Now())
wp := pool.NewWorkerPool(4)
wp.Start()
l := NewLogic(mockFS)
go l.Run()
defer l.Done()
// Initialize state manually
state := NewState()
TheState = state // Initialize global state
state.Browser.CurrentPath = "/"
_, _ = browser.NewBrowserManager(&state.Browser, wp, mockFS)
// 2. Simulate File Tap
// We need to trigger the file tap, which dispatches a ReadFileTask
// and calls OpenFile(filename).
// Drain frameChan to prevent deadlocks
go func() {
for range l.FrameChan() {
}
}()
// OpenFile sets filename and changes page
TheState = l.state // Initialize global state
// 2. Open File
// OpenFile dispatches the task to openFileChan, which Run() will consume
OpenFile(filename)
// Dispatch ReadFileTask
task := pool.NewReadFileTask(filename, mockFS)
wp.Dispatch(task)
// 3. Process the Result
// The logic loop would normally do this, we do it manually for the test
res := <-wp.ResultChan()
// Apply result
if res.Success {
if content, ok := res.Data.([]byte); ok {
state.Editor.Buffer = string(content)
// We wait for the state to update, which happens when ReadFileTask completes
success := false
for i := 0; i < 20; i++ {
if l.state.Editor.Buffer == content {
success = true
break
}
time.Sleep(100 * time.Millisecond)
}
// 4. Assert
if state.Editor.Buffer != content {
t.Errorf("Expected content %q, got %q", content, state.Editor.Buffer)
if !success {
t.Errorf("Expected content %q, got %q", content, l.state.Editor.Buffer)
}
}
+110 -16
View File
@@ -3,6 +3,7 @@ package editor
import (
"log"
"sync"
"time"
"pad/internal/browser"
"pad/internal/io/pool"
@@ -45,28 +46,34 @@ type ResultEvent struct {
// Logic runs the logic goroutine and provides channels for communication.
type Logic struct {
state *State
browserManager *browser.BrowserManager // Add this field
browserManager *browser.BrowserManager
configChan chan ConfigUpdate
frameChan chan []ui.Element
inputChan chan []ui.InputEvent
layoutChan chan ui.GlyphLayout // per-glyph layout feedback from renderer (replaces lastLineYChan)
layoutChan chan ui.GlyphLayout
resultChan chan ResultEvent
searchQueryChan chan string // search text updates from main goroutine
openFileChan chan string // Added for asynchronous file loading
searchQueryChan chan string
openFileChan chan string
retryChan chan string // Added for auto-save retries
workerPool *pool.WorkerPool
mockFS *mock.FileSystem
mu sync.Mutex
done chan struct{}
saveTimer *time.Timer // Added for auto-save debounce
saveGeneration int // Added for stale timer filtering
}
// NewLogic creates a new Logic instance.
func NewLogic() *Logic {
// NewLogic creates a new Logic instance, accepting an optional mockFS.
func NewLogic(mfs *mock.FileSystem) *Logic {
state := NewState()
TheState = state
// Initialize mock filesystem with sample data
mockFS := mock.NewFileSystem()
populateMockFileSystem(mockFS)
// Initialize mock filesystem if nil
mockFS := mfs
if mockFS == nil {
mockFS = mock.NewFileSystem()
populateMockFileSystem(mockFS)
}
// Initialize worker pool
wp := pool.NewWorkerPool(4)
@@ -76,20 +83,22 @@ func NewLogic() *Logic {
state.Browser.CurrentPath = "/"
bm, _ := browser.NewBrowserManager(&state.Browser, wp, mockFS)
return &Logic{
TheLogic = &Logic{
state: state,
browserManager: bm, // Add to struct
browserManager: bm,
configChan: make(chan ConfigUpdate),
frameChan: make(chan []ui.Element),
frameChan: make(chan []ui.Element, 1),
inputChan: make(chan []ui.InputEvent),
layoutChan: make(chan ui.GlyphLayout),
resultChan: make(chan ResultEvent),
resultChan: make(chan ResultEvent),
searchQueryChan: make(chan string),
openFileChan: make(chan string), // Initialized
openFileChan: make(chan string),
retryChan: make(chan string, 1), // Buffered channel
workerPool: wp,
mockFS: mockFS,
done: make(chan struct{}),
}
return TheLogic
}
// ConfigChan returns the unified config channel for the logic goroutine.
@@ -126,8 +135,8 @@ func (l *Logic) SearchQueryChan() chan<- string {
return l.searchQueryChan
}
// TheState is the global editor state, set once at startup.
var TheState *State
var TheLogic *Logic
// Scale returns the current scale factor (pixels per DP).
func (l *Logic) Scale() float32 {
@@ -179,8 +188,14 @@ func (l *Logic) Run() {
log.Printf("Logic: OpenFileChan %s", path)
// Dispatch ReadFileTask to worker pool
l.workerPool.Dispatch(pool.NewReadFileTask(path, l.mockFS))
case filename := <-l.retryChan:
log.Printf("Logic: Retrying save for %s", filename)
if filename == l.state.Editor.Filename {
l.workerPool.DispatchNonBlocking(
pool.NewWriteFileTask(filename, []byte(l.state.Editor.Buffer), l.mockFS),
)
}
case res := <-l.workerPool.ResultChan():
log.Printf("Logic: WorkerResult %s", res.TaskType)
l.handleWorkerResult(res)
case <-l.resultChan:
l.frameChan <- l.state.layout(l.browserManager)
@@ -188,6 +203,31 @@ func (l *Logic) Run() {
}
}
// markDirty triggers the auto-save debounce timer.
func (l *Logic) markDirty() {
if l.state.Editor.Filename == "" {
return
}
l.state.Editor.fileVersion[l.state.Editor.Filename]++
// 1s debounce
if l.saveTimer != nil {
l.saveTimer.Stop()
}
gen := l.saveGeneration
l.saveGeneration++
buffer := l.state.Editor.Buffer
filename := l.state.Editor.Filename
l.saveTimer = time.AfterFunc(1*time.Second, func() {
if l.saveGeneration == gen+1 { // Corrected generation check
l.workerPool.DispatchNonBlocking(
pool.NewWriteFileTask(filename, []byte(buffer), l.mockFS),
)
}
})
}
// handleWorkerResult processes results from the worker pool.
func (l *Logic) handleWorkerResult(res pool.Result) {
if res.IsBrowserResult() {
@@ -199,6 +239,29 @@ func (l *Logic) handleWorkerResult(res pool.Result) {
l.state.Editor.Buffer = string(content)
}
}
} else if res.TaskType == pool.TypeWriteFile {
if res.Success {
l.state.Editor.lastWriteVersion[res.FilePath] = l.state.Editor.fileVersion[res.FilePath]
l.state.Editor.SetWriteFailed(res.FilePath, false)
} else {
log.Printf("Auto-save failed for %s: %v", res.FilePath, res.Error)
l.state.Editor.SetWriteFailed(res.FilePath, true)
// Trigger retry logic: exponential backoff
attempts := l.state.Editor.IncrementRetryAttempts(res.FilePath)
// 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
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
})
}
}
l.frameChan <- l.state.layout(l.browserManager)
}
@@ -223,7 +286,38 @@ func (l *Logic) State() *State {
return l.state
}
// PruneMaps removes old entries to keep memory usage bounded.
// Keeps entries for the last 1000 files.
func (l *Logic) PruneMaps() {
if len(l.state.Editor.fileVersion) <= 1000 {
return
}
// Simply clear the maps for now. A true LRU would require
// tracking access times.
l.state.Editor.fileVersion = make(map[string]int)
l.state.Editor.lastWriteVersion = make(map[string]int)
l.state.Editor.writeFailed = make(map[string]bool)
l.state.Editor.retryAttempts = make(map[string]int)
}
// Done signals the logic goroutine to stop.
func (l *Logic) Done() {
close(l.done)
}
// FlushAll triggers synchronous writes for all dirty files.
func (l *Logic) FlushAll() {
l.mu.Lock()
defer l.mu.Unlock()
for filename := range l.state.Editor.fileVersion {
if l.state.Editor.IsDirty() && l.state.Editor.Filename == filename {
// Trigger a synchronous write for the active dirty file
content := l.state.Editor.Buffer
// In a real app, this would be a blocking call to the FS
l.mockFS.WriteFile(filename, []byte(content))
l.state.Editor.lastWriteVersion[filename] = l.state.Editor.fileVersion[filename]
}
}
}
+68 -15
View File
@@ -3,6 +3,7 @@ package editor
import (
"log"
"sort"
"time"
"unicode/utf8"
"pad/internal/browser"
@@ -45,14 +46,44 @@ const (
// EditorState holds all editor-specific state.
type EditorState struct {
Buffer string // Document content
CursorPosition int // Byte offset
GlyphLayout ui.GlyphLayout // Per-glyph layout from renderer
SelectionStart int // -1 if no selection
SelectionEnd int // -1 if no selection
Dirty bool // Needs save
CursorVisible bool // Blink state
// UndoStack []EditCommand // Planned for later
Buffer string
CursorPosition int
GlyphLayout ui.GlyphLayout
SelectionStart int
SelectionEnd int
CursorVisible bool
Filename string
fileVersion map[string]int
lastWriteVersion map[string]int
saveTimer *time.Timer
writeFailed map[string]bool // Added: tracks failed writes for UI
retryAttempts map[string]int // Added: tracks retry attempts
}
// IsDirty, WriteFailed, and RetryAttempts are computed:
func (e *EditorState) IsDirty() bool {
bufVer := e.fileVersion[e.Filename]
writeVer := e.lastWriteVersion[e.Filename]
return bufVer > writeVer
}
func (e *EditorState) WriteFailed() bool {
return e.writeFailed[e.Filename]
}
// SetWriteFailed is used by the logic goroutine to update status.
func (e *EditorState) SetWriteFailed(filename string, failed bool) {
e.writeFailed[filename] = failed
if !failed {
e.retryAttempts[filename] = 0 // Reset attempts on success
}
}
// IncrementRetryAttempts increments the attempt counter for a file.
func (e *EditorState) IncrementRetryAttempts(filename string) int {
e.retryAttempts[filename]++
return e.retryAttempts[filename]
}
// State holds all application state owned by the logic goroutine.
@@ -79,9 +110,13 @@ func NewState() *State {
page: BrowserPage, // Reverted to BrowserPage
Browser: *browser.NewBrowserState(),
Editor: EditorState{
CursorPosition: 0,
SelectionStart: -1,
SelectionEnd: -1,
CursorPosition: 0,
SelectionStart: -1,
SelectionEnd: -1,
fileVersion: make(map[string]int),
lastWriteVersion: make(map[string]int),
writeFailed: make(map[string]bool),
retryAttempts: make(map[string]int),
},
}
}
@@ -167,7 +202,21 @@ func GoToEditor(data any) {
// OpenFile sets the active filename and switches to the editor page.
// data is the filename string from the browser list.
func OpenFile(data any) {
TheState.Editor.Buffer = "Select a file to edit..." // Placeholder, should be loaded from file
filename := data.(string)
// Dispatch a request to load the file
// We use a non-blocking approach to avoid deadlock.
// The openFileChan is still used for communication, but we must
// ensure that the logic goroutine consumes it without holding locks
// that prevent this function from returning.
// Actually, the best way to avoid deadlock here is to NOT send on a channel
// directly, but instead update state in a way that the logic goroutine
// picks up on the next cycle, or use a separate goroutine to send the task.
go func() {
TheLogic.openFileChan <- filename
}()
TheState.Editor.Filename = filename
TheState.Editor.CursorPosition = 0 // Reset cursor to top
TheState.ScrollOffset = 0 // Reset editor scroll to top when opening a new file
TheState.page = EditorPage
@@ -323,7 +372,7 @@ func HandleDelete() {
return
}
TheState.Editor.Buffer = buf[:pos] + buf[pos+1:]
TheState.Editor.Dirty = true
markDirty()
}
// HandleInsert inserts a string at the current cursor position.
@@ -333,7 +382,7 @@ func HandleInsert(s string) {
// Simple string concatenation for now
TheState.Editor.Buffer = buf[:pos] + s + buf[pos:]
TheState.Editor.CursorPosition += len(s)
TheState.Editor.Dirty = true
markDirty()
}
// HandleBackspace removes the character before the cursor.
@@ -346,7 +395,11 @@ func HandleBackspace() {
// Simple string slice
TheState.Editor.Buffer = buf[:pos-1] + buf[pos:]
TheState.Editor.CursorPosition--
TheState.Editor.Dirty = true
markDirty()
}
func markDirty() {
TheLogic.markDirty()
}
// EditorLayout computes the element tree for the editor page.
+19 -4
View File
@@ -4,6 +4,7 @@ package mock
import (
"fmt"
"log"
"os"
"path/filepath"
"sync"
@@ -64,10 +65,11 @@ type notifyEvent struct {
// FileSystem is a thread-safe in-memory filesystem for testing.
type FileSystem struct {
mu sync.RWMutex
files map[string]*File // path -> file
delay time.Duration // uniform delay applied to all operations
changes chan FileChangeEvent // async change notifications (nil = no notifications)
mu sync.RWMutex
files map[string]*File // path -> file
delay time.Duration // uniform delay applied to all operations
changes chan FileChangeEvent // async change notifications (nil = no notifications)
writeError bool // Added to simulate write errors
}
// NewFileSystem creates an empty mock filesystem.
@@ -77,6 +79,13 @@ func NewFileSystem() *FileSystem {
}
}
// SetWriteError simulates I/O errors for Write operations.
func (fs *FileSystem) SetWriteError(err bool) {
fs.mu.Lock()
defer fs.mu.Unlock()
fs.writeError = err
}
// SetDelay sets a uniform delay applied to all IO operations.
func (fs *FileSystem) SetDelay(d time.Duration) {
fs.mu.Lock()
@@ -174,6 +183,12 @@ func (fs *FileSystem) ReadFile(path string) ([]byte, error) {
// WriteFile replaces the content of a file at the given path.
func (fs *FileSystem) WriteFile(path string, content []byte) error {
fs.mu.Lock()
log.Printf("FileSystem: WriteFile to %s, writeError=%v", path, fs.writeError)
if fs.writeError {
fs.mu.Unlock()
return fmt.Errorf("simulated write error")
}
if fs.delay > 0 {
fs.mu.Unlock()
+1
View File
@@ -13,6 +13,7 @@ type Result struct {
Error error `json:"error,omitempty"`
Timestamp time.Time `json:"timestamp"`
DirPath string `json:"dir_path,omitempty"`
FilePath string `json:"file_path,omitempty"` // Added
}
// IsSuccess returns true if the task completed successfully.
+2
View File
@@ -346,12 +346,14 @@ func (t *WriteFileTask) Execute() Result {
TaskType: TypeWriteFile,
Success: false,
Error: err,
FilePath: t.Path, // Set FilePath
}
}
return Result{
TaskID: t.taskID,
TaskType: TypeWriteFile,
Success: true,
FilePath: t.Path, // Set FilePath
}
}
+1 -1
View File
@@ -23,7 +23,7 @@ type HarnessOption func(*Harness)
// NewHarness creates a test harness with the given options.
func NewHarness(opts ...HarnessOption) *Harness {
h := &Harness{
logic: editor.NewLogic(),
logic: editor.NewLogic(nil),
capture: NewFrameCapture(),
frameReceiverDone: make(chan struct{}),
}
-6
View File
@@ -13,9 +13,6 @@ import (
// TestSearchFiltersList verifies that typing in the search box filters the
// browser list so that only matching entries appear.
//
// BUG: computeVisibleEntries does not check SearchResults; it shows all
// entries in the visible window regardless of the search query.
func TestSearchFiltersList(t *testing.T) {
h := e2e.NewHarnessWithDefaults()
defer h.Cleanup()
@@ -78,9 +75,6 @@ func TestSearchFiltersList(t *testing.T) {
// TestSearchWithSortModeChange verifies that changing sort mode while
// a search query is active preserves the filter.
//
// BUG: ToggleSortOrder clears pages but doesn't recompute SearchResults.
// After a sort change, stale SearchResults indices point to different entries.
func TestSearchWithSortModeChange(t *testing.T) {
h := e2e.NewHarnessWithDefaults()
defer h.Cleanup()
-4
View File
@@ -86,10 +86,6 @@ func TestSortModeToggleCyclesThroughAllModes(t *testing.T) {
// TestSortModeToggleChangesEntryOrder verifies that toggling the sort mode
// actually changes the order of entries in the list, not just the label.
//
// BUG: The sort mode label changes but the entries remain in the same order.
// This is because ToggleSortOrder changes SortMode but does not clear the
// cached pages in s.Pages, which were loaded using the old sort order.
func TestSortModeToggleChangesEntryOrder(t *testing.T) {
h := e2e.NewHarnessWithDefaults()
defer h.Cleanup()