adaptive_optimization_test.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. package indexer
  2. import (
  3. "sync"
  4. "sync/atomic"
  5. "testing"
  6. "time"
  7. )
  8. // Mock config for testing
  9. type mockConfigForAdaptive struct {
  10. workerCount int
  11. batchSize int
  12. }
  13. func (m *mockConfigForAdaptive) GetWorkerCount() int {
  14. return m.workerCount
  15. }
  16. func (m *mockConfigForAdaptive) SetWorkerCount(count int) {
  17. m.workerCount = count
  18. }
  19. // Test helper to create adaptive optimizer with mock config
  20. func createTestAdaptiveOptimizer(workerCount int) *AdaptiveOptimizer {
  21. config := &Config{
  22. WorkerCount: workerCount,
  23. BatchSize: 1000,
  24. }
  25. return NewAdaptiveOptimizer(config)
  26. }
  27. func TestAdaptiveOptimizer_NewAdaptiveOptimizer(t *testing.T) {
  28. config := &Config{
  29. WorkerCount: 8,
  30. BatchSize: 1000,
  31. }
  32. ao := NewAdaptiveOptimizer(config)
  33. if ao == nil {
  34. t.Fatal("NewAdaptiveOptimizer returned nil")
  35. }
  36. if ao.config.WorkerCount != 8 {
  37. t.Errorf("Expected worker count 8, got %d", ao.config.WorkerCount)
  38. }
  39. if ao.cpuMonitor.targetUtilization != 0.75 {
  40. t.Errorf("Expected target CPU utilization 0.75, got %f", ao.cpuMonitor.targetUtilization)
  41. }
  42. if ao.batchSizeController.baseBatchSize != 1000 {
  43. t.Errorf("Expected base batch size 1000, got %d", ao.batchSizeController.baseBatchSize)
  44. }
  45. }
  46. func TestAdaptiveOptimizer_SetWorkerCountChangeCallback(t *testing.T) {
  47. ao := createTestAdaptiveOptimizer(4)
  48. var callbackOldCount, callbackNewCount int
  49. callbackCalled := false
  50. ao.SetWorkerCountChangeCallback(func(oldCount, newCount int) {
  51. callbackOldCount = oldCount
  52. callbackNewCount = newCount
  53. callbackCalled = true
  54. })
  55. // Trigger a callback
  56. if ao.onWorkerCountChange != nil {
  57. ao.onWorkerCountChange(4, 6)
  58. }
  59. if !callbackCalled {
  60. t.Error("Expected callback to be called")
  61. }
  62. if callbackOldCount != 4 {
  63. t.Errorf("Expected old count 4, got %d", callbackOldCount)
  64. }
  65. if callbackNewCount != 6 {
  66. t.Errorf("Expected new count 6, got %d", callbackNewCount)
  67. }
  68. }
  69. func TestAdaptiveOptimizer_suggestWorkerIncrease(t *testing.T) {
  70. ao := createTestAdaptiveOptimizer(4)
  71. var actualOldCount, actualNewCount int
  72. var callbackCalled bool
  73. ao.SetWorkerCountChangeCallback(func(oldCount, newCount int) {
  74. actualOldCount = oldCount
  75. actualNewCount = newCount
  76. callbackCalled = true
  77. })
  78. // Test CPU underutilization scenario
  79. currentCPU := 0.5 // 50% utilization
  80. targetCPU := 0.8 // 80% target
  81. ao.suggestWorkerIncrease(currentCPU, targetCPU)
  82. if !callbackCalled {
  83. t.Error("Expected worker count change callback to be called")
  84. }
  85. if actualOldCount != 4 {
  86. t.Errorf("Expected old worker count 4, got %d", actualOldCount)
  87. }
  88. // Should increase workers, but not more than max allowed
  89. if actualNewCount <= 4 {
  90. t.Errorf("Expected new worker count to be greater than 4, got %d", actualNewCount)
  91. }
  92. // Verify config was updated
  93. if ao.config.WorkerCount != actualNewCount {
  94. t.Errorf("Expected config worker count to be updated to %d, got %d", actualNewCount, ao.config.WorkerCount)
  95. }
  96. }
  97. func TestAdaptiveOptimizer_suggestWorkerDecrease(t *testing.T) {
  98. ao := createTestAdaptiveOptimizer(8)
  99. var actualOldCount, actualNewCount int
  100. var callbackCalled bool
  101. ao.SetWorkerCountChangeCallback(func(oldCount, newCount int) {
  102. actualOldCount = oldCount
  103. actualNewCount = newCount
  104. callbackCalled = true
  105. })
  106. // Test CPU over-utilization scenario
  107. currentCPU := 0.95 // 95% utilization
  108. targetCPU := 0.8 // 80% target
  109. ao.suggestWorkerDecrease(currentCPU, targetCPU)
  110. if !callbackCalled {
  111. t.Error("Expected worker count change callback to be called")
  112. }
  113. if actualOldCount != 8 {
  114. t.Errorf("Expected old worker count 8, got %d", actualOldCount)
  115. }
  116. // Should decrease workers, but not below minimum
  117. if actualNewCount >= 8 {
  118. t.Errorf("Expected new worker count to be less than 8, got %d", actualNewCount)
  119. }
  120. // Should not go below minimum
  121. if actualNewCount < ao.cpuMonitor.minWorkers {
  122. t.Errorf("New worker count %d should not be below minimum %d", actualNewCount, ao.cpuMonitor.minWorkers)
  123. }
  124. // Verify config was updated
  125. if ao.config.WorkerCount != actualNewCount {
  126. t.Errorf("Expected config worker count to be updated to %d, got %d", actualNewCount, ao.config.WorkerCount)
  127. }
  128. }
  129. func TestAdaptiveOptimizer_adjustWorkerCount_NoChange(t *testing.T) {
  130. ao := createTestAdaptiveOptimizer(4)
  131. var callbackCalled bool
  132. ao.SetWorkerCountChangeCallback(func(oldCount, newCount int) {
  133. callbackCalled = true
  134. })
  135. // Test no change scenario
  136. ao.adjustWorkerCount(4) // Same as current
  137. if callbackCalled {
  138. t.Error("Expected no callback when worker count doesn't change")
  139. }
  140. if ao.config.WorkerCount != 4 {
  141. t.Errorf("Expected worker count to remain 4, got %d", ao.config.WorkerCount)
  142. }
  143. }
  144. func TestAdaptiveOptimizer_adjustWorkerCount_InvalidCount(t *testing.T) {
  145. ao := createTestAdaptiveOptimizer(4)
  146. var callbackCalled bool
  147. ao.SetWorkerCountChangeCallback(func(oldCount, newCount int) {
  148. callbackCalled = true
  149. })
  150. // Test invalid count (0 or negative)
  151. ao.adjustWorkerCount(0)
  152. ao.adjustWorkerCount(-1)
  153. if callbackCalled {
  154. t.Error("Expected no callback for invalid worker counts")
  155. }
  156. if ao.config.WorkerCount != 4 {
  157. t.Errorf("Expected worker count to remain 4, got %d", ao.config.WorkerCount)
  158. }
  159. }
  160. func TestAdaptiveOptimizer_GetOptimalBatchSize(t *testing.T) {
  161. ao := createTestAdaptiveOptimizer(4)
  162. // Initial batch size should be from config
  163. batchSize := ao.GetOptimalBatchSize()
  164. expectedInitial := int32(1000)
  165. if batchSize != int(expectedInitial) {
  166. t.Errorf("Expected initial batch size %d, got %d", expectedInitial, batchSize)
  167. }
  168. // Test updating batch size
  169. newBatchSize := int32(1500)
  170. atomic.StoreInt32(&ao.batchSizeController.currentBatchSize, newBatchSize)
  171. batchSize = ao.GetOptimalBatchSize()
  172. if batchSize != int(newBatchSize) {
  173. t.Errorf("Expected updated batch size %d, got %d", newBatchSize, batchSize)
  174. }
  175. }
  176. func TestAdaptiveOptimizer_measureAndAdjustCPU_WithinThreshold(t *testing.T) {
  177. ao := createTestAdaptiveOptimizer(4)
  178. var callbackCalled bool
  179. ao.SetWorkerCountChangeCallback(func(oldCount, newCount int) {
  180. callbackCalled = true
  181. })
  182. // Mock CPU measurements within threshold
  183. ao.cpuMonitor.measurements = []float64{0.78, 0.79, 0.81, 0.82} // Around 0.8 target
  184. ao.measureAndAdjustCPU()
  185. // Should not trigger worker adjustment if within threshold
  186. if callbackCalled {
  187. t.Error("Expected no worker adjustment when CPU is within threshold")
  188. }
  189. }
  190. func TestAdaptiveOptimizer_GetCPUUtilization(t *testing.T) {
  191. ao := createTestAdaptiveOptimizer(4)
  192. // Set current utilization
  193. ao.cpuMonitor.currentUtilization = 0.75
  194. utilization := ao.GetCPUUtilization()
  195. if utilization != 0.75 {
  196. t.Errorf("Expected CPU utilization 0.75, got %f", utilization)
  197. }
  198. }
  199. func TestAdaptiveOptimizer_GetOptimizationStats(t *testing.T) {
  200. ao := createTestAdaptiveOptimizer(4)
  201. // Set some test values
  202. atomic.StoreInt64(&ao.optimizationsMade, 5)
  203. ao.avgThroughput = 25.5
  204. ao.avgLatency = 2 * time.Second
  205. ao.cpuMonitor.currentUtilization = 0.85
  206. stats := ao.GetOptimizationStats()
  207. if stats.OptimizationsMade != 5 {
  208. t.Errorf("Expected 5 optimizations made, got %d", stats.OptimizationsMade)
  209. }
  210. if stats.AvgThroughput != 25.5 {
  211. t.Errorf("Expected avg throughput 25.5, got %f", stats.AvgThroughput)
  212. }
  213. if stats.AvgLatency != 2*time.Second {
  214. t.Errorf("Expected avg latency 2s, got %v", stats.AvgLatency)
  215. }
  216. if stats.CPUUtilization != 0.85 {
  217. t.Errorf("Expected CPU utilization 0.85, got %f", stats.CPUUtilization)
  218. }
  219. if stats.CurrentBatchSize != 1000 {
  220. t.Errorf("Expected current batch size 1000, got %d", stats.CurrentBatchSize)
  221. }
  222. }
  223. func TestAdaptiveOptimizer_StartStop(t *testing.T) {
  224. ao := createTestAdaptiveOptimizer(4)
  225. // Test start
  226. err := ao.Start()
  227. if err != nil {
  228. t.Fatalf("Failed to start adaptive optimizer: %v", err)
  229. }
  230. // Verify running state
  231. if atomic.LoadInt32(&ao.running) != 1 {
  232. t.Error("Expected adaptive optimizer to be running")
  233. }
  234. // Test starting again (should fail)
  235. err = ao.Start()
  236. if err == nil {
  237. t.Error("Expected error when starting already running optimizer")
  238. }
  239. // Small delay to let goroutines start
  240. time.Sleep(100 * time.Millisecond)
  241. // Test stop
  242. ao.Stop()
  243. // Verify stopped state
  244. if atomic.LoadInt32(&ao.running) != 0 {
  245. t.Error("Expected adaptive optimizer to be stopped")
  246. }
  247. }
  248. func TestAdaptiveOptimizer_WorkerAdjustmentLimits(t *testing.T) {
  249. // Test maximum worker limit
  250. ao := createTestAdaptiveOptimizer(16) // Start with high count
  251. ao.cpuMonitor.maxWorkers = 20
  252. var actualNewCount int
  253. ao.SetWorkerCountChangeCallback(func(oldCount, newCount int) {
  254. actualNewCount = newCount
  255. })
  256. // Try to increase beyond max
  257. ao.suggestWorkerIncrease(0.2, 0.8) // Very low CPU, should want to increase
  258. if actualNewCount > ao.cpuMonitor.maxWorkers {
  259. t.Errorf("New worker count %d exceeds maximum %d", actualNewCount, ao.cpuMonitor.maxWorkers)
  260. }
  261. // Test minimum worker limit
  262. ao2 := createTestAdaptiveOptimizer(3)
  263. ao2.cpuMonitor.minWorkers = 2
  264. ao2.SetWorkerCountChangeCallback(func(oldCount, newCount int) {
  265. actualNewCount = newCount
  266. })
  267. // Try to decrease below min
  268. ao2.suggestWorkerDecrease(0.98, 0.8) // Very high CPU, should want to decrease
  269. if actualNewCount < ao2.cpuMonitor.minWorkers {
  270. t.Errorf("New worker count %d below minimum %d", actualNewCount, ao2.cpuMonitor.minWorkers)
  271. }
  272. }
  273. func TestAdaptiveOptimizer_ConcurrentAccess(t *testing.T) {
  274. ao := createTestAdaptiveOptimizer(4)
  275. var wg sync.WaitGroup
  276. var adjustmentCount int32
  277. ao.SetWorkerCountChangeCallback(func(oldCount, newCount int) {
  278. atomic.AddInt32(&adjustmentCount, 1)
  279. })
  280. // Simulate concurrent CPU measurements and adjustments
  281. for i := 0; i < 10; i++ {
  282. wg.Add(1)
  283. go func() {
  284. defer wg.Done()
  285. // Simulate alternating high and low CPU
  286. if i%2 == 0 {
  287. ao.suggestWorkerIncrease(0.4, 0.8)
  288. } else {
  289. ao.suggestWorkerDecrease(0.95, 0.8)
  290. }
  291. }()
  292. }
  293. wg.Wait()
  294. // Verify that some adjustments were made
  295. finalCount := atomic.LoadInt32(&adjustmentCount)
  296. if finalCount == 0 {
  297. t.Error("Expected some worker adjustments to be made")
  298. }
  299. // Verify final state is valid
  300. if ao.config.WorkerCount < ao.cpuMonitor.minWorkers || ao.config.WorkerCount > ao.cpuMonitor.maxWorkers {
  301. t.Errorf("Final worker count %d outside valid range [%d, %d]",
  302. ao.config.WorkerCount, ao.cpuMonitor.minWorkers, ao.cpuMonitor.maxWorkers)
  303. }
  304. }