|
| 1 | +package config |
| 2 | + |
| 3 | +import ( |
| 4 | + "errors" |
| 5 | + "fmt" |
| 6 | + "os" |
| 7 | + "os/exec" |
| 8 | + "path/filepath" |
| 9 | + "strings" |
| 10 | + "sync" |
| 11 | + "testing" |
| 12 | + |
| 13 | + "gopkg.in/yaml.v3" |
| 14 | +) |
| 15 | + |
| 16 | +// TestRaceConditionEndToEnd reproduces the real file-level race condition that |
| 17 | +// occurs when multiple cencli processes initialize config concurrently against |
| 18 | +// the same data directory. Each subprocess is a real OS process with its own |
| 19 | +// viper instance — just like production. The race is in the non-atomic |
| 20 | +// read-modify-write of config.yaml (viper.WriteConfig + addDocCommentsToYAML). |
| 21 | +// |
| 22 | +// Run with: go test -run TestRaceConditionEndToEnd -count=1 -v ./internal/config/ |
| 23 | +func TestRaceConditionEndToEnd(t *testing.T) { |
| 24 | + const processes = 15 |
| 25 | + |
| 26 | + dataDir := t.TempDir() |
| 27 | + if err := os.MkdirAll(filepath.Join(dataDir, "templates"), 0o755); err != nil { |
| 28 | + t.Fatal(err) |
| 29 | + } |
| 30 | + |
| 31 | + configPath := filepath.Join(dataDir, "config.yaml") |
| 32 | + |
| 33 | + type procResult struct { |
| 34 | + id int |
| 35 | + exitCode int |
| 36 | + output string |
| 37 | + err error |
| 38 | + } |
| 39 | + |
| 40 | + var ( |
| 41 | + wg sync.WaitGroup |
| 42 | + mu sync.Mutex |
| 43 | + results []procResult |
| 44 | + ) |
| 45 | + |
| 46 | + // All processes start as close together as possible. |
| 47 | + start := make(chan struct{}) |
| 48 | + |
| 49 | + for i := 0; i < processes; i++ { |
| 50 | + wg.Add(1) |
| 51 | + go func(id int) { |
| 52 | + defer wg.Done() |
| 53 | + <-start |
| 54 | + |
| 55 | + cmd := exec.Command( |
| 56 | + os.Args[0], |
| 57 | + "-test.run=^TestRaceWorker$", |
| 58 | + "-test.v", |
| 59 | + ) |
| 60 | + cmd.Env = append(os.Environ(), |
| 61 | + "RACE_WORKER=1", |
| 62 | + fmt.Sprintf("RACE_DATA_DIR=%s", dataDir), |
| 63 | + ) |
| 64 | + |
| 65 | + out, err := cmd.CombinedOutput() |
| 66 | + |
| 67 | + exitCode := 0 |
| 68 | + if err != nil { |
| 69 | + var ee *exec.ExitError |
| 70 | + if errors.As(err, &ee) { |
| 71 | + exitCode = ee.ExitCode() |
| 72 | + } else { |
| 73 | + exitCode = -1 |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + mu.Lock() |
| 78 | + results = append(results, procResult{ |
| 79 | + id: id, |
| 80 | + exitCode: exitCode, |
| 81 | + output: string(out), |
| 82 | + err: err, |
| 83 | + }) |
| 84 | + mu.Unlock() |
| 85 | + }(i) |
| 86 | + } |
| 87 | + |
| 88 | + close(start) |
| 89 | + wg.Wait() |
| 90 | + |
| 91 | + // Tally process-level failures. |
| 92 | + var processErrors int |
| 93 | + for _, r := range results { |
| 94 | + if r.exitCode != 0 { |
| 95 | + processErrors++ |
| 96 | + t.Logf("process %d exited %d:\n%s", r.id, r.exitCode, r.output) |
| 97 | + } |
| 98 | + } |
| 99 | + |
| 100 | + // Check the final state of config.yaml — the file all processes raced on. |
| 101 | + finalRaw, err := os.ReadFile(configPath) |
| 102 | + if err != nil { |
| 103 | + t.Fatalf("cannot read final config.yaml: %v", err) |
| 104 | + } |
| 105 | + |
| 106 | + var ( |
| 107 | + fileEmpty bool |
| 108 | + fileCorrupt bool |
| 109 | + yamlErr string |
| 110 | + ) |
| 111 | + |
| 112 | + if len(finalRaw) == 0 { |
| 113 | + fileEmpty = true |
| 114 | + } else { |
| 115 | + var parsed map[string]interface{} |
| 116 | + if err := yaml.Unmarshal(finalRaw, &parsed); err != nil { |
| 117 | + fileCorrupt = true |
| 118 | + yamlErr = err.Error() |
| 119 | + } |
| 120 | + } |
| 121 | + |
| 122 | + t.Logf("--- Race Condition Results ---") |
| 123 | + t.Logf(" Processes launched: %d", processes) |
| 124 | + t.Logf(" Process failures: %d", processErrors) |
| 125 | + t.Logf(" Final file empty: %v", fileEmpty) |
| 126 | + t.Logf(" Final file corrupt: %v", fileCorrupt) |
| 127 | + if fileCorrupt { |
| 128 | + t.Logf(" YAML error: %s", yamlErr) |
| 129 | + t.Logf(" File content:\n%s", finalRaw) |
| 130 | + } |
| 131 | + |
| 132 | + if processErrors > 0 || fileEmpty || fileCorrupt { |
| 133 | + t.Errorf("Race condition reproduced: processes_failed=%d file_empty=%v file_corrupt=%v\n"+ |
| 134 | + "Multiple processes doing read-modify-write on config.yaml without file locking\n"+ |
| 135 | + "causes corruption visible to concurrent or subsequent CLI invocations.", |
| 136 | + processErrors, fileEmpty, fileCorrupt) |
| 137 | + } |
| 138 | +} |
| 139 | + |
| 140 | +// TestRaceWorker verifies that config.New() produces a valid, non-corrupt |
| 141 | +// config file. When spawned as a subprocess by TestRaceConditionEndToEnd |
| 142 | +// (RACE_WORKER=1, RACE_DATA_DIR set), it operates against the shared data |
| 143 | +// directory to exercise the file-lock under contention. When run standalone |
| 144 | +// it uses its own temp directory as a basic config.New() smoke test. |
| 145 | +func TestRaceWorker(t *testing.T) { |
| 146 | + dataDir := os.Getenv("RACE_DATA_DIR") |
| 147 | + if dataDir == "" { |
| 148 | + dataDir = t.TempDir() |
| 149 | + } |
| 150 | + |
| 151 | + cfg, cErr := New(dataDir) |
| 152 | + if cErr != nil { |
| 153 | + t.Fatalf("New() failed: %v", cErr) |
| 154 | + } |
| 155 | + |
| 156 | + // Verify the returned config is sane. |
| 157 | + if cfg.OutputFormat == "" { |
| 158 | + t.Error("config has empty output-format") |
| 159 | + } |
| 160 | + |
| 161 | + // Verify the file on disk is valid YAML right after our write. |
| 162 | + configPath := filepath.Join(dataDir, "config.yaml") |
| 163 | + raw, err := os.ReadFile(configPath) |
| 164 | + if err != nil { |
| 165 | + t.Fatalf("cannot read config.yaml after New(): %v", err) |
| 166 | + } |
| 167 | + if len(raw) == 0 { |
| 168 | + t.Fatal("config.yaml is empty immediately after New()") |
| 169 | + } |
| 170 | + |
| 171 | + var parsed map[string]interface{} |
| 172 | + if err := yaml.Unmarshal(raw, &parsed); err != nil { |
| 173 | + t.Fatalf("config.yaml is corrupted after New(): %v", err) |
| 174 | + } |
| 175 | + |
| 176 | + // Check for partial writes — key fields should be present. |
| 177 | + requiredKeys := []string{"output-format", "streaming", "timeouts", "retry-strategy"} |
| 178 | + content := string(raw) |
| 179 | + for _, key := range requiredKeys { |
| 180 | + if !strings.Contains(content, key+":") { |
| 181 | + t.Errorf("config.yaml missing expected key %q — possible truncated write", key) |
| 182 | + } |
| 183 | + } |
| 184 | +} |
0 commit comments